qlogicagent 2.16.3 → 2.16.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -11
- package/dist/agent.js +20 -21
- package/dist/cli.js +517 -382
- package/dist/index.js +516 -381
- package/dist/orchestration.js +12 -13
- package/dist/protocol.js +1 -1
- package/dist/types/agent/tool-loop/completion-action-policy.d.ts +3 -1
- package/dist/types/agent/tool-loop.d.ts +12 -1
- package/dist/types/agent/types.d.ts +2 -2
- package/dist/types/cli/acp-extended-handlers.d.ts +25 -0
- package/dist/types/cli/agent-runtime-bootstrap.d.ts +0 -2
- package/dist/types/cli/community-resource-installer.d.ts +5 -3
- package/dist/types/cli/core-tools/fork-system-prompt.d.ts +0 -2
- package/dist/types/cli/core-tools/registry.d.ts +1 -2
- package/dist/types/cli/core-tools/session-tool-manifest.d.ts +0 -2
- package/dist/types/cli/handlers/community-handler.d.ts +4 -0
- package/dist/types/cli/handlers/goal-handler.d.ts +54 -0
- package/dist/types/cli/handlers/turn-handler.d.ts +0 -1
- package/dist/types/cli/skill-invocation-service.d.ts +6 -0
- package/dist/types/cli/{skill-meta-tool-bootstrap.d.ts → skill-tools-bootstrap.d.ts} +6 -12
- package/dist/types/cli/stdio-agent-session-bootstrap.d.ts +0 -1
- package/dist/types/cli/tool-bootstrap-core-registration.d.ts +1 -9
- package/dist/types/cli/tool-bootstrap.d.ts +0 -2
- package/dist/types/contracts/turn-event.d.ts +1 -1
- package/dist/types/orchestration/agent-instance.d.ts +19 -2
- package/dist/types/orchestration/delegation-coordinator.d.ts +43 -0
- package/dist/types/orchestration/goal-acceptance.d.ts +20 -0
- package/dist/types/orchestration/goal-loop-coordinator.d.ts +87 -0
- package/dist/types/orchestration/goal-mode-adapters.d.ts +94 -0
- package/dist/types/orchestration/goal-run-persistence.d.ts +15 -0
- package/dist/types/orchestration/goal-run-types.d.ts +112 -0
- package/dist/types/orchestration/index.d.ts +1 -1
- package/dist/types/orchestration/skill-improvement.d.ts +1 -21
- package/dist/types/orchestration/subagent/agent-registry.d.ts +1 -1
- package/dist/types/orchestration/workflow/host-executors.d.ts +1 -1
- package/dist/types/orchestration/workflow/node-schema.d.ts +3 -3
- package/dist/types/orchestration/workflow/qla-executor-host.d.ts +2 -2
- package/dist/types/orchestration/workflow/workflow-scheduler.d.ts +1 -1
- package/dist/types/protocol/methods.d.ts +0 -3
- package/dist/types/protocol/wire/acp-agent-management.d.ts +33 -1
- package/dist/types/protocol/wire/acp-protocol.d.ts +17 -2
- package/dist/types/protocol/wire/agent-events.d.ts +2 -2
- package/dist/types/protocol/wire/agent-methods.d.ts +0 -2
- package/dist/types/protocol/wire/notification-payloads.d.ts +36 -20
- package/dist/types/runtime/community/community-pet-publisher.d.ts +21 -24
- package/dist/types/runtime/community/community-signal-reporter.d.ts +0 -14
- package/dist/types/runtime/config/tunable-defaults.d.ts +0 -21
- package/dist/types/runtime/hooks/community-discovery-hook.d.ts +18 -0
- package/dist/types/runtime/infra/acp-protocol-adapter.d.ts +2 -2
- package/dist/types/runtime/infra/agent-install-runner.d.ts +1 -1
- package/dist/types/runtime/infra/llmrouter-catalog.d.ts +10 -0
- package/dist/types/runtime/infra/skill-resolver.d.ts +1 -1
- package/dist/types/runtime/pet/pet-community-assets.d.ts +16 -11
- package/dist/types/runtime/pet/pet-profile-service.d.ts +2 -2
- package/dist/types/runtime/pet/petdex-asset.d.ts +28 -0
- package/dist/types/runtime/ports/tool-contracts.d.ts +1 -10
- package/dist/types/runtime/prompt/environment-context.d.ts +8 -32
- package/dist/types/runtime/tasks/task-types.d.ts +2 -32
- package/dist/types/skills/permissions/hook-runner.d.ts +0 -22
- package/dist/types/skills/plugins/plugin-api.d.ts +1 -1
- package/dist/types/skills/portable-tool.d.ts +2 -8
- package/dist/types/skills/tools/skill-tool.d.ts +57 -22
- package/dist/types/skills/tools.d.ts +5 -39
- package/dist/types/transport/acp-server.d.ts +13 -1
- package/package.json +1 -2
- package/dist/types/cli/core-tools/team-registry.d.ts +0 -62
- package/dist/types/cli/core-tools/team-tool-bootstrap.d.ts +0 -11
- package/dist/types/cli/core-tools/team-tool-service.d.ts +0 -43
- package/dist/types/cli/skill-meta-subturn-service.d.ts +0 -26
- package/dist/types/runtime/hooks/skill-recall-hooks.d.ts +0 -37
- package/dist/types/runtime/sandbox/skill-sandbox.d.ts +0 -53
- package/dist/types/runtime/sandbox/windows-skill-sandbox.d.ts +0 -78
- package/dist/types/skills/permissions/community-sandbox-policy.d.ts +0 -3
- package/dist/types/skills/permissions/community-sandbox-red-team-cli.d.ts +0 -7
- package/dist/types/skills/permissions/community-sandbox-red-team.d.ts +0 -32
- package/dist/types/skills/tools/team-tool.d.ts +0 -152
- package/dist/types/skills/tools/tool-search-tool.d.ts +0 -75
- package/dist/types/skills/tools/tool-selection-eval.d.ts +0 -49
- package/dist/types/skills/tools/tool-selection-eval.dataset.d.ts +0 -5
- package/dist/types/skills/tools/tool-selection-eval.tasks.d.ts +0 -9
package/dist/agent.js
CHANGED
|
@@ -1,45 +1,44 @@
|
|
|
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(Pn)){let r=On(o[0]);r&&(e.state.devServerUrls.includes(r)||e.state.devServerUrls.push(r))}if(ja(e.toolName,e.rawArguments,e.content)&&Br(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&&Ua(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(Ha(e.toolName,e.rawArguments))if(!e.ok||Ga(e.content)){e.state.buildVerified=!1;let r=e.content.trim().slice(0,500);r&&!e.state.buildFailureEvidence.includes(r)&&e.state.buildFailureEvidence.push(r)}else{e.state.buildVerified=!0,e.state.buildFailureEvidence=[];let r=e.content.trim().slice(0,300);r&&!e.state.buildEvidence.includes(r)&&e.state.buildEvidence.push(r)}}function Dn(e,t){return{artifactRoot:e.artifactRoot,writePaths:[...e.writePaths],outOfRootWrites:[...e.outOfRootWrites],devServerUrls:[...e.devServerUrls],browserVerified:e.browserVerified,browserEvidence:[...e.browserEvidence],browserFailureEvidence:[...e.browserFailureEvidence],requiresBrowserAcceptance:ie(t)}}function Pr(e){let t=Ea(e);for(let n of e)n.role!=="assistant"||typeof n.content!="string"||$n(t,n.content);return t}function $n(e,t){let n=t.match(/(?:^|\n)\s*-\s*artifactRoot:\s*([^\n]+)/i)?.[1]?.trim();n&&!/not declared/i.test(n)&&!e.artifactRoot&&(e.artifactRoot=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(Pn)){let l=On(i[0]);l&&!e.devServerUrls.includes(l)&&e.devServerUrls.push(l)}for(let i of t.matchAll(Pn)){let l=On(i[0]);l&&/^https?:\/\/(?:localhost|127\.0\.0\.1):\d+\//i.test(l)&&(e.devServerUrls.includes(l)||e.devServerUrls.push(l))}}function Lr(e){let t=e.content.trim(),n=ie(e.inputMessages),o=Pa(e.inputMessages),r=Nn(e.inputMessages),s=Ka(t),i=t;if(Or(e.activeTasks??[]).length>0&&(i=Na(i)),n&&!e.artifactContract.browserVerified&&(i=Fa(i)),r&&!e.artifactContract.buildVerified&&(i=Ba(i)),!(s&&e.totalToolCallCount===0)&&o&&!Sr(i)){let h=$a(i);i=i?`${i}
|
|
1
|
+
function sn(e,t,n,o){return{role:"assistant",content:t||null,tool_calls:e,...n&&n.length>0?{thinkingBlocks:n}:{},...o?{reasoning_content:o}:{}}}function V(e,t){let n=t.ok?typeof t.payload=="string"?t.payload:JSON.stringify(t.payload??""):`Error: ${t.error??"Tool execution failed"}`;return{role:"tool",tool_call_id:e,content:n,...!t.ok&&{is_error:!0},...t.toolReferences?.length?{toolReferences:t.toolReferences}:{},...t.imageUrls?.length?{imageUrls:t.imageUrls}:{}}}var di=/\b(?:daily|weekly|monthly)(?:\/(?:daily|weekly|monthly))* (?:usage )?limit(?:s)?(?: (?:exhausted|reached|exceeded))?\b/i,xe={rateLimit:[/rate[_ ]limit|too many requests|429/,"model_cooldown","exceeded your current quota","resource has been exhausted","quota exceeded","resource_exhausted","usage limit",/\btpm\b/i,"tokens per minute","tokens per day"],overloaded:[/overloaded_error|"type"\s*:\s*"overloaded_error"/i,"overloaded",/service[_ ]unavailable.*(?:overload|capacity|high[_ ]demand)|(?:overload|capacity|high[_ ]demand).*service[_ ]unavailable/i,"high demand"],timeout:["timeout","timed out","service unavailable","deadline exceeded","context deadline exceeded","connection error","network error","network request failed","fetch failed","socket hang up",/\beconn(?:refused|reset|aborted)\b/i,/\benotfound\b/i,/\beai_again\b/i,/without sending (?:any )?chunks?/i,/\bstop reason:\s*(?:abort|error|network_error)\b/i,/\breason:\s*(?:abort|error|network_error)\b/i,/\bunhandled stop reason:\s*(?:abort|error|network_error)\b/i],billing:[/["']?(?:status|code)["']?\s*[:=]\s*402\b|\bhttp\s*402\b|\berror(?:\s+code)?\s*[:=]?\s*402\b|\b(?:got|returned|received)\s+(?:a\s+)?402\b|^\s*402\s+payment/i,"payment required","insufficient credits",/insufficient[_ ]quota/i,"credit balance","plans & billing","insufficient balance"],authPermanent:[/api[_ ]?key[_ ]?(?:revoked|invalid|deactivated|deleted)/i,"invalid_api_key","key has been disabled","key has been revoked","account has been deactivated",/could not (?:authenticate|validate).*(?:api[_ ]?key|credentials)/i,"permission_error","not allowed for this organization"],auth:[/invalid[_ ]?api[_ ]?key/,"incorrect api key","invalid token","authentication","re-authenticate","oauth token refresh failed","unauthorized","forbidden","access denied","insufficient permissions","insufficient permission",/missing scopes?:/i,"expired","token has expired",/\b401\b/,/\b403\b/,"no credentials found","no api key found"],format:["string should match pattern","tool_use.id","tool_use_id","messages.1.content.1.tool_use.id","invalid request format",/tool call id was.*must be/i]},fi=/^(?:error[:\s-]+)?billing(?:\s+error)?(?:[:\s-]+|$)|^(?:error[:\s-]+)?(?:credit balance|insufficient credits?|payment required|http\s*402\b)/i,pi=/["']?(?:status|code)["']?\s*[:=]\s*402\b|\bhttp\s*402\b|\berror(?:\s+code)?\s*[:=]?\s*402\b|^\s*402\s+payment/i,mi=512,gi=/^(?:http\s*)?(\d{3})(?:\s+([\s\S]+))?$/i;var hi=new Set([500,502,503,504,521,522,523,524,529]),yi=["insufficient credits","insufficient quota","credit balance","insufficient balance","plans & billing","add more credits","top up"],bi=["upgrade your plan","upgrade plan","current plan","subscription"],Ti=["daily","weekly","monthly"],Ci=["try again","retry","temporary","cooldown"],ki=["usage limit","rate limit","organization usage"],Ri=["organization","workspace"],xi=["billing period","exceeded","reached","exhausted"],vi=/["']?(?:status|code)["']?\s*[:=]\s*402\b|\bhttp\s*402\b|\berror(?:\s+code)?\s*[:=]?\s*402\b|\b(?:got|returned|received)\s+(?:a\s+)?402\b|^\s*402\s+payment required\b/i,_i=/^(?:error[:\s-]+)?(?:(?:http\s*)?402(?:\s+payment required)?|payment required)(?:[:\s-]+|$)/i;function ve(e,t){if(!e)return!1;let n=e.toLowerCase();return t.some(o=>o instanceof RegExp?o.test(n):n.includes(o))}function wi(e){return ve(e,xe.format)}function $o(e){return ve(e,xe.rateLimit)}function Ai(e){return ve(e,xe.timeout)}function Si(e){return di.test(e)}function an(e){let t=e.toLowerCase();return t?e.length>mi?pi.test(t):ve(t,xe.billing)?!0:fi.test(e)?t.includes("upgrade")||t.includes("credits")||t.includes("payment")||t.includes("plan"):!1:!1}function Uo(e){return ve(e,xe.authPermanent)}function Mi(e){return ve(e,xe.auth)}function jo(e){return ve(e,xe.overloaded)}function Re(e,t){return t.some(n=>e.includes(n))}function Ei(e){return Re(e,yi)||Re(e,bi)&&e.includes("limit")||e.includes("billing hard limit")||e.includes("hard limit reached")||e.includes("maximum allowed")&&e.includes("limit")}function Ii(e){let t=Re(e,Ti),n=e.includes("spend limit")||e.includes("spending limit"),o=Re(e,Ri);return Re(e,Ci)&&Re(e,ki)||t&&(e.includes("usage limit")||n)||t&&e.includes("limit")&&e.includes("reset")||o&&e.includes("limit")&&(n||Re(e,xi))}function Pi(e){return e.trim().toLowerCase().replace(_i,"").trim()}function qo(e){let t=Pi(e);return!t||Ei(t)?"billing":$o(t)||Ii(t)?"rate_limit":"billing"}function Oi(e){return vi.test(e)?qo(e):null}function zo(e){let t=e.match(gi);if(!t)return null;let n=Number(t[1]);return Number.isFinite(n)?{code:n,rest:(t[2]??"").trim()}:null}function Li(e){if(!e)return!1;let t=e.toLowerCase();return t.includes('"type":"api_error"')&&t.includes("internal server error")}function Ni(e){let t=e.trim();if(!t)return!1;let n=zo(t);return n?hi.has(n.code):!1}function Ho(e,t){return typeof e!="number"||!Number.isFinite(e)?null:e===402?t?qo(t):"billing":e===429?"rate_limit":e===401||e===403?t&&Uo(t)?"auth_permanent":"auth":e===408?"timeout":e===503?t&&jo(t)?"overloaded":"timeout":e===502||e===504?"timeout":e===529?"overloaded":e===400?t&&an(t)?"billing":"format":null}function Fi(e){if(!e)return!1;let t=e.toLowerCase();return!!(t.includes("unknown model")||t.includes("model not found")||t.includes("model_not_found")||t.includes("not_found_error")||t.includes("does not exist")&&t.includes("model")||t.includes("invalid model")&&!t.includes("invalid model reference")||/models\/[^\s]+ is not found/i.test(e)||/\b404\b/.test(e)&&/not[-_ ]?found/i.test(e))}function Bi(e){if(!e)return!1;let t=e.toLowerCase();return t.includes("session not found")||t.includes("session does not exist")||t.includes("session expired")||t.includes("session invalid")||t.includes("conversation not found")||t.includes("conversation does not exist")||t.includes("conversation expired")||t.includes("conversation invalid")||t.includes("no such session")||t.includes("invalid session")||t.includes("session id not found")||t.includes("conversation id not found")}function Go(e){if(Bi(e))return"session_expired";if(Fi(e))return"model_not_found";let t=Oi(e);return t||(Si(e)?an(e)?"billing":"rate_limit":$o(e)?"rate_limit":jo(e)?"overloaded":Ni(e)?zo(e.trim())?.code===529?"overloaded":"timeout":Li(e)?"timeout":wi(e)?"format":an(e)?"billing":Ai(e)?"timeout":Uo(e)?"auth_permanent":Mi(e)?"auth":null)}var Di={timeout:"RETRYABLE_TRANSIENT",overloaded:"RETRYABLE_TRANSIENT",rate_limit:"RETRYABLE_DEGRADED",auth:"NON_RETRYABLE_AUTH",auth_permanent:"NON_RETRYABLE_AUTH",billing:"NON_RETRYABLE_QUOTA",format:"NON_RETRYABLE_CONTENT",model_not_found:"NON_RETRYABLE_CONTENT",session_expired:"NON_RETRYABLE_CONTENT",unknown:"RETRYABLE_TRANSIENT"},$i=new Set(["RETRYABLE_TRANSIENT","RETRYABLE_DEGRADED","TOOL_EXECUTION_FAILED"]);function Fe(e,t){let n=Ho(e,t)??(t?Go(t):null);return n?Di[n]:typeof e=="number"&&e>=400&&e<500?"NON_RETRYABLE_CONTENT":"RETRYABLE_TRANSIENT"}function ln(e){return $i.has(e)}function Wo(e){let t=typeof e.content=="string"?e.content:e.content!=null?JSON.stringify(e.content):"";return Math.ceil(t.length/4)}var Ui=new Set(["file_read","read","Read","bash","shell","Bash","grep","search","Grep","grep_search","glob","Glob","file_search","web_search","WebSearch","web_fetch","WebFetch","file_edit","edit","Edit","file_write","write","Write"]),Xe=class{constructor(t=20,n=Wo){this.preserveRecentCount=t;this.estimateTokens=n}preserveRecentCount;estimateTokens;compress(t,n){if(t.length<=this.preserveRecentCount)return{messages:t,droppedCount:0,strategy:"micro-compact"};let o=t.length-this.preserveRecentCount,r=0,s=0;return{messages:t.map((a,u)=>{if(u>=o||a.role!=="tool"||typeof a.content!="string"||!a.name||!Ui.has(a.name)||a.content.length<=200)return a;let f=this.estimateTokens(a);return s+=f,r++,{...a,content:`[result cleared \u2014 ${a.content.length} chars]`}}),droppedCount:r,strategy:"micro-compact",metrics:r>0?{tokensBefore:0,tokensAfter:0,compressionRatio:0,latencyMs:0,usedLlm:!1,cacheInvalidated:!1}:void 0}}};function cn(e,t,n=Wo){if(t.size===0)return{messages:e,tokensFreed:0,removedCount:0};let o=0,r=0,s=[];for(let a of e){let u=a.tool_call_id??"";if(u&&t.has(u)){o+=n(a),r++,t.delete(u);continue}s.push(a)}let i=r>0?{role:"system",content:`[${r} messages removed by snip]`}:void 0;return{messages:s,tokensFreed:o,removedCount:r,boundaryMessage:i}}function un(){return{stages:[]}}function dn(e,t,n){let o=n?.thresholdMessages??40;if(e.filter(a=>a.role!=="system").length<=o)return{messages:e,stagedCount:0};let s=Vo(e,t),i=ji(s,t,o);if(i.length===0)return{messages:s,stagedCount:0};for(let a of i)t.stages.push(a);return s=Vo(e,t),{messages:s,stagedCount:i.length}}function fn(e,t){let n=0;for(let o of t.stages)o.committed||(o.committed=!0,n++);return n===0?{messages:e,committed:0}:{messages:Xo(e,t),committed:n}}function Vo(e,t){return t.stages.filter(o=>o.committed).length===0?e:Xo(e,t)}function Xo(e,t){let n=t.stages.filter(r=>r.committed).sort((r,s)=>s.range[0]-r.range[0]),o=[...e];for(let r of n){let[s,i]=r.range;if(s>=o.length)continue;let a=Math.min(i,o.length),u={role:"system",content:r.summary};o.splice(s,a-s,u)}return o}function ji(e,t,n){let o=Math.max(0,e.length-Math.floor(n/2)),r=[],s=new Set(t.stages.map(u=>`${u.range[0]}-${u.range[1]}`)),i=-1,a=0;for(let u=0;u<o;u++){let f=e[u];if(f.role==="tool"||f.role==="assistant"&&typeof f.content=="string"&&f.content==="")i<0&&(i=u),a++;else{if(a>=3){let T=`${i}-${i+a}`;s.has(T)||r.push({id:`collapse_${i}_${i+a}`,range:[i,i+a],summary:`[${a} tool results collapsed]`,committed:!1})}i=-1,a=0}}if(a>=3){let u=`${i}-${i+a}`;s.has(u)||r.push({id:`collapse_${i}_${i+a}`,range:[i,i+a],summary:`[${a} tool results collapsed]`,committed:!1})}return r}import{readFileSync as qi,writeFileSync as zi,mkdirSync as Hi}from"node:fs";import{join as Gi,dirname as Wi}from"node:path";var ge=Math.min(Math.max(1,Number(process.env.TOOL_LOOP_DEFAULT_BUDGET)||25),100),Ko=Math.max(1e3,Number(process.env.TOOL_LOOP_TOOL_TIMEOUT_MS)||24e4),Yo=3,Zo=2,gt=2,Jo=128e3,Qo=13e3,er=16384,tr=65536,nr=3,or=65536,pn=500,rr=3;var sr=3e4,ir=3,_e=2;var ar=3,lr=2,cr=300*1e3,ur=3,dr=720*60*60*1e3;var vu=3600*1e3;var _u=50*1024,wu=500*1024,Au=500*1024*1024,Su=50*1024*1024;var Mu=60*1024;var pr=0;var Vi="skill-patterns.json";function mr(e){return Gi(e,".qlogicagent",Vi)}function Xi(e){let t=mr(e);try{return JSON.parse(qi(t,"utf8"))}catch{return{version:1,patterns:{}}}}function fr(e,t){let n=mr(e);Hi(Wi(n),{recursive:!0}),zi(n,JSON.stringify(t,null,2),"utf8")}function Ki(e){let t=Date.now()-dr;for(let[n,o]of Object.entries(e.patterns))new Date(o.lastSeen).getTime()<t&&delete e.patterns[n]}function gr(e,t){if(t.length===0)return!1;let n=hr(t),o=Xi(e);Ki(o);let r=new Date().toISOString(),s=o.patterns[n];if(s||(s={signature:n,count:0,firstSeen:r,lastSeen:r,promoted:!1},o.patterns[n]=s),s.promoted)return fr(e,o),!1;s.count++,s.lastSeen=r;let i=s.count>=ur;return i&&(s.promoted=!0),fr(e,o),i}function hr(e){return[...e].sort().join("+")}function Yi(e,t){return!(!e.ok||e.existingSkillName||!e.multiStep||e.toolCallCount<ar||e.distinctToolCount<lr||Date.now()-pr<cr||t?.projectRoot&&t.tools.length>0&&!gr(t.projectRoot,t.tools))}function Zi(e){return e.existingSkillName?e.feedback==="negative":!1}function mn(e,t){return Zi(e)?{type:"skill.improve",skillName:e.existingSkillName,reason:"negative user feedback on existing skill execution"}:Yi(e,t)?(pr=Date.now(),{type:"skill.create",suggestedName:t.suggestedName??`auto-skill-${t.tools.slice(0,3).join("-")}`,description:`Multi-step orchestration using ${t.tools.join(", ")}`,tools:t.tools,stepCount:e.toolCallCount}):null}function Ji(e){let t=new Set(e.map(gn).filter(Boolean)),n=t.has("exec"),o=["read","search","write","edit","patch"].some(r=>t.has(r));return!n||!o?"You must call one of the available tools before responding.":'You must call one of the available tools before responding. Tool selection is part of correctness. Use read/search/write/edit/patch for file paths and file maintenance. For search, always include `mode` and `pattern`; examples: {"mode":"filename","pattern":"**/*.md"} or {"mode":"content","pattern":"TODO","fileGlob":"*.ts"}. Use exec only for shell commands with the required `command` field; never pass `path`, `filePath`, or file content to exec.'}function gn(e){return e.function&&typeof e.function=="object"&&typeof e.function.name=="string"?e.function.name.trim():typeof e.name=="string"?e.name.trim():""}function Qi(e){return e==="enabled-eligible"||e==="installed-awaiting-approval"}function ea(e){return new Map((e??[]).map(t=>[t.toolName,t]))}function ta(e){if(!e.eligibility?.length)return[...e.tools];let t=ea(e.eligibility);return e.tools.filter(n=>{let o=gn(n);if(!o)return!1;let r=t.get(o);return!r||Qi(r.status)})}function na(e){let t=[],n=e.compatibility??{},o=e.toolChoice;if(e.thinkingEnabled&&n.requireAutoWhenThinking){let r=typeof o=="object"&&o&&!Array.isArray(o)?String(o.type??""):o;r&&r!=="auto"&&r!=="none"&&(t.push("tool_choice downgraded to auto because thinking mode requires auto/none compatibility."),o="auto")}if(o==="required"&&n.allowRequiredToolChoice===!1){let r=n.requiredFallback??"auto";t.push(`tool_choice=required is not supported by this provider; downgraded to ${r}.`),o=r}if(o&&typeof o=="object"&&!Array.isArray(o)&&o.type==="function"&&n.allowNamedToolChoice===!1){let r=n.namedFallback??"required";t.push(`named tool_choice is not supported by this provider; downgraded to ${r}.`),o=r}return{normalizedToolChoice:o,warnings:t}}function hn(e){let t=na({toolChoice:e.toolChoice,thinkingEnabled:e.thinkingEnabled,compatibility:e.compatibility}),n=t.normalizedToolChoice,o=[...t.warnings],r=ta({tools:e.tools,eligibility:e.eligibility});if(!n||n==="auto")return{tools:r,normalizedToolChoice:n,warnings:o};if(n==="none")return{tools:[],normalizedToolChoice:"none",warnings:o};if(n==="required"){if(r.length===0)throw new Error("tool_choice=required but no tools were provided");return{tools:r,normalizedToolChoice:"required",extraSystemPrompt:Ji(r),warnings:o}}if(typeof n=="object"&&!Array.isArray(n)&&n.type==="function"){let s=n.function??void 0,i=typeof s?.name=="string"?s.name.trim():"";if(!i)throw new Error("tool_choice.function.name is required");let a=r.filter(u=>gn(u)===i);if(a.length===0)throw new Error(`tool_choice requested unknown tool: ${i}`);return{tools:a,normalizedToolChoice:{type:"function",function:{name:i}},extraSystemPrompt:`You must call the ${i} tool before responding.`,warnings:o}}return{tools:r,normalizedToolChoice:n,warnings:o}}var oa=["stop","aborted","timeout","cancelled","interrupted","error"],ra=["tool_calls","toolCalls","function_call","functionCall","raw_tool_calls","rawToolCalls"];function yr(e){return e==null?[]:typeof e=="string"?e.length>0?[{type:"text",text:e}]:[]:Array.isArray(e)?e:[{type:"text",text:String(e)}]}function sa(e,t){return{...e,content:[...yr(e.content),...yr(t.content)]}}function ia(e){let t=new Set;if(e.role!=="assistant"||!Array.isArray(e.tool_calls))return t;for(let n of e.tool_calls)typeof n.id=="string"&&n.id&&t.add(n.id);return t}function aa(e){let t=new Set,n=[];for(let o=0;o<e.length;o+=1){if(t.has(o))continue;let r=e[o];if(!r)continue;n.push(r);let s=ia(r);if(s.size!==0)for(let i=o+1;i<e.length;i+=1){if(t.has(i))continue;let a=e[i];a?.role==="tool"&&typeof a.tool_call_id=="string"&&s.has(a.tool_call_id)&&(n.push(a),t.add(i))}}return n}function la(e){if(!e||typeof e!="object")return!1;if(e.function&&typeof e.function=="object"){let t=e.function.name;if(typeof t=="string"&&t.length>0)return!0}return typeof e.name=="string"&&e.name.length>0}function ca(e){return new Set((e??oa).map(t=>t.trim().toLowerCase()))}function ua(e,t){return e?ca(t).has(e.trim().toLowerCase()):!1}function yn(e){if(!Array.isArray(e)||e.length===0)return[...e];let t=e.map(u=>{if(u.role==="assistant"&&Array.isArray(u.tool_calls)){let f=u.tool_calls.filter(h=>la(h));return{...u,...f.length>0?{tool_calls:f}:{tool_calls:void 0}}}return{...u}}),n=new Set;for(let u of t)if(!(u.role!=="assistant"||!Array.isArray(u.tool_calls)))for(let f of u.tool_calls)typeof f.id=="string"&&f.id&&n.add(f.id);let o=t.filter(u=>u.role!=="tool"?!0:!!(u.tool_call_id&&n.has(u.tool_call_id))),r=new Set;for(let u of o)u.role==="tool"&&typeof u.tool_call_id=="string"&&u.tool_call_id&&r.add(u.tool_call_id);let s=[];for(let u of o){if(u.role==="assistant"&&Array.isArray(u.tool_calls)&&u.tool_calls.length>0){let f=u.tool_calls.filter(h=>typeof h.id=="string"&&r.has(h.id));if(f.length===0){let{tool_calls:h,...T}=u;T.content!=null&&T.content!==""&&s.push(T);continue}if(f.length<u.tool_calls.length){s.push({...u,tool_calls:f});continue}}s.push(u)}let i=aa(s),a=[];for(let u of i){let f=a.length>0?a[a.length-1]:void 0;if(u.role==="user"&&f?.role==="user"){a[a.length-1]=sa(f,u);continue}a.push(u)}return a}function bn(e,t){return ua(t?.stopReason,t?.forcedStopReasons)?e.map(n=>{if(n.role!=="assistant")return{...n};let o={...n};for(let r of ra)delete o[r];return o}):[...e]}function Tn(e,t){let n=t?.placeholderToolResult??"Error: Tool loop interrupted before the tool result was replayed.",o=new Set;for(let s of e)s.role==="tool"&&typeof s.tool_call_id=="string"&&s.tool_call_id&&o.add(s.tool_call_id);let r=[];for(let s of e)if(r.push({...s}),!(s.role!=="assistant"||!Array.isArray(s.tool_calls)||s.tool_calls.length===0))for(let i of s.tool_calls)typeof i.id!="string"||!i.id||o.has(i.id)||(o.add(i.id),r.push({role:"tool",tool_call_id:i.id,content:n}));return r}function Cn(e,t){let n=yn(e),o=bn(n,t);return Tn(o,t)}function da(e){let t=new Set,n=new Set;for(let o of e){if(o.role==="assistant"&&Array.isArray(o.tool_calls))for(let r of o.tool_calls)typeof r.id=="string"&&r.id&&t.add(r.id);o.role==="tool"&&typeof o.tool_call_id=="string"&&o.tool_call_id&&n.add(o.tool_call_id)}return[...t].filter(o=>!n.has(o))}function fa(e){let t=new Set;for(let n of e)n.role==="tool"&&typeof n.tool_call_id=="string"&&n.tool_call_id&&t.add(n.tool_call_id);return[...t]}function pa(e){return{round:e.round??0,maxRounds:e.maxRounds,pendingToolCallIds:[...e.pendingToolCallIds??[]],completedToolCallIds:[...e.completedToolCallIds??[]],lastStopReason:e.lastStopReason,replayMessages:[...e.replayMessages??[]]}}function kn(e,t){return{round:e.round+1,maxRounds:e.maxRounds,pendingToolCallIds:[...t.pendingToolCallIds??e.pendingToolCallIds],completedToolCallIds:[...t.completedToolCallIds??e.completedToolCallIds],lastStopReason:t.lastStopReason??e.lastStopReason,replayMessages:[...t.replayMessages??e.replayMessages]}}function ht(e,t){return{round:e.round,maxRounds:e.maxRounds,pendingToolCallIds:[],completedToolCallIds:[...t.completedToolCallIds??e.completedToolCallIds],lastStopReason:t.lastStopReason??e.lastStopReason,replayMessages:[...t.replayMessages??e.replayMessages]}}function yt(e){let t=[],n=yn(e.replayMessages);n.length!==e.replayMessages.length&&t.push({kind:"drop-orphan-tool-result",detail:"Removed orphan tool results or invalid assistant tool calls."});let o=bn(n,e.options);o.some((s,i)=>s!==n[i])&&t.push({kind:"strip-forced-stop-tool-metadata",detail:"Removed assistant tool-call metadata after forced stop."});let r=Tn(o,e.options);return r.length>o.length&&t.push({kind:"inject-placeholder-tool-result",detail:"Injected placeholder tool result for pending tool calls."}),{state:pa({maxRounds:e.maxRounds,round:e.round,lastStopReason:e.lastStopReason,replayMessages:r,pendingToolCallIds:da(r),completedToolCallIds:fa(r)}),recoveryActions:t}}var ma=new Set(["main","sdk","agent","compact","hook","verification","side_question"]);function Rn(e){return e?ma.has(e):!0}function xn(e){return e===429||e===529}function bt(e,t=500,n=32e3){let o=Math.min(t*Math.pow(2,e-1),n);return o+Math.floor(Math.random()*o*.25)}var qu={maxBackoffMs:300*1e3,resetCapMs:360*60*1e3,heartbeatIntervalMs:3e4};function Tt(){let e=process.env.QLOGICAGENT_PERSISTENT_RETRY;return e==="1"||e==="true"}var Ke=class extends Error{constructor(n,o){super(`Model fallback triggered: ${n} -> ${o}`);this.originalModel=n;this.fallbackModel=o;this.name="FallbackTriggeredError"}originalModel;fallbackModel};function vn(e){return{promptTokens:0,hasAttemptedReactiveCompact:!1,currentMaxOutputTokens:e.maxOutputTokens,consecutiveTruncations:0,aborted:e.abortSignal?.aborted??!1}}function _n(e,t){if(e.aborted)return{level:"blocking",usagePercent:100,reason:"budget_exhausted"};let n=t.contextWindowTokens-t.responseBufferTokens-e.currentMaxOutputTokens,o=n>0?e.promptTokens/n*100:100;return e.promptTokens>=n?e.hasAttemptedReactiveCompact||!t.reactiveCompactEnabled?{level:"blocking",usagePercent:o,reason:"prompt_too_long"}:{level:"blocking",usagePercent:o,reason:"prompt_too_long"}:o>=85?{level:"warning",usagePercent:o,remainingTokens:n-e.promptTokens}:{level:"ok"}}function wn(e,t,n){let o=e.message?.toLowerCase()??"",r=e.status??0;return r===413||o.includes("prompt_too_long")||o.includes("context_length_exceeded")?!t.hasAttemptedReactiveCompact&&n.reactiveCompactEnabled?{action:"reactive_compact"}:{action:"abort",reason:"prompt_too_long_unrecoverable"}:r>=500&&r<600?{action:"retry",reason:`server_error_${r}`}:r===429?{action:"retry",reason:"rate_limited"}:r===401||r===403?{action:"abort",reason:"auth_error"}:r===404?{action:"abort",reason:"model_not_found"}:{action:"abort",reason:o||"unknown_error"}}function An(e,t,n){if(!t.outputEscalationEnabled)return{shouldEscalate:!1,newMax:e.currentMaxOutputTokens};if(e.consecutiveTruncations>=3)return{shouldEscalate:!1,newMax:e.currentMaxOutputTokens};let o=Math.min(e.currentMaxOutputTokens*2,n);return o<=e.currentMaxOutputTokens?{shouldEscalate:!1,newMax:e.currentMaxOutputTokens}:{shouldEscalate:!0,newMax:o}}function Sn(e,t){return e.aborted?!0:t.abortSignal?.aborted?(e.aborted=!0,!0):!1}var ha={maxConsecutiveFailures:3,minMessagesAfterCompact:4,targetUsagePercent:50};function Mn(){return{consecutiveFailures:0,attemptedThisTurn:!1,lastCompactAt:null,toolsAtLastCompact:[]}}function Be(e,t=ha){return!(e.attemptedThisTurn||e.consecutiveFailures>=t.maxConsecutiveFailures)}import{createHash as Vl}from"node:crypto";import{existsSync as Ie,readFileSync as Nt}from"node:fs";function En(e,t){let n=e.get(t.index)??{id:"",name:"",arguments:""};t.id&&(n.id=t.id),t.name&&(n.name=t.name),n.arguments+=t.arguments??"",e.set(t.index,n)}function $(e,t,n,o){e?.invoke(t,n).catch(r=>{let s=r instanceof Error?r.message:String(r);o.warn(`[hook:${t}] handler failed: ${s}`)})}function br(e,t){let n=typeof t.message?.content=="string"?t.message.content:"",o=n?n.slice(0,2e3):void 0,r=t.details,s=typeof r?.stdout=="string"?r.stdout.slice(0,8e3):void 0,i=typeof r?.stderr=="string"?r.stderr.slice(0,4e3):void 0,a=typeof r?.exitCode=="number"?r.exitCode:void 0;return{type:"tool_result",turnId:e,callId:t.callId,name:t.toolName,ok:t.ok,error:t.error,outputPreview:o,durationMs:t.durationMs,exitCode:a,stdout:s,stderr:i,details:r}}function Tr(e,t){if(!t.ok)return[];let n=t.details;if(!n)return[];let o=ya(n);return o?(Array.isArray(n.mediaUrls)?n.mediaUrls.filter(s=>typeof s=="string"&&s.trim().length>0):[]).map(s=>({type:"media_result",turnId:e,mediaType:o,url:s,model:typeof n.model=="string"?n.model:void 0,provider:typeof n.provider=="string"?n.provider:void 0,durationSeconds:typeof n.durationMs=="number"?n.durationMs/1e3:void 0,taskId:typeof n.taskId=="string"?n.taskId:void 0})):[]}function ya(e){let t=typeof e.type=="string"?e.type:"";if(!t)return null;if(t==="three_d_generate")return"3d";let n=t.split("_")[0];return n==="image"||n==="tts"||n==="video"||n==="music"?n:null}var ba=new Set(["write","edit","patch"]);function Cr(e){let{turnId:t,result:n,toolCalls:o}=e;if(!n.ok)return[];let r=o.find(a=>a.id===n.callId);if(!r)return[];let s=[],i=Ta(r.function.arguments);if(!i)return s;if(ba.has(n.toolName)){let a=Ca(i);a&&s.push({type:"artifact",turnId:t,artifactId:`artifact-${n.callId}`,artifactType:ka(a),title:a.split(/[\\/]/).pop()||a,filePath:a,language:Ra(a)})}return s}function Ta(e){try{return JSON.parse(e)}catch{return null}}function Ca(e){return typeof e.file_path=="string"?e.file_path:typeof e.filePath=="string"?e.filePath:typeof e.path=="string"?e.path:void 0}function ka(e){let t=e.split(".").pop()?.toLowerCase()??"";return["png","jpg","jpeg","gif","webp","svg","bmp","ico"].includes(t)?"image":["md","txt","pdf","doc","docx","rtf","html"].includes(t)?"document":["mermaid","mmd","dot","puml","plantuml"].includes(t)?"diagram":["csv","tsv","xlsx","xls"].includes(t)?"table":["ts","tsx","js","jsx","py","rs","go","java","c","cpp","h","cs","rb","sh","sql","json","yaml","yml","toml","xml","css","scss","vue","svelte"].includes(t)?"code":"file"}function Ra(e){let t=e.split(".").pop()?.toLowerCase()??"";return{ts:"typescript",tsx:"typescriptreact",js:"javascript",jsx:"javascriptreact",py:"python",rs:"rust",go:"go",java:"java",c:"c",cpp:"cpp",h:"c",cs:"csharp",rb:"ruby",sh:"shellscript",sql:"sql",json:"json",yaml:"yaml",yml:"yaml",toml:"toml",xml:"xml",html:"html",css:"css",scss:"scss",vue:"vue",svelte:"svelte",md:"markdown"}[t]}var xa=new Set(["write","edit","patch"]),va=new Set(["image_generate"]),_a=/\b(?:build|create|make|develop|implement|scaffold|generate)\b[\s\S]{0,80}\b(?:app|application|web ?app|website|site|dashboard|frontend|react|vite|vue|next|svelte|game)\b|\b(?:vite|react|vue|next\.js|frontend|browser-visible)\b|(?:构建|创建|开发|实现|生成|搭建)[\s\S]{0,24}(?:应用|网站|网页|前端|页面|项目|游戏|看板|仪表盘|app)/i;var wa=/\b(?:under|inside|in|at|to|root|directory|folder|output directory|output folder)\s+([A-Za-z]:[\\/][^\s"'`<>|]+)|(?:目录|文件夹|根目录|输出到|放到|位于)\s*([A-Za-z]:[\\/][^\s"'`<>|]+)/gi,In=/https?:\/\/[^\s"'`<>),;]+/gi,Aa=/\b(?:fatal|timeout|timed out|waitforselector|waiting for locator|strict mode violation|exception|traceback|eaddrinuse|page crashed|browser closed|target closed)\b|鏃犳硶灏唡閿欒|澶辫触|瓒呮椂/i,Sa=/\b(?:default vite|vite \+ react|edit src\/app|click on the vite|vite page)\b|默认\s*Vite/i,kr=/\b(?:browser|playwright|puppeteer|screenshot|opened|loaded|navigated|visible|locator|page\.goto|http:\/\/127\.0\.0\.1|http:\/\/localhost)\b|(?:浏览器|截图|页面可见|打开页面|加载页面|内置浏览器|自动化)/i;function Ma(e){let t=$n(e);return{artifactRoot:t,rootSource:t?"explicit":void 0,writePaths:[],outOfRootWrites:[],devServerUrls:[],browserVerified:!1,browserEvidence:[],browserFailureEvidence:[],buildVerified:!1,buildEvidence:[],buildFailureEvidence:[]}}function se(e){return e.some(t=>t.role==="user"&&typeof t.content=="string"&&_a.test(t.content))}var Ea=new RegExp(["\\b(?:tests?|test suite|unit tests?|the suite|build|compiles?|compilation|typecheck|lint)\\b[\\s\\S]{0,24}\\b(?:pass(?:es|ing)?|green|succeed(?:s|ed)?|clean|work(?:s|ing)?)\\b","\\b(?:pass(?:es|ing)?|green|succeed(?:s|ed)?)\\b[\\s\\S]{0,16}\\b(?:tests?|the suite|build)\\b","\\bfix(?:es|ing)?\\b[\\s\\S]{0,24}\\b(?:failing|broken)\\b[\\s\\S]{0,12}\\b(?:tests?|build|spec)\\b","\\bmake it (?:build|compile|pass)\\b","\\b(?:run|rerun|re-run) (?:the )?(?:tests?|test suite|build|spec)\\b","\\b(?:npm (?:test|run build)|pnpm (?:test|build)|yarn (?:test|build)|pytest|go test|cargo (?:test|build)|vitest|jest|gradle|mvn)\\b","(?:\u8BA9|\u4F7F|\u786E\u4FDD)[\\s\\S]{0,12}(?:\u6D4B\u8BD5|\u5355\u6D4B|\u7528\u4F8B|\u6784\u5EFA|\u7F16\u8BD1)[\\s\\S]{0,8}(?:\u901A\u8FC7|\u8DD1\u901A|\u6210\u529F|\u7EFF)","(?:\u4FEE\u590D|\u4FEE\u597D|\u89E3\u51B3)[\\s\\S]{0,12}(?:\u5931\u8D25\u7684?\u6D4B\u8BD5|\u6D4B\u8BD5\u5931\u8D25|\u7F16\u8BD1\u9519\u8BEF|\u6784\u5EFA\u9519\u8BEF|\u7F16\u8BD1\u62A5\u9519|\u62A5\u9519)","\u6D4B\u8BD5\u901A\u8FC7|\u8DD1\u901A\u6D4B\u8BD5|\u7F16\u8BD1\u901A\u8FC7|\u6784\u5EFA\u901A\u8FC7|\u901A\u8FC7(?:\u5168\u90E8|\u6240\u6709)?\u6D4B\u8BD5|\u8BA9\u6D4B\u8BD5\u53D8\u7EFF"].join("|"),"i");function Ln(e){return e.some(t=>t.role==="user"&&typeof t.content=="string"&&Ea.test(t.content))}function Ia(e){return e.some(t=>{if(t.role!=="user"||typeof t.content!="string")return!1;let n=t.content.toLowerCase(),o=/\b(?:app|application|web ?app|website|site|dashboard|frontend|react|vite|vue|next|svelte|game)\b/.test(n)||/(?:应用|网站|网页|前端|页面|项目|游戏|看板|仪表盘|app)/.test(t.content),r=/\b(?:research|market|analysis|analyze|recommendation|strategy|sourced|citations?|report|brief|memo|study|whitepaper)\b/.test(n)||/(?:研究|报告|分析|评估|建议|策略|引用|来源|事实|调研|备忘录)/.test(t.content);if(o&&!r)return!1;let s=t.content.replace(/[A-Za-z]:[\\/][^\s"'`<>|]+/g," ").replace(/\b[A-Za-z0-9._-]*review\.(?:md|txt|docx|pdf)\b/gi," ").toLowerCase();return/\b(?:research|market|analysis|analyze|recommendation|strategy|sourced|citations?|report|brief|memo|study|whitepaper)\b/.test(s)?!0:/(?:研究|分析|审计|评估|建议|策略|引用|来源|事实)/.test(s)})}function Rr(e){return["Done","Not done","Artifacts","Verification","Blockers","Next action"].every(t=>new RegExp(`(^|\\n)${t}:`,"i").test(e))}function _r(e){return["Sourced facts","Assumptions","Recommendations","Unsupported claims"].every(t=>new RegExp(`(^|\\n)${t}:`,"i").test(e))}function Nn(e,t){let n=Pr(t);return n?xa.has(e)?xr(n.path,n.file_path,n.filePath,n.filename,n.file):va.has(e)?xr(n.output_path,Array.isArray(n.output_paths)?n.output_paths[0]:void 0):null:null}function wr(e){let t=Nn(e.toolName,e.rawArguments);if(!t||!se(e.inputMessages))return null;if(!e.state.artifactRoot){let r=$n(e.inputMessages);r?(e.state.artifactRoot=r,e.state.rootSource="explicit"):(e.state.artifactRoot=Or(t),e.state.rootSource=e.state.artifactRoot?"inferred":void 0)}let n=e.state.artifactRoot;if(!n||e.state.rootSource!=="explicit"||Nr(t,n))return null;let o=`Artifact root contract blocked ${e.toolName}: attempted to write ${t}, but this deliverable root is ${n}. Keep generated app/project files inside the declared artifactRoot, or ask for explicit approval before changing scope.`;return{path:t,artifactRoot:n,error:o}}function Ar(e){let t=Nn(e.toolName,e.rawArguments);return!t||!Wa(t)?null:{path:t,error:`Read-only context-pack blocked ${e.toolName}: attempted to write ${t}. Context packs are source evidence; write document indexes, checkpoints, and maintenance updates under benchmark-state instead.`}}function Fn(e,t){e.writePaths.includes(t.path)||e.writePaths.push(t.path),e.outOfRootWrites.some(n=>n.path===t.path&&n.toolName===t.toolName)||e.outOfRootWrites.push(t)}function Sr(e){let t=Nn(e.toolName,e.rawArguments);if(t){if(!e.state.artifactRoot){let o=$n(e.inputMessages);e.state.artifactRoot=o??Or(t),e.state.rootSource=o?"explicit":e.state.artifactRoot?"inferred":void 0}e.state.writePaths.includes(t)||e.state.writePaths.push(t),se(e.inputMessages)&&e.state.artifactRoot&&e.state.rootSource==="explicit"&&!Nr(t,e.state.artifactRoot)&&Fn(e.state,{path:t,artifactRoot:e.state.artifactRoot,toolName:e.toolName})}let n=`${e.rawArguments}
|
|
2
|
+
${e.content}`;for(let o of n.matchAll(In)){let r=On(o[0]);r&&(e.state.devServerUrls.includes(r)||e.state.devServerUrls.push(r))}if(Ua(e.toolName,e.rawArguments,e.content)&&Lr(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&&$a(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(za(e.toolName,e.rawArguments))if(!e.ok||Ha(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 Bn(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:se(t)}}function Mr(e){let t=Ma(e);for(let n of e)n.role!=="assistant"||typeof n.content!="string"||Dn(t,n.content);return t}function Dn(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 a=he(i.trim());a&&!e.writePaths.includes(a)&&e.writePaths.push(a)}let s=t.match(/(?:^|\n)\s*-\s*urls:\s*([^\n]+)/i)?.[1]?.trim();if(s&&!/none recorded/i.test(s))for(let i of s.matchAll(In)){let a=On(i[0]);a&&!e.devServerUrls.includes(a)&&e.devServerUrls.push(a)}for(let i of t.matchAll(In)){let a=On(i[0]);a&&/^https?:\/\/(?:localhost|127\.0\.0\.1):\d+\//i.test(a)&&(e.devServerUrls.includes(a)||e.devServerUrls.push(a))}}function Er(e){let t=e.content.trim(),n=se(e.inputMessages),o=Ia(e.inputMessages),r=Ln(e.inputMessages),s=Va(t),i=t;if(Ir(e.activeTasks??[]).length>0&&(i=La(i)),n&&!e.artifactContract.browserVerified&&(i=Na(i)),r&&!e.artifactContract.buildVerified&&(i=Fa(i)),!(s&&e.totalToolCallCount===0)&&o&&!_r(i)){let h=Da(i);i=i?`${i}
|
|
4
3
|
|
|
5
|
-
${h}`:h}let u=!!e.artifactContract.artifactRoot||e.artifactContract.writePaths.length>0||e.artifactContract.devServerUrls.length>0||e.artifactContract.browserVerified||e.artifactContract.outOfRootWrites.length>0;if((e.totalToolCallCount>0||n||r||u)&&!
|
|
4
|
+
${h}`:h}let u=!!e.artifactContract.artifactRoot||e.artifactContract.writePaths.length>0||e.artifactContract.devServerUrls.length>0||e.artifactContract.browserVerified||e.artifactContract.outOfRootWrites.length>0;if((e.totalToolCallCount>0||n||r||u)&&!Rr(i)&&!Rr(i)){let h=Pa({...e,content:i,needsBrowser:n,needsResearch:o,needsBuild:r});i=i?`${i}
|
|
6
5
|
|
|
7
|
-
${h}`:h}return i}function
|
|
8
|
-
`)}function
|
|
9
|
-
`)}function
|
|
10
|
-
${n}`),s=
|
|
6
|
+
${h}`:h}return i}function Pa(e){let t=[],n=[],o=Ir(e.activeTasks??[]);if(o.length>0&&(n.push(`Task list still has ${o.length} unresolved item(s): ${o.map(Oa).join("; ")}.`),t.push("Update unresolved task items to completed, cancelled, or an explicit blocker before claiming completion.")),e.artifactContract.outOfRootWrites.length>0&&(n.push("Artifact root drift was detected and at least one write was outside the deliverable root."),t.push(...e.artifactContract.outOfRootWrites.slice(0,3).map(f=>`${f.toolName} attempted ${f.path} outside ${f.artifactRoot}.`))),e.needsBrowser&&!e.artifactContract.browserVerified){let f=e.artifactContract.browserFailureEvidence[0];n.push(f?"Browser-visible acceptance was attempted but failed; no passing browser evidence was recorded.":"Browser-visible acceptance was not recorded for this app/frontend deliverable."),t.push(f?`Fix the browser verification failure before claiming completion: ${f}`:"Load the served app in a browser-capable tool and verify visible UI behavior before claiming completion.")}if(e.needsBuild&&!e.artifactContract.buildVerified){let f=e.artifactContract.buildFailureEvidence[0];n.push(f?"A test/build run is still failing; no passing test/build evidence was recorded.":"The requested test/build was not run to a passing result."),t.push(f?`Fix the code and re-run the test/build until it passes (do not edit the test): ${f.slice(0,200)}`:"Run the project's test/build command and confirm it exits 0 before claiming completion.")}e.needsResearch&&!_r(e.content)&&n.push("Research/report quality audit sections were not separated in the model response.");let r=Ba(e.content,e.blockedToolCalls??[]);r.length>0&&(n.push("The turn stopped with unresolved tool-call blockers instead of completing all requested work."),t.push(...r.slice(0,5).map(f=>`${f.name} blocked by ${f.reason}.`)));let s=e.totalToolCallCount>0?`Ran ${e.totalToolCallCount} tool call${e.totalToolCallCount===1?"":"s"} (${[...e.distinctToolNames].join(", ")||"unknown tools"}).`:"No tool work was recorded.",i=[e.artifactContract.artifactRoot?`artifactRoot: ${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"],a=e.artifactContract.browserVerified?`Browser evidence recorded: ${e.artifactContract.browserEvidence[0]??"yes"}`:e.needsBrowser?e.artifactContract.browserFailureEvidence[0]?`Browser verification failed: ${e.artifactContract.browserFailureEvidence[0]}`:"Browser evidence missing.":e.needsBuild?e.artifactContract.buildVerified?`Test/build passed: ${e.artifactContract.buildEvidence[0]??"yes"}`:e.artifactContract.buildFailureEvidence[0]?`Test/build failing: ${e.artifactContract.buildFailureEvidence[0].slice(0,200)}`:"No passing test/build evidence recorded.":"No browser acceptance required for this request.",u=t.length>0?"Resolve the blocker(s), then rerun verification and issue a new final status.":"Proceed with user review or requested follow-up.";return["Done:",`- ${s}`,"","Not done:",...n.length>0?n.map(f=>`- ${f}`):["- None recorded."],"","Artifacts:",...i.map(f=>`- ${f}`),"","Verification:",`- ${a}`,"","Blockers:",...t.length>0?t.map(f=>`- ${f}`):["- None recorded."],"","Next action:",`- ${u}`].join(`
|
|
7
|
+
`)}function Ir(e){return e.filter(t=>t.status!=="completed")}function Oa(e){return`#${e.id} ${e.title} (${e.status})`}function La(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 Na(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 Fa(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 Ba(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 Da(e){let t=/\b(?:source|citation|cited|http|https|来源|引用)\b/i.test(e),n=/\b(?:recommend|strategy|should|go|no-go|risk|mitigation|建议|策略|风险|缓解)\b/i.test(e),o=/\b(?:assum|uncertain|unknown|gap|unsupported|verify|need|缺口|假设|不确定|未验证|需确认)\b/i.test(e);return["Sourced facts:",t?"- Source-backed claims are present in the response and must remain tied to the cited URLs or named evidence.":"- No clearly source-backed facts were isolated; treat factual claims as unsupported until evidence is added.","","Assumptions:",o?"- Assumptions, uncertainties, or verification gaps are explicitly called out in the response.":"- No explicit assumptions were separated; reviewer should treat missing premises as open gaps.","","Recommendations:",n?"- Recommendations are present and should be read as advice conditioned on the stated evidence and assumptions.":"- No recommendation section was clearly separated.","","Unsupported claims:","- Any claim without visible evidence must be treated as unsupported until reviewed."].join(`
|
|
8
|
+
`)}function Pr(e){try{return JSON.parse(e)}catch{return null}}function xr(...e){for(let t of e)if(typeof t=="string"&&t.trim())return t.trim();return null}function $n(e){for(let t of e)if(!(t.role!=="user"||typeof t.content!="string"))for(let n of t.content.matchAll(wa)){let o=n[1]??n[2],r=Ct(o??"");if(r&&!Ga(r))return he(r)}}function Or(e){let t=he(Ct(e));if(!t)return;let n=t.toLowerCase();if(n.endsWith("/package.json"))return vr(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 vr(t)}function $a(e,t,n){if(/^read$/i.test(e)||n.includes("<persisted-output>")||Lr(n)||/\b(?:syntax error|command not found|cannot find|not recognized|failed|failure|exception|traceback|eaddrinuse)\b|无法将|错误|失败/i.test(n))return!1;let o=kr.test(n),r=/\b(?:playwright|puppeteer|browser|screenshot|locator|page\.goto|dom snapshot|visible text|assertion)\b|浏览器|截图|可见|定位器/i.test(`${t}
|
|
9
|
+
${n}`),s=Un(e)&&kr.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)||Sa.test(n)&&!/\b(?:absent|removed|not present|gone|没有|不是默认|已移除)\b/i.test(n))}function Ua(e,t,n){return/^read$/i.test(e)||!Un(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 Lr(e){return/\b(?:no failed|0 failed|without failed|no failures|failure:? none|failed checks?:? none)\b/i.test(e)?!1:Aa.test(e)?!0:/\b(?:fail|failed|failure|error)\b/i.test(e)}function Un(e){return/^(?:exec|bash|shell|powershell|terminal|playwright|browser|computer)$/i.test(e)}var ja=new RegExp(["(?:^|[\\s;&|(])(?:npm|pnpm|yarn|bun)\\s+(?:run\\s+)?(?:test|t|build|lint|typecheck|tsc|check)\\b","(?:^|[\\s;&|(])npx\\s+(?:-y\\s+)?(?:vitest|jest|mocha|tsc|playwright|ava|tap)\\b","(?:^|[\\s;&|(])(?:vitest|jest|mocha|ava|pytest|py\\.test|ctest|tsc)\\b","(?:^|[\\s;&|(])python\\s+-m\\s+(?:pytest|unittest)\\b","(?:^|[\\s;&|(])go\\s+test\\b","(?:^|[\\s;&|(])cargo\\s+(?:test|build|check)\\b","(?:^|[\\s;&|(])(?:mvn|gradle|gradlew|make|cmake)\\s+\\S","(?:^|[\\s;&|(])node\\s+(?:--test\\b|[^\\n;&|]*test[^\\n;&|]*\\.[cm]?js)"].join("|"),"i");function qa(e){let t=Pr(e);return t&&typeof t.command=="string"?t.command:""}function za(e,t){return Un(e)?ja.test(qa(t)):!1}function Ha(e){return/\[exit [1-9]\d*\b|\(exit code [1-9]\d*\b|\[interrupted — exit code [1-9]\d*/.test(e)}function Ga(e){return/\.[A-Za-z0-9]{1,12}$/.test(e)}function Nr(e,t){let n=Pn(e),o=Pn(t);return n===o||n.startsWith(`${o}/`)}function Wa(e){return Pn(e).split("/").includes("context-pack")}function Pn(e){return Ct(e).replace(/\\/g,"/").replace(/\/+/g,"/").replace(/\/$/u,"").toLowerCase()}function he(e){return Ct(e).replace(/\\/g,"/").replace(/\/+/g,"/").replace(/\/$/u,"")}function On(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 Ct(e){return e.trim().replace(/[).,;:,。;、:]+$/u,"")}function Va(e){return/^[A-Z0-9_ -]{6,80}$/.test(e.trim())}function vr(e){let t=he(e),n=t.lastIndexOf("/");return n>0?t.slice(0,n):t}var Xa=/^no (matches|files|results) found(?:\s+for:.*)?\.?$|^file not found|^not found|^0 results|^\(exit code \d+, no output\)$/i,Ka=new Set(["search","web_search","grep","glob","find","list","read","exec"]),Ya=/[A-Za-z]:[\\/](?:[^\s"'`<>|,\uFF0C\u3001;\uFF1B\u3002]+[\\/])*[^\s"'`<>|,\uFF0C\u3001;\uFF1B\u3002]+\.[A-Za-z0-9]{1,12}/g,Za=/(?:^|[\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,Ja=/(?:^|[\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,Qa=/\b(?:create|generate|write|produce|save|output|deliver|deliverables?|artifacts?|required|required files?|must generate|self-verify)\b|(?:生成|创建|写入|输出|保存|交付|产物|文件|必须|自检|验证)/i;function Fr(e){if(!Ka.has(e.toolName))return!1;let t=typeof e.message?.content=="string"?e.message.content.trim():"";return t.length>0&&t.length<200&&Xa.test(t)}function kt(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 el=/\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,Br=50,Dr=90;function $r(e){if(!e)return!1;for(let t of e)if(t.role==="user"&&typeof t.content=="string"&&el.test(t.content))return!0;return!1}var tl=/(?:我来|我先|我现在就?|让我先?|接下来我?|我帮你|我这就|我会|我将|我去|我看)[^。.!?!?\n]{0,12}(?:做|搭建?|写|开发|实现|构建|生成|创建|新建|建立|改|修复?|检查|读取?|运行|跑|执行|看一?下?|查看|配置|安装|部署|分析|整理|定位|排查|找)/,nl=/\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 Ur(e){let t=e.trim();return t.length===0||t.length>200||t.includes("```")?!1:tl.test(t)||nl.test(t)}function jr(e,t){if(typeof e=="number"&&Number.isFinite(e)&&e>=1)return Math.min(Math.round(e),100);let n=Rt(t);return n>=3?Math.min(Math.max(25,20+n*15),100):se(t??[])?Math.min(Math.max(25,Dr),100):$r(t)?Math.min(Math.max(25,Br),100):25}function Rt(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(Ya))o(i[0]);if(Qa.test(s)){for(let i of s.matchAll(Za)){let a=i[1]?.toLowerCase();if(!a)continue;t.add(`relative:${a.replace(/\\/g,"/")}`);let u=a.replace(/\\/g,"/").split("/").pop();u&&n.add(u)}for(let i of s.matchAll(Ja)){let a=i[1]?.toLowerCase();!a||n.has(a)||t.add(`name:${a}`)}}}return t.size}function qr(e,t){if(typeof e=="number"&&Number.isFinite(e)&&e>=1)return Math.min(Math.round(e),100);let n=Rt(t);return n>=3?Math.min(Math.max(ge,20+n*15),100):se(t??[])?Math.min(Math.max(ge,Dr),100):$r(t)?Math.min(Math.max(ge,Br),100):ge}function zr(e){return e.filter(t=>t.role!=="assistant"?!0:!(typeof t.content=="string"&&t.content.trim()===""))}function jn(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
10
|
|
|
12
|
-
`)):""}function
|
|
11
|
+
`)):""}function qn(e,t){let n=kt(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
12
|
|
|
14
13
|
\u6700\u540E\u4E00\u6B21\u5DE5\u5177\u9519\u8BEF\uFF1A
|
|
15
14
|
${n}
|
|
16
15
|
|
|
17
16
|
\u8BF7\u6839\u636E\u4E0A\u9762\u7684\u9519\u8BEF\u4FEE\u6B63\u540E\u91CD\u8BD5\uFF0C\u6216\u6362\u4E00\u79CD\u5B9E\u73B0\u65B9\u5F0F\u3002`:`${o}
|
|
18
17
|
|
|
19
|
-
\u8BF7\u91CD\u8BD5\uFF0C\u6216\u6362\u4E00\u79CD\u5B9E\u73B0\u65B9\u5F0F\u3002`}function
|
|
18
|
+
\u8BF7\u91CD\u8BD5\uFF0C\u6216\u6362\u4E00\u79CD\u5B9E\u73B0\u65B9\u5F0F\u3002`}function Hr(e){let t,n;for(let r=e.length-1;r>=0;r--){let s=e[r];if(s?.role==="tool"&&typeof s.content=="string"&&s.content.startsWith("Error: ")){t=s.content.slice(7,807).trim(),n=typeof s.tool_call_id=="string"?s.tool_call_id:void 0;break}}if(!t)return null;let o;if(n)for(let r of e){let s=r.tool_calls;if(Array.isArray(s))for(let i of s){let a=i;if(a.id!==n)continue;let u=a.function;typeof u?.arguments=="string"&&(o=zn(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
19
|
|
|
21
20
|
`+(o?`\u6700\u540E\u4E00\u6B21\u8C03\u7528\uFF1A${o}
|
|
22
21
|
`:"")+`\u6700\u540E\u4E00\u6B21\u9519\u8BEF\uFF1A
|
|
23
22
|
${t}
|
|
24
23
|
|
|
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 Yn(e){try{if(e.endsWith("/*")){let n=e.slice(0,-2);return
|
|
24
|
+
\u8BF7\u6309\u9519\u8BEF\u4FE1\u606F\u7EA0\u6B63\u540E\u518D\u91CD\u8BD5\uFF1A\u5982\u679C\u662F\u547D\u4EE4\u884C\u5DE5\u5177\uFF0C\u5148\u7528\u5B83\u81EA\u5E26\u7684\u5E2E\u52A9\u786E\u8BA4\u6B63\u786E\u7684\u5B50\u547D\u4EE4/\u53C2\u6570/\u8BED\u6CD5\uFF08\u5982 \`<\u5DE5\u5177> --help\` \u6216 \`<\u5DE5\u5177> help <\u5B50\u547D\u4EE4>\`\uFF09\uFF0C\u4E0D\u8981\u51ED\u76F4\u89C9\u62FC\u547D\u4EE4\uFF1B\u6216\u6362\u4E00\u79CD\u5B9E\u73B0\u65B9\u5F0F\u3002`}}function zn(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 Hn(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 Gn(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 Gr(e){return e==="length"||e==="max_tokens"}function Wn(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 Wr(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 Vr(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*Xr(e){let{messages:t,contentReplacementState:n,snipRemovedIds:o,collapseStore:r,guardConfig:s,runtimePorts:i,hooks:a,hookCtx:u,sessionId:f,currentModel:h,log:T,recovery:R,onAutocompact:x}=e,w;{let v=await i.enforceToolResultBudget(t,n,f);w=v.messages,v.newlyReplacedCount>0&&(T.info(`tool-result-budget: persisted ${v.newlyReplacedCount} oversized tool results`),yield R("tool_result_budget",`${v.newlyReplacedCount} persisted`))}{let v=cn(w,o);w=v.messages,v.removedCount>0&&(T.info(`snip: removed ${v.removedCount} messages, freed ~${v.tokensFreed} tokens`),yield R("snip",`${v.removedCount} messages`))}{let P=new Xe().compress(w,0);P.droppedCount>0&&(w=P.messages,T.info(`microcompact: cleared ${P.droppedCount} old tool results`))}if(w=dn(w,r).messages,s.contextWindowTokens>0){let v=s.contextWindowTokens*.75,P=i.getActiveContextCompressionEngine(),A;P?A=await P.compressAsync(w,v,{model:h,sessionId:f}):A=i.compressMessages(w,{budget:v,model:h}),A.droppedCount>0&&(w=A.messages,T.info(`autocompact: ${A.strategy}, dropped ${A.droppedCount}`),yield R("autocompact",`${A.strategy}: ${A.droppedCount} dropped`),yield{type:"lifecycle",turnId:u.turnId,kind:"context_compression",status:"completed",detail:`${A.strategy}: ${A.droppedCount} dropped`},x(),$(a,"context.after_compact",{...u,removedCount:A.droppedCount},T))}return w=zr(w),w}async function*Kr(e,t){let{state:n,guardState:o,fallbackModel:r,signal:s,querySource:i,turnId:a,log:u,emitRecovery:f}=t;if(e instanceof Ke&&r)return u.info(`model fallback triggered: ${e.originalModel} -> ${e.fallbackModel}`),yield f("model_fallback",`${e.originalModel} -> ${e.fallbackModel}`),{kind:"continue",patch:{currentModel:e.fallbackModel,consecutive529Errors:0,consecutiveApiRetries:0,transition:void 0}};let h=e instanceof Error?e.message:String(e),T=typeof e?.status=="number"?e.status:void 0;if(!T&&h&&(h.includes("ECONNRESET")||h.includes("EPIPE"))){let x=(n.consecutiveApiRetries??0)+1;return x>_e?(u.info(`stale connection retry limit reached (${_e}), aborting`),yield{type:"error",turnId:a,error:h,code:"RETRIES_EXHAUSTED",usage:n.totalUsage},{kind:"return"}):(u.info(`stale connection (${h.includes("ECONNRESET")?"ECONNRESET":"EPIPE"}): retrying`),yield f("stale_connection_retry",h.slice(0,80)),{kind:"continue",patch:{consecutiveApiRetries:x,transition:void 0}})}let R=Vr({status:T,message:h});if(R!==null)return u.info(`max_tokens overflow: adjusting to ${R}`),o.currentMaxOutputTokens=R,{kind:"continue",patch:{maxOutputTokensOverride:R,transition:void 0}};if(xn(T)){n.consecutive529Errors++;let x=2,w=r&&n.currentModel!==r;if(n.consecutive529Errors>x&&!w&&!Tt())return u.info(`transient ${T} \u8133 ${n.consecutive529Errors}: hard limit reached, aborting`),yield{type:"error",turnId:a,error:`API unavailable after ${n.consecutive529Errors} consecutive ${T} errors`,code:"API_ERROR",usage:n.totalUsage},{kind:"return"};if(n.consecutive529Errors>=ir&&r&&n.currentModel!==r)return u.info(`529 \u8133 ${n.consecutive529Errors}: triggering fallback to ${r}`),yield f("model_fallback",`529 \u8133 ${n.consecutive529Errors}`),{kind:"continue",patch:{currentModel:r,consecutive529Errors:0,transition:void 0}};if(Tt()){let v=bt(n.consecutive529Errors);u.info(`persistent retry: waiting ${v}ms (attempt ${n.consecutive529Errors})`);let P=v;for(;P>0;){if(s?.aborted)return yield{type:"error",turnId:a,error:"Aborted during retry wait",code:"ABORTED",usage:n.totalUsage},{kind:"return"};yield{type:"heartbeat",turnId:a,message:`Retrying in ${Math.ceil(P/1e3)}s (${T})`};let A=Math.min(P,sr);await new Promise(L=>setTimeout(L,A)),P-=A}return{kind:"continue",patch:{transition:void 0}}}if(Rn(i)){let P=Wr({status:T,message:h})??bt(n.consecutive529Errors);return u.info(`transient ${T}: retry in ${P}ms`),yield f("retry",`${T} retry in ${P}ms`),await new Promise(A=>setTimeout(A,P)),{kind:"continue",patch:{transition:void 0}}}u.info(`background source ${i}: not retrying ${T}`)}return{kind:"streamError",streamError:{status:T,message:h}}}import{readdirSync as es,statSync as Ze}from"node:fs";var ol=/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,ts=/[A-Za-z]:[\\/](?:[^\s"'`<>|,\uFF0C\u3001;\uFF1B\u3002]+[\\/])*[^\s"'`<>|,\uFF0C\u3001;\uFF1B\u3002]+\.[A-Za-z0-9]{1,12}/g,Yr=/\s*[,\uFF0C\u3001;\uFF1B]\s*([^\s"'`<>|,\uFF0C\u3001;\uFF1B\u3002\\/]+\.[A-Za-z0-9]{1,12})/gy,rl=/\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,sl=/(?:^|[\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,il=/(?:^|[\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,al=/(?:^|[\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,ll=/\b(?:create|generate|write|produce|save|output|deliver|deliverables?|artifacts?|required|required files?|must generate|self-verify)\b|(?:生成|创建|写入|输出|保存|交付|产物|文件|必须|自检|验证)/i,cl=/\bpreviews?[\\/]\s*(?:containing|with|under|for)?[^.。;;\n]*(?:rendered|preview|previews|check|evidence|verify|verification)\b/i,ul=/(?:do\s*not|don'?t|never|不要|不能|别|勿|禁止|不准|不得)[^.。;;\n]{0,14}(?:create|write|make|produce|generate|生成|创建|写入|写出|建立|新建)/i;function X(e){return e.trim().replace(/[),.;:\uFF0C\u3002\uFF1B\u3001]+$/u,"").replace(/\\/g,"/").toLowerCase()}function ns(e){return e.trim().replace(/[),.;:\uFF0C\u3002\uFF1B\u3001]+$/u,"").replace(/\\/g,"/").replace(/\/+$/u,"")}function Zr(e){return/\.[A-Za-z0-9]{1,12}$/u.test(e.replace(/[),.;:\uFF0C\u3002\uFF1B\u3001]+$/u,""))}function Jr(e,t,n){let o=Math.max(e.lastIndexOf(".",t),e.lastIndexOf(`
|
|
25
|
+
`,t),e.lastIndexOf(";",t),e.lastIndexOf("\u3002",t),e.lastIndexOf("\uFF1B",t))+1,r=e.slice(o,t).toLowerCase();if(/\b(?:do\s+not|don't|never)\s+(?:leave|create|write|include|keep|produce|add|generate)\b/i.test(r)||/\b(?:remove|delete|exclude)\b/i.test(r))return!0;let s=e.slice(Math.max(0,t-16),t+n.length);return new RegExp(`\\bno\\s+${is(n)}\\b`,"i").test(s)}function Vn(e){return e.replace(/https?:\/\/\S+/gu," ")}function Xn(e){let t=new Set,n=[],o=r=>{let s=r.replace(/[),.;:\uFF0C\u3002\uFF1B]+$/u,""),i=X(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=Vn(r.content);for(let i of s.matchAll(ts)){let a=i[0],u=(i.index??0)+a.length;if(s[u]==="/"||s[u]==="\\")continue;o(a);let f=a.replace(/\\/g,"/"),h=f.lastIndexOf("/");if(h>=0){let T=f.slice(0,h+1);Yr.lastIndex=u;let R;for(;(R=Yr.exec(s))!==null;)o(`${T}${R[1]}`)}}}for(let r of e){if(r.role!=="user"||typeof r.content!="string")continue;let s=Vn(r.content);if(!ll.test(s))continue;let i=Array.from(s.matchAll(rl)).map(u=>ns(u[1]??"")).filter(u=>u&&!Zr(u));if(i.length===0)continue;let a=i[i.length-1];for(let u of s.matchAll(sl)){let f=u[1];f&&(Jr(s,u.index??0,f)||o(`${a}/${f}`))}for(let u of s.matchAll(il)){let f=u[1];f&&(Jr(s,u.index??0,f)||o(`${a}/${f}`))}for(let u of s.matchAll(al)){let f=u[1];f&&(Zr(f)||/(?:assets[\\/]generated|screenshots(?:[\\/]|$)|previews(?:[\\/]|$))/i.test(f)&&/\b(?:generated|bitmap|png|screenshots?|preview|previews|evidence|assets?|containing)\b/i.test(s)&&o(`${a}/${f}/*`))}cl.test(s)&&o(`${a}/previews/*`)}return n}function vt(e){if(e.role!=="tool")return!1;let t=typeof e.content=="string"?e.content:"";return e.is_error!==!0&&!t.startsWith("Error:")}function Kn(e){let t=new Set,n=new Map,o=[];for(let r of e){let s=r,i=Array.isArray(s.tool_calls)?s.tool_calls:[];for(let a of i){let u=a,f=u.id,h=u.function;typeof f=="string"&&typeof h?.name=="string"&&n.set(f,h.name)}}for(let r of e){let s=r;if(vt(s)){let i=s.tool_call_id;typeof i=="string"&&t.add(i),(typeof i=="string"?n.get(i):void 0)==="exec"&&typeof s.content=="string"&&o.push(s.content)}}for(let r of e){let s=r,i=Array.isArray(s.tool_calls)?s.tool_calls:[];for(let a of i){let u=a,f=u.id;if(typeof f=="string"&&t.size>0&&!t.has(f))continue;let h=u.function;if(!(typeof h?.name!="string"||typeof h.arguments!="string"))try{let T=JSON.parse(h.arguments);if(h.name==="write"||h.name==="edit"){for(let R of["path","filePath","file_path"]){let x=T[R];typeof x=="string"&&o.push(x)}continue}if(h.name==="exec"){let R=T.command;typeof R=="string"&&o.push(R)}}catch{h.name==="exec"&&o.push(h.arguments)}}}return o.join(`
|
|
26
|
+
`).replace(/\\/g,"/").toLowerCase()}function Yn(e){try{if(e.endsWith("/*")){let n=e.slice(0,-2);return es(n,{withFileTypes:!0}).some(r=>{if(!r.isFile())return!1;try{return Ze(`${n}/${r.name}`).size>0}catch{return!1}})}let t=Ze(e);return t.isFile()&&t.size>0}catch{return!1}}function dl(e,t){let n=X(t);if(!n.endsWith("/*"))return e.includes(n);let o=n.slice(0,-1);return e.includes(o)}function fl(e){let t=new Set;for(let n of e){let o=n,r=Array.isArray(o.tool_calls)?o.tool_calls:[];for(let s of r){let i=s,a=i.id,u=i.function;typeof a=="string"&&u?.name==="agent"&&t.add(a)}}for(let n of e){let o=n,r=o.tool_call_id;if(typeof r=="string"&&t.has(r)&&vt(o))return!0}return!1}function pl(e){let t=ss(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 ml(e){let t=ns(e),n=t.lastIndexOf("/");return n>=0?t.slice(0,n):""}function gl(e){if(e.length===0)return"";let t=e.map(o=>ml(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 hl(e,t){let n=X(e);return t.some(o=>{let r=X(o);return r.endsWith("/*")?n.startsWith(r.slice(0,-1)):n===r})}function os(e){let t=new Set,n=new Map;for(let o of e){let r=o,s=Array.isArray(r.tool_calls)?r.tool_calls:[];for(let i of s){let a=i,u=a.id,f=a.function;if(typeof u!="string"||f?.name!=="write"&&f?.name!=="edit"||typeof f.arguments!="string")continue;let h=_t(f.arguments);if(!h)continue;let T=wt(h);T&&n.set(u,T)}}for(let o of e){let r=o;if(!vt(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 yl(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 bl(e){return[...new Set([...e.matchAll(/\bGoal\s+\d+\b/gi)].map(t=>t[0].replace(/\s+/g," ").replace(/\bgoal\b/i,"Goal")))]}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 a=i,u=a.id,f=a.function;if(typeof u!="string"||f?.name!=="write"&&f?.name!=="edit"||typeof f.arguments!="string")continue;let h=_t(f.arguments);if(!h)continue;let T=wt(h)??"",R=as(h);(/\bartifact[-_\s]?index\b/i.test(T)||/\bartifact[-_\s]?index\b/i.test(R))&&n.set(u,R)}}for(let o of e){let r=o;if(!vt(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 Cl(e){let t=ss(e.inputMessages);if(!yl(t))return[];let n=Tl(e.messages).at(-1);if(!n)return[];let o=[],r=bl(t).filter(u=>!new RegExp(`\\b${is(u)}\\b`,"i").test(n));r.length>0&&o.push({type:"missing_goal_labels",detail:`Missing requested row labels in the generated index: ${r.join(", ")}`});let s=/\b(?:failed|partial|missing|not\s+found|no\s+[^.\n|]*evidence)\b/i.test(n),i=/\b(?:all\s+checks\s+pass|confirmed\s*:\s*all|everything\s+(?:passes|passed)|fully\s+verified)\b/i.test(e.finalText);s&&i&&o.push({type:"overconfident_final",detail:"Final response claimed all checks pass while the generated index contains failed, partial, missing, or no-evidence rows."});let a=n.split(/\r?\n/u).filter(u=>/\bno\s+[^|\n]*(?:found|evidence|files?)\b/i.test(u)&&!/\b(?:not\s+verified|unverified|unknown|not\s+checked|search\s+scope|checked\s+path)\b/i.test(u));return a.length>0&&o.push({type:"unsupported_absence",detail:`Absence claims need scoped evidence or must be marked unverified: ${a.slice(0,3).join(" ; ")}`}),o}function kl(e){let t=[],n=o=>{let r;try{r=es(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{Ze(i).size>0&&t.push(i)}catch{}}};try{if(!Ze(e).isDirectory())return[]}catch{return[]}return n(e),t}function Rl(e,t){if(!pl(e))return[];let n=Xn(e),o=n.filter(i=>!X(i).endsWith("/*"));if(o.length<2)return[];let r=gl(o);if(!r||r.split("/").length<3)return[];let s=X(r);return[...new Set([...os(t),...kl(r)])].filter(i=>X(i).startsWith(`${s}/`)&&!hl(i,n)&&Yn(i))}function rs(e,t){let n=Xn(e);if(n.length===0)return[];let o=Kn(t);return n.filter(r=>!dl(o,r))}function Ye(e){return Zn(e).fail}function xl(e){return e.replace(/[.,;:,。;:、!?]+$/u,"")}function xt(e){if(!e)return!1;let t=xl(e);return/^[A-Za-z0-9_.:-]+$/u.test(t)&&/[0-9_:-]/u.test(t)}function Zn(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))xt(s[2])&&(n=`${s[1].toUpperCase()} ${t(s[2])}`);for(let s of r.content.matchAll(/\bFAIL\s+([A-Za-z0-9_.:-]+)/gi))xt(s[1])&&(o=`FAIL ${t(s[1])}`);for(let s of r.content.matchAll(/\b([A-Za-z0-9_.:-]+)\s+(DONE|PASS)\b/gi))xt(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))xt(s[1])&&(o=`${t(s[1])} FAIL`)}return{done:n,fail:o}}function ss(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 is(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Me(e){let t=rs(e.inputMessages,e.messages).filter(o=>!Yn(o));return t.length===0?void 0:`${Ye(e.inputMessages)??"FAIL"} ${e.reason}. Missing required output file evidence: ${t.join(", ")}`}function _t(e){try{let t=JSON.parse(e);return t&&typeof t=="object"&&!Array.isArray(t)?t:null}catch{return null}}function wt(e){for(let t of["path","filePath","file_path"]){let n=e[t];if(typeof n=="string"&&n.trim())return n}}function as(e){for(let t of["content","newContent","replacement","text"]){let n=e[t];if(typeof n=="string")return n}return""}function ls(e){let t=e.toolCall.function.name;if(t!=="write"&&t!=="edit")return;let n=Zn(e.inputMessages);if(!n.done)return;let o=_t(e.toolCall.function.arguments);if(!o)return;let r=wt(o),s=as(o);if(!r||!s.includes(n.done))return;let i=Xn(e.inputMessages);if(i.length<2)return;let a=X(r);if(!i.some(T=>X(T)===a))return;let f=Kn(e.messages),h=i.filter(T=>X(T)!==a).filter(T=>!f.includes(X(T)));if(h.length!==0)return`Premature completion artifact blocked: this write/edit attempted to store the requested DONE marker in ${r} before evidence existed for sibling required output files: ${h.join(", ")}. Create or verify the missing files first, or report the requested FAIL marker with the real reason.`}function Ae(e,t){return{role:"assistant",content:e,...t.length>0&&{thinkingBlocks:[...t]}}}function vl(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 _l(e){let t=[...e].reverse().find(n=>n.role==="tool");t&&typeof t.content=="string"&&(t.content+=`
|
|
28
27
|
|
|
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:
|
|
28
|
+
\u923F\u72C5\u7B0D NOTE: You used shell commands but did not call the write or edit tool to create/modify the file. Shell commands may fail silently or produce incorrect results on this platform. Please use the 'write' tool directly to create the requested file with the correct content.`)}function Se(e,t,n,o){return{reason:e,messages:[...t,n,o],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}}}function cs(e){try{return Ze(e).isFile()}catch{return!1}}function wl(e,t){let n=new Map;for(let s of e){if(s.role!=="user"||typeof s.content!="string")continue;let i=Vn(s.content);if(ul.test(i))for(let a of i.matchAll(ts)){let u=a[0].replace(/[),.;:,。;]+$/u,""),f=X(u);f&&n.set(f,u)}}if(n.size===0)return[];let o=Kn(t),r=[];for(let[s,i]of n)(o.includes(s)||cs(i))&&r.push(s);return r}var Al="File not found:",Qr=/\b(?:create|write|make|generate|produce|save|output|deliver|initialize|init|ensure|touch|scaffold|build|set\s+up)\b|生成|创建|写入|写出|新建|建立|保存|输出|交付|初始化|确保/i,Sl=/\b(?:if|when|unless)\b[^.。;;\n]{0,40}(?:missing|not\s+exist|does\s*n['o]?t\s+exist|absent|no\s+such)|(?:如果|若|要是|倘若)[^.。;;\n]{0,24}(?:不存在|没有|缺失|不在|未创建)/i;function Ml(e,t){let n=t.slice(t.lastIndexOf("/")+1),o=/[.。;;!?!?\n]/u;for(let r of e){if(r.role!=="user"||typeof r.content!="string")continue;let s=r.content.replace(/\\/g,"/").toLowerCase(),i=n.length>3&&n!==t?[t,n]:[t];for(let a of i){let u=0;for(;;){let f=s.indexOf(a,u);if(f===-1)break;u=f+1;let h=f;for(;h>0&&!o.test(s[h-1]);)h--;let T=f+a.length;for(;T<s.length&&!o.test(s[T]);)T++;let R=r.content.slice(h,T);if(Qr.test(R))return!0}}}for(let r of e){if(r.role!=="user"||typeof r.content!="string")continue;let s=r.content.replace(/\\/g,"/").toLowerCase();if((s.includes(t)||n.length>3&&n!==t&&s.includes(n))&&Qr.test(r.content)&&Sl.test(r.content))return!0}return!1}function El(e){let t=new Map;for(let o of e){let r=o,s=Array.isArray(r.tool_calls)?r.tool_calls:[];for(let i of s){let a=i,u=a.id,f=a.function;if(typeof u!="string"||f?.name!=="read"||typeof f.arguments!="string")continue;let h=_t(f.arguments),T=h?wt(h):void 0;T&&t.set(u,T)}}let n=new Map;for(let o of e){let r=o;if(r.role!=="tool")continue;let s=r.tool_call_id;if(typeof s!="string")continue;let i=t.get(s);if(!i)continue;let a=typeof r.content=="string"?r.content:"";(r.is_error===!0||a.startsWith("Error:"))&&a.includes(Al)&&n.set(X(i),i)}return n}function Il(e,t){let n=El(t);if(n.size===0)return[];let o=new Set(os(t).map(X)),r=[];for(let[s,i]of n)Ml(e,s)||(o.has(s)||cs(i))&&r.push(s);return r}function Jn(e){let t=e.inputMessages.find(x=>x.role==="user"),n=typeof t?.content=="string"?t.content:"",o=ol.test(n),r=e.distinctToolNames.has("write")||e.distinctToolNames.has("edit"),s=Zn(e.inputMessages),i=wl(e.inputMessages,e.messages);if(i.length>0){e.log.info(`forbidden-file-creation guard: agent wrote ${i.length} file(s) the user forbade creating`);let x=Ye(e.inputMessages),w={role:"user",content:`You created a file the request explicitly forbade creating: ${i.join(", ")}. That is a constraint violation, not success \u2014 do NOT claim "completed" or "handled". Delete the file you wrongly created, then report ${x??"FAILED"} with the real reason: the task could not be done without violating the stated constraint. Do not fabricate a successful outcome.`};return Se("forbidden_file_creation",e.messages,Ae(e.finalText,e.thinkingBlocks),w)}let a=Il(e.inputMessages,e.messages),u=s.fail!==void 0&&e.finalText.includes(s.fail);if(a.length>0&&!u){e.log.info(`self-created-read-target guard: agent created ${a.length} file(s) it had read as not-found`);let x=Ye(e.inputMessages),w={role:"user",content:"You were asked to read "+a.join(", ")+`, but your read showed the file did not exist; you then created it yourself. Manufacturing an input you were told to read is not success \u2014 do NOT claim "completed" or "handled". Delete the file you wrongly created, then report ${x??"FAILED"} with the real reason: the file does not exist and the task cannot be done without fabricating it.`};return Se("self_created_read_target",e.messages,Ae(e.finalText,e.thinkingBlocks),w)}let f=fl(e.messages),h=rs(e.inputMessages,e.messages).filter(x=>!(f&&Yn(x)));if(h.length>0&&e.totalToolCallCount>0){if(s.fail!==void 0&&e.finalText.includes(s.fail))return null;e.log.info(`explicit required file verification: ${h.length} file(s) missing`);let x=Ye(e.inputMessages),w={role:"user",content:`Before completing, verify that every explicitly requested output file exists and is non-empty. Missing required output file evidence: ${h.join(", ")}. Create the missing files now, or if you cannot complete them, respond with ${x??"FAIL"} and the real reason. Do not claim completion until the missing files are handled.`};return Se("explicit_required_file_verification",e.messages,Ae(e.finalText,e.thinkingBlocks),w)}let T=Rl(e.inputMessages,e.messages);if(T.length>0&&e.totalToolCallCount>0){if(s.fail!==void 0&&e.finalText.includes(s.fail))return null;e.log.info(`explicit extra file verification: ${T.length} unexpected file(s)`);let x=Ye(e.inputMessages),w={role:"user",content:`The latest request asked for exactly the listed output artifacts, but extra files were produced under the output root: ${T.join(", ")}. Remove the extra files now, move scratch work outside the deliverable directory, or if you cannot make the output exact, respond with ${x??"FAIL"} and the real reason. Do not claim completion while extra deliverables remain.`};return Se("explicit_extra_file_verification",e.messages,Ae(e.finalText,e.thinkingBlocks),w)}let R=Cl({inputMessages:e.inputMessages,messages:e.messages,finalText:e.finalText});if(R.length>0&&e.totalToolCallCount>0){if(s.fail!==void 0&&e.finalText.includes(s.fail))return null;e.log.info(`artifact index evidence verification: ${R.length} issue(s)`);let x={role:"user",content:"Before completing, correct the artifact index against the actual evidence scope. "+R.map(w=>w.detail).join(" ")+" Use the exact requested Goal row labels, cite concrete evidence names/paths for status claims, and mark a row as not verified/unknown instead of claiming exhaustive absence without scoped evidence. Do not claim all checks pass while any row is failed, partial, missing, or unverified. After correcting and verifying the file, finish with the final status contract."};return Se("artifact_index_evidence_verification",e.messages,Ae(e.finalText,e.thinkingBlocks),x)}if(e.stopHookActive)return null;if(o&&!r){e.log.info("AP1 action-verification: user requested file action but no write/edit tool was called, injecting nudge"),e.totalToolCallCount>0&&_l(e.messages);let x={role:"user",content:e.totalToolCallCount===0?"You described what to do but did not actually call any tool to write or edit a file. Please use the write or edit tool now to perform the requested action. Do not just describe the changes - actually make them.":"You used shell commands but did not call the write or edit tool to create/modify the file. Shell commands may fail on this platform. Please use the write tool directly to create the requested file with the correct content."};return Se("file_action_verification",e.messages,Ae(e.finalText,e.thinkingBlocks),x)}if(e.totalToolCallCount>=3&&e.distinctToolNames.has("write")&&e.messages.filter(vl).length>=3){e.log.info("AP3 verification nudge: 3+ files created, injecting completeness check");let w={role:"user",content:"You created multiple files. Before completing, verify: (1) All imports between your files resolve to real exports. (2) No TODO, placeholder, or 'not implemented' stubs remain. (3) Functions that are imported are actually called, not just declared. If everything is correct, confirm completion. If not, fix the issues now."};return Se("multi_file_skeleton_verification",e.messages,Ae(e.finalText,e.thinkingBlocks),w)}return null}function Pl(e,t){return{role:"assistant",content:e,...t.length>0&&{thinkingBlocks:[...t]}}}async function us(e){if(!e.hooks)return null;let t=await e.hooks.invoke("stop",{sessionId:e.sessionId,reason:"completed"});if(t.action==="prevent")return e.log.info(`stop hook prevented continuation: ${t.reason??"no reason"}`),{action:"end",content:e.finalText};if(t.action==="abort"){let n=t.reason??"Stop hook requested continuation";e.log.info(`stop hook blocking: ${n}`);let o={role:"user",content:n};return{action:"continue",messages:[...e.messages,Pl(e.finalText,e.thinkingBlocks),o],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}}}return null}var Ol=5;function Ll(e){return e.inputTokens+e.outputTokens+(e.reasoningTokens??0)}function Nl(e,t){return{role:"assistant",content:e,...t.length>0&&{thinkingBlocks:[...t]}}}function ds(e){if(!e.tokenBudget||e.tokenBudget<=0||e.budgetContinuationCount>=Ol)return null;let t=Ll(e.totalUsage),n=t/e.tokenBudget*100,o=t-e.lastBudgetGlobalTokens;if(e.budgetContinuationCount>=rr&&o<pn&&e.lastBudgetDeltaTokens<pn)return e.log.info(`token budget early stop: diminishing returns at ${Math.round(n)}% (delta=${o})`),null;if(n>=90)return null;let s=e.budgetContinuationCount+1,i={role:"user",content:e.getBudgetContinuationMessage(n,t,e.tokenBudget)};return e.log.info(`token budget continuation #${s}: ${Math.round(n)}% used`),{messages:[...e.messages,Nl(e.finalText,e.thinkingBlocks),i],budgetContinuationCount:s,lastBudgetDeltaTokens:o,lastBudgetGlobalTokens:t,recoveryDetail:`${Math.round(n)}% used (#${s})`,transition:{reason:"token_budget_continuation"}}}function Qn(e){if(e.totalToolCallCount<=0)return null;let t={ok:!0,toolCallCount:e.totalToolCallCount,distinctToolCount:e.distinctToolNames.size,multiStep:e.totalToolCallCount>=2,hasSubAgent:!1,feedback:null,existingSkillName:null};return mn(t,{tools:[...e.distinctToolNames],projectRoot:e.projectRoot})}var Je="*";function fs(e,t){let n=[],o=[];for(let r of e){let s=hs(r.function.name,r.function.arguments),i=ys(r.function.name,Je),a=Math.max(t.get(s)??0,t.get(i)??0);a>=gt?o.push({call:r,failCount:a,error:`Tool "${r.function.name}" has failed ${a} times this turn for this target. The target likely does not exist. Stop trying variations of the same target and switch to a verified target or report the issue to the user.`}):n.push(r)}return{allowed:n,blocked:o}}function ps(){return{role:"user",content:"Tool calls were blocked because the tool has failed too many times with different arguments. The resource you are looking for does not exist. Stop trying variations and tell the user what happened."}}function ms(e){if(e.ok&&!e.softEmpty)return;let t=hs(e.toolName,e.toolArguments),n=e.toolFailureCounts.get(t)??0;e.toolFailureCounts.set(t,n+1)}function gs(e){let t=[];for(let[n,o]of e.toolFailureCounts)if(o>=gt&&(e.snapshot.get(n)??0)<gt){let{toolName:r,target:s}=Dl(n);t.push({role:"user",content:`Tool "${r}" has now failed/returned empty results ${o} times for target "${s}". That target clearly does not exist or is not useful. Do NOT retry variations of the same target. Report the result to the user immediately.`})}return t}function hs(e,t){return ys(e,Fl(e,t))}function Fl(e,t){let n=Bl(t);return e==="read"||e==="write"||e==="edit"||e==="patch"?eo(n?.path??n?.file_path??n?.filePath):e==="search"?eo([n?.mode,n?.path,n?.fileGlob,n?.pattern].filter(Boolean).join("|")):e==="exec"?eo(n?.command):Je}function Bl(e){if(e)try{let t=JSON.parse(e);return t&&typeof t=="object"&&!Array.isArray(t)?t:void 0}catch{return}}function eo(e){return typeof e=="string"&&e.trim()?e.trim().replaceAll("\\","/").toLowerCase():Je}function ys(e,t){return`${e}::${t}`}function Dl(e){let t=e.indexOf("::");return t<0?{toolName:e,target:Je}:{toolName:e.slice(0,t),target:e.slice(t+2)||Je}}var $l=new Set(["find","grep","rg","ag","ack","locate","which","whereis"]),Ul=new Set(["cat","head","tail","less","more","wc","stat","file","sed","strings","jq","awk","cut","sort","uniq","tr"]),jl=new Set(["ls","tree","du","dir","gci","get-childitem"]),ql=new Set(["grep","rg","ag","ack","find"]);var zl=new Set(["mv","cp","rm","mkdir","rmdir","chmod","chown","chgrp","touch","ln","cd","export","unset","wait"]);function Hl(e){let n=e.replace(/\\\n/g," ").trim().split(/[|;&]/).shift()?.trim()??"";if(!n)return null;let o=n.split(/\s+/),r=0;for(;r<o.length&&/^[A-Za-z_]\w*=/.test(o[r]);)r++;let s=/^(?:timeout|time|nice|nohup|stdbuf|command|builtin|exec)$/;for(;r<o.length;){let f=o[r];if(s.test(f)){for(r++;r<o.length&&/^[-+]/.test(o[r]);)r++;r<o.length&&/^\d+(?:\.\d+)?[smhd]?$/.test(o[r])&&r++;continue}break}if(r>=o.length)return null;let i=o[r],a=i.lastIndexOf("/");return(a>=0?i.slice(a+1):i).toLowerCase()}function Gl(e){return/(?:^|[;&|])\s*(?:cd|pushd|popd)\b/.test(e)}function bs(e){let t=Hl(e),n=t!==null&&$l.has(t),o=t!==null&&Ul.has(t),r=t!==null&&jl.has(t),s=t!==null&&zl.has(t),i=/(?:[^2]>|^>|\|>)/.test(e),a=Gl(e),u=(n||o||r)&&!i&&!a;return{firstCommand:t,isSearch:n,isRead:o,isList:r,isSilent:s,isConcurrencySafe:u,isReadOnly:u}}function Ts(e){return e.isRead?!0:e.firstCommand!==null&&ql.has(e.firstCommand)}function Cs(e){return e.isRead?"Command blocked: read local file contents with the read tool, not exec (cat/head/tail/sed/etc.). Reserve exec for system/build/test commands.":'Command blocked: search local file contents with the search tool (mode "content"), not exec (grep/find/rg/etc.). Reserve exec for system/build/test commands.'}function Xl(e,t){if(e.length!==1||e[0]?.function.name!=="stt")return!1;let n=[...t].reverse().find(i=>i.role==="user");if(!n)return!1;let o=Array.isArray(n.audioUrls)&&n.audioUrls.some(i=>typeof i=="string"&&i.trim()),r=typeof n.content=="string"?n.content:"",s=/\b(?:stt|speech[-\s]?to[-\s]?text|transcribe|transcription|audio[-\s]?to[-\s]?text)\b|转写|转录|语音转文字|音频转文字|听写/i.test(r);return o&&s}function Kl(e,t){let n=Yl(t);if(!n)return null;let o=Zl(n);if(!o)return null;let r=[...e].reverse().find(a=>a.role==="user"),s=typeof r?.content=="string"?r.content:"",i=/\bAUDIO_STT_RESULT\s+([^\s<]+)\s+<transcription\b/i.exec(s);return i?.[1]?`AUDIO_STT_RESULT ${i[1]} ${o}`:o}function Yl(e){let t=[e.details?.transcription,e.details?.text,e.details?.preview];for(let o of t)if(typeof o=="string"&&o.trim())return o.trim();let n=e.message?.content;return typeof n=="string"?n.trim():""}function Zl(e){return e.toLocaleLowerCase().replace(/[^\p{L}\p{N}\s]+/gu," ").replace(/\s+/g," ").trim()}function k(e){return[...new Set(e.map(t=>t.function.name))].sort()}function Mt(e){return[...e].sort((t,n)=>t.function.name.localeCompare(n.function.name))}function At(e){let t=new Set,n=[];for(let o of e){let r=`${o.name}\0${o.reason}`;t.has(r)||(t.add(r),n.push(o))}return n.sort((o,r)=>`${o.name}:${o.reason}`.localeCompare(`${r.name}:${r.reason}`))}function Jl(e,t,n,o,r){let s=r.filter(i=>i.name===e).sort((i,a)=>ks(i.reason)-ks(a.reason))[0];return t.includes(e)?s?`${e}=policy-filtered:${s.reason}`:n.includes(e)?o.includes(e)?`${e}=called`:`${e}=enabled-not-used`:`${e}=policy-filtered:not-enabled`:`${e}=not-exposed`}function ks(e){return e==="invalid-arguments"?0:e==="blocked-by-policy"||e.startsWith("policy-suppressed:")?1:e==="confirmation-timeout"?2:e==="dedicated-tool-required"?3:e==="read-only-context-pack"?4:e==="not-offered"?5:e==="read-cycle-policy"?6:e==="identical-repeat-policy"?7:e==="variant-failure-policy"?8:10}function Ql(e){let t=typeof e.blockReason=="string"?e.blockReason:void 0;if(e.blocked&&/confirmation timed out/i.test(t??""))return"confirmation-timeout";if(e.blocked)return"blocked-by-policy";let n=typeof e.details?.error=="string"?e.details.error:void 0;if(n==="dedicated_tool_required")return"dedicated-tool-required";if(n==="existing_file_update_tool_required")return"existing-file-update-tool-required";if(n==="invalid_arguments")return"invalid-arguments";if(n==="blocked_global_process_kill")return"global-process-kill-blocked";if(n==="blocked_by_guard")return"blocked-by-policy"}function Rs(e){let t=new Set(e.map(n=>n.function.name));return t.has("read")||t.has("search")||t.has("write")||t.has("edit")||t.has("patch")}function ye(e,t){return t.size===0?[...e]:e.filter(n=>!t.has(n.function.name))}var ec=new Set(["edit","patch","read"]);function xs(e,t){let n=e.filter(o=>ec.has(o.function.name)&&!t.has(o.function.name));return n.length>0?Mt(n):e.filter(o=>o.function.name!=="write"&&!t.has(o.function.name))}function to(e,t){let n=new Set(t);return e.filter(o=>!n.has(o))}function tc(e){if(!e)return;let t=e.trim();return(t.match(/Last error:\s*(.+?)\.\s*Do not retry\./s)?.[1]?.trim()??t).slice(0,600).trim()||void 0}function vs(e){let n=de(e)?.command;return typeof n=="string"&&n.trim()?n:void 0}var It=5174;function _s(e,t){let n=String(t);return[new RegExp(`(?:^|\\s)--port(?:=|\\s+)${n}(?:\\s|$)`),new RegExp(`(?:^|\\s)-p(?:=|\\s+)${n}(?:\\s|$)`),new RegExp(`(?:localhost|127\\.0\\.0\\.1|0\\.0\\.0\\.0|\\[?::1\\]?):${n}\\b`,"i")].some(r=>r.test(e))}function nc(e){return/\b(vite|npx\s+vite|pnpm\s+(?:run\s+)?dev|npm\s+(?:run\s+)?dev|yarn\s+(?:run\s+)?dev)\b/i.test(e)}function Ps(e){return/(?:^|\s)--strictPort(?:\s|$)/.test(e)}function oc(e){if(Ps(e))return e;let t=/\s+(?:\d?>&\d|\d?>\s*\S+|>\s*\S+|<\s*\S+).*$/.exec(e);return!t||t.index===void 0?`${e.trim()} --strictPort`:`${e.slice(0,t.index).trim()} --strictPort${e.slice(t.index)}`}function ws(e,t){let n=de(e)??{};return JSON.stringify({...n,command:t})}function rc(e){let t=e.replace(/^(?:\s*sleep\s+\d+(?:\.\d+)?\s*(?:&&|;)\s*)+/i,"").trim();return t&&t!==e.trim()?t:null}function sc(e){return _s(e,It)?{action:"block",error:"Command blocked: port 5174 is reserved for the Xiaozhi Claw frontend. Start generated apps on an explicit non-5174 port and include --strictPort when using Vite."}:nc(e)&&_s(e,It-1)&&!Ps(e)?{action:"rewrite",command:oc(e)}:null}function Pt(e){let t=[];for(let n of e.devServerUrls)if(!(!/^https?:\/\/(?:localhost|127\.0\.0\.1):\d+\b/i.test(n)||new RegExp(`:${It}\\b`).test(n)))try{let o=new URL(n);if(/^\/api(?:\/|$)/i.test(o.pathname))continue;let r=`${o.protocol}//${o.host}${o.pathname==="/"?"":o.pathname}`;t.includes(r)||t.push(r)}catch{continue}return t}function As(e){let t=Pt(e);return`Browser-visible acceptance is still missing. Do not finish from source inspection or web_fetch output. Use exec to run real browser automation (Playwright or an equivalent browser runner) against ${t.length>0?t.join(", "):"the generated localhost dev server URL"}. Do not run a plain \`node verify.js\` script that imports \`@playwright/test\` unless that package is installed in the target project. Prefer one of these reliable forms: (a) if \`node -e "require.resolve('playwright')"\` succeeds, run a plain Node script importing \`chromium\` from \`playwright\`; or (b) write a Playwright spec and run it with \`npx -y playwright@latest test <spec-file>\` instead of \`node <spec-file>\`. If a localhost URL responds, reuse that running service for browser verification; do not treat a later EADDRINUSE restart attempt as proof that the app is unavailable. Only switch to a new explicit non-5174 port when the observed localhost URL is unreachable or serves the wrong app. Verify rendered visible UI, app-specific routes/screens, and requested interactions; default HTML fetches, bundled JS inspection, and static source review do not count as browser evidence. After the browser automation succeeds, report the exact visible assertions from the tool result.`}function ic(e){let t=e.buildFailureEvidence[0];return"The test/build you ran is still FAILING, so the task is not complete. "+(t?`Last failing output:
|
|
30
29
|
${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 Os(e){let n=de(e)?.command;return typeof n=="string"&&n.trim()?n.trim():null}var
|
|
30
|
+
`:"")+"Do not finish or claim success from source inspection. Diagnose the failure, edit the source to fix the root cause, then RE-RUN the same test/build command via exec. Repeat until the command exits 0 (passes), then report the passing output. Do NOT modify, weaken, or delete the test/assertions to force a pass."}function Os(e){let n=de(e)?.command;return typeof n=="string"&&n.trim()?n.trim():null}var ac=4;function lc(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=Os(t);return n?`exec:${n.replace(/\s+/g," ")}`:null}return null}function Ss(e){let t=Os(e);return t?/\b(?:npx\s+)?playwright\s+install(?:\s+--with-deps)?\s+chromium\b/i.test(t):!1}function cc(e){let t=Pt(e);return`Browser automation prerequisites are already installed. Do not run \`playwright install\` again. Use exec to run an actual browser verification script against ${t.length>0?t.join(", "):"the generated localhost dev server URL"}: open the page with Playwright/Puppeteer, assert visible app-specific text and interactions, then report the visible assertions. If using Playwright from a plain node script, import \`chromium\` from \`playwright\` and do not use the \`test()\` API unless running through \`npx -y playwright@latest test <spec-file>\`. Do not execute a file that imports \`@playwright/test\` with plain \`node\`; that fails when the generated app did not install the test package.`}function uc(e){return[`Quick task-list status sync: the list still shows unresolved item(s): ${e.filter(n=>n.status!=="completed").map(n=>`#${n.id} ${n.title} (${n.status})`).join("; ")}.`,"If your final answer already shows these are done, just mark them completed with the task tool to match \u2014 this is a status sync, not a request to redo work.","Mark items completed only if the work is actually done and verified; otherwise mark them blocked/cancelled if the task tool supports that status, or keep them unresolved and report the blocker.","Do not produce a final completion claim until task status and the final answer agree."].join(" ")}function dc(e){let t=new Set(["completed","blocked","cancelled","canceled","failed"]);return e.some(n=>!t.has(n.status.toLowerCase()))}function fc(e){return e?Cs(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 Ms(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=>Jl(s,t.availableToolNames,t.enabledToolNames,t.toolCallNames,t.blockedToolCalls)).join(", ");return`${e}
|
|
32
31
|
|
|
33
32
|
Tool availability diagnostics:
|
|
34
33
|
availableToolNames: ${t.availableToolNames.join(", ")}
|
|
35
34
|
enabledToolNames: ${t.enabledToolNames.join(", ")}
|
|
36
35
|
toolCallNames: ${t.toolCallNames.join(", ")||"none"}
|
|
37
36
|
blockedToolCalls: ${n}
|
|
38
|
-
attribution: ${r}`}function ue(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function
|
|
39
|
-
`),i=
|
|
37
|
+
attribution: ${r}`}function ue(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function pc(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.${mc(e.function.name)}`}return null}function mc(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 Ee(e,t){if(!e||typeof e!="object")return;let n=e[t];return typeof n=="string"?n:void 0}function Et(e,t){if(!e||typeof e!="object")return;let n=e[t];return typeof n=="boolean"?n:void 0}function gc(e,t){if(!e||typeof e!="object")return;let n=e[t];return typeof n=="number"&&Number.isFinite(n)?n:void 0}function hc(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 yc(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 bc(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 Tc(e,t){if(e.toolName!=="task")return!1;let n=Ee(e.details,"taskId");return!n||!be(t).has(n)?!1:Ee(e.details,"action")==="output"&&Et(e.details,"running")===!0}var Cc=180,kc=40;function Rc(e){return/\(no output yet\)|\bno output yet\b/i.test(e)}function xc(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 vc(e){if(!e||typeof e!="object")return null;let t=e.taskList;if(!Array.isArray(t))return null;let n=[];for(let o of t){if(!o||typeof o!="object")continue;let r=o,s=r.id,i=r.title,a=r.status;typeof s!="number"||!Number.isFinite(s)||typeof i!="string"||!i.trim()||typeof a!="string"||!a.trim()||n.push({id:s,title:i,status:a})}return n}var oo=new Set(["read","search"]),_c=new Set(["write","edit","patch","image_generate"]),wc=18e4,Ac=3,Qe=1,Sc=1,Mc=1,Ec=4,Ic=2,Z=new Map([["requirements.md","requirements"],["decisions.md","decisions"],["defects.md","defects"],["acceptance.md","acceptance"]]),lo=new Set(["document-index.json","decision-state-table.json","context-pack-evidence.json"]),Ls=[{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}],ro=new Set(["write","edit","patch"]),Pc=new Set(["read","search","exec"]);function Ns(e){let t=H(e),n=Te(t);return t.split("/").includes("context-pack")&&Z.has(n)?Qe:t.split("/").includes("benchmark-state")&&lo.has(n)?Mc:t.includes("/qlogicagent-sessions/")&&t.includes("/tool-results/")?Sc:Ac}function no(e){let t=H(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")&&lo.has(Te(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 co(e){let t=H(e);return t.split("/").includes("context-pack")&&Z.has(Te(t))}function Fs(e){let t=H(e),o=t.indexOf("/context-pack/");return o<0?null:t.slice(0,o)}function Oc(e){let t=[...e].filter(co).map(Fs).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 Ie(o)}catch{return!1}})}function Bs(e){return[...Z.keys()].every(t=>e.has(t))}function uo(e){for(let t of e.values()){if(!t.path)continue;let n=Fs(t.path);if(n)return`${n}/benchmark-state`}return null}function Ds(e){if(!Bs(e))return[];let t=uo(e);return t?[...lo].map(n=>`${t}/${n}`).filter(n=>{try{return!Ie(n)}catch{return!0}}):[]}function Lc(e,t){let n=Ds(e);if(n.length===0)return null;let o=uo(e);if(!o)return null;let s=[...Z.keys()].map(a=>{let u=e.get(a);return`${a}: path=${u?.path??"unknown"}, contentHash=${u?.contentHash??"unknown"}, fileSizeBytes=${u?.fileSizeBytes??"unknown"}, recordCount=${u?.recordCount??"unknown"}, summary=${u?.summary??""}`}).join(`
|
|
38
|
+
`),i=Ls.map(a=>`${a.id}: ${a.decision}`).join(`
|
|
40
39
|
`);return["You have already read and indexed requirements.md, decisions.md, defects.md, and acceptance.md for this long-horizon benchmark.","Do not read context-pack, persisted tool-result previews, or compact benchmark-state files again in this turn.","Before any more analysis or final answer, maintain the benchmark state files using write/edit/patch only.",`Benchmark-state directory: ${o}.`,`Missing files: ${n.join(", ")}.`,"Create missing files with write. If any target already exists, update it with edit or patch instead of write.","For every contentHash and fileSizeBytes you write, copy the EXACT value from the 'Document evidence already available' section below. Do NOT compute, approximate, or invent a hash \u2014 you must not re-read the large read-only context-pack files to produce one.","The context-pack inputs (requirements.md, decisions.md, defects.md, acceptance.md) are READ-ONLY and immutable: their content and contentHash cannot change between turns. If a hash ever appears to differ from what you recorded, the source did NOT change \u2014 suspect your own recorded value first (stale, or never tool-derived). Never raise a 'source changed' blocker for these files.","Acceptance verdicts are monotonic unless re-derived from primary evidence: do NOT flip a previously-PASSing criterion to FAIL on a derived/secondary signal such as a hash diff. Change a PASS to FAIL only after re-checking the actual acceptance condition against primary evidence, and cite that evidence.","Required files:","- document-index.json: include contextPackPath and a documents object keyed by requirements.md, decisions.md, defects.md, acceptance.md with path, contentHash, fileSizeBytes, recordCount, indexVersion, summary, and lastReviewedTurn.","- decision-state-table.json: include D001-D006 with id, decision, status, evidence, and lastConfirmedTurn.","- context-pack-evidence.json: include turn and fileVerification for requirements.md, decisions.md, defects.md, acceptance.md with path, contentHash, and fileSizeBytes.",`Current turn: ${t}.`,"Document evidence already available:",s,"Decision records to preserve:",i].join(`
|
|
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.
|
|
40
|
+
`)}function Es(e){return ro.has(e)}function Nc(e){return e.benchmarkStateMaintenanceRequiredFiles.size>0&&[...e.benchmarkStateMaintenanceRequiredFiles].every(t=>Fc(e,t))}function Fc(e,t){if(e.benchmarkStateMaintenanceWrittenFiles.has(t))return!0;try{if(!Ie(t))return!1;let n=Te(t);if(n!=="document-index.json"&&n!=="context-pack-evidence.json")return!0;let o=Nt(t,"utf8");return fo(e.maintainedDocuments,t,JSON.stringify({content:o})).ok}catch{return!1}}function fo(e,t,n){let o=Te(t);if(o!=="document-index.json"&&o!=="context-pack-evidence.json")return{ok:!0};let r=Jc(n);if(!r)return{ok:!1,reason:`${o} write did not include JSON content`};let s=de(r);if(!s)return{ok:!1,reason:`${o} content is not a JSON object`};if(o==="document-index.json"){let a=ue(s.documents);if(!a)return{ok:!1,reason:"document-index.json missing documents object"};for(let u of Z.keys()){let f=e.get(u),h=ue(a[u]);if(!f||!h)return{ok:!1,reason:`document-index.json missing ${u}`};if(h.contentHash!==f.contentHash)return{ok:!1,reason:`document-index.json ${u} contentHash does not match read.details`};if(h.fileSizeBytes!==f.fileSizeBytes)return{ok:!1,reason:`document-index.json ${u} fileSizeBytes does not match read.details`}}return{ok:!0}}let i=ue(s.fileVerification);if(!i)return{ok:!1,reason:"context-pack-evidence.json missing fileVerification object"};for(let a of Z.keys()){let u=e.get(a),f=ue(i[a]);if(!u||!f)return{ok:!1,reason:`context-pack-evidence.json missing ${a}`};if(f.contentHash!==u.contentHash)return{ok:!1,reason:`context-pack-evidence.json ${a} contentHash does not match read.details`};if(f.fileSizeBytes!==u.fileSizeBytes)return{ok:!1,reason:`context-pack-evidence.json ${a} fileSizeBytes does not match read.details`}}return{ok:!0}}function Bc(e){if(!Bs(e))return[];let t=uo(e);if(!t)return[];let n=[];for(let o of["document-index.json","context-pack-evidence.json"]){let r=`${t}/${o}`,s;try{if(!Ie(r))continue;s=Nt(r,"utf8")}catch{continue}let i=fo(e,r,JSON.stringify({content:s}));i.ok||n.push({path:r,reason:i.reason})}return n}function Dc(e,t,n,o){if(e.filter(a=>a.name==="read"&&a.reason==="read-cycle-policy").length<Ec)return!1;let s=new Set([...t].filter(co).map(Te));return[...Z.keys()].every(a=>s.has(a))?[...Z.keys()].every(a=>o.has(a))||n||Oc(t):!1}function $s(e,t,n){if(e!=="write"||!n.has("edit")&&!n.has("patch"))return null;let o=Lt(t);if(!o)return null;try{if(!Ie(o))return null}catch{return null}return{path:o,error:`Existing file update blocked for "${o}". Use edit or patch for existing files so the event stream can distinguish file creation from incremental maintenance.`}}var Ot=class extends Error{constructor(n){super(`LLM stream idle timeout after ${n}ms without a chunk.`);this.timeoutMs=n;this.name="LLMStreamIdleTimeoutError"}timeoutMs;code="LLM_STREAM_TIMEOUT"};async function*$c(e,t){if(!Number.isFinite(t)||t<=0){yield*e;return}let n=e[Symbol.asyncIterator]();try{for(;;){let o,r=await Promise.race([n.next(),new Promise(s=>{o=setTimeout(()=>s("timeout"),t)})]);if(o&&clearTimeout(o),r==="timeout")throw new Ot(t);if(r.done)return;yield r.value}}finally{n.return?.().catch(()=>{})}}function so(e){try{let t=JSON.parse(e),n=t.file_path??t.path??t.filePath;return typeof n=="string"&&n.trim()?n:void 0}catch{return}}function Lt(e){try{let t=JSON.parse(e),n=t.file_path??t.path??t.filePath;return typeof n=="string"&&n.trim()?n:void 0}catch{return}}function Uc(e){return e.flatMap(t=>{if(jc(t.function.arguments))return[t];let n=qc(t.function.arguments);return n.length<2?[t]:n.map((o,r)=>({...t,id:`${t.id}__json_${r+1}`,function:{...t.function,arguments:JSON.stringify(o)}}))})}function jc(e){try{let t=JSON.parse(e);return!!t&&typeof t=="object"&&!Array.isArray(t)}catch{return!1}}function qc(e){let t=[],n=0,o=-1,r=!1,s=!1,i=0;for(let a=0;a<e.length;a+=1){let u=e[a];if(r){s?s=!1:u==="\\"?s=!0:u==='"'&&(r=!1);continue}if(u==='"'){r=!0;continue}if(u==="{"){if(n===0){if(e.slice(i,a).trim())return[];o=a}n+=1;continue}if(u!=="}"||(n-=1,n!==0||o<0))continue;let f=de(e.slice(o,a+1));if(!f)return[];t.push(f),i=a+1,o=-1}return n!==0||r||e.slice(i).trim()?[]:t}function de(e){try{let t=JSON.parse(e);return t&&typeof t=="object"&&!Array.isArray(t)?t:null}catch{return null}}function H(e){let t=e.trim().replace(/\\/g,"/");for(t=t.replace(/\/{2,}/g,"/");t.includes("/./");)t=t.replace(/\/\.\//g,"/");return t=t.replace(/\/\.$/,""),/^[a-z]:\//i.test(t)&&(t=t.toLowerCase()),t.replace(/\/$/,"")}function Te(e){let t=e.trim().replace(/\\/g,"/");return t.slice(t.lastIndexOf("/")+1).toLowerCase()}function po(e){return`sha256:${Vl("sha256").update(e).digest("hex")}`}function zc(e,t){let n=t.split(/\r?\n/).map(a=>a.trim()).filter(Boolean),o=n[0]??e,r=n.find(a=>/record\s+0*1\b/i.test(a)),s=r&&r!==o?`${o}; ${r}`:o,i=s.length>180?`${s.slice(0,177)}...`:s;return i.toLowerCase().includes(e.toLowerCase())?i:`${e}: ${i}`}function Hc(e){return Object.fromEntries([...e.entries()].sort(([t],[n])=>t.localeCompare(n)))}function Gc(e,t,n,o){let r=[...t.values()].sort((u,f)=>(u.name??"").localeCompare(f.name??""));if(r.length===0)return null;let s=r.map(u=>`${u.name??"document"}:${u.contentHash??"unknown"}`).join("|"),i=Ls.map(u=>({...u,evidence:`read:long-horizon-documents:${po(`${u.id}:${s}`)}`,lastConfirmedTurn:o})),a={strategy:"maintained-document-index",nextReadPolicy:"use maintained index before full document reread",budgetStatus:"within-budget",maxReadsPerDocument:Qe,observedReadsByPath:Hc(n)};return{type:"document_maintenance",turnId:e,checkpointId:`${e}-docs-${r.length}`,documents:r,decisionStateTable:i,readCycleFindings:[],readCycleGuard:a}}function Wc(e){let t=e.find(o=>o.path)?.path??"",n=t.lastIndexOf("/");return n>0?t.slice(0,n):t}function St(e,t){return e.get(t)??null}function Vc(e){let t=St(e,"requirements.md"),n=St(e,"decisions.md"),o=St(e,"defects.md"),r=St(e,"acceptance.md");if(!t||!n||!o||!r)return null;let s=[t,n,o,r];return{goal:`Maintain long-horizon project state from ${t.name}, ${n.name}, ${o.name}, and ${r.name}`,artifactRoot:Wc(s),decisions:[n.summary],defects:[o.summary],acceptanceCriteria:[r.summary],blockers:[],nextAction:"Continue from the maintained document index and read only explicitly missing sections"}}function Xc(e,t){let n=Vc(t);return n?[{type:"lifecycle",turnId:e,kind:"goal_reconstruction",reconstruction:n},{type:"lifecycle",turnId:e,kind:"memory_drift",status:"none",detail:"No memory drift detected against the maintained document index."}]:[]}function Kc(e,t,n,o,r){let s=io(t,n,o,r);if(!s)return!1;let i=s.name;return i?(e.maintainedDocuments.set(i,s),!0):!1}function io(e,t,n,o){let r=Te(e);if(!Z.has(r))return null;let s=eu(t)??t,i=Qc(o,"contentHash"),a=De(o??null,"fileSizeBytes"),u=i??po(s);return{name:r,path:H(e),indexed:!0,maintained:!0,indexVersion:u,contentHash:u,summary:zc(r,s),lastReviewedTurn:n,fileSizeBytes:a??Buffer.byteLength(s,"utf8"),recordCount:Us(s)}}function Yc(e,t){return $s(e.function.name,e.function.arguments,t)!==null}function Zc(e,t){let n=Lt(t.function.arguments);return`This exact write call to an existing file has been attempted ${e} times${n?` for "${n}"`:""}. Do not call write again for this existing file. Use edit or patch for the existing-file update, then continue verification.`}function Jc(e){let n=de(e)?.content;return typeof n=="string"?n:void 0}function Qc(e,t){let n=e?.[t];return typeof n=="string"&&n.trim()?n.trim():void 0}function Us(e){let t=e.split(/\r?\n/).map(n=>n.trim()).filter(Boolean).length;return Math.max(1,t)}function eu(e){if(!e.includes("<persisted-output>"))return null;let n=e.match(/Full output saved to:\s*(.+?)(?:\r?\n|$)/)?.[1]?.trim();if(!n)return null;try{return Ie(n)?Nt(n,"utf8"):null}catch{return null}}function tu(e){let t=new Map;for(let s of e)if(!(s.role!=="assistant"||!Array.isArray(s.tool_calls)))for(let i of s.tool_calls){if(i.function?.name!=="read"||typeof i.id!="string"||typeof i.function.arguments!="string")continue;let a=so(i.function.arguments);if(!a)continue;let u=H(a);Ns(u)===Qe&&t.set(i.id,{path:u})}let n=new Map,o=new Map,r=!1;for(let s of e){if(s.role!=="tool"||typeof s.tool_call_id!="string"||s.is_error===!0)continue;let i=t.get(s.tool_call_id);if(!i)continue;let a=typeof s.content=="string"?s.content:"";if(!a||/^Error:/i.test(a.trim()))continue;n.set(i.path,(n.get(i.path)??0)+1);let u=io(i.path,a,0);u?.name&&o.set(u.name,u)}for(let s of iu(e)){r=!0;for(let i of Z.keys()){let a=H(`${s}/${i}`);if(n.set(a,Math.max(n.get(a)??0,Qe)),!o.has(i)){let u=io(a,`${i} maintained by benchmark-state/document-index.json from prior conversation history.`,0);u?.name&&o.set(u.name,u)}}}for(let s of nu(e)){r=!0;for(let i of s.documents)!i.name||!i.path||(n.set(i.path,Math.max(n.get(i.path)??0,Qe)),o.set(i.name,i))}return{fileReadCounts:n,maintainedDocuments:o,persistedBenchmarkStateRecovered:r}}function nu(e){let t=[];for(let n of ou(e)){let o=Is(`${n}/document-index.json`),r=Is(`${n}/context-pack-evidence.json`),s=$e(o,"contextPackPath")??ru(r);if(!s)continue;let i=su(s,o,r);i.length===Z.size&&t.push({documents:i})}return t}function ou(e){let t=new Set;for(let n of e){if(typeof n.content!="string")continue;let r=n.content.replace(/\\/g,"/").matchAll(/([a-zA-Z]:\/[^\s"'`<>]*?\/benchmark-state)(?=\/|[\s.,;:)\]}]|$)/g);for(let s of r){let i=H(s[1]??"");i&&t.add(i)}}return[...t]}function Is(e){try{if(!Ie(e))return null;let t=JSON.parse(Nt(e,"utf8"));return t&&typeof t=="object"&&!Array.isArray(t)?t:null}catch{return null}}function $e(e,t){let n=e?.[t];return typeof n=="string"&&n.trim()?H(n):void 0}function ru(e){let t=e?.fileVerification;if(!(!t||typeof t!="object"||Array.isArray(t)))for(let n of Z.keys()){let o=t[n];if(!o||typeof o!="object"||Array.isArray(o))continue;let r=$e(o,"path");if(!r)continue;let s=`/${n}`;if(r.endsWith(s))return r.slice(0,-s.length)}}function su(e,t,n){let o=ue(t?.documents),r=ue(n?.fileVerification),s=[];for(let i of Z.keys()){let a=ue(o?.[i]),u=ue(r?.[i]);if(!a&&!u)return[];let f=$e(a,"path"),T=$e(u,"path")??(f?.includes("/context-pack/")?f:H(`${e}/${i}`)),R=$e(a,"contentHash")??$e(u,"contentHash")??po(`${i}:${T}`),x=typeof a?.summary=="string"&&a.summary.trim()?a.summary.trim():`${i} maintained by persisted benchmark-state/document-index.json.`;s.push({name:i,path:H(T),indexed:!0,maintained:!0,indexVersion:String(a?.indexVersion??R),contentHash:R,summary:x,lastReviewedTurn:ao(a,"lastReviewedTurn")??ao(n,"turn")??0,fileSizeBytes:De(a,"fileSizeBytes")??De(u,"fileSizeBytes")??De(u,"sizeBytes")??Buffer.byteLength(x,"utf8"),recordCount:De(a,"recordCount")??De(u,"recordCount")??Us(x)})}return s}function ao(e,t){let n=e?.[t];return typeof n=="number"&&Number.isFinite(n)?n:void 0}function De(e,t){let n=ao(e,t);return n&&n>0?n:void 0}function iu(e){let t=e.slice(0,Math.max(0,e.length-1)),n=new Set;for(let o of t){if(typeof o.content!="string")continue;let r=o.content.replace(/\\/g,"/").toLowerCase();if(!r.includes("benchmark-state/document-index")&&!r.includes("benchmark-state/context-pack-evidence")&&!r.includes("maintained document index"))continue;let s=r.matchAll(/([a-z]:\/[^\s"'`<>]*?\/context-pack)(?=\/|[\s.,;:)\]}]|$)/gi);for(let i of s){let a=H(i[1]??"");a&&n.add(a)}}return[...n]}function au(e){e.identicalSuccessfulToolResults.clear();for(let t of[...e.identicalCallCounts.keys()]){let n=t.slice(0,t.indexOf("::"));oo.has(n)&&e.identicalCallCounts.delete(t)}}async function*js(e,t,n,o){let{turnId:r,sessionId:s,messages:i,availableTools:a,tools:u,model:f,apiKey:h,temperature:T=0,hooks:R,signal:x}=e,w={sessionId:s,turnId:r},v=e.maxTurns??0,P=e.querySource,A=e.runtimePorts.resolveToolEligibility(u,e.toolEligibilityContext),L=A.eligibleTools,D=[];for(let m of A.blockedTools)D.push({name:m.toolName,reason:"blocked-by-policy"}),yield{type:"tool_blocked",turnId:r,callId:"",name:m.toolName,reason:"blocked-by-policy"};let j=jr(e.maxRounds,i),ne=qr(e.maxToolCalls,i),Ft=!(typeof e.maxRounds=="number"&&e.maxRounds>=1)&&!(typeof e.maxToolCalls=="number"&&e.maxToolCalls>=1),mo=Rt(i),Pe={contextWindowTokens:e.contextWindowTokens??Jo,responseBufferTokens:Qo,maxOutputTokens:e.maxOutputTokens??er,abortSignal:x,reactiveCompactEnabled:!0,outputEscalationEnabled:!0},N=new Set,F=0,Ue=0,je=0,et=0,go=new Map,K=new Set,b=ye(L,K),qe=!1,Bt=!1,Dt,$t=()=>k(b),Vs=Xl(L,i),Ut=!1,ho=0,yo=0,q=!1,tt=!1,jt=tu(i),c={messages:[...i],maxOutputTokensRecoveryCount:0,hasAttemptedReactiveCompact:!1,maxOutputTokensOverride:void 0,turnCount:1,transition:void 0,guardState:vn(Pe),reactiveCompactState:Mn(),toolLoopState:yt({maxRounds:j,replayMessages:[...i]}).state,consecutiveFailedRounds:0,finalText:"",totalUsage:{inputTokens:0,outputTokens:0},collapseStore:un(),currentModel:f,consecutive529Errors:0,consecutiveApiRetries:0,stopHookActive:void 0,lastResponseId:void 0,snipRemovedIds:new Set,contentReplacementState:e.runtimePorts.createContentReplacementState(),budgetContinuationCount:0,repeatedToolFailureRecoveryCount:0,lastBudgetDeltaTokens:0,lastBudgetGlobalTokens:0,identicalCallCounts:new Map,identicalSuccessfulToolResults:new Map,toolFailureCounts:new Map,fileReadCounts:jt.fileReadCounts,fileReadCycleBlockedPaths:new Set,fileReadCycleNudgedPaths:new Set,maintainedDocuments:jt.maintainedDocuments,persistedBenchmarkStateRecovered:jt.persistedBenchmarkStateRecovered,benchmarkStateMaintenanceRequiredFiles:new Set,benchmarkStateMaintenanceWrittenFiles:new Set,recoveryTrace:new Map,artifactContract:Mr(i),browserAcceptanceRecoveryCount:0,buildVerificationRecoveryCount:0,benchmarkStateIntegrityRecoveryCount:0,backgroundAgentTaskIds:new Set,backgroundAgentNoOutputPollCounts:new Map,stalledBackgroundAgentTasks:new Map,notOfferedToolRecoveryCount:0,existingFileUpdateRecoveryCount:0,taskListReconciliationCount:0,lastTaskList:[]},qt=Math.max(v*5,200),Xs=4,Ks=4,bo=0,To=new Map,zt,M=(m,z)=>{let fe=`${m}:${z??""}`,oe=(To.get(fe)??0)+1;if(To.set(fe,oe),m==="autocompact"){let U=c.recoveryTrace.get("autocompact")??0;if(oe>Xs||U>=Ks){let J=`Repeated context compression made no forward progress: ${z??"autocompact"}`;return zt=J,c.recoveryTrace.set("compression_loop_guard",(c.recoveryTrace.get("compression_loop_guard")??0)+1),{type:"recovery",turnId:r,action:"compression_loop_guard",detail:J}}}return c.recoveryTrace.set(m,(c.recoveryTrace.get(m)??0)+1),{type:"recovery",turnId:r,action:m,detail:z}},Ys=()=>({type:"tool_use_summary",turnId:r,availableToolNames:k(a??u),enabledToolNames:$t(),toolCallNames:[...N].sort(),blockedToolCalls:At(D)}),Zs=m=>Er({content:m,inputMessages:i,messages:c.messages,totalToolCallCount:F,distinctToolNames:N,artifactContract:c.artifactContract,blockedToolCalls:At(D),activeTasks:c.lastTaskList}),Js=m=>({type:"end",turnId:r,content:m,usage:c.totalUsage,model:c.currentModel,...c.recoveryTrace.size>0?{recoveryTrace:Object.fromEntries(c.recoveryTrace)}:{}});function*G(m){let z=Zs(m);Dn(c.artifactContract,z),Gt()&&(yield Ht()),yield Ys(),yield Js(z)}let Ht=()=>({type:"artifact_contract",turnId:r,...Bn(c.artifactContract,i)}),Gt=()=>{let m=Bn(c.artifactContract,i);return!!(m.requiresBrowserAcceptance||m.artifactRoot||m.writePaths.length>0||m.outOfRootWrites.length>0||m.devServerUrls.length>0||m.browserVerified)},nt=(m,z)=>c.finalText||jn(m,o),Qs=(m,z,fe)=>{let oe=Me({inputMessages:i,messages:z,reason:fe});return oe||m||jn(z,o)};for(;;){if(bo++,bo>qt){o.info(`hard iteration cap reached (${qt}), forcing completion`);let l=nt(c.messages,`hard iteration cap reached (${qt}) before completing the final status contract`);yield*G(l);return}let{messages:m,maxOutputTokensRecoveryCount:z,maxOutputTokensOverride:fe,turnCount:oe,guardState:U,reactiveCompactState:J,collapseStore:Wt}=c,{toolLoopState:Q}=c;if(e.refreshTools&&oe>1){let l=e.refreshTools(),d=ye(l,K);d!==b&&(b=d,o.debug(`tools refreshed: ${l.length} tools`))}if(Sn(U,Pe)){o.info(`turn aborted by guard at turn ${oe}`),yield{type:"error",turnId:r,error:"Turn aborted",code:"ABORTED",usage:c.totalUsage};return}let Ce=_n(U,Pe);if(Ce.level==="blocking"){Ce.reason==="prompt_too_long"&&Be(J)&&(J.attemptedThisTurn=!0,U.hasAttemptedReactiveCompact=!0,o.info(`token budget blocking (${Ce.reason}), reactive compact needed`),yield M("reactive_compact","token budget pre-check")),o.info(`token budget blocking (${Ce.reason}), ending tool loop`);break}Ce.level==="warning"&&o.info(`token budget warning: ${Ce.usagePercent}% used, ${Ce.remainingTokens} remaining`);let ot=yield*Xr({messages:m,contentReplacementState:c.contentReplacementState,snipRemovedIds:c.snipRemovedIds,collapseStore:Wt,guardState:U,guardConfig:Pe,runtimePorts:e.runtimePorts,hooks:R,hookCtx:w,sessionId:s,currentModel:c.currentModel,log:o,recovery:M,onAutocompact:()=>{c.hasAttemptedReactiveCompact=!1}});if(zt){yield*G(`${zt}. Stop compressing the same context repeatedly; continue from the maintained document index or report the incomplete state explicitly.`);return}let ei=q?"required":e.toolChoice==="required"&&Ut?"auto":e.toolChoice??"auto";q=!1;let Oe=hn({tools:b,toolChoice:ei}),Co=k(Oe.tools).join("\0"),ko=Dt!==void 0&&Dt!==Co;ko&&c.lastResponseId&&(yield M("stateless_retry","tool schema changed; replaying full history without previous_response_id"));let ti=tt||ko?void 0:c.lastResponseId;Dt=Co;let ze=yt({maxRounds:j,replayMessages:ot,lastStopReason:Q.lastStopReason,options:{stopReason:Q.lastStopReason}}),Ro=Oe.extraSystemPrompt?[{role:"system",content:Oe.extraSystemPrompt},...ze.state.replayMessages]:ze.state.replayMessages;Q=ze.state,ze.recoveryActions.length>0&&o.debug(`tool loop recovery: ${ze.recoveryActions.map(l=>l.detail??l.kind).join("; ")}`),o.debug(`turn ${oe}, messages: ${Ro.length}`),$(R,"turn.before_inference",{...w,model:c.currentModel},o);let Vt=!1,Xt=[],xo=new Map,vo="stop",ee,E=null,rt=!1,_o=!1,He=[],ae=[];try{let l=t.stream({model:c.currentModel,messages:Ro,...Oe.tools.length>0?{tools:Oe.tools,toolChoice:Oe.normalizedToolChoice??"auto"}:{},temperature:T,maxTokens:(fe??U.currentMaxOutputTokens)||void 0,streamRequired:e.streamRequired,previousResponseId:ti,reasoning:e.reasoning,promptCacheKey:e.promptCacheKey,promptCacheRetention:e.promptCacheRetention,serviceTier:e.serviceTier,openaiBuiltinTools:e.openaiBuiltinTools,maxToolCalls:e.maxToolCalls,parallelToolCalls:e.parallelToolCalls,textVerbosity:e.textVerbosity},h,x);for await(let d of $c(l,e.llmStreamIdleTimeoutMs??wc))switch(d.type){case"delta":Xt.push(d.text);break;case"tool_call_delta":Vt=!0,En(xo,d);break;case"reasoning_delta":He.push(d.text);break;case"reasoning_block_complete":d.signature&&ae.push({thinking:He.join(""),signature:d.signature}),He.length=0;break;case"usage":ee={inputTokens:d.promptTokens,outputTokens:d.completionTokens,reasoningTokens:d.reasoningTokens,cacheRead:d.cacheReadTokens,cacheWrite:d.cacheCreationTokens};break;case"response_id":tt||(c.lastResponseId=d.id);break;case"annotations":yield{type:"annotations",turnId:r,annotations:d.annotations};break;case"builtin_tool_status":yield{type:"heartbeat",turnId:r,message:`${d.toolType}: ${d.event}`};break;case"done":_o=!0,vo=d.finishReason;break}if(Vt||$(R,"turn.after_inference",{...w,model:c.currentModel},o),e.postSamplingHooks&&e.postSamplingHooks.length>0){let d=c.currentModel;for(let g of e.postSamplingHooks)try{g({messages:[...ot],model:d,sessionId:s})}catch{}}}catch(l){if(l instanceof Ot){$(R,"stop.failure",{sessionId:s,reason:l.code,error:l.message},o),yield{type:"error",turnId:r,error:l.message,code:l.code,usage:c.totalUsage};return}let d=yield*Kr(l,{state:c,guardState:U,fallbackModel:e.fallbackModel,signal:x,querySource:P,turnId:r,log:o,emitRecovery:M});if(d.kind==="return")return;if(d.kind==="continue"){c={...c,...d.patch};continue}E=d.streamError}if(!E&&!_o){let l="LLM stream closed before a terminal event; the response was likely truncated upstream.";$(R,"stop.failure",{sessionId:s,reason:"RETRYABLE_TRANSIENT",error:l},o),yield{type:"error",turnId:r,error:l,code:"RETRYABLE_TRANSIENT",usage:c.totalUsage};return}if(E&&$(R,"turn.after_inference",{...w,model:c.currentModel,response:{error:E.message}},o),E){if(!tt&&c.lastResponseId&&/previous_response_id not found/i.test(E.message)){let l=(c.consecutiveApiRetries??0)+1;if(l<=_e){o.info("previous_response_id not found \u2014 disabling response-id chaining, retrying statelessly"),yield M("stateless_retry","previous_response_id not found; replaying full history"),tt=!0,c={...c,lastResponseId:void 0,consecutiveApiRetries:l,transition:void 0};continue}}if(Gn(E))rt=!0,o.info(`withheld prompt_too_long error (status=${E.status})`);else if(Wn(E))rt=!0,o.info(`withheld media_size error (status=${E.status})`);else{let l=wn({status:E.status??500,message:E.message},U,Pe);if(l.action==="reactive_compact"&&Be(J)&&(J.attemptedThisTurn=!0,U.hasAttemptedReactiveCompact=!0,yield M("reactive_compact",`API ${E.status??500}: ${E.message}`)),l.action==="retry"){let g=(c.consecutiveApiRetries??0)+1;if(g>_e){o.info(`API retry limit reached (${_e}), aborting`);let y=Fe(E.status,E.message);yield{type:"error",turnId:r,error:E.message,code:y,usage:c.totalUsage};return}yield M("retry",l.reason),c={...c,consecutiveApiRetries:g,transition:void 0};continue}let d=Fe(E.status,E.message);$(R,"stop.failure",{sessionId:s,reason:d,error:E.message},o),yield{type:"error",turnId:r,error:E.message,code:d,usage:c.totalUsage};return}}ee&&(c.totalUsage.inputTokens+=ee.inputTokens,c.totalUsage.outputTokens+=ee.outputTokens,ee.reasoningTokens&&(c.totalUsage.reasoningTokens=(c.totalUsage.reasoningTokens??0)+ee.reasoningTokens),ee.cacheRead&&(c.totalUsage.cacheRead=(c.totalUsage.cacheRead??0)+ee.cacheRead),ee.cacheWrite&&(c.totalUsage.cacheWrite=(c.totalUsage.cacheWrite??0)+ee.cacheWrite)),ee?.inputTokens&&(U.promptTokens=ee.inputTokens);let st=Xt.join(""),te=[...xo.values()].map((l,d)=>({id:l.id||`tc_${r}_${d}`,type:"function",function:{name:l.name,arguments:l.arguments}}));if(te=Uc(te),te.length===0&&!Vt){if(st&&(c.finalText=st),e.toolChoice==="required"&&!Ut&&b.length>0&&ho<2){ho++;let C=b.map(O=>O.function.name).filter(Boolean).slice(0,8).join(", ");c={...c,messages:[...m,{role:"user",content:`You must call one available tool before answering. Available tools for this request: ${C}. Do not answer from memory, prior context, or guesses.`}],finalText:"",transition:{reason:"next_turn"}};continue}if(rt&&E&&Gn(E)){if(c.transition?.reason!=="collapse_drain_retry"){let C=fn(ot,Wt);if(C.committed>0){o.info(`collapse drain: committed ${C.committed} stages`),yield M("collapse_drain",`${C.committed} stages committed`),c={...c,messages:C.messages,transition:{reason:"collapse_drain_retry",committed:C.committed}};continue}}if(Be(J)){J.attemptedThisTurn=!0,U.hasAttemptedReactiveCompact=!0,o.info("withheld 413: reactive compact attempt"),yield M("reactive_compact","withheld prompt_too_long"),c={...c,hasAttemptedReactiveCompact:!0,transition:{reason:"reactive_compact_retry"}};continue}o.info("withheld 413: recovery exhausted, surfacing error"),$(R,"stop.failure",{sessionId:s,reason:"prompt_too_long",error:E.message},o),yield{type:"error",turnId:r,error:E.message,code:"PROMPT_TOO_LONG",usage:c.totalUsage};return}if(rt&&E&&Wn(E)){if(Be(J)){J.attemptedThisTurn=!0,U.hasAttemptedReactiveCompact=!0,o.info("withheld media error: reactive compact strip-retry"),yield M("reactive_compact","media error strip-retry"),c={...c,hasAttemptedReactiveCompact:!0,transition:{reason:"reactive_compact_retry"}};continue}o.info("withheld media error: recovery exhausted"),$(R,"stop.failure",{sessionId:s,reason:"media_error",error:E.message},o),yield{type:"error",turnId:r,error:E.message,code:"IMAGE_ERROR",usage:c.totalUsage};return}if(Gr(vo)){U.consecutiveTruncations+=1;let C=e.modelMaxOutputTokens??tr,O=An(U,Pe,C);if(O.shouldEscalate&&fe===void 0){U.currentMaxOutputTokens=O.newMax,o.info(`max_output_tokens escalate: ${O.newMax} tokens`),yield M("output_escalation",`${O.newMax} tokens`),c={...c,maxOutputTokensOverride:or,transition:{reason:"max_output_tokens_escalate"}};continue}if(z<nr){let I={role:"user",content:"Output token limit hit. Resume directly - no apology, no recap of what you were doing. Pick up mid-thought if that is where the cut happened. Break remaining work into smaller pieces."};o.info(`max_output_tokens recovery #${z+1}`),yield M("max_output_tokens_recovery",`attempt ${z+1}`),c={...c,messages:[...ot,I],maxOutputTokensRecoveryCount:z+1,maxOutputTokensOverride:void 0,transition:{reason:"max_output_tokens_recovery",attempt:z+1}};continue}o.info("max_output_tokens recovery exhausted, completing with partial content")}else U.consecutiveTruncations=0;Q=ht(Q,{replayMessages:m,lastStopReason:"completed"});let l=await us({hooks:R,sessionId:s,messages:m,finalText:c.finalText,thinkingBlocks:ae,log:o});if(l?.action==="end"){let C=Qs(l.content,m,"stop hook prevented continuation before completing the final status contract");yield*G(C);return}if(l?.action==="continue"){c={...c,messages:l.messages,stopHookActive:l.stopHookActive,transition:l.transition};continue}let d=ds({tokenBudget:e.tokenBudget,totalUsage:c.totalUsage,budgetContinuationCount:c.budgetContinuationCount,lastBudgetDeltaTokens:c.lastBudgetDeltaTokens,lastBudgetGlobalTokens:c.lastBudgetGlobalTokens,messages:m,finalText:c.finalText,thinkingBlocks:ae,getBudgetContinuationMessage:e.runtimePorts.getBudgetContinuationMessage,log:o});if(d){yield M("budget_continuation",d.recoveryDetail),c={...c,messages:d.messages,budgetContinuationCount:d.budgetContinuationCount,lastBudgetDeltaTokens:d.lastBudgetDeltaTokens,lastBudgetGlobalTokens:d.lastBudgetGlobalTokens,transition:d.transition};continue}if(c.finalText.trim()&&dc(c.lastTaskList)&&c.taskListReconciliationCount<1){let C=b.find(O=>O.function.name==="task")??(a??u).find(O=>O.function.name==="task");if(C){let O=uc(c.lastTaskList),I=k(b),ce=ye(L,K);b=ce.some(Ve=>Ve.function.name==="task")?ce:Mt([...ce,C]),c={...c,taskListReconciliationCount:c.taskListReconciliationCount+1,messages:[...m,{role:"assistant",content:c.finalText},{role:"user",content:O}],transition:{reason:"next_turn"}},q=!0,yield{type:"tool_selection_policy",turnId:r,policyId:"task_list_reconciliation_required",intent:"lifecycle_reconciliation",reason:"task-list-final-status-mismatch",availableToolNames:k(a??u),enabledToolNamesBefore:I,enabledToolNamesAfter:k(b),suppressedToolNames:[],nextAction:"reconcile-task-list-before-final"},yield M("task_list_reconciliation_required","nudging task-list status sync before the final response");continue}}if(se(i)&&!c.artifactContract.browserVerified&&Pt(c.artifactContract).length>0&&b.some(C=>C.function.name==="exec")&&c.browserAcceptanceRecoveryCount<4){let C=As(c.artifactContract);c={...c,browserAcceptanceRecoveryCount:c.browserAcceptanceRecoveryCount+1,messages:[...m,{role:"assistant",content:c.finalText},{role:"user",content:C}],transition:{reason:"next_turn"}},q=!0,yield M("browser_acceptance_required","forcing browser automation before app/frontend completion");continue}if((e.buildVerificationGate??!0)&&Ln(i)&&!c.artifactContract.buildVerified&&c.artifactContract.buildFailureEvidence.length>0&&b.some(C=>C.function.name==="exec")&&c.buildVerificationRecoveryCount<3){let C=ic(c.artifactContract);c={...c,buildVerificationRecoveryCount:c.buildVerificationRecoveryCount+1,messages:[...m,{role:"assistant",content:c.finalText},{role:"user",content:C}],transition:{reason:"next_turn"}},q=!0,yield M("build_verification_required","test/build still failing; forcing a fix+rerun before completion");continue}let g=Jn({inputMessages:i,messages:m,finalText:c.finalText,thinkingBlocks:ae,stopHookActive:c.stopHookActive,totalToolCallCount:F,distinctToolNames:N,log:o});if(g){if(c.stopHookActive&&c.finalText.trim()===""){let C=Me({inputMessages:i,messages:g.messages,reason:"stop hook produced an empty response after tool use"});if(C){yield*G(C);return}}c={...c,messages:g.messages,stopHookActive:g.stopHookActive,transition:g.transition};continue}if(F===0&&b.length>0&&e.toolChoice!=="none"&&yo<1&&Ur(st)){yo++,q=!0,yield M("intent_without_action","announced but did not act; forcing a tool call"),c={...c,messages:[...m,{role:"assistant",content:st},{role:"user",content:"You announced an action but did not take it. Carry it out NOW, in this response: call the appropriate tool to actually do what you just said you would do. Do not restate your intention or describe a plan \u2014 perform it."}],finalText:"",transition:{reason:"next_turn"}};continue}let y=Qn({totalToolCallCount:F,distinctToolNames:N,projectRoot:e.projectRoot});y&&(yield{type:"skill_instruction",turnId:r,instruction:y});let p=nt(m,"the model ended with an empty response after tool use before completing the final status contract");for(let C of Xt)yield{type:"delta",turnId:r,text:C};yield*G(p);return}let ni=ae.length===0&&He.length>0?He.join(""):void 0;m.push(sn(te,void 0,ae.length>0?ae:void 0,ni)),Q=kn(Q,{replayMessages:m,pendingToolCallIds:te.map(l=>l.id),completedToolCallIds:Q.completedToolCallIds,lastStopReason:"tool_calls"});let it=c.identicalCallCounts,Ge=[],le=[],We=[],wo=!1;for(let l of te){if(bc(l,c)){Ge.push(l);continue}let d=`${l.function.name}::${l.function.arguments}`,g=it.get(d)??0;if(it.set(d,g+1),g+1>Zo){let y=oo.has(l.function.name)||l.function.name==="exec"?c.identicalSuccessfulToolResults.get(d):void 0;if(y){We.push({call:l,result:y,repeatCount:g+1});continue}le.push(l),wo||(wo=!0,o.info(`AP4 blocked: ${l.function.name} repeated ${g+1}x`))}else Ge.push(l)}let W=[],oi=new Set(b.map(l=>l.function.name)),Ao=new Set(le.filter(l=>Yc(l,oi)).map(l=>l.id));for(let l of We){let d=l.call,g=`Reused previous successful ${d.function.name} result for identical arguments (attempt ${l.repeatCount}); no additional tool execution was performed.
|
|
42
41
|
|
|
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
|
-
${
|
|
42
|
+
${l.result.content}`,y=V(d.id,{ok:!0,payload:g,imageUrls:l.result.imageUrls,toolReferences:l.result.toolReferences});m.push(y),W.push(d.id),N.add(d.function.name),F++,yield{type:"tool_result",turnId:r,callId:d.id,name:d.function.name,ok:!0,outputPreview:g.slice(0,2e3),durationMs:0,details:{type:d.function.name,reusedIdenticalCall:!0,repeatCount:l.repeatCount}}}if(We.some(l=>l.call.function.name==="exec"&&Ss(l.call.function.arguments))){let l=k(b);m.push({role:"user",content:cc(c.artifactContract)}),yield{type:"tool_selection_policy",turnId:r,policyId:"browser_verification_after_preparation_required",intent:"verification",reason:"repeated-browser-preparation-command",availableToolNames:k(a??u),enabledToolNamesBefore:l,enabledToolNamesAfter:l,suppressedToolNames:[],nextAction:"run-browser-verification-script-not-playwright-install"},yield M("browser_verification_after_preparation_required","reused successful browser preparation command")}for(let l of le){D.push({name:l.function.name,reason:"identical-repeat-policy"});let d=it.get(`${l.function.name}::${l.function.arguments}`),g=kt(m,l.function.name),y=tc(g),p=Ao.has(l.id)?Zc(d,l):y?`This exact tool call has been attempted ${d} times. Last error: ${y}. Do not retry. Report this error to the user.`:`This exact tool call has been attempted ${d} times and keeps failing. Do not retry it. Report the issue to the user or try a completely different approach.`,C=V(l.id,{ok:!1,error:p});m.push(C),W.push(l.id),N.add(l.function.name),F++,yield{type:"tool_result",turnId:r,callId:l.id,name:l.function.name,ok:!1,error:p}}if(le.length>0&&Ge.length===0&&We.length===0&&le.every(l=>Ao.has(l.id))&&c.existingFileUpdateRecoveryCount<2){let l=k(b);b=xs(L,K);let d=k(b);qe=!0,q=!0;let g=[...new Set(le.map(y=>Lt(y.function.arguments)).filter(y=>!!y))];m.push({role:"user",content:`Existing-file maintenance recovery: the same write call was repeatedly attempted for an existing file. Do not use write for these existing path(s): ${g.join(", ")||"(unknown)"}. Do not delete, remove, or recreate an existing file to make write succeed; that is artifact path drift, not maintenance. Use read only if you need the current contents, then use edit or patch for the smallest valid change. After the edit/patch succeeds, continue build/browser verification normally.`}),yield{type:"tool_selection_policy",turnId:r,policyId:"existing_file_update_recovery",intent:"tool_recovery",reason:"repeated-existing-file-write",availableToolNames:k(a??u),enabledToolNamesBefore:l,enabledToolNamesAfter:d,suppressedToolNames:to(l,d),nextAction:"use-read-edit-or-patch-for-existing-file-update"},yield M("existing_file_update_recovery",g.join(",")||"unknown"),c={...c,messages:m,existingFileUpdateRecoveryCount:c.existingFileUpdateRecoveryCount+1,transition:{reason:"next_turn"}};continue}if(le.length>0){let l=kt(m,le[0].function.name),d={role:"user",content:"Tool calls were blocked because you repeated them with identical arguments too many times. "+(l?`The error was: "${l}". Tell the user about this error. `:"The operation is not working. ")+"Stop retrying and report the result to the user."};m.push(d)}let ri=mo>=3&&c.repeatedToolFailureRecoveryCount<1;if(le.length>0&&Ge.length===0&&We.length===0&&!ri){let l=Ms(qn(m,1),{availableToolNames:k(a??u),enabledToolNames:$t(),toolCallNames:[...N].sort(),blockedToolCalls:At(D)});yield*G(l);return}let So=[],Kt=[];for(let l of Ge){let d=Ar({toolName:l.function.name,rawArguments:l.function.arguments});d?Kt.push({call:l,...d}):So.push(l)}for(let l of Kt){let d=l.call;D.push({name:d.function.name,reason:"read-only-context-pack"}),m.push(V(d.id,{ok:!1,error:l.error})),W.push(d.id),N.add(d.function.name),F++,yield{type:"tool_result",turnId:r,callId:d.id,name:d.function.name,ok:!1,error:l.error},o.warn(`read-only context-pack blocked: ${d.function.name} ${l.path}`)}Kt.length>0&&m.push({role:"user",content:"A write was blocked because context-pack is read-only evidence. Continue by writing compact indexes, checkpoints, and maintenance updates under benchmark-state; do not retry writes into context-pack."});let si=new Set(b.map(l=>l.function.name)),Mo=[],at=[];for(let l of So){let d=$s(l.function.name,l.function.arguments,si);d?at.push({call:l,...d}):Mo.push(l)}for(let l of at){let d=l.call;D.push({name:d.function.name,reason:"existing-file-update-tool-required"}),m.push(V(d.id,{ok:!1,error:l.error})),W.push(d.id),N.add(d.function.name),F++,yield{type:"tool_result",turnId:r,callId:d.id,name:d.function.name,ok:!1,error:l.error},o.info(`existing file update blocked: ${d.function.name} ${l.path}`)}if(at.length>0){let l=k(b);b=xs(L,K);let d=k(b);qe=!0,q=!0;let g=[...new Set(at.map(y=>y.path))];m.push({role:"user",content:`Existing-file maintenance recovery: a write was blocked because the target file already exists and edit/patch are enabled. Do not use write for these existing path(s): ${g.join(", ")||"(unknown)"}. Do not delete, remove, or recreate an existing file to make write succeed; that is artifact path drift, not maintenance. Use read only if you need the current contents, then use edit or patch for the smallest valid change. After the edit/patch succeeds, continue build/browser verification normally.`}),yield{type:"tool_selection_policy",turnId:r,policyId:"existing_file_update_recovery",intent:"tool_recovery",reason:"existing-file-write-blocked",availableToolNames:k(a??u),enabledToolNamesBefore:l,enabledToolNamesAfter:d,suppressedToolNames:to(l,d),nextAction:"use-read-edit-or-patch-for-existing-file-update"},yield M("existing_file_update_recovery",g.join(",")||"unknown"),c={...c,messages:m,existingFileUpdateRecoveryCount:c.existingFileUpdateRecoveryCount+1,transition:{reason:"next_turn"}};continue}let Eo=[],Yt=[];for(let l of Mo){let d=wr({state:c.artifactContract,inputMessages:i,toolName:l.function.name,rawArguments:l.function.arguments});d?Yt.push({call:l,...d}):Eo.push(l)}for(let l of Yt){let d=l.call;D.push({name:d.function.name,reason:"artifact-root-contract"}),Fn(c.artifactContract,{path:l.path,artifactRoot:l.artifactRoot,toolName:d.function.name}),m.push(V(d.id,{ok:!1,error:l.error})),W.push(d.id),N.add(d.function.name),F++,yield{type:"tool_result",turnId:r,callId:d.id,name:d.function.name,ok:!1,error:l.error},Gt()&&(yield Ht()),o.warn(`artifact root contract blocked: ${d.function.name}`)}Yt.length>0&&m.push({role:"user",content:"A write was blocked by the artifactRoot contract. Continue inside the declared artifactRoot, or stop with an honest final status that lists the root drift as Not done."});let Io=[],Zt=[];for(let l of Eo){let d=ls({inputMessages:i,messages:m,toolCall:l});d?Zt.push({call:l,error:d}):Io.push(l)}for(let l of Zt){let d=l.call;D.push({name:d.function.name,reason:"premature-completion-artifact"}),m.push(V(d.id,{ok:!1,error:l.error})),W.push(d.id),N.add(d.function.name),F++,yield{type:"tool_result",turnId:r,callId:d.id,name:d.function.name,ok:!1,error:l.error},o.info(`premature completion artifact blocked: ${d.function.name}`)}Zt.length>0&&m.push({role:"user",content:"A tool attempted to write a completion artifact before all explicitly requested output files had evidence. Do not write final DONE markers or success reports into artifacts until the missing files are created or verified. If you cannot complete them, respond with the requested FAIL marker and the real reason."});let ii=new Set(b.map(l=>l.function.name)),Po=[],lt=[];for(let l of Io)ii.has(l.function.name)?Po.push(l):lt.push(l);for(let l of lt){let d=`Tool "${l.function.name}" was not offered for this turn and will not be executed. Use only the tools listed in the current request.`;D.push({name:l.function.name,reason:"not-offered"}),m.push(V(l.id,{ok:!1,error:d})),W.push(l.id),N.add(l.function.name),o.warn(`unoffered tool call suppressed: ${l.function.name}`)}if(lt.length>0&&c.notOfferedToolRecoveryCount<1){let l=[...new Set(lt.map(C=>C.function.name))].sort(),d=qe&&l.includes("write"),g=l.filter(C=>K.has(C)),p=(a??u).filter(C=>l.includes(C.function.name));if(g.length>0)c.notOfferedToolRecoveryCount+=1,q=!0,m.push({role:"user",content:`You retried ${g.map(C=>`\`${C}\``).join(", ")} after it was disabled by this turn's tool-selection policy. Do not retry policy-suppressed tools in this turn. Continue using only the currently enabled tools, or stop with a clear blocker.`}),yield{type:"tool_selection_policy",turnId:r,policyId:"policy_suppressed_tool_retry_blocked",intent:"tool_recovery",reason:"requested-tool-disabled-by-turn-policy",availableToolNames:k(a??u),enabledToolNamesBefore:k(b),enabledToolNamesAfter:k(b),suppressedToolNames:g,nextAction:"continue-with-currently-enabled-tools-or-report-blocker"},yield M("policy_suppressed_tool_retry_blocked",g.join(","));else if(!d&&p.length>0){let C=k(b),O=new Map(b.map(I=>[I.function.name,I]));for(let I of p)O.set(I.function.name,I);b=Mt([...O.values()]),c.notOfferedToolRecoveryCount+=1,q=!0,yield{type:"tool_selection_policy",turnId:r,policyId:"available_tool_reenabled_after_not_offered_call",intent:"tool_recovery",reason:"requested-tool-available-but-disabled",availableToolNames:k(a??u),enabledToolNamesBefore:C,enabledToolNamesAfter:k(b),suppressedToolNames:[],nextAction:"retry-with-reenabled-requested-tool"},m.push({role:"user",content:`You called ${l.map(I=>`\`${I}\``).join(", ")} but it was not enabled for that round even though it is available. The requested available tool has now been re-enabled. Use the re-enabled tool once with valid arguments; do not repeat a disabled-tool call.`}),yield M("available_tool_reenabled_after_not_offered_call",l.join(","))}}let Oo=[],Jt=[];for(let l of Po){let d=b.find(y=>y.function.name===l.function.name),g=pc(d,l.function.arguments);g?Jt.push({call:l,error:g}):Oo.push(l)}for(let l of Jt){let d=l.call;D.push({name:d.function.name,reason:"invalid-arguments"}),c.toolFailureCounts,d.function.name,m.push(V(d.id,{ok:!1,error:l.error})),W.push(d.id),N.add(d.function.name),F++,yield{type:"tool_result",turnId:r,callId:d.id,name:d.function.name,ok:!1,error:l.error,details:{type:d.function.name,error:"invalid_arguments"}},o.info(`invalid tool arguments blocked: ${d.function.name}`)}Jt.length>0&&m.push({role:"user",content:"Some tool calls were blocked before execution because they did not match the tool schema. Do not retry the same tool with substituted fields. Use the required field names exactly, switch to the correct tool, or stop and report the invalid tool input."});let ct=[],Qt=[];for(let l of Oo){if(l.function.name!=="exec"){ct.push(l);continue}let d=vs(l.function.arguments);if(!d){ct.push(l);continue}let g=bs(d);Ts(g)&&Rs(L)?Qt.push({call:l,error:fc(g)}):ct.push(l)}for(let l of Qt){let d=l.call;D.push({name:d.function.name,reason:"dedicated-tool-required"});let g=k(b),y=b.filter(p=>["read","search"].includes(p.function.name));y.length>0&&(b=y,Bt=!0,q=!0),m.push(V(d.id,{ok:!1,error:l.error})),W.push(d.id),N.add(d.function.name),F++,yield{type:"tool_result",turnId:r,callId:d.id,name:d.function.name,ok:!1,error:l.error,details:{type:d.function.name,error:"dedicated_tool_required",dedicatedTool:"read/search"}},o.info(`dedicated file tool preflight blocked: ${d.function.name}`),yield{type:"tool_selection_policy",turnId:r,policyId:"dedicated_file_tool_required",intent:"fresh_evidence",reason:"exec-file-read-search-list-blocked",availableToolNames:k(a??u),enabledToolNamesBefore:g,enabledToolNamesAfter:k(b),suppressedToolNames:g.filter(p=>!["read","search"].includes(p)),nextAction:"use-read-search-for-file-inspection-then-resume-build-run-verify-tools"}}Qt.length>0&&m.push({role:"user",content:"Exec was blocked because it attempted local file reading/searching/listing. Use read/search for the next local file inspection step. After that, resume exec only for non-inspection commands such as installs, builds, dev servers, and verification scripts."});let ut=[],en=[],Lo=[],No=[];for(let l of ct){if(l.function.name!=="exec"){ut.push(l);continue}let d=l,g=vs(d.function.arguments),y=g?rc(g):null;y&&(d={...d,function:{...d.function,arguments:ws(d.function.arguments,y)}},No.push({originalCommand:g??"",rewrittenCommand:y}),g=y);let p=g?sc(g):null;if(p?.action==="block")en.push({call:d,error:p.error});else if(p?.action==="rewrite"){let C={...d,function:{...d.function,arguments:ws(d.function.arguments,p.command)}};Lo.push({call:C,originalCommand:g??"",rewrittenCommand:p.command}),ut.push(C)}else ut.push(d)}for(let l of No)yield{type:"tool_selection_policy",turnId:r,policyId:"exec_sleep_prefix_guard",intent:"verification",reason:"sleep-prefix-removed",availableToolNames:k(a??u),enabledToolNamesBefore:k(b),enabledToolNamesAfter:k(b),suppressedToolNames:[],nextAction:"execute-command-without-blocking-sleep-prefix"},o.info(`blocking sleep prefix removed before exec: ${l.originalCommand} -> ${l.rewrittenCommand}`);for(let l of Lo){let d=k(b);yield{type:"tool_selection_policy",turnId:r,policyId:"reserved_frontend_port_guard",intent:"verification",reason:"vite-strict-port-normalized",availableToolNames:k(a??u),enabledToolNamesBefore:d,enabledToolNamesAfter:k(b),suppressedToolNames:[],nextAction:"execute-normalized-vite-dev-server-command-with-strict-port"},o.info(`vite strict port normalized before exec: ${l.originalCommand} -> ${l.rewrittenCommand}`)}for(let l of en){let d=l.call;D.push({name:d.function.name,reason:"reserved-frontend-port"});let g=k(b);m.push(V(d.id,{ok:!1,error:l.error})),W.push(d.id),N.add(d.function.name),F++,yield{type:"tool_result",turnId:r,callId:d.id,name:d.function.name,ok:!1,error:l.error,details:{type:d.function.name,error:"reserved_frontend_port",reservedPort:It}},o.info(`reserved frontend port preflight blocked: ${d.function.name}`),yield{type:"tool_selection_policy",turnId:r,policyId:"reserved_frontend_port_guard",intent:"verification",reason:"reserved-frontend-port",availableToolNames:k(a??u),enabledToolNamesBefore:g,enabledToolNamesAfter:k(b),suppressedToolNames:[],nextAction:"restart-generated-dev-server-on-explicit-non-5174-port-with-strict-port"}}en.length>0&&m.push({role:"user",content:"A dev server command was blocked because it could occupy or fallback onto port 5174, which is reserved for the Xiaozhi Claw frontend. Retry with an explicit generated-app port other than 5174 and use --strictPort for Vite so browser evidence cannot be polluted."});let dt=[],Le=[];for(let l of ut){if(l.function.name!=="read"){dt.push(l);continue}let d=so(l.function.arguments);if(!d){dt.push(l);continue}let g=H(d),y=Ns(g);(c.fileReadCounts.get(g)??0)>=y?Le.push({call:l,filePath:g,maxReads:y}):dt.push(l)}for(let l of Le){let d=l.call,g=`Read cycle policy blocked another read of "${l.filePath}" after ${l.maxReads} successful reads in this turn. Stop rereading the same large document. ${no(l.filePath)}`;D.push({name:d.function.name,reason:"read-cycle-policy"}),c.fileReadCycleBlockedPaths.add(l.filePath),m.push(V(d.id,{ok:!1,error:g})),W.push(d.id),N.add(d.function.name),F++,yield{type:"tool_result",turnId:r,callId:d.id,name:d.function.name,ok:!1,error:g},o.info(`read cycle blocked: ${l.filePath}`)}if(Le.length>0){let l=[...new Set(Le.map(y=>`${y.filePath} (max ${y.maxReads})`))].join(", "),d=[...new Set(Le.map(y=>no(y.filePath)))].join(" ");if(m.push({role:"user",content:`Further reads were blocked because these large/context documents already reached their per-turn read limit: ${l}. Do not retry the read with a different path spelling. ${d} Continue from maintained requirements/defects/decisions/acceptance evidence and report any truly missing section explicitly.`}),b.some(y=>Es(y.function.name))&&(c.persistedBenchmarkStateRecovered||Le.some(y=>co(y.filePath)))){let y=k(b),p=y.filter(C=>Pc.has(C)).sort();yield{type:"tool_selection_policy",turnId:r,policyId:"long_horizon_benchmark_state_maintenance",intent:"benchmark_state_maintenance",reason:"read-cycle-guard-retains-evidence-tools",availableToolNames:k(a??u),enabledToolNamesBefore:y,enabledToolNamesAfter:k(b),suppressedToolNames:[],nextAction:"maintenance-or-final-answer"},m.push({role:"user",content:`Do not reread the blocked large/context document paths again. Evidence tools still enabled: ${p.join(", ")||"none"}. Use read/search only for targeted verification of generated artifacts, file names, and missing sections; use edit/patch/write only if benchmark-state maintenance needs an update; otherwise stop tool use and answer from the maintained benchmark-state evidence. Classify any unused edit/patch/write tools as not needed, not missing.`}),yield M("benchmark_state_maintenance_tool_bias","retaining targeted evidence tools after long-horizon read-cycle guard")}if(Dc(D,c.fileReadCycleBlockedPaths,c.persistedBenchmarkStateRecovered,c.maintainedDocuments)){yield*G("Stopped repeated long-horizon context-pack rereads after the read-cycle guard blocked every maintained source document. Continue from benchmark-state/document-index.json, decision-state-table.json, and context-pack-evidence.json; do not reread or rewrite context-pack source documents.");return}}let tn=fs(dt,c.toolFailureCounts),nn=tn.allowed;if(Ft&&nn.length>Math.max(0,ne-F)){let l=Hn({currentToolBudget:ne,currentRoundBudget:j,toolHardCap:100,roundHardCap:100,continuationCount:je,successfulSinceLastCheck:Ue-et,fileReadCounts:c.fileReadCounts,windowTools:ge,windowRounds:25});l&&(ne=l.nextToolBudget,j=l.nextRoundBudget,je=l.continuationCount,et=Ue,o.info(`tool budget continuation #${l.continuationCount}: tools\u2192${ne}, rounds\u2192${j} (progress detected)`))}let Fo=Math.max(0,ne-F),pe=Fo>0?nn.slice(0,Fo):[],on=nn.slice(pe.length),ai=on.length>0;if(tn.blocked.length>0){for(let l of tn.blocked){let d=l.call;D.push({name:d.function.name,reason:"variant-failure-policy"});let g=V(d.id,{ok:!1,error:l.error});m.push(g),W.push(d.id),N.add(d.function.name),F++,yield{type:"tool_result",turnId:r,callId:d.id,name:d.function.name,ok:!1,error:l.error},o.info(`variant tool blocked: ${d.function.name} failed ${l.failCount}x with different args`)}m.push(ps())}if(on.length>0){let l=`Tool call budget exhausted (${ne}) for this turn. Stop requesting more tools and report what remains incomplete.`;for(let d of on){D.push({name:d.function.name,reason:"tool-call-budget"});let g=V(d.id,{ok:!1,error:l});m.push(g),W.push(d.id),N.add(d.function.name),F++,yield{type:"tool_result",turnId:r,callId:d.id,name:d.function.name,ok:!1,error:l}}m.push({role:"user",content:`${l} You reached this turn's tool budget after ${je} extension(s). Do NOT claim the task is complete or that all files were created if it is not. Be honest in your reply: (1) state plainly the turn stopped before finishing; (2) list concretely what is DONE vs what is still UNFINISHED; (3) tell the user to reply "\u7EE7\u7EED" to finish the rest. If explicitly requested output files are still missing, respond with the requested FAIL marker and the real reason.`})}for(let l of pe){let d=l.function.arguments,g=b.find(y=>y.function.name===l.function.name);if(g?.backfillObservableInput)try{let y=JSON.parse(l.function.arguments),p={...y};g.backfillObservableInput(p),Object.keys(p).some(O=>!(O in y))&&(d=JSON.stringify(p))}catch{}yield{type:"tool_call",turnId:r,callId:l.id,name:l.function.name,arguments:d,inputSummary:zn(d)}}let li=new Map(c.toolFailureCounts),ft=null;try{let l=e.runtimePorts.createStreamingToolExecutor({toolInvoker:n,hooks:R,sessionId:s,turnId:r,log:o,signal:x,maxConcurrentTools:e?.maxConcurrentTools,maxExecutionMs:Ko});for(let p of pe)l.addTool(p);let d=!1;for await(let p of l.getRemainingResults()){let C=Ql(p);if(C){if(D.push({name:p.toolName,reason:C}),p.toolName==="exec"&&C==="dedicated-tool-required"&&Rs(L)){let _=k(b);m.push({role:"user",content:"Exec was blocked because it attempted local file reading/searching/listing. Use read/search for local file inspection. Exec remains available only for non-inspection commands such as installs, builds, dev servers, and verification scripts."}),yield{type:"tool_selection_policy",turnId:r,policyId:"dedicated_file_tool_required",intent:"fresh_evidence",reason:"exec-file-read-search-list-blocked",availableToolNames:k(a??u),enabledToolNamesBefore:_,enabledToolNamesAfter:k(b),suppressedToolNames:[],nextAction:"use-read-search-for-file-inspection-or-exec-for-build-run-verify"}}if(p.toolName==="exec"&&C==="confirmation-timeout"){let _=k(b);K.add("exec");let S=ye(L,K);S.length>0&&(b=Mt(S),q=!0),m.push({role:"user",content:"Exec confirmation timed out, so exec is disabled for the rest of this turn. Do not retry exec. Use read/search for inspection, edit/patch/write for file updates, ask_user only for missing user input, or stop with a clear blocker if no non-exec tool can complete the request."}),yield{type:"tool_selection_policy",turnId:r,policyId:"exec_confirmation_timeout_recovery",intent:"tool_recovery",reason:"exec-confirmation-timeout",availableToolNames:k(a??u),enabledToolNamesBefore:_,enabledToolNamesAfter:k(b),suppressedToolNames:to(_,k(b)),nextAction:"continue-with-non-exec-tools-or-report-confirmation-blocker"}}if(p.toolName==="exec"&&C==="global-process-kill-blocked"){let _=k(b);m.push({role:"user",content:"Exec was blocked because it attempted to terminate every node process. Do not retry taskkill/killall/pkill/Stop-Process by process name. If a generated app server conflicts with another process, start the generated app on a new explicit non-5174 port with strict port behavior, or stop only an owned background task by its task id. Continue by verifying the app on the reachable generated-app URL."}),yield{type:"tool_selection_policy",turnId:r,policyId:"global_process_kill_recovery",intent:"verification",reason:"global-node-process-kill-blocked",availableToolNames:k(a??u),enabledToolNamesBefore:_,enabledToolNamesAfter:k(b),suppressedToolNames:[],nextAction:"use-owned-task-cancel-or-new-explicit-port"}}}p.blocked&&(yield{type:"tool_blocked",turnId:r,callId:p.callId,name:p.toolName,reason:p.blockReason??"blocked"}),m.push(p.message),W.push(p.callId),N.add(p.toolName);let O=Tc(p,c);O||F++;let I=p.ok&&Fr(p);if(p.ok&&!I&&!O&&(Ue+=1),O||ms({toolFailureCounts:c.toolFailureCounts,toolName:p.toolName,toolArguments:pe.find(_=>_.id===p.callId)?.function.arguments,ok:p.ok,softEmpty:I}),p.ok&&_c.has(p.toolName)&&au(c),p.ok&&Es(p.toolName)){let _=pe.find(B=>B.id===p.callId),S=_?Lt(_.function.arguments):void 0;if(S){let B=H(S);if(c.benchmarkStateMaintenanceRequiredFiles.has(B)){let re=fo(c.maintainedDocuments,B,_?.function.arguments??"");re.ok?c.benchmarkStateMaintenanceWrittenFiles.add(B):(D.push({name:p.toolName,reason:"benchmark-state-invalid-content"}),m.push({role:"user",content:`Benchmark-state maintenance write for ${B} is incomplete: ${re.reason}. Rewrite or patch the file using the document evidence already provided; do not reread context-pack source documents.`}))}}}if(p.ok&&!I&&(oo.has(p.toolName)||p.toolName==="exec"&&p.details?.type==="exec_background"||p.toolName==="exec"&&Ss(pe.find(_=>_.id===p.callId)?.function.arguments??""))){let _=pe.find(B=>B.id===p.callId),S=typeof p.message?.content=="string"?p.message.content:"";if(_&&S){let B=Array.isArray(p.message.imageUrls)?p.message.imageUrls.filter(me=>typeof me=="string"):void 0,re=Array.isArray(p.message.toolReferences)?p.message.toolReferences.filter(me=>typeof me=="string"):void 0;c.identicalSuccessfulToolResults.set(`${_.function.name}::${_.function.arguments}`,{content:S,imageUrls:B,toolReferences:re})}}if(p.toolName==="agent"){let _=Ee(p.details,"agentId"),S=Ee(p.details,"status"),B=Et(p.details,"background");p.ok&&_&&B===!0&&S==="running"&&be(c).add(_)}if(p.toolName==="task"){let _=vc(p.details);_&&(c.lastTaskList=_);let S=Ee(p.details,"taskId"),B=Et(p.details,"running"),re=Ee(p.details,"lifecycle"),me=Ee(p.details,"action");if(S&&(me==="cancel"||B===!1||re&&re!=="running"&&re!=="pending"))be(c).delete(S),c.backgroundAgentNoOutputPollCounts.delete(S),c.stalledBackgroundAgentTasks.delete(S);else if(S&&me==="output"&&B===!0&&be(c).has(S)){let Bo=typeof p.message?.content=="string"?p.message.content:"",Do=Et(p.details,"hasOutput");if(Do!==void 0?Do===!1:Rc(Bo)){let rn=(c.backgroundAgentNoOutputPollCounts.get(S)??0)+1;c.backgroundAgentNoOutputPollCounts.set(S,rn);let mt=gc(p.details,"elapsedSeconds")??xc(Bo);(mt!==void 0&&mt>=Cc||mt===void 0&&rn>=kc)&&c.stalledBackgroundAgentTasks.set(S,`no output after ${mt??"unknown"}s across ${rn} poll(s)`)}else c.backgroundAgentNoOutputPollCounts.delete(S),c.stalledBackgroundAgentTasks.delete(S)}}if(p.ok&&p.toolName==="read"){let _=pe.find(S=>S.id===p.callId);if(_){let S=so(_.function.arguments);if(S){let B=H(S),re=c.fileReadCounts.get(B)??0;c.fileReadCounts.set(B,re+1);let me=typeof p.message?.content=="string"?p.message.content:"";d=Kc(c,S,me,c.turnCount,p.details)||d}}}yield br(r,p);for(let _ of Tr(r,p))yield _;for(let _ of Cr({turnId:r,result:p,toolCalls:te}))yield _;let Ve=te.find(_=>_.id===p.callId),ui=typeof p.message?.content=="string"?p.message.content:"";if(Ve){Sr({state:c.artifactContract,inputMessages:i,toolName:p.toolName,rawArguments:Ve.function.arguments,ok:p.ok,content:ui}),Gt()&&(yield Ht());let _=lc(p.toolName,Ve.function.arguments);if(_){let S=(go.get(_)??0)+1;if(go.set(_,S),S===ac){let B=_.startsWith("exec:")?"exec":"edit";c.recoveryTrace.set(`no_progress_observed:${B}`,(c.recoveryTrace.get(`no_progress_observed:${B}`)??0)+1)}}}!ft&&Vs&&p.toolName==="stt"&&p.ok&&(ft=Kl(i,p))}if(qe&&(b=ye(L,K),qe=!1),Bt&&(b=ye(L,K),Bt=!1),d){let p=Gc(r,c.maintainedDocuments,c.fileReadCounts,c.turnCount);p&&(yield p);for(let I of Xc(r,c.maintainedDocuments))yield I;let C=Lc(c.maintainedDocuments,c.turnCount),O=b.some(I=>ro.has(I.function.name));if(C&&O){c.benchmarkStateMaintenanceRequiredFiles=new Set(Ds(c.maintainedDocuments).map(H));for(let I of b)ro.has(I.function.name)||K.add(I.function.name);b=ye(b,K),q=!0,m.push({role:"user",content:C}),yield M("benchmark_state_maintenance_required","forcing write/edit/patch after long-horizon document index")}}let g=be(c);if(g.size>0){let p=(a??u).find(C=>C.function.name==="task");if(p){let C=k(b),O=[...g].filter(I=>c.stalledBackgroundAgentTasks.has(I)).sort();if(O.length>0){b=[p],q=!0;let I=O.map(ce=>`${ce}: ${c.stalledBackgroundAgentTasks.get(ce)}`).join("; ");m.push({role:"user",content:yc(O,{reason:I})}),yield{type:"tool_selection_policy",turnId:r,policyId:"background_agent_no_output_watchdog_cancel_required",intent:"lifecycle_reconciliation",reason:"background-agent-no-output-watchdog",availableToolNames:k(a??u),enabledToolNamesBefore:C,enabledToolNamesAfter:k(b),suppressedToolNames:C.filter(ce=>ce!=="task"),nextAction:"cancel-stalled-background-task"},yield M("background_agent_no_output_watchdog_cancel_required",I);continue}b=[p],q=!0,m.push({role:"user",content:hc(g)}),yield{type:"tool_selection_policy",turnId:r,policyId:"background_agent_lifecycle_poll_required",intent:"lifecycle_reconciliation",reason:"background-agent-task-unresolved",availableToolNames:k(a??u),enabledToolNamesBefore:C,enabledToolNamesAfter:k(b),suppressedToolNames:C.filter(I=>I!=="task"),nextAction:"poll-existing-background-task-output"},yield M("background_agent_lifecycle_poll_required",[...g].sort().join(","));continue}}else b.length===1&&b[0]?.function.name==="task"&&(b=ye(L,K));if(se(i)&&!c.artifactContract.browserVerified&&Pt(c.artifactContract).length>0&&b.some(p=>p.function.name==="exec")&&c.browserAcceptanceRecoveryCount<4){let p=As(c.artifactContract);c={...c,browserAcceptanceRecoveryCount:c.browserAcceptanceRecoveryCount+1,messages:[...m,{role:"user",content:p}],transition:{reason:"next_turn"}},q=!0,yield M("browser_acceptance_required","forcing browser automation after localhost app URL was observed");continue}let y=Bc(c.maintainedDocuments);if(y.length>0&&c.benchmarkStateIntegrityRecoveryCount<Ic){let p=y.map(C=>`${Te(C.path)}: ${C.reason}`).join("; ");c={...c,benchmarkStateIntegrityRecoveryCount:c.benchmarkStateIntegrityRecoveryCount+1,messages:[...m,{role:"user",content:"Your maintained benchmark-state hash files no longer match the tool-derived ground truth: "+p+". The context-pack inputs are read-only and immutable \u2014 the source did NOT change. Restore the exact recorded contentHash/fileSizeBytes; do NOT flip any acceptance verdict on this phantom drift."}],transition:{reason:"next_turn"}},q=!0,yield M("benchmark_state_integrity_required","on-disk benchmark-state hash file contradicts tool-derived ground truth; forcing a correction before completion");continue}if(Nc(c)){yield*G("Maintained benchmark-state files after indexing the context pack. Stopping this turn now because the required document-index.json, decision-state-table.json, and context-pack-evidence.json writes are complete; do not continue into extra writes, context-pack modifications, or repeated reads.");return}}catch(l){let d=l instanceof Error?l.message:String(l);yield{type:"error",turnId:r,error:d,code:"TOOL_EXECUTION_ERROR",usage:c.totalUsage};return}if(ft){yield*G(ft);return}if(m.push(...gs({toolFailureCounts:c.toolFailureCounts,snapshot:li})),ai){let l=Me({inputMessages:i,messages:m,reason:`tool call budget exhausted (${ne}) before completing all required files`});if(l){yield*G(l);return}}Q=ht(Q,{replayMessages:m,completedToolCallIds:[...Q.completedToolCallIds,...W],lastStopReason:"tool_calls"}),e.toolChoice==="required"&&te.length>0&&(Ut=!0);let ci=te.length>0&&te.every(l=>{let d=m.find(y=>y?.role==="tool"&&y?.tool_call_id===l.id);if(!d)return!0;let g=d.content;return typeof g=="string"&&g.startsWith("Error: ")}),ke=c.consecutiveFailedRounds;if(ci){if(ke+=1,ke>=Yo){if(mo>=3&&c.repeatedToolFailureRecoveryCount<1){let y=Jn({inputMessages:i,messages:m,finalText:c.finalText,thinkingBlocks:[],stopHookActive:c.stopHookActive,totalToolCallCount:F,distinctToolNames:N,log:o});if(y?.reason==="explicit_required_file_verification"||y?.reason==="explicit_extra_file_verification"){yield M("repeated_tool_failure_artifact_recovery","one recovery nudge before ending a complex explicit artifact turn after repeated tool failures"),c={...c,messages:y.messages,stopHookActive:y.stopHookActive,transition:y.transition,consecutiveFailedRounds:0,repeatedToolFailureRecoveryCount:c.repeatedToolFailureRecoveryCount+1};continue}}if(c.repeatedToolFailureRecoveryCount<1){let y=Hr(m);if(y){yield M("repeated_tool_failure_self_correction","one help-guided self-correction round before ending on repeated tool failures"),c={...c,messages:[...m,y],consecutiveFailedRounds:0,repeatedToolFailureRecoveryCount:c.repeatedToolFailureRecoveryCount+1};continue}}let l=`repeated tool failures (${ke} rounds in a row)`,d=Me({inputMessages:i,messages:m,reason:`${l} before all required files were produced`})??(c.finalText.trim()?c.finalText:qn(m,ke)),g=Ms(d,{availableToolNames:k(a??u),enabledToolNames:$t(),toolCallNames:[...N].sort(),blockedToolCalls:At(D)});o.info(`early exit: ${ke} consecutive failed rounds, returning ${c.finalText?"partial":"fallback"} response`),yield*G(g);return}}else ke=0;let pt=[...c.fileReadCycleBlockedPaths].filter(l=>!c.fileReadCycleNudgedPaths.has(l));if(pt.length>0){let l=pt.join(", "),d=[...new Set(pt.map(no))].join(" ");o.info(`AP5: file read cycle detected on ${l}, injecting nudge`);let g={role:"user",content:`Read-cycle guard blocked repeated reads for: ${l}. ${d} Stop reading these source files this turn; summarize from maintained evidence and explain any remaining uncertainty.`};m.push(g);for(let y of pt)c.fileReadCycleNudgedPaths.add(y)}let Ne=oe+1;if(v>0&&Ne>v){if(o.info(`max turns reached (${v}), completing`),R){let g=await R.invoke("stop",{sessionId:s,reason:"max_turns"});if(g.action==="abort"){let y=g.reason??"Stop hook requested continuation after max_turns",p={role:"assistant",content:c.finalText,...ae.length>0&&{thinkingBlocks:[...ae]}};c={...c,messages:[...m,p,{role:"user",content:y}],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}};continue}}let l=Me({inputMessages:i,messages:m,reason:`tool loop max turns reached (${v}) before completing all required files`});if(l){yield*G(l);return}let d=nt(m,`tool loop max turns reached (${v}) before completing the final status contract`);yield*G(d);return}if(Ft&&be(c).size>0&&Ne>j&&j<100&&(j=Math.min(100,Ne+25),o.info(`background task lifecycle wait extended round budget to ${j}`)),Ft&&Ne>j){let l=Hn({currentToolBudget:ne,currentRoundBudget:j,toolHardCap:100,roundHardCap:100,continuationCount:je,successfulSinceLastCheck:Ue-et,fileReadCounts:c.fileReadCounts,windowTools:ge,windowRounds:25});l&&(j=l.nextRoundBudget,ne=l.nextToolBudget,je=l.continuationCount,et=Ue,o.info(`round budget continuation #${l.continuationCount}: rounds\u2192${j}, tools\u2192${ne} (progress detected)`))}if(Ne>j){o.info(`tool loop budget exhausted (${j} rounds), returning`);let l=Qn({totalToolCallCount:F,distinctToolNames:N,projectRoot:e.projectRoot});l&&(yield{type:"skill_instruction",turnId:r,instruction:l});let d=Me({inputMessages:i,messages:m,reason:`tool budget exhausted (${j} rounds) before completing all required files`});if(d){yield*G(d);return}let g=nt(m,`tool budget exhausted (${j} rounds) before completing the final status contract`);yield*G(g);return}c={messages:m,maxOutputTokensRecoveryCount:0,hasAttemptedReactiveCompact:!1,maxOutputTokensOverride:void 0,turnCount:Ne,transition:{reason:"next_turn"},guardState:U,reactiveCompactState:J,toolLoopState:Q,consecutiveFailedRounds:ke,finalText:c.finalText,totalUsage:c.totalUsage,collapseStore:Wt,currentModel:c.currentModel,consecutive529Errors:0,consecutiveApiRetries:0,stopHookActive:c.stopHookActive,lastResponseId:c.lastResponseId,snipRemovedIds:c.snipRemovedIds,contentReplacementState:c.contentReplacementState,budgetContinuationCount:c.budgetContinuationCount,repeatedToolFailureRecoveryCount:c.repeatedToolFailureRecoveryCount,lastBudgetDeltaTokens:c.lastBudgetDeltaTokens,lastBudgetGlobalTokens:c.lastBudgetGlobalTokens,identicalCallCounts:it,identicalSuccessfulToolResults:c.identicalSuccessfulToolResults,artifactContract:c.artifactContract,toolFailureCounts:c.toolFailureCounts,fileReadCounts:c.fileReadCounts,fileReadCycleBlockedPaths:c.fileReadCycleBlockedPaths,fileReadCycleNudgedPaths:c.fileReadCycleNudgedPaths,maintainedDocuments:c.maintainedDocuments,persistedBenchmarkStateRecovered:c.persistedBenchmarkStateRecovered,benchmarkStateMaintenanceRequiredFiles:c.benchmarkStateMaintenanceRequiredFiles,benchmarkStateMaintenanceWrittenFiles:c.benchmarkStateMaintenanceWrittenFiles,recoveryTrace:c.recoveryTrace,browserAcceptanceRecoveryCount:c.browserAcceptanceRecoveryCount,buildVerificationRecoveryCount:c.buildVerificationRecoveryCount,benchmarkStateIntegrityRecoveryCount:c.benchmarkStateIntegrityRecoveryCount,backgroundAgentTaskIds:be(c),backgroundAgentNoOutputPollCounts:c.backgroundAgentNoOutputPollCounts,stalledBackgroundAgentTasks:c.stalledBackgroundAgentTasks,notOfferedToolRecoveryCount:c.notOfferedToolRecoveryCount,existingFileUpdateRecoveryCount:c.existingFileUpdateRecoveryCount,taskListReconciliationCount:c.taskListReconciliationCount,lastTaskList:c.lastTaskList}}}var lu=["\u63A5\u5355\u91D1\u989D","\u5408\u540C\u91D1\u989D","\u62A5\u4EF7","\u9884\u7B97","\u91D1\u989D","price","amount","contract amount"];function Hs(e){let t=cu(e),n=["[Recalled memories]","- L1 project MD is project-scoped working memory.","- L2 long-term memory is cross-project canonical memory.","- If L1 and L2 conflict on the same entity/fact, do not silently merge or choose. Surface the conflict and ask the user to confirm. For current-project operational tasks, use L1 only as a project-scoped clue until confirmed into L2."];if(t.length>0){n.push("[Memory conflict detected]");for(let o of t)n.push(`- entity: ${o.entity}; fact: ${o.predicate}; L1 project MD says: ${zs(o.l1Amount)}; L2 long-term says: ${zs(o.l2Amount)}; action: ask the user which value is current before using it.`)}for(let o of e){let r=fu(o);n.push(`- [${r}] ${o.text}`)}return n.join(`
|
|
43
|
+
`)}function cu(e){let t=e.filter(r=>r.source==="l1-project-md").flatMap(r=>qs(r.text)),n=e.filter(r=>r.source==="l2-long-term").flatMap(r=>qs(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 pu(o)}function qs(e){let t=[];for(let n of e.split(/\r?\n/)){let o=n.trim();if(o)for(let r of lu){if(r==="\u91D1\u989D"&&/(接单金额|合同金额)/u.test(o))continue;let s=new RegExp(`${mu(r)}[^0-9.\u4E07kK,]{0,12}([0-9][0-9.,]*\\s*(?:\u4E07|k|K)?)`,"gi");for(let i of o.matchAll(s)){let a=du(i[1]);a!==null&&t.push({entity:uu(o,r),predicate:r,amount:a,text:o})}}}return t}function uu(e,t){if(/Galaxy\s+Tech/i.test(e))return"Galaxy Tech";if(e.includes("\u7528\u6237"))return"\u7528\u6237";let n=e.toLowerCase().indexOf(t.toLowerCase()),r=(n>=0?e.slice(0,n):"").replace(/[#*`:\-,。;;,.]/g," ").trim().split(/\s+/).filter(Boolean);return r[r.length-1]??"unknown"}function du(e){let t=e.replace(/,/g,"").replace(/\s+/g,"").trim(),n=t.endsWith("\u4E07")?1e4:/k$/i.test(t)?1e3:1,o=Number(t.replace(/[万kK]$/u,""));return Number.isFinite(o)?o*n:null}function fu(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 zs(e){return Number.isInteger(e)?String(e):String(Number(e.toFixed(4)))}function pu(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 mu(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var gu=8192;async function Gs(e){let{hooks:t,detectRecallCategories:n,log:o,sessionId:r,turnId:s,query:i}=e;try{let a=n(i),f=(await t.invoke("memory.before_recall",{sessionId:r,turnId:s,query:i,preferredCategories:a.preferred.length>0?a.preferred:void 0,deprioritizedCategories:a.deprioritized.length>0?a.deprioritized:void 0}))?.context?.recalledMemories,h=null;if(f&&f.length>0){let T=0,R=[];for(let x of f){let w=(x.text?.length??0)*2;if(T+w>gu)break;R.push(x),T+=w}R.length>0&&(h=`[Recalled memories \u2014 context priority: project-specific facts override general user preferences when they conflict]
|
|
44
|
+
${Hs(R)}`)}return $(t,"memory.after_recall",{sessionId:r,turnId:s,blockCount:f?.length??0},o),h}catch{return null}}var Ws=class{transport;apiKey;toolInvoker;log;hooks;maxRounds;configuredMaxRounds;projectRoot;runtimePorts;constructor(t){this.transport=t.llmTransport,this.apiKey=t.apiKey,this.toolInvoker=t.toolInvoker,this.log=t.log,this.hooks=t.hooks,this.projectRoot=t.projectRoot,this.runtimePorts=t.runtimePorts,this.configuredMaxRounds=typeof t.maxRounds=="number"&&Number.isFinite(t.maxRounds)?Math.min(t.maxRounds,100):void 0,this.maxRounds=Math.min(this.configuredMaxRounds??25,100)}async*run(t,n){let{turnId:o,messages:r,availableTools:s,tools:i,systemPrompt:a,config:u}=t,f={sessionId:t.sessionId,turnId:o};yield{type:"start",turnId:o},$(this.hooks,"turn.submitted",{...f,prompt:r[r.length-1]?.content??void 0},this.log);let h=Cn(r),T=[];if(a&&T.push({role:"system",content:a}),T.push(...h),this.hooks){let v=h.filter(A=>A.role==="user").pop(),P=typeof v?.content=="string"?v.content.slice(0,500):void 0;if(P){let A=await Gs({hooks:this.hooks,detectRecallCategories:L=>this.runtimePorts.detectRecallCategories(L),log:this.log,sessionId:t.sessionId,turnId:o,query:P});A&&T.splice(a?1:0,0,{role:"system",content:A})}}let R=u?.model??"",x=typeof u?.maxRounds=="number"&&Number.isFinite(u.maxRounds)?u.maxRounds:this.configuredMaxRounds,w=x===void 0?void 0:Math.min(x,100);try{let v=u?.reasoning;u?.reasoning?.effort==="auto"&&(v={...u?.reasoning,effort:"medium"});let P={turnId:o,sessionId:t.sessionId,messages:T,availableTools:s,tools:i,refreshTools:t.refreshTools,model:R,apiKey:u?.apiKey??this.apiKey,temperature:u?.temperature,maxRounds:w,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:v,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},A;for await(let L of js(P,this.transport,this.toolInvoker,this.log))A=L,yield L;A?.type==="end"?$(this.hooks,"turn.completed",{...f},this.log):A?.type==="error"&&$(this.hooks,"turn.failed",{...f,code:A.code,error:A.error},this.log)}catch(v){if(n?.aborted)$(this.hooks,"turn.failed",{...f,code:"ABORTED",error:"Turn aborted"},this.log),yield{type:"error",turnId:o,error:"Turn aborted",code:"ABORTED"};else{let P=v instanceof Error?v.message:String(v),A=typeof v?.status=="number"?v.status:void 0,L=Fe(A,P);this.log.error(`turn ${o} error [${L}, retryable=${ln(L)}]: ${P}`),$(this.hooks,"turn.failed",{...f,code:L,error:P},this.log),yield{type:"error",turnId:o,error:P,code:L}}}}};export{Ws as Agent};
|