function m(t,l){let o=String(t??"");return o.length<=l?o:`${o.slice(0,Math.max(0,l-30))}

[tool result truncated for size]`}function J(t,l){if(typeof t=="string")return m(t,l);try{return m(JSON.stringify(t),l)}catch{return m(String(t),l)}}function p(t){let l=new Set;for(let e of t)if(e.role==="assistant"&&Array.isArray(e.tool_calls))for(let n of e.tool_calls)l.add(n.id);let o=t.filter(e=>e.role==="tool"?l.has(e.tool_call_id):!0),s=new Set;for(let e of o)e.role==="tool"&&s.add(e.tool_call_id);return o.map(e=>{if(e.role!=="assistant"||!Array.isArray(e.tool_calls)||e.tool_calls.every(u=>s.has(u.id)))return e;let{tool_calls:f,...r}=e;return{...r,content:r.content||""}})}function N(t){let l=Array.isArray(t?.messages)?t.messages:[],o=l.find(n=>n.role==="system"),s=l.slice(-4).map(n=>({...n,content:m(n.content,n.role==="tool"?1200:2500)}));s=p(s);let e={...t,messages:[o,...s].filter(Boolean)};return delete e.tools,e}async function O({body:t,streaming:l,auth:o,options:s,fetchCompletion:e,fetchStreamingCompletion:n,onFallbackLog:f}){try{return l?await n(t,o,s):await e(t,o,s)}catch(r){let u=String(r?.message||r||"");if(!/proxy error 413|payload too large/i.test(u))throw r;let i=N(t);return typeof f=="function"&&f(t,i),{data:l?await n(i,o,s):await e(i,o,s),fallback:i}}}async function P({body:t,auth:l,options:o,streaming:s,toolContext:e,activeSkills:n,round:f,verbose:r,dependencies:u,config:i={}}){let h=i.maxToolResultChars||3e3,{fetchCompletion:x,fetchStreamingCompletion:w,onFallbackLog:R,hasToolCalls:k,getTextContent:C,parseToolCalls:S,buildAssistantMessage:z,buildToolResultMessage:B,executeTool:M,onToolCallLog:_,injectTools:F}=u;Array.isArray(t?.messages)&&(t.messages=p(t.messages));let g=await O({body:t,streaming:s,auth:l,options:o,fetchCompletion:x,fetchStreamingCompletion:w,onFallbackLog:R}),d=g?.data||g;if(!k(d))return{done:!0,text:C(d),body:g?.fallback||t};let c=S(d),y=g?.fallback||t;y.messages.push(z(d)),r&&typeof _=="function"&&_(c);let T=await Promise.all(c.map((a,A)=>(typeof o.onToolCall=="function"&&o.onToolCall(a.name,a.args,{round:f,index:A,total:c.length}),M(a,e))));for(let a=0;a<c.length;a++){let I=c[a].name==="get_skill_context"?typeof T[a]=="string"?T[a]:JSON.stringify(T[a]):J(T[a],h);y.messages.push(B(c[a].id,I))}return typeof o.onToolCall=="function"&&o.onToolCall(null),F(y,n),{done:!1,body:y}}export{P as runAssistantRound};
