qlogicagent 2.14.1 → 2.14.4

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,12 +1,12 @@
1
- function Ge(e,t,o,n){return{role:"assistant",content:t||null,tool_calls:e,...o&&o.length>0?{thinkingBlocks:o}:{},...n?{reasoning_content:n}:{}}}function W(e,t){let o=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:o,...!t.ok&&{is_error:!0},...t.toolReferences?.length?{toolReferences:t.toolReferences}:{},...t.imageUrls?.length?{imageUrls:t.imageUrls}:{}}}var _n=/\b(?:daily|weekly|monthly)(?:\/(?:daily|weekly|monthly))* (?:usage )?limit(?:s)?(?: (?:exhausted|reached|exceeded))?\b/i,Z={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]},Mn=/^(?:error[:\s-]+)?billing(?:\s+error)?(?:[:\s-]+|$)|^(?:error[:\s-]+)?(?:credit balance|insufficient credits?|payment required|http\s*402\b)/i,An=/["']?(?:status|code)["']?\s*[:=]\s*402\b|\bhttp\s*402\b|\berror(?:\s+code)?\s*[:=]?\s*402\b|^\s*402\s+payment/i,vn=512,Sn=/^(?:http\s*)?(\d{3})(?:\s+([\s\S]+))?$/i;var En=new Set([500,502,503,504,521,522,523,524,529]),wn=["insufficient credits","insufficient quota","credit balance","insufficient balance","plans & billing","add more credits","top up"],In=["upgrade your plan","upgrade plan","current plan","subscription"],Pn=["daily","weekly","monthly"],Ln=["try again","retry","temporary","cooldown"],On=["usage limit","rate limit","organization usage"],Fn=["organization","workspace"],Nn=["billing period","exceeded","reached","exhausted"],Dn=/["']?(?: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,Bn=/^(?:error[:\s-]+)?(?:(?:http\s*)?402(?:\s+payment required)?|payment required)(?:[:\s-]+|$)/i;function J(e,t){if(!e)return!1;let o=e.toLowerCase();return t.some(n=>n instanceof RegExp?n.test(o):o.includes(n))}function $n(e){return J(e,Z.format)}function Gt(e){return J(e,Z.rateLimit)}function Un(e){return J(e,Z.timeout)}function jn(e){return _n.test(e)}function Ke(e){let t=e.toLowerCase();return t?e.length>vn?An.test(t):J(t,Z.billing)?!0:Mn.test(e)?t.includes("upgrade")||t.includes("credits")||t.includes("payment")||t.includes("plan"):!1:!1}function Kt(e){return J(e,Z.authPermanent)}function qn(e){return J(e,Z.auth)}function Wt(e){return J(e,Z.overloaded)}function V(e,t){return t.some(o=>e.includes(o))}function zn(e){return V(e,wn)||V(e,In)&&e.includes("limit")||e.includes("billing hard limit")||e.includes("hard limit reached")||e.includes("maximum allowed")&&e.includes("limit")}function Hn(e){let t=V(e,Pn),o=e.includes("spend limit")||e.includes("spending limit"),n=V(e,Fn);return V(e,Ln)&&V(e,On)||t&&(e.includes("usage limit")||o)||t&&e.includes("limit")&&e.includes("reset")||n&&e.includes("limit")&&(o||V(e,Nn))}function Gn(e){return e.trim().toLowerCase().replace(Bn,"").trim()}function Xt(e){let t=Gn(e);return!t||zn(t)?"billing":Gt(t)||Hn(t)?"rate_limit":"billing"}function Kn(e){return Dn.test(e)?Xt(e):null}function Yt(e){let t=e.match(Sn);if(!t)return null;let o=Number(t[1]);return Number.isFinite(o)?{code:o,rest:(t[2]??"").trim()}:null}function Wn(e){if(!e)return!1;let t=e.toLowerCase();return t.includes('"type":"api_error"')&&t.includes("internal server error")}function Xn(e){let t=e.trim();if(!t)return!1;let o=Yt(t);return o?En.has(o.code):!1}function Vt(e,t){return typeof e!="number"||!Number.isFinite(e)?null:e===402?t?Xt(t):"billing":e===429?"rate_limit":e===401||e===403?t&&Kt(t)?"auth_permanent":"auth":e===408?"timeout":e===503?t&&Wt(t)?"overloaded":"timeout":e===502||e===504?"timeout":e===529?"overloaded":e===400?t&&Ke(t)?"billing":"format":null}function Yn(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 Vn(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 Zt(e){if(Vn(e))return"session_expired";if(Yn(e))return"model_not_found";let t=Kn(e);return t||(jn(e)?Ke(e)?"billing":"rate_limit":Gt(e)?"rate_limit":Wt(e)?"overloaded":Xn(e)?Yt(e.trim())?.code===529?"overloaded":"timeout":Wn(e)?"timeout":$n(e)?"format":Ke(e)?"billing":Un(e)?"timeout":Kt(e)?"auth_permanent":qn(e)?"auth":null)}var Zn={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"},Jn=new Set(["RETRYABLE_TRANSIENT","RETRYABLE_DEGRADED","TOOL_EXECUTION_FAILED"]);function ne(e,t){let o=Vt(e,t)??(t?Zt(t):null);return o?Zn[o]:typeof e=="number"&&e>=400&&e<500?"NON_RETRYABLE_CONTENT":"RETRYABLE_TRANSIENT"}function We(e){return Jn.has(e)}function Jt(e){let t=typeof e.content=="string"?e.content:e.content!=null?JSON.stringify(e.content):"";return Math.ceil(t.length/4)}var Qn=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"]),me=class{constructor(t=20,o=Jt){this.preserveRecentCount=t;this.estimateTokens=o}preserveRecentCount;estimateTokens;compress(t,o){if(t.length<=this.preserveRecentCount)return{messages:t,droppedCount:0,strategy:"micro-compact"};let n=t.length-this.preserveRecentCount,r=0,s=0;return{messages:t.map((a,d)=>{if(d>=n||a.role!=="tool"||typeof a.content!="string"||!a.name||!Qn.has(a.name)||a.content.length<=200)return a;let p=this.estimateTokens(a);return s+=p,r++,{...a,content:`[result cleared \u2014 ${a.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 Xe(e,t,o=Jt){if(t.size===0)return{messages:e,tokensFreed:0,removedCount:0};let n=0,r=0,s=[];for(let a of e){let d=a.tool_call_id??"";if(d&&t.has(d)){n+=o(a),r++,t.delete(d);continue}s.push(a)}let i=r>0?{role:"system",content:`[${r} messages removed by snip]`}:void 0;return{messages:s,tokensFreed:n,removedCount:r,boundaryMessage:i}}function Ye(){return{stages:[]}}function Ve(e,t,o){let n=o?.thresholdMessages??40;if(e.filter(a=>a.role!=="system").length<=n)return{messages:e,stagedCount:0};let s=Qt(e,t),i=er(s,t,n);if(i.length===0)return{messages:s,stagedCount:0};for(let a of i)t.stages.push(a);return s=Qt(e,t),{messages:s,stagedCount:i.length}}function Ze(e,t){let o=0;for(let n of t.stages)n.committed||(n.committed=!0,o++);return o===0?{messages:e,committed:0}:{messages:eo(e,t),committed:o}}function Qt(e,t){return t.stages.filter(n=>n.committed).length===0?e:eo(e,t)}function eo(e,t){let o=t.stages.filter(r=>r.committed).sort((r,s)=>s.range[0]-r.range[0]),n=[...e];for(let r of o){let[s,i]=r.range;if(s>=n.length)continue;let a=Math.min(i,n.length),d={role:"system",content:r.summary};n.splice(s,a-s,d)}return n}function er(e,t,o){let n=Math.max(0,e.length-Math.floor(o/2)),r=[],s=new Set(t.stages.map(d=>`${d.range[0]}-${d.range[1]}`)),i=-1,a=0;for(let d=0;d<n;d++){let p=e[d];if(p.role==="tool"||p.role==="assistant"&&typeof p.content=="string"&&p.content==="")i<0&&(i=d),a++;else{if(a>=3){let m=`${i}-${i+a}`;s.has(m)||r.push({id:`collapse_${i}_${i+a}`,range:[i,i+a],summary:`[${a} tool results collapsed]`,committed:!1})}i=-1,a=0}}if(a>=3){let d=`${i}-${i+a}`;s.has(d)||r.push({id:`collapse_${i}_${i+a}`,range:[i,i+a],summary:`[${a} tool results collapsed]`,committed:!1})}return r}import{existsSync as et,readFileSync as Ro,writeFileSync as tr,readdirSync as bo,mkdirSync as or}from"node:fs";import{join as tt,dirname as nr}from"node:path";var Je=Math.min(Math.max(1,Number(process.env.TOOL_LOOP_DEFAULT_BUDGET)||25),100),to=Math.max(1e3,Number(process.env.TOOL_LOOP_TOOL_TIMEOUT_MS)||24e4),oo=3,no=2,be=2,ro=128e3,so=13e3,io=16384,ao=65536,lo=3,co=65536,Qe=500,uo=3;var po=3e4,mo=3,re=2;var fo=20;var go=3,yo=2,ho=300*1e3,To=3,Co=720*60*60*1e3;var Ps=300*1e3;var Ls=3600*1e3;var Os=50*1024,Fs=500*1024,Ns=500*1024*1024,Ds=50*1024*1024;var Bs=60*1024;var xo=0;var rr="skill-patterns.json";function _o(e){return tt(e,".qlogicagent",rr)}function sr(e){let t=_o(e);try{return JSON.parse(Ro(t,"utf8"))}catch{return{version:1,patterns:{}}}}function ko(e,t){let o=_o(e);or(nr(o),{recursive:!0}),tr(o,JSON.stringify(t,null,2),"utf8")}function ir(e){let t=Date.now()-Co;for(let[o,n]of Object.entries(e.patterns))new Date(n.lastSeen).getTime()<t&&delete e.patterns[o]}function Mo(e,t){if(t.length===0)return!1;let o=xe(t),n=sr(e);ir(n);let r=new Date().toISOString(),s=n.patterns[o];if(s||(s={signature:o,count:0,firstSeen:r,lastSeen:r,promoted:!1},n.patterns[o]=s),s.promoted)return ko(e,n),!1;s.count++,s.lastSeen=r;let i=s.count>=To;return i&&(s.promoted=!0),ko(e,n),i}function xe(e){return[...e].sort().join("+")}function ar(e,t){if(!et(t))return null;let o=xe(e);try{let n=bo(t,{withFileTypes:!0});for(let r of n){if(!r.isDirectory())continue;let s=tt(t,r.name,"SKILL.md");try{let a=Ro(s,"utf8").match(/^tools:\s*\n((?:\s+-\s+\S+\n?)+)/m);if(a){let d=a[1].split(`
2
- `).map(p=>p.replace(/^\s*-\s*/,"").trim()).filter(Boolean);if(xe(d)===o)return r.name}}catch{}}}catch{}return null}function lr(e){if(!et(e))return 0;try{return bo(e,{withFileTypes:!0}).filter(t=>t.isDirectory()&&et(tt(e,t.name,"SKILL.md"))).length}catch{return 0}}function cr(e,t){return!(!e.ok||e.existingSkillName||!e.multiStep||e.toolCallCount<go||e.distinctToolCount<yo||Date.now()-xo<ho||t?.projectSkillsDir&&(lr(t.projectSkillsDir)>=fo||t.tools.length>0&&ar(t.tools,t.projectSkillsDir))||t?.projectRoot&&t.tools.length>0&&!Mo(t.projectRoot,t.tools))}function ur(e){return e.existingSkillName?e.feedback==="negative":!1}function ot(e,t){return ur(e)?{type:"skill.improve",skillName:e.existingSkillName,reason:"negative user feedback on existing skill execution"}:cr(e,t)?(xo=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 Ao(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 dr(e){return e==="enabled-eligible"||e==="installed-awaiting-approval"}function pr(e){return new Map((e??[]).map(t=>[t.toolName,t]))}function mr(e){if(!e.eligibility?.length)return[...e.tools];let t=pr(e.eligibility);return e.tools.filter(o=>{let n=Ao(o);if(!n)return!1;let r=t.get(n);return!r||dr(r.status)})}function fr(e){let t=[],o=e.compatibility??{},n=e.toolChoice;if(e.thinkingEnabled&&o.requireAutoWhenThinking){let r=typeof n=="object"&&n&&!Array.isArray(n)?String(n.type??""):n;r&&r!=="auto"&&r!=="none"&&(t.push("tool_choice downgraded to auto because thinking mode requires auto/none compatibility."),n="auto")}if(n==="required"&&o.allowRequiredToolChoice===!1){let r=o.requiredFallback??"auto";t.push(`tool_choice=required is not supported by this provider; downgraded to ${r}.`),n=r}if(n&&typeof n=="object"&&!Array.isArray(n)&&n.type==="function"&&o.allowNamedToolChoice===!1){let r=o.namedFallback??"required";t.push(`named tool_choice is not supported by this provider; downgraded to ${r}.`),n=r}return{normalizedToolChoice:n,warnings:t}}function nt(e){let t=fr({toolChoice:e.toolChoice,thinkingEnabled:e.thinkingEnabled,compatibility:e.compatibility}),o=t.normalizedToolChoice,n=[...t.warnings],r=mr({tools:e.tools,eligibility:e.eligibility});if(!o||o==="auto")return{tools:r,normalizedToolChoice:o,warnings:n};if(o==="none")return{tools:[],normalizedToolChoice:"none",warnings:n};if(o==="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:n}}if(typeof o=="object"&&!Array.isArray(o)&&o.type==="function"){let s=o.function??void 0,i=typeof s?.name=="string"?s.name.trim():"";if(!i)throw new Error("tool_choice.function.name is required");let a=r.filter(d=>Ao(d)===i);if(a.length===0)throw new Error(`tool_choice requested unknown tool: ${i}`);return{tools:a,normalizedToolChoice:{type:"function",function:{name:i}},extraSystemPrompt:`You must call the ${i} tool before responding.`,warnings:n}}return{tools:r,normalizedToolChoice:o,warnings:n}}var gr=["stop","aborted","timeout","cancelled","interrupted","error"],yr=["tool_calls","toolCalls","function_call","functionCall","raw_tool_calls","rawToolCalls"];function vo(e){return e==null?[]:typeof e=="string"?e.length>0?[{type:"text",text:e}]:[]:Array.isArray(e)?e:[{type:"text",text:String(e)}]}function hr(e,t){return{...e,content:[...vo(e.content),...vo(t.content)]}}function Tr(e){let t=new Set;if(e.role!=="assistant"||!Array.isArray(e.tool_calls))return t;for(let o of e.tool_calls)typeof o.id=="string"&&o.id&&t.add(o.id);return t}function Cr(e){let t=new Set,o=[];for(let n=0;n<e.length;n+=1){if(t.has(n))continue;let r=e[n];if(!r)continue;o.push(r);let s=Tr(r);if(s.size!==0)for(let i=n+1;i<e.length;i+=1){if(t.has(i))continue;let a=e[i];a?.role==="tool"&&typeof a.tool_call_id=="string"&&s.has(a.tool_call_id)&&(o.push(a),t.add(i))}}return o}function kr(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 Rr(e){return new Set((e??gr).map(t=>t.trim().toLowerCase()))}function br(e,t){return e?Rr(t).has(e.trim().toLowerCase()):!1}function rt(e){if(!Array.isArray(e)||e.length===0)return[...e];let t=e.map(d=>{if(d.role==="assistant"&&Array.isArray(d.tool_calls)){let p=d.tool_calls.filter(f=>kr(f));return{...d,...p.length>0?{tool_calls:p}:{tool_calls:void 0}}}return{...d}}),o=new Set;for(let d of t)if(!(d.role!=="assistant"||!Array.isArray(d.tool_calls)))for(let p of d.tool_calls)typeof p.id=="string"&&p.id&&o.add(p.id);let n=t.filter(d=>d.role!=="tool"?!0:!!(d.tool_call_id&&o.has(d.tool_call_id))),r=new Set;for(let d of n)d.role==="tool"&&typeof d.tool_call_id=="string"&&d.tool_call_id&&r.add(d.tool_call_id);let s=[];for(let d of n){if(d.role==="assistant"&&Array.isArray(d.tool_calls)&&d.tool_calls.length>0){let p=d.tool_calls.filter(f=>typeof f.id=="string"&&r.has(f.id));if(p.length===0){let{tool_calls:f,...m}=d;m.content!=null&&m.content!==""&&s.push(m);continue}if(p.length<d.tool_calls.length){s.push({...d,tool_calls:p});continue}}s.push(d)}let i=Cr(s),a=[];for(let d of i){let p=a.length>0?a[a.length-1]:void 0;if(d.role==="user"&&p?.role==="user"){a[a.length-1]=hr(p,d);continue}a.push(d)}return a}function st(e,t){return br(t?.stopReason,t?.forcedStopReasons)?e.map(o=>{if(o.role!=="assistant")return{...o};let n={...o};for(let r of yr)delete n[r];return n}):[...e]}function it(e,t){let o=t?.placeholderToolResult??"Error: Tool loop interrupted before the tool result was replayed.",n=new Set;for(let s of e)s.role==="tool"&&typeof s.tool_call_id=="string"&&s.tool_call_id&&n.add(s.tool_call_id);let r=[];for(let s of e)if(r.push({...s}),!(s.role!=="assistant"||!Array.isArray(s.tool_calls)||s.tool_calls.length===0))for(let i of s.tool_calls)typeof i.id!="string"||!i.id||n.has(i.id)||(n.add(i.id),r.push({role:"tool",tool_call_id:i.id,content:o}));return r}function at(e,t){let o=rt(e),n=st(o,t);return it(n,t)}function xr(e){let t=new Set,o=new Set;for(let n of e){if(n.role==="assistant"&&Array.isArray(n.tool_calls))for(let r of n.tool_calls)typeof r.id=="string"&&r.id&&t.add(r.id);n.role==="tool"&&typeof n.tool_call_id=="string"&&n.tool_call_id&&o.add(n.tool_call_id)}return[...t].filter(n=>!o.has(n))}function _r(e){let t=new Set;for(let o of e)o.role==="tool"&&typeof o.tool_call_id=="string"&&o.tool_call_id&&t.add(o.tool_call_id);return[...t]}function Mr(e){return{round:e.round??0,maxRounds:e.maxRounds,pendingToolCallIds:[...e.pendingToolCallIds??[]],completedToolCallIds:[...e.completedToolCallIds??[]],lastStopReason:e.lastStopReason,replayMessages:[...e.replayMessages??[]]}}function lt(e,t){return{round:e.round+1,maxRounds:e.maxRounds,pendingToolCallIds:[...t.pendingToolCallIds??e.pendingToolCallIds],completedToolCallIds:[...t.completedToolCallIds??e.completedToolCallIds],lastStopReason:t.lastStopReason??e.lastStopReason,replayMessages:[...t.replayMessages??e.replayMessages]}}function _e(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 Me(e){let t=[],o=rt(e.replayMessages);o.length!==e.replayMessages.length&&t.push({kind:"drop-orphan-tool-result",detail:"Removed orphan tool results or invalid assistant tool calls."});let n=st(o,e.options);n.some((s,i)=>s!==o[i])&&t.push({kind:"strip-forced-stop-tool-metadata",detail:"Removed assistant tool-call metadata after forced stop."});let r=it(n,e.options);return r.length>n.length&&t.push({kind:"inject-placeholder-tool-result",detail:"Injected placeholder tool result for pending tool calls."}),{state:Mr({maxRounds:e.maxRounds,round:e.round,lastStopReason:e.lastStopReason,replayMessages:r,pendingToolCallIds:xr(r),completedToolCallIds:_r(r)}),recoveryActions:t}}var Ar=new Set(["main","sdk","agent","compact","hook","verification","side_question"]);function ct(e){return e?Ar.has(e):!0}function ut(e){return e===429||e===529}function Ae(e,t=500,o=32e3){let n=Math.min(t*Math.pow(2,e-1),o);return n+Math.floor(Math.random()*n*.25)}var Vs={maxBackoffMs:300*1e3,resetCapMs:360*60*1e3,heartbeatIntervalMs:3e4};function ve(){let e=process.env.QLOGICAGENT_PERSISTENT_RETRY;return e==="1"||e==="true"}var fe=class extends Error{constructor(o,n){super(`Model fallback triggered: ${o} -> ${n}`);this.originalModel=o;this.fallbackModel=n;this.name="FallbackTriggeredError"}originalModel;fallbackModel};function dt(e){return{promptTokens:0,hasAttemptedReactiveCompact:!1,currentMaxOutputTokens:e.maxOutputTokens,consecutiveTruncations:0,aborted:e.abortSignal?.aborted??!1}}function pt(e,t){if(e.aborted)return{level:"blocking",usagePercent:100,reason:"budget_exhausted"};let o=t.contextWindowTokens-t.responseBufferTokens-e.currentMaxOutputTokens,n=o>0?e.promptTokens/o*100:100;return e.promptTokens>=o?e.hasAttemptedReactiveCompact||!t.reactiveCompactEnabled?{level:"blocking",usagePercent:n,reason:"prompt_too_long"}:{level:"blocking",usagePercent:n,reason:"prompt_too_long"}:n>=85?{level:"warning",usagePercent:n,remainingTokens:o-e.promptTokens}:{level:"ok"}}function mt(e,t,o){let n=e.message?.toLowerCase()??"",r=e.status??0;return r===413||n.includes("prompt_too_long")||n.includes("context_length_exceeded")?!t.hasAttemptedReactiveCompact&&o.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:n||"unknown_error"}}function ft(e,t,o){if(!t.outputEscalationEnabled)return{shouldEscalate:!1,newMax:e.currentMaxOutputTokens};if(e.consecutiveTruncations>=3)return{shouldEscalate:!1,newMax:e.currentMaxOutputTokens};let n=Math.min(e.currentMaxOutputTokens*2,o);return n<=e.currentMaxOutputTokens?{shouldEscalate:!1,newMax:e.currentMaxOutputTokens}:{shouldEscalate:!0,newMax:n}}function gt(e,t){return e.aborted?!0:t.abortSignal?.aborted?(e.aborted=!0,!0):!1}var Sr={maxConsecutiveFailures:3,minMessagesAfterCompact:4,targetUsagePercent:50};function yt(){return{consecutiveFailures:0,attemptedThisTurn:!1,lastCompactAt:null,toolsAtLastCompact:[]}}function se(e,t=Sr){return!(e.attemptedThisTurn||e.consecutiveFailures>=t.maxConsecutiveFailures)}function ht(e,t){let o=e.get(t.index)??{id:"",name:"",arguments:""};t.id&&(o.id=t.id),t.name&&(o.name=t.name),o.arguments+=t.arguments??"",e.set(t.index,o)}function S(e,t,o,n){e?.invoke(t,o).catch(r=>{let s=r instanceof Error?r.message:String(r);n.warn(`[hook:${t}] handler failed: ${s}`)})}function So(e,t){let o=typeof t.message?.content=="string"?t.message.content:"",n=o?o.slice(0,2e3):void 0,r=t.details,s=typeof r?.stdout=="string"?r.stdout.slice(0,8e3):void 0,i=typeof r?.stderr=="string"?r.stderr.slice(0,4e3):void 0,a=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:n,durationMs:t.durationMs,exitCode:a,stdout:s,stderr:i,details:r}}function Eo(e,t){if(!t.ok)return[];let o=t.details;if(!o)return[];let n=Er(o);return n?(Array.isArray(o.mediaUrls)?o.mediaUrls.filter(s=>typeof s=="string"&&s.trim().length>0):[]).map(s=>({type:"media_result",turnId:e,mediaType:n,url:s,model:typeof o.model=="string"?o.model:void 0,provider:typeof o.provider=="string"?o.provider:void 0,durationSeconds:typeof o.durationMs=="number"?o.durationMs/1e3:void 0,taskId:typeof o.taskId=="string"?o.taskId:void 0})):[]}function Er(e){let t=typeof e.type=="string"?e.type:"";if(!t)return null;if(t==="three_d_generate")return"3d";let o=t.split("_")[0];return o==="image"||o==="tts"||o==="video"||o==="music"?o:null}var wr=new Set(["write","edit","patch"]);function wo(e){let{turnId:t,result:o,toolCalls:n}=e;if(!o.ok)return[];let r=n.find(a=>a.id===o.callId);if(!r)return[];let s=[],i=Ir(r.function.arguments);if(!i)return s;if(o.toolName==="plan_mode"&&i.action==="exit"&&typeof i.plan=="string"&&i.plan.length>0&&s.push({type:"plan_update",turnId:t,slug:"approved-plan",content:i.plan}),wr.has(o.toolName)){let a=Pr(i);a&&s.push({type:"artifact",turnId:t,artifactId:`artifact-${o.callId}`,artifactType:Lr(a),title:a.split(/[\\/]/).pop()||a,filePath:a,language:Or(a)})}return s}function Ir(e){try{return JSON.parse(e)}catch{return null}}function Pr(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 Lr(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 Or(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 Fr=/^no (matches|files|results) found(?:\s+for:.*)?\.?$|^file not found|^not found|^0 results|^\(exit code \d+, no output\)$/i,Nr=new Set(["search","web_search","grep","glob","find","list","read","exec"]),Dr=/[A-Za-z]:[\\/](?:[^\s"'`<>|,\uFF0C\u3001;\uFF1B\u3002]+[\\/])*[^\s"'`<>|,\uFF0C\u3001;\uFF1B\u3002]+\.[A-Za-z0-9]{1,12}/g,Br=/(?:^|[\s"'`([{,;:\uFF0C\u3001\uFF1B])((?:[A-Za-z0-9._-]+[\\/])+[A-Za-z0-9][A-Za-z0-9._-]*\.(?:xlsx|xls|pptx|ppt|docx|pdf|md|markdown|html|css|js|jsx|ts|tsx|json|csv|tsv|png|jpg|jpeg|webp|svg|gif|mp4|mov|wav|mp3|m4a|zip|petdex))(?:$|[\s"'`\])},;:\uFF0C\u3001\uFF1B\u3002])/gi,$r=/(?:^|[\s"'`([{,;:\uFF0C\u3001\uFF1B])([A-Za-z0-9][A-Za-z0-9._-]*\.(?:xlsx|xls|pptx|ppt|docx|pdf|md|markdown|html|css|js|jsx|ts|tsx|json|csv|tsv|png|jpg|jpeg|webp|svg|gif|mp4|mov|wav|mp3|m4a|zip|petdex))(?:$|[\s"'`\])},;:\uFF0C\u3001\uFF1B\u3002])/gi,Ur=/\b(?:create|generate|write|produce|save|output|deliver|deliverables?|artifacts?|required|required files?|must generate|self-verify)\b|(?:生成|创建|写入|输出|保存|交付|产物|文件|必须|自检|验证)/i;function Po(e){if(!Nr.has(e.toolName))return!1;let t=typeof e.message?.content=="string"?e.message.content.trim():"";return t.length>0&&t.length<200&&Fr.test(t)}function Tt(e,t){for(let o=e.length-1;o>=0;o--){let n=e[o];if(!n||n.role!=="tool")continue;let r=typeof n.content=="string"?n.content:"";if(r.startsWith("Error: "))return r.slice(7).trim()}}function Lo(e,t){if(typeof e=="number"&&Number.isFinite(e)&&e>=1)return Math.min(Math.round(e),100);let o=Ee(t);return o>=3?Math.min(Math.max(25,20+o*15),100):25}function Ee(e){if(!e)return 0;let t=new Set,o=new Set,n=r=>{let s=r.replace(/[),.;:\uFF0C\u3002\uFF1B\u3001]+$/u,"").replace(/\\/g,"/").toLowerCase();t.add(`path:${s}`);let i=s.split("/").pop();i&&o.add(i)};for(let r of e){if(r.role!=="user"||typeof r.content!="string")continue;let s=r.content;for(let i of r.content.matchAll(Dr))n(i[0]);if(Ur.test(s)){for(let i of s.matchAll(Br)){let a=i[1]?.toLowerCase();if(!a)continue;t.add(`relative:${a.replace(/\\/g,"/")}`);let d=a.replace(/\\/g,"/").split("/").pop();d&&o.add(d)}for(let i of s.matchAll($r)){let a=i[1]?.toLowerCase();!a||o.has(a)||t.add(`name:${a}`)}}}return t.size}function Oo(e,t){if(typeof e=="number"&&Number.isFinite(e)&&e>=1)return Math.min(Math.round(e),100);let o=Ee(t);return o>=3?Math.min(Math.max(Je,20+o*15),100):Je}function Fo(e){return e.filter(t=>t.role!=="assistant"?!0:!(typeof t.content=="string"&&t.content.trim()===""))}function Ct(e,t){let o=[];for(let n=e.length-1;n>=0;n--){let r=e[n];if(r.role==="tool"&&typeof r.content=="string")o.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 o.length>0?(t.info(`synthesizeFallbackContent: synthesized from ${o.length} tool result(s)`),o.join(`
1
+ function Qe(e,t,n,o){return{role:"assistant",content:t||null,tool_calls:e,...n&&n.length>0?{thinkingBlocks:n}:{},...o?{reasoning_content:o}:{}}}function Y(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 Fn=/\b(?:daily|weekly|monthly)(?:\/(?:daily|weekly|monthly))* (?:usage )?limit(?:s)?(?: (?:exhausted|reached|exceeded))?\b/i,oe={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]},Nn=/^(?:error[:\s-]+)?billing(?:\s+error)?(?:[:\s-]+|$)|^(?:error[:\s-]+)?(?:credit balance|insufficient credits?|payment required|http\s*402\b)/i,Bn=/["']?(?:status|code)["']?\s*[:=]\s*402\b|\bhttp\s*402\b|\berror(?:\s+code)?\s*[:=]?\s*402\b|^\s*402\s+payment/i,Dn=512,$n=/^(?:http\s*)?(\d{3})(?:\s+([\s\S]+))?$/i;var Un=new Set([500,502,503,504,521,522,523,524,529]),jn=["insufficient credits","insufficient quota","credit balance","insufficient balance","plans & billing","add more credits","top up"],qn=["upgrade your plan","upgrade plan","current plan","subscription"],Hn=["daily","weekly","monthly"],zn=["try again","retry","temporary","cooldown"],Gn=["usage limit","rate limit","organization usage"],Kn=["organization","workspace"],Wn=["billing period","exceeded","reached","exhausted"],Xn=/["']?(?: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,Yn=/^(?:error[:\s-]+)?(?:(?:http\s*)?402(?:\s+payment required)?|payment required)(?:[:\s-]+|$)/i;function ne(e,t){if(!e)return!1;let n=e.toLowerCase();return t.some(o=>o instanceof RegExp?o.test(n):n.includes(o))}function Vn(e){return ne(e,oe.format)}function no(e){return ne(e,oe.rateLimit)}function Zn(e){return ne(e,oe.timeout)}function Jn(e){return Fn.test(e)}function et(e){let t=e.toLowerCase();return t?e.length>Dn?Bn.test(t):ne(t,oe.billing)?!0:Nn.test(e)?t.includes("upgrade")||t.includes("credits")||t.includes("payment")||t.includes("plan"):!1:!1}function ro(e){return ne(e,oe.authPermanent)}function Qn(e){return ne(e,oe.auth)}function so(e){return ne(e,oe.overloaded)}function te(e,t){return t.some(n=>e.includes(n))}function er(e){return te(e,jn)||te(e,qn)&&e.includes("limit")||e.includes("billing hard limit")||e.includes("hard limit reached")||e.includes("maximum allowed")&&e.includes("limit")}function tr(e){let t=te(e,Hn),n=e.includes("spend limit")||e.includes("spending limit"),o=te(e,Kn);return te(e,zn)&&te(e,Gn)||t&&(e.includes("usage limit")||n)||t&&e.includes("limit")&&e.includes("reset")||o&&e.includes("limit")&&(n||te(e,Wn))}function or(e){return e.trim().toLowerCase().replace(Yn,"").trim()}function io(e){let t=or(e);return!t||er(t)?"billing":no(t)||tr(t)?"rate_limit":"billing"}function nr(e){return Xn.test(e)?io(e):null}function ao(e){let t=e.match($n);if(!t)return null;let n=Number(t[1]);return Number.isFinite(n)?{code:n,rest:(t[2]??"").trim()}:null}function rr(e){if(!e)return!1;let t=e.toLowerCase();return t.includes('"type":"api_error"')&&t.includes("internal server error")}function sr(e){let t=e.trim();if(!t)return!1;let n=ao(t);return n?Un.has(n.code):!1}function lo(e,t){return typeof e!="number"||!Number.isFinite(e)?null:e===402?t?io(t):"billing":e===429?"rate_limit":e===401||e===403?t&&ro(t)?"auth_permanent":"auth":e===408?"timeout":e===503?t&&so(t)?"overloaded":"timeout":e===502||e===504?"timeout":e===529?"overloaded":e===400?t&&et(t)?"billing":"format":null}function ir(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 ar(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 co(e){if(ar(e))return"session_expired";if(ir(e))return"model_not_found";let t=nr(e);return t||(Jn(e)?et(e)?"billing":"rate_limit":no(e)?"rate_limit":so(e)?"overloaded":sr(e)?ao(e.trim())?.code===529?"overloaded":"timeout":rr(e)?"timeout":Vn(e)?"format":et(e)?"billing":Zn(e)?"timeout":ro(e)?"auth_permanent":Qn(e)?"auth":null)}var lr={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"},cr=new Set(["RETRYABLE_TRANSIENT","RETRYABLE_DEGRADED","TOOL_EXECUTION_FAILED"]);function ie(e,t){let n=lo(e,t)??(t?co(t):null);return n?lr[n]:typeof e=="number"&&e>=400&&e<500?"NON_RETRYABLE_CONTENT":"RETRYABLE_TRANSIENT"}function tt(e){return cr.has(e)}function uo(e){let t=typeof e.content=="string"?e.content:e.content!=null?JSON.stringify(e.content):"";return Math.ceil(t.length/4)}var ur=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"]),Ce=class{constructor(t=20,n=uo){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,s=0;return{messages:t.map((a,u)=>{if(u>=o||a.role!=="tool"||typeof a.content!="string"||!a.name||!ur.has(a.name)||a.content.length<=200)return a;let p=this.estimateTokens(a);return s+=p,r++,{...a,content:`[result cleared \u2014 ${a.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 ot(e,t,n=uo){if(t.size===0)return{messages:e,tokensFreed:0,removedCount:0};let o=0,r=0,s=[];for(let a of e){let u=a.tool_call_id??"";if(u&&t.has(u)){o+=n(a),r++,t.delete(u);continue}s.push(a)}let i=r>0?{role:"system",content:`[${r} messages removed by snip]`}:void 0;return{messages:s,tokensFreed:o,removedCount:r,boundaryMessage:i}}function nt(){return{stages:[]}}function rt(e,t,n){let o=n?.thresholdMessages??40;if(e.filter(a=>a.role!=="system").length<=o)return{messages:e,stagedCount:0};let s=po(e,t),i=dr(s,t,o);if(i.length===0)return{messages:s,stagedCount:0};for(let a of i)t.stages.push(a);return s=po(e,t),{messages:s,stagedCount:i.length}}function st(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:mo(e,t),committed:n}}function po(e,t){return t.stages.filter(o=>o.committed).length===0?e:mo(e,t)}function mo(e,t){let n=t.stages.filter(r=>r.committed).sort((r,s)=>s.range[0]-r.range[0]),o=[...e];for(let r of n){let[s,i]=r.range;if(s>=o.length)continue;let a=Math.min(i,o.length),u={role:"system",content:r.summary};o.splice(s,a-s,u)}return o}function dr(e,t,n){let o=Math.max(0,e.length-Math.floor(n/2)),r=[],s=new Set(t.stages.map(u=>`${u.range[0]}-${u.range[1]}`)),i=-1,a=0;for(let u=0;u<o;u++){let p=e[u];if(p.role==="tool"||p.role==="assistant"&&typeof p.content=="string"&&p.content==="")i<0&&(i=u),a++;else{if(a>=3){let m=`${i}-${i+a}`;s.has(m)||r.push({id:`collapse_${i}_${i+a}`,range:[i,i+a],summary:`[${a} tool results collapsed]`,committed:!1})}i=-1,a=0}}if(a>=3){let u=`${i}-${i+a}`;s.has(u)||r.push({id:`collapse_${i}_${i+a}`,range:[i,i+a],summary:`[${a} tool results collapsed]`,committed:!1})}return r}import{existsSync as at,readFileSync as Lo,writeFileSync as pr,readdirSync as Oo,mkdirSync as mr}from"node:fs";import{join as lt,dirname as fr}from"node:path";var re=Math.min(Math.max(1,Number(process.env.TOOL_LOOP_DEFAULT_BUDGET)||25),100),fo=Math.max(1e3,Number(process.env.TOOL_LOOP_TOOL_TIMEOUT_MS)||24e4),go=3,yo=2,Pe=2,ho=128e3,To=13e3,Co=16384,ko=65536,Ro=3,bo=65536,it=500,xo=3;var _o=3e4,Mo=3,ae=2;var Ao=20;var vo=3,So=2,Eo=300*1e3,wo=3,Io=720*60*60*1e3;var Gs=300*1e3;var Ks=3600*1e3;var Ws=50*1024,Xs=500*1024,Ys=500*1024*1024,Vs=50*1024*1024;var Zs=60*1024;var Fo=0;var gr="skill-patterns.json";function No(e){return lt(e,".qlogicagent",gr)}function yr(e){let t=No(e);try{return JSON.parse(Lo(t,"utf8"))}catch{return{version:1,patterns:{}}}}function Po(e,t){let n=No(e);mr(fr(n),{recursive:!0}),pr(n,JSON.stringify(t,null,2),"utf8")}function hr(e){let t=Date.now()-Io;for(let[n,o]of Object.entries(e.patterns))new Date(o.lastSeen).getTime()<t&&delete e.patterns[n]}function Bo(e,t){if(t.length===0)return!1;let n=Le(t),o=yr(e);hr(o);let r=new Date().toISOString(),s=o.patterns[n];if(s||(s={signature:n,count:0,firstSeen:r,lastSeen:r,promoted:!1},o.patterns[n]=s),s.promoted)return Po(e,o),!1;s.count++,s.lastSeen=r;let i=s.count>=wo;return i&&(s.promoted=!0),Po(e,o),i}function Le(e){return[...e].sort().join("+")}function Tr(e,t){if(!at(t))return null;let n=Le(e);try{let o=Oo(t,{withFileTypes:!0});for(let r of o){if(!r.isDirectory())continue;let s=lt(t,r.name,"SKILL.md");try{let a=Lo(s,"utf8").match(/^tools:\s*\n((?:\s+-\s+\S+\n?)+)/m);if(a){let u=a[1].split(`
2
+ `).map(p=>p.replace(/^\s*-\s*/,"").trim()).filter(Boolean);if(Le(u)===n)return r.name}}catch{}}}catch{}return null}function Cr(e){if(!at(e))return 0;try{return Oo(e,{withFileTypes:!0}).filter(t=>t.isDirectory()&&at(lt(e,t.name,"SKILL.md"))).length}catch{return 0}}function kr(e,t){return!(!e.ok||e.existingSkillName||!e.multiStep||e.toolCallCount<vo||e.distinctToolCount<So||Date.now()-Fo<Eo||t?.projectSkillsDir&&(Cr(t.projectSkillsDir)>=Ao||t.tools.length>0&&Tr(t.tools,t.projectSkillsDir))||t?.projectRoot&&t.tools.length>0&&!Bo(t.projectRoot,t.tools))}function Rr(e){return e.existingSkillName?e.feedback==="negative":!1}function ct(e,t){return Rr(e)?{type:"skill.improve",skillName:e.existingSkillName,reason:"negative user feedback on existing skill execution"}:kr(e,t)?(Fo=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 Do(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 br(e){return e==="enabled-eligible"||e==="installed-awaiting-approval"}function xr(e){return new Map((e??[]).map(t=>[t.toolName,t]))}function _r(e){if(!e.eligibility?.length)return[...e.tools];let t=xr(e.eligibility);return e.tools.filter(n=>{let o=Do(n);if(!o)return!1;let r=t.get(o);return!r||br(r.status)})}function Mr(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 ut(e){let t=Mr({toolChoice:e.toolChoice,thinkingEnabled:e.thinkingEnabled,compatibility:e.compatibility}),n=t.normalizedToolChoice,o=[...t.warnings],r=_r({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 s=n.function??void 0,i=typeof s?.name=="string"?s.name.trim():"";if(!i)throw new Error("tool_choice.function.name is required");let a=r.filter(u=>Do(u)===i);if(a.length===0)throw new Error(`tool_choice requested unknown tool: ${i}`);return{tools:a,normalizedToolChoice:{type:"function",function:{name:i}},extraSystemPrompt:`You must call the ${i} tool before responding.`,warnings:o}}return{tools:r,normalizedToolChoice:n,warnings:o}}var Ar=["stop","aborted","timeout","cancelled","interrupted","error"],vr=["tool_calls","toolCalls","function_call","functionCall","raw_tool_calls","rawToolCalls"];function $o(e){return e==null?[]:typeof e=="string"?e.length>0?[{type:"text",text:e}]:[]:Array.isArray(e)?e:[{type:"text",text:String(e)}]}function Sr(e,t){return{...e,content:[...$o(e.content),...$o(t.content)]}}function Er(e){let t=new Set;if(e.role!=="assistant"||!Array.isArray(e.tool_calls))return t;for(let n of e.tool_calls)typeof n.id=="string"&&n.id&&t.add(n.id);return t}function wr(e){let t=new Set,n=[];for(let o=0;o<e.length;o+=1){if(t.has(o))continue;let r=e[o];if(!r)continue;n.push(r);let s=Er(r);if(s.size!==0)for(let i=o+1;i<e.length;i+=1){if(t.has(i))continue;let a=e[i];a?.role==="tool"&&typeof a.tool_call_id=="string"&&s.has(a.tool_call_id)&&(n.push(a),t.add(i))}}return n}function Ir(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 Pr(e){return new Set((e??Ar).map(t=>t.trim().toLowerCase()))}function Lr(e,t){return e?Pr(t).has(e.trim().toLowerCase()):!1}function dt(e){if(!Array.isArray(e)||e.length===0)return[...e];let t=e.map(u=>{if(u.role==="assistant"&&Array.isArray(u.tool_calls)){let p=u.tool_calls.filter(f=>Ir(f));return{...u,...p.length>0?{tool_calls:p}:{tool_calls:void 0}}}return{...u}}),n=new Set;for(let u of t)if(!(u.role!=="assistant"||!Array.isArray(u.tool_calls)))for(let p of u.tool_calls)typeof p.id=="string"&&p.id&&n.add(p.id);let o=t.filter(u=>u.role!=="tool"?!0:!!(u.tool_call_id&&n.has(u.tool_call_id))),r=new Set;for(let u of o)u.role==="tool"&&typeof u.tool_call_id=="string"&&u.tool_call_id&&r.add(u.tool_call_id);let s=[];for(let u of o){if(u.role==="assistant"&&Array.isArray(u.tool_calls)&&u.tool_calls.length>0){let p=u.tool_calls.filter(f=>typeof f.id=="string"&&r.has(f.id));if(p.length===0){let{tool_calls:f,...m}=u;m.content!=null&&m.content!==""&&s.push(m);continue}if(p.length<u.tool_calls.length){s.push({...u,tool_calls:p});continue}}s.push(u)}let i=wr(s),a=[];for(let u of i){let p=a.length>0?a[a.length-1]:void 0;if(u.role==="user"&&p?.role==="user"){a[a.length-1]=Sr(p,u);continue}a.push(u)}return a}function pt(e,t){return Lr(t?.stopReason,t?.forcedStopReasons)?e.map(n=>{if(n.role!=="assistant")return{...n};let o={...n};for(let r of vr)delete o[r];return o}):[...e]}function mt(e,t){let n=t?.placeholderToolResult??"Error: Tool loop interrupted before the tool result was replayed.",o=new Set;for(let s of e)s.role==="tool"&&typeof s.tool_call_id=="string"&&s.tool_call_id&&o.add(s.tool_call_id);let r=[];for(let s of e)if(r.push({...s}),!(s.role!=="assistant"||!Array.isArray(s.tool_calls)||s.tool_calls.length===0))for(let i of s.tool_calls)typeof i.id!="string"||!i.id||o.has(i.id)||(o.add(i.id),r.push({role:"tool",tool_call_id:i.id,content:n}));return r}function ft(e,t){let n=dt(e),o=pt(n,t);return mt(o,t)}function Or(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 Fr(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 Nr(e){return{round:e.round??0,maxRounds:e.maxRounds,pendingToolCallIds:[...e.pendingToolCallIds??[]],completedToolCallIds:[...e.completedToolCallIds??[]],lastStopReason:e.lastStopReason,replayMessages:[...e.replayMessages??[]]}}function gt(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 Oe(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 Fe(e){let t=[],n=dt(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=pt(n,e.options);o.some((s,i)=>s!==n[i])&&t.push({kind:"strip-forced-stop-tool-metadata",detail:"Removed assistant tool-call metadata after forced stop."});let r=mt(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:Nr({maxRounds:e.maxRounds,round:e.round,lastStopReason:e.lastStopReason,replayMessages:r,pendingToolCallIds:Or(r),completedToolCallIds:Fr(r)}),recoveryActions:t}}var Br=new Set(["main","sdk","agent","compact","hook","verification","side_question"]);function yt(e){return e?Br.has(e):!0}function ht(e){return e===429||e===529}function Ne(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 ci={maxBackoffMs:300*1e3,resetCapMs:360*60*1e3,heartbeatIntervalMs:3e4};function Be(){let e=process.env.QLOGICAGENT_PERSISTENT_RETRY;return e==="1"||e==="true"}var ke=class extends Error{constructor(n,o){super(`Model fallback triggered: ${n} -> ${o}`);this.originalModel=n;this.fallbackModel=o;this.name="FallbackTriggeredError"}originalModel;fallbackModel};function Tt(e){return{promptTokens:0,hasAttemptedReactiveCompact:!1,currentMaxOutputTokens:e.maxOutputTokens,consecutiveTruncations:0,aborted:e.abortSignal?.aborted??!1}}function Ct(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 kt(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 Rt(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 bt(e,t){return e.aborted?!0:t.abortSignal?.aborted?(e.aborted=!0,!0):!1}var $r={maxConsecutiveFailures:3,minMessagesAfterCompact:4,targetUsagePercent:50};function xt(){return{consecutiveFailures:0,attemptedThisTurn:!1,lastCompactAt:null,toolsAtLastCompact:[]}}function le(e,t=$r){return!(e.attemptedThisTurn||e.consecutiveFailures>=t.maxConsecutiveFailures)}function _t(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 E(e,t,n,o){e?.invoke(t,n).catch(r=>{let s=r instanceof Error?r.message:String(r);o.warn(`[hook:${t}] handler failed: ${s}`)})}function Uo(e,t){let n=typeof t.message?.content=="string"?t.message.content:"",o=n?n.slice(0,2e3):void 0,r=t.details,s=typeof r?.stdout=="string"?r.stdout.slice(0,8e3):void 0,i=typeof r?.stderr=="string"?r.stderr.slice(0,4e3):void 0,a=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:a,stdout:s,stderr:i,details:r}}function jo(e,t){if(!t.ok)return[];let n=t.details;if(!n)return[];let o=Ur(n);return o?(Array.isArray(n.mediaUrls)?n.mediaUrls.filter(s=>typeof s=="string"&&s.trim().length>0):[]).map(s=>({type:"media_result",turnId:e,mediaType:o,url:s,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 Ur(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 jr=new Set(["write","edit","patch"]);function qo(e){let{turnId:t,result:n,toolCalls:o}=e;if(!n.ok)return[];let r=o.find(a=>a.id===n.callId);if(!r)return[];let s=[],i=qr(r.function.arguments);if(!i)return s;if(n.toolName==="plan_mode"&&i.action==="exit"&&typeof i.plan=="string"&&i.plan.length>0&&s.push({type:"plan_update",turnId:t,slug:"approved-plan",content:i.plan}),jr.has(n.toolName)){let a=Hr(i);a&&s.push({type:"artifact",turnId:t,artifactId:`artifact-${n.callId}`,artifactType:zr(a),title:a.split(/[\\/]/).pop()||a,filePath:a,language:Gr(a)})}return s}function qr(e){try{return JSON.parse(e)}catch{return null}}function Hr(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 zr(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 Gr(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 Kr=/^no (matches|files|results) found(?:\s+for:.*)?\.?$|^file not found|^not found|^0 results|^\(exit code \d+, no output\)$/i,Wr=new Set(["search","web_search","grep","glob","find","list","read","exec"]),Xr=/[A-Za-z]:[\\/](?:[^\s"'`<>|,\uFF0C\u3001;\uFF1B\u3002]+[\\/])*[^\s"'`<>|,\uFF0C\u3001;\uFF1B\u3002]+\.[A-Za-z0-9]{1,12}/g,Yr=/(?:^|[\s"'`([{,;:\uFF0C\u3001\uFF1B])((?:[A-Za-z0-9._-]+[\\/])+[A-Za-z0-9][A-Za-z0-9._-]*\.(?:xlsx|xls|pptx|ppt|docx|pdf|md|markdown|html|css|js|jsx|ts|tsx|json|csv|tsv|png|jpg|jpeg|webp|svg|gif|mp4|mov|wav|mp3|m4a|zip|petdex))(?:$|[\s"'`\])},;:\uFF0C\u3001\uFF1B\u3002])/gi,Vr=/(?:^|[\s"'`([{,;:\uFF0C\u3001\uFF1B])([A-Za-z0-9][A-Za-z0-9._-]*\.(?:xlsx|xls|pptx|ppt|docx|pdf|md|markdown|html|css|js|jsx|ts|tsx|json|csv|tsv|png|jpg|jpeg|webp|svg|gif|mp4|mov|wav|mp3|m4a|zip|petdex))(?:$|[\s"'`\])},;:\uFF0C\u3001\uFF1B\u3002])/gi,Zr=/\b(?:create|generate|write|produce|save|output|deliver|deliverables?|artifacts?|required|required files?|must generate|self-verify)\b|(?:生成|创建|写入|输出|保存|交付|产物|文件|必须|自检|验证)/i;function Ho(e){if(!Wr.has(e.toolName))return!1;let t=typeof e.message?.content=="string"?e.message.content.trim():"";return t.length>0&&t.length<200&&Kr.test(t)}function Mt(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()}}var Jr=/\b(?:build|create|make|develop|implement|scaffold|generate)\b[\s\S]{0,40}\b(?:app|application|game|website|web ?app|site|system|tool|project|dashboard|platform|service|server)\b|(?:做|搭|写|开发|实现|构建|生成|搭建)[\s\S]{0,12}(?:游戏|应用|网站|系统|程序|项目|工具|平台|服务|网页|app)/i,zo=50;function Go(e){if(!e)return!1;for(let t of e)if(t.role==="user"&&typeof t.content=="string"&&Jr.test(t.content))return!0;return!1}function Ko(e,t){if(typeof e=="number"&&Number.isFinite(e)&&e>=1)return Math.min(Math.round(e),100);let n=De(t);return n>=3?Math.min(Math.max(25,20+n*15),100):Go(t)?Math.min(Math.max(25,zo),100):25}function De(e){if(!e)return 0;let t=new Set,n=new Set,o=r=>{let s=r.replace(/[),.;:\uFF0C\u3002\uFF1B\u3001]+$/u,"").replace(/\\/g,"/").toLowerCase();t.add(`path:${s}`);let i=s.split("/").pop();i&&n.add(i)};for(let r of e){if(r.role!=="user"||typeof r.content!="string")continue;let s=r.content;for(let i of r.content.matchAll(Xr))o(i[0]);if(Zr.test(s)){for(let i of s.matchAll(Yr)){let a=i[1]?.toLowerCase();if(!a)continue;t.add(`relative:${a.replace(/\\/g,"/")}`);let u=a.replace(/\\/g,"/").split("/").pop();u&&n.add(u)}for(let i of s.matchAll(Vr)){let a=i[1]?.toLowerCase();!a||n.has(a)||t.add(`name:${a}`)}}}return t.size}function Wo(e,t){if(typeof e=="number"&&Number.isFinite(e)&&e>=1)return Math.min(Math.round(e),100);let n=De(t);return n>=3?Math.min(Math.max(re,20+n*15),100):Go(t)?Math.min(Math.max(re,zo),100):re}function Xo(e){return e.filter(t=>t.role!=="assistant"?!0:!(typeof t.content=="string"&&t.content.trim()===""))}function At(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 No(e){try{let t=JSON.parse(e),n=[t.description,t.command,t.query,t.url,t.path,t.file_path,t.filePath,t.pattern,t.model].find(s=>typeof s=="string"&&s.trim().length>0);if(typeof n=="string")return n.trim().slice(0,240);let r=Object.keys(t);return r.length>0?r.slice(0,5).join(" / "):void 0}catch{return}}function kt(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 Do(e){return e==="length"||e==="max_tokens"}function Rt(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 Bo(e){let t=e.headers;if(!t)return null;let o=t["retry-after"]??t["Retry-After"];if(!o)return null;let n=parseInt(o,10);return!isNaN(n)&&n>0?n*1e3:null}function $o(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 o=parseInt(t[1],10),n=parseInt(t[3],10);if(isNaN(o)||isNaN(n))return null;let r=n-o-1e3;return r>=3e3?r:null}async function*Uo(e){let{messages:t,contentReplacementState:o,snipRemovedIds:n,collapseStore:r,guardConfig:s,runtimePorts:i,hooks:a,hookCtx:d,sessionId:p,currentModel:f,log:m,recovery:b,onAutocompact:T}=e,h;{let k=await i.enforceToolResultBudget(t,o,p);h=k.messages,k.newlyReplacedCount>0&&(m.info(`tool-result-budget: persisted ${k.newlyReplacedCount} oversized tool results`),yield b("tool_result_budget",`${k.newlyReplacedCount} persisted`))}{let k=Xe(h,n);h=k.messages,k.removedCount>0&&(m.info(`snip: removed ${k.removedCount} messages, freed ~${k.tokensFreed} tokens`),yield b("snip",`${k.removedCount} messages`))}{let _=new me().compress(h,0);_.droppedCount>0&&(h=_.messages,m.info(`microcompact: cleared ${_.droppedCount} old tool results`))}if(h=Ve(h,r).messages,s.contextWindowTokens>0){let k=s.contextWindowTokens*.75,_=i.getActiveContextCompressionEngine(),R;_?R=await _.compressAsync(h,k,{model:f,sessionId:p}):R=i.compressMessages(h,{budget:k,model:f}),R.droppedCount>0&&(h=R.messages,m.info(`autocompact: ${R.strategy}, dropped ${R.droppedCount}`),yield b("autocompact",`${R.strategy}: ${R.droppedCount} dropped`),T(),S(a,"context.after_compact",{...d,removedCount:R.droppedCount},m))}return h=Fo(h),h}async function*jo(e,t){let{state:o,guardState:n,fallbackModel:r,signal:s,querySource:i,turnId:a,log:d,emitRecovery:p}=t;if(e instanceof fe&&r)return d.info(`model fallback triggered: ${e.originalModel} -> ${e.fallbackModel}`),yield p("model_fallback",`${e.originalModel} -> ${e.fallbackModel}`),{kind:"continue",patch:{currentModel:e.fallbackModel,consecutive529Errors:0,consecutiveApiRetries:0,transition:void 0}};let f=e instanceof Error?e.message:String(e),m=typeof e?.status=="number"?e.status:void 0;if(!m&&f&&(f.includes("ECONNRESET")||f.includes("EPIPE"))){let T=(o.consecutiveApiRetries??0)+1;return T>re?(d.info(`stale connection retry limit reached (${re}), aborting`),yield{type:"error",turnId:a,error:f,code:"RETRIES_EXHAUSTED",usage:o.totalUsage},{kind:"return"}):(d.info(`stale connection (${f.includes("ECONNRESET")?"ECONNRESET":"EPIPE"}): retrying`),yield p("stale_connection_retry",f.slice(0,80)),{kind:"continue",patch:{consecutiveApiRetries:T,transition:void 0}})}let b=$o({status:m,message:f});if(b!==null)return d.info(`max_tokens overflow: adjusting to ${b}`),n.currentMaxOutputTokens=b,{kind:"continue",patch:{maxOutputTokensOverride:b,transition:void 0}};if(ut(m)){o.consecutive529Errors++;let T=2,h=r&&o.currentModel!==r;if(o.consecutive529Errors>T&&!h&&!ve())return d.info(`transient ${m} \u8133 ${o.consecutive529Errors}: hard limit reached, aborting`),yield{type:"error",turnId:a,error:`API unavailable after ${o.consecutive529Errors} consecutive ${m} errors`,code:"API_ERROR",usage:o.totalUsage},{kind:"return"};if(o.consecutive529Errors>=mo&&r&&o.currentModel!==r)return d.info(`529 \u8133 ${o.consecutive529Errors}: triggering fallback to ${r}`),yield p("model_fallback",`529 \u8133 ${o.consecutive529Errors}`),{kind:"continue",patch:{currentModel:r,consecutive529Errors:0,transition:void 0}};if(ve()){let k=Ae(o.consecutive529Errors);d.info(`persistent retry: waiting ${k}ms (attempt ${o.consecutive529Errors})`);let _=k;for(;_>0;){if(s?.aborted)return yield{type:"error",turnId:a,error:"Aborted during retry wait",code:"ABORTED",usage:o.totalUsage},{kind:"return"};yield{type:"heartbeat",turnId:a,message:`Retrying in ${Math.ceil(_/1e3)}s (${m})`};let R=Math.min(_,po);await new Promise(P=>setTimeout(P,R)),_-=R}return{kind:"continue",patch:{transition:void 0}}}if(ct(i)){let _=Bo({status:m,message:f})??Ae(o.consecutive529Errors);return d.info(`transient ${m}: retry in ${_}ms`),yield p("retry",`${m} retry in ${_}ms`),await new Promise(R=>setTimeout(R,_)),{kind:"continue",patch:{transition:void 0}}}d.info(`background source ${i}: not retrying ${m}`)}return{kind:"streamError",streamError:{status:m,message:f}}}import{readdirSync as Go,statSync as Ie}from"node:fs";var jr=/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,qr=/[A-Za-z]:[\\/](?:[^\s"'`<>|,\uFF0C\u3001;\uFF1B\u3002]+[\\/])*[^\s"'`<>|,\uFF0C\u3001;\uFF1B\u3002]+\.[A-Za-z0-9]{1,12}/g,qo=/\s*[,\uFF0C\u3001;\uFF1B]\s*([^\s"'`<>|,\uFF0C\u3001;\uFF1B\u3002\\/]+\.[A-Za-z0-9]{1,12})/gy,zr=/\b(?:in|into|under|to|at|output(?:\s+to)?|save(?:\s+to)?|saved?\s+under)\s+([A-Za-z]:[\\/][^\s"'`<>|,\uFF0C\u3001;\uFF1B\u3002]+)/gi,Hr=/(?:^|[\s"'`([{,;:\uFF0C\u3001\uFF1B])([A-Za-z0-9][A-Za-z0-9._-]*\.(?:xlsx|xls|pptx|ppt|docx|pdf|md|markdown|html|css|js|jsx|ts|tsx|json|csv|tsv|png|jpg|jpeg|webp|svg|gif|mp4|mov|wav|mp3|m4a|zip|petdex))(?:$|[\s"'`\])},;:\uFF0C\u3001\uFF1B\u3002])/gi,Gr=/(?:^|[\s"'`([{,;:\uFF0C\u3001\uFF1B])([A-Za-z0-9][A-Za-z0-9._-]*(?:[\\/][A-Za-z0-9][A-Za-z0-9._-]*)+\.(?:xlsx|xls|pptx|ppt|docx|pdf|md|markdown|html|css|js|jsx|ts|tsx|json|csv|tsv|png|jpg|jpeg|webp|svg|gif|mp4|mov|wav|mp3|m4a|zip|petdex))(?:$|[\s"'`\])},.;:\uFF0C\u3001\uFF1B\u3002])/gi,Kr=/(?:^|[\s"'`([{,;:\uFF0C\u3001\uFF1B])([A-Za-z0-9][A-Za-z0-9._-]*(?:[\\/][A-Za-z0-9][A-Za-z0-9._-]*)+)[\\/]?(?:$|[\s"'`\])},;:\uFF0C\u3001\uFF1B\u3002])/gi,Wr=/\b(?:create|generate|write|produce|save|output|deliver|deliverables?|artifacts?|required|required files?|must generate|self-verify)\b|(?:生成|创建|写入|输出|保存|交付|产物|文件|必须|自检|验证)/i,Xr=/\bpreviews?[\\/]\s*(?:containing|with|under|for)?[^.。;;\n]*(?:rendered|preview|previews|check|evidence|verify|verification)\b/i;function B(e){return e.trim().replace(/[),.;:\uFF0C\u3002\uFF1B\u3001]+$/u,"").replace(/\\/g,"/").toLowerCase()}function Ko(e){return e.trim().replace(/[),.;:\uFF0C\u3002\uFF1B\u3001]+$/u,"").replace(/\\/g,"/").replace(/\/+$/u,"")}function zo(e){return/\.[A-Za-z0-9]{1,12}$/u.test(e.replace(/[),.;:\uFF0C\u3002\uFF1B\u3001]+$/u,""))}function Ho(e,t,o){let n=Math.max(e.lastIndexOf(".",t),e.lastIndexOf(`
5
- `,t),e.lastIndexOf(";",t),e.lastIndexOf("\u3002",t),e.lastIndexOf("\uFF1B",t))+1,r=e.slice(n,t).toLowerCase();if(/\b(?:do\s+not|don't|never)\s+(?:leave|create|write|include|keep|produce|add|generate)\b/i.test(r)||/\b(?:remove|delete|exclude)\b/i.test(r))return!0;let s=e.slice(Math.max(0,t-16),t+o.length);return new RegExp(`\\bno\\s+${Pe(o)}\\b`,"i").test(s)}function Le(e){let t=new Set,o=[],n=r=>{let s=r.replace(/[),.;:\uFF0C\u3002\uFF1B]+$/u,""),i=B(s);t.has(i)||(t.add(i),o.push(s))};for(let r of e)if(!(r.role!=="user"||typeof r.content!="string"))for(let s of r.content.matchAll(qr)){let i=s[0];n(i);let a=(s.index??0)+i.length,d=i.replace(/\\/g,"/"),p=d.lastIndexOf("/");if(p>=0){let f=d.slice(0,p+1);qo.lastIndex=a;let m;for(;(m=qo.exec(r.content))!==null;)n(`${f}${m[1]}`)}}for(let r of e){if(r.role!=="user"||typeof r.content!="string")continue;let s=r.content;if(!Wr.test(s))continue;let i=Array.from(s.matchAll(zr)).map(d=>Ko(d[1]??"")).filter(d=>d&&!zo(d));if(i.length===0)continue;let a=i[i.length-1];for(let d of s.matchAll(Hr)){let p=d[1];p&&(Ho(s,d.index??0,p)||n(`${a}/${p}`))}for(let d of s.matchAll(Gr)){let p=d[1];p&&(Ho(s,d.index??0,p)||n(`${a}/${p}`))}for(let d of s.matchAll(Kr)){let p=d[1];p&&(zo(p)||/(?:assets[\\/]generated|screenshots(?:[\\/]|$)|previews(?:[\\/]|$))/i.test(p)&&/\b(?:generated|bitmap|png|screenshots?|preview|previews|evidence|assets?|containing)\b/i.test(s)&&n(`${a}/${p}/*`))}Xr.test(s)&&n(`${a}/previews/*`)}return o}function Wo(e){if(e.role!=="tool")return!1;let t=typeof e.content=="string"?e.content:"";return e.is_error!==!0&&!t.startsWith("Error:")}function Xo(e){let t=new Set,o=new Map,n=[];for(let r of e){let s=r,i=Array.isArray(s.tool_calls)?s.tool_calls:[];for(let a of i){let d=a,p=d.id,f=d.function;typeof p=="string"&&typeof f?.name=="string"&&o.set(p,f.name)}}for(let r of e){let s=r;if(Wo(s)){let i=s.tool_call_id;typeof i=="string"&&t.add(i),(typeof i=="string"?o.get(i):void 0)==="exec"&&typeof s.content=="string"&&n.push(s.content)}}for(let r of e){let s=r,i=Array.isArray(s.tool_calls)?s.tool_calls:[];for(let a of i){let d=a,p=d.id;if(typeof p=="string"&&t.size>0&&!t.has(p))continue;let f=d.function;if(!(typeof f?.name!="string"||typeof f.arguments!="string"))try{let m=JSON.parse(f.arguments);if(f.name==="write"||f.name==="edit"){for(let b of["path","filePath","file_path"]){let T=m[b];typeof T=="string"&&n.push(T)}continue}if(f.name==="exec"){let b=m.command;typeof b=="string"&&n.push(b)}}catch{f.name==="exec"&&n.push(f.arguments)}}}return n.join(`
6
- `).replace(/\\/g,"/").toLowerCase()}function xt(e){try{if(e.endsWith("/*")){let o=e.slice(0,-2);return Go(o,{withFileTypes:!0}).some(r=>{if(!r.isFile())return!1;try{return Ie(`${o}/${r.name}`).size>0}catch{return!1}})}let t=Ie(e);return t.isFile()&&t.size>0}catch{return!1}}function Yr(e,t){let o=B(t);if(!o.endsWith("/*"))return e.includes(o);let n=o.slice(0,-1);return e.includes(n)}function Vr(e){let t=Mt(e);return/\b(?:exactly|only)\b[^.\n]*(?:artifacts?|files?|outputs?|deliverables?)/i.test(t)||/(?:artifacts?|files?|outputs?|deliverables?)[^.\n]*\b(?:exactly|only)\b/i.test(t)}function Zr(e){let t=Ko(e),o=t.lastIndexOf("/");return o>=0?t.slice(0,o):""}function Jr(e){if(e.length===0)return"";let t=e.map(n=>Zr(n).split("/")),o=[];for(let n=0;n<t[0].length;n++){let r=t[0][n];if(t.every(s=>s[n]?.toLowerCase()===r.toLowerCase()))o.push(r);else break}return o.join("/")}function Qr(e,t){let o=B(e);return t.some(n=>{let r=B(n);return r.endsWith("/*")?o.startsWith(r.slice(0,-1)):o===r})}function es(e){let t=new Set,o=new Map;for(let n of e){let r=n,s=Array.isArray(r.tool_calls)?r.tool_calls:[];for(let i of s){let a=i,d=a.id,p=a.function;if(typeof d!="string"||p?.name!=="write"&&p?.name!=="edit"||typeof p.arguments!="string")continue;let f=Qo(p.arguments);if(!f)continue;let m=en(f);m&&o.set(d,m)}}for(let n of e){let r=n;if(!Wo(r))continue;let s=r.tool_call_id;typeof s=="string"&&t.add(s)}return[...o.entries()].filter(([n])=>t.has(n)).map(([,n])=>n)}function ts(e){let t=[],o=n=>{let r;try{r=Go(n,{withFileTypes:!0})}catch{return}for(let s of r){let i=`${n}/${s.name}`;if(s.isDirectory()){o(i);continue}if(s.isFile())try{Ie(i).size>0&&t.push(i)}catch{}}};try{if(!Ie(e).isDirectory())return[]}catch{return[]}return o(e),t}function Yo(e,t){if(!Vr(e))return[];let o=Le(e),n=o.filter(i=>!B(i).endsWith("/*"));if(n.length<2)return[];let r=Jr(n);if(!r||r.split("/").length<3)return[];let s=B(r);return[...new Set([...es(t),...ts(r)])].filter(i=>B(i).startsWith(`${s}/`)&&!Qr(i,o)&&xt(i))}function _t(e,t){let o=Le(e);if(o.length===0)return[];let n=Xo(t);return o.filter(r=>!Yr(n,r))}function bt(e){return ge(e).fail}function os(e){return e.replace(/[.,;:]+$/u,"")}function we(e){if(!e)return!1;let t=os(e);return/^[A-Za-z0-9_.:-]+$/u.test(t)&&/[0-9_:-]/u.test(t)}function ge(e){let t=r=>r.replace(/[.,;:]+$/u,""),o,n;for(let r of e)if(!(r.role!=="user"||typeof r.content!="string")){for(let s of r.content.matchAll(/\b(DONE|PASS)\s+([A-Za-z0-9_.:-]+)/gi))we(s[2])&&(o=`${s[1].toUpperCase()} ${t(s[2])}`);for(let s of r.content.matchAll(/\bFAIL\s+([A-Za-z0-9_.:-]+)/gi))we(s[1])&&(n=`FAIL ${t(s[1])}`);for(let s of r.content.matchAll(/\b([A-Za-z0-9_.:-]+)\s+(DONE|PASS)\b/gi))we(s[1])&&(o=`${t(s[1])} ${s[2].toUpperCase()}`);for(let s of r.content.matchAll(/\b([A-Za-z0-9_.:-]+)\s+FAIL\b/gi))we(s[1])&&(n=`${t(s[1])} FAIL`)}return{done:o,fail:n}}function Vo(e){let t=n=>n.replace(/[.,;:]+$/u,""),o;for(let n of e){if(n.role!=="user"||typeof n.content!="string")continue;let r=n.content;for(let s of r.matchAll(/\bMarker\s*:\s*([A-Za-z0-9_.:-]+)/gi))o=t(s[1]);for(let s of r.matchAll(/\b(?:include|with|contains?)\s+marker\s+([A-Za-z0-9_.:-]+)/gi))o=t(s[1])}return o}function Mt(e){for(let t=e.length-1;t>=0;t--){let o=e[t];if(o.role==="user"&&typeof o.content=="string")return o.content}return""}function Pe(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Zo(e,t){let o=Mt(e);for(let n of[t.done,t.fail]){if(!n)continue;let s=new RegExp(`\\bfinal\\s+(?:answer|response|reply)\\s+exactly\\s*:?\\s*${Pe(n)}([^\\n]*)`,"i").exec(o);if(s){let p=(s[1]??"").trimStart();if(p===""||/^[.!?]/u.test(p))return n}let a=new RegExp(`\\b(?:reply|respond)\\s+exactly(?:\\s+with)?\\s*:?\\s*${Pe(n)}([^\\n]*)`,"i").exec(o);if(!a)continue;let d=(a[1]??"").trimStart();if(d===""||/^[.!?。!?]/u.test(d))return n}}function ns(e,t,o){let n=Mt(e),r=[t.done,t.fail,o].filter(s=>typeof s=="string"&&s.length>0);return[...new Set(r)].filter(s=>new RegExp(`\\bstarts?\\s+with\\s+${Pe(s)}\\b`,"i").test(n))}function te(e){let t=_t(e.inputMessages,e.messages).filter(n=>!xt(n));return t.length===0?void 0:`${bt(e.inputMessages)??"FAIL"} ${e.reason}. Missing required output file evidence: ${t.join(", ")}`}function Oe(e){let t=ge(e.inputMessages);if(!t.done){let n=Vo(e.inputMessages);return n?`FAIL ${n} ${e.reason}. The model did not produce the requested final marker ${n}.`:void 0}return`${t.fail??"FAIL"} ${e.reason}. The model did not produce the requested final marker ${t.done}.`}function Jo(e){let t=ge(e.inputMessages),o=Zo(e.inputMessages,t);if(!(!o||Le(e.inputMessages).length===0||_t(e.inputMessages,e.messages).filter(i=>!xt(i)).length>0||Yo(e.inputMessages,e.messages).length>0))return o}function Qo(e){try{let t=JSON.parse(e);return t&&typeof t=="object"&&!Array.isArray(t)?t:null}catch{return null}}function en(e){for(let t of["path","filePath","file_path"]){let o=e[t];if(typeof o=="string"&&o.trim())return o}}function rs(e){for(let t of["content","newContent","replacement","text"]){let o=e[t];if(typeof o=="string")return o}return""}function tn(e){let t=e.toolCall.function.name;if(t!=="write"&&t!=="edit")return;let o=ge(e.inputMessages);if(!o.done)return;let n=Qo(e.toolCall.function.arguments);if(!n)return;let r=en(n),s=rs(n);if(!r||!s.includes(o.done))return;let i=Le(e.inputMessages);if(i.length<2)return;let a=B(r);if(!i.some(m=>B(m)===a))return;let p=Xo(e.messages),f=i.filter(m=>B(m)!==a).filter(m=>!p.includes(B(m)));if(f.length!==0)return`Premature completion artifact blocked: this write/edit attempted to store the requested DONE marker in ${r} before evidence existed for sibling required output files: ${f.join(", ")}. Create or verify the missing files first, or report the requested FAIL marker with the real reason.`}function Q(e,t){return{role:"assistant",content:e,...t.length>0&&{thinkingBlocks:[...t]}}}function ss(e){let t=e,o=t.is_error===!0||typeof t.content=="string"&&t.content.startsWith("Error:");return t.role==="tool"&&typeof t.content=="string"&&!o}function is(e){let t=[...e].reverse().find(o=>o.role==="tool");t&&typeof t.content=="string"&&(t.content+=`
4
+ `)):""}function Yo(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(s=>typeof s=="string"&&s.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 vt(e){if(e.continuationCount>=5||e.currentToolBudget>=e.toolHardCap&&e.currentRoundBudget>=e.roundHardCap||e.successfulSinceLastCheck<=0)return null;for(let t of e.fileReadCounts.values())if(t>=3)return null;return{nextToolBudget:Math.min(e.currentToolBudget+e.windowTools,e.toolHardCap),nextRoundBudget:Math.min(e.currentRoundBudget+e.windowRounds,e.roundHardCap),continuationCount:e.continuationCount+1}}function St(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 Vo(e){return e==="length"||e==="max_tokens"}function Et(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 Zo(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 Jo(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*Qo(e){let{messages:t,contentReplacementState:n,snipRemovedIds:o,collapseStore:r,guardConfig:s,runtimePorts:i,hooks:a,hookCtx:u,sessionId:p,currentModel:f,log:m,recovery:k,onAutocompact:M}=e,g;{let T=await i.enforceToolResultBudget(t,n,p);g=T.messages,T.newlyReplacedCount>0&&(m.info(`tool-result-budget: persisted ${T.newlyReplacedCount} oversized tool results`),yield k("tool_result_budget",`${T.newlyReplacedCount} persisted`))}{let T=ot(g,o);g=T.messages,T.removedCount>0&&(m.info(`snip: removed ${T.removedCount} messages, freed ~${T.tokensFreed} tokens`),yield k("snip",`${T.removedCount} messages`))}{let b=new Ce().compress(g,0);b.droppedCount>0&&(g=b.messages,m.info(`microcompact: cleared ${b.droppedCount} old tool results`))}if(g=rt(g,r).messages,s.contextWindowTokens>0){let T=s.contextWindowTokens*.75,b=i.getActiveContextCompressionEngine(),R;b?R=await b.compressAsync(g,T,{model:f,sessionId:p}):R=i.compressMessages(g,{budget:T,model:f}),R.droppedCount>0&&(g=R.messages,m.info(`autocompact: ${R.strategy}, dropped ${R.droppedCount}`),yield k("autocompact",`${R.strategy}: ${R.droppedCount} dropped`),M(),E(a,"context.after_compact",{...u,removedCount:R.droppedCount},m))}return g=Xo(g),g}async function*en(e,t){let{state:n,guardState:o,fallbackModel:r,signal:s,querySource:i,turnId:a,log:u,emitRecovery:p}=t;if(e instanceof ke&&r)return u.info(`model fallback triggered: ${e.originalModel} -> ${e.fallbackModel}`),yield p("model_fallback",`${e.originalModel} -> ${e.fallbackModel}`),{kind:"continue",patch:{currentModel:e.fallbackModel,consecutive529Errors:0,consecutiveApiRetries:0,transition:void 0}};let f=e instanceof Error?e.message:String(e),m=typeof e?.status=="number"?e.status:void 0;if(!m&&f&&(f.includes("ECONNRESET")||f.includes("EPIPE"))){let M=(n.consecutiveApiRetries??0)+1;return M>ae?(u.info(`stale connection retry limit reached (${ae}), aborting`),yield{type:"error",turnId:a,error:f,code:"RETRIES_EXHAUSTED",usage:n.totalUsage},{kind:"return"}):(u.info(`stale connection (${f.includes("ECONNRESET")?"ECONNRESET":"EPIPE"}): retrying`),yield p("stale_connection_retry",f.slice(0,80)),{kind:"continue",patch:{consecutiveApiRetries:M,transition:void 0}})}let k=Jo({status:m,message:f});if(k!==null)return u.info(`max_tokens overflow: adjusting to ${k}`),o.currentMaxOutputTokens=k,{kind:"continue",patch:{maxOutputTokensOverride:k,transition:void 0}};if(ht(m)){n.consecutive529Errors++;let M=2,g=r&&n.currentModel!==r;if(n.consecutive529Errors>M&&!g&&!Be())return u.info(`transient ${m} \u8133 ${n.consecutive529Errors}: hard limit reached, aborting`),yield{type:"error",turnId:a,error:`API unavailable after ${n.consecutive529Errors} consecutive ${m} errors`,code:"API_ERROR",usage:n.totalUsage},{kind:"return"};if(n.consecutive529Errors>=Mo&&r&&n.currentModel!==r)return u.info(`529 \u8133 ${n.consecutive529Errors}: triggering fallback to ${r}`),yield p("model_fallback",`529 \u8133 ${n.consecutive529Errors}`),{kind:"continue",patch:{currentModel:r,consecutive529Errors:0,transition:void 0}};if(Be()){let T=Ne(n.consecutive529Errors);u.info(`persistent retry: waiting ${T}ms (attempt ${n.consecutive529Errors})`);let b=T;for(;b>0;){if(s?.aborted)return yield{type:"error",turnId:a,error:"Aborted during retry wait",code:"ABORTED",usage:n.totalUsage},{kind:"return"};yield{type:"heartbeat",turnId:a,message:`Retrying in ${Math.ceil(b/1e3)}s (${m})`};let R=Math.min(b,_o);await new Promise(A=>setTimeout(A,R)),b-=R}return{kind:"continue",patch:{transition:void 0}}}if(yt(i)){let b=Zo({status:m,message:f})??Ne(n.consecutive529Errors);return u.info(`transient ${m}: retry in ${b}ms`),yield p("retry",`${m} retry in ${b}ms`),await new Promise(R=>setTimeout(R,b)),{kind:"continue",patch:{transition:void 0}}}u.info(`background source ${i}: not retrying ${m}`)}return{kind:"streamError",streamError:{status:m,message:f}}}import{readdirSync as rn,statSync as Ue}from"node:fs";var Qr=/create\s+(?:a\s+)?file|write\s+(?:a\s+)?file|make\s+(?:a\s+)?file|\bfix\b|implement|modify|update|repair|generate\s+(?:a\s+)?file|new\s+file/i,es=/[A-Za-z]:[\\/](?:[^\s"'`<>|,\uFF0C\u3001;\uFF1B\u3002]+[\\/])*[^\s"'`<>|,\uFF0C\u3001;\uFF1B\u3002]+\.[A-Za-z0-9]{1,12}/g,tn=/\s*[,\uFF0C\u3001;\uFF1B]\s*([^\s"'`<>|,\uFF0C\u3001;\uFF1B\u3002\\/]+\.[A-Za-z0-9]{1,12})/gy,ts=/\b(?:in|into|under|to|at|output(?:\s+to)?|save(?:\s+to)?|saved?\s+under)\s+([A-Za-z]:[\\/][^\s"'`<>|,\uFF0C\u3001;\uFF1B\u3002]+)/gi,os=/(?:^|[\s"'`([{,;:\uFF0C\u3001\uFF1B])([A-Za-z0-9][A-Za-z0-9._-]*\.(?:xlsx|xls|pptx|ppt|docx|pdf|md|markdown|html|css|js|jsx|ts|tsx|json|csv|tsv|png|jpg|jpeg|webp|svg|gif|mp4|mov|wav|mp3|m4a|zip|petdex))(?:$|[\s"'`\])},;:\uFF0C\u3001\uFF1B\u3002])/gi,ns=/(?:^|[\s"'`([{,;:\uFF0C\u3001\uFF1B])([A-Za-z0-9][A-Za-z0-9._-]*(?:[\\/][A-Za-z0-9][A-Za-z0-9._-]*)+\.(?:xlsx|xls|pptx|ppt|docx|pdf|md|markdown|html|css|js|jsx|ts|tsx|json|csv|tsv|png|jpg|jpeg|webp|svg|gif|mp4|mov|wav|mp3|m4a|zip|petdex))(?:$|[\s"'`\])},.;:\uFF0C\u3001\uFF1B\u3002])/gi,rs=/(?:^|[\s"'`([{,;:\uFF0C\u3001\uFF1B])([A-Za-z0-9][A-Za-z0-9._-]*(?:[\\/][A-Za-z0-9][A-Za-z0-9._-]*)+)[\\/]?(?:$|[\s"'`\])},;:\uFF0C\u3001\uFF1B\u3002])/gi,ss=/\b(?:create|generate|write|produce|save|output|deliver|deliverables?|artifacts?|required|required files?|must generate|self-verify)\b|(?:生成|创建|写入|输出|保存|交付|产物|文件|必须|自检|验证)/i,is=/\bpreviews?[\\/]\s*(?:containing|with|under|for)?[^.。;;\n]*(?:rendered|preview|previews|check|evidence|verify|verification)\b/i;function U(e){return e.trim().replace(/[),.;:\uFF0C\u3002\uFF1B\u3001]+$/u,"").replace(/\\/g,"/").toLowerCase()}function sn(e){return e.trim().replace(/[),.;:\uFF0C\u3002\uFF1B\u3001]+$/u,"").replace(/\\/g,"/").replace(/\/+$/u,"")}function on(e){return/\.[A-Za-z0-9]{1,12}$/u.test(e.replace(/[),.;:\uFF0C\u3002\uFF1B\u3001]+$/u,""))}function nn(e,t,n){let o=Math.max(e.lastIndexOf(".",t),e.lastIndexOf(`
5
+ `,t),e.lastIndexOf(";",t),e.lastIndexOf("\u3002",t),e.lastIndexOf("\uFF1B",t))+1,r=e.slice(o,t).toLowerCase();if(/\b(?:do\s+not|don't|never)\s+(?:leave|create|write|include|keep|produce|add|generate)\b/i.test(r)||/\b(?:remove|delete|exclude)\b/i.test(r))return!0;let s=e.slice(Math.max(0,t-16),t+n.length);return new RegExp(`\\bno\\s+${Re(n)}\\b`,"i").test(s)}function je(e){let t=new Set,n=[],o=r=>{let s=r.replace(/[),.;:\uFF0C\u3002\uFF1B]+$/u,""),i=U(s);t.has(i)||(t.add(i),n.push(s))};for(let r of e)if(!(r.role!=="user"||typeof r.content!="string"))for(let s of r.content.matchAll(es)){let i=s[0];o(i);let a=(s.index??0)+i.length,u=i.replace(/\\/g,"/"),p=u.lastIndexOf("/");if(p>=0){let f=u.slice(0,p+1);tn.lastIndex=a;let m;for(;(m=tn.exec(r.content))!==null;)o(`${f}${m[1]}`)}}for(let r of e){if(r.role!=="user"||typeof r.content!="string")continue;let s=r.content;if(!ss.test(s))continue;let i=Array.from(s.matchAll(ts)).map(u=>sn(u[1]??"")).filter(u=>u&&!on(u));if(i.length===0)continue;let a=i[i.length-1];for(let u of s.matchAll(os)){let p=u[1];p&&(nn(s,u.index??0,p)||o(`${a}/${p}`))}for(let u of s.matchAll(ns)){let p=u[1];p&&(nn(s,u.index??0,p)||o(`${a}/${p}`))}for(let u of s.matchAll(rs)){let p=u[1];p&&(on(p)||/(?:assets[\\/]generated|screenshots(?:[\\/]|$)|previews(?:[\\/]|$))/i.test(p)&&/\b(?:generated|bitmap|png|screenshots?|preview|previews|evidence|assets?|containing)\b/i.test(s)&&o(`${a}/${p}/*`))}is.test(s)&&o(`${a}/previews/*`)}return n}function It(e){if(e.role!=="tool")return!1;let t=typeof e.content=="string"?e.content:"";return e.is_error!==!0&&!t.startsWith("Error:")}function an(e){let t=new Set,n=new Map,o=[];for(let r of e){let s=r,i=Array.isArray(s.tool_calls)?s.tool_calls:[];for(let a of i){let u=a,p=u.id,f=u.function;typeof p=="string"&&typeof f?.name=="string"&&n.set(p,f.name)}}for(let r of e){let s=r;if(It(s)){let i=s.tool_call_id;typeof i=="string"&&t.add(i),(typeof i=="string"?n.get(i):void 0)==="exec"&&typeof s.content=="string"&&o.push(s.content)}}for(let r of e){let s=r,i=Array.isArray(s.tool_calls)?s.tool_calls:[];for(let a of i){let u=a,p=u.id;if(typeof p=="string"&&t.size>0&&!t.has(p))continue;let f=u.function;if(!(typeof f?.name!="string"||typeof f.arguments!="string"))try{let m=JSON.parse(f.arguments);if(f.name==="write"||f.name==="edit"){for(let k of["path","filePath","file_path"]){let M=m[k];typeof M=="string"&&o.push(M)}continue}if(f.name==="exec"){let k=m.command;typeof k=="string"&&o.push(k)}}catch{f.name==="exec"&&o.push(f.arguments)}}}return o.join(`
6
+ `).replace(/\\/g,"/").toLowerCase()}function Pt(e){try{if(e.endsWith("/*")){let n=e.slice(0,-2);return rn(n,{withFileTypes:!0}).some(r=>{if(!r.isFile())return!1;try{return Ue(`${n}/${r.name}`).size>0}catch{return!1}})}let t=Ue(e);return t.isFile()&&t.size>0}catch{return!1}}function as(e,t){let n=U(t);if(!n.endsWith("/*"))return e.includes(n);let o=n.slice(0,-1);return e.includes(o)}function ls(e){let t=ue(e);return/\b(?:exactly|only)\b[^.\n]*(?:artifacts?|files?|outputs?|deliverables?)/i.test(t)||/(?:artifacts?|files?|outputs?|deliverables?)[^.\n]*\b(?:exactly|only)\b/i.test(t)}function cs(e){let t=sn(e),n=t.lastIndexOf("/");return n>=0?t.slice(0,n):""}function us(e){if(e.length===0)return"";let t=e.map(o=>cs(o).split("/")),n=[];for(let o=0;o<t[0].length;o++){let r=t[0][o];if(t.every(s=>s[o]?.toLowerCase()===r.toLowerCase()))n.push(r);else break}return n.join("/")}function ds(e,t){let n=U(e);return t.some(o=>{let r=U(o);return r.endsWith("/*")?n.startsWith(r.slice(0,-1)):n===r})}function ps(e){let t=new Set,n=new Map;for(let o of e){let r=o,s=Array.isArray(r.tool_calls)?r.tool_calls:[];for(let i of s){let a=i,u=a.id,p=a.function;if(typeof u!="string"||p?.name!=="write"&&p?.name!=="edit"||typeof p.arguments!="string")continue;let f=Bt(p.arguments);if(!f)continue;let m=Dt(f);m&&n.set(u,m)}}for(let o of e){let r=o;if(!It(r))continue;let s=r.tool_call_id;typeof s=="string"&&t.add(s)}return[...n.entries()].filter(([o])=>t.has(o)).map(([,o])=>o)}function ln(e){return/\bartifact[-_\s]?index\b/i.test(e)&&(/\b(?:evidence|status|failed|partial|passed|verified)\b/i.test(e)||/\bGoal\s+\d+\b/i.test(e))}function ms(e){return[...new Set([...e.matchAll(/\bGoal\s+\d+\b/gi)].map(t=>t[0].replace(/\s+/g," ").replace(/\bgoal\b/i,"Goal")))]}function cn(e){let t=new Set,n=new Map;for(let o of e){let r=o,s=Array.isArray(r.tool_calls)?r.tool_calls:[];for(let i of s){let a=i,u=a.id,p=a.function;if(typeof u!="string"||p?.name!=="write"&&p?.name!=="edit"||typeof p.arguments!="string")continue;let f=Bt(p.arguments);if(!f)continue;let m=Dt(f)??"",k=pn(f);(/\bartifact[-_\s]?index\b/i.test(m)||/\bartifact[-_\s]?index\b/i.test(k))&&n.set(u,k)}}for(let o of e){let r=o;if(!It(r))continue;let s=r.tool_call_id;typeof s=="string"&&t.add(s)}return[...n.entries()].filter(([o])=>t.has(o)).map(([,o])=>o).filter(o=>o.trim().length>0)}function un(e){let t=ue(e.inputMessages);if(!ln(t))return[];let n=cn(e.messages).at(-1);if(!n)return[];let o=[],r=ms(t).filter(u=>!new RegExp(`\\b${Re(u)}\\b`,"i").test(n));r.length>0&&o.push({type:"missing_goal_labels",detail:`Missing requested row labels in the generated index: ${r.join(", ")}`});let s=/\b(?:failed|partial|missing|not\s+found|no\s+[^.\n|]*evidence)\b/i.test(n),i=/\b(?:all\s+checks\s+pass|confirmed\s*:\s*all|everything\s+(?:passes|passed)|fully\s+verified)\b/i.test(e.finalText);s&&i&&o.push({type:"overconfident_final",detail:"Final response claimed all checks pass while the generated index contains failed, partial, missing, or no-evidence rows."});let a=n.split(/\r?\n/u).filter(u=>/\bno\s+[^|\n]*(?:found|evidence|files?)\b/i.test(u)&&!/\b(?:not\s+verified|unverified|unknown|not\s+checked|search\s+scope|checked\s+path)\b/i.test(u));return a.length>0&&o.push({type:"unsupported_absence",detail:`Absence claims need scoped evidence or must be marked unverified: ${a.slice(0,3).join(" ; ")}`}),o}function fs(e){let t=[],n=o=>{let r;try{r=rn(o,{withFileTypes:!0})}catch{return}for(let s of r){let i=`${o}/${s.name}`;if(s.isDirectory()){n(i);continue}if(s.isFile())try{Ue(i).size>0&&t.push(i)}catch{}}};try{if(!Ue(e).isDirectory())return[]}catch{return[]}return n(e),t}function dn(e,t){if(!ls(e))return[];let n=je(e),o=n.filter(i=>!U(i).endsWith("/*"));if(o.length<2)return[];let r=us(o);if(!r||r.split("/").length<3)return[];let s=U(r);return[...new Set([...ps(t),...fs(r)])].filter(i=>U(i).startsWith(`${s}/`)&&!ds(i,n)&&Pt(i))}function Lt(e,t){let n=je(e);if(n.length===0)return[];let o=an(t);return n.filter(r=>!as(o,r))}function wt(e){return be(e).fail}function gs(e){return e.replace(/[.,;:]+$/u,"")}function $e(e){if(!e)return!1;let t=gs(e);return/^[A-Za-z0-9_.:-]+$/u.test(t)&&/[0-9_:-]/u.test(t)}function be(e){let t=r=>r.replace(/[.,;:]+$/u,""),n,o;for(let r of e)if(!(r.role!=="user"||typeof r.content!="string")){for(let s of r.content.matchAll(/\b(DONE|PASS)\s+([A-Za-z0-9_.:-]+)/gi))$e(s[2])&&(n=`${s[1].toUpperCase()} ${t(s[2])}`);for(let s of r.content.matchAll(/\bFAIL\s+([A-Za-z0-9_.:-]+)/gi))$e(s[1])&&(o=`FAIL ${t(s[1])}`);for(let s of r.content.matchAll(/\b([A-Za-z0-9_.:-]+)\s+(DONE|PASS)\b/gi))$e(s[1])&&(n=`${t(s[1])} ${s[2].toUpperCase()}`);for(let s of r.content.matchAll(/\b([A-Za-z0-9_.:-]+)\s+FAIL\b/gi))$e(s[1])&&(o=`${t(s[1])} FAIL`)}return{done:n,fail:o}}function Ot(e){let t=o=>o.replace(/[.,;:]+$/u,""),n;for(let o of e){if(o.role!=="user"||typeof o.content!="string")continue;let r=o.content;for(let s of r.matchAll(/\bMarker\s*:\s*([A-Za-z0-9_.:-]+)/gi))n=t(s[1]);for(let s of r.matchAll(/\b(?:include|with|contains?)\s+marker\s+([A-Za-z0-9_.:-]+)/gi))n=t(s[1])}return n}function ue(e){for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.role==="user"&&typeof n.content=="string")return n.content}return""}function Re(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function ys(e,t){let n=ue(e);for(let o of[t.done,t.fail]){if(!o)continue;let s=new RegExp(`\\bfinal\\s+(?:answer|response|reply)\\s+exactly\\s*:?\\s*${Re(o)}([^\\n]*)`,"i").exec(n);if(s){let p=(s[1]??"").trimStart();if(p===""||/^[.!?]/u.test(p))return o}let a=new RegExp(`\\b(?:reply|respond)\\s+exactly(?:\\s+with)?\\s*:?\\s*${Re(o)}([^\\n]*)`,"i").exec(n);if(!a)continue;let u=(a[1]??"").trimStart();if(u===""||/^[.!?。!?]/u.test(u))return o}}function Ft(e,t){let n=ys(e,t);if(n)return n;let o=ue(e),r=Ot(e);if(r){let a=/\breply\s+with\s+(?:the\s+)?marker\s+plus\s+suffix\s+([A-Za-z0-9_.:-]+)\s+as\s+one\s+token\b/i.exec(o)?.[1]?.replace(/[.,;:]+$/u,"");if(a)return`${r}${a}`}return/\b(?:reply|respond)\s+exactly(?:\s+with)?\s*:?\s*([A-Za-z0-9_.:-]+)(?:\s*$|[.!?\u3002\uFF01\uFF1F])/i.exec(o)?.[1]?.replace(/[.,;:]+$/u,"")}function hs(e,t,n){let o=ue(e),r=[t.done,t.fail,n].filter(s=>typeof s=="string"&&s.length>0);return[...new Set(r)].filter(s=>new RegExp(`\\bstarts?\\s+with\\s+${Re(s)}\\b`,"i").test(o))}function se(e){let t=Lt(e.inputMessages,e.messages).filter(o=>!Pt(o));return t.length===0?void 0:`${wt(e.inputMessages)??"FAIL"} ${e.reason}. Missing required output file evidence: ${t.join(", ")}`}function qe(e){let t=be(e.inputMessages);if(!t.done){let o=Ot(e.inputMessages)??Ft(e.inputMessages,t);return o?`FAIL ${o} ${e.reason}. The model did not produce the requested final marker ${o}.`:void 0}return`${t.fail??"FAIL"} ${e.reason}. The model did not produce the requested final marker ${t.done}.`}function Nt(e){let t=be(e.inputMessages),n=Ft(e.inputMessages,t);if(!n)return;if(je(e.inputMessages).length===0){let i=ue(e.inputMessages);return!ln(i)||!cn(e.messages).some(p=>p.includes(n))?void 0:un({inputMessages:e.inputMessages,messages:e.messages,finalText:""}).length===0?n:void 0}if(!(Lt(e.inputMessages,e.messages).filter(i=>!Pt(i)).length>0||dn(e.inputMessages,e.messages).length>0))return n}function Bt(e){try{let t=JSON.parse(e);return t&&typeof t=="object"&&!Array.isArray(t)?t:null}catch{return null}}function Dt(e){for(let t of["path","filePath","file_path"]){let n=e[t];if(typeof n=="string"&&n.trim())return n}}function pn(e){for(let t of["content","newContent","replacement","text"]){let n=e[t];if(typeof n=="string")return n}return""}function mn(e){let t=e.toolCall.function.name;if(t!=="write"&&t!=="edit")return;let n=be(e.inputMessages);if(!n.done)return;let o=Bt(e.toolCall.function.arguments);if(!o)return;let r=Dt(o),s=pn(o);if(!r||!s.includes(n.done))return;let i=je(e.inputMessages);if(i.length<2)return;let a=U(r);if(!i.some(m=>U(m)===a))return;let p=an(e.messages),f=i.filter(m=>U(m)!==a).filter(m=>!p.includes(U(m)));if(f.length!==0)return`Premature completion artifact blocked: this write/edit attempted to store the requested DONE marker in ${r} before evidence existed for sibling required output files: ${f.join(", ")}. Create or verify the missing files first, or report the requested FAIL marker with the real reason.`}function Z(e,t){return{role:"assistant",content:e,...t.length>0&&{thinkingBlocks:[...t]}}}function Ts(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 Cs(e){let t=[...e].reverse().find(n=>n.role==="tool");t&&typeof t.content=="string"&&(t.content+=`
7
7
 
8
- \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 ee(e,t,o,n){return{reason:e,messages:[...t,o,n],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}}}function At(e){let t=e.inputMessages.find(T=>T.role==="user"),o=typeof t?.content=="string"?t.content:"",n=jr.test(o),r=e.distinctToolNames.has("write")||e.distinctToolNames.has("edit"),s=ge(e.inputMessages),i=Vo(e.inputMessages),a=ns(e.inputMessages,s,i),d=s.done!==void 0&&e.finalText.includes(s.done)||s.fail!==void 0&&e.finalText.includes(s.fail)||i!==void 0&&e.finalText.includes(i),p=a.length===0||a.some(T=>e.finalText.trimStart().startsWith(T)),f=Zo(e.inputMessages,s),m=_t(e.inputMessages,e.messages);if(m.length>0&&e.totalToolCallCount>0){if(s.fail!==void 0&&e.finalText.includes(s.fail))return null;e.log.info(`explicit required file verification: ${m.length} file(s) missing`);let T=bt(e.inputMessages),h={role:"user",content:`Before completing, verify that every explicitly requested output file exists and is non-empty. Missing required output file evidence: ${m.join(", ")}. Create the missing files now, or if you cannot complete them, respond with ${T??"FAIL"} and the real reason. Do not claim completion until the missing files are handled.`};return ee("explicit_required_file_verification",e.messages,Q(e.finalText,e.thinkingBlocks),h)}let b=Yo(e.inputMessages,e.messages);if(b.length>0&&e.totalToolCallCount>0){if(s.fail!==void 0&&e.finalText.includes(s.fail))return null;e.log.info(`explicit extra file verification: ${b.length} unexpected file(s)`);let T=bt(e.inputMessages),h={role:"user",content:`The latest request asked for exactly the listed output artifacts, but extra files were produced under the output root: ${b.join(", ")}. Remove the extra files now, move scratch work outside the deliverable directory, or if you cannot make the output exact, respond with ${T??"FAIL"} and the real reason. Do not claim completion while extra deliverables remain.`};return ee("explicit_extra_file_verification",e.messages,Q(e.finalText,e.thinkingBlocks),h)}if(a.length>0&&e.totalToolCallCount>0&&!p){e.log.info("final marker verification: explicit final marker was not at the start of the response");let T={role:"user",content:`The requested output file evidence is present, but your final response did not start with the explicit completion marker. Your final response must start with one of the requested final markers: ${a.join(" or ")}. No preface, heading, markdown emphasis, or summary may appear before the marker.`};return ee("final_marker_verification",e.messages,Q(e.finalText,e.thinkingBlocks),T)}if((s.done!==void 0||i!==void 0)&&e.totalToolCallCount>0&&!d){e.log.info("final marker verification: explicit final DONE/FAIL marker missing");let T=s.done??i,h={role:"user",content:"The requested output file evidence is present, but your final response omitted the explicit completion marker. "+(s.done?`If you have verified the artifacts, Reply exactly with ${s.done}. `:`Your final response must include marker ${T} and clearly say whether the run passed or failed. `)+(s.fail?`If verification failed, reply with ${s.fail} and the real reason. `:`If verification failed, reply with FAIL ${T??""} and the real reason. `)+"Do not end the turn without one of the requested final markers."};return ee("final_marker_verification",e.messages,Q(e.finalText,e.thinkingBlocks),h)}if(f!==void 0&&e.totalToolCallCount>0&&e.finalText.trim()!==f){e.log.info("final marker verification: exact-only final marker response had extra text");let T={role:"user",content:`Reply exactly with ${f} and no other text.`};return ee("final_marker_verification",e.messages,Q(e.finalText,e.thinkingBlocks),T)}if(d&&r||e.stopHookActive)return null;if(n&&!r){e.log.info("AP1 action-verification: user requested file action but no write/edit tool was called, injecting nudge"),e.totalToolCallCount>0&&is(e.messages);let T={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 ee("file_action_verification",e.messages,Q(e.finalText,e.thinkingBlocks),T)}if(e.totalToolCallCount>=3&&e.distinctToolNames.has("write")&&e.messages.filter(ss).length>=3){e.log.info("AP3 verification nudge: 3+ files created, injecting completeness check");let h={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 ee("multi_file_skeleton_verification",e.messages,Q(e.finalText,e.thinkingBlocks),h)}return null}function as(e,t){return{role:"assistant",content:e,...t.length>0&&{thinkingBlocks:[...t]}}}async function on(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 o=t.reason??"Stop hook requested continuation";e.log.info(`stop hook blocking: ${o}`);let n={role:"user",content:o};return{action:"continue",messages:[...e.messages,as(e.finalText,e.thinkingBlocks),n],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}}}return null}var ls=5;function cs(e){return e.inputTokens+e.outputTokens+(e.reasoningTokens??0)}function us(e,t){return{role:"assistant",content:e,...t.length>0&&{thinkingBlocks:[...t]}}}function nn(e){if(!e.tokenBudget||e.tokenBudget<=0||e.budgetContinuationCount>=ls)return null;let t=cs(e.totalUsage),o=t/e.tokenBudget*100,n=t-e.lastBudgetGlobalTokens;if(e.budgetContinuationCount>=uo&&n<Qe&&e.lastBudgetDeltaTokens<Qe)return e.log.info(`token budget early stop: diminishing returns at ${Math.round(o)}% (delta=${n})`),null;if(o>=90)return null;let s=e.budgetContinuationCount+1,i={role:"user",content:e.getBudgetContinuationMessage(o,t,e.tokenBudget)};return e.log.info(`token budget continuation #${s}: ${Math.round(o)}% used`),{messages:[...e.messages,us(e.finalText,e.thinkingBlocks),i],budgetContinuationCount:s,lastBudgetDeltaTokens:n,lastBudgetGlobalTokens:t,recoveryDetail:`${Math.round(o)}% used (#${s})`,transition:{reason:"token_budget_continuation"}}}function vt(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 ot(t,{tools:[...e.distinctToolNames],projectRoot:e.projectRoot})}function rn(e,t){let o=[],n=[];for(let r of e){let s=t.get(r.function.name)??0;s>=be?n.push({call:r,failCount:s,error:`Tool "${r.function.name}" has failed ${s} times this turn with different arguments. The target likely does not exist. Stop trying variations and report the issue to the user.`}):o.push(r)}return{allowed:o,blocked:n}}function sn(){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 an(e){if(e.ok&&!e.softEmpty)return;let t=e.toolFailureCounts.get(e.toolName)??0;e.toolFailureCounts.set(e.toolName,t+1)}function ln(e){let t=[];for(let[o,n]of e.toolFailureCounts)n>=be&&(e.snapshot.get(o)??0)<be&&t.push({role:"user",content:`Tool "${o}" has now failed/returned empty results ${n} times with different arguments. The target clearly does not exist. Do NOT call "${o}" again. Report the result to the user immediately.`});return t}function ps(e,t){if(e.length!==1||e[0]?.function.name!=="stt")return!1;let o=[...t].reverse().find(i=>i.role==="user");if(!o)return!1;let n=Array.isArray(o.audioUrls)&&o.audioUrls.some(i=>typeof i=="string"&&i.trim()),r=typeof o.content=="string"?o.content:"",s=/\b(?:stt|speech[-\s]?to[-\s]?text|transcribe|transcription|audio[-\s]?to[-\s]?text)\b|转写|转录|语音转文字|音频转文字|听写/i.test(r);return n&&s}function ms(e,t){let o=fs(t);if(!o)return null;let n=gs(o);if(!n)return null;let r=[...e].reverse().find(a=>a.role==="user"),s=typeof r?.content=="string"?r.content:"",i=/\bAUDIO_STT_RESULT\s+([^\s<]+)\s+<transcription\b/i.exec(s);return i?.[1]?`AUDIO_STT_RESULT ${i[1]} ${n}`:n}function fs(e){let t=[e.details?.transcription,e.details?.text,e.details?.preview];for(let n of t)if(typeof n=="string"&&n.trim())return n.trim();let o=e.message?.content;return typeof o=="string"?o.trim():""}function gs(e){return e.toLocaleLowerCase().replace(/[^\p{L}\p{N}\s]+/gu," ").replace(/\s+/g," ").trim()}var St=new Set(["read","search"]),ys=new Set(["write","edit","patch","image_generate"]);function hs(e){e.identicalSuccessfulToolResults.clear();for(let t of[...e.identicalCallCounts.keys()]){let o=t.slice(0,t.indexOf("::"));St.has(o)&&e.identicalCallCounts.delete(t)}}async function*cn(e,t,o,n){let{turnId:r,sessionId:s,messages:i,tools:a,model:d,apiKey:p,temperature:f=0,hooks:m,signal:b}=e,T={sessionId:s,turnId:r},h=e.maxTurns??0,k=e.querySource,_=e.runtimePorts.resolveToolEligibility(a,e.toolEligibilityContext),R=_.eligibleTools;for(let g of _.blockedTools)yield{type:"tool_blocked",turnId:r,callId:"",name:g.toolName,reason:"blocked-by-policy"};let P=Lo(e.maxRounds,i),oe=Oo(e.maxToolCalls,i),Fe=Ee(i),q={contextWindowTokens:e.contextWindowTokens??ro,responseBufferTokens:so,maxOutputTokens:e.maxOutputTokens??io,abortSignal:b,reactiveCompactEnabled:!0,outputEscalationEnabled:!0},L=new Set,E=0,X=R,gn=ps(R,i),ye,Ne=!1,Et=0,c={messages:[...i],maxOutputTokensRecoveryCount:0,hasAttemptedReactiveCompact:!1,maxOutputTokensOverride:void 0,turnCount:1,transition:void 0,guardState:dt(q),reactiveCompactState:yt(),toolLoopState:Me({maxRounds:P,replayMessages:[...i]}).state,consecutiveFailedRounds:0,finalText:"",totalUsage:{inputTokens:0,outputTokens:0},collapseStore:Ye(),currentModel:d,consecutive529Errors:0,consecutiveApiRetries:0,stopHookActive:void 0,lastResponseId:void 0,snipRemovedIds:new Set,contentReplacementState:e.runtimePorts.createContentReplacementState(),budgetContinuationCount:0,finalMarkerEmptyRecoveryCount:0,repeatedToolFailureRecoveryCount:0,lastBudgetDeltaTokens:0,lastBudgetGlobalTokens:0,identicalCallCounts:new Map,identicalSuccessfulToolResults:new Map,toolFailureCounts:new Map,fileReadCounts:new Map,recoveryTrace:new Map},De=Math.max(h*5,200),wt=0,O=(g,F)=>(c.recoveryTrace.set(g,(c.recoveryTrace.get(g)??0)+1),{type:"recovery",turnId:r,action:g,detail:F}),I=g=>({type:"end",turnId:r,content:g,usage:c.totalUsage,model:c.currentModel,...c.recoveryTrace.size>0?{recoveryTrace:Object.fromEntries(c.recoveryTrace)}:{}}),ae=(g,F)=>{if(c.finalText.trim()===""){let z=Oe({inputMessages:i,reason:F});if(z)return z}return c.finalText||Ct(g,n)},yn=(g,F,z)=>{let H=te({inputMessages:i,messages:F,reason:z});if(H)return H;if(g.trim()===""){let A=Oe({inputMessages:i,reason:z});if(A)return A}return g||Ct(F,n)};for(;;){if(wt++,wt>De){n.info(`hard iteration cap reached (${De}), forcing completion`);let l=ae(c.messages,`hard iteration cap reached (${De}) before producing the requested final marker`);yield I(l);return}let{messages:g,maxOutputTokensRecoveryCount:F,maxOutputTokensOverride:z,turnCount:H,guardState:A,reactiveCompactState:U,collapseStore:Be}=c,{toolLoopState:N}=c;if(ye){try{let l=await ye;l&&(yield{type:"tool_use_summary",turnId:r,summary:l})}catch{}ye=void 0}if(e.refreshTools&&H>1){let l=e.refreshTools();l!==X&&(X=l,n.debug(`tools refreshed: ${l.length} tools`))}if(gt(A,q)){n.info(`turn aborted by guard at turn ${H}`),yield{type:"error",turnId:r,error:"Turn aborted",code:"ABORTED",usage:c.totalUsage};return}let Y=pt(A,q);if(Y.level==="blocking"){Y.reason==="prompt_too_long"&&se(U)&&(U.attemptedThisTurn=!0,A.hasAttemptedReactiveCompact=!0,n.info(`token budget blocking (${Y.reason}), reactive compact needed`),yield O("reactive_compact","token budget pre-check")),n.info(`token budget blocking (${Y.reason}), ending tool loop`);break}Y.level==="warning"&&n.info(`token budget warning: ${Y.usagePercent}% used, ${Y.remainingTokens} remaining`);let he=yield*Uo({messages:g,contentReplacementState:c.contentReplacementState,snipRemovedIds:c.snipRemovedIds,collapseStore:Be,guardState:A,guardConfig:q,runtimePorts:e.runtimePorts,hooks:m,hookCtx:T,sessionId:s,currentModel:c.currentModel,log:n,recovery:O,onAutocompact:()=>{c.hasAttemptedReactiveCompact=!1}}),hn=e.toolChoice==="required"&&Ne?"auto":e.toolChoice??"auto",le=nt({tools:X,toolChoice:hn}),ce=Me({maxRounds:P,replayMessages:he,lastStopReason:N.lastStopReason,options:{stopReason:N.lastStopReason}}),It=le.extraSystemPrompt?[{role:"system",content:le.extraSystemPrompt},...ce.state.replayMessages]:ce.state.replayMessages;N=ce.state,ce.recoveryActions.length>0&&n.debug(`tool loop recovery: ${ce.recoveryActions.map(l=>l.detail??l.kind).join("; ")}`),n.debug(`turn ${H}, messages: ${It.length}`),S(m,"turn.before_inference",{...T,model:c.currentModel},n);let $e=!1,Ue=[],Pt=new Map,Lt="stop",D,x=null,Te=!1,Ot=!1,ue=[],j=[];try{for await(let l of t.stream({model:c.currentModel,messages:It,...le.tools.length>0?{tools:le.tools,toolChoice:le.normalizedToolChoice??"auto"}:{},temperature:f,maxTokens:(z??A.currentMaxOutputTokens)||void 0,streamRequired:e.streamRequired,previousResponseId:c.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},p,b))switch(l.type){case"delta":Ue.push(l.text);break;case"tool_call_delta":$e=!0,ht(Pt,l);break;case"reasoning_delta":ue.push(l.text);break;case"reasoning_block_complete":l.signature&&j.push({thinking:ue.join(""),signature:l.signature}),ue.length=0;break;case"usage":D={inputTokens:l.promptTokens,outputTokens:l.completionTokens,reasoningTokens:l.reasoningTokens,cacheRead:l.cacheReadTokens,cacheWrite:l.cacheCreationTokens};break;case"response_id":c.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":Ot=!0,Lt=l.finishReason;break}if($e||S(m,"turn.after_inference",{...T,model:c.currentModel},n),e.postSamplingHooks&&e.postSamplingHooks.length>0){let l=c.currentModel;for(let u of e.postSamplingHooks)try{u({messages:[...he],model:l,sessionId:s})}catch{}}}catch(l){let u=yield*jo(l,{state:c,guardState:A,fallbackModel:e.fallbackModel,signal:b,querySource:k,turnId:r,log:n,emitRecovery:O});if(u.kind==="return")return;if(u.kind==="continue"){c={...c,...u.patch};continue}x=u.streamError}if(!x&&!Ot){let l="LLM stream closed before a terminal event; the response was likely truncated upstream.";S(m,"stop.failure",{sessionId:s,reason:"RETRYABLE_TRANSIENT",error:l},n),yield{type:"error",turnId:r,error:l,code:"RETRYABLE_TRANSIENT",usage:c.totalUsage};return}if(x&&S(m,"turn.after_inference",{...T,model:c.currentModel,response:{error:x.message}},n),x)if(kt(x))Te=!0,n.info(`withheld prompt_too_long error (status=${x.status})`);else if(Rt(x))Te=!0,n.info(`withheld media_size error (status=${x.status})`);else{let l=mt({status:x.status??500,message:x.message},A,q);if(l.action==="reactive_compact"&&se(U)&&(U.attemptedThisTurn=!0,A.hasAttemptedReactiveCompact=!0,yield O("reactive_compact",`API ${x.status??500}: ${x.message}`)),l.action==="retry"){let y=(c.consecutiveApiRetries??0)+1;if(y>re){n.info(`API retry limit reached (${re}), aborting`);let C=ne(x.status,x.message);yield{type:"error",turnId:r,error:x.message,code:C,usage:c.totalUsage};return}yield O("retry",l.reason),c={...c,consecutiveApiRetries:y,transition:void 0};continue}let u=ne(x.status,x.message);S(m,"stop.failure",{sessionId:s,reason:u,error:x.message},n),yield{type:"error",turnId:r,error:x.message,code:u,usage:c.totalUsage};return}D&&(c.totalUsage.inputTokens+=D.inputTokens,c.totalUsage.outputTokens+=D.outputTokens,D.reasoningTokens&&(c.totalUsage.reasoningTokens=(c.totalUsage.reasoningTokens??0)+D.reasoningTokens),D.cacheRead&&(c.totalUsage.cacheRead=(c.totalUsage.cacheRead??0)+D.cacheRead),D.cacheWrite&&(c.totalUsage.cacheWrite=(c.totalUsage.cacheWrite??0)+D.cacheWrite)),D?.inputTokens&&(A.promptTokens=D.inputTokens);let Ft=Ue.join(""),$=[...Pt.values()].map(l=>({id:l.id||`tc_${r}_${H}_${Math.random().toString(36).slice(2,8)}`,type:"function",function:{name:l.name,arguments:l.arguments}}));if($.length===0&&!$e){if(Ft&&(c.finalText=Ft),e.toolChoice==="required"&&!Ne&&X.length>0&&Et<2){Et++;let M=X.map(w=>w.function.name).filter(Boolean).slice(0,8).join(", ");c={...c,messages:[...g,{role:"user",content:`You must call one available tool before answering. Available tools for this request: ${M}. Do not answer from memory, prior context, or guesses.`}],finalText:"",transition:{reason:"next_turn"}};continue}if(Te&&x&&kt(x)){if(c.transition?.reason!=="collapse_drain_retry"){let M=Ze(he,Be);if(M.committed>0){n.info(`collapse drain: committed ${M.committed} stages`),yield O("collapse_drain",`${M.committed} stages committed`),c={...c,messages:M.messages,transition:{reason:"collapse_drain_retry",committed:M.committed}};continue}}if(se(U)){U.attemptedThisTurn=!0,A.hasAttemptedReactiveCompact=!0,n.info("withheld 413: reactive compact attempt"),yield O("reactive_compact","withheld prompt_too_long"),c={...c,hasAttemptedReactiveCompact:!0,transition:{reason:"reactive_compact_retry"}};continue}n.info("withheld 413: recovery exhausted, surfacing error"),S(m,"stop.failure",{sessionId:s,reason:"prompt_too_long",error:x.message},n),yield{type:"error",turnId:r,error:x.message,code:"PROMPT_TOO_LONG",usage:c.totalUsage};return}if(Te&&x&&Rt(x)){if(se(U)){U.attemptedThisTurn=!0,A.hasAttemptedReactiveCompact=!0,n.info("withheld media error: reactive compact strip-retry"),yield O("reactive_compact","media error strip-retry"),c={...c,hasAttemptedReactiveCompact:!0,transition:{reason:"reactive_compact_retry"}};continue}n.info("withheld media error: recovery exhausted"),S(m,"stop.failure",{sessionId:s,reason:"media_error",error:x.message},n),yield{type:"error",turnId:r,error:x.message,code:"IMAGE_ERROR",usage:c.totalUsage};return}if(Do(Lt)){A.consecutiveTruncations+=1;let M=e.modelMaxOutputTokens??ao,w=ft(A,q,M);if(w.shouldEscalate&&z===void 0){A.currentMaxOutputTokens=w.newMax,n.info(`max_output_tokens escalate: ${w.newMax} tokens`),yield O("output_escalation",`${w.newMax} tokens`),c={...c,maxOutputTokensOverride:co,transition:{reason:"max_output_tokens_escalate"}};continue}if(F<lo){let K={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."};n.info(`max_output_tokens recovery #${F+1}`),yield O("max_output_tokens_recovery",`attempt ${F+1}`),c={...c,messages:[...he,K],maxOutputTokensRecoveryCount:F+1,maxOutputTokensOverride:void 0,transition:{reason:"max_output_tokens_recovery",attempt:F+1}};continue}n.info("max_output_tokens recovery exhausted, completing with partial content")}else A.consecutiveTruncations=0;N=_e(N,{replayMessages:g,lastStopReason:"completed"});let l=await on({hooks:m,sessionId:s,messages:g,finalText:c.finalText,thinkingBlocks:j,log:n});if(l?.action==="end"){let M=yn(l.content,g,"stop hook prevented continuation before producing the requested final marker");yield I(M);return}if(l?.action==="continue"){c={...c,messages:l.messages,stopHookActive:l.stopHookActive,transition:l.transition};continue}let u=nn({tokenBudget:e.tokenBudget,totalUsage:c.totalUsage,budgetContinuationCount:c.budgetContinuationCount,lastBudgetDeltaTokens:c.lastBudgetDeltaTokens,lastBudgetGlobalTokens:c.lastBudgetGlobalTokens,messages:g,finalText:c.finalText,thinkingBlocks:j,getBudgetContinuationMessage:e.runtimePorts.getBudgetContinuationMessage,log:n});if(u){yield O("budget_continuation",u.recoveryDetail),c={...c,messages:u.messages,budgetContinuationCount:u.budgetContinuationCount,lastBudgetDeltaTokens:u.lastBudgetDeltaTokens,lastBudgetGlobalTokens:u.lastBudgetGlobalTokens,transition:u.transition};continue}let y=At({inputMessages:i,messages:g,finalText:c.finalText,thinkingBlocks:j,stopHookActive:c.stopHookActive,totalToolCallCount:E,distinctToolNames:L,log:n});if(y){if(c.stopHookActive&&(y.reason==="final_marker_verification"||c.finalText.trim()==="")){let M=te({inputMessages:i,messages:y.messages,reason:"final marker verification produced an empty response after tool use"});if(M){yield I(M);return}if(y.reason==="final_marker_verification"&&c.finalText.trim()===""&&c.finalMarkerEmptyRecoveryCount<1){yield O("final_marker_empty_retry","one extra retry after empty marker nudge"),c={...c,messages:y.messages,stopHookActive:y.stopHookActive,transition:y.transition,finalMarkerEmptyRecoveryCount:c.finalMarkerEmptyRecoveryCount+1};continue}let w=Jo({inputMessages:i,messages:y.messages});if(w){yield I(w);return}let K=Oe({inputMessages:i,reason:"final marker verification produced an empty response after tool use"});if(K){yield I(K);return}}c={...c,messages:y.messages,stopHookActive:y.stopHookActive,transition:y.transition};continue}let C=vt({totalToolCallCount:E,distinctToolNames:L,projectRoot:e.projectRoot});C&&(yield{type:"skill_instruction",turnId:r,instruction:C});let v=ae(g,"the model ended with an empty response after tool use before producing the requested final marker");for(let M of Ue)yield{type:"delta",turnId:r,text:M};yield I(v);return}let Tn=j.length===0&&ue.length>0?ue.join(""):void 0;g.push(Ge($,void 0,j.length>0?j:void 0,Tn)),N=lt(N,{replayMessages:g,pendingToolCallIds:$.map(l=>l.id),completedToolCallIds:N.completedToolCallIds,lastStopReason:"tool_calls"});let Ce=c.identicalCallCounts,Nt=[],ke=[],Dt=[],Bt=!1;for(let l of $){let u=`${l.function.name}::${l.function.arguments}`,y=Ce.get(u)??0;if(Ce.set(u,y+1),y+1>no){let C=St.has(l.function.name)?c.identicalSuccessfulToolResults.get(u):void 0;if(C){Dt.push({call:l,result:C,repeatCount:y+1});continue}ke.push(l),Bt||(Bt=!0,n.info(`AP4 blocked: ${l.function.name} repeated ${y+1}x`))}else Nt.push(l)}let G=[];for(let l of Dt){let u=l.call,y=`Reused previous successful ${u.function.name} result for identical arguments (attempt ${l.repeatCount}); no additional tool execution was performed.
8
+ \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 J(e,t,n,o){return{reason:e,messages:[...t,n,o],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}}}function $t(e){let t=e.inputMessages.find(g=>g.role==="user"),n=typeof t?.content=="string"?t.content:"",o=Qr.test(n),r=e.distinctToolNames.has("write")||e.distinctToolNames.has("edit"),s=be(e.inputMessages),i=Ot(e.inputMessages),a=hs(e.inputMessages,s,i),u=s.done!==void 0&&e.finalText.includes(s.done)||s.fail!==void 0&&e.finalText.includes(s.fail)||i!==void 0&&e.finalText.includes(i),p=a.length===0||a.some(g=>e.finalText.trimStart().startsWith(g)),f=Ft(e.inputMessages,s),m=Lt(e.inputMessages,e.messages);if(m.length>0&&e.totalToolCallCount>0){if(s.fail!==void 0&&e.finalText.includes(s.fail))return null;e.log.info(`explicit required file verification: ${m.length} file(s) missing`);let g=wt(e.inputMessages),T={role:"user",content:`Before completing, verify that every explicitly requested output file exists and is non-empty. Missing required output file evidence: ${m.join(", ")}. Create the missing files now, or if you cannot complete them, respond with ${g??"FAIL"} and the real reason. Do not claim completion until the missing files are handled.`};return J("explicit_required_file_verification",e.messages,Z(e.finalText,e.thinkingBlocks),T)}let k=dn(e.inputMessages,e.messages);if(k.length>0&&e.totalToolCallCount>0){if(s.fail!==void 0&&e.finalText.includes(s.fail))return null;e.log.info(`explicit extra file verification: ${k.length} unexpected file(s)`);let g=wt(e.inputMessages),T={role:"user",content:`The latest request asked for exactly the listed output artifacts, but extra files were produced under the output root: ${k.join(", ")}. Remove the extra files now, move scratch work outside the deliverable directory, or if you cannot make the output exact, respond with ${g??"FAIL"} and the real reason. Do not claim completion while extra deliverables remain.`};return J("explicit_extra_file_verification",e.messages,Z(e.finalText,e.thinkingBlocks),T)}let M=un({inputMessages:e.inputMessages,messages:e.messages,finalText:e.finalText});if(M.length>0&&e.totalToolCallCount>0){if(s.fail!==void 0&&e.finalText.includes(s.fail))return null;e.log.info(`artifact index evidence verification: ${M.length} issue(s)`);let g=f??s.done??i??"the requested marker",T={role:"user",content:"Before completing, correct the artifact index against the actual evidence scope. "+M.map(b=>b.detail).join(" ")+` Use the exact requested Goal row labels, cite concrete evidence names/paths for status claims, and mark a row as not verified/unknown instead of claiming exhaustive absence without scoped evidence. Do not claim all checks pass while any row is failed, partial, missing, or unverified. After correcting and verifying the file, reply exactly with ${g}.`};return J("artifact_index_evidence_verification",e.messages,Z(e.finalText,e.thinkingBlocks),T)}if(a.length>0&&e.totalToolCallCount>0&&!p){e.log.info("final marker verification: explicit final marker was not at the start of the response");let g={role:"user",content:`The requested output file evidence is present, but your final response did not start with the explicit completion marker. Your final response must start with one of the requested final markers: ${a.join(" or ")}. No preface, heading, markdown emphasis, or summary may appear before the marker.`};return J("final_marker_verification",e.messages,Z(e.finalText,e.thinkingBlocks),g)}if((s.done!==void 0||i!==void 0)&&e.totalToolCallCount>0&&!u){e.log.info("final marker verification: explicit final DONE/FAIL marker missing");let g=s.done??i,T={role:"user",content:"The requested output file evidence is present, but your final response omitted the explicit completion marker. "+(s.done?`If you have verified the artifacts, Reply exactly with ${s.done}. `:`Your final response must include marker ${g} and clearly say whether the run passed or failed. `)+(s.fail?`If verification failed, reply with ${s.fail} and the real reason. `:`If verification failed, reply with FAIL ${g??""} and the real reason. `)+"Do not end the turn without one of the requested final markers."};return J("final_marker_verification",e.messages,Z(e.finalText,e.thinkingBlocks),T)}if(f!==void 0&&e.finalText.trim()!==f){e.log.info("final marker verification: exact-only final marker response had extra text");let g={role:"user",content:`Reply exactly with ${f} and no other text.`};return J("final_marker_verification",e.messages,Z(e.finalText,e.thinkingBlocks),g)}if(u&&r||e.stopHookActive)return null;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&&Cs(e.messages);let g={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 J("file_action_verification",e.messages,Z(e.finalText,e.thinkingBlocks),g)}if(e.totalToolCallCount>=3&&e.distinctToolNames.has("write")&&e.messages.filter(Ts).length>=3){e.log.info("AP3 verification nudge: 3+ files created, injecting completeness check");let T={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 J("multi_file_skeleton_verification",e.messages,Z(e.finalText,e.thinkingBlocks),T)}return null}function ks(e,t){return{role:"assistant",content:e,...t.length>0&&{thinkingBlocks:[...t]}}}async function fn(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,ks(e.finalText,e.thinkingBlocks),o],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}}}return null}var Rs=5;function bs(e){return e.inputTokens+e.outputTokens+(e.reasoningTokens??0)}function xs(e,t){return{role:"assistant",content:e,...t.length>0&&{thinkingBlocks:[...t]}}}function gn(e){if(!e.tokenBudget||e.tokenBudget<=0||e.budgetContinuationCount>=Rs)return null;let t=bs(e.totalUsage),n=t/e.tokenBudget*100,o=t-e.lastBudgetGlobalTokens;if(e.budgetContinuationCount>=xo&&o<it&&e.lastBudgetDeltaTokens<it)return e.log.info(`token budget early stop: diminishing returns at ${Math.round(n)}% (delta=${o})`),null;if(n>=90)return null;let s=e.budgetContinuationCount+1,i={role:"user",content:e.getBudgetContinuationMessage(n,t,e.tokenBudget)};return e.log.info(`token budget continuation #${s}: ${Math.round(n)}% used`),{messages:[...e.messages,xs(e.finalText,e.thinkingBlocks),i],budgetContinuationCount:s,lastBudgetDeltaTokens:o,lastBudgetGlobalTokens:t,recoveryDetail:`${Math.round(n)}% used (#${s})`,transition:{reason:"token_budget_continuation"}}}function Ut(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 ct(t,{tools:[...e.distinctToolNames],projectRoot:e.projectRoot})}function yn(e,t){let n=[],o=[];for(let r of e){let s=t.get(r.function.name)??0;s>=Pe?o.push({call:r,failCount:s,error:`Tool "${r.function.name}" has failed ${s} 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 hn(){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 Tn(e){if(e.ok&&!e.softEmpty)return;let t=e.toolFailureCounts.get(e.toolName)??0;e.toolFailureCounts.set(e.toolName,t+1)}function Cn(e){let t=[];for(let[n,o]of e.toolFailureCounts)o>=Pe&&(e.snapshot.get(n)??0)<Pe&&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}function Ms(e,t){if(e.length!==1||e[0]?.function.name!=="stt")return!1;let n=[...t].reverse().find(i=>i.role==="user");if(!n)return!1;let o=Array.isArray(n.audioUrls)&&n.audioUrls.some(i=>typeof i=="string"&&i.trim()),r=typeof n.content=="string"?n.content:"",s=/\b(?:stt|speech[-\s]?to[-\s]?text|transcribe|transcription|audio[-\s]?to[-\s]?text)\b|转写|转录|语音转文字|音频转文字|听写/i.test(r);return o&&s}function As(e,t){let n=vs(t);if(!n)return null;let o=Ss(n);if(!o)return null;let r=[...e].reverse().find(a=>a.role==="user"),s=typeof r?.content=="string"?r.content:"",i=/\bAUDIO_STT_RESULT\s+([^\s<]+)\s+<transcription\b/i.exec(s);return i?.[1]?`AUDIO_STT_RESULT ${i[1]} ${o}`:o}function vs(e){let t=[e.details?.transcription,e.details?.text,e.details?.preview];for(let o of t)if(typeof o=="string"&&o.trim())return o.trim();let n=e.message?.content;return typeof n=="string"?n.trim():""}function Ss(e){return e.toLocaleLowerCase().replace(/[^\p{L}\p{N}\s]+/gu," ").replace(/\s+/g," ").trim()}var jt=new Set(["read","search"]),Es=new Set(["write","edit","patch","image_generate"]);function ws(e){e.identicalSuccessfulToolResults.clear();for(let t of[...e.identicalCallCounts.keys()]){let n=t.slice(0,t.indexOf("::"));jt.has(n)&&e.identicalCallCounts.delete(t)}}async function*kn(e,t,n,o){let{turnId:r,sessionId:s,messages:i,tools:a,model:u,apiKey:p,temperature:f=0,hooks:m,signal:k}=e,M={sessionId:s,turnId:r},g=e.maxTurns??0,T=e.querySource,b=e.runtimePorts.resolveToolEligibility(a,e.toolEligibilityContext),R=b.eligibleTools;for(let y of b.blockedTools)yield{type:"tool_blocked",turnId:r,callId:"",name:y.toolName,reason:"blocked-by-policy"};let A=Ko(e.maxRounds,i),L=Wo(e.maxToolCalls,i),xe=!(typeof e.maxRounds=="number"&&e.maxRounds>=1)&&!(typeof e.maxToolCalls=="number"&&e.maxToolCalls>=1),He=De(i),H={contextWindowTokens:e.contextWindowTokens??ho,responseBufferTokens:To,maxOutputTokens:e.maxOutputTokens??Co,abortSignal:k,reactiveCompactEnabled:!0,outputEscalationEnabled:!0},w=new Set,F=0,de=0,pe=0,_e=0,Q=R,An=Ms(R,i),Me,ze=!1,qt=0,c={messages:[...i],maxOutputTokensRecoveryCount:0,hasAttemptedReactiveCompact:!1,maxOutputTokensOverride:void 0,turnCount:1,transition:void 0,guardState:Tt(H),reactiveCompactState:xt(),toolLoopState:Fe({maxRounds:A,replayMessages:[...i]}).state,consecutiveFailedRounds:0,finalText:"",totalUsage:{inputTokens:0,outputTokens:0},collapseStore:nt(),currentModel:u,consecutive529Errors:0,consecutiveApiRetries:0,stopHookActive:void 0,lastResponseId:void 0,snipRemovedIds:new Set,contentReplacementState:e.runtimePorts.createContentReplacementState(),budgetContinuationCount:0,finalMarkerEmptyRecoveryCount:0,repeatedToolFailureRecoveryCount:0,lastBudgetDeltaTokens:0,lastBudgetGlobalTokens:0,identicalCallCounts:new Map,identicalSuccessfulToolResults:new Map,toolFailureCounts:new Map,fileReadCounts:new Map,recoveryTrace:new Map},Ge=Math.max(g*5,200),Ht=0,O=(y,N)=>(c.recoveryTrace.set(y,(c.recoveryTrace.get(y)??0)+1),{type:"recovery",turnId:r,action:y,detail:N}),P=y=>({type:"end",turnId:r,content:y,usage:c.totalUsage,model:c.currentModel,...c.recoveryTrace.size>0?{recoveryTrace:Object.fromEntries(c.recoveryTrace)}:{}}),me=(y,N)=>{let K=Nt({inputMessages:i,messages:y});if(K)return K;if(c.finalText.trim()===""){let $=qe({inputMessages:i,reason:N});if($)return $}return c.finalText||At(y,o)},vn=(y,N,K)=>{let $=se({inputMessages:i,messages:N,reason:K});if($)return $;if(y.trim()===""){let v=qe({inputMessages:i,reason:K});if(v)return v}return y||At(N,o)};for(;;){if(Ht++,Ht>Ge){o.info(`hard iteration cap reached (${Ge}), forcing completion`);let l=me(c.messages,`hard iteration cap reached (${Ge}) before producing the requested final marker`);yield P(l);return}let{messages:y,maxOutputTokensRecoveryCount:N,maxOutputTokensOverride:K,turnCount:$,guardState:v,reactiveCompactState:z,collapseStore:Ke}=c,{toolLoopState:B}=c;if(Me){try{let l=await Me;l&&(yield{type:"tool_use_summary",turnId:r,summary:l})}catch{}Me=void 0}if(e.refreshTools&&$>1){let l=e.refreshTools();l!==Q&&(Q=l,o.debug(`tools refreshed: ${l.length} tools`))}if(bt(v,H)){o.info(`turn aborted by guard at turn ${$}`),yield{type:"error",turnId:r,error:"Turn aborted",code:"ABORTED",usage:c.totalUsage};return}let ee=Ct(v,H);if(ee.level==="blocking"){ee.reason==="prompt_too_long"&&le(z)&&(z.attemptedThisTurn=!0,v.hasAttemptedReactiveCompact=!0,o.info(`token budget blocking (${ee.reason}), reactive compact needed`),yield O("reactive_compact","token budget pre-check")),o.info(`token budget blocking (${ee.reason}), ending tool loop`);break}ee.level==="warning"&&o.info(`token budget warning: ${ee.usagePercent}% used, ${ee.remainingTokens} remaining`);let Ae=yield*Qo({messages:y,contentReplacementState:c.contentReplacementState,snipRemovedIds:c.snipRemovedIds,collapseStore:Ke,guardState:v,guardConfig:H,runtimePorts:e.runtimePorts,hooks:m,hookCtx:M,sessionId:s,currentModel:c.currentModel,log:o,recovery:O,onAutocompact:()=>{c.hasAttemptedReactiveCompact=!1}}),Sn=e.toolChoice==="required"&&ze?"auto":e.toolChoice??"auto",fe=ut({tools:Q,toolChoice:Sn}),ge=Fe({maxRounds:A,replayMessages:Ae,lastStopReason:B.lastStopReason,options:{stopReason:B.lastStopReason}}),zt=fe.extraSystemPrompt?[{role:"system",content:fe.extraSystemPrompt},...ge.state.replayMessages]:ge.state.replayMessages;B=ge.state,ge.recoveryActions.length>0&&o.debug(`tool loop recovery: ${ge.recoveryActions.map(l=>l.detail??l.kind).join("; ")}`),o.debug(`turn ${$}, messages: ${zt.length}`),E(m,"turn.before_inference",{...M,model:c.currentModel},o);let We=!1,Xe=[],Gt=new Map,Kt="stop",D,x=null,ve=!1,Wt=!1,ye=[],G=[];try{for await(let l of t.stream({model:c.currentModel,messages:zt,...fe.tools.length>0?{tools:fe.tools,toolChoice:fe.normalizedToolChoice??"auto"}:{},temperature:f,maxTokens:(K??v.currentMaxOutputTokens)||void 0,streamRequired:e.streamRequired,previousResponseId:c.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},p,k))switch(l.type){case"delta":Xe.push(l.text);break;case"tool_call_delta":We=!0,_t(Gt,l);break;case"reasoning_delta":ye.push(l.text);break;case"reasoning_block_complete":l.signature&&G.push({thinking:ye.join(""),signature:l.signature}),ye.length=0;break;case"usage":D={inputTokens:l.promptTokens,outputTokens:l.completionTokens,reasoningTokens:l.reasoningTokens,cacheRead:l.cacheReadTokens,cacheWrite:l.cacheCreationTokens};break;case"response_id":c.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":Wt=!0,Kt=l.finishReason;break}if(We||E(m,"turn.after_inference",{...M,model:c.currentModel},o),e.postSamplingHooks&&e.postSamplingHooks.length>0){let l=c.currentModel;for(let d of e.postSamplingHooks)try{d({messages:[...Ae],model:l,sessionId:s})}catch{}}}catch(l){let d=yield*en(l,{state:c,guardState:v,fallbackModel:e.fallbackModel,signal:k,querySource:T,turnId:r,log:o,emitRecovery:O});if(d.kind==="return")return;if(d.kind==="continue"){c={...c,...d.patch};continue}x=d.streamError}if(!x&&!Wt){let l="LLM stream closed before a terminal event; the response was likely truncated upstream.";E(m,"stop.failure",{sessionId:s,reason:"RETRYABLE_TRANSIENT",error:l},o),yield{type:"error",turnId:r,error:l,code:"RETRYABLE_TRANSIENT",usage:c.totalUsage};return}if(x&&E(m,"turn.after_inference",{...M,model:c.currentModel,response:{error:x.message}},o),x)if(St(x))ve=!0,o.info(`withheld prompt_too_long error (status=${x.status})`);else if(Et(x))ve=!0,o.info(`withheld media_size error (status=${x.status})`);else{let l=kt({status:x.status??500,message:x.message},v,H);if(l.action==="reactive_compact"&&le(z)&&(z.attemptedThisTurn=!0,v.hasAttemptedReactiveCompact=!0,yield O("reactive_compact",`API ${x.status??500}: ${x.message}`)),l.action==="retry"){let h=(c.consecutiveApiRetries??0)+1;if(h>ae){o.info(`API retry limit reached (${ae}), aborting`);let C=ie(x.status,x.message);yield{type:"error",turnId:r,error:x.message,code:C,usage:c.totalUsage};return}yield O("retry",l.reason),c={...c,consecutiveApiRetries:h,transition:void 0};continue}let d=ie(x.status,x.message);E(m,"stop.failure",{sessionId:s,reason:d,error:x.message},o),yield{type:"error",turnId:r,error:x.message,code:d,usage:c.totalUsage};return}D&&(c.totalUsage.inputTokens+=D.inputTokens,c.totalUsage.outputTokens+=D.outputTokens,D.reasoningTokens&&(c.totalUsage.reasoningTokens=(c.totalUsage.reasoningTokens??0)+D.reasoningTokens),D.cacheRead&&(c.totalUsage.cacheRead=(c.totalUsage.cacheRead??0)+D.cacheRead),D.cacheWrite&&(c.totalUsage.cacheWrite=(c.totalUsage.cacheWrite??0)+D.cacheWrite)),D?.inputTokens&&(v.promptTokens=D.inputTokens);let Xt=Xe.join(""),j=[...Gt.values()].map(l=>({id:l.id||`tc_${r}_${$}_${Math.random().toString(36).slice(2,8)}`,type:"function",function:{name:l.name,arguments:l.arguments}}));if(j.length===0&&!We){if(Xt&&(c.finalText=Xt),e.toolChoice==="required"&&!ze&&Q.length>0&&qt<2){qt++;let _=Q.map(I=>I.function.name).filter(Boolean).slice(0,8).join(", ");c={...c,messages:[...y,{role:"user",content:`You must call one available tool before answering. Available tools for this request: ${_}. Do not answer from memory, prior context, or guesses.`}],finalText:"",transition:{reason:"next_turn"}};continue}if(ve&&x&&St(x)){if(c.transition?.reason!=="collapse_drain_retry"){let _=st(Ae,Ke);if(_.committed>0){o.info(`collapse drain: committed ${_.committed} stages`),yield O("collapse_drain",`${_.committed} stages committed`),c={...c,messages:_.messages,transition:{reason:"collapse_drain_retry",committed:_.committed}};continue}}if(le(z)){z.attemptedThisTurn=!0,v.hasAttemptedReactiveCompact=!0,o.info("withheld 413: reactive compact attempt"),yield O("reactive_compact","withheld prompt_too_long"),c={...c,hasAttemptedReactiveCompact:!0,transition:{reason:"reactive_compact_retry"}};continue}o.info("withheld 413: recovery exhausted, surfacing error"),E(m,"stop.failure",{sessionId:s,reason:"prompt_too_long",error:x.message},o),yield{type:"error",turnId:r,error:x.message,code:"PROMPT_TOO_LONG",usage:c.totalUsage};return}if(ve&&x&&Et(x)){if(le(z)){z.attemptedThisTurn=!0,v.hasAttemptedReactiveCompact=!0,o.info("withheld media error: reactive compact strip-retry"),yield O("reactive_compact","media error strip-retry"),c={...c,hasAttemptedReactiveCompact:!0,transition:{reason:"reactive_compact_retry"}};continue}o.info("withheld media error: recovery exhausted"),E(m,"stop.failure",{sessionId:s,reason:"media_error",error:x.message},o),yield{type:"error",turnId:r,error:x.message,code:"IMAGE_ERROR",usage:c.totalUsage};return}if(Vo(Kt)){v.consecutiveTruncations+=1;let _=e.modelMaxOutputTokens??ko,I=Rt(v,H,_);if(I.shouldEscalate&&K===void 0){v.currentMaxOutputTokens=I.newMax,o.info(`max_output_tokens escalate: ${I.newMax} tokens`),yield O("output_escalation",`${I.newMax} tokens`),c={...c,maxOutputTokensOverride:bo,transition:{reason:"max_output_tokens_escalate"}};continue}if(N<Ro){let X={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 #${N+1}`),yield O("max_output_tokens_recovery",`attempt ${N+1}`),c={...c,messages:[...Ae,X],maxOutputTokensRecoveryCount:N+1,maxOutputTokensOverride:void 0,transition:{reason:"max_output_tokens_recovery",attempt:N+1}};continue}o.info("max_output_tokens recovery exhausted, completing with partial content")}else v.consecutiveTruncations=0;B=Oe(B,{replayMessages:y,lastStopReason:"completed"});let l=await fn({hooks:m,sessionId:s,messages:y,finalText:c.finalText,thinkingBlocks:G,log:o});if(l?.action==="end"){let _=vn(l.content,y,"stop hook prevented continuation before producing the requested final marker");yield P(_);return}if(l?.action==="continue"){c={...c,messages:l.messages,stopHookActive:l.stopHookActive,transition:l.transition};continue}let d=gn({tokenBudget:e.tokenBudget,totalUsage:c.totalUsage,budgetContinuationCount:c.budgetContinuationCount,lastBudgetDeltaTokens:c.lastBudgetDeltaTokens,lastBudgetGlobalTokens:c.lastBudgetGlobalTokens,messages:y,finalText:c.finalText,thinkingBlocks:G,getBudgetContinuationMessage:e.runtimePorts.getBudgetContinuationMessage,log:o});if(d){yield O("budget_continuation",d.recoveryDetail),c={...c,messages:d.messages,budgetContinuationCount:d.budgetContinuationCount,lastBudgetDeltaTokens:d.lastBudgetDeltaTokens,lastBudgetGlobalTokens:d.lastBudgetGlobalTokens,transition:d.transition};continue}let h=$t({inputMessages:i,messages:y,finalText:c.finalText,thinkingBlocks:G,stopHookActive:c.stopHookActive,totalToolCallCount:F,distinctToolNames:w,log:o});if(h){if(c.stopHookActive&&(h.reason==="final_marker_verification"||c.finalText.trim()==="")){let _=se({inputMessages:i,messages:h.messages,reason:"final marker verification produced an empty response after tool use"});if(_){yield P(_);return}if(h.reason==="final_marker_verification"&&c.finalText.trim()===""&&c.finalMarkerEmptyRecoveryCount<1){yield O("final_marker_empty_retry","one extra retry after empty marker nudge"),c={...c,messages:h.messages,stopHookActive:h.stopHookActive,transition:h.transition,finalMarkerEmptyRecoveryCount:c.finalMarkerEmptyRecoveryCount+1};continue}let I=Nt({inputMessages:i,messages:h.messages});if(I){yield P(I);return}let X=qe({inputMessages:i,reason:"final marker verification produced an empty response after tool use"});if(X){yield P(X);return}}c={...c,messages:h.messages,stopHookActive:h.stopHookActive,transition:h.transition};continue}let C=Ut({totalToolCallCount:F,distinctToolNames:w,projectRoot:e.projectRoot});C&&(yield{type:"skill_instruction",turnId:r,instruction:C});let S=me(y,"the model ended with an empty response after tool use before producing the requested final marker");for(let _ of Xe)yield{type:"delta",turnId:r,text:_};yield P(S);return}let En=G.length===0&&ye.length>0?ye.join(""):void 0;y.push(Qe(j,void 0,G.length>0?G:void 0,En)),B=gt(B,{replayMessages:y,pendingToolCallIds:j.map(l=>l.id),completedToolCallIds:B.completedToolCallIds,lastStopReason:"tool_calls"});let Se=c.identicalCallCounts,Yt=[],Ee=[],Vt=[],Zt=!1;for(let l of j){let d=`${l.function.name}::${l.function.arguments}`,h=Se.get(d)??0;if(Se.set(d,h+1),h+1>yo){let C=jt.has(l.function.name)?c.identicalSuccessfulToolResults.get(d):void 0;if(C){Vt.push({call:l,result:C,repeatCount:h+1});continue}Ee.push(l),Zt||(Zt=!0,o.info(`AP4 blocked: ${l.function.name} repeated ${h+1}x`))}else Yt.push(l)}let W=[];for(let l of Vt){let d=l.call,h=`Reused previous successful ${d.function.name} result for identical arguments (attempt ${l.repeatCount}); no additional tool execution was performed.
9
9
 
10
- ${l.result.content}`,C=W(u.id,{ok:!0,payload:y,imageUrls:l.result.imageUrls,toolReferences:l.result.toolReferences});g.push(C),G.push(u.id),L.add(u.function.name),E++,yield{type:"tool_result",turnId:r,callId:u.id,name:u.function.name,ok:!0,outputPreview:y.slice(0,2e3),durationMs:0,details:{type:u.function.name,reusedIdenticalCall:!0,repeatCount:l.repeatCount}}}for(let l of ke){let u=Ce.get(`${l.function.name}::${l.function.arguments}`),y=Tt(g,l.function.name),C=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.`,v=W(l.id,{ok:!1,error:C});g.push(v),G.push(l.id),L.add(l.function.name),E++,yield{type:"tool_result",turnId:r,callId:l.id,name:l.function.name,ok:!1,error:C}}if(ke.length>0){let l=Tt(g,ke[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."};g.push(u)}let $t=[],je=[];for(let l of Nt){let u=tn({inputMessages:i,messages:g,toolCall:l});u?je.push({call:l,error:u}):$t.push(l)}for(let l of je){let u=l.call;g.push(W(u.id,{ok:!1,error:l.error})),G.push(u.id),L.add(u.function.name),E++,yield{type:"tool_result",turnId:r,callId:u.id,name:u.function.name,ok:!1,error:l.error},n.info(`premature completion artifact blocked: ${u.function.name}`)}je.length>0&&g.push({role:"user",content:"A tool attempted to write a completion artifact before all explicitly requested output files had evidence. Do not write final DONE markers or success reports into artifacts until the missing files are created or verified. If you cannot complete them, respond with the requested FAIL marker and the real reason."});let Cn=new Set(X.map(l=>l.function.name)),Ut=[],jt=[];for(let l of $t)Cn.has(l.function.name)?Ut.push(l):jt.push(l);for(let l of jt){let u=`Tool "${l.function.name}" was not offered for this turn and will not be executed. Use only the tools listed in the current request.`;g.push(W(l.id,{ok:!1,error:u})),G.push(l.id),n.warn(`unoffered tool call suppressed: ${l.function.name}`)}let qe=rn(Ut,c.toolFailureCounts),qt=qe.allowed,zt=Math.max(0,oe-E),de=zt>0?qt.slice(0,zt):[],ze=qt.slice(de.length),kn=ze.length>0;if(qe.blocked.length>0){for(let l of qe.blocked){let u=l.call,y=W(u.id,{ok:!1,error:l.error});g.push(y),G.push(u.id),L.add(u.function.name),E++,yield{type:"tool_result",turnId:r,callId:u.id,name:u.function.name,ok:!1,error:l.error},n.info(`variant tool blocked: ${u.function.name} failed ${l.failCount}x with different args`)}g.push(sn())}if(ze.length>0){let l=`Tool call budget exhausted (${oe}) for this turn. Stop requesting more tools and report what remains incomplete.`;for(let u of ze){let y=W(u.id,{ok:!1,error:l});g.push(y),G.push(u.id),L.add(u.function.name),E++,yield{type:"tool_result",turnId:r,callId:u.id,name:u.function.name,ok:!1,error:l}}g.push({role:"user",content:`${l} If explicitly requested output files are still missing, respond with the requested FAIL marker and the real reason.`})}for(let l of de){let u=l.function.arguments,y=X.find(C=>C.function.name===l.function.name);if(y?.backfillObservableInput)try{let C=JSON.parse(l.function.arguments),v={...C};y.backfillObservableInput(v),Object.keys(v).some(w=>!(w in C))&&(u=JSON.stringify(v))}catch{}yield{type:"tool_call",turnId:r,callId:l.id,name:l.function.name,arguments:u,inputSummary:No(u)}}let Rn=new Map(c.toolFailureCounts),Re=null;try{let l=e.runtimePorts.createStreamingToolExecutor({toolInvoker:o,hooks:m,sessionId:s,turnId:r,log:n,signal:b,maxConcurrentTools:e?.maxConcurrentTools,maxExecutionMs:to});for(let u of de)l.addTool(u);for await(let u of l.getRemainingResults()){u.blocked&&(yield{type:"tool_blocked",turnId:r,callId:u.callId,name:u.toolName,reason:u.blockReason??"blocked"}),g.push(u.message),G.push(u.callId),L.add(u.toolName),E++;let y=u.ok&&Po(u);if(an({toolFailureCounts:c.toolFailureCounts,toolName:u.toolName,ok:u.ok,softEmpty:y}),u.ok&&ys.has(u.toolName)&&hs(c),u.ok&&!y&&St.has(u.toolName)){let C=de.find(M=>M.id===u.callId),v=typeof u.message?.content=="string"?u.message.content:"";if(C&&v){let M=Array.isArray(u.message.imageUrls)?u.message.imageUrls.filter(K=>typeof K=="string"):void 0,w=Array.isArray(u.message.toolReferences)?u.message.toolReferences.filter(K=>typeof K=="string"):void 0;c.identicalSuccessfulToolResults.set(`${C.function.name}::${C.function.arguments}`,{content:v,imageUrls:M,toolReferences:w})}}if(u.ok&&u.toolName==="read"){let C=de.find(v=>v.id===u.callId);if(C)try{let v=JSON.parse(C.function.arguments),M=v.file_path??v.path??v.filePath??"";if(M){let w=c.fileReadCounts.get(M)??0;c.fileReadCounts.set(M,w+1)}}catch{}}yield So(r,u);for(let C of Eo(r,u))yield C;for(let C of wo({turnId:r,result:u,toolCalls:$}))yield C;!Re&&gn&&u.toolName==="stt"&&u.ok&&(Re=ms(i,u))}}catch(l){let u=l instanceof Error?l.message:String(l);yield{type:"error",turnId:r,error:u,code:"TOOL_EXECUTION_ERROR",usage:c.totalUsage};return}if(Re){yield I(Re);return}if(g.push(...ln({toolFailureCounts:c.toolFailureCounts,snapshot:Rn})),kn){let l=te({inputMessages:i,messages:g,reason:`tool call budget exhausted (${oe}) before completing all required files`});if(l){yield I(l);return}}if(N=_e(N,{replayMessages:g,completedToolCallIds:[...N.completedToolCallIds,...G],lastStopReason:"tool_calls"}),e.toolChoice==="required"&&$.length>0&&(Ne=!0),e.generateToolUseSummary&&$.length>0){let l=$.map(u=>({name:u.function.name,arguments:u.function.arguments}));ye=e.generateToolUseSummary(l).catch(()=>null)}let bn=$.length>0&&$.every(l=>{let u=g.find(C=>C?.role==="tool"&&C?.tool_call_id===l.id);if(!u)return!0;let y=u.content;return typeof y=="string"&&y.startsWith("Error: ")}),pe=c.consecutiveFailedRounds;if(bn){if(pe+=1,pe>=oo){if(Fe>=3&&c.repeatedToolFailureRecoveryCount<1){let y=At({inputMessages:i,messages:g,finalText:c.finalText,thinkingBlocks:[],stopHookActive:c.stopHookActive,totalToolCallCount:E,distinctToolNames:L,log:n});if(y?.reason==="explicit_required_file_verification"||y?.reason==="explicit_extra_file_verification"){yield O("repeated_tool_failure_artifact_recovery","one recovery nudge before ending a complex explicit artifact turn after repeated tool failures"),c={...c,messages:y.messages,stopHookActive:y.stopHookActive,transition:y.transition,consecutiveFailedRounds:0,repeatedToolFailureRecoveryCount:c.repeatedToolFailureRecoveryCount+1};continue}}let l=te({inputMessages:i,messages:g,reason:"repeated tool failures stopped the turn before completing all required files"});if(l){yield I(l);return}let u=ae(g,"repeated tool failures stopped the turn before producing the requested final marker");n.info(`early exit: ${pe} consecutive failed rounds, returning ${c.finalText?"partial":"fallback"} response`),yield I(u);return}}else pe=0;let xn=3,Ht=[...c.fileReadCounts.entries()].filter(([,l])=>l>=xn);if(Ht.length>0){let l=Ht.map(([y])=>y).join(", ");n.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.`};g.push(u),c.fileReadCounts.clear()}let He=H+1;if(h>0&&He>h){if(n.info(`max turns reached (${h}), completing`),m){let y=await m.invoke("stop",{sessionId:s,reason:"max_turns"});if(y.action==="abort"){let C=y.reason??"Stop hook requested continuation after max_turns",v={role:"assistant",content:c.finalText,...j.length>0&&{thinkingBlocks:[...j]}};c={...c,messages:[...g,v,{role:"user",content:C}],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}};continue}}let l=te({inputMessages:i,messages:g,reason:`tool loop max turns reached (${h}) before completing all required files`});if(l){yield I(l);return}let u=ae(g,`tool loop max turns reached (${h}) before producing the requested final marker`);yield I(u);return}if(He>P){n.info(`tool loop budget exhausted (${P} rounds), returning`);let l=vt({totalToolCallCount:E,distinctToolNames:L,projectRoot:e.projectRoot});l&&(yield{type:"skill_instruction",turnId:r,instruction:l});let u=te({inputMessages:i,messages:g,reason:`tool budget exhausted (${P} rounds) before completing all required files`});if(u){yield I(u);return}let y=ae(g,`tool budget exhausted (${P} rounds) before producing the requested final marker`);yield I(y);return}c={messages:g,maxOutputTokensRecoveryCount:0,hasAttemptedReactiveCompact:!1,maxOutputTokensOverride:void 0,turnCount:He,transition:{reason:"next_turn"},guardState:A,reactiveCompactState:U,toolLoopState:N,consecutiveFailedRounds:pe,finalText:c.finalText,totalUsage:c.totalUsage,collapseStore:Be,currentModel:c.currentModel,consecutive529Errors:0,consecutiveApiRetries:0,stopHookActive:c.stopHookActive,lastResponseId:c.lastResponseId,snipRemovedIds:c.snipRemovedIds,contentReplacementState:c.contentReplacementState,budgetContinuationCount:c.budgetContinuationCount,finalMarkerEmptyRecoveryCount:c.finalMarkerEmptyRecoveryCount,repeatedToolFailureRecoveryCount:c.repeatedToolFailureRecoveryCount,lastBudgetDeltaTokens:c.lastBudgetDeltaTokens,lastBudgetGlobalTokens:c.lastBudgetGlobalTokens,identicalCallCounts:Ce,identicalSuccessfulToolResults:c.identicalSuccessfulToolResults,toolFailureCounts:c.toolFailureCounts,fileReadCounts:c.fileReadCounts,recoveryTrace:c.recoveryTrace}}}var Ts=["\u63A5\u5355\u91D1\u989D","\u5408\u540C\u91D1\u989D","\u62A5\u4EF7","\u9884\u7B97","\u91D1\u989D","price","amount","contract amount"];function pn(e){let t=Cs(e),o=["[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){o.push("[Memory conflict detected]");for(let n of t)o.push(`- entity: ${n.entity}; fact: ${n.predicate}; L1 project MD says: ${dn(n.l1Amount)}; L2 long-term says: ${dn(n.l2Amount)}; action: ask the user which value is current before using it.`)}for(let n of e){let r=bs(n);o.push(`- [${r}] ${n.text}`)}return o.join(`
11
- `)}function Cs(e){let t=e.filter(r=>r.source==="l1-project-md").flatMap(r=>un(r.text)),o=e.filter(r=>r.source==="l2-long-term").flatMap(r=>un(r.text)),n=[];for(let r of t)for(let s of o)r.entity===s.entity&&r.predicate===s.predicate&&r.amount!==s.amount&&n.push({entity:r.entity,predicate:r.predicate,l1Amount:r.amount,l2Amount:s.amount,l1Text:r.text,l2Text:s.text});return xs(n)}function un(e){let t=[];for(let o of e.split(/\r?\n/)){let n=o.trim();if(n)for(let r of Ts){if(r==="\u91D1\u989D"&&/(接单金额|合同金额)/u.test(n))continue;let s=new RegExp(`${_s(r)}[^0-9.\u4E07kK,]{0,12}([0-9][0-9.,]*\\s*(?:\u4E07|k|K)?)`,"gi");for(let i of n.matchAll(s)){let a=Rs(i[1]);a!==null&&t.push({entity:ks(n,r),predicate:r,amount:a,text:n})}}}return t}function ks(e,t){if(/Galaxy\s+Tech/i.test(e))return"Galaxy Tech";if(e.includes("\u7528\u6237"))return"\u7528\u6237";let o=e.toLowerCase().indexOf(t.toLowerCase()),r=(o>=0?e.slice(0,o):"").replace(/[#*`:\-,。;;,.]/g," ").trim().split(/\s+/).filter(Boolean);return r[r.length-1]??"unknown"}function Rs(e){let t=e.replace(/,/g,"").replace(/\s+/g,"").trim(),o=t.endsWith("\u4E07")?1e4:/k$/i.test(t)?1e3:1,n=Number(t.replace(/[万kK]$/u,""));return Number.isFinite(n)?n*o:null}function bs(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 dn(e){return Number.isInteger(e)?String(e):String(Number(e.toFixed(4)))}function xs(e){let t=new Set;return e.filter(o=>{let n=`${o.entity}\0${o.predicate}\0${o.l1Amount}\0${o.l2Amount}`;return t.has(n)?!1:(t.add(n),!0)})}function _s(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var Ms=8192;async function mn(e){let{hooks:t,detectRecallCategories:o,log:n,sessionId:r,turnId:s,query:i}=e;try{let a=o(i),p=(await t.invoke("memory.before_recall",{sessionId:r,turnId:s,query:i,preferredCategories:a.preferred.length>0?a.preferred:void 0,deprioritizedCategories:a.deprioritized.length>0?a.deprioritized:void 0}))?.context?.recalledMemories,f=null;if(p&&p.length>0){let m=0,b=[];for(let T of p){let h=(T.text?.length??0)*2;if(m+h>Ms)break;b.push(T),m+=h}b.length>0&&(f=`[Recalled memories \u2014 context priority: project-specific facts override general user preferences when they conflict]
12
- ${pn(b)}`)}return S(t,"memory.after_recall",{sessionId:r,turnId:s,blockCount:p?.length??0},n),f}catch{return null}}var fn=class{transport;apiKey;toolInvoker;log;hooks;maxRounds;configuredMaxRounds;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.configuredMaxRounds=typeof t.maxRounds=="number"&&Number.isFinite(t.maxRounds)?Math.min(t.maxRounds,100):void 0,this.maxRounds=Math.min(this.configuredMaxRounds??25,100)}async*run(t,o){let{turnId:n,messages:r,tools:s,systemPrompt:i,config:a}=t,d={sessionId:t.sessionId,turnId:n};yield{type:"start",turnId:n},S(this.hooks,"turn.submitted",{...d,prompt:r[r.length-1]?.content??void 0},this.log);let p=at(r),f=[];if(i&&f.push({role:"system",content:i}),f.push(...p),this.hooks){let h=p.filter(_=>_.role==="user").pop(),k=typeof h?.content=="string"?h.content.slice(0,500):void 0;if(k){let _=await mn({hooks:this.hooks,detectRecallCategories:R=>this.runtimePorts.detectRecallCategories(R),log:this.log,sessionId:t.sessionId,turnId:n,query:k});_&&f.splice(i?1:0,0,{role:"system",content:_})}}let m=a?.model??"",b=typeof a?.maxRounds=="number"&&Number.isFinite(a.maxRounds)?a.maxRounds:this.configuredMaxRounds,T=b===void 0?void 0:Math.min(b,100);try{let h=async P=>{let oe=this.runtimePorts.resolveModelForPurpose("smallModel");if(!oe)return null;try{let Fe=P.map(E=>`${E.name}(${E.arguments.slice(0,200)})`).join(", "),q=this.transport.stream({model:oe,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:Fe}],tools:[],maxTokens:60},a?.apiKey??this.apiKey),L="";for await(let E of q)E.type==="delta"&&(L+=E.text);return L.trim()||null}catch{return null}},k=a?.reasoning;a?.reasoning?.effort==="auto"&&(k={...a?.reasoning,effort:"medium"});let _={turnId:n,sessionId:t.sessionId,messages:f,tools:s,model:m,apiKey:a?.apiKey??this.apiKey,temperature:a?.temperature,maxRounds:T,contextWindowTokens:a?.contextWindowTokens,maxOutputTokens:a?.maxOutputTokens,modelMaxOutputTokens:a?.modelMaxOutputTokens,toolChoice:a?.toolChoice,parentDepth:a?.parentDepth,hooks:this.hooks,fallbackModel:a?.fallbackModel,maxTurns:a?.maxTurns,tokenBudget:a?.tokenBudget,maxConcurrentTools:a?.maxConcurrentTools,streamRequired:a?.streamRequired,reasoning:k,promptCacheKey:a?.promptCacheKey,promptCacheRetention:a?.promptCacheRetention,serviceTier:a?.serviceTier,openaiBuiltinTools:a?.openaiBuiltinTools,maxToolCalls:a?.maxToolCalls,parallelToolCalls:a?.parallelToolCalls,textVerbosity:a?.textVerbosity,projectRoot:this.projectRoot,generateToolUseSummary:h,runtimePorts:this.runtimePorts.toolLoop,signal:o},R;for await(let P of cn(_,this.transport,this.toolInvoker,this.log))R=P,yield P;R?.type==="end"?S(this.hooks,"turn.completed",{...d},this.log):R?.type==="error"&&S(this.hooks,"turn.failed",{...d,code:R.code,error:R.error},this.log)}catch(h){if(o?.aborted)S(this.hooks,"turn.failed",{...d,code:"ABORTED",error:"Turn aborted"},this.log),yield{type:"error",turnId:n,error:"Turn aborted",code:"ABORTED"};else{let k=h instanceof Error?h.message:String(h),_=typeof h?.status=="number"?h.status:void 0,R=ne(_,k);this.log.error(`turn ${n} error [${R}, retryable=${We(R)}]: ${k}`),S(this.hooks,"turn.failed",{...d,code:R,error:k},this.log),yield{type:"error",turnId:n,error:k,code:R}}}}};export{fn as Agent};
10
+ ${l.result.content}`,C=Y(d.id,{ok:!0,payload:h,imageUrls:l.result.imageUrls,toolReferences:l.result.toolReferences});y.push(C),W.push(d.id),w.add(d.function.name),F++,yield{type:"tool_result",turnId:r,callId:d.id,name:d.function.name,ok:!0,outputPreview:h.slice(0,2e3),durationMs:0,details:{type:d.function.name,reusedIdenticalCall:!0,repeatCount:l.repeatCount}}}for(let l of Ee){let d=Se.get(`${l.function.name}::${l.function.arguments}`),h=Mt(y,l.function.name),C=h?`This exact tool call has been attempted ${d} times. Last error: ${h}. Do not retry. Report this error to the user.`:`This exact tool call has been attempted ${d} times and keeps failing. Do not retry it. Report the issue to the user or try a completely different approach.`,S=Y(l.id,{ok:!1,error:C});y.push(S),W.push(l.id),w.add(l.function.name),F++,yield{type:"tool_result",turnId:r,callId:l.id,name:l.function.name,ok:!1,error:C}}if(Ee.length>0){let l=Mt(y,Ee[0].function.name),d={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(d)}let Jt=[],Ye=[];for(let l of Yt){let d=mn({inputMessages:i,messages:y,toolCall:l});d?Ye.push({call:l,error:d}):Jt.push(l)}for(let l of Ye){let d=l.call;y.push(Y(d.id,{ok:!1,error:l.error})),W.push(d.id),w.add(d.function.name),F++,yield{type:"tool_result",turnId:r,callId:d.id,name:d.function.name,ok:!1,error:l.error},o.info(`premature completion artifact blocked: ${d.function.name}`)}Ye.length>0&&y.push({role:"user",content:"A tool attempted to write a completion artifact before all explicitly requested output files had evidence. Do not write final DONE markers or success reports into artifacts until the missing files are created or verified. If you cannot complete them, respond with the requested FAIL marker and the real reason."});let wn=new Set(Q.map(l=>l.function.name)),Qt=[],eo=[];for(let l of Jt)wn.has(l.function.name)?Qt.push(l):eo.push(l);for(let l of eo){let d=`Tool "${l.function.name}" was not offered for this turn and will not be executed. Use only the tools listed in the current request.`;y.push(Y(l.id,{ok:!1,error:d})),W.push(l.id),o.warn(`unoffered tool call suppressed: ${l.function.name}`)}let Ve=yn(Qt,c.toolFailureCounts),Ze=Ve.allowed;if(xe&&Ze.length>Math.max(0,L-F)){let l=vt({currentToolBudget:L,currentRoundBudget:A,toolHardCap:100,roundHardCap:100,continuationCount:pe,successfulSinceLastCheck:de-_e,fileReadCounts:c.fileReadCounts,windowTools:re,windowRounds:25});l&&(L=l.nextToolBudget,A=l.nextRoundBudget,pe=l.continuationCount,_e=de,o.info(`tool budget continuation #${l.continuationCount}: tools\u2192${L}, rounds\u2192${A} (progress detected)`))}let to=Math.max(0,L-F),he=to>0?Ze.slice(0,to):[],Je=Ze.slice(he.length),In=Je.length>0;if(Ve.blocked.length>0){for(let l of Ve.blocked){let d=l.call,h=Y(d.id,{ok:!1,error:l.error});y.push(h),W.push(d.id),w.add(d.function.name),F++,yield{type:"tool_result",turnId:r,callId:d.id,name:d.function.name,ok:!1,error:l.error},o.info(`variant tool blocked: ${d.function.name} failed ${l.failCount}x with different args`)}y.push(hn())}if(Je.length>0){let l=`Tool call budget exhausted (${L}) for this turn. Stop requesting more tools and report what remains incomplete.`;for(let d of Je){let h=Y(d.id,{ok:!1,error:l});y.push(h),W.push(d.id),w.add(d.function.name),F++,yield{type:"tool_result",turnId:r,callId:d.id,name:d.function.name,ok:!1,error:l}}y.push({role:"user",content:`${l} You reached this turn's tool budget after ${pe} extension(s). Do NOT claim the task is complete or that all files were created if it is not. Be honest in your reply: (1) state plainly the turn stopped before finishing; (2) list concretely what is DONE vs what is still UNFINISHED; (3) tell the user to reply "\u7EE7\u7EED" to finish the rest. If explicitly requested output files are still missing, respond with the requested FAIL marker and the real reason.`})}for(let l of he){let d=l.function.arguments,h=Q.find(C=>C.function.name===l.function.name);if(h?.backfillObservableInput)try{let C=JSON.parse(l.function.arguments),S={...C};h.backfillObservableInput(S),Object.keys(S).some(I=>!(I in C))&&(d=JSON.stringify(S))}catch{}yield{type:"tool_call",turnId:r,callId:l.id,name:l.function.name,arguments:d,inputSummary:Yo(d)}}let Pn=new Map(c.toolFailureCounts),we=null;try{let l=e.runtimePorts.createStreamingToolExecutor({toolInvoker:n,hooks:m,sessionId:s,turnId:r,log:o,signal:k,maxConcurrentTools:e?.maxConcurrentTools,maxExecutionMs:fo});for(let d of he)l.addTool(d);for await(let d of l.getRemainingResults()){d.blocked&&(yield{type:"tool_blocked",turnId:r,callId:d.callId,name:d.toolName,reason:d.blockReason??"blocked"}),y.push(d.message),W.push(d.callId),w.add(d.toolName),F++;let h=d.ok&&Ho(d);if(d.ok&&!h&&(de+=1),Tn({toolFailureCounts:c.toolFailureCounts,toolName:d.toolName,ok:d.ok,softEmpty:h}),d.ok&&Es.has(d.toolName)&&ws(c),d.ok&&!h&&jt.has(d.toolName)){let C=he.find(_=>_.id===d.callId),S=typeof d.message?.content=="string"?d.message.content:"";if(C&&S){let _=Array.isArray(d.message.imageUrls)?d.message.imageUrls.filter(X=>typeof X=="string"):void 0,I=Array.isArray(d.message.toolReferences)?d.message.toolReferences.filter(X=>typeof X=="string"):void 0;c.identicalSuccessfulToolResults.set(`${C.function.name}::${C.function.arguments}`,{content:S,imageUrls:_,toolReferences:I})}}if(d.ok&&d.toolName==="read"){let C=he.find(S=>S.id===d.callId);if(C)try{let S=JSON.parse(C.function.arguments),_=S.file_path??S.path??S.filePath??"";if(_){let I=c.fileReadCounts.get(_)??0;c.fileReadCounts.set(_,I+1)}}catch{}}yield Uo(r,d);for(let C of jo(r,d))yield C;for(let C of qo({turnId:r,result:d,toolCalls:j}))yield C;!we&&An&&d.toolName==="stt"&&d.ok&&(we=As(i,d))}}catch(l){let d=l instanceof Error?l.message:String(l);yield{type:"error",turnId:r,error:d,code:"TOOL_EXECUTION_ERROR",usage:c.totalUsage};return}if(we){yield P(we);return}if(y.push(...Cn({toolFailureCounts:c.toolFailureCounts,snapshot:Pn})),In){let l=se({inputMessages:i,messages:y,reason:`tool call budget exhausted (${L}) before completing all required files`});if(l){yield P(l);return}}if(B=Oe(B,{replayMessages:y,completedToolCallIds:[...B.completedToolCallIds,...W],lastStopReason:"tool_calls"}),e.toolChoice==="required"&&j.length>0&&(ze=!0),e.generateToolUseSummary&&j.length>0){let l=j.map(d=>({name:d.function.name,arguments:d.function.arguments}));Me=e.generateToolUseSummary(l).catch(()=>null)}let Ln=j.length>0&&j.every(l=>{let d=y.find(C=>C?.role==="tool"&&C?.tool_call_id===l.id);if(!d)return!0;let h=d.content;return typeof h=="string"&&h.startsWith("Error: ")}),Te=c.consecutiveFailedRounds;if(Ln){if(Te+=1,Te>=go){if(He>=3&&c.repeatedToolFailureRecoveryCount<1){let h=$t({inputMessages:i,messages:y,finalText:c.finalText,thinkingBlocks:[],stopHookActive:c.stopHookActive,totalToolCallCount:F,distinctToolNames:w,log:o});if(h?.reason==="explicit_required_file_verification"||h?.reason==="explicit_extra_file_verification"){yield O("repeated_tool_failure_artifact_recovery","one recovery nudge before ending a complex explicit artifact turn after repeated tool failures"),c={...c,messages:h.messages,stopHookActive:h.stopHookActive,transition:h.transition,consecutiveFailedRounds:0,repeatedToolFailureRecoveryCount:c.repeatedToolFailureRecoveryCount+1};continue}}let l=se({inputMessages:i,messages:y,reason:"repeated tool failures stopped the turn before completing all required files"});if(l){yield P(l);return}let d=me(y,"repeated tool failures stopped the turn before producing the requested final marker");o.info(`early exit: ${Te} consecutive failed rounds, returning ${c.finalText?"partial":"fallback"} response`),yield P(d);return}}else Te=0;let On=3,oo=[...c.fileReadCounts.entries()].filter(([,l])=>l>=On);if(oo.length>0){let l=oo.map(([h])=>h).join(", ");o.info(`AP5: file read cycle detected on ${l}, injecting nudge`);let d={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(d),c.fileReadCounts.clear()}let Ie=$+1;if(g>0&&Ie>g){if(o.info(`max turns reached (${g}), completing`),m){let h=await m.invoke("stop",{sessionId:s,reason:"max_turns"});if(h.action==="abort"){let C=h.reason??"Stop hook requested continuation after max_turns",S={role:"assistant",content:c.finalText,...G.length>0&&{thinkingBlocks:[...G]}};c={...c,messages:[...y,S,{role:"user",content:C}],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}};continue}}let l=se({inputMessages:i,messages:y,reason:`tool loop max turns reached (${g}) before completing all required files`});if(l){yield P(l);return}let d=me(y,`tool loop max turns reached (${g}) before producing the requested final marker`);yield P(d);return}if(xe&&Ie>A){let l=vt({currentToolBudget:L,currentRoundBudget:A,toolHardCap:100,roundHardCap:100,continuationCount:pe,successfulSinceLastCheck:de-_e,fileReadCounts:c.fileReadCounts,windowTools:re,windowRounds:25});l&&(A=l.nextRoundBudget,L=l.nextToolBudget,pe=l.continuationCount,_e=de,o.info(`round budget continuation #${l.continuationCount}: rounds\u2192${A}, tools\u2192${L} (progress detected)`))}if(Ie>A){o.info(`tool loop budget exhausted (${A} rounds), returning`);let l=Ut({totalToolCallCount:F,distinctToolNames:w,projectRoot:e.projectRoot});l&&(yield{type:"skill_instruction",turnId:r,instruction:l});let d=se({inputMessages:i,messages:y,reason:`tool budget exhausted (${A} rounds) before completing all required files`});if(d){yield P(d);return}let h=me(y,`tool budget exhausted (${A} rounds) before producing the requested final marker`);yield P(h);return}c={messages:y,maxOutputTokensRecoveryCount:0,hasAttemptedReactiveCompact:!1,maxOutputTokensOverride:void 0,turnCount:Ie,transition:{reason:"next_turn"},guardState:v,reactiveCompactState:z,toolLoopState:B,consecutiveFailedRounds:Te,finalText:c.finalText,totalUsage:c.totalUsage,collapseStore:Ke,currentModel:c.currentModel,consecutive529Errors:0,consecutiveApiRetries:0,stopHookActive:c.stopHookActive,lastResponseId:c.lastResponseId,snipRemovedIds:c.snipRemovedIds,contentReplacementState:c.contentReplacementState,budgetContinuationCount:c.budgetContinuationCount,finalMarkerEmptyRecoveryCount:c.finalMarkerEmptyRecoveryCount,repeatedToolFailureRecoveryCount:c.repeatedToolFailureRecoveryCount,lastBudgetDeltaTokens:c.lastBudgetDeltaTokens,lastBudgetGlobalTokens:c.lastBudgetGlobalTokens,identicalCallCounts:Se,identicalSuccessfulToolResults:c.identicalSuccessfulToolResults,toolFailureCounts:c.toolFailureCounts,fileReadCounts:c.fileReadCounts,recoveryTrace:c.recoveryTrace}}}var Is=["\u63A5\u5355\u91D1\u989D","\u5408\u540C\u91D1\u989D","\u62A5\u4EF7","\u9884\u7B97","\u91D1\u989D","price","amount","contract amount"];function xn(e){let t=Ps(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: ${bn(o.l1Amount)}; L2 long-term says: ${bn(o.l2Amount)}; action: ask the user which value is current before using it.`)}for(let o of e){let r=Fs(o);n.push(`- [${r}] ${o.text}`)}return n.join(`
11
+ `)}function Ps(e){let t=e.filter(r=>r.source==="l1-project-md").flatMap(r=>Rn(r.text)),n=e.filter(r=>r.source==="l2-long-term").flatMap(r=>Rn(r.text)),o=[];for(let r of t)for(let s of n)r.entity===s.entity&&r.predicate===s.predicate&&r.amount!==s.amount&&o.push({entity:r.entity,predicate:r.predicate,l1Amount:r.amount,l2Amount:s.amount,l1Text:r.text,l2Text:s.text});return Ns(o)}function Rn(e){let t=[];for(let n of e.split(/\r?\n/)){let o=n.trim();if(o)for(let r of Is){if(r==="\u91D1\u989D"&&/(接单金额|合同金额)/u.test(o))continue;let s=new RegExp(`${Bs(r)}[^0-9.\u4E07kK,]{0,12}([0-9][0-9.,]*\\s*(?:\u4E07|k|K)?)`,"gi");for(let i of o.matchAll(s)){let a=Os(i[1]);a!==null&&t.push({entity:Ls(o,r),predicate:r,amount:a,text:o})}}}return t}function Ls(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 Os(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 Fs(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 bn(e){return Number.isInteger(e)?String(e):String(Number(e.toFixed(4)))}function Ns(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 Bs(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var Ds=8192;async function _n(e){let{hooks:t,detectRecallCategories:n,log:o,sessionId:r,turnId:s,query:i}=e;try{let a=n(i),p=(await t.invoke("memory.before_recall",{sessionId:r,turnId:s,query:i,preferredCategories:a.preferred.length>0?a.preferred:void 0,deprioritizedCategories:a.deprioritized.length>0?a.deprioritized:void 0}))?.context?.recalledMemories,f=null;if(p&&p.length>0){let m=0,k=[];for(let M of p){let g=(M.text?.length??0)*2;if(m+g>Ds)break;k.push(M),m+=g}k.length>0&&(f=`[Recalled memories \u2014 context priority: project-specific facts override general user preferences when they conflict]
12
+ ${xn(k)}`)}return E(t,"memory.after_recall",{sessionId:r,turnId:s,blockCount:p?.length??0},o),f}catch{return null}}var Mn=class{transport;apiKey;toolInvoker;log;hooks;maxRounds;configuredMaxRounds;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.configuredMaxRounds=typeof t.maxRounds=="number"&&Number.isFinite(t.maxRounds)?Math.min(t.maxRounds,100):void 0,this.maxRounds=Math.min(this.configuredMaxRounds??25,100)}async*run(t,n){let{turnId:o,messages:r,tools:s,systemPrompt:i,config:a}=t,u={sessionId:t.sessionId,turnId:o};yield{type:"start",turnId:o},E(this.hooks,"turn.submitted",{...u,prompt:r[r.length-1]?.content??void 0},this.log);let p=ft(r),f=[];if(i&&f.push({role:"system",content:i}),f.push(...p),this.hooks){let g=p.filter(b=>b.role==="user").pop(),T=typeof g?.content=="string"?g.content.slice(0,500):void 0;if(T){let b=await _n({hooks:this.hooks,detectRecallCategories:R=>this.runtimePorts.detectRecallCategories(R),log:this.log,sessionId:t.sessionId,turnId:o,query:T});b&&f.splice(i?1:0,0,{role:"system",content:b})}}let m=a?.model??"",k=typeof a?.maxRounds=="number"&&Number.isFinite(a.maxRounds)?a.maxRounds:this.configuredMaxRounds,M=k===void 0?void 0:Math.min(k,100);try{let g=async A=>{let L=this.runtimePorts.resolveModelForPurpose("smallModel");if(!L)return null;try{let xe=A.map(w=>`${w.name}(${w.arguments.slice(0,200)})`).join(", "),He=this.transport.stream({model:L,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:xe}],tools:[],maxTokens:60},a?.apiKey??this.apiKey),H="";for await(let w of He)w.type==="delta"&&(H+=w.text);return H.trim()||null}catch{return null}},T=a?.reasoning;a?.reasoning?.effort==="auto"&&(T={...a?.reasoning,effort:"medium"});let b={turnId:o,sessionId:t.sessionId,messages:f,tools:s,model:m,apiKey:a?.apiKey??this.apiKey,temperature:a?.temperature,maxRounds:M,contextWindowTokens:a?.contextWindowTokens,maxOutputTokens:a?.maxOutputTokens,modelMaxOutputTokens:a?.modelMaxOutputTokens,toolChoice:a?.toolChoice,parentDepth:a?.parentDepth,hooks:this.hooks,fallbackModel:a?.fallbackModel,maxTurns:a?.maxTurns,tokenBudget:a?.tokenBudget,maxConcurrentTools:a?.maxConcurrentTools,streamRequired:a?.streamRequired,reasoning:T,promptCacheKey:a?.promptCacheKey,promptCacheRetention:a?.promptCacheRetention,serviceTier:a?.serviceTier,openaiBuiltinTools:a?.openaiBuiltinTools,maxToolCalls:a?.maxToolCalls,parallelToolCalls:a?.parallelToolCalls,textVerbosity:a?.textVerbosity,projectRoot:this.projectRoot,generateToolUseSummary:g,runtimePorts:this.runtimePorts.toolLoop,signal:n},R;for await(let A of kn(b,this.transport,this.toolInvoker,this.log))R=A,yield A;R?.type==="end"?E(this.hooks,"turn.completed",{...u},this.log):R?.type==="error"&&E(this.hooks,"turn.failed",{...u,code:R.code,error:R.error},this.log)}catch(g){if(n?.aborted)E(this.hooks,"turn.failed",{...u,code:"ABORTED",error:"Turn aborted"},this.log),yield{type:"error",turnId:o,error:"Turn aborted",code:"ABORTED"};else{let T=g instanceof Error?g.message:String(g),b=typeof g?.status=="number"?g.status:void 0,R=ie(b,T);this.log.error(`turn ${o} error [${R}, retryable=${tt(R)}]: ${T}`),E(this.hooks,"turn.failed",{...u,code:R,error:T},this.log),yield{type:"error",turnId:o,error:T,code:R}}}}};export{Mn as Agent};