@juspay/neurolink 12.14.17 → 12.14.18

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.14.17](https://github.com/juspay/neurolink/compare/v12.14.16...v12.14.17) (2026-09-17)
1
+ ## [12.14.18](https://github.com/juspay/neurolink/compare/v12.14.17...v12.14.18) (2026-09-18)
2
2
 
3
3
  ### Bug Fixes
4
4
 
5
- - **(bedrock):** count only the tools the turn actually executed ([c1fc7b1](https://github.com/juspay/neurolink/commit/c1fc7b11f51d2d6b07f7c3de9138cabe1ed778e6)), closes [#1697](https://github.com/juspay/neurolink/issues/1697) [#1697](https://github.com/juspay/neurolink/issues/1697)
5
+ - **(proxy):** handle Claude Code tool additions in Codex fallback ([5a52baf](https://github.com/juspay/neurolink/commit/5a52baf19da76f3896949f3fefe0026032bc9b83))
6
6
 
7
7
  ## [11.2.3](https://github.com/juspay/neurolink/compare/v11.2.2...v11.2.3) (2026-08-19)
8
8
 
@@ -2280,10 +2280,13 @@ ${h}`:h);continue}if(typeof d.content=="string")r.push({role:d.role,content:d.co
2280
2280
  data: ${r}
2281
2281
 
2282
2282
  `}var Kk=class{state="idle";currentBlockType=null;sawToolUseBlock=!1;blockIndex=0;hasOpenedBlock=!1;outputTokens=0;messageStarted=!1;messageId;model;inputTokens;constructor(e,t=0){this.messageId=kXt(),this.model=e,this.inputTokens=t}getState(){return this.state}getCurrentBlockType(){return this.currentBlockType}getBlockIndex(){return this.blockIndex}static pingEvent(){return $c("ping",{type:"ping"})}*ensureMessageStarted(){if(this.messageStarted)return;const e={type:"message_start",message:{id:this.messageId,type:"message",role:"assistant",content:[],model:this.model,stop_reason:null,stop_sequence:null,usage:{input_tokens:this.inputTokens,output_tokens:0}}};yield $c("message_start",e),yield $c("ping",{type:"ping"}),this.messageStarted=!0,this.state="streaming"}*closeCurrentBlock(){this.currentBlockType!==null&&(yield $c("content_block_stop",{type:"content_block_stop",index:this.blockIndex}),this.currentBlockType=null)}*openBlock(e){yield*this.closeCurrentBlock(),this.hasOpenedBlock&&(this.blockIndex+=1),this.hasOpenedBlock=!0;const t={type:"content_block_start",index:this.blockIndex,content_block:e};yield $c("content_block_start",t),this.currentBlockType=e.type}*start(){this.state==="idle"&&(yield*this.ensureMessageStarted())}*pushDelta(e){if(this.state==="done"||this.state==="error")return;yield*this.ensureMessageStarted(),this.currentBlockType!=="text"&&(yield*this.openBlock({type:"text",text:""}));const t={type:"content_block_delta",index:this.blockIndex,delta:{type:"text_delta",text:e}};yield $c("content_block_delta",t)}*pushThinkingDelta(e){if(this.state==="done"||this.state==="error")return;yield*this.ensureMessageStarted(),this.currentBlockType!=="thinking"&&(yield*this.openBlock({type:"thinking",thinking:""}));const t={type:"content_block_delta",index:this.blockIndex,delta:{type:"thinking_delta",thinking:e}};yield $c("content_block_delta",t)}*pushToolUse(e,t,r){if(this.state==="done"||this.state==="error")return;this.sawToolUseBlock=!0,yield*this.ensureMessageStarted(),yield*this.openBlock({type:"tool_use",id:e,name:t,input:""});const n=JSON.stringify(r??{}),o=100;for(let s=0;s<n.length;s+=o){const i=n.slice(s,s+o),a={type:"content_block_delta",index:this.blockIndex,delta:{type:"input_json_delta",partial_json:i}};yield $c("content_block_delta",a)}if(n.length===0){const s={type:"content_block_delta",index:this.blockIndex,delta:{type:"input_json_delta",partial_json:"{}"}};yield $c("content_block_delta",s)}yield*this.closeCurrentBlock()}*finish(e,t,r){if(this.state==="idle"&&(yield*this.ensureMessageStarted()),this.state==="done"||this.state==="error")return;this.outputTokens=e??this.outputTokens;const n=this.sawToolUseBlock&&(!t||t==="stop")?"tool_use":t;yield*this.closeCurrentBlock();const o={type:"message_delta",delta:{stop_reason:AXt(n),stop_sequence:null},usage:{...r,output_tokens:this.outputTokens}};yield $c("message_delta",o),yield $c("message_stop",{type:"message_stop"}),this.state="done"}*emitError(e,t){this.state="error";const r=Aa(e,t);yield $c("error",r)}};Hn();var rF=100*1024,OJr=5e3,$oe=2048,xXt=1024*1024,Jd="...[TRUNCATED]";function nF(e){const t=[];let r=0;for(;r<e.length;){const n=/\r\n\r\n|\n\n|\r\r/.exec(e.slice(r));if(!n||n.index===void 0)break;const o=r+n.index,s=e.slice(r,o);r=o+n[0].length;let i="";const a=[],c=s.split(/\r\n|\n|\r/);for(const u of c)if(u.startsWith("event:"))i=u.slice(6).trim();else if(u.startsWith("data:")){const d=u.slice(5);a.push(d.startsWith(" ")?d.slice(1):d)}const l=a.join(`
2283
- `);(i||l)&&t.push({event:i,data:l})}return{events:t,remainder:e.slice(r)}}function NJr(e){return{messageStopReceived:!1,messageId:"",model:"",inputTokens:0,outputTokens:0,cacheCreationInputTokens:0,cacheReadInputTokens:0,contentBlocks:[],blockByteCounts:new Map,stopReason:null,stopSequence:null,eventCount:0,startTime:Date.now(),totalBytesReceived:0,events:[],rawTextChunks:e?[]:void 0,rawTextBytes:0,rawTextTruncated:!1,eventLogTruncated:!1}}function Dw(e){return Buffer.byteLength(e,"utf8")}function Uoe(e,t){if(Dw(e)<=t)return e;const r=Dw(Jd);if(t<=0||t<r)return"";let n="",o=0;for(const s of e){const i=Dw(s);if(o+i+r>t)break;n+=s,o+=i}return`${n}${Jd}`}function Boe(e,t){return Uoe(e,t)}function zoe(e,t,r,n){const o=Dw(t);if(r>=n)return{value:e&&e.endsWith(Jd)?e:`${e??""}${Jd}`,nextBytes:r+o};const s=n-r,i=r+o;return o<=s?{value:`${e??""}${t}`,nextBytes:i}:{value:`${e??""}${Uoe(t,s)}`,nextBytes:i}}function IXt(e,t){if(!e.rawTextChunks||e.rawTextTruncated)return;const r=xXt-e.rawTextBytes;if(r<=0){e.rawTextChunks.push(Jd),e.rawTextTruncated=!0;return}const n=Dw(t);if(n<=r){e.rawTextChunks.push(t),e.rawTextBytes+=n;return}e.rawTextChunks.push(Uoe(t,r)),e.rawTextBytes=xXt,e.rawTextTruncated=!0}function LJr(e){return Dw(e.text??e.thinking??e.toolInput??"")}function FJr(e){const t=e.inputTokens+e.outputTokens;return{messageId:e.messageId,messageStopReceived:e.messageStopReceived,firstUsefulOutputAt:e.firstUsefulOutputAt,firstUsefulOutputEvent:e.firstUsefulOutputEvent,observationIncomplete:e.observationIncomplete,model:e.model,usage:{inputTokens:e.inputTokens,outputTokens:e.outputTokens,cacheCreationInputTokens:e.cacheCreationInputTokens,cacheReadInputTokens:e.cacheReadInputTokens,totalTokens:t},contentBlocks:e.contentBlocks,stopReason:e.stopReason,stopSequence:e.stopSequence,eventCount:e.eventCount,streamDurationMs:Date.now()-e.startTime,totalBytesReceived:e.totalBytesReceived,events:e.events,...e.streamErrorMessage?{streamErrorMessage:e.streamErrorMessage}:{},...e.rawTextChunks?{rawText:e.rawTextChunks.join("")}:{},rawTextTruncated:e.rawTextTruncated}}function $Jr(e,t){const r=t.message;if(!r)return;e.messageId=r.id??"",e.model=r.model??"";const n=r.usage;n&&(e.inputTokens+=n.input_tokens??0,e.outputTokens+=n.output_tokens??0,e.cacheCreationInputTokens+=n.cache_creation_input_tokens??0,e.cacheReadInputTokens+=n.cache_read_input_tokens??0)}function UJr(e,t){const r=t.index??0,n=t.content_block;if(!n)return;const o=n.type,s={index:r,type:o};o==="text"?s.text=n.text??"":o==="thinking"?s.thinking=n.thinking??"":o==="tool_use"&&(s.toolName=n.name??"",s.toolId=n.id??"",s.toolInput=""),e.contentBlocks.push(s),e.blockByteCounts.set(r,LJr(s))}function BJr(e,t){const r=t.index??0,n=t.delta;if(!n)return;const o=e.contentBlocks.find(a=>a.index===r);if(!o)return;const s=e.blockByteCounts.get(r)??0,i=s>=rF;if(n.type==="text_delta"&&n.text!==null){const a=n.text,c=zoe(o.text,a,s,rF);e.blockByteCounts.set(r,c.nextBytes),(!i||!o.text?.endsWith(Jd))&&(o.text=c.value)}else if(n.type==="thinking_delta"&&n.thinking!==null){const a=n.thinking,c=zoe(o.thinking,a,s,rF);e.blockByteCounts.set(r,c.nextBytes),(!i||!o.thinking?.endsWith(Jd))&&(o.thinking=c.value)}else if(n.type==="input_json_delta"&&n.partial_json!==null){const a=n.partial_json,c=zoe(o.toolInput,a,s,rF);e.blockByteCounts.set(r,c.nextBytes),(!i||!o.toolInput?.endsWith(Jd))&&(o.toolInput=c.value)}}function zJr(e,t){const r=t.delta;r&&(e.stopReason=r.stop_reason??e.stopReason,e.stopSequence=r.stop_sequence??e.stopSequence);const n=t.usage;n&&(e.outputTokens+=n.output_tokens??0)}function GJr(e,t){e.eventCount++;const r=Date.now();if(e.events.length<OJr-1?t.event==="content_block_delta"?e.events.push({type:t.event,timestamp:r,data:""}):e.events.push({type:t.event,timestamp:r,data:Boe(t.data,$oe)}):e.eventLogTruncated||(e.events.push({type:"truncated",timestamp:r,data:Jd}),e.eventLogTruncated=!0),!t.data)return;if(t.data.length>1024*1024){e.observationIncomplete=!0;return}let n;try{n=JSON.parse(t.data)}catch{e.observationIncomplete=!0;return}const o=n&&typeof n=="object"&&"type"in n?n.type:void 0,s=t.event||(typeof o=="string"?o:"");if(s==="error"||o==="error"){const i=n&&typeof n=="object"?n:{},c=(i.error&&typeof i.error=="object"?i.error:void 0)?.message??i.message;e.streamErrorMessage=typeof c=="string"&&c.trim()?Boe(c.trim(),$oe):Boe(t.data,$oe)}if(s==="message_stop"&&(e.messageStopReceived=!0),s==="content_block_delta"&&n&&typeof n=="object"&&"delta"in n){const i=n.delta;i&&typeof i=="object"&&("text"in i&&typeof i.text=="string"&&i.text.trim().length>0||"partial_json"in i&&typeof i.partial_json=="string"&&i.partial_json.trim().length>0||"refusal"in i&&typeof i.refusal=="string"&&i.refusal.trim().length>0)&&e.firstUsefulOutputAt===void 0&&(e.firstUsefulOutputAt=r,e.firstUsefulOutputEvent=`content_block_delta.${"text"in i?"text":"refusal"in i?"refusal":"partial_json"}`)}if(e.firstUsefulOutputAt===void 0&&n&&typeof n=="object"){const i=n;s==="message_start"&&Toe(i.message)&&(e.firstUsefulOutputAt=r,e.firstUsefulOutputEvent="message_start.content");const a=i.content_block;if(s==="content_block_start"&&a&&typeof a=="object"){const c=a;(typeof c.text=="string"&&c.text.trim().length>0||typeof c.refusal=="string"&&c.refusal.trim().length>0||(c.type==="tool_use"||c.type==="server_tool_use")&&c.input&&typeof c.input=="object"&&Object.keys(c.input).length>0)&&(e.firstUsefulOutputAt=r,e.firstUsefulOutputEvent="content_block_start")}if(s==="content_block_stop"&&typeof i.index=="number"){const c=e.contentBlocks.find(l=>l.index===i.index);c?.type==="tool_use"&&c.toolName&&(e.firstUsefulOutputAt=r,e.firstUsefulOutputEvent="content_block_stop.tool_use")}}switch(s){case"message_start":$Jr(e,n);break;case"content_block_start":UJr(e,n);break;case"content_block_delta":BJr(e,n);break;case"message_delta":zJr(e,n);break;default:break}}function oF(e={}){const t=e.captureRawText??!1,r=NJr(t);let n="",o=!1,s=!1;const i=new TextDecoder;let a;const c=new Promise(w=>{a=w});function l(){s||(s=!0,n.trim()&&(r.observationIncomplete=!0),a(FJr(r)))}const u=new TransformStream({transform(w,E){E.enqueue(w),r.totalBytesReceived+=w.byteLength;const _=i.decode(w,{stream:!0});if(IXt(r,_),n+=_,o){const k=/\r\n\r\n|\n\n|\r\r/.exec(n);if(!k){n=n.slice(-4);return}n=n.slice(k.index+k[0].length),o=!1}const{events:b,remainder:A}=nF(n);n=A,n.length>1024*1024&&(r.observationIncomplete=!0,o=!0,n=n.slice(-4));for(const k of b)GJr(r,k)},flush(){const w=i.decode();w&&(IXt(r,w),n+=w),l()}}),d=u.writable.getWriter();let m;const h=new WritableStream({start(w){m=w},write(w){return d.write(w)},close(){return d.close()},abort(w){return l(),d.abort(w)}});d.closed.catch(w=>{l();try{m.error(w)}catch{}});const f=u.readable.getReader();return{stream:{readable:new ReadableStream({async pull(w){try{const{done:E,value:_}=await f.read();E?w.close():w.enqueue(_)}catch(E){w.error(E)}},async cancel(w){l();try{m.error(w)}catch{}await Promise.allSettled([f.cancel(w),d.abort(w)])}}),writable:h},telemetry:c}}Qt();var Jk=e=>typeof e=="number"&&Number.isFinite(e)&&e>0?Math.floor(e):0;function sF(e){if(!e||typeof e!="object")return!1;if("type"in e){if(e.type==="function_call")return"arguments"in e&&typeof e.arguments=="string"&&e.arguments.trim().length>0;if(e.type==="custom_tool_call")return"input"in e&&typeof e.input=="string"&&e.input.trim().length>0;if(e.type==="output_text")return"text"in e&&typeof e.text=="string"&&e.text.trim().length>0;if(e.type==="refusal")return"refusal"in e&&typeof e.refusal=="string"&&e.refusal.trim().length>0}return"content"in e&&Array.isArray(e.content)&&e.content.some(sF)}function Goe(e){if(e===null||typeof e!="object")return null;const t=e,r=t.response,n=r&&typeof r=="object"&&r.usage?r.usage:t.usage;if(!n||typeof n!="object")return null;const o=n.input_tokens??n.prompt_tokens,s=n.output_tokens??n.completion_tokens;if(o===void 0&&s===void 0)return null;const i=n.input_tokens_details,a=n.output_tokens_details;return{inputTokens:Jk(o),outputTokens:Jk(s),cacheReadTokens:Jk(i?.cached_tokens),cacheCreationTokens:Jk(i?.cache_write_tokens),reasoningTokens:Jk(a?.reasoning_tokens)}}var RXt=256*1024;function qJr(){const e=process.env.NEUROLINK_PROXY_CODEX_CAPTURE;if(!e||process.env.NEUROLINK_PROXY_LOG_SINK==="otel")return null;let t=0,r=!1;return n=>{if(!(t>=RXt))try{const o=RXt-t,s=n.byteLength>o?n.subarray(0,o):n;HS(e,s,{flag:r?"a":"w"}),r=!0,t+=s.byteLength}catch{}}}function jJr(){const e={completed:!1,terminalBytes:0};let t=0;const r=g=>{for(const y of g)if(y.data.trim()!=="[DONE]")try{const w=JSON.parse(y.data);if(!w||typeof w!="object"){e.observationIncomplete=!0;continue}const E=Goe(w);E&&(u=E);const _=w.type??y.event;(_==="response.output_text.delta"||_==="response.refusal.delta"||_==="response.function_call_arguments.delta")&&typeof w.delta=="string"&&w.delta.trim().length>0&&e.firstUsefulOutputAt===void 0&&(e.firstUsefulOutputAt=Date.now(),e.firstUsefulOutputEvent=String(_));const b=sF(w.item),A=w.response,k=_==="response.completed"&&A&&typeof A=="object"&&"output"in A&&Array.isArray(A.output)&&A.output.some(sF),R=_==="response.output_text.done"&&typeof w.text=="string"&&w.text.trim().length>0||_==="response.refusal.done"&&typeof w.refusal=="string"&&w.refusal.trim().length>0||_==="response.function_call_arguments.done"&&typeof w.arguments=="string"&&w.arguments.trim().length>0||_==="response.custom_tool_call_input.done"&&typeof w.input=="string"&&w.input.trim().length>0||(_==="response.content_part.added"||_==="response.content_part.done")&&sF(w.part),I=_==="response.custom_tool_call_input.delta"&&typeof w.delta=="string"&&w.delta.trim().length>0;if(e.firstUsefulOutputAt===void 0&&(R||k||I||(_==="response.output_item.added"||_==="response.output_item.done")&&b)&&(e.firstUsefulOutputAt=Date.now(),e.firstUsefulOutputEvent=String(_)),_==="response.completed")e.completed=!0,e.terminalBytes=t;else if(_==="error"||_==="response.failed"||_==="response.incomplete"){e.errorType="stream_error";const x=w.response,M=x&&typeof x=="object"?x:w,O=M.error,U=O&&typeof O=="object"?O:M,P=M.incomplete_details,N=P&&typeof P=="object"&&"reason"in P?P.reason:void 0;e.errorCode=typeof U.code=="string"?qr(U.code).slice(0,200):typeof N=="string"?qr(N).slice(0,200):String(_),e.errorMessage=typeof U.message=="string"?qr(U.message).slice(0,200):_==="response.incomplete"?"Codex reported an incomplete response":"Codex reported a stream failure",e.terminalBytes=t}}catch{e.observationIncomplete=!0}};let n=()=>{};const o=new Promise(g=>{n=g});let s=!1;const i=g=>{s||(s=!0,n(g))},a=new TextDecoder,c=qJr();let l="",u=null;const d=1024*1024;let m=!1;const h={transform(g,y){y.enqueue(g),t+=g.byteLength;try{if(c?.(g),l+=a.decode(g,{stream:!0}),m){const _=/\r\n\r\n|\n\n|\r\r/.exec(l);if(!_){l=l.slice(-3);return}l=l.slice(_.index+_[0].length),m=!1}const{events:w,remainder:E}=nF(l);l=E,r(w),l.length>d&&(e.observationIncomplete=!0,l=l.slice(-2),m=!0)}catch{e.observationIncomplete=!0}},flush(){(m||l.trim())&&(e.observationIncomplete=!0),i(u)},cancel(){i(u)}};return{stream:new TransformStream(h),usage:o,evidence:()=>({...e})}}var Yk=class extends Error{status;responseBody;constructor(e,t){super(`Codex fallback request returned HTTP ${e}`),this.name="CodexFallbackResponseError",this.status=e,this.responseBody=t}};function Pl(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Ow(e){return typeof e=="string"&&e.length>0?e:void 0}function HJr(e){if(typeof e.system=="string")return e.system||void 0;if(Array.isArray(e.system))return e.system.map(r=>typeof r.text=="string"?r.text:"").filter(Boolean).join(`
2283
+ `);(i||l)&&t.push({event:i,data:l})}return{events:t,remainder:e.slice(r)}}function NJr(e){return{messageStopReceived:!1,messageId:"",model:"",inputTokens:0,outputTokens:0,cacheCreationInputTokens:0,cacheReadInputTokens:0,contentBlocks:[],blockByteCounts:new Map,stopReason:null,stopSequence:null,eventCount:0,startTime:Date.now(),totalBytesReceived:0,events:[],rawTextChunks:e?[]:void 0,rawTextBytes:0,rawTextTruncated:!1,eventLogTruncated:!1}}function Dw(e){return Buffer.byteLength(e,"utf8")}function Uoe(e,t){if(Dw(e)<=t)return e;const r=Dw(Jd);if(t<=0||t<r)return"";let n="",o=0;for(const s of e){const i=Dw(s);if(o+i+r>t)break;n+=s,o+=i}return`${n}${Jd}`}function Boe(e,t){return Uoe(e,t)}function zoe(e,t,r,n){const o=Dw(t);if(r>=n)return{value:e&&e.endsWith(Jd)?e:`${e??""}${Jd}`,nextBytes:r+o};const s=n-r,i=r+o;return o<=s?{value:`${e??""}${t}`,nextBytes:i}:{value:`${e??""}${Uoe(t,s)}`,nextBytes:i}}function IXt(e,t){if(!e.rawTextChunks||e.rawTextTruncated)return;const r=xXt-e.rawTextBytes;if(r<=0){e.rawTextChunks.push(Jd),e.rawTextTruncated=!0;return}const n=Dw(t);if(n<=r){e.rawTextChunks.push(t),e.rawTextBytes+=n;return}e.rawTextChunks.push(Uoe(t,r)),e.rawTextBytes=xXt,e.rawTextTruncated=!0}function LJr(e){return Dw(e.text??e.thinking??e.toolInput??"")}function FJr(e){const t=e.inputTokens+e.outputTokens;return{messageId:e.messageId,messageStopReceived:e.messageStopReceived,firstUsefulOutputAt:e.firstUsefulOutputAt,firstUsefulOutputEvent:e.firstUsefulOutputEvent,observationIncomplete:e.observationIncomplete,model:e.model,usage:{inputTokens:e.inputTokens,outputTokens:e.outputTokens,cacheCreationInputTokens:e.cacheCreationInputTokens,cacheReadInputTokens:e.cacheReadInputTokens,totalTokens:t},contentBlocks:e.contentBlocks,stopReason:e.stopReason,stopSequence:e.stopSequence,eventCount:e.eventCount,streamDurationMs:Date.now()-e.startTime,totalBytesReceived:e.totalBytesReceived,events:e.events,...e.streamErrorMessage?{streamErrorMessage:e.streamErrorMessage}:{},...e.rawTextChunks?{rawText:e.rawTextChunks.join("")}:{},rawTextTruncated:e.rawTextTruncated}}function $Jr(e,t){const r=t.message;if(!r)return;e.messageId=r.id??"",e.model=r.model??"";const n=r.usage;n&&(e.inputTokens+=n.input_tokens??0,e.outputTokens+=n.output_tokens??0,e.cacheCreationInputTokens+=n.cache_creation_input_tokens??0,e.cacheReadInputTokens+=n.cache_read_input_tokens??0)}function UJr(e,t){const r=t.index??0,n=t.content_block;if(!n)return;const o=n.type,s={index:r,type:o};o==="text"?s.text=n.text??"":o==="thinking"?s.thinking=n.thinking??"":o==="tool_use"&&(s.toolName=n.name??"",s.toolId=n.id??"",s.toolInput=""),e.contentBlocks.push(s),e.blockByteCounts.set(r,LJr(s))}function BJr(e,t){const r=t.index??0,n=t.delta;if(!n)return;const o=e.contentBlocks.find(a=>a.index===r);if(!o)return;const s=e.blockByteCounts.get(r)??0,i=s>=rF;if(n.type==="text_delta"&&n.text!==null){const a=n.text,c=zoe(o.text,a,s,rF);e.blockByteCounts.set(r,c.nextBytes),(!i||!o.text?.endsWith(Jd))&&(o.text=c.value)}else if(n.type==="thinking_delta"&&n.thinking!==null){const a=n.thinking,c=zoe(o.thinking,a,s,rF);e.blockByteCounts.set(r,c.nextBytes),(!i||!o.thinking?.endsWith(Jd))&&(o.thinking=c.value)}else if(n.type==="input_json_delta"&&n.partial_json!==null){const a=n.partial_json,c=zoe(o.toolInput,a,s,rF);e.blockByteCounts.set(r,c.nextBytes),(!i||!o.toolInput?.endsWith(Jd))&&(o.toolInput=c.value)}}function zJr(e,t){const r=t.delta;r&&(e.stopReason=r.stop_reason??e.stopReason,e.stopSequence=r.stop_sequence??e.stopSequence);const n=t.usage;n&&(e.outputTokens+=n.output_tokens??0)}function GJr(e,t){e.eventCount++;const r=Date.now();if(e.events.length<OJr-1?t.event==="content_block_delta"?e.events.push({type:t.event,timestamp:r,data:""}):e.events.push({type:t.event,timestamp:r,data:Boe(t.data,$oe)}):e.eventLogTruncated||(e.events.push({type:"truncated",timestamp:r,data:Jd}),e.eventLogTruncated=!0),!t.data)return;if(t.data.length>1024*1024){e.observationIncomplete=!0;return}let n;try{n=JSON.parse(t.data)}catch{e.observationIncomplete=!0;return}const o=n&&typeof n=="object"&&"type"in n?n.type:void 0,s=t.event||(typeof o=="string"?o:"");if(s==="error"||o==="error"){const i=n&&typeof n=="object"?n:{},c=(i.error&&typeof i.error=="object"?i.error:void 0)?.message??i.message;e.streamErrorMessage=typeof c=="string"&&c.trim()?Boe(c.trim(),$oe):Boe(t.data,$oe)}if(s==="message_stop"&&(e.messageStopReceived=!0),s==="content_block_delta"&&n&&typeof n=="object"&&"delta"in n){const i=n.delta;i&&typeof i=="object"&&("text"in i&&typeof i.text=="string"&&i.text.trim().length>0||"partial_json"in i&&typeof i.partial_json=="string"&&i.partial_json.trim().length>0||"refusal"in i&&typeof i.refusal=="string"&&i.refusal.trim().length>0)&&e.firstUsefulOutputAt===void 0&&(e.firstUsefulOutputAt=r,e.firstUsefulOutputEvent=`content_block_delta.${"text"in i?"text":"refusal"in i?"refusal":"partial_json"}`)}if(e.firstUsefulOutputAt===void 0&&n&&typeof n=="object"){const i=n;s==="message_start"&&Toe(i.message)&&(e.firstUsefulOutputAt=r,e.firstUsefulOutputEvent="message_start.content");const a=i.content_block;if(s==="content_block_start"&&a&&typeof a=="object"){const c=a;(typeof c.text=="string"&&c.text.trim().length>0||typeof c.refusal=="string"&&c.refusal.trim().length>0||(c.type==="tool_use"||c.type==="server_tool_use")&&c.input&&typeof c.input=="object"&&Object.keys(c.input).length>0)&&(e.firstUsefulOutputAt=r,e.firstUsefulOutputEvent="content_block_start")}if(s==="content_block_stop"&&typeof i.index=="number"){const c=e.contentBlocks.find(l=>l.index===i.index);c?.type==="tool_use"&&c.toolName&&(e.firstUsefulOutputAt=r,e.firstUsefulOutputEvent="content_block_stop.tool_use")}}switch(s){case"message_start":$Jr(e,n);break;case"content_block_start":UJr(e,n);break;case"content_block_delta":BJr(e,n);break;case"message_delta":zJr(e,n);break;default:break}}function oF(e={}){const t=e.captureRawText??!1,r=NJr(t);let n="",o=!1,s=!1;const i=new TextDecoder;let a;const c=new Promise(w=>{a=w});function l(){s||(s=!0,n.trim()&&(r.observationIncomplete=!0),a(FJr(r)))}const u=new TransformStream({transform(w,E){E.enqueue(w),r.totalBytesReceived+=w.byteLength;const _=i.decode(w,{stream:!0});if(IXt(r,_),n+=_,o){const k=/\r\n\r\n|\n\n|\r\r/.exec(n);if(!k){n=n.slice(-4);return}n=n.slice(k.index+k[0].length),o=!1}const{events:b,remainder:A}=nF(n);n=A,n.length>1024*1024&&(r.observationIncomplete=!0,o=!0,n=n.slice(-4));for(const k of b)GJr(r,k)},flush(){const w=i.decode();w&&(IXt(r,w),n+=w),l()}}),d=u.writable.getWriter();let m;const h=new WritableStream({start(w){m=w},write(w){return d.write(w)},close(){return d.close()},abort(w){return l(),d.abort(w)}});d.closed.catch(w=>{l();try{m.error(w)}catch{}});const f=u.readable.getReader();return{stream:{readable:new ReadableStream({async pull(w){try{const{done:E,value:_}=await f.read();E?w.close():w.enqueue(_)}catch(E){w.error(E)}},async cancel(w){l();try{m.error(w)}catch{}await Promise.allSettled([f.cancel(w),d.abort(w)])}}),writable:h},telemetry:c}}Qt();var Jk=e=>typeof e=="number"&&Number.isFinite(e)&&e>0?Math.floor(e):0;function sF(e){if(!e||typeof e!="object")return!1;if("type"in e){if(e.type==="function_call")return"arguments"in e&&typeof e.arguments=="string"&&e.arguments.trim().length>0;if(e.type==="custom_tool_call")return"input"in e&&typeof e.input=="string"&&e.input.trim().length>0;if(e.type==="output_text")return"text"in e&&typeof e.text=="string"&&e.text.trim().length>0;if(e.type==="refusal")return"refusal"in e&&typeof e.refusal=="string"&&e.refusal.trim().length>0}return"content"in e&&Array.isArray(e.content)&&e.content.some(sF)}function Goe(e){if(e===null||typeof e!="object")return null;const t=e,r=t.response,n=r&&typeof r=="object"&&r.usage?r.usage:t.usage;if(!n||typeof n!="object")return null;const o=n.input_tokens??n.prompt_tokens,s=n.output_tokens??n.completion_tokens;if(o===void 0&&s===void 0)return null;const i=n.input_tokens_details,a=n.output_tokens_details;return{inputTokens:Jk(o),outputTokens:Jk(s),cacheReadTokens:Jk(i?.cached_tokens),cacheCreationTokens:Jk(i?.cache_write_tokens),reasoningTokens:Jk(a?.reasoning_tokens)}}var RXt=256*1024;function qJr(){const e=process.env.NEUROLINK_PROXY_CODEX_CAPTURE;if(!e||process.env.NEUROLINK_PROXY_LOG_SINK==="otel")return null;let t=0,r=!1;return n=>{if(!(t>=RXt))try{const o=RXt-t,s=n.byteLength>o?n.subarray(0,o):n;HS(e,s,{flag:r?"a":"w"}),r=!0,t+=s.byteLength}catch{}}}function jJr(){const e={completed:!1,terminalBytes:0};let t=0;const r=g=>{for(const y of g)if(y.data.trim()!=="[DONE]")try{const w=JSON.parse(y.data);if(!w||typeof w!="object"){e.observationIncomplete=!0;continue}const E=Goe(w);E&&(u=E);const _=w.type??y.event;(_==="response.output_text.delta"||_==="response.refusal.delta"||_==="response.function_call_arguments.delta")&&typeof w.delta=="string"&&w.delta.trim().length>0&&e.firstUsefulOutputAt===void 0&&(e.firstUsefulOutputAt=Date.now(),e.firstUsefulOutputEvent=String(_));const b=sF(w.item),A=w.response,k=_==="response.completed"&&A&&typeof A=="object"&&"output"in A&&Array.isArray(A.output)&&A.output.some(sF),R=_==="response.output_text.done"&&typeof w.text=="string"&&w.text.trim().length>0||_==="response.refusal.done"&&typeof w.refusal=="string"&&w.refusal.trim().length>0||_==="response.function_call_arguments.done"&&typeof w.arguments=="string"&&w.arguments.trim().length>0||_==="response.custom_tool_call_input.done"&&typeof w.input=="string"&&w.input.trim().length>0||(_==="response.content_part.added"||_==="response.content_part.done")&&sF(w.part),I=_==="response.custom_tool_call_input.delta"&&typeof w.delta=="string"&&w.delta.trim().length>0;if(e.firstUsefulOutputAt===void 0&&(R||k||I||(_==="response.output_item.added"||_==="response.output_item.done")&&b)&&(e.firstUsefulOutputAt=Date.now(),e.firstUsefulOutputEvent=String(_)),_==="response.completed")e.completed=!0,e.terminalBytes=t;else if(_==="error"||_==="response.failed"||_==="response.incomplete"){e.errorType="stream_error";const x=w.response,M=x&&typeof x=="object"?x:w,O=M.error,U=O&&typeof O=="object"?O:M,P=M.incomplete_details,N=P&&typeof P=="object"&&"reason"in P?P.reason:void 0;e.errorCode=typeof U.code=="string"?qr(U.code).slice(0,200):typeof N=="string"?qr(N).slice(0,200):String(_),e.errorMessage=typeof U.message=="string"?qr(U.message).slice(0,200):_==="response.incomplete"?"Codex reported an incomplete response":"Codex reported a stream failure",e.terminalBytes=t}}catch{e.observationIncomplete=!0}};let n=()=>{};const o=new Promise(g=>{n=g});let s=!1;const i=g=>{s||(s=!0,n(g))},a=new TextDecoder,c=qJr();let l="",u=null;const d=1024*1024;let m=!1;const h={transform(g,y){y.enqueue(g),t+=g.byteLength;try{if(c?.(g),l+=a.decode(g,{stream:!0}),m){const _=/\r\n\r\n|\n\n|\r\r/.exec(l);if(!_){l=l.slice(-3);return}l=l.slice(_.index+_[0].length),m=!1}const{events:w,remainder:E}=nF(l);l=E,r(w),l.length>d&&(e.observationIncomplete=!0,l=l.slice(-2),m=!0)}catch{e.observationIncomplete=!0}},flush(){(m||l.trim())&&(e.observationIncomplete=!0),i(u)},cancel(){i(u)}};return{stream:new TransformStream(h),usage:o,evidence:()=>({...e})}}var Yk=class extends Error{status;responseBody;constructor(e,t){super(`Codex fallback request returned HTTP ${e}`),this.name="CodexFallbackResponseError",this.status=e,this.responseBody=t}};function Pl(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Ow(e){return typeof e=="string"&&e.length>0?e:void 0}function HJr(e){const t=[];if(typeof e.system=="string")e.system&&t.push(e.system);else if(Array.isArray(e.system)){const r=e.system.map(n=>typeof n.text=="string"?n.text:"").filter(Boolean).join(`
2284
2284
 
2285
- `)||void 0}function VJr(e){if(e.source.type==="url"&&e.source.url)return e.source.url;if(e.source.type==="base64"&&e.source.data)return`data:${e.source.media_type??"image/png"};base64,${e.source.data}`}function MXt(e){return typeof e=="string"?e:e.map(t=>{switch(t.type){case"text":return t.text;case"thinking":return t.thinking;case"image":return"[image attachment]";case"tool_use":return`[tool call ${t.name}] ${JSON.stringify(t.input??{})}`;case"tool_result":return MXt(t.content)}}).join(`
2286
- `)}function WJr(e,t){const r=t==="assistant"?"output_text":"input_text";switch(e.type){case"text":return{type:r,text:e.text};case"thinking":return{type:r,text:e.thinking};case"image":{const n=VJr(e);return t==="user"&&n?{type:"input_image",image_url:n}:{type:r,text:"[image attachment]"}}}}function KJr(e,t){if(typeof t=="string")return[{role:e,content:[{type:e==="assistant"?"output_text":"input_text",text:t}]}];const r=[];let n=[];const o=()=>{n.length!==0&&(r.push({role:e,content:n}),n=[])};for(const s of t){if(s.type==="tool_use"){o(),r.push({type:"function_call",call_id:s.id,name:s.name,arguments:JSON.stringify(s.input??{})});continue}if(s.type==="tool_result"){o(),r.push({type:"function_call_output",call_id:s.tool_use_id,output:MXt(s.content)});continue}n.push(WJr(s,e))}return o(),r}function JJr(e,t,r){const n=e.messages.flatMap(i=>KJr(i.role,i.content)),o={model:t,input:n,stream:!0,store:!1,...r!==void 0?{reasoning:{effort:r}}:{}},s=HJr(e);if(s&&(o.instructions=s),e.tools&&e.tools.length>0&&(o.tools=e.tools.map(i=>({type:"function",name:i.name,...i.description?{description:i.description}:{},parameters:i.input_schema}))),e.tool_choice)switch(e.tool_choice.type){case"any":o.tool_choice="required";break;case"tool":o.tool_choice={type:"function",name:e.tool_choice.name};break;default:o.tool_choice=e.tool_choice.type;break}return o}function YJr(e){if(Pl(e))return e;if(typeof e!="string")throw new Error("Codex fallback function call is missing JSON arguments");try{const t=JSON.parse(e||"{}");if(!Pl(t))throw new Error("not an object");return t}catch{throw new Error("Codex fallback function call returned invalid JSON arguments")}}function qoe(e){return!Pl(e)||e.type!=="message"||!Array.isArray(e.content)?"":e.content.filter(Pl).filter(t=>t.type==="output_text").map(t=>typeof t.text=="string"?t.text:"").join("")}function PXt(e,t){if(e.type!=="function_call")return;const r=Ow(e.call_id),n=Ow(e.name);if(!r||!n)throw new Error("Codex fallback function call is missing an id or name");t.set(r,{toolCallId:r,toolName:n,args:YJr(e.arguments)})}function DXt(e){const t=e.replace(/\r\n?/g,`
2285
+ `);r&&t.push(r)}for(const r of e.messages){if(r.role!=="system")continue;const n=typeof r.content=="string"?r.content:r.content.map(o=>o.type==="text"?o.text:"").filter(Boolean).join(`
2286
+ `);n&&t.push(n)}return t.length>0?t.join(`
2287
+
2288
+ `):void 0}function VJr(e){if(e.source.type==="url"&&e.source.url)return e.source.url;if(e.source.type==="base64"&&e.source.data)return`data:${e.source.media_type??"image/png"};base64,${e.source.data}`}function MXt(e){return typeof e=="string"?e:e.map(t=>{switch(t.type){case"text":return t.text;case"thinking":return t.thinking;case"image":return"[image attachment]";case"tool_use":return`[tool call ${t.name}] ${JSON.stringify(t.input??{})}`;case"tool_result":return MXt(t.content)}}).join(`
2289
+ `)}function WJr(e,t){const r=t==="assistant"?"output_text":"input_text";switch(e.type){case"text":return{type:r,text:e.text};case"thinking":return{type:r,text:e.thinking};case"image":{const n=VJr(e);return t==="user"&&n?{type:"input_image",image_url:n}:{type:r,text:"[image attachment]"}}}}function KJr(e,t){if(typeof t=="string")return[{role:e,content:[{type:e==="assistant"?"output_text":"input_text",text:t}]}];const r=[];let n=[];const o=()=>{n.length!==0&&(r.push({role:e,content:n}),n=[])};for(const s of t){if(s.type==="tool_use"){o(),r.push({type:"function_call",call_id:s.id,name:s.name,arguments:JSON.stringify(s.input??{})});continue}if(s.type==="tool_result"){o(),r.push({type:"function_call_output",call_id:s.tool_use_id,output:MXt(s.content)});continue}if(s.type==="tool_addition")continue;const i=WJr(s,e);i&&n.push(i)}return o(),r}function JJr(e,t,r){const n=e.messages.flatMap(i=>i.role==="system"?[]:KJr(i.role,i.content)),o={model:t,input:n,stream:!0,store:!1,...r!==void 0?{reasoning:{effort:r}}:{}},s=HJr(e);if(s&&(o.instructions=s),e.tools&&e.tools.length>0&&(o.tools=e.tools.map(i=>({type:"function",name:i.name,...i.description?{description:i.description}:{},parameters:i.input_schema}))),e.tool_choice)switch(e.tool_choice.type){case"any":o.tool_choice="required";break;case"tool":o.tool_choice={type:"function",name:e.tool_choice.name};break;default:o.tool_choice=e.tool_choice.type;break}return o}function YJr(e){if(Pl(e))return e;if(typeof e!="string")throw new Error("Codex fallback function call is missing JSON arguments");try{const t=JSON.parse(e||"{}");if(!Pl(t))throw new Error("not an object");return t}catch{throw new Error("Codex fallback function call returned invalid JSON arguments")}}function qoe(e){return!Pl(e)||e.type!=="message"||!Array.isArray(e.content)?"":e.content.filter(Pl).filter(t=>t.type==="output_text").map(t=>typeof t.text=="string"?t.text:"").join("")}function PXt(e,t){if(e.type!=="function_call")return;const r=Ow(e.call_id),n=Ow(e.name);if(!r||!n)throw new Error("Codex fallback function call is missing an id or name");t.set(r,{toolCallId:r,toolName:n,args:YJr(e.arguments)})}function DXt(e){const t=e.replace(/\r\n?/g,`
2287
2290
  `).split(`
2288
2291
 
2289
2292
  `),r=[];for(const n of t){if(!n.trim())continue;let o;const s=[];for(const a of n.split(`
@@ -25,17 +25,40 @@ function asNonEmptyString(value) {
25
25
  return typeof value === "string" && value.length > 0 ? value : undefined;
26
26
  }
27
27
  function buildSystemInstructions(body) {
28
+ const instructions = [];
28
29
  if (typeof body.system === "string") {
29
- return body.system || undefined;
30
+ if (body.system) {
31
+ instructions.push(body.system);
32
+ }
30
33
  }
31
- if (Array.isArray(body.system)) {
34
+ else if (Array.isArray(body.system)) {
32
35
  const text = body.system
33
36
  .map((block) => (typeof block.text === "string" ? block.text : ""))
34
37
  .filter(Boolean)
35
38
  .join("\n\n");
36
- return text || undefined;
39
+ if (text) {
40
+ instructions.push(text);
41
+ }
37
42
  }
38
- return undefined;
43
+ for (const message of body.messages) {
44
+ // Claude's public Messages type restricts message roles to user/assistant,
45
+ // but Claude Code can emit an inline system message for context-management
46
+ // edits. Preserve its text as instructions instead of sending a non-leading
47
+ // system item to the Codex conversation input.
48
+ if (message.role !== "system") {
49
+ continue;
50
+ }
51
+ const text = typeof message.content === "string"
52
+ ? message.content
53
+ : message.content
54
+ .map((block) => (block.type === "text" ? block.text : ""))
55
+ .filter(Boolean)
56
+ .join("\n");
57
+ if (text) {
58
+ instructions.push(text);
59
+ }
60
+ }
61
+ return instructions.length > 0 ? instructions.join("\n\n") : undefined;
39
62
  }
40
63
  function imageUrlForBlock(block) {
41
64
  if (block.source.type === "url" && block.source.url) {
@@ -126,14 +149,26 @@ function convertClaudeMessage(role, content) {
126
149
  });
127
150
  continue;
128
151
  }
129
- messageContent.push(toCodexContentPart(block, role));
152
+ // Claude Code context-management messages can contain `tool_addition`
153
+ // blocks. The live tool definitions are already carried by `body.tools`;
154
+ // these history markers must not become undefined array entries because
155
+ // JSON encodes array undefined values as null and Codex rejects them.
156
+ if (block.type === "tool_addition") {
157
+ continue;
158
+ }
159
+ const contentPart = toCodexContentPart(block, role);
160
+ if (contentPart) {
161
+ messageContent.push(contentPart);
162
+ }
130
163
  }
131
164
  flushMessage();
132
165
  return input;
133
166
  }
134
167
  /** Convert a Claude Messages request into the ChatGPT Codex Responses shape. */
135
168
  export function convertClaudeRequestToCodex(body, model, reasoningEffort) {
136
- const input = body.messages.flatMap((message) => convertClaudeMessage(message.role, message.content));
169
+ const input = body.messages.flatMap((message) => message.role === "system"
170
+ ? []
171
+ : convertClaudeMessage(message.role, message.content));
137
172
  const request = {
138
173
  model,
139
174
  input,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@juspay/neurolink",
3
- "version": "12.14.17",
3
+ "version": "12.14.18",
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": {