@juspay/neurolink 13.10.2 → 13.10.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,8 +1,8 @@
1
- ## [13.10.2](https://github.com/juspay/neurolink/compare/v13.10.1...v13.10.2) (2026-11-03)
1
+ ## [13.10.3](https://github.com/juspay/neurolink/compare/v13.10.2...v13.10.3) (2026-11-03)
2
2
 
3
3
  ### Bug Fixes
4
4
 
5
- - **(mcp):** key servers by id, keep tool error messages and convert Zod 4 tool schemas by their input ([8c38b74](https://github.com/juspay/neurolink/commit/8c38b74e56f2b3df254289d79629aaa35ca0ea7b)), closes [Error#message](https://github.com/juspay/Error/issues/message)
5
+ - **(deps):** move the otel exporters to 0.219 ([3176715](https://github.com/juspay/neurolink/commit/3176715617c48825366ad0ed8376873cd1debabf))
6
6
 
7
7
  ## [11.2.3](https://github.com/juspay/neurolink/compare/v11.2.2...v11.2.3) (2026-08-19)
8
8
 
@@ -2378,7 +2378,7 @@ data: ${r}
2378
2378
  `))E.startsWith("event:")?w=E.slice(6).trim():E.startsWith("data:")&&b.push(E.slice(5).trim());w&&b.length>0&&m(w,b.join(`
2379
2379
  `),g),y=i.indexOf(`
2380
2380
 
2381
- `)}};return new TransformStream({transform(g,y){i+=o.decode(g,{stream:!0}),h(y)},flush(g){if(i+=o.decode(),h(g),!d){d=!0;const y="Anthropic stream ended before message_stop";t.onError?.(y),p(g,r.emitError(y))}}})}Mr();var s8=60*6e4,mzn=1e4,hTe=5e3,hzn=2e3;function fTe(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 Ea("sha256").update(t).digest("hex")}function Fs(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 rc(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 gTe(e){if(typeof e=="string")try{e=JSON.parse(e)}catch{throw Fs("PROXY_TOKEN_BUDGET_CONFIG","Token budget configuration is not valid JSON")}if(!e||typeof e!="object"||Array.isArray(e))throw Fs("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 Fs("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 gLr(){const e=process.env.NEUROLINK_PROXY_TOKEN_BUDGET;return e===void 0||e.trim()===""?void 0:gTe(e)}function fzn(e){const t=gLr(),r=e===void 0?void 0:gTe(e);if(!t)return r;if(!r)return t;const n={windowMs:Math.max(t.windowMs??s8,r.windowMs??s8)};for(const o of["maxInFlightTokens","accountWindowTokens","sessionWindowTokens"]){const i=t[o],s=r[o];(i!==void 0||s!==void 0)&&(n[o]=Math.min(i??Number.MAX_SAFE_INTEGER,s??Number.MAX_SAFE_INTEGER))}return n}function gzn(e){return!!(e?.maxInFlightTokens||e?.accountWindowTokens||e?.sessionWindowTokens)}function yLr(e){for(const t of["provider","accountKey","sessionKey","requestId"])if(typeof e[t]!="string"||e[t].length===0||e[t].length>512)throw Fs("PROXY_TOKEN_BUDGET_INPUT","Token budget requires bounded provider, account, session and request identities");if(!Number.isSafeInteger(e.reservationTokens)||e.reservationTokens<=0)throw Fs("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 Fs("PROXY_TOKEN_BUDGET_INPUT","Token estimate provenance must be bounded text")}var yzn=class{constructor(e="supervisor",t=Date.now,r=mzn,n=hTe){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,i]of this.buckets)i.inFlightTokens===0&&r-i.lastTouched>=i.windowMs&&this.buckets.delete(o);if(this.buckets.size>=this.maxKeys)throw Fs("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"){yLr(e);const r=gTe(e.policy??{});if(this.leases.size>=this.maxLeases)throw Fs("PROXY_TOKEN_BUDGET_CAPACITY","Token budget outstanding reservation capacity is full");const n=r.windowMs??s8,o=`account:${JSON.stringify([e.provider,e.accountKey])}`,i=`session:${JSON.stringify(e.sessionKey)}`,s=this.bucket(o,n),a=this.bucket(i,n),u=e.reservationTokens;if(r.maxInFlightTokens!==void 0&&u>r.maxInFlightTokens-s.inFlightTokens||r.accountWindowTokens!==void 0&&u>r.accountWindowTokens-s.chargedTokens||r.sessionWindowTokens!==void 0&&u>r.sessionWindowTokens-a.chargedTokens)throw Fs("PROXY_TOKEN_BUDGET_EXCEEDED","Token budget would be exceeded before upstream dispatch");if(u>Number.MAX_SAFE_INTEGER-Math.max(s.chargedTokens,a.chargedTokens))throw Fs("PROXY_TOKEN_BUDGET_CAPACITY","Token accounting integer capacity is full");s.chargedTokens+=u,s.inFlightTokens+=u,a.chargedTokens+=u,a.inFlightTokens+=u;const l={scope:this.scope,reservationTokens:u,accountChargedTokens:s.chargedTokens,accountInFlightTokens:s.inFlightTokens,sessionChargedTokens:a.chargedTokens,sessionInFlightTokens:a.inFlightTokens,windowMs:n,estimateProvenance:e.estimateProvenance??"caller_estimate_input_plus_max_output"},c=Wr();return this.leases.set(c,{owner:t,accountKey:o,sessionKey:i,estimate:u,snapshot:l}),{leaseId:c,snapshot:{...l}}}settle(e,t,r,n=!1){const o=this.leases.get(e);if(!o)return;if(o.owner!==t)throw Fs("PROXY_TOKEN_BUDGET_OWNER","Token budget lease belongs to another worker");if(r!==void 0&&(!Number.isSafeInteger(r)||r<0))throw Fs("PROXY_TOKEN_BUDGET_USAGE","Reported token usage must be a nonnegative safe integer");const i=n?0:r??o.estimate,s=this.bucket(o.accountKey,o.snapshot.windowMs),a=this.bucket(o.sessionKey,o.snapshot.windowMs);for(const u of[s,a])u.chargedTokens=Math.min(Number.MAX_SAFE_INTEGER,Math.max(0,u.chargedTokens+i-o.estimate)),u.inFlightTokens=Math.max(0,u.inFlightTokens-o.estimate);return this.leases.delete(e),{...o.snapshot,accountChargedTokens:s.chargedTokens,accountInFlightTokens:s.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)}},yTe=new yzn(process.env.NEUROLINK_PROXY_SOCKET_WORKER==="1"?"process":"supervisor"),jm=new Map,K4=new Set;function vLr(e){if(K4.size>=hTe){const t=K4.values().next().value;t&&K4.delete(t)}K4.add(e)}var wLr=!1;function vzn(){wLr||(wLr=!0,process.on("message",e=>{if(!e||typeof e!="object"||e.type!=="proxy-budget:response")return;const t=e,r=jm.get(t.rpcId);if(!r){K4.delete(t.rpcId)&&t.ok&&typeof t.leaseId=="string"&&t.leaseId.length<=128&&process.connected&&process.send&&process.send({type:"proxy-budget:request",rpcId:Wr(),pid:process.pid,generation:Number(process.env.NEUROLINK_PROXY_WORKER_GENERATION),action:"cancel",leaseId:t.leaseId},()=>{});return}jm.delete(t.rpcId),clearTimeout(r.timer),t.ok?r.resolve(t):r.reject(Fs(t.errorCode??"PROXY_TOKEN_BUDGET_UNAVAILABLE",t.error??"Token budget coordinator refused the request"))}),process.on("disconnect",()=>{for(const e of jm.values())clearTimeout(e.timer),e.reject(Fs("PROXY_TOKEN_BUDGET_UNAVAILABLE","Token budget supervisor disconnected"));jm.clear()}))}function vTe(e){return vzn(),new Promise((t,r)=>{if(!process.connected||!process.send||jm.size>=hTe){r(Fs("PROXY_TOKEN_BUDGET_UNAVAILABLE","Token budget supervisor IPC is unavailable"));return}const n=Wr(),o=setTimeout(()=>{jm.delete(n),e.action==="reserve"&&vLr(n),r(Fs("PROXY_TOKEN_BUDGET_UNAVAILABLE","Token budget supervisor response timed out; dispatch refused"))},hzn);jm.set(n,{resolve:t,reject:r,timer:o});const i=s=>{!s||!jm.has(n)||(clearTimeout(o),jm.delete(n),e.action==="reserve"&&vLr(n),r(Fs("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)},i)}catch(s){i(s instanceof Error?s:new Error("IPC failed"))}})}async function wTe(e){const t=fzn(e.policy);if(!gzn(t))return{leaseId:"disabled",snapshot:{scope:"disabled",reservationTokens:0,accountChargedTokens:0,accountInFlightTokens:0,sessionChargedTokens:0,sessionInFlightTokens:0,windowMs:t?.windowMs??s8,estimateProvenance:"disabled"},settle:async()=>{},cancelBeforeDispatch:async()=>{}};yLr(e);const r=process.env.NEUROLINK_PROXY_SOCKET_WORKER==="1",n={...e,policy:t},o=r?await vTe({action:"reserve",reservation:n}):yTe.reserve(n,"local");if(!o.leaseId||!o.snapshot)throw Fs("PROXY_TOKEN_BUDGET_UNAVAILABLE","Token budget supervisor returned incomplete reservation proof");const i=o.leaseId;let s=!1;const a={leaseId:i,snapshot:{...o.snapshot,scope:r?"supervisor":"process"},settle:async u=>{if(s)return;const l=r?(await vTe({action:"settle",leaseId:i,actualTotalTokens:u})).snapshot:yTe.settle(i,"local",u);s=!0,l&&(a.snapshot={...l,scope:r?"supervisor":"process"})},cancelBeforeDispatch:async()=>{if(s)return;const u=r?(await vTe({action:"cancel",leaseId:i})).snapshot:yTe.settle(i,"local",void 0,!0);s=!0,u&&(a.snapshot={...u,scope:r?"supervisor":"process"})}};return a}async function bTe(e,t){try{await e.settle(t)}catch{e.snapshot={...e.snapshot,settlement:"unconfirmed"}}}It(),H6(),Mr(),zh(),Jt();var bLr=new Map;function a8(e){return bLr.get(e)??bLr.get(e.replace(/:codex-fallback$/,""))}function pS(e){const t=typeof e.requestId=="string"?a8(e.requestId):void 0,r=Qt.getSpanContext(yt.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,i={...n,traceFlags:o};return LS(i)?{traceId:i.traceId,spanId:i.spanId,traceFlags:o}:void 0}function TTe(e){const t=pS(e);return t?Qt.setSpanContext(az,t):yt.active()}var wzn=async()=>{},_Yn=globalThis.crypto,EYn=globalThis.ReadableStream||class{},TLr=wzn,SYn=globalThis.URL,kYn=globalThis.URLSearchParams,_Te=e=>{try{return JSON.stringify(e,null,2)}catch{return String(e)}};_Te.custom=Symbol.for("nodejs.util.inspect.custom"),_Te.colors={},_Te.styles={};var bzn=globalThis.TextDecoder,_Lr=globalThis.TextEncoder,AYn=globalThis.performance||{now:()=>Date.now()},CYn=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),i=new Uint8Array(o.length);for(let s=0;s<o.length;s++)i[s]=o.charCodeAt(s);return i}if(n==="hex"){const o=new Uint8Array(t.length/2);for(let i=0;i<t.length;i+=2)o[i/2]=parseInt(t.substr(i,2),16);return o}return new _Lr().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((i,s)=>i+s.length,0),n=new Uint8Array(r);let o=0;for(const i of t)n.set(i,o),o+=i.length;return n}static byteLength(t,r){return r==="base64"?Math.ceil(t.length*3/4):new _Lr().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 bzn().decode(this)}},Tzn=e=>({[Symbol.toPrimitive](){return e},ref(){return this},unref(){return this},hasRef(){return!1},refresh(){return this},close(){}}),_zn=(...e)=>Tzn(globalThis.setTimeout(...e)),IYn=globalThis.clearTimeout,RYn=globalThis.clearInterval;br(),got(),wot(),H6(),Xx(),zh();var ELr=Gd(import.meta.url),u8,SLr,kLr,ALr=!1;function Ezn(){ALr||({ExportResultCode:u8,parseKeyPairsIntoRecord:SLr}=ELr("@opentelemetry/core"),{JsonLogsSerializer:kLr}=ELr("@opentelemetry/otlp-transformer"),ALr=!0)}var Szn=j6(RL),kzn=64*1024,Azn=5,Czn=new Set([429,502,503,504]),xzn=new Set(["ECONNRESET","ECONNREFUSED","EPIPE","ETIMEDOUT","EAI_AGAIN","ENOTFOUND","ENETUNREACH","EHOSTUNREACH"]),qo=class extends Error{constructor(e,t=!1,r){super(e),this.retryable=t,this.retryAfterMs=r,this.name="ProxyOtlpResponseError"}retryable;retryAfterMs};function Izn(e){return e instanceof qo&&e.retryable?e.retryAfterMs??0:void 0}function CLr(e){return process.env[`OTEL_EXPORTER_OTLP_LOGS_${e}`]?.trim()||process.env[`OTEL_EXPORTER_OTLP_${e}`]?.trim()||void 0}function ETe(e){const t=CLr(e);if(t)try{return xi(t)}catch{throw new Error(`Proxy OTLP ${e} file could not be read`)}}function Rzn(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 Mzn(e){let t;try{t=JSON.parse(e.toString("utf8"))}catch{throw new qo("OTLP response JSON is empty or malformed")}if(!t||typeof t!="object"||Array.isArray(t))throw new qo("OTLP response must be a JSON object");if(Object.keys(t).some(a=>a!=="partialSuccess"&&a!=="partial_success"))throw new qo("OTLP response has unexpected fields");if("partialSuccess"in t&&"partial_success"in t)throw new qo("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 qo("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 qo("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 qo("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 qo("OTLP partial success response is malformed");const i="rejectedLogRecords"in r?r.rejectedLogRecords:"rejected_log_records"in r?r.rejected_log_records:0;if(i===null||i===0||i==="0")return;const s=typeof i=="string"&&/^\d+$/.test(i)||typeof i=="number"&&Number.isSafeInteger(i)&&i>=0?BigInt(i):void 0;if(s===void 0||s>9223372036854775807n)throw new qo("OTLP rejected record count is malformed");if(s>0n)throw new qo("OTLP partial success rejected log records")}function Pzn(e,t){Ezn();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=CLr("COMPRESSION")??"none";if(n!=="none"&&n!=="gzip")throw new Error("Proxy OTLP compression must be none or gzip");const o={};try{for(const m of[process.env.OTEL_EXPORTER_OTLP_HEADERS,process.env.OTEL_EXPORTER_OTLP_LOGS_HEADERS])for(const[h,g]of Object.entries(SLr(m)))pot(h),mot(h,g),o[h.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 i={ca:ETe("CERTIFICATE"),cert:ETe("CLIENT_CERTIFICATE"),key:ETe("CLIENT_KEY")};if(!!i.cert!=!!i.key)throw new Error("Proxy OTLP client certificate and key must be set together");const s=r.protocol==="https:"?new MQ({keepAlive:!0,maxSockets:30,...i}):new IQ({keepAlive:!0,maxSockets:30}),a=r.protocol==="https:"?yot:hot;let u=!1;const l=new Set,c=new Set,d=(m,h)=>new Promise((g,y)=>{let v=!1;const w=a(r,{method:"POST",agent:s,signal:h,headers:{...o,"content-length":String(m.byteLength)}},b=>{v=!0;const E=b.statusCode??0,k=P=>{y(P),b.destroy()};if(E!==200){k(new qo(`OTLP HTTP ${E}`,Czn.has(E),Rzn(b.headers["retry-after"])));return}const A=b.headers["content-encoding"];if(A&&A!=="identity"){k(new qo("OTLP response encoding is unsupported"));return}const C=b.headers["content-type"];if(C&&C.split(";",1)[0].trim().toLowerCase()!=="application/json"){k(new qo("OTLP response content type is not JSON"));return}const M=[];let x=0;b.on("data",P=>{if(x+=P.length,x>kzn){k(new qo("OTLP response exceeds 64 KiB limit"));return}M.push(P)}),b.on("aborted",()=>y(new qo("OTLP success response was interrupted"))),b.on("error",()=>y(new qo("OTLP success response could not be read"))),b.on("end",()=>{try{Mzn(Buffer.concat(M)),g()}catch(P){y(P)}})});w.on("error",b=>y(new qo(h.aborted?"OTLP export deadline exceeded":"OTLP transport failed",!v&&(h.aborted||xzn.has(b.code??""))))),w.end(m)}),p=async m=>{const h=new AbortController;c.add(h);const g=Date.now()+t,y=setTimeout(()=>h.abort(),t);y.unref();try{const v=kLr.serializeRequest(m);if(!v)throw new qo("OTLP serialization produced no payload");const w=n==="gzip"?await Szn(v):v;let b=0;for(;!h.signal.aborted&&Date.now()<g;){b++;try{await d(w,h.signal);return}catch(E){if(!(E instanceof qo)||!E.retryable)throw E;if(b>=Azn)throw new qo("OTLP retry attempt limit reached",!0,E.retryAfterMs);const k=Math.min(5e3,1e3*2**Math.min(b-1,3)),A=Math.max(E.retryAfterMs??0,k*(.8+Math.random()*.4));if(A>=g-Date.now())throw new qo("OTLP retry exceeds export deadline",!0,A);await _zn(A,void 0,{signal:h.signal})}}throw new qo("OTLP export deadline exceeded",!0)}catch(v){throw v instanceof qo?v:new qo(h.signal.aborted?"OTLP export deadline exceeded":"OTLP export failed",h.signal.aborted)}finally{clearTimeout(y),c.delete(h)}};return{abortPending(){u=!0;for(const m of c)m.abort();s.destroy()},export(m,h){if(u){h({code:u8.FAILED,error:new Error("OTLP transport is shut down")});return}const g=p(m).then(()=>h({code:u8.SUCCESS}),y=>h({code:u8.FAILED,error:y}));l.add(g),g.finally(()=>l.delete(g)).catch(()=>{})},async shutdown(){u=!0,await Promise.allSettled(l),s.destroy()}}}It(),Mt(),Or(),Mr(),H6(),Xx();var MYn=1024*1024,PYn=8*1024*1024,DYn=j6(RL);function xLr(e,t){if(!e)return[""];const r=[],n=Buffer.from(e,"utf8");for(let o=0;o<n.length;){let i=Math.min(o+Math.max(4,t),n.length);for(;i<n.length&&(n[i]&192)===128;)i-=1;r.push(n.subarray(o,i).toString("utf8")),o=i}return r}var l8=Gd(import.meta.url),ILr,$v,RLr,MLr,PLr,DLr=!1;function Dzn(){DLr||({SeverityNumber:ILr}=l8("@opentelemetry/api-logs"),{ExportResultCode:$v}=l8("@opentelemetry/core"),{resourceFromAttributes:RLr}=l8("@opentelemetry/resources"),{BatchLogRecordProcessor:MLr,LoggerProvider:PLr}=l8("@opentelemetry/sdk-logs"),DLr=!0)}var mS,c8=[],Fv=new Map,OLr=new WeakMap,NLr=new Set,d8=!1,Ozn=128*1024,LLr=3e4,STe=LLr+1e3,Nzn=2e4,$Lr=12e4,Lzn=new Set(["console","runtime","telemetry_delivery"]);function $zn(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 Zi={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 nc(){return process.env.NEUROLINK_PROXY_LOG_SINK==="otel"}function p8(e,t,r,n){const o=new Set,i=new WeakMap,s=new WeakMap,a=new Set,u=r==="metadata"||r==="indexes"?$Lr:0,l=new Set,c=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},p=[];let m=!1;const h=(k,A,C)=>{const M=(P,D)=>{const L=P.attributes[D];return typeof L=="string"?L.slice(0,128):void 0},x={id:Wr(),at:new Date().toISOString(),reason:A,...C?{error:er(C.message).slice(0,256)}:{},records:k.slice(0,64).map(P=>({eventId:M(P,"proxy.event_id")??"unavailable",kind:M(P,"proxy.record_kind"),requestId:M(P,"request.id"),captureId:M(P,"body.capture_id")}))};d.recentFailures.length===16&&(d.recentFailures.shift(),d.failureHistoryEvicted++),d.recentFailures.push(x),k.some(P=>P.attributes["proxy.record_kind"]!=="telemetry_delivery")&&(p.length===16&&p.shift(),p.push(x))},g=()=>{m||!p.length||d8||(m=!0,queueMicrotask(()=>{m=!1;for(const k of p.splice(0))hS("telemetry_delivery",{queue:r,...k})}))},y=Pzn(e,LLr),v={export(k,A){const C=performance.now();for(const q of k){const H=q.attributes["body.capture_id"],ne=typeof H=="string"?Fv.get(H):void 0;ne&&(ne.maxChunkQueueWaitMs=Math.max(ne.maxChunkQueueWaitMs??0,C-(i.get(q)??C)))}let M=!1,x=!1,P,D,L,O=0;const U=Math.min(...k.map(q=>i.get(q)??C))+u,$=()=>{P&&L&&G(L)};a.add($);const G=q=>{if(!M){M=!0,clearTimeout(D),clearTimeout(P),a.delete($),x&&(d.retryingRecords-=k.length),d.outstanding-=k.length,q.code===$v.SUCCESS?(d.transportAcknowledged+=k.length,d.lastAcknowledgedAt=new Date().toISOString(),g()):(d.exportUnconfirmed+=k.length,d.lastFailureAt=new Date().toISOString(),h(k,"export_unconfirmed",q.error));for(const H of k){o.delete(H),d.outstandingBytes-=s.get(H)??0;const ne=H.attributes?.["body.capture_id"],X=typeof ne=="string"?Fv.get(ne):void 0;if(X){X.maxChunkExportMs=Math.max(X.maxChunkExportMs??0,performance.now()-C);const oe=OLr.get(X);q.code===$v.SUCCESS&&(oe===void 0||Date.now()<oe)?X.acknowledged++:X.unconfirmed++,X.notify?.()}}for(const H of l)H();for(const H of c)H();A(q)}},B=()=>{if(P=void 0,u&&performance.now()>=U){d.retentionExpired+=k.length,G({code:$v.FAILED,error:new Error("OTLP metadata retention budget exceeded")});return}O++,O>1&&d.retriedBatches++;let q=!1;const H=ne=>{if(q||M)return;q=!0,clearTimeout(D);const X=ne.code===$v.FAILED?Izn(ne.error):void 0;if(u&&X!==void 0&&!d8){d.lastTransientFailureAt=new Date().toISOString();const oe=Math.max(X,Math.min(1e4,1e3*2**Math.min(O-1,4))*(.8+Math.random()*.4));if(performance.now()+oe<U){x||(x=!0,d.retryingRecords+=k.length),L=ne,P=setTimeout(B,oe),P.unref();return}d.retentionExpired+=k.length}G(ne)};D=setTimeout(()=>H({code:$v.FAILED,error:new Error("OTLP export callback deadline exceeded")}),STe),D.unref();try{y.export(k,H)}catch(ne){H({code:$v.FAILED,error:ne instanceof Error?ne:new Error(String(ne))})}};B()},shutdown:()=>y.shutdown()},w=new MLr(v,{maxQueueSize:t,maxExportBatchSize:64,scheduledDelayMillis:r==="bodies"?25:1e3,exportTimeoutMillis:u+STe+1e3}),b={onEmit(k){k.attributes["proxy.event_id"]??=Wr(),d.attempted++;const A=k.attributes?.["body.capture_id"],C=typeof A=="string"?Fv.get(A):void 0;C&&C.emitted++;const M=$zn(k);if(d.outstanding>=t||d.outstandingBytes+M>n){d.dropped++,d.outstandingBytes+M>n&&d.byteLimitDrops++,h([k],"queue_full"),C&&(C.dropped++,C.notify?.());return}d.submitted++,d.outstanding++,d.outstandingBytes+=M,d.highWaterBytes=Math.max(d.highWaterBytes,d.outstandingBytes),s.set(k,M),o.add(k),i.set(k,performance.now()),d.highWaterOutstanding=Math.max(d.highWaterOutstanding,d.outstanding),w.onEmit(k)},forceFlush:async()=>{const k=new Set(o);try{await w.forceFlush()}finally{await new Promise(A=>{const C=()=>{[...k].some(M=>o.has(M))||(c.delete(C),A())};c.add(C),C()})}},shutdown:async()=>{try{await b.forceFlush()}finally{await w.shutdown()}}};return{state:d,processor:b,capacity:t,byteCapacity:n,retentionMs:u,kind:r,waitForCapacity:k=>new Promise(A=>{const C=setTimeout(()=>M(!1),Math.max(0,k-Date.now()));C.unref?.();const M=P=>{clearTimeout(C),l.delete(x),A(P)},x=()=>{Date.now()>=k?M(!1):d.outstanding<t&&M(!0)};l.add(x),x()}),abortPending:()=>y.abortPending(),stopRetention:()=>{for(const k of a)k()},oldestOutstandingAgeMs:()=>{let k=performance.now();for(const A of o)k=Math.min(k,i.get(A)??k);return o.size?Math.max(0,performance.now()-k):0}}}async function Fzn(e,t,r){Zi.attempted++;const n=Buffer.byteLength(t,"utf8");if(!mS||d8||Fv.has(e)||Zi.pending>=Zi.maxPending||Zi.pendingBytes+n>Zi.maxPendingBytes)return Zi.rejected++,{status:"rejected",acknowledgedChunks:0,unconfirmedChunks:0,droppedChunks:0,reason:Fv.has(e)?"body_capture_id_in_use":!mS||d8?"body_exporter_unavailable":"body_publication_queue_full"};Zi.pending++,Zi.pendingBytes+=n,Zi.highWaterPending=Math.max(Zi.highWaterPending,Zi.pending),Zi.highWaterBytes=Math.max(Zi.highWaterBytes,Zi.pendingBytes);const o={acknowledged:0,unconfirmed:0,dropped:0,emitted:0};Fv.set(e,o);let i;const s=(async()=>{const a=c8.find(b=>b.kind==="bodies");if(!a)return{status:"rejected",acknowledgedChunks:0,unconfirmedChunks:0,droppedChunks:0,reason:"body_exporter_unavailable"};const u=performance.now(),l=Date.now()+Nzn;OLr.set(o,l);const c=xLr(t,Ozn);let d=0,p;try{for(let b=0;b<c.length;b++){for(;a.state.outstanding>=a.capacity;){const E=performance.now(),k=await a.waitForCapacity(l);if(d+=performance.now()-E,!k){p="body_publication_deadline";break}}if(Date.now()>=l){p="body_publication_deadline";break}r(c[b],b,c.length),b%4===3&&await TLr()}}catch{p="body_publication_failed"}const m=new Promise(b=>{const E=()=>{o.acknowledged+o.unconfirmed+o.dropped>=o.emitted&&(o.notify=void 0,b())};o.notify=E,E()});let h;const g=await Promise.race([m.then(()=>!0),new Promise(b=>{h=setTimeout(()=>b(!1),Math.max(0,l-Date.now())),h.unref?.()})]).finally(()=>clearTimeout(h));g||(i=m),(!g||Date.now()>=l)&&(p??="body_publication_deadline"),!p&&o.unconfirmed?p="body_export_unconfirmed":!p&&o.dropped&&(p="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!==c.length?"partial":v?"export_unconfirmed":"transport_acknowledged",expectedChunks:c.length,acknowledgedChunks:o.acknowledged,unconfirmedChunks:v,droppedChunks:o.dropped,notSubmittedChunks:c.length-o.emitted,publicationMs:performance.now()-u,capacityWaitMs:d,maxChunkQueueWaitMs:o.maxChunkQueueWaitMs??0,maxChunkExportMs:o.maxChunkExportMs??0,...p?{reason:p}:{}}})();NLr.add(s);try{const a=await s;return a.status==="transport_acknowledged"?Zi.transportAcknowledged++:a.status==="export_unconfirmed"?Zi.exportUnconfirmed++:a.status==="rejected"?Zi.rejected++:Zi.partial++,a}finally{NLr.delete(s);const a=()=>{Fv.delete(e),Zi.pending--,Zi.pendingBytes-=n};i?i.then(a,a):a()}}function FLr(e="worker"){if(!nc())return;if(mS)return mS;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 u=new URL(a);if(!["http:","https:"].includes(u.protocol))throw new Error("Proxy OTLP logs endpoint must use HTTP or HTTPS");const l=["localhost","127.0.0.1","[::1]"].includes(u.hostname);if(u.protocol==="http:"&&!l)throw new Error("Proxy OTLP logs require HTTPS for non-loopback collectors")}Dzn();const n=p8(t,2048,"metadata",8*1024*1024),o=p8(r,256,"bodies",40*1024*1024),i=p8(t,512,"diagnostics",2*1024*1024),s=p8(t,1024,"indexes",8*1024*1024);return c8.push(n,o,i,s),mS=new PLr({forceFlushTimeoutMillis:$Lr+STe+2e3,resource:RLr({"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,u){(a.attributes?.["proxy.record_kind"]==="body"?o:a.attributes?.["proxy.record_kind"]==="body_capture_index"?s:a.attributes?.["proxy.lifecycle.event"]==="runtime_sample"||Lzn.has(String(a.attributes?.["proxy.record_kind"]))?i:n).processor.onEmit(a,u)},forceFlush:async()=>{await Promise.all(c8.map(a=>a.processor.forceFlush()))},shutdown:async()=>{await Promise.all(c8.map(a=>a.processor.shutdown()))}}]}),mS}function hS(e,t){if(nc())try{const r=typeof t.requestId=="string"&&!t.traceId?a8(t.requestId):void 0,n=r?{...t,...r}:t;FLr()?.getLogger("neurolink-proxy-events").emit({context:TTe(n),severityNumber:ILr.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{Uzn++}}var Uzn=0;Mr();var ULr=1024,BLr=5*6e4;function Bzn(e={}){const t=e.now??(()=>performance.now()),r=e.bytesPerMinute?.trim(),n=r?Number(r):null,o=n!==null&&(!Number.isSafeInteger(n)||n<=0),i=new Map;let s=n??1/0,a=t(),u=0,l=0,c=0,d=0,p=0;const m=()=>{const h=t();n!==null&&!o&&(s=Math.min(n,s+Math.max(0,h-a)*n/6e4)),a=h;for(const[g,y]of i)y.expiresAt<=h&&i.delete(g)};return{snapshot(){return m(),{deduplicationEnabled:e.deduplicate!==!1,maxReferences:ULr,referenceTtlMs:BLr,references:i.size,byteBudgetPerMinute:o?null:n,invalidByteBudget:o,availableBytes:n===null||o?null:Math.floor(s),submittedBytes:u,deduplicatedCaptures:l,deduplicatedBytes:c,policyExcludedCaptures:d,policyExcludedBytes:p}},async publish(h,g,y){if(m(),g.redactedBody===void 0)return{};const v=Buffer.byteLength(g.redactedBody,"utf8"),w=e.deduplicate!==!1&&g.bodySha256&&h.captureId?JSON.stringify([h.requestId,g.bodySha256,v]):void 0,b=w?i.get(w):void 0;if(b&&b.reference.captureId!==h.captureId&&await b.acknowledged&&b.expiresAt>t())return l++,c+=v,{delivery:{status:"reference",reason:"identical_redacted_payload"},reference:{...b.reference}};if(m(),o||v>s)return d++,p+=v,{delivery:{status:"policy_excluded",reason:o?"body_byte_budget_invalid":"body_byte_budget_exhausted"}};s-=v,u+=v;let E=()=>{};const k=w&&h.captureId&&g.bodySha256?{reference:{captureId:h.captureId,requestId:h.requestId,bodySha256:g.bodySha256,redactedBodyBytes:v,exportedAt:""},expiresAt:t()+BLr,acknowledged:new Promise(C=>{E=C})}:void 0;if(w&&k){if(i.size>=ULr){const C=i.keys().next().value;C!==void 0&&i.delete(C)}i.set(w,k)}let A=!1;try{const C=await y();return A=C?.status==="transport_acknowledged",k&&A&&(k.reference.exportedAt=new Date().toISOString()),{delivery:C}}finally{E(A),w&&!A&&i.get(w)===k&&i.delete(w)}}}}Sr(),aa(),z(),Ld(),Jf(),ro(),Ti(),Pqt();var J4=64,m8=32*1024*1024,zLr=64,GLr=32*1024*1024,zzn=2e4,Gzn=16*1024*1024,qLr=2e4,Uv,qzn,sg=0,jzn=0,ur={attempted:0,completed:0,rejected:0,failed:0,pending:0,pendingBytes:0,maxPending:J4,maxPendingBytes:m8,highWaterPending:0,highWaterBytes:0,waiting:0,waitingBytes:0,maxWaiting:zLr,maxWaitingBytes:GLr,highWaterWaiting:0,highWaterWaitingBytes:0,admissionWaits:0,admissionTimeouts:0,rejectionReasons:{}},X4=new Map,jLr=new Map,Bv=[],h8;function VLr(e){return Date.now()<sg||ur.pending>=J4||ur.pendingBytes+e>m8?!1:(ur.pending+=1,ur.pendingBytes+=e,ur.highWaterPending=Math.max(ur.highWaterPending,ur.pending),ur.highWaterBytes=Math.max(ur.highWaterBytes,ur.pendingBytes),!0)}function kTe(){if(Bv.length){if(Date.now()<sg){h8||(h8=setTimeout(()=>{h8=void 0,kTe()},Math.max(1,sg-Date.now())),h8.unref?.());return}for(let e=0;e<Bv.length&&!(ur.pending>=J4);){const t=Bv[e];if(!VLr(t.bytes)){e+=1;continue}Bv.splice(e,1),clearTimeout(t.timer),ur.waiting-=1,ur.waitingBytes-=t.bytes,t.resolve("admitted")}}}function Vzn(e){return ur.waiting>=zLr||ur.waitingBytes+e>GLr?Promise.resolve("queue_full"):(ur.admissionWaits+=1,ur.waiting+=1,ur.waitingBytes+=e,ur.highWaterWaiting=Math.max(ur.highWaterWaiting,ur.waiting),ur.highWaterWaitingBytes=Math.max(ur.highWaterWaitingBytes,ur.waitingBytes),new Promise(t=>{const r=setTimeout(()=>{const n=Bv.findIndex(o=>o.timer===r);n<0||(Bv.splice(n,1),ur.waiting-=1,ur.waitingBytes-=e,ur.admissionTimeouts+=1,t("timeout"),kTe())},zzn);r.unref?.(),Bv.push({bytes:e,queuedAt:Date.now(),resolve:t,timer:r})}))}function HLr(e){ur.pending-=1,ur.pendingBytes-=e,kTe()}function Hzn(e,t){const r=[e],n=new Set;let o=0,i=0;for(;r.length;){if(++i>1e5)throw new Error("body_capture_traversal_limit");if(o>t)return o;const s=r.pop();if(typeof s=="string"){o+=16+s.length*2;continue}if(o+=16,!(!s||typeof s!="object")){if(n.has(s))throw new Error("body_capture_unsupported_value");if(n.add(s),!Array.isArray(s)&&Object.getPrototypeOf(s)!==Object.prototype&&Object.getPrototypeOf(s)!==null)throw new Error("body_capture_unsupported_value");for(const a of Object.keys(s)){o+=16+a.length*2;const u=Object.getOwnPropertyDescriptor(s,a);if(!u||u.get||u.set)throw new Error("body_capture_unsupported_value");if(r.push(u.value),r.length>1e5)throw new Error("body_capture_traversal_limit");if(o>t)return o}}}return o}function ATe(e,t){const r=X4.get(e);r&&(X4.delete(e),clearTimeout(r.timer),r.resolve(t),X4.size||Uv?.unref())}function CTe(e,t){if(Uv===e){Uv=void 0,sg=Date.now()+5e3;for(const r of X4.keys())ATe(r,{error:t,stored:{bodyWriteFailed:!0}});e.terminate().catch(()=>{})}}function Wzn(){if(Uv)return Uv;const e=new tie(qzn??new URL("./bodyCaptureWorkerEntry.js",import.meta.url),{execArgv:process.execArgv.filter(t=>!t.startsWith("--input-type")),resourceLimits:{maxOldGenerationSizeMb:128}});return Uv=e,e.on("message",t=>{Uv===e&&ATe(t.id,t.result)}),e.on("error",()=>CTe(e,"body_worker_error")),e.on("exit",()=>CTe(e,"body_worker_exit")),e.unref(),e}async function Kzn(e,t,r){ur.attempted+=1;const n=Date.now(),o=t===null?m8:Gzn;let i,s;try{i=Hzn(e,o)}catch(d){i=1/0,s=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(i<=o&&Date.now()>=sg&&(a=VLr(i)?"admitted":t===null?await Vzn(i):"queue_full"),a!=="admitted"){ur.rejected+=1;const d=i>o?s??"body_capture_entry_too_large":Date.now()<sg?"body_worker_backoff":a==="timeout"?"body_capture_admission_timeout":"body_capture_queue_full";return ur.lastError=d,ur.lastRejectedAt=new Date().toISOString(),ur.rejectionReasons[d]=(ur.rejectionReasons[d]??0)+1,r({error:d,stored:{bodyWriteFailed:!0},admissionWaitMs:Math.max(0,Date.now()-n),admission:{limitingResource:i>o?"entry":Date.now()<sg?"worker":ur.pending>=J4?"captures":"bytes",estimatedBytes:Number.isFinite(i)?i:void 0,maxEntryBytes:o,pending:ur.pending,pendingBytes:ur.pendingBytes,maxPending:J4,maxPendingBytes:m8}})}const u=Date.now();let l;try{l=Wzn()}catch{return sg=Date.now()+5e3,HLr(i),ur.failed+=1,r({error:"body_worker_start_failed",stored:{bodyWriteFailed:!0}})}const c=++jzn;return new Promise(d=>{const p=setTimeout(()=>CTe(l,"body_worker_timeout"),qLr);p.unref(),X4.set(c,{timer:p,startedAt:Date.now(),resolve:m=>{jLr.set(c,Date.now()),m.admissionWaitMs=Math.max(0,u-n),m.workerQueueWaitMs=Math.max(0,(m.queueWaitMs??0)-m.admissionWaitMs),r(m).catch(()=>{m.error??="body_capture_publication_failed"}).finally(()=>{jLr.delete(c),HLr(i),m.error||m.stored.bodyWriteFailed?ur.failed+=1:ur.completed+=1,m.error&&(ur.lastError=m.error),d()})}}),l.ref();try{l.postMessage({id:c,entry:e,logDir:t,queuedAt:n})}catch{ATe(c,{error:"body_capture_clone_failed",stored:{bodyWriteFailed:!0}})}})}Jt(),PM();var WLr=new FS;function bp(){return WLr.getStore()}function f8(){return WLr.getStore()!==void 0}zh();var Jzn=class{export(){}shutdown(){return Promise.resolve()}};qrt();var Xzn=class{constructor(){}getLogger(){return{emit(){}}}forceFlush(){return Promise.resolve()}shutdown(){return Promise.resolve()}},Yzn=class{onStart(){}onEnd(){}shutdown(){return Promise.resolve()}forceFlush(){return Promise.resolve()}};Hr();var Zzn=Gd(import.meta.url),fS,KLr=!1;function JLr(){KLr||({SeverityNumber:fS}=Zzn("@opentelemetry/api-logs"),KLr=!0)}var gS=null,xTe=!1,Qzn=Bzn(),ITe=new Set,RTe=5e3,OYn=qLr+2*RTe,eGn=4096,g8=new Map,tGn=Fre,MTe=()=>({attempted:0,written:0,inFlight:0,pending:0,dropped:0,writeTimeouts:0,unconfirmedWrites:0}),rGn={requests:MTe(),attempts:MTe(),debug:MTe()};async function PTe(e,t,r,n={}){const o=rGn[r];if(o.attempted+=1,o.pending+o.inFlight>=eGn){o.dropped+=1;return}o.pending+=1;const i=XLr((g8.get(e)??Promise.resolve()).then(async()=>{o.pending-=1,o.inFlight+=1;const s=setTimeout(()=>{o.writeTimeouts+=1},RTe);s.unref?.();try{await tGn(e,t,{mode:384,flag:"a"}),o.written+=1}catch(a){o.unconfirmedWrites+=1,o.lastErrorCode=a?.code??"UNKNOWN"}finally{clearTimeout(s),o.inFlight-=1}}));if(g8.set(e,i),i.then(()=>{g8.get(e)===i&&g8.delete(e)}),n.waitForPersistence)return i;await kt(i,RTe,"Proxy metadata write remains pending").catch(()=>{})}function XLr(e){return ITe.add(e),e.then(()=>ITe.delete(e),()=>ITe.delete(e)),e}var YLr,ZLr=!1,nGn=16e3;function oGn(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,i=e.cacheCreation1hTokens;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||i!==void 0&&(!Number.isFinite(i)||i<0||i>o)||e.inputIncludesCachedTokens===!0&&n+o>t||e.inputIncludesCachedTokens===!0&&(e.cacheReadTokensObserved===!1||e.cacheCreationTokensObserved===!1)){e.pricingStatus="usage_incomplete";return}if(!Xp(e.pricingProvider,e.model)){e.pricingStatus="unavailable";return}if(!oee(e.pricingProvider,e.model)){e.pricingStatus="inferred";return}const s=Pm({inputTokens:t,outputTokens:r,cacheReadTokens:n,cacheCreationTokens:o,inputIncludesCachedTokens:e.inputIncludesCachedTokens,...e.cacheCreation1hTokens!==void 0?{cacheCreation1hTokens:e.cacheCreation1hTokens}:{}});e.pricingStatus="exact",e.apiEquivalentCostUsd=Il(e.pricingProvider,e.model,s);const a=Il(e.pricingProvider,e.model,{...s,input:s.input+(s.cacheReadTokens??0),cacheReadTokens:0});e.apiEquivalentCacheSavingsUsd=Math.max(0,Math.round((a-e.apiEquivalentCostUsd)*1e6)/1e6)}async function yS(e){if(Object.assign(e,sS(e.requestId)),oGn(e),!e.traceId||e.traceFlags===void 0){const n=pS(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",!A8n(e)||!xTe||!gS&&!nc())return;if(nc()){await e6r(e);return}const t=$t(gS,`proxy-${new Date().toISOString().split("T")[0]}.jsonl`),r=JSON.stringify(e)+`
2381
+ `)}};return new TransformStream({transform(g,y){i+=o.decode(g,{stream:!0}),h(y)},flush(g){if(i+=o.decode(),h(g),!d){d=!0;const y="Anthropic stream ended before message_stop";t.onError?.(y),p(g,r.emitError(y))}}})}Mr();var s8=60*6e4,mzn=1e4,hTe=5e3,hzn=2e3;function fTe(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 Ea("sha256").update(t).digest("hex")}function Fs(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 rc(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 gTe(e){if(typeof e=="string")try{e=JSON.parse(e)}catch{throw Fs("PROXY_TOKEN_BUDGET_CONFIG","Token budget configuration is not valid JSON")}if(!e||typeof e!="object"||Array.isArray(e))throw Fs("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 Fs("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 gLr(){const e=process.env.NEUROLINK_PROXY_TOKEN_BUDGET;return e===void 0||e.trim()===""?void 0:gTe(e)}function fzn(e){const t=gLr(),r=e===void 0?void 0:gTe(e);if(!t)return r;if(!r)return t;const n={windowMs:Math.max(t.windowMs??s8,r.windowMs??s8)};for(const o of["maxInFlightTokens","accountWindowTokens","sessionWindowTokens"]){const i=t[o],s=r[o];(i!==void 0||s!==void 0)&&(n[o]=Math.min(i??Number.MAX_SAFE_INTEGER,s??Number.MAX_SAFE_INTEGER))}return n}function gzn(e){return!!(e?.maxInFlightTokens||e?.accountWindowTokens||e?.sessionWindowTokens)}function yLr(e){for(const t of["provider","accountKey","sessionKey","requestId"])if(typeof e[t]!="string"||e[t].length===0||e[t].length>512)throw Fs("PROXY_TOKEN_BUDGET_INPUT","Token budget requires bounded provider, account, session and request identities");if(!Number.isSafeInteger(e.reservationTokens)||e.reservationTokens<=0)throw Fs("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 Fs("PROXY_TOKEN_BUDGET_INPUT","Token estimate provenance must be bounded text")}var yzn=class{constructor(e="supervisor",t=Date.now,r=mzn,n=hTe){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,i]of this.buckets)i.inFlightTokens===0&&r-i.lastTouched>=i.windowMs&&this.buckets.delete(o);if(this.buckets.size>=this.maxKeys)throw Fs("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"){yLr(e);const r=gTe(e.policy??{});if(this.leases.size>=this.maxLeases)throw Fs("PROXY_TOKEN_BUDGET_CAPACITY","Token budget outstanding reservation capacity is full");const n=r.windowMs??s8,o=`account:${JSON.stringify([e.provider,e.accountKey])}`,i=`session:${JSON.stringify(e.sessionKey)}`,s=this.bucket(o,n),a=this.bucket(i,n),u=e.reservationTokens;if(r.maxInFlightTokens!==void 0&&u>r.maxInFlightTokens-s.inFlightTokens||r.accountWindowTokens!==void 0&&u>r.accountWindowTokens-s.chargedTokens||r.sessionWindowTokens!==void 0&&u>r.sessionWindowTokens-a.chargedTokens)throw Fs("PROXY_TOKEN_BUDGET_EXCEEDED","Token budget would be exceeded before upstream dispatch");if(u>Number.MAX_SAFE_INTEGER-Math.max(s.chargedTokens,a.chargedTokens))throw Fs("PROXY_TOKEN_BUDGET_CAPACITY","Token accounting integer capacity is full");s.chargedTokens+=u,s.inFlightTokens+=u,a.chargedTokens+=u,a.inFlightTokens+=u;const l={scope:this.scope,reservationTokens:u,accountChargedTokens:s.chargedTokens,accountInFlightTokens:s.inFlightTokens,sessionChargedTokens:a.chargedTokens,sessionInFlightTokens:a.inFlightTokens,windowMs:n,estimateProvenance:e.estimateProvenance??"caller_estimate_input_plus_max_output"},c=Wr();return this.leases.set(c,{owner:t,accountKey:o,sessionKey:i,estimate:u,snapshot:l}),{leaseId:c,snapshot:{...l}}}settle(e,t,r,n=!1){const o=this.leases.get(e);if(!o)return;if(o.owner!==t)throw Fs("PROXY_TOKEN_BUDGET_OWNER","Token budget lease belongs to another worker");if(r!==void 0&&(!Number.isSafeInteger(r)||r<0))throw Fs("PROXY_TOKEN_BUDGET_USAGE","Reported token usage must be a nonnegative safe integer");const i=n?0:r??o.estimate,s=this.bucket(o.accountKey,o.snapshot.windowMs),a=this.bucket(o.sessionKey,o.snapshot.windowMs);for(const u of[s,a])u.chargedTokens=Math.min(Number.MAX_SAFE_INTEGER,Math.max(0,u.chargedTokens+i-o.estimate)),u.inFlightTokens=Math.max(0,u.inFlightTokens-o.estimate);return this.leases.delete(e),{...o.snapshot,accountChargedTokens:s.chargedTokens,accountInFlightTokens:s.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)}},yTe=new yzn(process.env.NEUROLINK_PROXY_SOCKET_WORKER==="1"?"process":"supervisor"),jm=new Map,K4=new Set;function vLr(e){if(K4.size>=hTe){const t=K4.values().next().value;t&&K4.delete(t)}K4.add(e)}var wLr=!1;function vzn(){wLr||(wLr=!0,process.on("message",e=>{if(!e||typeof e!="object"||e.type!=="proxy-budget:response")return;const t=e,r=jm.get(t.rpcId);if(!r){K4.delete(t.rpcId)&&t.ok&&typeof t.leaseId=="string"&&t.leaseId.length<=128&&process.connected&&process.send&&process.send({type:"proxy-budget:request",rpcId:Wr(),pid:process.pid,generation:Number(process.env.NEUROLINK_PROXY_WORKER_GENERATION),action:"cancel",leaseId:t.leaseId},()=>{});return}jm.delete(t.rpcId),clearTimeout(r.timer),t.ok?r.resolve(t):r.reject(Fs(t.errorCode??"PROXY_TOKEN_BUDGET_UNAVAILABLE",t.error??"Token budget coordinator refused the request"))}),process.on("disconnect",()=>{for(const e of jm.values())clearTimeout(e.timer),e.reject(Fs("PROXY_TOKEN_BUDGET_UNAVAILABLE","Token budget supervisor disconnected"));jm.clear()}))}function vTe(e){return vzn(),new Promise((t,r)=>{if(!process.connected||!process.send||jm.size>=hTe){r(Fs("PROXY_TOKEN_BUDGET_UNAVAILABLE","Token budget supervisor IPC is unavailable"));return}const n=Wr(),o=setTimeout(()=>{jm.delete(n),e.action==="reserve"&&vLr(n),r(Fs("PROXY_TOKEN_BUDGET_UNAVAILABLE","Token budget supervisor response timed out; dispatch refused"))},hzn);jm.set(n,{resolve:t,reject:r,timer:o});const i=s=>{!s||!jm.has(n)||(clearTimeout(o),jm.delete(n),e.action==="reserve"&&vLr(n),r(Fs("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)},i)}catch(s){i(s instanceof Error?s:new Error("IPC failed"))}})}async function wTe(e){const t=fzn(e.policy);if(!gzn(t))return{leaseId:"disabled",snapshot:{scope:"disabled",reservationTokens:0,accountChargedTokens:0,accountInFlightTokens:0,sessionChargedTokens:0,sessionInFlightTokens:0,windowMs:t?.windowMs??s8,estimateProvenance:"disabled"},settle:async()=>{},cancelBeforeDispatch:async()=>{}};yLr(e);const r=process.env.NEUROLINK_PROXY_SOCKET_WORKER==="1",n={...e,policy:t},o=r?await vTe({action:"reserve",reservation:n}):yTe.reserve(n,"local");if(!o.leaseId||!o.snapshot)throw Fs("PROXY_TOKEN_BUDGET_UNAVAILABLE","Token budget supervisor returned incomplete reservation proof");const i=o.leaseId;let s=!1;const a={leaseId:i,snapshot:{...o.snapshot,scope:r?"supervisor":"process"},settle:async u=>{if(s)return;const l=r?(await vTe({action:"settle",leaseId:i,actualTotalTokens:u})).snapshot:yTe.settle(i,"local",u);s=!0,l&&(a.snapshot={...l,scope:r?"supervisor":"process"})},cancelBeforeDispatch:async()=>{if(s)return;const u=r?(await vTe({action:"cancel",leaseId:i})).snapshot:yTe.settle(i,"local",void 0,!0);s=!0,u&&(a.snapshot={...u,scope:r?"supervisor":"process"})}};return a}async function bTe(e,t){try{await e.settle(t)}catch{e.snapshot={...e.snapshot,settlement:"unconfirmed"}}}It(),H6(),Mr(),zh(),Jt();var bLr=new Map;function a8(e){return bLr.get(e)??bLr.get(e.replace(/:codex-fallback$/,""))}function pS(e){const t=typeof e.requestId=="string"?a8(e.requestId):void 0,r=Qt.getSpanContext(yt.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,i={...n,traceFlags:o};return LS(i)?{traceId:i.traceId,spanId:i.spanId,traceFlags:o}:void 0}function TTe(e){const t=pS(e);return t?Qt.setSpanContext(az,t):yt.active()}var wzn=async()=>{},_Yn=globalThis.crypto,EYn=globalThis.ReadableStream||class{},TLr=wzn,SYn=globalThis.URL,kYn=globalThis.URLSearchParams,_Te=e=>{try{return JSON.stringify(e,null,2)}catch{return String(e)}};_Te.custom=Symbol.for("nodejs.util.inspect.custom"),_Te.colors={},_Te.styles={};var bzn=globalThis.TextDecoder,_Lr=globalThis.TextEncoder,AYn=globalThis.performance||{now:()=>Date.now()},CYn=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),i=new Uint8Array(o.length);for(let s=0;s<o.length;s++)i[s]=o.charCodeAt(s);return i}if(n==="hex"){const o=new Uint8Array(t.length/2);for(let i=0;i<t.length;i+=2)o[i/2]=parseInt(t.substr(i,2),16);return o}return new _Lr().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((i,s)=>i+s.length,0),n=new Uint8Array(r);let o=0;for(const i of t)n.set(i,o),o+=i.length;return n}static byteLength(t,r){return r==="base64"?Math.ceil(t.length*3/4):new _Lr().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 bzn().decode(this)}},Tzn=e=>({[Symbol.toPrimitive](){return e},ref(){return this},unref(){return this},hasRef(){return!1},refresh(){return this},close(){}}),_zn=(...e)=>Tzn(globalThis.setTimeout(...e)),IYn=globalThis.clearTimeout,RYn=globalThis.clearInterval;br(),got(),wot(),H6(),Xx(),zh();var ELr=Gd(import.meta.url),u8,SLr,kLr,ALr=!1;function Ezn(){ALr||({ExportResultCode:u8,parseKeyPairsIntoRecord:SLr}=ELr("@opentelemetry/core"),{JsonLogsSerializer:kLr}=ELr("@opentelemetry/otlp-transformer"),ALr=!0)}var Szn=j6(RL),kzn=64*1024,Azn=5,Czn=new Set([429,502,503,504]),xzn=new Set(["ECONNRESET","ECONNREFUSED","EPIPE","ETIMEDOUT","EAI_AGAIN","ENOTFOUND","ENETUNREACH","EHOSTUNREACH"]),qo=class extends Error{constructor(e,t=!1,r){super(e),this.retryable=t,this.retryAfterMs=r,this.name="ProxyOtlpResponseError"}retryable;retryAfterMs};function Izn(e){return e instanceof qo&&e.retryable?e.retryAfterMs??0:void 0}function CLr(e){return process.env[`OTEL_EXPORTER_OTLP_LOGS_${e}`]?.trim()||process.env[`OTEL_EXPORTER_OTLP_${e}`]?.trim()||void 0}function ETe(e){const t=CLr(e);if(t)try{return xi(t)}catch{throw new Error(`Proxy OTLP ${e} file could not be read`)}}function Rzn(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 Mzn(e){let t;try{t=JSON.parse(e.toString("utf8"))}catch{throw new qo("OTLP response JSON is empty or malformed")}if(!t||typeof t!="object"||Array.isArray(t))throw new qo("OTLP response must be a JSON object");if(Object.keys(t).some(a=>a!=="partialSuccess"&&a!=="partial_success"))throw new qo("OTLP response has unexpected fields");if("partialSuccess"in t&&"partial_success"in t)throw new qo("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 qo("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 qo("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 qo("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 qo("OTLP partial success response is malformed");const i="rejectedLogRecords"in r?r.rejectedLogRecords:"rejected_log_records"in r?r.rejected_log_records:0;if(i===null||i===0||i==="0")return;const s=typeof i=="string"&&/^\d+$/.test(i)||typeof i=="number"&&Number.isSafeInteger(i)&&i>=0?BigInt(i):void 0;if(s===void 0||s>9223372036854775807n)throw new qo("OTLP rejected record count is malformed");if(s>0n)throw new qo("OTLP partial success rejected log records")}function Pzn(e,t){Ezn();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=CLr("COMPRESSION")??"none";if(n!=="none"&&n!=="gzip")throw new Error("Proxy OTLP compression must be none or gzip");const o={};try{for(const m of[process.env.OTEL_EXPORTER_OTLP_HEADERS,process.env.OTEL_EXPORTER_OTLP_LOGS_HEADERS])for(const[h,g]of Object.entries(SLr(m)))pot(h),mot(h,g),o[h.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 i={ca:ETe("CERTIFICATE"),cert:ETe("CLIENT_CERTIFICATE"),key:ETe("CLIENT_KEY")};if(!!i.cert!=!!i.key)throw new Error("Proxy OTLP client certificate and key must be set together");const s=r.protocol==="https:"?new MQ({keepAlive:!0,maxSockets:30,...i}):new IQ({keepAlive:!0,maxSockets:30}),a=r.protocol==="https:"?yot:hot;let u=!1;const l=new Set,c=new Set,d=(m,h)=>new Promise((g,y)=>{let v=!1;const w=a(r,{method:"POST",agent:s,signal:h,headers:{...o,"content-length":String(m.byteLength)}},b=>{v=!0;const E=b.statusCode??0,k=P=>{y(P),b.destroy()};if(E!==200){k(new qo(`OTLP HTTP ${E}`,Czn.has(E),Rzn(b.headers["retry-after"])));return}const A=b.headers["content-encoding"];if(A&&A!=="identity"){k(new qo("OTLP response encoding is unsupported"));return}const C=b.headers["content-type"];if(C&&C.split(";",1)[0].trim().toLowerCase()!=="application/json"){k(new qo("OTLP response content type is not JSON"));return}const M=[];let x=0;b.on("data",P=>{if(x+=P.length,x>kzn){k(new qo("OTLP response exceeds 64 KiB limit"));return}M.push(P)}),b.on("aborted",()=>y(new qo("OTLP success response was interrupted"))),b.on("error",()=>y(new qo("OTLP success response could not be read"))),b.on("end",()=>{try{Mzn(Buffer.concat(M)),g()}catch(P){y(P)}})});w.on("error",b=>y(new qo(h.aborted?"OTLP export deadline exceeded":"OTLP transport failed",!v&&(h.aborted||xzn.has(b.code??""))))),w.end(m)}),p=async m=>{const h=new AbortController;c.add(h);const g=Date.now()+t,y=setTimeout(()=>h.abort(),t);y.unref();try{const v=kLr.serializeRequest(m);if(!v)throw new qo("OTLP serialization produced no payload");const w=n==="gzip"?await Szn(v):v;let b=0;for(;!h.signal.aborted&&Date.now()<g;){b++;try{await d(w,h.signal);return}catch(E){if(!(E instanceof qo)||!E.retryable)throw E;if(b>=Azn)throw new qo("OTLP retry attempt limit reached",!0,E.retryAfterMs);const k=Math.min(5e3,1e3*2**Math.min(b-1,3)),A=Math.max(E.retryAfterMs??0,k*(.8+Math.random()*.4));if(A>=g-Date.now())throw new qo("OTLP retry exceeds export deadline",!0,A);await _zn(A,void 0,{signal:h.signal})}}throw new qo("OTLP export deadline exceeded",!0)}catch(v){throw v instanceof qo?v:new qo(h.signal.aborted?"OTLP export deadline exceeded":"OTLP export failed",h.signal.aborted)}finally{clearTimeout(y),c.delete(h)}};return{abortPending(){u=!0;for(const m of c)m.abort();s.destroy()},export(m,h){if(u){h({code:u8.FAILED,error:new Error("OTLP transport is shut down")});return}const g=p(m).then(()=>h({code:u8.SUCCESS}),y=>h({code:u8.FAILED,error:y}));l.add(g),g.finally(()=>l.delete(g)).catch(()=>{})},async forceFlush(){await Promise.allSettled(l)},async shutdown(){u=!0,await Promise.allSettled(l),s.destroy()}}}It(),Mt(),Or(),Mr(),H6(),Xx();var MYn=1024*1024,PYn=8*1024*1024,DYn=j6(RL);function xLr(e,t){if(!e)return[""];const r=[],n=Buffer.from(e,"utf8");for(let o=0;o<n.length;){let i=Math.min(o+Math.max(4,t),n.length);for(;i<n.length&&(n[i]&192)===128;)i-=1;r.push(n.subarray(o,i).toString("utf8")),o=i}return r}var l8=Gd(import.meta.url),ILr,$v,RLr,MLr,PLr,DLr=!1;function Dzn(){DLr||({SeverityNumber:ILr}=l8("@opentelemetry/api-logs"),{ExportResultCode:$v}=l8("@opentelemetry/core"),{resourceFromAttributes:RLr}=l8("@opentelemetry/resources"),{BatchLogRecordProcessor:MLr,LoggerProvider:PLr}=l8("@opentelemetry/sdk-logs"),DLr=!0)}var mS,c8=[],Fv=new Map,OLr=new WeakMap,NLr=new Set,d8=!1,Ozn=128*1024,LLr=3e4,STe=LLr+1e3,Nzn=2e4,$Lr=12e4,Lzn=new Set(["console","runtime","telemetry_delivery"]);function $zn(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 Zi={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 nc(){return process.env.NEUROLINK_PROXY_LOG_SINK==="otel"}function p8(e,t,r,n){const o=new Set,i=new WeakMap,s=new WeakMap,a=new Set,u=r==="metadata"||r==="indexes"?$Lr:0,l=new Set,c=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},p=[];let m=!1;const h=(k,A,C)=>{const M=(P,D)=>{const L=P.attributes[D];return typeof L=="string"?L.slice(0,128):void 0},x={id:Wr(),at:new Date().toISOString(),reason:A,...C?{error:er(C.message).slice(0,256)}:{},records:k.slice(0,64).map(P=>({eventId:M(P,"proxy.event_id")??"unavailable",kind:M(P,"proxy.record_kind"),requestId:M(P,"request.id"),captureId:M(P,"body.capture_id")}))};d.recentFailures.length===16&&(d.recentFailures.shift(),d.failureHistoryEvicted++),d.recentFailures.push(x),k.some(P=>P.attributes["proxy.record_kind"]!=="telemetry_delivery")&&(p.length===16&&p.shift(),p.push(x))},g=()=>{m||!p.length||d8||(m=!0,queueMicrotask(()=>{m=!1;for(const k of p.splice(0))hS("telemetry_delivery",{queue:r,...k})}))},y=Pzn(e,LLr),v={export(k,A){const C=performance.now();for(const q of k){const H=q.attributes["body.capture_id"],ne=typeof H=="string"?Fv.get(H):void 0;ne&&(ne.maxChunkQueueWaitMs=Math.max(ne.maxChunkQueueWaitMs??0,C-(i.get(q)??C)))}let M=!1,x=!1,P,D,L,O=0;const U=Math.min(...k.map(q=>i.get(q)??C))+u,$=()=>{P&&L&&G(L)};a.add($);const G=q=>{if(!M){M=!0,clearTimeout(D),clearTimeout(P),a.delete($),x&&(d.retryingRecords-=k.length),d.outstanding-=k.length,q.code===$v.SUCCESS?(d.transportAcknowledged+=k.length,d.lastAcknowledgedAt=new Date().toISOString(),g()):(d.exportUnconfirmed+=k.length,d.lastFailureAt=new Date().toISOString(),h(k,"export_unconfirmed",q.error));for(const H of k){o.delete(H),d.outstandingBytes-=s.get(H)??0;const ne=H.attributes?.["body.capture_id"],X=typeof ne=="string"?Fv.get(ne):void 0;if(X){X.maxChunkExportMs=Math.max(X.maxChunkExportMs??0,performance.now()-C);const oe=OLr.get(X);q.code===$v.SUCCESS&&(oe===void 0||Date.now()<oe)?X.acknowledged++:X.unconfirmed++,X.notify?.()}}for(const H of l)H();for(const H of c)H();A(q)}},B=()=>{if(P=void 0,u&&performance.now()>=U){d.retentionExpired+=k.length,G({code:$v.FAILED,error:new Error("OTLP metadata retention budget exceeded")});return}O++,O>1&&d.retriedBatches++;let q=!1;const H=ne=>{if(q||M)return;q=!0,clearTimeout(D);const X=ne.code===$v.FAILED?Izn(ne.error):void 0;if(u&&X!==void 0&&!d8){d.lastTransientFailureAt=new Date().toISOString();const oe=Math.max(X,Math.min(1e4,1e3*2**Math.min(O-1,4))*(.8+Math.random()*.4));if(performance.now()+oe<U){x||(x=!0,d.retryingRecords+=k.length),L=ne,P=setTimeout(B,oe),P.unref();return}d.retentionExpired+=k.length}G(ne)};D=setTimeout(()=>H({code:$v.FAILED,error:new Error("OTLP export callback deadline exceeded")}),STe),D.unref();try{y.export(k,H)}catch(ne){H({code:$v.FAILED,error:ne instanceof Error?ne:new Error(String(ne))})}};B()},forceFlush:()=>y.forceFlush(),shutdown:()=>y.shutdown()},w=new MLr(v,{maxQueueSize:t,maxExportBatchSize:64,scheduledDelayMillis:r==="bodies"?25:1e3,exportTimeoutMillis:u+STe+1e3}),b={onEmit(k){k.attributes["proxy.event_id"]??=Wr(),d.attempted++;const A=k.attributes?.["body.capture_id"],C=typeof A=="string"?Fv.get(A):void 0;C&&C.emitted++;const M=$zn(k);if(d.outstanding>=t||d.outstandingBytes+M>n){d.dropped++,d.outstandingBytes+M>n&&d.byteLimitDrops++,h([k],"queue_full"),C&&(C.dropped++,C.notify?.());return}d.submitted++,d.outstanding++,d.outstandingBytes+=M,d.highWaterBytes=Math.max(d.highWaterBytes,d.outstandingBytes),s.set(k,M),o.add(k),i.set(k,performance.now()),d.highWaterOutstanding=Math.max(d.highWaterOutstanding,d.outstanding),w.onEmit(k)},forceFlush:async()=>{const k=new Set(o);try{await w.forceFlush()}finally{await new Promise(A=>{const C=()=>{[...k].some(M=>o.has(M))||(c.delete(C),A())};c.add(C),C()})}},shutdown:async()=>{try{await b.forceFlush()}finally{await w.shutdown()}}};return{state:d,processor:b,capacity:t,byteCapacity:n,retentionMs:u,kind:r,waitForCapacity:k=>new Promise(A=>{const C=setTimeout(()=>M(!1),Math.max(0,k-Date.now()));C.unref?.();const M=P=>{clearTimeout(C),l.delete(x),A(P)},x=()=>{Date.now()>=k?M(!1):d.outstanding<t&&M(!0)};l.add(x),x()}),abortPending:()=>y.abortPending(),stopRetention:()=>{for(const k of a)k()},oldestOutstandingAgeMs:()=>{let k=performance.now();for(const A of o)k=Math.min(k,i.get(A)??k);return o.size?Math.max(0,performance.now()-k):0}}}async function Fzn(e,t,r){Zi.attempted++;const n=Buffer.byteLength(t,"utf8");if(!mS||d8||Fv.has(e)||Zi.pending>=Zi.maxPending||Zi.pendingBytes+n>Zi.maxPendingBytes)return Zi.rejected++,{status:"rejected",acknowledgedChunks:0,unconfirmedChunks:0,droppedChunks:0,reason:Fv.has(e)?"body_capture_id_in_use":!mS||d8?"body_exporter_unavailable":"body_publication_queue_full"};Zi.pending++,Zi.pendingBytes+=n,Zi.highWaterPending=Math.max(Zi.highWaterPending,Zi.pending),Zi.highWaterBytes=Math.max(Zi.highWaterBytes,Zi.pendingBytes);const o={acknowledged:0,unconfirmed:0,dropped:0,emitted:0};Fv.set(e,o);let i;const s=(async()=>{const a=c8.find(b=>b.kind==="bodies");if(!a)return{status:"rejected",acknowledgedChunks:0,unconfirmedChunks:0,droppedChunks:0,reason:"body_exporter_unavailable"};const u=performance.now(),l=Date.now()+Nzn;OLr.set(o,l);const c=xLr(t,Ozn);let d=0,p;try{for(let b=0;b<c.length;b++){for(;a.state.outstanding>=a.capacity;){const E=performance.now(),k=await a.waitForCapacity(l);if(d+=performance.now()-E,!k){p="body_publication_deadline";break}}if(Date.now()>=l){p="body_publication_deadline";break}r(c[b],b,c.length),b%4===3&&await TLr()}}catch{p="body_publication_failed"}const m=new Promise(b=>{const E=()=>{o.acknowledged+o.unconfirmed+o.dropped>=o.emitted&&(o.notify=void 0,b())};o.notify=E,E()});let h;const g=await Promise.race([m.then(()=>!0),new Promise(b=>{h=setTimeout(()=>b(!1),Math.max(0,l-Date.now())),h.unref?.()})]).finally(()=>clearTimeout(h));g||(i=m),(!g||Date.now()>=l)&&(p??="body_publication_deadline"),!p&&o.unconfirmed?p="body_export_unconfirmed":!p&&o.dropped&&(p="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!==c.length?"partial":v?"export_unconfirmed":"transport_acknowledged",expectedChunks:c.length,acknowledgedChunks:o.acknowledged,unconfirmedChunks:v,droppedChunks:o.dropped,notSubmittedChunks:c.length-o.emitted,publicationMs:performance.now()-u,capacityWaitMs:d,maxChunkQueueWaitMs:o.maxChunkQueueWaitMs??0,maxChunkExportMs:o.maxChunkExportMs??0,...p?{reason:p}:{}}})();NLr.add(s);try{const a=await s;return a.status==="transport_acknowledged"?Zi.transportAcknowledged++:a.status==="export_unconfirmed"?Zi.exportUnconfirmed++:a.status==="rejected"?Zi.rejected++:Zi.partial++,a}finally{NLr.delete(s);const a=()=>{Fv.delete(e),Zi.pending--,Zi.pendingBytes-=n};i?i.then(a,a):a()}}function FLr(e="worker"){if(!nc())return;if(mS)return mS;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 u=new URL(a);if(!["http:","https:"].includes(u.protocol))throw new Error("Proxy OTLP logs endpoint must use HTTP or HTTPS");const l=["localhost","127.0.0.1","[::1]"].includes(u.hostname);if(u.protocol==="http:"&&!l)throw new Error("Proxy OTLP logs require HTTPS for non-loopback collectors")}Dzn();const n=p8(t,2048,"metadata",8*1024*1024),o=p8(r,256,"bodies",40*1024*1024),i=p8(t,512,"diagnostics",2*1024*1024),s=p8(t,1024,"indexes",8*1024*1024);return c8.push(n,o,i,s),mS=new PLr({forceFlushTimeoutMillis:$Lr+STe+2e3,resource:RLr({"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,u){(a.attributes?.["proxy.record_kind"]==="body"?o:a.attributes?.["proxy.record_kind"]==="body_capture_index"?s:a.attributes?.["proxy.lifecycle.event"]==="runtime_sample"||Lzn.has(String(a.attributes?.["proxy.record_kind"]))?i:n).processor.onEmit(a,u)},forceFlush:async()=>{await Promise.all(c8.map(a=>a.processor.forceFlush()))},shutdown:async()=>{await Promise.all(c8.map(a=>a.processor.shutdown()))}}]}),mS}function hS(e,t){if(nc())try{const r=typeof t.requestId=="string"&&!t.traceId?a8(t.requestId):void 0,n=r?{...t,...r}:t;FLr()?.getLogger("neurolink-proxy-events").emit({context:TTe(n),severityNumber:ILr.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{Uzn++}}var Uzn=0;Mr();var ULr=1024,BLr=5*6e4;function Bzn(e={}){const t=e.now??(()=>performance.now()),r=e.bytesPerMinute?.trim(),n=r?Number(r):null,o=n!==null&&(!Number.isSafeInteger(n)||n<=0),i=new Map;let s=n??1/0,a=t(),u=0,l=0,c=0,d=0,p=0;const m=()=>{const h=t();n!==null&&!o&&(s=Math.min(n,s+Math.max(0,h-a)*n/6e4)),a=h;for(const[g,y]of i)y.expiresAt<=h&&i.delete(g)};return{snapshot(){return m(),{deduplicationEnabled:e.deduplicate!==!1,maxReferences:ULr,referenceTtlMs:BLr,references:i.size,byteBudgetPerMinute:o?null:n,invalidByteBudget:o,availableBytes:n===null||o?null:Math.floor(s),submittedBytes:u,deduplicatedCaptures:l,deduplicatedBytes:c,policyExcludedCaptures:d,policyExcludedBytes:p}},async publish(h,g,y){if(m(),g.redactedBody===void 0)return{};const v=Buffer.byteLength(g.redactedBody,"utf8"),w=e.deduplicate!==!1&&g.bodySha256&&h.captureId?JSON.stringify([h.requestId,g.bodySha256,v]):void 0,b=w?i.get(w):void 0;if(b&&b.reference.captureId!==h.captureId&&await b.acknowledged&&b.expiresAt>t())return l++,c+=v,{delivery:{status:"reference",reason:"identical_redacted_payload"},reference:{...b.reference}};if(m(),o||v>s)return d++,p+=v,{delivery:{status:"policy_excluded",reason:o?"body_byte_budget_invalid":"body_byte_budget_exhausted"}};s-=v,u+=v;let E=()=>{};const k=w&&h.captureId&&g.bodySha256?{reference:{captureId:h.captureId,requestId:h.requestId,bodySha256:g.bodySha256,redactedBodyBytes:v,exportedAt:""},expiresAt:t()+BLr,acknowledged:new Promise(C=>{E=C})}:void 0;if(w&&k){if(i.size>=ULr){const C=i.keys().next().value;C!==void 0&&i.delete(C)}i.set(w,k)}let A=!1;try{const C=await y();return A=C?.status==="transport_acknowledged",k&&A&&(k.reference.exportedAt=new Date().toISOString()),{delivery:C}}finally{E(A),w&&!A&&i.get(w)===k&&i.delete(w)}}}}Sr(),aa(),z(),Ld(),Jf(),ro(),Ti(),Pqt();var J4=64,m8=32*1024*1024,zLr=64,GLr=32*1024*1024,zzn=2e4,Gzn=16*1024*1024,qLr=2e4,Uv,qzn,sg=0,jzn=0,ur={attempted:0,completed:0,rejected:0,failed:0,pending:0,pendingBytes:0,maxPending:J4,maxPendingBytes:m8,highWaterPending:0,highWaterBytes:0,waiting:0,waitingBytes:0,maxWaiting:zLr,maxWaitingBytes:GLr,highWaterWaiting:0,highWaterWaitingBytes:0,admissionWaits:0,admissionTimeouts:0,rejectionReasons:{}},X4=new Map,jLr=new Map,Bv=[],h8;function VLr(e){return Date.now()<sg||ur.pending>=J4||ur.pendingBytes+e>m8?!1:(ur.pending+=1,ur.pendingBytes+=e,ur.highWaterPending=Math.max(ur.highWaterPending,ur.pending),ur.highWaterBytes=Math.max(ur.highWaterBytes,ur.pendingBytes),!0)}function kTe(){if(Bv.length){if(Date.now()<sg){h8||(h8=setTimeout(()=>{h8=void 0,kTe()},Math.max(1,sg-Date.now())),h8.unref?.());return}for(let e=0;e<Bv.length&&!(ur.pending>=J4);){const t=Bv[e];if(!VLr(t.bytes)){e+=1;continue}Bv.splice(e,1),clearTimeout(t.timer),ur.waiting-=1,ur.waitingBytes-=t.bytes,t.resolve("admitted")}}}function Vzn(e){return ur.waiting>=zLr||ur.waitingBytes+e>GLr?Promise.resolve("queue_full"):(ur.admissionWaits+=1,ur.waiting+=1,ur.waitingBytes+=e,ur.highWaterWaiting=Math.max(ur.highWaterWaiting,ur.waiting),ur.highWaterWaitingBytes=Math.max(ur.highWaterWaitingBytes,ur.waitingBytes),new Promise(t=>{const r=setTimeout(()=>{const n=Bv.findIndex(o=>o.timer===r);n<0||(Bv.splice(n,1),ur.waiting-=1,ur.waitingBytes-=e,ur.admissionTimeouts+=1,t("timeout"),kTe())},zzn);r.unref?.(),Bv.push({bytes:e,queuedAt:Date.now(),resolve:t,timer:r})}))}function HLr(e){ur.pending-=1,ur.pendingBytes-=e,kTe()}function Hzn(e,t){const r=[e],n=new Set;let o=0,i=0;for(;r.length;){if(++i>1e5)throw new Error("body_capture_traversal_limit");if(o>t)return o;const s=r.pop();if(typeof s=="string"){o+=16+s.length*2;continue}if(o+=16,!(!s||typeof s!="object")){if(n.has(s))throw new Error("body_capture_unsupported_value");if(n.add(s),!Array.isArray(s)&&Object.getPrototypeOf(s)!==Object.prototype&&Object.getPrototypeOf(s)!==null)throw new Error("body_capture_unsupported_value");for(const a of Object.keys(s)){o+=16+a.length*2;const u=Object.getOwnPropertyDescriptor(s,a);if(!u||u.get||u.set)throw new Error("body_capture_unsupported_value");if(r.push(u.value),r.length>1e5)throw new Error("body_capture_traversal_limit");if(o>t)return o}}}return o}function ATe(e,t){const r=X4.get(e);r&&(X4.delete(e),clearTimeout(r.timer),r.resolve(t),X4.size||Uv?.unref())}function CTe(e,t){if(Uv===e){Uv=void 0,sg=Date.now()+5e3;for(const r of X4.keys())ATe(r,{error:t,stored:{bodyWriteFailed:!0}});e.terminate().catch(()=>{})}}function Wzn(){if(Uv)return Uv;const e=new tie(qzn??new URL("./bodyCaptureWorkerEntry.js",import.meta.url),{execArgv:process.execArgv.filter(t=>!t.startsWith("--input-type")),resourceLimits:{maxOldGenerationSizeMb:128}});return Uv=e,e.on("message",t=>{Uv===e&&ATe(t.id,t.result)}),e.on("error",()=>CTe(e,"body_worker_error")),e.on("exit",()=>CTe(e,"body_worker_exit")),e.unref(),e}async function Kzn(e,t,r){ur.attempted+=1;const n=Date.now(),o=t===null?m8:Gzn;let i,s;try{i=Hzn(e,o)}catch(d){i=1/0,s=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(i<=o&&Date.now()>=sg&&(a=VLr(i)?"admitted":t===null?await Vzn(i):"queue_full"),a!=="admitted"){ur.rejected+=1;const d=i>o?s??"body_capture_entry_too_large":Date.now()<sg?"body_worker_backoff":a==="timeout"?"body_capture_admission_timeout":"body_capture_queue_full";return ur.lastError=d,ur.lastRejectedAt=new Date().toISOString(),ur.rejectionReasons[d]=(ur.rejectionReasons[d]??0)+1,r({error:d,stored:{bodyWriteFailed:!0},admissionWaitMs:Math.max(0,Date.now()-n),admission:{limitingResource:i>o?"entry":Date.now()<sg?"worker":ur.pending>=J4?"captures":"bytes",estimatedBytes:Number.isFinite(i)?i:void 0,maxEntryBytes:o,pending:ur.pending,pendingBytes:ur.pendingBytes,maxPending:J4,maxPendingBytes:m8}})}const u=Date.now();let l;try{l=Wzn()}catch{return sg=Date.now()+5e3,HLr(i),ur.failed+=1,r({error:"body_worker_start_failed",stored:{bodyWriteFailed:!0}})}const c=++jzn;return new Promise(d=>{const p=setTimeout(()=>CTe(l,"body_worker_timeout"),qLr);p.unref(),X4.set(c,{timer:p,startedAt:Date.now(),resolve:m=>{jLr.set(c,Date.now()),m.admissionWaitMs=Math.max(0,u-n),m.workerQueueWaitMs=Math.max(0,(m.queueWaitMs??0)-m.admissionWaitMs),r(m).catch(()=>{m.error??="body_capture_publication_failed"}).finally(()=>{jLr.delete(c),HLr(i),m.error||m.stored.bodyWriteFailed?ur.failed+=1:ur.completed+=1,m.error&&(ur.lastError=m.error),d()})}}),l.ref();try{l.postMessage({id:c,entry:e,logDir:t,queuedAt:n})}catch{ATe(c,{error:"body_capture_clone_failed",stored:{bodyWriteFailed:!0}})}})}Jt(),PM();var WLr=new FS;function bp(){return WLr.getStore()}function f8(){return WLr.getStore()!==void 0}zh();var Jzn=class{export(){}shutdown(){return Promise.resolve()}};qrt();var Xzn=class{constructor(){}getLogger(){return{emit(){}}}forceFlush(){return Promise.resolve()}shutdown(){return Promise.resolve()}},Yzn=class{onStart(){}onEnd(){}shutdown(){return Promise.resolve()}forceFlush(){return Promise.resolve()}};Hr();var Zzn=Gd(import.meta.url),fS,KLr=!1;function JLr(){KLr||({SeverityNumber:fS}=Zzn("@opentelemetry/api-logs"),KLr=!0)}var gS=null,xTe=!1,Qzn=Bzn(),ITe=new Set,RTe=5e3,OYn=qLr+2*RTe,eGn=4096,g8=new Map,tGn=Fre,MTe=()=>({attempted:0,written:0,inFlight:0,pending:0,dropped:0,writeTimeouts:0,unconfirmedWrites:0}),rGn={requests:MTe(),attempts:MTe(),debug:MTe()};async function PTe(e,t,r,n={}){const o=rGn[r];if(o.attempted+=1,o.pending+o.inFlight>=eGn){o.dropped+=1;return}o.pending+=1;const i=XLr((g8.get(e)??Promise.resolve()).then(async()=>{o.pending-=1,o.inFlight+=1;const s=setTimeout(()=>{o.writeTimeouts+=1},RTe);s.unref?.();try{await tGn(e,t,{mode:384,flag:"a"}),o.written+=1}catch(a){o.unconfirmedWrites+=1,o.lastErrorCode=a?.code??"UNKNOWN"}finally{clearTimeout(s),o.inFlight-=1}}));if(g8.set(e,i),i.then(()=>{g8.get(e)===i&&g8.delete(e)}),n.waitForPersistence)return i;await kt(i,RTe,"Proxy metadata write remains pending").catch(()=>{})}function XLr(e){return ITe.add(e),e.then(()=>ITe.delete(e),()=>ITe.delete(e)),e}var YLr,ZLr=!1,nGn=16e3;function oGn(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,i=e.cacheCreation1hTokens;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||i!==void 0&&(!Number.isFinite(i)||i<0||i>o)||e.inputIncludesCachedTokens===!0&&n+o>t||e.inputIncludesCachedTokens===!0&&(e.cacheReadTokensObserved===!1||e.cacheCreationTokensObserved===!1)){e.pricingStatus="usage_incomplete";return}if(!Xp(e.pricingProvider,e.model)){e.pricingStatus="unavailable";return}if(!oee(e.pricingProvider,e.model)){e.pricingStatus="inferred";return}const s=Pm({inputTokens:t,outputTokens:r,cacheReadTokens:n,cacheCreationTokens:o,inputIncludesCachedTokens:e.inputIncludesCachedTokens,...e.cacheCreation1hTokens!==void 0?{cacheCreation1hTokens:e.cacheCreation1hTokens}:{}});e.pricingStatus="exact",e.apiEquivalentCostUsd=Il(e.pricingProvider,e.model,s);const a=Il(e.pricingProvider,e.model,{...s,input:s.input+(s.cacheReadTokens??0),cacheReadTokens:0});e.apiEquivalentCacheSavingsUsd=Math.max(0,Math.round((a-e.apiEquivalentCostUsd)*1e6)/1e6)}async function yS(e){if(Object.assign(e,sS(e.requestId)),oGn(e),!e.traceId||e.traceFlags===void 0){const n=pS(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",!A8n(e)||!xTe||!gS&&!nc())return;if(nc()){await e6r(e);return}const t=$t(gS,`proxy-${new Date().toISOString().split("T")[0]}.jsonl`),r=JSON.stringify(e)+`
2382
2382
  `;try{await PTe(t,r,"requests")}catch{}e6r(e)}async function DTe(e){if(!e.traceId||e.traceFlags===void 0){const n=pS(e);n&&(e.traceId=n.traceId,e.spanId=n.spanId,e.traceFlags=n.traceFlags)}if(Object.assign(e,sS(e.requestId)),C8n(e),!xTe||!gS&&!nc())return;if(nc()){hS("attempt",e);return}const t=$t(gS,`proxy-attempts-${new Date().toISOString().split("T")[0]}.jsonl`),r=JSON.stringify(e)+`
2383
2383
  `;try{await PTe(t,r,"attempts")}catch{}}function iGn(){const e=process.env.OTEL_EXPORTER_OTLP_ENDPOINT;if(e)try{return new Xzn({resource:dN({"service.name":process.env.OTEL_SERVICE_NAME||"neurolink"}),processors:[new Yzn(new Jzn({url:`${e}/v1/logs`}),{maxQueueSize:2048,maxExportBatchSize:64,scheduledDelayMillis:2e3,exportTimeoutMillis:3e4})]})}catch(t){f.warn("[RequestLogger] Failed to create OTLP log exporter",{error:t instanceof Error?t.message:String(t)});return}}async function QLr(){return nc()?FLr():(ZLr||(ZLr=!0,YLr=iGn()),YLr)}function e6r(e){return QLr().then(t=>{if(!t)return;JLr();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,i=n?o?fS.WARN:fS.ERROR:fS.INFO,s=n?o?"WARN":"ERROR":"INFO";r.emit({context:TTe(e),severityNumber:i,severityText:s,body:nc()?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 t6r(e,t){return QLr().then(async r=>{if(!r||t.redactedBody===void 0)return;JLr();const n=r.getLogger("neurolink-proxy-bodies","1.0.0"),o=e.captureId??Wr(),i=(a,u,l)=>{n.emit({context:TTe(e),severityNumber:(e.responseStatus??0)>=400?fS.WARN:fS.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":u,"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(nc())return Fzn(o,t.redactedBody,i);const s=xLr(t.redactedBody,nGn);for(let a=0;a<s.length;a++)a>0&&a%4===0&&await TLr(),i(s[a],a,s.length)}).catch(()=>{})}function OTe(){return xTe&&(!!gS||nc())}async function vS(e){if(!OTe())return;if(f8()){hS("body_capture_index",{timestamp:e.timestamp,requestId:e.requestId,captureId:e.captureId??Wr(),phase:e.phase,bodyDelivery:{status:"policy_excluded",reason:"borrowed_traffic"}});return}const t=pS(e),r=gS,n={...e,captureId:e.captureId??Wr(),body:void 0},i=XLr(Kzn(e,r,async s=>{const a=s.headers,u=s.stored,l=new Date(n.timestamp).toISOString().split("T")[0],c=r?$t(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:u.bodyPath,bodySha256:u.bodySha256,observedBodyBytes:n.bodySize,redactedBodyBytes:u.redactedBodyBytes,storedFileBytes:u.storedFileBytes,bodyTruncated:u.bodyTruncated,bodyCaptureLimitBytes:u.bodyCaptureLimitBytes,originalRedactedBodyBytes:u.originalRedactedBodyBytes,inputRetainedBytes:u.inputRetainedBytes,inputEncoding:u.inputEncoding,sourceTruncated:u.sourceTruncated,processingTruncated:u.processingTruncated,redactionLossy:u.redactionLossy,unparseableRedactedFrames:u.unparseableRedactedFrames,bodyWriteFailed:u.bodyWriteFailed,captureError:s.error,captureAdmission:s.admission,captureQueueWaitMs:s.queueWaitMs,captureProcessingMs:s.processingMs,captureAdmissionWaitMs:s.admissionWaitMs,captureWorkerQueueWaitMs:s.workerQueueWaitMs,metadata:s.error?void 0:n.metadata};if(t&&(d.traceId=t.traceId,d.spanId=t.spanId,d.traceFlags=t.traceFlags),nc()){const p=await Qzn.publish(n,u,()=>t6r({...n,traceId:t?.traceId??n.traceId,spanId:t?.spanId??n.spanId,traceFlags:t?.traceFlags??n.traceFlags},u));d.bodyReference=p.reference,d.bodyDelivery=p.delivery??{status:s.error?"capture_rejected":u.redactedBody===void 0?"no_body":"export_unconfirmed",...s.error?{reason:s.error}:{}},hS("body_capture_index",d);return}try{c&&await PTe(c,JSON.stringify(d)+`
2384
2384
  `,"debug",{waitForPersistence:!0})}catch{}await t6r({...n,traceId:t?.traceId??n.traceId,spanId:t?.spanId??n.spanId,traceFlags:t?.traceFlags??n.traceFlags},u)}));if(!nc())return i}var sGn=1024*1024,aGn=16*1024*1024,NTe=0;function r6r(e,t,r,n){const o=i=>{vS({timestamp:new Date().toISOString(),requestId:e.requestId,model:t,stream:r,durationMs:Date.now()-n,...i})};return{log:o,request(){o({phase:"client_request",headers:e.headers,body:e.body,contentType:"application/json"})},json(i,s){o({phase:"client_response",headers:{"content-type":"application/json"},body:i,contentType:"application/json",responseStatus:s})},accumulator(i,s,a){const u=OTe(),l=[];let c=0,d=0,p=!1,m=!1;const h=g=>{if(m||!u)return;c+=g.byteLength;const y=Math.min(sGn-d,aGn-NTe);if(!p&&y>0){const v=Uint8Array.from(g.subarray(0,y));l.push(v),d+=v.byteLength,NTe+=v.byteLength,p=v.byteLength!==g.byteLength}else p||=g.byteLength>0};return{append:h,appendEvent(g){if(!(m||!u))try{h(new TextEncoder().encode(`data: ${JSON.stringify(g)??"null"}
@@ -297,6 +297,7 @@ function createTrackedProcessor(url, capacity, kind, byteCapacity) {
297
297
  };
298
298
  send();
299
299
  },
300
+ forceFlush: () => transport.forceFlush(),
300
301
  shutdown: () => transport.shutdown(),
301
302
  };
302
303
  const batch = new BatchLogRecordProcessor(exporter, {
@@ -363,6 +363,9 @@ export function createProxyOtlpLogTransport(endpoint, timeoutMillis) {
363
363
  active.add(operation);
364
364
  void operation.finally(() => active.delete(operation)).catch(() => { });
365
365
  },
366
+ async forceFlush() {
367
+ await Promise.allSettled(active);
368
+ },
366
369
  async shutdown() {
367
370
  closed = true;
368
371
  await Promise.allSettled(active);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@juspay/neurolink",
3
- "version": "13.10.2",
3
+ "version": "13.10.3",
4
4
  "packageManager": "pnpm@10.34.9+sha512.f49b5a8ea0fdedb44bb3c0c1d6575092a53c2950d95b7ad15df11f17974877a2de3a01c07e934e9b28ce716e51c09a94962c7306d09be2e1e4b18a8c8762fd32",
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": {
@@ -537,18 +537,18 @@
537
537
  "@langfuse/core": "5.13.1",
538
538
  "@langfuse/tracing": "5.13.1",
539
539
  "@modelcontextprotocol/sdk": "1.32.2",
540
- "@opentelemetry/api-logs": "0.214.0",
541
- "@opentelemetry/context-async-hooks": "2.6.1",
540
+ "@opentelemetry/api-logs": "0.219.0",
541
+ "@opentelemetry/context-async-hooks": "2.8.0",
542
542
  "@opentelemetry/core": "2.8.0",
543
- "@opentelemetry/exporter-logs-otlp-http": "0.214.0",
544
- "@opentelemetry/exporter-metrics-otlp-http": "0.214.0",
545
- "@opentelemetry/exporter-trace-otlp-http": "0.214.0",
546
- "@opentelemetry/otlp-transformer": "0.214.0",
547
- "@opentelemetry/resources": "2.6.1",
548
- "@opentelemetry/sdk-logs": "0.214.0",
549
- "@opentelemetry/sdk-metrics": "2.6.1",
550
- "@opentelemetry/sdk-trace-base": "2.6.1",
551
- "@opentelemetry/sdk-trace-node": "2.6.1",
543
+ "@opentelemetry/exporter-logs-otlp-http": "0.219.0",
544
+ "@opentelemetry/exporter-metrics-otlp-http": "0.219.0",
545
+ "@opentelemetry/exporter-trace-otlp-http": "0.219.0",
546
+ "@opentelemetry/otlp-transformer": "0.219.0",
547
+ "@opentelemetry/resources": "2.8.0",
548
+ "@opentelemetry/sdk-logs": "0.219.0",
549
+ "@opentelemetry/sdk-metrics": "2.8.0",
550
+ "@opentelemetry/sdk-trace-base": "2.8.0",
551
+ "@opentelemetry/sdk-trace-node": "2.8.0",
552
552
  "@opentelemetry/semantic-conventions": "1.40.0",
553
553
  "@types/json-schema": "7.0.15",
554
554
  "@types/ws": "8.18.1",
@@ -793,8 +793,8 @@
793
793
  "archiver-utils>glob": "14.0.2",
794
794
  "readdir-glob>minimatch": "11.0.2",
795
795
  "@semantic-release/npm": "^13.1.4",
796
- "@opentelemetry/sdk-trace-base": "^2.6.0",
797
- "@opentelemetry/sdk-trace-node": "^2.6.0",
796
+ "@opentelemetry/sdk-trace-base@<2.8.0": "2.8.0",
797
+ "@opentelemetry/sdk-trace-node@<2.8.0": "2.8.0",
798
798
  "jws@<4.0.1": ">=4.0.1",
799
799
  "tar@<7.5.8": ">=7.5.8",
800
800
  "qs@<6.16.0": ">=6.16.0",