@juspay/neurolink 12.3.0 → 12.4.1
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 +3 -3
- package/dist/browser/neurolink.min.js +5 -5
- package/dist/cli/proxy-clients/gemini.d.ts +51 -0
- package/dist/cli/proxy-clients/gemini.js +278 -0
- package/dist/cli/proxy-clients/openCode.d.ts +41 -0
- package/dist/cli/proxy-clients/openCode.js +212 -27
- package/dist/cli/proxy-clients/registry.js +2 -0
- package/dist/cli/proxy-clients/snapshot.d.ts +13 -0
- package/dist/cli/proxy-clients/snapshot.js +18 -0
- package/dist/constants/proxyModels.d.ts +22 -0
- package/dist/constants/proxyModels.js +36 -0
- package/dist/core/baseProvider.d.ts +1 -1
- package/dist/core/baseProvider.js +2 -2
- package/dist/evaluation/scorers/rule/formatScorer.js +1 -1
- package/dist/mcp/mcpRegistryClient.js +1 -1
- package/dist/middleware/utils/guardrailsUtils.js +1 -1
- package/dist/neurolink.js +2 -2
- package/dist/proxy/proxyTranslationEngine.js +3 -22
- package/dist/rag/ChunkerFactory.js +1 -1
- package/dist/server/websocket/WebSocketHandler.js +3 -3
- package/dist/types/proxyClient.d.ts +33 -0
- package/dist/workflow/config.d.ts +1 -1
- package/dist/workflow/config.js +1 -1
- package/dist/workflow/core/workflowRegistry.js +1 -1
- package/dist/workflow/core/workflowRunner.js +1 -1
- package/dist/workflow/utils/workflowMetrics.d.ts +1 -1
- package/dist/workflow/utils/workflowMetrics.js +1 -1
- package/package.json +2 -1
|
@@ -2342,16 +2342,16 @@ data: ${r}
|
|
|
2342
2342
|
`))k.startsWith("event:")?b=k.slice(6).trim():k.startsWith("data:")&&T.push(k.slice(5).trim());b&&T.length>0&&h(b,T.join(`
|
|
2343
2343
|
`),y),v=s.indexOf(`
|
|
2344
2344
|
|
|
2345
|
-
`)}};return new TransformStream({transform(y,v){s+=o.decode(y,{stream:!0}),g(v)},flush(y){if(s+=o.decode(),g(y),!d){d=!0;const v="Anthropic stream ended before message_stop";t.onError?.(v),m(y,r.emitError(v))}}})}Lr(),ic(),q(),gn(),ya(),Ft(),NS(),Em();var gpn=globalThis.crypto,Cnn=class{getStore(){}run(e,t,...r){return t(...r)}enterWith(){}disable(){}},ypn=globalThis.ReadableStream||class{},vpn=globalThis.URL,_pn=globalThis.URLSearchParams,Wae=e=>{try{return JSON.stringify(e,null,2)}catch{return String(e)}};Wae.custom=Symbol.for("nodejs.util.inspect.custom"),Wae.colors={},Wae.styles={};var knn=globalThis.TextDecoder,
|
|
2345
|
+
`)}};return new TransformStream({transform(y,v){s+=o.decode(y,{stream:!0}),g(v)},flush(y){if(s+=o.decode(),g(y),!d){d=!0;const v="Anthropic stream ended before message_stop";t.onError?.(v),m(y,r.emitError(v))}}})}var hsr=["claude-opus-4-6","claude-sonnet-4-6","claude-haiku-4-5","claude-sonnet-4-20250514","claude-3-5-sonnet-20241022","claude-3-5-haiku-20241022","gpt-4o","gemini-2.5-pro","gemini-2.5-flash"];Lr(),ic(),q(),gn(),ya(),Ft(),NS(),Em();var gpn=globalThis.crypto,Cnn=class{getStore(){}run(e,t,...r){return t(...r)}enterWith(){}disable(){}},ypn=globalThis.ReadableStream||class{},vpn=globalThis.URL,_pn=globalThis.URLSearchParams,Wae=e=>{try{return JSON.stringify(e,null,2)}catch{return String(e)}};Wae.custom=Symbol.for("nodejs.util.inspect.custom"),Wae.colors={},Wae.styles={};var knn=globalThis.TextDecoder,fsr=globalThis.TextEncoder,wpn=globalThis.performance||{now:()=>Date.now()},bpn=globalThis.Buffer||class extends Uint8Array{static from(t,r){if(typeof t=="string"){const n=(r||"utf8").toLowerCase();if(n==="base64"){const o=atob(t),s=new Uint8Array(o.length);for(let i=0;i<o.length;i++)s[i]=o.charCodeAt(i);return s}if(n==="hex"){const o=new Uint8Array(t.length/2);for(let s=0;s<t.length;s+=2)o[s/2]=parseInt(t.substr(s,2),16);return o}return new fsr().encode(t)}return new Uint8Array(t)}static alloc(t){return new Uint8Array(t)}static isBuffer(t){return t instanceof Uint8Array}static concat(t){const r=t.reduce((s,i)=>s+i.length,0),n=new Uint8Array(r);let o=0;for(const s of t)n.set(s,o),o+=s.length;return n}static byteLength(t,r){return r==="base64"?Math.ceil(t.length*3/4):new fsr().encode(t).length}toString(t){const r=(t||"utf8").toLowerCase();if(r==="hex")return Array.from(new Uint8Array(this.buffer,this.byteOffset,this.byteLength)).map(n=>n.toString(16).padStart(2,"0")).join("");if(r==="base64"){let n="";for(let o=0;o<this.length;o++)n+=String.fromCharCode(this[o]);return btoa(n)}return new knn().decode(this)}},Epn=globalThis.clearTimeout,Spn=globalThis.clearInterval,gsr=new Cnn;function Gw(){return gsr.getStore()}function xnn(){return gsr.getStore()!==void 0}NUe();var sA={UNSPECIFIED:0,TRACE:1,TRACE2:2,TRACE3:3,TRACE4:4,DEBUG:5,DEBUG2:6,DEBUG3:7,DEBUG4:8,INFO:9,INFO2:10,INFO3:11,INFO4:12,WARN:13,WARN2:14,WARN3:15,WARN4:16,ERROR:17,ERROR2:18,ERROR3:19,ERROR4:20,FATAL:21,FATAL2:22,FATAL3:23,FATAL4:24},Th=null,Kae=!1,Jae=new Set,R2=5e3;function M2(e){return Jae.add(e),e.then(()=>Jae.delete(e),()=>Jae.delete(e)),e}var Hw=null,ysr=0,Ann=10,Inn=16e3,Rnn=1024*1024,Mnn=`
|
|
2346
2346
|
...[TRUNCATED]`,Pnn=VP(AH),Dnn=new Set(["authorization","proxy-authorization","x-api-key","cookie","set-cookie"]),Onn=/token|secret|key|password|credential/i,Nnn=/("(?:password|access_token|refresh_token|api_key|apiKey|secret|authorization|token|credential|x-api-key)"\s*:\s*)"(?:[^"\\]|\\.)*"/gi;async function Eh(e){if(!Kae||!Th)return;if(!e.traceId){const o=new Yv().getCurrentTraceContext();o&&(e.traceId=o.traceId,e.spanId=o.spanId)}const t=Cr(Th,`proxy-${new Date().toISOString().split("T")[0]}.jsonl`),r=JSON.stringify(e)+`
|
|
2347
2347
|
`;try{await M2(l0(t,r,{mode:384,flag:"a",signal:AbortSignal.timeout(R2)}))}catch{}$nn(e)}async function Lnn(e){if(!Kae||!Th)return;if(!e.traceId){const o=new Yv().getCurrentTraceContext();o&&(e.traceId=o.traceId,e.spanId=o.spanId)}const t=Cr(Th,`proxy-attempts-${new Date().toISOString().split("T")[0]}.jsonl`),r=JSON.stringify(e)+`
|
|
2348
|
-
`;try{await M2(l0(t,r,{mode:384,flag:"a",signal:AbortSignal.timeout(R2)}))}catch{}}async function
|
|
2349
|
-
`,{mode:384,flag:"a",signal:AbortSignal.timeout(R2)}))}catch{}Wnn({...e,traceId:r?.traceId??e.traceId,spanId:r?.spanId??e.spanId},s)}fie(),yn(),ct(),q();var P2=300*1e3;function Yae(e){if(typeof e=="string")return e;if(e&&typeof e=="object"){const t=e;if(typeof t.content=="string")return t.content;if(t.type==="text-delta"&&typeof t.textDelta=="string")return t.textDelta;if(typeof t.text=="string")return t.text}return null}function
|
|
2348
|
+
`;try{await M2(l0(t,r,{mode:384,flag:"a",signal:AbortSignal.timeout(R2)}))}catch{}}async function vsr(){if(Hw!==!1){if(Hw!==null)return Hw;ysr++;try{const{getLoggerProvider:e}=await Promise.resolve().then(()=>(qm(),rJ)),t=e();if(t)return Hw=t,t;ysr>=Ann&&(Hw=!1);return}catch{Hw=!1;return}}}function $nn(e){vsr().then(t=>{if(!t)return;const r=t.getLogger("neurolink-proxy","1.0.0"),n=(e.responseStatus??0)>=400,o=e.responseStatus===429,s=n?o?sA.WARN:sA.ERROR:sA.INFO,i=n?o?"WARN":"ERROR":"INFO";r.emit({severityNumber:s,severityText:i,body:`${e.method} ${e.path} \u2192 ${e.responseStatus} (${e.responseTimeMs}ms)`,attributes:{"request.id":e.requestId,"http.method":e.method,"http.path":e.path,"http.status_code":e.responseStatus,"response.time_ms":e.responseTimeMs,"ai.model":e.model,"ai.stream":e.stream,"ai.tool_count":e.toolCount,"account.name":e.account,"account.type":e.accountType,...e.routingDecision&&{"routing.mode":e.routingDecision.mode,"routing.strategy":e.routingDecision.strategy,"routing.selection_reason":e.routingDecision.selectionReason,"routing.initial_account":e.routingDecision.initialAccount,"routing.candidate_count":e.routingDecision.candidates.length,"routing.final_account_changed":e.routingDecision.initialAccount!==e.account&&e.routingDecision.candidates.some(a=>a.account===e.account&&a.accountType===e.accountType)},...e.inputTokens!==void 0&&{"ai.input_tokens":e.inputTokens},...e.outputTokens!==void 0&&{"ai.output_tokens":e.outputTokens},...e.cacheCreationTokens!==void 0&&{"ai.cache_creation_tokens":e.cacheCreationTokens},...e.cacheReadTokens!==void 0&&{"ai.cache_read_tokens":e.cacheReadTokens},...e.errorType&&{"error.type":e.errorType},...e.errorMessage&&{"error.message":e.errorMessage},...e.traceId&&{"trace.id":e.traceId},...e.spanId&&{"span.id":e.spanId},is_success:e.responseStatus===200,is_rate_limited:e.responseStatus===429,is_overloaded:e.responseStatus===529,is_error:n,source:"otlp"}})}).catch(()=>{})}function Fnn(e){if(!e)return e;const t={};for(const[r,n]of Object.entries(e)){const o=r.toLowerCase();Dnn.has(o)||Onn.test(o)?t[r]="[REDACTED]":t[r]=n}return t}function Unn(e){if(e!=null)return typeof e=="string"?e:JSON.stringify(e)}function Bnn(e){const t=Unn(e);if(t!==void 0)return t.replace(Nnn,'$1"[REDACTED]"')}function znn(e){return e.replace(/[^a-zA-Z0-9._-]+/g,"_")}function jnn(e){return Kc("sha256").update(e).digest("hex")}function Vw(e){return Buffer.byteLength(e,"utf8")}function qnn(e,t,r=Mnn){const n=Vw(e);if(n<=t)return{value:e,bytes:n,truncated:!1};const o=Vw(r);if(t<=o)return{value:r,bytes:o,truncated:!0};let s="",i=0;for(const l of e){const c=Vw(l);if(i+c+o>t)break;s+=l,i+=c}const a=`${s}${r}`;return{value:a,bytes:Vw(a),truncated:!0}}function Gnn(e,t){if(!e)return[""];const r=[];let n="",o=0;for(const s of e){const i=Vw(s);if(n&&o+i>t){r.push(n),n=s,o=i;continue}n+=s,o+=i}return n&&r.push(n),r}function Hnn(e){const t=Bnn(e);return t===void 0?{truncated:!1}:qnn(t,Rnn)}async function Vnn(e,t,r,n){if(!Th||r===void 0)return{};const o=new Date(e.timestamp).toISOString().split("T")[0],s=Cr(Th,"bodies",o,e.requestId);Os(s)||C1(s,{recursive:!0,mode:448}),Bz(s,448);const i=`${Date.now()}-${znn(e.phase)}`+(e.attempt!==void 0?`-attempt-${e.attempt}`:"")+".json.gz",a=Cr(s,i),l=JSON.stringify({timestamp:e.timestamp,requestId:e.requestId,phase:e.phase,model:e.model,stream:e.stream,account:e.account,accountType:e.accountType,attempt:e.attempt,responseStatus:e.responseStatus,durationMs:e.durationMs,contentType:e.contentType,headers:t,body:r,traceId:e.traceId,spanId:e.spanId,metadata:e.metadata}),c=await Pnn(l);return await l0(a,c,{mode:384,signal:AbortSignal.timeout(R2)}),{bodyPath:a,bodySha256:jnn(r),redactedBodyBytes:Vw(r),storedFileBytes:c.byteLength,redactedBody:r,bodyTruncated:n}}function Wnn(e,t){vsr().then(r=>{if(!r||t.redactedBody===void 0)return;const n=r.getLogger("neurolink-proxy-bodies","1.0.0"),o=Gnn(t.redactedBody,Inn),s=Math.max(1,o.length);for(let i=0;i<s;i++){const a=o[i]??"";n.emit({severityNumber:(e.responseStatus??0)>=400?sA.WARN:sA.INFO,severityText:(e.responseStatus??0)>=400?"WARN":"INFO",body:a,attributes:{"event.name":"proxy.body_capture","request.id":e.requestId,"body.phase":e.phase,"body.chunk_index":i,"body.chunk_count":s,"body.content_type":e.contentType??"application/json","ai.model":e.model,"ai.stream":e.stream,...e.account&&{"account.name":e.account},...e.accountType&&{"account.type":e.accountType},...e.attempt!==void 0&&{"proxy.attempt":e.attempt},...e.responseStatus!==void 0&&{"http.status_code":e.responseStatus},...e.durationMs!==void 0&&{"response.time_ms":e.durationMs},...t.bodySha256&&{"body.sha256":t.bodySha256},...t.bodyPath&&{"body.path":t.bodyPath.split("/").slice(-2).join("/")},...t.redactedBodyBytes!==void 0&&{"body.bytes":t.redactedBodyBytes},...t.bodyTruncated!==void 0&&{"body.truncated":t.bodyTruncated},...e.traceId&&{"trace.id":e.traceId},...e.spanId&&{"span.id":e.spanId},...e.metadata&&{"body.metadata_json":JSON.stringify(e.metadata)},source:"otlp"}})}}).catch(()=>{})}async function Knn(e){if(!Kae||!Th||xnn())return;const t=new Yv,r=e.traceId&&e.spanId?{traceId:e.traceId,spanId:e.spanId}:t.getCurrentTraceContext(),n=Fnn(e.headers),o=Hnn(e.body);let s;try{s=await M2(Vnn(e,n,o.value,o.truncated))}catch(c){f.warn("[RequestLogger] writeBodyArtifact failed, falling back to in-memory body for OTLP",{error:c}),s={redactedBody:o.value,redactedBodyBytes:o.bytes,bodyTruncated:o.truncated,bodyWriteFailed:!0}}const i=new Date(e.timestamp).toISOString().split("T")[0],a=Cr(Th,`proxy-debug-${i}.jsonl`),l={timestamp:e.timestamp,type:"body_capture",requestId:e.requestId,phase:e.phase,model:e.model,stream:e.stream,headers:n,contentType:e.contentType,responseStatus:e.responseStatus,durationMs:e.durationMs,account:e.account,accountType:e.accountType,attempt:e.attempt,bodyPath:s.bodyPath,bodySha256:s.bodySha256,observedBodyBytes:e.bodySize,redactedBodyBytes:s.redactedBodyBytes??o.bytes,storedFileBytes:s.storedFileBytes,bodyTruncated:s.bodyTruncated??o.truncated,bodyWriteFailed:s.bodyWriteFailed,metadata:e.metadata};r&&(l.traceId=r.traceId,l.spanId=r.spanId);try{await M2(l0(a,JSON.stringify(l)+`
|
|
2349
|
+
`,{mode:384,flag:"a",signal:AbortSignal.timeout(R2)}))}catch{}Wnn({...e,traceId:r?.traceId??e.traceId,spanId:r?.spanId??e.spanId},s)}fie(),yn(),ct(),q();var P2=300*1e3;function Yae(e){if(typeof e=="string")return e;if(e&&typeof e=="object"){const t=e;if(typeof t.content=="string")return t.content;if(t.type==="text-delta"&&typeof t.textDelta=="string")return t.textDelta;if(typeof t.text=="string")return t.text}return null}function _sr(e){return e.args??e.parameters??e.input??{}}function D2(e,t){return e.trim().length>0||(t?.length??0)>0}function Ww(e){if(!e||typeof e!="object")return{input:0,output:0,total:0};const t=e,r=(typeof t.inputTokens=="number"?t.inputTokens:0)||(typeof t.promptTokens=="number"?t.promptTokens:0)||(typeof t.input=="number"?t.input:0),n=(typeof t.outputTokens=="number"?t.outputTokens:0)||(typeof t.completionTokens=="number"?t.completionTokens:0)||(typeof t.output=="number"?t.output:0);return{input:r,output:n,total:r+n}}function Jnn(e,t){return e==="litellm"&&t==="open-large"}function Ynn(e,t){if(e==="litellm")return!0;if(e==="vertex"){const r=t?.toLowerCase()??"";return!/gemini-(2\.5|3)/.test(r)}return!1}function Zae(e,t={}){const r=e.conversationMessages.slice(0,-1),n=Object.keys(e.tools),o=e,s=Jnn(t.provider,t.model)?[]:e.images,i=o.thinkingConfig&&!Ynn(t.provider,t.model)?o.thinkingConfig:void 0,a=e,l=a.toolChoiceName?{type:"tool",toolName:a.toolChoiceName}:a.toolChoice;return{input:{text:e.prompt,...s.length>0?{images:s}:{}},...t.provider?{provider:t.provider}:{},...t.model?{model:t.model}:{},systemPrompt:e.systemPrompt,...e.maxTokens!==void 0?{maxTokens:e.maxTokens}:{},...e.temperature!==void 0?{temperature:e.temperature}:{},...e.topP!==void 0?{topP:e.topP}:{},...o.topK!==void 0?{topK:o.topK}:{},...e.stopSequences?.length?{stopSequences:e.stopSequences}:{},...i?{thinkingConfig:i}:{},...n.length===0?{disableTools:!0}:{},...n.length>0?{tools:e.tools,toolFilter:n}:{},...l?{toolChoice:l}:{},...r.length>0?{conversationMessages:r}:{},disableInternalFallback:!0,skipToolPromptInjection:!0,maxSteps:1}}function Znn(e){const t=new nsr(e,0);return{start:()=>t.start(),pushDelta:r=>t.pushDelta(r),pushToolUse:(r,n,o)=>t.pushToolUse(r,n,o),finish:(r,n)=>t.finish(n.output,r),emitError:r=>t.emitError(500,r)}}function Xnn(e){const t=new msr(e);return{start:()=>t.start(),pushDelta:r=>t.pushDelta(r),pushToolUse:(r,n,o)=>t.pushToolUse(r,n,o),finish:(r,n)=>t.finish(r,n),emitError:r=>t.emitError(r)}}function Qnn(e){return e==="claude"?Gae():usr()}function Xae(e){return e==="claude"?"end_turn":"stop"}function wsr(e){return e==="claude"?"[proxy]":e==="gemini"?"[proxy:gemini]":"[proxy:openai]"}async function Qae(e){const{ctx:t,format:r,requestModel:n,parsed:o,attempts:s,tracer:i,requestStartTime:a}=e,l=wsr(r),c=r==="claude"?Znn(n):r==="gemini"?vnn(n):Xnn(n),u=15e3,d=new TextEncoder;let m,h=!1,g=!1,y=!1,v,_,b=!1,T="No translation providers succeeded",k,A="translation";const I=new ReadableStream({async start(M){for(const R of c.start())M.enqueue(d.encode(R));m=setInterval(()=>{try{M.enqueue(d.encode(`: keep-alive
|
|
2350
2350
|
|
|
2351
|
-
`))}catch{}},u);try{for(let R=0;R<s.length&&!h;R++){const x=s[R];A=x.label??"translation",f.always(`[proxy:${r}] attempt ${R+1}/${s.length}: ${x.label}`),xw(A,"translation");let O="";try{const N=Zae(o,x.provider?{provider:x.provider,model:x.model}:{}),P=await zt(t.neurolink.stream(N),P2,`Translation attempt ${x.label} timed out after ${P2}ms`);for(k=P.stream[Symbol.asyncIterator]();!h;){const{value:U,done:j}=await k.next();if(j||h)break;const B=Yae(U);if(B){O+=B;for(const z of c.pushDelta(B))M.enqueue(d.encode(z))}}if(h)return;const L=P.toolCalls??[];if(!D2(O,L)){T=`Translated provider ${x.label} returned no content or tool calls`,f.debug(`${l} translation attempt ${x.label} returned no content or tool calls`),an(A,"translation",502);continue}if(!h&&L.length)for(const U of L){const j=U.toolName??U.name??"unknown",B=U.toolCallId||Qnn(r);for(const z of c.pushToolUse(B,j,vsr(U)))M.enqueue(d.encode(z))}if(!h){const U=P.finishReason??Xae(r),j=Ww(P.usage);for(const B of c.finish(U,j))M.enqueue(d.encode(B))}v=P.model,_=x.provider,i&&v&&v!==n&&(i.setModelSubstitution(n,v,_),b=!0);const $=Ww(P.usage);i?.setUsage({inputTokens:$.input,outputTokens:$.output,cacheCreationTokens:0,cacheReadTokens:0}),i?.recordMetrics(),g=!0;return}catch(N){if(h)return;if(T=N instanceof Error?N.message:String(N),O.trim().length>0){y=!0,an(A,"translation",502),f.always(`${l} mid-stream error: ${T}`);for(const P of c.emitError(`Upstream stream interrupted: ${T}`))M.enqueue(d.encode(P));return}f.debug(`${l} translation attempt ${x.label} failed: ${T}`),an(A,"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,x=h?"client_cancelled":y?"stream_error":g?void 0:"generation_error",O=h?"Client cancelled the streaming response":g?void 0:T;x&&O?(i?.setError(x,O.slice(0,500)),Fx(R,A,"translation",{requestId:t.requestId,errorType:x,terminalOutcome:x,message:O})):K$(A,"translation"),i?.end(R,Date.now()-a);const N=i?.getTraceContext();Eh({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",responseStatus:R,responseTimeMs:Date.now()-a,...x?{errorType:x}:{},...O?{errorMessage:O.slice(0,500)}:{},...N?.traceId?{traceId:N.traceId}:{},...N?.spanId?{spanId:N.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 ele(e){const{ctx:t,format:r,requestModel:n,parsed:o,attempts:s,tracer:i,requestStartTime:a,terminalFailureStatus:l=500}=e,c=_sr(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}`),xw(d,"translation");try{const y=Zae(o,g.provider?{provider:g.provider,model:g.model}:{}),v=await zt(t.neurolink.stream(y),P2,`Translation attempt ${g.label} timed out after ${P2}ms`);let _="";for await(const A of v.stream){const I=Yae(A);I&&(_+=I)}if(!D2(_,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`),an(d,"translation",502);continue}const b={content:_,model:v.model,finishReason:v.finishReason??Xae(r),reasoning:void 0,usage:v.usage?Ww(v.usage):void 0,toolCalls:v.toolCalls};i&&v.model&&v.model!==n&&i.setModelSubstitution(n,v.model,g.provider);const T=Ww(v.usage);i?.setUsage({inputTokens:T.input,outputTokens:T.output,cacheCreationTokens:0,cacheReadTokens:0}),i?.recordMetrics(),i?.end(200,Date.now()-a),K$(d,"translation");const k=i?.getTraceContext();return Eh({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",responseStatus:200,responseTimeMs:Date.now()-a,inputTokens:T.input,outputTokens:T.output,...k?.traceId?{traceId:k.traceId}:{},...k?.spanId?{spanId:k.spanId}:{}}),r==="claude"?rsr(b,n):r==="gemini"?gnn(b.content,b.finishReason??Xae(r),T,b.model??n,b.toolCalls):psr(b,n)}catch(y){u=y instanceof Error?y.message:String(y),f.debug(`${c} translation attempt ${g.label} failed: ${u}`),an(d,"translation",500)}}Fx(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 Eh({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",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 eon(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 wsr)t.push({id:r,object:"model",created:0,owned_by:"neurolink"});return{object:"list",data:t}}var wsr=["claude-opus-4-6","claude-sonnet-4-6","claude-haiku-4-5","claude-sonnet-4-20250514","claude-3-5-sonnet-20241022","claude-3-5-haiku-20241022","gpt-4o","gemini-2.5-pro","gemini-2.5-flash"];function ton(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(...wsr);const r=new Set,o=t.filter(s=>r.has(s)?!1:(r.add(s),!0)).map(s=>({type:"model",id:s,display_name:ron(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 ron(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}yr(),Vr(),er(),qm(),NUe(),uc(),KE(),q();var non="[ProxyTracer]",tle=null;function iA(){if(tle)return tle;const e=Ph.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 tle=t,t}var oon=new Set(["authorization","proxy-authorization","x-api-key","cookie","set-cookie"]),son=/token|secret|key|password|credential/i;function rle(e){const t={};for(const[r,n]of Object.entries(e)){const o=r.toLowerCase();oon.has(o)||son.test(o)?t[r]="[REDACTED]":t[r]=n}return t}var ion=/api[_-]?key|token|secret|password|credential|authorization/i,O2=process.env.NEUROLINK_PROXY_TRACE_BODY_LOGGING==="true",nle=Number.parseInt(process.env.NEUROLINK_PROXY_TRACE_BODY_LOG_BYTES??"8192",10),bsr=200;function Tsr(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]=ion.test(l)?"[REDACTED]":o(c);return a};var n=o;const s=JSON.parse(r);return JSON.stringify(o(s))}catch{return r}}function ole(e){return{"proxy.body":Tsr(e,nle),"proxy.body.size":e.length,"proxy.body.logged":!0,"proxy.body.truncated":e.length>nle}}function aon(e){return e?e.startsWith("claude-cli/")?"cli":e.startsWith("ai/")?"sdk":"unknown":"unknown"}var sle=class dcr{rootSpan;proxyTracer=HD("neurolink.proxy");bridge=new Yv;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=HD("neurolink.proxy");let o=Er.active();if(r){const m=new Yv().extractContext(r);m&&(o=_t.setSpanContext(Er.active(),m))}const s=t.clientApp??aon(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 dcr(i,t.requestId,t.model,t.stream,t.provider??"anthropic");return k0({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(`${non} 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}},_t.setSpan(Er.active(),this.rootSpan))}startAccountSelection(){return this.proxyTracer.startSpan("proxy.account_selection",{attributes:{"proxy.request_id":this.requestId}},_t.setSpan(Er.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}},_t.setSpan(Er.active(),this.rootSpan))}startStream(){return this.proxyTracer.startSpan("proxy.stream",{attributes:{"proxy.request_id":this.requestId,"gen_ai.request.model":this.model}},_t.setSpan(Er.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),k0({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=Ga(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}:{}}),iA().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(!O2){this.rootSpan.addEvent("proxy.client.request_body",{"proxy.body.size":t.length,"proxy.body.logged":!1});return}this.rootSpan.addEvent("proxy.client.request_body",{...ole(t)})}logRequestHeaders(t){this.rootSpan.addEvent("proxy.client.request_headers",{"proxy.headers":JSON.stringify(rle(t))})}logUpstreamRequestBody(t){if(!O2){this.rootSpan.addEvent("proxy.upstream.request_body",{"proxy.body.size":t.length,"proxy.body.logged":!1});return}this.rootSpan.addEvent("proxy.upstream.request_body",{...ole(t)})}logUpstreamRequestHeaders(t){this.rootSpan.addEvent("proxy.upstream.request_headers",{"proxy.headers":JSON.stringify(rle(t))})}logUpstreamResponseHeaders(t){this.rootSpan.addEvent("proxy.upstream.response_headers",{"proxy.headers":JSON.stringify(rle(t))})}logUpstreamResponseBody(t){if(!O2){this.rootSpan.addEvent("proxy.upstream.response_body",{"proxy.body.size":t.length,"proxy.body.logged":!1});return}this.rootSpan.addEvent("proxy.upstream.response_body",{...ole(t)})}logStreamEvents(t){if(!O2){this.rootSpan.addEvent("proxy.stream.events",{"proxy.stream.event_count":t.length,"proxy.body.logged":!1});return}const r=t.length>bsr,n=t.slice(0,bsr).map(o=>({...o,data:o.data?Tsr(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){iA().retriesTotal.add(1,{model:this.model,account:t,reason:r})}recordBodySizes(t,r){const n=iA(),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=iA(),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=Ga(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=Ga(this.billingProvider,this.model,{input:this.usage.inputTokens,output:this.usage.outputTokens,total:t,cacheCreationTokens:this.usage.cacheCreationTokens,cacheReadTokens:this.usage.cacheReadTokens});kf.getInstance().recordAIRequest(this.billingProvider,this.model,t,r,n>0?n:void 0)}getTraceHeaders(){return this.bridge.injectContext({},_t.setSpan(Er.active(),this.rootSpan))}};function aA(e){try{const t=iA(),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 N2=1024*1024,ile=`
|
|
2351
|
+
`))}catch{}},u);try{for(let R=0;R<s.length&&!h;R++){const x=s[R];A=x.label??"translation",f.always(`[proxy:${r}] attempt ${R+1}/${s.length}: ${x.label}`),xw(A,"translation");let O="";try{const N=Zae(o,x.provider?{provider:x.provider,model:x.model}:{}),P=await zt(t.neurolink.stream(N),P2,`Translation attempt ${x.label} timed out after ${P2}ms`);for(k=P.stream[Symbol.asyncIterator]();!h;){const{value:U,done:j}=await k.next();if(j||h)break;const B=Yae(U);if(B){O+=B;for(const z of c.pushDelta(B))M.enqueue(d.encode(z))}}if(h)return;const L=P.toolCalls??[];if(!D2(O,L)){T=`Translated provider ${x.label} returned no content or tool calls`,f.debug(`${l} translation attempt ${x.label} returned no content or tool calls`),an(A,"translation",502);continue}if(!h&&L.length)for(const U of L){const j=U.toolName??U.name??"unknown",B=U.toolCallId||Qnn(r);for(const z of c.pushToolUse(B,j,_sr(U)))M.enqueue(d.encode(z))}if(!h){const U=P.finishReason??Xae(r),j=Ww(P.usage);for(const B of c.finish(U,j))M.enqueue(d.encode(B))}v=P.model,_=x.provider,i&&v&&v!==n&&(i.setModelSubstitution(n,v,_),b=!0);const $=Ww(P.usage);i?.setUsage({inputTokens:$.input,outputTokens:$.output,cacheCreationTokens:0,cacheReadTokens:0}),i?.recordMetrics(),g=!0;return}catch(N){if(h)return;if(T=N instanceof Error?N.message:String(N),O.trim().length>0){y=!0,an(A,"translation",502),f.always(`${l} mid-stream error: ${T}`);for(const P of c.emitError(`Upstream stream interrupted: ${T}`))M.enqueue(d.encode(P));return}f.debug(`${l} translation attempt ${x.label} failed: ${T}`),an(A,"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,x=h?"client_cancelled":y?"stream_error":g?void 0:"generation_error",O=h?"Client cancelled the streaming response":g?void 0:T;x&&O?(i?.setError(x,O.slice(0,500)),Fx(R,A,"translation",{requestId:t.requestId,errorType:x,terminalOutcome:x,message:O})):K$(A,"translation"),i?.end(R,Date.now()-a);const N=i?.getTraceContext();Eh({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",responseStatus:R,responseTimeMs:Date.now()-a,...x?{errorType:x}:{},...O?{errorMessage:O.slice(0,500)}:{},...N?.traceId?{traceId:N.traceId}:{},...N?.spanId?{spanId:N.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 ele(e){const{ctx:t,format:r,requestModel:n,parsed:o,attempts:s,tracer:i,requestStartTime:a,terminalFailureStatus:l=500}=e,c=wsr(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}`),xw(d,"translation");try{const y=Zae(o,g.provider?{provider:g.provider,model:g.model}:{}),v=await zt(t.neurolink.stream(y),P2,`Translation attempt ${g.label} timed out after ${P2}ms`);let _="";for await(const A of v.stream){const I=Yae(A);I&&(_+=I)}if(!D2(_,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`),an(d,"translation",502);continue}const b={content:_,model:v.model,finishReason:v.finishReason??Xae(r),reasoning:void 0,usage:v.usage?Ww(v.usage):void 0,toolCalls:v.toolCalls};i&&v.model&&v.model!==n&&i.setModelSubstitution(n,v.model,g.provider);const T=Ww(v.usage);i?.setUsage({inputTokens:T.input,outputTokens:T.output,cacheCreationTokens:0,cacheReadTokens:0}),i?.recordMetrics(),i?.end(200,Date.now()-a),K$(d,"translation");const k=i?.getTraceContext();return Eh({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",responseStatus:200,responseTimeMs:Date.now()-a,inputTokens:T.input,outputTokens:T.output,...k?.traceId?{traceId:k.traceId}:{},...k?.spanId?{spanId:k.spanId}:{}}),r==="claude"?rsr(b,n):r==="gemini"?gnn(b.content,b.finishReason??Xae(r),T,b.model??n,b.toolCalls):psr(b,n)}catch(y){u=y instanceof Error?y.message:String(y),f.debug(`${c} translation attempt ${g.label} failed: ${u}`),an(d,"translation",500)}}Fx(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 Eh({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",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 eon(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 hsr)t.push({id:r,object:"model",created:0,owned_by:"neurolink"});return{object:"list",data:t}}function ton(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(...hsr);const r=new Set,o=t.filter(s=>r.has(s)?!1:(r.add(s),!0)).map(s=>({type:"model",id:s,display_name:ron(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 ron(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}yr(),Vr(),er(),qm(),NUe(),uc(),KE(),q();var non="[ProxyTracer]",tle=null;function iA(){if(tle)return tle;const e=Ph.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 tle=t,t}var oon=new Set(["authorization","proxy-authorization","x-api-key","cookie","set-cookie"]),son=/token|secret|key|password|credential/i;function rle(e){const t={};for(const[r,n]of Object.entries(e)){const o=r.toLowerCase();oon.has(o)||son.test(o)?t[r]="[REDACTED]":t[r]=n}return t}var ion=/api[_-]?key|token|secret|password|credential|authorization/i,O2=process.env.NEUROLINK_PROXY_TRACE_BODY_LOGGING==="true",nle=Number.parseInt(process.env.NEUROLINK_PROXY_TRACE_BODY_LOG_BYTES??"8192",10),bsr=200;function Tsr(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]=ion.test(l)?"[REDACTED]":o(c);return a};var n=o;const s=JSON.parse(r);return JSON.stringify(o(s))}catch{return r}}function ole(e){return{"proxy.body":Tsr(e,nle),"proxy.body.size":e.length,"proxy.body.logged":!0,"proxy.body.truncated":e.length>nle}}function aon(e){return e?e.startsWith("claude-cli/")?"cli":e.startsWith("ai/")?"sdk":"unknown":"unknown"}var sle=class dcr{rootSpan;proxyTracer=HD("neurolink.proxy");bridge=new Yv;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=HD("neurolink.proxy");let o=Er.active();if(r){const m=new Yv().extractContext(r);m&&(o=_t.setSpanContext(Er.active(),m))}const s=t.clientApp??aon(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 dcr(i,t.requestId,t.model,t.stream,t.provider??"anthropic");return k0({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(`${non} 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}},_t.setSpan(Er.active(),this.rootSpan))}startAccountSelection(){return this.proxyTracer.startSpan("proxy.account_selection",{attributes:{"proxy.request_id":this.requestId}},_t.setSpan(Er.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}},_t.setSpan(Er.active(),this.rootSpan))}startStream(){return this.proxyTracer.startSpan("proxy.stream",{attributes:{"proxy.request_id":this.requestId,"gen_ai.request.model":this.model}},_t.setSpan(Er.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),k0({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=Ga(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}:{}}),iA().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(!O2){this.rootSpan.addEvent("proxy.client.request_body",{"proxy.body.size":t.length,"proxy.body.logged":!1});return}this.rootSpan.addEvent("proxy.client.request_body",{...ole(t)})}logRequestHeaders(t){this.rootSpan.addEvent("proxy.client.request_headers",{"proxy.headers":JSON.stringify(rle(t))})}logUpstreamRequestBody(t){if(!O2){this.rootSpan.addEvent("proxy.upstream.request_body",{"proxy.body.size":t.length,"proxy.body.logged":!1});return}this.rootSpan.addEvent("proxy.upstream.request_body",{...ole(t)})}logUpstreamRequestHeaders(t){this.rootSpan.addEvent("proxy.upstream.request_headers",{"proxy.headers":JSON.stringify(rle(t))})}logUpstreamResponseHeaders(t){this.rootSpan.addEvent("proxy.upstream.response_headers",{"proxy.headers":JSON.stringify(rle(t))})}logUpstreamResponseBody(t){if(!O2){this.rootSpan.addEvent("proxy.upstream.response_body",{"proxy.body.size":t.length,"proxy.body.logged":!1});return}this.rootSpan.addEvent("proxy.upstream.response_body",{...ole(t)})}logStreamEvents(t){if(!O2){this.rootSpan.addEvent("proxy.stream.events",{"proxy.stream.event_count":t.length,"proxy.body.logged":!1});return}const r=t.length>bsr,n=t.slice(0,bsr).map(o=>({...o,data:o.data?Tsr(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){iA().retriesTotal.add(1,{model:this.model,account:t,reason:r})}recordBodySizes(t,r){const n=iA(),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=iA(),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=Ga(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=Ga(this.billingProvider,this.model,{input:this.usage.inputTokens,output:this.usage.outputTokens,total:t,cacheCreationTokens:this.usage.cacheCreationTokens,cacheReadTokens:this.usage.cacheReadTokens});kf.getInstance().recordAIRequest(this.billingProvider,this.model,t,r,n>0?n:void 0)}getTraceHeaders(){return this.bridge.injectContext({},_t.setSpan(Er.active(),this.rootSpan))}};function aA(e){try{const t=iA(),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 N2=1024*1024,ile=`
|
|
2352
2352
|
...[TRUNCATED]`;function Esr(){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<N2){const v=N2-n;t.push(y.slice(0,v)),n+=Math.min(y.length,v)}else o||(t.push(ile),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<N2){const _=e.decode(y,{stream:!0}),b=N2-n,T=_.slice(0,b);t.push(T),n+=Math.min(_.length,b),_.length>b&&!o&&(t.push(ile),o=!0)}else o||(t.push(ile),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}}_xt();var lon=[["claude-cli/","claude-code"],["ai/","sdk"]],con=200;function uon(e){if(!e)return"unknown";const t=e.trim();let r,n=0;for(const[o,s]of lon)t.startsWith(o)&&o.length>n&&(r=s,n=o.length);return r??"unknown"}function don(e){if(e){for(const[t,r]of Object.entries(e))if(t.toLowerCase()==="user-agent"&&typeof r=="string"){const n=r.trim();return n?n.slice(0,con):void 0}}}function ale(e){const t=don(e);return{clientApp:uon(t),userAgent:t}}var L2=100*1024,pon=5e3,lle=2048,Ssr=1024*1024,Fp="...[TRUNCATED]";function $2(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 mon(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 Kw(e){return Buffer.byteLength(e,"utf8")}function cle(e,t){if(Kw(e)<=t)return e;const r=Kw(Fp);if(t<=0||t<r)return"";let n="",o=0;for(const s of e){const i=Kw(s);if(o+i+r>t)break;n+=s,o+=i}return`${n}${Fp}`}function ule(e,t){return cle(e,t)}function dle(e,t,r,n){const o=Kw(t);if(r>=n)return{value:e&&e.endsWith(Fp)?e:`${e??""}${Fp}`,nextBytes:r+o};const s=n-r,i=r+o;return o<=s?{value:`${e??""}${t}`,nextBytes:i}:{value:`${e??""}${cle(t,s)}`,nextBytes:i}}function Csr(e,t){if(!e.rawTextChunks||e.rawTextTruncated)return;const r=Ssr-e.rawTextBytes;if(r<=0){e.rawTextChunks.push(Fp),e.rawTextTruncated=!0;return}const n=Kw(t);if(n<=r){e.rawTextChunks.push(t),e.rawTextBytes+=n;return}e.rawTextChunks.push(cle(t,r)),e.rawTextBytes=Ssr,e.rawTextTruncated=!0}function hon(e){return Kw(e.text??e.thinking??e.toolInput??"")}function fon(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 gon(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 yon(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,hon(s))}function von(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>=L2;if(n.type==="text_delta"&&n.text!==null){const a=n.text,l=dle(o.text,a,s,L2);e.blockByteCounts.set(r,l.nextBytes),(!i||!o.text?.endsWith(Fp))&&(o.text=l.value)}else if(n.type==="thinking_delta"&&n.thinking!==null){const a=n.thinking,l=dle(o.thinking,a,s,L2);e.blockByteCounts.set(r,l.nextBytes),(!i||!o.thinking?.endsWith(Fp))&&(o.thinking=l.value)}else if(n.type==="input_json_delta"&&n.partial_json!==null){const a=n.partial_json,l=dle(o.toolInput,a,s,L2);e.blockByteCounts.set(r,l.nextBytes),(!i||!o.toolInput?.endsWith(Fp))&&(o.toolInput=l.value)}}function _on(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 ksr(e,t){e.eventCount++;const r=Date.now();if(e.events.length<pon-1?t.event==="content_block_delta"?e.events.push({type:t.event,timestamp:r,data:""}):e.events.push({type:t.event,timestamp:r,data:ule(t.data,lle)}):e.eventLogTruncated||(e.events.push({type:"truncated",timestamp:r,data:Fp}),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()?ule(i.trim(),lle):ule(t.data,lle)}switch(t.event){case"message_start":gon(e,n);break;case"content_block_start":yon(e,n);break;case"content_block_delta":von(e,n);break;case"message_delta":_on(e,n);break;default:break}}function F2(e={}){const t=e.captureRawText??!1,r=mon(t);let n="",o=!1;const s=new TextDecoder;let i;const a=new Promise(v=>{i=v});function l(){o||(o=!0,i(fon(r)))}const c=new TransformStream({transform(v,_){_.enqueue(v),r.totalBytesReceived+=v.byteLength;const b=s.decode(v,{stream:!0});Csr(r,b),n+=b;const{events:T,remainder:k}=$2(n);n=k;for(const A of T)ksr(r,A)},flush(){const v=s.decode();if(v&&(Csr(r,v),n+=v),n.trim()){const{events:_}=$2(n+`
|
|
2353
2353
|
|
|
2354
|
-
`);for(const b of _)ksr(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}}Kr(),ii(),rr(),Mc(),q(),Bl();var won="proxy-peers.json",bon=1e3,Ton={exhausted:9e5,withheld:6e5,paused:3e5,revoked:864e5,expired:864e5,unreachable:6e4,upstream_error:12e4},Eon=null,Up={},lA=0,cA=-1,uA=!1,xsr=new ol;function ple(){return Eon??St(Va(),".neurolink",won)}function Son(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 Con(e){return e?.code==="ENOENT"}async function mle(e={}){const t=Date.now();if(!e.force&&uA&&t-lA<bon)return;const r=ple();let n;try{n=(await qs(r)).mtimeMs}catch(o){if(!Con(o))throw o;Up={},cA=-1,lA=t,uA=!0;return}if(!e.force&&uA&&n===cA){lA=t;return}try{const o=JSON.parse(await Wr(r,"utf8"));Up=Object.fromEntries(Object.entries(o?.peers??{}).filter(s=>Son(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)}`),Up={}}cA=n,lA=t,uA=!0}async function Asr(){const e={schemaVersion:1,peers:Up};await sl(ple(),e);try{cA=(await qs(ple())).mtimeMs}catch{cA=-1}lA=Date.now(),uA=!0}function Isr(e){return e.trim().toLowerCase()}async function kon(){return await mle(),Object.values(Up).sort((e,t)=>e.priority-t.priority||e.createdAt-t.createdAt)}async function xon(e=Date.now()){return(await kon()).filter(r=>r.enabled&&!(r.cooldownUntil&&r.cooldownUntil>e))}function Aon(e){return Ton[e]}var Ion=6048e5;async function hle(e,t,r){await xsr.runExclusive(async()=>{await mle({force:!0});const n=Isr(e),o=Up[n];if(!o)return;const s=(r??0)*1e3,i=Date.now()+Math.min(Ion,Math.max(Aon(t),Number.isFinite(s)?s:0));Up[n]={...o,cooldownUntil:i,cooldownReason:t,updatedAt:Date.now()},await Asr()})}async function Ron(e,t){await xsr.runExclusive(async()=>{await mle({force:!0});const r=Isr(e),n=Up[r];n&&(Up[r]={...n,cooldownUntil:0,lastUsedAt:Date.now(),updatedAt:Date.now(),...t?{lastObservation:t}:{}},await Asr())})}Kr(),ii(),rr(),Mc(),Q$();var Mon=6048e5,Pon=9e5,Don=864e5;function Oon(e){return!e.usable}function Rsr(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 Msr(e,t){return gie(e,t)}function Psr(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??Mon,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??Pon,offlineGraceMs:r?.offlineGraceMs??Don,gates:e.gates,entitlementSnapshot:e.entitlement.ledger==="coins"?e.entitlement.coins??0:"unlimited"};return{...i,signature:Msr(Rsr(i),n)}}function Non(e,t){const{signature:r,...n}=e;return aQt(Msr(Rsr(n),t),r)}function Lon(e){const t=e.now??Date.now();if(!Non(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 $on(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:Psr(e.grant,t),lenderUrl:(e.lenderUrl??"").replace(/\/+$/,"")}}Bl();var Fon="proxy-resident-grants.json",Uon=1e3,Bon=null,ky={},dA=0,pA=-1,mA=!1,zon=new ol;function fle(){return Bon??St(Va(),".neurolink",Fon)}function jon(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 qon(e){return e?.code==="ENOENT"}async function Dsr(e={}){const t=Date.now();if(!e.force&&mA&&t-dA<Uon)return;const r=fle();let n;try{n=(await qs(r)).mtimeMs}catch(o){if(!qon(o))throw o;ky={},pA=-1,dA=t,mA=!0;return}if(!e.force&&mA&&n===pA){dA=t;return}try{const o=JSON.parse(await Wr(r,"utf8"));ky=Object.fromEntries(Object.entries(o?.grants??{}).filter(s=>jon(s[1])))}catch(o){if(e.force)throw o;ky={}}pA=n,dA=t,mA=!0}async function Gon(){const e={schemaVersion:1,grants:ky};await sl(fle(),e);try{pA=(await qs(fle())).mtimeMs}catch{pA=-1}dA=Date.now(),mA=!0}function Osr(e){return e.toLowerCase()}async function gle(e){await Dsr();const t=e.toLowerCase(),r=t.includes(":")?t.slice(t.indexOf(":")+1):t;return ky[Osr(r)]}async function Hon(e,t=Date.now()){const r=await gle(e);if(r)return Lon({lease:r.lease,secret:r.leaseSecret,...r.lastHeartbeatAt!==void 0?{lastHeartbeatAt:r.lastHeartbeatAt}:{},now:t})}async function Von(e,t){await zon.runExclusive(async()=>{await Dsr({force:!0});const r=Osr(e),n=ky[r];n&&(ky[r]={...n,unreportedCoins:(n.unreportedCoins??0)+t,unreportedRequests:(n.unreportedRequests??0)+1},await Gon())})}q();var Won=15e3,Kon=12e4;function Jon(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 Nsr(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 Yon(e){const t=Nsr(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 Zon(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()},Kon),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 Xon(e){const{peer:t,body:r,stream:n}=e,o=new AbortController,s=setTimeout(()=>o.abort(),Won);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 Ron(t.name,Yon(i)).catch(u=>{f.debug(`[proxy] could not record success for peer=${t.name}: ${u instanceof Error?u.message:String(u)}`)}),{ok:!0,response:Zon(i,t,o),peer:t};const a=i.headers.get("x-neurolink-grant-reason"),l=Jon(a),c=Nsr(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)}}qx();var Qon=36e5,esn={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 tsn(e){return esn[e]}function rsn(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 nsn(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 osn(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 Lsr(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 $sr(e,t,r){const n=e.spillover;if(!n)return!1;const o=n.beforeResetHours*Qon,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 yle(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 vle(e,t,r,n){const o=e.gates,{inScope:s,outOfScope:i}=yle(o,t),a=s.some(m=>$sr(o,m,r)),l=Lsr(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=$sr(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=Lsr(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 _le(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 ssn="x-neurolink-share-token",isn="x-neurolink-grant-status",asn="x-neurolink-grant-reason",lsn="x-neurolink-grant-remaining-coins",csn="x-neurolink-grant-peer";function usn(e){const t=e[ssn];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 cXr(o)?o:void 0}function dsn(e){return e===401?"authentication_error":e===403?"permission_error":"rate_limit_error"}function psn(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 Jw(e,t){const{status:r,grant:n,retryAfterSeconds:o}=t,s={[isn]:psn(e,n),[asn]:e};return n&&(s[csn]=n.peerLabel,n.entitlement.ledger==="coins"&&(s[lsn]=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:dsn(r),message:t.message??tsn(e)}}}}qx(),Kr(),ii(),rr(),Mc(),Bl();var msn="proxy-share-audit.json",hsn=2,fsn=3,gsn=1e3,ysn=null,Yw={},hA=0,fA=-1,gA=!1,vsn=new ol;function wle(){return ysn??St(Va(),".neurolink",msn)}function _sn(e){return e?.code==="ENOENT"}async function wsn(e={}){const t=Date.now();if(!e.force&&gA&&t-hA<gsn)return;const r=wle();let n;try{n=(await qs(r)).mtimeMs}catch(o){if(!_sn(o))throw o;Yw={},fA=-1,hA=t,gA=!0;return}if(!e.force&&gA&&n===fA){hA=t;return}try{Yw=JSON.parse(await Wr(r,"utf8"))?.records??{}}catch(o){if(e.force)throw o;Yw={}}fA=n,hA=t,gA=!0}async function bsn(){const e={schemaVersion:1,records:Yw};await sl(wle(),e);try{fA=(await qs(wle())).mtimeMs}catch{fA=-1}hA=Date.now(),gA=!0}function Fsr(e,t){return e===null||t===null?0:Math.max(0,(t-e)*100)}function Tsn(e,t,r=hsn){if(!e)return{drifted:!1,reason:"no_baseline"};if(t.lenderRequests>0)return{drifted:!1,reason:"attributable"};const n=Fsr(e.sessionUsed,t.sessionUsed),o=Fsr(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 Esn(e){const t=e.streakLimit??fsn;return vsn.runExclusive(async()=>{await wsn({force:!0});const r=Yw[e.grantId],n=e.lenderRequestsTotal===void 0?e.observation:{...e.observation,lenderRequests:Math.max(0,e.lenderRequestsTotal-(r?.lenderRequestsTotal??0))},o=Tsn(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),Yw[e.grantId]=i,await bsn(),{verdict:o,shouldPause:a}})}Vo(),Kr(),ii(),rr(),Mc(),Bl();var Ssn="proxy-share-provisioning.json",Csn=9e5,ksn=/^[A-Za-z0-9_-]{43}$/,xsn=/^[A-Za-z0-9_-]{16,128}$/,Asn=null,Zw={},Usr=!1,Bsr=new ol;function zsr(){return Asn??St(Va(),".neurolink",Ssn)}function Isn(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 jsr(e={}){if(!(Usr&&!e.force)){try{const t=JSON.parse(await Wr(zsr(),"utf8"));Zw=Object.fromEntries(Object.entries(t?.requests??{}).filter(r=>Isn(r[1])))}catch{Zw={}}Usr=!0}}async function qsr(){const e={schemaVersion:1,requests:Zw};await sl(zsr(),e)}function Rsn(e,t=Date.now()){return e.status!=="consumed"&&e.expiresAt>t}async function Msn(e){if(!ksn.test(e.codeChallenge))return{ok:!1,reason:"code_challenge must be a base64url S256 digest"};if(!xsn.test(e.state))return{ok:!1,reason:"state must be 16-128 base64url characters"};const t=e.now??Date.now();return Bsr.runExclusive(async()=>{await jsr({force:!0});const r={schemaVersion:1,grantId:e.grantId,codeChallenge:e.codeChallenge,challengeMethod:"S256",state:e.state,requestedAt:t,expiresAt:t+Csn,status:"pending"};return Zw[e.grantId]=r,await qsr(),{ok:!0,request:r}})}async function Psn(e,t=Date.now()){return Bsr.runExclusive(async()=>{await jsr({force:!0});const r=Zw[e];if(!r||!Rsn(r,t))return{status:"none"};if(r.status!=="authorized"||!r.code)return{status:"pending"};const{code:n,...o}=r;return Zw[e]={...o,status:"consumed",claimedAt:t},await qsr(),{status:"ready",code:r.code,state:r.state}})}bQt(),Vo(),Kr(),ii(),rr(),Mc(),qx(),Q$();var Dsn="proxy-share-notes.json",Gsr="nln",Osn=null,Xw={},Hsr=!1,Nsn=new ol;function Vsr(){return Osn??St(Va(),".neurolink",Dsn)}async function Wsr(e={}){if(!(Hsr&&!e.force)){try{Xw=JSON.parse(await Wr(Vsr(),"utf8"))?.notes??{}}catch{Xw={}}Hsr=!0}}async function Lsn(){const{writeJsonSnapshotAtomically:e}=await Promise.resolve().then(()=>(Bl(),aie)),t={schemaVersion:1,notes:Xw};await e(Vsr(),t)}function $sn(e){const t=e.trim();if(t.startsWith(`${Gsr}_`))try{const r=JSON.parse(Buffer.from(t.slice(Gsr.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 Fsn(e,t,r=Date.now()){const{signature:n,...o}=e;if(!t||!X$(o,n,t))return{status:"forged",coins:0};await Wsr({force:!0});const s=Xw[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 Usn(e){const t=e.now??Date.now(),{signature:r,...n}=e.note;if(!e.secret||!X$(n,r,e.secret))return{ok:!1,status:"forged"};const o=await Nsn.runExclusive(async()=>{await Wsr({force:!0});const i=Xw[e.note.noteId];return i?i.redeemedAt!==void 0?{status:"spent",coins:i.coins}:i.notAfter<=t?{status:"expired",coins:i.coins}:(Xw[i.noteId]={...i,redeemedAt:t,redeemedByGrant:e.grantId},await Lsn(),{status:"valid",coins:i.coins}):{status:"unknown",coins:0}});if(o.status!=="valid")return{ok:!1,status:o.status};const s=await dQt(e.grantId,o.coins);return{ok:!0,coins:o.coins,balance:s}}Q$(),DQt();var Bsn=64*1024,zsn=32;function Ksr(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 Jsr(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 jsn(e){const t=new TextDecoder,r=[];let n="",o=0;for(;o<Bsn&&r.length<zsn;){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}=$2(n),l=a.find(Jsr);return l?{kind:"sse_error",chunks:r,...Ksr(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=$2(n);n=i.remainder;for(const a of i.events){if(Jsr(a))return{kind:"sse_error",chunks:r,...Ksr(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 Ysr(){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 U2(e,t){return e.kind==="completed"&&t?{kind:"upstream_error",message:t}:e}function qsn(e){const t=e.toLowerCase();return t.includes("opus")?"opus":t.includes("sonnet")?"sonnet":t.includes("haiku")?"haiku":"other"}function yA(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:qsn(r),attempts:s,skipped:[]}}function B2(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 Gsn=1,Hsn=20;function ble(e){return typeof e=="number"&&Number.isInteger(e)&&e>=Gsn&&e<=Hsn?e:void 0}Bl(),fie(),_r(),q(),yn(),ey();var z2=new Set(["cookie","proxy-authorization","host","connection","content-length","transfer-encoding"]),Tle="proxy/internal",Ele="internal",Sh=0,Zsr=0,vA=5,j2=2,Sle=[250,1e3],Xsr=[250,500,1e3,2e3],Cle=1,Vsn=120*1e3,kle=2,Qsr=3e4,eir=11520*60*1e3,tir=5e3,Wsn=900*1e3,rir=900*1e3,Ksn=3e4,Jsn=300*1e3,_A=900*1e3,nir;function xle(e,t){return nir??=new pS({headersTimeout:_A,bodyTimeout:_A}),fetch(e,{...t,dispatcher:nir})}var Hl=new Map,wA=new nnn,Qw=new snn,oir=900*1e3,sir=new Map,iir=new Map,q2=new Map,Ysn={release:()=>{}};function air(e){let t=q2.get(e);return t||(t={active:0,waiters:[]},q2.set(e,t)),t}function Ale(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(lir(e,t))}}function lir(e,t){let r=!1;return{release:()=>{r||(r=!0,t.active=Math.max(0,t.active-1),Ale(e,t),cir(e,t))}}}function cir(e,t){t.active===0&&t.waiters.length===0&&q2.delete(e)}function Zsn(e,t){const r=ble(t);if(r===void 0)return Ysn;const n=air(e);if(!(n.waiters.length>0||n.active>=r))return n.active+=1,lir(e,n)}function Xsn(e,t){const r=ble(t);if(r===void 0)return!0;const n=q2.get(e);return!n||n.waiters.length===0&&n.active<r}function Qsn(e,t){const r=ble(t);if(r===void 0)throw new Error("Account admission queue requires an explicit capacity");const n=air(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),Ale(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),Ale(e,n)),cir(e,n)}}}async function ein(e,t,r,n=dir){const o=[...new Set(e)].map(i=>Qsn(i,t));let s;try{return await zt(tOe(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 uir=!1,Ile=6e4,dir=9e4,tin=12e4,rin=250,nin=15e3;function xy(e,t,r){t<=1||e===r&&(Sh=(Sh+1)%t)}function pir(e,t){if(!t)return 0;const r=e.findIndex(n=>$or(n.key,t));return r>=0?r:0}function oin(e,t){if(e.length<=1)return;const r=pir(e,t);if(Sh===r)return;const n=e[r],o=Hl.get(n.key);if((!o||!o.coolingUntil||Date.now()>=o.coolingUntil)&&(Sh=r,o?.coolingUntil)){const s=o.coolingUntil;o.coolingUntil=void 0,o.coolingReason=void 0,by(n.key,s).catch(()=>{}),f.always(`[proxy] home primary account=${n.label} cooling expired, resetting primaryAccountIndex to ${r}`)}}function mir(e){const t=Hl.get(e);return!!t?.coolingUntil&&Date.now()<t.coolingUntil}function sin(e,t,r=Date.now()){let n=sir.get(e);if(!n||r>=n.coolingUntil?(n={coolingUntil:t,retriesClaimed:0},sir.set(e,n)):t>n.coolingUntil&&(n.coolingUntil=t),!(n.retriesClaimed>=kle))return n.retriesClaimed+=1,n.retriesClaimed}function iin(e,t,r=Date.now()){if(t<=r)return 0;if(t-r>dir)return;let n=iir.get(e);!n||r>=n.coolingUntil?(n={coolingUntil:t,nextAdmissionAt:t},iir.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>nin))return n.nextAdmissionAt=o+rin,o-r}async function ain(e){const t=Date.now()+tin;for(;Date.now()<t;){const r=e.filter(i=>!mir(i.key));if(r.length>0)return r;const n=Date.now(),o=e.map(i=>({account:i,state:ll(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=iin(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 zp(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 bA(e,t){try{const r=t.poolAccounts?pnn(t.poolAccounts.map(o=>{const s=Hl.get(o.key);return{...s?.coolingUntil!==void 0?{coolingUntil:s.coolingUntil}:{},...s?.quota?{quota:s.quota}:{}}})):void 0,n=dnn({...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??{},...jin(n)}}catch(r){f.debug(`[proxy] failed to publish limit headers: ${r instanceof Error?r.message:String(r)}`)}}function G2(e,t,r){const n=Math.min(eir,(r&&Oor[r])??eir);return Math.min(Math.max(e,t+tir),t+n)}function Rle(e,t,r,n=e?.unifiedStatus,o=Ay){if(e&&e.weeklyStatus==="rejected"){const a=$i(e.weeklyResetAt,r)??(t>0?r+t:r+Ile);return{reason:"weekly",coolingUntil:G2(a,r,"weekly"),rotateImmediately:!0}}const s=W2(e,o);if(e&&e.sessionStatus==="rejected"&&!s){const a=$i(e.sessionResetAt,r)??(t>0?r+t:r+Ile);return{reason:"session",coolingUntil:G2(a,r,"session"),rotateImmediately:!0}}if(n?.trim().toLowerCase()==="rejected"&&!s){const a=t>0?r+t:r+rir;return{reason:"unified",coolingUntil:G2(a,r,"unified"),rotateImmediately:!0}}const i=t>0?t:Ile;return{reason:"transient",coolingUntil:r+Math.max(tir,Math.min(i,Wsn)),rotateImmediately:!1}}function Mle(e,t){return Math.max(0,Math.round((e-t)/6e4))}function Ple(e,t,r,n=Ay){const o=W2(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+rir,i="unified"),s===void 0)return null;const a=G2(s,r,i);return!e.coolingUntil||a>e.coolingUntil?(e.coolingUntil=a,e.coolingReason=i,f.always(`[proxy] proactively cooling account (${i}) ~${Mle(a,r)}m from success-response quota (status rejected)`),{kind:"cooled",coolingUntil:a,coolingReason:i??"unified"}):null}async function lin(e){try{const[t,r]=await Promise.all([Fae(),nA()]),n=Date.now();for(const o of e){const s=ll(o.key);!s.quota&&t[o.label]&&(s.quota=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 cin=15e3,hir=new Map,H2=null,uin=4;async function fir(e,t,r,n){if(t.ok===!1)return null;const o=ll(e.key),s=Jor(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=Ty(o.quota,s);const i=Ple(o,s,Date.now());return i?.kind==="cooled"?await wd(e.key,i.coolingUntil,i.coolingReason).catch(()=>{}):i?.kind==="cleared"&&await by(e.key,i.coolingUntil).catch(()=>{}),await Sy(e.label,s).catch(()=>{}),s}async function gir(e){const t=await Xrn(e);return t.ok===!1||Jor(t.usage,{now:Date.now(),prior:Hl.get(e.key)?.quota??null})?t:{ok:!1,reason:"parse",error:"usage payload had no recognizable limit windows"}}async function V2(e,t){const r=await wA.run(e,t,gir);r.kind!=="completed"||r.result.ok===!1||await fir(e,r.result,r.startedAt)}async function Dle(e={}){const t=Date.now(),r=await Wor(e.accountAllowlist),n=e.accountFilter?r.filter(c=>c.label===e.accountFilter||c.key===e.accountFilter):r,o=await Fae().catch(()=>({})),s=(c,u,d,m)=>{const h=Hl.get(c.key),g={account:c.label,key:c.key,type:c.type,status:u,quota:d??h?.quota??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:wA.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=hir.get(u.key)??0;if(Date.now()-d<cin){i[c]=s(u,"throttled",null);continue}hir.set(u.key,Date.now());try{const m=await wA.run(u,`manual:${u.key}`,gir,{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 fir(u,h,m.startedAt,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(uin,n.length||1)},()=>l())),{fetchedAt:t,snapshot:!1,results:i,refreshMetrics:wA.getMetrics()}}function Ole(){const e=(process.env.NEUROLINK_PROXY_QUOTA_ROUTING??"").toLowerCase();return e!=="off"&&e!=="false"&&e!=="0"}function Nle(){const e=Number(process.env.NEUROLINK_PROXY_SESSION_SOFT_LIMIT??"");return Number.isFinite(e)&&e>0&&e<=1?e:.97}function TA(){const e=Number(process.env.NEUROLINK_PROXY_SESSION_RESET_TOLERANCE_MS??"");return Number.isInteger(e)&&e>0?e:900*1e3}var Ay="auto";function Lle(e){e!==void 0&&(Ay=e)}function din(){return Ay}function W2(e,t=Ay){return t==="never"?!1:Uor(e)}var pin=4;function K2(e){return e.toLowerCase().replace(/[^a-z0-9]/g,"")}function min(e){const t=K2(e);return t.startsWith("claude")?t.slice(6):t}function hin(e,t,r){if(e.scopeModelId&&K2(E2(e.scopeModelId))===r)return Number.MAX_SAFE_INTEGER;if(!e.scopeModel)return null;const n=min(e.scopeModel);return n.length<pin||!t.includes(n)?null:n.length}function yir(e,t){return t.updatedAt??e.windowsUpdatedAt??e.lastUpdated}function vir(e,t,r=Date.now()){if(!e?.windows?.length||!t)return null;const n=K2(t);if(!n)return null;const o=K2(E2(t));let s=null,i=-1,a=-1;for(const l of e.windows){if(r-yir(e,l)>oir)continue;const c=hin(l,n,o);if(c===null)continue;const u=yir(e,l);(c>i||c===i&&u>a)&&(s=l,i=c,a=u)}return s}function fin(e,t,r=Date.now(),n=Ay){if(!t||e.length===0)return{eligible:e,exhaustion:null};const o=[],s=[];let i;for(const l of e){const c=Hl.get(l.key)?.quota,u=vir(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)&&!W2(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??E2(t),earliestResetMs:a,accounts:s.map(l=>l.label),...i?{overageDisabledReason:i}:{}}}}function J2(e,t,r,n,o,s=Ay){const i=Hl.get(e),a=i?.quota,l=a&&Number.isFinite(a.lastUpdated)?a.lastUpdated:null,c=l===null?null:Math.max(0,t-l),u=wA.getState(e),d=c!==null&&c>oir,m=Y=>Y.trim().toLowerCase(),h=Uor(a),g=[a?.unifiedStatus,a?.sessionStatus,a?.weeklyStatus].filter(Y=>!!Y?.trim()),y=d&&!!a&&!h&&g.some(Y=>m(Y)!=="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),A=k!==void 0,I=T!==void 0,M=_?A?_.sessionUsed??0:0:null,R=_?I?_.weeklyUsed??null:0:null,x=_?A?_.sessionStatus??"unknown":"allowed":null,O=_?I?_.weeklyStatus??"unknown":"allowed":null,N=W2(_,s),P=!N&&(x==="rejected"||x==="throttled"||O==="rejected"||O==="throttled"||_?.unifiedStatus?.trim().toLowerCase()==="rejected"||A&&(M??0)>=1||I&&(R??0)>=1),D=!P&&!N&&A&&(M??0)>=r,L=P||D,$=vir(_,o,t),U=$?$i($.resetsAt,t):void 0,j=U!==void 0,B=$?j?$.used:0:null,z=$?j?$.status??"unknown":"allowed":null,J=!d&&j&&(B??0)>=r;return{usable:!b&&!P&&(z!=="rejected"||N),saturated:L,scopedModel:$?.scopeModel??null,scopedStatus:z,scopedUsed:B,scopedReset:U??Number.POSITIVE_INFINITY,scopedUsedForSort:B??-1,scopedSaturated:J,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:P?"hard":D?"soft":"none",softLimitOverrideReason:N&&A&&(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:N,overageStatus:_?.overageStatus??null,sessionStatus:x,sessionUsed:M,sessionResetBucket:A?Math.floor(k/n):Number.POSITIVE_INFINITY,sessionReset:k??Number.POSITIVE_INFINITY,weeklyStatus:O,weeklyReset:T??Number.POSITIVE_INFINITY,weeklyUsed:R,weeklyUsedForSort:R??-1}}function _ir(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 gin(e,t,r,n,o,s){const i=new Map(e.map(a=>[a.key,J2(a.key,t,n,o,s)]));return{orderedAccounts:[...e].sort((a,l)=>_ir(a,l,i,r)[0]),metricsByKey:i}}function yin(e,t,r,n){for(const u of e){if(u.type!=="oauth")continue;const d=n?.get(u.key)??J2(u.key,Date.now(),r,TA());d.quotaFreshness==="unknown"?V2(u,`startup-unknown:${u.key}`).catch(m=>{f.debug(`[proxy] background quota discovery failed account=${u.label}: ${Td(m)}`)}):d.quotaFreshness==="refresh_due"&&V2(u,`ambiguous:${d.quotaLastUpdated??0}`).catch(m=>{f.debug(`[proxy] ambiguous quota refresh failed account=${u.label}: ${Td(m)}`)})}const o=t[0],s=t[1];if(!o||!s||s.type!=="oauth")return;const i=Hl.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(":");V2(s,c).catch(u=>{f.debug(`[proxy] quota handoff prewarm failed account=${s.label}: ${Td(u)}`)})}function vin(e,t,r,n){!t||t.type!=="oauth"||J2(t.key,Date.now(),n,TA()).quotaFreshness==="fresh"||V2(t,`hard-handoff:${e.key}:${r}:${t.key}`).catch(s=>{f.debug(`[proxy] hard-handoff quota refresh failed account=${t.label}: ${Td(s)}`)})}function _in(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",_=_ir(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 win(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"&&oin(t,n),h){const y=gin(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!==Zsr&&(Sh=pir(c,n),Zsr=c.length),c.length>1&&(m=Sh%c.length,r==="round-robin"&&(Sh=(Sh+1)%c.length),m>0)){const y=c.splice(0,m);c.push(...y)}d=new Map(t.map(y=>[y.key,J2(y.key,u,s,i,a)]))}const g=_in({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 Y2=new Map,bin=300*1e3,Tin=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"]),Ein=["oauth-2025-04-20","claude-code-20250219","fine-grained-tool-streaming-2025-05-14"];function Z2(e){return e.replace(/[^a-zA-Z0-9._@-]/g,"_")}function wir(e){return St(Va(),".neurolink","header-snapshots",`anthropic_${Z2(e)}.json`)}function Sin(e,t){if(t?.headers)for(const[r,n]of Object.entries(t.headers)){const o=r.toLowerCase();typeof n=="string"&&!e[o]&&!z2.has(o)&&o!=="authorization"&&o!=="x-api-key"&&o!=="x-claude-code-session-id"&&(e[o]=n)}}async function Cin(e){try{const t=Z2(e),r=Y2.get(t);if(r&&Date.now()-r.loadedAt<bin)return r.snapshot;const n=wir(e);try{await _P(n)}catch{return null}const o=JSON.parse(await Wr(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:(Y2.set(t,{snapshot:s,loadedAt:Date.now()}),s)}catch{return null}}function kin(e,t){const r={...t??{}};for(const[n,o]of Object.entries(e)){const s=n.toLowerCase();typeof o=="string"&&Tin.has(s)&&!z2.has(s)&&s!=="authorization"&&s!=="x-api-key"&&s!=="x-claude-code-session-id"&&(r[s]=o)}return r}function bir(e){if(!e||typeof e!="object")return;const t=e,r=ext(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 Tir(e,t){return typeof e["x-claude-code-session-id"]=="string"||e["user-agent"]?.startsWith("claude-cli/")||!!t?.metadataUserId||!!t?.billingHeader||!!t?.agentBlock}function xin(e,t){return e?JSON.stringify(e.headers??{})===JSON.stringify(t.headers??{})&&JSON.stringify(e.body??{})===JSON.stringify(t.body??{}):!1}async function Ain(e,t){const r=wir(e);await sl(r,t,384),Y2.set(Z2(e),{snapshot:t,loadedAt:Date.now()})}async function Iin(e,t,r,n){const o=await Cin(e);let s;try{s=JSON.parse(n)}catch{return o}const i=bir(s);if(!Tir(r,i))return o;const a={accountKey:t,capturedAt:new Date().toISOString(),source:"claude-code",headers:kin(r,o?.headers),body:{...o?.body??{},...i??{},...typeof r["x-claude-code-session-id"]=="string"?{sessionId:r["x-claude-code-session-id"]}:{}}};if(xin(o,a))return o;try{await Ain(e,a)}catch(l){f.warn("[proxy] failed to persist Claude snapshot",{accountLabel:e,error:l instanceof Error?l.message:String(l)}),Y2.set(Z2(e),{snapshot:a,loadedAt:Date.now()})}return a}function $le(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 Eir(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 Rin(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:xO(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&&vxt(s,s.system),s.system=[d,i]}}}else{const c={type:"text",text:xO(r?.body?.billingHeader)};s.system=[c,i]}const a=t.substring(0,Math.min(20,t.length)),l=txt(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 Min(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:T2,label:s,token:r,refreshToken:n,expiresAt:o,type:"oauth",persistTarget:{credPath:t}});if(!i)return a();const l=ll(T2);if(l.permanentlyDisabled)return;const c=(await nA())[T2];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 Bp(a(),l,"missing_refresh_token");return}const u={token:r,refreshToken:n,expiresAt:o,label:s},d=await Hor(u);if(!d.success){if(Cy(d)){await Bp(a(),l,"refresh_invalid");return}const m=await eF(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 A2(t,u),await tF(a(),l),f.always("[proxy] refreshed legacy account at startup"),a()}async function Pin(e){const{ctx:t,body:r,route:n,modelRouter:o,tracer:s,requestStartTime:i,logProxyBody:a}=e;s?.setMode("full");const l=Hae(r),c=yA({provider:n.provider,model:n.model},o?.getFallbackChain()??[],r.model,l,o?.isAutoFallbackEnabled?.()??!1);Sir(a,"translated_request",c);const u=c.attempts;if(r.stream)return Qae({ctx:t,format:"claude",requestModel:r.model,parsed:l,attempts:u,tracer:s,requestStartTime:i});try{return await ele({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=Gl(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 Sir(e,t,r){e({phase:"routing_decision",contentType:"application/json",body:{stage:t,attempts:r.attempts}})}async function Din(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))!z2.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"}}),xw("passthrough","passthrough");let m;try{m=await xle("https://api.anthropic.com/v1/messages?beta=true",{method:"POST",headers:u,body:l,signal:AbortSignal.timeout(_A)})}catch(g){const y=g instanceof Error?g.message:String(g);an("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=Gl(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=zw(m.headers,{model:r.model});bA(t,{upstreamHeaders:m.headers,quota:g,source:g?"live":"none",accountType:"passthrough",servedBy:"anthropic",attempt:1})}if(!m.ok){const g=await m.text();an("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 Gl(m.status,g)}}return r.stream&&m.body?Nin({ctx:t,body:r,bodyStr:l,response:m,tracer:o,requestStartTime:s,toolCount:c,upstreamSpan:d,upstreamResponseHeaders:h,logProxyBody:i,logFinalRequest:a}):Lin({ctx:t,body:r,bodyStr:l,response:m,tracer:o,requestStartTime:s,toolCount:c,upstreamSpan:d,upstreamResponseHeaders:h,logProxyBody:i,logFinalRequest:a})}function Oin(e){const t=e.getReader(),r=Ysr();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 Nin(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}=Esr(),h=n.body;if(!h)throw an("passthrough","passthrough",502),new Error("Expected passthrough stream response body");const g=Oin(h);let y=g.stream,v=!1;const _=(T,k,A,I)=>v?!1:(v=!0,k==="stream_error"&&an("passthrough","passthrough",T),c(T,"passthrough","passthrough",k,A,I),!0);if(o)try{const{stream:T,telemetry:k}=F2({captureRawText:!0});y=y.pipeThrough(T);const A=o,I=i,M=n,R=r.length;Promise.all([k,m,g.outcome]).then(([x,O,N])=>{const P=U2(N,x.streamErrorMessage),D=Ch(P);A.setUsage({inputTokens:x.usage.inputTokens,outputTokens:x.usage.outputTokens,cacheCreationTokens:x.usage.cacheCreationInputTokens,cacheReadTokens:x.usage.cacheReadInputTokens}),A.logStreamEvents(x.events),A.setResponseInfo(Eir(x));const L=parseFloat(M.headers.get("anthropic-ratelimit-unified-5h-utilization")??""),$=parseFloat(M.headers.get("anthropic-ratelimit-unified-7d-utilization")??""),U={inputTokens:x.usage.inputTokens,outputTokens:x.usage.outputTokens,cacheCreationTokens:x.usage.cacheCreationInputTokens,cacheReadTokens:x.usage.cacheReadInputTokens};isNaN(L)||(U.rateLimitAfter5h=L),isNaN($)||(U.rateLimitAfter7d=$),(!isNaN(L)||!isNaN($))&&A.setUsage(U),A.logUpstreamResponseBody(x.rawText??""),A.recordMetrics(),A.recordBodySizes(R,x.totalBytesReceived),I?.end(),D&&A.setError(D.errorType,D.message),A.end(D?.status??n.status,Date.now()-s),_(D?.status??n.status,D?.errorType,D?.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:200,durationMs:Date.now()-s}),l({phase:"client_response",headers:u,body:O.text,bodySize:O.totalBytes,contentType:u["content-type"]??"text/event-stream",account:"passthrough",accountType:"passthrough",attempt:1,responseStatus:200,durationMs:Date.now()-s})}).catch(x=>{if(v)return;const O=x instanceof Error?x.message:String(x);A.setError("stream_telemetry_error",O),I?.end(),A.end(500,Date.now()-s),_(500,"stream_telemetry_error",O)})}catch{g.outcome.then(T=>{const k=Ch(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}=F2({captureRawText:!0});y=y.pipeThrough(T),Promise.all([k,m,g.outcome]).then(([A,I,M])=>{const R=U2(M,A.streamErrorMessage),x=Ch(R);_(x?.status??n.status,x?.errorType,x?.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: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(A=>{v||_(500,"stream_telemetry_error",A instanceof Error?A.message:String(A))})}catch{g.outcome.then(T=>{const k=Ch(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 Lin(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($le(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 $in(e){const t=Gw();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=ll(d.key).quota,h=$i(m?.sessionResetAt,r)??null,g=$i(m?.weeklyResetAt,r)??null,y=await kie(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 wie(t.grantId);if(!o)return{accounts:e.accounts};const s=await xie(t.grantId,yle(o.gates,n).inScope),i=vle(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=_le(i.excluded),u=Jw(c,{status:rsn(c),grant:o,retryAfterSeconds:kir(n,r)});return e.ctx.responseHeaders={...e.ctx.responseHeaders??{},...u.headers},f.always(`[proxy] share ${t.peerLabel} withheld: ${c} (${i.excluded.length} accounts)`),{accounts:[],refusal:{response:e.buildLoggedClaudeError(u.status,u.body.error.message,u.body.error.type),status:u.status,message:u.body.error.message}}}async function Fin(e){const t=[],r=[];for(const n of e){const o=await Hon(n.key);if(!o){t.push(n);continue}if(!Oon(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 Uin(e,t){const r=[],n=[],o=Date.now();for(const s of e){const i=await gle(s.key);if(!i){r.push(s);continue}const a=i.lease.gates;if(!osn(a.models,t)){f.always(`[proxy] leased account=${s.label} does not cover model ${fo(t??"unknown")}`),n.push({label:s.label,reason:"model_not_allowed"});continue}if(a.schedule&&!nsn(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=ll(s.key).quota,c=$i(l?.sessionResetAt,o)??null,u=$i(l?.weeklyResetAt,o)??null,d=await kie(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 xie(i.grantId,[m]),{accounts:g,...y}=a,v=vle(Bin(i,y),[m],o,h);if(v.allowed.length===0){const _=_le(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 Bin(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 zin(e,t,r){const n=Date.now(),o=i=>{CXr({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=Gw();if(s){o(s.grantId);return}gle(e).then(i=>{i&&o(i.grantId)}).catch(()=>{})}function Fle(e,t,r){const n=Cie({inputTokens:r.inputTokens??0,outputTokens:r.outputTokens??0,...r.cacheCreationTokens!==void 0?{cacheCreationTokens:r.cacheCreationTokens}:{},...r.cacheReadTokens!==void 0?{cacheReadTokens:r.cacheReadTokens}:{}},t);Von(e,n).catch(()=>{})}function Cir(e,t){if(!t||typeof t!="object")return;const r=t.usage;if(!r)return;const n=Jin(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};Ule(e.key,n,o),Fle(e.label,n,o)}function Ule(e,t,r){const n=Gw();n&&kXr({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 jin(e){if(!Gw())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 qin(e,t){const r=e.provisionedAccount;if(!r)return{paused:!1,detail:"no provisioned account recorded"};const n=Hl.get(`anthropic:${r}`),o=XXt(r),{verdict:s,shouldPause:i}=await Esn({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 uXr(e.id,"paused"),{paused:!0,detail:s.drifted?s.detail:"repeated unexplained usage"}):{paused:!1,detail:s.drifted?s.detail:"consistent"}}async function Gin(e,t){await uQt(e.id,t)}function Hin(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 Vin=1,Win=["live","complete","handshake","limits"];async function Kin(e,t){const r=Date.now(),n=await Wor(t),o=await Promise.all(n.map(async c=>{const u=ll(c.key).quota,d=$i(u?.sessionResetAt,r)??null,m=$i(u?.weeklyResetAt,r)??null,h=await kie(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=yle(e.gates,o).inScope,i=await xie(e.id,s),a=vle(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(TXr(e)))}:{},servable:a.allowed.length>0,...a.allowed.length===0&&a.excluded.length>0?{withheldReason:_le(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=kir(o,r);return c===void 0?{}:{retryAfterSeconds:c}})():{}}}function Iy(e){return!e.ok}async function Ry(e){const t=usn(e);if(!t)return{ok:!1,body:Jw("missing_token",{status:401}).body};const r=await pXr(t);return r?{ok:!0,grant:r}:{ok:!1,body:Jw("unknown_token",{status:401}).body}}function Jin(e){if(!e||typeof e!="object")return;const t=e.model;return typeof t=="string"?t:void 0}function kir(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 Yin(e){const{ctx:t,body:r,tracer:n,requestStartTime:o,accountStrategy:s,primaryAccountKey:i,accountAllowlist:a,quotaRoutingEnabled:l=Ole(),sessionSoftLimit:c=Nle(),sessionResetToleranceMs:u=TA(),buildLoggedClaudeError:d,setRoutingDecision:m}=e,h=await Promise.resolve().then(()=>(gn(),_l)),g=await Promise.resolve().then(()=>(ic(),MT)),y=[],v=`${g.homedir()}/.neurolink/anthropic-credentials.json`,{tokenStore:_}=await Promise.resolve().then(()=>(Nx(),lie)),b=await nA();uir||(await _.pruneExpired(),uir=!0);const T=await _.listByPrefix("anthropic:"),k=[];let A=0,I=0;for(const ce of T){if(!Nae(ce,a)){f.debug(`[proxy] skipping account=${ce} (not in account allowlist)`);continue}if(await _.isDisabled(ce)){const me=ll(ce),$e=await _.getDisabledReason(ce);if($e==="refresh_failed")await _.markEnabled(ce),f.always(`[proxy] account=${ce.split(":")[1]??ce} re-enabled for legacy refresh failure recheck`),me.permanentlyDisabled=!1,me.consecutiveRefreshFailures=0;else{f.debug(`[proxy] skipping disabled account=${ce.split(":")[1]??ce}`),me.permanentlyDisabled=!0,$e==="entitlement_blocked"&&k.push(ce.split(":")[1]??ce),A+=1;continue}}const re=await _.loadTokens(ce);if(!re){I+=1;continue}let G=re.accessToken,K=re.refreshToken,Ce=re.expiresAt;const be=ce.split(":")[1]??ce,ge=re.tokenType==="Bearer"?"oauth":"api_key",H=ll(ce),se=b[ce];se?.coolingUntil>Date.now()&&(!H.coolingUntil||se.coolingUntil>H.coolingUntil)&&(H.coolingUntil=se.coolingUntil,H.coolingReason=se.reason);const ye=()=>{y.push({key:ce,label:be,token:G,refreshToken:K,expiresAt:Ce,type:ge,persistTarget:{providerKey:ce}})};if(Ce?Ce<Date.now():!1){if(H.permanentlyDisabled)continue;if(H.coolingReason==="auth"&&H.coolingUntil&&H.coolingUntil>Date.now()){ye();continue}if(!K){f.always(`[proxy] skipping account=${be} (expired, no refresh token)`),await Bp({key:ce,label:be,token:G,type:"oauth"},H,"missing_refresh_token");continue}const me={token:G,refreshToken:K,expiresAt:Ce,label:be},$e=await x2(me,{providerKey:ce});if(!$e.success){const Se={key:ce,label:be,token:G,type:"oauth"};if(Cy($e))f.always(`[proxy] skipping account=${be} (refresh token rejected: ${$e.error?.slice(0,200)??"unknown"})`),await Bp(Se,H,"refresh_invalid");else{const ne=await eF(Se,H);f.always(`[proxy] account=${be} refresh temporarily unavailable (${$e.status??"network"}); cooling until ${new Date(ne).toISOString()} and rotating`),ye()}continue}G=me.token,K=me.refreshToken,Ce=me.expiresAt,await _.saveTokens(ce,{accessToken:G,refreshToken:K,expiresAt:Ce??Date.now()+36e5,tokenType:"Bearer"}),f.always(`[proxy] refreshed expired account=${ce.split(":")[1]??ce} at startup`),await tF({key:ce},H)}ye()}if(y.length===0&&For(T.length,T2,a))try{const ce=JSON.parse(h.readFileSync(v,"utf8")),re=await Min(ce,v);re&&y.push(re)}catch{}if(process.env.ANTHROPIC_API_KEY&&y.length===0&&For(T.length,Lor,a)&&y.push({key:Lor,label:"env",token:process.env.ANTHROPIC_API_KEY,type:"api_key"}),y.length===0){if(k.length>0&&k.length===A&&I===0){const re=Iir({status:403,accounts:k,message:"OAuth authentication is not allowed for this organization.",errorCode:"oauth_not_allowed_for_organization"});return n?.setError("permission_error",re),n?.end(403,Date.now()-o),{response:d(403,re,"permission_error")}}const ce=a?"No allowed Anthropic credentials are currently available":T.length>0?"Configured Anthropic accounts are disabled or unavailable":"No Anthropic credentials found";return n?.setError("authentication_error",ce),n?.end(401,Date.now()-o),{response:d(401,ce)}}for(const ce of y)wan(ce);await lin(y);const M=y.filter(ce=>!ll(ce.key).permanentlyDisabled),R=await Fin(M),x=await Uin(R.accounts,typeof r.model=="string"?r.model:void 0),O={accounts:x.accounts,withheld:[...R.withheld,...x.withheld]},N=O.accounts;if(N.length===0&&O.withheld.length>0){const ce=O.withheld.map(K=>`${K.label} (${K.reason})`).join(", "),G=O.withheld.every(K=>K.reason==="model_not_allowed")?`Borrowed account(s) do not cover the requested model: ${ce}. Ask the lender to widen the share, or use a model it allows.`:`Borrowed account(s) are no longer covered by a lease: ${ce}. Run 'neurolink proxy peer sync' to check in with the lender, or ask them to resume the share.`;return n?.setError("permission_error",G),n?.end(403,Date.now()-o),{response:d(403,G,"permission_error")}}const P=await $in({accounts:N,ctx:t,buildLoggedClaudeError:d});if(P.refusal)return n?.setError("rate_limit_error",P.refusal.message),n?.end(P.refusal.status,Date.now()-o),{response:P.refusal.response};const D=P.accounts;if(D.length===0){const ce=rF(y.map(re=>re.label));return n?.setError("authentication_error",ce),n?.end(401,Date.now()-o),{response:d(401,ce)}}const{orderedAccounts:L,metricsByKey:$}=win({enabledAccounts:D,accountStrategy:s,primaryAccountKey:i,quotaRoutingEnabled:l,sessionSoftLimit:c,sessionResetToleranceMs:u,requestedModel:typeof r.model=="string"?r.model:void 0,setRoutingDecision:m});s==="fill-first"&&l&&D.length>1&&yin(D,L,c,$);const U=Can(r),j=JSON.stringify(U),B=Date.now(),z=Array.isArray(r.tools)?r.tools.length:0,J="https://api.anthropic.com/v1/messages?beta=true",Y=t.headers??{},ie=bir(r);return{accounts:y,enabledAccounts:D,orderedAccounts:L,bodyStr:j,requestStart:B,toolCount:z,url:J,clientHeaders:Y,isClaudeClientRequest:Tir(Y,ie)}}async function Zin(e){const{ctx:t,body:r,tracer:n,requestStartTime:o,logProxyBody:s,logFinalRequest:i,options:a,providerLabel:l,idleTimeoutMs:c=Vsn}=e,u=new AbortController;let d;try{d=await zt(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:A}=await zt(b.next(),c,`Fallback ${l} stream timed out after ${c}ms of inactivity`);if(A)return T;const I=Yae(k);I&&(T+=I,_?.(I))}}catch(k){throw u.abort(k),b.return?.().catch(()=>{}),k}};if(r.stream){const _=new nsr(r.model,0),b=[];for(const x of _.start())b.push(x);const T=await m(x=>{for(const O of _.pushDelta(x))b.push(O)}),k=d.toolCalls??[];if(!D2(T,k))throw new Error(`Translated provider ${l} returned no content or tool calls`);if(k.length)for(const x of k){const O=x.toolName??x.name??"unknown";for(const N of _.pushToolUse(Gae(),O,vsr(x)))b.push(N)}const A=d.finishReason??"end_turn",I=Ww(d.usage);for(const x of _.finish(I.output,A))b.push(x);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 x of b)yield x}return R()}const h=await m();if(!D2(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?Ww(d.usage):void 0,toolCalls:d.toolCalls};n?.end(200,Date.now()-o);const y=rsr(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 xir(e){let t;for(let r=0;r<=Cle;r+=1)try{return await Zin(e)}catch(n){if(t=n,!jle(n)||r===Cle)throw n;const o=Sle[r]??250;f.always(`[proxy] retrying fallback=${e.providerLabel} after transient network error (${r+1}/${Cle}) in ${o}ms: ${SA(Td(n))}`),await zp(o)}throw t}async function Air(e){if(Gw())return null;const t=await xon();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 Xon({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}async function Xin(e){const{ctx:t,body:r,parsedFallbackRequest:n,modelRouter:o,tracer:s,requestStartTime:i,logProxyBody:a,logFinalRequest:l}=e,c=o?.getFallbackChain()??[],u=yA({provider:"anthropic",model:r.model},c,r.model,n);a({phase:"routing_decision",contentType:"application/json",body:{stage:"anthropic_fallback",attempts:u.attempts.slice(1)}}),s?.setFallbackInfo({triggered:!0,attemptCount:u.attempts.slice(1).length,reason:"all_anthropic_accounts_exhausted"});let d;for(const m of u.attempts.slice(1)){if(!m.provider||!m.model)continue;const h=await U_.checkFallbackProviderAvailability(m.provider,m.model);if(!h.available){const y=h.reason??"provider unavailable";f.always(`[proxy] fallback ${m.provider}/${m.model} health-check failed (${y}), skipping`),aA({provider:m.provider,model:m.model,status:"failure",errorMessage:`[unavailable] ${y}`,durationMs:0}),d=`[${m.provider}/${m.model}] unavailable: ${y}`;continue}const g=Date.now();try{f.always(`[proxy] fallback \u2192 ${m.provider}/${m.model}`);const y=qir(n,{provider:m.provider,model:m.model}),v=await xir({ctx:t,body:r,tracer:s,requestStartTime:i,logProxyBody:a,logFinalRequest:l,options:y,providerLabel:m.provider});return aA({provider:m.provider,model:m.model,status:"success",durationMs:Date.now()-g}),s?.setFallbackInfo({triggered:!0,provider:m.provider,model:m.model,attemptCount:u.attempts.slice(1).length,reason:"fallback_success"}),bA(t,{quota:null,source:"none",servedBy:m.provider}),{response:v}}catch(y){const v=SA(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 ${m.provider}/${m.model} failed [${_}]: ${SA(Td(y))}`),aA({provider:m.provider,model:m.model,status:"failure",errorMessage:`[${_}] ${v}`,durationMs:Date.now()-g}),d=`[${m.provider}/${m.model}] ${SA(Td(y))}`}}return{response:null,lastErrorMessage:d}}async function Qin(e){const{ctx:t,body:r,tracer:n,requestStartTime:o,logProxyBody:s,logFinalRequest:i}=e,a=Date.now();try{const l=Hae(r),c=yA({provider:"anthropic",model:r.model},[],r.model,l,!0);if(Sir(s,"auto_fallback",c),!c.attempts.find(h=>h.label==="auto-provider"))return{response:null};f.always("[proxy] fallback \u2192 auto-provider");const d=qir(l),m=await xir({ctx:t,body:r,tracer:n,requestStartTime:o,logProxyBody:s,logFinalRequest:i,options:d,providerLabel:"auto-provider"});return aA({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"}),bA(t,{quota:null,source:"none",servedBy:"auto-provider"}),{response:m}}catch(l){const c=SA(Td(l));return f.always(`[proxy] fallback auto-provider failed: ${c}`),aA({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 ean(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 Iir(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: ${ean(e.accounts)}. Upstream: "${e.message}". Ask an organization admin to re-enable Claude Code OAuth access, then run: neurolink auth enable anthropic:<account>.`}function tan(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 ran(e){for(const t of e){const r=Hl.get(t.key)?.quota;if(r?.overageDisabledReason&&r.overageStatus?.trim().toLowerCase()!=="allowed")return r.overageDisabledReason}}function Rir(e){return e?` Paid extra usage is unavailable for this organization (${e}), so there is no additional capacity before the window resets.`:""}function nan(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()}.`+Rir(e.overageDisabledReason)}function oan(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=Iir(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){t?.setError("invalid_request_error",Or(s.body)),t?.end(s.status,Date.now()-r);try{const D=JSON.parse(s.body);return b(s.status,"","final","invalid_request_error",Or(s.body)),_({phase:"client_response",headers:{"content-type":s.contentType??"application/json"},body:s.body,bodySize:Buffer.byteLength(s.body,"utf8"),contentType:s.contentType??"application/json",responseStatus:s.status,durationMs:Date.now()-r}),D}catch{return v(s.status,Or(s.body),"invalid_request_error")}}if((l||c)&&!u){const D=g?` Fallback also failed: ${g}`:"",L=h==="shared_provider_transport"?"shared Anthropic network":h==="connection_transport"?"Anthropic connection":null,$=`${L?`${L} 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",$.slice(0,500)),t?.end(502,Date.now()-r),v(502,$,g?"fallback_exhausted":"transient_error",{...m?{errorCode:m}:{},...h?{transportScope:h}:{}})}const k=(D,L)=>{const $=Gl(429,D,"overloaded_error");t?.setError("rate_limit_error",D),t?.end(429,Date.now()-r),b(429,"","final","rate_limit_error",D);const U=JSON.stringify($),j={"content-type":"application/json","retry-after":String(L)};return _({phase:"client_response",headers:j,body:U,bodySize:Buffer.byteLength(U,"utf8"),contentType:"application/json",responseStatus:429,durationMs:Date.now()-r}),new Response(U,{status:429,headers:j})};if(a){const D=nan(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}`:"",L=`All Anthropic accounts failed. Last error: ${d instanceof Error?d.message:String(d??"unknown")}.${D}`;return t?.setError("all_accounts_failed",L.slice(0,500)),t?.end(502,Date.now()-r),v(502,L,g?"fallback_exhausted":"all_accounts_failed")}const A=Date.now(),I=y.map(D=>ll(D.key)).filter(D=>D.coolingUntil&&D.coolingUntil>A&&D.coolingReason!=="auth"),M=Math.min(...I.map(D=>D.coolingUntil??Number.POSITIVE_INFINITY)),R=y.length>0&&I.length===y.length,x=R?Math.max(1,Math.ceil((M-A)/1e3)):1,O=tan(I),N=Rir(ran(y)),P=R?`All ${y.length} Anthropic accounts are cooling after the ${O} was exhausted. Earliest retry at ${new Date(M).toISOString()}.${N}`:`All ${y.length} accounts rate-limited after per-account retries.${N}`;return f.always(`[proxy] all accounts rate-limited, retry in ${x}s`),k(P,x)}async function Mir(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 _=zw(s.headers,{model:r.model});if(_){zin(n.key,o.quota,_),o.quota=Ty(o.quota,_);const T=Ple(o,_,Date.now());T?.kind==="cooled"?wd(n.key,T.coolingUntil,T.coolingReason).catch(()=>{}):T?.kind==="cleared"&&by(n.key,T.coolingUntil).catch(()=>{}),Sy(n.label,_).catch(()=>{})}const b={};return s.headers.forEach((T,k)=>{b[k]=T}),i?.logUpstreamResponseHeaders(b),bA(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?san({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}):aan({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 san(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){an(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=Gl(502,"No response body from upstream"),x=JSON.stringify(R);return g({phase:"client_response",headers:{"content-type":"application/json"},body:x,bodySize:Buffer.byteLength(x,"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 jsn(_);if(b.kind==="transport_error"){const R=Td(b.error),x=Buffer.concat(b.chunks.map(O=>Buffer.from(O))).toString("utf8");return f.always(`[proxy] stream failed before first chunk account=${n.label}: ${R}; returning terminal error to avoid replaying an ambiguous request`),an(n.label,n.type,502),h(502,"stream_error",R,{retryable:!1}),m?.end(),g({phase:"upstream_response",headers:i,body:x,bodySize:Buffer.byteLength(x,"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:Dir({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`),an(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"),x=b.errorType==="rate_limit_error",O=x?429:502,N=zw(i,{model:r.model}),P=Date.now();if(x){const D=Rle(N,B2(i["retry-after"]??null),P,S2(i));o.quota=N?Ty(o.quota,N):o.quota;const L=D.reason==="transient"?"transient":"quota";(!o.coolingUntil||D.coolingUntil>o.coolingUntil)&&(o.coolingUntil=D.coolingUntil,o.coolingReason=D.reason,await wd(n.key,D.coolingUntil,D.reason).catch(()=>{})),an(n.label,n.type,429,L),h(429,"rate_limit_error",b.message,{retryable:!0,rateLimitKind:L,cooldownReason:D.reason})}else an(n.label,n.type,O),h(O,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,x?"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:O,upstreamErrorType:b.errorType}}),{retryNextAccount:!0,failure:{message:b.message,rateLimit:x,...b.errorType==="overloaded_error"?{retryDelayMs:Uir(u)}:{}}}}h(s.status,void 0,void 0,{attemptDurationMs:Date.now()-c});const T=Ysr();let k=!1;const A=new ReadableStream({start(R){for(const x of b.chunks)R.enqueue(x)},async pull(R){if(!k)try{const{done:x,value:O}=await _.read();if(k)return;if(x){k=!0,T.complete(),R.close();return}R.enqueue(O)}catch(x){const O=Td(x);if(f.always(`[proxy] mid-stream error account=${n.label}: ${O}`),T.fail(O),!k){k=!0;const N=`event: error
|
|
2354
|
+
`);for(const b of _)ksr(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}}Kr(),ii(),rr(),Mc(),q(),Bl();var won="proxy-peers.json",bon=1e3,Ton={exhausted:9e5,withheld:6e5,paused:3e5,revoked:864e5,expired:864e5,unreachable:6e4,upstream_error:12e4},Eon=null,Up={},lA=0,cA=-1,uA=!1,xsr=new ol;function ple(){return Eon??St(Va(),".neurolink",won)}function Son(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 Con(e){return e?.code==="ENOENT"}async function mle(e={}){const t=Date.now();if(!e.force&&uA&&t-lA<bon)return;const r=ple();let n;try{n=(await qs(r)).mtimeMs}catch(o){if(!Con(o))throw o;Up={},cA=-1,lA=t,uA=!0;return}if(!e.force&&uA&&n===cA){lA=t;return}try{const o=JSON.parse(await Wr(r,"utf8"));Up=Object.fromEntries(Object.entries(o?.peers??{}).filter(s=>Son(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)}`),Up={}}cA=n,lA=t,uA=!0}async function Asr(){const e={schemaVersion:1,peers:Up};await sl(ple(),e);try{cA=(await qs(ple())).mtimeMs}catch{cA=-1}lA=Date.now(),uA=!0}function Isr(e){return e.trim().toLowerCase()}async function kon(){return await mle(),Object.values(Up).sort((e,t)=>e.priority-t.priority||e.createdAt-t.createdAt)}async function xon(e=Date.now()){return(await kon()).filter(r=>r.enabled&&!(r.cooldownUntil&&r.cooldownUntil>e))}function Aon(e){return Ton[e]}var Ion=6048e5;async function hle(e,t,r){await xsr.runExclusive(async()=>{await mle({force:!0});const n=Isr(e),o=Up[n];if(!o)return;const s=(r??0)*1e3,i=Date.now()+Math.min(Ion,Math.max(Aon(t),Number.isFinite(s)?s:0));Up[n]={...o,cooldownUntil:i,cooldownReason:t,updatedAt:Date.now()},await Asr()})}async function Ron(e,t){await xsr.runExclusive(async()=>{await mle({force:!0});const r=Isr(e),n=Up[r];n&&(Up[r]={...n,cooldownUntil:0,lastUsedAt:Date.now(),updatedAt:Date.now(),...t?{lastObservation:t}:{}},await Asr())})}Kr(),ii(),rr(),Mc(),Q$();var Mon=6048e5,Pon=9e5,Don=864e5;function Oon(e){return!e.usable}function Rsr(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 Msr(e,t){return gie(e,t)}function Psr(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??Mon,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??Pon,offlineGraceMs:r?.offlineGraceMs??Don,gates:e.gates,entitlementSnapshot:e.entitlement.ledger==="coins"?e.entitlement.coins??0:"unlimited"};return{...i,signature:Msr(Rsr(i),n)}}function Non(e,t){const{signature:r,...n}=e;return aQt(Msr(Rsr(n),t),r)}function Lon(e){const t=e.now??Date.now();if(!Non(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 $on(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:Psr(e.grant,t),lenderUrl:(e.lenderUrl??"").replace(/\/+$/,"")}}Bl();var Fon="proxy-resident-grants.json",Uon=1e3,Bon=null,ky={},dA=0,pA=-1,mA=!1,zon=new ol;function fle(){return Bon??St(Va(),".neurolink",Fon)}function jon(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 qon(e){return e?.code==="ENOENT"}async function Dsr(e={}){const t=Date.now();if(!e.force&&mA&&t-dA<Uon)return;const r=fle();let n;try{n=(await qs(r)).mtimeMs}catch(o){if(!qon(o))throw o;ky={},pA=-1,dA=t,mA=!0;return}if(!e.force&&mA&&n===pA){dA=t;return}try{const o=JSON.parse(await Wr(r,"utf8"));ky=Object.fromEntries(Object.entries(o?.grants??{}).filter(s=>jon(s[1])))}catch(o){if(e.force)throw o;ky={}}pA=n,dA=t,mA=!0}async function Gon(){const e={schemaVersion:1,grants:ky};await sl(fle(),e);try{pA=(await qs(fle())).mtimeMs}catch{pA=-1}dA=Date.now(),mA=!0}function Osr(e){return e.toLowerCase()}async function gle(e){await Dsr();const t=e.toLowerCase(),r=t.includes(":")?t.slice(t.indexOf(":")+1):t;return ky[Osr(r)]}async function Hon(e,t=Date.now()){const r=await gle(e);if(r)return Lon({lease:r.lease,secret:r.leaseSecret,...r.lastHeartbeatAt!==void 0?{lastHeartbeatAt:r.lastHeartbeatAt}:{},now:t})}async function Von(e,t){await zon.runExclusive(async()=>{await Dsr({force:!0});const r=Osr(e),n=ky[r];n&&(ky[r]={...n,unreportedCoins:(n.unreportedCoins??0)+t,unreportedRequests:(n.unreportedRequests??0)+1},await Gon())})}q();var Won=15e3,Kon=12e4;function Jon(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 Nsr(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 Yon(e){const t=Nsr(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 Zon(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()},Kon),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 Xon(e){const{peer:t,body:r,stream:n}=e,o=new AbortController,s=setTimeout(()=>o.abort(),Won);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 Ron(t.name,Yon(i)).catch(u=>{f.debug(`[proxy] could not record success for peer=${t.name}: ${u instanceof Error?u.message:String(u)}`)}),{ok:!0,response:Zon(i,t,o),peer:t};const a=i.headers.get("x-neurolink-grant-reason"),l=Jon(a),c=Nsr(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)}}qx();var Qon=36e5,esn={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 tsn(e){return esn[e]}function rsn(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 nsn(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 osn(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 Lsr(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 $sr(e,t,r){const n=e.spillover;if(!n)return!1;const o=n.beforeResetHours*Qon,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 yle(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 vle(e,t,r,n){const o=e.gates,{inScope:s,outOfScope:i}=yle(o,t),a=s.some(m=>$sr(o,m,r)),l=Lsr(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=$sr(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=Lsr(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 _le(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 ssn="x-neurolink-share-token",isn="x-neurolink-grant-status",asn="x-neurolink-grant-reason",lsn="x-neurolink-grant-remaining-coins",csn="x-neurolink-grant-peer";function usn(e){const t=e[ssn];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 cXr(o)?o:void 0}function dsn(e){return e===401?"authentication_error":e===403?"permission_error":"rate_limit_error"}function psn(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 Jw(e,t){const{status:r,grant:n,retryAfterSeconds:o}=t,s={[isn]:psn(e,n),[asn]:e};return n&&(s[csn]=n.peerLabel,n.entitlement.ledger==="coins"&&(s[lsn]=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:dsn(r),message:t.message??tsn(e)}}}}qx(),Kr(),ii(),rr(),Mc(),Bl();var msn="proxy-share-audit.json",hsn=2,fsn=3,gsn=1e3,ysn=null,Yw={},hA=0,fA=-1,gA=!1,vsn=new ol;function wle(){return ysn??St(Va(),".neurolink",msn)}function _sn(e){return e?.code==="ENOENT"}async function wsn(e={}){const t=Date.now();if(!e.force&&gA&&t-hA<gsn)return;const r=wle();let n;try{n=(await qs(r)).mtimeMs}catch(o){if(!_sn(o))throw o;Yw={},fA=-1,hA=t,gA=!0;return}if(!e.force&&gA&&n===fA){hA=t;return}try{Yw=JSON.parse(await Wr(r,"utf8"))?.records??{}}catch(o){if(e.force)throw o;Yw={}}fA=n,hA=t,gA=!0}async function bsn(){const e={schemaVersion:1,records:Yw};await sl(wle(),e);try{fA=(await qs(wle())).mtimeMs}catch{fA=-1}hA=Date.now(),gA=!0}function Fsr(e,t){return e===null||t===null?0:Math.max(0,(t-e)*100)}function Tsn(e,t,r=hsn){if(!e)return{drifted:!1,reason:"no_baseline"};if(t.lenderRequests>0)return{drifted:!1,reason:"attributable"};const n=Fsr(e.sessionUsed,t.sessionUsed),o=Fsr(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 Esn(e){const t=e.streakLimit??fsn;return vsn.runExclusive(async()=>{await wsn({force:!0});const r=Yw[e.grantId],n=e.lenderRequestsTotal===void 0?e.observation:{...e.observation,lenderRequests:Math.max(0,e.lenderRequestsTotal-(r?.lenderRequestsTotal??0))},o=Tsn(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),Yw[e.grantId]=i,await bsn(),{verdict:o,shouldPause:a}})}Vo(),Kr(),ii(),rr(),Mc(),Bl();var Ssn="proxy-share-provisioning.json",Csn=9e5,ksn=/^[A-Za-z0-9_-]{43}$/,xsn=/^[A-Za-z0-9_-]{16,128}$/,Asn=null,Zw={},Usr=!1,Bsr=new ol;function zsr(){return Asn??St(Va(),".neurolink",Ssn)}function Isn(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 jsr(e={}){if(!(Usr&&!e.force)){try{const t=JSON.parse(await Wr(zsr(),"utf8"));Zw=Object.fromEntries(Object.entries(t?.requests??{}).filter(r=>Isn(r[1])))}catch{Zw={}}Usr=!0}}async function qsr(){const e={schemaVersion:1,requests:Zw};await sl(zsr(),e)}function Rsn(e,t=Date.now()){return e.status!=="consumed"&&e.expiresAt>t}async function Msn(e){if(!ksn.test(e.codeChallenge))return{ok:!1,reason:"code_challenge must be a base64url S256 digest"};if(!xsn.test(e.state))return{ok:!1,reason:"state must be 16-128 base64url characters"};const t=e.now??Date.now();return Bsr.runExclusive(async()=>{await jsr({force:!0});const r={schemaVersion:1,grantId:e.grantId,codeChallenge:e.codeChallenge,challengeMethod:"S256",state:e.state,requestedAt:t,expiresAt:t+Csn,status:"pending"};return Zw[e.grantId]=r,await qsr(),{ok:!0,request:r}})}async function Psn(e,t=Date.now()){return Bsr.runExclusive(async()=>{await jsr({force:!0});const r=Zw[e];if(!r||!Rsn(r,t))return{status:"none"};if(r.status!=="authorized"||!r.code)return{status:"pending"};const{code:n,...o}=r;return Zw[e]={...o,status:"consumed",claimedAt:t},await qsr(),{status:"ready",code:r.code,state:r.state}})}bQt(),Vo(),Kr(),ii(),rr(),Mc(),qx(),Q$();var Dsn="proxy-share-notes.json",Gsr="nln",Osn=null,Xw={},Hsr=!1,Nsn=new ol;function Vsr(){return Osn??St(Va(),".neurolink",Dsn)}async function Wsr(e={}){if(!(Hsr&&!e.force)){try{Xw=JSON.parse(await Wr(Vsr(),"utf8"))?.notes??{}}catch{Xw={}}Hsr=!0}}async function Lsn(){const{writeJsonSnapshotAtomically:e}=await Promise.resolve().then(()=>(Bl(),aie)),t={schemaVersion:1,notes:Xw};await e(Vsr(),t)}function $sn(e){const t=e.trim();if(t.startsWith(`${Gsr}_`))try{const r=JSON.parse(Buffer.from(t.slice(Gsr.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 Fsn(e,t,r=Date.now()){const{signature:n,...o}=e;if(!t||!X$(o,n,t))return{status:"forged",coins:0};await Wsr({force:!0});const s=Xw[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 Usn(e){const t=e.now??Date.now(),{signature:r,...n}=e.note;if(!e.secret||!X$(n,r,e.secret))return{ok:!1,status:"forged"};const o=await Nsn.runExclusive(async()=>{await Wsr({force:!0});const i=Xw[e.note.noteId];return i?i.redeemedAt!==void 0?{status:"spent",coins:i.coins}:i.notAfter<=t?{status:"expired",coins:i.coins}:(Xw[i.noteId]={...i,redeemedAt:t,redeemedByGrant:e.grantId},await Lsn(),{status:"valid",coins:i.coins}):{status:"unknown",coins:0}});if(o.status!=="valid")return{ok:!1,status:o.status};const s=await dQt(e.grantId,o.coins);return{ok:!0,coins:o.coins,balance:s}}Q$(),DQt();var Bsn=64*1024,zsn=32;function Ksr(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 Jsr(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 jsn(e){const t=new TextDecoder,r=[];let n="",o=0;for(;o<Bsn&&r.length<zsn;){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}=$2(n),l=a.find(Jsr);return l?{kind:"sse_error",chunks:r,...Ksr(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=$2(n);n=i.remainder;for(const a of i.events){if(Jsr(a))return{kind:"sse_error",chunks:r,...Ksr(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 Ysr(){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 U2(e,t){return e.kind==="completed"&&t?{kind:"upstream_error",message:t}:e}function qsn(e){const t=e.toLowerCase();return t.includes("opus")?"opus":t.includes("sonnet")?"sonnet":t.includes("haiku")?"haiku":"other"}function yA(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:qsn(r),attempts:s,skipped:[]}}function B2(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 Gsn=1,Hsn=20;function ble(e){return typeof e=="number"&&Number.isInteger(e)&&e>=Gsn&&e<=Hsn?e:void 0}Bl(),fie(),_r(),q(),yn(),ey();var z2=new Set(["cookie","proxy-authorization","host","connection","content-length","transfer-encoding"]),Tle="proxy/internal",Ele="internal",Sh=0,Zsr=0,vA=5,j2=2,Sle=[250,1e3],Xsr=[250,500,1e3,2e3],Cle=1,Vsn=120*1e3,kle=2,Qsr=3e4,eir=11520*60*1e3,tir=5e3,Wsn=900*1e3,rir=900*1e3,Ksn=3e4,Jsn=300*1e3,_A=900*1e3,nir;function xle(e,t){return nir??=new pS({headersTimeout:_A,bodyTimeout:_A}),fetch(e,{...t,dispatcher:nir})}var Hl=new Map,wA=new nnn,Qw=new snn,oir=900*1e3,sir=new Map,iir=new Map,q2=new Map,Ysn={release:()=>{}};function air(e){let t=q2.get(e);return t||(t={active:0,waiters:[]},q2.set(e,t)),t}function Ale(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(lir(e,t))}}function lir(e,t){let r=!1;return{release:()=>{r||(r=!0,t.active=Math.max(0,t.active-1),Ale(e,t),cir(e,t))}}}function cir(e,t){t.active===0&&t.waiters.length===0&&q2.delete(e)}function Zsn(e,t){const r=ble(t);if(r===void 0)return Ysn;const n=air(e);if(!(n.waiters.length>0||n.active>=r))return n.active+=1,lir(e,n)}function Xsn(e,t){const r=ble(t);if(r===void 0)return!0;const n=q2.get(e);return!n||n.waiters.length===0&&n.active<r}function Qsn(e,t){const r=ble(t);if(r===void 0)throw new Error("Account admission queue requires an explicit capacity");const n=air(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),Ale(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),Ale(e,n)),cir(e,n)}}}async function ein(e,t,r,n=dir){const o=[...new Set(e)].map(i=>Qsn(i,t));let s;try{return await zt(tOe(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 uir=!1,Ile=6e4,dir=9e4,tin=12e4,rin=250,nin=15e3;function xy(e,t,r){t<=1||e===r&&(Sh=(Sh+1)%t)}function pir(e,t){if(!t)return 0;const r=e.findIndex(n=>$or(n.key,t));return r>=0?r:0}function oin(e,t){if(e.length<=1)return;const r=pir(e,t);if(Sh===r)return;const n=e[r],o=Hl.get(n.key);if((!o||!o.coolingUntil||Date.now()>=o.coolingUntil)&&(Sh=r,o?.coolingUntil)){const s=o.coolingUntil;o.coolingUntil=void 0,o.coolingReason=void 0,by(n.key,s).catch(()=>{}),f.always(`[proxy] home primary account=${n.label} cooling expired, resetting primaryAccountIndex to ${r}`)}}function mir(e){const t=Hl.get(e);return!!t?.coolingUntil&&Date.now()<t.coolingUntil}function sin(e,t,r=Date.now()){let n=sir.get(e);if(!n||r>=n.coolingUntil?(n={coolingUntil:t,retriesClaimed:0},sir.set(e,n)):t>n.coolingUntil&&(n.coolingUntil=t),!(n.retriesClaimed>=kle))return n.retriesClaimed+=1,n.retriesClaimed}function iin(e,t,r=Date.now()){if(t<=r)return 0;if(t-r>dir)return;let n=iir.get(e);!n||r>=n.coolingUntil?(n={coolingUntil:t,nextAdmissionAt:t},iir.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>nin))return n.nextAdmissionAt=o+rin,o-r}async function ain(e){const t=Date.now()+tin;for(;Date.now()<t;){const r=e.filter(i=>!mir(i.key));if(r.length>0)return r;const n=Date.now(),o=e.map(i=>({account:i,state:ll(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=iin(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 zp(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 bA(e,t){try{const r=t.poolAccounts?pnn(t.poolAccounts.map(o=>{const s=Hl.get(o.key);return{...s?.coolingUntil!==void 0?{coolingUntil:s.coolingUntil}:{},...s?.quota?{quota:s.quota}:{}}})):void 0,n=dnn({...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??{},...jin(n)}}catch(r){f.debug(`[proxy] failed to publish limit headers: ${r instanceof Error?r.message:String(r)}`)}}function G2(e,t,r){const n=Math.min(eir,(r&&Oor[r])??eir);return Math.min(Math.max(e,t+tir),t+n)}function Rle(e,t,r,n=e?.unifiedStatus,o=Ay){if(e&&e.weeklyStatus==="rejected"){const a=$i(e.weeklyResetAt,r)??(t>0?r+t:r+Ile);return{reason:"weekly",coolingUntil:G2(a,r,"weekly"),rotateImmediately:!0}}const s=W2(e,o);if(e&&e.sessionStatus==="rejected"&&!s){const a=$i(e.sessionResetAt,r)??(t>0?r+t:r+Ile);return{reason:"session",coolingUntil:G2(a,r,"session"),rotateImmediately:!0}}if(n?.trim().toLowerCase()==="rejected"&&!s){const a=t>0?r+t:r+rir;return{reason:"unified",coolingUntil:G2(a,r,"unified"),rotateImmediately:!0}}const i=t>0?t:Ile;return{reason:"transient",coolingUntil:r+Math.max(tir,Math.min(i,Wsn)),rotateImmediately:!1}}function Mle(e,t){return Math.max(0,Math.round((e-t)/6e4))}function Ple(e,t,r,n=Ay){const o=W2(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+rir,i="unified"),s===void 0)return null;const a=G2(s,r,i);return!e.coolingUntil||a>e.coolingUntil?(e.coolingUntil=a,e.coolingReason=i,f.always(`[proxy] proactively cooling account (${i}) ~${Mle(a,r)}m from success-response quota (status rejected)`),{kind:"cooled",coolingUntil:a,coolingReason:i??"unified"}):null}async function lin(e){try{const[t,r]=await Promise.all([Fae(),nA()]),n=Date.now();for(const o of e){const s=ll(o.key);!s.quota&&t[o.label]&&(s.quota=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 cin=15e3,hir=new Map,H2=null,uin=4;async function fir(e,t,r,n){if(t.ok===!1)return null;const o=ll(e.key),s=Jor(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=Ty(o.quota,s);const i=Ple(o,s,Date.now());return i?.kind==="cooled"?await wd(e.key,i.coolingUntil,i.coolingReason).catch(()=>{}):i?.kind==="cleared"&&await by(e.key,i.coolingUntil).catch(()=>{}),await Sy(e.label,s).catch(()=>{}),s}async function gir(e){const t=await Xrn(e);return t.ok===!1||Jor(t.usage,{now:Date.now(),prior:Hl.get(e.key)?.quota??null})?t:{ok:!1,reason:"parse",error:"usage payload had no recognizable limit windows"}}async function V2(e,t){const r=await wA.run(e,t,gir);r.kind!=="completed"||r.result.ok===!1||await fir(e,r.result,r.startedAt)}async function Dle(e={}){const t=Date.now(),r=await Wor(e.accountAllowlist),n=e.accountFilter?r.filter(c=>c.label===e.accountFilter||c.key===e.accountFilter):r,o=await Fae().catch(()=>({})),s=(c,u,d,m)=>{const h=Hl.get(c.key),g={account:c.label,key:c.key,type:c.type,status:u,quota:d??h?.quota??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:wA.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=hir.get(u.key)??0;if(Date.now()-d<cin){i[c]=s(u,"throttled",null);continue}hir.set(u.key,Date.now());try{const m=await wA.run(u,`manual:${u.key}`,gir,{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 fir(u,h,m.startedAt,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(uin,n.length||1)},()=>l())),{fetchedAt:t,snapshot:!1,results:i,refreshMetrics:wA.getMetrics()}}function Ole(){const e=(process.env.NEUROLINK_PROXY_QUOTA_ROUTING??"").toLowerCase();return e!=="off"&&e!=="false"&&e!=="0"}function Nle(){const e=Number(process.env.NEUROLINK_PROXY_SESSION_SOFT_LIMIT??"");return Number.isFinite(e)&&e>0&&e<=1?e:.97}function TA(){const e=Number(process.env.NEUROLINK_PROXY_SESSION_RESET_TOLERANCE_MS??"");return Number.isInteger(e)&&e>0?e:900*1e3}var Ay="auto";function Lle(e){e!==void 0&&(Ay=e)}function din(){return Ay}function W2(e,t=Ay){return t==="never"?!1:Uor(e)}var pin=4;function K2(e){return e.toLowerCase().replace(/[^a-z0-9]/g,"")}function min(e){const t=K2(e);return t.startsWith("claude")?t.slice(6):t}function hin(e,t,r){if(e.scopeModelId&&K2(E2(e.scopeModelId))===r)return Number.MAX_SAFE_INTEGER;if(!e.scopeModel)return null;const n=min(e.scopeModel);return n.length<pin||!t.includes(n)?null:n.length}function yir(e,t){return t.updatedAt??e.windowsUpdatedAt??e.lastUpdated}function vir(e,t,r=Date.now()){if(!e?.windows?.length||!t)return null;const n=K2(t);if(!n)return null;const o=K2(E2(t));let s=null,i=-1,a=-1;for(const l of e.windows){if(r-yir(e,l)>oir)continue;const c=hin(l,n,o);if(c===null)continue;const u=yir(e,l);(c>i||c===i&&u>a)&&(s=l,i=c,a=u)}return s}function fin(e,t,r=Date.now(),n=Ay){if(!t||e.length===0)return{eligible:e,exhaustion:null};const o=[],s=[];let i;for(const l of e){const c=Hl.get(l.key)?.quota,u=vir(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)&&!W2(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??E2(t),earliestResetMs:a,accounts:s.map(l=>l.label),...i?{overageDisabledReason:i}:{}}}}function J2(e,t,r,n,o,s=Ay){const i=Hl.get(e),a=i?.quota,l=a&&Number.isFinite(a.lastUpdated)?a.lastUpdated:null,c=l===null?null:Math.max(0,t-l),u=wA.getState(e),d=c!==null&&c>oir,m=Y=>Y.trim().toLowerCase(),h=Uor(a),g=[a?.unifiedStatus,a?.sessionStatus,a?.weeklyStatus].filter(Y=>!!Y?.trim()),y=d&&!!a&&!h&&g.some(Y=>m(Y)!=="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),A=k!==void 0,I=T!==void 0,M=_?A?_.sessionUsed??0:0:null,R=_?I?_.weeklyUsed??null:0:null,x=_?A?_.sessionStatus??"unknown":"allowed":null,O=_?I?_.weeklyStatus??"unknown":"allowed":null,N=W2(_,s),P=!N&&(x==="rejected"||x==="throttled"||O==="rejected"||O==="throttled"||_?.unifiedStatus?.trim().toLowerCase()==="rejected"||A&&(M??0)>=1||I&&(R??0)>=1),D=!P&&!N&&A&&(M??0)>=r,L=P||D,$=vir(_,o,t),U=$?$i($.resetsAt,t):void 0,j=U!==void 0,B=$?j?$.used:0:null,z=$?j?$.status??"unknown":"allowed":null,J=!d&&j&&(B??0)>=r;return{usable:!b&&!P&&(z!=="rejected"||N),saturated:L,scopedModel:$?.scopeModel??null,scopedStatus:z,scopedUsed:B,scopedReset:U??Number.POSITIVE_INFINITY,scopedUsedForSort:B??-1,scopedSaturated:J,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:P?"hard":D?"soft":"none",softLimitOverrideReason:N&&A&&(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:N,overageStatus:_?.overageStatus??null,sessionStatus:x,sessionUsed:M,sessionResetBucket:A?Math.floor(k/n):Number.POSITIVE_INFINITY,sessionReset:k??Number.POSITIVE_INFINITY,weeklyStatus:O,weeklyReset:T??Number.POSITIVE_INFINITY,weeklyUsed:R,weeklyUsedForSort:R??-1}}function _ir(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 gin(e,t,r,n,o,s){const i=new Map(e.map(a=>[a.key,J2(a.key,t,n,o,s)]));return{orderedAccounts:[...e].sort((a,l)=>_ir(a,l,i,r)[0]),metricsByKey:i}}function yin(e,t,r,n){for(const u of e){if(u.type!=="oauth")continue;const d=n?.get(u.key)??J2(u.key,Date.now(),r,TA());d.quotaFreshness==="unknown"?V2(u,`startup-unknown:${u.key}`).catch(m=>{f.debug(`[proxy] background quota discovery failed account=${u.label}: ${Td(m)}`)}):d.quotaFreshness==="refresh_due"&&V2(u,`ambiguous:${d.quotaLastUpdated??0}`).catch(m=>{f.debug(`[proxy] ambiguous quota refresh failed account=${u.label}: ${Td(m)}`)})}const o=t[0],s=t[1];if(!o||!s||s.type!=="oauth")return;const i=Hl.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(":");V2(s,c).catch(u=>{f.debug(`[proxy] quota handoff prewarm failed account=${s.label}: ${Td(u)}`)})}function vin(e,t,r,n){!t||t.type!=="oauth"||J2(t.key,Date.now(),n,TA()).quotaFreshness==="fresh"||V2(t,`hard-handoff:${e.key}:${r}:${t.key}`).catch(s=>{f.debug(`[proxy] hard-handoff quota refresh failed account=${t.label}: ${Td(s)}`)})}function _in(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",_=_ir(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 win(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"&&oin(t,n),h){const y=gin(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!==Zsr&&(Sh=pir(c,n),Zsr=c.length),c.length>1&&(m=Sh%c.length,r==="round-robin"&&(Sh=(Sh+1)%c.length),m>0)){const y=c.splice(0,m);c.push(...y)}d=new Map(t.map(y=>[y.key,J2(y.key,u,s,i,a)]))}const g=_in({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 Y2=new Map,bin=300*1e3,Tin=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"]),Ein=["oauth-2025-04-20","claude-code-20250219","fine-grained-tool-streaming-2025-05-14"];function Z2(e){return e.replace(/[^a-zA-Z0-9._@-]/g,"_")}function wir(e){return St(Va(),".neurolink","header-snapshots",`anthropic_${Z2(e)}.json`)}function Sin(e,t){if(t?.headers)for(const[r,n]of Object.entries(t.headers)){const o=r.toLowerCase();typeof n=="string"&&!e[o]&&!z2.has(o)&&o!=="authorization"&&o!=="x-api-key"&&o!=="x-claude-code-session-id"&&(e[o]=n)}}async function Cin(e){try{const t=Z2(e),r=Y2.get(t);if(r&&Date.now()-r.loadedAt<bin)return r.snapshot;const n=wir(e);try{await _P(n)}catch{return null}const o=JSON.parse(await Wr(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:(Y2.set(t,{snapshot:s,loadedAt:Date.now()}),s)}catch{return null}}function kin(e,t){const r={...t??{}};for(const[n,o]of Object.entries(e)){const s=n.toLowerCase();typeof o=="string"&&Tin.has(s)&&!z2.has(s)&&s!=="authorization"&&s!=="x-api-key"&&s!=="x-claude-code-session-id"&&(r[s]=o)}return r}function bir(e){if(!e||typeof e!="object")return;const t=e,r=ext(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 Tir(e,t){return typeof e["x-claude-code-session-id"]=="string"||e["user-agent"]?.startsWith("claude-cli/")||!!t?.metadataUserId||!!t?.billingHeader||!!t?.agentBlock}function xin(e,t){return e?JSON.stringify(e.headers??{})===JSON.stringify(t.headers??{})&&JSON.stringify(e.body??{})===JSON.stringify(t.body??{}):!1}async function Ain(e,t){const r=wir(e);await sl(r,t,384),Y2.set(Z2(e),{snapshot:t,loadedAt:Date.now()})}async function Iin(e,t,r,n){const o=await Cin(e);let s;try{s=JSON.parse(n)}catch{return o}const i=bir(s);if(!Tir(r,i))return o;const a={accountKey:t,capturedAt:new Date().toISOString(),source:"claude-code",headers:kin(r,o?.headers),body:{...o?.body??{},...i??{},...typeof r["x-claude-code-session-id"]=="string"?{sessionId:r["x-claude-code-session-id"]}:{}}};if(xin(o,a))return o;try{await Ain(e,a)}catch(l){f.warn("[proxy] failed to persist Claude snapshot",{accountLabel:e,error:l instanceof Error?l.message:String(l)}),Y2.set(Z2(e),{snapshot:a,loadedAt:Date.now()})}return a}function $le(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 Eir(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 Rin(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:xO(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&&vxt(s,s.system),s.system=[d,i]}}}else{const c={type:"text",text:xO(r?.body?.billingHeader)};s.system=[c,i]}const a=t.substring(0,Math.min(20,t.length)),l=txt(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 Min(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:T2,label:s,token:r,refreshToken:n,expiresAt:o,type:"oauth",persistTarget:{credPath:t}});if(!i)return a();const l=ll(T2);if(l.permanentlyDisabled)return;const c=(await nA())[T2];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 Bp(a(),l,"missing_refresh_token");return}const u={token:r,refreshToken:n,expiresAt:o,label:s},d=await Hor(u);if(!d.success){if(Cy(d)){await Bp(a(),l,"refresh_invalid");return}const m=await eF(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 A2(t,u),await tF(a(),l),f.always("[proxy] refreshed legacy account at startup"),a()}async function Pin(e){const{ctx:t,body:r,route:n,modelRouter:o,tracer:s,requestStartTime:i,logProxyBody:a}=e;s?.setMode("full");const l=Hae(r),c=yA({provider:n.provider,model:n.model},o?.getFallbackChain()??[],r.model,l,o?.isAutoFallbackEnabled?.()??!1);Sir(a,"translated_request",c);const u=c.attempts;if(r.stream)return Qae({ctx:t,format:"claude",requestModel:r.model,parsed:l,attempts:u,tracer:s,requestStartTime:i});try{return await ele({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=Gl(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 Sir(e,t,r){e({phase:"routing_decision",contentType:"application/json",body:{stage:t,attempts:r.attempts}})}async function Din(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))!z2.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"}}),xw("passthrough","passthrough");let m;try{m=await xle("https://api.anthropic.com/v1/messages?beta=true",{method:"POST",headers:u,body:l,signal:AbortSignal.timeout(_A)})}catch(g){const y=g instanceof Error?g.message:String(g);an("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=Gl(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=zw(m.headers,{model:r.model});bA(t,{upstreamHeaders:m.headers,quota:g,source:g?"live":"none",accountType:"passthrough",servedBy:"anthropic",attempt:1})}if(!m.ok){const g=await m.text();an("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 Gl(m.status,g)}}return r.stream&&m.body?Nin({ctx:t,body:r,bodyStr:l,response:m,tracer:o,requestStartTime:s,toolCount:c,upstreamSpan:d,upstreamResponseHeaders:h,logProxyBody:i,logFinalRequest:a}):Lin({ctx:t,body:r,bodyStr:l,response:m,tracer:o,requestStartTime:s,toolCount:c,upstreamSpan:d,upstreamResponseHeaders:h,logProxyBody:i,logFinalRequest:a})}function Oin(e){const t=e.getReader(),r=Ysr();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 Nin(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}=Esr(),h=n.body;if(!h)throw an("passthrough","passthrough",502),new Error("Expected passthrough stream response body");const g=Oin(h);let y=g.stream,v=!1;const _=(T,k,A,I)=>v?!1:(v=!0,k==="stream_error"&&an("passthrough","passthrough",T),c(T,"passthrough","passthrough",k,A,I),!0);if(o)try{const{stream:T,telemetry:k}=F2({captureRawText:!0});y=y.pipeThrough(T);const A=o,I=i,M=n,R=r.length;Promise.all([k,m,g.outcome]).then(([x,O,N])=>{const P=U2(N,x.streamErrorMessage),D=Ch(P);A.setUsage({inputTokens:x.usage.inputTokens,outputTokens:x.usage.outputTokens,cacheCreationTokens:x.usage.cacheCreationInputTokens,cacheReadTokens:x.usage.cacheReadInputTokens}),A.logStreamEvents(x.events),A.setResponseInfo(Eir(x));const L=parseFloat(M.headers.get("anthropic-ratelimit-unified-5h-utilization")??""),$=parseFloat(M.headers.get("anthropic-ratelimit-unified-7d-utilization")??""),U={inputTokens:x.usage.inputTokens,outputTokens:x.usage.outputTokens,cacheCreationTokens:x.usage.cacheCreationInputTokens,cacheReadTokens:x.usage.cacheReadInputTokens};isNaN(L)||(U.rateLimitAfter5h=L),isNaN($)||(U.rateLimitAfter7d=$),(!isNaN(L)||!isNaN($))&&A.setUsage(U),A.logUpstreamResponseBody(x.rawText??""),A.recordMetrics(),A.recordBodySizes(R,x.totalBytesReceived),I?.end(),D&&A.setError(D.errorType,D.message),A.end(D?.status??n.status,Date.now()-s),_(D?.status??n.status,D?.errorType,D?.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:200,durationMs:Date.now()-s}),l({phase:"client_response",headers:u,body:O.text,bodySize:O.totalBytes,contentType:u["content-type"]??"text/event-stream",account:"passthrough",accountType:"passthrough",attempt:1,responseStatus:200,durationMs:Date.now()-s})}).catch(x=>{if(v)return;const O=x instanceof Error?x.message:String(x);A.setError("stream_telemetry_error",O),I?.end(),A.end(500,Date.now()-s),_(500,"stream_telemetry_error",O)})}catch{g.outcome.then(T=>{const k=Ch(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}=F2({captureRawText:!0});y=y.pipeThrough(T),Promise.all([k,m,g.outcome]).then(([A,I,M])=>{const R=U2(M,A.streamErrorMessage),x=Ch(R);_(x?.status??n.status,x?.errorType,x?.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: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(A=>{v||_(500,"stream_telemetry_error",A instanceof Error?A.message:String(A))})}catch{g.outcome.then(T=>{const k=Ch(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 Lin(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($le(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 $in(e){const t=Gw();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=ll(d.key).quota,h=$i(m?.sessionResetAt,r)??null,g=$i(m?.weeklyResetAt,r)??null,y=await kie(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 wie(t.grantId);if(!o)return{accounts:e.accounts};const s=await xie(t.grantId,yle(o.gates,n).inScope),i=vle(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=_le(i.excluded),u=Jw(c,{status:rsn(c),grant:o,retryAfterSeconds:kir(n,r)});return e.ctx.responseHeaders={...e.ctx.responseHeaders??{},...u.headers},f.always(`[proxy] share ${t.peerLabel} withheld: ${c} (${i.excluded.length} accounts)`),{accounts:[],refusal:{response:e.buildLoggedClaudeError(u.status,u.body.error.message,u.body.error.type),status:u.status,message:u.body.error.message}}}async function Fin(e){const t=[],r=[];for(const n of e){const o=await Hon(n.key);if(!o){t.push(n);continue}if(!Oon(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 Uin(e,t){const r=[],n=[],o=Date.now();for(const s of e){const i=await gle(s.key);if(!i){r.push(s);continue}const a=i.lease.gates;if(!osn(a.models,t)){f.always(`[proxy] leased account=${s.label} does not cover model ${fo(t??"unknown")}`),n.push({label:s.label,reason:"model_not_allowed"});continue}if(a.schedule&&!nsn(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=ll(s.key).quota,c=$i(l?.sessionResetAt,o)??null,u=$i(l?.weeklyResetAt,o)??null,d=await kie(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 xie(i.grantId,[m]),{accounts:g,...y}=a,v=vle(Bin(i,y),[m],o,h);if(v.allowed.length===0){const _=_le(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 Bin(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 zin(e,t,r){const n=Date.now(),o=i=>{CXr({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=Gw();if(s){o(s.grantId);return}gle(e).then(i=>{i&&o(i.grantId)}).catch(()=>{})}function Fle(e,t,r){const n=Cie({inputTokens:r.inputTokens??0,outputTokens:r.outputTokens??0,...r.cacheCreationTokens!==void 0?{cacheCreationTokens:r.cacheCreationTokens}:{},...r.cacheReadTokens!==void 0?{cacheReadTokens:r.cacheReadTokens}:{}},t);Von(e,n).catch(()=>{})}function Cir(e,t){if(!t||typeof t!="object")return;const r=t.usage;if(!r)return;const n=Jin(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};Ule(e.key,n,o),Fle(e.label,n,o)}function Ule(e,t,r){const n=Gw();n&&kXr({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 jin(e){if(!Gw())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 qin(e,t){const r=e.provisionedAccount;if(!r)return{paused:!1,detail:"no provisioned account recorded"};const n=Hl.get(`anthropic:${r}`),o=XXt(r),{verdict:s,shouldPause:i}=await Esn({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 uXr(e.id,"paused"),{paused:!0,detail:s.drifted?s.detail:"repeated unexplained usage"}):{paused:!1,detail:s.drifted?s.detail:"consistent"}}async function Gin(e,t){await uQt(e.id,t)}function Hin(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 Vin=1,Win=["live","complete","handshake","limits"];async function Kin(e,t){const r=Date.now(),n=await Wor(t),o=await Promise.all(n.map(async c=>{const u=ll(c.key).quota,d=$i(u?.sessionResetAt,r)??null,m=$i(u?.weeklyResetAt,r)??null,h=await kie(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=yle(e.gates,o).inScope,i=await xie(e.id,s),a=vle(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(TXr(e)))}:{},servable:a.allowed.length>0,...a.allowed.length===0&&a.excluded.length>0?{withheldReason:_le(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=kir(o,r);return c===void 0?{}:{retryAfterSeconds:c}})():{}}}function Iy(e){return!e.ok}async function Ry(e){const t=usn(e);if(!t)return{ok:!1,body:Jw("missing_token",{status:401}).body};const r=await pXr(t);return r?{ok:!0,grant:r}:{ok:!1,body:Jw("unknown_token",{status:401}).body}}function Jin(e){if(!e||typeof e!="object")return;const t=e.model;return typeof t=="string"?t:void 0}function kir(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 Yin(e){const{ctx:t,body:r,tracer:n,requestStartTime:o,accountStrategy:s,primaryAccountKey:i,accountAllowlist:a,quotaRoutingEnabled:l=Ole(),sessionSoftLimit:c=Nle(),sessionResetToleranceMs:u=TA(),buildLoggedClaudeError:d,setRoutingDecision:m}=e,h=await Promise.resolve().then(()=>(gn(),_l)),g=await Promise.resolve().then(()=>(ic(),MT)),y=[],v=`${g.homedir()}/.neurolink/anthropic-credentials.json`,{tokenStore:_}=await Promise.resolve().then(()=>(Nx(),lie)),b=await nA();uir||(await _.pruneExpired(),uir=!0);const T=await _.listByPrefix("anthropic:"),k=[];let A=0,I=0;for(const ce of T){if(!Nae(ce,a)){f.debug(`[proxy] skipping account=${ce} (not in account allowlist)`);continue}if(await _.isDisabled(ce)){const me=ll(ce),$e=await _.getDisabledReason(ce);if($e==="refresh_failed")await _.markEnabled(ce),f.always(`[proxy] account=${ce.split(":")[1]??ce} re-enabled for legacy refresh failure recheck`),me.permanentlyDisabled=!1,me.consecutiveRefreshFailures=0;else{f.debug(`[proxy] skipping disabled account=${ce.split(":")[1]??ce}`),me.permanentlyDisabled=!0,$e==="entitlement_blocked"&&k.push(ce.split(":")[1]??ce),A+=1;continue}}const re=await _.loadTokens(ce);if(!re){I+=1;continue}let G=re.accessToken,K=re.refreshToken,Ce=re.expiresAt;const be=ce.split(":")[1]??ce,ge=re.tokenType==="Bearer"?"oauth":"api_key",H=ll(ce),se=b[ce];se?.coolingUntil>Date.now()&&(!H.coolingUntil||se.coolingUntil>H.coolingUntil)&&(H.coolingUntil=se.coolingUntil,H.coolingReason=se.reason);const ye=()=>{y.push({key:ce,label:be,token:G,refreshToken:K,expiresAt:Ce,type:ge,persistTarget:{providerKey:ce}})};if(Ce?Ce<Date.now():!1){if(H.permanentlyDisabled)continue;if(H.coolingReason==="auth"&&H.coolingUntil&&H.coolingUntil>Date.now()){ye();continue}if(!K){f.always(`[proxy] skipping account=${be} (expired, no refresh token)`),await Bp({key:ce,label:be,token:G,type:"oauth"},H,"missing_refresh_token");continue}const me={token:G,refreshToken:K,expiresAt:Ce,label:be},$e=await x2(me,{providerKey:ce});if(!$e.success){const Se={key:ce,label:be,token:G,type:"oauth"};if(Cy($e))f.always(`[proxy] skipping account=${be} (refresh token rejected: ${$e.error?.slice(0,200)??"unknown"})`),await Bp(Se,H,"refresh_invalid");else{const ne=await eF(Se,H);f.always(`[proxy] account=${be} refresh temporarily unavailable (${$e.status??"network"}); cooling until ${new Date(ne).toISOString()} and rotating`),ye()}continue}G=me.token,K=me.refreshToken,Ce=me.expiresAt,await _.saveTokens(ce,{accessToken:G,refreshToken:K,expiresAt:Ce??Date.now()+36e5,tokenType:"Bearer"}),f.always(`[proxy] refreshed expired account=${ce.split(":")[1]??ce} at startup`),await tF({key:ce},H)}ye()}if(y.length===0&&For(T.length,T2,a))try{const ce=JSON.parse(h.readFileSync(v,"utf8")),re=await Min(ce,v);re&&y.push(re)}catch{}if(process.env.ANTHROPIC_API_KEY&&y.length===0&&For(T.length,Lor,a)&&y.push({key:Lor,label:"env",token:process.env.ANTHROPIC_API_KEY,type:"api_key"}),y.length===0){if(k.length>0&&k.length===A&&I===0){const re=Iir({status:403,accounts:k,message:"OAuth authentication is not allowed for this organization.",errorCode:"oauth_not_allowed_for_organization"});return n?.setError("permission_error",re),n?.end(403,Date.now()-o),{response:d(403,re,"permission_error")}}const ce=a?"No allowed Anthropic credentials are currently available":T.length>0?"Configured Anthropic accounts are disabled or unavailable":"No Anthropic credentials found";return n?.setError("authentication_error",ce),n?.end(401,Date.now()-o),{response:d(401,ce)}}for(const ce of y)wan(ce);await lin(y);const M=y.filter(ce=>!ll(ce.key).permanentlyDisabled),R=await Fin(M),x=await Uin(R.accounts,typeof r.model=="string"?r.model:void 0),O={accounts:x.accounts,withheld:[...R.withheld,...x.withheld]},N=O.accounts;if(N.length===0&&O.withheld.length>0){const ce=O.withheld.map(K=>`${K.label} (${K.reason})`).join(", "),G=O.withheld.every(K=>K.reason==="model_not_allowed")?`Borrowed account(s) do not cover the requested model: ${ce}. Ask the lender to widen the share, or use a model it allows.`:`Borrowed account(s) are no longer covered by a lease: ${ce}. Run 'neurolink proxy peer sync' to check in with the lender, or ask them to resume the share.`;return n?.setError("permission_error",G),n?.end(403,Date.now()-o),{response:d(403,G,"permission_error")}}const P=await $in({accounts:N,ctx:t,buildLoggedClaudeError:d});if(P.refusal)return n?.setError("rate_limit_error",P.refusal.message),n?.end(P.refusal.status,Date.now()-o),{response:P.refusal.response};const D=P.accounts;if(D.length===0){const ce=rF(y.map(re=>re.label));return n?.setError("authentication_error",ce),n?.end(401,Date.now()-o),{response:d(401,ce)}}const{orderedAccounts:L,metricsByKey:$}=win({enabledAccounts:D,accountStrategy:s,primaryAccountKey:i,quotaRoutingEnabled:l,sessionSoftLimit:c,sessionResetToleranceMs:u,requestedModel:typeof r.model=="string"?r.model:void 0,setRoutingDecision:m});s==="fill-first"&&l&&D.length>1&&yin(D,L,c,$);const U=Can(r),j=JSON.stringify(U),B=Date.now(),z=Array.isArray(r.tools)?r.tools.length:0,J="https://api.anthropic.com/v1/messages?beta=true",Y=t.headers??{},ie=bir(r);return{accounts:y,enabledAccounts:D,orderedAccounts:L,bodyStr:j,requestStart:B,toolCount:z,url:J,clientHeaders:Y,isClaudeClientRequest:Tir(Y,ie)}}async function Zin(e){const{ctx:t,body:r,tracer:n,requestStartTime:o,logProxyBody:s,logFinalRequest:i,options:a,providerLabel:l,idleTimeoutMs:c=Vsn}=e,u=new AbortController;let d;try{d=await zt(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:A}=await zt(b.next(),c,`Fallback ${l} stream timed out after ${c}ms of inactivity`);if(A)return T;const I=Yae(k);I&&(T+=I,_?.(I))}}catch(k){throw u.abort(k),b.return?.().catch(()=>{}),k}};if(r.stream){const _=new nsr(r.model,0),b=[];for(const x of _.start())b.push(x);const T=await m(x=>{for(const O of _.pushDelta(x))b.push(O)}),k=d.toolCalls??[];if(!D2(T,k))throw new Error(`Translated provider ${l} returned no content or tool calls`);if(k.length)for(const x of k){const O=x.toolName??x.name??"unknown";for(const N of _.pushToolUse(Gae(),O,_sr(x)))b.push(N)}const A=d.finishReason??"end_turn",I=Ww(d.usage);for(const x of _.finish(I.output,A))b.push(x);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 x of b)yield x}return R()}const h=await m();if(!D2(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?Ww(d.usage):void 0,toolCalls:d.toolCalls};n?.end(200,Date.now()-o);const y=rsr(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 xir(e){let t;for(let r=0;r<=Cle;r+=1)try{return await Zin(e)}catch(n){if(t=n,!jle(n)||r===Cle)throw n;const o=Sle[r]??250;f.always(`[proxy] retrying fallback=${e.providerLabel} after transient network error (${r+1}/${Cle}) in ${o}ms: ${SA(Td(n))}`),await zp(o)}throw t}async function Air(e){if(Gw())return null;const t=await xon();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 Xon({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}async function Xin(e){const{ctx:t,body:r,parsedFallbackRequest:n,modelRouter:o,tracer:s,requestStartTime:i,logProxyBody:a,logFinalRequest:l}=e,c=o?.getFallbackChain()??[],u=yA({provider:"anthropic",model:r.model},c,r.model,n);a({phase:"routing_decision",contentType:"application/json",body:{stage:"anthropic_fallback",attempts:u.attempts.slice(1)}}),s?.setFallbackInfo({triggered:!0,attemptCount:u.attempts.slice(1).length,reason:"all_anthropic_accounts_exhausted"});let d;for(const m of u.attempts.slice(1)){if(!m.provider||!m.model)continue;const h=await U_.checkFallbackProviderAvailability(m.provider,m.model);if(!h.available){const y=h.reason??"provider unavailable";f.always(`[proxy] fallback ${m.provider}/${m.model} health-check failed (${y}), skipping`),aA({provider:m.provider,model:m.model,status:"failure",errorMessage:`[unavailable] ${y}`,durationMs:0}),d=`[${m.provider}/${m.model}] unavailable: ${y}`;continue}const g=Date.now();try{f.always(`[proxy] fallback \u2192 ${m.provider}/${m.model}`);const y=qir(n,{provider:m.provider,model:m.model}),v=await xir({ctx:t,body:r,tracer:s,requestStartTime:i,logProxyBody:a,logFinalRequest:l,options:y,providerLabel:m.provider});return aA({provider:m.provider,model:m.model,status:"success",durationMs:Date.now()-g}),s?.setFallbackInfo({triggered:!0,provider:m.provider,model:m.model,attemptCount:u.attempts.slice(1).length,reason:"fallback_success"}),bA(t,{quota:null,source:"none",servedBy:m.provider}),{response:v}}catch(y){const v=SA(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 ${m.provider}/${m.model} failed [${_}]: ${SA(Td(y))}`),aA({provider:m.provider,model:m.model,status:"failure",errorMessage:`[${_}] ${v}`,durationMs:Date.now()-g}),d=`[${m.provider}/${m.model}] ${SA(Td(y))}`}}return{response:null,lastErrorMessage:d}}async function Qin(e){const{ctx:t,body:r,tracer:n,requestStartTime:o,logProxyBody:s,logFinalRequest:i}=e,a=Date.now();try{const l=Hae(r),c=yA({provider:"anthropic",model:r.model},[],r.model,l,!0);if(Sir(s,"auto_fallback",c),!c.attempts.find(h=>h.label==="auto-provider"))return{response:null};f.always("[proxy] fallback \u2192 auto-provider");const d=qir(l),m=await xir({ctx:t,body:r,tracer:n,requestStartTime:o,logProxyBody:s,logFinalRequest:i,options:d,providerLabel:"auto-provider"});return aA({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"}),bA(t,{quota:null,source:"none",servedBy:"auto-provider"}),{response:m}}catch(l){const c=SA(Td(l));return f.always(`[proxy] fallback auto-provider failed: ${c}`),aA({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 ean(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 Iir(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: ${ean(e.accounts)}. Upstream: "${e.message}". Ask an organization admin to re-enable Claude Code OAuth access, then run: neurolink auth enable anthropic:<account>.`}function tan(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 ran(e){for(const t of e){const r=Hl.get(t.key)?.quota;if(r?.overageDisabledReason&&r.overageStatus?.trim().toLowerCase()!=="allowed")return r.overageDisabledReason}}function Rir(e){return e?` Paid extra usage is unavailable for this organization (${e}), so there is no additional capacity before the window resets.`:""}function nan(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()}.`+Rir(e.overageDisabledReason)}function oan(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=Iir(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){t?.setError("invalid_request_error",Or(s.body)),t?.end(s.status,Date.now()-r);try{const D=JSON.parse(s.body);return b(s.status,"","final","invalid_request_error",Or(s.body)),_({phase:"client_response",headers:{"content-type":s.contentType??"application/json"},body:s.body,bodySize:Buffer.byteLength(s.body,"utf8"),contentType:s.contentType??"application/json",responseStatus:s.status,durationMs:Date.now()-r}),D}catch{return v(s.status,Or(s.body),"invalid_request_error")}}if((l||c)&&!u){const D=g?` Fallback also failed: ${g}`:"",L=h==="shared_provider_transport"?"shared Anthropic network":h==="connection_transport"?"Anthropic connection":null,$=`${L?`${L} 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",$.slice(0,500)),t?.end(502,Date.now()-r),v(502,$,g?"fallback_exhausted":"transient_error",{...m?{errorCode:m}:{},...h?{transportScope:h}:{}})}const k=(D,L)=>{const $=Gl(429,D,"overloaded_error");t?.setError("rate_limit_error",D),t?.end(429,Date.now()-r),b(429,"","final","rate_limit_error",D);const U=JSON.stringify($),j={"content-type":"application/json","retry-after":String(L)};return _({phase:"client_response",headers:j,body:U,bodySize:Buffer.byteLength(U,"utf8"),contentType:"application/json",responseStatus:429,durationMs:Date.now()-r}),new Response(U,{status:429,headers:j})};if(a){const D=nan(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}`:"",L=`All Anthropic accounts failed. Last error: ${d instanceof Error?d.message:String(d??"unknown")}.${D}`;return t?.setError("all_accounts_failed",L.slice(0,500)),t?.end(502,Date.now()-r),v(502,L,g?"fallback_exhausted":"all_accounts_failed")}const A=Date.now(),I=y.map(D=>ll(D.key)).filter(D=>D.coolingUntil&&D.coolingUntil>A&&D.coolingReason!=="auth"),M=Math.min(...I.map(D=>D.coolingUntil??Number.POSITIVE_INFINITY)),R=y.length>0&&I.length===y.length,x=R?Math.max(1,Math.ceil((M-A)/1e3)):1,O=tan(I),N=Rir(ran(y)),P=R?`All ${y.length} Anthropic accounts are cooling after the ${O} was exhausted. Earliest retry at ${new Date(M).toISOString()}.${N}`:`All ${y.length} accounts rate-limited after per-account retries.${N}`;return f.always(`[proxy] all accounts rate-limited, retry in ${x}s`),k(P,x)}async function Mir(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 _=zw(s.headers,{model:r.model});if(_){zin(n.key,o.quota,_),o.quota=Ty(o.quota,_);const T=Ple(o,_,Date.now());T?.kind==="cooled"?wd(n.key,T.coolingUntil,T.coolingReason).catch(()=>{}):T?.kind==="cleared"&&by(n.key,T.coolingUntil).catch(()=>{}),Sy(n.label,_).catch(()=>{})}const b={};return s.headers.forEach((T,k)=>{b[k]=T}),i?.logUpstreamResponseHeaders(b),bA(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?san({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}):aan({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 san(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){an(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=Gl(502,"No response body from upstream"),x=JSON.stringify(R);return g({phase:"client_response",headers:{"content-type":"application/json"},body:x,bodySize:Buffer.byteLength(x,"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 jsn(_);if(b.kind==="transport_error"){const R=Td(b.error),x=Buffer.concat(b.chunks.map(O=>Buffer.from(O))).toString("utf8");return f.always(`[proxy] stream failed before first chunk account=${n.label}: ${R}; returning terminal error to avoid replaying an ambiguous request`),an(n.label,n.type,502),h(502,"stream_error",R,{retryable:!1}),m?.end(),g({phase:"upstream_response",headers:i,body:x,bodySize:Buffer.byteLength(x,"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:Dir({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`),an(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"),x=b.errorType==="rate_limit_error",O=x?429:502,N=zw(i,{model:r.model}),P=Date.now();if(x){const D=Rle(N,B2(i["retry-after"]??null),P,S2(i));o.quota=N?Ty(o.quota,N):o.quota;const L=D.reason==="transient"?"transient":"quota";(!o.coolingUntil||D.coolingUntil>o.coolingUntil)&&(o.coolingUntil=D.coolingUntil,o.coolingReason=D.reason,await wd(n.key,D.coolingUntil,D.reason).catch(()=>{})),an(n.label,n.type,429,L),h(429,"rate_limit_error",b.message,{retryable:!0,rateLimitKind:L,cooldownReason:D.reason})}else an(n.label,n.type,O),h(O,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,x?"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:O,upstreamErrorType:b.errorType}}),{retryNextAccount:!0,failure:{message:b.message,rateLimit:x,...b.errorType==="overloaded_error"?{retryDelayMs:Uir(u)}:{}}}}h(s.status,void 0,void 0,{attemptDurationMs:Date.now()-c});const T=Ysr();let k=!1;const A=new ReadableStream({start(R){for(const x of b.chunks)R.enqueue(x)},async pull(R){if(!k)try{const{done:x,value:O}=await _.read();if(k)return;if(x){k=!0,T.complete(),R.close();return}R.enqueue(O)}catch(x){const O=Td(x);if(f.always(`[proxy] mid-stream error account=${n.label}: ${O}`),T.fail(O),!k){k=!0;const N=`event: error
|
|
2355
2355
|
data: ${JSON.stringify({type:"error",error:{type:"api_error",message:`Upstream stream interrupted: ${O}`}})}
|
|
2356
2356
|
|
|
2357
2357
|
`;R.enqueue(new TextEncoder().encode(N)),R.close()}}},cancel(){return k=!0,T.cancel(),_.cancel()}}),{response:I,telemetryDone:M}=ian({ctx:t,account:n,response:s,responseHeaders:i,remainingStream:A,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 Ch(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 X2(e,t){e.kind==="upstream_error"&&an(t.label,t.type,502)}function ian(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}=Esr();let v=s,_;if(a)try{const{stream:k,telemetry:A}=F2({captureRawText:!0});v=v.pipeThrough(k);const I=a,M=d,R=n,x=u.length,O=r.label,N=r.key;_=Promise.all([A,y,i]).then(([P,D,L])=>{const $=U2(L,P.streamErrorMessage);X2($,r),I.setUsage({inputTokens:P.usage.inputTokens,outputTokens:P.usage.outputTokens,cacheCreationTokens:P.usage.cacheCreationInputTokens,cacheReadTokens:P.usage.cacheReadInputTokens}),Ule(N,P.model,{inputTokens:P.usage.inputTokens,outputTokens:P.usage.outputTokens,cacheCreationTokens:P.usage.cacheCreationInputTokens,cacheReadTokens:P.usage.cacheReadInputTokens}),Fle(O,P.model,{inputTokens:P.usage.inputTokens,outputTokens:P.usage.outputTokens,cacheCreationTokens:P.usage.cacheCreationInputTokens,cacheReadTokens:P.usage.cacheReadInputTokens}),I.logStreamEvents(P.events),I.setResponseInfo(Eir(P));const U=parseFloat(R.headers.get("anthropic-ratelimit-unified-5h-utilization")??""),j=parseFloat(R.headers.get("anthropic-ratelimit-unified-7d-utilization")??""),B={inputTokens:P.usage.inputTokens,outputTokens:P.usage.outputTokens,cacheCreationTokens:P.usage.cacheCreationInputTokens,cacheReadTokens:P.usage.cacheReadInputTokens};isNaN(U)||(B.rateLimitAfter5h=U),isNaN(j)||(B.rateLimitAfter7d=j),(!isNaN(U)||!isNaN(j))&&I.setUsage(B),I.logUpstreamResponseBody(P.rawText??""),I.recordMetrics(),I.recordBodySizes(x,P.totalBytesReceived),M?.end();const z=Ch($),J={inputTokens:P.usage.inputTokens,outputTokens:P.usage.outputTokens,cacheCreationTokens:P.usage.cacheCreationInputTokens,cacheReadTokens:P.usage.cacheReadInputTokens};z?(I.setError(z.errorType,z.message),I.end(z.status,Date.now()-l),h(z.status,O,r.type,z.errorType,z.message,J)):(I.end(200,Date.now()-l),h(200,O,r.type,void 0,void 0,J)),m({phase:"upstream_response",headers:o,body:P.rawText??"",bodySize:P.totalBytesReceived,contentType:o["content-type"]??"text/event-stream",account:O,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:O,accountType:r.type,attempt:c,responseStatus:200,durationMs:Date.now()-l})}).catch(P=>{I.setError("stream_telemetry_error",P instanceof Error?P.message:String(P)),M?.end(),I.end(500,Date.now()-l),h(500,O,r.type,"stream_telemetry_error",P instanceof Error?P.message:String(P))})}catch{_=i.then(k=>{X2(k,r);const A=Ch(k);d?.end(),A?(a.setError(A.errorType,A.message),a.end(A.status,Date.now()-l),h(A.status,r.label,r.type,A.errorType,A.message)):(a.end(n.status,Date.now()-l),h(n.status,r.label,r.type))}).catch(()=>{})}else{d?.end();try{const{stream:k,telemetry:A}=F2({captureRawText:!0});v=v.pipeThrough(k);const I=r.label,M=r.key;_=Promise.all([A,y,i]).then(([R,x,O])=>{const N=U2(O,R.streamErrorMessage);X2(N,r);const P=Ch(N),D={inputTokens:R.usage.inputTokens,outputTokens:R.usage.outputTokens,cacheCreationTokens:R.usage.cacheCreationInputTokens,cacheReadTokens:R.usage.cacheReadInputTokens};Ule(M,R.model,D),Fle(I,R.model,D),P?h(P.status,I,r.type,P.errorType,P.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:x.text,bodySize:x.totalBytes,contentType:o["content-type"]??"text/event-stream",account:I,accountType:r.type,attempt:c,responseStatus:200,durationMs:Date.now()-l})}).catch(R=>{const x=R instanceof Error?R.message:String(R);h(500,r.label,r.type,"stream_telemetry_error",x)})}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=>{X2(k,r);const A=Ch(k);A?h(A.status,r.label,r.type,A.errorType,A.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 aan(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(Cir(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($le(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 lan(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=zw(o.headers,{model:n});if(g){r.quota=Ty(r.quota,g);const b=Ple(r,g,Date.now());b?.kind==="cooled"?wd(t.key,b.coolingUntil,b.coolingReason).catch(()=>{}):b?.kind==="cleared"&&by(t.key,b.coolingUntil).catch(()=>{}),Sy(t.label,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(Cir(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($le(_)),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 can(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:A,sawTransientFailure:I,sawNetworkError:M}=e;an(n.label,n.type,401),g(401,"authentication_error","received 401 from Anthropic",{retryable:!0});let R=b,x=T,O=k,N=A,P=I,D=M,L=h,$=!1,U="received 401 from Anthropic";for(let j=0;j<vA;j++){f.always(`[proxy] \u2190 401 account=${n.label} refreshing (attempt ${j+1}/${vA})`);const B=await x2(n,n.persistTarget);if(!B.success){if(U=`refresh failed for account=${n.label} attempt ${j+1}/${vA}: ${B.error?.slice(0,200)??"unknown"}`,R=U,Cy(B))await Bp(n,o,"refresh_invalid"),x=rF(n.label),f.always(`[proxy] account=${n.label} refresh token rejected; disabled until re-authentication`);else{const re=await eF(n,o);P=!0,f.always(`[proxy] account=${n.label} refresh temporarily unavailable (${B.status??"network"}); cooling until ${new Date(re).toISOString()} and rotating`)}break}n.persistTarget&&await A2(n.persistTarget,n),await tF(n,o),s.authorization=`Bearer ${n.token}`;const z=m(),J=Date.now();xw(n.label,n.type);const Y=(re,G,K,Ce)=>g(re,G,K,{...Ce,attempt:z,attemptDurationMs:Ce?.attemptDurationMs??Date.now()-J}),ie=i(n.token).bodyStr,ce=Date.now();y({phase:"upstream_request",headers:s,body:ie,bodySize:Buffer.byteLength(ie,"utf8"),contentType:s["content-type"]??"application/json",account:n.label,accountType:n.type,attempt:z,metadata:{upstreamMethod:"POST",upstreamUrl:a}});try{const re=await xle(a,{method:"POST",headers:s,body:ie,signal:AbortSignal.timeout(_A)});if(re.ok){$=!0,o.consecutiveRefreshFailures=0,f.always(`[proxy] \u2190 200 account=${n.label} (after ${j+1} refresh(es))`);const H=r.stream?await Mir({ctx:t,body:r,account:n,accountState:o,response:re,tracer:u,requestStartTime:d,fetchStartMs:ce,attemptNumber:z,finalBodyStr:ie,upstreamSpan:L,logAttempt:Y,logProxyBody:y,logFinalRequest:_,onStreamTerminal:v}):{response:await lan({account:n,accountState:o,requestedModel:r.model,retryResp:re,tracer:u,requestStartTime:d,fetchStartMs:ce,attemptNumber:z,finalBodyStr:ie,upstreamSpan:L,logAttempt:Y,logProxyBody:y,logFinalRequest:_})};if("retryNextAccount"in H){const se=H.failure;return{continueLoop:!0,...se?.retryDelayMs?{retryDelayMs:se.retryDelayMs}:{},lastError:se?.message??R,authFailureMessage:x,entitlementFailure:O,sawRateLimit:N||!!se?.rateLimit,sawTransientFailure:P||!!(se&&!se.rateLimit),sawNetworkError:D,upstreamSpan:void 0}}return{response:H.response,holdsAccountAdmission:H.holdsAccountAdmission,continueLoop:!1,lastError:R,authFailureMessage:x,entitlementFailure:O,sawRateLimit:N,sawTransientFailure:P,sawNetworkError:D,upstreamSpan:void 0}}const G=re.status,K=await re.text(),Ce={};re.headers.forEach((H,se)=>{Ce[se]=H});const be={...Ce};delete be.authorization,delete be["x-api-key"];const ge=K.length>4e3?K.slice(0,4e3)+"...[truncated]":K;if(u?.logUpstreamResponseHeaders(be),u?.logUpstreamResponseBody(ge),y({phase:"upstream_response",headers:be,body:ge,bodySize:Buffer.byteLength(K,"utf8"),contentType:Ce["content-type"]??"application/json",account:n.label,accountType:n.type,attempt:z,responseStatus:G,durationMs:Date.now()-ce}),U=`retry ${j+1}/${vA} failed with status ${G}`,R=K,f.debug(`[proxy] retry ${j+1} failed: ${G} ${K.substring(0,120)}`),G===429&&Oir(Ce,K))return f.always(`[proxy] \u2190 429 account=${n.label} anti-abuse/construction rejection after OAuth refresh \u2014 returning non-retryable request error`),Y(429,"construction_rejection",K),u?.setError("construction_rejection",K.slice(0,500)),L?.end(),{response:Pir({terminalError:Nir(),account:n,tracer:u,requestStartTime:d,attemptNumber:z,logProxyBody:y,logFinalRequest:_}),continueLoop:!1,lastError:K,authFailureMessage:x,entitlementFailure:O,sawRateLimit:N,sawTransientFailure:P,sawNetworkError:D,upstreamSpan:void 0};if(G===429){N=!0;const H=Date.now(),se=zw(Ce,{model:r.model});se&&(o.quota=Ty(o.quota,se));const ye=Rle(se,B2(Ce["retry-after"]??null),H,S2(Ce)),Q=ye.reason==="transient"?"transient":"quota";an(n.label,n.type,G,Q),Y(429,"rate_limit_error",K,{retryable:!0,rateLimitKind:Q,cooldownReason:ye.reason}),(!o.coolingUntil||ye.coolingUntil>o.coolingUntil)&&(o.coolingUntil=ye.coolingUntil,o.coolingReason=ye.reason),se&&Sy(n.label,se).catch(()=>{}),await wd(n.key,o.coolingUntil??ye.coolingUntil,o.coolingReason??ye.reason).catch(()=>{}),xy(n.key,l.length,c[0]?.key);break}if(G===401||G===402||G===403){if(qle(G,K)){const H=kh(K);an(n.label,n.type,G),Y(G,"permission_error",Or(K)),O={status:G,accounts:[...O?.accounts??[],n.label],message:O?.message??H.message??Or(K),...H.errorCode?{errorCode:H.errorCode}:{}},n.type==="oauth"&&jir(G,K)&&await Bp(n,o,"entitlement_blocked"),U=`entitlement blocked for account=${n.label}`,R=U,f.always(`[proxy] \u2190 ${G} account=${n.label} entitlement blocked after refresh; advancing to next account`);break}an(n.label,n.type,G),Y(G,"authentication_error",Or(K),{retryable:!0}),j<vA-1&&await zp(1e3);continue}if(Gir(G,K)){an(n.label,n.type,G),Y(G,"api_error",Or(K),{retryable:!0}),P=!0;break}Y(G,"api_error",Or(K));try{return _(G,n.label,n.type,"api_error",Or(K)),{response:JSON.parse(K),continueLoop:!1,lastError:R,authFailureMessage:x,entitlementFailure:O,sawRateLimit:N,sawTransientFailure:P,sawNetworkError:D,upstreamSpan:L}}catch{return _(G,n.label,n.type,"api_error",Or(K)),{response:Gl(G,K),continueLoop:!1,lastError:R,authFailureMessage:x,entitlementFailure:O,sawRateLimit:N,sawTransientFailure:P,sawNetworkError:D,upstreamSpan:L}}}catch(re){D=!0,an(n.label,n.type,502);const G=re instanceof Error?re.message:String(re);U=`network error on retry ${j+1}: ${G}`,R=U;const K=jle(re);if(Y(502,"network_error",G,{retryable:K,errorCode:EA(re)??"unknown"}),f.debug(`[proxy] ${U}`),!K)return L?.end(),{response:Dir({account:n,tracer:u,requestStartTime:d,attemptNumber:z,logProxyBody:y,logFinalRequest:_,errorType:"network_error",message:G}),continueLoop:!1,lastError:R,authFailureMessage:x,entitlementFailure:O,sawRateLimit:N,sawTransientFailure:P,sawNetworkError:D,upstreamSpan:void 0};break}}return $||(R=U,f.always(`[proxy] \u26A0 account=${n.label} auth retries exhausted, rotating to next account`),u?.setError("authentication_error",U),u?.recordRetry(n.label,"auth_exhausted"),L?.end(),L=void 0,xy(n.key,l.length,c[0]?.key)),{continueLoop:!0,lastError:R,authFailureMessage:x,entitlementFailure:O,sawRateLimit:N,sawTransientFailure:P,sawNetworkError:D,upstreamSpan:L}}function Ble(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=Gl(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 Pir(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),Ble({responseStatus:t.status,account:r,errBody:t.body,errRespHeaders:t.headers,requestStartTime:o,attemptNumber:s,logProxyBody:i,logFinalRequest:a,errorType:t.errorType})}function Dir(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=Gl(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 uan(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:_}=e;let b=h,T=g,k=y,A=v,I=_;const M=await t.text(),R={};if(t.headers.forEach((x,O)=>{R[O]=x}),i?.logUpstreamResponseHeaders(R),i?.logUpstreamResponseBody(M),d({phase:"upstream_response",headers:R,body:M,bodySize:Buffer.byteLength(M,"utf8"),contentType:R["content-type"]??"application/json",account:r.label,accountType:r.type,attempt:c,responseStatus:t.status,durationMs:Date.now()-l}),Ean(t.status,M))return San(t.status,M)?(f.always(`[proxy] \u2190 ${t.status} account=${r.label} beta unavailable for subscription; advancing to next account`),u(t.status,"invalid_request_error",Or(M)),i?.setError("invalid_request_error",Or(M)),i?.recordRetry(r.label,"beta_unavailable"),xy(r.key,o.length,s[0]?.key),b=Or(M),{continueLoop:!0,lastError:b,authFailureMessage:T,sawTransientFailure:k,invalidRequestFailure:A,entitlementFailure:I,upstreamSpan:void 0}):(f.always(`[proxy] \u2190 ${t.status} upstream invalid_request_error`),u(t.status,"invalid_request_error",Or(M)),i?.setError("invalid_request_error",Or(M)),A={status:t.status,body:M,contentType:R["content-type"]},b=Or(M),{continueLoop:!1,lastError:b,authFailureMessage:T,sawTransientFailure:k,invalidRequestFailure:A,entitlementFailure:I,upstreamSpan:void 0});if(r.type==="oauth"&&qle(t.status,M)){const x=kh(M);return an(r.label,r.type,t.status),I={status:t.status,accounts:[...I?.accounts??[],r.label],message:I?.message??x.message??Or(M),...x.errorCode?{errorCode:x.errorCode}:{}},f.always(`[proxy] \u2190 ${t.status} account=${r.label} entitlement blocked${x.errorCode?` (${x.errorCode})`:""}; advancing to next account`),u(t.status,"permission_error",Or(M)),i?.setError("permission_error",Or(M)),i?.recordRetry(r.label,"entitlement_blocked"),r.type==="oauth"&&jir(t.status,M)&&await Bp(r,n,"entitlement_blocked"),xy(r.key,o.length,s[0]?.key),b=Or(M),{continueLoop:!0,lastError:b,authFailureMessage:T,sawTransientFailure:k,invalidRequestFailure:A,entitlementFailure:I,upstreamSpan:void 0}}if((t.status===401||t.status===402||t.status===403)&&r.type==="oauth"&&!r.refreshToken)return an(r.label,r.type,t.status),await Bp(r,n,"missing_refresh_token"),T=rF(r.label),f.always(`[proxy] \u2190 ${t.status} account=${r.label} (auth failure, no refresh token)`),b=M,u(t.status,"authentication_error",Or(M)),i?.setError("authentication_error",Or(M)),i?.recordRetry(r.label,"auth_no_refresh"),xy(r.key,o.length,s[0]?.key),{continueLoop:!0,lastError:b,authFailureMessage:T,sawTransientFailure:k,invalidRequestFailure:A,entitlementFailure:I,upstreamSpan:void 0};if((t.status===401||t.status===402||t.status===403)&&r.type==="api_key")return an(r.label,r.type,t.status),T="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)`),b=M,u(t.status,"authentication_error",Or(M)),i?.setError("authentication_error",Or(M)),i?.recordRetry(r.label,"auth_api_key"),xy(r.key,o.length,s[0]?.key),{continueLoop:!0,lastError:b,authFailureMessage:T,sawTransientFailure:k,invalidRequestFailure:A,entitlementFailure:I,upstreamSpan:void 0};if(t.status===404)return f.always(`[proxy] \u2190 404 account=${r.label}`),u(404,"not_found_error",Or(M)),i?.setError("not_found_error",Or(M)),i?.end(404,Date.now()-a),{response:Ble({responseStatus:404,account:r,errBody:M,errRespHeaders:R,requestStartTime:a,attemptNumber:c,logProxyBody:d,logFinalRequest:m,errorType:"not_found_error"}),continueLoop:!1,lastError:b,authFailureMessage:T,sawTransientFailure:k,invalidRequestFailure:A,entitlementFailure:I,upstreamSpan:void 0};if(Gir(t.status,M)){const x=kan(t.status,M);return an(r.label,r.type,t.status,t.status===429?"transient":void 0),k=!0,f.always(`[proxy] \u2190 ${t.status} account=${r.label} (${x?"overloaded":"transient"})`),b=M,u(t.status,"api_error",Or(M),t.status===429?{retryable:!0,rateLimitKind:"transient",cooldownReason:"transient"}:void 0),i?.setError(x?"overloaded_error":"transient_error",Or(M)),i?.recordRetry(r.label,x?"overloaded":"transient"),{continueLoop:!0,retrySameAccount:!x,...x?{retryDelayMs:Uir(c)}:{},lastError:b,authFailureMessage:T,sawTransientFailure:k,invalidRequestFailure:A,entitlementFailure:I,upstreamSpan:void 0}}return f.always(`[proxy] \u2190 ${t.status} account=${r.label}`),f.debug(`[claude-proxy] error body: ${M.substring(0,200)}`),u(t.status,"api_error",Or(M)),i?.setError("api_error",Or(M)),i?.end(t.status,Date.now()-a),{response:Ble({responseStatus:t.status,account:r,errBody:M,errRespHeaders:R,requestStartTime:a,attemptNumber:c,logProxyBody:d,logFinalRequest:m,errorType:"api_error"}),continueLoop:!1,lastError:b,authFailureMessage:T,sawTransientFailure:k,invalidRequestFailure:A,entitlementFailure:I,upstreamSpan:void 0}}function dan(e){const{ctx:t,body:r,clientRequestBody:n}=e;let o;try{o=sle.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();Knn({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?Tle:void 0),T=h?g||void 0:m>=400?Ele:void 0;m>=400?Fx(m,b,T,{requestId:t.requestId,errorType:y,terminalOutcome:y==="client_cancelled"?"client_cancelled":y?.includes("stream")?"stream_error":"handler_error",message:v,errorCode:_?.errorCode}):K$(b,T);const k=o?.getTraceContext();Eh({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??"",accountType:T??"",...ale(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}:{},...k?{traceId:k.traceId,spanId:k.spanId}:{},...a?{routingDecision:a}:{}})},d=(m,h,g,y)=>{const v=Gl(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 pan(e){const{ctx:t,body:r,toolCount:n,requestStart:o,tracer:s,account:i,attemptNumber:a}=e,l=Date.now();return(c,u,d,m)=>{const h=Date.now(),g=s?.getTraceContext();Lnn({timestamp:new Date().toISOString(),requestId:t.requestId,attempt:m?.attempt??a,method:t.method,path:t.path,model:r.model,stream:!!r.stream,toolCount:n,account:i.label,accountType:i.type,responseStatus:c,responseTimeMs:h-o,attemptDurationMs:m?.attemptDurationMs??h-l,...u?{errorType:u}:{},...d?{errorMessage:d}:{},...m?.errorCode?{errorCode:m.errorCode}:{},...m?.transportScope?{transportScope:m.transportScope}:{},...m?.inputTokens!==void 0?{inputTokens:m.inputTokens}:{},...m?.outputTokens!==void 0?{outputTokens:m.outputTokens}:{},...m?.cacheCreationTokens!==void 0?{cacheCreationTokens:m.cacheCreationTokens}:{},...m?.cacheReadTokens!==void 0?{cacheReadTokens:m.cacheReadTokens}:{},...m?.retryable!==void 0?{retryable:m.retryable}:{},...m?.rateLimitKind?{rateLimitKind:m.rateLimitKind}:{},...m?.cooldownReason?{cooldownReason:m.cooldownReason}:{},...g?{traceId:g.traceId,spanId:g.spanId}:{}})}}async function man(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(Bae(t)){const R=await x2(t,t.persistTarget);if(R.success)t.persistTarget&&await A2(t.persistTarget,t),await tF(t,r);else return h=`token refresh failed for account=${t.label}: ${R.error?.slice(0,200)??"unknown"}`,Cy(R)?(await Bp(t,r,"refresh_invalid"),g=rF(t.label)):await eF(t,r),d(Cy(R)?401:503,Cy(R)?"authentication_error":"token_refresh_unavailable",String(h)),{continueLoop:!0,lastError:h,authFailureMessage:g}}const y=t.type==="oauth",v={};for(const[R,x]of Object.entries(o))typeof x=="string"&&(v[R]=x);const _=y?await Iin(t.label,t.key,v,n):null,b={};for(const[R,x]of Object.entries(o)){const O=R.toLowerCase();typeof x=="string"&&!z2.has(O)&&(b[O]=x)}if(b["content-type"]="application/json",y?(b.authorization=`Bearer ${t.token}`,delete b["x-api-key"],Sin(b,_)):(b["x-api-key"]=t.token,delete b.authorization),b["user-agent"]||(b["user-agent"]=Tg),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"]??"",x=new Set(R.split(",").map(O=>O.trim()).filter(Boolean));for(const O of s?WC:Ein)x.add(O);b["anthropic-beta"]=[...x].join(",")}else{const R=(b["anthropic-beta"]??"").split(",").map(x=>x.trim()).filter(x=>x&&!WC.includes(x)).join(",");R?b["anthropic-beta"]=R:delete b["anthropic-beta"]}const T=R=>y?Rin(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 A=k.bodyStr;f.always(`[proxy] \u2192 account=${t.label} (${t.type})`),xw(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(A),Object.assign(b,a.getTraceHeaders())),m({phase:"upstream_request",headers:b,body:A,bodySize:Buffer.byteLength(A,"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:A,fetchStartMs:I,upstreamSpan:M}}function Oir(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 Nir(){return{status:400,body:JSON.stringify(Gl(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 han(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 A=_;let I;try{I=await xle(t,{method:"POST",headers:r,body:n,signal:AbortSignal.timeout(_A)})}catch(M){const R=jle(M),x=ban(M);k=!0,an(s.label,s.type,502);const O=EA(M)??"unknown",N=M instanceof Error?M.message:String(M);if(b=N,f.always(`[proxy] fetch error account=${s.label} code=${O} (${R?"retryable":"terminal"}): ${N}`),u(502,"network_error",N,{retryable:R,errorCode:O,transportScope:x}),c?.setError("network_error",N),R&&c?.recordRetry(s.label,"network_error"),A?.end(),!R)throw M;return{continueLoop:!0,retrySameAccount:!0,transportScope:x,errorCode:O,lastError:b,sawRateLimit:T,sawNetworkError:k,upstreamSpan:void 0}}if(I.status===429){const M=B2(I.headers.get("retry-after")),R={};I.headers.forEach((U,j)=>{R[j]=U}),b=await I.text();const x={...R};delete x.authorization,delete x["x-api-key"];const O=String(b).length>4e3?String(b).slice(0,4e3)+"...[truncated]":String(b);if(c?.logUpstreamResponseHeaders(x),c?.logUpstreamResponseBody(O),d({phase:"upstream_response",headers:x,body:O,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}),Oir(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)),A?.end(),{continueLoop:!1,terminalError:Nir(),lastError:b,sawRateLimit:T,sawNetworkError:k,upstreamSpan:void 0};T=!0;const N=Date.now(),P=zw(R,{model:o}),D=S2(R),L=Rle(P,M,N,D),$=L.reason==="transient"?"transient":"quota";return an(s.label,s.type,429,$),f.always(`[proxy] \u2190 429 account=${s.label} reason=${L.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 ${L.rotateImmediately?`rotate now, cool ${Mle(L.coolingUntil,N)}m`:"retry same account (transient)"}`),u(429,"rate_limit_error",String(b),{retryable:!0,rateLimitKind:$,cooldownReason:L.reason}),c?.setError("rate_limit_error",String(b).slice(0,500)),c?.recordRetry(s.label,"rate_limit"),A?.end(),{continueLoop:!0,retrySameAccount:!L.rotateImmediately,retryAfterMs:M,cooldownPlan:L,...P?{quota:P}:{},lastError:b,sawRateLimit:T,sawNetworkError:k,upstreamSpan:void 0}}return{continueLoop:!1,response:I,lastError:b,sawRateLimit:T,sawNetworkError:k,upstreamSpan:A}}function fan(e){return e.invalidRequestFailure===null}async function gan(e){const{ctx:t,body:r,modelRouter:n,tracer:o,requestStartTime:s,accountStrategy:i,primaryAccountKey:a,accountAllowlist:l,quotaRoutingEnabled:c=Ole(),sessionSoftLimit:u=Nle(),sessionResetToleranceMs:d=TA(),buildLoggedClaudeError:m,logProxyBody:h,logFinalRequest:g,setRoutingDecision:y}=e,v=Hae(r),_=await Yin({ctx:t,body:r,tracer:o,requestStartTime:s,accountStrategy:i,primaryAccountKey:a,accountAllowlist:l,quotaRoutingEnabled:c,sessionSoftLimit:u,sessionResetToleranceMs:d,buildLoggedClaudeError:m,setRoutingDecision:y});if("response"in _){const z=await Air({body:r,logFinalRequest:g});return z||_.response}const{accounts:b,enabledAccounts:T,orderedAccounts:k,bodyStr:A,requestStart:I,toolCount:M,url:R,clientHeaders:x,isClaudeClientRequest:O}=_,N=din(),P={lastError:void 0,sawRateLimit:!1,sawNetworkError:!1,sawTransientFailure:!1,invalidRequestFailure:null,authFailureMessage:null,authCooldownMessage:null,entitlementFailure:null,scopedExhaustion:null,attemptNumber:0},D=o?.startAccountSelection();let $=k.filter(z=>!mir(z.key));if($.length===0&&($=await ain(k)),$.length===0&&k.length>0){const z=k.map(Y=>ll(Y.key)),J=z.some(Y=>Y.coolingReason!=="auth");if(P.sawRateLimit=J,P.sawTransientFailure=!J,P.lastError=J?"All Anthropic accounts have active rate-limit cooldowns":"All Anthropic accounts have active authentication cooldowns",!J){const Y=Math.min(...z.map(ie=>ie.coolingUntil??Number.POSITIVE_INFINITY));P.authCooldownMessage=`All ${k.length} Anthropic accounts are temporarily unavailable while OAuth refresh is cooling. Earliest retry at ${new Date(Y).toISOString()}.`}}const U=fin($,typeof r.model=="string"?r.model:void 0,Date.now(),N);U.eligible.length>0?$=U.eligible:U.exhaustion&&(P.scopedExhaustion=U.exhaustion,P.lastError=`Model-scoped limit exhausted for ${U.exhaustion.model}`,$=[]);const j=n?.getMaxInflightPerAccount?.();let B;j!==void 0&&$.length>0&&$.every(z=>!Xsn(z.key,j))&&(B=await ein($.map(z=>z.key),j,t.abortSignal));e:for(const[z,J]of $.entries()){const Y=z<$.length-1,ie=ll(J.key);let ce=0,re=0;for(;;){const G=await Qw.acquire(t.abortSignal);if(G.allowed===!1){P.sawNetworkError=!0,P.lastTransportErrorCode=G.errorCode??void 0,P.lastTransportScope=G.transportScope,P.lastError=`Anthropic transport recovery probe failed (${G.errorCode??"unknown"})`;break e}P.attemptNumber+=1,o&&P.attemptNumber===1&&D&&(o.setAccountSelection({strategy:i,accountsTotal:b.length,accountsHealthy:T.length,selectedAccount:J.label,accountType:J.type}),D.end());const K=pan({ctx:t,body:r,toolCount:M,requestStart:I,tracer:o,account:J,attemptNumber:P.attemptNumber}),Ce=await man({account:J,accountState:ie,bodyStr:A,clientHeaders:x,isClaudeClientRequest:O,url:R,tracer:o,attemptNumber:P.attemptNumber,currentLastError:P.lastError,currentAuthFailureMessage:P.authFailureMessage,logAttempt:K,logProxyBody:h});if(P.lastError=Ce.lastError,P.authFailureMessage=Ce.authFailureMessage,Ce.continueLoop||!Ce.headers||!Ce.buildUpstreamBody||!Ce.finalBodyStr||Ce.fetchStartMs===void 0){G.probe&&Qw.reportProbeAbandoned(G);continue e}let be;if(B?.accountKey===J.key?(be=B.lease,B=void 0):(be=Zsn(J.key,j),be&&B&&(B.lease.release(),B=void 0)),!be){G.probe&&Qw.reportProbeAbandoned(G);continue e}let ge=!1;try{let H;try{H=await han({url:R,headers:Ce.headers,finalBodyStr:Ce.finalBodyStr,requestedModel:r.model,account:J,accountState:ie,enabledAccounts:T,orderedAccounts:k,tracer:o,logAttempt:K,logProxyBody:h,fetchStartMs:Ce.fetchStartMs,attemptNumber:P.attemptNumber,currentLastError:P.lastError,currentSawRateLimit:P.sawRateLimit,currentSawNetworkError:P.sawNetworkError,upstreamSpan:Ce.upstreamSpan})}catch(me){throw G.probe&&Qw.reportProbeAbandoned(G),me}if(H.transportScope?Qw.reportTransportFailure(H.errorCode,H.transportScope,G):Qw.reportSuccess(G),P.lastError=H.lastError,P.sawRateLimit=H.sawRateLimit,P.sawNetworkError=H.sawNetworkError,H.transportScope&&(P.lastTransportScope=H.transportScope,P.lastTransportErrorCode=H.errorCode),H.terminalError)return Pir({terminalError:H.terminalError,account:J,tracer:o,requestStartTime:s,attemptNumber:P.attemptNumber,logProxyBody:h,logFinalRequest:g});if(H.continueLoop||!H.response){if(H.cooldownPlan){const me=H.cooldownPlan;H.quota&&(ie.quota=Ty(ie.quota,H.quota),Sy(J.label,H.quota).catch(()=>{}));let $e=!1;(!ie.coolingUntil||me.coolingUntil>ie.coolingUntil)&&(ie.coolingUntil=me.coolingUntil,ie.coolingReason=me.reason,$e=!0),$e&&await wd(J.key,ie.coolingUntil,ie.coolingReason??me.reason).catch(()=>{});const Se=H.retrySameAccount?sin(J.key,me.coolingUntil):void 0;if(H.retrySameAccount&&H.retryAfterMs!==void 0&&re<kle&&Se!==void 0){re+=1;const ne=Math.min(H.retryAfterMs||1e3,Qsr),Fe=Math.min(Qsr,Bir(ne*Se));f.always(`[proxy] retrying same account=${J.label} after transient 429 (shared slot ${Se}/${kle}) in ${Fe}ms`),await zp(Fe);continue}xy(J.key,T.length,k[0]?.key),f.always(`[proxy] account=${J.label} rate-limited (${me.reason}); cooling ~${Mle(me.coolingUntil,Date.now())}m until ${new Date(me.coolingUntil).toISOString()}, rotating`),me.rotateImmediately&&vin(J,$[z+1],me.coolingUntil,u);continue e}if(H.retrySameAccount&&ce<j2){ce+=1;const me=Fir(ce);f.always(`[proxy] retrying same account=${J.label} after transient network error (${ce}/${j2}) in ${me}ms`),await zp(me);continue}if(H.retrySameAccount&&!H.transportScope&&f.always(`[proxy] exhausted transient same-account retries for account=${J.label}; rotating`),H.transportScope){f.always(`[proxy] Anthropic ${H.transportScope} failure code=${H.errorCode??"unknown"}; suppressing cross-account rotation after ${ce+1} attempts`);break e}continue e}let se=H.upstreamSpan;const ye=H.response;if(ye.status===401&&J.type==="oauth"&&J.refreshToken){const me=await can({ctx:t,body:r,account:J,accountState:ie,headers:Ce.headers,buildUpstreamBody:Ce.buildUpstreamBody,url:R,enabledAccounts:T,orderedAccounts:k,tracer:o,requestStartTime:s,allocateAttemptNumber:()=>(P.attemptNumber+=1,P.attemptNumber),upstreamSpan:se,logAttempt:K,logProxyBody:h,logFinalRequest:g,onStreamTerminal:be.release,lastError:P.lastError,authFailureMessage:P.authFailureMessage,entitlementFailure:P.entitlementFailure,sawRateLimit:P.sawRateLimit,sawTransientFailure:P.sawTransientFailure,sawNetworkError:P.sawNetworkError});if(P.lastError=me.lastError,P.authFailureMessage=me.authFailureMessage,P.entitlementFailure=me.entitlementFailure,P.sawRateLimit=me.sawRateLimit,P.sawTransientFailure=me.sawTransientFailure,P.sawNetworkError=me.sawNetworkError,se=me.upstreamSpan,me.response!==void 0)return ge=me.holdsAccountAdmission===!0,me.response;if(me.continueLoop){Y&&me.retryDelayMs&&(f.always(`[proxy] pacing cross-account SSE overload rotation for ${me.retryDelayMs}ms after auth refresh`),await zp(me.retryDelayMs));continue e}}if(!ye.ok){const me=await uan({response:ye,account:J,accountState:ie,enabledAccounts:T,orderedAccounts:k,tracer:o,requestStartTime:s,fetchStartMs:Ce.fetchStartMs,attemptNumber:P.attemptNumber,logAttempt:K,logProxyBody:h,logFinalRequest:g,lastError:P.lastError,authFailureMessage:P.authFailureMessage,sawTransientFailure:P.sawTransientFailure,invalidRequestFailure:P.invalidRequestFailure,entitlementFailure:P.entitlementFailure});if(P.lastError=me.lastError,P.authFailureMessage=me.authFailureMessage,P.sawTransientFailure=me.sawTransientFailure,P.invalidRequestFailure=me.invalidRequestFailure,P.entitlementFailure=me.entitlementFailure,me.response!==void 0)return me.response;if(me.continueLoop){if(me.retrySameAccount&&ce<j2){ce+=1;const $e=Fir(ce);f.always(`[proxy] retrying same account=${J.label} after transient upstream ${ye.status} (${ce}/${j2}) in ${$e}ms`),await zp($e);continue}me.retrySameAccount&&f.always(`[proxy] exhausted transient same-account retries for account=${J.label}; rotating`),Y&&me.retryDelayMs&&(f.always(`[proxy] pacing cross-account overload rotation for ${me.retryDelayMs}ms`),await zp(me.retryDelayMs));continue e}break e}if(ie.coolingUntil&&Date.now()>=ie.coolingUntil){const me=ie.coolingUntil;ie.coolingUntil=void 0,ie.coolingReason=void 0,by(J.key,me).catch(()=>{})}const Q=await Mir({ctx:t,body:r,account:J,accountState:ie,response:ye,tracer:o,requestStartTime:s,fetchStartMs:Ce.fetchStartMs,attemptNumber:P.attemptNumber,finalBodyStr:Ce.finalBodyStr,upstreamSpan:se,logAttempt:K,logProxyBody:h,logFinalRequest:g,onStreamTerminal:be.release,poolAccounts:T});if("retryNextAccount"in Q){Q.failure&&(P.lastError=Q.failure.message,P.sawRateLimit||=Q.failure.rateLimit,P.sawTransientFailure||=!Q.failure.rateLimit,Y&&Q.failure.retryDelayMs&&(f.always(`[proxy] pacing cross-account SSE overload rotation for ${Q.failure.retryDelayMs}ms`),await zp(Q.failure.retryDelayMs)));continue e}return ge=Q.holdsAccountAdmission===!0,Q.response}finally{ge||be.release()}}}if(B?.lease.release(),P.attemptNumber===0&&D?.end(),fan(P)){let z;const J=await Air({body:r,logFinalRequest:g});if(J)return J;const Y=await Xin({ctx:t,body:r,parsedFallbackRequest:v,modelRouter:n,tracer:o,requestStartTime:s,logProxyBody:h,logFinalRequest:g});if(Y.response)return Y.response;if(z=Y.lastErrorMessage,!P.sawRateLimit&&n?.isAutoFallbackEnabled?.()){const ie=await Qin({ctx:t,body:r,tracer:o,requestStartTime:s,logProxyBody:h,logFinalRequest:g});if(ie.response)return ie.response;z=ie.lastErrorMessage??z}P.fallbackFailureMessage=z}{const z=k[0],J=z?Hl.get(z.key):void 0;bA(t,{quota:J?.quota??null,source:J?.quota?"snapshot":"none",...z?{account:z}:{},...J?{accountState:J}:{},attempt:P.attemptNumber,poolAccounts:T})}return oan({tracer:o,requestStartTime:s,authFailureMessage:P.authFailureMessage,authCooldownMessage:P.authCooldownMessage,invalidRequestFailure:P.invalidRequestFailure,entitlementFailure:P.entitlementFailure,scopedExhaustion:P.scopedExhaustion,sawNetworkError:P.sawNetworkError,sawTransientFailure:P.sawTransientFailure,sawRateLimit:P.sawRateLimit,lastError:P.lastError,lastTransportErrorCode:P.lastTransportErrorCode,lastTransportScope:P.lastTransportScope,fallbackFailureMessage:P.fallbackFailureMessage,orderedAccounts:k,buildLoggedClaudeError:m,logProxyBody:h,logFinalRequest:g})}function Lir(e){return e!==void 0&&"runtimeConfigProvider"in e&&typeof e.runtimeConfigProvider=="function"}function $ir(e){const{ctx:t,body:r,status:n,message:o,errorType:s}=e;return Fx(n,Tle,Ele,{requestId:t.requestId,errorType:s,terminalOutcome:"handler_error",message:o}),Eh({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:Tle,accountType:Ele,responseStatus:n,responseTimeMs:0,errorType:s,errorMessage:o}),Gl(n,o)}var yan=new Set(["oauth","api_key"]);function zle(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?Math.round(e*1e3):null}function van(e){if(!e||typeof e!="object")return null;const t={...e};return t.sessionResetAtMs=zle(t.sessionResetAt),t.weeklyResetAtMs=zle(t.weeklyResetAt),Array.isArray(t.windows)&&(t.windows=t.windows.map(r=>{const n={...r};return n.resetsAtMs=zle(n.resetsAt),n.severity=n.severity??(n.status==="rejected"?"critical":"normal"),n.isActive=n.isActive??!1,n})),t}function Q2(e){return e==="allowed"?"ok":e==="rejected"||e==="throttled"?"degraded":"unknown"}function _an(e,t="",r="fill-first",n=!1,o,s){const i=Lir(s)?s.accountAllowlist:s,a=Lir(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:Ole(),sessionSoftLimit:Nle(),sessionResetToleranceMs:TA(),useOverage:"auto"};Lle(c.useOverage);const u=c.modelRouter,d=l.body;if(typeof d?.model!="string"||!Array.isArray(d?.messages))return $ir({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 $ir({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}=dan({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?Din({ctx:l,body:d,clientRequestBody:g,tracer:y,requestStartTime:v,logProxyBody:_,logFinalRequest:b}):gan({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})):Pin({ctx:l,body:d,route:{provider:h.provider,model:h.model},modelRouter:u,tracer:y,requestStartTime:v,logProxyBody:_})}catch(A){const I=A instanceof Error?A.message:String(A);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: ${A instanceof Error?A.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 wie(u);if(!d||!d.leaseSecret||!Hin(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 Gin(d,h);const g=await qin(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:Psr(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 Ry(l.headers);return Iy(c)?c.body:{ok:!0,protocol:Vin,capabilities:Win,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 Ry(l.headers);if(Iy(c))return c.body;if(c.grant.state!=="active")return Jw(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 Msn({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 Ry(l.headers);if(Iy(c))return c.body;const u=await Psn(c.grant.id);if(u.status!=="ready")return{ok:!0,status:u.status};const d=await oXr();return{ok:!0,status:"ready",claim:$on({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 Ry(l.headers);if(Iy(c))return c.body;const u=Number(l.query?.since??0);return{ok:!0,receipts:await vQt(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 Ry(l.headers);if(Iy(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."}}:X$({consumedByYou:m,alreadyNetted:h,grantId:c.grant.id},String(d?.signature??""),u)?{ok:!0,...await _Qt({grantId:c.grant.id,consumedFromPeer:m,peerAlreadyNetted:h})}:Jw("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=$sn(String(c?.note??""));if(!u)return{type:"error",error:{type:"invalid_request_error",message:"That is not a NeuroLink coin note."}};const d=await dXr();if(!c?.redeem)return{ok:!0,...await Fsn(u,d)};const m=await Ry(l.headers);if(Iy(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 Usn({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 Ry(l.headers);if(Iy(c))return c.body;const u=a?.();return{ok:!0,...await Kin(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()=>ton(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 Gl(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(Gw())return Jw("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;Lle(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?(H2||(H2=Dle({accountAllowlist:u}).finally(()=>{H2=null})),H2):Dle({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=P=>!!d&&!!P&&$or(P,d),h=l.query?.refresh==="true";h&&Lle(c?.useOverage);let g={fetchedAt:Date.now(),snapshot:!h,results:[]},y=null;try{g=await Dle({accountAllowlist:u,snapshotOnly:!h})}catch(P){y=P instanceof Error?P.message:String(P)}const{getUsageSnapshot:v}=await Promise.resolve().then(()=>(fie(),WXt)),_=v().stats.accounts,b=Date.now();let T={};try{T=await nA()}catch{}const k=P=>{if(!P)return!1;const D=T[P]?.coolingUntil;return typeof D=="number"&&D>b};let A=new Map,I=null,M="";try{const{readAccountUsage:P,currentUsageDate:D}=await Promise.resolve().then(()=>(NXr(),OQt));M=D(),A=await P(M)}catch(P){I=P instanceof Error?P.message:String(P)}const R=new Map;for(const P of Object.values(_))R.set(P.label,P);const x=[],O=new Set;for(const P of g.results){const D=P.account;O.add(D);const L=R.get(D),$=van(P.quota),U=k(P.key??null);x.push({label:D,key:P.key??null,kind:"account",type:P.type??L?.type??"oauth",status:U?"cooling":Q2($?.weeklyStatus)==="degraded"||Q2($?.sessionStatus)==="degraded"?"exhausted":"active",cooling:U,allowed:null,expired:null,isPrimary:m(P.key??D),requests:L?L.successCount+L.errorCount:null,errors:L?.errorCount??null,rateLimits:L?.rateLimitCount??null,quotaRateLimits:L?.quotaRateLimitCount??null,quota:$?{...$,sessionHealth:Q2($.sessionStatus),weeklyHealth:Q2($.weeklyStatus)}:null,usage:A.get(D)??null})}for(const P of Object.values(_)){if(O.has(P.label))continue;const D=yan.has(P.type);x.push({label:P.label,key:null,kind:D?"account":P.type==="translation"?"translation":"internal",type:P.type,status:D?"unrouted":null,cooling:!1,allowed:null,expired:null,isPrimary:m(P.label),requests:P.successCount+P.errorCount,errors:P.errorCount,rateLimits:P.rateLimitCount,quotaRateLimits:P.quotaRateLimitCount,quota:null,usage:A.get(P.label)??null})}return{generatedAt:Date.now(),usageDate:M,quotaFromSnapshot:!h,usageError:I,quotaError:y,costBasis:"api-equivalent",accounts:x}},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 ll(e){const t=Hl.get(e);if(t)return t;const r={consecutiveRefreshFailures:0,permanentlyDisabled:!1};return Hl.set(e,r),r}function wan(e){const t=ll(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 Bp(e,t,r){try{const{tokenStore:n}=await Promise.resolve().then(()=>(Nx(),lie)),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 eF(e,t){t.consecutiveRefreshFailures+=1;const r=Math.min(t.consecutiveRefreshFailures-1,4),n=Math.min(Jsn,Ksn*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 wd(e.key,s,i).catch(()=>{}),s}async function tF(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 by(e.key,r).catch(()=>{})}function rF(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 Fir(e){const t=Math.min(Math.max(e-1,0),Sle.length-1);return Sle[t]??0}function Uir(e){const t=Math.min(Math.max(e-1,0),Xsr.length-1);return Bir(Xsr[t]??250)}async function zp(e){await new Promise(t=>setTimeout(t,e))}function Bir(e){return e+Math.floor(Math.random()*e*.25)}function EA(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 Td(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=[EA(e),n&&n!==t&&n].filter(Boolean).join(": ");return s?`${t} (${s})`:t}function jle(e){const t=EA(e);return t!==void 0&&["ECONNREFUSED","EADDRNOTAVAIL","ENOTFOUND","EAI_AGAIN","EHOSTUNREACH","UND_ERR_CONNECT_TIMEOUT","UND_ERR_CONNECT"].includes(t)}function ban(e){const t=EA(e);return t==="ENOTFOUND"||t==="EAI_AGAIN"?"shared_provider_transport":"connection_transport"}var Tan=new Set([408,500,502,503,504,520,521,522,523,524,525,526,529]);function kh(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 Ean(e,t){return e===422?!0:kh(t).errorType==="invalid_request_error"||t.includes("invalid_request_error")}function San(e,t){if(e!==400)return!1;const r=kh(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 zir=new Set(["oauth_not_allowed_for_organization","oauth_not_allowed","organization_disabled"]);function qle(e,t){if(e!==401&&e!==402&&e!==403)return!1;const r=kh(t);return r.errorType==="permission_error"?!0:r.errorCode!==void 0&&zir.has(r.errorCode)}function jir(e,t){if(!qle(e,t))return!1;const r=kh(t);return r.errorCode!==void 0&&zir.has(r.errorCode)}function Can(e){return{...e,messages:e.messages.map(t=>typeof t.content!="string"?t:{...t,content:[{type:"text",text:t.content}]})}}var qir=Zae;function Gir(e,t){if(Tan.has(e))return!0;if(e!==400)return!1;const r=kh(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 kan(e,t){return e===529||kh(t).errorType==="overloaded_error"}var xan=500;function SA(e){return fo(e,xan)}_r(),q();var Aan=55669,Ian="generateContent",Hir="streamGenerateContent";function Ran(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 Man(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 Pan(e,t="",r=Aan,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}=Ran(o.path);if(!a||l!==Ian&&l!==Hir)return Vae(404,`Unsupported Gemini endpoint: ${o.path}`,"NOT_FOUND");const c=o.body;if(!c||!Array.isArray(c.contents)||c.contents.length===0)return Vae(400,"Request must include a non-empty 'contents' array");const u=l===Hir,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=fnn(h,c,u),y=Man(g),_=yA({provider:m??"auto",model:h},s?.getFallbackChain()??[],a,y,s?.isAutoFallbackEnabled?.()??!1).attempts;let b;try{b=sle.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 Qae({ctx:o,format:"gemini",requestModel:a,parsed:g,attempts:_,tracer:b,requestStartTime:i}):await ele({ctx:o,format:"gemini",requestModel:a,parsed:g,attempts:_,tracer:b,requestStartTime:i})}catch(T){const k=T instanceof Error?T.message:String(T),A=fo(k);return f.always(`[proxy:gemini] request failed: ${A}`),b?.setError("generation_error",A),b?.end(500,Date.now()-i),Vae(500,"Internal proxy error","INTERNAL")}}}]}}Vr(),yr();function Gle(e,t,r){return n=>gt({name:e,tracer:He.http,attributes:{"http.route":t,"http.request.id":n.requestId??""}},()=>r(n))}function Vir(e="/api"){return{prefix:`${e}/health`,routes:[{method:"GET",path:`${e}/health`,handler:Gle("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:Gle("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:Gle("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"]}]}}yn(),_r(),q();var Wir=300*1e3,Dan=55669;function Oan(e){return e?{status:502,errorType:"loopback_stream_error",errorMessage:e}:{status:499,errorType:"client_cancelled",errorMessage:"Client cancelled the OpenAI-compatible stream"}}function CA(e,t){return new Response(JSON.stringify(bnn(e,t)),{status:e,headers:{"content-type":"application/json"}})}function Nan(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 Lan(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={})=>Eh({timestamp:new Date().toISOString(),requestId:t.requestId,method:t.method,path:t.path,model:r.model,stream:i,toolCount:a,account:"",accountType:"openai-bridge",...ale(t.headers),responseStatus:g,responseTimeMs:Date.now()-o,...y}),c=Tnn(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 zt(fetch(u,{method:"POST",headers:d,body:JSON.stringify({...c,stream:i})}),Wir,`Anthropic loopback timed out after ${Wir}ms`);if(!m.ok){const g=await m.text().catch(()=>""),y=fo(g);return f.always(`[proxy:openai] anthropic loopback error ${m.status}: ${y}`),await l(m.status,{errorType:"loopback_upstream_error",errorMessage:y}),CA(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"}),CA(502,"Anthropic loopback returned empty stream body");let g;const v=m.body.pipeThrough(Snn(r.model,{onError:k=>{g=fo(k)}})).getReader();let _=!1;const b=async(k,A,I)=>{_||(_=!0,await l(k,{errorType:A,errorMessage:I}))},T=new ReadableStream({async pull(k){try{const{value:A,done:I}=await v.read();if(I){g?await b(502,"loopback_stream_error",g):await b(200),k.close();return}k.enqueue(A)}catch(A){const I=fo(A instanceof Error?A.message:String(A));await b(502,"loopback_stream_error",I),k.error(A)}},async cancel(k){try{await v.cancel(k)}finally{const A=Oan(g);await b(A.status,A.errorType,A.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}),Enn(h,r.model)}function $an(e,t="",r=Dan,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 CA(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 Lan({ctx:o,body:a,targetModel:u,requestStartTime:i,loopbackPort:r})}catch(v){const _=v instanceof Error?v.message:String(v),b=fo(_);return f.always(`[proxy:openai] anthropic loopback failed: ${b}`),await Eh({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}),CA(502,"Anthropic loopback failed")}const d=_nn(a),m=Nan(d),g=yA({provider:c??"auto",model:u},s?.getFallbackChain()??[],a.model,m,s?.isAutoFallbackEnabled?.()??!1).attempts;let y;try{y=sle.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?Qae({ctx:o,format:"openai",requestModel:a.model,parsed:d,attempts:g,tracer:y,requestStartTime:i}):await ele({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=fo(_);return f.always(`[proxy:openai] request failed: ${b}`),y?.setError("generation_error",b),y?.end(500,Date.now()-i),CA(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 eon(o)}}]}}Nx(),Kr(),ii(),rr(),q();var Fan="app_EMoamEEZ73f0CkXaXp7hrann",Uan="https://auth.openai.com/oauth/token",Ban=["openid","profile","email","offline_access"],Hle="https://chatgpt.com/backend-api/codex",zan=`${Hle}/responses`,Cpn=`${Hle}/usage`,Kir=`${Hle}/models`,jan="0.144.4",Jir=`codex_cli_rs/${jan} (external; neurolink-proxy)`,qan="codex_cli_rs",kpn=St(Va(),".codex","auth.json");function Yir(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 Gan(e){if(!e)return null;const t=e["https://api.openai.com/auth"];return t&&typeof t=="object"?t:null}function Zir(e){const t=e.split(".");if(t.length!==3)return{};const r=Yir(t[1]),n=Gan(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 Han(e){if(!e)return;const t=e.split(".");if(t.length!==3)return;const r=Yir(t[1]);return typeof r?.email=="string"?r.email:void 0}function nF(e,t){return t&&t.length>0?t:Zir(e).accountId}function Van(e){const t=Zir(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:Han(e.id_token)}}async function Vle(e,t={}){const r=new URLSearchParams({grant_type:"refresh_token",refresh_token:e,client_id:Fan,scope:Ban.join(" ")}),n=await fetch(Uan,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json","User-Agent":Jir},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"),Van({access_token:o.access_token,refresh_token:o.refresh_token??e,id_token:o.id_token})}function Wan(e){const t=e?.status;return typeof t!="number"||t<400||t>=500?!1:t!==408&&t!==429}function Kan(e,t=300*1e3){return e?e-t<=Date.now():!1}to();var kA=e=>typeof e=="number"&&Number.isFinite(e)&&e>0?Math.floor(e):0;function Jan(e){if(e===null||typeof e!="object")return null;const t=e,r=t.response,n=r&&typeof r=="object"&&r.usage?r.usage:t.usage;if(!n||typeof n!="object")return null;const o=n.input_tokens??n.prompt_tokens,s=n.output_tokens??n.completion_tokens;if(o===void 0&&s===void 0)return null;const i=n.input_tokens_details,a=n.output_tokens_details;return{inputTokens:kA(o),outputTokens:kA(s),cacheReadTokens:kA(i?.cached_tokens),cacheCreationTokens:kA(i?.cache_write_tokens),reasoningTokens:kA(a?.reasoning_tokens)}}function Xir(e){let t=null;for(const r of e.split(`
|