qlogicagent 2.16.5 → 2.16.6
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 +20 -20
- package/dist/cli.js +372 -366
- package/dist/index.js +371 -365
- package/dist/orchestration.js +10 -10
- package/dist/types/agent/tool-loop/loop-helpers.d.ts +1 -4
- package/dist/types/agent/tool-loop/pseudo-tool-output.d.ts +8 -0
- package/dist/types/agent/tool-loop/tool-failure-policy.d.ts +0 -1
- package/dist/types/agent/tool-loop/tool-guardrails.d.ts +24 -0
- package/dist/types/agent/tool-loop/tool-result-classification.d.ts +10 -0
- package/dist/types/cli/acp-commands.d.ts +1 -2
- package/dist/types/cli/handlers/pinned-skill-context.d.ts +2 -0
- package/dist/types/cli/skill-invocation-service.d.ts +2 -0
- package/dist/types/runtime/execution/untrusted-tool-result.d.ts +2 -0
- package/dist/types/runtime/infra/skill-resolver.d.ts +8 -2
- package/dist/types/skills/mcp/mcp-manager.d.ts +20 -2
- package/dist/types/skills/skill-system/skill-bundles.d.ts +8 -0
- package/dist/types/skills/skill-system/skill-frontmatter.d.ts +1 -5
- package/dist/types/skills/skill-system/skill-lifecycle.d.ts +13 -1
- package/dist/types/skills/skill-system/skill-preprocessing.d.ts +11 -0
- package/dist/types/skills/skill-system/skill-types.d.ts +0 -75
- package/dist/types/skills/skill-system/skill-validation.d.ts +1 -0
- package/dist/types/skills/tools/skill-tool.d.ts +2 -1
- package/package.json +3 -2
- package/dist/types/skills/skill-system/skill-source.d.ts +0 -38
package/dist/agent.js
CHANGED
|
@@ -1,44 +1,44 @@
|
|
|
1
|
-
function sn(e,t,n,o){return{role:"assistant",content:t||null,tool_calls:e,...n&&n.length>0?{thinkingBlocks:n}:{},...o?{reasoning_content:o}:{}}}function V(e,t){let n=t.ok?typeof t.payload=="string"?t.payload:JSON.stringify(t.payload??""):`Error: ${t.error??"Tool execution failed"}`;return{role:"tool",tool_call_id:e,content:n,...!t.ok&&{is_error:!0},...t.toolReferences?.length?{toolReferences:t.toolReferences}:{},...t.imageUrls?.length?{imageUrls:t.imageUrls}:{}}}var di=/\b(?:daily|weekly|monthly)(?:\/(?:daily|weekly|monthly))* (?:usage )?limit(?:s)?(?: (?:exhausted|reached|exceeded))?\b/i,xe={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]},fi=/^(?:error[:\s-]+)?billing(?:\s+error)?(?:[:\s-]+|$)|^(?:error[:\s-]+)?(?:credit balance|insufficient credits?|payment required|http\s*402\b)/i,pi=/["']?(?:status|code)["']?\s*[:=]\s*402\b|\bhttp\s*402\b|\berror(?:\s+code)?\s*[:=]?\s*402\b|^\s*402\s+payment/i,mi=512,gi=/^(?:http\s*)?(\d{3})(?:\s+([\s\S]+))?$/i;var hi=new Set([500,502,503,504,521,522,523,524,529]),yi=["insufficient credits","insufficient quota","credit balance","insufficient balance","plans & billing","add more credits","top up"],bi=["upgrade your plan","upgrade plan","current plan","subscription"],Ti=["daily","weekly","monthly"],Ci=["try again","retry","temporary","cooldown"],ki=["usage limit","rate limit","organization usage"],Ri=["organization","workspace"],xi=["billing period","exceeded","reached","exhausted"],vi=/["']?(?: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,_i=/^(?:error[:\s-]+)?(?:(?:http\s*)?402(?:\s+payment required)?|payment required)(?:[:\s-]+|$)/i;function ve(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 ve(e,xe.format)}function $o(e){return ve(e,xe.rateLimit)}function Ai(e){return ve(e,xe.timeout)}function Si(e){return di.test(e)}function an(e){let t=e.toLowerCase();return t?e.length>mi?pi.test(t):ve(t,xe.billing)?!0:fi.test(e)?t.includes("upgrade")||t.includes("credits")||t.includes("payment")||t.includes("plan"):!1:!1}function Uo(e){return ve(e,xe.authPermanent)}function Mi(e){return ve(e,xe.auth)}function jo(e){return ve(e,xe.overloaded)}function Re(e,t){return t.some(n=>e.includes(n))}function Ei(e){return Re(e,yi)||Re(e,bi)&&e.includes("limit")||e.includes("billing hard limit")||e.includes("hard limit reached")||e.includes("maximum allowed")&&e.includes("limit")}function Ii(e){let t=Re(e,Ti),n=e.includes("spend limit")||e.includes("spending limit"),o=Re(e,Ri);return Re(e,Ci)&&Re(e,ki)||t&&(e.includes("usage limit")||n)||t&&e.includes("limit")&&e.includes("reset")||o&&e.includes("limit")&&(n||Re(e,xi))}function Pi(e){return e.trim().toLowerCase().replace(_i,"").trim()}function qo(e){let t=Pi(e);return!t||Ei(t)?"billing":$o(t)||Ii(t)?"rate_limit":"billing"}function Oi(e){return vi.test(e)?qo(e):null}function zo(e){let t=e.match(gi);if(!t)return null;let n=Number(t[1]);return Number.isFinite(n)?{code:n,rest:(t[2]??"").trim()}:null}function Li(e){if(!e)return!1;let t=e.toLowerCase();return t.includes('"type":"api_error"')&&t.includes("internal server error")}function Ni(e){let t=e.trim();if(!t)return!1;let n=zo(t);return n?hi.has(n.code):!1}function Ho(e,t){return typeof e!="number"||!Number.isFinite(e)?null:e===402?t?qo(t):"billing":e===429?"rate_limit":e===401||e===403?t&&Uo(t)?"auth_permanent":"auth":e===408?"timeout":e===503?t&&jo(t)?"overloaded":"timeout":e===502||e===504?"timeout":e===529?"overloaded":e===400?t&&an(t)?"billing":"format":null}function Fi(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 Bi(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 Go(e){if(Bi(e))return"session_expired";if(Fi(e))return"model_not_found";let t=Oi(e);return t||(Si(e)?an(e)?"billing":"rate_limit":$o(e)?"rate_limit":jo(e)?"overloaded":Ni(e)?zo(e.trim())?.code===529?"overloaded":"timeout":Li(e)?"timeout":wi(e)?"format":an(e)?"billing":Ai(e)?"timeout":Uo(e)?"auth_permanent":Mi(e)?"auth":null)}var Di={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"},$i=new Set(["RETRYABLE_TRANSIENT","RETRYABLE_DEGRADED","TOOL_EXECUTION_FAILED"]);function Fe(e,t){let n=Ho(e,t)??(t?Go(t):null);return n?Di[n]:typeof e=="number"&&e>=400&&e<500?"NON_RETRYABLE_CONTENT":"RETRYABLE_TRANSIENT"}function ln(e){return $i.has(e)}function Wo(e){let t=typeof e.content=="string"?e.content:e.content!=null?JSON.stringify(e.content):"";return Math.ceil(t.length/4)}var Ui=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"]),Xe=class{constructor(t=20,n=Wo){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||!Ui.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 cn(e,t,n=Wo){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 un(){return{stages:[]}}function dn(e,t,n){let o=n?.thresholdMessages??40;if(e.filter(a=>a.role!=="system").length<=o)return{messages:e,stagedCount:0};let s=Vo(e,t),i=ji(s,t,o);if(i.length===0)return{messages:s,stagedCount:0};for(let a of i)t.stages.push(a);return s=Vo(e,t),{messages:s,stagedCount:i.length}}function fn(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:Xo(e,t),committed:n}}function Vo(e,t){return t.stages.filter(o=>o.committed).length===0?e:Xo(e,t)}function Xo(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 ji(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 f=e[u];if(f.role==="tool"||f.role==="assistant"&&typeof f.content=="string"&&f.content==="")i<0&&(i=u),a++;else{if(a>=3){let T=`${i}-${i+a}`;s.has(T)||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 qi,writeFileSync as zi,mkdirSync as Hi}from"node:fs";import{join as Gi,dirname as Wi}from"node:path";var ge=Math.min(Math.max(1,Number(process.env.TOOL_LOOP_DEFAULT_BUDGET)||25),100),Ko=Math.max(1e3,Number(process.env.TOOL_LOOP_TOOL_TIMEOUT_MS)||24e4),Yo=3,Zo=2,gt=2,Jo=128e3,Qo=13e3,er=16384,tr=65536,nr=3,or=65536,pn=500,rr=3;var sr=3e4,ir=3,_e=2;var ar=3,lr=2,cr=300*1e3,ur=3,dr=720*60*60*1e3;var vu=3600*1e3;var _u=50*1024,wu=500*1024,Au=500*1024*1024,Su=50*1024*1024;var Mu=60*1024;var pr=0;var Vi="skill-patterns.json";function mr(e){return Gi(e,".qlogicagent",Vi)}function Xi(e){let t=mr(e);try{return JSON.parse(qi(t,"utf8"))}catch{return{version:1,patterns:{}}}}function fr(e,t){let n=mr(e);Hi(Wi(n),{recursive:!0}),zi(n,JSON.stringify(t,null,2),"utf8")}function Ki(e){let t=Date.now()-dr;for(let[n,o]of Object.entries(e.patterns))new Date(o.lastSeen).getTime()<t&&delete e.patterns[n]}function gr(e,t){if(t.length===0)return!1;let n=hr(t),o=Xi(e);Ki(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 fr(e,o),!1;s.count++,s.lastSeen=r;let i=s.count>=ur;return i&&(s.promoted=!0),fr(e,o),i}function hr(e){return[...e].sort().join("+")}function Yi(e,t){return!(!e.ok||e.existingSkillName||!e.multiStep||e.toolCallCount<ar||e.distinctToolCount<lr||Date.now()-pr<cr||t?.projectRoot&&t.tools.length>0&&!gr(t.projectRoot,t.tools))}function Zi(e){return e.existingSkillName?e.feedback==="negative":!1}function mn(e,t){return Zi(e)?{type:"skill.improve",skillName:e.existingSkillName,reason:"negative user feedback on existing skill execution"}:Yi(e,t)?(pr=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 Ji(e){let t=new Set(e.map(gn).filter(Boolean)),n=t.has("exec"),o=["read","search","write","edit","patch"].some(r=>t.has(r));return!n||!o?"You must call one of the available tools before responding.":'You must call one of the available tools before responding. 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 gn(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 Qi(e){return e==="enabled-eligible"||e==="installed-awaiting-approval"}function ea(e){return new Map((e??[]).map(t=>[t.toolName,t]))}function ta(e){if(!e.eligibility?.length)return[...e.tools];let t=ea(e.eligibility);return e.tools.filter(n=>{let o=gn(n);if(!o)return!1;let r=t.get(o);return!r||Qi(r.status)})}function na(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 hn(e){let t=na({toolChoice:e.toolChoice,thinkingEnabled:e.thinkingEnabled,compatibility:e.compatibility}),n=t.normalizedToolChoice,o=[...t.warnings],r=ta({tools:e.tools,eligibility:e.eligibility});if(!n||n==="auto")return{tools:r,normalizedToolChoice:n,warnings:o};if(n==="none")return{tools:[],normalizedToolChoice:"none",warnings:o};if(n==="required"){if(r.length===0)throw new Error("tool_choice=required but no tools were provided");return{tools:r,normalizedToolChoice:"required",extraSystemPrompt:Ji(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=>gn(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 oa=["stop","aborted","timeout","cancelled","interrupted","error"],ra=["tool_calls","toolCalls","function_call","functionCall","raw_tool_calls","rawToolCalls"];function yr(e){return e==null?[]:typeof e=="string"?e.length>0?[{type:"text",text:e}]:[]:Array.isArray(e)?e:[{type:"text",text:String(e)}]}function sa(e,t){return{...e,content:[...yr(e.content),...yr(t.content)]}}function ia(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 aa(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=ia(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 la(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 ca(e){return new Set((e??oa).map(t=>t.trim().toLowerCase()))}function ua(e,t){return e?ca(t).has(e.trim().toLowerCase()):!1}function yn(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 f=u.tool_calls.filter(h=>la(h));return{...u,...f.length>0?{tool_calls:f}:{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 f of u.tool_calls)typeof f.id=="string"&&f.id&&n.add(f.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 f=u.tool_calls.filter(h=>typeof h.id=="string"&&r.has(h.id));if(f.length===0){let{tool_calls:h,...T}=u;T.content!=null&&T.content!==""&&s.push(T);continue}if(f.length<u.tool_calls.length){s.push({...u,tool_calls:f});continue}}s.push(u)}let i=aa(s),a=[];for(let u of i){let f=a.length>0?a[a.length-1]:void 0;if(u.role==="user"&&f?.role==="user"){a[a.length-1]=sa(f,u);continue}a.push(u)}return a}function bn(e,t){return ua(t?.stopReason,t?.forcedStopReasons)?e.map(n=>{if(n.role!=="assistant")return{...n};let o={...n};for(let r of ra)delete o[r];return o}):[...e]}function Tn(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 Cn(e,t){let n=yn(e),o=bn(n,t);return Tn(o,t)}function da(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 fa(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 pa(e){return{round:e.round??0,maxRounds:e.maxRounds,pendingToolCallIds:[...e.pendingToolCallIds??[]],completedToolCallIds:[...e.completedToolCallIds??[]],lastStopReason:e.lastStopReason,replayMessages:[...e.replayMessages??[]]}}function kn(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 ht(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 yt(e){let t=[],n=yn(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=bn(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=Tn(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:pa({maxRounds:e.maxRounds,round:e.round,lastStopReason:e.lastStopReason,replayMessages:r,pendingToolCallIds:da(r),completedToolCallIds:fa(r)}),recoveryActions:t}}var ma=new Set(["main","sdk","agent","compact","hook","verification","side_question"]);function Rn(e){return e?ma.has(e):!0}function xn(e){return e===429||e===529}function bt(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 qu={maxBackoffMs:300*1e3,resetCapMs:360*60*1e3,heartbeatIntervalMs:3e4};function Tt(){let e=process.env.QLOGICAGENT_PERSISTENT_RETRY;return e==="1"||e==="true"}var Ke=class extends Error{constructor(n,o){super(`Model fallback triggered: ${n} -> ${o}`);this.originalModel=n;this.fallbackModel=o;this.name="FallbackTriggeredError"}originalModel;fallbackModel};function vn(e){return{promptTokens:0,hasAttemptedReactiveCompact:!1,currentMaxOutputTokens:e.maxOutputTokens,consecutiveTruncations:0,aborted:e.abortSignal?.aborted??!1}}function _n(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 wn(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 An(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 Sn(e,t){return e.aborted?!0:t.abortSignal?.aborted?(e.aborted=!0,!0):!1}var ha={maxConsecutiveFailures:3,minMessagesAfterCompact:4,targetUsagePercent:50};function Mn(){return{consecutiveFailures:0,attemptedThisTurn:!1,lastCompactAt:null,toolsAtLastCompact:[]}}function Be(e,t=ha){return!(e.attemptedThisTurn||e.consecutiveFailures>=t.maxConsecutiveFailures)}import{createHash as Vl}from"node:crypto";import{existsSync as Ie,readFileSync as Nt}from"node:fs";function En(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 br(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 Tr(e,t){if(!t.ok)return[];let n=t.details;if(!n)return[];let o=ya(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 ya(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 ba=new Set(["write","edit","patch"]);function Cr(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=Ta(r.function.arguments);if(!i)return s;if(ba.has(n.toolName)){let a=Ca(i);a&&s.push({type:"artifact",turnId:t,artifactId:`artifact-${n.callId}`,artifactType:ka(a),title:a.split(/[\\/]/).pop()||a,filePath:a,language:Ra(a)})}return s}function Ta(e){try{return JSON.parse(e)}catch{return null}}function Ca(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 ka(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 Ra(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 xa=new Set(["write","edit","patch"]),va=new Set(["image_generate"]),_a=/\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 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,In=/https?:\/\/[^\s"'`<>),;]+/gi,Aa=/\b(?:fatal|timeout|timed out|waitforselector|waiting for locator|strict mode violation|exception|traceback|eaddrinuse|page crashed|browser closed|target closed)\b|鏃犳硶灏唡閿欒|澶辫触|瓒呮椂/i,Sa=/\b(?:default vite|vite \+ react|edit src\/app|click on the vite|vite page)\b|默认\s*Vite/i,kr=/\b(?:browser|playwright|puppeteer|screenshot|opened|loaded|navigated|visible|locator|page\.goto|http:\/\/127\.0\.0\.1|http:\/\/localhost)\b|(?:浏览器|截图|页面可见|打开页面|加载页面|内置浏览器|自动化)/i;function Ma(e){let t=$n(e);return{artifactRoot:t,rootSource:t?"explicit":void 0,writePaths:[],outOfRootWrites:[],devServerUrls:[],browserVerified:!1,browserEvidence:[],browserFailureEvidence:[],buildVerified:!1,buildEvidence:[],buildFailureEvidence:[]}}function se(e){return e.some(t=>t.role==="user"&&typeof t.content=="string"&&_a.test(t.content))}var Ea=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 Ln(e){return e.some(t=>t.role==="user"&&typeof t.content=="string"&&Ea.test(t.content))}function Ia(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 Rr(e){return["Done","Not done","Artifacts","Verification","Blockers","Next action"].every(t=>new RegExp(`(^|\\n)${t}:`,"i").test(e))}function _r(e){return["Sourced facts","Assumptions","Recommendations","Unsupported claims"].every(t=>new RegExp(`(^|\\n)${t}:`,"i").test(e))}function Nn(e,t){let n=Pr(t);return n?xa.has(e)?xr(n.path,n.file_path,n.filePath,n.filename,n.file):va.has(e)?xr(n.output_path,Array.isArray(n.output_paths)?n.output_paths[0]:void 0):null:null}function wr(e){let t=Nn(e.toolName,e.rawArguments);if(!t||!se(e.inputMessages))return null;if(!e.state.artifactRoot){let r=$n(e.inputMessages);r?(e.state.artifactRoot=r,e.state.rootSource="explicit"):(e.state.artifactRoot=Or(t),e.state.rootSource=e.state.artifactRoot?"inferred":void 0)}let n=e.state.artifactRoot;if(!n||e.state.rootSource!=="explicit"||Nr(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 Ar(e){let t=Nn(e.toolName,e.rawArguments);return!t||!Wa(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 Fn(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 Sr(e){let t=Nn(e.toolName,e.rawArguments);if(t){if(!e.state.artifactRoot){let o=$n(e.inputMessages);e.state.artifactRoot=o??Or(t),e.state.rootSource=o?"explicit":e.state.artifactRoot?"inferred":void 0}e.state.writePaths.includes(t)||e.state.writePaths.push(t),se(e.inputMessages)&&e.state.artifactRoot&&e.state.rootSource==="explicit"&&!Nr(t,e.state.artifactRoot)&&Fn(e.state,{path:t,artifactRoot:e.state.artifactRoot,toolName:e.toolName})}let n=`${e.rawArguments}
|
|
2
|
-
${e.content}`;for(let o of n.matchAll(
|
|
1
|
+
function ln(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 ki=/\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]},Ri=/^(?:error[:\s-]+)?billing(?:\s+error)?(?:[:\s-]+|$)|^(?:error[:\s-]+)?(?:credit balance|insufficient credits?|payment required|http\s*402\b)/i,xi=/["']?(?:status|code)["']?\s*[:=]\s*402\b|\bhttp\s*402\b|\berror(?:\s+code)?\s*[:=]?\s*402\b|^\s*402\s+payment/i,_i=512,vi=/^(?:http\s*)?(\d{3})(?:\s+([\s\S]+))?$/i;var wi=new Set([500,502,503,504,521,522,523,524,529]),Ai=["insufficient credits","insufficient quota","credit balance","insufficient balance","plans & billing","add more credits","top up"],Si=["upgrade your plan","upgrade plan","current plan","subscription"],Mi=["daily","weekly","monthly"],Ei=["try again","retry","temporary","cooldown"],Ii=["usage limit","rate limit","organization usage"],Pi=["organization","workspace"],Oi=["billing period","exceeded","reached","exhausted"],Ni=/["']?(?: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,Li=/^(?:error[:\s-]+)?(?:(?:http\s*)?402(?:\s+payment required)?|payment required)(?:[:\s-]+|$)/i;function we(e,t){if(!e)return!1;let n=e.toLowerCase();return t.some(o=>o instanceof RegExp?o.test(n):n.includes(o))}function Fi(e){return we(e,ve.format)}function Vo(e){return we(e,ve.rateLimit)}function Bi(e){return we(e,ve.timeout)}function Di(e){return ki.test(e)}function cn(e){let t=e.toLowerCase();return t?e.length>_i?xi.test(t):we(t,ve.billing)?!0:Ri.test(e)?t.includes("upgrade")||t.includes("credits")||t.includes("payment")||t.includes("plan"):!1:!1}function Xo(e){return we(e,ve.authPermanent)}function $i(e){return we(e,ve.auth)}function Ko(e){return we(e,ve.overloaded)}function _e(e,t){return t.some(n=>e.includes(n))}function Ui(e){return _e(e,Ai)||_e(e,Si)&&e.includes("limit")||e.includes("billing hard limit")||e.includes("hard limit reached")||e.includes("maximum allowed")&&e.includes("limit")}function ji(e){let t=_e(e,Mi),n=e.includes("spend limit")||e.includes("spending limit"),o=_e(e,Pi);return _e(e,Ei)&&_e(e,Ii)||t&&(e.includes("usage limit")||n)||t&&e.includes("limit")&&e.includes("reset")||o&&e.includes("limit")&&(n||_e(e,Oi))}function qi(e){return e.trim().toLowerCase().replace(Li,"").trim()}function Yo(e){let t=qi(e);return!t||Ui(t)?"billing":Vo(t)||ji(t)?"rate_limit":"billing"}function zi(e){return Ni.test(e)?Yo(e):null}function Zo(e){let t=e.match(vi);if(!t)return null;let n=Number(t[1]);return Number.isFinite(n)?{code:n,rest:(t[2]??"").trim()}:null}function Hi(e){if(!e)return!1;let t=e.toLowerCase();return t.includes('"type":"api_error"')&&t.includes("internal server error")}function Gi(e){let t=e.trim();if(!t)return!1;let n=Zo(t);return n?wi.has(n.code):!1}function Jo(e,t){return typeof e!="number"||!Number.isFinite(e)?null:e===402?t?Yo(t):"billing":e===429?"rate_limit":e===401||e===403?t&&Xo(t)?"auth_permanent":"auth":e===408?"timeout":e===503?t&&Ko(t)?"overloaded":"timeout":e===502||e===504?"timeout":e===529?"overloaded":e===400?t&&cn(t)?"billing":"format":null}function Wi(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 Vi(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 Qo(e){if(Vi(e))return"session_expired";if(Wi(e))return"model_not_found";let t=zi(e);return t||(Di(e)?cn(e)?"billing":"rate_limit":Vo(e)?"rate_limit":Ko(e)?"overloaded":Gi(e)?Zo(e.trim())?.code===529?"overloaded":"timeout":Hi(e)?"timeout":Fi(e)?"format":cn(e)?"billing":Bi(e)?"timeout":Xo(e)?"auth_permanent":$i(e)?"auth":null)}var Xi={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"},Ki=new Set(["RETRYABLE_TRANSIENT","RETRYABLE_DEGRADED","TOOL_EXECUTION_FAILED"]);function $e(e,t){let n=Jo(e,t)??(t?Qo(t):null);return n?Xi[n]:typeof e=="number"&&e>=400&&e<500?"NON_RETRYABLE_CONTENT":"RETRYABLE_TRANSIENT"}function un(e){return Ki.has(e)}function er(e){let t=typeof e.content=="string"?e.content:e.content!=null?JSON.stringify(e.content):"";return Math.ceil(t.length/4)}var Yi=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=er){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||!Yi.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 dn(e,t,n=er){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 fn(){return{stages:[]}}function pn(e,t,n){let o=n?.thresholdMessages??40;if(e.filter(a=>a.role!=="system").length<=o)return{messages:e,stagedCount:0};let s=tr(e,t),i=Zi(s,t,o);if(i.length===0)return{messages:s,stagedCount:0};for(let a of i)t.stages.push(a);return s=tr(e,t),{messages:s,stagedCount:i.length}}function mn(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:nr(e,t),committed:n}}function tr(e,t){return t.stages.filter(o=>o.committed).length===0?e:nr(e,t)}function nr(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 Zi(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 f=e[u];if(f.role==="tool"||f.role==="assistant"&&typeof f.content=="string"&&f.content==="")i<0&&(i=u),a++;else{if(a>=3){let T=`${i}-${i+a}`;s.has(T)||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 Ji,writeFileSync as Qi,mkdirSync as ea}from"node:fs";import{join as ta,dirname as na}from"node:path";var ye=Math.min(Math.max(1,Number(process.env.TOOL_LOOP_DEFAULT_BUDGET)||25),100),or=Math.max(1e3,Number(process.env.TOOL_LOOP_TOOL_TIMEOUT_MS)||24e4),rr=3,sr=2,yt=2,ir=128e3,ar=13e3,lr=16384,cr=65536,ur=3,dr=65536,gn=500,fr=3;var pr=3e4,mr=3,Ae=2;var gr=3,hr=2,yr=300*1e3,br=3,Tr=720*60*60*1e3;var Wu=3600*1e3;var Vu=50*1024,Xu=500*1024,Ku=500*1024*1024,Yu=50*1024*1024;var Zu=60*1024;var kr=0;var oa="skill-patterns.json";function Rr(e){return ta(e,".qlogicagent",oa)}function ra(e){let t=Rr(e);try{return JSON.parse(Ji(t,"utf8"))}catch{return{version:1,patterns:{}}}}function Cr(e,t){let n=Rr(e);ea(na(n),{recursive:!0}),Qi(n,JSON.stringify(t,null,2),"utf8")}function sa(e){let t=Date.now()-Tr;for(let[n,o]of Object.entries(e.patterns))new Date(o.lastSeen).getTime()<t&&delete e.patterns[n]}function xr(e,t){if(t.length===0)return!1;let n=_r(t),o=ra(e);sa(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 Cr(e,o),!1;s.count++,s.lastSeen=r;let i=s.count>=br;return i&&(s.promoted=!0),Cr(e,o),i}function _r(e){return[...e].sort().join("+")}function ia(e,t){return!(!e.ok||e.existingSkillName||!e.multiStep||e.toolCallCount<gr||e.distinctToolCount<hr||Date.now()-kr<yr||t?.projectRoot&&t.tools.length>0&&!xr(t.projectRoot,t.tools))}function aa(e){return e.existingSkillName?e.feedback==="negative":!1}function hn(e,t){return aa(e)?{type:"skill.improve",skillName:e.existingSkillName,reason:"negative user feedback on existing skill execution"}:ia(e,t)?(kr=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 la(e){return[...new Set(e.map(bt).filter(Boolean))].sort((t,n)=>t.localeCompare(n))}function vr(e){let t=la(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 ca(e){let t=[...new Set(e.map(bt).filter(Boolean))].sort((i,a)=>i.localeCompare(a)),n=new Set(t),o=vr(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 bt(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 ua(e){return e==="enabled-eligible"||e==="installed-awaiting-approval"}function da(e){return new Map((e??[]).map(t=>[t.toolName,t]))}function fa(e){if(!e.eligibility?.length)return[...e.tools];let t=da(e.eligibility);return e.tools.filter(n=>{let o=bt(n);if(!o)return!1;let r=t.get(o);return!r||ua(r.status)})}function pa(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 yn(e){let t=pa({toolChoice:e.toolChoice,thinkingEnabled:e.thinkingEnabled,compatibility:e.compatibility}),n=t.normalizedToolChoice,o=[...t.warnings],r=fa({tools:e.tools,eligibility:e.eligibility});if(!n||n==="auto")return{tools:r,normalizedToolChoice:n,...r.length>0?{extraSystemPrompt:vr(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:ca(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=>bt(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 ma=["stop","aborted","timeout","cancelled","interrupted","error"],ga=["tool_calls","toolCalls","function_call","functionCall","raw_tool_calls","rawToolCalls"];function wr(e){return e==null?[]:typeof e=="string"?e.length>0?[{type:"text",text:e}]:[]:Array.isArray(e)?e:[{type:"text",text:String(e)}]}function ha(e,t){return{...e,content:[...wr(e.content),...wr(t.content)]}}function ya(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 ba(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=ya(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 Ta(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 Ca(e){return new Set((e??ma).map(t=>t.trim().toLowerCase()))}function ka(e,t){return e?Ca(t).has(e.trim().toLowerCase()):!1}function bn(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 f=u.tool_calls.filter(h=>Ta(h));return{...u,...f.length>0?{tool_calls:f}:{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 f of u.tool_calls)typeof f.id=="string"&&f.id&&n.add(f.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 f=u.tool_calls.filter(h=>typeof h.id=="string"&&r.has(h.id));if(f.length===0){let{tool_calls:h,...T}=u;T.content!=null&&T.content!==""&&s.push(T);continue}if(f.length<u.tool_calls.length){s.push({...u,tool_calls:f});continue}}s.push(u)}let i=ba(s),a=[];for(let u of i){let f=a.length>0?a[a.length-1]:void 0;if(u.role==="user"&&f?.role==="user"){a[a.length-1]=ha(f,u);continue}a.push(u)}return a}function Tn(e,t){return ka(t?.stopReason,t?.forcedStopReasons)?e.map(n=>{if(n.role!=="assistant")return{...n};let o={...n};for(let r of ga)delete o[r];return o}):[...e]}function Cn(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 kn(e,t){let n=bn(e),o=Tn(n,t);return Cn(o,t)}function Ra(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 xa(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 _a(e){return{round:e.round??0,maxRounds:e.maxRounds,pendingToolCallIds:[...e.pendingToolCallIds??[]],completedToolCallIds:[...e.completedToolCallIds??[]],lastStopReason:e.lastStopReason,replayMessages:[...e.replayMessages??[]]}}function Rn(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 Tt(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 Ct(e){let t=[],n=bn(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=Tn(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=Cn(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:_a({maxRounds:e.maxRounds,round:e.round,lastStopReason:e.lastStopReason,replayMessages:r,pendingToolCallIds:Ra(r),completedToolCallIds:xa(r)}),recoveryActions:t}}var va=new Set(["main","sdk","agent","compact","hook","verification","side_question"]);function xn(e){return e?va.has(e):!0}function _n(e){return e===429||e===529}function kt(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 ud={maxBackoffMs:300*1e3,resetCapMs:360*60*1e3,heartbeatIntervalMs:3e4};function Rt(){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 vn(e){return{promptTokens:0,hasAttemptedReactiveCompact:!1,currentMaxOutputTokens:e.maxOutputTokens,consecutiveTruncations:0,aborted:e.abortSignal?.aborted??!1}}function wn(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 An(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 Sn(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 Mn(e,t){return e.aborted?!0:t.abortSignal?.aborted?(e.aborted=!0,!0):!1}var Aa={maxConsecutiveFailures:3,minMessagesAfterCompact:4,targetUsagePercent:50};function En(){return{consecutiveFailures:0,attemptedThisTurn:!1,lastCompactAt:null,toolsAtLastCompact:[]}}function Ue(e,t=Aa){return!(e.attemptedThisTurn||e.consecutiveFailures>=t.maxConsecutiveFailures)}import{createHash as lc}from"node:crypto";import{existsSync as Oe,readFileSync as Bt}from"node:fs";function In(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 Ar(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 Sr(e,t){if(!t.ok)return[];let n=t.details;if(!n)return[];let o=Sa(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 Sa(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 Ma=new Set(["write","edit","patch"]);function Mr(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=Ea(r.function.arguments);if(!i)return s;if(Ma.has(n.toolName)){let a=Ia(i);a&&s.push({type:"artifact",turnId:t,artifactId:`artifact-${n.callId}`,artifactType:Pa(a),title:a.split(/[\\/]/).pop()||a,filePath:a,language:Oa(a)})}return s}function Ea(e){try{return JSON.parse(e)}catch{return null}}function Ia(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 Pa(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 Oa(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 Na=new Set(["write","edit","patch"]),La=new Set(["image_generate"]),Fa=/\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 Ba=/\b(?:under|inside|in|at|to|root|directory|folder|output directory|output folder)\s+([A-Za-z]:[\\/][^\s"'`<>|]+)|(?:目录|文件夹|根目录|输出到|放到|位于)\s*([A-Za-z]:[\\/][^\s"'`<>|]+)/gi,Pn=/https?:\/\/[^\s"'`<>),;]+/gi,Da=/\b(?:fatal|timeout|timed out|waitforselector|waiting for locator|strict mode violation|exception|traceback|eaddrinuse|page crashed|browser closed|target closed)\b|鏃犳硶灏唡閿欒|澶辫触|瓒呮椂/i,$a=/\b(?:default vite|vite \+ react|edit src\/app|click on the vite|vite page)\b|默认\s*Vite/i,Er=/\b(?:browser|playwright|puppeteer|screenshot|opened|loaded|navigated|visible|locator|page\.goto|http:\/\/127\.0\.0\.1|http:\/\/localhost)\b|(?:浏览器|截图|页面可见|打开页面|加载页面|内置浏览器|自动化)/i;function Ua(e){let t=Un(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"&&Fa.test(t.content))}var ja=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 Ln(e){return e.some(t=>t.role==="user"&&typeof t.content=="string"&&ja.test(t.content))}function qa(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 Ir(e){return["Done","Not done","Artifacts","Verification","Blockers","Next action"].every(t=>new RegExp(`(^|\\n)${t}:`,"i").test(e))}function Nr(e){return["Sourced facts","Assumptions","Recommendations","Unsupported claims"].every(t=>new RegExp(`(^|\\n)${t}:`,"i").test(e))}function Fn(e,t){let n=jr(t);return n?Na.has(e)?Pr(n.path,n.file_path,n.filePath,n.filename,n.file):La.has(e)?Pr(n.output_path,Array.isArray(n.output_paths)?n.output_paths[0]:void 0):null:null}function Lr(e){let t=Fn(e.toolName,e.rawArguments);if(!t||!ae(e.inputMessages))return null;if(!e.state.artifactRoot){let r=Un(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"||Hr(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 Fr(e){let t=Fn(e.toolName,e.rawArguments);return!t||!ol(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 Bn(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 Br(e){let t=Fn(e.toolName,e.rawArguments);if(t){if(!e.state.artifactRoot){let o=Un(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),ae(e.inputMessages)&&e.state.artifactRoot&&e.state.rootSource==="explicit"&&!Hr(t,e.state.artifactRoot)&&Bn(e.state,{path:t,artifactRoot:e.state.artifactRoot,toolName:e.toolName})}let n=`${e.rawArguments}
|
|
2
|
+
${e.content}`;for(let o of n.matchAll(Pn)){let r=Nn(o[0]);r&&(e.state.devServerUrls.includes(r)||e.state.devServerUrls.push(r))}if(Za(e.toolName,e.rawArguments,e.content)&&zr(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&&Ya(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(el(e.toolName,e.rawArguments))if(!e.ok||tl(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 Dn(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 Dr(e){let t=Ua(e);for(let n of e)n.role!=="assistant"||typeof n.content!="string"||$n(t,n.content);return t}function $n(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=be(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=be(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=be(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(Pn)){let a=Nn(i[0]);a&&!e.devServerUrls.includes(a)&&e.devServerUrls.push(a)}for(let i of t.matchAll(Pn)){let a=Nn(i[0]);a&&/^https?:\/\/(?:localhost|127\.0\.0\.1):\d+\//i.test(a)&&(e.devServerUrls.includes(a)||e.devServerUrls.push(a))}}function $r(e){let t=e.content.trim(),n=ae(e.inputMessages),o=qa(e.inputMessages),r=Ln(e.inputMessages),s=rl(t),i=t;if(Ur(e.activeTasks??[]).length>0&&(i=Ga(i)),n&&!e.artifactContract.browserVerified&&(i=Wa(i)),r&&!e.artifactContract.buildVerified&&(i=Va(i)),!(s&&e.totalToolCallCount===0)&&o&&!Nr(i)){let h=Ka(i);i=i?`${i}
|
|
3
3
|
|
|
4
|
-
${h}`:h}let u=!!e.artifactContract.artifactRoot||e.artifactContract.writePaths.length>0||e.artifactContract.devServerUrls.length>0||e.artifactContract.browserVerified||e.artifactContract.outOfRootWrites.length>0;if((e.totalToolCallCount>0||n||r||u)&&!
|
|
4
|
+
${h}`:h}let u=!!e.artifactContract.artifactRoot||e.artifactContract.writePaths.length>0||e.artifactContract.devServerUrls.length>0||e.artifactContract.browserVerified||e.artifactContract.outOfRootWrites.length>0;if((e.totalToolCallCount>0||n||r||u)&&!Ir(i)&&!Ir(i)){let h=za({...e,content:i,needsBrowser:n,needsResearch:o,needsBuild:r});i=i?`${i}
|
|
5
5
|
|
|
6
|
-
${h}`:h}return i}function
|
|
7
|
-
`)}function
|
|
8
|
-
`)}function
|
|
9
|
-
${n}`),s=
|
|
6
|
+
${h}`:h}return i}function za(e){let t=[],n=[],o=Ur(e.activeTasks??[]);if(o.length>0&&(n.push(`Task list still has ${o.length} unresolved item(s): ${o.map(Ha).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(f=>`${f.toolName} attempted ${f.path} outside ${f.artifactRoot}.`))),e.needsBrowser&&!e.artifactContract.browserVerified){let f=e.artifactContract.browserFailureEvidence[0];n.push(f?"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(f?`Fix the browser verification failure before claiming completion: ${f}`:"Load the served app in a browser-capable tool and verify visible UI behavior before claiming completion.")}if(e.needsBuild&&!e.artifactContract.buildVerified){let f=e.artifactContract.buildFailureEvidence[0];n.push(f?"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(f?`Fix the code and re-run the test/build until it passes (do not edit the test): ${f.slice(0,200)}`:"Run the project's test/build command and confirm it exits 0 before claiming completion.")}e.needsResearch&&!Nr(e.content)&&n.push("Research/report quality audit sections were not separated in the model response.");let r=Xa(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(f=>`${f.name} blocked by ${f.reason}.`)));let s=e.totalToolCallCount>0?`Ran ${e.totalToolCallCount} tool call${e.totalToolCallCount===1?"":"s"} (${[...e.distinctToolNames].join(", ")||"unknown tools"}).`:"No tool work was recorded.",i=[e.artifactContract.artifactRoot?`artifactRoot: ${be(e.artifactContract.artifactRoot)}`:"artifactRoot: not declared",e.artifactContract.writePaths.length>0?`files: ${e.artifactContract.writePaths.slice(0,8).map(be).join(", ")}`:"files: no write paths recorded",e.artifactContract.devServerUrls.length>0?`urls: ${e.artifactContract.devServerUrls.join(", ")}`:"urls: none recorded"],a=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.",u=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:",`- ${s}`,"","Not done:",...n.length>0?n.map(f=>`- ${f}`):["- None recorded."],"","Artifacts:",...i.map(f=>`- ${f}`),"","Verification:",`- ${a}`,"","Blockers:",...t.length>0?t.map(f=>`- ${f}`):["- None recorded."],"","Next action:",`- ${u}`].join(`
|
|
7
|
+
`)}function Ur(e){return e.filter(t=>t.status!=="completed")}function Ha(e){return`#${e.id} ${e.title} (${e.status})`}function Ga(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 Wa(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 Va(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 Xa(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 Ka(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 jr(e){try{return JSON.parse(e)}catch{return null}}function Pr(...e){for(let t of e)if(typeof t=="string"&&t.trim())return t.trim();return null}function Un(e){for(let t of e)if(!(t.role!=="user"||typeof t.content!="string"))for(let n of t.content.matchAll(Ba)){let o=n[1]??n[2],r=xt(o??"");if(r&&!nl(r))return be(r)}}function qr(e){let t=be(xt(e));if(!t)return;let n=t.toLowerCase();if(n.endsWith("/package.json"))return Or(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 Or(t)}function Ya(e,t,n){if(/^read$/i.test(e)||n.includes("<persisted-output>")||zr(n)||/\b(?:syntax error|command not found|cannot find|not recognized|failed|failure|exception|traceback|eaddrinuse)\b|无法将|错误|失败/i.test(n))return!1;let o=Er.test(n),r=/\b(?:playwright|puppeteer|browser|screenshot|locator|page\.goto|dom snapshot|visible text|assertion)\b|浏览器|截图|可见|定位器/i.test(`${t}
|
|
9
|
+
${n}`),s=jn(e)&&Er.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)||$a.test(n)&&!/\b(?:absent|removed|not present|gone|没有|不是默认|已移除)\b/i.test(n))}function Za(e,t,n){return/^read$/i.test(e)||!jn(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 zr(e){return/\b(?:no failed|0 failed|without failed|no failures|failure:? none|failed checks?:? none)\b/i.test(e)?!1:Da.test(e)?!0:/\b(?:fail|failed|failure|error)\b/i.test(e)}function jn(e){return/^(?:exec|bash|shell|powershell|terminal|playwright|browser|computer)$/i.test(e)}var Ja=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 Qa(e){let t=jr(e);return t&&typeof t.command=="string"?t.command:""}function el(e,t){return jn(e)?Ja.test(Qa(t)):!1}function tl(e){return/\[exit [1-9]\d*\b|\(exit code [1-9]\d*\b|\[interrupted — exit code [1-9]\d*/.test(e)}function nl(e){return/\.[A-Za-z0-9]{1,12}$/.test(e)}function Hr(e,t){let n=On(e),o=On(t);return n===o||n.startsWith(`${o}/`)}function ol(e){return On(e).split("/").includes("context-pack")}function On(e){return xt(e).replace(/\\/g,"/").replace(/\/+/g,"/").replace(/\/$/u,"").toLowerCase()}function be(e){return xt(e).replace(/\\/g,"/").replace(/\/+/g,"/").replace(/\/$/u,"")}function Nn(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 xt(e){return e.trim().replace(/[).,;:,。;、:]+$/u,"")}function rl(e){return/^[A-Z0-9_ -]{6,80}$/.test(e.trim())}function Or(e){let t=be(e),n=t.lastIndexOf("/");return n>0?t.slice(0,n):t}var sl=/^no (matches|files|results) found(?:\s+for:.*)?\.?$|^file not found|^not found|^0 results|^\(exit code \d+, no output\)$/i,il=new Set(["search","web_search","grep","glob","find","list","read","exec"]);function qn(e){if(!il.has(e.toolName))return!1;let t=typeof e.message?.content=="string"?al(e.message.content).trim():"";return t.length>0&&t.length<200&&sl.test(t)}function al(e){return e.match(/<untrusted_tool_result\b[^>]*>\s*([\s\S]*?)\s*<\/untrusted_tool_result>/i)?.[1]??e}var ll=/[A-Za-z]:[\\/](?:[^\s"'`<>|,\uFF0C\u3001;\uFF1B\u3002]+[\\/])*[^\s"'`<>|,\uFF0C\u3001;\uFF1B\u3002]+\.[A-Za-z0-9]{1,12}/g,cl=/(?:^|[\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,ul=/(?:^|[\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,dl=/\b(?:create|generate|write|produce|save|output|deliver|deliverables?|artifacts?|required|required files?|must generate|self-verify)\b|(?:生成|创建|写入|输出|保存|交付|产物|文件|必须|自检|验证)/i;function _t(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 fl=/\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,Gr=50,Wr=90;function Vr(e){if(!e)return!1;for(let t of e)if(t.role==="user"&&typeof t.content=="string"&&fl.test(t.content))return!0;return!1}var pl=/(?:我来|我先|我现在就?|让我先?|接下来我?|我帮你|我这就|我会|我将|我去|我看)[^。.!?!?\n]{0,12}(?:做|搭建?|写|开发|实现|构建|生成|创建|新建|建立|改|修复?|检查|读取?|运行|跑|执行|看一?下?|查看|配置|安装|部署|分析|整理|定位|排查|找)/,ml=/\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 Xr(e){let t=e.trim();return t.length===0||t.length>200||t.includes("```")?!1:pl.test(t)||ml.test(t)}function Kr(e,t){if(typeof e=="number"&&Number.isFinite(e)&&e>=1)return Math.min(Math.round(e),100);let n=vt(t);return n>=3?Math.min(Math.max(25,20+n*15),100):ae(t??[])?Math.min(Math.max(25,Wr),100):Vr(t)?Math.min(Math.max(25,Gr),100):25}function vt(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(ll))o(i[0]);if(dl.test(s)){for(let i of s.matchAll(cl)){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(ul)){let a=i[1]?.toLowerCase();!a||n.has(a)||t.add(`name:${a}`)}}}return t.size}function Yr(e,t){if(typeof e=="number"&&Number.isFinite(e)&&e>=1)return Math.min(Math.round(e),100);let n=vt(t);return n>=3?Math.min(Math.max(ye,20+n*15),100):ae(t??[])?Math.min(Math.max(ye,Wr),100):Vr(t)?Math.min(Math.max(ye,Gr),100):ye}function Zr(e){return e.filter(t=>t.role!=="assistant"?!0:!(typeof t.content=="string"&&t.content.trim()===""))}function zn(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
10
|
|
|
11
|
-
`)):""}function
|
|
11
|
+
`)):""}function Hn(e,t){let n=_t(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
12
|
|
|
13
13
|
\u6700\u540E\u4E00\u6B21\u5DE5\u5177\u9519\u8BEF\uFF1A
|
|
14
14
|
${n}
|
|
15
15
|
|
|
16
16
|
\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
17
|
|
|
18
|
-
\u8BF7\u91CD\u8BD5\uFF0C\u6216\u6362\u4E00\u79CD\u5B9E\u73B0\u65B9\u5F0F\u3002`}function
|
|
18
|
+
\u8BF7\u91CD\u8BD5\uFF0C\u6216\u6362\u4E00\u79CD\u5B9E\u73B0\u65B9\u5F0F\u3002`}function Jr(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=Gn(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
19
|
|
|
20
20
|
`+(o?`\u6700\u540E\u4E00\u6B21\u8C03\u7528\uFF1A${o}
|
|
21
21
|
`:"")+`\u6700\u540E\u4E00\u6B21\u9519\u8BEF\uFF1A
|
|
22
22
|
${t}
|
|
23
23
|
|
|
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
|
|
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+${
|
|
26
|
-
`).replace(/\\/g,"/").toLowerCase()}function
|
|
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 Gn(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 Wn(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 Vn(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 Qr(e){return e==="length"||e==="max_tokens"}function Xn(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 es(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 ts(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*ns(e){let{messages:t,contentReplacementState:n,snipRemovedIds:o,collapseStore:r,guardConfig:s,runtimePorts:i,hooks:a,hookCtx:u,sessionId:f,currentModel:h,log:T,recovery:R,onAutocompact:_}=e,A;{let w=await i.enforceToolResultBudget(t,n,f);A=w.messages,w.newlyReplacedCount>0&&(T.info(`tool-result-budget: persisted ${w.newlyReplacedCount} oversized tool results`),yield R("tool_result_budget",`${w.newlyReplacedCount} persisted`))}{let w=dn(A,o);A=w.messages,w.removedCount>0&&(T.info(`snip: removed ${w.removedCount} messages, freed ~${w.tokensFreed} tokens`),yield R("snip",`${w.removedCount} messages`))}{let P=new Ze().compress(A,0);P.droppedCount>0&&(A=P.messages,T.info(`microcompact: cleared ${P.droppedCount} old tool results`))}if(A=pn(A,r).messages,s.contextWindowTokens>0){let w=s.contextWindowTokens*.75,P=i.getActiveContextCompressionEngine(),S;P?S=await P.compressAsync(A,w,{model:h,sessionId:f}):S=i.compressMessages(A,{budget:w,model:h}),S.droppedCount>0&&(A=S.messages,T.info(`autocompact: ${S.strategy}, dropped ${S.droppedCount}`),yield R("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},T))}return A=Zr(A),A}async function*os(e,t){let{state:n,guardState:o,fallbackModel:r,signal:s,querySource:i,turnId:a,log:u,emitRecovery:f}=t;if(e instanceof Je&&r)return u.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),T=typeof e?.status=="number"?e.status:void 0;if(!T&&h&&(h.includes("ECONNRESET")||h.includes("EPIPE"))){let _=(n.consecutiveApiRetries??0)+1;return _>Ae?(u.info(`stale connection retry limit reached (${Ae}), aborting`),yield{type:"error",turnId:a,error:h,code:"RETRIES_EXHAUSTED",usage:n.totalUsage},{kind:"return"}):(u.info(`stale connection (${h.includes("ECONNRESET")?"ECONNRESET":"EPIPE"}): retrying`),yield f("stale_connection_retry",h.slice(0,80)),{kind:"continue",patch:{consecutiveApiRetries:_,transition:void 0}})}let R=ts({status:T,message:h});if(R!==null)return u.info(`max_tokens overflow: adjusting to ${R}`),o.currentMaxOutputTokens=R,{kind:"continue",patch:{maxOutputTokensOverride:R,transition:void 0}};if(_n(T)){n.consecutive529Errors++;let _=2,A=r&&n.currentModel!==r;if(n.consecutive529Errors>_&&!A&&!Rt())return u.info(`transient ${T} \u8133 ${n.consecutive529Errors}: hard limit reached, aborting`),yield{type:"error",turnId:a,error:`API unavailable after ${n.consecutive529Errors} consecutive ${T} errors`,code:"API_ERROR",usage:n.totalUsage},{kind:"return"};if(n.consecutive529Errors>=mr&&r&&n.currentModel!==r)return u.info(`529 \u8133 ${n.consecutive529Errors}: triggering fallback to ${r}`),yield f("model_fallback",`529 \u8133 ${n.consecutive529Errors}`),{kind:"continue",patch:{currentModel:r,consecutive529Errors:0,transition:void 0}};if(Rt()){let w=kt(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 (${T})`};let S=Math.min(P,pr);await new Promise(O=>setTimeout(O,S)),P-=S}return{kind:"continue",patch:{transition:void 0}}}if(xn(i)){let P=es({status:T,message:h})??kt(n.consecutive529Errors);return u.info(`transient ${T}: retry in ${P}ms`),yield f("retry",`${T} retry in ${P}ms`),await new Promise(S=>setTimeout(S,P)),{kind:"continue",patch:{transition:void 0}}}u.info(`background source ${i}: not retrying ${T}`)}return{kind:"streamError",streamError:{status:T,message:h}}}import{readdirSync as ls,statSync as et}from"node:fs";var gl=/create\s+(?:a\s+)?file|write\s+(?:a\s+)?file|make\s+(?:a\s+)?file|\bfix\b|implement|modify|update|repair|generate\s+(?:a\s+)?file|new\s+file/i,cs=/[A-Za-z]:[\\/](?:[^\s"'`<>|,\uFF0C\u3001;\uFF1B\u3002]+[\\/])*[^\s"'`<>|,\uFF0C\u3001;\uFF1B\u3002]+\.[A-Za-z0-9]{1,12}/g,rs=/\s*[,\uFF0C\u3001;\uFF1B]\s*([^\s"'`<>|,\uFF0C\u3001;\uFF1B\u3002\\/]+\.[A-Za-z0-9]{1,12})/gy,hl=/\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,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=/(?:^|[\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,Tl=/(?:^|[\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,Cl=/\b(?:create|generate|write|produce|save|output|deliver|deliverables?|artifacts?|required|required files?|must generate|self-verify)\b|(?:生成|创建|写入|输出|保存|交付|产物|文件|必须|自检|验证)/i,kl=/\bpreviews?[\\/]\s*(?:containing|with|under|for)?[^.。;;\n]*(?:rendered|preview|previews|check|evidence|verify|verification)\b/i,Rl=/(?: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 us(e){return e.trim().replace(/[),.;:\uFF0C\u3002\uFF1B\u3001]+$/u,"").replace(/\\/g,"/").replace(/\/+$/u,"")}function ss(e){return/\.[A-Za-z0-9]{1,12}$/u.test(e.replace(/[),.;:\uFF0C\u3002\uFF1B\u3001]+$/u,""))}function is(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+${ms(n)}\\b`,"i").test(s)}function Kn(e){return e.replace(/https?:\/\/\S+/gu," ")}function Yn(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=Kn(r.content);for(let i of s.matchAll(cs)){let a=i[0],u=(i.index??0)+a.length;if(s[u]==="/"||s[u]==="\\")continue;o(a);let f=a.replace(/\\/g,"/"),h=f.lastIndexOf("/");if(h>=0){let T=f.slice(0,h+1);rs.lastIndex=u;let R;for(;(R=rs.exec(s))!==null;)o(`${T}${R[1]}`)}}}for(let r of e){if(r.role!=="user"||typeof r.content!="string")continue;let s=Kn(r.content);if(!Cl.test(s))continue;let i=Array.from(s.matchAll(hl)).map(u=>us(u[1]??"")).filter(u=>u&&!ss(u));if(i.length===0)continue;let a=i[i.length-1];for(let u of s.matchAll(yl)){let f=u[1];f&&(is(s,u.index??0,f)||o(`${a}/${f}`))}for(let u of s.matchAll(bl)){let f=u[1];f&&(is(s,u.index??0,f)||o(`${a}/${f}`))}for(let u of s.matchAll(Tl)){let f=u[1];f&&(ss(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}/*`))}kl.test(s)&&o(`${a}/previews/*`)}return n}function At(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,f=u.id,h=u.function;typeof f=="string"&&typeof h?.name=="string"&&n.set(f,h.name)}}for(let r of e){let s=r;if(At(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,f=u.id;if(typeof f=="string"&&t.size>0&&!t.has(f))continue;let h=u.function;if(!(typeof h?.name!="string"||typeof h.arguments!="string"))try{let T=JSON.parse(h.arguments);if(h.name==="write"||h.name==="edit"){for(let R of["path","filePath","file_path"]){let _=T[R];typeof _=="string"&&o.push(_)}continue}if(h.name==="exec"){let R=T.command;typeof R=="string"&&o.push(R)}}catch{h.name==="exec"&&o.push(h.arguments)}}}return o.join(`
|
|
26
|
+
`).replace(/\\/g,"/").toLowerCase()}function Jn(e){try{if(e.endsWith("/*")){let n=e.slice(0,-2);return ls(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 xl(e,t){let n=K(t);if(!n.endsWith("/*"))return e.includes(n);let o=n.slice(0,-1);return e.includes(o)}function _l(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)&&At(o))return!0}return!1}function vl(e){let t=ps(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 wl(e){let t=us(e),n=t.lastIndexOf("/");return n>=0?t.slice(0,n):""}function Al(e){if(e.length===0)return"";let t=e.map(o=>wl(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 Sl(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 ds(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,f=a.function;if(typeof u!="string"||f?.name!=="write"&&f?.name!=="edit"||typeof f.arguments!="string")continue;let h=St(f.arguments);if(!h)continue;let T=Mt(h);T&&n.set(u,T)}}for(let o of e){let r=o;if(!At(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 Ml(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 El(e){return[...new Set([...e.matchAll(/\bGoal\s+\d+\b/gi)].map(t=>t[0].replace(/\s+/g," ").replace(/\bgoal\b/i,"Goal")))]}function Il(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,f=a.function;if(typeof u!="string"||f?.name!=="write"&&f?.name!=="edit"||typeof f.arguments!="string")continue;let h=St(f.arguments);if(!h)continue;let T=Mt(h)??"",R=gs(h);(/\bartifact[-_\s]?index\b/i.test(T)||/\bartifact[-_\s]?index\b/i.test(R))&&n.set(u,R)}}for(let o of e){let r=o;if(!At(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 Pl(e){let t=ps(e.inputMessages);if(!Ml(t))return[];let n=Il(e.messages).at(-1);if(!n)return[];let o=[],r=El(t).filter(u=>!new RegExp(`\\b${ms(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 Ol(e){let t=[],n=o=>{let r;try{r=ls(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 Nl(e,t){if(!vl(e))return[];let n=Yn(e),o=n.filter(i=>!K(i).endsWith("/*"));if(o.length<2)return[];let r=Al(o);if(!r||r.split("/").length<3)return[];let s=K(r);return[...new Set([...ds(t),...Ol(r)])].filter(i=>K(i).startsWith(`${s}/`)&&!Sl(i,n)&&Jn(i))}function fs(e,t){let n=Yn(e);if(n.length===0)return[];let o=Zn(t);return n.filter(r=>!xl(o,r))}function Qe(e){return Qn(e).fail}function Ll(e){return e.replace(/[.,;:,。;:、!?]+$/u,"")}function wt(e){if(!e)return!1;let t=Ll(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))wt(s[2])&&(n=`${s[1].toUpperCase()} ${t(s[2])}`);for(let s of r.content.matchAll(/\bFAIL\s+([A-Za-z0-9_.:-]+)/gi))wt(s[1])&&(o=`FAIL ${t(s[1])}`);for(let s of r.content.matchAll(/\b([A-Za-z0-9_.:-]+)\s+(DONE|PASS)\b/gi))wt(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))wt(s[1])&&(o=`${t(s[1])} FAIL`)}return{done:n,fail:o}}function ps(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 ms(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ie(e){let t=fs(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 St(e){try{let t=JSON.parse(e);return t&&typeof t=="object"&&!Array.isArray(t)?t:null}catch{return null}}function Mt(e){for(let t of["path","filePath","file_path"]){let n=e[t];if(typeof n=="string"&&n.trim())return n}}function gs(e){for(let t of["content","newContent","replacement","text"]){let n=e[t];if(typeof n=="string")return n}return""}function hs(e){let t=e.toolCall.function.name;if(t!=="write"&&t!=="edit")return;let n=Qn(e.inputMessages);if(!n.done)return;let o=St(e.toolCall.function.arguments);if(!o)return;let r=Mt(o),s=gs(o);if(!r||!s.includes(n.done))return;let i=Yn(e.inputMessages);if(i.length<2)return;let a=K(r);if(!i.some(T=>K(T)===a))return;let f=Zn(e.messages),h=i.filter(T=>K(T)!==a).filter(T=>!f.includes(K(T)));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 Me(e,t){return{role:"assistant",content:e,...t.length>0&&{thinkingBlocks:[...t]}}}function Fl(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 Bl(e){let t=[...e].reverse().find(n=>n.role==="tool");t&&typeof t.content=="string"&&(t.content+=`
|
|
27
27
|
|
|
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 Se(e,t,n,o){return{reason:e,messages:[...t,n,o],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}}}function cs(e){try{return Ze(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=Vn(s.content);if(ul.test(i))for(let a of i.matchAll(ts)){let u=a[0].replace(/[),.;:,。;]+$/u,""),f=X(u);f&&n.set(f,u)}}if(n.size===0)return[];let o=Kn(t),r=[];for(let[s,i]of n)(o.includes(s)||cs(i))&&r.push(s);return r}var Al="File not found:",Qr=/\b(?:create|write|make|generate|produce|save|output|deliver|initialize|init|ensure|touch|scaffold|build|set\s+up)\b|生成|创建|写入|写出|新建|建立|保存|输出|交付|初始化|确保/i,Sl=/\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 Ml(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 f=s.indexOf(a,u);if(f===-1)break;u=f+1;let h=f;for(;h>0&&!o.test(s[h-1]);)h--;let T=f+a.length;for(;T<s.length&&!o.test(s[T]);)T++;let R=r.content.slice(h,T);if(Qr.test(R))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))&&Qr.test(r.content)&&Sl.test(r.content))return!0}return!1}function El(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,f=a.function;if(typeof u!="string"||f?.name!=="read"||typeof f.arguments!="string")continue;let h=_t(f.arguments),T=h?wt(h):void 0;T&&t.set(u,T)}}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(Al)&&n.set(X(i),i)}return n}function Il(e,t){let n=El(t);if(n.size===0)return[];let o=new Set(os(t).map(X)),r=[];for(let[s,i]of n)Ml(e,s)||(o.has(s)||cs(i))&&r.push(s);return r}function Jn(e){let t=e.inputMessages.find(x=>x.role==="user"),n=typeof t?.content=="string"?t.content:"",o=ol.test(n),r=e.distinctToolNames.has("write")||e.distinctToolNames.has("edit"),s=Zn(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=Ye(e.inputMessages),w={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 Se("forbidden_file_creation",e.messages,Ae(e.finalText,e.thinkingBlocks),w)}let a=Il(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 x=Ye(e.inputMessages),w={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 Se("self_created_read_target",e.messages,Ae(e.finalText,e.thinkingBlocks),w)}let f=fl(e.messages),h=rs(e.inputMessages,e.messages).filter(x=>!(f&&Yn(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=Ye(e.inputMessages),w={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 Se("explicit_required_file_verification",e.messages,Ae(e.finalText,e.thinkingBlocks),w)}let T=Rl(e.inputMessages,e.messages);if(T.length>0&&e.totalToolCallCount>0){if(s.fail!==void 0&&e.finalText.includes(s.fail))return null;e.log.info(`explicit extra file verification: ${T.length} unexpected file(s)`);let x=Ye(e.inputMessages),w={role:"user",content:`The latest request asked for exactly the listed output artifacts, but extra files were produced under the output root: ${T.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 Se("explicit_extra_file_verification",e.messages,Ae(e.finalText,e.thinkingBlocks),w)}let R=Cl({inputMessages:e.inputMessages,messages:e.messages,finalText:e.finalText});if(R.length>0&&e.totalToolCallCount>0){if(s.fail!==void 0&&e.finalText.includes(s.fail))return null;e.log.info(`artifact index evidence verification: ${R.length} issue(s)`);let x={role:"user",content:"Before completing, correct the artifact index against the actual evidence scope. "+R.map(w=>w.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 Se("artifact_index_evidence_verification",e.messages,Ae(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&&_l(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 Se("file_action_verification",e.messages,Ae(e.finalText,e.thinkingBlocks),x)}if(e.totalToolCallCount>=3&&e.distinctToolNames.has("write")&&e.messages.filter(vl).length>=3){e.log.info("AP3 verification nudge: 3+ files created, injecting completeness check");let w={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 Se("multi_file_skeleton_verification",e.messages,Ae(e.finalText,e.thinkingBlocks),w)}return null}function Pl(e,t){return{role:"assistant",content:e,...t.length>0&&{thinkingBlocks:[...t]}}}async function us(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,Pl(e.finalText,e.thinkingBlocks),o],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}}}return null}var Ol=5;function Ll(e){return e.inputTokens+e.outputTokens+(e.reasoningTokens??0)}function Nl(e,t){return{role:"assistant",content:e,...t.length>0&&{thinkingBlocks:[...t]}}}function ds(e){if(!e.tokenBudget||e.tokenBudget<=0||e.budgetContinuationCount>=Ol)return null;let t=Ll(e.totalUsage),n=t/e.tokenBudget*100,o=t-e.lastBudgetGlobalTokens;if(e.budgetContinuationCount>=rr&&o<pn&&e.lastBudgetDeltaTokens<pn)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,Nl(e.finalText,e.thinkingBlocks),i],budgetContinuationCount:s,lastBudgetDeltaTokens:o,lastBudgetGlobalTokens:t,recoveryDetail:`${Math.round(n)}% used (#${s})`,transition:{reason:"token_budget_continuation"}}}function Qn(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 mn(t,{tools:[...e.distinctToolNames],projectRoot:e.projectRoot})}var Je="*";function fs(e,t){let n=[],o=[];for(let r of e){let s=hs(r.function.name,r.function.arguments),i=ys(r.function.name,Je),a=Math.max(t.get(s)??0,t.get(i)??0);a>=gt?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 ps(){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 ms(e){if(e.ok&&!e.softEmpty)return;let t=hs(e.toolName,e.toolArguments),n=e.toolFailureCounts.get(t)??0;e.toolFailureCounts.set(t,n+1)}function gs(e){let t=[];for(let[n,o]of e.toolFailureCounts)if(o>=gt&&(e.snapshot.get(n)??0)<gt){let{toolName:r,target:s}=Dl(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 hs(e,t){return ys(e,Fl(e,t))}function Fl(e,t){let n=Bl(t);return e==="read"||e==="write"||e==="edit"||e==="patch"?eo(n?.path??n?.file_path??n?.filePath):e==="search"?eo([n?.mode,n?.path,n?.fileGlob,n?.pattern].filter(Boolean).join("|")):e==="exec"?eo(n?.command):Je}function Bl(e){if(e)try{let t=JSON.parse(e);return t&&typeof t=="object"&&!Array.isArray(t)?t:void 0}catch{return}}function eo(e){return typeof e=="string"&&e.trim()?e.trim().replaceAll("\\","/").toLowerCase():Je}function ys(e,t){return`${e}::${t}`}function Dl(e){let t=e.indexOf("::");return t<0?{toolName:e,target:Je}:{toolName:e.slice(0,t),target:e.slice(t+2)||Je}}var $l=new Set(["find","grep","rg","ag","ack","locate","which","whereis"]),Ul=new Set(["cat","head","tail","less","more","wc","stat","file","sed","strings","jq","awk","cut","sort","uniq","tr"]),jl=new Set(["ls","tree","du","dir","gci","get-childitem"]),ql=new Set(["grep","rg","ag","ack","find"]);var zl=new Set(["mv","cp","rm","mkdir","rmdir","chmod","chown","chgrp","touch","ln","cd","export","unset","wait"]);function Hl(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 Gl(e){return/(?:^|[;&|])\s*(?:cd|pushd|popd)\b/.test(e)}function bs(e){let t=Hl(e),n=t!==null&&$l.has(t),o=t!==null&&Ul.has(t),r=t!==null&&jl.has(t),s=t!==null&&zl.has(t),i=/(?:[^2]>|^>|\|>)/.test(e),a=Gl(e),u=(n||o||r)&&!i&&!a;return{firstCommand:t,isSearch:n,isRead:o,isList:r,isSilent:s,isConcurrencySafe:u,isReadOnly:u}}function Ts(e){return e.isRead?!0:e.firstCommand!==null&&ql.has(e.firstCommand)}function Cs(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 Xl(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 Kl(e,t){let n=Yl(t);if(!n)return null;let o=Zl(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 Yl(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 Zl(e){return e.toLocaleLowerCase().replace(/[^\p{L}\p{N}\s]+/gu," ").replace(/\s+/g," ").trim()}function k(e){return[...new Set(e.map(t=>t.function.name))].sort()}function Mt(e){return[...e].sort((t,n)=>t.function.name.localeCompare(n.function.name))}function At(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 Jl(e,t,n,o,r){let s=r.filter(i=>i.name===e).sort((i,a)=>ks(i.reason)-ks(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 ks(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 Ql(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 Rs(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 ye(e,t){return t.size===0?[...e]:e.filter(n=>!t.has(n.function.name))}var ec=new Set(["edit","patch","read"]);function xs(e,t){let n=e.filter(o=>ec.has(o.function.name)&&!t.has(o.function.name));return n.length>0?Mt(n):e.filter(o=>o.function.name!=="write"&&!t.has(o.function.name))}function to(e,t){let n=new Set(t);return e.filter(o=>!n.has(o))}function tc(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 vs(e){let n=de(e)?.command;return typeof n=="string"&&n.trim()?n:void 0}var It=5174;function _s(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 nc(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 Ps(e){return/(?:^|\s)--strictPort(?:\s|$)/.test(e)}function oc(e){if(Ps(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 ws(e,t){let n=de(e)??{};return JSON.stringify({...n,command:t})}function rc(e){let t=e.replace(/^(?:\s*sleep\s+\d+(?:\.\d+)?\s*(?:&&|;)\s*)+/i,"").trim();return t&&t!==e.trim()?t:null}function sc(e){return _s(e,It)?{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."}:nc(e)&&_s(e,It-1)&&!Ps(e)?{action:"rewrite",command:oc(e)}:null}function Pt(e){let t=[];for(let n of e.devServerUrls)if(!(!/^https?:\/\/(?:localhost|127\.0\.0\.1):\d+\b/i.test(n)||new RegExp(`:${It}\\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 As(e){let t=Pt(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 ic(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:
|
|
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 Ee(e,t,n,o){return{reason:e,messages:[...t,n,o],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}}}function ys(e){try{return et(e).isFile()}catch{return!1}}function Dl(e,t){let n=new Map;for(let s of e){if(s.role!=="user"||typeof s.content!="string")continue;let i=Kn(s.content);if(Rl.test(i))for(let a of i.matchAll(cs)){let u=a[0].replace(/[),.;:,。;]+$/u,""),f=K(u);f&&n.set(f,u)}}if(n.size===0)return[];let o=Zn(t),r=[];for(let[s,i]of n)(o.includes(s)||ys(i))&&r.push(s);return r}var $l="File not found:",as=/\b(?:create|write|make|generate|produce|save|output|deliver|initialize|init|ensure|touch|scaffold|build|set\s+up)\b|生成|创建|写入|写出|新建|建立|保存|输出|交付|初始化|确保/i,Ul=/\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 jl(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 f=s.indexOf(a,u);if(f===-1)break;u=f+1;let h=f;for(;h>0&&!o.test(s[h-1]);)h--;let T=f+a.length;for(;T<s.length&&!o.test(s[T]);)T++;let R=r.content.slice(h,T);if(as.test(R))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))&&as.test(r.content)&&Ul.test(r.content))return!0}return!1}function ql(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,f=a.function;if(typeof u!="string"||f?.name!=="read"||typeof f.arguments!="string")continue;let h=St(f.arguments),T=h?Mt(h):void 0;T&&t.set(u,T)}}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($l)&&n.set(K(i),i)}return n}function zl(e,t){let n=ql(t);if(n.size===0)return[];let o=new Set(ds(t).map(K)),r=[];for(let[s,i]of n)jl(e,s)||(o.has(s)||ys(i))&&r.push(s);return r}function eo(e){let t=e.inputMessages.find(_=>_.role==="user"),n=typeof t?.content=="string"?t.content:"",o=gl.test(n),r=e.distinctToolNames.has("write")||e.distinctToolNames.has("edit"),s=Qn(e.inputMessages),i=Dl(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 Ee("forbidden_file_creation",e.messages,Me(e.finalText,e.thinkingBlocks),A)}let a=zl(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 Ee("self_created_read_target",e.messages,Me(e.finalText,e.thinkingBlocks),A)}let f=_l(e.messages),h=fs(e.inputMessages,e.messages).filter(_=>!(f&&Jn(_)));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 _=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: ${h.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 Ee("explicit_required_file_verification",e.messages,Me(e.finalText,e.thinkingBlocks),A)}let T=Nl(e.inputMessages,e.messages);if(T.length>0&&e.totalToolCallCount>0){if(s.fail!==void 0&&e.finalText.includes(s.fail))return null;e.log.info(`explicit extra file verification: ${T.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: ${T.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 Ee("explicit_extra_file_verification",e.messages,Me(e.finalText,e.thinkingBlocks),A)}let R=Pl({inputMessages:e.inputMessages,messages:e.messages,finalText:e.finalText});if(R.length>0&&e.totalToolCallCount>0){if(s.fail!==void 0&&e.finalText.includes(s.fail))return null;e.log.info(`artifact index evidence verification: ${R.length} issue(s)`);let _={role:"user",content:"Before completing, correct the artifact index against the actual evidence scope. "+R.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 Ee("artifact_index_evidence_verification",e.messages,Me(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&&Bl(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 Ee("file_action_verification",e.messages,Me(e.finalText,e.thinkingBlocks),_)}if(e.totalToolCallCount>=3&&e.distinctToolNames.has("write")&&e.messages.filter(Fl).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 Ee("multi_file_skeleton_verification",e.messages,Me(e.finalText,e.thinkingBlocks),A)}return null}function Hl(e,t){return{role:"assistant",content:e,...t.length>0&&{thinkingBlocks:[...t]}}}async function bs(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,Hl(e.finalText,e.thinkingBlocks),o],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}}}return null}var Gl=5;function Wl(e){return e.inputTokens+e.outputTokens+(e.reasoningTokens??0)}function Vl(e,t){return{role:"assistant",content:e,...t.length>0&&{thinkingBlocks:[...t]}}}function Ts(e){if(!e.tokenBudget||e.tokenBudget<=0||e.budgetContinuationCount>=Gl)return null;let t=Wl(e.totalUsage),n=t/e.tokenBudget*100,o=t-e.lastBudgetGlobalTokens;if(e.budgetContinuationCount>=fr&&o<gn&&e.lastBudgetDeltaTokens<gn)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,Vl(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 hn(t,{tools:[...e.distinctToolNames],projectRoot:e.projectRoot})}function Cs(e){let t=Xl(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(Kl(t,o)||Yl(t,o))return{toolName:o};return null}function Xl(e){return e.replace(/```[\s\S]*?```/g,"")}function Kl(e,t){let n=ks(t);return new RegExp(`<\\s*${n}\\b[\\s\\S]*?<\\s*\\/\\s*${n}\\s*>`,"i").test(e)}function Yl(e,t){let n=ks(t);return new RegExp(`\\b(?:call|use|invoke|run)\\s+${n}\\s*\\(|\\b${n}\\s*\\(`,"i").test(e)}function ks(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var tt="*";function Rs(e,t){let n=[],o=[];for(let r of e){let s=ws(r.function.name,r.function.arguments),i=As(r.function.name,tt),a=Math.max(t.get(s)??0,t.get(i)??0);a>=yt?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 xs(){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 _s(e){if(e.ok&&!e.softEmpty)return;let t=ws(e.toolName,e.toolArguments),n=e.toolFailureCounts.get(t)??0;e.toolFailureCounts.set(t,n+1)}function vs(e){let t=[];for(let[n,o]of e.toolFailureCounts)if(o>=yt&&(e.snapshot.get(n)??0)<yt){let{toolName:r,target:s}=Ql(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 ws(e,t){return As(e,Zl(e,t))}function Zl(e,t){let n=Jl(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 Jl(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 As(e,t){return`${e}::${t}`}function Ql(e){let t=e.indexOf("::");return t<0?{toolName:e,target:tt}:{toolName:e.slice(0,t),target:e.slice(t+2)||tt}}var ec=new Set(["find","grep","rg","ag","ack","locate","which","whereis"]),tc=new Set(["cat","head","tail","less","more","wc","stat","file","sed","strings","jq","awk","cut","sort","uniq","tr"]),nc=new Set(["ls","tree","du","dir","gci","get-childitem"]),oc=new Set(["grep","rg","ag","ack","find"]);var rc=new Set(["mv","cp","rm","mkdir","rmdir","chmod","chown","chgrp","touch","ln","cd","export","unset","wait"]);function sc(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 ic(e){return/(?:^|[;&|])\s*(?:cd|pushd|popd)\b/.test(e)}function Ss(e){let t=sc(e),n=t!==null&&ec.has(t),o=t!==null&&tc.has(t),r=t!==null&&nc.has(t),s=t!==null&&rc.has(t),i=/(?:[^2]>|^>|\|>)/.test(e),a=ic(e),u=(n||o||r)&&!i&&!a;return{firstCommand:t,isSearch:n,isRead:o,isList:r,isSilent:s,isConcurrencySafe:u,isReadOnly:u}}function Ms(e){return e.isRead?!0:e.firstCommand!==null&&oc.has(e.firstCommand)}function Es(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 cc(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 uc(e,t){let n=dc(t);if(!n)return null;let o=fc(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 dc(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 fc(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,pc=/(?: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,mc=/(?:\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,gc=/(?: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,hc=/\b([A-Z0-9_]*MCP_GRAPH_CHECK[A-Z0-9_]*_20260626)\b/;function zs(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 Hs(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,f=typeof u?.name=="string"?u.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 yc(e,t){let n=zs(e),o=Hs(t,"read");if(!o||o.length>4e3)return null;let r=bc(n,o);return r||(qs.test(n)?o:null)}function bc(e,t){let n=pc.exec(e)?.[1];if(!n)return null;let o=mc.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 Tc(e,t){let n=zs(e),o=gc.exec(n)?.[1],r=hc.exec(n)?.[1];if(!o||!r)return null;let s=Hs(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 Et(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 Cc(e,t,n,o,r){let s=r.filter(i=>i.name===e).sort((i,a)=>Is(i.reason)-Is(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 Is(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 kc(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 Ps(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 Rc=new Set(["edit","patch","read"]);function Os(e,t){let n=e.filter(o=>Rc.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 xc(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 Ns(e){let n=fe(e)?.command;return typeof n=="string"&&n.trim()?n:void 0}var Ot=5174;function Ls(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 _c(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 Gs(e){return/(?:^|\s)--strictPort(?:\s|$)/.test(e)}function vc(e){if(Gs(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 Fs(e,t){let n=fe(e)??{};return JSON.stringify({...n,command:t})}function wc(e){let t=e.replace(/^(?:\s*sleep\s+\d+(?:\.\d+)?\s*(?:&&|;)\s*)+/i,"").trim();return t&&t!==e.trim()?t:null}function Ac(e){return Ls(e,Ot)?{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."}:_c(e)&&Ls(e,Ot-1)&&!Gs(e)?{action:"rewrite",command:vc(e)}:null}function Nt(e){let t=[];for(let n of e.devServerUrls)if(!(!/^https?:\/\/(?:localhost|127\.0\.0\.1):\d+\b/i.test(n)||new RegExp(`:${Ot}\\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 Bs(e){let t=Nt(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 Sc(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
29
|
${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
|
|
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 Ws(e){let n=fe(e)?.command;return typeof n=="string"&&n.trim()?n.trim():null}var Mc=4;function Ec(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=Ws(t);return n?`exec:${n.replace(/\s+/g," ")}`:null}return null}function Ds(e){let t=Ws(e);return t?/\b(?:npx\s+)?playwright\s+install(?:\s+--with-deps)?\s+chromium\b/i.test(t):!1}function Ic(e){let t=Nt(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 Pc(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 Oc(e){let t=new Set(["completed","blocked","cancelled","canceled","failed"]);return e.some(n=>!t.has(n.status.toLowerCase()))}function Nc(e){return e?Es(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 $s(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=>Cc(s,t.availableToolNames,t.enabledToolNames,t.toolCallNames,t.blockedToolCalls)).join(", ");return`${e}
|
|
31
31
|
|
|
32
32
|
Tool availability diagnostics:
|
|
33
33
|
availableToolNames: ${t.availableToolNames.join(", ")}
|
|
34
34
|
enabledToolNames: ${t.enabledToolNames.join(", ")}
|
|
35
35
|
toolCallNames: ${t.toolCallNames.join(", ")||"none"}
|
|
36
36
|
blockedToolCalls: ${n}
|
|
37
|
-
attribution: ${r}`}function
|
|
38
|
-
`),i=
|
|
37
|
+
attribution: ${r}`}function de(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function Lc(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.${Fc(e.function.name)}`}return null}function Fc(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 Pe(e,t){if(!e||typeof e!="object")return;let n=e[t];return typeof n=="string"?n:void 0}function Pt(e,t){if(!e||typeof e!="object")return;let n=e[t];return typeof n=="boolean"?n:void 0}function Bc(e,t){if(!e||typeof e!="object")return;let n=e[t];return typeof n=="number"&&Number.isFinite(n)?n:void 0}function Dc(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 $c(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 Uc(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"&&Ce(t).has(o)}function jc(e,t){if(e.toolName!=="task")return!1;let n=Pe(e.details,"taskId");return!n||!Ce(t).has(n)?!1:Pe(e.details,"action")==="output"&&Pt(e.details,"running")===!0}var qc=180,zc=40;function Hc(e){return/\(no output yet\)|\bno output yet\b/i.test(e)}function Gc(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 Wc(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"]),Vc=new Set(["write","edit","patch","image_generate"]),Xc=18e4,Kc=3,nt=1,Yc=1,Zc=1,Jc=4,Qc=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"]),Vs=[{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"]),eu=new Set(["read","search","exec"]);function Xs(e){let t=G(e),n=ke(t);return t.split("/").includes("context-pack")&&J.has(n)?nt:t.split("/").includes("benchmark-state")&&uo.has(n)?Zc:t.includes("/qlogicagent-sessions/")&&t.includes("/tool-results/")?Yc:Kc}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(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 fo(e){let t=G(e);return t.split("/").includes("context-pack")&&J.has(ke(t))}function Ks(e){let t=G(e),o=t.indexOf("/context-pack/");return o<0?null:t.slice(0,o)}function tu(e){let t=[...e].filter(fo).map(Ks).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 Oe(o)}catch{return!1}})}function Ys(e){return[...J.keys()].every(t=>e.has(t))}function po(e){for(let t of e.values()){if(!t.path)continue;let n=Ks(t.path);if(n)return`${n}/benchmark-state`}return null}function Zs(e){if(!Ys(e))return[];let t=po(e);return t?[...uo].map(n=>`${t}/${n}`).filter(n=>{try{return!Oe(n)}catch{return!0}}):[]}function nu(e,t){let n=Zs(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=Vs.map(a=>`${a.id}: ${a.decision}`).join(`
|
|
39
39
|
`);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 Es(e){return ro.has(e)}function Nc(e){return e.benchmarkStateMaintenanceRequiredFiles.size>0&&[...e.benchmarkStateMaintenanceRequiredFiles].every(t=>Fc(e,t))}function Fc(e,t){if(e.benchmarkStateMaintenanceWrittenFiles.has(t))return!0;try{if(!Ie(t))return!1;let n=Te(t);if(n!=="document-index.json"&&n!=="context-pack-evidence.json")return!0;let o=Nt(t,"utf8");return fo(e.maintainedDocuments,t,JSON.stringify({content:o})).ok}catch{return!1}}function fo(e,t,n){let o=Te(t);if(o!=="document-index.json"&&o!=="context-pack-evidence.json")return{ok:!0};let r=Jc(n);if(!r)return{ok:!1,reason:`${o} write did not include JSON content`};let s=de(r);if(!s)return{ok:!1,reason:`${o} content is not a JSON object`};if(o==="document-index.json"){let a=ue(s.documents);if(!a)return{ok:!1,reason:"document-index.json missing documents object"};for(let u of Z.keys()){let f=e.get(u),h=ue(a[u]);if(!f||!h)return{ok:!1,reason:`document-index.json missing ${u}`};if(h.contentHash!==f.contentHash)return{ok:!1,reason:`document-index.json ${u} contentHash does not match read.details`};if(h.fileSizeBytes!==f.fileSizeBytes)return{ok:!1,reason:`document-index.json ${u} fileSizeBytes does not match read.details`}}return{ok:!0}}let i=ue(s.fileVerification);if(!i)return{ok:!1,reason:"context-pack-evidence.json missing fileVerification object"};for(let a of Z.keys()){let u=e.get(a),f=ue(i[a]);if(!u||!f)return{ok:!1,reason:`context-pack-evidence.json missing ${a}`};if(f.contentHash!==u.contentHash)return{ok:!1,reason:`context-pack-evidence.json ${a} contentHash does not match read.details`};if(f.fileSizeBytes!==u.fileSizeBytes)return{ok:!1,reason:`context-pack-evidence.json ${a} fileSizeBytes does not match read.details`}}return{ok:!0}}function Bc(e){if(!Bs(e))return[];let t=uo(e);if(!t)return[];let n=[];for(let o of["document-index.json","context-pack-evidence.json"]){let r=`${t}/${o}`,s;try{if(!Ie(r))continue;s=Nt(r,"utf8")}catch{continue}let i=fo(e,r,JSON.stringify({content:s}));i.ok||n.push({path:r,reason:i.reason})}return n}function Dc(e,t,n,o){if(e.filter(a=>a.name==="read"&&a.reason==="read-cycle-policy").length<Ec)return!1;let s=new Set([...t].filter(co).map(Te));return[...Z.keys()].every(a=>s.has(a))?[...Z.keys()].every(a=>o.has(a))||n||Oc(t):!1}function $s(e,t,n){if(e!=="write"||!n.has("edit")&&!n.has("patch"))return null;let o=Lt(t);if(!o)return null;try{if(!Ie(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 Ot=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*$c(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 Ot(t);if(r.done)return;yield r.value}}finally{n.return?.().catch(()=>{})}}function so(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 Lt(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 Uc(e){return e.flatMap(t=>{if(jc(t.function.arguments))return[t];let n=qc(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 jc(e){try{let t=JSON.parse(e);return!!t&&typeof t=="object"&&!Array.isArray(t)}catch{return!1}}function qc(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 f=de(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 de(e){try{let t=JSON.parse(e);return t&&typeof t=="object"&&!Array.isArray(t)?t:null}catch{return null}}function H(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 Te(e){let t=e.trim().replace(/\\/g,"/");return t.slice(t.lastIndexOf("/")+1).toLowerCase()}function po(e){return`sha256:${Vl("sha256").update(e).digest("hex")}`}function zc(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 Hc(e){return Object.fromEntries([...e.entries()].sort(([t],[n])=>t.localeCompare(n)))}function Gc(e,t,n,o){let r=[...t.values()].sort((u,f)=>(u.name??"").localeCompare(f.name??""));if(r.length===0)return null;let s=r.map(u=>`${u.name??"document"}:${u.contentHash??"unknown"}`).join("|"),i=Ls.map(u=>({...u,evidence:`read:long-horizon-documents:${po(`${u.id}:${s}`)}`,lastConfirmedTurn:o})),a={strategy:"maintained-document-index",nextReadPolicy:"use maintained index before full document reread",budgetStatus:"within-budget",maxReadsPerDocument:Qe,observedReadsByPath:Hc(n)};return{type:"document_maintenance",turnId:e,checkpointId:`${e}-docs-${r.length}`,documents:r,decisionStateTable:i,readCycleFindings:[],readCycleGuard:a}}function Wc(e){let t=e.find(o=>o.path)?.path??"",n=t.lastIndexOf("/");return n>0?t.slice(0,n):t}function St(e,t){return e.get(t)??null}function Vc(e){let t=St(e,"requirements.md"),n=St(e,"decisions.md"),o=St(e,"defects.md"),r=St(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:Wc(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 Xc(e,t){let n=Vc(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 Kc(e,t,n,o,r){let s=io(t,n,o,r);if(!s)return!1;let i=s.name;return i?(e.maintainedDocuments.set(i,s),!0):!1}function io(e,t,n,o){let r=Te(e);if(!Z.has(r))return null;let s=eu(t)??t,i=Qc(o,"contentHash"),a=De(o??null,"fileSizeBytes"),u=i??po(s);return{name:r,path:H(e),indexed:!0,maintained:!0,indexVersion:u,contentHash:u,summary:zc(r,s),lastReviewedTurn:n,fileSizeBytes:a??Buffer.byteLength(s,"utf8"),recordCount:Us(s)}}function Yc(e,t){return $s(e.function.name,e.function.arguments,t)!==null}function Zc(e,t){let n=Lt(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 Jc(e){let n=de(e)?.content;return typeof n=="string"?n:void 0}function Qc(e,t){let n=e?.[t];return typeof n=="string"&&n.trim()?n.trim():void 0}function Us(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 Ie(n)?Nt(n,"utf8"):null}catch{return null}}function tu(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=so(i.function.arguments);if(!a)continue;let u=H(a);Ns(u)===Qe&&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=io(i.path,a,0);u?.name&&o.set(u.name,u)}for(let s of iu(e)){r=!0;for(let i of Z.keys()){let a=H(`${s}/${i}`);if(n.set(a,Math.max(n.get(a)??0,Qe)),!o.has(i)){let u=io(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 nu(e)){r=!0;for(let i of s.documents)!i.name||!i.path||(n.set(i.path,Math.max(n.get(i.path)??0,Qe)),o.set(i.name,i))}return{fileReadCounts:n,maintainedDocuments:o,persistedBenchmarkStateRecovered:r}}function nu(e){let t=[];for(let n of ou(e)){let o=Is(`${n}/document-index.json`),r=Is(`${n}/context-pack-evidence.json`),s=$e(o,"contextPackPath")??ru(r);if(!s)continue;let i=su(s,o,r);i.length===Z.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=H(s[1]??"");i&&t.add(i)}}return[...t]}function Is(e){try{if(!Ie(e))return null;let t=JSON.parse(Nt(e,"utf8"));return t&&typeof t=="object"&&!Array.isArray(t)?t:null}catch{return null}}function $e(e,t){let n=e?.[t];return typeof n=="string"&&n.trim()?H(n):void 0}function ru(e){let t=e?.fileVerification;if(!(!t||typeof t!="object"||Array.isArray(t)))for(let n of Z.keys()){let o=t[n];if(!o||typeof o!="object"||Array.isArray(o))continue;let r=$e(o,"path");if(!r)continue;let s=`/${n}`;if(r.endsWith(s))return r.slice(0,-s.length)}}function su(e,t,n){let o=ue(t?.documents),r=ue(n?.fileVerification),s=[];for(let i of Z.keys()){let a=ue(o?.[i]),u=ue(r?.[i]);if(!a&&!u)return[];let f=$e(a,"path"),T=$e(u,"path")??(f?.includes("/context-pack/")?f:H(`${e}/${i}`)),R=$e(a,"contentHash")??$e(u,"contentHash")??po(`${i}:${T}`),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:H(T),indexed:!0,maintained:!0,indexVersion:String(a?.indexVersion??R),contentHash:R,summary:x,lastReviewedTurn:ao(a,"lastReviewedTurn")??ao(n,"turn")??0,fileSizeBytes:De(a,"fileSizeBytes")??De(u,"fileSizeBytes")??De(u,"sizeBytes")??Buffer.byteLength(x,"utf8"),recordCount:De(a,"recordCount")??De(u,"recordCount")??Us(x)})}return s}function ao(e,t){let n=e?.[t];return typeof n=="number"&&Number.isFinite(n)?n:void 0}function De(e,t){let n=ao(e,t);return n&&n>0?n:void 0}function iu(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=H(i[1]??"");a&&n.add(a)}}return[...n]}function au(e){e.identicalSuccessfulToolResults.clear();for(let t of[...e.identicalCallCounts.keys()]){let n=t.slice(0,t.indexOf("::"));oo.has(n)&&e.identicalCallCounts.delete(t)}}async function*js(e,t,n,o){let{turnId:r,sessionId:s,messages:i,availableTools:a,tools:u,model:f,apiKey:h,temperature:T=0,hooks:R,signal:x}=e,w={sessionId:s,turnId:r},v=e.maxTurns??0,P=e.querySource,A=e.runtimePorts.resolveToolEligibility(u,e.toolEligibilityContext),L=A.eligibleTools,D=[];for(let m of A.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 j=jr(e.maxRounds,i),ne=qr(e.maxToolCalls,i),Ft=!(typeof e.maxRounds=="number"&&e.maxRounds>=1)&&!(typeof e.maxToolCalls=="number"&&e.maxToolCalls>=1),mo=Rt(i),Pe={contextWindowTokens:e.contextWindowTokens??Jo,responseBufferTokens:Qo,maxOutputTokens:e.maxOutputTokens??er,abortSignal:x,reactiveCompactEnabled:!0,outputEscalationEnabled:!0},N=new Set,F=0,Ue=0,je=0,et=0,go=new Map,K=new Set,b=ye(L,K),qe=!1,Bt=!1,Dt,$t=()=>k(b),Vs=Xl(L,i),Ut=!1,ho=0,yo=0,q=!1,tt=!1,jt=tu(i),c={messages:[...i],maxOutputTokensRecoveryCount:0,hasAttemptedReactiveCompact:!1,maxOutputTokensOverride:void 0,turnCount:1,transition:void 0,guardState:vn(Pe),reactiveCompactState:Mn(),toolLoopState:yt({maxRounds:j,replayMessages:[...i]}).state,consecutiveFailedRounds:0,finalText:"",totalUsage:{inputTokens:0,outputTokens:0},collapseStore:un(),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:jt.fileReadCounts,fileReadCycleBlockedPaths:new Set,fileReadCycleNudgedPaths:new Set,maintainedDocuments:jt.maintainedDocuments,persistedBenchmarkStateRecovered:jt.persistedBenchmarkStateRecovered,benchmarkStateMaintenanceRequiredFiles:new Set,benchmarkStateMaintenanceWrittenFiles:new Set,recoveryTrace:new Map,artifactContract:Mr(i),browserAcceptanceRecoveryCount:0,buildVerificationRecoveryCount:0,benchmarkStateIntegrityRecoveryCount:0,backgroundAgentTaskIds:new Set,backgroundAgentNoOutputPollCounts:new Map,stalledBackgroundAgentTasks:new Map,notOfferedToolRecoveryCount:0,existingFileUpdateRecoveryCount:0,taskListReconciliationCount:0,lastTaskList:[]},qt=Math.max(v*5,200),Xs=4,Ks=4,bo=0,To=new Map,zt,M=(m,z)=>{let fe=`${m}:${z??""}`,oe=(To.get(fe)??0)+1;if(To.set(fe,oe),m==="autocompact"){let U=c.recoveryTrace.get("autocompact")??0;if(oe>Xs||U>=Ks){let J=`Repeated context compression made no forward progress: ${z??"autocompact"}`;return zt=J,c.recoveryTrace.set("compression_loop_guard",(c.recoveryTrace.get("compression_loop_guard")??0)+1),{type:"recovery",turnId:r,action:"compression_loop_guard",detail:J}}}return c.recoveryTrace.set(m,(c.recoveryTrace.get(m)??0)+1),{type:"recovery",turnId:r,action:m,detail:z}},Ys=()=>({type:"tool_use_summary",turnId:r,availableToolNames:k(a??u),enabledToolNames:$t(),toolCallNames:[...N].sort(),blockedToolCalls:At(D)}),Zs=m=>Er({content:m,inputMessages:i,messages:c.messages,totalToolCallCount:F,distinctToolNames:N,artifactContract:c.artifactContract,blockedToolCalls:At(D),activeTasks:c.lastTaskList}),Js=m=>({type:"end",turnId:r,content:m,usage:c.totalUsage,model:c.currentModel,...c.recoveryTrace.size>0?{recoveryTrace:Object.fromEntries(c.recoveryTrace)}:{}});function*G(m){let z=Zs(m);Dn(c.artifactContract,z),Gt()&&(yield Ht()),yield Ys(),yield Js(z)}let Ht=()=>({type:"artifact_contract",turnId:r,...Bn(c.artifactContract,i)}),Gt=()=>{let m=Bn(c.artifactContract,i);return!!(m.requiresBrowserAcceptance||m.artifactRoot||m.writePaths.length>0||m.outOfRootWrites.length>0||m.devServerUrls.length>0||m.browserVerified)},nt=(m,z)=>c.finalText||jn(m,o),Qs=(m,z,fe)=>{let oe=Me({inputMessages:i,messages:z,reason:fe});return oe||m||jn(z,o)};for(;;){if(bo++,bo>qt){o.info(`hard iteration cap reached (${qt}), forcing completion`);let l=nt(c.messages,`hard iteration cap reached (${qt}) before completing the final status contract`);yield*G(l);return}let{messages:m,maxOutputTokensRecoveryCount:z,maxOutputTokensOverride:fe,turnCount:oe,guardState:U,reactiveCompactState:J,collapseStore:Wt}=c,{toolLoopState:Q}=c;if(e.refreshTools&&oe>1){let l=e.refreshTools(),d=ye(l,K);d!==b&&(b=d,o.debug(`tools refreshed: ${l.length} tools`))}if(Sn(U,Pe)){o.info(`turn aborted by guard at turn ${oe}`),yield{type:"error",turnId:r,error:"Turn aborted",code:"ABORTED",usage:c.totalUsage};return}let Ce=_n(U,Pe);if(Ce.level==="blocking"){Ce.reason==="prompt_too_long"&&Be(J)&&(J.attemptedThisTurn=!0,U.hasAttemptedReactiveCompact=!0,o.info(`token budget blocking (${Ce.reason}), reactive compact needed`),yield M("reactive_compact","token budget pre-check")),o.info(`token budget blocking (${Ce.reason}), ending tool loop`);break}Ce.level==="warning"&&o.info(`token budget warning: ${Ce.usagePercent}% used, ${Ce.remainingTokens} remaining`);let ot=yield*Xr({messages:m,contentReplacementState:c.contentReplacementState,snipRemovedIds:c.snipRemovedIds,collapseStore:Wt,guardState:U,guardConfig:Pe,runtimePorts:e.runtimePorts,hooks:R,hookCtx:w,sessionId:s,currentModel:c.currentModel,log:o,recovery:M,onAutocompact:()=>{c.hasAttemptedReactiveCompact=!1}});if(zt){yield*G(`${zt}. Stop compressing the same context repeatedly; continue from the maintained document index or report the incomplete state explicitly.`);return}let ei=q?"required":e.toolChoice==="required"&&Ut?"auto":e.toolChoice??"auto";q=!1;let Oe=hn({tools:b,toolChoice:ei}),Co=k(Oe.tools).join("\0"),ko=Dt!==void 0&&Dt!==Co;ko&&c.lastResponseId&&(yield M("stateless_retry","tool schema changed; replaying full history without previous_response_id"));let ti=tt||ko?void 0:c.lastResponseId;Dt=Co;let ze=yt({maxRounds:j,replayMessages:ot,lastStopReason:Q.lastStopReason,options:{stopReason:Q.lastStopReason}}),Ro=Oe.extraSystemPrompt?[{role:"system",content:Oe.extraSystemPrompt},...ze.state.replayMessages]:ze.state.replayMessages;Q=ze.state,ze.recoveryActions.length>0&&o.debug(`tool loop recovery: ${ze.recoveryActions.map(l=>l.detail??l.kind).join("; ")}`),o.debug(`turn ${oe}, messages: ${Ro.length}`),$(R,"turn.before_inference",{...w,model:c.currentModel},o);let Vt=!1,Xt=[],xo=new Map,vo="stop",ee,E=null,rt=!1,_o=!1,He=[],ae=[];try{let l=t.stream({model:c.currentModel,messages:Ro,...Oe.tools.length>0?{tools:Oe.tools,toolChoice:Oe.normalizedToolChoice??"auto"}:{},temperature:T,maxTokens:(fe??U.currentMaxOutputTokens)||void 0,streamRequired:e.streamRequired,previousResponseId:ti,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 $c(l,e.llmStreamIdleTimeoutMs??wc))switch(d.type){case"delta":Xt.push(d.text);break;case"tool_call_delta":Vt=!0,En(xo,d);break;case"reasoning_delta":He.push(d.text);break;case"reasoning_block_complete":d.signature&&ae.push({thinking:He.join(""),signature:d.signature}),He.length=0;break;case"usage":ee={inputTokens:d.promptTokens,outputTokens:d.completionTokens,reasoningTokens:d.reasoningTokens,cacheRead:d.cacheReadTokens,cacheWrite:d.cacheCreationTokens};break;case"response_id":tt||(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":_o=!0,vo=d.finishReason;break}if(Vt||$(R,"turn.after_inference",{...w,model:c.currentModel},o),e.postSamplingHooks&&e.postSamplingHooks.length>0){let d=c.currentModel;for(let g of e.postSamplingHooks)try{g({messages:[...ot],model:d,sessionId:s})}catch{}}}catch(l){if(l instanceof Ot){$(R,"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*Kr(l,{state:c,guardState:U,fallbackModel:e.fallbackModel,signal:x,querySource:P,turnId:r,log:o,emitRecovery:M});if(d.kind==="return")return;if(d.kind==="continue"){c={...c,...d.patch};continue}E=d.streamError}if(!E&&!_o){let l="LLM stream closed before a terminal event; the response was likely truncated upstream.";$(R,"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(E&&$(R,"turn.after_inference",{...w,model:c.currentModel,response:{error:E.message}},o),E){if(!tt&&c.lastResponseId&&/previous_response_id not found/i.test(E.message)){let l=(c.consecutiveApiRetries??0)+1;if(l<=_e){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"),tt=!0,c={...c,lastResponseId:void 0,consecutiveApiRetries:l,transition:void 0};continue}}if(Gn(E))rt=!0,o.info(`withheld prompt_too_long error (status=${E.status})`);else if(Wn(E))rt=!0,o.info(`withheld media_size error (status=${E.status})`);else{let l=wn({status:E.status??500,message:E.message},U,Pe);if(l.action==="reactive_compact"&&Be(J)&&(J.attemptedThisTurn=!0,U.hasAttemptedReactiveCompact=!0,yield M("reactive_compact",`API ${E.status??500}: ${E.message}`)),l.action==="retry"){let g=(c.consecutiveApiRetries??0)+1;if(g>_e){o.info(`API retry limit reached (${_e}), aborting`);let y=Fe(E.status,E.message);yield{type:"error",turnId:r,error:E.message,code:y,usage:c.totalUsage};return}yield M("retry",l.reason),c={...c,consecutiveApiRetries:g,transition:void 0};continue}let d=Fe(E.status,E.message);$(R,"stop.failure",{sessionId:s,reason:d,error:E.message},o),yield{type:"error",turnId:r,error:E.message,code:d,usage:c.totalUsage};return}}ee&&(c.totalUsage.inputTokens+=ee.inputTokens,c.totalUsage.outputTokens+=ee.outputTokens,ee.reasoningTokens&&(c.totalUsage.reasoningTokens=(c.totalUsage.reasoningTokens??0)+ee.reasoningTokens),ee.cacheRead&&(c.totalUsage.cacheRead=(c.totalUsage.cacheRead??0)+ee.cacheRead),ee.cacheWrite&&(c.totalUsage.cacheWrite=(c.totalUsage.cacheWrite??0)+ee.cacheWrite)),ee?.inputTokens&&(U.promptTokens=ee.inputTokens);let st=Xt.join(""),te=[...xo.values()].map((l,d)=>({id:l.id||`tc_${r}_${d}`,type:"function",function:{name:l.name,arguments:l.arguments}}));if(te=Uc(te),te.length===0&&!Vt){if(st&&(c.finalText=st),e.toolChoice==="required"&&!Ut&&b.length>0&&ho<2){ho++;let C=b.map(O=>O.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: ${C}. Do not answer from memory, prior context, or guesses.`}],finalText:"",transition:{reason:"next_turn"}};continue}if(rt&&E&&Gn(E)){if(c.transition?.reason!=="collapse_drain_retry"){let C=fn(ot,Wt);if(C.committed>0){o.info(`collapse drain: committed ${C.committed} stages`),yield M("collapse_drain",`${C.committed} stages committed`),c={...c,messages:C.messages,transition:{reason:"collapse_drain_retry",committed:C.committed}};continue}}if(Be(J)){J.attemptedThisTurn=!0,U.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"),$(R,"stop.failure",{sessionId:s,reason:"prompt_too_long",error:E.message},o),yield{type:"error",turnId:r,error:E.message,code:"PROMPT_TOO_LONG",usage:c.totalUsage};return}if(rt&&E&&Wn(E)){if(Be(J)){J.attemptedThisTurn=!0,U.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"),$(R,"stop.failure",{sessionId:s,reason:"media_error",error:E.message},o),yield{type:"error",turnId:r,error:E.message,code:"IMAGE_ERROR",usage:c.totalUsage};return}if(Gr(vo)){U.consecutiveTruncations+=1;let C=e.modelMaxOutputTokens??tr,O=An(U,Pe,C);if(O.shouldEscalate&&fe===void 0){U.currentMaxOutputTokens=O.newMax,o.info(`max_output_tokens escalate: ${O.newMax} tokens`),yield M("output_escalation",`${O.newMax} tokens`),c={...c,maxOutputTokensOverride:or,transition:{reason:"max_output_tokens_escalate"}};continue}if(z<nr){let I={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:[...ot,I],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 U.consecutiveTruncations=0;Q=ht(Q,{replayMessages:m,lastStopReason:"completed"});let l=await us({hooks:R,sessionId:s,messages:m,finalText:c.finalText,thinkingBlocks:ae,log:o});if(l?.action==="end"){let C=Qs(l.content,m,"stop hook prevented continuation before completing the final status contract");yield*G(C);return}if(l?.action==="continue"){c={...c,messages:l.messages,stopHookActive:l.stopHookActive,transition:l.transition};continue}let d=ds({tokenBudget:e.tokenBudget,totalUsage:c.totalUsage,budgetContinuationCount:c.budgetContinuationCount,lastBudgetDeltaTokens:c.lastBudgetDeltaTokens,lastBudgetGlobalTokens:c.lastBudgetGlobalTokens,messages:m,finalText:c.finalText,thinkingBlocks:ae,getBudgetContinuationMessage:e.runtimePorts.getBudgetContinuationMessage,log:o});if(d){yield M("budget_continuation",d.recoveryDetail),c={...c,messages:d.messages,budgetContinuationCount:d.budgetContinuationCount,lastBudgetDeltaTokens:d.lastBudgetDeltaTokens,lastBudgetGlobalTokens:d.lastBudgetGlobalTokens,transition:d.transition};continue}if(c.finalText.trim()&&dc(c.lastTaskList)&&c.taskListReconciliationCount<1){let C=b.find(O=>O.function.name==="task")??(a??u).find(O=>O.function.name==="task");if(C){let O=uc(c.lastTaskList),I=k(b),ce=ye(L,K);b=ce.some(Ve=>Ve.function.name==="task")?ce:Mt([...ce,C]),c={...c,taskListReconciliationCount:c.taskListReconciliationCount+1,messages:[...m,{role:"assistant",content:c.finalText},{role:"user",content:O}],transition:{reason:"next_turn"}},q=!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??u),enabledToolNamesBefore:I,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(se(i)&&!c.artifactContract.browserVerified&&Pt(c.artifactContract).length>0&&b.some(C=>C.function.name==="exec")&&c.browserAcceptanceRecoveryCount<4){let C=As(c.artifactContract);c={...c,browserAcceptanceRecoveryCount:c.browserAcceptanceRecoveryCount+1,messages:[...m,{role:"assistant",content:c.finalText},{role:"user",content:C}],transition:{reason:"next_turn"}},q=!0,yield M("browser_acceptance_required","forcing browser automation before app/frontend completion");continue}if((e.buildVerificationGate??!0)&&Ln(i)&&!c.artifactContract.buildVerified&&c.artifactContract.buildFailureEvidence.length>0&&b.some(C=>C.function.name==="exec")&&c.buildVerificationRecoveryCount<3){let C=ic(c.artifactContract);c={...c,buildVerificationRecoveryCount:c.buildVerificationRecoveryCount+1,messages:[...m,{role:"assistant",content:c.finalText},{role:"user",content:C}],transition:{reason:"next_turn"}},q=!0,yield M("build_verification_required","test/build still failing; forcing a fix+rerun before completion");continue}let g=Jn({inputMessages:i,messages:m,finalText:c.finalText,thinkingBlocks:ae,stopHookActive:c.stopHookActive,totalToolCallCount:F,distinctToolNames:N,log:o});if(g){if(c.stopHookActive&&c.finalText.trim()===""){let C=Me({inputMessages:i,messages:g.messages,reason:"stop hook produced an empty response after tool use"});if(C){yield*G(C);return}}c={...c,messages:g.messages,stopHookActive:g.stopHookActive,transition:g.transition};continue}if(F===0&&b.length>0&&e.toolChoice!=="none"&&yo<1&&Ur(st)){yo++,q=!0,yield M("intent_without_action","announced but did not act; forcing a tool call"),c={...c,messages:[...m,{role:"assistant",content:st},{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 y=Qn({totalToolCallCount:F,distinctToolNames:N,projectRoot:e.projectRoot});y&&(yield{type:"skill_instruction",turnId:r,instruction:y});let p=nt(m,"the model ended with an empty response after tool use before completing the final status contract");for(let C of Xt)yield{type:"delta",turnId:r,text:C};yield*G(p);return}let ni=ae.length===0&&He.length>0?He.join(""):void 0;m.push(sn(te,void 0,ae.length>0?ae:void 0,ni)),Q=kn(Q,{replayMessages:m,pendingToolCallIds:te.map(l=>l.id),completedToolCallIds:Q.completedToolCallIds,lastStopReason:"tool_calls"});let it=c.identicalCallCounts,Ge=[],le=[],We=[],wo=!1;for(let l of te){if(bc(l,c)){Ge.push(l);continue}let d=`${l.function.name}::${l.function.arguments}`,g=it.get(d)??0;if(it.set(d,g+1),g+1>Zo){let y=oo.has(l.function.name)||l.function.name==="exec"?c.identicalSuccessfulToolResults.get(d):void 0;if(y){We.push({call:l,result:y,repeatCount:g+1});continue}le.push(l),wo||(wo=!0,o.info(`AP4 blocked: ${l.function.name} repeated ${g+1}x`))}else Ge.push(l)}let W=[],oi=new Set(b.map(l=>l.function.name)),Ao=new Set(le.filter(l=>Yc(l,oi)).map(l=>l.id));for(let l of We){let d=l.call,g=`Reused previous successful ${d.function.name} result for identical arguments (attempt ${l.repeatCount}); no additional tool execution was performed.
|
|
40
|
+
`)}function Us(e){return io.has(e)}function ou(e){return e.benchmarkStateMaintenanceRequiredFiles.size>0&&[...e.benchmarkStateMaintenanceRequiredFiles].every(t=>ru(e,t))}function ru(e,t){if(e.benchmarkStateMaintenanceWrittenFiles.has(t))return!0;try{if(!Oe(t))return!1;let n=ke(t);if(n!=="document-index.json"&&n!=="context-pack-evidence.json")return!0;let o=Bt(t,"utf8");return mo(e.maintainedDocuments,t,JSON.stringify({content:o})).ok}catch{return!1}}function mo(e,t,n){let o=ke(t);if(o!=="document-index.json"&&o!=="context-pack-evidence.json")return{ok:!0};let r=Cu(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 f=e.get(u),h=de(a[u]);if(!f||!h)return{ok:!1,reason:`document-index.json missing ${u}`};if(h.contentHash!==f.contentHash)return{ok:!1,reason:`document-index.json ${u} contentHash does not match read.details`};if(h.fileSizeBytes!==f.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),f=de(i[a]);if(!u||!f)return{ok:!1,reason:`context-pack-evidence.json missing ${a}`};if(f.contentHash!==u.contentHash)return{ok:!1,reason:`context-pack-evidence.json ${a} contentHash does not match read.details`};if(f.fileSizeBytes!==u.fileSizeBytes)return{ok:!1,reason:`context-pack-evidence.json ${a} fileSizeBytes does not match read.details`}}return{ok:!0}}function su(e){if(!Ys(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(!Oe(r))continue;s=Bt(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 iu(e,t,n,o){if(e.filter(a=>a.name==="read"&&a.reason==="read-cycle-policy").length<Jc)return!1;let s=new Set([...t].filter(fo).map(ke));return[...J.keys()].every(a=>s.has(a))?[...J.keys()].every(a=>o.has(a))||n||tu(t):!1}function Js(e,t,n){if(e!=="write"||!n.has("edit")&&!n.has("patch"))return null;let o=Ft(t);if(!o)return null;try{if(!Oe(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 Lt=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*au(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 Lt(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 Ft(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 lu(e){return e.flatMap(t=>{if(cu(t.function.arguments))return[t];let n=uu(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 cu(e){try{let t=JSON.parse(e);return!!t&&typeof t=="object"&&!Array.isArray(t)}catch{return!1}}function uu(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 f=fe(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 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 ke(e){let t=e.trim().replace(/\\/g,"/");return t.slice(t.lastIndexOf("/")+1).toLowerCase()}function go(e){return`sha256:${lc("sha256").update(e).digest("hex")}`}function du(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 fu(e){return Object.fromEntries([...e.entries()].sort(([t],[n])=>t.localeCompare(n)))}function pu(e,t,n,o){let r=[...t.values()].sort((u,f)=>(u.name??"").localeCompare(f.name??""));if(r.length===0)return null;let s=r.map(u=>`${u.name??"document"}:${u.contentHash??"unknown"}`).join("|"),i=Vs.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:fu(n)};return{type:"document_maintenance",turnId:e,checkpointId:`${e}-docs-${r.length}`,documents:r,decisionStateTable:i,readCycleFindings:[],readCycleGuard:a}}function mu(e){let t=e.find(o=>o.path)?.path??"",n=t.lastIndexOf("/");return n>0?t.slice(0,n):t}function It(e,t){return e.get(t)??null}function gu(e){let t=It(e,"requirements.md"),n=It(e,"decisions.md"),o=It(e,"defects.md"),r=It(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:mu(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 hu(e,t){let n=gu(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 yu(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=ke(e);if(!J.has(r))return null;let s=Ru(t)??t,i=ku(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:du(r,s),lastReviewedTurn:n,fileSizeBytes:a??Buffer.byteLength(s,"utf8"),recordCount:Qs(s)}}function bu(e,t){return Js(e.function.name,e.function.arguments,t)!==null}function Tu(e,t){let n=Ft(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 Cu(e){let n=fe(e)?.content;return typeof n=="string"?n:void 0}function ku(e,t){let n=e?.[t];return typeof n=="string"&&n.trim()?n.trim():void 0}function Qs(e){let t=e.split(/\r?\n/).map(n=>n.trim()).filter(Boolean).length;return Math.max(1,t)}function Ru(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 Oe(n)?Bt(n,"utf8"):null}catch{return null}}function xu(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);Xs(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 Su(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 _u(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 _u(e){let t=[];for(let n of vu(e)){let o=js(`${n}/document-index.json`),r=js(`${n}/context-pack-evidence.json`),s=ze(o,"contextPackPath")??wu(r);if(!s)continue;let i=Au(s,o,r);i.length===J.size&&t.push({documents:i})}return t}function vu(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(!Oe(e))return null;let t=JSON.parse(Bt(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 wu(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 Au(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 f=ze(a,"path"),T=ze(u,"path")??(f?.includes("/context-pack/")?f:G(`${e}/${i}`)),R=ze(a,"contentHash")??ze(u,"contentHash")??go(`${i}:${T}`),_=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(T),indexed:!0,maintained:!0,indexVersion:String(a?.indexVersion??R),contentHash:R,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")??Qs(_)})}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 Su(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 Mu(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*ei(e,t,n,o){let{turnId:r,sessionId:s,messages:i,availableTools:a,tools:u,model:f,apiKey:h,temperature:T=0,hooks:R,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=Kr(e.maxRounds,i),re=Yr(e.maxToolCalls,i),Dt=!(typeof e.maxRounds=="number"&&e.maxRounds>=1)&&!(typeof e.maxToolCalls=="number"&&e.maxToolCalls>=1),ho=vt(i),Ne={contextWindowTokens:e.contextWindowTokens??ir,responseBufferTokens:ar,maxOutputTokens:e.maxOutputTokens??lr,abortSignal:_,reactiveCompactEnabled:!0,outputEscalationEnabled:!0},L=new Set,F=0,He=0,Ge=0,ot=0,yo=new Map,Y=new Set,y=Te(O,Y),We=!1,$t=!1,Ut,jt=()=>C(y),ii=cc(O,i),qt=!1,bo=0,To=0,Co=0,U=!1,rt=!1,zt=xu(i),c={messages:[...i],maxOutputTokensRecoveryCount:0,hasAttemptedReactiveCompact:!1,maxOutputTokensOverride:void 0,turnCount:1,transition:void 0,guardState:vn(Ne),reactiveCompactState:En(),toolLoopState:Ct({maxRounds:q,replayMessages:[...i]}).state,consecutiveFailedRounds:0,finalText:"",totalUsage:{inputTokens:0,outputTokens:0},collapseStore:fn(),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:zt.fileReadCounts,fileReadCycleBlockedPaths:new Set,fileReadCycleNudgedPaths:new Set,maintainedDocuments:zt.maintainedDocuments,persistedBenchmarkStateRecovered:zt.persistedBenchmarkStateRecovered,benchmarkStateMaintenanceRequiredFiles:new Set,benchmarkStateMaintenanceWrittenFiles:new Set,recoveryTrace:new Map,artifactContract:Dr(i),browserAcceptanceRecoveryCount:0,buildVerificationRecoveryCount:0,benchmarkStateIntegrityRecoveryCount:0,backgroundAgentTaskIds:new Set,backgroundAgentNoOutputPollCounts:new Map,stalledBackgroundAgentTasks:new Map,notOfferedToolRecoveryCount:0,existingFileUpdateRecoveryCount:0,taskListReconciliationCount:0,lastTaskList:[]},Ht=Math.max(w*5,200),ai=4,li=4,ko=0,Ro=new Map,Gt,M=(m,z)=>{let pe=`${m}:${z??""}`,se=(Ro.get(pe)??0)+1;if(Ro.set(pe,se),m==="autocompact"){let j=c.recoveryTrace.get("autocompact")??0;if(se>ai||j>=li){let Q=`Repeated context compression made no forward progress: ${z??"autocompact"}`;return Gt=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}},xo=()=>({type:"tool_use_summary",turnId:r,availableToolNames:C(a??u),enabledToolNames:jt(),toolCallNames:[...L].sort(),blockedToolCalls:Et(D)}),ci=m=>$r({content:m,inputMessages:i,messages:c.messages,totalToolCallCount:F,distinctToolNames:L,artifactContract:c.artifactContract,blockedToolCalls:Et(D),activeTasks:c.lastTaskList}),_o=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=ci(m);$n(c.artifactContract,z),Vt()&&(yield Wt()),yield xo(),yield _o(z)}function*vo(m){yield xo(),yield _o(m)}let Wt=()=>({type:"artifact_contract",turnId:r,...Dn(c.artifactContract,i)}),Vt=()=>{let m=Dn(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||zn(m,o),ui=(m,z,pe)=>{let se=Ie({inputMessages:i,messages:z,reason:pe});return se||m||zn(z,o)};for(;;){if(ko++,ko>Ht){o.info(`hard iteration cap reached (${Ht}), forcing completion`);let l=st(c.messages,`hard iteration cap reached (${Ht}) before completing the final status contract`);yield*W(l);return}let{messages:m,maxOutputTokensRecoveryCount:z,maxOutputTokensOverride:pe,turnCount:se,guardState:j,reactiveCompactState:Q,collapseStore:Xt}=c,{toolLoopState:ee}=c;if(e.refreshTools&&se>1){let l=e.refreshTools(),d=Te(l,Y);d!==y&&(y=d,o.debug(`tools refreshed: ${l.length} tools`))}if(Mn(j,Ne)){o.info(`turn aborted by guard at turn ${se}`),yield{type:"error",turnId:r,error:"Turn aborted",code:"ABORTED",usage:c.totalUsage};return}let Re=wn(j,Ne);if(Re.level==="blocking"){Re.reason==="prompt_too_long"&&Ue(Q)&&(Q.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 it=yield*ns({messages:m,contentReplacementState:c.contentReplacementState,snipRemovedIds:c.snipRemovedIds,collapseStore:Xt,guardState:j,guardConfig:Ne,runtimePorts:e.runtimePorts,hooks:R,hookCtx:A,sessionId:s,currentModel:c.currentModel,log:o,recovery:M,onAutocompact:()=>{c.hasAttemptedReactiveCompact=!1}});if(Gt){yield*W(`${Gt}. Stop compressing the same context repeatedly; continue from the maintained document index or report the incomplete state explicitly.`);return}let di=U?"required":e.toolChoice==="required"&&qt?"auto":e.toolChoice??"auto";U=!1;let Le=yn({tools:y,toolChoice:di}),wo=C(Le.tools).join("\0"),Ao=Ut!==void 0&&Ut!==wo;Ao&&c.lastResponseId&&(yield M("stateless_retry","tool schema changed; replaying full history without previous_response_id"));let fi=rt||Ao?void 0:c.lastResponseId;Ut=wo;let Ve=Ct({maxRounds:q,replayMessages:it,lastStopReason:ee.lastStopReason,options:{stopReason:ee.lastStopReason}}),So=Le.extraSystemPrompt?[{role:"system",content:Le.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: ${So.length}`),$(R,"turn.before_inference",{...A,model:c.currentModel},o);let Kt=!1,Yt=[],Mo=new Map,Eo="stop",te,I=null,at=!1,Io=!1,Xe=[],ce=[];try{let l=t.stream({model:c.currentModel,messages:So,...Le.tools.length>0?{tools:Le.tools,toolChoice:Le.normalizedToolChoice??"auto"}:{},temperature:T,maxTokens:(pe??j.currentMaxOutputTokens)||void 0,streamRequired:e.streamRequired,previousResponseId:fi,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,_);for await(let d of au(l,e.llmStreamIdleTimeoutMs??Xc))switch(d.type){case"delta":Yt.push(d.text);break;case"tool_call_delta":Kt=!0,In(Mo,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":Io=!0,Eo=d.finishReason;break}if(Kt||$(R,"turn.after_inference",{...A,model:c.currentModel},o),e.postSamplingHooks&&e.postSamplingHooks.length>0){let d=c.currentModel;for(let g of e.postSamplingHooks)try{g({messages:[...it],model:d,sessionId:s})}catch{}}}catch(l){if(l instanceof Lt){$(R,"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*os(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&&!Io){let l="LLM stream closed before a terminal event; the response was likely truncated upstream.";$(R,"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&&$(R,"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<=Ae){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(Vn(I))at=!0,o.info(`withheld prompt_too_long error (status=${I.status})`);else if(Xn(I))at=!0,o.info(`withheld media_size error (status=${I.status})`);else{let l=An({status:I.status??500,message:I.message},j,Ne);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 g=(c.consecutiveApiRetries??0)+1;if(g>Ae){o.info(`API retry limit reached (${Ae}), aborting`);let b=$e(I.status,I.message);yield{type:"error",turnId:r,error:I.message,code:b,usage:c.totalUsage};return}yield M("retry",l.reason),c={...c,consecutiveApiRetries:g,transition:void 0};continue}let d=$e(I.status,I.message);$(R,"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 Fe=Yt.join(""),ne=[...Mo.values()].map((l,d)=>({id:l.id||`tc_${r}_${d}`,type:"function",function:{name:l.name,arguments:l.arguments}}));if(ne=lu(ne),ne.length===0&&!Kt){Fe&&(c.finalText=Fe);let l=je([...y,...a??u]),d=e.toolChoice==="none"?null:Cs({text:Fe,enabledToolNames:C(l)});if(d&&To<2){if(To++,!new Set(y.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(y),ge=new Map(y.map(x=>[x.function.name,x]));for(let x of N)ge.set(x.function.name,x);y=je([...ge.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(y),suppressedToolNames:[],nextAction:"retry-with-native-tool-call"}}}c={...c,messages:[...m,{role:"assistant",content:Fe},{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"&&!qt&&y.length>0&&bo<2){bo++;let k=y.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: ${k}. Do not answer from memory, prior context, or guesses.`}],finalText:"",transition:{reason:"next_turn"}};continue}if(at&&I&&Vn(I)){if(c.transition?.reason!=="collapse_drain_retry"){let k=mn(it,Xt);if(k.committed>0){o.info(`collapse drain: committed ${k.committed} stages`),yield M("collapse_drain",`${k.committed} stages committed`),c={...c,messages:k.messages,transition:{reason:"collapse_drain_retry",committed:k.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"),$(R,"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(at&&I&&Xn(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"),$(R,"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(Qr(Eo)){j.consecutiveTruncations+=1;let k=e.modelMaxOutputTokens??cr,N=Sn(j,Ne,k);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:dr,transition:{reason:"max_output_tokens_escalate"}};continue}if(z<ur){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=Tt(ee,{replayMessages:m,lastStopReason:"completed"});let g=await bs({hooks:R,sessionId:s,messages:m,finalText:c.finalText,thinkingBlocks:ce,log:o});if(g?.action==="end"){let k=ui(g.content,m,"stop hook prevented continuation before completing the final status contract");yield*W(k);return}if(g?.action==="continue"){c={...c,messages:g.messages,stopHookActive:g.stopHookActive,transition:g.transition};continue}let b=Ts({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(b){yield M("budget_continuation",b.recoveryDetail),c={...c,messages:b.messages,budgetContinuationCount:b.budgetContinuationCount,lastBudgetDeltaTokens:b.lastBudgetDeltaTokens,lastBudgetGlobalTokens:b.lastBudgetGlobalTokens,transition:b.transition};continue}if(c.finalText.trim()&&Oc(c.lastTaskList)&&c.taskListReconciliationCount<1){let k=y.find(N=>N.function.name==="task")??(a??u).find(N=>N.function.name==="task");if(k){let N=Pc(c.lastTaskList),oe=C(y),ge=Te(O,Y);y=ge.some(x=>x.function.name==="task")?ge:je([...ge,k]),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(y),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&&Nt(c.artifactContract).length>0&&y.some(k=>k.function.name==="exec")&&c.browserAcceptanceRecoveryCount<4){let k=Bs(c.artifactContract);c={...c,browserAcceptanceRecoveryCount:c.browserAcceptanceRecoveryCount+1,messages:[...m,{role:"assistant",content:c.finalText},{role:"user",content:k}],transition:{reason:"next_turn"}},U=!0,yield M("browser_acceptance_required","forcing browser automation before app/frontend completion");continue}if((e.buildVerificationGate??!0)&&Ln(i)&&!c.artifactContract.buildVerified&&c.artifactContract.buildFailureEvidence.length>0&&y.some(k=>k.function.name==="exec")&&c.buildVerificationRecoveryCount<3){let k=Sc(c.artifactContract);c={...c,buildVerificationRecoveryCount:c.buildVerificationRecoveryCount+1,messages:[...m,{role:"assistant",content:c.finalText},{role:"user",content:k}],transition:{reason:"next_turn"}},U=!0,yield M("build_verification_required","test/build still failing; forcing a fix+rerun before completion");continue}let p=eo({inputMessages:i,messages:m,finalText:c.finalText,thinkingBlocks:ce,stopHookActive:c.stopHookActive,totalToolCallCount:F,distinctToolNames:L,log:o});if(p){if(c.stopHookActive&&c.finalText.trim()===""){let k=Ie({inputMessages:i,messages:p.messages,reason:"stop hook produced an empty response after tool use"});if(k){yield*W(k);return}}c={...c,messages:p.messages,stopHookActive:p.stopHookActive,transition:p.transition};continue}if(F===0&&y.length>0&&e.toolChoice!=="none"&&Co<1&&Xr(Fe)){Co++,U=!0,yield M("intent_without_action","announced but did not act; forcing a tool call"),c={...c,messages:[...m,{role:"assistant",content:Fe},{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 k of Yt)yield{type:"delta",turnId:r,text:k};yield*W(H);return}let pi=ce.length===0&&Xe.length>0?Xe.join(""):void 0;m.push(ln(ne,void 0,ce.length>0?ce:void 0,pi)),ee=Rn(ee,{replayMessages:m,pendingToolCallIds:ne.map(l=>l.id),completedToolCallIds:ee.completedToolCallIds,lastStopReason:"tool_calls"});let lt=c.identicalCallCounts,Ke=[],ue=[],Ye=[],Po=!1;for(let l of ne){if(Uc(l,c)){Ke.push(l);continue}let d=`${l.function.name}::${l.function.arguments}`,g=lt.get(d)??0;if(lt.set(d,g+1),g+1>sr){let b=so.has(l.function.name)||l.function.name==="exec"?c.identicalSuccessfulToolResults.get(d):void 0;if(b){Ye.push({call:l,result:b,repeatCount:g+1});continue}ue.push(l),Po||(Po=!0,o.info(`AP4 blocked: ${l.function.name} repeated ${g+1}x`))}else Ke.push(l)}let V=[],mi=new Set(y.map(l=>l.function.name)),Oo=new Set(ue.filter(l=>bu(l,mi)).map(l=>l.id));for(let l of Ye){let d=l.call,g=`Reused previous successful ${d.function.name} result for identical arguments (attempt ${l.repeatCount}); no additional tool execution was performed.
|
|
41
41
|
|
|
42
|
-
${l.result.content}`,y=V(d.id,{ok:!0,payload:g,imageUrls:l.result.imageUrls,toolReferences:l.result.toolReferences});m.push(y),W.push(d.id),N.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(We.some(l=>l.call.function.name==="exec"&&Ss(l.call.function.arguments))){let l=k(b);m.push({role:"user",content:cc(c.artifactContract)}),yield{type:"tool_selection_policy",turnId:r,policyId:"browser_verification_after_preparation_required",intent:"verification",reason:"repeated-browser-preparation-command",availableToolNames:k(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 le){D.push({name:l.function.name,reason:"identical-repeat-policy"});let d=it.get(`${l.function.name}::${l.function.arguments}`),g=kt(m,l.function.name),y=tc(g),p=Ao.has(l.id)?Zc(d,l):y?`This exact tool call has been attempted ${d} times. Last error: ${y}. 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.`,C=V(l.id,{ok:!1,error:p});m.push(C),W.push(l.id),N.add(l.function.name),F++,yield{type:"tool_result",turnId:r,callId:l.id,name:l.function.name,ok:!1,error:p}}if(le.length>0&&Ge.length===0&&We.length===0&&le.every(l=>Ao.has(l.id))&&c.existingFileUpdateRecoveryCount<2){let l=k(b);b=xs(L,K);let d=k(b);qe=!0,q=!0;let g=[...new Set(le.map(y=>Lt(y.function.arguments)).filter(y=>!!y))];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??u),enabledToolNamesBefore:l,enabledToolNamesAfter:d,suppressedToolNames:to(l,d),nextAction:"use-read-edit-or-patch-for-existing-file-update"},yield M("existing_file_update_recovery",g.join(",")||"unknown"),c={...c,messages:m,existingFileUpdateRecoveryCount:c.existingFileUpdateRecoveryCount+1,transition:{reason:"next_turn"}};continue}if(le.length>0){let l=kt(m,le[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 ri=mo>=3&&c.repeatedToolFailureRecoveryCount<1;if(le.length>0&&Ge.length===0&&We.length===0&&!ri){let l=Ms(qn(m,1),{availableToolNames:k(a??u),enabledToolNames:$t(),toolCallNames:[...N].sort(),blockedToolCalls:At(D)});yield*G(l);return}let So=[],Kt=[];for(let l of Ge){let d=Ar({toolName:l.function.name,rawArguments:l.function.arguments});d?Kt.push({call:l,...d}):So.push(l)}for(let l of Kt){let d=l.call;D.push({name:d.function.name,reason:"read-only-context-pack"}),m.push(V(d.id,{ok:!1,error:l.error})),W.push(d.id),N.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}`)}Kt.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 si=new Set(b.map(l=>l.function.name)),Mo=[],at=[];for(let l of So){let d=$s(l.function.name,l.function.arguments,si);d?at.push({call:l,...d}):Mo.push(l)}for(let l of at){let d=l.call;D.push({name:d.function.name,reason:"existing-file-update-tool-required"}),m.push(V(d.id,{ok:!1,error:l.error})),W.push(d.id),N.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(at.length>0){let l=k(b);b=xs(L,K);let d=k(b);qe=!0,q=!0;let g=[...new Set(at.map(y=>y.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??u),enabledToolNamesBefore:l,enabledToolNamesAfter:d,suppressedToolNames:to(l,d),nextAction:"use-read-edit-or-patch-for-existing-file-update"},yield M("existing_file_update_recovery",g.join(",")||"unknown"),c={...c,messages:m,existingFileUpdateRecoveryCount:c.existingFileUpdateRecoveryCount+1,transition:{reason:"next_turn"}};continue}let Eo=[],Yt=[];for(let l of Mo){let d=wr({state:c.artifactContract,inputMessages:i,toolName:l.function.name,rawArguments:l.function.arguments});d?Yt.push({call:l,...d}):Eo.push(l)}for(let l of Yt){let d=l.call;D.push({name:d.function.name,reason:"artifact-root-contract"}),Fn(c.artifactContract,{path:l.path,artifactRoot:l.artifactRoot,toolName:d.function.name}),m.push(V(d.id,{ok:!1,error:l.error})),W.push(d.id),N.add(d.function.name),F++,yield{type:"tool_result",turnId:r,callId:d.id,name:d.function.name,ok:!1,error:l.error},Gt()&&(yield Ht()),o.warn(`artifact root contract blocked: ${d.function.name}`)}Yt.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 Io=[],Zt=[];for(let l of Eo){let d=ls({inputMessages:i,messages:m,toolCall:l});d?Zt.push({call:l,error:d}):Io.push(l)}for(let l of Zt){let d=l.call;D.push({name:d.function.name,reason:"premature-completion-artifact"}),m.push(V(d.id,{ok:!1,error:l.error})),W.push(d.id),N.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}`)}Zt.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 ii=new Set(b.map(l=>l.function.name)),Po=[],lt=[];for(let l of Io)ii.has(l.function.name)?Po.push(l):lt.push(l);for(let l of lt){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(V(l.id,{ok:!1,error:d})),W.push(l.id),N.add(l.function.name),o.warn(`unoffered tool call suppressed: ${l.function.name}`)}if(lt.length>0&&c.notOfferedToolRecoveryCount<1){let l=[...new Set(lt.map(C=>C.function.name))].sort(),d=qe&&l.includes("write"),g=l.filter(C=>K.has(C)),p=(a??u).filter(C=>l.includes(C.function.name));if(g.length>0)c.notOfferedToolRecoveryCount+=1,q=!0,m.push({role:"user",content:`You retried ${g.map(C=>`\`${C}\``).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??u),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 C=k(b),O=new Map(b.map(I=>[I.function.name,I]));for(let I of p)O.set(I.function.name,I);b=Mt([...O.values()]),c.notOfferedToolRecoveryCount+=1,q=!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??u),enabledToolNamesBefore:C,enabledToolNamesAfter:k(b),suppressedToolNames:[],nextAction:"retry-with-reenabled-requested-tool"},m.push({role:"user",content:`You called ${l.map(I=>`\`${I}\``).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 Oo=[],Jt=[];for(let l of Po){let d=b.find(y=>y.function.name===l.function.name),g=pc(d,l.function.arguments);g?Jt.push({call:l,error:g}):Oo.push(l)}for(let l of Jt){let d=l.call;D.push({name:d.function.name,reason:"invalid-arguments"}),c.toolFailureCounts,d.function.name,m.push(V(d.id,{ok:!1,error:l.error})),W.push(d.id),N.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}`)}Jt.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 ct=[],Qt=[];for(let l of Oo){if(l.function.name!=="exec"){ct.push(l);continue}let d=vs(l.function.arguments);if(!d){ct.push(l);continue}let g=bs(d);Ts(g)&&Rs(L)?Qt.push({call:l,error:fc(g)}):ct.push(l)}for(let l of Qt){let d=l.call;D.push({name:d.function.name,reason:"dedicated-tool-required"});let g=k(b),y=b.filter(p=>["read","search"].includes(p.function.name));y.length>0&&(b=y,Bt=!0,q=!0),m.push(V(d.id,{ok:!1,error:l.error})),W.push(d.id),N.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??u),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"}}Qt.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 ut=[],en=[],Lo=[],No=[];for(let l of ct){if(l.function.name!=="exec"){ut.push(l);continue}let d=l,g=vs(d.function.arguments),y=g?rc(g):null;y&&(d={...d,function:{...d.function,arguments:ws(d.function.arguments,y)}},No.push({originalCommand:g??"",rewrittenCommand:y}),g=y);let p=g?sc(g):null;if(p?.action==="block")en.push({call:d,error:p.error});else if(p?.action==="rewrite"){let C={...d,function:{...d.function,arguments:ws(d.function.arguments,p.command)}};Lo.push({call:C,originalCommand:g??"",rewrittenCommand:p.command}),ut.push(C)}else ut.push(d)}for(let l of No)yield{type:"tool_selection_policy",turnId:r,policyId:"exec_sleep_prefix_guard",intent:"verification",reason:"sleep-prefix-removed",availableToolNames:k(a??u),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 Lo){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??u),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 en){let d=l.call;D.push({name:d.function.name,reason:"reserved-frontend-port"});let g=k(b);m.push(V(d.id,{ok:!1,error:l.error})),W.push(d.id),N.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:It}},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??u),enabledToolNamesBefore:g,enabledToolNamesAfter:k(b),suppressedToolNames:[],nextAction:"restart-generated-dev-server-on-explicit-non-5174-port-with-strict-port"}}en.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 dt=[],Le=[];for(let l of ut){if(l.function.name!=="read"){dt.push(l);continue}let d=so(l.function.arguments);if(!d){dt.push(l);continue}let g=H(d),y=Ns(g);(c.fileReadCounts.get(g)??0)>=y?Le.push({call:l,filePath:g,maxReads:y}):dt.push(l)}for(let l of Le){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. ${no(l.filePath)}`;D.push({name:d.function.name,reason:"read-cycle-policy"}),c.fileReadCycleBlockedPaths.add(l.filePath),m.push(V(d.id,{ok:!1,error:g})),W.push(d.id),N.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(Le.length>0){let l=[...new Set(Le.map(y=>`${y.filePath} (max ${y.maxReads})`))].join(", "),d=[...new Set(Le.map(y=>no(y.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(y=>Es(y.function.name))&&(c.persistedBenchmarkStateRecovered||Le.some(y=>co(y.filePath)))){let y=k(b),p=y.filter(C=>Pc.has(C)).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??u),enabledToolNamesBefore:y,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(Dc(D,c.fileReadCycleBlockedPaths,c.persistedBenchmarkStateRecovered,c.maintainedDocuments)){yield*G("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 tn=fs(dt,c.toolFailureCounts),nn=tn.allowed;if(Ft&&nn.length>Math.max(0,ne-F)){let l=Hn({currentToolBudget:ne,currentRoundBudget:j,toolHardCap:100,roundHardCap:100,continuationCount:je,successfulSinceLastCheck:Ue-et,fileReadCounts:c.fileReadCounts,windowTools:ge,windowRounds:25});l&&(ne=l.nextToolBudget,j=l.nextRoundBudget,je=l.continuationCount,et=Ue,o.info(`tool budget continuation #${l.continuationCount}: tools\u2192${ne}, rounds\u2192${j} (progress detected)`))}let Fo=Math.max(0,ne-F),pe=Fo>0?nn.slice(0,Fo):[],on=nn.slice(pe.length),ai=on.length>0;if(tn.blocked.length>0){for(let l of tn.blocked){let d=l.call;D.push({name:d.function.name,reason:"variant-failure-policy"});let g=V(d.id,{ok:!1,error:l.error});m.push(g),W.push(d.id),N.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(ps())}if(on.length>0){let l=`Tool call budget exhausted (${ne}) for this turn. Stop requesting more tools and report what remains incomplete.`;for(let d of on){D.push({name:d.function.name,reason:"tool-call-budget"});let g=V(d.id,{ok:!1,error:l});m.push(g),W.push(d.id),N.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 ${je} 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 pe){let d=l.function.arguments,g=b.find(y=>y.function.name===l.function.name);if(g?.backfillObservableInput)try{let y=JSON.parse(l.function.arguments),p={...y};g.backfillObservableInput(p),Object.keys(p).some(O=>!(O in y))&&(d=JSON.stringify(p))}catch{}yield{type:"tool_call",turnId:r,callId:l.id,name:l.function.name,arguments:d,inputSummary:zn(d)}}let li=new Map(c.toolFailureCounts),ft=null;try{let l=e.runtimePorts.createStreamingToolExecutor({toolInvoker:n,hooks:R,sessionId:s,turnId:r,log:o,signal:x,maxConcurrentTools:e?.maxConcurrentTools,maxExecutionMs:Ko});for(let p of pe)l.addTool(p);let d=!1;for await(let p of l.getRemainingResults()){let C=Ql(p);if(C){if(D.push({name:p.toolName,reason:C}),p.toolName==="exec"&&C==="dedicated-tool-required"&&Rs(L)){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??u),enabledToolNamesBefore:_,enabledToolNamesAfter:k(b),suppressedToolNames:[],nextAction:"use-read-search-for-file-inspection-or-exec-for-build-run-verify"}}if(p.toolName==="exec"&&C==="confirmation-timeout"){let _=k(b);K.add("exec");let S=ye(L,K);S.length>0&&(b=Mt(S),q=!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??u),enabledToolNamesBefore:_,enabledToolNamesAfter:k(b),suppressedToolNames:to(_,k(b)),nextAction:"continue-with-non-exec-tools-or-report-confirmation-blocker"}}if(p.toolName==="exec"&&C==="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??u),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),W.push(p.callId),N.add(p.toolName);let O=Tc(p,c);O||F++;let I=p.ok&&Fr(p);if(p.ok&&!I&&!O&&(Ue+=1),O||ms({toolFailureCounts:c.toolFailureCounts,toolName:p.toolName,toolArguments:pe.find(_=>_.id===p.callId)?.function.arguments,ok:p.ok,softEmpty:I}),p.ok&&_c.has(p.toolName)&&au(c),p.ok&&Es(p.toolName)){let _=pe.find(B=>B.id===p.callId),S=_?Lt(_.function.arguments):void 0;if(S){let B=H(S);if(c.benchmarkStateMaintenanceRequiredFiles.has(B)){let re=fo(c.maintainedDocuments,B,_?.function.arguments??"");re.ok?c.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: ${re.reason}. Rewrite or patch the file using the document evidence already provided; do not reread context-pack source documents.`}))}}}if(p.ok&&!I&&(oo.has(p.toolName)||p.toolName==="exec"&&p.details?.type==="exec_background"||p.toolName==="exec"&&Ss(pe.find(_=>_.id===p.callId)?.function.arguments??""))){let _=pe.find(B=>B.id===p.callId),S=typeof p.message?.content=="string"?p.message.content:"";if(_&&S){let B=Array.isArray(p.message.imageUrls)?p.message.imageUrls.filter(me=>typeof me=="string"):void 0,re=Array.isArray(p.message.toolReferences)?p.message.toolReferences.filter(me=>typeof me=="string"):void 0;c.identicalSuccessfulToolResults.set(`${_.function.name}::${_.function.arguments}`,{content:S,imageUrls:B,toolReferences:re})}}if(p.toolName==="agent"){let _=Ee(p.details,"agentId"),S=Ee(p.details,"status"),B=Et(p.details,"background");p.ok&&_&&B===!0&&S==="running"&&be(c).add(_)}if(p.toolName==="task"){let _=vc(p.details);_&&(c.lastTaskList=_);let S=Ee(p.details,"taskId"),B=Et(p.details,"running"),re=Ee(p.details,"lifecycle"),me=Ee(p.details,"action");if(S&&(me==="cancel"||B===!1||re&&re!=="running"&&re!=="pending"))be(c).delete(S),c.backgroundAgentNoOutputPollCounts.delete(S),c.stalledBackgroundAgentTasks.delete(S);else if(S&&me==="output"&&B===!0&&be(c).has(S)){let Bo=typeof p.message?.content=="string"?p.message.content:"",Do=Et(p.details,"hasOutput");if(Do!==void 0?Do===!1:Rc(Bo)){let rn=(c.backgroundAgentNoOutputPollCounts.get(S)??0)+1;c.backgroundAgentNoOutputPollCounts.set(S,rn);let mt=gc(p.details,"elapsedSeconds")??xc(Bo);(mt!==void 0&&mt>=Cc||mt===void 0&&rn>=kc)&&c.stalledBackgroundAgentTasks.set(S,`no output after ${mt??"unknown"}s across ${rn} poll(s)`)}else c.backgroundAgentNoOutputPollCounts.delete(S),c.stalledBackgroundAgentTasks.delete(S)}}if(p.ok&&p.toolName==="read"){let _=pe.find(S=>S.id===p.callId);if(_){let S=so(_.function.arguments);if(S){let B=H(S),re=c.fileReadCounts.get(B)??0;c.fileReadCounts.set(B,re+1);let me=typeof p.message?.content=="string"?p.message.content:"";d=Kc(c,S,me,c.turnCount,p.details)||d}}}yield br(r,p);for(let _ of Tr(r,p))yield _;for(let _ of Cr({turnId:r,result:p,toolCalls:te}))yield _;let Ve=te.find(_=>_.id===p.callId),ui=typeof p.message?.content=="string"?p.message.content:"";if(Ve){Sr({state:c.artifactContract,inputMessages:i,toolName:p.toolName,rawArguments:Ve.function.arguments,ok:p.ok,content:ui}),Gt()&&(yield Ht());let _=lc(p.toolName,Ve.function.arguments);if(_){let S=(go.get(_)??0)+1;if(go.set(_,S),S===ac){let B=_.startsWith("exec:")?"exec":"edit";c.recoveryTrace.set(`no_progress_observed:${B}`,(c.recoveryTrace.get(`no_progress_observed:${B}`)??0)+1)}}}!ft&&Vs&&p.toolName==="stt"&&p.ok&&(ft=Kl(i,p))}if(qe&&(b=ye(L,K),qe=!1),Bt&&(b=ye(L,K),Bt=!1),d){let p=Gc(r,c.maintainedDocuments,c.fileReadCounts,c.turnCount);p&&(yield p);for(let I of Xc(r,c.maintainedDocuments))yield I;let C=Lc(c.maintainedDocuments,c.turnCount),O=b.some(I=>ro.has(I.function.name));if(C&&O){c.benchmarkStateMaintenanceRequiredFiles=new Set(Ds(c.maintainedDocuments).map(H));for(let I of b)ro.has(I.function.name)||K.add(I.function.name);b=ye(b,K),q=!0,m.push({role:"user",content:C}),yield M("benchmark_state_maintenance_required","forcing write/edit/patch after long-horizon document index")}}let g=be(c);if(g.size>0){let p=(a??u).find(C=>C.function.name==="task");if(p){let C=k(b),O=[...g].filter(I=>c.stalledBackgroundAgentTasks.has(I)).sort();if(O.length>0){b=[p],q=!0;let I=O.map(ce=>`${ce}: ${c.stalledBackgroundAgentTasks.get(ce)}`).join("; ");m.push({role:"user",content:yc(O,{reason:I})}),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??u),enabledToolNamesBefore:C,enabledToolNamesAfter:k(b),suppressedToolNames:C.filter(ce=>ce!=="task"),nextAction:"cancel-stalled-background-task"},yield M("background_agent_no_output_watchdog_cancel_required",I);continue}b=[p],q=!0,m.push({role:"user",content:hc(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??u),enabledToolNamesBefore:C,enabledToolNamesAfter:k(b),suppressedToolNames:C.filter(I=>I!=="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=ye(L,K));if(se(i)&&!c.artifactContract.browserVerified&&Pt(c.artifactContract).length>0&&b.some(p=>p.function.name==="exec")&&c.browserAcceptanceRecoveryCount<4){let p=As(c.artifactContract);c={...c,browserAcceptanceRecoveryCount:c.browserAcceptanceRecoveryCount+1,messages:[...m,{role:"user",content:p}],transition:{reason:"next_turn"}},q=!0,yield M("browser_acceptance_required","forcing browser automation after localhost app URL was observed");continue}let y=Bc(c.maintainedDocuments);if(y.length>0&&c.benchmarkStateIntegrityRecoveryCount<Ic){let p=y.map(C=>`${Te(C.path)}: ${C.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: "+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"}},q=!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(Nc(c)){yield*G("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(ft){yield*G(ft);return}if(m.push(...gs({toolFailureCounts:c.toolFailureCounts,snapshot:li})),ai){let l=Me({inputMessages:i,messages:m,reason:`tool call budget exhausted (${ne}) before completing all required files`});if(l){yield*G(l);return}}Q=ht(Q,{replayMessages:m,completedToolCallIds:[...Q.completedToolCallIds,...W],lastStopReason:"tool_calls"}),e.toolChoice==="required"&&te.length>0&&(Ut=!0);let ci=te.length>0&&te.every(l=>{let d=m.find(y=>y?.role==="tool"&&y?.tool_call_id===l.id);if(!d)return!0;let g=d.content;return typeof g=="string"&&g.startsWith("Error: ")}),ke=c.consecutiveFailedRounds;if(ci){if(ke+=1,ke>=Yo){if(mo>=3&&c.repeatedToolFailureRecoveryCount<1){let y=Jn({inputMessages:i,messages:m,finalText:c.finalText,thinkingBlocks:[],stopHookActive:c.stopHookActive,totalToolCallCount:F,distinctToolNames:N,log:o});if(y?.reason==="explicit_required_file_verification"||y?.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:y.messages,stopHookActive:y.stopHookActive,transition:y.transition,consecutiveFailedRounds:0,repeatedToolFailureRecoveryCount:c.repeatedToolFailureRecoveryCount+1};continue}}if(c.repeatedToolFailureRecoveryCount<1){let y=Hr(m);if(y){yield M("repeated_tool_failure_self_correction","one help-guided self-correction round before ending on repeated tool failures"),c={...c,messages:[...m,y],consecutiveFailedRounds:0,repeatedToolFailureRecoveryCount:c.repeatedToolFailureRecoveryCount+1};continue}}let l=`repeated tool failures (${ke} rounds in a row)`,d=Me({inputMessages:i,messages:m,reason:`${l} before all required files were produced`})??(c.finalText.trim()?c.finalText:qn(m,ke)),g=Ms(d,{availableToolNames:k(a??u),enabledToolNames:$t(),toolCallNames:[...N].sort(),blockedToolCalls:At(D)});o.info(`early exit: ${ke} consecutive failed rounds, returning ${c.finalText?"partial":"fallback"} response`),yield*G(g);return}}else ke=0;let pt=[...c.fileReadCycleBlockedPaths].filter(l=>!c.fileReadCycleNudgedPaths.has(l));if(pt.length>0){let l=pt.join(", "),d=[...new Set(pt.map(no))].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 y of pt)c.fileReadCycleNudgedPaths.add(y)}let Ne=oe+1;if(v>0&&Ne>v){if(o.info(`max turns reached (${v}), completing`),R){let g=await R.invoke("stop",{sessionId:s,reason:"max_turns"});if(g.action==="abort"){let y=g.reason??"Stop hook requested continuation after max_turns",p={role:"assistant",content:c.finalText,...ae.length>0&&{thinkingBlocks:[...ae]}};c={...c,messages:[...m,p,{role:"user",content:y}],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}};continue}}let l=Me({inputMessages:i,messages:m,reason:`tool loop max turns reached (${v}) before completing all required files`});if(l){yield*G(l);return}let d=nt(m,`tool loop max turns reached (${v}) before completing the final status contract`);yield*G(d);return}if(Ft&&be(c).size>0&&Ne>j&&j<100&&(j=Math.min(100,Ne+25),o.info(`background task lifecycle wait extended round budget to ${j}`)),Ft&&Ne>j){let l=Hn({currentToolBudget:ne,currentRoundBudget:j,toolHardCap:100,roundHardCap:100,continuationCount:je,successfulSinceLastCheck:Ue-et,fileReadCounts:c.fileReadCounts,windowTools:ge,windowRounds:25});l&&(j=l.nextRoundBudget,ne=l.nextToolBudget,je=l.continuationCount,et=Ue,o.info(`round budget continuation #${l.continuationCount}: rounds\u2192${j}, tools\u2192${ne} (progress detected)`))}if(Ne>j){o.info(`tool loop budget exhausted (${j} rounds), returning`);let l=Qn({totalToolCallCount:F,distinctToolNames:N,projectRoot:e.projectRoot});l&&(yield{type:"skill_instruction",turnId:r,instruction:l});let d=Me({inputMessages:i,messages:m,reason:`tool budget exhausted (${j} rounds) before completing all required files`});if(d){yield*G(d);return}let g=nt(m,`tool budget exhausted (${j} rounds) before completing the final status contract`);yield*G(g);return}c={messages:m,maxOutputTokensRecoveryCount:0,hasAttemptedReactiveCompact:!1,maxOutputTokensOverride:void 0,turnCount:Ne,transition:{reason:"next_turn"},guardState:U,reactiveCompactState:J,toolLoopState:Q,consecutiveFailedRounds:ke,finalText:c.finalText,totalUsage:c.totalUsage,collapseStore:Wt,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:it,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:be(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 Hs(e){let t=cu(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: ${zs(o.l1Amount)}; L2 long-term says: ${zs(o.l2Amount)}; action: ask the user which value is current before using it.`)}for(let o of e){let r=fu(o);n.push(`- [${r}] ${o.text}`)}return n.join(`
|
|
43
|
-
`)}function
|
|
44
|
-
${
|
|
42
|
+
${l.result.content}`,b=X(d.id,{ok:!0,payload:g,imageUrls:l.result.imageUrls,toolReferences:l.result.toolReferences});m.push(b),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(Ye.some(l=>l.call.function.name==="exec"&&Ds(l.call.function.arguments))){let l=C(y);m.push({role:"user",content:Ic(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=lt.get(`${l.function.name}::${l.function.arguments}`),g=_t(m,l.function.name),b=xc(g),p=Oo.has(l.id)?Tu(d,l):b?`This exact tool call has been attempted ${d} times. Last error: ${b}. 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:p});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:p}}if(ue.length>0&&Ke.length===0&&Ye.length===0&&ue.every(l=>Oo.has(l.id))&&c.existingFileUpdateRecoveryCount<2){let l=C(y);y=Os(O,Y);let d=C(y);We=!0,U=!0;let g=[...new Set(ue.map(b=>Ft(b.function.arguments)).filter(b=>!!b))];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: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",g.join(",")||"unknown"),c={...c,messages:m,existingFileUpdateRecoveryCount:c.existingFileUpdateRecoveryCount+1,transition:{reason:"next_turn"}};continue}if(ue.length>0){let l=_t(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 gi=ho>=3&&c.repeatedToolFailureRecoveryCount<1;if(ue.length>0&&Ke.length===0&&Ye.length===0&&!gi){let l=$s(Hn(m,1),{availableToolNames:C(a??u),enabledToolNames:jt(),toolCallNames:[...L].sort(),blockedToolCalls:Et(D)});yield*W(l);return}let No=[],Zt=[];for(let l of Ke){let d=Fr({toolName:l.function.name,rawArguments:l.function.arguments});d?Zt.push({call:l,...d}):No.push(l)}for(let l of Zt){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}`)}Zt.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 hi=new Set(y.map(l=>l.function.name)),Lo=[],ct=[];for(let l of No){let d=Js(l.function.name,l.function.arguments,hi);d?ct.push({call:l,...d}):Lo.push(l)}for(let l of ct){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(ct.length>0){let l=C(y);y=Os(O,Y);let d=C(y);We=!0,U=!0;let g=[...new Set(ct.map(b=>b.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: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",g.join(",")||"unknown"),c={...c,messages:m,existingFileUpdateRecoveryCount:c.existingFileUpdateRecoveryCount+1,transition:{reason:"next_turn"}};continue}let Fo=[],Jt=[];for(let l of Lo){let d=Lr({state:c.artifactContract,inputMessages:i,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:"artifact-root-contract"}),Bn(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},Vt()&&(yield Wt()),o.warn(`artifact root contract blocked: ${d.function.name}`)}Jt.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 Bo=[],Qt=[];for(let l of Fo){let d=hs({inputMessages:i,messages:m,toolCall:l});d?Qt.push({call:l,error:d}):Bo.push(l)}for(let l of Qt){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}`)}Qt.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 yi=new Set(y.map(l=>l.function.name)),Do=[],ut=[];for(let l of Bo)yi.has(l.function.name)?Do.push(l):ut.push(l);for(let l of ut){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(ut.length>0&&c.notOfferedToolRecoveryCount<1){let l=[...new Set(ut.map(v=>v.function.name))].sort(),d=We&&l.includes("write"),g=l.filter(v=>Y.has(v)),p=(a??u).filter(v=>l.includes(v.function.name));if(g.length>0)c.notOfferedToolRecoveryCount+=1,U=!0,m.push({role:"user",content:`You retried ${g.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(y),enabledToolNamesAfter:C(y),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 v=C(y),H=new Map(y.map(k=>[k.function.name,k]));for(let k of p)H.set(k.function.name,k);y=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(y),suppressedToolNames:[],nextAction:"retry-with-reenabled-requested-tool"},m.push({role:"user",content:`You called ${l.map(k=>`\`${k}\``).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 $o=[],en=[];for(let l of Do){let d=y.find(b=>b.function.name===l.function.name),g=Lc(d,l.function.arguments);g?en.push({call:l,error:g}):$o.push(l)}for(let l of en){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}`)}en.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 dt=[],tn=[];for(let l of $o){if(l.function.name!=="exec"){dt.push(l);continue}let d=Ns(l.function.arguments);if(!d){dt.push(l);continue}let g=Ss(d);Ms(g)&&Ps(O)?tn.push({call:l,error:Nc(g)}):dt.push(l)}for(let l of tn){let d=l.call;D.push({name:d.function.name,reason:"dedicated-tool-required"});let g=C(y),b=y.filter(p=>["read","search"].includes(p.function.name));b.length>0&&(y=b,$t=!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:g,enabledToolNamesAfter:C(y),suppressedToolNames:g.filter(p=>!["read","search"].includes(p)),nextAction:"use-read-search-for-file-inspection-then-resume-build-run-verify-tools"}}tn.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 ft=[],nn=[],Uo=[],jo=[];for(let l of dt){if(l.function.name!=="exec"){ft.push(l);continue}let d=l,g=Ns(d.function.arguments),b=g?wc(g):null;b&&(d={...d,function:{...d.function,arguments:Fs(d.function.arguments,b)}},jo.push({originalCommand:g??"",rewrittenCommand:b}),g=b);let p=g?Ac(g):null;if(p?.action==="block")nn.push({call:d,error:p.error});else if(p?.action==="rewrite"){let v={...d,function:{...d.function,arguments:Fs(d.function.arguments,p.command)}};Uo.push({call:v,originalCommand:g??"",rewrittenCommand:p.command}),ft.push(v)}else ft.push(d)}for(let l of jo)yield{type:"tool_selection_policy",turnId:r,policyId:"exec_sleep_prefix_guard",intent:"verification",reason:"sleep-prefix-removed",availableToolNames:C(a??u),enabledToolNamesBefore:C(y),enabledToolNamesAfter:C(y),suppressedToolNames:[],nextAction:"execute-command-without-blocking-sleep-prefix"},o.info(`blocking sleep prefix removed before exec: ${l.originalCommand} -> ${l.rewrittenCommand}`);for(let l of Uo){let d=C(y);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(y),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 nn){let d=l.call;D.push({name:d.function.name,reason:"reserved-frontend-port"});let g=C(y);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:Ot}},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:g,enabledToolNamesAfter:C(y),suppressedToolNames:[],nextAction:"restart-generated-dev-server-on-explicit-non-5174-port-with-strict-port"}}nn.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 pt=[],Be=[];for(let l of ft){if(l.function.name!=="read"){pt.push(l);continue}let d=ao(l.function.arguments);if(!d){pt.push(l);continue}let g=G(d),b=Xs(g);(c.fileReadCounts.get(g)??0)>=b?Be.push({call:l,filePath:g,maxReads:b}):pt.push(l)}for(let l of Be){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. ${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: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(Be.length>0){let l=[...new Set(Be.map(b=>`${b.filePath} (max ${b.maxReads})`))].join(", "),d=[...new Set(Be.map(b=>ro(b.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.`}),y.some(b=>Us(b.function.name))&&(c.persistedBenchmarkStateRecovered||Be.some(b=>fo(b.filePath)))){let b=C(y),p=b.filter(v=>eu.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:b,enabledToolNamesAfter:C(y),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(iu(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 on=Rs(pt,c.toolFailureCounts),rn=on.allowed;if(Dt&&rn.length>Math.max(0,re-F)){let l=Wn({currentToolBudget:re,currentRoundBudget:q,toolHardCap:100,roundHardCap:100,continuationCount:Ge,successfulSinceLastCheck:He-ot,fileReadCounts:c.fileReadCounts,windowTools:ye,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 qo=Math.max(0,re-F),me=qo>0?rn.slice(0,qo):[],sn=rn.slice(me.length),bi=sn.length>0;if(on.blocked.length>0){for(let l of on.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(xs())}if(sn.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 sn){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 me){let d=l.function.arguments,g=y.find(b=>b.function.name===l.function.name);if(g?.backfillObservableInput)try{let b=JSON.parse(l.function.arguments),p={...b};g.backfillObservableInput(p),Object.keys(p).some(H=>!(H in b))&&(d=JSON.stringify(p))}catch{}yield{type:"tool_call",turnId:r,callId:l.id,name:l.function.name,arguments:d,inputSummary:Gn(d)}}let Ti=new Map(c.toolFailureCounts),mt=null;try{let l=e.runtimePorts.createStreamingToolExecutor({toolInvoker:n,hooks:R,sessionId:s,turnId:r,log:o,signal:_,maxConcurrentTools:e?.maxConcurrentTools,maxExecutionMs:or});for(let p of me)l.addTool(p);let d=!1;for await(let p of l.getRemainingResults()){let v=kc(p);if(v){if(D.push({name:p.toolName,reason:v}),p.toolName==="exec"&&v==="dedicated-tool-required"&&Ps(O)){let x=C(y);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(y),suppressedToolNames:[],nextAction:"use-read-search-for-file-inspection-or-exec-for-build-run-verify"}}if(p.toolName==="exec"&&v==="confirmation-timeout"){let x=C(y);Y.add("exec");let E=Te(O,Y);E.length>0&&(y=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(y),suppressedToolNames:oo(x,C(y)),nextAction:"continue-with-non-exec-tools-or-report-confirmation-blocker"}}if(p.toolName==="exec"&&v==="global-process-kill-blocked"){let x=C(y);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(y),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=jc(p,c);H||F++;let k=p.ok&&qn(p);if(p.ok&&!k&&!H&&(He+=1),H||_s({toolFailureCounts:c.toolFailureCounts,toolName:p.toolName,toolArguments:me.find(x=>x.id===p.callId)?.function.arguments,ok:p.ok,softEmpty:k}),p.ok&&Vc.has(p.toolName)&&Mu(c),p.ok&&Us(p.toolName)){let x=me.find(B=>B.id===p.callId),E=x?Ft(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:p.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(p.ok&&!k&&(so.has(p.toolName)||p.toolName==="exec"&&p.details?.type==="exec_background"||p.toolName==="exec"&&Ds(me.find(x=>x.id===p.callId)?.function.arguments??""))){let x=me.find(B=>B.id===p.callId),E=typeof p.message?.content=="string"?p.message.content:"";if(x&&E){let B=Array.isArray(p.message.imageUrls)?p.message.imageUrls.filter(he=>typeof he=="string"):void 0,ie=Array.isArray(p.message.toolReferences)?p.message.toolReferences.filter(he=>typeof he=="string"):void 0;c.identicalSuccessfulToolResults.set(`${x.function.name}::${x.function.arguments}`,{content:E,imageUrls:B,toolReferences:ie})}}if(p.toolName==="agent"){let x=Pe(p.details,"agentId"),E=Pe(p.details,"status"),B=Pt(p.details,"background");p.ok&&x&&B===!0&&E==="running"&&Ce(c).add(x)}if(p.toolName==="task"){let x=Wc(p.details);x&&(c.lastTaskList=x);let E=Pe(p.details,"taskId"),B=Pt(p.details,"running"),ie=Pe(p.details,"lifecycle"),he=Pe(p.details,"action");if(E&&(he==="cancel"||B===!1||ie&&ie!=="running"&&ie!=="pending"))Ce(c).delete(E),c.backgroundAgentNoOutputPollCounts.delete(E),c.stalledBackgroundAgentTasks.delete(E);else if(E&&he==="output"&&B===!0&&Ce(c).has(E)){let Go=typeof p.message?.content=="string"?p.message.content:"",Wo=Pt(p.details,"hasOutput");if(Wo!==void 0?Wo===!1:Hc(Go)){let an=(c.backgroundAgentNoOutputPollCounts.get(E)??0)+1;c.backgroundAgentNoOutputPollCounts.set(E,an);let ht=Bc(p.details,"elapsedSeconds")??Gc(Go);(ht!==void 0&&ht>=qc||ht===void 0&&an>=zc)&&c.stalledBackgroundAgentTasks.set(E,`no output after ${ht??"unknown"}s across ${an} poll(s)`)}else c.backgroundAgentNoOutputPollCounts.delete(E),c.stalledBackgroundAgentTasks.delete(E)}}if(p.ok&&p.toolName==="read"){let x=me.find(E=>E.id===p.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 he=typeof p.message?.content=="string"?p.message.content:"";d=yu(c,E,he,c.turnCount,p.details)||d}}}yield Ar(r,p);for(let x of Sr(r,p))yield x;for(let x of Mr({turnId:r,result:p,toolCalls:ne}))yield x;let oe=ne.find(x=>x.id===p.callId),ge=typeof p.message?.content=="string"?p.message.content:"";if(oe){Br({state:c.artifactContract,inputMessages:i,toolName:p.toolName,rawArguments:oe.function.arguments,ok:p.ok,content:ge}),Vt()&&(yield Wt());let x=Ec(p.toolName,oe.function.arguments);if(x){let E=(yo.get(x)??0)+1;if(yo.set(x,E),E===Mc){let B=x.startsWith("exec:")?"exec":"edit";c.recoveryTrace.set(`no_progress_observed:${B}`,(c.recoveryTrace.get(`no_progress_observed:${B}`)??0)+1)}}}!mt&&ii&&p.toolName==="stt"&&p.ok&&(mt=uc(i,p))}if(We&&(y=Te(O,Y),We=!1),$t&&(y=Te(O,Y),$t=!1),d){let p=pu(r,c.maintainedDocuments,c.fileReadCounts,c.turnCount);p&&(yield p);for(let k of hu(r,c.maintainedDocuments))yield k;let v=nu(c.maintainedDocuments,c.turnCount),H=y.some(k=>io.has(k.function.name));if(v&&H){c.benchmarkStateMaintenanceRequiredFiles=new Set(Zs(c.maintainedDocuments).map(G));for(let k of y)io.has(k.function.name)||Y.add(k.function.name);y=Te(y,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 g=Ce(c);if(g.size>0){let p=(a??u).find(v=>v.function.name==="task");if(p){let v=C(y),H=[...g].filter(k=>c.stalledBackgroundAgentTasks.has(k)).sort();if(H.length>0){y=[p],U=!0;let k=H.map(N=>`${N}: ${c.stalledBackgroundAgentTasks.get(N)}`).join("; ");m.push({role:"user",content:$c(H,{reason:k})}),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(y),suppressedToolNames:v.filter(N=>N!=="task"),nextAction:"cancel-stalled-background-task"},yield M("background_agent_no_output_watchdog_cancel_required",k);continue}y=[p],U=!0,m.push({role:"user",content:Dc(g)}),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(y),suppressedToolNames:v.filter(k=>k!=="task"),nextAction:"poll-existing-background-task-output"},yield M("background_agent_lifecycle_poll_required",[...g].sort().join(","));continue}}else y.length===1&&y[0]?.function.name==="task"&&(y=Te(O,Y));if(ae(i)&&!c.artifactContract.browserVerified&&Nt(c.artifactContract).length>0&&y.some(p=>p.function.name==="exec")&&c.browserAcceptanceRecoveryCount<4){let p=Bs(c.artifactContract);c={...c,browserAcceptanceRecoveryCount:c.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 b=su(c.maintainedDocuments);if(b.length>0&&c.benchmarkStateIntegrityRecoveryCount<Qc){let p=b.map(v=>`${ke(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: "+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(ou(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(mt){yield*W(mt);return}let zo=yc(i,m);if(zo){yield*vo(zo);return}let Ho=Tc(i,m);if(Ho){yield*vo(Ho);return}if(m.push(...vs({toolFailureCounts:c.toolFailureCounts,snapshot:Ti})),bi){let l=Ie({inputMessages:i,messages:m,reason:`tool call budget exhausted (${re}) before completing all required files`});if(l){yield*W(l);return}}ee=Tt(ee,{replayMessages:m,completedToolCallIds:[...ee.completedToolCallIds,...V],lastStopReason:"tool_calls"}),e.toolChoice==="required"&&ne.length>0&&(qt=!0);let Ci=ne.length>0&&ne.every(l=>{let d=m.find(b=>b?.role==="tool"&&b?.tool_call_id===l.id);if(!d)return!0;let g=d.content;return typeof g=="string"&&g.startsWith("Error: ")}),xe=c.consecutiveFailedRounds;if(Ci){if(xe+=1,xe>=rr){if(ho>=3&&c.repeatedToolFailureRecoveryCount<1){let b=eo({inputMessages:i,messages:m,finalText:c.finalText,thinkingBlocks:[],stopHookActive:c.stopHookActive,totalToolCallCount:F,distinctToolNames:L,log:o});if(b?.reason==="explicit_required_file_verification"||b?.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:b.messages,stopHookActive:b.stopHookActive,transition:b.transition,consecutiveFailedRounds:0,repeatedToolFailureRecoveryCount:c.repeatedToolFailureRecoveryCount+1};continue}}if(c.repeatedToolFailureRecoveryCount<1){let b=Jr(m);if(b){yield M("repeated_tool_failure_self_correction","one help-guided self-correction round before ending on repeated tool failures"),c={...c,messages:[...m,b],consecutiveFailedRounds:0,repeatedToolFailureRecoveryCount:c.repeatedToolFailureRecoveryCount+1};continue}}let l=`repeated tool failures (${xe} rounds in a row)`,d=Ie({inputMessages:i,messages:m,reason:`${l} before all required files were produced`})??(c.finalText.trim()?c.finalText:Hn(m,xe)),g=$s(d,{availableToolNames:C(a??u),enabledToolNames:jt(),toolCallNames:[...L].sort(),blockedToolCalls:Et(D)});o.info(`early exit: ${xe} consecutive failed rounds, returning ${c.finalText?"partial":"fallback"} response`),yield*W(g);return}}else xe=0;let gt=[...c.fileReadCycleBlockedPaths].filter(l=>!c.fileReadCycleNudgedPaths.has(l));if(gt.length>0){let l=gt.join(", "),d=[...new Set(gt.map(ro))].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 b of gt)c.fileReadCycleNudgedPaths.add(b)}let De=se+1;if(w>0&&De>w){if(o.info(`max turns reached (${w}), completing`),R){let g=await R.invoke("stop",{sessionId:s,reason:"max_turns"});if(g.action==="abort"){let b=g.reason??"Stop hook requested continuation after max_turns",p={role:"assistant",content:c.finalText,...ce.length>0&&{thinkingBlocks:[...ce]}};c={...c,messages:[...m,p,{role:"user",content:b}],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}};continue}}let l=Ie({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(Dt&&Ce(c).size>0&&De>q&&q<100&&(q=Math.min(100,De+25),o.info(`background task lifecycle wait extended round budget to ${q}`)),Dt&&De>q){let l=Wn({currentToolBudget:re,currentRoundBudget:q,toolHardCap:100,roundHardCap:100,continuationCount:Ge,successfulSinceLastCheck:He-ot,fileReadCounts:c.fileReadCounts,windowTools:ye,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=Ie({inputMessages:i,messages:m,reason:`tool budget exhausted (${q} rounds) before completing all required files`});if(d){yield*W(d);return}let g=st(m,`tool budget exhausted (${q} rounds) before completing the final status contract`);yield*W(g);return}c={messages:m,maxOutputTokensRecoveryCount:0,hasAttemptedReactiveCompact:!1,maxOutputTokensOverride:void 0,turnCount:De,transition:{reason:"next_turn"},guardState:j,reactiveCompactState:Q,toolLoopState:ee,consecutiveFailedRounds:xe,finalText:c.finalText,totalUsage:c.totalUsage,collapseStore:Xt,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:lt,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:Ce(c),backgroundAgentNoOutputPollCounts:c.backgroundAgentNoOutputPollCounts,stalledBackgroundAgentTasks:c.stalledBackgroundAgentTasks,notOfferedToolRecoveryCount:c.notOfferedToolRecoveryCount,existingFileUpdateRecoveryCount:c.existingFileUpdateRecoveryCount,taskListReconciliationCount:c.taskListReconciliationCount,lastTaskList:c.lastTaskList}}}var Eu=["\u63A5\u5355\u91D1\u989D","\u5408\u540C\u91D1\u989D","\u62A5\u4EF7","\u9884\u7B97","\u91D1\u989D","price","amount","contract amount"];function oi(e){let t=Iu(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: ${ni(o.l1Amount)}; L2 long-term says: ${ni(o.l2Amount)}; action: ask the user which value is current before using it.`)}for(let o of e){let r=Nu(o);n.push(`- [${r}] ${o.text}`)}return n.join(`
|
|
43
|
+
`)}function Iu(e){let t=e.filter(r=>r.source==="l1-project-md").flatMap(r=>ti(r.text)),n=e.filter(r=>r.source==="l2-long-term").flatMap(r=>ti(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 Lu(o)}function ti(e){let t=[];for(let n of e.split(/\r?\n/)){let o=n.trim();if(o)for(let r of Eu){if(r==="\u91D1\u989D"&&/(接单金额|合同金额)/u.test(o))continue;let s=new RegExp(`${Fu(r)}[^0-9.\u4E07kK,]{0,12}([0-9][0-9.,]*\\s*(?:\u4E07|k|K)?)`,"gi");for(let i of o.matchAll(s)){let a=Ou(i[1]);a!==null&&t.push({entity:Pu(o,r),predicate:r,amount:a,text:o})}}}return t}function Pu(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 Ou(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 Nu(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 ni(e){return Number.isInteger(e)?String(e):String(Number(e.toFixed(4)))}function Lu(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 Fu(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var Bu=8192;async function ri(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 T=0,R=[];for(let _ of f){let A=(_.text?.length??0)*2;if(T+A>Bu)break;R.push(_),T+=A}R.length>0&&(h=`[Recalled memories \u2014 context priority: project-specific facts override general user preferences when they conflict]
|
|
44
|
+
${oi(R)}`)}return $(t,"memory.after_recall",{sessionId:r,turnId:s,blockCount:f?.length??0},o),h}catch{return null}}var si=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,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=kn(r),T=[];if(a&&T.push({role:"system",content:a}),T.push(...h),this.hooks){let w=h.filter(S=>S.role==="user").pop(),P=typeof w?.content=="string"?w.content.slice(0,500):void 0;if(P){let S=await ri({hooks:this.hooks,detectRecallCategories:O=>this.runtimePorts.detectRecallCategories(O),log:this.log,sessionId:t.sessionId,turnId:o,query:P});S&&T.splice(a?1:0,0,{role:"system",content:S})}}let R=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:T,availableTools:s,tools:i,refreshTools:t.refreshTools,model:R,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 ei(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(w){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=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=${un(O)}]: ${P}`),$(this.hooks,"turn.failed",{...f,code:O,error:P},this.log),yield{type:"error",turnId:o,error:P,code:O}}}}};export{si as Agent};
|