qlogicagent 1.0.0 → 1.1.0
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 +7 -7
- package/dist/cli.js +204 -195
- package/dist/index.js +204 -195
- package/dist/orchestration.js +10 -10
- package/dist/types/agent/tool-loop.d.ts +2 -0
- package/dist/types/agent/types.d.ts +54 -1
- package/dist/types/cli/stdio-server.d.ts +10 -0
- package/dist/types/cli/tool-bootstrap.d.ts +13 -1
- package/dist/types/llm/index.d.ts +1 -1
- package/dist/types/llm/llm-client.d.ts +1 -1
- package/dist/types/llm/media-client.d.ts +3 -4
- package/dist/types/llm/media-transport.d.ts +75 -4
- package/dist/types/llm/provider-def.d.ts +124 -3
- package/dist/types/llm/provider-registry.d.ts +5 -0
- package/dist/types/llm/provider-tool-api.d.ts +44 -0
- package/dist/types/llm/retry.d.ts +37 -0
- package/dist/types/llm/transport.d.ts +161 -2
- package/dist/types/llm/transports/anthropic-messages.d.ts +7 -0
- package/dist/types/llm/transports/minimax-media.d.ts +5 -0
- package/dist/types/llm/transports/openai-chat.d.ts +44 -3
- package/dist/types/llm/transports/realtime-transport.d.ts +183 -0
- package/dist/types/llm/transports/volcengine-grounding.d.ts +58 -0
- package/dist/types/llm/transports/volcengine-media.d.ts +50 -0
- package/dist/types/llm/transports/volcengine-responses.d.ts +60 -0
- package/dist/types/llm/transports/zhipu-media.d.ts +60 -0
- package/dist/types/llm/transports/zhipu-tool-api.d.ts +35 -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-cascade.d.ts +40 -0
- package/dist/types/orchestration/tool-loop/tool-schema.d.ts +4 -1
- package/dist/types/protocol/methods.d.ts +19 -0
- package/dist/types/skills/memory/memory-extractor.d.ts +1 -1
- package/dist/types/skills/tools/file-management-tool.d.ts +90 -0
- package/dist/types/skills/tools/image-generate-tool.d.ts +13 -1
- package/dist/types/skills/tools/music-generate-tool.d.ts +25 -0
- package/dist/types/skills/tools/stt-tool.d.ts +33 -0
- package/dist/types/skills/tools/three-d-generate-tool.d.ts +45 -0
- package/dist/types/skills/tools/tts-tool.d.ts +12 -0
- package/dist/types/skills/tools/video-edit-tool.d.ts +5 -2
- package/dist/types/skills/tools/video-generate-tool.d.ts +102 -2
- package/dist/types/skills/tools/video-merge-tool.d.ts +1 -1
- package/dist/types/skills/tools/video-upscale-tool.d.ts +1 -1
- package/dist/types/skills/tools/voice-clone-tool.d.ts +40 -0
- package/package.json +1 -1
package/dist/agent.js
CHANGED
|
@@ -1,18 +1,18 @@
|
|
|
1
|
-
var qt=Object.defineProperty;var Ht=(e,t)=>()=>(e&&(t=e(e=0)),t);var Wt=(e,t)=>{for(var n in t)qt(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 hn(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 Tn(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=[],a=[];for(let l of e){let s=l.function.name,{level:p,reasons:g}=hn(l,t),d=Tn(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 fn,Ft=Ht(()=>{"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,t){return{role:"assistant",content:t||null,tool_calls:e}}function J(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 Kt=/\b(?:daily|weekly|monthly)(?:\/(?:daily|weekly|monthly))* (?:usage )?limit(?:s)?(?: (?:exhausted|reached|exceeded))?\b/i,U={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]},Yt=/^(?:error[:\s-]+)?billing(?:\s+error)?(?:[:\s-]+|$)|^(?:error[:\s-]+)?(?:credit balance|insufficient credits?|payment required|http\s*402\b)/i,Xt=/["']?(?: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 j(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 j(e,U.format)}function Ve(e){return j(e,U.rateLimit)}function co(e){return j(e,U.timeout)}function uo(e){return Kt.test(e)}function ye(e){let t=e.toLowerCase();return t?e.length>Jt?Xt.test(t):j(t,U.billing)?!0:Yt.test(e)?t.includes("upgrade")||t.includes("credits")||t.includes("payment")||t.includes("plan"):!1:!1}function Qe(e){return j(e,U.authPermanent)}function po(e){return j(e,U.auth)}function Ze(e){return j(e,U.overloaded)}function $(e,t){return t.some(n=>e.includes(n))}function mo(e){return $(e,Zt)||$(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=$(e,to),n=e.includes("spend limit")||e.includes("spending limit"),o=$(e,ro);return $(e,oo)&&$(e,no)||t&&(e.includes("usage limit")||n)||t&&e.includes("limit")&&e.includes("reset")||o&&e.includes("limit")&&(n||$(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 ho(e){if(!e)return!1;let t=e.toLowerCase();return t.includes('"type":"api_error"')&&t.includes("internal server error")}function To(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":To(e)?tt(e.trim())?.code===529?"overloaded":"timeout":ho(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"},Ro={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 he(e){return Ro[e]}var rt=4,V=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 R=this.estimateTokens(m);if(a-R<0&&p>=rt)break;if(a-R<0&&p<rt){s.unshift(m),p++;continue}a-=R,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 Q=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:_o(a.content,this.maxToolResultChars)})),droppedCount:o,strategy:"tool-result-trim"}}};function _o(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(`}
|
|
1
|
+
var Kt=Object.defineProperty;var Xt=(e,t)=>()=>(e&&(t=e(e=0)),t);var Yt=(e,t)=>{for(var n in t)Kt(e,n,{get:t[n],enumerable:!0})};var Bt={};Yt(Bt,{resolveToolEligibility:()=>_n});function Cn(e,t){if(Tn.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 bn(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||Cn(n,t.dangerousPatterns)?(r.push("dangerous_tool"),{level:3,reasons:r}):{level:2,reasons:r}}function kn(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 _n(e,t={}){let n=new Map,o=[],r=[],a=[];for(let l of e){let s=l.function.name,{level:p,reasons:g}=bn(l,t),d=kn(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 Tn,Dt=Xt(()=>{"use strict";Tn=[/^(?: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,o){return{role:"assistant",content:t||null,tool_calls:e,...n&&n.length>0?{thinkingBlocks:n}:{},...o?{reasoning_content:o}:{}}}function Q(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 Jt=/\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]},Vt=/^(?:error[:\s-]+)?billing(?:\s+error)?(?:[:\s-]+|$)|^(?:error[:\s-]+)?(?:credit balance|insufficient credits?|payment required|http\s*402\b)/i,Qt=/["']?(?:status|code)["']?\s*[:=]\s*402\b|\bhttp\s*402\b|\berror(?:\s+code)?\s*[:=]?\s*402\b|^\s*402\s+payment/i,Zt=512,eo=/^(?:http\s*)?(\d{3})(?:\s+([\s\S]+))?$/i;var to=new Set([500,502,503,504,521,522,523,524,529]),oo=["insufficient credits","insufficient quota","credit balance","insufficient balance","plans & billing","add more credits","top up"],no=["upgrade your plan","upgrade plan","current plan","subscription"],ro=["daily","weekly","monthly"],so=["try again","retry","temporary","cooldown"],io=["usage limit","rate limit","organization usage"],ao=["organization","workspace"],lo=["billing period","exceeded","reached","exhausted"],co=/["']?(?: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,uo=/^(?: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 po(e){return z(e,j.format)}function Ze(e){return z(e,j.rateLimit)}function mo(e){return z(e,j.timeout)}function go(e){return Jt.test(e)}function Te(e){let t=e.toLowerCase();return t?e.length>Zt?Qt.test(t):z(t,j.billing)?!0:Vt.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 fo(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 yo(e){return $(e,oo)||$(e,no)&&e.includes("limit")||e.includes("billing hard limit")||e.includes("hard limit reached")||e.includes("maximum allowed")&&e.includes("limit")}function ho(e){let t=$(e,ro),n=e.includes("spend limit")||e.includes("spending limit"),o=$(e,ao);return $(e,so)&&$(e,io)||t&&(e.includes("usage limit")||n)||t&&e.includes("limit")&&e.includes("reset")||o&&e.includes("limit")&&(n||$(e,lo))}function To(e){return e.trim().toLowerCase().replace(uo,"").trim()}function ot(e){let t=To(e);return!t||yo(t)?"billing":Ze(t)||ho(t)?"rate_limit":"billing"}function Co(e){return co.test(e)?ot(e):null}function nt(e){let t=e.match(eo);if(!t)return null;let n=Number(t[1]);return Number.isFinite(n)?{code:n,rest:(t[2]??"").trim()}:null}function bo(e){if(!e)return!1;let t=e.toLowerCase();return t.includes('"type":"api_error"')&&t.includes("internal server error")}function ko(e){let t=e.trim();if(!t)return!1;let n=nt(t);return n?to.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 _o(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 Ro(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(Ro(e))return"session_expired";if(_o(e))return"model_not_found";let t=Co(e);return t||(go(e)?Te(e)?"billing":"rate_limit":Ze(e)?"rate_limit":tt(e)?"overloaded":ko(e)?nt(e.trim())?.code===529?"overloaded":"timeout":bo(e)?"timeout":po(e)?"format":Te(e)?"billing":mo(e)?"timeout":et(e)?"auth_permanent":fo(e)?"auth":null)}var xo={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"},vo=new Set(["RETRYABLE_TRANSIENT","RETRYABLE_DEGRADED","TOOL_EXECUTION_FAILED"]);function G(e,t){let n=rt(e,t)??(t?st(t):null);return n?xo[n]:typeof e=="number"&&e>=400&&e<500?"NON_RETRYABLE_CONTENT":"RETRYABLE_TRANSIENT"}function Ce(e){return vo.has(e)}var it=4,Z=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 ee=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:So(a.content,this.maxToolResultChars)})),droppedCount:o,strategy:"tool-result-trim"}}};function So(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
3
|
`));if(a>t*.5)return n.slice(0,a+1)+`
|
|
4
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 Te(...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 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,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}},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"]),z=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,a=0;return{messages:t.map((s,p)=>{if(p>=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 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 ke(e,t,n=it){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 Re(){return{stages:[]}}function _e(e,t,n){let o=n?.thresholdMessages??40;if(e.filter(s=>s.role!=="system").length<=o)return{messages:e,stagedCount:0};let a=at(e,t),l=vo(a,t,o);if(l.length===0)return{messages:a,stagedCount:0};for(let s of l)t.stages.push(s);return a=at(e,t),{messages:a,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,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 vo(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 So(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"}:So(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 ve(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 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=>ct(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 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 Se(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=>No(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]=Po(p,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??"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 Me(e,t){let n=Se(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=Se(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((a,l)=>a!==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 Hn={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 q(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 Xo,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,ht=65536,Tt=3,Ct=65536,bt=3e4,kt=3,oe=5,Rt=5e4,_t=2e5,Ue=2e3;var Qo="tool-results",vt="<persisted-output>",Zo="</persisted-output>";function St(){return{seenIds:new Set,replacements:new Map}}function At(e){return xt(Vo(),"qlogicagent-sessions",e,Qo)}async function en(e){try{await Xo(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 te=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}},oe=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 Ao=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"]),q=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||!Ao.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=Eo(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 Eo(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 Mo(e){return!(!e.ok||e.existingSkillName||!e.multiStep||e.toolCallCount<3||e.distinctToolCount<2)}function wo(e){return e.existingSkillName?e.feedback==="negative":!1}function ue(e,t){return wo(e)?{type:"skill.improve",skillName:e.existingSkillName,reason:"negative user feedback on existing skill execution"}:Mo(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 Io(e){return e==="enabled-eligible"||e==="installed-awaiting-approval"}function Lo(e){return new Map((e??[]).map(t=>[t.toolName,t]))}function Oo(e){if(!e.eligibility?.length)return[...e.tools];let t=Lo(e.eligibility);return e.tools.filter(n=>{let o=dt(n);if(!o)return!1;let r=t.get(o);return!r||Io(r.status)})}function Po(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=Po({toolChoice:e.toolChoice,thinkingEnabled:e.thinkingEnabled,compatibility:e.compatibility}),n=t.normalizedToolChoice,o=[...t.warnings],r=Oo({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 No=["stop","aborted","timeout","cancelled","interrupted","error"],Fo=["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 Bo(e,t){return{...e,content:[...pt(e.content),...pt(t.content)]}}function Do(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 Uo(e){return new Set((e??No).map(t=>t.trim().toLowerCase()))}function $o(e,t){return e?Uo(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=>Do(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]=Bo(p,s);continue}l.push(s)}return l}function Me(e,t){return $o(t?.stopReason,t?.forcedStopReasons)?e.map(n=>{if(n.role!=="assistant")return{...n};let o={...n};for(let r of Fo)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 jo(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 zo(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 qo(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 de(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 pe(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:qo({maxRounds:e.maxRounds,round:e.round,lastStopReason:e.lastStopReason,replayMessages:r,pendingToolCallIds:jo(r),completedToolCallIds:zo(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 me(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 Xn={maxBackoffMs:300*1e3,resetCapMs:360*60*1e3,heartbeatIntervalMs:3e4};function Ne(){let e=process.env.QLOGICAGENT_PERSISTENT_RETRY;return e==="1"||e==="true"}var ne=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 Ho={maxConsecutiveFailures:3,minMessagesAfterCompact:4,targetUsagePercent:50};function je(){return{consecutiveFailures:0,attemptedThisTurn:!1,lastCompactAt:null,toolsAtLastCompact:[]}}function H(e,t=Ho){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 Qo,writeFile as Zo}from"fs/promises";import{join as St}from"path";import{tmpdir as en}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,re=5,xt=5e4,vt=2e5,ze=2e3;var tn="tool-results",At="<persisted-output>",on="</persisted-output>";function Et(){return{seenIds:new Set,replacements:new Map}}function Mt(e){return St(en(),"qlogicagent-sessions",e,tn)}async function nn(e){try{await Qo(Mt(e),{recursive:!0})}catch{}}function rn(e,t){let n=t.replace(/[^a-zA-Z0-9_-]/g,"_");return St(Mt(e),`${n}.txt`)}function sn(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 nn(n);let o=rn(n,t);try{await Zo(o,e,{encoding:"utf-8",flag:"wx"})}catch(l){if(l.code!=="EEXIST")return null}let{preview:r,hasMore:a}=sn(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 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 sn(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 Lt(e,t,n,o=_t){let r=nn(e);if(r.length===0)return{messages:e,newlyReplacedCount:0};let a=new Map,l=[];for(let d of r){let{mustReapply:m,frozen:R,fresh:y}=rn(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,x)=>h+x.size,0),C=y.reduce((h,x)=>h+x.size,0),T=_+C>o?sn(y,_,o):[],I=new Set(T.map(h=>h.toolCallId));for(let h of d)I.has(h.toolCallId)||t.seenIds.add(h.toolCallId);T.length>0&&l.push(...T)}if(a.size===0&&l.length===0)return{messages:e,newlyReplacedCount:0};let s=await Promise.all(l.map(async d=>{let m=await Mt(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 R=wt(m);a.set(d.toolCallId,R),t.replacements.set(d.toolCallId,R),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 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:a,hooks:l,sessionId:s,turnId:p,log:g}=this.config,d=t.toolCall.function.name,m=!1,R=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:cn(R)});if(h.action==="abort"){let x=h.reason??"blocked by policy";g.info(`tool ${d} blocked: ${x}`),t.results.push({callId:t.id,toolName:d,ok:!1,error:x,blocked:!0,blockReason:x,message:J(t.id,{ok:!1,error:x})}),t.status="completed";return}h.action==="continue"&&h.context?.arguments&&(R=JSON.stringify(h.context.arguments))}catch{}let y=await a.invoke(p,d,R,this.siblingAbortController.signal),_=this.getAbortReason();if(_&&!m){t.results.push(this.createSyntheticError(t,_)),t.status="completed";return}let C=!y.error,T=y.result;C&&T&&T.length>5e4&&(T=await It(T,t.id,s));let I=J(t.id,{ok:C,payload:T,error:y.error});C||(m=!0,ln.has(d)&&(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:p,callId:t.id,toolName:d,ok:C,...y.error?{error:y.error}:{}}).catch(()=>{}),t.results.push({callId:t.id,toolName:d,ok:C,error:y.error,message:I}),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 Hr}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 Wr=new ee;function mn(){return Te(new Q(dn),new z(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 a=je(e),l=je(r.messages);pn.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:be(a,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.")}var kn=new Set(["write","edit","patch","apply_patch"]);function Rn(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 _n(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 xn(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 vn(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 Sn(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 An(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 En(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:a,messages:l,tools:s,model:p,apiKey:g,temperature:d,hooks:m,signal:R}=e,y={sessionId:a,turnId:r},_=e.maxTurns??0,C=e.querySource,{resolveToolEligibility:T}=await Promise.resolve().then(()=>(Ft(),Nt)),I=T(s,e.toolEligibilityContext),h=I.eligibleTools;for(let E of I.blockedTools)yield{type:"tool_blocked",turnId:r,callId:"",name:E.toolName,reason:"blocked-by-policy"};if(!h.length){yield*Mn(r,p,l,g,d,R,t,o);return}let x=xn(e.maxRounds),L={contextWindowTokens:e.contextWindowTokens??gt,responseBufferTokens:ft,maxOutputTokens:e.maxOutputTokens??yt,abortSignal:R,reactiveCompactEnabled:!0,outputEscalationEnabled:!0},H=new Set,D=0,ne=h,re,c={messages:[...l],maxOutputTokensRecoveryCount:0,hasAttemptedReactiveCompact:!1,maxOutputTokensOverride:void 0,turnCount:1,transition:void 0,guardState:Pe(L),reactiveCompactState:$e(),toolLoopState:ue({maxRounds:x,replayMessages:[...l]}).state,consecutiveFailedRounds:0,finalText:"",totalUsage:{prompt:0,completion:0},collapseStore:Re(),currentModel:p,consecutive529Errors:0,consecutiveApiRetries:0,stopHookActive:void 0,snipRemovedIds:new Set,contentReplacementState:St()};for(;;){let{messages:E,maxOutputTokensRecoveryCount:W,hasAttemptedReactiveCompact:In,maxOutputTokensOverride:qe,turnCount:K,guardState:v,reactiveCompactState:N,collapseStore:me}=c,{toolLoopState:O}=c;if(re){try{let i=await re;i&&(yield{type:"tool_use_summary",turnId:r,summary:i})}catch{}re=void 0}if(e.refreshTools&&K>1){let i=e.refreshTools();i!==ne&&(ne=i,o.debug(`tools refreshed: ${i.length} tools`))}if(Be(v,L)){o.info(`turn aborted by guard at turn ${K}`),yield{type:"error",turnId:r,error:"Turn aborted",code:"ABORTED"};return}let B=Ne(v,L);if(B.level==="blocking"){B.reason==="prompt_too_long"&&q(N)&&(N.attemptedThisTurn=!0,v.hasAttemptedReactiveCompact=!0,o.info(`token budget blocking (${B.reason}), reactive compact needed`),yield{type:"recovery",turnId:r,action:"reactive_compact",detail:"token budget pre-check"}),o.info(`token budget blocking (${B.reason}), ending tool loop`);break}B.level==="warning"&&o.info(`token budget warning: ${B.usagePercent}% used, ${B.remainingTokens} remaining`);let S;{let i=await Lt(E,c.contentReplacementState,a);S=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=ke(S,c.snipRemovedIds);S=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 z().compress(S,0);u.droppedCount>0&&(S=u.messages,o.info(`microcompact: cleared ${u.droppedCount} old tool results`))}if(S=_e(S,me).messages,v.promptTokens>0){let i=Ot(S,{budget:L.contextWindowTokens*.75,model:c.currentModel});i.droppedCount>0&&(S=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(()=>{}))}S=En(S);let se=ve({tools:ne,toolChoice:e.toolChoice??"auto"}),Y=ue({maxRounds:x,replayMessages:S,lastStopReason:O.lastStopReason,options:{stopReason:O.lastStopReason}}),He=se.extraSystemPrompt?[{role:"system",content:se.extraSystemPrompt},...Y.state.replayMessages]:Y.state.replayMessages;O=Y.state,Y.recoveryActions.length>0&&o.debug(`tool loop recovery: ${Y.recoveryActions.map(i=>i.detail??i.kind).join("; ")}`),o.debug(`turn ${K}, messages: ${He.length}`),m?.invoke("turn.before_inference",{...y,model:c.currentModel}).catch(()=>{});let ie=!1,We=[],Ke=new Map,Ye="stop",P,f=null,ae=!1;try{for await(let i of t.stream({model:c.currentModel,messages:He,tools:se.tools,toolChoice:se.normalizedToolChoice??"auto",temperature:d,maxTokens:(qe??v.currentMaxOutputTokens)||void 0},g,R))switch(i.type){case"delta":We.push(i.text),ie||(yield{type:"delta",turnId:r,text:i.text});break;case"tool_call_delta":ie=!0,dt(Ke,i);break;case"reasoning_delta":break;case"usage":P={prompt:i.promptTokens,completion:i.completionTokens,reasoning:i.reasoningTokens,cacheRead:i.cacheReadTokens,cacheCreation:i.cacheCreationTokens};break;case"done":Ye=i.finishReason;break}if(ie||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:[...S],model:i,sessionId:a})}catch{}}}catch(i){if(i instanceof te&&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),b=typeof i?.status=="number"?i.status:void 0;if(!b&&u&&(u.includes("ECONNRESET")||u.includes("EPIPE"))){let A=(c.consecutiveApiRetries??0)+1;if(A>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:A,transition:void 0};continue}let M=An({status:b,message:u});if(M!==null){o.info(`max_tokens overflow: adjusting to ${M}`),v.currentMaxOutputTokens=M,c={...c,maxOutputTokensOverride:M,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 A=de(c.consecutive529Errors);o.info(`persistent retry: waiting ${A}ms (attempt ${c.consecutive529Errors})`);let k=A;for(;k>0;){if(R?.aborted){yield{type:"error",turnId:r,error:"Aborted during retry wait",code:"ABORTED"};return}yield{type:"heartbeat",turnId:r,message:`Retrying in ${Math.ceil(k/1e3)}s (${b})`};let w=Math.min(k,bt);await new Promise(Gt=>setTimeout(Gt,w)),k-=w}c={...c,transition:void 0};continue}if(Ie(C)){let k=Sn({status:b,message:u})??de(c.consecutive529Errors);o.info(`transient ${b}: retry in ${k}ms`),yield{type:"recovery",turnId:r,action:"retry",detail:`${b} retry in ${k}ms`},await new Promise(w=>setTimeout(w,k)),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 i=Fe({status:f.status??500,message:f.message},v,L);if(i.action==="reactive_compact"&&q(N)&&(N.attemptedThisTurn=!0,v.hasAttemptedReactiveCompact=!0,yield{type:"recovery",turnId:r,action:"reactive_compact",detail:`API ${f.status??500}: ${f.message}`}),i.action==="retry"){let b=(c.consecutiveApiRetries??0)+1;if(b>oe){o.info(`API retry limit reached (${oe}), aborting`);let M=G(f.status,f.message);yield{type:"error",turnId:r,error:f.message,code:M};return}yield{type:"recovery",turnId:r,action:"retry",detail:i.reason},c={...c,consecutiveApiRetries:b,transition:void 0};continue}let u=G(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};return}P&&(c.totalUsage.prompt+=P.prompt,c.totalUsage.completion+=P.completion,P.reasoning&&(c.totalUsage.reasoning=(c.totalUsage.reasoning??0)+P.reasoning),P.cacheRead&&(c.totalUsage.cacheRead=(c.totalUsage.cacheRead??0)+P.cacheRead),P.cacheCreation&&(c.totalUsage.cacheCreation=(c.totalUsage.cacheCreation??0)+P.cacheCreation)),P?.prompt&&(v.promptTokens=P.prompt),c.finalText=We.join("");let F=[...Ke.values()].map(i=>({id:i.id||`tc_${r}_${K}_${Math.random().toString(36).slice(2,8)}`,type:"function",function:{name:i.name,arguments:i.arguments}}));if(F.length===0&&!ie){if(ae&&f&&Dt(f)){if(c.transition?.reason!=="collapse_drain_retry"){let i=xe(S,me);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(q(N)){N.attemptedThisTurn=!0,v.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"};return}if(ae&&f&&Bt(f)){if(q(N)){N.attemptedThisTurn=!0,v.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"};return}if(vn(Ye)){v.consecutiveTruncations+=1;let i=e.modelMaxOutputTokens??ht,u=De(v,L,i);if(u.shouldEscalate&&qe===void 0){v.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<Tt){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 v.consecutiveTruncations=0;if(O=ce(O,{replayMessages:E,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 b={role:"user",content:u};c={...c,messages:[...E,{role:"assistant",content:c.finalText},b],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 b={role:"user",content:Pt(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`},c={...c,messages:[...E,{role:"assistant",content:c.finalText},b],transition:{reason:"token_budget_continuation"}};continue}}if(D>0){let i={ok:!0,toolCallCount:D,distinctToolCount:H.size,multiStep:D>=2,hasSubAgent:!1,feedback:null,existingSkillName:null},u=le(i,{tools:[...H]});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 F){let u=i.function.arguments,b=ne.find(M=>M.function.name===i.function.name);if(b?.backfillObservableInput)try{let M=JSON.parse(i.function.arguments),A={...M};b.backfillObservableInput(A),Object.keys(A).some(w=>!(w in M))&&(u=JSON.stringify(A))}catch{}yield{type:"tool_call",turnId:r,callId:i.id,name:i.function.name,arguments:u}}E.push(fe(F,c.finalText||void 0)),O=we(O,{replayMessages:E,pendingToolCallIds:F.map(i=>i.id),completedToolCallIds:O.completedToolCallIds,lastStopReason:"tool_calls"});let Xe=[];try{let i=new pe({toolInvoker:n,hooks:m,sessionId:a,turnId:r,log:o,signal:R,maxConcurrentTools:e?.maxConcurrentTools});for(let u of F)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"}),E.push(u.message),Xe.push(u.callId),H.add(u.toolName),D++;let b=typeof u.message?.content=="string"?u.message.content:"",M=u.ok&&b?b.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:M},u.ok){let A=F.find(k=>k.id===u.callId);if(A){if(u.toolName==="plan_mode")try{let k=JSON.parse(A.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(kn.has(u.toolName))try{let k=JSON.parse(A.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:Rn(w),title:w.split(/[\\/]/).pop()||w,filePath:w,language:_n(w)})}catch{}}}}}catch(i){let u=i instanceof Error?i.message:String(i);yield{type:"error",turnId:r,error:u,code:"TOOL_EXECUTION_ERROR"};return}if(O=ce(O,{replayMessages:E,completedToolCallIds:[...O.completedToolCallIds,...Xe],lastStopReason:"tool_calls"}),e.generateToolUseSummary&&F.length>0){let i=F.map(u=>({name:u.function.name,arguments:u.function.arguments}));re=e.generateToolUseSummary(i).catch(()=>null)}let Je=E.slice(-F.length),zt=Je.length>0&&Je.every(i=>{let u=i?.content;return typeof u!="string"?!1:u.startsWith("Error: ")}),X=c.consecutiveFailedRounds;if(zt){if(X+=1,X>=mt&&c.finalText){o.info(`early exit: ${X} consecutive failed rounds, returning partial response`),yield{type:"end",turnId:r,content:c.finalText,usage:c.totalUsage,model:c.currentModel};return}}else X=0;let ge=K+1;if(_>0&&ge>_){if(o.info(`max turns reached (${_}), 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";c={...c,messages:[...E,{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>x){if(o.info(`tool loop budget exhausted (${x} rounds), returning`),D>0){let i={ok:!0,toolCallCount:D,distinctToolCount:H.size,multiStep:D>=2,hasSubAgent:!1,feedback:null,existingSkillName:null},u=le(i,{tools:[...H]});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:E,maxOutputTokensRecoveryCount:0,hasAttemptedReactiveCompact:!1,maxOutputTokensOverride:void 0,turnCount:ge,transition:{reason:"next_turn"},guardState:v,reactiveCompactState:N,toolLoopState:O,consecutiveFailedRounds:X,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*Mn(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 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: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=Me(r),d=[];if(l&&d.push({role:"system",content:l}),d.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:_}),T=C?.context?.recalledMemories;if(T&&T.length>0){let I=T.map(h=>`- ${h.text}`).join(`
|
|
15
|
+
`,t+=on,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 an(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 ln(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 cn(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=an(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}=ln(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?cn(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 un=new Set(["read_file","file_read","FileRead","grep","Grep","glob","Glob","search","list_dir","find_files","web_fetch","web_search","WebFetch","WebSearch"]),dn=new Set(["bash","execute_command","Bash","shell"]),ge=class{tools=[];hasErrored=!1;erroredToolDescription="";discarded=!1;siblingAbortController;progressResolve;config;concurrencySafe;constructor(t){this.config=t,this.concurrencySafe=t.concurrencySafeTools??un,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:Q(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:pn(_)});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:Q(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=Q(t.id,{ok:b,payload:C,error:y.error});b||(m=!0,dn.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 pn(e){try{return JSON.parse(e)}catch{return}}import{readFile as Xr}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 qe(e){let t=0;for(let n of e)t+=He(n);return t}var Ge={"deepseek-v4-flash":1e6,"deepseek-v4-pro":1e6,"deepseek-chat":1e6,"deepseek-reasoner":1e6,"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 mn(e){if(!e)return 128e3;if(e in Ge)return Ge[e];let t=e.toLowerCase();for(let[n,o]of Object.entries(Ge))if(t.startsWith(n.toLowerCase()))return o;return 128e3}var gn=8e3;var fn=new te(200);var Yr=new oe;function yn(){return be(new ee(gn),new q(20,He),new Z(He))}var hn=null;function Nt(e,t){let n=t?.budget??ke({modelContextWindow:mn(t?.model)}),r=(t?.pipeline??yn()).compress(e,n);if(r.droppedCount>0){let a=qe(e),l=qe(r.messages);fn.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&&hn?.(r.droppedCount,qe(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 xn=new Set(["write","edit","patch","apply_patch"]);function vn(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 Sn(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 An(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 En(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 Mn(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 wn(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 In(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*Ln(r,p,l,g,d,_,t,o);return}let v=An(e.maxRounds),I={contextWindowTokens:e.contextWindowTokens??yt,responseBufferTokens:ht,maxOutputTokens:e.maxOutputTokens??Tt,abortSignal:_,reactiveCompactEnabled:!0,outputEscalationEnabled:!0},W=new Set,D=0,se=h,ie,c={messages:[...l],maxOutputTokensRecoveryCount:0,hasAttemptedReactiveCompact:!1,maxOutputTokensOverride:void 0,turnCount:1,transition:void 0,guardState:Fe(I),reactiveCompactState:je(),toolLoopState:pe({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:Pn,maxOutputTokensOverride:We,turnCount:X,guardState:S,reactiveCompactState:F,collapseStore:fe}=c,{toolLoopState:L}=c;if(ie){try{let i=await ie;i&&(yield{type:"tool_use_summary",turnId:r,summary:i})}catch{}ie=void 0}if(e.refreshTools&&X>1){let i=e.refreshTools();i!==se&&(se=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(F)&&(F.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 q().compress(A,0);u.droppedCount>0&&(A=u.messages,o.info(`microcompact: cleared ${u.droppedCount} old tool results`))}if(A=ve(A,fe).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=In(A);let ae=Ae({tools:se,toolChoice:e.toolChoice??"auto"}),Y=pe({maxRounds:v,replayMessages:A,lastStopReason:L.lastStopReason,options:{stopReason:L.lastStopReason}}),Ke=ae.extraSystemPrompt?[{role:"system",content:ae.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 le=!1,Xe=[],Ye=new Map,Je="stop",O,f=null,ce=!1,J=[],N=[];try{for await(let i of t.stream({model:c.currentModel,messages:Ke,tools:ae.tools,toolChoice:ae.normalizedToolChoice??"auto",temperature:d,maxTokens:(We??S.currentMaxOutputTokens)||void 0,streamRequired:e.streamRequired},g,_))switch(i.type){case"delta":Xe.push(i.text),le||(yield{type:"delta",turnId:r,text:i.text});break;case"tool_call_delta":le=!0,mt(Ye,i);break;case"reasoning_delta":J.push(i.text);break;case"reasoning_block_complete":i.signature&&N.push({thinking:J.join(""),signature:i.signature}),J.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(le||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 ne&&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>re){o.info(`stale connection retry limit reached (${re}), 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=wn({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=me(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(Wt=>setTimeout(Wt,w)),k-=w}c={...c,transition:void 0};continue}if(Oe(b)){let k=Mn({status:T,message:u})??me(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))ce=!0,o.info(`withheld prompt_too_long error (status=${f.status})`);else if($t(f))ce=!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(F)&&(F.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>re){o.info(`API retry limit reached (${re}), aborting`);let x=G(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=G(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&&!le){if(ce&&f&&Ut(f)){if(c.transition?.reason!=="collapse_drain_retry"){let i=Se(A,fe);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(F)){F.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(ce&&f&&$t(f)){if(H(F)){F.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(En(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=de(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,...N.length>0&&{thinkingBlocks:[...N]}};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,...N.length>0&&{thinkingBlocks:[...N]}};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=ue(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=se.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}}let Gt=N.length===0&&J.length>0?J.join(""):void 0;M.push(he(B,c.finalText||void 0,N.length>0?N:void 0,Gt)),L=Le(L,{replayMessages:M,pendingToolCallIds:B.map(i=>i.id),completedToolCallIds:L.completedToolCallIds,lastStopReason:"tool_calls"});let Ve=[];try{let i=new ge({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(xn.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:vn(w),title:w.split(/[\\/]/).pop()||w,filePath:w,language:Sn(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=de(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}));ie=e.generateToolUseSummary(i).catch(()=>null)}let Qe=M.slice(-B.length),Ht=Qe.length>0&&Qe.every(i=>{let u=i?.content;return typeof u!="string"?!1:u.startsWith("Error: ")}),V=c.consecutiveFailedRounds;if(Ht){if(V+=1,V>=ft&&c.finalText){o.info(`early exit: ${V} consecutive failed rounds, returning partial response`),yield{type:"end",turnId:r,content:c.finalText,usage:c.totalUsage,model:c.currentModel};return}}else V=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,...N.length>0&&{thinkingBlocks:[...N]}};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=ue(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:F,toolLoopState:L,consecutiveFailedRounds:V,finalText:c.finalText,totalUsage:c.totalUsage,collapseStore:fe,currentModel:c.currentModel,consecutive529Errors:0,consecutiveApiRetries:0,stopHookActive:c.stopHookActive,snipRemovedIds:c.snipRemovedIds,contentReplacementState:c.contentReplacementState}}}async function*Ln(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 qt=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
17
|
`);d.splice(l?1:0,0,{role:"system",content:`[Recalled from long-term memory]
|
|
18
|
-
${
|
|
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,streamRequired:s?.streamRequired,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=G(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{qt as Agent};
|