@juspay/neurolink 12.7.8 → 12.7.9
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/CHANGELOG.md
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
## [12.7.
|
|
1
|
+
## [12.7.9](https://github.com/juspay/neurolink/compare/v12.7.8...v12.7.9) (2026-09-01)
|
|
2
2
|
|
|
3
3
|
### Bug Fixes
|
|
4
4
|
|
|
5
|
-
- **(
|
|
5
|
+
- **(proxy):** reconcile recovered quota cooldowns ([05fc16d](https://github.com/juspay/neurolink/commit/05fc16d14c1c61a7f328f3a9221f4129bf6938b7))
|
|
6
6
|
|
|
7
7
|
## [11.2.3](https://github.com/juspay/neurolink/compare/v11.2.2...v11.2.3) (2026-08-19)
|
|
8
8
|
|
|
@@ -2367,7 +2367,7 @@ data: ${r}
|
|
|
2367
2367
|
`))}catch{}},u);try{for(let R=0;R<s.length&&!h;R++){const A=s[R];x=A.label??"translation",f.always(`[proxy:${r}] attempt ${R+1}/${s.length}: ${A.label}`),Ty(x,"translation");let P="";try{const L=Ile(o,A.provider?{provider:A.provider,model:A.model}:{}),N=await Bt(t.neurolink.stream(L),rF,`Translation attempt ${A.label} timed out after ${rF}ms`);for(k=N.stream[Symbol.asyncIterator]();!h;){const{value:$,done:B}=await k.next();if(B||h)break;const z=Ale($);if(z){P+=z;for(const j of c.pushDelta(z))M.enqueue(d.encode(j))}}if(h)return;const O=N.toolCalls??[];if(!nF(P,O)){T=`Translated provider ${A.label} returned no content or tool calls`,f.debug(`${l} translation attempt ${A.label} returned no content or tool calls`),$r(x,"translation",502);continue}if(!h&&O.length)for(const $ of O){const B=$.toolName??$.name??"unknown",z=$.toolCallId||nin(r);for(const j of c.pushToolUse(z,B,Rir($)))M.enqueue(d.encode(j))}if(!h){const $=N.finishReason??Rle(r),B=ub(N.usage);for(const z of c.finish($,B))M.enqueue(d.encode(z))}v=N.model,_=A.provider,i&&v&&v!==n&&(i.setModelSubstitution(n,v,_),b=!0);const F=ub(N.usage);i?.setUsage({inputTokens:F.input,outputTokens:F.output,cacheCreationTokens:0,cacheReadTokens:0}),i?.recordMetrics(),g=!0;return}catch(L){if(h)return;if(T=L instanceof Error?L.message:String(L),P.trim().length>0){y=!0,$r(x,"translation",502),f.always(`${l} mid-stream error: ${T}`);for(const N of c.emitError(`Upstream stream interrupted: ${T}`))M.enqueue(d.encode(N));return}f.debug(`${l} translation attempt ${A.label} failed: ${T}`),$r(x,"translation",500)}}if(!h){f.always(`${l} all translation attempts failed: ${T}`);for(const R of c.emitError(T))M.enqueue(d.encode(R))}}finally{m&&clearInterval(m),h||M.close(),!b&&i&&v&&v!==n&&(i.setModelSubstitution(n,v,_),b=!0);const R=h?499:g?200:y?502:500,A=h?"client_cancelled":y?"stream_error":g?void 0:"generation_error",P=h?"Client cancelled the streaming response":g?void 0:T;A&&P?(i?.setError(A,P.slice(0,500)),Uw(R,x,"translation",{requestId:t.requestId,errorType:A,terminalOutcome:A,message:P})):iA(x,"translation"),i?.end(R,Date.now()-a);const L=i?.getTraceContext();Rh({timestamp:new Date().toISOString(),requestId:t.requestId,method:t.method,path:t.path,model:n,stream:!0,toolCount:Object.keys(o.tools).length,account:"translation",accountType:"translation",...cb(t.headers),responseStatus:R,responseTimeMs:Date.now()-a,...A?{errorType:A}:{},...P?{errorMessage:P.slice(0,500)}:{},...L?.traceId?{traceId:L.traceId}:{},...L?.spanId?{spanId:L.spanId}:{}})}},cancel(){h=!0,m&&(clearInterval(m),m=void 0),k?.return&&k.return(void 0).catch(M=>{f.debug(`${l} upstream cancel error: ${M instanceof Error?M.message:String(M)}`)})}});return new Response(I,{headers:{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}})}async function Ple(e){const{ctx:t,format:r,requestModel:n,parsed:o,attempts:s,tracer:i,requestStartTime:a,terminalFailureStatus:l=500}=e,c=Mir(r);let u="No translation providers succeeded",d="translation";for(let h=0;h<s.length;h++){const g=s[h];d=g.label??"translation",f.always(`[proxy:${r}] attempt ${h+1}/${s.length}: ${g.label}`),Ty(d,"translation");try{const y=Ile(o,g.provider?{provider:g.provider,model:g.model}:{}),v=await Bt(t.neurolink.stream(y),rF,`Translation attempt ${g.label} timed out after ${rF}ms`);let _="";for await(const x of v.stream){const I=Ale(x);I&&(_+=I)}if(!nF(_,v.toolCalls)){u=`Translated provider ${g.label} returned no content or tool calls`,f.debug(`${c} translation attempt ${g.label} returned no content or tool calls`),$r(d,"translation",502);continue}const b={content:_,model:v.model,finishReason:v.finishReason??Rle(r),reasoning:void 0,usage:v.usage?ub(v.usage):void 0,toolCalls:v.toolCalls};i&&v.model&&v.model!==n&&i.setModelSubstitution(n,v.model,g.provider);const T=ub(v.usage);i?.setUsage({inputTokens:T.input,outputTokens:T.output,cacheCreationTokens:0,cacheReadTokens:0}),i?.recordMetrics(),i?.end(200,Date.now()-a),iA(d,"translation");const k=i?.getTraceContext();return Rh({timestamp:new Date().toISOString(),requestId:t.requestId,method:t.method,path:t.path,model:n,stream:!1,toolCount:Object.keys(o.tools).length,account:"translation",accountType:"translation",...cb(t.headers),responseStatus:200,responseTimeMs:Date.now()-a,inputTokens:T.input,outputTokens:T.output,...k?.traceId?{traceId:k.traceId}:{},...k?.spanId?{spanId:k.spanId}:{}}),r==="claude"?ble(b,n):r==="gemini"?ysn(b.content,b.finishReason??Rle(r),T,b.model??n,b.toolCalls):Tir(b,n)}catch(y){u=y instanceof Error?y.message:String(y),f.debug(`${c} translation attempt ${g.label} failed: ${u}`),$r(d,"translation",500)}}Uw(l,d,"translation",{requestId:t.requestId,errorType:"generation_error",terminalOutcome:"handler_error",message:u}),i?.setError("generation_error",u.slice(0,500)),i?.end(l,Date.now()-a);const m=i?.getTraceContext();throw Rh({timestamp:new Date().toISOString(),requestId:t.requestId,method:t.method,path:t.path,model:n,stream:!1,toolCount:Object.keys(o.tools).length,account:"translation",accountType:"translation",...cb(t.headers),responseStatus:l,responseTimeMs:Date.now()-a,errorType:"generation_error",errorMessage:u.slice(0,500),...m?.traceId?{traceId:m.traceId}:{},...m?.spanId?{spanId:m.spanId}:{}}),new Ne({code:Xe.PROVIDER_NOT_AVAILABLE,message:u,category:"execution",severity:"high",retriable:!1,context:{attemptLabel:d,format:r}})}function oin(e){const t=[];if(e){const r=e.getModelMappings?.()??[];for(const o of r)t.push({id:o.from,object:"model",created:0,owned_by:"neurolink"});const n=e.getPassthroughModels?.()??[];for(const o of n)t.push({id:o,object:"model",created:0,owned_by:"neurolink"})}if(t.length===0)for(const r of Sir)t.push({id:r,object:"model",created:0,owned_by:"neurolink"});return{object:"list",data:t}}function sin(e){const t=[];if(e){const s=e.getModelMappings?.()??[];for(const a of s)a.from&&t.push(a.from);const i=e.getPassthroughModels?.()??[];for(const a of i)t.push(a)}t.length===0&&t.push(...Sir);const r=new Set,o=t.filter(s=>r.has(s)?!1:(r.add(s),!0)).map(s=>({type:"model",id:s,display_name:iin(s),created_at:new Date(0).toISOString()}));return{data:o,first_id:o[0]?.id??null,last_id:o[o.length-1]?.id??null,has_more:!1}}function iin(e){const r=e.replace(/-\d{8}$/,"").split("-"),n=[],o=[];for(const i of r)/^\d+$/.test(i)&&o.length>0&&o[0].toLowerCase()==="claude"?n.push(i):o.push(i.charAt(0).toUpperCase()+i.slice(1));const s=n.length>0?` ${n.join(".")}`:"";return o.length>0?`${o[0]}${s}${o.slice(1).length?" "+o.slice(1).join(" "):""}`:e}vr(),Wr(),er(),Wm(),x6e(),mc(),mS(),q();var ain="[ProxyTracer]",Dle=null;function PA(){if(Dle)return Dle;const e=Fh.getMeter("neurolink.proxy","1.0.0"),t={requestsTotal:e.createCounter("proxy_requests_total",{description:"Total number of proxy requests",unit:"{request}"}),requestDuration:e.createHistogram("proxy_request_duration_ms",{description:"Proxy request duration in milliseconds",unit:"ms"}),tokensInput:e.createCounter("proxy_tokens_input",{description:"Total input tokens consumed via proxy",unit:"{token}"}),tokensOutput:e.createCounter("proxy_tokens_output",{description:"Total output tokens produced via proxy",unit:"{token}"}),tokensCacheRead:e.createCounter("proxy_tokens_cache_read",{description:"Total cache-read tokens via proxy",unit:"{token}"}),tokensCacheCreation:e.createCounter("proxy_tokens_cache_creation",{description:"Total cache-creation tokens via proxy",unit:"{token}"}),tokensReasoning:e.createCounter("proxy_tokens_reasoning",{description:"Total reasoning tokens via proxy",unit:"{token}"}),costTotal:e.createCounter("proxy_cost_usd_total",{description:"Total estimated cost in USD",unit:"USD"}),errorsTotal:e.createCounter("proxy_errors_total",{description:"Total proxy errors",unit:"{error}"}),retriesTotal:e.createCounter("proxy_retries_total",{description:"Total upstream retry attempts",unit:"{retry}"}),modelSubstitutionTotal:e.createCounter("proxy_model_substitution_total",{description:"Total proxy requests where the response model differs from the requested model",unit:"{substitution}"}),requestBodySize:e.createHistogram("proxy_request_body_bytes",{description:"Request body size in bytes sent upstream",unit:"By"}),responseBodySize:e.createHistogram("proxy_response_body_bytes",{description:"Response body size in bytes received from upstream",unit:"By"}),fallbackAttemptsTotal:e.createCounter("proxy_fallback_attempts_total",{description:"Total fallback provider attempts",unit:"{attempt}"}),fallbackSuccessTotal:e.createCounter("proxy_fallback_success_total",{description:"Total successful fallback provider responses",unit:"{success}"}),fallbackFailureTotal:e.createCounter("proxy_fallback_failure_total",{description:"Total failed fallback provider responses",unit:"{failure}"})};return Dle=t,t}var lin=new Set(["authorization","proxy-authorization","x-api-key","cookie","set-cookie"]),cin=/token|secret|key|password|credential/i;function Ole(e){const t={};for(const[r,n]of Object.entries(e)){const o=r.toLowerCase();lin.has(o)||cin.test(o)?t[r]="[REDACTED]":t[r]=n}return t}var uin=/api[_-]?key|token|secret|password|credential|authorization/i,oF=process.env.NEUROLINK_PROXY_TRACE_BODY_LOGGING==="true",Nle=Number.parseInt(process.env.NEUROLINK_PROXY_TRACE_BODY_LOG_BYTES??"8192",10),Pir=200;function Dir(e,t=8192){const r=e.length>t?e.slice(0,t)+"\u2026[truncated]":e;try{let o=function(i){if(i===null||typeof i!="object")return i;if(Array.isArray(i))return i.map(o);const a={};for(const[l,c]of Object.entries(i))a[l]=uin.test(l)?"[REDACTED]":o(c);return a};var n=o;const s=JSON.parse(r);return JSON.stringify(o(s))}catch{return r}}function Lle(e){return{"proxy.body":Dir(e,Nle),"proxy.body.size":e.length,"proxy.body.logged":!0,"proxy.body.truncated":e.length>Nle}}function din(e){return e?e.startsWith("claude-cli/")?"cli":e.startsWith("ai/")?"sdk":"unknown":"unknown"}var $le=class kur{rootSpan;proxyTracer=m4("neurolink.proxy");bridge=new i0;requestId;model;billingProvider;startTime;isStream;accountEmail;usage;mode="full";constructor(t,r,n,o,s){this.rootSpan=t,this.requestId=r,this.model=n,this.billingProvider=s,this.startTime=Date.now(),this.isStream=o}static startRequest(t,r){const n=m4("neurolink.proxy");let o=Sr.active();if(r){const m=new i0().extractContext(r);m&&(o=vt.setSpanContext(Sr.active(),m))}const s=t.clientApp??din(t.userAgent),i=n.startSpan("proxy.request",{attributes:{"proxy.request_id":t.requestId,"http.method":t.method,"http.target":t.path,"gen_ai.request.model":t.model,"proxy.stream":t.stream,"proxy.tool_count":t.toolCount,"proxy.client_app":s}},o);t.sessionId&&i.setAttribute("session.id",t.sessionId),t.userAgent&&i.setAttribute("http.user_agent",t.userAgent),t.toolNames&&t.toolNames.length>0&&i.setAttribute("gen_ai.request.tool_names",JSON.stringify(t.toolNames));const a=r?.["x-neurolink-session-id"],l=r?.["x-neurolink-user-id"],c=r?.["x-neurolink-conversation-id"];a&&i.setAttribute("neurolink.session_id",a),l&&i.setAttribute("neurolink.user_id",l),c&&i.setAttribute("neurolink.conversation_id",c);const u=new kur(i,t.requestId,t.model,t.stream,t.provider??"anthropic");return $0({sessionId:a??t.sessionId,userId:l,conversationId:c,requestId:t.requestId,traceName:`proxy:${t.model}`,operationName:"proxy.request",metadata:{clientApp:s,stream:t.stream,toolCount:t.toolCount}}).catch(d=>{f.debug(`${ain} Failed to set Langfuse context`,{error:d instanceof Error?d.message:String(d)})}),u}startReceive(){return this.proxyTracer.startSpan("proxy.receive",{attributes:{"proxy.request_id":this.requestId}},vt.setSpan(Sr.active(),this.rootSpan))}startAccountSelection(){return this.proxyTracer.startSpan("proxy.account_selection",{attributes:{"proxy.request_id":this.requestId}},vt.setSpan(Sr.active(),this.rootSpan))}startUpstreamAttempt(t){return this.proxyTracer.startSpan("proxy.upstream",{attributes:{"proxy.request_id":this.requestId,"proxy.upstream.attempt":t.attempt,"proxy.upstream.account":t.account,"proxy.upstream.polyfill_headers":t.polyfillHeaders,"proxy.upstream.polyfill_body":t.polyfillBody,"http.url":t.upstreamUrl}},vt.setSpan(Sr.active(),this.rootSpan))}startStream(){return this.proxyTracer.startSpan("proxy.stream",{attributes:{"proxy.request_id":this.requestId,"gen_ai.request.model":this.model}},vt.setSpan(Sr.active(),this.rootSpan))}setAccountSelection(t){this.accountEmail=t.selectedAccount,this.rootSpan.setAttributes({"proxy.account.strategy":t.strategy,"proxy.account.total":t.accountsTotal,"proxy.account.healthy":t.accountsHealthy,"proxy.account.selected":t.selectedAccount,"proxy.account.type":t.accountType}),t.rateLimitBefore5h!==void 0&&this.rootSpan.setAttribute("proxy.ratelimit.before.5h",t.rateLimitBefore5h),t.rateLimitBefore7d!==void 0&&this.rootSpan.setAttribute("proxy.ratelimit.before.7d",t.rateLimitBefore7d),$0({userId:t.selectedAccount}).catch(()=>{})}setUsage(t){this.usage=t;const r=t.inputTokens+t.outputTokens+t.cacheCreationTokens+t.cacheReadTokens+(t.reasoningTokens??0);this.rootSpan.setAttributes({"ai.tokens.input":t.inputTokens,"ai.tokens.output":t.outputTokens,"ai.tokens.total":r,"ai.tokens.cache_creation":t.cacheCreationTokens,"ai.tokens.cache_read":t.cacheReadTokens}),t.reasoningTokens!==void 0&&this.rootSpan.setAttribute("ai.tokens.reasoning",t.reasoningTokens),this.rootSpan.setAttributes({"gen_ai.usage.input_tokens":t.inputTokens,"gen_ai.usage.output_tokens":t.outputTokens,"gen_ai.usage.total_tokens":r});const n=Ha(this.billingProvider,this.model,{input:t.inputTokens,output:t.outputTokens,total:r,cacheCreationTokens:t.cacheCreationTokens,cacheReadTokens:t.cacheReadTokens});n>0&&this.rootSpan.setAttributes({"ai.cost.total":n,"ai.cost.currency":"USD"}),t.rateLimitAfter5h!==void 0&&this.rootSpan.setAttribute("proxy.ratelimit.after.5h",t.rateLimitAfter5h),t.rateLimitAfter7d!==void 0&&this.rootSpan.setAttribute("proxy.ratelimit.after.7d",t.rateLimitAfter7d)}setResponseInfo(t){t.responseModel&&this.rootSpan.setAttribute("gen_ai.response.model",t.responseModel),t.finishReason&&this.rootSpan.setAttribute("gen_ai.response.finish_reason",t.finishReason),t.stopSequence&&this.rootSpan.setAttribute("gen_ai.response.stop_sequence",t.stopSequence),t.toolCalls&&t.toolCalls.length>0&&(this.rootSpan.setAttributes({"gen_ai.response.tool_calls":JSON.stringify(t.toolCalls),"gen_ai.response.tool_call_count":t.toolCalls.length}),this.rootSpan.addEvent("proxy.response.tool_calls",{"gen_ai.response.tool_calls":JSON.stringify(t.toolCalls)}))}setError(t,r){this.rootSpan.setAttributes({"error.type":t,"error.message":r,error:!0})}setMode(t){this.mode=t,this.rootSpan.setAttribute("proxy.mode",t)}setModelSubstitution(t,r,n){this.model=r,n&&(this.billingProvider=n),this.rootSpan.setAttributes({"proxy.model_substituted":!0,"proxy.original_model":t,"proxy.actual_model":r,"gen_ai.response.model":r,...n?{"proxy.actual_provider":n}:{}}),PA().modelSubstitutionTotal.add(1,{requested_model:t,actual_model:r})}setFallbackInfo(t){this.rootSpan&&this.rootSpan.setAttributes({"proxy.fallback.triggered":t.triggered,...t.provider?{"proxy.fallback.provider":t.provider}:{},...t.model?{"proxy.fallback.model":t.model}:{},"proxy.fallback.attempt_count":t.attemptCount,"proxy.fallback.reason":t.reason})}logRequestBody(t){if(!oF){this.rootSpan.addEvent("proxy.client.request_body",{"proxy.body.size":t.length,"proxy.body.logged":!1});return}this.rootSpan.addEvent("proxy.client.request_body",{...Lle(t)})}logRequestHeaders(t){this.rootSpan.addEvent("proxy.client.request_headers",{"proxy.headers":JSON.stringify(Ole(t))})}logUpstreamRequestBody(t){if(!oF){this.rootSpan.addEvent("proxy.upstream.request_body",{"proxy.body.size":t.length,"proxy.body.logged":!1});return}this.rootSpan.addEvent("proxy.upstream.request_body",{...Lle(t)})}logUpstreamRequestHeaders(t){this.rootSpan.addEvent("proxy.upstream.request_headers",{"proxy.headers":JSON.stringify(Ole(t))})}logUpstreamResponseHeaders(t){this.rootSpan.addEvent("proxy.upstream.response_headers",{"proxy.headers":JSON.stringify(Ole(t))})}logUpstreamResponseBody(t){if(!oF){this.rootSpan.addEvent("proxy.upstream.response_body",{"proxy.body.size":t.length,"proxy.body.logged":!1});return}this.rootSpan.addEvent("proxy.upstream.response_body",{...Lle(t)})}logStreamEvents(t){if(!oF){this.rootSpan.addEvent("proxy.stream.events",{"proxy.stream.event_count":t.length,"proxy.body.logged":!1});return}const r=t.length>Pir,n=t.slice(0,Pir).map(o=>({...o,data:o.data?Dir(o.data,Nle):""}));r&&n.push({type:"truncated",timestamp:Date.now(),data:"\u2026[truncated]"}),this.rootSpan.addEvent("proxy.stream.events",{"proxy.stream.event_count":t.length,"proxy.stream.events":JSON.stringify(n),"proxy.body.logged":!0,"proxy.body.truncated":r})}recordRetry(t,r){PA().retriesTotal.add(1,{model:this.model,account:t,reason:r})}recordBodySizes(t,r){const n=PA(),o={model:this.model,account:this.accountEmail??"unknown"};t!==void 0&&t>0&&n.requestBodySize.record(t,o),r!==void 0&&r>0&&n.responseBodySize.record(r,o)}getTraceContext(){const t=this.rootSpan.spanContext();return{traceId:t.traceId,spanId:t.spanId}}getUsage(){return this.usage}end(t,r){this.rootSpan.setAttributes({"http.status_code":t,"proxy.duration_ms":r,"proxy.mode":this.mode,...this.accountEmail?{"proxy.account":this.accountEmail}:void 0}),t>=400?this.rootSpan.setStatus({code:qe.ERROR,message:`HTTP ${t}`}):this.rootSpan.setStatus({code:qe.OK}),this.rootSpan.end();const n=PA(),o={model:this.model,account:this.accountEmail??"unknown",status:String(t),stream:String(this.isStream),mode:this.mode};if(n.requestsTotal.add(1,o),n.requestDuration.record(r,o),this.usage){const s={model:this.model,account:this.accountEmail??"unknown"};n.tokensInput.add(this.usage.inputTokens,s),n.tokensOutput.add(this.usage.outputTokens,s),n.tokensCacheRead.add(this.usage.cacheReadTokens,s),n.tokensCacheCreation.add(this.usage.cacheCreationTokens,s),this.usage.reasoningTokens&&n.tokensReasoning.add(this.usage.reasoningTokens,s);const i=this.usage.inputTokens+this.usage.outputTokens+this.usage.cacheCreationTokens+this.usage.cacheReadTokens+(this.usage.reasoningTokens??0),a=Ha(this.billingProvider,this.model,{input:this.usage.inputTokens,output:this.usage.outputTokens,total:i,cacheCreationTokens:this.usage.cacheCreationTokens,cacheReadTokens:this.usage.cacheReadTokens});a>0&&n.costTotal.add(a,s)}if(t>=400){const s=t===429?"rate_limit":t===401?"auth":t>=500?"server":"client";n.errorsTotal.add(1,{model:this.model,account:this.accountEmail??"unknown",error_type:s,status:String(t)})}}recordMetrics(){if(!this.usage)return;const t=this.usage.inputTokens+this.usage.outputTokens+this.usage.cacheCreationTokens+this.usage.cacheReadTokens+(this.usage.reasoningTokens??0),r=Date.now()-this.startTime,n=Ha(this.billingProvider,this.model,{input:this.usage.inputTokens,output:this.usage.outputTokens,total:t,cacheCreationTokens:this.usage.cacheCreationTokens,cacheReadTokens:this.usage.cacheReadTokens});Pf.getInstance().recordAIRequest(this.billingProvider,this.model,t,r,n>0?n:void 0)}getTraceHeaders(){return this.bridge.injectContext({},vt.setSpan(Sr.active(),this.rootSpan))}};function DA(e){try{const t=PA(),r={provider:e.provider,model:e.model};t.fallbackAttemptsTotal.add(1,r),e.status==="success"?t.fallbackSuccessTotal.add(1,r):t.fallbackFailureTotal.add(1,{...r,error:e.errorMessage?.slice(0,100)??"unknown"})}catch{}}var sF=1024*1024,Fle=`
|
|
2368
2368
|
...[TRUNCATED]`;function Oir(){const e=new TextDecoder,t=[];let r=0,n=0,o=!1,s=!1,i;const a=new Promise(y=>{i=y});function l(){if(s)return;s=!0;const y=e.decode();if(y)if(n<sF){const v=sF-n;t.push(y.slice(0,v)),n+=Math.min(y.length,v)}else o||(t.push(Fle),o=!0);i({totalBytes:r,text:t.join(""),truncated:o})}const c=new TransformStream({transform(y,v){if(v.enqueue(y),r+=y.byteLength,n<sF){const _=e.decode(y,{stream:!0}),b=sF-n,T=_.slice(0,b);t.push(T),n+=Math.min(_.length,b),_.length>b&&!o&&(t.push(Fle),o=!0)}else o||(t.push(Fle),o=!0)},flush(){l()}}),u=c.writable.getWriter();let d;const m=new WritableStream({start(y){d=y},write(y){return u.write(y)},close(){return u.close()},abort(y){return l(),u.abort(y)}});u.closed.catch(y=>{l();try{d.error(y)}catch{}});const h=c.readable.getReader();return{stream:{readable:new ReadableStream({async pull(y){try{const{done:v,value:_}=await h.read();v?y.close():y.enqueue(_)}catch(v){y.error(v)}},async cancel(y){l();try{d.error(y)}catch{}await Promise.allSettled([h.cancel(y),u.abort(y)])}}),writable:m},capture:a}}uAt();var iF=100*1024,pin=5e3,Ule=2048,Nir=1024*1024,Bp="...[TRUNCATED]";function aF(e){const t=[];let r=0;for(;r<e.length;){const n=/\r\n\r\n|\n\n|\r\r/.exec(e.slice(r));if(!n||n.index===void 0)break;const o=r+n.index,s=e.slice(r,o);r=o+n[0].length;let i="",a="";const l=s.split(/\r\n|\n|\r/);for(const c of l)c.startsWith("event: ")?i=c.slice(7).trim():c.startsWith("data: ")?a=c.slice(6):c.startsWith("data:")&&(a=c.slice(5));(i||a)&&t.push({event:i,data:a})}return{events:t,remainder:e.slice(r)}}function min(e){return{messageId:"",model:"",inputTokens:0,outputTokens:0,cacheCreationInputTokens:0,cacheReadInputTokens:0,contentBlocks:[],blockByteCounts:new Map,stopReason:null,stopSequence:null,eventCount:0,startTime:Date.now(),totalBytesReceived:0,events:[],rawTextChunks:e?[]:void 0,rawTextBytes:0,rawTextTruncated:!1,eventLogTruncated:!1}}function db(e){return Buffer.byteLength(e,"utf8")}function Ble(e,t){if(db(e)<=t)return e;const r=db(Bp);if(t<=0||t<r)return"";let n="",o=0;for(const s of e){const i=db(s);if(o+i+r>t)break;n+=s,o+=i}return`${n}${Bp}`}function zle(e,t){return Ble(e,t)}function jle(e,t,r,n){const o=db(t);if(r>=n)return{value:e&&e.endsWith(Bp)?e:`${e??""}${Bp}`,nextBytes:r+o};const s=n-r,i=r+o;return o<=s?{value:`${e??""}${t}`,nextBytes:i}:{value:`${e??""}${Ble(t,s)}`,nextBytes:i}}function Lir(e,t){if(!e.rawTextChunks||e.rawTextTruncated)return;const r=Nir-e.rawTextBytes;if(r<=0){e.rawTextChunks.push(Bp),e.rawTextTruncated=!0;return}const n=db(t);if(n<=r){e.rawTextChunks.push(t),e.rawTextBytes+=n;return}e.rawTextChunks.push(Ble(t,r)),e.rawTextBytes=Nir,e.rawTextTruncated=!0}function hin(e){return db(e.text??e.thinking??e.toolInput??"")}function fin(e){const t=e.inputTokens+e.outputTokens;return{messageId:e.messageId,model:e.model,usage:{inputTokens:e.inputTokens,outputTokens:e.outputTokens,cacheCreationInputTokens:e.cacheCreationInputTokens,cacheReadInputTokens:e.cacheReadInputTokens,totalTokens:t},contentBlocks:e.contentBlocks,stopReason:e.stopReason,stopSequence:e.stopSequence,eventCount:e.eventCount,streamDurationMs:Date.now()-e.startTime,totalBytesReceived:e.totalBytesReceived,events:e.events,...e.streamErrorMessage?{streamErrorMessage:e.streamErrorMessage}:{},...e.rawTextChunks?{rawText:e.rawTextChunks.join("")}:{}}}function gin(e,t){const r=t.message;if(!r)return;e.messageId=r.id??"",e.model=r.model??"";const n=r.usage;n&&(e.inputTokens+=n.input_tokens??0,e.outputTokens+=n.output_tokens??0,e.cacheCreationInputTokens+=n.cache_creation_input_tokens??0,e.cacheReadInputTokens+=n.cache_read_input_tokens??0)}function yin(e,t){const r=t.index??0,n=t.content_block;if(!n)return;const o=n.type,s={index:r,type:o};o==="text"?s.text=n.text??"":o==="thinking"?s.thinking=n.thinking??"":o==="tool_use"&&(s.toolName=n.name??"",s.toolId=n.id??"",s.toolInput=""),e.contentBlocks.push(s),e.blockByteCounts.set(r,hin(s))}function vin(e,t){const r=t.index??0,n=t.delta;if(!n)return;const o=e.contentBlocks.find(a=>a.index===r);if(!o)return;const s=e.blockByteCounts.get(r)??0,i=s>=iF;if(n.type==="text_delta"&&n.text!==null){const a=n.text,l=jle(o.text,a,s,iF);e.blockByteCounts.set(r,l.nextBytes),(!i||!o.text?.endsWith(Bp))&&(o.text=l.value)}else if(n.type==="thinking_delta"&&n.thinking!==null){const a=n.thinking,l=jle(o.thinking,a,s,iF);e.blockByteCounts.set(r,l.nextBytes),(!i||!o.thinking?.endsWith(Bp))&&(o.thinking=l.value)}else if(n.type==="input_json_delta"&&n.partial_json!==null){const a=n.partial_json,l=jle(o.toolInput,a,s,iF);e.blockByteCounts.set(r,l.nextBytes),(!i||!o.toolInput?.endsWith(Bp))&&(o.toolInput=l.value)}}function _in(e,t){const r=t.delta;r&&(e.stopReason=r.stop_reason??e.stopReason,e.stopSequence=r.stop_sequence??e.stopSequence);const n=t.usage;n&&(e.outputTokens+=n.output_tokens??0)}function $ir(e,t){e.eventCount++;const r=Date.now();if(e.events.length<pin-1?t.event==="content_block_delta"?e.events.push({type:t.event,timestamp:r,data:""}):e.events.push({type:t.event,timestamp:r,data:zle(t.data,Ule)}):e.eventLogTruncated||(e.events.push({type:"truncated",timestamp:r,data:Bp}),e.eventLogTruncated=!0),!t.data)return;let n;try{n=JSON.parse(t.data)}catch{return}if(t.event==="error"){const o=n&&typeof n=="object"?n:{},i=(o.error&&typeof o.error=="object"?o.error:void 0)?.message??o.message;e.streamErrorMessage=typeof i=="string"&&i.trim()?zle(i.trim(),Ule):zle(t.data,Ule)}switch(t.event){case"message_start":gin(e,n);break;case"content_block_start":yin(e,n);break;case"content_block_delta":vin(e,n);break;case"message_delta":_in(e,n);break;default:break}}function lF(e={}){const t=e.captureRawText??!1,r=min(t);let n="",o=!1;const s=new TextDecoder;let i;const a=new Promise(v=>{i=v});function l(){o||(o=!0,i(fin(r)))}const c=new TransformStream({transform(v,_){_.enqueue(v),r.totalBytesReceived+=v.byteLength;const b=s.decode(v,{stream:!0});Lir(r,b),n+=b;const{events:T,remainder:k}=aF(n);n=k;for(const x of T)$ir(r,x)},flush(){const v=s.decode();if(v&&(Lir(r,v),n+=v),n.trim()){const{events:_}=aF(n+`
|
|
2369
2369
|
|
|
2370
|
-
`);for(const b of _)$ir(r,b)}l()}}),u=c.writable.getWriter();let d;const m=new WritableStream({start(v){d=v},write(v){return u.write(v)},close(){return u.close()},abort(v){return l(),u.abort(v)}});u.closed.catch(v=>{l();try{d.error(v)}catch{}});const h=c.readable.getReader();return{stream:{readable:new ReadableStream({async pull(v){try{const{done:_,value:b}=await h.read();_?v.close():v.enqueue(b)}catch(_){v.error(_)}},async cancel(v){l();try{d.error(v)}catch{}await Promise.allSettled([h.cancel(v),u.abort(v)])}}),writable:m},telemetry:a}}Jr(),ii(),nr(),Oc(),q(),Gl();var win="proxy-peers.json",bin=1e3,Tin={exhausted:9e5,withheld:6e5,paused:3e5,revoked:864e5,expired:864e5,unreachable:6e4,upstream_error:12e4},Ein=null,zp={},OA=0,NA=-1,LA=!1,Fir=new sl;function qle(){return Ein??St(Wa(),".neurolink",win)}function Sin(e){if(!e||typeof e!="object")return!1;const t=e;return typeof t.name=="string"&&typeof t.url=="string"&&typeof t.token=="string"&&typeof t.priority=="number"&&typeof t.enabled=="boolean"}function Cin(e){return e?.code==="ENOENT"}async function Gle(e={}){const t=Date.now();if(!e.force&&LA&&t-OA<bin)return;const r=qle();let n;try{n=(await qs(r)).mtimeMs}catch(o){if(!Cin(o))throw o;zp={},NA=-1,OA=t,LA=!0;return}if(!e.force&&LA&&n===NA){OA=t;return}try{const o=JSON.parse(await Kr(r,"utf8"));zp=Object.fromEntries(Object.entries(o?.peers??{}).filter(s=>Sin(s[1])))}catch(o){if(e.force)throw o;f.always(`[proxy] peer list unreadable, treating as empty: ${o instanceof Error?o.message:String(o)}`),zp={}}NA=n,OA=t,LA=!0}async function Uir(){const e={schemaVersion:1,peers:zp};await il(qle(),e);try{NA=(await qs(qle())).mtimeMs}catch{NA=-1}OA=Date.now(),LA=!0}function Bir(e){return e.trim().toLowerCase()}async function kin(){return await Gle(),Object.values(zp).sort((e,t)=>e.priority-t.priority||e.createdAt-t.createdAt)}async function xin(e=Date.now()){return(await kin()).filter(r=>r.enabled&&!(r.cooldownUntil&&r.cooldownUntil>e))}function Ain(e){return Tin[e]}var Iin=6048e5;async function Hle(e,t,r){await Fir.runExclusive(async()=>{await Gle({force:!0});const n=Bir(e),o=zp[n];if(!o)return;const s=(r??0)*1e3,i=Date.now()+Math.min(Iin,Math.max(Ain(t),Number.isFinite(s)?s:0));zp[n]={...o,cooldownUntil:i,cooldownReason:t,updatedAt:Date.now()},await Uir()})}async function Rin(e,t){await Fir.runExclusive(async()=>{await Gle({force:!0});const r=Bir(e),n=zp[r];n&&(zp[r]={...n,cooldownUntil:0,lastUsedAt:Date.now(),updatedAt:Date.now(),...t?{lastObservation:t}:{}},await Uir())})}Jr(),ii(),nr(),Oc(),w$();var Min=6048e5,Pin=9e5,Din=864e5;function Oin(e){return!e.usable}function zir(e){return{schemaVersion:e.schemaVersion,grantId:e.grantId,peerLabel:e.peerLabel,issuedAt:e.issuedAt,notAfter:e.notAfter,heartbeatEveryMs:e.heartbeatEveryMs,offlineGraceMs:e.offlineGraceMs,gates:e.gates,entitlementSnapshot:e.entitlementSnapshot}}function jir(e,t){return Yie(e,t)}function qir(e,t=Date.now()){const r=e.leasePolicy,n=e.leaseSecret;if(!n)throw new Error(`Grant ${e.id} has no lease secret \u2014 provision it before issuing a lease.`);const o=r?.ttlMs??Min,s=Math.min(t+o,e.gates.notAfter??Number.POSITIVE_INFINITY),i={schemaVersion:1,grantId:e.id,peerLabel:e.peerLabel,issuedAt:t,notAfter:s,heartbeatEveryMs:r?.heartbeatEveryMs??Pin,offlineGraceMs:r?.offlineGraceMs??Din,gates:e.gates,entitlementSnapshot:e.entitlement.ledger==="coins"?e.entitlement.coins??0:"unlimited"};return{...i,signature:jir(zir(i),n)}}function Nin(e,t){const{signature:r,...n}=e;return ler(jir(zir(n),t),r)}function Lin(e){const t=e.now??Date.now();if(!Nin(e.lease,e.secret))return{usable:!1,reason:"unsigned",detail:"lease signature does not match the lender's secret"};if(e.lease.notAfter<=t)return{usable:!1,reason:"expired",detail:"the lease's hard expiry has passed"};const r=e.lastHeartbeatAt??e.lease.issuedAt;return r+e.lease.offlineGraceMs<=t?{usable:!1,reason:"grace_elapsed",detail:"the lender has been unreachable for longer than this lease allows"}:{usable:!0,nextHeartbeatDueAt:r+e.lease.heartbeatEveryMs}}function $in(e){const t=e.now??Date.now();if(!e.grant.leaseSecret)throw new Error(`Grant ${e.grant.id} has no lease secret \u2014 attach lease material first.`);return{code:e.code,state:e.state,accountLabel:`${e.grant.peerLabel}-via-${e.lenderName}`,leaseSecret:e.grant.leaseSecret,lease:qir(e.grant,t),lenderUrl:(e.lenderUrl??"").replace(/\/+$/,"")}}Gl();var Fin="proxy-resident-grants.json",Uin=1e3,Bin=null,Py={},$A=0,FA=-1,UA=!1,zin=new sl;function Vle(){return Bin??St(Wa(),".neurolink",Fin)}function jin(e){if(!e||typeof e!="object")return!1;const t=e;return typeof t.accountLabel=="string"&&typeof t.grantId=="string"&&typeof t.leaseSecret=="string"&&!!t.lease}function qin(e){return e?.code==="ENOENT"}async function Gir(e={}){const t=Date.now();if(!e.force&&UA&&t-$A<Uin)return;const r=Vle();let n;try{n=(await qs(r)).mtimeMs}catch(o){if(!qin(o))throw o;Py={},FA=-1,$A=t,UA=!0;return}if(!e.force&&UA&&n===FA){$A=t;return}try{const o=JSON.parse(await Kr(r,"utf8"));Py=Object.fromEntries(Object.entries(o?.grants??{}).filter(s=>jin(s[1])))}catch(o){if(e.force)throw o;Py={}}FA=n,$A=t,UA=!0}async function Gin(){const e={schemaVersion:1,grants:Py};await il(Vle(),e);try{FA=(await qs(Vle())).mtimeMs}catch{FA=-1}$A=Date.now(),UA=!0}function Hir(e){return e.toLowerCase()}async function Wle(e){await Gir();const t=e.toLowerCase(),r=t.includes(":")?t.slice(t.indexOf(":")+1):t;return Py[Hir(r)]}async function Hin(e,t=Date.now()){const r=await Wle(e);if(r)return Lin({lease:r.lease,secret:r.leaseSecret,...r.lastHeartbeatAt!==void 0?{lastHeartbeatAt:r.lastHeartbeatAt}:{},now:t})}async function Vin(e,t){await zin.runExclusive(async()=>{await Gir({force:!0});const r=Hir(e),n=Py[r];n&&(Py[r]={...n,unreportedCoins:(n.unreportedCoins??0)+t,unreportedRequests:(n.unreportedRequests??0)+1},await Gin())})}q();var Win=15e3,Kin=12e4;function Jin(e){switch(e){case"exhausted":return"exhausted";case"paused":return"paused";case"revoked":return"revoked";case"expired":return"expired";case"reserve_floor":case"spillover_inactive":case"slice_exhausted":case"no_capacity":return"withheld";case"missing_token":case"unknown_token":case"malformed_token":return"revoked";default:return"upstream_error"}}function Vir(e,t){const r=e.headers.get(t);if(r===null||r.trim()==="")return;const n=Number(r);return Number.isFinite(n)?n:void 0}function Yin(e){const t=Vir(e,"x-neurolink-grant-remaining-coins");return{observedAt:Date.now(),...e.headers.get("x-neurolink-grant-status")?{grantStatus:e.headers.get("x-neurolink-grant-status")??""}:{},...e.headers.get("x-neurolink-grant-reason")?{grantReason:e.headers.get("x-neurolink-grant-reason")??""}:{},...t!==void 0?{remainingCoins:t}:{}}}function Zin(e,t,r){const n=e.body;if(!n)return e;let o;const s=()=>{o!==void 0&&(clearTimeout(o),o=void 0)},i=()=>{s(),o=setTimeout(()=>{f.always(`[proxy] peer=${t.name} went quiet mid-response; abandoning it`),Hle(t.name,"unreachable").catch(l=>{f.debug(`[proxy] could not cool peer=${t.name} after a stall: ${l instanceof Error?l.message:String(l)}`)}),r.abort()},Kin),o.unref?.()},a=n.pipeThrough(new TransformStream({start:i,transform(l,c){i(),c.enqueue(l)},flush:s}));return r.signal.addEventListener("abort",s,{once:!0}),new Response(a,{status:e.status,statusText:e.statusText,headers:e.headers})}async function Xin(e){const{peer:t,body:r,stream:n}=e,o=new AbortController,s=setTimeout(()=>o.abort(),Win);e.signal&&(e.signal.aborted?o.abort():e.signal.addEventListener("abort",()=>o.abort(),{once:!0}));try{const i=await fetch(`${t.url}/v1/messages`,{method:"POST",headers:{"content-type":"application/json","x-neurolink-share-token":t.token,accept:n?"text/event-stream":"application/json"},body:r,signal:o.signal});if(i.ok)return await Rin(t.name,Yin(i)).catch(u=>{f.debug(`[proxy] could not record success for peer=${t.name}: ${u instanceof Error?u.message:String(u)}`)}),{ok:!0,response:Zin(i,t,o),peer:t};const a=i.headers.get("x-neurolink-grant-reason"),l=Jin(a),c=Vir(i,"retry-after");return await Hle(t.name,l,c),await i.text().catch(()=>""),f.always(`[proxy] peer=${t.name} declined (${l}); cooling before retry`),{ok:!1,peer:t,status:i.status,reason:l,message:`peer ${t.name} declined: ${l}`,...c!==void 0?{retryAfterSeconds:c}:{}}}catch(i){const a=i instanceof Error?i.message:String(i);return e.signal?.aborted?(f.debug(`[proxy] peer=${t.name} attempt cancelled by the caller: ${a}`),{ok:!1,peer:t,reason:"unreachable",message:`peer ${t.name} attempt cancelled`}):(await Hle(t.name,"unreachable").catch(l=>{f.debug(`[proxy] could not cool peer=${t.name}: ${l instanceof Error?l.message:String(l)}`)}),f.always(`[proxy] peer=${t.name} unreachable: ${a}`),{ok:!1,peer:t,reason:"unreachable",message:`peer ${t.name} unreachable`})}finally{clearTimeout(s)}}dA();var Qin=36e5,ean={missing_token:"No share token was presented.",unknown_token:"Share token is not recognized.",malformed_token:"Share token is malformed.",paused:"The lender has paused this share.",revoked:"This share has been revoked.",expired:"This share has expired.",out_of_window:"This share is outside its allowed hours.",model_not_allowed:"This share does not cover the requested model.",exhausted:"This share has no credit remaining.",rate_limited:"This share's request rate limit was exceeded.",concurrency_limited:"This share's concurrent request limit was reached.",reserve_floor:"The lender's reserved headroom is in force.",spillover_inactive:"This share serves only the lender's spare capacity, and none is spare yet.",slice_exhausted:"This share has used its allotted portion of the window.",no_capacity:"No lender account can currently serve this share."};function tan(e){return ean[e]}function ran(e){switch(e){case"missing_token":case"unknown_token":case"malformed_token":return 401;case"paused":case"revoked":case"expired":case"out_of_window":case"model_not_allowed":return 403;default:return 429}}function nan(e,t){const r=new Date(t).getHours(),{fromHour:n,toHour:o}=e;return n===o?!0:n<o?r>=n&&r<o:r>=n||r<o}function oan(e,t){if(!e||e.length===0)return!0;if(!t)return!1;const r=t.toLowerCase();return e.some(n=>r.includes(n.toLowerCase()))}function Wir(e,t){const r=n=>n===void 0?t:t===void 0?n:Math.min(n,t);return{session:r(e?.session5hPct),weekly:r(e?.weekly7dPct)}}function Kir(e,t,r){const n=e.spillover;if(!n)return!1;const o=n.beforeResetHours*Qin,s=n.whenUtilizationBelowPct/100,i=t.weeklyResetAt!==null&&t.weeklyResetAt-r<=o&&t.weeklyResetAt>r&&t.weeklyUsed!==null&&t.weeklyUsed<s,a=t.sessionResetAt!==null&&t.sessionResetAt-r<=o&&t.sessionResetAt>r&&t.sessionUsed!==null&&t.sessionUsed<s;return i||a}function Kle(e,t){if(!e.accounts||e.accounts.length===0)return{inScope:[...t],outOfScope:[]};const r=new Set(e.accounts.map(s=>s.trim().toLowerCase())),n=[],o=[];for(const s of t){const i=s.accountKey.toLowerCase(),a=i.includes(":")?i.slice(i.indexOf(":")+1):i;r.has(i)||r.has(a)?n.push(s):o.push(s)}return{inScope:n,outOfScope:o}}function Jle(e,t,r,n){const o=e.gates,{inScope:s,outOfScope:i}=Kle(o,t),a=s.some(m=>Kir(o,m,r)),l=Wir(o.maxSlice,a?o.spillover?.maxSlicePct:void 0);if(l.session!==void 0&&n.sessionFraction*100>=l.session||l.weekly!==void 0&&n.weeklyFraction*100>=l.weekly)return{allowed:[],excluded:[...s.map(m=>({accountKey:m.accountKey,reason:"slice_exhausted"})),...i.map(m=>({accountKey:m.accountKey,reason:"no_capacity"}))]};const u=[],d=i.map(m=>({accountKey:m.accountKey,reason:"no_capacity"}));for(const m of s){const h=Kir(o,m,r);if(o.spillover&&!h){d.push({accountKey:m.accountKey,reason:"spillover_inactive"});continue}const g=o.reserveFloor;if(g){const b=g.session5hPct!==void 0&&m.sessionUsed!==null&&m.sessionUsed*100>100-g.session5hPct,T=g.weekly7dPct!==void 0&&m.weeklyUsed!==null&&m.weeklyUsed*100>100-g.weekly7dPct;if(b||T){d.push({accountKey:m.accountKey,reason:"reserve_floor"});continue}}const y=Wir(o.maxSlicePerAccount,h?o.spillover?.maxSlicePct:void 0),v=y.session!==void 0&&m.borrowedSessionFraction*100>=y.session,_=y.weekly!==void 0&&m.borrowedWeeklyFraction*100>=y.weekly;if(v||_){d.push({accountKey:m.accountKey,reason:"slice_exhausted"});continue}u.push(m.accountKey)}return{allowed:u,excluded:d}}function Yle(e){return e.some(t=>t.reason==="reserve_floor")?"reserve_floor":e.some(t=>t.reason==="spillover_inactive")?"spillover_inactive":e.some(t=>t.reason==="slice_exhausted")?"slice_exhausted":"no_capacity"}var san="x-neurolink-share-token",ian="x-neurolink-grant-status",aan="x-neurolink-grant-reason",lan="x-neurolink-grant-remaining-coins",can="x-neurolink-grant-peer";function uan(e){const t=e[san];if(t?.trim())return t.trim();const r=e.authorization??e.Authorization;if(!r)return;const n=r.trim(),o=n.toLowerCase().startsWith("bearer ")?n.slice(7).trim():n;return LQr(o)?o:void 0}function dan(e){return e===401?"authentication_error":e===403?"permission_error":"rate_limit_error"}function pan(e,t){switch(e){case"paused":return"paused";case"revoked":return"revoked";case"expired":return"expired";case"exhausted":return"exhausted";case"out_of_window":return"out-of-window";case"missing_token":case"unknown_token":case"malformed_token":return"unauthorized";default:return t?.state??"active"}}function pb(e,t){const{status:r,grant:n,retryAfterSeconds:o}=t,s={[ian]:pan(e,n),[aan]:e};return n&&(s[can]=n.peerLabel,n.entitlement.ledger==="coins"&&(s[lan]=String(Math.max(0,Math.floor(n.entitlement.coins??0))))),o!==void 0&&(s["retry-after"]=String(Math.max(1,Math.round(o)))),{status:r,headers:s,body:{type:"error",error:{type:dan(r),message:t.message??tan(e)}}}}dA(),Jr(),ii(),nr(),Oc(),Gl();var man="proxy-share-audit.json",han=2,fan=3,gan=1e3,yan=null,mb={},BA=0,zA=-1,jA=!1,van=new sl;function Zle(){return yan??St(Wa(),".neurolink",man)}function _an(e){return e?.code==="ENOENT"}async function wan(e={}){const t=Date.now();if(!e.force&&jA&&t-BA<gan)return;const r=Zle();let n;try{n=(await qs(r)).mtimeMs}catch(o){if(!_an(o))throw o;mb={},zA=-1,BA=t,jA=!0;return}if(!e.force&&jA&&n===zA){BA=t;return}try{mb=JSON.parse(await Kr(r,"utf8"))?.records??{}}catch(o){if(e.force)throw o;mb={}}zA=n,BA=t,jA=!0}async function ban(){const e={schemaVersion:1,records:mb};await il(Zle(),e);try{zA=(await qs(Zle())).mtimeMs}catch{zA=-1}BA=Date.now(),jA=!0}function Jir(e,t){return e===null||t===null?0:Math.max(0,(t-e)*100)}function Tan(e,t,r=han){if(!e)return{drifted:!1,reason:"no_baseline"};if(t.lenderRequests>0)return{drifted:!1,reason:"attributable"};const n=Jir(e.sessionUsed,t.sessionUsed),o=Jir(e.weeklyUsed,t.weeklyUsed),s=Math.max(n,o);return s<=r?{drifted:!1,reason:"quiet"}:t.reportedCoins>0?{drifted:!1,reason:"attributable"}:{drifted:!0,unexplainedSessionPct:n,unexplainedWeeklyPct:o,detail:`the account moved ${s.toFixed(1)}% of a window since the last check-in while this node served none of it and the borrower reported no spend`}}async function Ean(e){const t=e.streakLimit??fan;return van.runExclusive(async()=>{await wan({force:!0});const r=mb[e.grantId],n=e.lenderRequestsTotal===void 0?e.observation:{...e.observation,lenderRequests:Math.max(0,e.lenderRequestsTotal-(r?.lenderRequestsTotal??0))},o=Tan(r?.lastObservation,n,e.tolerancePct),s=o.drifted?(r?.driftStreak??0)+1:0,i={grantId:e.grantId,accountLabel:e.accountLabel,lastObservation:n,...e.lenderRequestsTotal!==void 0?{lenderRequestsTotal:e.lenderRequestsTotal}:r?.lenderRequestsTotal!==void 0?{lenderRequestsTotal:r.lenderRequestsTotal}:{},driftStreak:s,...o.drifted?{lastDriftAt:n.at,lastDriftDetail:o.detail}:{...r?.lastDriftAt!==void 0?{lastDriftAt:r.lastDriftAt}:{},...r?.lastDriftDetail!==void 0?{lastDriftDetail:r.lastDriftDetail}:{}},...r?.autoPausedAt!==void 0?{autoPausedAt:r.autoPausedAt}:{}},a=s>=t&&i.autoPausedAt===void 0;return a&&(i.autoPausedAt=n.at),mb[e.grantId]=i,await ban(),{verdict:o,shouldPause:a}})}Ho(),Jr(),ii(),nr(),Oc(),Gl();var San="proxy-share-provisioning.json",Can=9e5,kan=/^[A-Za-z0-9_-]{43}$/,xan=/^[A-Za-z0-9_-]{16,128}$/,Aan=null,hb={},Yir=!1,Zir=new sl;function Xir(){return Aan??St(Wa(),".neurolink",San)}function Ian(e){if(!e||typeof e!="object")return!1;const t=e;return typeof t.grantId=="string"&&typeof t.codeChallenge=="string"&&typeof t.state=="string"&&typeof t.expiresAt=="number"&&typeof t.status=="string"}async function Qir(e={}){if(!(Yir&&!e.force)){try{const t=JSON.parse(await Kr(Xir(),"utf8"));hb=Object.fromEntries(Object.entries(t?.requests??{}).filter(r=>Ian(r[1])))}catch{hb={}}Yir=!0}}async function ear(){const e={schemaVersion:1,requests:hb};await il(Xir(),e)}function Ran(e,t=Date.now()){return e.status!=="consumed"&&e.expiresAt>t}async function Man(e){if(!kan.test(e.codeChallenge))return{ok:!1,reason:"code_challenge must be a base64url S256 digest"};if(!xan.test(e.state))return{ok:!1,reason:"state must be 16-128 base64url characters"};const t=e.now??Date.now();return Zir.runExclusive(async()=>{await Qir({force:!0});const r={schemaVersion:1,grantId:e.grantId,codeChallenge:e.codeChallenge,challengeMethod:"S256",state:e.state,requestedAt:t,expiresAt:t+Can,status:"pending"};return hb[e.grantId]=r,await ear(),{ok:!0,request:r}})}async function Pan(e,t=Date.now()){return Zir.runExclusive(async()=>{await Qir({force:!0});const r=hb[e];if(!r||!Ran(r,t))return{status:"none"};if(r.status!=="authorized"||!r.code)return{status:"pending"};const{code:n,...o}=r;return hb[e]={...o,status:"consumed",claimedAt:t},await ear(),{status:"ready",code:r.code,state:r.state}})}Ter(),Ho(),Jr(),ii(),nr(),Oc(),dA(),w$();var Dan="proxy-share-notes.json",tar="nln",Oan=null,fb={},rar=!1,Nan=new sl;function nar(){return Oan??St(Wa(),".neurolink",Dan)}async function oar(e={}){if(!(rar&&!e.force)){try{fb=JSON.parse(await Kr(nar(),"utf8"))?.notes??{}}catch{fb={}}rar=!0}}async function Lan(){const{writeJsonSnapshotAtomically:e}=await Promise.resolve().then(()=>(Gl(),Fie)),t={schemaVersion:1,notes:fb};await e(nar(),t)}function $an(e){const t=e.trim();if(t.startsWith(`${tar}_`))try{const r=JSON.parse(Buffer.from(t.slice(tar.length+1),"base64url").toString("utf8"));return typeof r?.noteId!="string"||typeof r.coins!="number"||typeof r.signature!="string"||typeof r.notAfter!="number"?void 0:r}catch{return}}async function Fan(e,t,r=Date.now()){const{signature:n,...o}=e;if(!t||!_$(o,n,t))return{status:"forged",coins:0};await oar({force:!0});const s=fb[e.noteId];return s?s.redeemedAt!==void 0?{status:"spent",coins:s.coins}:s.notAfter<=r?{status:"expired",coins:s.coins}:{status:"valid",coins:s.coins}:{status:"unknown",coins:0}}async function Uan(e){const t=e.now??Date.now(),{signature:r,...n}=e.note;if(!e.secret||!_$(n,r,e.secret))return{ok:!1,status:"forged"};const o=await Nan.runExclusive(async()=>{await oar({force:!0});const i=fb[e.note.noteId];return i?i.redeemedAt!==void 0?{status:"spent",coins:i.coins}:i.notAfter<=t?{status:"expired",coins:i.coins}:(fb[i.noteId]={...i,redeemedAt:t,redeemedByGrant:e.grantId},await Lan(),{status:"valid",coins:i.coins}):{status:"unknown",coins:0}});if(o.status!=="valid")return{ok:!1,status:o.status};const s=await per(e.grantId,o.coins);return{ok:!0,coins:o.coins,balance:s}}w$(),Oer();var Ban=64*1024,zan=32;function sar(e){try{const t=JSON.parse(e);return{errorType:t.error?.type??t.type??"stream_error",message:t.error?.message??t.message??"Upstream SSE error"}}catch{return{errorType:"stream_error",message:e.trim()||"Upstream SSE error"}}}function iar(e){if(e.event==="error")return!0;try{const t=JSON.parse(e.data);return t.type==="error"||t.error!==void 0}catch{return!1}}async function jan(e){const t=new TextDecoder,r=[];let n="",o=0;for(;o<Ban&&r.length<zan;){let s;try{s=await e.read()}catch(a){return{kind:"transport_error",chunks:r,error:a}}if(s.done){n+=t.decode();const{events:a}=aF(n),l=a.find(iar);return l?{kind:"sse_error",chunks:r,...sar(l.data)}:r.length>0?{kind:"ready",chunks:r}:{kind:"empty",chunks:r}}if(!s.value||s.value.length===0)continue;r.push(s.value),o+=s.value.byteLength,n+=t.decode(s.value,{stream:!0});const i=aF(n);n=i.remainder;for(const a of i.events){if(iar(a))return{kind:"sse_error",chunks:r,...sar(a.data)};if(a.event!=="ping"&&(a.event||a.data))return{kind:"ready",chunks:r}}}return r.length>0?{kind:"ready",chunks:r}:{kind:"empty",chunks:r}}function aar(){let e=!1,t;const r=new Promise(o=>{t=o}),n=o=>{e||(e=!0,t(o))};return{outcome:r,complete:()=>n({kind:"completed"}),fail:o=>n({kind:"upstream_error",message:o}),cancel:()=>n({kind:"client_cancelled"})}}function cF(e,t){return e.kind==="completed"&&t?{kind:"upstream_error",message:t}:e}function qan(e){const t=e.toLowerCase();return t.includes("opus")?"opus":t.includes("sonnet")?"sonnet":t.includes("haiku")?"haiku":"other"}function gb(e,t,r,n,o=!1){const s=[{provider:e.provider,model:e.model,label:`${e.provider}/${e.model??"unknown"}`}];for(const i of t)i.provider===e.provider&&i.model===e.model||s.push({provider:i.provider,model:i.model,label:`${i.provider}/${i.model}`});return o&&(t.length===0||s.length===1)&&s.push({label:"auto-provider"}),{requestedModel:r,modelTier:qan(r),attempts:s,skipped:[]}}function uF(e){if(!e)return 0;const t=parseInt(e,10);if(!Number.isNaN(t))return Math.max(1,t)*1e3;const r=new Date(e);return Number.isNaN(r.getTime())?0:Math.max(1e3,r.getTime()-Date.now())}var Gan=1,Han=20;function Xle(e){return typeof e=="number"&&Number.isInteger(e)&&e>=Gan&&e<=Han?e:void 0}Gl(),v$(),wr(),q(),pn(),iy(),rA(),Jr(),ii(),nr(),q();var Van="app_EMoamEEZ73f0CkXaXp7hrann",Wan="https://auth.openai.com/oauth/token",Kan=["openid","profile","email","offline_access"],Qle="https://chatgpt.com/backend-api/codex",Jan=`${Qle}/responses`,xhn=`${Qle}/usage`,lar=`${Qle}/models`,Yan="0.144.4",car=`codex_cli_rs/${Yan} (external; neurolink-proxy)`,Zan="codex_cli_rs",Ahn=St(Wa(),".codex","auth.json");function uar(e){try{const t=e+"=".repeat((4-e.length%4)%4),r=Buffer.from(t.replace(/-/g,"+").replace(/_/g,"/"),"base64").toString("utf8"),n=JSON.parse(r);return n&&typeof n=="object"?n:null}catch{return null}}function Xan(e){if(!e)return null;const t=e["https://api.openai.com/auth"];return t&&typeof t=="object"?t:null}function dar(e){const t=e.split(".");if(t.length!==3)return{};const r=uar(t[1]),n=Xan(r),o=typeof n?.chatgpt_account_id=="string"?n.chatgpt_account_id:void 0,s=typeof n?.chatgpt_plan_type=="string"?n.chatgpt_plan_type:void 0,i=typeof r?.exp=="number"?r.exp*1e3:void 0;return{accountId:o,planType:s,expiresAt:i}}function Qan(e){if(!e)return;const t=e.split(".");if(t.length!==3)return;const r=uar(t[1]);return typeof r?.email=="string"?r.email:void 0}function dF(e,t){return t&&t.length>0?t:dar(e).accountId}function eln(e){const t=dar(e.access_token);return{accessToken:e.access_token,refreshToken:e.refresh_token,idToken:e.id_token,accountId:e.account_id??t.accountId,expiresAt:t.expiresAt,planType:t.planType,email:Qan(e.id_token)}}async function tln(e,t={}){const r=new URLSearchParams({grant_type:"refresh_token",refresh_token:e,client_id:Van,scope:Kan.join(" ")}),n=await fetch(Wan,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json","User-Agent":car},body:r.toString(),signal:AbortSignal.timeout(t.timeoutMs??1e4)});if(!n.ok){const s=await n.text().catch(()=>"");throw Object.assign(new Error(`Codex token refresh failed: ${n.status} ${s.slice(0,200)}`),{status:n.status})}const o=await n.json();if(!o.access_token)throw new Error("Codex token refresh returned no access_token");return f.debug("Codex token refreshed"),eln({access_token:o.access_token,refresh_token:o.refresh_token??e,id_token:o.id_token})}function rln(e){const t=e?.status;return typeof t!="number"||t<400||t>=500?!1:t!==408&&t!==429}function nln(e,t=300*1e3){return e?e-t<=Date.now():!1}var ece="codex:";function tce(e){return typeof e!="number"||!Number.isFinite(e)?0:Math.min(1,Math.max(0,e/100))}function rce(e,t){if(!e)return 0;if(typeof e.resets_at=="number"&&Number.isFinite(e.resets_at)&&e.resets_at>0)return e.resets_at>4102444800?Math.floor(e.resets_at/1e3):e.resets_at;const r=typeof e.resets_in_seconds=="number"?e.resets_in_seconds:e.reset_after;return typeof r=="number"&&Number.isFinite(r)&&r>0?t+Math.floor(r):0}function nce(e){return e>=1?"rejected":"allowed"}function par(e,t,r,n){if(!r)return null;const o=tce(r.used_percent);return{kind:e,group:t,used:o,status:nce(o),resetsAt:rce(r,n),isActive:!0}}function oln(e,t=Date.now()){const r=Math.floor(t/1e3),n=e?.primary??null,o=e?.secondary??null,s=tce(n?.used_percent),i=tce(o?.used_percent),a=[],l=par("session","session",n,r),c=par("weekly_all","weekly",o,r);return l&&a.push(l),c&&a.push(c),{sessionUsed:s,sessionStatus:nce(s),sessionResetAt:rce(n,r),weeklyUsed:i,weeklyStatus:nce(i),weeklyResetAt:rce(o,r),fallbackPercentage:0,overageStatus:"rejected",lastUpdated:t,windows:a.length>0?a:void 0,windowsUpdatedAt:a.length>0?t:void 0,source:"usage-api"}}function mar(e,t=Date.now()){const r=e.get("x-codex-ratelimit")??e.get("x-codex-active-limit")??null;if(!r)return null;try{const n=JSON.parse(r),o="rate_limits"in n&&n.rate_limits?n.rate_limits:n;return oln(o,t)}catch{return null}}pn(),q();var sln=1e3;function oce(e){try{e?.()}catch(t){f.shouldLog("debug")&&f.debug("[proxy] response lifecycle observer failed",{error:t instanceof Error?t.message:String(t)})}}function iln(e,t,r){if(!e.body)return t(),oce(()=>r?.onTerminal?.({outcome:"bodyless",observedBodyBytes:0,responseChunks:0})),e;const n=e.body.getReader();let o=0,s=0,i=!1,a=!1;n.closed.then(()=>{a=!0},()=>{});const l=u=>{i||(i=!0,t(),oce(()=>r?.onTerminal?.({outcome:u,observedBodyBytes:o,responseChunks:s})))},c=new ReadableStream({async pull(u){try{const{value:d,done:m}=await n.read();if(m){l("completed"),u.close();return}u.enqueue(d),o+=d.byteLength,s+=1,s===1&&oce(()=>r?.onFirstChunk?.({observedBodyBytes:o,responseChunks:1}))}catch(d){l("stream_error"),u.error(d)}},async cancel(u){await Promise.resolve(),l(a?"completed":"client_cancelled"),await Bt(n.cancel(u),sln,"Timed out cancelling the upstream proxy response")}});return new Response(c,{status:e.status,statusText:e.statusText,headers:e.headers})}v$(),wr(),q();var har=900*1e3,far=6e4,aln=900*1e3,gar=6e4,jp="codex-oauth",lln="neurolink.codexFallback";function yar(e){if(!e||typeof e!="object")return;const t=e.code;if(typeof t=="string")return t;const r=e.cause;if(!r||typeof r!="object")return;const n=r.code;return typeof n=="string"?n:void 0}function cln(e){const t=yar(e);return t==="ENOTFOUND"||t==="EAI_AGAIN"?"shared_provider_transport":"connection_transport"}function pF(e,t){return Xn(e).slice(0,200)||t}var sce=new Map;async function uln(e,t,r,n){const o=sce.get(e);if(o)return o;const s=(async()=>{const i=await r.peekTokens(e).catch(()=>null),a=i?.refreshToken??t,l=await n(a),c={accessToken:l.accessToken,refreshToken:l.refreshToken??a,expiresAt:l.expiresAt??i?.expiresAt??Date.now()+36e5};return i&&await r.saveTokens(e,{...c,tokenType:"Bearer",...i.scope?{scope:i.scope}:{}}),c})().finally(()=>{sce.delete(e)});return sce.set(e,s),s}async function ice(e,t){return uln(e,t,al,tln)}var dln=new Set(["host","connection","content-length","transfer-encoding","cookie","proxy-authorization","authorization","x-api-key","chatgpt-account-id","accept-encoding"]);function mF(e,t){return new Response(JSON.stringify({error:{type:"proxy_error",message:t}}),{status:e,headers:{"content-type":"application/json"}})}async function _ar(){const e=await al.listByPrefix(ece),[t,r]=await Promise.all([AA(),hle()]),n=Date.now(),o=[];for(const s of e){if(await al.isDisabled(s))continue;const i=await al.loadTokens(s);if(!i||i.tokenType!=="Bearer")continue;let a=i.accessToken,l=i.expiresAt;if(nln(l)&&i.refreshToken)try{const d=await ice(s,i.refreshToken);a=d.accessToken,l=d.expiresAt??l}catch(d){f.debug(`Codex proactive refresh failed for ${s.slice(ece.length)}: ${d instanceof Error?d.message:String(d)}`)}const c=t[s],u=c&&c.coolingUntil>n;o.push({key:s,label:s.slice(ece.length)||s,token:a,refreshToken:i.refreshToken,expiresAt:l,accountId:dF(a),quota:r[s],coolingUntil:u?c.coolingUntil:void 0,coolingReason:c?.reason,expiredCooldownUntil:c&&!u?c.coolingUntil:void 0})}return o}function war(e,t){return[...e].sort((r,n)=>{const o=r.coolingUntil!==void 0&&r.coolingUntil>t,s=n.coolingUntil!==void 0&&n.coolingUntil>t;if(o!==s)return o?1:-1;const i=r.quota?r.quota.sessionUsed:-1,a=n.quota?n.quota.sessionUsed:-1;return i-a})}function bar(e,t){const r={};for(const[o,s]of Object.entries(e)){const i=o.toLowerCase();dln.has(i)||(r[i]=s)}r.authorization=`Bearer ${t.token}`;const n=dF(t.token,t.accountId);return n&&(r["chatgpt-account-id"]=n),r["content-type"]="application/json",r["user-agent"]||(r["user-agent"]=car),r.originator||(r.originator=Zan),r.accept||(r.accept="text/event-stream"),r}function pln(e,t,r){const n=r+far;if(e){if(e.weeklyStatus==="rejected"&&e.weeklyResetAt>0)return{coolingUntil:Math.max(e.weeklyResetAt*1e3,n),reason:"weekly"};if(e.sessionStatus==="rejected"&&e.sessionResetAt>0)return{coolingUntil:Math.max(e.sessionResetAt*1e3,n),reason:"session"}}const o=Math.min(aln,Math.max(t,far));return{coolingUntil:r+o,reason:"transient"}}function mln(e,t,r,n){e.responseHeaders||(e.responseHeaders={}),e.responseHeaders["x-neurolink-account"]=t.label,e.responseHeaders["x-neurolink-account-type"]="codex-oauth",e.responseHeaders["x-neurolink-served-by"]="codex",e.responseHeaders["x-neurolink-attempt"]=String(r),e.responseHeaders["x-neurolink-quota-source"]=n?"live":"none",n&&(e.responseHeaders["x-neurolink-quota-session-left-pct"]=String(Math.round((1-n.sessionUsed)*100)),e.responseHeaders["x-neurolink-weekly-left-pct"]=String(Math.round((1-n.weeklyUsed)*100)))}async function Tar(e){const t=Date.now(),r=e.body??{},n=JSON.stringify(r),o=typeof r.model=="string"?r.model:"-",s=e.metadata?.[lln]===!0,i=(b,T,k={})=>Rh({timestamp:new Date().toISOString(),requestId:e.requestId,method:e.method,path:e.path,model:o,stream:!0,toolCount:Array.isArray(r.tools)?r.tools.length:0,account:b?.label??"",...b?{accountKey:b.key}:{},accountType:b?jp:"",provider:"openai",...cb(e.headers),responseStatus:T,responseTimeMs:Date.now()-t,...k});let a=!1;const l=async(b,T,k={})=>{s||a||(a=!0,T>=400?Uw(T,b?.label,b?jp:void 0,{requestId:e.requestId,...b?{accountKey:b.key}:{},errorType:k.errorType,terminalOutcome:k.terminalOutcome??"handler_error",message:k.errorMessage,errorCode:k.errorCode}):iA(b?.label,b?jp:void 0),await i(b,T,k))},c=(b,T,k,x,I={})=>{Air({timestamp:new Date().toISOString(),requestId:e.requestId,attempt:T,method:e.method,path:e.path,model:o,stream:!0,toolCount:Array.isArray(r.tools)?r.tools.length:0,account:b.label,accountKey:b.key,accountType:jp,provider:"openai",responseStatus:x,responseTimeMs:Date.now()-t,attemptDurationMs:Date.now()-k,...I}).catch(()=>{})},u=await _ar();if(u.length===0)return await l(void 0,401,{errorType:"no_accounts",errorMessage:"No Codex accounts"}),mF(401,"No Codex accounts configured. Run `neurolink auth login codex`.");const d=Date.now(),m=war(u,d),h=m.filter(b=>!(b.coolingUntil!==void 0&&b.coolingUntil>d));if(h.length===0){const b=m.reduce((k,x)=>x.coolingUntil===void 0?k:k===void 0?x.coolingUntil:Math.min(k,x.coolingUntil),void 0),T=b?Math.max(1,Math.ceil((b-d)/1e3)):60;return await l(void 0,429,{errorType:"all_accounts_cooling",errorMessage:"All Codex accounts are rate-limited"}),new Response(JSON.stringify({error:{type:"rate_limit_error",message:"All Codex accounts are currently rate-limited"}}),{status:429,headers:{"content-type":"application/json","retry-after":String(T)}})}let g=0,y="All Codex accounts failed",v=502,_;for(const b of h){let T=!1;for(;;){g+=1;const k=Date.now();_=b,Ty(b.label,jp);let x;try{x=await fetch(Jan,{method:"POST",headers:bar(e.headers,b),body:n,signal:AbortSignal.timeout(har)})}catch(A){f.debug(`Codex upstream fetch failed (${b.label}): ${Xn(A instanceof Error?A.message:String(A))}`);const P=pF(A instanceof Error?A.message:String(A),"Codex upstream request failed"),L=yar(A),N=cln(A);$r(b.label,jp,502),c(b,g,k,502,{errorType:"network_error",errorMessage:P,...L?{errorCode:L}:{},transportScope:N,retryable:!0}),y="Codex upstream request failed",v=502;break}if(x.ok){const A=mar(x.headers);A&&Ry(b.key,A).catch(()=>{}),b.expiredCooldownUntil!==void 0&&xy(b.key,b.expiredCooldownUntil).catch(()=>{}),mln(e,b,g,A),c(b,g,k,x.status);const P={"content-type":x.headers.get("content-type")??"text/event-stream","cache-control":"no-cache",connection:"keep-alive",...e.responseHeaders??{}};if(!x.body)return await l(b,x.status,{terminalOutcome:"bodyless"}),new Response(x.body,{status:x.status,headers:P});const{stream:L,usage:N}=rsn(),D=new Response(x.body.pipeThrough(L),{status:x.status,headers:P});return iln(D,()=>{},{onTerminal:({outcome:O})=>{N.then(F=>{const $=F?{inputTokens:F.inputTokens,outputTokens:F.outputTokens,cacheReadTokens:F.cacheReadTokens,cacheCreationTokens:F.cacheCreationTokens}:{};return O==="completed"||O==="bodyless"?l(b,x.status,{terminalOutcome:O,...$}):l(b,O==="client_cancelled"?499:502,{errorType:O==="client_cancelled"?"client_cancelled":"stream_error",errorMessage:O==="client_cancelled"?"Client cancelled Codex stream":"Codex upstream stream failed",terminalOutcome:O,...$})}).catch(()=>{})}})}const I=await x.text().catch(()=>"");if((x.status===401||x.status===403)&&!T&&b.refreshToken){const A=pF(I,"Codex authentication rejected upstream");$r(b.label,jp,x.status),c(b,g,k,x.status,{errorType:"authentication_error",errorMessage:A,retryable:!0}),T=!0;const P={accessToken:b.token,refreshToken:b.refreshToken,expiresAt:b.expiresAt??0};try{const L=await ice(b.key,b.refreshToken);b.token=L.accessToken,b.refreshToken=L.refreshToken??b.refreshToken,b.expiresAt=L.expiresAt??b.expiresAt,b.accountId=dF(L.accessToken);continue}catch(L){if(rln(L)){await al.markDisabledIfCurrent(b.key,P,"refresh_invalid")&&f.always(`[proxy] codex account=${b.label} disabled until re-authentication. Run: neurolink auth login codex --label ${b.label}`),v=401,y="Codex token refresh failed; re-login required";break}await Td(b.key,Date.now()+gar,"auth").catch(()=>{}),f.debug(`[proxy] codex account=${b.label} refresh failed transiently; cooling and rotating`),v=503,y="Codex token refresh temporarily unavailable";break}}if(x.status===429){const A=mar(x.headers);A&&Ry(b.key,A).catch(()=>{});const P=uF(x.headers.get("retry-after")),L=pln(A,P,Date.now());await Td(b.key,L.coolingUntil,L.reason).catch(()=>{});const N=L.reason==="transient"?"transient":"quota",D=pF(I,"Codex account rate-limited");$r(b.label,jp,x.status,N),c(b,g,k,x.status,{errorType:"rate_limit_error",errorMessage:D,retryable:!0,rateLimitKind:N,cooldownReason:L.reason}),v=429,y="Codex account rate-limited";break}(x.status===401||x.status===403)&&await Td(b.key,Date.now()+gar,"auth").catch(()=>{});const M=pF(I,"Codex error"),R=x.status===401||x.status===403?"authentication_error":"api_error";$r(b.label,jp,x.status),c(b,g,k,x.status,{errorType:R,errorMessage:M,retryable:x.status>=500}),v=x.status>=500?502:x.status,y=M;break}}return await l(_,v,{errorType:"all_accounts_failed",errorMessage:y}),mF(v,y)}async function hln(e){const t=await _ar();if(t.length===0)return mF(401,"No Codex accounts configured. Run `neurolink auth login codex`.");const r=Date.now(),n=war(t,r),o=d=>d.coolingUntil!==void 0&&d.coolingUntil>r,s=[...n.filter(d=>!o(d)),...n.filter(o)],a=new URLSearchParams(e.query??{}).toString(),l=a?`${lar}?${a}`:lar;let c=502,u="Codex model discovery upstream failed";for(const d of s){let m=!1;for(;;){let h;try{h=await fetch(l,{method:"GET",headers:bar(e.headers??{},d),signal:AbortSignal.timeout(har)})}catch(v){c=502,u=`Codex model discovery upstream failed: ${v instanceof Error?v.message:String(v)}`;break}if(h.status===401||h.status===403){if(!m&&d.refreshToken){m=!0;try{const v=await ice(d.key,d.refreshToken);d.token=v.accessToken,d.refreshToken=v.refreshToken??d.refreshToken,d.expiresAt=v.expiresAt??d.expiresAt,d.accountId=dF(v.accessToken);continue}catch{c=401,u="Codex token refresh failed; re-login required";break}}c=h.status,u="Codex model discovery rejected upstream";break}const g=await h.text(),y=h.headers.get("content-type")??"application/json";return new Response(g,{status:h.status,headers:{"content-type":y}})}}return mF(c,u)}function fln(e=""){return{prefix:`${e}/backend-api/codex`,routes:[{method:"POST",path:`${e}/backend-api/codex/responses`,description:"Codex ChatGPT-backend Responses API (account pool)",handler:t=>Tar(t)},{method:"GET",path:`${e}/backend-api/codex/models`,description:"Codex model discovery, relayed upstream (account pool)",handler:t=>hln(t)}]}}var hF=new Set(["cookie","proxy-authorization","host","connection","content-length","transfer-encoding"]),ace="proxy/internal",lce="internal";function Ear(e,t){return e?t==="codex-oauth"?{accountKey:e.startsWith("codex:")?e:`codex:${e}`,provider:"openai"}:t==="oauth"||t==="api_key"||t==="passthrough"?{accountKey:t==="passthrough"?e:eA(e),provider:"anthropic"}:{}:{}}var Mh=0,Sar=0,qA=5,fF=2,cce=[250,1e3],Car=[250,500,1e3,2e3],uce=1,gln=120*1e3,dce=2,kar=3e4,xar=11520*60*1e3,Aar=5e3,yln=900*1e3,Iar=900*1e3,vln=3e4,_ln=300*1e3,GA=900*1e3,Rar;function pce(e,t){return Rar??=new PS({headersTimeout:GA,bodyTimeout:GA}),fetch(e,{...t,dispatcher:Rar})}var Jl=new Map,HA=new Gon,yb=new Von,Mar=900*1e3,Par=new Map,Dar=new Map,gF=new Map,wln={release:()=>{}};function Oar(e){let t=gF.get(e);return t||(t={active:0,waiters:[]},gF.set(e,t)),t}function mce(e,t){for(;t.waiters.length>0&&t.active<t.waiters[0].capacity;){const r=t.waiters.shift();if(!r)return;t.active+=1,r.resolve(Nar(e,t))}}function Nar(e,t){let r=!1;return{release:()=>{r||(r=!0,t.active=Math.max(0,t.active-1),mce(e,t),Lar(e,t))}}}function Lar(e,t){t.active===0&&t.waiters.length===0&&gF.delete(e)}function bln(e,t){const r=Xle(t);if(r===void 0)return wln;const n=Oar(e);if(!(n.waiters.length>0||n.active>=r))return n.active+=1,Nar(e,n)}function Tln(e,t){const r=Xle(t);if(r===void 0)return!0;const n=gF.get(e);return!n||n.waiters.length===0&&n.active<r}function Eln(e,t){const r=Xle(t);if(r===void 0)throw new Error("Account admission queue requires an explicit capacity");const n=Oar(e);let o=!0,s,i;const a=new Promise(c=>{i=c}),l={capacity:r,resolve:c=>{o=!1,s=c,i(c)}};return n.waiters.push(l),mce(e,n),{accountKey:e,promise:a,cancel:()=>{if(s){const u=s;s=void 0,u.release();return}if(!o)return;o=!1;const c=n.waiters.indexOf(l);c>=0&&(n.waiters.splice(c,1),mce(e,n)),Lar(e,n)}}}async function Sln(e,t,r,n=Far){const o=[...new Set(e)].map(i=>Eln(i,t));let s;try{return await Bt(WOe(Promise.race(o.map(i=>i.promise.then(a=>s?(a.release(),new Promise(()=>{})):(s=i.accountKey,{accountKey:i.accountKey,lease:a})))),r),n,`Account admission timed out after ${n}ms`)}catch(i){if(r?.aborted)throw i;return}finally{for(const i of o)i.accountKey!==s&&i.cancel()}}var $ar=!1,hce=6e4,Far=9e4,Cln=12e4,kln=250,xln=15e3;function Dy(e,t,r){t<=1||e===r&&(Mh=(Mh+1)%t)}function Uar(e,t){if(!t)return 0;const r=e.findIndex(n=>zQt(n.key,t));return r>=0?r:0}function Aln(e,t){if(e.length<=1)return;const r=Uar(e,t);if(Mh===r)return;const n=e[r],o=Jl.get(n.key);if((!o||!o.coolingUntil||Date.now()>=o.coolingUntil)&&(Mh=r,o?.coolingUntil)){const s=o.coolingUntil;o.coolingUntil=void 0,o.coolingReason=void 0,xy(n.key,s).catch(()=>{}),f.always(`[proxy] home primary account=${n.label} cooling expired, resetting primaryAccountIndex to ${r}`)}}function Bar(e){const t=Jl.get(e);return!!t?.coolingUntil&&Date.now()<t.coolingUntil}function Iln(e,t,r=Date.now()){let n=Par.get(e);if(!n||r>=n.coolingUntil?(n={coolingUntil:t,retriesClaimed:0},Par.set(e,n)):t>n.coolingUntil&&(n.coolingUntil=t),!(n.retriesClaimed>=dce))return n.retriesClaimed+=1,n.retriesClaimed}function Rln(e,t,r=Date.now()){if(t<=r)return 0;if(t-r>Far)return;let n=Dar.get(e);!n||r>=n.coolingUntil?(n={coolingUntil:t,nextAdmissionAt:t},Dar.set(e,n)):t>n.coolingUntil&&(n.coolingUntil=t,n.nextAdmissionAt=Math.max(n.nextAdmissionAt,t));const o=Math.max(r,n.coolingUntil,n.nextAdmissionAt);if(!(o-n.coolingUntil>xln))return n.nextAdmissionAt=o+kln,o-r}async function Mln(e){const t=Date.now()+Cln;for(;Date.now()<t;){const r=e.filter(i=>!Bar(i.key));if(r.length>0)return r;const n=Date.now(),o=e.map(i=>({account:i,state:dl(i.key)})).filter(({state:i})=>i.coolingReason==="transient"&&i.coolingUntil!==void 0&&i.coolingUntil>n).sort((i,a)=>(i.state.coolingUntil??Number.POSITIVE_INFINITY)-(a.state.coolingUntil??Number.POSITIVE_INFINITY))[0];if(!o?.state.coolingUntil)return[];const s=Rln(o.account.key,o.state.coolingUntil,n);if(s===void 0||n+s>t)return[];f.always(`[proxy] all usable accounts are transiently cooling; queueing request for account=${o.account.label} in ${s}ms`),await Gp(s)}return[]}function $i(e,t){if(!e||e<=0)return;const r=e>4102444800?e:e*1e3;return r>t?r:void 0}function VA(e,t){try{const r=t.poolAccounts?Qon(t.poolAccounts.map(o=>{const s=Jl.get(o.key);return{...s?.coolingUntil!==void 0?{coolingUntil:s.coolingUntil}:{},...s?.quota?{quota:s.quota}:{}}})):void 0,n=Xon({...t.upstreamHeaders?{upstreamHeaders:t.upstreamHeaders}:{},context:{quota:t.quota??null,source:t.source,...t.account?{accountLabel:t.account.label}:{},...t.accountType??t.account?.type?{accountType:t.accountType??t.account?.type}:{},...t.servedBy?{servedBy:t.servedBy}:{},...t.attempt!==void 0?{attempt:t.attempt}:{},...t.accountState?.coolingUntil!==void 0?{coolingUntil:t.accountState.coolingUntil}:{},...t.accountState?.coolingReason?{coolingReason:t.accountState.coolingReason}:{},...r?{pool:r}:{}}});e.responseHeaders={...e.responseHeaders??{},...Qar(n)}}catch(r){f.debug(`[proxy] failed to publish limit headers: ${r instanceof Error?r.message:String(r)}`)}}function yF(e,t,r){const n=Math.min(xar,(r&&Gsr[r])??xar);return Math.min(Math.max(e,t+Aar),t+n)}function fce(e,t,r,n=e?.unifiedStatus,o=Oy){if(e&&e.weeklyStatus==="rejected"){const a=$i(e.weeklyResetAt,r)??(t>0?r+t:r+hce);return{reason:"weekly",coolingUntil:yF(a,r,"weekly"),rotateImmediately:!0}}const s=wF(e,o);if(e&&e.sessionStatus==="rejected"&&!s){const a=$i(e.sessionResetAt,r)??(t>0?r+t:r+hce);return{reason:"session",coolingUntil:yF(a,r,"session"),rotateImmediately:!0}}if(n?.trim().toLowerCase()==="rejected"&&!s){const a=t>0?r+t:r+Iar;return{reason:"unified",coolingUntil:yF(a,r,"unified"),rotateImmediately:!0}}const i=t>0?t:hce;return{reason:"transient",coolingUntil:r+Math.max(Aar,Math.min(i,yln)),rotateImmediately:!1}}function gce(e,t){return Math.max(0,Math.round((e-t)/6e4))}function yce(e,t,r,n=Oy){const o=wF(t,n);let s,i;if(t.weeklyStatus==="rejected"&&(s=$i(t.weeklyResetAt,r),i="weekly"),s===void 0&&o&&e.coolingUntil&&(e.coolingReason==="session"||e.coolingReason==="unified")){const l=e.coolingUntil;return e.coolingUntil=void 0,e.coolingReason=void 0,f.always("[proxy] clearing subscription cooldown because Anthropic explicitly permits overage"),{kind:"cleared",coolingUntil:l}}if(s===void 0&&t.sessionStatus==="rejected"&&!o?(s=$i(t.sessionResetAt,r),i="session"):s===void 0&&t.unifiedStatus==="rejected"&&!o&&(s=r+Iar,i="unified"),s===void 0)return null;const a=yF(s,r,i);return!e.coolingUntil||a>e.coolingUntil?(e.coolingUntil=a,e.coolingReason=i,f.always(`[proxy] proactively cooling account (${i}) ~${gce(a,r)}m from success-response quota (status rejected)`),{kind:"cooled",coolingUntil:a,coolingReason:i??"unified"}):null}async function Pln(e){try{const[t,r]=await Promise.all([hle(),AA()]),n=Date.now();for(const o of e){const s=dl(o.key);s.quota||(s.quota=t[o.key]??t[o.label]);const i=r[o.key];i?.coolingUntil>n&&(!s.coolingUntil||i.coolingUntil>s.coolingUntil)&&(s.coolingUntil=i.coolingUntil,s.coolingReason=i.reason)}}catch{}}var Dln=15e3,zar=new Map,vF=null,Oln=4;async function jar(e,t,r,n){if(t.ok===!1)return null;const o=dl(e.key),s=rir(t.usage,{now:r,prior:o.quota??n??null});if(!s)return null;if(s.lastUpdated<(o.quota?.lastUpdated??0))return o.quota??null;o.quota=Ay(o.quota,s);const i=yce(o,s,Date.now());return i?.kind==="cooled"?await Td(e.key,i.coolingUntil,i.coolingReason).catch(()=>{}):i?.kind==="cleared"&&await xy(e.key,i.coolingUntil).catch(()=>{}),await Ry(e.key,s).catch(()=>{}),s}async function qar(e){const t=await Uon(e);return t.ok===!1||rir(t.usage,{now:Date.now(),prior:Jl.get(e.key)?.quota??null})?t:{ok:!1,reason:"parse",error:"usage payload had no recognizable limit windows"}}async function _F(e,t){const r=await HA.run(e,t,qar);r.kind!=="completed"||r.result.ok===!1||await jar(e,r.result,r.startedAt)}async function vce(e={}){const t=Date.now(),r=await eir(e.accountAllowlist),n=e.accountFilter?r.filter(c=>c.label===e.accountFilter||c.key===e.accountFilter):r,o=await hle().catch(()=>({})),s=(c,u,d,m)=>{const h=Jl.get(c.key),g={account:c.label,key:c.key,type:c.type,status:u,quota:d??h?.quota??o[c.key]??o[c.label]??null};return m!==void 0&&(g.error=m),h?.coolingUntil&&h.coolingUntil>Date.now()&&(g.coolingUntil=h.coolingUntil,h.coolingReason&&(g.coolingReason=h.coolingReason)),g};if(e.snapshotOnly)return{fetchedAt:t,snapshot:!0,results:n.map(c=>s(c,"snapshot",null)),refreshMetrics:HA.getMetrics()};const i=new Array(n.length);let a=0;const l=async()=>{for(;;){const c=a++;if(c>=n.length)return;const u=n[c];if(u.type!=="oauth"){i[c]=s(u,"skipped_api_key",null);continue}const d=zar.get(u.key)??0;if(Date.now()-d<Dln){i[c]=s(u,"throttled",null);continue}zar.set(u.key,Date.now());try{const m=await HA.run(u,`manual:${u.key}`,qar,{force:!0});if(m.kind!=="completed"){i[c]=s(u,"throttled",null);continue}const h=m.result;if(h.ok===!1){i[c]=s(u,"error",null,h.error);continue}const g=await jar(u,h,m.startedAt,o[u.key]??o[u.label]??null);if(!g){i[c]=s(u,"error",null,"usage payload had no recognizable limit windows");continue}i[c]=s(u,"refreshed",g)}catch(m){i[c]=s(u,"error",null,m instanceof Error?m.message:String(m))}}};return await Promise.all(Array.from({length:Math.min(Oln,n.length||1)},()=>l())),{fetchedAt:t,snapshot:!1,results:i,refreshMetrics:HA.getMetrics()}}function _ce(){const e=(process.env.NEUROLINK_PROXY_QUOTA_ROUTING??"").toLowerCase();return e!=="off"&&e!=="false"&&e!=="0"}function wce(){const e=Number(process.env.NEUROLINK_PROXY_SESSION_SOFT_LIMIT??"");return Number.isFinite(e)&&e>0&&e<=1?e:.97}function WA(){const e=Number(process.env.NEUROLINK_PROXY_SESSION_RESET_TOLERANCE_MS??"");return Number.isInteger(e)&&e>0?e:900*1e3}var Oy="auto";function bce(e){e!==void 0&&(Oy=e)}function Nln(){return Oy}function wF(e,t=Oy){return t==="never"?!1:Vsr(e)}var Lln=4;function bF(e){return e.toLowerCase().replace(/[^a-z0-9]/g,"")}function $ln(e){const t=bF(e);return t.startsWith("claude")?t.slice(6):t}function Fln(e,t,r){if(e.scopeModelId&&bF(H$(e.scopeModelId))===r)return Number.MAX_SAFE_INTEGER;if(!e.scopeModel)return null;const n=$ln(e.scopeModel);return n.length<Lln||!t.includes(n)?null:n.length}function Gar(e,t){return t.updatedAt??e.windowsUpdatedAt??e.lastUpdated}function Har(e,t,r=Date.now()){if(!e?.windows?.length||!t)return null;const n=bF(t);if(!n)return null;const o=bF(H$(t));let s=null,i=-1,a=-1;for(const l of e.windows){if(r-Gar(e,l)>Mar)continue;const c=Fln(l,n,o);if(c===null)continue;const u=Gar(e,l);(c>i||c===i&&u>a)&&(s=l,i=c,a=u)}return s}function Uln(e,t,r=Date.now(),n=Oy){if(!t||e.length===0)return{eligible:e,exhaustion:null};const o=[],s=[];let i;for(const l of e){const c=Jl.get(l.key)?.quota,u=Har(c,t,r),d=u?$i(u.resetsAt,r):void 0;if(!(u!==null&&d!==void 0&&((u.status??"").trim().toLowerCase()==="rejected"||(u.used??0)>=1)&&!wF(c,n))||!u){o.push(l);continue}s.push({label:l.label,window:u}),i??=c?.overageDisabledReason}if(o.length>0||s.length===0)return{eligible:o,exhaustion:null};const a=Math.min(...s.map(l=>$i(l.window.resetsAt,r)??Number.POSITIVE_INFINITY));return{eligible:o,exhaustion:{model:t,scopeModel:s[0]?.window.scopeModel??H$(t),earliestResetMs:a,accounts:s.map(l=>l.label),...i?{overageDisabledReason:i}:{}}}}function TF(e,t,r,n,o,s=Oy){const i=Jl.get(e),a=i?.quota,l=a&&Number.isFinite(a.lastUpdated)?a.lastUpdated:null,c=l===null?null:Math.max(0,t-l),u=HA.getState(e),d=c!==null&&c>Mar,m=G=>G.trim().toLowerCase(),h=Vsr(a),g=[a?.unifiedStatus,a?.sessionStatus,a?.weeklyStatus].filter(G=>!!G?.trim()),y=d&&!!a&&!h&&g.some(G=>m(G)!=="allowed"),v=a?d?y?"refresh_due":"stale_known":"fresh":"unknown",_=y?void 0:a,b=!!i?.coolingUntil&&t<i.coolingUntil,T=$i(_?.weeklyResetAt,t),k=$i(_?.sessionResetAt,t),x=k!==void 0,I=T!==void 0,M=_?x?_.sessionUsed??0:0:null,R=_?I?_.weeklyUsed??null:0:null,A=_?x?_.sessionStatus??"unknown":"allowed":null,P=_?I?_.weeklyStatus??"unknown":"allowed":null,L=wF(_,s),N=!L&&(A==="rejected"||A==="throttled"||P==="rejected"||P==="throttled"||_?.unifiedStatus?.trim().toLowerCase()==="rejected"||x&&(M??0)>=1||I&&(R??0)>=1),D=!N&&!L&&x&&(M??0)>=r,O=N||D,F=Har(_,o,t),$=F?$i(F.resetsAt,t):void 0,B=$!==void 0,z=F?B?F.used:0:null,j=F?B?F.status??"unknown":"allowed":null,K=!d&&B&&(z??0)>=r;return{usable:!b&&!N&&(j!=="rejected"||L),saturated:O,scopedModel:F?.scopeModel??null,scopedStatus:j,scopedUsed:z,scopedReset:$??Number.POSITIVE_INFINITY,scopedUsedForSort:z??-1,scopedSaturated:K,hasQuota:!!a,quotaEvidenceRank:v==="fresh"||v==="stale_known"?0:v==="refresh_due"?1:2,quotaStale:d,quotaFreshness:v,refreshNeeded:v==="unknown"||v==="refresh_due",refreshReason:v==="unknown"?"startup_unknown":v==="refresh_due"?"ambiguous_snapshot":null,refreshInFlight:u.inFlight,lastRefreshAttemptAt:u.lastAttemptAt??null,lastRefreshSuccessAt:u.lastSuccessAt??null,nextRefreshEligibleAt:u.nextEligibleAt??null,saturationKind:N?"hard":D?"soft":"none",softLimitOverrideReason:L&&x&&(M??0)>=r?"overage":null,quotaLastUpdated:l,quotaAgeMs:c,coolingActive:b,coolingReason:i?.coolingReason??null,coolingUntil:i?.coolingUntil??0,unifiedStatus:_?.unifiedStatus??null,fallbackStatus:_?.fallbackStatus??null,upgradePaths:_?.upgradePaths??null,overageEligible:L,overageStatus:_?.overageStatus??null,sessionStatus:A,sessionUsed:M,sessionResetBucket:x?Math.floor(k/n):Number.POSITIVE_INFINITY,sessionReset:k??Number.POSITIVE_INFINITY,weeklyStatus:P,weeklyReset:T??Number.POSITIVE_INFINITY,weeklyUsed:R,weeklyUsedForSort:R??-1}}function Var(e,t,r,n){const o=r.get(e.key),s=r.get(t.key);if(!o||!s)return[0,"insertion_order"];if(o.usable!==s.usable)return[o.usable?-1:1,"availability"];if(!o.usable&&!s.usable){const i=o.coolingUntil||Number.POSITIVE_INFINITY,a=s.coolingUntil||Number.POSITIVE_INFINITY;return[i===a?0:i-a,i===a?"insertion_order":"cooldown_recovery"]}if(o.quotaEvidenceRank!==s.quotaEvidenceRank)return[o.quotaEvidenceRank-s.quotaEvidenceRank,"quota_evidence"];if(o.saturated!==s.saturated)return[o.saturated?1:-1,"session_headroom"];if(o.scopedSaturated!==s.scopedSaturated)return[o.scopedSaturated?1:-1,"scoped_headroom"];if(o.saturated&&s.saturated){if(o.sessionResetBucket!==s.sessionResetBucket)return[o.sessionResetBucket-s.sessionResetBucket,"session_reset"];if(o.weeklyReset!==s.weeklyReset)return[o.weeklyReset-s.weeklyReset,"weekly_reset"]}else{if(o.weeklyReset!==s.weeklyReset)return[o.weeklyReset-s.weeklyReset,"weekly_reset"];if(o.sessionResetBucket!==s.sessionResetBucket)return[o.sessionResetBucket-s.sessionResetBucket,"session_reset"]}return o.scopedUsed!==null&&s.scopedUsed!==null&&o.scopedUsedForSort!==s.scopedUsedForSort?[s.scopedUsedForSort-o.scopedUsedForSort,"scoped_utilization"]:o.weeklyUsedForSort!==s.weeklyUsedForSort?[s.weeklyUsedForSort-o.weeklyUsedForSort,"weekly_utilization"]:n&&e.key===n!=(t.key===n)?[e.key===n?-1:1,"configured_primary"]:[0,"insertion_order"]}function Bln(e,t,r,n,o,s){const i=new Map(e.map(a=>[a.key,TF(a.key,t,n,o,s)]));return{orderedAccounts:[...e].sort((a,l)=>Var(a,l,i,r)[0]),metricsByKey:i}}function zln(e,t,r,n){for(const u of e){if(u.type!=="oauth")continue;const d=n?.get(u.key)??TF(u.key,Date.now(),r,WA());d.quotaFreshness==="unknown"?_F(u,`startup-unknown:${u.key}`).catch(m=>{f.debug(`[proxy] background quota discovery failed account=${u.label}: ${Sd(m)}`)}):d.quotaFreshness==="refresh_due"&&_F(u,`ambiguous:${d.quotaLastUpdated??0}`).catch(m=>{f.debug(`[proxy] ambiguous quota refresh failed account=${u.label}: ${Sd(m)}`)})}const o=t[0],s=t[1];if(!o||!s||s.type!=="oauth")return;const i=Jl.get(o.key)?.quota;if(!i)return;const a=Math.max(0,r-.05);if(!((i.sessionUsed??0)>=a||(i.weeklyUsed??0)>=.9))return;const c=["handoff",o.key,i.sessionResetAt??0,i.weeklyResetAt??0,s.key].join(":");_F(s,c).catch(u=>{f.debug(`[proxy] quota handoff prewarm failed account=${s.label}: ${Sd(u)}`)})}function jln(e,t,r,n){!t||t.type!=="oauth"||TF(t.key,Date.now(),n,WA()).quotaFreshness==="fresh"||_F(t,`hard-handoff:${e.key}:${r}:${t.key}`).catch(s=>{f.debug(`[proxy] hard-handoff quota refresh failed account=${t.label}: ${Sd(s)}`)})}function qln(e){const{accounts:t,orderedAccounts:r,metricsByKey:n,evaluatedAt:o,strategy:s,primaryKey:i,quotaRoutingEnabled:a,quotaOrdered:l,sessionSoftLimit:c,sessionResetToleranceMs:u,rotationOffset:d}=e,m=new Map(t.map((b,T)=>[b.key,T])),h=!!i&&t.some(b=>b.key===i),g=[];for(const b of r){const T=n.get(b.key);if(!T){f.warn(`[proxy] routing evidence omitted because metrics are missing for account=${b.label}`);return}g.push({account:b.label,accountType:b.type,sourceIndex:m.get(b.key)??g.length,rank:g.length,configuredPrimary:!!i&&b.key===i,usable:T.usable,saturated:T.saturated,quotaObserved:T.hasQuota,quotaStale:T.quotaStale,quotaFreshness:T.quotaFreshness,refreshNeeded:T.refreshNeeded,refreshReason:T.refreshReason,refreshInFlight:T.refreshInFlight,lastRefreshAttemptAt:T.lastRefreshAttemptAt,lastRefreshSuccessAt:T.lastRefreshSuccessAt,nextRefreshEligibleAt:T.nextRefreshEligibleAt,saturationKind:T.saturationKind,softLimitOverrideReason:T.softLimitOverrideReason,quotaLastUpdated:T.quotaLastUpdated,quotaAgeMs:T.quotaAgeMs,coolingActive:T.coolingActive,coolingReason:T.coolingReason,coolingUntil:T.coolingUntil>0&&Number.isFinite(T.coolingUntil)?T.coolingUntil:null,unifiedStatus:T.unifiedStatus,fallbackStatus:T.fallbackStatus,upgradePaths:T.upgradePaths,overageEligible:T.overageEligible,overageStatus:T.overageStatus,sessionStatus:T.sessionStatus,sessionUsed:T.sessionUsed,sessionResetAt:Number.isFinite(T.sessionReset)?T.sessionReset:null,sessionResetBucket:Number.isFinite(T.sessionResetBucket)?T.sessionResetBucket:null,weeklyStatus:T.weeklyStatus,weeklyUsed:T.weeklyUsed,weeklyResetAt:Number.isFinite(T.weeklyReset)?T.weeklyReset:null,scopedModel:T.scopedModel,scopedStatus:T.scopedStatus,scopedUsed:T.scopedUsed,scopedResetAt:Number.isFinite(T.scopedReset)?T.scopedReset:null})}const y=r[0];let v,_;return r.length===1?(v="single_account",_="single_account"):l?(v="quota",_=Var(r[0],r[1],n,i)[1]):s==="round-robin"?(v="round_robin",_="round_robin"):(v="primary",_=h&&y?.key===i?"configured_primary":"insertion_order"),{schemaVersion:1,evaluatedAt:new Date(o).toISOString(),strategy:s,mode:v,selectionReason:_,quotaRoutingEnabled:a,quotaInputsUsed:l,sessionSoftLimit:c,sessionResetToleranceMs:u,configuredPrimaryAccount:i??null,configuredPrimaryMatched:h,rotationOffset:d,initialAccount:y?.label??"",candidates:g}}function Gln(e){const{enabledAccounts:t,accountStrategy:r,primaryAccountKey:n,quotaRoutingEnabled:o,sessionSoftLimit:s,sessionResetToleranceMs:i,requestedModel:a,setRoutingDecision:l}=e;let c=[...t];const u=Date.now();let d,m=0;const h=r==="fill-first"&&c.length>1&&o;if(!h&&r==="fill-first"&&Aln(t,n),h){const y=Bln(t,u,n,s,i,a);c=y.orderedAccounts,d=y.metricsByKey,f.shouldLog("debug")&&f.debug(`[proxy] quota-ordered fill sequence: ${c.map(v=>v.label).join(" \u2192 ")}`)}else{if(r==="round-robin"&&c.length!==Sar&&(Mh=Uar(c,n),Sar=c.length),c.length>1&&(m=Mh%c.length,r==="round-robin"&&(Mh=(Mh+1)%c.length),m>0)){const y=c.splice(0,m);c.push(...y)}d=new Map(t.map(y=>[y.key,TF(y.key,u,s,i,a)]))}const g=qln({accounts:t,orderedAccounts:c,metricsByKey:d,evaluatedAt:u,strategy:r,primaryKey:n,quotaRoutingEnabled:o,quotaOrdered:h,sessionSoftLimit:s,sessionResetToleranceMs:i,rotationOffset:m});return g&&l(g),{orderedAccounts:c,metricsByKey:d}}var EF=new Map,Hln=300*1e3,Vln=new Set(["accept","accept-encoding","accept-language","anthropic-beta","anthropic-dangerous-direct-browser-access","anthropic-version","sec-fetch-mode","user-agent","x-app","x-stainless-arch","x-stainless-lang","x-stainless-os","x-stainless-package-version","x-stainless-retry-count","x-stainless-runtime","x-stainless-runtime-version","x-stainless-timeout","x-subscription-tier"]),Wln=["oauth-2025-04-20","claude-code-20250219","fine-grained-tool-streaming-2025-05-14"];function SF(e){return e.replace(/[^a-zA-Z0-9._@-]/g,"_")}function War(e){return St(Wa(),".neurolink","header-snapshots",`anthropic_${SF(e)}.json`)}function Kln(e,t){if(t?.headers)for(const[r,n]of Object.entries(t.headers)){const o=r.toLowerCase();typeof n=="string"&&!e[o]&&!hF.has(o)&&o!=="authorization"&&o!=="x-api-key"&&o!=="x-claude-code-session-id"&&(e[o]=n)}}async function Jln(e){try{const t=SF(e),r=EF.get(t);if(r&&Date.now()-r.loadedAt<Hln)return r.snapshot;const n=War(e);try{await jP(n)}catch{return null}const o=JSON.parse(await Kr(n,"utf8"));if(!o||typeof o!="object")return null;const s={accountKey:"accountKey"in o&&typeof o.accountKey=="string"?o.accountKey:`anthropic:${e}`,capturedAt:"capturedAt"in o&&typeof o.capturedAt=="string"?o.capturedAt:new Date(0).toISOString(),source:"claude-code",headers:"headers"in o&&o.headers?o.headers:{},...o.body?{body:o.body}:{}};return Object.keys(s.headers).length===0&&Object.keys(s.body??{}).length===0?null:(EF.set(t,{snapshot:s,loadedAt:Date.now()}),s)}catch{return null}}function Yln(e,t){const r={...t??{}};for(const[n,o]of Object.entries(e)){const s=n.toLowerCase();typeof o=="string"&&Vln.has(s)&&!hF.has(s)&&s!=="authorization"&&s!=="x-api-key"&&s!=="x-claude-code-session-id"&&(r[s]=o)}return r}function Kar(e){if(!e||typeof e!="object")return;const t=e,r=Hxt(t.metadata?.user_id),n=Array.isArray(t.system)?t.system:typeof t.system=="string"?[{type:"text",text:t.system}]:[],o=n.find(i=>typeof i?.text=="string"&&i.text.includes("x-anthropic-billing-header"))?.text,s=n.find(i=>typeof i?.text=="string"&&i.text.includes("Claude Agent SDK"))?.text;if(!(!r&&!o&&!s))return{...r?{metadataUserId:r.metadataUserId}:{},...r?{sessionId:r.sessionId}:{},...o?{billingHeader:o}:{},...s?{agentBlock:s}:{}}}function Jar(e,t){return typeof e["x-claude-code-session-id"]=="string"||e["user-agent"]?.startsWith("claude-cli/")||!!t?.metadataUserId||!!t?.billingHeader||!!t?.agentBlock}function Zln(e,t){return e?JSON.stringify(e.headers??{})===JSON.stringify(t.headers??{})&&JSON.stringify(e.body??{})===JSON.stringify(t.body??{}):!1}async function Xln(e,t){const r=War(e);await il(r,t,384),EF.set(SF(e),{snapshot:t,loadedAt:Date.now()})}async function Qln(e,t,r,n){const o=await Jln(e);let s;try{s=JSON.parse(n)}catch{return o}const i=Kar(s);if(!Jar(r,i))return o;const a={accountKey:t,capturedAt:new Date().toISOString(),source:"claude-code",headers:Yln(r,o?.headers),body:{...o?.body??{},...i??{},...typeof r["x-claude-code-session-id"]=="string"?{sessionId:r["x-claude-code-session-id"]}:{}}};if(Zln(o,a))return o;try{await Xln(e,a)}catch(l){f.warn("[proxy] failed to persist Claude snapshot",{accountLabel:e,error:l instanceof Error?l.message:String(l)}),EF.set(SF(e),{snapshot:a,loadedAt:Date.now()})}return a}function Tce(e){const t={};if(!e||typeof e!="object")return t;const r=e;if(typeof r.model=="string"&&(t.responseModel=r.model),typeof r.stop_reason=="string"&&(t.finishReason=r.stop_reason),typeof r.stop_sequence=="string"&&(t.stopSequence=r.stop_sequence),Array.isArray(r.content)){const n=r.content.filter(o=>!!o&&typeof o=="object"&&o.type==="tool_use").map(o=>String(o.name??"")).filter(o=>o.length>0);n.length>0&&(t.toolCalls=n)}return t}function Yar(e){const t={};e.model&&(t.responseModel=e.model),e.stopReason&&(t.finishReason=e.stopReason),e.stopSequence&&(t.stopSequence=e.stopSequence);const r=(e.contentBlocks??[]).filter(n=>n.type==="tool_use").map(n=>String(n.toolName??"")).filter(n=>n.length>0);return r.length>0&&(t.toolCalls=r),t}function ecn(e,t,r,n,o){try{const s=JSON.parse(e),i={type:"text",text:r?.body?.agentBlock||"You are a Claude agent, built on Anthropic's Claude Agent SDK."};if(s.system){if(typeof s.system=="string"&&(s.system=[{type:"text",text:s.system}]),Array.isArray(s.system)){const c=s.system.findIndex(h=>typeof h.text=="string"&&h.text.includes("x-anthropic-billing-header")),u=s.system.findIndex(h=>typeof h.text=="string"&&h.text.includes("Claude Agent SDK")),d={type:"text",text:JO(s.system[c]?.text??r?.body?.billingHeader)};if(n&&u>=0)c<0&&s.system.unshift(d);else{const h=[c,u].filter(g=>g>=0).sort((g,y)=>y-g);for(const g of h)s.system.splice(g,1);s.system.length>0&&cAt(s,s.system),s.system=[d,i]}}}else{const c={type:"text",text:JO(r?.body?.billingHeader)};s.system=[c,i]}const a=t.substring(0,Math.min(20,t.length)),l=Vxt(a,{existingUserId:s.metadata?.user_id??r?.body?.metadataUserId,preferredSessionId:o??r?.body?.sessionId});return s.metadata={...s.metadata,user_id:l.metadataUserId},{bodyStr:JSON.stringify(s),sessionId:l.sessionId}}catch{return{bodyStr:e}}}async function tcn(e,t){if(!e.oauth?.accessToken)return;let r=e.oauth.accessToken,n=e.oauth.refreshToken,o=e.oauth.expiresAt;const s=e.email?.trim()||"legacy-default",i=o?o<Date.now():!1,a=()=>({key:tA,label:s,token:r,refreshToken:n,expiresAt:o,type:"oauth",persistTarget:{credPath:t}});if(!i)return a();const l=dl(tA);if(l.permanentlyDisabled)return;const c=(await AA())[tA];if(c?.coolingUntil>Date.now()&&(!l.coolingUntil||c.coolingUntil>l.coolingUntil)&&(l.coolingUntil=c.coolingUntil,l.coolingReason=c.reason),l.coolingReason==="auth"&&l.coolingUntil&&l.coolingUntil>Date.now())return a();if(!n){f.always("[proxy] skipping legacy account (expired, no refresh token)"),await qp(a(),l,"missing_refresh_token");return}const u={token:r,refreshToken:n,expiresAt:o,label:s},d=await Xsr(u);if(!d.success){if(My(d)){await qp(a(),l,"refresh_invalid");return}const m=await xF(a(),l);return f.always(`[proxy] legacy refresh temporarily unavailable (${d.status??"network"}); cooling until ${new Date(m).toISOString()}`),a()}return r=u.token,n=u.refreshToken,o=u.expiresAt,await Y$(t,u),await AF(a(),l),f.always("[proxy] refreshed legacy account at startup"),a()}async function rcn(e){const{ctx:t,body:r,route:n,modelRouter:o,tracer:s,requestStartTime:i,logProxyBody:a}=e;s?.setMode("full");const l=wle(r),c=gb({provider:n.provider,model:n.model},o?.getFallbackChain()??[],r.model,l,o?.isAutoFallbackEnabled?.()??!1);Zar(a,"translated_request",c);const u=c.attempts;if(r.stream)return Mle({ctx:t,format:"claude",requestModel:r.model,parsed:l,attempts:u,tracer:s,requestStartTime:i});try{return await Ple({ctx:t,format:"claude",requestModel:r.model,parsed:l,attempts:u,tracer:s,requestStartTime:i,terminalFailureStatus:502})}catch(d){const m=d instanceof Error?d.message:"unknown error";f.error(`[claude-proxy] Translated generation failed for ${r.model}: ${m}`);const h=ul(502,`Generation failed: ${m}`),g=JSON.stringify(h);return a({phase:"client_response",headers:{"content-type":"application/json"},body:g,bodySize:Buffer.byteLength(g,"utf8"),contentType:"application/json",account:"translation",accountType:"translation",responseStatus:502,durationMs:Date.now()-i}),h}}function Zar(e,t,r){e({phase:"routing_decision",contentType:"application/json",body:{stage:t,attempts:r.attempts}})}async function ncn(e){const{ctx:t,body:r,clientRequestBody:n,tracer:o,requestStartTime:s,logProxyBody:i,logFinalRequest:a}=e;o?.setMode("passthrough-cli");const l=n,c=Array.isArray(r.tools)?r.tools.length:0,u={};for(const[g,y]of Object.entries(t.headers))!hF.has(g.toLowerCase())&&y&&(u[g]=y);u["content-type"]||(u["content-type"]="application/json");const d=o?.startUpstreamAttempt({account:"passthrough",attempt:1,polyfillHeaders:!1,polyfillBody:!1,upstreamUrl:"https://api.anthropic.com/v1/messages?beta=true"});o?.logUpstreamRequestHeaders(u),o?.logUpstreamRequestBody(l),i({phase:"upstream_request",headers:u,body:l,bodySize:Buffer.byteLength(l,"utf8"),contentType:u["content-type"]??"application/json",account:"passthrough",accountType:"passthrough",attempt:1,metadata:{upstreamMethod:"POST",upstreamUrl:"https://api.anthropic.com/v1/messages?beta=true"}}),Ty("passthrough","passthrough");let m;try{m=await pce("https://api.anthropic.com/v1/messages?beta=true",{method:"POST",headers:u,body:l,signal:AbortSignal.timeout(GA)})}catch(g){const y=g instanceof Error?g.message:String(g);$r("passthrough","passthrough",502),o?.setError("network_error",y),d?.end(),o?.end(502,Date.now()-s),a(502,"passthrough","passthrough","network_error",y);const v=ul(502,`Passthrough fetch failed: ${y}`),_=JSON.stringify(v);return i({phase:"client_response",headers:{"content-type":"application/json"},body:_,bodySize:Buffer.byteLength(_,"utf8"),contentType:"application/json",account:"passthrough",accountType:"passthrough",attempt:1,responseStatus:502,durationMs:Date.now()-s}),v}const h={};m.headers.forEach((g,y)=>{h[y]=g}),o?.logUpstreamResponseHeaders(h);{const g=nb(m.headers,{model:r.model});VA(t,{upstreamHeaders:m.headers,quota:g,source:g?"live":"none",accountType:"passthrough",servedBy:"anthropic",attempt:1})}if(!m.ok){const g=await m.text();$r("passthrough","passthrough",m.status,m.status===429?"quota":void 0),o?.logUpstreamResponseBody(g),i({phase:"upstream_response",headers:h,body:g,bodySize:Buffer.byteLength(g,"utf8"),contentType:h["content-type"]??"application/json",account:"passthrough",accountType:"passthrough",attempt:1,responseStatus:m.status,durationMs:Date.now()-s}),i({phase:"client_response",headers:h,body:g,bodySize:Buffer.byteLength(g,"utf8"),contentType:h["content-type"]??"application/json",account:"passthrough",accountType:"passthrough",attempt:1,responseStatus:m.status,durationMs:Date.now()-s}),d?.end(),o?.setError("api_error",g.slice(0,500)),o?.end(m.status,Date.now()-s),a(m.status,"passthrough","passthrough",m.status===429?"rate_limit_error":"api_error",g);try{return JSON.parse(g)}catch{return ul(m.status,g)}}return r.stream&&m.body?scn({ctx:t,body:r,bodyStr:l,response:m,tracer:o,requestStartTime:s,toolCount:c,upstreamSpan:d,upstreamResponseHeaders:h,logProxyBody:i,logFinalRequest:a}):icn({ctx:t,body:r,bodyStr:l,response:m,tracer:o,requestStartTime:s,toolCount:c,upstreamSpan:d,upstreamResponseHeaders:h,logProxyBody:i,logFinalRequest:a})}function ocn(e){const t=e.getReader(),r=aar();let n=!1;return{stream:new ReadableStream({async pull(s){if(!n)try{const{done:i,value:a}=await t.read();if(n)return;if(i){n=!0,r.complete(),s.close();return}s.enqueue(a)}catch(i){n=!0;const a=i instanceof Error?i.message:String(i);r.fail(a),s.error(i)}},cancel(s){return n=!0,r.cancel(),t.cancel(s)}}),outcome:r.outcome}}async function scn(e){const{ctx:t,bodyStr:r,response:n,tracer:o,requestStartTime:s,upstreamSpan:i,upstreamResponseHeaders:a,logProxyBody:l,logFinalRequest:c}=e,u={...a},{stream:d,capture:m}=Oir(),h=n.body;if(!h)throw $r("passthrough","passthrough",502),new Error("Expected passthrough stream response body");const g=ocn(h);let y=g.stream,v=!1;const _=(T,k,x,I)=>v?!1:(v=!0,k==="stream_error"&&$r("passthrough","passthrough",T),c(T,"passthrough","passthrough",k,x,I),!0);if(o)try{const{stream:T,telemetry:k}=lF({captureRawText:!0});y=y.pipeThrough(T);const x=o,I=i,M=n,R=r.length;Promise.all([k,m,g.outcome]).then(([A,P,L])=>{const N=cF(L,A.streamErrorMessage),D=Ph(N);x.setUsage({inputTokens:A.usage.inputTokens,outputTokens:A.usage.outputTokens,cacheCreationTokens:A.usage.cacheCreationInputTokens,cacheReadTokens:A.usage.cacheReadInputTokens}),x.logStreamEvents(A.events),x.setResponseInfo(Yar(A));const O=parseFloat(M.headers.get("anthropic-ratelimit-unified-5h-utilization")??""),F=parseFloat(M.headers.get("anthropic-ratelimit-unified-7d-utilization")??""),$={inputTokens:A.usage.inputTokens,outputTokens:A.usage.outputTokens,cacheCreationTokens:A.usage.cacheCreationInputTokens,cacheReadTokens:A.usage.cacheReadInputTokens};isNaN(O)||($.rateLimitAfter5h=O),isNaN(F)||($.rateLimitAfter7d=F),(!isNaN(O)||!isNaN(F))&&x.setUsage($),x.logUpstreamResponseBody(A.rawText??""),x.recordMetrics(),x.recordBodySizes(R,A.totalBytesReceived),I?.end(),D&&x.setError(D.errorType,D.message),x.end(D?.status??n.status,Date.now()-s),_(D?.status??n.status,D?.errorType,D?.message,{inputTokens:A.usage.inputTokens,outputTokens:A.usage.outputTokens,cacheCreationTokens:A.usage.cacheCreationInputTokens,cacheReadTokens:A.usage.cacheReadInputTokens}),l({phase:"upstream_response",headers:u,body:A.rawText??"",bodySize:A.totalBytesReceived,contentType:u["content-type"]??"text/event-stream",account:"passthrough",accountType:"passthrough",attempt:1,responseStatus:200,durationMs:Date.now()-s}),l({phase:"client_response",headers:u,body:P.text,bodySize:P.totalBytes,contentType:u["content-type"]??"text/event-stream",account:"passthrough",accountType:"passthrough",attempt:1,responseStatus:200,durationMs:Date.now()-s})}).catch(A=>{if(v)return;const P=A instanceof Error?A.message:String(A);x.setError("stream_telemetry_error",P),I?.end(),x.end(500,Date.now()-s),_(500,"stream_telemetry_error",P)})}catch{g.outcome.then(T=>{const k=Ph(T);i?.end(),k&&o.setError(k.errorType,k.message),o.end(k?.status??n.status,Date.now()-s),_(k?.status??n.status,k?.errorType,k?.message)})}else try{const{stream:T,telemetry:k}=lF({captureRawText:!0});y=y.pipeThrough(T),Promise.all([k,m,g.outcome]).then(([x,I,M])=>{const R=cF(M,x.streamErrorMessage),A=Ph(R);_(A?.status??n.status,A?.errorType,A?.message,{inputTokens:x.usage.inputTokens,outputTokens:x.usage.outputTokens,cacheCreationTokens:x.usage.cacheCreationInputTokens,cacheReadTokens:x.usage.cacheReadInputTokens}),l({phase:"upstream_response",headers:u,body:x.rawText??"",bodySize:x.totalBytesReceived,contentType:u["content-type"]??"text/event-stream",account:"passthrough",accountType:"passthrough",attempt:1,responseStatus:n.status,durationMs:Date.now()-s}),l({phase:"client_response",headers:u,body:I.text,bodySize:I.totalBytes,contentType:u["content-type"]??"text/event-stream",account:"passthrough",accountType:"passthrough",attempt:1,responseStatus:n.status,durationMs:Date.now()-s})}).catch(x=>{v||_(500,"stream_telemetry_error",x instanceof Error?x.message:String(x))})}catch{g.outcome.then(T=>{const k=Ph(T);_(k?.status??n.status,k?.errorType,k?.message)})}const b=y.pipeThrough(d);return new Response(b,{status:n.status,headers:{...u,...t.responseHeaders??{}}})}async function icn(e){const{bodyStr:t,response:r,tracer:n,requestStartTime:o,upstreamSpan:s,upstreamResponseHeaders:i,logProxyBody:a,logFinalRequest:l}=e,c=await r.text();n?.logUpstreamResponseBody(c),a({phase:"upstream_response",headers:i,body:c,bodySize:Buffer.byteLength(c,"utf8"),contentType:i["content-type"]??"application/json",account:"passthrough",accountType:"passthrough",attempt:1,responseStatus:r.status,durationMs:Date.now()-o}),a({phase:"client_response",headers:i,body:c,bodySize:Buffer.byteLength(c,"utf8"),contentType:i["content-type"]??"application/json",account:"passthrough",accountType:"passthrough",attempt:1,responseStatus:r.status,durationMs:Date.now()-o});const u=JSON.parse(c);if(n&&u&&typeof u=="object"){const d=u.usage;if(d){n.setUsage({inputTokens:d.input_tokens??0,outputTokens:d.output_tokens??0,cacheCreationTokens:d.cache_creation_input_tokens??0,cacheReadTokens:d.cache_read_input_tokens??0});const h=parseFloat(r.headers.get("anthropic-ratelimit-unified-5h-utilization")??""),g=parseFloat(r.headers.get("anthropic-ratelimit-unified-7d-utilization")??"");if(!isNaN(h)||!isNaN(g)){const y={inputTokens:d.input_tokens??0,outputTokens:d.output_tokens??0,cacheCreationTokens:d.cache_creation_input_tokens??0,cacheReadTokens:d.cache_read_input_tokens??0};isNaN(h)||(y.rateLimitAfter5h=h),isNaN(g)||(y.rateLimitAfter7d=g),n.setUsage(y)}}n.setResponseInfo(Tce(u)),n.recordMetrics();const m=JSON.stringify(u);n.recordBodySizes(t.length,m.length),s?.end(),n.end(r.status,Date.now()-o),l(r.status,"passthrough","passthrough",void 0,void 0,{inputTokens:d?.input_tokens,outputTokens:d?.output_tokens,cacheCreationTokens:d?.cache_creation_input_tokens,cacheReadTokens:d?.cache_read_input_tokens})}else s?.end(),n?.end(r.status,Date.now()-o),l(r.status,"passthrough","passthrough");return u}async function acn(e){const t=ib();if(!t)return{accounts:e.accounts};if(e.accounts.length===0)return{accounts:e.accounts};const r=Date.now(),n=await Promise.all(e.accounts.map(async d=>{const m=dl(d.key).quota,h=$i(m?.sessionResetAt,r)??null,g=$i(m?.weeklyResetAt,r)??null,y=await iae(t.grantId,d.key,h,g);return{accountKey:d.key,sessionUsed:m?.sessionUsed??null,weeklyUsed:m?.weeklyUsed??null,sessionResetAt:h,weeklyResetAt:g,borrowedSessionFraction:y.sessionFraction,borrowedWeeklyFraction:y.weeklyFraction}})),o=await eae(t.grantId);if(!o)return{accounts:e.accounts};const s=await aae(t.grantId,Kle(o.gates,n).inScope),i=Jle(o,n,r,s),a=new Set(i.allowed),l=e.accounts.filter(d=>a.has(d.key));if(l.length>0)return{accounts:l};const c=Yle(i.excluded),u=pb(c,{status:ran(c),grant:o,retryAfterSeconds:elr(n,r)});return f.always(`[proxy] share ${t.peerLabel} withheld: ${c} (${i.excluded.length} accounts)`),{accounts:[],refusal:{status:u.status,message:u.body.error.message,errorType:u.body.error.type,responseHeaders:u.headers}}}async function lcn(e){const t=[],r=[];for(const n of e){const o=await Hin(n.key);if(!o){t.push(n);continue}if(!Oin(o)){t.push(n);continue}f.always(`[proxy] withholding leased account=${n.label}: ${o.reason}`),r.push({label:n.label,reason:o.reason})}return{accounts:t,withheld:r}}async function ccn(e,t){const r=[],n=[],o=Date.now();for(const s of e){const i=await Wle(s.key);if(!i){r.push(s);continue}const a=i.lease.gates;if(!oan(a.models,t)){f.always(`[proxy] leased account=${s.label} does not cover model ${Xn(t??"unknown")}`),n.push({label:s.label,reason:"model_not_allowed"});continue}if(a.schedule&&!nan(a.schedule,o)){f.always(`[proxy] leased account=${s.label} is outside its allowed hours`),n.push({label:s.label,reason:"out_of_window"});continue}const l=dl(s.key).quota,c=$i(l?.sessionResetAt,o)??null,u=$i(l?.weeklyResetAt,o)??null,d=await iae(i.grantId,s.key,c,u),m={accountKey:s.key,sessionUsed:l?.sessionUsed??null,weeklyUsed:l?.weeklyUsed??null,sessionResetAt:c,weeklyResetAt:u,borrowedSessionFraction:d.sessionFraction,borrowedWeeklyFraction:d.weeklyFraction},h=await aae(i.grantId,[m]),{accounts:g,...y}=a,v=Jle(ucn(i,y),[m],o,h);if(v.allowed.length===0){const _=Yle(v.excluded);f.always(`[proxy] withholding leased account=${s.label}: ${_}`),n.push({label:s.label,reason:_});continue}r.push(s)}return{accounts:r,withheld:n}}function ucn(e,t){const r=e.lease.entitlementSnapshot;return{schemaVersion:1,id:e.grantId,peerLabel:e.lease.peerLabel,tokenHash:"",tokenSalt:"",level:"complete",state:"active",entitlement:r==="unlimited"?{ledger:"unlimited"}:{ledger:"coins",coins:r},gates:t,createdAt:e.lease.issuedAt,updatedAt:e.lease.issuedAt}}function dcn(e,t,r){const n=Date.now(),o=i=>{XQr({grantId:i,accountKey:e,sessionBefore:t?.sessionUsed??null,sessionAfter:r.sessionUsed,sessionResetAt:$i(r.sessionResetAt,n)??null,weeklyBefore:t?.weeklyUsed??null,weeklyAfter:r.weeklyUsed,weeklyResetAt:$i(r.weeklyResetAt,n)??null})},s=ib();if(s){o(s.grantId);return}Wle(e).then(i=>{i&&o(i.grantId)}).catch(()=>{})}function Ece(e,t,r){const n=sae({inputTokens:r.inputTokens??0,outputTokens:r.outputTokens??0,...r.cacheCreationTokens!==void 0?{cacheCreationTokens:r.cacheCreationTokens}:{},...r.cacheReadTokens!==void 0?{cacheReadTokens:r.cacheReadTokens}:{}},t);Vin(e,n).catch(()=>{})}function Xar(e,t){if(!t||typeof t!="object")return;const r=t.usage;if(!r)return;const n=vcn(t),o={inputTokens:r.input_tokens??0,outputTokens:r.output_tokens??0,cacheCreationTokens:r.cache_creation_input_tokens??0,cacheReadTokens:r.cache_read_input_tokens??0};Sce(e.key,n,o),Ece(e.label,n,o)}function Sce(e,t,r){const n=ib();n&&QQr({grantId:n.grantId,accountKey:e,model:t??n.model,usage:{inputTokens:r.inputTokens??0,outputTokens:r.outputTokens??0,...r.cacheCreationTokens!==void 0?{cacheCreationTokens:r.cacheCreationTokens}:{},...r.cacheReadTokens!==void 0?{cacheReadTokens:r.cacheReadTokens}:{}},...n.holdId?{holdId:n.holdId}:{}})}function Qar(e){if(!ib())return e;const t={};for(const[r,n]of Object.entries(e)){const o=r.toLowerCase();o==="x-neurolink-account"||o==="x-neurolink-account-type"||o.startsWith("x-neurolink-pool-")||(t[r]=n)}return t}async function pcn(e,t){const r=e.provisionedAccount;if(!r)return{paused:!1,detail:"no provisioned account recorded"};const n=Jl.get(`anthropic:${r}`),o=QQt(r,"oauth"),{verdict:s,shouldPause:i}=await Ean({grantId:e.id,accountLabel:r,lenderRequestsTotal:o?.successCount??0,observation:{at:Date.now(),sessionUsed:n?.quota?.sessionUsed??null,weeklyUsed:n?.quota?.weeklyUsed??null,reportedCoins:t,lenderRequests:0}});return i?(await $Qr(e.id,"paused"),{paused:!0,detail:s.drifted?s.detail:"repeated unexplained usage"}):{paused:!1,detail:s.drifted?s.detail:"consistent"}}async function mcn(e,t){await der(e.id,t)}function hcn(e,t){if(e.length!==t.length||e.length===0)return!1;let r=0;for(let n=0;n<e.length;n+=1)r|=e.charCodeAt(n)^t.charCodeAt(n);return r===0}var fcn=1,gcn=["live","complete","handshake","limits"];async function ycn(e,t){const r=Date.now(),n=await eir(t),o=await Promise.all(n.map(async c=>{const u=dl(c.key).quota,d=$i(u?.sessionResetAt,r)??null,m=$i(u?.weeklyResetAt,r)??null,h=await iae(e.id,c.key,d,m);return{accountKey:c.key,sessionUsed:u?.sessionUsed??null,weeklyUsed:u?.weeklyUsed??null,sessionResetAt:d,weeklyResetAt:m,borrowedSessionFraction:h.sessionFraction,borrowedWeeklyFraction:h.weeklyFraction}})),s=Kle(e.gates,o).inScope,i=await aae(e.id,s),a=Jle(e,o,r,i),l=(c,u)=>c===void 0?null:Math.max(0,c-u*100);return{grantState:e.state,level:e.level,ledger:e.entitlement.ledger,...e.entitlement.ledger==="coins"?{remainingCoins:Math.max(0,Math.floor(JQr(e)))}:{},servable:a.allowed.length>0,...a.allowed.length===0&&a.excluded.length>0?{withheldReason:Yle(a.excluded)}:{},sliceLeftPct:{session:l(e.gates.maxSlice?.session5hPct,i.sessionFraction),weekly:l(e.gates.maxSlice?.weekly7dPct,i.weeklyFraction)},...a.allowed.length===0?(()=>{const c=elr(o,r);return c===void 0?{}:{retryAfterSeconds:c}})():{}}}function Ny(e){return!e.ok}async function Ly(e){const t=uan(e);if(!t)return{ok:!1,body:pb("missing_token",{status:401}).body};const r=await UQr(t);return r?{ok:!0,grant:r}:{ok:!1,body:pb("unknown_token",{status:401}).body}}function vcn(e){if(!e||typeof e!="object")return;const t=e.model;return typeof t=="string"?t:void 0}function elr(e,t){const r=e.flatMap(n=>[n.sessionResetAt,n.weeklyResetAt]).filter(n=>n!==null&&n>t);if(r.length!==0)return Math.max(1,Math.round((Math.min(...r)-t)/1e3))}async function _cn(e){const{ctx:t,body:r,accountStrategy:n,primaryAccountKey:o,accountAllowlist:s,quotaRoutingEnabled:i=_ce(),sessionSoftLimit:a=wce(),sessionResetToleranceMs:l=WA(),setRoutingDecision:c}=e,u=await Promise.resolve().then(()=>(nn(),Tl)),d=await Promise.resolve().then(()=>(ma(),YT)),m=[],h=`${d.homedir()}/.neurolink/anthropic-credentials.json`,{tokenStore:g}=await Promise.resolve().then(()=>(rA(),jie)),y=await AA();$ar||(await g.pruneExpired(),$ar=!0);const v=await g.listByPrefix("anthropic:"),_=[];let b=0,T=0;for(const K of v){if(!Uie(K,s)){f.debug(`[proxy] skipping account=${K} (not in account allowlist)`);continue}if(await g.isDisabled(K)){const ie=dl(K),le=await g.getDisabledReason(K);if(le==="refresh_failed")await g.markEnabled(K),f.always(`[proxy] account=${K.split(":")[1]??K} re-enabled for legacy refresh failure recheck`),ie.permanentlyDisabled=!1,ie.consecutiveRefreshFailures=0;else{f.debug(`[proxy] skipping disabled account=${K.split(":")[1]??K}`),ie.permanentlyDisabled=!0,le==="entitlement_blocked"&&_.push(K.split(":")[1]??K),b+=1;continue}}const G=await g.loadTokens(K);if(!G){T+=1;continue}let Q=G.accessToken,ve=G.refreshToken,ee=G.expiresAt;const H=K.split(":")[1]??K,Z=G.tokenType==="Bearer"?"oauth":"api_key",Ee=dl(K),Se=y[K];Se?.coolingUntil>Date.now()&&(!Ee.coolingUntil||Se.coolingUntil>Ee.coolingUntil)&&(Ee.coolingUntil=Se.coolingUntil,Ee.coolingReason=Se.reason);const me=()=>{m.push({key:K,label:H,token:Q,refreshToken:ve,expiresAt:ee,type:Z,persistTarget:{providerKey:K}})};if(ee?ee<Date.now():!1){if(Ee.permanentlyDisabled)continue;if(Ee.coolingReason==="auth"&&Ee.coolingUntil&&Ee.coolingUntil>Date.now()){me();continue}if(!ve){f.always(`[proxy] skipping account=${H} (expired, no refresh token)`),await qp({key:K,label:H,token:Q,type:"oauth"},Ee,"missing_refresh_token");continue}const ie={token:Q,refreshToken:ve,expiresAt:ee,label:H},le=await J$(ie,{providerKey:K});if(!le.success){const te={key:K,label:H,token:Q,type:"oauth"};if(My(le))f.always(`[proxy] skipping account=${H} (refresh token rejected: ${le.error?.slice(0,200)??"unknown"})`),await qp(te,Ee,"refresh_invalid");else{const Ie=await xF(te,Ee);f.always(`[proxy] account=${H} refresh temporarily unavailable (${le.status??"network"}); cooling until ${new Date(Ie).toISOString()} and rotating`),me()}continue}Q=ie.token,ve=ie.refreshToken,ee=ie.expiresAt,await g.saveTokens(K,{accessToken:Q,refreshToken:ve,expiresAt:ee??Date.now()+36e5,tokenType:"Bearer"}),f.always(`[proxy] refreshed expired account=${K.split(":")[1]??K} at startup`),await AF({key:K},Ee)}me()}if(m.length===0&&jQt(v.length,tA,s))try{const K=JSON.parse(u.readFileSync(h,"utf8")),G=await tcn(K,h);G&&m.push(G)}catch{}if(process.env.ANTHROPIC_API_KEY&&m.length===0&&jQt(v.length,Bie,s)&&m.push({key:Bie,label:"env",token:process.env.ANTHROPIC_API_KEY,type:"api_key"}),m.length===0)return _.length>0&&_.length===b&&T===0?{failure:{status:403,message:olr({status:403,accounts:_,message:"OAuth authentication is not allowed for this organization.",errorCode:"oauth_not_allowed_for_organization"}),errorType:"permission_error"}}:{failure:{status:401,message:s?"No allowed Anthropic credentials are currently available":v.length>0?"Configured Anthropic accounts are disabled or unavailable":"No Anthropic credentials found",errorType:"authentication_error"}};for(const K of m)Gcn(K);await Pln(m);const k=m.filter(K=>!dl(K.key).permanentlyDisabled),x=await lcn(k),I=await ccn(x.accounts,typeof r.model=="string"?r.model:void 0),M={accounts:I.accounts,withheld:[...x.withheld,...I.withheld]},R=M.accounts;if(R.length===0&&M.withheld.length>0){const K=M.withheld.map(ve=>`${ve.label} (${ve.reason})`).join(", ");return{failure:{status:403,message:M.withheld.every(ve=>ve.reason==="model_not_allowed")?`Borrowed account(s) do not cover the requested model: ${K}. Ask the lender to widen the share, or use a model it allows.`:`Borrowed account(s) are no longer covered by a lease: ${K}. Run 'neurolink proxy peer sync' to check in with the lender, or ask them to resume the share.`,errorType:"permission_error"}}}const A=await acn({accounts:R});if(A.refusal)return{failure:A.refusal};const P=A.accounts;if(P.length===0)return{failure:{status:401,message:IF(m.map(G=>G.label)),errorType:"authentication_error"}};const{orderedAccounts:L,metricsByKey:N}=Gln({enabledAccounts:P,accountStrategy:n,primaryAccountKey:o,quotaRoutingEnabled:i,sessionSoftLimit:a,sessionResetToleranceMs:l,requestedModel:typeof r.model=="string"?r.model:void 0,setRoutingDecision:c});n==="fill-first"&&i&&P.length>1&&zln(P,L,a,N);const D=Ycn(r),O=JSON.stringify(D),F=Date.now(),$=Array.isArray(r.tools)?r.tools.length:0,B="https://api.anthropic.com/v1/messages?beta=true",z=t.headers??{},j=Kar(r);return{accounts:m,enabledAccounts:P,orderedAccounts:L,bodyStr:O,requestStart:F,toolCount:$,url:B,clientHeaders:z,isClaudeClientRequest:Jar(z,j)}}async function wcn(e){const{ctx:t,body:r,tracer:n,requestStartTime:o,logProxyBody:s,logFinalRequest:i,options:a,providerLabel:l,idleTimeoutMs:c=gln}=e,u=new AbortController;let d;try{d=await Bt(t.neurolink.stream({...a,abortSignal:u.signal}),c,`Fallback ${l} initialization timed out after ${c}ms`)}catch(_){throw u.abort(_),_}const m=async _=>{const b=d.stream[Symbol.asyncIterator]();let T="";try{for(;;){const{value:k,done:x}=await Bt(b.next(),c,`Fallback ${l} stream timed out after ${c}ms of inactivity`);if(x)return T;const I=Ale(k);I&&(T+=I,_?.(I))}}catch(k){throw u.abort(k),b.return?.().catch(()=>{}),k}};if(r.stream){const _=new Tle(r.model,0),b=[];for(const A of _.start())b.push(A);const T=await m(A=>{for(const P of _.pushDelta(A))b.push(P)}),k=d.toolCalls??[];if(!nF(T,k))throw new Error(`Translated provider ${l} returned no content or tool calls`);if(k.length)for(const A of k){const P=A.toolName??A.name??"unknown";for(const L of _.pushToolUse(Z$(),P,Rir(A)))b.push(L)}const x=d.finishReason??"end_turn",I=ub(d.usage);for(const A of _.finish(I.output,x))b.push(A);n?.end(200,Date.now()-o),i(200,"",l,void 0,void 0,{inputTokens:I.input,outputTokens:I.output});const M=b.join("");s({phase:"client_response",headers:{"content-type":"text/event-stream"},body:M,bodySize:Buffer.byteLength(M,"utf8"),contentType:"text/event-stream",responseStatus:200,durationMs:Date.now()-o});async function*R(){for(const A of b)yield A}return R()}const h=await m();if(!nF(h,d.toolCalls))throw new Error(`Translated provider ${l} returned no content or tool calls`);const g={content:h,model:d.model,finishReason:d.finishReason??"end_turn",reasoning:void 0,usage:d.usage?ub(d.usage):void 0,toolCalls:d.toolCalls};n?.end(200,Date.now()-o);const y=ble(g,r.model);i(200,"",l,void 0,void 0,{inputTokens:g.usage?.input,outputTokens:g.usage?.output});const v=JSON.stringify(y);return s({phase:"client_response",headers:{"content-type":"application/json"},body:v,bodySize:Buffer.byteLength(v,"utf8"),contentType:"application/json",responseStatus:200,durationMs:Date.now()-o}),y}async function tlr(e){let t;for(let r=0;r<=uce;r+=1)try{return await wcn(e)}catch(n){if(t=n,!xce(n)||r===uce)throw n;const o=cce[r]??250;f.always(`[proxy] retrying fallback=${e.providerLabel} after transient network error (${r+1}/${uce}) in ${o}ms: ${JA(Sd(n))}`),await Gp(o)}throw t}async function bcn(e){const{ctx:t,body:r,model:n,tracer:o,requestStartTime:s,logProxyBody:i,logFinalRequest:a}=e,l={...t,requestId:`${t.requestId}:codex-fallback`,method:"POST",path:"/backend-api/codex/responses",headers:{"content-type":"application/json",accept:"text/event-stream"},query:{},params:{},body:asn(r,n),metadata:{...t.metadata,"neurolink.codexFallback":!0},responseHeaders:{}},c=await Tar(l),u={...l.responseHeaders??{}};let d;try{d=await hsn(c)}catch(_){throw _ instanceof Ele&&f.always(`[proxy] Codex fallback returned ${_.status}: ${Xn(_.responseBody,500)}`),_}Object.keys(u).length>0&&(t.responseHeaders??={},Object.assign(t.responseHeaders,Qar(u)));const m=u["x-neurolink-account"]??"",h=u["x-neurolink-account-type"]??"codex-oauth",g={content:d.text,model:r.model,finishReason:d.finishReason,...d.usage?{usage:d.usage}:{},toolCalls:d.toolCalls};if(r.stream){const _=new Tle(r.model,d.usage?.input??0),b=[];for(const x of _.start())b.push(x);if(d.text)for(const x of _.pushDelta(d.text))b.push(x);for(const x of d.toolCalls)for(const I of _.pushToolUse(Z$(),x.toolName,x.args))b.push(I);for(const x of _.finish(d.usage?.output,d.finishReason))b.push(x);o?.end(200,Date.now()-s),a(200,m,h,void 0,void 0,{inputTokens:d.usage?.input,outputTokens:d.usage?.output,cacheCreationTokens:d.usage?.cacheCreationTokens,cacheReadTokens:d.usage?.cacheReadTokens});const T=b.join("");i({phase:"client_response",headers:{"content-type":"text/event-stream"},body:T,bodySize:Buffer.byteLength(T,"utf8"),contentType:"text/event-stream",responseStatus:200,durationMs:Date.now()-s});async function*k(){for(const x of b)yield x}return k()}o?.end(200,Date.now()-s);const y=ble(g,r.model);a(200,m,h,void 0,void 0,{inputTokens:d.usage?.input,outputTokens:d.usage?.output,cacheCreationTokens:d.usage?.cacheCreationTokens,cacheReadTokens:d.usage?.cacheReadTokens});const v=JSON.stringify(y);return i({phase:"client_response",headers:{"content-type":"application/json"},body:v,bodySize:Buffer.byteLength(v,"utf8"),contentType:"application/json",responseStatus:200,durationMs:Date.now()-s}),y}async function rlr(e){if(ib())return null;const t=await xin();if(t.length===0)return null;const r=e.body.stream===!0,n=JSON.stringify(e.body);for(const o of t){f.always(`[proxy] local pool spent \u2014 trying peer=${o.name}`);const s=await Xin({peer:o,body:n,stream:r});if(s.ok)return f.always(`[proxy] served by peer=${o.name}`),e.logFinalRequest(s.response.status,`peer:${o.name}`,"peer"),r?new Response(s.response.body,{status:s.response.status,headers:{"content-type":s.response.headers.get("content-type")??"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}}):await s.response.json().catch(()=>null)??null}return null}function Tcn(e){return!(e instanceof Ele)||e.status!==400?null:{status:e.status,body:e.responseBody,contentType:"application/json"}}async function nlr(e){const{ctx:t,body:r,parsedFallbackRequest:n,fallbackPlan:o,modelRouter:s,tracer:i,requestStartTime:a,logProxyBody:l,logFinalRequest:c}=e,u=o??gb({provider:"anthropic",model:r.model},s?.getFallbackChain()??[],r.model,n);l({phase:"routing_decision",contentType:"application/json",body:{stage:"anthropic_fallback",attempts:u.attempts.slice(1)}}),i?.setFallbackInfo({triggered:!0,attemptCount:u.attempts.slice(1).length,reason:"all_anthropic_accounts_exhausted"});let d,m;for(const h of u.attempts.slice(1)){if(!h.provider||!h.model)continue;const g=Date.now();try{f.always(`[proxy] fallback \u2192 ${h.provider}/${h.model}`);let y;if(h.provider==="codex")y=await bcn({ctx:t,body:r,model:h.model,tracer:i,requestStartTime:a,logProxyBody:l,logFinalRequest:c});else{const v=await Z_.checkFallbackProviderAvailability(h.provider,h.model);if(!v.available){const b=v.reason??"provider unavailable";f.always(`[proxy] fallback ${h.provider}/${h.model} health-check failed (${b}), skipping`),DA({provider:h.provider,model:h.model,status:"failure",errorMessage:`[unavailable] ${b}`,durationMs:0}),d=`[${h.provider}/${h.model}] unavailable: ${b}`;continue}const _=_lr(n,{provider:h.provider,model:h.model});y=await tlr({ctx:t,body:r,tracer:i,requestStartTime:a,logProxyBody:l,logFinalRequest:c,options:_,providerLabel:h.provider})}return DA({provider:h.provider,model:h.model,status:"success",durationMs:Date.now()-g}),i?.setFallbackInfo({triggered:!0,provider:h.provider,model:h.model,attemptCount:u.attempts.slice(1).length,reason:"fallback_success"}),h.provider!=="codex"&&VA(t,{quota:null,source:"none",servedBy:h.provider}),{response:y}}catch(y){m??=Tcn(y)??void 0;const v=JA(y instanceof Error?y.message:String(y));let _="unknown";v.includes("Rate limit")||v.includes("rate_limit")||v.includes("max_parallel_requests")?_="rate_limit":v.includes("context length")||v.includes("ContextWindowExceeded")?_="context_overflow":v.includes("no content or tool calls")||v.includes("NoOutputGenerated")?_="empty_response":v.includes("thinking_level")||v.includes("Field required")?_="schema_mismatch":v.includes("Resource exhausted")&&(_="provider_quota"),f.always(`[proxy] fallback ${h.provider}/${h.model} failed [${_}]: ${JA(Sd(y))}`),DA({provider:h.provider,model:h.model,status:"failure",errorMessage:`[${_}] ${v}`,durationMs:Date.now()-g}),d=`[${h.provider}/${h.model}] ${JA(Sd(y))}`}}return{response:null,lastErrorMessage:d,...m?{invalidRequestFailure:m}:{}}}async function Ecn(e){const{ctx:t,body:r,tracer:n,requestStartTime:o,logProxyBody:s,logFinalRequest:i}=e,a=Date.now();try{const l=wle(r),c=gb({provider:"anthropic",model:r.model},[],r.model,l,!0);if(Zar(s,"auto_fallback",c),!c.attempts.find(h=>h.label==="auto-provider"))return{response:null};f.always("[proxy] fallback \u2192 auto-provider");const d=_lr(l),m=await tlr({ctx:t,body:r,tracer:n,requestStartTime:o,logProxyBody:s,logFinalRequest:i,options:d,providerLabel:"auto-provider"});return DA({provider:"auto-provider",model:r.model,status:"success",durationMs:Date.now()-a}),n?.setFallbackInfo({triggered:!0,provider:"auto-provider",model:r.model,attemptCount:1,reason:"fallback_success"}),VA(t,{quota:null,source:"none",servedBy:"auto-provider"}),{response:m}}catch(l){const c=JA(Sd(l));return f.always(`[proxy] fallback auto-provider failed: ${c}`),DA({provider:"auto-provider",model:r.model,status:"failure",errorMessage:c,durationMs:Date.now()-a}),n?.setFallbackInfo({triggered:!0,provider:"auto-provider",model:r.model,attemptCount:1,reason:"fallback_failure"}),{response:null,lastErrorMessage:c}}}function Scn(e,t=5){const r=[...new Set(e)];return r.length<=t?r.join(", "):`${r.slice(0,t).join(", ")} and ${r.length-t} more`}function olr(e){const t=new Set(e.accounts).size,r=e.errorCode?` (${e.errorCode})`:"";return`All ${t} Anthropic account${t===1?"":"s"} are blocked by an organization entitlement policy${r}. Accounts: ${Scn(e.accounts)}. Upstream: "${e.message}". Ask an organization admin to re-enable Claude Code OAuth access, then run: neurolink auth enable anthropic:<account>.`}function Ccn(e){const t=new Set(e.map(r=>r.coolingReason));if(t.size===1)switch([...t][0]){case"session":return"5-hour subscription window";case"weekly":return"7-day subscription window";case"unified":return"subscription limit";case"transient":return"upstream burst limit";default:break}return"upstream rate limits"}function kcn(e){for(const t of e){const r=Jl.get(t.key)?.quota;if(r?.overageDisabledReason&&r.overageStatus?.trim().toLowerCase()!=="allowed")return r.overageDisabledReason}}function slr(e){return e?` Paid extra usage is unavailable for this organization (${e}), so there is no additional capacity before the window resets.`:""}function xcn(e){const t=new Set(e.accounts).size;return`All ${t} Anthropic account${t===1?"":"s"} have exhausted the model-scoped limit for ${e.model} (window "${e.scopeModel}"). Other models remain available on this pool \u2014 switch model, or add an account with remaining ${e.scopeModel} capacity. Earliest reset at ${new Date(e.earliestResetMs).toISOString()}.`+slr(e.overageDisabledReason)}function ilr(e){const{tracer:t,requestStartTime:r,authFailureMessage:n,authCooldownMessage:o,invalidRequestFailure:s,entitlementFailure:i,scopedExhaustion:a,sawNetworkError:l,sawTransientFailure:c,sawRateLimit:u,lastError:d,lastTransportErrorCode:m,lastTransportScope:h,fallbackFailureMessage:g,orderedAccounts:y,buildLoggedClaudeError:v,logProxyBody:_,logFinalRequest:b}=e;if(i!==null&&y.length>0&&new Set(i.accounts).size>=y.length&&i&&!u){const D=olr(i);return t?.setError("permission_error",D),t?.end(403,Date.now()-r),v(403,D,"permission_error")}if(n&&!u)return t?.setError("authentication_error",n),t?.end(401,Date.now()-r),v(401,n);if(o&&!u)return t?.setError("token_refresh_unavailable",o),t?.end(503,Date.now()-r),v(503,o,"token_refresh_unavailable");if(s&&!u){const D=Cd(s.body),O=D.message!==void 0,F=Or(D.message??s.body),$=O?s.body:JSON.stringify(ul(s.status,F,"invalid_request_error")),B=O?s.contentType??"application/json":"application/json";return t?.setError("invalid_request_error",F),t?.end(s.status,Date.now()-r),b(s.status,"","final","invalid_request_error",F),_({phase:"client_response",headers:{"content-type":B},body:$,bodySize:Buffer.byteLength($,"utf8"),contentType:B,responseStatus:s.status,durationMs:Date.now()-r}),new Response($,{status:s.status,headers:{"content-type":B}})}if((l||c)&&!u){const D=g?` Fallback also failed: ${g}`:"",O=h==="shared_provider_transport"?"shared Anthropic network":h==="connection_transport"?"Anthropic connection":null,F=`${O?`${O} failure prevented safe cross-account rotation`:"All Anthropic accounts failed due to transient upstream/network errors"}. Last error${m?` (${m})`:""}: ${d instanceof Error?d.message:String(d??"unknown")}.${D}`;return t?.setError("transient_error",F.slice(0,500)),t?.end(502,Date.now()-r),v(502,F,g?"fallback_exhausted":"transient_error",{...m?{errorCode:m}:{},...h?{transportScope:h}:{}})}const k=(D,O)=>{const F=ul(429,D,"overloaded_error");t?.setError("rate_limit_error",D),t?.end(429,Date.now()-r),b(429,"","final","rate_limit_error",D);const $=JSON.stringify(F),B={"content-type":"application/json","retry-after":String(O)};return _({phase:"client_response",headers:B,body:$,bodySize:Buffer.byteLength($,"utf8"),contentType:"application/json",responseStatus:429,durationMs:Date.now()-r}),new Response($,{status:429,headers:B})};if(a){const D=xcn(a);return f.always(`[proxy] model-scoped limit exhausted for ${a.model} on all accounts`),k(D,Math.max(1,Math.ceil((a.earliestResetMs-Date.now())/1e3)))}if(!u){const D=g?` Fallback also failed: ${g}`:"",O=`All Anthropic accounts failed. Last error: ${d instanceof Error?d.message:String(d??"unknown")}.${D}`;return t?.setError("all_accounts_failed",O.slice(0,500)),t?.end(502,Date.now()-r),v(502,O,g?"fallback_exhausted":"all_accounts_failed")}const x=Date.now(),I=y.map(D=>dl(D.key)).filter(D=>D.coolingUntil&&D.coolingUntil>x&&D.coolingReason!=="auth"),M=Math.min(...I.map(D=>D.coolingUntil??Number.POSITIVE_INFINITY)),R=y.length>0&&I.length===y.length,A=R?Math.max(1,Math.ceil((M-x)/1e3)):1,P=Ccn(I),L=slr(kcn(y)),N=R?`All ${y.length} Anthropic accounts are cooling after the ${P} was exhausted. Earliest retry at ${new Date(M).toISOString()}.${L}`:`All ${y.length} accounts rate-limited after per-account retries.${L}`;return f.always(`[proxy] all accounts rate-limited, retry in ${A}s`),k(N,A)}async function alr(e){const{ctx:t,body:r,account:n,accountState:o,response:s,tracer:i,requestStartTime:a,fetchStartMs:l,attemptNumber:c,finalBodyStr:u,upstreamSpan:d,logAttempt:m,logProxyBody:h,onStreamTerminal:g,poolAccounts:y,logFinalRequest:v}=e;o.consecutiveRefreshFailures=0,f.always(`[proxy] \u2190 ${s.status} account=${n.label}`);const _=nb(s.headers,{model:r.model});if(_){dcn(n.key,o.quota,_),o.quota=Ay(o.quota,_);const T=yce(o,_,Date.now());T?.kind==="cooled"?Td(n.key,T.coolingUntil,T.coolingReason).catch(()=>{}):T?.kind==="cleared"&&xy(n.key,T.coolingUntil).catch(()=>{}),Ry(n.key,_).catch(()=>{})}const b={};return s.headers.forEach((T,k)=>{b[k]=T}),i?.logUpstreamResponseHeaders(b),VA(t,{upstreamHeaders:s.headers,quota:_??o.quota??null,source:_?"live":o.quota?"snapshot":"none",account:n,accountState:o,servedBy:"anthropic",attempt:c,...y?{poolAccounts:y}:{}}),r.stream?Acn({ctx:t,body:r,account:n,accountState:o,response:s,responseHeaders:b,tracer:i,requestStartTime:a,fetchStartMs:l,attemptNumber:c,finalBodyStr:u,upstreamSpan:d,logAttempt:m,logProxyBody:h,logFinalRequest:v,onStreamTerminal:g}):Rcn({account:n,response:s,responseHeaders:b,tracer:i,requestStartTime:a,fetchStartMs:l,attemptNumber:c,finalBodyStr:u,upstreamSpan:d,logAttempt:m,logProxyBody:h,logFinalRequest:v})}async function Acn(e){const{ctx:t,body:r,account:n,accountState:o,response:s,responseHeaders:i,tracer:a,requestStartTime:l,fetchStartMs:c,attemptNumber:u,finalBodyStr:d,upstreamSpan:m,logAttempt:h,logProxyBody:g,onStreamTerminal:y,logFinalRequest:v}=e;if(!s.body){$r(n.label,n.type,502),h(502,"stream_error","No response body from upstream"),m?.end(),a?.setError("stream_error","No response body from upstream"),a?.end(502,Date.now()-l),v(502,n.label,n.type,"stream_error","No response body from upstream");const R=ul(502,"No response body from upstream"),A=JSON.stringify(R);return g({phase:"client_response",headers:{"content-type":"application/json"},body:A,bodySize:Buffer.byteLength(A,"utf8"),contentType:"application/json",account:n.label,accountType:n.type,attempt:u,responseStatus:502,durationMs:Date.now()-l}),{response:R}}const _=s.body.getReader(),b=await jan(_);if(b.kind==="transport_error"){const R=Sd(b.error),A=Buffer.concat(b.chunks.map(P=>Buffer.from(P))).toString("utf8");return f.always(`[proxy] stream failed before first chunk account=${n.label}: ${R}; returning terminal error to avoid replaying an ambiguous request`),$r(n.label,n.type,502),h(502,"stream_error",R,{retryable:!1}),m?.end(),g({phase:"upstream_response",headers:i,body:A,bodySize:Buffer.byteLength(A,"utf8"),contentType:i["content-type"]??"text/event-stream",account:n.label,accountType:n.type,attempt:u,responseStatus:s.status,durationMs:Date.now()-c,metadata:{logicalStatus:502,transportError:R}}),{response:clr({account:n,tracer:a,requestStartTime:l,attemptNumber:u,logProxyBody:g,logFinalRequest:v,errorType:"stream_error",message:R})}}if(b.kind==="empty")return await _.cancel().catch(()=>{}),f.always(`[proxy] \u2190 empty stream from account=${n.label}, trying next`),$r(n.label,n.type,502),h(502,"empty_stream","Empty upstream stream",{retryable:!0}),a?.recordRetry(n.label,"empty_stream"),m?.end(),g({phase:"upstream_response",headers:i,body:"",bodySize:0,contentType:i["content-type"]??"text/event-stream",account:n.label,accountType:n.type,attempt:u,responseStatus:s.status,durationMs:Date.now()-c,metadata:{logicalStatus:502,upstreamErrorType:"empty_stream"}}),{retryNextAccount:!0,failure:{message:"Empty upstream stream",rateLimit:!1}};if(b.kind==="sse_error"){await _.cancel().catch(()=>{});const R=Buffer.concat(b.chunks.map(D=>Buffer.from(D))).toString("utf8"),A=b.errorType==="rate_limit_error",P=A?429:502,L=nb(i,{model:r.model}),N=Date.now();if(A){const D=fce(L,uF(i["retry-after"]??null),N,V$(i));o.quota=L?Ay(o.quota,L):o.quota;const O=D.reason==="transient"?"transient":"quota";(!o.coolingUntil||D.coolingUntil>o.coolingUntil)&&(o.coolingUntil=D.coolingUntil,o.coolingReason=D.reason,await Td(n.key,D.coolingUntil,D.reason).catch(()=>{})),$r(n.label,n.type,429,O),h(429,"rate_limit_error",b.message,{retryable:!0,rateLimitKind:O,cooldownReason:D.reason})}else $r(n.label,n.type,P),h(P,b.errorType,b.message,{retryable:!0});return f.always(`[proxy] immediate SSE ${b.errorType} account=${n.label}: ${b.message}; rotating before client commit`),a?.recordRetry(n.label,A?"stream_rate_limit_before_commit":"stream_error_before_commit"),m?.end(),g({phase:"upstream_response",headers:i,body:R,bodySize:Buffer.byteLength(R,"utf8"),contentType:i["content-type"]??"text/event-stream",account:n.label,accountType:n.type,attempt:u,responseStatus:s.status,durationMs:Date.now()-c,metadata:{logicalStatus:P,upstreamErrorType:b.errorType}}),{retryNextAccount:!0,failure:{message:b.message,rateLimit:A,...b.errorType==="overloaded_error"?{retryDelayMs:flr(u)}:{}}}}h(s.status,void 0,void 0,{attemptDurationMs:Date.now()-c});const T=aar();let k=!1;const x=new ReadableStream({start(R){for(const A of b.chunks)R.enqueue(A)},async pull(R){if(!k)try{const{done:A,value:P}=await _.read();if(k)return;if(A){k=!0,T.complete(),R.close();return}R.enqueue(P)}catch(A){const P=Sd(A);if(f.always(`[proxy] mid-stream error account=${n.label}: ${P}`),T.fail(P),!k){k=!0;const L=`event: error
|
|
2370
|
+
`);for(const b of _)$ir(r,b)}l()}}),u=c.writable.getWriter();let d;const m=new WritableStream({start(v){d=v},write(v){return u.write(v)},close(){return u.close()},abort(v){return l(),u.abort(v)}});u.closed.catch(v=>{l();try{d.error(v)}catch{}});const h=c.readable.getReader();return{stream:{readable:new ReadableStream({async pull(v){try{const{done:_,value:b}=await h.read();_?v.close():v.enqueue(b)}catch(_){v.error(_)}},async cancel(v){l();try{d.error(v)}catch{}await Promise.allSettled([h.cancel(v),u.abort(v)])}}),writable:m},telemetry:a}}Jr(),ii(),nr(),Oc(),q(),Gl();var win="proxy-peers.json",bin=1e3,Tin={exhausted:9e5,withheld:6e5,paused:3e5,revoked:864e5,expired:864e5,unreachable:6e4,upstream_error:12e4},Ein=null,zp={},OA=0,NA=-1,LA=!1,Fir=new sl;function qle(){return Ein??St(Wa(),".neurolink",win)}function Sin(e){if(!e||typeof e!="object")return!1;const t=e;return typeof t.name=="string"&&typeof t.url=="string"&&typeof t.token=="string"&&typeof t.priority=="number"&&typeof t.enabled=="boolean"}function Cin(e){return e?.code==="ENOENT"}async function Gle(e={}){const t=Date.now();if(!e.force&&LA&&t-OA<bin)return;const r=qle();let n;try{n=(await qs(r)).mtimeMs}catch(o){if(!Cin(o))throw o;zp={},NA=-1,OA=t,LA=!0;return}if(!e.force&&LA&&n===NA){OA=t;return}try{const o=JSON.parse(await Kr(r,"utf8"));zp=Object.fromEntries(Object.entries(o?.peers??{}).filter(s=>Sin(s[1])))}catch(o){if(e.force)throw o;f.always(`[proxy] peer list unreadable, treating as empty: ${o instanceof Error?o.message:String(o)}`),zp={}}NA=n,OA=t,LA=!0}async function Uir(){const e={schemaVersion:1,peers:zp};await il(qle(),e);try{NA=(await qs(qle())).mtimeMs}catch{NA=-1}OA=Date.now(),LA=!0}function Bir(e){return e.trim().toLowerCase()}async function kin(){return await Gle(),Object.values(zp).sort((e,t)=>e.priority-t.priority||e.createdAt-t.createdAt)}async function xin(e=Date.now()){return(await kin()).filter(r=>r.enabled&&!(r.cooldownUntil&&r.cooldownUntil>e))}function Ain(e){return Tin[e]}var Iin=6048e5;async function Hle(e,t,r){await Fir.runExclusive(async()=>{await Gle({force:!0});const n=Bir(e),o=zp[n];if(!o)return;const s=(r??0)*1e3,i=Date.now()+Math.min(Iin,Math.max(Ain(t),Number.isFinite(s)?s:0));zp[n]={...o,cooldownUntil:i,cooldownReason:t,updatedAt:Date.now()},await Uir()})}async function Rin(e,t){await Fir.runExclusive(async()=>{await Gle({force:!0});const r=Bir(e),n=zp[r];n&&(zp[r]={...n,cooldownUntil:0,lastUsedAt:Date.now(),updatedAt:Date.now(),...t?{lastObservation:t}:{}},await Uir())})}Jr(),ii(),nr(),Oc(),w$();var Min=6048e5,Pin=9e5,Din=864e5;function Oin(e){return!e.usable}function zir(e){return{schemaVersion:e.schemaVersion,grantId:e.grantId,peerLabel:e.peerLabel,issuedAt:e.issuedAt,notAfter:e.notAfter,heartbeatEveryMs:e.heartbeatEveryMs,offlineGraceMs:e.offlineGraceMs,gates:e.gates,entitlementSnapshot:e.entitlementSnapshot}}function jir(e,t){return Yie(e,t)}function qir(e,t=Date.now()){const r=e.leasePolicy,n=e.leaseSecret;if(!n)throw new Error(`Grant ${e.id} has no lease secret \u2014 provision it before issuing a lease.`);const o=r?.ttlMs??Min,s=Math.min(t+o,e.gates.notAfter??Number.POSITIVE_INFINITY),i={schemaVersion:1,grantId:e.id,peerLabel:e.peerLabel,issuedAt:t,notAfter:s,heartbeatEveryMs:r?.heartbeatEveryMs??Pin,offlineGraceMs:r?.offlineGraceMs??Din,gates:e.gates,entitlementSnapshot:e.entitlement.ledger==="coins"?e.entitlement.coins??0:"unlimited"};return{...i,signature:jir(zir(i),n)}}function Nin(e,t){const{signature:r,...n}=e;return ler(jir(zir(n),t),r)}function Lin(e){const t=e.now??Date.now();if(!Nin(e.lease,e.secret))return{usable:!1,reason:"unsigned",detail:"lease signature does not match the lender's secret"};if(e.lease.notAfter<=t)return{usable:!1,reason:"expired",detail:"the lease's hard expiry has passed"};const r=e.lastHeartbeatAt??e.lease.issuedAt;return r+e.lease.offlineGraceMs<=t?{usable:!1,reason:"grace_elapsed",detail:"the lender has been unreachable for longer than this lease allows"}:{usable:!0,nextHeartbeatDueAt:r+e.lease.heartbeatEveryMs}}function $in(e){const t=e.now??Date.now();if(!e.grant.leaseSecret)throw new Error(`Grant ${e.grant.id} has no lease secret \u2014 attach lease material first.`);return{code:e.code,state:e.state,accountLabel:`${e.grant.peerLabel}-via-${e.lenderName}`,leaseSecret:e.grant.leaseSecret,lease:qir(e.grant,t),lenderUrl:(e.lenderUrl??"").replace(/\/+$/,"")}}Gl();var Fin="proxy-resident-grants.json",Uin=1e3,Bin=null,Py={},$A=0,FA=-1,UA=!1,zin=new sl;function Vle(){return Bin??St(Wa(),".neurolink",Fin)}function jin(e){if(!e||typeof e!="object")return!1;const t=e;return typeof t.accountLabel=="string"&&typeof t.grantId=="string"&&typeof t.leaseSecret=="string"&&!!t.lease}function qin(e){return e?.code==="ENOENT"}async function Gir(e={}){const t=Date.now();if(!e.force&&UA&&t-$A<Uin)return;const r=Vle();let n;try{n=(await qs(r)).mtimeMs}catch(o){if(!qin(o))throw o;Py={},FA=-1,$A=t,UA=!0;return}if(!e.force&&UA&&n===FA){$A=t;return}try{const o=JSON.parse(await Kr(r,"utf8"));Py=Object.fromEntries(Object.entries(o?.grants??{}).filter(s=>jin(s[1])))}catch(o){if(e.force)throw o;Py={}}FA=n,$A=t,UA=!0}async function Gin(){const e={schemaVersion:1,grants:Py};await il(Vle(),e);try{FA=(await qs(Vle())).mtimeMs}catch{FA=-1}$A=Date.now(),UA=!0}function Hir(e){return e.toLowerCase()}async function Wle(e){await Gir();const t=e.toLowerCase(),r=t.includes(":")?t.slice(t.indexOf(":")+1):t;return Py[Hir(r)]}async function Hin(e,t=Date.now()){const r=await Wle(e);if(r)return Lin({lease:r.lease,secret:r.leaseSecret,...r.lastHeartbeatAt!==void 0?{lastHeartbeatAt:r.lastHeartbeatAt}:{},now:t})}async function Vin(e,t){await zin.runExclusive(async()=>{await Gir({force:!0});const r=Hir(e),n=Py[r];n&&(Py[r]={...n,unreportedCoins:(n.unreportedCoins??0)+t,unreportedRequests:(n.unreportedRequests??0)+1},await Gin())})}q();var Win=15e3,Kin=12e4;function Jin(e){switch(e){case"exhausted":return"exhausted";case"paused":return"paused";case"revoked":return"revoked";case"expired":return"expired";case"reserve_floor":case"spillover_inactive":case"slice_exhausted":case"no_capacity":return"withheld";case"missing_token":case"unknown_token":case"malformed_token":return"revoked";default:return"upstream_error"}}function Vir(e,t){const r=e.headers.get(t);if(r===null||r.trim()==="")return;const n=Number(r);return Number.isFinite(n)?n:void 0}function Yin(e){const t=Vir(e,"x-neurolink-grant-remaining-coins");return{observedAt:Date.now(),...e.headers.get("x-neurolink-grant-status")?{grantStatus:e.headers.get("x-neurolink-grant-status")??""}:{},...e.headers.get("x-neurolink-grant-reason")?{grantReason:e.headers.get("x-neurolink-grant-reason")??""}:{},...t!==void 0?{remainingCoins:t}:{}}}function Zin(e,t,r){const n=e.body;if(!n)return e;let o;const s=()=>{o!==void 0&&(clearTimeout(o),o=void 0)},i=()=>{s(),o=setTimeout(()=>{f.always(`[proxy] peer=${t.name} went quiet mid-response; abandoning it`),Hle(t.name,"unreachable").catch(l=>{f.debug(`[proxy] could not cool peer=${t.name} after a stall: ${l instanceof Error?l.message:String(l)}`)}),r.abort()},Kin),o.unref?.()},a=n.pipeThrough(new TransformStream({start:i,transform(l,c){i(),c.enqueue(l)},flush:s}));return r.signal.addEventListener("abort",s,{once:!0}),new Response(a,{status:e.status,statusText:e.statusText,headers:e.headers})}async function Xin(e){const{peer:t,body:r,stream:n}=e,o=new AbortController,s=setTimeout(()=>o.abort(),Win);e.signal&&(e.signal.aborted?o.abort():e.signal.addEventListener("abort",()=>o.abort(),{once:!0}));try{const i=await fetch(`${t.url}/v1/messages`,{method:"POST",headers:{"content-type":"application/json","x-neurolink-share-token":t.token,accept:n?"text/event-stream":"application/json"},body:r,signal:o.signal});if(i.ok)return await Rin(t.name,Yin(i)).catch(u=>{f.debug(`[proxy] could not record success for peer=${t.name}: ${u instanceof Error?u.message:String(u)}`)}),{ok:!0,response:Zin(i,t,o),peer:t};const a=i.headers.get("x-neurolink-grant-reason"),l=Jin(a),c=Vir(i,"retry-after");return await Hle(t.name,l,c),await i.text().catch(()=>""),f.always(`[proxy] peer=${t.name} declined (${l}); cooling before retry`),{ok:!1,peer:t,status:i.status,reason:l,message:`peer ${t.name} declined: ${l}`,...c!==void 0?{retryAfterSeconds:c}:{}}}catch(i){const a=i instanceof Error?i.message:String(i);return e.signal?.aborted?(f.debug(`[proxy] peer=${t.name} attempt cancelled by the caller: ${a}`),{ok:!1,peer:t,reason:"unreachable",message:`peer ${t.name} attempt cancelled`}):(await Hle(t.name,"unreachable").catch(l=>{f.debug(`[proxy] could not cool peer=${t.name}: ${l instanceof Error?l.message:String(l)}`)}),f.always(`[proxy] peer=${t.name} unreachable: ${a}`),{ok:!1,peer:t,reason:"unreachable",message:`peer ${t.name} unreachable`})}finally{clearTimeout(s)}}dA();var Qin=36e5,ean={missing_token:"No share token was presented.",unknown_token:"Share token is not recognized.",malformed_token:"Share token is malformed.",paused:"The lender has paused this share.",revoked:"This share has been revoked.",expired:"This share has expired.",out_of_window:"This share is outside its allowed hours.",model_not_allowed:"This share does not cover the requested model.",exhausted:"This share has no credit remaining.",rate_limited:"This share's request rate limit was exceeded.",concurrency_limited:"This share's concurrent request limit was reached.",reserve_floor:"The lender's reserved headroom is in force.",spillover_inactive:"This share serves only the lender's spare capacity, and none is spare yet.",slice_exhausted:"This share has used its allotted portion of the window.",no_capacity:"No lender account can currently serve this share."};function tan(e){return ean[e]}function ran(e){switch(e){case"missing_token":case"unknown_token":case"malformed_token":return 401;case"paused":case"revoked":case"expired":case"out_of_window":case"model_not_allowed":return 403;default:return 429}}function nan(e,t){const r=new Date(t).getHours(),{fromHour:n,toHour:o}=e;return n===o?!0:n<o?r>=n&&r<o:r>=n||r<o}function oan(e,t){if(!e||e.length===0)return!0;if(!t)return!1;const r=t.toLowerCase();return e.some(n=>r.includes(n.toLowerCase()))}function Wir(e,t){const r=n=>n===void 0?t:t===void 0?n:Math.min(n,t);return{session:r(e?.session5hPct),weekly:r(e?.weekly7dPct)}}function Kir(e,t,r){const n=e.spillover;if(!n)return!1;const o=n.beforeResetHours*Qin,s=n.whenUtilizationBelowPct/100,i=t.weeklyResetAt!==null&&t.weeklyResetAt-r<=o&&t.weeklyResetAt>r&&t.weeklyUsed!==null&&t.weeklyUsed<s,a=t.sessionResetAt!==null&&t.sessionResetAt-r<=o&&t.sessionResetAt>r&&t.sessionUsed!==null&&t.sessionUsed<s;return i||a}function Kle(e,t){if(!e.accounts||e.accounts.length===0)return{inScope:[...t],outOfScope:[]};const r=new Set(e.accounts.map(s=>s.trim().toLowerCase())),n=[],o=[];for(const s of t){const i=s.accountKey.toLowerCase(),a=i.includes(":")?i.slice(i.indexOf(":")+1):i;r.has(i)||r.has(a)?n.push(s):o.push(s)}return{inScope:n,outOfScope:o}}function Jle(e,t,r,n){const o=e.gates,{inScope:s,outOfScope:i}=Kle(o,t),a=s.some(m=>Kir(o,m,r)),l=Wir(o.maxSlice,a?o.spillover?.maxSlicePct:void 0);if(l.session!==void 0&&n.sessionFraction*100>=l.session||l.weekly!==void 0&&n.weeklyFraction*100>=l.weekly)return{allowed:[],excluded:[...s.map(m=>({accountKey:m.accountKey,reason:"slice_exhausted"})),...i.map(m=>({accountKey:m.accountKey,reason:"no_capacity"}))]};const u=[],d=i.map(m=>({accountKey:m.accountKey,reason:"no_capacity"}));for(const m of s){const h=Kir(o,m,r);if(o.spillover&&!h){d.push({accountKey:m.accountKey,reason:"spillover_inactive"});continue}const g=o.reserveFloor;if(g){const b=g.session5hPct!==void 0&&m.sessionUsed!==null&&m.sessionUsed*100>100-g.session5hPct,T=g.weekly7dPct!==void 0&&m.weeklyUsed!==null&&m.weeklyUsed*100>100-g.weekly7dPct;if(b||T){d.push({accountKey:m.accountKey,reason:"reserve_floor"});continue}}const y=Wir(o.maxSlicePerAccount,h?o.spillover?.maxSlicePct:void 0),v=y.session!==void 0&&m.borrowedSessionFraction*100>=y.session,_=y.weekly!==void 0&&m.borrowedWeeklyFraction*100>=y.weekly;if(v||_){d.push({accountKey:m.accountKey,reason:"slice_exhausted"});continue}u.push(m.accountKey)}return{allowed:u,excluded:d}}function Yle(e){return e.some(t=>t.reason==="reserve_floor")?"reserve_floor":e.some(t=>t.reason==="spillover_inactive")?"spillover_inactive":e.some(t=>t.reason==="slice_exhausted")?"slice_exhausted":"no_capacity"}var san="x-neurolink-share-token",ian="x-neurolink-grant-status",aan="x-neurolink-grant-reason",lan="x-neurolink-grant-remaining-coins",can="x-neurolink-grant-peer";function uan(e){const t=e[san];if(t?.trim())return t.trim();const r=e.authorization??e.Authorization;if(!r)return;const n=r.trim(),o=n.toLowerCase().startsWith("bearer ")?n.slice(7).trim():n;return LQr(o)?o:void 0}function dan(e){return e===401?"authentication_error":e===403?"permission_error":"rate_limit_error"}function pan(e,t){switch(e){case"paused":return"paused";case"revoked":return"revoked";case"expired":return"expired";case"exhausted":return"exhausted";case"out_of_window":return"out-of-window";case"missing_token":case"unknown_token":case"malformed_token":return"unauthorized";default:return t?.state??"active"}}function pb(e,t){const{status:r,grant:n,retryAfterSeconds:o}=t,s={[ian]:pan(e,n),[aan]:e};return n&&(s[can]=n.peerLabel,n.entitlement.ledger==="coins"&&(s[lan]=String(Math.max(0,Math.floor(n.entitlement.coins??0))))),o!==void 0&&(s["retry-after"]=String(Math.max(1,Math.round(o)))),{status:r,headers:s,body:{type:"error",error:{type:dan(r),message:t.message??tan(e)}}}}dA(),Jr(),ii(),nr(),Oc(),Gl();var man="proxy-share-audit.json",han=2,fan=3,gan=1e3,yan=null,mb={},BA=0,zA=-1,jA=!1,van=new sl;function Zle(){return yan??St(Wa(),".neurolink",man)}function _an(e){return e?.code==="ENOENT"}async function wan(e={}){const t=Date.now();if(!e.force&&jA&&t-BA<gan)return;const r=Zle();let n;try{n=(await qs(r)).mtimeMs}catch(o){if(!_an(o))throw o;mb={},zA=-1,BA=t,jA=!0;return}if(!e.force&&jA&&n===zA){BA=t;return}try{mb=JSON.parse(await Kr(r,"utf8"))?.records??{}}catch(o){if(e.force)throw o;mb={}}zA=n,BA=t,jA=!0}async function ban(){const e={schemaVersion:1,records:mb};await il(Zle(),e);try{zA=(await qs(Zle())).mtimeMs}catch{zA=-1}BA=Date.now(),jA=!0}function Jir(e,t){return e===null||t===null?0:Math.max(0,(t-e)*100)}function Tan(e,t,r=han){if(!e)return{drifted:!1,reason:"no_baseline"};if(t.lenderRequests>0)return{drifted:!1,reason:"attributable"};const n=Jir(e.sessionUsed,t.sessionUsed),o=Jir(e.weeklyUsed,t.weeklyUsed),s=Math.max(n,o);return s<=r?{drifted:!1,reason:"quiet"}:t.reportedCoins>0?{drifted:!1,reason:"attributable"}:{drifted:!0,unexplainedSessionPct:n,unexplainedWeeklyPct:o,detail:`the account moved ${s.toFixed(1)}% of a window since the last check-in while this node served none of it and the borrower reported no spend`}}async function Ean(e){const t=e.streakLimit??fan;return van.runExclusive(async()=>{await wan({force:!0});const r=mb[e.grantId],n=e.lenderRequestsTotal===void 0?e.observation:{...e.observation,lenderRequests:Math.max(0,e.lenderRequestsTotal-(r?.lenderRequestsTotal??0))},o=Tan(r?.lastObservation,n,e.tolerancePct),s=o.drifted?(r?.driftStreak??0)+1:0,i={grantId:e.grantId,accountLabel:e.accountLabel,lastObservation:n,...e.lenderRequestsTotal!==void 0?{lenderRequestsTotal:e.lenderRequestsTotal}:r?.lenderRequestsTotal!==void 0?{lenderRequestsTotal:r.lenderRequestsTotal}:{},driftStreak:s,...o.drifted?{lastDriftAt:n.at,lastDriftDetail:o.detail}:{...r?.lastDriftAt!==void 0?{lastDriftAt:r.lastDriftAt}:{},...r?.lastDriftDetail!==void 0?{lastDriftDetail:r.lastDriftDetail}:{}},...r?.autoPausedAt!==void 0?{autoPausedAt:r.autoPausedAt}:{}},a=s>=t&&i.autoPausedAt===void 0;return a&&(i.autoPausedAt=n.at),mb[e.grantId]=i,await ban(),{verdict:o,shouldPause:a}})}Ho(),Jr(),ii(),nr(),Oc(),Gl();var San="proxy-share-provisioning.json",Can=9e5,kan=/^[A-Za-z0-9_-]{43}$/,xan=/^[A-Za-z0-9_-]{16,128}$/,Aan=null,hb={},Yir=!1,Zir=new sl;function Xir(){return Aan??St(Wa(),".neurolink",San)}function Ian(e){if(!e||typeof e!="object")return!1;const t=e;return typeof t.grantId=="string"&&typeof t.codeChallenge=="string"&&typeof t.state=="string"&&typeof t.expiresAt=="number"&&typeof t.status=="string"}async function Qir(e={}){if(!(Yir&&!e.force)){try{const t=JSON.parse(await Kr(Xir(),"utf8"));hb=Object.fromEntries(Object.entries(t?.requests??{}).filter(r=>Ian(r[1])))}catch{hb={}}Yir=!0}}async function ear(){const e={schemaVersion:1,requests:hb};await il(Xir(),e)}function Ran(e,t=Date.now()){return e.status!=="consumed"&&e.expiresAt>t}async function Man(e){if(!kan.test(e.codeChallenge))return{ok:!1,reason:"code_challenge must be a base64url S256 digest"};if(!xan.test(e.state))return{ok:!1,reason:"state must be 16-128 base64url characters"};const t=e.now??Date.now();return Zir.runExclusive(async()=>{await Qir({force:!0});const r={schemaVersion:1,grantId:e.grantId,codeChallenge:e.codeChallenge,challengeMethod:"S256",state:e.state,requestedAt:t,expiresAt:t+Can,status:"pending"};return hb[e.grantId]=r,await ear(),{ok:!0,request:r}})}async function Pan(e,t=Date.now()){return Zir.runExclusive(async()=>{await Qir({force:!0});const r=hb[e];if(!r||!Ran(r,t))return{status:"none"};if(r.status!=="authorized"||!r.code)return{status:"pending"};const{code:n,...o}=r;return hb[e]={...o,status:"consumed",claimedAt:t},await ear(),{status:"ready",code:r.code,state:r.state}})}Ter(),Ho(),Jr(),ii(),nr(),Oc(),dA(),w$();var Dan="proxy-share-notes.json",tar="nln",Oan=null,fb={},rar=!1,Nan=new sl;function nar(){return Oan??St(Wa(),".neurolink",Dan)}async function oar(e={}){if(!(rar&&!e.force)){try{fb=JSON.parse(await Kr(nar(),"utf8"))?.notes??{}}catch{fb={}}rar=!0}}async function Lan(){const{writeJsonSnapshotAtomically:e}=await Promise.resolve().then(()=>(Gl(),Fie)),t={schemaVersion:1,notes:fb};await e(nar(),t)}function $an(e){const t=e.trim();if(t.startsWith(`${tar}_`))try{const r=JSON.parse(Buffer.from(t.slice(tar.length+1),"base64url").toString("utf8"));return typeof r?.noteId!="string"||typeof r.coins!="number"||typeof r.signature!="string"||typeof r.notAfter!="number"?void 0:r}catch{return}}async function Fan(e,t,r=Date.now()){const{signature:n,...o}=e;if(!t||!_$(o,n,t))return{status:"forged",coins:0};await oar({force:!0});const s=fb[e.noteId];return s?s.redeemedAt!==void 0?{status:"spent",coins:s.coins}:s.notAfter<=r?{status:"expired",coins:s.coins}:{status:"valid",coins:s.coins}:{status:"unknown",coins:0}}async function Uan(e){const t=e.now??Date.now(),{signature:r,...n}=e.note;if(!e.secret||!_$(n,r,e.secret))return{ok:!1,status:"forged"};const o=await Nan.runExclusive(async()=>{await oar({force:!0});const i=fb[e.note.noteId];return i?i.redeemedAt!==void 0?{status:"spent",coins:i.coins}:i.notAfter<=t?{status:"expired",coins:i.coins}:(fb[i.noteId]={...i,redeemedAt:t,redeemedByGrant:e.grantId},await Lan(),{status:"valid",coins:i.coins}):{status:"unknown",coins:0}});if(o.status!=="valid")return{ok:!1,status:o.status};const s=await per(e.grantId,o.coins);return{ok:!0,coins:o.coins,balance:s}}w$(),Oer();var Ban=64*1024,zan=32;function sar(e){try{const t=JSON.parse(e);return{errorType:t.error?.type??t.type??"stream_error",message:t.error?.message??t.message??"Upstream SSE error"}}catch{return{errorType:"stream_error",message:e.trim()||"Upstream SSE error"}}}function iar(e){if(e.event==="error")return!0;try{const t=JSON.parse(e.data);return t.type==="error"||t.error!==void 0}catch{return!1}}async function jan(e){const t=new TextDecoder,r=[];let n="",o=0;for(;o<Ban&&r.length<zan;){let s;try{s=await e.read()}catch(a){return{kind:"transport_error",chunks:r,error:a}}if(s.done){n+=t.decode();const{events:a}=aF(n),l=a.find(iar);return l?{kind:"sse_error",chunks:r,...sar(l.data)}:r.length>0?{kind:"ready",chunks:r}:{kind:"empty",chunks:r}}if(!s.value||s.value.length===0)continue;r.push(s.value),o+=s.value.byteLength,n+=t.decode(s.value,{stream:!0});const i=aF(n);n=i.remainder;for(const a of i.events){if(iar(a))return{kind:"sse_error",chunks:r,...sar(a.data)};if(a.event!=="ping"&&(a.event||a.data))return{kind:"ready",chunks:r}}}return r.length>0?{kind:"ready",chunks:r}:{kind:"empty",chunks:r}}function aar(){let e=!1,t;const r=new Promise(o=>{t=o}),n=o=>{e||(e=!0,t(o))};return{outcome:r,complete:()=>n({kind:"completed"}),fail:o=>n({kind:"upstream_error",message:o}),cancel:()=>n({kind:"client_cancelled"})}}function cF(e,t){return e.kind==="completed"&&t?{kind:"upstream_error",message:t}:e}function qan(e){const t=e.toLowerCase();return t.includes("opus")?"opus":t.includes("sonnet")?"sonnet":t.includes("haiku")?"haiku":"other"}function gb(e,t,r,n,o=!1){const s=[{provider:e.provider,model:e.model,label:`${e.provider}/${e.model??"unknown"}`}];for(const i of t)i.provider===e.provider&&i.model===e.model||s.push({provider:i.provider,model:i.model,label:`${i.provider}/${i.model}`});return o&&(t.length===0||s.length===1)&&s.push({label:"auto-provider"}),{requestedModel:r,modelTier:qan(r),attempts:s,skipped:[]}}function uF(e){if(!e)return 0;const t=parseInt(e,10);if(!Number.isNaN(t))return Math.max(1,t)*1e3;const r=new Date(e);return Number.isNaN(r.getTime())?0:Math.max(1e3,r.getTime()-Date.now())}var Gan=1,Han=20;function Xle(e){return typeof e=="number"&&Number.isInteger(e)&&e>=Gan&&e<=Han?e:void 0}Gl(),v$(),wr(),q(),pn(),iy(),rA(),Jr(),ii(),nr(),q();var Van="app_EMoamEEZ73f0CkXaXp7hrann",Wan="https://auth.openai.com/oauth/token",Kan=["openid","profile","email","offline_access"],Qle="https://chatgpt.com/backend-api/codex",Jan=`${Qle}/responses`,xhn=`${Qle}/usage`,lar=`${Qle}/models`,Yan="0.144.4",car=`codex_cli_rs/${Yan} (external; neurolink-proxy)`,Zan="codex_cli_rs",Ahn=St(Wa(),".codex","auth.json");function uar(e){try{const t=e+"=".repeat((4-e.length%4)%4),r=Buffer.from(t.replace(/-/g,"+").replace(/_/g,"/"),"base64").toString("utf8"),n=JSON.parse(r);return n&&typeof n=="object"?n:null}catch{return null}}function Xan(e){if(!e)return null;const t=e["https://api.openai.com/auth"];return t&&typeof t=="object"?t:null}function dar(e){const t=e.split(".");if(t.length!==3)return{};const r=uar(t[1]),n=Xan(r),o=typeof n?.chatgpt_account_id=="string"?n.chatgpt_account_id:void 0,s=typeof n?.chatgpt_plan_type=="string"?n.chatgpt_plan_type:void 0,i=typeof r?.exp=="number"?r.exp*1e3:void 0;return{accountId:o,planType:s,expiresAt:i}}function Qan(e){if(!e)return;const t=e.split(".");if(t.length!==3)return;const r=uar(t[1]);return typeof r?.email=="string"?r.email:void 0}function dF(e,t){return t&&t.length>0?t:dar(e).accountId}function eln(e){const t=dar(e.access_token);return{accessToken:e.access_token,refreshToken:e.refresh_token,idToken:e.id_token,accountId:e.account_id??t.accountId,expiresAt:t.expiresAt,planType:t.planType,email:Qan(e.id_token)}}async function tln(e,t={}){const r=new URLSearchParams({grant_type:"refresh_token",refresh_token:e,client_id:Van,scope:Kan.join(" ")}),n=await fetch(Wan,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json","User-Agent":car},body:r.toString(),signal:AbortSignal.timeout(t.timeoutMs??1e4)});if(!n.ok){const s=await n.text().catch(()=>"");throw Object.assign(new Error(`Codex token refresh failed: ${n.status} ${s.slice(0,200)}`),{status:n.status})}const o=await n.json();if(!o.access_token)throw new Error("Codex token refresh returned no access_token");return f.debug("Codex token refreshed"),eln({access_token:o.access_token,refresh_token:o.refresh_token??e,id_token:o.id_token})}function rln(e){const t=e?.status;return typeof t!="number"||t<400||t>=500?!1:t!==408&&t!==429}function nln(e,t=300*1e3){return e?e-t<=Date.now():!1}var ece="codex:";function tce(e){return typeof e!="number"||!Number.isFinite(e)?0:Math.min(1,Math.max(0,e/100))}function rce(e,t){if(!e)return 0;if(typeof e.resets_at=="number"&&Number.isFinite(e.resets_at)&&e.resets_at>0)return e.resets_at>4102444800?Math.floor(e.resets_at/1e3):e.resets_at;const r=typeof e.resets_in_seconds=="number"?e.resets_in_seconds:e.reset_after;return typeof r=="number"&&Number.isFinite(r)&&r>0?t+Math.floor(r):0}function nce(e){return e>=1?"rejected":"allowed"}function par(e,t,r,n){if(!r)return null;const o=tce(r.used_percent);return{kind:e,group:t,used:o,status:nce(o),resetsAt:rce(r,n),isActive:!0}}function oln(e,t=Date.now()){const r=Math.floor(t/1e3),n=e?.primary??null,o=e?.secondary??null,s=tce(n?.used_percent),i=tce(o?.used_percent),a=[],l=par("session","session",n,r),c=par("weekly_all","weekly",o,r);return l&&a.push(l),c&&a.push(c),{sessionUsed:s,sessionStatus:nce(s),sessionResetAt:rce(n,r),weeklyUsed:i,weeklyStatus:nce(i),weeklyResetAt:rce(o,r),fallbackPercentage:0,overageStatus:"rejected",lastUpdated:t,windows:a.length>0?a:void 0,windowsUpdatedAt:a.length>0?t:void 0,source:"usage-api"}}function mar(e,t=Date.now()){const r=e.get("x-codex-ratelimit")??e.get("x-codex-active-limit")??null;if(!r)return null;try{const n=JSON.parse(r),o="rate_limits"in n&&n.rate_limits?n.rate_limits:n;return oln(o,t)}catch{return null}}pn(),q();var sln=1e3;function oce(e){try{e?.()}catch(t){f.shouldLog("debug")&&f.debug("[proxy] response lifecycle observer failed",{error:t instanceof Error?t.message:String(t)})}}function iln(e,t,r){if(!e.body)return t(),oce(()=>r?.onTerminal?.({outcome:"bodyless",observedBodyBytes:0,responseChunks:0})),e;const n=e.body.getReader();let o=0,s=0,i=!1,a=!1;n.closed.then(()=>{a=!0},()=>{});const l=u=>{i||(i=!0,t(),oce(()=>r?.onTerminal?.({outcome:u,observedBodyBytes:o,responseChunks:s})))},c=new ReadableStream({async pull(u){try{const{value:d,done:m}=await n.read();if(m){l("completed"),u.close();return}u.enqueue(d),o+=d.byteLength,s+=1,s===1&&oce(()=>r?.onFirstChunk?.({observedBodyBytes:o,responseChunks:1}))}catch(d){l("stream_error"),u.error(d)}},async cancel(u){await Promise.resolve(),l(a?"completed":"client_cancelled"),await Bt(n.cancel(u),sln,"Timed out cancelling the upstream proxy response")}});return new Response(c,{status:e.status,statusText:e.statusText,headers:e.headers})}v$(),wr(),q();var har=900*1e3,far=6e4,aln=900*1e3,gar=6e4,jp="codex-oauth",lln="neurolink.codexFallback";function yar(e){if(!e||typeof e!="object")return;const t=e.code;if(typeof t=="string")return t;const r=e.cause;if(!r||typeof r!="object")return;const n=r.code;return typeof n=="string"?n:void 0}function cln(e){const t=yar(e);return t==="ENOTFOUND"||t==="EAI_AGAIN"?"shared_provider_transport":"connection_transport"}function pF(e,t){return Xn(e).slice(0,200)||t}var sce=new Map;async function uln(e,t,r,n){const o=sce.get(e);if(o)return o;const s=(async()=>{const i=await r.peekTokens(e).catch(()=>null),a=i?.refreshToken??t,l=await n(a),c={accessToken:l.accessToken,refreshToken:l.refreshToken??a,expiresAt:l.expiresAt??i?.expiresAt??Date.now()+36e5};return i&&await r.saveTokens(e,{...c,tokenType:"Bearer",...i.scope?{scope:i.scope}:{}}),c})().finally(()=>{sce.delete(e)});return sce.set(e,s),s}async function ice(e,t){return uln(e,t,al,tln)}var dln=new Set(["host","connection","content-length","transfer-encoding","cookie","proxy-authorization","authorization","x-api-key","chatgpt-account-id","accept-encoding"]);function mF(e,t){return new Response(JSON.stringify({error:{type:"proxy_error",message:t}}),{status:e,headers:{"content-type":"application/json"}})}async function _ar(){const e=await al.listByPrefix(ece),[t,r]=await Promise.all([AA(),hle()]),n=Date.now(),o=[];for(const s of e){if(await al.isDisabled(s))continue;const i=await al.loadTokens(s);if(!i||i.tokenType!=="Bearer")continue;let a=i.accessToken,l=i.expiresAt;if(nln(l)&&i.refreshToken)try{const d=await ice(s,i.refreshToken);a=d.accessToken,l=d.expiresAt??l}catch(d){f.debug(`Codex proactive refresh failed for ${s.slice(ece.length)}: ${d instanceof Error?d.message:String(d)}`)}const c=t[s],u=c&&c.coolingUntil>n;o.push({key:s,label:s.slice(ece.length)||s,token:a,refreshToken:i.refreshToken,expiresAt:l,accountId:dF(a),quota:r[s],coolingUntil:u?c.coolingUntil:void 0,coolingReason:c?.reason,expiredCooldownUntil:c&&!u?c.coolingUntil:void 0})}return o}function war(e,t){return[...e].sort((r,n)=>{const o=r.coolingUntil!==void 0&&r.coolingUntil>t,s=n.coolingUntil!==void 0&&n.coolingUntil>t;if(o!==s)return o?1:-1;const i=r.quota?r.quota.sessionUsed:-1,a=n.quota?n.quota.sessionUsed:-1;return i-a})}function bar(e,t){const r={};for(const[o,s]of Object.entries(e)){const i=o.toLowerCase();dln.has(i)||(r[i]=s)}r.authorization=`Bearer ${t.token}`;const n=dF(t.token,t.accountId);return n&&(r["chatgpt-account-id"]=n),r["content-type"]="application/json",r["user-agent"]||(r["user-agent"]=car),r.originator||(r.originator=Zan),r.accept||(r.accept="text/event-stream"),r}function pln(e,t,r){const n=r+far;if(e){if(e.weeklyStatus==="rejected"&&e.weeklyResetAt>0)return{coolingUntil:Math.max(e.weeklyResetAt*1e3,n),reason:"weekly"};if(e.sessionStatus==="rejected"&&e.sessionResetAt>0)return{coolingUntil:Math.max(e.sessionResetAt*1e3,n),reason:"session"}}const o=Math.min(aln,Math.max(t,far));return{coolingUntil:r+o,reason:"transient"}}function mln(e,t,r,n){e.responseHeaders||(e.responseHeaders={}),e.responseHeaders["x-neurolink-account"]=t.label,e.responseHeaders["x-neurolink-account-type"]="codex-oauth",e.responseHeaders["x-neurolink-served-by"]="codex",e.responseHeaders["x-neurolink-attempt"]=String(r),e.responseHeaders["x-neurolink-quota-source"]=n?"live":"none",n&&(e.responseHeaders["x-neurolink-quota-session-left-pct"]=String(Math.round((1-n.sessionUsed)*100)),e.responseHeaders["x-neurolink-weekly-left-pct"]=String(Math.round((1-n.weeklyUsed)*100)))}async function Tar(e){const t=Date.now(),r=e.body??{},n=JSON.stringify(r),o=typeof r.model=="string"?r.model:"-",s=e.metadata?.[lln]===!0,i=(b,T,k={})=>Rh({timestamp:new Date().toISOString(),requestId:e.requestId,method:e.method,path:e.path,model:o,stream:!0,toolCount:Array.isArray(r.tools)?r.tools.length:0,account:b?.label??"",...b?{accountKey:b.key}:{},accountType:b?jp:"",provider:"openai",...cb(e.headers),responseStatus:T,responseTimeMs:Date.now()-t,...k});let a=!1;const l=async(b,T,k={})=>{s||a||(a=!0,T>=400?Uw(T,b?.label,b?jp:void 0,{requestId:e.requestId,...b?{accountKey:b.key}:{},errorType:k.errorType,terminalOutcome:k.terminalOutcome??"handler_error",message:k.errorMessage,errorCode:k.errorCode}):iA(b?.label,b?jp:void 0),await i(b,T,k))},c=(b,T,k,x,I={})=>{Air({timestamp:new Date().toISOString(),requestId:e.requestId,attempt:T,method:e.method,path:e.path,model:o,stream:!0,toolCount:Array.isArray(r.tools)?r.tools.length:0,account:b.label,accountKey:b.key,accountType:jp,provider:"openai",responseStatus:x,responseTimeMs:Date.now()-t,attemptDurationMs:Date.now()-k,...I}).catch(()=>{})},u=await _ar();if(u.length===0)return await l(void 0,401,{errorType:"no_accounts",errorMessage:"No Codex accounts"}),mF(401,"No Codex accounts configured. Run `neurolink auth login codex`.");const d=Date.now(),m=war(u,d),h=m.filter(b=>!(b.coolingUntil!==void 0&&b.coolingUntil>d));if(h.length===0){const b=m.reduce((k,x)=>x.coolingUntil===void 0?k:k===void 0?x.coolingUntil:Math.min(k,x.coolingUntil),void 0),T=b?Math.max(1,Math.ceil((b-d)/1e3)):60;return await l(void 0,429,{errorType:"all_accounts_cooling",errorMessage:"All Codex accounts are rate-limited"}),new Response(JSON.stringify({error:{type:"rate_limit_error",message:"All Codex accounts are currently rate-limited"}}),{status:429,headers:{"content-type":"application/json","retry-after":String(T)}})}let g=0,y="All Codex accounts failed",v=502,_;for(const b of h){let T=!1;for(;;){g+=1;const k=Date.now();_=b,Ty(b.label,jp);let x;try{x=await fetch(Jan,{method:"POST",headers:bar(e.headers,b),body:n,signal:AbortSignal.timeout(har)})}catch(A){f.debug(`Codex upstream fetch failed (${b.label}): ${Xn(A instanceof Error?A.message:String(A))}`);const P=pF(A instanceof Error?A.message:String(A),"Codex upstream request failed"),L=yar(A),N=cln(A);$r(b.label,jp,502),c(b,g,k,502,{errorType:"network_error",errorMessage:P,...L?{errorCode:L}:{},transportScope:N,retryable:!0}),y="Codex upstream request failed",v=502;break}if(x.ok){const A=mar(x.headers);A&&Ry(b.key,A).catch(()=>{}),b.expiredCooldownUntil!==void 0&&xy(b.key,b.expiredCooldownUntil).catch(()=>{}),mln(e,b,g,A),c(b,g,k,x.status);const P={"content-type":x.headers.get("content-type")??"text/event-stream","cache-control":"no-cache",connection:"keep-alive",...e.responseHeaders??{}};if(!x.body)return await l(b,x.status,{terminalOutcome:"bodyless"}),new Response(x.body,{status:x.status,headers:P});const{stream:L,usage:N}=rsn(),D=new Response(x.body.pipeThrough(L),{status:x.status,headers:P});return iln(D,()=>{},{onTerminal:({outcome:O})=>{N.then(F=>{const $=F?{inputTokens:F.inputTokens,outputTokens:F.outputTokens,cacheReadTokens:F.cacheReadTokens,cacheCreationTokens:F.cacheCreationTokens}:{};return O==="completed"||O==="bodyless"?l(b,x.status,{terminalOutcome:O,...$}):l(b,O==="client_cancelled"?499:502,{errorType:O==="client_cancelled"?"client_cancelled":"stream_error",errorMessage:O==="client_cancelled"?"Client cancelled Codex stream":"Codex upstream stream failed",terminalOutcome:O,...$})}).catch(()=>{})}})}const I=await x.text().catch(()=>"");if((x.status===401||x.status===403)&&!T&&b.refreshToken){const A=pF(I,"Codex authentication rejected upstream");$r(b.label,jp,x.status),c(b,g,k,x.status,{errorType:"authentication_error",errorMessage:A,retryable:!0}),T=!0;const P={accessToken:b.token,refreshToken:b.refreshToken,expiresAt:b.expiresAt??0};try{const L=await ice(b.key,b.refreshToken);b.token=L.accessToken,b.refreshToken=L.refreshToken??b.refreshToken,b.expiresAt=L.expiresAt??b.expiresAt,b.accountId=dF(L.accessToken);continue}catch(L){if(rln(L)){await al.markDisabledIfCurrent(b.key,P,"refresh_invalid")&&f.always(`[proxy] codex account=${b.label} disabled until re-authentication. Run: neurolink auth login codex --label ${b.label}`),v=401,y="Codex token refresh failed; re-login required";break}await Td(b.key,Date.now()+gar,"auth").catch(()=>{}),f.debug(`[proxy] codex account=${b.label} refresh failed transiently; cooling and rotating`),v=503,y="Codex token refresh temporarily unavailable";break}}if(x.status===429){const A=mar(x.headers);A&&Ry(b.key,A).catch(()=>{});const P=uF(x.headers.get("retry-after")),L=pln(A,P,Date.now());await Td(b.key,L.coolingUntil,L.reason).catch(()=>{});const N=L.reason==="transient"?"transient":"quota",D=pF(I,"Codex account rate-limited");$r(b.label,jp,x.status,N),c(b,g,k,x.status,{errorType:"rate_limit_error",errorMessage:D,retryable:!0,rateLimitKind:N,cooldownReason:L.reason}),v=429,y="Codex account rate-limited";break}(x.status===401||x.status===403)&&await Td(b.key,Date.now()+gar,"auth").catch(()=>{});const M=pF(I,"Codex error"),R=x.status===401||x.status===403?"authentication_error":"api_error";$r(b.label,jp,x.status),c(b,g,k,x.status,{errorType:R,errorMessage:M,retryable:x.status>=500}),v=x.status>=500?502:x.status,y=M;break}}return await l(_,v,{errorType:"all_accounts_failed",errorMessage:y}),mF(v,y)}async function hln(e){const t=await _ar();if(t.length===0)return mF(401,"No Codex accounts configured. Run `neurolink auth login codex`.");const r=Date.now(),n=war(t,r),o=d=>d.coolingUntil!==void 0&&d.coolingUntil>r,s=[...n.filter(d=>!o(d)),...n.filter(o)],a=new URLSearchParams(e.query??{}).toString(),l=a?`${lar}?${a}`:lar;let c=502,u="Codex model discovery upstream failed";for(const d of s){let m=!1;for(;;){let h;try{h=await fetch(l,{method:"GET",headers:bar(e.headers??{},d),signal:AbortSignal.timeout(har)})}catch(v){c=502,u=`Codex model discovery upstream failed: ${v instanceof Error?v.message:String(v)}`;break}if(h.status===401||h.status===403){if(!m&&d.refreshToken){m=!0;try{const v=await ice(d.key,d.refreshToken);d.token=v.accessToken,d.refreshToken=v.refreshToken??d.refreshToken,d.expiresAt=v.expiresAt??d.expiresAt,d.accountId=dF(v.accessToken);continue}catch{c=401,u="Codex token refresh failed; re-login required";break}}c=h.status,u="Codex model discovery rejected upstream";break}const g=await h.text(),y=h.headers.get("content-type")??"application/json";return new Response(g,{status:h.status,headers:{"content-type":y}})}}return mF(c,u)}function fln(e=""){return{prefix:`${e}/backend-api/codex`,routes:[{method:"POST",path:`${e}/backend-api/codex/responses`,description:"Codex ChatGPT-backend Responses API (account pool)",handler:t=>Tar(t)},{method:"GET",path:`${e}/backend-api/codex/models`,description:"Codex model discovery, relayed upstream (account pool)",handler:t=>hln(t)}]}}var hF=new Set(["cookie","proxy-authorization","host","connection","content-length","transfer-encoding"]),ace="proxy/internal",lce="internal";function Ear(e,t){return e?t==="codex-oauth"?{accountKey:e.startsWith("codex:")?e:`codex:${e}`,provider:"openai"}:t==="oauth"||t==="api_key"||t==="passthrough"?{accountKey:t==="passthrough"?e:eA(e),provider:"anthropic"}:{}:{}}var Mh=0,Sar=0,qA=5,fF=2,cce=[250,1e3],Car=[250,500,1e3,2e3],uce=1,gln=120*1e3,dce=2,kar=3e4,xar=11520*60*1e3,Aar=5e3,yln=900*1e3,Iar=900*1e3,vln=3e4,_ln=300*1e3,GA=900*1e3,Rar;function pce(e,t){return Rar??=new PS({headersTimeout:GA,bodyTimeout:GA}),fetch(e,{...t,dispatcher:Rar})}var Jl=new Map,HA=new Gon,yb=new Von,Mar=900*1e3,Par=new Map,Dar=new Map,gF=new Map,wln={release:()=>{}};function Oar(e){let t=gF.get(e);return t||(t={active:0,waiters:[]},gF.set(e,t)),t}function mce(e,t){for(;t.waiters.length>0&&t.active<t.waiters[0].capacity;){const r=t.waiters.shift();if(!r)return;t.active+=1,r.resolve(Nar(e,t))}}function Nar(e,t){let r=!1;return{release:()=>{r||(r=!0,t.active=Math.max(0,t.active-1),mce(e,t),Lar(e,t))}}}function Lar(e,t){t.active===0&&t.waiters.length===0&&gF.delete(e)}function bln(e,t){const r=Xle(t);if(r===void 0)return wln;const n=Oar(e);if(!(n.waiters.length>0||n.active>=r))return n.active+=1,Nar(e,n)}function Tln(e,t){const r=Xle(t);if(r===void 0)return!0;const n=gF.get(e);return!n||n.waiters.length===0&&n.active<r}function Eln(e,t){const r=Xle(t);if(r===void 0)throw new Error("Account admission queue requires an explicit capacity");const n=Oar(e);let o=!0,s,i;const a=new Promise(c=>{i=c}),l={capacity:r,resolve:c=>{o=!1,s=c,i(c)}};return n.waiters.push(l),mce(e,n),{accountKey:e,promise:a,cancel:()=>{if(s){const u=s;s=void 0,u.release();return}if(!o)return;o=!1;const c=n.waiters.indexOf(l);c>=0&&(n.waiters.splice(c,1),mce(e,n)),Lar(e,n)}}}async function Sln(e,t,r,n=Far){const o=[...new Set(e)].map(i=>Eln(i,t));let s;try{return await Bt(WOe(Promise.race(o.map(i=>i.promise.then(a=>s?(a.release(),new Promise(()=>{})):(s=i.accountKey,{accountKey:i.accountKey,lease:a})))),r),n,`Account admission timed out after ${n}ms`)}catch(i){if(r?.aborted)throw i;return}finally{for(const i of o)i.accountKey!==s&&i.cancel()}}var $ar=!1,hce=6e4,Far=9e4,Cln=12e4,kln=250,xln=15e3;function Dy(e,t,r){t<=1||e===r&&(Mh=(Mh+1)%t)}function Uar(e,t){if(!t)return 0;const r=e.findIndex(n=>zQt(n.key,t));return r>=0?r:0}function Aln(e,t){if(e.length<=1)return;const r=Uar(e,t);if(Mh===r)return;const n=e[r],o=Jl.get(n.key);if((!o||!o.coolingUntil||Date.now()>=o.coolingUntil)&&(Mh=r,o?.coolingUntil)){const s=o.coolingUntil;o.coolingUntil=void 0,o.coolingReason=void 0,xy(n.key,s).catch(()=>{}),f.always(`[proxy] home primary account=${n.label} cooling expired, resetting primaryAccountIndex to ${r}`)}}function Bar(e){const t=Jl.get(e);return!!t?.coolingUntil&&Date.now()<t.coolingUntil}function Iln(e,t,r=Date.now()){let n=Par.get(e);if(!n||r>=n.coolingUntil?(n={coolingUntil:t,retriesClaimed:0},Par.set(e,n)):t>n.coolingUntil&&(n.coolingUntil=t),!(n.retriesClaimed>=dce))return n.retriesClaimed+=1,n.retriesClaimed}function Rln(e,t,r=Date.now()){if(t<=r)return 0;if(t-r>Far)return;let n=Dar.get(e);!n||r>=n.coolingUntil?(n={coolingUntil:t,nextAdmissionAt:t},Dar.set(e,n)):t>n.coolingUntil&&(n.coolingUntil=t,n.nextAdmissionAt=Math.max(n.nextAdmissionAt,t));const o=Math.max(r,n.coolingUntil,n.nextAdmissionAt);if(!(o-n.coolingUntil>xln))return n.nextAdmissionAt=o+kln,o-r}async function Mln(e){const t=Date.now()+Cln;for(;Date.now()<t;){const r=e.filter(i=>!Bar(i.key));if(r.length>0)return r;const n=Date.now(),o=e.map(i=>({account:i,state:dl(i.key)})).filter(({state:i})=>i.coolingReason==="transient"&&i.coolingUntil!==void 0&&i.coolingUntil>n).sort((i,a)=>(i.state.coolingUntil??Number.POSITIVE_INFINITY)-(a.state.coolingUntil??Number.POSITIVE_INFINITY))[0];if(!o?.state.coolingUntil)return[];const s=Rln(o.account.key,o.state.coolingUntil,n);if(s===void 0||n+s>t)return[];f.always(`[proxy] all usable accounts are transiently cooling; queueing request for account=${o.account.label} in ${s}ms`),await Gp(s)}return[]}function $i(e,t){if(!e||e<=0)return;const r=e>4102444800?e:e*1e3;return r>t?r:void 0}function VA(e,t){try{const r=t.poolAccounts?Qon(t.poolAccounts.map(o=>{const s=Jl.get(o.key);return{...s?.coolingUntil!==void 0?{coolingUntil:s.coolingUntil}:{},...s?.quota?{quota:s.quota}:{}}})):void 0,n=Xon({...t.upstreamHeaders?{upstreamHeaders:t.upstreamHeaders}:{},context:{quota:t.quota??null,source:t.source,...t.account?{accountLabel:t.account.label}:{},...t.accountType??t.account?.type?{accountType:t.accountType??t.account?.type}:{},...t.servedBy?{servedBy:t.servedBy}:{},...t.attempt!==void 0?{attempt:t.attempt}:{},...t.accountState?.coolingUntil!==void 0?{coolingUntil:t.accountState.coolingUntil}:{},...t.accountState?.coolingReason?{coolingReason:t.accountState.coolingReason}:{},...r?{pool:r}:{}}});e.responseHeaders={...e.responseHeaders??{},...Qar(n)}}catch(r){f.debug(`[proxy] failed to publish limit headers: ${r instanceof Error?r.message:String(r)}`)}}function yF(e,t,r){const n=Math.min(xar,(r&&Gsr[r])??xar);return Math.min(Math.max(e,t+Aar),t+n)}function fce(e,t,r,n=e?.unifiedStatus,o=Oy){if(e&&e.weeklyStatus==="rejected"){const a=$i(e.weeklyResetAt,r)??(t>0?r+t:r+hce);return{reason:"weekly",coolingUntil:yF(a,r,"weekly"),rotateImmediately:!0}}const s=wF(e,o);if(e&&e.sessionStatus==="rejected"&&!s){const a=$i(e.sessionResetAt,r)??(t>0?r+t:r+hce);return{reason:"session",coolingUntil:yF(a,r,"session"),rotateImmediately:!0}}if(n?.trim().toLowerCase()==="rejected"&&!s){const a=t>0?r+t:r+Iar;return{reason:"unified",coolingUntil:yF(a,r,"unified"),rotateImmediately:!0}}const i=t>0?t:hce;return{reason:"transient",coolingUntil:r+Math.max(Aar,Math.min(i,yln)),rotateImmediately:!1}}function gce(e,t){return Math.max(0,Math.round((e-t)/6e4))}function yce(e,t,r,n=Oy){const o=wF(t,n);let s,i;if(t.weeklyStatus==="rejected"&&(s=$i(t.weeklyResetAt,r),i="weekly"),s===void 0&&o&&e.coolingUntil&&(e.coolingReason==="session"||e.coolingReason==="unified")){const l=e.coolingUntil;return e.coolingUntil=void 0,e.coolingReason=void 0,f.always("[proxy] clearing subscription cooldown because Anthropic explicitly permits overage"),{kind:"cleared",coolingUntil:l}}if(s===void 0&&t.sessionStatus==="rejected"&&!o?(s=$i(t.sessionResetAt,r),i="session"):s===void 0&&t.unifiedStatus==="rejected"&&!o&&(s=r+Iar,i="unified"),s===void 0){if(!!e.coolingUntil&&(e.coolingReason==="weekly"&&t.weeklyStatus==="allowed"||e.coolingReason==="session"&&t.sessionStatus==="allowed"||e.coolingReason==="unified"&&t.unifiedStatus==="allowed")&&e.coolingUntil){const c=e.coolingUntil,u=e.coolingReason;return e.coolingUntil=void 0,e.coolingReason=void 0,f.always(`[proxy] clearing ${u} cooldown from fresh provider quota`),{kind:"cleared",coolingUntil:c}}return null}const a=yF(s,r,i);return!e.coolingUntil||a>e.coolingUntil?(e.coolingUntil=a,e.coolingReason=i,f.always(`[proxy] proactively cooling account (${i}) ~${gce(a,r)}m from success-response quota (status rejected)`),{kind:"cooled",coolingUntil:a,coolingReason:i??"unified"}):null}async function Pln(e){try{const[t,r]=await Promise.all([hle(),AA()]),n=Date.now();for(const o of e){const s=dl(o.key);s.quota||(s.quota=t[o.key]??t[o.label]);const i=r[o.key];i?.coolingUntil>n&&(!s.coolingUntil||i.coolingUntil>s.coolingUntil)&&(s.coolingUntil=i.coolingUntil,s.coolingReason=i.reason)}}catch{}}var Dln=15e3,zar=new Map,vF=null,Oln=4;async function jar(e,t,r,n){if(t.ok===!1)return null;const o=dl(e.key),s=rir(t.usage,{now:r,prior:o.quota??n??null});if(!s)return null;if(s.lastUpdated<(o.quota?.lastUpdated??0))return o.quota??null;o.quota=Ay(o.quota,s);const i=yce(o,s,Date.now());return i?.kind==="cooled"?await Td(e.key,i.coolingUntil,i.coolingReason).catch(()=>{}):i?.kind==="cleared"&&await xy(e.key,i.coolingUntil).catch(()=>{}),await Ry(e.key,s).catch(()=>{}),s}async function qar(e){const t=await Uon(e);return t.ok===!1||rir(t.usage,{now:Date.now(),prior:Jl.get(e.key)?.quota??null})?t:{ok:!1,reason:"parse",error:"usage payload had no recognizable limit windows"}}async function _F(e,t){const r=await HA.run(e,t,qar);r.kind!=="completed"||r.result.ok===!1||await jar(e,r.result,r.startedAt)}async function vce(e={}){const t=Date.now(),r=await eir(e.accountAllowlist),n=e.accountFilter?r.filter(c=>c.label===e.accountFilter||c.key===e.accountFilter):r,o=await hle().catch(()=>({})),s=(c,u,d,m)=>{const h=Jl.get(c.key),g={account:c.label,key:c.key,type:c.type,status:u,quota:d??h?.quota??o[c.key]??o[c.label]??null};return m!==void 0&&(g.error=m),h?.coolingUntil&&h.coolingUntil>Date.now()&&(g.coolingUntil=h.coolingUntil,h.coolingReason&&(g.coolingReason=h.coolingReason)),g};if(e.snapshotOnly)return{fetchedAt:t,snapshot:!0,results:n.map(c=>s(c,"snapshot",null)),refreshMetrics:HA.getMetrics()};const i=new Array(n.length);let a=0;const l=async()=>{for(;;){const c=a++;if(c>=n.length)return;const u=n[c];if(u.type!=="oauth"){i[c]=s(u,"skipped_api_key",null);continue}const d=zar.get(u.key)??0;if(Date.now()-d<Dln){i[c]=s(u,"throttled",null);continue}zar.set(u.key,Date.now());try{const m=await HA.run(u,`manual:${u.key}`,qar,{force:!0});if(m.kind!=="completed"){i[c]=s(u,"throttled",null);continue}const h=m.result;if(h.ok===!1){i[c]=s(u,"error",null,h.error);continue}const g=await jar(u,h,m.startedAt,o[u.key]??o[u.label]??null);if(!g){i[c]=s(u,"error",null,"usage payload had no recognizable limit windows");continue}i[c]=s(u,"refreshed",g)}catch(m){i[c]=s(u,"error",null,m instanceof Error?m.message:String(m))}}};return await Promise.all(Array.from({length:Math.min(Oln,n.length||1)},()=>l())),{fetchedAt:t,snapshot:!1,results:i,refreshMetrics:HA.getMetrics()}}function _ce(){const e=(process.env.NEUROLINK_PROXY_QUOTA_ROUTING??"").toLowerCase();return e!=="off"&&e!=="false"&&e!=="0"}function wce(){const e=Number(process.env.NEUROLINK_PROXY_SESSION_SOFT_LIMIT??"");return Number.isFinite(e)&&e>0&&e<=1?e:.97}function WA(){const e=Number(process.env.NEUROLINK_PROXY_SESSION_RESET_TOLERANCE_MS??"");return Number.isInteger(e)&&e>0?e:900*1e3}var Oy="auto";function bce(e){e!==void 0&&(Oy=e)}function Nln(){return Oy}function wF(e,t=Oy){return t==="never"?!1:Vsr(e)}var Lln=4;function bF(e){return e.toLowerCase().replace(/[^a-z0-9]/g,"")}function $ln(e){const t=bF(e);return t.startsWith("claude")?t.slice(6):t}function Fln(e,t,r){if(e.scopeModelId&&bF(H$(e.scopeModelId))===r)return Number.MAX_SAFE_INTEGER;if(!e.scopeModel)return null;const n=$ln(e.scopeModel);return n.length<Lln||!t.includes(n)?null:n.length}function Gar(e,t){return t.updatedAt??e.windowsUpdatedAt??e.lastUpdated}function Har(e,t,r=Date.now()){if(!e?.windows?.length||!t)return null;const n=bF(t);if(!n)return null;const o=bF(H$(t));let s=null,i=-1,a=-1;for(const l of e.windows){if(r-Gar(e,l)>Mar)continue;const c=Fln(l,n,o);if(c===null)continue;const u=Gar(e,l);(c>i||c===i&&u>a)&&(s=l,i=c,a=u)}return s}function Uln(e,t,r=Date.now(),n=Oy){if(!t||e.length===0)return{eligible:e,exhaustion:null};const o=[],s=[];let i;for(const l of e){const c=Jl.get(l.key)?.quota,u=Har(c,t,r),d=u?$i(u.resetsAt,r):void 0;if(!(u!==null&&d!==void 0&&((u.status??"").trim().toLowerCase()==="rejected"||(u.used??0)>=1)&&!wF(c,n))||!u){o.push(l);continue}s.push({label:l.label,window:u}),i??=c?.overageDisabledReason}if(o.length>0||s.length===0)return{eligible:o,exhaustion:null};const a=Math.min(...s.map(l=>$i(l.window.resetsAt,r)??Number.POSITIVE_INFINITY));return{eligible:o,exhaustion:{model:t,scopeModel:s[0]?.window.scopeModel??H$(t),earliestResetMs:a,accounts:s.map(l=>l.label),...i?{overageDisabledReason:i}:{}}}}function TF(e,t,r,n,o,s=Oy){const i=Jl.get(e),a=i?.quota,l=a&&Number.isFinite(a.lastUpdated)?a.lastUpdated:null,c=l===null?null:Math.max(0,t-l),u=HA.getState(e),d=c!==null&&c>Mar,m=G=>G.trim().toLowerCase(),h=Vsr(a),g=[a?.unifiedStatus,a?.sessionStatus,a?.weeklyStatus].filter(G=>!!G?.trim()),y=d&&!!a&&!h&&g.some(G=>m(G)!=="allowed"),v=a?d?y?"refresh_due":"stale_known":"fresh":"unknown",_=y?void 0:a,b=!!i?.coolingUntil&&t<i.coolingUntil,T=$i(_?.weeklyResetAt,t),k=$i(_?.sessionResetAt,t),x=k!==void 0,I=T!==void 0,M=_?x?_.sessionUsed??0:0:null,R=_?I?_.weeklyUsed??null:0:null,A=_?x?_.sessionStatus??"unknown":"allowed":null,P=_?I?_.weeklyStatus??"unknown":"allowed":null,L=wF(_,s),N=!L&&(A==="rejected"||A==="throttled"||P==="rejected"||P==="throttled"||_?.unifiedStatus?.trim().toLowerCase()==="rejected"||x&&(M??0)>=1||I&&(R??0)>=1),D=!N&&!L&&x&&(M??0)>=r,O=N||D,F=Har(_,o,t),$=F?$i(F.resetsAt,t):void 0,B=$!==void 0,z=F?B?F.used:0:null,j=F?B?F.status??"unknown":"allowed":null,K=!d&&B&&(z??0)>=r;return{usable:!b&&!N&&(j!=="rejected"||L),saturated:O,scopedModel:F?.scopeModel??null,scopedStatus:j,scopedUsed:z,scopedReset:$??Number.POSITIVE_INFINITY,scopedUsedForSort:z??-1,scopedSaturated:K,hasQuota:!!a,quotaEvidenceRank:v==="fresh"||v==="stale_known"?0:v==="refresh_due"?1:2,quotaStale:d,quotaFreshness:v,refreshNeeded:v==="unknown"||v==="refresh_due",refreshReason:v==="unknown"?"startup_unknown":v==="refresh_due"?"ambiguous_snapshot":null,refreshInFlight:u.inFlight,lastRefreshAttemptAt:u.lastAttemptAt??null,lastRefreshSuccessAt:u.lastSuccessAt??null,nextRefreshEligibleAt:u.nextEligibleAt??null,saturationKind:N?"hard":D?"soft":"none",softLimitOverrideReason:L&&x&&(M??0)>=r?"overage":null,quotaLastUpdated:l,quotaAgeMs:c,coolingActive:b,coolingReason:i?.coolingReason??null,coolingUntil:i?.coolingUntil??0,unifiedStatus:_?.unifiedStatus??null,fallbackStatus:_?.fallbackStatus??null,upgradePaths:_?.upgradePaths??null,overageEligible:L,overageStatus:_?.overageStatus??null,sessionStatus:A,sessionUsed:M,sessionResetBucket:x?Math.floor(k/n):Number.POSITIVE_INFINITY,sessionReset:k??Number.POSITIVE_INFINITY,weeklyStatus:P,weeklyReset:T??Number.POSITIVE_INFINITY,weeklyUsed:R,weeklyUsedForSort:R??-1}}function Var(e,t,r,n){const o=r.get(e.key),s=r.get(t.key);if(!o||!s)return[0,"insertion_order"];if(o.usable!==s.usable)return[o.usable?-1:1,"availability"];if(!o.usable&&!s.usable){const i=o.coolingUntil||Number.POSITIVE_INFINITY,a=s.coolingUntil||Number.POSITIVE_INFINITY;return[i===a?0:i-a,i===a?"insertion_order":"cooldown_recovery"]}if(o.quotaEvidenceRank!==s.quotaEvidenceRank)return[o.quotaEvidenceRank-s.quotaEvidenceRank,"quota_evidence"];if(o.saturated!==s.saturated)return[o.saturated?1:-1,"session_headroom"];if(o.scopedSaturated!==s.scopedSaturated)return[o.scopedSaturated?1:-1,"scoped_headroom"];if(o.saturated&&s.saturated){if(o.sessionResetBucket!==s.sessionResetBucket)return[o.sessionResetBucket-s.sessionResetBucket,"session_reset"];if(o.weeklyReset!==s.weeklyReset)return[o.weeklyReset-s.weeklyReset,"weekly_reset"]}else{if(o.weeklyReset!==s.weeklyReset)return[o.weeklyReset-s.weeklyReset,"weekly_reset"];if(o.sessionResetBucket!==s.sessionResetBucket)return[o.sessionResetBucket-s.sessionResetBucket,"session_reset"]}return o.scopedUsed!==null&&s.scopedUsed!==null&&o.scopedUsedForSort!==s.scopedUsedForSort?[s.scopedUsedForSort-o.scopedUsedForSort,"scoped_utilization"]:o.weeklyUsedForSort!==s.weeklyUsedForSort?[s.weeklyUsedForSort-o.weeklyUsedForSort,"weekly_utilization"]:n&&e.key===n!=(t.key===n)?[e.key===n?-1:1,"configured_primary"]:[0,"insertion_order"]}function Bln(e,t,r,n,o,s){const i=new Map(e.map(a=>[a.key,TF(a.key,t,n,o,s)]));return{orderedAccounts:[...e].sort((a,l)=>Var(a,l,i,r)[0]),metricsByKey:i}}function zln(e,t,r,n){for(const u of e){if(u.type!=="oauth")continue;const d=n?.get(u.key)??TF(u.key,Date.now(),r,WA());d.quotaFreshness==="unknown"?_F(u,`startup-unknown:${u.key}`).catch(m=>{f.debug(`[proxy] background quota discovery failed account=${u.label}: ${Sd(m)}`)}):d.quotaFreshness==="refresh_due"&&_F(u,`ambiguous:${d.quotaLastUpdated??0}`).catch(m=>{f.debug(`[proxy] ambiguous quota refresh failed account=${u.label}: ${Sd(m)}`)})}const o=t[0],s=t[1];if(!o||!s||s.type!=="oauth")return;const i=Jl.get(o.key)?.quota;if(!i)return;const a=Math.max(0,r-.05);if(!((i.sessionUsed??0)>=a||(i.weeklyUsed??0)>=.9))return;const c=["handoff",o.key,i.sessionResetAt??0,i.weeklyResetAt??0,s.key].join(":");_F(s,c).catch(u=>{f.debug(`[proxy] quota handoff prewarm failed account=${s.label}: ${Sd(u)}`)})}function jln(e,t,r,n){!t||t.type!=="oauth"||TF(t.key,Date.now(),n,WA()).quotaFreshness==="fresh"||_F(t,`hard-handoff:${e.key}:${r}:${t.key}`).catch(s=>{f.debug(`[proxy] hard-handoff quota refresh failed account=${t.label}: ${Sd(s)}`)})}function qln(e){const{accounts:t,orderedAccounts:r,metricsByKey:n,evaluatedAt:o,strategy:s,primaryKey:i,quotaRoutingEnabled:a,quotaOrdered:l,sessionSoftLimit:c,sessionResetToleranceMs:u,rotationOffset:d}=e,m=new Map(t.map((b,T)=>[b.key,T])),h=!!i&&t.some(b=>b.key===i),g=[];for(const b of r){const T=n.get(b.key);if(!T){f.warn(`[proxy] routing evidence omitted because metrics are missing for account=${b.label}`);return}g.push({account:b.label,accountType:b.type,sourceIndex:m.get(b.key)??g.length,rank:g.length,configuredPrimary:!!i&&b.key===i,usable:T.usable,saturated:T.saturated,quotaObserved:T.hasQuota,quotaStale:T.quotaStale,quotaFreshness:T.quotaFreshness,refreshNeeded:T.refreshNeeded,refreshReason:T.refreshReason,refreshInFlight:T.refreshInFlight,lastRefreshAttemptAt:T.lastRefreshAttemptAt,lastRefreshSuccessAt:T.lastRefreshSuccessAt,nextRefreshEligibleAt:T.nextRefreshEligibleAt,saturationKind:T.saturationKind,softLimitOverrideReason:T.softLimitOverrideReason,quotaLastUpdated:T.quotaLastUpdated,quotaAgeMs:T.quotaAgeMs,coolingActive:T.coolingActive,coolingReason:T.coolingReason,coolingUntil:T.coolingUntil>0&&Number.isFinite(T.coolingUntil)?T.coolingUntil:null,unifiedStatus:T.unifiedStatus,fallbackStatus:T.fallbackStatus,upgradePaths:T.upgradePaths,overageEligible:T.overageEligible,overageStatus:T.overageStatus,sessionStatus:T.sessionStatus,sessionUsed:T.sessionUsed,sessionResetAt:Number.isFinite(T.sessionReset)?T.sessionReset:null,sessionResetBucket:Number.isFinite(T.sessionResetBucket)?T.sessionResetBucket:null,weeklyStatus:T.weeklyStatus,weeklyUsed:T.weeklyUsed,weeklyResetAt:Number.isFinite(T.weeklyReset)?T.weeklyReset:null,scopedModel:T.scopedModel,scopedStatus:T.scopedStatus,scopedUsed:T.scopedUsed,scopedResetAt:Number.isFinite(T.scopedReset)?T.scopedReset:null})}const y=r[0];let v,_;return r.length===1?(v="single_account",_="single_account"):l?(v="quota",_=Var(r[0],r[1],n,i)[1]):s==="round-robin"?(v="round_robin",_="round_robin"):(v="primary",_=h&&y?.key===i?"configured_primary":"insertion_order"),{schemaVersion:1,evaluatedAt:new Date(o).toISOString(),strategy:s,mode:v,selectionReason:_,quotaRoutingEnabled:a,quotaInputsUsed:l,sessionSoftLimit:c,sessionResetToleranceMs:u,configuredPrimaryAccount:i??null,configuredPrimaryMatched:h,rotationOffset:d,initialAccount:y?.label??"",candidates:g}}function Gln(e){const{enabledAccounts:t,accountStrategy:r,primaryAccountKey:n,quotaRoutingEnabled:o,sessionSoftLimit:s,sessionResetToleranceMs:i,requestedModel:a,setRoutingDecision:l}=e;let c=[...t];const u=Date.now();let d,m=0;const h=r==="fill-first"&&c.length>1&&o;if(!h&&r==="fill-first"&&Aln(t,n),h){const y=Bln(t,u,n,s,i,a);c=y.orderedAccounts,d=y.metricsByKey,f.shouldLog("debug")&&f.debug(`[proxy] quota-ordered fill sequence: ${c.map(v=>v.label).join(" \u2192 ")}`)}else{if(r==="round-robin"&&c.length!==Sar&&(Mh=Uar(c,n),Sar=c.length),c.length>1&&(m=Mh%c.length,r==="round-robin"&&(Mh=(Mh+1)%c.length),m>0)){const y=c.splice(0,m);c.push(...y)}d=new Map(t.map(y=>[y.key,TF(y.key,u,s,i,a)]))}const g=qln({accounts:t,orderedAccounts:c,metricsByKey:d,evaluatedAt:u,strategy:r,primaryKey:n,quotaRoutingEnabled:o,quotaOrdered:h,sessionSoftLimit:s,sessionResetToleranceMs:i,rotationOffset:m});return g&&l(g),{orderedAccounts:c,metricsByKey:d}}var EF=new Map,Hln=300*1e3,Vln=new Set(["accept","accept-encoding","accept-language","anthropic-beta","anthropic-dangerous-direct-browser-access","anthropic-version","sec-fetch-mode","user-agent","x-app","x-stainless-arch","x-stainless-lang","x-stainless-os","x-stainless-package-version","x-stainless-retry-count","x-stainless-runtime","x-stainless-runtime-version","x-stainless-timeout","x-subscription-tier"]),Wln=["oauth-2025-04-20","claude-code-20250219","fine-grained-tool-streaming-2025-05-14"];function SF(e){return e.replace(/[^a-zA-Z0-9._@-]/g,"_")}function War(e){return St(Wa(),".neurolink","header-snapshots",`anthropic_${SF(e)}.json`)}function Kln(e,t){if(t?.headers)for(const[r,n]of Object.entries(t.headers)){const o=r.toLowerCase();typeof n=="string"&&!e[o]&&!hF.has(o)&&o!=="authorization"&&o!=="x-api-key"&&o!=="x-claude-code-session-id"&&(e[o]=n)}}async function Jln(e){try{const t=SF(e),r=EF.get(t);if(r&&Date.now()-r.loadedAt<Hln)return r.snapshot;const n=War(e);try{await jP(n)}catch{return null}const o=JSON.parse(await Kr(n,"utf8"));if(!o||typeof o!="object")return null;const s={accountKey:"accountKey"in o&&typeof o.accountKey=="string"?o.accountKey:`anthropic:${e}`,capturedAt:"capturedAt"in o&&typeof o.capturedAt=="string"?o.capturedAt:new Date(0).toISOString(),source:"claude-code",headers:"headers"in o&&o.headers?o.headers:{},...o.body?{body:o.body}:{}};return Object.keys(s.headers).length===0&&Object.keys(s.body??{}).length===0?null:(EF.set(t,{snapshot:s,loadedAt:Date.now()}),s)}catch{return null}}function Yln(e,t){const r={...t??{}};for(const[n,o]of Object.entries(e)){const s=n.toLowerCase();typeof o=="string"&&Vln.has(s)&&!hF.has(s)&&s!=="authorization"&&s!=="x-api-key"&&s!=="x-claude-code-session-id"&&(r[s]=o)}return r}function Kar(e){if(!e||typeof e!="object")return;const t=e,r=Hxt(t.metadata?.user_id),n=Array.isArray(t.system)?t.system:typeof t.system=="string"?[{type:"text",text:t.system}]:[],o=n.find(i=>typeof i?.text=="string"&&i.text.includes("x-anthropic-billing-header"))?.text,s=n.find(i=>typeof i?.text=="string"&&i.text.includes("Claude Agent SDK"))?.text;if(!(!r&&!o&&!s))return{...r?{metadataUserId:r.metadataUserId}:{},...r?{sessionId:r.sessionId}:{},...o?{billingHeader:o}:{},...s?{agentBlock:s}:{}}}function Jar(e,t){return typeof e["x-claude-code-session-id"]=="string"||e["user-agent"]?.startsWith("claude-cli/")||!!t?.metadataUserId||!!t?.billingHeader||!!t?.agentBlock}function Zln(e,t){return e?JSON.stringify(e.headers??{})===JSON.stringify(t.headers??{})&&JSON.stringify(e.body??{})===JSON.stringify(t.body??{}):!1}async function Xln(e,t){const r=War(e);await il(r,t,384),EF.set(SF(e),{snapshot:t,loadedAt:Date.now()})}async function Qln(e,t,r,n){const o=await Jln(e);let s;try{s=JSON.parse(n)}catch{return o}const i=Kar(s);if(!Jar(r,i))return o;const a={accountKey:t,capturedAt:new Date().toISOString(),source:"claude-code",headers:Yln(r,o?.headers),body:{...o?.body??{},...i??{},...typeof r["x-claude-code-session-id"]=="string"?{sessionId:r["x-claude-code-session-id"]}:{}}};if(Zln(o,a))return o;try{await Xln(e,a)}catch(l){f.warn("[proxy] failed to persist Claude snapshot",{accountLabel:e,error:l instanceof Error?l.message:String(l)}),EF.set(SF(e),{snapshot:a,loadedAt:Date.now()})}return a}function Tce(e){const t={};if(!e||typeof e!="object")return t;const r=e;if(typeof r.model=="string"&&(t.responseModel=r.model),typeof r.stop_reason=="string"&&(t.finishReason=r.stop_reason),typeof r.stop_sequence=="string"&&(t.stopSequence=r.stop_sequence),Array.isArray(r.content)){const n=r.content.filter(o=>!!o&&typeof o=="object"&&o.type==="tool_use").map(o=>String(o.name??"")).filter(o=>o.length>0);n.length>0&&(t.toolCalls=n)}return t}function Yar(e){const t={};e.model&&(t.responseModel=e.model),e.stopReason&&(t.finishReason=e.stopReason),e.stopSequence&&(t.stopSequence=e.stopSequence);const r=(e.contentBlocks??[]).filter(n=>n.type==="tool_use").map(n=>String(n.toolName??"")).filter(n=>n.length>0);return r.length>0&&(t.toolCalls=r),t}function ecn(e,t,r,n,o){try{const s=JSON.parse(e),i={type:"text",text:r?.body?.agentBlock||"You are a Claude agent, built on Anthropic's Claude Agent SDK."};if(s.system){if(typeof s.system=="string"&&(s.system=[{type:"text",text:s.system}]),Array.isArray(s.system)){const c=s.system.findIndex(h=>typeof h.text=="string"&&h.text.includes("x-anthropic-billing-header")),u=s.system.findIndex(h=>typeof h.text=="string"&&h.text.includes("Claude Agent SDK")),d={type:"text",text:JO(s.system[c]?.text??r?.body?.billingHeader)};if(n&&u>=0)c<0&&s.system.unshift(d);else{const h=[c,u].filter(g=>g>=0).sort((g,y)=>y-g);for(const g of h)s.system.splice(g,1);s.system.length>0&&cAt(s,s.system),s.system=[d,i]}}}else{const c={type:"text",text:JO(r?.body?.billingHeader)};s.system=[c,i]}const a=t.substring(0,Math.min(20,t.length)),l=Vxt(a,{existingUserId:s.metadata?.user_id??r?.body?.metadataUserId,preferredSessionId:o??r?.body?.sessionId});return s.metadata={...s.metadata,user_id:l.metadataUserId},{bodyStr:JSON.stringify(s),sessionId:l.sessionId}}catch{return{bodyStr:e}}}async function tcn(e,t){if(!e.oauth?.accessToken)return;let r=e.oauth.accessToken,n=e.oauth.refreshToken,o=e.oauth.expiresAt;const s=e.email?.trim()||"legacy-default",i=o?o<Date.now():!1,a=()=>({key:tA,label:s,token:r,refreshToken:n,expiresAt:o,type:"oauth",persistTarget:{credPath:t}});if(!i)return a();const l=dl(tA);if(l.permanentlyDisabled)return;const c=(await AA())[tA];if(c?.coolingUntil>Date.now()&&(!l.coolingUntil||c.coolingUntil>l.coolingUntil)&&(l.coolingUntil=c.coolingUntil,l.coolingReason=c.reason),l.coolingReason==="auth"&&l.coolingUntil&&l.coolingUntil>Date.now())return a();if(!n){f.always("[proxy] skipping legacy account (expired, no refresh token)"),await qp(a(),l,"missing_refresh_token");return}const u={token:r,refreshToken:n,expiresAt:o,label:s},d=await Xsr(u);if(!d.success){if(My(d)){await qp(a(),l,"refresh_invalid");return}const m=await xF(a(),l);return f.always(`[proxy] legacy refresh temporarily unavailable (${d.status??"network"}); cooling until ${new Date(m).toISOString()}`),a()}return r=u.token,n=u.refreshToken,o=u.expiresAt,await Y$(t,u),await AF(a(),l),f.always("[proxy] refreshed legacy account at startup"),a()}async function rcn(e){const{ctx:t,body:r,route:n,modelRouter:o,tracer:s,requestStartTime:i,logProxyBody:a}=e;s?.setMode("full");const l=wle(r),c=gb({provider:n.provider,model:n.model},o?.getFallbackChain()??[],r.model,l,o?.isAutoFallbackEnabled?.()??!1);Zar(a,"translated_request",c);const u=c.attempts;if(r.stream)return Mle({ctx:t,format:"claude",requestModel:r.model,parsed:l,attempts:u,tracer:s,requestStartTime:i});try{return await Ple({ctx:t,format:"claude",requestModel:r.model,parsed:l,attempts:u,tracer:s,requestStartTime:i,terminalFailureStatus:502})}catch(d){const m=d instanceof Error?d.message:"unknown error";f.error(`[claude-proxy] Translated generation failed for ${r.model}: ${m}`);const h=ul(502,`Generation failed: ${m}`),g=JSON.stringify(h);return a({phase:"client_response",headers:{"content-type":"application/json"},body:g,bodySize:Buffer.byteLength(g,"utf8"),contentType:"application/json",account:"translation",accountType:"translation",responseStatus:502,durationMs:Date.now()-i}),h}}function Zar(e,t,r){e({phase:"routing_decision",contentType:"application/json",body:{stage:t,attempts:r.attempts}})}async function ncn(e){const{ctx:t,body:r,clientRequestBody:n,tracer:o,requestStartTime:s,logProxyBody:i,logFinalRequest:a}=e;o?.setMode("passthrough-cli");const l=n,c=Array.isArray(r.tools)?r.tools.length:0,u={};for(const[g,y]of Object.entries(t.headers))!hF.has(g.toLowerCase())&&y&&(u[g]=y);u["content-type"]||(u["content-type"]="application/json");const d=o?.startUpstreamAttempt({account:"passthrough",attempt:1,polyfillHeaders:!1,polyfillBody:!1,upstreamUrl:"https://api.anthropic.com/v1/messages?beta=true"});o?.logUpstreamRequestHeaders(u),o?.logUpstreamRequestBody(l),i({phase:"upstream_request",headers:u,body:l,bodySize:Buffer.byteLength(l,"utf8"),contentType:u["content-type"]??"application/json",account:"passthrough",accountType:"passthrough",attempt:1,metadata:{upstreamMethod:"POST",upstreamUrl:"https://api.anthropic.com/v1/messages?beta=true"}}),Ty("passthrough","passthrough");let m;try{m=await pce("https://api.anthropic.com/v1/messages?beta=true",{method:"POST",headers:u,body:l,signal:AbortSignal.timeout(GA)})}catch(g){const y=g instanceof Error?g.message:String(g);$r("passthrough","passthrough",502),o?.setError("network_error",y),d?.end(),o?.end(502,Date.now()-s),a(502,"passthrough","passthrough","network_error",y);const v=ul(502,`Passthrough fetch failed: ${y}`),_=JSON.stringify(v);return i({phase:"client_response",headers:{"content-type":"application/json"},body:_,bodySize:Buffer.byteLength(_,"utf8"),contentType:"application/json",account:"passthrough",accountType:"passthrough",attempt:1,responseStatus:502,durationMs:Date.now()-s}),v}const h={};m.headers.forEach((g,y)=>{h[y]=g}),o?.logUpstreamResponseHeaders(h);{const g=nb(m.headers,{model:r.model});VA(t,{upstreamHeaders:m.headers,quota:g,source:g?"live":"none",accountType:"passthrough",servedBy:"anthropic",attempt:1})}if(!m.ok){const g=await m.text();$r("passthrough","passthrough",m.status,m.status===429?"quota":void 0),o?.logUpstreamResponseBody(g),i({phase:"upstream_response",headers:h,body:g,bodySize:Buffer.byteLength(g,"utf8"),contentType:h["content-type"]??"application/json",account:"passthrough",accountType:"passthrough",attempt:1,responseStatus:m.status,durationMs:Date.now()-s}),i({phase:"client_response",headers:h,body:g,bodySize:Buffer.byteLength(g,"utf8"),contentType:h["content-type"]??"application/json",account:"passthrough",accountType:"passthrough",attempt:1,responseStatus:m.status,durationMs:Date.now()-s}),d?.end(),o?.setError("api_error",g.slice(0,500)),o?.end(m.status,Date.now()-s),a(m.status,"passthrough","passthrough",m.status===429?"rate_limit_error":"api_error",g);try{return JSON.parse(g)}catch{return ul(m.status,g)}}return r.stream&&m.body?scn({ctx:t,body:r,bodyStr:l,response:m,tracer:o,requestStartTime:s,toolCount:c,upstreamSpan:d,upstreamResponseHeaders:h,logProxyBody:i,logFinalRequest:a}):icn({ctx:t,body:r,bodyStr:l,response:m,tracer:o,requestStartTime:s,toolCount:c,upstreamSpan:d,upstreamResponseHeaders:h,logProxyBody:i,logFinalRequest:a})}function ocn(e){const t=e.getReader(),r=aar();let n=!1;return{stream:new ReadableStream({async pull(s){if(!n)try{const{done:i,value:a}=await t.read();if(n)return;if(i){n=!0,r.complete(),s.close();return}s.enqueue(a)}catch(i){n=!0;const a=i instanceof Error?i.message:String(i);r.fail(a),s.error(i)}},cancel(s){return n=!0,r.cancel(),t.cancel(s)}}),outcome:r.outcome}}async function scn(e){const{ctx:t,bodyStr:r,response:n,tracer:o,requestStartTime:s,upstreamSpan:i,upstreamResponseHeaders:a,logProxyBody:l,logFinalRequest:c}=e,u={...a},{stream:d,capture:m}=Oir(),h=n.body;if(!h)throw $r("passthrough","passthrough",502),new Error("Expected passthrough stream response body");const g=ocn(h);let y=g.stream,v=!1;const _=(T,k,x,I)=>v?!1:(v=!0,k==="stream_error"&&$r("passthrough","passthrough",T),c(T,"passthrough","passthrough",k,x,I),!0);if(o)try{const{stream:T,telemetry:k}=lF({captureRawText:!0});y=y.pipeThrough(T);const x=o,I=i,M=n,R=r.length;Promise.all([k,m,g.outcome]).then(([A,P,L])=>{const N=cF(L,A.streamErrorMessage),D=Ph(N);x.setUsage({inputTokens:A.usage.inputTokens,outputTokens:A.usage.outputTokens,cacheCreationTokens:A.usage.cacheCreationInputTokens,cacheReadTokens:A.usage.cacheReadInputTokens}),x.logStreamEvents(A.events),x.setResponseInfo(Yar(A));const O=parseFloat(M.headers.get("anthropic-ratelimit-unified-5h-utilization")??""),F=parseFloat(M.headers.get("anthropic-ratelimit-unified-7d-utilization")??""),$={inputTokens:A.usage.inputTokens,outputTokens:A.usage.outputTokens,cacheCreationTokens:A.usage.cacheCreationInputTokens,cacheReadTokens:A.usage.cacheReadInputTokens};isNaN(O)||($.rateLimitAfter5h=O),isNaN(F)||($.rateLimitAfter7d=F),(!isNaN(O)||!isNaN(F))&&x.setUsage($),x.logUpstreamResponseBody(A.rawText??""),x.recordMetrics(),x.recordBodySizes(R,A.totalBytesReceived),I?.end(),D&&x.setError(D.errorType,D.message),x.end(D?.status??n.status,Date.now()-s),_(D?.status??n.status,D?.errorType,D?.message,{inputTokens:A.usage.inputTokens,outputTokens:A.usage.outputTokens,cacheCreationTokens:A.usage.cacheCreationInputTokens,cacheReadTokens:A.usage.cacheReadInputTokens}),l({phase:"upstream_response",headers:u,body:A.rawText??"",bodySize:A.totalBytesReceived,contentType:u["content-type"]??"text/event-stream",account:"passthrough",accountType:"passthrough",attempt:1,responseStatus:200,durationMs:Date.now()-s}),l({phase:"client_response",headers:u,body:P.text,bodySize:P.totalBytes,contentType:u["content-type"]??"text/event-stream",account:"passthrough",accountType:"passthrough",attempt:1,responseStatus:200,durationMs:Date.now()-s})}).catch(A=>{if(v)return;const P=A instanceof Error?A.message:String(A);x.setError("stream_telemetry_error",P),I?.end(),x.end(500,Date.now()-s),_(500,"stream_telemetry_error",P)})}catch{g.outcome.then(T=>{const k=Ph(T);i?.end(),k&&o.setError(k.errorType,k.message),o.end(k?.status??n.status,Date.now()-s),_(k?.status??n.status,k?.errorType,k?.message)})}else try{const{stream:T,telemetry:k}=lF({captureRawText:!0});y=y.pipeThrough(T),Promise.all([k,m,g.outcome]).then(([x,I,M])=>{const R=cF(M,x.streamErrorMessage),A=Ph(R);_(A?.status??n.status,A?.errorType,A?.message,{inputTokens:x.usage.inputTokens,outputTokens:x.usage.outputTokens,cacheCreationTokens:x.usage.cacheCreationInputTokens,cacheReadTokens:x.usage.cacheReadInputTokens}),l({phase:"upstream_response",headers:u,body:x.rawText??"",bodySize:x.totalBytesReceived,contentType:u["content-type"]??"text/event-stream",account:"passthrough",accountType:"passthrough",attempt:1,responseStatus:n.status,durationMs:Date.now()-s}),l({phase:"client_response",headers:u,body:I.text,bodySize:I.totalBytes,contentType:u["content-type"]??"text/event-stream",account:"passthrough",accountType:"passthrough",attempt:1,responseStatus:n.status,durationMs:Date.now()-s})}).catch(x=>{v||_(500,"stream_telemetry_error",x instanceof Error?x.message:String(x))})}catch{g.outcome.then(T=>{const k=Ph(T);_(k?.status??n.status,k?.errorType,k?.message)})}const b=y.pipeThrough(d);return new Response(b,{status:n.status,headers:{...u,...t.responseHeaders??{}}})}async function icn(e){const{bodyStr:t,response:r,tracer:n,requestStartTime:o,upstreamSpan:s,upstreamResponseHeaders:i,logProxyBody:a,logFinalRequest:l}=e,c=await r.text();n?.logUpstreamResponseBody(c),a({phase:"upstream_response",headers:i,body:c,bodySize:Buffer.byteLength(c,"utf8"),contentType:i["content-type"]??"application/json",account:"passthrough",accountType:"passthrough",attempt:1,responseStatus:r.status,durationMs:Date.now()-o}),a({phase:"client_response",headers:i,body:c,bodySize:Buffer.byteLength(c,"utf8"),contentType:i["content-type"]??"application/json",account:"passthrough",accountType:"passthrough",attempt:1,responseStatus:r.status,durationMs:Date.now()-o});const u=JSON.parse(c);if(n&&u&&typeof u=="object"){const d=u.usage;if(d){n.setUsage({inputTokens:d.input_tokens??0,outputTokens:d.output_tokens??0,cacheCreationTokens:d.cache_creation_input_tokens??0,cacheReadTokens:d.cache_read_input_tokens??0});const h=parseFloat(r.headers.get("anthropic-ratelimit-unified-5h-utilization")??""),g=parseFloat(r.headers.get("anthropic-ratelimit-unified-7d-utilization")??"");if(!isNaN(h)||!isNaN(g)){const y={inputTokens:d.input_tokens??0,outputTokens:d.output_tokens??0,cacheCreationTokens:d.cache_creation_input_tokens??0,cacheReadTokens:d.cache_read_input_tokens??0};isNaN(h)||(y.rateLimitAfter5h=h),isNaN(g)||(y.rateLimitAfter7d=g),n.setUsage(y)}}n.setResponseInfo(Tce(u)),n.recordMetrics();const m=JSON.stringify(u);n.recordBodySizes(t.length,m.length),s?.end(),n.end(r.status,Date.now()-o),l(r.status,"passthrough","passthrough",void 0,void 0,{inputTokens:d?.input_tokens,outputTokens:d?.output_tokens,cacheCreationTokens:d?.cache_creation_input_tokens,cacheReadTokens:d?.cache_read_input_tokens})}else s?.end(),n?.end(r.status,Date.now()-o),l(r.status,"passthrough","passthrough");return u}async function acn(e){const t=ib();if(!t)return{accounts:e.accounts};if(e.accounts.length===0)return{accounts:e.accounts};const r=Date.now(),n=await Promise.all(e.accounts.map(async d=>{const m=dl(d.key).quota,h=$i(m?.sessionResetAt,r)??null,g=$i(m?.weeklyResetAt,r)??null,y=await iae(t.grantId,d.key,h,g);return{accountKey:d.key,sessionUsed:m?.sessionUsed??null,weeklyUsed:m?.weeklyUsed??null,sessionResetAt:h,weeklyResetAt:g,borrowedSessionFraction:y.sessionFraction,borrowedWeeklyFraction:y.weeklyFraction}})),o=await eae(t.grantId);if(!o)return{accounts:e.accounts};const s=await aae(t.grantId,Kle(o.gates,n).inScope),i=Jle(o,n,r,s),a=new Set(i.allowed),l=e.accounts.filter(d=>a.has(d.key));if(l.length>0)return{accounts:l};const c=Yle(i.excluded),u=pb(c,{status:ran(c),grant:o,retryAfterSeconds:elr(n,r)});return f.always(`[proxy] share ${t.peerLabel} withheld: ${c} (${i.excluded.length} accounts)`),{accounts:[],refusal:{status:u.status,message:u.body.error.message,errorType:u.body.error.type,responseHeaders:u.headers}}}async function lcn(e){const t=[],r=[];for(const n of e){const o=await Hin(n.key);if(!o){t.push(n);continue}if(!Oin(o)){t.push(n);continue}f.always(`[proxy] withholding leased account=${n.label}: ${o.reason}`),r.push({label:n.label,reason:o.reason})}return{accounts:t,withheld:r}}async function ccn(e,t){const r=[],n=[],o=Date.now();for(const s of e){const i=await Wle(s.key);if(!i){r.push(s);continue}const a=i.lease.gates;if(!oan(a.models,t)){f.always(`[proxy] leased account=${s.label} does not cover model ${Xn(t??"unknown")}`),n.push({label:s.label,reason:"model_not_allowed"});continue}if(a.schedule&&!nan(a.schedule,o)){f.always(`[proxy] leased account=${s.label} is outside its allowed hours`),n.push({label:s.label,reason:"out_of_window"});continue}const l=dl(s.key).quota,c=$i(l?.sessionResetAt,o)??null,u=$i(l?.weeklyResetAt,o)??null,d=await iae(i.grantId,s.key,c,u),m={accountKey:s.key,sessionUsed:l?.sessionUsed??null,weeklyUsed:l?.weeklyUsed??null,sessionResetAt:c,weeklyResetAt:u,borrowedSessionFraction:d.sessionFraction,borrowedWeeklyFraction:d.weeklyFraction},h=await aae(i.grantId,[m]),{accounts:g,...y}=a,v=Jle(ucn(i,y),[m],o,h);if(v.allowed.length===0){const _=Yle(v.excluded);f.always(`[proxy] withholding leased account=${s.label}: ${_}`),n.push({label:s.label,reason:_});continue}r.push(s)}return{accounts:r,withheld:n}}function ucn(e,t){const r=e.lease.entitlementSnapshot;return{schemaVersion:1,id:e.grantId,peerLabel:e.lease.peerLabel,tokenHash:"",tokenSalt:"",level:"complete",state:"active",entitlement:r==="unlimited"?{ledger:"unlimited"}:{ledger:"coins",coins:r},gates:t,createdAt:e.lease.issuedAt,updatedAt:e.lease.issuedAt}}function dcn(e,t,r){const n=Date.now(),o=i=>{XQr({grantId:i,accountKey:e,sessionBefore:t?.sessionUsed??null,sessionAfter:r.sessionUsed,sessionResetAt:$i(r.sessionResetAt,n)??null,weeklyBefore:t?.weeklyUsed??null,weeklyAfter:r.weeklyUsed,weeklyResetAt:$i(r.weeklyResetAt,n)??null})},s=ib();if(s){o(s.grantId);return}Wle(e).then(i=>{i&&o(i.grantId)}).catch(()=>{})}function Ece(e,t,r){const n=sae({inputTokens:r.inputTokens??0,outputTokens:r.outputTokens??0,...r.cacheCreationTokens!==void 0?{cacheCreationTokens:r.cacheCreationTokens}:{},...r.cacheReadTokens!==void 0?{cacheReadTokens:r.cacheReadTokens}:{}},t);Vin(e,n).catch(()=>{})}function Xar(e,t){if(!t||typeof t!="object")return;const r=t.usage;if(!r)return;const n=vcn(t),o={inputTokens:r.input_tokens??0,outputTokens:r.output_tokens??0,cacheCreationTokens:r.cache_creation_input_tokens??0,cacheReadTokens:r.cache_read_input_tokens??0};Sce(e.key,n,o),Ece(e.label,n,o)}function Sce(e,t,r){const n=ib();n&&QQr({grantId:n.grantId,accountKey:e,model:t??n.model,usage:{inputTokens:r.inputTokens??0,outputTokens:r.outputTokens??0,...r.cacheCreationTokens!==void 0?{cacheCreationTokens:r.cacheCreationTokens}:{},...r.cacheReadTokens!==void 0?{cacheReadTokens:r.cacheReadTokens}:{}},...n.holdId?{holdId:n.holdId}:{}})}function Qar(e){if(!ib())return e;const t={};for(const[r,n]of Object.entries(e)){const o=r.toLowerCase();o==="x-neurolink-account"||o==="x-neurolink-account-type"||o.startsWith("x-neurolink-pool-")||(t[r]=n)}return t}async function pcn(e,t){const r=e.provisionedAccount;if(!r)return{paused:!1,detail:"no provisioned account recorded"};const n=Jl.get(`anthropic:${r}`),o=QQt(r,"oauth"),{verdict:s,shouldPause:i}=await Ean({grantId:e.id,accountLabel:r,lenderRequestsTotal:o?.successCount??0,observation:{at:Date.now(),sessionUsed:n?.quota?.sessionUsed??null,weeklyUsed:n?.quota?.weeklyUsed??null,reportedCoins:t,lenderRequests:0}});return i?(await $Qr(e.id,"paused"),{paused:!0,detail:s.drifted?s.detail:"repeated unexplained usage"}):{paused:!1,detail:s.drifted?s.detail:"consistent"}}async function mcn(e,t){await der(e.id,t)}function hcn(e,t){if(e.length!==t.length||e.length===0)return!1;let r=0;for(let n=0;n<e.length;n+=1)r|=e.charCodeAt(n)^t.charCodeAt(n);return r===0}var fcn=1,gcn=["live","complete","handshake","limits"];async function ycn(e,t){const r=Date.now(),n=await eir(t),o=await Promise.all(n.map(async c=>{const u=dl(c.key).quota,d=$i(u?.sessionResetAt,r)??null,m=$i(u?.weeklyResetAt,r)??null,h=await iae(e.id,c.key,d,m);return{accountKey:c.key,sessionUsed:u?.sessionUsed??null,weeklyUsed:u?.weeklyUsed??null,sessionResetAt:d,weeklyResetAt:m,borrowedSessionFraction:h.sessionFraction,borrowedWeeklyFraction:h.weeklyFraction}})),s=Kle(e.gates,o).inScope,i=await aae(e.id,s),a=Jle(e,o,r,i),l=(c,u)=>c===void 0?null:Math.max(0,c-u*100);return{grantState:e.state,level:e.level,ledger:e.entitlement.ledger,...e.entitlement.ledger==="coins"?{remainingCoins:Math.max(0,Math.floor(JQr(e)))}:{},servable:a.allowed.length>0,...a.allowed.length===0&&a.excluded.length>0?{withheldReason:Yle(a.excluded)}:{},sliceLeftPct:{session:l(e.gates.maxSlice?.session5hPct,i.sessionFraction),weekly:l(e.gates.maxSlice?.weekly7dPct,i.weeklyFraction)},...a.allowed.length===0?(()=>{const c=elr(o,r);return c===void 0?{}:{retryAfterSeconds:c}})():{}}}function Ny(e){return!e.ok}async function Ly(e){const t=uan(e);if(!t)return{ok:!1,body:pb("missing_token",{status:401}).body};const r=await UQr(t);return r?{ok:!0,grant:r}:{ok:!1,body:pb("unknown_token",{status:401}).body}}function vcn(e){if(!e||typeof e!="object")return;const t=e.model;return typeof t=="string"?t:void 0}function elr(e,t){const r=e.flatMap(n=>[n.sessionResetAt,n.weeklyResetAt]).filter(n=>n!==null&&n>t);if(r.length!==0)return Math.max(1,Math.round((Math.min(...r)-t)/1e3))}async function _cn(e){const{ctx:t,body:r,accountStrategy:n,primaryAccountKey:o,accountAllowlist:s,quotaRoutingEnabled:i=_ce(),sessionSoftLimit:a=wce(),sessionResetToleranceMs:l=WA(),setRoutingDecision:c}=e,u=await Promise.resolve().then(()=>(nn(),Tl)),d=await Promise.resolve().then(()=>(ma(),YT)),m=[],h=`${d.homedir()}/.neurolink/anthropic-credentials.json`,{tokenStore:g}=await Promise.resolve().then(()=>(rA(),jie)),y=await AA();$ar||(await g.pruneExpired(),$ar=!0);const v=await g.listByPrefix("anthropic:"),_=[];let b=0,T=0;for(const K of v){if(!Uie(K,s)){f.debug(`[proxy] skipping account=${K} (not in account allowlist)`);continue}if(await g.isDisabled(K)){const ie=dl(K),le=await g.getDisabledReason(K);if(le==="refresh_failed")await g.markEnabled(K),f.always(`[proxy] account=${K.split(":")[1]??K} re-enabled for legacy refresh failure recheck`),ie.permanentlyDisabled=!1,ie.consecutiveRefreshFailures=0;else{f.debug(`[proxy] skipping disabled account=${K.split(":")[1]??K}`),ie.permanentlyDisabled=!0,le==="entitlement_blocked"&&_.push(K.split(":")[1]??K),b+=1;continue}}const G=await g.loadTokens(K);if(!G){T+=1;continue}let Q=G.accessToken,ve=G.refreshToken,ee=G.expiresAt;const H=K.split(":")[1]??K,Z=G.tokenType==="Bearer"?"oauth":"api_key",Ee=dl(K),Se=y[K];Se?.coolingUntil>Date.now()&&(!Ee.coolingUntil||Se.coolingUntil>Ee.coolingUntil)&&(Ee.coolingUntil=Se.coolingUntil,Ee.coolingReason=Se.reason);const me=()=>{m.push({key:K,label:H,token:Q,refreshToken:ve,expiresAt:ee,type:Z,persistTarget:{providerKey:K}})};if(ee?ee<Date.now():!1){if(Ee.permanentlyDisabled)continue;if(Ee.coolingReason==="auth"&&Ee.coolingUntil&&Ee.coolingUntil>Date.now()){me();continue}if(!ve){f.always(`[proxy] skipping account=${H} (expired, no refresh token)`),await qp({key:K,label:H,token:Q,type:"oauth"},Ee,"missing_refresh_token");continue}const ie={token:Q,refreshToken:ve,expiresAt:ee,label:H},le=await J$(ie,{providerKey:K});if(!le.success){const te={key:K,label:H,token:Q,type:"oauth"};if(My(le))f.always(`[proxy] skipping account=${H} (refresh token rejected: ${le.error?.slice(0,200)??"unknown"})`),await qp(te,Ee,"refresh_invalid");else{const Ie=await xF(te,Ee);f.always(`[proxy] account=${H} refresh temporarily unavailable (${le.status??"network"}); cooling until ${new Date(Ie).toISOString()} and rotating`),me()}continue}Q=ie.token,ve=ie.refreshToken,ee=ie.expiresAt,await g.saveTokens(K,{accessToken:Q,refreshToken:ve,expiresAt:ee??Date.now()+36e5,tokenType:"Bearer"}),f.always(`[proxy] refreshed expired account=${K.split(":")[1]??K} at startup`),await AF({key:K},Ee)}me()}if(m.length===0&&jQt(v.length,tA,s))try{const K=JSON.parse(u.readFileSync(h,"utf8")),G=await tcn(K,h);G&&m.push(G)}catch{}if(process.env.ANTHROPIC_API_KEY&&m.length===0&&jQt(v.length,Bie,s)&&m.push({key:Bie,label:"env",token:process.env.ANTHROPIC_API_KEY,type:"api_key"}),m.length===0)return _.length>0&&_.length===b&&T===0?{failure:{status:403,message:olr({status:403,accounts:_,message:"OAuth authentication is not allowed for this organization.",errorCode:"oauth_not_allowed_for_organization"}),errorType:"permission_error"}}:{failure:{status:401,message:s?"No allowed Anthropic credentials are currently available":v.length>0?"Configured Anthropic accounts are disabled or unavailable":"No Anthropic credentials found",errorType:"authentication_error"}};for(const K of m)Gcn(K);await Pln(m);const k=m.filter(K=>!dl(K.key).permanentlyDisabled),x=await lcn(k),I=await ccn(x.accounts,typeof r.model=="string"?r.model:void 0),M={accounts:I.accounts,withheld:[...x.withheld,...I.withheld]},R=M.accounts;if(R.length===0&&M.withheld.length>0){const K=M.withheld.map(ve=>`${ve.label} (${ve.reason})`).join(", ");return{failure:{status:403,message:M.withheld.every(ve=>ve.reason==="model_not_allowed")?`Borrowed account(s) do not cover the requested model: ${K}. Ask the lender to widen the share, or use a model it allows.`:`Borrowed account(s) are no longer covered by a lease: ${K}. Run 'neurolink proxy peer sync' to check in with the lender, or ask them to resume the share.`,errorType:"permission_error"}}}const A=await acn({accounts:R});if(A.refusal)return{failure:A.refusal};const P=A.accounts;if(P.length===0)return{failure:{status:401,message:IF(m.map(G=>G.label)),errorType:"authentication_error"}};const{orderedAccounts:L,metricsByKey:N}=Gln({enabledAccounts:P,accountStrategy:n,primaryAccountKey:o,quotaRoutingEnabled:i,sessionSoftLimit:a,sessionResetToleranceMs:l,requestedModel:typeof r.model=="string"?r.model:void 0,setRoutingDecision:c});n==="fill-first"&&i&&P.length>1&&zln(P,L,a,N);const D=Ycn(r),O=JSON.stringify(D),F=Date.now(),$=Array.isArray(r.tools)?r.tools.length:0,B="https://api.anthropic.com/v1/messages?beta=true",z=t.headers??{},j=Kar(r);return{accounts:m,enabledAccounts:P,orderedAccounts:L,bodyStr:O,requestStart:F,toolCount:$,url:B,clientHeaders:z,isClaudeClientRequest:Jar(z,j)}}async function wcn(e){const{ctx:t,body:r,tracer:n,requestStartTime:o,logProxyBody:s,logFinalRequest:i,options:a,providerLabel:l,idleTimeoutMs:c=gln}=e,u=new AbortController;let d;try{d=await Bt(t.neurolink.stream({...a,abortSignal:u.signal}),c,`Fallback ${l} initialization timed out after ${c}ms`)}catch(_){throw u.abort(_),_}const m=async _=>{const b=d.stream[Symbol.asyncIterator]();let T="";try{for(;;){const{value:k,done:x}=await Bt(b.next(),c,`Fallback ${l} stream timed out after ${c}ms of inactivity`);if(x)return T;const I=Ale(k);I&&(T+=I,_?.(I))}}catch(k){throw u.abort(k),b.return?.().catch(()=>{}),k}};if(r.stream){const _=new Tle(r.model,0),b=[];for(const A of _.start())b.push(A);const T=await m(A=>{for(const P of _.pushDelta(A))b.push(P)}),k=d.toolCalls??[];if(!nF(T,k))throw new Error(`Translated provider ${l} returned no content or tool calls`);if(k.length)for(const A of k){const P=A.toolName??A.name??"unknown";for(const L of _.pushToolUse(Z$(),P,Rir(A)))b.push(L)}const x=d.finishReason??"end_turn",I=ub(d.usage);for(const A of _.finish(I.output,x))b.push(A);n?.end(200,Date.now()-o),i(200,"",l,void 0,void 0,{inputTokens:I.input,outputTokens:I.output});const M=b.join("");s({phase:"client_response",headers:{"content-type":"text/event-stream"},body:M,bodySize:Buffer.byteLength(M,"utf8"),contentType:"text/event-stream",responseStatus:200,durationMs:Date.now()-o});async function*R(){for(const A of b)yield A}return R()}const h=await m();if(!nF(h,d.toolCalls))throw new Error(`Translated provider ${l} returned no content or tool calls`);const g={content:h,model:d.model,finishReason:d.finishReason??"end_turn",reasoning:void 0,usage:d.usage?ub(d.usage):void 0,toolCalls:d.toolCalls};n?.end(200,Date.now()-o);const y=ble(g,r.model);i(200,"",l,void 0,void 0,{inputTokens:g.usage?.input,outputTokens:g.usage?.output});const v=JSON.stringify(y);return s({phase:"client_response",headers:{"content-type":"application/json"},body:v,bodySize:Buffer.byteLength(v,"utf8"),contentType:"application/json",responseStatus:200,durationMs:Date.now()-o}),y}async function tlr(e){let t;for(let r=0;r<=uce;r+=1)try{return await wcn(e)}catch(n){if(t=n,!xce(n)||r===uce)throw n;const o=cce[r]??250;f.always(`[proxy] retrying fallback=${e.providerLabel} after transient network error (${r+1}/${uce}) in ${o}ms: ${JA(Sd(n))}`),await Gp(o)}throw t}async function bcn(e){const{ctx:t,body:r,model:n,tracer:o,requestStartTime:s,logProxyBody:i,logFinalRequest:a}=e,l={...t,requestId:`${t.requestId}:codex-fallback`,method:"POST",path:"/backend-api/codex/responses",headers:{"content-type":"application/json",accept:"text/event-stream"},query:{},params:{},body:asn(r,n),metadata:{...t.metadata,"neurolink.codexFallback":!0},responseHeaders:{}},c=await Tar(l),u={...l.responseHeaders??{}};let d;try{d=await hsn(c)}catch(_){throw _ instanceof Ele&&f.always(`[proxy] Codex fallback returned ${_.status}: ${Xn(_.responseBody,500)}`),_}Object.keys(u).length>0&&(t.responseHeaders??={},Object.assign(t.responseHeaders,Qar(u)));const m=u["x-neurolink-account"]??"",h=u["x-neurolink-account-type"]??"codex-oauth",g={content:d.text,model:r.model,finishReason:d.finishReason,...d.usage?{usage:d.usage}:{},toolCalls:d.toolCalls};if(r.stream){const _=new Tle(r.model,d.usage?.input??0),b=[];for(const x of _.start())b.push(x);if(d.text)for(const x of _.pushDelta(d.text))b.push(x);for(const x of d.toolCalls)for(const I of _.pushToolUse(Z$(),x.toolName,x.args))b.push(I);for(const x of _.finish(d.usage?.output,d.finishReason))b.push(x);o?.end(200,Date.now()-s),a(200,m,h,void 0,void 0,{inputTokens:d.usage?.input,outputTokens:d.usage?.output,cacheCreationTokens:d.usage?.cacheCreationTokens,cacheReadTokens:d.usage?.cacheReadTokens});const T=b.join("");i({phase:"client_response",headers:{"content-type":"text/event-stream"},body:T,bodySize:Buffer.byteLength(T,"utf8"),contentType:"text/event-stream",responseStatus:200,durationMs:Date.now()-s});async function*k(){for(const x of b)yield x}return k()}o?.end(200,Date.now()-s);const y=ble(g,r.model);a(200,m,h,void 0,void 0,{inputTokens:d.usage?.input,outputTokens:d.usage?.output,cacheCreationTokens:d.usage?.cacheCreationTokens,cacheReadTokens:d.usage?.cacheReadTokens});const v=JSON.stringify(y);return i({phase:"client_response",headers:{"content-type":"application/json"},body:v,bodySize:Buffer.byteLength(v,"utf8"),contentType:"application/json",responseStatus:200,durationMs:Date.now()-s}),y}async function rlr(e){if(ib())return null;const t=await xin();if(t.length===0)return null;const r=e.body.stream===!0,n=JSON.stringify(e.body);for(const o of t){f.always(`[proxy] local pool spent \u2014 trying peer=${o.name}`);const s=await Xin({peer:o,body:n,stream:r});if(s.ok)return f.always(`[proxy] served by peer=${o.name}`),e.logFinalRequest(s.response.status,`peer:${o.name}`,"peer"),r?new Response(s.response.body,{status:s.response.status,headers:{"content-type":s.response.headers.get("content-type")??"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}}):await s.response.json().catch(()=>null)??null}return null}function Tcn(e){return!(e instanceof Ele)||e.status!==400?null:{status:e.status,body:e.responseBody,contentType:"application/json"}}async function nlr(e){const{ctx:t,body:r,parsedFallbackRequest:n,fallbackPlan:o,modelRouter:s,tracer:i,requestStartTime:a,logProxyBody:l,logFinalRequest:c}=e,u=o??gb({provider:"anthropic",model:r.model},s?.getFallbackChain()??[],r.model,n);l({phase:"routing_decision",contentType:"application/json",body:{stage:"anthropic_fallback",attempts:u.attempts.slice(1)}}),i?.setFallbackInfo({triggered:!0,attemptCount:u.attempts.slice(1).length,reason:"all_anthropic_accounts_exhausted"});let d,m;for(const h of u.attempts.slice(1)){if(!h.provider||!h.model)continue;const g=Date.now();try{f.always(`[proxy] fallback \u2192 ${h.provider}/${h.model}`);let y;if(h.provider==="codex")y=await bcn({ctx:t,body:r,model:h.model,tracer:i,requestStartTime:a,logProxyBody:l,logFinalRequest:c});else{const v=await Z_.checkFallbackProviderAvailability(h.provider,h.model);if(!v.available){const b=v.reason??"provider unavailable";f.always(`[proxy] fallback ${h.provider}/${h.model} health-check failed (${b}), skipping`),DA({provider:h.provider,model:h.model,status:"failure",errorMessage:`[unavailable] ${b}`,durationMs:0}),d=`[${h.provider}/${h.model}] unavailable: ${b}`;continue}const _=_lr(n,{provider:h.provider,model:h.model});y=await tlr({ctx:t,body:r,tracer:i,requestStartTime:a,logProxyBody:l,logFinalRequest:c,options:_,providerLabel:h.provider})}return DA({provider:h.provider,model:h.model,status:"success",durationMs:Date.now()-g}),i?.setFallbackInfo({triggered:!0,provider:h.provider,model:h.model,attemptCount:u.attempts.slice(1).length,reason:"fallback_success"}),h.provider!=="codex"&&VA(t,{quota:null,source:"none",servedBy:h.provider}),{response:y}}catch(y){m??=Tcn(y)??void 0;const v=JA(y instanceof Error?y.message:String(y));let _="unknown";v.includes("Rate limit")||v.includes("rate_limit")||v.includes("max_parallel_requests")?_="rate_limit":v.includes("context length")||v.includes("ContextWindowExceeded")?_="context_overflow":v.includes("no content or tool calls")||v.includes("NoOutputGenerated")?_="empty_response":v.includes("thinking_level")||v.includes("Field required")?_="schema_mismatch":v.includes("Resource exhausted")&&(_="provider_quota"),f.always(`[proxy] fallback ${h.provider}/${h.model} failed [${_}]: ${JA(Sd(y))}`),DA({provider:h.provider,model:h.model,status:"failure",errorMessage:`[${_}] ${v}`,durationMs:Date.now()-g}),d=`[${h.provider}/${h.model}] ${JA(Sd(y))}`}}return{response:null,lastErrorMessage:d,...m?{invalidRequestFailure:m}:{}}}async function Ecn(e){const{ctx:t,body:r,tracer:n,requestStartTime:o,logProxyBody:s,logFinalRequest:i}=e,a=Date.now();try{const l=wle(r),c=gb({provider:"anthropic",model:r.model},[],r.model,l,!0);if(Zar(s,"auto_fallback",c),!c.attempts.find(h=>h.label==="auto-provider"))return{response:null};f.always("[proxy] fallback \u2192 auto-provider");const d=_lr(l),m=await tlr({ctx:t,body:r,tracer:n,requestStartTime:o,logProxyBody:s,logFinalRequest:i,options:d,providerLabel:"auto-provider"});return DA({provider:"auto-provider",model:r.model,status:"success",durationMs:Date.now()-a}),n?.setFallbackInfo({triggered:!0,provider:"auto-provider",model:r.model,attemptCount:1,reason:"fallback_success"}),VA(t,{quota:null,source:"none",servedBy:"auto-provider"}),{response:m}}catch(l){const c=JA(Sd(l));return f.always(`[proxy] fallback auto-provider failed: ${c}`),DA({provider:"auto-provider",model:r.model,status:"failure",errorMessage:c,durationMs:Date.now()-a}),n?.setFallbackInfo({triggered:!0,provider:"auto-provider",model:r.model,attemptCount:1,reason:"fallback_failure"}),{response:null,lastErrorMessage:c}}}function Scn(e,t=5){const r=[...new Set(e)];return r.length<=t?r.join(", "):`${r.slice(0,t).join(", ")} and ${r.length-t} more`}function olr(e){const t=new Set(e.accounts).size,r=e.errorCode?` (${e.errorCode})`:"";return`All ${t} Anthropic account${t===1?"":"s"} are blocked by an organization entitlement policy${r}. Accounts: ${Scn(e.accounts)}. Upstream: "${e.message}". Ask an organization admin to re-enable Claude Code OAuth access, then run: neurolink auth enable anthropic:<account>.`}function Ccn(e){const t=new Set(e.map(r=>r.coolingReason));if(t.size===1)switch([...t][0]){case"session":return"5-hour subscription window";case"weekly":return"7-day subscription window";case"unified":return"subscription limit";case"transient":return"upstream burst limit";default:break}return"upstream rate limits"}function kcn(e){for(const t of e){const r=Jl.get(t.key)?.quota;if(r?.overageDisabledReason&&r.overageStatus?.trim().toLowerCase()!=="allowed")return r.overageDisabledReason}}function slr(e){return e?` Paid extra usage is unavailable for this organization (${e}), so there is no additional capacity before the window resets.`:""}function xcn(e){const t=new Set(e.accounts).size;return`All ${t} Anthropic account${t===1?"":"s"} have exhausted the model-scoped limit for ${e.model} (window "${e.scopeModel}"). Other models remain available on this pool \u2014 switch model, or add an account with remaining ${e.scopeModel} capacity. Earliest reset at ${new Date(e.earliestResetMs).toISOString()}.`+slr(e.overageDisabledReason)}function ilr(e){const{tracer:t,requestStartTime:r,authFailureMessage:n,authCooldownMessage:o,invalidRequestFailure:s,entitlementFailure:i,scopedExhaustion:a,sawNetworkError:l,sawTransientFailure:c,sawRateLimit:u,lastError:d,lastTransportErrorCode:m,lastTransportScope:h,fallbackFailureMessage:g,orderedAccounts:y,buildLoggedClaudeError:v,logProxyBody:_,logFinalRequest:b}=e;if(i!==null&&y.length>0&&new Set(i.accounts).size>=y.length&&i&&!u){const D=olr(i);return t?.setError("permission_error",D),t?.end(403,Date.now()-r),v(403,D,"permission_error")}if(n&&!u)return t?.setError("authentication_error",n),t?.end(401,Date.now()-r),v(401,n);if(o&&!u)return t?.setError("token_refresh_unavailable",o),t?.end(503,Date.now()-r),v(503,o,"token_refresh_unavailable");if(s&&!u){const D=Cd(s.body),O=D.message!==void 0,F=Or(D.message??s.body),$=O?s.body:JSON.stringify(ul(s.status,F,"invalid_request_error")),B=O?s.contentType??"application/json":"application/json";return t?.setError("invalid_request_error",F),t?.end(s.status,Date.now()-r),b(s.status,"","final","invalid_request_error",F),_({phase:"client_response",headers:{"content-type":B},body:$,bodySize:Buffer.byteLength($,"utf8"),contentType:B,responseStatus:s.status,durationMs:Date.now()-r}),new Response($,{status:s.status,headers:{"content-type":B}})}if((l||c)&&!u){const D=g?` Fallback also failed: ${g}`:"",O=h==="shared_provider_transport"?"shared Anthropic network":h==="connection_transport"?"Anthropic connection":null,F=`${O?`${O} failure prevented safe cross-account rotation`:"All Anthropic accounts failed due to transient upstream/network errors"}. Last error${m?` (${m})`:""}: ${d instanceof Error?d.message:String(d??"unknown")}.${D}`;return t?.setError("transient_error",F.slice(0,500)),t?.end(502,Date.now()-r),v(502,F,g?"fallback_exhausted":"transient_error",{...m?{errorCode:m}:{},...h?{transportScope:h}:{}})}const k=(D,O)=>{const F=ul(429,D,"overloaded_error");t?.setError("rate_limit_error",D),t?.end(429,Date.now()-r),b(429,"","final","rate_limit_error",D);const $=JSON.stringify(F),B={"content-type":"application/json","retry-after":String(O)};return _({phase:"client_response",headers:B,body:$,bodySize:Buffer.byteLength($,"utf8"),contentType:"application/json",responseStatus:429,durationMs:Date.now()-r}),new Response($,{status:429,headers:B})};if(a){const D=xcn(a);return f.always(`[proxy] model-scoped limit exhausted for ${a.model} on all accounts`),k(D,Math.max(1,Math.ceil((a.earliestResetMs-Date.now())/1e3)))}if(!u){const D=g?` Fallback also failed: ${g}`:"",O=`All Anthropic accounts failed. Last error: ${d instanceof Error?d.message:String(d??"unknown")}.${D}`;return t?.setError("all_accounts_failed",O.slice(0,500)),t?.end(502,Date.now()-r),v(502,O,g?"fallback_exhausted":"all_accounts_failed")}const x=Date.now(),I=y.map(D=>dl(D.key)).filter(D=>D.coolingUntil&&D.coolingUntil>x&&D.coolingReason!=="auth"),M=Math.min(...I.map(D=>D.coolingUntil??Number.POSITIVE_INFINITY)),R=y.length>0&&I.length===y.length,A=R?Math.max(1,Math.ceil((M-x)/1e3)):1,P=Ccn(I),L=slr(kcn(y)),N=R?`All ${y.length} Anthropic accounts are cooling after the ${P} was exhausted. Earliest retry at ${new Date(M).toISOString()}.${L}`:`All ${y.length} accounts rate-limited after per-account retries.${L}`;return f.always(`[proxy] all accounts rate-limited, retry in ${A}s`),k(N,A)}async function alr(e){const{ctx:t,body:r,account:n,accountState:o,response:s,tracer:i,requestStartTime:a,fetchStartMs:l,attemptNumber:c,finalBodyStr:u,upstreamSpan:d,logAttempt:m,logProxyBody:h,onStreamTerminal:g,poolAccounts:y,logFinalRequest:v}=e;o.consecutiveRefreshFailures=0,f.always(`[proxy] \u2190 ${s.status} account=${n.label}`);const _=nb(s.headers,{model:r.model});if(_){dcn(n.key,o.quota,_),o.quota=Ay(o.quota,_);const T=yce(o,_,Date.now());T?.kind==="cooled"?Td(n.key,T.coolingUntil,T.coolingReason).catch(()=>{}):T?.kind==="cleared"&&xy(n.key,T.coolingUntil).catch(()=>{}),Ry(n.key,_).catch(()=>{})}const b={};return s.headers.forEach((T,k)=>{b[k]=T}),i?.logUpstreamResponseHeaders(b),VA(t,{upstreamHeaders:s.headers,quota:_??o.quota??null,source:_?"live":o.quota?"snapshot":"none",account:n,accountState:o,servedBy:"anthropic",attempt:c,...y?{poolAccounts:y}:{}}),r.stream?Acn({ctx:t,body:r,account:n,accountState:o,response:s,responseHeaders:b,tracer:i,requestStartTime:a,fetchStartMs:l,attemptNumber:c,finalBodyStr:u,upstreamSpan:d,logAttempt:m,logProxyBody:h,logFinalRequest:v,onStreamTerminal:g}):Rcn({account:n,response:s,responseHeaders:b,tracer:i,requestStartTime:a,fetchStartMs:l,attemptNumber:c,finalBodyStr:u,upstreamSpan:d,logAttempt:m,logProxyBody:h,logFinalRequest:v})}async function Acn(e){const{ctx:t,body:r,account:n,accountState:o,response:s,responseHeaders:i,tracer:a,requestStartTime:l,fetchStartMs:c,attemptNumber:u,finalBodyStr:d,upstreamSpan:m,logAttempt:h,logProxyBody:g,onStreamTerminal:y,logFinalRequest:v}=e;if(!s.body){$r(n.label,n.type,502),h(502,"stream_error","No response body from upstream"),m?.end(),a?.setError("stream_error","No response body from upstream"),a?.end(502,Date.now()-l),v(502,n.label,n.type,"stream_error","No response body from upstream");const R=ul(502,"No response body from upstream"),A=JSON.stringify(R);return g({phase:"client_response",headers:{"content-type":"application/json"},body:A,bodySize:Buffer.byteLength(A,"utf8"),contentType:"application/json",account:n.label,accountType:n.type,attempt:u,responseStatus:502,durationMs:Date.now()-l}),{response:R}}const _=s.body.getReader(),b=await jan(_);if(b.kind==="transport_error"){const R=Sd(b.error),A=Buffer.concat(b.chunks.map(P=>Buffer.from(P))).toString("utf8");return f.always(`[proxy] stream failed before first chunk account=${n.label}: ${R}; returning terminal error to avoid replaying an ambiguous request`),$r(n.label,n.type,502),h(502,"stream_error",R,{retryable:!1}),m?.end(),g({phase:"upstream_response",headers:i,body:A,bodySize:Buffer.byteLength(A,"utf8"),contentType:i["content-type"]??"text/event-stream",account:n.label,accountType:n.type,attempt:u,responseStatus:s.status,durationMs:Date.now()-c,metadata:{logicalStatus:502,transportError:R}}),{response:clr({account:n,tracer:a,requestStartTime:l,attemptNumber:u,logProxyBody:g,logFinalRequest:v,errorType:"stream_error",message:R})}}if(b.kind==="empty")return await _.cancel().catch(()=>{}),f.always(`[proxy] \u2190 empty stream from account=${n.label}, trying next`),$r(n.label,n.type,502),h(502,"empty_stream","Empty upstream stream",{retryable:!0}),a?.recordRetry(n.label,"empty_stream"),m?.end(),g({phase:"upstream_response",headers:i,body:"",bodySize:0,contentType:i["content-type"]??"text/event-stream",account:n.label,accountType:n.type,attempt:u,responseStatus:s.status,durationMs:Date.now()-c,metadata:{logicalStatus:502,upstreamErrorType:"empty_stream"}}),{retryNextAccount:!0,failure:{message:"Empty upstream stream",rateLimit:!1}};if(b.kind==="sse_error"){await _.cancel().catch(()=>{});const R=Buffer.concat(b.chunks.map(D=>Buffer.from(D))).toString("utf8"),A=b.errorType==="rate_limit_error",P=A?429:502,L=nb(i,{model:r.model}),N=Date.now();if(A){const D=fce(L,uF(i["retry-after"]??null),N,V$(i));o.quota=L?Ay(o.quota,L):o.quota;const O=D.reason==="transient"?"transient":"quota";(!o.coolingUntil||D.coolingUntil>o.coolingUntil)&&(o.coolingUntil=D.coolingUntil,o.coolingReason=D.reason,await Td(n.key,D.coolingUntil,D.reason).catch(()=>{})),$r(n.label,n.type,429,O),h(429,"rate_limit_error",b.message,{retryable:!0,rateLimitKind:O,cooldownReason:D.reason})}else $r(n.label,n.type,P),h(P,b.errorType,b.message,{retryable:!0});return f.always(`[proxy] immediate SSE ${b.errorType} account=${n.label}: ${b.message}; rotating before client commit`),a?.recordRetry(n.label,A?"stream_rate_limit_before_commit":"stream_error_before_commit"),m?.end(),g({phase:"upstream_response",headers:i,body:R,bodySize:Buffer.byteLength(R,"utf8"),contentType:i["content-type"]??"text/event-stream",account:n.label,accountType:n.type,attempt:u,responseStatus:s.status,durationMs:Date.now()-c,metadata:{logicalStatus:P,upstreamErrorType:b.errorType}}),{retryNextAccount:!0,failure:{message:b.message,rateLimit:A,...b.errorType==="overloaded_error"?{retryDelayMs:flr(u)}:{}}}}h(s.status,void 0,void 0,{attemptDurationMs:Date.now()-c});const T=aar();let k=!1;const x=new ReadableStream({start(R){for(const A of b.chunks)R.enqueue(A)},async pull(R){if(!k)try{const{done:A,value:P}=await _.read();if(k)return;if(A){k=!0,T.complete(),R.close();return}R.enqueue(P)}catch(A){const P=Sd(A);if(f.always(`[proxy] mid-stream error account=${n.label}: ${P}`),T.fail(P),!k){k=!0;const L=`event: error
|
|
2371
2371
|
data: ${JSON.stringify({type:"error",error:{type:"api_error",message:`Upstream stream interrupted: ${P}`}})}
|
|
2372
2372
|
|
|
2373
2373
|
`;R.enqueue(new TextEncoder().encode(L)),R.close()}}},cancel(){return k=!0,T.cancel(),_.cancel()}}),{response:I,telemetryDone:M}=Icn({ctx:t,account:n,response:s,responseHeaders:i,remainingStream:x,streamOutcome:T.outcome,tracer:a,requestStartTime:l,attemptNumber:u,finalBodyStr:d,upstreamSpan:m,logProxyBody:g,logFinalRequest:v});return M.then(()=>y?.(),()=>y?.()),{response:I,holdsAccountAdmission:!0}}function Ph(e){if(e.kind==="upstream_error")return{status:502,errorType:"stream_error",message:e.message};if(e.kind==="client_cancelled")return{status:499,errorType:"client_cancelled",message:"Client cancelled the streaming response"}}function CF(e,t){e.kind==="upstream_error"&&$r(t.label,t.type,502)}function Icn(e){const{ctx:t,account:r,response:n,responseHeaders:o,remainingStream:s,streamOutcome:i,tracer:a,requestStartTime:l,attemptNumber:c,finalBodyStr:u,upstreamSpan:d,logProxyBody:m,logFinalRequest:h}=e,{stream:g,capture:y}=Oir();let v=s,_;if(a)try{const{stream:k,telemetry:x}=lF({captureRawText:!0});v=v.pipeThrough(k);const I=a,M=d,R=n,A=u.length,P=r.label,L=r.key;_=Promise.all([x,y,i]).then(([N,D,O])=>{const F=cF(O,N.streamErrorMessage);CF(F,r),I.setUsage({inputTokens:N.usage.inputTokens,outputTokens:N.usage.outputTokens,cacheCreationTokens:N.usage.cacheCreationInputTokens,cacheReadTokens:N.usage.cacheReadInputTokens}),Sce(L,N.model,{inputTokens:N.usage.inputTokens,outputTokens:N.usage.outputTokens,cacheCreationTokens:N.usage.cacheCreationInputTokens,cacheReadTokens:N.usage.cacheReadInputTokens}),Ece(P,N.model,{inputTokens:N.usage.inputTokens,outputTokens:N.usage.outputTokens,cacheCreationTokens:N.usage.cacheCreationInputTokens,cacheReadTokens:N.usage.cacheReadInputTokens}),I.logStreamEvents(N.events),I.setResponseInfo(Yar(N));const $=parseFloat(R.headers.get("anthropic-ratelimit-unified-5h-utilization")??""),B=parseFloat(R.headers.get("anthropic-ratelimit-unified-7d-utilization")??""),z={inputTokens:N.usage.inputTokens,outputTokens:N.usage.outputTokens,cacheCreationTokens:N.usage.cacheCreationInputTokens,cacheReadTokens:N.usage.cacheReadInputTokens};isNaN($)||(z.rateLimitAfter5h=$),isNaN(B)||(z.rateLimitAfter7d=B),(!isNaN($)||!isNaN(B))&&I.setUsage(z),I.logUpstreamResponseBody(N.rawText??""),I.recordMetrics(),I.recordBodySizes(A,N.totalBytesReceived),M?.end();const j=Ph(F),K={inputTokens:N.usage.inputTokens,outputTokens:N.usage.outputTokens,cacheCreationTokens:N.usage.cacheCreationInputTokens,cacheReadTokens:N.usage.cacheReadInputTokens};j?(I.setError(j.errorType,j.message),I.end(j.status,Date.now()-l),h(j.status,P,r.type,j.errorType,j.message,K)):(I.end(200,Date.now()-l),h(200,P,r.type,void 0,void 0,K)),m({phase:"upstream_response",headers:o,body:N.rawText??"",bodySize:N.totalBytesReceived,contentType:o["content-type"]??"text/event-stream",account:P,accountType:r.type,attempt:c,responseStatus:200,durationMs:Date.now()-l}),m({phase:"client_response",headers:o,body:D.text,bodySize:D.totalBytes,contentType:o["content-type"]??"text/event-stream",account:P,accountType:r.type,attempt:c,responseStatus:200,durationMs:Date.now()-l})}).catch(N=>{I.setError("stream_telemetry_error",N instanceof Error?N.message:String(N)),M?.end(),I.end(500,Date.now()-l),h(500,P,r.type,"stream_telemetry_error",N instanceof Error?N.message:String(N))})}catch{_=i.then(k=>{CF(k,r);const x=Ph(k);d?.end(),x?(a.setError(x.errorType,x.message),a.end(x.status,Date.now()-l),h(x.status,r.label,r.type,x.errorType,x.message)):(a.end(n.status,Date.now()-l),h(n.status,r.label,r.type))}).catch(()=>{})}else{d?.end();try{const{stream:k,telemetry:x}=lF({captureRawText:!0});v=v.pipeThrough(k);const I=r.label,M=r.key;_=Promise.all([x,y,i]).then(([R,A,P])=>{const L=cF(P,R.streamErrorMessage);CF(L,r);const N=Ph(L),D={inputTokens:R.usage.inputTokens,outputTokens:R.usage.outputTokens,cacheCreationTokens:R.usage.cacheCreationInputTokens,cacheReadTokens:R.usage.cacheReadInputTokens};Sce(M,R.model,D),Ece(I,R.model,D),N?h(N.status,I,r.type,N.errorType,N.message,D):h(200,I,r.type,void 0,void 0,D),m({phase:"upstream_response",headers:o,body:R.rawText??"",bodySize:R.totalBytesReceived,contentType:o["content-type"]??"text/event-stream",account:I,accountType:r.type,attempt:c,responseStatus:200,durationMs:Date.now()-l}),m({phase:"client_response",headers:o,body:A.text,bodySize:A.totalBytes,contentType:o["content-type"]??"text/event-stream",account:I,accountType:r.type,attempt:c,responseStatus:200,durationMs:Date.now()-l})}).catch(R=>{const A=R instanceof Error?R.message:String(R);h(500,r.label,r.type,"stream_telemetry_error",A)})}catch{y.then(k=>{m({phase:"client_response",headers:o,body:k.text,bodySize:k.totalBytes,contentType:o["content-type"]??"text/event-stream",account:r.label,accountType:r.type,attempt:c,responseStatus:200,durationMs:Date.now()-l})}).catch(()=>{}),_=i.then(k=>{CF(k,r);const x=Ph(k);x?h(x.status,r.label,r.type,x.errorType,x.message):h(n.status,r.label,r.type)}).catch(()=>{})}}const b=v.pipeThrough(g),T={...t.responseHeaders??{},"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"};return{response:new Response(b,{status:n.status,headers:T}),telemetryDone:_}}async function Rcn(e){const{account:t,response:r,responseHeaders:n,tracer:o,requestStartTime:s,fetchStartMs:i,attemptNumber:a,finalBodyStr:l,upstreamSpan:c,logAttempt:u,logProxyBody:d,logFinalRequest:m}=e,h=await r.text();u(r.status,void 0,void 0,{attemptDurationMs:Date.now()-i}),o?.logUpstreamResponseBody(h),d({phase:"upstream_response",headers:n,body:h,bodySize:Buffer.byteLength(h,"utf8"),contentType:n["content-type"]??"application/json",account:t.label,accountType:t.type,attempt:a,responseStatus:r.status,durationMs:Date.now()-i}),d({phase:"client_response",headers:n,body:h,bodySize:Buffer.byteLength(h,"utf8"),contentType:n["content-type"]??"application/json",account:t.label,accountType:t.type,attempt:a,responseStatus:r.status,durationMs:Date.now()-s});const g=JSON.parse(h);if(Xar(t,g),o&&g&&typeof g=="object"){const y=g.usage;if(y){o.setUsage({inputTokens:y.input_tokens??0,outputTokens:y.output_tokens??0,cacheCreationTokens:y.cache_creation_input_tokens??0,cacheReadTokens:y.cache_read_input_tokens??0});const _=parseFloat(r.headers.get("anthropic-ratelimit-unified-5h-utilization")??""),b=parseFloat(r.headers.get("anthropic-ratelimit-unified-7d-utilization")??"");if(!isNaN(_)||!isNaN(b)){const T={inputTokens:y.input_tokens??0,outputTokens:y.output_tokens??0,cacheCreationTokens:y.cache_creation_input_tokens??0,cacheReadTokens:y.cache_read_input_tokens??0};isNaN(_)||(T.rateLimitAfter5h=_),isNaN(b)||(T.rateLimitAfter7d=b),o.setUsage(T)}}o.setResponseInfo(Tce(g)),o.recordMetrics();const v=JSON.stringify(g);o.recordBodySizes(l.length,v.length),c?.end(),o.end(r.status,Date.now()-s),m(r.status,t.label,t.type,void 0,void 0,{inputTokens:y?.input_tokens,outputTokens:y?.output_tokens,cacheCreationTokens:y?.cache_creation_input_tokens,cacheReadTokens:y?.cache_read_input_tokens})}else{c?.end();const y=g&&typeof g=="object"?g.usage:void 0;m(r.status,t.label,t.type,void 0,void 0,{inputTokens:y?.input_tokens,outputTokens:y?.output_tokens,cacheCreationTokens:y?.cache_creation_input_tokens,cacheReadTokens:y?.cache_read_input_tokens})}return{response:g}}async function Mcn(e){const{account:t,accountState:r,requestedModel:n,retryResp:o,tracer:s,requestStartTime:i,fetchStartMs:a,attemptNumber:l,finalBodyStr:c,upstreamSpan:u,logAttempt:d,logProxyBody:m,logFinalRequest:h}=e,g=nb(o.headers,{model:n});if(g){r.quota=Ay(r.quota,g);const b=yce(r,g,Date.now());b?.kind==="cooled"?Td(t.key,b.coolingUntil,b.coolingReason).catch(()=>{}):b?.kind==="cleared"&&xy(t.key,b.coolingUntil).catch(()=>{}),Ry(t.key,g).catch(T=>{f.debug("[proxy] Failed to persist account quota after auth retry",{account:t.label,error:T instanceof Error?T.message:String(T)})})}const y=Object.fromEntries([...o.headers.entries()]),v=await o.text();d(o.status,void 0,void 0,{attemptDurationMs:Date.now()-a}),s?.logUpstreamResponseHeaders(y),s?.logUpstreamResponseBody(v),m({phase:"upstream_response",headers:y,body:v,bodySize:Buffer.byteLength(v,"utf8"),contentType:y["content-type"]??"application/json",account:t.label,accountType:t.type,attempt:l,responseStatus:o.status,durationMs:Date.now()-a}),m({phase:"client_response",headers:y,body:v,bodySize:Buffer.byteLength(v,"utf8"),contentType:y["content-type"]??"application/json",account:t.label,accountType:t.type,attempt:l,responseStatus:o.status,durationMs:Date.now()-i});const _=JSON.parse(v);if(Xar(t,_),s&&_&&typeof _=="object"){const b=_.usage;b&&s.setUsage({inputTokens:b.input_tokens??0,outputTokens:b.output_tokens??0,cacheCreationTokens:b.cache_creation_input_tokens??0,cacheReadTokens:b.cache_read_input_tokens??0}),s.setResponseInfo(Tce(_)),s.recordMetrics();const T=JSON.stringify(_);s.recordBodySizes(c.length,T.length),u?.end(),s.end(o.status,Date.now()-i),h(o.status,t.label,t.type,void 0,void 0,{inputTokens:b?.input_tokens,outputTokens:b?.output_tokens,cacheCreationTokens:b?.cache_creation_input_tokens,cacheReadTokens:b?.cache_read_input_tokens})}else u?.end(),h(o.status,t.label,t.type);return _}async function Pcn(e){const{ctx:t,body:r,account:n,accountState:o,headers:s,buildUpstreamBody:i,url:a,enabledAccounts:l,orderedAccounts:c,tracer:u,requestStartTime:d,allocateAttemptNumber:m,upstreamSpan:h,logAttempt:g,logProxyBody:y,onStreamTerminal:v,logFinalRequest:_,lastError:b,authFailureMessage:T,entitlementFailure:k,sawRateLimit:x,sawTransientFailure:I,sawNetworkError:M}=e;$r(n.label,n.type,401),g(401,"authentication_error","received 401 from Anthropic",{retryable:!0});let R=b,A=T,P=k,L=x,N=I,D=M,O=h,F=!1,$="received 401 from Anthropic";for(let B=0;B<qA;B++){f.always(`[proxy] \u2190 401 account=${n.label} refreshing (attempt ${B+1}/${qA})`);const z=await J$(n,n.persistTarget);if(!z.success){if($=`refresh failed for account=${n.label} attempt ${B+1}/${qA}: ${z.error?.slice(0,200)??"unknown"}`,R=$,My(z))await qp(n,o,"refresh_invalid"),A=IF(n.label),f.always(`[proxy] account=${n.label} refresh token rejected; disabled until re-authentication`);else{const ee=await xF(n,o);N=!0,f.always(`[proxy] account=${n.label} refresh temporarily unavailable (${z.status??"network"}); cooling until ${new Date(ee).toISOString()} and rotating`)}break}n.persistTarget&&await Y$(n.persistTarget,n),await AF(n,o),s.authorization=`Bearer ${n.token}`;const j=m(),K=Date.now();Ty(n.label,n.type);const G=(ee,H,Z,Ee)=>g(ee,H,Z,{...Ee,attempt:j,attemptDurationMs:Ee?.attemptDurationMs??Date.now()-K}),Q=i(n.token).bodyStr,ve=Date.now();y({phase:"upstream_request",headers:s,body:Q,bodySize:Buffer.byteLength(Q,"utf8"),contentType:s["content-type"]??"application/json",account:n.label,accountType:n.type,attempt:j,metadata:{upstreamMethod:"POST",upstreamUrl:a}});try{const ee=await pce(a,{method:"POST",headers:s,body:Q,signal:AbortSignal.timeout(GA)});if(ee.ok){F=!0,o.consecutiveRefreshFailures=0,f.always(`[proxy] \u2190 200 account=${n.label} (after ${B+1} refresh(es))`);const J=r.stream?await alr({ctx:t,body:r,account:n,accountState:o,response:ee,tracer:u,requestStartTime:d,fetchStartMs:ve,attemptNumber:j,finalBodyStr:Q,upstreamSpan:O,logAttempt:G,logProxyBody:y,logFinalRequest:_,onStreamTerminal:v}):{response:await Mcn({account:n,accountState:o,requestedModel:r.model,retryResp:ee,tracer:u,requestStartTime:d,fetchStartMs:ve,attemptNumber:j,finalBodyStr:Q,upstreamSpan:O,logAttempt:G,logProxyBody:y,logFinalRequest:_})};if("retryNextAccount"in J){const ie=J.failure;return{continueLoop:!0,...ie?.retryDelayMs?{retryDelayMs:ie.retryDelayMs}:{},lastError:ie?.message??R,authFailureMessage:A,entitlementFailure:P,sawRateLimit:L||!!ie?.rateLimit,sawTransientFailure:N||!!(ie&&!ie.rateLimit),sawNetworkError:D,upstreamSpan:void 0}}return{response:J.response,holdsAccountAdmission:J.holdsAccountAdmission,continueLoop:!1,lastError:R,authFailureMessage:A,entitlementFailure:P,sawRateLimit:L,sawTransientFailure:N,sawNetworkError:D,upstreamSpan:void 0}}const H=ee.status,Z=await ee.text(),Ee={};ee.headers.forEach((J,ie)=>{Ee[ie]=J});const Se={...Ee};delete Se.authorization,delete Se["x-api-key"];const me=Z.length>4e3?Z.slice(0,4e3)+"...[truncated]":Z;if(u?.logUpstreamResponseHeaders(Se),u?.logUpstreamResponseBody(me),y({phase:"upstream_response",headers:Se,body:me,bodySize:Buffer.byteLength(Z,"utf8"),contentType:Ee["content-type"]??"application/json",account:n.label,accountType:n.type,attempt:j,responseStatus:H,durationMs:Date.now()-ve}),$=`retry ${B+1}/${qA} failed with status ${H}`,R=Z,f.debug(`[proxy] retry ${B+1} failed: ${H} ${Z.substring(0,120)}`),H===429&&ulr(Ee,Z))return f.always(`[proxy] \u2190 429 account=${n.label} anti-abuse/construction rejection after OAuth refresh \u2014 returning non-retryable request error`),G(429,"construction_rejection",Z),u?.setError("construction_rejection",Z.slice(0,500)),O?.end(),{response:llr({terminalError:dlr(),account:n,tracer:u,requestStartTime:d,attemptNumber:j,logProxyBody:y,logFinalRequest:_}),continueLoop:!1,lastError:Z,authFailureMessage:A,entitlementFailure:P,sawRateLimit:L,sawTransientFailure:N,sawNetworkError:D,upstreamSpan:void 0};if(H===429){L=!0;const J=Date.now(),ie=nb(Ee,{model:r.model});ie&&(o.quota=Ay(o.quota,ie));const le=fce(ie,uF(Ee["retry-after"]??null),J,V$(Ee)),te=le.reason==="transient"?"transient":"quota";$r(n.label,n.type,H,te),G(429,"rate_limit_error",Z,{retryable:!0,rateLimitKind:te,cooldownReason:le.reason}),(!o.coolingUntil||le.coolingUntil>o.coolingUntil)&&(o.coolingUntil=le.coolingUntil,o.coolingReason=le.reason),ie&&Ry(n.key,ie).catch(()=>{}),await Td(n.key,o.coolingUntil??le.coolingUntil,o.coolingReason??le.reason).catch(()=>{}),Dy(n.key,l.length,c[0]?.key);break}if(H===401||H===402||H===403){if(Ace(H,Z)){const J=Cd(Z);$r(n.label,n.type,H),G(H,"permission_error",Or(Z)),P={status:H,accounts:[...P?.accounts??[],n.label],message:P?.message??J.message??Or(Z),...J.errorCode?{errorCode:J.errorCode}:{}},n.type==="oauth"&&vlr(H,Z)&&await qp(n,o,"entitlement_blocked"),$=`entitlement blocked for account=${n.label}`,R=$,f.always(`[proxy] \u2190 ${H} account=${n.label} entitlement blocked after refresh; advancing to next account`);break}$r(n.label,n.type,H),G(H,"authentication_error",Or(Z),{retryable:!0}),B<qA-1&&await Gp(1e3);continue}if(wlr(H,Z)){$r(n.label,n.type,H),G(H,"api_error",Or(Z),{retryable:!0}),N=!0;break}G(H,"api_error",Or(Z));try{return _(H,n.label,n.type,"api_error",Or(Z)),{response:JSON.parse(Z),continueLoop:!1,lastError:R,authFailureMessage:A,entitlementFailure:P,sawRateLimit:L,sawTransientFailure:N,sawNetworkError:D,upstreamSpan:O}}catch{return _(H,n.label,n.type,"api_error",Or(Z)),{response:ul(H,Z),continueLoop:!1,lastError:R,authFailureMessage:A,entitlementFailure:P,sawRateLimit:L,sawTransientFailure:N,sawNetworkError:D,upstreamSpan:O}}}catch(ee){D=!0,$r(n.label,n.type,502);const H=ee instanceof Error?ee.message:String(ee);$=`network error on retry ${B+1}: ${H}`,R=$;const Z=xce(ee);if(G(502,"network_error",H,{retryable:Z,errorCode:KA(ee)??"unknown"}),f.debug(`[proxy] ${$}`),!Z)return O?.end(),{response:clr({account:n,tracer:u,requestStartTime:d,attemptNumber:j,logProxyBody:y,logFinalRequest:_,errorType:"network_error",message:H}),continueLoop:!1,lastError:R,authFailureMessage:A,entitlementFailure:P,sawRateLimit:L,sawTransientFailure:N,sawNetworkError:D,upstreamSpan:void 0};break}}return F||(R=$,f.always(`[proxy] \u26A0 account=${n.label} auth retries exhausted, rotating to next account`),u?.setError("authentication_error",$),u?.recordRetry(n.label,"auth_exhausted"),O?.end(),O=void 0,Dy(n.key,l.length,c[0]?.key)),{continueLoop:!0,lastError:R,authFailureMessage:A,entitlementFailure:P,sawRateLimit:L,sawTransientFailure:N,sawNetworkError:D,upstreamSpan:O}}function Cce(e){const{responseStatus:t,account:r,errBody:n,errRespHeaders:o,requestStartTime:s,attemptNumber:i,logProxyBody:a,logFinalRequest:l,errorType:c}=e;try{const u=JSON.parse(n);return l(t,r.label,r.type,c,Or(n)),a({phase:"client_response",headers:{"content-type":o["content-type"]??"application/json"},body:n,bodySize:Buffer.byteLength(n,"utf8"),contentType:o["content-type"]??"application/json",account:r.label,accountType:r.type,attempt:i,responseStatus:t,durationMs:Date.now()-s}),u}catch{l(t,r.label,r.type,c,Or(n));const u=ul(t,n),d=JSON.stringify(u);return a({phase:"client_response",headers:{"content-type":"application/json"},body:d,bodySize:Buffer.byteLength(d,"utf8"),contentType:"application/json",account:r.label,accountType:r.type,attempt:i,responseStatus:t,durationMs:Date.now()-s}),u}}function llr(e){const{terminalError:t,account:r,tracer:n,requestStartTime:o,attemptNumber:s,logProxyBody:i,logFinalRequest:a}=e;return n?.end(t.status,Date.now()-o),Cce({responseStatus:t.status,account:r,errBody:t.body,errRespHeaders:t.headers,requestStartTime:o,attemptNumber:s,logProxyBody:i,logFinalRequest:a,errorType:t.errorType})}function clr(e){const{account:t,tracer:r,requestStartTime:n,attemptNumber:o,logProxyBody:s,logFinalRequest:i,errorType:a,message:l}=e;r?.setError(a,l),r?.end(502,Date.now()-n),i(502,t.label,t.type,a,l);const c=ul(502,l),u=JSON.stringify(c);return s({phase:"client_response",headers:{"content-type":"application/json"},body:u,bodySize:Buffer.byteLength(u,"utf8"),contentType:"application/json",account:t.label,accountType:t.type,attempt:o,responseStatus:502,durationMs:Date.now()-n}),c}async function Dcn(e){const{response:t,account:r,accountState:n,enabledAccounts:o,orderedAccounts:s,tracer:i,requestStartTime:a,fetchStartMs:l,attemptNumber:c,logAttempt:u,logProxyBody:d,logFinalRequest:m,lastError:h,authFailureMessage:g,sawTransientFailure:y,invalidRequestFailure:v,entitlementFailure:_,allowConfiguredModelFallback:b=!1}=e;let T=h,k=g,x=y,I=v,M=_;const R=await t.text(),A={};if(t.headers.forEach((P,L)=>{A[L]=P}),i?.logUpstreamResponseHeaders(A),i?.logUpstreamResponseBody(R),d({phase:"upstream_response",headers:A,body:R,bodySize:Buffer.byteLength(R,"utf8"),contentType:A["content-type"]??"application/json",account:r.label,accountType:r.type,attempt:c,responseStatus:t.status,durationMs:Date.now()-l}),Wcn(t.status,R))return Jcn(t.status,R)?(f.always(`[proxy] \u2190 ${t.status} account=${r.label} beta unavailable for subscription; advancing to next account`),u(t.status,"invalid_request_error",Or(R)),i?.setError("invalid_request_error",Or(R)),i?.recordRetry(r.label,"beta_unavailable"),Dy(r.key,o.length,s[0]?.key),T=Or(R),{continueLoop:!0,lastError:T,authFailureMessage:k,sawTransientFailure:x,invalidRequestFailure:I,entitlementFailure:M,upstreamSpan:void 0}):(f.always(`[proxy] \u2190 ${t.status} upstream invalid_request_error`),u(t.status,"invalid_request_error",Or(R)),i?.setError("invalid_request_error",Or(R)),I={status:t.status,body:R,contentType:A["content-type"]},T=Or(R),{continueLoop:!1,lastError:T,authFailureMessage:k,sawTransientFailure:x,invalidRequestFailure:I,entitlementFailure:M,upstreamSpan:void 0});if(r.type==="oauth"&&Ace(t.status,R)){const P=Cd(R);return $r(r.label,r.type,t.status),M={status:t.status,accounts:[...M?.accounts??[],r.label],message:M?.message??P.message??Or(R),...P.errorCode?{errorCode:P.errorCode}:{}},f.always(`[proxy] \u2190 ${t.status} account=${r.label} entitlement blocked${P.errorCode?` (${P.errorCode})`:""}; advancing to next account`),u(t.status,"permission_error",Or(R)),i?.setError("permission_error",Or(R)),i?.recordRetry(r.label,"entitlement_blocked"),r.type==="oauth"&&vlr(t.status,R)&&await qp(r,n,"entitlement_blocked"),Dy(r.key,o.length,s[0]?.key),T=Or(R),{continueLoop:!0,lastError:T,authFailureMessage:k,sawTransientFailure:x,invalidRequestFailure:I,entitlementFailure:M,upstreamSpan:void 0}}if((t.status===401||t.status===402||t.status===403)&&r.type==="oauth"&&!r.refreshToken)return $r(r.label,r.type,t.status),await qp(r,n,"missing_refresh_token"),k=IF(r.label),f.always(`[proxy] \u2190 ${t.status} account=${r.label} (auth failure, no refresh token)`),T=R,u(t.status,"authentication_error",Or(R)),i?.setError("authentication_error",Or(R)),i?.recordRetry(r.label,"auth_no_refresh"),Dy(r.key,o.length,s[0]?.key),{continueLoop:!0,lastError:T,authFailureMessage:k,sawTransientFailure:x,invalidRequestFailure:I,entitlementFailure:M,upstreamSpan:void 0};if((t.status===401||t.status===402||t.status===403)&&r.type==="api_key")return $r(r.label,r.type,t.status),k="Authentication failed for Anthropic API key credentials. Update ANTHROPIC_API_KEY or re-login with OAuth.",f.always(`[proxy] \u2190 ${t.status} account=${r.label} (auth failure, api_key)`),T=R,u(t.status,"authentication_error",Or(R)),i?.setError("authentication_error",Or(R)),i?.recordRetry(r.label,"auth_api_key"),Dy(r.key,o.length,s[0]?.key),{continueLoop:!0,lastError:T,authFailureMessage:k,sawTransientFailure:x,invalidRequestFailure:I,entitlementFailure:M,upstreamSpan:void 0};if(t.status===404)return b&&Kcn(t.status,R)?(f.always(`[proxy] \u2190 404 account=${r.label} model unavailable; trying configured fallback`),u(404,"not_found_error",Or(R)),i?.setError("not_found_error",Or(R)),i?.recordRetry(r.label,"model_not_found"),T=Or(R),{continueLoop:!1,lastError:T,authFailureMessage:k,sawTransientFailure:x,invalidRequestFailure:I,entitlementFailure:M,upstreamSpan:void 0}):(f.always(`[proxy] \u2190 404 account=${r.label}`),u(404,"not_found_error",Or(R)),i?.setError("not_found_error",Or(R)),i?.end(404,Date.now()-a),{response:Cce({responseStatus:404,account:r,errBody:R,errRespHeaders:A,requestStartTime:a,attemptNumber:c,logProxyBody:d,logFinalRequest:m,errorType:"not_found_error"}),continueLoop:!1,lastError:T,authFailureMessage:k,sawTransientFailure:x,invalidRequestFailure:I,entitlementFailure:M,upstreamSpan:void 0});if(wlr(t.status,R)){const P=Zcn(t.status,R);return $r(r.label,r.type,t.status,t.status===429?"transient":void 0),x=!0,f.always(`[proxy] \u2190 ${t.status} account=${r.label} (${P?"overloaded":"transient"})`),T=R,u(t.status,"api_error",Or(R),t.status===429?{retryable:!0,rateLimitKind:"transient",cooldownReason:"transient"}:void 0),i?.setError(P?"overloaded_error":"transient_error",Or(R)),i?.recordRetry(r.label,P?"overloaded":"transient"),{continueLoop:!0,retrySameAccount:!P,...P?{retryDelayMs:flr(c)}:{},lastError:T,authFailureMessage:k,sawTransientFailure:x,invalidRequestFailure:I,entitlementFailure:M,upstreamSpan:void 0}}return f.always(`[proxy] \u2190 ${t.status} account=${r.label}`),f.debug(`[claude-proxy] error body: ${R.substring(0,200)}`),u(t.status,"api_error",Or(R)),i?.setError("api_error",Or(R)),i?.end(t.status,Date.now()-a),{response:Cce({responseStatus:t.status,account:r,errBody:R,errRespHeaders:A,requestStartTime:a,attemptNumber:c,logProxyBody:d,logFinalRequest:m,errorType:"api_error"}),continueLoop:!1,lastError:T,authFailureMessage:k,sawTransientFailure:x,invalidRequestFailure:I,entitlementFailure:M,upstreamSpan:void 0}}function Ocn(e){const{ctx:t,body:r,clientRequestBody:n}=e;let o;try{o=$le.startRequest({requestId:t.requestId,method:t.method,path:t.path,model:r.model,stream:r.stream??!1,toolCount:Array.isArray(r.tools)?r.tools.length:0,toolNames:Array.isArray(r.tools)?r.tools.map(h=>h&&typeof h=="object"&&"name"in h?String(h.name??""):"").filter(h=>h.length>0):void 0,sessionId:t.headers["x-neurolink-session-id"]??t.headers["x-claude-code-session-id"]??void 0,userAgent:t.headers["user-agent"]??void 0},t.headers);const m=o.startReceive();o.logRequestHeaders(t.headers),o.logRequestBody(n),m.end()}catch{o=void 0}const s=Date.now(),i=m=>{const h=o?.getTraceContext();Ksn({timestamp:new Date().toISOString(),requestId:t.requestId,model:r.model,stream:r.stream??!1,...m,...h?{traceId:h.traceId,spanId:h.spanId}:{}})};let a;const l=m=>{if(a){f.debug(`[claude-proxy] ignored duplicate routing decision for request ${t.requestId}`);return}a=m};let c=!1;const u=(m,h,g,y,v,_)=>{if(c){f.debug(`[claude-proxy] ignored duplicate finalization for request ${t.requestId}`);return}c=!0;const b=h||(m>=400?ace:void 0),T=h?g||void 0:m>=400?lce:void 0,k=Ear(b,T);m>=400?Uw(m,b,T,{requestId:t.requestId,...k.accountKey?{accountKey:k.accountKey}:{},errorType:y,terminalOutcome:y==="client_cancelled"?"client_cancelled":y?.includes("stream")?"stream_error":"handler_error",message:v,errorCode:_?.errorCode}):iA(b,T);const x=o?.getTraceContext();Rh({timestamp:new Date().toISOString(),requestId:t.requestId,method:t.method,path:t.path,model:r.model,stream:!!r.stream,toolCount:Array.isArray(r.tools)?r.tools.length:0,account:b??"",...k.accountKey?{accountKey:k.accountKey}:{},accountType:T??"",...k.provider?{provider:k.provider}:{},...cb(t.headers),responseStatus:m,responseTimeMs:Date.now()-s,...y?{errorType:y}:{},...v?{errorMessage:v}:{},..._?.errorCode?{errorCode:_.errorCode}:{},..._?.transportScope?{transportScope:_.transportScope}:{},..._?.inputTokens!==void 0?{inputTokens:_.inputTokens}:{},..._?.outputTokens!==void 0?{outputTokens:_.outputTokens}:{},..._?.cacheCreationTokens!==void 0?{cacheCreationTokens:_.cacheCreationTokens}:{},..._?.cacheReadTokens!==void 0?{cacheReadTokens:_.cacheReadTokens}:{},...x?{traceId:x.traceId,spanId:x.spanId}:{},...a?{routingDecision:a}:{}})},d=(m,h,g,y)=>{const v=ul(m,h,g),_=JSON.stringify(v);return u(m,y?.account??"",y?.accountType??"final",g,h,y),i({phase:"client_response",headers:{"content-type":"application/json"},body:_,bodySize:Buffer.byteLength(_,"utf8"),contentType:"application/json",responseStatus:m,durationMs:Date.now()-s,...y}),v};return i({phase:"client_request",headers:t.headers,body:n,bodySize:Buffer.byteLength(n,"utf8"),contentType:t.headers["content-type"]??"application/json"}),{tracer:o,requestStartTime:s,logProxyBody:i,logFinalRequest:u,buildLoggedClaudeError:d,setRoutingDecision:l}}function Ncn(e){const{ctx:t,body:r,toolCount:n,requestStart:o,tracer:s,account:i,attemptNumber:a}=e,l=Date.now(),c=Ear(i.label,i.type);return(u,d,m,h)=>{const g=Date.now(),y=s?.getTraceContext();Air({timestamp:new Date().toISOString(),requestId:t.requestId,attempt:h?.attempt??a,method:t.method,path:t.path,model:r.model,stream:!!r.stream,toolCount:n,account:i.label,accountKey:i.key,accountType:i.type,...c.provider?{provider:c.provider}:{},responseStatus:u,responseTimeMs:g-o,attemptDurationMs:h?.attemptDurationMs??g-l,...d?{errorType:d}:{},...m?{errorMessage:m}:{},...h?.errorCode?{errorCode:h.errorCode}:{},...h?.transportScope?{transportScope:h.transportScope}:{},...h?.inputTokens!==void 0?{inputTokens:h.inputTokens}:{},...h?.outputTokens!==void 0?{outputTokens:h.outputTokens}:{},...h?.cacheCreationTokens!==void 0?{cacheCreationTokens:h.cacheCreationTokens}:{},...h?.cacheReadTokens!==void 0?{cacheReadTokens:h.cacheReadTokens}:{},...h?.retryable!==void 0?{retryable:h.retryable}:{},...h?.rateLimitKind?{rateLimitKind:h.rateLimitKind}:{},...h?.cooldownReason?{cooldownReason:h.cooldownReason}:{},...y?{traceId:y.traceId,spanId:y.spanId}:{}})}}async function Lcn(e){const{account:t,accountState:r,bodyStr:n,clientHeaders:o,isClaudeClientRequest:s,url:i,tracer:a,attemptNumber:l,currentLastError:c,currentAuthFailureMessage:u,logAttempt:d,logProxyBody:m}=e;let h=c,g=u;if(gle(t)){const R=await J$(t,t.persistTarget);if(R.success)t.persistTarget&&await Y$(t.persistTarget,t),await AF(t,r);else return h=`token refresh failed for account=${t.label}: ${R.error?.slice(0,200)??"unknown"}`,My(R)?(await qp(t,r,"refresh_invalid"),g=IF(t.label)):await xF(t,r),d(My(R)?401:503,My(R)?"authentication_error":"token_refresh_unavailable",String(h)),{continueLoop:!0,lastError:h,authFailureMessage:g}}const y=t.type==="oauth",v={};for(const[R,A]of Object.entries(o))typeof A=="string"&&(v[R]=A);const _=y?await Qln(t.label,t.key,v,n):null,b={};for(const[R,A]of Object.entries(o)){const P=R.toLowerCase();typeof A=="string"&&!hF.has(P)&&(b[P]=A)}if(b["content-type"]="application/json",y?(b.authorization=`Bearer ${t.token}`,delete b["x-api-key"],Kln(b,_)):(b["x-api-key"]=t.token,delete b.authorization),b["user-agent"]||(b["user-agent"]=Ag),b["anthropic-version"]||(b["anthropic-version"]="2023-06-01"),b["anthropic-dangerous-direct-browser-access"]||(b["anthropic-dangerous-direct-browser-access"]="true"),b["x-app"]||(b["x-app"]="cli"),b.accept||(b.accept="application/json"),y){const R=s?b["anthropic-beta"]??"":o["anthropic-beta"]??"",A=new Set(R.split(",").map(P=>P.trim()).filter(Boolean));for(const P of s?mk:Wln)A.add(P);b["anthropic-beta"]=[...A].join(",")}else{const R=(b["anthropic-beta"]??"").split(",").map(A=>A.trim()).filter(A=>A&&!mk.includes(A)).join(",");R?b["anthropic-beta"]=R:delete b["anthropic-beta"]}const T=R=>y?ecn(n,R,_,s,b["x-claude-code-session-id"]):{bodyStr:n},k=T(t.token);y&&k.sessionId&&!b["x-claude-code-session-id"]&&(b["x-claude-code-session-id"]=k.sessionId);const x=k.bodyStr;f.always(`[proxy] \u2192 account=${t.label} (${t.type})`),Ty(t.label,t.type);const I=Date.now();let M;return a&&(M=a.startUpstreamAttempt({attempt:l,account:t.label,polyfillHeaders:y,polyfillBody:y,upstreamUrl:i}),a.logUpstreamRequestHeaders(b),a.logUpstreamRequestBody(x),Object.assign(b,a.getTraceHeaders())),m({phase:"upstream_request",headers:b,body:x,bodySize:Buffer.byteLength(x,"utf8"),contentType:b["content-type"]??"application/json",account:t.label,accountType:t.type,attempt:l,metadata:{upstreamMethod:"POST",upstreamUrl:i}}),{continueLoop:!1,lastError:h,authFailureMessage:g,headers:b,buildUpstreamBody:T,finalBodyStr:x,fetchStartMs:I,upstreamSpan:M}}function ulr(e,t){const r=!!e["retry-after"],n=Object.keys(e).some(o=>o.toLowerCase().startsWith("anthropic-ratelimit-"));return r||n?!1:t.includes("rate_limit_error")&&/"message"\s*:\s*"Error"/.test(t)}function dlr(){return{status:400,body:JSON.stringify(ul(400,"Anthropic rejected the OAuth request shape. This is not an account rate limit.","invalid_request_error")),headers:{"content-type":"application/json"},errorType:"construction_rejection"}}async function $cn(e){const{url:t,headers:r,finalBodyStr:n,requestedModel:o,account:s,accountState:i,enabledAccounts:a,orderedAccounts:l,tracer:c,logAttempt:u,logProxyBody:d,fetchStartMs:m,attemptNumber:h,currentLastError:g,currentSawRateLimit:y,currentSawNetworkError:v,upstreamSpan:_}=e;let b=g,T=y,k=v;const x=_;let I;try{I=await pce(t,{method:"POST",headers:r,body:n,signal:AbortSignal.timeout(GA)})}catch(M){const R=xce(M),A=Hcn(M);k=!0,$r(s.label,s.type,502);const P=KA(M)??"unknown",L=M instanceof Error?M.message:String(M);if(b=L,f.always(`[proxy] fetch error account=${s.label} code=${P} (${R?"retryable":"terminal"}): ${L}`),u(502,"network_error",L,{retryable:R,errorCode:P,transportScope:A}),c?.setError("network_error",L),R&&c?.recordRetry(s.label,"network_error"),x?.end(),!R)throw M;return{continueLoop:!0,retrySameAccount:!0,transportScope:A,errorCode:P,lastError:b,sawRateLimit:T,sawNetworkError:k,upstreamSpan:void 0}}if(I.status===429){const M=uF(I.headers.get("retry-after")),R={};I.headers.forEach(($,B)=>{R[B]=$}),b=await I.text();const A={...R};delete A.authorization,delete A["x-api-key"];const P=String(b).length>4e3?String(b).slice(0,4e3)+"...[truncated]":String(b);if(c?.logUpstreamResponseHeaders(A),c?.logUpstreamResponseBody(P),d({phase:"upstream_response",headers:A,body:P,bodySize:Buffer.byteLength(String(b),"utf8"),contentType:R["content-type"]??"application/json",account:s.label,accountType:s.type,attempt:h,responseStatus:429,durationMs:Date.now()-m}),ulr(R,String(b)))return f.always(`[proxy] \u2190 429 account=${s.label} anti-abuse/construction rejection (no ratelimit headers, body="Error") \u2014 NOT a real rate limit; returning non-retryable request error`),u(429,"construction_rejection",String(b)),c?.setError("construction_rejection",String(b).slice(0,500)),x?.end(),{continueLoop:!1,terminalError:dlr(),lastError:b,sawRateLimit:T,sawNetworkError:k,upstreamSpan:void 0};T=!0;const L=Date.now(),N=nb(R,{model:o}),D=V$(R),O=fce(N,M,L,D),F=O.reason==="transient"?"transient":"quota";return $r(s.label,s.type,429,F),f.always(`[proxy] \u2190 429 account=${s.label} reason=${O.reason} retry-after=${M}ms 5h-status=${R["anthropic-ratelimit-unified-5h-status"]??"unknown"} 7d-status=${R["anthropic-ratelimit-unified-7d-status"]??"unknown"} unified-status=${D??"unknown"} \u2192 ${O.rotateImmediately?`rotate now, cool ${gce(O.coolingUntil,L)}m`:"retry same account (transient)"}`),u(429,"rate_limit_error",String(b),{retryable:!0,rateLimitKind:F,cooldownReason:O.reason}),c?.setError("rate_limit_error",String(b).slice(0,500)),c?.recordRetry(s.label,"rate_limit"),x?.end(),{continueLoop:!0,retrySameAccount:!O.rotateImmediately,retryAfterMs:M,cooldownPlan:O,...N?{quota:N}:{},lastError:b,sawRateLimit:T,sawNetworkError:k,upstreamSpan:void 0}}return{continueLoop:!1,response:I,lastError:b,sawRateLimit:T,sawNetworkError:k,upstreamSpan:x}}function Fcn(e){return e.invalidRequestFailure===null}function Ucn(e){const{ctx:t,tracer:r,requestStartTime:n,failure:o,buildLoggedClaudeError:s}=e;return o.responseHeaders&&(t.responseHeaders={...t.responseHeaders??{},...o.responseHeaders}),r?.setError(o.errorType,o.message),r?.end(o.status,Date.now()-n),s(o.status,o.message,o.errorType)}async function Bcn(e){const{ctx:t,body:r,modelRouter:n,tracer:o,requestStartTime:s,accountStrategy:i,primaryAccountKey:a,accountAllowlist:l,quotaRoutingEnabled:c=_ce(),sessionSoftLimit:u=wce(),sessionResetToleranceMs:d=WA(),buildLoggedClaudeError:m,logProxyBody:h,logFinalRequest:g,setRoutingDecision:y}=e,v=wle(r),_=gb({provider:"anthropic",model:r.model},n?.getFallbackChain()??[],r.model,v),b=_.attempts.slice(1).some(G=>!!(G.provider&&G.model)),T=await _cn({ctx:t,body:r,accountStrategy:i,primaryAccountKey:a,accountAllowlist:l,quotaRoutingEnabled:c,sessionSoftLimit:u,sessionResetToleranceMs:d,setRoutingDecision:y});if("failure"in T){const G=await rlr({body:r,logFinalRequest:g});if(G)return G;const Q=await nlr({ctx:t,body:r,parsedFallbackRequest:v,fallbackPlan:_,modelRouter:n,tracer:o,requestStartTime:s,logProxyBody:h,logFinalRequest:g});return Q.response?Q.response:Q.invalidRequestFailure?ilr({tracer:o,requestStartTime:s,authFailureMessage:null,authCooldownMessage:null,invalidRequestFailure:Q.invalidRequestFailure,entitlementFailure:null,scopedExhaustion:null,sawNetworkError:!1,sawTransientFailure:!1,sawRateLimit:!1,lastError:void 0,orderedAccounts:[],buildLoggedClaudeError:m,logProxyBody:h,logFinalRequest:g}):Ucn({ctx:t,tracer:o,requestStartTime:s,failure:T.failure,buildLoggedClaudeError:m})}const{accounts:k,enabledAccounts:x,orderedAccounts:I,bodyStr:M,requestStart:R,toolCount:A,url:P,clientHeaders:L,isClaudeClientRequest:N}=T,D=Nln(),O={lastError:void 0,sawRateLimit:!1,sawNetworkError:!1,sawTransientFailure:!1,invalidRequestFailure:null,authFailureMessage:null,authCooldownMessage:null,entitlementFailure:null,scopedExhaustion:null,attemptNumber:0},F=o?.startAccountSelection();let B=I.filter(G=>!Bar(G.key));if(B.length===0&&(B=await Mln(I)),B.length===0&&I.length>0){const G=I.map(ve=>dl(ve.key)),Q=G.some(ve=>ve.coolingReason!=="auth");if(O.sawRateLimit=Q,O.sawTransientFailure=!Q,O.lastError=Q?"All Anthropic accounts have active rate-limit cooldowns":"All Anthropic accounts have active authentication cooldowns",!Q){const ve=Math.min(...G.map(ee=>ee.coolingUntil??Number.POSITIVE_INFINITY));O.authCooldownMessage=`All ${I.length} Anthropic accounts are temporarily unavailable while OAuth refresh is cooling. Earliest retry at ${new Date(ve).toISOString()}.`}}const z=Uln(B,typeof r.model=="string"?r.model:void 0,Date.now(),D);z.eligible.length>0?B=z.eligible:z.exhaustion&&(O.scopedExhaustion=z.exhaustion,O.lastError=`Model-scoped limit exhausted for ${z.exhaustion.model}`,B=[]);const j=n?.getMaxInflightPerAccount?.();let K;j!==void 0&&B.length>0&&B.every(G=>!Tln(G.key,j))&&(K=await Sln(B.map(G=>G.key),j,t.abortSignal));e:for(const[G,Q]of B.entries()){const ve=G<B.length-1,ee=dl(Q.key);let H=0,Z=0;for(;;){const Ee=await yb.acquire(t.abortSignal);if(Ee.allowed===!1){O.sawNetworkError=!0,O.lastTransportErrorCode=Ee.errorCode??void 0,O.lastTransportScope=Ee.transportScope,O.lastError=`Anthropic transport recovery probe failed (${Ee.errorCode??"unknown"})`;break e}O.attemptNumber+=1,o&&O.attemptNumber===1&&F&&(o.setAccountSelection({strategy:i,accountsTotal:k.length,accountsHealthy:x.length,selectedAccount:Q.label,accountType:Q.type}),F.end());const Se=Ncn({ctx:t,body:r,toolCount:A,requestStart:R,tracer:o,account:Q,attemptNumber:O.attemptNumber}),me=await Lcn({account:Q,accountState:ee,bodyStr:M,clientHeaders:L,isClaudeClientRequest:N,url:P,tracer:o,attemptNumber:O.attemptNumber,currentLastError:O.lastError,currentAuthFailureMessage:O.authFailureMessage,logAttempt:Se,logProxyBody:h});if(O.lastError=me.lastError,O.authFailureMessage=me.authFailureMessage,me.continueLoop||!me.headers||!me.buildUpstreamBody||!me.finalBodyStr||me.fetchStartMs===void 0){Ee.probe&&yb.reportProbeAbandoned(Ee);continue e}let J;if(K?.accountKey===Q.key?(J=K.lease,K=void 0):(J=bln(Q.key,j),J&&K&&(K.lease.release(),K=void 0)),!J){Ee.probe&&yb.reportProbeAbandoned(Ee);continue e}let ie=!1;try{let le;try{le=await $cn({url:P,headers:me.headers,finalBodyStr:me.finalBodyStr,requestedModel:r.model,account:Q,accountState:ee,enabledAccounts:x,orderedAccounts:I,tracer:o,logAttempt:Se,logProxyBody:h,fetchStartMs:me.fetchStartMs,attemptNumber:O.attemptNumber,currentLastError:O.lastError,currentSawRateLimit:O.sawRateLimit,currentSawNetworkError:O.sawNetworkError,upstreamSpan:me.upstreamSpan})}catch(ue){throw Ee.probe&&yb.reportProbeAbandoned(Ee),ue}if(le.transportScope?yb.reportTransportFailure(le.errorCode,le.transportScope,Ee):yb.reportSuccess(Ee),O.lastError=le.lastError,O.sawRateLimit=le.sawRateLimit,O.sawNetworkError=le.sawNetworkError,le.transportScope&&(O.lastTransportScope=le.transportScope,O.lastTransportErrorCode=le.errorCode),le.terminalError)return llr({terminalError:le.terminalError,account:Q,tracer:o,requestStartTime:s,attemptNumber:O.attemptNumber,logProxyBody:h,logFinalRequest:g});if(le.continueLoop||!le.response){if(le.cooldownPlan){const ue=le.cooldownPlan;le.quota&&(ee.quota=Ay(ee.quota,le.quota),Ry(Q.key,le.quota).catch(()=>{}));let ne=!1;(!ee.coolingUntil||ue.coolingUntil>ee.coolingUntil)&&(ee.coolingUntil=ue.coolingUntil,ee.coolingReason=ue.reason,ne=!0),ne&&await Td(Q.key,ee.coolingUntil,ee.coolingReason??ue.reason).catch(()=>{});const $e=le.retrySameAccount?Iln(Q.key,ue.coolingUntil):void 0;if(le.retrySameAccount&&le.retryAfterMs!==void 0&&Z<dce&&$e!==void 0){Z+=1;const ae=Math.min(le.retryAfterMs||1e3,kar),se=Math.min(kar,glr(ae*$e));f.always(`[proxy] retrying same account=${Q.label} after transient 429 (shared slot ${$e}/${dce}) in ${se}ms`),await Gp(se);continue}Dy(Q.key,x.length,I[0]?.key),f.always(`[proxy] account=${Q.label} rate-limited (${ue.reason}); cooling ~${gce(ue.coolingUntil,Date.now())}m until ${new Date(ue.coolingUntil).toISOString()}, rotating`),ue.rotateImmediately&&jln(Q,B[G+1],ue.coolingUntil,u);continue e}if(le.retrySameAccount&&H<fF){H+=1;const ue=hlr(H);f.always(`[proxy] retrying same account=${Q.label} after transient network error (${H}/${fF}) in ${ue}ms`),await Gp(ue);continue}if(le.retrySameAccount&&!le.transportScope&&f.always(`[proxy] exhausted transient same-account retries for account=${Q.label}; rotating`),le.transportScope){f.always(`[proxy] Anthropic ${le.transportScope} failure code=${le.errorCode??"unknown"}; suppressing cross-account rotation after ${H+1} attempts`);break e}continue e}let te=le.upstreamSpan;const Ie=le.response;if(Ie.status===401&&Q.type==="oauth"&&Q.refreshToken){const ue=await Pcn({ctx:t,body:r,account:Q,accountState:ee,headers:me.headers,buildUpstreamBody:me.buildUpstreamBody,url:P,enabledAccounts:x,orderedAccounts:I,tracer:o,requestStartTime:s,allocateAttemptNumber:()=>(O.attemptNumber+=1,O.attemptNumber),upstreamSpan:te,logAttempt:Se,logProxyBody:h,logFinalRequest:g,onStreamTerminal:J.release,lastError:O.lastError,authFailureMessage:O.authFailureMessage,entitlementFailure:O.entitlementFailure,sawRateLimit:O.sawRateLimit,sawTransientFailure:O.sawTransientFailure,sawNetworkError:O.sawNetworkError});if(O.lastError=ue.lastError,O.authFailureMessage=ue.authFailureMessage,O.entitlementFailure=ue.entitlementFailure,O.sawRateLimit=ue.sawRateLimit,O.sawTransientFailure=ue.sawTransientFailure,O.sawNetworkError=ue.sawNetworkError,te=ue.upstreamSpan,ue.response!==void 0)return ie=ue.holdsAccountAdmission===!0,ue.response;if(ue.continueLoop){ve&&ue.retryDelayMs&&(f.always(`[proxy] pacing cross-account SSE overload rotation for ${ue.retryDelayMs}ms after auth refresh`),await Gp(ue.retryDelayMs));continue e}}if(!Ie.ok){const ue=await Dcn({response:Ie,account:Q,accountState:ee,enabledAccounts:x,orderedAccounts:I,tracer:o,requestStartTime:s,fetchStartMs:me.fetchStartMs,attemptNumber:O.attemptNumber,logAttempt:Se,logProxyBody:h,logFinalRequest:g,lastError:O.lastError,authFailureMessage:O.authFailureMessage,sawTransientFailure:O.sawTransientFailure,invalidRequestFailure:O.invalidRequestFailure,entitlementFailure:O.entitlementFailure,allowConfiguredModelFallback:b});if(O.lastError=ue.lastError,O.authFailureMessage=ue.authFailureMessage,O.sawTransientFailure=ue.sawTransientFailure,O.invalidRequestFailure=ue.invalidRequestFailure,O.entitlementFailure=ue.entitlementFailure,ue.response!==void 0)return ue.response;if(ue.continueLoop){if(ue.retrySameAccount&&H<fF){H+=1;const ne=hlr(H);f.always(`[proxy] retrying same account=${Q.label} after transient upstream ${Ie.status} (${H}/${fF}) in ${ne}ms`),await Gp(ne);continue}ue.retrySameAccount&&f.always(`[proxy] exhausted transient same-account retries for account=${Q.label}; rotating`),ve&&ue.retryDelayMs&&(f.always(`[proxy] pacing cross-account overload rotation for ${ue.retryDelayMs}ms`),await Gp(ue.retryDelayMs));continue e}break e}if(ee.coolingUntil&&Date.now()>=ee.coolingUntil){const ue=ee.coolingUntil;ee.coolingUntil=void 0,ee.coolingReason=void 0,xy(Q.key,ue).catch(()=>{})}const Fe=await alr({ctx:t,body:r,account:Q,accountState:ee,response:Ie,tracer:o,requestStartTime:s,fetchStartMs:me.fetchStartMs,attemptNumber:O.attemptNumber,finalBodyStr:me.finalBodyStr,upstreamSpan:te,logAttempt:Se,logProxyBody:h,logFinalRequest:g,onStreamTerminal:J.release,poolAccounts:x});if("retryNextAccount"in Fe){Fe.failure&&(O.lastError=Fe.failure.message,O.sawRateLimit||=Fe.failure.rateLimit,O.sawTransientFailure||=!Fe.failure.rateLimit,ve&&Fe.failure.retryDelayMs&&(f.always(`[proxy] pacing cross-account SSE overload rotation for ${Fe.failure.retryDelayMs}ms`),await Gp(Fe.failure.retryDelayMs)));continue e}return ie=Fe.holdsAccountAdmission===!0,Fe.response}finally{ie||J.release()}}}if(K?.lease.release(),O.attemptNumber===0&&F?.end(),Fcn(O)){let G;const Q=await rlr({body:r,logFinalRequest:g});if(Q)return Q;const ve=await nlr({ctx:t,body:r,parsedFallbackRequest:v,fallbackPlan:_,modelRouter:n,tracer:o,requestStartTime:s,logProxyBody:h,logFinalRequest:g});if(ve.response)return ve.response;if(ve.invalidRequestFailure&&!O.sawRateLimit&&(O.invalidRequestFailure=ve.invalidRequestFailure),G=ve.lastErrorMessage,O.invalidRequestFailure===null&&!O.sawRateLimit&&n?.isAutoFallbackEnabled?.()){const ee=await Ecn({ctx:t,body:r,tracer:o,requestStartTime:s,logProxyBody:h,logFinalRequest:g});if(ee.response)return ee.response;G=ee.lastErrorMessage??G}O.fallbackFailureMessage=G}{const G=I[0],Q=G?Jl.get(G.key):void 0;VA(t,{quota:Q?.quota??null,source:Q?.quota?"snapshot":"none",...G?{account:G}:{},...Q?{accountState:Q}:{},attempt:O.attemptNumber,poolAccounts:x})}return ilr({tracer:o,requestStartTime:s,authFailureMessage:O.authFailureMessage,authCooldownMessage:O.authCooldownMessage,invalidRequestFailure:O.invalidRequestFailure,entitlementFailure:O.entitlementFailure,scopedExhaustion:O.scopedExhaustion,sawNetworkError:O.sawNetworkError,sawTransientFailure:O.sawTransientFailure,sawRateLimit:O.sawRateLimit,lastError:O.lastError,lastTransportErrorCode:O.lastTransportErrorCode,lastTransportScope:O.lastTransportScope,fallbackFailureMessage:O.fallbackFailureMessage,orderedAccounts:I,buildLoggedClaudeError:m,logProxyBody:h,logFinalRequest:g})}function plr(e){return e!==void 0&&"runtimeConfigProvider"in e&&typeof e.runtimeConfigProvider=="function"}function mlr(e){const{ctx:t,body:r,status:n,message:o,errorType:s}=e;return Uw(n,ace,lce,{requestId:t.requestId,errorType:s,terminalOutcome:"handler_error",message:o}),Rh({timestamp:new Date().toISOString(),requestId:t.requestId,method:t.method,path:t.path,model:typeof r?.model=="string"?r.model:"",stream:r?.stream??!1,toolCount:Array.isArray(r?.tools)?r.tools.length:0,account:ace,accountType:lce,responseStatus:n,responseTimeMs:0,errorType:s,errorMessage:o}),ul(n,o)}var zcn=new Set(["oauth","api_key"]);function kce(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?Math.round(e*1e3):null}function jcn(e){if(!e||typeof e!="object")return null;const t={...e};return t.sessionResetAtMs=kce(t.sessionResetAt),t.weeklyResetAtMs=kce(t.weeklyResetAt),Array.isArray(t.windows)&&(t.windows=t.windows.map(r=>{const n={...r};return n.resetsAtMs=kce(n.resetsAt),n.severity=n.severity??(n.status==="rejected"?"critical":"normal"),n.isActive=n.isActive??!1,n})),t}function kF(e){return e==="allowed"?"ok":e==="rejected"||e==="throttled"?"degraded":"unknown"}function qcn(e,t="",r="fill-first",n=!1,o,s){const i=plr(s)?s.accountAllowlist:s,a=plr(s)?s.runtimeConfigProvider:void 0;return{prefix:`${t}/v1`,routes:[{method:"POST",path:`${t}/v1/messages`,handler:async l=>{const c=a?.()??{generation:0,strategy:r,modelRouter:e,passthrough:n,primaryAccountKey:o,accountAllowlist:i,quotaRoutingEnabled:_ce(),sessionSoftLimit:wce(),sessionResetToleranceMs:WA(),useOverage:"auto"};bce(c.useOverage);const u=c.modelRouter,d=l.body;if(typeof d?.model!="string"||!Array.isArray(d?.messages))return mlr({ctx:l,body:d,status:400,message:"Missing required fields: model, messages",errorType:"invalid_request_error"});const m=d.model.toLowerCase();if(!u&&!m.startsWith("claude-"))return mlr({ctx:l,body:d,status:404,message:`Model '${d.model}' is not an Anthropic model. The proxy only supports Claude models. Use a model router to route non-Claude models to other providers.`,errorType:"not_found_error"});const h=u?.resolve(d.model)??{provider:"anthropic",model:d.model},g=JSON.stringify(d),{tracer:y,requestStartTime:v,logProxyBody:_,logFinalRequest:b,buildLoggedClaudeError:T,setRoutingDecision:k}=Ocn({ctx:l,body:d,clientRequestBody:g});try{return h.provider===null?(y?.setError("not_found_error",`Model '${d.model}' is not a Claude model.`),y?.end(404,Date.now()-v),T(404,`Model '${d.model}' is not a Claude model. Use a model router to route it to another provider.`)):h.provider==="anthropic"?(y?.setMode("passthrough"),c.passthrough?ncn({ctx:l,body:d,clientRequestBody:g,tracer:y,requestStartTime:v,logProxyBody:_,logFinalRequest:b}):Bcn({ctx:l,body:d,modelRouter:u,tracer:y,requestStartTime:v,accountStrategy:c.strategy,primaryAccountKey:c.primaryAccountKey,accountAllowlist:c.accountAllowlist,quotaRoutingEnabled:c.quotaRoutingEnabled,sessionSoftLimit:c.sessionSoftLimit,sessionResetToleranceMs:c.sessionResetToleranceMs,buildLoggedClaudeError:T,logProxyBody:_,logFinalRequest:b,setRoutingDecision:k})):rcn({ctx:l,body:d,route:{provider:h.provider,model:h.model},modelRouter:u,tracer:y,requestStartTime:v,logProxyBody:_})}catch(x){const I=x instanceof Error?x.message:String(x);return f.error(`[claude-proxy] Generation error for ${d.model}: ${I}`),y?.setError("generation_error",I.slice(0,500)),y?.end(502,Date.now()-v),T(502,`Generation failed: ${x instanceof Error?x.message:"unknown error"}`)}},description:"Claude-compatible messages endpoint routed through NeuroLink",tags:["claude-proxy","messages"],streaming:{enabled:!0,contentType:"text/event-stream"}},{method:"POST",path:`${t}/peer/heartbeat`,handler:async l=>{const c=l.headers["x-neurolink-share-token"],u=l.headers["x-neurolink-grant-id"];if(!c||!u)return{ok:!1,stop:!0,reason:"no grant identified"};const d=await eae(u);if(!d||!d.leaseSecret||!hcn(d.leaseSecret,c))return{ok:!1,stop:!0,reason:"grant not recognized"};if(d.level!=="complete")return{ok:!1,stop:!0,reason:"grant is not a complete share"};if(d.state!=="active")return{ok:!1,stop:!0,reason:d.state};const m=l.body,h=Number(m?.coinsSpent??0);Number.isFinite(h)&&h>0&&await mcn(d,h);const g=await pcn(d,Number.isFinite(h)?h:0);return g.paused?(f.always(`[proxy] auto-paused share ${d.peerLabel}: ${g.detail}`),{ok:!1,stop:!0,reason:"usage drift"}):{ok:!0,lease:qir(d)}},description:"Complete-share heartbeat: report spend, renew the lease",tags:["claude-proxy","sharing"]},{method:"GET",path:`${t}/peer/handshake`,handler:async l=>{const c=await Ly(l.headers);return Ny(c)?c.body:{ok:!0,protocol:fcn,capabilities:gcn,grant:{peerLabel:c.grant.peerLabel,level:c.grant.level,state:c.grant.state,ledger:c.grant.entitlement.ledger}}},description:"Peer handshake: protocol version, capabilities, grant state",tags:["claude-proxy","sharing"]},{method:"POST",path:`${t}/peer/provision`,handler:async l=>{const c=await Ly(l.headers);if(Ny(c))return c.body;if(c.grant.state!=="active")return pb(c.grant.state==="paused"?"paused":"revoked",{status:403,grant:c.grant}).body;if(c.grant.level!=="complete")return{type:"error",error:{type:"invalid_request_error",message:"This is a live share. Ask the lender to run `neurolink proxy share level --to complete` first."}};const u=l.body,d=await Man({grantId:c.grant.id,codeChallenge:String(u?.codeChallenge??""),state:String(u?.state??"")});return d.ok!==!0?{type:"error",error:{type:"invalid_request_error",message:d.reason}}:(f.always(`[proxy] ${c.grant.peerLabel} asked to be provisioned \u2014 run \`neurolink proxy share provision --peer ${c.grant.peerLabel}\``),{ok:!0,status:"pending",expiresAt:d.request.expiresAt})},description:"Lodge a PKCE challenge for a resident credential (complete shares)",tags:["claude-proxy","sharing"]},{method:"GET",path:`${t}/peer/provision`,handler:async l=>{const c=await Ly(l.headers);if(Ny(c))return c.body;const u=await Pan(c.grant.id);if(u.status!=="ready")return{ok:!0,status:u.status};const d=await MQr();return{ok:!0,status:"ready",claim:$in({grant:c.grant,lenderName:"lender",...d?{lenderUrl:d}:{},code:u.code,state:u.state})}},description:"Collect the authorization code the lender produced",tags:["claude-proxy","sharing"]},{method:"GET",path:`${t}/peer/receipts`,handler:async l=>{const c=await Ly(l.headers);if(Ny(c))return c.body;const u=Number(l.query?.since??0);return{ok:!0,receipts:await _er(c.grant.id,Number.isFinite(u)?u:0)}},description:"Collect signed receipts for this grant's settled charges",tags:["claude-proxy","sharing"]},{method:"POST",path:`${t}/peer/net`,handler:async l=>{const c=await Ly(l.headers);if(Ny(c))return c.body;const u=c.grant.receiptSecret;if(!u)return{type:"error",error:{type:"invalid_request_error",message:"This grant predates receipts and cannot be netted. Ask the lender to re-issue it."}};const d=l.body,m=Number(d?.consumedByYou??NaN),h=Number(d?.alreadyNetted??NaN);return!Number.isFinite(m)||!Number.isFinite(h)?{type:"error",error:{type:"invalid_request_error",message:"A netting claim needs both cumulative totals."}}:_$({consumedByYou:m,alreadyNetted:h,grantId:c.grant.id},String(d?.signature??""),u)?{ok:!0,...await wer({grantId:c.grant.id,consumedFromPeer:m,peerAlreadyNetted:h})}:pb("unknown_token",{status:401}).body},description:"Settle one round of reciprocal netting against this grant",tags:["claude-proxy","sharing"]},{method:"POST",path:`${t}/peer/note`,handler:async l=>{const c=l.body,u=$an(String(c?.note??""));if(!u)return{type:"error",error:{type:"invalid_request_error",message:"That is not a NeuroLink coin note."}};const d=await FQr();if(!c?.redeem)return{ok:!0,...await Fan(u,d)};const m=await Ly(l.headers);if(Ny(m))return m.body;if(m.grant.entitlement.ledger!=="coins")return{type:"error",error:{type:"invalid_request_error",message:"This grant is unlimited \u2014 there is no balance to redeem into."}};const h=await Uan({note:u,grantId:m.grant.id,secret:d});return h.ok!==!0?{ok:!1,status:h.status,error:{type:"invalid_request_error",message:`That note is ${h.status}.`}}:{ok:!0,status:"redeemed",coins:h.coins,balance:h.balance??null}},description:"Check or redeem a transferable coin note",tags:["claude-proxy","sharing"]},{method:"GET",path:`${t}/peer/limits`,handler:async l=>{const c=await Ly(l.headers);if(Ny(c))return c.body;const u=a?.();return{ok:!0,...await ycn(c.grant,u?.accountAllowlist??i)}},description:"Peer limits: remaining coins, slice left, whether the grant can be served",tags:["claude-proxy","sharing"]},{method:"GET",path:`${t}/v1/models`,handler:async l=>{const c=a?a().modelRouter:e;return gt({name:"neurolink.http.claudeProxy.listModels",tracer:He.http,attributes:{"http.route":`${t}/v1/models`}},async()=>sin(c))},description:"List available models (Anthropic schema)",tags:["claude-proxy","models"]},{method:"POST",path:`${t}/v1/messages/count_tokens`,handler:async l=>gt({name:"neurolink.http.claudeProxy.countTokens",tracer:He.http,attributes:{"http.route":`${t}/v1/messages/count_tokens`}},async c=>{const u=l.body;if(typeof u?.model!="string"||!Array.isArray(u?.messages))return ul(400,"Missing required fields: model, messages");const d=u.messages.map(h=>typeof h.content=="string"?h.content:JSON.stringify(h.content)).join(" "),m=Math.ceil(d.length/4);return c.setAttribute("ai.model",u.model),c.setAttribute("gen_ai.usage.input_tokens",m),{input_tokens:m}}),description:"Count tokens for a messages request",tags:["claude-proxy","tokens"]},{method:"GET",path:`${t}/limits`,handler:async l=>{if(ib())return pb("no_capacity",{status:403,message:"This proxy does not expose pool limits to peers. Use GET /peer/limits for what your grant may still do."}).body;const c=a?.(),u=c?.accountAllowlist??i;bce(c?.useOverage);const d=l.query?.snapshot==="true"||l.query?.snapshot==="1",m=l.query?.account;return gt({name:"neurolink.http.claudeProxy.limits",tracer:He.http,attributes:{"http.route":`${t}/limits`}},async()=>!d&&!m?(vF||(vF=vce({accountAllowlist:u}).finally(()=>{vF=null})),vF):vce({accountAllowlist:u,accountFilter:m,snapshotOnly:d}))},description:"Fetch fresh per-account limits from Anthropic (usage API). ?account=<label> for one account, ?snapshot=true for stored state",tags:["claude-proxy","limits"]},{method:"GET",path:`${t}/accounts`,handler:async l=>{const c=a?.(),u=c?.accountAllowlist??i,d=c?.primaryAccountKey??o,m=N=>!!d&&!!N&&zQt(N,d),h=l.query?.refresh==="true";h&&bce(c?.useOverage);let g={fetchedAt:Date.now(),snapshot:!h,results:[]},y=null;try{g=await vce({accountAllowlist:u,snapshotOnly:!h})}catch(N){y=N instanceof Error?N.message:String(N)}const{getUsageSnapshot:v}=await Promise.resolve().then(()=>(v$(),KQt)),_=v().stats.accounts,b=Date.now();let T={};try{T=await AA()}catch{}const k=N=>{if(!N)return!1;const D=T[N]?.coolingUntil;return typeof D=="number"&&D>b};let x=new Map,I=null,M="";try{const{readAccountUsage:N,currentUsageDate:D}=await Promise.resolve().then(()=>(len(),Ner));M=D(),x=await N(M)}catch(N){I=N instanceof Error?N.message:String(N)}const R=new Map;for(const N of Object.values(_))R.set(N.label,N);const A=[],P=new Set;for(const N of g.results){const D=N.account;P.add(D);const O=R.get(D),F=jcn(N.quota),$=k(N.key??null);A.push({label:D,key:N.key??null,kind:"account",type:N.type??O?.type??"oauth",status:$?"cooling":kF(F?.weeklyStatus)==="degraded"||kF(F?.sessionStatus)==="degraded"?"exhausted":"active",cooling:$,allowed:null,expired:null,isPrimary:m(N.key??D),requests:O?O.successCount+O.errorCount:null,errors:O?.errorCount??null,rateLimits:O?.rateLimitCount??null,quotaRateLimits:O?.quotaRateLimitCount??null,quota:F?{...F,sessionHealth:kF(F.sessionStatus),weeklyHealth:kF(F.weeklyStatus)}:null,usage:x.get(D)??null})}for(const N of Object.values(_)){if(P.has(N.label))continue;const D=zcn.has(N.type);A.push({label:N.label,key:null,kind:D?"account":N.type==="translation"?"translation":"internal",type:N.type,status:D?"unrouted":null,cooling:!1,allowed:null,expired:null,isPrimary:m(N.label),requests:N.successCount+N.errorCount,errors:N.errorCount,rateLimits:N.rateLimitCount,quotaRateLimits:N.quotaRateLimitCount,quota:null,usage:x.get(N.label)??null})}return{generatedAt:Date.now(),usageDate:M,quotaFromSnapshot:!h,usageError:I,quotaError:y,costBasis:"api-equivalent",accounts:A}},description:"One row per account: status, quota, and today's tokens and API-equivalent cost. ?refresh=true forces a live quota fetch",tags:["claude-proxy","accounts"]}]}}function dl(e){const t=Jl.get(e);if(t)return t;const r={consecutiveRefreshFailures:0,permanentlyDisabled:!1};return Jl.set(e,r),r}function Gcn(e){const t=dl(e.key),r=t.lastToken!==e.token||t.lastRefreshToken!==e.refreshToken,n=t.permanentlyDisabled;n&&f.always(`[proxy] account=${e.label} is enabled in the token store; clearing stale runtime auth-disable state`),t.permanentlyDisabled=!1,(r||n)&&(t.consecutiveRefreshFailures=0),t.lastToken=e.token,t.lastRefreshToken=e.refreshToken}async function qp(e,t,r){try{const{tokenStore:n}=await Promise.resolve().then(()=>(rA(),jie)),o=e.persistTarget&&typeof e.persistTarget!="string"&&"providerKey"in e.persistTarget?e.persistTarget.providerKey:void 0;if(o){if(!await n.markDisabledIfCurrent(o,{accessToken:e.token,refreshToken:e.refreshToken,expiresAt:e.expiresAt??0},r))return t.permanentlyDisabled=!1,f.always(`[proxy] account=${e.label} credentials changed while authentication was in flight; ignored stale disable`),!1}else await n.markDisabled(e.key,r)}catch(n){f.debug(`[proxy] failed to persist disabled state for ${e.label}: ${n instanceof Error?n.message:String(n)}`)}return t.permanentlyDisabled=!0,f.always(r==="entitlement_blocked"?`[proxy] account=${e.label} disabled: the organization blocks Claude Code OAuth. Ask an admin to re-enable it, then run: neurolink auth enable ${e.key}`:`[proxy] account=${e.label} disabled until re-authentication. Run: neurolink auth login anthropic --method oauth`),!0}async function xF(e,t){t.consecutiveRefreshFailures+=1;const r=Math.min(t.consecutiveRefreshFailures-1,4),n=Math.min(_ln,vln*2**r),o=Date.now()+n;(!t.coolingUntil||o>t.coolingUntil)&&(t.coolingUntil=o,t.coolingReason="auth");const s=t.coolingUntil??o,i=t.coolingReason??"auth";return t.coolingUntil=s,t.coolingReason=i,await Td(e.key,s,i).catch(()=>{}),s}async function AF(e,t){if(t.consecutiveRefreshFailures=0,t.coolingReason!=="auth"||!t.coolingUntil)return;const r=t.coolingUntil;t.coolingUntil=void 0,t.coolingReason=void 0,await xy(e.key,r).catch(()=>{})}function IF(e){return`Account(s) require re-authentication: ${Array.isArray(e)?e.join(", "):e}. Run: neurolink auth login anthropic --method oauth`}function Or(e,t=180){const r=e.replace(/\s+/g," ").trim();return r.length<=t?r:`${r.slice(0,t)}...`}function hlr(e){const t=Math.min(Math.max(e-1,0),cce.length-1);return cce[t]??0}function flr(e){const t=Math.min(Math.max(e-1,0),Car.length-1);return glr(Car[t]??250)}async function Gp(e){await new Promise(t=>setTimeout(t,e))}function glr(e){return e+Math.floor(Math.random()*e*.25)}function KA(e){if(!e||typeof e!="object")return;const t=e.code;if(typeof t=="string")return t;const r=e.cause;if(!r||typeof r!="object")return;const n=r.code;return typeof n=="string"?n:void 0}function Sd(e){const t=e instanceof Error?e.message:String(e);if(!e||typeof e!="object")return t;const r=e.cause,n=r instanceof Error?r.message:r&&typeof r=="object"?String(r.message??""):"",s=[KA(e),n&&n!==t&&n].filter(Boolean).join(": ");return s?`${t} (${s})`:t}function xce(e){const t=KA(e);return t!==void 0&&["ECONNREFUSED","EADDRNOTAVAIL","ENOTFOUND","EAI_AGAIN","EHOSTUNREACH","UND_ERR_CONNECT_TIMEOUT","UND_ERR_CONNECT"].includes(t)}function Hcn(e){const t=KA(e);return t==="ENOTFOUND"||t==="EAI_AGAIN"?"shared_provider_transport":"connection_transport"}var Vcn=new Set([408,500,502,503,504,520,521,522,523,524,525,526,529]);function Cd(e){try{const t=JSON.parse(e);if(t&&t.type==="error"&&t.error&&typeof t.error=="object"){const r=t.error.details?.error_code;return{errorType:typeof t.error.type=="string"?t.error.type:void 0,message:typeof t.error.message=="string"?t.error.message:void 0,...typeof r=="string"?{errorCode:r}:{}}}}catch{}return{}}function Wcn(e,t){return e===422?!0:Cd(t).errorType==="invalid_request_error"||t.includes("invalid_request_error")}function Kcn(e,t){if(e!==404)return!1;const r=Cd(t);return r.errorType==="not_found_error"&&(r.message??"").toLowerCase().includes("model")}function Jcn(e,t){if(e!==400)return!1;const r=Cd(t);if(r.errorType!=="invalid_request_error")return!1;const n=(r.message??"").toLowerCase();return n.includes("beta")&&n.includes("subscription")&&n.includes("available")}var ylr=new Set(["oauth_not_allowed_for_organization","oauth_not_allowed","organization_disabled"]);function Ace(e,t){if(e!==401&&e!==402&&e!==403)return!1;const r=Cd(t);return r.errorType==="permission_error"?!0:r.errorCode!==void 0&&ylr.has(r.errorCode)}function vlr(e,t){if(!Ace(e,t))return!1;const r=Cd(t);return r.errorCode!==void 0&&ylr.has(r.errorCode)}function Ycn(e){return{...e,messages:e.messages.map(t=>typeof t.content!="string"?t:{...t,content:[{type:"text",text:t.content}]})}}var _lr=Ile;function wlr(e,t){if(Vcn.has(e))return!0;if(e!==400)return!1;const r=Cd(t);if(r.errorType==="overloaded_error")return!0;if(r.errorType!=="api_error")return!1;const n=(r.message??t).toLowerCase();return n.includes("<!doctype html")||n.includes("error code 520")||n.includes("web server is returning an unknown error")||n.includes("cloudflare")||n.includes("internal server error")}function Zcn(e,t){return e===529||Cd(t).errorType==="overloaded_error"}var Xcn=500;function JA(e){return Xn(e,Xcn)}wr(),q();var Qcn=55669,eun="generateContent",blr="streamGenerateContent";function tun(e){const r=e.split("?")[0].replace(/\/+$/,"").split("/").pop()??"",n=r.lastIndexOf(":");return n===-1?{modelId:r,action:void 0}:{modelId:r.slice(0,n),action:r.slice(n+1)}}function run(e){return{model:e.model,maxTokens:e.maxTokens??4096,temperature:e.temperature,topP:e.topP,systemPrompt:e.systemPrompt,stream:e.stream,prompt:e.prompt,images:e.images,conversationMessages:e.conversationMessages,tools:e.tools,stopSequences:e.stopSequences}}function nun(e,t="",r=Qcn,n){return{prefix:`${t}/v1beta`,routes:[{method:"POST",path:`${t}/v1beta/models/:model`,description:"Gemini-compatible generateContent / streamGenerateContent (translation mode)",handler:async o=>{const s=n?n().modelRouter:e,i=Date.now(),{modelId:a,action:l}=tun(o.path);if(!a||l!==eun&&l!==blr)return Sle(404,`Unsupported Gemini endpoint: ${o.path}`,"NOT_FOUND");const c=o.body;if(!c||!Array.isArray(c.contents)||c.contents.length===0)return Sle(400,"Request must include a non-empty 'contents' array");const u=l===blr,d=s?s.resolve(a):{provider:null,model:a},m=d.provider??void 0,h=d.model??a;f.debug(`[proxy:gemini] ${a} \u2192 ${m??"auto"}/${h}`);const g=gsn(h,c,u),y=run(g),_=gb({provider:m??"auto",model:h},s?.getFallbackChain()??[],a,y,s?.isAutoFallbackEnabled?.()??!1).attempts;let b;try{b=$le.startRequest({requestId:o.requestId,method:o.method,path:o.path,model:a,stream:u,toolCount:Object.keys(g.tools).length,clientApp:"gemini-compat",userAgent:o.headers["user-agent"]??"",provider:m??"google-ai"},o.headers),b.setMode("full")}catch{}try{return u?await Mle({ctx:o,format:"gemini",requestModel:a,parsed:g,attempts:_,tracer:b,requestStartTime:i}):await Ple({ctx:o,format:"gemini",requestModel:a,parsed:g,attempts:_,tracer:b,requestStartTime:i})}catch(T){const k=T instanceof Error?T.message:String(T),x=Xn(k);return f.always(`[proxy:gemini] request failed: ${x}`),b?.setError("generation_error",x),b?.end(500,Date.now()-i),Sle(500,"Internal proxy error","INTERNAL")}}}]}}Wr(),vr();function Ice(e,t,r){return n=>gt({name:e,tracer:He.http,attributes:{"http.route":t,"http.request.id":n.requestId??""}},()=>r(n))}function Tlr(e="/api"){return{prefix:`${e}/health`,routes:[{method:"GET",path:`${e}/health`,handler:Ice("neurolink.http.health.check",`${e}/health`,async()=>({status:"ok",timestamp:new Date().toISOString(),uptime:process.uptime()*1e3,version:process.env.npm_package_version||"unknown"})),description:"Basic health check",tags:["health"]},{method:"GET",path:`${e}/health/live`,handler:Ice("neurolink.http.health.live",`${e}/health/live`,async()=>({status:"alive",timestamp:new Date().toISOString()})),description:"Kubernetes liveness probe",tags:["health"]},{method:"GET",path:`${e}/health/ready`,handler:t=>gt({name:"neurolink.http.health.ready",tracer:He.http,attributes:{"http.route":`${e}/health/ready`,"http.request.id":t.requestId??""}},async r=>{const n=await t.toolRegistry.listTools(),o=n.length>0,s=!!t.externalServerManager;let i=!0;if(t.externalServerManager){const l=t.externalServerManager.getServerStatuses();for(const c of l)if(c.status!=="connected"){i=!1;break}}const a=o||!s||i;return r.setAttribute("health.ready",a),r.setAttribute("health.tools_count",n.length),r.setAttribute("health.external_servers_ready",i),{ready:a,timestamp:new Date().toISOString(),services:{neurolink:!0,tools:o,externalServers:i}}}),description:"Kubernetes readiness probe",tags:["health"]},{method:"GET",path:`${e}/health/startup`,handler:t=>gt({name:"neurolink.http.health.startup",tracer:He.http,attributes:{"http.route":`${e}/health/startup`,"http.request.id":t.requestId??""}},async r=>{const n=await t.toolRegistry.listTools();return r.setAttribute("health.tools_count",n.length),{started:!0,timestamp:new Date().toISOString(),services:{neurolink:!0,toolsLoaded:n.length,externalServerManager:!!t.externalServerManager}}}),description:"Kubernetes startup probe",tags:["health"]},{method:"GET",path:`${e}/health/detailed`,handler:t=>gt({name:"neurolink.http.health.detailed",tracer:He.http,attributes:{"http.route":`${e}/health/detailed`,"http.request.id":t.requestId??""}},async r=>{const n=await t.toolRegistry.listTools(),o={};for(const c of n){const u=typeof c.source=="string"?c.source:c.serverId||"built-in";o[u]=(o[u]||0)+1}const s=[];if(t.externalServerManager){const c=t.externalServerManager.getServerStatuses();for(const u of c)s.push({name:u.serverId,status:u.status,toolCount:u.toolCount})}const i=t.neurolink.conversationMemory,a={available:!!i,type:i?.constructor.name||"none"},l={status:"ok",timestamp:new Date().toISOString(),uptime:process.uptime()*1e3,version:process.env.npm_package_version||"unknown",node:{version:process.version,platform:process.platform,arch:process.arch},memory:{...a,process:{heapUsed:Math.round(process.memoryUsage().heapUsed/1024/1024),heapTotal:Math.round(process.memoryUsage().heapTotal/1024/1024),rss:Math.round(process.memoryUsage().rss/1024/1024),external:Math.round(process.memoryUsage().external/1024/1024)}},tools:{total:n.length,bySource:o},externalServers:{count:s.length,servers:s}};if(t.metadata?.accountPool){const c=t.metadata.accountPool,u=c.getAllAccounts(),d={};for(const m of u)d[m.status]=(d[m.status]||0)+1;l.proxy={totalAccounts:u.length,statusDistribution:d,healthyCount:c.getHealthyCount(),strategy:c.getStrategy()},r.setAttribute("health.proxy.accounts",u.length),r.setAttribute("health.proxy.healthy",c.getHealthyCount())}return r.setAttribute("health.tools_count",n.length),r.setAttribute("health.external_servers_count",s.length),r.setAttribute("health.memory.heap_mb",Math.round(process.memoryUsage().heapUsed/1024/1024)),l}),description:"Detailed health information",tags:["health"]},{method:"GET",path:`${e}/version`,handler:Ice("neurolink.http.version",`${e}/version`,async()=>({name:"@juspay/neurolink",version:process.env.npm_package_version||"unknown",node:process.version,timestamp:new Date().toISOString()})),description:"Get version information",tags:["health","version"]}]}}pn(),wr(),q();var Elr=300*1e3,oun=55669;function sun(e){return e?{status:502,errorType:"loopback_stream_error",errorMessage:e}:{status:499,errorType:"client_cancelled",errorMessage:"Client cancelled the OpenAI-compatible stream"}}function YA(e,t){return new Response(JSON.stringify(Tsn(e,t)),{status:e,headers:{"content-type":"application/json"}})}function iun(e){return{model:e.model,maxTokens:e.maxTokens??4096,temperature:e.temperature,topP:e.topP,systemPrompt:typeof e.systemPrompt=="string"?e.systemPrompt:void 0,stream:e.stream,prompt:e.prompt,images:e.images,conversationMessages:e.conversationMessages,tools:e.tools,toolChoice:e.toolChoice,toolChoiceName:e.toolChoiceName,stopSequences:e.stopSequences}}async function aun(e){const{ctx:t,body:r,targetModel:n,requestStartTime:o,loopbackPort:s}=e,i=r.stream===!0,a=r.tools?.length??0,l=(g,y={})=>Rh({timestamp:new Date().toISOString(),requestId:t.requestId,method:t.method,path:t.path,model:r.model,stream:i,toolCount:a,account:"",accountType:"openai-bridge",...cb(t.headers),responseStatus:g,responseTimeMs:Date.now()-o,...y}),c=Esn(r);c.model=n;const u=`http://127.0.0.1:${s}/v1/messages`,d={"content-type":"application/json",accept:i?"text/event-stream":"application/json"};for(const[g,y]of Object.entries(t.headers)){if(typeof y!="string")continue;const v=g.toLowerCase();(v.startsWith("anthropic-")||v==="x-api-key")&&(d[v]=y)}const m=await Bt(fetch(u,{method:"POST",headers:d,body:JSON.stringify({...c,stream:i})}),Elr,`Anthropic loopback timed out after ${Elr}ms`);if(!m.ok){const g=await m.text().catch(()=>""),y=Xn(g);return f.always(`[proxy:openai] anthropic loopback error ${m.status}: ${y}`),await l(m.status,{errorType:"loopback_upstream_error",errorMessage:y}),YA(m.status,y||`Anthropic loopback failed with status ${m.status}`)}if(i){if(!m.body)return await l(502,{errorType:"loopback_empty_stream",errorMessage:"Anthropic loopback returned empty stream body"}),YA(502,"Anthropic loopback returned empty stream body");let g;const v=m.body.pipeThrough(Csn(r.model,{onError:k=>{g=Xn(k)}})).getReader();let _=!1;const b=async(k,x,I)=>{_||(_=!0,await l(k,{errorType:x,errorMessage:I}))},T=new ReadableStream({async pull(k){try{const{value:x,done:I}=await v.read();if(I){g?await b(502,"loopback_stream_error",g):await b(200),k.close();return}k.enqueue(x)}catch(x){const I=Xn(x instanceof Error?x.message:String(x));await b(502,"loopback_stream_error",I),k.error(x)}},async cancel(k){try{await v.cancel(k)}finally{const x=sun(g);await b(x.status,x.errorType,x.errorMessage)}}});return new Response(T,{status:200,headers:{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}})}const h=await m.json();return await l(200,{inputTokens:h.usage?.input_tokens,outputTokens:h.usage?.output_tokens,cacheCreationTokens:h.usage?.cache_creation_input_tokens,cacheReadTokens:h.usage?.cache_read_input_tokens}),Ssn(h,r.model)}function lun(e,t="",r=oun,n){return{prefix:`${t}/v1`,routes:[{method:"POST",path:`${t}/v1/chat/completions`,description:"OpenAI-compatible chat completions (translation mode)",handler:async o=>{const s=n?n().modelRouter:e,i=Date.now(),a=o.body;if(!a||!a.model||!a.messages?.length)return YA(400,"Request must include 'model' and 'messages' fields");const l=s?s.resolve(a.model):{provider:null,model:a.model},c=l.provider??void 0,u=l.model??a.model;if(f.debug(`[proxy:openai] ${a.model} \u2192 ${c??"auto"}/${u}`),l.provider==="anthropic")try{return await aun({ctx:o,body:a,targetModel:u,requestStartTime:i,loopbackPort:r})}catch(v){const _=v instanceof Error?v.message:String(v),b=Xn(_);return f.always(`[proxy:openai] anthropic loopback failed: ${b}`),await Rh({timestamp:new Date().toISOString(),requestId:o.requestId,method:o.method,path:o.path,model:a.model,stream:a.stream===!0,toolCount:a.tools?.length??0,account:"",accountType:"openai-bridge",responseStatus:502,responseTimeMs:Date.now()-i,errorType:"loopback_exception",errorMessage:b}),YA(502,"Anthropic loopback failed")}const d=wsn(a),m=iun(d),g=gb({provider:c??"auto",model:u},s?.getFallbackChain()??[],a.model,m,s?.isAutoFallbackEnabled?.()??!1).attempts;let y;try{y=$le.startRequest({requestId:o.requestId,method:o.method,path:o.path,model:a.model,stream:a.stream===!0,toolCount:Object.keys(d.tools).length,clientApp:"openai-compat",userAgent:o.headers["user-agent"]??"",provider:c??"openai-compatible"},o.headers),y.setMode("full")}catch{}try{return a.stream?Mle({ctx:o,format:"openai",requestModel:a.model,parsed:d,attempts:g,tracer:y,requestStartTime:i}):await Ple({ctx:o,format:"openai",requestModel:a.model,parsed:d,attempts:g,tracer:y,requestStartTime:i})}catch(v){const _=v instanceof Error?v.message:String(v),b=Xn(_);return f.always(`[proxy:openai] request failed: ${b}`),y?.setError("generation_error",b),y?.end(500,Date.now()-i),YA(500,"Internal proxy error")}}},{method:"GET",path:`${t}/v1/models`,description:"List available models in OpenAI format",handler:async()=>{const o=n?n().modelRouter:e;return oin(o)}}]}}er(),Gr(),Wr(),vr(),Pp();function $y(e,t,r){return n=>gt({name:e,tracer:He.http,attributes:{"http.route":t,"http.request.id":n.requestId}},async o=>{const s=await r(n);if(s&&typeof s=="object"){const i=s.error;if(i!=null){const a=typeof i=="string"?i:typeof i?.message=="string"?i.message:"MCP handler error";o.setStatus({code:qe.ERROR,message:a})}}return s})}var cun=p.object({name:p.string().min(1,"Server name is required"),toolName:p.string().min(1,"Tool name is required")});async function uun(e){const t=e.externalServerManager;if(!t)return{servers:[],total:0,message:"External server manager not available",metadata:{timestamp:new Date().toISOString(),requestId:e.requestId}};const r=t.listServers(),n=t.getServerStatuses(),o=new Map(n.map(i=>[i.serverId,i])),s=r.map(i=>{const a=o.get(i.name);return{serverId:i.name,name:i.name,status:a?.status||"disconnected",toolCount:a?.toolCount||0,lastHealthCheck:a?.checkedAt?.toISOString(),error:a?.issues?.[0]}});return{servers:s,total:s.length,metadata:{timestamp:new Date().toISOString(),requestId:e.requestId}}}async function dun(e){const t=Cu(Lw,e.params,e.requestId);if(!t.success)return t.error;const{name:r}=t.data,n=e.externalServerManager;if(!n)return Kt("MCP_UNAVAILABLE","External server manager not available",void 0,e.requestId);if(!n.listServers().find(u=>u.name===r))return Kt("SERVER_NOT_FOUND",`MCP server '${r}' not found`,void 0,e.requestId);const a=n.getServerStatuses().find(u=>u.serverId===r),c=(await e.toolRegistry.listTools()).filter(u=>u.source===r);return{serverId:r,name:r,status:a?.status||"disconnected",toolCount:a?.toolCount||0,tools:c.map(u=>({name:u.name,description:u.description})),lastHealthCheck:a?.checkedAt?.toISOString(),error:a?.issues?.[0],metadata:{timestamp:new Date().toISOString(),requestId:e.requestId}}}async function pun(e){const t=Cu(Lw,e.params,e.requestId);if(!t.success)return t.error;const{name:r}=t.data,n=e.externalServerManager;if(!n)return Kt("MCP_UNAVAILABLE","External server manager not available",void 0,e.requestId);try{if(!n.listServers().find(l=>l.name===r))return Kt("SERVER_NOT_FOUND",`Server '${r}' not found`,void 0,e.requestId);const a=n.getServerStatuses().find(l=>l.serverId===r);return{success:!0,server:{serverId:r,name:r,status:a?.status||"disconnected",toolCount:a?.toolCount||0},message:"Server status retrieved (full reconnect requires server restart)",metadata:{timestamp:new Date().toISOString(),requestId:e.requestId}}}catch(o){return Kt("RECONNECT_FAILED",o instanceof Error?o.message:String(o),void 0,e.requestId)}}async function mun(e){const t=Cu(Lw,e.params,e.requestId);if(!t.success)return t.error;const{name:r}=t.data,n=e.externalServerManager;if(!n)return Kt("MCP_UNAVAILABLE","External server manager not available",void 0,e.requestId);try{const o=await n.removeServer(r);return o.success?{success:!0,message:`Server '${r}' removed`,metadata:{timestamp:new Date().toISOString(),requestId:e.requestId}}:Kt("REMOVE_FAILED",o.error||"Failed to remove server",void 0,e.requestId)}catch(o){return Kt("REMOVE_FAILED",o instanceof Error?o.message:String(o),void 0,e.requestId)}}async function hun(e){const t=Cu(Lw,e.params,e.requestId);if(!t.success)return t.error;const{name:r}=t.data,o=(await e.toolRegistry.listTools()).filter(s=>s.source===r);if(o.length===0){const s=e.externalServerManager;if(s&&!s.listServers().find(l=>l.name===r))return Kt("SERVER_NOT_FOUND",`MCP server '${r}' not found`,void 0,e.requestId)}return{serverId:r,tools:o.map(s=>({name:s.name,description:s.description,inputSchema:s.inputSchema})),total:o.length,metadata:{timestamp:new Date().toISOString(),requestId:e.requestId}}}async function fun(e){const t=Cu(cun,e.params,e.requestId);if(!t.success)return t.error;const{name:r,toolName:n}=t.data,o=yd(u$,e.body||{},e.requestId);if(!o.success)return o.error;const s=o.data,i=Date.now();try{return(await e.toolRegistry.listTools()).find(u=>u.name===n&&u.source===r)?{success:!0,data:await e.toolRegistry.executeTool(n,s),duration:Date.now()-i,metadata:{server:r,toolName:n,timestamp:new Date().toISOString(),requestId:e.requestId}}:Kt("TOOL_NOT_FOUND",`Tool '${n}' not found on server '${r}'`,void 0,e.requestId)}catch(a){return Kt("EXECUTION_FAILED",a instanceof Error?a.message:String(a),{duration:Date.now()-i},e.requestId)}}async function gun(e){const t=e.externalServerManager;if(!t)return{healthy:!1,message:"External server manager not available",servers:[]};const n=t.getServerStatuses().map(i=>({name:i.serverId,healthy:i.isHealthy,error:i.issues?.[0]})),o=n.every(i=>i.healthy),s=n.some(i=>i.healthy);return{healthy:n.length===0||o,status:n.length===0?"no_servers":o?"all_healthy":s?"degraded":"unhealthy",servers:n,timestamp:new Date().toISOString()}}function Slr(e="/api"){return{prefix:`${e}/mcp`,routes:[{method:"GET",path:`${e}/mcp/servers`,handler:$y("neurolink.http.mcp.listServers",`${e}/mcp/servers`,uun),description:"List all MCP servers",tags:["mcp"]},{method:"GET",path:`${e}/mcp/servers/:name`,handler:$y("neurolink.http.mcp.getServer",`${e}/mcp/servers/:name`,dun),description:"Get MCP server status",tags:["mcp"]},{method:"POST",path:`${e}/mcp/servers/:name/reconnect`,handler:$y("neurolink.http.mcp.reconnectServer",`${e}/mcp/servers/:name/reconnect`,pun),description:"Reconnect to an MCP server",tags:["mcp"]},{method:"DELETE",path:`${e}/mcp/servers/:name`,handler:$y("neurolink.http.mcp.removeServer",`${e}/mcp/servers/:name`,mun),description:"Remove an MCP server",tags:["mcp"]},{method:"GET",path:`${e}/mcp/servers/:name/tools`,handler:$y("neurolink.http.mcp.listServerTools",`${e}/mcp/servers/:name/tools`,hun),description:"List tools from a specific MCP server",tags:["mcp","tools"]},{method:"POST",path:`${e}/mcp/servers/:name/tools/:toolName/execute`,handler:$y("neurolink.http.mcp.executeTool",`${e}/mcp/servers/:name/tools/:toolName/execute`,fun),description:"Execute a tool from a specific MCP server",tags:["mcp","tools"]},{method:"GET",path:`${e}/mcp/health`,handler:$y("neurolink.http.mcp.health",`${e}/mcp/health`,gun),description:"Health check for all MCP servers",tags:["mcp","health"]}]}}Wr(),vr(),Pp();function Fy(e,t,r){return n=>gt({name:e,tracer:He.http,attributes:{"http.route":t,"http.request.id":n.requestId}},()=>r(n))}async function yun(e){const t=Cu(Mie,e.params,e.requestId);if(!t.success)return t.error;const{id:r}=t.data,n=e.query.limit?parseInt(e.query.limit,10):50,o=e.query.offset?parseInt(e.query.offset,10):0,s=isNaN(n)||n<1?50:Math.min(n,100),i=isNaN(o)||o<0?0:o,a=e.neurolink.conversationMemory;if(!a)return Kt("MEMORY_UNAVAILABLE","Conversation memory not available",void 0,e.requestId);try{let l=[];if("getUserSessionHistory"in a){const d=e.query.userId||"default",m=await a.getUserSessionHistory(d,r);if(m===null)return Kt("SESSION_NOT_FOUND",`Session '${r}' not found`,void 0,e.requestId);l=m}else if("getSession"in a){const d=a.getSession(r);if(!d)return Kt("SESSION_NOT_FOUND",`Session '${r}' not found`,void 0,e.requestId);l=d.messages}else if("buildContextMessages"in a&&(l=await a.buildContextMessages(r),l.length===0))return Kt("SESSION_NOT_FOUND",`Session '${r}' not found or has no messages`,void 0,e.requestId);const c=l.length,u=l.slice(i,i+s);return{sessionId:r,messages:u,total:c,limit:s,offset:i,metadata:{timestamp:new Date().toISOString(),requestId:e.requestId}}}catch(l){return Kt("MEMORY_ERROR",l instanceof Error?l.message:"Failed to get session messages",void 0,e.requestId)}}async function vun(e){const t=Cu(Mie,e.params,e.requestId);if(!t.success)return t.error;const{id:r}=t.data,n=e.neurolink.conversationMemory;if(!n)return Kt("MEMORY_UNAVAILABLE","Conversation memory not available",void 0,e.requestId);try{if("getUserSessionObject"in n){const o=e.query.userId||"default",s=await n.getUserSessionObject(o,r);return s===null?Kt("SESSION_NOT_FOUND",`Session '${r}' not found`,void 0,e.requestId):{session:s,metadata:{timestamp:new Date().toISOString(),requestId:e.requestId}}}else if("getSession"in n){const o=n.getSession(r);return o?{session:o,metadata:{timestamp:new Date().toISOString(),requestId:e.requestId}}:Kt("SESSION_NOT_FOUND",`Session '${r}' not found`,void 0,e.requestId)}return Kt("MEMORY_ERROR","Session retrieval not supported for this memory type",void 0,e.requestId)}catch(o){return Kt("MEMORY_ERROR",o instanceof Error?o.message:"Failed to get session",void 0,e.requestId)}}async function _un(e){const t=e.query.userId,r=e.query.limit?parseInt(e.query.limit,10):50,n=e.query.offset?parseInt(e.query.offset,10):0,o=isNaN(r)||r<1?50:Math.min(r,100),s=isNaN(n)||n<0?0:n,i=e.neurolink.conversationMemory;if(!i)return Kt("MEMORY_UNAVAILABLE","Conversation memory not available",void 0,e.requestId);try{let a=[];if("getUserAllSessionsHistory"in i&&t)a=await i.getUserAllSessionsHistory(t);else if("getUserSessions"in i&&t){const u=await i.getUserSessions(t);if("getUserSessionMetadata"in i){const d=u.map(h=>i.getUserSessionMetadata(t,h));a=(await Promise.all(d)).filter(h=>h!==null)}else a=u.map(d=>({id:d}))}else if("getStats"in i){const u=await i.getStats?.();return{sessions:[],total:u?.totalSessions||0,limit:o,offset:s,message:"Session listing not fully supported for in-memory storage. Use /stats endpoint for session counts.",metadata:{timestamp:new Date().toISOString(),requestId:e.requestId}}}const l=a.length;return{sessions:a.slice(s,s+o),total:l,limit:o,offset:s,metadata:{timestamp:new Date().toISOString(),requestId:e.requestId}}}catch(a){return Kt("MEMORY_ERROR",a instanceof Error?a.message:"Failed to list sessions",void 0,e.requestId)}}async function wun(e){const t=e.neurolink.conversationMemory;if(!t)return Kt("MEMORY_UNAVAILABLE","Conversation memory not available",void 0,e.requestId);try{const r=await t.getStats?.();return{available:!0,type:t.constructor.name,stats:r||{message:"Statistics not available for this memory type"},timestamp:new Date().toISOString()}}catch(r){return Kt("MEMORY_ERROR",r instanceof Error?r.message:"Failed to get statistics",void 0,e.requestId)}}async function bun(e){const t=Cu(Rie,e.params,e.requestId);if(!t.success)return t.error;const{sessionId:r}=t.data,n=e.neurolink.conversationMemory;if(!n)return Kt("MEMORY_UNAVAILABLE","Conversation memory not available",void 0,e.requestId);try{return await n.clearSession?.(r)===!1?Kt("SESSION_NOT_FOUND",`Session '${r}' not found`,void 0,e.requestId):{success:!0,sessionId:r,message:"Session cleared successfully",metadata:{timestamp:new Date().toISOString(),requestId:e.requestId}}}catch(o){return Kt("MEMORY_ERROR",o instanceof Error?o.message:"Failed to clear session",void 0,e.requestId)}}async function Tun(e){const t=e.neurolink.conversationMemory;if(!t)return Kt("MEMORY_UNAVAILABLE","Conversation memory not available",void 0,e.requestId);try{return await t.clearAllSessions?.(),{success:!0,message:"All sessions cleared successfully",metadata:{timestamp:new Date().toISOString(),requestId:e.requestId}}}catch(r){return Kt("MEMORY_ERROR",r instanceof Error?r.message:"Failed to clear sessions",void 0,e.requestId)}}async function Eun(e){const t=e.neurolink.conversationMemory;return{available:!!t,type:t?.constructor.name||"none",timestamp:new Date().toISOString()}}function Clr(e="/api"){return{prefix:`${e}/memory`,routes:[{method:"GET",path:`${e}/memory/sessions/:id/messages`,handler:Fy("neurolink.http.memory.getSessionMessages",`${e}/memory/sessions/:id/messages`,yun),description:"Get messages for a session",tags:["memory"]},{method:"GET",path:`${e}/memory/sessions/:id`,handler:Fy("neurolink.http.memory.getSession",`${e}/memory/sessions/:id`,vun),description:"Get session by ID",tags:["memory"]},{method:"GET",path:`${e}/memory/sessions`,handler:Fy("neurolink.http.memory.listSessions",`${e}/memory/sessions`,_un),description:"List all conversation sessions",tags:["memory"]},{method:"GET",path:`${e}/memory/stats`,handler:Fy("neurolink.http.memory.stats",`${e}/memory/stats`,wun),description:"Get memory statistics",tags:["memory"]},{method:"DELETE",path:`${e}/memory/sessions/:sessionId`,handler:Fy("neurolink.http.memory.clearSession",`${e}/memory/sessions/:sessionId`,bun),description:"Clear a conversation session",tags:["memory"]},{method:"DELETE",path:`${e}/memory/sessions`,handler:Fy("neurolink.http.memory.clearAllSessions",`${e}/memory/sessions`,Tun),description:"Clear all conversation sessions",tags:["memory"]},{method:"GET",path:`${e}/memory/health`,handler:Fy("neurolink.http.memory.health",`${e}/memory/health`,Eun),description:"Check memory system health",tags:["memory","health"]}]}}q(),Wr(),vr();function Sun(e="/api",t){return t||f.debug("[OpenAPI] createOpenApiRoutes called without getRoutes callback. Custom routes will not be documented in the OpenAPI spec."),{prefix:`${e}/openapi`,routes:[{method:"GET",path:`${e}/openapi.json`,handler:async()=>gt({name:"neurolink.http.openapi.json",tracer:He.http,attributes:{"http.route":`${e}/openapi.json`,"openapi.format":"json"}},async r=>{const n=t?.()??[];return t?n.length===0&&f.debug("[OpenAPI] getRoutes returned empty array. No custom routes will be documented."):f.warn("[OpenAPI] No getRoutes callback provided. OpenAPI spec will use default endpoint definitions. Use registerAllRoutes(server, basePath, { enableSwagger: true }) to automatically include your routes."),r.setAttribute("openapi.route_count",n.length),new xA({basePath:e,routes:n}).generate()}),description:"Get OpenAPI specification as JSON",tags:["openapi","documentation"]},{method:"GET",path:`${e}/openapi.yaml`,handler:async()=>gt({name:"neurolink.http.openapi.yaml",tracer:He.http,attributes:{"http.route":`${e}/openapi.yaml`,"openapi.format":"yaml"}},async r=>{const n=t?.()??[];return t?n.length===0&&f.debug("[OpenAPI] getRoutes returned empty array. No custom routes will be documented."):f.warn("[OpenAPI] No getRoutes callback provided. OpenAPI spec will use default endpoint definitions. Use registerAllRoutes(server, basePath, { enableSwagger: true }) to automatically include your routes."),r.setAttribute("openapi.route_count",n.length),{_raw:!0,contentType:"text/yaml",body:new xA({basePath:e,routes:n}).toYAML()}}),description:"Get OpenAPI specification as YAML",tags:["openapi","documentation"]},{method:"GET",path:`${e}/docs`,handler:async()=>gt({name:"neurolink.http.openapi.docs",tracer:He.http,attributes:{"http.route":`${e}/docs`}},async()=>({_raw:!0,contentType:"text/html",body:`<!DOCTYPE html>
|
|
@@ -56,11 +56,10 @@ declare function resetEpochToMs(resetEpoch: number | undefined, now: number): nu
|
|
|
56
56
|
*/
|
|
57
57
|
declare function planCooldownFor429(quota: AccountQuota | null, retryAfterMs: number, now: number, unifiedStatus?: string | undefined, policy?: ProxyOveragePolicy): AccountCooldownPlan;
|
|
58
58
|
/**
|
|
59
|
-
*
|
|
60
|
-
*
|
|
61
|
-
*
|
|
62
|
-
*
|
|
63
|
-
* 429, except when the provider explicitly enables paid overage.
|
|
59
|
+
* Reconcile quota-backed cooldowns against a fresh provider observation. A
|
|
60
|
+
* rejected window parks the account until its reset; an allowed observation for
|
|
61
|
+
* that same window releases an earlier cooldown whose reset timestamp was
|
|
62
|
+
* stale. Transient and authentication cooldowns are intentionally untouched.
|
|
64
63
|
*/
|
|
65
64
|
declare function reconcileCooldownFromQuota(state: RuntimeAccountState, quota: AccountQuota, now: number, policy?: ProxyOveragePolicy): ProxyQuotaCooldownUpdate;
|
|
66
65
|
/**
|
|
@@ -604,11 +604,10 @@ function minutesUntil(untilMs, now) {
|
|
|
604
604
|
return Math.max(0, Math.round((untilMs - now) / 60000));
|
|
605
605
|
}
|
|
606
606
|
/**
|
|
607
|
-
*
|
|
608
|
-
*
|
|
609
|
-
*
|
|
610
|
-
*
|
|
611
|
-
* 429, except when the provider explicitly enables paid overage.
|
|
607
|
+
* Reconcile quota-backed cooldowns against a fresh provider observation. A
|
|
608
|
+
* rejected window parks the account until its reset; an allowed observation for
|
|
609
|
+
* that same window releases an earlier cooldown whose reset timestamp was
|
|
610
|
+
* stale. Transient and authentication cooldowns are intentionally untouched.
|
|
612
611
|
*/
|
|
613
612
|
function reconcileCooldownFromQuota(state, quota, now, policy = overagePolicy) {
|
|
614
613
|
const overageAvailable = isOverageUsable(quota, policy);
|
|
@@ -641,6 +640,20 @@ function reconcileCooldownFromQuota(state, quota, now, policy = overagePolicy) {
|
|
|
641
640
|
reason = "unified";
|
|
642
641
|
}
|
|
643
642
|
if (until === undefined) {
|
|
643
|
+
const recoveredQuotaCooldown = !!state.coolingUntil &&
|
|
644
|
+
((state.coolingReason === "weekly" && quota.weeklyStatus === "allowed") ||
|
|
645
|
+
(state.coolingReason === "session" &&
|
|
646
|
+
quota.sessionStatus === "allowed") ||
|
|
647
|
+
(state.coolingReason === "unified" &&
|
|
648
|
+
quota.unifiedStatus === "allowed"));
|
|
649
|
+
if (recoveredQuotaCooldown && state.coolingUntil) {
|
|
650
|
+
const previousCoolingUntil = state.coolingUntil;
|
|
651
|
+
const previousCoolingReason = state.coolingReason;
|
|
652
|
+
state.coolingUntil = undefined;
|
|
653
|
+
state.coolingReason = undefined;
|
|
654
|
+
logger.always(`[proxy] clearing ${previousCoolingReason} cooldown from fresh provider quota`);
|
|
655
|
+
return { kind: "cleared", coolingUntil: previousCoolingUntil };
|
|
656
|
+
}
|
|
644
657
|
return null;
|
|
645
658
|
}
|
|
646
659
|
const clamped = clampCooldownUntil(until, now, reason);
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@juspay/neurolink",
|
|
3
|
-
"version": "12.7.
|
|
3
|
+
"version": "12.7.9",
|
|
4
4
|
"packageManager": "pnpm@10.15.1",
|
|
5
5
|
"description": "TypeScript AI SDK with 24+ LLM providers behind one consistent API. MCP-native (connect any MCP server), voice TTS/STT/realtime, RAG, agents, memory, context compaction. OpenAI · Anthropic · Gemini · Bedrock · Azure · Ollama · DeepSeek · NVIDIA NIM and more.",
|
|
6
6
|
"author": {
|