@juspay/neurolink 12.18.0 → 12.18.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,8 @@
|
|
|
1
|
-
## [12.18.
|
|
1
|
+
## [12.18.1](https://github.com/juspay/neurolink/compare/v12.18.0...v12.18.1) (2026-09-20)
|
|
2
2
|
|
|
3
|
-
###
|
|
3
|
+
### Bug Fixes
|
|
4
4
|
|
|
5
|
-
- **(proxy):**
|
|
5
|
+
- **(proxy):** stop history truncation discarding turns to reach a user head ([a1f6258](https://github.com/juspay/neurolink/commit/a1f6258f1dbc6b0a49d095f4ddd9c29eba4764fb))
|
|
6
6
|
|
|
7
7
|
## [11.2.3](https://github.com/juspay/neurolink/compare/v11.2.2...v11.2.3) (2026-08-19)
|
|
8
8
|
|
|
@@ -2314,7 +2314,7 @@ data: ${r}
|
|
|
2314
2314
|
`))_.startsWith("event:")?w=_.slice(6).trim():_.startsWith("data:")&&E.push(_.slice(5).trim());w&&E.length>0&&h(w,E.join(`
|
|
2315
2315
|
`),g),y=s.indexOf(`
|
|
2316
2316
|
|
|
2317
|
-
`)}};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))}}})}hl(),ss();function TA(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Men(e){return TA(e)&&typeof e.role=="string"&&e.role!=="user"}function drr(e){return Array.isArray(e.content)?e.content:[e]}function Pen(e){if(!TA(e))return[];const t=[];e.type==="function_call"&&typeof e.call_id=="string"&&t.push(e.call_id);for(const r of drr(e))TA(r)&&r.type==="tool_use"&&typeof r.id=="string"&&t.push(r.id);return t}function Den(e){if(!TA(e))return[];const t=[];e.type==="function_call_output"&&typeof e.call_id=="string"&&t.push(e.call_id);for(const r of drr(e))TA(r)&&r.type==="tool_result"&&typeof r.tool_use_id=="string"&&t.push(r.tool_use_id);return t}function Oen(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 Den(s))n.delete(i);for(const i of Pen(s))n.add(i);n.size===0&&(t.push(r),r=[])}return r.length>0&&t.push(r),t}function Nen(e){if(Array.isArray(e.messages))return"messages";if(Array.isArray(e.conversationMessages))return"conversationMessages";if(Array.isArray(e.input))return"input"}function Len(e){const t={body:e.body,historyModified:!1,unitsRemoved:0,itemsRemoved:0},r=e.body,n=Nen(r);if(n===void 0)return t;const o=r[n],s=Oen(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&&Men(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 Os(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function sm(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>0}function Fen(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(!Os(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&&!sm(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(!Os(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=Os(n)?n.contextWindow:void 0,s=Os(n)?n.maxOutputTokens:void 0,i=Os(n)?n.compactAtTokens:void 0,a=Os(n)?n.compactToTokens:void 0;if(!r.includes("/")||!Os(n)||!sm(o)||s!==void 0&&!sm(s)||i!==void 0&&(!sm(i)||i>=o)||a!==void 0&&(!sm(a)||!sm(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 mrr,Use;function $en(){const e=process.env.NEUROLINK_PROXY_CONTEXT_POLICY;return(!Use||e!==mrr)&&(Use=Fen(e),mrr=e),Use}function V2(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)V2(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),Os(o.function)&&typeof o.function.name=="string"&&t.add(o.function.name)}typeof o.toolName=="string"&&t.add(o.toolName),Os(o.functionCall)&&typeof o.functionCall.name=="string"&&t.add(o.functionCall.name);for(const[s,i]of Object.entries(o))s!=="tools"&&V2(i,t,r,n+1)}function Uen(e){if(Os(e))return typeof e.name=="string"?e.name:Os(e.function)&&typeof e.function.name=="string"?e.function.name:void 0}function prr(e){return Array.isArray(e)?e.length:Os(e)?Object.keys(e).length:0}function ow(e,t,r,n=new WeakSet,o=0){if(typeof e=="string")return nr(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+ow(a,t,r,n,o+1)+4,0);const s=e;return e instanceof Uint8Array||e instanceof ArrayBuffer?(r.multimodal=!0,mM):typeof s.text=="string"&&Array.isArray(s.images)?(r.multimodal=s.images.length>0||r.multimodal,nr(s.text,t)+s.images.length*mM):["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,mM):Object.entries(s).reduce((i,[a,c])=>i+nr(a,t)+ow(c,t,r,n,o+1),0)}finally{n.delete(e)}}function Bse(e){const t=e.policy??$en(),r=e.body;let n=e.body;const o=r.tools;if(t.toolAllowlist){const N=new Set(t.toolAllowlist);V2(r,N),V2(e.toolReferenceBody,N);const U=r.tool_choice;Os(U)&&(typeof U.name=="string"&&N.add(U.name),Os(U.function)&&typeof U.function.name=="string"&&N.add(U.function.name));const P=Array.isArray(o)?o.filter(D=>{const F=Uen(D);return F===void 0||N.has(F)}):Os(o)?Object.fromEntries(Object.entries(o).filter(([D])=>N.has(D))):o;n={...e.body,tools:P,...Array.isArray(r.toolFilter)?{toolFilter:r.toolFilter.filter(D=>typeof D!="string"||N.has(D))}:{}}}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=ow(s.tools,l,i),d=[s.instructions,s.system,s.systemPrompt,s.systemInstruction].reduce((N,U)=>N+ow(U,l,i),0),m=[s.response_format,s.output_config,s.structuredOutput,s.schema,Os(s.text)?s.text.format:void 0,Os(s.generationConfig)?s.generationConfig.responseSchema:void 0,Os(s.generationConfig)?s.generationConfig.responseJsonSchema:void 0].reduce((N,U)=>N+ow(U,l,i),0),h=N=>ow(N,l,a),f=24+m+u+d,g=()=>[s.messages,s.input,s.contents,s.conversationMessages,s.prompt].reduce((N,U)=>N+h(U),0);let y=f+g();const T=t.models?.[`${e.provider}/${e.model}`];let w=!1,E=0;const _=y;if(T?.compactAtTokens!==void 0&&T.compactToTokens!==void 0&&y>T.compactAtTokens){const N=Len({body:n,inputTokensEstimate:y,targetTokens:T.compactToTokens,estimate:h});if(N.historyModified&&(n=N.body,s=n,w=!0,E=N.unitsRemoved,a={multimodal:!1},y=f+g()),y>T.compactToTokens)throw new _r("proxy_context_compaction_failed",`Compaction could not bring ${e.provider}/${e.model} within ${T.compactToTokens} tokens; ${y} remain after removing every removable unit`)}const k=t7(e.provider,e.model),C=T?.contextWindow??k,x=T?.maxOutputTokens??r7(e.provider,e.model),R=e.maxOutputTokens??s.max_tokens??s.max_output_tokens??s.maxTokens??(Os(s.generationConfig)?s.generationConfig.maxOutputTokens:void 0);if(R!==void 0&&!sm(R))throw new _r("invalid_output_budget","Requested output tokens must be a positive safe integer");const I=e.provider==="codex"?x??t.outputReserveTokens??32768:sm(R)?R:x??t.outputReserveTokens??32768,M={provider:e.provider,model:e.model,inputTokensEstimate:y,toolsTokensEstimate:u,instructionsTokensEstimate:d,schemaTokensEstimate:m,outputTokensReserve:I,reasoningIncludedInOutputReserve:!0,...C?{contextWindow:C}:{},contextLimitSource:T?"configured":k?"discovered":"unknown",tokenCountSource:"estimated",multimodalEstimate:c(),originalToolCount:prr(o),retainedToolCount:prr(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(x!==void 0&&sm(R)&&e.provider!=="codex"&&R>x)throw new _r("proxy_output_budget_exceeded","Requested output exceeds the serving model's known output limit",M);if(C!==void 0&&t.enforceDiscoveredLimits!==!1&&!c()&&y+I>C)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}}ln();var W2=60*6e4,Ben=1e4,zse=5e3,zen=2e3;function qse(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 Jy("sha256").update(t).digest("hex")}function ni(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 Vc(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 Gse(e){if(typeof e=="string")try{e=JSON.parse(e)}catch{throw ni("PROXY_TOKEN_BUDGET_CONFIG","Token budget configuration is not valid JSON")}if(!e||typeof e!="object"||Array.isArray(e))throw ni("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 ni("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 hrr(){const e=process.env.NEUROLINK_PROXY_TOKEN_BUDGET;return e===void 0||e.trim()===""?void 0:Gse(e)}function qen(e){const t=hrr(),r=e===void 0?void 0:Gse(e);if(!t)return r;if(!r)return t;const n={windowMs:Math.max(t.windowMs??W2,r.windowMs??W2)};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 Gen(e){return!!(e?.maxInFlightTokens||e?.accountWindowTokens||e?.sessionWindowTokens)}function frr(e){for(const t of["provider","accountKey","sessionKey","requestId"])if(typeof e[t]!="string"||e[t].length===0||e[t].length>512)throw ni("PROXY_TOKEN_BUDGET_INPUT","Token budget requires bounded provider, account, session and request identities");if(!Number.isSafeInteger(e.reservationTokens)||e.reservationTokens<=0)throw ni("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 ni("PROXY_TOKEN_BUDGET_INPUT","Token estimate provenance must be bounded text")}var Hen=class{constructor(e="supervisor",t=Date.now,r=Ben,n=zse){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 ni("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"){frr(e);const r=Gse(e.policy??{});if(this.leases.size>=this.maxLeases)throw ni("PROXY_TOKEN_BUDGET_CAPACITY","Token budget outstanding reservation capacity is full");const n=r.windowMs??W2,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 ni("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 ni("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=cn();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 ni("PROXY_TOKEN_BUDGET_OWNER","Token budget lease belongs to another worker");if(r!==void 0&&(!Number.isSafeInteger(r)||r<0))throw ni("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)}},Hse=new Hen(process.env.NEUROLINK_PROXY_SOCKET_WORKER==="1"?"process":"supervisor"),im=new Map,wA=new Set;function grr(e){if(wA.size>=zse){const t=wA.values().next().value;t&&wA.delete(t)}wA.add(e)}var yrr=!1;function jen(){yrr||(yrr=!0,process.on("message",e=>{if(!e||typeof e!="object"||e.type!=="proxy-budget:response")return;const t=e,r=im.get(t.rpcId);if(!r){wA.delete(t.rpcId)&&t.ok&&typeof t.leaseId=="string"&&t.leaseId.length<=128&&process.connected&&process.send&&process.send({type:"proxy-budget:request",rpcId:cn(),pid:process.pid,generation:Number(process.env.NEUROLINK_PROXY_WORKER_GENERATION),action:"cancel",leaseId:t.leaseId},()=>{});return}im.delete(t.rpcId),clearTimeout(r.timer),t.ok?r.resolve(t):r.reject(ni(t.errorCode??"PROXY_TOKEN_BUDGET_UNAVAILABLE",t.error??"Token budget coordinator refused the request"))}),process.on("disconnect",()=>{for(const e of im.values())clearTimeout(e.timer),e.reject(ni("PROXY_TOKEN_BUDGET_UNAVAILABLE","Token budget supervisor disconnected"));im.clear()}))}function jse(e){return jen(),new Promise((t,r)=>{if(!process.connected||!process.send||im.size>=zse){r(ni("PROXY_TOKEN_BUDGET_UNAVAILABLE","Token budget supervisor IPC is unavailable"));return}const n=cn(),o=setTimeout(()=>{im.delete(n),e.action==="reserve"&&grr(n),r(ni("PROXY_TOKEN_BUDGET_UNAVAILABLE","Token budget supervisor response timed out; dispatch refused"))},zen);im.set(n,{resolve:t,reject:r,timer:o});const s=i=>{!i||!im.has(n)||(clearTimeout(o),im.delete(n),e.action==="reserve"&&grr(n),r(ni("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 Vse(e){const t=qen(e.policy);if(!Gen(t))return{leaseId:"disabled",snapshot:{scope:"disabled",reservationTokens:0,accountChargedTokens:0,accountInFlightTokens:0,sessionChargedTokens:0,sessionInFlightTokens:0,windowMs:t?.windowMs??W2,estimateProvenance:"disabled"},settle:async()=>{},cancelBeforeDispatch:async()=>{}};frr(e);const r=process.env.NEUROLINK_PROXY_SOCKET_WORKER==="1",n={...e,policy:t},o=r?await jse({action:"reserve",reservation:n}):Hse.reserve(n,"local");if(!o.leaseId||!o.snapshot)throw ni("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 jse({action:"settle",leaseId:s,actualTotalTokens:c})).snapshot:Hse.settle(s,"local",c);i=!0,l&&(a.snapshot={...l,scope:r?"supervisor":"process"})},cancelBeforeDispatch:async()=>{if(i)return;const c=r?(await jse({action:"cancel",leaseId:s})).snapshot:Hse.settle(s,"local",void 0,!0);i=!0,c&&(a.snapshot={...c,scope:r?"supervisor":"process"})}};return a}async function Wse(e,t){try{await e.settle(t)}catch{e.snapshot={...e.snapshot,settlement:"unconfirmed"}}}Ut(),eD(),ln(),Yt();var vrr=new Map;function Kse(e){return vrr.get(e)??vrr.get(e.replace(/:codex-fallback$/,""))}function sw(e){const t=typeof e.requestId=="string"?Kse(e.requestId):void 0,r=dt.getSpanContext(mr.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 OF(s)?{traceId:s.traceId,spanId:s.spanId,traceFlags:o}:void 0}function Jse(e){const t=sw(e);return t?dt.setSpanContext(NF,t):mr.active()}var Ven=async()=>{},tln=globalThis.crypto,rln=globalThis.ReadableStream||class{},Trr=Ven,nln=globalThis.URL,oln=globalThis.URLSearchParams,Yse=e=>{try{return JSON.stringify(e,null,2)}catch{return String(e)}};Yse.custom=Symbol.for("nodejs.util.inspect.custom"),Yse.colors={},Yse.styles={};var Wen=globalThis.TextDecoder,wrr=globalThis.TextEncoder,sln=globalThis.performance||{now:()=>Date.now()},iln=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 wrr().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 wrr().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 Wen().decode(this)}},Ken=e=>({[Symbol.toPrimitive](){return e},ref(){return this},unref(){return this},hasRef(){return!1},refresh(){return this},close(){}}),Jen=(...e)=>Ken(globalThis.setTimeout(...e)),cln=globalThis.clearTimeout,lln=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};FV(),Yn(),SXe();var uln=globalThis.crypto,Yen=class{constructor(){throw new Error("[NeuroLink:browser] Node HTTP agents require a server runtime")}},dln=globalThis.ReadableStream||class{},Xen=()=>({}),mln=globalThis.URL,pln=globalThis.URLSearchParams,Xse=e=>{try{return JSON.stringify(e,null,2)}catch{return String(e)}};Xse.custom=Symbol.for("nodejs.util.inspect.custom"),Xse.colors={},Xse.styles={};var Zen=globalThis.TextDecoder,Err=globalThis.TextEncoder,hln=globalThis.performance||{now:()=>Date.now()},fln=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 Err().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 Err().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 Zen().decode(this)}},yln=globalThis.clearTimeout,vln=globalThis.clearInterval;eD(),Z4(),FV();var Qen={serializeRequest(){throw new Error("[NeuroLink:browser] proxy OTLP log transport requires a server runtime")}},etn=ZP(X4),ttn=64*1024,rtn=5,ntn=new Set([429,502,503,504]),otn=new Set(["ECONNRESET","ECONNREFUSED","EPIPE","ETIMEDOUT","EAI_AGAIN","ENOTFOUND","ENETUNREACH","EHOSTUNREACH"]),_o=class extends Error{constructor(e,t=!1,r){super(e),this.retryable=t,this.retryAfterMs=r,this.name="ProxyOtlpResponseError"}retryable;retryAfterMs};function Srr(e){return process.env[`OTEL_EXPORTER_OTLP_LOGS_${e}`]?.trim()||process.env[`OTEL_EXPORTER_OTLP_${e}`]?.trim()||void 0}function Zse(e){const t=Srr(e);if(t)try{return li(t)}catch{throw new Error(`Proxy OTLP ${e} file could not be read`)}}function stn(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 itn(e){let t;try{t=JSON.parse(e.toString("utf8"))}catch{throw new _o("OTLP response JSON is empty or malformed")}if(!t||typeof t!="object"||Array.isArray(t))throw new _o("OTLP response must be a JSON object");if(Object.keys(t).some(a=>a!=="partialSuccess"&&a!=="partial_success"))throw new _o("OTLP response has unexpected fields");if("partialSuccess"in t&&"partial_success"in t)throw new _o("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 _o("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 _o("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 _o("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 _o("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 _o("OTLP rejected record count is malformed");if(i>0n)throw new _o("OTLP partial success rejected log records")}function atn(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=Srr("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,f]of Object.entries(cmt(m)))yXe(h),vXe(h,f),o[h.toLowerCase()]=f}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:Zse("CERTIFICATE"),cert:Zse("CLIENT_CERTIFICATE"),key:Zse("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 Yen({keepAlive:!0,maxSockets:30,...s}):new gXe({keepAlive:!0,maxSockets:30}),a=r.protocol==="https:"?Xen:TXe;let c=!1;const l=new Set,u=(m,h)=>new Promise((f,g)=>{let y=!1;const T=a(r,{method:"POST",agent:i,signal:h,headers:{...o,"content-length":String(m.byteLength)}},w=>{y=!0;const E=w.statusCode??0,_=I=>{g(I),w.destroy()};if(E!==200){_(new _o(`OTLP HTTP ${E}`,ntn.has(E),stn(w.headers["retry-after"])));return}const k=w.headers["content-encoding"];if(k&&k!=="identity"){_(new _o("OTLP response encoding is unsupported"));return}const C=w.headers["content-type"];if(C&&C.split(";",1)[0].trim().toLowerCase()!=="application/json"){_(new _o("OTLP response content type is not JSON"));return}const x=[];let R=0;w.on("data",I=>{if(R+=I.length,R>ttn){_(new _o("OTLP response exceeds 64 KiB limit"));return}x.push(I)}),w.on("aborted",()=>g(new _o("OTLP success response was interrupted"))),w.on("error",()=>g(new _o("OTLP success response could not be read"))),w.on("end",()=>{try{itn(Buffer.concat(x)),f()}catch(I){g(I)}})});T.on("error",w=>g(new _o(h.aborted?"OTLP export deadline exceeded":"OTLP transport failed",!h.aborted&&!y&&otn.has(w.code??"")))),T.end(m)}),d=async m=>{const h=new AbortController,f=Date.now()+t,g=setTimeout(()=>h.abort(),t);g.unref();try{const y=Qen.serializeRequest(m);if(!y)throw new _o("OTLP serialization produced no payload");const T=n==="gzip"?await etn(y):y;let w=0;for(;!h.signal.aborted&&Date.now()<f;){w++;try{await u(T,h.signal);return}catch(E){if(!(E instanceof _o)||!E.retryable)throw E;if(w>=rtn)throw new _o("OTLP retry attempt limit reached");const _=Math.min(5e3,1e3*2**Math.min(w-1,3)),k=Math.max(E.retryAfterMs??0,_*(.8+Math.random()*.4));if(k>=f-Date.now())throw new _o("OTLP retry exceeds export deadline");await Jen(k,void 0,{signal:h.signal})}}throw new _o("OTLP export deadline exceeded")}catch(y){throw y instanceof _o?y:new _o(h.signal.aborted?"OTLP export deadline exceeded":"OTLP export failed")}finally{clearTimeout(g)}};return{export(m,h){if(c){h({code:Km.FAILED,error:new Error("OTLP transport is shut down")});return}const f=d(m).then(()=>h({code:Km.SUCCESS}),g=>h({code:Km.FAILED,error:g}));l.add(f),f.finally(()=>l.delete(f)).catch(()=>{})},async shutdown(){c=!0,await Promise.allSettled(l),i.destroy()}}}q8(),fmt(),Ut(),Wt(),Dr(),ln(),eD(),Z4();var Tln=1024*1024,wln=8*1024*1024,Eln=ZP(X4);function brr(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 aw,K2=[],$g=new Map,_rr=new WeakMap,Crr=new Set,Qse=!1,ctn=128*1024,krr=3e4,Arr=krr+1e3,ltn=2e4,hs={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 Wc(){return process.env.NEUROLINK_PROXY_LOG_SINK==="otel"}function xrr(e,t,r){const n=new Set,o=new WeakMap,s=new Set,i=new Set,a={attempted:0,submitted:0,transportAcknowledged:0,exportUnconfirmed:0,dropped:0,outstanding:0,lastAcknowledgedAt:void 0,lastFailureAt:void 0,highWaterOutstanding:0,recentFailures:[],failureHistoryEvicted:0},c=[];let l=!1;const u=(T,w,E)=>{const _=(C,x)=>{const R=C.attributes[x];return typeof R=="string"?R.slice(0,128):void 0},k={id:cn(),at:new Date().toISOString(),reason:w,...E?{error:ar(E.message).slice(0,256)}:{},records:T.slice(0,64).map(C=>({eventId:_(C,"proxy.event_id")??"unavailable",kind:_(C,"proxy.record_kind"),requestId:_(C,"request.id"),captureId:_(C,"body.capture_id")}))};a.recentFailures.length===16&&(a.recentFailures.shift(),a.failureHistoryEvicted++),a.recentFailures.push(k),T.some(C=>C.attributes["proxy.record_kind"]!=="telemetry_delivery")&&(c.length===16&&c.shift(),c.push(k))},d=()=>{l||!c.length||Qse||(l=!0,queueMicrotask(()=>{l=!1;for(const T of c.splice(0))cw("telemetry_delivery",{queue:r,...T})}))},m=atn(e,krr),h={export(T,w){const E=performance.now();for(const x of T){const R=x.attributes["body.capture_id"],I=typeof R=="string"?$g.get(R):void 0;I&&(I.maxChunkQueueWaitMs=Math.max(I.maxChunkQueueWaitMs??0,E-(o.get(x)??E)))}let _=!1;const k=setTimeout(()=>C({code:Km.FAILED,error:new Error("OTLP export callback deadline exceeded")}),Arr);k.unref();const C=x=>{if(!_){_=!0,clearTimeout(k),a.outstanding-=T.length,x.code===Km.SUCCESS?(a.transportAcknowledged+=T.length,a.lastAcknowledgedAt=new Date().toISOString(),d()):(a.exportUnconfirmed+=T.length,a.lastFailureAt=new Date().toISOString(),u(T,"export_unconfirmed",x.error));for(const R of T){n.delete(R);const I=R.attributes?.["body.capture_id"],M=typeof I=="string"?$g.get(I):void 0;if(M){M.maxChunkExportMs=Math.max(M.maxChunkExportMs??0,performance.now()-E);const N=_rr.get(M);x.code===Km.SUCCESS&&(N===void 0||Date.now()<N)?M.acknowledged++:M.unconfirmed++,M.notify?.()}}for(const R of s)R();for(const R of i)R();w(x)}};try{m.export(T,C)}catch(x){C({code:Km.FAILED,error:x instanceof Error?x:new Error(String(x))})}},shutdown:()=>m.shutdown()},f=new UV(h,{maxQueueSize:t,maxExportBatchSize:64,scheduledDelayMillis:r==="bodies"?25:1e3,exportTimeoutMillis:Arr}),g={onEmit(T){T.attributes["proxy.event_id"]??=cn(),a.attempted++;const w=T.attributes?.["body.capture_id"],E=typeof w=="string"?$g.get(w):void 0;if(E&&E.emitted++,a.outstanding>=t){a.dropped++,u([T],"queue_full"),E&&(E.dropped++,E.notify?.());return}a.submitted++,a.outstanding++,n.add(T),o.set(T,performance.now()),a.highWaterOutstanding=Math.max(a.highWaterOutstanding,a.outstanding),f.onEmit(T)},forceFlush:async()=>{const T=new Set(n);try{await f.forceFlush()}finally{await new Promise(w=>{const E=()=>{[...T].some(_=>n.has(_))||(i.delete(E),w())};i.add(E),E()})}},shutdown:async()=>{try{await g.forceFlush()}finally{await f.shutdown()}}};return{state:a,processor:g,capacity:t,kind:r,waitForCapacity:T=>new Promise(w=>{const E=setTimeout(()=>_(!1),Math.max(0,T-Date.now()));E.unref?.();const _=C=>{clearTimeout(E),s.delete(k),w(C)},k=()=>{Date.now()>=T?_(!1):a.outstanding<t&&_(!0)};s.add(k),k()})}}async function utn(e,t,r){hs.attempted++;const n=Buffer.byteLength(t,"utf8");if(!aw||Qse||$g.has(e)||hs.pending>=hs.maxPending||hs.pendingBytes+n>hs.maxPendingBytes)return hs.rejected++,{status:"rejected",acknowledgedChunks:0,unconfirmedChunks:0,droppedChunks:0,reason:$g.has(e)?"body_capture_id_in_use":!aw||Qse?"body_exporter_unavailable":"body_publication_queue_full"};hs.pending++,hs.pendingBytes+=n,hs.highWaterPending=Math.max(hs.highWaterPending,hs.pending),hs.highWaterBytes=Math.max(hs.highWaterBytes,hs.pendingBytes);const o={acknowledged:0,unconfirmed:0,dropped:0,emitted:0};$g.set(e,o);let s;const i=(async()=>{const a=K2.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()+ltn;_rr.set(o,l);const u=brr(t,ctn);let d=0,m;try{for(let E=0;E<u.length;E++){for(;a.state.outstanding>=a.capacity;){const _=performance.now(),k=await a.waitForCapacity(l);if(d+=performance.now()-_,!k){m="body_publication_deadline";break}}if(Date.now()>=l){m="body_publication_deadline";break}r(u[E],E,u.length),E%4===3&&await Trr()}}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),T=o.unconfirmed+y;return{status:o.emitted===0?"rejected":o.dropped||o.emitted!==u.length?"partial":T?"export_unconfirmed":"transport_acknowledged",expectedChunks:u.length,acknowledgedChunks:o.acknowledged,unconfirmedChunks:T,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}:{}}})();Crr.add(i);try{const a=await i;return a.status==="transport_acknowledged"?hs.transportAcknowledged++:a.status==="export_unconfirmed"?hs.exportUnconfirmed++:a.status==="rejected"?hs.rejected++:hs.partial++,a}finally{Crr.delete(i);const a=()=>{$g.delete(e),hs.pending--,hs.pendingBytes-=n};s?s.then(a,a):a()}}function Irr(e="worker"){if(!Wc())return;if(aw)return aw;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 s of[t,r]){const i=new URL(s);if(!["http:","https:"].includes(i.protocol))throw new Error("Proxy OTLP logs endpoint must use HTTP or HTTPS");const a=["localhost","127.0.0.1","[::1]"].includes(i.hostname);if(i.protocol==="http:"&&!a)throw new Error("Proxy OTLP logs require HTTPS for non-loopback collectors")}const n=xrr(t,2048,"metadata"),o=xrr(r,256,"bodies");return K2.push(n,o),aw=new $V({resource:G1({"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(s,i){(s.attributes?.["proxy.record_kind"]==="body"?o:n).processor.onEmit(s,i)},forceFlush:async()=>{await Promise.all(K2.map(s=>s.processor.forceFlush()))},shutdown:async()=>{await Promise.all(K2.map(s=>s.processor.shutdown()))}}]}),aw}function cw(e,t){if(Wc())try{const r=typeof t.requestId=="string"&&!t.traceId?Kse(t.requestId):void 0,n=r?{...t,...r}:t;Irr()?.getLogger("neurolink-proxy-events").emit({context:Jse(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{dtn++}}var dtn=0;ln(),hr(),Ri(),bc(),nn(),qo();var Sln=globalThis.crypto,bln=globalThis.ReadableStream||class{},_ln=globalThis.URL,Cln=globalThis.URLSearchParams,eie=e=>{try{return JSON.stringify(e,null,2)}catch{return String(e)}};eie.custom=Symbol.for("nodejs.util.inspect.custom"),eie.colors={},eie.styles={};var mtn=globalThis.TextDecoder,Rrr=globalThis.TextEncoder,kln=globalThis.performance||{now:()=>Date.now()},ptn=class{},Aln=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 Rrr().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 Rrr().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 mtn().decode(this)}},Iln=globalThis.clearTimeout,Rln=globalThis.clearInterval,EA=64,J2=32*1024*1024,Mrr=64,Prr=32*1024*1024,htn=2e4,ftn=16*1024*1024,Drr=2e4,Ug,gtn,Lp=0,ytn=0,Kt={attempted:0,completed:0,rejected:0,failed:0,pending:0,pendingBytes:0,maxPending:EA,maxPendingBytes:J2,highWaterPending:0,highWaterBytes:0,waiting:0,waitingBytes:0,maxWaiting:Mrr,maxWaitingBytes:Prr,highWaterWaiting:0,highWaterWaitingBytes:0,admissionWaits:0,admissionTimeouts:0,rejectionReasons:{}},SA=new Map,Orr=new Map,Bg=[],Y2;function Nrr(e){return Date.now()<Lp||Kt.pending>=EA||Kt.pendingBytes+e>J2?!1:(Kt.pending+=1,Kt.pendingBytes+=e,Kt.highWaterPending=Math.max(Kt.highWaterPending,Kt.pending),Kt.highWaterBytes=Math.max(Kt.highWaterBytes,Kt.pendingBytes),!0)}function tie(){if(Bg.length){if(Date.now()<Lp){Y2||(Y2=setTimeout(()=>{Y2=void 0,tie()},Math.max(1,Lp-Date.now())),Y2.unref?.());return}for(let e=0;e<Bg.length&&!(Kt.pending>=EA);){const t=Bg[e];if(!Nrr(t.bytes)){e+=1;continue}Bg.splice(e,1),clearTimeout(t.timer),Kt.waiting-=1,Kt.waitingBytes-=t.bytes,t.resolve("admitted")}}}function vtn(e){return Kt.waiting>=Mrr||Kt.waitingBytes+e>Prr?Promise.resolve("queue_full"):(Kt.admissionWaits+=1,Kt.waiting+=1,Kt.waitingBytes+=e,Kt.highWaterWaiting=Math.max(Kt.highWaterWaiting,Kt.waiting),Kt.highWaterWaitingBytes=Math.max(Kt.highWaterWaitingBytes,Kt.waitingBytes),new Promise(t=>{const r=setTimeout(()=>{const n=Bg.findIndex(o=>o.timer===r);n<0||(Bg.splice(n,1),Kt.waiting-=1,Kt.waitingBytes-=e,Kt.admissionTimeouts+=1,t("timeout"),tie())},htn);r.unref?.(),Bg.push({bytes:e,queuedAt:Date.now(),resolve:t,timer:r})}))}function Lrr(e){Kt.pending-=1,Kt.pendingBytes-=e,tie()}function Ttn(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 rie(e,t){const r=SA.get(e);r&&(SA.delete(e),clearTimeout(r.timer),r.resolve(t),SA.size||Ug?.unref())}function nie(e,t){if(Ug===e){Ug=void 0,Lp=Date.now()+5e3;for(const r of SA.keys())rie(r,{error:t,stored:{bodyWriteFailed:!0}});e.terminate().catch(()=>{})}}function wtn(){if(Ug)return Ug;const e=new ptn(gtn??new URL("./bodyCaptureWorkerEntry.js",import.meta.url),{execArgv:process.execArgv.filter(t=>!t.startsWith("--input-type")),resourceLimits:{maxOldGenerationSizeMb:128}});return Ug=e,e.on("message",t=>{Ug===e&&rie(t.id,t.result)}),e.on("error",()=>nie(e,"body_worker_error")),e.on("exit",()=>nie(e,"body_worker_exit")),e.unref(),e}async function Etn(e,t,r){Kt.attempted+=1;const n=Date.now(),o=t===null?J2:ftn;let s,i;try{s=Ttn(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()>=Lp&&(a=Nrr(s)?"admitted":t===null?await vtn(s):"queue_full"),a!=="admitted"){Kt.rejected+=1;const d=s>o?i??"body_capture_entry_too_large":Date.now()<Lp?"body_worker_backoff":a==="timeout"?"body_capture_admission_timeout":"body_capture_queue_full";return Kt.lastError=d,Kt.lastRejectedAt=new Date().toISOString(),Kt.rejectionReasons[d]=(Kt.rejectionReasons[d]??0)+1,r({error:d,stored:{bodyWriteFailed:!0},admissionWaitMs:Math.max(0,Date.now()-n),admission:{limitingResource:s>o?"entry":Date.now()<Lp?"worker":Kt.pending>=EA?"captures":"bytes",estimatedBytes:Number.isFinite(s)?s:void 0,maxEntryBytes:o,pending:Kt.pending,pendingBytes:Kt.pendingBytes,maxPending:EA,maxPendingBytes:J2}})}const c=Date.now();let l;try{l=wtn()}catch{return Lp=Date.now()+5e3,Lrr(s),Kt.failed+=1,r({error:"body_worker_start_failed",stored:{bodyWriteFailed:!0}})}const u=++ytn;return new Promise(d=>{const m=setTimeout(()=>nie(l,"body_worker_timeout"),Drr);m.unref(),SA.set(u,{timer:m,startedAt:Date.now(),resolve:h=>{Orr.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(()=>{Orr.delete(u),Lrr(s),h.error||h.stored.bodyWriteFailed?Kt.failed+=1:Kt.completed+=1,h.error&&(Kt.lastError=h.error),d()})}}),l.ref();try{l.postMessage({id:u,entry:e,logDir:t,queuedAt:n})}catch{rie(u,{error:"body_capture_clone_failed",stored:{bodyWriteFailed:!0}})}})}var Frr=new Wtr;function lw(){return Frr.getStore()}function $rr(){return Frr.getStore()!==void 0}Nr();var uw=null,oie=!1,sie=new Set,iie=5e3,Mln=Drr+2*iie,Stn=4096,X2=new Map,btn=$H,aie=()=>({attempted:0,written:0,inFlight:0,pending:0,dropped:0,writeTimeouts:0,unconfirmedWrites:0}),_tn={requests:aie(),attempts:aie(),debug:aie()};async function cie(e,t,r,n={}){const o=_tn[r];if(o.attempted+=1,o.pending+o.inFlight>=Stn){o.dropped+=1;return}o.pending+=1;const s=Urr((X2.get(e)??Promise.resolve()).then(async()=>{o.pending-=1,o.inFlight+=1;const i=setTimeout(()=>{o.writeTimeouts+=1},iie);i.unref?.();try{await btn(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(X2.set(e,s),s.then(()=>{X2.get(e)===s&&X2.delete(e)}),n.waitForPersistence)return s;await _t(s,iie,"Proxy metadata write remains pending").catch(()=>{})}function Urr(e){return sie.add(e),e.then(()=>sie.delete(e),()=>sie.delete(e)),e}var dw=null,Brr=0,Ctn=10,ktn=16e3;function Atn(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.pricingStatus="usage_incomplete";return}if(!ad(e.pricingProvider,e.model)){e.pricingStatus="unavailable";return}if(!X1(e.pricingProvider,e.model)){e.pricingStatus="inferred";return}const s=Op({inputTokens:t,outputTokens:r,cacheReadTokens:n,cacheCreationTokens:o,inputIncludesCachedTokens:e.inputIncludesCachedTokens});e.pricingStatus="exact",e.apiEquivalentCostUsd=Hi(e.pricingProvider,e.model,s);const i=Hi(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 mw(e){if(Object.assign(e,vA(e.requestId)),Atn(e),!e.traceId||e.traceFlags===void 0){const n=sw(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",!gen(e)||!oie||!uw&&!Wc())return;if(Wc()){await qrr(e);return}const t=At(uw,`proxy-${new Date().toISOString().split("T")[0]}.jsonl`),r=JSON.stringify(e)+`
|
|
2317
|
+
`)}};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))}}})}hl(),ss();function TA(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Men(e){return TA(e)&&e.role==="system"}function drr(e){return Array.isArray(e.content)?e.content:[e]}function Pen(e){if(!TA(e))return[];const t=[];e.type==="function_call"&&typeof e.call_id=="string"&&t.push(e.call_id);for(const r of drr(e))TA(r)&&r.type==="tool_use"&&typeof r.id=="string"&&t.push(r.id);return t}function Den(e){if(!TA(e))return[];const t=[];e.type==="function_call_output"&&typeof e.call_id=="string"&&t.push(e.call_id);for(const r of drr(e))TA(r)&&r.type==="tool_result"&&typeof r.tool_use_id=="string"&&t.push(r.tool_use_id);return t}function Oen(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 Den(s))n.delete(i);for(const i of Pen(s))n.add(i);n.size===0&&(t.push(r),r=[])}return r.length>0&&t.push(r),t}function Nen(e){if(Array.isArray(e.messages))return"messages";if(Array.isArray(e.conversationMessages))return"conversationMessages";if(Array.isArray(e.input))return"input"}function Len(e){const t={body:e.body,historyModified:!1,unitsRemoved:0,itemsRemoved:0},r=e.body,n=Nen(r);if(n===void 0)return t;const o=r[n],s=Oen(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&&Men(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 Os(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function sm(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>0}function Fen(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(!Os(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&&!sm(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(!Os(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=Os(n)?n.contextWindow:void 0,s=Os(n)?n.maxOutputTokens:void 0,i=Os(n)?n.compactAtTokens:void 0,a=Os(n)?n.compactToTokens:void 0;if(!r.includes("/")||!Os(n)||!sm(o)||s!==void 0&&!sm(s)||i!==void 0&&(!sm(i)||i>=o)||a!==void 0&&(!sm(a)||!sm(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 mrr,Use;function $en(){const e=process.env.NEUROLINK_PROXY_CONTEXT_POLICY;return(!Use||e!==mrr)&&(Use=Fen(e),mrr=e),Use}function V2(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)V2(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),Os(o.function)&&typeof o.function.name=="string"&&t.add(o.function.name)}typeof o.toolName=="string"&&t.add(o.toolName),Os(o.functionCall)&&typeof o.functionCall.name=="string"&&t.add(o.functionCall.name);for(const[s,i]of Object.entries(o))s!=="tools"&&V2(i,t,r,n+1)}function Uen(e){if(Os(e))return typeof e.name=="string"?e.name:Os(e.function)&&typeof e.function.name=="string"?e.function.name:void 0}function prr(e){return Array.isArray(e)?e.length:Os(e)?Object.keys(e).length:0}function ow(e,t,r,n=new WeakSet,o=0){if(typeof e=="string")return nr(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+ow(a,t,r,n,o+1)+4,0);const s=e;return e instanceof Uint8Array||e instanceof ArrayBuffer?(r.multimodal=!0,mM):typeof s.text=="string"&&Array.isArray(s.images)?(r.multimodal=s.images.length>0||r.multimodal,nr(s.text,t)+s.images.length*mM):["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,mM):Object.entries(s).reduce((i,[a,c])=>i+nr(a,t)+ow(c,t,r,n,o+1),0)}finally{n.delete(e)}}function Bse(e){const t=e.policy??$en(),r=e.body;let n=e.body;const o=r.tools;if(t.toolAllowlist){const N=new Set(t.toolAllowlist);V2(r,N),V2(e.toolReferenceBody,N);const U=r.tool_choice;Os(U)&&(typeof U.name=="string"&&N.add(U.name),Os(U.function)&&typeof U.function.name=="string"&&N.add(U.function.name));const P=Array.isArray(o)?o.filter(D=>{const F=Uen(D);return F===void 0||N.has(F)}):Os(o)?Object.fromEntries(Object.entries(o).filter(([D])=>N.has(D))):o;n={...e.body,tools:P,...Array.isArray(r.toolFilter)?{toolFilter:r.toolFilter.filter(D=>typeof D!="string"||N.has(D))}:{}}}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=ow(s.tools,l,i),d=[s.instructions,s.system,s.systemPrompt,s.systemInstruction].reduce((N,U)=>N+ow(U,l,i),0),m=[s.response_format,s.output_config,s.structuredOutput,s.schema,Os(s.text)?s.text.format:void 0,Os(s.generationConfig)?s.generationConfig.responseSchema:void 0,Os(s.generationConfig)?s.generationConfig.responseJsonSchema:void 0].reduce((N,U)=>N+ow(U,l,i),0),h=N=>ow(N,l,a),f=24+m+u+d,g=()=>[s.messages,s.input,s.contents,s.conversationMessages,s.prompt].reduce((N,U)=>N+h(U),0);let y=f+g();const T=t.models?.[`${e.provider}/${e.model}`];let w=!1,E=0;const _=y;if(T?.compactAtTokens!==void 0&&T.compactToTokens!==void 0&&y>T.compactAtTokens){const N=Len({body:n,inputTokensEstimate:y,targetTokens:T.compactToTokens,estimate:h});if(N.historyModified&&(n=N.body,s=n,w=!0,E=N.unitsRemoved,a={multimodal:!1},y=f+g()),y>T.compactToTokens)throw new _r("proxy_context_compaction_failed",`Compaction could not bring ${e.provider}/${e.model} within ${T.compactToTokens} tokens; ${y} remain after removing every removable unit`)}const k=t7(e.provider,e.model),C=T?.contextWindow??k,x=T?.maxOutputTokens??r7(e.provider,e.model),R=e.maxOutputTokens??s.max_tokens??s.max_output_tokens??s.maxTokens??(Os(s.generationConfig)?s.generationConfig.maxOutputTokens:void 0);if(R!==void 0&&!sm(R))throw new _r("invalid_output_budget","Requested output tokens must be a positive safe integer");const I=e.provider==="codex"?x??t.outputReserveTokens??32768:sm(R)?R:x??t.outputReserveTokens??32768,M={provider:e.provider,model:e.model,inputTokensEstimate:y,toolsTokensEstimate:u,instructionsTokensEstimate:d,schemaTokensEstimate:m,outputTokensReserve:I,reasoningIncludedInOutputReserve:!0,...C?{contextWindow:C}:{},contextLimitSource:T?"configured":k?"discovered":"unknown",tokenCountSource:"estimated",multimodalEstimate:c(),originalToolCount:prr(o),retainedToolCount:prr(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(x!==void 0&&sm(R)&&e.provider!=="codex"&&R>x)throw new _r("proxy_output_budget_exceeded","Requested output exceeds the serving model's known output limit",M);if(C!==void 0&&t.enforceDiscoveredLimits!==!1&&!c()&&y+I>C)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}}ln();var W2=60*6e4,Ben=1e4,zse=5e3,zen=2e3;function qse(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 Jy("sha256").update(t).digest("hex")}function ni(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 Vc(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 Gse(e){if(typeof e=="string")try{e=JSON.parse(e)}catch{throw ni("PROXY_TOKEN_BUDGET_CONFIG","Token budget configuration is not valid JSON")}if(!e||typeof e!="object"||Array.isArray(e))throw ni("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 ni("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 hrr(){const e=process.env.NEUROLINK_PROXY_TOKEN_BUDGET;return e===void 0||e.trim()===""?void 0:Gse(e)}function qen(e){const t=hrr(),r=e===void 0?void 0:Gse(e);if(!t)return r;if(!r)return t;const n={windowMs:Math.max(t.windowMs??W2,r.windowMs??W2)};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 Gen(e){return!!(e?.maxInFlightTokens||e?.accountWindowTokens||e?.sessionWindowTokens)}function frr(e){for(const t of["provider","accountKey","sessionKey","requestId"])if(typeof e[t]!="string"||e[t].length===0||e[t].length>512)throw ni("PROXY_TOKEN_BUDGET_INPUT","Token budget requires bounded provider, account, session and request identities");if(!Number.isSafeInteger(e.reservationTokens)||e.reservationTokens<=0)throw ni("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 ni("PROXY_TOKEN_BUDGET_INPUT","Token estimate provenance must be bounded text")}var Hen=class{constructor(e="supervisor",t=Date.now,r=Ben,n=zse){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 ni("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"){frr(e);const r=Gse(e.policy??{});if(this.leases.size>=this.maxLeases)throw ni("PROXY_TOKEN_BUDGET_CAPACITY","Token budget outstanding reservation capacity is full");const n=r.windowMs??W2,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 ni("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 ni("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=cn();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 ni("PROXY_TOKEN_BUDGET_OWNER","Token budget lease belongs to another worker");if(r!==void 0&&(!Number.isSafeInteger(r)||r<0))throw ni("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)}},Hse=new Hen(process.env.NEUROLINK_PROXY_SOCKET_WORKER==="1"?"process":"supervisor"),im=new Map,wA=new Set;function grr(e){if(wA.size>=zse){const t=wA.values().next().value;t&&wA.delete(t)}wA.add(e)}var yrr=!1;function jen(){yrr||(yrr=!0,process.on("message",e=>{if(!e||typeof e!="object"||e.type!=="proxy-budget:response")return;const t=e,r=im.get(t.rpcId);if(!r){wA.delete(t.rpcId)&&t.ok&&typeof t.leaseId=="string"&&t.leaseId.length<=128&&process.connected&&process.send&&process.send({type:"proxy-budget:request",rpcId:cn(),pid:process.pid,generation:Number(process.env.NEUROLINK_PROXY_WORKER_GENERATION),action:"cancel",leaseId:t.leaseId},()=>{});return}im.delete(t.rpcId),clearTimeout(r.timer),t.ok?r.resolve(t):r.reject(ni(t.errorCode??"PROXY_TOKEN_BUDGET_UNAVAILABLE",t.error??"Token budget coordinator refused the request"))}),process.on("disconnect",()=>{for(const e of im.values())clearTimeout(e.timer),e.reject(ni("PROXY_TOKEN_BUDGET_UNAVAILABLE","Token budget supervisor disconnected"));im.clear()}))}function jse(e){return jen(),new Promise((t,r)=>{if(!process.connected||!process.send||im.size>=zse){r(ni("PROXY_TOKEN_BUDGET_UNAVAILABLE","Token budget supervisor IPC is unavailable"));return}const n=cn(),o=setTimeout(()=>{im.delete(n),e.action==="reserve"&&grr(n),r(ni("PROXY_TOKEN_BUDGET_UNAVAILABLE","Token budget supervisor response timed out; dispatch refused"))},zen);im.set(n,{resolve:t,reject:r,timer:o});const s=i=>{!i||!im.has(n)||(clearTimeout(o),im.delete(n),e.action==="reserve"&&grr(n),r(ni("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 Vse(e){const t=qen(e.policy);if(!Gen(t))return{leaseId:"disabled",snapshot:{scope:"disabled",reservationTokens:0,accountChargedTokens:0,accountInFlightTokens:0,sessionChargedTokens:0,sessionInFlightTokens:0,windowMs:t?.windowMs??W2,estimateProvenance:"disabled"},settle:async()=>{},cancelBeforeDispatch:async()=>{}};frr(e);const r=process.env.NEUROLINK_PROXY_SOCKET_WORKER==="1",n={...e,policy:t},o=r?await jse({action:"reserve",reservation:n}):Hse.reserve(n,"local");if(!o.leaseId||!o.snapshot)throw ni("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 jse({action:"settle",leaseId:s,actualTotalTokens:c})).snapshot:Hse.settle(s,"local",c);i=!0,l&&(a.snapshot={...l,scope:r?"supervisor":"process"})},cancelBeforeDispatch:async()=>{if(i)return;const c=r?(await jse({action:"cancel",leaseId:s})).snapshot:Hse.settle(s,"local",void 0,!0);i=!0,c&&(a.snapshot={...c,scope:r?"supervisor":"process"})}};return a}async function Wse(e,t){try{await e.settle(t)}catch{e.snapshot={...e.snapshot,settlement:"unconfirmed"}}}Ut(),eD(),ln(),Yt();var vrr=new Map;function Kse(e){return vrr.get(e)??vrr.get(e.replace(/:codex-fallback$/,""))}function sw(e){const t=typeof e.requestId=="string"?Kse(e.requestId):void 0,r=dt.getSpanContext(mr.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 OF(s)?{traceId:s.traceId,spanId:s.spanId,traceFlags:o}:void 0}function Jse(e){const t=sw(e);return t?dt.setSpanContext(NF,t):mr.active()}var Ven=async()=>{},tln=globalThis.crypto,rln=globalThis.ReadableStream||class{},Trr=Ven,nln=globalThis.URL,oln=globalThis.URLSearchParams,Yse=e=>{try{return JSON.stringify(e,null,2)}catch{return String(e)}};Yse.custom=Symbol.for("nodejs.util.inspect.custom"),Yse.colors={},Yse.styles={};var Wen=globalThis.TextDecoder,wrr=globalThis.TextEncoder,sln=globalThis.performance||{now:()=>Date.now()},iln=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 wrr().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 wrr().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 Wen().decode(this)}},Ken=e=>({[Symbol.toPrimitive](){return e},ref(){return this},unref(){return this},hasRef(){return!1},refresh(){return this},close(){}}),Jen=(...e)=>Ken(globalThis.setTimeout(...e)),cln=globalThis.clearTimeout,lln=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};FV(),Yn(),SXe();var uln=globalThis.crypto,Yen=class{constructor(){throw new Error("[NeuroLink:browser] Node HTTP agents require a server runtime")}},dln=globalThis.ReadableStream||class{},Xen=()=>({}),mln=globalThis.URL,pln=globalThis.URLSearchParams,Xse=e=>{try{return JSON.stringify(e,null,2)}catch{return String(e)}};Xse.custom=Symbol.for("nodejs.util.inspect.custom"),Xse.colors={},Xse.styles={};var Zen=globalThis.TextDecoder,Err=globalThis.TextEncoder,hln=globalThis.performance||{now:()=>Date.now()},fln=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 Err().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 Err().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 Zen().decode(this)}},yln=globalThis.clearTimeout,vln=globalThis.clearInterval;eD(),Z4(),FV();var Qen={serializeRequest(){throw new Error("[NeuroLink:browser] proxy OTLP log transport requires a server runtime")}},etn=ZP(X4),ttn=64*1024,rtn=5,ntn=new Set([429,502,503,504]),otn=new Set(["ECONNRESET","ECONNREFUSED","EPIPE","ETIMEDOUT","EAI_AGAIN","ENOTFOUND","ENETUNREACH","EHOSTUNREACH"]),_o=class extends Error{constructor(e,t=!1,r){super(e),this.retryable=t,this.retryAfterMs=r,this.name="ProxyOtlpResponseError"}retryable;retryAfterMs};function Srr(e){return process.env[`OTEL_EXPORTER_OTLP_LOGS_${e}`]?.trim()||process.env[`OTEL_EXPORTER_OTLP_${e}`]?.trim()||void 0}function Zse(e){const t=Srr(e);if(t)try{return li(t)}catch{throw new Error(`Proxy OTLP ${e} file could not be read`)}}function stn(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 itn(e){let t;try{t=JSON.parse(e.toString("utf8"))}catch{throw new _o("OTLP response JSON is empty or malformed")}if(!t||typeof t!="object"||Array.isArray(t))throw new _o("OTLP response must be a JSON object");if(Object.keys(t).some(a=>a!=="partialSuccess"&&a!=="partial_success"))throw new _o("OTLP response has unexpected fields");if("partialSuccess"in t&&"partial_success"in t)throw new _o("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 _o("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 _o("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 _o("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 _o("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 _o("OTLP rejected record count is malformed");if(i>0n)throw new _o("OTLP partial success rejected log records")}function atn(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=Srr("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,f]of Object.entries(cmt(m)))yXe(h),vXe(h,f),o[h.toLowerCase()]=f}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:Zse("CERTIFICATE"),cert:Zse("CLIENT_CERTIFICATE"),key:Zse("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 Yen({keepAlive:!0,maxSockets:30,...s}):new gXe({keepAlive:!0,maxSockets:30}),a=r.protocol==="https:"?Xen:TXe;let c=!1;const l=new Set,u=(m,h)=>new Promise((f,g)=>{let y=!1;const T=a(r,{method:"POST",agent:i,signal:h,headers:{...o,"content-length":String(m.byteLength)}},w=>{y=!0;const E=w.statusCode??0,_=I=>{g(I),w.destroy()};if(E!==200){_(new _o(`OTLP HTTP ${E}`,ntn.has(E),stn(w.headers["retry-after"])));return}const k=w.headers["content-encoding"];if(k&&k!=="identity"){_(new _o("OTLP response encoding is unsupported"));return}const C=w.headers["content-type"];if(C&&C.split(";",1)[0].trim().toLowerCase()!=="application/json"){_(new _o("OTLP response content type is not JSON"));return}const x=[];let R=0;w.on("data",I=>{if(R+=I.length,R>ttn){_(new _o("OTLP response exceeds 64 KiB limit"));return}x.push(I)}),w.on("aborted",()=>g(new _o("OTLP success response was interrupted"))),w.on("error",()=>g(new _o("OTLP success response could not be read"))),w.on("end",()=>{try{itn(Buffer.concat(x)),f()}catch(I){g(I)}})});T.on("error",w=>g(new _o(h.aborted?"OTLP export deadline exceeded":"OTLP transport failed",!h.aborted&&!y&&otn.has(w.code??"")))),T.end(m)}),d=async m=>{const h=new AbortController,f=Date.now()+t,g=setTimeout(()=>h.abort(),t);g.unref();try{const y=Qen.serializeRequest(m);if(!y)throw new _o("OTLP serialization produced no payload");const T=n==="gzip"?await etn(y):y;let w=0;for(;!h.signal.aborted&&Date.now()<f;){w++;try{await u(T,h.signal);return}catch(E){if(!(E instanceof _o)||!E.retryable)throw E;if(w>=rtn)throw new _o("OTLP retry attempt limit reached");const _=Math.min(5e3,1e3*2**Math.min(w-1,3)),k=Math.max(E.retryAfterMs??0,_*(.8+Math.random()*.4));if(k>=f-Date.now())throw new _o("OTLP retry exceeds export deadline");await Jen(k,void 0,{signal:h.signal})}}throw new _o("OTLP export deadline exceeded")}catch(y){throw y instanceof _o?y:new _o(h.signal.aborted?"OTLP export deadline exceeded":"OTLP export failed")}finally{clearTimeout(g)}};return{export(m,h){if(c){h({code:Km.FAILED,error:new Error("OTLP transport is shut down")});return}const f=d(m).then(()=>h({code:Km.SUCCESS}),g=>h({code:Km.FAILED,error:g}));l.add(f),f.finally(()=>l.delete(f)).catch(()=>{})},async shutdown(){c=!0,await Promise.allSettled(l),i.destroy()}}}q8(),fmt(),Ut(),Wt(),Dr(),ln(),eD(),Z4();var Tln=1024*1024,wln=8*1024*1024,Eln=ZP(X4);function brr(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 aw,K2=[],$g=new Map,_rr=new WeakMap,Crr=new Set,Qse=!1,ctn=128*1024,krr=3e4,Arr=krr+1e3,ltn=2e4,hs={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 Wc(){return process.env.NEUROLINK_PROXY_LOG_SINK==="otel"}function xrr(e,t,r){const n=new Set,o=new WeakMap,s=new Set,i=new Set,a={attempted:0,submitted:0,transportAcknowledged:0,exportUnconfirmed:0,dropped:0,outstanding:0,lastAcknowledgedAt:void 0,lastFailureAt:void 0,highWaterOutstanding:0,recentFailures:[],failureHistoryEvicted:0},c=[];let l=!1;const u=(T,w,E)=>{const _=(C,x)=>{const R=C.attributes[x];return typeof R=="string"?R.slice(0,128):void 0},k={id:cn(),at:new Date().toISOString(),reason:w,...E?{error:ar(E.message).slice(0,256)}:{},records:T.slice(0,64).map(C=>({eventId:_(C,"proxy.event_id")??"unavailable",kind:_(C,"proxy.record_kind"),requestId:_(C,"request.id"),captureId:_(C,"body.capture_id")}))};a.recentFailures.length===16&&(a.recentFailures.shift(),a.failureHistoryEvicted++),a.recentFailures.push(k),T.some(C=>C.attributes["proxy.record_kind"]!=="telemetry_delivery")&&(c.length===16&&c.shift(),c.push(k))},d=()=>{l||!c.length||Qse||(l=!0,queueMicrotask(()=>{l=!1;for(const T of c.splice(0))cw("telemetry_delivery",{queue:r,...T})}))},m=atn(e,krr),h={export(T,w){const E=performance.now();for(const x of T){const R=x.attributes["body.capture_id"],I=typeof R=="string"?$g.get(R):void 0;I&&(I.maxChunkQueueWaitMs=Math.max(I.maxChunkQueueWaitMs??0,E-(o.get(x)??E)))}let _=!1;const k=setTimeout(()=>C({code:Km.FAILED,error:new Error("OTLP export callback deadline exceeded")}),Arr);k.unref();const C=x=>{if(!_){_=!0,clearTimeout(k),a.outstanding-=T.length,x.code===Km.SUCCESS?(a.transportAcknowledged+=T.length,a.lastAcknowledgedAt=new Date().toISOString(),d()):(a.exportUnconfirmed+=T.length,a.lastFailureAt=new Date().toISOString(),u(T,"export_unconfirmed",x.error));for(const R of T){n.delete(R);const I=R.attributes?.["body.capture_id"],M=typeof I=="string"?$g.get(I):void 0;if(M){M.maxChunkExportMs=Math.max(M.maxChunkExportMs??0,performance.now()-E);const N=_rr.get(M);x.code===Km.SUCCESS&&(N===void 0||Date.now()<N)?M.acknowledged++:M.unconfirmed++,M.notify?.()}}for(const R of s)R();for(const R of i)R();w(x)}};try{m.export(T,C)}catch(x){C({code:Km.FAILED,error:x instanceof Error?x:new Error(String(x))})}},shutdown:()=>m.shutdown()},f=new UV(h,{maxQueueSize:t,maxExportBatchSize:64,scheduledDelayMillis:r==="bodies"?25:1e3,exportTimeoutMillis:Arr}),g={onEmit(T){T.attributes["proxy.event_id"]??=cn(),a.attempted++;const w=T.attributes?.["body.capture_id"],E=typeof w=="string"?$g.get(w):void 0;if(E&&E.emitted++,a.outstanding>=t){a.dropped++,u([T],"queue_full"),E&&(E.dropped++,E.notify?.());return}a.submitted++,a.outstanding++,n.add(T),o.set(T,performance.now()),a.highWaterOutstanding=Math.max(a.highWaterOutstanding,a.outstanding),f.onEmit(T)},forceFlush:async()=>{const T=new Set(n);try{await f.forceFlush()}finally{await new Promise(w=>{const E=()=>{[...T].some(_=>n.has(_))||(i.delete(E),w())};i.add(E),E()})}},shutdown:async()=>{try{await g.forceFlush()}finally{await f.shutdown()}}};return{state:a,processor:g,capacity:t,kind:r,waitForCapacity:T=>new Promise(w=>{const E=setTimeout(()=>_(!1),Math.max(0,T-Date.now()));E.unref?.();const _=C=>{clearTimeout(E),s.delete(k),w(C)},k=()=>{Date.now()>=T?_(!1):a.outstanding<t&&_(!0)};s.add(k),k()})}}async function utn(e,t,r){hs.attempted++;const n=Buffer.byteLength(t,"utf8");if(!aw||Qse||$g.has(e)||hs.pending>=hs.maxPending||hs.pendingBytes+n>hs.maxPendingBytes)return hs.rejected++,{status:"rejected",acknowledgedChunks:0,unconfirmedChunks:0,droppedChunks:0,reason:$g.has(e)?"body_capture_id_in_use":!aw||Qse?"body_exporter_unavailable":"body_publication_queue_full"};hs.pending++,hs.pendingBytes+=n,hs.highWaterPending=Math.max(hs.highWaterPending,hs.pending),hs.highWaterBytes=Math.max(hs.highWaterBytes,hs.pendingBytes);const o={acknowledged:0,unconfirmed:0,dropped:0,emitted:0};$g.set(e,o);let s;const i=(async()=>{const a=K2.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()+ltn;_rr.set(o,l);const u=brr(t,ctn);let d=0,m;try{for(let E=0;E<u.length;E++){for(;a.state.outstanding>=a.capacity;){const _=performance.now(),k=await a.waitForCapacity(l);if(d+=performance.now()-_,!k){m="body_publication_deadline";break}}if(Date.now()>=l){m="body_publication_deadline";break}r(u[E],E,u.length),E%4===3&&await Trr()}}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),T=o.unconfirmed+y;return{status:o.emitted===0?"rejected":o.dropped||o.emitted!==u.length?"partial":T?"export_unconfirmed":"transport_acknowledged",expectedChunks:u.length,acknowledgedChunks:o.acknowledged,unconfirmedChunks:T,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}:{}}})();Crr.add(i);try{const a=await i;return a.status==="transport_acknowledged"?hs.transportAcknowledged++:a.status==="export_unconfirmed"?hs.exportUnconfirmed++:a.status==="rejected"?hs.rejected++:hs.partial++,a}finally{Crr.delete(i);const a=()=>{$g.delete(e),hs.pending--,hs.pendingBytes-=n};s?s.then(a,a):a()}}function Irr(e="worker"){if(!Wc())return;if(aw)return aw;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 s of[t,r]){const i=new URL(s);if(!["http:","https:"].includes(i.protocol))throw new Error("Proxy OTLP logs endpoint must use HTTP or HTTPS");const a=["localhost","127.0.0.1","[::1]"].includes(i.hostname);if(i.protocol==="http:"&&!a)throw new Error("Proxy OTLP logs require HTTPS for non-loopback collectors")}const n=xrr(t,2048,"metadata"),o=xrr(r,256,"bodies");return K2.push(n,o),aw=new $V({resource:G1({"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(s,i){(s.attributes?.["proxy.record_kind"]==="body"?o:n).processor.onEmit(s,i)},forceFlush:async()=>{await Promise.all(K2.map(s=>s.processor.forceFlush()))},shutdown:async()=>{await Promise.all(K2.map(s=>s.processor.shutdown()))}}]}),aw}function cw(e,t){if(Wc())try{const r=typeof t.requestId=="string"&&!t.traceId?Kse(t.requestId):void 0,n=r?{...t,...r}:t;Irr()?.getLogger("neurolink-proxy-events").emit({context:Jse(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{dtn++}}var dtn=0;ln(),hr(),Ri(),bc(),nn(),qo();var Sln=globalThis.crypto,bln=globalThis.ReadableStream||class{},_ln=globalThis.URL,Cln=globalThis.URLSearchParams,eie=e=>{try{return JSON.stringify(e,null,2)}catch{return String(e)}};eie.custom=Symbol.for("nodejs.util.inspect.custom"),eie.colors={},eie.styles={};var mtn=globalThis.TextDecoder,Rrr=globalThis.TextEncoder,kln=globalThis.performance||{now:()=>Date.now()},ptn=class{},Aln=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 Rrr().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 Rrr().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 mtn().decode(this)}},Iln=globalThis.clearTimeout,Rln=globalThis.clearInterval,EA=64,J2=32*1024*1024,Mrr=64,Prr=32*1024*1024,htn=2e4,ftn=16*1024*1024,Drr=2e4,Ug,gtn,Lp=0,ytn=0,Kt={attempted:0,completed:0,rejected:0,failed:0,pending:0,pendingBytes:0,maxPending:EA,maxPendingBytes:J2,highWaterPending:0,highWaterBytes:0,waiting:0,waitingBytes:0,maxWaiting:Mrr,maxWaitingBytes:Prr,highWaterWaiting:0,highWaterWaitingBytes:0,admissionWaits:0,admissionTimeouts:0,rejectionReasons:{}},SA=new Map,Orr=new Map,Bg=[],Y2;function Nrr(e){return Date.now()<Lp||Kt.pending>=EA||Kt.pendingBytes+e>J2?!1:(Kt.pending+=1,Kt.pendingBytes+=e,Kt.highWaterPending=Math.max(Kt.highWaterPending,Kt.pending),Kt.highWaterBytes=Math.max(Kt.highWaterBytes,Kt.pendingBytes),!0)}function tie(){if(Bg.length){if(Date.now()<Lp){Y2||(Y2=setTimeout(()=>{Y2=void 0,tie()},Math.max(1,Lp-Date.now())),Y2.unref?.());return}for(let e=0;e<Bg.length&&!(Kt.pending>=EA);){const t=Bg[e];if(!Nrr(t.bytes)){e+=1;continue}Bg.splice(e,1),clearTimeout(t.timer),Kt.waiting-=1,Kt.waitingBytes-=t.bytes,t.resolve("admitted")}}}function vtn(e){return Kt.waiting>=Mrr||Kt.waitingBytes+e>Prr?Promise.resolve("queue_full"):(Kt.admissionWaits+=1,Kt.waiting+=1,Kt.waitingBytes+=e,Kt.highWaterWaiting=Math.max(Kt.highWaterWaiting,Kt.waiting),Kt.highWaterWaitingBytes=Math.max(Kt.highWaterWaitingBytes,Kt.waitingBytes),new Promise(t=>{const r=setTimeout(()=>{const n=Bg.findIndex(o=>o.timer===r);n<0||(Bg.splice(n,1),Kt.waiting-=1,Kt.waitingBytes-=e,Kt.admissionTimeouts+=1,t("timeout"),tie())},htn);r.unref?.(),Bg.push({bytes:e,queuedAt:Date.now(),resolve:t,timer:r})}))}function Lrr(e){Kt.pending-=1,Kt.pendingBytes-=e,tie()}function Ttn(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 rie(e,t){const r=SA.get(e);r&&(SA.delete(e),clearTimeout(r.timer),r.resolve(t),SA.size||Ug?.unref())}function nie(e,t){if(Ug===e){Ug=void 0,Lp=Date.now()+5e3;for(const r of SA.keys())rie(r,{error:t,stored:{bodyWriteFailed:!0}});e.terminate().catch(()=>{})}}function wtn(){if(Ug)return Ug;const e=new ptn(gtn??new URL("./bodyCaptureWorkerEntry.js",import.meta.url),{execArgv:process.execArgv.filter(t=>!t.startsWith("--input-type")),resourceLimits:{maxOldGenerationSizeMb:128}});return Ug=e,e.on("message",t=>{Ug===e&&rie(t.id,t.result)}),e.on("error",()=>nie(e,"body_worker_error")),e.on("exit",()=>nie(e,"body_worker_exit")),e.unref(),e}async function Etn(e,t,r){Kt.attempted+=1;const n=Date.now(),o=t===null?J2:ftn;let s,i;try{s=Ttn(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()>=Lp&&(a=Nrr(s)?"admitted":t===null?await vtn(s):"queue_full"),a!=="admitted"){Kt.rejected+=1;const d=s>o?i??"body_capture_entry_too_large":Date.now()<Lp?"body_worker_backoff":a==="timeout"?"body_capture_admission_timeout":"body_capture_queue_full";return Kt.lastError=d,Kt.lastRejectedAt=new Date().toISOString(),Kt.rejectionReasons[d]=(Kt.rejectionReasons[d]??0)+1,r({error:d,stored:{bodyWriteFailed:!0},admissionWaitMs:Math.max(0,Date.now()-n),admission:{limitingResource:s>o?"entry":Date.now()<Lp?"worker":Kt.pending>=EA?"captures":"bytes",estimatedBytes:Number.isFinite(s)?s:void 0,maxEntryBytes:o,pending:Kt.pending,pendingBytes:Kt.pendingBytes,maxPending:EA,maxPendingBytes:J2}})}const c=Date.now();let l;try{l=wtn()}catch{return Lp=Date.now()+5e3,Lrr(s),Kt.failed+=1,r({error:"body_worker_start_failed",stored:{bodyWriteFailed:!0}})}const u=++ytn;return new Promise(d=>{const m=setTimeout(()=>nie(l,"body_worker_timeout"),Drr);m.unref(),SA.set(u,{timer:m,startedAt:Date.now(),resolve:h=>{Orr.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(()=>{Orr.delete(u),Lrr(s),h.error||h.stored.bodyWriteFailed?Kt.failed+=1:Kt.completed+=1,h.error&&(Kt.lastError=h.error),d()})}}),l.ref();try{l.postMessage({id:u,entry:e,logDir:t,queuedAt:n})}catch{rie(u,{error:"body_capture_clone_failed",stored:{bodyWriteFailed:!0}})}})}var Frr=new Wtr;function lw(){return Frr.getStore()}function $rr(){return Frr.getStore()!==void 0}Nr();var uw=null,oie=!1,sie=new Set,iie=5e3,Mln=Drr+2*iie,Stn=4096,X2=new Map,btn=$H,aie=()=>({attempted:0,written:0,inFlight:0,pending:0,dropped:0,writeTimeouts:0,unconfirmedWrites:0}),_tn={requests:aie(),attempts:aie(),debug:aie()};async function cie(e,t,r,n={}){const o=_tn[r];if(o.attempted+=1,o.pending+o.inFlight>=Stn){o.dropped+=1;return}o.pending+=1;const s=Urr((X2.get(e)??Promise.resolve()).then(async()=>{o.pending-=1,o.inFlight+=1;const i=setTimeout(()=>{o.writeTimeouts+=1},iie);i.unref?.();try{await btn(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(X2.set(e,s),s.then(()=>{X2.get(e)===s&&X2.delete(e)}),n.waitForPersistence)return s;await _t(s,iie,"Proxy metadata write remains pending").catch(()=>{})}function Urr(e){return sie.add(e),e.then(()=>sie.delete(e),()=>sie.delete(e)),e}var dw=null,Brr=0,Ctn=10,ktn=16e3;function Atn(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.pricingStatus="usage_incomplete";return}if(!ad(e.pricingProvider,e.model)){e.pricingStatus="unavailable";return}if(!X1(e.pricingProvider,e.model)){e.pricingStatus="inferred";return}const s=Op({inputTokens:t,outputTokens:r,cacheReadTokens:n,cacheCreationTokens:o,inputIncludesCachedTokens:e.inputIncludesCachedTokens});e.pricingStatus="exact",e.apiEquivalentCostUsd=Hi(e.pricingProvider,e.model,s);const i=Hi(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 mw(e){if(Object.assign(e,vA(e.requestId)),Atn(e),!e.traceId||e.traceFlags===void 0){const n=sw(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",!gen(e)||!oie||!uw&&!Wc())return;if(Wc()){await qrr(e);return}const t=At(uw,`proxy-${new Date().toISOString().split("T")[0]}.jsonl`),r=JSON.stringify(e)+`
|
|
2318
2318
|
`;try{await cie(t,r,"requests")}catch{}qrr(e)}async function lie(e){if(!e.traceId||e.traceFlags===void 0){const n=sw(e);n&&(e.traceId=n.traceId,e.spanId=n.spanId,e.traceFlags=n.traceFlags)}if(Object.assign(e,vA(e.requestId)),yen(e),!oie||!uw&&!Wc())return;if(Wc()){cw("attempt",e);return}const t=At(uw,`proxy-attempts-${new Date().toISOString().split("T")[0]}.jsonl`),r=JSON.stringify(e)+`
|
|
2319
2319
|
`;try{await cie(t,r,"attempts")}catch{}}async function zrr(){if(Wc())return Irr();if(dw!==!1){if(dw!==null)return dw;Brr++;try{const{getLoggerProvider:e}=await Promise.resolve().then(()=>(Ym(),qV)),t=e();if(t)return dw=t,t;Brr>=Ctn&&(dw=!1);return}catch{dw=!1;return}}}function qrr(e){return zrr().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:Jse(e),severityNumber:s,severityText:i,body:Wc()?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 Grr(e,t){return zrr().then(async r=>{if(!r||t.redactedBody===void 0)return;const n=r.getLogger("neurolink-proxy-bodies","1.0.0"),o=e.captureId??cn(),s=(a,c,l)=>{n.emit({context:Jse(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(Wc())return utn(o,t.redactedBody,s);const i=brr(t.redactedBody,ktn);for(let a=0;a<i.length;a++)a>0&&a%4===0&&await Trr(),s(i[a],a,i.length)}).catch(()=>{})}function uie(){return oie&&(!!uw||Wc())}async function pw(e){if(!uie())return;if($rr()){cw("body_capture_index",{timestamp:e.timestamp,requestId:e.requestId,captureId:e.captureId??cn(),phase:e.phase,bodyDelivery:{status:"policy_excluded",reason:"borrowed_traffic"}});return}const t=sw(e),r=uw,n={...e,captureId:e.captureId??cn(),body:void 0},s=Urr(Etn(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),Wc()){const m=await Grr({...n,traceId:t?.traceId??n.traceId,spanId:t?.spanId??n.spanId,traceFlags:t?.traceFlags??n.traceFlags},c);d.bodyDelivery=m??{status:i.error?"capture_rejected":c.redactedBody===void 0?"no_body":"export_unconfirmed",...i.error?{reason:i.error}:{}},cw("body_capture_index",d);return}try{u&&await cie(u,JSON.stringify(d)+`
|
|
2320
2320
|
`,"debug",{waitForPersistence:!0})}catch{}await Grr({...n,traceId:t?.traceId??n.traceId,spanId:t?.spanId??n.spanId,traceFlags:t?.traceFlags??n.traceFlags},c)}));if(!Wc())return s}var xtn=1024*1024,Itn=16*1024*1024,die=0;function Hrr(e,t,r,n){const o=s=>{pw({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=uie(),l=[];let u=0,d=0,m=!1,h=!1;const f=g=>{if(h||!c)return;u+=g.byteLength;const y=Math.min(xtn-d,Itn-die);if(!m&&y>0){const T=Uint8Array.from(g.subarray(0,y));l.push(T),d+=T.byteLength,die+=T.byteLength,m=T.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"}
|
|
@@ -13,15 +13,17 @@ function record(value) {
|
|
|
13
13
|
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
14
14
|
}
|
|
15
15
|
/**
|
|
16
|
-
* A turn that cannot
|
|
16
|
+
* A turn that cannot open a history.
|
|
17
17
|
*
|
|
18
|
-
*
|
|
19
|
-
*
|
|
20
|
-
*
|
|
21
|
-
*
|
|
18
|
+
* Verified against the live API: an assistant turn at the head is accepted
|
|
19
|
+
* (plain, carrying a complete tool pair, repeated, or opening with a signed
|
|
20
|
+
* `thinking` block). A `role: "system"` message is not — the Messages API
|
|
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
24
|
*/
|
|
23
|
-
function
|
|
24
|
-
return record(item) &&
|
|
25
|
+
function isDirectiveTurn(item) {
|
|
26
|
+
return record(item) && item.role === "system";
|
|
25
27
|
}
|
|
26
28
|
function blocksOf(item) {
|
|
27
29
|
return Array.isArray(item.content) ? item.content : [item];
|
|
@@ -153,10 +155,13 @@ export function truncateHistoryForBudget(args) {
|
|
|
153
155
|
if (removedUnits === 0) {
|
|
154
156
|
return unchanged;
|
|
155
157
|
}
|
|
156
|
-
//
|
|
157
|
-
//
|
|
158
|
+
// Only leading system directives are skipped. Advancing to the next *user*
|
|
159
|
+
// turn instead would discard every tool exchange in between, which in an
|
|
160
|
+
// agentic history is most of the conversation; an assistant head is
|
|
161
|
+
// accepted upstream, and unit grouping already keeps every `tool_result`
|
|
162
|
+
// with its `tool_use`.
|
|
158
163
|
while (removedUnits < removable &&
|
|
159
|
-
|
|
164
|
+
isDirectiveTurn(items[units[removedUnits][0]])) {
|
|
160
165
|
removedUnits += 1;
|
|
161
166
|
}
|
|
162
167
|
const keptIndices = units.slice(removedUnits).flat();
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@juspay/neurolink",
|
|
3
|
-
"version": "12.18.
|
|
3
|
+
"version": "12.18.1",
|
|
4
4
|
"packageManager": "pnpm@10.15.1",
|
|
5
5
|
"description": "TypeScript AI SDK with 24+ LLM providers behind one consistent API. MCP-native (connect any MCP server), voice TTS/STT/realtime, RAG, agents, memory, context compaction. OpenAI · Anthropic · Gemini · Bedrock · Azure · Ollama · DeepSeek · NVIDIA NIM and more.",
|
|
6
6
|
"author": {
|