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