@juspay/neurolink 12.31.0 → 12.31.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,8 +1,9 @@
1
- ## [12.31.0](https://github.com/juspay/neurolink/compare/v12.30.2...v12.31.0) (2026-09-26)
1
+ ## [12.31.1](https://github.com/juspay/neurolink/compare/v12.31.0...v12.31.1) (2026-09-26)
2
2
 
3
- ### Features
3
+ ### Bug Fixes
4
4
 
5
- - **(office):** convert DOCX to markdown and add XLSX sheet selection and output formats ([a2a5c2f](https://github.com/juspay/neurolink/commit/a2a5c2fd5f44ff4158ddfebe82158495f252d0d2))
5
+ - **(proxy):** keep a hand-picked Codex provider after an unclean exit ([e43704c](https://github.com/juspay/neurolink/commit/e43704c19335c65c35ba0455707a327a3c72cdca))
6
+ - **(proxy):** keep every Codex call family paired through truncation ([5694a04](https://github.com/juspay/neurolink/commit/5694a04f7c892a5054fd9562c4f4e9a358cc728c))
6
7
 
7
8
  ## [11.2.3](https://github.com/juspay/neurolink/compare/v11.2.2...v11.2.3) (2026-08-19)
8
9
 
@@ -2339,7 +2339,7 @@ data: ${r}
2339
2339
  `))_.startsWith("event:")?w=_.slice(6).trim():_.startsWith("data:")&&E.push(_.slice(5).trim());w&&E.length>0&&h(w,E.join(`
2340
2340
  `),g),y=s.indexOf(`
2341
2341
 
2342
- `)}};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))}}})}Sl(),Ko();function cx(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Osn(e){return cx(e)&&e.role==="system"}function $sr(e){return Array.isArray(e.content)?e.content:[e]}function Nsn(e){if(!cx(e))return[];const t=[];e.type==="function_call"&&typeof e.call_id=="string"&&t.push(e.call_id);for(const r of $sr(e))cx(r)&&r.type==="tool_use"&&typeof r.id=="string"&&t.push(r.id);return t}function Lsn(e){if(!cx(e))return[];const t=[];e.type==="function_call_output"&&typeof e.call_id=="string"&&t.push(e.call_id);for(const r of $sr(e))cx(r)&&r.type==="tool_result"&&typeof r.tool_use_id=="string"&&t.push(r.tool_use_id);return t}function Fsn(e){const t=[];let r=[];const n=new Set;for(let o=0;o<e.length;o+=1){const s=e[o];r.push(o);for(const i of Lsn(s))n.delete(i);for(const i of Nsn(s))n.add(i);n.size===0&&(t.push(r),r=[])}return r.length>0&&t.push(r),t}function $sn(e){if(Array.isArray(e.messages))return"messages";if(Array.isArray(e.conversationMessages))return"conversationMessages";if(Array.isArray(e.input))return"input"}function Usn(e){const t={body:e.body,historyModified:!1,unitsRemoved:0,itemsRemoved:0},r=e.body,n=$sn(r);if(n===void 0)return t;const o=r[n],s=Fsn(o);if(s.length<=1)return t;const i=s.map(h=>e.estimate(h.map(f=>o[f]))),a=n==="conversationMessages"?s.length:s.length-1;let c=0,l=e.inputTokensEstimate;for(;c<a&&l>e.targetTokens;)l-=i[c],c+=1;if(c===0)return t;for(;c<a&&Osn(o[s[c][0]]);)c+=1;const d=s.slice(c).flat().map(h=>o[h]),m=o.length-d.length;return{body:{...e.body,[n]:d},historyModified:!0,unitsRemoved:c,itemsRemoved:m}}var _r=class extends Error{constructor(e,t,r){super(t),this.code=e,this.evidence=r,this.name="ProxyContextPreflightError"}code;evidence;status=400;retryable=!1};function Ls(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function hm(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>0}function Bsn(e){if(!e?.trim())return{};let t;try{t=JSON.parse(e)}catch{throw new _r("invalid_context_policy","NEUROLINK_PROXY_CONTEXT_POLICY must contain a JSON object")}if(!Ls(t))throw new _r("invalid_context_policy","Proxy context policy must be an object");for(const r of Object.keys(t))if(!["maxInputTokens","outputReserveTokens","enforceDiscoveredLimits","toolAllowlist","models"].includes(r))throw new _r("invalid_context_policy",`Unknown context policy field: ${r}`);for(const r of["maxInputTokens","outputReserveTokens"])if(t[r]!==void 0&&!hm(t[r]))throw new _r("invalid_context_policy",`${r} must be a positive safe integer`);if(t.enforceDiscoveredLimits!==void 0&&typeof t.enforceDiscoveredLimits!="boolean")throw new _r("invalid_context_policy","enforceDiscoveredLimits must be boolean");if(t.toolAllowlist!==void 0&&(!Array.isArray(t.toolAllowlist)||t.toolAllowlist.length>4096||!t.toolAllowlist.every(r=>typeof r=="string"&&r.length>0&&r.length<=256)))throw new _r("invalid_context_policy","toolAllowlist must be a bounded array of tool names");if(t.models!==void 0){if(!Ls(t.models)||Object.keys(t.models).length>1024)throw new _r("invalid_context_policy","models must be a bounded map of provider/model limits");for(const[r,n]of Object.entries(t.models)){const o=Ls(n)?n.contextWindow:void 0,s=Ls(n)?n.maxOutputTokens:void 0,i=Ls(n)?n.compactAtTokens:void 0,a=Ls(n)?n.compactToTokens:void 0;if(!r.includes("/")||!Ls(n)||!hm(o)||s!==void 0&&!hm(s)||i!==void 0&&(!hm(i)||i>=o)||a!==void 0&&(!hm(a)||!hm(i)||a>=i)||i!==void 0&&a===void 0||Object.keys(n).some(c=>!["contextWindow","maxOutputTokens","compactAtTokens","compactToTokens"].includes(c)))throw new _r("invalid_context_policy","Each model needs an explicit provider/model key, a positive contextWindow/output limit, and a compaction target below its trigger")}}return t}var Usr,$ae;function zsn(){const e=process.env.NEUROLINK_PROXY_CONTEXT_POLICY;return(!$ae||e!==Usr)&&($ae=Bsn(e),Usr=e),$ae}function KF(e,t,r=new WeakSet,n=0){if(!e||typeof e!="object"||n>128||r.has(e))return;if(r.add(e),Array.isArray(e)){for(const s of e)KF(s,t,r,n+1);return}const o=e;if(["tool_use","function_call","tool_call","function"].includes(String(o.type))){const s=o.name??o.toolName;typeof s=="string"&&t.add(s),Ls(o.function)&&typeof o.function.name=="string"&&t.add(o.function.name)}typeof o.toolName=="string"&&t.add(o.toolName),Ls(o.functionCall)&&typeof o.functionCall.name=="string"&&t.add(o.functionCall.name);for(const[s,i]of Object.entries(o))s!=="tools"&&KF(i,t,r,n+1)}function qsn(e){if(Ls(e))return typeof e.name=="string"?e.name:Ls(e.function)&&typeof e.function.name=="string"?e.function.name:void 0}function Bsr(e){return Array.isArray(e)?e.length:Ls(e)?Object.keys(e).length:0}function Aw(e,t,r,n=new WeakSet,o=0){if(typeof e=="string")return Gt(e,t)+1;if(typeof e=="number"||typeof e=="boolean")return 1;if(!e||typeof e!="object")return 0;if(o>128)throw new _r("context_structure_too_deep","Request context nesting exceeds the supported limit");if(n.has(e))return 0;n.add(e);try{if(Array.isArray(e))return e.reduce((i,a)=>i+Aw(a,t,r,n,o+1)+4,0);const s=e;return e instanceof Uint8Array||e instanceof ArrayBuffer?(r.multimodal=!0,A_):typeof s.text=="string"&&Array.isArray(s.images)?(r.multimodal=s.images.length>0||r.multimodal,Gt(s.text,t)+s.images.length*A_):["input_image","image","image_url","input_audio","audio","file","input_file","document"].includes(String(s.type))||s.inlineData!==void 0||s.fileData!==void 0?(r.multimodal=!0,A_):Object.entries(s).reduce((i,[a,c])=>i+Gt(a,t)+Aw(c,t,r,n,o+1),0)}finally{n.delete(e)}}function Uae(e){const t=e.policy??zsn(),r=e.body;let n=e.body;const o=r.tools;if(t.toolAllowlist){const D=new Set(t.toolAllowlist);KF(r,D),KF(e.toolReferenceBody,D);const U=r.tool_choice;Ls(U)&&(typeof U.name=="string"&&D.add(U.name),Ls(U.function)&&typeof U.function.name=="string"&&D.add(U.function.name));const P=Array.isArray(o)?o.filter($=>{const F=qsn($);return F===void 0||D.has(F)}):Ls(o)?Object.fromEntries(Object.entries(o).filter(([$])=>D.has($))):o;n={...e.body,tools:P,...Array.isArray(r.toolFilter)?{toolFilter:r.toolFilter.filter($=>typeof $!="string"||D.has($))}:{}}}let s=n;const i={multimodal:!1};let a={multimodal:!1};const c=()=>i.multimodal||a.multimodal,l=e.provider==="codex"?"openai":e.provider,u=Aw(s.tools,l,i),d=[s.instructions,s.system,s.systemPrompt,s.systemInstruction].reduce((D,U)=>D+Aw(U,l,i),0),m=[s.response_format,s.output_config,s.structuredOutput,s.schema,Ls(s.text)?s.text.format:void 0,Ls(s.generationConfig)?s.generationConfig.responseSchema:void 0,Ls(s.generationConfig)?s.generationConfig.responseJsonSchema:void 0].reduce((D,U)=>D+Aw(U,l,i),0),h=D=>Aw(D,l,a),f=24+m+u+d,g=()=>[s.messages,s.input,s.contents,s.conversationMessages,s.prompt].reduce((D,U)=>D+h(U),0);let y=f+g();const v=t.models?.[`${e.provider}/${e.model}`];let w=!1,E=0;const _=y;if(v?.compactAtTokens!==void 0&&v.compactToTokens!==void 0&&y>v.compactAtTokens){const D=Usn({body:n,inputTokensEstimate:y,targetTokens:v.compactToTokens,estimate:h});if(D.historyModified&&(n=D.body,s=n,w=!0,E=D.unitsRemoved,a={multimodal:!1},y=f+g()),y>v.compactToTokens)throw new _r("proxy_context_compaction_failed",`Compaction could not bring ${e.provider}/${e.model} within ${v.compactToTokens} tokens; ${y} remain after removing every removable unit`)}const C=_V(e.provider,e.model),A=v?.contextWindow??C,k=v?.maxOutputTokens??CV(e.provider,e.model),R=e.maxOutputTokens??s.max_tokens??s.max_output_tokens??s.maxTokens??(Ls(s.generationConfig)?s.generationConfig.maxOutputTokens:void 0);if(R!==void 0&&!hm(R))throw new _r("invalid_output_budget","Requested output tokens must be a positive safe integer");const I=e.provider==="codex"?k??t.outputReserveTokens??32768:hm(R)?R:k??t.outputReserveTokens??32768,M={provider:e.provider,model:e.model,inputTokensEstimate:y,toolsTokensEstimate:u,instructionsTokensEstimate:d,schemaTokensEstimate:m,outputTokensReserve:I,reasoningIncludedInOutputReserve:!0,...A?{contextWindow:A}:{},contextLimitSource:v?"configured":C?"discovered":"unknown",tokenCountSource:"estimated",multimodalEstimate:c(),originalToolCount:Bsr(o),retainedToolCount:Bsr(s.tools),historyModified:w,...w?{historyUnitsRemoved:E,inputTokensBeforeTruncation:_}:{}};if(t.maxInputTokens!==void 0&&y>t.maxInputTokens)throw new _r("proxy_input_budget_exceeded","Estimated input exceeds the configured proxy token budget; reduce context or tools before retrying",M);if(k!==void 0&&hm(R)&&e.provider!=="codex"&&R>k)throw new _r("proxy_output_budget_exceeded","Requested output exceeds the serving model's known output limit",M);if(A!==void 0&&t.enforceDiscoveredLimits!==!1&&!c()&&y+I>A)throw new _r("proxy_context_window_exceeded",`Estimated input plus output/reasoning reserve exceeds the serving model context window; ${w?"history was truncated and still does not fit":"no history was truncated"}`,M);return{body:n,inputTokensEstimate:y,outputTokensReserve:I,totalTokensReservation:y+I,evidence:M}}Wr();var JF=60*6e4,Gsn=1e4,Bae=5e3,jsn=2e3;function zae(e){const t=e.get("x-neurolink-session-id")??e.get("x-claude-code-session-id")??e.get("session_id")??e.get("session-id")??"unattributed";return Hm("sha256").update(t).digest("hex")}function ai(e,t){const r=e==="PROXY_TOKEN_BUDGET_EXCEEDED"?429:e==="PROXY_TOKEN_BUDGET_INPUT"?400:503;return Object.assign(new Error(t),{code:e,status:r,statusCode:r,retryable:!1})}function el(e){return!e||typeof e!="object"||!("code"in e)||typeof e.code!="string"||!e.code.startsWith("PROXY_TOKEN_BUDGET_")?null:{code:e.code,status:e.code==="PROXY_TOKEN_BUDGET_EXCEEDED"?429:e.code==="PROXY_TOKEN_BUDGET_INPUT"?400:503,retryable:!1,message:e instanceof Error?e.message:"Proxy token budget admission failed"}}function qae(e){if(typeof e=="string")try{e=JSON.parse(e)}catch{throw ai("PROXY_TOKEN_BUDGET_CONFIG","Token budget configuration is not valid JSON")}if(!e||typeof e!="object"||Array.isArray(e))throw ai("PROXY_TOKEN_BUDGET_CONFIG","Token budget configuration must be an object");const t={};for(const[r,n]of Object.entries(e)){if(!["maxInFlightTokens","accountWindowTokens","sessionWindowTokens","windowMs"].includes(r)||typeof n!="number"||!Number.isSafeInteger(n)||n<=0)throw ai("PROXY_TOKEN_BUDGET_CONFIG","Token budget limits must be positive safe integers with supported names");r==="maxInFlightTokens"&&(t.maxInFlightTokens=n),r==="accountWindowTokens"&&(t.accountWindowTokens=n),r==="sessionWindowTokens"&&(t.sessionWindowTokens=n),r==="windowMs"&&(t.windowMs=n)}return t}function zsr(){const e=process.env.NEUROLINK_PROXY_TOKEN_BUDGET;return e===void 0||e.trim()===""?void 0:qae(e)}function Hsn(e){const t=zsr(),r=e===void 0?void 0:qae(e);if(!t)return r;if(!r)return t;const n={windowMs:Math.max(t.windowMs??JF,r.windowMs??JF)};for(const o of["maxInFlightTokens","accountWindowTokens","sessionWindowTokens"]){const s=t[o],i=r[o];(s!==void 0||i!==void 0)&&(n[o]=Math.min(s??Number.MAX_SAFE_INTEGER,i??Number.MAX_SAFE_INTEGER))}return n}function Vsn(e){return!!(e?.maxInFlightTokens||e?.accountWindowTokens||e?.sessionWindowTokens)}function qsr(e){for(const t of["provider","accountKey","sessionKey","requestId"])if(typeof e[t]!="string"||e[t].length===0||e[t].length>512)throw ai("PROXY_TOKEN_BUDGET_INPUT","Token budget requires bounded provider, account, session and request identities");if(!Number.isSafeInteger(e.reservationTokens)||e.reservationTokens<=0)throw ai("PROXY_TOKEN_BUDGET_INPUT","Token reservation must be a positive safe integer");if(e.estimateProvenance!==void 0&&(typeof e.estimateProvenance!="string"||e.estimateProvenance.length>128))throw ai("PROXY_TOKEN_BUDGET_INPUT","Token estimate provenance must be bounded text")}var Wsn=class{constructor(e="supervisor",t=Date.now,r=Gsn,n=Bae){this.scope=e,this.now=t,this.maxKeys=r,this.maxLeases=n}scope;now;maxKeys;maxLeases;buckets=new Map;leases=new Map;bucket(e,t){const r=this.now();let n=this.buckets.get(e);if(!n){if(this.buckets.size>=this.maxKeys)for(const[o,s]of this.buckets)s.inFlightTokens===0&&r-s.lastTouched>=s.windowMs&&this.buckets.delete(o);if(this.buckets.size>=this.maxKeys)throw ai("PROXY_TOKEN_BUDGET_CAPACITY","Token budget scope capacity is full; retry after its window expires");n={chargedTokens:0,inFlightTokens:0,startedAt:r,windowMs:t,lastTouched:r},this.buckets.set(e,n)}return n.windowMs=Math.max(n.windowMs,t),r-n.startedAt>=n.windowMs&&(n.startedAt=r,n.chargedTokens=n.inFlightTokens,n.windowMs=t),n.lastTouched=r,n}reserve(e,t="local"){qsr(e);const r=qae(e.policy??{});if(this.leases.size>=this.maxLeases)throw ai("PROXY_TOKEN_BUDGET_CAPACITY","Token budget outstanding reservation capacity is full");const n=r.windowMs??JF,o=`account:${JSON.stringify([e.provider,e.accountKey])}`,s=`session:${JSON.stringify(e.sessionKey)}`,i=this.bucket(o,n),a=this.bucket(s,n),c=e.reservationTokens;if(r.maxInFlightTokens!==void 0&&c>r.maxInFlightTokens-i.inFlightTokens||r.accountWindowTokens!==void 0&&c>r.accountWindowTokens-i.chargedTokens||r.sessionWindowTokens!==void 0&&c>r.sessionWindowTokens-a.chargedTokens)throw ai("PROXY_TOKEN_BUDGET_EXCEEDED","Token budget would be exceeded before upstream dispatch");if(c>Number.MAX_SAFE_INTEGER-Math.max(i.chargedTokens,a.chargedTokens))throw ai("PROXY_TOKEN_BUDGET_CAPACITY","Token accounting integer capacity is full");i.chargedTokens+=c,i.inFlightTokens+=c,a.chargedTokens+=c,a.inFlightTokens+=c;const l={scope:this.scope,reservationTokens:c,accountChargedTokens:i.chargedTokens,accountInFlightTokens:i.inFlightTokens,sessionChargedTokens:a.chargedTokens,sessionInFlightTokens:a.inFlightTokens,windowMs:n,estimateProvenance:e.estimateProvenance??"caller_estimate_input_plus_max_output"},u=dn();return this.leases.set(u,{owner:t,accountKey:o,sessionKey:s,estimate:c,snapshot:l}),{leaseId:u,snapshot:{...l}}}settle(e,t,r,n=!1){const o=this.leases.get(e);if(!o)return;if(o.owner!==t)throw ai("PROXY_TOKEN_BUDGET_OWNER","Token budget lease belongs to another worker");if(r!==void 0&&(!Number.isSafeInteger(r)||r<0))throw ai("PROXY_TOKEN_BUDGET_USAGE","Reported token usage must be a nonnegative safe integer");const s=n?0:r??o.estimate,i=this.bucket(o.accountKey,o.snapshot.windowMs),a=this.bucket(o.sessionKey,o.snapshot.windowMs);for(const c of[i,a])c.chargedTokens=Math.min(Number.MAX_SAFE_INTEGER,Math.max(0,c.chargedTokens+s-o.estimate)),c.inFlightTokens=Math.max(0,c.inFlightTokens-o.estimate);return this.leases.delete(e),{...o.snapshot,accountChargedTokens:i.chargedTokens,accountInFlightTokens:i.inFlightTokens,sessionChargedTokens:a.chargedTokens,sessionInFlightTokens:a.inFlightTokens,settlement:n?"cancelled_before_dispatch":r===void 0?"estimate_retained":"provider_reported"}}ownerExited(e){for(const[t,r]of this.leases)r.owner===e&&this.settle(t,e)}},Gae=new Wsn(process.env.NEUROLINK_PROXY_SOCKET_WORKER==="1"?"process":"supervisor"),fm=new Map,lx=new Set;function Gsr(e){if(lx.size>=Bae){const t=lx.values().next().value;t&&lx.delete(t)}lx.add(e)}var jsr=!1;function Ksn(){jsr||(jsr=!0,process.on("message",e=>{if(!e||typeof e!="object"||e.type!=="proxy-budget:response")return;const t=e,r=fm.get(t.rpcId);if(!r){lx.delete(t.rpcId)&&t.ok&&typeof t.leaseId=="string"&&t.leaseId.length<=128&&process.connected&&process.send&&process.send({type:"proxy-budget:request",rpcId:dn(),pid:process.pid,generation:Number(process.env.NEUROLINK_PROXY_WORKER_GENERATION),action:"cancel",leaseId:t.leaseId},()=>{});return}fm.delete(t.rpcId),clearTimeout(r.timer),t.ok?r.resolve(t):r.reject(ai(t.errorCode??"PROXY_TOKEN_BUDGET_UNAVAILABLE",t.error??"Token budget coordinator refused the request"))}),process.on("disconnect",()=>{for(const e of fm.values())clearTimeout(e.timer),e.reject(ai("PROXY_TOKEN_BUDGET_UNAVAILABLE","Token budget supervisor disconnected"));fm.clear()}))}function jae(e){return Ksn(),new Promise((t,r)=>{if(!process.connected||!process.send||fm.size>=Bae){r(ai("PROXY_TOKEN_BUDGET_UNAVAILABLE","Token budget supervisor IPC is unavailable"));return}const n=dn(),o=setTimeout(()=>{fm.delete(n),e.action==="reserve"&&Gsr(n),r(ai("PROXY_TOKEN_BUDGET_UNAVAILABLE","Token budget supervisor response timed out; dispatch refused"))},jsn);fm.set(n,{resolve:t,reject:r,timer:o});const s=i=>{!i||!fm.has(n)||(clearTimeout(o),fm.delete(n),e.action==="reserve"&&Gsr(n),r(ai("PROXY_TOKEN_BUDGET_UNAVAILABLE","Token budget IPC send failed")))};try{process.send({...e,type:"proxy-budget:request",rpcId:n,pid:process.pid,generation:Number(process.env.NEUROLINK_PROXY_WORKER_GENERATION)},s)}catch(i){s(i instanceof Error?i:new Error("IPC failed"))}})}async function Hae(e){const t=Hsn(e.policy);if(!Vsn(t))return{leaseId:"disabled",snapshot:{scope:"disabled",reservationTokens:0,accountChargedTokens:0,accountInFlightTokens:0,sessionChargedTokens:0,sessionInFlightTokens:0,windowMs:t?.windowMs??JF,estimateProvenance:"disabled"},settle:async()=>{},cancelBeforeDispatch:async()=>{}};qsr(e);const r=process.env.NEUROLINK_PROXY_SOCKET_WORKER==="1",n={...e,policy:t},o=r?await jae({action:"reserve",reservation:n}):Gae.reserve(n,"local");if(!o.leaseId||!o.snapshot)throw ai("PROXY_TOKEN_BUDGET_UNAVAILABLE","Token budget supervisor returned incomplete reservation proof");const s=o.leaseId;let i=!1;const a={leaseId:s,snapshot:{...o.snapshot,scope:r?"supervisor":"process"},settle:async c=>{if(i)return;const l=r?(await jae({action:"settle",leaseId:s,actualTotalTokens:c})).snapshot:Gae.settle(s,"local",c);i=!0,l&&(a.snapshot={...l,scope:r?"supervisor":"process"})},cancelBeforeDispatch:async()=>{if(i)return;const c=r?(await jae({action:"cancel",leaseId:s})).snapshot:Gae.settle(s,"local",void 0,!0);i=!0,c&&(a.snapshot={...c,scope:r?"supervisor":"process"})}};return a}async function Vae(e,t){try{await e.settle(t)}catch{e.snapshot={...e.snapshot,settlement:"unconfirmed"}}}Ut(),JD(),Wr(),Xt();var Hsr=new Map;function Wae(e){return Hsr.get(e)??Hsr.get(e.replace(/:codex-fallback$/,""))}function xw(e){const t=typeof e.requestId=="string"?Wae(e.requestId):void 0,r=lt.getSpanContext(fr.active()),n=typeof e.traceId=="string"&&typeof e.spanId=="string"?{traceId:e.traceId,spanId:e.spanId}:t??r;if(!n)return;const o=typeof e.traceFlags=="number"&&Number.isInteger(e.traceFlags)&&e.traceFlags>=0&&e.traceFlags<=255?e.traceFlags:t?.traceId===n.traceId?t.traceFlags:r?.traceId===n.traceId?r.traceFlags:0,s={...n,traceFlags:o};return z$(s)?{traceId:s.traceId,spanId:s.spanId,traceFlags:o}:void 0}function Kae(e){const t=xw(e);return t?lt.setSpanContext(q$,t):fr.active()}var Jsn=async()=>{},fhn=globalThis.crypto,ghn=globalThis.ReadableStream||class{},Vsr=Jsn,yhn=globalThis.URL,vhn=globalThis.URLSearchParams,Jae=e=>{try{return JSON.stringify(e,null,2)}catch{return String(e)}};Jae.custom=Symbol.for("nodejs.util.inspect.custom"),Jae.colors={},Jae.styles={};var Ysn=globalThis.TextDecoder,Wsr=globalThis.TextEncoder,Thn=globalThis.performance||{now:()=>Date.now()},whn=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 Wsr().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 Wsr().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 Ysn().decode(this)}},Xsn=e=>({[Symbol.toPrimitive](){return e},ref(){return this},unref(){return this},hasRef(){return!1},refresh(){return this},close(){}}),Zsn=(...e)=>Xsn(globalThis.setTimeout(...e)),bhn=globalThis.clearTimeout,Shn=globalThis.clearInterval,Iw={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};lW(),Mn(),det();var _hn=globalThis.crypto,Qsn=class{constructor(){throw new Error("[NeuroLink:browser] Node HTTP agents require a server runtime")}},Chn=globalThis.ReadableStream||class{},ein=()=>({}),khn=globalThis.URL,Ahn=globalThis.URLSearchParams,Yae=e=>{try{return JSON.stringify(e,null,2)}catch{return String(e)}};Yae.custom=Symbol.for("nodejs.util.inspect.custom"),Yae.colors={},Yae.styles={};var tin=globalThis.TextDecoder,Ksr=globalThis.TextEncoder,xhn=globalThis.performance||{now:()=>Date.now()},Ihn=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 Ksr().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 Ksr().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 tin().decode(this)}},Mhn=globalThis.clearTimeout,Phn=globalThis.clearInterval;JD(),J4(),lW();var rin={serializeRequest(){throw new Error("[NeuroLink:browser] proxy OTLP log transport requires a server runtime")}},nin=WD(K4),oin=64*1024,sin=5,iin=new Set([429,502,503,504]),ain=new Set(["ECONNRESET","ECONNREFUSED","EPIPE","ETIMEDOUT","EAI_AGAIN","ENOTFOUND","ENETUNREACH","EHOSTUNREACH"]),vo=class extends Error{constructor(e,t=!1,r){super(e),this.retryable=t,this.retryAfterMs=r,this.name="ProxyOtlpResponseError"}retryable;retryAfterMs};function cin(e){return e instanceof vo&&e.retryable?e.retryAfterMs??0:void 0}function Jsr(e){return process.env[`OTEL_EXPORTER_OTLP_LOGS_${e}`]?.trim()||process.env[`OTEL_EXPORTER_OTLP_${e}`]?.trim()||void 0}function Xae(e){const t=Jsr(e);if(t)try{return li(t)}catch{throw new Error(`Proxy OTLP ${e} file could not be read`)}}function lin(e){if(!e)return;if(/^\d+$/.test(e.trim()))return Number(e)*1e3;const t=Date.parse(e);return Number.isFinite(t)?Math.max(0,t-Date.now()):void 0}function uin(e){let t;try{t=JSON.parse(e.toString("utf8"))}catch{throw new vo("OTLP response JSON is empty or malformed")}if(!t||typeof t!="object"||Array.isArray(t))throw new vo("OTLP response must be a JSON object");if(Object.keys(t).some(a=>a!=="partialSuccess"&&a!=="partial_success"))throw new vo("OTLP response has unexpected fields");if("partialSuccess"in t&&"partial_success"in t)throw new vo("OTLP response has ambiguous field aliases");const r="partialSuccess"in t?t.partialSuccess:"partial_success"in t?t.partial_success:void 0;if(r==null)return;if(typeof r!="object"||Array.isArray(r))throw new vo("OTLP partial success response is malformed");const n=new Set(["rejectedLogRecords","rejected_log_records","errorMessage","error_message"]);if(Object.keys(r).some(a=>!n.has(a)))throw new vo("OTLP partial success response has unexpected fields");if("rejectedLogRecords"in r&&"rejected_log_records"in r||"errorMessage"in r&&"error_message"in r)throw new vo("OTLP partial success has ambiguous field aliases");const o="errorMessage"in r?r.errorMessage:"error_message"in r?r.error_message:void 0;if(o!=null&&typeof o!="string")throw new vo("OTLP partial success response is malformed");const s="rejectedLogRecords"in r?r.rejectedLogRecords:"rejected_log_records"in r?r.rejected_log_records:0;if(s===null||s===0||s==="0")return;const i=typeof s=="string"&&/^\d+$/.test(s)||typeof s=="number"&&Number.isSafeInteger(s)&&s>=0?BigInt(s):void 0;if(i===void 0||i>9223372036854775807n)throw new vo("OTLP rejected record count is malformed");if(i>0n)throw new vo("OTLP partial success rejected log records")}function din(e,t){let r;try{r=new URL(e)}catch{throw new Error("Proxy OTLP endpoint is invalid")}if(!new Set(["http:","https:"]).has(r.protocol))throw new Error("Proxy OTLP endpoint must use HTTP or HTTPS");if(r.username||r.password)throw new Error("Proxy OTLP endpoint credentials must use OTLP headers");const n=Jsr("COMPRESSION")??"none";if(n!=="none"&&n!=="gzip")throw new Error("Proxy OTLP compression must be none or gzip");const o={};try{for(const h of[process.env.OTEL_EXPORTER_OTLP_HEADERS,process.env.OTEL_EXPORTER_OTLP_LOGS_HEADERS])for(const[f,g]of Object.entries(_ht(h)))set(f),iet(f,g),o[f.toLowerCase()]=g}catch{throw new Error("Proxy OTLP headers are invalid")}o["content-type"]="application/json",o.accept="application/json",o["accept-encoding"]="identity",delete o["content-encoding"],n==="gzip"&&(o["content-encoding"]="gzip");const s={ca:Xae("CERTIFICATE"),cert:Xae("CLIENT_CERTIFICATE"),key:Xae("CLIENT_KEY")};if(!!s.cert!=!!s.key)throw new Error("Proxy OTLP client certificate and key must be set together");const i=r.protocol==="https:"?new Qsn({keepAlive:!0,maxSockets:30,...s}):new oet({keepAlive:!0,maxSockets:30}),a=r.protocol==="https:"?ein:aet;let c=!1;const l=new Set,u=new Set,d=(h,f)=>new Promise((g,y)=>{let v=!1;const w=a(r,{method:"POST",agent:i,signal:f,headers:{...o,"content-length":String(h.byteLength)}},E=>{v=!0;const _=E.statusCode??0,C=M=>{y(M),E.destroy()};if(_!==200){C(new vo(`OTLP HTTP ${_}`,iin.has(_),lin(E.headers["retry-after"])));return}const A=E.headers["content-encoding"];if(A&&A!=="identity"){C(new vo("OTLP response encoding is unsupported"));return}const k=E.headers["content-type"];if(k&&k.split(";",1)[0].trim().toLowerCase()!=="application/json"){C(new vo("OTLP response content type is not JSON"));return}const R=[];let I=0;E.on("data",M=>{if(I+=M.length,I>oin){C(new vo("OTLP response exceeds 64 KiB limit"));return}R.push(M)}),E.on("aborted",()=>y(new vo("OTLP success response was interrupted"))),E.on("error",()=>y(new vo("OTLP success response could not be read"))),E.on("end",()=>{try{uin(Buffer.concat(R)),g()}catch(M){y(M)}})});w.on("error",E=>y(new vo(f.aborted?"OTLP export deadline exceeded":"OTLP transport failed",!v&&(f.aborted||ain.has(E.code??""))))),w.end(h)}),m=async h=>{const f=new AbortController;u.add(f);const g=Date.now()+t,y=setTimeout(()=>f.abort(),t);y.unref();try{const v=rin.serializeRequest(h);if(!v)throw new vo("OTLP serialization produced no payload");const w=n==="gzip"?await nin(v):v;let E=0;for(;!f.signal.aborted&&Date.now()<g;){E++;try{await d(w,f.signal);return}catch(_){if(!(_ instanceof vo)||!_.retryable)throw _;if(E>=sin)throw new vo("OTLP retry attempt limit reached",!0,_.retryAfterMs);const C=Math.min(5e3,1e3*2**Math.min(E-1,3)),A=Math.max(_.retryAfterMs??0,C*(.8+Math.random()*.4));if(A>=g-Date.now())throw new vo("OTLP retry exceeds export deadline",!0,A);await Zsn(A,void 0,{signal:f.signal})}}throw new vo("OTLP export deadline exceeded",!0)}catch(v){throw v instanceof vo?v:new vo(f.signal.aborted?"OTLP export deadline exceeded":"OTLP export failed",f.signal.aborted)}finally{clearTimeout(y),u.delete(f)}};return{abortPending(){c=!0;for(const h of u)h.abort();i.destroy()},export(h,f){if(c){f({code:Su.FAILED,error:new Error("OTLP transport is shut down")});return}const g=m(h).then(()=>f({code:Su.SUCCESS}),y=>f({code:Su.FAILED,error:y}));l.add(g),g.finally(()=>l.delete(g)).catch(()=>{})},async shutdown(){c=!0,await Promise.allSettled(l),i.destroy()}}}CH(),Mht(),Ut(),zt(),Or(),Wr(),JD(),J4();var Dhn=1024*1024,Ohn=8*1024*1024,Nhn=WD(K4);function Ysr(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 Rw,YF=[],ny=new Map,Xsr=new WeakMap,Zsr=new Set,XF=!1,min=128*1024,Qsr=3e4,Zae=Qsr+1e3,pin=2e4,eir=12e4,hin=new Set(["console","runtime","telemetry_delivery"]);function fin(e){try{return 512+Buffer.byteLength(typeof e.body=="string"?e.body:JSON.stringify(e.body)??"","utf8")+Buffer.byteLength(JSON.stringify(e.attributes),"utf8")}catch{return 1/0}}var gs={attempted:0,transportAcknowledged:0,exportUnconfirmed:0,rejected:0,partial:0,pending:0,pendingBytes:0,highWaterPending:0,highWaterBytes:0,maxPending:64,maxPendingBytes:32*1024*1024};function tl(){return process.env.NEUROLINK_PROXY_LOG_SINK==="otel"}function ZF(e,t,r,n){const o=new Set,s=new WeakMap,i=new WeakMap,a=new Set,c=r==="metadata"||r==="indexes"?eir:0,l=new Set,u=new Set,d={attempted:0,submitted:0,transportAcknowledged:0,exportUnconfirmed:0,dropped:0,outstanding:0,outstandingBytes:0,highWaterBytes:0,byteLimitDrops:0,retryingRecords:0,retriedBatches:0,retentionExpired:0,lastTransientFailureAt:void 0,lastAcknowledgedAt:void 0,lastFailureAt:void 0,highWaterOutstanding:0,recentFailures:[],failureHistoryEvicted:0},m=[];let h=!1;const f=(C,A,k)=>{const R=(M,D)=>{const U=M.attributes[D];return typeof U=="string"?U.slice(0,128):void 0},I={id:dn(),at:new Date().toISOString(),reason:A,...k?{error:lr(k.message).slice(0,256)}:{},records:C.slice(0,64).map(M=>({eventId:R(M,"proxy.event_id")??"unavailable",kind:R(M,"proxy.record_kind"),requestId:R(M,"request.id"),captureId:R(M,"body.capture_id")}))};d.recentFailures.length===16&&(d.recentFailures.shift(),d.failureHistoryEvicted++),d.recentFailures.push(I),C.some(M=>M.attributes["proxy.record_kind"]!=="telemetry_delivery")&&(m.length===16&&m.shift(),m.push(I))},g=()=>{h||!m.length||XF||(h=!0,queueMicrotask(()=>{h=!1;for(const C of m.splice(0))Mw("telemetry_delivery",{queue:r,...C})}))},y=din(e,Qsr),v={export(C,A){const k=performance.now();for(const V of C){const G=V.attributes["body.capture_id"],Y=typeof G=="string"?ny.get(G):void 0;Y&&(Y.maxChunkQueueWaitMs=Math.max(Y.maxChunkQueueWaitMs??0,k-(s.get(V)??k)))}let R=!1,I=!1,M,D,U,P=0;const F=Math.min(...C.map(V=>s.get(V)??k))+c,N=()=>{M&&U&&z(U)};a.add(N);const z=V=>{if(!R){R=!0,clearTimeout(D),clearTimeout(M),a.delete(N),I&&(d.retryingRecords-=C.length),d.outstanding-=C.length,V.code===Su.SUCCESS?(d.transportAcknowledged+=C.length,d.lastAcknowledgedAt=new Date().toISOString(),g()):(d.exportUnconfirmed+=C.length,d.lastFailureAt=new Date().toISOString(),f(C,"export_unconfirmed",V.error));for(const G of C){o.delete(G),d.outstandingBytes-=i.get(G)??0;const Y=G.attributes?.["body.capture_id"],se=typeof Y=="string"?ny.get(Y):void 0;if(se){se.maxChunkExportMs=Math.max(se.maxChunkExportMs??0,performance.now()-k);const Z=Xsr.get(se);V.code===Su.SUCCESS&&(Z===void 0||Date.now()<Z)?se.acknowledged++:se.unconfirmed++,se.notify?.()}}for(const G of l)G();for(const G of u)G();A(V)}},B=()=>{if(M=void 0,c&&performance.now()>=F){d.retentionExpired+=C.length,z({code:Su.FAILED,error:new Error("OTLP metadata retention budget exceeded")});return}P++,P>1&&d.retriedBatches++;let V=!1;const G=Y=>{if(V||R)return;V=!0,clearTimeout(D);const se=Y.code===Su.FAILED?cin(Y.error):void 0;if(c&&se!==void 0&&!XF){d.lastTransientFailureAt=new Date().toISOString();const Z=Math.max(se,Math.min(1e4,1e3*2**Math.min(P-1,4))*(.8+Math.random()*.4));if(performance.now()+Z<F){I||(I=!0,d.retryingRecords+=C.length),U=Y,M=setTimeout(B,Z),M.unref();return}d.retentionExpired+=C.length}z(Y)};D=setTimeout(()=>G({code:Su.FAILED,error:new Error("OTLP export callback deadline exceeded")}),Zae),D.unref();try{y.export(C,G)}catch(Y){G({code:Su.FAILED,error:Y instanceof Error?Y:new Error(String(Y))})}};B()},shutdown:()=>y.shutdown()},w=new dW(v,{maxQueueSize:t,maxExportBatchSize:64,scheduledDelayMillis:r==="bodies"?25:1e3,exportTimeoutMillis:c+Zae+1e3}),E={onEmit(C){C.attributes["proxy.event_id"]??=dn(),d.attempted++;const A=C.attributes?.["body.capture_id"],k=typeof A=="string"?ny.get(A):void 0;k&&k.emitted++;const R=fin(C);if(d.outstanding>=t||d.outstandingBytes+R>n){d.dropped++,d.outstandingBytes+R>n&&d.byteLimitDrops++,f([C],"queue_full"),k&&(k.dropped++,k.notify?.());return}d.submitted++,d.outstanding++,d.outstandingBytes+=R,d.highWaterBytes=Math.max(d.highWaterBytes,d.outstandingBytes),i.set(C,R),o.add(C),s.set(C,performance.now()),d.highWaterOutstanding=Math.max(d.highWaterOutstanding,d.outstanding),w.onEmit(C)},forceFlush:async()=>{const C=new Set(o);try{await w.forceFlush()}finally{await new Promise(A=>{const k=()=>{[...C].some(R=>o.has(R))||(u.delete(k),A())};u.add(k),k()})}},shutdown:async()=>{try{await E.forceFlush()}finally{await w.shutdown()}}};return{state:d,processor:E,capacity:t,byteCapacity:n,retentionMs:c,kind:r,waitForCapacity:C=>new Promise(A=>{const k=setTimeout(()=>R(!1),Math.max(0,C-Date.now()));k.unref?.();const R=M=>{clearTimeout(k),l.delete(I),A(M)},I=()=>{Date.now()>=C?R(!1):d.outstanding<t&&R(!0)};l.add(I),I()}),abortPending:()=>y.abortPending(),stopRetention:()=>{for(const C of a)C()},oldestOutstandingAgeMs:()=>{let C=performance.now();for(const A of o)C=Math.min(C,s.get(A)??C);return o.size?Math.max(0,performance.now()-C):0}}}async function gin(e,t,r){gs.attempted++;const n=Buffer.byteLength(t,"utf8");if(!Rw||XF||ny.has(e)||gs.pending>=gs.maxPending||gs.pendingBytes+n>gs.maxPendingBytes)return gs.rejected++,{status:"rejected",acknowledgedChunks:0,unconfirmedChunks:0,droppedChunks:0,reason:ny.has(e)?"body_capture_id_in_use":!Rw||XF?"body_exporter_unavailable":"body_publication_queue_full"};gs.pending++,gs.pendingBytes+=n,gs.highWaterPending=Math.max(gs.highWaterPending,gs.pending),gs.highWaterBytes=Math.max(gs.highWaterBytes,gs.pendingBytes);const o={acknowledged:0,unconfirmed:0,dropped:0,emitted:0};ny.set(e,o);let s;const i=(async()=>{const a=YF.find(E=>E.kind==="bodies");if(!a)return{status:"rejected",acknowledgedChunks:0,unconfirmedChunks:0,droppedChunks:0,reason:"body_exporter_unavailable"};const c=performance.now(),l=Date.now()+pin;Xsr.set(o,l);const u=Ysr(t,min);let d=0,m;try{for(let E=0;E<u.length;E++){for(;a.state.outstanding>=a.capacity;){const _=performance.now(),C=await a.waitForCapacity(l);if(d+=performance.now()-_,!C){m="body_publication_deadline";break}}if(Date.now()>=l){m="body_publication_deadline";break}r(u[E],E,u.length),E%4===3&&await Vsr()}}catch{m="body_publication_failed"}const h=new Promise(E=>{const _=()=>{o.acknowledged+o.unconfirmed+o.dropped>=o.emitted&&(o.notify=void 0,E())};o.notify=_,_()});let f;const g=await Promise.race([h.then(()=>!0),new Promise(E=>{f=setTimeout(()=>E(!1),Math.max(0,l-Date.now())),f.unref?.()})]).finally(()=>clearTimeout(f));g||(s=h),(!g||Date.now()>=l)&&(m??="body_publication_deadline"),!m&&o.unconfirmed?m="body_export_unconfirmed":!m&&o.dropped&&(m="body_export_queue_full");const y=Math.max(0,o.emitted-o.acknowledged-o.unconfirmed-o.dropped),v=o.unconfirmed+y;return{status:o.emitted===0?"rejected":o.dropped||o.emitted!==u.length?"partial":v?"export_unconfirmed":"transport_acknowledged",expectedChunks:u.length,acknowledgedChunks:o.acknowledged,unconfirmedChunks:v,droppedChunks:o.dropped,notSubmittedChunks:u.length-o.emitted,publicationMs:performance.now()-c,capacityWaitMs:d,maxChunkQueueWaitMs:o.maxChunkQueueWaitMs??0,maxChunkExportMs:o.maxChunkExportMs??0,...m?{reason:m}:{}}})();Zsr.add(i);try{const a=await i;return a.status==="transport_acknowledged"?gs.transportAcknowledged++:a.status==="export_unconfirmed"?gs.exportUnconfirmed++:a.status==="rejected"?gs.rejected++:gs.partial++,a}finally{Zsr.delete(i);const a=()=>{ny.delete(e),gs.pending--,gs.pendingBytes-=n};s?s.then(a,a):a()}}function tir(e="worker"){if(!tl())return;if(Rw)return Rw;const t=process.env.OTEL_EXPORTER_OTLP_LOGS_ENDPOINT??(process.env.OTEL_EXPORTER_OTLP_ENDPOINT?`${process.env.OTEL_EXPORTER_OTLP_ENDPOINT.replace(/\/$/,"")}/v1/logs`:void 0);if(!t)throw new Error("OTel-only proxy logging requires an OTLP endpoint");const r=process.env.NEUROLINK_PROXY_OTLP_BODIES_ENDPOINT??t;for(const a of[t,r]){const c=new URL(a);if(!["http:","https:"].includes(c.protocol))throw new Error("Proxy OTLP logs endpoint must use HTTP or HTTPS");const l=["localhost","127.0.0.1","[::1]"].includes(c.hostname);if(c.protocol==="http:"&&!l)throw new Error("Proxy OTLP logs require HTTPS for non-loopback collectors")}const n=ZF(t,2048,"metadata",8*1024*1024),o=ZF(r,256,"bodies",40*1024*1024),s=ZF(t,512,"diagnostics",2*1024*1024),i=ZF(t,1024,"indexes",8*1024*1024);return YF.push(n,o,s,i),Rw=new uW({forceFlushTimeoutMillis:eir+Zae+2e3,resource:WM({"service.name":process.env.OTEL_SERVICE_NAME??"neurolink-proxy","service.instance.id":`${e}-${process.pid}`,"process.pid":process.pid,"proxy.process.role":e}),processors:[{onEmit(a,c){(a.attributes?.["proxy.record_kind"]==="body"?o:a.attributes?.["proxy.record_kind"]==="body_capture_index"?i:a.attributes?.["proxy.lifecycle.event"]==="runtime_sample"||hin.has(String(a.attributes?.["proxy.record_kind"]))?s:n).processor.onEmit(a,c)},forceFlush:async()=>{await Promise.all(YF.map(a=>a.processor.forceFlush()))},shutdown:async()=>{await Promise.all(YF.map(a=>a.processor.shutdown()))}}]}),Rw}function Mw(e,t){if(tl())try{const r=typeof t.requestId=="string"&&!t.traceId?Wae(t.requestId):void 0,n=r?{...t,...r}:t;tir()?.getLogger("neurolink-proxy-events").emit({context:Kae(n),severityNumber:Iw.INFO,severityText:"INFO",body:JSON.stringify(n),attributes:{"proxy.record_kind":e,"event.name":`proxy.${e}`,...typeof t.requestId=="string"?{"request.id":t.requestId}:{},...typeof t.event=="string"?{"proxy.lifecycle.event":t.event}:{}}})}catch{yin++}}var yin=0;Wr();var rir=1024,nir=5*6e4;function vin(e={}){const t=e.now??(()=>performance.now()),r=e.bytesPerMinute?.trim(),n=r?Number(r):null,o=n!==null&&(!Number.isSafeInteger(n)||n<=0),s=new Map;let i=n??1/0,a=t(),c=0,l=0,u=0,d=0,m=0;const h=()=>{const f=t();n!==null&&!o&&(i=Math.min(n,i+Math.max(0,f-a)*n/6e4)),a=f;for(const[g,y]of s)y.expiresAt<=f&&s.delete(g)};return{snapshot(){return h(),{deduplicationEnabled:e.deduplicate!==!1,maxReferences:rir,referenceTtlMs:nir,references:s.size,byteBudgetPerMinute:o?null:n,invalidByteBudget:o,availableBytes:n===null||o?null:Math.floor(i),submittedBytes:c,deduplicatedCaptures:l,deduplicatedBytes:u,policyExcludedCaptures:d,policyExcludedBytes:m}},async publish(f,g,y){if(h(),g.redactedBody===void 0)return{};const v=Buffer.byteLength(g.redactedBody,"utf8"),w=e.deduplicate!==!1&&g.bodySha256&&f.captureId?JSON.stringify([f.requestId,g.bodySha256,v]):void 0,E=w?s.get(w):void 0;if(E&&E.reference.captureId!==f.captureId&&await E.acknowledged&&E.expiresAt>t())return l++,u+=v,{delivery:{status:"reference",reason:"identical_redacted_payload"},reference:{...E.reference}};if(h(),o||v>i)return d++,m+=v,{delivery:{status:"policy_excluded",reason:o?"body_byte_budget_invalid":"body_byte_budget_exhausted"}};i-=v,c+=v;let _=()=>{};const C=w&&f.captureId&&g.bodySha256?{reference:{captureId:f.captureId,requestId:f.requestId,bodySha256:g.bodySha256,redactedBodyBytes:v,exportedAt:""},expiresAt:t()+nir,acknowledged:new Promise(k=>{_=k})}:void 0;if(w&&C){if(s.size>=rir){const k=s.keys().next().value;k!==void 0&&s.delete(k)}s.set(w,C)}let A=!1;try{const k=await y();return A=k?.status==="transport_acknowledged",C&&A&&(C.reference.exportedAt=new Date().toISOString()),{delivery:k}}finally{_(A),w&&!A&&s.get(w)===C&&s.delete(w)}}}}hr(),Ri(),Ja(),on(),Wo();var Lhn=globalThis.crypto,Fhn=globalThis.ReadableStream||class{},$hn=globalThis.URL,Uhn=globalThis.URLSearchParams,Qae=e=>{try{return JSON.stringify(e,null,2)}catch{return String(e)}};Qae.custom=Symbol.for("nodejs.util.inspect.custom"),Qae.colors={},Qae.styles={};var Tin=globalThis.TextDecoder,oir=globalThis.TextEncoder,Bhn=globalThis.performance||{now:()=>Date.now()},win=class{},zhn=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 oir().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 oir().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 Tin().decode(this)}},Ghn=globalThis.clearTimeout,jhn=globalThis.clearInterval,ux=64,QF=32*1024*1024,sir=64,iir=32*1024*1024,Ein=2e4,bin=16*1024*1024,air=2e4,oy,Sin,Zp=0,_in=0,Jt={attempted:0,completed:0,rejected:0,failed:0,pending:0,pendingBytes:0,maxPending:ux,maxPendingBytes:QF,highWaterPending:0,highWaterBytes:0,waiting:0,waitingBytes:0,maxWaiting:sir,maxWaitingBytes:iir,highWaterWaiting:0,highWaterWaitingBytes:0,admissionWaits:0,admissionTimeouts:0,rejectionReasons:{}},dx=new Map,cir=new Map,sy=[],e$;function lir(e){return Date.now()<Zp||Jt.pending>=ux||Jt.pendingBytes+e>QF?!1:(Jt.pending+=1,Jt.pendingBytes+=e,Jt.highWaterPending=Math.max(Jt.highWaterPending,Jt.pending),Jt.highWaterBytes=Math.max(Jt.highWaterBytes,Jt.pendingBytes),!0)}function ece(){if(sy.length){if(Date.now()<Zp){e$||(e$=setTimeout(()=>{e$=void 0,ece()},Math.max(1,Zp-Date.now())),e$.unref?.());return}for(let e=0;e<sy.length&&!(Jt.pending>=ux);){const t=sy[e];if(!lir(t.bytes)){e+=1;continue}sy.splice(e,1),clearTimeout(t.timer),Jt.waiting-=1,Jt.waitingBytes-=t.bytes,t.resolve("admitted")}}}function Cin(e){return Jt.waiting>=sir||Jt.waitingBytes+e>iir?Promise.resolve("queue_full"):(Jt.admissionWaits+=1,Jt.waiting+=1,Jt.waitingBytes+=e,Jt.highWaterWaiting=Math.max(Jt.highWaterWaiting,Jt.waiting),Jt.highWaterWaitingBytes=Math.max(Jt.highWaterWaitingBytes,Jt.waitingBytes),new Promise(t=>{const r=setTimeout(()=>{const n=sy.findIndex(o=>o.timer===r);n<0||(sy.splice(n,1),Jt.waiting-=1,Jt.waitingBytes-=e,Jt.admissionTimeouts+=1,t("timeout"),ece())},Ein);r.unref?.(),sy.push({bytes:e,queuedAt:Date.now(),resolve:t,timer:r})}))}function uir(e){Jt.pending-=1,Jt.pendingBytes-=e,ece()}function kin(e,t){const r=[e],n=new Set;let o=0,s=0;for(;r.length;){if(++s>1e5)throw new Error("body_capture_traversal_limit");if(o>t)return o;const i=r.pop();if(typeof i=="string"){o+=16+i.length*2;continue}if(o+=16,!(!i||typeof i!="object")){if(n.has(i))throw new Error("body_capture_unsupported_value");if(n.add(i),!Array.isArray(i)&&Object.getPrototypeOf(i)!==Object.prototype&&Object.getPrototypeOf(i)!==null)throw new Error("body_capture_unsupported_value");for(const a of Object.keys(i)){o+=16+a.length*2;const c=Object.getOwnPropertyDescriptor(i,a);if(!c||c.get||c.set)throw new Error("body_capture_unsupported_value");if(r.push(c.value),r.length>1e5)throw new Error("body_capture_traversal_limit");if(o>t)return o}}}return o}function tce(e,t){const r=dx.get(e);r&&(dx.delete(e),clearTimeout(r.timer),r.resolve(t),dx.size||oy?.unref())}function rce(e,t){if(oy===e){oy=void 0,Zp=Date.now()+5e3;for(const r of dx.keys())tce(r,{error:t,stored:{bodyWriteFailed:!0}});e.terminate().catch(()=>{})}}function Ain(){if(oy)return oy;const e=new win(Sin??new URL("./bodyCaptureWorkerEntry.js",import.meta.url),{execArgv:process.execArgv.filter(t=>!t.startsWith("--input-type")),resourceLimits:{maxOldGenerationSizeMb:128}});return oy=e,e.on("message",t=>{oy===e&&tce(t.id,t.result)}),e.on("error",()=>rce(e,"body_worker_error")),e.on("exit",()=>rce(e,"body_worker_exit")),e.unref(),e}async function xin(e,t,r){Jt.attempted+=1;const n=Date.now(),o=t===null?QF:bin;let s,i;try{s=kin(e,o)}catch(d){s=1/0,i=d instanceof Error&&["body_capture_entry_too_large","body_capture_traversal_limit","body_capture_unsupported_value"].includes(d.message)?d.message:"body_capture_unsupported_value"}let a="queue_full";if(s<=o&&Date.now()>=Zp&&(a=lir(s)?"admitted":t===null?await Cin(s):"queue_full"),a!=="admitted"){Jt.rejected+=1;const d=s>o?i??"body_capture_entry_too_large":Date.now()<Zp?"body_worker_backoff":a==="timeout"?"body_capture_admission_timeout":"body_capture_queue_full";return Jt.lastError=d,Jt.lastRejectedAt=new Date().toISOString(),Jt.rejectionReasons[d]=(Jt.rejectionReasons[d]??0)+1,r({error:d,stored:{bodyWriteFailed:!0},admissionWaitMs:Math.max(0,Date.now()-n),admission:{limitingResource:s>o?"entry":Date.now()<Zp?"worker":Jt.pending>=ux?"captures":"bytes",estimatedBytes:Number.isFinite(s)?s:void 0,maxEntryBytes:o,pending:Jt.pending,pendingBytes:Jt.pendingBytes,maxPending:ux,maxPendingBytes:QF}})}const c=Date.now();let l;try{l=Ain()}catch{return Zp=Date.now()+5e3,uir(s),Jt.failed+=1,r({error:"body_worker_start_failed",stored:{bodyWriteFailed:!0}})}const u=++_in;return new Promise(d=>{const m=setTimeout(()=>rce(l,"body_worker_timeout"),air);m.unref(),dx.set(u,{timer:m,startedAt:Date.now(),resolve:h=>{cir.set(u,Date.now()),h.admissionWaitMs=Math.max(0,c-n),h.workerQueueWaitMs=Math.max(0,(h.queueWaitMs??0)-h.admissionWaitMs),r(h).catch(()=>{h.error??="body_capture_publication_failed"}).finally(()=>{cir.delete(u),uir(s),h.error||h.stored.bodyWriteFailed?Jt.failed+=1:Jt.completed+=1,h.error&&(Jt.lastError=h.error),d()})}}),l.ref();try{l.postMessage({id:u,entry:e,logDir:t,queuedAt:n})}catch{tce(u,{error:"body_capture_clone_failed",stored:{bodyWriteFailed:!0}})}})}j$();var dir=new Wx;function Pw(){return dir.getStore()}function mir(){return dir.getStore()!==void 0}Lr();var Dw=null,nce=!1,Iin=vin(),oce=new Set,sce=5e3,Hhn=air+2*sce,Rin=4096,t$=new Map,Min=E7,ice=()=>({attempted:0,written:0,inFlight:0,pending:0,dropped:0,writeTimeouts:0,unconfirmedWrites:0}),Pin={requests:ice(),attempts:ice(),debug:ice()};async function ace(e,t,r,n={}){const o=Pin[r];if(o.attempted+=1,o.pending+o.inFlight>=Rin){o.dropped+=1;return}o.pending+=1;const s=pir((t$.get(e)??Promise.resolve()).then(async()=>{o.pending-=1,o.inFlight+=1;const i=setTimeout(()=>{o.writeTimeouts+=1},sce);i.unref?.();try{await Min(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(t$.set(e,s),s.then(()=>{t$.get(e)===s&&t$.delete(e)}),n.waitForPersistence)return s;await Ct(s,sce,"Proxy metadata write remains pending").catch(()=>{})}function pir(e){return oce.add(e),e.then(()=>oce.delete(e),()=>oce.delete(e)),e}var Ow=null,hir=0,Din=10,Oin=16e3;function Nin(e){if(e.apiEquivalentCostUsd=null,e.apiEquivalentCacheSavingsUsd=null,e.pricingBasis="api_price_table",e.pricingProvider=e.provider??"openai-compatible",e.usageOwnerRequestId&&e.usageOwnerRequestId!==e.requestId){e.pricingStatus="owned_by_child";return}const t=e.inputTokens,r=e.outputTokens,n=e.cacheReadTokens??0,o=e.cacheCreationTokens??0;if(t===void 0||r===void 0||!Number.isFinite(t)||t<0||!Number.isFinite(r)||r<0||!Number.isFinite(n)||n<0||!Number.isFinite(o)||o<0||e.inputIncludesCachedTokens===!0&&n+o>t||e.inputIncludesCachedTokens===!0&&(e.cacheReadTokensObserved===!1||e.cacheCreationTokensObserved===!1)){e.pricingStatus="usage_incomplete";return}if(!wd(e.pricingProvider,e.model)){e.pricingStatus="unavailable";return}if(!t4(e.pricingProvider,e.model)){e.pricingStatus="inferred";return}const s=Yp({inputTokens:t,outputTokens:r,cacheReadTokens:n,cacheCreationTokens:o,inputIncludesCachedTokens:e.inputIncludesCachedTokens});e.pricingStatus="exact",e.apiEquivalentCostUsd=xi(e.pricingProvider,e.model,s);const i=xi(e.pricingProvider,e.model,{...s,input:s.input+(s.cacheReadTokens??0),cacheReadTokens:0});e.apiEquivalentCacheSavingsUsd=Math.max(0,Math.round((i-e.apiEquivalentCostUsd)*1e6)/1e6)}async function Nw(e){if(Object.assign(e,ax(e.requestId)),Nin(e),!e.traceId||e.traceFlags===void 0){const n=xw(e);n&&Object.assign(e,n)}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",!Tsn(e)||!nce||!Dw&&!tl())return;if(tl()){await gir(e);return}const t=At(Dw,`proxy-${new Date().toISOString().split("T")[0]}.jsonl`),r=JSON.stringify(e)+`
2342
+ `)}};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))}}})}Sl(),Ko();function cx(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Osn(e){return cx(e)&&e.role==="system"}function $sr(e){return Array.isArray(e.content)?e.content:[e]}function Nsn(e){if(!cx(e))return[];const t=[];typeof e.type=="string"&&e.type.endsWith("_call")&&typeof e.call_id=="string"&&t.push(e.call_id);for(const r of $sr(e))cx(r)&&r.type==="tool_use"&&typeof r.id=="string"&&t.push(r.id);return t}function Lsn(e){if(!cx(e))return[];const t=[];typeof e.type=="string"&&e.type.endsWith("_call_output")&&typeof e.call_id=="string"&&t.push(e.call_id);for(const r of $sr(e))cx(r)&&r.type==="tool_result"&&typeof r.tool_use_id=="string"&&t.push(r.tool_use_id);return t}function Fsn(e){const t=[];let r=[];const n=new Set;for(let o=0;o<e.length;o+=1){const s=e[o];r.push(o);for(const i of Lsn(s))n.delete(i);for(const i of Nsn(s))n.add(i);n.size===0&&(t.push(r),r=[])}return r.length>0&&t.push(r),t}function $sn(e){if(Array.isArray(e.messages))return"messages";if(Array.isArray(e.conversationMessages))return"conversationMessages";if(Array.isArray(e.input))return"input"}function Usn(e){const t={body:e.body,historyModified:!1,unitsRemoved:0,itemsRemoved:0},r=e.body,n=$sn(r);if(n===void 0)return t;const o=r[n],s=Fsn(o);if(s.length<=1)return t;const i=s.map(h=>e.estimate(h.map(f=>o[f]))),a=n==="conversationMessages"?s.length:s.length-1;let c=0,l=e.inputTokensEstimate;for(;c<a&&l>e.targetTokens;)l-=i[c],c+=1;if(c===0)return t;for(;c<a&&Osn(o[s[c][0]]);)c+=1;const d=s.slice(c).flat().map(h=>o[h]),m=o.length-d.length;return{body:{...e.body,[n]:d},historyModified:!0,unitsRemoved:c,itemsRemoved:m}}var _r=class extends Error{constructor(e,t,r){super(t),this.code=e,this.evidence=r,this.name="ProxyContextPreflightError"}code;evidence;status=400;retryable=!1};function Ls(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function hm(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>0}function Bsn(e){if(!e?.trim())return{};let t;try{t=JSON.parse(e)}catch{throw new _r("invalid_context_policy","NEUROLINK_PROXY_CONTEXT_POLICY must contain a JSON object")}if(!Ls(t))throw new _r("invalid_context_policy","Proxy context policy must be an object");for(const r of Object.keys(t))if(!["maxInputTokens","outputReserveTokens","enforceDiscoveredLimits","toolAllowlist","models"].includes(r))throw new _r("invalid_context_policy",`Unknown context policy field: ${r}`);for(const r of["maxInputTokens","outputReserveTokens"])if(t[r]!==void 0&&!hm(t[r]))throw new _r("invalid_context_policy",`${r} must be a positive safe integer`);if(t.enforceDiscoveredLimits!==void 0&&typeof t.enforceDiscoveredLimits!="boolean")throw new _r("invalid_context_policy","enforceDiscoveredLimits must be boolean");if(t.toolAllowlist!==void 0&&(!Array.isArray(t.toolAllowlist)||t.toolAllowlist.length>4096||!t.toolAllowlist.every(r=>typeof r=="string"&&r.length>0&&r.length<=256)))throw new _r("invalid_context_policy","toolAllowlist must be a bounded array of tool names");if(t.models!==void 0){if(!Ls(t.models)||Object.keys(t.models).length>1024)throw new _r("invalid_context_policy","models must be a bounded map of provider/model limits");for(const[r,n]of Object.entries(t.models)){const o=Ls(n)?n.contextWindow:void 0,s=Ls(n)?n.maxOutputTokens:void 0,i=Ls(n)?n.compactAtTokens:void 0,a=Ls(n)?n.compactToTokens:void 0;if(!r.includes("/")||!Ls(n)||!hm(o)||s!==void 0&&!hm(s)||i!==void 0&&(!hm(i)||i>=o)||a!==void 0&&(!hm(a)||!hm(i)||a>=i)||i!==void 0&&a===void 0||Object.keys(n).some(c=>!["contextWindow","maxOutputTokens","compactAtTokens","compactToTokens"].includes(c)))throw new _r("invalid_context_policy","Each model needs an explicit provider/model key, a positive contextWindow/output limit, and a compaction target below its trigger")}}return t}var Usr,$ae;function zsn(){const e=process.env.NEUROLINK_PROXY_CONTEXT_POLICY;return(!$ae||e!==Usr)&&($ae=Bsn(e),Usr=e),$ae}function KF(e,t,r=new WeakSet,n=0){if(!e||typeof e!="object"||n>128||r.has(e))return;if(r.add(e),Array.isArray(e)){for(const s of e)KF(s,t,r,n+1);return}const o=e;if(["tool_use","function_call","tool_call","function"].includes(String(o.type))){const s=o.name??o.toolName;typeof s=="string"&&t.add(s),Ls(o.function)&&typeof o.function.name=="string"&&t.add(o.function.name)}typeof o.toolName=="string"&&t.add(o.toolName),Ls(o.functionCall)&&typeof o.functionCall.name=="string"&&t.add(o.functionCall.name);for(const[s,i]of Object.entries(o))s!=="tools"&&KF(i,t,r,n+1)}function qsn(e){if(Ls(e))return typeof e.name=="string"?e.name:Ls(e.function)&&typeof e.function.name=="string"?e.function.name:void 0}function Bsr(e){return Array.isArray(e)?e.length:Ls(e)?Object.keys(e).length:0}function Aw(e,t,r,n=new WeakSet,o=0){if(typeof e=="string")return Gt(e,t)+1;if(typeof e=="number"||typeof e=="boolean")return 1;if(!e||typeof e!="object")return 0;if(o>128)throw new _r("context_structure_too_deep","Request context nesting exceeds the supported limit");if(n.has(e))return 0;n.add(e);try{if(Array.isArray(e))return e.reduce((i,a)=>i+Aw(a,t,r,n,o+1)+4,0);const s=e;return e instanceof Uint8Array||e instanceof ArrayBuffer?(r.multimodal=!0,A_):typeof s.text=="string"&&Array.isArray(s.images)?(r.multimodal=s.images.length>0||r.multimodal,Gt(s.text,t)+s.images.length*A_):["input_image","image","image_url","input_audio","audio","file","input_file","document"].includes(String(s.type))||s.inlineData!==void 0||s.fileData!==void 0?(r.multimodal=!0,A_):Object.entries(s).reduce((i,[a,c])=>i+Gt(a,t)+Aw(c,t,r,n,o+1),0)}finally{n.delete(e)}}function Uae(e){const t=e.policy??zsn(),r=e.body;let n=e.body;const o=r.tools;if(t.toolAllowlist){const D=new Set(t.toolAllowlist);KF(r,D),KF(e.toolReferenceBody,D);const U=r.tool_choice;Ls(U)&&(typeof U.name=="string"&&D.add(U.name),Ls(U.function)&&typeof U.function.name=="string"&&D.add(U.function.name));const P=Array.isArray(o)?o.filter($=>{const F=qsn($);return F===void 0||D.has(F)}):Ls(o)?Object.fromEntries(Object.entries(o).filter(([$])=>D.has($))):o;n={...e.body,tools:P,...Array.isArray(r.toolFilter)?{toolFilter:r.toolFilter.filter($=>typeof $!="string"||D.has($))}:{}}}let s=n;const i={multimodal:!1};let a={multimodal:!1};const c=()=>i.multimodal||a.multimodal,l=e.provider==="codex"?"openai":e.provider,u=Aw(s.tools,l,i),d=[s.instructions,s.system,s.systemPrompt,s.systemInstruction].reduce((D,U)=>D+Aw(U,l,i),0),m=[s.response_format,s.output_config,s.structuredOutput,s.schema,Ls(s.text)?s.text.format:void 0,Ls(s.generationConfig)?s.generationConfig.responseSchema:void 0,Ls(s.generationConfig)?s.generationConfig.responseJsonSchema:void 0].reduce((D,U)=>D+Aw(U,l,i),0),h=D=>Aw(D,l,a),f=24+m+u+d,g=()=>[s.messages,s.input,s.contents,s.conversationMessages,s.prompt].reduce((D,U)=>D+h(U),0);let y=f+g();const v=t.models?.[`${e.provider}/${e.model}`];let w=!1,E=0;const _=y;if(v?.compactAtTokens!==void 0&&v.compactToTokens!==void 0&&y>v.compactAtTokens){const D=Usn({body:n,inputTokensEstimate:y,targetTokens:v.compactToTokens,estimate:h});if(D.historyModified&&(n=D.body,s=n,w=!0,E=D.unitsRemoved,a={multimodal:!1},y=f+g()),y>v.compactToTokens)throw new _r("proxy_context_compaction_failed",`Compaction could not bring ${e.provider}/${e.model} within ${v.compactToTokens} tokens; ${y} remain after removing every removable unit`)}const C=_V(e.provider,e.model),A=v?.contextWindow??C,k=v?.maxOutputTokens??CV(e.provider,e.model),R=e.maxOutputTokens??s.max_tokens??s.max_output_tokens??s.maxTokens??(Ls(s.generationConfig)?s.generationConfig.maxOutputTokens:void 0);if(R!==void 0&&!hm(R))throw new _r("invalid_output_budget","Requested output tokens must be a positive safe integer");const I=e.provider==="codex"?k??t.outputReserveTokens??32768:hm(R)?R:k??t.outputReserveTokens??32768,M={provider:e.provider,model:e.model,inputTokensEstimate:y,toolsTokensEstimate:u,instructionsTokensEstimate:d,schemaTokensEstimate:m,outputTokensReserve:I,reasoningIncludedInOutputReserve:!0,...A?{contextWindow:A}:{},contextLimitSource:v?"configured":C?"discovered":"unknown",tokenCountSource:"estimated",multimodalEstimate:c(),originalToolCount:Bsr(o),retainedToolCount:Bsr(s.tools),historyModified:w,...w?{historyUnitsRemoved:E,inputTokensBeforeTruncation:_}:{}};if(t.maxInputTokens!==void 0&&y>t.maxInputTokens)throw new _r("proxy_input_budget_exceeded","Estimated input exceeds the configured proxy token budget; reduce context or tools before retrying",M);if(k!==void 0&&hm(R)&&e.provider!=="codex"&&R>k)throw new _r("proxy_output_budget_exceeded","Requested output exceeds the serving model's known output limit",M);if(A!==void 0&&t.enforceDiscoveredLimits!==!1&&!c()&&y+I>A)throw new _r("proxy_context_window_exceeded",`Estimated input plus output/reasoning reserve exceeds the serving model context window; ${w?"history was truncated and still does not fit":"no history was truncated"}`,M);return{body:n,inputTokensEstimate:y,outputTokensReserve:I,totalTokensReservation:y+I,evidence:M}}Wr();var JF=60*6e4,Gsn=1e4,Bae=5e3,jsn=2e3;function zae(e){const t=e.get("x-neurolink-session-id")??e.get("x-claude-code-session-id")??e.get("session_id")??e.get("session-id")??"unattributed";return Hm("sha256").update(t).digest("hex")}function ai(e,t){const r=e==="PROXY_TOKEN_BUDGET_EXCEEDED"?429:e==="PROXY_TOKEN_BUDGET_INPUT"?400:503;return Object.assign(new Error(t),{code:e,status:r,statusCode:r,retryable:!1})}function el(e){return!e||typeof e!="object"||!("code"in e)||typeof e.code!="string"||!e.code.startsWith("PROXY_TOKEN_BUDGET_")?null:{code:e.code,status:e.code==="PROXY_TOKEN_BUDGET_EXCEEDED"?429:e.code==="PROXY_TOKEN_BUDGET_INPUT"?400:503,retryable:!1,message:e instanceof Error?e.message:"Proxy token budget admission failed"}}function qae(e){if(typeof e=="string")try{e=JSON.parse(e)}catch{throw ai("PROXY_TOKEN_BUDGET_CONFIG","Token budget configuration is not valid JSON")}if(!e||typeof e!="object"||Array.isArray(e))throw ai("PROXY_TOKEN_BUDGET_CONFIG","Token budget configuration must be an object");const t={};for(const[r,n]of Object.entries(e)){if(!["maxInFlightTokens","accountWindowTokens","sessionWindowTokens","windowMs"].includes(r)||typeof n!="number"||!Number.isSafeInteger(n)||n<=0)throw ai("PROXY_TOKEN_BUDGET_CONFIG","Token budget limits must be positive safe integers with supported names");r==="maxInFlightTokens"&&(t.maxInFlightTokens=n),r==="accountWindowTokens"&&(t.accountWindowTokens=n),r==="sessionWindowTokens"&&(t.sessionWindowTokens=n),r==="windowMs"&&(t.windowMs=n)}return t}function zsr(){const e=process.env.NEUROLINK_PROXY_TOKEN_BUDGET;return e===void 0||e.trim()===""?void 0:qae(e)}function Hsn(e){const t=zsr(),r=e===void 0?void 0:qae(e);if(!t)return r;if(!r)return t;const n={windowMs:Math.max(t.windowMs??JF,r.windowMs??JF)};for(const o of["maxInFlightTokens","accountWindowTokens","sessionWindowTokens"]){const s=t[o],i=r[o];(s!==void 0||i!==void 0)&&(n[o]=Math.min(s??Number.MAX_SAFE_INTEGER,i??Number.MAX_SAFE_INTEGER))}return n}function Vsn(e){return!!(e?.maxInFlightTokens||e?.accountWindowTokens||e?.sessionWindowTokens)}function qsr(e){for(const t of["provider","accountKey","sessionKey","requestId"])if(typeof e[t]!="string"||e[t].length===0||e[t].length>512)throw ai("PROXY_TOKEN_BUDGET_INPUT","Token budget requires bounded provider, account, session and request identities");if(!Number.isSafeInteger(e.reservationTokens)||e.reservationTokens<=0)throw ai("PROXY_TOKEN_BUDGET_INPUT","Token reservation must be a positive safe integer");if(e.estimateProvenance!==void 0&&(typeof e.estimateProvenance!="string"||e.estimateProvenance.length>128))throw ai("PROXY_TOKEN_BUDGET_INPUT","Token estimate provenance must be bounded text")}var Wsn=class{constructor(e="supervisor",t=Date.now,r=Gsn,n=Bae){this.scope=e,this.now=t,this.maxKeys=r,this.maxLeases=n}scope;now;maxKeys;maxLeases;buckets=new Map;leases=new Map;bucket(e,t){const r=this.now();let n=this.buckets.get(e);if(!n){if(this.buckets.size>=this.maxKeys)for(const[o,s]of this.buckets)s.inFlightTokens===0&&r-s.lastTouched>=s.windowMs&&this.buckets.delete(o);if(this.buckets.size>=this.maxKeys)throw ai("PROXY_TOKEN_BUDGET_CAPACITY","Token budget scope capacity is full; retry after its window expires");n={chargedTokens:0,inFlightTokens:0,startedAt:r,windowMs:t,lastTouched:r},this.buckets.set(e,n)}return n.windowMs=Math.max(n.windowMs,t),r-n.startedAt>=n.windowMs&&(n.startedAt=r,n.chargedTokens=n.inFlightTokens,n.windowMs=t),n.lastTouched=r,n}reserve(e,t="local"){qsr(e);const r=qae(e.policy??{});if(this.leases.size>=this.maxLeases)throw ai("PROXY_TOKEN_BUDGET_CAPACITY","Token budget outstanding reservation capacity is full");const n=r.windowMs??JF,o=`account:${JSON.stringify([e.provider,e.accountKey])}`,s=`session:${JSON.stringify(e.sessionKey)}`,i=this.bucket(o,n),a=this.bucket(s,n),c=e.reservationTokens;if(r.maxInFlightTokens!==void 0&&c>r.maxInFlightTokens-i.inFlightTokens||r.accountWindowTokens!==void 0&&c>r.accountWindowTokens-i.chargedTokens||r.sessionWindowTokens!==void 0&&c>r.sessionWindowTokens-a.chargedTokens)throw ai("PROXY_TOKEN_BUDGET_EXCEEDED","Token budget would be exceeded before upstream dispatch");if(c>Number.MAX_SAFE_INTEGER-Math.max(i.chargedTokens,a.chargedTokens))throw ai("PROXY_TOKEN_BUDGET_CAPACITY","Token accounting integer capacity is full");i.chargedTokens+=c,i.inFlightTokens+=c,a.chargedTokens+=c,a.inFlightTokens+=c;const l={scope:this.scope,reservationTokens:c,accountChargedTokens:i.chargedTokens,accountInFlightTokens:i.inFlightTokens,sessionChargedTokens:a.chargedTokens,sessionInFlightTokens:a.inFlightTokens,windowMs:n,estimateProvenance:e.estimateProvenance??"caller_estimate_input_plus_max_output"},u=dn();return this.leases.set(u,{owner:t,accountKey:o,sessionKey:s,estimate:c,snapshot:l}),{leaseId:u,snapshot:{...l}}}settle(e,t,r,n=!1){const o=this.leases.get(e);if(!o)return;if(o.owner!==t)throw ai("PROXY_TOKEN_BUDGET_OWNER","Token budget lease belongs to another worker");if(r!==void 0&&(!Number.isSafeInteger(r)||r<0))throw ai("PROXY_TOKEN_BUDGET_USAGE","Reported token usage must be a nonnegative safe integer");const s=n?0:r??o.estimate,i=this.bucket(o.accountKey,o.snapshot.windowMs),a=this.bucket(o.sessionKey,o.snapshot.windowMs);for(const c of[i,a])c.chargedTokens=Math.min(Number.MAX_SAFE_INTEGER,Math.max(0,c.chargedTokens+s-o.estimate)),c.inFlightTokens=Math.max(0,c.inFlightTokens-o.estimate);return this.leases.delete(e),{...o.snapshot,accountChargedTokens:i.chargedTokens,accountInFlightTokens:i.inFlightTokens,sessionChargedTokens:a.chargedTokens,sessionInFlightTokens:a.inFlightTokens,settlement:n?"cancelled_before_dispatch":r===void 0?"estimate_retained":"provider_reported"}}ownerExited(e){for(const[t,r]of this.leases)r.owner===e&&this.settle(t,e)}},Gae=new Wsn(process.env.NEUROLINK_PROXY_SOCKET_WORKER==="1"?"process":"supervisor"),fm=new Map,lx=new Set;function Gsr(e){if(lx.size>=Bae){const t=lx.values().next().value;t&&lx.delete(t)}lx.add(e)}var jsr=!1;function Ksn(){jsr||(jsr=!0,process.on("message",e=>{if(!e||typeof e!="object"||e.type!=="proxy-budget:response")return;const t=e,r=fm.get(t.rpcId);if(!r){lx.delete(t.rpcId)&&t.ok&&typeof t.leaseId=="string"&&t.leaseId.length<=128&&process.connected&&process.send&&process.send({type:"proxy-budget:request",rpcId:dn(),pid:process.pid,generation:Number(process.env.NEUROLINK_PROXY_WORKER_GENERATION),action:"cancel",leaseId:t.leaseId},()=>{});return}fm.delete(t.rpcId),clearTimeout(r.timer),t.ok?r.resolve(t):r.reject(ai(t.errorCode??"PROXY_TOKEN_BUDGET_UNAVAILABLE",t.error??"Token budget coordinator refused the request"))}),process.on("disconnect",()=>{for(const e of fm.values())clearTimeout(e.timer),e.reject(ai("PROXY_TOKEN_BUDGET_UNAVAILABLE","Token budget supervisor disconnected"));fm.clear()}))}function jae(e){return Ksn(),new Promise((t,r)=>{if(!process.connected||!process.send||fm.size>=Bae){r(ai("PROXY_TOKEN_BUDGET_UNAVAILABLE","Token budget supervisor IPC is unavailable"));return}const n=dn(),o=setTimeout(()=>{fm.delete(n),e.action==="reserve"&&Gsr(n),r(ai("PROXY_TOKEN_BUDGET_UNAVAILABLE","Token budget supervisor response timed out; dispatch refused"))},jsn);fm.set(n,{resolve:t,reject:r,timer:o});const s=i=>{!i||!fm.has(n)||(clearTimeout(o),fm.delete(n),e.action==="reserve"&&Gsr(n),r(ai("PROXY_TOKEN_BUDGET_UNAVAILABLE","Token budget IPC send failed")))};try{process.send({...e,type:"proxy-budget:request",rpcId:n,pid:process.pid,generation:Number(process.env.NEUROLINK_PROXY_WORKER_GENERATION)},s)}catch(i){s(i instanceof Error?i:new Error("IPC failed"))}})}async function Hae(e){const t=Hsn(e.policy);if(!Vsn(t))return{leaseId:"disabled",snapshot:{scope:"disabled",reservationTokens:0,accountChargedTokens:0,accountInFlightTokens:0,sessionChargedTokens:0,sessionInFlightTokens:0,windowMs:t?.windowMs??JF,estimateProvenance:"disabled"},settle:async()=>{},cancelBeforeDispatch:async()=>{}};qsr(e);const r=process.env.NEUROLINK_PROXY_SOCKET_WORKER==="1",n={...e,policy:t},o=r?await jae({action:"reserve",reservation:n}):Gae.reserve(n,"local");if(!o.leaseId||!o.snapshot)throw ai("PROXY_TOKEN_BUDGET_UNAVAILABLE","Token budget supervisor returned incomplete reservation proof");const s=o.leaseId;let i=!1;const a={leaseId:s,snapshot:{...o.snapshot,scope:r?"supervisor":"process"},settle:async c=>{if(i)return;const l=r?(await jae({action:"settle",leaseId:s,actualTotalTokens:c})).snapshot:Gae.settle(s,"local",c);i=!0,l&&(a.snapshot={...l,scope:r?"supervisor":"process"})},cancelBeforeDispatch:async()=>{if(i)return;const c=r?(await jae({action:"cancel",leaseId:s})).snapshot:Gae.settle(s,"local",void 0,!0);i=!0,c&&(a.snapshot={...c,scope:r?"supervisor":"process"})}};return a}async function Vae(e,t){try{await e.settle(t)}catch{e.snapshot={...e.snapshot,settlement:"unconfirmed"}}}Ut(),JD(),Wr(),Xt();var Hsr=new Map;function Wae(e){return Hsr.get(e)??Hsr.get(e.replace(/:codex-fallback$/,""))}function xw(e){const t=typeof e.requestId=="string"?Wae(e.requestId):void 0,r=lt.getSpanContext(fr.active()),n=typeof e.traceId=="string"&&typeof e.spanId=="string"?{traceId:e.traceId,spanId:e.spanId}:t??r;if(!n)return;const o=typeof e.traceFlags=="number"&&Number.isInteger(e.traceFlags)&&e.traceFlags>=0&&e.traceFlags<=255?e.traceFlags:t?.traceId===n.traceId?t.traceFlags:r?.traceId===n.traceId?r.traceFlags:0,s={...n,traceFlags:o};return z$(s)?{traceId:s.traceId,spanId:s.spanId,traceFlags:o}:void 0}function Kae(e){const t=xw(e);return t?lt.setSpanContext(q$,t):fr.active()}var Jsn=async()=>{},fhn=globalThis.crypto,ghn=globalThis.ReadableStream||class{},Vsr=Jsn,yhn=globalThis.URL,vhn=globalThis.URLSearchParams,Jae=e=>{try{return JSON.stringify(e,null,2)}catch{return String(e)}};Jae.custom=Symbol.for("nodejs.util.inspect.custom"),Jae.colors={},Jae.styles={};var Ysn=globalThis.TextDecoder,Wsr=globalThis.TextEncoder,Thn=globalThis.performance||{now:()=>Date.now()},whn=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 Wsr().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 Wsr().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 Ysn().decode(this)}},Xsn=e=>({[Symbol.toPrimitive](){return e},ref(){return this},unref(){return this},hasRef(){return!1},refresh(){return this},close(){}}),Zsn=(...e)=>Xsn(globalThis.setTimeout(...e)),bhn=globalThis.clearTimeout,Shn=globalThis.clearInterval,Iw={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};lW(),Mn(),det();var _hn=globalThis.crypto,Qsn=class{constructor(){throw new Error("[NeuroLink:browser] Node HTTP agents require a server runtime")}},Chn=globalThis.ReadableStream||class{},ein=()=>({}),khn=globalThis.URL,Ahn=globalThis.URLSearchParams,Yae=e=>{try{return JSON.stringify(e,null,2)}catch{return String(e)}};Yae.custom=Symbol.for("nodejs.util.inspect.custom"),Yae.colors={},Yae.styles={};var tin=globalThis.TextDecoder,Ksr=globalThis.TextEncoder,xhn=globalThis.performance||{now:()=>Date.now()},Ihn=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 Ksr().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 Ksr().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 tin().decode(this)}},Mhn=globalThis.clearTimeout,Phn=globalThis.clearInterval;JD(),J4(),lW();var rin={serializeRequest(){throw new Error("[NeuroLink:browser] proxy OTLP log transport requires a server runtime")}},nin=WD(K4),oin=64*1024,sin=5,iin=new Set([429,502,503,504]),ain=new Set(["ECONNRESET","ECONNREFUSED","EPIPE","ETIMEDOUT","EAI_AGAIN","ENOTFOUND","ENETUNREACH","EHOSTUNREACH"]),vo=class extends Error{constructor(e,t=!1,r){super(e),this.retryable=t,this.retryAfterMs=r,this.name="ProxyOtlpResponseError"}retryable;retryAfterMs};function cin(e){return e instanceof vo&&e.retryable?e.retryAfterMs??0:void 0}function Jsr(e){return process.env[`OTEL_EXPORTER_OTLP_LOGS_${e}`]?.trim()||process.env[`OTEL_EXPORTER_OTLP_${e}`]?.trim()||void 0}function Xae(e){const t=Jsr(e);if(t)try{return li(t)}catch{throw new Error(`Proxy OTLP ${e} file could not be read`)}}function lin(e){if(!e)return;if(/^\d+$/.test(e.trim()))return Number(e)*1e3;const t=Date.parse(e);return Number.isFinite(t)?Math.max(0,t-Date.now()):void 0}function uin(e){let t;try{t=JSON.parse(e.toString("utf8"))}catch{throw new vo("OTLP response JSON is empty or malformed")}if(!t||typeof t!="object"||Array.isArray(t))throw new vo("OTLP response must be a JSON object");if(Object.keys(t).some(a=>a!=="partialSuccess"&&a!=="partial_success"))throw new vo("OTLP response has unexpected fields");if("partialSuccess"in t&&"partial_success"in t)throw new vo("OTLP response has ambiguous field aliases");const r="partialSuccess"in t?t.partialSuccess:"partial_success"in t?t.partial_success:void 0;if(r==null)return;if(typeof r!="object"||Array.isArray(r))throw new vo("OTLP partial success response is malformed");const n=new Set(["rejectedLogRecords","rejected_log_records","errorMessage","error_message"]);if(Object.keys(r).some(a=>!n.has(a)))throw new vo("OTLP partial success response has unexpected fields");if("rejectedLogRecords"in r&&"rejected_log_records"in r||"errorMessage"in r&&"error_message"in r)throw new vo("OTLP partial success has ambiguous field aliases");const o="errorMessage"in r?r.errorMessage:"error_message"in r?r.error_message:void 0;if(o!=null&&typeof o!="string")throw new vo("OTLP partial success response is malformed");const s="rejectedLogRecords"in r?r.rejectedLogRecords:"rejected_log_records"in r?r.rejected_log_records:0;if(s===null||s===0||s==="0")return;const i=typeof s=="string"&&/^\d+$/.test(s)||typeof s=="number"&&Number.isSafeInteger(s)&&s>=0?BigInt(s):void 0;if(i===void 0||i>9223372036854775807n)throw new vo("OTLP rejected record count is malformed");if(i>0n)throw new vo("OTLP partial success rejected log records")}function din(e,t){let r;try{r=new URL(e)}catch{throw new Error("Proxy OTLP endpoint is invalid")}if(!new Set(["http:","https:"]).has(r.protocol))throw new Error("Proxy OTLP endpoint must use HTTP or HTTPS");if(r.username||r.password)throw new Error("Proxy OTLP endpoint credentials must use OTLP headers");const n=Jsr("COMPRESSION")??"none";if(n!=="none"&&n!=="gzip")throw new Error("Proxy OTLP compression must be none or gzip");const o={};try{for(const h of[process.env.OTEL_EXPORTER_OTLP_HEADERS,process.env.OTEL_EXPORTER_OTLP_LOGS_HEADERS])for(const[f,g]of Object.entries(_ht(h)))set(f),iet(f,g),o[f.toLowerCase()]=g}catch{throw new Error("Proxy OTLP headers are invalid")}o["content-type"]="application/json",o.accept="application/json",o["accept-encoding"]="identity",delete o["content-encoding"],n==="gzip"&&(o["content-encoding"]="gzip");const s={ca:Xae("CERTIFICATE"),cert:Xae("CLIENT_CERTIFICATE"),key:Xae("CLIENT_KEY")};if(!!s.cert!=!!s.key)throw new Error("Proxy OTLP client certificate and key must be set together");const i=r.protocol==="https:"?new Qsn({keepAlive:!0,maxSockets:30,...s}):new oet({keepAlive:!0,maxSockets:30}),a=r.protocol==="https:"?ein:aet;let c=!1;const l=new Set,u=new Set,d=(h,f)=>new Promise((g,y)=>{let v=!1;const w=a(r,{method:"POST",agent:i,signal:f,headers:{...o,"content-length":String(h.byteLength)}},E=>{v=!0;const _=E.statusCode??0,C=M=>{y(M),E.destroy()};if(_!==200){C(new vo(`OTLP HTTP ${_}`,iin.has(_),lin(E.headers["retry-after"])));return}const A=E.headers["content-encoding"];if(A&&A!=="identity"){C(new vo("OTLP response encoding is unsupported"));return}const k=E.headers["content-type"];if(k&&k.split(";",1)[0].trim().toLowerCase()!=="application/json"){C(new vo("OTLP response content type is not JSON"));return}const R=[];let I=0;E.on("data",M=>{if(I+=M.length,I>oin){C(new vo("OTLP response exceeds 64 KiB limit"));return}R.push(M)}),E.on("aborted",()=>y(new vo("OTLP success response was interrupted"))),E.on("error",()=>y(new vo("OTLP success response could not be read"))),E.on("end",()=>{try{uin(Buffer.concat(R)),g()}catch(M){y(M)}})});w.on("error",E=>y(new vo(f.aborted?"OTLP export deadline exceeded":"OTLP transport failed",!v&&(f.aborted||ain.has(E.code??""))))),w.end(h)}),m=async h=>{const f=new AbortController;u.add(f);const g=Date.now()+t,y=setTimeout(()=>f.abort(),t);y.unref();try{const v=rin.serializeRequest(h);if(!v)throw new vo("OTLP serialization produced no payload");const w=n==="gzip"?await nin(v):v;let E=0;for(;!f.signal.aborted&&Date.now()<g;){E++;try{await d(w,f.signal);return}catch(_){if(!(_ instanceof vo)||!_.retryable)throw _;if(E>=sin)throw new vo("OTLP retry attempt limit reached",!0,_.retryAfterMs);const C=Math.min(5e3,1e3*2**Math.min(E-1,3)),A=Math.max(_.retryAfterMs??0,C*(.8+Math.random()*.4));if(A>=g-Date.now())throw new vo("OTLP retry exceeds export deadline",!0,A);await Zsn(A,void 0,{signal:f.signal})}}throw new vo("OTLP export deadline exceeded",!0)}catch(v){throw v instanceof vo?v:new vo(f.signal.aborted?"OTLP export deadline exceeded":"OTLP export failed",f.signal.aborted)}finally{clearTimeout(y),u.delete(f)}};return{abortPending(){c=!0;for(const h of u)h.abort();i.destroy()},export(h,f){if(c){f({code:Su.FAILED,error:new Error("OTLP transport is shut down")});return}const g=m(h).then(()=>f({code:Su.SUCCESS}),y=>f({code:Su.FAILED,error:y}));l.add(g),g.finally(()=>l.delete(g)).catch(()=>{})},async shutdown(){c=!0,await Promise.allSettled(l),i.destroy()}}}CH(),Mht(),Ut(),zt(),Or(),Wr(),JD(),J4();var Dhn=1024*1024,Ohn=8*1024*1024,Nhn=WD(K4);function Ysr(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 Rw,YF=[],ny=new Map,Xsr=new WeakMap,Zsr=new Set,XF=!1,min=128*1024,Qsr=3e4,Zae=Qsr+1e3,pin=2e4,eir=12e4,hin=new Set(["console","runtime","telemetry_delivery"]);function fin(e){try{return 512+Buffer.byteLength(typeof e.body=="string"?e.body:JSON.stringify(e.body)??"","utf8")+Buffer.byteLength(JSON.stringify(e.attributes),"utf8")}catch{return 1/0}}var gs={attempted:0,transportAcknowledged:0,exportUnconfirmed:0,rejected:0,partial:0,pending:0,pendingBytes:0,highWaterPending:0,highWaterBytes:0,maxPending:64,maxPendingBytes:32*1024*1024};function tl(){return process.env.NEUROLINK_PROXY_LOG_SINK==="otel"}function ZF(e,t,r,n){const o=new Set,s=new WeakMap,i=new WeakMap,a=new Set,c=r==="metadata"||r==="indexes"?eir:0,l=new Set,u=new Set,d={attempted:0,submitted:0,transportAcknowledged:0,exportUnconfirmed:0,dropped:0,outstanding:0,outstandingBytes:0,highWaterBytes:0,byteLimitDrops:0,retryingRecords:0,retriedBatches:0,retentionExpired:0,lastTransientFailureAt:void 0,lastAcknowledgedAt:void 0,lastFailureAt:void 0,highWaterOutstanding:0,recentFailures:[],failureHistoryEvicted:0},m=[];let h=!1;const f=(C,A,k)=>{const R=(M,D)=>{const U=M.attributes[D];return typeof U=="string"?U.slice(0,128):void 0},I={id:dn(),at:new Date().toISOString(),reason:A,...k?{error:lr(k.message).slice(0,256)}:{},records:C.slice(0,64).map(M=>({eventId:R(M,"proxy.event_id")??"unavailable",kind:R(M,"proxy.record_kind"),requestId:R(M,"request.id"),captureId:R(M,"body.capture_id")}))};d.recentFailures.length===16&&(d.recentFailures.shift(),d.failureHistoryEvicted++),d.recentFailures.push(I),C.some(M=>M.attributes["proxy.record_kind"]!=="telemetry_delivery")&&(m.length===16&&m.shift(),m.push(I))},g=()=>{h||!m.length||XF||(h=!0,queueMicrotask(()=>{h=!1;for(const C of m.splice(0))Mw("telemetry_delivery",{queue:r,...C})}))},y=din(e,Qsr),v={export(C,A){const k=performance.now();for(const V of C){const G=V.attributes["body.capture_id"],Y=typeof G=="string"?ny.get(G):void 0;Y&&(Y.maxChunkQueueWaitMs=Math.max(Y.maxChunkQueueWaitMs??0,k-(s.get(V)??k)))}let R=!1,I=!1,M,D,U,P=0;const F=Math.min(...C.map(V=>s.get(V)??k))+c,N=()=>{M&&U&&z(U)};a.add(N);const z=V=>{if(!R){R=!0,clearTimeout(D),clearTimeout(M),a.delete(N),I&&(d.retryingRecords-=C.length),d.outstanding-=C.length,V.code===Su.SUCCESS?(d.transportAcknowledged+=C.length,d.lastAcknowledgedAt=new Date().toISOString(),g()):(d.exportUnconfirmed+=C.length,d.lastFailureAt=new Date().toISOString(),f(C,"export_unconfirmed",V.error));for(const G of C){o.delete(G),d.outstandingBytes-=i.get(G)??0;const Y=G.attributes?.["body.capture_id"],se=typeof Y=="string"?ny.get(Y):void 0;if(se){se.maxChunkExportMs=Math.max(se.maxChunkExportMs??0,performance.now()-k);const Z=Xsr.get(se);V.code===Su.SUCCESS&&(Z===void 0||Date.now()<Z)?se.acknowledged++:se.unconfirmed++,se.notify?.()}}for(const G of l)G();for(const G of u)G();A(V)}},B=()=>{if(M=void 0,c&&performance.now()>=F){d.retentionExpired+=C.length,z({code:Su.FAILED,error:new Error("OTLP metadata retention budget exceeded")});return}P++,P>1&&d.retriedBatches++;let V=!1;const G=Y=>{if(V||R)return;V=!0,clearTimeout(D);const se=Y.code===Su.FAILED?cin(Y.error):void 0;if(c&&se!==void 0&&!XF){d.lastTransientFailureAt=new Date().toISOString();const Z=Math.max(se,Math.min(1e4,1e3*2**Math.min(P-1,4))*(.8+Math.random()*.4));if(performance.now()+Z<F){I||(I=!0,d.retryingRecords+=C.length),U=Y,M=setTimeout(B,Z),M.unref();return}d.retentionExpired+=C.length}z(Y)};D=setTimeout(()=>G({code:Su.FAILED,error:new Error("OTLP export callback deadline exceeded")}),Zae),D.unref();try{y.export(C,G)}catch(Y){G({code:Su.FAILED,error:Y instanceof Error?Y:new Error(String(Y))})}};B()},shutdown:()=>y.shutdown()},w=new dW(v,{maxQueueSize:t,maxExportBatchSize:64,scheduledDelayMillis:r==="bodies"?25:1e3,exportTimeoutMillis:c+Zae+1e3}),E={onEmit(C){C.attributes["proxy.event_id"]??=dn(),d.attempted++;const A=C.attributes?.["body.capture_id"],k=typeof A=="string"?ny.get(A):void 0;k&&k.emitted++;const R=fin(C);if(d.outstanding>=t||d.outstandingBytes+R>n){d.dropped++,d.outstandingBytes+R>n&&d.byteLimitDrops++,f([C],"queue_full"),k&&(k.dropped++,k.notify?.());return}d.submitted++,d.outstanding++,d.outstandingBytes+=R,d.highWaterBytes=Math.max(d.highWaterBytes,d.outstandingBytes),i.set(C,R),o.add(C),s.set(C,performance.now()),d.highWaterOutstanding=Math.max(d.highWaterOutstanding,d.outstanding),w.onEmit(C)},forceFlush:async()=>{const C=new Set(o);try{await w.forceFlush()}finally{await new Promise(A=>{const k=()=>{[...C].some(R=>o.has(R))||(u.delete(k),A())};u.add(k),k()})}},shutdown:async()=>{try{await E.forceFlush()}finally{await w.shutdown()}}};return{state:d,processor:E,capacity:t,byteCapacity:n,retentionMs:c,kind:r,waitForCapacity:C=>new Promise(A=>{const k=setTimeout(()=>R(!1),Math.max(0,C-Date.now()));k.unref?.();const R=M=>{clearTimeout(k),l.delete(I),A(M)},I=()=>{Date.now()>=C?R(!1):d.outstanding<t&&R(!0)};l.add(I),I()}),abortPending:()=>y.abortPending(),stopRetention:()=>{for(const C of a)C()},oldestOutstandingAgeMs:()=>{let C=performance.now();for(const A of o)C=Math.min(C,s.get(A)??C);return o.size?Math.max(0,performance.now()-C):0}}}async function gin(e,t,r){gs.attempted++;const n=Buffer.byteLength(t,"utf8");if(!Rw||XF||ny.has(e)||gs.pending>=gs.maxPending||gs.pendingBytes+n>gs.maxPendingBytes)return gs.rejected++,{status:"rejected",acknowledgedChunks:0,unconfirmedChunks:0,droppedChunks:0,reason:ny.has(e)?"body_capture_id_in_use":!Rw||XF?"body_exporter_unavailable":"body_publication_queue_full"};gs.pending++,gs.pendingBytes+=n,gs.highWaterPending=Math.max(gs.highWaterPending,gs.pending),gs.highWaterBytes=Math.max(gs.highWaterBytes,gs.pendingBytes);const o={acknowledged:0,unconfirmed:0,dropped:0,emitted:0};ny.set(e,o);let s;const i=(async()=>{const a=YF.find(E=>E.kind==="bodies");if(!a)return{status:"rejected",acknowledgedChunks:0,unconfirmedChunks:0,droppedChunks:0,reason:"body_exporter_unavailable"};const c=performance.now(),l=Date.now()+pin;Xsr.set(o,l);const u=Ysr(t,min);let d=0,m;try{for(let E=0;E<u.length;E++){for(;a.state.outstanding>=a.capacity;){const _=performance.now(),C=await a.waitForCapacity(l);if(d+=performance.now()-_,!C){m="body_publication_deadline";break}}if(Date.now()>=l){m="body_publication_deadline";break}r(u[E],E,u.length),E%4===3&&await Vsr()}}catch{m="body_publication_failed"}const h=new Promise(E=>{const _=()=>{o.acknowledged+o.unconfirmed+o.dropped>=o.emitted&&(o.notify=void 0,E())};o.notify=_,_()});let f;const g=await Promise.race([h.then(()=>!0),new Promise(E=>{f=setTimeout(()=>E(!1),Math.max(0,l-Date.now())),f.unref?.()})]).finally(()=>clearTimeout(f));g||(s=h),(!g||Date.now()>=l)&&(m??="body_publication_deadline"),!m&&o.unconfirmed?m="body_export_unconfirmed":!m&&o.dropped&&(m="body_export_queue_full");const y=Math.max(0,o.emitted-o.acknowledged-o.unconfirmed-o.dropped),v=o.unconfirmed+y;return{status:o.emitted===0?"rejected":o.dropped||o.emitted!==u.length?"partial":v?"export_unconfirmed":"transport_acknowledged",expectedChunks:u.length,acknowledgedChunks:o.acknowledged,unconfirmedChunks:v,droppedChunks:o.dropped,notSubmittedChunks:u.length-o.emitted,publicationMs:performance.now()-c,capacityWaitMs:d,maxChunkQueueWaitMs:o.maxChunkQueueWaitMs??0,maxChunkExportMs:o.maxChunkExportMs??0,...m?{reason:m}:{}}})();Zsr.add(i);try{const a=await i;return a.status==="transport_acknowledged"?gs.transportAcknowledged++:a.status==="export_unconfirmed"?gs.exportUnconfirmed++:a.status==="rejected"?gs.rejected++:gs.partial++,a}finally{Zsr.delete(i);const a=()=>{ny.delete(e),gs.pending--,gs.pendingBytes-=n};s?s.then(a,a):a()}}function tir(e="worker"){if(!tl())return;if(Rw)return Rw;const t=process.env.OTEL_EXPORTER_OTLP_LOGS_ENDPOINT??(process.env.OTEL_EXPORTER_OTLP_ENDPOINT?`${process.env.OTEL_EXPORTER_OTLP_ENDPOINT.replace(/\/$/,"")}/v1/logs`:void 0);if(!t)throw new Error("OTel-only proxy logging requires an OTLP endpoint");const r=process.env.NEUROLINK_PROXY_OTLP_BODIES_ENDPOINT??t;for(const a of[t,r]){const c=new URL(a);if(!["http:","https:"].includes(c.protocol))throw new Error("Proxy OTLP logs endpoint must use HTTP or HTTPS");const l=["localhost","127.0.0.1","[::1]"].includes(c.hostname);if(c.protocol==="http:"&&!l)throw new Error("Proxy OTLP logs require HTTPS for non-loopback collectors")}const n=ZF(t,2048,"metadata",8*1024*1024),o=ZF(r,256,"bodies",40*1024*1024),s=ZF(t,512,"diagnostics",2*1024*1024),i=ZF(t,1024,"indexes",8*1024*1024);return YF.push(n,o,s,i),Rw=new uW({forceFlushTimeoutMillis:eir+Zae+2e3,resource:WM({"service.name":process.env.OTEL_SERVICE_NAME??"neurolink-proxy","service.instance.id":`${e}-${process.pid}`,"process.pid":process.pid,"proxy.process.role":e}),processors:[{onEmit(a,c){(a.attributes?.["proxy.record_kind"]==="body"?o:a.attributes?.["proxy.record_kind"]==="body_capture_index"?i:a.attributes?.["proxy.lifecycle.event"]==="runtime_sample"||hin.has(String(a.attributes?.["proxy.record_kind"]))?s:n).processor.onEmit(a,c)},forceFlush:async()=>{await Promise.all(YF.map(a=>a.processor.forceFlush()))},shutdown:async()=>{await Promise.all(YF.map(a=>a.processor.shutdown()))}}]}),Rw}function Mw(e,t){if(tl())try{const r=typeof t.requestId=="string"&&!t.traceId?Wae(t.requestId):void 0,n=r?{...t,...r}:t;tir()?.getLogger("neurolink-proxy-events").emit({context:Kae(n),severityNumber:Iw.INFO,severityText:"INFO",body:JSON.stringify(n),attributes:{"proxy.record_kind":e,"event.name":`proxy.${e}`,...typeof t.requestId=="string"?{"request.id":t.requestId}:{},...typeof t.event=="string"?{"proxy.lifecycle.event":t.event}:{}}})}catch{yin++}}var yin=0;Wr();var rir=1024,nir=5*6e4;function vin(e={}){const t=e.now??(()=>performance.now()),r=e.bytesPerMinute?.trim(),n=r?Number(r):null,o=n!==null&&(!Number.isSafeInteger(n)||n<=0),s=new Map;let i=n??1/0,a=t(),c=0,l=0,u=0,d=0,m=0;const h=()=>{const f=t();n!==null&&!o&&(i=Math.min(n,i+Math.max(0,f-a)*n/6e4)),a=f;for(const[g,y]of s)y.expiresAt<=f&&s.delete(g)};return{snapshot(){return h(),{deduplicationEnabled:e.deduplicate!==!1,maxReferences:rir,referenceTtlMs:nir,references:s.size,byteBudgetPerMinute:o?null:n,invalidByteBudget:o,availableBytes:n===null||o?null:Math.floor(i),submittedBytes:c,deduplicatedCaptures:l,deduplicatedBytes:u,policyExcludedCaptures:d,policyExcludedBytes:m}},async publish(f,g,y){if(h(),g.redactedBody===void 0)return{};const v=Buffer.byteLength(g.redactedBody,"utf8"),w=e.deduplicate!==!1&&g.bodySha256&&f.captureId?JSON.stringify([f.requestId,g.bodySha256,v]):void 0,E=w?s.get(w):void 0;if(E&&E.reference.captureId!==f.captureId&&await E.acknowledged&&E.expiresAt>t())return l++,u+=v,{delivery:{status:"reference",reason:"identical_redacted_payload"},reference:{...E.reference}};if(h(),o||v>i)return d++,m+=v,{delivery:{status:"policy_excluded",reason:o?"body_byte_budget_invalid":"body_byte_budget_exhausted"}};i-=v,c+=v;let _=()=>{};const C=w&&f.captureId&&g.bodySha256?{reference:{captureId:f.captureId,requestId:f.requestId,bodySha256:g.bodySha256,redactedBodyBytes:v,exportedAt:""},expiresAt:t()+nir,acknowledged:new Promise(k=>{_=k})}:void 0;if(w&&C){if(s.size>=rir){const k=s.keys().next().value;k!==void 0&&s.delete(k)}s.set(w,C)}let A=!1;try{const k=await y();return A=k?.status==="transport_acknowledged",C&&A&&(C.reference.exportedAt=new Date().toISOString()),{delivery:k}}finally{_(A),w&&!A&&s.get(w)===C&&s.delete(w)}}}}hr(),Ri(),Ja(),on(),Wo();var Lhn=globalThis.crypto,Fhn=globalThis.ReadableStream||class{},$hn=globalThis.URL,Uhn=globalThis.URLSearchParams,Qae=e=>{try{return JSON.stringify(e,null,2)}catch{return String(e)}};Qae.custom=Symbol.for("nodejs.util.inspect.custom"),Qae.colors={},Qae.styles={};var Tin=globalThis.TextDecoder,oir=globalThis.TextEncoder,Bhn=globalThis.performance||{now:()=>Date.now()},win=class{},zhn=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 oir().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 oir().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 Tin().decode(this)}},Ghn=globalThis.clearTimeout,jhn=globalThis.clearInterval,ux=64,QF=32*1024*1024,sir=64,iir=32*1024*1024,Ein=2e4,bin=16*1024*1024,air=2e4,oy,Sin,Zp=0,_in=0,Jt={attempted:0,completed:0,rejected:0,failed:0,pending:0,pendingBytes:0,maxPending:ux,maxPendingBytes:QF,highWaterPending:0,highWaterBytes:0,waiting:0,waitingBytes:0,maxWaiting:sir,maxWaitingBytes:iir,highWaterWaiting:0,highWaterWaitingBytes:0,admissionWaits:0,admissionTimeouts:0,rejectionReasons:{}},dx=new Map,cir=new Map,sy=[],e$;function lir(e){return Date.now()<Zp||Jt.pending>=ux||Jt.pendingBytes+e>QF?!1:(Jt.pending+=1,Jt.pendingBytes+=e,Jt.highWaterPending=Math.max(Jt.highWaterPending,Jt.pending),Jt.highWaterBytes=Math.max(Jt.highWaterBytes,Jt.pendingBytes),!0)}function ece(){if(sy.length){if(Date.now()<Zp){e$||(e$=setTimeout(()=>{e$=void 0,ece()},Math.max(1,Zp-Date.now())),e$.unref?.());return}for(let e=0;e<sy.length&&!(Jt.pending>=ux);){const t=sy[e];if(!lir(t.bytes)){e+=1;continue}sy.splice(e,1),clearTimeout(t.timer),Jt.waiting-=1,Jt.waitingBytes-=t.bytes,t.resolve("admitted")}}}function Cin(e){return Jt.waiting>=sir||Jt.waitingBytes+e>iir?Promise.resolve("queue_full"):(Jt.admissionWaits+=1,Jt.waiting+=1,Jt.waitingBytes+=e,Jt.highWaterWaiting=Math.max(Jt.highWaterWaiting,Jt.waiting),Jt.highWaterWaitingBytes=Math.max(Jt.highWaterWaitingBytes,Jt.waitingBytes),new Promise(t=>{const r=setTimeout(()=>{const n=sy.findIndex(o=>o.timer===r);n<0||(sy.splice(n,1),Jt.waiting-=1,Jt.waitingBytes-=e,Jt.admissionTimeouts+=1,t("timeout"),ece())},Ein);r.unref?.(),sy.push({bytes:e,queuedAt:Date.now(),resolve:t,timer:r})}))}function uir(e){Jt.pending-=1,Jt.pendingBytes-=e,ece()}function kin(e,t){const r=[e],n=new Set;let o=0,s=0;for(;r.length;){if(++s>1e5)throw new Error("body_capture_traversal_limit");if(o>t)return o;const i=r.pop();if(typeof i=="string"){o+=16+i.length*2;continue}if(o+=16,!(!i||typeof i!="object")){if(n.has(i))throw new Error("body_capture_unsupported_value");if(n.add(i),!Array.isArray(i)&&Object.getPrototypeOf(i)!==Object.prototype&&Object.getPrototypeOf(i)!==null)throw new Error("body_capture_unsupported_value");for(const a of Object.keys(i)){o+=16+a.length*2;const c=Object.getOwnPropertyDescriptor(i,a);if(!c||c.get||c.set)throw new Error("body_capture_unsupported_value");if(r.push(c.value),r.length>1e5)throw new Error("body_capture_traversal_limit");if(o>t)return o}}}return o}function tce(e,t){const r=dx.get(e);r&&(dx.delete(e),clearTimeout(r.timer),r.resolve(t),dx.size||oy?.unref())}function rce(e,t){if(oy===e){oy=void 0,Zp=Date.now()+5e3;for(const r of dx.keys())tce(r,{error:t,stored:{bodyWriteFailed:!0}});e.terminate().catch(()=>{})}}function Ain(){if(oy)return oy;const e=new win(Sin??new URL("./bodyCaptureWorkerEntry.js",import.meta.url),{execArgv:process.execArgv.filter(t=>!t.startsWith("--input-type")),resourceLimits:{maxOldGenerationSizeMb:128}});return oy=e,e.on("message",t=>{oy===e&&tce(t.id,t.result)}),e.on("error",()=>rce(e,"body_worker_error")),e.on("exit",()=>rce(e,"body_worker_exit")),e.unref(),e}async function xin(e,t,r){Jt.attempted+=1;const n=Date.now(),o=t===null?QF:bin;let s,i;try{s=kin(e,o)}catch(d){s=1/0,i=d instanceof Error&&["body_capture_entry_too_large","body_capture_traversal_limit","body_capture_unsupported_value"].includes(d.message)?d.message:"body_capture_unsupported_value"}let a="queue_full";if(s<=o&&Date.now()>=Zp&&(a=lir(s)?"admitted":t===null?await Cin(s):"queue_full"),a!=="admitted"){Jt.rejected+=1;const d=s>o?i??"body_capture_entry_too_large":Date.now()<Zp?"body_worker_backoff":a==="timeout"?"body_capture_admission_timeout":"body_capture_queue_full";return Jt.lastError=d,Jt.lastRejectedAt=new Date().toISOString(),Jt.rejectionReasons[d]=(Jt.rejectionReasons[d]??0)+1,r({error:d,stored:{bodyWriteFailed:!0},admissionWaitMs:Math.max(0,Date.now()-n),admission:{limitingResource:s>o?"entry":Date.now()<Zp?"worker":Jt.pending>=ux?"captures":"bytes",estimatedBytes:Number.isFinite(s)?s:void 0,maxEntryBytes:o,pending:Jt.pending,pendingBytes:Jt.pendingBytes,maxPending:ux,maxPendingBytes:QF}})}const c=Date.now();let l;try{l=Ain()}catch{return Zp=Date.now()+5e3,uir(s),Jt.failed+=1,r({error:"body_worker_start_failed",stored:{bodyWriteFailed:!0}})}const u=++_in;return new Promise(d=>{const m=setTimeout(()=>rce(l,"body_worker_timeout"),air);m.unref(),dx.set(u,{timer:m,startedAt:Date.now(),resolve:h=>{cir.set(u,Date.now()),h.admissionWaitMs=Math.max(0,c-n),h.workerQueueWaitMs=Math.max(0,(h.queueWaitMs??0)-h.admissionWaitMs),r(h).catch(()=>{h.error??="body_capture_publication_failed"}).finally(()=>{cir.delete(u),uir(s),h.error||h.stored.bodyWriteFailed?Jt.failed+=1:Jt.completed+=1,h.error&&(Jt.lastError=h.error),d()})}}),l.ref();try{l.postMessage({id:u,entry:e,logDir:t,queuedAt:n})}catch{tce(u,{error:"body_capture_clone_failed",stored:{bodyWriteFailed:!0}})}})}j$();var dir=new Wx;function Pw(){return dir.getStore()}function mir(){return dir.getStore()!==void 0}Lr();var Dw=null,nce=!1,Iin=vin(),oce=new Set,sce=5e3,Hhn=air+2*sce,Rin=4096,t$=new Map,Min=E7,ice=()=>({attempted:0,written:0,inFlight:0,pending:0,dropped:0,writeTimeouts:0,unconfirmedWrites:0}),Pin={requests:ice(),attempts:ice(),debug:ice()};async function ace(e,t,r,n={}){const o=Pin[r];if(o.attempted+=1,o.pending+o.inFlight>=Rin){o.dropped+=1;return}o.pending+=1;const s=pir((t$.get(e)??Promise.resolve()).then(async()=>{o.pending-=1,o.inFlight+=1;const i=setTimeout(()=>{o.writeTimeouts+=1},sce);i.unref?.();try{await Min(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(t$.set(e,s),s.then(()=>{t$.get(e)===s&&t$.delete(e)}),n.waitForPersistence)return s;await Ct(s,sce,"Proxy metadata write remains pending").catch(()=>{})}function pir(e){return oce.add(e),e.then(()=>oce.delete(e),()=>oce.delete(e)),e}var Ow=null,hir=0,Din=10,Oin=16e3;function Nin(e){if(e.apiEquivalentCostUsd=null,e.apiEquivalentCacheSavingsUsd=null,e.pricingBasis="api_price_table",e.pricingProvider=e.provider??"openai-compatible",e.usageOwnerRequestId&&e.usageOwnerRequestId!==e.requestId){e.pricingStatus="owned_by_child";return}const t=e.inputTokens,r=e.outputTokens,n=e.cacheReadTokens??0,o=e.cacheCreationTokens??0;if(t===void 0||r===void 0||!Number.isFinite(t)||t<0||!Number.isFinite(r)||r<0||!Number.isFinite(n)||n<0||!Number.isFinite(o)||o<0||e.inputIncludesCachedTokens===!0&&n+o>t||e.inputIncludesCachedTokens===!0&&(e.cacheReadTokensObserved===!1||e.cacheCreationTokensObserved===!1)){e.pricingStatus="usage_incomplete";return}if(!wd(e.pricingProvider,e.model)){e.pricingStatus="unavailable";return}if(!t4(e.pricingProvider,e.model)){e.pricingStatus="inferred";return}const s=Yp({inputTokens:t,outputTokens:r,cacheReadTokens:n,cacheCreationTokens:o,inputIncludesCachedTokens:e.inputIncludesCachedTokens});e.pricingStatus="exact",e.apiEquivalentCostUsd=xi(e.pricingProvider,e.model,s);const i=xi(e.pricingProvider,e.model,{...s,input:s.input+(s.cacheReadTokens??0),cacheReadTokens:0});e.apiEquivalentCacheSavingsUsd=Math.max(0,Math.round((i-e.apiEquivalentCostUsd)*1e6)/1e6)}async function Nw(e){if(Object.assign(e,ax(e.requestId)),Nin(e),!e.traceId||e.traceFlags===void 0){const n=xw(e);n&&Object.assign(e,n)}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",!Tsn(e)||!nce||!Dw&&!tl())return;if(tl()){await gir(e);return}const t=At(Dw,`proxy-${new Date().toISOString().split("T")[0]}.jsonl`),r=JSON.stringify(e)+`
2343
2343
  `;try{await ace(t,r,"requests")}catch{}gir(e)}async function cce(e){if(!e.traceId||e.traceFlags===void 0){const n=xw(e);n&&(e.traceId=n.traceId,e.spanId=n.spanId,e.traceFlags=n.traceFlags)}if(Object.assign(e,ax(e.requestId)),wsn(e),!nce||!Dw&&!tl())return;if(tl()){Mw("attempt",e);return}const t=At(Dw,`proxy-attempts-${new Date().toISOString().split("T")[0]}.jsonl`),r=JSON.stringify(e)+`
2344
2344
  `;try{await ace(t,r,"attempts")}catch{}}async function fir(){if(tl())return tir();if(Ow!==!1){if(Ow!==null)return Ow;hir++;try{const{getLoggerProvider:e}=await Promise.resolve().then(()=>(ip(),hW)),t=e();if(t)return Ow=t,t;hir>=Din&&(Ow=!1);return}catch{Ow=!1;return}}}function gir(e){return fir().then(t=>{if(!t)return;const r=t.getLogger("neurolink-proxy","1.0.0"),n=(e.responseStatus??0)>=400||!!e.errorType||e.terminalOutcome==="stream_error"||e.terminalOutcome==="handler_error"||e.terminalOutcome==="client_cancelled",o=e.responseStatus===429,s=n?o?Iw.WARN:Iw.ERROR:Iw.INFO,i=n?o?"WARN":"ERROR":"INFO";r.emit({context:Kae(e),severityNumber:s,severityText:i,body:tl()?JSON.stringify(e):`${e.method} ${e.path} \u2192 ${e.responseStatus} (${e.responseTimeMs}ms)`,attributes:{"proxy.record_kind":"request_final","proxy.accounting_scope":e.accountingScope??"client",...e.parentRequestId?{"proxy.parent_request_id":e.parentRequestId}:{},...e.usageOwnerRequestId?{"proxy.usage_owner_request_id":e.usageOwnerRequestId}:{},...e.inputIncludesCachedTokens!==void 0?{"ai.input_includes_cached_tokens":e.inputIncludesCachedTokens}:{},"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,"ai.pricing.status":e.pricingStatus,"ai.pricing.basis":e.pricingBasis,"ai.pricing.provider":e.pricingProvider,...e.apiEquivalentCostUsd!==null&&e.apiEquivalentCostUsd!==void 0?{"ai.cost.api_equivalent_usd":e.apiEquivalentCostUsd}:{},...e.apiEquivalentCacheSavingsUsd!==null&&e.apiEquivalentCacheSavingsUsd!==void 0?{"ai.cost.cache_savings_usd":e.apiEquivalentCacheSavingsUsd}:{},"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:!n&&e.responseStatus>=200&&e.responseStatus<400,is_rate_limited:e.responseStatus===429,is_overloaded:e.responseStatus===529,is_error:n,source:"otlp"}})}).catch(()=>{})}function yir(e,t){return fir().then(async r=>{if(!r||t.redactedBody===void 0)return;const n=r.getLogger("neurolink-proxy-bodies","1.0.0"),o=e.captureId??dn(),s=(a,c,l)=>{n.emit({context:Kae(e),severityNumber:(e.responseStatus??0)>=400?Iw.WARN:Iw.INFO,severityText:(e.responseStatus??0)>=400?"WARN":"INFO",body:a,attributes:{"event.name":"proxy.body_capture","proxy.record_kind":"body","request.id":e.requestId,"body.phase":e.phase,"body.capture_id":o,"body.chunk_index":c,"body.chunk_count":l,"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"}})};if(tl())return gin(o,t.redactedBody,s);const i=Ysr(t.redactedBody,Oin);for(let a=0;a<i.length;a++)a>0&&a%4===0&&await Vsr(),s(i[a],a,i.length)}).catch(()=>{})}function lce(){return nce&&(!!Dw||tl())}async function Lw(e){if(!lce())return;if(mir()){Mw("body_capture_index",{timestamp:e.timestamp,requestId:e.requestId,captureId:e.captureId??dn(),phase:e.phase,bodyDelivery:{status:"policy_excluded",reason:"borrowed_traffic"}});return}const t=xw(e),r=Dw,n={...e,captureId:e.captureId??dn(),body:void 0},s=pir(xin(e,r,async i=>{const a=i.headers,c=i.stored,l=new Date(n.timestamp).toISOString().split("T")[0],u=r?At(r,`proxy-debug-${l}.jsonl`):void 0,d={timestamp:n.timestamp,type:"body_capture",requestId:n.requestId,captureId:n.captureId,phase:n.phase,model:n.model,stream:n.stream,headers:a,contentType:n.contentType,responseStatus:n.responseStatus,durationMs:n.durationMs,account:n.account,accountType:n.accountType,attempt:n.attempt,bodyPath:c.bodyPath,bodySha256:c.bodySha256,observedBodyBytes:n.bodySize,redactedBodyBytes:c.redactedBodyBytes,storedFileBytes:c.storedFileBytes,bodyTruncated:c.bodyTruncated,bodyCaptureLimitBytes:c.bodyCaptureLimitBytes,originalRedactedBodyBytes:c.originalRedactedBodyBytes,inputRetainedBytes:c.inputRetainedBytes,inputEncoding:c.inputEncoding,sourceTruncated:c.sourceTruncated,processingTruncated:c.processingTruncated,redactionLossy:c.redactionLossy,unparseableRedactedFrames:c.unparseableRedactedFrames,bodyWriteFailed:c.bodyWriteFailed,captureError:i.error,captureAdmission:i.admission,captureQueueWaitMs:i.queueWaitMs,captureProcessingMs:i.processingMs,captureAdmissionWaitMs:i.admissionWaitMs,captureWorkerQueueWaitMs:i.workerQueueWaitMs,metadata:i.error?void 0:n.metadata};if(t&&(d.traceId=t.traceId,d.spanId=t.spanId,d.traceFlags=t.traceFlags),tl()){const m=await Iin.publish(n,c,()=>yir({...n,traceId:t?.traceId??n.traceId,spanId:t?.spanId??n.spanId,traceFlags:t?.traceFlags??n.traceFlags},c));d.bodyReference=m.reference,d.bodyDelivery=m.delivery??{status:i.error?"capture_rejected":c.redactedBody===void 0?"no_body":"export_unconfirmed",...i.error?{reason:i.error}:{}},Mw("body_capture_index",d);return}try{u&&await ace(u,JSON.stringify(d)+`
2345
2345
  `,"debug",{waitForPersistence:!0})}catch{}await yir({...n,traceId:t?.traceId??n.traceId,spanId:t?.spanId??n.spanId,traceFlags:t?.traceFlags??n.traceFlags},c)}));if(!tl())return s}var Lin=1024*1024,Fin=16*1024*1024,uce=0;function vir(e,t,r,n){const o=s=>{Lw({timestamp:new Date().toISOString(),requestId:e.requestId,model:t,stream:r,durationMs:Date.now()-n,...s})};return{log:o,request(){o({phase:"client_request",headers:e.headers,body:e.body,contentType:"application/json"})},json(s,i){o({phase:"client_response",headers:{"content-type":"application/json"},body:s,contentType:"application/json",responseStatus:i})},accumulator(s,i,a){const c=lce(),l=[];let u=0,d=0,m=!1,h=!1;const f=g=>{if(h||!c)return;u+=g.byteLength;const y=Math.min(Lin-d,Fin-uce);if(!m&&y>0){const v=Uint8Array.from(g.subarray(0,y));l.push(v),d+=v.byteLength,uce+=v.byteLength,m=v.byteLength!==g.byteLength}else m||=g.byteLength>0};return{append:f,appendEvent(g){if(!(h||!c))try{f(new TextEncoder().encode(`data: ${JSON.stringify(g)??"null"}
@@ -158,23 +158,28 @@ export async function setCodexProxySettings(baseUrl) {
158
158
  logger.warn(`[proxy] Codex: config.toml declares [${duplicate}] more than once; leaving it untouched`);
159
159
  return false;
160
160
  }
161
- // Snapshot the user's original selector once (survives crashes/restarts).
162
- if (!fs.existsSync(getCodexSnapshotPath())) {
163
- // Same preamble boundary the edit paths use. Matching document-wide would
164
- // capture a `model_provider` belonging to a table — a legacy
165
- // `[profiles.<name>]` block, say — and the restore would then write that
166
- // profile's provider back as the top-level selector.
167
- let providerMatch = null;
168
- editTomlPreamble(original, (preamble) => {
169
- providerMatch = preamble.match(CODEX_PROVIDER_LINE_RE);
170
- return null;
171
- });
172
- // Ignore a stale managed selector line if present in the original.
173
- const originalProviderLine = providerMatch && !/"neurolink"/.test(providerMatch[0])
174
- ? providerMatch[0]
175
- : null;
161
+ // Same preamble boundary the edit paths use. Matching document-wide would
162
+ // capture a `model_provider` belonging to a table — a legacy
163
+ // `[profiles.<name>]` block, say — and the restore would then write that
164
+ // profile's provider back as the top-level selector.
165
+ let providerMatch = null;
166
+ editTomlPreamble(original, (preamble) => {
167
+ providerMatch = preamble.match(CODEX_PROVIDER_LINE_RE);
168
+ return null;
169
+ });
170
+ // A selector naming "neurolink" is the one the proxy writes, possibly left
171
+ // by an earlier run, and never the user's choice.
172
+ const userProviderLine = providerMatch && !/"neurolink"/.test(providerMatch[0])
173
+ ? providerMatch[0]
174
+ : null;
175
+ const selectorIsOurs = providerMatch !== null && userProviderLine === null;
176
+ // Snapshot on first touch, and again whenever the top-level selector is
177
+ // not the proxy's. An unclean exit skips restore and leaves the snapshot
178
+ // behind; a provider the user then picks by hand, or a selector they
179
+ // remove, is newer than that snapshot and is what restore must bring back.
180
+ if (!fs.existsSync(getCodexSnapshotPath()) || !selectorIsOurs) {
176
181
  fs.mkdirSync(join(homedir(), ".neurolink"), { recursive: true });
177
- await writeFileAtomic(getCodexSnapshotPath(), JSON.stringify({ originalProviderLine }, null, 2), 0o600);
182
+ await writeFileAtomic(getCodexSnapshotPath(), JSON.stringify({ originalProviderLine: userProviderLine }, null, 2), 0o600);
178
183
  }
179
184
  // Every proxy start applies. Rewriting a file that already matches only
180
185
  // widens the window for racing Codex's own saves.
@@ -19,8 +19,8 @@ function record(value) {
19
19
  * (plain, carrying a complete tool pair, repeated, or opening with a signed
20
20
  * `thinking` block). A `role: "system"` message is not — the Messages API
21
21
  * requires the initial system prompt in the top-level `system` parameter.
22
- * Items with no role (Codex `function_call` / `function_call_output`) are not
23
- * turns and are left alone.
22
+ * Items with no role (Codex `*_call` / `*_call_output`) are not turns and are
23
+ * left alone.
24
24
  */
25
25
  function isDirectiveTurn(item) {
26
26
  return record(item) && item.role === "system";
@@ -28,13 +28,26 @@ function isDirectiveTurn(item) {
28
28
  function blocksOf(item) {
29
29
  return Array.isArray(item.content) ? item.content : [item];
30
30
  }
31
- /** Tool-call ids this item opens. */
31
+ /**
32
+ * Tool-call ids this item opens.
33
+ *
34
+ * Matched on the `_call` suffix rather than an enumerated list of item types.
35
+ * The Responses API has several call families — `function_call`,
36
+ * `custom_tool_call`, `local_shell_call`, `computer_call` — and an unrecognised
37
+ * one is worse than useless here: it opens no id, so unit grouping cannot see
38
+ * the pair and truncation is free to cut between a call and its answer. A live
39
+ * Codex session failed exactly that way, upstream rejecting the request with
40
+ * "No tool call found for custom tool call output with call_id ...". Suffix
41
+ * matching keeps the next family from reintroducing it silently.
42
+ */
32
43
  function definedCallIds(item) {
33
44
  if (!record(item)) {
34
45
  return [];
35
46
  }
36
47
  const ids = [];
37
- if (item.type === "function_call" && typeof item.call_id === "string") {
48
+ if (typeof item.type === "string" &&
49
+ item.type.endsWith("_call") &&
50
+ typeof item.call_id === "string") {
38
51
  ids.push(item.call_id);
39
52
  }
40
53
  for (const block of blocksOf(item)) {
@@ -46,13 +59,20 @@ function definedCallIds(item) {
46
59
  }
47
60
  return ids;
48
61
  }
49
- /** Tool-call ids this item answers. */
62
+ /**
63
+ * Tool-call ids this item answers.
64
+ *
65
+ * Suffix-matched for the same reason `definedCallIds` is. `_call_output` is
66
+ * checked rather than `_call` because no output type ends in `_call`, so the
67
+ * two predicates stay disjoint without ordering between them.
68
+ */
50
69
  function referencedCallIds(item) {
51
70
  if (!record(item)) {
52
71
  return [];
53
72
  }
54
73
  const ids = [];
55
- if (item.type === "function_call_output" &&
74
+ if (typeof item.type === "string" &&
75
+ item.type.endsWith("_call_output") &&
56
76
  typeof item.call_id === "string") {
57
77
  ids.push(item.call_id);
58
78
  }
@@ -69,7 +89,8 @@ function referencedCallIds(item) {
69
89
  * Group items so a tool call and every answer to it stay in one unit.
70
90
  *
71
91
  * A unit stays open while any call it opened is still unanswered, so removing
72
- * whole units can never strand a `tool_result` or a `function_call_output`.
92
+ * whole units can never strand a tool answer — an Anthropic `tool_result` or
93
+ * any Responses API `*_call_output`.
73
94
  */
74
95
  function groupIntoUnits(items) {
75
96
  const units = [];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@juspay/neurolink",
3
- "version": "12.31.0",
3
+ "version": "12.31.1",
4
4
  "packageManager": "pnpm@10.15.1",
5
5
  "description": "The pipe layer of an AI nervous system: one interface connecting provider neurons to your application, across three inference types — generate, stream and decide. `decide` returns typed, calibrated judgements from a non-generative model (~400ms, ~$0.00002/call) for routing, tool selection and context budgeting. MCP-native (4 transports), voice TTS/STT/realtime, RAG, agents, memory, compaction, 9 observability exporters. OpenAI · Anthropic · Gemini · Bedrock · Azure · Ollama · TypeSafe Jev and more.",
6
6
  "author": {