var p=class{async fetchCompletion(e,o,s={}){throw new Error("fetchCompletion() must be implemented")}async fetchStreamingCompletion(e,o,s={}){throw new Error("fetchStreamingCompletion() must be implemented")}};function _(n){return Buffer.byteLength(JSON.stringify(n),"utf8")}function S(n,e){let o=String(n||"");if(o.length<=e)return o;let s=Math.max(0,e-28);return`${o.slice(0,s)}

[truncated for size budget]`}function B(n,e=0){if(!n||typeof n!="object"||e>8)return n;if(Array.isArray(n))return n.map(s=>B(s,e+1));let o={};for(let[s,t]of Object.entries(n))s==="description"||s==="title"||s==="examples"||s==="default"||(o[s]=B(t,e+1));return o}function U(n=[]){return n.map(e=>({...e,function:{...e.function,description:S(e.function?.description||"",180),parameters:B(e.function?.parameters||{type:"object",properties:{}})}}))}function R(n){let e=new Set;for(let t of n)if(t.role==="assistant"&&Array.isArray(t.tool_calls))for(let r of t.tool_calls)e.add(r.id);let o=n.filter(t=>t.role==="tool"?e.has(t.tool_call_id):!0),s=new Set;for(let t of o)t.role==="tool"&&s.add(t.tool_call_id);return o.map(t=>{if(t.role!=="assistant"||!Array.isArray(t.tool_calls)||t.tool_calls.every(a=>s.has(a.id)))return t;let{tool_calls:m,...c}=t;return{...c,content:c.content||""}})}function E(n,e={}){let o=e.maxBytes||49e3,s=e.systemMaxChars||12e3,t={...n,messages:Array.isArray(n.messages)?[...n.messages]:[],tools:Array.isArray(n.tools)?U(n.tools):n.tools};t.messages.length>0&&t.messages[0]?.role==="system"&&(t.messages[0]={...t.messages[0],content:S(t.messages[0].content,s)});let r=!1;for(;_(t)>o&&t.messages.length>2;)t.messages.splice(1,1),r=!0;if(r&&(t.messages=R(t.messages)),_(t)>o&&t.messages.length>0&&(t.messages[0]={...t.messages[0],content:S(t.messages[0].content,6e3)},r=!0),_(t)>o){let m=t.messages.find(a=>a.role==="system")||t.messages[0],c=t.messages.slice(-2);t.messages=R([m,...c].filter(Boolean).map((a,i)=>({...a,content:S(a.content,i===0?4e3:8e3)}))),r=!0}return{body:t,meta:{bytes:_(t),trimmed:r,maxBytes:o,messageCount:t.messages.length}}}var $=n=>Buffer.byteLength(JSON.stringify(n),"utf8"),k=class extends p{async fetchCompletion(e,o,s={}){let t=$(e),{body:r,meta:m}=E(e,s.payloadCompaction);s.onBudget?.({streaming:!1,beforeBytes:t,meta:m});let c=this.#t(s),a=`${o.baseUrl}${s.chatCompletionsPath||"/v1/chat/completions"}`,i=await fetch(a,{method:"POST",headers:o.headers,body:JSON.stringify(r),signal:c});if(!i.ok){let l=await i.text();throw i.status===401||i.status===403?new Error("Session expired. Run `zibby login` to re-authenticate."):new Error(`Proxy error ${i.status}: ${l}`)}return i.json()}async fetchStreamingCompletion(e,o,s={}){let t={...e,stream:!0},r=$(t),{body:m,meta:c}=E(t,s.payloadCompaction);s.onBudget?.({streaming:!0,beforeBytes:r,meta:c});let a=this.#t(s),i=`${o.baseUrl}${s.chatCompletionsPath||"/v1/chat/completions"}`,l=await fetch(i,{method:"POST",headers:o.headers,body:JSON.stringify(m),signal:a});if(!l.ok){let y=await l.text();throw l.status===401||l.status===403?new Error("Session expired. Run `zibby login` to re-authenticate."):new Error(`Proxy error ${l.status}: ${y}`)}let O=l.body.getReader(),P=new TextDecoder,b="",A="",g=new Map;for(;;){let{done:y,value:u}=await O.read();if(y)break;b+=P.decode(u,{stream:!0});let h=b.split(`
`);b=h.pop();for(let T of h){if(!T.startsWith("data: "))continue;let C=T.slice(6).trim();if(C==="[DONE]")continue;let M;try{M=JSON.parse(C)}catch{continue}let d=M.choices?.[0]?.delta;if(d&&(d.content&&(A+=d.content,s.onToken&&s.onToken(d.content)),d.tool_calls))for(let f of d.tool_calls){let w=f.index??0;g.has(w)||g.set(w,{id:"",name:"",args:""});let x=g.get(w);f.id&&(x.id=f.id),f.function?.name&&(x.name=f.function.name),f.function?.arguments!=null&&(x.args+=f.function.arguments)}}}if(g.size>0){let y=[...g.entries()].sort(([u],[h])=>u-h).map(([,u])=>({id:u.id,type:"function",function:{name:u.name,arguments:u.args}}));return{choices:[{message:{role:"assistant",content:A||null,tool_calls:y}}]}}return{choices:[{message:{role:"assistant",content:A}}]}}#t(e={}){let o=[e.signal,e.timeout?AbortSignal.timeout(e.timeout):null].filter(Boolean);return o.length>1?AbortSignal.any(o):o[0]||void 0}};export{k as OpenAICompletionProvider};
