qlogicagent 0.6.0 → 1.0.1
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.
- package/dist/agent.js +10 -10
- package/dist/cli.js +182 -172
- package/dist/index.js +182 -172
- package/dist/orchestration.js +9 -9
- package/dist/types/agent/types.d.ts +58 -0
- package/dist/types/cli/stdio-server.d.ts +60 -0
- package/dist/types/cli/tool-bootstrap.d.ts +5 -13
- package/dist/types/llm/index.d.ts +7 -1
- package/dist/types/llm/media-client.d.ts +43 -0
- package/dist/types/llm/media-transport.d.ts +80 -0
- package/dist/types/llm/model-catalog.d.ts +4 -4
- package/dist/types/llm/provider-def.d.ts +7 -0
- package/dist/types/llm/provider-registry.d.ts +1 -1
- package/dist/types/llm/transport.d.ts +6 -0
- package/dist/types/llm/transports/anthropic-messages.d.ts +34 -11
- package/dist/types/llm/transports/gemini-media.d.ts +21 -0
- package/dist/types/llm/transports/minimax-media.d.ts +21 -0
- package/dist/types/llm/transports/openai-chat.d.ts +1 -1
- package/dist/types/llm/transports/openai-media.d.ts +24 -0
- package/dist/types/llm/transports/qwen-media.d.ts +25 -0
- package/dist/types/llm/transports/volcengine-media.d.ts +34 -0
- package/dist/types/orchestration/error-handling/error-classification.d.ts +1 -10
- package/dist/types/orchestration/index.d.ts +1 -1
- package/dist/types/orchestration/tool-loop/tool-schema.d.ts +4 -2
- package/dist/types/protocol/index.d.ts +7 -0
- package/dist/types/protocol/methods.d.ts +380 -0
- package/dist/types/protocol/notifications.d.ts +296 -0
- package/dist/types/runtime/prompt/environment-context.d.ts +1 -1
- package/dist/types/runtime/session/index.d.ts +1 -1
- package/dist/types/runtime/session/session-state.d.ts +18 -9
- package/dist/types/skills/memory/qmemory-adapter.d.ts +1 -0
- package/dist/types/skills/tools/shell/shell-exec.d.ts +2 -0
- package/package.json +1 -1
package/dist/agent.js
CHANGED
|
@@ -1,18 +1,18 @@
|
|
|
1
|
-
var Ht=Object.defineProperty;var qt=(e,t)=>()=>(e&&(t=e(e=0)),t);var Wt=(e,t)=>{for(var n in t)Ht(e,n,{get:t[n],enumerable:!0})};var Nt={};Wt(Nt,{resolveToolEligibility:()=>Cn});function yn(e,t){if(fn.some(n=>n.test(e)))return!0;if(t)for(let n of t)try{if(new RegExp(n,"i").test(e))return!0}catch{}return!1}function Tn(e,t){let n=e.function.name,o=e.meta,r=[];return t.blockedToolNames?.includes(n)?(r.push("policy_blocked"),{level:5,reasons:r}):o?.isReadOnly?(r.push("always_allowed"),{level:1,reasons:r}):o?.requiresApproval?(r.push("approval_required"),{level:4,reasons:r}):o?.isDangerous||yn(n,t.dangerousPatterns)?(r.push("dangerous_tool"),{level:3,reasons:r}):{level:2,reasons:r}}function hn(e){switch(e){case 1:return"eligible";case 2:return"eligible";case 3:return"dangerous-notify";case 4:return"approval-required";case 5:return"blocked-by-policy"}}function Cn(e,t={}){let n=new Map,o=[],r=[],i=[];for(let l of e){let s=l.function.name,{level:d,reasons:g}=Tn(l,t),p=hn(d),m={toolName:s,status:p,permissionLevel:d,approvalRequired:d===4,reasonCodes:g};n.set(s,m),d===5?r.push(m):(o.push(l),d===4&&i.push(m))}return{eligibleTools:o,blockedTools:r,approvalRequiredTools:i,eligibilityByName:n}}var fn,Ft=qt(()=>{"use strict";fn=[/^(?:bash|shell|exec|terminal|run_command)$/i,/^(?:write_file|delete_file|move_file|create_directory)$/i,/^(?:git_push|git_reset|git_force)$/i]});function fe(e){return{role:"assistant",content:"",tool_calls:e}}function J(e,t){return{role:"tool",tool_call_id:e,content:JSON.stringify(t.ok?{ok:!0,payload:t.payload}:{ok:!1,error:t.error??"Tool invoke failed"})}}var Kt=/\b(?:daily|weekly|monthly)(?:\/(?:daily|weekly|monthly))* (?:usage )?limit(?:s)?(?: (?:exhausted|reached|exceeded))?\b/i,$={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]},Xt=/^(?:error[:\s-]+)?billing(?:\s+error)?(?:[:\s-]+|$)|^(?:error[:\s-]+)?(?:credit balance|insufficient credits?|payment required|http\s*402\b)/i,Yt=/["']?(?:status|code)["']?\s*[:=]\s*402\b|\bhttp\s*402\b|\berror(?:\s+code)?\s*[:=]?\s*402\b|^\s*402\s+payment/i,Jt=512,Vt=/^(?:http\s*)?(\d{3})(?:\s+([\s\S]+))?$/i;var Qt=new Set([500,502,503,504,521,522,523,524,529]),Zt=["insufficient credits","insufficient quota","credit balance","insufficient balance","plans & billing","add more credits","top up"],eo=["upgrade your plan","upgrade plan","current plan","subscription"],to=["daily","weekly","monthly"],oo=["try again","retry","temporary","cooldown"],no=["usage limit","rate limit","organization usage"],ro=["organization","workspace"],so=["billing period","exceeded","reached","exhausted"],io=/["']?(?: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,ao=/^(?:error[:\s-]+)?(?:(?:http\s*)?402(?:\s+payment required)?|payment required)(?:[:\s-]+|$)/i;function U(e,t){if(!e)return!1;let n=e.toLowerCase();return t.some(o=>o instanceof RegExp?o.test(n):n.includes(o))}function lo(e){return U(e,$.format)}function Ve(e){return U(e,$.rateLimit)}function co(e){return U(e,$.timeout)}function uo(e){return Kt.test(e)}function ye(e){let t=e.toLowerCase();return t?e.length>Jt?Yt.test(t):U(t,$.billing)?!0:Xt.test(e)?t.includes("upgrade")||t.includes("credits")||t.includes("payment")||t.includes("plan"):!1:!1}function Qe(e){return U(e,$.authPermanent)}function po(e){return U(e,$.auth)}function Ze(e){return U(e,$.overloaded)}function B(e,t){return t.some(n=>e.includes(n))}function mo(e){return B(e,Zt)||B(e,eo)&&e.includes("limit")||e.includes("billing hard limit")||e.includes("hard limit reached")||e.includes("maximum allowed")&&e.includes("limit")}function go(e){let t=B(e,to),n=e.includes("spend limit")||e.includes("spending limit"),o=B(e,ro);return B(e,oo)&&B(e,no)||t&&(e.includes("usage limit")||n)||t&&e.includes("limit")&&e.includes("reset")||o&&e.includes("limit")&&(n||B(e,so))}function fo(e){return e.trim().toLowerCase().replace(ao,"").trim()}function et(e){let t=fo(e);return!t||mo(t)?"billing":Ve(t)||go(t)?"rate_limit":"billing"}function yo(e){return io.test(e)?et(e):null}function tt(e){let t=e.match(Vt);if(!t)return null;let n=Number(t[1]);return Number.isFinite(n)?{code:n,rest:(t[2]??"").trim()}:null}function To(e){if(!e)return!1;let t=e.toLowerCase();return t.includes('"type":"api_error"')&&t.includes("internal server error")}function ho(e){let t=e.trim();if(!t)return!1;let n=tt(t);return n?Qt.has(n.code):!1}function ot(e,t){return typeof e!="number"||!Number.isFinite(e)?null:e===402?t?et(t):"billing":e===429?"rate_limit":e===401||e===403?t&&Qe(t)?"auth_permanent":"auth":e===408?"timeout":e===503?t&&Ze(t)?"overloaded":"timeout":e===502||e===504?"timeout":e===529?"overloaded":e===400?t&&ye(t)?"billing":"format":null}function Co(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 bo(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 nt(e){if(bo(e))return"session_expired";if(Co(e))return"model_not_found";let t=yo(e);return t||(uo(e)?ye(e)?"billing":"rate_limit":Ve(e)?"rate_limit":Ze(e)?"overloaded":ho(e)?tt(e.trim())?.code===529?"overloaded":"timeout":To(e)?"timeout":lo(e)?"format":ye(e)?"billing":co(e)?"timeout":Qe(e)?"auth_permanent":po(e)?"auth":null)}var ko={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"},_o={RETRYABLE_TRANSIENT:{retryable:!0,maxRetries:3,baseDelayMs:1e3,backoffMultiplier:2,switchProvider:!0},RETRYABLE_DEGRADED:{retryable:!0,maxRetries:2,baseDelayMs:5e3,backoffMultiplier:3,switchProvider:!0},NON_RETRYABLE_AUTH:{retryable:!1,maxRetries:0,baseDelayMs:0,backoffMultiplier:1,switchProvider:!0},NON_RETRYABLE_CONTENT:{retryable:!1,maxRetries:0,baseDelayMs:0,backoffMultiplier:1,switchProvider:!1},NON_RETRYABLE_QUOTA:{retryable:!1,maxRetries:0,baseDelayMs:0,backoffMultiplier:1,switchProvider:!0},TOOL_EXECUTION_FAILED:{retryable:!0,maxRetries:1,baseDelayMs:500,backoffMultiplier:1,switchProvider:!1}};function G(e,t){let n=ot(e,t)??(t?nt(t):null);return n?ko[n]:typeof e=="number"&&e>=400&&e<500?"NON_RETRYABLE_CONTENT":"RETRYABLE_TRANSIENT"}function Te(e){return _o[e]}var rt=4,V=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 l;for(let p of r)if(p.role==="user"){l=p;break}if(l&&(i-=this.estimateTokens(l)),i<=0)return{messages:l?[...o,l]:o,droppedCount:r.length-(l?1:0),strategy:"sliding-window"};let s=[],d=0;for(let p=r.length-1;p>=0;p--){let m=r[p];if(m===l)continue;let k=this.estimateTokens(m);if(i-k<0&&d>=rt)break;if(i-k<0&&d<rt){s.unshift(m),d++;continue}i-=k,s.unshift(m),d++}let g=[...o];return l&&!s.includes(l)&&g.push(l),g.push(...s),{messages:g,droppedCount:r.length-(s.length+(l&&!s.includes(l)?1:0)),strategy:"sliding-window"}}};var Q=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:Ro(i.content,this.maxToolResultChars)})),droppedCount:o,strategy:"tool-result-trim"}}};function Ro(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
|
+
var Wt=Object.defineProperty;var Kt=(e,t)=>()=>(e&&(t=e(e=0)),t);var Xt=(e,t)=>{for(var n in t)Wt(e,n,{get:t[n],enumerable:!0})};var Bt={};Xt(Bt,{resolveToolEligibility:()=>kn});function Tn(e,t){if(hn.some(n=>n.test(e)))return!0;if(t)for(let n of t)try{if(new RegExp(n,"i").test(e))return!0}catch{}return!1}function Cn(e,t){let n=e.function.name,o=e.meta,r=[];return t.blockedToolNames?.includes(n)?(r.push("policy_blocked"),{level:5,reasons:r}):o?.isReadOnly?(r.push("always_allowed"),{level:1,reasons:r}):o?.requiresApproval?(r.push("approval_required"),{level:4,reasons:r}):o?.isDangerous||Tn(n,t.dangerousPatterns)?(r.push("dangerous_tool"),{level:3,reasons:r}):{level:2,reasons:r}}function bn(e){switch(e){case 1:return"eligible";case 2:return"eligible";case 3:return"dangerous-notify";case 4:return"approval-required";case 5:return"blocked-by-policy"}}function kn(e,t={}){let n=new Map,o=[],r=[],a=[];for(let l of e){let s=l.function.name,{level:p,reasons:g}=Cn(l,t),d=bn(p),m={toolName:s,status:d,permissionLevel:p,approvalRequired:p===4,reasonCodes:g};n.set(s,m),p===5?r.push(m):(o.push(l),p===4&&a.push(m))}return{eligibleTools:o,blockedTools:r,approvalRequiredTools:a,eligibilityByName:n}}var hn,Dt=Kt(()=>{"use strict";hn=[/^(?:bash|shell|exec|terminal|run_command)$/i,/^(?:write_file|delete_file|move_file|create_directory)$/i,/^(?:git_push|git_reset|git_force)$/i]});function he(e,t,n){return{role:"assistant",content:t||null,tool_calls:e,...n&&n.length>0?{thinkingBlocks:n}:{}}}function V(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}}var Yt=/\b(?:daily|weekly|monthly)(?:\/(?:daily|weekly|monthly))* (?:usage )?limit(?:s)?(?: (?:exhausted|reached|exceeded))?\b/i,j={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]},Jt=/^(?:error[:\s-]+)?billing(?:\s+error)?(?:[:\s-]+|$)|^(?:error[:\s-]+)?(?:credit balance|insufficient credits?|payment required|http\s*402\b)/i,Vt=/["']?(?:status|code)["']?\s*[:=]\s*402\b|\bhttp\s*402\b|\berror(?:\s+code)?\s*[:=]?\s*402\b|^\s*402\s+payment/i,Qt=512,Zt=/^(?:http\s*)?(\d{3})(?:\s+([\s\S]+))?$/i;var eo=new Set([500,502,503,504,521,522,523,524,529]),to=["insufficient credits","insufficient quota","credit balance","insufficient balance","plans & billing","add more credits","top up"],oo=["upgrade your plan","upgrade plan","current plan","subscription"],no=["daily","weekly","monthly"],ro=["try again","retry","temporary","cooldown"],so=["usage limit","rate limit","organization usage"],io=["organization","workspace"],ao=["billing period","exceeded","reached","exhausted"],lo=/["']?(?: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,co=/^(?:error[:\s-]+)?(?:(?:http\s*)?402(?:\s+payment required)?|payment required)(?:[:\s-]+|$)/i;function z(e,t){if(!e)return!1;let n=e.toLowerCase();return t.some(o=>o instanceof RegExp?o.test(n):n.includes(o))}function uo(e){return z(e,j.format)}function Ze(e){return z(e,j.rateLimit)}function po(e){return z(e,j.timeout)}function mo(e){return Yt.test(e)}function Te(e){let t=e.toLowerCase();return t?e.length>Qt?Vt.test(t):z(t,j.billing)?!0:Jt.test(e)?t.includes("upgrade")||t.includes("credits")||t.includes("payment")||t.includes("plan"):!1:!1}function et(e){return z(e,j.authPermanent)}function go(e){return z(e,j.auth)}function tt(e){return z(e,j.overloaded)}function $(e,t){return t.some(n=>e.includes(n))}function fo(e){return $(e,to)||$(e,oo)&&e.includes("limit")||e.includes("billing hard limit")||e.includes("hard limit reached")||e.includes("maximum allowed")&&e.includes("limit")}function yo(e){let t=$(e,no),n=e.includes("spend limit")||e.includes("spending limit"),o=$(e,io);return $(e,ro)&&$(e,so)||t&&(e.includes("usage limit")||n)||t&&e.includes("limit")&&e.includes("reset")||o&&e.includes("limit")&&(n||$(e,ao))}function ho(e){return e.trim().toLowerCase().replace(co,"").trim()}function ot(e){let t=ho(e);return!t||fo(t)?"billing":Ze(t)||yo(t)?"rate_limit":"billing"}function To(e){return lo.test(e)?ot(e):null}function nt(e){let t=e.match(Zt);if(!t)return null;let n=Number(t[1]);return Number.isFinite(n)?{code:n,rest:(t[2]??"").trim()}:null}function Co(e){if(!e)return!1;let t=e.toLowerCase();return t.includes('"type":"api_error"')&&t.includes("internal server error")}function bo(e){let t=e.trim();if(!t)return!1;let n=nt(t);return n?eo.has(n.code):!1}function rt(e,t){return typeof e!="number"||!Number.isFinite(e)?null:e===402?t?ot(t):"billing":e===429?"rate_limit":e===401||e===403?t&&et(t)?"auth_permanent":"auth":e===408?"timeout":e===503?t&&tt(t)?"overloaded":"timeout":e===502||e===504?"timeout":e===529?"overloaded":e===400?t&&Te(t)?"billing":"format":null}function ko(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 _o(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 st(e){if(_o(e))return"session_expired";if(ko(e))return"model_not_found";let t=To(e);return t||(mo(e)?Te(e)?"billing":"rate_limit":Ze(e)?"rate_limit":tt(e)?"overloaded":bo(e)?nt(e.trim())?.code===529?"overloaded":"timeout":Co(e)?"timeout":uo(e)?"format":Te(e)?"billing":po(e)?"timeout":et(e)?"auth_permanent":go(e)?"auth":null)}var Ro={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"},xo=new Set(["RETRYABLE_TRANSIENT","RETRYABLE_DEGRADED","TOOL_EXECUTION_FAILED"]);function q(e,t){let n=rt(e,t)??(t?st(t):null);return n?Ro[n]:typeof e=="number"&&e>=400&&e<500?"NON_RETRYABLE_CONTENT":"RETRYABLE_TRANSIENT"}function Ce(e){return xo.has(e)}var it=4,Q=class{constructor(t){this.estimateTokens=t}estimateTokens;compress(t,n){let o=[],r=[];for(let d of t)d.role==="system"?o.push(d):r.push(d);let a=n;for(let d of o)a-=this.estimateTokens(d);let l;for(let d of r)if(d.role==="user"){l=d;break}if(l&&(a-=this.estimateTokens(l)),a<=0)return{messages:l?[...o,l]:o,droppedCount:r.length-(l?1:0),strategy:"sliding-window"};let s=[],p=0;for(let d=r.length-1;d>=0;d--){let m=r[d];if(m===l)continue;let _=this.estimateTokens(m);if(a-_<0&&p>=it)break;if(a-_<0&&p<it){s.unshift(m),p++;continue}a-=_,s.unshift(m),p++}let g=[...o];return l&&!s.includes(l)&&g.push(l),g.push(...s),{messages:g,droppedCount:r.length-(s.length+(l&&!s.includes(l)?1:0)),strategy:"sliding-window"}}};var Z=class{constructor(t=8e3){this.maxToolResultChars=t}maxToolResultChars;compress(t,n){let o=0;return{messages:t.map(a=>a.role!=="tool"||typeof a.content!="string"||a.content.length<=this.maxToolResultChars?a:(o++,{...a,content:vo(a.content,this.maxToolResultChars)})),droppedCount:o,strategy:"tool-result-trim"}}};function vo(e,t){if(e.length<=t)return e;let n=e.slice(0,t);if(e.trimStart().startsWith("{")||e.trimStart().startsWith("[")){let a=Math.max(n.lastIndexOf("},"),n.lastIndexOf("],"),n.lastIndexOf(`}
|
|
2
2
|
`),n.lastIndexOf(`]
|
|
3
|
-
`));if(
|
|
4
|
-
[...truncated: ${e.length-
|
|
3
|
+
`));if(a>t*.5)return n.slice(0,a+1)+`
|
|
4
|
+
[...truncated: ${e.length-a-1} chars omitted]`}let r=n.lastIndexOf(`
|
|
5
5
|
`);return r>t*.7?n.slice(0,r)+`
|
|
6
6
|
[...truncated: ${e.length-r} chars omitted]`:n+`
|
|
7
|
-
[...truncated: ${e.length-t} chars omitted]`}function he(...e){return{compress(t,n){let o=t,r=0,i=[];for(let l of e){let s=l.compress(o,n);o=s.messages,r+=s.droppedCount,s.droppedCount>0&&i.push(s.strategy)}return{messages:o,droppedCount:r,strategy:i.length>0?i.join("+"):"none"}}}}var st={modelContextWindow:128e3,targetUsageRatio:.75,minBudget:16e3,maxBudget:12e4};function Ce(e={}){let t={...st,...e},n=Math.floor(t.modelContextWindow*t.targetUsageRatio);return Math.max(t.minBudget,Math.min(n,t.maxBudget))}function be(e,t){let n=e/t;return n<=.8?"none":n<=1?"trim-only":n<=1.5?"sliding-window":"llm-summarize"}var Z=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,l=0;for(let s of this.events)n+=s.tokensBefore>0?s.tokensAfter/s.tokensBefore:1,o+=s.latencyMs,r+=Math.max(0,s.tokensBefore-s.tokensAfter),s.usedLlm&&i++,s.cacheInvalidated&&l++;return{totalCompressions:t,totalLlmCalls:i,totalCacheInvalidations:l,averageCompressionRatio:n/t,averageLatencyMs:o/t,totalTokensSaved:r,recentEvents:this.events.slice(-10)}}reset(){this.events.length=0}},ee=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 it(e){let t=typeof e.content=="string"?e.content:e.content!=null?JSON.stringify(e.content):"";return Math.ceil(t.length/4)}var xo=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"]),j=class{constructor(t=20,n=it){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=t.length-this.preserveRecentCount,r=0,i=0;return{messages:t.map((s,d)=>{if(d>=o||s.role!=="tool"||typeof s.content!="string"||!s.name||!xo.has(s.name)||s.content.length<=200)return s;let g=this.estimateTokens(s);return i+=g,r++,{...s,content:`[result cleared \u2014 ${s.content.length} chars]`}}),droppedCount:r,strategy:"micro-compact",metrics:r>0?{tokensBefore:0,tokensAfter:0,compressionRatio:0,latencyMs:0,usedLlm:!1,cacheInvalidated:!1}:void 0}}};function ke(e,t,n=it){if(t.size===0)return{messages:e,tokensFreed:0,removedCount:0};let o=0,r=0,i=[];for(let s of e){let d=s.tool_call_id??"";if(d&&t.has(d)){o+=n(s),r++,t.delete(d);continue}i.push(s)}let l=r>0?{role:"system",content:`[${r} messages removed by snip]`}:void 0;return{messages:i,tokensFreed:o,removedCount:r,boundaryMessage:l}}function _e(){return{stages:[]}}function Re(e,t,n){let o=n?.thresholdMessages??40;if(e.filter(s=>s.role!=="system").length<=o)return{messages:e,stagedCount:0};let i=at(e,t),l=So(i,t,o);if(l.length===0)return{messages:i,stagedCount:0};for(let s of l)t.stages.push(s);return i=at(e,t),{messages:i,stagedCount:l.length}}function xe(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:lt(e,t),committed:n}}function at(e,t){return t.stages.filter(o=>o.committed).length===0?e:lt(e,t)}function lt(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,l]=r.range;if(i>=o.length)continue;let s=Math.min(l,o.length),d={role:"system",content:r.summary};o.splice(i,s-i,d)}return o}function So(e,t,n){let o=Math.max(0,e.length-Math.floor(n/2)),r=[],i=new Set(t.stages.map(d=>`${d.range[0]}-${d.range[1]}`)),l=-1,s=0;for(let d=0;d<o;d++){let g=e[d];if(g.role==="tool"||g.role==="assistant"&&typeof g.content=="string"&&g.content==="")l<0&&(l=d),s++;else{if(s>=3){let m=`${l}-${l+s}`;i.has(m)||r.push({id:`collapse_${l}_${l+s}`,range:[l,l+s],summary:`[${s} tool results collapsed]`,committed:!1})}l=-1,s=0}}if(s>=3){let d=`${l}-${l+s}`;i.has(d)||r.push({id:`collapse_${l}_${l+s}`,range:[l,l+s],summary:`[${s} tool results collapsed]`,committed:!1})}return r}function vo(e){return!(!e.ok||e.existingSkillName||!e.multiStep||e.toolCallCount<3||e.distinctToolCount<2)}function Ao(e){return e.existingSkillName?e.feedback==="negative":!1}function le(e,t){return Ao(e)?{type:"skill.improve",skillName:e.existingSkillName,reason:"negative user feedback on existing skill execution"}:vo(e)?{type:"skill.create",suggestedName:t.suggestedName??`auto-skill-${t.tools.slice(0,3).join("-")}`,description:`Multi-step orchestration using ${t.tools.join(", ")}`,tools:t.tools,stepCount:e.toolCallCount}:null}function ct(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 Eo(e){return e==="enabled-eligible"||e==="installed-awaiting-approval"}function Mo(e){return new Map((e??[]).map(t=>[t.toolName,t]))}function wo(e){if(!e.eligibility?.length)return[...e.tools];let t=Mo(e.eligibility);return e.tools.filter(n=>{let o=ct(n);if(!o)return!1;let r=t.get(o);return!r||Eo(r.status)})}function Io(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 Se(e){let t=Io({toolChoice:e.toolChoice,thinkingEnabled:e.thinkingEnabled,compatibility:e.compatibility}),n=t.normalizedToolChoice,o=[...t.warnings],r=wo({tools:e.tools,eligibility:e.eligibility});if(!n||n==="auto")return{tools:r,normalizedToolChoice:n,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:"You must call one of the available tools before responding.",warnings:o}}if(typeof n=="object"&&!Array.isArray(n)&&n.type==="function"){let i=n.function??void 0,l=typeof i?.name=="string"?i.name.trim():"";if(!l)throw new Error("tool_choice.function.name is required");let s=r.filter(d=>ct(d)===l);if(s.length===0)throw new Error(`tool_choice requested unknown tool: ${l}`);return{tools:s,normalizedToolChoice:{type:"function",function:{name:l}},extraSystemPrompt:`You must call the ${l} tool before responding.`,warnings:o}}return{tools:r,normalizedToolChoice:n,warnings:o}}var Lo=["stop","aborted","timeout","cancelled","interrupted","error"],Oo=["tool_calls","toolCalls","function_call","functionCall","raw_tool_calls","rawToolCalls"];function ut(e){return e==null?[]:typeof e=="string"?e.length>0?[{type:"text",text:e}]:[]:Array.isArray(e)?e:[{type:"text",text:String(e)}]}function Po(e,t){return{...e,content:[...ut(e.content),...ut(t.content)]}}function No(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 Fo(e){return new Set((e??Lo).map(t=>t.trim().toLowerCase()))}function Do(e,t){return e?Fo(t).has(e.trim().toLowerCase()):!1}function ve(e){if(!Array.isArray(e)||e.length===0)return[...e];let t=e.map(s=>{if(s.role==="assistant"&&Array.isArray(s.tool_calls)){let d=s.tool_calls.filter(g=>No(g));return{...s,...d.length>0?{tool_calls:d}:{tool_calls:void 0}}}return{...s}}),n=new Set;for(let s of t)if(!(s.role!=="assistant"||!Array.isArray(s.tool_calls)))for(let d of s.tool_calls)typeof d.id=="string"&&d.id&&n.add(d.id);let o=t.filter(s=>s.role!=="tool"?!0:!!(s.tool_call_id&&n.has(s.tool_call_id))),r=new Set;for(let s of o)s.role==="tool"&&typeof s.tool_call_id=="string"&&s.tool_call_id&&r.add(s.tool_call_id);let i=[];for(let s of o){if(s.role==="assistant"&&Array.isArray(s.tool_calls)&&s.tool_calls.length>0){let d=s.tool_calls.filter(g=>typeof g.id=="string"&&r.has(g.id));if(d.length===0){let{tool_calls:g,...p}=s;p.content!=null&&p.content!==""&&i.push(p);continue}if(d.length<s.tool_calls.length){i.push({...s,tool_calls:d});continue}}i.push(s)}let l=[];for(let s of i){let d=l.length>0?l[l.length-1]:void 0;if(s.role==="user"&&d?.role==="user"){l[l.length-1]=Po(d,s);continue}l.push(s)}return l}function Ae(e,t){return Do(t?.stopReason,t?.forcedStopReasons)?e.map(n=>{if(n.role!=="assistant")return{...n};let o={...n};for(let r of Oo)delete o[r];return o}):[...e]}function Ee(e,t){let n=t?.placeholderToolResult??JSON.stringify({ok:!1,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 l of i.tool_calls)typeof l.id!="string"||!l.id||o.has(l.id)||(o.add(l.id),r.push({role:"tool",tool_call_id:l.id,content:n}));return r}function Me(e,t){let n=ve(e),o=Ae(n,t);return Ee(o,t)}function Bo(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 $o(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 Uo(e){return{round:e.round??0,maxRounds:e.maxRounds,pendingToolCallIds:[...e.pendingToolCallIds??[]],completedToolCallIds:[...e.completedToolCallIds??[]],lastStopReason:e.lastStopReason,replayMessages:[...e.replayMessages??[]]}}function we(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 ce(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 ue(e){let t=[],n=ve(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=Ae(n,e.options);o.some((i,l)=>i!==n[l])&&t.push({kind:"strip-forced-stop-tool-metadata",detail:"Removed assistant tool-call metadata after forced stop."});let r=Ee(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:Uo({maxRounds:e.maxRounds,round:e.round,lastStopReason:e.lastStopReason,replayMessages:r,pendingToolCallIds:Bo(r),completedToolCallIds:$o(r)}),recoveryActions:t}}var jo=new Set(["main","sdk","agent","compact","hook","verification","side_question"]);function Ie(e){return e?jo.has(e):!0}function Le(e){return e===429||e===529}function de(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 zn={maxBackoffMs:300*1e3,resetCapMs:360*60*1e3,heartbeatIntervalMs:3e4};function Oe(){let e=process.env.QLOGICAGENT_PERSISTENT_RETRY;return e==="1"||e==="true"}var te=class extends Error{constructor(n,o){super(`Model fallback triggered: ${n} -> ${o}`);this.originalModel=n;this.fallbackModel=o;this.name="FallbackTriggeredError"}originalModel;fallbackModel};function Pe(e){return{promptTokens:0,hasAttemptedReactiveCompact:!1,currentMaxOutputTokens:e.maxOutputTokens,consecutiveTruncations:0,aborted:e.abortSignal?.aborted??!1}}function Ne(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 Fe(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"}:{action:"abort",reason:o||"unknown_error"}}function De(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 Be(e,t){return e.aborted?!0:t.abortSignal?.aborted?(e.aborted=!0,!0):!1}var zo={maxConsecutiveFailures:3,minMessagesAfterCompact:4,targetUsagePercent:50};function $e(){return{consecutiveFailures:0,attemptedThisTurn:!1,lastCompactAt:null,toolsAtLastCompact:[]}}function H(e,t=zo){return!(e.attemptedThisTurn||e.consecutiveFailures>=t.maxConsecutiveFailures)}function dt(e,t){let n=e.get(t.index);n||(n={id:"",name:"",arguments:""},e.set(t.index,n)),t.id&&(n.id=t.id),t.name&&(n.name+=t.name),n.arguments+=t.arguments}import{mkdir as Yo,writeFile as Jo}from"fs/promises";import{join as xt}from"path";import{tmpdir as Vo}from"os";var pt=Math.min(Math.max(1,Number(process.env.TOOL_LOOP_DEFAULT_BUDGET)||25),100),mt=3,gt=128e3,ft=13e3,yt=16384,Tt=65536,ht=3,Ct=65536,bt=3e4,kt=3,oe=5,_t=5e4,Rt=2e5,Ue=2e3;var Qo="tool-results",St="<persisted-output>",Zo="</persisted-output>";function vt(){return{seenIds:new Set,replacements:new Map}}function At(e){return xt(Vo(),"qlogicagent-sessions",e,Qo)}async function en(e){try{await Yo(At(e),{recursive:!0})}catch{}}function tn(e,t){let n=t.replace(/[^a-zA-Z0-9_-]/g,"_");return xt(At(e),`${n}.txt`)}function on(e,t){if(e.length<=t)return{preview:e,hasMore:!1};let o=e.slice(0,t).lastIndexOf(`
|
|
8
|
-
`),r=o>t*.5?o:t;return{preview:e.slice(0,r),hasMore:!0}}function
|
|
7
|
+
[...truncated: ${e.length-t} chars omitted]`}function be(...e){return{compress(t,n){let o=t,r=0,a=[];for(let l of e){let s=l.compress(o,n);o=s.messages,r+=s.droppedCount,s.droppedCount>0&&a.push(s.strategy)}return{messages:o,droppedCount:r,strategy:a.length>0?a.join("+"):"none"}}}}var at={modelContextWindow:128e3,targetUsageRatio:.75,minBudget:16e3,maxBudget:12e4};function ke(e={}){let t={...at,...e},n=Math.floor(t.modelContextWindow*t.targetUsageRatio);return Math.max(t.minBudget,Math.min(n,t.maxBudget))}function _e(e,t){let n=e/t;return n<=.8?"none":n<=1?"trim-only":n<=1.5?"sliding-window":"llm-summarize"}var ee=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,a=0,l=0;for(let s of this.events)n+=s.tokensBefore>0?s.tokensAfter/s.tokensBefore:1,o+=s.latencyMs,r+=Math.max(0,s.tokensBefore-s.tokensAfter),s.usedLlm&&a++,s.cacheInvalidated&&l++;return{totalCompressions:t,totalLlmCalls:a,totalCacheInvalidations:l,averageCompressionRatio:n/t,averageLatencyMs:o/t,totalTokensSaved:r,recentEvents:this.events.slice(-10)}}reset(){this.events.length=0}},te=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 lt(e){let t=typeof e.content=="string"?e.content:e.content!=null?JSON.stringify(e.content):"";return Math.ceil(t.length/4)}var So=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"]),G=class{constructor(t=20,n=lt){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=t.length-this.preserveRecentCount,r=0,a=0;return{messages:t.map((s,p)=>{if(p>=o||s.role!=="tool"||typeof s.content!="string"||!s.name||!So.has(s.name)||s.content.length<=200)return s;let g=this.estimateTokens(s);return a+=g,r++,{...s,content:`[result cleared \u2014 ${s.content.length} chars]`}}),droppedCount:r,strategy:"micro-compact",metrics:r>0?{tokensBefore:0,tokensAfter:0,compressionRatio:0,latencyMs:0,usedLlm:!1,cacheInvalidated:!1}:void 0}}};function Re(e,t,n=lt){if(t.size===0)return{messages:e,tokensFreed:0,removedCount:0};let o=0,r=0,a=[];for(let s of e){let p=s.tool_call_id??"";if(p&&t.has(p)){o+=n(s),r++,t.delete(p);continue}a.push(s)}let l=r>0?{role:"system",content:`[${r} messages removed by snip]`}:void 0;return{messages:a,tokensFreed:o,removedCount:r,boundaryMessage:l}}function xe(){return{stages:[]}}function ve(e,t,n){let o=n?.thresholdMessages??40;if(e.filter(s=>s.role!=="system").length<=o)return{messages:e,stagedCount:0};let a=ct(e,t),l=Ao(a,t,o);if(l.length===0)return{messages:a,stagedCount:0};for(let s of l)t.stages.push(s);return a=ct(e,t),{messages:a,stagedCount:l.length}}function Se(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:ut(e,t),committed:n}}function ct(e,t){return t.stages.filter(o=>o.committed).length===0?e:ut(e,t)}function ut(e,t){let n=t.stages.filter(r=>r.committed).sort((r,a)=>a.range[0]-r.range[0]),o=[...e];for(let r of n){let[a,l]=r.range;if(a>=o.length)continue;let s=Math.min(l,o.length),p={role:"system",content:r.summary};o.splice(a,s-a,p)}return o}function Ao(e,t,n){let o=Math.max(0,e.length-Math.floor(n/2)),r=[],a=new Set(t.stages.map(p=>`${p.range[0]}-${p.range[1]}`)),l=-1,s=0;for(let p=0;p<o;p++){let g=e[p];if(g.role==="tool"||g.role==="assistant"&&typeof g.content=="string"&&g.content==="")l<0&&(l=p),s++;else{if(s>=3){let m=`${l}-${l+s}`;a.has(m)||r.push({id:`collapse_${l}_${l+s}`,range:[l,l+s],summary:`[${s} tool results collapsed]`,committed:!1})}l=-1,s=0}}if(s>=3){let p=`${l}-${l+s}`;a.has(p)||r.push({id:`collapse_${l}_${l+s}`,range:[l,l+s],summary:`[${s} tool results collapsed]`,committed:!1})}return r}function Eo(e){return!(!e.ok||e.existingSkillName||!e.multiStep||e.toolCallCount<3||e.distinctToolCount<2)}function Mo(e){return e.existingSkillName?e.feedback==="negative":!1}function ce(e,t){return Mo(e)?{type:"skill.improve",skillName:e.existingSkillName,reason:"negative user feedback on existing skill execution"}:Eo(e)?{type:"skill.create",suggestedName:t.suggestedName??`auto-skill-${t.tools.slice(0,3).join("-")}`,description:`Multi-step orchestration using ${t.tools.join(", ")}`,tools:t.tools,stepCount:e.toolCallCount}:null}function dt(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 wo(e){return e==="enabled-eligible"||e==="installed-awaiting-approval"}function Io(e){return new Map((e??[]).map(t=>[t.toolName,t]))}function Lo(e){if(!e.eligibility?.length)return[...e.tools];let t=Io(e.eligibility);return e.tools.filter(n=>{let o=dt(n);if(!o)return!1;let r=t.get(o);return!r||wo(r.status)})}function Oo(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 Ae(e){let t=Oo({toolChoice:e.toolChoice,thinkingEnabled:e.thinkingEnabled,compatibility:e.compatibility}),n=t.normalizedToolChoice,o=[...t.warnings],r=Lo({tools:e.tools,eligibility:e.eligibility});if(!n||n==="auto")return{tools:r,normalizedToolChoice:n,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:"You must call one of the available tools before responding.",warnings:o}}if(typeof n=="object"&&!Array.isArray(n)&&n.type==="function"){let a=n.function??void 0,l=typeof a?.name=="string"?a.name.trim():"";if(!l)throw new Error("tool_choice.function.name is required");let s=r.filter(p=>dt(p)===l);if(s.length===0)throw new Error(`tool_choice requested unknown tool: ${l}`);return{tools:s,normalizedToolChoice:{type:"function",function:{name:l}},extraSystemPrompt:`You must call the ${l} tool before responding.`,warnings:o}}return{tools:r,normalizedToolChoice:n,warnings:o}}var Po=["stop","aborted","timeout","cancelled","interrupted","error"],No=["tool_calls","toolCalls","function_call","functionCall","raw_tool_calls","rawToolCalls"];function pt(e){return e==null?[]:typeof e=="string"?e.length>0?[{type:"text",text:e}]:[]:Array.isArray(e)?e:[{type:"text",text:String(e)}]}function Fo(e,t){return{...e,content:[...pt(e.content),...pt(t.content)]}}function Bo(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 Do(e){return new Set((e??Po).map(t=>t.trim().toLowerCase()))}function Uo(e,t){return e?Do(t).has(e.trim().toLowerCase()):!1}function Ee(e){if(!Array.isArray(e)||e.length===0)return[...e];let t=e.map(s=>{if(s.role==="assistant"&&Array.isArray(s.tool_calls)){let p=s.tool_calls.filter(g=>Bo(g));return{...s,...p.length>0?{tool_calls:p}:{tool_calls:void 0}}}return{...s}}),n=new Set;for(let s of t)if(!(s.role!=="assistant"||!Array.isArray(s.tool_calls)))for(let p of s.tool_calls)typeof p.id=="string"&&p.id&&n.add(p.id);let o=t.filter(s=>s.role!=="tool"?!0:!!(s.tool_call_id&&n.has(s.tool_call_id))),r=new Set;for(let s of o)s.role==="tool"&&typeof s.tool_call_id=="string"&&s.tool_call_id&&r.add(s.tool_call_id);let a=[];for(let s of o){if(s.role==="assistant"&&Array.isArray(s.tool_calls)&&s.tool_calls.length>0){let p=s.tool_calls.filter(g=>typeof g.id=="string"&&r.has(g.id));if(p.length===0){let{tool_calls:g,...d}=s;d.content!=null&&d.content!==""&&a.push(d);continue}if(p.length<s.tool_calls.length){a.push({...s,tool_calls:p});continue}}a.push(s)}let l=[];for(let s of a){let p=l.length>0?l[l.length-1]:void 0;if(s.role==="user"&&p?.role==="user"){l[l.length-1]=Fo(p,s);continue}l.push(s)}return l}function Me(e,t){return Uo(t?.stopReason,t?.forcedStopReasons)?e.map(n=>{if(n.role!=="assistant")return{...n};let o={...n};for(let r of No)delete o[r];return o}):[...e]}function we(e,t){let n=t?.placeholderToolResult??"Error: Tool loop interrupted before the tool result was replayed.",o=new Set;for(let a of e)a.role==="tool"&&typeof a.tool_call_id=="string"&&a.tool_call_id&&o.add(a.tool_call_id);let r=[];for(let a of e)if(r.push({...a}),!(a.role!=="assistant"||!Array.isArray(a.tool_calls)||a.tool_calls.length===0))for(let l of a.tool_calls)typeof l.id!="string"||!l.id||o.has(l.id)||(o.add(l.id),r.push({role:"tool",tool_call_id:l.id,content:n}));return r}function Ie(e,t){let n=Ee(e),o=Me(n,t);return we(o,t)}function $o(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 jo(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 zo(e){return{round:e.round??0,maxRounds:e.maxRounds,pendingToolCallIds:[...e.pendingToolCallIds??[]],completedToolCallIds:[...e.completedToolCallIds??[]],lastStopReason:e.lastStopReason,replayMessages:[...e.replayMessages??[]]}}function Le(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 ue(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 de(e){let t=[],n=Ee(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=Me(n,e.options);o.some((a,l)=>a!==n[l])&&t.push({kind:"strip-forced-stop-tool-metadata",detail:"Removed assistant tool-call metadata after forced stop."});let r=we(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:zo({maxRounds:e.maxRounds,round:e.round,lastStopReason:e.lastStopReason,replayMessages:r,pendingToolCallIds:$o(r),completedToolCallIds:jo(r)}),recoveryActions:t}}var Go=new Set(["main","sdk","agent","compact","hook","verification","side_question"]);function Oe(e){return e?Go.has(e):!0}function Pe(e){return e===429||e===529}function pe(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 Kn={maxBackoffMs:300*1e3,resetCapMs:360*60*1e3,heartbeatIntervalMs:3e4};function Ne(){let e=process.env.QLOGICAGENT_PERSISTENT_RETRY;return e==="1"||e==="true"}var oe=class extends Error{constructor(n,o){super(`Model fallback triggered: ${n} -> ${o}`);this.originalModel=n;this.fallbackModel=o;this.name="FallbackTriggeredError"}originalModel;fallbackModel};function Fe(e){return{promptTokens:0,hasAttemptedReactiveCompact:!1,currentMaxOutputTokens:e.maxOutputTokens,consecutiveTruncations:0,aborted:e.abortSignal?.aborted??!1}}function Be(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 De(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 Ue(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 $e(e,t){return e.aborted?!0:t.abortSignal?.aborted?(e.aborted=!0,!0):!1}var qo={maxConsecutiveFailures:3,minMessagesAfterCompact:4,targetUsagePercent:50};function je(){return{consecutiveFailures:0,attemptedThisTurn:!1,lastCompactAt:null,toolsAtLastCompact:[]}}function H(e,t=qo){return!(e.attemptedThisTurn||e.consecutiveFailures>=t.maxConsecutiveFailures)}function mt(e,t){let n=e.get(t.index);n||(n={id:"",name:"",arguments:""},e.set(t.index,n)),t.id&&(n.id=t.id),t.name&&(n.name+=t.name),n.arguments+=t.arguments}import{mkdir as Vo,writeFile as Qo}from"fs/promises";import{join as St}from"path";import{tmpdir as Zo}from"os";var gt=Math.min(Math.max(1,Number(process.env.TOOL_LOOP_DEFAULT_BUDGET)||25),100),ft=3,yt=128e3,ht=13e3,Tt=16384,Ct=65536,bt=3,kt=65536,_t=3e4,Rt=3,ne=5,xt=5e4,vt=2e5,ze=2e3;var en="tool-results",At="<persisted-output>",tn="</persisted-output>";function Et(){return{seenIds:new Set,replacements:new Map}}function Mt(e){return St(Zo(),"qlogicagent-sessions",e,en)}async function on(e){try{await Vo(Mt(e),{recursive:!0})}catch{}}function nn(e,t){let n=t.replace(/[^a-zA-Z0-9_-]/g,"_");return St(Mt(e),`${n}.txt`)}function rn(e,t){if(e.length<=t)return{preview:e,hasMore:!1};let o=e.slice(0,t).lastIndexOf(`
|
|
8
|
+
`),r=o>t*.5?o:t;return{preview:e.slice(0,r),hasMore:!0}}function wt(e){return e.includes(At)}async function It(e,t,n){await on(n);let o=nn(n,t);try{await Qo(o,e,{encoding:"utf-8",flag:"wx"})}catch(l){if(l.code!=="EEXIST")return null}let{preview:r,hasMore:a}=rn(e,ze);return{filepath:o,originalSize:e.length,preview:r,hasMore:a}}function Lt(e){let t=`${At}
|
|
9
9
|
`;return t+=`Output too large (${e.originalSize} chars). Full output saved to: ${e.filepath}
|
|
10
10
|
|
|
11
|
-
`,t+=`Preview (first ${
|
|
11
|
+
`,t+=`Preview (first ${ze} bytes):
|
|
12
12
|
`,t+=e.preview,t+=e.hasMore?`
|
|
13
13
|
...
|
|
14
14
|
`:`
|
|
15
|
-
`,t+=
|
|
16
|
-
...[truncated ${e.length-o} chars]`}function nn(e){let t=[],n=[];for(let o of e)o.role==="tool"&&typeof o.content=="string"&&o.tool_call_id?Et(o.content)||n.push({toolCallId:o.tool_call_id,content:o.content,size:o.content.length}):o.role==="assistant"&&n.length>0&&(t.push(n),n=[]);return n.length>0&&t.push(n),t}function rn(e,t){let n=[],o=[],r=[];for(let i of e){let l=t.replacements.get(i.toolCallId);l!==void 0?n.push({...i,replacement:l}):t.seenIds.has(i.toolCallId)?o.push(i):r.push(i)}return{mustReapply:n,frozen:o,fresh:r}}function sn(e,t,n){let o=[...e].sort((l,s)=>s.size-l.size),r=[],i=t+e.reduce((l,s)=>l+s.size,0);for(let l of o){if(i<=n)break;r.push(l),i-=l.size}return r}async function Lt(e,t,n,o=Rt){let r=nn(e);if(r.length===0)return{messages:e,newlyReplacedCount:0};let i=new Map,l=[];for(let p of r){let{mustReapply:m,frozen:k,fresh:y}=rn(p,t);for(let T of m)i.set(T.toolCallId,T.replacement);if(y.length===0){for(let T of p)t.seenIds.add(T.toolCallId);continue}let _=k.reduce((T,R)=>T+R.size,0),C=y.reduce((T,R)=>T+R.size,0),h=_+C>o?sn(y,_,o):[],A=new Set(h.map(T=>T.toolCallId));for(let T of p)A.has(T.toolCallId)||t.seenIds.add(T.toolCallId);h.length>0&&l.push(...h)}if(i.size===0&&l.length===0)return{messages:e,newlyReplacedCount:0};let s=await Promise.all(l.map(async p=>{let m=await Mt(p.content,p.toolCallId,n);return{candidate:p,result:m}})),d=0;for(let{candidate:p,result:m}of s){if(t.seenIds.add(p.toolCallId),!m)continue;let k=wt(m);i.set(p.toolCallId,k),t.replacements.set(p.toolCallId,k),d++}return i.size===0?{messages:e,newlyReplacedCount:0}:{messages:e.map(p=>{if(p.role!=="tool"||!p.tool_call_id)return p;let m=i.get(p.tool_call_id);return m===void 0?p:{...p,content:m}}),newlyReplacedCount:d}}var an=new Set(["read_file","file_read","FileRead","grep","Grep","glob","Glob","search","list_dir","find_files","web_fetch","web_search","WebFetch","WebSearch"]),ln=new Set(["bash","execute_command","Bash","shell"]),pe=class{tools=[];hasErrored=!1;erroredToolDescription="";discarded=!1;siblingAbortController;progressResolve;config;concurrencySafe;constructor(t){this.config=t,this.concurrencySafe=t.concurrencySafeTools??an,this.siblingAbortController=new AbortController,t.signal&&t.signal.addEventListener("abort",()=>{this.siblingAbortController.abort("parent_abort")},{once:!0})}discard(){this.discarded=!0}addTool(t){let n=this.concurrencySafe.has(t.function.name);this.tools.push({id:t.id,toolCall:t,status:"queued",isConcurrencySafe:n,results:[],pendingProgress:[]}),this.processQueue()}canExecuteTool(t){let n=this.tools.filter(r=>r.status==="executing"),o=this.config.maxConcurrentTools;return o&&o>0&&n.length>=o?!1:n.length===0||t&&n.every(r=>r.isConcurrencySafe)}async processQueue(){for(let t of this.tools)if(t.status==="queued"){if(this.canExecuteTool(t.isConcurrencySafe))await this.executeTool(t);else if(!t.isConcurrencySafe)break}}getAbortReason(){return this.discarded?"discarded":this.hasErrored?"sibling_error":this.config.signal?.aborted?"user_interrupted":null}getToolDescription(t){let n;try{n=JSON.parse(t.toolCall.function.arguments)}catch{}let o=n?.command??n?.file_path??n?.pattern??"";if(typeof o=="string"&&o.length>0){let r=o.length>40?o.slice(0,40)+"\u2026":o;return`${t.toolCall.function.name}(${r})`}return t.toolCall.function.name}createSyntheticError(t,n){let o=this.erroredToolDescription,r=n==="user_interrupted"?"User rejected tool use":n==="discarded"?"Streaming fallback - tool execution discarded":o?`Cancelled: parallel tool call ${o} errored`:"Cancelled: parallel tool call errored";return{callId:t.id,toolName:t.toolCall.function.name,ok:!1,error:r,message:J(t.id,{ok:!1,error:r})}}async executeTool(t){t.status="executing";let o=(async()=>{let r=this.getAbortReason();if(r){t.results.push(this.createSyntheticError(t,r)),t.status="completed";return}let{toolInvoker:i,hooks:l,sessionId:s,turnId:d,log:g}=this.config,p=t.toolCall.function.name,m=!1,k=t.toolCall.function.arguments;if(l)try{let T=await l.invoke("tool.before_invoke",{sessionId:s,turnId:d,callId:t.id,toolName:p,arguments:cn(k)});if(T.action==="abort"){let R=T.reason??"blocked by policy";g.info(`tool ${p} blocked: ${R}`),t.results.push({callId:t.id,toolName:p,ok:!1,error:R,blocked:!0,blockReason:R,message:J(t.id,{ok:!1,error:R})}),t.status="completed";return}T.action==="continue"&&T.context?.arguments&&(k=JSON.stringify(T.context.arguments))}catch{}let y=await i.invoke(d,p,k,this.siblingAbortController.signal),_=this.getAbortReason();if(_&&!m){t.results.push(this.createSyntheticError(t,_)),t.status="completed";return}let C=!y.error,h=y.result;C&&h&&h.length>5e4&&(h=await It(h,t.id,s));let A=J(t.id,{ok:C,payload:h,error:y.error});C||(m=!0,ln.has(p)&&(this.hasErrored=!0,this.erroredToolDescription=this.getToolDescription(t),this.siblingAbortController.abort("sibling_error"))),l?.invoke(C?"tool.after_invoke":"tool.invoke_failed",{sessionId:s,turnId:d,callId:t.id,toolName:p,ok:C,...y.error?{error:y.error}:{}}).catch(()=>{}),t.results.push({callId:t.id,toolName:p,ok:C,error:y.error,message:A}),t.status="completed"})();t.promise=o,o.finally(()=>{this.processQueue()})}*getCompletedResults(){if(!this.discarded){for(let t of this.tools)if(t.status!=="yielded"){if(t.status==="completed"&&t.results.length>0){t.status="yielded";for(let n of t.results)yield n}else if(t.status==="executing"&&!t.isConcurrencySafe)break}}}async*getRemainingResults(){if(!this.discarded){for(;this.hasUnfinishedTools();){await this.processQueue();for(let t of this.getCompletedResults())yield t;if(this.hasExecutingTools()&&!this.hasCompletedResults()){let t=this.tools.filter(o=>o.status==="executing"&&o.promise).map(o=>o.promise),n=new Promise(o=>{this.progressResolve=o});t.length>0&&await Promise.race([...t,n])}}for(let t of this.getCompletedResults())yield t}}hasCompletedResults(){return this.tools.some(t=>t.status==="completed")}hasExecutingTools(){return this.tools.some(t=>t.status==="executing")}hasUnfinishedTools(){return this.tools.some(t=>t.status!=="yielded")}};function cn(e){try{return JSON.parse(e)}catch{return}}import{readFile as zr}from"node:fs/promises";function Ge(e){let t=typeof e.content=="string"?e.content:e.content!=null?JSON.stringify(e.content):"";return Math.ceil(t.length/4)}function je(e){let t=0;for(let n of e)t+=Ge(n);return t}var ze={"deepseek-chat":64e3,"deepseek-reasoner":64e3,"deepseek-v4-flash":64e3,"gpt-4o":128e3,"gpt-4o-mini":128e3,"claude-sonnet-4-20250514":2e5,"claude-3-5-haiku-20241022":2e5,"gemini-2.0-flash":1e6,"gemini-2.5-flash-preview-05-20":1e6};function un(e){if(!e)return 128e3;if(e in ze)return ze[e];let t=e.toLowerCase();for(let[n,o]of Object.entries(ze))if(t.startsWith(n.toLowerCase()))return o;return 128e3}var dn=8e3;var pn=new Z(200);var Gr=new ee;function mn(){return he(new Q(dn),new j(20,Ge),new V(Ge))}var gn=null;function Ot(e,t){let n=t?.budget??Ce({modelContextWindow:un(t?.model)}),r=(t?.pipeline??mn()).compress(e,n);if(r.droppedCount>0){let i=je(e),l=je(r.messages);pn.record({timestamp:Date.now(),strategy:r.strategy,tokensBefore:i,tokensAfter:l,droppedCount:r.droppedCount,latencyMs:r.metrics?.latencyMs??0,usedLlm:!1,cacheInvalidated:r.metrics?.cacheInvalidated??!1,tier:be(i,n)})}return r.droppedCount>0&&gn?.(r.droppedCount,je(r.messages)),r}function Pt(e,t,n){let o=n-t;return`[Budget] ${Math.round(e)}% used (${t.toLocaleString()} / ${n.toLocaleString()} tokens). ${o.toLocaleString()} tokens remaining. `+(e>=90?"Wrap up your current task \u2014 you are near the token limit.":"Continue working \u2014 do not summarize prematurely.")}function kn(e){return typeof e=="number"&&Number.isFinite(e)&&e>=1?Math.min(Math.round(e),100):pt}function Dt(e){let t=e.message.toLowerCase();return e.status===413||t.includes("prompt_too_long")||t.includes("context_length_exceeded")||t.includes("maximum context length")}function _n(e){return e==="length"||e==="max_tokens"}function Bt(e){let t=e.message.toLowerCase();return(t.includes("image")||t.includes("media")||t.includes("file too large")||t.includes("payload too large"))&&(e.status===413||t.includes("too large")||t.includes("size"))}function Rn(e){let t=e.headers;if(!t)return null;let n=t["retry-after"]??t["Retry-After"];if(!n)return null;let o=parseInt(n,10);return!isNaN(o)&&o>0?o*1e3:null}function xn(e){if(e.status!==400)return null;let t=e.message.match(/input length and `max_tokens` exceed context limit: (\d+) \+ (\d+) > (\d+)/);if(!t?.[1]||!t?.[3])return null;let n=parseInt(t[1],10),o=parseInt(t[3],10);if(isNaN(n)||isNaN(o))return null;let r=o-n-1e3;return r>=3e3?r:null}function Sn(e){return e.filter(t=>t.role!=="assistant"?!0:!(typeof t.content=="string"&&t.content.trim()===""))}async function*$t(e,t,n,o){let{turnId:r,sessionId:i,messages:l,tools:s,model:d,apiKey:g,temperature:p,hooks:m,signal:k}=e,y={sessionId:i,turnId:r},_=e.maxTurns??0,C=e.querySource,{resolveToolEligibility:h}=await Promise.resolve().then(()=>(Ft(),Nt)),A=h(s,e.toolEligibilityContext),T=A.eligibleTools;for(let v of A.blockedTools)yield{type:"tool_blocked",turnId:r,callId:"",name:v.toolName,reason:"blocked-by-policy"};if(!T.length){yield*vn(r,d,l,g,p,k,t,o);return}let R=kn(e.maxRounds),E={contextWindowTokens:e.contextWindowTokens??gt,responseBufferTokens:ft,maxOutputTokens:e.maxOutputTokens??yt,abortSignal:k,reactiveCompactEnabled:!0,outputEscalationEnabled:!0},q=new Set,F=0,ne=T,re,c={messages:[...l],maxOutputTokensRecoveryCount:0,hasAttemptedReactiveCompact:!1,maxOutputTokensOverride:void 0,turnCount:1,transition:void 0,guardState:Pe(E),reactiveCompactState:$e(),toolLoopState:ue({maxRounds:R,replayMessages:[...l]}).state,consecutiveFailedRounds:0,finalText:"",totalUsage:{prompt:0,completion:0},collapseStore:_e(),currentModel:d,consecutive529Errors:0,consecutiveApiRetries:0,stopHookActive:void 0,snipRemovedIds:new Set,contentReplacementState:vt()};for(;;){let{messages:v,maxOutputTokensRecoveryCount:W,hasAttemptedReactiveCompact:En,maxOutputTokensOverride:He,turnCount:K,guardState:x,reactiveCompactState:L,collapseStore:me}=c,{toolLoopState:M}=c;if(re){try{let a=await re;a&&(yield{type:"tool_use_summary",turnId:r,summary:a})}catch{}re=void 0}if(e.refreshTools&&K>1){let a=e.refreshTools();a!==ne&&(ne=a,o.debug(`tools refreshed: ${a.length} tools`))}if(Be(x,E)){o.info(`turn aborted by guard at turn ${K}`),yield{type:"error",turnId:r,error:"Turn aborted",code:"ABORTED"};return}let D=Ne(x,E);if(D.level==="blocking"){D.reason==="prompt_too_long"&&H(L)&&(L.attemptedThisTurn=!0,x.hasAttemptedReactiveCompact=!0,o.info(`token budget blocking (${D.reason}), reactive compact needed`),yield{type:"recovery",turnId:r,action:"reactive_compact",detail:"token budget pre-check"}),o.info(`token budget blocking (${D.reason}), ending tool loop`);break}D.level==="warning"&&o.info(`token budget warning: ${D.usagePercent}% used, ${D.remainingTokens} remaining`);let S;{let a=await Lt(v,c.contentReplacementState,i);S=a.messages,a.newlyReplacedCount>0&&(o.info(`tool-result-budget: persisted ${a.newlyReplacedCount} oversized tool results`),yield{type:"recovery",turnId:r,action:"tool_result_budget",detail:`${a.newlyReplacedCount} persisted`})}{let a=ke(S,c.snipRemovedIds);S=a.messages,a.removedCount>0&&(o.info(`snip: removed ${a.removedCount} messages, freed ~${a.tokensFreed} tokens`),yield{type:"recovery",turnId:r,action:"snip",detail:`${a.removedCount} messages`})}{let u=new j().compress(S,0);u.droppedCount>0&&(S=u.messages,o.info(`microcompact: cleared ${u.droppedCount} old tool results`))}if(S=Re(S,me).messages,x.promptTokens>0){let a=Ot(S,{budget:E.contextWindowTokens*.75,model:c.currentModel});a.droppedCount>0&&(S=a.messages,o.info(`autocompact: ${a.strategy}, dropped ${a.droppedCount}`),yield{type:"recovery",turnId:r,action:"autocompact",detail:`${a.strategy}: ${a.droppedCount} dropped`},c.hasAttemptedReactiveCompact=!1,m?.invoke("context.after_compact",{...y,removedCount:a.droppedCount}).catch(()=>{}))}S=Sn(S);let se=Se({tools:ne,toolChoice:e.toolChoice??"auto"}),X=ue({maxRounds:R,replayMessages:S,lastStopReason:M.lastStopReason,options:{stopReason:M.lastStopReason}}),qe=se.extraSystemPrompt?[{role:"system",content:se.extraSystemPrompt},...X.state.replayMessages]:X.state.replayMessages;M=X.state,X.recoveryActions.length>0&&o.debug(`tool loop recovery: ${X.recoveryActions.map(a=>a.detail??a.kind).join("; ")}`),o.debug(`turn ${K}, messages: ${qe.length}`),m?.invoke("turn.before_inference",{...y,model:c.currentModel}).catch(()=>{});let ie=!1,We=[],Ke=new Map,Xe="stop",P,f=null,ae=!1;try{for await(let a of t.stream({model:c.currentModel,messages:qe,tools:se.tools,toolChoice:se.normalizedToolChoice??"auto",temperature:p,maxTokens:(He??x.currentMaxOutputTokens)||void 0},g,k))switch(a.type){case"delta":We.push(a.text),ie||(yield{type:"delta",turnId:r,text:a.text});break;case"tool_call_delta":ie=!0,dt(Ke,a);break;case"reasoning_delta":break;case"usage":P={prompt:a.promptTokens,completion:a.completionTokens,reasoning:a.reasoningTokens};break;case"done":Xe=a.finishReason;break}if(ie||m?.invoke("turn.after_inference",{...y,model:c.currentModel}).catch(()=>{}),e.postSamplingHooks&&e.postSamplingHooks.length>0){let a=c.currentModel;for(let u of e.postSamplingHooks)try{u({messages:[...S],model:a,sessionId:i})}catch{}}}catch(a){if(a instanceof te&&e.fallbackModel){o.info(`model fallback triggered: ${a.originalModel} \u2192 ${a.fallbackModel}`),yield{type:"recovery",turnId:r,action:"model_fallback",detail:`${a.originalModel} \u2192 ${a.fallbackModel}`},c={...c,currentModel:a.fallbackModel,consecutive529Errors:0,consecutiveApiRetries:0,transition:void 0};continue}let u=a instanceof Error?a.message:String(a),b=typeof a?.status=="number"?a.status:void 0;if(!b&&u&&(u.includes("ECONNRESET")||u.includes("EPIPE"))){let I=(c.consecutiveApiRetries??0)+1;if(I>oe){o.info(`stale connection retry limit reached (${oe}), aborting`),yield{type:"error",turnId:r,error:u,code:"RETRIES_EXHAUSTED"};return}o.info(`stale connection (${u.includes("ECONNRESET")?"ECONNRESET":"EPIPE"}): retrying`),yield{type:"recovery",turnId:r,action:"stale_connection_retry",detail:u.slice(0,80)},c={...c,consecutiveApiRetries:I,transition:void 0};continue}let w=xn({status:b,message:u});if(w!==null){o.info(`max_tokens overflow: adjusting to ${w}`),x.currentMaxOutputTokens=w,c={...c,maxOutputTokensOverride:w,transition:void 0};continue}if(Le(b)){if(c.consecutive529Errors++,c.consecutive529Errors>=kt&&e.fallbackModel&&c.currentModel!==e.fallbackModel){o.info(`529 \xD7 ${c.consecutive529Errors}: triggering fallback to ${e.fallbackModel}`),yield{type:"recovery",turnId:r,action:"model_fallback",detail:`529 \xD7 ${c.consecutive529Errors}`},c={...c,currentModel:e.fallbackModel,consecutive529Errors:0,transition:void 0};continue}if(Oe()){let I=de(c.consecutive529Errors);o.info(`persistent retry: waiting ${I}ms (attempt ${c.consecutive529Errors})`);let O=I;for(;O>0;){if(k?.aborted){yield{type:"error",turnId:r,error:"Aborted during retry wait",code:"ABORTED"};return}yield{type:"heartbeat",turnId:r,message:`Retrying in ${Math.ceil(O/1e3)}s (${b})`};let z=Math.min(O,bt);await new Promise(Gt=>setTimeout(Gt,z)),O-=z}c={...c,transition:void 0};continue}if(Ie(C)){let O=Rn({status:b,message:u})??de(c.consecutive529Errors);o.info(`transient ${b}: retry in ${O}ms`),yield{type:"recovery",turnId:r,action:"retry",detail:`${b} retry in ${O}ms`},await new Promise(z=>setTimeout(z,O)),c={...c,transition:void 0};continue}o.info(`background source ${C}: not retrying ${b}`)}f={status:b,message:u}}if(f&&m?.invoke("turn.after_inference",{...y,model:c.currentModel,response:{error:f.message}}).catch(()=>{}),f)if(Dt(f))ae=!0,o.info(`withheld prompt_too_long error (status=${f.status})`);else if(Bt(f))ae=!0,o.info(`withheld media_size error (status=${f.status})`);else{let a=Fe({status:f.status??500,message:f.message},x,E);if(a.action==="reactive_compact"&&H(L)&&(L.attemptedThisTurn=!0,x.hasAttemptedReactiveCompact=!0,yield{type:"recovery",turnId:r,action:"reactive_compact",detail:`API ${f.status??500}: ${f.message}`}),a.action==="retry"){let b=(c.consecutiveApiRetries??0)+1;if(b>oe){o.info(`API retry limit reached (${oe}), aborting`);let w=G(f.status,f.message);yield{type:"error",turnId:r,error:f.message,code:w};return}yield{type:"recovery",turnId:r,action:"retry",detail:a.reason},c={...c,consecutiveApiRetries:b,transition:void 0};continue}let u=G(f.status,f.message);m?.invoke("stop.failure",{sessionId:i,reason:u,error:f.message}).catch(()=>{}),yield{type:"error",turnId:r,error:f.message,code:u};return}P&&(c.totalUsage.prompt+=P.prompt,c.totalUsage.completion+=P.completion,P.reasoning&&(c.totalUsage.reasoning=(c.totalUsage.reasoning??0)+P.reasoning)),P?.prompt&&(x.promptTokens=P.prompt),c.finalText=We.join("");let N=[...Ke.values()].map(a=>({id:a.id||`tc_${r}_${K}_${Math.random().toString(36).slice(2,8)}`,type:"function",function:{name:a.name,arguments:a.arguments}}));if(N.length===0&&!ie){if(ae&&f&&Dt(f)){if(c.transition?.reason!=="collapse_drain_retry"){let a=xe(S,me);if(a.committed>0){o.info(`collapse drain: committed ${a.committed} stages`),yield{type:"recovery",turnId:r,action:"collapse_drain",detail:`${a.committed} stages committed`},c={...c,messages:a.messages,transition:{reason:"collapse_drain_retry",committed:a.committed}};continue}}if(H(L)){L.attemptedThisTurn=!0,x.hasAttemptedReactiveCompact=!0,o.info("withheld 413: reactive compact attempt"),yield{type:"recovery",turnId:r,action:"reactive_compact",detail:"withheld prompt_too_long"},c={...c,hasAttemptedReactiveCompact:!0,transition:{reason:"reactive_compact_retry"}};continue}o.info("withheld 413: recovery exhausted, surfacing error"),m?.invoke("stop.failure",{sessionId:i,reason:"prompt_too_long",error:f.message}).catch(()=>{}),yield{type:"error",turnId:r,error:f.message,code:"PROMPT_TOO_LONG"};return}if(ae&&f&&Bt(f)){if(H(L)){L.attemptedThisTurn=!0,x.hasAttemptedReactiveCompact=!0,o.info("withheld media error: reactive compact strip-retry"),yield{type:"recovery",turnId:r,action:"reactive_compact",detail:"media error strip-retry"},c={...c,hasAttemptedReactiveCompact:!0,transition:{reason:"reactive_compact_retry"}};continue}o.info("withheld media error: recovery exhausted"),m?.invoke("stop.failure",{sessionId:i,reason:"media_error",error:f.message}).catch(()=>{}),yield{type:"error",turnId:r,error:f.message,code:"IMAGE_ERROR"};return}if(_n(Xe)){x.consecutiveTruncations+=1;let a=e.modelMaxOutputTokens??Tt,u=De(x,E,a);if(u.shouldEscalate&&He===void 0){x.currentMaxOutputTokens=u.newMax,o.info(`max_output_tokens escalate: ${u.newMax} tokens`),yield{type:"recovery",turnId:r,action:"output_escalation",detail:`${u.newMax} tokens`},c={...c,maxOutputTokensOverride:Ct,transition:{reason:"max_output_tokens_escalate"}};continue}if(W<ht){let b={role:"user",content:"Output token limit hit. Resume directly \u2014 no apology, no recap of what you were doing. Pick up mid-thought if that is where the cut happened. Break remaining work into smaller pieces."};o.info(`max_output_tokens recovery #${W+1}`),yield{type:"recovery",turnId:r,action:"max_output_tokens_recovery",detail:`attempt ${W+1}`},c={...c,messages:[...S,b],maxOutputTokensRecoveryCount:W+1,maxOutputTokensOverride:void 0,transition:{reason:"max_output_tokens_recovery",attempt:W+1}};continue}o.info("max_output_tokens recovery exhausted, completing with partial content")}else x.consecutiveTruncations=0;if(M=ce(M,{replayMessages:v,lastStopReason:"completed"}),m){let a=await m.invoke("stop",{sessionId:i,reason:"completed"});if(a.action==="prevent"){o.info(`stop hook prevented continuation: ${a.reason??"no reason"}`),yield{type:"end",turnId:r,content:c.finalText,usage:c.totalUsage,model:c.currentModel};return}if(a.action==="abort"){let u=a.reason??"Stop hook requested continuation";o.info(`stop hook blocking: ${u}`);let b={role:"user",content:u};c={...c,messages:[...v,{role:"assistant",content:c.finalText},b],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}};continue}}if(e.tokenBudget&&e.tokenBudget>0){let a=c.totalUsage.prompt+c.totalUsage.completion+(c.totalUsage.reasoning??0),u=a/e.tokenBudget*100;if(u<90){let b={role:"user",content:Pt(u,a,e.tokenBudget)};o.info(`token budget continuation: ${Math.round(u)}% used`),yield{type:"recovery",turnId:r,action:"budget_continuation",detail:`${Math.round(u)}% used`},c={...c,messages:[...v,{role:"assistant",content:c.finalText},b],transition:{reason:"token_budget_continuation"}};continue}}if(F>0){let a={ok:!0,toolCallCount:F,distinctToolCount:q.size,multiStep:F>=2,hasSubAgent:!1,feedback:null,existingSkillName:null},u=le(a,{tools:[...q]});u&&(yield{type:"skill_instruction",turnId:r,instruction:u})}yield{type:"end",turnId:r,content:c.finalText,usage:c.totalUsage,model:c.currentModel};return}for(let a of N){let u=a.function.arguments,b=ne.find(w=>w.function.name===a.function.name);if(b?.backfillObservableInput)try{let w=JSON.parse(a.function.arguments),I={...w};b.backfillObservableInput(I),Object.keys(I).some(z=>!(z in w))&&(u=JSON.stringify(I))}catch{}yield{type:"tool_call",turnId:r,callId:a.id,name:a.function.name,arguments:u}}v.push(fe(N)),M=we(M,{replayMessages:v,pendingToolCallIds:N.map(a=>a.id),completedToolCallIds:M.completedToolCallIds,lastStopReason:"tool_calls"});let Ye=[];try{let a=new pe({toolInvoker:n,hooks:m,sessionId:i,turnId:r,log:o,signal:k,maxConcurrentTools:e?.maxConcurrentTools});for(let u of N)a.addTool(u);for await(let u of a.getRemainingResults())u.blocked&&(yield{type:"tool_blocked",turnId:r,callId:u.callId,name:u.toolName,reason:u.blockReason??"blocked"}),v.push(u.message),Ye.push(u.callId),q.add(u.toolName),F++,yield{type:"tool_result",turnId:r,callId:u.callId,name:u.toolName,ok:u.ok,error:u.error}}catch(a){let u=a instanceof Error?a.message:String(a);yield{type:"error",turnId:r,error:u,code:"TOOL_EXECUTION_ERROR"};return}if(M=ce(M,{replayMessages:v,completedToolCallIds:[...M.completedToolCallIds,...Ye],lastStopReason:"tool_calls"}),e.generateToolUseSummary&&N.length>0){let a=N.map(u=>({name:u.function.name,arguments:u.function.arguments}));re=e.generateToolUseSummary(a).catch(()=>null)}let Je=v.slice(-N.length),zt=Je.length>0&&Je.every(a=>{let u=a?.content;if(typeof u!="string")return!1;try{return JSON.parse(u)?.ok===!1}catch{return!1}}),Y=c.consecutiveFailedRounds;if(zt){if(Y+=1,Y>=mt&&c.finalText){o.info(`early exit: ${Y} consecutive failed rounds, returning partial response`),yield{type:"end",turnId:r,content:c.finalText,usage:c.totalUsage,model:c.currentModel};return}}else Y=0;let ge=K+1;if(_>0&&ge>_){if(o.info(`max turns reached (${_}), completing`),m){let a=await m.invoke("stop",{sessionId:i,reason:"max_turns"});if(a.action==="abort"){let u=a.reason??"Stop hook requested continuation after max_turns";c={...c,messages:[...v,{role:"assistant",content:c.finalText},{role:"user",content:u}],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}};continue}}yield{type:"end",turnId:r,content:c.finalText,usage:c.totalUsage,model:c.currentModel};return}if(ge>R){if(c.finalText){if(o.info(`tool loop budget exhausted (${R} rounds), returning partial response`),F>0){let a={ok:!0,toolCallCount:F,distinctToolCount:q.size,multiStep:F>=2,hasSubAgent:!1,feedback:null,existingSkillName:null},u=le(a,{tools:[...q]});u&&(yield{type:"skill_instruction",turnId:r,instruction:u})}yield{type:"end",turnId:r,content:c.finalText,usage:c.totalUsage,model:c.currentModel};return}yield{type:"error",turnId:r,error:`Tool loop exceeded budget (${R} rounds)`,code:"TOOL_LOOP_LIMIT"};return}c={messages:v,maxOutputTokensRecoveryCount:0,hasAttemptedReactiveCompact:!1,maxOutputTokensOverride:void 0,turnCount:ge,transition:{reason:"next_turn"},guardState:x,reactiveCompactState:L,toolLoopState:M,consecutiveFailedRounds:Y,finalText:c.finalText,totalUsage:c.totalUsage,collapseStore:me,currentModel:c.currentModel,consecutive529Errors:0,consecutiveApiRetries:0,stopHookActive:c.stopHookActive,snipRemovedIds:c.snipRemovedIds,contentReplacementState:c.contentReplacementState}}}async function*vn(e,t,n,o,r,i,l,s){let d=[],g;s.debug(`single LLM round, messages: ${n.length}`);for await(let p of l.stream({model:t,messages:n,temperature:r},o,i))switch(p.type){case"delta":d.push(p.text),yield{type:"delta",turnId:e,text:p.text};break;case"usage":g={prompt:p.promptTokens,completion:p.completionTokens,reasoning:p.reasoningTokens};break;case"done":break}yield{type:"end",turnId:e,content:d.join(""),usage:g??{prompt:0,completion:0},model:t}}var jt=class{transport;apiKey;toolInvoker;log;hooks;maxRounds;constructor(t){this.transport=t.llmTransport,this.apiKey=t.apiKey,this.toolInvoker=t.toolInvoker,this.log=t.log,this.hooks=t.hooks,this.maxRounds=Math.min(t.maxRounds??25,100)}async*run(t,n){let{turnId:o,messages:r,tools:i,systemPrompt:l,config:s}=t,d={sessionId:t.sessionId,turnId:o};yield{type:"start",turnId:o},this.hooks?.invoke("turn.submitted",{...d,prompt:r[r.length-1]?.content??void 0}).catch(()=>{});let g=Me(r),p=[];if(l&&p.push({role:"system",content:l}),p.push(...g),this.hooks){let y=g.filter(C=>C.role==="user").pop(),_=typeof y?.content=="string"?y.content.slice(0,500):void 0;if(_)try{let C=await this.hooks.invoke("memory.before_recall",{sessionId:t.sessionId,turnId:o,query:_}),h=C?.context?.recalledMemories;if(h&&h.length>0){let A=h.map(T=>`- ${T.text}`).join(`
|
|
17
|
-
`);
|
|
18
|
-
${
|
|
15
|
+
`,t+=tn,t}async function Ot(e,t,n,o=xt){if(e.length<=o||wt(e))return e;let r=await It(e,t,n);return r?Lt(r):e.slice(0,o)+`
|
|
16
|
+
...[truncated ${e.length-o} chars]`}function sn(e){let t=[],n=[];for(let o of e)o.role==="tool"&&typeof o.content=="string"&&o.tool_call_id?wt(o.content)||n.push({toolCallId:o.tool_call_id,content:o.content,size:o.content.length}):o.role==="assistant"&&n.length>0&&(t.push(n),n=[]);return n.length>0&&t.push(n),t}function an(e,t){let n=[],o=[],r=[];for(let a of e){let l=t.replacements.get(a.toolCallId);l!==void 0?n.push({...a,replacement:l}):t.seenIds.has(a.toolCallId)?o.push(a):r.push(a)}return{mustReapply:n,frozen:o,fresh:r}}function ln(e,t,n){let o=[...e].sort((l,s)=>s.size-l.size),r=[],a=t+e.reduce((l,s)=>l+s.size,0);for(let l of o){if(a<=n)break;r.push(l),a-=l.size}return r}async function Pt(e,t,n,o=vt){let r=sn(e);if(r.length===0)return{messages:e,newlyReplacedCount:0};let a=new Map,l=[];for(let d of r){let{mustReapply:m,frozen:_,fresh:y}=an(d,t);for(let h of m)a.set(h.toolCallId,h.replacement);if(y.length===0){for(let h of d)t.seenIds.add(h.toolCallId);continue}let R=_.reduce((h,v)=>h+v.size,0),b=y.reduce((h,v)=>h+v.size,0),C=R+b>o?ln(y,R,o):[],P=new Set(C.map(h=>h.toolCallId));for(let h of d)P.has(h.toolCallId)||t.seenIds.add(h.toolCallId);C.length>0&&l.push(...C)}if(a.size===0&&l.length===0)return{messages:e,newlyReplacedCount:0};let s=await Promise.all(l.map(async d=>{let m=await It(d.content,d.toolCallId,n);return{candidate:d,result:m}})),p=0;for(let{candidate:d,result:m}of s){if(t.seenIds.add(d.toolCallId),!m)continue;let _=Lt(m);a.set(d.toolCallId,_),t.replacements.set(d.toolCallId,_),p++}return a.size===0?{messages:e,newlyReplacedCount:0}:{messages:e.map(d=>{if(d.role!=="tool"||!d.tool_call_id)return d;let m=a.get(d.tool_call_id);return m===void 0?d:{...d,content:m}}),newlyReplacedCount:p}}var cn=new Set(["read_file","file_read","FileRead","grep","Grep","glob","Glob","search","list_dir","find_files","web_fetch","web_search","WebFetch","WebSearch"]),un=new Set(["bash","execute_command","Bash","shell"]),me=class{tools=[];hasErrored=!1;erroredToolDescription="";discarded=!1;siblingAbortController;progressResolve;config;concurrencySafe;constructor(t){this.config=t,this.concurrencySafe=t.concurrencySafeTools??cn,this.siblingAbortController=new AbortController,t.signal&&t.signal.addEventListener("abort",()=>{this.siblingAbortController.abort("parent_abort")},{once:!0})}discard(){this.discarded=!0}addTool(t){let n=this.concurrencySafe.has(t.function.name);this.tools.push({id:t.id,toolCall:t,status:"queued",isConcurrencySafe:n,results:[],pendingProgress:[]}),this.processQueue()}canExecuteTool(t){let n=this.tools.filter(r=>r.status==="executing"),o=this.config.maxConcurrentTools;return o&&o>0&&n.length>=o?!1:n.length===0||t&&n.every(r=>r.isConcurrencySafe)}async processQueue(){for(let t of this.tools)if(t.status==="queued"){if(this.canExecuteTool(t.isConcurrencySafe))await this.executeTool(t);else if(!t.isConcurrencySafe)break}}getAbortReason(){return this.discarded?"discarded":this.hasErrored?"sibling_error":this.config.signal?.aborted?"user_interrupted":null}getToolDescription(t){let n;try{n=JSON.parse(t.toolCall.function.arguments)}catch{}let o=n?.command??n?.file_path??n?.pattern??"";if(typeof o=="string"&&o.length>0){let r=o.length>40?o.slice(0,40)+"\u2026":o;return`${t.toolCall.function.name}(${r})`}return t.toolCall.function.name}createSyntheticError(t,n){let o=this.erroredToolDescription,r=n==="user_interrupted"?"User rejected tool use":n==="discarded"?"Streaming fallback - tool execution discarded":o?`Cancelled: parallel tool call ${o} errored`:"Cancelled: parallel tool call errored";return{callId:t.id,toolName:t.toolCall.function.name,ok:!1,error:r,message:V(t.id,{ok:!1,error:r})}}async executeTool(t){t.status="executing";let o=(async()=>{let r=this.getAbortReason();if(r){t.results.push(this.createSyntheticError(t,r)),t.status="completed";return}let{toolInvoker:a,hooks:l,sessionId:s,turnId:p,log:g}=this.config,d=t.toolCall.function.name,m=!1,_=t.toolCall.function.arguments;if(l)try{let h=await l.invoke("tool.before_invoke",{sessionId:s,turnId:p,callId:t.id,toolName:d,arguments:dn(_)});if(h.action==="abort"){let v=h.reason??"blocked by policy";g.info(`tool ${d} blocked: ${v}`),t.results.push({callId:t.id,toolName:d,ok:!1,error:v,blocked:!0,blockReason:v,message:V(t.id,{ok:!1,error:v})}),t.status="completed";return}h.action==="continue"&&h.context?.arguments&&(_=JSON.stringify(h.context.arguments))}catch{}let y=await a.invoke(p,d,_,this.siblingAbortController.signal),R=this.getAbortReason();if(R&&!m){t.results.push(this.createSyntheticError(t,R)),t.status="completed";return}let b=!y.error,C=y.result;b&&C&&C.length>5e4&&(C=await Ot(C,t.id,s));let P=V(t.id,{ok:b,payload:C,error:y.error});b||(m=!0,un.has(d)&&(this.hasErrored=!0,this.erroredToolDescription=this.getToolDescription(t),this.siblingAbortController.abort("sibling_error"))),l?.invoke(b?"tool.after_invoke":"tool.invoke_failed",{sessionId:s,turnId:p,callId:t.id,toolName:d,ok:b,...y.error?{error:y.error}:{}}).catch(()=>{}),t.results.push({callId:t.id,toolName:d,ok:b,error:y.error,message:P}),t.status="completed"})();t.promise=o,o.finally(()=>{this.processQueue()})}*getCompletedResults(){if(!this.discarded){for(let t of this.tools)if(t.status!=="yielded"){if(t.status==="completed"&&t.results.length>0){t.status="yielded";for(let n of t.results)yield n}else if(t.status==="executing"&&!t.isConcurrencySafe)break}}}async*getRemainingResults(){if(!this.discarded){for(;this.hasUnfinishedTools();){await this.processQueue();for(let t of this.getCompletedResults())yield t;if(this.hasExecutingTools()&&!this.hasCompletedResults()){let t=this.tools.filter(o=>o.status==="executing"&&o.promise).map(o=>o.promise),n=new Promise(o=>{this.progressResolve=o});t.length>0&&await Promise.race([...t,n])}}for(let t of this.getCompletedResults())yield t}}hasCompletedResults(){return this.tools.some(t=>t.status==="completed")}hasExecutingTools(){return this.tools.some(t=>t.status==="executing")}hasUnfinishedTools(){return this.tools.some(t=>t.status!=="yielded")}};function dn(e){try{return JSON.parse(e)}catch{return}}import{readFile as Kr}from"node:fs/promises";function He(e){let t=typeof e.content=="string"?e.content:e.content!=null?JSON.stringify(e.content):"";return Math.ceil(t.length/4)}function Ge(e){let t=0;for(let n of e)t+=He(n);return t}var qe={"deepseek-chat":64e3,"deepseek-reasoner":64e3,"deepseek-v4-flash":64e3,"gpt-4o":128e3,"gpt-4o-mini":128e3,"claude-sonnet-4-20250514":2e5,"claude-3-5-haiku-20241022":2e5,"gemini-2.0-flash":1e6,"gemini-2.5-flash-preview-05-20":1e6};function pn(e){if(!e)return 128e3;if(e in qe)return qe[e];let t=e.toLowerCase();for(let[n,o]of Object.entries(qe))if(t.startsWith(n.toLowerCase()))return o;return 128e3}var mn=8e3;var gn=new ee(200);var Xr=new te;function fn(){return be(new Z(mn),new G(20,He),new Q(He))}var yn=null;function Nt(e,t){let n=t?.budget??ke({modelContextWindow:pn(t?.model)}),r=(t?.pipeline??fn()).compress(e,n);if(r.droppedCount>0){let a=Ge(e),l=Ge(r.messages);gn.record({timestamp:Date.now(),strategy:r.strategy,tokensBefore:a,tokensAfter:l,droppedCount:r.droppedCount,latencyMs:r.metrics?.latencyMs??0,usedLlm:!1,cacheInvalidated:r.metrics?.cacheInvalidated??!1,tier:_e(a,n)})}return r.droppedCount>0&&yn?.(r.droppedCount,Ge(r.messages)),r}function Ft(e,t,n){let o=n-t;return`[Budget] ${Math.round(e)}% used (${t.toLocaleString()} / ${n.toLocaleString()} tokens). ${o.toLocaleString()} tokens remaining. `+(e>=90?"Wrap up your current task \u2014 you are near the token limit.":"Continue working \u2014 do not summarize prematurely.")}var Rn=new Set(["write","edit","patch","apply_patch"]);function xn(e){let t=e.split(".").pop()?.toLowerCase()??"";return["png","jpg","jpeg","gif","webp","svg","bmp","ico"].includes(t)?"image":["md","txt","pdf","doc","docx","rtf","html"].includes(t)?"document":["mermaid","mmd","dot","puml","plantuml"].includes(t)?"diagram":["csv","tsv","xlsx","xls"].includes(t)?"table":["ts","tsx","js","jsx","py","rs","go","java","c","cpp","h","cs","rb","sh","sql","json","yaml","yml","toml","xml","css","scss","vue","svelte"].includes(t)?"code":"file"}function vn(e){let t=e.split(".").pop()?.toLowerCase()??"";return{ts:"typescript",tsx:"typescriptreact",js:"javascript",jsx:"javascriptreact",py:"python",rs:"rust",go:"go",java:"java",c:"c",cpp:"cpp",h:"c",cs:"csharp",rb:"ruby",sh:"shellscript",sql:"sql",json:"json",yaml:"yaml",yml:"yaml",toml:"toml",xml:"xml",html:"html",css:"css",scss:"scss",vue:"vue",svelte:"svelte",md:"markdown"}[t]}function Sn(e){return typeof e=="number"&&Number.isFinite(e)&&e>=1?Math.min(Math.round(e),100):gt}function Ut(e){let t=e.message.toLowerCase();return e.status===413||t.includes("prompt_too_long")||t.includes("context_length_exceeded")||t.includes("maximum context length")}function An(e){return e==="length"||e==="max_tokens"}function $t(e){let t=e.message.toLowerCase();return(t.includes("image")||t.includes("media")||t.includes("file too large")||t.includes("payload too large"))&&(e.status===413||t.includes("too large")||t.includes("size"))}function En(e){let t=e.headers;if(!t)return null;let n=t["retry-after"]??t["Retry-After"];if(!n)return null;let o=parseInt(n,10);return!isNaN(o)&&o>0?o*1e3:null}function Mn(e){if(e.status!==400)return null;let t=e.message.match(/input length and `max_tokens` exceed context limit: (\d+) \+ (\d+) > (\d+)/);if(!t?.[1]||!t?.[3])return null;let n=parseInt(t[1],10),o=parseInt(t[3],10);if(isNaN(n)||isNaN(o))return null;let r=o-n-1e3;return r>=3e3?r:null}function wn(e){return e.filter(t=>t.role!=="assistant"?!0:!(typeof t.content=="string"&&t.content.trim()===""))}async function*jt(e,t,n,o){let{turnId:r,sessionId:a,messages:l,tools:s,model:p,apiKey:g,temperature:d,hooks:m,signal:_}=e,y={sessionId:a,turnId:r},R=e.maxTurns??0,b=e.querySource,{resolveToolEligibility:C}=await Promise.resolve().then(()=>(Dt(),Bt)),P=C(s,e.toolEligibilityContext),h=P.eligibleTools;for(let M of P.blockedTools)yield{type:"tool_blocked",turnId:r,callId:"",name:M.toolName,reason:"blocked-by-policy"};if(!h.length){yield*In(r,p,l,g,d,_,t,o);return}let v=Sn(e.maxRounds),I={contextWindowTokens:e.contextWindowTokens??yt,responseBufferTokens:ht,maxOutputTokens:e.maxOutputTokens??Tt,abortSignal:_,reactiveCompactEnabled:!0,outputEscalationEnabled:!0},W=new Set,D=0,re=h,se,c={messages:[...l],maxOutputTokensRecoveryCount:0,hasAttemptedReactiveCompact:!1,maxOutputTokensOverride:void 0,turnCount:1,transition:void 0,guardState:Fe(I),reactiveCompactState:je(),toolLoopState:de({maxRounds:v,replayMessages:[...l]}).state,consecutiveFailedRounds:0,finalText:"",totalUsage:{prompt:0,completion:0},collapseStore:xe(),currentModel:p,consecutive529Errors:0,consecutiveApiRetries:0,stopHookActive:void 0,snipRemovedIds:new Set,contentReplacementState:Et()};for(;;){let{messages:M,maxOutputTokensRecoveryCount:K,hasAttemptedReactiveCompact:On,maxOutputTokensOverride:We,turnCount:X,guardState:S,reactiveCompactState:N,collapseStore:ge}=c,{toolLoopState:L}=c;if(se){try{let i=await se;i&&(yield{type:"tool_use_summary",turnId:r,summary:i})}catch{}se=void 0}if(e.refreshTools&&X>1){let i=e.refreshTools();i!==re&&(re=i,o.debug(`tools refreshed: ${i.length} tools`))}if($e(S,I)){o.info(`turn aborted by guard at turn ${X}`),yield{type:"error",turnId:r,error:"Turn aborted",code:"ABORTED",usage:c.totalUsage};return}let U=Be(S,I);if(U.level==="blocking"){U.reason==="prompt_too_long"&&H(N)&&(N.attemptedThisTurn=!0,S.hasAttemptedReactiveCompact=!0,o.info(`token budget blocking (${U.reason}), reactive compact needed`),yield{type:"recovery",turnId:r,action:"reactive_compact",detail:"token budget pre-check"}),o.info(`token budget blocking (${U.reason}), ending tool loop`);break}U.level==="warning"&&o.info(`token budget warning: ${U.usagePercent}% used, ${U.remainingTokens} remaining`);let A;{let i=await Pt(M,c.contentReplacementState,a);A=i.messages,i.newlyReplacedCount>0&&(o.info(`tool-result-budget: persisted ${i.newlyReplacedCount} oversized tool results`),yield{type:"recovery",turnId:r,action:"tool_result_budget",detail:`${i.newlyReplacedCount} persisted`})}{let i=Re(A,c.snipRemovedIds);A=i.messages,i.removedCount>0&&(o.info(`snip: removed ${i.removedCount} messages, freed ~${i.tokensFreed} tokens`),yield{type:"recovery",turnId:r,action:"snip",detail:`${i.removedCount} messages`})}{let u=new G().compress(A,0);u.droppedCount>0&&(A=u.messages,o.info(`microcompact: cleared ${u.droppedCount} old tool results`))}if(A=ve(A,ge).messages,S.promptTokens>0){let i=Nt(A,{budget:I.contextWindowTokens*.75,model:c.currentModel});i.droppedCount>0&&(A=i.messages,o.info(`autocompact: ${i.strategy}, dropped ${i.droppedCount}`),yield{type:"recovery",turnId:r,action:"autocompact",detail:`${i.strategy}: ${i.droppedCount} dropped`},c.hasAttemptedReactiveCompact=!1,m?.invoke("context.after_compact",{...y,removedCount:i.droppedCount}).catch(()=>{}))}A=wn(A);let ie=Ae({tools:re,toolChoice:e.toolChoice??"auto"}),Y=de({maxRounds:v,replayMessages:A,lastStopReason:L.lastStopReason,options:{stopReason:L.lastStopReason}}),Ke=ie.extraSystemPrompt?[{role:"system",content:ie.extraSystemPrompt},...Y.state.replayMessages]:Y.state.replayMessages;L=Y.state,Y.recoveryActions.length>0&&o.debug(`tool loop recovery: ${Y.recoveryActions.map(i=>i.detail??i.kind).join("; ")}`),o.debug(`turn ${X}, messages: ${Ke.length}`),m?.invoke("turn.before_inference",{...y,model:c.currentModel}).catch(()=>{});let ae=!1,Xe=[],Ye=new Map,Je="stop",O,f=null,le=!1,fe=[],F=[];try{for await(let i of t.stream({model:c.currentModel,messages:Ke,tools:ie.tools,toolChoice:ie.normalizedToolChoice??"auto",temperature:d,maxTokens:(We??S.currentMaxOutputTokens)||void 0},g,_))switch(i.type){case"delta":Xe.push(i.text),ae||(yield{type:"delta",turnId:r,text:i.text});break;case"tool_call_delta":ae=!0,mt(Ye,i);break;case"reasoning_delta":fe.push(i.text);break;case"reasoning_block_complete":F.push({thinking:fe.join(""),signature:i.signature}),fe.length=0;break;case"usage":O={prompt:i.promptTokens,completion:i.completionTokens,reasoning:i.reasoningTokens,cacheRead:i.cacheReadTokens,cacheCreation:i.cacheCreationTokens};break;case"done":Je=i.finishReason;break}if(ae||m?.invoke("turn.after_inference",{...y,model:c.currentModel}).catch(()=>{}),e.postSamplingHooks&&e.postSamplingHooks.length>0){let i=c.currentModel;for(let u of e.postSamplingHooks)try{u({messages:[...A],model:i,sessionId:a})}catch{}}}catch(i){if(i instanceof oe&&e.fallbackModel){o.info(`model fallback triggered: ${i.originalModel} \u2192 ${i.fallbackModel}`),yield{type:"recovery",turnId:r,action:"model_fallback",detail:`${i.originalModel} \u2192 ${i.fallbackModel}`},c={...c,currentModel:i.fallbackModel,consecutive529Errors:0,consecutiveApiRetries:0,transition:void 0};continue}let u=i instanceof Error?i.message:String(i),T=typeof i?.status=="number"?i.status:void 0;if(!T&&u&&(u.includes("ECONNRESET")||u.includes("EPIPE"))){let E=(c.consecutiveApiRetries??0)+1;if(E>ne){o.info(`stale connection retry limit reached (${ne}), aborting`),yield{type:"error",turnId:r,error:u,code:"RETRIES_EXHAUSTED",usage:c.totalUsage};return}o.info(`stale connection (${u.includes("ECONNRESET")?"ECONNRESET":"EPIPE"}): retrying`),yield{type:"recovery",turnId:r,action:"stale_connection_retry",detail:u.slice(0,80)},c={...c,consecutiveApiRetries:E,transition:void 0};continue}let x=Mn({status:T,message:u});if(x!==null){o.info(`max_tokens overflow: adjusting to ${x}`),S.currentMaxOutputTokens=x,c={...c,maxOutputTokensOverride:x,transition:void 0};continue}if(Pe(T)){if(c.consecutive529Errors++,c.consecutive529Errors>=Rt&&e.fallbackModel&&c.currentModel!==e.fallbackModel){o.info(`529 \xD7 ${c.consecutive529Errors}: triggering fallback to ${e.fallbackModel}`),yield{type:"recovery",turnId:r,action:"model_fallback",detail:`529 \xD7 ${c.consecutive529Errors}`},c={...c,currentModel:e.fallbackModel,consecutive529Errors:0,transition:void 0};continue}if(Ne()){let E=pe(c.consecutive529Errors);o.info(`persistent retry: waiting ${E}ms (attempt ${c.consecutive529Errors})`);let k=E;for(;k>0;){if(_?.aborted){yield{type:"error",turnId:r,error:"Aborted during retry wait",code:"ABORTED",usage:c.totalUsage};return}yield{type:"heartbeat",turnId:r,message:`Retrying in ${Math.ceil(k/1e3)}s (${T})`};let w=Math.min(k,_t);await new Promise(Ht=>setTimeout(Ht,w)),k-=w}c={...c,transition:void 0};continue}if(Oe(b)){let k=En({status:T,message:u})??pe(c.consecutive529Errors);o.info(`transient ${T}: retry in ${k}ms`),yield{type:"recovery",turnId:r,action:"retry",detail:`${T} retry in ${k}ms`},await new Promise(w=>setTimeout(w,k)),c={...c,transition:void 0};continue}o.info(`background source ${b}: not retrying ${T}`)}f={status:T,message:u}}if(f&&m?.invoke("turn.after_inference",{...y,model:c.currentModel,response:{error:f.message}}).catch(()=>{}),f)if(Ut(f))le=!0,o.info(`withheld prompt_too_long error (status=${f.status})`);else if($t(f))le=!0,o.info(`withheld media_size error (status=${f.status})`);else{let i=De({status:f.status??500,message:f.message},S,I);if(i.action==="reactive_compact"&&H(N)&&(N.attemptedThisTurn=!0,S.hasAttemptedReactiveCompact=!0,yield{type:"recovery",turnId:r,action:"reactive_compact",detail:`API ${f.status??500}: ${f.message}`}),i.action==="retry"){let T=(c.consecutiveApiRetries??0)+1;if(T>ne){o.info(`API retry limit reached (${ne}), aborting`);let x=q(f.status,f.message);yield{type:"error",turnId:r,error:f.message,code:x,usage:c.totalUsage};return}yield{type:"recovery",turnId:r,action:"retry",detail:i.reason},c={...c,consecutiveApiRetries:T,transition:void 0};continue}let u=q(f.status,f.message);m?.invoke("stop.failure",{sessionId:a,reason:u,error:f.message}).catch(()=>{}),yield{type:"error",turnId:r,error:f.message,code:u,usage:c.totalUsage};return}O&&(c.totalUsage.prompt+=O.prompt,c.totalUsage.completion+=O.completion,O.reasoning&&(c.totalUsage.reasoning=(c.totalUsage.reasoning??0)+O.reasoning),O.cacheRead&&(c.totalUsage.cacheRead=(c.totalUsage.cacheRead??0)+O.cacheRead),O.cacheCreation&&(c.totalUsage.cacheCreation=(c.totalUsage.cacheCreation??0)+O.cacheCreation)),O?.prompt&&(S.promptTokens=O.prompt),c.finalText=Xe.join("");let B=[...Ye.values()].map(i=>({id:i.id||`tc_${r}_${X}_${Math.random().toString(36).slice(2,8)}`,type:"function",function:{name:i.name,arguments:i.arguments}}));if(B.length===0&&!ae){if(le&&f&&Ut(f)){if(c.transition?.reason!=="collapse_drain_retry"){let i=Se(A,ge);if(i.committed>0){o.info(`collapse drain: committed ${i.committed} stages`),yield{type:"recovery",turnId:r,action:"collapse_drain",detail:`${i.committed} stages committed`},c={...c,messages:i.messages,transition:{reason:"collapse_drain_retry",committed:i.committed}};continue}}if(H(N)){N.attemptedThisTurn=!0,S.hasAttemptedReactiveCompact=!0,o.info("withheld 413: reactive compact attempt"),yield{type:"recovery",turnId:r,action:"reactive_compact",detail:"withheld prompt_too_long"},c={...c,hasAttemptedReactiveCompact:!0,transition:{reason:"reactive_compact_retry"}};continue}o.info("withheld 413: recovery exhausted, surfacing error"),m?.invoke("stop.failure",{sessionId:a,reason:"prompt_too_long",error:f.message}).catch(()=>{}),yield{type:"error",turnId:r,error:f.message,code:"PROMPT_TOO_LONG",usage:c.totalUsage};return}if(le&&f&&$t(f)){if(H(N)){N.attemptedThisTurn=!0,S.hasAttemptedReactiveCompact=!0,o.info("withheld media error: reactive compact strip-retry"),yield{type:"recovery",turnId:r,action:"reactive_compact",detail:"media error strip-retry"},c={...c,hasAttemptedReactiveCompact:!0,transition:{reason:"reactive_compact_retry"}};continue}o.info("withheld media error: recovery exhausted"),m?.invoke("stop.failure",{sessionId:a,reason:"media_error",error:f.message}).catch(()=>{}),yield{type:"error",turnId:r,error:f.message,code:"IMAGE_ERROR",usage:c.totalUsage};return}if(An(Je)){S.consecutiveTruncations+=1;let i=e.modelMaxOutputTokens??Ct,u=Ue(S,I,i);if(u.shouldEscalate&&We===void 0){S.currentMaxOutputTokens=u.newMax,o.info(`max_output_tokens escalate: ${u.newMax} tokens`),yield{type:"recovery",turnId:r,action:"output_escalation",detail:`${u.newMax} tokens`},c={...c,maxOutputTokensOverride:kt,transition:{reason:"max_output_tokens_escalate"}};continue}if(K<bt){let T={role:"user",content:"Output token limit hit. Resume directly \u2014 no apology, no recap of what you were doing. Pick up mid-thought if that is where the cut happened. Break remaining work into smaller pieces."};o.info(`max_output_tokens recovery #${K+1}`),yield{type:"recovery",turnId:r,action:"max_output_tokens_recovery",detail:`attempt ${K+1}`},c={...c,messages:[...A,T],maxOutputTokensRecoveryCount:K+1,maxOutputTokensOverride:void 0,transition:{reason:"max_output_tokens_recovery",attempt:K+1}};continue}o.info("max_output_tokens recovery exhausted, completing with partial content")}else S.consecutiveTruncations=0;if(L=ue(L,{replayMessages:M,lastStopReason:"completed"}),m){let i=await m.invoke("stop",{sessionId:a,reason:"completed"});if(i.action==="prevent"){o.info(`stop hook prevented continuation: ${i.reason??"no reason"}`),yield{type:"end",turnId:r,content:c.finalText,usage:c.totalUsage,model:c.currentModel};return}if(i.action==="abort"){let u=i.reason??"Stop hook requested continuation";o.info(`stop hook blocking: ${u}`);let T={role:"user",content:u},x={role:"assistant",content:c.finalText,...F.length>0&&{thinkingBlocks:[...F]}};c={...c,messages:[...M,x,T],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}};continue}}if(e.tokenBudget&&e.tokenBudget>0){let i=c.totalUsage.prompt+c.totalUsage.completion+(c.totalUsage.reasoning??0),u=i/e.tokenBudget*100;if(u<90){let T={role:"user",content:Ft(u,i,e.tokenBudget)};o.info(`token budget continuation: ${Math.round(u)}% used`),yield{type:"recovery",turnId:r,action:"budget_continuation",detail:`${Math.round(u)}% used`};let x={role:"assistant",content:c.finalText,...F.length>0&&{thinkingBlocks:[...F]}};c={...c,messages:[...M,x,T],transition:{reason:"token_budget_continuation"}};continue}}if(D>0){let i={ok:!0,toolCallCount:D,distinctToolCount:W.size,multiStep:D>=2,hasSubAgent:!1,feedback:null,existingSkillName:null},u=ce(i,{tools:[...W]});u&&(yield{type:"skill_instruction",turnId:r,instruction:u})}yield{type:"end",turnId:r,content:c.finalText,usage:c.totalUsage,model:c.currentModel};return}for(let i of B){let u=i.function.arguments,T=re.find(x=>x.function.name===i.function.name);if(T?.backfillObservableInput)try{let x=JSON.parse(i.function.arguments),E={...x};T.backfillObservableInput(E),Object.keys(E).some(w=>!(w in x))&&(u=JSON.stringify(E))}catch{}yield{type:"tool_call",turnId:r,callId:i.id,name:i.function.name,arguments:u}}M.push(he(B,c.finalText||void 0,F.length>0?F:void 0)),L=Le(L,{replayMessages:M,pendingToolCallIds:B.map(i=>i.id),completedToolCallIds:L.completedToolCallIds,lastStopReason:"tool_calls"});let Ve=[];try{let i=new me({toolInvoker:n,hooks:m,sessionId:a,turnId:r,log:o,signal:_,maxConcurrentTools:e?.maxConcurrentTools});for(let u of B)i.addTool(u);for await(let u of i.getRemainingResults()){u.blocked&&(yield{type:"tool_blocked",turnId:r,callId:u.callId,name:u.toolName,reason:u.blockReason??"blocked"}),M.push(u.message),Ve.push(u.callId),W.add(u.toolName),D++;let T=typeof u.message?.content=="string"?u.message.content:"",x=u.ok&&T?T.slice(0,2e3):void 0;if(yield{type:"tool_result",turnId:r,callId:u.callId,name:u.toolName,ok:u.ok,error:u.error,outputPreview:x},u.ok){let E=B.find(k=>k.id===u.callId);if(E){if(u.toolName==="plan_mode")try{let k=JSON.parse(E.function.arguments);k.action==="exit"&&typeof k.plan=="string"&&k.plan.length>0&&(yield{type:"plan_update",turnId:r,slug:"approved-plan",content:k.plan})}catch{}if(Rn.has(u.toolName))try{let k=JSON.parse(E.function.arguments),w=typeof k.file_path=="string"?k.file_path:typeof k.filePath=="string"?k.filePath:typeof k.path=="string"?k.path:void 0;w&&(yield{type:"artifact",turnId:r,artifactId:`artifact-${u.callId}`,artifactType:xn(w),title:w.split(/[\\/]/).pop()||w,filePath:w,language:vn(w)})}catch{}}}}}catch(i){let u=i instanceof Error?i.message:String(i);yield{type:"error",turnId:r,error:u,code:"TOOL_EXECUTION_ERROR",usage:c.totalUsage};return}if(L=ue(L,{replayMessages:M,completedToolCallIds:[...L.completedToolCallIds,...Ve],lastStopReason:"tool_calls"}),e.generateToolUseSummary&&B.length>0){let i=B.map(u=>({name:u.function.name,arguments:u.function.arguments}));se=e.generateToolUseSummary(i).catch(()=>null)}let Qe=M.slice(-B.length),qt=Qe.length>0&&Qe.every(i=>{let u=i?.content;return typeof u!="string"?!1:u.startsWith("Error: ")}),J=c.consecutiveFailedRounds;if(qt){if(J+=1,J>=ft&&c.finalText){o.info(`early exit: ${J} consecutive failed rounds, returning partial response`),yield{type:"end",turnId:r,content:c.finalText,usage:c.totalUsage,model:c.currentModel};return}}else J=0;let ye=X+1;if(R>0&&ye>R){if(o.info(`max turns reached (${R}), completing`),m){let i=await m.invoke("stop",{sessionId:a,reason:"max_turns"});if(i.action==="abort"){let u=i.reason??"Stop hook requested continuation after max_turns",T={role:"assistant",content:c.finalText,...F.length>0&&{thinkingBlocks:[...F]}};c={...c,messages:[...M,T,{role:"user",content:u}],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}};continue}}yield{type:"end",turnId:r,content:c.finalText,usage:c.totalUsage,model:c.currentModel};return}if(ye>v){if(o.info(`tool loop budget exhausted (${v} rounds), returning`),D>0){let i={ok:!0,toolCallCount:D,distinctToolCount:W.size,multiStep:D>=2,hasSubAgent:!1,feedback:null,existingSkillName:null},u=ce(i,{tools:[...W]});u&&(yield{type:"skill_instruction",turnId:r,instruction:u})}yield{type:"end",turnId:r,content:c.finalText,usage:c.totalUsage,model:c.currentModel};return}c={messages:M,maxOutputTokensRecoveryCount:0,hasAttemptedReactiveCompact:!1,maxOutputTokensOverride:void 0,turnCount:ye,transition:{reason:"next_turn"},guardState:S,reactiveCompactState:N,toolLoopState:L,consecutiveFailedRounds:J,finalText:c.finalText,totalUsage:c.totalUsage,collapseStore:ge,currentModel:c.currentModel,consecutive529Errors:0,consecutiveApiRetries:0,stopHookActive:c.stopHookActive,snipRemovedIds:c.snipRemovedIds,contentReplacementState:c.contentReplacementState}}}async function*In(e,t,n,o,r,a,l,s){let p=[],g;s.debug(`single LLM round, messages: ${n.length}`);for await(let d of l.stream({model:t,messages:n,temperature:r},o,a))switch(d.type){case"delta":p.push(d.text),yield{type:"delta",turnId:e,text:d.text};break;case"usage":g={prompt:d.promptTokens,completion:d.completionTokens,reasoning:d.reasoningTokens,cacheRead:d.cacheReadTokens,cacheCreation:d.cacheCreationTokens};break;case"done":break}yield{type:"end",turnId:e,content:p.join(""),usage:g??{prompt:0,completion:0},model:t}}var Gt=class{transport;apiKey;toolInvoker;log;hooks;maxRounds;constructor(t){this.transport=t.llmTransport,this.apiKey=t.apiKey,this.toolInvoker=t.toolInvoker,this.log=t.log,this.hooks=t.hooks,this.maxRounds=Math.min(t.maxRounds??25,100)}async*run(t,n){let{turnId:o,messages:r,tools:a,systemPrompt:l,config:s}=t,p={sessionId:t.sessionId,turnId:o};yield{type:"start",turnId:o},this.hooks?.invoke("turn.submitted",{...p,prompt:r[r.length-1]?.content??void 0}).catch(()=>{});let g=Ie(r),d=[];if(l&&d.push({role:"system",content:l}),d.push(...g),this.hooks){let y=g.filter(b=>b.role==="user").pop(),R=typeof y?.content=="string"?y.content.slice(0,500):void 0;if(R)try{let b=await this.hooks.invoke("memory.before_recall",{sessionId:t.sessionId,turnId:o,query:R}),C=b?.context?.recalledMemories;if(C&&C.length>0){let P=C.map(h=>`- ${h.text}`).join(`
|
|
17
|
+
`);d.splice(l?1:0,0,{role:"system",content:`[Recalled from long-term memory]
|
|
18
|
+
${P}`})}this.hooks.invoke("memory.after_recall",{sessionId:t.sessionId,turnId:o,blockCount:b?.context?.recalledMemories?.length??0}).catch(()=>{})}catch{}}let m=s?.model??"",_=Math.min(s?.maxRounds??this.maxRounds,100);try{let y=s?.summaryModel?async C=>{try{let P=C.map(I=>`${I.name}(${I.arguments.slice(0,200)})`).join(", "),h=this.transport.stream({model:s.summaryModel,messages:[{role:"system",content:"Summarize the tool usage in ~30 chars, git-commit-subject style. Reply with ONLY the summary, nothing else."},{role:"user",content:P}],tools:[],maxTokens:60},s.apiKey??this.apiKey),v="";for await(let I of h)I.type==="delta"&&(v+=I.text);return v.trim()||null}catch{return null}}:void 0,R={turnId:o,sessionId:t.sessionId,messages:d,tools:a,model:m,apiKey:s?.apiKey??this.apiKey,temperature:s?.temperature,maxRounds:_,contextWindowTokens:s?.contextWindowTokens,maxOutputTokens:s?.maxOutputTokens,modelMaxOutputTokens:s?.modelMaxOutputTokens,toolChoice:s?.toolChoice,parentDepth:s?.parentDepth,hooks:this.hooks,fallbackModel:s?.fallbackModel,maxTurns:s?.maxTurns,tokenBudget:s?.tokenBudget,maxConcurrentTools:s?.maxConcurrentTools,generateToolUseSummary:y,signal:n},b;for await(let C of jt(R,this.transport,this.toolInvoker,this.log))b=C,yield C;b?.type==="end"?this.hooks?.invoke("turn.completed",{...p}).catch(()=>{}):b?.type==="error"&&this.hooks?.invoke("turn.failed",{...p,code:b.code,error:b.error}).catch(()=>{})}catch(y){if(n?.aborted)this.hooks?.invoke("turn.failed",{...p,code:"ABORTED",error:"Turn aborted"}).catch(()=>{}),yield{type:"error",turnId:o,error:"Turn aborted",code:"ABORTED"};else{let R=y instanceof Error?y.message:String(y),b=typeof y?.status=="number"?y.status:void 0,C=q(b,R);this.log.error(`turn ${o} error [${C}, retryable=${Ce(C)}]: ${R}`),this.hooks?.invoke("turn.failed",{...p,code:C,error:R}).catch(()=>{}),yield{type:"error",turnId:o,error:R,code:C}}}}};export{Gt as Agent};
|