qlogicagent 2.17.1 → 2.17.5

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,44 +1,47 @@
1
- function cn(e,t,n,o){return{role:"assistant",content:t||null,tool_calls:e,...n&&n.length>0?{thinkingBlocks:n}:{},...o?{reasoning_content:o}:{}}}function X(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 _i=/\b(?:daily|weekly|monthly)(?:\/(?:daily|weekly|monthly))* (?:usage )?limit(?:s)?(?: (?:exhausted|reached|exceeded))?\b/i,we={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]},vi=/^(?:error[:\s-]+)?billing(?:\s+error)?(?:[:\s-]+|$)|^(?:error[:\s-]+)?(?:credit balance|insufficient credits?|payment required|http\s*402\b)/i,wi=/["']?(?:status|code)["']?\s*[:=]\s*402\b|\bhttp\s*402\b|\berror(?:\s+code)?\s*[:=]?\s*402\b|^\s*402\s+payment/i,Ai=512,Si=/^(?:http\s*)?(\d{3})(?:\s+([\s\S]+))?$/i;var Mi=new Set([500,502,503,504,521,522,523,524,529]),Ei=["insufficient credits","insufficient quota","credit balance","insufficient balance","plans & billing","add more credits","top up"],Ii=["upgrade your plan","upgrade plan","current plan","subscription"],Pi=["daily","weekly","monthly"],Oi=["try again","retry","temporary","cooldown"],Ni=["usage limit","rate limit","organization usage"],Li=["organization","workspace"],Fi=["billing period","exceeded","reached","exhausted"],Bi=/["']?(?: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,Di=/^(?:error[:\s-]+)?(?:(?:http\s*)?402(?:\s+payment required)?|payment required)(?:[:\s-]+|$)/i;function Ae(e,t){if(!e)return!1;let n=e.toLowerCase();return t.some(o=>o instanceof RegExp?o.test(n):n.includes(o))}function $i(e){return Ae(e,we.format)}function Ko(e){return Ae(e,we.rateLimit)}function Ui(e){return Ae(e,we.timeout)}function ji(e){return _i.test(e)}function un(e){let t=e.toLowerCase();return t?e.length>Ai?wi.test(t):Ae(t,we.billing)?!0:vi.test(e)?t.includes("upgrade")||t.includes("credits")||t.includes("payment")||t.includes("plan"):!1:!1}function Yo(e){return Ae(e,we.authPermanent)}function qi(e){return Ae(e,we.auth)}function Zo(e){return Ae(e,we.overloaded)}function ve(e,t){return t.some(n=>e.includes(n))}function zi(e){return ve(e,Ei)||ve(e,Ii)&&e.includes("limit")||e.includes("billing hard limit")||e.includes("hard limit reached")||e.includes("maximum allowed")&&e.includes("limit")}function Hi(e){let t=ve(e,Pi),n=e.includes("spend limit")||e.includes("spending limit"),o=ve(e,Li);return ve(e,Oi)&&ve(e,Ni)||t&&(e.includes("usage limit")||n)||t&&e.includes("limit")&&e.includes("reset")||o&&e.includes("limit")&&(n||ve(e,Fi))}function Gi(e){return e.trim().toLowerCase().replace(Di,"").trim()}function Jo(e){let t=Gi(e);return!t||zi(t)?"billing":Ko(t)||Hi(t)?"rate_limit":"billing"}function Wi(e){return Bi.test(e)?Jo(e):null}function Qo(e){let t=e.match(Si);if(!t)return null;let n=Number(t[1]);return Number.isFinite(n)?{code:n,rest:(t[2]??"").trim()}:null}function Vi(e){if(!e)return!1;let t=e.toLowerCase();return t.includes('"type":"api_error"')&&t.includes("internal server error")}function Xi(e){let t=e.trim();if(!t)return!1;let n=Qo(t);return n?Mi.has(n.code):!1}function er(e,t){return typeof e!="number"||!Number.isFinite(e)?null:e===402?t?Jo(t):"billing":e===429?"rate_limit":e===401||e===403?t&&Yo(t)?"auth_permanent":"auth":e===408?"timeout":e===503?t&&Zo(t)?"overloaded":"timeout":e===502||e===504?"timeout":e===529?"overloaded":e===400?t&&un(t)?"billing":"format":null}function Ki(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 Yi(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 tr(e){if(Yi(e))return"session_expired";if(Ki(e))return"model_not_found";let t=Wi(e);return t||(ji(e)?un(e)?"billing":"rate_limit":Ko(e)?"rate_limit":Zo(e)?"overloaded":Xi(e)?Qo(e.trim())?.code===529?"overloaded":"timeout":Vi(e)?"timeout":$i(e)?"format":un(e)?"billing":Ui(e)?"timeout":Yo(e)?"auth_permanent":qi(e)?"auth":null)}var Zi={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"},Ji=new Set(["RETRYABLE_TRANSIENT","RETRYABLE_DEGRADED","TOOL_EXECUTION_FAILED"]);function $e(e,t){let n=er(e,t)??(t?tr(t):null);return n?Zi[n]:typeof e=="number"&&e>=400&&e<500?"NON_RETRYABLE_CONTENT":"RETRYABLE_TRANSIENT"}function dn(e){return Ji.has(e)}function nr(e){let t=typeof e.content=="string"?e.content:e.content!=null?JSON.stringify(e.content):"";return Math.ceil(t.length/4)}var Qi=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"]),Ze=class{constructor(t=20,n=nr){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||!Qi.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 fn(e,t,n=nr){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 pn(){return{stages:[]}}function mn(e,t,n){let o=n?.thresholdMessages??40;if(e.filter(a=>a.role!=="system").length<=o)return{messages:e,stagedCount:0};let s=or(e,t),i=ea(s,t,o);if(i.length===0)return{messages:s,stagedCount:0};for(let a of i)t.stages.push(a);return s=or(e,t),{messages:s,stagedCount:i.length}}function gn(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:rr(e,t),committed:n}}function or(e,t){return t.stages.filter(o=>o.committed).length===0?e:rr(e,t)}function rr(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 ea(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 g=`${i}-${i+a}`;s.has(g)||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{readFileSync as ta,writeFileSync as na,mkdirSync as oa}from"node:fs";import{join as ra,dirname as sa}from"node:path";var be=Math.min(Math.max(1,Number(process.env.TOOL_LOOP_DEFAULT_BUDGET)||25),100),sr=Math.max(1e3,Number(process.env.TOOL_LOOP_TOOL_TIMEOUT_MS)||24e4),ir=3,ar=2,bt=2,lr=128e3,cr=13e3,ur=16384,dr=65536,fr=3,pr=65536,hn=500,mr=3;var gr=3e4,hr=3,Se=2;var yr=3,br=2,Tr=300*1e3,Cr=3,kr=720*60*60*1e3;var Zu=3600*1e3;var Ju=50*1024,Qu=500*1024,ed=500*1024*1024,td=50*1024*1024;var nd=60*1024;var xr=0;var ia="skill-patterns.json";function _r(e){return ra(e,".qlogicagent",ia)}function aa(e){let t=_r(e);try{return JSON.parse(ta(t,"utf8"))}catch{return{version:1,patterns:{}}}}function Rr(e,t){let n=_r(e);oa(sa(n),{recursive:!0}),na(n,JSON.stringify(t,null,2),"utf8")}function la(e){let t=Date.now()-kr;for(let[n,o]of Object.entries(e.patterns))new Date(o.lastSeen).getTime()<t&&delete e.patterns[n]}function vr(e,t){if(t.length===0)return!1;let n=wr(t),o=aa(e);la(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 Rr(e,o),!1;s.count++,s.lastSeen=r;let i=s.count>=Cr;return i&&(s.promoted=!0),Rr(e,o),i}function wr(e){return[...e].sort().join("+")}function ca(e,t){return!(!e.ok||e.existingSkillName||!e.multiStep||e.toolCallCount<yr||e.distinctToolCount<br||Date.now()-xr<Tr||t?.projectRoot&&t.tools.length>0&&!vr(t.projectRoot,t.tools))}function ua(e){return e.existingSkillName?e.feedback==="negative":!1}function yn(e,t){return ua(e)?{type:"skill.improve",skillName:e.existingSkillName,reason:"negative user feedback on existing skill execution"}:ca(e,t)?(xr=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 da(e){return[...new Set(e.map(Tt).filter(Boolean))].sort((t,n)=>t.localeCompare(n))}function Ar(e){let t=da(e);return t.length===0?"":`Available tools for this round: ${t.join(", ")}. Do not mention, invent, or attempt any tool that is not in this list.`}function fa(e){let t=[...new Set(e.map(Tt).filter(Boolean))].sort((i,a)=>i.localeCompare(a)),n=new Set(t),o=Ar(e),r=n.has("exec"),s=["read","search","write","edit","patch"].some(i=>n.has(i));return!r||!s?"You must call one of the available tools before responding. "+o:"You must call one of the available tools before responding. "+o+' Tool selection is part of correctness. Use read/search/write/edit/patch for file paths and file maintenance. For search, always include `mode` and `pattern`; examples: {"mode":"filename","pattern":"**/*.md"} or {"mode":"content","pattern":"TODO","fileGlob":"*.ts"}. Use exec only for shell commands with the required `command` field; never pass `path`, `filePath`, or file content to exec.'}function Tt(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 pa(e){return e==="enabled-eligible"||e==="installed-awaiting-approval"}function ma(e){return new Map((e??[]).map(t=>[t.toolName,t]))}function ga(e){if(!e.eligibility?.length)return[...e.tools];let t=ma(e.eligibility);return e.tools.filter(n=>{let o=Tt(n);if(!o)return!1;let r=t.get(o);return!r||pa(r.status)})}function ha(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 bn(e){let t=ha({toolChoice:e.toolChoice,thinkingEnabled:e.thinkingEnabled,compatibility:e.compatibility}),n=t.normalizedToolChoice,o=[...t.warnings],r=ga({tools:e.tools,eligibility:e.eligibility});if(!n||n==="auto")return{tools:r,normalizedToolChoice:n,...r.length>0?{extraSystemPrompt:Ar(r)}:{},warnings:o};if(n==="none")return{tools:[],normalizedToolChoice:"none",warnings:o};if(n==="required"){if(r.length===0)throw new Error("tool_choice=required but no tools were provided");return{tools:r,normalizedToolChoice:"required",extraSystemPrompt:fa(r),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=>Tt(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 ya=["stop","aborted","timeout","cancelled","interrupted","error"],ba=["tool_calls","toolCalls","function_call","functionCall","raw_tool_calls","rawToolCalls"];function Sr(e){return e==null?[]:typeof e=="string"?e.length>0?[{type:"text",text:e}]:[]:Array.isArray(e)?e:[{type:"text",text:String(e)}]}function Ta(e,t){return{...e,content:[...Sr(e.content),...Sr(t.content)]}}function Ca(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 ka(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=Ca(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 Ra(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 xa(e){return new Set((e??ya).map(t=>t.trim().toLowerCase()))}function _a(e,t){return e?xa(t).has(e.trim().toLowerCase()):!1}function Tn(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(y=>Ra(y));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(y=>typeof y.id=="string"&&r.has(y.id));if(p.length===0){let{tool_calls:y,...g}=u;g.content!=null&&g.content!==""&&s.push(g);continue}if(p.length<u.tool_calls.length){s.push({...u,tool_calls:p});continue}}s.push(u)}let i=ka(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]=Ta(p,u);continue}a.push(u)}return a}function Cn(e,t){return _a(t?.stopReason,t?.forcedStopReasons)?e.map(n=>{if(n.role!=="assistant")return{...n};let o={...n};for(let r of ba)delete o[r];return o}):[...e]}function kn(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 Rn(e,t){let n=Tn(e),o=Cn(n,t);return kn(o,t)}function va(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 wa(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 Aa(e){return{round:e.round??0,maxRounds:e.maxRounds,pendingToolCallIds:[...e.pendingToolCallIds??[]],completedToolCallIds:[...e.completedToolCallIds??[]],lastStopReason:e.lastStopReason,replayMessages:[...e.replayMessages??[]]}}function xn(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 Ct(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 kt(e){let t=[],n=Tn(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=Cn(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=kn(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:Aa({maxRounds:e.maxRounds,round:e.round,lastStopReason:e.lastStopReason,replayMessages:r,pendingToolCallIds:va(r),completedToolCallIds:wa(r)}),recoveryActions:t}}var Sa=new Set(["main","sdk","agent","compact","hook","verification","side_question"]);function _n(e){return e?Sa.has(e):!0}function vn(e){return e===429||e===529}function Rt(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 gd={maxBackoffMs:300*1e3,resetCapMs:360*60*1e3,heartbeatIntervalMs:3e4};function xt(){let e=process.env.QLOGICAGENT_PERSISTENT_RETRY;return e==="1"||e==="true"}var Je=class extends Error{constructor(n,o){super(`Model fallback triggered: ${n} -> ${o}`);this.originalModel=n;this.fallbackModel=o;this.name="FallbackTriggeredError"}originalModel;fallbackModel};function wn(e){return{promptTokens:0,hasAttemptedReactiveCompact:!1,currentMaxOutputTokens:e.maxOutputTokens,consecutiveTruncations:0,aborted:e.abortSignal?.aborted??!1}}function An(e,t){if(e.aborted)return{level:"blocking",usagePercent:100,reason:"budget_exhausted"};let n=t.contextWindowTokens-t.responseBufferTokens-e.currentMaxOutputTokens,o=n>0?e.promptTokens/n*100:100;return e.promptTokens>=n?e.hasAttemptedReactiveCompact||!t.reactiveCompactEnabled?{level:"blocking",usagePercent:o,reason:"prompt_too_long"}:{level:"blocking",usagePercent:o,reason:"prompt_too_long"}:o>=85?{level:"warning",usagePercent:o,remainingTokens:n-e.promptTokens}:{level:"ok"}}function Sn(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 Mn(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 En(e,t){return e.aborted?!0:t.abortSignal?.aborted?(e.aborted=!0,!0):!1}var Ea={maxConsecutiveFailures:3,minMessagesAfterCompact:4,targetUsagePercent:50};function In(){return{consecutiveFailures:0,attemptedThisTurn:!1,lastCompactAt:null,toolsAtLastCompact:[]}}function Ue(e,t=Ea){return!(e.attemptedThisTurn||e.consecutiveFailures>=t.maxConsecutiveFailures)}import{createHash as pc}from"node:crypto";import{existsSync as Ne,readFileSync as $t}from"node:fs";function Pn(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,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 Mr(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 Er(e,t){if(!t.ok)return[];let n=t.details;if(!n)return[];let o=Ia(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 Ia(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 Pa=new Set(["write","edit","patch"]);function Ir(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=Oa(r.function.arguments);if(!i)return s;if(Pa.has(n.toolName)){let a=Na(i);a&&s.push({type:"artifact",turnId:t,artifactId:`artifact-${n.callId}`,artifactType:La(a),title:a.split(/[\\/]/).pop()||a,filePath:a,language:Fa(a)})}return s}function Oa(e){try{return JSON.parse(e)}catch{return null}}function Na(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 La(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 Fa(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 Ba=new Set(["write","edit","patch"]),Da=new Set(["image_generate"]),$a=/\b(?:verify|test|check|validate)\b[\s\S]{0,48}\b(?:browser|browser-visible|playwright|visible ui)\b|\b(?:browser|browser-visible|playwright|visible ui)\b[\s\S]{0,48}\b(?:verify|test|check|validate)\b/i,Ua=/\b(?:build|create|make|develop|implement|scaffold|generate)\b[\s\S]{0,80}\b(?:app|application|web ?app|website|site|dashboard|frontend|react|vite|vue|next|svelte|game)\b|\b(?:vite|react|vue|next\.js|frontend|browser-visible)\b|(?:构建|创建|开发|实现|生成|搭建)[\s\S]{0,24}(?:应用|网站|网页|前端|页面|项目|游戏|看板|仪表盘|app)/i;var ja=/\b(?:under|inside|in|at|to|root|directory|folder|output directory|output folder)\s+([A-Za-z]:[\\/][^\s"'`<>|]+)|(?:目录|文件夹|根目录|输出到|放到|位于)\s*([A-Za-z]:[\\/][^\s"'`<>|]+)/gi,On=/https?:\/\/[^\s"'`<>),;]+/gi,qa=/\b(?:fatal|timeout|timed out|waitforselector|waiting for locator|strict mode violation|exception|traceback|eaddrinuse|page crashed|browser closed|target closed)\b|鏃犳硶灏唡閿欒|澶辫触|瓒呮椂/i,za=/\b(?:default vite|vite \+ react|edit src\/app|click on the vite|vite page)\b|默认\s*Vite/i,Pr=/\b(?:browser|playwright|puppeteer|screenshot|opened|loaded|navigated|visible|locator|page\.goto|http:\/\/127\.0\.0\.1|http:\/\/localhost)\b|(?:浏览器|截图|页面可见|打开页面|加载页面|内置浏览器|自动化)/i;function Ha(e){let t=jn(e);return{artifactRoot:t,rootSource:t?"explicit":void 0,writePaths:[],outOfRootWrites:[],devServerUrls:[],browserVerified:!1,browserEvidence:[],browserFailureEvidence:[],buildVerified:!1,buildEvidence:[],buildFailureEvidence:[]}}function ae(e){return e.some(t=>t.role==="user"&&typeof t.content=="string"&&(Ua.test(t.content)||$a.test(t.content)))}var Ga=new RegExp(["\\b(?:tests?|test suite|unit tests?|the suite|build|compiles?|compilation|typecheck|lint)\\b[\\s\\S]{0,24}\\b(?:pass(?:es|ing)?|green|succeed(?:s|ed)?|clean|work(?:s|ing)?)\\b","\\b(?:pass(?:es|ing)?|green|succeed(?:s|ed)?)\\b[\\s\\S]{0,16}\\b(?:tests?|the suite|build)\\b","\\bfix(?:es|ing)?\\b[\\s\\S]{0,24}\\b(?:failing|broken)\\b[\\s\\S]{0,12}\\b(?:tests?|build|spec)\\b","\\bmake it (?:build|compile|pass)\\b","\\b(?:run|rerun|re-run) (?:the )?(?:tests?|test suite|build|spec)\\b","\\b(?:npm (?:test|run build)|pnpm (?:test|build)|yarn (?:test|build)|pytest|go test|cargo (?:test|build)|vitest|jest|gradle|mvn)\\b","(?:\u8BA9|\u4F7F|\u786E\u4FDD)[\\s\\S]{0,12}(?:\u6D4B\u8BD5|\u5355\u6D4B|\u7528\u4F8B|\u6784\u5EFA|\u7F16\u8BD1)[\\s\\S]{0,8}(?:\u901A\u8FC7|\u8DD1\u901A|\u6210\u529F|\u7EFF)","(?:\u4FEE\u590D|\u4FEE\u597D|\u89E3\u51B3)[\\s\\S]{0,12}(?:\u5931\u8D25\u7684?\u6D4B\u8BD5|\u6D4B\u8BD5\u5931\u8D25|\u7F16\u8BD1\u9519\u8BEF|\u6784\u5EFA\u9519\u8BEF|\u7F16\u8BD1\u62A5\u9519|\u62A5\u9519)","\u6D4B\u8BD5\u901A\u8FC7|\u8DD1\u901A\u6D4B\u8BD5|\u7F16\u8BD1\u901A\u8FC7|\u6784\u5EFA\u901A\u8FC7|\u901A\u8FC7(?:\u5168\u90E8|\u6240\u6709)?\u6D4B\u8BD5|\u8BA9\u6D4B\u8BD5\u53D8\u7EFF"].join("|"),"i");function Fn(e){return e.some(t=>t.role==="user"&&typeof t.content=="string"&&Ga.test(t.content))}function Wa(e){return e.some(t=>{if(t.role!=="user"||typeof t.content!="string")return!1;let n=t.content.toLowerCase(),o=/\b(?:app|application|web ?app|website|site|dashboard|frontend|react|vite|vue|next|svelte|game)\b/.test(n)||/(?:应用|网站|网页|前端|页面|项目|游戏|看板|仪表盘|app)/.test(t.content),r=/\b(?:research|market|analysis|analyze|recommendation|strategy|sourced|citations?|report|brief|memo|study|whitepaper)\b/.test(n)||/(?:研究|报告|分析|评估|建议|策略|引用|来源|事实|调研|备忘录)/.test(t.content);if(o&&!r)return!1;let s=t.content.replace(/[A-Za-z]:[\\/][^\s"'`<>|]+/g," ").replace(/\b[A-Za-z0-9._-]*review\.(?:md|txt|docx|pdf)\b/gi," ").toLowerCase();return/\b(?:research|market|analysis|analyze|recommendation|strategy|sourced|citations?|report|brief|memo|study|whitepaper)\b/.test(s)?!0:/(?:研究|分析|审计|评估|建议|策略|引用|来源|事实)/.test(s)})}function Va(e){return e.some(t=>{if(t.role!=="user"||typeof t.content!="string")return!1;let n=t.content.toLowerCase();return/\b(?:final status|status contract|acceptance report|audit trail|done\/not done|done-notdone|not done|artifacts?|verification|blockers?|next action|benchmark-state|long-horizon benchmark)\b/.test(n)})}function Or(e){return["Done","Not done","Artifacts","Verification","Blockers","Next action"].every(t=>new RegExp(`(^|\\n)${t}:`,"i").test(e))}function Fr(e){return["Sourced facts","Assumptions","Recommendations","Unsupported claims"].every(t=>new RegExp(`(^|\\n)${t}:`,"i").test(e))}function Bn(e,t){let n=Hr(t);return n?Ba.has(e)?Nr(n.path,n.file_path,n.filePath,n.filename,n.file):Da.has(e)?Nr(n.output_path,Array.isArray(n.output_paths)?n.output_paths[0]:void 0):null:null}function Br(e){let t=Bn(e.toolName,e.rawArguments);if(!t||!ae(e.inputMessages))return null;if(!e.state.artifactRoot){let r=jn(e.inputMessages);r?(e.state.artifactRoot=r,e.state.rootSource="explicit"):(e.state.artifactRoot=Gr(t),e.state.rootSource=e.state.artifactRoot?"inferred":void 0)}let n=e.state.artifactRoot;if(!n||e.state.rootSource!=="explicit"||Vr(t,n))return null;let o=`Artifact root contract blocked ${e.toolName}: attempted to write ${t}, but this deliverable root is ${n}. Keep generated app/project files inside the declared artifactRoot, or ask for explicit approval before changing scope.`;return{path:t,artifactRoot:n,error:o}}function Dr(e){let t=Bn(e.toolName,e.rawArguments);return!t||!al(t)?null:{path:t,error:`Read-only context-pack blocked ${e.toolName}: attempted to write ${t}. Context packs are source evidence; write document indexes, checkpoints, and maintenance updates under benchmark-state instead.`}}function Dn(e,t){e.writePaths.includes(t.path)||e.writePaths.push(t.path),e.outOfRootWrites.some(n=>n.path===t.path&&n.toolName===t.toolName)||e.outOfRootWrites.push(t)}function $r(e){let t=Bn(e.toolName,e.rawArguments);if(t){if(!e.state.artifactRoot){let o=jn(e.inputMessages);e.state.artifactRoot=o??Gr(t),e.state.rootSource=o?"explicit":e.state.artifactRoot?"inferred":void 0}e.state.writePaths.includes(t)||e.state.writePaths.push(t),ae(e.inputMessages)&&e.state.artifactRoot&&e.state.rootSource==="explicit"&&!Vr(t,e.state.artifactRoot)&&Dn(e.state,{path:t,artifactRoot:e.state.artifactRoot,toolName:e.toolName})}let n=`${e.rawArguments}
2
- ${e.content}`;for(let o of n.matchAll(On)){let r=Ln(o[0]);r&&(e.state.devServerUrls.includes(r)||e.state.devServerUrls.push(r))}if(tl(e.toolName,e.rawArguments,e.content)&&Wr(e.content)){e.state.browserVerified=!1;let o=e.content.trim().slice(0,500);o&&!e.state.browserFailureEvidence.includes(o)&&e.state.browserFailureEvidence.push(o)}if(e.ok&&e.state.browserFailureEvidence.length===0&&el(e.toolName,e.rawArguments,e.content)){e.state.browserVerified=!0;let o=e.content.trim().slice(0,500);o&&!e.state.browserEvidence.includes(o)&&e.state.browserEvidence.push(o)}if(rl(e.toolName,e.rawArguments))if(!e.ok||sl(e.content)){e.state.buildVerified=!1;let r=e.content.trim().slice(0,500);r&&!e.state.buildFailureEvidence.includes(r)&&e.state.buildFailureEvidence.push(r)}else{e.state.buildVerified=!0,e.state.buildFailureEvidence=[];let r=e.content.trim().slice(0,300);r&&!e.state.buildEvidence.includes(r)&&e.state.buildEvidence.push(r)}}function $n(e,t){return{artifactRoot:e.artifactRoot,writePaths:[...e.writePaths],outOfRootWrites:[...e.outOfRootWrites],devServerUrls:[...e.devServerUrls],browserVerified:e.browserVerified,browserEvidence:[...e.browserEvidence],browserFailureEvidence:[...e.browserFailureEvidence],requiresBrowserAcceptance:ae(t)}}function Ur(e){let t=Ha(e);for(let n of e)n.role!=="assistant"||typeof n.content!="string"||Un(t,n.content);return t}function Un(e,t){let n=t.match(/(?:^|\n)\s*-\s*artifactRoot:\s*([^\n]+)/i)?.[1]?.trim();n&&!/not declared/i.test(n)&&!e.artifactRoot&&(e.artifactRoot=Te(n),e.rootSource="inferred");let o=t.match(/(?:artifact path|artifact root|project root)\s*\n+```[a-zA-Z0-9_-]*\n?([^`\n]+)\n?```/i)?.[1]?.trim();o&&!e.artifactRoot&&(e.artifactRoot=Te(o),e.rootSource="inferred");let r=t.match(/(?:^|\n)\s*-\s*files:\s*([^\n]+)/i)?.[1]?.trim();if(r&&!/no write paths recorded/i.test(r))for(let i of r.split(/\s*,\s*/)){let a=Te(i.trim());a&&!e.writePaths.includes(a)&&e.writePaths.push(a)}let s=t.match(/(?:^|\n)\s*-\s*urls:\s*([^\n]+)/i)?.[1]?.trim();if(s&&!/none recorded/i.test(s))for(let i of s.matchAll(On)){let a=Ln(i[0]);a&&!e.devServerUrls.includes(a)&&e.devServerUrls.push(a)}for(let i of t.matchAll(On)){let a=Ln(i[0]);a&&/^https?:\/\/(?:localhost|127\.0\.0\.1):\d+\//i.test(a)&&(e.devServerUrls.includes(a)||e.devServerUrls.push(a))}}function jr(e){let t=e.content.trim(),n=ae(e.inputMessages),o=Wa(e.inputMessages),r=Fn(e.inputMessages),s=Va(e.inputMessages),i=ll(t),a=t,u=qr(e.activeTasks??[]);if(u.length>0&&(a=Ya(a)),n&&!e.artifactContract.browserVerified&&(a=Za(a)),r&&!e.artifactContract.buildVerified&&(a=Ja(a)),!(i&&e.totalToolCallCount===0)&&o&&!Fr(a)){let k=Qa(a);a=a?`${a}
1
+ function fn(e,t,n,o){return{role:"assistant",content:t||null,tool_calls:e,...n&&n.length>0?{thinkingBlocks:n}:{},...o?{reasoning_content:o}:{}}}function X(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 Ii=/\b(?:daily|weekly|monthly)(?:\/(?:daily|weekly|monthly))* (?:usage )?limit(?:s)?(?: (?:exhausted|reached|exceeded))?\b/i,ve={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]},Pi=/^(?:error[:\s-]+)?billing(?:\s+error)?(?:[:\s-]+|$)|^(?:error[:\s-]+)?(?:credit balance|insufficient credits?|payment required|http\s*402\b)/i,Oi=/["']?(?:status|code)["']?\s*[:=]\s*402\b|\bhttp\s*402\b|\berror(?:\s+code)?\s*[:=]?\s*402\b|^\s*402\s+payment/i,Ni=512,Li=/^(?:http\s*)?(\d{3})(?:\s+([\s\S]+))?$/i;var Fi=new Set([500,502,503,504,521,522,523,524,529]),Bi=["insufficient credits","insufficient quota","credit balance","insufficient balance","plans & billing","add more credits","top up"],Di=["upgrade your plan","upgrade plan","current plan","subscription"],$i=["daily","weekly","monthly"],Ui=["try again","retry","temporary","cooldown"],ji=["usage limit","rate limit","organization usage"],qi=["organization","workspace"],zi=["billing period","exceeded","reached","exhausted"],Hi=/["']?(?: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,Gi=/^(?:error[:\s-]+)?(?:(?:http\s*)?402(?:\s+payment required)?|payment required)(?:[:\s-]+|$)/i;function Ae(e,t){if(!e)return!1;let n=e.toLowerCase();return t.some(o=>o instanceof RegExp?o.test(n):n.includes(o))}function Wi(e){return Ae(e,ve.format)}function Jo(e){return Ae(e,ve.rateLimit)}function Vi(e){return Ae(e,ve.timeout)}function Xi(e){return Ii.test(e)}function pn(e){let t=e.toLowerCase();return t?e.length>Ni?Oi.test(t):Ae(t,ve.billing)?!0:Pi.test(e)?t.includes("upgrade")||t.includes("credits")||t.includes("payment")||t.includes("plan"):!1:!1}function Qo(e){return Ae(e,ve.authPermanent)}function Ki(e){return Ae(e,ve.auth)}function er(e){return Ae(e,ve.overloaded)}function _e(e,t){return t.some(n=>e.includes(n))}function Yi(e){return _e(e,Bi)||_e(e,Di)&&e.includes("limit")||e.includes("billing hard limit")||e.includes("hard limit reached")||e.includes("maximum allowed")&&e.includes("limit")}function Zi(e){let t=_e(e,$i),n=e.includes("spend limit")||e.includes("spending limit"),o=_e(e,qi);return _e(e,Ui)&&_e(e,ji)||t&&(e.includes("usage limit")||n)||t&&e.includes("limit")&&e.includes("reset")||o&&e.includes("limit")&&(n||_e(e,zi))}function Ji(e){return e.trim().toLowerCase().replace(Gi,"").trim()}function tr(e){let t=Ji(e);return!t||Yi(t)?"billing":Jo(t)||Zi(t)?"rate_limit":"billing"}function Qi(e){return Hi.test(e)?tr(e):null}function nr(e){let t=e.match(Li);if(!t)return null;let n=Number(t[1]);return Number.isFinite(n)?{code:n,rest:(t[2]??"").trim()}:null}function ea(e){if(!e)return!1;let t=e.toLowerCase();return t.includes('"type":"api_error"')&&t.includes("internal server error")}function ta(e){let t=e.trim();if(!t)return!1;let n=nr(t);return n?Fi.has(n.code):!1}function or(e,t){return typeof e!="number"||!Number.isFinite(e)?null:e===402?t?tr(t):"billing":e===429?"rate_limit":e===401||e===403?t&&Qo(t)?"auth_permanent":"auth":e===408?"timeout":e===503?t&&er(t)?"overloaded":"timeout":e===502||e===504?"timeout":e===529?"overloaded":e===400?t&&pn(t)?"billing":"format":null}function na(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 oa(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 rr(e){if(oa(e))return"session_expired";if(na(e))return"model_not_found";let t=Qi(e);return t||(Xi(e)?pn(e)?"billing":"rate_limit":Jo(e)?"rate_limit":er(e)?"overloaded":ta(e)?nr(e.trim())?.code===529?"overloaded":"timeout":ea(e)?"timeout":Wi(e)?"format":pn(e)?"billing":Vi(e)?"timeout":Qo(e)?"auth_permanent":Ki(e)?"auth":null)}var ra={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"},sa=new Set(["RETRYABLE_TRANSIENT","RETRYABLE_DEGRADED","TOOL_EXECUTION_FAILED"]);function De(e,t){let n=or(e,t)??(t?rr(t):null);return n?ra[n]:typeof e=="number"&&e>=400&&e<500?"NON_RETRYABLE_CONTENT":"RETRYABLE_TRANSIENT"}function mn(e){return sa.has(e)}function sr(e){let t=typeof e.content=="string"?e.content:e.content!=null?JSON.stringify(e.content):"";return Math.ceil(t.length/4)}var ia=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"]),Je=class{constructor(t=20,n=sr){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,c)=>{if(c>=o||a.role!=="tool"||typeof a.content!="string"||!a.name||!ia.has(a.name)||a.content.length<=200)return a;let f=this.estimateTokens(a);return s+=f,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 gn(e,t,n=sr){if(t.size===0)return{messages:e,tokensFreed:0,removedCount:0};let o=0,r=0,s=[];for(let a of e){let c=a.tool_call_id??"";if(c&&t.has(c)){o+=n(a),r++,t.delete(c);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 hn(){return{stages:[]}}function yn(e,t,n){let o=n?.thresholdMessages??40;if(e.filter(a=>a.role!=="system").length<=o)return{messages:e,stagedCount:0};let s=ir(e,t),i=aa(s,t,o);if(i.length===0)return{messages:s,stagedCount:0};for(let a of i)t.stages.push(a);return s=ir(e,t),{messages:s,stagedCount:i.length}}function bn(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:ar(e,t),committed:n}}function ir(e,t){return t.stages.filter(o=>o.committed).length===0?e:ar(e,t)}function ar(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),c={role:"system",content:r.summary};o.splice(s,a-s,c)}return o}function aa(e,t,n){let o=Math.max(0,e.length-Math.floor(n/2)),r=[],s=new Set(t.stages.map(c=>`${c.range[0]}-${c.range[1]}`)),i=-1,a=0;for(let c=0;c<o;c++){let f=e[c];if(f.role==="tool"||f.role==="assistant"&&typeof f.content=="string"&&f.content==="")i<0&&(i=c),a++;else{if(a>=3){let y=`${i}-${i+a}`;s.has(y)||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 c=`${i}-${i+a}`;s.has(c)||r.push({id:`collapse_${i}_${i+a}`,range:[i,i+a],summary:`[${a} tool results collapsed]`,committed:!1})}return r}import{readFileSync as la,writeFileSync as ca,mkdirSync as ua}from"node:fs";import{join as da,dirname as fa}from"node:path";var be=Math.min(Math.max(1,Number(process.env.TOOL_LOOP_DEFAULT_BUDGET)||25),100),lr=Math.max(1e3,Number(process.env.TOOL_LOOP_TOOL_TIMEOUT_MS)||24e4),cr=3,ur=2,Ct=2,dr=128e3,fr=13e3,pr=16384,mr=65536,gr=3,hr=65536,Tn=500,yr=3;var br=3e4,Tr=3,we=2;var Cr=3,kr=2,Rr=300*1e3,xr=3,_r=720*60*60*1e3;var ed=3600*1e3;var td=50*1024,nd=500*1024,od=500*1024*1024,rd=50*1024*1024;var sd=60*1024;var Ar=0;var pa="skill-patterns.json";function wr(e){return da(e,".qlogicagent",pa)}function ma(e){let t=wr(e);try{return JSON.parse(la(t,"utf8"))}catch{return{version:1,patterns:{}}}}function vr(e,t){let n=wr(e);ua(fa(n),{recursive:!0}),ca(n,JSON.stringify(t,null,2),"utf8")}function ga(e){let t=Date.now()-_r;for(let[n,o]of Object.entries(e.patterns))new Date(o.lastSeen).getTime()<t&&delete e.patterns[n]}function Sr(e,t){if(t.length===0)return!1;let n=Mr(t),o=ma(e);ga(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 vr(e,o),!1;s.count++,s.lastSeen=r;let i=s.count>=xr;return i&&(s.promoted=!0),vr(e,o),i}function Mr(e){return[...e].sort().join("+")}function ha(e,t){return!(!e.ok||e.existingSkillName||!e.multiStep||e.toolCallCount<Cr||e.distinctToolCount<kr||Date.now()-Ar<Rr||t?.projectRoot&&t.tools.length>0&&!Sr(t.projectRoot,t.tools))}function ya(e){return e.existingSkillName?e.feedback==="negative":!1}function Cn(e,t){return ya(e)?{type:"skill.improve",skillName:e.existingSkillName,reason:"negative user feedback on existing skill execution"}:ha(e,t)?(Ar=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 ba(e){return[...new Set(e.map(kt).filter(Boolean))].sort((t,n)=>t.localeCompare(n))}function Er(e){let t=ba(e);return t.length===0?"":`Available tools for this round: ${t.join(", ")}. Do not mention, invent, or attempt any tool that is not in this list.`}function Ta(e){let t=[...new Set(e.map(kt).filter(Boolean))].sort((i,a)=>i.localeCompare(a)),n=new Set(t),o=Er(e),r=n.has("exec"),s=["read","search","write","edit","patch"].some(i=>n.has(i));return!r||!s?"You must call one of the available tools before responding. "+o:"You must call one of the available tools before responding. "+o+' Tool selection is part of correctness. Use read/search/write/edit/patch for file paths and file maintenance. For search, always include `mode` and `pattern`; examples: {"mode":"filename","pattern":"**/*.md"} or {"mode":"content","pattern":"TODO","fileGlob":"*.ts"}. Use exec only for shell commands with the required `command` field; never pass `path`, `filePath`, or file content to exec.'}function kt(e){return e.function&&typeof e.function=="object"&&typeof e.function.name=="string"?e.function.name.trim():typeof e.name=="string"?e.name.trim():""}function Ca(e){return e==="enabled-eligible"||e==="installed-awaiting-approval"}function ka(e){return new Map((e??[]).map(t=>[t.toolName,t]))}function Ra(e){if(!e.eligibility?.length)return[...e.tools];let t=ka(e.eligibility);return e.tools.filter(n=>{let o=kt(n);if(!o)return!1;let r=t.get(o);return!r||Ca(r.status)})}function xa(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 kn(e){let t=xa({toolChoice:e.toolChoice,thinkingEnabled:e.thinkingEnabled,compatibility:e.compatibility}),n=t.normalizedToolChoice,o=[...t.warnings],r=Ra({tools:e.tools,eligibility:e.eligibility});if(!n||n==="auto")return{tools:r,normalizedToolChoice:n,...r.length>0?{extraSystemPrompt:Er(r)}:{},warnings:o};if(n==="none")return{tools:[],normalizedToolChoice:"none",warnings:o};if(n==="required"){if(r.length===0)throw new Error("tool_choice=required but no tools were provided");return{tools:r,normalizedToolChoice:"required",extraSystemPrompt:Ta(r),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(c=>kt(c)===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 _a=["stop","aborted","timeout","cancelled","interrupted","error"],va=["tool_calls","toolCalls","function_call","functionCall","raw_tool_calls","rawToolCalls"];function Ir(e){return e==null?[]:typeof e=="string"?e.length>0?[{type:"text",text:e}]:[]:Array.isArray(e)?e:[{type:"text",text:String(e)}]}function Aa(e,t){return{...e,content:[...Ir(e.content),...Ir(t.content)]}}function wa(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 Sa(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=wa(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 Ma(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 Ea(e){return new Set((e??_a).map(t=>t.trim().toLowerCase()))}function Ia(e,t){return e?Ea(t).has(e.trim().toLowerCase()):!1}function Rn(e){if(!Array.isArray(e)||e.length===0)return[...e];let t=e.map(c=>{if(c.role==="assistant"&&Array.isArray(c.tool_calls)){let f=c.tool_calls.filter(h=>Ma(h));return{...c,...f.length>0?{tool_calls:f}:{tool_calls:void 0}}}return{...c}}),n=new Set;for(let c of t)if(!(c.role!=="assistant"||!Array.isArray(c.tool_calls)))for(let f of c.tool_calls)typeof f.id=="string"&&f.id&&n.add(f.id);let o=t.filter(c=>c.role!=="tool"?!0:!!(c.tool_call_id&&n.has(c.tool_call_id))),r=new Set;for(let c of o)c.role==="tool"&&typeof c.tool_call_id=="string"&&c.tool_call_id&&r.add(c.tool_call_id);let s=[];for(let c of o){if(c.role==="assistant"&&Array.isArray(c.tool_calls)&&c.tool_calls.length>0){let f=c.tool_calls.filter(h=>typeof h.id=="string"&&r.has(h.id));if(f.length===0){let{tool_calls:h,...y}=c;y.content!=null&&y.content!==""&&s.push(y);continue}if(f.length<c.tool_calls.length){s.push({...c,tool_calls:f});continue}}s.push(c)}let i=Sa(s),a=[];for(let c of i){let f=a.length>0?a[a.length-1]:void 0;if(c.role==="user"&&f?.role==="user"){a[a.length-1]=Aa(f,c);continue}a.push(c)}return a}function xn(e,t){return Ia(t?.stopReason,t?.forcedStopReasons)?e.map(n=>{if(n.role!=="assistant")return{...n};let o={...n};for(let r of va)delete o[r];return o}):[...e]}function _n(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 vn(e,t){let n=Rn(e),o=xn(n,t);return _n(o,t)}function Pa(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 Oa(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 Na(e){return{round:e.round??0,maxRounds:e.maxRounds,pendingToolCallIds:[...e.pendingToolCallIds??[]],completedToolCallIds:[...e.completedToolCallIds??[]],lastStopReason:e.lastStopReason,replayMessages:[...e.replayMessages??[]]}}function An(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 Rt(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 xt(e){let t=[],n=Rn(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=xn(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=_n(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:Na({maxRounds:e.maxRounds,round:e.round,lastStopReason:e.lastStopReason,replayMessages:r,pendingToolCallIds:Pa(r),completedToolCallIds:Oa(r)}),recoveryActions:t}}var La=new Set(["main","sdk","agent","compact","hook","verification","side_question"]);function wn(e){return e?La.has(e):!0}function Sn(e){return e===429||e===529}function _t(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 bd={maxBackoffMs:300*1e3,resetCapMs:360*60*1e3,heartbeatIntervalMs:3e4};function vt(){let e=process.env.QLOGICAGENT_PERSISTENT_RETRY;return e==="1"||e==="true"}var Qe=class extends Error{constructor(n,o){super(`Model fallback triggered: ${n} -> ${o}`);this.originalModel=n;this.fallbackModel=o;this.name="FallbackTriggeredError"}originalModel;fallbackModel};function Mn(e){return{promptTokens:0,hasAttemptedReactiveCompact:!1,currentMaxOutputTokens:e.maxOutputTokens,consecutiveTruncations:0,aborted:e.abortSignal?.aborted??!1}}function En(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 In(e,t,n){let o=e.message?.toLowerCase()??"",r=e.status??0;return r===413||o.includes("prompt_too_long")||o.includes("context_length_exceeded")?!t.hasAttemptedReactiveCompact&&n.reactiveCompactEnabled?{action:"reactive_compact"}:{action:"abort",reason:"prompt_too_long_unrecoverable"}:r>=500&&r<600?{action:"retry",reason:`server_error_${r}`}:r===429?{action:"retry",reason:"rate_limited"}:r===401||r===403?{action:"abort",reason:"auth_error"}:r===404?{action:"abort",reason:"model_not_found"}:{action:"abort",reason:o||"unknown_error"}}function Pn(e,t,n){if(!t.outputEscalationEnabled)return{shouldEscalate:!1,newMax:e.currentMaxOutputTokens};if(e.consecutiveTruncations>=3)return{shouldEscalate:!1,newMax:e.currentMaxOutputTokens};let o=Math.min(e.currentMaxOutputTokens*2,n);return o<=e.currentMaxOutputTokens?{shouldEscalate:!1,newMax:e.currentMaxOutputTokens}:{shouldEscalate:!0,newMax:o}}function On(e,t){return e.aborted?!0:t.abortSignal?.aborted?(e.aborted=!0,!0):!1}var Ba={maxConsecutiveFailures:3,minMessagesAfterCompact:4,targetUsagePercent:50};function Nn(){return{consecutiveFailures:0,attemptedThisTurn:!1,lastCompactAt:null,toolsAtLastCompact:[]}}function $e(e,t=Ba){return!(e.attemptedThisTurn||e.consecutiveFailures>=t.maxConsecutiveFailures)}import{createHash as hc}from"node:crypto";import{existsSync as Ne,readFileSync as jt}from"node:fs";function Ln(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,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 Pr(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 Or(e,t){if(!t.ok)return[];let n=t.details;if(!n)return[];let o=Da(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 Da(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 $a=new Set(["write","edit","patch"]);function Nr(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=Ua(r.function.arguments);if(!i)return s;if($a.has(n.toolName)){let a=ja(i);a&&s.push({type:"artifact",turnId:t,artifactId:`artifact-${n.callId}`,artifactType:qa(a),title:a.split(/[\\/]/).pop()||a,filePath:a,language:za(a)})}return s}function Ua(e){try{return JSON.parse(e)}catch{return null}}function ja(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 qa(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 za(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 $r=new Set(["write","edit","patch"]),Ur=new Set(["image_generate"]),Ha=/\b(?:verify|test|check|validate)\b[\s\S]{0,48}\b(?:browser|browser-visible|playwright|visible ui)\b|\b(?:browser|browser-visible|playwright|visible ui)\b[\s\S]{0,48}\b(?:verify|test|check|validate)\b/i,Ga=/\b(?:build|create|make|develop|implement|scaffold|generate)\b[\s\S]{0,80}\b(?:app|application|web ?app|website|site|dashboard|frontend|react|vite|vue|next|svelte|game)\b|\b(?:vite|react|vue|next\.js|frontend|browser-visible)\b|(?:构建|创建|开发|实现|生成|搭建)[\s\S]{0,24}(?:应用|网站|网页|前端|页面|项目|游戏|看板|仪表盘|app)/i,Wa=/\b(?:under|inside|in|at|to|root|directory|folder|output directory|output folder)\s+([A-Za-z]:[\\/][^\s"'`<>|]+)|(?:目录|文件夹|根目录|输出到|放到|位于)\s*([A-Za-z]:[\\/][^\s"'`<>|]+)/gi,Bn=/https?:\/\/[^\s"'`<>),;]+/gi,Va=/\b(?:fatal|timeout|timed out|waitforselector|waiting for locator|strict mode violation|exception|traceback|eaddrinuse|page crashed|browser closed|target closed)\b|无法访问|错误|失败|超时/i,Xa=/\b(?:default vite|vite \+ react|edit src\/app|click on the vite|vite page)\b|默认\s*Vite/i,Lr=/\b(?:browser|playwright|puppeteer|screenshot|opened|loaded|navigated|visible|locator|page\.goto|http:\/\/127\.0\.0\.1|http:\/\/localhost)\b|(?:浏览器|截图|页面可见|打开页面|加载页面|内置浏览器|自动化)/i;function Ka(e){let t=qn(e);return{artifactRoot:t,rootSource:t?"explicit":void 0,writePaths:[],outOfRootWrites:[],devServerUrls:[],browserVerified:!1,browserEvidence:[],browserFailureEvidence:[],buildVerified:!1,buildEvidence:[],buildFailureEvidence:[]}}function de(e){return e.some(t=>t.role==="user"&&typeof t.content=="string"&&(Ga.test(t.content)||Ha.test(t.content)))}var Ya=new RegExp(["\\b(?:tests?|test suite|unit tests?|the suite|build|compiles?|compilation|typecheck|lint)\\b[\\s\\S]{0,24}\\b(?:pass(?:es|ing)?|green|succeed(?:s|ed)?|clean|work(?:s|ing)?)\\b","\\b(?:pass(?:es|ing)?|green|succeed(?:s|ed)?)\\b[\\s\\S]{0,16}\\b(?:tests?|the suite|build)\\b","\\bfix(?:es|ing)?\\b[\\s\\S]{0,24}\\b(?:failing|broken)\\b[\\s\\S]{0,12}\\b(?:tests?|build|spec)\\b","\\bmake it (?:build|compile|pass)\\b","\\b(?:run|rerun|re-run) (?:the )?(?:tests?|test suite|build|spec)\\b","\\b(?:npm (?:test|run build)|pnpm (?:test|build)|yarn (?:test|build)|pytest|go test|cargo (?:test|build)|vitest|jest|gradle|mvn)\\b","(?:\u8BA9|\u4F7F|\u786E\u4FDD)[\\s\\S]{0,12}(?:\u6D4B\u8BD5|\u5355\u6D4B|\u7528\u4F8B|\u6784\u5EFA|\u7F16\u8BD1)[\\s\\S]{0,8}(?:\u901A\u8FC7|\u8DD1\u901A|\u6210\u529F|\u7EFF)","(?:\u4FEE\u590D|\u4FEE\u597D|\u89E3\u51B3)[\\s\\S]{0,12}(?:\u5931\u8D25\u7684?\u6D4B\u8BD5|\u6D4B\u8BD5\u5931\u8D25|\u7F16\u8BD1\u9519\u8BEF|\u6784\u5EFA\u9519\u8BEF|\u7F16\u8BD1\u62A5\u9519|\u62A5\u9519)","\u6D4B\u8BD5\u901A\u8FC7|\u8DD1\u901A\u6D4B\u8BD5|\u7F16\u8BD1\u901A\u8FC7|\u6784\u5EFA\u901A\u8FC7|\u901A\u8FC7(?:\u5168\u90E8|\u6240\u6709)?\u6D4B\u8BD5|\u8BA9\u6D4B\u8BD5\u53D8\u7EFF"].join("|"),"i");function jr(e){return e.some(t=>t.role==="user"&&typeof t.content=="string"&&Ya.test(t.content))}var Fn=/```final-status[ \t]*\r?\n([\s\S]*?)\r?\n[ \t]*```/g,Za=new Set([...$r,...Ur,"exec","bash","shell","powershell","terminal","playwright","browser","computer"]);function qr(e){for(let t of e)if(Za.has(t))return!0;return!1}var zr=["## Final status block","When this turn produced artifacts (files written, apps served), asserted verification (browser/build/tests), left requested work incomplete or blocked, or the user explicitly asked for a final status or an evidence audit, end your final message with exactly one fenced block:","","```final-status",'{"schema":1,"done":["\u2026"],"notDone":["\u2026"],"artifacts":{"root":"\u2026","files":["\u2026"],"urls":["\u2026"]},"verification":{"browser":"verified|failed|not-run","build":"passed|failed|not-run"},"sources":{"cited":["https://\u2026"]},"blockers":["\u2026"],"nextAction":"\u2026"}',"```","","Every field must reflect actual tool activity from this turn; the engine cross-checks the block against its own tool records and strips unsupported claims. Omit fields that do not apply. Omit the whole block for ordinary conversation."].join(`
2
+ `);function Hr(e){Fn.lastIndex=0;let t=null;for(let o=Fn.exec(e);o;o=Fn.exec(e))t=o;if(!t)return null;let n={start:t.index,end:t.index+t[0].length};try{let o=JSON.parse(t[1]);if(!o||typeof o!="object"||Array.isArray(o))return{claim:null,...n};let r=o;return r.schema!==1?{claim:null,...n}:{claim:r,...n}}catch{return{claim:null,...n}}}function Fr(e){return"```final-status\n"+JSON.stringify(e,null,2)+"\n```"}function Dn(e,t){let n=Jr(t);return n?$r.has(e)?Br(n.path,n.file_path,n.filePath,n.filename,n.file):Ur.has(e)?Br(n.output_path,Array.isArray(n.output_paths)?n.output_paths[0]:void 0):null:null}function Gr(e){let t=Dn(e.toolName,e.rawArguments);if(!t||!de(e.inputMessages))return null;if(!e.state.artifactRoot){let r=qn(e.inputMessages);r?(e.state.artifactRoot=r,e.state.rootSource="explicit"):(e.state.artifactRoot=Qr(t),e.state.rootSource=e.state.artifactRoot?"inferred":void 0)}let n=e.state.artifactRoot;if(!n||e.state.rootSource!=="explicit"||ts(t,n))return null;let o=`Artifact root contract blocked ${e.toolName}: attempted to write ${t}, but this deliverable root is ${n}. Keep generated app/project files inside the declared artifactRoot, or ask for explicit approval before changing scope.`;return{path:t,artifactRoot:n,error:o}}function Wr(e){let t=Dn(e.toolName,e.rawArguments);return!t||!ul(t)?null:{path:t,error:`Read-only context-pack blocked ${e.toolName}: attempted to write ${t}. Context packs are source evidence; write document indexes, checkpoints, and maintenance updates under benchmark-state instead.`}}function $n(e,t){e.writePaths.includes(t.path)||e.writePaths.push(t.path),e.outOfRootWrites.some(n=>n.path===t.path&&n.toolName===t.toolName)||e.outOfRootWrites.push(t)}function Vr(e){let t=Dn(e.toolName,e.rawArguments);if(t){if(!e.state.artifactRoot){let o=qn(e.inputMessages);e.state.artifactRoot=o??Qr(t),e.state.rootSource=o?"explicit":e.state.artifactRoot?"inferred":void 0}e.state.writePaths.includes(t)||e.state.writePaths.push(t),de(e.inputMessages)&&e.state.artifactRoot&&e.state.rootSource==="explicit"&&!ts(t,e.state.artifactRoot)&&$n(e.state,{path:t,artifactRoot:e.state.artifactRoot,toolName:e.toolName})}let n=`${e.rawArguments}
3
+ ${e.content}`;for(let o of n.matchAll(Bn)){let r=et(o[0]);r&&(e.state.devServerUrls.includes(r)||e.state.devServerUrls.push(r))}if(rl(e.toolName,e.rawArguments,e.content)&&es(e.content)){e.state.browserVerified=!1;let o=e.content.trim().slice(0,500);o&&!e.state.browserFailureEvidence.includes(o)&&e.state.browserFailureEvidence.push(o)}if(e.ok&&e.state.browserFailureEvidence.length===0&&ol(e.toolName,e.rawArguments,e.content)){e.state.browserVerified=!0;let o=e.content.trim().slice(0,500);o&&!e.state.browserEvidence.includes(o)&&e.state.browserEvidence.push(o)}if(al(e.toolName,e.rawArguments))if(!e.ok||ll(e.content)){e.state.buildVerified=!1;let r=e.content.trim().slice(0,500);r&&!e.state.buildFailureEvidence.includes(r)&&e.state.buildFailureEvidence.push(r)}else{e.state.buildVerified=!0,e.state.buildFailureEvidence=[];let r=e.content.trim().slice(0,300);r&&!e.state.buildEvidence.includes(r)&&e.state.buildEvidence.push(r)}}function Un(e,t){return{artifactRoot:e.artifactRoot,writePaths:[...e.writePaths],outOfRootWrites:[...e.outOfRootWrites],devServerUrls:[...e.devServerUrls],browserVerified:e.browserVerified,browserEvidence:[...e.browserEvidence],browserFailureEvidence:[...e.browserFailureEvidence],requiresBrowserAcceptance:de(t)}}function Xr(e){let t=Ka(e);for(let n of e)n.role!=="assistant"||typeof n.content!="string"||jn(t,n.content);return t.recoveredBaseline={writePaths:t.writePaths.length,devServerUrls:t.devServerUrls.length,artifactRoot:!!t.artifactRoot},t}function jn(e,t){let n=Hr(t)?.claim?.artifacts;if(n){typeof n.root=="string"&&n.root&&!e.artifactRoot&&(e.artifactRoot=Se(n.root),e.rootSource="inferred");for(let o of n.files??[]){if(typeof o!="string")continue;let r=Se(o.trim());r&&!e.writePaths.includes(r)&&e.writePaths.push(r)}for(let o of n.urls??[]){if(typeof o!="string")continue;let r=et(o);r&&!e.devServerUrls.includes(r)&&e.devServerUrls.push(r)}}for(let o of t.matchAll(Bn)){let r=et(o[0]);r&&/^https?:\/\/(?:localhost|127\.0\.0\.1):\d+\//i.test(r)&&(e.devServerUrls.includes(r)||e.devServerUrls.push(r))}}function Kr(e){let t=e.content.trim();if(!e.contractActive)return{content:t,malformedBlock:!1};let n=Hr(t);if(n?.claim){let i=t.slice(0,n.start).trimEnd(),a=t.slice(n.end).trim(),c=[i,a].filter(Boolean).join(`
4
+ `),{claim:f,notices:h}=Ja(n.claim,c,e),y=[i,Fr(f),a];return h.length>0&&y.push(h.map(C=>`Engine notice: ${C}`).join(`
5
+ `)),{content:y.filter(Boolean).join(`
3
6
 
4
- ${k}`:k}let p=!!e.artifactContract.artifactRoot||e.artifactContract.writePaths.length>0||e.artifactContract.devServerUrls.length>0||e.artifactContract.browserVerified||e.artifactContract.outOfRootWrites.length>0,y=zr(a,e.blockedToolCalls??[]);if((s||n||r||o||p||u.length>0||y.length>0)&&!Or(a)&&!Or(a)){let k=Xa({...e,content:a,needsBrowser:n,needsResearch:o,needsBuild:r});a=a?`${a}
7
+ `),malformedBlock:!1}}let o=n!==null;if(dl(t)&&e.totalToolCallCount===0)return{content:t,malformedBlock:o};let r=Qa(e);if(!r)return{content:t,malformedBlock:o};let s=Fr(r);return{content:t?`${t}
5
8
 
6
- ${k}`:k}return a}function Xa(e){let t=[],n=[],o=qr(e.activeTasks??[]);if(o.length>0&&(n.push(`Task list still has ${o.length} unresolved item(s): ${o.map(Ka).join("; ")}.`),t.push("Update unresolved task items to completed, cancelled, or an explicit blocker before claiming completion.")),e.artifactContract.outOfRootWrites.length>0&&(n.push("Artifact root drift was detected and at least one write was outside the deliverable root."),t.push(...e.artifactContract.outOfRootWrites.slice(0,3).map(g=>`${g.toolName} attempted ${g.path} outside ${g.artifactRoot}.`))),e.needsBrowser&&!e.artifactContract.browserVerified){let g=e.artifactContract.browserFailureEvidence[0];n.push(g?"Browser-visible acceptance was attempted but failed; no passing browser evidence was recorded.":"Browser-visible acceptance was not recorded for this app/frontend deliverable."),t.push(g?`Fix the browser verification failure before claiming completion: ${g}`:"Load the served app in a browser-capable tool and verify visible UI behavior before claiming completion.")}if(e.needsBuild&&!e.artifactContract.buildVerified){let g=e.artifactContract.buildFailureEvidence[0];n.push(g?"A test/build run is still failing; no passing test/build evidence was recorded.":"The requested test/build was not run to a passing result."),t.push(g?`Fix the code and re-run the test/build until it passes (do not edit the test): ${g.slice(0,200)}`:"Run the project's test/build command and confirm it exits 0 before claiming completion.")}e.needsResearch&&!Fr(e.content)&&n.push("Research/report quality audit sections were not separated in the model response.");let r=zr(e.content,e.blockedToolCalls??[]);r.length>0&&(n.push("The turn stopped with unresolved tool-call blockers instead of completing all requested work."),t.push(...r.slice(0,5).map(g=>`${g.name} blocked by ${g.reason}.`)));let s=e.visibleToolCallCount??e.totalToolCallCount,i=[...e.visibleToolNames??e.distinctToolNames],a=s>0?`Ran ${s} tool call${s===1?"":"s"} (${i.join(", ")||"unknown tools"}).`:e.totalToolCallCount>0?"No tool calls were executed; blocked requests are listed below.":"No tool work was recorded.",u=[e.artifactContract.artifactRoot?`artifactRoot: ${Te(e.artifactContract.artifactRoot)}`:"artifactRoot: not declared",e.artifactContract.writePaths.length>0?`files: ${e.artifactContract.writePaths.slice(0,8).map(Te).join(", ")}`:"files: no write paths recorded",e.artifactContract.devServerUrls.length>0?`urls: ${e.artifactContract.devServerUrls.join(", ")}`:"urls: none recorded"],p=e.artifactContract.browserVerified?`Browser evidence recorded: ${e.artifactContract.browserEvidence[0]??"yes"}`:e.needsBrowser?e.artifactContract.browserFailureEvidence[0]?`Browser verification failed: ${e.artifactContract.browserFailureEvidence[0]}`:"Browser evidence missing.":e.needsBuild?e.artifactContract.buildVerified?`Test/build passed: ${e.artifactContract.buildEvidence[0]??"yes"}`:e.artifactContract.buildFailureEvidence[0]?`Test/build failing: ${e.artifactContract.buildFailureEvidence[0].slice(0,200)}`:"No passing test/build evidence recorded.":"No browser acceptance required for this request.",y=t.length>0?"Resolve the blocker(s), then rerun verification and issue a new final status.":"Proceed with user review or requested follow-up.";return["Done:",`- ${a}`,"","Not done:",...n.length>0?n.map(g=>`- ${g}`):["- None recorded."],"","Artifacts:",...u.map(g=>`- ${g}`),"","Verification:",`- ${p}`,"","Blockers:",...t.length>0?t.map(g=>`- ${g}`):["- None recorded."],"","Next action:",`- ${y}`].join(`
7
- `)}function qr(e){return e.filter(t=>t.status!=="completed")}function Ka(e){return`#${e.id} ${e.title} (${e.status})`}function Ya(e){if(!e)return e;let t="Completion is not confirmed because the task list still has unresolved items.";return e.replace(/\bNo issues to fix\.\s*\*\*Completion confirmed\.\*\*/gi,t).replace(/\bNo issues to fix\.\s*Completion confirmed\./gi,t).replace(/\*\*Completion confirmed\.\*\*/gi,"**Completion not confirmed.**").replace(/\bCompletion confirmed\./gi,"Completion not confirmed.")}function Za(e){return e&&e.replace(/\bAll\s+\d+\s*\/\s*\d+\s+browser-visible acceptance checks passed\.?/gi,"Browser-visible acceptance is not confirmed by recorded browser evidence.").replace(/\bAll\s+\d+\s+(?:Playwright|Puppeteer|browser|browser-visible)\s+(?:browser\s+)?(?:assertions?|checks?|tests?)\s+passed\.?/gi,"Browser-visible acceptance is not confirmed by recorded browser evidence.").replace(/\b(?:All|Every)\s+(?:Playwright|Puppeteer|browser|browser-visible)\s+(?:browser\s+)?(?:assertions?|checks?|tests?)\s+passed\.?/gi,"Browser-visible acceptance is not confirmed by recorded browser evidence.").replace(/(\*\*)?PM MVP App\s*(?:—|-)\s*Complete(\*\*)?/gi,"$1PM MVP App \u2014 Not complete$2").replace(/\bfully built and browser-verified\b/gi,"built but not browser-verified").replace(/\b(?<!not )browser-verified\b/gi,"not browser-verified").replace(/\*\*Completion confirmed\.\*\*/gi,"**Completion not confirmed.**").replace(/\bCompletion confirmed\./gi,"Completion not confirmed.")}function Ja(e){return e&&e.replace(/\ball\s+(?:\d+\s+)?tests?\s+(?:are\s+)?(?:now\s+)?pass(?:ing|ed)?\b\.?/gi,"Tests are not confirmed passing by a recorded test run.").replace(/\btests?\s+(?:are\s+)?(?:now\s+)?(?:green|passing)\b\.?/gi,"Tests are not confirmed passing by a recorded test run.").replace(/\bbuild\s+(?:succeed(?:s|ed)?|passes|passed|is green|works)\b\.?/gi,"Build is not confirmed by a recorded build run.").replace(/\b(?:compiles?|compiled)\s+(?:cleanly|successfully|without\s+errors?)\b\.?/gi,"Compilation is not confirmed by a recorded build run.").replace(/\*\*Completion confirmed\.\*\*/gi,"**Completion not confirmed.**").replace(/\bCompletion confirmed\./gi,"Completion not confirmed.")}function zr(e,t){if(t.length===0)return[];if(!/stopp?ed|stop|failed|failure|blocked|tool error|最后一次工具错误|已停止本轮|失败|阻断/i.test(e))return[];let n=new Set(["artifact-root-contract","dedicated-tool-required","identical-repeat-policy","invalid-arguments","not-offered","read-only-context-pack","tool-call-budget","variant-failure-policy"]),o=/benchmark-state files after indexing the context pack/i.test(e)&&/writes are complete/i.test(e);return t.filter(r=>!(!n.has(r.reason)||o&&r.reason==="not-offered"))}function Qa(e){let t=/\b(?:source|citation|cited|http|https|来源|引用)\b/i.test(e),n=/\b(?:recommend|strategy|should|go|no-go|risk|mitigation|建议|策略|风险|缓解)\b/i.test(e),o=/\b(?:assum|uncertain|unknown|gap|unsupported|verify|need|缺口|假设|不确定|未验证|需确认)\b/i.test(e);return["Sourced facts:",t?"- Source-backed claims are present in the response and must remain tied to the cited URLs or named evidence.":"- No clearly source-backed facts were isolated; treat factual claims as unsupported until evidence is added.","","Assumptions:",o?"- Assumptions, uncertainties, or verification gaps are explicitly called out in the response.":"- No explicit assumptions were separated; reviewer should treat missing premises as open gaps.","","Recommendations:",n?"- Recommendations are present and should be read as advice conditioned on the stated evidence and assumptions.":"- No recommendation section was clearly separated.","","Unsupported claims:","- Any claim without visible evidence must be treated as unsupported until reviewed."].join(`
8
- `)}function Hr(e){try{return JSON.parse(e)}catch{return null}}function Nr(...e){for(let t of e)if(typeof t=="string"&&t.trim())return t.trim();return null}function jn(e){for(let t of e)if(!(t.role!=="user"||typeof t.content!="string"))for(let n of t.content.matchAll(ja)){let o=n[1]??n[2],r=_t(o??"");if(r&&!il(r))return Te(r)}}function Gr(e){let t=Te(_t(e));if(!t)return;let n=t.toLowerCase();if(n.endsWith("/package.json"))return Lr(t);let o=n.lastIndexOf("/src/");if(o>0)return t.slice(0,o);if(n.endsWith("/index.html")||n.endsWith("/vite.config.ts")||n.endsWith("/vite.config.js"))return Lr(t)}function el(e,t,n){if(/^read$/i.test(e)||n.includes("<persisted-output>")||Wr(n)||/\b(?:syntax error|command not found|cannot find|not recognized|failed|failure|exception|traceback|eaddrinuse)\b|无法将|错误|失败/i.test(n))return!1;let o=Pr.test(n),r=/\b(?:playwright|puppeteer|browser|screenshot|locator|page\.goto|dom snapshot|visible text|assertion)\b|浏览器|截图|可见|定位器/i.test(`${t}
9
- ${n}`),s=qn(e)&&Pr.test(t)&&o&&r&&/\b(?:ok|success|passed|loaded|visible|rendered|found|present|assertion passed)\b|可见|加载成功|通过/i.test(n),i=/\b(?:200|ok|success|passed|loaded|visible|rendered|found|present|assertion passed)\b|可见|加载成功|通过/i.test(n);return!(!s&&!(o&&r&&i)||za.test(n)&&!/\b(?:absent|removed|not present|gone|没有|不是默认|已移除)\b/i.test(n))}function tl(e,t,n){return/^read$/i.test(e)||!qn(e)?!1:/\b(?:playwright|puppeteer|browser|screenshot|locator|page\.goto|dom snapshot|visible text|assertion|waitforselector|test-browser|browser verification)\b|浏览器|截图|页面可见|打开页面|加载页面|内置浏览器|自动化/i.test(t)?!0:/\b(?:page\.waitForSelector|waitforselector|strict mode violation|browser closed|target closed|page crashed|locator\(|locator\.)\b/i.test(n)}function Wr(e){return/\b(?:no failed|0 failed|without failed|no failures|failure:? none|failed checks?:? none)\b/i.test(e)?!1:qa.test(e)?!0:/\b(?:fail|failed|failure|error)\b/i.test(e)}function qn(e){return/^(?:exec|bash|shell|powershell|terminal|playwright|browser|computer)$/i.test(e)}var nl=new RegExp(["(?:^|[\\s;&|(])(?:npm|pnpm|yarn|bun)\\s+(?:run\\s+)?(?:test|t|build|lint|typecheck|tsc|check)\\b","(?:^|[\\s;&|(])npx\\s+(?:-y\\s+)?(?:vitest|jest|mocha|tsc|playwright|ava|tap)\\b","(?:^|[\\s;&|(])(?:vitest|jest|mocha|ava|pytest|py\\.test|ctest|tsc)\\b","(?:^|[\\s;&|(])python\\s+-m\\s+(?:pytest|unittest)\\b","(?:^|[\\s;&|(])go\\s+test\\b","(?:^|[\\s;&|(])cargo\\s+(?:test|build|check)\\b","(?:^|[\\s;&|(])(?:mvn|gradle|gradlew|make|cmake)\\s+\\S","(?:^|[\\s;&|(])node\\s+(?:--test\\b|[^\\n;&|]*test[^\\n;&|]*\\.[cm]?js)"].join("|"),"i");function ol(e){let t=Hr(e);return t&&typeof t.command=="string"?t.command:""}function rl(e,t){return qn(e)?nl.test(ol(t)):!1}function sl(e){return/\[exit [1-9]\d*\b|\(exit code [1-9]\d*\b|\[interrupted — exit code [1-9]\d*/.test(e)}function il(e){return/\.[A-Za-z0-9]{1,12}$/.test(e)}function Vr(e,t){let n=Nn(e),o=Nn(t);return n===o||n.startsWith(`${o}/`)}function al(e){return Nn(e).split("/").includes("context-pack")}function Nn(e){return _t(e).replace(/\\/g,"/").replace(/\/+/g,"/").replace(/\/$/u,"").toLowerCase()}function Te(e){return _t(e).replace(/\\/g,"/").replace(/\/+/g,"/").replace(/\/$/u,"")}function Ln(e){let t=e.replace(/[).,;]+$/u,"");if(t.endsWith(":"))return null;try{let n=new URL(t);return n.protocol!=="http:"&&n.protocol!=="https:"||!n.hostname?null:t}catch{return null}}function _t(e){return e.trim().replace(/[).,;:,。;、:]+$/u,"")}function ll(e){return/^[A-Z0-9_ -]{6,80}$/.test(e.trim())}function Lr(e){let t=Te(e),n=t.lastIndexOf("/");return n>0?t.slice(0,n):t}var cl=/^no (matches|files|results) found(?:\s+for:.*)?\.?$|^file not found|^not found|^0 results|^\(exit code \d+, no output\)$/i,ul=new Set(["search","web_search","grep","glob","find","list","read","exec"]);function zn(e){if(!ul.has(e.toolName))return!1;let t=typeof e.message?.content=="string"?dl(e.message.content).trim():"";return t.length>0&&t.length<200&&cl.test(t)}function dl(e){return e.match(/<untrusted_tool_result\b[^>]*>\s*([\s\S]*?)\s*<\/untrusted_tool_result>/i)?.[1]??e}var fl=/[A-Za-z]:[\\/](?:[^\s"'`<>|,\uFF0C\u3001;\uFF1B\u3002]+[\\/])*[^\s"'`<>|,\uFF0C\u3001;\uFF1B\u3002]+\.[A-Za-z0-9]{1,12}/g,pl=/(?:^|[\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,ml=/(?:^|[\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,gl=/\b(?:create|generate|write|produce|save|output|deliver|deliverables?|artifacts?|required|required files?|must generate|self-verify)\b|(?:生成|创建|写入|输出|保存|交付|产物|文件|必须|自检|验证)/i;function vt(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 hl=/\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,Xr=50,Kr=90;function Yr(e){if(!e)return!1;for(let t of e)if(t.role==="user"&&typeof t.content=="string"&&hl.test(t.content))return!0;return!1}var yl=/(?:我来|我先|我现在就?|让我先?|接下来我?|我帮你|我这就|我会|我将|我去|我看)[^。.!?!?\n]{0,12}(?:做|搭建?|写|开发|实现|构建|生成|创建|新建|建立|改|修复?|检查|读取?|运行|跑|执行|看一?下?|查看|配置|安装|部署|分析|整理|定位|排查|找)/,bl=/\b(?:let me|i['’]?ll|i will|i['’]?m going to|let['’]?s)\b[^.!?\n]{0,24}\b(?:build|create|make|write|implement|generate|check|read|run|look|set up|scaffold|add|fix|inspect|search|find|list|analyze|review|start|debug|investigate)\b/i;function Zr(e){let t=e.trim();return t.length===0||t.length>200||t.includes("```")?!1:yl.test(t)||bl.test(t)}function Jr(e,t){if(typeof e=="number"&&Number.isFinite(e)&&e>=1)return Math.min(Math.round(e),100);let n=wt(t);return n>=3?Math.min(Math.max(25,20+n*15),100):ae(t??[])?Math.min(Math.max(25,Kr),100):Yr(t)?Math.min(Math.max(25,Xr),100):25}function wt(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(fl))o(i[0]);if(gl.test(s)){for(let i of s.matchAll(pl)){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(ml)){let a=i[1]?.toLowerCase();!a||n.has(a)||t.add(`name:${a}`)}}}return t.size}function Qr(e,t){if(typeof e=="number"&&Number.isFinite(e)&&e>=1)return Math.min(Math.round(e),100);let n=wt(t);return n>=3?Math.min(Math.max(be,20+n*15),100):ae(t??[])?Math.min(Math.max(be,Kr),100):Yr(t)?Math.min(Math.max(be,Xr),100):be}function es(e){return e.filter(t=>t.role!=="assistant"?!0:!(typeof t.content=="string"&&t.content.trim()===""))}function Hn(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(`
9
+ ${s}`:s,malformedBlock:o}}function Ja(e,t,n){let o=n.artifactContract,r=[],s={...e,schema:1,author:"model"};if(s.verification){let a={...s.verification};a.browser==="verified"&&o.browserEvidence.length===0&&(a.browser=o.browserFailureEvidence.length>0?"failed":"not-run",r.push(`browser "verified" claim corrected to "${a.browser}" \u2014 no passing browser evidence was recorded this turn.`)),a.build==="passed"&&!o.buildVerified&&(a.build=o.buildFailureEvidence.length>0?"failed":"not-run",r.push(`build "passed" claim corrected to "${a.build}" \u2014 no passing test/build run was recorded this turn.`)),s.verification=a}let i=Yr(n.activeTasks??[]);if(i.length>0&&(s.done?.length??0)>0){let a=[...s.notDone??[]];for(let c of i){let f=`Task ${Zr(c)} is unresolved.`;a.includes(f)||a.push(f)}s.notDone=a,r.push(`${i.length} task item(s) remain unresolved; completion is not confirmed.`)}if(s.artifacts?.files?.length){let a=o.writePaths.map(Ue),c=typeof s.artifacts.root=="string"&&s.artifacts.root?s.artifacts.root:o.artifactRoot,f=C=>{let x=Ue(C);return x?a.includes(x)||c&&a.includes(Ue(`${c}/${C}`))?!0:a.some(v=>v.endsWith(`/${x}`)):!1},h=s.artifacts.files.filter(C=>typeof C=="string"&&f(C)),y=s.artifacts.files.length-h.length;y>0&&(s.artifacts={...s.artifacts,files:h},r.push(`${y} artifact file claim(s) removed \u2014 not recorded as written this turn.`))}if(s.sources?.cited?.length){let a=new Set([...nl(t),...o.devServerUrls]),c=[];for(let h of s.sources.cited){if(typeof h!="string")continue;let y=et(h);y&&a.has(y)&&!c.includes(y)&&c.push(y)}let f=s.sources.cited.length-c.length;f>0&&(s.sources={...s.sources,cited:c},r.push(`${f} cited source(s) removed \u2014 not seen in this turn's response or tool results.`))}return{claim:s,notices:r}}function Qa(e){let t=e.artifactContract,n=Yr(e.activeTasks??[]),o=e.forcedStop?tl(e.blockedToolCalls??[]):[],r=t.recoveredBaseline??{writePaths:0,devServerUrls:0,artifactRoot:!1},s=t.writePaths.slice(r.writePaths),i=t.devServerUrls.slice(r.devServerUrls);if(!(!!t.artifactRoot&&!r.artifactRoot||s.length>0||i.length>0||t.browserVerified||t.outOfRootWrites.length>0||t.buildVerified||t.buildFailureEvidence.length>0)&&n.length===0&&o.length===0)return null;let c=[],f=[];n.length>0&&(c.push(`Task list still has ${n.length} unresolved item(s): ${n.map(Zr).join("; ")}.`),f.push("Update unresolved task items to completed, cancelled, or an explicit blocker before claiming completion.")),t.outOfRootWrites.length>0&&(c.push("At least one write landed outside the declared deliverable root."),f.push(...t.outOfRootWrites.slice(0,3).map(A=>`${A.toolName} attempted ${A.path} outside ${A.artifactRoot}.`))),!t.buildVerified&&t.buildFailureEvidence.length>0&&(c.push("A test/build run is failing; no passing test/build evidence was recorded."),f.push(`Fix the code and re-run the test/build until it passes: ${t.buildFailureEvidence[0].slice(0,200)}`)),o.length>0&&(c.push("The turn stopped with unresolved tool-call blockers instead of completing all requested work."),f.push(...o.slice(0,5).map(A=>`${A.name} blocked by ${A.reason}.`)));let h=e.visibleToolCallCount??e.totalToolCallCount,y=[...e.visibleToolNames??e.distinctToolNames],x={schema:1,author:"engine",done:[h>0?`Ran ${h} tool call${h===1?"":"s"} (${y.join(", ")||"unknown tools"}).`:e.totalToolCallCount>0?"No tool calls were executed; blocked requests are listed under blockers.":"No tool work was recorded."],verification:{browser:t.browserVerified?"verified":t.browserFailureEvidence.length>0?"failed":"not-run",build:t.buildVerified?"passed":t.buildFailureEvidence.length>0?"failed":"not-run"},nextAction:f.length>0?"Resolve the blocker(s), then rerun verification and issue a new final status.":"Proceed with user review or requested follow-up."};c.length>0&&(x.notDone=c),f.length>0&&(x.blockers=f);let v={};return t.artifactRoot&&(v.root=Se(t.artifactRoot)),s.length>0&&(v.files=s.slice(0,8).map(Se)),i.length>0&&(v.urls=[...i]),Object.keys(v).length>0&&(x.artifacts=v),x}function Yr(e){return e.filter(t=>t.status!=="completed")}function Zr(e){return`#${e.id} ${e.title} (${e.status})`}var el=new Set(["artifact-root-contract","dedicated-tool-required","identical-repeat-policy","invalid-arguments","not-offered","read-only-context-pack","tool-call-budget","variant-failure-policy"]);function tl(e){return e.filter(t=>el.has(t.reason))}function nl(e){let t=[];for(let n of e.matchAll(Bn)){let o=et(n[0]);o&&!t.includes(o)&&t.push(o)}return t}function Jr(e){try{return JSON.parse(e)}catch{return null}}function Br(...e){for(let t of e)if(typeof t=="string"&&t.trim())return t.trim();return null}function qn(e){for(let t of e)if(!(t.role!=="user"||typeof t.content!="string"))for(let n of t.content.matchAll(Wa)){let o=n[1]??n[2],r=At(o??"");if(r&&!cl(r))return Se(r)}}function Qr(e){let t=Se(At(e));if(!t)return;let n=t.toLowerCase();if(n.endsWith("/package.json"))return Dr(t);let o=n.lastIndexOf("/src/");if(o>0)return t.slice(0,o);if(n.endsWith("/index.html")||n.endsWith("/vite.config.ts")||n.endsWith("/vite.config.js"))return Dr(t)}function ol(e,t,n){if(/^read$/i.test(e)||n.includes("<persisted-output>")||es(n)||/\b(?:syntax error|command not found|cannot find|not recognized|failed|failure|exception|traceback|eaddrinuse)\b|无法将|错误|失败/i.test(n))return!1;let o=Lr.test(n),r=/\b(?:playwright|puppeteer|browser|screenshot|locator|page\.goto|dom snapshot|visible text|assertion)\b|浏览器|截图|可见|定位器/i.test(`${t}
10
+ ${n}`),s=zn(e)&&Lr.test(t)&&o&&r&&/\b(?:ok|success|passed|loaded|visible|rendered|found|present|assertion passed)\b|可见|加载成功|通过/i.test(n),i=/\b(?:200|ok|success|passed|loaded|visible|rendered|found|present|assertion passed)\b|可见|加载成功|通过/i.test(n);return!(!s&&!(o&&r&&i)||Xa.test(n)&&!/\b(?:absent|removed|not present|gone|没有|不是默认|已移除)\b/i.test(n))}function rl(e,t,n){return/^read$/i.test(e)||!zn(e)?!1:/\b(?:playwright|puppeteer|browser|screenshot|locator|page\.goto|dom snapshot|visible text|assertion|waitforselector|test-browser|browser verification)\b|浏览器|截图|页面可见|打开页面|加载页面|内置浏览器|自动化/i.test(t)?!0:/\b(?:page\.waitForSelector|waitforselector|strict mode violation|browser closed|target closed|page crashed|locator\(|locator\.)\b/i.test(n)}function es(e){return/\b(?:no failed|0 failed|without failed|no failures|failure:? none|failed checks?:? none)\b/i.test(e)?!1:Va.test(e)?!0:/\b(?:fail|failed|failure|error)\b/i.test(e)}function zn(e){return/^(?:exec|bash|shell|powershell|terminal|playwright|browser|computer)$/i.test(e)}var sl=new RegExp(["(?:^|[\\s;&|(])(?:npm|pnpm|yarn|bun)\\s+(?:run\\s+)?(?:test|t|build|lint|typecheck|tsc|check)\\b","(?:^|[\\s;&|(])npx\\s+(?:-y\\s+)?(?:vitest|jest|mocha|tsc|playwright|ava|tap)\\b","(?:^|[\\s;&|(])(?:vitest|jest|mocha|ava|pytest|py\\.test|ctest|tsc)\\b","(?:^|[\\s;&|(])python\\s+-m\\s+(?:pytest|unittest)\\b","(?:^|[\\s;&|(])go\\s+test\\b","(?:^|[\\s;&|(])cargo\\s+(?:test|build|check)\\b","(?:^|[\\s;&|(])(?:mvn|gradle|gradlew|make|cmake)\\s+\\S","(?:^|[\\s;&|(])node\\s+(?:--test\\b|[^\\n;&|]*test[^\\n;&|]*\\.[cm]?js)"].join("|"),"i");function il(e){let t=Jr(e);return t&&typeof t.command=="string"?t.command:""}function al(e,t){return zn(e)?sl.test(il(t)):!1}function ll(e){return/\[exit [1-9]\d*\b|\(exit code [1-9]\d*\b|\[interrupted exit code [1-9]\d*/.test(e)}function cl(e){return/\.[A-Za-z0-9]{1,12}$/.test(e)}function ts(e,t){let n=Ue(e),o=Ue(t);return n===o||n.startsWith(`${o}/`)}function ul(e){return Ue(e).split("/").includes("context-pack")}function Ue(e){return At(e).replace(/\\/g,"/").replace(/\/+/g,"/").replace(/\/$/u,"").toLowerCase()}function Se(e){return At(e).replace(/\\/g,"/").replace(/\/+/g,"/").replace(/\/$/u,"")}function et(e){let t=e.replace(/[).,;]+$/u,"");if(t.endsWith(":"))return null;try{let n=new URL(t);return n.protocol!=="http:"&&n.protocol!=="https:"||!n.hostname?null:t}catch{return null}}function At(e){return e.trim().replace(/[).,;:,。;、:]+$/u,"")}function dl(e){return/^[A-Z0-9_ -]{6,80}$/.test(e.trim())}function Dr(e){let t=Se(e),n=t.lastIndexOf("/");return n>0?t.slice(0,n):t}var fl=/^no (matches|files|results) found(?:\s+for:.*)?\.?$|^file not found|^not found|^0 results|^\(exit code \d+, no output\)$/i,pl=new Set(["search","web_search","grep","glob","find","list","read","exec"]);function Hn(e){if(!pl.has(e.toolName))return!1;let t=typeof e.message?.content=="string"?ml(e.message.content).trim():"";return t.length>0&&t.length<200&&fl.test(t)}function ml(e){return e.match(/<untrusted_tool_result\b[^>]*>\s*([\s\S]*?)\s*<\/untrusted_tool_result>/i)?.[1]??e}var gl=/[A-Za-z]:[\\/](?:[^\s"'`<>|,\uFF0C\u3001;\uFF1B\u3002]+[\\/])*[^\s"'`<>|,\uFF0C\u3001;\uFF1B\u3002]+\.[A-Za-z0-9]{1,12}/g,hl=/(?:^|[\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,yl=/(?:^|[\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,bl=/\b(?:create|generate|write|produce|save|output|deliver|deliverables?|artifacts?|required|required files?|must generate|self-verify)\b|(?:生成|创建|写入|输出|保存|交付|产物|文件|必须|自检|验证)/i;function wt(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 Tl=/\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,ns=50,os=90;function rs(e){if(!e)return!1;for(let t of e)if(t.role==="user"&&typeof t.content=="string"&&Tl.test(t.content))return!0;return!1}var Cl=/(?:我来|我先|我现在就?|让我先?|接下来我?|我帮你|我这就|我会|我将|我去|我看)[^。.!?!?\n]{0,12}(?:做|搭建?|写|开发|实现|构建|生成|创建|新建|建立|改|修复?|检查|读取?|运行|跑|执行|看一?下?|查看|配置|安装|部署|分析|整理|定位|排查|找)/,kl=/\b(?:let me|i['’]?ll|i will|i['’]?m going to|let['’]?s)\b[^.!?\n]{0,24}\b(?:build|create|make|write|implement|generate|check|read|run|look|set up|scaffold|add|fix|inspect|search|find|list|analyze|review|start|debug|investigate)\b/i;function ss(e){let t=e.trim();return t.length===0||t.length>200||t.includes("```")?!1:Cl.test(t)||kl.test(t)}function is(e,t){if(typeof e=="number"&&Number.isFinite(e)&&e>=1)return Math.min(Math.round(e),100);let n=St(t);return n>=3?Math.min(Math.max(25,20+n*15),100):de(t??[])?Math.min(Math.max(25,os),100):rs(t)?Math.min(Math.max(25,ns),100):25}function St(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(gl))o(i[0]);if(bl.test(s)){for(let i of s.matchAll(hl)){let a=i[1]?.toLowerCase();if(!a)continue;t.add(`relative:${a.replace(/\\/g,"/")}`);let c=a.replace(/\\/g,"/").split("/").pop();c&&n.add(c)}for(let i of s.matchAll(yl)){let a=i[1]?.toLowerCase();!a||n.has(a)||t.add(`name:${a}`)}}}return t.size}function as(e,t){if(typeof e=="number"&&Number.isFinite(e)&&e>=1)return Math.min(Math.round(e),100);let n=St(t);return n>=3?Math.min(Math.max(be,20+n*15),100):de(t??[])?Math.min(Math.max(be,os),100):rs(t)?Math.min(Math.max(be,ns),100):be}function ls(e){return e.filter(t=>t.role!=="assistant"?!0:!(typeof t.content=="string"&&t.content.trim()===""))}function Gn(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(`
10
11
 
11
- `)):""}function Gn(e,t){let n=vt(e,"")?.slice(0,600).trim(),o=`\u5DF2\u505C\u6B62\u672C\u8F6E\uFF1A\u5DE5\u5177\u8FDE\u7EED ${t} \u8F6E\u8C03\u7528\u5931\u8D25\uFF0C\u7EE7\u7EED\u91CD\u8BD5\u6CA1\u6709\u610F\u4E49\u3002`;return n?`${o}
12
+ `)):""}function Wn(e,t){let n=wt(e,"")?.slice(0,600).trim(),o=`\u5DF2\u505C\u6B62\u672C\u8F6E\uFF1A\u5DE5\u5177\u8FDE\u7EED ${t} \u8F6E\u8C03\u7528\u5931\u8D25\uFF0C\u7EE7\u7EED\u91CD\u8BD5\u6CA1\u6709\u610F\u4E49\u3002`;return n?`${o}
12
13
 
13
14
  \u6700\u540E\u4E00\u6B21\u5DE5\u5177\u9519\u8BEF\uFF1A
14
15
  ${n}
15
16
 
16
17
  \u8BF7\u6839\u636E\u4E0A\u9762\u7684\u9519\u8BEF\u4FEE\u6B63\u540E\u91CD\u8BD5\uFF0C\u6216\u6362\u4E00\u79CD\u5B9E\u73B0\u65B9\u5F0F\u3002`:`${o}
17
18
 
18
- \u8BF7\u91CD\u8BD5\uFF0C\u6216\u6362\u4E00\u79CD\u5B9E\u73B0\u65B9\u5F0F\u3002`}function ts(e){let t,n;for(let r=e.length-1;r>=0;r--){let s=e[r];if(s?.role==="tool"&&typeof s.content=="string"&&s.content.startsWith("Error: ")){t=s.content.slice(7,807).trim(),n=typeof s.tool_call_id=="string"?s.tool_call_id:void 0;break}}if(!t)return null;let o;if(n)for(let r of e){let s=r.tool_calls;if(Array.isArray(s))for(let i of s){let a=i;if(a.id!==n)continue;let u=a.function;typeof u?.arguments=="string"&&(o=Wn(u.arguments)??u.arguments.slice(0,200))}}return{role:"user",content:`\u4F60\u6700\u8FD1\u7684\u5DE5\u5177\u8C03\u7528\u8FDE\u7EED\u5931\u8D25\u4E86\u3002\u653E\u5F03\u4E4B\u524D\u5148\u505C\u4E0B\u6765\u7EA0\u6B63\u2014\u2014**\u4E0D\u8981\u518D\u91CD\u590D\u540C\u6837\u7684\u5931\u8D25\u547D\u4EE4**\u3002
19
+ \u8BF7\u91CD\u8BD5\uFF0C\u6216\u6362\u4E00\u79CD\u5B9E\u73B0\u65B9\u5F0F\u3002`}function cs(e){let t,n;for(let r=e.length-1;r>=0;r--){let s=e[r];if(s?.role==="tool"&&typeof s.content=="string"&&s.content.startsWith("Error: ")){t=s.content.slice(7,807).trim(),n=typeof s.tool_call_id=="string"?s.tool_call_id:void 0;break}}if(!t)return null;let o;if(n)for(let r of e){let s=r.tool_calls;if(Array.isArray(s))for(let i of s){let a=i;if(a.id!==n)continue;let c=a.function;typeof c?.arguments=="string"&&(o=Vn(c.arguments)??c.arguments.slice(0,200))}}return{role:"user",content:`\u4F60\u6700\u8FD1\u7684\u5DE5\u5177\u8C03\u7528\u8FDE\u7EED\u5931\u8D25\u4E86\u3002\u653E\u5F03\u4E4B\u524D\u5148\u505C\u4E0B\u6765\u7EA0\u6B63\u2014\u2014**\u4E0D\u8981\u518D\u91CD\u590D\u540C\u6837\u7684\u5931\u8D25\u547D\u4EE4**\u3002
19
20
 
20
21
  `+(o?`\u6700\u540E\u4E00\u6B21\u8C03\u7528\uFF1A${o}
21
22
  `:"")+`\u6700\u540E\u4E00\u6B21\u9519\u8BEF\uFF1A
22
23
  ${t}
23
24
 
24
- \u8BF7\u6309\u9519\u8BEF\u4FE1\u606F\u7EA0\u6B63\u540E\u518D\u91CD\u8BD5\uFF1A\u5982\u679C\u662F\u547D\u4EE4\u884C\u5DE5\u5177\uFF0C\u5148\u7528\u5B83\u81EA\u5E26\u7684\u5E2E\u52A9\u786E\u8BA4\u6B63\u786E\u7684\u5B50\u547D\u4EE4/\u53C2\u6570/\u8BED\u6CD5\uFF08\u5982 \`<\u5DE5\u5177> --help\` \u6216 \`<\u5DE5\u5177> help <\u5B50\u547D\u4EE4>\`\uFF09\uFF0C\u4E0D\u8981\u51ED\u76F4\u89C9\u62FC\u547D\u4EE4\uFF1B\u6216\u6362\u4E00\u79CD\u5B9E\u73B0\u65B9\u5F0F\u3002`}}function Wn(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 Vn(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 Xn(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 ns(e){return e==="length"||e==="max_tokens"}function Kn(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 os(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 rs(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*ss(e){let{messages:t,contentReplacementState:n,snipRemovedIds:o,collapseStore:r,guardConfig:s,runtimePorts:i,hooks:a,hookCtx:u,sessionId:p,currentModel:y,log:g,recovery:k,onAutocompact:_}=e,A;{let w=await i.enforceToolResultBudget(t,n,p);A=w.messages,w.newlyReplacedCount>0&&(g.info(`tool-result-budget: persisted ${w.newlyReplacedCount} oversized tool results`),yield k("tool_result_budget",`${w.newlyReplacedCount} persisted`))}{let w=fn(A,o);A=w.messages,w.removedCount>0&&(g.info(`snip: removed ${w.removedCount} messages, freed ~${w.tokensFreed} tokens`),yield k("snip",`${w.removedCount} messages`))}{let P=new Ze().compress(A,0);P.droppedCount>0&&(A=P.messages,g.info(`microcompact: cleared ${P.droppedCount} old tool results`))}if(A=mn(A,r).messages,s.contextWindowTokens>0){let w=s.contextWindowTokens*.75,P=i.getActiveContextCompressionEngine(),S;P?S=await P.compressAsync(A,w,{model:y,sessionId:p}):S=i.compressMessages(A,{budget:w,model:y}),S.droppedCount>0&&(A=S.messages,g.info(`autocompact: ${S.strategy}, dropped ${S.droppedCount}`),yield k("autocompact",`${S.strategy}: ${S.droppedCount} dropped`),yield{type:"lifecycle",turnId:u.turnId,kind:"context_compression",status:"completed",detail:`${S.strategy}: ${S.droppedCount} dropped`},_(),$(a,"context.after_compact",{...u,removedCount:S.droppedCount},g))}return A=es(A),A}async function*is(e,t){let{state:n,guardState:o,fallbackModel:r,signal:s,querySource:i,turnId:a,log:u,emitRecovery:p}=t;if(e instanceof Je&&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 y=e instanceof Error?e.message:String(e),g=typeof e?.status=="number"?e.status:void 0;if(!g&&y&&(y.includes("ECONNRESET")||y.includes("EPIPE"))){let _=(n.consecutiveApiRetries??0)+1;return _>Se?(u.info(`stale connection retry limit reached (${Se}), aborting`),yield{type:"error",turnId:a,error:y,code:"RETRIES_EXHAUSTED",usage:n.totalUsage},{kind:"return"}):(u.info(`stale connection (${y.includes("ECONNRESET")?"ECONNRESET":"EPIPE"}): retrying`),yield p("stale_connection_retry",y.slice(0,80)),{kind:"continue",patch:{consecutiveApiRetries:_,transition:void 0}})}let k=rs({status:g,message:y});if(k!==null)return u.info(`max_tokens overflow: adjusting to ${k}`),o.currentMaxOutputTokens=k,{kind:"continue",patch:{maxOutputTokensOverride:k,transition:void 0}};if(vn(g)){n.consecutive529Errors++;let _=2,A=r&&n.currentModel!==r;if(n.consecutive529Errors>_&&!A&&!xt())return u.info(`transient ${g} \u8133 ${n.consecutive529Errors}: hard limit reached, aborting`),yield{type:"error",turnId:a,error:`API unavailable after ${n.consecutive529Errors} consecutive ${g} errors`,code:"API_ERROR",usage:n.totalUsage},{kind:"return"};if(n.consecutive529Errors>=hr&&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(xt()){let w=Rt(n.consecutive529Errors);u.info(`persistent retry: waiting ${w}ms (attempt ${n.consecutive529Errors})`);let P=w;for(;P>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(P/1e3)}s (${g})`};let S=Math.min(P,gr);await new Promise(O=>setTimeout(O,S)),P-=S}return{kind:"continue",patch:{transition:void 0}}}if(_n(i)){let P=os({status:g,message:y})??Rt(n.consecutive529Errors);return u.info(`transient ${g}: retry in ${P}ms`),yield p("retry",`${g} retry in ${P}ms`),await new Promise(S=>setTimeout(S,P)),{kind:"continue",patch:{transition:void 0}}}u.info(`background source ${i}: not retrying ${g}`)}return{kind:"streamError",streamError:{status:g,message:y}}}import{readdirSync as ds,statSync as et}from"node:fs";var Tl=/create\s+(?:a\s+)?file|write\s+(?:a\s+)?file|make\s+(?:a\s+)?file|generate\s+(?:a\s+)?file|new\s+file/i,Cl=/\bfix\b|implement|modify|update|repair/i,fs=/[A-Za-z]:[\\/](?:[^\s"'`<>|,\uFF0C\u3001;\uFF1B\u3002]+[\\/])*[^\s"'`<>|,\uFF0C\u3001;\uFF1B\u3002]+\.[A-Za-z0-9]{1,12}/g,as=/\s*[,\uFF0C\u3001;\uFF1B]\s*([^\s"'`<>|,\uFF0C\u3001;\uFF1B\u3002\\/]+\.[A-Za-z0-9]{1,12})/gy,kl=/\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,Rl=/(?:^|[\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,xl=/(?:^|[\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,_l=/(?:^|[\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,vl=/\b(?:create|generate|write|produce|save|output|deliver|deliverables?|artifacts?|required|required files?|must generate|self-verify)\b|(?:生成|创建|写入|输出|保存|交付|产物|文件|必须|自检|验证)/i,wl=/\bpreviews?[\\/]\s*(?:containing|with|under|for)?[^.。;;\n]*(?:rendered|preview|previews|check|evidence|verify|verification)\b/i,Al=/(?:do\s*not|don'?t|never|不要|不能|别|勿|禁止|不准|不得)[^.。;;\n]{0,14}(?:create|write|make|produce|generate|生成|创建|写入|写出|建立|新建)/i;function K(e){return e.trim().replace(/[),.;:\uFF0C\u3002\uFF1B\u3001]+$/u,"").replace(/\\/g,"/").toLowerCase()}function ps(e){return e.trim().replace(/[),.;:\uFF0C\u3002\uFF1B\u3001]+$/u,"").replace(/\\/g,"/").replace(/\/+$/u,"")}function ls(e){return/\.[A-Za-z0-9]{1,12}$/u.test(e.replace(/[),.;:\uFF0C\u3002\uFF1B\u3001]+$/u,""))}function cs(e,t,n){let o=Math.max(e.lastIndexOf(".",t),e.lastIndexOf(`
25
- `,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+${ys(n)}\\b`,"i").test(s)}function Yn(e){return e.replace(/https?:\/\/\S+/gu," ")}function St(e){let t=new Set,n=[],o=r=>{let s=r.replace(/[),.;:\uFF0C\u3002\uFF1B]+$/u,""),i=K(s);t.has(i)||(t.add(i),n.push(s))};for(let r of e){if(r.role!=="user"||typeof r.content!="string")continue;let s=Yn(r.content);for(let i of s.matchAll(fs)){let a=i[0],u=(i.index??0)+a.length;if(s[u]==="/"||s[u]==="\\")continue;o(a);let p=a.replace(/\\/g,"/"),y=p.lastIndexOf("/");if(y>=0){let g=p.slice(0,y+1);as.lastIndex=u;let k;for(;(k=as.exec(s))!==null;)o(`${g}${k[1]}`)}}}for(let r of e){if(r.role!=="user"||typeof r.content!="string")continue;let s=Yn(r.content);if(!vl.test(s))continue;let i=Array.from(s.matchAll(kl)).map(u=>ps(u[1]??"")).filter(u=>u&&!ls(u));if(i.length===0)continue;let a=i[i.length-1];for(let u of s.matchAll(Rl)){let p=u[1];p&&(cs(s,u.index??0,p)||o(`${a}/${p}`))}for(let u of s.matchAll(xl)){let p=u[1];p&&(cs(s,u.index??0,p)||o(`${a}/${p}`))}for(let u of s.matchAll(_l)){let p=u[1];p&&(ls(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}/*`))}wl.test(s)&&o(`${a}/previews/*`)}return n}function Mt(e){if(e.role!=="tool")return!1;let t=typeof e.content=="string"?e.content:"";return e.is_error!==!0&&!t.startsWith("Error:")}function Zn(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,y=u.function;typeof p=="string"&&typeof y?.name=="string"&&n.set(p,y.name)}}for(let r of e){let s=r;if(Mt(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 y=u.function;if(!(typeof y?.name!="string"||typeof y.arguments!="string"))try{let g=JSON.parse(y.arguments);if(y.name==="write"||y.name==="edit"){for(let k of["path","filePath","file_path"]){let _=g[k];typeof _=="string"&&o.push(_)}continue}if(y.name==="exec"){let k=g.command;typeof k=="string"&&o.push(k)}}catch{y.name==="exec"&&o.push(y.arguments)}}}return o.join(`
26
- `).replace(/\\/g,"/").toLowerCase()}function Jn(e){try{if(e.endsWith("/*")){let n=e.slice(0,-2);return ds(n,{withFileTypes:!0}).some(r=>{if(!r.isFile())return!1;try{return et(`${n}/${r.name}`).size>0}catch{return!1}})}let t=et(e);return t.isFile()&&t.size>0}catch{return!1}}function Sl(e,t){let n=K(t);if(!n.endsWith("/*"))return e.includes(n);let o=n.slice(0,-1);return e.includes(o)}function Ml(e){let t=new Set;for(let n of e){let o=n,r=Array.isArray(o.tool_calls)?o.tool_calls:[];for(let s of r){let i=s,a=i.id,u=i.function;typeof a=="string"&&u?.name==="agent"&&t.add(a)}}for(let n of e){let o=n,r=o.tool_call_id;if(typeof r=="string"&&t.has(r)&&Mt(o))return!0}return!1}function El(e){let t=hs(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 Il(e){let t=ps(e),n=t.lastIndexOf("/");return n>=0?t.slice(0,n):""}function Pl(e){if(e.length===0)return"";let t=e.map(o=>Il(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 Ol(e,t){let n=K(e);return t.some(o=>{let r=K(o);return r.endsWith("/*")?n.startsWith(r.slice(0,-1)):n===r})}function ms(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 y=Et(p.arguments);if(!y)continue;let g=It(y);g&&n.set(u,g)}}for(let o of e){let r=o;if(!Mt(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 Nl(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 Ll(e){return[...new Set([...e.matchAll(/\bGoal\s+\d+\b/gi)].map(t=>t[0].replace(/\s+/g," ").replace(/\bgoal\b/i,"Goal")))]}function Fl(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 y=Et(p.arguments);if(!y)continue;let g=It(y)??"",k=bs(y);(/\bartifact[-_\s]?index\b/i.test(g)||/\bartifact[-_\s]?index\b/i.test(k))&&n.set(u,k)}}for(let o of e){let r=o;if(!Mt(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 Bl(e){let t=hs(e.inputMessages);if(!Nl(t))return[];let n=Fl(e.messages).at(-1);if(!n)return[];let o=[],r=Ll(t).filter(u=>!new RegExp(`\\b${ys(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 Dl(e){let t=[],n=o=>{let r;try{r=ds(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{et(i).size>0&&t.push(i)}catch{}}};try{if(!et(e).isDirectory())return[]}catch{return[]}return n(e),t}function $l(e,t){if(!El(e))return[];let n=St(e),o=n.filter(i=>!K(i).endsWith("/*"));if(o.length<2)return[];let r=Pl(o);if(!r||r.split("/").length<3)return[];let s=K(r);return[...new Set([...ms(t),...Dl(r)])].filter(i=>K(i).startsWith(`${s}/`)&&!Ol(i,n)&&Jn(i))}function gs(e,t){let n=St(e);if(n.length===0)return[];let o=Zn(t);return n.filter(r=>!Sl(o,r))}function Qe(e){return Qn(e).fail}function Ul(e){return e.replace(/[.,;:,。;:、!?]+$/u,"")}function At(e){if(!e)return!1;let t=Ul(e);return/^[A-Za-z0-9_.:-]+$/u.test(t)&&/[0-9_:-]/u.test(t)}function Qn(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))At(s[2])&&(n=`${s[1].toUpperCase()} ${t(s[2])}`);for(let s of r.content.matchAll(/\bFAIL\s+([A-Za-z0-9_.:-]+)/gi))At(s[1])&&(o=`FAIL ${t(s[1])}`);for(let s of r.content.matchAll(/\b([A-Za-z0-9_.:-]+)\s+(DONE|PASS)\b/gi))At(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))At(s[1])&&(o=`${t(s[1])} FAIL`)}return{done:n,fail:o}}function hs(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 ys(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Pe(e){let t=gs(e.inputMessages,e.messages).filter(o=>!Jn(o));return t.length===0?void 0:`${Qe(e.inputMessages)??"FAIL"} ${e.reason}. Missing required output file evidence: ${t.join(", ")}`}function Et(e){try{let t=JSON.parse(e);return t&&typeof t=="object"&&!Array.isArray(t)?t:null}catch{return null}}function It(e){for(let t of["path","filePath","file_path"]){let n=e[t];if(typeof n=="string"&&n.trim())return n}}function bs(e){for(let t of["content","newContent","replacement","text"]){let n=e[t];if(typeof n=="string")return n}return""}function Ts(e){let t=e.toolCall.function.name;if(t!=="write"&&t!=="edit")return;let n=Qn(e.inputMessages);if(!n.done)return;let o=Et(e.toolCall.function.arguments);if(!o)return;let r=It(o),s=bs(o);if(!r||!s.includes(n.done))return;let i=St(e.inputMessages);if(i.length<2)return;let a=K(r);if(!i.some(g=>K(g)===a))return;let p=Zn(e.messages),y=i.filter(g=>K(g)!==a).filter(g=>!p.includes(K(g)));if(y.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: ${y.join(", ")}. Create or verify the missing files first, or report the requested FAIL marker with the real reason.`}function Ee(e,t){return{role:"assistant",content:e,...t.length>0&&{thinkingBlocks:[...t]}}}function jl(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 ql(e){let t=[...e].reverse().find(n=>n.role==="tool");t&&typeof t.content=="string"&&(t.content+=`
25
+ \u8BF7\u6309\u9519\u8BEF\u4FE1\u606F\u7EA0\u6B63\u540E\u518D\u91CD\u8BD5\uFF1A\u5982\u679C\u662F\u547D\u4EE4\u884C\u5DE5\u5177\uFF0C\u5148\u7528\u5B83\u81EA\u5E26\u7684\u5E2E\u52A9\u786E\u8BA4\u6B63\u786E\u7684\u5B50\u547D\u4EE4/\u53C2\u6570/\u8BED\u6CD5\uFF08\u5982 \`<\u5DE5\u5177> --help\` \u6216 \`<\u5DE5\u5177> help <\u5B50\u547D\u4EE4>\`\uFF09\uFF0C\u4E0D\u8981\u51ED\u76F4\u89C9\u62FC\u547D\u4EE4\uFF1B\u6216\u6362\u4E00\u79CD\u5B9E\u73B0\u65B9\u5F0F\u3002`}}function Vn(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 Xn(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 Kn(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 us(e){return e==="length"||e==="max_tokens"}function Yn(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 ds(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 fs(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*ps(e){let{messages:t,contentReplacementState:n,snipRemovedIds:o,collapseStore:r,guardConfig:s,runtimePorts:i,hooks:a,hookCtx:c,sessionId:f,currentModel:h,log:y,recovery:C,onAutocompact:x}=e,v;{let A=await i.enforceToolResultBudget(t,n,f);v=A.messages,A.newlyReplacedCount>0&&(y.info(`tool-result-budget: persisted ${A.newlyReplacedCount} oversized tool results`),yield C("tool_result_budget",`${A.newlyReplacedCount} persisted`))}{let A=gn(v,o);v=A.messages,A.removedCount>0&&(y.info(`snip: removed ${A.removedCount} messages, freed ~${A.tokensFreed} tokens`),yield C("snip",`${A.removedCount} messages`))}{let P=new Je().compress(v,0);P.droppedCount>0&&(v=P.messages,y.info(`microcompact: cleared ${P.droppedCount} old tool results`))}if(v=yn(v,r).messages,s.contextWindowTokens>0){let A=s.contextWindowTokens*.75,P=i.getActiveContextCompressionEngine(),S;P?S=await P.compressAsync(v,A,{model:h,sessionId:f}):S=i.compressMessages(v,{budget:A,model:h}),S.droppedCount>0&&(v=S.messages,y.info(`autocompact: ${S.strategy}, dropped ${S.droppedCount}`),yield C("autocompact",`${S.strategy}: ${S.droppedCount} dropped`),yield{type:"lifecycle",turnId:c.turnId,kind:"context_compression",status:"completed",detail:`${S.strategy}: ${S.droppedCount} dropped`},x(),$(a,"context.after_compact",{...c,removedCount:S.droppedCount},y))}return v=ls(v),v}async function*ms(e,t){let{state:n,guardState:o,fallbackModel:r,signal:s,querySource:i,turnId:a,log:c,emitRecovery:f}=t;if(e instanceof Qe&&r)return c.info(`model fallback triggered: ${e.originalModel} -> ${e.fallbackModel}`),yield f("model_fallback",`${e.originalModel} -> ${e.fallbackModel}`),{kind:"continue",patch:{currentModel:e.fallbackModel,consecutive529Errors:0,consecutiveApiRetries:0,transition:void 0}};let h=e instanceof Error?e.message:String(e),y=typeof e?.status=="number"?e.status:void 0;if(!y&&h&&(h.includes("ECONNRESET")||h.includes("EPIPE"))){let x=(n.consecutiveApiRetries??0)+1;return x>we?(c.info(`stale connection retry limit reached (${we}), aborting`),yield{type:"error",turnId:a,error:h,code:"RETRIES_EXHAUSTED",usage:n.totalUsage},{kind:"return"}):(c.info(`stale connection (${h.includes("ECONNRESET")?"ECONNRESET":"EPIPE"}): retrying`),yield f("stale_connection_retry",h.slice(0,80)),{kind:"continue",patch:{consecutiveApiRetries:x,transition:void 0}})}let C=fs({status:y,message:h});if(C!==null)return c.info(`max_tokens overflow: adjusting to ${C}`),o.currentMaxOutputTokens=C,{kind:"continue",patch:{maxOutputTokensOverride:C,transition:void 0}};if(Sn(y)){n.consecutive529Errors++;let x=2,v=r&&n.currentModel!==r;if(n.consecutive529Errors>x&&!v&&!vt())return c.info(`transient ${y} \xD7 ${n.consecutive529Errors}: hard limit reached, aborting`),yield{type:"error",turnId:a,error:`API unavailable after ${n.consecutive529Errors} consecutive ${y} errors`,code:"API_ERROR",usage:n.totalUsage},{kind:"return"};if(n.consecutive529Errors>=Tr&&r&&n.currentModel!==r)return c.info(`529 \xD7 ${n.consecutive529Errors}: triggering fallback to ${r}`),yield f("model_fallback",`529 \xD7 ${n.consecutive529Errors}`),{kind:"continue",patch:{currentModel:r,consecutive529Errors:0,transition:void 0}};if(vt()){let A=_t(n.consecutive529Errors);c.info(`persistent retry: waiting ${A}ms (attempt ${n.consecutive529Errors})`);let P=A;for(;P>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(P/1e3)}s (${y})`};let S=Math.min(P,br);await new Promise(O=>setTimeout(O,S)),P-=S}return{kind:"continue",patch:{transition:void 0}}}if(wn(i)){let P=ds({status:y,message:h})??_t(n.consecutive529Errors);return c.info(`transient ${y}: retry in ${P}ms`),yield f("retry",`${y} retry in ${P}ms`),await new Promise(S=>setTimeout(S,P)),{kind:"continue",patch:{transition:void 0}}}c.info(`background source ${i}: not retrying ${y}`)}return{kind:"streamError",streamError:{status:y,message:h}}}import{readdirSync as Ts,statSync as nt}from"node:fs";var Rl=/create\s+(?:a\s+)?file|write\s+(?:a\s+)?file|make\s+(?:a\s+)?file|generate\s+(?:a\s+)?file|new\s+file/i,xl=/\bfix\b|implement|modify|update|repair/i,Cs=/[A-Za-z]:[\\/](?:[^\s"'`<>|,\uFF0C\u3001;\uFF1B\u3002]+[\\/])*[^\s"'`<>|,\uFF0C\u3001;\uFF1B\u3002]+\.[A-Za-z0-9]{1,12}/g,gs=/\s*[,\uFF0C\u3001;\uFF1B]\s*([^\s"'`<>|,\uFF0C\u3001;\uFF1B\u3002\\/]+\.[A-Za-z0-9]{1,12})/gy,_l=/\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,vl=/(?:^|[\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,Al=/(?:^|[\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,wl=/(?:^|[\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,Sl=/\b(?:create|generate|write|produce|save|output|deliver|deliverables?|artifacts?|required|required files?|must generate|self-verify)\b|(?:生成|创建|写入|输出|保存|交付|产物|文件|必须|自检|验证)/i,Ml=/\bpreviews?[\\/]\s*(?:containing|with|under|for)?[^.。;;\n]*(?:rendered|preview|previews|check|evidence|verify|verification)\b/i,El=/(?:do\s*not|don'?t|never|不要|不能|别|勿|禁止|不准|不得)[^.。;;\n]{0,14}(?:create|write|make|produce|generate|生成|创建|写入|写出|建立|新建)/i;function K(e){return e.trim().replace(/[),.;:\uFF0C\u3002\uFF1B\u3001]+$/u,"").replace(/\\/g,"/").toLowerCase()}function ks(e){return e.trim().replace(/[),.;:\uFF0C\u3002\uFF1B\u3001]+$/u,"").replace(/\\/g,"/").replace(/\/+$/u,"")}function hs(e){return/\.[A-Za-z0-9]{1,12}$/u.test(e.replace(/[),.;:\uFF0C\u3002\uFF1B\u3001]+$/u,""))}function ys(e,t,n){let o=Math.max(e.lastIndexOf(".",t),e.lastIndexOf(`
26
+ `,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+${vs(n)}\\b`,"i").test(s)}function Zn(e){return e.replace(/https?:\/\/\S+/gu," ")}function Et(e){let t=new Set,n=[],o=r=>{let s=r.replace(/[),.;:\uFF0C\u3002\uFF1B]+$/u,""),i=K(s);t.has(i)||(t.add(i),n.push(s))};for(let r of e){if(r.role!=="user"||typeof r.content!="string")continue;let s=Zn(r.content);for(let i of s.matchAll(Cs)){let a=i[0],c=(i.index??0)+a.length;if(s[c]==="/"||s[c]==="\\")continue;o(a);let f=a.replace(/\\/g,"/"),h=f.lastIndexOf("/");if(h>=0){let y=f.slice(0,h+1);gs.lastIndex=c;let C;for(;(C=gs.exec(s))!==null;)o(`${y}${C[1]}`)}}}for(let r of e){if(r.role!=="user"||typeof r.content!="string")continue;let s=Zn(r.content);if(!Sl.test(s))continue;let i=Array.from(s.matchAll(_l)).map(c=>ks(c[1]??"")).filter(c=>c&&!hs(c));if(i.length===0)continue;let a=i[i.length-1];for(let c of s.matchAll(vl)){let f=c[1];f&&(ys(s,c.index??0,f)||o(`${a}/${f}`))}for(let c of s.matchAll(Al)){let f=c[1];f&&(ys(s,c.index??0,f)||o(`${a}/${f}`))}for(let c of s.matchAll(wl)){let f=c[1];f&&(hs(f)||/(?:assets[\\/]generated|screenshots(?:[\\/]|$)|previews(?:[\\/]|$))/i.test(f)&&/\b(?:generated|bitmap|png|screenshots?|preview|previews|evidence|assets?|containing)\b/i.test(s)&&o(`${a}/${f}/*`))}Ml.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 Jn(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 c=a,f=c.id,h=c.function;typeof f=="string"&&typeof h?.name=="string"&&n.set(f,h.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 c=a,f=c.id;if(typeof f=="string"&&t.size>0&&!t.has(f))continue;let h=c.function;if(!(typeof h?.name!="string"||typeof h.arguments!="string"))try{let y=JSON.parse(h.arguments);if(h.name==="write"||h.name==="edit"){for(let C of["path","filePath","file_path"]){let x=y[C];typeof x=="string"&&o.push(x)}continue}if(h.name==="exec"){let C=y.command;typeof C=="string"&&o.push(C)}}catch{h.name==="exec"&&o.push(h.arguments)}}}return o.join(`
27
+ `).replace(/\\/g,"/").toLowerCase()}function Qn(e){try{if(e.endsWith("/*")){let n=e.slice(0,-2);return Ts(n,{withFileTypes:!0}).some(r=>{if(!r.isFile())return!1;try{return nt(`${n}/${r.name}`).size>0}catch{return!1}})}let t=nt(e);return t.isFile()&&t.size>0}catch{return!1}}function Il(e,t){let n=K(t);if(!n.endsWith("/*"))return e.includes(n);let o=n.slice(0,-1);return e.includes(o)}function Pl(e){let t=new Set;for(let n of e){let o=n,r=Array.isArray(o.tool_calls)?o.tool_calls:[];for(let s of r){let i=s,a=i.id,c=i.function;typeof a=="string"&&c?.name==="agent"&&t.add(a)}}for(let n of e){let o=n,r=o.tool_call_id;if(typeof r=="string"&&t.has(r)&&It(o))return!0}return!1}function Ol(e){let t=_s(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 Nl(e){let t=ks(e),n=t.lastIndexOf("/");return n>=0?t.slice(0,n):""}function Ll(e){if(e.length===0)return"";let t=e.map(o=>Nl(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 Fl(e,t){let n=K(e);return t.some(o=>{let r=K(o);return r.endsWith("/*")?n.startsWith(r.slice(0,-1)):n===r})}function Rs(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,c=a.id,f=a.function;if(typeof c!="string"||f?.name!=="write"&&f?.name!=="edit"||typeof f.arguments!="string")continue;let h=Pt(f.arguments);if(!h)continue;let y=Ot(h);y&&n.set(c,y)}}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 Bl(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 Dl(e){return[...new Set([...e.matchAll(/\bGoal\s+\d+\b/gi)].map(t=>t[0].replace(/\s+/g," ").replace(/\bgoal\b/i,"Goal")))]}function $l(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,c=a.id,f=a.function;if(typeof c!="string"||f?.name!=="write"&&f?.name!=="edit"||typeof f.arguments!="string")continue;let h=Pt(f.arguments);if(!h)continue;let y=Ot(h)??"",C=As(h);(/\bartifact[-_\s]?index\b/i.test(y)||/\bartifact[-_\s]?index\b/i.test(C))&&n.set(c,C)}}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 Ul(e){let t=_s(e.inputMessages);if(!Bl(t))return[];let n=$l(e.messages).at(-1);if(!n)return[];let o=[],r=Dl(t).filter(c=>!new RegExp(`\\b${vs(c)}\\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(c=>/\bno\s+[^|\n]*(?:found|evidence|files?)\b/i.test(c)&&!/\b(?:not\s+verified|unverified|unknown|not\s+checked|search\s+scope|checked\s+path)\b/i.test(c));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 jl(e){let t=[],n=o=>{let r;try{r=Ts(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{nt(i).size>0&&t.push(i)}catch{}}};try{if(!nt(e).isDirectory())return[]}catch{return[]}return n(e),t}function ql(e,t){if(!Ol(e))return[];let n=Et(e),o=n.filter(i=>!K(i).endsWith("/*"));if(o.length<2)return[];let r=Ll(o);if(!r||r.split("/").length<3)return[];let s=K(r);return[...new Set([...Rs(t),...jl(r)])].filter(i=>K(i).startsWith(`${s}/`)&&!Fl(i,n)&&Qn(i))}function xs(e,t){let n=Et(e);if(n.length===0)return[];let o=Jn(t);return n.filter(r=>!Il(o,r))}function tt(e){return eo(e).fail}function zl(e){return e.replace(/[.,;:,。;:、!?]+$/u,"")}function Mt(e){if(!e)return!1;let t=zl(e);return/^[A-Za-z0-9_.:-]+$/u.test(t)&&/[0-9_:-]/u.test(t)}function eo(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))Mt(s[2])&&(n=`${s[1].toUpperCase()} ${t(s[2])}`);for(let s of r.content.matchAll(/\bFAIL\s+([A-Za-z0-9_.:-]+)/gi))Mt(s[1])&&(o=`FAIL ${t(s[1])}`);for(let s of r.content.matchAll(/\b([A-Za-z0-9_.:-]+)\s+(DONE|PASS)\b/gi))Mt(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))Mt(s[1])&&(o=`${t(s[1])} FAIL`)}return{done:n,fail:o}}function _s(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 vs(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Pe(e){let t=xs(e.inputMessages,e.messages).filter(o=>!Qn(o));return t.length===0?void 0:`${tt(e.inputMessages)??"FAIL"} ${e.reason}. Missing required output file evidence: ${t.join(", ")}`}function Pt(e){try{let t=JSON.parse(e);return t&&typeof t=="object"&&!Array.isArray(t)?t:null}catch{return null}}function Ot(e){for(let t of["path","filePath","file_path"]){let n=e[t];if(typeof n=="string"&&n.trim())return n}}function As(e){for(let t of["content","newContent","replacement","text"]){let n=e[t];if(typeof n=="string")return n}return""}function ws(e){let t=e.toolCall.function.name;if(t!=="write"&&t!=="edit")return;let n=eo(e.inputMessages);if(!n.done)return;let o=Pt(e.toolCall.function.arguments);if(!o)return;let r=Ot(o),s=As(o);if(!r||!s.includes(n.done))return;let i=Et(e.inputMessages);if(i.length<2)return;let a=K(r);if(!i.some(y=>K(y)===a))return;let f=Jn(e.messages),h=i.filter(y=>K(y)!==a).filter(y=>!f.includes(K(y)));if(h.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: ${h.join(", ")}. Create or verify the missing files first, or report the requested FAIL marker with the real reason.`}function Ee(e,t){return{role:"assistant",content:e,...t.length>0&&{thinkingBlocks:[...t]}}}function Hl(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 Gl(e){let t=[...e].reverse().find(n=>n.role==="tool");t&&typeof t.content=="string"&&(t.content+=`
27
28
 
28
- \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 Ie(e,t,n,o){return{reason:e,messages:[...t,n,o],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}}}function Cs(e){try{return et(e).isFile()}catch{return!1}}function zl(e,t){let n=new Map;for(let s of e){if(s.role!=="user"||typeof s.content!="string")continue;let i=Yn(s.content);if(Al.test(i))for(let a of i.matchAll(fs)){let u=a[0].replace(/[),.;:,。;]+$/u,""),p=K(u);p&&n.set(p,u)}}if(n.size===0)return[];let o=Zn(t),r=[];for(let[s,i]of n)(o.includes(s)||Cs(i))&&r.push(s);return r}var Hl="File not found:",us=/\b(?:create|write|make|generate|produce|save|output|deliver|initialize|init|ensure|touch|scaffold|build|set\s+up)\b|生成|创建|写入|写出|新建|建立|保存|输出|交付|初始化|确保/i,Gl=/\b(?:if|when|unless)\b[^.。;;\n]{0,40}(?:missing|not\s+exist|does\s*n['o]?t\s+exist|absent|no\s+such)|(?:如果|若|要是|倘若)[^.。;;\n]{0,24}(?:不存在|没有|缺失|不在|未创建)/i;function Wl(e,t){let n=t.slice(t.lastIndexOf("/")+1),o=/[.。;;!?!?\n]/u;for(let r of e){if(r.role!=="user"||typeof r.content!="string")continue;let s=r.content.replace(/\\/g,"/").toLowerCase(),i=n.length>3&&n!==t?[t,n]:[t];for(let a of i){let u=0;for(;;){let p=s.indexOf(a,u);if(p===-1)break;u=p+1;let y=p;for(;y>0&&!o.test(s[y-1]);)y--;let g=p+a.length;for(;g<s.length&&!o.test(s[g]);)g++;let k=r.content.slice(y,g);if(us.test(k))return!0}}}for(let r of e){if(r.role!=="user"||typeof r.content!="string")continue;let s=r.content.replace(/\\/g,"/").toLowerCase();if((s.includes(t)||n.length>3&&n!==t&&s.includes(n))&&us.test(r.content)&&Gl.test(r.content))return!0}return!1}function Vl(e){let t=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!=="read"||typeof p.arguments!="string")continue;let y=Et(p.arguments),g=y?It(y):void 0;g&&t.set(u,g)}}let n=new Map;for(let o of e){let r=o;if(r.role!=="tool")continue;let s=r.tool_call_id;if(typeof s!="string")continue;let i=t.get(s);if(!i)continue;let a=typeof r.content=="string"?r.content:"";(r.is_error===!0||a.startsWith("Error:"))&&a.includes(Hl)&&n.set(K(i),i)}return n}function Xl(e,t){let n=Vl(t);if(n.size===0)return[];let o=new Set(ms(t).map(K)),r=[];for(let[s,i]of n)Wl(e,s)||(o.has(s)||Cs(i))&&r.push(s);return r}function eo(e){let t=e.inputMessages.find(_=>_.role==="user"),n=typeof t?.content=="string"?t.content:"",o=Tl.test(n)||Cl.test(n)&&St(e.inputMessages).length>0,r=e.distinctToolNames.has("write")||e.distinctToolNames.has("edit"),s=Qn(e.inputMessages),i=zl(e.inputMessages,e.messages);if(i.length>0){e.log.info(`forbidden-file-creation guard: agent wrote ${i.length} file(s) the user forbade creating`);let _=Qe(e.inputMessages),A={role:"user",content:`You created a file the request explicitly forbade creating: ${i.join(", ")}. That is a constraint violation, not success \u2014 do NOT claim "completed" or "handled". Delete the file you wrongly created, then report ${_??"FAILED"} with the real reason: the task could not be done without violating the stated constraint. Do not fabricate a successful outcome.`};return Ie("forbidden_file_creation",e.messages,Ee(e.finalText,e.thinkingBlocks),A)}let a=Xl(e.inputMessages,e.messages),u=s.fail!==void 0&&e.finalText.includes(s.fail);if(a.length>0&&!u){e.log.info(`self-created-read-target guard: agent created ${a.length} file(s) it had read as not-found`);let _=Qe(e.inputMessages),A={role:"user",content:"You were asked to read "+a.join(", ")+`, but your read showed the file did not exist; you then created it yourself. Manufacturing an input you were told to read is not success \u2014 do NOT claim "completed" or "handled". Delete the file you wrongly created, then report ${_??"FAILED"} with the real reason: the file does not exist and the task cannot be done without fabricating it.`};return Ie("self_created_read_target",e.messages,Ee(e.finalText,e.thinkingBlocks),A)}let p=Ml(e.messages),y=gs(e.inputMessages,e.messages).filter(_=>!(p&&Jn(_)));if(y.length>0&&e.totalToolCallCount>0){if(s.fail!==void 0&&e.finalText.includes(s.fail))return null;e.log.info(`explicit required file verification: ${y.length} file(s) missing`);let _=Qe(e.inputMessages),A={role:"user",content:`Before completing, verify that every explicitly requested output file exists and is non-empty. Missing required output file evidence: ${y.join(", ")}. Create the missing files now, or if you cannot complete them, respond with ${_??"FAIL"} and the real reason. Do not claim completion until the missing files are handled.`};return Ie("explicit_required_file_verification",e.messages,Ee(e.finalText,e.thinkingBlocks),A)}let g=$l(e.inputMessages,e.messages);if(g.length>0&&e.totalToolCallCount>0){if(s.fail!==void 0&&e.finalText.includes(s.fail))return null;e.log.info(`explicit extra file verification: ${g.length} unexpected file(s)`);let _=Qe(e.inputMessages),A={role:"user",content:`The latest request asked for exactly the listed output artifacts, but extra files were produced under the output root: ${g.join(", ")}. Remove the extra files now, move scratch work outside the deliverable directory, or if you cannot make the output exact, respond with ${_??"FAIL"} and the real reason. Do not claim completion while extra deliverables remain.`};return Ie("explicit_extra_file_verification",e.messages,Ee(e.finalText,e.thinkingBlocks),A)}let k=Bl({inputMessages:e.inputMessages,messages:e.messages,finalText:e.finalText});if(k.length>0&&e.totalToolCallCount>0){if(s.fail!==void 0&&e.finalText.includes(s.fail))return null;e.log.info(`artifact index evidence verification: ${k.length} issue(s)`);let _={role:"user",content:"Before completing, correct the artifact index against the actual evidence scope. "+k.map(A=>A.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, finish with the final status contract."};return Ie("artifact_index_evidence_verification",e.messages,Ee(e.finalText,e.thinkingBlocks),_)}if(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&&ql(e.messages);let _={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 Ie("file_action_verification",e.messages,Ee(e.finalText,e.thinkingBlocks),_)}if(e.totalToolCallCount>=3&&e.distinctToolNames.has("write")&&e.messages.filter(jl).length>=3){e.log.info("AP3 verification nudge: 3+ files created, injecting completeness check");let A={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 Ie("multi_file_skeleton_verification",e.messages,Ee(e.finalText,e.thinkingBlocks),A)}return null}function Kl(e,t){return{role:"assistant",content:e,...t.length>0&&{thinkingBlocks:[...t]}}}async function ks(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,Kl(e.finalText,e.thinkingBlocks),o],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}}}return null}var Yl=5;function Zl(e){return e.inputTokens+e.outputTokens+(e.reasoningTokens??0)}function Jl(e,t){return{role:"assistant",content:e,...t.length>0&&{thinkingBlocks:[...t]}}}function Rs(e){if(!e.tokenBudget||e.tokenBudget<=0||e.budgetContinuationCount>=Yl)return null;let t=Zl(e.totalUsage),n=t/e.tokenBudget*100,o=t-e.lastBudgetGlobalTokens;if(e.budgetContinuationCount>=mr&&o<hn&&e.lastBudgetDeltaTokens<hn)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,Jl(e.finalText,e.thinkingBlocks),i],budgetContinuationCount:s,lastBudgetDeltaTokens:o,lastBudgetGlobalTokens:t,recoveryDetail:`${Math.round(n)}% used (#${s})`,transition:{reason:"token_budget_continuation"}}}function to(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 yn(t,{tools:[...e.distinctToolNames],projectRoot:e.projectRoot})}function xs(e){let t=Ql(e.text);if(!t.trim())return null;let n=[...new Set(e.enabledToolNames.filter(o=>o.trim()))].sort((o,r)=>r.length-o.length);for(let o of n)if(ec(t,o)||tc(t,o))return{toolName:o};return null}function Ql(e){return e.replace(/```[\s\S]*?```/g,"")}function ec(e,t){let n=_s(t);return new RegExp(`<\\s*${n}\\b[\\s\\S]*?<\\s*\\/\\s*${n}\\s*>`,"i").test(e)}function tc(e,t){let n=_s(t);return new RegExp(`\\b(?:call|use|invoke|run)\\s+${n}\\s*\\(|\\b${n}\\s*\\(`,"i").test(e)}function _s(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var tt="*";function vs(e,t){let n=[],o=[];for(let r of e){let s=Ms(r.function.name,r.function.arguments),i=Es(r.function.name,tt),a=Math.max(t.get(s)??0,t.get(i)??0);a>=bt?o.push({call:r,failCount:a,error:`Tool "${r.function.name}" has failed ${a} times this turn for this target. The target likely does not exist. Stop trying variations of the same target and switch to a verified target or report the issue to the user.`}):n.push(r)}return{allowed:n,blocked:o}}function ws(){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 As(e){if(e.ok&&!e.softEmpty)return;let t=Ms(e.toolName,e.toolArguments),n=e.toolFailureCounts.get(t)??0;e.toolFailureCounts.set(t,n+1)}function Ss(e){let t=[];for(let[n,o]of e.toolFailureCounts)if(o>=bt&&(e.snapshot.get(n)??0)<bt){let{toolName:r,target:s}=rc(n);t.push({role:"user",content:`Tool "${r}" has now failed/returned empty results ${o} times for target "${s}". That target clearly does not exist or is not useful. Do NOT retry variations of the same target. Report the result to the user immediately.`})}return t}function Ms(e,t){return Es(e,nc(e,t))}function nc(e,t){let n=oc(t);return e==="read"||e==="write"||e==="edit"||e==="patch"?no(n?.path??n?.file_path??n?.filePath):e==="search"?no([n?.mode,n?.path,n?.fileGlob,n?.pattern].filter(Boolean).join("|")):e==="exec"?no(n?.command):tt}function oc(e){if(e)try{let t=JSON.parse(e);return t&&typeof t=="object"&&!Array.isArray(t)?t:void 0}catch{return}}function no(e){return typeof e=="string"&&e.trim()?e.trim().replaceAll("\\","/").toLowerCase():tt}function Es(e,t){return`${e}::${t}`}function rc(e){let t=e.indexOf("::");return t<0?{toolName:e,target:tt}:{toolName:e.slice(0,t),target:e.slice(t+2)||tt}}var sc=new Set(["find","grep","rg","ag","ack","locate","which","whereis"]),ic=new Set(["cat","head","tail","less","more","wc","stat","file","sed","strings","jq","awk","cut","sort","uniq","tr"]),ac=new Set(["ls","tree","du","dir","gci","get-childitem"]),lc=new Set(["grep","rg","ag","ack","find"]);var cc=new Set(["mv","cp","rm","mkdir","rmdir","chmod","chown","chgrp","touch","ln","cd","export","unset","wait"]);function uc(e){let n=e.replace(/\\\n/g," ").trim().split(/[|;&]/).shift()?.trim()??"";if(!n)return null;let o=n.split(/\s+/),r=0;for(;r<o.length&&/^[A-Za-z_]\w*=/.test(o[r]);)r++;let s=/^(?:timeout|time|nice|nohup|stdbuf|command|builtin|exec)$/;for(;r<o.length;){let p=o[r];if(s.test(p)){for(r++;r<o.length&&/^[-+]/.test(o[r]);)r++;r<o.length&&/^\d+(?:\.\d+)?[smhd]?$/.test(o[r])&&r++;continue}break}if(r>=o.length)return null;let i=o[r],a=i.lastIndexOf("/");return(a>=0?i.slice(a+1):i).toLowerCase()}function dc(e){return/(?:^|[;&|])\s*(?:cd|pushd|popd)\b/.test(e)}function Is(e){let t=uc(e),n=t!==null&&sc.has(t),o=t!==null&&ic.has(t),r=t!==null&&ac.has(t),s=t!==null&&cc.has(t),i=/(?:[^2]>|^>|\|>)/.test(e),a=dc(e),u=(n||o||r)&&!i&&!a;return{firstCommand:t,isSearch:n,isRead:o,isList:r,isSilent:s,isConcurrencySafe:u,isReadOnly:u}}function Ps(e){return e.isRead?!0:e.firstCommand!==null&&lc.has(e.firstCommand)}function Os(e){return e.isRead?"Command blocked: read local file contents with the read tool, not exec (cat/head/tail/sed/etc.). Reserve exec for system/build/test commands.":'Command blocked: search local file contents with the search tool (mode "content"), not exec (grep/find/rg/etc.). Reserve exec for system/build/test commands.'}function mc(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 gc(e,t){let n=hc(t);if(!n)return null;let o=yc(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 hc(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 yc(e){return e.toLocaleLowerCase().replace(/[^\p{L}\p{N}\s]+/gu," ").replace(/\s+/g," ").trim()}var Gs=/\b(?:only\s+(?:answer|return|output)|answer\s+only|return\s+only|output\s+only)\b[\s\S]{0,80}\b(?:token|contents?|content|value|result)\b|(?:\u53ea|\u4ec5|\u50c5)(?:\u56de\u7b54|\u56de\u590d|\u56de\u8986|\u8f93\u51fa|\u8fd4\u56de)[^\n\u3002\uff1b;]{0,40}(?:token|\u5185\u5bb9|\u503c|\u7ed3\u679c)/i,bc=/(?:JSON|json)[\s\S]{0,120}(?:top[- ]level|\u9876\u5c42)[\s\S]{0,80}\b([A-Za-z_$][\w$.-]*)\b[\s\S]{0,40}(?:field|key|property|\u5b57\u6bb5|\u5c5e\u6027)/i,Tc=/(?:\bonly\s+(?:answer|return|output)\b|(?:\u53ea|\u4ec5|\u50c5)(?:\u56de\u7b54|\u56de\u590d|\u56de\u8986|\u8f93\u51fa|\u8fd4\u56de))\s*[::]\s*([A-Za-z0-9_.:-]+:\s*)<[^>\n]+>/i,Cc=/(?:memory\s+graph|MCP\s+memory\s+graph|\u8bb0\u5fc6\u56fe\u8c31|\u5f53\u524d\u56fe\u8c31)[\s\S]{0,120}(?:entity|\u5b9e\u4f53)\s+([A-Za-z0-9_.:-]+)/i,kc=/\b([A-Z0-9_]*MCP_GRAPH_CHECK[A-Z0-9_]*_20260626)\b/;function Ws(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 Vs(e,t){let n=new Map;for(let o of e){if(o.role!=="assistant")continue;let r=o.tool_calls;if(Array.isArray(r))for(let s of r){if(!s||typeof s!="object")continue;let i=s,a=typeof i.id=="string"?i.id:"",u=i.function&&typeof i.function=="object"?i.function:void 0,p=typeof u?.name=="string"?u.name:"";a&&p&&n.set(a,p)}}for(let o=e.length-1;o>=0;o--){let r=e[o];if(r?.role!=="tool")continue;let s=typeof r.tool_call_id=="string"?r.tool_call_id:"";if(n.get(s)!==t)continue;let i=typeof r.content=="string"?r.content.trim():"";if(!(!i||i.startsWith("Error: ")))return i}return null}function Rc(e,t){let n=Ws(e),o=Vs(t,"read");if(!o||o.length>4e3)return null;let r=xc(n,o);return r||(Gs.test(n)?o:null)}function xc(e,t){let n=bc.exec(e)?.[1];if(!n)return null;let o=Tc.exec(e)?.[1]??"";if(!o&&!Gs.test(e))return null;let r;try{r=JSON.parse(t)}catch{return null}if(!r||typeof r!="object"||Array.isArray(r))return null;let s=r;if(!Object.hasOwn(s,n))return null;let i=s[n],a=typeof i=="string"?i:JSON.stringify(i);return typeof a!="string"?null:`${o}${a}`}function _c(e,t){let n=Ws(e),o=Cc.exec(n)?.[1],r=kc.exec(n)?.[1];if(!o||!r)return null;let s=Vs(t,"mcp__memory__read_graph");if(!s)return null;let i=s.toLowerCase().includes(o.toLowerCase());return`${r}: ${i?"yes":"no"}`}function C(e){return[...new Set(e.map(t=>t.function.name))].sort()}function je(e){return[...e].sort((t,n)=>t.function.name.localeCompare(n.function.name))}function Pt(e){let t=new Set,n=[];for(let o of e){let r=`${o.name}\0${o.reason}`;t.has(r)||(t.add(r),n.push(o))}return n.sort((o,r)=>`${o.name}:${o.reason}`.localeCompare(`${r.name}:${r.reason}`))}function vc(e,t,n,o,r){let s=r.filter(i=>i.name===e).sort((i,a)=>Ns(i.reason)-Ns(a.reason))[0];return t.includes(e)?s?`${e}=policy-filtered:${s.reason}`:n.includes(e)?o.includes(e)?`${e}=called`:`${e}=enabled-not-used`:`${e}=policy-filtered:not-enabled`:`${e}=not-exposed`}function Ns(e){return e==="invalid-arguments"?0:e==="blocked-by-policy"||e.startsWith("policy-suppressed:")?1:e==="confirmation-timeout"?2:e==="dedicated-tool-required"?3:e==="read-only-context-pack"?4:e==="not-offered"?5:e==="read-cycle-policy"?6:e==="identical-repeat-policy"?7:e==="variant-failure-policy"?8:10}function wc(e){let t=typeof e.blockReason=="string"?e.blockReason:void 0;if(e.blocked&&/confirmation timed out/i.test(t??""))return"confirmation-timeout";if(e.blocked)return"blocked-by-policy";let n=typeof e.details?.error=="string"?e.details.error:void 0;if(n==="dedicated_tool_required")return"dedicated-tool-required";if(n==="existing_file_update_tool_required")return"existing-file-update-tool-required";if(n==="invalid_arguments")return"invalid-arguments";if(n==="blocked_global_process_kill")return"global-process-kill-blocked";if(n==="blocked_by_guard")return"blocked-by-policy"}function Ls(e){let t=new Set(e.map(n=>n.function.name));return t.has("read")||t.has("search")||t.has("write")||t.has("edit")||t.has("patch")}function Ce(e,t){return t.size===0?[...e]:e.filter(n=>!t.has(n.function.name))}var Ac=new Set(["edit","patch","read"]);function Fs(e,t){let n=e.filter(o=>Ac.has(o.function.name)&&!t.has(o.function.name));return n.length>0?je(n):e.filter(o=>o.function.name!=="write"&&!t.has(o.function.name))}function oo(e,t){let n=new Set(t);return e.filter(o=>!n.has(o))}function Sc(e){if(!e)return;let t=e.trim();return(t.match(/Last error:\s*(.+?)\.\s*Do not retry\./s)?.[1]?.trim()??t).slice(0,600).trim()||void 0}function Bs(e){let n=fe(e)?.command;return typeof n=="string"&&n.trim()?n:void 0}var Lt=5174;function Ds(e,t){let n=String(t);return[new RegExp(`(?:^|\\s)--port(?:=|\\s+)${n}(?:\\s|$)`),new RegExp(`(?:^|\\s)-p(?:=|\\s+)${n}(?:\\s|$)`),new RegExp(`(?:localhost|127\\.0\\.0\\.1|0\\.0\\.0\\.0|\\[?::1\\]?):${n}\\b`,"i")].some(r=>r.test(e))}function Mc(e){return/\b(vite|npx\s+vite|pnpm\s+(?:run\s+)?dev|npm\s+(?:run\s+)?dev|yarn\s+(?:run\s+)?dev)\b/i.test(e)}function Xs(e){return/(?:^|\s)--strictPort(?:\s|$)/.test(e)}function Ec(e){if(Xs(e))return e;let t=/\s+(?:\d?>&\d|\d?>\s*\S+|>\s*\S+|<\s*\S+).*$/.exec(e);return!t||t.index===void 0?`${e.trim()} --strictPort`:`${e.slice(0,t.index).trim()} --strictPort${e.slice(t.index)}`}function $s(e,t){let n=fe(e)??{};return JSON.stringify({...n,command:t})}function Ic(e){let t=e.replace(/^(?:\s*sleep\s+\d+(?:\.\d+)?\s*(?:&&|;)\s*)+/i,"").trim();return t&&t!==e.trim()?t:null}function Pc(e){return Ds(e,Lt)?{action:"block",error:"Command blocked: port 5174 is reserved for the Xiaozhi Claw frontend. Start generated apps on an explicit non-5174 port and include --strictPort when using Vite."}:Mc(e)&&Ds(e,Lt-1)&&!Xs(e)?{action:"rewrite",command:Ec(e)}:null}function Ft(e){let t=[];for(let n of e.devServerUrls)if(!(!/^https?:\/\/(?:localhost|127\.0\.0\.1):\d+\b/i.test(n)||new RegExp(`:${Lt}\\b`).test(n)))try{let o=new URL(n);if(/^\/api(?:\/|$)/i.test(o.pathname))continue;let r=`${o.protocol}//${o.host}${o.pathname==="/"?"":o.pathname}`;t.includes(r)||t.push(r)}catch{continue}return t}function Us(e){let t=Ft(e);return`Browser-visible acceptance is still missing. Do not finish from source inspection or web_fetch output. Use exec to run real browser automation (Playwright or an equivalent browser runner) against ${t.length>0?t.join(", "):"the generated localhost dev server URL"}. Do not run a plain \`node verify.js\` script that imports \`@playwright/test\` unless that package is installed in the target project. Prefer one of these reliable forms: (a) if \`node -e "require.resolve('playwright')"\` succeeds, run a plain Node script importing \`chromium\` from \`playwright\`; or (b) write a Playwright spec and run it with \`npx -y playwright@latest test <spec-file>\` instead of \`node <spec-file>\`. If a localhost URL responds, reuse that running service for browser verification; do not treat a later EADDRINUSE restart attempt as proof that the app is unavailable. Only switch to a new explicit non-5174 port when the observed localhost URL is unreachable or serves the wrong app. Verify rendered visible UI, app-specific routes/screens, and requested interactions; default HTML fetches, bundled JS inspection, and static source review do not count as browser evidence. After the browser automation succeeds, report the exact visible assertions from the tool result.`}function Oc(e){let t=e.buildFailureEvidence[0];return"The test/build you ran is still FAILING, so the task is not complete. "+(t?`Last failing output:
29
+ \u26A0\uFE0F 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 Ie(e,t,n,o){return{reason:e,messages:[...t,n,o],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}}}function Ss(e){try{return nt(e).isFile()}catch{return!1}}function Wl(e,t){let n=new Map;for(let s of e){if(s.role!=="user"||typeof s.content!="string")continue;let i=Zn(s.content);if(El.test(i))for(let a of i.matchAll(Cs)){let c=a[0].replace(/[),.;:,。;]+$/u,""),f=K(c);f&&n.set(f,c)}}if(n.size===0)return[];let o=Jn(t),r=[];for(let[s,i]of n)(o.includes(s)||Ss(i))&&r.push(s);return r}var Vl="File not found:",bs=/\b(?:create|write|make|generate|produce|save|output|deliver|initialize|init|ensure|touch|scaffold|build|set\s+up)\b|生成|创建|写入|写出|新建|建立|保存|输出|交付|初始化|确保/i,Xl=/\b(?:if|when|unless)\b[^.。;;\n]{0,40}(?:missing|not\s+exist|does\s*n['o]?t\s+exist|absent|no\s+such)|(?:如果|若|要是|倘若)[^.。;;\n]{0,24}(?:不存在|没有|缺失|不在|未创建)/i;function Kl(e,t){let n=t.slice(t.lastIndexOf("/")+1),o=/[.。;;!?!?\n]/u;for(let r of e){if(r.role!=="user"||typeof r.content!="string")continue;let s=r.content.replace(/\\/g,"/").toLowerCase(),i=n.length>3&&n!==t?[t,n]:[t];for(let a of i){let c=0;for(;;){let f=s.indexOf(a,c);if(f===-1)break;c=f+1;let h=f;for(;h>0&&!o.test(s[h-1]);)h--;let y=f+a.length;for(;y<s.length&&!o.test(s[y]);)y++;let C=r.content.slice(h,y);if(bs.test(C))return!0}}}for(let r of e){if(r.role!=="user"||typeof r.content!="string")continue;let s=r.content.replace(/\\/g,"/").toLowerCase();if((s.includes(t)||n.length>3&&n!==t&&s.includes(n))&&bs.test(r.content)&&Xl.test(r.content))return!0}return!1}function Yl(e){let t=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,c=a.id,f=a.function;if(typeof c!="string"||f?.name!=="read"||typeof f.arguments!="string")continue;let h=Pt(f.arguments),y=h?Ot(h):void 0;y&&t.set(c,y)}}let n=new Map;for(let o of e){let r=o;if(r.role!=="tool")continue;let s=r.tool_call_id;if(typeof s!="string")continue;let i=t.get(s);if(!i)continue;let a=typeof r.content=="string"?r.content:"";(r.is_error===!0||a.startsWith("Error:"))&&a.includes(Vl)&&n.set(K(i),i)}return n}function Zl(e,t){let n=Yl(t);if(n.size===0)return[];let o=new Set(Rs(t).map(K)),r=[];for(let[s,i]of n)Kl(e,s)||(o.has(s)||Ss(i))&&r.push(s);return r}function to(e){let t=e.inputMessages.find(x=>x.role==="user"),n=typeof t?.content=="string"?t.content:"",o=Rl.test(n)||xl.test(n)&&Et(e.inputMessages).length>0,r=e.distinctToolNames.has("write")||e.distinctToolNames.has("edit"),s=eo(e.inputMessages),i=Wl(e.inputMessages,e.messages);if(i.length>0){e.log.info(`forbidden-file-creation guard: agent wrote ${i.length} file(s) the user forbade creating`);let x=tt(e.inputMessages),v={role:"user",content:`You created a file the request explicitly forbade creating: ${i.join(", ")}. That is a constraint violation, not success \u2014 do NOT claim "completed" or "handled". Delete the file you wrongly created, then report ${x??"FAILED"} with the real reason: the task could not be done without violating the stated constraint. Do not fabricate a successful outcome.`};return Ie("forbidden_file_creation",e.messages,Ee(e.finalText,e.thinkingBlocks),v)}let a=Zl(e.inputMessages,e.messages),c=s.fail!==void 0&&e.finalText.includes(s.fail);if(a.length>0&&!c){e.log.info(`self-created-read-target guard: agent created ${a.length} file(s) it had read as not-found`);let x=tt(e.inputMessages),v={role:"user",content:"You were asked to read "+a.join(", ")+`, but your read showed the file did not exist; you then created it yourself. Manufacturing an input you were told to read is not success \u2014 do NOT claim "completed" or "handled". Delete the file you wrongly created, then report ${x??"FAILED"} with the real reason: the file does not exist and the task cannot be done without fabricating it.`};return Ie("self_created_read_target",e.messages,Ee(e.finalText,e.thinkingBlocks),v)}let f=Pl(e.messages),h=xs(e.inputMessages,e.messages).filter(x=>!(f&&Qn(x)));if(h.length>0&&e.totalToolCallCount>0){if(s.fail!==void 0&&e.finalText.includes(s.fail))return null;e.log.info(`explicit required file verification: ${h.length} file(s) missing`);let x=tt(e.inputMessages),v={role:"user",content:`Before completing, verify that every explicitly requested output file exists and is non-empty. Missing required output file evidence: ${h.join(", ")}. Create the missing files now, or if you cannot complete them, respond with ${x??"FAIL"} and the real reason. Do not claim completion until the missing files are handled.`};return Ie("explicit_required_file_verification",e.messages,Ee(e.finalText,e.thinkingBlocks),v)}let y=ql(e.inputMessages,e.messages);if(y.length>0&&e.totalToolCallCount>0){if(s.fail!==void 0&&e.finalText.includes(s.fail))return null;e.log.info(`explicit extra file verification: ${y.length} unexpected file(s)`);let x=tt(e.inputMessages),v={role:"user",content:`The latest request asked for exactly the listed output artifacts, but extra files were produced under the output root: ${y.join(", ")}. Remove the extra files now, move scratch work outside the deliverable directory, or if you cannot make the output exact, respond with ${x??"FAIL"} and the real reason. Do not claim completion while extra deliverables remain.`};return Ie("explicit_extra_file_verification",e.messages,Ee(e.finalText,e.thinkingBlocks),v)}let C=Ul({inputMessages:e.inputMessages,messages:e.messages,finalText:e.finalText});if(C.length>0&&e.totalToolCallCount>0){if(s.fail!==void 0&&e.finalText.includes(s.fail))return null;e.log.info(`artifact index evidence verification: ${C.length} issue(s)`);let x={role:"user",content:"Before completing, correct the artifact index against the actual evidence scope. "+C.map(v=>v.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, finish with the final status contract."};return Ie("artifact_index_evidence_verification",e.messages,Ee(e.finalText,e.thinkingBlocks),x)}if(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&&Gl(e.messages);let x={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 Ie("file_action_verification",e.messages,Ee(e.finalText,e.thinkingBlocks),x)}if(e.totalToolCallCount>=3&&e.distinctToolNames.has("write")&&e.messages.filter(Hl).length>=3){e.log.info("AP3 verification nudge: 3+ files created, injecting completeness check");let v={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 Ie("multi_file_skeleton_verification",e.messages,Ee(e.finalText,e.thinkingBlocks),v)}return null}function Jl(e,t){return{role:"assistant",content:e,...t.length>0&&{thinkingBlocks:[...t]}}}async function Ms(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,Jl(e.finalText,e.thinkingBlocks),o],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}}}return null}var Ql=5;function ec(e){return e.inputTokens+e.outputTokens+(e.reasoningTokens??0)}function tc(e,t){return{role:"assistant",content:e,...t.length>0&&{thinkingBlocks:[...t]}}}function Es(e){if(!e.tokenBudget||e.tokenBudget<=0||e.budgetContinuationCount>=Ql)return null;let t=ec(e.totalUsage),n=t/e.tokenBudget*100,o=t-e.lastBudgetGlobalTokens;if(e.budgetContinuationCount>=yr&&o<Tn&&e.lastBudgetDeltaTokens<Tn)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,tc(e.finalText,e.thinkingBlocks),i],budgetContinuationCount:s,lastBudgetDeltaTokens:o,lastBudgetGlobalTokens:t,recoveryDetail:`${Math.round(n)}% used (#${s})`,transition:{reason:"token_budget_continuation"}}}function no(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 Cn(t,{tools:[...e.distinctToolNames],projectRoot:e.projectRoot})}function Is(e){let t=nc(e.text);if(!t.trim())return null;let n=[...new Set(e.enabledToolNames.filter(o=>o.trim()))].sort((o,r)=>r.length-o.length);for(let o of n)if(oc(t,o)||rc(t,o))return{toolName:o};return null}function nc(e){return e.replace(/```[\s\S]*?```/g,"")}function oc(e,t){let n=Ps(t);return new RegExp(`<\\s*${n}\\b[\\s\\S]*?<\\s*\\/\\s*${n}\\s*>`,"i").test(e)}function rc(e,t){let n=Ps(t);return new RegExp(`\\b(?:call|use|invoke|run)\\s+${n}\\s*\\(|\\b${n}\\s*\\(`,"i").test(e)}function Ps(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var ot="*";function Os(e,t){let n=[],o=[];for(let r of e){let s=Bs(r.function.name,r.function.arguments),i=Ds(r.function.name,ot),a=Math.max(t.get(s)??0,t.get(i)??0);a>=Ct?o.push({call:r,failCount:a,error:`Tool "${r.function.name}" has failed ${a} times this turn for this target. The target likely does not exist. Stop trying variations of the same target and switch to a verified target or report the issue to the user.`}):n.push(r)}return{allowed:n,blocked:o}}function Ns(){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 Ls(e){if(e.ok&&!e.softEmpty)return;let t=Bs(e.toolName,e.toolArguments),n=e.toolFailureCounts.get(t)??0;e.toolFailureCounts.set(t,n+1)}function Fs(e){let t=[];for(let[n,o]of e.toolFailureCounts)if(o>=Ct&&(e.snapshot.get(n)??0)<Ct){let{toolName:r,target:s}=ac(n);t.push({role:"user",content:`Tool "${r}" has now failed/returned empty results ${o} times for target "${s}". That target clearly does not exist or is not useful. Do NOT retry variations of the same target. Report the result to the user immediately.`})}return t}function Bs(e,t){return Ds(e,sc(e,t))}function sc(e,t){let n=ic(t);return e==="read"||e==="write"||e==="edit"||e==="patch"?oo(n?.path??n?.file_path??n?.filePath):e==="search"?oo([n?.mode,n?.path,n?.fileGlob,n?.pattern].filter(Boolean).join("|")):e==="exec"?oo(n?.command):ot}function ic(e){if(e)try{let t=JSON.parse(e);return t&&typeof t=="object"&&!Array.isArray(t)?t:void 0}catch{return}}function oo(e){return typeof e=="string"&&e.trim()?e.trim().replaceAll("\\","/").toLowerCase():ot}function Ds(e,t){return`${e}::${t}`}function ac(e){let t=e.indexOf("::");return t<0?{toolName:e,target:ot}:{toolName:e.slice(0,t),target:e.slice(t+2)||ot}}var lc=new Set(["find","grep","rg","ag","ack","locate","which","whereis"]),cc=new Set(["cat","head","tail","less","more","wc","stat","file","sed","strings","jq","awk","cut","sort","uniq","tr"]),uc=new Set(["ls","tree","du","dir","gci","get-childitem"]),dc=new Set(["grep","rg","ag","ack","find"]);var fc=new Set(["mv","cp","rm","mkdir","rmdir","chmod","chown","chgrp","touch","ln","cd","export","unset","wait"]);function pc(e){let n=e.replace(/\\\n/g," ").trim().split(/[|;&]/).shift()?.trim()??"";if(!n)return null;let o=n.split(/\s+/),r=0;for(;r<o.length&&/^[A-Za-z_]\w*=/.test(o[r]);)r++;let s=/^(?:timeout|time|nice|nohup|stdbuf|command|builtin|exec)$/;for(;r<o.length;){let f=o[r];if(s.test(f)){for(r++;r<o.length&&/^[-+]/.test(o[r]);)r++;r<o.length&&/^\d+(?:\.\d+)?[smhd]?$/.test(o[r])&&r++;continue}break}if(r>=o.length)return null;let i=o[r],a=i.lastIndexOf("/");return(a>=0?i.slice(a+1):i).toLowerCase()}function mc(e){return/(?:^|[;&|])\s*(?:cd|pushd|popd)\b/.test(e)}function $s(e){let t=pc(e),n=t!==null&&lc.has(t),o=t!==null&&cc.has(t),r=t!==null&&uc.has(t),s=t!==null&&fc.has(t),i=/(?:[^2]>|^>|\|>)/.test(e),a=mc(e),c=(n||o||r)&&!i&&!a;return{firstCommand:t,isSearch:n,isRead:o,isList:r,isSilent:s,isConcurrencySafe:c,isReadOnly:c}}function Us(e){return e.isRead?!0:e.firstCommand!==null&&dc.has(e.firstCommand)}function js(e){return e.isRead?"Command blocked: read local file contents with the read tool, not exec (cat/head/tail/sed/etc.). Reserve exec for system/build/test commands.":'Command blocked: search local file contents with the search tool (mode "content"), not exec (grep/find/rg/etc.). Reserve exec for system/build/test commands.'}function yc(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 bc(e,t){let n=Tc(t);if(!n)return null;let o=Cc(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 Tc(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 Cc(e){return e.toLocaleLowerCase().replace(/[^\p{L}\p{N}\s]+/gu," ").replace(/\s+/g," ").trim()}var Qs=/\b(?:only\s+(?:answer|return|output)|answer\s+only|return\s+only|output\s+only)\b[\s\S]{0,80}\b(?:token|contents?|content|value|result)\b|(?:\u53ea|\u4ec5|\u50c5)(?:\u56de\u7b54|\u56de\u590d|\u56de\u8986|\u8f93\u51fa|\u8fd4\u56de)[^\n\u3002\uff1b;]{0,40}(?:token|\u5185\u5bb9|\u503c|\u7ed3\u679c)/i,kc=/(?:JSON|json)[\s\S]{0,120}(?:top[- ]level|\u9876\u5c42)[\s\S]{0,80}\b([A-Za-z_$][\w$.-]*)\b[\s\S]{0,40}(?:field|key|property|\u5b57\u6bb5|\u5c5e\u6027)/i,Rc=/(?:\bonly\s+(?:answer|return|output)\b|(?:\u53ea|\u4ec5|\u50c5)(?:\u56de\u7b54|\u56de\u590d|\u56de\u8986|\u8f93\u51fa|\u8fd4\u56de))\s*[::]\s*([A-Za-z0-9_.:-]+:\s*)<[^>\n]+>/i,xc=/(?:memory\s+graph|MCP\s+memory\s+graph|\u8bb0\u5fc6\u56fe\u8c31|\u5f53\u524d\u56fe\u8c31)[\s\S]{0,120}(?:entity|\u5b9e\u4f53)\s+([A-Za-z0-9_.:-]+)/i,_c=/\b([A-Z0-9_]*MCP_GRAPH_CHECK[A-Z0-9_]*_20260626)\b/;function ei(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 ti(e,t){let n=new Map;for(let o of e){if(o.role!=="assistant")continue;let r=o.tool_calls;if(Array.isArray(r))for(let s of r){if(!s||typeof s!="object")continue;let i=s,a=typeof i.id=="string"?i.id:"",c=i.function&&typeof i.function=="object"?i.function:void 0,f=typeof c?.name=="string"?c.name:"";a&&f&&n.set(a,f)}}for(let o=e.length-1;o>=0;o--){let r=e[o];if(r?.role!=="tool")continue;let s=typeof r.tool_call_id=="string"?r.tool_call_id:"";if(n.get(s)!==t)continue;let i=typeof r.content=="string"?r.content.trim():"";if(!(!i||i.startsWith("Error: ")))return i}return null}function vc(e,t){let n=ei(e),o=ti(t,"read");if(!o||o.length>4e3)return null;let r=Ac(n,o);return r||(Qs.test(n)?o:null)}function Ac(e,t){let n=kc.exec(e)?.[1];if(!n)return null;let o=Rc.exec(e)?.[1]??"";if(!o&&!Qs.test(e))return null;let r;try{r=JSON.parse(t)}catch{return null}if(!r||typeof r!="object"||Array.isArray(r))return null;let s=r;if(!Object.hasOwn(s,n))return null;let i=s[n],a=typeof i=="string"?i:JSON.stringify(i);return typeof a!="string"?null:`${o}${a}`}function wc(e,t){let n=ei(e),o=xc.exec(n)?.[1],r=_c.exec(n)?.[1];if(!o||!r)return null;let s=ti(t,"mcp__memory__read_graph");if(!s)return null;let i=s.toLowerCase().includes(o.toLowerCase());return`${r}: ${i?"yes":"no"}`}function k(e){return[...new Set(e.map(t=>t.function.name))].sort()}function je(e){return[...e].sort((t,n)=>t.function.name.localeCompare(n.function.name))}function Nt(e){let t=new Set,n=[];for(let o of e){let r=`${o.name}\0${o.reason}`;t.has(r)||(t.add(r),n.push(o))}return n.sort((o,r)=>`${o.name}:${o.reason}`.localeCompare(`${r.name}:${r.reason}`))}function Sc(e,t,n,o,r){let s=r.filter(i=>i.name===e).sort((i,a)=>qs(i.reason)-qs(a.reason))[0];return t.includes(e)?s?`${e}=policy-filtered:${s.reason}`:n.includes(e)?o.includes(e)?`${e}=called`:`${e}=enabled-not-used`:`${e}=policy-filtered:not-enabled`:`${e}=not-exposed`}function qs(e){return e==="invalid-arguments"?0:e==="blocked-by-policy"||e.startsWith("policy-suppressed:")?1:e==="confirmation-timeout"?2:e==="dedicated-tool-required"?3:e==="read-only-context-pack"?4:e==="not-offered"?5:e==="read-cycle-policy"?6:e==="identical-repeat-policy"?7:e==="variant-failure-policy"?8:10}function Mc(e){let t=typeof e.blockReason=="string"?e.blockReason:void 0;if(e.blocked&&/confirmation timed out/i.test(t??""))return"confirmation-timeout";if(e.blocked)return"blocked-by-policy";let n=typeof e.details?.error=="string"?e.details.error:void 0;if(n==="dedicated_tool_required")return"dedicated-tool-required";if(n==="existing_file_update_tool_required")return"existing-file-update-tool-required";if(n==="invalid_arguments")return"invalid-arguments";if(n==="blocked_global_process_kill")return"global-process-kill-blocked";if(n==="blocked_by_guard")return"blocked-by-policy"}function zs(e){let t=new Set(e.map(n=>n.function.name));return t.has("read")||t.has("search")||t.has("write")||t.has("edit")||t.has("patch")}function Te(e,t){return t.size===0?[...e]:e.filter(n=>!t.has(n.function.name))}var Ec=new Set(["edit","patch","read"]);function Hs(e,t){let n=e.filter(o=>Ec.has(o.function.name)&&!t.has(o.function.name));return n.length>0?je(n):e.filter(o=>o.function.name!=="write"&&!t.has(o.function.name))}function ro(e,t){let n=new Set(t);return e.filter(o=>!n.has(o))}function Ic(e){if(!e)return;let t=e.trim();return(t.match(/Last error:\s*(.+?)\.\s*Do not retry\./s)?.[1]?.trim()??t).slice(0,600).trim()||void 0}function Gs(e){let n=pe(e)?.command;return typeof n=="string"&&n.trim()?n:void 0}var Bt=5174;function Ws(e,t){let n=String(t);return[new RegExp(`(?:^|\\s)--port(?:=|\\s+)${n}(?:\\s|$)`),new RegExp(`(?:^|\\s)-p(?:=|\\s+)${n}(?:\\s|$)`),new RegExp(`(?:localhost|127\\.0\\.0\\.1|0\\.0\\.0\\.0|\\[?::1\\]?):${n}\\b`,"i")].some(r=>r.test(e))}function Pc(e){return/\b(vite|npx\s+vite|pnpm\s+(?:run\s+)?dev|npm\s+(?:run\s+)?dev|yarn\s+(?:run\s+)?dev)\b/i.test(e)}function ni(e){return/(?:^|\s)--strictPort(?:\s|$)/.test(e)}function Oc(e){if(ni(e))return e;let t=/\s+(?:\d?>&\d|\d?>\s*\S+|>\s*\S+|<\s*\S+).*$/.exec(e);return!t||t.index===void 0?`${e.trim()} --strictPort`:`${e.slice(0,t.index).trim()} --strictPort${e.slice(t.index)}`}function Vs(e,t){let n=pe(e)??{};return JSON.stringify({...n,command:t})}function Nc(e){let t=e.replace(/^(?:\s*sleep\s+\d+(?:\.\d+)?\s*(?:&&|;)\s*)+/i,"").trim();return t&&t!==e.trim()?t:null}function Lc(e){return Ws(e,Bt)?{action:"block",error:"Command blocked: port 5174 is reserved for the Xiaozhi Claw frontend. Start generated apps on an explicit non-5174 port and include --strictPort when using Vite."}:Pc(e)&&Ws(e,Bt-1)&&!ni(e)?{action:"rewrite",command:Oc(e)}:null}function Dt(e){let t=[];for(let n of e.devServerUrls)if(!(!/^https?:\/\/(?:localhost|127\.0\.0\.1):\d+\b/i.test(n)||new RegExp(`:${Bt}\\b`).test(n)))try{let o=new URL(n);if(/^\/api(?:\/|$)/i.test(o.pathname))continue;let r=`${o.protocol}//${o.host}${o.pathname==="/"?"":o.pathname}`;t.includes(r)||t.push(r)}catch{continue}return t}function Xs(e){let t=Dt(e);return`Browser-visible acceptance is still missing. Do not finish from source inspection or web_fetch output. Use exec to run real browser automation (Playwright or an equivalent browser runner) against ${t.length>0?t.join(", "):"the generated localhost dev server URL"}. Do not run a plain \`node verify.js\` script that imports \`@playwright/test\` unless that package is installed in the target project. Prefer one of these reliable forms: (a) if \`node -e "require.resolve('playwright')"\` succeeds, run a plain Node script importing \`chromium\` from \`playwright\`; or (b) write a Playwright spec and run it with \`npx -y playwright@latest test <spec-file>\` instead of \`node <spec-file>\`. If a localhost URL responds, reuse that running service for browser verification; do not treat a later EADDRINUSE restart attempt as proof that the app is unavailable. Only switch to a new explicit non-5174 port when the observed localhost URL is unreachable or serves the wrong app. Verify rendered visible UI, app-specific routes/screens, and requested interactions; default HTML fetches, bundled JS inspection, and static source review do not count as browser evidence. After the browser automation succeeds, report the exact visible assertions from the tool result.`}function Fc(e){let t=e.buildFailureEvidence[0];return"The test/build you ran is still FAILING, so the task is not complete. "+(t?`Last failing output:
29
30
  ${t.slice(0,600)}
30
- `:"")+"Do not finish or claim success from source inspection. Diagnose the failure, edit the source to fix the root cause, then RE-RUN the same test/build command via exec. Repeat until the command exits 0 (passes), then report the passing output. Do NOT modify, weaken, or delete the test/assertions to force a pass."}function Ks(e){let n=fe(e)?.command;return typeof n=="string"&&n.trim()?n.trim():null}var Nc=4;function Lc(e,t){if(/^(?:write|edit|patch)$/i.test(e)){let n=fe(t),o=n?["path","file_path","filePath","filename","file"].map(r=>n[r]).find(r=>typeof r=="string"):void 0;return o?`edit:${o.replace(/\\/g,"/").toLowerCase()}`:null}if(/^exec$/i.test(e)){let n=Ks(t);return n?`exec:${n.replace(/\s+/g," ")}`:null}return null}function js(e){let t=Ks(e);return t?/\b(?:npx\s+)?playwright\s+install(?:\s+--with-deps)?\s+chromium\b/i.test(t):!1}function Fc(e){let t=Ft(e);return`Browser automation prerequisites are already installed. Do not run \`playwright install\` again. Use exec to run an actual browser verification script against ${t.length>0?t.join(", "):"the generated localhost dev server URL"}: open the page with Playwright/Puppeteer, assert visible app-specific text and interactions, then report the visible assertions. If using Playwright from a plain node script, import \`chromium\` from \`playwright\` and do not use the \`test()\` API unless running through \`npx -y playwright@latest test <spec-file>\`. Do not execute a file that imports \`@playwright/test\` with plain \`node\`; that fails when the generated app did not install the test package.`}function Bc(e){return[`Quick task-list status sync: the list still shows unresolved item(s): ${e.filter(n=>n.status!=="completed").map(n=>`#${n.id} ${n.title} (${n.status})`).join("; ")}.`,"If your final answer already shows these are done, just mark them completed with the task tool to match \u2014 this is a status sync, not a request to redo work.","Mark items completed only if the work is actually done and verified; otherwise mark them blocked/cancelled if the task tool supports that status, or keep them unresolved and report the blocker.","Do not produce a final completion claim until task status and the final answer agree."].join(" ")}function Dc(e){let t=new Set(["completed","blocked","cancelled","canceled","failed"]);return e.some(n=>!t.has(n.status.toLowerCase()))}function $c(e){return e?Os(e):"Command blocked: local file reads/searches/listing must use the dedicated read/search tools, not exec. Use read for file contents and search for filename or content lookup."}function qs(e,t){let n=t.blockedToolCalls.length>0?t.blockedToolCalls.map(s=>`${s.name}:${s.reason}`).join(", "):"none",r=[...new Set([...t.toolCallNames,"write","edit","patch"])].sort().map(s=>vc(s,t.availableToolNames,t.enabledToolNames,t.toolCallNames,t.blockedToolCalls)).join(", ");return`${e}
31
+ `:"")+"Do not finish or claim success from source inspection. Diagnose the failure, edit the source to fix the root cause, then RE-RUN the same test/build command via exec. Repeat until the command exits 0 (passes), then report the passing output. Do NOT modify, weaken, or delete the test/assertions to force a pass."}function oi(e){let n=pe(e)?.command;return typeof n=="string"&&n.trim()?n.trim():null}var Bc=4;function Dc(e,t){if(/^(?:write|edit|patch)$/i.test(e)){let n=pe(t),o=n?["path","file_path","filePath","filename","file"].map(r=>n[r]).find(r=>typeof r=="string"):void 0;return o?`edit:${o.replace(/\\/g,"/").toLowerCase()}`:null}if(/^exec$/i.test(e)){let n=oi(t);return n?`exec:${n.replace(/\s+/g," ")}`:null}return null}function Ks(e){let t=oi(e);return t?/\b(?:npx\s+)?playwright\s+install(?:\s+--with-deps)?\s+chromium\b/i.test(t):!1}function $c(e){let t=Dt(e);return`Browser automation prerequisites are already installed. Do not run \`playwright install\` again. Use exec to run an actual browser verification script against ${t.length>0?t.join(", "):"the generated localhost dev server URL"}: open the page with Playwright/Puppeteer, assert visible app-specific text and interactions, then report the visible assertions. If using Playwright from a plain node script, import \`chromium\` from \`playwright\` and do not use the \`test()\` API unless running through \`npx -y playwright@latest test <spec-file>\`. Do not execute a file that imports \`@playwright/test\` with plain \`node\`; that fails when the generated app did not install the test package.`}function Uc(e){return[`Quick task-list status sync: the list still shows unresolved item(s): ${e.filter(n=>n.status!=="completed").map(n=>`#${n.id} ${n.title} (${n.status})`).join("; ")}.`,"If your final answer already shows these are done, just mark them completed with the task tool to match \u2014 this is a status sync, not a request to redo work.","Mark items completed only if the work is actually done and verified; otherwise mark them blocked/cancelled if the task tool supports that status, or keep them unresolved and report the blocker.","Do not produce a final completion claim until task status and the final answer agree."].join(" ")}function jc(e){let t=new Set(["completed","blocked","cancelled","canceled","failed"]);return e.some(n=>!t.has(n.status.toLowerCase()))}function qc(e){return e?js(e):"Command blocked: local file reads/searches/listing must use the dedicated read/search tools, not exec. Use read for file contents and search for filename or content lookup."}function Ys(e,t){let n=t.blockedToolCalls.length>0?t.blockedToolCalls.map(s=>`${s.name}:${s.reason}`).join(", "):"none",r=[...new Set([...t.toolCallNames,"write","edit","patch"])].sort().map(s=>Sc(s,t.availableToolNames,t.enabledToolNames,t.toolCallNames,t.blockedToolCalls)).join(", ");return`${e}
31
32
 
32
33
  Tool availability diagnostics:
33
34
  availableToolNames: ${t.availableToolNames.join(", ")}
34
35
  enabledToolNames: ${t.enabledToolNames.join(", ")}
35
36
  toolCallNames: ${t.toolCallNames.join(", ")||"none"}
36
37
  blockedToolCalls: ${n}
37
- attribution: ${r}`}function de(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function Uc(e,t){if(!e)return null;let n=de(e.function.parameters),o=Array.isArray(n?.required)?n.required.filter(s=>typeof s=="string"&&s.trim().length>0):[];if(o.length===0)return null;let r=fe(t);if(!r)return`Tool "${e.function.name}" arguments must be a JSON object.`;for(let s of o){let i=r[s];if(typeof i=="string"?i.trim().length===0:i==null)return`Tool "${e.function.name}" missing required field \`${s}\`. Use the tool schema exactly instead of substituting another field.${jc(e.function.name)}`}return null}function jc(e){return e==="search"?' Retry search with `mode` and `pattern`, for example {"mode":"filename","pattern":"**/*.md"} or {"mode":"content","pattern":"TODO","fileGlob":"*.ts"}.':e==="exec"?" Retry exec with `command` only, or switch to read/search/write/edit/patch for file paths and file maintenance.":""}function Oe(e,t){if(!e||typeof e!="object")return;let n=e[t];return typeof n=="string"?n:void 0}function Nt(e,t){if(!e||typeof e!="object")return;let n=e[t];return typeof n=="boolean"?n:void 0}function qc(e,t){if(!e||typeof e!="object")return;let n=e[t];return typeof n=="number"&&Number.isFinite(n)?n:void 0}function zc(e){let t=[...e].sort();return[`Background agent task(s) are still unresolved: ${t.map(n=>`\`${n}\``).join(", ")}.`,"Do not launch replacement agents and do not claim they are lost while their task ids are known.",`Poll each existing task with ${t.map(n=>`task(action="output", taskId="${n}")`).join(", ")}.`,"Only after every task is completed, failed, or explicitly cancelled may you synthesize artifacts or report a blocker."].join(" ")}function Hc(e,t){return[`Background agent task(s) exceeded the no-output watchdog: ${e.map(n=>`\`${n}\``).join(", ")}.`,`Reason: ${t.reason}.`,`Cancel each stalled task now with ${e.map(n=>`task(action="cancel", taskId="${n}")`).join(", ")}.`,"After cancellation, do not relaunch replacement agents for the same work in this turn.","Resume in the parent task with direct write/edit/patch/exec work inside the declared artifact root, or report an explicit blocker with the stalled task ids."].join(" ")}function Gc(e,t){if(e.function.name!=="task")return!1;let n=fe(e.function.arguments);if(n?.action!=="output")return!1;let o=n.taskId;return typeof o=="string"&&ke(t).has(o)}function Wc(e,t){if(e.toolName!=="task")return!1;let n=Oe(e.details,"taskId");return!n||!ke(t).has(n)?!1:Oe(e.details,"action")==="output"&&Nt(e.details,"running")===!0}var Vc=180,Xc=40;function Kc(e){return/\(no output yet\)|\bno output yet\b/i.test(e)}function Yc(e){let t=e.match(/\brunning for\s+(\d+)s\b/i);if(!t?.[1])return;let n=Number(t[1]);return Number.isFinite(n)?n:void 0}function ke(e){return e.backgroundAgentTaskIds??(e.backgroundAgentTaskIds=new Set)}function Zc(e){if(!e||typeof e!="object")return null;let t=e.taskList;if(!Array.isArray(t))return null;let n=[];for(let o of t){if(!o||typeof o!="object")continue;let r=o,s=r.id,i=r.title,a=r.status;typeof s!="number"||!Number.isFinite(s)||typeof i!="string"||!i.trim()||typeof a!="string"||!a.trim()||n.push({id:s,title:i,status:a})}return n}var so=new Set(["read","search"]),Jc=new Set(["write","edit","patch","image_generate"]),Qc=18e4,eu=3,nt=1,tu=1,nu=1,ou=4,ru=2,J=new Map([["requirements.md","requirements"],["decisions.md","decisions"],["defects.md","defects"],["acceptance.md","acceptance"]]),uo=new Set(["document-index.json","decision-state-table.json","context-pack-evidence.json"]),Ys=[{id:"D001",decision:"artifact root must remain stable for the whole scenario",status:"confirmed",evidence:"maintained-document-index",lastConfirmedTurn:0},{id:"D002",decision:"every browser checkpoint must use the real Xiaozhi Claw frontend",status:"confirmed",evidence:"maintained-document-index",lastConfirmedTurn:0},{id:"D003",decision:"unsupported facts are assumptions until verified",status:"confirmed",evidence:"maintained-document-index",lastConfirmedTurn:0},{id:"D004",decision:"defects and decisions must be maintained as separate artifacts",status:"confirmed",evidence:"maintained-document-index",lastConfirmedTurn:0},{id:"D005",decision:"final release requires initial version, acceptance, rework, second review, and release candidate",status:"confirmed",evidence:"maintained-document-index",lastConfirmedTurn:0},{id:"D006",decision:"after every reopen, reconstruct goal, artifacts, decisions, defects, acceptance criteria, blockers, and next action",status:"confirmed",evidence:"maintained-document-index",lastConfirmedTurn:0}],io=new Set(["write","edit","patch"]),su=new Set(["read","search","exec"]);function Zs(e){let t=G(e),n=Re(t);return t.split("/").includes("context-pack")&&J.has(n)?nt:t.split("/").includes("benchmark-state")&&uo.has(n)?nu:t.includes("/qlogicagent-sessions/")&&t.includes("/tool-results/")?tu:eu}function ro(e){let t=G(e);if(t.split("/").includes("context-pack")){let n=t.split("/context-pack/")[0];return`Use benchmark-state summaries instead: ${n}/benchmark-state/document-index.json, ${n}/benchmark-state/decision-state-table.json, and ${n}/benchmark-state/context-pack-evidence.json. If those summaries are stale, update compact checkpoint files under benchmark-state; do not reread or rewrite context-pack.`}return t.includes("/qlogicagent-sessions/")&&t.includes("/tool-results/")?"This is a persisted large tool-result preview. Use the first read, the original tool_result preview, and maintained benchmark-state summaries; do not reread tool-result cache files.":t.split("/").includes("benchmark-state")&&uo.has(Re(t))?"This compact benchmark-state file was already read this turn. Use the in-turn tool result, prior maintained summary, and decision state already in conversation; do not reread compact state files in a loop.":"Use the maintained index, prior tool results, or a narrow section-specific read instead of rereading the same file."}function fo(e){let t=G(e);return t.split("/").includes("context-pack")&&J.has(Re(t))}function Js(e){let t=G(e),o=t.indexOf("/context-pack/");return o<0?null:t.slice(0,o)}function iu(e){let t=[...e].filter(fo).map(Js).filter(o=>!!o);if(t.length===0)return!1;let n=t[0];return[`${n}/benchmark-state/document-index.json`,`${n}/benchmark-state/decision-state-table.json`,`${n}/benchmark-state/context-pack-evidence.json`].every(o=>{try{return Ne(o)}catch{return!1}})}function Qs(e){return[...J.keys()].every(t=>e.has(t))}function po(e){for(let t of e.values()){if(!t.path)continue;let n=Js(t.path);if(n)return`${n}/benchmark-state`}return null}function ei(e){if(!Qs(e))return[];let t=po(e);return t?[...uo].map(n=>`${t}/${n}`).filter(n=>{try{return!Ne(n)}catch{return!0}}):[]}function au(e,t){let n=ei(e);if(n.length===0)return null;let o=po(e);if(!o)return null;let s=[...J.keys()].map(a=>{let u=e.get(a);return`${a}: path=${u?.path??"unknown"}, contentHash=${u?.contentHash??"unknown"}, fileSizeBytes=${u?.fileSizeBytes??"unknown"}, recordCount=${u?.recordCount??"unknown"}, summary=${u?.summary??""}`}).join(`
38
- `),i=Ys.map(a=>`${a.id}: ${a.decision}`).join(`
38
+ attribution: ${r}`}function fe(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function zc(e,t){if(!e)return null;let n=fe(e.function.parameters),o=Array.isArray(n?.required)?n.required.filter(s=>typeof s=="string"&&s.trim().length>0):[];if(o.length===0)return null;let r=pe(t);if(!r)return`Tool "${e.function.name}" arguments must be a JSON object.`;for(let s of o){let i=r[s];if(typeof i=="string"?i.trim().length===0:i==null)return`Tool "${e.function.name}" missing required field \`${s}\`. Use the tool schema exactly instead of substituting another field.${Hc(e.function.name)}`}return null}function Hc(e){return e==="search"?' Retry search with `mode` and `pattern`, for example {"mode":"filename","pattern":"**/*.md"} or {"mode":"content","pattern":"TODO","fileGlob":"*.ts"}.':e==="exec"?" Retry exec with `command` only, or switch to read/search/write/edit/patch for file paths and file maintenance.":""}function Oe(e,t){if(!e||typeof e!="object")return;let n=e[t];return typeof n=="string"?n:void 0}function Ft(e,t){if(!e||typeof e!="object")return;let n=e[t];return typeof n=="boolean"?n:void 0}function Gc(e,t){if(!e||typeof e!="object")return;let n=e[t];return typeof n=="number"&&Number.isFinite(n)?n:void 0}function Wc(e){let t=[...e].sort();return[`Background agent task(s) are still unresolved: ${t.map(n=>`\`${n}\``).join(", ")}.`,"Do not launch replacement agents and do not claim they are lost while their task ids are known.",`Poll each existing task with ${t.map(n=>`task(action="output", taskId="${n}")`).join(", ")}.`,"Only after every task is completed, failed, or explicitly cancelled may you synthesize artifacts or report a blocker."].join(" ")}function Vc(e,t){return[`Background agent task(s) exceeded the no-output watchdog: ${e.map(n=>`\`${n}\``).join(", ")}.`,`Reason: ${t.reason}.`,`Cancel each stalled task now with ${e.map(n=>`task(action="cancel", taskId="${n}")`).join(", ")}.`,"After cancellation, do not relaunch replacement agents for the same work in this turn.","Resume in the parent task with direct write/edit/patch/exec work inside the declared artifact root, or report an explicit blocker with the stalled task ids."].join(" ")}function Xc(e,t){if(e.function.name!=="task")return!1;let n=pe(e.function.arguments);if(n?.action!=="output")return!1;let o=n.taskId;return typeof o=="string"&&Ce(t).has(o)}function Kc(e,t){if(e.toolName!=="task")return!1;let n=Oe(e.details,"taskId");return!n||!Ce(t).has(n)?!1:Oe(e.details,"action")==="output"&&Ft(e.details,"running")===!0}var Yc=180,Zc=40;function Jc(e){return/\(no output yet\)|\bno output yet\b/i.test(e)}function Qc(e){let t=e.match(/\brunning for\s+(\d+)s\b/i);if(!t?.[1])return;let n=Number(t[1]);return Number.isFinite(n)?n:void 0}function Ce(e){return e.backgroundAgentTaskIds??(e.backgroundAgentTaskIds=new Set)}function eu(e){if(!e||typeof e!="object")return null;let t=e.taskList;if(!Array.isArray(t))return null;let n=[];for(let o of t){if(!o||typeof o!="object")continue;let r=o,s=r.id,i=r.title,a=r.status;typeof s!="number"||!Number.isFinite(s)||typeof i!="string"||!i.trim()||typeof a!="string"||!a.trim()||n.push({id:s,title:i,status:a})}return n}var io=new Set(["read","search"]),tu=new Set(["write","edit","patch","image_generate"]),nu=18e4,ou=3,rt=1,ru=1,su=1,iu=4,au=2,J=new Map([["requirements.md","requirements"],["decisions.md","decisions"],["defects.md","defects"],["acceptance.md","acceptance"]]),fo=new Set(["document-index.json","decision-state-table.json","context-pack-evidence.json"]),ri=[{id:"D001",decision:"artifact root must remain stable for the whole scenario",status:"confirmed",evidence:"maintained-document-index",lastConfirmedTurn:0},{id:"D002",decision:"every browser checkpoint must use the real Xiaozhi Claw frontend",status:"confirmed",evidence:"maintained-document-index",lastConfirmedTurn:0},{id:"D003",decision:"unsupported facts are assumptions until verified",status:"confirmed",evidence:"maintained-document-index",lastConfirmedTurn:0},{id:"D004",decision:"defects and decisions must be maintained as separate artifacts",status:"confirmed",evidence:"maintained-document-index",lastConfirmedTurn:0},{id:"D005",decision:"final release requires initial version, acceptance, rework, second review, and release candidate",status:"confirmed",evidence:"maintained-document-index",lastConfirmedTurn:0},{id:"D006",decision:"after every reopen, reconstruct goal, artifacts, decisions, defects, acceptance criteria, blockers, and next action",status:"confirmed",evidence:"maintained-document-index",lastConfirmedTurn:0}],ao=new Set(["write","edit","patch"]),lu=new Set(["read","search","exec"]);function si(e){let t=G(e),n=ke(t);return t.split("/").includes("context-pack")&&J.has(n)?rt:t.split("/").includes("benchmark-state")&&fo.has(n)?su:t.includes("/qlogicagent-sessions/")&&t.includes("/tool-results/")?ru:ou}function so(e){let t=G(e);if(t.split("/").includes("context-pack")){let n=t.split("/context-pack/")[0];return`Use benchmark-state summaries instead: ${n}/benchmark-state/document-index.json, ${n}/benchmark-state/decision-state-table.json, and ${n}/benchmark-state/context-pack-evidence.json. If those summaries are stale, update compact checkpoint files under benchmark-state; do not reread or rewrite context-pack.`}return t.includes("/qlogicagent-sessions/")&&t.includes("/tool-results/")?"This is a persisted large tool-result preview. Use the first read, the original tool_result preview, and maintained benchmark-state summaries; do not reread tool-result cache files.":t.split("/").includes("benchmark-state")&&fo.has(ke(t))?"This compact benchmark-state file was already read this turn. Use the in-turn tool result, prior maintained summary, and decision state already in conversation; do not reread compact state files in a loop.":"Use the maintained index, prior tool results, or a narrow section-specific read instead of rereading the same file."}function po(e){let t=G(e);return t.split("/").includes("context-pack")&&J.has(ke(t))}function ii(e){let t=G(e),o=t.indexOf("/context-pack/");return o<0?null:t.slice(0,o)}function cu(e){let t=[...e].filter(po).map(ii).filter(o=>!!o);if(t.length===0)return!1;let n=t[0];return[`${n}/benchmark-state/document-index.json`,`${n}/benchmark-state/decision-state-table.json`,`${n}/benchmark-state/context-pack-evidence.json`].every(o=>{try{return Ne(o)}catch{return!1}})}function ai(e){return[...J.keys()].every(t=>e.has(t))}function mo(e){for(let t of e.values()){if(!t.path)continue;let n=ii(t.path);if(n)return`${n}/benchmark-state`}return null}function li(e){if(!ai(e))return[];let t=mo(e);return t?[...fo].map(n=>`${t}/${n}`).filter(n=>{try{return!Ne(n)}catch{return!0}}):[]}function uu(e,t){let n=li(e);if(n.length===0)return null;let o=mo(e);if(!o)return null;let s=[...J.keys()].map(a=>{let c=e.get(a);return`${a}: path=${c?.path??"unknown"}, contentHash=${c?.contentHash??"unknown"}, fileSizeBytes=${c?.fileSizeBytes??"unknown"}, recordCount=${c?.recordCount??"unknown"}, summary=${c?.summary??""}`}).join(`
39
+ `),i=ri.map(a=>`${a.id}: ${a.decision}`).join(`
39
40
  `);return["You have already read and indexed requirements.md, decisions.md, defects.md, and acceptance.md for this long-horizon benchmark.","Do not read context-pack, persisted tool-result previews, or compact benchmark-state files again in this turn.","Before any more analysis or final answer, maintain the benchmark state files using write/edit/patch only.",`Benchmark-state directory: ${o}.`,`Missing files: ${n.join(", ")}.`,"Create missing files with write. If any target already exists, update it with edit or patch instead of write.","For every contentHash and fileSizeBytes you write, copy the EXACT value from the 'Document evidence already available' section below. Do NOT compute, approximate, or invent a hash \u2014 you must not re-read the large read-only context-pack files to produce one.","The context-pack inputs (requirements.md, decisions.md, defects.md, acceptance.md) are READ-ONLY and immutable: their content and contentHash cannot change between turns. If a hash ever appears to differ from what you recorded, the source did NOT change \u2014 suspect your own recorded value first (stale, or never tool-derived). Never raise a 'source changed' blocker for these files.","Acceptance verdicts are monotonic unless re-derived from primary evidence: do NOT flip a previously-PASSing criterion to FAIL on a derived/secondary signal such as a hash diff. Change a PASS to FAIL only after re-checking the actual acceptance condition against primary evidence, and cite that evidence.","Required files:","- document-index.json: include contextPackPath and a documents object keyed by requirements.md, decisions.md, defects.md, acceptance.md with path, contentHash, fileSizeBytes, recordCount, indexVersion, summary, and lastReviewedTurn.","- decision-state-table.json: include D001-D006 with id, decision, status, evidence, and lastConfirmedTurn.","- context-pack-evidence.json: include turn and fileVerification for requirements.md, decisions.md, defects.md, acceptance.md with path, contentHash, and fileSizeBytes.",`Current turn: ${t}.`,"Document evidence already available:",s,"Decision records to preserve:",i].join(`
40
- `)}function zs(e){return io.has(e)}function lu(e){return e.benchmarkStateMaintenanceRequiredFiles.size>0&&[...e.benchmarkStateMaintenanceRequiredFiles].every(t=>cu(e,t))}function cu(e,t){if(e.benchmarkStateMaintenanceWrittenFiles.has(t))return!0;try{if(!Ne(t))return!1;let n=Re(t);if(n!=="document-index.json"&&n!=="context-pack-evidence.json")return!0;let o=$t(t,"utf8");return mo(e.maintainedDocuments,t,JSON.stringify({content:o})).ok}catch{return!1}}function mo(e,t,n){let o=Re(t);if(o!=="document-index.json"&&o!=="context-pack-evidence.json")return{ok:!0};let r=vu(n);if(!r)return{ok:!1,reason:`${o} write did not include JSON content`};let s=fe(r);if(!s)return{ok:!1,reason:`${o} content is not a JSON object`};if(o==="document-index.json"){let a=de(s.documents);if(!a)return{ok:!1,reason:"document-index.json missing documents object"};for(let u of J.keys()){let p=e.get(u),y=de(a[u]);if(!p||!y)return{ok:!1,reason:`document-index.json missing ${u}`};if(y.contentHash!==p.contentHash)return{ok:!1,reason:`document-index.json ${u} contentHash does not match read.details`};if(y.fileSizeBytes!==p.fileSizeBytes)return{ok:!1,reason:`document-index.json ${u} fileSizeBytes does not match read.details`}}return{ok:!0}}let i=de(s.fileVerification);if(!i)return{ok:!1,reason:"context-pack-evidence.json missing fileVerification object"};for(let a of J.keys()){let u=e.get(a),p=de(i[a]);if(!u||!p)return{ok:!1,reason:`context-pack-evidence.json missing ${a}`};if(p.contentHash!==u.contentHash)return{ok:!1,reason:`context-pack-evidence.json ${a} contentHash does not match read.details`};if(p.fileSizeBytes!==u.fileSizeBytes)return{ok:!1,reason:`context-pack-evidence.json ${a} fileSizeBytes does not match read.details`}}return{ok:!0}}function uu(e){if(!Qs(e))return[];let t=po(e);if(!t)return[];let n=[];for(let o of["document-index.json","context-pack-evidence.json"]){let r=`${t}/${o}`,s;try{if(!Ne(r))continue;s=$t(r,"utf8")}catch{continue}let i=mo(e,r,JSON.stringify({content:s}));i.ok||n.push({path:r,reason:i.reason})}return n}function du(e,t,n,o){if(e.filter(a=>a.name==="read"&&a.reason==="read-cycle-policy").length<ou)return!1;let s=new Set([...t].filter(fo).map(Re));return[...J.keys()].every(a=>s.has(a))?[...J.keys()].every(a=>o.has(a))||n||iu(t):!1}function ti(e,t,n){if(e!=="write"||!n.has("edit")&&!n.has("patch"))return null;let o=Dt(t);if(!o)return null;try{if(!Ne(o))return null}catch{return null}return{path:o,error:`Existing file update blocked for "${o}". Use edit or patch for existing files so the event stream can distinguish file creation from incremental maintenance.`}}var Bt=class extends Error{constructor(n){super(`LLM stream idle timeout after ${n}ms without a chunk.`);this.timeoutMs=n;this.name="LLMStreamIdleTimeoutError"}timeoutMs;code="LLM_STREAM_TIMEOUT"};async function*fu(e,t){if(!Number.isFinite(t)||t<=0){yield*e;return}let n=e[Symbol.asyncIterator]();try{for(;;){let o,r=await Promise.race([n.next(),new Promise(s=>{o=setTimeout(()=>s("timeout"),t)})]);if(o&&clearTimeout(o),r==="timeout")throw new Bt(t);if(r.done)return;yield r.value}}finally{n.return?.().catch(()=>{})}}function ao(e){try{let t=JSON.parse(e),n=t.file_path??t.path??t.filePath;return typeof n=="string"&&n.trim()?n:void 0}catch{return}}function Dt(e){try{let t=JSON.parse(e),n=t.file_path??t.path??t.filePath;return typeof n=="string"&&n.trim()?n:void 0}catch{return}}function pu(e){return e.flatMap(t=>{if(mu(t.function.arguments))return[t];let n=gu(t.function.arguments);return n.length<2?[t]:n.map((o,r)=>({...t,id:`${t.id}__json_${r+1}`,function:{...t.function,arguments:JSON.stringify(o)}}))})}function mu(e){try{let t=JSON.parse(e);return!!t&&typeof t=="object"&&!Array.isArray(t)}catch{return!1}}function gu(e){let t=[],n=0,o=-1,r=!1,s=!1,i=0;for(let a=0;a<e.length;a+=1){let u=e[a];if(r){s?s=!1:u==="\\"?s=!0:u==='"'&&(r=!1);continue}if(u==='"'){r=!0;continue}if(u==="{"){if(n===0){if(e.slice(i,a).trim())return[];o=a}n+=1;continue}if(u!=="}"||(n-=1,n!==0||o<0))continue;let p=fe(e.slice(o,a+1));if(!p)return[];t.push(p),i=a+1,o=-1}return n!==0||r||e.slice(i).trim()?[]:t}function fe(e){try{let t=JSON.parse(e);return t&&typeof t=="object"&&!Array.isArray(t)?t:null}catch{return null}}function G(e){let t=e.trim().replace(/\\/g,"/");for(t=t.replace(/\/{2,}/g,"/");t.includes("/./");)t=t.replace(/\/\.\//g,"/");return t=t.replace(/\/\.$/,""),/^[a-z]:\//i.test(t)&&(t=t.toLowerCase()),t.replace(/\/$/,"")}function Re(e){let t=e.trim().replace(/\\/g,"/");return t.slice(t.lastIndexOf("/")+1).toLowerCase()}function go(e){return`sha256:${pc("sha256").update(e).digest("hex")}`}function hu(e,t){let n=t.split(/\r?\n/).map(a=>a.trim()).filter(Boolean),o=n[0]??e,r=n.find(a=>/record\s+0*1\b/i.test(a)),s=r&&r!==o?`${o}; ${r}`:o,i=s.length>180?`${s.slice(0,177)}...`:s;return i.toLowerCase().includes(e.toLowerCase())?i:`${e}: ${i}`}function yu(e){return Object.fromEntries([...e.entries()].sort(([t],[n])=>t.localeCompare(n)))}function bu(e,t,n,o){let r=[...t.values()].sort((u,p)=>(u.name??"").localeCompare(p.name??""));if(r.length===0)return null;let s=r.map(u=>`${u.name??"document"}:${u.contentHash??"unknown"}`).join("|"),i=Ys.map(u=>({...u,evidence:`read:long-horizon-documents:${go(`${u.id}:${s}`)}`,lastConfirmedTurn:o})),a={strategy:"maintained-document-index",nextReadPolicy:"use maintained index before full document reread",budgetStatus:"within-budget",maxReadsPerDocument:nt,observedReadsByPath:yu(n)};return{type:"document_maintenance",turnId:e,checkpointId:`${e}-docs-${r.length}`,documents:r,decisionStateTable:i,readCycleFindings:[],readCycleGuard:a}}function Tu(e){let t=e.find(o=>o.path)?.path??"",n=t.lastIndexOf("/");return n>0?t.slice(0,n):t}function Ot(e,t){return e.get(t)??null}function Cu(e){let t=Ot(e,"requirements.md"),n=Ot(e,"decisions.md"),o=Ot(e,"defects.md"),r=Ot(e,"acceptance.md");if(!t||!n||!o||!r)return null;let s=[t,n,o,r];return{goal:`Maintain long-horizon project state from ${t.name}, ${n.name}, ${o.name}, and ${r.name}`,artifactRoot:Tu(s),decisions:[n.summary],defects:[o.summary],acceptanceCriteria:[r.summary],blockers:[],nextAction:"Continue from the maintained document index and read only explicitly missing sections"}}function ku(e,t){let n=Cu(t);return n?[{type:"lifecycle",turnId:e,kind:"goal_reconstruction",reconstruction:n},{type:"lifecycle",turnId:e,kind:"memory_drift",status:"none",detail:"No memory drift detected against the maintained document index."}]:[]}function Ru(e,t,n,o,r){let s=lo(t,n,o,r);if(!s)return!1;let i=s.name;return i?(e.maintainedDocuments.set(i,s),!0):!1}function lo(e,t,n,o){let r=Re(e);if(!J.has(r))return null;let s=Au(t)??t,i=wu(o,"contentHash"),a=qe(o??null,"fileSizeBytes"),u=i??go(s);return{name:r,path:G(e),indexed:!0,maintained:!0,indexVersion:u,contentHash:u,summary:hu(r,s),lastReviewedTurn:n,fileSizeBytes:a??Buffer.byteLength(s,"utf8"),recordCount:ni(s)}}function xu(e,t){return ti(e.function.name,e.function.arguments,t)!==null}function _u(e,t){let n=Dt(t.function.arguments);return`This exact write call to an existing file has been attempted ${e} times${n?` for "${n}"`:""}. Do not call write again for this existing file. Use edit or patch for the existing-file update, then continue verification.`}function vu(e){let n=fe(e)?.content;return typeof n=="string"?n:void 0}function wu(e,t){let n=e?.[t];return typeof n=="string"&&n.trim()?n.trim():void 0}function ni(e){let t=e.split(/\r?\n/).map(n=>n.trim()).filter(Boolean).length;return Math.max(1,t)}function Au(e){if(!e.includes("<persisted-output>"))return null;let n=e.match(/Full output saved to:\s*(.+?)(?:\r?\n|$)/)?.[1]?.trim();if(!n)return null;try{return Ne(n)?$t(n,"utf8"):null}catch{return null}}function Su(e){let t=new Map;for(let s of e)if(!(s.role!=="assistant"||!Array.isArray(s.tool_calls)))for(let i of s.tool_calls){if(i.function?.name!=="read"||typeof i.id!="string"||typeof i.function.arguments!="string")continue;let a=ao(i.function.arguments);if(!a)continue;let u=G(a);Zs(u)===nt&&t.set(i.id,{path:u})}let n=new Map,o=new Map,r=!1;for(let s of e){if(s.role!=="tool"||typeof s.tool_call_id!="string"||s.is_error===!0)continue;let i=t.get(s.tool_call_id);if(!i)continue;let a=typeof s.content=="string"?s.content:"";if(!a||/^Error:/i.test(a.trim()))continue;n.set(i.path,(n.get(i.path)??0)+1);let u=lo(i.path,a,0);u?.name&&o.set(u.name,u)}for(let s of Ou(e)){r=!0;for(let i of J.keys()){let a=G(`${s}/${i}`);if(n.set(a,Math.max(n.get(a)??0,nt)),!o.has(i)){let u=lo(a,`${i} maintained by benchmark-state/document-index.json from prior conversation history.`,0);u?.name&&o.set(u.name,u)}}}for(let s of Mu(e)){r=!0;for(let i of s.documents)!i.name||!i.path||(n.set(i.path,Math.max(n.get(i.path)??0,nt)),o.set(i.name,i))}return{fileReadCounts:n,maintainedDocuments:o,persistedBenchmarkStateRecovered:r}}function Mu(e){let t=[];for(let n of Eu(e)){let o=Hs(`${n}/document-index.json`),r=Hs(`${n}/context-pack-evidence.json`),s=ze(o,"contextPackPath")??Iu(r);if(!s)continue;let i=Pu(s,o,r);i.length===J.size&&t.push({documents:i})}return t}function Eu(e){let t=new Set;for(let n of e){if(typeof n.content!="string")continue;let r=n.content.replace(/\\/g,"/").matchAll(/([a-zA-Z]:\/[^\s"'`<>]*?\/benchmark-state)(?=\/|[\s.,;:)\]}]|$)/g);for(let s of r){let i=G(s[1]??"");i&&t.add(i)}}return[...t]}function Hs(e){try{if(!Ne(e))return null;let t=JSON.parse($t(e,"utf8"));return t&&typeof t=="object"&&!Array.isArray(t)?t:null}catch{return null}}function ze(e,t){let n=e?.[t];return typeof n=="string"&&n.trim()?G(n):void 0}function Iu(e){let t=e?.fileVerification;if(!(!t||typeof t!="object"||Array.isArray(t)))for(let n of J.keys()){let o=t[n];if(!o||typeof o!="object"||Array.isArray(o))continue;let r=ze(o,"path");if(!r)continue;let s=`/${n}`;if(r.endsWith(s))return r.slice(0,-s.length)}}function Pu(e,t,n){let o=de(t?.documents),r=de(n?.fileVerification),s=[];for(let i of J.keys()){let a=de(o?.[i]),u=de(r?.[i]);if(!a&&!u)return[];let p=ze(a,"path"),g=ze(u,"path")??(p?.includes("/context-pack/")?p:G(`${e}/${i}`)),k=ze(a,"contentHash")??ze(u,"contentHash")??go(`${i}:${g}`),_=typeof a?.summary=="string"&&a.summary.trim()?a.summary.trim():`${i} maintained by persisted benchmark-state/document-index.json.`;s.push({name:i,path:G(g),indexed:!0,maintained:!0,indexVersion:String(a?.indexVersion??k),contentHash:k,summary:_,lastReviewedTurn:co(a,"lastReviewedTurn")??co(n,"turn")??0,fileSizeBytes:qe(a,"fileSizeBytes")??qe(u,"fileSizeBytes")??qe(u,"sizeBytes")??Buffer.byteLength(_,"utf8"),recordCount:qe(a,"recordCount")??qe(u,"recordCount")??ni(_)})}return s}function co(e,t){let n=e?.[t];return typeof n=="number"&&Number.isFinite(n)?n:void 0}function qe(e,t){let n=co(e,t);return n&&n>0?n:void 0}function Ou(e){let t=e.slice(0,Math.max(0,e.length-1)),n=new Set;for(let o of t){if(typeof o.content!="string")continue;let r=o.content.replace(/\\/g,"/").toLowerCase();if(!r.includes("benchmark-state/document-index")&&!r.includes("benchmark-state/context-pack-evidence")&&!r.includes("maintained document index"))continue;let s=r.matchAll(/([a-z]:\/[^\s"'`<>]*?\/context-pack)(?=\/|[\s.,;:)\]}]|$)/gi);for(let i of s){let a=G(i[1]??"");a&&n.add(a)}}return[...n]}function Nu(e){e.identicalSuccessfulToolResults.clear();for(let t of[...e.identicalCallCounts.keys()]){let n=t.slice(0,t.indexOf("::"));so.has(n)&&e.identicalCallCounts.delete(t)}}async function*oi(e,t,n,o){let{turnId:r,sessionId:s,messages:i,availableTools:a,tools:u,model:p,apiKey:y,temperature:g=0,hooks:k,signal:_}=e,A={sessionId:s,turnId:r},w=e.maxTurns??0,P=e.querySource,S=e.runtimePorts.resolveToolEligibility(u,e.toolEligibilityContext),O=S.eligibleTools,D=[];for(let m of S.blockedTools)D.push({name:m.toolName,reason:"blocked-by-policy"}),yield{type:"tool_blocked",turnId:r,callId:"",name:m.toolName,reason:"blocked-by-policy"};let q=Jr(e.maxRounds,i),re=Qr(e.maxToolCalls,i),Ut=!(typeof e.maxRounds=="number"&&e.maxRounds>=1)&&!(typeof e.maxToolCalls=="number"&&e.maxToolCalls>=1),ho=wt(i),Le={contextWindowTokens:e.contextWindowTokens??lr,responseBufferTokens:cr,maxOutputTokens:e.maxOutputTokens??ur,abortSignal:_,reactiveCompactEnabled:!0,outputEscalationEnabled:!0},L=new Set,F=0,yo=new Set,bo=0,He=0,Ge=0,ot=0,To=new Map,Y=new Set,b=Ce(O,Y),We=!1,jt=!1,qt,zt=()=>C(b),ci=mc(O,i),Ht=!1,Co=0,ko=0,Ro=0,U=!1,rt=!1,Gt=Su(i),c={messages:[...i],maxOutputTokensRecoveryCount:0,hasAttemptedReactiveCompact:!1,maxOutputTokensOverride:void 0,turnCount:1,transition:void 0,guardState:wn(Le),reactiveCompactState:In(),toolLoopState:kt({maxRounds:q,replayMessages:[...i]}).state,consecutiveFailedRounds:0,finalText:"",totalUsage:{inputTokens:0,outputTokens:0},collapseStore:pn(),currentModel:p,consecutive529Errors:0,consecutiveApiRetries:0,stopHookActive:void 0,lastResponseId:void 0,snipRemovedIds:new Set,contentReplacementState:e.runtimePorts.createContentReplacementState(),budgetContinuationCount:0,repeatedToolFailureRecoveryCount:0,lastBudgetDeltaTokens:0,lastBudgetGlobalTokens:0,identicalCallCounts:new Map,identicalSuccessfulToolResults:new Map,toolFailureCounts:new Map,fileReadCounts:Gt.fileReadCounts,fileReadCycleBlockedPaths:new Set,fileReadCycleNudgedPaths:new Set,maintainedDocuments:Gt.maintainedDocuments,persistedBenchmarkStateRecovered:Gt.persistedBenchmarkStateRecovered,benchmarkStateMaintenanceRequiredFiles:new Set,benchmarkStateMaintenanceWrittenFiles:new Set,recoveryTrace:new Map,artifactContract:Ur(i),browserAcceptanceRecoveryCount:0,buildVerificationRecoveryCount:0,benchmarkStateIntegrityRecoveryCount:0,backgroundAgentTaskIds:new Set,backgroundAgentNoOutputPollCounts:new Map,stalledBackgroundAgentTasks:new Map,notOfferedToolRecoveryCount:0,existingFileUpdateRecoveryCount:0,taskListReconciliationCount:0,lastTaskList:[]},Wt=Math.max(w*5,200),ui=4,di=4,xo=0,_o=new Map,Vt,M=(m,z)=>{let pe=`${m}:${z??""}`,se=(_o.get(pe)??0)+1;if(_o.set(pe,se),m==="autocompact"){let j=c.recoveryTrace.get("autocompact")??0;if(se>ui||j>=di){let Q=`Repeated context compression made no forward progress: ${z??"autocompact"}`;return Vt=Q,c.recoveryTrace.set("compression_loop_guard",(c.recoveryTrace.get("compression_loop_guard")??0)+1),{type:"recovery",turnId:r,action:"compression_loop_guard",detail:Q}}}return c.recoveryTrace.set(m,(c.recoveryTrace.get(m)??0)+1),{type:"recovery",turnId:r,action:m,detail:z}},vo=()=>({type:"tool_use_summary",turnId:r,availableToolNames:C(a??u),enabledToolNames:zt(),toolCallNames:[...L].sort(),blockedToolCalls:Pt(D)}),fi=m=>jr({content:m,inputMessages:i,messages:c.messages,totalToolCallCount:F,distinctToolNames:L,visibleToolCallCount:bo,visibleToolNames:yo,artifactContract:c.artifactContract,blockedToolCalls:Pt(D),activeTasks:c.lastTaskList}),wo=m=>({type:"end",turnId:r,content:m,usage:c.totalUsage,model:c.currentModel,...c.recoveryTrace.size>0?{recoveryTrace:Object.fromEntries(c.recoveryTrace)}:{}});function*W(m){let z=fi(m);Un(c.artifactContract,z),Kt()&&(yield Xt()),yield vo(),yield wo(z)}function*Ao(m){yield vo(),yield wo(m)}let Xt=()=>({type:"artifact_contract",turnId:r,...$n(c.artifactContract,i)}),Kt=()=>{let m=$n(c.artifactContract,i);return!!(m.requiresBrowserAcceptance||m.artifactRoot||m.writePaths.length>0||m.outOfRootWrites.length>0||m.devServerUrls.length>0||m.browserVerified)},st=(m,z)=>c.finalText||Hn(m,o),pi=(m,z,pe)=>{let se=Pe({inputMessages:i,messages:z,reason:pe});return se||m||Hn(z,o)};for(;;){if(xo++,xo>Wt){o.info(`hard iteration cap reached (${Wt}), forcing completion`);let l=st(c.messages,`hard iteration cap reached (${Wt}) before completing the final status contract`);yield*W(l);return}let{messages:m,maxOutputTokensRecoveryCount:z,maxOutputTokensOverride:pe,turnCount:se,guardState:j,reactiveCompactState:Q,collapseStore:Yt}=c,{toolLoopState:ee}=c;if(e.refreshTools&&se>1){let l=e.refreshTools(),d=Ce(l,Y);d!==b&&(b=d,o.debug(`tools refreshed: ${l.length} tools`))}if(En(j,Le)){o.info(`turn aborted by guard at turn ${se}`),yield{type:"error",turnId:r,error:"Turn aborted",code:"ABORTED",usage:c.totalUsage};return}let xe=An(j,Le);if(xe.level==="blocking"){xe.reason==="prompt_too_long"&&Ue(Q)&&(Q.attemptedThisTurn=!0,j.hasAttemptedReactiveCompact=!0,o.info(`token budget blocking (${xe.reason}), reactive compact needed`),yield M("reactive_compact","token budget pre-check")),o.info(`token budget blocking (${xe.reason}), ending tool loop`);break}xe.level==="warning"&&o.info(`token budget warning: ${xe.usagePercent}% used, ${xe.remainingTokens} remaining`);let it=yield*ss({messages:m,contentReplacementState:c.contentReplacementState,snipRemovedIds:c.snipRemovedIds,collapseStore:Yt,guardState:j,guardConfig:Le,runtimePorts:e.runtimePorts,hooks:k,hookCtx:A,sessionId:s,currentModel:c.currentModel,log:o,recovery:M,onAutocompact:()=>{c.hasAttemptedReactiveCompact=!1}});if(Vt){yield*W(`${Vt}. Stop compressing the same context repeatedly; continue from the maintained document index or report the incomplete state explicitly.`);return}let mi=U?"required":e.toolChoice==="required"&&Ht?"auto":e.toolChoice??"auto";U=!1;let Fe=bn({tools:b,toolChoice:mi}),So=C(Fe.tools).join("\0"),Mo=qt!==void 0&&qt!==So;Mo&&c.lastResponseId&&(yield M("stateless_retry","tool schema changed; replaying full history without previous_response_id"));let gi=rt||Mo?void 0:c.lastResponseId;qt=So;let Ve=kt({maxRounds:q,replayMessages:it,lastStopReason:ee.lastStopReason,options:{stopReason:ee.lastStopReason}}),Eo=Fe.extraSystemPrompt?[{role:"system",content:Fe.extraSystemPrompt},...Ve.state.replayMessages]:Ve.state.replayMessages;ee=Ve.state,Ve.recoveryActions.length>0&&o.debug(`tool loop recovery: ${Ve.recoveryActions.map(l=>l.detail??l.kind).join("; ")}`),o.debug(`turn ${se}, messages: ${Eo.length}`),$(k,"turn.before_inference",{...A,model:c.currentModel},o);let Zt=!1,at=[],Io=new Map,Po="stop",te,I=null,lt=!1,Oo=!1,Xe=[],ce=[];try{let l=t.stream({model:c.currentModel,messages:Eo,...Fe.tools.length>0?{tools:Fe.tools,toolChoice:Fe.normalizedToolChoice??"auto"}:{},temperature:g,maxTokens:(pe??j.currentMaxOutputTokens)||void 0,streamRequired:e.streamRequired,previousResponseId:gi,reasoning:e.reasoning,promptCacheKey:e.promptCacheKey,promptCacheRetention:e.promptCacheRetention,serviceTier:e.serviceTier,openaiBuiltinTools:e.openaiBuiltinTools,maxToolCalls:e.maxToolCalls,parallelToolCalls:e.parallelToolCalls,textVerbosity:e.textVerbosity},y,_);for await(let d of fu(l,e.llmStreamIdleTimeoutMs??Qc))switch(d.type){case"delta":at.push(d.text);break;case"tool_call_delta":Zt=!0,Pn(Io,d);break;case"reasoning_delta":Xe.push(d.text);break;case"reasoning_block_complete":d.signature&&ce.push({thinking:Xe.join(""),signature:d.signature}),Xe.length=0;break;case"usage":te={inputTokens:d.promptTokens,outputTokens:d.completionTokens,reasoningTokens:d.reasoningTokens,cacheRead:d.cacheReadTokens,cacheWrite:d.cacheCreationTokens};break;case"response_id":rt||(c.lastResponseId=d.id);break;case"annotations":yield{type:"annotations",turnId:r,annotations:d.annotations};break;case"builtin_tool_status":yield{type:"heartbeat",turnId:r,message:`${d.toolType}: ${d.event}`};break;case"done":Oo=!0,Po=d.finishReason;break}if(Zt||$(k,"turn.after_inference",{...A,model:c.currentModel},o),e.postSamplingHooks&&e.postSamplingHooks.length>0){let d=c.currentModel;for(let h of e.postSamplingHooks)try{h({messages:[...it],model:d,sessionId:s})}catch{}}}catch(l){if(l instanceof Bt){$(k,"stop.failure",{sessionId:s,reason:l.code,error:l.message},o),yield{type:"error",turnId:r,error:l.message,code:l.code,usage:c.totalUsage};return}let d=yield*is(l,{state:c,guardState:j,fallbackModel:e.fallbackModel,signal:_,querySource:P,turnId:r,log:o,emitRecovery:M});if(d.kind==="return")return;if(d.kind==="continue"){c={...c,...d.patch};continue}I=d.streamError}if(!I&&!Oo){let l="LLM stream closed before a terminal event; the response was likely truncated upstream.";$(k,"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(I&&$(k,"turn.after_inference",{...A,model:c.currentModel,response:{error:I.message}},o),I){if(!rt&&c.lastResponseId&&/previous_response_id not found/i.test(I.message)){let l=(c.consecutiveApiRetries??0)+1;if(l<=Se){o.info("previous_response_id not found \u2014 disabling response-id chaining, retrying statelessly"),yield M("stateless_retry","previous_response_id not found; replaying full history"),rt=!0,c={...c,lastResponseId:void 0,consecutiveApiRetries:l,transition:void 0};continue}}if(Xn(I))lt=!0,o.info(`withheld prompt_too_long error (status=${I.status})`);else if(Kn(I))lt=!0,o.info(`withheld media_size error (status=${I.status})`);else{let l=Sn({status:I.status??500,message:I.message},j,Le);if(l.action==="reactive_compact"&&Ue(Q)&&(Q.attemptedThisTurn=!0,j.hasAttemptedReactiveCompact=!0,yield M("reactive_compact",`API ${I.status??500}: ${I.message}`)),l.action==="retry"){let h=(c.consecutiveApiRetries??0)+1;if(h>Se){o.info(`API retry limit reached (${Se}), aborting`);let T=$e(I.status,I.message);yield{type:"error",turnId:r,error:I.message,code:T,usage:c.totalUsage};return}yield M("retry",l.reason),c={...c,consecutiveApiRetries:h,transition:void 0};continue}let d=$e(I.status,I.message);$(k,"stop.failure",{sessionId:s,reason:d,error:I.message},o),yield{type:"error",turnId:r,error:I.message,code:d,usage:c.totalUsage};return}}te&&(c.totalUsage.inputTokens+=te.inputTokens,c.totalUsage.outputTokens+=te.outputTokens,te.reasoningTokens&&(c.totalUsage.reasoningTokens=(c.totalUsage.reasoningTokens??0)+te.reasoningTokens),te.cacheRead&&(c.totalUsage.cacheRead=(c.totalUsage.cacheRead??0)+te.cacheRead),te.cacheWrite&&(c.totalUsage.cacheWrite=(c.totalUsage.cacheWrite??0)+te.cacheWrite)),te?.inputTokens&&(j.promptTokens=te.inputTokens);let me=at.join(""),ne=[...Io.values()].map((l,d)=>({id:l.id||`tc_${r}_${d}`,type:"function",function:{name:l.name,arguments:l.arguments}}));if(ne=pu(ne),ne.length===0&&!Zt){me&&(c.finalText=me);let l=je([...b,...a??u]),d=e.toolChoice==="none"?null:xs({text:me,enabledToolNames:C(l)});if(d&&ko<2){if(ko++,!new Set(b.map(N=>N.function.name)).has(d.toolName)){let N=(a??u).filter(oe=>oe.function.name===d.toolName);if(N.length>0){let oe=C(b),he=new Map(b.map(x=>[x.function.name,x]));for(let x of N)he.set(x.function.name,x);b=je([...he.values()]),yield{type:"tool_selection_policy",turnId:r,policyId:"available_tool_reenabled_after_pseudo_output",intent:"tool_recovery",reason:"pseudo-tool-output-named-available-tool",availableToolNames:C(a??u),enabledToolNamesBefore:oe,enabledToolNamesAfter:C(b),suppressedToolNames:[],nextAction:"retry-with-native-tool-call"}}}c={...c,messages:[...m,{role:"assistant",content:me},{role:"user",content:`Your last response printed a pseudo tool invocation for ${d.toolName} instead of making a real tool call. Do not write XML tags, function-call prose, or placeholder tool syntax. Call the real ${d.toolName} tool now using the native tool-call channel, or explain why it cannot be used.`}],finalText:"",transition:{reason:"next_turn"}},U=!0,yield M("pseudo_tool_output_retry",d.toolName);continue}if(e.toolChoice==="required"&&!Ht&&b.length>0&&Co<2){Co++;let R=b.map(N=>N.function.name).filter(Boolean).slice(0,8).join(", ");c={...c,messages:[...m,{role:"user",content:`You must call one available tool before answering. Available tools for this request: ${R}. Do not answer from memory, prior context, or guesses.`}],finalText:"",transition:{reason:"next_turn"}};continue}if(lt&&I&&Xn(I)){if(c.transition?.reason!=="collapse_drain_retry"){let R=gn(it,Yt);if(R.committed>0){o.info(`collapse drain: committed ${R.committed} stages`),yield M("collapse_drain",`${R.committed} stages committed`),c={...c,messages:R.messages,transition:{reason:"collapse_drain_retry",committed:R.committed}};continue}}if(Ue(Q)){Q.attemptedThisTurn=!0,j.hasAttemptedReactiveCompact=!0,o.info("withheld 413: reactive compact attempt"),yield M("reactive_compact","withheld prompt_too_long"),c={...c,hasAttemptedReactiveCompact:!0,transition:{reason:"reactive_compact_retry"}};continue}o.info("withheld 413: recovery exhausted, surfacing error"),$(k,"stop.failure",{sessionId:s,reason:"prompt_too_long",error:I.message},o),yield{type:"error",turnId:r,error:I.message,code:"PROMPT_TOO_LONG",usage:c.totalUsage};return}if(lt&&I&&Kn(I)){if(Ue(Q)){Q.attemptedThisTurn=!0,j.hasAttemptedReactiveCompact=!0,o.info("withheld media error: reactive compact strip-retry"),yield M("reactive_compact","media error strip-retry"),c={...c,hasAttemptedReactiveCompact:!0,transition:{reason:"reactive_compact_retry"}};continue}o.info("withheld media error: recovery exhausted"),$(k,"stop.failure",{sessionId:s,reason:"media_error",error:I.message},o),yield{type:"error",turnId:r,error:I.message,code:"IMAGE_ERROR",usage:c.totalUsage};return}if(ns(Po)){j.consecutiveTruncations+=1;let R=e.modelMaxOutputTokens??dr,N=Mn(j,Le,R);if(N.shouldEscalate&&pe===void 0){j.currentMaxOutputTokens=N.newMax,o.info(`max_output_tokens escalate: ${N.newMax} tokens`),yield M("output_escalation",`${N.newMax} tokens`),c={...c,maxOutputTokensOverride:pr,transition:{reason:"max_output_tokens_escalate"}};continue}if(z<fr){let oe={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 #${z+1}`),yield M("max_output_tokens_recovery",`attempt ${z+1}`),c={...c,messages:[...it,oe],maxOutputTokensRecoveryCount:z+1,maxOutputTokensOverride:void 0,transition:{reason:"max_output_tokens_recovery",attempt:z+1}};continue}o.info("max_output_tokens recovery exhausted, completing with partial content")}else j.consecutiveTruncations=0;ee=Ct(ee,{replayMessages:m,lastStopReason:"completed"});let h=await ks({hooks:k,sessionId:s,messages:m,finalText:c.finalText,thinkingBlocks:ce,log:o});if(h?.action==="end"){let R=pi(h.content,m,"stop hook prevented continuation before completing the final status contract");yield*W(R);return}if(h?.action==="continue"){c={...c,messages:h.messages,stopHookActive:h.stopHookActive,transition:h.transition};continue}let T=Rs({tokenBudget:e.tokenBudget,totalUsage:c.totalUsage,budgetContinuationCount:c.budgetContinuationCount,lastBudgetDeltaTokens:c.lastBudgetDeltaTokens,lastBudgetGlobalTokens:c.lastBudgetGlobalTokens,messages:m,finalText:c.finalText,thinkingBlocks:ce,getBudgetContinuationMessage:e.runtimePorts.getBudgetContinuationMessage,log:o});if(T){yield M("budget_continuation",T.recoveryDetail),c={...c,messages:T.messages,budgetContinuationCount:T.budgetContinuationCount,lastBudgetDeltaTokens:T.lastBudgetDeltaTokens,lastBudgetGlobalTokens:T.lastBudgetGlobalTokens,transition:T.transition};continue}if(c.finalText.trim()&&Dc(c.lastTaskList)&&c.taskListReconciliationCount<1){let R=b.find(N=>N.function.name==="task")??(a??u).find(N=>N.function.name==="task");if(R){let N=Bc(c.lastTaskList),oe=C(b),he=Ce(O,Y);b=he.some(x=>x.function.name==="task")?he:je([...he,R]),c={...c,taskListReconciliationCount:c.taskListReconciliationCount+1,messages:[...m,{role:"assistant",content:c.finalText},{role:"user",content:N}],transition:{reason:"next_turn"}},U=!0,yield{type:"tool_selection_policy",turnId:r,policyId:"task_list_reconciliation_required",intent:"lifecycle_reconciliation",reason:"task-list-final-status-mismatch",availableToolNames:C(a??u),enabledToolNamesBefore:oe,enabledToolNamesAfter:C(b),suppressedToolNames:[],nextAction:"reconcile-task-list-before-final"},yield M("task_list_reconciliation_required","nudging task-list status sync before the final response");continue}}if(ae(i)&&!c.artifactContract.browserVerified&&Ft(c.artifactContract).length>0&&b.some(R=>R.function.name==="exec")&&c.browserAcceptanceRecoveryCount<4){let R=Us(c.artifactContract);c={...c,browserAcceptanceRecoveryCount:c.browserAcceptanceRecoveryCount+1,messages:[...m,{role:"assistant",content:c.finalText},{role:"user",content:R}],transition:{reason:"next_turn"}},U=!0,yield M("browser_acceptance_required","forcing browser automation before app/frontend completion");continue}if((e.buildVerificationGate??!0)&&Fn(i)&&!c.artifactContract.buildVerified&&c.artifactContract.buildFailureEvidence.length>0&&b.some(R=>R.function.name==="exec")&&c.buildVerificationRecoveryCount<3){let R=Oc(c.artifactContract);c={...c,buildVerificationRecoveryCount:c.buildVerificationRecoveryCount+1,messages:[...m,{role:"assistant",content:c.finalText},{role:"user",content:R}],transition:{reason:"next_turn"}},U=!0,yield M("build_verification_required","test/build still failing; forcing a fix+rerun before completion");continue}let f=eo({inputMessages:i,messages:m,finalText:c.finalText,thinkingBlocks:ce,stopHookActive:c.stopHookActive,totalToolCallCount:F,distinctToolNames:L,log:o});if(f){if(c.stopHookActive&&c.finalText.trim()===""){let R=Pe({inputMessages:i,messages:f.messages,reason:"stop hook produced an empty response after tool use"});if(R){yield*W(R);return}}c={...c,messages:f.messages,stopHookActive:f.stopHookActive,transition:f.transition};continue}if(F===0&&b.length>0&&e.toolChoice!=="none"&&Ro<1&&Zr(me)){Ro++,U=!0,yield M("intent_without_action","announced but did not act; forcing a tool call"),c={...c,messages:[...m,{role:"assistant",content:me},{role:"user",content:"You announced an action but did not take it. Carry it out NOW, in this response: call the appropriate tool to actually do what you just said you would do. Do not restate your intention or describe a plan \u2014 perform it."}],finalText:"",transition:{reason:"next_turn"}};continue}let v=to({totalToolCallCount:F,distinctToolNames:L,projectRoot:e.projectRoot});v&&(yield{type:"skill_instruction",turnId:r,instruction:v});let H=st(m,"the model ended with an empty response after tool use before completing the final status contract");for(let R of at)yield{type:"delta",turnId:r,text:R};yield*W(H);return}let hi=ce.length===0&&Xe.length>0?Xe.join(""):void 0;if(me)for(let l of at)yield{type:"delta",turnId:r,text:l};m.push(cn(ne,me||void 0,ce.length>0?ce:void 0,hi)),ee=xn(ee,{replayMessages:m,pendingToolCallIds:ne.map(l=>l.id),completedToolCallIds:ee.completedToolCallIds,lastStopReason:"tool_calls"});let ct=c.identicalCallCounts,Ke=[],ue=[],Ye=[],No=!1;for(let l of ne){if(Gc(l,c)){Ke.push(l);continue}let d=`${l.function.name}::${l.function.arguments}`,h=ct.get(d)??0;if(ct.set(d,h+1),h+1>ar){let T=so.has(l.function.name)||l.function.name==="exec"?c.identicalSuccessfulToolResults.get(d):void 0;if(T){Ye.push({call:l,result:T,repeatCount:h+1});continue}ue.push(l),No||(No=!0,o.info(`AP4 blocked: ${l.function.name} repeated ${h+1}x`))}else Ke.push(l)}let V=[],yi=new Set(b.map(l=>l.function.name)),Lo=new Set(ue.filter(l=>xu(l,yi)).map(l=>l.id));for(let l of Ye){let d=l.call,h=`Reused previous successful ${d.function.name} result for identical arguments (attempt ${l.repeatCount}); no additional tool execution was performed.
41
+ `)}function Zs(e){return ao.has(e)}function du(e){return e.benchmarkStateMaintenanceRequiredFiles.size>0&&[...e.benchmarkStateMaintenanceRequiredFiles].every(t=>fu(e,t))}function fu(e,t){if(e.benchmarkStateMaintenanceWrittenFiles.has(t))return!0;try{if(!Ne(t))return!1;let n=ke(t);if(n!=="document-index.json"&&n!=="context-pack-evidence.json")return!0;let o=jt(t,"utf8");return go(e.maintainedDocuments,t,JSON.stringify({content:o})).ok}catch{return!1}}function go(e,t,n){let o=ke(t);if(o!=="document-index.json"&&o!=="context-pack-evidence.json")return{ok:!0};let r=Su(n);if(!r)return{ok:!1,reason:`${o} write did not include JSON content`};let s=pe(r);if(!s)return{ok:!1,reason:`${o} content is not a JSON object`};if(o==="document-index.json"){let a=fe(s.documents);if(!a)return{ok:!1,reason:"document-index.json missing documents object"};for(let c of J.keys()){let f=e.get(c),h=fe(a[c]);if(!f||!h)return{ok:!1,reason:`document-index.json missing ${c}`};if(h.contentHash!==f.contentHash)return{ok:!1,reason:`document-index.json ${c} contentHash does not match read.details`};if(h.fileSizeBytes!==f.fileSizeBytes)return{ok:!1,reason:`document-index.json ${c} fileSizeBytes does not match read.details`}}return{ok:!0}}let i=fe(s.fileVerification);if(!i)return{ok:!1,reason:"context-pack-evidence.json missing fileVerification object"};for(let a of J.keys()){let c=e.get(a),f=fe(i[a]);if(!c||!f)return{ok:!1,reason:`context-pack-evidence.json missing ${a}`};if(f.contentHash!==c.contentHash)return{ok:!1,reason:`context-pack-evidence.json ${a} contentHash does not match read.details`};if(f.fileSizeBytes!==c.fileSizeBytes)return{ok:!1,reason:`context-pack-evidence.json ${a} fileSizeBytes does not match read.details`}}return{ok:!0}}function pu(e){if(!ai(e))return[];let t=mo(e);if(!t)return[];let n=[];for(let o of["document-index.json","context-pack-evidence.json"]){let r=`${t}/${o}`,s;try{if(!Ne(r))continue;s=jt(r,"utf8")}catch{continue}let i=go(e,r,JSON.stringify({content:s}));i.ok||n.push({path:r,reason:i.reason})}return n}function mu(e,t,n,o){if(e.filter(a=>a.name==="read"&&a.reason==="read-cycle-policy").length<iu)return!1;let s=new Set([...t].filter(po).map(ke));return[...J.keys()].every(a=>s.has(a))?[...J.keys()].every(a=>o.has(a))||n||cu(t):!1}function ci(e,t,n){if(e!=="write"||!n.has("edit")&&!n.has("patch"))return null;let o=Ut(t);if(!o)return null;try{if(!Ne(o))return null}catch{return null}return{path:o,error:`Existing file update blocked for "${o}". Use edit or patch for existing files so the event stream can distinguish file creation from incremental maintenance.`}}var $t=class extends Error{constructor(n){super(`LLM stream idle timeout after ${n}ms without a chunk.`);this.timeoutMs=n;this.name="LLMStreamIdleTimeoutError"}timeoutMs;code="LLM_STREAM_TIMEOUT"};async function*gu(e,t){if(!Number.isFinite(t)||t<=0){yield*e;return}let n=e[Symbol.asyncIterator]();try{for(;;){let o,r=await Promise.race([n.next(),new Promise(s=>{o=setTimeout(()=>s("timeout"),t)})]);if(o&&clearTimeout(o),r==="timeout")throw new $t(t);if(r.done)return;yield r.value}}finally{n.return?.().catch(()=>{})}}function lo(e){try{let t=JSON.parse(e),n=t.file_path??t.path??t.filePath;return typeof n=="string"&&n.trim()?n:void 0}catch{return}}function Ut(e){try{let t=JSON.parse(e),n=t.file_path??t.path??t.filePath;return typeof n=="string"&&n.trim()?n:void 0}catch{return}}function hu(e){return e.flatMap(t=>{if(yu(t.function.arguments))return[t];let n=bu(t.function.arguments);return n.length<2?[t]:n.map((o,r)=>({...t,id:`${t.id}__json_${r+1}`,function:{...t.function,arguments:JSON.stringify(o)}}))})}function yu(e){try{let t=JSON.parse(e);return!!t&&typeof t=="object"&&!Array.isArray(t)}catch{return!1}}function bu(e){let t=[],n=0,o=-1,r=!1,s=!1,i=0;for(let a=0;a<e.length;a+=1){let c=e[a];if(r){s?s=!1:c==="\\"?s=!0:c==='"'&&(r=!1);continue}if(c==='"'){r=!0;continue}if(c==="{"){if(n===0){if(e.slice(i,a).trim())return[];o=a}n+=1;continue}if(c!=="}"||(n-=1,n!==0||o<0))continue;let f=pe(e.slice(o,a+1));if(!f)return[];t.push(f),i=a+1,o=-1}return n!==0||r||e.slice(i).trim()?[]:t}function pe(e){try{let t=JSON.parse(e);return t&&typeof t=="object"&&!Array.isArray(t)?t:null}catch{return null}}function G(e){let t=e.trim().replace(/\\/g,"/");for(t=t.replace(/\/{2,}/g,"/");t.includes("/./");)t=t.replace(/\/\.\//g,"/");return t=t.replace(/\/\.$/,""),/^[a-z]:\//i.test(t)&&(t=t.toLowerCase()),t.replace(/\/$/,"")}function ke(e){let t=e.trim().replace(/\\/g,"/");return t.slice(t.lastIndexOf("/")+1).toLowerCase()}function ho(e){return`sha256:${hc("sha256").update(e).digest("hex")}`}function Tu(e,t){let n=t.split(/\r?\n/).map(a=>a.trim()).filter(Boolean),o=n[0]??e,r=n.find(a=>/record\s+0*1\b/i.test(a)),s=r&&r!==o?`${o}; ${r}`:o,i=s.length>180?`${s.slice(0,177)}...`:s;return i.toLowerCase().includes(e.toLowerCase())?i:`${e}: ${i}`}function Cu(e){return Object.fromEntries([...e.entries()].sort(([t],[n])=>t.localeCompare(n)))}function ku(e,t,n,o){let r=[...t.values()].sort((c,f)=>(c.name??"").localeCompare(f.name??""));if(r.length===0)return null;let s=r.map(c=>`${c.name??"document"}:${c.contentHash??"unknown"}`).join("|"),i=ri.map(c=>({...c,evidence:`read:long-horizon-documents:${ho(`${c.id}:${s}`)}`,lastConfirmedTurn:o})),a={strategy:"maintained-document-index",nextReadPolicy:"use maintained index before full document reread",budgetStatus:"within-budget",maxReadsPerDocument:rt,observedReadsByPath:Cu(n)};return{type:"document_maintenance",turnId:e,checkpointId:`${e}-docs-${r.length}`,documents:r,decisionStateTable:i,readCycleFindings:[],readCycleGuard:a}}function Ru(e){let t=e.find(o=>o.path)?.path??"",n=t.lastIndexOf("/");return n>0?t.slice(0,n):t}function Lt(e,t){return e.get(t)??null}function xu(e){let t=Lt(e,"requirements.md"),n=Lt(e,"decisions.md"),o=Lt(e,"defects.md"),r=Lt(e,"acceptance.md");if(!t||!n||!o||!r)return null;let s=[t,n,o,r];return{goal:`Maintain long-horizon project state from ${t.name}, ${n.name}, ${o.name}, and ${r.name}`,artifactRoot:Ru(s),decisions:[n.summary],defects:[o.summary],acceptanceCriteria:[r.summary],blockers:[],nextAction:"Continue from the maintained document index and read only explicitly missing sections"}}function _u(e,t){let n=xu(t);return n?[{type:"lifecycle",turnId:e,kind:"goal_reconstruction",reconstruction:n},{type:"lifecycle",turnId:e,kind:"memory_drift",status:"none",detail:"No memory drift detected against the maintained document index."}]:[]}function vu(e,t,n,o,r){let s=co(t,n,o,r);if(!s)return!1;let i=s.name;return i?(e.maintainedDocuments.set(i,s),!0):!1}function co(e,t,n,o){let r=ke(e);if(!J.has(r))return null;let s=Eu(t)??t,i=Mu(o,"contentHash"),a=qe(o??null,"fileSizeBytes"),c=i??ho(s);return{name:r,path:G(e),indexed:!0,maintained:!0,indexVersion:c,contentHash:c,summary:Tu(r,s),lastReviewedTurn:n,fileSizeBytes:a??Buffer.byteLength(s,"utf8"),recordCount:ui(s)}}function Au(e,t){return ci(e.function.name,e.function.arguments,t)!==null}function wu(e,t){let n=Ut(t.function.arguments);return`This exact write call to an existing file has been attempted ${e} times${n?` for "${n}"`:""}. Do not call write again for this existing file. Use edit or patch for the existing-file update, then continue verification.`}function Su(e){let n=pe(e)?.content;return typeof n=="string"?n:void 0}function Mu(e,t){let n=e?.[t];return typeof n=="string"&&n.trim()?n.trim():void 0}function ui(e){let t=e.split(/\r?\n/).map(n=>n.trim()).filter(Boolean).length;return Math.max(1,t)}function Eu(e){if(!e.includes("<persisted-output>"))return null;let n=e.match(/Full output saved to:\s*(.+?)(?:\r?\n|$)/)?.[1]?.trim();if(!n)return null;try{return Ne(n)?jt(n,"utf8"):null}catch{return null}}function Iu(e){let t=new Map;for(let s of e)if(!(s.role!=="assistant"||!Array.isArray(s.tool_calls)))for(let i of s.tool_calls){if(i.function?.name!=="read"||typeof i.id!="string"||typeof i.function.arguments!="string")continue;let a=lo(i.function.arguments);if(!a)continue;let c=G(a);si(c)===rt&&t.set(i.id,{path:c})}let n=new Map,o=new Map,r=!1;for(let s of e){if(s.role!=="tool"||typeof s.tool_call_id!="string"||s.is_error===!0)continue;let i=t.get(s.tool_call_id);if(!i)continue;let a=typeof s.content=="string"?s.content:"";if(!a||/^Error:/i.test(a.trim()))continue;n.set(i.path,(n.get(i.path)??0)+1);let c=co(i.path,a,0);c?.name&&o.set(c.name,c)}for(let s of Fu(e)){r=!0;for(let i of J.keys()){let a=G(`${s}/${i}`);if(n.set(a,Math.max(n.get(a)??0,rt)),!o.has(i)){let c=co(a,`${i} maintained by benchmark-state/document-index.json from prior conversation history.`,0);c?.name&&o.set(c.name,c)}}}for(let s of Pu(e)){r=!0;for(let i of s.documents)!i.name||!i.path||(n.set(i.path,Math.max(n.get(i.path)??0,rt)),o.set(i.name,i))}return{fileReadCounts:n,maintainedDocuments:o,persistedBenchmarkStateRecovered:r}}function Pu(e){let t=[];for(let n of Ou(e)){let o=Js(`${n}/document-index.json`),r=Js(`${n}/context-pack-evidence.json`),s=ze(o,"contextPackPath")??Nu(r);if(!s)continue;let i=Lu(s,o,r);i.length===J.size&&t.push({documents:i})}return t}function Ou(e){let t=new Set;for(let n of e){if(typeof n.content!="string")continue;let r=n.content.replace(/\\/g,"/").matchAll(/([a-zA-Z]:\/[^\s"'`<>]*?\/benchmark-state)(?=\/|[\s.,;:)\]}]|$)/g);for(let s of r){let i=G(s[1]??"");i&&t.add(i)}}return[...t]}function Js(e){try{if(!Ne(e))return null;let t=JSON.parse(jt(e,"utf8"));return t&&typeof t=="object"&&!Array.isArray(t)?t:null}catch{return null}}function ze(e,t){let n=e?.[t];return typeof n=="string"&&n.trim()?G(n):void 0}function Nu(e){let t=e?.fileVerification;if(!(!t||typeof t!="object"||Array.isArray(t)))for(let n of J.keys()){let o=t[n];if(!o||typeof o!="object"||Array.isArray(o))continue;let r=ze(o,"path");if(!r)continue;let s=`/${n}`;if(r.endsWith(s))return r.slice(0,-s.length)}}function Lu(e,t,n){let o=fe(t?.documents),r=fe(n?.fileVerification),s=[];for(let i of J.keys()){let a=fe(o?.[i]),c=fe(r?.[i]);if(!a&&!c)return[];let f=ze(a,"path"),y=ze(c,"path")??(f?.includes("/context-pack/")?f:G(`${e}/${i}`)),C=ze(a,"contentHash")??ze(c,"contentHash")??ho(`${i}:${y}`),x=typeof a?.summary=="string"&&a.summary.trim()?a.summary.trim():`${i} maintained by persisted benchmark-state/document-index.json.`;s.push({name:i,path:G(y),indexed:!0,maintained:!0,indexVersion:String(a?.indexVersion??C),contentHash:C,summary:x,lastReviewedTurn:uo(a,"lastReviewedTurn")??uo(n,"turn")??0,fileSizeBytes:qe(a,"fileSizeBytes")??qe(c,"fileSizeBytes")??qe(c,"sizeBytes")??Buffer.byteLength(x,"utf8"),recordCount:qe(a,"recordCount")??qe(c,"recordCount")??ui(x)})}return s}function uo(e,t){let n=e?.[t];return typeof n=="number"&&Number.isFinite(n)?n:void 0}function qe(e,t){let n=uo(e,t);return n&&n>0?n:void 0}function Fu(e){let t=e.slice(0,Math.max(0,e.length-1)),n=new Set;for(let o of t){if(typeof o.content!="string")continue;let r=o.content.replace(/\\/g,"/").toLowerCase();if(!r.includes("benchmark-state/document-index")&&!r.includes("benchmark-state/context-pack-evidence")&&!r.includes("maintained document index"))continue;let s=r.matchAll(/([a-z]:\/[^\s"'`<>]*?\/context-pack)(?=\/|[\s.,;:)\]}]|$)/gi);for(let i of s){let a=G(i[1]??"");a&&n.add(a)}}return[...n]}function Bu(e){e.identicalSuccessfulToolResults.clear();for(let t of[...e.identicalCallCounts.keys()]){let n=t.slice(0,t.indexOf("::"));io.has(n)&&e.identicalCallCounts.delete(t)}}async function*di(e,t,n,o){let{turnId:r,sessionId:s,messages:i,availableTools:a,tools:c,model:f,apiKey:h,temperature:y=0,hooks:C,signal:x}=e,v={sessionId:s,turnId:r},A=e.maxTurns??0,P=e.querySource,S=e.runtimePorts.resolveToolEligibility(c,e.toolEligibilityContext),O=S.eligibleTools,D=[];for(let m of S.blockedTools)D.push({name:m.toolName,reason:"blocked-by-policy"}),yield{type:"tool_blocked",turnId:r,callId:"",name:m.toolName,reason:"blocked-by-policy"};let q=is(e.maxRounds,i),se=as(e.maxToolCalls,i),qt=!(typeof e.maxRounds=="number"&&e.maxRounds>=1)&&!(typeof e.maxToolCalls=="number"&&e.maxToolCalls>=1),yo=St(i),Le={contextWindowTokens:e.contextWindowTokens??dr,responseBufferTokens:fr,maxOutputTokens:e.maxOutputTokens??pr,abortSignal:x,reactiveCompactEnabled:!0,outputEscalationEnabled:!0},L=new Set,F=0,bo=new Set,To=0,He=0,Ge=0,st=0,Co=new Map,Y=new Set,b=Te(O,Y),We=!1,zt=!1,Ht,Gt=()=>k(b),yi=yc(O,i),Wt=!1,ko=0,Ro=0,xo=0,U=!1,it=!1,Vt=Iu(i),u={messages:[...i],maxOutputTokensRecoveryCount:0,hasAttemptedReactiveCompact:!1,maxOutputTokensOverride:void 0,turnCount:1,transition:void 0,guardState:Mn(Le),reactiveCompactState:Nn(),toolLoopState:xt({maxRounds:q,replayMessages:[...i]}).state,consecutiveFailedRounds:0,finalText:"",totalUsage:{inputTokens:0,outputTokens:0},collapseStore:hn(),currentModel:f,consecutive529Errors:0,consecutiveApiRetries:0,stopHookActive:void 0,lastResponseId:void 0,snipRemovedIds:new Set,contentReplacementState:e.runtimePorts.createContentReplacementState(),budgetContinuationCount:0,repeatedToolFailureRecoveryCount:0,lastBudgetDeltaTokens:0,lastBudgetGlobalTokens:0,identicalCallCounts:new Map,identicalSuccessfulToolResults:new Map,toolFailureCounts:new Map,fileReadCounts:Vt.fileReadCounts,fileReadCycleBlockedPaths:new Set,fileReadCycleNudgedPaths:new Set,maintainedDocuments:Vt.maintainedDocuments,persistedBenchmarkStateRecovered:Vt.persistedBenchmarkStateRecovered,benchmarkStateMaintenanceRequiredFiles:new Set,benchmarkStateMaintenanceWrittenFiles:new Set,recoveryTrace:new Map,artifactContract:Xr(i),browserAcceptanceRecoveryCount:0,buildVerificationRecoveryCount:0,benchmarkStateIntegrityRecoveryCount:0,backgroundAgentTaskIds:new Set,backgroundAgentNoOutputPollCounts:new Map,stalledBackgroundAgentTasks:new Map,notOfferedToolRecoveryCount:0,existingFileUpdateRecoveryCount:0,taskListReconciliationCount:0,lastTaskList:[]},Xt=Math.max(A*5,200),bi=4,Ti=4,_o=0,vo=new Map,Kt,M=(m,z)=>{let Q=`${m}:${z??""}`,ie=(vo.get(Q)??0)+1;if(vo.set(Q,ie),m==="autocompact"){let j=u.recoveryTrace.get("autocompact")??0;if(ie>bi||j>=Ti){let ee=`Repeated context compression made no forward progress: ${z??"autocompact"}`;return Kt=ee,u.recoveryTrace.set("compression_loop_guard",(u.recoveryTrace.get("compression_loop_guard")??0)+1),{type:"recovery",turnId:r,action:"compression_loop_guard",detail:ee}}}return u.recoveryTrace.set(m,(u.recoveryTrace.get(m)??0)+1),{type:"recovery",turnId:r,action:m,detail:z}},Ao=()=>({type:"tool_use_summary",turnId:r,availableToolNames:k(a??c),enabledToolNames:Gt(),toolCallNames:[...L].sort(),blockedToolCalls:Nt(D)}),wo=qr((a??c).map(m=>m.function.name)),Yt=!1,So=m=>({type:"end",turnId:r,content:m,usage:u.totalUsage,model:u.currentModel,...u.recoveryTrace.size>0?{recoveryTrace:Object.fromEntries(u.recoveryTrace)}:{}});function*W(m,z){let Q=Kr({content:m,contractActive:wo,totalToolCallCount:F,distinctToolNames:L,visibleToolCallCount:To,visibleToolNames:bo,artifactContract:u.artifactContract,blockedToolCalls:Nt(D),activeTasks:u.lastTaskList,forcedStop:z?.forcedStop??Yt});Q.malformedBlock&&(yield M("final_status_block_malformed","final-status block was not valid schema-1 JSON; treated as absent")),jn(u.artifactContract,Q.content),Jt()&&(yield Zt()),yield Ao(),yield So(Q.content)}function*Mo(m){yield Ao(),yield So(m)}let Zt=()=>({type:"artifact_contract",turnId:r,...Un(u.artifactContract,i)}),Jt=()=>{let m=Un(u.artifactContract,i);return!!(m.requiresBrowserAcceptance||m.artifactRoot||m.writePaths.length>0||m.outOfRootWrites.length>0||m.devServerUrls.length>0||m.browserVerified)},at=(m,z)=>(Yt=!0,u.finalText||Gn(m,o)),Ci=(m,z,Q)=>{Yt=!0;let ie=Pe({inputMessages:i,messages:z,reason:Q});return ie||m||Gn(z,o)};for(;;){if(_o++,_o>Xt){o.info(`hard iteration cap reached (${Xt}), forcing completion`);let l=at(u.messages,`hard iteration cap reached (${Xt}) before completing the final status contract`);yield*W(l);return}let{messages:m,maxOutputTokensRecoveryCount:z,maxOutputTokensOverride:Q,turnCount:ie,guardState:j,reactiveCompactState:ee,collapseStore:Qt}=u,{toolLoopState:te}=u;if(e.refreshTools&&ie>1){let l=e.refreshTools(),d=Te(l,Y);d!==b&&(b=d,o.debug(`tools refreshed: ${l.length} tools`))}if(On(j,Le)){o.info(`turn aborted by guard at turn ${ie}`),yield{type:"error",turnId:r,error:"Turn aborted",code:"ABORTED",usage:u.totalUsage};return}let Re=En(j,Le);if(Re.level==="blocking"){Re.reason==="prompt_too_long"&&$e(ee)&&(ee.attemptedThisTurn=!0,j.hasAttemptedReactiveCompact=!0,o.info(`token budget blocking (${Re.reason}), reactive compact needed`),yield M("reactive_compact","token budget pre-check")),o.info(`token budget blocking (${Re.reason}), ending tool loop`);break}Re.level==="warning"&&o.info(`token budget warning: ${Re.usagePercent}% used, ${Re.remainingTokens} remaining`);let lt=yield*ps({messages:m,contentReplacementState:u.contentReplacementState,snipRemovedIds:u.snipRemovedIds,collapseStore:Qt,guardState:j,guardConfig:Le,runtimePorts:e.runtimePorts,hooks:C,hookCtx:v,sessionId:s,currentModel:u.currentModel,log:o,recovery:M,onAutocompact:()=>{u.hasAttemptedReactiveCompact=!1}});if(Kt){yield*W(`${Kt}. Stop compressing the same context repeatedly; continue from the maintained document index or report the incomplete state explicitly.`,{forcedStop:!0});return}let ki=U?"required":e.toolChoice==="required"&&Wt?"auto":e.toolChoice??"auto";U=!1;let Ve=kn({tools:b,toolChoice:ki}),Eo=k(Ve.tools).join("\0"),Io=Ht!==void 0&&Ht!==Eo;Io&&u.lastResponseId&&(yield M("stateless_retry","tool schema changed; replaying full history without previous_response_id"));let Ri=it||Io?void 0:u.lastResponseId;Ht=Eo;let Xe=xt({maxRounds:q,replayMessages:lt,lastStopReason:te.lastStopReason,options:{stopReason:te.lastStopReason}}),Po=[Ve.extraSystemPrompt,wo?zr:void 0].filter(l=>!!l).join(`
41
42
 
42
- ${l.result.content}`,T=X(d.id,{ok:!0,payload:h,imageUrls:l.result.imageUrls,toolReferences:l.result.toolReferences});m.push(T),V.push(d.id),L.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}}}if(Ye.some(l=>l.call.function.name==="exec"&&js(l.call.function.arguments))){let l=C(b);m.push({role:"user",content:Fc(c.artifactContract)}),yield{type:"tool_selection_policy",turnId:r,policyId:"browser_verification_after_preparation_required",intent:"verification",reason:"repeated-browser-preparation-command",availableToolNames:C(a??u),enabledToolNamesBefore:l,enabledToolNamesAfter:l,suppressedToolNames:[],nextAction:"run-browser-verification-script-not-playwright-install"},yield M("browser_verification_after_preparation_required","reused successful browser preparation command")}for(let l of ue){D.push({name:l.function.name,reason:"identical-repeat-policy"});let d=ct.get(`${l.function.name}::${l.function.arguments}`),h=vt(m,l.function.name),T=Sc(h),f=Lo.has(l.id)?_u(d,l):T?`This exact tool call has been attempted ${d} times. Last error: ${T}. 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.`,v=X(l.id,{ok:!1,error:f});m.push(v),V.push(l.id),L.add(l.function.name),F++,yield{type:"tool_result",turnId:r,callId:l.id,name:l.function.name,ok:!1,error:f}}if(ue.length>0&&Ke.length===0&&Ye.length===0&&ue.every(l=>Lo.has(l.id))&&c.existingFileUpdateRecoveryCount<2){let l=C(b);b=Fs(O,Y);let d=C(b);We=!0,U=!0;let h=[...new Set(ue.map(T=>Dt(T.function.arguments)).filter(T=>!!T))];m.push({role:"user",content:`Existing-file maintenance recovery: the same write call was repeatedly attempted for an existing file. Do not use write for these existing path(s): ${h.join(", ")||"(unknown)"}. Do not delete, remove, or recreate an existing file to make write succeed; that is artifact path drift, not maintenance. Use read only if you need the current contents, then use edit or patch for the smallest valid change. After the edit/patch succeeds, continue build/browser verification normally.`}),yield{type:"tool_selection_policy",turnId:r,policyId:"existing_file_update_recovery",intent:"tool_recovery",reason:"repeated-existing-file-write",availableToolNames:C(a??u),enabledToolNamesBefore:l,enabledToolNamesAfter:d,suppressedToolNames:oo(l,d),nextAction:"use-read-edit-or-patch-for-existing-file-update"},yield M("existing_file_update_recovery",h.join(",")||"unknown"),c={...c,messages:m,existingFileUpdateRecoveryCount:c.existingFileUpdateRecoveryCount+1,transition:{reason:"next_turn"}};continue}if(ue.length>0){let l=vt(m,ue[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."};m.push(d)}let bi=ho>=3&&c.repeatedToolFailureRecoveryCount<1;if(ue.length>0&&Ke.length===0&&Ye.length===0&&!bi){let l=qs(Gn(m,1),{availableToolNames:C(a??u),enabledToolNames:zt(),toolCallNames:[...L].sort(),blockedToolCalls:Pt(D)});yield*W(l);return}let Fo=[],Jt=[];for(let l of Ke){let d=Dr({toolName:l.function.name,rawArguments:l.function.arguments});d?Jt.push({call:l,...d}):Fo.push(l)}for(let l of Jt){let d=l.call;D.push({name:d.function.name,reason:"read-only-context-pack"}),m.push(X(d.id,{ok:!1,error:l.error})),V.push(d.id),L.add(d.function.name),F++,yield{type:"tool_result",turnId:r,callId:d.id,name:d.function.name,ok:!1,error:l.error},o.warn(`read-only context-pack blocked: ${d.function.name} ${l.path}`)}Jt.length>0&&m.push({role:"user",content:"A write was blocked because context-pack is read-only evidence. Continue by writing compact indexes, checkpoints, and maintenance updates under benchmark-state; do not retry writes into context-pack."});let Ti=new Set(b.map(l=>l.function.name)),Bo=[],ut=[];for(let l of Fo){let d=ti(l.function.name,l.function.arguments,Ti);d?ut.push({call:l,...d}):Bo.push(l)}for(let l of ut){let d=l.call;D.push({name:d.function.name,reason:"existing-file-update-tool-required"}),m.push(X(d.id,{ok:!1,error:l.error})),V.push(d.id),L.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(`existing file update blocked: ${d.function.name} ${l.path}`)}if(ut.length>0){let l=C(b);b=Fs(O,Y);let d=C(b);We=!0,U=!0;let h=[...new Set(ut.map(T=>T.path))];m.push({role:"user",content:`Existing-file maintenance recovery: a write was blocked because the target file already exists and edit/patch are enabled. Do not use write for these existing path(s): ${h.join(", ")||"(unknown)"}. Do not delete, remove, or recreate an existing file to make write succeed; that is artifact path drift, not maintenance. Use read only if you need the current contents, then use edit or patch for the smallest valid change. After the edit/patch succeeds, continue build/browser verification normally.`}),yield{type:"tool_selection_policy",turnId:r,policyId:"existing_file_update_recovery",intent:"tool_recovery",reason:"existing-file-write-blocked",availableToolNames:C(a??u),enabledToolNamesBefore:l,enabledToolNamesAfter:d,suppressedToolNames:oo(l,d),nextAction:"use-read-edit-or-patch-for-existing-file-update"},yield M("existing_file_update_recovery",h.join(",")||"unknown"),c={...c,messages:m,existingFileUpdateRecoveryCount:c.existingFileUpdateRecoveryCount+1,transition:{reason:"next_turn"}};continue}let Do=[],Qt=[];for(let l of Bo){let d=Br({state:c.artifactContract,inputMessages:i,toolName:l.function.name,rawArguments:l.function.arguments});d?Qt.push({call:l,...d}):Do.push(l)}for(let l of Qt){let d=l.call;D.push({name:d.function.name,reason:"artifact-root-contract"}),Dn(c.artifactContract,{path:l.path,artifactRoot:l.artifactRoot,toolName:d.function.name}),m.push(X(d.id,{ok:!1,error:l.error})),V.push(d.id),L.add(d.function.name),F++,yield{type:"tool_result",turnId:r,callId:d.id,name:d.function.name,ok:!1,error:l.error},Kt()&&(yield Xt()),o.warn(`artifact root contract blocked: ${d.function.name}`)}Qt.length>0&&m.push({role:"user",content:"A write was blocked by the artifactRoot contract. Continue inside the declared artifactRoot, or stop with an honest final status that lists the root drift as Not done."});let $o=[],en=[];for(let l of Do){let d=Ts({inputMessages:i,messages:m,toolCall:l});d?en.push({call:l,error:d}):$o.push(l)}for(let l of en){let d=l.call;D.push({name:d.function.name,reason:"premature-completion-artifact"}),m.push(X(d.id,{ok:!1,error:l.error})),V.push(d.id),L.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}`)}en.length>0&&m.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 Ci=new Set(b.map(l=>l.function.name)),Uo=[],dt=[];for(let l of $o)Ci.has(l.function.name)?Uo.push(l):dt.push(l);for(let l of dt){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.`;D.push({name:l.function.name,reason:"not-offered"}),m.push(X(l.id,{ok:!1,error:d})),V.push(l.id),L.add(l.function.name),o.warn(`unoffered tool call suppressed: ${l.function.name}`)}if(dt.length>0&&c.notOfferedToolRecoveryCount<1){let l=[...new Set(dt.map(v=>v.function.name))].sort(),d=We&&l.includes("write"),h=l.filter(v=>Y.has(v)),f=(a??u).filter(v=>l.includes(v.function.name));if(h.length>0)c.notOfferedToolRecoveryCount+=1,U=!0,m.push({role:"user",content:`You retried ${h.map(v=>`\`${v}\``).join(", ")} after it was disabled by this turn's tool-selection policy. Do not retry policy-suppressed tools in this turn. Continue using only the currently enabled tools, or stop with a clear blocker.`}),yield{type:"tool_selection_policy",turnId:r,policyId:"policy_suppressed_tool_retry_blocked",intent:"tool_recovery",reason:"requested-tool-disabled-by-turn-policy",availableToolNames:C(a??u),enabledToolNamesBefore:C(b),enabledToolNamesAfter:C(b),suppressedToolNames:h,nextAction:"continue-with-currently-enabled-tools-or-report-blocker"},yield M("policy_suppressed_tool_retry_blocked",h.join(","));else if(!d&&f.length>0){let v=C(b),H=new Map(b.map(R=>[R.function.name,R]));for(let R of f)H.set(R.function.name,R);b=je([...H.values()]),c.notOfferedToolRecoveryCount+=1,U=!0,yield{type:"tool_selection_policy",turnId:r,policyId:"available_tool_reenabled_after_not_offered_call",intent:"tool_recovery",reason:"requested-tool-available-but-disabled",availableToolNames:C(a??u),enabledToolNamesBefore:v,enabledToolNamesAfter:C(b),suppressedToolNames:[],nextAction:"retry-with-reenabled-requested-tool"},m.push({role:"user",content:`You called ${l.map(R=>`\`${R}\``).join(", ")} but it was not enabled for that round even though it is available. The requested available tool has now been re-enabled. Use the re-enabled tool once with valid arguments; do not repeat a disabled-tool call.`}),yield M("available_tool_reenabled_after_not_offered_call",l.join(","))}}let jo=[],tn=[];for(let l of Uo){let d=b.find(T=>T.function.name===l.function.name),h=Uc(d,l.function.arguments);h?tn.push({call:l,error:h}):jo.push(l)}for(let l of tn){let d=l.call;D.push({name:d.function.name,reason:"invalid-arguments"}),m.push(X(d.id,{ok:!1,error:l.error})),V.push(d.id),L.add(d.function.name),F++,yield{type:"tool_result",turnId:r,callId:d.id,name:d.function.name,ok:!1,error:l.error,details:{type:d.function.name,error:"invalid_arguments"}},o.info(`invalid tool arguments blocked: ${d.function.name}`)}tn.length>0&&m.push({role:"user",content:"Some tool calls were blocked before execution because they did not match the tool schema. Do not retry the same tool with substituted fields. Use the required field names exactly, switch to the correct tool, or stop and report the invalid tool input."});let ft=[],nn=[];for(let l of jo){if(l.function.name!=="exec"){ft.push(l);continue}let d=Bs(l.function.arguments);if(!d){ft.push(l);continue}let h=Is(d);Ps(h)&&Ls(O)?nn.push({call:l,error:$c(h)}):ft.push(l)}for(let l of nn){let d=l.call;D.push({name:d.function.name,reason:"dedicated-tool-required"});let h=C(b),T=b.filter(f=>["read","search"].includes(f.function.name));T.length>0&&(b=T,jt=!0,U=!0),m.push(X(d.id,{ok:!1,error:l.error})),V.push(d.id),L.add(d.function.name),F++,yield{type:"tool_result",turnId:r,callId:d.id,name:d.function.name,ok:!1,error:l.error,details:{type:d.function.name,error:"dedicated_tool_required",dedicatedTool:"read/search"}},o.info(`dedicated file tool preflight blocked: ${d.function.name}`),yield{type:"tool_selection_policy",turnId:r,policyId:"dedicated_file_tool_required",intent:"fresh_evidence",reason:"exec-file-read-search-list-blocked",availableToolNames:C(a??u),enabledToolNamesBefore:h,enabledToolNamesAfter:C(b),suppressedToolNames:h.filter(f=>!["read","search"].includes(f)),nextAction:"use-read-search-for-file-inspection-then-resume-build-run-verify-tools"}}nn.length>0&&m.push({role:"user",content:"Exec was blocked because it attempted local file reading/searching/listing. Use read/search for the next local file inspection step. After that, resume exec only for non-inspection commands such as installs, builds, dev servers, and verification scripts."});let pt=[],on=[],qo=[],zo=[];for(let l of ft){if(l.function.name!=="exec"){pt.push(l);continue}let d=l,h=Bs(d.function.arguments),T=h?Ic(h):null;T&&(d={...d,function:{...d.function,arguments:$s(d.function.arguments,T)}},zo.push({originalCommand:h??"",rewrittenCommand:T}),h=T);let f=h?Pc(h):null;if(f?.action==="block")on.push({call:d,error:f.error});else if(f?.action==="rewrite"){let v={...d,function:{...d.function,arguments:$s(d.function.arguments,f.command)}};qo.push({call:v,originalCommand:h??"",rewrittenCommand:f.command}),pt.push(v)}else pt.push(d)}for(let l of zo)yield{type:"tool_selection_policy",turnId:r,policyId:"exec_sleep_prefix_guard",intent:"verification",reason:"sleep-prefix-removed",availableToolNames:C(a??u),enabledToolNamesBefore:C(b),enabledToolNamesAfter:C(b),suppressedToolNames:[],nextAction:"execute-command-without-blocking-sleep-prefix"},o.info(`blocking sleep prefix removed before exec: ${l.originalCommand} -> ${l.rewrittenCommand}`);for(let l of qo){let d=C(b);yield{type:"tool_selection_policy",turnId:r,policyId:"reserved_frontend_port_guard",intent:"verification",reason:"vite-strict-port-normalized",availableToolNames:C(a??u),enabledToolNamesBefore:d,enabledToolNamesAfter:C(b),suppressedToolNames:[],nextAction:"execute-normalized-vite-dev-server-command-with-strict-port"},o.info(`vite strict port normalized before exec: ${l.originalCommand} -> ${l.rewrittenCommand}`)}for(let l of on){let d=l.call;D.push({name:d.function.name,reason:"reserved-frontend-port"});let h=C(b);m.push(X(d.id,{ok:!1,error:l.error})),V.push(d.id),L.add(d.function.name),F++,yield{type:"tool_result",turnId:r,callId:d.id,name:d.function.name,ok:!1,error:l.error,details:{type:d.function.name,error:"reserved_frontend_port",reservedPort:Lt}},o.info(`reserved frontend port preflight blocked: ${d.function.name}`),yield{type:"tool_selection_policy",turnId:r,policyId:"reserved_frontend_port_guard",intent:"verification",reason:"reserved-frontend-port",availableToolNames:C(a??u),enabledToolNamesBefore:h,enabledToolNamesAfter:C(b),suppressedToolNames:[],nextAction:"restart-generated-dev-server-on-explicit-non-5174-port-with-strict-port"}}on.length>0&&m.push({role:"user",content:"A dev server command was blocked because it could occupy or fallback onto port 5174, which is reserved for the Xiaozhi Claw frontend. Retry with an explicit generated-app port other than 5174 and use --strictPort for Vite so browser evidence cannot be polluted."});let mt=[],Be=[];for(let l of pt){if(l.function.name!=="read"){mt.push(l);continue}let d=ao(l.function.arguments);if(!d){mt.push(l);continue}let h=G(d),T=Zs(h);(c.fileReadCounts.get(h)??0)>=T?Be.push({call:l,filePath:h,maxReads:T}):mt.push(l)}for(let l of Be){let d=l.call,h=`Read cycle policy blocked another read of "${l.filePath}" after ${l.maxReads} successful reads in this turn. Stop rereading the same large document. ${ro(l.filePath)}`;D.push({name:d.function.name,reason:"read-cycle-policy"}),c.fileReadCycleBlockedPaths.add(l.filePath),m.push(X(d.id,{ok:!1,error:h})),V.push(d.id),L.add(d.function.name),F++,yield{type:"tool_result",turnId:r,callId:d.id,name:d.function.name,ok:!1,error:h},o.info(`read cycle blocked: ${l.filePath}`)}if(Be.length>0){let l=[...new Set(Be.map(T=>`${T.filePath} (max ${T.maxReads})`))].join(", "),d=[...new Set(Be.map(T=>ro(T.filePath)))].join(" ");if(m.push({role:"user",content:`Further reads were blocked because these large/context documents already reached their per-turn read limit: ${l}. Do not retry the read with a different path spelling. ${d} Continue from maintained requirements/defects/decisions/acceptance evidence and report any truly missing section explicitly.`}),b.some(T=>zs(T.function.name))&&(c.persistedBenchmarkStateRecovered||Be.some(T=>fo(T.filePath)))){let T=C(b),f=T.filter(v=>su.has(v)).sort();yield{type:"tool_selection_policy",turnId:r,policyId:"long_horizon_benchmark_state_maintenance",intent:"benchmark_state_maintenance",reason:"read-cycle-guard-retains-evidence-tools",availableToolNames:C(a??u),enabledToolNamesBefore:T,enabledToolNamesAfter:C(b),suppressedToolNames:[],nextAction:"maintenance-or-final-answer"},m.push({role:"user",content:`Do not reread the blocked large/context document paths again. Evidence tools still enabled: ${f.join(", ")||"none"}. Use read/search only for targeted verification of generated artifacts, file names, and missing sections; use edit/patch/write only if benchmark-state maintenance needs an update; otherwise stop tool use and answer from the maintained benchmark-state evidence. Classify any unused edit/patch/write tools as not needed, not missing.`}),yield M("benchmark_state_maintenance_tool_bias","retaining targeted evidence tools after long-horizon read-cycle guard")}if(du(D,c.fileReadCycleBlockedPaths,c.persistedBenchmarkStateRecovered,c.maintainedDocuments)){yield*W("Stopped repeated long-horizon context-pack rereads after the read-cycle guard blocked every maintained source document. Continue from benchmark-state/document-index.json, decision-state-table.json, and context-pack-evidence.json; do not reread or rewrite context-pack source documents.");return}}let rn=vs(mt,c.toolFailureCounts),sn=rn.allowed;if(Ut&&sn.length>Math.max(0,re-F)){let l=Vn({currentToolBudget:re,currentRoundBudget:q,toolHardCap:100,roundHardCap:100,continuationCount:Ge,successfulSinceLastCheck:He-ot,fileReadCounts:c.fileReadCounts,windowTools:be,windowRounds:25});l&&(re=l.nextToolBudget,q=l.nextRoundBudget,Ge=l.continuationCount,ot=He,o.info(`tool budget continuation #${l.continuationCount}: tools\u2192${re}, rounds\u2192${q} (progress detected)`))}let Ho=Math.max(0,re-F),ge=Ho>0?sn.slice(0,Ho):[],an=sn.slice(ge.length),ki=an.length>0;if(rn.blocked.length>0){for(let l of rn.blocked){let d=l.call;D.push({name:d.function.name,reason:"variant-failure-policy"});let h=X(d.id,{ok:!1,error:l.error});m.push(h),V.push(d.id),L.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`)}m.push(ws())}if(an.length>0){let l=`Tool call budget exhausted (${re}) for this turn. Stop requesting more tools and report what remains incomplete.`;for(let d of an){D.push({name:d.function.name,reason:"tool-call-budget"});let h=X(d.id,{ok:!1,error:l});m.push(h),V.push(d.id),L.add(d.function.name),F++,yield{type:"tool_result",turnId:r,callId:d.id,name:d.function.name,ok:!1,error:l}}m.push({role:"user",content:`${l} You reached this turn's tool budget after ${Ge} 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 ge){let d=l.function.arguments,h=b.find(T=>T.function.name===l.function.name);if(h?.backfillObservableInput)try{let T=JSON.parse(l.function.arguments),f={...T};h.backfillObservableInput(f),Object.keys(f).some(H=>!(H in T))&&(d=JSON.stringify(f))}catch{}yield{type:"tool_call",turnId:r,callId:l.id,name:l.function.name,arguments:d,inputSummary:Wn(d)},yo.add(l.function.name),bo++}let Ri=new Map(c.toolFailureCounts),gt=null;try{let l=e.runtimePorts.createStreamingToolExecutor({toolInvoker:n,hooks:k,sessionId:s,turnId:r,log:o,signal:_,maxConcurrentTools:e?.maxConcurrentTools,maxExecutionMs:sr});for(let f of ge)l.addTool(f);let d=!1;for await(let f of l.getRemainingResults()){let v=wc(f);if(v){if(D.push({name:f.toolName,reason:v}),f.toolName==="exec"&&v==="dedicated-tool-required"&&Ls(O)){let x=C(b);m.push({role:"user",content:"Exec was blocked because it attempted local file reading/searching/listing. Use read/search for local file inspection. Exec remains available only for non-inspection commands such as installs, builds, dev servers, and verification scripts."}),yield{type:"tool_selection_policy",turnId:r,policyId:"dedicated_file_tool_required",intent:"fresh_evidence",reason:"exec-file-read-search-list-blocked",availableToolNames:C(a??u),enabledToolNamesBefore:x,enabledToolNamesAfter:C(b),suppressedToolNames:[],nextAction:"use-read-search-for-file-inspection-or-exec-for-build-run-verify"}}if(f.toolName==="exec"&&v==="confirmation-timeout"){let x=C(b);Y.add("exec");let E=Ce(O,Y);E.length>0&&(b=je(E),U=!0),m.push({role:"user",content:"Exec confirmation timed out, so exec is disabled for the rest of this turn. Do not retry exec. Use read/search for inspection, edit/patch/write for file updates, ask_user only for missing user input, or stop with a clear blocker if no non-exec tool can complete the request."}),yield{type:"tool_selection_policy",turnId:r,policyId:"exec_confirmation_timeout_recovery",intent:"tool_recovery",reason:"exec-confirmation-timeout",availableToolNames:C(a??u),enabledToolNamesBefore:x,enabledToolNamesAfter:C(b),suppressedToolNames:oo(x,C(b)),nextAction:"continue-with-non-exec-tools-or-report-confirmation-blocker"}}if(f.toolName==="exec"&&v==="global-process-kill-blocked"){let x=C(b);m.push({role:"user",content:"Exec was blocked because it attempted to terminate every node process. Do not retry taskkill/killall/pkill/Stop-Process by process name. If a generated app server conflicts with another process, start the generated app on a new explicit non-5174 port with strict port behavior, or stop only an owned background task by its task id. Continue by verifying the app on the reachable generated-app URL."}),yield{type:"tool_selection_policy",turnId:r,policyId:"global_process_kill_recovery",intent:"verification",reason:"global-node-process-kill-blocked",availableToolNames:C(a??u),enabledToolNamesBefore:x,enabledToolNamesAfter:C(b),suppressedToolNames:[],nextAction:"use-owned-task-cancel-or-new-explicit-port"}}}f.blocked&&(yield{type:"tool_blocked",turnId:r,callId:f.callId,name:f.toolName,reason:f.blockReason??"blocked"}),m.push(f.message),V.push(f.callId),L.add(f.toolName);let H=Wc(f,c);H||F++;let R=f.ok&&zn(f);if(f.ok&&!R&&!H&&(He+=1),H||As({toolFailureCounts:c.toolFailureCounts,toolName:f.toolName,toolArguments:ge.find(x=>x.id===f.callId)?.function.arguments,ok:f.ok,softEmpty:R}),f.ok&&Jc.has(f.toolName)&&Nu(c),f.ok&&zs(f.toolName)){let x=ge.find(B=>B.id===f.callId),E=x?Dt(x.function.arguments):void 0;if(E){let B=G(E);if(c.benchmarkStateMaintenanceRequiredFiles.has(B)){let ie=mo(c.maintainedDocuments,B,x?.function.arguments??"");ie.ok?c.benchmarkStateMaintenanceWrittenFiles.add(B):(D.push({name:f.toolName,reason:"benchmark-state-invalid-content"}),m.push({role:"user",content:`Benchmark-state maintenance write for ${B} is incomplete: ${ie.reason}. Rewrite or patch the file using the document evidence already provided; do not reread context-pack source documents.`}))}}}if(f.ok&&!R&&(so.has(f.toolName)||f.toolName==="exec"&&f.details?.type==="exec_background"||f.toolName==="exec"&&js(ge.find(x=>x.id===f.callId)?.function.arguments??""))){let x=ge.find(B=>B.id===f.callId),E=typeof f.message?.content=="string"?f.message.content:"";if(x&&E){let B=Array.isArray(f.message.imageUrls)?f.message.imageUrls.filter(ye=>typeof ye=="string"):void 0,ie=Array.isArray(f.message.toolReferences)?f.message.toolReferences.filter(ye=>typeof ye=="string"):void 0;c.identicalSuccessfulToolResults.set(`${x.function.name}::${x.function.arguments}`,{content:E,imageUrls:B,toolReferences:ie})}}if(f.toolName==="agent"){let x=Oe(f.details,"agentId"),E=Oe(f.details,"status"),B=Nt(f.details,"background");f.ok&&x&&B===!0&&E==="running"&&ke(c).add(x)}if(f.toolName==="task"){let x=Zc(f.details);x&&(c.lastTaskList=x);let E=Oe(f.details,"taskId"),B=Nt(f.details,"running"),ie=Oe(f.details,"lifecycle"),ye=Oe(f.details,"action");if(E&&(ye==="cancel"||B===!1||ie&&ie!=="running"&&ie!=="pending"))ke(c).delete(E),c.backgroundAgentNoOutputPollCounts.delete(E),c.stalledBackgroundAgentTasks.delete(E);else if(E&&ye==="output"&&B===!0&&ke(c).has(E)){let Vo=typeof f.message?.content=="string"?f.message.content:"",Xo=Nt(f.details,"hasOutput");if(Xo!==void 0?Xo===!1:Kc(Vo)){let ln=(c.backgroundAgentNoOutputPollCounts.get(E)??0)+1;c.backgroundAgentNoOutputPollCounts.set(E,ln);let yt=qc(f.details,"elapsedSeconds")??Yc(Vo);(yt!==void 0&&yt>=Vc||yt===void 0&&ln>=Xc)&&c.stalledBackgroundAgentTasks.set(E,`no output after ${yt??"unknown"}s across ${ln} poll(s)`)}else c.backgroundAgentNoOutputPollCounts.delete(E),c.stalledBackgroundAgentTasks.delete(E)}}if(f.ok&&f.toolName==="read"){let x=ge.find(E=>E.id===f.callId);if(x){let E=ao(x.function.arguments);if(E){let B=G(E),ie=c.fileReadCounts.get(B)??0;c.fileReadCounts.set(B,ie+1);let ye=typeof f.message?.content=="string"?f.message.content:"";d=Ru(c,E,ye,c.turnCount,f.details)||d}}}yield Mr(r,f);for(let x of Er(r,f))yield x;for(let x of Ir({turnId:r,result:f,toolCalls:ne}))yield x;let oe=ne.find(x=>x.id===f.callId),he=typeof f.message?.content=="string"?f.message.content:"";if(oe){$r({state:c.artifactContract,inputMessages:i,toolName:f.toolName,rawArguments:oe.function.arguments,ok:f.ok,content:he}),Kt()&&(yield Xt());let x=Lc(f.toolName,oe.function.arguments);if(x){let E=(To.get(x)??0)+1;if(To.set(x,E),E===Nc){let B=x.startsWith("exec:")?"exec":"edit";c.recoveryTrace.set(`no_progress_observed:${B}`,(c.recoveryTrace.get(`no_progress_observed:${B}`)??0)+1)}}}!gt&&ci&&f.toolName==="stt"&&f.ok&&(gt=gc(i,f))}if(We&&(b=Ce(O,Y),We=!1),jt&&(b=Ce(O,Y),jt=!1),d){let f=bu(r,c.maintainedDocuments,c.fileReadCounts,c.turnCount);f&&(yield f);for(let R of ku(r,c.maintainedDocuments))yield R;let v=au(c.maintainedDocuments,c.turnCount),H=b.some(R=>io.has(R.function.name));if(v&&H){c.benchmarkStateMaintenanceRequiredFiles=new Set(ei(c.maintainedDocuments).map(G));for(let R of b)io.has(R.function.name)||Y.add(R.function.name);b=Ce(b,Y),U=!0,m.push({role:"user",content:v}),yield M("benchmark_state_maintenance_required","forcing write/edit/patch after long-horizon document index")}}let h=ke(c);if(h.size>0){let f=(a??u).find(v=>v.function.name==="task");if(f){let v=C(b),H=[...h].filter(R=>c.stalledBackgroundAgentTasks.has(R)).sort();if(H.length>0){b=[f],U=!0;let R=H.map(N=>`${N}: ${c.stalledBackgroundAgentTasks.get(N)}`).join("; ");m.push({role:"user",content:Hc(H,{reason:R})}),yield{type:"tool_selection_policy",turnId:r,policyId:"background_agent_no_output_watchdog_cancel_required",intent:"lifecycle_reconciliation",reason:"background-agent-no-output-watchdog",availableToolNames:C(a??u),enabledToolNamesBefore:v,enabledToolNamesAfter:C(b),suppressedToolNames:v.filter(N=>N!=="task"),nextAction:"cancel-stalled-background-task"},yield M("background_agent_no_output_watchdog_cancel_required",R);continue}b=[f],U=!0,m.push({role:"user",content:zc(h)}),yield{type:"tool_selection_policy",turnId:r,policyId:"background_agent_lifecycle_poll_required",intent:"lifecycle_reconciliation",reason:"background-agent-task-unresolved",availableToolNames:C(a??u),enabledToolNamesBefore:v,enabledToolNamesAfter:C(b),suppressedToolNames:v.filter(R=>R!=="task"),nextAction:"poll-existing-background-task-output"},yield M("background_agent_lifecycle_poll_required",[...h].sort().join(","));continue}}else b.length===1&&b[0]?.function.name==="task"&&(b=Ce(O,Y));if(ae(i)&&!c.artifactContract.browserVerified&&Ft(c.artifactContract).length>0&&b.some(f=>f.function.name==="exec")&&c.browserAcceptanceRecoveryCount<4){let f=Us(c.artifactContract);c={...c,browserAcceptanceRecoveryCount:c.browserAcceptanceRecoveryCount+1,messages:[...m,{role:"user",content:f}],transition:{reason:"next_turn"}},U=!0,yield M("browser_acceptance_required","forcing browser automation after localhost app URL was observed");continue}let T=uu(c.maintainedDocuments);if(T.length>0&&c.benchmarkStateIntegrityRecoveryCount<ru){let f=T.map(v=>`${Re(v.path)}: ${v.reason}`).join("; ");c={...c,benchmarkStateIntegrityRecoveryCount:c.benchmarkStateIntegrityRecoveryCount+1,messages:[...m,{role:"user",content:"Your maintained benchmark-state hash files no longer match the tool-derived ground truth: "+f+". The context-pack inputs are read-only and immutable \u2014 the source did NOT change. Restore the exact recorded contentHash/fileSizeBytes; do NOT flip any acceptance verdict on this phantom drift."}],transition:{reason:"next_turn"}},U=!0,yield M("benchmark_state_integrity_required","on-disk benchmark-state hash file contradicts tool-derived ground truth; forcing a correction before completion");continue}if(lu(c)){yield*W("Maintained benchmark-state files after indexing the context pack. Stopping this turn now because the required document-index.json, decision-state-table.json, and context-pack-evidence.json writes are complete; do not continue into extra writes, context-pack modifications, or repeated reads.");return}}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(gt){yield*W(gt);return}let Go=Rc(i,m);if(Go){yield*Ao(Go);return}let Wo=_c(i,m);if(Wo){yield*Ao(Wo);return}if(m.push(...Ss({toolFailureCounts:c.toolFailureCounts,snapshot:Ri})),ki){let l=Pe({inputMessages:i,messages:m,reason:`tool call budget exhausted (${re}) before completing all required files`});if(l){yield*W(l);return}}ee=Ct(ee,{replayMessages:m,completedToolCallIds:[...ee.completedToolCallIds,...V],lastStopReason:"tool_calls"}),e.toolChoice==="required"&&ne.length>0&&(Ht=!0);let xi=ne.length>0&&ne.every(l=>{let d=m.find(T=>T?.role==="tool"&&T?.tool_call_id===l.id);if(!d)return!0;let h=d.content;return typeof h=="string"&&h.startsWith("Error: ")}),_e=c.consecutiveFailedRounds;if(xi){if(_e+=1,_e>=ir){if(ho>=3&&c.repeatedToolFailureRecoveryCount<1){let T=eo({inputMessages:i,messages:m,finalText:c.finalText,thinkingBlocks:[],stopHookActive:c.stopHookActive,totalToolCallCount:F,distinctToolNames:L,log:o});if(T?.reason==="explicit_required_file_verification"||T?.reason==="explicit_extra_file_verification"){yield M("repeated_tool_failure_artifact_recovery","one recovery nudge before ending a complex explicit artifact turn after repeated tool failures"),c={...c,messages:T.messages,stopHookActive:T.stopHookActive,transition:T.transition,consecutiveFailedRounds:0,repeatedToolFailureRecoveryCount:c.repeatedToolFailureRecoveryCount+1};continue}}if(c.repeatedToolFailureRecoveryCount<1){let T=ts(m);if(T){yield M("repeated_tool_failure_self_correction","one help-guided self-correction round before ending on repeated tool failures"),c={...c,messages:[...m,T],consecutiveFailedRounds:0,repeatedToolFailureRecoveryCount:c.repeatedToolFailureRecoveryCount+1};continue}}let l=`repeated tool failures (${_e} rounds in a row)`,d=Pe({inputMessages:i,messages:m,reason:`${l} before all required files were produced`})??(c.finalText.trim()?c.finalText:Gn(m,_e)),h=qs(d,{availableToolNames:C(a??u),enabledToolNames:zt(),toolCallNames:[...L].sort(),blockedToolCalls:Pt(D)});o.info(`early exit: ${_e} consecutive failed rounds, returning ${c.finalText?"partial":"fallback"} response`),yield*W(h);return}}else _e=0;let ht=[...c.fileReadCycleBlockedPaths].filter(l=>!c.fileReadCycleNudgedPaths.has(l));if(ht.length>0){let l=ht.join(", "),d=[...new Set(ht.map(ro))].join(" ");o.info(`AP5: file read cycle detected on ${l}, injecting nudge`);let h={role:"user",content:`Read-cycle guard blocked repeated reads for: ${l}. ${d} Stop reading these source files this turn; summarize from maintained evidence and explain any remaining uncertainty.`};m.push(h);for(let T of ht)c.fileReadCycleNudgedPaths.add(T)}let De=se+1;if(w>0&&De>w){if(o.info(`max turns reached (${w}), completing`),k){let h=await k.invoke("stop",{sessionId:s,reason:"max_turns"});if(h.action==="abort"){let T=h.reason??"Stop hook requested continuation after max_turns",f={role:"assistant",content:c.finalText,...ce.length>0&&{thinkingBlocks:[...ce]}};c={...c,messages:[...m,f,{role:"user",content:T}],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}};continue}}let l=Pe({inputMessages:i,messages:m,reason:`tool loop max turns reached (${w}) before completing all required files`});if(l){yield*W(l);return}let d=st(m,`tool loop max turns reached (${w}) before completing the final status contract`);yield*W(d);return}if(Ut&&ke(c).size>0&&De>q&&q<100&&(q=Math.min(100,De+25),o.info(`background task lifecycle wait extended round budget to ${q}`)),Ut&&De>q){let l=Vn({currentToolBudget:re,currentRoundBudget:q,toolHardCap:100,roundHardCap:100,continuationCount:Ge,successfulSinceLastCheck:He-ot,fileReadCounts:c.fileReadCounts,windowTools:be,windowRounds:25});l&&(q=l.nextRoundBudget,re=l.nextToolBudget,Ge=l.continuationCount,ot=He,o.info(`round budget continuation #${l.continuationCount}: rounds\u2192${q}, tools\u2192${re} (progress detected)`))}if(De>q){o.info(`tool loop budget exhausted (${q} rounds), returning`);let l=to({totalToolCallCount:F,distinctToolNames:L,projectRoot:e.projectRoot});l&&(yield{type:"skill_instruction",turnId:r,instruction:l});let d=Pe({inputMessages:i,messages:m,reason:`tool budget exhausted (${q} rounds) before completing all required files`});if(d){yield*W(d);return}let h=st(m,`tool budget exhausted (${q} rounds) before completing the final status contract`);yield*W(h);return}c={messages:m,maxOutputTokensRecoveryCount:0,hasAttemptedReactiveCompact:!1,maxOutputTokensOverride:void 0,turnCount:De,transition:{reason:"next_turn"},guardState:j,reactiveCompactState:Q,toolLoopState:ee,consecutiveFailedRounds:_e,finalText:c.finalText,totalUsage:c.totalUsage,collapseStore:Yt,currentModel:c.currentModel,consecutive529Errors:0,consecutiveApiRetries:0,stopHookActive:c.stopHookActive,lastResponseId:c.lastResponseId,snipRemovedIds:c.snipRemovedIds,contentReplacementState:c.contentReplacementState,budgetContinuationCount:c.budgetContinuationCount,repeatedToolFailureRecoveryCount:c.repeatedToolFailureRecoveryCount,lastBudgetDeltaTokens:c.lastBudgetDeltaTokens,lastBudgetGlobalTokens:c.lastBudgetGlobalTokens,identicalCallCounts:ct,identicalSuccessfulToolResults:c.identicalSuccessfulToolResults,artifactContract:c.artifactContract,toolFailureCounts:c.toolFailureCounts,fileReadCounts:c.fileReadCounts,fileReadCycleBlockedPaths:c.fileReadCycleBlockedPaths,fileReadCycleNudgedPaths:c.fileReadCycleNudgedPaths,maintainedDocuments:c.maintainedDocuments,persistedBenchmarkStateRecovered:c.persistedBenchmarkStateRecovered,benchmarkStateMaintenanceRequiredFiles:c.benchmarkStateMaintenanceRequiredFiles,benchmarkStateMaintenanceWrittenFiles:c.benchmarkStateMaintenanceWrittenFiles,recoveryTrace:c.recoveryTrace,browserAcceptanceRecoveryCount:c.browserAcceptanceRecoveryCount,buildVerificationRecoveryCount:c.buildVerificationRecoveryCount,benchmarkStateIntegrityRecoveryCount:c.benchmarkStateIntegrityRecoveryCount,backgroundAgentTaskIds:ke(c),backgroundAgentNoOutputPollCounts:c.backgroundAgentNoOutputPollCounts,stalledBackgroundAgentTasks:c.stalledBackgroundAgentTasks,notOfferedToolRecoveryCount:c.notOfferedToolRecoveryCount,existingFileUpdateRecoveryCount:c.existingFileUpdateRecoveryCount,taskListReconciliationCount:c.taskListReconciliationCount,lastTaskList:c.lastTaskList}}}var Lu=["\u63A5\u5355\u91D1\u989D","\u5408\u540C\u91D1\u989D","\u62A5\u4EF7","\u9884\u7B97","\u91D1\u989D","price","amount","contract amount"];function ii(e){let t=Fu(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: ${si(o.l1Amount)}; L2 long-term says: ${si(o.l2Amount)}; action: ask the user which value is current before using it.`)}for(let o of e){let r=$u(o);n.push(`- [${r}] ${o.text}`)}return n.join(`
43
- `)}function Fu(e){let t=e.filter(r=>r.source==="l1-project-md").flatMap(r=>ri(r.text)),n=e.filter(r=>r.source==="l2-long-term").flatMap(r=>ri(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 Uu(o)}function ri(e){let t=[];for(let n of e.split(/\r?\n/)){let o=n.trim();if(o)for(let r of Lu){if(r==="\u91D1\u989D"&&/(接单金额|合同金额)/u.test(o))continue;let s=new RegExp(`${ju(r)}[^0-9.\u4E07kK,]{0,12}([0-9][0-9.,]*\\s*(?:\u4E07|k|K)?)`,"gi");for(let i of o.matchAll(s)){let a=Du(i[1]);a!==null&&t.push({entity:Bu(o,r),predicate:r,amount:a,text:o})}}}return t}function Bu(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 Du(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 $u(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 si(e){return Number.isInteger(e)?String(e):String(Number(e.toFixed(4)))}function Uu(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 ju(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var qu=8192;async function ai(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,y=null;if(p&&p.length>0){let g=0,k=[];for(let _ of p){let A=(_.text?.length??0)*2;if(g+A>qu)break;k.push(_),g+=A}k.length>0&&(y=`[Recalled memories \u2014 context priority: project-specific facts override general user preferences when they conflict]
44
- ${ii(k)}`)}return $(t,"memory.after_recall",{sessionId:r,turnId:s,blockCount:p?.length??0},o),y}catch{return null}}var li=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,availableTools:s,tools:i,systemPrompt:a,config:u}=t,p={sessionId:t.sessionId,turnId:o};yield{type:"start",turnId:o},$(this.hooks,"turn.submitted",{...p,prompt:r[r.length-1]?.content??void 0},this.log);let y=Rn(r),g=[];if(a&&g.push({role:"system",content:a}),g.push(...y),this.hooks){let w=y.filter(S=>S.role==="user").pop(),P=typeof w?.content=="string"?w.content.slice(0,500):void 0;if(P){let S=await ai({hooks:this.hooks,detectRecallCategories:O=>this.runtimePorts.detectRecallCategories(O),log:this.log,sessionId:t.sessionId,turnId:o,query:P});S&&g.splice(a?1:0,0,{role:"system",content:S})}}let k=u?.model??"",_=typeof u?.maxRounds=="number"&&Number.isFinite(u.maxRounds)?u.maxRounds:this.configuredMaxRounds,A=_===void 0?void 0:Math.min(_,100);try{let w=u?.reasoning;u?.reasoning?.effort==="auto"&&(w={...u?.reasoning,effort:"medium"});let P={turnId:o,sessionId:t.sessionId,messages:g,availableTools:s,tools:i,refreshTools:t.refreshTools,model:k,apiKey:u?.apiKey??this.apiKey,temperature:u?.temperature,maxRounds:A,contextWindowTokens:u?.contextWindowTokens,maxOutputTokens:u?.maxOutputTokens,modelMaxOutputTokens:u?.modelMaxOutputTokens,toolChoice:u?.toolChoice,parentDepth:u?.parentDepth,hooks:this.hooks,fallbackModel:u?.fallbackModel,maxTurns:u?.maxTurns,tokenBudget:u?.tokenBudget,maxConcurrentTools:u?.maxConcurrentTools,streamRequired:u?.streamRequired,reasoning:w,promptCacheKey:u?.promptCacheKey,promptCacheRetention:u?.promptCacheRetention,serviceTier:u?.serviceTier,openaiBuiltinTools:u?.openaiBuiltinTools,maxToolCalls:u?.maxToolCalls,parallelToolCalls:u?.parallelToolCalls,textVerbosity:u?.textVerbosity,projectRoot:this.projectRoot,runtimePorts:this.runtimePorts.toolLoop,signal:n},S;for await(let O of oi(P,this.transport,this.toolInvoker,this.log))S=O,yield O;S?.type==="end"?$(this.hooks,"turn.completed",{...p},this.log):S?.type==="error"&&$(this.hooks,"turn.failed",{...p,code:S.code,error:S.error},this.log)}catch(w){if(n?.aborted)$(this.hooks,"turn.failed",{...p,code:"ABORTED",error:"Turn aborted"},this.log),yield{type:"error",turnId:o,error:"Turn aborted",code:"ABORTED"};else{let P=w instanceof Error?w.message:String(w),S=typeof w?.status=="number"?w.status:void 0,O=$e(S,P);this.log.error(`turn ${o} error [${O}, retryable=${dn(O)}]: ${P}`),$(this.hooks,"turn.failed",{...p,code:O,error:P},this.log),yield{type:"error",turnId:o,error:P,code:O}}}}};export{li as Agent};
43
+ `),Oo=Po?[{role:"system",content:Po},...Xe.state.replayMessages]:Xe.state.replayMessages;te=Xe.state,Xe.recoveryActions.length>0&&o.debug(`tool loop recovery: ${Xe.recoveryActions.map(l=>l.detail??l.kind).join("; ")}`),o.debug(`turn ${ie}, messages: ${Oo.length}`),$(C,"turn.before_inference",{...v,model:u.currentModel},o);let en=!1,ct=[],No=new Map,Lo="stop",ne,I=null,ut=!1,Fo=!1,Ke=[],ce=[];try{let l=t.stream({model:u.currentModel,messages:Oo,...Ve.tools.length>0?{tools:Ve.tools,toolChoice:Ve.normalizedToolChoice??"auto"}:{},temperature:y,maxTokens:(Q??j.currentMaxOutputTokens)||void 0,streamRequired:e.streamRequired,previousResponseId:Ri,reasoning:e.reasoning,promptCacheKey:e.promptCacheKey,promptCacheRetention:e.promptCacheRetention,serviceTier:e.serviceTier,openaiBuiltinTools:e.openaiBuiltinTools,maxToolCalls:e.maxToolCalls,parallelToolCalls:e.parallelToolCalls,textVerbosity:e.textVerbosity},h,x);for await(let d of gu(l,e.llmStreamIdleTimeoutMs??nu))switch(d.type){case"delta":ct.push(d.text);break;case"tool_call_delta":en=!0,Ln(No,d);break;case"reasoning_delta":Ke.push(d.text);break;case"reasoning_block_complete":d.signature&&ce.push({thinking:Ke.join(""),signature:d.signature}),Ke.length=0;break;case"usage":ne={inputTokens:d.promptTokens,outputTokens:d.completionTokens,reasoningTokens:d.reasoningTokens,cacheRead:d.cacheReadTokens,cacheWrite:d.cacheCreationTokens};break;case"response_id":it||(u.lastResponseId=d.id);break;case"annotations":yield{type:"annotations",turnId:r,annotations:d.annotations};break;case"builtin_tool_status":yield{type:"heartbeat",turnId:r,message:`${d.toolType}: ${d.event}`};break;case"done":Fo=!0,Lo=d.finishReason;break}if(en||$(C,"turn.after_inference",{...v,model:u.currentModel},o),e.postSamplingHooks&&e.postSamplingHooks.length>0){let d=u.currentModel;for(let g of e.postSamplingHooks)try{g({messages:[...lt],model:d,sessionId:s})}catch{}}}catch(l){if(l instanceof $t){$(C,"stop.failure",{sessionId:s,reason:l.code,error:l.message},o),yield{type:"error",turnId:r,error:l.message,code:l.code,usage:u.totalUsage};return}let d=yield*ms(l,{state:u,guardState:j,fallbackModel:e.fallbackModel,signal:x,querySource:P,turnId:r,log:o,emitRecovery:M});if(d.kind==="return")return;if(d.kind==="continue"){u={...u,...d.patch};continue}I=d.streamError}if(!I&&!Fo){let l="LLM stream closed before a terminal event; the response was likely truncated upstream.";$(C,"stop.failure",{sessionId:s,reason:"RETRYABLE_TRANSIENT",error:l},o),yield{type:"error",turnId:r,error:l,code:"RETRYABLE_TRANSIENT",usage:u.totalUsage};return}if(I&&$(C,"turn.after_inference",{...v,model:u.currentModel,response:{error:I.message}},o),I){if(!it&&u.lastResponseId&&/previous_response_id not found/i.test(I.message)){let l=(u.consecutiveApiRetries??0)+1;if(l<=we){o.info("previous_response_id not found \u2014 disabling response-id chaining, retrying statelessly"),yield M("stateless_retry","previous_response_id not found; replaying full history"),it=!0,u={...u,lastResponseId:void 0,consecutiveApiRetries:l,transition:void 0};continue}}if(Kn(I))ut=!0,o.info(`withheld prompt_too_long error (status=${I.status})`);else if(Yn(I))ut=!0,o.info(`withheld media_size error (status=${I.status})`);else{let l=In({status:I.status??500,message:I.message},j,Le);if(l.action==="reactive_compact"&&$e(ee)&&(ee.attemptedThisTurn=!0,j.hasAttemptedReactiveCompact=!0,yield M("reactive_compact",`API ${I.status??500}: ${I.message}`)),l.action==="retry"){let g=(u.consecutiveApiRetries??0)+1;if(g>we){o.info(`API retry limit reached (${we}), aborting`);let T=De(I.status,I.message);yield{type:"error",turnId:r,error:I.message,code:T,usage:u.totalUsage};return}yield M("retry",l.reason),u={...u,consecutiveApiRetries:g,transition:void 0};continue}let d=De(I.status,I.message);$(C,"stop.failure",{sessionId:s,reason:d,error:I.message},o),yield{type:"error",turnId:r,error:I.message,code:d,usage:u.totalUsage};return}}ne&&(u.totalUsage.inputTokens+=ne.inputTokens,u.totalUsage.outputTokens+=ne.outputTokens,ne.reasoningTokens&&(u.totalUsage.reasoningTokens=(u.totalUsage.reasoningTokens??0)+ne.reasoningTokens),ne.cacheRead&&(u.totalUsage.cacheRead=(u.totalUsage.cacheRead??0)+ne.cacheRead),ne.cacheWrite&&(u.totalUsage.cacheWrite=(u.totalUsage.cacheWrite??0)+ne.cacheWrite)),ne?.inputTokens&&(j.promptTokens=ne.inputTokens);let me=ct.join(""),oe=[...No.values()].map((l,d)=>({id:l.id||`tc_${r}_${d}`,type:"function",function:{name:l.name,arguments:l.arguments}}));if(oe=hu(oe),oe.length===0&&!en){me&&(u.finalText=me);let l=je([...b,...a??c]),d=e.toolChoice==="none"?null:Is({text:me,enabledToolNames:k(l)});if(d&&Ro<2){if(Ro++,!new Set(b.map(N=>N.function.name)).has(d.toolName)){let N=(a??c).filter(re=>re.function.name===d.toolName);if(N.length>0){let re=k(b),he=new Map(b.map(_=>[_.function.name,_]));for(let _ of N)he.set(_.function.name,_);b=je([...he.values()]),yield{type:"tool_selection_policy",turnId:r,policyId:"available_tool_reenabled_after_pseudo_output",intent:"tool_recovery",reason:"pseudo-tool-output-named-available-tool",availableToolNames:k(a??c),enabledToolNamesBefore:re,enabledToolNamesAfter:k(b),suppressedToolNames:[],nextAction:"retry-with-native-tool-call"}}}u={...u,messages:[...m,{role:"assistant",content:me},{role:"user",content:`Your last response printed a pseudo tool invocation for ${d.toolName} instead of making a real tool call. Do not write XML tags, function-call prose, or placeholder tool syntax. Call the real ${d.toolName} tool now using the native tool-call channel, or explain why it cannot be used.`}],finalText:"",transition:{reason:"next_turn"}},U=!0,yield M("pseudo_tool_output_retry",d.toolName);continue}if(e.toolChoice==="required"&&!Wt&&b.length>0&&ko<2){ko++;let R=b.map(N=>N.function.name).filter(Boolean).slice(0,8).join(", ");u={...u,messages:[...m,{role:"user",content:`You must call one available tool before answering. Available tools for this request: ${R}. Do not answer from memory, prior context, or guesses.`}],finalText:"",transition:{reason:"next_turn"}};continue}if(ut&&I&&Kn(I)){if(u.transition?.reason!=="collapse_drain_retry"){let R=bn(lt,Qt);if(R.committed>0){o.info(`collapse drain: committed ${R.committed} stages`),yield M("collapse_drain",`${R.committed} stages committed`),u={...u,messages:R.messages,transition:{reason:"collapse_drain_retry",committed:R.committed}};continue}}if($e(ee)){ee.attemptedThisTurn=!0,j.hasAttemptedReactiveCompact=!0,o.info("withheld 413: reactive compact attempt"),yield M("reactive_compact","withheld prompt_too_long"),u={...u,hasAttemptedReactiveCompact:!0,transition:{reason:"reactive_compact_retry"}};continue}o.info("withheld 413: recovery exhausted, surfacing error"),$(C,"stop.failure",{sessionId:s,reason:"prompt_too_long",error:I.message},o),yield{type:"error",turnId:r,error:I.message,code:"PROMPT_TOO_LONG",usage:u.totalUsage};return}if(ut&&I&&Yn(I)){if($e(ee)){ee.attemptedThisTurn=!0,j.hasAttemptedReactiveCompact=!0,o.info("withheld media error: reactive compact strip-retry"),yield M("reactive_compact","media error strip-retry"),u={...u,hasAttemptedReactiveCompact:!0,transition:{reason:"reactive_compact_retry"}};continue}o.info("withheld media error: recovery exhausted"),$(C,"stop.failure",{sessionId:s,reason:"media_error",error:I.message},o),yield{type:"error",turnId:r,error:I.message,code:"IMAGE_ERROR",usage:u.totalUsage};return}if(us(Lo)){j.consecutiveTruncations+=1;let R=e.modelMaxOutputTokens??mr,N=Pn(j,Le,R);if(N.shouldEscalate&&Q===void 0){j.currentMaxOutputTokens=N.newMax,o.info(`max_output_tokens escalate: ${N.newMax} tokens`),yield M("output_escalation",`${N.newMax} tokens`),u={...u,maxOutputTokensOverride:hr,transition:{reason:"max_output_tokens_escalate"}};continue}if(z<gr){let re={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 #${z+1}`),yield M("max_output_tokens_recovery",`attempt ${z+1}`),u={...u,messages:[...lt,re],maxOutputTokensRecoveryCount:z+1,maxOutputTokensOverride:void 0,transition:{reason:"max_output_tokens_recovery",attempt:z+1}};continue}o.info("max_output_tokens recovery exhausted, completing with partial content")}else j.consecutiveTruncations=0;te=Rt(te,{replayMessages:m,lastStopReason:"completed"});let g=await Ms({hooks:C,sessionId:s,messages:m,finalText:u.finalText,thinkingBlocks:ce,log:o});if(g?.action==="end"){let R=Ci(g.content,m,"stop hook prevented continuation before completing the final status contract");yield*W(R);return}if(g?.action==="continue"){u={...u,messages:g.messages,stopHookActive:g.stopHookActive,transition:g.transition};continue}let T=Es({tokenBudget:e.tokenBudget,totalUsage:u.totalUsage,budgetContinuationCount:u.budgetContinuationCount,lastBudgetDeltaTokens:u.lastBudgetDeltaTokens,lastBudgetGlobalTokens:u.lastBudgetGlobalTokens,messages:m,finalText:u.finalText,thinkingBlocks:ce,getBudgetContinuationMessage:e.runtimePorts.getBudgetContinuationMessage,log:o});if(T){yield M("budget_continuation",T.recoveryDetail),u={...u,messages:T.messages,budgetContinuationCount:T.budgetContinuationCount,lastBudgetDeltaTokens:T.lastBudgetDeltaTokens,lastBudgetGlobalTokens:T.lastBudgetGlobalTokens,transition:T.transition};continue}if(u.finalText.trim()&&jc(u.lastTaskList)&&u.taskListReconciliationCount<1){let R=b.find(N=>N.function.name==="task")??(a??c).find(N=>N.function.name==="task");if(R){let N=Uc(u.lastTaskList),re=k(b),he=Te(O,Y);b=he.some(_=>_.function.name==="task")?he:je([...he,R]),u={...u,taskListReconciliationCount:u.taskListReconciliationCount+1,messages:[...m,{role:"assistant",content:u.finalText},{role:"user",content:N}],transition:{reason:"next_turn"}},U=!0,yield{type:"tool_selection_policy",turnId:r,policyId:"task_list_reconciliation_required",intent:"lifecycle_reconciliation",reason:"task-list-final-status-mismatch",availableToolNames:k(a??c),enabledToolNamesBefore:re,enabledToolNamesAfter:k(b),suppressedToolNames:[],nextAction:"reconcile-task-list-before-final"},yield M("task_list_reconciliation_required","nudging task-list status sync before the final response");continue}}if(de(i)&&!u.artifactContract.browserVerified&&Dt(u.artifactContract).length>0&&b.some(R=>R.function.name==="exec")&&u.browserAcceptanceRecoveryCount<4){let R=Xs(u.artifactContract);u={...u,browserAcceptanceRecoveryCount:u.browserAcceptanceRecoveryCount+1,messages:[...m,{role:"assistant",content:u.finalText},{role:"user",content:R}],transition:{reason:"next_turn"}},U=!0,yield M("browser_acceptance_required","forcing browser automation before app/frontend completion");continue}if((e.buildVerificationGate??!0)&&jr(i)&&!u.artifactContract.buildVerified&&u.artifactContract.buildFailureEvidence.length>0&&b.some(R=>R.function.name==="exec")&&u.buildVerificationRecoveryCount<3){let R=Fc(u.artifactContract);u={...u,buildVerificationRecoveryCount:u.buildVerificationRecoveryCount+1,messages:[...m,{role:"assistant",content:u.finalText},{role:"user",content:R}],transition:{reason:"next_turn"}},U=!0,yield M("build_verification_required","test/build still failing; forcing a fix+rerun before completion");continue}let p=to({inputMessages:i,messages:m,finalText:u.finalText,thinkingBlocks:ce,stopHookActive:u.stopHookActive,totalToolCallCount:F,distinctToolNames:L,log:o});if(p){if(u.stopHookActive&&u.finalText.trim()===""){let R=Pe({inputMessages:i,messages:p.messages,reason:"stop hook produced an empty response after tool use"});if(R){yield*W(R,{forcedStop:!0});return}}u={...u,messages:p.messages,stopHookActive:p.stopHookActive,transition:p.transition};continue}if(F===0&&b.length>0&&e.toolChoice!=="none"&&xo<1&&ss(me)){xo++,U=!0,yield M("intent_without_action","announced but did not act; forcing a tool call"),u={...u,messages:[...m,{role:"assistant",content:me},{role:"user",content:"You announced an action but did not take it. Carry it out NOW, in this response: call the appropriate tool to actually do what you just said you would do. Do not restate your intention or describe a plan \u2014 perform it."}],finalText:"",transition:{reason:"next_turn"}};continue}let w=no({totalToolCallCount:F,distinctToolNames:L,projectRoot:e.projectRoot});w&&(yield{type:"skill_instruction",turnId:r,instruction:w});let H=at(m,"the model ended with an empty response after tool use before completing the final status contract");for(let R of ct)yield{type:"delta",turnId:r,text:R};yield*W(H);return}let xi=ce.length===0&&Ke.length>0?Ke.join(""):void 0;if(me)for(let l of ct)yield{type:"delta",turnId:r,text:l};m.push(fn(oe,me||void 0,ce.length>0?ce:void 0,xi)),te=An(te,{replayMessages:m,pendingToolCallIds:oe.map(l=>l.id),completedToolCallIds:te.completedToolCallIds,lastStopReason:"tool_calls"});let dt=u.identicalCallCounts,Ye=[],ue=[],Ze=[],Bo=!1;for(let l of oe){if(Xc(l,u)){Ye.push(l);continue}let d=`${l.function.name}::${l.function.arguments}`,g=dt.get(d)??0;if(dt.set(d,g+1),g+1>ur){let T=io.has(l.function.name)||l.function.name==="exec"?u.identicalSuccessfulToolResults.get(d):void 0;if(T){Ze.push({call:l,result:T,repeatCount:g+1});continue}ue.push(l),Bo||(Bo=!0,o.info(`AP4 blocked: ${l.function.name} repeated ${g+1}x`))}else Ye.push(l)}let V=[],_i=new Set(b.map(l=>l.function.name)),Do=new Set(ue.filter(l=>Au(l,_i)).map(l=>l.id));for(let l of Ze){let d=l.call,g=`Reused previous successful ${d.function.name} result for identical arguments (attempt ${l.repeatCount}); no additional tool execution was performed.
44
+
45
+ ${l.result.content}`,T=X(d.id,{ok:!0,payload:g,imageUrls:l.result.imageUrls,toolReferences:l.result.toolReferences});m.push(T),V.push(d.id),L.add(d.function.name),F++,yield{type:"tool_result",turnId:r,callId:d.id,name:d.function.name,ok:!0,outputPreview:g.slice(0,2e3),durationMs:0,details:{type:d.function.name,reusedIdenticalCall:!0,repeatCount:l.repeatCount}}}if(Ze.some(l=>l.call.function.name==="exec"&&Ks(l.call.function.arguments))){let l=k(b);m.push({role:"user",content:$c(u.artifactContract)}),yield{type:"tool_selection_policy",turnId:r,policyId:"browser_verification_after_preparation_required",intent:"verification",reason:"repeated-browser-preparation-command",availableToolNames:k(a??c),enabledToolNamesBefore:l,enabledToolNamesAfter:l,suppressedToolNames:[],nextAction:"run-browser-verification-script-not-playwright-install"},yield M("browser_verification_after_preparation_required","reused successful browser preparation command")}for(let l of ue){D.push({name:l.function.name,reason:"identical-repeat-policy"});let d=dt.get(`${l.function.name}::${l.function.arguments}`),g=wt(m,l.function.name),T=Ic(g),p=Do.has(l.id)?wu(d,l):T?`This exact tool call has been attempted ${d} times. Last error: ${T}. 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.`,w=X(l.id,{ok:!1,error:p});m.push(w),V.push(l.id),L.add(l.function.name),F++,yield{type:"tool_result",turnId:r,callId:l.id,name:l.function.name,ok:!1,error:p}}if(ue.length>0&&Ye.length===0&&Ze.length===0&&ue.every(l=>Do.has(l.id))&&u.existingFileUpdateRecoveryCount<2){let l=k(b);b=Hs(O,Y);let d=k(b);We=!0,U=!0;let g=[...new Set(ue.map(T=>Ut(T.function.arguments)).filter(T=>!!T))];m.push({role:"user",content:`Existing-file maintenance recovery: the same write call was repeatedly attempted for an existing file. Do not use write for these existing path(s): ${g.join(", ")||"(unknown)"}. Do not delete, remove, or recreate an existing file to make write succeed; that is artifact path drift, not maintenance. Use read only if you need the current contents, then use edit or patch for the smallest valid change. After the edit/patch succeeds, continue build/browser verification normally.`}),yield{type:"tool_selection_policy",turnId:r,policyId:"existing_file_update_recovery",intent:"tool_recovery",reason:"repeated-existing-file-write",availableToolNames:k(a??c),enabledToolNamesBefore:l,enabledToolNamesAfter:d,suppressedToolNames:ro(l,d),nextAction:"use-read-edit-or-patch-for-existing-file-update"},yield M("existing_file_update_recovery",g.join(",")||"unknown"),u={...u,messages:m,existingFileUpdateRecoveryCount:u.existingFileUpdateRecoveryCount+1,transition:{reason:"next_turn"}};continue}if(ue.length>0){let l=wt(m,ue[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."};m.push(d)}let vi=yo>=3&&u.repeatedToolFailureRecoveryCount<1;if(ue.length>0&&Ye.length===0&&Ze.length===0&&!vi){let l=Ys(Wn(m,1),{availableToolNames:k(a??c),enabledToolNames:Gt(),toolCallNames:[...L].sort(),blockedToolCalls:Nt(D)});yield*W(l);return}let $o=[],tn=[];for(let l of Ye){let d=Wr({toolName:l.function.name,rawArguments:l.function.arguments});d?tn.push({call:l,...d}):$o.push(l)}for(let l of tn){let d=l.call;D.push({name:d.function.name,reason:"read-only-context-pack"}),m.push(X(d.id,{ok:!1,error:l.error})),V.push(d.id),L.add(d.function.name),F++,yield{type:"tool_result",turnId:r,callId:d.id,name:d.function.name,ok:!1,error:l.error},o.warn(`read-only context-pack blocked: ${d.function.name} ${l.path}`)}tn.length>0&&m.push({role:"user",content:"A write was blocked because context-pack is read-only evidence. Continue by writing compact indexes, checkpoints, and maintenance updates under benchmark-state; do not retry writes into context-pack."});let Ai=new Set(b.map(l=>l.function.name)),Uo=[],ft=[];for(let l of $o){let d=ci(l.function.name,l.function.arguments,Ai);d?ft.push({call:l,...d}):Uo.push(l)}for(let l of ft){let d=l.call;D.push({name:d.function.name,reason:"existing-file-update-tool-required"}),m.push(X(d.id,{ok:!1,error:l.error})),V.push(d.id),L.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(`existing file update blocked: ${d.function.name} ${l.path}`)}if(ft.length>0){let l=k(b);b=Hs(O,Y);let d=k(b);We=!0,U=!0;let g=[...new Set(ft.map(T=>T.path))];m.push({role:"user",content:`Existing-file maintenance recovery: a write was blocked because the target file already exists and edit/patch are enabled. Do not use write for these existing path(s): ${g.join(", ")||"(unknown)"}. Do not delete, remove, or recreate an existing file to make write succeed; that is artifact path drift, not maintenance. Use read only if you need the current contents, then use edit or patch for the smallest valid change. After the edit/patch succeeds, continue build/browser verification normally.`}),yield{type:"tool_selection_policy",turnId:r,policyId:"existing_file_update_recovery",intent:"tool_recovery",reason:"existing-file-write-blocked",availableToolNames:k(a??c),enabledToolNamesBefore:l,enabledToolNamesAfter:d,suppressedToolNames:ro(l,d),nextAction:"use-read-edit-or-patch-for-existing-file-update"},yield M("existing_file_update_recovery",g.join(",")||"unknown"),u={...u,messages:m,existingFileUpdateRecoveryCount:u.existingFileUpdateRecoveryCount+1,transition:{reason:"next_turn"}};continue}let jo=[],nn=[];for(let l of Uo){let d=Gr({state:u.artifactContract,inputMessages:i,toolName:l.function.name,rawArguments:l.function.arguments});d?nn.push({call:l,...d}):jo.push(l)}for(let l of nn){let d=l.call;D.push({name:d.function.name,reason:"artifact-root-contract"}),$n(u.artifactContract,{path:l.path,artifactRoot:l.artifactRoot,toolName:d.function.name}),m.push(X(d.id,{ok:!1,error:l.error})),V.push(d.id),L.add(d.function.name),F++,yield{type:"tool_result",turnId:r,callId:d.id,name:d.function.name,ok:!1,error:l.error},Jt()&&(yield Zt()),o.warn(`artifact root contract blocked: ${d.function.name}`)}nn.length>0&&m.push({role:"user",content:"A write was blocked by the artifactRoot contract. Continue inside the declared artifactRoot, or stop with an honest final status that lists the root drift as Not done."});let qo=[],on=[];for(let l of jo){let d=ws({inputMessages:i,messages:m,toolCall:l});d?on.push({call:l,error:d}):qo.push(l)}for(let l of on){let d=l.call;D.push({name:d.function.name,reason:"premature-completion-artifact"}),m.push(X(d.id,{ok:!1,error:l.error})),V.push(d.id),L.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}`)}on.length>0&&m.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 wi=new Set(b.map(l=>l.function.name)),zo=[],pt=[];for(let l of qo)wi.has(l.function.name)?zo.push(l):pt.push(l);for(let l of pt){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.`;D.push({name:l.function.name,reason:"not-offered"}),m.push(X(l.id,{ok:!1,error:d})),V.push(l.id),L.add(l.function.name),o.warn(`unoffered tool call suppressed: ${l.function.name}`)}if(pt.length>0&&u.notOfferedToolRecoveryCount<1){let l=[...new Set(pt.map(w=>w.function.name))].sort(),d=We&&l.includes("write"),g=l.filter(w=>Y.has(w)),p=(a??c).filter(w=>l.includes(w.function.name));if(g.length>0)u.notOfferedToolRecoveryCount+=1,U=!0,m.push({role:"user",content:`You retried ${g.map(w=>`\`${w}\``).join(", ")} after it was disabled by this turn's tool-selection policy. Do not retry policy-suppressed tools in this turn. Continue using only the currently enabled tools, or stop with a clear blocker.`}),yield{type:"tool_selection_policy",turnId:r,policyId:"policy_suppressed_tool_retry_blocked",intent:"tool_recovery",reason:"requested-tool-disabled-by-turn-policy",availableToolNames:k(a??c),enabledToolNamesBefore:k(b),enabledToolNamesAfter:k(b),suppressedToolNames:g,nextAction:"continue-with-currently-enabled-tools-or-report-blocker"},yield M("policy_suppressed_tool_retry_blocked",g.join(","));else if(!d&&p.length>0){let w=k(b),H=new Map(b.map(R=>[R.function.name,R]));for(let R of p)H.set(R.function.name,R);b=je([...H.values()]),u.notOfferedToolRecoveryCount+=1,U=!0,yield{type:"tool_selection_policy",turnId:r,policyId:"available_tool_reenabled_after_not_offered_call",intent:"tool_recovery",reason:"requested-tool-available-but-disabled",availableToolNames:k(a??c),enabledToolNamesBefore:w,enabledToolNamesAfter:k(b),suppressedToolNames:[],nextAction:"retry-with-reenabled-requested-tool"},m.push({role:"user",content:`You called ${l.map(R=>`\`${R}\``).join(", ")} but it was not enabled for that round even though it is available. The requested available tool has now been re-enabled. Use the re-enabled tool once with valid arguments; do not repeat a disabled-tool call.`}),yield M("available_tool_reenabled_after_not_offered_call",l.join(","))}}let Ho=[],rn=[];for(let l of zo){let d=b.find(T=>T.function.name===l.function.name),g=zc(d,l.function.arguments);g?rn.push({call:l,error:g}):Ho.push(l)}for(let l of rn){let d=l.call;D.push({name:d.function.name,reason:"invalid-arguments"}),m.push(X(d.id,{ok:!1,error:l.error})),V.push(d.id),L.add(d.function.name),F++,yield{type:"tool_result",turnId:r,callId:d.id,name:d.function.name,ok:!1,error:l.error,details:{type:d.function.name,error:"invalid_arguments"}},o.info(`invalid tool arguments blocked: ${d.function.name}`)}rn.length>0&&m.push({role:"user",content:"Some tool calls were blocked before execution because they did not match the tool schema. Do not retry the same tool with substituted fields. Use the required field names exactly, switch to the correct tool, or stop and report the invalid tool input."});let mt=[],sn=[];for(let l of Ho){if(l.function.name!=="exec"){mt.push(l);continue}let d=Gs(l.function.arguments);if(!d){mt.push(l);continue}let g=$s(d);Us(g)&&zs(O)?sn.push({call:l,error:qc(g)}):mt.push(l)}for(let l of sn){let d=l.call;D.push({name:d.function.name,reason:"dedicated-tool-required"});let g=k(b),T=b.filter(p=>["read","search"].includes(p.function.name));T.length>0&&(b=T,zt=!0,U=!0),m.push(X(d.id,{ok:!1,error:l.error})),V.push(d.id),L.add(d.function.name),F++,yield{type:"tool_result",turnId:r,callId:d.id,name:d.function.name,ok:!1,error:l.error,details:{type:d.function.name,error:"dedicated_tool_required",dedicatedTool:"read/search"}},o.info(`dedicated file tool preflight blocked: ${d.function.name}`),yield{type:"tool_selection_policy",turnId:r,policyId:"dedicated_file_tool_required",intent:"fresh_evidence",reason:"exec-file-read-search-list-blocked",availableToolNames:k(a??c),enabledToolNamesBefore:g,enabledToolNamesAfter:k(b),suppressedToolNames:g.filter(p=>!["read","search"].includes(p)),nextAction:"use-read-search-for-file-inspection-then-resume-build-run-verify-tools"}}sn.length>0&&m.push({role:"user",content:"Exec was blocked because it attempted local file reading/searching/listing. Use read/search for the next local file inspection step. After that, resume exec only for non-inspection commands such as installs, builds, dev servers, and verification scripts."});let gt=[],an=[],Go=[],Wo=[];for(let l of mt){if(l.function.name!=="exec"){gt.push(l);continue}let d=l,g=Gs(d.function.arguments),T=g?Nc(g):null;T&&(d={...d,function:{...d.function,arguments:Vs(d.function.arguments,T)}},Wo.push({originalCommand:g??"",rewrittenCommand:T}),g=T);let p=g?Lc(g):null;if(p?.action==="block")an.push({call:d,error:p.error});else if(p?.action==="rewrite"){let w={...d,function:{...d.function,arguments:Vs(d.function.arguments,p.command)}};Go.push({call:w,originalCommand:g??"",rewrittenCommand:p.command}),gt.push(w)}else gt.push(d)}for(let l of Wo)yield{type:"tool_selection_policy",turnId:r,policyId:"exec_sleep_prefix_guard",intent:"verification",reason:"sleep-prefix-removed",availableToolNames:k(a??c),enabledToolNamesBefore:k(b),enabledToolNamesAfter:k(b),suppressedToolNames:[],nextAction:"execute-command-without-blocking-sleep-prefix"},o.info(`blocking sleep prefix removed before exec: ${l.originalCommand} -> ${l.rewrittenCommand}`);for(let l of Go){let d=k(b);yield{type:"tool_selection_policy",turnId:r,policyId:"reserved_frontend_port_guard",intent:"verification",reason:"vite-strict-port-normalized",availableToolNames:k(a??c),enabledToolNamesBefore:d,enabledToolNamesAfter:k(b),suppressedToolNames:[],nextAction:"execute-normalized-vite-dev-server-command-with-strict-port"},o.info(`vite strict port normalized before exec: ${l.originalCommand} -> ${l.rewrittenCommand}`)}for(let l of an){let d=l.call;D.push({name:d.function.name,reason:"reserved-frontend-port"});let g=k(b);m.push(X(d.id,{ok:!1,error:l.error})),V.push(d.id),L.add(d.function.name),F++,yield{type:"tool_result",turnId:r,callId:d.id,name:d.function.name,ok:!1,error:l.error,details:{type:d.function.name,error:"reserved_frontend_port",reservedPort:Bt}},o.info(`reserved frontend port preflight blocked: ${d.function.name}`),yield{type:"tool_selection_policy",turnId:r,policyId:"reserved_frontend_port_guard",intent:"verification",reason:"reserved-frontend-port",availableToolNames:k(a??c),enabledToolNamesBefore:g,enabledToolNamesAfter:k(b),suppressedToolNames:[],nextAction:"restart-generated-dev-server-on-explicit-non-5174-port-with-strict-port"}}an.length>0&&m.push({role:"user",content:"A dev server command was blocked because it could occupy or fallback onto port 5174, which is reserved for the Xiaozhi Claw frontend. Retry with an explicit generated-app port other than 5174 and use --strictPort for Vite so browser evidence cannot be polluted."});let ht=[],Fe=[];for(let l of gt){if(l.function.name!=="read"){ht.push(l);continue}let d=lo(l.function.arguments);if(!d){ht.push(l);continue}let g=G(d),T=si(g);(u.fileReadCounts.get(g)??0)>=T?Fe.push({call:l,filePath:g,maxReads:T}):ht.push(l)}for(let l of Fe){let d=l.call,g=`Read cycle policy blocked another read of "${l.filePath}" after ${l.maxReads} successful reads in this turn. Stop rereading the same large document. ${so(l.filePath)}`;D.push({name:d.function.name,reason:"read-cycle-policy"}),u.fileReadCycleBlockedPaths.add(l.filePath),m.push(X(d.id,{ok:!1,error:g})),V.push(d.id),L.add(d.function.name),F++,yield{type:"tool_result",turnId:r,callId:d.id,name:d.function.name,ok:!1,error:g},o.info(`read cycle blocked: ${l.filePath}`)}if(Fe.length>0){let l=[...new Set(Fe.map(T=>`${T.filePath} (max ${T.maxReads})`))].join(", "),d=[...new Set(Fe.map(T=>so(T.filePath)))].join(" ");if(m.push({role:"user",content:`Further reads were blocked because these large/context documents already reached their per-turn read limit: ${l}. Do not retry the read with a different path spelling. ${d} Continue from maintained requirements/defects/decisions/acceptance evidence and report any truly missing section explicitly.`}),b.some(T=>Zs(T.function.name))&&(u.persistedBenchmarkStateRecovered||Fe.some(T=>po(T.filePath)))){let T=k(b),p=T.filter(w=>lu.has(w)).sort();yield{type:"tool_selection_policy",turnId:r,policyId:"long_horizon_benchmark_state_maintenance",intent:"benchmark_state_maintenance",reason:"read-cycle-guard-retains-evidence-tools",availableToolNames:k(a??c),enabledToolNamesBefore:T,enabledToolNamesAfter:k(b),suppressedToolNames:[],nextAction:"maintenance-or-final-answer"},m.push({role:"user",content:`Do not reread the blocked large/context document paths again. Evidence tools still enabled: ${p.join(", ")||"none"}. Use read/search only for targeted verification of generated artifacts, file names, and missing sections; use edit/patch/write only if benchmark-state maintenance needs an update; otherwise stop tool use and answer from the maintained benchmark-state evidence. Classify any unused edit/patch/write tools as not needed, not missing.`}),yield M("benchmark_state_maintenance_tool_bias","retaining targeted evidence tools after long-horizon read-cycle guard")}if(mu(D,u.fileReadCycleBlockedPaths,u.persistedBenchmarkStateRecovered,u.maintainedDocuments)){yield*W("Stopped repeated long-horizon context-pack rereads after the read-cycle guard blocked every maintained source document. Continue from benchmark-state/document-index.json, decision-state-table.json, and context-pack-evidence.json; do not reread or rewrite context-pack source documents.",{forcedStop:!0});return}}let ln=Os(ht,u.toolFailureCounts),cn=ln.allowed;if(qt&&cn.length>Math.max(0,se-F)){let l=Xn({currentToolBudget:se,currentRoundBudget:q,toolHardCap:100,roundHardCap:100,continuationCount:Ge,successfulSinceLastCheck:He-st,fileReadCounts:u.fileReadCounts,windowTools:be,windowRounds:25});l&&(se=l.nextToolBudget,q=l.nextRoundBudget,Ge=l.continuationCount,st=He,o.info(`tool budget continuation #${l.continuationCount}: tools\u2192${se}, rounds\u2192${q} (progress detected)`))}let Vo=Math.max(0,se-F),ge=Vo>0?cn.slice(0,Vo):[],un=cn.slice(ge.length),Si=un.length>0;if(ln.blocked.length>0){for(let l of ln.blocked){let d=l.call;D.push({name:d.function.name,reason:"variant-failure-policy"});let g=X(d.id,{ok:!1,error:l.error});m.push(g),V.push(d.id),L.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`)}m.push(Ns())}if(un.length>0){let l=`Tool call budget exhausted (${se}) for this turn. Stop requesting more tools and report what remains incomplete.`;for(let d of un){D.push({name:d.function.name,reason:"tool-call-budget"});let g=X(d.id,{ok:!1,error:l});m.push(g),V.push(d.id),L.add(d.function.name),F++,yield{type:"tool_result",turnId:r,callId:d.id,name:d.function.name,ok:!1,error:l}}m.push({role:"user",content:`${l} You reached this turn's tool budget after ${Ge} 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 ge){let d=l.function.arguments,g=b.find(T=>T.function.name===l.function.name);if(g?.backfillObservableInput)try{let T=JSON.parse(l.function.arguments),p={...T};g.backfillObservableInput(p),Object.keys(p).some(H=>!(H in T))&&(d=JSON.stringify(p))}catch{}yield{type:"tool_call",turnId:r,callId:l.id,name:l.function.name,arguments:d,inputSummary:Vn(d)},bo.add(l.function.name),To++}let Mi=new Map(u.toolFailureCounts),yt=null;try{let l=e.runtimePorts.createStreamingToolExecutor({toolInvoker:n,hooks:C,sessionId:s,turnId:r,log:o,signal:x,maxConcurrentTools:e?.maxConcurrentTools,maxExecutionMs:lr});for(let p of ge)l.addTool(p);let d=!1;for await(let p of l.getRemainingResults()){let w=Mc(p);if(w){if(D.push({name:p.toolName,reason:w}),p.toolName==="exec"&&w==="dedicated-tool-required"&&zs(O)){let _=k(b);m.push({role:"user",content:"Exec was blocked because it attempted local file reading/searching/listing. Use read/search for local file inspection. Exec remains available only for non-inspection commands such as installs, builds, dev servers, and verification scripts."}),yield{type:"tool_selection_policy",turnId:r,policyId:"dedicated_file_tool_required",intent:"fresh_evidence",reason:"exec-file-read-search-list-blocked",availableToolNames:k(a??c),enabledToolNamesBefore:_,enabledToolNamesAfter:k(b),suppressedToolNames:[],nextAction:"use-read-search-for-file-inspection-or-exec-for-build-run-verify"}}if(p.toolName==="exec"&&w==="confirmation-timeout"){let _=k(b);Y.add("exec");let E=Te(O,Y);E.length>0&&(b=je(E),U=!0),m.push({role:"user",content:"Exec confirmation timed out, so exec is disabled for the rest of this turn. Do not retry exec. Use read/search for inspection, edit/patch/write for file updates, ask_user only for missing user input, or stop with a clear blocker if no non-exec tool can complete the request."}),yield{type:"tool_selection_policy",turnId:r,policyId:"exec_confirmation_timeout_recovery",intent:"tool_recovery",reason:"exec-confirmation-timeout",availableToolNames:k(a??c),enabledToolNamesBefore:_,enabledToolNamesAfter:k(b),suppressedToolNames:ro(_,k(b)),nextAction:"continue-with-non-exec-tools-or-report-confirmation-blocker"}}if(p.toolName==="exec"&&w==="global-process-kill-blocked"){let _=k(b);m.push({role:"user",content:"Exec was blocked because it attempted to terminate every node process. Do not retry taskkill/killall/pkill/Stop-Process by process name. If a generated app server conflicts with another process, start the generated app on a new explicit non-5174 port with strict port behavior, or stop only an owned background task by its task id. Continue by verifying the app on the reachable generated-app URL."}),yield{type:"tool_selection_policy",turnId:r,policyId:"global_process_kill_recovery",intent:"verification",reason:"global-node-process-kill-blocked",availableToolNames:k(a??c),enabledToolNamesBefore:_,enabledToolNamesAfter:k(b),suppressedToolNames:[],nextAction:"use-owned-task-cancel-or-new-explicit-port"}}}p.blocked&&(yield{type:"tool_blocked",turnId:r,callId:p.callId,name:p.toolName,reason:p.blockReason??"blocked"}),m.push(p.message),V.push(p.callId),L.add(p.toolName);let H=Kc(p,u);H||F++;let R=p.ok&&Hn(p);if(p.ok&&!R&&!H&&(He+=1),H||Ls({toolFailureCounts:u.toolFailureCounts,toolName:p.toolName,toolArguments:ge.find(_=>_.id===p.callId)?.function.arguments,ok:p.ok,softEmpty:R}),p.ok&&tu.has(p.toolName)&&Bu(u),p.ok&&Zs(p.toolName)){let _=ge.find(B=>B.id===p.callId),E=_?Ut(_.function.arguments):void 0;if(E){let B=G(E);if(u.benchmarkStateMaintenanceRequiredFiles.has(B)){let ae=go(u.maintainedDocuments,B,_?.function.arguments??"");ae.ok?u.benchmarkStateMaintenanceWrittenFiles.add(B):(D.push({name:p.toolName,reason:"benchmark-state-invalid-content"}),m.push({role:"user",content:`Benchmark-state maintenance write for ${B} is incomplete: ${ae.reason}. Rewrite or patch the file using the document evidence already provided; do not reread context-pack source documents.`}))}}}if(p.ok&&!R&&(io.has(p.toolName)||p.toolName==="exec"&&p.details?.type==="exec_background"||p.toolName==="exec"&&Ks(ge.find(_=>_.id===p.callId)?.function.arguments??""))){let _=ge.find(B=>B.id===p.callId),E=typeof p.message?.content=="string"?p.message.content:"";if(_&&E){let B=Array.isArray(p.message.imageUrls)?p.message.imageUrls.filter(ye=>typeof ye=="string"):void 0,ae=Array.isArray(p.message.toolReferences)?p.message.toolReferences.filter(ye=>typeof ye=="string"):void 0;u.identicalSuccessfulToolResults.set(`${_.function.name}::${_.function.arguments}`,{content:E,imageUrls:B,toolReferences:ae})}}if(p.toolName==="agent"){let _=Oe(p.details,"agentId"),E=Oe(p.details,"status"),B=Ft(p.details,"background");p.ok&&_&&B===!0&&E==="running"&&Ce(u).add(_)}if(p.toolName==="task"){let _=eu(p.details);_&&(u.lastTaskList=_);let E=Oe(p.details,"taskId"),B=Ft(p.details,"running"),ae=Oe(p.details,"lifecycle"),ye=Oe(p.details,"action");if(E&&(ye==="cancel"||B===!1||ae&&ae!=="running"&&ae!=="pending"))Ce(u).delete(E),u.backgroundAgentNoOutputPollCounts.delete(E),u.stalledBackgroundAgentTasks.delete(E);else if(E&&ye==="output"&&B===!0&&Ce(u).has(E)){let Yo=typeof p.message?.content=="string"?p.message.content:"",Zo=Ft(p.details,"hasOutput");if(Zo!==void 0?Zo===!1:Jc(Yo)){let dn=(u.backgroundAgentNoOutputPollCounts.get(E)??0)+1;u.backgroundAgentNoOutputPollCounts.set(E,dn);let Tt=Gc(p.details,"elapsedSeconds")??Qc(Yo);(Tt!==void 0&&Tt>=Yc||Tt===void 0&&dn>=Zc)&&u.stalledBackgroundAgentTasks.set(E,`no output after ${Tt??"unknown"}s across ${dn} poll(s)`)}else u.backgroundAgentNoOutputPollCounts.delete(E),u.stalledBackgroundAgentTasks.delete(E)}}if(p.ok&&p.toolName==="read"){let _=ge.find(E=>E.id===p.callId);if(_){let E=lo(_.function.arguments);if(E){let B=G(E),ae=u.fileReadCounts.get(B)??0;u.fileReadCounts.set(B,ae+1);let ye=typeof p.message?.content=="string"?p.message.content:"";d=vu(u,E,ye,u.turnCount,p.details)||d}}}yield Pr(r,p);for(let _ of Or(r,p))yield _;for(let _ of Nr({turnId:r,result:p,toolCalls:oe}))yield _;let re=oe.find(_=>_.id===p.callId),he=typeof p.message?.content=="string"?p.message.content:"";if(re){Vr({state:u.artifactContract,inputMessages:i,toolName:p.toolName,rawArguments:re.function.arguments,ok:p.ok,content:he}),Jt()&&(yield Zt());let _=Dc(p.toolName,re.function.arguments);if(_){let E=(Co.get(_)??0)+1;if(Co.set(_,E),E===Bc){let B=_.startsWith("exec:")?"exec":"edit";u.recoveryTrace.set(`no_progress_observed:${B}`,(u.recoveryTrace.get(`no_progress_observed:${B}`)??0)+1)}}}!yt&&yi&&p.toolName==="stt"&&p.ok&&(yt=bc(i,p))}if(We&&(b=Te(O,Y),We=!1),zt&&(b=Te(O,Y),zt=!1),d){let p=ku(r,u.maintainedDocuments,u.fileReadCounts,u.turnCount);p&&(yield p);for(let R of _u(r,u.maintainedDocuments))yield R;let w=uu(u.maintainedDocuments,u.turnCount),H=b.some(R=>ao.has(R.function.name));if(w&&H){u.benchmarkStateMaintenanceRequiredFiles=new Set(li(u.maintainedDocuments).map(G));for(let R of b)ao.has(R.function.name)||Y.add(R.function.name);b=Te(b,Y),U=!0,m.push({role:"user",content:w}),yield M("benchmark_state_maintenance_required","forcing write/edit/patch after long-horizon document index")}}let g=Ce(u);if(g.size>0){let p=(a??c).find(w=>w.function.name==="task");if(p){let w=k(b),H=[...g].filter(R=>u.stalledBackgroundAgentTasks.has(R)).sort();if(H.length>0){b=[p],U=!0;let R=H.map(N=>`${N}: ${u.stalledBackgroundAgentTasks.get(N)}`).join("; ");m.push({role:"user",content:Vc(H,{reason:R})}),yield{type:"tool_selection_policy",turnId:r,policyId:"background_agent_no_output_watchdog_cancel_required",intent:"lifecycle_reconciliation",reason:"background-agent-no-output-watchdog",availableToolNames:k(a??c),enabledToolNamesBefore:w,enabledToolNamesAfter:k(b),suppressedToolNames:w.filter(N=>N!=="task"),nextAction:"cancel-stalled-background-task"},yield M("background_agent_no_output_watchdog_cancel_required",R);continue}b=[p],U=!0,m.push({role:"user",content:Wc(g)}),yield{type:"tool_selection_policy",turnId:r,policyId:"background_agent_lifecycle_poll_required",intent:"lifecycle_reconciliation",reason:"background-agent-task-unresolved",availableToolNames:k(a??c),enabledToolNamesBefore:w,enabledToolNamesAfter:k(b),suppressedToolNames:w.filter(R=>R!=="task"),nextAction:"poll-existing-background-task-output"},yield M("background_agent_lifecycle_poll_required",[...g].sort().join(","));continue}}else b.length===1&&b[0]?.function.name==="task"&&(b=Te(O,Y));if(de(i)&&!u.artifactContract.browserVerified&&Dt(u.artifactContract).length>0&&b.some(p=>p.function.name==="exec")&&u.browserAcceptanceRecoveryCount<4){let p=Xs(u.artifactContract);u={...u,browserAcceptanceRecoveryCount:u.browserAcceptanceRecoveryCount+1,messages:[...m,{role:"user",content:p}],transition:{reason:"next_turn"}},U=!0,yield M("browser_acceptance_required","forcing browser automation after localhost app URL was observed");continue}let T=pu(u.maintainedDocuments);if(T.length>0&&u.benchmarkStateIntegrityRecoveryCount<au){let p=T.map(w=>`${ke(w.path)}: ${w.reason}`).join("; ");u={...u,benchmarkStateIntegrityRecoveryCount:u.benchmarkStateIntegrityRecoveryCount+1,messages:[...m,{role:"user",content:"Your maintained benchmark-state hash files no longer match the tool-derived ground truth: "+p+". The context-pack inputs are read-only and immutable \u2014 the source did NOT change. Restore the exact recorded contentHash/fileSizeBytes; do NOT flip any acceptance verdict on this phantom drift."}],transition:{reason:"next_turn"}},U=!0,yield M("benchmark_state_integrity_required","on-disk benchmark-state hash file contradicts tool-derived ground truth; forcing a correction before completion");continue}if(du(u)){yield*W("Maintained benchmark-state files after indexing the context pack. Stopping this turn now because the required document-index.json, decision-state-table.json, and context-pack-evidence.json writes are complete; do not continue into extra writes, context-pack modifications, or repeated reads.");return}}catch(l){let d=l instanceof Error?l.message:String(l);yield{type:"error",turnId:r,error:d,code:"TOOL_EXECUTION_ERROR",usage:u.totalUsage};return}if(yt){yield*W(yt);return}let Xo=vc(i,m);if(Xo){yield*Mo(Xo);return}let Ko=wc(i,m);if(Ko){yield*Mo(Ko);return}if(m.push(...Fs({toolFailureCounts:u.toolFailureCounts,snapshot:Mi})),Si){let l=Pe({inputMessages:i,messages:m,reason:`tool call budget exhausted (${se}) before completing all required files`});if(l){yield*W(l,{forcedStop:!0});return}}te=Rt(te,{replayMessages:m,completedToolCallIds:[...te.completedToolCallIds,...V],lastStopReason:"tool_calls"}),e.toolChoice==="required"&&oe.length>0&&(Wt=!0);let Ei=oe.length>0&&oe.every(l=>{let d=m.find(T=>T?.role==="tool"&&T?.tool_call_id===l.id);if(!d)return!0;let g=d.content;return typeof g=="string"&&g.startsWith("Error: ")}),xe=u.consecutiveFailedRounds;if(Ei){if(xe+=1,xe>=cr){if(yo>=3&&u.repeatedToolFailureRecoveryCount<1){let T=to({inputMessages:i,messages:m,finalText:u.finalText,thinkingBlocks:[],stopHookActive:u.stopHookActive,totalToolCallCount:F,distinctToolNames:L,log:o});if(T?.reason==="explicit_required_file_verification"||T?.reason==="explicit_extra_file_verification"){yield M("repeated_tool_failure_artifact_recovery","one recovery nudge before ending a complex explicit artifact turn after repeated tool failures"),u={...u,messages:T.messages,stopHookActive:T.stopHookActive,transition:T.transition,consecutiveFailedRounds:0,repeatedToolFailureRecoveryCount:u.repeatedToolFailureRecoveryCount+1};continue}}if(u.repeatedToolFailureRecoveryCount<1){let T=cs(m);if(T){yield M("repeated_tool_failure_self_correction","one help-guided self-correction round before ending on repeated tool failures"),u={...u,messages:[...m,T],consecutiveFailedRounds:0,repeatedToolFailureRecoveryCount:u.repeatedToolFailureRecoveryCount+1};continue}}let l=`repeated tool failures (${xe} rounds in a row)`,d=Pe({inputMessages:i,messages:m,reason:`${l} before all required files were produced`})??(u.finalText.trim()?u.finalText:Wn(m,xe)),g=Ys(d,{availableToolNames:k(a??c),enabledToolNames:Gt(),toolCallNames:[...L].sort(),blockedToolCalls:Nt(D)});o.info(`early exit: ${xe} consecutive failed rounds, returning ${u.finalText?"partial":"fallback"} response`),yield*W(g,{forcedStop:!0});return}}else xe=0;let bt=[...u.fileReadCycleBlockedPaths].filter(l=>!u.fileReadCycleNudgedPaths.has(l));if(bt.length>0){let l=bt.join(", "),d=[...new Set(bt.map(so))].join(" ");o.info(`AP5: file read cycle detected on ${l}, injecting nudge`);let g={role:"user",content:`Read-cycle guard blocked repeated reads for: ${l}. ${d} Stop reading these source files this turn; summarize from maintained evidence and explain any remaining uncertainty.`};m.push(g);for(let T of bt)u.fileReadCycleNudgedPaths.add(T)}let Be=ie+1;if(A>0&&Be>A){if(o.info(`max turns reached (${A}), completing`),C){let g=await C.invoke("stop",{sessionId:s,reason:"max_turns"});if(g.action==="abort"){let T=g.reason??"Stop hook requested continuation after max_turns",p={role:"assistant",content:u.finalText,...ce.length>0&&{thinkingBlocks:[...ce]}};u={...u,messages:[...m,p,{role:"user",content:T}],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}};continue}}let l=Pe({inputMessages:i,messages:m,reason:`tool loop max turns reached (${A}) before completing all required files`});if(l){yield*W(l,{forcedStop:!0});return}let d=at(m,`tool loop max turns reached (${A}) before completing the final status contract`);yield*W(d);return}if(qt&&Ce(u).size>0&&Be>q&&q<100&&(q=Math.min(100,Be+25),o.info(`background task lifecycle wait extended round budget to ${q}`)),qt&&Be>q){let l=Xn({currentToolBudget:se,currentRoundBudget:q,toolHardCap:100,roundHardCap:100,continuationCount:Ge,successfulSinceLastCheck:He-st,fileReadCounts:u.fileReadCounts,windowTools:be,windowRounds:25});l&&(q=l.nextRoundBudget,se=l.nextToolBudget,Ge=l.continuationCount,st=He,o.info(`round budget continuation #${l.continuationCount}: rounds\u2192${q}, tools\u2192${se} (progress detected)`))}if(Be>q){o.info(`tool loop budget exhausted (${q} rounds), returning`);let l=no({totalToolCallCount:F,distinctToolNames:L,projectRoot:e.projectRoot});l&&(yield{type:"skill_instruction",turnId:r,instruction:l});let d=Pe({inputMessages:i,messages:m,reason:`tool budget exhausted (${q} rounds) before completing all required files`});if(d){yield*W(d,{forcedStop:!0});return}let g=at(m,`tool budget exhausted (${q} rounds) before completing the final status contract`);yield*W(g);return}u={messages:m,maxOutputTokensRecoveryCount:0,hasAttemptedReactiveCompact:!1,maxOutputTokensOverride:void 0,turnCount:Be,transition:{reason:"next_turn"},guardState:j,reactiveCompactState:ee,toolLoopState:te,consecutiveFailedRounds:xe,finalText:u.finalText,totalUsage:u.totalUsage,collapseStore:Qt,currentModel:u.currentModel,consecutive529Errors:0,consecutiveApiRetries:0,stopHookActive:u.stopHookActive,lastResponseId:u.lastResponseId,snipRemovedIds:u.snipRemovedIds,contentReplacementState:u.contentReplacementState,budgetContinuationCount:u.budgetContinuationCount,repeatedToolFailureRecoveryCount:u.repeatedToolFailureRecoveryCount,lastBudgetDeltaTokens:u.lastBudgetDeltaTokens,lastBudgetGlobalTokens:u.lastBudgetGlobalTokens,identicalCallCounts:dt,identicalSuccessfulToolResults:u.identicalSuccessfulToolResults,artifactContract:u.artifactContract,toolFailureCounts:u.toolFailureCounts,fileReadCounts:u.fileReadCounts,fileReadCycleBlockedPaths:u.fileReadCycleBlockedPaths,fileReadCycleNudgedPaths:u.fileReadCycleNudgedPaths,maintainedDocuments:u.maintainedDocuments,persistedBenchmarkStateRecovered:u.persistedBenchmarkStateRecovered,benchmarkStateMaintenanceRequiredFiles:u.benchmarkStateMaintenanceRequiredFiles,benchmarkStateMaintenanceWrittenFiles:u.benchmarkStateMaintenanceWrittenFiles,recoveryTrace:u.recoveryTrace,browserAcceptanceRecoveryCount:u.browserAcceptanceRecoveryCount,buildVerificationRecoveryCount:u.buildVerificationRecoveryCount,benchmarkStateIntegrityRecoveryCount:u.benchmarkStateIntegrityRecoveryCount,backgroundAgentTaskIds:Ce(u),backgroundAgentNoOutputPollCounts:u.backgroundAgentNoOutputPollCounts,stalledBackgroundAgentTasks:u.stalledBackgroundAgentTasks,notOfferedToolRecoveryCount:u.notOfferedToolRecoveryCount,existingFileUpdateRecoveryCount:u.existingFileUpdateRecoveryCount,taskListReconciliationCount:u.taskListReconciliationCount,lastTaskList:u.lastTaskList}}}var Du=["\u63A5\u5355\u91D1\u989D","\u5408\u540C\u91D1\u989D","\u62A5\u4EF7","\u9884\u7B97","\u91D1\u989D","price","amount","contract amount"];function mi(e){let t=$u(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: ${pi(o.l1Amount)}; L2 long-term says: ${pi(o.l2Amount)}; action: ask the user which value is current before using it.`)}for(let o of e){let r=qu(o);n.push(`- [${r}] ${o.text}`)}return n.join(`
46
+ `)}function $u(e){let t=e.filter(r=>r.source==="l1-project-md").flatMap(r=>fi(r.text)),n=e.filter(r=>r.source==="l2-long-term").flatMap(r=>fi(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 zu(o)}function fi(e){let t=[];for(let n of e.split(/\r?\n/)){let o=n.trim();if(o)for(let r of Du){if(r==="\u91D1\u989D"&&/(接单金额|合同金额)/u.test(o))continue;let s=new RegExp(`${Hu(r)}[^0-9.\u4E07kK,]{0,12}([0-9][0-9.,]*\\s*(?:\u4E07|k|K)?)`,"gi");for(let i of o.matchAll(s)){let a=ju(i[1]);a!==null&&t.push({entity:Uu(o,r),predicate:r,amount:a,text:o})}}}return t}function Uu(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 ju(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 qu(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 pi(e){return Number.isInteger(e)?String(e):String(Number(e.toFixed(4)))}function zu(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 Hu(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var Gu=8192;async function gi(e){let{hooks:t,detectRecallCategories:n,log:o,sessionId:r,turnId:s,query:i}=e;try{let a=n(i),f=(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,h=null;if(f&&f.length>0){let y=0,C=[];for(let x of f){let v=(x.text?.length??0)*2;if(y+v>Gu)break;C.push(x),y+=v}C.length>0&&(h=`[Recalled memories \u2014 context priority: project-specific facts override general user preferences when they conflict]
47
+ ${mi(C)}`)}return $(t,"memory.after_recall",{sessionId:r,turnId:s,blockCount:f?.length??0},o),h}catch{return null}}var hi=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,availableTools:s,tools:i,systemPrompt:a,config:c}=t,f={sessionId:t.sessionId,turnId:o};yield{type:"start",turnId:o},$(this.hooks,"turn.submitted",{...f,prompt:r[r.length-1]?.content??void 0},this.log);let h=vn(r),y=[];if(a&&y.push({role:"system",content:a}),y.push(...h),this.hooks){let A=h.filter(S=>S.role==="user").pop(),P=typeof A?.content=="string"?A.content.slice(0,500):void 0;if(P){let S=await gi({hooks:this.hooks,detectRecallCategories:O=>this.runtimePorts.detectRecallCategories(O),log:this.log,sessionId:t.sessionId,turnId:o,query:P});S&&y.splice(a?1:0,0,{role:"system",content:S})}}let C=c?.model??"",x=typeof c?.maxRounds=="number"&&Number.isFinite(c.maxRounds)?c.maxRounds:this.configuredMaxRounds,v=x===void 0?void 0:Math.min(x,100);try{let A=c?.reasoning;c?.reasoning?.effort==="auto"&&(A={...c?.reasoning,effort:"medium"});let P={turnId:o,sessionId:t.sessionId,messages:y,availableTools:s,tools:i,refreshTools:t.refreshTools,model:C,apiKey:c?.apiKey??this.apiKey,temperature:c?.temperature,maxRounds:v,contextWindowTokens:c?.contextWindowTokens,maxOutputTokens:c?.maxOutputTokens,modelMaxOutputTokens:c?.modelMaxOutputTokens,toolChoice:c?.toolChoice,parentDepth:c?.parentDepth,hooks:this.hooks,fallbackModel:c?.fallbackModel,maxTurns:c?.maxTurns,tokenBudget:c?.tokenBudget,maxConcurrentTools:c?.maxConcurrentTools,streamRequired:c?.streamRequired,reasoning:A,promptCacheKey:c?.promptCacheKey,promptCacheRetention:c?.promptCacheRetention,serviceTier:c?.serviceTier,openaiBuiltinTools:c?.openaiBuiltinTools,maxToolCalls:c?.maxToolCalls,parallelToolCalls:c?.parallelToolCalls,textVerbosity:c?.textVerbosity,projectRoot:this.projectRoot,runtimePorts:this.runtimePorts.toolLoop,signal:n},S;for await(let O of di(P,this.transport,this.toolInvoker,this.log))S=O,yield O;S?.type==="end"?$(this.hooks,"turn.completed",{...f},this.log):S?.type==="error"&&$(this.hooks,"turn.failed",{...f,code:S.code,error:S.error},this.log)}catch(A){if(n?.aborted)$(this.hooks,"turn.failed",{...f,code:"ABORTED",error:"Turn aborted"},this.log),yield{type:"error",turnId:o,error:"Turn aborted",code:"ABORTED"};else{let P=A instanceof Error?A.message:String(A),S=typeof A?.status=="number"?A.status:void 0,O=De(S,P);this.log.error(`turn ${o} error [${O}, retryable=${mn(O)}]: ${P}`),$(this.hooks,"turn.failed",{...f,code:O,error:P},this.log),yield{type:"error",turnId:o,error:P,code:O}}}}};export{hi as Agent};