qlogicagent 2.16.3 → 2.16.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/agent.js +21 -21
- package/dist/cli.js +352 -352
- package/dist/index.js +352 -352
- package/dist/types/agent/tool-loop/completion-action-policy.d.ts +2 -1
- package/dist/types/agent/tool-loop.d.ts +8 -1
- package/dist/types/protocol/wire/acp-protocol.d.ts +3 -0
- package/dist/types/runtime/infra/llmrouter-catalog.d.ts +10 -0
- package/package.json +1 -1
package/dist/agent.js
CHANGED
|
@@ -1,45 +1,45 @@
|
|
|
1
|
-
function rn(e,t,n,o){return{role:"assistant",content:t||null,tool_calls:e,...n&&n.length>0?{thinkingBlocks:n}:{},...o?{reasoning_content:o}:{}}}function G(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 fi=/\b(?:daily|weekly|monthly)(?:\/(?:daily|weekly|monthly))* (?:usage )?limit(?:s)?(?: (?:exhausted|reached|exceeded))?\b/i,Re={rateLimit:[/rate[_ ]limit|too many requests|429/,"model_cooldown","exceeded your current quota","resource has been exhausted","quota exceeded","resource_exhausted","usage limit",/\btpm\b/i,"tokens per minute","tokens per day"],overloaded:[/overloaded_error|"type"\s*:\s*"overloaded_error"/i,"overloaded",/service[_ ]unavailable.*(?:overload|capacity|high[_ ]demand)|(?:overload|capacity|high[_ ]demand).*service[_ ]unavailable/i,"high demand"],timeout:["timeout","timed out","service unavailable","deadline exceeded","context deadline exceeded","connection error","network error","network request failed","fetch failed","socket hang up",/\beconn(?:refused|reset|aborted)\b/i,/\benotfound\b/i,/\beai_again\b/i,/without sending (?:any )?chunks?/i,/\bstop reason:\s*(?:abort|error|network_error)\b/i,/\breason:\s*(?:abort|error|network_error)\b/i,/\bunhandled stop reason:\s*(?:abort|error|network_error)\b/i],billing:[/["']?(?:status|code)["']?\s*[:=]\s*402\b|\bhttp\s*402\b|\berror(?:\s+code)?\s*[:=]?\s*402\b|\b(?:got|returned|received)\s+(?:a\s+)?402\b|^\s*402\s+payment/i,"payment required","insufficient credits",/insufficient[_ ]quota/i,"credit balance","plans & billing","insufficient balance"],authPermanent:[/api[_ ]?key[_ ]?(?:revoked|invalid|deactivated|deleted)/i,"invalid_api_key","key has been disabled","key has been revoked","account has been deactivated",/could not (?:authenticate|validate).*(?:api[_ ]?key|credentials)/i,"permission_error","not allowed for this organization"],auth:[/invalid[_ ]?api[_ ]?key/,"incorrect api key","invalid token","authentication","re-authenticate","oauth token refresh failed","unauthorized","forbidden","access denied","insufficient permissions","insufficient permission",/missing scopes?:/i,"expired","token has expired",/\b401\b/,/\b403\b/,"no credentials found","no api key found"],format:["string should match pattern","tool_use.id","tool_use_id","messages.1.content.1.tool_use.id","invalid request format",/tool call id was.*must be/i]},pi=/^(?:error[:\s-]+)?billing(?:\s+error)?(?:[:\s-]+|$)|^(?:error[:\s-]+)?(?:credit balance|insufficient credits?|payment required|http\s*402\b)/i,mi=/["']?(?:status|code)["']?\s*[:=]\s*402\b|\bhttp\s*402\b|\berror(?:\s+code)?\s*[:=]?\s*402\b|^\s*402\s+payment/i,gi=512,hi=/^(?:http\s*)?(\d{3})(?:\s+([\s\S]+))?$/i;var yi=new Set([500,502,503,504,521,522,523,524,529]),bi=["insufficient credits","insufficient quota","credit balance","insufficient balance","plans & billing","add more credits","top up"],Ti=["upgrade your plan","upgrade plan","current plan","subscription"],Ci=["daily","weekly","monthly"],ki=["try again","retry","temporary","cooldown"],Ri=["usage limit","rate limit","organization usage"],xi=["organization","workspace"],_i=["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,wi=/^(?:error[:\s-]+)?(?:(?:http\s*)?402(?:\s+payment required)?|payment required)(?:[:\s-]+|$)/i;function xe(e,t){if(!e)return!1;let n=e.toLowerCase();return t.some(o=>o instanceof RegExp?o.test(n):n.includes(o))}function Ai(e){return xe(e,Re.format)}function Uo(e){return xe(e,Re.rateLimit)}function Si(e){return xe(e,Re.timeout)}function Mi(e){return fi.test(e)}function sn(e){let t=e.toLowerCase();return t?e.length>gi?mi.test(t):xe(t,Re.billing)?!0:pi.test(e)?t.includes("upgrade")||t.includes("credits")||t.includes("payment")||t.includes("plan"):!1:!1}function jo(e){return xe(e,Re.authPermanent)}function Ei(e){return xe(e,Re.auth)}function qo(e){return xe(e,Re.overloaded)}function ke(e,t){return t.some(n=>e.includes(n))}function Ii(e){return ke(e,bi)||ke(e,Ti)&&e.includes("limit")||e.includes("billing hard limit")||e.includes("hard limit reached")||e.includes("maximum allowed")&&e.includes("limit")}function Pi(e){let t=ke(e,Ci),n=e.includes("spend limit")||e.includes("spending limit"),o=ke(e,xi);return ke(e,ki)&&ke(e,Ri)||t&&(e.includes("usage limit")||n)||t&&e.includes("limit")&&e.includes("reset")||o&&e.includes("limit")&&(n||ke(e,_i))}function Li(e){return e.trim().toLowerCase().replace(wi,"").trim()}function zo(e){let t=Li(e);return!t||Ii(t)?"billing":Uo(t)||Pi(t)?"rate_limit":"billing"}function Oi(e){return vi.test(e)?zo(e):null}function Ho(e){let t=e.match(hi);if(!t)return null;let n=Number(t[1]);return Number.isFinite(n)?{code:n,rest:(t[2]??"").trim()}:null}function Ni(e){if(!e)return!1;let t=e.toLowerCase();return t.includes('"type":"api_error"')&&t.includes("internal server error")}function Fi(e){let t=e.trim();if(!t)return!1;let n=Ho(t);return n?yi.has(n.code):!1}function Go(e,t){return typeof e!="number"||!Number.isFinite(e)?null:e===402?t?zo(t):"billing":e===429?"rate_limit":e===401||e===403?t&&jo(t)?"auth_permanent":"auth":e===408?"timeout":e===503?t&&qo(t)?"overloaded":"timeout":e===502||e===504?"timeout":e===529?"overloaded":e===400?t&&sn(t)?"billing":"format":null}function Bi(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 Di(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 Wo(e){if(Di(e))return"session_expired";if(Bi(e))return"model_not_found";let t=Oi(e);return t||(Mi(e)?sn(e)?"billing":"rate_limit":Uo(e)?"rate_limit":qo(e)?"overloaded":Fi(e)?Ho(e.trim())?.code===529?"overloaded":"timeout":Ni(e)?"timeout":Ai(e)?"format":sn(e)?"billing":Si(e)?"timeout":jo(e)?"auth_permanent":Ei(e)?"auth":null)}var $i={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"},Ui=new Set(["RETRYABLE_TRANSIENT","RETRYABLE_DEGRADED","TOOL_EXECUTION_FAILED"]);function Le(e,t){let n=Go(e,t)??(t?Wo(t):null);return n?$i[n]:typeof e=="number"&&e>=400&&e<500?"NON_RETRYABLE_CONTENT":"RETRYABLE_TRANSIENT"}function an(e){return Ui.has(e)}function Vo(e){let t=typeof e.content=="string"?e.content:e.content!=null?JSON.stringify(e.content):"";return Math.ceil(t.length/4)}var ji=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"]),Ge=class{constructor(t=20,n=Vo){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((l,u)=>{if(u>=o||l.role!=="tool"||typeof l.content!="string"||!l.name||!ji.has(l.name)||l.content.length<=200)return l;let p=this.estimateTokens(l);return s+=p,r++,{...l,content:`[result cleared \u2014 ${l.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 ln(e,t,n=Vo){if(t.size===0)return{messages:e,tokensFreed:0,removedCount:0};let o=0,r=0,s=[];for(let l of e){let u=l.tool_call_id??"";if(u&&t.has(u)){o+=n(l),r++,t.delete(u);continue}s.push(l)}let i=r>0?{role:"system",content:`[${r} messages removed by snip]`}:void 0;return{messages:s,tokensFreed:o,removedCount:r,boundaryMessage:i}}function cn(){return{stages:[]}}function un(e,t,n){let o=n?.thresholdMessages??40;if(e.filter(l=>l.role!=="system").length<=o)return{messages:e,stagedCount:0};let s=Ko(e,t),i=qi(s,t,o);if(i.length===0)return{messages:s,stagedCount:0};for(let l of i)t.stages.push(l);return s=Ko(e,t),{messages:s,stagedCount:i.length}}function dn(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 Ko(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 l=Math.min(i,o.length),u={role:"system",content:r.summary};o.splice(s,l-s,u)}return o}function qi(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,l=0;for(let u=0;u<o;u++){let p=e[u];if(p.role==="tool"||p.role==="assistant"&&typeof p.content=="string"&&p.content==="")i<0&&(i=u),l++;else{if(l>=3){let b=`${i}-${i+l}`;s.has(b)||r.push({id:`collapse_${i}_${i+l}`,range:[i,i+l],summary:`[${l} tool results collapsed]`,committed:!1})}i=-1,l=0}}if(l>=3){let u=`${i}-${i+l}`;s.has(u)||r.push({id:`collapse_${i}_${i+l}`,range:[i,i+l],summary:`[${l} tool results collapsed]`,committed:!1})}return r}import{existsSync as pn,readFileSync as gr,writeFileSync as zi,readdirSync as hr,mkdirSync as Hi}from"node:fs";import{join as mn,dirname as Gi}from"node:path";var ge=Math.min(Math.max(1,Number(process.env.TOOL_LOOP_DEFAULT_BUDGET)||25),100),Yo=Math.max(1e3,Number(process.env.TOOL_LOOP_TOOL_TIMEOUT_MS)||24e4),Zo=3,Jo=2,ft=2,Qo=128e3,er=13e3,tr=16384,nr=65536,or=3,rr=65536,fn=500,sr=3;var ir=3e4,ar=3,_e=2;var lr=20;var cr=3,ur=2,dr=300*1e3,fr=3,pr=720*60*60*1e3;var Cu=300*1e3;var ku=3600*1e3;var Ru=50*1024,xu=500*1024,_u=500*1024*1024,vu=50*1024*1024;var wu=60*1024;var yr=0;var Wi="skill-patterns.json";function br(e){return mn(e,".qlogicagent",Wi)}function Vi(e){let t=br(e);try{return JSON.parse(gr(t,"utf8"))}catch{return{version:1,patterns:{}}}}function mr(e,t){let n=br(e);Hi(Gi(n),{recursive:!0}),zi(n,JSON.stringify(t,null,2),"utf8")}function Ki(e){let t=Date.now()-pr;for(let[n,o]of Object.entries(e.patterns))new Date(o.lastSeen).getTime()<t&&delete e.patterns[n]}function Tr(e,t){if(t.length===0)return!1;let n=pt(t),o=Vi(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 mr(e,o),!1;s.count++,s.lastSeen=r;let i=s.count>=fr;return i&&(s.promoted=!0),mr(e,o),i}function pt(e){return[...e].sort().join("+")}function Xi(e,t){if(!pn(t))return null;let n=pt(e);try{let o=hr(t,{withFileTypes:!0});for(let r of o){if(!r.isDirectory())continue;let s=mn(t,r.name,"SKILL.md");try{let l=gr(s,"utf8").match(/^tools:\s*\n((?:\s+-\s+\S+\n?)+)/m);if(l){let u=l[1].split(`
|
|
2
|
-
`).map(p=>p.replace(/^\s*-\s*/,"").trim()).filter(Boolean);if(pt(u)===n)return r.name}}catch{}}}catch{}return null}function Yi(e){if(!pn(e))return 0;try{return hr(e,{withFileTypes:!0}).filter(t=>t.isDirectory()&&pn(mn(e,t.name,"SKILL.md"))).length}catch{return 0}}function Zi(e,t){return!(!e.ok||e.existingSkillName||!e.multiStep||e.toolCallCount<cr||e.distinctToolCount<ur||Date.now()-yr<dr||t?.projectSkillsDir&&(Yi(t.projectSkillsDir)>=lr||t.tools.length>0&&Xi(t.tools,t.projectSkillsDir))||t?.projectRoot&&t.tools.length>0&&!Tr(t.projectRoot,t.tools))}function Ji(e){return e.existingSkillName?e.feedback==="negative":!1}function gn(e,t){return Ji(e)?{type:"skill.improve",skillName:e.existingSkillName,reason:"negative user feedback on existing skill execution"}:Zi(e,t)?(yr=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 Qi(e){let t=new Set(e.map(hn).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 hn(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 ea(e){return e==="enabled-eligible"||e==="installed-awaiting-approval"}function ta(e){return new Map((e??[]).map(t=>[t.toolName,t]))}function na(e){if(!e.eligibility?.length)return[...e.tools];let t=ta(e.eligibility);return e.tools.filter(n=>{let o=hn(n);if(!o)return!1;let r=t.get(o);return!r||ea(r.status)})}function oa(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=oa({toolChoice:e.toolChoice,thinkingEnabled:e.thinkingEnabled,compatibility:e.compatibility}),n=t.normalizedToolChoice,o=[...t.warnings],r=na({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:Qi(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 l=r.filter(u=>hn(u)===i);if(l.length===0)throw new Error(`tool_choice requested unknown tool: ${i}`);return{tools:l,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 ra=["stop","aborted","timeout","cancelled","interrupted","error"],sa=["tool_calls","toolCalls","function_call","functionCall","raw_tool_calls","rawToolCalls"];function Cr(e){return e==null?[]:typeof e=="string"?e.length>0?[{type:"text",text:e}]:[]:Array.isArray(e)?e:[{type:"text",text:String(e)}]}function ia(e,t){return{...e,content:[...Cr(e.content),...Cr(t.content)]}}function aa(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 la(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=aa(r);if(s.size!==0)for(let i=o+1;i<e.length;i+=1){if(t.has(i))continue;let l=e[i];l?.role==="tool"&&typeof l.tool_call_id=="string"&&s.has(l.tool_call_id)&&(n.push(l),t.add(i))}}return n}function ca(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 ua(e){return new Set((e??ra).map(t=>t.trim().toLowerCase()))}function da(e,t){return e?ua(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 p=u.tool_calls.filter(h=>ca(h));return{...u,...p.length>0?{tool_calls:p}:{tool_calls:void 0}}}return{...u}}),n=new Set;for(let u of t)if(!(u.role!=="assistant"||!Array.isArray(u.tool_calls)))for(let p of u.tool_calls)typeof p.id=="string"&&p.id&&n.add(p.id);let o=t.filter(u=>u.role!=="tool"?!0:!!(u.tool_call_id&&n.has(u.tool_call_id))),r=new Set;for(let u of o)u.role==="tool"&&typeof u.tool_call_id=="string"&&u.tool_call_id&&r.add(u.tool_call_id);let s=[];for(let u of o){if(u.role==="assistant"&&Array.isArray(u.tool_calls)&&u.tool_calls.length>0){let p=u.tool_calls.filter(h=>typeof h.id=="string"&&r.has(h.id));if(p.length===0){let{tool_calls:h,...b}=u;b.content!=null&&b.content!==""&&s.push(b);continue}if(p.length<u.tool_calls.length){s.push({...u,tool_calls:p});continue}}s.push(u)}let i=la(s),l=[];for(let u of i){let p=l.length>0?l[l.length-1]:void 0;if(u.role==="user"&&p?.role==="user"){l[l.length-1]=ia(p,u);continue}l.push(u)}return l}function Tn(e,t){return da(t?.stopReason,t?.forcedStopReasons)?e.map(n=>{if(n.role!=="assistant")return{...n};let o={...n};for(let r of sa)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 fa(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 pa(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 ma(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 mt(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 gt(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:ma({maxRounds:e.maxRounds,round:e.round,lastStopReason:e.lastStopReason,replayMessages:r,pendingToolCallIds:fa(r),completedToolCallIds:pa(r)}),recoveryActions:t}}var ga=new Set(["main","sdk","agent","compact","hook","verification","side_question"]);function xn(e){return e?ga.has(e):!0}function _n(e){return e===429||e===529}function ht(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 Du={maxBackoffMs:300*1e3,resetCapMs:360*60*1e3,heartbeatIntervalMs:3e4};function yt(){let e=process.env.QLOGICAGENT_PERSISTENT_RETRY;return e==="1"||e==="true"}var We=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 ya={maxConsecutiveFailures:3,minMessagesAfterCompact:4,targetUsagePercent:50};function En(){return{consecutiveFailures:0,attemptedThisTurn:!1,lastCompactAt:null,toolsAtLastCompact:[]}}function Oe(e,t=ya){return!(e.attemptedThisTurn||e.consecutiveFailures>=t.maxConsecutiveFailures)}import{createHash as zl}from"node:crypto";import{existsSync as Be,readFileSync as uo}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 D(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 kr(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,l=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:l,stdout:s,stderr:i,details:r}}function Rr(e,t){if(!t.ok)return[];let n=t.details;if(!n)return[];let o=ba(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 ba(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 Ta=new Set(["write","edit","patch"]);function xr(e){let{turnId:t,result:n,toolCalls:o}=e;if(!n.ok)return[];let r=o.find(l=>l.id===n.callId);if(!r)return[];let s=[],i=Ca(r.function.arguments);if(!i)return s;if(Ta.has(n.toolName)){let l=ka(i);l&&s.push({type:"artifact",turnId:t,artifactId:`artifact-${n.callId}`,artifactType:Ra(l),title:l.split(/[\\/]/).pop()||l,filePath:l,language:xa(l)})}return s}function Ca(e){try{return JSON.parse(e)}catch{return null}}function ka(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 Ra(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 xa(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 _a=new Set(["write","edit","patch"]),va=new Set(["image_generate"]),wa=/\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 Aa=/\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,Sa=/\b(?:fatal|timeout|timed out|waitforselector|waiting for locator|strict mode violation|exception|traceback|eaddrinuse|page crashed|browser closed|target closed)\b|鏃犳硶灏唡閿欒|澶辫触|瓒呮椂/i,Ma=/\b(?:default vite|vite \+ react|edit src\/app|click on the vite|vite page)\b|默认\s*Vite/i,_r=/\b(?:browser|playwright|puppeteer|screenshot|opened|loaded|navigated|visible|locator|page\.goto|http:\/\/127\.0\.0\.1|http:\/\/localhost)\b|(?:浏览器|截图|页面可见|打开页面|加载页面|内置浏览器|自动化)/i;function Ea(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 ie(e){return e.some(t=>t.role==="user"&&typeof t.content=="string"&&wa.test(t.content))}var Ia=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 Nn(e){return e.some(t=>t.role==="user"&&typeof t.content=="string"&&Ia.test(t.content))}function Pa(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 vr(e){return["Done","Not done","Artifacts","Verification","Blockers","Next action"].every(t=>new RegExp(`(^|\\n)${t}:`,"i").test(e))}function Sr(e){return["Sourced facts","Assumptions","Recommendations","Unsupported claims"].every(t=>new RegExp(`(^|\\n)${t}:`,"i").test(e))}function Fn(e,t){let n=Nr(t);return n?_a.has(e)?wr(n.path,n.file_path,n.filePath,n.filename,n.file):va.has(e)?wr(n.output_path,Array.isArray(n.output_paths)?n.output_paths[0]:void 0):null:null}function Mr(e){let t=Fn(e.toolName,e.rawArguments);if(!t||!ie(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=Fr(t),e.state.rootSource=e.state.artifactRoot?"inferred":void 0)}let n=e.state.artifactRoot;if(!n||e.state.rootSource!=="explicit"||Dr(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 Er(e){let t=Fn(e.toolName,e.rawArguments);return!t||!Va(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 Ir(e){let t=Fn(e.toolName,e.rawArguments);if(t){if(!e.state.artifactRoot){let o=Un(e.inputMessages);e.state.artifactRoot=o??Fr(t),e.state.rootSource=o?"explicit":e.state.artifactRoot?"inferred":void 0}e.state.writePaths.includes(t)||e.state.writePaths.push(t),ie(e.inputMessages)&&e.state.artifactRoot&&e.state.rootSource==="explicit"&&!Dr(t,e.state.artifactRoot)&&Bn(e.state,{path:t,artifactRoot:e.state.artifactRoot,toolName:e.toolName})}let n=`${e.rawArguments}
|
|
3
|
-
${e.content}`;for(let o of n.matchAll(
|
|
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 G(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 pi=/\b(?:daily|weekly|monthly)(?:\/(?:daily|weekly|monthly))* (?:usage )?limit(?:s)?(?: (?:exhausted|reached|exceeded))?\b/i,Re={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]},mi=/^(?:error[:\s-]+)?billing(?:\s+error)?(?:[:\s-]+|$)|^(?:error[:\s-]+)?(?:credit balance|insufficient credits?|payment required|http\s*402\b)/i,gi=/["']?(?:status|code)["']?\s*[:=]\s*402\b|\bhttp\s*402\b|\berror(?:\s+code)?\s*[:=]?\s*402\b|^\s*402\s+payment/i,hi=512,yi=/^(?:http\s*)?(\d{3})(?:\s+([\s\S]+))?$/i;var bi=new Set([500,502,503,504,521,522,523,524,529]),Ti=["insufficient credits","insufficient quota","credit balance","insufficient balance","plans & billing","add more credits","top up"],Ci=["upgrade your plan","upgrade plan","current plan","subscription"],ki=["daily","weekly","monthly"],Ri=["try again","retry","temporary","cooldown"],xi=["usage limit","rate limit","organization usage"],_i=["organization","workspace"],vi=["billing period","exceeded","reached","exhausted"],wi=/["']?(?: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,Ai=/^(?:error[:\s-]+)?(?:(?:http\s*)?402(?:\s+payment required)?|payment required)(?:[:\s-]+|$)/i;function xe(e,t){if(!e)return!1;let n=e.toLowerCase();return t.some(o=>o instanceof RegExp?o.test(n):n.includes(o))}function Si(e){return xe(e,Re.format)}function qo(e){return xe(e,Re.rateLimit)}function Mi(e){return xe(e,Re.timeout)}function Ei(e){return pi.test(e)}function an(e){let t=e.toLowerCase();return t?e.length>hi?gi.test(t):xe(t,Re.billing)?!0:mi.test(e)?t.includes("upgrade")||t.includes("credits")||t.includes("payment")||t.includes("plan"):!1:!1}function zo(e){return xe(e,Re.authPermanent)}function Ii(e){return xe(e,Re.auth)}function Ho(e){return xe(e,Re.overloaded)}function ke(e,t){return t.some(n=>e.includes(n))}function Pi(e){return ke(e,Ti)||ke(e,Ci)&&e.includes("limit")||e.includes("billing hard limit")||e.includes("hard limit reached")||e.includes("maximum allowed")&&e.includes("limit")}function Oi(e){let t=ke(e,ki),n=e.includes("spend limit")||e.includes("spending limit"),o=ke(e,_i);return ke(e,Ri)&&ke(e,xi)||t&&(e.includes("usage limit")||n)||t&&e.includes("limit")&&e.includes("reset")||o&&e.includes("limit")&&(n||ke(e,vi))}function Li(e){return e.trim().toLowerCase().replace(Ai,"").trim()}function Go(e){let t=Li(e);return!t||Pi(t)?"billing":qo(t)||Oi(t)?"rate_limit":"billing"}function Ni(e){return wi.test(e)?Go(e):null}function Wo(e){let t=e.match(yi);if(!t)return null;let n=Number(t[1]);return Number.isFinite(n)?{code:n,rest:(t[2]??"").trim()}:null}function Fi(e){if(!e)return!1;let t=e.toLowerCase();return t.includes('"type":"api_error"')&&t.includes("internal server error")}function Bi(e){let t=e.trim();if(!t)return!1;let n=Wo(t);return n?bi.has(n.code):!1}function Vo(e,t){return typeof e!="number"||!Number.isFinite(e)?null:e===402?t?Go(t):"billing":e===429?"rate_limit":e===401||e===403?t&&zo(t)?"auth_permanent":"auth":e===408?"timeout":e===503?t&&Ho(t)?"overloaded":"timeout":e===502||e===504?"timeout":e===529?"overloaded":e===400?t&&an(t)?"billing":"format":null}function Di(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 $i(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 Ko(e){if($i(e))return"session_expired";if(Di(e))return"model_not_found";let t=Ni(e);return t||(Ei(e)?an(e)?"billing":"rate_limit":qo(e)?"rate_limit":Ho(e)?"overloaded":Bi(e)?Wo(e.trim())?.code===529?"overloaded":"timeout":Fi(e)?"timeout":Si(e)?"format":an(e)?"billing":Mi(e)?"timeout":zo(e)?"auth_permanent":Ii(e)?"auth":null)}var Ui={timeout:"RETRYABLE_TRANSIENT",overloaded:"RETRYABLE_TRANSIENT",rate_limit:"RETRYABLE_DEGRADED",auth:"NON_RETRYABLE_AUTH",auth_permanent:"NON_RETRYABLE_AUTH",billing:"NON_RETRYABLE_QUOTA",format:"NON_RETRYABLE_CONTENT",model_not_found:"NON_RETRYABLE_CONTENT",session_expired:"NON_RETRYABLE_CONTENT",unknown:"RETRYABLE_TRANSIENT"},ji=new Set(["RETRYABLE_TRANSIENT","RETRYABLE_DEGRADED","TOOL_EXECUTION_FAILED"]);function Oe(e,t){let n=Vo(e,t)??(t?Ko(t):null);return n?Ui[n]:typeof e=="number"&&e>=400&&e<500?"NON_RETRYABLE_CONTENT":"RETRYABLE_TRANSIENT"}function ln(e){return ji.has(e)}function Xo(e){let t=typeof e.content=="string"?e.content:e.content!=null?JSON.stringify(e.content):"";return Math.ceil(t.length/4)}var qi=new Set(["file_read","read","Read","bash","shell","Bash","grep","search","Grep","grep_search","glob","Glob","file_search","web_search","WebSearch","web_fetch","WebFetch","file_edit","edit","Edit","file_write","write","Write"]),Ve=class{constructor(t=20,n=Xo){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((l,u)=>{if(u>=o||l.role!=="tool"||typeof l.content!="string"||!l.name||!qi.has(l.name)||l.content.length<=200)return l;let p=this.estimateTokens(l);return s+=p,r++,{...l,content:`[result cleared \u2014 ${l.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=Xo){if(t.size===0)return{messages:e,tokensFreed:0,removedCount:0};let o=0,r=0,s=[];for(let l of e){let u=l.tool_call_id??"";if(u&&t.has(u)){o+=n(l),r++,t.delete(u);continue}s.push(l)}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(l=>l.role!=="system").length<=o)return{messages:e,stagedCount:0};let s=Yo(e,t),i=zi(s,t,o);if(i.length===0)return{messages:s,stagedCount:0};for(let l of i)t.stages.push(l);return s=Yo(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:Zo(e,t),committed:n}}function Yo(e,t){return t.stages.filter(o=>o.committed).length===0?e:Zo(e,t)}function Zo(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 l=Math.min(i,o.length),u={role:"system",content:r.summary};o.splice(s,l-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,l=0;for(let u=0;u<o;u++){let p=e[u];if(p.role==="tool"||p.role==="assistant"&&typeof p.content=="string"&&p.content==="")i<0&&(i=u),l++;else{if(l>=3){let b=`${i}-${i+l}`;s.has(b)||r.push({id:`collapse_${i}_${i+l}`,range:[i,i+l],summary:`[${l} tool results collapsed]`,committed:!1})}i=-1,l=0}}if(l>=3){let u=`${i}-${i+l}`;s.has(u)||r.push({id:`collapse_${i}_${i+l}`,range:[i,i+l],summary:`[${l} tool results collapsed]`,committed:!1})}return r}import{existsSync as mn,readFileSync as yr,writeFileSync as Hi,readdirSync as br,mkdirSync as Gi}from"node:fs";import{join as gn,dirname as Wi}from"node:path";var ge=Math.min(Math.max(1,Number(process.env.TOOL_LOOP_DEFAULT_BUDGET)||25),100),Jo=Math.max(1e3,Number(process.env.TOOL_LOOP_TOOL_TIMEOUT_MS)||24e4),Qo=3,er=2,pt=2,tr=128e3,nr=13e3,or=16384,rr=65536,sr=3,ir=65536,pn=500,ar=3;var lr=3e4,cr=3,_e=2;var ur=20;var dr=3,fr=2,pr=300*1e3,mr=3,gr=720*60*60*1e3;var xu=300*1e3;var _u=3600*1e3;var vu=50*1024,wu=500*1024,Au=500*1024*1024,Su=50*1024*1024;var Mu=60*1024;var Tr=0;var Vi="skill-patterns.json";function Cr(e){return gn(e,".qlogicagent",Vi)}function Ki(e){let t=Cr(e);try{return JSON.parse(yr(t,"utf8"))}catch{return{version:1,patterns:{}}}}function hr(e,t){let n=Cr(e);Gi(Wi(n),{recursive:!0}),Hi(n,JSON.stringify(t,null,2),"utf8")}function Xi(e){let t=Date.now()-gr;for(let[n,o]of Object.entries(e.patterns))new Date(o.lastSeen).getTime()<t&&delete e.patterns[n]}function kr(e,t){if(t.length===0)return!1;let n=mt(t),o=Ki(e);Xi(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 hr(e,o),!1;s.count++,s.lastSeen=r;let i=s.count>=mr;return i&&(s.promoted=!0),hr(e,o),i}function mt(e){return[...e].sort().join("+")}function Yi(e,t){if(!mn(t))return null;let n=mt(e);try{let o=br(t,{withFileTypes:!0});for(let r of o){if(!r.isDirectory())continue;let s=gn(t,r.name,"SKILL.md");try{let l=yr(s,"utf8").match(/^tools:\s*\n((?:\s+-\s+\S+\n?)+)/m);if(l){let u=l[1].split(`
|
|
2
|
+
`).map(p=>p.replace(/^\s*-\s*/,"").trim()).filter(Boolean);if(mt(u)===n)return r.name}}catch{}}}catch{}return null}function Zi(e){if(!mn(e))return 0;try{return br(e,{withFileTypes:!0}).filter(t=>t.isDirectory()&&mn(gn(e,t.name,"SKILL.md"))).length}catch{return 0}}function Ji(e,t){return!(!e.ok||e.existingSkillName||!e.multiStep||e.toolCallCount<dr||e.distinctToolCount<fr||Date.now()-Tr<pr||t?.projectSkillsDir&&(Zi(t.projectSkillsDir)>=ur||t.tools.length>0&&Yi(t.tools,t.projectSkillsDir))||t?.projectRoot&&t.tools.length>0&&!kr(t.projectRoot,t.tools))}function Qi(e){return e.existingSkillName?e.feedback==="negative":!1}function hn(e,t){return Qi(e)?{type:"skill.improve",skillName:e.existingSkillName,reason:"negative user feedback on existing skill execution"}:Ji(e,t)?(Tr=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 ea(e){let t=new Set(e.map(yn).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 yn(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 ta(e){return e==="enabled-eligible"||e==="installed-awaiting-approval"}function na(e){return new Map((e??[]).map(t=>[t.toolName,t]))}function oa(e){if(!e.eligibility?.length)return[...e.tools];let t=na(e.eligibility);return e.tools.filter(n=>{let o=yn(n);if(!o)return!1;let r=t.get(o);return!r||ta(r.status)})}function ra(e){let t=[],n=e.compatibility??{},o=e.toolChoice;if(e.thinkingEnabled&&n.requireAutoWhenThinking){let r=typeof o=="object"&&o&&!Array.isArray(o)?String(o.type??""):o;r&&r!=="auto"&&r!=="none"&&(t.push("tool_choice downgraded to auto because thinking mode requires auto/none compatibility."),o="auto")}if(o==="required"&&n.allowRequiredToolChoice===!1){let r=n.requiredFallback??"auto";t.push(`tool_choice=required is not supported by this provider; downgraded to ${r}.`),o=r}if(o&&typeof o=="object"&&!Array.isArray(o)&&o.type==="function"&&n.allowNamedToolChoice===!1){let r=n.namedFallback??"required";t.push(`named tool_choice is not supported by this provider; downgraded to ${r}.`),o=r}return{normalizedToolChoice:o,warnings:t}}function bn(e){let t=ra({toolChoice:e.toolChoice,thinkingEnabled:e.thinkingEnabled,compatibility:e.compatibility}),n=t.normalizedToolChoice,o=[...t.warnings],r=oa({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:ea(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 l=r.filter(u=>yn(u)===i);if(l.length===0)throw new Error(`tool_choice requested unknown tool: ${i}`);return{tools:l,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 sa=["stop","aborted","timeout","cancelled","interrupted","error"],ia=["tool_calls","toolCalls","function_call","functionCall","raw_tool_calls","rawToolCalls"];function Rr(e){return e==null?[]:typeof e=="string"?e.length>0?[{type:"text",text:e}]:[]:Array.isArray(e)?e:[{type:"text",text:String(e)}]}function aa(e,t){return{...e,content:[...Rr(e.content),...Rr(t.content)]}}function la(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 ca(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=la(r);if(s.size!==0)for(let i=o+1;i<e.length;i+=1){if(t.has(i))continue;let l=e[i];l?.role==="tool"&&typeof l.tool_call_id=="string"&&s.has(l.tool_call_id)&&(n.push(l),t.add(i))}}return n}function ua(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 da(e){return new Set((e??sa).map(t=>t.trim().toLowerCase()))}function fa(e,t){return e?da(t).has(e.trim().toLowerCase()):!1}function Tn(e){if(!Array.isArray(e)||e.length===0)return[...e];let t=e.map(u=>{if(u.role==="assistant"&&Array.isArray(u.tool_calls)){let p=u.tool_calls.filter(y=>ua(y));return{...u,...p.length>0?{tool_calls:p}:{tool_calls:void 0}}}return{...u}}),n=new Set;for(let u of t)if(!(u.role!=="assistant"||!Array.isArray(u.tool_calls)))for(let p of u.tool_calls)typeof p.id=="string"&&p.id&&n.add(p.id);let o=t.filter(u=>u.role!=="tool"?!0:!!(u.tool_call_id&&n.has(u.tool_call_id))),r=new Set;for(let u of o)u.role==="tool"&&typeof u.tool_call_id=="string"&&u.tool_call_id&&r.add(u.tool_call_id);let s=[];for(let u of o){if(u.role==="assistant"&&Array.isArray(u.tool_calls)&&u.tool_calls.length>0){let p=u.tool_calls.filter(y=>typeof y.id=="string"&&r.has(y.id));if(p.length===0){let{tool_calls:y,...b}=u;b.content!=null&&b.content!==""&&s.push(b);continue}if(p.length<u.tool_calls.length){s.push({...u,tool_calls:p});continue}}s.push(u)}let i=ca(s),l=[];for(let u of i){let p=l.length>0?l[l.length-1]:void 0;if(u.role==="user"&&p?.role==="user"){l[l.length-1]=aa(p,u);continue}l.push(u)}return l}function Cn(e,t){return fa(t?.stopReason,t?.forcedStopReasons)?e.map(n=>{if(n.role!=="assistant")return{...n};let o={...n};for(let r of ia)delete o[r];return o}):[...e]}function kn(e,t){let n=t?.placeholderToolResult??"Error: Tool loop interrupted before the tool result was replayed.",o=new Set;for(let s of e)s.role==="tool"&&typeof s.tool_call_id=="string"&&s.tool_call_id&&o.add(s.tool_call_id);let r=[];for(let s of e)if(r.push({...s}),!(s.role!=="assistant"||!Array.isArray(s.tool_calls)||s.tool_calls.length===0))for(let i of s.tool_calls)typeof i.id!="string"||!i.id||o.has(i.id)||(o.add(i.id),r.push({role:"tool",tool_call_id:i.id,content:n}));return r}function Rn(e,t){let n=Tn(e),o=Cn(n,t);return kn(o,t)}function pa(e){let t=new Set,n=new Set;for(let o of e){if(o.role==="assistant"&&Array.isArray(o.tool_calls))for(let r of o.tool_calls)typeof r.id=="string"&&r.id&&t.add(r.id);o.role==="tool"&&typeof o.tool_call_id=="string"&&o.tool_call_id&&n.add(o.tool_call_id)}return[...t].filter(o=>!n.has(o))}function ma(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 ga(e){return{round:e.round??0,maxRounds:e.maxRounds,pendingToolCallIds:[...e.pendingToolCallIds??[]],completedToolCallIds:[...e.completedToolCallIds??[]],lastStopReason:e.lastStopReason,replayMessages:[...e.replayMessages??[]]}}function xn(e,t){return{round:e.round+1,maxRounds:e.maxRounds,pendingToolCallIds:[...t.pendingToolCallIds??e.pendingToolCallIds],completedToolCallIds:[...t.completedToolCallIds??e.completedToolCallIds],lastStopReason:t.lastStopReason??e.lastStopReason,replayMessages:[...t.replayMessages??e.replayMessages]}}function gt(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 ht(e){let t=[],n=Tn(e.replayMessages);n.length!==e.replayMessages.length&&t.push({kind:"drop-orphan-tool-result",detail:"Removed orphan tool results or invalid assistant tool calls."});let o=Cn(n,e.options);o.some((s,i)=>s!==n[i])&&t.push({kind:"strip-forced-stop-tool-metadata",detail:"Removed assistant tool-call metadata after forced stop."});let r=kn(o,e.options);return r.length>o.length&&t.push({kind:"inject-placeholder-tool-result",detail:"Injected placeholder tool result for pending tool calls."}),{state:ga({maxRounds:e.maxRounds,round:e.round,lastStopReason:e.lastStopReason,replayMessages:r,pendingToolCallIds:pa(r),completedToolCallIds:ma(r)}),recoveryActions:t}}var ha=new Set(["main","sdk","agent","compact","hook","verification","side_question"]);function _n(e){return e?ha.has(e):!0}function vn(e){return e===429||e===529}function yt(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 ju={maxBackoffMs:300*1e3,resetCapMs:360*60*1e3,heartbeatIntervalMs:3e4};function bt(){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 wn(e){return{promptTokens:0,hasAttemptedReactiveCompact:!1,currentMaxOutputTokens:e.maxOutputTokens,consecutiveTruncations:0,aborted:e.abortSignal?.aborted??!1}}function An(e,t){if(e.aborted)return{level:"blocking",usagePercent:100,reason:"budget_exhausted"};let n=t.contextWindowTokens-t.responseBufferTokens-e.currentMaxOutputTokens,o=n>0?e.promptTokens/n*100:100;return e.promptTokens>=n?e.hasAttemptedReactiveCompact||!t.reactiveCompactEnabled?{level:"blocking",usagePercent:o,reason:"prompt_too_long"}:{level:"blocking",usagePercent:o,reason:"prompt_too_long"}:o>=85?{level:"warning",usagePercent:o,remainingTokens:n-e.promptTokens}:{level:"ok"}}function Sn(e,t,n){let o=e.message?.toLowerCase()??"",r=e.status??0;return r===413||o.includes("prompt_too_long")||o.includes("context_length_exceeded")?!t.hasAttemptedReactiveCompact&&n.reactiveCompactEnabled?{action:"reactive_compact"}:{action:"abort",reason:"prompt_too_long_unrecoverable"}:r>=500&&r<600?{action:"retry",reason:`server_error_${r}`}:r===429?{action:"retry",reason:"rate_limited"}:r===401||r===403?{action:"abort",reason:"auth_error"}:r===404?{action:"abort",reason:"model_not_found"}:{action:"abort",reason:o||"unknown_error"}}function Mn(e,t,n){if(!t.outputEscalationEnabled)return{shouldEscalate:!1,newMax:e.currentMaxOutputTokens};if(e.consecutiveTruncations>=3)return{shouldEscalate:!1,newMax:e.currentMaxOutputTokens};let o=Math.min(e.currentMaxOutputTokens*2,n);return o<=e.currentMaxOutputTokens?{shouldEscalate:!1,newMax:e.currentMaxOutputTokens}:{shouldEscalate:!0,newMax:o}}function En(e,t){return e.aborted?!0:t.abortSignal?.aborted?(e.aborted=!0,!0):!1}var ba={maxConsecutiveFailures:3,minMessagesAfterCompact:4,targetUsagePercent:50};function In(){return{consecutiveFailures:0,attemptedThisTurn:!1,lastCompactAt:null,toolsAtLastCompact:[]}}function Le(e,t=ba){return!(e.attemptedThisTurn||e.consecutiveFailures>=t.maxConsecutiveFailures)}import{createHash as Wl}from"node:crypto";import{existsSync as $e,readFileSync as po}from"node:fs";function Pn(e,t){let n=e.get(t.index)??{id:"",name:"",arguments:""};t.id&&(n.id=t.id),t.name&&(n.name=t.name),n.arguments+=t.arguments??"",e.set(t.index,n)}function D(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 xr(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,l=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:l,stdout:s,stderr:i,details:r}}function _r(e,t){if(!t.ok)return[];let n=t.details;if(!n)return[];let o=Ta(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 Ta(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 Ca=new Set(["write","edit","patch"]);function vr(e){let{turnId:t,result:n,toolCalls:o}=e;if(!n.ok)return[];let r=o.find(l=>l.id===n.callId);if(!r)return[];let s=[],i=ka(r.function.arguments);if(!i)return s;if(Ca.has(n.toolName)){let l=Ra(i);l&&s.push({type:"artifact",turnId:t,artifactId:`artifact-${n.callId}`,artifactType:xa(l),title:l.split(/[\\/]/).pop()||l,filePath:l,language:_a(l)})}return s}function ka(e){try{return JSON.parse(e)}catch{return null}}function Ra(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 xa(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 _a(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 va=new Set(["write","edit","patch"]),wa=new Set(["image_generate"]),Aa=/\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 Sa=/\b(?:under|inside|in|at|to|root|directory|folder|output directory|output folder)\s+([A-Za-z]:[\\/][^\s"'`<>|]+)|(?:目录|文件夹|根目录|输出到|放到|位于)\s*([A-Za-z]:[\\/][^\s"'`<>|]+)/gi,On=/https?:\/\/[^\s"'`<>),;]+/gi,Ma=/\b(?:fatal|timeout|timed out|waitforselector|waiting for locator|strict mode violation|exception|traceback|eaddrinuse|page crashed|browser closed|target closed)\b|鏃犳硶灏唡閿欒|澶辫触|瓒呮椂/i,Ea=/\b(?:default vite|vite \+ react|edit src\/app|click on the vite|vite page)\b|默认\s*Vite/i,wr=/\b(?:browser|playwright|puppeteer|screenshot|opened|loaded|navigated|visible|locator|page\.goto|http:\/\/127\.0\.0\.1|http:\/\/localhost)\b|(?:浏览器|截图|页面可见|打开页面|加载页面|内置浏览器|自动化)/i;function Ia(e){let t=jn(e);return{artifactRoot:t,rootSource:t?"explicit":void 0,writePaths:[],outOfRootWrites:[],devServerUrls:[],browserVerified:!1,browserEvidence:[],browserFailureEvidence:[],buildVerified:!1,buildEvidence:[],buildFailureEvidence:[]}}function ie(e){return e.some(t=>t.role==="user"&&typeof t.content=="string"&&Aa.test(t.content))}var Pa=new RegExp(["\\b(?:tests?|test suite|unit tests?|the suite|build|compiles?|compilation|typecheck|lint)\\b[\\s\\S]{0,24}\\b(?:pass(?:es|ing)?|green|succeed(?:s|ed)?|clean|work(?:s|ing)?)\\b","\\b(?:pass(?:es|ing)?|green|succeed(?:s|ed)?)\\b[\\s\\S]{0,16}\\b(?:tests?|the suite|build)\\b","\\bfix(?:es|ing)?\\b[\\s\\S]{0,24}\\b(?:failing|broken)\\b[\\s\\S]{0,12}\\b(?:tests?|build|spec)\\b","\\bmake it (?:build|compile|pass)\\b","\\b(?:run|rerun|re-run) (?:the )?(?:tests?|test suite|build|spec)\\b","\\b(?:npm (?:test|run build)|pnpm (?:test|build)|yarn (?:test|build)|pytest|go test|cargo (?:test|build)|vitest|jest|gradle|mvn)\\b","(?:\u8BA9|\u4F7F|\u786E\u4FDD)[\\s\\S]{0,12}(?:\u6D4B\u8BD5|\u5355\u6D4B|\u7528\u4F8B|\u6784\u5EFA|\u7F16\u8BD1)[\\s\\S]{0,8}(?:\u901A\u8FC7|\u8DD1\u901A|\u6210\u529F|\u7EFF)","(?:\u4FEE\u590D|\u4FEE\u597D|\u89E3\u51B3)[\\s\\S]{0,12}(?:\u5931\u8D25\u7684?\u6D4B\u8BD5|\u6D4B\u8BD5\u5931\u8D25|\u7F16\u8BD1\u9519\u8BEF|\u6784\u5EFA\u9519\u8BEF|\u7F16\u8BD1\u62A5\u9519|\u62A5\u9519)","\u6D4B\u8BD5\u901A\u8FC7|\u8DD1\u901A\u6D4B\u8BD5|\u7F16\u8BD1\u901A\u8FC7|\u6784\u5EFA\u901A\u8FC7|\u901A\u8FC7(?:\u5168\u90E8|\u6240\u6709)?\u6D4B\u8BD5|\u8BA9\u6D4B\u8BD5\u53D8\u7EFF"].join("|"),"i");function Fn(e){return e.some(t=>t.role==="user"&&typeof t.content=="string"&&Pa.test(t.content))}function Oa(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 Ar(e){return["Done","Not done","Artifacts","Verification","Blockers","Next action"].every(t=>new RegExp(`(^|\\n)${t}:`,"i").test(e))}function Er(e){return["Sourced facts","Assumptions","Recommendations","Unsupported claims"].every(t=>new RegExp(`(^|\\n)${t}:`,"i").test(e))}function Bn(e,t){let n=Br(t);return n?va.has(e)?Sr(n.path,n.file_path,n.filePath,n.filename,n.file):wa.has(e)?Sr(n.output_path,Array.isArray(n.output_paths)?n.output_paths[0]:void 0):null:null}function Ir(e){let t=Bn(e.toolName,e.rawArguments);if(!t||!ie(e.inputMessages))return null;if(!e.state.artifactRoot){let r=jn(e.inputMessages);r?(e.state.artifactRoot=r,e.state.rootSource="explicit"):(e.state.artifactRoot=Dr(t),e.state.rootSource=e.state.artifactRoot?"inferred":void 0)}let n=e.state.artifactRoot;if(!n||e.state.rootSource!=="explicit"||Ur(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 Pr(e){let t=Bn(e.toolName,e.rawArguments);return!t||!Ka(t)?null:{path:t,error:`Read-only context-pack blocked ${e.toolName}: attempted to write ${t}. Context packs are source evidence; write document indexes, checkpoints, and maintenance updates under benchmark-state instead.`}}function Dn(e,t){e.writePaths.includes(t.path)||e.writePaths.push(t.path),e.outOfRootWrites.some(n=>n.path===t.path&&n.toolName===t.toolName)||e.outOfRootWrites.push(t)}function Or(e){let t=Bn(e.toolName,e.rawArguments);if(t){if(!e.state.artifactRoot){let o=jn(e.inputMessages);e.state.artifactRoot=o??Dr(t),e.state.rootSource=o?"explicit":e.state.artifactRoot?"inferred":void 0}e.state.writePaths.includes(t)||e.state.writePaths.push(t),ie(e.inputMessages)&&e.state.artifactRoot&&e.state.rootSource==="explicit"&&!Ur(t,e.state.artifactRoot)&&Dn(e.state,{path:t,artifactRoot:e.state.artifactRoot,toolName:e.toolName})}let n=`${e.rawArguments}
|
|
3
|
+
${e.content}`;for(let o of n.matchAll(On)){let r=Nn(o[0]);r&&(e.state.devServerUrls.includes(r)||e.state.devServerUrls.push(r))}if(qa(e.toolName,e.rawArguments,e.content)&&$r(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&&ja(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(Ga(e.toolName,e.rawArguments))if(!e.ok||Wa(e.content)){e.state.buildVerified=!1;let r=e.content.trim().slice(0,500);r&&!e.state.buildFailureEvidence.includes(r)&&e.state.buildFailureEvidence.push(r)}else{e.state.buildVerified=!0,e.state.buildFailureEvidence=[];let r=e.content.trim().slice(0,300);r&&!e.state.buildEvidence.includes(r)&&e.state.buildEvidence.push(r)}}function $n(e,t){return{artifactRoot:e.artifactRoot,writePaths:[...e.writePaths],outOfRootWrites:[...e.outOfRootWrites],devServerUrls:[...e.devServerUrls],browserVerified:e.browserVerified,browserEvidence:[...e.browserEvidence],browserFailureEvidence:[...e.browserFailureEvidence],requiresBrowserAcceptance:ie(t)}}function Lr(e){let t=Ia(e);for(let n of e)n.role!=="assistant"||typeof n.content!="string"||Un(t,n.content);return t}function Un(e,t){let n=t.match(/(?:^|\n)\s*-\s*artifactRoot:\s*([^\n]+)/i)?.[1]?.trim();n&&!/not declared/i.test(n)&&!e.artifactRoot&&(e.artifactRoot=he(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=he(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 l=he(i.trim());l&&!e.writePaths.includes(l)&&e.writePaths.push(l)}let s=t.match(/(?:^|\n)\s*-\s*urls:\s*([^\n]+)/i)?.[1]?.trim();if(s&&!/none recorded/i.test(s))for(let i of s.matchAll(On)){let l=Nn(i[0]);l&&!e.devServerUrls.includes(l)&&e.devServerUrls.push(l)}for(let i of t.matchAll(On)){let l=Nn(i[0]);l&&/^https?:\/\/(?:localhost|127\.0\.0\.1):\d+\//i.test(l)&&(e.devServerUrls.includes(l)||e.devServerUrls.push(l))}}function Nr(e){let t=e.content.trim(),n=ie(e.inputMessages),o=Oa(e.inputMessages),r=Fn(e.inputMessages),s=Xa(t),i=t;if(Fr(e.activeTasks??[]).length>0&&(i=Fa(i)),n&&!e.artifactContract.browserVerified&&(i=Ba(i)),r&&!e.artifactContract.buildVerified&&(i=Da(i)),!(s&&e.totalToolCallCount===0)&&o&&!Er(i)){let y=Ua(i);i=i?`${i}
|
|
4
4
|
|
|
5
|
-
${
|
|
5
|
+
${y}`:y}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)&&!Ar(i)&&!Ar(i)){let y=La({...e,content:i,needsBrowser:n,needsResearch:o,needsBuild:r});i=i?`${i}
|
|
6
6
|
|
|
7
|
-
${
|
|
8
|
-
`)}function
|
|
9
|
-
`)}function
|
|
10
|
-
${n}`),s=
|
|
7
|
+
${y}`:y}return i}function La(e){let t=[],n=[],o=Fr(e.activeTasks??[]);if(o.length>0&&(n.push(`Task list still has ${o.length} unresolved item(s): ${o.map(Na).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(p=>`${p.toolName} attempted ${p.path} outside ${p.artifactRoot}.`))),e.needsBrowser&&!e.artifactContract.browserVerified){let p=e.artifactContract.browserFailureEvidence[0];n.push(p?"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(p?`Fix the browser verification failure before claiming completion: ${p}`:"Load the served app in a browser-capable tool and verify visible UI behavior before claiming completion.")}if(e.needsBuild&&!e.artifactContract.buildVerified){let p=e.artifactContract.buildFailureEvidence[0];n.push(p?"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(p?`Fix the code and re-run the test/build until it passes (do not edit the test): ${p.slice(0,200)}`:"Run the project's test/build command and confirm it exits 0 before claiming completion.")}e.needsResearch&&!Er(e.content)&&n.push("Research/report quality audit sections were not separated in the model response.");let r=$a(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(p=>`${p.name} blocked by ${p.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: ${he(e.artifactContract.artifactRoot)}`:"artifactRoot: not declared",e.artifactContract.writePaths.length>0?`files: ${e.artifactContract.writePaths.slice(0,8).map(he).join(", ")}`:"files: no write paths recorded",e.artifactContract.devServerUrls.length>0?`urls: ${e.artifactContract.devServerUrls.join(", ")}`:"urls: none recorded"],l=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(p=>`- ${p}`):["- None recorded."],"","Artifacts:",...i.map(p=>`- ${p}`),"","Verification:",`- ${l}`,"","Blockers:",...t.length>0?t.map(p=>`- ${p}`):["- None recorded."],"","Next action:",`- ${u}`].join(`
|
|
8
|
+
`)}function Fr(e){return e.filter(t=>t.status!=="completed")}function Na(e){return`#${e.id} ${e.title} (${e.status})`}function Fa(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 Ba(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 Da(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 $a(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 Ua(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(`
|
|
9
|
+
`)}function Br(e){try{return JSON.parse(e)}catch{return null}}function Sr(...e){for(let t of e)if(typeof t=="string"&&t.trim())return t.trim();return null}function jn(e){for(let t of e)if(!(t.role!=="user"||typeof t.content!="string"))for(let n of t.content.matchAll(Sa)){let o=n[1]??n[2],r=Tt(o??"");if(r&&!Va(r))return he(r)}}function Dr(e){let t=he(Tt(e));if(!t)return;let n=t.toLowerCase();if(n.endsWith("/package.json"))return Mr(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 Mr(t)}function ja(e,t,n){if(/^read$/i.test(e)||n.includes("<persisted-output>")||$r(n)||/\b(?:syntax error|command not found|cannot find|not recognized|failed|failure|exception|traceback|eaddrinuse)\b|无法将|错误|失败/i.test(n))return!1;let o=wr.test(n),r=/\b(?:playwright|puppeteer|browser|screenshot|locator|page\.goto|dom snapshot|visible text|assertion)\b|浏览器|截图|可见|定位器/i.test(`${t}
|
|
10
|
+
${n}`),s=qn(e)&&wr.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)||Ea.test(n)&&!/\b(?:absent|removed|not present|gone|没有|不是默认|已移除)\b/i.test(n))}function qa(e,t,n){return/^read$/i.test(e)||!qn(e)?!1:/\b(?:playwright|puppeteer|browser|screenshot|locator|page\.goto|dom snapshot|visible text|assertion|waitforselector|test-browser|browser verification)\b|浏览器|截图|页面可见|打开页面|加载页面|内置浏览器|自动化/i.test(t)?!0:/\b(?:page\.waitForSelector|waitforselector|strict mode violation|browser closed|target closed|page crashed|locator\(|locator\.)\b/i.test(n)}function $r(e){return/\b(?:no failed|0 failed|without failed|no failures|failure:? none|failed checks?:? none)\b/i.test(e)?!1:Ma.test(e)?!0:/\b(?:fail|failed|failure|error)\b/i.test(e)}function qn(e){return/^(?:exec|bash|shell|powershell|terminal|playwright|browser|computer)$/i.test(e)}var za=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 Ha(e){let t=Br(e);return t&&typeof t.command=="string"?t.command:""}function Ga(e,t){return qn(e)?za.test(Ha(t)):!1}function Wa(e){return/\[exit [1-9]\d*\b|\(exit code [1-9]\d*\b|\[interrupted — exit code [1-9]\d*/.test(e)}function Va(e){return/\.[A-Za-z0-9]{1,12}$/.test(e)}function Ur(e,t){let n=Ln(e),o=Ln(t);return n===o||n.startsWith(`${o}/`)}function Ka(e){return Ln(e).split("/").includes("context-pack")}function Ln(e){return Tt(e).replace(/\\/g,"/").replace(/\/+/g,"/").replace(/\/$/u,"").toLowerCase()}function he(e){return Tt(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 Tt(e){return e.trim().replace(/[).,;:,。;、:]+$/u,"")}function Xa(e){return/^[A-Z0-9_ -]{6,80}$/.test(e.trim())}function Mr(e){let t=he(e),n=t.lastIndexOf("/");return n>0?t.slice(0,n):t}var Ya=/^no (matches|files|results) found(?:\s+for:.*)?\.?$|^file not found|^not found|^0 results|^\(exit code \d+, no output\)$/i,Za=new Set(["search","web_search","grep","glob","find","list","read","exec"]),Ja=/[A-Za-z]:[\\/](?:[^\s"'`<>|,\uFF0C\u3001;\uFF1B\u3002]+[\\/])*[^\s"'`<>|,\uFF0C\u3001;\uFF1B\u3002]+\.[A-Za-z0-9]{1,12}/g,Qa=/(?:^|[\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,el=/(?:^|[\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,tl=/\b(?:create|generate|write|produce|save|output|deliver|deliverables?|artifacts?|required|required files?|must generate|self-verify)\b|(?:生成|创建|写入|输出|保存|交付|产物|文件|必须|自检|验证)/i;function jr(e){if(!Za.has(e.toolName))return!1;let t=typeof e.message?.content=="string"?e.message.content.trim():"";return t.length>0&&t.length<200&&Ya.test(t)}function Ct(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 nl=/\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,qr=50,zr=90;function Hr(e){if(!e)return!1;for(let t of e)if(t.role==="user"&&typeof t.content=="string"&&nl.test(t.content))return!0;return!1}var ol=/(?:我来|我先|我现在就?|让我先?|接下来我?|我帮你|我这就|我会|我将|我去|我看)[^。.!?!?\n]{0,12}(?:做|搭建?|写|开发|实现|构建|生成|创建|新建|建立|改|修复?|检查|读取?|运行|跑|执行|看一?下?|查看|配置|安装|部署|分析|整理|定位|排查|找)/,rl=/\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 Gr(e){let t=e.trim();return t.length===0||t.length>200||t.includes("```")?!1:ol.test(t)||rl.test(t)}function Wr(e,t){if(typeof e=="number"&&Number.isFinite(e)&&e>=1)return Math.min(Math.round(e),100);let n=kt(t);return n>=3?Math.min(Math.max(25,20+n*15),100):ie(t??[])?Math.min(Math.max(25,zr),100):Hr(t)?Math.min(Math.max(25,qr),100):25}function kt(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(Ja))o(i[0]);if(tl.test(s)){for(let i of s.matchAll(Qa)){let l=i[1]?.toLowerCase();if(!l)continue;t.add(`relative:${l.replace(/\\/g,"/")}`);let u=l.replace(/\\/g,"/").split("/").pop();u&&n.add(u)}for(let i of s.matchAll(el)){let l=i[1]?.toLowerCase();!l||n.has(l)||t.add(`name:${l}`)}}}return t.size}function Vr(e,t){if(typeof e=="number"&&Number.isFinite(e)&&e>=1)return Math.min(Math.round(e),100);let n=kt(t);return n>=3?Math.min(Math.max(ge,20+n*15),100):ie(t??[])?Math.min(Math.max(ge,zr),100):Hr(t)?Math.min(Math.max(ge,qr),100):ge}function Kr(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(`
|
|
11
11
|
|
|
12
|
-
`)):""}function
|
|
12
|
+
`)):""}function Hn(e,t){let n=Ct(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}
|
|
13
13
|
|
|
14
14
|
\u6700\u540E\u4E00\u6B21\u5DE5\u5177\u9519\u8BEF\uFF1A
|
|
15
15
|
${n}
|
|
16
16
|
|
|
17
17
|
\u8BF7\u6839\u636E\u4E0A\u9762\u7684\u9519\u8BEF\u4FEE\u6B63\u540E\u91CD\u8BD5\uFF0C\u6216\u6362\u4E00\u79CD\u5B9E\u73B0\u65B9\u5F0F\u3002`:`${o}
|
|
18
18
|
|
|
19
|
-
\u8BF7\u91CD\u8BD5\uFF0C\u6216\u6362\u4E00\u79CD\u5B9E\u73B0\u65B9\u5F0F\u3002`}function
|
|
19
|
+
\u8BF7\u91CD\u8BD5\uFF0C\u6216\u6362\u4E00\u79CD\u5B9E\u73B0\u65B9\u5F0F\u3002`}function Xr(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 l=i;if(l.id!==n)continue;let u=l.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
|
|
20
20
|
|
|
21
21
|
`+(o?`\u6700\u540E\u4E00\u6B21\u8C03\u7528\uFF1A${o}
|
|
22
22
|
`:"")+`\u6700\u540E\u4E00\u6B21\u9519\u8BEF\uFF1A
|
|
23
23
|
${t}
|
|
24
24
|
|
|
25
|
-
\u8BF7\u6309\u9519\u8BEF\u4FE1\u606F\u7EA0\u6B63\u540E\u518D\u91CD\u8BD5\uFF1A\u5982\u679C\u662F\u547D\u4EE4\u884C\u5DE5\u5177\uFF0C\u5148\u7528\u5B83\u81EA\u5E26\u7684\u5E2E\u52A9\u786E\u8BA4\u6B63\u786E\u7684\u5B50\u547D\u4EE4/\u53C2\u6570/\u8BED\u6CD5\uFF08\u5982 \`<\u5DE5\u5177> --help\` \u6216 \`<\u5DE5\u5177> help <\u5B50\u547D\u4EE4>\`\uFF09\uFF0C\u4E0D\u8981\u51ED\u76F4\u89C9\u62FC\u547D\u4EE4\uFF1B\u6216\u6362\u4E00\u79CD\u5B9E\u73B0\u65B9\u5F0F\u3002`}}function
|
|
26
|
-
`,t),e.lastIndexOf(";",t),e.lastIndexOf("\u3002",t),e.lastIndexOf("\uFF1B",t))+1,r=e.slice(o,t).toLowerCase();if(/\b(?:do\s+not|don't|never)\s+(?:leave|create|write|include|keep|produce|add|generate)\b/i.test(r)||/\b(?:remove|delete|exclude)\b/i.test(r))return!0;let s=e.slice(Math.max(0,t-16),t+n.length);return new RegExp(`\\bno\\s+${
|
|
27
|
-
`).replace(/\\/g,"/").toLowerCase()}function
|
|
25
|
+
\u8BF7\u6309\u9519\u8BEF\u4FE1\u606F\u7EA0\u6B63\u540E\u518D\u91CD\u8BD5\uFF1A\u5982\u679C\u662F\u547D\u4EE4\u884C\u5DE5\u5177\uFF0C\u5148\u7528\u5B83\u81EA\u5E26\u7684\u5E2E\u52A9\u786E\u8BA4\u6B63\u786E\u7684\u5B50\u547D\u4EE4/\u53C2\u6570/\u8BED\u6CD5\uFF08\u5982 \`<\u5DE5\u5177> --help\` \u6216 \`<\u5DE5\u5177> help <\u5B50\u547D\u4EE4>\`\uFF09\uFF0C\u4E0D\u8981\u51ED\u76F4\u89C9\u62FC\u547D\u4EE4\uFF1B\u6216\u6362\u4E00\u79CD\u5B9E\u73B0\u65B9\u5F0F\u3002`}}function 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 Yr(e){return e==="length"||e==="max_tokens"}function Kn(e){let t=e.message.toLowerCase();return(t.includes("image")||t.includes("media")||t.includes("file too large")||t.includes("payload too large"))&&(e.status===413||t.includes("too large")||t.includes("size"))}function Zr(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 Jr(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*Qr(e){let{messages:t,contentReplacementState:n,snipRemovedIds:o,collapseStore:r,guardConfig:s,runtimePorts:i,hooks:l,hookCtx:u,sessionId:p,currentModel:y,log:b,recovery:k,onAutocompact:I}=e,P;{let x=await i.enforceToolResultBudget(t,n,p);P=x.messages,x.newlyReplacedCount>0&&(b.info(`tool-result-budget: persisted ${x.newlyReplacedCount} oversized tool results`),yield k("tool_result_budget",`${x.newlyReplacedCount} persisted`))}{let x=cn(P,o);P=x.messages,x.removedCount>0&&(b.info(`snip: removed ${x.removedCount} messages, freed ~${x.tokensFreed} tokens`),yield k("snip",`${x.removedCount} messages`))}{let E=new Ve().compress(P,0);E.droppedCount>0&&(P=E.messages,b.info(`microcompact: cleared ${E.droppedCount} old tool results`))}if(P=dn(P,r).messages,s.contextWindowTokens>0){let x=s.contextWindowTokens*.75,E=i.getActiveContextCompressionEngine(),w;E?w=await E.compressAsync(P,x,{model:y,sessionId:p}):w=i.compressMessages(P,{budget:x,model:y}),w.droppedCount>0&&(P=w.messages,b.info(`autocompact: ${w.strategy}, dropped ${w.droppedCount}`),yield k("autocompact",`${w.strategy}: ${w.droppedCount} dropped`),yield{type:"lifecycle",turnId:u.turnId,kind:"context_compression",status:"completed",detail:`${w.strategy}: ${w.droppedCount} dropped`},I(),D(l,"context.after_compact",{...u,removedCount:w.droppedCount},b))}return P=Kr(P),P}async function*es(e,t){let{state:n,guardState:o,fallbackModel:r,signal:s,querySource:i,turnId:l,log:u,emitRecovery:p}=t;if(e instanceof Ke&&r)return u.info(`model fallback triggered: ${e.originalModel} -> ${e.fallbackModel}`),yield p("model_fallback",`${e.originalModel} -> ${e.fallbackModel}`),{kind:"continue",patch:{currentModel:e.fallbackModel,consecutive529Errors:0,consecutiveApiRetries:0,transition:void 0}};let y=e instanceof Error?e.message:String(e),b=typeof e?.status=="number"?e.status:void 0;if(!b&&y&&(y.includes("ECONNRESET")||y.includes("EPIPE"))){let I=(n.consecutiveApiRetries??0)+1;return I>_e?(u.info(`stale connection retry limit reached (${_e}), aborting`),yield{type:"error",turnId:l,error:y,code:"RETRIES_EXHAUSTED",usage:n.totalUsage},{kind:"return"}):(u.info(`stale connection (${y.includes("ECONNRESET")?"ECONNRESET":"EPIPE"}): retrying`),yield p("stale_connection_retry",y.slice(0,80)),{kind:"continue",patch:{consecutiveApiRetries:I,transition:void 0}})}let k=Jr({status:b,message:y});if(k!==null)return u.info(`max_tokens overflow: adjusting to ${k}`),o.currentMaxOutputTokens=k,{kind:"continue",patch:{maxOutputTokensOverride:k,transition:void 0}};if(vn(b)){n.consecutive529Errors++;let I=2,P=r&&n.currentModel!==r;if(n.consecutive529Errors>I&&!P&&!bt())return u.info(`transient ${b} \u8133 ${n.consecutive529Errors}: hard limit reached, aborting`),yield{type:"error",turnId:l,error:`API unavailable after ${n.consecutive529Errors} consecutive ${b} errors`,code:"API_ERROR",usage:n.totalUsage},{kind:"return"};if(n.consecutive529Errors>=cr&&r&&n.currentModel!==r)return u.info(`529 \u8133 ${n.consecutive529Errors}: triggering fallback to ${r}`),yield p("model_fallback",`529 \u8133 ${n.consecutive529Errors}`),{kind:"continue",patch:{currentModel:r,consecutive529Errors:0,transition:void 0}};if(bt()){let x=yt(n.consecutive529Errors);u.info(`persistent retry: waiting ${x}ms (attempt ${n.consecutive529Errors})`);let E=x;for(;E>0;){if(s?.aborted)return yield{type:"error",turnId:l,error:"Aborted during retry wait",code:"ABORTED",usage:n.totalUsage},{kind:"return"};yield{type:"heartbeat",turnId:l,message:`Retrying in ${Math.ceil(E/1e3)}s (${b})`};let w=Math.min(E,lr);await new Promise(O=>setTimeout(O,w)),E-=w}return{kind:"continue",patch:{transition:void 0}}}if(_n(i)){let E=Zr({status:b,message:y})??yt(n.consecutive529Errors);return u.info(`transient ${b}: retry in ${E}ms`),yield p("retry",`${b} retry in ${E}ms`),await new Promise(w=>setTimeout(w,E)),{kind:"continue",patch:{transition:void 0}}}u.info(`background source ${i}: not retrying ${b}`)}return{kind:"streamError",streamError:{status:b,message:y}}}import{readdirSync as rs,statSync as Xe}from"node:fs";var sl=/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,ss=/[A-Za-z]:[\\/](?:[^\s"'`<>|,\uFF0C\u3001;\uFF1B\u3002]+[\\/])*[^\s"'`<>|,\uFF0C\u3001;\uFF1B\u3002]+\.[A-Za-z0-9]{1,12}/g,ts=/\s*[,\uFF0C\u3001;\uFF1B]\s*([^\s"'`<>|,\uFF0C\u3001;\uFF1B\u3002\\/]+\.[A-Za-z0-9]{1,12})/gy,il=/\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,al=/(?:^|[\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,ll=/(?:^|[\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,cl=/(?:^|[\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,ul=/\b(?:create|generate|write|produce|save|output|deliver|deliverables?|artifacts?|required|required files?|must generate|self-verify)\b|(?:生成|创建|写入|输出|保存|交付|产物|文件|必须|自检|验证)/i,dl=/\bpreviews?[\\/]\s*(?:containing|with|under|for)?[^.。;;\n]*(?:rendered|preview|previews|check|evidence|verify|verification)\b/i,fl=/(?:do\s*not|don'?t|never|不要|不能|别|勿|禁止|不准|不得)[^.。;;\n]{0,14}(?:create|write|make|produce|generate|生成|创建|写入|写出|建立|新建)/i;function te(e){return e.trim().replace(/[),.;:\uFF0C\u3002\uFF1B\u3001]+$/u,"").replace(/\\/g,"/").toLowerCase()}function is(e){return e.trim().replace(/[),.;:\uFF0C\u3002\uFF1B\u3001]+$/u,"").replace(/\\/g,"/").replace(/\/+$/u,"")}function ns(e){return/\.[A-Za-z0-9]{1,12}$/u.test(e.replace(/[),.;:\uFF0C\u3002\uFF1B\u3001]+$/u,""))}function os(e,t,n){let o=Math.max(e.lastIndexOf(".",t),e.lastIndexOf(`
|
|
26
|
+
`,t),e.lastIndexOf(";",t),e.lastIndexOf("\u3002",t),e.lastIndexOf("\uFF1B",t))+1,r=e.slice(o,t).toLowerCase();if(/\b(?:do\s+not|don't|never)\s+(?:leave|create|write|include|keep|produce|add|generate)\b/i.test(r)||/\b(?:remove|delete|exclude)\b/i.test(r))return!0;let s=e.slice(Math.max(0,t-16),t+n.length);return new RegExp(`\\bno\\s+${cs(n)}\\b`,"i").test(s)}function Xn(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=te(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=Xn(r.content);for(let i of s.matchAll(ss)){let l=i[0],u=(i.index??0)+l.length;if(s[u]==="/"||s[u]==="\\")continue;o(l);let p=l.replace(/\\/g,"/"),y=p.lastIndexOf("/");if(y>=0){let b=p.slice(0,y+1);ts.lastIndex=u;let k;for(;(k=ts.exec(s))!==null;)o(`${b}${k[1]}`)}}}for(let r of e){if(r.role!=="user"||typeof r.content!="string")continue;let s=Xn(r.content);if(!ul.test(s))continue;let i=Array.from(s.matchAll(il)).map(u=>is(u[1]??"")).filter(u=>u&&!ns(u));if(i.length===0)continue;let l=i[i.length-1];for(let u of s.matchAll(al)){let p=u[1];p&&(os(s,u.index??0,p)||o(`${l}/${p}`))}for(let u of s.matchAll(ll)){let p=u[1];p&&(os(s,u.index??0,p)||o(`${l}/${p}`))}for(let u of s.matchAll(cl)){let p=u[1];p&&(ns(p)||/(?:assets[\\/]generated|screenshots(?:[\\/]|$)|previews(?:[\\/]|$))/i.test(p)&&/\b(?:generated|bitmap|png|screenshots?|preview|previews|evidence|assets?|containing)\b/i.test(s)&&o(`${l}/${p}/*`))}dl.test(s)&&o(`${l}/previews/*`)}return n}function _t(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 l of i){let u=l,p=u.id,y=u.function;typeof p=="string"&&typeof y?.name=="string"&&n.set(p,y.name)}}for(let r of e){let s=r;if(_t(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 l of i){let u=l,p=u.id;if(typeof p=="string"&&t.size>0&&!t.has(p))continue;let y=u.function;if(!(typeof y?.name!="string"||typeof y.arguments!="string"))try{let b=JSON.parse(y.arguments);if(y.name==="write"||y.name==="edit"){for(let k of["path","filePath","file_path"]){let I=b[k];typeof I=="string"&&o.push(I)}continue}if(y.name==="exec"){let k=b.command;typeof k=="string"&&o.push(k)}}catch{y.name==="exec"&&o.push(y.arguments)}}}return o.join(`
|
|
27
|
+
`).replace(/\\/g,"/").toLowerCase()}function Jn(e){try{if(e.endsWith("/*")){let n=e.slice(0,-2);return rs(n,{withFileTypes:!0}).some(r=>{if(!r.isFile())return!1;try{return Xe(`${n}/${r.name}`).size>0}catch{return!1}})}let t=Xe(e);return t.isFile()&&t.size>0}catch{return!1}}function pl(e,t){let n=te(t);if(!n.endsWith("/*"))return e.includes(n);let o=n.slice(0,-1);return e.includes(o)}function ml(e){let t=new Set;for(let n of e){let o=n,r=Array.isArray(o.tool_calls)?o.tool_calls:[];for(let s of r){let i=s,l=i.id,u=i.function;typeof l=="string"&&u?.name==="agent"&&t.add(l)}}for(let n of e){let o=n,r=o.tool_call_id;if(typeof r=="string"&&t.has(r)&&_t(o))return!0}return!1}function gl(e){let t=ls(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 hl(e){let t=is(e),n=t.lastIndexOf("/");return n>=0?t.slice(0,n):""}function yl(e){if(e.length===0)return"";let t=e.map(o=>hl(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 bl(e,t){let n=te(e);return t.some(o=>{let r=te(o);return r.endsWith("/*")?n.startsWith(r.slice(0,-1)):n===r})}function Tl(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 l=i,u=l.id,p=l.function;if(typeof u!="string"||p?.name!=="write"&&p?.name!=="edit"||typeof p.arguments!="string")continue;let y=eo(p.arguments);if(!y)continue;let b=to(y);b&&n.set(u,b)}}for(let o of e){let r=o;if(!_t(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 Cl(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 kl(e){return[...new Set([...e.matchAll(/\bGoal\s+\d+\b/gi)].map(t=>t[0].replace(/\s+/g," ").replace(/\bgoal\b/i,"Goal")))]}function Rl(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 l=i,u=l.id,p=l.function;if(typeof u!="string"||p?.name!=="write"&&p?.name!=="edit"||typeof p.arguments!="string")continue;let y=eo(p.arguments);if(!y)continue;let b=to(y)??"",k=us(y);(/\bartifact[-_\s]?index\b/i.test(b)||/\bartifact[-_\s]?index\b/i.test(k))&&n.set(u,k)}}for(let o of e){let r=o;if(!_t(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 xl(e){let t=ls(e.inputMessages);if(!Cl(t))return[];let n=Rl(e.messages).at(-1);if(!n)return[];let o=[],r=kl(t).filter(u=>!new RegExp(`\\b${cs(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 l=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 l.length>0&&o.push({type:"unsupported_absence",detail:`Absence claims need scoped evidence or must be marked unverified: ${l.slice(0,3).join(" ; ")}`}),o}function _l(e){let t=[],n=o=>{let r;try{r=rs(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{Xe(i).size>0&&t.push(i)}catch{}}};try{if(!Xe(e).isDirectory())return[]}catch{return[]}return n(e),t}function vl(e,t){if(!gl(e))return[];let n=Yn(e),o=n.filter(i=>!te(i).endsWith("/*"));if(o.length<2)return[];let r=yl(o);if(!r||r.split("/").length<3)return[];let s=te(r);return[...new Set([...Tl(t),..._l(r)])].filter(i=>te(i).startsWith(`${s}/`)&&!bl(i,n)&&Jn(i))}function as(e,t){let n=Yn(e);if(n.length===0)return[];let o=Zn(t);return n.filter(r=>!pl(o,r))}function xt(e){return Qn(e).fail}function wl(e){return e.replace(/[.,;:,。;:、!?]+$/u,"")}function Rt(e){if(!e)return!1;let t=wl(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))Rt(s[2])&&(n=`${s[1].toUpperCase()} ${t(s[2])}`);for(let s of r.content.matchAll(/\bFAIL\s+([A-Za-z0-9_.:-]+)/gi))Rt(s[1])&&(o=`FAIL ${t(s[1])}`);for(let s of r.content.matchAll(/\b([A-Za-z0-9_.:-]+)\s+(DONE|PASS)\b/gi))Rt(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))Rt(s[1])&&(o=`${t(s[1])} FAIL`)}return{done:n,fail:o}}function ls(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 cs(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function we(e){let t=as(e.inputMessages,e.messages).filter(o=>!Jn(o));return t.length===0?void 0:`${xt(e.inputMessages)??"FAIL"} ${e.reason}. Missing required output file evidence: ${t.join(", ")}`}function eo(e){try{let t=JSON.parse(e);return t&&typeof t=="object"&&!Array.isArray(t)?t:null}catch{return null}}function to(e){for(let t of["path","filePath","file_path"]){let n=e[t];if(typeof n=="string"&&n.trim())return n}}function us(e){for(let t of["content","newContent","replacement","text"]){let n=e[t];if(typeof n=="string")return n}return""}function ds(e){let t=e.toolCall.function.name;if(t!=="write"&&t!=="edit")return;let n=Qn(e.inputMessages);if(!n.done)return;let o=eo(e.toolCall.function.arguments);if(!o)return;let r=to(o),s=us(o);if(!r||!s.includes(n.done))return;let i=Yn(e.inputMessages);if(i.length<2)return;let l=te(r);if(!i.some(b=>te(b)===l))return;let p=Zn(e.messages),y=i.filter(b=>te(b)!==l).filter(b=>!p.includes(te(b)));if(y.length!==0)return`Premature completion artifact blocked: this write/edit attempted to store the requested DONE marker in ${r} before evidence existed for sibling required output files: ${y.join(", ")}. Create or verify the missing files first, or report the requested FAIL marker with the real reason.`}function Ne(e,t){return{role:"assistant",content:e,...t.length>0&&{thinkingBlocks:[...t]}}}function Al(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 Sl(e){let t=[...e].reverse().find(n=>n.role==="tool");t&&typeof t.content=="string"&&(t.content+=`
|
|
28
28
|
|
|
29
|
-
\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 Ke(e,t,n,o){return{reason:e,messages:[...t,n,o],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}}}function eo(e){let t=e.inputMessages.find(h=>h.role==="user"),n=typeof t?.content=="string"?t.content:"",o=rl.test(n),r=e.distinctToolNames.has("write")||e.distinctToolNames.has("edit"),s=Zn(e.inputMessages),i=pl(e.messages),l=is(e.inputMessages,e.messages).filter(h=>!(i&&Yn(h)));if(l.length>0&&e.totalToolCallCount>0){if(s.fail!==void 0&&e.finalText.includes(s.fail))return null;e.log.info(`explicit required file verification: ${l.length} file(s) missing`);let h=Kn(e.inputMessages),b={role:"user",content:`Before completing, verify that every explicitly requested output file exists and is non-empty. Missing required output file evidence: ${l.join(", ")}. Create the missing files now, or if you cannot complete them, respond with ${h??"FAIL"} and the real reason. Do not claim completion until the missing files are handled.`};return Ke("explicit_required_file_verification",e.messages,Ve(e.finalText,e.thinkingBlocks),b)}let u=_l(e.inputMessages,e.messages);if(u.length>0&&e.totalToolCallCount>0){if(s.fail!==void 0&&e.finalText.includes(s.fail))return null;e.log.info(`explicit extra file verification: ${u.length} unexpected file(s)`);let h=Kn(e.inputMessages),b={role:"user",content:`The latest request asked for exactly the listed output artifacts, but extra files were produced under the output root: ${u.join(", ")}. Remove the extra files now, move scratch work outside the deliverable directory, or if you cannot make the output exact, respond with ${h??"FAIL"} and the real reason. Do not claim completion while extra deliverables remain.`};return Ke("explicit_extra_file_verification",e.messages,Ve(e.finalText,e.thinkingBlocks),b)}let p=Rl({inputMessages:e.inputMessages,messages:e.messages,finalText:e.finalText});if(p.length>0&&e.totalToolCallCount>0){if(s.fail!==void 0&&e.finalText.includes(s.fail))return null;e.log.info(`artifact index evidence verification: ${p.length} issue(s)`);let h={role:"user",content:"Before completing, correct the artifact index against the actual evidence scope. "+p.map(b=>b.detail).join(" ")+" Use the exact requested Goal row labels, cite concrete evidence names/paths for status claims, and mark a row as not verified/unknown instead of claiming exhaustive absence without scoped evidence. Do not claim all checks pass while any row is failed, partial, missing, or unverified. After correcting and verifying the file, finish with the final status contract."};return Ke("artifact_index_evidence_verification",e.messages,Ve(e.finalText,e.thinkingBlocks),h)}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&&Al(e.messages);let h={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 Ke("file_action_verification",e.messages,Ve(e.finalText,e.thinkingBlocks),h)}if(e.totalToolCallCount>=3&&e.distinctToolNames.has("write")&&e.messages.filter(wl).length>=3){e.log.info("AP3 verification nudge: 3+ files created, injecting completeness check");let b={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 Ke("multi_file_skeleton_verification",e.messages,Ve(e.finalText,e.thinkingBlocks),b)}return null}function Sl(e,t){return{role:"assistant",content:e,...t.length>0&&{thinkingBlocks:[...t]}}}async function ds(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,Sl(e.finalText,e.thinkingBlocks),o],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}}}return null}var Ml=5;function El(e){return e.inputTokens+e.outputTokens+(e.reasoningTokens??0)}function Il(e,t){return{role:"assistant",content:e,...t.length>0&&{thinkingBlocks:[...t]}}}function fs(e){if(!e.tokenBudget||e.tokenBudget<=0||e.budgetContinuationCount>=Ml)return null;let t=El(e.totalUsage),n=t/e.tokenBudget*100,o=t-e.lastBudgetGlobalTokens;if(e.budgetContinuationCount>=sr&&o<fn&&e.lastBudgetDeltaTokens<fn)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,Il(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 gn(t,{tools:[...e.distinctToolNames],projectRoot:e.projectRoot})}var Xe="*";function ps(e,t){let n=[],o=[];for(let r of e){let s=ys(r.function.name,r.function.arguments),i=bs(r.function.name,Xe),l=Math.max(t.get(s)??0,t.get(i)??0);l>=ft?o.push({call:r,failCount:l,error:`Tool "${r.function.name}" has failed ${l} 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 ms(){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 gs(e){if(e.ok&&!e.softEmpty)return;let t=ys(e.toolName,e.toolArguments),n=e.toolFailureCounts.get(t)??0;e.toolFailureCounts.set(t,n+1)}function hs(e){let t=[];for(let[n,o]of e.toolFailureCounts)if(o>=ft&&(e.snapshot.get(n)??0)<ft){let{toolName:r,target:s}=Ol(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 ys(e,t){return bs(e,Pl(e,t))}function Pl(e,t){let n=Ll(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):Xe}function Ll(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():Xe}function bs(e,t){return`${e}::${t}`}function Ol(e){let t=e.indexOf("::");return t<0?{toolName:e,target:Xe}:{toolName:e.slice(0,t),target:e.slice(t+2)||Xe}}var Nl=new Set(["find","grep","rg","ag","ack","locate","which","whereis"]),Fl=new Set(["cat","head","tail","less","more","wc","stat","file","sed","strings","jq","awk","cut","sort","uniq","tr"]),Bl=new Set(["ls","tree","du","dir","gci","get-childitem"]),Dl=new Set(["grep","rg","ag","ack","find"]);var $l=new Set(["mv","cp","rm","mkdir","rmdir","chmod","chown","chgrp","touch","ln","cd","export","unset","wait"]);function Ul(e){let n=e.replace(/\\\n/g," ").trim().split(/[|;&]/).shift()?.trim()??"";if(!n)return null;let o=n.split(/\s+/),r=0;for(;r<o.length&&/^[A-Za-z_]\w*=/.test(o[r]);)r++;let s=/^(?:timeout|time|nice|nohup|stdbuf|command|builtin|exec)$/;for(;r<o.length;){let p=o[r];if(s.test(p)){for(r++;r<o.length&&/^[-+]/.test(o[r]);)r++;r<o.length&&/^\d+(?:\.\d+)?[smhd]?$/.test(o[r])&&r++;continue}break}if(r>=o.length)return null;let i=o[r],l=i.lastIndexOf("/");return(l>=0?i.slice(l+1):i).toLowerCase()}function jl(e){return/(?:^|[;&|])\s*(?:cd|pushd|popd)\b/.test(e)}function Ts(e){let t=Ul(e),n=t!==null&&Nl.has(t),o=t!==null&&Fl.has(t),r=t!==null&&Bl.has(t),s=t!==null&&$l.has(t),i=/(?:[^2]>|^>|\|>)/.test(e),l=jl(e),u=(n||o||r)&&!i&&!l;return{firstCommand:t,isSearch:n,isRead:o,isList:r,isSilent:s,isConcurrencySafe:u,isReadOnly:u}}function Cs(e){return e.isRead?!0:e.firstCommand!==null&&Dl.has(e.firstCommand)}function ks(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 Hl(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 Gl(e,t){let n=Wl(t);if(!n)return null;let o=Vl(n);if(!o)return null;let r=[...e].reverse().find(l=>l.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 Wl(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 Vl(e){return e.toLocaleLowerCase().replace(/[^\p{L}\p{N}\s]+/gu," ").replace(/\s+/g," ").trim()}function C(e){return[...new Set(e.map(t=>t.function.name))].sort()}function wt(e){return[...e].sort((t,n)=>t.function.name.localeCompare(n.function.name))}function _t(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 Kl(e,t,n,o,r){let s=r.filter(i=>i.name===e).sort((i,l)=>Rs(i.reason)-Rs(l.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 Rs(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 Xl(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 xs(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 Yl=new Set(["edit","patch","read"]);function _s(e,t){let n=e.filter(o=>Yl.has(o.function.name)&&!t.has(o.function.name));return n.length>0?wt(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 Zl(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 St=5174;function ws(e,t){let n=String(t);return[new RegExp(`(?:^|\\s)--port(?:=|\\s+)${n}(?:\\s|$)`),new RegExp(`(?:^|\\s)-p(?:=|\\s+)${n}(?:\\s|$)`),new RegExp(`(?:localhost|127\\.0\\.0\\.1|0\\.0\\.0\\.0|\\[?::1\\]?):${n}\\b`,"i")].some(r=>r.test(e))}function Jl(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 Ls(e){return/(?:^|\s)--strictPort(?:\s|$)/.test(e)}function Ql(e){if(Ls(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 As(e,t){let n=de(e)??{};return JSON.stringify({...n,command:t})}function ec(e){let t=e.replace(/^(?:\s*sleep\s+\d+(?:\.\d+)?\s*(?:&&|;)\s*)+/i,"").trim();return t&&t!==e.trim()?t:null}function tc(e){return ws(e,St)?{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."}:Jl(e)&&ws(e,St-1)&&!Ls(e)?{action:"rewrite",command:Ql(e)}:null}function Mt(e){let t=[];for(let n of e.devServerUrls)if(!(!/^https?:\/\/(?:localhost|127\.0\.0\.1):\d+\b/i.test(n)||new RegExp(`:${St}\\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 Ss(e){let t=Mt(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 nc(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
|
+
\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 Fe(e,t,n,o){return{reason:e,messages:[...t,n,o],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}}}function Ml(e){try{return Xe(e).isFile()}catch{return!1}}function El(e,t){let n=new Map;for(let s of e){if(s.role!=="user"||typeof s.content!="string")continue;let i=Xn(s.content);if(fl.test(i))for(let l of i.matchAll(ss)){let u=l[0].replace(/[),.;:,。;]+$/u,""),p=te(u);p&&n.set(p,u)}}if(n.size===0)return[];let o=Zn(t),r=[];for(let[s,i]of n)(o.includes(s)||Ml(i))&&r.push(s);return r}function no(e){let t=e.inputMessages.find(b=>b.role==="user"),n=typeof t?.content=="string"?t.content:"",o=sl.test(n),r=e.distinctToolNames.has("write")||e.distinctToolNames.has("edit"),s=Qn(e.inputMessages),i=El(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 b=xt(e.inputMessages),k={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 ${b??"FAILED"} with the real reason: the task could not be done without violating the stated constraint. Do not fabricate a successful outcome.`};return Fe("forbidden_file_creation",e.messages,Ne(e.finalText,e.thinkingBlocks),k)}let l=ml(e.messages),u=as(e.inputMessages,e.messages).filter(b=>!(l&&Jn(b)));if(u.length>0&&e.totalToolCallCount>0){if(s.fail!==void 0&&e.finalText.includes(s.fail))return null;e.log.info(`explicit required file verification: ${u.length} file(s) missing`);let b=xt(e.inputMessages),k={role:"user",content:`Before completing, verify that every explicitly requested output file exists and is non-empty. Missing required output file evidence: ${u.join(", ")}. Create the missing files now, or if you cannot complete them, respond with ${b??"FAIL"} and the real reason. Do not claim completion until the missing files are handled.`};return Fe("explicit_required_file_verification",e.messages,Ne(e.finalText,e.thinkingBlocks),k)}let p=vl(e.inputMessages,e.messages);if(p.length>0&&e.totalToolCallCount>0){if(s.fail!==void 0&&e.finalText.includes(s.fail))return null;e.log.info(`explicit extra file verification: ${p.length} unexpected file(s)`);let b=xt(e.inputMessages),k={role:"user",content:`The latest request asked for exactly the listed output artifacts, but extra files were produced under the output root: ${p.join(", ")}. Remove the extra files now, move scratch work outside the deliverable directory, or if you cannot make the output exact, respond with ${b??"FAIL"} and the real reason. Do not claim completion while extra deliverables remain.`};return Fe("explicit_extra_file_verification",e.messages,Ne(e.finalText,e.thinkingBlocks),k)}let y=xl({inputMessages:e.inputMessages,messages:e.messages,finalText:e.finalText});if(y.length>0&&e.totalToolCallCount>0){if(s.fail!==void 0&&e.finalText.includes(s.fail))return null;e.log.info(`artifact index evidence verification: ${y.length} issue(s)`);let b={role:"user",content:"Before completing, correct the artifact index against the actual evidence scope. "+y.map(k=>k.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 Fe("artifact_index_evidence_verification",e.messages,Ne(e.finalText,e.thinkingBlocks),b)}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&&Sl(e.messages);let b={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 Fe("file_action_verification",e.messages,Ne(e.finalText,e.thinkingBlocks),b)}if(e.totalToolCallCount>=3&&e.distinctToolNames.has("write")&&e.messages.filter(Al).length>=3){e.log.info("AP3 verification nudge: 3+ files created, injecting completeness check");let k={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 Fe("multi_file_skeleton_verification",e.messages,Ne(e.finalText,e.thinkingBlocks),k)}return null}function Il(e,t){return{role:"assistant",content:e,...t.length>0&&{thinkingBlocks:[...t]}}}async function fs(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,Il(e.finalText,e.thinkingBlocks),o],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}}}return null}var Pl=5;function Ol(e){return e.inputTokens+e.outputTokens+(e.reasoningTokens??0)}function Ll(e,t){return{role:"assistant",content:e,...t.length>0&&{thinkingBlocks:[...t]}}}function ps(e){if(!e.tokenBudget||e.tokenBudget<=0||e.budgetContinuationCount>=Pl)return null;let t=Ol(e.totalUsage),n=t/e.tokenBudget*100,o=t-e.lastBudgetGlobalTokens;if(e.budgetContinuationCount>=ar&&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,Ll(e.finalText,e.thinkingBlocks),i],budgetContinuationCount:s,lastBudgetDeltaTokens:o,lastBudgetGlobalTokens:t,recoveryDetail:`${Math.round(n)}% used (#${s})`,transition:{reason:"token_budget_continuation"}}}function oo(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})}var Ye="*";function ms(e,t){let n=[],o=[];for(let r of e){let s=bs(r.function.name,r.function.arguments),i=Ts(r.function.name,Ye),l=Math.max(t.get(s)??0,t.get(i)??0);l>=pt?o.push({call:r,failCount:l,error:`Tool "${r.function.name}" has failed ${l} 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 gs(){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 hs(e){if(e.ok&&!e.softEmpty)return;let t=bs(e.toolName,e.toolArguments),n=e.toolFailureCounts.get(t)??0;e.toolFailureCounts.set(t,n+1)}function ys(e){let t=[];for(let[n,o]of e.toolFailureCounts)if(o>=pt&&(e.snapshot.get(n)??0)<pt){let{toolName:r,target:s}=Bl(n);t.push({role:"user",content:`Tool "${r}" has now failed/returned empty results ${o} times for target "${s}". That target clearly does not exist or is not useful. Do NOT retry variations of the same target. Report the result to the user immediately.`})}return t}function bs(e,t){return Ts(e,Nl(e,t))}function Nl(e,t){let n=Fl(t);return e==="read"||e==="write"||e==="edit"||e==="patch"?ro(n?.path??n?.file_path??n?.filePath):e==="search"?ro([n?.mode,n?.path,n?.fileGlob,n?.pattern].filter(Boolean).join("|")):e==="exec"?ro(n?.command):Ye}function Fl(e){if(e)try{let t=JSON.parse(e);return t&&typeof t=="object"&&!Array.isArray(t)?t:void 0}catch{return}}function ro(e){return typeof e=="string"&&e.trim()?e.trim().replaceAll("\\","/").toLowerCase():Ye}function Ts(e,t){return`${e}::${t}`}function Bl(e){let t=e.indexOf("::");return t<0?{toolName:e,target:Ye}:{toolName:e.slice(0,t),target:e.slice(t+2)||Ye}}var Dl=new Set(["find","grep","rg","ag","ack","locate","which","whereis"]),$l=new Set(["cat","head","tail","less","more","wc","stat","file","sed","strings","jq","awk","cut","sort","uniq","tr"]),Ul=new Set(["ls","tree","du","dir","gci","get-childitem"]),jl=new Set(["grep","rg","ag","ack","find"]);var ql=new Set(["mv","cp","rm","mkdir","rmdir","chmod","chown","chgrp","touch","ln","cd","export","unset","wait"]);function zl(e){let n=e.replace(/\\\n/g," ").trim().split(/[|;&]/).shift()?.trim()??"";if(!n)return null;let o=n.split(/\s+/),r=0;for(;r<o.length&&/^[A-Za-z_]\w*=/.test(o[r]);)r++;let s=/^(?:timeout|time|nice|nohup|stdbuf|command|builtin|exec)$/;for(;r<o.length;){let p=o[r];if(s.test(p)){for(r++;r<o.length&&/^[-+]/.test(o[r]);)r++;r<o.length&&/^\d+(?:\.\d+)?[smhd]?$/.test(o[r])&&r++;continue}break}if(r>=o.length)return null;let i=o[r],l=i.lastIndexOf("/");return(l>=0?i.slice(l+1):i).toLowerCase()}function Hl(e){return/(?:^|[;&|])\s*(?:cd|pushd|popd)\b/.test(e)}function Cs(e){let t=zl(e),n=t!==null&&Dl.has(t),o=t!==null&&$l.has(t),r=t!==null&&Ul.has(t),s=t!==null&&ql.has(t),i=/(?:[^2]>|^>|\|>)/.test(e),l=Hl(e),u=(n||o||r)&&!i&&!l;return{firstCommand:t,isSearch:n,isRead:o,isList:r,isSilent:s,isConcurrencySafe:u,isReadOnly:u}}function ks(e){return e.isRead?!0:e.firstCommand!==null&&jl.has(e.firstCommand)}function Rs(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 Vl(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=Xl(t);if(!n)return null;let o=Yl(n);if(!o)return null;let r=[...e].reverse().find(l=>l.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 Xl(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 Yl(e){return e.toLocaleLowerCase().replace(/[^\p{L}\p{N}\s]+/gu," ").replace(/\s+/g," ").trim()}function C(e){return[...new Set(e.map(t=>t.function.name))].sort()}function At(e){return[...e].sort((t,n)=>t.function.name.localeCompare(n.function.name))}function vt(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 Zl(e,t,n,o,r){let s=r.filter(i=>i.name===e).sort((i,l)=>xs(i.reason)-xs(l.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 xs(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 Jl(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 _s(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 Ql=new Set(["edit","patch","read"]);function vs(e,t){let n=e.filter(o=>Ql.has(o.function.name)&&!t.has(o.function.name));return n.length>0?At(n):e.filter(o=>o.function.name!=="write"&&!t.has(o.function.name))}function so(e,t){let n=new Set(t);return e.filter(o=>!n.has(o))}function ec(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 ws(e){let n=de(e)?.command;return typeof n=="string"&&n.trim()?n:void 0}var Mt=5174;function As(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 tc(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 Ls(e){return/(?:^|\s)--strictPort(?:\s|$)/.test(e)}function nc(e){if(Ls(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 Ss(e,t){let n=de(e)??{};return JSON.stringify({...n,command:t})}function oc(e){let t=e.replace(/^(?:\s*sleep\s+\d+(?:\.\d+)?\s*(?:&&|;)\s*)+/i,"").trim();return t&&t!==e.trim()?t:null}function rc(e){return As(e,Mt)?{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."}:tc(e)&&As(e,Mt-1)&&!Ls(e)?{action:"rewrite",command:nc(e)}:null}function Et(e){let t=[];for(let n of e.devServerUrls)if(!(!/^https?:\/\/(?:localhost|127\.0\.0\.1):\d+\b/i.test(n)||new RegExp(`:${Mt}\\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 Ms(e){let t=Et(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:
|
|
30
30
|
${t.slice(0,600)}
|
|
31
|
-
`:"")+"Do not finish or claim success from source inspection. Diagnose the failure, edit the source to fix the root cause, then RE-RUN the same test/build command via exec. Repeat until the command exits 0 (passes), then report the passing output. Do NOT modify, weaken, or delete the test/assertions to force a pass."}function
|
|
31
|
+
`:"")+"Do not finish or claim success from source inspection. Diagnose the failure, edit the source to fix the root cause, then RE-RUN the same test/build command via exec. Repeat until the command exits 0 (passes), then report the passing output. Do NOT modify, weaken, or delete the test/assertions to force a pass."}function Ns(e){let n=de(e)?.command;return typeof n=="string"&&n.trim()?n.trim():null}var ic=4;function ac(e,t){if(/^(?:write|edit|patch)$/i.test(e)){let n=de(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=Ns(t);return n?`exec:${n.replace(/\s+/g," ")}`:null}return null}function Es(e){let t=Ns(e);return t?/\b(?:npx\s+)?playwright\s+install(?:\s+--with-deps)?\s+chromium\b/i.test(t):!1}function lc(e){let t=Et(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 cc(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 uc(e){let t=new Set(["completed","blocked","cancelled","canceled","failed"]);return e.some(n=>!t.has(n.status.toLowerCase()))}function dc(e){return e?Rs(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 Is(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=>Zl(s,t.availableToolNames,t.enabledToolNames,t.toolCallNames,t.blockedToolCalls)).join(", ");return`${e}
|
|
32
32
|
|
|
33
33
|
Tool availability diagnostics:
|
|
34
34
|
availableToolNames: ${t.availableToolNames.join(", ")}
|
|
35
35
|
enabledToolNames: ${t.enabledToolNames.join(", ")}
|
|
36
36
|
toolCallNames: ${t.toolCallNames.join(", ")||"none"}
|
|
37
37
|
blockedToolCalls: ${n}
|
|
38
|
-
attribution: ${r}`}function ue(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function
|
|
39
|
-
`),i=
|
|
38
|
+
attribution: ${r}`}function ue(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function fc(e,t){if(!e)return null;let n=ue(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=de(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.${pc(e.function.name)}`}return null}function pc(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 Ae(e,t){if(!e||typeof e!="object")return;let n=e[t];return typeof n=="string"?n:void 0}function St(e,t){if(!e||typeof e!="object")return;let n=e[t];return typeof n=="boolean"?n:void 0}function mc(e,t){if(!e||typeof e!="object")return;let n=e[t];return typeof n=="number"&&Number.isFinite(n)?n:void 0}function gc(e){let t=[...e].sort();return[`Background agent task(s) are still unresolved: ${t.map(n=>`\`${n}\``).join(", ")}.`,"Do not launch replacement agents and do not claim they are lost while their task ids are known.",`Poll each existing task with ${t.map(n=>`task(action="output", taskId="${n}")`).join(", ")}.`,"Only after every task is completed, failed, or explicitly cancelled may you synthesize artifacts or report a blocker."].join(" ")}function hc(e,t){return[`Background agent task(s) exceeded the no-output watchdog: ${e.map(n=>`\`${n}\``).join(", ")}.`,`Reason: ${t.reason}.`,`Cancel each stalled task now with ${e.map(n=>`task(action="cancel", taskId="${n}")`).join(", ")}.`,"After cancellation, do not relaunch replacement agents for the same work in this turn.","Resume in the parent task with direct write/edit/patch/exec work inside the declared artifact root, or report an explicit blocker with the stalled task ids."].join(" ")}function yc(e,t){if(e.function.name!=="task")return!1;let n=de(e.function.arguments);if(n?.action!=="output")return!1;let o=n.taskId;return typeof o=="string"&&be(t).has(o)}function bc(e,t){if(e.toolName!=="task")return!1;let n=Ae(e.details,"taskId");return!n||!be(t).has(n)?!1:Ae(e.details,"action")==="output"&&St(e.details,"running")===!0}var Tc=180,Cc=40;function kc(e){return/\(no output yet\)|\bno output yet\b/i.test(e)}function Rc(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 be(e){return e.backgroundAgentTaskIds??(e.backgroundAgentTaskIds=new Set)}function xc(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,l=r.status;typeof s!="number"||!Number.isFinite(s)||typeof i!="string"||!i.trim()||typeof l!="string"||!l.trim()||n.push({id:s,title:i,status:l})}return n}var ao=new Set(["read","search"]),_c=new Set(["write","edit","patch","image_generate"]),vc=18e4,wc=3,Ze=1,Ac=1,Sc=1,Mc=4,Z=new Map([["requirements.md","requirements"],["decisions.md","decisions"],["defects.md","defects"],["acceptance.md","acceptance"]]),mo=new Set(["document-index.json","decision-state-table.json","context-pack-evidence.json"]),Fs=[{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}],lo=new Set(["write","edit","patch"]),Ec=new Set(["read","search","exec"]);function Bs(e){let t=W(e),n=Se(t);return t.split("/").includes("context-pack")&&Z.has(n)?Ze:t.split("/").includes("benchmark-state")&&mo.has(n)?Sc:t.includes("/qlogicagent-sessions/")&&t.includes("/tool-results/")?Ac:wc}function io(e){let t=W(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")&&mo.has(Se(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 go(e){let t=W(e);return t.split("/").includes("context-pack")&&Z.has(Se(t))}function Ds(e){let t=W(e),o=t.indexOf("/context-pack/");return o<0?null:t.slice(0,o)}function Ic(e){let t=[...e].filter(go).map(Ds).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 $e(o)}catch{return!1}})}function Pc(e){return[...Z.keys()].every(t=>e.has(t))}function $s(e){for(let t of e.values()){if(!t.path)continue;let n=Ds(t.path);if(n)return`${n}/benchmark-state`}return null}function Us(e){if(!Pc(e))return[];let t=$s(e);return t?[...mo].map(n=>`${t}/${n}`).filter(n=>{try{return!$e(n)}catch{return!0}}):[]}function Oc(e,t){let n=Us(e);if(n.length===0)return null;let o=$s(e);if(!o)return null;let s=[...Z.keys()].map(l=>{let u=e.get(l);return`${l}: path=${u?.path??"unknown"}, contentHash=${u?.contentHash??"unknown"}, fileSizeBytes=${u?.fileSizeBytes??"unknown"}, recordCount=${u?.recordCount??"unknown"}, summary=${u?.summary??""}`}).join(`
|
|
39
|
+
`),i=Fs.map(l=>`${l.id}: ${l.decision}`).join(`
|
|
40
40
|
`);return["You have already read and indexed requirements.md, decisions.md, defects.md, and acceptance.md for this long-horizon benchmark.","Do not read context-pack, persisted tool-result previews, or compact benchmark-state files again in this turn.","Before any more analysis or final answer, maintain the benchmark state files using write/edit/patch only.",`Benchmark-state directory: ${o}.`,`Missing files: ${n.join(", ")}.`,"Create missing files with write. If any target already exists, update it with edit or patch instead of write.","For every contentHash and fileSizeBytes you write, copy the EXACT value from the 'Document evidence already available' section below. Do NOT compute, approximate, or invent a hash \u2014 you must not re-read the large read-only context-pack files to produce one.","The context-pack inputs (requirements.md, decisions.md, defects.md, acceptance.md) are READ-ONLY and immutable: their content and contentHash cannot change between turns. If a hash ever appears to differ from what you recorded, the source did NOT change \u2014 suspect your own recorded value first (stale, or never tool-derived). Never raise a 'source changed' blocker for these files.","Acceptance verdicts are monotonic unless re-derived from primary evidence: do NOT flip a previously-PASSing criterion to FAIL on a derived/secondary signal such as a hash diff. Change a PASS to FAIL only after re-checking the actual acceptance condition against primary evidence, and cite that evidence.","Required files:","- document-index.json: include contextPackPath and a documents object keyed by requirements.md, decisions.md, defects.md, acceptance.md with path, contentHash, fileSizeBytes, recordCount, indexVersion, summary, and lastReviewedTurn.","- decision-state-table.json: include D001-D006 with id, decision, status, evidence, and lastConfirmedTurn.","- context-pack-evidence.json: include turn and fileVerification for requirements.md, decisions.md, defects.md, acceptance.md with path, contentHash, and fileSizeBytes.",`Current turn: ${t}.`,"Document evidence already available:",s,"Decision records to preserve:",i].join(`
|
|
41
|
-
`)}function Is(e){return io.has(e)}function Ic(e){return e.benchmarkStateMaintenanceRequiredFiles.size>0&&[...e.benchmarkStateMaintenanceRequiredFiles].every(t=>Pc(e,t))}function Pc(e,t){if(e.benchmarkStateMaintenanceWrittenFiles.has(t))return!0;try{if(!Be(t))return!1;let n=Se(t);if(n!=="document-index.json"&&n!=="context-pack-evidence.json")return!0;let o=uo(t,"utf8");return Us(e,t,JSON.stringify({content:o})).ok}catch{return!1}}function Us(e,t,n){let o=Se(t);if(o!=="document-index.json"&&o!=="context-pack-evidence.json")return{ok:!0};let r=Kc(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 l=ue(s.documents);if(!l)return{ok:!1,reason:"document-index.json missing documents object"};for(let u of Z.keys()){let p=e.maintainedDocuments.get(u),h=ue(l[u]);if(!p||!h)return{ok:!1,reason:`document-index.json missing ${u}`};if(h.contentHash!==p.contentHash)return{ok:!1,reason:`document-index.json ${u} contentHash does not match read.details`};if(h.fileSizeBytes!==p.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 l of Z.keys()){let u=e.maintainedDocuments.get(l),p=ue(i[l]);if(!u||!p)return{ok:!1,reason:`context-pack-evidence.json missing ${l}`};if(p.contentHash!==u.contentHash)return{ok:!1,reason:`context-pack-evidence.json ${l} contentHash does not match read.details`};if(p.fileSizeBytes!==u.fileSizeBytes)return{ok:!1,reason:`context-pack-evidence.json ${l} fileSizeBytes does not match read.details`}}return{ok:!0}}function Lc(e,t,n,o){if(e.filter(l=>l.name==="read"&&l.reason==="read-cycle-policy").length<wc)return!1;let s=new Set([...t].filter(po).map(Se));return[...Z.keys()].every(l=>s.has(l))?[...Z.keys()].every(l=>o.has(l))||n||Sc(t):!1}function js(e,t,n){if(e!=="write"||!n.has("edit")&&!n.has("patch"))return null;let o=It(t);if(!o)return null;try{if(!Be(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 Et=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*Oc(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 Et(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 It(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 Nc(e){try{let t=JSON.parse(e),n=typeof t.query=="string"?t.query.trim():"";return n.startsWith("select:")?n.slice(7).split(",").map(o=>o.trim()).filter(Boolean).sort():[]}catch{return[]}}function Fc(e){return e.flatMap(t=>{if(Bc(t.function.arguments))return[t];let n=Dc(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 Bc(e){try{let t=JSON.parse(e);return!!t&&typeof t=="object"&&!Array.isArray(t)}catch{return!1}}function Dc(e){let t=[],n=0,o=-1,r=!1,s=!1,i=0;for(let l=0;l<e.length;l+=1){let u=e[l];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,l).trim())return[];o=l}n+=1;continue}if(u!=="}"||(n-=1,n!==0||o<0))continue;let p=de(e.slice(o,l+1));if(!p)return[];t.push(p),i=l+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 W(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 Se(e){let t=e.trim().replace(/\\/g,"/");return t.slice(t.lastIndexOf("/")+1).toLowerCase()}function mo(e){return`sha256:${zl("sha256").update(e).digest("hex")}`}function $c(e,t){let n=t.split(/\r?\n/).map(l=>l.trim()).filter(Boolean),o=n[0]??e,r=n.find(l=>/record\s+0*1\b/i.test(l)),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 Uc(e){return Object.fromEntries([...e.entries()].sort(([t],[n])=>t.localeCompare(n)))}function jc(e,t,n,o){let r=[...t.values()].sort((u,p)=>(u.name??"").localeCompare(p.name??""));if(r.length===0)return null;let s=r.map(u=>`${u.name??"document"}:${u.contentHash??"unknown"}`).join("|"),i=Ns.map(u=>({...u,evidence:`read:long-horizon-documents:${mo(`${u.id}:${s}`)}`,lastConfirmedTurn:o})),l={strategy:"maintained-document-index",nextReadPolicy:"use maintained index before full document reread",budgetStatus:"within-budget",maxReadsPerDocument:Ye,observedReadsByPath:Uc(n)};return{type:"document_maintenance",turnId:e,checkpointId:`${e}-docs-${r.length}`,documents:r,decisionStateTable:i,readCycleFindings:[],readCycleGuard:l}}function qc(e){let t=e.find(o=>o.path)?.path??"",n=t.lastIndexOf("/");return n>0?t.slice(0,n):t}function vt(e,t){return e.get(t)??null}function zc(e){let t=vt(e,"requirements.md"),n=vt(e,"decisions.md"),o=vt(e,"defects.md"),r=vt(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:qc(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 Hc(e,t){let n=zc(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 Gc(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=Se(e);if(!Z.has(r))return null;let s=Yc(t)??t,i=Xc(o,"contentHash"),l=Ne(o??null,"fileSizeBytes"),u=i??mo(s);return{name:r,path:W(e),indexed:!0,maintained:!0,indexVersion:u,contentHash:u,summary:$c(r,s),lastReviewedTurn:n,fileSizeBytes:l??Buffer.byteLength(s,"utf8"),recordCount:qs(s)}}function Wc(e,t){return js(e.function.name,e.function.arguments,t)!==null}function Vc(e,t){let n=It(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 Kc(e){let n=de(e)?.content;return typeof n=="string"?n:void 0}function Xc(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 Yc(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 Be(n)?uo(n,"utf8"):null}catch{return null}}function Zc(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 l=ao(i.function.arguments);if(!l)continue;let u=W(l);Fs(u)===Ye&&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 l=typeof s.content=="string"?s.content:"";if(!l||/^Error:/i.test(l.trim()))continue;n.set(i.path,(n.get(i.path)??0)+1);let u=lo(i.path,l,0);u?.name&&o.set(u.name,u)}for(let s of nu(e)){r=!0;for(let i of Z.keys()){let l=W(`${s}/${i}`);if(n.set(l,Math.max(n.get(l)??0,Ye)),!o.has(i)){let u=lo(l,`${i} maintained by benchmark-state/document-index.json from prior conversation history.`,0);u?.name&&o.set(u.name,u)}}}for(let s of Jc(e)){r=!0;for(let i of s.documents)!i.name||!i.path||(n.set(i.path,Math.max(n.get(i.path)??0,Ye)),o.set(i.name,i))}return{fileReadCounts:n,maintainedDocuments:o,persistedBenchmarkStateRecovered:r}}function Jc(e){let t=[];for(let n of Qc(e)){let o=Ps(`${n}/document-index.json`),r=Ps(`${n}/context-pack-evidence.json`),s=Fe(o,"contextPackPath")??eu(r);if(!s)continue;let i=tu(s,o,r);i.length===Z.size&&t.push({documents:i})}return t}function Qc(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=W(s[1]??"");i&&t.add(i)}}return[...t]}function Ps(e){try{if(!Be(e))return null;let t=JSON.parse(uo(e,"utf8"));return t&&typeof t=="object"&&!Array.isArray(t)?t:null}catch{return null}}function Fe(e,t){let n=e?.[t];return typeof n=="string"&&n.trim()?W(n):void 0}function eu(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=Fe(o,"path");if(!r)continue;let s=`/${n}`;if(r.endsWith(s))return r.slice(0,-s.length)}}function tu(e,t,n){let o=ue(t?.documents),r=ue(n?.fileVerification),s=[];for(let i of Z.keys()){let l=ue(o?.[i]),u=ue(r?.[i]);if(!l&&!u)return[];let p=Fe(l,"path"),b=Fe(u,"path")??(p?.includes("/context-pack/")?p:W(`${e}/${i}`)),k=Fe(l,"contentHash")??Fe(u,"contentHash")??mo(`${i}:${b}`),I=typeof l?.summary=="string"&&l.summary.trim()?l.summary.trim():`${i} maintained by persisted benchmark-state/document-index.json.`;s.push({name:i,path:W(b),indexed:!0,maintained:!0,indexVersion:String(l?.indexVersion??k),contentHash:k,summary:I,lastReviewedTurn:co(l,"lastReviewedTurn")??co(n,"turn")??0,fileSizeBytes:Ne(l,"fileSizeBytes")??Ne(u,"fileSizeBytes")??Ne(u,"sizeBytes")??Buffer.byteLength(I,"utf8"),recordCount:Ne(l,"recordCount")??Ne(u,"recordCount")??qs(I)})}return s}function co(e,t){let n=e?.[t];return typeof n=="number"&&Number.isFinite(n)?n:void 0}function Ne(e,t){let n=co(e,t);return n&&n>0?n:void 0}function nu(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 l=W(i[1]??"");l&&n.add(l)}}return[...n]}function ou(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*zs(e,t,n,o){let{turnId:r,sessionId:s,messages:i,availableTools:l,tools:u,model:p,apiKey:h,temperature:b=0,hooks:k,signal:I}=e,P={sessionId:s,turnId:r},x=e.maxTurns??0,E=e.querySource,w=e.runtimePorts.resolveToolEligibility(u,e.toolEligibilityContext),L=w.eligibleTools,F=[];for(let m of w.blockedTools)F.push({name:m.toolName,reason:"blocked-by-policy"}),yield{type:"tool_blocked",turnId:r,callId:"",name:m.toolName,reason:"blocked-by-policy"};let U=Hr(e.maxRounds,i),oe=Gr(e.maxToolCalls,i),Pt=!(typeof e.maxRounds=="number"&&e.maxRounds>=1)&&!(typeof e.maxToolCalls=="number"&&e.maxToolCalls>=1),go=Ct(i),Me={contextWindowTokens:e.contextWindowTokens??Qo,responseBufferTokens:er,maxOutputTokens:e.maxOutputTokens??tr,abortSignal:I,reactiveCompactEnabled:!0,outputEscalationEnabled:!0},O=new Set,N=0,De=0,$e=0,Ze=0,ho=new Map,K=new Set,y=ye(L,K),Ue=!1,Lt=!1,Ot,Nt=()=>C(y),Xs=Hl(L,i),Ft=!1,yo=0,bo=0,z=!1,Je=!1,Bt=Zc(i),c={messages:[...i],maxOutputTokensRecoveryCount:0,hasAttemptedReactiveCompact:!1,maxOutputTokensOverride:void 0,turnCount:1,transition:void 0,guardState:vn(Me),reactiveCompactState:En(),toolLoopState:gt({maxRounds:U,replayMessages:[...i]}).state,consecutiveFailedRounds:0,finalText:"",totalUsage:{inputTokens:0,outputTokens:0},collapseStore:cn(),currentModel:p,consecutive529Errors:0,consecutiveApiRetries:0,stopHookActive:void 0,lastResponseId:void 0,snipRemovedIds:new Set,contentReplacementState:e.runtimePorts.createContentReplacementState(),budgetContinuationCount:0,repeatedToolFailureRecoveryCount:0,lastBudgetDeltaTokens:0,lastBudgetGlobalTokens:0,identicalCallCounts:new Map,identicalSuccessfulToolResults:new Map,toolFailureCounts:new Map,fileReadCounts:Bt.fileReadCounts,fileReadCycleBlockedPaths:new Set,fileReadCycleNudgedPaths:new Set,maintainedDocuments:Bt.maintainedDocuments,persistedBenchmarkStateRecovered:Bt.persistedBenchmarkStateRecovered,benchmarkStateMaintenanceRequiredFiles:new Set,benchmarkStateMaintenanceWrittenFiles:new Set,recoveryTrace:new Map,artifactContract:Pr(i),browserAcceptanceRecoveryCount:0,buildVerificationRecoveryCount:0,backgroundAgentTaskIds:new Set,backgroundAgentNoOutputPollCounts:new Map,stalledBackgroundAgentTasks:new Map,notOfferedToolRecoveryCount:0,existingFileUpdateRecoveryCount:0,taskListReconciliationCount:0,lastTaskList:[]},Dt=Math.max(x*5,200),Ys=4,Zs=4,To=0,Co=new Map,$t,S=(m,j)=>{let fe=`${m}:${j??""}`,re=(Co.get(fe)??0)+1;if(Co.set(fe,re),m==="autocompact"){let $=c.recoveryTrace.get("autocompact")??0;if(re>Ys||$>=Zs){let J=`Repeated context compression made no forward progress: ${j??"autocompact"}`;return $t=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:j}},Js=()=>({type:"tool_use_summary",turnId:r,availableToolNames:C(l??u),enabledToolNames:Nt(),toolCallNames:[...O].sort(),blockedToolCalls:_t(F)}),Qs=m=>Lr({content:m,inputMessages:i,messages:c.messages,totalToolCallCount:N,distinctToolNames:O,artifactContract:c.artifactContract,blockedToolCalls:_t(F),activeTasks:c.lastTaskList}),ei=m=>({type:"end",turnId:r,content:m,usage:c.totalUsage,model:c.currentModel,...c.recoveryTrace.size>0?{recoveryTrace:Object.fromEntries(c.recoveryTrace)}:{}});function*V(m){let j=Qs(m);$n(c.artifactContract,j),jt()&&(yield Ut()),yield Js(),yield ei(j)}let Ut=()=>({type:"artifact_contract",turnId:r,...Dn(c.artifactContract,i)}),jt=()=>{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)},Qe=(m,j)=>c.finalText||qn(m,o),ti=(m,j,fe)=>{let re=we({inputMessages:i,messages:j,reason:fe});return re||m||qn(j,o)};for(;;){if(To++,To>Dt){o.info(`hard iteration cap reached (${Dt}), forcing completion`);let a=Qe(c.messages,`hard iteration cap reached (${Dt}) before completing the final status contract`);yield*V(a);return}let{messages:m,maxOutputTokensRecoveryCount:j,maxOutputTokensOverride:fe,turnCount:re,guardState:$,reactiveCompactState:J,collapseStore:qt}=c,{toolLoopState:Q}=c;if(e.refreshTools&&re>1){let a=e.refreshTools(),d=ye(a,K);d!==y&&(y=d,o.debug(`tools refreshed: ${a.length} tools`))}if(Mn($,Me)){o.info(`turn aborted by guard at turn ${re}`),yield{type:"error",turnId:r,error:"Turn aborted",code:"ABORTED",usage:c.totalUsage};return}let Te=wn($,Me);if(Te.level==="blocking"){Te.reason==="prompt_too_long"&&Oe(J)&&(J.attemptedThisTurn=!0,$.hasAttemptedReactiveCompact=!0,o.info(`token budget blocking (${Te.reason}), reactive compact needed`),yield S("reactive_compact","token budget pre-check")),o.info(`token budget blocking (${Te.reason}), ending tool loop`);break}Te.level==="warning"&&o.info(`token budget warning: ${Te.usagePercent}% used, ${Te.remainingTokens} remaining`);let et=yield*Zr({messages:m,contentReplacementState:c.contentReplacementState,snipRemovedIds:c.snipRemovedIds,collapseStore:qt,guardState:$,guardConfig:Me,runtimePorts:e.runtimePorts,hooks:k,hookCtx:P,sessionId:s,currentModel:c.currentModel,log:o,recovery:S,onAutocompact:()=>{c.hasAttemptedReactiveCompact=!1}});if($t){yield*V(`${$t}. Stop compressing the same context repeatedly; continue from the maintained document index or report the incomplete state explicitly.`);return}let ni=z?"required":e.toolChoice==="required"&&Ft?"auto":e.toolChoice??"auto";z=!1;let Ee=yn({tools:y,toolChoice:ni}),ko=C(Ee.tools).join("\0"),Ro=Ot!==void 0&&Ot!==ko;Ro&&c.lastResponseId&&(yield S("stateless_retry","tool schema changed; replaying full history without previous_response_id"));let oi=Je||Ro?void 0:c.lastResponseId;Ot=ko;let je=gt({maxRounds:U,replayMessages:et,lastStopReason:Q.lastStopReason,options:{stopReason:Q.lastStopReason}}),xo=Ee.extraSystemPrompt?[{role:"system",content:Ee.extraSystemPrompt},...je.state.replayMessages]:je.state.replayMessages;Q=je.state,je.recoveryActions.length>0&&o.debug(`tool loop recovery: ${je.recoveryActions.map(a=>a.detail??a.kind).join("; ")}`),o.debug(`turn ${re}, messages: ${xo.length}`),D(k,"turn.before_inference",{...P,model:c.currentModel},o);let zt=!1,Ht=[],_o=new Map,vo="stop",ee,M=null,tt=!1,wo=!1,qe=[],le=[];try{let a=t.stream({model:c.currentModel,messages:xo,...Ee.tools.length>0?{tools:Ee.tools,toolChoice:Ee.normalizedToolChoice??"auto"}:{},temperature:b,maxTokens:(fe??$.currentMaxOutputTokens)||void 0,streamRequired:e.streamRequired,previousResponseId:oi,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,I);for await(let d of Oc(a,e.llmStreamIdleTimeoutMs??Rc))switch(d.type){case"delta":Ht.push(d.text);break;case"tool_call_delta":zt=!0,In(_o,d);break;case"reasoning_delta":qe.push(d.text);break;case"reasoning_block_complete":d.signature&&le.push({thinking:qe.join(""),signature:d.signature}),qe.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":Je||(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":wo=!0,vo=d.finishReason;break}if(zt||D(k,"turn.after_inference",{...P,model:c.currentModel},o),e.postSamplingHooks&&e.postSamplingHooks.length>0){let d=c.currentModel;for(let g of e.postSamplingHooks)try{g({messages:[...et],model:d,sessionId:s})}catch{}}}catch(a){if(a instanceof Et){D(k,"stop.failure",{sessionId:s,reason:a.code,error:a.message},o),yield{type:"error",turnId:r,error:a.message,code:a.code,usage:c.totalUsage};return}let d=yield*Jr(a,{state:c,guardState:$,fallbackModel:e.fallbackModel,signal:I,querySource:E,turnId:r,log:o,emitRecovery:S});if(d.kind==="return")return;if(d.kind==="continue"){c={...c,...d.patch};continue}M=d.streamError}if(!M&&!wo){let a="LLM stream closed before a terminal event; the response was likely truncated upstream.";D(k,"stop.failure",{sessionId:s,reason:"RETRYABLE_TRANSIENT",error:a},o),yield{type:"error",turnId:r,error:a,code:"RETRYABLE_TRANSIENT",usage:c.totalUsage};return}if(M&&D(k,"turn.after_inference",{...P,model:c.currentModel,response:{error:M.message}},o),M){if(!Je&&c.lastResponseId&&/previous_response_id not found/i.test(M.message)){let a=(c.consecutiveApiRetries??0)+1;if(a<=_e){o.info("previous_response_id not found \u2014 disabling response-id chaining, retrying statelessly"),yield S("stateless_retry","previous_response_id not found; replaying full history"),Je=!0,c={...c,lastResponseId:void 0,consecutiveApiRetries:a,transition:void 0};continue}}if(Wn(M))tt=!0,o.info(`withheld prompt_too_long error (status=${M.status})`);else if(Vn(M))tt=!0,o.info(`withheld media_size error (status=${M.status})`);else{let a=An({status:M.status??500,message:M.message},$,Me);if(a.action==="reactive_compact"&&Oe(J)&&(J.attemptedThisTurn=!0,$.hasAttemptedReactiveCompact=!0,yield S("reactive_compact",`API ${M.status??500}: ${M.message}`)),a.action==="retry"){let g=(c.consecutiveApiRetries??0)+1;if(g>_e){o.info(`API retry limit reached (${_e}), aborting`);let f=Le(M.status,M.message);yield{type:"error",turnId:r,error:M.message,code:f,usage:c.totalUsage};return}yield S("retry",a.reason),c={...c,consecutiveApiRetries:g,transition:void 0};continue}let d=Le(M.status,M.message);D(k,"stop.failure",{sessionId:s,reason:d,error:M.message},o),yield{type:"error",turnId:r,error:M.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&&($.promptTokens=ee.inputTokens);let nt=Ht.join(""),te=[..._o.values()].map((a,d)=>({id:a.id||`tc_${r}_${d}`,type:"function",function:{name:a.name,arguments:a.arguments}}));if(te=Fc(te),te.length===0&&!zt){if(nt&&(c.finalText=nt),e.toolChoice==="required"&&!Ft&&y.length>0&&yo<2){yo++;let T=y.map(v=>v.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: ${T}. Do not answer from memory, prior context, or guesses.`}],finalText:"",transition:{reason:"next_turn"}};continue}if(tt&&M&&Wn(M)){if(c.transition?.reason!=="collapse_drain_retry"){let T=dn(et,qt);if(T.committed>0){o.info(`collapse drain: committed ${T.committed} stages`),yield S("collapse_drain",`${T.committed} stages committed`),c={...c,messages:T.messages,transition:{reason:"collapse_drain_retry",committed:T.committed}};continue}}if(Oe(J)){J.attemptedThisTurn=!0,$.hasAttemptedReactiveCompact=!0,o.info("withheld 413: reactive compact attempt"),yield S("reactive_compact","withheld prompt_too_long"),c={...c,hasAttemptedReactiveCompact:!0,transition:{reason:"reactive_compact_retry"}};continue}o.info("withheld 413: recovery exhausted, surfacing error"),D(k,"stop.failure",{sessionId:s,reason:"prompt_too_long",error:M.message},o),yield{type:"error",turnId:r,error:M.message,code:"PROMPT_TOO_LONG",usage:c.totalUsage};return}if(tt&&M&&Vn(M)){if(Oe(J)){J.attemptedThisTurn=!0,$.hasAttemptedReactiveCompact=!0,o.info("withheld media error: reactive compact strip-retry"),yield S("reactive_compact","media error strip-retry"),c={...c,hasAttemptedReactiveCompact:!0,transition:{reason:"reactive_compact_retry"}};continue}o.info("withheld media error: recovery exhausted"),D(k,"stop.failure",{sessionId:s,reason:"media_error",error:M.message},o),yield{type:"error",turnId:r,error:M.message,code:"IMAGE_ERROR",usage:c.totalUsage};return}if(Kr(vo)){$.consecutiveTruncations+=1;let T=e.modelMaxOutputTokens??nr,v=Sn($,Me,T);if(v.shouldEscalate&&fe===void 0){$.currentMaxOutputTokens=v.newMax,o.info(`max_output_tokens escalate: ${v.newMax} tokens`),yield S("output_escalation",`${v.newMax} tokens`),c={...c,maxOutputTokensOverride:rr,transition:{reason:"max_output_tokens_escalate"}};continue}if(j<or){let X={role:"user",content:"Output token limit hit. Resume directly - no apology, no recap of what you were doing. Pick up mid-thought if that is where the cut happened. Break remaining work into smaller pieces."};o.info(`max_output_tokens recovery #${j+1}`),yield S("max_output_tokens_recovery",`attempt ${j+1}`),c={...c,messages:[...et,X],maxOutputTokensRecoveryCount:j+1,maxOutputTokensOverride:void 0,transition:{reason:"max_output_tokens_recovery",attempt:j+1}};continue}o.info("max_output_tokens recovery exhausted, completing with partial content")}else $.consecutiveTruncations=0;Q=mt(Q,{replayMessages:m,lastStopReason:"completed"});let a=await ds({hooks:k,sessionId:s,messages:m,finalText:c.finalText,thinkingBlocks:le,log:o});if(a?.action==="end"){let T=ti(a.content,m,"stop hook prevented continuation before completing the final status contract");yield*V(T);return}if(a?.action==="continue"){c={...c,messages:a.messages,stopHookActive:a.stopHookActive,transition:a.transition};continue}let d=fs({tokenBudget:e.tokenBudget,totalUsage:c.totalUsage,budgetContinuationCount:c.budgetContinuationCount,lastBudgetDeltaTokens:c.lastBudgetDeltaTokens,lastBudgetGlobalTokens:c.lastBudgetGlobalTokens,messages:m,finalText:c.finalText,thinkingBlocks:le,getBudgetContinuationMessage:e.runtimePorts.getBudgetContinuationMessage,log:o});if(d){yield S("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()&&ac(c.lastTaskList)&&c.taskListReconciliationCount<1){let T=y.find(v=>v.function.name==="task")??(l??u).find(v=>v.function.name==="task");if(T){let v=ic(c.lastTaskList),X=C(y),q=ye(L,K);y=q.some(nn=>nn.function.name==="task")?q:wt([...q,T]),c={...c,taskListReconciliationCount:c.taskListReconciliationCount+1,messages:[...m,{role:"assistant",content:c.finalText},{role:"user",content:v}],transition:{reason:"next_turn"}},z=!0,yield{type:"tool_selection_policy",turnId:r,policyId:"task_list_reconciliation_required",intent:"lifecycle_reconciliation",reason:"task-list-final-status-mismatch",availableToolNames:C(l??u),enabledToolNamesBefore:X,enabledToolNamesAfter:C(y),suppressedToolNames:[],nextAction:"reconcile-task-list-before-final"},yield S("task_list_reconciliation_required","nudging task-list status sync before the final response");continue}}if(ie(i)&&!c.artifactContract.browserVerified&&Mt(c.artifactContract).length>0&&y.some(T=>T.function.name==="exec")&&c.browserAcceptanceRecoveryCount<4){let T=Ss(c.artifactContract);c={...c,browserAcceptanceRecoveryCount:c.browserAcceptanceRecoveryCount+1,messages:[...m,{role:"assistant",content:c.finalText},{role:"user",content:T}],transition:{reason:"next_turn"}},z=!0,yield S("browser_acceptance_required","forcing browser automation before app/frontend completion");continue}if((e.buildVerificationGate??!0)&&Nn(i)&&!c.artifactContract.buildVerified&&c.artifactContract.buildFailureEvidence.length>0&&y.some(T=>T.function.name==="exec")&&c.buildVerificationRecoveryCount<3){let T=nc(c.artifactContract);c={...c,buildVerificationRecoveryCount:c.buildVerificationRecoveryCount+1,messages:[...m,{role:"assistant",content:c.finalText},{role:"user",content:T}],transition:{reason:"next_turn"}},z=!0,yield S("build_verification_required","test/build still failing; forcing a fix+rerun before completion");continue}let g=eo({inputMessages:i,messages:m,finalText:c.finalText,thinkingBlocks:le,stopHookActive:c.stopHookActive,totalToolCallCount:N,distinctToolNames:O,log:o});if(g){if(c.stopHookActive&&c.finalText.trim()===""){let T=we({inputMessages:i,messages:g.messages,reason:"stop hook produced an empty response after tool use"});if(T){yield*V(T);return}}c={...c,messages:g.messages,stopHookActive:g.stopHookActive,transition:g.transition};continue}if(N===0&&y.length>0&&e.toolChoice!=="none"&&bo<1&&zr(nt)){bo++,z=!0,yield S("intent_without_action","announced but did not act; forcing a tool call"),c={...c,messages:[...m,{role:"assistant",content:nt},{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 f=to({totalToolCallCount:N,distinctToolNames:O,projectRoot:e.projectRoot});f&&(yield{type:"skill_instruction",turnId:r,instruction:f});let R=Qe(m,"the model ended with an empty response after tool use before completing the final status contract");for(let T of Ht)yield{type:"delta",turnId:r,text:T};yield*V(R);return}let ri=le.length===0&&qe.length>0?qe.join(""):void 0;m.push(rn(te,void 0,le.length>0?le:void 0,ri)),Q=Rn(Q,{replayMessages:m,pendingToolCallIds:te.map(a=>a.id),completedToolCallIds:Q.completedToolCallIds,lastStopReason:"tool_calls"});let ot=c.identicalCallCounts,ze=[],ce=[],He=[],Ao=!1;for(let a of te){if(mc(a,c)){ze.push(a);continue}let d=`${a.function.name}::${a.function.arguments}`,g=ot.get(d)??0;if(ot.set(d,g+1),g+1>Jo){let f=so.has(a.function.name)||a.function.name==="exec"?c.identicalSuccessfulToolResults.get(d):void 0;if(f){He.push({call:a,result:f,repeatCount:g+1});continue}ce.push(a),Ao||(Ao=!0,o.info(`AP4 blocked: ${a.function.name} repeated ${g+1}x`))}else ze.push(a)}let H=[],si=new Set(y.map(a=>a.function.name)),So=new Set(ce.filter(a=>Wc(a,si)).map(a=>a.id));for(let a of He){let d=a.call,g=`Reused previous successful ${d.function.name} result for identical arguments (attempt ${a.repeatCount}); no additional tool execution was performed.
|
|
41
|
+
`)}function Ps(e){return lo.has(e)}function Lc(e){return e.benchmarkStateMaintenanceRequiredFiles.size>0&&[...e.benchmarkStateMaintenanceRequiredFiles].every(t=>Nc(e,t))}function Nc(e,t){if(e.benchmarkStateMaintenanceWrittenFiles.has(t))return!0;try{if(!$e(t))return!1;let n=Se(t);if(n!=="document-index.json"&&n!=="context-pack-evidence.json")return!0;let o=po(t,"utf8");return js(e.maintainedDocuments,t,JSON.stringify({content:o})).ok}catch{return!1}}function js(e,t,n){let o=Se(t);if(o!=="document-index.json"&&o!=="context-pack-evidence.json")return{ok:!0};let r=Zc(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 l=ue(s.documents);if(!l)return{ok:!1,reason:"document-index.json missing documents object"};for(let u of Z.keys()){let p=e.get(u),y=ue(l[u]);if(!p||!y)return{ok:!1,reason:`document-index.json missing ${u}`};if(y.contentHash!==p.contentHash)return{ok:!1,reason:`document-index.json ${u} contentHash does not match read.details`};if(y.fileSizeBytes!==p.fileSizeBytes)return{ok:!1,reason:`document-index.json ${u} fileSizeBytes does not match read.details`}}return{ok:!0}}let i=ue(s.fileVerification);if(!i)return{ok:!1,reason:"context-pack-evidence.json missing fileVerification object"};for(let l of Z.keys()){let u=e.get(l),p=ue(i[l]);if(!u||!p)return{ok:!1,reason:`context-pack-evidence.json missing ${l}`};if(p.contentHash!==u.contentHash)return{ok:!1,reason:`context-pack-evidence.json ${l} contentHash does not match read.details`};if(p.fileSizeBytes!==u.fileSizeBytes)return{ok:!1,reason:`context-pack-evidence.json ${l} fileSizeBytes does not match read.details`}}return{ok:!0}}function Fc(e,t,n,o){if(e.filter(l=>l.name==="read"&&l.reason==="read-cycle-policy").length<Mc)return!1;let s=new Set([...t].filter(go).map(Se));return[...Z.keys()].every(l=>s.has(l))?[...Z.keys()].every(l=>o.has(l))||n||Ic(t):!1}function qs(e,t,n){if(e!=="write"||!n.has("edit")&&!n.has("patch"))return null;let o=Pt(t);if(!o)return null;try{if(!$e(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 It=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*Bc(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 It(t);if(r.done)return;yield r.value}}finally{n.return?.().catch(()=>{})}}function co(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 Pt(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 Dc(e){try{let t=JSON.parse(e),n=typeof t.query=="string"?t.query.trim():"";return n.startsWith("select:")?n.slice(7).split(",").map(o=>o.trim()).filter(Boolean).sort():[]}catch{return[]}}function $c(e){return e.flatMap(t=>{if(Uc(t.function.arguments))return[t];let n=jc(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 Uc(e){try{let t=JSON.parse(e);return!!t&&typeof t=="object"&&!Array.isArray(t)}catch{return!1}}function jc(e){let t=[],n=0,o=-1,r=!1,s=!1,i=0;for(let l=0;l<e.length;l+=1){let u=e[l];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,l).trim())return[];o=l}n+=1;continue}if(u!=="}"||(n-=1,n!==0||o<0))continue;let p=de(e.slice(o,l+1));if(!p)return[];t.push(p),i=l+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 W(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 Se(e){let t=e.trim().replace(/\\/g,"/");return t.slice(t.lastIndexOf("/")+1).toLowerCase()}function ho(e){return`sha256:${Wl("sha256").update(e).digest("hex")}`}function qc(e,t){let n=t.split(/\r?\n/).map(l=>l.trim()).filter(Boolean),o=n[0]??e,r=n.find(l=>/record\s+0*1\b/i.test(l)),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 zc(e){return Object.fromEntries([...e.entries()].sort(([t],[n])=>t.localeCompare(n)))}function Hc(e,t,n,o){let r=[...t.values()].sort((u,p)=>(u.name??"").localeCompare(p.name??""));if(r.length===0)return null;let s=r.map(u=>`${u.name??"document"}:${u.contentHash??"unknown"}`).join("|"),i=Fs.map(u=>({...u,evidence:`read:long-horizon-documents:${ho(`${u.id}:${s}`)}`,lastConfirmedTurn:o})),l={strategy:"maintained-document-index",nextReadPolicy:"use maintained index before full document reread",budgetStatus:"within-budget",maxReadsPerDocument:Ze,observedReadsByPath:zc(n)};return{type:"document_maintenance",turnId:e,checkpointId:`${e}-docs-${r.length}`,documents:r,decisionStateTable:i,readCycleFindings:[],readCycleGuard:l}}function Gc(e){let t=e.find(o=>o.path)?.path??"",n=t.lastIndexOf("/");return n>0?t.slice(0,n):t}function wt(e,t){return e.get(t)??null}function Wc(e){let t=wt(e,"requirements.md"),n=wt(e,"decisions.md"),o=wt(e,"defects.md"),r=wt(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:Gc(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 Vc(e,t){let n=Wc(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=uo(t,n,o,r);if(!s)return!1;let i=s.name;return i?(e.maintainedDocuments.set(i,s),!0):!1}function uo(e,t,n,o){let r=Se(e);if(!Z.has(r))return null;let s=Qc(t)??t,i=Jc(o,"contentHash"),l=Be(o??null,"fileSizeBytes"),u=i??ho(s);return{name:r,path:W(e),indexed:!0,maintained:!0,indexVersion:u,contentHash:u,summary:qc(r,s),lastReviewedTurn:n,fileSizeBytes:l??Buffer.byteLength(s,"utf8"),recordCount:zs(s)}}function Xc(e,t){return qs(e.function.name,e.function.arguments,t)!==null}function Yc(e,t){let n=Pt(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 Zc(e){let n=de(e)?.content;return typeof n=="string"?n:void 0}function Jc(e,t){let n=e?.[t];return typeof n=="string"&&n.trim()?n.trim():void 0}function zs(e){let t=e.split(/\r?\n/).map(n=>n.trim()).filter(Boolean).length;return Math.max(1,t)}function Qc(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 $e(n)?po(n,"utf8"):null}catch{return null}}function eu(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 l=co(i.function.arguments);if(!l)continue;let u=W(l);Bs(u)===Ze&&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 l=typeof s.content=="string"?s.content:"";if(!l||/^Error:/i.test(l.trim()))continue;n.set(i.path,(n.get(i.path)??0)+1);let u=uo(i.path,l,0);u?.name&&o.set(u.name,u)}for(let s of su(e)){r=!0;for(let i of Z.keys()){let l=W(`${s}/${i}`);if(n.set(l,Math.max(n.get(l)??0,Ze)),!o.has(i)){let u=uo(l,`${i} maintained by benchmark-state/document-index.json from prior conversation history.`,0);u?.name&&o.set(u.name,u)}}}for(let s of tu(e)){r=!0;for(let i of s.documents)!i.name||!i.path||(n.set(i.path,Math.max(n.get(i.path)??0,Ze)),o.set(i.name,i))}return{fileReadCounts:n,maintainedDocuments:o,persistedBenchmarkStateRecovered:r}}function tu(e){let t=[];for(let n of nu(e)){let o=Os(`${n}/document-index.json`),r=Os(`${n}/context-pack-evidence.json`),s=De(o,"contextPackPath")??ou(r);if(!s)continue;let i=ru(s,o,r);i.length===Z.size&&t.push({documents:i})}return t}function nu(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=W(s[1]??"");i&&t.add(i)}}return[...t]}function Os(e){try{if(!$e(e))return null;let t=JSON.parse(po(e,"utf8"));return t&&typeof t=="object"&&!Array.isArray(t)?t:null}catch{return null}}function De(e,t){let n=e?.[t];return typeof n=="string"&&n.trim()?W(n):void 0}function ou(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=De(o,"path");if(!r)continue;let s=`/${n}`;if(r.endsWith(s))return r.slice(0,-s.length)}}function ru(e,t,n){let o=ue(t?.documents),r=ue(n?.fileVerification),s=[];for(let i of Z.keys()){let l=ue(o?.[i]),u=ue(r?.[i]);if(!l&&!u)return[];let p=De(l,"path"),b=De(u,"path")??(p?.includes("/context-pack/")?p:W(`${e}/${i}`)),k=De(l,"contentHash")??De(u,"contentHash")??ho(`${i}:${b}`),I=typeof l?.summary=="string"&&l.summary.trim()?l.summary.trim():`${i} maintained by persisted benchmark-state/document-index.json.`;s.push({name:i,path:W(b),indexed:!0,maintained:!0,indexVersion:String(l?.indexVersion??k),contentHash:k,summary:I,lastReviewedTurn:fo(l,"lastReviewedTurn")??fo(n,"turn")??0,fileSizeBytes:Be(l,"fileSizeBytes")??Be(u,"fileSizeBytes")??Be(u,"sizeBytes")??Buffer.byteLength(I,"utf8"),recordCount:Be(l,"recordCount")??Be(u,"recordCount")??zs(I)})}return s}function fo(e,t){let n=e?.[t];return typeof n=="number"&&Number.isFinite(n)?n:void 0}function Be(e,t){let n=fo(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 l=W(i[1]??"");l&&n.add(l)}}return[...n]}function iu(e){e.identicalSuccessfulToolResults.clear();for(let t of[...e.identicalCallCounts.keys()]){let n=t.slice(0,t.indexOf("::"));ao.has(n)&&e.identicalCallCounts.delete(t)}}async function*Hs(e,t,n,o){let{turnId:r,sessionId:s,messages:i,availableTools:l,tools:u,model:p,apiKey:y,temperature:b=0,hooks:k,signal:I}=e,P={sessionId:s,turnId:r},x=e.maxTurns??0,E=e.querySource,w=e.runtimePorts.resolveToolEligibility(u,e.toolEligibilityContext),O=w.eligibleTools,F=[];for(let m of w.blockedTools)F.push({name:m.toolName,reason:"blocked-by-policy"}),yield{type:"tool_blocked",turnId:r,callId:"",name:m.toolName,reason:"blocked-by-policy"};let U=Wr(e.maxRounds,i),oe=Vr(e.maxToolCalls,i),Ot=!(typeof e.maxRounds=="number"&&e.maxRounds>=1)&&!(typeof e.maxToolCalls=="number"&&e.maxToolCalls>=1),yo=kt(i),Me={contextWindowTokens:e.contextWindowTokens??tr,responseBufferTokens:nr,maxOutputTokens:e.maxOutputTokens??or,abortSignal:I,reactiveCompactEnabled:!0,outputEscalationEnabled:!0},L=new Set,N=0,Ue=0,je=0,Je=0,bo=new Map,K=new Set,h=ye(O,K),qe=!1,Lt=!1,Nt,Ft=()=>C(h),Ys=Vl(O,i),Bt=!1,To=0,Co=0,z=!1,Qe=!1,Dt=eu(i),c={messages:[...i],maxOutputTokensRecoveryCount:0,hasAttemptedReactiveCompact:!1,maxOutputTokensOverride:void 0,turnCount:1,transition:void 0,guardState:wn(Me),reactiveCompactState:In(),toolLoopState:ht({maxRounds:U,replayMessages:[...i]}).state,consecutiveFailedRounds:0,finalText:"",totalUsage:{inputTokens:0,outputTokens:0},collapseStore:un(),currentModel:p,consecutive529Errors:0,consecutiveApiRetries:0,stopHookActive:void 0,lastResponseId:void 0,snipRemovedIds:new Set,contentReplacementState:e.runtimePorts.createContentReplacementState(),budgetContinuationCount:0,repeatedToolFailureRecoveryCount:0,lastBudgetDeltaTokens:0,lastBudgetGlobalTokens:0,identicalCallCounts:new Map,identicalSuccessfulToolResults:new Map,toolFailureCounts:new Map,fileReadCounts:Dt.fileReadCounts,fileReadCycleBlockedPaths:new Set,fileReadCycleNudgedPaths:new Set,maintainedDocuments:Dt.maintainedDocuments,persistedBenchmarkStateRecovered:Dt.persistedBenchmarkStateRecovered,benchmarkStateMaintenanceRequiredFiles:new Set,benchmarkStateMaintenanceWrittenFiles:new Set,recoveryTrace:new Map,artifactContract:Lr(i),browserAcceptanceRecoveryCount:0,buildVerificationRecoveryCount:0,backgroundAgentTaskIds:new Set,backgroundAgentNoOutputPollCounts:new Map,stalledBackgroundAgentTasks:new Map,notOfferedToolRecoveryCount:0,existingFileUpdateRecoveryCount:0,taskListReconciliationCount:0,lastTaskList:[]},$t=Math.max(x*5,200),Zs=4,Js=4,ko=0,Ro=new Map,Ut,S=(m,j)=>{let fe=`${m}:${j??""}`,re=(Ro.get(fe)??0)+1;if(Ro.set(fe,re),m==="autocompact"){let $=c.recoveryTrace.get("autocompact")??0;if(re>Zs||$>=Js){let J=`Repeated context compression made no forward progress: ${j??"autocompact"}`;return Ut=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:j}},Qs=()=>({type:"tool_use_summary",turnId:r,availableToolNames:C(l??u),enabledToolNames:Ft(),toolCallNames:[...L].sort(),blockedToolCalls:vt(F)}),ei=m=>Nr({content:m,inputMessages:i,messages:c.messages,totalToolCallCount:N,distinctToolNames:L,artifactContract:c.artifactContract,blockedToolCalls:vt(F),activeTasks:c.lastTaskList}),ti=m=>({type:"end",turnId:r,content:m,usage:c.totalUsage,model:c.currentModel,...c.recoveryTrace.size>0?{recoveryTrace:Object.fromEntries(c.recoveryTrace)}:{}});function*V(m){let j=ei(m);Un(c.artifactContract,j),qt()&&(yield jt()),yield Qs(),yield ti(j)}let jt=()=>({type:"artifact_contract",turnId:r,...$n(c.artifactContract,i)}),qt=()=>{let m=$n(c.artifactContract,i);return!!(m.requiresBrowserAcceptance||m.artifactRoot||m.writePaths.length>0||m.outOfRootWrites.length>0||m.devServerUrls.length>0||m.browserVerified)},et=(m,j)=>c.finalText||zn(m,o),ni=(m,j,fe)=>{let re=we({inputMessages:i,messages:j,reason:fe});return re||m||zn(j,o)};for(;;){if(ko++,ko>$t){o.info(`hard iteration cap reached (${$t}), forcing completion`);let a=et(c.messages,`hard iteration cap reached (${$t}) before completing the final status contract`);yield*V(a);return}let{messages:m,maxOutputTokensRecoveryCount:j,maxOutputTokensOverride:fe,turnCount:re,guardState:$,reactiveCompactState:J,collapseStore:zt}=c,{toolLoopState:Q}=c;if(e.refreshTools&&re>1){let a=e.refreshTools(),d=ye(a,K);d!==h&&(h=d,o.debug(`tools refreshed: ${a.length} tools`))}if(En($,Me)){o.info(`turn aborted by guard at turn ${re}`),yield{type:"error",turnId:r,error:"Turn aborted",code:"ABORTED",usage:c.totalUsage};return}let Te=An($,Me);if(Te.level==="blocking"){Te.reason==="prompt_too_long"&&Le(J)&&(J.attemptedThisTurn=!0,$.hasAttemptedReactiveCompact=!0,o.info(`token budget blocking (${Te.reason}), reactive compact needed`),yield S("reactive_compact","token budget pre-check")),o.info(`token budget blocking (${Te.reason}), ending tool loop`);break}Te.level==="warning"&&o.info(`token budget warning: ${Te.usagePercent}% used, ${Te.remainingTokens} remaining`);let tt=yield*Qr({messages:m,contentReplacementState:c.contentReplacementState,snipRemovedIds:c.snipRemovedIds,collapseStore:zt,guardState:$,guardConfig:Me,runtimePorts:e.runtimePorts,hooks:k,hookCtx:P,sessionId:s,currentModel:c.currentModel,log:o,recovery:S,onAutocompact:()=>{c.hasAttemptedReactiveCompact=!1}});if(Ut){yield*V(`${Ut}. Stop compressing the same context repeatedly; continue from the maintained document index or report the incomplete state explicitly.`);return}let oi=z?"required":e.toolChoice==="required"&&Bt?"auto":e.toolChoice??"auto";z=!1;let Ee=bn({tools:h,toolChoice:oi}),xo=C(Ee.tools).join("\0"),_o=Nt!==void 0&&Nt!==xo;_o&&c.lastResponseId&&(yield S("stateless_retry","tool schema changed; replaying full history without previous_response_id"));let ri=Qe||_o?void 0:c.lastResponseId;Nt=xo;let ze=ht({maxRounds:U,replayMessages:tt,lastStopReason:Q.lastStopReason,options:{stopReason:Q.lastStopReason}}),vo=Ee.extraSystemPrompt?[{role:"system",content:Ee.extraSystemPrompt},...ze.state.replayMessages]:ze.state.replayMessages;Q=ze.state,ze.recoveryActions.length>0&&o.debug(`tool loop recovery: ${ze.recoveryActions.map(a=>a.detail??a.kind).join("; ")}`),o.debug(`turn ${re}, messages: ${vo.length}`),D(k,"turn.before_inference",{...P,model:c.currentModel},o);let Ht=!1,Gt=[],wo=new Map,Ao="stop",ee,M=null,nt=!1,So=!1,He=[],le=[];try{let a=t.stream({model:c.currentModel,messages:vo,...Ee.tools.length>0?{tools:Ee.tools,toolChoice:Ee.normalizedToolChoice??"auto"}:{},temperature:b,maxTokens:(fe??$.currentMaxOutputTokens)||void 0,streamRequired:e.streamRequired,previousResponseId:ri,reasoning:e.reasoning,promptCacheKey:e.promptCacheKey,promptCacheRetention:e.promptCacheRetention,serviceTier:e.serviceTier,openaiBuiltinTools:e.openaiBuiltinTools,maxToolCalls:e.maxToolCalls,parallelToolCalls:e.parallelToolCalls,textVerbosity:e.textVerbosity},y,I);for await(let d of Bc(a,e.llmStreamIdleTimeoutMs??vc))switch(d.type){case"delta":Gt.push(d.text);break;case"tool_call_delta":Ht=!0,Pn(wo,d);break;case"reasoning_delta":He.push(d.text);break;case"reasoning_block_complete":d.signature&&le.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":Qe||(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":So=!0,Ao=d.finishReason;break}if(Ht||D(k,"turn.after_inference",{...P,model:c.currentModel},o),e.postSamplingHooks&&e.postSamplingHooks.length>0){let d=c.currentModel;for(let g of e.postSamplingHooks)try{g({messages:[...tt],model:d,sessionId:s})}catch{}}}catch(a){if(a instanceof It){D(k,"stop.failure",{sessionId:s,reason:a.code,error:a.message},o),yield{type:"error",turnId:r,error:a.message,code:a.code,usage:c.totalUsage};return}let d=yield*es(a,{state:c,guardState:$,fallbackModel:e.fallbackModel,signal:I,querySource:E,turnId:r,log:o,emitRecovery:S});if(d.kind==="return")return;if(d.kind==="continue"){c={...c,...d.patch};continue}M=d.streamError}if(!M&&!So){let a="LLM stream closed before a terminal event; the response was likely truncated upstream.";D(k,"stop.failure",{sessionId:s,reason:"RETRYABLE_TRANSIENT",error:a},o),yield{type:"error",turnId:r,error:a,code:"RETRYABLE_TRANSIENT",usage:c.totalUsage};return}if(M&&D(k,"turn.after_inference",{...P,model:c.currentModel,response:{error:M.message}},o),M){if(!Qe&&c.lastResponseId&&/previous_response_id not found/i.test(M.message)){let a=(c.consecutiveApiRetries??0)+1;if(a<=_e){o.info("previous_response_id not found \u2014 disabling response-id chaining, retrying statelessly"),yield S("stateless_retry","previous_response_id not found; replaying full history"),Qe=!0,c={...c,lastResponseId:void 0,consecutiveApiRetries:a,transition:void 0};continue}}if(Vn(M))nt=!0,o.info(`withheld prompt_too_long error (status=${M.status})`);else if(Kn(M))nt=!0,o.info(`withheld media_size error (status=${M.status})`);else{let a=Sn({status:M.status??500,message:M.message},$,Me);if(a.action==="reactive_compact"&&Le(J)&&(J.attemptedThisTurn=!0,$.hasAttemptedReactiveCompact=!0,yield S("reactive_compact",`API ${M.status??500}: ${M.message}`)),a.action==="retry"){let g=(c.consecutiveApiRetries??0)+1;if(g>_e){o.info(`API retry limit reached (${_e}), aborting`);let f=Oe(M.status,M.message);yield{type:"error",turnId:r,error:M.message,code:f,usage:c.totalUsage};return}yield S("retry",a.reason),c={...c,consecutiveApiRetries:g,transition:void 0};continue}let d=Oe(M.status,M.message);D(k,"stop.failure",{sessionId:s,reason:d,error:M.message},o),yield{type:"error",turnId:r,error:M.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&&($.promptTokens=ee.inputTokens);let ot=Gt.join(""),ne=[...wo.values()].map((a,d)=>({id:a.id||`tc_${r}_${d}`,type:"function",function:{name:a.name,arguments:a.arguments}}));if(ne=$c(ne),ne.length===0&&!Ht){if(ot&&(c.finalText=ot),e.toolChoice==="required"&&!Bt&&h.length>0&&To<2){To++;let T=h.map(v=>v.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: ${T}. Do not answer from memory, prior context, or guesses.`}],finalText:"",transition:{reason:"next_turn"}};continue}if(nt&&M&&Vn(M)){if(c.transition?.reason!=="collapse_drain_retry"){let T=fn(tt,zt);if(T.committed>0){o.info(`collapse drain: committed ${T.committed} stages`),yield S("collapse_drain",`${T.committed} stages committed`),c={...c,messages:T.messages,transition:{reason:"collapse_drain_retry",committed:T.committed}};continue}}if(Le(J)){J.attemptedThisTurn=!0,$.hasAttemptedReactiveCompact=!0,o.info("withheld 413: reactive compact attempt"),yield S("reactive_compact","withheld prompt_too_long"),c={...c,hasAttemptedReactiveCompact:!0,transition:{reason:"reactive_compact_retry"}};continue}o.info("withheld 413: recovery exhausted, surfacing error"),D(k,"stop.failure",{sessionId:s,reason:"prompt_too_long",error:M.message},o),yield{type:"error",turnId:r,error:M.message,code:"PROMPT_TOO_LONG",usage:c.totalUsage};return}if(nt&&M&&Kn(M)){if(Le(J)){J.attemptedThisTurn=!0,$.hasAttemptedReactiveCompact=!0,o.info("withheld media error: reactive compact strip-retry"),yield S("reactive_compact","media error strip-retry"),c={...c,hasAttemptedReactiveCompact:!0,transition:{reason:"reactive_compact_retry"}};continue}o.info("withheld media error: recovery exhausted"),D(k,"stop.failure",{sessionId:s,reason:"media_error",error:M.message},o),yield{type:"error",turnId:r,error:M.message,code:"IMAGE_ERROR",usage:c.totalUsage};return}if(Yr(Ao)){$.consecutiveTruncations+=1;let T=e.modelMaxOutputTokens??rr,v=Mn($,Me,T);if(v.shouldEscalate&&fe===void 0){$.currentMaxOutputTokens=v.newMax,o.info(`max_output_tokens escalate: ${v.newMax} tokens`),yield S("output_escalation",`${v.newMax} tokens`),c={...c,maxOutputTokensOverride:ir,transition:{reason:"max_output_tokens_escalate"}};continue}if(j<sr){let X={role:"user",content:"Output token limit hit. Resume directly - no apology, no recap of what you were doing. Pick up mid-thought if that is where the cut happened. Break remaining work into smaller pieces."};o.info(`max_output_tokens recovery #${j+1}`),yield S("max_output_tokens_recovery",`attempt ${j+1}`),c={...c,messages:[...tt,X],maxOutputTokensRecoveryCount:j+1,maxOutputTokensOverride:void 0,transition:{reason:"max_output_tokens_recovery",attempt:j+1}};continue}o.info("max_output_tokens recovery exhausted, completing with partial content")}else $.consecutiveTruncations=0;Q=gt(Q,{replayMessages:m,lastStopReason:"completed"});let a=await fs({hooks:k,sessionId:s,messages:m,finalText:c.finalText,thinkingBlocks:le,log:o});if(a?.action==="end"){let T=ni(a.content,m,"stop hook prevented continuation before completing the final status contract");yield*V(T);return}if(a?.action==="continue"){c={...c,messages:a.messages,stopHookActive:a.stopHookActive,transition:a.transition};continue}let d=ps({tokenBudget:e.tokenBudget,totalUsage:c.totalUsage,budgetContinuationCount:c.budgetContinuationCount,lastBudgetDeltaTokens:c.lastBudgetDeltaTokens,lastBudgetGlobalTokens:c.lastBudgetGlobalTokens,messages:m,finalText:c.finalText,thinkingBlocks:le,getBudgetContinuationMessage:e.runtimePorts.getBudgetContinuationMessage,log:o});if(d){yield S("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()&&uc(c.lastTaskList)&&c.taskListReconciliationCount<1){let T=h.find(v=>v.function.name==="task")??(l??u).find(v=>v.function.name==="task");if(T){let v=cc(c.lastTaskList),X=C(h),q=ye(O,K);h=q.some(on=>on.function.name==="task")?q:At([...q,T]),c={...c,taskListReconciliationCount:c.taskListReconciliationCount+1,messages:[...m,{role:"assistant",content:c.finalText},{role:"user",content:v}],transition:{reason:"next_turn"}},z=!0,yield{type:"tool_selection_policy",turnId:r,policyId:"task_list_reconciliation_required",intent:"lifecycle_reconciliation",reason:"task-list-final-status-mismatch",availableToolNames:C(l??u),enabledToolNamesBefore:X,enabledToolNamesAfter:C(h),suppressedToolNames:[],nextAction:"reconcile-task-list-before-final"},yield S("task_list_reconciliation_required","nudging task-list status sync before the final response");continue}}if(ie(i)&&!c.artifactContract.browserVerified&&Et(c.artifactContract).length>0&&h.some(T=>T.function.name==="exec")&&c.browserAcceptanceRecoveryCount<4){let T=Ms(c.artifactContract);c={...c,browserAcceptanceRecoveryCount:c.browserAcceptanceRecoveryCount+1,messages:[...m,{role:"assistant",content:c.finalText},{role:"user",content:T}],transition:{reason:"next_turn"}},z=!0,yield S("browser_acceptance_required","forcing browser automation before app/frontend completion");continue}if((e.buildVerificationGate??!0)&&Fn(i)&&!c.artifactContract.buildVerified&&c.artifactContract.buildFailureEvidence.length>0&&h.some(T=>T.function.name==="exec")&&c.buildVerificationRecoveryCount<3){let T=sc(c.artifactContract);c={...c,buildVerificationRecoveryCount:c.buildVerificationRecoveryCount+1,messages:[...m,{role:"assistant",content:c.finalText},{role:"user",content:T}],transition:{reason:"next_turn"}},z=!0,yield S("build_verification_required","test/build still failing; forcing a fix+rerun before completion");continue}let g=no({inputMessages:i,messages:m,finalText:c.finalText,thinkingBlocks:le,stopHookActive:c.stopHookActive,totalToolCallCount:N,distinctToolNames:L,log:o});if(g){if(c.stopHookActive&&c.finalText.trim()===""){let T=we({inputMessages:i,messages:g.messages,reason:"stop hook produced an empty response after tool use"});if(T){yield*V(T);return}}c={...c,messages:g.messages,stopHookActive:g.stopHookActive,transition:g.transition};continue}if(N===0&&h.length>0&&e.toolChoice!=="none"&&Co<1&&Gr(ot)){Co++,z=!0,yield S("intent_without_action","announced but did not act; forcing a tool call"),c={...c,messages:[...m,{role:"assistant",content:ot},{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 f=oo({totalToolCallCount:N,distinctToolNames:L,projectRoot:e.projectRoot});f&&(yield{type:"skill_instruction",turnId:r,instruction:f});let R=et(m,"the model ended with an empty response after tool use before completing the final status contract");for(let T of Gt)yield{type:"delta",turnId:r,text:T};yield*V(R);return}let si=le.length===0&&He.length>0?He.join(""):void 0;m.push(sn(ne,void 0,le.length>0?le:void 0,si)),Q=xn(Q,{replayMessages:m,pendingToolCallIds:ne.map(a=>a.id),completedToolCallIds:Q.completedToolCallIds,lastStopReason:"tool_calls"});let rt=c.identicalCallCounts,Ge=[],ce=[],We=[],Mo=!1;for(let a of ne){if(yc(a,c)){Ge.push(a);continue}let d=`${a.function.name}::${a.function.arguments}`,g=rt.get(d)??0;if(rt.set(d,g+1),g+1>er){let f=ao.has(a.function.name)||a.function.name==="exec"?c.identicalSuccessfulToolResults.get(d):void 0;if(f){We.push({call:a,result:f,repeatCount:g+1});continue}ce.push(a),Mo||(Mo=!0,o.info(`AP4 blocked: ${a.function.name} repeated ${g+1}x`))}else Ge.push(a)}let H=[],ii=new Set(h.map(a=>a.function.name)),Eo=new Set(ce.filter(a=>Xc(a,ii)).map(a=>a.id));for(let a of We){let d=a.call,g=`Reused previous successful ${d.function.name} result for identical arguments (attempt ${a.repeatCount}); no additional tool execution was performed.
|
|
42
42
|
|
|
43
|
-
${a.result.content}`,f=G(d.id,{ok:!0,payload:g,imageUrls:a.result.imageUrls,toolReferences:a.result.toolReferences});m.push(f),H.push(d.id),O.add(d.function.name),N++,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:a.repeatCount}}}if(He.some(a=>a.call.function.name==="exec"&&Ms(a.call.function.arguments))){let a=C(y);m.push({role:"user",content:sc(c.artifactContract)}),yield{type:"tool_selection_policy",turnId:r,policyId:"browser_verification_after_preparation_required",intent:"verification",reason:"repeated-browser-preparation-command",availableToolNames:C(l??u),enabledToolNamesBefore:a,enabledToolNamesAfter:a,suppressedToolNames:[],nextAction:"run-browser-verification-script-not-playwright-install"},yield S("browser_verification_after_preparation_required","reused successful browser preparation command")}for(let a of ce){F.push({name:a.function.name,reason:"identical-repeat-policy"});let d=ot.get(`${a.function.name}::${a.function.arguments}`),g=Tt(m,a.function.name),f=Zl(g),R=So.has(a.id)?Vc(d,a):f?`This exact tool call has been attempted ${d} times. Last error: ${f}. 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.`,T=G(a.id,{ok:!1,error:R});m.push(T),H.push(a.id),O.add(a.function.name),N++,yield{type:"tool_result",turnId:r,callId:a.id,name:a.function.name,ok:!1,error:R}}if(ce.length>0&&ze.length===0&&He.length===0&&ce.every(a=>So.has(a.id))&&c.existingFileUpdateRecoveryCount<2){let a=C(y);y=_s(L,K);let d=C(y);Ue=!0,z=!0;let g=[...new Set(ce.map(f=>It(f.function.arguments)).filter(f=>!!f))];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(l??u),enabledToolNamesBefore:a,enabledToolNamesAfter:d,suppressedToolNames:oo(a,d),nextAction:"use-read-edit-or-patch-for-existing-file-update"},yield S("existing_file_update_recovery",g.join(",")||"unknown"),c={...c,messages:m,existingFileUpdateRecoveryCount:c.existingFileUpdateRecoveryCount+1,transition:{reason:"next_turn"}};continue}if(ce.length>0){let a=Tt(m,ce[0].function.name),d={role:"user",content:"Tool calls were blocked because you repeated them with identical arguments too many times. "+(a?`The error was: "${a}". Tell the user about this error. `:"The operation is not working. ")+"Stop retrying and report the result to the user."};m.push(d)}let ii=go>=3&&c.repeatedToolFailureRecoveryCount<1;if(ce.length>0&&ze.length===0&&He.length===0&&!ii){let a=Es(zn(m,1),{availableToolNames:C(l??u),enabledToolNames:Nt(),toolCallNames:[...O].sort(),blockedToolCalls:_t(F)});yield*V(a);return}let Mo=[],Gt=[];for(let a of ze){let d=Er({toolName:a.function.name,rawArguments:a.function.arguments});d?Gt.push({call:a,...d}):Mo.push(a)}for(let a of Gt){let d=a.call;F.push({name:d.function.name,reason:"read-only-context-pack"}),m.push(G(d.id,{ok:!1,error:a.error})),H.push(d.id),O.add(d.function.name),N++,yield{type:"tool_result",turnId:r,callId:d.id,name:d.function.name,ok:!1,error:a.error},o.warn(`read-only context-pack blocked: ${d.function.name} ${a.path}`)}Gt.length>0&&m.push({role:"user",content:"A write was blocked because context-pack is read-only evidence. Continue by writing compact indexes, checkpoints, and maintenance updates under benchmark-state; do not retry writes into context-pack."});let ai=new Set(y.map(a=>a.function.name)),Eo=[],rt=[];for(let a of Mo){let d=js(a.function.name,a.function.arguments,ai);d?rt.push({call:a,...d}):Eo.push(a)}for(let a of rt){let d=a.call;F.push({name:d.function.name,reason:"existing-file-update-tool-required"}),m.push(G(d.id,{ok:!1,error:a.error})),H.push(d.id),O.add(d.function.name),N++,yield{type:"tool_result",turnId:r,callId:d.id,name:d.function.name,ok:!1,error:a.error},o.info(`existing file update blocked: ${d.function.name} ${a.path}`)}if(rt.length>0){let a=C(y);y=_s(L,K);let d=C(y);Ue=!0,z=!0;let g=[...new Set(rt.map(f=>f.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(l??u),enabledToolNamesBefore:a,enabledToolNamesAfter:d,suppressedToolNames:oo(a,d),nextAction:"use-read-edit-or-patch-for-existing-file-update"},yield S("existing_file_update_recovery",g.join(",")||"unknown"),c={...c,messages:m,existingFileUpdateRecoveryCount:c.existingFileUpdateRecoveryCount+1,transition:{reason:"next_turn"}};continue}let Io=[],Wt=[];for(let a of Eo){let d=Mr({state:c.artifactContract,inputMessages:i,toolName:a.function.name,rawArguments:a.function.arguments});d?Wt.push({call:a,...d}):Io.push(a)}for(let a of Wt){let d=a.call;F.push({name:d.function.name,reason:"artifact-root-contract"}),Bn(c.artifactContract,{path:a.path,artifactRoot:a.artifactRoot,toolName:d.function.name}),m.push(G(d.id,{ok:!1,error:a.error})),H.push(d.id),O.add(d.function.name),N++,yield{type:"tool_result",turnId:r,callId:d.id,name:d.function.name,ok:!1,error:a.error},jt()&&(yield Ut()),o.warn(`artifact root contract blocked: ${d.function.name}`)}Wt.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 Po=[],Vt=[];for(let a of Io){let d=us({inputMessages:i,messages:m,toolCall:a});d?Vt.push({call:a,error:d}):Po.push(a)}for(let a of Vt){let d=a.call;F.push({name:d.function.name,reason:"premature-completion-artifact"}),m.push(G(d.id,{ok:!1,error:a.error})),H.push(d.id),O.add(d.function.name),N++,yield{type:"tool_result",turnId:r,callId:d.id,name:d.function.name,ok:!1,error:a.error},o.info(`premature completion artifact blocked: ${d.function.name}`)}Vt.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 li=new Set(y.map(a=>a.function.name)),Lo=[],st=[];for(let a of Po)li.has(a.function.name)?Lo.push(a):st.push(a);for(let a of st){let d=`Tool "${a.function.name}" was not offered for this turn and will not be executed. Use only the tools listed in the current request.`;F.push({name:a.function.name,reason:"not-offered"}),m.push(G(a.id,{ok:!1,error:d})),H.push(a.id),O.add(a.function.name),o.warn(`unoffered tool call suppressed: ${a.function.name}`)}if(st.length>0&&c.notOfferedToolRecoveryCount<1){let a=[...new Set(st.map(T=>T.function.name))].sort(),d=Ue&&a.includes("write"),g=a.filter(T=>K.has(T)),f=l??u,R=f.filter(T=>a.includes(T.function.name));if(g.length>0)c.notOfferedToolRecoveryCount+=1,z=!0,m.push({role:"user",content:`You retried ${g.map(T=>`\`${T}\``).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, use tool_search if it is enabled, 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(l??u),enabledToolNamesBefore:C(y),enabledToolNamesAfter:C(y),suppressedToolNames:g,nextAction:"continue-with-currently-enabled-tools-or-report-blocker"},yield S("policy_suppressed_tool_retry_blocked",g.join(","));else if(!d&&R.length>0){let T=C(y),v=new Map(y.map(q=>[q.function.name,q]));for(let q of R)v.set(q.function.name,q);let X=f.find(q=>q.function.name==="tool_search");X&&v.set(X.function.name,X),y=wt([...v.values()]),c.notOfferedToolRecoveryCount+=1,z=!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(l??u),enabledToolNamesBefore:T,enabledToolNamesAfter:C(y),suppressedToolNames:[],nextAction:"retry-with-reenabled-requested-tool-or-tool-search"},m.push({role:"user",content:`You called ${a.map(q=>`\`${q}\``).join(", ")} but it was not enabled for that round even though it is available. The requested available tool has now been re-enabled, with tool_search kept available for discovery. Use the re-enabled tool once with valid arguments, or use tool_search to find the right indexed tool; do not repeat a disabled-tool call.`}),yield S("available_tool_reenabled_after_not_offered_call",a.join(","))}}let Oo=[],Kt=[];for(let a of Lo){let d=y.find(f=>f.function.name===a.function.name),g=cc(d,a.function.arguments);g?Kt.push({call:a,error:g}):Oo.push(a)}for(let a of Kt){let d=a.call;F.push({name:d.function.name,reason:"invalid-arguments"}),c.toolFailureCounts,d.function.name,m.push(G(d.id,{ok:!1,error:a.error})),H.push(d.id),O.add(d.function.name),N++,yield{type:"tool_result",turnId:r,callId:d.id,name:d.function.name,ok:!1,error:a.error,details:{type:d.function.name,error:"invalid_arguments"}},o.info(`invalid tool arguments blocked: ${d.function.name}`)}Kt.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 it=[],Xt=[];for(let a of Oo){if(a.function.name!=="exec"){it.push(a);continue}let d=vs(a.function.arguments);if(!d){it.push(a);continue}let g=Ts(d);Cs(g)&&xs(L)?Xt.push({call:a,error:lc(g)}):it.push(a)}for(let a of Xt){let d=a.call;F.push({name:d.function.name,reason:"dedicated-tool-required"});let g=C(y),f=y.filter(R=>["read","search"].includes(R.function.name));f.length>0&&(y=f,Lt=!0,z=!0),m.push(G(d.id,{ok:!1,error:a.error})),H.push(d.id),O.add(d.function.name),N++,yield{type:"tool_result",turnId:r,callId:d.id,name:d.function.name,ok:!1,error:a.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(l??u),enabledToolNamesBefore:g,enabledToolNamesAfter:C(y),suppressedToolNames:g.filter(R=>!["read","search"].includes(R)),nextAction:"use-read-search-for-file-inspection-then-resume-build-run-verify-tools"}}Xt.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 Yt=[],Zt=[];for(let a of it){if(a.function.name!=="tool_search"){Yt.push(a);continue}let g=Nc(a.function.arguments).filter(f=>K.has(f));g.length>0?Zt.push({call:a,selectedNames:g}):Yt.push(a)}for(let a of Zt){let d=a.call,f=`tool_search cannot activate ${a.selectedNames.join(", ")} in this turn because the tool-selection policy has disabled it. Use the currently enabled tools instead, search for an alternative capability, or report the policy blocker.`;F.push({name:d.function.name,reason:"policy-suppressed-selection"}),m.push(G(d.id,{ok:!1,error:f})),H.push(d.id),O.add(d.function.name),N++,yield{type:"tool_result",turnId:r,callId:d.id,name:d.function.name,ok:!1,error:f,details:{type:d.function.name,error:"policy_suppressed_selection",selectedNames:a.selectedNames}},yield{type:"tool_selection_policy",turnId:r,policyId:"tool_search_policy_suppressed_selection",intent:"tool_recovery",reason:"selected-tool-disabled-by-turn-policy",availableToolNames:C(l??u),enabledToolNamesBefore:C(y),enabledToolNamesAfter:C(y),suppressedToolNames:a.selectedNames,nextAction:"search-alternative-tool-or-use-currently-enabled-tools"}}Zt.length>0&&m.push({role:"user",content:"tool_search direct selection was blocked because it targeted a policy-suppressed tool. Do not use select: for suppressed tools in this turn. Search for alternatives or continue with currently enabled tools."});let at=[],Jt=[],No=[],Fo=[];for(let a of Yt){if(a.function.name!=="exec"){at.push(a);continue}let d=a,g=vs(d.function.arguments),f=g?ec(g):null;f&&(d={...d,function:{...d.function,arguments:As(d.function.arguments,f)}},Fo.push({originalCommand:g??"",rewrittenCommand:f}),g=f);let R=g?tc(g):null;if(R?.action==="block")Jt.push({call:d,error:R.error});else if(R?.action==="rewrite"){let T={...d,function:{...d.function,arguments:As(d.function.arguments,R.command)}};No.push({call:T,originalCommand:g??"",rewrittenCommand:R.command}),at.push(T)}else at.push(d)}for(let a of Fo)yield{type:"tool_selection_policy",turnId:r,policyId:"exec_sleep_prefix_guard",intent:"verification",reason:"sleep-prefix-removed",availableToolNames:C(l??u),enabledToolNamesBefore:C(y),enabledToolNamesAfter:C(y),suppressedToolNames:[],nextAction:"execute-command-without-blocking-sleep-prefix"},o.info(`blocking sleep prefix removed before exec: ${a.originalCommand} -> ${a.rewrittenCommand}`);for(let a of No){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(l??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: ${a.originalCommand} -> ${a.rewrittenCommand}`)}for(let a of Jt){let d=a.call;F.push({name:d.function.name,reason:"reserved-frontend-port"});let g=C(y);m.push(G(d.id,{ok:!1,error:a.error})),H.push(d.id),O.add(d.function.name),N++,yield{type:"tool_result",turnId:r,callId:d.id,name:d.function.name,ok:!1,error:a.error,details:{type:d.function.name,error:"reserved_frontend_port",reservedPort:St}},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(l??u),enabledToolNamesBefore:g,enabledToolNamesAfter:C(y),suppressedToolNames:[],nextAction:"restart-generated-dev-server-on-explicit-non-5174-port-with-strict-port"}}Jt.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 lt=[],Ie=[];for(let a of at){if(a.function.name!=="read"){lt.push(a);continue}let d=ao(a.function.arguments);if(!d){lt.push(a);continue}let g=W(d),f=Fs(g);(c.fileReadCounts.get(g)??0)>=f?Ie.push({call:a,filePath:g,maxReads:f}):lt.push(a)}for(let a of Ie){let d=a.call,g=`Read cycle policy blocked another read of "${a.filePath}" after ${a.maxReads} successful reads in this turn. Stop rereading the same large document. ${ro(a.filePath)}`;F.push({name:d.function.name,reason:"read-cycle-policy"}),c.fileReadCycleBlockedPaths.add(a.filePath),m.push(G(d.id,{ok:!1,error:g})),H.push(d.id),O.add(d.function.name),N++,yield{type:"tool_result",turnId:r,callId:d.id,name:d.function.name,ok:!1,error:g},o.info(`read cycle blocked: ${a.filePath}`)}if(Ie.length>0){let a=[...new Set(Ie.map(f=>`${f.filePath} (max ${f.maxReads})`))].join(", "),d=[...new Set(Ie.map(f=>ro(f.filePath)))].join(" ");if(m.push({role:"user",content:`Further reads were blocked because these large/context documents already reached their per-turn read limit: ${a}. 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(f=>Is(f.function.name))&&(c.persistedBenchmarkStateRecovered||Ie.some(f=>po(f.filePath)))){let f=C(y),R=f.filter(T=>Ac.has(T)).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(l??u),enabledToolNamesBefore:f,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: ${R.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 S("benchmark_state_maintenance_tool_bias","retaining targeted evidence tools after long-horizon read-cycle guard")}if(Lc(F,c.fileReadCycleBlockedPaths,c.persistedBenchmarkStateRecovered,c.maintainedDocuments)){yield*V("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 Qt=ps(lt,c.toolFailureCounts),en=Qt.allowed;if(Pt&&en.length>Math.max(0,oe-N)){let a=Gn({currentToolBudget:oe,currentRoundBudget:U,toolHardCap:100,roundHardCap:100,continuationCount:$e,successfulSinceLastCheck:De-Ze,fileReadCounts:c.fileReadCounts,windowTools:ge,windowRounds:25});a&&(oe=a.nextToolBudget,U=a.nextRoundBudget,$e=a.continuationCount,Ze=De,o.info(`tool budget continuation #${a.continuationCount}: tools\u2192${oe}, rounds\u2192${U} (progress detected)`))}let Bo=Math.max(0,oe-N),pe=Bo>0?en.slice(0,Bo):[],tn=en.slice(pe.length),ci=tn.length>0;if(Qt.blocked.length>0){for(let a of Qt.blocked){let d=a.call;F.push({name:d.function.name,reason:"variant-failure-policy"});let g=G(d.id,{ok:!1,error:a.error});m.push(g),H.push(d.id),O.add(d.function.name),N++,yield{type:"tool_result",turnId:r,callId:d.id,name:d.function.name,ok:!1,error:a.error},o.info(`variant tool blocked: ${d.function.name} failed ${a.failCount}x with different args`)}m.push(ms())}if(tn.length>0){let a=`Tool call budget exhausted (${oe}) for this turn. Stop requesting more tools and report what remains incomplete.`;for(let d of tn){F.push({name:d.function.name,reason:"tool-call-budget"});let g=G(d.id,{ok:!1,error:a});m.push(g),H.push(d.id),O.add(d.function.name),N++,yield{type:"tool_result",turnId:r,callId:d.id,name:d.function.name,ok:!1,error:a}}m.push({role:"user",content:`${a} You reached this turn's tool budget after ${$e} 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 a of pe){let d=a.function.arguments,g=y.find(f=>f.function.name===a.function.name);if(g?.backfillObservableInput)try{let f=JSON.parse(a.function.arguments),R={...f};g.backfillObservableInput(R),Object.keys(R).some(v=>!(v in f))&&(d=JSON.stringify(R))}catch{}yield{type:"tool_call",turnId:r,callId:a.id,name:a.function.name,arguments:d,inputSummary:Hn(d)}}let ui=new Map(c.toolFailureCounts),ct=null;try{let a=e.runtimePorts.createStreamingToolExecutor({toolInvoker:n,hooks:k,sessionId:s,turnId:r,log:o,signal:I,maxConcurrentTools:e?.maxConcurrentTools,maxExecutionMs:Yo});for(let f of pe)a.addTool(f);let d=!1;for await(let f of a.getRemainingResults()){let R=Xl(f);if(R){if(F.push({name:f.toolName,reason:R}),f.toolName==="exec"&&R==="dedicated-tool-required"&&xs(L)){let _=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(l??u),enabledToolNamesBefore:_,enabledToolNamesAfter:C(y),suppressedToolNames:[],nextAction:"use-read-search-for-file-inspection-or-exec-for-build-run-verify"}}if(f.toolName==="exec"&&R==="confirmation-timeout"){let _=C(y);K.add("exec");let A=ye(L,K);A.length>0&&(y=wt(A),z=!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/tool_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(l??u),enabledToolNamesBefore:_,enabledToolNamesAfter:C(y),suppressedToolNames:oo(_,C(y)),nextAction:"continue-with-non-exec-tools-or-report-confirmation-blocker"}}if(f.toolName==="exec"&&R==="global-process-kill-blocked"){let _=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(l??u),enabledToolNamesBefore:_,enabledToolNamesAfter:C(y),suppressedToolNames:[],nextAction:"use-owned-task-cancel-or-new-explicit-port"}}}f.blocked&&(yield{type:"tool_blocked",turnId:r,callId:f.callId,name:f.toolName,reason:f.blockReason??"blocked"}),m.push(f.message),H.push(f.callId),O.add(f.toolName);let T=gc(f,c);T||N++;let v=f.ok&&$r(f);if(f.ok&&!v&&!T&&(De+=1),T||gs({toolFailureCounts:c.toolFailureCounts,toolName:f.toolName,toolArguments:pe.find(_=>_.id===f.callId)?.function.arguments,ok:f.ok,softEmpty:v}),f.ok&&kc.has(f.toolName)&&ou(c),f.ok&&Is(f.toolName)){let _=pe.find(B=>B.id===f.callId),A=_?It(_.function.arguments):void 0;if(A){let B=W(A);if(c.benchmarkStateMaintenanceRequiredFiles.has(B)){let se=Us(c,B,_?.function.arguments??"");se.ok?c.benchmarkStateMaintenanceWrittenFiles.add(B):(F.push({name:f.toolName,reason:"benchmark-state-invalid-content"}),m.push({role:"user",content:`Benchmark-state maintenance write for ${B} is incomplete: ${se.reason}. Rewrite or patch the file using the document evidence already provided; do not reread context-pack source documents.`}))}}}if(f.ok&&!v&&(so.has(f.toolName)||f.toolName==="exec"&&f.details?.type==="exec_background"||f.toolName==="exec"&&Ms(pe.find(_=>_.id===f.callId)?.function.arguments??""))){let _=pe.find(B=>B.id===f.callId),A=typeof f.message?.content=="string"?f.message.content:"";if(_&&A){let B=Array.isArray(f.message.imageUrls)?f.message.imageUrls.filter(me=>typeof me=="string"):void 0,se=Array.isArray(f.message.toolReferences)?f.message.toolReferences.filter(me=>typeof me=="string"):void 0;c.identicalSuccessfulToolResults.set(`${_.function.name}::${_.function.arguments}`,{content:A,imageUrls:B,toolReferences:se})}}if(f.toolName==="agent"){let _=Ae(f.details,"agentId"),A=Ae(f.details,"status"),B=At(f.details,"background");f.ok&&_&&B===!0&&A==="running"&&be(c).add(_)}if(f.toolName==="task"){let _=Cc(f.details);_&&(c.lastTaskList=_);let A=Ae(f.details,"taskId"),B=At(f.details,"running"),se=Ae(f.details,"lifecycle"),me=Ae(f.details,"action");if(A&&(me==="cancel"||B===!1||se&&se!=="running"&&se!=="pending"))be(c).delete(A),c.backgroundAgentNoOutputPollCounts.delete(A),c.stalledBackgroundAgentTasks.delete(A);else if(A&&me==="output"&&B===!0&&be(c).has(A)){let Do=typeof f.message?.content=="string"?f.message.content:"",$o=At(f.details,"hasOutput");if($o!==void 0?$o===!1:bc(Do)){let on=(c.backgroundAgentNoOutputPollCounts.get(A)??0)+1;c.backgroundAgentNoOutputPollCounts.set(A,on);let dt=dc(f.details,"elapsedSeconds")??Tc(Do);(dt!==void 0&&dt>=hc||dt===void 0&&on>=yc)&&c.stalledBackgroundAgentTasks.set(A,`no output after ${dt??"unknown"}s across ${on} poll(s)`)}else c.backgroundAgentNoOutputPollCounts.delete(A),c.stalledBackgroundAgentTasks.delete(A)}}if(f.ok&&f.toolName==="read"){let _=pe.find(A=>A.id===f.callId);if(_){let A=ao(_.function.arguments);if(A){let B=W(A),se=c.fileReadCounts.get(B)??0;c.fileReadCounts.set(B,se+1);let me=typeof f.message?.content=="string"?f.message.content:"";d=Gc(c,A,me,c.turnCount,f.details)||d}}}yield kr(r,f);for(let _ of Rr(r,f))yield _;for(let _ of xr({turnId:r,result:f,toolCalls:te}))yield _;let q=te.find(_=>_.id===f.callId),nn=typeof f.message?.content=="string"?f.message.content:"";if(q){Ir({state:c.artifactContract,inputMessages:i,toolName:f.toolName,rawArguments:q.function.arguments,ok:f.ok,content:nn}),jt()&&(yield Ut());let _=rc(f.toolName,q.function.arguments);if(_){let A=(ho.get(_)??0)+1;if(ho.set(_,A),A===oc){let B=_.startsWith("exec:")?"exec":"edit";c.recoveryTrace.set(`no_progress_observed:${B}`,(c.recoveryTrace.get(`no_progress_observed:${B}`)??0)+1)}}}!ct&&Xs&&f.toolName==="stt"&&f.ok&&(ct=Gl(i,f))}if(Ue&&(y=ye(L,K),Ue=!1),Lt&&(y=ye(L,K),Lt=!1),d){let f=jc(r,c.maintainedDocuments,c.fileReadCounts,c.turnCount);f&&(yield f);for(let v of Hc(r,c.maintainedDocuments))yield v;let R=Ec(c.maintainedDocuments,c.turnCount),T=y.some(v=>io.has(v.function.name));if(R&&T){c.benchmarkStateMaintenanceRequiredFiles=new Set($s(c.maintainedDocuments).map(W));for(let v of y)io.has(v.function.name)||K.add(v.function.name);y=ye(y,K),z=!0,m.push({role:"user",content:R}),yield S("benchmark_state_maintenance_required","forcing write/edit/patch after long-horizon document index")}}let g=be(c);if(g.size>0){let f=(l??u).find(R=>R.function.name==="task");if(f){let R=C(y),T=[...g].filter(v=>c.stalledBackgroundAgentTasks.has(v)).sort();if(T.length>0){y=[f],z=!0;let v=T.map(X=>`${X}: ${c.stalledBackgroundAgentTasks.get(X)}`).join("; ");m.push({role:"user",content:pc(T,{reason:v})}),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(l??u),enabledToolNamesBefore:R,enabledToolNamesAfter:C(y),suppressedToolNames:R.filter(X=>X!=="task"),nextAction:"cancel-stalled-background-task"},yield S("background_agent_no_output_watchdog_cancel_required",v);continue}y=[f],z=!0,m.push({role:"user",content:fc(g)}),yield{type:"tool_selection_policy",turnId:r,policyId:"background_agent_lifecycle_poll_required",intent:"lifecycle_reconciliation",reason:"background-agent-task-unresolved",availableToolNames:C(l??u),enabledToolNamesBefore:R,enabledToolNamesAfter:C(y),suppressedToolNames:R.filter(v=>v!=="task"),nextAction:"poll-existing-background-task-output"},yield S("background_agent_lifecycle_poll_required",[...g].sort().join(","));continue}}else y.length===1&&y[0]?.function.name==="task"&&(y=ye(L,K));if(ie(i)&&!c.artifactContract.browserVerified&&Mt(c.artifactContract).length>0&&y.some(f=>f.function.name==="exec")&&c.browserAcceptanceRecoveryCount<4){let f=Ss(c.artifactContract);c={...c,browserAcceptanceRecoveryCount:c.browserAcceptanceRecoveryCount+1,messages:[...m,{role:"user",content:f}],transition:{reason:"next_turn"}},z=!0,yield S("browser_acceptance_required","forcing browser automation after localhost app URL was observed");continue}if(Ic(c)){yield*V("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(a){let d=a instanceof Error?a.message:String(a);yield{type:"error",turnId:r,error:d,code:"TOOL_EXECUTION_ERROR",usage:c.totalUsage};return}if(ct){yield*V(ct);return}if(m.push(...hs({toolFailureCounts:c.toolFailureCounts,snapshot:ui})),ci){let a=we({inputMessages:i,messages:m,reason:`tool call budget exhausted (${oe}) before completing all required files`});if(a){yield*V(a);return}}Q=mt(Q,{replayMessages:m,completedToolCallIds:[...Q.completedToolCallIds,...H],lastStopReason:"tool_calls"}),e.toolChoice==="required"&&te.length>0&&(Ft=!0);let di=te.length>0&&te.every(a=>{let d=m.find(f=>f?.role==="tool"&&f?.tool_call_id===a.id);if(!d)return!0;let g=d.content;return typeof g=="string"&&g.startsWith("Error: ")}),Ce=c.consecutiveFailedRounds;if(di){if(Ce+=1,Ce>=Zo){if(go>=3&&c.repeatedToolFailureRecoveryCount<1){let f=eo({inputMessages:i,messages:m,finalText:c.finalText,thinkingBlocks:[],stopHookActive:c.stopHookActive,totalToolCallCount:N,distinctToolNames:O,log:o});if(f?.reason==="explicit_required_file_verification"||f?.reason==="explicit_extra_file_verification"){yield S("repeated_tool_failure_artifact_recovery","one recovery nudge before ending a complex explicit artifact turn after repeated tool failures"),c={...c,messages:f.messages,stopHookActive:f.stopHookActive,transition:f.transition,consecutiveFailedRounds:0,repeatedToolFailureRecoveryCount:c.repeatedToolFailureRecoveryCount+1};continue}}if(c.repeatedToolFailureRecoveryCount<1){let f=Vr(m);if(f){yield S("repeated_tool_failure_self_correction","one help-guided self-correction round before ending on repeated tool failures"),c={...c,messages:[...m,f],consecutiveFailedRounds:0,repeatedToolFailureRecoveryCount:c.repeatedToolFailureRecoveryCount+1};continue}}let a=`repeated tool failures (${Ce} rounds in a row)`,d=we({inputMessages:i,messages:m,reason:`${a} before all required files were produced`})??(c.finalText.trim()?c.finalText:zn(m,Ce)),g=Es(d,{availableToolNames:C(l??u),enabledToolNames:Nt(),toolCallNames:[...O].sort(),blockedToolCalls:_t(F)});o.info(`early exit: ${Ce} consecutive failed rounds, returning ${c.finalText?"partial":"fallback"} response`),yield*V(g);return}}else Ce=0;let ut=[...c.fileReadCycleBlockedPaths].filter(a=>!c.fileReadCycleNudgedPaths.has(a));if(ut.length>0){let a=ut.join(", "),d=[...new Set(ut.map(ro))].join(" ");o.info(`AP5: file read cycle detected on ${a}, injecting nudge`);let g={role:"user",content:`Read-cycle guard blocked repeated reads for: ${a}. ${d} Stop reading these source files this turn; summarize from maintained evidence and explain any remaining uncertainty.`};m.push(g);for(let f of ut)c.fileReadCycleNudgedPaths.add(f)}let Pe=re+1;if(x>0&&Pe>x){if(o.info(`max turns reached (${x}), completing`),k){let g=await k.invoke("stop",{sessionId:s,reason:"max_turns"});if(g.action==="abort"){let f=g.reason??"Stop hook requested continuation after max_turns",R={role:"assistant",content:c.finalText,...le.length>0&&{thinkingBlocks:[...le]}};c={...c,messages:[...m,R,{role:"user",content:f}],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}};continue}}let a=we({inputMessages:i,messages:m,reason:`tool loop max turns reached (${x}) before completing all required files`});if(a){yield*V(a);return}let d=Qe(m,`tool loop max turns reached (${x}) before completing the final status contract`);yield*V(d);return}if(Pt&&be(c).size>0&&Pe>U&&U<100&&(U=Math.min(100,Pe+25),o.info(`background task lifecycle wait extended round budget to ${U}`)),Pt&&Pe>U){let a=Gn({currentToolBudget:oe,currentRoundBudget:U,toolHardCap:100,roundHardCap:100,continuationCount:$e,successfulSinceLastCheck:De-Ze,fileReadCounts:c.fileReadCounts,windowTools:ge,windowRounds:25});a&&(U=a.nextRoundBudget,oe=a.nextToolBudget,$e=a.continuationCount,Ze=De,o.info(`round budget continuation #${a.continuationCount}: rounds\u2192${U}, tools\u2192${oe} (progress detected)`))}if(Pe>U){o.info(`tool loop budget exhausted (${U} rounds), returning`);let a=to({totalToolCallCount:N,distinctToolNames:O,projectRoot:e.projectRoot});a&&(yield{type:"skill_instruction",turnId:r,instruction:a});let d=we({inputMessages:i,messages:m,reason:`tool budget exhausted (${U} rounds) before completing all required files`});if(d){yield*V(d);return}let g=Qe(m,`tool budget exhausted (${U} rounds) before completing the final status contract`);yield*V(g);return}c={messages:m,maxOutputTokensRecoveryCount:0,hasAttemptedReactiveCompact:!1,maxOutputTokensOverride:void 0,turnCount:Pe,transition:{reason:"next_turn"},guardState:$,reactiveCompactState:J,toolLoopState:Q,consecutiveFailedRounds:Ce,finalText:c.finalText,totalUsage:c.totalUsage,collapseStore:qt,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:ot,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,backgroundAgentTaskIds:be(c),backgroundAgentNoOutputPollCounts:c.backgroundAgentNoOutputPollCounts,stalledBackgroundAgentTasks:c.stalledBackgroundAgentTasks,notOfferedToolRecoveryCount:c.notOfferedToolRecoveryCount,existingFileUpdateRecoveryCount:c.existingFileUpdateRecoveryCount,taskListReconciliationCount:c.taskListReconciliationCount,lastTaskList:c.lastTaskList}}}var ru=["\u63A5\u5355\u91D1\u989D","\u5408\u540C\u91D1\u989D","\u62A5\u4EF7","\u9884\u7B97","\u91D1\u989D","price","amount","contract amount"];function Ws(e){let t=su(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: ${Gs(o.l1Amount)}; L2 long-term says: ${Gs(o.l2Amount)}; action: ask the user which value is current before using it.`)}for(let o of e){let r=lu(o);n.push(`- [${r}] ${o.text}`)}return n.join(`
|
|
44
|
-
`)}function
|
|
45
|
-
${
|
|
43
|
+
${a.result.content}`,f=G(d.id,{ok:!0,payload:g,imageUrls:a.result.imageUrls,toolReferences:a.result.toolReferences});m.push(f),H.push(d.id),L.add(d.function.name),N++,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:a.repeatCount}}}if(We.some(a=>a.call.function.name==="exec"&&Es(a.call.function.arguments))){let a=C(h);m.push({role:"user",content:lc(c.artifactContract)}),yield{type:"tool_selection_policy",turnId:r,policyId:"browser_verification_after_preparation_required",intent:"verification",reason:"repeated-browser-preparation-command",availableToolNames:C(l??u),enabledToolNamesBefore:a,enabledToolNamesAfter:a,suppressedToolNames:[],nextAction:"run-browser-verification-script-not-playwright-install"},yield S("browser_verification_after_preparation_required","reused successful browser preparation command")}for(let a of ce){F.push({name:a.function.name,reason:"identical-repeat-policy"});let d=rt.get(`${a.function.name}::${a.function.arguments}`),g=Ct(m,a.function.name),f=ec(g),R=Eo.has(a.id)?Yc(d,a):f?`This exact tool call has been attempted ${d} times. Last error: ${f}. 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.`,T=G(a.id,{ok:!1,error:R});m.push(T),H.push(a.id),L.add(a.function.name),N++,yield{type:"tool_result",turnId:r,callId:a.id,name:a.function.name,ok:!1,error:R}}if(ce.length>0&&Ge.length===0&&We.length===0&&ce.every(a=>Eo.has(a.id))&&c.existingFileUpdateRecoveryCount<2){let a=C(h);h=vs(O,K);let d=C(h);qe=!0,z=!0;let g=[...new Set(ce.map(f=>Pt(f.function.arguments)).filter(f=>!!f))];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(l??u),enabledToolNamesBefore:a,enabledToolNamesAfter:d,suppressedToolNames:so(a,d),nextAction:"use-read-edit-or-patch-for-existing-file-update"},yield S("existing_file_update_recovery",g.join(",")||"unknown"),c={...c,messages:m,existingFileUpdateRecoveryCount:c.existingFileUpdateRecoveryCount+1,transition:{reason:"next_turn"}};continue}if(ce.length>0){let a=Ct(m,ce[0].function.name),d={role:"user",content:"Tool calls were blocked because you repeated them with identical arguments too many times. "+(a?`The error was: "${a}". Tell the user about this error. `:"The operation is not working. ")+"Stop retrying and report the result to the user."};m.push(d)}let ai=yo>=3&&c.repeatedToolFailureRecoveryCount<1;if(ce.length>0&&Ge.length===0&&We.length===0&&!ai){let a=Is(Hn(m,1),{availableToolNames:C(l??u),enabledToolNames:Ft(),toolCallNames:[...L].sort(),blockedToolCalls:vt(F)});yield*V(a);return}let Io=[],Wt=[];for(let a of Ge){let d=Pr({toolName:a.function.name,rawArguments:a.function.arguments});d?Wt.push({call:a,...d}):Io.push(a)}for(let a of Wt){let d=a.call;F.push({name:d.function.name,reason:"read-only-context-pack"}),m.push(G(d.id,{ok:!1,error:a.error})),H.push(d.id),L.add(d.function.name),N++,yield{type:"tool_result",turnId:r,callId:d.id,name:d.function.name,ok:!1,error:a.error},o.warn(`read-only context-pack blocked: ${d.function.name} ${a.path}`)}Wt.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 li=new Set(h.map(a=>a.function.name)),Po=[],st=[];for(let a of Io){let d=qs(a.function.name,a.function.arguments,li);d?st.push({call:a,...d}):Po.push(a)}for(let a of st){let d=a.call;F.push({name:d.function.name,reason:"existing-file-update-tool-required"}),m.push(G(d.id,{ok:!1,error:a.error})),H.push(d.id),L.add(d.function.name),N++,yield{type:"tool_result",turnId:r,callId:d.id,name:d.function.name,ok:!1,error:a.error},o.info(`existing file update blocked: ${d.function.name} ${a.path}`)}if(st.length>0){let a=C(h);h=vs(O,K);let d=C(h);qe=!0,z=!0;let g=[...new Set(st.map(f=>f.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(l??u),enabledToolNamesBefore:a,enabledToolNamesAfter:d,suppressedToolNames:so(a,d),nextAction:"use-read-edit-or-patch-for-existing-file-update"},yield S("existing_file_update_recovery",g.join(",")||"unknown"),c={...c,messages:m,existingFileUpdateRecoveryCount:c.existingFileUpdateRecoveryCount+1,transition:{reason:"next_turn"}};continue}let Oo=[],Vt=[];for(let a of Po){let d=Ir({state:c.artifactContract,inputMessages:i,toolName:a.function.name,rawArguments:a.function.arguments});d?Vt.push({call:a,...d}):Oo.push(a)}for(let a of Vt){let d=a.call;F.push({name:d.function.name,reason:"artifact-root-contract"}),Dn(c.artifactContract,{path:a.path,artifactRoot:a.artifactRoot,toolName:d.function.name}),m.push(G(d.id,{ok:!1,error:a.error})),H.push(d.id),L.add(d.function.name),N++,yield{type:"tool_result",turnId:r,callId:d.id,name:d.function.name,ok:!1,error:a.error},qt()&&(yield jt()),o.warn(`artifact root contract blocked: ${d.function.name}`)}Vt.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 Lo=[],Kt=[];for(let a of Oo){let d=ds({inputMessages:i,messages:m,toolCall:a});d?Kt.push({call:a,error:d}):Lo.push(a)}for(let a of Kt){let d=a.call;F.push({name:d.function.name,reason:"premature-completion-artifact"}),m.push(G(d.id,{ok:!1,error:a.error})),H.push(d.id),L.add(d.function.name),N++,yield{type:"tool_result",turnId:r,callId:d.id,name:d.function.name,ok:!1,error:a.error},o.info(`premature completion artifact blocked: ${d.function.name}`)}Kt.length>0&&m.push({role:"user",content:"A tool attempted to write a completion artifact before all explicitly requested output files had evidence. Do not write final DONE markers or success reports into artifacts until the missing files are created or verified. If you cannot complete them, respond with the requested FAIL marker and the real reason."});let ci=new Set(h.map(a=>a.function.name)),No=[],it=[];for(let a of Lo)ci.has(a.function.name)?No.push(a):it.push(a);for(let a of it){let d=`Tool "${a.function.name}" was not offered for this turn and will not be executed. Use only the tools listed in the current request.`;F.push({name:a.function.name,reason:"not-offered"}),m.push(G(a.id,{ok:!1,error:d})),H.push(a.id),L.add(a.function.name),o.warn(`unoffered tool call suppressed: ${a.function.name}`)}if(it.length>0&&c.notOfferedToolRecoveryCount<1){let a=[...new Set(it.map(T=>T.function.name))].sort(),d=qe&&a.includes("write"),g=a.filter(T=>K.has(T)),f=l??u,R=f.filter(T=>a.includes(T.function.name));if(g.length>0)c.notOfferedToolRecoveryCount+=1,z=!0,m.push({role:"user",content:`You retried ${g.map(T=>`\`${T}\``).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, use tool_search if it is enabled, 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(l??u),enabledToolNamesBefore:C(h),enabledToolNamesAfter:C(h),suppressedToolNames:g,nextAction:"continue-with-currently-enabled-tools-or-report-blocker"},yield S("policy_suppressed_tool_retry_blocked",g.join(","));else if(!d&&R.length>0){let T=C(h),v=new Map(h.map(q=>[q.function.name,q]));for(let q of R)v.set(q.function.name,q);let X=f.find(q=>q.function.name==="tool_search");X&&v.set(X.function.name,X),h=At([...v.values()]),c.notOfferedToolRecoveryCount+=1,z=!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(l??u),enabledToolNamesBefore:T,enabledToolNamesAfter:C(h),suppressedToolNames:[],nextAction:"retry-with-reenabled-requested-tool-or-tool-search"},m.push({role:"user",content:`You called ${a.map(q=>`\`${q}\``).join(", ")} but it was not enabled for that round even though it is available. The requested available tool has now been re-enabled, with tool_search kept available for discovery. Use the re-enabled tool once with valid arguments, or use tool_search to find the right indexed tool; do not repeat a disabled-tool call.`}),yield S("available_tool_reenabled_after_not_offered_call",a.join(","))}}let Fo=[],Xt=[];for(let a of No){let d=h.find(f=>f.function.name===a.function.name),g=fc(d,a.function.arguments);g?Xt.push({call:a,error:g}):Fo.push(a)}for(let a of Xt){let d=a.call;F.push({name:d.function.name,reason:"invalid-arguments"}),c.toolFailureCounts,d.function.name,m.push(G(d.id,{ok:!1,error:a.error})),H.push(d.id),L.add(d.function.name),N++,yield{type:"tool_result",turnId:r,callId:d.id,name:d.function.name,ok:!1,error:a.error,details:{type:d.function.name,error:"invalid_arguments"}},o.info(`invalid tool arguments blocked: ${d.function.name}`)}Xt.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 at=[],Yt=[];for(let a of Fo){if(a.function.name!=="exec"){at.push(a);continue}let d=ws(a.function.arguments);if(!d){at.push(a);continue}let g=Cs(d);ks(g)&&_s(O)?Yt.push({call:a,error:dc(g)}):at.push(a)}for(let a of Yt){let d=a.call;F.push({name:d.function.name,reason:"dedicated-tool-required"});let g=C(h),f=h.filter(R=>["read","search"].includes(R.function.name));f.length>0&&(h=f,Lt=!0,z=!0),m.push(G(d.id,{ok:!1,error:a.error})),H.push(d.id),L.add(d.function.name),N++,yield{type:"tool_result",turnId:r,callId:d.id,name:d.function.name,ok:!1,error:a.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(l??u),enabledToolNamesBefore:g,enabledToolNamesAfter:C(h),suppressedToolNames:g.filter(R=>!["read","search"].includes(R)),nextAction:"use-read-search-for-file-inspection-then-resume-build-run-verify-tools"}}Yt.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 Zt=[],Jt=[];for(let a of at){if(a.function.name!=="tool_search"){Zt.push(a);continue}let g=Dc(a.function.arguments).filter(f=>K.has(f));g.length>0?Jt.push({call:a,selectedNames:g}):Zt.push(a)}for(let a of Jt){let d=a.call,f=`tool_search cannot activate ${a.selectedNames.join(", ")} in this turn because the tool-selection policy has disabled it. Use the currently enabled tools instead, search for an alternative capability, or report the policy blocker.`;F.push({name:d.function.name,reason:"policy-suppressed-selection"}),m.push(G(d.id,{ok:!1,error:f})),H.push(d.id),L.add(d.function.name),N++,yield{type:"tool_result",turnId:r,callId:d.id,name:d.function.name,ok:!1,error:f,details:{type:d.function.name,error:"policy_suppressed_selection",selectedNames:a.selectedNames}},yield{type:"tool_selection_policy",turnId:r,policyId:"tool_search_policy_suppressed_selection",intent:"tool_recovery",reason:"selected-tool-disabled-by-turn-policy",availableToolNames:C(l??u),enabledToolNamesBefore:C(h),enabledToolNamesAfter:C(h),suppressedToolNames:a.selectedNames,nextAction:"search-alternative-tool-or-use-currently-enabled-tools"}}Jt.length>0&&m.push({role:"user",content:"tool_search direct selection was blocked because it targeted a policy-suppressed tool. Do not use select: for suppressed tools in this turn. Search for alternatives or continue with currently enabled tools."});let lt=[],Qt=[],Bo=[],Do=[];for(let a of Zt){if(a.function.name!=="exec"){lt.push(a);continue}let d=a,g=ws(d.function.arguments),f=g?oc(g):null;f&&(d={...d,function:{...d.function,arguments:Ss(d.function.arguments,f)}},Do.push({originalCommand:g??"",rewrittenCommand:f}),g=f);let R=g?rc(g):null;if(R?.action==="block")Qt.push({call:d,error:R.error});else if(R?.action==="rewrite"){let T={...d,function:{...d.function,arguments:Ss(d.function.arguments,R.command)}};Bo.push({call:T,originalCommand:g??"",rewrittenCommand:R.command}),lt.push(T)}else lt.push(d)}for(let a of Do)yield{type:"tool_selection_policy",turnId:r,policyId:"exec_sleep_prefix_guard",intent:"verification",reason:"sleep-prefix-removed",availableToolNames:C(l??u),enabledToolNamesBefore:C(h),enabledToolNamesAfter:C(h),suppressedToolNames:[],nextAction:"execute-command-without-blocking-sleep-prefix"},o.info(`blocking sleep prefix removed before exec: ${a.originalCommand} -> ${a.rewrittenCommand}`);for(let a of Bo){let d=C(h);yield{type:"tool_selection_policy",turnId:r,policyId:"reserved_frontend_port_guard",intent:"verification",reason:"vite-strict-port-normalized",availableToolNames:C(l??u),enabledToolNamesBefore:d,enabledToolNamesAfter:C(h),suppressedToolNames:[],nextAction:"execute-normalized-vite-dev-server-command-with-strict-port"},o.info(`vite strict port normalized before exec: ${a.originalCommand} -> ${a.rewrittenCommand}`)}for(let a of Qt){let d=a.call;F.push({name:d.function.name,reason:"reserved-frontend-port"});let g=C(h);m.push(G(d.id,{ok:!1,error:a.error})),H.push(d.id),L.add(d.function.name),N++,yield{type:"tool_result",turnId:r,callId:d.id,name:d.function.name,ok:!1,error:a.error,details:{type:d.function.name,error:"reserved_frontend_port",reservedPort:Mt}},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(l??u),enabledToolNamesBefore:g,enabledToolNamesAfter:C(h),suppressedToolNames:[],nextAction:"restart-generated-dev-server-on-explicit-non-5174-port-with-strict-port"}}Qt.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 ct=[],Ie=[];for(let a of lt){if(a.function.name!=="read"){ct.push(a);continue}let d=co(a.function.arguments);if(!d){ct.push(a);continue}let g=W(d),f=Bs(g);(c.fileReadCounts.get(g)??0)>=f?Ie.push({call:a,filePath:g,maxReads:f}):ct.push(a)}for(let a of Ie){let d=a.call,g=`Read cycle policy blocked another read of "${a.filePath}" after ${a.maxReads} successful reads in this turn. Stop rereading the same large document. ${io(a.filePath)}`;F.push({name:d.function.name,reason:"read-cycle-policy"}),c.fileReadCycleBlockedPaths.add(a.filePath),m.push(G(d.id,{ok:!1,error:g})),H.push(d.id),L.add(d.function.name),N++,yield{type:"tool_result",turnId:r,callId:d.id,name:d.function.name,ok:!1,error:g},o.info(`read cycle blocked: ${a.filePath}`)}if(Ie.length>0){let a=[...new Set(Ie.map(f=>`${f.filePath} (max ${f.maxReads})`))].join(", "),d=[...new Set(Ie.map(f=>io(f.filePath)))].join(" ");if(m.push({role:"user",content:`Further reads were blocked because these large/context documents already reached their per-turn read limit: ${a}. 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.`}),h.some(f=>Ps(f.function.name))&&(c.persistedBenchmarkStateRecovered||Ie.some(f=>go(f.filePath)))){let f=C(h),R=f.filter(T=>Ec.has(T)).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(l??u),enabledToolNamesBefore:f,enabledToolNamesAfter:C(h),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: ${R.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 S("benchmark_state_maintenance_tool_bias","retaining targeted evidence tools after long-horizon read-cycle guard")}if(Fc(F,c.fileReadCycleBlockedPaths,c.persistedBenchmarkStateRecovered,c.maintainedDocuments)){yield*V("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 en=ms(ct,c.toolFailureCounts),tn=en.allowed;if(Ot&&tn.length>Math.max(0,oe-N)){let a=Wn({currentToolBudget:oe,currentRoundBudget:U,toolHardCap:100,roundHardCap:100,continuationCount:je,successfulSinceLastCheck:Ue-Je,fileReadCounts:c.fileReadCounts,windowTools:ge,windowRounds:25});a&&(oe=a.nextToolBudget,U=a.nextRoundBudget,je=a.continuationCount,Je=Ue,o.info(`tool budget continuation #${a.continuationCount}: tools\u2192${oe}, rounds\u2192${U} (progress detected)`))}let $o=Math.max(0,oe-N),pe=$o>0?tn.slice(0,$o):[],nn=tn.slice(pe.length),ui=nn.length>0;if(en.blocked.length>0){for(let a of en.blocked){let d=a.call;F.push({name:d.function.name,reason:"variant-failure-policy"});let g=G(d.id,{ok:!1,error:a.error});m.push(g),H.push(d.id),L.add(d.function.name),N++,yield{type:"tool_result",turnId:r,callId:d.id,name:d.function.name,ok:!1,error:a.error},o.info(`variant tool blocked: ${d.function.name} failed ${a.failCount}x with different args`)}m.push(gs())}if(nn.length>0){let a=`Tool call budget exhausted (${oe}) for this turn. Stop requesting more tools and report what remains incomplete.`;for(let d of nn){F.push({name:d.function.name,reason:"tool-call-budget"});let g=G(d.id,{ok:!1,error:a});m.push(g),H.push(d.id),L.add(d.function.name),N++,yield{type:"tool_result",turnId:r,callId:d.id,name:d.function.name,ok:!1,error:a}}m.push({role:"user",content:`${a} 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 a of pe){let d=a.function.arguments,g=h.find(f=>f.function.name===a.function.name);if(g?.backfillObservableInput)try{let f=JSON.parse(a.function.arguments),R={...f};g.backfillObservableInput(R),Object.keys(R).some(v=>!(v in f))&&(d=JSON.stringify(R))}catch{}yield{type:"tool_call",turnId:r,callId:a.id,name:a.function.name,arguments:d,inputSummary:Gn(d)}}let di=new Map(c.toolFailureCounts),ut=null;try{let a=e.runtimePorts.createStreamingToolExecutor({toolInvoker:n,hooks:k,sessionId:s,turnId:r,log:o,signal:I,maxConcurrentTools:e?.maxConcurrentTools,maxExecutionMs:Jo});for(let f of pe)a.addTool(f);let d=!1;for await(let f of a.getRemainingResults()){let R=Jl(f);if(R){if(F.push({name:f.toolName,reason:R}),f.toolName==="exec"&&R==="dedicated-tool-required"&&_s(O)){let _=C(h);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(l??u),enabledToolNamesBefore:_,enabledToolNamesAfter:C(h),suppressedToolNames:[],nextAction:"use-read-search-for-file-inspection-or-exec-for-build-run-verify"}}if(f.toolName==="exec"&&R==="confirmation-timeout"){let _=C(h);K.add("exec");let A=ye(O,K);A.length>0&&(h=At(A),z=!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/tool_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(l??u),enabledToolNamesBefore:_,enabledToolNamesAfter:C(h),suppressedToolNames:so(_,C(h)),nextAction:"continue-with-non-exec-tools-or-report-confirmation-blocker"}}if(f.toolName==="exec"&&R==="global-process-kill-blocked"){let _=C(h);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(l??u),enabledToolNamesBefore:_,enabledToolNamesAfter:C(h),suppressedToolNames:[],nextAction:"use-owned-task-cancel-or-new-explicit-port"}}}f.blocked&&(yield{type:"tool_blocked",turnId:r,callId:f.callId,name:f.toolName,reason:f.blockReason??"blocked"}),m.push(f.message),H.push(f.callId),L.add(f.toolName);let T=bc(f,c);T||N++;let v=f.ok&&jr(f);if(f.ok&&!v&&!T&&(Ue+=1),T||hs({toolFailureCounts:c.toolFailureCounts,toolName:f.toolName,toolArguments:pe.find(_=>_.id===f.callId)?.function.arguments,ok:f.ok,softEmpty:v}),f.ok&&_c.has(f.toolName)&&iu(c),f.ok&&Ps(f.toolName)){let _=pe.find(B=>B.id===f.callId),A=_?Pt(_.function.arguments):void 0;if(A){let B=W(A);if(c.benchmarkStateMaintenanceRequiredFiles.has(B)){let se=js(c.maintainedDocuments,B,_?.function.arguments??"");se.ok?c.benchmarkStateMaintenanceWrittenFiles.add(B):(F.push({name:f.toolName,reason:"benchmark-state-invalid-content"}),m.push({role:"user",content:`Benchmark-state maintenance write for ${B} is incomplete: ${se.reason}. Rewrite or patch the file using the document evidence already provided; do not reread context-pack source documents.`}))}}}if(f.ok&&!v&&(ao.has(f.toolName)||f.toolName==="exec"&&f.details?.type==="exec_background"||f.toolName==="exec"&&Es(pe.find(_=>_.id===f.callId)?.function.arguments??""))){let _=pe.find(B=>B.id===f.callId),A=typeof f.message?.content=="string"?f.message.content:"";if(_&&A){let B=Array.isArray(f.message.imageUrls)?f.message.imageUrls.filter(me=>typeof me=="string"):void 0,se=Array.isArray(f.message.toolReferences)?f.message.toolReferences.filter(me=>typeof me=="string"):void 0;c.identicalSuccessfulToolResults.set(`${_.function.name}::${_.function.arguments}`,{content:A,imageUrls:B,toolReferences:se})}}if(f.toolName==="agent"){let _=Ae(f.details,"agentId"),A=Ae(f.details,"status"),B=St(f.details,"background");f.ok&&_&&B===!0&&A==="running"&&be(c).add(_)}if(f.toolName==="task"){let _=xc(f.details);_&&(c.lastTaskList=_);let A=Ae(f.details,"taskId"),B=St(f.details,"running"),se=Ae(f.details,"lifecycle"),me=Ae(f.details,"action");if(A&&(me==="cancel"||B===!1||se&&se!=="running"&&se!=="pending"))be(c).delete(A),c.backgroundAgentNoOutputPollCounts.delete(A),c.stalledBackgroundAgentTasks.delete(A);else if(A&&me==="output"&&B===!0&&be(c).has(A)){let Uo=typeof f.message?.content=="string"?f.message.content:"",jo=St(f.details,"hasOutput");if(jo!==void 0?jo===!1:kc(Uo)){let rn=(c.backgroundAgentNoOutputPollCounts.get(A)??0)+1;c.backgroundAgentNoOutputPollCounts.set(A,rn);let ft=mc(f.details,"elapsedSeconds")??Rc(Uo);(ft!==void 0&&ft>=Tc||ft===void 0&&rn>=Cc)&&c.stalledBackgroundAgentTasks.set(A,`no output after ${ft??"unknown"}s across ${rn} poll(s)`)}else c.backgroundAgentNoOutputPollCounts.delete(A),c.stalledBackgroundAgentTasks.delete(A)}}if(f.ok&&f.toolName==="read"){let _=pe.find(A=>A.id===f.callId);if(_){let A=co(_.function.arguments);if(A){let B=W(A),se=c.fileReadCounts.get(B)??0;c.fileReadCounts.set(B,se+1);let me=typeof f.message?.content=="string"?f.message.content:"";d=Kc(c,A,me,c.turnCount,f.details)||d}}}yield xr(r,f);for(let _ of _r(r,f))yield _;for(let _ of vr({turnId:r,result:f,toolCalls:ne}))yield _;let q=ne.find(_=>_.id===f.callId),on=typeof f.message?.content=="string"?f.message.content:"";if(q){Or({state:c.artifactContract,inputMessages:i,toolName:f.toolName,rawArguments:q.function.arguments,ok:f.ok,content:on}),qt()&&(yield jt());let _=ac(f.toolName,q.function.arguments);if(_){let A=(bo.get(_)??0)+1;if(bo.set(_,A),A===ic){let B=_.startsWith("exec:")?"exec":"edit";c.recoveryTrace.set(`no_progress_observed:${B}`,(c.recoveryTrace.get(`no_progress_observed:${B}`)??0)+1)}}}!ut&&Ys&&f.toolName==="stt"&&f.ok&&(ut=Kl(i,f))}if(qe&&(h=ye(O,K),qe=!1),Lt&&(h=ye(O,K),Lt=!1),d){let f=Hc(r,c.maintainedDocuments,c.fileReadCounts,c.turnCount);f&&(yield f);for(let v of Vc(r,c.maintainedDocuments))yield v;let R=Oc(c.maintainedDocuments,c.turnCount),T=h.some(v=>lo.has(v.function.name));if(R&&T){c.benchmarkStateMaintenanceRequiredFiles=new Set(Us(c.maintainedDocuments).map(W));for(let v of h)lo.has(v.function.name)||K.add(v.function.name);h=ye(h,K),z=!0,m.push({role:"user",content:R}),yield S("benchmark_state_maintenance_required","forcing write/edit/patch after long-horizon document index")}}let g=be(c);if(g.size>0){let f=(l??u).find(R=>R.function.name==="task");if(f){let R=C(h),T=[...g].filter(v=>c.stalledBackgroundAgentTasks.has(v)).sort();if(T.length>0){h=[f],z=!0;let v=T.map(X=>`${X}: ${c.stalledBackgroundAgentTasks.get(X)}`).join("; ");m.push({role:"user",content:hc(T,{reason:v})}),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(l??u),enabledToolNamesBefore:R,enabledToolNamesAfter:C(h),suppressedToolNames:R.filter(X=>X!=="task"),nextAction:"cancel-stalled-background-task"},yield S("background_agent_no_output_watchdog_cancel_required",v);continue}h=[f],z=!0,m.push({role:"user",content:gc(g)}),yield{type:"tool_selection_policy",turnId:r,policyId:"background_agent_lifecycle_poll_required",intent:"lifecycle_reconciliation",reason:"background-agent-task-unresolved",availableToolNames:C(l??u),enabledToolNamesBefore:R,enabledToolNamesAfter:C(h),suppressedToolNames:R.filter(v=>v!=="task"),nextAction:"poll-existing-background-task-output"},yield S("background_agent_lifecycle_poll_required",[...g].sort().join(","));continue}}else h.length===1&&h[0]?.function.name==="task"&&(h=ye(O,K));if(ie(i)&&!c.artifactContract.browserVerified&&Et(c.artifactContract).length>0&&h.some(f=>f.function.name==="exec")&&c.browserAcceptanceRecoveryCount<4){let f=Ms(c.artifactContract);c={...c,browserAcceptanceRecoveryCount:c.browserAcceptanceRecoveryCount+1,messages:[...m,{role:"user",content:f}],transition:{reason:"next_turn"}},z=!0,yield S("browser_acceptance_required","forcing browser automation after localhost app URL was observed");continue}if(Lc(c)){yield*V("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(a){let d=a instanceof Error?a.message:String(a);yield{type:"error",turnId:r,error:d,code:"TOOL_EXECUTION_ERROR",usage:c.totalUsage};return}if(ut){yield*V(ut);return}if(m.push(...ys({toolFailureCounts:c.toolFailureCounts,snapshot:di})),ui){let a=we({inputMessages:i,messages:m,reason:`tool call budget exhausted (${oe}) before completing all required files`});if(a){yield*V(a);return}}Q=gt(Q,{replayMessages:m,completedToolCallIds:[...Q.completedToolCallIds,...H],lastStopReason:"tool_calls"}),e.toolChoice==="required"&&ne.length>0&&(Bt=!0);let fi=ne.length>0&&ne.every(a=>{let d=m.find(f=>f?.role==="tool"&&f?.tool_call_id===a.id);if(!d)return!0;let g=d.content;return typeof g=="string"&&g.startsWith("Error: ")}),Ce=c.consecutiveFailedRounds;if(fi){if(Ce+=1,Ce>=Qo){if(yo>=3&&c.repeatedToolFailureRecoveryCount<1){let f=no({inputMessages:i,messages:m,finalText:c.finalText,thinkingBlocks:[],stopHookActive:c.stopHookActive,totalToolCallCount:N,distinctToolNames:L,log:o});if(f?.reason==="explicit_required_file_verification"||f?.reason==="explicit_extra_file_verification"){yield S("repeated_tool_failure_artifact_recovery","one recovery nudge before ending a complex explicit artifact turn after repeated tool failures"),c={...c,messages:f.messages,stopHookActive:f.stopHookActive,transition:f.transition,consecutiveFailedRounds:0,repeatedToolFailureRecoveryCount:c.repeatedToolFailureRecoveryCount+1};continue}}if(c.repeatedToolFailureRecoveryCount<1){let f=Xr(m);if(f){yield S("repeated_tool_failure_self_correction","one help-guided self-correction round before ending on repeated tool failures"),c={...c,messages:[...m,f],consecutiveFailedRounds:0,repeatedToolFailureRecoveryCount:c.repeatedToolFailureRecoveryCount+1};continue}}let a=`repeated tool failures (${Ce} rounds in a row)`,d=we({inputMessages:i,messages:m,reason:`${a} before all required files were produced`})??(c.finalText.trim()?c.finalText:Hn(m,Ce)),g=Is(d,{availableToolNames:C(l??u),enabledToolNames:Ft(),toolCallNames:[...L].sort(),blockedToolCalls:vt(F)});o.info(`early exit: ${Ce} consecutive failed rounds, returning ${c.finalText?"partial":"fallback"} response`),yield*V(g);return}}else Ce=0;let dt=[...c.fileReadCycleBlockedPaths].filter(a=>!c.fileReadCycleNudgedPaths.has(a));if(dt.length>0){let a=dt.join(", "),d=[...new Set(dt.map(io))].join(" ");o.info(`AP5: file read cycle detected on ${a}, injecting nudge`);let g={role:"user",content:`Read-cycle guard blocked repeated reads for: ${a}. ${d} Stop reading these source files this turn; summarize from maintained evidence and explain any remaining uncertainty.`};m.push(g);for(let f of dt)c.fileReadCycleNudgedPaths.add(f)}let Pe=re+1;if(x>0&&Pe>x){if(o.info(`max turns reached (${x}), completing`),k){let g=await k.invoke("stop",{sessionId:s,reason:"max_turns"});if(g.action==="abort"){let f=g.reason??"Stop hook requested continuation after max_turns",R={role:"assistant",content:c.finalText,...le.length>0&&{thinkingBlocks:[...le]}};c={...c,messages:[...m,R,{role:"user",content:f}],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}};continue}}let a=we({inputMessages:i,messages:m,reason:`tool loop max turns reached (${x}) before completing all required files`});if(a){yield*V(a);return}let d=et(m,`tool loop max turns reached (${x}) before completing the final status contract`);yield*V(d);return}if(Ot&&be(c).size>0&&Pe>U&&U<100&&(U=Math.min(100,Pe+25),o.info(`background task lifecycle wait extended round budget to ${U}`)),Ot&&Pe>U){let a=Wn({currentToolBudget:oe,currentRoundBudget:U,toolHardCap:100,roundHardCap:100,continuationCount:je,successfulSinceLastCheck:Ue-Je,fileReadCounts:c.fileReadCounts,windowTools:ge,windowRounds:25});a&&(U=a.nextRoundBudget,oe=a.nextToolBudget,je=a.continuationCount,Je=Ue,o.info(`round budget continuation #${a.continuationCount}: rounds\u2192${U}, tools\u2192${oe} (progress detected)`))}if(Pe>U){o.info(`tool loop budget exhausted (${U} rounds), returning`);let a=oo({totalToolCallCount:N,distinctToolNames:L,projectRoot:e.projectRoot});a&&(yield{type:"skill_instruction",turnId:r,instruction:a});let d=we({inputMessages:i,messages:m,reason:`tool budget exhausted (${U} rounds) before completing all required files`});if(d){yield*V(d);return}let g=et(m,`tool budget exhausted (${U} rounds) before completing the final status contract`);yield*V(g);return}c={messages:m,maxOutputTokensRecoveryCount:0,hasAttemptedReactiveCompact:!1,maxOutputTokensOverride:void 0,turnCount:Pe,transition:{reason:"next_turn"},guardState:$,reactiveCompactState:J,toolLoopState:Q,consecutiveFailedRounds:Ce,finalText:c.finalText,totalUsage:c.totalUsage,collapseStore:zt,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:rt,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,backgroundAgentTaskIds:be(c),backgroundAgentNoOutputPollCounts:c.backgroundAgentNoOutputPollCounts,stalledBackgroundAgentTasks:c.stalledBackgroundAgentTasks,notOfferedToolRecoveryCount:c.notOfferedToolRecoveryCount,existingFileUpdateRecoveryCount:c.existingFileUpdateRecoveryCount,taskListReconciliationCount:c.taskListReconciliationCount,lastTaskList:c.lastTaskList}}}var au=["\u63A5\u5355\u91D1\u989D","\u5408\u540C\u91D1\u989D","\u62A5\u4EF7","\u9884\u7B97","\u91D1\u989D","price","amount","contract amount"];function Vs(e){let t=lu(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: ${Ws(o.l1Amount)}; L2 long-term says: ${Ws(o.l2Amount)}; action: ask the user which value is current before using it.`)}for(let o of e){let r=du(o);n.push(`- [${r}] ${o.text}`)}return n.join(`
|
|
44
|
+
`)}function lu(e){let t=e.filter(r=>r.source==="l1-project-md").flatMap(r=>Gs(r.text)),n=e.filter(r=>r.source==="l2-long-term").flatMap(r=>Gs(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 fu(o)}function Gs(e){let t=[];for(let n of e.split(/\r?\n/)){let o=n.trim();if(o)for(let r of au){if(r==="\u91D1\u989D"&&/(接单金额|合同金额)/u.test(o))continue;let s=new RegExp(`${pu(r)}[^0-9.\u4E07kK,]{0,12}([0-9][0-9.,]*\\s*(?:\u4E07|k|K)?)`,"gi");for(let i of o.matchAll(s)){let l=uu(i[1]);l!==null&&t.push({entity:cu(o,r),predicate:r,amount:l,text:o})}}}return t}function cu(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 uu(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 du(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 Ws(e){return Number.isInteger(e)?String(e):String(Number(e.toFixed(4)))}function fu(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 pu(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var mu=8192;async function Ks(e){let{hooks:t,detectRecallCategories:n,log:o,sessionId:r,turnId:s,query:i}=e;try{let l=n(i),p=(await t.invoke("memory.before_recall",{sessionId:r,turnId:s,query:i,preferredCategories:l.preferred.length>0?l.preferred:void 0,deprioritizedCategories:l.deprioritized.length>0?l.deprioritized:void 0}))?.context?.recalledMemories,y=null;if(p&&p.length>0){let b=0,k=[];for(let I of p){let P=(I.text?.length??0)*2;if(b+P>mu)break;k.push(I),b+=P}k.length>0&&(y=`[Recalled memories \u2014 context priority: project-specific facts override general user preferences when they conflict]
|
|
45
|
+
${Vs(k)}`)}return D(t,"memory.after_recall",{sessionId:r,turnId:s,blockCount:p?.length??0},o),y}catch{return null}}var Xs=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:l,config:u}=t,p={sessionId:t.sessionId,turnId:o};yield{type:"start",turnId:o},D(this.hooks,"turn.submitted",{...p,prompt:r[r.length-1]?.content??void 0},this.log);let y=Rn(r),b=[];if(l&&b.push({role:"system",content:l}),b.push(...y),this.hooks){let x=y.filter(w=>w.role==="user").pop(),E=typeof x?.content=="string"?x.content.slice(0,500):void 0;if(E){let w=await Ks({hooks:this.hooks,detectRecallCategories:O=>this.runtimePorts.detectRecallCategories(O),log:this.log,sessionId:t.sessionId,turnId:o,query:E});w&&b.splice(l?1:0,0,{role:"system",content:w})}}let k=u?.model??"",I=typeof u?.maxRounds=="number"&&Number.isFinite(u.maxRounds)?u.maxRounds:this.configuredMaxRounds,P=I===void 0?void 0:Math.min(I,100);try{let x=u?.reasoning;u?.reasoning?.effort==="auto"&&(x={...u?.reasoning,effort:"medium"});let E={turnId:o,sessionId:t.sessionId,messages:b,availableTools:s,tools:i,refreshTools:t.refreshTools,model:k,apiKey:u?.apiKey??this.apiKey,temperature:u?.temperature,maxRounds:P,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:x,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},w;for await(let O of Hs(E,this.transport,this.toolInvoker,this.log))w=O,yield O;w?.type==="end"?D(this.hooks,"turn.completed",{...p},this.log):w?.type==="error"&&D(this.hooks,"turn.failed",{...p,code:w.code,error:w.error},this.log)}catch(x){if(n?.aborted)D(this.hooks,"turn.failed",{...p,code:"ABORTED",error:"Turn aborted"},this.log),yield{type:"error",turnId:o,error:"Turn aborted",code:"ABORTED"};else{let E=x instanceof Error?x.message:String(x),w=typeof x?.status=="number"?x.status:void 0,O=Oe(w,E);this.log.error(`turn ${o} error [${O}, retryable=${ln(O)}]: ${E}`),D(this.hooks,"turn.failed",{...p,code:O,error:E},this.log),yield{type:"error",turnId:o,error:E,code:O}}}}};export{Xs as Agent};
|