function i(s){return Buffer.byteLength(JSON.stringify(s),"utf8")}function c(s,t){let o=String(s||"");if(o.length<=t)return o;let n=Math.max(0,t-28);return`${o.slice(0,n)}

[truncated for size budget]`}function f(s,t=0){if(!s||typeof s!="object"||t>8)return s;if(Array.isArray(s))return s.map(n=>f(n,t+1));let o={};for(let[n,e]of Object.entries(s))n==="description"||n==="title"||n==="examples"||n==="default"||(o[n]=f(e,t+1));return o}function _(s=[]){return s.map(t=>({...t,function:{...t.function,description:c(t.function?.description||"",180),parameters:f(t.function?.parameters||{type:"object",properties:{}})}}))}function g(s){let t=new Set;for(let e of s)if(e.role==="assistant"&&Array.isArray(e.tool_calls))for(let r of e.tool_calls)t.add(r.id);let o=s.filter(e=>e.role==="tool"?t.has(e.tool_call_id):!0),n=new Set;for(let e of o)e.role==="tool"&&n.add(e.tool_call_id);return o.map(e=>{if(e.role!=="assistant"||!Array.isArray(e.tool_calls)||e.tool_calls.every(a=>n.has(a.id)))return e;let{tool_calls:u,...l}=e;return{...l,content:l.content||""}})}function y(s,t={}){let o=t.maxBytes||49e3,n=t.systemMaxChars||12e3,e={...s,messages:Array.isArray(s.messages)?[...s.messages]:[],tools:Array.isArray(s.tools)?_(s.tools):s.tools};e.messages.length>0&&e.messages[0]?.role==="system"&&(e.messages[0]={...e.messages[0],content:c(e.messages[0].content,n)});let r=!1;for(;i(e)>o&&e.messages.length>2;)e.messages.splice(1,1),r=!0;if(r&&(e.messages=g(e.messages)),i(e)>o&&e.messages.length>0&&(e.messages[0]={...e.messages[0],content:c(e.messages[0].content,6e3)},r=!0),i(e)>o){let u=e.messages.find(a=>a.role==="system")||e.messages[0],l=e.messages.slice(-2);e.messages=g([u,...l].filter(Boolean).map((a,m)=>({...a,content:c(a.content,m===0?4e3:8e3)}))),r=!0}return{body:e,meta:{bytes:i(e),trimmed:r,maxBytes:o,messageCount:e.messages.length}}}export{y as applyPayloadBudget};
