@juspay/neurolink 12.13.0 → 12.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,8 +1,8 @@
1
- ## [12.13.0](https://github.com/juspay/neurolink/compare/v12.12.16...v12.13.0) (2026-09-10)
1
+ ## [12.14.0](https://github.com/juspay/neurolink/compare/v12.13.0...v12.14.0) (2026-09-12)
2
2
 
3
3
  ### Features
4
4
 
5
- - **(anthropic):** truthful stream termination and an opt-in execution-control contract ([10fa282](https://github.com/juspay/neurolink/commit/10fa282f247803b7746ae9c0b5a171ff6e6ea59e))
5
+ - **(proxy):** auto-configure Grok Build with catalog windows and backends ([5ae2975](https://github.com/juspay/neurolink/commit/5ae2975228b1539261c0877e3bb0a8a3773a2ab5))
6
6
 
7
7
  ## [11.2.3](https://github.com/juspay/neurolink/compare/v11.2.2...v11.2.3) (2026-08-19)
8
8
 
@@ -2309,7 +2309,7 @@ data: ${r}
2309
2309
  `)}};return new TransformStream({transform(g,y){s+=o.decode(g,{stream:!0}),f(y)},flush(g){if(s+=o.decode(),f(g),!d){d=!0;const y="Anthropic stream ended before message_stop";t.onError?.(y),m(g,r.emitError(y))}}})}var sXt=["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"];pr(),_i(),kn(),Fo();var gJr=async()=>{},qrn=globalThis.crypto,jrn=globalThis.ReadableStream||class{},yJr=gJr,Hrn=globalThis.URL,Vrn=globalThis.URLSearchParams,moe=e=>{try{return JSON.stringify(e,null,2)}catch{return String(e)}};moe.custom=Symbol.for("nodejs.util.inspect.custom"),moe.colors={},moe.styles={};var vJr=globalThis.TextDecoder,iXt=globalThis.TextEncoder,Wrn=globalThis.performance||{now:()=>Date.now()},Krn=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 iXt().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 iXt().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 vJr().decode(this)}},Yrn=globalThis.clearTimeout,Zrn=globalThis.clearInterval,Xrn=globalThis.crypto,Qrn=globalThis.ReadableStream||class{},enn=globalThis.URL,tnn=globalThis.URLSearchParams,poe=e=>{try{return JSON.stringify(e,null,2)}catch{return String(e)}};poe.custom=Symbol.for("nodejs.util.inspect.custom"),poe.colors={},poe.styles={};var wJr=globalThis.TextDecoder,aXt=globalThis.TextEncoder,rnn=globalThis.performance||{now:()=>Date.now()},TJr=class{},nnn=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 aXt().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 aXt().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 wJr().decode(this)}},snn=globalThis.clearTimeout,inn=globalThis.clearInterval,cXt=16,lXt=32*1024*1024,VL=8*1024*1024,EJr=2e4,vg,SJr,WL=0,_Jr=0,tc={attempted:0,completed:0,rejected:0,failed:0,pending:0,pendingBytes:0,maxPending:cXt,maxPendingBytes:lXt},zk=new Map;function bJr(e){const t=[e],r=new Set;let n=0,o=0;for(;t.length;){if(++o>1e5||n>VL)return 1/0;const s=t.pop();if(typeof s=="string"){n+=s.length*3;continue}if(n+=16,!(!s||typeof s!="object")){if(r.has(s)||(r.add(s),!Array.isArray(s)&&Object.getPrototypeOf(s)!==Object.prototype&&Object.getPrototypeOf(s)!==null))return 1/0;for(const i of Object.keys(s)){n+=i.length*3;const a=Object.getOwnPropertyDescriptor(s,i);if(!a||a.get||a.set||(t.push(a.value),t.length>1e5||n>VL))return 1/0}}}return n}function hoe(e,t){const r=zk.get(e);r&&(zk.delete(e),clearTimeout(r.timer),r.resolve(t),zk.size||vg?.unref())}function foe(e,t){if(vg===e){vg=void 0,WL=Date.now()+5e3;for(const r of zk.keys())hoe(r,{error:t,stored:{bodyWriteFailed:!0}});e.terminate().catch(()=>{})}}function CJr(){if(vg)return vg;const e=new TJr(SJr??new URL("./bodyCaptureWorkerEntry.js",import.meta.url),{execArgv:process.execArgv.filter(t=>!t.startsWith("--input-type")),resourceLimits:{maxOldGenerationSizeMb:128}});return vg=e,e.on("message",t=>{vg===e&&hoe(t.id,t.result)}),e.on("error",()=>foe(e,"body_worker_error")),e.on("exit",()=>foe(e,"body_worker_exit")),e.unref(),e}async function kJr(e,t,r){tc.attempted+=1;let n;try{n=bJr(e)}catch{n=1/0}if(n>VL||tc.pending>=cXt||tc.pendingBytes+n>lXt||Date.now()<WL){tc.rejected+=1;const i=n>VL?"body_capture_too_large_or_non_json":Date.now()<WL?"body_worker_backoff":"body_capture_queue_full";return tc.lastError=i,r({error:i,stored:{bodyWriteFailed:!0}})}let o;try{o=CJr()}catch{return tc.failed+=1,WL=Date.now()+5e3,r({error:"body_worker_start_failed",stored:{bodyWriteFailed:!0}})}const s=++_Jr;return new Promise(i=>{const a=setTimeout(()=>foe(o,"body_worker_timeout"),EJr);a.unref(),zk.set(s,{timer:a,resolve:c=>{r(c).catch(()=>{c.error??="body_capture_publication_failed"}).finally(()=>{tc.pending-=1,tc.pendingBytes-=n,c.error||c.stored.bodyWriteFailed?tc.failed+=1:tc.completed+=1,c.error&&(tc.lastError=c.error),i()})}}),tc.pending+=1,tc.pendingBytes+=n,o.ref();try{o.postMessage({id:s,entry:e,logDir:t,queuedAt:Date.now()})}catch{hoe(s,{error:"body_capture_clone_failed",stored:{bodyWriteFailed:!0}})}})}Vt(),Ir(),Bn(),uft(),$H();var ann=1024*1024,cnn=dW(OH);function AJr(e,t){if(!e)return[""];const r=[],n=Buffer.from(e,"utf8");for(let o=0;o<n.length;){let s=Math.min(o+Math.max(4,t),n.length);for(;s<n.length&&(n[s]&192)===128;)s-=1;r.push(n.subarray(o,s).toString("utf8")),o=s}return r}var lnn=globalThis.crypto,xJr=class{getStore(){}run(e,t,...r){return t(...r)}enterWith(){}disable(){}},unn=globalThis.ReadableStream||class{},dnn=globalThis.URL,mnn=globalThis.URLSearchParams,goe=e=>{try{return JSON.stringify(e,null,2)}catch{return String(e)}};goe.custom=Symbol.for("nodejs.util.inspect.custom"),goe.colors={},goe.styles={};var IJr=globalThis.TextDecoder,uXt=globalThis.TextEncoder,pnn=globalThis.performance||{now:()=>Date.now()},hnn=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 uXt().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 uXt().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 IJr().decode(this)}},gnn=globalThis.clearTimeout,ynn=globalThis.clearInterval,dXt=new xJr;function Mw(){return dXt.getStore()}function RJr(){return dXt.getStore()!==void 0}sPe();var Gk={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};Gr();var Pw=null,yoe=!1,voe=new Set,mXt=5e3,MJr=4096,KL=new Map,PJr=Pq,woe=()=>({attempted:0,written:0,inFlight:0,pending:0,dropped:0,writeTimeouts:0,unconfirmedWrites:0}),DJr={requests:woe(),attempts:woe(),debug:woe()};async function Toe(e,t,r,n={}){const o=DJr[r];if(o.attempted+=1,o.pending+o.inFlight>=MJr){o.dropped+=1;return}o.pending+=1;const s=pXt((KL.get(e)??Promise.resolve()).then(async()=>{o.pending-=1,o.inFlight+=1;const i=setTimeout(()=>{o.writeTimeouts+=1},mXt);i.unref?.();try{await PJr(e,t,{mode:384,flag:"a"}),o.written+=1}catch(a){o.unconfirmedWrites+=1,o.lastErrorCode=a?.code??"UNKNOWN"}finally{clearTimeout(i),o.inFlight-=1}}));if(KL.set(e,s),s.then(()=>{KL.get(e)===s&&KL.delete(e)}),n.waitForPersistence)return s;await xt(s,mXt,"Proxy metadata write remains pending").catch(()=>{})}function pXt(e){return voe.add(e),e.then(()=>voe.delete(e),()=>voe.delete(e)),e}var Dw=null,hXt=0,OJr=10,NJr=16e3;async function Sp(e){if(e.terminalOutcome??=e.errorType==="client_cancelled"||e.responseStatus===499?"client_cancelled":e.errorType?.includes("stream")?"stream_error":e.responseStatus>=400||e.errorType?"handler_error":"completed",tJr(e),!yoe||!Pw)return;if(!e.traceId){const o=new xy().getCurrentTraceContext();o&&(e.traceId=o.traceId,e.spanId=o.spanId)}const t=Ct(Pw,`proxy-${new Date().toISOString().split("T")[0]}.jsonl`),r=JSON.stringify(e)+`
2310
2310
  `;try{await Toe(t,r,"requests")}catch{}LJr(e)}async function fXt(e){if(!yoe||!Pw)return;if(!e.traceId){const o=new xy().getCurrentTraceContext();o&&(e.traceId=o.traceId,e.spanId=o.spanId)}const t=Ct(Pw,`proxy-attempts-${new Date().toISOString().split("T")[0]}.jsonl`),r=JSON.stringify(e)+`
2311
2311
  `;try{await Toe(t,r,"attempts")}catch{}}async function gXt(){if(Dw!==!1){if(Dw!==null)return Dw;hXt++;try{const{getLoggerProvider:e}=await Promise.resolve().then(()=>(Fm(),C7)),t=e();if(t)return Dw=t,t;hXt>=OJr&&(Dw=!1);return}catch{Dw=!1;return}}}function LJr(e){gXt().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?Gk.WARN:Gk.ERROR:Gk.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 FJr(e,t){return gXt().then(async r=>{if(!r||t.redactedBody===void 0)return;const n=r.getLogger("neurolink-proxy-bodies","1.0.0"),o=AJr(t.redactedBody,NJr),s=Math.max(1,o.length);for(let i=0;i<s;i++){i>0&&i%4===0&&await yJr();const a=o[i]??"";n.emit({severityNumber:(e.responseStatus??0)>=400?Gk.WARN:Gk.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 $Jr(e){if(!yoe||!Pw||RJr())return;const t=new xy,r=e.traceId&&e.spanId?{traceId:e.traceId,spanId:e.spanId}:t.getCurrentTraceContext(),n=Pw,o={...e,body:void 0};return pXt(kJr(e,n,async i=>{const a=i.headers,c=i.stored,l=new Date(o.timestamp).toISOString().split("T")[0],u=Ct(n,`proxy-debug-${l}.jsonl`),d={timestamp:o.timestamp,type:"body_capture",requestId:o.requestId,phase:o.phase,model:o.model,stream:o.stream,headers:a,contentType:o.contentType,responseStatus:o.responseStatus,durationMs:o.durationMs,account:o.account,accountType:o.accountType,attempt:o.attempt,bodyPath:c.bodyPath,bodySha256:c.bodySha256,observedBodyBytes:o.bodySize,redactedBodyBytes:c.redactedBodyBytes,storedFileBytes:c.storedFileBytes,bodyTruncated:c.bodyTruncated,bodyWriteFailed:c.bodyWriteFailed,captureError:i.error,captureQueueWaitMs:i.queueWaitMs,captureProcessingMs:i.processingMs,metadata:i.error?void 0:o.metadata};r&&(d.traceId=r.traceId,d.spanId=r.spanId);try{await Toe(u,JSON.stringify(d)+`
2312
- `,"debug",{waitForPersistence:!0})}catch{}await FJr({...o,traceId:r?.traceId??o.traceId,spanId:r?.spanId??o.spanId},c)}))}var UJr=[["claude-cli/","claude-code"],["ai/","sdk"],["opencode/","opencode"],["QwenCode/","qwen-code"],["GeminiCLI-","gemini-cli"],["codex_exec/","codex"]],BJr=200;function zJr(e){if(!e)return"unknown";const t=e.trim();let r,n=0;for(const[o,s]of UJr)t.startsWith(o)&&o.length>n&&(r=s,n=o.length);return r??"unknown"}function GJr(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,BJr):void 0}}}function Ow(e){const t=GJr(e);return{clientApp:zJr(t),userAgent:t}}sL(),Gr(),tt(),U();var JL=300*1e3;function Eoe(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 yXt(e){return e.args??e.parameters??e.input??{}}function YL(e,t){return e.trim().length>0||(t?.length??0)>0}function Nw(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 qJr(e,t){return e==="litellm"&&t==="open-large"}function jJr(e,t){if(e==="litellm")return!0;if(e==="vertex"){const r=t?.toLowerCase()??"";return!/gemini-(2\.5|3)/.test(r)}return!1}function Soe(e,t={}){const r=e.conversationMessages.slice(0,-1),n=Object.keys(e.tools),o=e,s=qJr(t.provider,t.model)?[]:e.images,i=o.thinkingConfig&&!jJr(t.provider,t.model)?o.thinkingConfig:void 0,a=e,c=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}:{},...c?{toolChoice:c}:{},...r.length>0?{conversationMessages:r}:{},disableInternalFallback:!0,skipToolPromptInjection:!0,maxSteps:1}}function HJr(e){const t=new Fk(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 VJr(e){const t=new oXt(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 WJr(e){return e==="claude"?BL():tXt()}function _oe(e){return e==="claude"?"end_turn":"stop"}function vXt(e){return e==="claude"?"[proxy]":e==="gemini"?"[proxy:gemini]":"[proxy:openai]"}async function boe(e){const{ctx:t,format:r,requestModel:n,parsed:o,attempts:s,tracer:i,requestStartTime:a}=e,c=vXt(r),l=r==="claude"?HJr(n):r==="gemini"?lJr(n):VJr(n),u=15e3,d=new TextEncoder;let m,h=!1,f=!1,g=!1,y,w,E=!1,_="No translation providers succeeded",C,x="translation";const b=new ReadableStream({async start(I){for(const R of l.start())I.enqueue(d.encode(R));m=setInterval(()=>{try{I.enqueue(d.encode(`: keep-alive
2312
+ `,"debug",{waitForPersistence:!0})}catch{}await FJr({...o,traceId:r?.traceId??o.traceId,spanId:r?.spanId??o.spanId},c)}))}var UJr=[["claude-cli/","claude-code"],["ai/","sdk"],["opencode/","opencode"],["QwenCode/","qwen-code"],["GeminiCLI-","gemini-cli"],["codex_exec/","codex"],["grok-shell/","grok"]],BJr=200;function zJr(e){if(!e)return"unknown";const t=e.trim();let r,n=0;for(const[o,s]of UJr)t.startsWith(o)&&o.length>n&&(r=s,n=o.length);return r??"unknown"}function GJr(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,BJr):void 0}}}function Ow(e){const t=GJr(e);return{clientApp:zJr(t),userAgent:t}}sL(),Gr(),tt(),U();var JL=300*1e3;function Eoe(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 yXt(e){return e.args??e.parameters??e.input??{}}function YL(e,t){return e.trim().length>0||(t?.length??0)>0}function Nw(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 qJr(e,t){return e==="litellm"&&t==="open-large"}function jJr(e,t){if(e==="litellm")return!0;if(e==="vertex"){const r=t?.toLowerCase()??"";return!/gemini-(2\.5|3)/.test(r)}return!1}function Soe(e,t={}){const r=e.conversationMessages.slice(0,-1),n=Object.keys(e.tools),o=e,s=qJr(t.provider,t.model)?[]:e.images,i=o.thinkingConfig&&!jJr(t.provider,t.model)?o.thinkingConfig:void 0,a=e,c=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}:{},...c?{toolChoice:c}:{},...r.length>0?{conversationMessages:r}:{},disableInternalFallback:!0,skipToolPromptInjection:!0,maxSteps:1}}function HJr(e){const t=new Fk(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 VJr(e){const t=new oXt(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 WJr(e){return e==="claude"?BL():tXt()}function _oe(e){return e==="claude"?"end_turn":"stop"}function vXt(e){return e==="claude"?"[proxy]":e==="gemini"?"[proxy:gemini]":"[proxy:openai]"}async function boe(e){const{ctx:t,format:r,requestModel:n,parsed:o,attempts:s,tracer:i,requestStartTime:a}=e,c=vXt(r),l=r==="claude"?HJr(n):r==="gemini"?lJr(n):VJr(n),u=15e3,d=new TextEncoder;let m,h=!1,f=!1,g=!1,y,w,E=!1,_="No translation providers succeeded",C,x="translation";const b=new ReadableStream({async start(I){for(const R of l.start())I.enqueue(d.encode(R));m=setInterval(()=>{try{I.enqueue(d.encode(`: keep-alive
2313
2313
 
2314
2314
  `))}catch{}},u);try{for(let R=0;R<s.length&&!h;R++){const A=s[R];x=A.label??"translation",p.always(`[proxy:${r}] attempt ${R+1}/${s.length}: ${A.label}`),cg(x,"translation");let P="";try{const L=Soe(o,A.provider?{provider:A.provider,model:A.model}:{}),B=await xt(t.neurolink.stream(L),JL,`Translation attempt ${A.label} timed out after ${JL}ms`);for(C=B.stream[Symbol.asyncIterator]();!h;){const{value:F,done:G}=await C.next();if(G||h)break;const j=Eoe(F);if(j){P+=j;for(const q of l.pushDelta(j))I.enqueue(d.encode(q))}}if(h)return;const D=B.toolCalls??[];if(!YL(P,D)){_=`Translated provider ${A.label} returned no content or tool calls`,p.debug(`${c} translation attempt ${A.label} returned no content or tool calls`),ur(x,"translation",502);continue}if(!h&&D.length)for(const F of D){const G=F.toolName??F.name??"unknown",j=F.toolCallId||WJr(r);for(const q of l.pushToolUse(j,G,yXt(F)))I.enqueue(d.encode(q))}if(!h){const F=B.finishReason??_oe(r),G=Nw(B.usage);for(const j of l.finish(F,G))I.enqueue(d.encode(j))}y=B.model,w=A.provider,i&&y&&y!==n&&(i.setModelSubstitution(n,y,w),E=!0);const $=Nw(B.usage);i?.setUsage({inputTokens:$.input,outputTokens:$.output,cacheCreationTokens:0,cacheReadTokens:0}),i?.recordMetrics(),f=!0;return}catch(L){if(h)return;if(_=L instanceof Error?L.message:String(L),P.trim().length>0){g=!0,ur(x,"translation",502),p.always(`${c} mid-stream error: ${_}`);for(const B of l.emitError(`Upstream stream interrupted: ${_}`))I.enqueue(d.encode(B));return}p.debug(`${c} translation attempt ${A.label} failed: ${_}`),ur(x,"translation",500)}}if(!h){p.always(`${c} all translation attempts failed: ${_}`);for(const R of l.emitError(_))I.enqueue(d.encode(R))}}finally{m&&clearInterval(m),h||I.close(),!E&&i&&y&&y!==n&&(i.setModelSubstitution(n,y,w),E=!0);const R=h?499:f?200:g?502:500,A=h?"client_cancelled":g?"stream_error":f?void 0:"generation_error",P=h?"Client cancelled the streaming response":f?void 0:_;A&&P?(i?.setError(A,P.slice(0,500)),aw(R,x,"translation",{requestId:t.requestId,errorType:A,terminalOutcome:A,message:P})):dk(x,"translation"),i?.end(R,Date.now()-a);const L=i?.getTraceContext();Sp({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",...Ow(t.headers),responseStatus:R,responseTimeMs:Date.now()-a,...A?{errorType:A}:{},...P?{errorMessage:P.slice(0,500)}:{},...L?.traceId?{traceId:L.traceId}:{},...L?.spanId?{spanId:L.spanId}:{}})}},cancel(){h=!0,m&&(clearInterval(m),m=void 0),C?.return&&C.return(void 0).catch(I=>{p.debug(`${c} upstream cancel error: ${I instanceof Error?I.message:String(I)}`)})}});return new Response(b,{headers:{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}})}async function Coe(e){const{ctx:t,format:r,requestModel:n,parsed:o,attempts:s,tracer:i,requestStartTime:a,terminalFailureStatus:c=500}=e,l=vXt(r);let u="No translation providers succeeded",d="translation";for(let h=0;h<s.length;h++){const f=s[h];d=f.label??"translation",p.always(`[proxy:${r}] attempt ${h+1}/${s.length}: ${f.label}`),cg(d,"translation");try{const g=Soe(o,f.provider?{provider:f.provider,model:f.model}:{}),y=await xt(t.neurolink.stream(g),JL,`Translation attempt ${f.label} timed out after ${JL}ms`);let w="";for await(const x of y.stream){const b=Eoe(x);b&&(w+=b)}if(!YL(w,y.toolCalls)){u=`Translated provider ${f.label} returned no content or tool calls`,p.debug(`${l} translation attempt ${f.label} returned no content or tool calls`),ur(d,"translation",502);continue}const E={content:w,model:y.model,finishReason:y.finishReason??_oe(r),reasoning:void 0,usage:y.usage?Nw(y.usage):void 0,toolCalls:y.toolCalls};i&&y.model&&y.model!==n&&i.setModelSubstitution(n,y.model,f.provider);const _=Nw(y.usage);i?.setUsage({inputTokens:_.input,outputTokens:_.output,cacheCreationTokens:0,cacheReadTokens:0}),i?.recordMetrics(),i?.end(200,Date.now()-a),dk(d,"translation");const C=i?.getTraceContext();return Sp({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",...Ow(t.headers),responseStatus:200,responseTimeMs:Date.now()-a,inputTokens:_.input,outputTokens:_.output,...C?.traceId?{traceId:C.traceId}:{},...C?.spanId?{spanId:C.spanId}:{}}),r==="claude"?ooe(E,n):r==="gemini"?aJr(E.content,E.finishReason??_oe(r),_,E.model??n,E.toolCalls):nXt(E,n)}catch(g){u=g instanceof Error?g.message:String(g),p.debug(`${l} translation attempt ${f.label} failed: ${u}`),ur(d,"translation",500)}}aw(c,d,"translation",{requestId:t.requestId,errorType:"generation_error",terminalOutcome:"handler_error",message:u}),i?.setError("generation_error",u.slice(0,500)),i?.end(c,Date.now()-a);const m=i?.getTraceContext();throw Sp({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",...Ow(t.headers),responseStatus:c,responseTimeMs:Date.now()-a,errorType:"generation_error",errorMessage:u.slice(0,500),...m?.traceId?{traceId:m.traceId}:{},...m?.spanId?{spanId:m.spanId}:{}}),new be({code:ze.PROVIDER_NOT_AVAILABLE,message:u,category:"execution",severity:"high",retriable:!1,context:{attemptLabel:d,format:r}})}function KJr(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 sXt)t.push({id:r,object:"model",created:0,owned_by:"neurolink"});return{object:"list",data:t}}function JJr(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(...sXt);const r=new Set,o=t.filter(s=>r.has(s)?!1:(r.add(s),!0)).map(s=>({type:"model",id:s,display_name:YJr(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 YJr(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}cr(),Mr(),Zt(),Fm(),sPe(),Qc(),bS(),U();var ZJr="[ProxyTracer]",koe=null;function qk(){if(koe)return koe;const e=Ap.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 koe=t,t}var XJr=new Set(["authorization","proxy-authorization","x-api-key","cookie","set-cookie"]),QJr=/token|secret|key|password|credential/i;function Aoe(e){const t={};for(const[r,n]of Object.entries(e)){const o=r.toLowerCase();XJr.has(o)||QJr.test(o)?t[r]="[REDACTED]":t[r]=n}return t}var eYr=/api[_-]?key|token|secret|password|credential|authorization/i,ZL=process.env.NEUROLINK_PROXY_TRACE_BODY_LOGGING==="true",xoe=Number.parseInt(process.env.NEUROLINK_PROXY_TRACE_BODY_LOG_BYTES??"8192",10),wXt=200;function TXt(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[c,l]of Object.entries(i))a[c]=eYr.test(c)?"[REDACTED]":o(l);return a};var n=o;const s=JSON.parse(r);return JSON.stringify(o(s))}catch{return r}}function Ioe(e){return{"proxy.body":TXt(e,xoe),"proxy.body.size":e.length,"proxy.body.logged":!0,"proxy.body.truncated":e.length>xoe}}function tYr(e){return e?e.startsWith("claude-cli/")?"cli":e.startsWith("ai/")?"sdk":"unknown":"unknown"}var Roe=class Atr{rootSpan;proxyTracer=GM("neurolink.proxy");bridge=new xy;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=GM("neurolink.proxy");let o=Sr.active();if(r){const m=new xy().extractContext(r);m&&(o=ut.setSpanContext(Sr.active(),m))}const s=t.clientApp??tYr(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"],c=r?.["x-neurolink-user-id"],l=r?.["x-neurolink-conversation-id"];a&&i.setAttribute("neurolink.session_id",a),c&&i.setAttribute("neurolink.user_id",c),l&&i.setAttribute("neurolink.conversation_id",l);const u=new Atr(i,t.requestId,t.model,t.stream,t.provider??"anthropic");return r0({sessionId:a??t.sessionId,userId:c,conversationId:l,requestId:t.requestId,traceName:`proxy:${t.model}`,operationName:"proxy.request",metadata:{clientApp:s,stream:t.stream,toolCount:t.toolCount}}).catch(d=>{p.debug(`${ZJr} 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}},ut.setSpan(Sr.active(),this.rootSpan))}startAccountSelection(){return this.proxyTracer.startSpan("proxy.account_selection",{attributes:{"proxy.request_id":this.requestId}},ut.setSpan(Sr.active(),this.rootSpan))}startUpstreamAttempt(t){return this.proxyTracer.startSpan("proxy.upstream",{attributes:{"proxy.request_id":this.requestId,"proxy.upstream.attempt":t.attempt,"proxy.upstream.account":t.account,"proxy.upstream.polyfill_headers":t.polyfillHeaders,"proxy.upstream.polyfill_body":t.polyfillBody,"http.url":t.upstreamUrl}},ut.setSpan(Sr.active(),this.rootSpan))}startStream(){return this.proxyTracer.startSpan("proxy.stream",{attributes:{"proxy.request_id":this.requestId,"gen_ai.request.model":this.model}},ut.setSpan(Sr.active(),this.rootSpan))}setAccountSelection(t){this.accountEmail=t.selectedAccount,this.rootSpan.setAttributes({"proxy.account.strategy":t.strategy,"proxy.account.total":t.accountsTotal,"proxy.account.healthy":t.accountsHealthy,"proxy.account.selected":t.selectedAccount,"proxy.account.type":t.accountType}),t.rateLimitBefore5h!==void 0&&this.rootSpan.setAttribute("proxy.ratelimit.before.5h",t.rateLimitBefore5h),t.rateLimitBefore7d!==void 0&&this.rootSpan.setAttribute("proxy.ratelimit.before.7d",t.rateLimitBefore7d),r0({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=La(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}:{}}),qk().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(!ZL){this.rootSpan.addEvent("proxy.client.request_body",{"proxy.body.size":t.length,"proxy.body.logged":!1});return}this.rootSpan.addEvent("proxy.client.request_body",{...Ioe(t)})}logRequestHeaders(t){this.rootSpan.addEvent("proxy.client.request_headers",{"proxy.headers":JSON.stringify(Aoe(t))})}logUpstreamRequestBody(t){if(!ZL){this.rootSpan.addEvent("proxy.upstream.request_body",{"proxy.body.size":t.length,"proxy.body.logged":!1});return}this.rootSpan.addEvent("proxy.upstream.request_body",{...Ioe(t)})}logUpstreamRequestHeaders(t){this.rootSpan.addEvent("proxy.upstream.request_headers",{"proxy.headers":JSON.stringify(Aoe(t))})}logUpstreamResponseHeaders(t){this.rootSpan.addEvent("proxy.upstream.response_headers",{"proxy.headers":JSON.stringify(Aoe(t))})}logUpstreamResponseBody(t){if(!ZL){this.rootSpan.addEvent("proxy.upstream.response_body",{"proxy.body.size":t.length,"proxy.body.logged":!1});return}this.rootSpan.addEvent("proxy.upstream.response_body",{...Ioe(t)})}logStreamEvents(t){if(!ZL){this.rootSpan.addEvent("proxy.stream.events",{"proxy.stream.event_count":t.length,"proxy.body.logged":!1});return}const r=t.length>wXt,n=t.slice(0,wXt).map(o=>({...o,data:o.data?TXt(o.data,xoe):""}));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){qk().retriesTotal.add(1,{model:this.model,account:t,reason:r})}recordBodySizes(t,r){const n=qk(),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:Ne.ERROR,message:`HTTP ${t}`}):this.rootSpan.setStatus({code:Ne.OK}),this.rootSpan.end();const n=qk(),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=La(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=La(this.billingProvider,this.model,{input:this.usage.inputTokens,output:this.usage.outputTokens,total:t,cacheCreationTokens:this.usage.cacheCreationTokens,cacheReadTokens:this.usage.cacheReadTokens});fh.getInstance().recordAIRequest(this.billingProvider,this.model,t,r,n>0?n:void 0)}getTraceHeaders(){return this.bridge.injectContext({},ut.setSpan(Sr.active(),this.rootSpan))}};function Lw(e){try{const t=qk(),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 XL=1024*1024,Moe=`
2315
2315
  ...[TRUNCATED]`;function EXt(){const e=new TextDecoder,t=[];let r=0,n=0,o=!1,s=!1,i;const a=new Promise(g=>{i=g});function c(){if(s)return;s=!0;const g=e.decode();if(g)if(n<XL){const y=XL-n;t.push(g.slice(0,y)),n+=Math.min(g.length,y)}else o||(t.push(Moe),o=!0);i({totalBytes:r,text:t.join(""),truncated:o})}const l=new TransformStream({transform(g,y){if(y.enqueue(g),r+=g.byteLength,n<XL){const w=e.decode(g,{stream:!0}),E=XL-n,_=w.slice(0,E);t.push(_),n+=Math.min(w.length,E),w.length>E&&!o&&(t.push(Moe),o=!0)}else o||(t.push(Moe),o=!0)},flush(){c()}}),u=l.writable.getWriter();let d;const m=new WritableStream({start(g){d=g},write(g){return u.write(g)},close(){return u.close()},abort(g){return c(),u.abort(g)}});u.closed.catch(g=>{c();try{d.error(g)}catch{}});const h=l.readable.getReader();return{stream:{readable:new ReadableStream({async pull(g){try{const{done:y,value:w}=await h.read();y?g.close():g.enqueue(w)}catch(y){g.error(y)}},async cancel(g){c();try{d.error(g)}catch{}await Promise.allSettled([h.cancel(g),u.abort(g)])}}),writable:m},capture:a}}Lvt(),Ir(),Ds(),Vt(),Dc(),U(),Ya();var rYr="proxy-peers.json",nYr=1e3,oYr={exhausted:9e5,withheld:6e5,paused:3e5,revoked:864e5,expired:864e5,unreachable:6e4,upstream_error:12e4},sYr=null,Vd={},jk=0,Hk=-1,Vk=!1,SXt=new Ta;function Poe(){return sYr??ht(aa(),".neurolink",rYr)}function iYr(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 aYr(e){return e?.code==="ENOENT"}async function Doe(e={}){const t=Date.now();if(!e.force&&Vk&&t-jk<nYr)return;const r=Poe();let n;try{n=(await ws(r)).mtimeMs}catch(o){if(!aYr(o))throw o;Vd={},Hk=-1,jk=t,Vk=!0;return}if(!e.force&&Vk&&n===Hk){jk=t;return}try{const o=JSON.parse(await Pr(r,"utf8"));Vd=Object.fromEntries(Object.entries(o?.peers??{}).filter(s=>iYr(s[1])))}catch(o){if(e.force)throw o;p.always(`[proxy] peer list unreadable, treating as empty: ${o instanceof Error?o.message:String(o)}`),Vd={}}Hk=n,jk=t,Vk=!0}async function _Xt(){const e={schemaVersion:1,peers:Vd};await Ea(Poe(),e);try{Hk=(await ws(Poe())).mtimeMs}catch{Hk=-1}jk=Date.now(),Vk=!0}function bXt(e){return e.trim().toLowerCase()}async function cYr(){return await Doe(),Object.values(Vd).sort((e,t)=>e.priority-t.priority||e.createdAt-t.createdAt)}async function lYr(e=Date.now()){return(await cYr()).filter(r=>r.enabled&&!(r.cooldownUntil&&r.cooldownUntil>e))}function uYr(e){return oYr[e]}var dYr=6048e5;async function Ooe(e,t,r){await SXt.runExclusive(async()=>{await Doe({force:!0});const n=bXt(e),o=Vd[n];if(!o)return;const s=(r??0)*1e3,i=Date.now()+Math.min(dYr,Math.max(uYr(t),Number.isFinite(s)?s:0));Vd[n]={...o,cooldownUntil:i,cooldownReason:t,updatedAt:Date.now()},await _Xt()})}async function mYr(e,t){await SXt.runExclusive(async()=>{await Doe({force:!0});const r=bXt(e),n=Vd[r];n&&(Vd[r]={...n,cooldownUntil:0,lastUsedAt:Date.now(),updatedAt:Date.now(),...t?{lastObservation:t}:{}},await _Xt())})}Ir(),Ds(),Vt(),Dc(),aL();var pYr=6048e5,hYr=9e5,fYr=864e5;function gYr(e){return!e.usable}function CXt(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 kXt(e,t){return kre(e,t)}function AXt(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??pYr,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??hYr,offlineGraceMs:r?.offlineGraceMs??fYr,gates:e.gates,entitlementSnapshot:e.entitlement.ledger==="coins"?e.entitlement.coins??0:"unlimited"};return{...i,signature:kXt(CXt(i),n)}}function yYr(e,t){const{signature:r,...n}=e;return f9t(kXt(CXt(n),t),r)}function vYr(e){const t=e.now??Date.now();if(!yYr(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 wYr(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:AXt(e.grant,t),lenderUrl:(e.lenderUrl??"").replace(/\/+$/,"")}}Ya();var TYr="proxy-resident-grants.json",EYr=1e3,SYr=null,wg={},Wk=0,Kk=-1,Jk=!1,_Yr=new Ta;function Noe(){return SYr??ht(aa(),".neurolink",TYr)}function bYr(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 CYr(e){return e?.code==="ENOENT"}async function xXt(e={}){const t=Date.now();if(!e.force&&Jk&&t-Wk<EYr)return;const r=Noe();let n;try{n=(await ws(r)).mtimeMs}catch(o){if(!CYr(o))throw o;wg={},Kk=-1,Wk=t,Jk=!0;return}if(!e.force&&Jk&&n===Kk){Wk=t;return}try{const o=JSON.parse(await Pr(r,"utf8"));wg=Object.fromEntries(Object.entries(o?.grants??{}).filter(s=>bYr(s[1])))}catch(o){if(e.force)throw o;wg={}}Kk=n,Wk=t,Jk=!0}async function kYr(){const e={schemaVersion:1,grants:wg};await Ea(Noe(),e);try{Kk=(await ws(Noe())).mtimeMs}catch{Kk=-1}Wk=Date.now(),Jk=!0}function IXt(e){return e.toLowerCase()}async function Loe(e){await xXt();const t=e.toLowerCase(),r=t.includes(":")?t.slice(t.indexOf(":")+1):t;return wg[IXt(r)]}async function AYr(e,t=Date.now()){const r=await Loe(e);if(r)return vYr({lease:r.lease,secret:r.leaseSecret,...r.lastHeartbeatAt!==void 0?{lastHeartbeatAt:r.lastHeartbeatAt}:{},now:t})}async function xYr(e,t){await _Yr.runExclusive(async()=>{await xXt({force:!0});const r=IXt(e),n=wg[r];n&&(wg[r]={...n,unreportedCoins:(n.unreportedCoins??0)+t,unreportedRequests:(n.unreportedRequests??0)+1},await kYr())})}U();var IYr=15e3,RYr=12e4;function MYr(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 RXt(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 PYr(e){const t=RXt(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 DYr(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(()=>{p.always(`[proxy] peer=${t.name} went quiet mid-response; abandoning it`),Ooe(t.name,"unreachable").catch(c=>{p.debug(`[proxy] could not cool peer=${t.name} after a stall: ${c instanceof Error?c.message:String(c)}`)}),r.abort()},RYr),o.unref?.()},a=n.pipeThrough(new TransformStream({start:i,transform(c,l){i(),l.enqueue(c)},flush:s}));return r.signal.addEventListener("abort",s,{once:!0}),new Response(a,{status:e.status,statusText:e.statusText,headers:e.headers})}async function OYr(e){const{peer:t,body:r,stream:n}=e,o=new AbortController,s=setTimeout(()=>o.abort(),IYr);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 mYr(t.name,PYr(i)).catch(u=>{p.debug(`[proxy] could not record success for peer=${t.name}: ${u instanceof Error?u.message:String(u)}`)}),{ok:!0,response:DYr(i,t,o),peer:t};const a=i.headers.get("x-neurolink-grant-reason"),c=MYr(a),l=RXt(i,"retry-after");return await Ooe(t.name,c,l),await i.text().catch(()=>""),p.always(`[proxy] peer=${t.name} declined (${c}); cooling before retry`),{ok:!1,peer:t,status:i.status,reason:c,message:`peer ${t.name} declined: ${c}`,...l!==void 0?{retryAfterSeconds:l}:{}}}catch(i){const a=i instanceof Error?i.message:String(i);return e.signal?.aborted?(p.debug(`[proxy] peer=${t.name} attempt cancelled by the caller: ${a}`),{ok:!1,peer:t,reason:"unreachable",message:`peer ${t.name} attempt cancelled`}):(await Ooe(t.name,"unreachable").catch(c=>{p.debug(`[proxy] could not cool peer=${t.name}: ${c instanceof Error?c.message:String(c)}`)}),p.always(`[proxy] peer=${t.name} unreachable: ${a}`),{ok:!1,peer:t,reason:"unreachable",message:`peer ${t.name} unreachable`})}finally{clearTimeout(s)}}gk();var NYr=36e5,LYr={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 FYr(e){return LYr[e]}function $Yr(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 UYr(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 BYr(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 MXt(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 PXt(e,t,r){const n=e.spillover;if(!n)return!1;const o=n.beforeResetHours*NYr,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 Foe(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 $oe(e,t,r,n){const o=e.gates,{inScope:s,outOfScope:i}=Foe(o,t),a=s.some(m=>PXt(o,m,r)),c=MXt(o.maxSlice,a?o.spillover?.maxSlicePct:void 0);if(c.session!==void 0&&n.sessionFraction*100>=c.session||c.weekly!==void 0&&n.weeklyFraction*100>=c.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=PXt(o,m,r);if(o.spillover&&!h){d.push({accountKey:m.accountKey,reason:"spillover_inactive"});continue}const f=o.reserveFloor;if(f){const E=f.session5hPct!==void 0&&m.sessionUsed!==null&&m.sessionUsed*100>100-f.session5hPct,_=f.weekly7dPct!==void 0&&m.weeklyUsed!==null&&m.weeklyUsed*100>100-f.weekly7dPct;if(E||_){d.push({accountKey:m.accountKey,reason:"reserve_floor"});continue}}const g=MXt(o.maxSlicePerAccount,h?o.spillover?.maxSlicePct:void 0),y=g.session!==void 0&&m.borrowedSessionFraction*100>=g.session,w=g.weekly!==void 0&&m.borrowedWeeklyFraction*100>=g.weekly;if(y||w){d.push({accountKey:m.accountKey,reason:"slice_exhausted"});continue}u.push(m.accountKey)}return{allowed:u,excluded:d}}function Uoe(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 zYr="x-neurolink-share-token",GYr="x-neurolink-grant-status",qYr="x-neurolink-grant-reason",jYr="x-neurolink-grant-remaining-coins",HYr="x-neurolink-grant-peer";function VYr(e){const t=e[zYr];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 Mjr(o)?o:void 0}function WYr(e){return e===401?"authentication_error":e===403?"permission_error":"rate_limit_error"}function KYr(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 Fw(e,t){const{status:r,grant:n,retryAfterSeconds:o}=t,s={[GYr]:KYr(e,n),[qYr]:e};return n&&(s[HYr]=n.peerLabel,n.entitlement.ledger==="coins"&&(s[jYr]=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:WYr(r),message:t.message??FYr(e)}}}}gk(),Ir(),Ds(),Vt(),Dc(),Ya();var JYr="proxy-share-audit.json",YYr=2,ZYr=3,XYr=1e3,QYr=null,$w={},Yk=0,Zk=-1,Xk=!1,eZr=new Ta;function Boe(){return QYr??ht(aa(),".neurolink",JYr)}function tZr(e){return e?.code==="ENOENT"}async function rZr(e={}){const t=Date.now();if(!e.force&&Xk&&t-Yk<XYr)return;const r=Boe();let n;try{n=(await ws(r)).mtimeMs}catch(o){if(!tZr(o))throw o;$w={},Zk=-1,Yk=t,Xk=!0;return}if(!e.force&&Xk&&n===Zk){Yk=t;return}try{$w=JSON.parse(await Pr(r,"utf8"))?.records??{}}catch(o){if(e.force)throw o;$w={}}Zk=n,Yk=t,Xk=!0}async function nZr(){const e={schemaVersion:1,records:$w};await Ea(Boe(),e);try{Zk=(await ws(Boe())).mtimeMs}catch{Zk=-1}Yk=Date.now(),Xk=!0}function DXt(e,t){return e===null||t===null?0:Math.max(0,(t-e)*100)}function oZr(e,t,r=YYr){if(!e)return{drifted:!1,reason:"no_baseline"};if(t.lenderRequests>0)return{drifted:!1,reason:"attributable"};const n=DXt(e.sessionUsed,t.sessionUsed),o=DXt(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 sZr(e){const t=e.streakLimit??ZYr;return eZr.runExclusive(async()=>{await rZr({force:!0});const r=$w[e.grantId],n=e.lenderRequestsTotal===void 0?e.observation:{...e.observation,lenderRequests:Math.max(0,e.lenderRequestsTotal-(r?.lenderRequestsTotal??0))},o=oZr(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),$w[e.grantId]=i,await nZr(),{verdict:o,shouldPause:a}})}Bn(),Ir(),Ds(),Vt(),Dc(),Ya();var iZr="proxy-share-provisioning.json",aZr=9e5,cZr=/^[A-Za-z0-9_-]{43}$/,lZr=/^[A-Za-z0-9_-]{16,128}$/,uZr=null,Uw={},OXt=!1,NXt=new Ta;function LXt(){return uZr??ht(aa(),".neurolink",iZr)}function dZr(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 FXt(e={}){if(!(OXt&&!e.force)){try{const t=JSON.parse(await Pr(LXt(),"utf8"));Uw=Object.fromEntries(Object.entries(t?.requests??{}).filter(r=>dZr(r[1])))}catch{Uw={}}OXt=!0}}async function $Xt(){const e={schemaVersion:1,requests:Uw};await Ea(LXt(),e)}function mZr(e,t=Date.now()){return e.status!=="consumed"&&e.expiresAt>t}async function pZr(e){if(!cZr.test(e.codeChallenge))return{ok:!1,reason:"code_challenge must be a base64url S256 digest"};if(!lZr.test(e.state))return{ok:!1,reason:"state must be 16-128 base64url characters"};const t=e.now??Date.now();return NXt.runExclusive(async()=>{await FXt({force:!0});const r={schemaVersion:1,grantId:e.grantId,codeChallenge:e.codeChallenge,challengeMethod:"S256",state:e.state,requestedAt:t,expiresAt:t+aZr,status:"pending"};return Uw[e.grantId]=r,await $Xt(),{ok:!0,request:r}})}async function hZr(e,t=Date.now()){return NXt.runExclusive(async()=>{await FXt({force:!0});const r=Uw[e];if(!r||!mZr(r,t))return{status:"none"};if(r.status!=="authorized"||!r.code)return{status:"pending"};const{code:n,...o}=r;return Uw[e]={...o,status:"consumed",claimedAt:t},await $Xt(),{status:"ready",code:r.code,state:r.state}})}I9t(),Bn(),Ir(),Ds(),Vt(),Dc(),gk(),aL();var fZr="proxy-share-notes.json",UXt="nln",gZr=null,Bw={},BXt=!1,yZr=new Ta;function zXt(){return gZr??ht(aa(),".neurolink",fZr)}async function GXt(e={}){if(!(BXt&&!e.force)){try{Bw=JSON.parse(await Pr(zXt(),"utf8"))?.notes??{}}catch{Bw={}}BXt=!0}}async function vZr(){const{writeJsonSnapshotAtomically:e}=await Promise.resolve().then(()=>(Ya(),fre)),t={schemaVersion:1,notes:Bw};await e(zXt(),t)}function wZr(e){const t=e.trim();if(t.startsWith(`${UXt}_`))try{const r=JSON.parse(Buffer.from(t.slice(UXt.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 TZr(e,t,r=Date.now()){const{signature:n,...o}=e;if(!t||!iL(o,n,t))return{status:"forged",coins:0};await GXt({force:!0});const s=Bw[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 EZr(e){const t=e.now??Date.now(),{signature:r,...n}=e.note;if(!e.secret||!iL(n,r,e.secret))return{ok:!1,status:"forged"};const o=await yZr.runExclusive(async()=>{await GXt({force:!0});const i=Bw[e.note.noteId];return i?i.redeemedAt!==void 0?{status:"spent",coins:i.coins}:i.notAfter<=t?{status:"expired",coins:i.coins}:(Bw[i.noteId]={...i,redeemedAt:t,redeemedByGrant:e.grantId},await vZr(),{status:"valid",coins:i.coins}):{status:"unknown",coins:0}});if(o.status!=="valid")return{ok:!1,status:o.status};const s=await w9t(e.grantId,o.coins);return{ok:!0,coins:o.coins,balance:s}}aL(),z9t();var SZr=64*1024,_Zr=32;function qXt(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 jXt(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 bZr(e){const t=new TextDecoder,r=[];let n="",o=0;for(;o<SZr&&r.length<_Zr;){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}=GL(n),c=a.find(jXt);return c?{kind:"sse_error",chunks:r,...qXt(c.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=GL(n);n=i.remainder;for(const a of i.events){if(jXt(a))return{kind:"sse_error",chunks:r,...qXt(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 HXt(){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 QL(e,t,r){return e.kind==="completed"&&t?{kind:"upstream_error",message:t}:e.kind==="completed"&&r===!1?{kind:"upstream_error",message:"Anthropic stream ended without a message_stop event"}:e}function CZr(e){const t=e.toLowerCase();return t.includes("opus")?"opus":t.includes("sonnet")?"sonnet":t.includes("haiku")?"haiku":"other"}function zw(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,...i.reasoningEffort!==void 0?{reasoningEffort:i.reasoningEffort}:{},label:`${i.provider}/${i.model}`});return o&&(t.length===0||s.length===1)&&s.push({label:"auto-provider"}),{requestedModel:r,modelTier:CZr(r),attempts:s,skipped:[]}}function e2(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 kZr=1,AZr=20;function zoe(e){return typeof e=="number"&&Number.isInteger(e)&&e>=kZr&&e<=AZr?e:void 0}Ya(),sL(),or(),U(),Gr(),Hf(),ag(),sL(),or(),U();var Goe=900*1e3,VXt=6e4,xZr=900*1e3,WXt=6e4,Lc="codex-oauth",IZr="neurolink.codexFallback";function Qk(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 RZr(e){const t=Qk(e);return t==="ENOTFOUND"||t==="EAI_AGAIN"?"shared_provider_transport":"connection_transport"}function Gw(e,t){return Xr(e).slice(0,200)||t}var qoe=new Map;async function MZr(e,t,r,n){const o=qoe.get(e);if(o)return o;const s=(async()=>{const i=await r.peekTokens(e).catch(()=>null),a=i?.refreshToken??t,c=await n(a),l={accessToken:c.accessToken,refreshToken:c.refreshToken??a,expiresAt:c.expiresAt??i?.expiresAt??Date.now()+36e5};return i&&await r.saveTokens(e,{...l,tokenType:"Bearer",...i.scope?{scope:i.scope}:{}}),l})().finally(()=>{qoe.delete(e)});return qoe.set(e,s),s}async function joe(e,t){return MZr(e,t,ai,pKr)}var PZr=new Set(["host","connection","content-length","transfer-encoding","cookie","proxy-authorization","authorization","x-api-key","chatgpt-account-id","accept-encoding"]);function qw(e,t){return new Response(JSON.stringify({error:{type:"proxy_error",message:t}}),{status:e,headers:{"content-type":"application/json"}})}async function KXt(){const[e,t,r]=await Promise.all([ai.getProviderSnapshot(),Ok(),Wne()]),n=Date.now(),o=[];for(const[s,i]of Object.entries(e)){if(!s.startsWith(Ep)||i.disabled)continue;const a=i.tokens;if(!a||a.tokenType!=="Bearer")continue;let c=a.accessToken,l=a.expiresAt;if(fKr(l)&&a.refreshToken)try{const m=await joe(s,a.refreshToken);c=m.accessToken,l=m.expiresAt??l}catch(m){p.debug(`Codex proactive refresh failed for ${s.slice(Ep.length)}: ${m instanceof Error?m.message:String(m)}`)}const u=t[s],d=u&&u.coolingUntil>n;o.push({key:s,label:s.slice(Ep.length)||s,token:c,refreshToken:a.refreshToken,expiresAt:l,accountId:Lk(c),quota:r[s],coolingUntil:d?u.coolingUntil:void 0,coolingReason:u?.reason,expiredCooldownUntil:u&&!d?u.coolingUntil:void 0})}return o}function JXt(e,t){return[...e].sort((r,n)=>{const o=r.coolingUntil!==void 0&&r.coolingUntil>t,s=n.coolingUntil!==void 0&&n.coolingUntil>t;if(o!==s)return o?1:-1;const i=r.quota?r.quota.sessionUsed:-1,a=n.quota?n.quota.sessionUsed:-1;return i-a})}function YXt(e,t){const r={};for(const[o,s]of Object.entries(e)){const i=o.toLowerCase();PZr.has(i)||(r[i]=s)}r.authorization=`Bearer ${t.token}`;const n=Lk(t.token,t.accountId);return n&&(r["chatgpt-account-id"]=n),r["content-type"]="application/json",r["user-agent"]||(r["user-agent"]=Xne),r.originator||(r.originator=lKr),r.accept||(r.accept="text/event-stream"),r}function DZr(e,t,r){const n=r+VXt;if(e){if(e.weeklyStatus==="rejected"&&e.weeklyResetAt>0)return{coolingUntil:Math.max(e.weeklyResetAt*1e3,n),reason:"weekly"};if(e.sessionStatus==="rejected"&&e.sessionResetAt>0)return{coolingUntil:Math.max(e.sessionResetAt*1e3,n),reason:"session"}}const o=Math.min(xZr,Math.max(t,VXt));return{coolingUntil:r+o,reason:"transient"}}function OZr(e,t,r,n){e.responseHeaders||(e.responseHeaders={}),e.responseHeaders["x-neurolink-account"]=t.label,e.responseHeaders["x-neurolink-account-type"]="codex-oauth",e.responseHeaders["x-neurolink-served-by"]="codex",e.responseHeaders["x-neurolink-attempt"]=String(r),e.responseHeaders["x-neurolink-quota-source"]=n?"live":"none",n&&(e.responseHeaders["x-neurolink-quota-session-left-pct"]=String(Math.round((1-n.sessionUsed)*100)),e.responseHeaders["x-neurolink-weekly-left-pct"]=String(Math.round((1-n.weeklyUsed)*100)))}async function ZXt(e){const t=Date.now(),r=e.body??{},n=JSON.stringify(r),o=typeof r.model=="string"?r.model:"-",s=e.metadata?.[IZr]===!0,i=r.reasoning,a=i&&typeof i=="object"&&"effort"in i&&typeof i.effort=="string"?i.effort:void 0,c=(b,I,R={})=>Sp({timestamp:new Date().toISOString(),requestId:e.requestId,method:e.method,path:e.path,model:o,stream:!0,toolCount:Array.isArray(r.tools)?r.tools.length:0,account:b?.label??"",...b?{accountKey:b.key}:{},accountType:b?Lc:"",provider:"openai",...Ow(e.headers),responseStatus:I,responseTimeMs:Date.now()-t,...R});let l=!1;const u=async(b,I,R={})=>{s||l||(l=!0,I>=400?aw(I,b?.label,b?Lc:void 0,{requestId:e.requestId,...b?{accountKey:b.key}:{},errorType:R.errorType,terminalOutcome:R.terminalOutcome??"handler_error",message:R.errorMessage,errorCode:R.errorCode}):dk(b?.label,b?Lc:void 0),await c(b,I,R))},d=(b,I,R,A,P={})=>{fXt({timestamp:new Date().toISOString(),requestId:e.requestId,attempt:I,...s?{parentRequestId:e.requestId.replace(/:codex-fallback$/,"")}:{},...a?{reasoningEffort:a}:{},method:e.method,path:e.path,model:o,stream:!0,toolCount:Array.isArray(r.tools)?r.tools.length:0,account:b.label,accountKey:b.key,accountType:Lc,provider:"openai",responseStatus:A,responseTimeMs:Date.now()-t,attemptDurationMs:Date.now()-R,...P}).catch(()=>{})},m=await KXt(),h=async b=>(await u(b,499,{errorType:"client_cancelled",errorMessage:"Client cancelled Codex request",terminalOutcome:"client_cancelled"}),qw(499,"Client cancelled Codex request"));if(e.abortSignal?.aborted)return h();if(m.length===0)return await u(void 0,401,{errorType:"no_accounts",errorMessage:"No Codex accounts"}),qw(401,"No Codex accounts configured. Run `neurolink auth login codex`.");const f=Date.now(),g=JXt(m,f),y=g.filter(b=>!(b.coolingUntil!==void 0&&b.coolingUntil>f));if(y.length===0){const b=g.reduce((R,A)=>A.coolingUntil===void 0?R:R===void 0?A.coolingUntil:Math.min(R,A.coolingUntil),void 0),I=b?Math.max(1,Math.ceil((b-f)/1e3)):60;return await u(void 0,429,{errorType:"all_accounts_cooling",errorMessage:"All Codex accounts are rate-limited"}),new Response(JSON.stringify({error:{type:"rate_limit_error",message:"All Codex accounts are currently rate-limited"}}),{status:429,headers:{"content-type":"application/json","retry-after":String(I)}})}let w=0,E="All Codex accounts failed",_=502,C={errorType:"all_accounts_failed"},x;for(const b of y){let I=!1;for(;;){if(e.abortSignal?.aborted)return h(x);w+=1;const R=Date.now();x=b,cg(b.label,Lc);let A;try{A=await fetch(iKr,{method:"POST",headers:YXt(e.headers,b),body:n,signal:e.abortSignal?AbortSignal.any([e.abortSignal,AbortSignal.timeout(Goe)]):AbortSignal.timeout(Goe)})}catch(M){if(e.abortSignal?.aborted)return d(b,w,R,499,{errorType:"client_cancelled",errorMessage:"Client cancelled Codex request",retryable:!1}),h(b);p.debug(`Codex upstream fetch failed (${b.label}): ${Xr(M instanceof Error?M.message:String(M))}`);const D=Gw(M instanceof Error?M.message:String(M),"Codex upstream request failed"),$=Qk(M),F=RZr(M);if(ur(b.label,Lc,502),d(b,w,R,502,{errorType:"network_error",errorMessage:D,...$?{errorCode:$}:{},transportScope:F,retryable:["UND_ERR_CONNECT_TIMEOUT","ECONNREFUSED","ENOTFOUND","EAI_AGAIN"].includes($??"")}),C={errorType:"network_error",errorMessage:D,errorCode:$,transportScope:F},!["UND_ERR_CONNECT_TIMEOUT","ECONNREFUSED","ENOTFOUND","EAI_AGAIN"].includes($??""))return await u(b,502,{...C,errorMessage:D}),qw(502,"Codex upstream request failed");E="Codex upstream request failed",_=502;break}if(A.ok){const M=NZt(A.headers);M&&Tp(b.key,M).catch(()=>{}),b.expiredCooldownUntil!==void 0&&hg(b.key,b.expiredCooldownUntil).catch(()=>{}),OZr(e,b,w,M),d(b,w,R,A.status);const D={"content-type":A.headers.get("content-type")??"text/event-stream","cache-control":"no-cache",connection:"keep-alive",...e.responseHeaders??{}};if(!A.body)return ur(b.label,Lc,502),d(b,w,R,502,{errorType:"incomplete_stream",errorMessage:"Codex returned no response stream",retryable:!1}),await u(b,502,{terminalOutcome:"stream_error",errorType:"incomplete_stream",errorMessage:"Codex returned no response stream"}),new Response(A.body,{status:A.status,headers:D});const{stream:$,usage:F,evidence:G}=GKr(),j=new Response(A.body.pipeThrough($),{status:A.status,headers:D});return Bk(e.metadata,{onTerminal:({outcome:q,error:H,observedBodyBytes:W})=>F.then(se=>{const he=G(),de=he.completed&&W>=he.terminalBytes,J=he.errorType||(q==="completed"||q==="bodyless")&&!he.completed,ge=se?{inputTokens:se.inputTokens,outputTokens:se.outputTokens,cacheReadTokens:se.cacheReadTokens,cacheCreationTokens:se.cacheCreationTokens}:{},ye=he.firstUsefulOutputAt===void 0?{}:{firstUsefulOutputMs:Math.max(0,he.firstUsefulOutputAt-t)};return J?(ur(b.label,Lc,502),d(b,w,R,502,{errorType:he.errorType??"incomplete_stream",errorCode:he.errorCode,errorMessage:he.errorMessage??"Codex stream ended without a completion event",retryable:!1}),u(b,502,{...ge,...ye,terminalOutcome:"stream_error",errorType:he.errorType??"incomplete_stream",errorCode:he.errorCode,errorMessage:he.errorMessage??"Codex stream ended without a completion event"})):q==="completed"||q==="bodyless"||q==="client_cancelled"&&de?u(b,A.status,{terminalOutcome:"completed",...ge,...ye}):(q==="stream_error"&&(ur(b.label,Lc,502),d(b,w,R,502,{errorType:"stream_error",errorCode:Qk(H),errorMessage:Gw(H instanceof Error?H.message:"","Codex upstream stream failed"),retryable:!1})),u(b,q==="client_cancelled"?499:502,{errorType:q==="client_cancelled"?"client_cancelled":"stream_error",errorMessage:q==="client_cancelled"?"Client cancelled Codex stream":Gw(H instanceof Error?H.message:"","Codex upstream stream failed"),...q==="stream_error"?{errorCode:Qk(H)}:{},terminalOutcome:q,...ge,...ye}))}).catch(()=>{})}),j}const P=await A.text().catch(()=>"");if((A.status===401||A.status===403)&&!I&&b.refreshToken){const M=Gw(P,"Codex authentication rejected upstream");ur(b.label,Lc,A.status),d(b,w,R,A.status,{errorType:"authentication_error",errorMessage:M,retryable:!0}),I=!0;const D={accessToken:b.token,refreshToken:b.refreshToken,expiresAt:b.expiresAt??0};try{const $=await joe(b.key,b.refreshToken);b.token=$.accessToken,b.refreshToken=$.refreshToken??b.refreshToken,b.expiresAt=$.expiresAt??b.expiresAt,b.accountId=Lk($.accessToken);continue}catch($){if(hKr($)){await ai.markDisabledIfCurrent(b.key,D,"refresh_invalid")&&p.always(`[proxy] codex account=${b.label} disabled until re-authentication. Run: neurolink auth login codex --label ${b.label}`),C={errorType:"authentication_error",errorCode:"refresh_invalid"},_=401,E="Codex token refresh failed; re-login required";break}await bu(b.key,Date.now()+WXt,"auth").catch(()=>{}),p.debug(`[proxy] codex account=${b.label} refresh failed transiently; cooling and rotating`),C={errorType:"auth_refresh_unavailable",errorCode:Qk($)},_=503,E="Codex token refresh temporarily unavailable";break}}if(A.status===429){const M=NZt(A.headers);M&&Tp(b.key,M).catch(()=>{});const D=e2(A.headers.get("retry-after")),$=DZr(M,D,Date.now());await bu(b.key,$.coolingUntil,$.reason).catch(()=>{});const F=$.reason==="transient"?"transient":"quota",G=Gw(P,"Codex account rate-limited");ur(b.label,Lc,A.status,F),d(b,w,R,A.status,{errorType:"rate_limit_error",errorMessage:G,retryable:!0,rateLimitKind:F,cooldownReason:$.reason}),C={errorType:"rate_limit_error"},_=429,E="Codex account rate-limited";break}(A.status===401||A.status===403)&&await bu(b.key,Date.now()+WXt,"auth").catch(()=>{});const L=Gw(P,"Codex error"),B=A.status===401||A.status===403?"authentication_error":"api_error";ur(b.label,Lc,A.status),d(b,w,R,A.status,{errorType:B,errorMessage:L,retryable:A.status>=500}),C={errorType:B},_=A.status>=500?502:A.status,E=L;break}}return await u(x,_,{...C,errorMessage:C.errorMessage??E}),qw(_,E)}async function NZr(e){const t=await KXt();if(t.length===0)return qw(401,"No Codex accounts configured. Run `neurolink auth login codex`.");const r=Date.now(),n=JXt(t,r),o=d=>d.coolingUntil!==void 0&&d.coolingUntil>r,s=[...n.filter(d=>!o(d)),...n.filter(o)],a=new URLSearchParams(e.query??{}).toString(),c=a?`${IZt}?${a}`:IZt;let l=502,u="Codex model discovery upstream failed";for(const d of s){let m=!1;for(;;){let h;try{h=await fetch(c,{method:"GET",headers:YXt(e.headers??{},d),signal:AbortSignal.timeout(Goe)})}catch(y){l=502,u=`Codex model discovery upstream failed: ${y instanceof Error?y.message:String(y)}`;break}if(h.status===401||h.status===403){if(!m&&d.refreshToken){m=!0;try{const y=await joe(d.key,d.refreshToken);d.token=y.accessToken,d.refreshToken=y.refreshToken??d.refreshToken,d.expiresAt=y.expiresAt??d.expiresAt,d.accountId=Lk(y.accessToken);continue}catch{l=401,u="Codex token refresh failed; re-login required";break}}l=h.status,u="Codex model discovery rejected upstream";break}const f=await h.text(),g=h.headers.get("content-type")??"application/json";return new Response(f,{status:h.status,headers:{"content-type":g}})}}return qw(l,u)}function LZr(e=""){return{prefix:`${e}/backend-api/codex`,routes:[{method:"POST",path:`${e}/backend-api/codex/responses`,description:"Codex ChatGPT-backend Responses API (account pool)",handler:t=>ZXt(t)},{method:"GET",path:`${e}/backend-api/codex/models`,description:"Codex model discovery, relayed upstream (account pool)",handler:t=>NZr(t)}]}}var t2=new Set(["cookie","proxy-authorization","host","connection","content-length","transfer-encoding"]),Hoe="proxy/internal",Voe="internal";function XXt(e,t){return e?t==="codex-oauth"?{accountKey:e.startsWith("codex:")?e:`codex:${e}`,provider:"openai"}:t==="oauth"||t==="api_key"||t==="passthrough"?{accountKey:t==="passthrough"?e:hp(e),provider:"anthropic"}:{}:{}}var _p=0,QXt=0,eA=5,r2=2,Woe=[250,1e3],eQt=4,tQt=[250,500,1e3,2e3],Koe=1,FZr=120*1e3,Joe=2,rQt=3e4,nQt=11520*60*1e3,oQt=5e3,$Zr=900*1e3,Yoe=900*1e3,UZr=3e4,BZr=300*1e3,tA=900*1e3,sQt;function Zoe(e,t){return sQt??=new FS({headersTimeout:tA,bodyTimeout:tA}),fetch(e,{...t,dispatcher:sQt})}var rc=new Map,rA=new EKr,jw=new _Kr,Xoe=900*1e3,iQt=new Map,aQt=new Map,n2=new Map,zZr={release:()=>{}};function cQt(e){let t=n2.get(e);return t||(t={active:0,waiters:[]},n2.set(e,t)),t}function Qoe(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(lQt(e,t))}}function lQt(e,t){let r=!1;return{release:()=>{r||(r=!0,t.active=Math.max(0,t.active-1),Qoe(e,t),uQt(e,t))}}}function uQt(e,t){t.active===0&&t.waiters.length===0&&n2.delete(e)}function GZr(e,t){const r=zoe(t);if(r===void 0)return zZr;const n=cQt(e);if(!(n.waiters.length>0||n.active>=r))return n.active+=1,lQt(e,n)}function qZr(e,t){const r=zoe(t);if(r===void 0)return!0;const n=n2.get(e);return!n||n.waiters.length===0&&n.active<r}function jZr(e,t){const r=zoe(t);if(r===void 0)throw new Error("Account admission queue requires an explicit capacity");const n=cQt(e);let o=!0,s,i;const a=new Promise(l=>{i=l}),c={capacity:r,resolve:l=>{o=!1,s=l,i(l)}};return n.waiters.push(c),Qoe(e,n),{accountKey:e,promise:a,cancel:()=>{if(s){const u=s;s=void 0,u.release();return}if(!o)return;o=!1;const l=n.waiters.indexOf(c);l>=0&&(n.waiters.splice(l,1),Qoe(e,n)),uQt(e,n)}}}async function HZr(e,t,r,n=mQt){const o=[...new Set(e)].map(i=>jZr(i,t));let s;try{return await xt(N5(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 dQt=!1,ese,tse=6e4,mQt=9e4,VZr=12e4,WZr=250,KZr=15e3;function Tg(e,t,r){t<=1||e===r&&(_p=(_p+1)%t)}function pQt(e,t){if(!t)return 0;const r=e.findIndex(n=>K7t(n.key,t));return r>=0?r:0}function JZr(e,t){if(e.length<=1)return;const r=pQt(e,t);if(_p===r)return;const n=e[r],o=rc.get(n.key);if((!o||!o.coolingUntil||Date.now()>=o.coolingUntil)&&(_p=r,o?.coolingUntil)){const s=o.coolingUntil;o.coolingUntil=void 0,o.coolingReason=void 0,hg(n.key,s).catch(()=>{}),p.always(`[proxy] home primary account=${n.label} cooling expired, resetting primaryAccountIndex to ${r}`)}}function hQt(e){const t=rc.get(e);return!!t?.coolingUntil&&Date.now()<t.coolingUntil}function YZr(e,t,r=Date.now()){let n=iQt.get(e);if(!n||r>=n.coolingUntil?(n={coolingUntil:t,retriesClaimed:0},iQt.set(e,n)):t>n.coolingUntil&&(n.coolingUntil=t),!(n.retriesClaimed>=Joe))return n.retriesClaimed+=1,n.retriesClaimed}function ZZr(e,t,r=Date.now()){if(t<=r)return 0;if(t-r>mQt)return;let n=aQt.get(e);!n||r>=n.coolingUntil?(n={coolingUntil:t,nextAdmissionAt:t},aQt.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>KZr))return n.nextAdmissionAt=o+WZr,o-r}async function XZr(e){const t=Date.now()+VZr;for(;Date.now()<t;){const r=e.filter(i=>!hQt(i.key));if(r.length>0)return r;const n=Date.now(),o=e.map(i=>({account:i,state:Ca(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=ZZr(o.account.key,o.state.coolingUntil,n);if(s===void 0||n+s>t)return[];p.always(`[proxy] all usable accounts are transiently cooling; queueing request for account=${o.account.label} in ${s}ms`),await ku(s)}return[]}function As(e,t){if(!e||e<=0)return;const r=e>4102444800?e:e*1e3;return r>t?r:void 0}function nA(e,t){try{const r=t.poolAccounts?RKr(t.poolAccounts.map(o=>{const s=rc.get(o.key);return{...s?.coolingUntil!==void 0?{coolingUntil:s.coolingUntil}:{},...s?.quota?{quota:s.quota}:{}}})):void 0,n=IKr({...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??{},...hse(n)}}catch(r){p.debug(`[proxy] failed to publish limit headers: ${r instanceof Error?r.message:String(r)}`)}}function o2(e,t,r){const n=Math.min(nQt,(r&&fZt[r])??nQt);return Math.min(Math.max(e,t+oQt),t+n)}function s2(e){return e?.trim().toLowerCase()==="allowed"}function fQt(e,t){return!e||As(e.resetsAt,t)===void 0?!1:e.status?.trim().toLowerCase()==="rejected"||(e.used??0)>=1}function QZr(e,t,r,n=Fc){if(!e||!t||!s2(e.sessionStatus)||!s2(e.weeklyStatus)||Hw(e,n))return null;const o=use(e,t,r);return fQt(o,r)?o:null}function eXr(e,t,r=Fc){return!s2(e.sessionStatus)||!s2(e.weeklyStatus)||Hw(e,r)?!1:(e.windows??[]).some(n=>n.kind==="weekly_scoped"&&typeof n.scopeModel=="string"&&t-lse(e,n)<=Xoe&&fQt(n,t))}function rse(e,t,r,n=e?.unifiedStatus,o=Fc,s){if(e&&e.weeklyStatus==="rejected"){const l=As(e.weeklyResetAt,r)??(t>0?r+t:r+tse);return{reason:"weekly",scope:"account",coolingUntil:o2(l,r,"weekly"),rotateImmediately:!0}}const i=Hw(e,o);if(e&&e.sessionStatus==="rejected"&&!i){const l=As(e.sessionResetAt,r)??(t>0?r+t:r+tse);return{reason:"session",scope:"account",coolingUntil:o2(l,r,"session"),rotateImmediately:!0}}const a=QZr(e,s,r,o);if(a)return{reason:"unified",scope:"model",coolingUntil:As(a.resetsAt,r)??(t>0?r+t:r+Yoe),rotateImmediately:!0};if(n?.trim().toLowerCase()==="rejected"&&!i){const l=t>0?r+t:r+Yoe;return{reason:"unified",scope:"account",coolingUntil:o2(l,r,"unified"),rotateImmediately:!0}}const c=t>0?t:tse;return{reason:"transient",scope:"account",coolingUntil:r+Math.max(oQt,Math.min(c,$Zr)),rotateImmediately:!1}}function nse(e,t){return Math.max(0,Math.round((e-t)/6e4))}function ose(e,t,r,n=Fc){const o=Hw(t,n),s=eXr(t,r,n);let i,a;if(t.weeklyStatus==="rejected"&&(i=As(t.weeklyResetAt,r),a="weekly"),i===void 0&&o&&e.coolingUntil&&(e.coolingReason==="session"||e.coolingReason==="unified")){const l=e.coolingUntil;return e.coolingUntil=void 0,e.coolingReason=void 0,p.always("[proxy] clearing subscription cooldown because Anthropic explicitly permits overage"),{kind:"cleared",coolingUntil:l}}if(i===void 0&&t.sessionStatus==="rejected"&&!o?(i=As(t.sessionResetAt,r),a="session"):i===void 0&&t.unifiedStatus==="rejected"&&!o&&!s&&(i=r+Yoe,a="unified"),i===void 0){if(!!e.coolingUntil&&(e.coolingReason==="weekly"&&t.weeklyStatus==="allowed"||e.coolingReason==="session"&&t.sessionStatus==="allowed"||e.coolingReason==="unified"&&(t.unifiedStatus==="allowed"||s))&&e.coolingUntil){const u=e.coolingUntil,d=e.coolingReason;return e.coolingUntil=void 0,e.coolingReason=void 0,p.always(`[proxy] clearing ${d} cooldown from fresh provider quota`),{kind:"cleared",coolingUntil:u}}return null}const c=o2(i,r,a);return!e.coolingUntil||c>e.coolingUntil?(e.coolingUntil=c,e.coolingReason=a,p.always(`[proxy] proactively cooling account (${a}) ~${nse(c,r)}m from success-response quota (status rejected)`),{kind:"cooled",coolingUntil:c,coolingReason:a??"unified"}):null}async function tXr(e){try{const[t,r]=await Promise.all([Wne(),Ok()]),n=Date.now();for(const o of e){const s=Ca(o.key);s.quota||(s.quota=t[o.key]??t[o.label]);const i=r[o.key];i?.coolingUntil>n&&(!s.coolingUntil||i.coolingUntil>s.coolingUntil)&&(s.coolingUntil=i.coolingUntil,s.coolingReason=i.reason)}}catch{}}var rXr=15e3,gQt=new Map,i2=null,nXr=4;async function yQt(e,t,r,n){if(t.ok===!1)return null;const o=Ca(e.key),s=AZt(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=fg(o.quota,s);const i=ose(o,s,Date.now());return i?.kind==="cooled"?await bu(e.key,i.coolingUntil,i.coolingReason).catch(()=>{}):i?.kind==="cleared"&&await hg(e.key,i.coolingUntil).catch(()=>{}),await Tp(e.key,s).catch(()=>{}),s}async function vQt(e){const t=await eKr(e);return t.ok===!1||AZt(t.usage,{now:Date.now(),prior:rc.get(e.key)?.quota??null})?t:{ok:!1,reason:"parse",error:"usage payload had no recognizable limit windows"}}async function a2(e,t){const r=await rA.run(e,t,vQt);r.kind!=="completed"||r.result.ok===!1||await yQt(e,r.result,r.startedAt)}var oA=null;async function oXr(e){if(oA)return{anthropic:oA.anthropic,codex:oA.codex};const[t,r]=await Promise.all([CZt(e),yKr()]);return{anthropic:t,codex:r}}async function sXr(){if(oA)return oA.knownKeys;const[e,t]=await Promise.all([ai.listByPrefix("anthropic:"),ai.listByPrefix("codex:")]);return new Set([...e.map(hp),...t])}async function sse(e={}){const t=Date.now(),r=await oXr(e.accountAllowlist),n=[...r.anthropic.map(u=>({account:u,provider:"anthropic"})),...r.codex.map(u=>({account:u,provider:"codex"}))],o=e.accountFilter?n.filter(({account:u})=>u.label===e.accountFilter||u.key===e.accountFilter):n,s=await Wne().catch(()=>({})),i=(u,d,m,h,f)=>{const g=rc.get(u.key),y=d==="anthropic"?s[u.key]??s[u.label]??null:s[u.key]??null,w={account:u.label,key:u.key,provider:d,type:u.type,status:m,quota:h??g?.quota??y};return f!==void 0&&(w.error=f),g?.coolingUntil&&g.coolingUntil>Date.now()&&(w.coolingUntil=g.coolingUntil,g.coolingReason&&(w.coolingReason=g.coolingReason)),w};if(e.snapshotOnly)return{fetchedAt:t,snapshot:!0,results:o.map(({account:u,provider:d})=>i(u,d,"snapshot",null)),refreshMetrics:rA.getMetrics()};const a=new Array(o.length);let c=0;const l=async()=>{for(;;){const u=c++;if(u>=o.length)return;const{account:d,provider:m}=o[u];if(d.type!=="oauth"){a[u]=i(d,m,"skipped_api_key",null);continue}const h=gQt.get(d.key)??0;if(Date.now()-h<rXr){a[u]=i(d,m,"throttled",null);continue}if(gQt.set(d.key,Date.now()),m==="codex"){try{const f=await vKr(d);if(f.ok===!1){a[u]=i(d,m,"error",null,`codex usage fetch failed: ${f.reason}`);continue}await Tp(d.key,f.quota),a[u]=i(d,m,"refreshed",f.quota)}catch(f){a[u]=i(d,m,"error",null,f instanceof Error?f.message:String(f))}continue}try{const f=await rA.run(d,`manual:${d.key}`,vQt,{force:!0});if(f.kind!=="completed"){a[u]=i(d,m,"throttled",null);continue}const g=f.result;if(g.ok===!1){a[u]=i(d,m,"error",null,g.error);continue}const y=await yQt(d,g,f.startedAt,s[d.key]??s[d.label]??null);if(!y){a[u]=i(d,m,"error",null,"usage payload had no recognizable limit windows");continue}a[u]=i(d,m,"refreshed",y)}catch(f){a[u]=i(d,m,"error",null,f instanceof Error?f.message:String(f))}}};return await Promise.all(Array.from({length:Math.min(nXr,o.length||1)},()=>l())),{fetchedAt:t,snapshot:!1,results:a,refreshMetrics:rA.getMetrics()}}function ise(){const e=(process.env.NEUROLINK_PROXY_QUOTA_ROUTING??"").toLowerCase();return e!=="off"&&e!=="false"&&e!=="0"}function ase(){const e=Number(process.env.NEUROLINK_PROXY_SESSION_SOFT_LIMIT??"");return Number.isFinite(e)&&e>0&&e<=1?e:.97}function sA(){const e=Number(process.env.NEUROLINK_PROXY_SESSION_RESET_TOLERANCE_MS??"");return Number.isInteger(e)&&e>0?e:900*1e3}var Fc="auto";function cse(e){e!==void 0&&(Fc=e)}function iXr(){return Fc}function Hw(e,t=Fc){return t==="never"?!1:yZt(e)}var aXr=4;function c2(e){return e.toLowerCase().replace(/[^a-z0-9]/g,"")}function cXr(e){const t=c2(e);return t.startsWith("claude")?t.slice(6):t}function lXr(e,t,r){if(e.scopeModelId&&c2(OL(e.scopeModelId))===r)return Number.MAX_SAFE_INTEGER;if(!e.scopeModel)return null;const n=cXr(e.scopeModel);return n.length<aXr||!t.includes(n)?null:n.length}function lse(e,t){return t.updatedAt??e.windowsUpdatedAt??e.lastUpdated}function use(e,t,r=Date.now()){if(!e?.windows?.length||!t)return null;const n=c2(t);if(!n)return null;const o=c2(OL(t));let s=null,i=-1,a=-1;for(const c of e.windows){if(r-lse(e,c)>Xoe)continue;const l=lXr(c,n,o);if(l===null)continue;const u=lse(e,c);(l>i||l===i&&u>a)&&(s=c,i=l,a=u)}return s}function uXr(e,t,r=Date.now(),n=Fc){if(!t||e.length===0)return{eligible:e,exhaustion:null};const o=[],s=[];let i;for(const c of e){const l=rc.get(c.key)?.quota,u=use(l,t,r),d=u?As(u.resetsAt,r):void 0;if(!(u!==null&&d!==void 0&&((u.status??"").trim().toLowerCase()==="rejected"||(u.used??0)>=1)&&!Hw(l,n))||!u){o.push(c);continue}s.push({label:c.label,window:u}),i??=l?.overageDisabledReason}if(o.length>0||s.length===0)return{eligible:o,exhaustion:null};const a=Math.min(...s.map(c=>As(c.window.resetsAt,r)??Number.POSITIVE_INFINITY));return{eligible:o,exhaustion:{model:t,scopeModel:s[0]?.window.scopeModel??OL(t),earliestResetMs:a,accounts:s.map(c=>c.label),...i?{overageDisabledReason:i}:{}}}}function l2(e,t,r,n,o,s=Fc){const i=rc.get(e),a=i?.quota,c=a&&Number.isFinite(a.lastUpdated)?a.lastUpdated:null,l=c===null?null:Math.max(0,t-c),u=rA.getState(e),d=l!==null&&l>Xoe,m=W=>W.trim().toLowerCase(),h=yZt(a),f=[a?.unifiedStatus,a?.sessionStatus,a?.weeklyStatus].filter(W=>!!W?.trim()),g=d&&!!a&&!h&&f.some(W=>m(W)!=="allowed"),y=a?d?g?"refresh_due":"stale_known":"fresh":"unknown",w=g?void 0:a,E=!!i?.coolingUntil&&t<i.coolingUntil,_=As(w?.weeklyResetAt,t),C=As(w?.sessionResetAt,t),x=C!==void 0,b=_!==void 0,I=w?x?w.sessionUsed??0:0:null,R=w?b?w.weeklyUsed??null:0:null,A=w?x?w.sessionStatus??"unknown":"allowed":null,P=w?b?w.weeklyStatus??"unknown":"allowed":null,L=Hw(w,s),B=!L&&(A==="rejected"||A==="throttled"||P==="rejected"||P==="throttled"||w?.unifiedStatus?.trim().toLowerCase()==="rejected"||x&&(I??0)>=1||b&&(R??0)>=1),M=!B&&!L&&x&&(I??0)>=r,D=B||M,$=use(w,o,t),F=$?As($.resetsAt,t):void 0,G=F!==void 0,j=$?G?$.used:0:null,q=$?G?$.status??"unknown":"allowed":null,H=!d&&G&&(j??0)>=r;return{usable:!E&&!B&&(q!=="rejected"||L),saturated:D,scopedModel:$?.scopeModel??null,scopedStatus:q,scopedUsed:j,scopedReset:F??Number.POSITIVE_INFINITY,scopedUsedForSort:j??-1,scopedSaturated:H,hasQuota:!!a,quotaEvidenceRank:y==="fresh"||y==="stale_known"?0:y==="refresh_due"?1:2,quotaStale:d,quotaFreshness:y,refreshNeeded:y==="unknown"||y==="refresh_due",refreshReason:y==="unknown"?"startup_unknown":y==="refresh_due"?"ambiguous_snapshot":null,refreshInFlight:u.inFlight,lastRefreshAttemptAt:u.lastAttemptAt??null,lastRefreshSuccessAt:u.lastSuccessAt??null,nextRefreshEligibleAt:u.nextEligibleAt??null,saturationKind:B?"hard":M?"soft":"none",softLimitOverrideReason:L&&x&&(I??0)>=r?"overage":null,quotaLastUpdated:c,quotaAgeMs:l,coolingActive:E,coolingReason:i?.coolingReason??null,coolingUntil:i?.coolingUntil??0,unifiedStatus:w?.unifiedStatus??null,fallbackStatus:w?.fallbackStatus??null,upgradePaths:w?.upgradePaths??null,overageEligible:L,overageStatus:w?.overageStatus??null,sessionStatus:A,sessionUsed:I,sessionResetBucket:x?Math.floor(C/n):Number.POSITIVE_INFINITY,sessionReset:C??Number.POSITIVE_INFINITY,weeklyStatus:P,weeklyReset:_??Number.POSITIVE_INFINITY,weeklyUsed:R,weeklyUsedForSort:R??-1}}function wQt(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 dXr(e,t,r,n,o,s){const i=new Map(e.map(a=>[a.key,l2(a.key,t,n,o,s)]));return{orderedAccounts:[...e].sort((a,c)=>wQt(a,c,i,r)[0]),metricsByKey:i}}function mXr(e,t,r,n){for(const u of e){if(u.type!=="oauth")continue;const d=n?.get(u.key)??l2(u.key,Date.now(),r,sA());d.quotaFreshness==="unknown"?a2(u,`startup-unknown:${u.key}`).catch(m=>{p.debug(`[proxy] background quota discovery failed account=${u.label}: ${Ml(m)}`)}):d.quotaFreshness==="refresh_due"&&a2(u,`ambiguous:${d.quotaLastUpdated??0}`).catch(m=>{p.debug(`[proxy] ambiguous quota refresh failed account=${u.label}: ${Ml(m)}`)})}const o=t[0],s=t[1];if(!o||!s||s.type!=="oauth")return;const i=rc.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 l=["handoff",o.key,i.sessionResetAt??0,i.weeklyResetAt??0,s.key].join(":");a2(s,l).catch(u=>{p.debug(`[proxy] quota handoff prewarm failed account=${s.label}: ${Ml(u)}`)})}function pXr(e,t,r,n){!t||t.type!=="oauth"||l2(t.key,Date.now(),n,sA()).quotaFreshness==="fresh"||a2(t,`hard-handoff:${e.key}:${r}:${t.key}`).catch(s=>{p.debug(`[proxy] hard-handoff quota refresh failed account=${t.label}: ${Ml(s)}`)})}function hXr(e){const{accounts:t,orderedAccounts:r,metricsByKey:n,evaluatedAt:o,strategy:s,primaryKey:i,quotaRoutingEnabled:a,quotaOrdered:c,sessionSoftLimit:l,sessionResetToleranceMs:u,rotationOffset:d}=e,m=new Map(t.map((E,_)=>[E.key,_])),h=!!i&&t.some(E=>E.key===i),f=[];for(const E of r){const _=n.get(E.key);if(!_){p.warn(`[proxy] routing evidence omitted because metrics are missing for account=${E.label}`);return}f.push({account:E.label,accountType:E.type,sourceIndex:m.get(E.key)??f.length,rank:f.length,configuredPrimary:!!i&&E.key===i,usable:_.usable,saturated:_.saturated,quotaObserved:_.hasQuota,quotaStale:_.quotaStale,quotaFreshness:_.quotaFreshness,refreshNeeded:_.refreshNeeded,refreshReason:_.refreshReason,refreshInFlight:_.refreshInFlight,lastRefreshAttemptAt:_.lastRefreshAttemptAt,lastRefreshSuccessAt:_.lastRefreshSuccessAt,nextRefreshEligibleAt:_.nextRefreshEligibleAt,saturationKind:_.saturationKind,softLimitOverrideReason:_.softLimitOverrideReason,quotaLastUpdated:_.quotaLastUpdated,quotaAgeMs:_.quotaAgeMs,coolingActive:_.coolingActive,coolingReason:_.coolingReason,coolingUntil:_.coolingUntil>0&&Number.isFinite(_.coolingUntil)?_.coolingUntil:null,unifiedStatus:_.unifiedStatus,fallbackStatus:_.fallbackStatus,upgradePaths:_.upgradePaths,overageEligible:_.overageEligible,overageStatus:_.overageStatus,sessionStatus:_.sessionStatus,sessionUsed:_.sessionUsed,sessionResetAt:Number.isFinite(_.sessionReset)?_.sessionReset:null,sessionResetBucket:Number.isFinite(_.sessionResetBucket)?_.sessionResetBucket:null,weeklyStatus:_.weeklyStatus,weeklyUsed:_.weeklyUsed,weeklyResetAt:Number.isFinite(_.weeklyReset)?_.weeklyReset:null,scopedModel:_.scopedModel,scopedStatus:_.scopedStatus,scopedUsed:_.scopedUsed,scopedResetAt:Number.isFinite(_.scopedReset)?_.scopedReset:null})}const g=r[0];let y,w;return r.length===1?(y="single_account",w="single_account"):c?(y="quota",w=wQt(r[0],r[1],n,i)[1]):s==="round-robin"?(y="round_robin",w="round_robin"):(y="primary",w=h&&g?.key===i?"configured_primary":"insertion_order"),{schemaVersion:1,evaluatedAt:new Date(o).toISOString(),strategy:s,mode:y,selectionReason:w,quotaRoutingEnabled:a,quotaInputsUsed:c,sessionSoftLimit:l,sessionResetToleranceMs:u,configuredPrimaryAccount:i??null,configuredPrimaryMatched:h,rotationOffset:d,initialAccount:g?.label??"",candidates:f}}function fXr(e){const{enabledAccounts:t,accountStrategy:r,primaryAccountKey:n,quotaRoutingEnabled:o,sessionSoftLimit:s,sessionResetToleranceMs:i,requestedModel:a,setRoutingDecision:c}=e;let l=[...t];const u=Date.now();let d,m=0;const h=r==="fill-first"&&l.length>1&&o;if(!h&&r==="fill-first"&&JZr(t,n),h){const g=dXr(t,u,n,s,i,a);l=g.orderedAccounts,d=g.metricsByKey,p.shouldLog("debug")&&p.debug(`[proxy] quota-ordered fill sequence: ${l.map(y=>y.label).join(" \u2192 ")}`)}else{if(r==="round-robin"&&l.length!==QXt&&(_p=pQt(l,n),QXt=l.length),l.length>1&&(m=_p%l.length,r==="round-robin"&&(_p=(_p+1)%l.length),m>0)){const g=l.splice(0,m);l.push(...g)}d=new Map(t.map(g=>[g.key,l2(g.key,u,s,i,a)]))}const f=hXr({accounts:t,orderedAccounts:l,metricsByKey:d,evaluatedAt:u,strategy:r,primaryKey:n,quotaRoutingEnabled:o,quotaOrdered:h,sessionSoftLimit:s,sessionResetToleranceMs:i,rotationOffset:m});return f&&c(f),{orderedAccounts:l,metricsByKey:d}}var u2=new Map,gXr=300*1e3,yXr=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"]),vXr=["oauth-2025-04-20","claude-code-20250219","fine-grained-tool-streaming-2025-05-14"];function d2(e){return e.replace(/[^a-zA-Z0-9._@-]/g,"_")}function TQt(e){return ht(aa(),".neurolink","header-snapshots",`anthropic_${d2(e)}.json`)}function wXr(e,t){if(t?.headers)for(const[r,n]of Object.entries(t.headers)){const o=r.toLowerCase();typeof n=="string"&&!e[o]&&!t2.has(o)&&o!=="authorization"&&o!=="x-api-key"&&o!=="x-claude-code-session-id"&&(e[o]=n)}}async function TXr(e){try{const t=d2(e),r=u2.get(t);if(r&&Date.now()-r.loadedAt<gXr)return r.snapshot;const n=TQt(e);try{await C1(n)}catch{return null}const o=JSON.parse(await Pr(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:(u2.set(t,{snapshot:s,loadedAt:Date.now()}),s)}catch{return null}}function EXr(e,t){const r={...t??{}};for(const[n,o]of Object.entries(e)){const s=n.toLowerCase();typeof o=="string"&&yXr.has(s)&&!t2.has(s)&&s!=="authorization"&&s!=="x-api-key"&&s!=="x-claude-code-session-id"&&(r[s]=o)}return r}function EQt(e){if(!e||typeof e!="object")return;const t=e,r=yvt(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 SQt(e,t){return typeof e["x-claude-code-session-id"]=="string"||e["user-agent"]?.startsWith("claude-cli/")||!!t?.metadataUserId||!!t?.billingHeader||!!t?.agentBlock}function SXr(e,t){return e?JSON.stringify(e.headers??{})===JSON.stringify(t.headers??{})&&JSON.stringify(e.body??{})===JSON.stringify(t.body??{}):!1}async function _Xr(e,t){const r=TQt(e);await Ea(r,t,384),u2.set(d2(e),{snapshot:t,loadedAt:Date.now()})}async function bXr(e,t,r,n){const o=await TXr(e);let s;try{s=JSON.parse(n)}catch{return o}const i=EQt(s);if(!SQt(r,i))return o;const a={accountKey:t,capturedAt:new Date().toISOString(),source:"claude-code",headers:EXr(r,o?.headers),body:{...o?.body??{},...i??{},...typeof r["x-claude-code-session-id"]=="string"?{sessionId:r["x-claude-code-session-id"]}:{}}};if(SXr(o,a))return o;try{await _Xr(e,a)}catch(c){p.warn("[proxy] failed to persist Claude snapshot",{accountLabel:e,error:c instanceof Error?c.message:String(c)}),u2.set(d2(e),{snapshot:a,loadedAt:Date.now()})}return a}function dse(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 _Qt(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 CXr(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 l=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:M4(s.system[l]?.text??r?.body?.billingHeader)};if(n&&u>=0)l<0&&s.system.unshift(d);else{const h=[l,u].filter(f=>f>=0).sort((f,g)=>g-f);for(const f of h)s.system.splice(f,1);s.system.length>0&&Nvt(s,s.system),s.system=[d,i]}}}else{const l={type:"text",text:M4(r?.body?.billingHeader)};s.system=[l,i]}const a=t.substring(0,Math.min(20,t.length)),c=vvt(a,{existingUserId:s.metadata?.user_id??r?.body?.metadataUserId,preferredSessionId:o??r?.body?.sessionId});return s.metadata={...s.metadata,user_id:c.metadataUserId},{bodyStr:JSON.stringify(s),sessionId:c.sessionId}}catch{return{bodyStr:e}}}async function kXr(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:ak,label:s,token:r,refreshToken:n,expiresAt:o,type:"oauth",persistTarget:{credPath:t}});if(!i)return a();const c=Ca(ak);if(c.permanentlyDisabled)return;const l=(await Ok())[ak];if(l?.coolingUntil>Date.now()&&(!c.coolingUntil||l.coolingUntil>c.coolingUntil)&&(c.coolingUntil=l.coolingUntil,c.coolingReason=l.reason),c.coolingReason==="auth"&&c.coolingUntil&&c.coolingUntil>Date.now())return a();if(!n){p.always("[proxy] skipping legacy account (expired, no refresh token)"),await Wd(a(),c,"missing_refresh_token");return}const u={token:r,refreshToken:n,expiresAt:o,label:s},d=await _Zt(u);if(!d.success){if(yg(d)){await Wd(a(),c,"refresh_invalid");return}const m=await h2(a(),c);return p.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 UL(t,u),await f2(a(),c),p.always("[proxy] refreshed legacy account at startup"),a()}async function AXr(e){const{ctx:t,body:r,route:n,modelRouter:o,tracer:s,requestStartTime:i,logProxyBody:a}=e;s?.setMode("full");const c=noe(r),l=zw({provider:n.provider,model:n.model},o?.getFallbackChain()??[],r.model,c,o?.isAutoFallbackEnabled?.()??!1);bQt(a,"translated_request",l);const u=l.attempts;if(r.stream)return boe({ctx:t,format:"claude",requestModel:r.model,parsed:c,attempts:u,tracer:s,requestStartTime:i});try{return await Coe({ctx:t,format:"claude",requestModel:r.model,parsed:c,attempts:u,tracer:s,requestStartTime:i,terminalFailureStatus:502})}catch(d){const m=d instanceof Error?d.message:"unknown error";p.error(`[claude-proxy] Translated generation failed for ${r.model}: ${m}`);const h=ba(502,`Generation failed: ${m}`),f=JSON.stringify(h);return a({phase:"client_response",headers:{"content-type":"application/json"},body:f,bodySize:Buffer.byteLength(f,"utf8"),contentType:"application/json",account:"translation",accountType:"translation",responseStatus:502,durationMs:Date.now()-i}),h}}function bQt(e,t,r){e({phase:"routing_decision",contentType:"application/json",body:{stage:t,attempts:r.attempts}})}async function xXr(e){const{ctx:t,body:r,clientRequestBody:n,tracer:o,requestStartTime:s,logProxyBody:i,logFinalRequest:a}=e;o?.setMode("passthrough-cli");const c=n,l=Array.isArray(r.tools)?r.tools.length:0,u={};for(const[f,g]of Object.entries(t.headers))!t2.has(f.toLowerCase())&&g&&(u[f]=g);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(c),i({phase:"upstream_request",headers:u,body:c,bodySize:Buffer.byteLength(c,"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"}}),cg("passthrough","passthrough");let m;try{m=await Zoe("https://api.anthropic.com/v1/messages?beta=true",{method:"POST",headers:u,body:c,signal:AbortSignal.timeout(tA)})}catch(f){const g=f instanceof Error?f.message:String(f);ur("passthrough","passthrough",502),o?.setError("network_error",g),d?.end(),o?.end(502,Date.now()-s),a(502,"passthrough","passthrough","network_error",g);const y=ba(502,`Passthrough fetch failed: ${g}`),w=JSON.stringify(y);return i({phase:"client_response",headers:{"content-type":"application/json"},body:w,bodySize:Buffer.byteLength(w,"utf8"),contentType:"application/json",account:"passthrough",accountType:"passthrough",attempt:1,responseStatus:502,durationMs:Date.now()-s}),y}const h={};m.headers.forEach((f,g)=>{h[g]=f}),o?.logUpstreamResponseHeaders(h);{const f=kw(m.headers,{model:r.model});nA(t,{upstreamHeaders:m.headers,quota:f,source:f?"live":"none",accountType:"passthrough",servedBy:"anthropic",attempt:1})}if(!m.ok){const f=await m.text();ur("passthrough","passthrough",m.status,m.status===429?"quota":void 0),o?.logUpstreamResponseBody(f),i({phase:"upstream_response",headers:h,body:f,bodySize:Buffer.byteLength(f,"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:f,bodySize:Buffer.byteLength(f,"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",f.slice(0,500)),o?.end(m.status,Date.now()-s),a(m.status,"passthrough","passthrough",m.status===429?"rate_limit_error":"api_error",f);try{return JSON.parse(f)}catch{return ba(m.status,f)}}return r.stream&&m.body?RXr({ctx:t,body:r,bodyStr:c,response:m,tracer:o,requestStartTime:s,toolCount:l,upstreamSpan:d,upstreamResponseHeaders:h,logProxyBody:i,logFinalRequest:a}):MXr({ctx:t,body:r,bodyStr:c,response:m,tracer:o,requestStartTime:s,toolCount:l,upstreamSpan:d,upstreamResponseHeaders:h,logProxyBody:i,logFinalRequest:a})}function IXr(e){const t=e.getReader(),r=HXt();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 RXr(e){const{ctx:t,bodyStr:r,response:n,tracer:o,requestStartTime:s,upstreamSpan:i,upstreamResponseHeaders:a,logProxyBody:c,logFinalRequest:l}=e,u={...a},{stream:d,capture:m}=EXt(),h=n.body;if(!h)throw ur("passthrough","passthrough",502),new Error("Expected passthrough stream response body");const f=IXr(h);let g=f.stream,y=!1,w;const E=(C,x,b,I)=>y?!1:(y=!0,x==="stream_error"&&ur("passthrough","passthrough",C),l(C,"passthrough","passthrough",x,b,I),!0);if(o)try{const{stream:C,telemetry:x}=qL({captureRawText:!0});g=g.pipeThrough(C);const b=o,I=i,R=n,A=r.length;w=Promise.all([x,m,f.outcome]).then(([P,L,B])=>{const M=QL(B,P.streamErrorMessage,P.messageStopReceived);t.metadata.firstUsefulOutputAt=P.firstUsefulOutputAt;const D=bp(M);b.setUsage({inputTokens:P.usage.inputTokens,outputTokens:P.usage.outputTokens,cacheCreationTokens:P.usage.cacheCreationInputTokens,cacheReadTokens:P.usage.cacheReadInputTokens}),b.logStreamEvents(P.events),b.setResponseInfo(_Qt(P));const $=parseFloat(R.headers.get("anthropic-ratelimit-unified-5h-utilization")??""),F=parseFloat(R.headers.get("anthropic-ratelimit-unified-7d-utilization")??""),G={inputTokens:P.usage.inputTokens,outputTokens:P.usage.outputTokens,cacheCreationTokens:P.usage.cacheCreationInputTokens,cacheReadTokens:P.usage.cacheReadInputTokens};isNaN($)||(G.rateLimitAfter5h=$),isNaN(F)||(G.rateLimitAfter7d=F),(!isNaN($)||!isNaN(F))&&b.setUsage(G),b.logUpstreamResponseBody(P.rawText??""),b.recordMetrics(),b.recordBodySizes(A,P.totalBytesReceived),I?.end(),D&&b.setError(D.errorType,D.message),b.end(D?.status??n.status,Date.now()-s),E(D?.status??n.status,D?.errorType,D?.message,{inputTokens:P.usage.inputTokens,outputTokens:P.usage.outputTokens,cacheCreationTokens:P.usage.cacheCreationInputTokens,cacheReadTokens:P.usage.cacheReadInputTokens}),c({phase:"upstream_response",headers:u,body:P.rawText??"",bodySize:P.totalBytesReceived,contentType:u["content-type"]??"text/event-stream",account:"passthrough",accountType:"passthrough",attempt:1,responseStatus:200,durationMs:Date.now()-s}),c({phase:"client_response",headers:u,body:L.text,bodySize:L.totalBytes,contentType:u["content-type"]??"text/event-stream",account:"passthrough",accountType:"passthrough",attempt:1,responseStatus:200,durationMs:Date.now()-s})}).catch(P=>{if(y)return;const L=P instanceof Error?P.message:String(P);b.setError("stream_telemetry_error",L),I?.end(),b.end(500,Date.now()-s),E(500,"stream_telemetry_error",L)})}catch{w=f.outcome.then(C=>{const x=bp(C);i?.end(),x&&o.setError(x.errorType,x.message),o.end(x?.status??n.status,Date.now()-s),E(x?.status??n.status,x?.errorType,x?.message)})}else try{const{stream:C,telemetry:x}=qL({captureRawText:!0});g=g.pipeThrough(C),w=Promise.all([x,m,f.outcome]).then(([b,I,R])=>{const A=QL(R,b.streamErrorMessage,b.messageStopReceived);t.metadata.firstUsefulOutputAt=b.firstUsefulOutputAt;const P=bp(A);E(P?.status??n.status,P?.errorType,P?.message,{inputTokens:b.usage.inputTokens,outputTokens:b.usage.outputTokens,cacheCreationTokens:b.usage.cacheCreationInputTokens,cacheReadTokens:b.usage.cacheReadInputTokens}),c({phase:"upstream_response",headers:u,body:b.rawText??"",bodySize:b.totalBytesReceived,contentType:u["content-type"]??"text/event-stream",account:"passthrough",accountType:"passthrough",attempt:1,responseStatus:n.status,durationMs:Date.now()-s}),c({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(b=>{y||E(500,"stream_telemetry_error",b instanceof Error?b.message:String(b))})}catch{w=f.outcome.then(C=>{const x=bp(C);E(x?.status??n.status,x?.errorType,x?.message)})}const _=g.pipeThrough(d);return Bk(t.metadata,{onTerminal:()=>w}),new Response(_,{status:n.status,headers:{...u,...t.responseHeaders??{}}})}async function MXr(e){const{bodyStr:t,response:r,tracer:n,requestStartTime:o,upstreamSpan:s,upstreamResponseHeaders:i,logProxyBody:a,logFinalRequest:c}=e,l=await r.text();n?.logUpstreamResponseBody(l),a({phase:"upstream_response",headers:i,body:l,bodySize:Buffer.byteLength(l,"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:l,bodySize:Buffer.byteLength(l,"utf8"),contentType:i["content-type"]??"application/json",account:"passthrough",accountType:"passthrough",attempt:1,responseStatus:r.status,durationMs:Date.now()-o});const u=JSON.parse(l);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")??""),f=parseFloat(r.headers.get("anthropic-ratelimit-unified-7d-utilization")??"");if(!isNaN(h)||!isNaN(f)){const g={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)||(g.rateLimitAfter5h=h),isNaN(f)||(g.rateLimitAfter7d=f),n.setUsage(g)}}n.setResponseInfo(dse(u)),n.recordMetrics();const m=JSON.stringify(u);n.recordBodySizes(t.length,m.length),s?.end(),n.end(r.status,Date.now()-o),c(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),c(r.status,"passthrough","passthrough");return u}async function PXr(e){const t=Mw();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=Ca(d.key).quota,h=As(m?.sessionResetAt,r)??null,f=As(m?.weeklyResetAt,r)??null,g=await Lre(t.grantId,d.key,h,f);return{accountKey:d.key,sessionUsed:m?.sessionUsed??null,weeklyUsed:m?.weeklyUsed??null,sessionResetAt:h,weeklyResetAt:f,borrowedSessionFraction:g.sessionFraction,borrowedWeeklyFraction:g.weeklyFraction}})),o=await Rre(t.grantId);if(!o)return{accounts:e.accounts};const s=await Fre(t.grantId,Foe(o.gates,n).inScope),i=$oe(o,n,r,s),a=new Set(i.allowed),c=e.accounts.filter(d=>a.has(d.key));if(c.length>0)return{accounts:c};const l=Uoe(i.excluded),u=Fw(l,{status:$Yr(l),grant:o,retryAfterSeconds:kQt(n,r)});return p.always(`[proxy] share ${t.peerLabel} withheld: ${l} (${i.excluded.length} accounts)`),{accounts:[],refusal:{status:u.status,message:u.body.error.message,errorType:u.body.error.type,responseHeaders:u.headers}}}async function DXr(e){const t=[],r=[];for(const n of e){const o=await AYr(n.key);if(!o){t.push(n);continue}if(!gYr(o)){t.push(n);continue}p.always(`[proxy] withholding leased account=${n.label}: ${o.reason}`),r.push({label:n.label,reason:o.reason})}return{accounts:t,withheld:r}}async function OXr(e,t){const r=[],n=[],o=Date.now();for(const s of e){const i=await Loe(s.key);if(!i){r.push(s);continue}const a=i.lease.gates;if(!BYr(a.models,t)){p.always(`[proxy] leased account=${s.label} does not cover model ${Xr(t??"unknown")}`),n.push({label:s.label,reason:"model_not_allowed"});continue}if(a.schedule&&!UYr(a.schedule,o)){p.always(`[proxy] leased account=${s.label} is outside its allowed hours`),n.push({label:s.label,reason:"out_of_window"});continue}const c=Ca(s.key).quota,l=As(c?.sessionResetAt,o)??null,u=As(c?.weeklyResetAt,o)??null,d=await Lre(i.grantId,s.key,l,u),m={accountKey:s.key,sessionUsed:c?.sessionUsed??null,weeklyUsed:c?.weeklyUsed??null,sessionResetAt:l,weeklyResetAt:u,borrowedSessionFraction:d.sessionFraction,borrowedWeeklyFraction:d.weeklyFraction},h=await Fre(i.grantId,[m]),{accounts:f,...g}=a,y=$oe(NXr(i,g),[m],o,h);if(y.allowed.length===0){const w=Uoe(y.excluded);p.always(`[proxy] withholding leased account=${s.label}: ${w}`),n.push({label:s.label,reason:w});continue}r.push(s)}return{accounts:r,withheld:n}}function NXr(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 LXr(e,t,r){const n=Date.now(),o=i=>{Wjr({grantId:i,accountKey:e,sessionBefore:t?.sessionUsed??null,sessionAfter:r.sessionUsed,sessionResetAt:As(r.sessionResetAt,n)??null,weeklyBefore:t?.weeklyUsed??null,weeklyAfter:r.weeklyUsed,weeklyResetAt:As(r.weeklyResetAt,n)??null})},s=Mw();if(s){o(s.grantId);return}Loe(e).then(i=>{i&&o(i.grantId)}).catch(()=>{})}function mse(e,t,r){const n=Nre({inputTokens:r.inputTokens??0,outputTokens:r.outputTokens??0,...r.cacheCreationTokens!==void 0?{cacheCreationTokens:r.cacheCreationTokens}:{},...r.cacheReadTokens!==void 0?{cacheReadTokens:r.cacheReadTokens}:{}},t);xYr(e,n).catch(()=>{})}function CQt(e,t){if(!t||typeof t!="object")return;const r=t.usage;if(!r)return;const n=qXr(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};pse(e.key,n,o),mse(e.label,n,o)}function pse(e,t,r){const n=Mw();n&&Kjr({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 hse(e){if(!Mw())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 FXr(e,t){const r=e.provisionedAccount;if(!r)return{paused:!1,detail:"no provisioned account recorded"};const n=rc.get(`anthropic:${r}`),o=i9t(r,"oauth"),{verdict:s,shouldPause:i}=await sZr({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 Pjr(e.id,"paused"),{paused:!0,detail:s.drifted?s.detail:"repeated unexplained usage"}):{paused:!1,detail:s.drifted?s.detail:"consistent"}}async function $Xr(e,t){await v9t(e.id,t)}function UXr(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 BXr=1,zXr=["live","complete","handshake","limits"];async function GXr(e,t){const r=Date.now(),n=await CZt(t),o=await Promise.all(n.map(async l=>{const u=Ca(l.key).quota,d=As(u?.sessionResetAt,r)??null,m=As(u?.weeklyResetAt,r)??null,h=await Lre(e.id,l.key,d,m);return{accountKey:l.key,sessionUsed:u?.sessionUsed??null,weeklyUsed:u?.weeklyUsed??null,sessionResetAt:d,weeklyResetAt:m,borrowedSessionFraction:h.sessionFraction,borrowedWeeklyFraction:h.weeklyFraction}})),s=Foe(e.gates,o).inScope,i=await Fre(e.id,s),a=$oe(e,o,r,i),c=(l,u)=>l===void 0?null:Math.max(0,l-u*100);return{grantState:e.state,level:e.level,ledger:e.entitlement.ledger,...e.entitlement.ledger==="coins"?{remainingCoins:Math.max(0,Math.floor(jjr(e)))}:{},servable:a.allowed.length>0,...a.allowed.length===0&&a.excluded.length>0?{withheldReason:Uoe(a.excluded)}:{},sliceLeftPct:{session:c(e.gates.maxSlice?.session5hPct,i.sessionFraction),weekly:c(e.gates.maxSlice?.weekly7dPct,i.weeklyFraction)},...a.allowed.length===0?(()=>{const l=kQt(o,r);return l===void 0?{}:{retryAfterSeconds:l}})():{}}}function Eg(e){return!e.ok}async function Sg(e){const t=VYr(e);if(!t)return{ok:!1,body:Fw("missing_token",{status:401}).body};const r=await Ojr(t);return r?{ok:!0,grant:r}:{ok:!1,body:Fw("unknown_token",{status:401}).body}}function qXr(e){if(!e||typeof e!="object")return;const t=e.model;return typeof t=="string"?t:void 0}function kQt(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 jXr(e){const{ctx:t,body:r,accountStrategy:n,primaryAccountKey:o,accountAllowlist:s,quotaRoutingEnabled:i=ise(),sessionSoftLimit:a=ase(),sessionResetToleranceMs:c=sA(),setRoutingDecision:l}=e,u=await Promise.resolve().then(()=>(kn(),ql)),d=await Promise.resolve().then(()=>(_i(),tH)),m=[],h=`${d.homedir()}/.neurolink/anthropic-credentials.json`,{tokenStore:f}=await Promise.resolve().then(()=>(ag(),vre)),g=await Ok();dQt||(ese??=f.pruneExpired().then(()=>{dQt=!0}).finally(()=>{ese=void 0}),await ese);const y=await f.getProviderSnapshot(),w=Object.keys(y).filter(W=>W.startsWith("anthropic:")),E=[];let _=0,C=0;for(const W of w){if(!gre(W,s)){p.debug(`[proxy] skipping account=${W} (not in account allowlist)`);continue}if(y[W].disabled){const De=Ca(W),We=y[W].disabledReason;if(We==="refresh_failed")await f.markEnabled(W),p.always(`[proxy] account=${W.split(":")[1]??W} re-enabled for legacy refresh failure recheck`),De.permanentlyDisabled=!1,De.consecutiveRefreshFailures=0;else{p.debug(`[proxy] skipping disabled account=${W.split(":")[1]??W}`),De.permanentlyDisabled=!0,We==="entitlement_blocked"&&E.push(W.split(":")[1]??W),_+=1;continue}}const se=y[W].tokens;if(!se){C+=1;continue}let he=se.accessToken,de=se.refreshToken,J=se.expiresAt;const ge=W.split(":")[1]??W,ye=se.tokenType==="Bearer"?"oauth":"api_key",_e=Ca(W),Re=g[W];Re?.coolingUntil>Date.now()&&(!_e.coolingUntil||Re.coolingUntil>_e.coolingUntil)&&(_e.coolingUntil=Re.coolingUntil,_e.coolingReason=Re.reason);const ve=()=>{m.push({key:W,label:ge,token:he,refreshToken:de,expiresAt:J,type:ye,persistTarget:{providerKey:W}})};if(J?J<Date.now():!1){if(_e.permanentlyDisabled)continue;if(_e.coolingReason==="auth"&&_e.coolingUntil&&_e.coolingUntil>Date.now()){ve();continue}if(!de){p.always(`[proxy] skipping account=${ge} (expired, no refresh token)`),await Wd({key:W,label:ge,token:he,type:"oauth"},_e,"missing_refresh_token");continue}const De={token:he,refreshToken:de,expiresAt:J,label:ge},We=await $L(De,{providerKey:W});if(!We.success){const Ze={key:W,label:ge,token:he,type:"oauth"};if(yg(We))p.always(`[proxy] skipping account=${ge} (refresh token rejected: ${We.error?.slice(0,200)??"unknown"})`),await Wd(Ze,_e,"refresh_invalid");else{const Pt=await h2(Ze,_e);p.always(`[proxy] account=${ge} refresh temporarily unavailable (${We.status??"network"}); cooling until ${new Date(Pt).toISOString()} and rotating`),ve()}continue}he=De.token,de=De.refreshToken,J=De.expiresAt,await f.saveTokens(W,{accessToken:he,refreshToken:de,expiresAt:J??Date.now()+36e5,tokenType:"Bearer"}),p.always(`[proxy] refreshed expired account=${W.split(":")[1]??W} at startup`),await f2({key:W},_e)}ve()}if(m.length===0&&J7t(w.length,ak,s))try{const W=JSON.parse(u.readFileSync(h,"utf8")),se=await kXr(W,h);se&&m.push(se)}catch{}if(process.env.ANTHROPIC_API_KEY&&m.length===0&&J7t(w.length,yre,s)&&m.push({key:yre,label:"env",token:process.env.ANTHROPIC_API_KEY,type:"api_key"}),m.length===0)return E.length>0&&E.length===_&&C===0?{failure:{status:403,message:MQt({status:403,accounts:E,message:"OAuth authentication is not allowed for this organization.",errorCode:"oauth_not_allowed_for_organization"}),errorType:"permission_error"}}:{failure:{status:401,message:s?"No allowed Anthropic credentials are currently available":w.length>0?"Configured Anthropic accounts are disabled or unavailable":"No Anthropic credentials found",errorType:"authentication_error"}};for(const W of m)hQr(W);await tXr(m);const x=m.filter(W=>!Ca(W.key).permanentlyDisabled),b=await DXr(x),I=await OXr(b.accounts,typeof r.model=="string"?r.model:void 0),R={accounts:I.accounts,withheld:[...b.withheld,...I.withheld]},A=R.accounts;if(A.length===0&&R.withheld.length>0){const W=R.withheld.map(de=>`${de.label} (${de.reason})`).join(", ");return{failure:{status:403,message:R.withheld.every(de=>de.reason==="model_not_allowed")?`Borrowed account(s) do not cover the requested model: ${W}. Ask the lender to widen the share, or use a model it allows.`:`Borrowed account(s) are no longer covered by a lease: ${W}. Run 'neurolink proxy peer sync' to check in with the lender, or ask them to resume the share.`,errorType:"permission_error"}}}const P=await PXr({accounts:A});if(P.refusal)return{failure:P.refusal};const L=P.accounts;if(L.length===0)return{failure:{status:401,message:g2(m.map(se=>se.label)),errorType:"authentication_error"}};const{orderedAccounts:B,metricsByKey:M}=fXr({enabledAccounts:L,accountStrategy:n,primaryAccountKey:o,quotaRoutingEnabled:i,sessionSoftLimit:a,sessionResetToleranceMs:c,requestedModel:typeof r.model=="string"?r.model:void 0,setRoutingDecision:l});n==="fill-first"&&i&&L.length>1&&mXr(L,B,a,M);const D=TQr(r),$=JSON.stringify(D),F=Date.now(),G=Array.isArray(r.tools)?r.tools.length:0,j="https://api.anthropic.com/v1/messages?beta=true",q=t.headers??{},H=EQt(r);return{accounts:m,enabledAccounts:L,orderedAccounts:B,bodyStr:$,requestStart:F,toolCount:G,url:j,clientHeaders:q,isClaudeClientRequest:SQt(q,H)}}async function HXr(e){const{ctx:t,body:r,tracer:n,requestStartTime:o,logProxyBody:s,logFinalRequest:i,options:a,providerLabel:c,idleTimeoutMs:l=FZr}=e,u=new AbortController;let d;try{d=await xt(t.neurolink.stream({...a,abortSignal:u.signal}),l,`Fallback ${c} initialization timed out after ${l}ms`)}catch(w){throw u.abort(w),w}const m=async w=>{const E=d.stream[Symbol.asyncIterator]();let _="";try{for(;;){const{value:C,done:x}=await xt(E.next(),l,`Fallback ${c} stream timed out after ${l}ms of inactivity`);if(x)return _;const b=Eoe(C);b&&(_+=b,w?.(b))}}catch(C){throw u.abort(C),E.return?.().catch(()=>{}),C}};if(r.stream){const w=new Fk(r.model,0),E=[];for(const A of w.start())E.push(A);const _=await m(A=>{for(const P of w.pushDelta(A))E.push(P)}),C=d.toolCalls??[];if(!YL(_,C))throw new Error(`Translated provider ${c} returned no content or tool calls`);if(C.length)for(const A of C){const P=A.toolName??A.name??"unknown";for(const L of w.pushToolUse(BL(),P,yXt(A)))E.push(L)}const x=d.finishReason??"end_turn",b=Nw(d.usage);for(const A of w.finish(b.output,x))E.push(A);n?.end(200,Date.now()-o),i(200,"",c,void 0,void 0,{inputTokens:b.input,outputTokens:b.output});const I=E.join("");s({phase:"client_response",headers:{"content-type":"text/event-stream"},body:I,bodySize:Buffer.byteLength(I,"utf8"),contentType:"text/event-stream",responseStatus:200,durationMs:Date.now()-o});async function*R(){for(const A of E)yield A}return R()}const h=await m();if(!YL(h,d.toolCalls))throw new Error(`Translated provider ${c} returned no content or tool calls`);const f={content:h,model:d.model,finishReason:d.finishReason??"end_turn",reasoning:void 0,usage:d.usage?Nw(d.usage):void 0,toolCalls:d.toolCalls};n?.end(200,Date.now()-o);const g=ooe(f,r.model);i(200,"",c,void 0,void 0,{inputTokens:f.usage?.input,outputTokens:f.usage?.output});const y=JSON.stringify(g);return s({phase:"client_response",headers:{"content-type":"application/json"},body:y,bodySize:Buffer.byteLength(y,"utf8"),contentType:"application/json",responseStatus:200,durationMs:Date.now()-o}),g}async function AQt(e){let t;for(let r=0;r<=Koe;r+=1)try{return await HXr(e)}catch(n){if(t=n,!wse(n)||r===Koe)throw n;const o=Woe[r]??250;p.always(`[proxy] retrying fallback=${e.providerLabel} after transient network error (${r+1}/${Koe}) in ${o}ms: ${Vw(Ml(n))}`),await ku(o)}throw t}async function VXr(e){const{ctx:t,body:r,model:n,reasoningEffort:o,tracer:s,requestStartTime:i,logProxyBody:a,logFinalRequest:c}=e,l={...t,requestId:`${t.requestId}:codex-fallback`,method:"POST",path:"/backend-api/codex/responses",headers:{"content-type":"application/json",accept:"text/event-stream"},query:{},params:{},body:WKr(r,n,o),metadata:{...t.metadata,"neurolink.codexFallback":!0},responseHeaders:{}},u=await ZXt(l),d=rJr(l.metadata);let m=()=>{};const h=new Promise(b=>{m=b}),f=oJr(u,m,{onTerminal:b=>Promise.allSettled(d.map(async I=>I.onTerminal?.(b)))});Bk(t.metadata,{onTerminal:()=>h});const g={...l.responseHeaders??{}};if(r.stream){const b=await XKr(f,r.model);t.responseHeaders??={},Object.assign(t.responseHeaders,hse(g));const I=g["x-neurolink-account"]??"",R=g["x-neurolink-account-type"]??"codex-oauth";let A=!1,P="",L=0;const B=(F,G,j,q)=>{A||(A=!0,t.abortSignal?.removeEventListener("abort",M),F>=400&&(t.metadata.terminalErrorType=j),s?.end(F,Date.now()-i),c(F,I,R,j,q,{inputTokens:G?.usage?.input,outputTokens:G?.usage?.output,cacheCreationTokens:G?.usage?.cacheCreationTokens,cacheReadTokens:G?.usage?.cacheReadTokens}),Lw({provider:"codex",model:n,status:F<400?"success":"failure",durationMs:Date.now()-i,...q?{errorMessage:q}:{}}),a({phase:"client_response",contentType:"text/event-stream",body:P,bodySize:L,responseStatus:F,durationMs:Date.now()-i}))},M=()=>{B(499,void 0,"client_cancelled","Client cancelled Codex fallback stream"),b.cancel()};t.abortSignal?.addEventListener("abort",M,{once:!0}),Bk(t.metadata,{onTerminal:({outcome:F})=>{F==="client_cancelled"?M():F==="stream_error"&&(B(502,void 0,"stream_error","Codex fallback stream failed"),b.cancel())}});const D=F=>(L+=Buffer.byteLength(F),P.length<1024*1024&&(P+=F.slice(0,1024*1024-P.length)),F);async function*$(){try{if(t.abortSignal?.aborted){M();return}let F=b.frames.next();for(;!A;){let G;const j=new Promise(W=>{G=setTimeout(()=>W(null),15e3),G.unref()});let q;try{q=await Promise.race([F,j])}finally{clearTimeout(G)}if(A)return;if(q===null){yield D(Fk.pingEvent());continue}if(q.done===!0){B(200,q.value);return}const H=D(q.value);if(H.startsWith(`event: content_block_delta
@@ -11,13 +11,14 @@
11
11
  */
12
12
  import { spawn } from "node:child_process";
13
13
  import { homedir } from "node:os";
14
- import { dirname, join, resolve } from "node:path";
14
+ import { dirname, join } from "node:path";
15
15
  import { stripVTControlCharacters } from "node:util";
16
16
  import chalk from "chalk";
17
17
  import ora from "ora";
18
18
  import { buildProxyHealthResponse, createProxyReadinessState, markProxyDrainingForUpdate, markProxyReady, resumeProxyConnections, waitForProxyReadiness, } from "../../proxy/proxyHealth.js";
19
19
  import { logger } from "../../utils/logger.js";
20
20
  import { applyAllClients, restoreAllClients, } from "../proxy-clients/registry.js";
21
+ import { resolveProxyConfigPath } from "../../proxy/proxyConfig.js";
21
22
  import { redactUrlsInText, sanitizeForLog, } from "../../utils/logSanitize.js";
22
23
  import { withTimeout } from "../../utils/async/withTimeout.js";
23
24
  import { formatUptime, isProcessRunning, StateFileManager, } from "../utils/serverUtils.js";
@@ -2696,7 +2697,9 @@ async function startProxyRuntime(params) {
2696
2697
  logger.always(` ${chalk.bold("Env File:")} ${chalk.cyan(params.loadedEnvFile)}`);
2697
2698
  }
2698
2699
  if (!isDev) {
2699
- for (const result of await applyAllClients(url)) {
2700
+ for (const result of await applyAllClients(url, {
2701
+ configPath: params.configPath,
2702
+ })) {
2700
2703
  if (result.error) {
2701
2704
  // Visible, not debug-level. A client whose config could not be written
2702
2705
  // will keep talking to its own upstream, which looks like the proxy
@@ -2953,9 +2956,7 @@ async function startProxyCommandHandler(argv) {
2953
2956
  // content-filters. Runs once, after env load so it can be tuned via env.
2954
2957
  configureProxyKeepAliveDispatcher();
2955
2958
  const { neurolink, logsDir } = await createProxyNeurolinkRuntime(devPaths?.logsDir);
2956
- const configPath = argv.config
2957
- ? resolve(argv.config)
2958
- : join(homedir(), ".neurolink", "proxy-config.yaml");
2959
+ const configPath = resolveProxyConfigPath(argv.config);
2959
2960
  const runtimeConfigStore = await ProxyRuntimeConfigStore.create({
2960
2961
  configPath,
2961
2962
  configRequired: Boolean(argv.config),
@@ -3012,6 +3013,7 @@ async function startProxyCommandHandler(argv) {
3012
3013
  passthrough,
3013
3014
  logsDir,
3014
3015
  runtimeConfigStore,
3016
+ configPath,
3015
3017
  });
3016
3018
  }
3017
3019
  catch (error) {
@@ -4174,7 +4176,9 @@ export const proxySetupCommand = {
4174
4176
  const nextStep = stepNum + 1;
4175
4177
  console.info(chalk.blue(`\nStep ${nextStep}:`) + " Configuring Claude Code...");
4176
4178
  const url = `http://127.0.0.1:${port}`;
4177
- for (const result of await applyAllClients(url)) {
4179
+ for (const result of await applyAllClients(url, {
4180
+ configPath: resolveProxyConfigPath(argv.config),
4181
+ })) {
4178
4182
  if (result.error) {
4179
4183
  console.info(chalk.yellow(` ⚠ Could not auto-configure ${result.displayName}: ${result.error.message}`));
4180
4184
  // Claude Code is the one client whose manual fallback is a single
@@ -4364,9 +4368,7 @@ export const proxyInstallCommand = {
4364
4368
  });
4365
4369
  const envFile = envResolution.path;
4366
4370
  const explicitConfig = argv.config;
4367
- const configPath = explicitConfig
4368
- ? resolve(explicitConfig)
4369
- : join(homedir(), ".neurolink", "proxy-config.yaml");
4371
+ const configPath = resolveProxyConfigPath(explicitConfig);
4370
4372
  if (explicitConfig && !existsSync(configPath)) {
4371
4373
  console.info(chalk.red(`Proxy config file not found: ${configPath}`));
4372
4374
  process.exit(1);
@@ -0,0 +1,45 @@
1
+ /**
2
+ * Grok Build client configurator.
3
+ *
4
+ * Grok Build (`grok`, xAI's terminal agent) is a Codex-shaped TOML client
5
+ * that speaks three wire formats. Built-in `grok-4.6` / `grok-4.5` stay on
6
+ * xAI (`cli-chat-proxy.grok.com`, Responses API, 500k window). This writer
7
+ * does not remap those. It adds the proxy's advertised catalog as extra
8
+ * picker entries so Grok can send Claude traffic through `/v1/messages`
9
+ * (passthrough) and Gemini/OpenAI traffic through `/v1/chat/completions`
10
+ * (translation), each with a `context_window` that Grok's own compaction
11
+ * will honour — the proxy does not truncate.
12
+ *
13
+ * Snapshot lives in `~/.neurolink/`, following Codex, never inside
14
+ * `config.toml`. Grok's TOML parser is not a closed schema, but putting
15
+ * bookkeeping keys in the user's file is how OpenCode was bricked, and new
16
+ * writers do not rely on tolerance.
17
+ *
18
+ * Adaptive thinking: Grok's global `default_reasoning_effort = "xhigh"`
19
+ * becomes Anthropic `thinking.type = "adaptive"`. Haiku 4.5 rejects that
20
+ * with 400. Only Claude Opus/Sonnet 4.6 and 5.x keep reasoning enabled.
21
+ */
22
+ import type { CliGrokProxyModelSpec, CliProxyClientApplyOptions, CliProxyClientConfigurator, ModelMapping } from "../../types/index.js";
23
+ declare function getGrokConfigDir(): string;
24
+ declare function getGrokConfigPath(): string;
25
+ declare function getGrokSnapshotPath(): string;
26
+ declare function classifyGrokProxyModel(id: string, mapping?: ModelMapping): CliGrokProxyModelSpec;
27
+ declare function loadRoutedModelIds(configPath?: string): Promise<string[]>;
28
+ declare function catalogModelIds(configPath?: string): Promise<string[]>;
29
+ declare function buildGrokManagedBlock(baseUrl: string, configPath?: string): Promise<string>;
30
+ export declare function setGrokProxySettings(baseUrl: string, options?: CliProxyClientApplyOptions): Promise<boolean>;
31
+ export declare function clearGrokProxySettings(expectedBaseUrl?: string): Promise<boolean>;
32
+ export declare const grokConfigurator: CliProxyClientConfigurator;
33
+ /** Test-only export (CLAUDE.md rule 15 determinism exception). See openCode.ts. */
34
+ export declare const __grokTestHooks: {
35
+ getGrokConfigDir: typeof getGrokConfigDir;
36
+ getGrokConfigPath: typeof getGrokConfigPath;
37
+ getGrokSnapshotPath: typeof getGrokSnapshotPath;
38
+ setGrokProxySettings: typeof setGrokProxySettings;
39
+ clearGrokProxySettings: typeof clearGrokProxySettings;
40
+ classifyGrokProxyModel: typeof classifyGrokProxyModel;
41
+ loadRoutedModelIds: typeof loadRoutedModelIds;
42
+ catalogModelIds: typeof catalogModelIds;
43
+ buildGrokManagedBlock: typeof buildGrokManagedBlock;
44
+ };
45
+ export {};
@@ -0,0 +1,342 @@
1
+ /**
2
+ * Grok Build client configurator.
3
+ *
4
+ * Grok Build (`grok`, xAI's terminal agent) is a Codex-shaped TOML client
5
+ * that speaks three wire formats. Built-in `grok-4.6` / `grok-4.5` stay on
6
+ * xAI (`cli-chat-proxy.grok.com`, Responses API, 500k window). This writer
7
+ * does not remap those. It adds the proxy's advertised catalog as extra
8
+ * picker entries so Grok can send Claude traffic through `/v1/messages`
9
+ * (passthrough) and Gemini/OpenAI traffic through `/v1/chat/completions`
10
+ * (translation), each with a `context_window` that Grok's own compaction
11
+ * will honour — the proxy does not truncate.
12
+ *
13
+ * Snapshot lives in `~/.neurolink/`, following Codex, never inside
14
+ * `config.toml`. Grok's TOML parser is not a closed schema, but putting
15
+ * bookkeeping keys in the user's file is how OpenCode was bricked, and new
16
+ * writers do not rely on tolerance.
17
+ *
18
+ * Adaptive thinking: Grok's global `default_reasoning_effort = "xhigh"`
19
+ * becomes Anthropic `thinking.type = "adaptive"`. Haiku 4.5 rejects that
20
+ * with 400. Only Claude Opus/Sonnet 4.6 and 5.x keep reasoning enabled.
21
+ */
22
+ import { readFileSync } from "fs";
23
+ import { homedir } from "os";
24
+ import { join } from "path";
25
+ import { logger } from "../../utils/logger.js";
26
+ import { getContextWindowSize } from "../../constants/contextWindows.js";
27
+ import { DEFAULT_PROXY_MODEL_IDS } from "../../constants/proxyModels.js";
28
+ import { defaultProxyConfigPath, parseProxyConfigString, } from "../../proxy/proxyConfig.js";
29
+ import { isUsableSnapshot, shouldCaptureSnapshot, writeFileAtomic, } from "./snapshot.js";
30
+ const GROK_BLOCK_BEGIN = "# >>> neurolink-proxy (managed) >>>";
31
+ const GROK_BLOCK_END = "# <<< neurolink-proxy (managed) <<<";
32
+ const PLACEHOLDER_KEY = "neurolink-proxy";
33
+ const ANTHROPIC_VERSION = "2023-06-01";
34
+ function getGrokConfigDir() {
35
+ const env = process.env.GROK_HOME;
36
+ return env !== undefined && env.trim().length > 0
37
+ ? env.trim()
38
+ : join(homedir(), ".grok");
39
+ }
40
+ function getGrokConfigPath() {
41
+ return join(getGrokConfigDir(), "config.toml");
42
+ }
43
+ function getGrokSnapshotPath() {
44
+ return join(homedir(), ".neurolink", "grok-proxy-snapshot.json");
45
+ }
46
+ function escapeRegExp(value) {
47
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
48
+ }
49
+ function tomlKey(id) {
50
+ return /^[A-Za-z0-9_-]+$/.test(id) ? id : JSON.stringify(id);
51
+ }
52
+ function displayNameFor(id) {
53
+ const base = id.replace(/-\d{8}$/, "");
54
+ const pretty = base
55
+ .split("-")
56
+ .map((part) => /^\d/.test(part) ? part : part.charAt(0).toUpperCase() + part.slice(1))
57
+ .join(" ")
58
+ .replace(/(\d) (\d)/g, "$1.$2");
59
+ return `${pretty} (NeuroLink)`;
60
+ }
61
+ function providerForModelId(id) {
62
+ if (id.startsWith("claude-")) {
63
+ return "anthropic";
64
+ }
65
+ if (id.startsWith("gemini-")) {
66
+ return "vertex";
67
+ }
68
+ return "openai";
69
+ }
70
+ function providerFromMapping(provider, fallbackId) {
71
+ const normalized = provider.trim().toLowerCase();
72
+ if (normalized === "anthropic" || normalized === "claude") {
73
+ return "anthropic";
74
+ }
75
+ if (normalized === "openai") {
76
+ return "openai";
77
+ }
78
+ if (normalized === "vertex" ||
79
+ normalized === "google" ||
80
+ normalized === "google-ai" ||
81
+ normalized === "gemini") {
82
+ return "vertex";
83
+ }
84
+ return providerForModelId(fallbackId);
85
+ }
86
+ function isMissingFileError(error) {
87
+ if (!error || typeof error !== "object" || !("code" in error)) {
88
+ return false;
89
+ }
90
+ return error.code === "ENOENT";
91
+ }
92
+ /**
93
+ * Anthropic `thinking.type = "adaptive"` is what Grok emits for `xhigh`.
94
+ * Measured: Haiku 4.5 returns 400 "adaptive thinking is not supported".
95
+ * Opus/Sonnet 4.6 and the 5-series accept it.
96
+ */
97
+ function supportsAdaptiveThinking(id) {
98
+ return (/^claude-(opus|sonnet)-4-6$/.test(id) || /^claude-(opus|sonnet)-5/.test(id));
99
+ }
100
+ function classifyGrokProxyModel(id, mapping) {
101
+ const classifyId = mapping && mapping.to.trim().length > 0 ? mapping.to.trim() : id;
102
+ const provider = mapping
103
+ ? providerFromMapping(mapping.provider, classifyId)
104
+ : providerForModelId(id);
105
+ const windowProvider = mapping && mapping.provider.trim().length > 0
106
+ ? mapping.provider.trim()
107
+ : provider;
108
+ const apiBackend = provider === "anthropic" ? "messages" : "chat_completions";
109
+ const contextWindow = getContextWindowSize(windowProvider, classifyId);
110
+ return {
111
+ id,
112
+ name: displayNameFor(id),
113
+ apiBackend,
114
+ contextWindow,
115
+ maxCompletionTokens: contextWindow >= 1_000_000 ? 16_384 : 8_192,
116
+ supportsReasoningEffort: supportsAdaptiveThinking(classifyId),
117
+ };
118
+ }
119
+ async function loadRoutedMappings(configPath) {
120
+ const resolvedPath = configPath ?? defaultProxyConfigPath();
121
+ try {
122
+ const config = await parseProxyConfigString(readFileSync(resolvedPath, "utf8"));
123
+ return (config.routing?.modelMappings ?? []).filter((mapping) => mapping.from.trim().length > 0);
124
+ }
125
+ catch {
126
+ return [];
127
+ }
128
+ }
129
+ async function loadRoutedModelIds(configPath) {
130
+ return (await loadRoutedMappings(configPath)).map((mapping) => mapping.from.trim());
131
+ }
132
+ async function catalogGrokSpecs(configPath) {
133
+ const seen = new Set();
134
+ const specs = [];
135
+ const routed = await loadRoutedMappings(configPath);
136
+ const routedByFrom = new Map(routed.map((mapping) => [mapping.from.trim(), mapping]));
137
+ for (const id of [
138
+ ...DEFAULT_PROXY_MODEL_IDS,
139
+ ...routed.map((mapping) => mapping.from.trim()),
140
+ ]) {
141
+ if (id.startsWith("grok-") || seen.has(id)) {
142
+ continue;
143
+ }
144
+ seen.add(id);
145
+ specs.push(classifyGrokProxyModel(id, routedByFrom.get(id)));
146
+ }
147
+ return specs;
148
+ }
149
+ async function catalogModelIds(configPath) {
150
+ return (await catalogGrokSpecs(configPath)).map((spec) => spec.id);
151
+ }
152
+ function buildGrokModelBlock(spec, baseUrl) {
153
+ const lines = [
154
+ `[model.${tomlKey(spec.id)}]`,
155
+ `model = ${JSON.stringify(spec.id)}`,
156
+ `name = ${JSON.stringify(spec.name)}`,
157
+ `base_url = ${JSON.stringify(baseUrl)}`,
158
+ `api_backend = ${JSON.stringify(spec.apiBackend)}`,
159
+ `context_window = ${spec.contextWindow}`,
160
+ `auto_compact_threshold_percent = 80`,
161
+ `max_completion_tokens = ${spec.maxCompletionTokens}`,
162
+ `supports_backend_search = false`,
163
+ ];
164
+ if (!spec.supportsReasoningEffort) {
165
+ lines.push("supports_reasoning_effort = false");
166
+ }
167
+ if (spec.apiBackend === "messages") {
168
+ lines.push(`extra_headers = { "x-api-key" = ${JSON.stringify(PLACEHOLDER_KEY)}, "anthropic-version" = ${JSON.stringify(ANTHROPIC_VERSION)} }`);
169
+ }
170
+ else {
171
+ lines.push(`api_key = ${JSON.stringify(PLACEHOLDER_KEY)}`);
172
+ }
173
+ return lines.join("\n");
174
+ }
175
+ async function buildGrokManagedBlock(baseUrl, configPath) {
176
+ const specs = await catalogGrokSpecs(configPath);
177
+ const body = specs
178
+ .map((spec) => buildGrokModelBlock(spec, baseUrl))
179
+ .join("\n\n");
180
+ return [
181
+ GROK_BLOCK_BEGIN,
182
+ "# Proxy catalog. Built-in grok-4.6 / grok-4.5 stay on xAI.",
183
+ "# context_window is Grok's compaction limit and must be <= upstream.",
184
+ "",
185
+ body,
186
+ GROK_BLOCK_END,
187
+ "",
188
+ ].join("\n");
189
+ }
190
+ function stripGrokManagedBlock(text) {
191
+ const blockRe = new RegExp(`\\n?${escapeRegExp(GROK_BLOCK_BEGIN)}[\\s\\S]*?${escapeRegExp(GROK_BLOCK_END)}\\n?`, "g");
192
+ return text.replace(blockRe, "\n");
193
+ }
194
+ function extractManagedBaseUrl(text) {
195
+ const match = text.match(new RegExp(`${escapeRegExp(GROK_BLOCK_BEGIN)}[\\s\\S]*?base_url\\s*=\\s*"([^"]*)"`));
196
+ return match?.[1];
197
+ }
198
+ async function readGrokSnapshot() {
199
+ const fs = await import("fs");
200
+ let parsed;
201
+ try {
202
+ parsed = JSON.parse(fs.readFileSync(getGrokSnapshotPath(), "utf8"));
203
+ }
204
+ catch {
205
+ return null;
206
+ }
207
+ if (!isUsableSnapshot(parsed, "originalExisted")) {
208
+ logger.debug("[proxy] Grok: ignoring a malformed snapshot rather than treating it as empty");
209
+ return null;
210
+ }
211
+ const record = parsed;
212
+ const originalExisted = record.originalExisted;
213
+ const writtenBaseUrl = record.writtenBaseUrl;
214
+ if (typeof originalExisted !== "boolean") {
215
+ return null;
216
+ }
217
+ if (typeof writtenBaseUrl !== "string") {
218
+ return null;
219
+ }
220
+ return { originalExisted, writtenBaseUrl };
221
+ }
222
+ export async function setGrokProxySettings(baseUrl, options) {
223
+ const fs = await import("fs");
224
+ try {
225
+ fs.accessSync(getGrokConfigDir());
226
+ }
227
+ catch {
228
+ return false;
229
+ }
230
+ let original;
231
+ try {
232
+ original = fs.readFileSync(getGrokConfigPath(), "utf8");
233
+ }
234
+ catch (error) {
235
+ if (!isMissingFileError(error)) {
236
+ logger.warn("[proxy] Grok: unable to read config.toml; leaving it untouched");
237
+ return false;
238
+ }
239
+ original = null;
240
+ }
241
+ const existingSnapshot = await readGrokSnapshot();
242
+ if (existingSnapshot === null && fs.existsSync(getGrokSnapshotPath())) {
243
+ logger.warn("[proxy] Grok: snapshot file is unreadable; leaving config.toml untouched rather than overwriting with no way back");
244
+ return false;
245
+ }
246
+ const currentBlock = original
247
+ ? original.includes(GROK_BLOCK_BEGIN)
248
+ ? original.slice(original.indexOf(GROK_BLOCK_BEGIN), original.indexOf(GROK_BLOCK_END) === -1
249
+ ? original.length
250
+ : original.indexOf(GROK_BLOCK_END) + GROK_BLOCK_END.length)
251
+ : undefined
252
+ : undefined;
253
+ if (existingSnapshot === null ||
254
+ shouldCaptureSnapshot({
255
+ hasSnapshot: existingSnapshot !== null,
256
+ written: existingSnapshot?.writtenBaseUrl,
257
+ current: extractManagedBaseUrl(original ?? "") ?? currentBlock,
258
+ })) {
259
+ fs.mkdirSync(join(homedir(), ".neurolink"), { recursive: true });
260
+ await writeFileAtomic(getGrokSnapshotPath(), JSON.stringify({
261
+ originalExisted: existingSnapshot?.originalExisted ?? original !== null,
262
+ writtenBaseUrl: baseUrl,
263
+ }, null, 2), 0o600);
264
+ }
265
+ const withoutBlock = original ? stripGrokManagedBlock(original) : "";
266
+ const trimmed = withoutBlock.replace(/\s*$/, "\n");
267
+ const next = `${trimmed}\n${await buildGrokManagedBlock(baseUrl, options?.configPath)}`;
268
+ await writeFileAtomic(getGrokConfigPath(), next.startsWith("\n") && original === null
269
+ ? next.replace(/^\n+/, "")
270
+ : next, original === null ? 0o600 : undefined);
271
+ return true;
272
+ }
273
+ export async function clearGrokProxySettings(expectedBaseUrl) {
274
+ const fs = await import("fs");
275
+ let current;
276
+ try {
277
+ current = fs.readFileSync(getGrokConfigPath(), "utf8");
278
+ }
279
+ catch {
280
+ return false;
281
+ }
282
+ if (!current.includes(GROK_BLOCK_BEGIN)) {
283
+ return false;
284
+ }
285
+ const configuredUrl = extractManagedBaseUrl(current);
286
+ if (expectedBaseUrl &&
287
+ configuredUrl !== undefined &&
288
+ configuredUrl !== expectedBaseUrl) {
289
+ logger.debug("[proxy] Grok clear: base URL is not the one we wrote, leaving it intact");
290
+ return false;
291
+ }
292
+ const snapshot = await readGrokSnapshot();
293
+ if (snapshot === null) {
294
+ logger.warn("[proxy] Grok clear: no usable snapshot, leaving config.toml untouched rather than stripping a block we cannot prove we own");
295
+ return false;
296
+ }
297
+ const remainder = stripGrokManagedBlock(current).replace(/\s*$/, "\n");
298
+ if (!snapshot.originalExisted && remainder.trim().length === 0) {
299
+ fs.rmSync(getGrokConfigPath(), { force: true });
300
+ }
301
+ else {
302
+ await writeFileAtomic(getGrokConfigPath(), remainder);
303
+ }
304
+ try {
305
+ fs.rmSync(getGrokSnapshotPath(), { force: true });
306
+ }
307
+ catch {
308
+ // next apply overwrites
309
+ }
310
+ return true;
311
+ }
312
+ export const grokConfigurator = {
313
+ id: "grok",
314
+ displayName: "Grok Build",
315
+ detect: async () => {
316
+ const fs = await import("fs");
317
+ try {
318
+ fs.accessSync(getGrokConfigDir());
319
+ return true;
320
+ }
321
+ catch {
322
+ return false;
323
+ }
324
+ },
325
+ // Grok appends `/messages` or `/chat/completions` to `base_url`, so it
326
+ // takes the `/v1` door rather than the proxy root.
327
+ apply: (proxyBaseUrl, options) => setGrokProxySettings(`${proxyBaseUrl}/v1`, options),
328
+ restore: (proxyBaseUrl) => clearGrokProxySettings(`${proxyBaseUrl}/v1`),
329
+ };
330
+ /** Test-only export (CLAUDE.md rule 15 determinism exception). See openCode.ts. */
331
+ export const __grokTestHooks = {
332
+ getGrokConfigDir,
333
+ getGrokConfigPath,
334
+ getGrokSnapshotPath,
335
+ setGrokProxySettings,
336
+ clearGrokProxySettings,
337
+ classifyGrokProxyModel,
338
+ loadRoutedModelIds,
339
+ catalogModelIds,
340
+ buildGrokManagedBlock,
341
+ };
342
+ //# sourceMappingURL=grok.js.map
@@ -1,4 +1,4 @@
1
- import type { CliProxyClientApplyResult, CliProxyClientConfigurator, CliProxyClientRestoreResult } from "../../types/index.js";
1
+ import type { CliProxyClientApplyOptions, CliProxyClientApplyResult, CliProxyClientConfigurator, CliProxyClientRestoreResult } from "../../types/index.js";
2
2
  /**
3
3
  * Every CLI the proxy auto-configures, in apply order.
4
4
  *
@@ -14,6 +14,6 @@ export declare const PROXY_CLIENT_CONFIGURATORS: readonly CliProxyClientConfigur
14
14
  * how loudly to report — the daemon-start path logs failures at debug level
15
15
  * while the setup wizard prints a visible warning.
16
16
  */
17
- export declare function applyAllClients(proxyBaseUrl: string): Promise<CliProxyClientApplyResult[]>;
17
+ export declare function applyAllClients(proxyBaseUrl: string, options?: CliProxyClientApplyOptions): Promise<CliProxyClientApplyResult[]>;
18
18
  /** Restore every client's previous configuration. See applyAllClients. */
19
19
  export declare function restoreAllClients(proxyBaseUrl: string): Promise<CliProxyClientRestoreResult[]>;
@@ -5,6 +5,7 @@ import { codexConfigurator } from "./codex.js";
5
5
  import { qwenCodeConfigurator } from "./qwenCode.js";
6
6
  import { copilotConfigurator } from "./copilot.js";
7
7
  import { geminiConfigurator } from "./gemini.js";
8
+ import { grokConfigurator } from "./grok.js";
8
9
  /**
9
10
  * Every CLI the proxy auto-configures, in apply order.
10
11
  *
@@ -18,6 +19,7 @@ export const PROXY_CLIENT_CONFIGURATORS = [
18
19
  qwenCodeConfigurator,
19
20
  copilotConfigurator,
20
21
  geminiConfigurator,
22
+ grokConfigurator,
21
23
  ];
22
24
  /**
23
25
  * Point every detected client at the proxy.
@@ -27,12 +29,12 @@ export const PROXY_CLIENT_CONFIGURATORS = [
27
29
  * how loudly to report — the daemon-start path logs failures at debug level
28
30
  * while the setup wizard prints a visible warning.
29
31
  */
30
- export async function applyAllClients(proxyBaseUrl) {
32
+ export async function applyAllClients(proxyBaseUrl, options) {
31
33
  const results = [];
32
34
  for (const client of PROXY_CLIENT_CONFIGURATORS) {
33
35
  try {
34
36
  const applied = (await client.detect())
35
- ? await client.apply(proxyBaseUrl)
37
+ ? await client.apply(proxyBaseUrl, options)
36
38
  : false;
37
39
  // Only ask for a note when something was actually written: a note on a
38
40
  // client that was skipped would read as an instruction to act on a
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * Model IDs the proxy advertises when no routing config narrows the list.
3
3
  *
4
- * Two consumers need the same answer and must not drift apart:
4
+ * Three consumers need the same answer and must not drift apart:
5
5
  *
6
6
  * - `proxyTranslationEngine` serves them from `GET /v1/models`.
7
7
  * - The OpenCode client configurator writes them into `provider.neurolink.
@@ -9,6 +9,12 @@
9
9
  * It does not call `/v1/models`, so an empty map means every model id is
10
10
  * unknown and `opencode run` fails with `ProviderModelNotFoundError`
11
11
  * before a request is ever made.
12
+ * - The Grok Build configurator writes the same ids (plus any
13
+ * `routing.model-mappings` in the active proxy config — default
14
+ * `~/.neurolink/proxy-config.yaml`, or the path passed to `--config`)
15
+ * into `~/.grok/config.toml` as `[model.<id>]` entries, with
16
+ * `api_backend` and `context_window` so Grok's compaction matches the
17
+ * upstream. Built-in grok-* ids are skipped.
12
18
  *
13
19
  * Format matches the IDs used throughout `src/lib/models/` and
14
20
  * `src/lib/constants/` (e.g. `claude-3-5-haiku-20241022`, not
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * Model IDs the proxy advertises when no routing config narrows the list.
3
3
  *
4
- * Two consumers need the same answer and must not drift apart:
4
+ * Three consumers need the same answer and must not drift apart:
5
5
  *
6
6
  * - `proxyTranslationEngine` serves them from `GET /v1/models`.
7
7
  * - The OpenCode client configurator writes them into `provider.neurolink.
@@ -9,6 +9,12 @@
9
9
  * It does not call `/v1/models`, so an empty map means every model id is
10
10
  * unknown and `opencode run` fails with `ProviderModelNotFoundError`
11
11
  * before a request is ever made.
12
+ * - The Grok Build configurator writes the same ids (plus any
13
+ * `routing.model-mappings` in the active proxy config — default
14
+ * `~/.neurolink/proxy-config.yaml`, or the path passed to `--config`)
15
+ * into `~/.grok/config.toml` as `[model.<id>]` entries, with
16
+ * `api_backend` and `context_window` so Grok's compaction matches the
17
+ * upstream. Built-in grok-* ids are skipped.
12
18
  *
13
19
  * Format matches the IDs used throughout `src/lib/models/` and
14
20
  * `src/lib/constants/` (e.g. `claude-3-5-haiku-20241022`, not
@@ -39,6 +39,9 @@ const CLIENT_PREFIXES = [
39
39
  // different token, and it is left unmapped until someone measures it rather
40
40
  // than pattern-matched on a guess.
41
41
  ["codex_exec/", "codex"],
42
+ // "grok-shell/1.0.30 (macos; aarch64)" — measured 2026-09-12 on
43
+ // POST /v1/messages from Grok Build 1.0.30.
44
+ ["grok-shell/", "grok"],
42
45
  ];
43
46
  /**
44
47
  * Deliberately NOT mapped, and why each was ruled out.
@@ -11,6 +11,10 @@
11
11
  * falls back to JSON.parse.
12
12
  */
13
13
  import type { LoadProxyConfigOptions, ProxyConfigFile } from "../types/index.js";
14
+ /** Default on-disk path used when `proxy start` is not given `--config`. */
15
+ export declare function defaultProxyConfigPath(): string;
16
+ /** Resolve `--config` the same way `proxy start` / `proxy install` do. */
17
+ export declare function resolveProxyConfigPath(explicit?: string): string;
14
18
  /**
15
19
  * Replace all `${VAR}` / `${VAR:-default}` references in a string.
16
20
  *
@@ -11,9 +11,21 @@
11
11
  * falls back to JSON.parse.
12
12
  */
13
13
  import { readFile } from "node:fs/promises";
14
- import { extname } from "node:path";
14
+ import { homedir } from "node:os";
15
+ import { extname, join, resolve } from "node:path";
15
16
  import { MAX_MAX_INFLIGHT_PER_ACCOUNT, MIN_MAX_INFLIGHT_PER_ACCOUNT, } from "./modelRouter.js";
16
17
  import { logger } from "../utils/logger.js";
18
+ /** Default on-disk path used when `proxy start` is not given `--config`. */
19
+ export function defaultProxyConfigPath() {
20
+ return join(homedir(), ".neurolink", "proxy-config.yaml");
21
+ }
22
+ /** Resolve `--config` the same way `proxy start` / `proxy install` do. */
23
+ export function resolveProxyConfigPath(explicit) {
24
+ const trimmed = explicit?.trim();
25
+ return trimmed && trimmed.length > 0
26
+ ? resolve(trimmed)
27
+ : defaultProxyConfigPath();
28
+ }
17
29
  // ---------------------------------------------------------------------------
18
30
  // Environment variable resolution
19
31
  // ---------------------------------------------------------------------------
@@ -1,4 +1,14 @@
1
1
  import type { JsonObject } from "./common.js";
2
+ /** Options forwarded through `applyAllClients` into a configurator's `apply`. */
3
+ export type CliProxyClientApplyOptions = {
4
+ /**
5
+ * Absolute path of the proxy routing config this process loaded.
6
+ * The Grok writer reads `routing.model-mappings` from this file so a
7
+ * `proxy start --config` catalog matches `/v1/models`. Omit to use
8
+ * `~/.neurolink/proxy-config.yaml`.
9
+ */
10
+ configPath?: string;
11
+ };
2
12
  /**
3
13
  * One AI coding CLI the proxy can point at itself.
4
14
  *
@@ -22,7 +32,7 @@ export type CliProxyClientConfigurator = {
22
32
  * suffix its CLI needs. Returns false when nothing was written, so callers
23
33
  * never print a success message for work that did not happen.
24
34
  */
25
- apply: (proxyBaseUrl: string) => Promise<boolean>;
35
+ apply: (proxyBaseUrl: string, options?: CliProxyClientApplyOptions) => Promise<boolean>;
26
36
  /**
27
37
  * Restore the user's previous configuration. `proxyBaseUrl` is the same bare
28
38
  * origin; a configurator that finds a different URL configured must leave it
@@ -77,6 +87,29 @@ export type CliOpenCodeSnapshot = {
77
87
  /** What the writer last wrote, so apply() can recognise its own block. */
78
88
  written?: unknown;
79
89
  };
90
+ /**
91
+ * One Grok Build picker entry the proxy writer emits under `[model.<id>]`.
92
+ *
93
+ * `contextWindow` is Grok's compaction limit and must be <= the upstream
94
+ * model's window. `supportsReasoningEffort` is false when Grok's `xhigh`
95
+ * would become Anthropic adaptive thinking that the model rejects.
96
+ */
97
+ export type CliGrokProxyModelSpec = {
98
+ id: string;
99
+ name: string;
100
+ apiBackend: "messages" | "chat_completions";
101
+ contextWindow: number;
102
+ maxCompletionTokens: number;
103
+ supportsReasoningEffort: boolean;
104
+ };
105
+ /**
106
+ * Snapshot of whether `~/.grok/config.toml` existed before the proxy wrote
107
+ * its managed block. Persisted to `~/.neurolink/grok-proxy-snapshot.json`.
108
+ */
109
+ export type CliGrokSnapshot = {
110
+ originalExisted: boolean;
111
+ writtenBaseUrl: string;
112
+ };
80
113
  /**
81
114
  * Snapshot of the user's pre-existing Gemini CLI `~/.gemini/.env`.
82
115
  *
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@juspay/neurolink",
3
- "version": "12.13.0",
3
+ "version": "12.14.0",
4
4
  "packageManager": "pnpm@10.15.1",
5
5
  "description": "TypeScript AI SDK with 24+ LLM providers behind one consistent API. MCP-native (connect any MCP server), voice TTS/STT/realtime, RAG, agents, memory, context compaction. OpenAI · Anthropic · Gemini · Bedrock · Azure · Ollama · DeepSeek · NVIDIA NIM and more.",
6
6
  "author": {