qlogicagent 2.24.4 → 2.24.6

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.
@@ -1,29 +1,29 @@
1
- function _e(e,t,n,o){return{role:"assistant",content:t||null,tool_calls:e,...n&&n.length>0?{thinkingBlocks:n}:{},...o?{reasoning_content:o}:{}}}function Re(e,t){let n=t.ok?typeof t.payload=="string"?t.payload:JSON.stringify(t.payload??""):`Error: ${t.error??"Tool execution failed"}`;return{role:"tool",tool_call_id:e,content:n,...!t.ok&&{is_error:!0},...t.toolReferences?.length?{toolReferences:t.toolReferences}:{},...t.imageUrls?.length?{imageUrls:t.imageUrls}:{},...t.contentBlocks!==void 0?{contentBlocks:t.contentBlocks}:{},...t.structuredContent!==void 0?{structuredContent:t.structuredContent}:{},...t.mcpMeta!==void 0?{mcpMeta:t.mcpMeta}:{},...t.mcpIsError!==void 0?{mcpIsError:t.mcpIsError}:{}}}var xe=/\b(?:daily|weekly|monthly)(?:\/(?:daily|weekly|monthly))* (?:usage )?limit(?:s)?(?: (?:exhausted|reached|exceeded))?\b/i,h={rateLimit:[/rate[_ ]limit|too many requests|429/,"model_cooldown","exceeded your current quota","resource has been exhausted","quota exceeded","resource_exhausted","usage limit",/\btpm\b/i,"tokens per minute","tokens per day"],overloaded:[/overloaded_error|"type"\s*:\s*"overloaded_error"/i,"overloaded",/service[_ ]unavailable.*(?:overload|capacity|high[_ ]demand)|(?:overload|capacity|high[_ ]demand).*service[_ ]unavailable/i,"high demand"],timeout:["timeout","timed out","service unavailable","deadline exceeded","context deadline exceeded","connection error","network error","network request failed","fetch failed","socket hang up",/\beconn(?:refused|reset|aborted)\b/i,/\benotfound\b/i,/\beai_again\b/i,/without sending (?:any )?chunks?/i,/\bstop reason:\s*(?:abort|error|network_error)\b/i,/\breason:\s*(?:abort|error|network_error)\b/i,/\bunhandled stop reason:\s*(?:abort|error|network_error)\b/i],billing:[/["']?(?:status|code)["']?\s*[:=]\s*402\b|\bhttp\s*402\b|\berror(?:\s+code)?\s*[:=]?\s*402\b|\b(?:got|returned|received)\s+(?:a\s+)?402\b|^\s*402\s+payment/i,"payment required","insufficient credits",/insufficient[_ ]quota/i,"credit balance","plans & billing","insufficient balance"],authPermanent:[/api[_ ]?key[_ ]?(?:revoked|invalid|deactivated|deleted)/i,"invalid_api_key","key has been disabled","key has been revoked","account has been deactivated",/could not (?:authenticate|validate).*(?:api[_ ]?key|credentials)/i,"permission_error","not allowed for this organization"],auth:[/invalid[_ ]?api[_ ]?key/,"incorrect api key","invalid token","authentication","re-authenticate","oauth token refresh failed","unauthorized","forbidden","access denied","insufficient permissions","insufficient permission",/missing scopes?:/i,"expired","token has expired",/\b401\b/,/\b403\b/,"no credentials found","no api key found"],format:["string should match pattern","tool_use.id","tool_use_id","messages.1.content.1.tool_use.id","invalid request format",/tool call id was.*must be/i]},ke=/^(?:error[:\s-]+)?billing(?:\s+error)?(?:[:\s-]+|$)|^(?:error[:\s-]+)?(?:credit balance|insufficient credits?|payment required|http\s*402\b)/i,Ae=/["']?(?:status|code)["']?\s*[:=]\s*402\b|\bhttp\s*402\b|\berror(?:\s+code)?\s*[:=]?\s*402\b|^\s*402\s+payment/i,Se=512,Ee=/^(?:http\s*)?(\d{3})(?:\s+([\s\S]+))?$/i;var Me=new Set([500,502,503,504,521,522,523,524,529]),ve=["insufficient credits","insufficient quota","credit balance","insufficient balance","plans & billing","add more credits","top up"],Ie=["upgrade your plan","upgrade plan","current plan","subscription"],we=["daily","weekly","monthly"],Oe=["try again","retry","temporary","cooldown"],Le=["usage limit","rate limit","organization usage"],Pe=["organization","workspace"],Ne=["billing period","exceeded","reached","exhausted"],Fe=/["']?(?:status|code)["']?\s*[:=]\s*402\b|\bhttp\s*402\b|\berror(?:\s+code)?\s*[:=]?\s*402\b|\b(?:got|returned|received)\s+(?:a\s+)?402\b|^\s*402\s+payment required\b/i,De=/^(?:error[:\s-]+)?(?:(?:http\s*)?402(?:\s+payment required)?|payment required)(?:[:\s-]+|$)/i;function T(e,t){if(!e)return!1;let n=e.toLowerCase();return t.some(o=>o instanceof RegExp?o.test(n):n.includes(o))}function Be(e){return T(e,h.format)}function Q(e){return T(e,h.rateLimit)}function Ue(e){return T(e,h.timeout)}function Ge(e){return xe.test(e)}function P(e){let t=e.toLowerCase();return t?e.length>Se?Ae.test(t):T(t,h.billing)?!0:ke.test(e)?t.includes("upgrade")||t.includes("credits")||t.includes("payment")||t.includes("plan"):!1:!1}function ee(e){return T(e,h.authPermanent)}function $e(e){return T(e,h.auth)}function te(e){return T(e,h.overloaded)}function y(e,t){return t.some(n=>e.includes(n))}function je(e){return y(e,ve)||y(e,Ie)&&e.includes("limit")||e.includes("billing hard limit")||e.includes("hard limit reached")||e.includes("maximum allowed")&&e.includes("limit")}function ze(e){let t=y(e,we),n=e.includes("spend limit")||e.includes("spending limit"),o=y(e,Pe);return y(e,Oe)&&y(e,Le)||t&&(e.includes("usage limit")||n)||t&&e.includes("limit")&&e.includes("reset")||o&&e.includes("limit")&&(n||y(e,Ne))}function qe(e){return e.trim().toLowerCase().replace(De,"").trim()}function ne(e){let t=qe(e);return!t||je(t)?"billing":Q(t)||ze(t)?"rate_limit":"billing"}function He(e){return Fe.test(e)?ne(e):null}function oe(e){let t=e.match(Ee);if(!t)return null;let n=Number(t[1]);return Number.isFinite(n)?{code:n,rest:(t[2]??"").trim()}:null}function Ye(e){if(!e)return!1;let t=e.toLowerCase();return t.includes('"type":"api_error"')&&t.includes("internal server error")}function We(e){let t=e.trim();if(!t)return!1;let n=oe(t);return n?Me.has(n.code):!1}function re(e,t){return typeof e!="number"||!Number.isFinite(e)?null:e===402?t?ne(t):"billing":e===429?"rate_limit":e===401||e===403?t&&ee(t)?"auth_permanent":"auth":e===408?"timeout":e===503?t&&te(t)?"overloaded":"timeout":e===502||e===504?"timeout":e===529?"overloaded":e===400?t&&P(t)?"billing":"format":null}function Xe(e){if(!e)return!1;let t=e.toLowerCase();return!!(t.includes("unknown model")||t.includes("model not found")||t.includes("model_not_found")||t.includes("not_found_error")||t.includes("does not exist")&&t.includes("model")||t.includes("invalid model")&&!t.includes("invalid model reference")||/models\/[^\s]+ is not found/i.test(e)||/\b404\b/.test(e)&&/not[-_ ]?found/i.test(e))}function Ke(e){if(!e)return!1;let t=e.toLowerCase();return t.includes("session not found")||t.includes("session does not exist")||t.includes("session expired")||t.includes("session invalid")||t.includes("conversation not found")||t.includes("conversation does not exist")||t.includes("conversation expired")||t.includes("conversation invalid")||t.includes("no such session")||t.includes("invalid session")||t.includes("session id not found")||t.includes("conversation id not found")}function se(e){if(Ke(e))return"session_expired";if(Xe(e))return"model_not_found";let t=He(e);return t||(Ge(e)?P(e)?"billing":"rate_limit":Q(e)?"rate_limit":te(e)?"overloaded":We(e)?oe(e.trim())?.code===529?"overloaded":"timeout":Ye(e)?"timeout":Be(e)?"format":P(e)?"billing":Ue(e)?"timeout":ee(e)?"auth_permanent":$e(e)?"auth":null)}var Ve=new Set(["RETRYABLE_TRANSIENT","RETRYABLE_DEGRADED","TOOL_EXECUTION_FAILED"]);function ie(e){return Ve.has(e)}var Je={timeout:"RETRYABLE_TRANSIENT",overloaded:"RETRYABLE_TRANSIENT",rate_limit:"RETRYABLE_DEGRADED",auth:"NON_RETRYABLE_AUTH",auth_permanent:"NON_RETRYABLE_AUTH",billing:"NON_RETRYABLE_QUOTA",format:"NON_RETRYABLE_CONTENT",model_not_found:"NON_RETRYABLE_CONTENT",session_expired:"NON_RETRYABLE_CONTENT",unknown:"RETRYABLE_TRANSIENT"};function Ze(e,t){let n=re(e,t)??(t?se(t):null);return n?Je[n]:typeof e=="number"&&e>=400&&e<500?"NON_RETRYABLE_CONTENT":"RETRYABLE_TRANSIENT"}function q(e){return typeof e.compressAsync=="function"}var E="[Context capsule v1]";function C(e){return e.replace(/\b(api[_-]?key|access[_-]?token|refresh[_-]?token|password|passwd|secret)\b\s*[:=]\s*["']?[^\s"',;]+/giu,"$1=[REDACTED]").replace(/\b(?:sk|rk|pk)-[A-Za-z0-9_-]{12,}\b/gu,"[REDACTED_TOKEN]").replace(/\bBearer\s+[A-Za-z0-9._~+/=-]{8,}\b/giu,"Bearer [REDACTED]")}function Qe(e){let t=2166136261;for(let n=0;n<e.length;n++)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return(t>>>0).toString(16).padStart(8,"0")}function k(e){if(!(!e||typeof e.content!="string"||!e.content.startsWith(E)))try{let t=JSON.parse(e.content.slice(E.length).trim());return t?.receipt?.version===1&&typeof t.receipt.digest=="string"?t:void 0}catch{return}}function ce(e,t,n,o){let r=e.map(c=>c.itemId).filter(c=>!!c),i={...o?.state.anchors??{}};for(let c of e)for(let u of c.contextAnchors??[]){let p=i[u.category]??[];i[u.category]=[...new Set([...p,C(u.value)])].slice(-50)}let s=[...o?.state.userRequests??[],...e.filter(c=>c.role==="user").map(c=>C(typeof c.content=="string"?c.content:JSON.stringify(c.content??"")))].slice(-50),a={summary:C(t),userRequests:s,anchors:i},l={version:1,sourceMessageCount:(o?.receipt.sourceMessageCount??0)+e.length,sourceItemIds:[...new Set([...o?.receipt.sourceItemIds??[],...r])].slice(-200),firstItemId:o?.receipt.firstItemId??r[0],lastItemId:r.at(-1)??o?.receipt.lastItemId,priorDigest:o?.receipt.digest,tokensBefore:(o?.receipt.tokensBefore??0)+e.reduce((c,u)=>c+n(u),0)};return{receipt:{...l,digest:Qe(JSON.stringify({receipt:l,state:a}))},state:a}}function ue(e){return{role:"system",content:`${E}
2
- ${JSON.stringify(e)}`}}var ae=4;function le(e){return{role:"system",content:`[${e} earlier messages removed to fit the context budget]`}}var N=class{constructor(t){this.estimateTokens=t}estimateTokens;compress(t,n){let o=[],r=[];for(let p of t)p.role==="system"?o.push(p):r.push(p);let i=n;for(let p of o)i-=this.estimateTokens(p);let s;for(let p of r)if(p.role==="user"){s=p;break}if(s&&(i-=this.estimateTokens(s)),i<=0){let p=r.length-(s?1:0),d=s?[...o,s]:[...o];return p>0&&d.push(le(p)),{messages:d,droppedCount:p,strategy:"sliding-window"}}let a=[],l=0;for(let p=r.length-1;p>=0;p--){let d=r[p];if(d===s)continue;let m=this.estimateTokens(d);if(i-m<0&&l>=ae)break;if(i-m<0&&l<ae){a.unshift(d),l++;continue}i-=m,a.unshift(d),l++}let c=r.length-(a.length+(s&&!a.includes(s)?1:0)),u=[...o];return s&&!a.includes(s)&&u.push(s),c>0&&u.push(le(c)),u.push(...a),{messages:u,droppedCount:c,strategy:"sliding-window"}}},F=class{constructor(t,n){this.recentCount=t;this.summarize=n}recentCount;summarize;compress(t,n){let o=t.filter(l=>l.role==="system"),r=t.filter(l=>l.role!=="system");if(r.length<=this.recentCount)return{messages:t,droppedCount:0,strategy:"summarize-old"};let i=r.slice(0,r.length-this.recentCount),s=r.slice(r.length-this.recentCount),a=this.summarize(i);return{messages:[...o,{role:"system",content:`[Conversation summary]
3
- ${a}`},...s],droppedCount:i.length,strategy:"summarize-old"}}},D=class{constructor(t=8e3){this.maxToolResultChars=t}maxToolResultChars;compress(t,n){let o=0;return{messages:t.map(i=>i.role!=="tool"||typeof i.content!="string"||i.content.length<=this.maxToolResultChars?i:(o++,{...i,content:et(i.content,this.maxToolResultChars)})),droppedCount:o,strategy:"tool-result-trim"}}};function et(e,t){if(e.length<=t)return e;let n=e.slice(0,t);if(e.trimStart().startsWith("{")||e.trimStart().startsWith("[")){let i=Math.max(n.lastIndexOf("},"),n.lastIndexOf("],"),n.lastIndexOf(`}
1
+ function _e(e,t,n,o){return{role:"assistant",content:t||null,tool_calls:e,...n&&n.length>0?{thinkingBlocks:n}:{},...o?{reasoning_content:o}:{}}}function Re(e,t){let n=t.ok?typeof t.payload=="string"?t.payload:JSON.stringify(t.payload??""):`Error: ${t.error??"Tool execution failed"}`;return{role:"tool",tool_call_id:e,content:n,...!t.ok&&{is_error:!0},...t.toolReferences?.length?{toolReferences:t.toolReferences}:{},...t.imageUrls?.length?{imageUrls:t.imageUrls}:{},...t.contentBlocks!==void 0?{contentBlocks:t.contentBlocks}:{},...t.structuredContent!==void 0?{structuredContent:t.structuredContent}:{},...t.mcpMeta!==void 0?{mcpMeta:t.mcpMeta}:{},...t.mcpIsError!==void 0?{mcpIsError:t.mcpIsError}:{}}}var xe=/\b(?:daily|weekly|monthly)(?:\/(?:daily|weekly|monthly))* (?:usage )?limit(?:s)?(?: (?:exhausted|reached|exceeded))?\b/i,h={rateLimit:[/rate[_ ]limit|too many requests|429/,"model_cooldown","exceeded your current quota","resource has been exhausted","quota exceeded","resource_exhausted","usage limit",/\btpm\b/i,"tokens per minute","tokens per day"],overloaded:[/overloaded_error|"type"\s*:\s*"overloaded_error"/i,"overloaded",/service[_ ]unavailable.*(?:overload|capacity|high[_ ]demand)|(?:overload|capacity|high[_ ]demand).*service[_ ]unavailable/i,"high demand"],timeout:["timeout","timed out","service unavailable","deadline exceeded","context deadline exceeded","connection error","network error","network request failed","fetch failed","socket hang up",/\beconn(?:refused|reset|aborted)\b/i,/\benotfound\b/i,/\beai_again\b/i,/without sending (?:any )?chunks?/i,/\bstop reason:\s*(?:abort|error|network_error)\b/i,/\breason:\s*(?:abort|error|network_error)\b/i,/\bunhandled stop reason:\s*(?:abort|error|network_error)\b/i],billing:[/["']?(?:status|code)["']?\s*[:=]\s*402\b|\bhttp\s*402\b|\berror(?:\s+code)?\s*[:=]?\s*402\b|\b(?:got|returned|received)\s+(?:a\s+)?402\b|^\s*402\s+payment/i,"payment required","insufficient credits",/insufficient[_ ]quota/i,"credit balance","plans & billing","insufficient balance"],authPermanent:[/api[_ ]?key[_ ]?(?:revoked|invalid|deactivated|deleted)/i,"invalid_api_key","key has been disabled","key has been revoked","account has been deactivated",/could not (?:authenticate|validate).*(?:api[_ ]?key|credentials)/i,"permission_error","not allowed for this organization"],auth:[/invalid[_ ]?api[_ ]?key/,"incorrect api key","invalid token","authentication","re-authenticate","oauth token refresh failed","unauthorized","forbidden","access denied","insufficient permissions","insufficient permission",/missing scopes?:/i,"expired","token has expired",/\b401\b/,/\b403\b/,"no credentials found","no api key found"],format:["string should match pattern","tool_use.id","tool_use_id","messages.1.content.1.tool_use.id","invalid request format",/tool call id was.*must be/i]},ke=/^(?:error[:\s-]+)?billing(?:\s+error)?(?:[:\s-]+|$)|^(?:error[:\s-]+)?(?:credit balance|insufficient credits?|payment required|http\s*402\b)/i,Ae=/["']?(?:status|code)["']?\s*[:=]\s*402\b|\bhttp\s*402\b|\berror(?:\s+code)?\s*[:=]?\s*402\b|^\s*402\s+payment/i,Se=512,Ee=/^(?:http\s*)?(\d{3})(?:\s+([\s\S]+))?$/i;var Me=new Set([500,502,503,504,521,522,523,524,529]),ve=["insufficient credits","insufficient quota","credit balance","insufficient balance","plans & billing","add more credits","top up"],Ie=["upgrade your plan","upgrade plan","current plan","subscription"],we=["daily","weekly","monthly"],Oe=["try again","retry","temporary","cooldown"],Le=["usage limit","rate limit","organization usage"],Pe=["organization","workspace"],Ne=["billing period","exceeded","reached","exhausted"],Fe=/["']?(?:status|code)["']?\s*[:=]\s*402\b|\bhttp\s*402\b|\berror(?:\s+code)?\s*[:=]?\s*402\b|\b(?:got|returned|received)\s+(?:a\s+)?402\b|^\s*402\s+payment required\b/i,De=/^(?:error[:\s-]+)?(?:(?:http\s*)?402(?:\s+payment required)?|payment required)(?:[:\s-]+|$)/i;function T(e,t){if(!e)return!1;let n=e.toLowerCase();return t.some(o=>o instanceof RegExp?o.test(n):n.includes(o))}function Be(e){return T(e,h.format)}function Q(e){return T(e,h.rateLimit)}function Ue(e){return T(e,h.timeout)}function Ge(e){return xe.test(e)}function P(e){let t=e.toLowerCase();return t?e.length>Se?Ae.test(t):T(t,h.billing)?!0:ke.test(e)?t.includes("upgrade")||t.includes("credits")||t.includes("payment")||t.includes("plan"):!1:!1}function ee(e){return T(e,h.authPermanent)}function je(e){return T(e,h.auth)}function te(e){return T(e,h.overloaded)}function y(e,t){return t.some(n=>e.includes(n))}function $e(e){return y(e,ve)||y(e,Ie)&&e.includes("limit")||e.includes("billing hard limit")||e.includes("hard limit reached")||e.includes("maximum allowed")&&e.includes("limit")}function ze(e){let t=y(e,we),n=e.includes("spend limit")||e.includes("spending limit"),o=y(e,Pe);return y(e,Oe)&&y(e,Le)||t&&(e.includes("usage limit")||n)||t&&e.includes("limit")&&e.includes("reset")||o&&e.includes("limit")&&(n||y(e,Ne))}function qe(e){return e.trim().toLowerCase().replace(De,"").trim()}function ne(e){let t=qe(e);return!t||$e(t)?"billing":Q(t)||ze(t)?"rate_limit":"billing"}function He(e){return Fe.test(e)?ne(e):null}function oe(e){let t=e.match(Ee);if(!t)return null;let n=Number(t[1]);return Number.isFinite(n)?{code:n,rest:(t[2]??"").trim()}:null}function Ye(e){if(!e)return!1;let t=e.toLowerCase();return t.includes('"type":"api_error"')&&t.includes("internal server error")}function We(e){let t=e.trim();if(!t)return!1;let n=oe(t);return n?Me.has(n.code):!1}function re(e,t){return typeof e!="number"||!Number.isFinite(e)?null:e===402?t?ne(t):"billing":e===429?"rate_limit":e===401||e===403?t&&ee(t)?"auth_permanent":"auth":e===408?"timeout":e===503?t&&te(t)?"overloaded":"timeout":e===502||e===504?"timeout":e===529?"overloaded":e===400?t&&P(t)?"billing":"format":null}function Xe(e){if(!e)return!1;let t=e.toLowerCase();return!!(t.includes("unknown model")||t.includes("model not found")||t.includes("model_not_found")||t.includes("not_found_error")||t.includes("does not exist")&&t.includes("model")||t.includes("invalid model")&&!t.includes("invalid model reference")||/models\/[^\s]+ is not found/i.test(e)||/\b404\b/.test(e)&&/not[-_ ]?found/i.test(e))}function Ke(e){if(!e)return!1;let t=e.toLowerCase();return t.includes("session not found")||t.includes("session does not exist")||t.includes("session expired")||t.includes("session invalid")||t.includes("conversation not found")||t.includes("conversation does not exist")||t.includes("conversation expired")||t.includes("conversation invalid")||t.includes("no such session")||t.includes("invalid session")||t.includes("session id not found")||t.includes("conversation id not found")}function se(e){if(Ke(e))return"session_expired";if(Xe(e))return"model_not_found";let t=He(e);return t||(Ge(e)?P(e)?"billing":"rate_limit":Q(e)?"rate_limit":te(e)?"overloaded":We(e)?oe(e.trim())?.code===529?"overloaded":"timeout":Ye(e)?"timeout":Be(e)?"format":P(e)?"billing":Ue(e)?"timeout":ee(e)?"auth_permanent":je(e)?"auth":null)}var Ve=new Set(["RETRYABLE_TRANSIENT","RETRYABLE_DEGRADED","TOOL_EXECUTION_FAILED"]);function ie(e){return Ve.has(e)}var Je={timeout:"RETRYABLE_TRANSIENT",overloaded:"RETRYABLE_TRANSIENT",rate_limit:"RETRYABLE_DEGRADED",auth:"NON_RETRYABLE_AUTH",auth_permanent:"NON_RETRYABLE_AUTH",billing:"NON_RETRYABLE_QUOTA",format:"NON_RETRYABLE_CONTENT",model_not_found:"NON_RETRYABLE_CONTENT",session_expired:"NON_RETRYABLE_CONTENT",unknown:"RETRYABLE_TRANSIENT"};function Ze(e,t){let n=re(e,t)??(t?se(t):null);return n?Je[n]:typeof e=="number"&&e>=400&&e<500?"NON_RETRYABLE_CONTENT":"RETRYABLE_TRANSIENT"}function q(e){return typeof e.compressAsync=="function"}var E="[Context capsule v1]";function C(e){return e.replace(/\b(api[_-]?key|access[_-]?token|refresh[_-]?token|password|passwd|secret)\b\s*[:=]\s*["']?[^\s"',;]+/giu,"$1=[REDACTED]").replace(/\b(?:sk|rk|pk)-[A-Za-z0-9_-]{12,}\b/gu,"[REDACTED_TOKEN]").replace(/\bBearer\s+[A-Za-z0-9._~+/=-]{8,}\b/giu,"Bearer [REDACTED]")}function Qe(e){let t=2166136261;for(let n=0;n<e.length;n++)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return(t>>>0).toString(16).padStart(8,"0")}function k(e){if(!(!e||typeof e.content!="string"||!e.content.startsWith(E)))try{let t=JSON.parse(e.content.slice(E.length).trim());return t?.receipt?.version===1&&typeof t.receipt.digest=="string"?t:void 0}catch{return}}function ce(e,t,n,o){let r=e.map(c=>c.itemId).filter(c=>!!c),i={...o?.state.anchors??{}};for(let c of e)for(let u of c.contextAnchors??[]){let p=i[u.category]??[];i[u.category]=[...new Set([...p,C(u.value)])].slice(-50)}let s=[...o?.state.userRequests??[],...e.filter(c=>c.role==="user").map(c=>C(typeof c.content=="string"?c.content:JSON.stringify(c.content??"")))].slice(-50),l={summary:C(t),userRequests:s,anchors:i},a={version:1,sourceMessageCount:(o?.receipt.sourceMessageCount??0)+e.length,sourceItemIds:[...new Set([...o?.receipt.sourceItemIds??[],...r])].slice(-200),firstItemId:o?.receipt.firstItemId??r[0],lastItemId:r.at(-1)??o?.receipt.lastItemId,priorDigest:o?.receipt.digest,tokensBefore:(o?.receipt.tokensBefore??0)+e.reduce((c,u)=>c+n(u),0)};return{receipt:{...a,digest:Qe(JSON.stringify({receipt:a,state:l}))},state:l}}function ue(e){return{role:"system",content:`${E}
2
+ ${JSON.stringify(e)}`}}var ae=4;function le(e){return{role:"system",content:`[${e} earlier messages removed to fit the context budget]`}}var N=class{constructor(t){this.estimateTokens=t}estimateTokens;compress(t,n){let o=[],r=[];for(let p of t)p.role==="system"?o.push(p):r.push(p);let i=n;for(let p of o)i-=this.estimateTokens(p);let s;for(let p of r)if(p.role==="user"){s=p;break}if(s&&(i-=this.estimateTokens(s)),i<=0){let p=r.length-(s?1:0),d=s?[...o,s]:[...o];return p>0&&d.push(le(p)),{messages:d,droppedCount:p,strategy:"sliding-window"}}let l=[],a=0;for(let p=r.length-1;p>=0;p--){let d=r[p];if(d===s)continue;let m=this.estimateTokens(d);if(i-m<0&&a>=ae)break;if(i-m<0&&a<ae){l.unshift(d),a++;continue}i-=m,l.unshift(d),a++}let c=r.length-(l.length+(s&&!l.includes(s)?1:0)),u=[...o];return s&&!l.includes(s)&&u.push(s),c>0&&u.push(le(c)),u.push(...l),{messages:u,droppedCount:c,strategy:"sliding-window"}}},F=class{constructor(t,n){this.recentCount=t;this.summarize=n}recentCount;summarize;compress(t,n){let o=t.filter(a=>a.role==="system"),r=t.filter(a=>a.role!=="system");if(r.length<=this.recentCount)return{messages:t,droppedCount:0,strategy:"summarize-old"};let i=r.slice(0,r.length-this.recentCount),s=r.slice(r.length-this.recentCount),l=this.summarize(i);return{messages:[...o,{role:"system",content:`[Conversation summary]
3
+ ${l}`},...s],droppedCount:i.length,strategy:"summarize-old"}}},D=class{constructor(t=8e3){this.maxToolResultChars=t}maxToolResultChars;compress(t,n){let o=0;return{messages:t.map(i=>i.role!=="tool"||typeof i.content!="string"||i.content.length<=this.maxToolResultChars?i:(o++,{...i,content:et(i.content,this.maxToolResultChars)})),droppedCount:o,strategy:"tool-result-trim"}}};function et(e,t){if(e.length<=t)return e;let n=e.slice(0,t);if(e.trimStart().startsWith("{")||e.trimStart().startsWith("[")){let i=Math.max(n.lastIndexOf("},"),n.lastIndexOf("],"),n.lastIndexOf(`}
4
4
  `),n.lastIndexOf(`]
5
5
  `));if(i>t*.5)return n.slice(0,i+1)+`
6
6
  [...truncated: ${e.length-i-1} chars omitted]`}let r=n.lastIndexOf(`
7
7
  `);return r>t*.7?n.slice(0,r)+`
8
8
  [...truncated: ${e.length-r} chars omitted]`:n+`
9
- [...truncated: ${e.length-t} chars omitted]`}function tt(...e){return{compress(t,n){let o=t,r=0,i=[];for(let s of e){let a=s.compress(o,n);o=a.messages,r+=a.droppedCount,a.droppedCount>0&&i.push(a.strategy)}return{messages:o,droppedCount:r,strategy:i.length>0?i.join("+"):"none"}}}}function nt(...e){return{compress(t,n){let o=t,r=0,i=[];for(let s of e){let a=s.compress(o,n);o=a.messages,r+=a.droppedCount,a.droppedCount>0&&i.push(a.strategy)}return{messages:o,droppedCount:r,strategy:i.length>0?i.join("+"):"none"}},async compressAsync(t,n){let o=t,r=0,i=[],s=0,a=!1,l=!1;for(let c of e){let u=q(c)?await c.compressAsync(o,n):c.compress(o,n);o=u.messages,r+=u.droppedCount,u.droppedCount>0&&i.push(u.strategy),u.metrics&&(s+=u.metrics.latencyMs,a=a||u.metrics.usedLlm,l=l||!!u.metrics.cacheInvalidated)}return{messages:o,droppedCount:r,strategy:i.length>0?i.join("+"):"none",metrics:s>0||a?{tokensBefore:0,tokensAfter:0,compressionRatio:0,latencyMs:s,usedLlm:a,cacheInvalidated:l}:void 0}}}}function H(e,t){let n=e.filter(s=>s.role==="user"),o=e.filter(s=>s.tool_calls!=null),r=e.filter(s=>s.role==="tool"),i=["You are a conversation summarizer. Produce a structured summary of the conversation history below.","","## Instructions","Analyze the conversation and produce a summary with these sections:","","### 1. Primary Objective","What is the user's main goal or task? State it in one sentence.","","### 2. Key Decisions Made","List the important decisions, choices, or conclusions reached during the conversation.","","### 3. Current Progress",`Describe the current state. ${o.length>0?`${o.length} tool calls and ${r.length} tool results were exchanged.`:"No tools were used."}`,"","### 4. Pending Tasks","List any tasks that are in-progress or planned but not yet completed.","","### 5. Important Context","Preserve exact non-secret operational facts: file paths, URLs, port numbers, numeric values, version numbers, proper nouns, identifiers, and user-provided constraints. Never reproduce passwords, API keys, bearer tokens, cookies, or credentials; write [REDACTED] instead.","","### 6. All User Messages",`List ALL ${n.length} user messages chronologically, each as 1-2 sentences capturing the core request. Include exact non-secret values, identifiers, and keywords. Redact every secret even if the user asked to remember it. Do NOT omit any user message \u2014 every user request must be traceable in this summary.`,"","### 7. Error & Recovery History","Summarize any errors encountered and how they were resolved.","","### 8. User Preferences Expressed","Note any stated preferences about style, approach, or constraints.","","### 9. Technical State","Note file paths, variable names, API endpoints, or configuration values that were discussed.","","### 10. Conversation Flow","Briefly describe the overall flow: what happened first, what changed, where we are now."];return t?.taskContext&&i.push("","## Additional Context",t.taskContext),i.push("","## Conversation to Summarize","",...e.map(s=>{let a=C(typeof s.content=="string"?s.content:JSON.stringify(s.content??"")),l=s.role==="user"?a:a.length>2e3?a.slice(0,2e3)+"...":a;return`[${s.role}]: ${l}`}),"","## Output Format","Respond with a concise summary covering all 10 sections above. Use markdown headers.","Keep the total summary under 1000 words. Focus on actionable information and exact user requests."),i.join(`
10
- `)}var B=class{config;constructor(t){this.config={protectedHeadExchanges:t.protectedHeadExchanges,protectedTailMessages:t.protectedTailMessages,summarize:t.summarize,estimateTokens:t.estimateTokens??M,taskContext:t.taskContext}}compress(t,n){return{messages:t,droppedCount:0,strategy:"head-tail-protected"}}async compressAsync(t,n){let o=Date.now(),{system:r,nonSystem:i}=de(t),s=r.findIndex(f=>k(f)!==void 0),a=k(s>=0?r[s]:void 0),l=s>=0?[...r.slice(0,s),...r.slice(s+1)]:r,c=t.reduce((f,L)=>f+this.config.estimateTokens(L),0);if(c<=n)return{messages:t,droppedCount:0,strategy:"head-tail-protected"};let u=0,p=0;for(let f=0;f<i.length&&(i[f].role==="user"&&p++,!(p>this.config.protectedHeadExchanges));f++)u=f+1;let d=Math.max(this.config.protectedTailMessages,Math.floor(i.length*.4)),m=Math.max(u,i.length-d);if(m<=u)return{messages:t,droppedCount:0,strategy:"head-tail-protected"};let b=i.slice(0,u),_=i.slice(u,m),I=i.slice(m),w=H(_,{taskContext:[this.config.taskContext,a?`Prior verified capsule:
11
- ${JSON.stringify(a.state)}`:void 0].filter(Boolean).join(`
9
+ [...truncated: ${e.length-t} chars omitted]`}function tt(...e){return{compress(t,n){let o=t,r=0,i=[];for(let s of e){let l=s.compress(o,n);o=l.messages,r+=l.droppedCount,l.droppedCount>0&&i.push(l.strategy)}return{messages:o,droppedCount:r,strategy:i.length>0?i.join("+"):"none"}}}}function nt(...e){return{compress(t,n){let o=t,r=0,i=[];for(let s of e){let l=s.compress(o,n);o=l.messages,r+=l.droppedCount,l.droppedCount>0&&i.push(l.strategy)}return{messages:o,droppedCount:r,strategy:i.length>0?i.join("+"):"none"}},async compressAsync(t,n){let o=t,r=0,i=[],s=0,l=!1,a=!1;for(let c of e){let u=q(c)?await c.compressAsync(o,n):c.compress(o,n);o=u.messages,r+=u.droppedCount,u.droppedCount>0&&i.push(u.strategy),u.metrics&&(s+=u.metrics.latencyMs,l=l||u.metrics.usedLlm,a=a||!!u.metrics.cacheInvalidated)}return{messages:o,droppedCount:r,strategy:i.length>0?i.join("+"):"none",metrics:s>0||l?{tokensBefore:0,tokensAfter:0,compressionRatio:0,latencyMs:s,usedLlm:l,cacheInvalidated:a}:void 0}}}}function H(e,t){let n=e.filter(s=>s.role==="user"),o=e.filter(s=>s.tool_calls!=null),r=e.filter(s=>s.role==="tool"),i=["You are a conversation summarizer. Produce a structured summary of the conversation history below.","","## Instructions","Analyze the conversation and produce a summary with these sections:","","### 1. Primary Objective","What is the user's main goal or task? State it in one sentence.","","### 2. Key Decisions Made","List the important decisions, choices, or conclusions reached during the conversation.","","### 3. Current Progress",`Describe the current state. ${o.length>0?`${o.length} tool calls and ${r.length} tool results were exchanged.`:"No tools were used."}`,"","### 4. Pending Tasks","List any tasks that are in-progress or planned but not yet completed.","","### 5. Important Context","Preserve exact non-secret operational facts: file paths, URLs, port numbers, numeric values, version numbers, proper nouns, identifiers, and user-provided constraints. Never reproduce passwords, API keys, bearer tokens, cookies, or credentials; write [REDACTED] instead.","","### 6. All User Messages",`List ALL ${n.length} user messages chronologically, each as 1-2 sentences capturing the core request. Include exact non-secret values, identifiers, and keywords. Redact every secret even if the user asked to remember it. Do NOT omit any user message \u2014 every user request must be traceable in this summary.`,"","### 7. Error & Recovery History","Summarize any errors encountered and how they were resolved.","","### 8. User Preferences Expressed","Note any stated preferences about style, approach, or constraints.","","### 9. Technical State","Note file paths, variable names, API endpoints, or configuration values that were discussed.","","### 10. Conversation Flow","Briefly describe the overall flow: what happened first, what changed, where we are now."];return t?.taskContext&&i.push("","## Additional Context",t.taskContext),i.push("","## Conversation to Summarize","",...e.map(s=>{let l=C(typeof s.content=="string"?s.content:JSON.stringify(s.content??"")),a=s.role==="user"?l:l.length>2e3?l.slice(0,2e3)+"...":l;return`[${s.role}]: ${a}`}),"","## Output Format","Respond with a concise summary covering all 10 sections above. Use markdown headers.","Keep the total summary under 1000 words. Focus on actionable information and exact user requests."),i.join(`
10
+ `)}var B=class{config;constructor(t){this.config={protectedHeadExchanges:t.protectedHeadExchanges,protectedTailMessages:t.protectedTailMessages,summarize:t.summarize,estimateTokens:t.estimateTokens??M,taskContext:t.taskContext}}compress(t,n){return{messages:t,droppedCount:0,strategy:"head-tail-protected"}}async compressAsync(t,n){let o=Date.now(),{system:r,nonSystem:i}=de(t),s=r.findIndex(f=>k(f)!==void 0),l=k(s>=0?r[s]:void 0),a=s>=0?[...r.slice(0,s),...r.slice(s+1)]:r,c=t.reduce((f,L)=>f+this.config.estimateTokens(L),0);if(c<=n)return{messages:t,droppedCount:0,strategy:"head-tail-protected"};let u=0,p=0;for(let f=0;f<i.length&&(i[f].role==="user"&&p++,!(p>this.config.protectedHeadExchanges));f++)u=f+1;let d=Math.max(this.config.protectedTailMessages,Math.floor(i.length*.4)),m=Math.max(u,i.length-d);if(m<=u)return{messages:t,droppedCount:0,strategy:"head-tail-protected"};let b=i.slice(0,u),_=i.slice(u,m),I=i.slice(m),w=H(_,{taskContext:[this.config.taskContext,l?`Prior verified capsule:
11
+ ${JSON.stringify(l.state)}`:void 0].filter(Boolean).join(`
12
12
 
13
- `)||void 0}),A=C(await this.config.summarize(_,w)),O=ue(ce(_,A,this.config.estimateTokens,a)),x=[...l,...b,O,...I],g=Date.now()-o,R=x.reduce((f,L)=>f+this.config.estimateTokens(L),0);return{messages:x,droppedCount:_.length,strategy:"head-tail-protected",metrics:{tokensBefore:c,tokensAfter:R,compressionRatio:c>0?R/c:1,latencyMs:g,usedLlm:!0,cacheInvalidated:!0}}}},U=class{config;constructor(t){this.config={preserveRecentCount:t.preserveRecentCount,summarize:t.summarize,estimateTokens:t.estimateTokens??M}}compress(t,n){return{messages:t,droppedCount:0,strategy:"incremental-compact"}}async compressAsync(t,n){let o=Date.now(),{system:r,nonSystem:i}=de(t),s=r.findIndex(g=>k(g)!==void 0),a=s>=0?r[s]:void 0,l=k(a),c=s>=0?[...r.slice(0,s),...r.slice(s+1)]:r,u=Math.max(0,i.length-this.config.preserveRecentCount);if(u<=0)return{messages:t,droppedCount:0,strategy:"incremental-compact"};let p=t.reduce((g,R)=>g+this.config.estimateTokens(R),0);if(p<=n)return{messages:t,droppedCount:0,strategy:"incremental-compact"};let d=i.slice(0,u),m=i.slice(u),b=l?`Prior verified capsule state:
14
- ${JSON.stringify(l.state)}
13
+ `)||void 0}),A=C(await this.config.summarize(_,w)),O=ue(ce(_,A,this.config.estimateTokens,l)),x=[...a,...b,O,...I],g=Date.now()-o,R=x.reduce((f,L)=>f+this.config.estimateTokens(L),0);return{messages:x,droppedCount:_.length,strategy:"head-tail-protected",metrics:{tokensBefore:c,tokensAfter:R,compressionRatio:c>0?R/c:1,latencyMs:g,usedLlm:!0,cacheInvalidated:!0}}}},U=class{config;constructor(t){this.config={preserveRecentCount:t.preserveRecentCount,summarize:t.summarize,estimateTokens:t.estimateTokens??M}}compress(t,n){return{messages:t,droppedCount:0,strategy:"incremental-compact"}}async compressAsync(t,n){let o=Date.now(),{system:r,nonSystem:i}=de(t),s=r.findIndex(g=>k(g)!==void 0),l=s>=0?r[s]:void 0,a=k(l),c=s>=0?[...r.slice(0,s),...r.slice(s+1)]:r,u=Math.max(0,i.length-this.config.preserveRecentCount);if(u<=0)return{messages:t,droppedCount:0,strategy:"incremental-compact"};let p=t.reduce((g,R)=>g+this.config.estimateTokens(R),0);if(p<=n)return{messages:t,droppedCount:0,strategy:"incremental-compact"};let d=i.slice(0,u),m=i.slice(u),b=a?`Prior verified capsule state:
14
+ ${JSON.stringify(a.state)}
15
15
 
16
- Integrate only the new messages below:`:void 0,_=H(d,{taskContext:b}),I=C(await this.config.summarize(d,_)),w=ue(ce(d,I,this.config.estimateTokens,l)),A=[...c,w,...m],O=Date.now()-o,x=A.reduce((g,R)=>g+this.config.estimateTokens(R),0);return{messages:A,droppedCount:d.length,strategy:"incremental-compact",metrics:{tokensBefore:p,tokensAfter:x,compressionRatio:p>0?x/p:1,latencyMs:O,usedLlm:!0,cacheInvalidated:!0}}}},G=class{config;constructor(t){this.config=t}compress(t,n){let o=S(t),r=this.config.inner.compress(t,n),i=S(r.messages),s=o!==i&&r.droppedCount>0;return s&&this.config.onCacheInvalidated?.({droppedCount:r.droppedCount,strategy:r.strategy}),{...r,metrics:{...r.metrics??{tokensBefore:0,tokensAfter:0,compressionRatio:0,latencyMs:0,usedLlm:!1},cacheInvalidated:s}}}async compressAsync(t,n){let o=S(t),r=q(this.config.inner)?await this.config.inner.compressAsync(t,n):this.config.inner.compress(t,n),i=S(r.messages),s=o!==i&&r.droppedCount>0;return s&&this.config.onCacheInvalidated?.({droppedCount:r.droppedCount,strategy:r.strategy}),{...r,metrics:{...r.metrics??{tokensBefore:0,tokensAfter:0,compressionRatio:0,latencyMs:0,usedLlm:!1},cacheInvalidated:s}}}},pe={modelContextWindow:128e3,targetUsageRatio:.75,minBudget:16e3,maxBudget:12e4};function ot(e={}){let t={...pe,...e},n=Math.floor(t.modelContextWindow*t.targetUsageRatio);return Math.max(t.minBudget,Math.min(n,t.maxBudget))}function rt(e,t){let n=e/t;return n<=.8?"none":n<=1?"trim-only":n<=1.5?"sliding-window":"llm-summarize"}var $=class{events=[];maxEvents;constructor(t=100){this.maxEvents=t}record(t){this.events.push(t),this.events.length>this.maxEvents&&this.events.shift()}snapshot(){let t=this.events.length;if(t===0)return{totalCompressions:0,totalLlmCalls:0,totalCacheInvalidations:0,averageCompressionRatio:1,averageLatencyMs:0,totalTokensSaved:0,recentEvents:[]};let n=0,o=0,r=0,i=0,s=0;for(let a of this.events)n+=a.tokensBefore>0?a.tokensAfter/a.tokensBefore:1,o+=a.latencyMs,r+=Math.max(0,a.tokensBefore-a.tokensAfter),a.usedLlm&&i++,a.cacheInvalidated&&s++;return{totalCompressions:t,totalLlmCalls:i,totalCacheInvalidations:s,averageCompressionRatio:n/t,averageLatencyMs:o/t,totalTokensSaved:r,recentEvents:this.events.slice(-10)}}reset(){this.events.length=0}},j=class{engines=new Map;activeId;register(t){this.engines.set(t.id,t)}activate(t){return this.engines.has(t)?(this.activeId=t,!0):!1}getActive(){return this.activeId?this.engines.get(this.activeId):void 0}listEngines(){return Array.from(this.engines.values()).map(t=>({id:t.id,label:t.label,active:t.id===this.activeId}))}};function de(e){let t=[],n=[];for(let o of e)o.role==="system"?t.push(o):n.push(o);return{system:t,nonSystem:n}}function M(e){let t=typeof e.content=="string"?e.content:e.content!=null?JSON.stringify(e.content):"";return Math.ceil(t.length/4)}function S(e){let t=Math.min(e.length,5),n=[];for(let o=0;o<t;o++){let r=e[o],i=typeof r.content=="string"?r.content.slice(0,200):"";n.push(`${r.role}:${i}`)}return n.join("|")}var st=new Set(["file_read","read","Read","bash","shell","Bash","grep","search","Grep","grep_search","glob","Glob","file_search","web_search","WebSearch","web_fetch","WebFetch","file_edit","edit","Edit","file_write","write","Write"]),z=class{constructor(t=20,n=M){this.preserveRecentCount=t;this.estimateTokens=n}preserveRecentCount;estimateTokens;compress(t,n){if(t.length<=this.preserveRecentCount)return{messages:t,droppedCount:0,strategy:"micro-compact"};let o=new Map;for(let l of t){let c=l.tool_calls;if(Array.isArray(c))for(let u of c)u?.id&&u.function?.name&&o.set(u.id,u.function.name)}let r=t.length-this.preserveRecentCount,i=0,s=0;return{messages:t.map((l,c)=>{if(c>=r||l.role!=="tool"||typeof l.content!="string")return l;let u=l.name??o.get(l.tool_call_id??"");if(!u||!st.has(u)||l.content.length<=200)return l;let p=this.estimateTokens(l);return s+=p,i++,{...l,content:`[result cleared \u2014 ${l.content.length} chars]`}}),droppedCount:i,strategy:"micro-compact",metrics:i>0?{tokensBefore:0,tokensAfter:0,compressionRatio:0,latencyMs:0,usedLlm:!1,cacheInvalidated:!1}:void 0}}};function it(e){let t=new Map;for(let n=0;n<e.length;n++){let o=e[n];if(o.tool_calls&&Array.isArray(o.tool_calls))for(let r of o.tool_calls){let i=r.function?.name??"";if(/read|edit|write|file/i.test(i)&&r.function?.arguments)try{let s=JSON.parse(r.function.arguments),a=s.path??s.filePath??s.file_path??s.file;a&&typeof a=="string"&&t.set(a,n)}catch{}}o.role==="tool"&&o.name&&/read|edit|write|file/i.test(o.name)}return[...t.entries()].sort((n,o)=>o[1]-n[1]).map(([n])=>n)}async function at(e,t,n){let o=n.estimateTokens??(d=>Math.ceil(d.length/4)),r=it(t);if(r.length===0)return e;let i=e.map(d=>typeof d.content=="string"?d.content:"").join(`
17
- `),s=r.filter(d=>!i.includes(d));if(s.length===0)return e;let a=n.maxTokenBudget,l=[],c=0;for(let d of s){if(c>=n.maxFiles||a<=0)break;let m=await n.readFile(d);if(!m)continue;let b=o(m);b>a||(a-=b,c++,l.push({role:"system",content:`[Post-compact file recovery: ${d}]
16
+ Integrate only the new messages below:`:void 0,_=H(d,{taskContext:b}),I=C(await this.config.summarize(d,_)),w=ue(ce(d,I,this.config.estimateTokens,a)),A=[...c,w,...m],O=Date.now()-o,x=A.reduce((g,R)=>g+this.config.estimateTokens(R),0);return{messages:A,droppedCount:d.length,strategy:"incremental-compact",metrics:{tokensBefore:p,tokensAfter:x,compressionRatio:p>0?x/p:1,latencyMs:O,usedLlm:!0,cacheInvalidated:!0}}}},G=class{config;constructor(t){this.config=t}compress(t,n){let o=S(t),r=this.config.inner.compress(t,n),i=S(r.messages),s=o!==i&&r.droppedCount>0;return s&&this.config.onCacheInvalidated?.({droppedCount:r.droppedCount,strategy:r.strategy}),{...r,metrics:{...r.metrics??{tokensBefore:0,tokensAfter:0,compressionRatio:0,latencyMs:0,usedLlm:!1},cacheInvalidated:s}}}async compressAsync(t,n){let o=S(t),r=q(this.config.inner)?await this.config.inner.compressAsync(t,n):this.config.inner.compress(t,n),i=S(r.messages),s=o!==i&&r.droppedCount>0;return s&&this.config.onCacheInvalidated?.({droppedCount:r.droppedCount,strategy:r.strategy}),{...r,metrics:{...r.metrics??{tokensBefore:0,tokensAfter:0,compressionRatio:0,latencyMs:0,usedLlm:!1},cacheInvalidated:s}}}},pe={modelContextWindow:128e3,targetUsageRatio:.75,minBudget:16e3,maxBudget:12e4};function ot(e={}){let t={...pe,...e},n=Math.floor(t.modelContextWindow*t.targetUsageRatio);return Math.max(t.minBudget,Math.min(n,t.maxBudget))}function rt(e,t){let n=e/t;return n<=.8?"none":n<=1?"trim-only":n<=1.5?"sliding-window":"llm-summarize"}var j=class{events=[];maxEvents;constructor(t=100){this.maxEvents=t}record(t){this.events.push(t),this.events.length>this.maxEvents&&this.events.shift()}snapshot(){let t=this.events.length;if(t===0)return{totalCompressions:0,totalLlmCalls:0,totalCacheInvalidations:0,averageCompressionRatio:1,averageLatencyMs:0,totalTokensSaved:0,recentEvents:[]};let n=0,o=0,r=0,i=0,s=0;for(let l of this.events)n+=l.tokensBefore>0?l.tokensAfter/l.tokensBefore:1,o+=l.latencyMs,r+=Math.max(0,l.tokensBefore-l.tokensAfter),l.usedLlm&&i++,l.cacheInvalidated&&s++;return{totalCompressions:t,totalLlmCalls:i,totalCacheInvalidations:s,averageCompressionRatio:n/t,averageLatencyMs:o/t,totalTokensSaved:r,recentEvents:this.events.slice(-10)}}reset(){this.events.length=0}},$=class{engines=new Map;activeId;register(t){this.engines.set(t.id,t)}activate(t){return this.engines.has(t)?(this.activeId=t,!0):!1}getActive(){return this.activeId?this.engines.get(this.activeId):void 0}listEngines(){return Array.from(this.engines.values()).map(t=>({id:t.id,label:t.label,active:t.id===this.activeId}))}};function de(e){let t=[],n=[];for(let o of e)o.role==="system"?t.push(o):n.push(o);return{system:t,nonSystem:n}}function M(e){let t=typeof e.content=="string"?e.content:e.content!=null?JSON.stringify(e.content):"";return Math.ceil(t.length/4)}function S(e){let t=Math.min(e.length,5),n=[];for(let o=0;o<t;o++){let r=e[o],i=typeof r.content=="string"?r.content.slice(0,200):"";n.push(`${r.role}:${i}`)}return n.join("|")}var st=new Set(["file_read","read","Read","bash","shell","Bash","grep","search","Grep","grep_search","glob","Glob","file_search","web_search","WebSearch","web_fetch","WebFetch","file_edit","edit","Edit","file_write","write","Write"]);function it(e){let t=e;for(let n=0;n<3;n+=1){if(!t||typeof t!="object"||Array.isArray(t))return;let o=t,r=o.outcome??o.status;if(r==="committed"||r==="not-applied"||r==="indeterminate")return r;t=o.structuredContent}}var z=class{constructor(t=20,n=M){this.preserveRecentCount=t;this.estimateTokens=n}preserveRecentCount;estimateTokens;compress(t,n){if(t.length<=this.preserveRecentCount)return{messages:t,droppedCount:0,strategy:"micro-compact"};let o=new Map;for(let a of t){let c=a.tool_calls;if(Array.isArray(c))for(let u of c)u?.id&&u.function?.name&&o.set(u.id,u.function.name)}let r=t.length-this.preserveRecentCount,i=0,s=0;return{messages:t.map((a,c)=>{if(c>=r||a.role!=="tool"||typeof a.content!="string")return a;let u=a.name??o.get(a.tool_call_id??""),p=it(a.structuredContent);if(!p&&(!u||!st.has(u)))return a;let d=a.structuredContent?JSON.stringify(a.structuredContent).length:0;if(a.content.length<=200&&d<=200)return a;let m=this.estimateTokens(a);return s+=m,i++,{...a,content:`[result cleared \u2014 ${a.content.length+d} chars]`,...p?{structuredContent:{status:p,outcome:p}}:{}}}),droppedCount:i,strategy:"micro-compact",metrics:i>0?{tokensBefore:0,tokensAfter:0,compressionRatio:0,latencyMs:0,usedLlm:!1,cacheInvalidated:!1}:void 0}}};function at(e){let t=new Map;for(let n=0;n<e.length;n++){let o=e[n];if(o.tool_calls&&Array.isArray(o.tool_calls))for(let r of o.tool_calls){let i=r.function?.name??"";if(/read|edit|write|file/i.test(i)&&r.function?.arguments)try{let s=JSON.parse(r.function.arguments),l=s.path??s.filePath??s.file_path??s.file;l&&typeof l=="string"&&t.set(l,n)}catch{}}o.role==="tool"&&o.name&&/read|edit|write|file/i.test(o.name)}return[...t.entries()].sort((n,o)=>o[1]-n[1]).map(([n])=>n)}async function lt(e,t,n){let o=n.estimateTokens??(d=>Math.ceil(d.length/4)),r=at(t);if(r.length===0)return e;let i=e.map(d=>typeof d.content=="string"?d.content:"").join(`
17
+ `),s=r.filter(d=>!i.includes(d));if(s.length===0)return e;let l=n.maxTokenBudget,a=[],c=0;for(let d of s){if(c>=n.maxFiles||l<=0)break;let m=await n.readFile(d);if(!m)continue;let b=o(m);b>l||(l-=b,c++,a.push({role:"system",content:`[Post-compact file recovery: ${d}]
18
18
 
19
- ${m}`}))}if(l.length===0)return e;let u=[...e],p=-1;for(let d=0;d<u.length;d++)u[d].role==="system"&&(p=d);return u.splice(p+1,0,...l),u}function lt(e,t,n=M){if(t.size===0)return{messages:e,tokensFreed:0,removedCount:0};let o=0,r=0,i=[];for(let a of e){let l=a.tool_call_id??"";if(l&&t.has(l)){o+=n(a),r++,t.delete(l);continue}i.push(a)}let s=r>0?{role:"system",content:`[${r} messages removed by snip]`}:void 0;return{messages:i,tokensFreed:o,removedCount:r,boundaryMessage:s}}function ct(){return{stages:[]}}function ut(e,t,n){let o=n?.thresholdMessages??40;if(e.filter(a=>a.role!=="system").length<=o)return{messages:e,stagedCount:0};let i=me(e,t),s=dt(i,t,o);if(s.length===0)return{messages:i,stagedCount:0};for(let a of s)t.stages.push(a);return i=me(e,t),{messages:i,stagedCount:s.length}}function pt(e,t){let n=0;for(let o of t.stages)o.committed||(o.committed=!0,n++);return n===0?{messages:e,committed:0}:{messages:fe(e,t),committed:n}}function me(e,t){return t.stages.filter(o=>o.committed).length===0?e:fe(e,t)}function fe(e,t){let n=t.stages.filter(r=>r.committed).sort((r,i)=>i.range[0]-r.range[0]),o=[...e];for(let r of n){let[i,s]=r.range;if(i>=o.length)continue;let a=Math.min(s,o.length),l={role:"system",content:r.summary};o.splice(i,a-i,l)}return o}function dt(e,t,n){let o=Math.max(0,e.length-Math.floor(n/2)),r=[],i=new Set(t.stages.map(l=>`${l.range[0]}-${l.range[1]}`)),s=-1,a=0;for(let l=0;l<o;l++){let c=e[l];if(c.role==="tool"||c.role==="assistant"&&typeof c.content=="string"&&c.content==="")s<0&&(s=l),a++;else{if(a>=3){let p=`${s}-${s+a}`;i.has(p)||r.push({id:`collapse_${s}_${s+a}`,range:[s,s+a],summary:`[${a} tool results collapsed]`,committed:!1})}s=-1,a=0}}if(a>=3){let l=`${s}-${s+a}`;i.has(l)||r.push({id:`collapse_${s}_${s+a}`,range:[s,s+a],summary:`[${a} tool results collapsed]`,committed:!1})}return r}function mt(e){return[...new Set(e.map(v).filter(Boolean))].sort((t,n)=>t.localeCompare(n))}function ge(e){let t=mt(e);return t.length===0?"":`Available tools for this round: ${t.join(", ")}. Do not invent or attempt any tool outside this list. If the request needs a capability none of these tools cover, do not silently refuse: consider exec-based scripts/OS commands, and otherwise state plainly which capability is missing.`}function ft(e){let t=[...new Set(e.map(v).filter(Boolean))].sort((s,a)=>s.localeCompare(a)),n=new Set(t),o=ge(e),r=n.has("exec"),i=["read","search","write","edit","patch"].some(s=>n.has(s));return!r||!i?"You must call one of the available tools before responding. "+o:"You must call one of the available tools before responding. "+o+' Tool selection is part of correctness. Use read/search/write/edit/patch for file paths and file maintenance. For search, always include `mode` and `pattern`; examples: {"mode":"filename","pattern":"**/*.md"} or {"mode":"content","pattern":"TODO","fileGlob":"*.ts"}. Use exec only for shell commands with the required `command` field; never pass `path`, `filePath`, or file content to exec.'}function v(e){return e.function&&typeof e.function=="object"&&typeof e.function.name=="string"?e.function.name.trim():typeof e.name=="string"?e.name.trim():""}function gt(e){return e==="enabled-eligible"||e==="installed-awaiting-approval"}function yt(e){return new Map((e??[]).map(t=>[t.toolName,t]))}function ht(e){if(!e.eligibility?.length)return[...e.tools];let t=yt(e.eligibility);return e.tools.filter(n=>{let o=v(n);if(!o)return!1;let r=t.get(o);return!r||gt(r.status)})}function Tt(e){let t=[],n=e.compatibility??{},o=e.toolChoice;if(e.thinkingEnabled&&n.requireAutoWhenThinking){let r=typeof o=="object"&&o&&!Array.isArray(o)?String(o.type??""):o;r&&r!=="auto"&&r!=="none"&&(t.push("tool_choice downgraded to auto because thinking mode requires auto/none compatibility."),o="auto")}if(o==="required"&&n.allowRequiredToolChoice===!1){let r=n.requiredFallback??"auto";t.push(`tool_choice=required is not supported by this provider; downgraded to ${r}.`),o=r}if(o&&typeof o=="object"&&!Array.isArray(o)&&o.type==="function"&&n.allowNamedToolChoice===!1){let r=n.namedFallback??"required";t.push(`named tool_choice is not supported by this provider; downgraded to ${r}.`),o=r}return{normalizedToolChoice:o,warnings:t}}function Ct(e){let t=Tt({toolChoice:e.toolChoice,thinkingEnabled:e.thinkingEnabled,compatibility:e.compatibility}),n=t.normalizedToolChoice,o=[...t.warnings],r=ht({tools:e.tools,eligibility:e.eligibility});if(!n||n==="auto")return{tools:r,normalizedToolChoice:n,...r.length>0?{extraSystemPrompt:ge(r)}:{},warnings:o};if(n==="none")return{tools:[],normalizedToolChoice:"none",warnings:o};if(n==="required"){if(r.length===0)throw new Error("tool_choice=required but no tools were provided");return{tools:r,normalizedToolChoice:"required",extraSystemPrompt:ft(r),warnings:o}}if(typeof n=="object"&&!Array.isArray(n)&&n.type==="function"){let i=n.function??void 0,s=typeof i?.name=="string"?i.name.trim():"";if(!s)throw new Error("tool_choice.function.name is required");let a=r.filter(l=>v(l)===s);if(a.length===0)throw new Error(`tool_choice requested unknown tool: ${s}`);return{tools:a,normalizedToolChoice:{type:"function",function:{name:s}},extraSystemPrompt:`You must call the ${s} tool before responding.`,warnings:o}}return{tools:r,normalizedToolChoice:n,warnings:o}}var bt=["stop","aborted","timeout","cancelled","interrupted","error"],_t=["tool_calls","toolCalls","function_call","functionCall","raw_tool_calls","rawToolCalls"];function ye(e){return e==null?[]:typeof e=="string"?e.length>0?[{type:"text",text:e}]:[]:Array.isArray(e)?e:[{type:"text",text:String(e)}]}function Rt(e,t){return{...e,content:[...ye(e.content),...ye(t.content)]}}function xt(e){let t=new Set;if(e.role!=="assistant"||!Array.isArray(e.tool_calls))return t;for(let n of e.tool_calls)typeof n.id=="string"&&n.id&&t.add(n.id);return t}function kt(e){let t=new Set,n=[];for(let o=0;o<e.length;o+=1){if(t.has(o))continue;let r=e[o];if(!r)continue;n.push(r);let i=xt(r);if(i.size!==0)for(let s=o+1;s<e.length;s+=1){if(t.has(s))continue;let a=e[s];a?.role==="tool"&&typeof a.tool_call_id=="string"&&i.has(a.tool_call_id)&&(n.push(a),t.add(s))}}return n}function At(e){if(!e||typeof e!="object")return!1;if(e.function&&typeof e.function=="object"){let t=e.function.name;if(typeof t=="string"&&t.length>0)return!0}return typeof e.name=="string"&&e.name.length>0}function St(e){return new Set((e??bt).map(t=>t.trim().toLowerCase()))}function he(e,t){return e?St(t).has(e.trim().toLowerCase()):!1}function Et(e){let t=e.indexOf("|");return t<=0||t>=e.length-1?{callId:e}:{callId:e.slice(0,t),itemId:e.slice(t+1)}}function Y(e){if(!Array.isArray(e)||e.length===0)return[...e];let t=e.map(l=>{if(l.role==="assistant"&&Array.isArray(l.tool_calls)){let c=l.tool_calls.filter(u=>At(u));return{...l,...c.length>0?{tool_calls:c}:{tool_calls:void 0}}}return{...l}}),n=new Set;for(let l of t)if(!(l.role!=="assistant"||!Array.isArray(l.tool_calls)))for(let c of l.tool_calls)typeof c.id=="string"&&c.id&&n.add(c.id);let o=t.filter(l=>l.role!=="tool"?!0:!!(l.tool_call_id&&n.has(l.tool_call_id))),r=new Set;for(let l of o)l.role==="tool"&&typeof l.tool_call_id=="string"&&l.tool_call_id&&r.add(l.tool_call_id);let i=[];for(let l of o){if(l.role==="assistant"&&Array.isArray(l.tool_calls)&&l.tool_calls.length>0){let c=l.tool_calls.filter(u=>typeof u.id=="string"&&r.has(u.id));if(c.length===0){let{tool_calls:u,...p}=l;p.content!=null&&p.content!==""&&i.push(p);continue}if(c.length<l.tool_calls.length){i.push({...l,tool_calls:c});continue}}i.push(l)}let s=kt(i),a=[];for(let l of s){let c=a.length>0?a[a.length-1]:void 0;if(l.role==="user"&&c?.role==="user"){a[a.length-1]=Rt(c,l);continue}a.push(l)}return a}function W(e,t){return he(t?.stopReason,t?.forcedStopReasons)?e.map(n=>{if(n.role!=="assistant")return{...n};let o={...n};for(let r of _t)delete o[r];return o}):[...e]}function X(e,t){let n=t?.placeholderToolResult??"Error: Tool loop interrupted before the tool result was replayed.",o=new Set;for(let i of e)i.role==="tool"&&typeof i.tool_call_id=="string"&&i.tool_call_id&&o.add(i.tool_call_id);let r=[];for(let i of e)if(r.push({...i}),!(i.role!=="assistant"||!Array.isArray(i.tool_calls)||i.tool_calls.length===0))for(let s of i.tool_calls)typeof s.id!="string"||!s.id||o.has(s.id)||(o.add(s.id),r.push({role:"tool",tool_call_id:s.id,content:n}));return r}function Mt(e,t){let n=Y(e),o=W(n,t);return X(o,t)}function Te(e,t){let n=t?.placeholderFunctionCallOutput??"Error: Tool loop interrupted before function_call_output was provided.",o=he(t?.stopReason,t?.forcedStopReasons),r=[];for(let c=0;c<e.length;c+=1){let u=e[c];if(!u||typeof u!="object"){r.push(u);continue}if(u.type==="reasoning"&&typeof u.id=="string"&&u.id.startsWith("rs_")&&!e.slice(c+1).some(m=>m&&typeof m=="object"&&m.type!=="reasoning"))continue;if(u.type!=="function_call"){r.push({...u});continue}let p={...u};if(typeof p.id=="string"){let d=Et(p.id);d.itemId?.startsWith("fc_")&&(p.id=d.callId)}r.push(p)}let i=new Set,s=new Map;for(let c of r){if(c.type!=="function_call")continue;let u=typeof c.call_id=="string"&&c.call_id?c.call_id:typeof c.id=="string"?c.id:void 0;u&&(i.add(u),s.set(u,c))}let a=new Set,l=[];for(let c of r)if(!(o&&c.type==="function_call")){if(c.type==="function_call_output"){let u=typeof c.call_id=="string"?c.call_id:"";if(!u||!i.has(u))continue;a.add(u)}l.push(c)}for(let[c]of s)a.has(c)||o||l.push({type:"function_call_output",call_id:c,output:n});return l}function vt(e){let t=new Set,n=new Set;for(let o of e){if(o.role==="assistant"&&Array.isArray(o.tool_calls))for(let r of o.tool_calls)typeof r.id=="string"&&r.id&&t.add(r.id);o.role==="tool"&&typeof o.tool_call_id=="string"&&o.tool_call_id&&n.add(o.tool_call_id)}return[...t].filter(o=>!n.has(o))}function It(e){let t=new Set;for(let n of e)n.role==="tool"&&typeof n.tool_call_id=="string"&&n.tool_call_id&&t.add(n.tool_call_id);return[...t]}function wt(e){let t=new Set,n=new Set;for(let o of e){if(o.type==="function_call"){let r=typeof o.call_id=="string"&&o.call_id?o.call_id:typeof o.id=="string"?o.id:"";r&&t.add(r)}o.type==="function_call_output"&&typeof o.call_id=="string"&&o.call_id&&n.add(o.call_id)}return[...t].filter(o=>!n.has(o))}function Ot(e){let t=new Set;for(let n of e)n.type==="function_call_output"&&typeof n.call_id=="string"&&n.call_id&&t.add(n.call_id);return[...t]}function Ce(e){return{round:e.round??0,maxRounds:e.maxRounds,pendingToolCallIds:[...e.pendingToolCallIds??[]],completedToolCallIds:[...e.completedToolCallIds??[]],lastStopReason:e.lastStopReason,replayMessages:[...e.replayMessages??[]]}}function Lt(e,t){return{round:e.round+1,maxRounds:e.maxRounds,pendingToolCallIds:[...t.pendingToolCallIds??e.pendingToolCallIds],completedToolCallIds:[...t.completedToolCallIds??e.completedToolCallIds],lastStopReason:t.lastStopReason??e.lastStopReason,replayMessages:[...t.replayMessages??e.replayMessages]}}function Pt(e,t){return{round:e.round,maxRounds:e.maxRounds,pendingToolCallIds:[],completedToolCallIds:[...t.completedToolCallIds??e.completedToolCallIds],lastStopReason:t.lastStopReason??e.lastStopReason,replayMessages:[...t.replayMessages??e.replayMessages]}}function Nt(e){let t=[],n=Y(e.replayMessages);n.length!==e.replayMessages.length&&t.push({kind:"drop-orphan-tool-result",detail:"Removed orphan tool results or invalid assistant tool calls."});let o=W(n,e.options);o.some((i,s)=>i!==n[s])&&t.push({kind:"strip-forced-stop-tool-metadata",detail:"Removed assistant tool-call metadata after forced stop."});let r=X(o,e.options);return r.length>o.length&&t.push({kind:"inject-placeholder-tool-result",detail:"Injected placeholder tool result for pending tool calls."}),{state:Ce({maxRounds:e.maxRounds,round:e.round,lastStopReason:e.lastStopReason,replayMessages:r,pendingToolCallIds:vt(r),completedToolCallIds:It(r)}),recoveryActions:t}}function Ft(e){let t=Te(e.replayItems,e.options),n=[];return t.length!==e.replayItems.length&&n.push({kind:"drop-trailing-reasoning",detail:"Dropped dangling reasoning blocks or injected missing function_call_output items."}),t.some((o,r)=>o!==e.replayItems[r]&&o.type==="function_call")&&n.push({kind:"rewrite-openai-function-call-pair",detail:"Rewrote OpenAI function_call pairing ids for replay compatibility."}),{state:Ce({maxRounds:e.maxRounds,round:e.round,lastStopReason:e.lastStopReason,replayMessages:t,pendingToolCallIds:wt(t),completedToolCallIds:Ot(t)}),recoveryActions:n}}var Dt=new Set(["main","sdk","agent","compact","hook","verification","side_question"]);function Bt(e){return e?Dt.has(e):!0}function Ut(e){return e===429||e===529}function Gt(e,t=500,n=32e3){let o=Math.min(t*Math.pow(2,e-1),n);return o+Math.floor(Math.random()*o*.25)}var Mn={maxBackoffMs:300*1e3,resetCapMs:360*60*1e3,heartbeatIntervalMs:3e4};function $t(){let e=process.env.QLOGICAGENT_PERSISTENT_RETRY;return e==="1"||e==="true"}var K=class extends Error{constructor(n,o){super(`Model fallback triggered: ${n} -> ${o}`);this.originalModel=n;this.fallbackModel=o;this.name="FallbackTriggeredError"}originalModel;fallbackModel};var In=Math.min(Math.max(1,Number(process.env.TOOL_LOOP_DEFAULT_BUDGET)||25),100),wn=Math.max(1e3,Number(process.env.TOOL_LOOP_TOOL_TIMEOUT_MS)||24e4);var V=4;var On=50*1024,Ln=500*1024,Pn=500*1024*1024,Nn=50*1024*1024;var J="<fork-child-context>",be="Fork started \u2014 processing in background";function jt(e){return JSON.stringify(e).includes(J)}function zt(e){return e<V}function qt(e,t){let n=[...e.parentMessages],o=e.worktreePath?`
19
+ ${m}`}))}if(a.length===0)return e;let u=[...e],p=-1;for(let d=0;d<u.length;d++)u[d].role==="system"&&(p=d);return u.splice(p+1,0,...a),u}function ct(e,t,n=M){if(t.size===0)return{messages:e,tokensFreed:0,removedCount:0};let o=0,r=0,i=[];for(let l of e){let a=l.tool_call_id??"";if(a&&t.has(a)){o+=n(l),r++,t.delete(a);continue}i.push(l)}let s=r>0?{role:"system",content:`[${r} messages removed by snip]`}:void 0;return{messages:i,tokensFreed:o,removedCount:r,boundaryMessage:s}}function ut(){return{stages:[]}}function pt(e,t,n){let o=n?.thresholdMessages??40;if(e.filter(l=>l.role!=="system").length<=o)return{messages:e,stagedCount:0};let i=me(e,t),s=mt(i,t,o);if(s.length===0)return{messages:i,stagedCount:0};for(let l of s)t.stages.push(l);return i=me(e,t),{messages:i,stagedCount:s.length}}function dt(e,t){let n=0;for(let o of t.stages)o.committed||(o.committed=!0,n++);return n===0?{messages:e,committed:0}:{messages:fe(e,t),committed:n}}function me(e,t){return t.stages.filter(o=>o.committed).length===0?e:fe(e,t)}function fe(e,t){let n=t.stages.filter(r=>r.committed).sort((r,i)=>i.range[0]-r.range[0]),o=[...e];for(let r of n){let[i,s]=r.range;if(i>=o.length)continue;let l=Math.min(s,o.length),a={role:"system",content:r.summary};o.splice(i,l-i,a)}return o}function mt(e,t,n){let o=Math.max(0,e.length-Math.floor(n/2)),r=[],i=new Set(t.stages.map(a=>`${a.range[0]}-${a.range[1]}`)),s=-1,l=0;for(let a=0;a<o;a++){let c=e[a];if(c.role==="tool"||c.role==="assistant"&&typeof c.content=="string"&&c.content==="")s<0&&(s=a),l++;else{if(l>=3){let p=`${s}-${s+l}`;i.has(p)||r.push({id:`collapse_${s}_${s+l}`,range:[s,s+l],summary:`[${l} tool results collapsed]`,committed:!1})}s=-1,l=0}}if(l>=3){let a=`${s}-${s+l}`;i.has(a)||r.push({id:`collapse_${s}_${s+l}`,range:[s,s+l],summary:`[${l} tool results collapsed]`,committed:!1})}return r}function ft(e){return[...new Set(e.map(v).filter(Boolean))].sort((t,n)=>t.localeCompare(n))}function ge(e){let t=ft(e);return t.length===0?"":`Available tools for this round: ${t.join(", ")}. Do not invent or attempt any tool outside this list. If the request needs a capability none of these tools cover, do not silently refuse: consider exec-based scripts/OS commands, and otherwise state plainly which capability is missing.`}function gt(e){let t=[...new Set(e.map(v).filter(Boolean))].sort((s,l)=>s.localeCompare(l)),n=new Set(t),o=ge(e),r=n.has("exec"),i=["read","search","write","edit","patch"].some(s=>n.has(s));return!r||!i?"You must call one of the available tools before responding. "+o:"You must call one of the available tools before responding. "+o+' Tool selection is part of correctness. Use read/search/write/edit/patch for file paths and file maintenance. For search, always include `mode` and `pattern`; examples: {"mode":"filename","pattern":"**/*.md"} or {"mode":"content","pattern":"TODO","fileGlob":"*.ts"}. Use exec only for shell commands with the required `command` field; never pass `path`, `filePath`, or file content to exec.'}function v(e){return e.function&&typeof e.function=="object"&&typeof e.function.name=="string"?e.function.name.trim():typeof e.name=="string"?e.name.trim():""}function yt(e){return e==="enabled-eligible"||e==="installed-awaiting-approval"}function ht(e){return new Map((e??[]).map(t=>[t.toolName,t]))}function Tt(e){if(!e.eligibility?.length)return[...e.tools];let t=ht(e.eligibility);return e.tools.filter(n=>{let o=v(n);if(!o)return!1;let r=t.get(o);return!r||yt(r.status)})}function Ct(e){let t=[],n=e.compatibility??{},o=e.toolChoice;if(e.thinkingEnabled&&n.requireAutoWhenThinking){let r=typeof o=="object"&&o&&!Array.isArray(o)?String(o.type??""):o;r&&r!=="auto"&&r!=="none"&&(t.push("tool_choice downgraded to auto because thinking mode requires auto/none compatibility."),o="auto")}if(o==="required"&&n.allowRequiredToolChoice===!1){let r=n.requiredFallback??"auto";t.push(`tool_choice=required is not supported by this provider; downgraded to ${r}.`),o=r}if(o&&typeof o=="object"&&!Array.isArray(o)&&o.type==="function"&&n.allowNamedToolChoice===!1){let r=n.namedFallback??"required";t.push(`named tool_choice is not supported by this provider; downgraded to ${r}.`),o=r}return{normalizedToolChoice:o,warnings:t}}function bt(e){let t=Ct({toolChoice:e.toolChoice,thinkingEnabled:e.thinkingEnabled,compatibility:e.compatibility}),n=t.normalizedToolChoice,o=[...t.warnings],r=Tt({tools:e.tools,eligibility:e.eligibility});if(!n||n==="auto")return{tools:r,normalizedToolChoice:n,...r.length>0?{extraSystemPrompt:ge(r)}:{},warnings:o};if(n==="none")return{tools:[],normalizedToolChoice:"none",warnings:o};if(n==="required"){if(r.length===0)throw new Error("tool_choice=required but no tools were provided");return{tools:r,normalizedToolChoice:"required",extraSystemPrompt:gt(r),warnings:o}}if(typeof n=="object"&&!Array.isArray(n)&&n.type==="function"){let i=n.function??void 0,s=typeof i?.name=="string"?i.name.trim():"";if(!s)throw new Error("tool_choice.function.name is required");let l=r.filter(a=>v(a)===s);if(l.length===0)throw new Error(`tool_choice requested unknown tool: ${s}`);return{tools:l,normalizedToolChoice:{type:"function",function:{name:s}},extraSystemPrompt:`You must call the ${s} tool before responding.`,warnings:o}}return{tools:r,normalizedToolChoice:n,warnings:o}}var _t=["stop","aborted","timeout","cancelled","interrupted","error"],Rt=["tool_calls","toolCalls","function_call","functionCall","raw_tool_calls","rawToolCalls"];function ye(e){return e==null?[]:typeof e=="string"?e.length>0?[{type:"text",text:e}]:[]:Array.isArray(e)?e:[{type:"text",text:String(e)}]}function xt(e,t){return{...e,content:[...ye(e.content),...ye(t.content)]}}function kt(e){let t=new Set;if(e.role!=="assistant"||!Array.isArray(e.tool_calls))return t;for(let n of e.tool_calls)typeof n.id=="string"&&n.id&&t.add(n.id);return t}function At(e){let t=new Set,n=[];for(let o=0;o<e.length;o+=1){if(t.has(o))continue;let r=e[o];if(!r)continue;n.push(r);let i=kt(r);if(i.size!==0)for(let s=o+1;s<e.length;s+=1){if(t.has(s))continue;let l=e[s];l?.role==="tool"&&typeof l.tool_call_id=="string"&&i.has(l.tool_call_id)&&(n.push(l),t.add(s))}}return n}function St(e){if(!e||typeof e!="object")return!1;if(e.function&&typeof e.function=="object"){let t=e.function.name;if(typeof t=="string"&&t.length>0)return!0}return typeof e.name=="string"&&e.name.length>0}function Et(e){return new Set((e??_t).map(t=>t.trim().toLowerCase()))}function he(e,t){return e?Et(t).has(e.trim().toLowerCase()):!1}function Mt(e){let t=e.indexOf("|");return t<=0||t>=e.length-1?{callId:e}:{callId:e.slice(0,t),itemId:e.slice(t+1)}}function Y(e){if(!Array.isArray(e)||e.length===0)return[...e];let t=e.map(a=>{if(a.role==="assistant"&&Array.isArray(a.tool_calls)){let c=a.tool_calls.filter(u=>St(u));return{...a,...c.length>0?{tool_calls:c}:{tool_calls:void 0}}}return{...a}}),n=new Set;for(let a of t)if(!(a.role!=="assistant"||!Array.isArray(a.tool_calls)))for(let c of a.tool_calls)typeof c.id=="string"&&c.id&&n.add(c.id);let o=t.filter(a=>a.role!=="tool"?!0:!!(a.tool_call_id&&n.has(a.tool_call_id))),r=new Set;for(let a of o)a.role==="tool"&&typeof a.tool_call_id=="string"&&a.tool_call_id&&r.add(a.tool_call_id);let i=[];for(let a of o){if(a.role==="assistant"&&Array.isArray(a.tool_calls)&&a.tool_calls.length>0){let c=a.tool_calls.filter(u=>typeof u.id=="string"&&r.has(u.id));if(c.length===0){let{tool_calls:u,...p}=a;p.content!=null&&p.content!==""&&i.push(p);continue}if(c.length<a.tool_calls.length){i.push({...a,tool_calls:c});continue}}i.push(a)}let s=At(i),l=[];for(let a of s){let c=l.length>0?l[l.length-1]:void 0;if(a.role==="user"&&c?.role==="user"){l[l.length-1]=xt(c,a);continue}l.push(a)}return l}function W(e,t){return he(t?.stopReason,t?.forcedStopReasons)?e.map(n=>{if(n.role!=="assistant")return{...n};let o={...n};for(let r of Rt)delete o[r];return o}):[...e]}function X(e,t){let n=t?.placeholderToolResult??"Error: Tool loop interrupted before the tool result was replayed.",o=new Set;for(let i of e)i.role==="tool"&&typeof i.tool_call_id=="string"&&i.tool_call_id&&o.add(i.tool_call_id);let r=[];for(let i of e)if(r.push({...i}),!(i.role!=="assistant"||!Array.isArray(i.tool_calls)||i.tool_calls.length===0))for(let s of i.tool_calls)typeof s.id!="string"||!s.id||o.has(s.id)||(o.add(s.id),r.push({role:"tool",tool_call_id:s.id,content:n}));return r}function vt(e,t){let n=Y(e),o=W(n,t);return X(o,t)}function Te(e,t){let n=t?.placeholderFunctionCallOutput??"Error: Tool loop interrupted before function_call_output was provided.",o=he(t?.stopReason,t?.forcedStopReasons),r=[];for(let c=0;c<e.length;c+=1){let u=e[c];if(!u||typeof u!="object"){r.push(u);continue}if(u.type==="reasoning"&&typeof u.id=="string"&&u.id.startsWith("rs_")&&!e.slice(c+1).some(m=>m&&typeof m=="object"&&m.type!=="reasoning"))continue;if(u.type!=="function_call"){r.push({...u});continue}let p={...u};if(typeof p.id=="string"){let d=Mt(p.id);d.itemId?.startsWith("fc_")&&(p.id=d.callId)}r.push(p)}let i=new Set,s=new Map;for(let c of r){if(c.type!=="function_call")continue;let u=typeof c.call_id=="string"&&c.call_id?c.call_id:typeof c.id=="string"?c.id:void 0;u&&(i.add(u),s.set(u,c))}let l=new Set,a=[];for(let c of r)if(!(o&&c.type==="function_call")){if(c.type==="function_call_output"){let u=typeof c.call_id=="string"?c.call_id:"";if(!u||!i.has(u))continue;l.add(u)}a.push(c)}for(let[c]of s)l.has(c)||o||a.push({type:"function_call_output",call_id:c,output:n});return a}function It(e){let t=new Set,n=new Set;for(let o of e){if(o.role==="assistant"&&Array.isArray(o.tool_calls))for(let r of o.tool_calls)typeof r.id=="string"&&r.id&&t.add(r.id);o.role==="tool"&&typeof o.tool_call_id=="string"&&o.tool_call_id&&n.add(o.tool_call_id)}return[...t].filter(o=>!n.has(o))}function wt(e){let t=new Set;for(let n of e)n.role==="tool"&&typeof n.tool_call_id=="string"&&n.tool_call_id&&t.add(n.tool_call_id);return[...t]}function Ot(e){let t=new Set,n=new Set;for(let o of e){if(o.type==="function_call"){let r=typeof o.call_id=="string"&&o.call_id?o.call_id:typeof o.id=="string"?o.id:"";r&&t.add(r)}o.type==="function_call_output"&&typeof o.call_id=="string"&&o.call_id&&n.add(o.call_id)}return[...t].filter(o=>!n.has(o))}function Lt(e){let t=new Set;for(let n of e)n.type==="function_call_output"&&typeof n.call_id=="string"&&n.call_id&&t.add(n.call_id);return[...t]}function Ce(e){return{round:e.round??0,maxRounds:e.maxRounds,pendingToolCallIds:[...e.pendingToolCallIds??[]],completedToolCallIds:[...e.completedToolCallIds??[]],lastStopReason:e.lastStopReason,replayMessages:[...e.replayMessages??[]]}}function Pt(e,t){return{round:e.round+1,maxRounds:e.maxRounds,pendingToolCallIds:[...t.pendingToolCallIds??e.pendingToolCallIds],completedToolCallIds:[...t.completedToolCallIds??e.completedToolCallIds],lastStopReason:t.lastStopReason??e.lastStopReason,replayMessages:[...t.replayMessages??e.replayMessages]}}function Nt(e,t){return{round:e.round,maxRounds:e.maxRounds,pendingToolCallIds:[],completedToolCallIds:[...t.completedToolCallIds??e.completedToolCallIds],lastStopReason:t.lastStopReason??e.lastStopReason,replayMessages:[...t.replayMessages??e.replayMessages]}}function Ft(e){let t=[],n=Y(e.replayMessages);n.length!==e.replayMessages.length&&t.push({kind:"drop-orphan-tool-result",detail:"Removed orphan tool results or invalid assistant tool calls."});let o=W(n,e.options);o.some((i,s)=>i!==n[s])&&t.push({kind:"strip-forced-stop-tool-metadata",detail:"Removed assistant tool-call metadata after forced stop."});let r=X(o,e.options);return r.length>o.length&&t.push({kind:"inject-placeholder-tool-result",detail:"Injected placeholder tool result for pending tool calls."}),{state:Ce({maxRounds:e.maxRounds,round:e.round,lastStopReason:e.lastStopReason,replayMessages:r,pendingToolCallIds:It(r),completedToolCallIds:wt(r)}),recoveryActions:t}}function Dt(e){let t=Te(e.replayItems,e.options),n=[];return t.length!==e.replayItems.length&&n.push({kind:"drop-trailing-reasoning",detail:"Dropped dangling reasoning blocks or injected missing function_call_output items."}),t.some((o,r)=>o!==e.replayItems[r]&&o.type==="function_call")&&n.push({kind:"rewrite-openai-function-call-pair",detail:"Rewrote OpenAI function_call pairing ids for replay compatibility."}),{state:Ce({maxRounds:e.maxRounds,round:e.round,lastStopReason:e.lastStopReason,replayMessages:t,pendingToolCallIds:Ot(t),completedToolCallIds:Lt(t)}),recoveryActions:n}}var Bt=new Set(["main","sdk","agent","compact","hook","verification","side_question"]);function Ut(e){return e?Bt.has(e):!0}function Gt(e){return e===429||e===529}function jt(e,t=500,n=32e3){let o=Math.min(t*Math.pow(2,e-1),n);return o+Math.floor(Math.random()*o*.25)}var In={maxBackoffMs:300*1e3,resetCapMs:360*60*1e3,heartbeatIntervalMs:3e4};function $t(){let e=process.env.QLOGICAGENT_PERSISTENT_RETRY;return e==="1"||e==="true"}var K=class extends Error{constructor(n,o){super(`Model fallback triggered: ${n} -> ${o}`);this.originalModel=n;this.fallbackModel=o;this.name="FallbackTriggeredError"}originalModel;fallbackModel};var On=Math.min(Math.max(1,Number(process.env.TOOL_LOOP_DEFAULT_BUDGET)||25),100),Ln=Math.max(1e3,Number(process.env.TOOL_LOOP_TOOL_TIMEOUT_MS)||24e4);var V=4;var Pn=50*1024,Nn=500*1024,Fn=500*1024*1024,Dn=50*1024*1024;var J="<fork-child-context>",be="Fork started \u2014 processing in background";function zt(e){return JSON.stringify(e).includes(J)}function qt(e){return e<V}function Ht(e,t){let n=[...e.parentMessages],o=e.worktreePath?`
20
20
 
21
21
  Your working directory is: ${e.worktreePath}
22
22
  All file paths should be relative to this directory.`:"",r={role:"user",content:[{type:"text",text:`${J}
23
23
 
24
24
  You are the "${t.agent.name}" agent.${o}
25
25
 
26
- ${t.taskPrompt}`}]};return n.push(r),n}function Ht(e){return e.map(t=>({role:"tool",tool_call_id:t,content:be}))}function Yt(e,t){if(t.allowedTools&&t.allowedTools.length>0){let n=new Set(t.allowedTools);return e.filter(o=>n.has(o))}if(t.toolCapabilityProfile==="no_tools")return[];if(t.toolCapabilityProfile==="read_tools"){let n=new Set(["file_edit","create_file","write_file","replace_string_in_file","multi_replace_string_in_file","create_directory","delete_file","rename_file","move_file","exec","run_in_terminal","run_command","git_commit","git_push","patch"]);return e.filter(o=>!n.has(o))}return t.canFork?[...e]:e.filter(n=>n!=="agent")}function Wt(e,t,n){let o=Date.now().toString(36);return`${e}:fork:${t}:d${n}:${o}`}var Xt={name:"general",label:"General Purpose",description:"A general-purpose sub-agent that can perform any task with full tool access.",maxTurns:200,toolCapabilityProfile:"all_tools",canFork:!1},Kt={name:"explore",label:"Explore",description:"Fast read-only codebase exploration. Search files, read code, analyze structure. Cannot write or execute.",maxTurns:50,toolCapabilityProfile:"read_tools",allowedTools:["read","search","web_search","web_fetch","memory"],canFork:!1,systemPromptSuffix:"You are READ-ONLY: never attempt to modify files or run mutating commands. Locate and understand code, then report concrete findings with file:line references. Read excerpts rather than whole files; surface conclusions, not raw dumps."},Vt={name:"plan",label:"Plan",description:"Planning mode. Explore, analyze, and produce a structured plan. Cannot write files or execute commands.",maxTurns:80,toolCapabilityProfile:"read_tools",allowedTools:["read","search","web_search","web_fetch","memory","task"],canFork:!1,systemPromptSuffix:"You PLAN but do not execute: never write files or run commands. Investigate enough to ground the plan in the real code, then return a concrete, step-by-step implementation plan naming the specific files and changes involved."},Jt={name:"code",label:"Code",description:"A coding sub-agent with full tool access for implementation tasks.",maxTurns:200,toolCapabilityProfile:"all_tools",canFork:!0,systemPromptSuffix:"Implement the task directly by editing files. Read existing code before changing it, match the surrounding conventions, and verify your change compiles/passes where possible."},Zt={name:"research",label:"Research",description:"Web research and information gathering. Searches the web, fetches pages, and synthesizes findings.",maxTurns:30,toolCapabilityProfile:"read_tools",allowedTools:["web_search","web_fetch","read","search","memory"],canFork:!1,systemPromptSuffix:"Gather information from multiple sources before concluding. Distinguish facts from inferences, cite where each claim comes from, and synthesize \u2014 do not just dump search results."},Qt={name:"verify",label:"Verify",description:"Verification agent. Runs tests, checks build output, validates changes are correct.",maxTurns:40,toolCapabilityProfile:"all_tools",allowedTools:["exec","read","search","task"],canFork:!1,systemPromptSuffix:"Verify by RUNNING things (tests, builds, type-checks) and reading the actual output \u2014 do not assume. Report a clear verdict (pass/fail) with the evidence that supports it."},Z=[Xt,Kt,Vt,Jt,Zt,Qt];function en(){return[...Z]}function tn(e){return Z.find(t=>t.name===e)}function nn(e){return Z.some(t=>t.name===e)}function on(e,t){if(e.allowedTools&&e.allowedTools.length>0){let n=new Set(e.allowedTools);return t.filter(o=>n.has(o))}if(e.toolCapabilityProfile==="no_tools")return[];if(e.toolCapabilityProfile==="read_tools"){let n=new Set(["file_edit","create_file","write_file","replace_string_in_file","multi_replace_string_in_file","create_directory","delete_file","rename_file","move_file","exec","run_in_terminal","run_command","git_commit","git_push","patch"]);return t.filter(o=>!n.has(o))}return e.canFork?[...t]:t.filter(n=>n!=="agent")}function rn(e){return{permissionRole:"worker",isolation:"shared",lifecycle:"pending",depth:0,maxTurns:200,tokenBudget:0,startedAt:Date.now(),...e}}function sn(e){return{promptTokens:0,hasAttemptedReactiveCompact:!1,currentMaxOutputTokens:e.maxOutputTokens,consecutiveTruncations:0,aborted:e.abortSignal?.aborted??!1}}function an(e,t){if(e.aborted)return{level:"blocking",usagePercent:100,reason:"budget_exhausted"};let n=t.contextWindowTokens-t.responseBufferTokens-e.currentMaxOutputTokens,o=n>0?e.promptTokens/n*100:100;return e.promptTokens>=n?e.hasAttemptedReactiveCompact||!t.reactiveCompactEnabled?{level:"blocking",usagePercent:o,reason:"prompt_too_long"}:{level:"blocking",usagePercent:o,reason:"prompt_too_long"}:o>=85?{level:"warning",usagePercent:o,remainingTokens:n-e.promptTokens}:{level:"ok"}}function ln(e,t,n){let o=e.message?.toLowerCase()??"",r=e.status??0;return r===413||o.includes("prompt_too_long")||o.includes("context_length_exceeded")?!t.hasAttemptedReactiveCompact&&n.reactiveCompactEnabled?{action:"reactive_compact"}:{action:"abort",reason:"prompt_too_long_unrecoverable"}:r>=500&&r<600?{action:"retry",reason:`server_error_${r}`}:r===429?{action:"retry",reason:"rate_limited"}:r===401||r===403?{action:"abort",reason:"auth_error"}:r===404?{action:"abort",reason:"model_not_found"}:{action:"abort",reason:o||"unknown_error"}}function cn(e,t,n){if(!t.outputEscalationEnabled)return{shouldEscalate:!1,newMax:e.currentMaxOutputTokens};if(e.consecutiveTruncations>=3)return{shouldEscalate:!1,newMax:e.currentMaxOutputTokens};let o=Math.min(e.currentMaxOutputTokens*2,n);return o<=e.currentMaxOutputTokens?{shouldEscalate:!1,newMax:e.currentMaxOutputTokens}:{shouldEscalate:!0,newMax:o}}function un(e,t){return e.aborted?!0:t.abortSignal?.aborted?(e.aborted=!0,!0):!1}function pn(e){let t=[];if(e.todoList&&e.todoList.length>0){let n=e.todoList.map(o=>` ${o.status==="completed"?"[x]":o.status==="in-progress"?"[~]":"[ ]"} #${o.id}: ${o.title}`);t.push(`## Active Todo List
26
+ ${t.taskPrompt}`}]};return n.push(r),n}function Yt(e){return e.map(t=>({role:"tool",tool_call_id:t,content:be}))}function Wt(e,t){if(t.allowedTools&&t.allowedTools.length>0){let n=new Set(t.allowedTools);return e.filter(o=>n.has(o))}if(t.toolCapabilityProfile==="no_tools")return[];if(t.toolCapabilityProfile==="read_tools"){let n=new Set(["file_edit","create_file","write_file","replace_string_in_file","multi_replace_string_in_file","create_directory","delete_file","rename_file","move_file","exec","run_in_terminal","run_command","git_commit","git_push","patch"]);return e.filter(o=>!n.has(o))}return t.canFork?[...e]:e.filter(n=>n!=="agent")}function Xt(e,t,n){let o=Date.now().toString(36);return`${e}:fork:${t}:d${n}:${o}`}var Kt={name:"general",label:"General Purpose",description:"A general-purpose sub-agent that can perform any task with full tool access.",maxTurns:200,toolCapabilityProfile:"all_tools",canFork:!1},Vt={name:"explore",label:"Explore",description:"Fast read-only codebase exploration. Search files, read code, analyze structure. Cannot write or execute.",maxTurns:50,toolCapabilityProfile:"read_tools",allowedTools:["read","search","web_search","web_fetch","memory"],canFork:!1,systemPromptSuffix:"You are READ-ONLY: never attempt to modify files or run mutating commands. Locate and understand code, then report concrete findings with file:line references. Read excerpts rather than whole files; surface conclusions, not raw dumps."},Jt={name:"plan",label:"Plan",description:"Planning mode. Explore, analyze, and produce a structured plan. Cannot write files or execute commands.",maxTurns:80,toolCapabilityProfile:"read_tools",allowedTools:["read","search","web_search","web_fetch","memory","task"],canFork:!1,systemPromptSuffix:"You PLAN but do not execute: never write files or run commands. Investigate enough to ground the plan in the real code, then return a concrete, step-by-step implementation plan naming the specific files and changes involved."},Zt={name:"code",label:"Code",description:"A coding sub-agent with full tool access for implementation tasks.",maxTurns:200,toolCapabilityProfile:"all_tools",canFork:!0,systemPromptSuffix:"Implement the task directly by editing files. Read existing code before changing it, match the surrounding conventions, and verify your change compiles/passes where possible."},Qt={name:"research",label:"Research",description:"Web research and information gathering. Searches the web, fetches pages, and synthesizes findings.",maxTurns:30,toolCapabilityProfile:"read_tools",allowedTools:["web_search","web_fetch","read","search","memory"],canFork:!1,systemPromptSuffix:"Gather information from multiple sources before concluding. Distinguish facts from inferences, cite where each claim comes from, and synthesize \u2014 do not just dump search results."},en={name:"verify",label:"Verify",description:"Verification agent. Runs tests, checks build output, validates changes are correct.",maxTurns:40,toolCapabilityProfile:"all_tools",allowedTools:["exec","read","search","task"],canFork:!1,systemPromptSuffix:"Verify by RUNNING things (tests, builds, type-checks) and reading the actual output \u2014 do not assume. Report a clear verdict (pass/fail) with the evidence that supports it."},Z=[Kt,Vt,Jt,Zt,Qt,en];function tn(){return[...Z]}function nn(e){return Z.find(t=>t.name===e)}function on(e){return Z.some(t=>t.name===e)}function rn(e,t){if(e.allowedTools&&e.allowedTools.length>0){let n=new Set(e.allowedTools);return t.filter(o=>n.has(o))}if(e.toolCapabilityProfile==="no_tools")return[];if(e.toolCapabilityProfile==="read_tools"){let n=new Set(["file_edit","create_file","write_file","replace_string_in_file","multi_replace_string_in_file","create_directory","delete_file","rename_file","move_file","exec","run_in_terminal","run_command","git_commit","git_push","patch"]);return t.filter(o=>!n.has(o))}return e.canFork?[...t]:t.filter(n=>n!=="agent")}function sn(e){return{permissionRole:"worker",isolation:"shared",lifecycle:"pending",depth:0,maxTurns:200,tokenBudget:0,startedAt:Date.now(),...e}}function an(e){let t=Number.isFinite(e.totalPromptTokens)&&(e.totalPromptTokens??0)>0?Math.floor(e.totalPromptTokens):0,n=Number.isFinite(e.promptTokens)&&e.promptTokens>0?Math.floor(e.promptTokens):0,o=Number.isFinite(e.cacheReadTokens)&&(e.cacheReadTokens??0)>0?Math.floor(e.cacheReadTokens):0,r=Number.isFinite(e.cacheCreationTokens)&&(e.cacheCreationTokens??0)>0?Math.floor(e.cacheCreationTokens):0,i=o+r,s=i>n?n+i:n;return Math.max(t,s)}function ln(e){return{promptTokens:0,hasAttemptedReactiveCompact:!1,currentMaxOutputTokens:e.maxOutputTokens,consecutiveTruncations:0,aborted:e.abortSignal?.aborted??!1}}function cn(e,t){if(e.aborted)return{level:"blocking",usagePercent:100,reason:"budget_exhausted"};let n=t.contextWindowTokens-t.responseBufferTokens-e.currentMaxOutputTokens,o=n>0?e.promptTokens/n*100:100;return e.promptTokens>=n?e.hasAttemptedReactiveCompact||!t.reactiveCompactEnabled?{level:"blocking",usagePercent:o,reason:"prompt_too_long"}:{level:"blocking",usagePercent:o,reason:"prompt_too_long"}:o>=85?{level:"warning",usagePercent:o,remainingTokens:n-e.promptTokens}:{level:"ok"}}function un(e,t,n){let o=e.message?.toLowerCase()??"",r=e.status??0;return r===413||o.includes("prompt_too_long")||o.includes("context_length_exceeded")?!t.hasAttemptedReactiveCompact&&n.reactiveCompactEnabled?{action:"reactive_compact"}:{action:"abort",reason:"prompt_too_long_unrecoverable"}:r>=500&&r<600?{action:"retry",reason:`server_error_${r}`}:r===429?{action:"retry",reason:"rate_limited"}:r===401||r===403?{action:"abort",reason:"auth_error"}:r===404?{action:"abort",reason:"model_not_found"}:{action:"abort",reason:o||"unknown_error"}}function pn(e,t,n){if(!t.outputEscalationEnabled)return{shouldEscalate:!1,newMax:e.currentMaxOutputTokens};if(e.consecutiveTruncations>=3)return{shouldEscalate:!1,newMax:e.currentMaxOutputTokens};let o=Math.min(e.currentMaxOutputTokens*2,n);return o<=e.currentMaxOutputTokens?{shouldEscalate:!1,newMax:e.currentMaxOutputTokens}:{shouldEscalate:!0,newMax:o}}function dn(e,t){return e.aborted?!0:t.abortSignal?.aborted?(e.aborted=!0,!0):!1}function mn(e){let t=[];if(e.todoList&&e.todoList.length>0){let n=e.todoList.map(o=>` ${o.status==="completed"?"[x]":o.status==="in-progress"?"[~]":"[ ]"} #${o.id}: ${o.title}`);t.push(`## Active Todo List
27
27
  ${n.join(`
28
28
  `)}`)}if(e.activeSkillContext&&t.push(`## Active Skill: ${e.activeSkillContext.name}
29
29
  Step ${e.activeSkillContext.step}:
@@ -34,4 +34,4 @@ ${n.content}`);return t.length===0?null:`[Context was compressed. The following
34
34
 
35
35
  ${t.join(`
36
36
 
37
- `)}`}function dn(){return{attemptedThisTurn:!1,lastCompactAt:null,toolsAtLastCompact:[]}}function mn(e){return!e.attemptedThisTurn}export{E as CONTEXT_CAPSULE_MARKER,G as CacheAwareCompressionStrategy,$ as CompressionMetricsCollector,j as ContextEngineRegistry,pe as DEFAULT_ADAPTIVE_BUDGET_CONFIG,be as FORK_PLACEHOLDER_RESULT,J as FORK_SENTINEL_TAG,K as FallbackTriggeredError,B as HeadTailProtectedStrategy,U as IncrementalCompactStrategy,V as MAX_FORK_DEPTH,z as MicroCompactStrategy,N as SlidingWindowStrategy,F as SummarizeOldStrategy,D as ToolResultTrimStrategy,Lt as advanceToolLoopState,ut as applyContextCollapsesIfNeeded,Ct as applyToolChoicePolicy,_e as buildAssistantToolCallMessage,Ht as buildForkPlaceholderResults,qt as buildForkedMessages,pn as buildPostCompactRestorationMessage,H as buildStructuredSummaryPrompt,Re as buildToolResultMessage,an as calculateTokenWarningState,zt as canForkAtDepth,Ze as classifyError,nt as composeAsyncStrategies,tt as composeStrategies,ot as computeAdaptiveBudget,Gt as computeRetryBackoff,ct as createCollapseStore,dn as createReactiveCompactState,rn as createTaskState,sn as createTurnLoopGuardState,Wt as generateForkChildAgentId,tn as getBuiltInAgent,en as getBuiltInAgents,q as isAsyncCompressionStrategy,nn as isBuiltInAgent,Bt as isForegroundSource,jt as isInForkChild,$t as isPersistentRetryEnabled,ie as isRetryableCategory,Ut as isTransientCapacityError,k as parseContextCapsule,at as postCompactFileRecovery,pt as recoverContextCollapseFromOverflow,Nt as recoverToolLoopStateFromChatConversation,Ft as recoverToolLoopStateFromResponsesItems,C as redactCompressionSecrets,Mt as repairOpenAiChatConversation,on as resolveAgentToolSet,ln as resolveApiErrorRecovery,Yt as resolveForkChildTools,cn as resolveOutputTokenEscalation,rt as selectCompressionTier,Pt as settleToolLoopState,un as shouldAbortTurn,mn as shouldAttemptReactiveCompact,lt as snipCompactIfNeeded};
37
+ `)}`}function fn(){return{attemptedThisTurn:!1,lastCompactAt:null,toolsAtLastCompact:[]}}function gn(e){return!e.attemptedThisTurn}export{E as CONTEXT_CAPSULE_MARKER,G as CacheAwareCompressionStrategy,j as CompressionMetricsCollector,$ as ContextEngineRegistry,pe as DEFAULT_ADAPTIVE_BUDGET_CONFIG,be as FORK_PLACEHOLDER_RESULT,J as FORK_SENTINEL_TAG,K as FallbackTriggeredError,B as HeadTailProtectedStrategy,U as IncrementalCompactStrategy,V as MAX_FORK_DEPTH,z as MicroCompactStrategy,N as SlidingWindowStrategy,F as SummarizeOldStrategy,D as ToolResultTrimStrategy,Pt as advanceToolLoopState,pt as applyContextCollapsesIfNeeded,bt as applyToolChoicePolicy,_e as buildAssistantToolCallMessage,Yt as buildForkPlaceholderResults,Ht as buildForkedMessages,mn as buildPostCompactRestorationMessage,H as buildStructuredSummaryPrompt,Re as buildToolResultMessage,cn as calculateTokenWarningState,qt as canForkAtDepth,Ze as classifyError,nt as composeAsyncStrategies,tt as composeStrategies,ot as computeAdaptiveBudget,jt as computeRetryBackoff,ut as createCollapseStore,fn as createReactiveCompactState,sn as createTaskState,ln as createTurnLoopGuardState,Xt as generateForkChildAgentId,nn as getBuiltInAgent,tn as getBuiltInAgents,q as isAsyncCompressionStrategy,on as isBuiltInAgent,Ut as isForegroundSource,zt as isInForkChild,$t as isPersistentRetryEnabled,ie as isRetryableCategory,Gt as isTransientCapacityError,k as parseContextCapsule,lt as postCompactFileRecovery,dt as recoverContextCollapseFromOverflow,Ft as recoverToolLoopStateFromChatConversation,Dt as recoverToolLoopStateFromResponsesItems,C as redactCompressionSecrets,vt as repairOpenAiChatConversation,rn as resolveAgentToolSet,un as resolveApiErrorRecovery,Wt as resolveForkChildTools,pn as resolveOutputTokenEscalation,an as resolvePromptContextTokens,rt as selectCompressionTier,Nt as settleToolLoopState,dn as shouldAbortTurn,gn as shouldAttemptReactiveCompact,ct as snipCompactIfNeeded};
@@ -44,6 +44,19 @@ export interface TurnLoopGuardState {
44
44
  /** Whether the turn has been aborted. */
45
45
  aborted: boolean;
46
46
  }
47
+ export interface PromptContextUsage {
48
+ totalPromptTokens?: number;
49
+ promptTokens: number;
50
+ cacheReadTokens?: number;
51
+ cacheCreationTokens?: number;
52
+ }
53
+ /**
54
+ * Resolve the complete prompt context without double-counting providers whose
55
+ * prompt count already includes cached input. New transports declare the
56
+ * normalized total explicitly. The legacy fallback adds cache only when the
57
+ * cache fields prove the prompt count is an uncached-only value.
58
+ */
59
+ export declare function resolvePromptContextTokens(usage: PromptContextUsage): number;
47
60
  /** Initial guard state. */
48
61
  export declare function createTurnLoopGuardState(config: TurnLoopGuardConfig): TurnLoopGuardState;
49
62
  /**
@@ -10,5 +10,5 @@ export { isForegroundSource, isTransientCapacityError, computeRetryBackoff, isPe
10
10
  export { canForkAtDepth, buildForkedMessages, buildForkPlaceholderResults, FORK_PLACEHOLDER_RESULT, FORK_SENTINEL_TAG, generateForkChildAgentId, isInForkChild, MAX_FORK_DEPTH, resolveForkChildTools, type ForkChildConfig, type ForkChildMessage, type ForkContext, type ForkResult, } from "./subagent/fork-subagent.js";
11
11
  export { getBuiltInAgent, getBuiltInAgents, isBuiltInAgent, resolveAgentToolSet, type AgentDefinition, } from "./subagent/agent-registry.js";
12
12
  export { createTaskState, type IsolationMode, type PermissionRole, type TaskType, type TaskLifecycle, type TaskState, type TaskStateBase, type LocalBashTaskState, type LocalAgentTaskState, type RemoteAgentTaskState, } from "./subagent/task-types.js";
13
- export { calculateTokenWarningState, createTurnLoopGuardState, resolveApiErrorRecovery, resolveOutputTokenEscalation, shouldAbortTurn, type ApiErrorRecovery, type TokenWarningState, type TurnLoopGuardConfig, type TurnLoopGuardState, } from "./context/turn-loop-guard.js";
13
+ export { calculateTokenWarningState, createTurnLoopGuardState, resolvePromptContextTokens, resolveApiErrorRecovery, resolveOutputTokenEscalation, shouldAbortTurn, type ApiErrorRecovery, type TokenWarningState, type TurnLoopGuardConfig, type TurnLoopGuardState, } from "./context/turn-loop-guard.js";
14
14
  export { buildPostCompactRestorationMessage, createReactiveCompactState, shouldAttemptReactiveCompact, type ReactiveCompactConfig, type ReactiveCompactState, } from "./context/reactive-compact.js";
@@ -5,6 +5,7 @@ export interface CompressibleMessage {
5
5
  tool_call_id?: string;
6
6
  tool_calls?: unknown;
7
7
  name?: string;
8
+ structuredContent?: Record<string, unknown>;
8
9
  /** Optional canonical protocol coordinates used by compaction receipts. */
9
10
  threadId?: string;
10
11
  turnId?: string;
@@ -76,6 +76,7 @@ export type LLMChunk = {
76
76
  signature: string;
77
77
  } | {
78
78
  type: "usage";
79
+ totalPromptTokens?: number;
79
80
  promptTokens: number;
80
81
  completionTokens: number;
81
82
  reasoningTokens?: number;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "qlogicagent",
3
- "version": "2.24.4",
3
+ "version": "2.24.6",
4
4
  "packageManager": "pnpm@10.23.0",
5
5
  "description": "XiaozhiClaw standard ACP Agent adapter",
6
6
  "type": "module",
@@ -79,7 +79,7 @@
79
79
  "@agentclientprotocol/sdk": "^0.25.0",
80
80
  "@napi-rs/canvas": "0.1.100",
81
81
  "@xiaozhiclaw/module-sdk": "0.4.4",
82
- "@xiaozhiclaw/provider-core": "0.1.38",
82
+ "@xiaozhiclaw/provider-core": "0.1.39",
83
83
  "ajv": "8.20.0",
84
84
  "better-sqlite3": "^12.10.0",
85
85
  "dotenv": "^17.3.1",