qlogicagent 2.12.15 → 2.13.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/agent.js CHANGED
@@ -1,8 +1,8 @@
1
- function _e(e,t,n,o){return{role:"assistant",content:t||null,tool_calls:e,...n&&n.length>0?{thinkingBlocks:n}:{},...o?{reasoning_content:o}:{}}}function ue(e,t){let n=t.ok?typeof t.payload=="string"?t.payload:JSON.stringify(t.payload??""):`Error: ${t.error??"Tool execution failed"}`;return{role:"tool",tool_call_id:e,content:n,...!t.ok&&{is_error:!0},...t.toolReferences?.length?{toolReferences:t.toolReferences}:{},...t.imageUrls?.length?{imageUrls:t.imageUrls}:{}}}var Eo=/\b(?:daily|weekly|monthly)(?:\/(?:daily|weekly|monthly))* (?:usage )?limit(?:s)?(?: (?:exhausted|reached|exceeded))?\b/i,q={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]},Io=/^(?:error[:\s-]+)?billing(?:\s+error)?(?:[:\s-]+|$)|^(?:error[:\s-]+)?(?:credit balance|insufficient credits?|payment required|http\s*402\b)/i,wo=/["']?(?:status|code)["']?\s*[:=]\s*402\b|\bhttp\s*402\b|\berror(?:\s+code)?\s*[:=]?\s*402\b|^\s*402\s+payment/i,Po=512,Lo=/^(?:http\s*)?(\d{3})(?:\s+([\s\S]+))?$/i;var Oo=new Set([500,502,503,504,521,522,523,524,529]),No=["insufficient credits","insufficient quota","credit balance","insufficient balance","plans & billing","add more credits","top up"],Do=["upgrade your plan","upgrade plan","current plan","subscription"],Bo=["daily","weekly","monthly"],Fo=["try again","retry","temporary","cooldown"],Uo=["usage limit","rate limit","organization usage"],jo=["organization","workspace"],$o=["billing period","exceeded","reached","exhausted"],Ho=/["']?(?: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,Go=/^(?:error[:\s-]+)?(?:(?:http\s*)?402(?:\s+payment required)?|payment required)(?:[:\s-]+|$)/i;function K(e,t){if(!e)return!1;let n=e.toLowerCase();return t.some(o=>o instanceof RegExp?o.test(n):n.includes(o))}function qo(e){return K(e,q.format)}function dt(e){return K(e,q.rateLimit)}function Ko(e){return K(e,q.timeout)}function zo(e){return Eo.test(e)}function Se(e){let t=e.toLowerCase();return t?e.length>Po?wo.test(t):K(t,q.billing)?!0:Io.test(e)?t.includes("upgrade")||t.includes("credits")||t.includes("payment")||t.includes("plan"):!1:!1}function pt(e){return K(e,q.authPermanent)}function Wo(e){return K(e,q.auth)}function mt(e){return K(e,q.overloaded)}function G(e,t){return t.some(n=>e.includes(n))}function Xo(e){return G(e,No)||G(e,Do)&&e.includes("limit")||e.includes("billing hard limit")||e.includes("hard limit reached")||e.includes("maximum allowed")&&e.includes("limit")}function Yo(e){let t=G(e,Bo),n=e.includes("spend limit")||e.includes("spending limit"),o=G(e,jo);return G(e,Fo)&&G(e,Uo)||t&&(e.includes("usage limit")||n)||t&&e.includes("limit")&&e.includes("reset")||o&&e.includes("limit")&&(n||G(e,$o))}function Vo(e){return e.trim().toLowerCase().replace(Go,"").trim()}function gt(e){let t=Vo(e);return!t||Xo(t)?"billing":dt(t)||Yo(t)?"rate_limit":"billing"}function Jo(e){return Ho.test(e)?gt(e):null}function ft(e){let t=e.match(Lo);if(!t)return null;let n=Number(t[1]);return Number.isFinite(n)?{code:n,rest:(t[2]??"").trim()}:null}function Qo(e){if(!e)return!1;let t=e.toLowerCase();return t.includes('"type":"api_error"')&&t.includes("internal server error")}function Zo(e){let t=e.trim();if(!t)return!1;let n=ft(t);return n?Oo.has(n.code):!1}function yt(e,t){return typeof e!="number"||!Number.isFinite(e)?null:e===402?t?gt(t):"billing":e===429?"rate_limit":e===401||e===403?t&&pt(t)?"auth_permanent":"auth":e===408?"timeout":e===503?t&&mt(t)?"overloaded":"timeout":e===502||e===504?"timeout":e===529?"overloaded":e===400?t&&Se(t)?"billing":"format":null}function en(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 tn(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 Tt(e){if(tn(e))return"session_expired";if(en(e))return"model_not_found";let t=Jo(e);return t||(zo(e)?Se(e)?"billing":"rate_limit":dt(e)?"rate_limit":mt(e)?"overloaded":Zo(e)?ft(e.trim())?.code===529?"overloaded":"timeout":Qo(e)?"timeout":qo(e)?"format":Se(e)?"billing":Ko(e)?"timeout":pt(e)?"auth_permanent":Wo(e)?"auth":null)}var on={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"},nn=new Set(["RETRYABLE_TRANSIENT","RETRYABLE_DEGRADED","TOOL_EXECUTION_FAILED"]);function W(e,t){let n=yt(e,t)??(t?Tt(t):null);return n?on[n]:typeof e=="number"&&e>=400&&e<500?"NON_RETRYABLE_CONTENT":"RETRYABLE_TRANSIENT"}function Me(e){return nn.has(e)}function ht(e){let t=typeof e.content=="string"?e.content:e.content!=null?JSON.stringify(e.content):"";return Math.ceil(t.length/4)}var rn=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"]),te=class{constructor(t=20,n=ht){this.preserveRecentCount=t;this.estimateTokens=n}preserveRecentCount;estimateTokens;compress(t,n){if(t.length<=this.preserveRecentCount)return{messages:t,droppedCount:0,strategy:"micro-compact"};let o=t.length-this.preserveRecentCount,r=0,i=0;return{messages:t.map((s,d)=>{if(d>=o||s.role!=="tool"||typeof s.content!="string"||!s.name||!rn.has(s.name)||s.content.length<=200)return s;let g=this.estimateTokens(s);return i+=g,r++,{...s,content:`[result cleared \u2014 ${s.content.length} chars]`}}),droppedCount:r,strategy:"micro-compact",metrics:r>0?{tokensBefore:0,tokensAfter:0,compressionRatio:0,latencyMs:0,usedLlm:!1,cacheInvalidated:!1}:void 0}}};function Ae(e,t,n=ht){if(t.size===0)return{messages:e,tokensFreed:0,removedCount:0};let o=0,r=0,i=[];for(let s of e){let d=s.tool_call_id??"";if(d&&t.has(d)){o+=n(s),r++,t.delete(d);continue}i.push(s)}let c=r>0?{role:"system",content:`[${r} messages removed by snip]`}:void 0;return{messages:i,tokensFreed:o,removedCount:r,boundaryMessage:c}}function ve(){return{stages:[]}}function Ee(e,t,n){let o=n?.thresholdMessages??40;if(e.filter(s=>s.role!=="system").length<=o)return{messages:e,stagedCount:0};let i=Ct(e,t),c=sn(i,t,o);if(c.length===0)return{messages:i,stagedCount:0};for(let s of c)t.stages.push(s);return i=Ct(e,t),{messages:i,stagedCount:c.length}}function Ie(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:kt(e,t),committed:n}}function Ct(e,t){return t.stages.filter(o=>o.committed).length===0?e:kt(e,t)}function kt(e,t){let n=t.stages.filter(r=>r.committed).sort((r,i)=>i.range[0]-r.range[0]),o=[...e];for(let r of n){let[i,c]=r.range;if(i>=o.length)continue;let s=Math.min(c,o.length),d={role:"system",content:r.summary};o.splice(i,s-i,d)}return o}function sn(e,t,n){let o=Math.max(0,e.length-Math.floor(n/2)),r=[],i=new Set(t.stages.map(d=>`${d.range[0]}-${d.range[1]}`)),c=-1,s=0;for(let d=0;d<o;d++){let g=e[d];if(g.role==="tool"||g.role==="assistant"&&typeof g.content=="string"&&g.content==="")c<0&&(c=d),s++;else{if(s>=3){let f=`${c}-${c+s}`;i.has(f)||r.push({id:`collapse_${c}_${c+s}`,range:[c,c+s],summary:`[${s} tool results collapsed]`,committed:!1})}c=-1,s=0}}if(s>=3){let d=`${c}-${c+s}`;i.has(d)||r.push({id:`collapse_${c}_${c+s}`,range:[c,c+s],summary:`[${s} tool results collapsed]`,committed:!1})}return r}import{existsSync as Pe,readFileSync as jt,writeFileSync as an,readdirSync as $t,mkdirSync as ln}from"node:fs";import{join as Le,dirname as cn}from"node:path";var Rt=Math.min(Math.max(1,Number(process.env.TOOL_LOOP_DEFAULT_BUDGET)||25),100),bt=3,xt=2,de=2,_t=128e3,St=13e3,Mt=16384,At=65536,vt=3,Et=65536,we=500,It=3;var wt=3e4,Pt=3,X=2;var Lt=20;var Ot=3,Nt=2,Dt=300*1e3,Bt=3,Ft=720*60*60*1e3;var dr=300*1e3;var pr=3600*1e3;var mr=50*1024,gr=500*1024,fr=500*1024*1024,yr=50*1024*1024;var Tr=60*1024;var Ht=0;var un="skill-patterns.json";function Gt(e){return Le(e,".qlogicagent",un)}function dn(e){let t=Gt(e);try{return JSON.parse(jt(t,"utf8"))}catch{return{version:1,patterns:{}}}}function Ut(e,t){let n=Gt(e);ln(cn(n),{recursive:!0}),an(n,JSON.stringify(t,null,2),"utf8")}function pn(e){let t=Date.now()-Ft;for(let[n,o]of Object.entries(e.patterns))new Date(o.lastSeen).getTime()<t&&delete e.patterns[n]}function qt(e,t){if(t.length===0)return!1;let n=pe(t),o=dn(e);pn(o);let r=new Date().toISOString(),i=o.patterns[n];if(i||(i={signature:n,count:0,firstSeen:r,lastSeen:r,promoted:!1},o.patterns[n]=i),i.promoted)return Ut(e,o),!1;i.count++,i.lastSeen=r;let c=i.count>=Bt;return c&&(i.promoted=!0),Ut(e,o),c}function pe(e){return[...e].sort().join("+")}function mn(e,t){if(!Pe(t))return null;let n=pe(e);try{let o=$t(t,{withFileTypes:!0});for(let r of o){if(!r.isDirectory())continue;let i=Le(t,r.name,"SKILL.md");try{let s=jt(i,"utf8").match(/^tools:\s*\n((?:\s+-\s+\S+\n?)+)/m);if(s){let d=s[1].split(`
2
- `).map(g=>g.replace(/^\s*-\s*/,"").trim()).filter(Boolean);if(pe(d)===n)return r.name}}catch{}}}catch{}return null}function gn(e){if(!Pe(e))return 0;try{return $t(e,{withFileTypes:!0}).filter(t=>t.isDirectory()&&Pe(Le(e,t.name,"SKILL.md"))).length}catch{return 0}}function fn(e,t){return!(!e.ok||e.existingSkillName||!e.multiStep||e.toolCallCount<Ot||e.distinctToolCount<Nt||Date.now()-Ht<Dt||t?.projectSkillsDir&&(gn(t.projectSkillsDir)>=Lt||t.tools.length>0&&mn(t.tools,t.projectSkillsDir))||t?.projectRoot&&t.tools.length>0&&!qt(t.projectRoot,t.tools))}function yn(e){return e.existingSkillName?e.feedback==="negative":!1}function Oe(e,t){return yn(e)?{type:"skill.improve",skillName:e.existingSkillName,reason:"negative user feedback on existing skill execution"}:fn(e,t)?(Ht=Date.now(),{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 Kt(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 Tn(e){return e==="enabled-eligible"||e==="installed-awaiting-approval"}function hn(e){return new Map((e??[]).map(t=>[t.toolName,t]))}function Cn(e){if(!e.eligibility?.length)return[...e.tools];let t=hn(e.eligibility);return e.tools.filter(n=>{let o=Kt(n);if(!o)return!1;let r=t.get(o);return!r||Tn(r.status)})}function kn(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 Ne(e){let t=kn({toolChoice:e.toolChoice,thinkingEnabled:e.thinkingEnabled,compatibility:e.compatibility}),n=t.normalizedToolChoice,o=[...t.warnings],r=Cn({tools:e.tools,eligibility:e.eligibility});if(!n||n==="auto")return{tools:r,normalizedToolChoice:n,warnings:o};if(n==="none")return{tools:[],normalizedToolChoice:"none",warnings:o};if(n==="required"){if(r.length===0)throw new Error("tool_choice=required but no tools were provided");return{tools:r,normalizedToolChoice:"required",extraSystemPrompt:"You must call one of the available tools before responding.",warnings:o}}if(typeof n=="object"&&!Array.isArray(n)&&n.type==="function"){let i=n.function??void 0,c=typeof i?.name=="string"?i.name.trim():"";if(!c)throw new Error("tool_choice.function.name is required");let s=r.filter(d=>Kt(d)===c);if(s.length===0)throw new Error(`tool_choice requested unknown tool: ${c}`);return{tools:s,normalizedToolChoice:{type:"function",function:{name:c}},extraSystemPrompt:`You must call the ${c} tool before responding.`,warnings:o}}return{tools:r,normalizedToolChoice:n,warnings:o}}var Rn=["stop","aborted","timeout","cancelled","interrupted","error"],bn=["tool_calls","toolCalls","function_call","functionCall","raw_tool_calls","rawToolCalls"];function zt(e){return e==null?[]:typeof e=="string"?e.length>0?[{type:"text",text:e}]:[]:Array.isArray(e)?e:[{type:"text",text:String(e)}]}function xn(e,t){return{...e,content:[...zt(e.content),...zt(t.content)]}}function _n(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 Sn(e){return new Set((e??Rn).map(t=>t.trim().toLowerCase()))}function Mn(e,t){return e?Sn(t).has(e.trim().toLowerCase()):!1}function De(e){if(!Array.isArray(e)||e.length===0)return[...e];let t=e.map(s=>{if(s.role==="assistant"&&Array.isArray(s.tool_calls)){let d=s.tool_calls.filter(g=>_n(g));return{...s,...d.length>0?{tool_calls:d}:{tool_calls:void 0}}}return{...s}}),n=new Set;for(let s of t)if(!(s.role!=="assistant"||!Array.isArray(s.tool_calls)))for(let d of s.tool_calls)typeof d.id=="string"&&d.id&&n.add(d.id);let o=t.filter(s=>s.role!=="tool"?!0:!!(s.tool_call_id&&n.has(s.tool_call_id))),r=new Set;for(let s of o)s.role==="tool"&&typeof s.tool_call_id=="string"&&s.tool_call_id&&r.add(s.tool_call_id);let i=[];for(let s of o){if(s.role==="assistant"&&Array.isArray(s.tool_calls)&&s.tool_calls.length>0){let d=s.tool_calls.filter(g=>typeof g.id=="string"&&r.has(g.id));if(d.length===0){let{tool_calls:g,...m}=s;m.content!=null&&m.content!==""&&i.push(m);continue}if(d.length<s.tool_calls.length){i.push({...s,tool_calls:d});continue}}i.push(s)}let c=[];for(let s of i){let d=c.length>0?c[c.length-1]:void 0;if(s.role==="user"&&d?.role==="user"){c[c.length-1]=xn(d,s);continue}c.push(s)}return c}function Be(e,t){return Mn(t?.stopReason,t?.forcedStopReasons)?e.map(n=>{if(n.role!=="assistant")return{...n};let o={...n};for(let r of bn)delete o[r];return o}):[...e]}function Fe(e,t){let n=t?.placeholderToolResult??"Error: Tool loop interrupted before the tool result was replayed.",o=new Set;for(let i of e)i.role==="tool"&&typeof i.tool_call_id=="string"&&i.tool_call_id&&o.add(i.tool_call_id);let r=[];for(let i of e)if(r.push({...i}),!(i.role!=="assistant"||!Array.isArray(i.tool_calls)||i.tool_calls.length===0))for(let c of i.tool_calls)typeof c.id!="string"||!c.id||o.has(c.id)||(o.add(c.id),r.push({role:"tool",tool_call_id:c.id,content:n}));return r}function Ue(e,t){let n=De(e),o=Be(n,t);return Fe(o,t)}function An(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 vn(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 En(e){return{round:e.round??0,maxRounds:e.maxRounds,pendingToolCallIds:[...e.pendingToolCallIds??[]],completedToolCallIds:[...e.completedToolCallIds??[]],lastStopReason:e.lastStopReason,replayMessages:[...e.replayMessages??[]]}}function je(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 me(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 ge(e){let t=[],n=De(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=Be(n,e.options);o.some((i,c)=>i!==n[c])&&t.push({kind:"strip-forced-stop-tool-metadata",detail:"Removed assistant tool-call metadata after forced stop."});let r=Fe(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:En({maxRounds:e.maxRounds,round:e.round,lastStopReason:e.lastStopReason,replayMessages:r,pendingToolCallIds:An(r),completedToolCallIds:vn(r)}),recoveryActions:t}}var In=new Set(["main","sdk","agent","compact","hook","verification","side_question"]);function $e(e){return e?In.has(e):!0}function He(e){return e===429||e===529}function fe(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 Er={maxBackoffMs:300*1e3,resetCapMs:360*60*1e3,heartbeatIntervalMs:3e4};function ye(){let e=process.env.QLOGICAGENT_PERSISTENT_RETRY;return e==="1"||e==="true"}var oe=class extends Error{constructor(n,o){super(`Model fallback triggered: ${n} -> ${o}`);this.originalModel=n;this.fallbackModel=o;this.name="FallbackTriggeredError"}originalModel;fallbackModel};function Ge(e){return{promptTokens:0,hasAttemptedReactiveCompact:!1,currentMaxOutputTokens:e.maxOutputTokens,consecutiveTruncations:0,aborted:e.abortSignal?.aborted??!1}}function qe(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 Ke(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 ze(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 We(e,t){return e.aborted?!0:t.abortSignal?.aborted?(e.aborted=!0,!0):!1}var Pn={maxConsecutiveFailures:3,minMessagesAfterCompact:4,targetUsagePercent:50};function Xe(){return{consecutiveFailures:0,attemptedThisTurn:!1,lastCompactAt:null,toolsAtLastCompact:[]}}function Y(e,t=Pn){return!(e.attemptedThisTurn||e.consecutiveFailures>=t.maxConsecutiveFailures)}function Ye(e,t){let n=e.get(t.index)??{id:"",name:"",arguments:""};t.id&&(n.id=t.id),t.name&&(n.name=t.name),n.arguments+=t.arguments??"",e.set(t.index,n)}function M(e,t,n,o){e?.invoke(t,n).catch(r=>{let i=r instanceof Error?r.message:String(r);o.warn(`[hook:${t}] handler failed: ${i}`)})}function Wt(e,t){let n=typeof t.message?.content=="string"?t.message.content:"",o=n?n.slice(0,2e3):void 0,r=t.details,i=typeof r?.stdout=="string"?r.stdout.slice(0,8e3):void 0,c=typeof r?.stderr=="string"?r.stderr.slice(0,4e3):void 0,s=typeof r?.exitCode=="number"?r.exitCode:void 0;return{type:"tool_result",turnId:e,callId:t.callId,name:t.toolName,ok:t.ok,error:t.error,outputPreview:o,durationMs:t.durationMs,exitCode:s,stdout:i,stderr:c,details:r}}function Xt(e,t){if(!t.ok)return[];let n=t.details;if(!n)return[];let o=Ln(n);return o?(Array.isArray(n.mediaUrls)?n.mediaUrls.filter(i=>typeof i=="string"&&i.trim().length>0):[]).map(i=>({type:"media_result",turnId:e,mediaType:o,url:i,model:typeof n.model=="string"?n.model:void 0,provider:typeof n.provider=="string"?n.provider:void 0,durationSeconds:typeof n.durationMs=="number"?n.durationMs/1e3:void 0,taskId:typeof n.taskId=="string"?n.taskId:void 0})):[]}function Ln(e){let t=typeof e.type=="string"?e.type:"";if(!t)return null;if(t==="three_d_generate")return"3d";let n=t.split("_")[0];return n==="image"||n==="tts"||n==="video"||n==="music"?n:null}var On=new Set(["write","edit","patch"]);function Yt(e){let{turnId:t,result:n,toolCalls:o}=e;if(!n.ok)return[];let r=o.find(s=>s.id===n.callId);if(!r)return[];let i=[],c=Nn(r.function.arguments);if(!c)return i;if(n.toolName==="plan_mode"&&c.action==="exit"&&typeof c.plan=="string"&&c.plan.length>0&&i.push({type:"plan_update",turnId:t,slug:"approved-plan",content:c.plan}),On.has(n.toolName)){let s=Dn(c);s&&i.push({type:"artifact",turnId:t,artifactId:`artifact-${n.callId}`,artifactType:Bn(s),title:s.split(/[\\/]/).pop()||s,filePath:s,language:Fn(s)})}return i}function Nn(e){try{return JSON.parse(e)}catch{return null}}function Dn(e){return typeof e.file_path=="string"?e.file_path:typeof e.filePath=="string"?e.filePath:typeof e.path=="string"?e.path:void 0}function Bn(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 Fn(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]}var jn=/^no (matches|files|results) found(?:\s+for:.*)?\.?$|^file not found|^not found|^0 results|^\(exit code \d+, no output\)$/i,$n=new Set(["search","web_search","grep","glob","find","list","read","exec"]);function Vt(e){if(!$n.has(e.toolName))return!1;let t=typeof e.message?.content=="string"?e.message.content.trim():"";return t.length>0&&t.length<200&&jn.test(t)}function Ve(e,t){for(let n=e.length-1;n>=0;n--){let o=e[n];if(!o||o.role!=="tool")continue;let r=typeof o.content=="string"?o.content:"";if(r.startsWith("Error: "))return r.slice(7).trim()}}function Jt(e){return typeof e=="number"&&Number.isFinite(e)&&e>=1?Math.min(Math.round(e),100):Rt}function Qt(e){return e.filter(t=>t.role!=="assistant"?!0:!(typeof t.content=="string"&&t.content.trim()===""))}function V(e,t){let n=[];for(let o=e.length-1;o>=0;o--){let r=e[o];if(r.role==="tool"&&typeof r.content=="string")n.unshift(r.content.slice(0,500));else if(r.role==="assistant"){if(typeof r.content=="string"&&r.content.trim())return t.info("synthesizeFallbackContent: found assistant text, using it"),r.content;break}else break}return n.length>0?(t.info(`synthesizeFallbackContent: synthesized from ${n.length} tool result(s)`),n.join(`
1
+ function _e(e,t,n,o){return{role:"assistant",content:t||null,tool_calls:e,...n&&n.length>0?{thinkingBlocks:n}:{},...o?{reasoning_content:o}:{}}}function ue(e,t){let n=t.ok?typeof t.payload=="string"?t.payload:JSON.stringify(t.payload??""):`Error: ${t.error??"Tool execution failed"}`;return{role:"tool",tool_call_id:e,content:n,...!t.ok&&{is_error:!0},...t.toolReferences?.length?{toolReferences:t.toolReferences}:{},...t.imageUrls?.length?{imageUrls:t.imageUrls}:{}}}var Io=/\b(?:daily|weekly|monthly)(?:\/(?:daily|weekly|monthly))* (?:usage )?limit(?:s)?(?: (?:exhausted|reached|exceeded))?\b/i,q={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]},wo=/^(?:error[:\s-]+)?billing(?:\s+error)?(?:[:\s-]+|$)|^(?:error[:\s-]+)?(?:credit balance|insufficient credits?|payment required|http\s*402\b)/i,Lo=/["']?(?:status|code)["']?\s*[:=]\s*402\b|\bhttp\s*402\b|\berror(?:\s+code)?\s*[:=]?\s*402\b|^\s*402\s+payment/i,Po=512,Oo=/^(?:http\s*)?(\d{3})(?:\s+([\s\S]+))?$/i;var No=new Set([500,502,503,504,521,522,523,524,529]),Do=["insufficient credits","insufficient quota","credit balance","insufficient balance","plans & billing","add more credits","top up"],Bo=["upgrade your plan","upgrade plan","current plan","subscription"],Fo=["daily","weekly","monthly"],Uo=["try again","retry","temporary","cooldown"],jo=["usage limit","rate limit","organization usage"],$o=["organization","workspace"],Ho=["billing period","exceeded","reached","exhausted"],Go=/["']?(?: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,qo=/^(?:error[:\s-]+)?(?:(?:http\s*)?402(?:\s+payment required)?|payment required)(?:[:\s-]+|$)/i;function K(e,t){if(!e)return!1;let n=e.toLowerCase();return t.some(o=>o instanceof RegExp?o.test(n):n.includes(o))}function Ko(e){return K(e,q.format)}function pt(e){return K(e,q.rateLimit)}function zo(e){return K(e,q.timeout)}function Wo(e){return Io.test(e)}function Se(e){let t=e.toLowerCase();return t?e.length>Po?Lo.test(t):K(t,q.billing)?!0:wo.test(e)?t.includes("upgrade")||t.includes("credits")||t.includes("payment")||t.includes("plan"):!1:!1}function mt(e){return K(e,q.authPermanent)}function Xo(e){return K(e,q.auth)}function gt(e){return K(e,q.overloaded)}function G(e,t){return t.some(n=>e.includes(n))}function Yo(e){return G(e,Do)||G(e,Bo)&&e.includes("limit")||e.includes("billing hard limit")||e.includes("hard limit reached")||e.includes("maximum allowed")&&e.includes("limit")}function Vo(e){let t=G(e,Fo),n=e.includes("spend limit")||e.includes("spending limit"),o=G(e,$o);return G(e,Uo)&&G(e,jo)||t&&(e.includes("usage limit")||n)||t&&e.includes("limit")&&e.includes("reset")||o&&e.includes("limit")&&(n||G(e,Ho))}function Jo(e){return e.trim().toLowerCase().replace(qo,"").trim()}function ft(e){let t=Jo(e);return!t||Yo(t)?"billing":pt(t)||Vo(t)?"rate_limit":"billing"}function Qo(e){return Go.test(e)?ft(e):null}function yt(e){let t=e.match(Oo);if(!t)return null;let n=Number(t[1]);return Number.isFinite(n)?{code:n,rest:(t[2]??"").trim()}:null}function Zo(e){if(!e)return!1;let t=e.toLowerCase();return t.includes('"type":"api_error"')&&t.includes("internal server error")}function en(e){let t=e.trim();if(!t)return!1;let n=yt(t);return n?No.has(n.code):!1}function Tt(e,t){return typeof e!="number"||!Number.isFinite(e)?null:e===402?t?ft(t):"billing":e===429?"rate_limit":e===401||e===403?t&&mt(t)?"auth_permanent":"auth":e===408?"timeout":e===503?t&&gt(t)?"overloaded":"timeout":e===502||e===504?"timeout":e===529?"overloaded":e===400?t&&Se(t)?"billing":"format":null}function tn(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 on(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 ht(e){if(on(e))return"session_expired";if(tn(e))return"model_not_found";let t=Qo(e);return t||(Wo(e)?Se(e)?"billing":"rate_limit":pt(e)?"rate_limit":gt(e)?"overloaded":en(e)?yt(e.trim())?.code===529?"overloaded":"timeout":Zo(e)?"timeout":Ko(e)?"format":Se(e)?"billing":zo(e)?"timeout":mt(e)?"auth_permanent":Xo(e)?"auth":null)}var nn={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"},rn=new Set(["RETRYABLE_TRANSIENT","RETRYABLE_DEGRADED","TOOL_EXECUTION_FAILED"]);function W(e,t){let n=Tt(e,t)??(t?ht(t):null);return n?nn[n]:typeof e=="number"&&e>=400&&e<500?"NON_RETRYABLE_CONTENT":"RETRYABLE_TRANSIENT"}function Me(e){return rn.has(e)}function Ct(e){let t=typeof e.content=="string"?e.content:e.content!=null?JSON.stringify(e.content):"";return Math.ceil(t.length/4)}var sn=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"]),te=class{constructor(t=20,n=Ct){this.preserveRecentCount=t;this.estimateTokens=n}preserveRecentCount;estimateTokens;compress(t,n){if(t.length<=this.preserveRecentCount)return{messages:t,droppedCount:0,strategy:"micro-compact"};let o=t.length-this.preserveRecentCount,r=0,i=0;return{messages:t.map((s,d)=>{if(d>=o||s.role!=="tool"||typeof s.content!="string"||!s.name||!sn.has(s.name)||s.content.length<=200)return s;let g=this.estimateTokens(s);return i+=g,r++,{...s,content:`[result cleared \u2014 ${s.content.length} chars]`}}),droppedCount:r,strategy:"micro-compact",metrics:r>0?{tokensBefore:0,tokensAfter:0,compressionRatio:0,latencyMs:0,usedLlm:!1,cacheInvalidated:!1}:void 0}}};function Ae(e,t,n=Ct){if(t.size===0)return{messages:e,tokensFreed:0,removedCount:0};let o=0,r=0,i=[];for(let s of e){let d=s.tool_call_id??"";if(d&&t.has(d)){o+=n(s),r++,t.delete(d);continue}i.push(s)}let c=r>0?{role:"system",content:`[${r} messages removed by snip]`}:void 0;return{messages:i,tokensFreed:o,removedCount:r,boundaryMessage:c}}function ve(){return{stages:[]}}function Ee(e,t,n){let o=n?.thresholdMessages??40;if(e.filter(s=>s.role!=="system").length<=o)return{messages:e,stagedCount:0};let i=kt(e,t),c=an(i,t,o);if(c.length===0)return{messages:i,stagedCount:0};for(let s of c)t.stages.push(s);return i=kt(e,t),{messages:i,stagedCount:c.length}}function Ie(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:Rt(e,t),committed:n}}function kt(e,t){return t.stages.filter(o=>o.committed).length===0?e:Rt(e,t)}function Rt(e,t){let n=t.stages.filter(r=>r.committed).sort((r,i)=>i.range[0]-r.range[0]),o=[...e];for(let r of n){let[i,c]=r.range;if(i>=o.length)continue;let s=Math.min(c,o.length),d={role:"system",content:r.summary};o.splice(i,s-i,d)}return o}function an(e,t,n){let o=Math.max(0,e.length-Math.floor(n/2)),r=[],i=new Set(t.stages.map(d=>`${d.range[0]}-${d.range[1]}`)),c=-1,s=0;for(let d=0;d<o;d++){let g=e[d];if(g.role==="tool"||g.role==="assistant"&&typeof g.content=="string"&&g.content==="")c<0&&(c=d),s++;else{if(s>=3){let p=`${c}-${c+s}`;i.has(p)||r.push({id:`collapse_${c}_${c+s}`,range:[c,c+s],summary:`[${s} tool results collapsed]`,committed:!1})}c=-1,s=0}}if(s>=3){let d=`${c}-${c+s}`;i.has(d)||r.push({id:`collapse_${c}_${c+s}`,range:[c,c+s],summary:`[${s} tool results collapsed]`,committed:!1})}return r}import{existsSync as Le,readFileSync as $t,writeFileSync as ln,readdirSync as Ht,mkdirSync as cn}from"node:fs";import{join as Pe,dirname as un}from"node:path";var bt=Math.min(Math.max(1,Number(process.env.TOOL_LOOP_DEFAULT_BUDGET)||25),100),xt=3,_t=2,de=2,St=128e3,Mt=13e3,At=16384,vt=65536,Et=3,It=65536,we=500,wt=3;var Lt=3e4,Pt=3,X=2;var Ot=20;var Nt=3,Dt=2,Bt=300*1e3,Ft=3,Ut=720*60*60*1e3;var pr=300*1e3;var mr=3600*1e3;var gr=50*1024,fr=500*1024,yr=500*1024*1024,Tr=50*1024*1024;var hr=60*1024;var Gt=0;var dn="skill-patterns.json";function qt(e){return Pe(e,".qlogicagent",dn)}function pn(e){let t=qt(e);try{return JSON.parse($t(t,"utf8"))}catch{return{version:1,patterns:{}}}}function jt(e,t){let n=qt(e);cn(un(n),{recursive:!0}),ln(n,JSON.stringify(t,null,2),"utf8")}function mn(e){let t=Date.now()-Ut;for(let[n,o]of Object.entries(e.patterns))new Date(o.lastSeen).getTime()<t&&delete e.patterns[n]}function Kt(e,t){if(t.length===0)return!1;let n=pe(t),o=pn(e);mn(o);let r=new Date().toISOString(),i=o.patterns[n];if(i||(i={signature:n,count:0,firstSeen:r,lastSeen:r,promoted:!1},o.patterns[n]=i),i.promoted)return jt(e,o),!1;i.count++,i.lastSeen=r;let c=i.count>=Ft;return c&&(i.promoted=!0),jt(e,o),c}function pe(e){return[...e].sort().join("+")}function gn(e,t){if(!Le(t))return null;let n=pe(e);try{let o=Ht(t,{withFileTypes:!0});for(let r of o){if(!r.isDirectory())continue;let i=Pe(t,r.name,"SKILL.md");try{let s=$t(i,"utf8").match(/^tools:\s*\n((?:\s+-\s+\S+\n?)+)/m);if(s){let d=s[1].split(`
2
+ `).map(g=>g.replace(/^\s*-\s*/,"").trim()).filter(Boolean);if(pe(d)===n)return r.name}}catch{}}}catch{}return null}function fn(e){if(!Le(e))return 0;try{return Ht(e,{withFileTypes:!0}).filter(t=>t.isDirectory()&&Le(Pe(e,t.name,"SKILL.md"))).length}catch{return 0}}function yn(e,t){return!(!e.ok||e.existingSkillName||!e.multiStep||e.toolCallCount<Nt||e.distinctToolCount<Dt||Date.now()-Gt<Bt||t?.projectSkillsDir&&(fn(t.projectSkillsDir)>=Ot||t.tools.length>0&&gn(t.tools,t.projectSkillsDir))||t?.projectRoot&&t.tools.length>0&&!Kt(t.projectRoot,t.tools))}function Tn(e){return e.existingSkillName?e.feedback==="negative":!1}function Oe(e,t){return Tn(e)?{type:"skill.improve",skillName:e.existingSkillName,reason:"negative user feedback on existing skill execution"}:yn(e,t)?(Gt=Date.now(),{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 zt(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 hn(e){return e==="enabled-eligible"||e==="installed-awaiting-approval"}function Cn(e){return new Map((e??[]).map(t=>[t.toolName,t]))}function kn(e){if(!e.eligibility?.length)return[...e.tools];let t=Cn(e.eligibility);return e.tools.filter(n=>{let o=zt(n);if(!o)return!1;let r=t.get(o);return!r||hn(r.status)})}function Rn(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 Ne(e){let t=Rn({toolChoice:e.toolChoice,thinkingEnabled:e.thinkingEnabled,compatibility:e.compatibility}),n=t.normalizedToolChoice,o=[...t.warnings],r=kn({tools:e.tools,eligibility:e.eligibility});if(!n||n==="auto")return{tools:r,normalizedToolChoice:n,warnings:o};if(n==="none")return{tools:[],normalizedToolChoice:"none",warnings:o};if(n==="required"){if(r.length===0)throw new Error("tool_choice=required but no tools were provided");return{tools:r,normalizedToolChoice:"required",extraSystemPrompt:"You must call one of the available tools before responding.",warnings:o}}if(typeof n=="object"&&!Array.isArray(n)&&n.type==="function"){let i=n.function??void 0,c=typeof i?.name=="string"?i.name.trim():"";if(!c)throw new Error("tool_choice.function.name is required");let s=r.filter(d=>zt(d)===c);if(s.length===0)throw new Error(`tool_choice requested unknown tool: ${c}`);return{tools:s,normalizedToolChoice:{type:"function",function:{name:c}},extraSystemPrompt:`You must call the ${c} tool before responding.`,warnings:o}}return{tools:r,normalizedToolChoice:n,warnings:o}}var bn=["stop","aborted","timeout","cancelled","interrupted","error"],xn=["tool_calls","toolCalls","function_call","functionCall","raw_tool_calls","rawToolCalls"];function Wt(e){return e==null?[]:typeof e=="string"?e.length>0?[{type:"text",text:e}]:[]:Array.isArray(e)?e:[{type:"text",text:String(e)}]}function _n(e,t){return{...e,content:[...Wt(e.content),...Wt(t.content)]}}function Sn(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 Mn(e){return new Set((e??bn).map(t=>t.trim().toLowerCase()))}function An(e,t){return e?Mn(t).has(e.trim().toLowerCase()):!1}function De(e){if(!Array.isArray(e)||e.length===0)return[...e];let t=e.map(s=>{if(s.role==="assistant"&&Array.isArray(s.tool_calls)){let d=s.tool_calls.filter(g=>Sn(g));return{...s,...d.length>0?{tool_calls:d}:{tool_calls:void 0}}}return{...s}}),n=new Set;for(let s of t)if(!(s.role!=="assistant"||!Array.isArray(s.tool_calls)))for(let d of s.tool_calls)typeof d.id=="string"&&d.id&&n.add(d.id);let o=t.filter(s=>s.role!=="tool"?!0:!!(s.tool_call_id&&n.has(s.tool_call_id))),r=new Set;for(let s of o)s.role==="tool"&&typeof s.tool_call_id=="string"&&s.tool_call_id&&r.add(s.tool_call_id);let i=[];for(let s of o){if(s.role==="assistant"&&Array.isArray(s.tool_calls)&&s.tool_calls.length>0){let d=s.tool_calls.filter(g=>typeof g.id=="string"&&r.has(g.id));if(d.length===0){let{tool_calls:g,...T}=s;T.content!=null&&T.content!==""&&i.push(T);continue}if(d.length<s.tool_calls.length){i.push({...s,tool_calls:d});continue}}i.push(s)}let c=[];for(let s of i){let d=c.length>0?c[c.length-1]:void 0;if(s.role==="user"&&d?.role==="user"){c[c.length-1]=_n(d,s);continue}c.push(s)}return c}function Be(e,t){return An(t?.stopReason,t?.forcedStopReasons)?e.map(n=>{if(n.role!=="assistant")return{...n};let o={...n};for(let r of xn)delete o[r];return o}):[...e]}function Fe(e,t){let n=t?.placeholderToolResult??"Error: Tool loop interrupted before the tool result was replayed.",o=new Set;for(let i of e)i.role==="tool"&&typeof i.tool_call_id=="string"&&i.tool_call_id&&o.add(i.tool_call_id);let r=[];for(let i of e)if(r.push({...i}),!(i.role!=="assistant"||!Array.isArray(i.tool_calls)||i.tool_calls.length===0))for(let c of i.tool_calls)typeof c.id!="string"||!c.id||o.has(c.id)||(o.add(c.id),r.push({role:"tool",tool_call_id:c.id,content:n}));return r}function Ue(e,t){let n=De(e),o=Be(n,t);return Fe(o,t)}function vn(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 En(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 In(e){return{round:e.round??0,maxRounds:e.maxRounds,pendingToolCallIds:[...e.pendingToolCallIds??[]],completedToolCallIds:[...e.completedToolCallIds??[]],lastStopReason:e.lastStopReason,replayMessages:[...e.replayMessages??[]]}}function je(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 me(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 ge(e){let t=[],n=De(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=Be(n,e.options);o.some((i,c)=>i!==n[c])&&t.push({kind:"strip-forced-stop-tool-metadata",detail:"Removed assistant tool-call metadata after forced stop."});let r=Fe(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:In({maxRounds:e.maxRounds,round:e.round,lastStopReason:e.lastStopReason,replayMessages:r,pendingToolCallIds:vn(r),completedToolCallIds:En(r)}),recoveryActions:t}}var wn=new Set(["main","sdk","agent","compact","hook","verification","side_question"]);function $e(e){return e?wn.has(e):!0}function He(e){return e===429||e===529}function fe(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 Ir={maxBackoffMs:300*1e3,resetCapMs:360*60*1e3,heartbeatIntervalMs:3e4};function ye(){let e=process.env.QLOGICAGENT_PERSISTENT_RETRY;return e==="1"||e==="true"}var oe=class extends Error{constructor(n,o){super(`Model fallback triggered: ${n} -> ${o}`);this.originalModel=n;this.fallbackModel=o;this.name="FallbackTriggeredError"}originalModel;fallbackModel};function Ge(e){return{promptTokens:0,hasAttemptedReactiveCompact:!1,currentMaxOutputTokens:e.maxOutputTokens,consecutiveTruncations:0,aborted:e.abortSignal?.aborted??!1}}function qe(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 Ke(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 ze(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 We(e,t){return e.aborted?!0:t.abortSignal?.aborted?(e.aborted=!0,!0):!1}var Pn={maxConsecutiveFailures:3,minMessagesAfterCompact:4,targetUsagePercent:50};function Xe(){return{consecutiveFailures:0,attemptedThisTurn:!1,lastCompactAt:null,toolsAtLastCompact:[]}}function Y(e,t=Pn){return!(e.attemptedThisTurn||e.consecutiveFailures>=t.maxConsecutiveFailures)}function Ye(e,t){let n=e.get(t.index)??{id:"",name:"",arguments:""};t.id&&(n.id=t.id),t.name&&(n.name=t.name),n.arguments+=t.arguments??"",e.set(t.index,n)}function M(e,t,n,o){e?.invoke(t,n).catch(r=>{let i=r instanceof Error?r.message:String(r);o.warn(`[hook:${t}] handler failed: ${i}`)})}function Xt(e,t){let n=typeof t.message?.content=="string"?t.message.content:"",o=n?n.slice(0,2e3):void 0,r=t.details,i=typeof r?.stdout=="string"?r.stdout.slice(0,8e3):void 0,c=typeof r?.stderr=="string"?r.stderr.slice(0,4e3):void 0,s=typeof r?.exitCode=="number"?r.exitCode:void 0;return{type:"tool_result",turnId:e,callId:t.callId,name:t.toolName,ok:t.ok,error:t.error,outputPreview:o,durationMs:t.durationMs,exitCode:s,stdout:i,stderr:c,details:r}}function Yt(e,t){if(!t.ok)return[];let n=t.details;if(!n)return[];let o=On(n);return o?(Array.isArray(n.mediaUrls)?n.mediaUrls.filter(i=>typeof i=="string"&&i.trim().length>0):[]).map(i=>({type:"media_result",turnId:e,mediaType:o,url:i,model:typeof n.model=="string"?n.model:void 0,provider:typeof n.provider=="string"?n.provider:void 0,durationSeconds:typeof n.durationMs=="number"?n.durationMs/1e3:void 0,taskId:typeof n.taskId=="string"?n.taskId:void 0})):[]}function On(e){let t=typeof e.type=="string"?e.type:"";if(!t)return null;if(t==="three_d_generate")return"3d";let n=t.split("_")[0];return n==="image"||n==="tts"||n==="video"||n==="music"?n:null}var Nn=new Set(["write","edit","patch"]);function Vt(e){let{turnId:t,result:n,toolCalls:o}=e;if(!n.ok)return[];let r=o.find(s=>s.id===n.callId);if(!r)return[];let i=[],c=Dn(r.function.arguments);if(!c)return i;if(n.toolName==="plan_mode"&&c.action==="exit"&&typeof c.plan=="string"&&c.plan.length>0&&i.push({type:"plan_update",turnId:t,slug:"approved-plan",content:c.plan}),Nn.has(n.toolName)){let s=Bn(c);s&&i.push({type:"artifact",turnId:t,artifactId:`artifact-${n.callId}`,artifactType:Fn(s),title:s.split(/[\\/]/).pop()||s,filePath:s,language:Un(s)})}return i}function Dn(e){try{return JSON.parse(e)}catch{return null}}function Bn(e){return typeof e.file_path=="string"?e.file_path:typeof e.filePath=="string"?e.filePath:typeof e.path=="string"?e.path:void 0}function Fn(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 Un(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]}var $n=/^no (matches|files|results) found(?:\s+for:.*)?\.?$|^file not found|^not found|^0 results|^\(exit code \d+, no output\)$/i,Hn=new Set(["search","web_search","grep","glob","find","list","read","exec"]);function Jt(e){if(!Hn.has(e.toolName))return!1;let t=typeof e.message?.content=="string"?e.message.content.trim():"";return t.length>0&&t.length<200&&$n.test(t)}function Ve(e,t){for(let n=e.length-1;n>=0;n--){let o=e[n];if(!o||o.role!=="tool")continue;let r=typeof o.content=="string"?o.content:"";if(r.startsWith("Error: "))return r.slice(7).trim()}}function Qt(e){return typeof e=="number"&&Number.isFinite(e)&&e>=1?Math.min(Math.round(e),100):bt}function Zt(e){return e.filter(t=>t.role!=="assistant"?!0:!(typeof t.content=="string"&&t.content.trim()===""))}function V(e,t){let n=[];for(let o=e.length-1;o>=0;o--){let r=e[o];if(r.role==="tool"&&typeof r.content=="string")n.unshift(r.content.slice(0,500));else if(r.role==="assistant"){if(typeof r.content=="string"&&r.content.trim())return t.info("synthesizeFallbackContent: found assistant text, using it"),r.content;break}else break}return n.length>0?(t.info(`synthesizeFallbackContent: synthesized from ${n.length} tool result(s)`),n.join(`
3
3
 
4
- `)):""}function Zt(e){try{let t=JSON.parse(e),o=[t.description,t.command,t.query,t.url,t.path,t.file_path,t.filePath,t.pattern,t.model].find(i=>typeof i=="string"&&i.trim().length>0);if(typeof o=="string")return o.trim().slice(0,240);let r=Object.keys(t);return r.length>0?r.slice(0,5).join(" / "):void 0}catch{return}}function Je(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 eo(e){return e==="length"||e==="max_tokens"}function Qe(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 to(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 oo(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}async function*no(e,t,n,o,r,i,c,s){let d=[],g;s.debug(`single LLM round, messages: ${n.length}`);for await(let m of c.stream({model:t,messages:n,temperature:r},o,i))switch(m.type){case"delta":d.push(m.text),yield{type:"delta",turnId:e,text:m.text};break;case"usage":g={inputTokens:m.promptTokens,outputTokens:m.completionTokens,reasoningTokens:m.reasoningTokens,cacheRead:m.cacheReadTokens,cacheWrite:m.cacheCreationTokens};break;case"done":break}yield{type:"end",turnId:e,content:d.join(""),usage:g??{inputTokens:0,outputTokens:0},model:t}}async function*ro(e){let{messages:t,contentReplacementState:n,snipRemovedIds:o,collapseStore:r,guardState:i,guardConfig:c,runtimePorts:s,hooks:d,hookCtx:g,sessionId:m,currentModel:f,log:b,recovery:h,onAutocompact:x}=e,C;{let p=await s.enforceToolResultBudget(t,n,m);C=p.messages,p.newlyReplacedCount>0&&(b.info(`tool-result-budget: persisted ${p.newlyReplacedCount} oversized tool results`),yield h("tool_result_budget",`${p.newlyReplacedCount} persisted`))}{let p=Ae(C,o);C=p.messages,p.removedCount>0&&(b.info(`snip: removed ${p.removedCount} messages, freed ~${p.tokensFreed} tokens`),yield h("snip",`${p.removedCount} messages`))}{let _=new te().compress(C,0);_.droppedCount>0&&(C=_.messages,b.info(`microcompact: cleared ${_.droppedCount} old tool results`))}if(C=Ee(C,r).messages,i.promptTokens>0){let p=c.contextWindowTokens*.75,_=s.getActiveContextCompressionEngine(),S;_?S=await _.compressAsync(C,p,{model:f,sessionId:m}):S=s.compressMessages(C,{budget:p,model:f}),S.droppedCount>0&&(C=S.messages,b.info(`autocompact: ${S.strategy}, dropped ${S.droppedCount}`),yield h("autocompact",`${S.strategy}: ${S.droppedCount} dropped`),x(),M(d,"context.after_compact",{...g,removedCount:S.droppedCount},b))}return C=Qt(C),C}async function*so(e,t){let{state:n,guardState:o,fallbackModel:r,signal:i,querySource:c,turnId:s,log:d,emitRecovery:g}=t;if(e instanceof oe&&r)return d.info(`model fallback triggered: ${e.originalModel} -> ${e.fallbackModel}`),yield g("model_fallback",`${e.originalModel} -> ${e.fallbackModel}`),{kind:"continue",patch:{currentModel:e.fallbackModel,consecutive529Errors:0,consecutiveApiRetries:0,transition:void 0}};let m=e instanceof Error?e.message:String(e),f=typeof e?.status=="number"?e.status:void 0;if(!f&&m&&(m.includes("ECONNRESET")||m.includes("EPIPE"))){let h=(n.consecutiveApiRetries??0)+1;return h>X?(d.info(`stale connection retry limit reached (${X}), aborting`),yield{type:"error",turnId:s,error:m,code:"RETRIES_EXHAUSTED",usage:n.totalUsage},{kind:"return"}):(d.info(`stale connection (${m.includes("ECONNRESET")?"ECONNRESET":"EPIPE"}): retrying`),yield g("stale_connection_retry",m.slice(0,80)),{kind:"continue",patch:{consecutiveApiRetries:h,transition:void 0}})}let b=oo({status:f,message:m});if(b!==null)return d.info(`max_tokens overflow: adjusting to ${b}`),o.currentMaxOutputTokens=b,{kind:"continue",patch:{maxOutputTokensOverride:b,transition:void 0}};if(He(f)){n.consecutive529Errors++;let h=2,x=r&&n.currentModel!==r;if(n.consecutive529Errors>h&&!x&&!ye())return d.info(`transient ${f} \u8133 ${n.consecutive529Errors}: hard limit reached, aborting`),yield{type:"error",turnId:s,error:`API unavailable after ${n.consecutive529Errors} consecutive ${f} errors`,code:"API_ERROR",usage:n.totalUsage},{kind:"return"};if(n.consecutive529Errors>=Pt&&r&&n.currentModel!==r)return d.info(`529 \u8133 ${n.consecutive529Errors}: triggering fallback to ${r}`),yield g("model_fallback",`529 \u8133 ${n.consecutive529Errors}`),{kind:"continue",patch:{currentModel:r,consecutive529Errors:0,transition:void 0}};if(ye()){let C=fe(n.consecutive529Errors);d.info(`persistent retry: waiting ${C}ms (attempt ${n.consecutive529Errors})`);let p=C;for(;p>0;){if(i?.aborted)return yield{type:"error",turnId:s,error:"Aborted during retry wait",code:"ABORTED",usage:n.totalUsage},{kind:"return"};yield{type:"heartbeat",turnId:s,message:`Retrying in ${Math.ceil(p/1e3)}s (${f})`};let _=Math.min(p,wt);await new Promise(S=>setTimeout(S,_)),p-=_}return{kind:"continue",patch:{transition:void 0}}}if($e(c)){let p=to({status:f,message:m})??fe(n.consecutive529Errors);return d.info(`transient ${f}: retry in ${p}ms`),yield g("retry",`${f} retry in ${p}ms`),await new Promise(_=>setTimeout(_,p)),{kind:"continue",patch:{transition:void 0}}}d.info(`background source ${c}: not retrying ${f}`)}return{kind:"streamError",streamError:{status:f,message:m}}}var Hn=/create\s+(?:a\s+)?file|write\s+(?:a\s+)?file|make\s+(?:a\s+)?file|fix|implement|modify|update|repair|generate\s+(?:a\s+)?file|new\s+file/i;function io(e,t){return{role:"assistant",content:e,...t.length>0&&{thinkingBlocks:[...t]}}}function Gn(e){let t=e,n=t.is_error===!0||typeof t.content=="string"&&t.content.startsWith("Error:");return t.role==="tool"&&typeof t.content=="string"&&!n}function qn(e){let t=[...e].reverse().find(n=>n.role==="tool");t&&typeof t.content=="string"&&(t.content+=`
4
+ `)):""}function eo(e){try{let t=JSON.parse(e),o=[t.description,t.command,t.query,t.url,t.path,t.file_path,t.filePath,t.pattern,t.model].find(i=>typeof i=="string"&&i.trim().length>0);if(typeof o=="string")return o.trim().slice(0,240);let r=Object.keys(t);return r.length>0?r.slice(0,5).join(" / "):void 0}catch{return}}function Je(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 to(e){return e==="length"||e==="max_tokens"}function Qe(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 oo(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 no(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}async function*ro(e,t,n,o,r,i,c,s){let d=[],g,T=!1;s.debug(`single LLM round, messages: ${n.length}`);for await(let p of c.stream({model:t,messages:n,temperature:r},o,i))switch(p.type){case"delta":d.push(p.text),yield{type:"delta",turnId:e,text:p.text};break;case"usage":g={inputTokens:p.promptTokens,outputTokens:p.completionTokens,reasoningTokens:p.reasoningTokens,cacheRead:p.cacheReadTokens,cacheWrite:p.cacheCreationTokens};break;case"done":T=!0;break}if(!T){yield{type:"error",turnId:e,error:"LLM stream closed before a terminal event; the response was likely truncated upstream.",code:"RETRYABLE_TRANSIENT",usage:g??{inputTokens:0,outputTokens:0}};return}yield{type:"end",turnId:e,content:d.join(""),usage:g??{inputTokens:0,outputTokens:0},model:t}}async function*so(e){let{messages:t,contentReplacementState:n,snipRemovedIds:o,collapseStore:r,guardState:i,guardConfig:c,runtimePorts:s,hooks:d,hookCtx:g,sessionId:T,currentModel:p,log:b,recovery:h,onAutocompact:x}=e,C;{let m=await s.enforceToolResultBudget(t,n,T);C=m.messages,m.newlyReplacedCount>0&&(b.info(`tool-result-budget: persisted ${m.newlyReplacedCount} oversized tool results`),yield h("tool_result_budget",`${m.newlyReplacedCount} persisted`))}{let m=Ae(C,o);C=m.messages,m.removedCount>0&&(b.info(`snip: removed ${m.removedCount} messages, freed ~${m.tokensFreed} tokens`),yield h("snip",`${m.removedCount} messages`))}{let _=new te().compress(C,0);_.droppedCount>0&&(C=_.messages,b.info(`microcompact: cleared ${_.droppedCount} old tool results`))}if(C=Ee(C,r).messages,i.promptTokens>0){let m=c.contextWindowTokens*.75,_=s.getActiveContextCompressionEngine(),S;_?S=await _.compressAsync(C,m,{model:p,sessionId:T}):S=s.compressMessages(C,{budget:m,model:p}),S.droppedCount>0&&(C=S.messages,b.info(`autocompact: ${S.strategy}, dropped ${S.droppedCount}`),yield h("autocompact",`${S.strategy}: ${S.droppedCount} dropped`),x(),M(d,"context.after_compact",{...g,removedCount:S.droppedCount},b))}return C=Zt(C),C}async function*io(e,t){let{state:n,guardState:o,fallbackModel:r,signal:i,querySource:c,turnId:s,log:d,emitRecovery:g}=t;if(e instanceof oe&&r)return d.info(`model fallback triggered: ${e.originalModel} -> ${e.fallbackModel}`),yield g("model_fallback",`${e.originalModel} -> ${e.fallbackModel}`),{kind:"continue",patch:{currentModel:e.fallbackModel,consecutive529Errors:0,consecutiveApiRetries:0,transition:void 0}};let T=e instanceof Error?e.message:String(e),p=typeof e?.status=="number"?e.status:void 0;if(!p&&T&&(T.includes("ECONNRESET")||T.includes("EPIPE"))){let h=(n.consecutiveApiRetries??0)+1;return h>X?(d.info(`stale connection retry limit reached (${X}), aborting`),yield{type:"error",turnId:s,error:T,code:"RETRIES_EXHAUSTED",usage:n.totalUsage},{kind:"return"}):(d.info(`stale connection (${T.includes("ECONNRESET")?"ECONNRESET":"EPIPE"}): retrying`),yield g("stale_connection_retry",T.slice(0,80)),{kind:"continue",patch:{consecutiveApiRetries:h,transition:void 0}})}let b=no({status:p,message:T});if(b!==null)return d.info(`max_tokens overflow: adjusting to ${b}`),o.currentMaxOutputTokens=b,{kind:"continue",patch:{maxOutputTokensOverride:b,transition:void 0}};if(He(p)){n.consecutive529Errors++;let h=2,x=r&&n.currentModel!==r;if(n.consecutive529Errors>h&&!x&&!ye())return d.info(`transient ${p} \u8133 ${n.consecutive529Errors}: hard limit reached, aborting`),yield{type:"error",turnId:s,error:`API unavailable after ${n.consecutive529Errors} consecutive ${p} errors`,code:"API_ERROR",usage:n.totalUsage},{kind:"return"};if(n.consecutive529Errors>=Pt&&r&&n.currentModel!==r)return d.info(`529 \u8133 ${n.consecutive529Errors}: triggering fallback to ${r}`),yield g("model_fallback",`529 \u8133 ${n.consecutive529Errors}`),{kind:"continue",patch:{currentModel:r,consecutive529Errors:0,transition:void 0}};if(ye()){let C=fe(n.consecutive529Errors);d.info(`persistent retry: waiting ${C}ms (attempt ${n.consecutive529Errors})`);let m=C;for(;m>0;){if(i?.aborted)return yield{type:"error",turnId:s,error:"Aborted during retry wait",code:"ABORTED",usage:n.totalUsage},{kind:"return"};yield{type:"heartbeat",turnId:s,message:`Retrying in ${Math.ceil(m/1e3)}s (${p})`};let _=Math.min(m,Lt);await new Promise(S=>setTimeout(S,_)),m-=_}return{kind:"continue",patch:{transition:void 0}}}if($e(c)){let m=oo({status:p,message:T})??fe(n.consecutive529Errors);return d.info(`transient ${p}: retry in ${m}ms`),yield g("retry",`${p} retry in ${m}ms`),await new Promise(_=>setTimeout(_,m)),{kind:"continue",patch:{transition:void 0}}}d.info(`background source ${c}: not retrying ${p}`)}return{kind:"streamError",streamError:{status:p,message:T}}}var Gn=/create\s+(?:a\s+)?file|write\s+(?:a\s+)?file|make\s+(?:a\s+)?file|fix|implement|modify|update|repair|generate\s+(?:a\s+)?file|new\s+file/i;function ao(e,t){return{role:"assistant",content:e,...t.length>0&&{thinkingBlocks:[...t]}}}function qn(e){let t=e,n=t.is_error===!0||typeof t.content=="string"&&t.content.startsWith("Error:");return t.role==="tool"&&typeof t.content=="string"&&!n}function Kn(e){let t=[...e].reverse().find(n=>n.role==="tool");t&&typeof t.content=="string"&&(t.content+=`
5
5
 
6
- \u923F\u72C5\u7B0D NOTE: You used shell commands but did not call the write or edit tool to create/modify the file. Shell commands may fail silently or produce incorrect results on this platform. Please use the 'write' tool directly to create the requested file with the correct content.`)}function ao(e,t,n,o){return{reason:e,messages:[...t,n,o],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}}}function lo(e){if(e.stopHookActive)return null;let t=e.inputMessages.find(i=>i.role==="user"),n=typeof t?.content=="string"?t.content:"",o=Hn.test(n),r=e.distinctToolNames.has("write")||e.distinctToolNames.has("edit");if(o&&!r){e.log.info("AP1 action-verification: user requested file action but no write/edit tool was called, injecting nudge"),e.totalToolCallCount>0&&qn(e.messages);let i={role:"user",content:e.totalToolCallCount===0?"You described what to do but did not actually call any tool to write or edit a file. Please use the write or edit tool now to perform the requested action. Do not just describe the changes - actually make them.":"You used shell commands but did not call the write or edit tool to create/modify the file. Shell commands may fail on this platform. Please use the write tool directly to create the requested file with the correct content."};return ao("file_action_verification",e.messages,io(e.finalText,e.thinkingBlocks),i)}if(e.totalToolCallCount>=3&&e.distinctToolNames.has("write")&&e.messages.filter(Gn).length>=3){e.log.info("AP3 verification nudge: 3+ files created, injecting completeness check");let c={role:"user",content:"You created multiple files. Before completing, verify: (1) All imports between your files resolve to real exports. (2) No TODO, placeholder, or 'not implemented' stubs remain. (3) Functions that are imported are actually called, not just declared. If everything is correct, confirm completion. If not, fix the issues now."};return ao("multi_file_skeleton_verification",e.messages,io(e.finalText,e.thinkingBlocks),c)}return null}function Kn(e,t){return{role:"assistant",content:e,...t.length>0&&{thinkingBlocks:[...t]}}}async function co(e){if(!e.hooks)return null;let t=await e.hooks.invoke("stop",{sessionId:e.sessionId,reason:"completed"});if(t.action==="prevent")return e.log.info(`stop hook prevented continuation: ${t.reason??"no reason"}`),{action:"end",content:e.finalText};if(t.action==="abort"){let n=t.reason??"Stop hook requested continuation";e.log.info(`stop hook blocking: ${n}`);let o={role:"user",content:n};return{action:"continue",messages:[...e.messages,Kn(e.finalText,e.thinkingBlocks),o],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}}}return null}var zn=5;function Wn(e){return e.inputTokens+e.outputTokens+(e.reasoningTokens??0)}function Xn(e,t){return{role:"assistant",content:e,...t.length>0&&{thinkingBlocks:[...t]}}}function uo(e){if(!e.tokenBudget||e.tokenBudget<=0||e.budgetContinuationCount>=zn)return null;let t=Wn(e.totalUsage),n=t/e.tokenBudget*100,o=t-e.lastBudgetGlobalTokens;if(e.budgetContinuationCount>=It&&o<we&&e.lastBudgetDeltaTokens<we)return e.log.info(`token budget early stop: diminishing returns at ${Math.round(n)}% (delta=${o})`),null;if(n>=90)return null;let i=e.budgetContinuationCount+1,c={role:"user",content:e.getBudgetContinuationMessage(n,t,e.tokenBudget)};return e.log.info(`token budget continuation #${i}: ${Math.round(n)}% used`),{messages:[...e.messages,Xn(e.finalText,e.thinkingBlocks),c],budgetContinuationCount:i,lastBudgetDeltaTokens:o,lastBudgetGlobalTokens:t,recoveryDetail:`${Math.round(n)}% used (#${i})`,transition:{reason:"token_budget_continuation"}}}function Ze(e){if(e.totalToolCallCount<=0)return null;let t={ok:!0,toolCallCount:e.totalToolCallCount,distinctToolCount:e.distinctToolNames.size,multiStep:e.totalToolCallCount>=2,hasSubAgent:!1,feedback:null,existingSkillName:null};return Oe(t,{tools:[...e.distinctToolNames],projectRoot:e.projectRoot})}function po(e,t){let n=[],o=[];for(let r of e){let i=t.get(r.function.name)??0;i>=de?o.push({call:r,failCount:i,error:`Tool "${r.function.name}" has failed ${i} times this turn with different arguments. The target likely does not exist. Stop trying variations and report the issue to the user.`}):n.push(r)}return{allowed:n,blocked:o}}function mo(){return{role:"user",content:"Tool calls were blocked because the tool has failed too many times with different arguments. The resource you are looking for does not exist. Stop trying variations and tell the user what happened."}}function go(e){if(e.ok&&!e.softEmpty)return;let t=e.toolFailureCounts.get(e.toolName)??0;e.toolFailureCounts.set(e.toolName,t+1)}function fo(e){let t=[];for(let[n,o]of e.toolFailureCounts)o>=de&&(e.snapshot.get(n)??0)<de&&t.push({role:"user",content:`Tool "${n}" has now failed/returned empty results ${o} times with different arguments. The target clearly does not exist. Do NOT call "${n}" again. Report the result to the user immediately.`});return t}async function*yo(e,t,n,o){let{turnId:r,sessionId:i,messages:c,tools:s,model:d,apiKey:g,temperature:m=0,hooks:f,signal:b}=e,h={sessionId:i,turnId:r},x=e.maxTurns??0,C=e.querySource,p=e.runtimePorts.resolveToolEligibility(s,e.toolEligibilityContext),_=p.eligibleTools;for(let y of p.blockedTools)yield{type:"tool_blocked",turnId:r,callId:"",name:y.toolName,reason:"blocked-by-policy"};if(!_.length){yield*no(r,d,c,g,m,b,t,o);return}let S=Jt(e.maxRounds),F={contextWindowTokens:e.contextWindowTokens??_t,responseBufferTokens:St,maxOutputTokens:e.maxOutputTokens??Mt,abortSignal:b,reactiveCompactEnabled:!0,outputEscalationEnabled:!0},U=new Set,N=0,E=_,ne,Te=!1,et=0,a={messages:[...c],maxOutputTokensRecoveryCount:0,hasAttemptedReactiveCompact:!1,maxOutputTokensOverride:void 0,turnCount:1,transition:void 0,guardState:Ge(F),reactiveCompactState:Xe(),toolLoopState:ge({maxRounds:S,replayMessages:[...c]}).state,consecutiveFailedRounds:0,finalText:"",totalUsage:{inputTokens:0,outputTokens:0},collapseStore:ve(),currentModel:d,consecutive529Errors:0,consecutiveApiRetries:0,stopHookActive:void 0,lastResponseId:void 0,snipRemovedIds:new Set,contentReplacementState:e.runtimePorts.createContentReplacementState(),budgetContinuationCount:0,lastBudgetDeltaTokens:0,lastBudgetGlobalTokens:0,identicalCallCounts:new Map,toolFailureCounts:new Map,fileReadCounts:new Map,recoveryTrace:new Map},tt=Math.max(x*5,200),ot=0,P=(y,$)=>(a.recoveryTrace.set(y,(a.recoveryTrace.get(y)??0)+1),{type:"recovery",turnId:r,action:y,detail:$}),z=y=>({type:"end",turnId:r,content:y,usage:a.totalUsage,model:a.currentModel,...a.recoveryTrace.size>0?{recoveryTrace:Object.fromEntries(a.recoveryTrace)}:{}});for(;;){if(ot++,ot>tt){o.info(`hard iteration cap reached (${tt}), forcing completion`);let l=a.finalText||V(a.messages,o);yield z(l);return}let{messages:y,maxOutputTokensRecoveryCount:$,maxOutputTokensOverride:nt,turnCount:J,guardState:A,reactiveCompactState:D,collapseStore:he}=a,{toolLoopState:I}=a;if(ne){try{let l=await ne;l&&(yield{type:"tool_use_summary",turnId:r,summary:l})}catch{}ne=void 0}if(e.refreshTools&&J>1){let l=e.refreshTools();l!==E&&(E=l,o.debug(`tools refreshed: ${l.length} tools`))}if(We(A,F)){o.info(`turn aborted by guard at turn ${J}`),yield{type:"error",turnId:r,error:"Turn aborted",code:"ABORTED",usage:a.totalUsage};return}let H=qe(A,F);if(H.level==="blocking"){H.reason==="prompt_too_long"&&Y(D)&&(D.attemptedThisTurn=!0,A.hasAttemptedReactiveCompact=!0,o.info(`token budget blocking (${H.reason}), reactive compact needed`),yield P("reactive_compact","token budget pre-check")),o.info(`token budget blocking (${H.reason}), ending tool loop`);break}H.level==="warning"&&o.info(`token budget warning: ${H.usagePercent}% used, ${H.remainingTokens} remaining`);let re=yield*ro({messages:y,contentReplacementState:a.contentReplacementState,snipRemovedIds:a.snipRemovedIds,collapseStore:he,guardState:A,guardConfig:F,runtimePorts:e.runtimePorts,hooks:f,hookCtx:h,sessionId:i,currentModel:a.currentModel,log:o,recovery:P,onAutocompact:()=>{a.hasAttemptedReactiveCompact=!1}}),xo=e.toolChoice==="required"&&Te?"auto":e.toolChoice??"auto",se=Ne({tools:E,toolChoice:xo}),Q=ge({maxRounds:S,replayMessages:re,lastStopReason:I.lastStopReason,options:{stopReason:I.lastStopReason}}),rt=se.extraSystemPrompt?[{role:"system",content:se.extraSystemPrompt},...Q.state.replayMessages]:Q.state.replayMessages;I=Q.state,Q.recoveryActions.length>0&&o.debug(`tool loop recovery: ${Q.recoveryActions.map(l=>l.detail??l.kind).join("; ")}`),o.debug(`turn ${J}, messages: ${rt.length}`),M(f,"turn.before_inference",{...h,model:a.currentModel},o);let Ce=!1,ke=[],st=new Map,it="stop",w,k=null,ie=!1,Z=[],B=[];try{for await(let l of t.stream({model:a.currentModel,messages:rt,tools:se.tools,toolChoice:se.normalizedToolChoice??"auto",temperature:m,maxTokens:(nt??A.currentMaxOutputTokens)||void 0,streamRequired:e.streamRequired,previousResponseId:a.lastResponseId,reasoning:e.reasoning,promptCacheKey:e.promptCacheKey,promptCacheRetention:e.promptCacheRetention,serviceTier:e.serviceTier,openaiBuiltinTools:e.openaiBuiltinTools,maxToolCalls:e.maxToolCalls,parallelToolCalls:e.parallelToolCalls,textVerbosity:e.textVerbosity},g,b))switch(l.type){case"delta":ke.push(l.text);break;case"tool_call_delta":Ce=!0,Ye(st,l);break;case"reasoning_delta":Z.push(l.text);break;case"reasoning_block_complete":l.signature&&B.push({thinking:Z.join(""),signature:l.signature}),Z.length=0;break;case"usage":w={inputTokens:l.promptTokens,outputTokens:l.completionTokens,reasoningTokens:l.reasoningTokens,cacheRead:l.cacheReadTokens,cacheWrite:l.cacheCreationTokens};break;case"response_id":a.lastResponseId=l.id;break;case"annotations":yield{type:"annotations",turnId:r,annotations:l.annotations};break;case"builtin_tool_status":yield{type:"heartbeat",turnId:r,message:`${l.toolType}: ${l.event}`};break;case"done":it=l.finishReason;break}if(Ce||M(f,"turn.after_inference",{...h,model:a.currentModel},o),e.postSamplingHooks&&e.postSamplingHooks.length>0){let l=a.currentModel;for(let u of e.postSamplingHooks)try{u({messages:[...re],model:l,sessionId:i})}catch{}}}catch(l){let u=yield*so(l,{state:a,guardState:A,fallbackModel:e.fallbackModel,signal:b,querySource:C,turnId:r,log:o,emitRecovery:P});if(u.kind==="return")return;if(u.kind==="continue"){a={...a,...u.patch};continue}k=u.streamError}if(k&&M(f,"turn.after_inference",{...h,model:a.currentModel,response:{error:k.message}},o),k)if(Je(k))ie=!0,o.info(`withheld prompt_too_long error (status=${k.status})`);else if(Qe(k))ie=!0,o.info(`withheld media_size error (status=${k.status})`);else{let l=Ke({status:k.status??500,message:k.message},A,F);if(l.action==="reactive_compact"&&Y(D)&&(D.attemptedThisTurn=!0,A.hasAttemptedReactiveCompact=!0,yield P("reactive_compact",`API ${k.status??500}: ${k.message}`)),l.action==="retry"){let T=(a.consecutiveApiRetries??0)+1;if(T>X){o.info(`API retry limit reached (${X}), aborting`);let R=W(k.status,k.message);yield{type:"error",turnId:r,error:k.message,code:R,usage:a.totalUsage};return}yield P("retry",l.reason),a={...a,consecutiveApiRetries:T,transition:void 0};continue}let u=W(k.status,k.message);M(f,"stop.failure",{sessionId:i,reason:u,error:k.message},o),yield{type:"error",turnId:r,error:k.message,code:u,usage:a.totalUsage};return}w&&(a.totalUsage.inputTokens+=w.inputTokens,a.totalUsage.outputTokens+=w.outputTokens,w.reasoningTokens&&(a.totalUsage.reasoningTokens=(a.totalUsage.reasoningTokens??0)+w.reasoningTokens),w.cacheRead&&(a.totalUsage.cacheRead=(a.totalUsage.cacheRead??0)+w.cacheRead),w.cacheWrite&&(a.totalUsage.cacheWrite=(a.totalUsage.cacheWrite??0)+w.cacheWrite)),w?.inputTokens&&(A.promptTokens=w.inputTokens);let at=ke.join(""),O=[...st.values()].map(l=>({id:l.id||`tc_${r}_${J}_${Math.random().toString(36).slice(2,8)}`,type:"function",function:{name:l.name,arguments:l.arguments}}));if(O.length===0&&!Ce){if(at&&(a.finalText=at),e.toolChoice==="required"&&!Te&&E.length>0&&et<2){et++;let v=E.map(j=>j.function.name).filter(Boolean).slice(0,8).join(", ");a={...a,messages:[...y,{role:"user",content:`You must call one available tool before answering. Available tools for this request: ${v}. Do not answer from memory, prior context, or guesses.`}],finalText:"",transition:{reason:"next_turn"}};continue}if(ie&&k&&Je(k)){if(a.transition?.reason!=="collapse_drain_retry"){let v=Ie(re,he);if(v.committed>0){o.info(`collapse drain: committed ${v.committed} stages`),yield P("collapse_drain",`${v.committed} stages committed`),a={...a,messages:v.messages,transition:{reason:"collapse_drain_retry",committed:v.committed}};continue}}if(Y(D)){D.attemptedThisTurn=!0,A.hasAttemptedReactiveCompact=!0,o.info("withheld 413: reactive compact attempt"),yield P("reactive_compact","withheld prompt_too_long"),a={...a,hasAttemptedReactiveCompact:!0,transition:{reason:"reactive_compact_retry"}};continue}o.info("withheld 413: recovery exhausted, surfacing error"),M(f,"stop.failure",{sessionId:i,reason:"prompt_too_long",error:k.message},o),yield{type:"error",turnId:r,error:k.message,code:"PROMPT_TOO_LONG",usage:a.totalUsage};return}if(ie&&k&&Qe(k)){if(Y(D)){D.attemptedThisTurn=!0,A.hasAttemptedReactiveCompact=!0,o.info("withheld media error: reactive compact strip-retry"),yield P("reactive_compact","media error strip-retry"),a={...a,hasAttemptedReactiveCompact:!0,transition:{reason:"reactive_compact_retry"}};continue}o.info("withheld media error: recovery exhausted"),M(f,"stop.failure",{sessionId:i,reason:"media_error",error:k.message},o),yield{type:"error",turnId:r,error:k.message,code:"IMAGE_ERROR",usage:a.totalUsage};return}if(eo(it)){A.consecutiveTruncations+=1;let v=e.modelMaxOutputTokens??At,j=ze(A,F,v);if(j.shouldEscalate&&nt===void 0){A.currentMaxOutputTokens=j.newMax,o.info(`max_output_tokens escalate: ${j.newMax} tokens`),yield P("output_escalation",`${j.newMax} tokens`),a={...a,maxOutputTokensOverride:Et,transition:{reason:"max_output_tokens_escalate"}};continue}if($<vt){let vo={role:"user",content:"Output token limit hit. Resume directly - 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 #${$+1}`),yield P("max_output_tokens_recovery",`attempt ${$+1}`),a={...a,messages:[...re,vo],maxOutputTokensRecoveryCount:$+1,maxOutputTokensOverride:void 0,transition:{reason:"max_output_tokens_recovery",attempt:$+1}};continue}o.info("max_output_tokens recovery exhausted, completing with partial content")}else A.consecutiveTruncations=0;I=me(I,{replayMessages:y,lastStopReason:"completed"});let l=await co({hooks:f,sessionId:i,messages:y,finalText:a.finalText,thinkingBlocks:B,log:o});if(l?.action==="end"){yield z(l.content);return}if(l?.action==="continue"){a={...a,messages:l.messages,stopHookActive:l.stopHookActive,transition:l.transition};continue}let u=uo({tokenBudget:e.tokenBudget,totalUsage:a.totalUsage,budgetContinuationCount:a.budgetContinuationCount,lastBudgetDeltaTokens:a.lastBudgetDeltaTokens,lastBudgetGlobalTokens:a.lastBudgetGlobalTokens,messages:y,finalText:a.finalText,thinkingBlocks:B,getBudgetContinuationMessage:e.runtimePorts.getBudgetContinuationMessage,log:o});if(u){yield P("budget_continuation",u.recoveryDetail),a={...a,messages:u.messages,budgetContinuationCount:u.budgetContinuationCount,lastBudgetDeltaTokens:u.lastBudgetDeltaTokens,lastBudgetGlobalTokens:u.lastBudgetGlobalTokens,transition:u.transition};continue}let T=lo({inputMessages:c,messages:y,finalText:a.finalText,thinkingBlocks:B,stopHookActive:a.stopHookActive,totalToolCallCount:N,distinctToolNames:U,log:o});if(T){a={...a,messages:T.messages,stopHookActive:T.stopHookActive,transition:T.transition};continue}let R=Ze({totalToolCallCount:N,distinctToolNames:U,projectRoot:e.projectRoot});R&&(yield{type:"skill_instruction",turnId:r,instruction:R});let L=a.finalText||V(y,o);for(let v of ke)yield{type:"delta",turnId:r,text:v};yield z(L);return}let _o=B.length===0&&Z.length>0?Z.join(""):void 0;y.push(_e(O,void 0,B.length>0?B:void 0,_o)),I=je(I,{replayMessages:y,pendingToolCallIds:O.map(l=>l.id),completedToolCallIds:I.completedToolCallIds,lastStopReason:"tool_calls"});let ae=a.identicalCallCounts,lt=[],le=[],ct=!1;for(let l of O){let u=`${l.function.name}::${l.function.arguments}`,T=ae.get(u)??0;ae.set(u,T+1),T+1>xt?(le.push(l),ct||(ct=!0,o.info(`AP4 blocked: ${l.function.name} repeated ${T+1}x`))):lt.push(l)}let ce=[];for(let l of le){let u=ae.get(`${l.function.name}::${l.function.arguments}`),T=Ve(y,l.function.name),R=T?`This exact tool call has been attempted ${u} times. Last error: ${T}. Do not retry. Report this error to the user.`:`This exact tool call has been attempted ${u} times and keeps failing. Do not retry it. Report the issue to the user or try a completely different approach.`,L=ue(l.id,{ok:!1,error:R});y.push(L),ce.push(l.id),U.add(l.function.name),N++,yield{type:"tool_result",turnId:r,callId:l.id,name:l.function.name,ok:!1,error:R}}if(le.length>0){let l=Ve(y,le[0].function.name),u={role:"user",content:"Tool calls were blocked because you repeated them with identical arguments too many times. "+(l?`The error was: "${l}". Tell the user about this error. `:"The operation is not working. ")+"Stop retrying and report the result to the user."};y.push(u)}let Re=po(lt,a.toolFailureCounts),be=Re.allowed;if(Re.blocked.length>0){for(let l of Re.blocked){let u=l.call,T=ue(u.id,{ok:!1,error:l.error});y.push(T),ce.push(u.id),U.add(u.function.name),N++,yield{type:"tool_result",turnId:r,callId:u.id,name:u.function.name,ok:!1,error:l.error},o.info(`variant tool blocked: ${u.function.name} failed ${l.failCount}x with different args`)}y.push(mo())}for(let l of be){let u=l.function.arguments,T=E.find(R=>R.function.name===l.function.name);if(T?.backfillObservableInput)try{let R=JSON.parse(l.function.arguments),L={...R};T.backfillObservableInput(L),Object.keys(L).some(j=>!(j in R))&&(u=JSON.stringify(L))}catch{}yield{type:"tool_call",turnId:r,callId:l.id,name:l.function.name,arguments:u,inputSummary:Zt(u)}}let So=new Map(a.toolFailureCounts);try{let l=e.runtimePorts.createStreamingToolExecutor({toolInvoker:n,hooks:f,sessionId:i,turnId:r,log:o,signal:b,maxConcurrentTools:e?.maxConcurrentTools});for(let u of be)l.addTool(u);for await(let u of l.getRemainingResults()){if(u.blocked&&(yield{type:"tool_blocked",turnId:r,callId:u.callId,name:u.toolName,reason:u.blockReason??"blocked"}),y.push(u.message),ce.push(u.callId),U.add(u.toolName),N++,go({toolFailureCounts:a.toolFailureCounts,toolName:u.toolName,ok:u.ok,softEmpty:u.ok&&Vt(u)}),u.ok&&u.toolName==="read"){let T=be.find(R=>R.id===u.callId);if(T)try{let R=JSON.parse(T.function.arguments),L=R.file_path??R.path??R.filePath??"";if(L){let v=a.fileReadCounts.get(L)??0;a.fileReadCounts.set(L,v+1)}}catch{}}yield Wt(r,u);for(let T of Xt(r,u))yield T;for(let T of Yt({turnId:r,result:u,toolCalls:O}))yield T}}catch(l){let u=l instanceof Error?l.message:String(l);yield{type:"error",turnId:r,error:u,code:"TOOL_EXECUTION_ERROR",usage:a.totalUsage};return}if(y.push(...fo({toolFailureCounts:a.toolFailureCounts,snapshot:So})),I=me(I,{replayMessages:y,completedToolCallIds:[...I.completedToolCallIds,...ce],lastStopReason:"tool_calls"}),e.toolChoice==="required"&&O.length>0&&(Te=!0),e.generateToolUseSummary&&O.length>0){let l=O.map(u=>({name:u.function.name,arguments:u.function.arguments}));ne=e.generateToolUseSummary(l).catch(()=>null)}let Mo=O.length>0&&O.every(l=>{let u=y.find(R=>R?.role==="tool"&&R?.tool_call_id===l.id);if(!u)return!0;let T=u.content;return typeof T=="string"&&T.startsWith("Error: ")}),ee=a.consecutiveFailedRounds;if(Mo){if(ee+=1,ee>=bt){let l=a.finalText||V(y,o);o.info(`early exit: ${ee} consecutive failed rounds, returning ${a.finalText?"partial":"fallback"} response`),yield z(l);return}}else ee=0;let Ao=3,ut=[...a.fileReadCounts.entries()].filter(([,l])=>l>=Ao);if(ut.length>0){let l=ut.map(([T])=>T).join(", ");o.info(`AP5: file read cycle detected on ${l}, injecting nudge`);let u={role:"user",content:`You are reading the same files repeatedly (${l}). This indicates a circular dependency or cycle. Stop reading files, summarize your findings so far, and explain the circular structure to the user.`};y.push(u),a.fileReadCounts.clear()}let xe=J+1;if(x>0&&xe>x){if(o.info(`max turns reached (${x}), completing`),f){let u=await f.invoke("stop",{sessionId:i,reason:"max_turns"});if(u.action==="abort"){let T=u.reason??"Stop hook requested continuation after max_turns",R={role:"assistant",content:a.finalText,...B.length>0&&{thinkingBlocks:[...B]}};a={...a,messages:[...y,R,{role:"user",content:T}],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}};continue}}let l=a.finalText||V(y,o);yield z(l);return}if(xe>S){o.info(`tool loop budget exhausted (${S} rounds), returning`);let l=Ze({totalToolCallCount:N,distinctToolNames:U,projectRoot:e.projectRoot});l&&(yield{type:"skill_instruction",turnId:r,instruction:l});let u=a.finalText||V(y,o);yield z(u);return}a={messages:y,maxOutputTokensRecoveryCount:0,hasAttemptedReactiveCompact:!1,maxOutputTokensOverride:void 0,turnCount:xe,transition:{reason:"next_turn"},guardState:A,reactiveCompactState:D,toolLoopState:I,consecutiveFailedRounds:ee,finalText:a.finalText,totalUsage:a.totalUsage,collapseStore:he,currentModel:a.currentModel,consecutive529Errors:0,consecutiveApiRetries:0,stopHookActive:a.stopHookActive,lastResponseId:a.lastResponseId,snipRemovedIds:a.snipRemovedIds,contentReplacementState:a.contentReplacementState,budgetContinuationCount:a.budgetContinuationCount,lastBudgetDeltaTokens:a.lastBudgetDeltaTokens,lastBudgetGlobalTokens:a.lastBudgetGlobalTokens,identicalCallCounts:ae,toolFailureCounts:a.toolFailureCounts,fileReadCounts:a.fileReadCounts,recoveryTrace:a.recoveryTrace}}}var Vn=["\u63A5\u5355\u91D1\u989D","\u5408\u540C\u91D1\u989D","\u62A5\u4EF7","\u9884\u7B97","\u91D1\u989D","price","amount","contract amount"];function Co(e){let t=Jn(e),n=["[Recalled memories]","- L1 project MD is project-scoped working memory.","- L2 long-term memory is cross-project canonical memory.","- If L1 and L2 conflict on the same entity/fact, do not silently merge or choose. Surface the conflict and ask the user to confirm. For current-project operational tasks, use L1 only as a project-scoped clue until confirmed into L2."];if(t.length>0){n.push("[Memory conflict detected]");for(let o of t)n.push(`- entity: ${o.entity}; fact: ${o.predicate}; L1 project MD says: ${ho(o.l1Amount)}; L2 long-term says: ${ho(o.l2Amount)}; action: ask the user which value is current before using it.`)}for(let o of e){let r=er(o);n.push(`- [${r}] ${o.text}`)}return n.join(`
7
- `)}function Jn(e){let t=e.filter(r=>r.source==="l1-project-md").flatMap(r=>To(r.text)),n=e.filter(r=>r.source==="l2-long-term").flatMap(r=>To(r.text)),o=[];for(let r of t)for(let i of n)r.entity===i.entity&&r.predicate===i.predicate&&r.amount!==i.amount&&o.push({entity:r.entity,predicate:r.predicate,l1Amount:r.amount,l2Amount:i.amount,l1Text:r.text,l2Text:i.text});return tr(o)}function To(e){let t=[];for(let n of e.split(/\r?\n/)){let o=n.trim();if(o)for(let r of Vn){if(r==="\u91D1\u989D"&&/(接单金额|合同金额)/u.test(o))continue;let i=new RegExp(`${or(r)}[^0-9.\u4E07kK,]{0,12}([0-9][0-9.,]*\\s*(?:\u4E07|k|K)?)`,"gi");for(let c of o.matchAll(i)){let s=Zn(c[1]);s!==null&&t.push({entity:Qn(o,r),predicate:r,amount:s,text:o})}}}return t}function Qn(e,t){if(/Galaxy\s+Tech/i.test(e))return"Galaxy Tech";if(e.includes("\u7528\u6237"))return"\u7528\u6237";let n=e.toLowerCase().indexOf(t.toLowerCase()),r=(n>=0?e.slice(0,n):"").replace(/[#*`:\-,。;;,.]/g," ").trim().split(/\s+/).filter(Boolean);return r[r.length-1]??"unknown"}function Zn(e){let t=e.replace(/,/g,"").replace(/\s+/g,"").trim(),n=t.endsWith("\u4E07")?1e4:/k$/i.test(t)?1e3:1,o=Number(t.replace(/[万kK]$/u,""));return Number.isFinite(o)?o*n:null}function er(e){if(e.label)return e.label;switch(e.source){case"l1-project-md":return"L1 project MD";case"l2-long-term":return"L2 long-term";case"skill":return"Skill";case"system":return"System";default:return"Memory"}}function ho(e){return Number.isInteger(e)?String(e):String(Number(e.toFixed(4)))}function tr(e){let t=new Set;return e.filter(n=>{let o=`${n.entity}\0${n.predicate}\0${n.l1Amount}\0${n.l2Amount}`;return t.has(o)?!1:(t.add(o),!0)})}function or(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var nr=8192;async function ko(e){let{hooks:t,detectRecallCategories:n,log:o,sessionId:r,turnId:i,query:c}=e;try{let s=n(c),g=(await t.invoke("memory.before_recall",{sessionId:r,turnId:i,query:c,preferredCategories:s.preferred.length>0?s.preferred:void 0,deprioritizedCategories:s.deprioritized.length>0?s.deprioritized:void 0}))?.context?.recalledMemories,m=null;if(g&&g.length>0){let f=0,b=[];for(let h of g){let x=(h.text?.length??0)*2;if(f+x>nr)break;b.push(h),f+=x}b.length>0&&(m=`[Recalled memories \u2014 context priority: project-specific facts override general user preferences when they conflict]
8
- ${Co(b)}`)}return M(t,"memory.after_recall",{sessionId:r,turnId:i,blockCount:g?.length??0},o),m}catch{return null}}var bo=class{transport;apiKey;toolInvoker;log;hooks;maxRounds;projectRoot;runtimePorts;constructor(t){this.transport=t.llmTransport,this.apiKey=t.apiKey,this.toolInvoker=t.toolInvoker,this.log=t.log,this.hooks=t.hooks,this.projectRoot=t.projectRoot,this.runtimePorts=t.runtimePorts,this.maxRounds=Math.min(t.maxRounds??25,100)}async*run(t,n){let{turnId:o,messages:r,tools:i,systemPrompt:c,config:s}=t,d={sessionId:t.sessionId,turnId:o};yield{type:"start",turnId:o},M(this.hooks,"turn.submitted",{...d,prompt:r[r.length-1]?.content??void 0},this.log);let g=Ue(r),m=[];if(c&&m.push({role:"system",content:c}),m.push(...g),this.hooks){let h=g.filter(C=>C.role==="user").pop(),x=typeof h?.content=="string"?h.content.slice(0,500):void 0;if(x){let C=await ko({hooks:this.hooks,detectRecallCategories:p=>this.runtimePorts.detectRecallCategories(p),log:this.log,sessionId:t.sessionId,turnId:o,query:x});C&&m.splice(c?1:0,0,{role:"system",content:C})}}let f=s?.model??"",b=Math.min(s?.maxRounds??this.maxRounds,100);try{let h=async _=>{let S=this.runtimePorts.resolveModelForPurpose("smallModel");if(!S)return null;try{let F=_.map(E=>`${E.name}(${E.arguments.slice(0,200)})`).join(", "),U=this.transport.stream({model:S,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:F}],tools:[],maxTokens:60},s?.apiKey??this.apiKey),N="";for await(let E of U)E.type==="delta"&&(N+=E.text);return N.trim()||null}catch{return null}},x=s?.reasoning;s?.reasoning?.effort==="auto"&&(x={...s?.reasoning,effort:"medium"});let C={turnId:o,sessionId:t.sessionId,messages:m,tools:i,model:f,apiKey:s?.apiKey??this.apiKey,temperature:s?.temperature,maxRounds:b,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,reasoning:x,promptCacheKey:s?.promptCacheKey,promptCacheRetention:s?.promptCacheRetention,serviceTier:s?.serviceTier,openaiBuiltinTools:s?.openaiBuiltinTools,maxToolCalls:s?.maxToolCalls,parallelToolCalls:s?.parallelToolCalls,textVerbosity:s?.textVerbosity,projectRoot:this.projectRoot,generateToolUseSummary:h,runtimePorts:this.runtimePorts.toolLoop,signal:n},p;for await(let _ of yo(C,this.transport,this.toolInvoker,this.log))p=_,yield _;p?.type==="end"?M(this.hooks,"turn.completed",{...d},this.log):p?.type==="error"&&M(this.hooks,"turn.failed",{...d,code:p.code,error:p.error},this.log)}catch(h){if(n?.aborted)M(this.hooks,"turn.failed",{...d,code:"ABORTED",error:"Turn aborted"},this.log),yield{type:"error",turnId:o,error:"Turn aborted",code:"ABORTED"};else{let x=h instanceof Error?h.message:String(h),C=typeof h?.status=="number"?h.status:void 0,p=W(C,x);this.log.error(`turn ${o} error [${p}, retryable=${Me(p)}]: ${x}`),M(this.hooks,"turn.failed",{...d,code:p,error:x},this.log),yield{type:"error",turnId:o,error:x,code:p}}}}};export{bo as Agent};
6
+ \u923F\u72C5\u7B0D NOTE: You used shell commands but did not call the write or edit tool to create/modify the file. Shell commands may fail silently or produce incorrect results on this platform. Please use the 'write' tool directly to create the requested file with the correct content.`)}function lo(e,t,n,o){return{reason:e,messages:[...t,n,o],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}}}function co(e){if(e.stopHookActive)return null;let t=e.inputMessages.find(i=>i.role==="user"),n=typeof t?.content=="string"?t.content:"",o=Gn.test(n),r=e.distinctToolNames.has("write")||e.distinctToolNames.has("edit");if(o&&!r){e.log.info("AP1 action-verification: user requested file action but no write/edit tool was called, injecting nudge"),e.totalToolCallCount>0&&Kn(e.messages);let i={role:"user",content:e.totalToolCallCount===0?"You described what to do but did not actually call any tool to write or edit a file. Please use the write or edit tool now to perform the requested action. Do not just describe the changes - actually make them.":"You used shell commands but did not call the write or edit tool to create/modify the file. Shell commands may fail on this platform. Please use the write tool directly to create the requested file with the correct content."};return lo("file_action_verification",e.messages,ao(e.finalText,e.thinkingBlocks),i)}if(e.totalToolCallCount>=3&&e.distinctToolNames.has("write")&&e.messages.filter(qn).length>=3){e.log.info("AP3 verification nudge: 3+ files created, injecting completeness check");let c={role:"user",content:"You created multiple files. Before completing, verify: (1) All imports between your files resolve to real exports. (2) No TODO, placeholder, or 'not implemented' stubs remain. (3) Functions that are imported are actually called, not just declared. If everything is correct, confirm completion. If not, fix the issues now."};return lo("multi_file_skeleton_verification",e.messages,ao(e.finalText,e.thinkingBlocks),c)}return null}function zn(e,t){return{role:"assistant",content:e,...t.length>0&&{thinkingBlocks:[...t]}}}async function uo(e){if(!e.hooks)return null;let t=await e.hooks.invoke("stop",{sessionId:e.sessionId,reason:"completed"});if(t.action==="prevent")return e.log.info(`stop hook prevented continuation: ${t.reason??"no reason"}`),{action:"end",content:e.finalText};if(t.action==="abort"){let n=t.reason??"Stop hook requested continuation";e.log.info(`stop hook blocking: ${n}`);let o={role:"user",content:n};return{action:"continue",messages:[...e.messages,zn(e.finalText,e.thinkingBlocks),o],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}}}return null}var Wn=5;function Xn(e){return e.inputTokens+e.outputTokens+(e.reasoningTokens??0)}function Yn(e,t){return{role:"assistant",content:e,...t.length>0&&{thinkingBlocks:[...t]}}}function po(e){if(!e.tokenBudget||e.tokenBudget<=0||e.budgetContinuationCount>=Wn)return null;let t=Xn(e.totalUsage),n=t/e.tokenBudget*100,o=t-e.lastBudgetGlobalTokens;if(e.budgetContinuationCount>=wt&&o<we&&e.lastBudgetDeltaTokens<we)return e.log.info(`token budget early stop: diminishing returns at ${Math.round(n)}% (delta=${o})`),null;if(n>=90)return null;let i=e.budgetContinuationCount+1,c={role:"user",content:e.getBudgetContinuationMessage(n,t,e.tokenBudget)};return e.log.info(`token budget continuation #${i}: ${Math.round(n)}% used`),{messages:[...e.messages,Yn(e.finalText,e.thinkingBlocks),c],budgetContinuationCount:i,lastBudgetDeltaTokens:o,lastBudgetGlobalTokens:t,recoveryDetail:`${Math.round(n)}% used (#${i})`,transition:{reason:"token_budget_continuation"}}}function Ze(e){if(e.totalToolCallCount<=0)return null;let t={ok:!0,toolCallCount:e.totalToolCallCount,distinctToolCount:e.distinctToolNames.size,multiStep:e.totalToolCallCount>=2,hasSubAgent:!1,feedback:null,existingSkillName:null};return Oe(t,{tools:[...e.distinctToolNames],projectRoot:e.projectRoot})}function mo(e,t){let n=[],o=[];for(let r of e){let i=t.get(r.function.name)??0;i>=de?o.push({call:r,failCount:i,error:`Tool "${r.function.name}" has failed ${i} times this turn with different arguments. The target likely does not exist. Stop trying variations and report the issue to the user.`}):n.push(r)}return{allowed:n,blocked:o}}function go(){return{role:"user",content:"Tool calls were blocked because the tool has failed too many times with different arguments. The resource you are looking for does not exist. Stop trying variations and tell the user what happened."}}function fo(e){if(e.ok&&!e.softEmpty)return;let t=e.toolFailureCounts.get(e.toolName)??0;e.toolFailureCounts.set(e.toolName,t+1)}function yo(e){let t=[];for(let[n,o]of e.toolFailureCounts)o>=de&&(e.snapshot.get(n)??0)<de&&t.push({role:"user",content:`Tool "${n}" has now failed/returned empty results ${o} times with different arguments. The target clearly does not exist. Do NOT call "${n}" again. Report the result to the user immediately.`});return t}async function*To(e,t,n,o){let{turnId:r,sessionId:i,messages:c,tools:s,model:d,apiKey:g,temperature:T=0,hooks:p,signal:b}=e,h={sessionId:i,turnId:r},x=e.maxTurns??0,C=e.querySource,m=e.runtimePorts.resolveToolEligibility(s,e.toolEligibilityContext),_=m.eligibleTools;for(let f of m.blockedTools)yield{type:"tool_blocked",turnId:r,callId:"",name:f.toolName,reason:"blocked-by-policy"};if(!_.length){yield*ro(r,d,c,g,T,b,t,o);return}let S=Qt(e.maxRounds),F={contextWindowTokens:e.contextWindowTokens??St,responseBufferTokens:Mt,maxOutputTokens:e.maxOutputTokens??At,abortSignal:b,reactiveCompactEnabled:!0,outputEscalationEnabled:!0},U=new Set,N=0,E=_,ne,Te=!1,et=0,l={messages:[...c],maxOutputTokensRecoveryCount:0,hasAttemptedReactiveCompact:!1,maxOutputTokensOverride:void 0,turnCount:1,transition:void 0,guardState:Ge(F),reactiveCompactState:Xe(),toolLoopState:ge({maxRounds:S,replayMessages:[...c]}).state,consecutiveFailedRounds:0,finalText:"",totalUsage:{inputTokens:0,outputTokens:0},collapseStore:ve(),currentModel:d,consecutive529Errors:0,consecutiveApiRetries:0,stopHookActive:void 0,lastResponseId:void 0,snipRemovedIds:new Set,contentReplacementState:e.runtimePorts.createContentReplacementState(),budgetContinuationCount:0,lastBudgetDeltaTokens:0,lastBudgetGlobalTokens:0,identicalCallCounts:new Map,toolFailureCounts:new Map,fileReadCounts:new Map,recoveryTrace:new Map},tt=Math.max(x*5,200),ot=0,L=(f,$)=>(l.recoveryTrace.set(f,(l.recoveryTrace.get(f)??0)+1),{type:"recovery",turnId:r,action:f,detail:$}),z=f=>({type:"end",turnId:r,content:f,usage:l.totalUsage,model:l.currentModel,...l.recoveryTrace.size>0?{recoveryTrace:Object.fromEntries(l.recoveryTrace)}:{}});for(;;){if(ot++,ot>tt){o.info(`hard iteration cap reached (${tt}), forcing completion`);let a=l.finalText||V(l.messages,o);yield z(a);return}let{messages:f,maxOutputTokensRecoveryCount:$,maxOutputTokensOverride:nt,turnCount:J,guardState:A,reactiveCompactState:D,collapseStore:he}=l,{toolLoopState:I}=l;if(ne){try{let a=await ne;a&&(yield{type:"tool_use_summary",turnId:r,summary:a})}catch{}ne=void 0}if(e.refreshTools&&J>1){let a=e.refreshTools();a!==E&&(E=a,o.debug(`tools refreshed: ${a.length} tools`))}if(We(A,F)){o.info(`turn aborted by guard at turn ${J}`),yield{type:"error",turnId:r,error:"Turn aborted",code:"ABORTED",usage:l.totalUsage};return}let H=qe(A,F);if(H.level==="blocking"){H.reason==="prompt_too_long"&&Y(D)&&(D.attemptedThisTurn=!0,A.hasAttemptedReactiveCompact=!0,o.info(`token budget blocking (${H.reason}), reactive compact needed`),yield L("reactive_compact","token budget pre-check")),o.info(`token budget blocking (${H.reason}), ending tool loop`);break}H.level==="warning"&&o.info(`token budget warning: ${H.usagePercent}% used, ${H.remainingTokens} remaining`);let re=yield*so({messages:f,contentReplacementState:l.contentReplacementState,snipRemovedIds:l.snipRemovedIds,collapseStore:he,guardState:A,guardConfig:F,runtimePorts:e.runtimePorts,hooks:p,hookCtx:h,sessionId:i,currentModel:l.currentModel,log:o,recovery:L,onAutocompact:()=>{l.hasAttemptedReactiveCompact=!1}}),_o=e.toolChoice==="required"&&Te?"auto":e.toolChoice??"auto",se=Ne({tools:E,toolChoice:_o}),Q=ge({maxRounds:S,replayMessages:re,lastStopReason:I.lastStopReason,options:{stopReason:I.lastStopReason}}),rt=se.extraSystemPrompt?[{role:"system",content:se.extraSystemPrompt},...Q.state.replayMessages]:Q.state.replayMessages;I=Q.state,Q.recoveryActions.length>0&&o.debug(`tool loop recovery: ${Q.recoveryActions.map(a=>a.detail??a.kind).join("; ")}`),o.debug(`turn ${J}, messages: ${rt.length}`),M(p,"turn.before_inference",{...h,model:l.currentModel},o);let Ce=!1,ke=[],st=new Map,it="stop",w,k=null,ie=!1,at=!1,Z=[],B=[];try{for await(let a of t.stream({model:l.currentModel,messages:rt,tools:se.tools,toolChoice:se.normalizedToolChoice??"auto",temperature:T,maxTokens:(nt??A.currentMaxOutputTokens)||void 0,streamRequired:e.streamRequired,previousResponseId:l.lastResponseId,reasoning:e.reasoning,promptCacheKey:e.promptCacheKey,promptCacheRetention:e.promptCacheRetention,serviceTier:e.serviceTier,openaiBuiltinTools:e.openaiBuiltinTools,maxToolCalls:e.maxToolCalls,parallelToolCalls:e.parallelToolCalls,textVerbosity:e.textVerbosity},g,b))switch(a.type){case"delta":ke.push(a.text);break;case"tool_call_delta":Ce=!0,Ye(st,a);break;case"reasoning_delta":Z.push(a.text);break;case"reasoning_block_complete":a.signature&&B.push({thinking:Z.join(""),signature:a.signature}),Z.length=0;break;case"usage":w={inputTokens:a.promptTokens,outputTokens:a.completionTokens,reasoningTokens:a.reasoningTokens,cacheRead:a.cacheReadTokens,cacheWrite:a.cacheCreationTokens};break;case"response_id":l.lastResponseId=a.id;break;case"annotations":yield{type:"annotations",turnId:r,annotations:a.annotations};break;case"builtin_tool_status":yield{type:"heartbeat",turnId:r,message:`${a.toolType}: ${a.event}`};break;case"done":at=!0,it=a.finishReason;break}if(Ce||M(p,"turn.after_inference",{...h,model:l.currentModel},o),e.postSamplingHooks&&e.postSamplingHooks.length>0){let a=l.currentModel;for(let u of e.postSamplingHooks)try{u({messages:[...re],model:a,sessionId:i})}catch{}}}catch(a){let u=yield*io(a,{state:l,guardState:A,fallbackModel:e.fallbackModel,signal:b,querySource:C,turnId:r,log:o,emitRecovery:L});if(u.kind==="return")return;if(u.kind==="continue"){l={...l,...u.patch};continue}k=u.streamError}if(!k&&!at){let a="LLM stream closed before a terminal event; the response was likely truncated upstream.";M(p,"stop.failure",{sessionId:i,reason:"RETRYABLE_TRANSIENT",error:a},o),yield{type:"error",turnId:r,error:a,code:"RETRYABLE_TRANSIENT",usage:l.totalUsage};return}if(k&&M(p,"turn.after_inference",{...h,model:l.currentModel,response:{error:k.message}},o),k)if(Je(k))ie=!0,o.info(`withheld prompt_too_long error (status=${k.status})`);else if(Qe(k))ie=!0,o.info(`withheld media_size error (status=${k.status})`);else{let a=Ke({status:k.status??500,message:k.message},A,F);if(a.action==="reactive_compact"&&Y(D)&&(D.attemptedThisTurn=!0,A.hasAttemptedReactiveCompact=!0,yield L("reactive_compact",`API ${k.status??500}: ${k.message}`)),a.action==="retry"){let y=(l.consecutiveApiRetries??0)+1;if(y>X){o.info(`API retry limit reached (${X}), aborting`);let R=W(k.status,k.message);yield{type:"error",turnId:r,error:k.message,code:R,usage:l.totalUsage};return}yield L("retry",a.reason),l={...l,consecutiveApiRetries:y,transition:void 0};continue}let u=W(k.status,k.message);M(p,"stop.failure",{sessionId:i,reason:u,error:k.message},o),yield{type:"error",turnId:r,error:k.message,code:u,usage:l.totalUsage};return}w&&(l.totalUsage.inputTokens+=w.inputTokens,l.totalUsage.outputTokens+=w.outputTokens,w.reasoningTokens&&(l.totalUsage.reasoningTokens=(l.totalUsage.reasoningTokens??0)+w.reasoningTokens),w.cacheRead&&(l.totalUsage.cacheRead=(l.totalUsage.cacheRead??0)+w.cacheRead),w.cacheWrite&&(l.totalUsage.cacheWrite=(l.totalUsage.cacheWrite??0)+w.cacheWrite)),w?.inputTokens&&(A.promptTokens=w.inputTokens);let lt=ke.join(""),O=[...st.values()].map(a=>({id:a.id||`tc_${r}_${J}_${Math.random().toString(36).slice(2,8)}`,type:"function",function:{name:a.name,arguments:a.arguments}}));if(O.length===0&&!Ce){if(lt&&(l.finalText=lt),e.toolChoice==="required"&&!Te&&E.length>0&&et<2){et++;let v=E.map(j=>j.function.name).filter(Boolean).slice(0,8).join(", ");l={...l,messages:[...f,{role:"user",content:`You must call one available tool before answering. Available tools for this request: ${v}. Do not answer from memory, prior context, or guesses.`}],finalText:"",transition:{reason:"next_turn"}};continue}if(ie&&k&&Je(k)){if(l.transition?.reason!=="collapse_drain_retry"){let v=Ie(re,he);if(v.committed>0){o.info(`collapse drain: committed ${v.committed} stages`),yield L("collapse_drain",`${v.committed} stages committed`),l={...l,messages:v.messages,transition:{reason:"collapse_drain_retry",committed:v.committed}};continue}}if(Y(D)){D.attemptedThisTurn=!0,A.hasAttemptedReactiveCompact=!0,o.info("withheld 413: reactive compact attempt"),yield L("reactive_compact","withheld prompt_too_long"),l={...l,hasAttemptedReactiveCompact:!0,transition:{reason:"reactive_compact_retry"}};continue}o.info("withheld 413: recovery exhausted, surfacing error"),M(p,"stop.failure",{sessionId:i,reason:"prompt_too_long",error:k.message},o),yield{type:"error",turnId:r,error:k.message,code:"PROMPT_TOO_LONG",usage:l.totalUsage};return}if(ie&&k&&Qe(k)){if(Y(D)){D.attemptedThisTurn=!0,A.hasAttemptedReactiveCompact=!0,o.info("withheld media error: reactive compact strip-retry"),yield L("reactive_compact","media error strip-retry"),l={...l,hasAttemptedReactiveCompact:!0,transition:{reason:"reactive_compact_retry"}};continue}o.info("withheld media error: recovery exhausted"),M(p,"stop.failure",{sessionId:i,reason:"media_error",error:k.message},o),yield{type:"error",turnId:r,error:k.message,code:"IMAGE_ERROR",usage:l.totalUsage};return}if(to(it)){A.consecutiveTruncations+=1;let v=e.modelMaxOutputTokens??vt,j=ze(A,F,v);if(j.shouldEscalate&&nt===void 0){A.currentMaxOutputTokens=j.newMax,o.info(`max_output_tokens escalate: ${j.newMax} tokens`),yield L("output_escalation",`${j.newMax} tokens`),l={...l,maxOutputTokensOverride:It,transition:{reason:"max_output_tokens_escalate"}};continue}if($<Et){let Eo={role:"user",content:"Output token limit hit. Resume directly - 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 #${$+1}`),yield L("max_output_tokens_recovery",`attempt ${$+1}`),l={...l,messages:[...re,Eo],maxOutputTokensRecoveryCount:$+1,maxOutputTokensOverride:void 0,transition:{reason:"max_output_tokens_recovery",attempt:$+1}};continue}o.info("max_output_tokens recovery exhausted, completing with partial content")}else A.consecutiveTruncations=0;I=me(I,{replayMessages:f,lastStopReason:"completed"});let a=await uo({hooks:p,sessionId:i,messages:f,finalText:l.finalText,thinkingBlocks:B,log:o});if(a?.action==="end"){yield z(a.content);return}if(a?.action==="continue"){l={...l,messages:a.messages,stopHookActive:a.stopHookActive,transition:a.transition};continue}let u=po({tokenBudget:e.tokenBudget,totalUsage:l.totalUsage,budgetContinuationCount:l.budgetContinuationCount,lastBudgetDeltaTokens:l.lastBudgetDeltaTokens,lastBudgetGlobalTokens:l.lastBudgetGlobalTokens,messages:f,finalText:l.finalText,thinkingBlocks:B,getBudgetContinuationMessage:e.runtimePorts.getBudgetContinuationMessage,log:o});if(u){yield L("budget_continuation",u.recoveryDetail),l={...l,messages:u.messages,budgetContinuationCount:u.budgetContinuationCount,lastBudgetDeltaTokens:u.lastBudgetDeltaTokens,lastBudgetGlobalTokens:u.lastBudgetGlobalTokens,transition:u.transition};continue}let y=co({inputMessages:c,messages:f,finalText:l.finalText,thinkingBlocks:B,stopHookActive:l.stopHookActive,totalToolCallCount:N,distinctToolNames:U,log:o});if(y){l={...l,messages:y.messages,stopHookActive:y.stopHookActive,transition:y.transition};continue}let R=Ze({totalToolCallCount:N,distinctToolNames:U,projectRoot:e.projectRoot});R&&(yield{type:"skill_instruction",turnId:r,instruction:R});let P=l.finalText||V(f,o);for(let v of ke)yield{type:"delta",turnId:r,text:v};yield z(P);return}let So=B.length===0&&Z.length>0?Z.join(""):void 0;f.push(_e(O,void 0,B.length>0?B:void 0,So)),I=je(I,{replayMessages:f,pendingToolCallIds:O.map(a=>a.id),completedToolCallIds:I.completedToolCallIds,lastStopReason:"tool_calls"});let ae=l.identicalCallCounts,ct=[],le=[],ut=!1;for(let a of O){let u=`${a.function.name}::${a.function.arguments}`,y=ae.get(u)??0;ae.set(u,y+1),y+1>_t?(le.push(a),ut||(ut=!0,o.info(`AP4 blocked: ${a.function.name} repeated ${y+1}x`))):ct.push(a)}let ce=[];for(let a of le){let u=ae.get(`${a.function.name}::${a.function.arguments}`),y=Ve(f,a.function.name),R=y?`This exact tool call has been attempted ${u} times. Last error: ${y}. Do not retry. Report this error to the user.`:`This exact tool call has been attempted ${u} times and keeps failing. Do not retry it. Report the issue to the user or try a completely different approach.`,P=ue(a.id,{ok:!1,error:R});f.push(P),ce.push(a.id),U.add(a.function.name),N++,yield{type:"tool_result",turnId:r,callId:a.id,name:a.function.name,ok:!1,error:R}}if(le.length>0){let a=Ve(f,le[0].function.name),u={role:"user",content:"Tool calls were blocked because you repeated them with identical arguments too many times. "+(a?`The error was: "${a}". Tell the user about this error. `:"The operation is not working. ")+"Stop retrying and report the result to the user."};f.push(u)}let Re=mo(ct,l.toolFailureCounts),be=Re.allowed;if(Re.blocked.length>0){for(let a of Re.blocked){let u=a.call,y=ue(u.id,{ok:!1,error:a.error});f.push(y),ce.push(u.id),U.add(u.function.name),N++,yield{type:"tool_result",turnId:r,callId:u.id,name:u.function.name,ok:!1,error:a.error},o.info(`variant tool blocked: ${u.function.name} failed ${a.failCount}x with different args`)}f.push(go())}for(let a of be){let u=a.function.arguments,y=E.find(R=>R.function.name===a.function.name);if(y?.backfillObservableInput)try{let R=JSON.parse(a.function.arguments),P={...R};y.backfillObservableInput(P),Object.keys(P).some(j=>!(j in R))&&(u=JSON.stringify(P))}catch{}yield{type:"tool_call",turnId:r,callId:a.id,name:a.function.name,arguments:u,inputSummary:eo(u)}}let Mo=new Map(l.toolFailureCounts);try{let a=e.runtimePorts.createStreamingToolExecutor({toolInvoker:n,hooks:p,sessionId:i,turnId:r,log:o,signal:b,maxConcurrentTools:e?.maxConcurrentTools});for(let u of be)a.addTool(u);for await(let u of a.getRemainingResults()){if(u.blocked&&(yield{type:"tool_blocked",turnId:r,callId:u.callId,name:u.toolName,reason:u.blockReason??"blocked"}),f.push(u.message),ce.push(u.callId),U.add(u.toolName),N++,fo({toolFailureCounts:l.toolFailureCounts,toolName:u.toolName,ok:u.ok,softEmpty:u.ok&&Jt(u)}),u.ok&&u.toolName==="read"){let y=be.find(R=>R.id===u.callId);if(y)try{let R=JSON.parse(y.function.arguments),P=R.file_path??R.path??R.filePath??"";if(P){let v=l.fileReadCounts.get(P)??0;l.fileReadCounts.set(P,v+1)}}catch{}}yield Xt(r,u);for(let y of Yt(r,u))yield y;for(let y of Vt({turnId:r,result:u,toolCalls:O}))yield y}}catch(a){let u=a instanceof Error?a.message:String(a);yield{type:"error",turnId:r,error:u,code:"TOOL_EXECUTION_ERROR",usage:l.totalUsage};return}if(f.push(...yo({toolFailureCounts:l.toolFailureCounts,snapshot:Mo})),I=me(I,{replayMessages:f,completedToolCallIds:[...I.completedToolCallIds,...ce],lastStopReason:"tool_calls"}),e.toolChoice==="required"&&O.length>0&&(Te=!0),e.generateToolUseSummary&&O.length>0){let a=O.map(u=>({name:u.function.name,arguments:u.function.arguments}));ne=e.generateToolUseSummary(a).catch(()=>null)}let Ao=O.length>0&&O.every(a=>{let u=f.find(R=>R?.role==="tool"&&R?.tool_call_id===a.id);if(!u)return!0;let y=u.content;return typeof y=="string"&&y.startsWith("Error: ")}),ee=l.consecutiveFailedRounds;if(Ao){if(ee+=1,ee>=xt){let a=l.finalText||V(f,o);o.info(`early exit: ${ee} consecutive failed rounds, returning ${l.finalText?"partial":"fallback"} response`),yield z(a);return}}else ee=0;let vo=3,dt=[...l.fileReadCounts.entries()].filter(([,a])=>a>=vo);if(dt.length>0){let a=dt.map(([y])=>y).join(", ");o.info(`AP5: file read cycle detected on ${a}, injecting nudge`);let u={role:"user",content:`You are reading the same files repeatedly (${a}). This indicates a circular dependency or cycle. Stop reading files, summarize your findings so far, and explain the circular structure to the user.`};f.push(u),l.fileReadCounts.clear()}let xe=J+1;if(x>0&&xe>x){if(o.info(`max turns reached (${x}), completing`),p){let u=await p.invoke("stop",{sessionId:i,reason:"max_turns"});if(u.action==="abort"){let y=u.reason??"Stop hook requested continuation after max_turns",R={role:"assistant",content:l.finalText,...B.length>0&&{thinkingBlocks:[...B]}};l={...l,messages:[...f,R,{role:"user",content:y}],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}};continue}}let a=l.finalText||V(f,o);yield z(a);return}if(xe>S){o.info(`tool loop budget exhausted (${S} rounds), returning`);let a=Ze({totalToolCallCount:N,distinctToolNames:U,projectRoot:e.projectRoot});a&&(yield{type:"skill_instruction",turnId:r,instruction:a});let u=l.finalText||V(f,o);yield z(u);return}l={messages:f,maxOutputTokensRecoveryCount:0,hasAttemptedReactiveCompact:!1,maxOutputTokensOverride:void 0,turnCount:xe,transition:{reason:"next_turn"},guardState:A,reactiveCompactState:D,toolLoopState:I,consecutiveFailedRounds:ee,finalText:l.finalText,totalUsage:l.totalUsage,collapseStore:he,currentModel:l.currentModel,consecutive529Errors:0,consecutiveApiRetries:0,stopHookActive:l.stopHookActive,lastResponseId:l.lastResponseId,snipRemovedIds:l.snipRemovedIds,contentReplacementState:l.contentReplacementState,budgetContinuationCount:l.budgetContinuationCount,lastBudgetDeltaTokens:l.lastBudgetDeltaTokens,lastBudgetGlobalTokens:l.lastBudgetGlobalTokens,identicalCallCounts:ae,toolFailureCounts:l.toolFailureCounts,fileReadCounts:l.fileReadCounts,recoveryTrace:l.recoveryTrace}}}var Jn=["\u63A5\u5355\u91D1\u989D","\u5408\u540C\u91D1\u989D","\u62A5\u4EF7","\u9884\u7B97","\u91D1\u989D","price","amount","contract amount"];function ko(e){let t=Qn(e),n=["[Recalled memories]","- L1 project MD is project-scoped working memory.","- L2 long-term memory is cross-project canonical memory.","- If L1 and L2 conflict on the same entity/fact, do not silently merge or choose. Surface the conflict and ask the user to confirm. For current-project operational tasks, use L1 only as a project-scoped clue until confirmed into L2."];if(t.length>0){n.push("[Memory conflict detected]");for(let o of t)n.push(`- entity: ${o.entity}; fact: ${o.predicate}; L1 project MD says: ${Co(o.l1Amount)}; L2 long-term says: ${Co(o.l2Amount)}; action: ask the user which value is current before using it.`)}for(let o of e){let r=tr(o);n.push(`- [${r}] ${o.text}`)}return n.join(`
7
+ `)}function Qn(e){let t=e.filter(r=>r.source==="l1-project-md").flatMap(r=>ho(r.text)),n=e.filter(r=>r.source==="l2-long-term").flatMap(r=>ho(r.text)),o=[];for(let r of t)for(let i of n)r.entity===i.entity&&r.predicate===i.predicate&&r.amount!==i.amount&&o.push({entity:r.entity,predicate:r.predicate,l1Amount:r.amount,l2Amount:i.amount,l1Text:r.text,l2Text:i.text});return or(o)}function ho(e){let t=[];for(let n of e.split(/\r?\n/)){let o=n.trim();if(o)for(let r of Jn){if(r==="\u91D1\u989D"&&/(接单金额|合同金额)/u.test(o))continue;let i=new RegExp(`${nr(r)}[^0-9.\u4E07kK,]{0,12}([0-9][0-9.,]*\\s*(?:\u4E07|k|K)?)`,"gi");for(let c of o.matchAll(i)){let s=er(c[1]);s!==null&&t.push({entity:Zn(o,r),predicate:r,amount:s,text:o})}}}return t}function Zn(e,t){if(/Galaxy\s+Tech/i.test(e))return"Galaxy Tech";if(e.includes("\u7528\u6237"))return"\u7528\u6237";let n=e.toLowerCase().indexOf(t.toLowerCase()),r=(n>=0?e.slice(0,n):"").replace(/[#*`:\-,。;;,.]/g," ").trim().split(/\s+/).filter(Boolean);return r[r.length-1]??"unknown"}function er(e){let t=e.replace(/,/g,"").replace(/\s+/g,"").trim(),n=t.endsWith("\u4E07")?1e4:/k$/i.test(t)?1e3:1,o=Number(t.replace(/[万kK]$/u,""));return Number.isFinite(o)?o*n:null}function tr(e){if(e.label)return e.label;switch(e.source){case"l1-project-md":return"L1 project MD";case"l2-long-term":return"L2 long-term";case"skill":return"Skill";case"system":return"System";default:return"Memory"}}function Co(e){return Number.isInteger(e)?String(e):String(Number(e.toFixed(4)))}function or(e){let t=new Set;return e.filter(n=>{let o=`${n.entity}\0${n.predicate}\0${n.l1Amount}\0${n.l2Amount}`;return t.has(o)?!1:(t.add(o),!0)})}function nr(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var rr=8192;async function Ro(e){let{hooks:t,detectRecallCategories:n,log:o,sessionId:r,turnId:i,query:c}=e;try{let s=n(c),g=(await t.invoke("memory.before_recall",{sessionId:r,turnId:i,query:c,preferredCategories:s.preferred.length>0?s.preferred:void 0,deprioritizedCategories:s.deprioritized.length>0?s.deprioritized:void 0}))?.context?.recalledMemories,T=null;if(g&&g.length>0){let p=0,b=[];for(let h of g){let x=(h.text?.length??0)*2;if(p+x>rr)break;b.push(h),p+=x}b.length>0&&(T=`[Recalled memories \u2014 context priority: project-specific facts override general user preferences when they conflict]
8
+ ${ko(b)}`)}return M(t,"memory.after_recall",{sessionId:r,turnId:i,blockCount:g?.length??0},o),T}catch{return null}}var xo=class{transport;apiKey;toolInvoker;log;hooks;maxRounds;projectRoot;runtimePorts;constructor(t){this.transport=t.llmTransport,this.apiKey=t.apiKey,this.toolInvoker=t.toolInvoker,this.log=t.log,this.hooks=t.hooks,this.projectRoot=t.projectRoot,this.runtimePorts=t.runtimePorts,this.maxRounds=Math.min(t.maxRounds??25,100)}async*run(t,n){let{turnId:o,messages:r,tools:i,systemPrompt:c,config:s}=t,d={sessionId:t.sessionId,turnId:o};yield{type:"start",turnId:o},M(this.hooks,"turn.submitted",{...d,prompt:r[r.length-1]?.content??void 0},this.log);let g=Ue(r),T=[];if(c&&T.push({role:"system",content:c}),T.push(...g),this.hooks){let h=g.filter(C=>C.role==="user").pop(),x=typeof h?.content=="string"?h.content.slice(0,500):void 0;if(x){let C=await Ro({hooks:this.hooks,detectRecallCategories:m=>this.runtimePorts.detectRecallCategories(m),log:this.log,sessionId:t.sessionId,turnId:o,query:x});C&&T.splice(c?1:0,0,{role:"system",content:C})}}let p=s?.model??"",b=Math.min(s?.maxRounds??this.maxRounds,100);try{let h=async _=>{let S=this.runtimePorts.resolveModelForPurpose("smallModel");if(!S)return null;try{let F=_.map(E=>`${E.name}(${E.arguments.slice(0,200)})`).join(", "),U=this.transport.stream({model:S,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:F}],tools:[],maxTokens:60},s?.apiKey??this.apiKey),N="";for await(let E of U)E.type==="delta"&&(N+=E.text);return N.trim()||null}catch{return null}},x=s?.reasoning;s?.reasoning?.effort==="auto"&&(x={...s?.reasoning,effort:"medium"});let C={turnId:o,sessionId:t.sessionId,messages:T,tools:i,model:p,apiKey:s?.apiKey??this.apiKey,temperature:s?.temperature,maxRounds:b,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,reasoning:x,promptCacheKey:s?.promptCacheKey,promptCacheRetention:s?.promptCacheRetention,serviceTier:s?.serviceTier,openaiBuiltinTools:s?.openaiBuiltinTools,maxToolCalls:s?.maxToolCalls,parallelToolCalls:s?.parallelToolCalls,textVerbosity:s?.textVerbosity,projectRoot:this.projectRoot,generateToolUseSummary:h,runtimePorts:this.runtimePorts.toolLoop,signal:n},m;for await(let _ of To(C,this.transport,this.toolInvoker,this.log))m=_,yield _;m?.type==="end"?M(this.hooks,"turn.completed",{...d},this.log):m?.type==="error"&&M(this.hooks,"turn.failed",{...d,code:m.code,error:m.error},this.log)}catch(h){if(n?.aborted)M(this.hooks,"turn.failed",{...d,code:"ABORTED",error:"Turn aborted"},this.log),yield{type:"error",turnId:o,error:"Turn aborted",code:"ABORTED"};else{let x=h instanceof Error?h.message:String(h),C=typeof h?.status=="number"?h.status:void 0,m=W(C,x);this.log.error(`turn ${o} error [${m}, retryable=${Me(m)}]: ${x}`),M(this.hooks,"turn.failed",{...d,code:m,error:x},this.log),yield{type:"error",turnId:o,error:x,code:m}}}}};export{xo as Agent};