qlogicagent 2.15.9 → 2.16.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/agent.js +34 -16
- package/dist/cli.js +585 -514
- package/dist/index.js +584 -513
- package/dist/orchestration.js +9 -9
- package/dist/protocol.js +1 -1
- package/dist/types/agent/tool-loop/artifact-final-contract.d.ts +86 -0
- package/dist/types/agent/tool-loop/completion-action-policy.d.ts +1 -9
- package/dist/types/agent/tool-loop/tool-failure-policy.d.ts +2 -0
- package/dist/types/agent/tool-loop.d.ts +4 -10
- package/dist/types/agent/types.d.ts +9 -131
- package/dist/types/cli/acp-extended-handlers.d.ts +1 -0
- package/dist/types/cli/agent-config-coordinator.d.ts +11 -0
- package/dist/types/cli/core-tools/agent-tool-service.d.ts +1 -0
- package/dist/types/cli/handlers/agents-handler.d.ts +15 -6
- package/dist/types/cli/handlers/product-handler.d.ts +21 -2
- package/dist/types/cli/handlers/project-handler.d.ts +8 -0
- package/dist/types/cli/handlers/workflow-handler.d.ts +5 -0
- package/dist/types/cli/tool-bootstrap-core-registration.d.ts +5 -0
- package/dist/types/cli/turn-core.d.ts +4 -0
- package/dist/types/contracts/index.d.ts +1 -0
- package/dist/types/contracts/turn-event.d.ts +235 -0
- package/dist/types/orchestration/agent-instance.d.ts +45 -2
- package/dist/types/orchestration/agent-roster.d.ts +17 -0
- package/dist/types/orchestration/dag-scheduler.d.ts +27 -0
- package/dist/types/orchestration/product-budget.d.ts +7 -1
- package/dist/types/orchestration/product-persistence.d.ts +31 -0
- package/dist/types/orchestration/product-planner.d.ts +123 -0
- package/dist/types/orchestration/product-run-coordinator.d.ts +17 -1
- package/dist/types/orchestration/product-worktree.d.ts +3 -0
- package/dist/types/orchestration/skill-improvement.d.ts +2 -19
- package/dist/types/orchestration/solo-evaluator.d.ts +11 -6
- package/dist/types/orchestration/solo-spec-builder.d.ts +4 -0
- package/dist/types/orchestration/workflow/n8n-import.d.ts +26 -32
- package/dist/types/orchestration/workflow/n8n-template-compat.d.ts +5 -0
- package/dist/types/orchestration/workflow/node-registry.d.ts +13 -0
- package/dist/types/orchestration/workflow/node-schema.d.ts +10 -0
- package/dist/types/orchestration/workflow/qla-executor-host.d.ts +7 -1
- package/dist/types/protocol/methods.d.ts +8 -1
- package/dist/types/protocol/notifications.d.ts +1 -1
- package/dist/types/protocol/wire/acp-agent-management.d.ts +51 -0
- package/dist/types/protocol/wire/acp-protocol.d.ts +1 -0
- package/dist/types/protocol/wire/agent-events.d.ts +3 -3
- package/dist/types/protocol/wire/agent-methods.d.ts +14 -2
- package/dist/types/protocol/wire/index.d.ts +1 -1
- package/dist/types/protocol/wire/notification-payloads.d.ts +120 -11
- package/dist/types/runtime/infra/acp-detector.d.ts +37 -2
- package/dist/types/runtime/infra/acp-protocol-adapter.d.ts +9 -0
- package/dist/types/runtime/infra/agent-install-runner.d.ts +23 -0
- package/dist/types/runtime/infra/agent-process.d.ts +10 -0
- package/dist/types/runtime/ports/agent-execution-contracts.d.ts +4 -128
- package/dist/types/runtime/ports/tool-contracts.d.ts +6 -0
- package/dist/types/runtime/prompt/environment-context.d.ts +20 -1
- package/dist/types/skills/tools/ask-user-tool.d.ts +4 -2
- package/dist/types/skills/tools/shell/command-classification.d.ts +1 -0
- package/dist/types/skills/tools/tool-search-tool.d.ts +13 -0
- package/dist/types/skills/tools/tool-selection-eval.d.ts +49 -0
- package/dist/types/skills/tools/tool-selection-eval.dataset.d.ts +5 -0
- package/dist/types/skills/tools/write-tool.d.ts +2 -0
- package/dist/types/skills/tools.d.ts +21 -0
- package/dist/types/transport/acp-server.d.ts +1 -0
- package/package.json +2 -1
package/dist/agent.js
CHANGED
|
@@ -1,25 +1,43 @@
|
|
|
1
|
-
function ot(e,t,o,n){return{role:"assistant",content:t||null,tool_calls:e,...o&&o.length>0?{thinkingBlocks:o}:{},...n?{reasoning_content:n}:{}}}function V(e,t){let o=t.ok?typeof t.payload=="string"?t.payload:JSON.stringify(t.payload??""):`Error: ${t.error??"Tool execution failed"}`;return{role:"tool",tool_call_id:e,content:o,...!t.ok&&{is_error:!0},...t.toolReferences?.length?{toolReferences:t.toolReferences}:{},...t.imageUrls?.length?{imageUrls:t.imageUrls}:{}}}var qo=/\b(?:daily|weekly|monthly)(?:\/(?:daily|weekly|monthly))* (?:usage )?limit(?:s)?(?: (?:exhausted|reached|exceeded))?\b/i,oe={rateLimit:[/rate[_ ]limit|too many requests|429/,"model_cooldown","exceeded your current quota","resource has been exhausted","quota exceeded","resource_exhausted","usage limit",/\btpm\b/i,"tokens per minute","tokens per day"],overloaded:[/overloaded_error|"type"\s*:\s*"overloaded_error"/i,"overloaded",/service[_ ]unavailable.*(?:overload|capacity|high[_ ]demand)|(?:overload|capacity|high[_ ]demand).*service[_ ]unavailable/i,"high demand"],timeout:["timeout","timed out","service unavailable","deadline exceeded","context deadline exceeded","connection error","network error","network request failed","fetch failed","socket hang up",/\beconn(?:refused|reset|aborted)\b/i,/\benotfound\b/i,/\beai_again\b/i,/without sending (?:any )?chunks?/i,/\bstop reason:\s*(?:abort|error|network_error)\b/i,/\breason:\s*(?:abort|error|network_error)\b/i,/\bunhandled stop reason:\s*(?:abort|error|network_error)\b/i],billing:[/["']?(?:status|code)["']?\s*[:=]\s*402\b|\bhttp\s*402\b|\berror(?:\s+code)?\s*[:=]?\s*402\b|\b(?:got|returned|received)\s+(?:a\s+)?402\b|^\s*402\s+payment/i,"payment required","insufficient credits",/insufficient[_ ]quota/i,"credit balance","plans & billing","insufficient balance"],authPermanent:[/api[_ ]?key[_ ]?(?:revoked|invalid|deactivated|deleted)/i,"invalid_api_key","key has been disabled","key has been revoked","account has been deactivated",/could not (?:authenticate|validate).*(?:api[_ ]?key|credentials)/i,"permission_error","not allowed for this organization"],auth:[/invalid[_ ]?api[_ ]?key/,"incorrect api key","invalid token","authentication","re-authenticate","oauth token refresh failed","unauthorized","forbidden","access denied","insufficient permissions","insufficient permission",/missing scopes?:/i,"expired","token has expired",/\b401\b/,/\b403\b/,"no credentials found","no api key found"],format:["string should match pattern","tool_use.id","tool_use_id","messages.1.content.1.tool_use.id","invalid request format",/tool call id was.*must be/i]},Ho=/^(?:error[:\s-]+)?billing(?:\s+error)?(?:[:\s-]+|$)|^(?:error[:\s-]+)?(?:credit balance|insufficient credits?|payment required|http\s*402\b)/i,zo=/["']?(?:status|code)["']?\s*[:=]\s*402\b|\bhttp\s*402\b|\berror(?:\s+code)?\s*[:=]?\s*402\b|^\s*402\s+payment/i,Go=512,Wo=/^(?:http\s*)?(\d{3})(?:\s+([\s\S]+))?$/i;var Ko=new Set([500,502,503,504,521,522,523,524,529]),Xo=["insufficient credits","insufficient quota","credit balance","insufficient balance","plans & billing","add more credits","top up"],Yo=["upgrade your plan","upgrade plan","current plan","subscription"],Vo=["daily","weekly","monthly"],Zo=["try again","retry","temporary","cooldown"],Jo=["usage limit","rate limit","organization usage"],Qo=["organization","workspace"],er=["billing period","exceeded","reached","exhausted"],tr=/["']?(?: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,nr=/^(?:error[:\s-]+)?(?:(?:http\s*)?402(?:\s+payment required)?|payment required)(?:[:\s-]+|$)/i;function re(e,t){if(!e)return!1;let o=e.toLowerCase();return t.some(n=>n instanceof RegExp?n.test(o):o.includes(n))}function or(e){return re(e,oe.format)}function ln(e){return re(e,oe.rateLimit)}function rr(e){return re(e,oe.timeout)}function sr(e){return qo.test(e)}function rt(e){let t=e.toLowerCase();return t?e.length>Go?zo.test(t):re(t,oe.billing)?!0:Ho.test(e)?t.includes("upgrade")||t.includes("credits")||t.includes("payment")||t.includes("plan"):!1:!1}function cn(e){return re(e,oe.authPermanent)}function ir(e){return re(e,oe.auth)}function un(e){return re(e,oe.overloaded)}function ne(e,t){return t.some(o=>e.includes(o))}function ar(e){return ne(e,Xo)||ne(e,Yo)&&e.includes("limit")||e.includes("billing hard limit")||e.includes("hard limit reached")||e.includes("maximum allowed")&&e.includes("limit")}function lr(e){let t=ne(e,Vo),o=e.includes("spend limit")||e.includes("spending limit"),n=ne(e,Qo);return ne(e,Zo)&&ne(e,Jo)||t&&(e.includes("usage limit")||o)||t&&e.includes("limit")&&e.includes("reset")||n&&e.includes("limit")&&(o||ne(e,er))}function cr(e){return e.trim().toLowerCase().replace(nr,"").trim()}function dn(e){let t=cr(e);return!t||ar(t)?"billing":ln(t)||lr(t)?"rate_limit":"billing"}function ur(e){return tr.test(e)?dn(e):null}function pn(e){let t=e.match(Wo);if(!t)return null;let o=Number(t[1]);return Number.isFinite(o)?{code:o,rest:(t[2]??"").trim()}:null}function dr(e){if(!e)return!1;let t=e.toLowerCase();return t.includes('"type":"api_error"')&&t.includes("internal server error")}function pr(e){let t=e.trim();if(!t)return!1;let o=pn(t);return o?Ko.has(o.code):!1}function mn(e,t){return typeof e!="number"||!Number.isFinite(e)?null:e===402?t?dn(t):"billing":e===429?"rate_limit":e===401||e===403?t&&cn(t)?"auth_permanent":"auth":e===408?"timeout":e===503?t&&un(t)?"overloaded":"timeout":e===502||e===504?"timeout":e===529?"overloaded":e===400?t&&rt(t)?"billing":"format":null}function mr(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 fr(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 fn(e){if(fr(e))return"session_expired";if(mr(e))return"model_not_found";let t=ur(e);return t||(sr(e)?rt(e)?"billing":"rate_limit":ln(e)?"rate_limit":un(e)?"overloaded":pr(e)?pn(e.trim())?.code===529?"overloaded":"timeout":dr(e)?"timeout":or(e)?"format":rt(e)?"billing":rr(e)?"timeout":cn(e)?"auth_permanent":ir(e)?"auth":null)}var gr={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"},yr=new Set(["RETRYABLE_TRANSIENT","RETRYABLE_DEGRADED","TOOL_EXECUTION_FAILED"]);function le(e,t){let o=mn(e,t)??(t?fn(t):null);return o?gr[o]:typeof e=="number"&&e>=400&&e<500?"NON_RETRYABLE_CONTENT":"RETRYABLE_TRANSIENT"}function st(e){return yr.has(e)}function gn(e){let t=typeof e.content=="string"?e.content:e.content!=null?JSON.stringify(e.content):"";return Math.ceil(t.length/4)}var hr=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"]),Te=class{constructor(t=20,o=gn){this.preserveRecentCount=t;this.estimateTokens=o}preserveRecentCount;estimateTokens;compress(t,o){if(t.length<=this.preserveRecentCount)return{messages:t,droppedCount:0,strategy:"micro-compact"};let n=t.length-this.preserveRecentCount,r=0,s=0;return{messages:t.map((a,u)=>{if(u>=n||a.role!=="tool"||typeof a.content!="string"||!a.name||!hr.has(a.name)||a.content.length<=200)return a;let p=this.estimateTokens(a);return s+=p,r++,{...a,content:`[result cleared \u2014 ${a.content.length} chars]`}}),droppedCount:r,strategy:"micro-compact",metrics:r>0?{tokensBefore:0,tokensAfter:0,compressionRatio:0,latencyMs:0,usedLlm:!1,cacheInvalidated:!1}:void 0}}};function it(e,t,o=gn){if(t.size===0)return{messages:e,tokensFreed:0,removedCount:0};let n=0,r=0,s=[];for(let a of e){let u=a.tool_call_id??"";if(u&&t.has(u)){n+=o(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:n,removedCount:r,boundaryMessage:i}}function at(){return{stages:[]}}function lt(e,t,o){let n=o?.thresholdMessages??40;if(e.filter(a=>a.role!=="system").length<=n)return{messages:e,stagedCount:0};let s=yn(e,t),i=Tr(s,t,n);if(i.length===0)return{messages:s,stagedCount:0};for(let a of i)t.stages.push(a);return s=yn(e,t),{messages:s,stagedCount:i.length}}function ct(e,t){let o=0;for(let n of t.stages)n.committed||(n.committed=!0,o++);return o===0?{messages:e,committed:0}:{messages:hn(e,t),committed:o}}function yn(e,t){return t.stages.filter(n=>n.committed).length===0?e:hn(e,t)}function hn(e,t){let o=t.stages.filter(r=>r.committed).sort((r,s)=>s.range[0]-r.range[0]),n=[...e];for(let r of o){let[s,i]=r.range;if(s>=n.length)continue;let a=Math.min(i,n.length),u={role:"system",content:r.summary};n.splice(s,a-s,u)}return n}function Tr(e,t,o){let n=Math.max(0,e.length-Math.floor(o/2)),r=[],s=new Set(t.stages.map(u=>`${u.range[0]}-${u.range[1]}`)),i=-1,a=0;for(let u=0;u<n;u++){let p=e[u];if(p.role==="tool"||p.role==="assistant"&&typeof p.content=="string"&&p.content==="")i<0&&(i=u),a++;else{if(a>=3){let m=`${i}-${i+a}`;s.has(m)||r.push({id:`collapse_${i}_${i+a}`,range:[i,i+a],summary:`[${a} tool results collapsed]`,committed:!1})}i=-1,a=0}}if(a>=3){let u=`${i}-${i+a}`;s.has(u)||r.push({id:`collapse_${i}_${i+a}`,range:[i,i+a],summary:`[${a} tool results collapsed]`,committed:!1})}return r}import{existsSync as dt,readFileSync as Bn,writeFileSync as Cr,readdirSync as Dn,mkdirSync as kr}from"node:fs";import{join as pt,dirname as Rr}from"node:path";var se=Math.min(Math.max(1,Number(process.env.TOOL_LOOP_DEFAULT_BUDGET)||25),100),Tn=Math.max(1e3,Number(process.env.TOOL_LOOP_TOOL_TIMEOUT_MS)||24e4),Cn=3,kn=2,Fe=2,Rn=128e3,bn=13e3,xn=16384,_n=65536,Mn=3,An=65536,ut=500,vn=3;var Sn=3e4,En=3,ie=2;var wn=20;var In=3,Pn=2,Ln=300*1e3,On=3,Fn=720*60*60*1e3;var ei=300*1e3;var ti=3600*1e3;var ni=50*1024,oi=500*1024,ri=500*1024*1024,si=50*1024*1024;var ii=60*1024;var $n=0;var br="skill-patterns.json";function Un(e){return pt(e,".qlogicagent",br)}function xr(e){let t=Un(e);try{return JSON.parse(Bn(t,"utf8"))}catch{return{version:1,patterns:{}}}}function Nn(e,t){let o=Un(e);kr(Rr(o),{recursive:!0}),Cr(o,JSON.stringify(t,null,2),"utf8")}function _r(e){let t=Date.now()-Fn;for(let[o,n]of Object.entries(e.patterns))new Date(n.lastSeen).getTime()<t&&delete e.patterns[o]}function jn(e,t){if(t.length===0)return!1;let o=Ne(t),n=xr(e);_r(n);let r=new Date().toISOString(),s=n.patterns[o];if(s||(s={signature:o,count:0,firstSeen:r,lastSeen:r,promoted:!1},n.patterns[o]=s),s.promoted)return Nn(e,n),!1;s.count++,s.lastSeen=r;let i=s.count>=On;return i&&(s.promoted=!0),Nn(e,n),i}function Ne(e){return[...e].sort().join("+")}function Mr(e,t){if(!dt(t))return null;let o=Ne(e);try{let n=Dn(t,{withFileTypes:!0});for(let r of n){if(!r.isDirectory())continue;let s=pt(t,r.name,"SKILL.md");try{let a=Bn(s,"utf8").match(/^tools:\s*\n((?:\s+-\s+\S+\n?)+)/m);if(a){let u=a[1].split(`
|
|
2
|
-
`).map(p=>p.replace(/^\s*-\s*/,"").trim()).filter(Boolean);if(Ne(u)===o)return r.name}}catch{}}}catch{}return null}function Ar(e){if(!dt(e))return 0;try{return Dn(e,{withFileTypes:!0}).filter(t=>t.isDirectory()&&dt(pt(e,t.name,"SKILL.md"))).length}catch{return 0}}function vr(e,t){return!(!e.ok||e.existingSkillName||!e.multiStep||e.toolCallCount<In||e.distinctToolCount<Pn||Date.now()-$n<Ln||t?.projectSkillsDir&&(Ar(t.projectSkillsDir)>=wn||t.tools.length>0&&Mr(t.tools,t.projectSkillsDir))||t?.projectRoot&&t.tools.length>0&&!jn(t.projectRoot,t.tools))}function Sr(e){return e.existingSkillName?e.feedback==="negative":!1}function mt(e,t){return Sr(e)?{type:"skill.improve",skillName:e.existingSkillName,reason:"negative user feedback on existing skill execution"}:vr(e,t)?($n=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 qn(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 Er(e){return e==="enabled-eligible"||e==="installed-awaiting-approval"}function wr(e){return new Map((e??[]).map(t=>[t.toolName,t]))}function Ir(e){if(!e.eligibility?.length)return[...e.tools];let t=wr(e.eligibility);return e.tools.filter(o=>{let n=qn(o);if(!n)return!1;let r=t.get(n);return!r||Er(r.status)})}function Pr(e){let t=[],o=e.compatibility??{},n=e.toolChoice;if(e.thinkingEnabled&&o.requireAutoWhenThinking){let r=typeof n=="object"&&n&&!Array.isArray(n)?String(n.type??""):n;r&&r!=="auto"&&r!=="none"&&(t.push("tool_choice downgraded to auto because thinking mode requires auto/none compatibility."),n="auto")}if(n==="required"&&o.allowRequiredToolChoice===!1){let r=o.requiredFallback??"auto";t.push(`tool_choice=required is not supported by this provider; downgraded to ${r}.`),n=r}if(n&&typeof n=="object"&&!Array.isArray(n)&&n.type==="function"&&o.allowNamedToolChoice===!1){let r=o.namedFallback??"required";t.push(`named tool_choice is not supported by this provider; downgraded to ${r}.`),n=r}return{normalizedToolChoice:n,warnings:t}}function ft(e){let t=Pr({toolChoice:e.toolChoice,thinkingEnabled:e.thinkingEnabled,compatibility:e.compatibility}),o=t.normalizedToolChoice,n=[...t.warnings],r=Ir({tools:e.tools,eligibility:e.eligibility});if(!o||o==="auto")return{tools:r,normalizedToolChoice:o,warnings:n};if(o==="none")return{tools:[],normalizedToolChoice:"none",warnings:n};if(o==="required"){if(r.length===0)throw new Error("tool_choice=required but no tools were provided");return{tools:r,normalizedToolChoice:"required",extraSystemPrompt:"You must call one of the available tools before responding.",warnings:n}}if(typeof o=="object"&&!Array.isArray(o)&&o.type==="function"){let s=o.function??void 0,i=typeof s?.name=="string"?s.name.trim():"";if(!i)throw new Error("tool_choice.function.name is required");let a=r.filter(u=>qn(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:n}}return{tools:r,normalizedToolChoice:o,warnings:n}}var Lr=["stop","aborted","timeout","cancelled","interrupted","error"],Or=["tool_calls","toolCalls","function_call","functionCall","raw_tool_calls","rawToolCalls"];function Hn(e){return e==null?[]:typeof e=="string"?e.length>0?[{type:"text",text:e}]:[]:Array.isArray(e)?e:[{type:"text",text:String(e)}]}function Fr(e,t){return{...e,content:[...Hn(e.content),...Hn(t.content)]}}function Nr(e){let t=new Set;if(e.role!=="assistant"||!Array.isArray(e.tool_calls))return t;for(let o of e.tool_calls)typeof o.id=="string"&&o.id&&t.add(o.id);return t}function Br(e){let t=new Set,o=[];for(let n=0;n<e.length;n+=1){if(t.has(n))continue;let r=e[n];if(!r)continue;o.push(r);let s=Nr(r);if(s.size!==0)for(let i=n+1;i<e.length;i+=1){if(t.has(i))continue;let a=e[i];a?.role==="tool"&&typeof a.tool_call_id=="string"&&s.has(a.tool_call_id)&&(o.push(a),t.add(i))}}return o}function Dr(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 $r(e){return new Set((e??Lr).map(t=>t.trim().toLowerCase()))}function Ur(e,t){return e?$r(t).has(e.trim().toLowerCase()):!1}function gt(e){if(!Array.isArray(e)||e.length===0)return[...e];let t=e.map(u=>{if(u.role==="assistant"&&Array.isArray(u.tool_calls)){let p=u.tool_calls.filter(f=>Dr(f));return{...u,...p.length>0?{tool_calls:p}:{tool_calls:void 0}}}return{...u}}),o=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&&o.add(p.id);let n=t.filter(u=>u.role!=="tool"?!0:!!(u.tool_call_id&&o.has(u.tool_call_id))),r=new Set;for(let u of n)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 n){if(u.role==="assistant"&&Array.isArray(u.tool_calls)&&u.tool_calls.length>0){let p=u.tool_calls.filter(f=>typeof f.id=="string"&&r.has(f.id));if(p.length===0){let{tool_calls:f,...m}=u;m.content!=null&&m.content!==""&&s.push(m);continue}if(p.length<u.tool_calls.length){s.push({...u,tool_calls:p});continue}}s.push(u)}let i=Br(s),a=[];for(let u of i){let p=a.length>0?a[a.length-1]:void 0;if(u.role==="user"&&p?.role==="user"){a[a.length-1]=Fr(p,u);continue}a.push(u)}return a}function yt(e,t){return Ur(t?.stopReason,t?.forcedStopReasons)?e.map(o=>{if(o.role!=="assistant")return{...o};let n={...o};for(let r of Or)delete n[r];return n}):[...e]}function ht(e,t){let o=t?.placeholderToolResult??"Error: Tool loop interrupted before the tool result was replayed.",n=new Set;for(let s of e)s.role==="tool"&&typeof s.tool_call_id=="string"&&s.tool_call_id&&n.add(s.tool_call_id);let r=[];for(let s of e)if(r.push({...s}),!(s.role!=="assistant"||!Array.isArray(s.tool_calls)||s.tool_calls.length===0))for(let i of s.tool_calls)typeof i.id!="string"||!i.id||n.has(i.id)||(n.add(i.id),r.push({role:"tool",tool_call_id:i.id,content:o}));return r}function Tt(e,t){let o=gt(e),n=yt(o,t);return ht(n,t)}function jr(e){let t=new Set,o=new Set;for(let n of e){if(n.role==="assistant"&&Array.isArray(n.tool_calls))for(let r of n.tool_calls)typeof r.id=="string"&&r.id&&t.add(r.id);n.role==="tool"&&typeof n.tool_call_id=="string"&&n.tool_call_id&&o.add(n.tool_call_id)}return[...t].filter(n=>!o.has(n))}function qr(e){let t=new Set;for(let o of e)o.role==="tool"&&typeof o.tool_call_id=="string"&&o.tool_call_id&&t.add(o.tool_call_id);return[...t]}function Hr(e){return{round:e.round??0,maxRounds:e.maxRounds,pendingToolCallIds:[...e.pendingToolCallIds??[]],completedToolCallIds:[...e.completedToolCallIds??[]],lastStopReason:e.lastStopReason,replayMessages:[...e.replayMessages??[]]}}function Ct(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 Be(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 De(e){let t=[],o=gt(e.replayMessages);o.length!==e.replayMessages.length&&t.push({kind:"drop-orphan-tool-result",detail:"Removed orphan tool results or invalid assistant tool calls."});let n=yt(o,e.options);n.some((s,i)=>s!==o[i])&&t.push({kind:"strip-forced-stop-tool-metadata",detail:"Removed assistant tool-call metadata after forced stop."});let r=ht(n,e.options);return r.length>n.length&&t.push({kind:"inject-placeholder-tool-result",detail:"Injected placeholder tool result for pending tool calls."}),{state:Hr({maxRounds:e.maxRounds,round:e.round,lastStopReason:e.lastStopReason,replayMessages:r,pendingToolCallIds:jr(r),completedToolCallIds:qr(r)}),recoveryActions:t}}var zr=new Set(["main","sdk","agent","compact","hook","verification","side_question"]);function kt(e){return e?zr.has(e):!0}function Rt(e){return e===429||e===529}function $e(e,t=500,o=32e3){let n=Math.min(t*Math.pow(2,e-1),o);return n+Math.floor(Math.random()*n*.25)}var Ti={maxBackoffMs:300*1e3,resetCapMs:360*60*1e3,heartbeatIntervalMs:3e4};function Ue(){let e=process.env.QLOGICAGENT_PERSISTENT_RETRY;return e==="1"||e==="true"}var Ce=class extends Error{constructor(o,n){super(`Model fallback triggered: ${o} -> ${n}`);this.originalModel=o;this.fallbackModel=n;this.name="FallbackTriggeredError"}originalModel;fallbackModel};function bt(e){return{promptTokens:0,hasAttemptedReactiveCompact:!1,currentMaxOutputTokens:e.maxOutputTokens,consecutiveTruncations:0,aborted:e.abortSignal?.aborted??!1}}function xt(e,t){if(e.aborted)return{level:"blocking",usagePercent:100,reason:"budget_exhausted"};let o=t.contextWindowTokens-t.responseBufferTokens-e.currentMaxOutputTokens,n=o>0?e.promptTokens/o*100:100;return e.promptTokens>=o?e.hasAttemptedReactiveCompact||!t.reactiveCompactEnabled?{level:"blocking",usagePercent:n,reason:"prompt_too_long"}:{level:"blocking",usagePercent:n,reason:"prompt_too_long"}:n>=85?{level:"warning",usagePercent:n,remainingTokens:o-e.promptTokens}:{level:"ok"}}function _t(e,t,o){let n=e.message?.toLowerCase()??"",r=e.status??0;return r===413||n.includes("prompt_too_long")||n.includes("context_length_exceeded")?!t.hasAttemptedReactiveCompact&&o.reactiveCompactEnabled?{action:"reactive_compact"}:{action:"abort",reason:"prompt_too_long_unrecoverable"}:r>=500&&r<600?{action:"retry",reason:`server_error_${r}`}:r===429?{action:"retry",reason:"rate_limited"}:r===401||r===403?{action:"abort",reason:"auth_error"}:r===404?{action:"abort",reason:"model_not_found"}:{action:"abort",reason:n||"unknown_error"}}function Mt(e,t,o){if(!t.outputEscalationEnabled)return{shouldEscalate:!1,newMax:e.currentMaxOutputTokens};if(e.consecutiveTruncations>=3)return{shouldEscalate:!1,newMax:e.currentMaxOutputTokens};let n=Math.min(e.currentMaxOutputTokens*2,o);return n<=e.currentMaxOutputTokens?{shouldEscalate:!1,newMax:e.currentMaxOutputTokens}:{shouldEscalate:!0,newMax:n}}function At(e,t){return e.aborted?!0:t.abortSignal?.aborted?(e.aborted=!0,!0):!1}var Wr={maxConsecutiveFailures:3,minMessagesAfterCompact:4,targetUsagePercent:50};function vt(){return{consecutiveFailures:0,attemptedThisTurn:!1,lastCompactAt:null,toolsAtLastCompact:[]}}function ce(e,t=Wr){return!(e.attemptedThisTurn||e.consecutiveFailures>=t.maxConsecutiveFailures)}function St(e,t){let o=e.get(t.index)??{id:"",name:"",arguments:""};t.id&&(o.id=t.id),t.name&&(o.name=t.name),o.arguments+=t.arguments??"",e.set(t.index,o)}function E(e,t,o,n){e?.invoke(t,o).catch(r=>{let s=r instanceof Error?r.message:String(r);n.warn(`[hook:${t}] handler failed: ${s}`)})}function zn(e,t){let o=typeof t.message?.content=="string"?t.message.content:"",n=o?o.slice(0,2e3):void 0,r=t.details,s=typeof r?.stdout=="string"?r.stdout.slice(0,8e3):void 0,i=typeof r?.stderr=="string"?r.stderr.slice(0,4e3):void 0,a=typeof r?.exitCode=="number"?r.exitCode:void 0;return{type:"tool_result",turnId:e,callId:t.callId,name:t.toolName,ok:t.ok,error:t.error,outputPreview:n,durationMs:t.durationMs,exitCode:a,stdout:s,stderr:i,details:r}}function Gn(e,t){if(!t.ok)return[];let o=t.details;if(!o)return[];let n=Kr(o);return n?(Array.isArray(o.mediaUrls)?o.mediaUrls.filter(s=>typeof s=="string"&&s.trim().length>0):[]).map(s=>({type:"media_result",turnId:e,mediaType:n,url:s,model:typeof o.model=="string"?o.model:void 0,provider:typeof o.provider=="string"?o.provider:void 0,durationSeconds:typeof o.durationMs=="number"?o.durationMs/1e3:void 0,taskId:typeof o.taskId=="string"?o.taskId:void 0})):[]}function Kr(e){let t=typeof e.type=="string"?e.type:"";if(!t)return null;if(t==="three_d_generate")return"3d";let o=t.split("_")[0];return o==="image"||o==="tts"||o==="video"||o==="music"?o:null}var Xr=new Set(["write","edit","patch"]);function Wn(e){let{turnId:t,result:o,toolCalls:n}=e;if(!o.ok)return[];let r=n.find(a=>a.id===o.callId);if(!r)return[];let s=[],i=Yr(r.function.arguments);if(!i)return s;if(Xr.has(o.toolName)){let a=Vr(i);a&&s.push({type:"artifact",turnId:t,artifactId:`artifact-${o.callId}`,artifactType:Zr(a),title:a.split(/[\\/]/).pop()||a,filePath:a,language:Jr(a)})}return s}function Yr(e){try{return JSON.parse(e)}catch{return null}}function Vr(e){return typeof e.file_path=="string"?e.file_path:typeof e.filePath=="string"?e.filePath:typeof e.path=="string"?e.path:void 0}function Zr(e){let t=e.split(".").pop()?.toLowerCase()??"";return["png","jpg","jpeg","gif","webp","svg","bmp","ico"].includes(t)?"image":["md","txt","pdf","doc","docx","rtf","html"].includes(t)?"document":["mermaid","mmd","dot","puml","plantuml"].includes(t)?"diagram":["csv","tsv","xlsx","xls"].includes(t)?"table":["ts","tsx","js","jsx","py","rs","go","java","c","cpp","h","cs","rb","sh","sql","json","yaml","yml","toml","xml","css","scss","vue","svelte"].includes(t)?"code":"file"}function Jr(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 Qr=/^no (matches|files|results) found(?:\s+for:.*)?\.?$|^file not found|^not found|^0 results|^\(exit code \d+, no output\)$/i,es=new Set(["search","web_search","grep","glob","find","list","read","exec"]),ts=/[A-Za-z]:[\\/](?:[^\s"'`<>|,\uFF0C\u3001;\uFF1B\u3002]+[\\/])*[^\s"'`<>|,\uFF0C\u3001;\uFF1B\u3002]+\.[A-Za-z0-9]{1,12}/g,ns=/(?:^|[\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,os=/(?:^|[\s"'`([{,;:\uFF0C\u3001\uFF1B])([A-Za-z0-9][A-Za-z0-9._-]*\.(?:xlsx|xls|pptx|ppt|docx|pdf|md|markdown|html|css|js|jsx|ts|tsx|json|csv|tsv|png|jpg|jpeg|webp|svg|gif|mp4|mov|wav|mp3|m4a|zip|petdex))(?:$|[\s"'`\])},;:\uFF0C\u3001\uFF1B\u3002])/gi,rs=/\b(?:create|generate|write|produce|save|output|deliver|deliverables?|artifacts?|required|required files?|must generate|self-verify)\b|(?:生成|创建|写入|输出|保存|交付|产物|文件|必须|自检|验证)/i;function Kn(e){if(!es.has(e.toolName))return!1;let t=typeof e.message?.content=="string"?e.message.content.trim():"";return t.length>0&&t.length<200&&Qr.test(t)}function je(e,t){for(let o=e.length-1;o>=0;o--){let n=e[o];if(!n||n.role!=="tool")continue;let r=typeof n.content=="string"?n.content:"";if(r.startsWith("Error: "))return r.slice(7).trim()}}var ss=/\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,Xn=50;function Yn(e){if(!e)return!1;for(let t of e)if(t.role==="user"&&typeof t.content=="string"&&ss.test(t.content))return!0;return!1}var is=/(?:我来|我先|我现在就?|让我先?|接下来我?|我帮你|我这就|我会|我将|我去|我看)[^。.!?!?\n]{0,12}(?:做|搭建?|写|开发|实现|构建|生成|创建|新建|建立|改|修复?|检查|读取?|运行|跑|执行|看一?下?|查看|配置|安装|部署|分析|整理|定位|排查|找)/,as=/\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 Vn(e){let t=e.trim();return t.length===0||t.length>200||t.includes("```")?!1:is.test(t)||as.test(t)}function Zn(e,t){if(typeof e=="number"&&Number.isFinite(e)&&e>=1)return Math.min(Math.round(e),100);let o=qe(t);return o>=3?Math.min(Math.max(25,20+o*15),100):Yn(t)?Math.min(Math.max(25,Xn),100):25}function qe(e){if(!e)return 0;let t=new Set,o=new Set,n=r=>{let s=r.replace(/[),.;:\uFF0C\u3002\uFF1B\u3001]+$/u,"").replace(/\\/g,"/").toLowerCase();t.add(`path:${s}`);let i=s.split("/").pop();i&&o.add(i)};for(let r of e){if(r.role!=="user"||typeof r.content!="string")continue;let s=r.content;for(let i of r.content.matchAll(ts))n(i[0]);if(rs.test(s)){for(let i of s.matchAll(ns)){let a=i[1]?.toLowerCase();if(!a)continue;t.add(`relative:${a.replace(/\\/g,"/")}`);let u=a.replace(/\\/g,"/").split("/").pop();u&&o.add(u)}for(let i of s.matchAll(os)){let a=i[1]?.toLowerCase();!a||o.has(a)||t.add(`name:${a}`)}}}return t.size}function Jn(e,t){if(typeof e=="number"&&Number.isFinite(e)&&e>=1)return Math.min(Math.round(e),100);let o=qe(t);return o>=3?Math.min(Math.max(se,20+o*15),100):Yn(t)?Math.min(Math.max(se,Xn),100):se}function Qn(e){return e.filter(t=>t.role!=="assistant"?!0:!(typeof t.content=="string"&&t.content.trim()===""))}function Et(e,t){let o=[];for(let n=e.length-1;n>=0;n--){let r=e[n];if(r.role==="tool"&&typeof r.content=="string")o.unshift(r.content.slice(0,500));else if(r.role==="assistant"){if(typeof r.content=="string"&&r.content.trim())return t.info("synthesizeFallbackContent: found assistant text, using it"),r.content;break}else break}return o.length>0?(t.info(`synthesizeFallbackContent: synthesized from ${o.length} tool result(s)`),o.join(`
|
|
1
|
+
function tn(e,t,n,o){return{role:"assistant",content:t||null,tool_calls:e,...n&&n.length>0?{thinkingBlocks:n}:{},...o?{reasoning_content:o}:{}}}function z(e,t){let n=t.ok?typeof t.payload=="string"?t.payload:JSON.stringify(t.payload??""):`Error: ${t.error??"Tool execution failed"}`;return{role:"tool",tool_call_id:e,content:n,...!t.ok&&{is_error:!0},...t.toolReferences?.length?{toolReferences:t.toolReferences}:{},...t.imageUrls?.length?{imageUrls:t.imageUrls}:{}}}var ii=/\b(?:daily|weekly|monthly)(?:\/(?:daily|weekly|monthly))* (?:usage )?limit(?:s)?(?: (?:exhausted|reached|exceeded))?\b/i,ke={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]},ai=/^(?:error[:\s-]+)?billing(?:\s+error)?(?:[:\s-]+|$)|^(?:error[:\s-]+)?(?:credit balance|insufficient credits?|payment required|http\s*402\b)/i,li=/["']?(?:status|code)["']?\s*[:=]\s*402\b|\bhttp\s*402\b|\berror(?:\s+code)?\s*[:=]?\s*402\b|^\s*402\s+payment/i,ci=512,ui=/^(?:http\s*)?(\d{3})(?:\s+([\s\S]+))?$/i;var di=new Set([500,502,503,504,521,522,523,524,529]),fi=["insufficient credits","insufficient quota","credit balance","insufficient balance","plans & billing","add more credits","top up"],pi=["upgrade your plan","upgrade plan","current plan","subscription"],mi=["daily","weekly","monthly"],gi=["try again","retry","temporary","cooldown"],hi=["usage limit","rate limit","organization usage"],yi=["organization","workspace"],Ti=["billing period","exceeded","reached","exhausted"],bi=/["']?(?:status|code)["']?\s*[:=]\s*402\b|\bhttp\s*402\b|\berror(?:\s+code)?\s*[:=]?\s*402\b|\b(?:got|returned|received)\s+(?:a\s+)?402\b|^\s*402\s+payment required\b/i,Ci=/^(?:error[:\s-]+)?(?:(?:http\s*)?402(?:\s+payment required)?|payment required)(?:[:\s-]+|$)/i;function Re(e,t){if(!e)return!1;let n=e.toLowerCase();return t.some(o=>o instanceof RegExp?o.test(n):n.includes(o))}function ki(e){return Re(e,ke.format)}function No(e){return Re(e,ke.rateLimit)}function Ri(e){return Re(e,ke.timeout)}function xi(e){return ii.test(e)}function nn(e){let t=e.toLowerCase();return t?e.length>ci?li.test(t):Re(t,ke.billing)?!0:ai.test(e)?t.includes("upgrade")||t.includes("credits")||t.includes("payment")||t.includes("plan"):!1:!1}function Fo(e){return Re(e,ke.authPermanent)}function _i(e){return Re(e,ke.auth)}function Bo(e){return Re(e,ke.overloaded)}function Ce(e,t){return t.some(n=>e.includes(n))}function vi(e){return Ce(e,fi)||Ce(e,pi)&&e.includes("limit")||e.includes("billing hard limit")||e.includes("hard limit reached")||e.includes("maximum allowed")&&e.includes("limit")}function Ai(e){let t=Ce(e,mi),n=e.includes("spend limit")||e.includes("spending limit"),o=Ce(e,yi);return Ce(e,gi)&&Ce(e,hi)||t&&(e.includes("usage limit")||n)||t&&e.includes("limit")&&e.includes("reset")||o&&e.includes("limit")&&(n||Ce(e,Ti))}function wi(e){return e.trim().toLowerCase().replace(Ci,"").trim()}function Do(e){let t=wi(e);return!t||vi(t)?"billing":No(t)||Ai(t)?"rate_limit":"billing"}function Si(e){return bi.test(e)?Do(e):null}function $o(e){let t=e.match(ui);if(!t)return null;let n=Number(t[1]);return Number.isFinite(n)?{code:n,rest:(t[2]??"").trim()}:null}function Mi(e){if(!e)return!1;let t=e.toLowerCase();return t.includes('"type":"api_error"')&&t.includes("internal server error")}function Ei(e){let t=e.trim();if(!t)return!1;let n=$o(t);return n?di.has(n.code):!1}function Uo(e,t){return typeof e!="number"||!Number.isFinite(e)?null:e===402?t?Do(t):"billing":e===429?"rate_limit":e===401||e===403?t&&Fo(t)?"auth_permanent":"auth":e===408?"timeout":e===503?t&&Bo(t)?"overloaded":"timeout":e===502||e===504?"timeout":e===529?"overloaded":e===400?t&&nn(t)?"billing":"format":null}function Ii(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 Pi(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 jo(e){if(Pi(e))return"session_expired";if(Ii(e))return"model_not_found";let t=Si(e);return t||(xi(e)?nn(e)?"billing":"rate_limit":No(e)?"rate_limit":Bo(e)?"overloaded":Ei(e)?$o(e.trim())?.code===529?"overloaded":"timeout":Mi(e)?"timeout":ki(e)?"format":nn(e)?"billing":Ri(e)?"timeout":Fo(e)?"auth_permanent":_i(e)?"auth":null)}var Li={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"},Oi=new Set(["RETRYABLE_TRANSIENT","RETRYABLE_DEGRADED","TOOL_EXECUTION_FAILED"]);function Le(e,t){let n=Uo(e,t)??(t?jo(t):null);return n?Li[n]:typeof e=="number"&&e>=400&&e<500?"NON_RETRYABLE_CONTENT":"RETRYABLE_TRANSIENT"}function on(e){return Oi.has(e)}function qo(e){let t=typeof e.content=="string"?e.content:e.content!=null?JSON.stringify(e.content):"";return Math.ceil(t.length/4)}var Ni=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=qo){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||!Ni.has(a.name)||a.content.length<=200)return a;let p=this.estimateTokens(a);return s+=p,r++,{...a,content:`[result cleared \u2014 ${a.content.length} chars]`}}),droppedCount:r,strategy:"micro-compact",metrics:r>0?{tokensBefore:0,tokensAfter:0,compressionRatio:0,latencyMs:0,usedLlm:!1,cacheInvalidated:!1}:void 0}}};function rn(e,t,n=qo){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 l=r>0?{role:"system",content:`[${r} messages removed by snip]`}:void 0;return{messages:s,tokensFreed:o,removedCount:r,boundaryMessage:l}}function sn(){return{stages:[]}}function an(e,t,n){let o=n?.thresholdMessages??40;if(e.filter(a=>a.role!=="system").length<=o)return{messages:e,stagedCount:0};let s=zo(e,t),l=Fi(s,t,o);if(l.length===0)return{messages:s,stagedCount:0};for(let a of l)t.stages.push(a);return s=zo(e,t),{messages:s,stagedCount:l.length}}function ln(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:Ho(e,t),committed:n}}function zo(e,t){return t.stages.filter(o=>o.committed).length===0?e:Ho(e,t)}function Ho(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,l]=r.range;if(s>=o.length)continue;let a=Math.min(l,o.length),u={role:"system",content:r.summary};o.splice(s,a-s,u)}return o}function Fi(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]}`)),l=-1,a=0;for(let u=0;u<o;u++){let p=e[u];if(p.role==="tool"||p.role==="assistant"&&typeof p.content=="string"&&p.content==="")l<0&&(l=u),a++;else{if(a>=3){let T=`${l}-${l+a}`;s.has(T)||r.push({id:`collapse_${l}_${l+a}`,range:[l,l+a],summary:`[${a} tool results collapsed]`,committed:!1})}l=-1,a=0}}if(a>=3){let u=`${l}-${l+a}`;s.has(u)||r.push({id:`collapse_${l}_${l+a}`,range:[l,l+a],summary:`[${a} tool results collapsed]`,committed:!1})}return r}import{existsSync as un,readFileSync as ur,writeFileSync as Bi,readdirSync as dr,mkdirSync as Di}from"node:fs";import{join as dn,dirname as $i}from"node:path";var me=Math.min(Math.max(1,Number(process.env.TOOL_LOOP_DEFAULT_BUDGET)||25),100),Go=Math.max(1e3,Number(process.env.TOOL_LOOP_TOOL_TIMEOUT_MS)||24e4),Wo=3,Ko=2,ft=2,Xo=128e3,Vo=13e3,Yo=16384,Zo=65536,Jo=3,Qo=65536,cn=500,er=3;var tr=3e4,nr=3,xe=2;var or=20;var rr=3,sr=2,ir=300*1e3,ar=3,lr=720*60*60*1e3;var su=300*1e3;var iu=3600*1e3;var au=50*1024,lu=500*1024,cu=500*1024*1024,uu=50*1024*1024;var du=60*1024;var fr=0;var Ui="skill-patterns.json";function pr(e){return dn(e,".qlogicagent",Ui)}function ji(e){let t=pr(e);try{return JSON.parse(ur(t,"utf8"))}catch{return{version:1,patterns:{}}}}function cr(e,t){let n=pr(e);Di($i(n),{recursive:!0}),Bi(n,JSON.stringify(t,null,2),"utf8")}function qi(e){let t=Date.now()-lr;for(let[n,o]of Object.entries(e.patterns))new Date(o.lastSeen).getTime()<t&&delete e.patterns[n]}function mr(e,t){if(t.length===0)return!1;let n=pt(t),o=ji(e);qi(o);let r=new Date().toISOString(),s=o.patterns[n];if(s||(s={signature:n,count:0,firstSeen:r,lastSeen:r,promoted:!1},o.patterns[n]=s),s.promoted)return cr(e,o),!1;s.count++,s.lastSeen=r;let l=s.count>=ar;return l&&(s.promoted=!0),cr(e,o),l}function pt(e){return[...e].sort().join("+")}function zi(e,t){if(!un(t))return null;let n=pt(e);try{let o=dr(t,{withFileTypes:!0});for(let r of o){if(!r.isDirectory())continue;let s=dn(t,r.name,"SKILL.md");try{let a=ur(s,"utf8").match(/^tools:\s*\n((?:\s+-\s+\S+\n?)+)/m);if(a){let u=a[1].split(`
|
|
2
|
+
`).map(p=>p.replace(/^\s*-\s*/,"").trim()).filter(Boolean);if(pt(u)===n)return r.name}}catch{}}}catch{}return null}function Hi(e){if(!un(e))return 0;try{return dr(e,{withFileTypes:!0}).filter(t=>t.isDirectory()&&un(dn(e,t.name,"SKILL.md"))).length}catch{return 0}}function Gi(e,t){return!(!e.ok||e.existingSkillName||!e.multiStep||e.toolCallCount<rr||e.distinctToolCount<sr||Date.now()-fr<ir||t?.projectSkillsDir&&(Hi(t.projectSkillsDir)>=or||t.tools.length>0&&zi(t.tools,t.projectSkillsDir))||t?.projectRoot&&t.tools.length>0&&!mr(t.projectRoot,t.tools))}function Wi(e){return e.existingSkillName?e.feedback==="negative":!1}function fn(e,t){return Wi(e)?{type:"skill.improve",skillName:e.existingSkillName,reason:"negative user feedback on existing skill execution"}:Gi(e,t)?(fr=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 Ki(e){let t=new Set(e.map(pn).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 pn(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 Xi(e){return e==="enabled-eligible"||e==="installed-awaiting-approval"}function Vi(e){return new Map((e??[]).map(t=>[t.toolName,t]))}function Yi(e){if(!e.eligibility?.length)return[...e.tools];let t=Vi(e.eligibility);return e.tools.filter(n=>{let o=pn(n);if(!o)return!1;let r=t.get(o);return!r||Xi(r.status)})}function Zi(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 mn(e){let t=Zi({toolChoice:e.toolChoice,thinkingEnabled:e.thinkingEnabled,compatibility:e.compatibility}),n=t.normalizedToolChoice,o=[...t.warnings],r=Yi({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:Ki(r),warnings:o}}if(typeof n=="object"&&!Array.isArray(n)&&n.type==="function"){let s=n.function??void 0,l=typeof s?.name=="string"?s.name.trim():"";if(!l)throw new Error("tool_choice.function.name is required");let a=r.filter(u=>pn(u)===l);if(a.length===0)throw new Error(`tool_choice requested unknown tool: ${l}`);return{tools:a,normalizedToolChoice:{type:"function",function:{name:l}},extraSystemPrompt:`You must call the ${l} tool before responding.`,warnings:o}}return{tools:r,normalizedToolChoice:n,warnings:o}}var Ji=["stop","aborted","timeout","cancelled","interrupted","error"],Qi=["tool_calls","toolCalls","function_call","functionCall","raw_tool_calls","rawToolCalls"];function gr(e){return e==null?[]:typeof e=="string"?e.length>0?[{type:"text",text:e}]:[]:Array.isArray(e)?e:[{type:"text",text:String(e)}]}function ea(e,t){return{...e,content:[...gr(e.content),...gr(t.content)]}}function ta(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 na(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=ta(r);if(s.size!==0)for(let l=o+1;l<e.length;l+=1){if(t.has(l))continue;let a=e[l];a?.role==="tool"&&typeof a.tool_call_id=="string"&&s.has(a.tool_call_id)&&(n.push(a),t.add(l))}}return n}function oa(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 ra(e){return new Set((e??Ji).map(t=>t.trim().toLowerCase()))}function sa(e,t){return e?ra(t).has(e.trim().toLowerCase()):!1}function gn(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=>oa(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,...T}=u;T.content!=null&&T.content!==""&&s.push(T);continue}if(p.length<u.tool_calls.length){s.push({...u,tool_calls:p});continue}}s.push(u)}let l=na(s),a=[];for(let u of l){let p=a.length>0?a[a.length-1]:void 0;if(u.role==="user"&&p?.role==="user"){a[a.length-1]=ea(p,u);continue}a.push(u)}return a}function hn(e,t){return sa(t?.stopReason,t?.forcedStopReasons)?e.map(n=>{if(n.role!=="assistant")return{...n};let o={...n};for(let r of Qi)delete o[r];return o}):[...e]}function yn(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 l of s.tool_calls)typeof l.id!="string"||!l.id||o.has(l.id)||(o.add(l.id),r.push({role:"tool",tool_call_id:l.id,content:n}));return r}function Tn(e,t){let n=gn(e),o=hn(n,t);return yn(o,t)}function ia(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 aa(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 la(e){return{round:e.round??0,maxRounds:e.maxRounds,pendingToolCallIds:[...e.pendingToolCallIds??[]],completedToolCallIds:[...e.completedToolCallIds??[]],lastStopReason:e.lastStopReason,replayMessages:[...e.replayMessages??[]]}}function bn(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=gn(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=hn(n,e.options);o.some((s,l)=>s!==n[l])&&t.push({kind:"strip-forced-stop-tool-metadata",detail:"Removed assistant tool-call metadata after forced stop."});let r=yn(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:la({maxRounds:e.maxRounds,round:e.round,lastStopReason:e.lastStopReason,replayMessages:r,pendingToolCallIds:ia(r),completedToolCallIds:aa(r)}),recoveryActions:t}}var ca=new Set(["main","sdk","agent","compact","hook","verification","side_question"]);function Cn(e){return e?ca.has(e):!0}function kn(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 xu={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 Rn(e){return{promptTokens:0,hasAttemptedReactiveCompact:!1,currentMaxOutputTokens:e.maxOutputTokens,consecutiveTruncations:0,aborted:e.abortSignal?.aborted??!1}}function xn(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 _n(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 vn(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 An(e,t){return e.aborted?!0:t.abortSignal?.aborted?(e.aborted=!0,!0):!1}var da={maxConsecutiveFailures:3,minMessagesAfterCompact:4,targetUsagePercent:50};function wn(){return{consecutiveFailures:0,attemptedThisTurn:!1,lastCompactAt:null,toolsAtLastCompact:[]}}function Oe(e,t=da){return!(e.attemptedThisTurn||e.consecutiveFailures>=t.maxConsecutiveFailures)}import{createHash as Pl}from"node:crypto";import{existsSync as Be,readFileSync as ao}from"node:fs";function Sn(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 B(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 hr(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,l=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:l,details:r}}function yr(e,t){if(!t.ok)return[];let n=t.details;if(!n)return[];let o=fa(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 fa(e){let t=typeof e.type=="string"?e.type:"";if(!t)return null;if(t==="three_d_generate")return"3d";let n=t.split("_")[0];return n==="image"||n==="tts"||n==="video"||n==="music"?n:null}var pa=new Set(["write","edit","patch"]);function Tr(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=[],l=ma(r.function.arguments);if(!l)return s;if(pa.has(n.toolName)){let a=ga(l);a&&s.push({type:"artifact",turnId:t,artifactId:`artifact-${n.callId}`,artifactType:ha(a),title:a.split(/[\\/]/).pop()||a,filePath:a,language:ya(a)})}return s}function ma(e){try{return JSON.parse(e)}catch{return null}}function ga(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 ha(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 ya(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 Ta=new Set(["write","edit","patch"]),ba=new Set(["image_generate"]),Ca=/\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 ka=/\b(?:under|inside|in|at|to|root|directory|folder|output directory|output folder)\s+([A-Za-z]:[\\/][^\s"'`<>|]+)|(?:目录|文件夹|根目录|输出到|放到|位于)\s*([A-Za-z]:[\\/][^\s"'`<>|]+)/gi,Mn=/https?:\/\/[^\s"'`<>),;]+/gi,Ra=/\b(?:fatal|timeout|timed out|waitforselector|waiting for locator|strict mode violation|exception|traceback|eaddrinuse|page crashed|browser closed|target closed)\b|鏃犳硶灏唡閿欒|澶辫触|瓒呮椂/i,xa=/\b(?:default vite|vite \+ react|edit src\/app|click on the vite|vite page)\b|默认\s*Vite/i,br=/\b(?:browser|playwright|puppeteer|screenshot|opened|loaded|navigated|visible|locator|page\.goto|http:\/\/127\.0\.0\.1|http:\/\/localhost)\b|(?:浏览器|截图|页面可见|打开页面|加载页面|内置浏览器|自动化)/i;function _a(e){let t=Fn(e);return{artifactRoot:t,rootSource:t?"explicit":void 0,writePaths:[],outOfRootWrites:[],devServerUrls:[],browserVerified:!1,browserEvidence:[],browserFailureEvidence:[]}}function ie(e){return e.some(t=>t.role==="user"&&typeof t.content=="string"&&Ca.test(t.content))}function va(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 Cr(e){return["Done","Not done","Artifacts","Verification","Blockers","Next action"].every(t=>new RegExp(`(^|\\n)${t}:`,"i").test(e))}function xr(e){return["Sourced facts","Assumptions","Recommendations","Unsupported claims"].every(t=>new RegExp(`(^|\\n)${t}:`,"i").test(e))}function Pn(e,t){let n=Pa(t);return n?Ta.has(e)?kr(n.path,n.file_path,n.filePath,n.filename,n.file):ba.has(e)?kr(n.output_path,Array.isArray(n.output_paths)?n.output_paths[0]:void 0):null:null}function _r(e){let t=Pn(e.toolName,e.rawArguments);if(!t||!ie(e.inputMessages))return null;if(!e.state.artifactRoot){let r=Fn(e.inputMessages);r?(e.state.artifactRoot=r,e.state.rootSource="explicit"):(e.state.artifactRoot=Er(t),e.state.rootSource=e.state.artifactRoot?"inferred":void 0)}let n=e.state.artifactRoot;if(!n||e.state.rootSource!=="explicit"||Lr(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 vr(e){let t=Pn(e.toolName,e.rawArguments);return!t||!Fa(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 Ln(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 Ar(e){let t=Pn(e.toolName,e.rawArguments);if(t){if(!e.state.artifactRoot){let o=Fn(e.inputMessages);e.state.artifactRoot=o??Er(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"&&!Lr(t,e.state.artifactRoot)&&Ln(e.state,{path:t,artifactRoot:e.state.artifactRoot,toolName:e.toolName})}let n=`${e.rawArguments}
|
|
3
|
+
${e.content}`;for(let o of n.matchAll(Mn)){let r=In(o[0]);r&&(e.state.devServerUrls.includes(r)||e.state.devServerUrls.push(r))}if(Oa(e.toolName,e.rawArguments,e.content)&&Ir(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&&La(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)}}function On(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 wr(e){let t=_a(e);for(let n of e)n.role!=="assistant"||typeof n.content!="string"||Nn(t,n.content);return t}function Nn(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=ge(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=ge(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 l of r.split(/\s*,\s*/)){let a=ge(l.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 l of s.matchAll(Mn)){let a=In(l[0]);a&&!e.devServerUrls.includes(a)&&e.devServerUrls.push(a)}for(let l of t.matchAll(Mn)){let a=In(l[0]);a&&/^https?:\/\/(?:localhost|127\.0\.0\.1):\d+\//i.test(a)&&(e.devServerUrls.includes(a)||e.devServerUrls.push(a))}}function Sr(e){let t=e.content.trim(),n=ie(e.inputMessages),o=va(e.inputMessages),r=Ba(t),s=t;if(Mr(e.activeTasks??[]).length>0&&(s=Sa(s)),n&&!e.artifactContract.browserVerified&&(s=Ma(s)),!(r&&e.totalToolCallCount===0)&&o&&!xr(s)){let p=Ia(s);s=s?`${s}
|
|
3
4
|
|
|
4
|
-
|
|
5
|
+
${p}`:p}let a=!!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||a)&&!Cr(s)&&!Cr(s)){let p=Aa({...e,content:s,needsBrowser:n,needsResearch:o});s=s?`${s}
|
|
6
|
+
|
|
7
|
+
${p}`:p}return s}function Aa(e){let t=[],n=[],o=Mr(e.activeTasks??[]);if(o.length>0&&(n.push(`Task list still has ${o.length} unresolved item(s): ${o.map(wa).join("; ")}.`),t.push("Update unresolved task items to completed, cancelled, or an explicit blocker before claiming completion.")),e.artifactContract.outOfRootWrites.length>0&&(n.push("Artifact root drift was detected and at least one write was outside the deliverable root."),t.push(...e.artifactContract.outOfRootWrites.slice(0,3).map(p=>`${p.toolName} attempted ${p.path} outside ${p.artifactRoot}.`))),e.needsBrowser&&!e.artifactContract.browserVerified){let p=e.artifactContract.browserFailureEvidence[0];n.push(p?"Browser-visible acceptance was attempted but failed; no passing browser evidence was recorded.":"Browser-visible acceptance was not recorded for this app/frontend deliverable."),t.push(p?`Fix the browser verification failure before claiming completion: ${p}`:"Load the served app in a browser-capable tool and verify visible UI behavior before claiming completion.")}e.needsResearch&&!xr(e.content)&&n.push("Research/report quality audit sections were not separated in the model response.");let r=Ea(e.content,e.blockedToolCalls??[]);r.length>0&&(n.push("The turn stopped with unresolved tool-call blockers instead of completing all requested work."),t.push(...r.slice(0,5).map(p=>`${p.name} blocked by ${p.reason}.`)));let s=e.totalToolCallCount>0?`Ran ${e.totalToolCallCount} tool call${e.totalToolCallCount===1?"":"s"} (${[...e.distinctToolNames].join(", ")||"unknown tools"}).`:"No tool work was recorded.",l=[e.artifactContract.artifactRoot?`artifactRoot: ${ge(e.artifactContract.artifactRoot)}`:"artifactRoot: not declared",e.artifactContract.writePaths.length>0?`files: ${e.artifactContract.writePaths.slice(0,8).map(ge).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.":"No browser acceptance required for this request.",u=t.length>0?"Resolve the blocker(s), then rerun verification and issue a new final status.":"Proceed with user review or requested follow-up.";return["Done:",`- ${s}`,"","Not done:",...n.length>0?n.map(p=>`- ${p}`):["- None recorded."],"","Artifacts:",...l.map(p=>`- ${p}`),"","Verification:",`- ${a}`,"","Blockers:",...t.length>0?t.map(p=>`- ${p}`):["- None recorded."],"","Next action:",`- ${u}`].join(`
|
|
8
|
+
`)}function Mr(e){return e.filter(t=>t.status!=="completed")}function wa(e){return`#${e.id} ${e.title} (${e.status})`}function Sa(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 Ma(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 Ea(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 Ia(e){let t=/\b(?:source|citation|cited|http|https|来源|引用)\b/i.test(e),n=/\b(?:recommend|strategy|should|go|no-go|risk|mitigation|建议|策略|风险|缓解)\b/i.test(e),o=/\b(?:assum|uncertain|unknown|gap|unsupported|verify|need|缺口|假设|不确定|未验证|需确认)\b/i.test(e);return["Sourced facts:",t?"- Source-backed claims are present in the response and must remain tied to the cited URLs or named evidence.":"- No clearly source-backed facts were isolated; treat factual claims as unsupported until evidence is added.","","Assumptions:",o?"- Assumptions, uncertainties, or verification gaps are explicitly called out in the response.":"- No explicit assumptions were separated; reviewer should treat missing premises as open gaps.","","Recommendations:",n?"- Recommendations are present and should be read as advice conditioned on the stated evidence and assumptions.":"- No recommendation section was clearly separated.","","Unsupported claims:","- Any claim without visible evidence must be treated as unsupported until reviewed."].join(`
|
|
9
|
+
`)}function Pa(e){try{return JSON.parse(e)}catch{return null}}function kr(...e){for(let t of e)if(typeof t=="string"&&t.trim())return t.trim();return null}function Fn(e){for(let t of e)if(!(t.role!=="user"||typeof t.content!="string"))for(let n of t.content.matchAll(ka)){let o=n[1]??n[2],r=Tt(o??"");if(r&&!Na(r))return ge(r)}}function Er(e){let t=ge(Tt(e));if(!t)return;let n=t.toLowerCase();if(n.endsWith("/package.json"))return Rr(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 Rr(t)}function La(e,t,n){if(/^read$/i.test(e)||n.includes("<persisted-output>")||Ir(n)||/\b(?:syntax error|command not found|cannot find|not recognized|failed|failure|exception|traceback|eaddrinuse)\b|无法将|错误|失败/i.test(n))return!1;let o=br.test(n),r=/\b(?:playwright|puppeteer|browser|screenshot|locator|page\.goto|dom snapshot|visible text|assertion)\b|浏览器|截图|可见|定位器/i.test(`${t}
|
|
10
|
+
${n}`),s=Pr(e)&&br.test(t)&&o&&r&&/\b(?:ok|success|passed|loaded|visible|rendered|found|present|assertion passed)\b|可见|加载成功|通过/i.test(n),l=/\b(?:200|ok|success|passed|loaded|visible|rendered|found|present|assertion passed)\b|可见|加载成功|通过/i.test(n);return!(!s&&!(o&&r&&l)||xa.test(n)&&!/\b(?:absent|removed|not present|gone|没有|不是默认|已移除)\b/i.test(n))}function Oa(e,t,n){return/^read$/i.test(e)||!Pr(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 Ir(e){return/\b(?:no failed|0 failed|without failed|no failures|failure:? none|failed checks?:? none)\b/i.test(e)?!1:Ra.test(e)?!0:/\b(?:fail|failed|failure|error)\b/i.test(e)}function Pr(e){return/^(?:exec|bash|shell|powershell|terminal|playwright|browser|computer)$/i.test(e)}function Na(e){return/\.[A-Za-z0-9]{1,12}$/.test(e)}function Lr(e,t){let n=En(e),o=En(t);return n===o||n.startsWith(`${o}/`)}function Fa(e){return En(e).split("/").includes("context-pack")}function En(e){return Tt(e).replace(/\\/g,"/").replace(/\/+/g,"/").replace(/\/$/u,"").toLowerCase()}function ge(e){return Tt(e).replace(/\\/g,"/").replace(/\/+/g,"/").replace(/\/$/u,"")}function In(e){let t=e.replace(/[).,;]+$/u,"");if(t.endsWith(":"))return null;try{let n=new URL(t);return n.protocol!=="http:"&&n.protocol!=="https:"||!n.hostname?null:t}catch{return null}}function Tt(e){return e.trim().replace(/[).,;:,。;、:]+$/u,"")}function Ba(e){return/^[A-Z0-9_ -]{6,80}$/.test(e.trim())}function Rr(e){let t=ge(e),n=t.lastIndexOf("/");return n>0?t.slice(0,n):t}var Da=/^no (matches|files|results) found(?:\s+for:.*)?\.?$|^file not found|^not found|^0 results|^\(exit code \d+, no output\)$/i,$a=new Set(["search","web_search","grep","glob","find","list","read","exec"]),Ua=/[A-Za-z]:[\\/](?:[^\s"'`<>|,\uFF0C\u3001;\uFF1B\u3002]+[\\/])*[^\s"'`<>|,\uFF0C\u3001;\uFF1B\u3002]+\.[A-Za-z0-9]{1,12}/g,ja=/(?:^|[\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,qa=/(?:^|[\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,za=/\b(?:create|generate|write|produce|save|output|deliver|deliverables?|artifacts?|required|required files?|must generate|self-verify)\b|(?:生成|创建|写入|输出|保存|交付|产物|文件|必须|自检|验证)/i;function Or(e){if(!$a.has(e.toolName))return!1;let t=typeof e.message?.content=="string"?e.message.content.trim():"";return t.length>0&&t.length<200&&Da.test(t)}function bt(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 Ha=/\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,Nr=50,Fr=90;function Br(e){if(!e)return!1;for(let t of e)if(t.role==="user"&&typeof t.content=="string"&&Ha.test(t.content))return!0;return!1}var Ga=/(?:我来|我先|我现在就?|让我先?|接下来我?|我帮你|我这就|我会|我将|我去|我看)[^。.!?!?\n]{0,12}(?:做|搭建?|写|开发|实现|构建|生成|创建|新建|建立|改|修复?|检查|读取?|运行|跑|执行|看一?下?|查看|配置|安装|部署|分析|整理|定位|排查|找)/,Wa=/\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 Dr(e){let t=e.trim();return t.length===0||t.length>200||t.includes("```")?!1:Ga.test(t)||Wa.test(t)}function $r(e,t){if(typeof e=="number"&&Number.isFinite(e)&&e>=1)return Math.min(Math.round(e),100);let n=Ct(t);return n>=3?Math.min(Math.max(25,20+n*15),100):ie(t??[])?Math.min(Math.max(25,Fr),100):Br(t)?Math.min(Math.max(25,Nr),100):25}function Ct(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 l=s.split("/").pop();l&&n.add(l)};for(let r of e){if(r.role!=="user"||typeof r.content!="string")continue;let s=r.content;for(let l of r.content.matchAll(Ua))o(l[0]);if(za.test(s)){for(let l of s.matchAll(ja)){let a=l[1]?.toLowerCase();if(!a)continue;t.add(`relative:${a.replace(/\\/g,"/")}`);let u=a.replace(/\\/g,"/").split("/").pop();u&&n.add(u)}for(let l of s.matchAll(qa)){let a=l[1]?.toLowerCase();!a||n.has(a)||t.add(`name:${a}`)}}}return t.size}function Ur(e,t){if(typeof e=="number"&&Number.isFinite(e)&&e>=1)return Math.min(Math.round(e),100);let n=Ct(t);return n>=3?Math.min(Math.max(me,20+n*15),100):ie(t??[])?Math.min(Math.max(me,Fr),100):Br(t)?Math.min(Math.max(me,Nr),100):me}function jr(e){return e.filter(t=>t.role!=="assistant"?!0:!(typeof t.content=="string"&&t.content.trim()===""))}function Bn(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
|
+
|
|
12
|
+
`)):""}function Dn(e,t){let n=bt(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}
|
|
5
13
|
|
|
6
14
|
\u6700\u540E\u4E00\u6B21\u5DE5\u5177\u9519\u8BEF\uFF1A
|
|
7
|
-
${
|
|
15
|
+
${n}
|
|
8
16
|
|
|
9
|
-
\u8BF7\u6839\u636E\u4E0A\u9762\u7684\u9519\u8BEF\u4FEE\u6B63\u540E\u91CD\u8BD5\uFF0C\u6216\u6362\u4E00\u79CD\u5B9E\u73B0\u65B9\u5F0F\u3002`:`${
|
|
17
|
+
\u8BF7\u6839\u636E\u4E0A\u9762\u7684\u9519\u8BEF\u4FEE\u6B63\u540E\u91CD\u8BD5\uFF0C\u6216\u6362\u4E00\u79CD\u5B9E\u73B0\u65B9\u5F0F\u3002`:`${o}
|
|
10
18
|
|
|
11
|
-
\u8BF7\u91CD\u8BD5\uFF0C\u6216\u6362\u4E00\u79CD\u5B9E\u73B0\u65B9\u5F0F\u3002`}function
|
|
19
|
+
\u8BF7\u91CD\u8BD5\uFF0C\u6216\u6362\u4E00\u79CD\u5B9E\u73B0\u65B9\u5F0F\u3002`}function qr(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 l of s){let a=l;if(a.id!==n)continue;let u=a.function;typeof u?.arguments=="string"&&(o=$n(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
|
|
12
20
|
|
|
13
|
-
`+(
|
|
21
|
+
`+(o?`\u6700\u540E\u4E00\u6B21\u8C03\u7528\uFF1A${o}
|
|
14
22
|
`:"")+`\u6700\u540E\u4E00\u6B21\u9519\u8BEF\uFF1A
|
|
15
23
|
${t}
|
|
16
24
|
|
|
17
|
-
\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
|
|
18
|
-
`,t),e.lastIndexOf(";",t),e.lastIndexOf("\u3002",t),e.lastIndexOf("\uFF1B",t))+1,r=e.slice(
|
|
19
|
-
`).replace(/\\/g,"/").toLowerCase()}function
|
|
20
|
-
|
|
21
|
-
\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 Q(e,t,o,n){return{reason:e,messages:[...t,o,n],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}}}function Ht(e){let t=e.inputMessages.find(g=>g.role==="user"),o=typeof t?.content=="string"?t.content:"",n=ls.test(o),r=e.distinctToolNames.has("write")||e.distinctToolNames.has("edit"),s=Re(e.inputMessages),i=Dt(e.inputMessages),a=As(e.inputMessages,s,i),u=s.done!==void 0&&e.finalText.includes(s.done)||s.fail!==void 0&&e.finalText.includes(s.fail)||i!==void 0&&e.finalText.includes(i),p=a.length===0||a.some(g=>e.finalText.trimStart().startsWith(g)),f=$t(e.inputMessages,s),m=Bt(e.inputMessages,e.messages);if(m.length>0&&e.totalToolCallCount>0){if(s.fail!==void 0&&e.finalText.includes(s.fail))return null;e.log.info(`explicit required file verification: ${m.length} file(s) missing`);let g=Ot(e.inputMessages),T={role:"user",content:`Before completing, verify that every explicitly requested output file exists and is non-empty. Missing required output file evidence: ${m.join(", ")}. Create the missing files now, or if you cannot complete them, respond with ${g??"FAIL"} and the real reason. Do not claim completion until the missing files are handled.`};return Q("explicit_required_file_verification",e.messages,J(e.finalText,e.thinkingBlocks),T)}let C=To(e.inputMessages,e.messages);if(C.length>0&&e.totalToolCallCount>0){if(s.fail!==void 0&&e.finalText.includes(s.fail))return null;e.log.info(`explicit extra file verification: ${C.length} unexpected file(s)`);let g=Ot(e.inputMessages),T={role:"user",content:`The latest request asked for exactly the listed output artifacts, but extra files were produced under the output root: ${C.join(", ")}. Remove the extra files now, move scratch work outside the deliverable directory, or if you cannot make the output exact, respond with ${g??"FAIL"} and the real reason. Do not claim completion while extra deliverables remain.`};return Q("explicit_extra_file_verification",e.messages,J(e.finalText,e.thinkingBlocks),T)}let M=ho({inputMessages:e.inputMessages,messages:e.messages,finalText:e.finalText});if(M.length>0&&e.totalToolCallCount>0){if(s.fail!==void 0&&e.finalText.includes(s.fail))return null;e.log.info(`artifact index evidence verification: ${M.length} issue(s)`);let g=f??s.done??i??"the requested marker",T={role:"user",content:"Before completing, correct the artifact index against the actual evidence scope. "+M.map(b=>b.detail).join(" ")+` Use the exact requested Goal row labels, cite concrete evidence names/paths for status claims, and mark a row as not verified/unknown instead of claiming exhaustive absence without scoped evidence. Do not claim all checks pass while any row is failed, partial, missing, or unverified. After correcting and verifying the file, reply exactly with ${g}.`};return Q("artifact_index_evidence_verification",e.messages,J(e.finalText,e.thinkingBlocks),T)}if(a.length>0&&e.totalToolCallCount>0&&!p){e.log.info("final marker verification: explicit final marker was not at the start of the response");let g={role:"user",content:`The requested output file evidence is present, but your final response did not start with the explicit completion marker. Your final response must start with one of the requested final markers: ${a.join(" or ")}. No preface, heading, markdown emphasis, or summary may appear before the marker.`};return Q("final_marker_verification",e.messages,J(e.finalText,e.thinkingBlocks),g)}if((s.done!==void 0||i!==void 0)&&e.totalToolCallCount>0&&!u){e.log.info("final marker verification: explicit final DONE/FAIL marker missing");let g=s.done??i,T={role:"user",content:"The requested output file evidence is present, but your final response omitted the explicit completion marker. "+(s.done?`If you have verified the artifacts, Reply exactly with ${s.done}. `:`Your final response must include marker ${g} and clearly say whether the run passed or failed. `)+(s.fail?`If verification failed, reply with ${s.fail} and the real reason. `:`If verification failed, reply with FAIL ${g??""} and the real reason. `)+"Do not end the turn without one of the requested final markers."};return Q("final_marker_verification",e.messages,J(e.finalText,e.thinkingBlocks),T)}if(f!==void 0&&e.finalText.trim()!==f){e.log.info("final marker verification: exact-only final marker response had extra text");let g={role:"user",content:`Reply exactly with ${f} and no other text.`};return Q("final_marker_verification",e.messages,J(e.finalText,e.thinkingBlocks),g)}if(u&&r||e.stopHookActive)return null;if(n&&!r){e.log.info("AP1 action-verification: user requested file action but no write/edit tool was called, injecting nudge"),e.totalToolCallCount>0&&Ss(e.messages);let g={role:"user",content:e.totalToolCallCount===0?"You described what to do but did not actually call any tool to write or edit a file. Please use the write or edit tool now to perform the requested action. Do not just describe the changes - actually make them.":"You used shell commands but did not call the write or edit tool to create/modify the file. Shell commands may fail on this platform. Please use the write tool directly to create the requested file with the correct content."};return Q("file_action_verification",e.messages,J(e.finalText,e.thinkingBlocks),g)}if(e.totalToolCallCount>=3&&e.distinctToolNames.has("write")&&e.messages.filter(vs).length>=3){e.log.info("AP3 verification nudge: 3+ files created, injecting completeness check");let T={role:"user",content:"You created multiple files. Before completing, verify: (1) All imports between your files resolve to real exports. (2) No TODO, placeholder, or 'not implemented' stubs remain. (3) Functions that are imported are actually called, not just declared. If everything is correct, confirm completion. If not, fix the issues now."};return Q("multi_file_skeleton_verification",e.messages,J(e.finalText,e.thinkingBlocks),T)}return null}function Es(e,t){return{role:"assistant",content:e,...t.length>0&&{thinkingBlocks:[...t]}}}async function Ro(e){if(!e.hooks)return null;let t=await e.hooks.invoke("stop",{sessionId:e.sessionId,reason:"completed"});if(t.action==="prevent")return e.log.info(`stop hook prevented continuation: ${t.reason??"no reason"}`),{action:"end",content:e.finalText};if(t.action==="abort"){let o=t.reason??"Stop hook requested continuation";e.log.info(`stop hook blocking: ${o}`);let n={role:"user",content:o};return{action:"continue",messages:[...e.messages,Es(e.finalText,e.thinkingBlocks),n],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}}}return null}var ws=5;function Is(e){return e.inputTokens+e.outputTokens+(e.reasoningTokens??0)}function Ps(e,t){return{role:"assistant",content:e,...t.length>0&&{thinkingBlocks:[...t]}}}function bo(e){if(!e.tokenBudget||e.tokenBudget<=0||e.budgetContinuationCount>=ws)return null;let t=Is(e.totalUsage),o=t/e.tokenBudget*100,n=t-e.lastBudgetGlobalTokens;if(e.budgetContinuationCount>=vn&&n<ut&&e.lastBudgetDeltaTokens<ut)return e.log.info(`token budget early stop: diminishing returns at ${Math.round(o)}% (delta=${n})`),null;if(o>=90)return null;let s=e.budgetContinuationCount+1,i={role:"user",content:e.getBudgetContinuationMessage(o,t,e.tokenBudget)};return e.log.info(`token budget continuation #${s}: ${Math.round(o)}% used`),{messages:[...e.messages,Ps(e.finalText,e.thinkingBlocks),i],budgetContinuationCount:s,lastBudgetDeltaTokens:n,lastBudgetGlobalTokens:t,recoveryDetail:`${Math.round(o)}% used (#${s})`,transition:{reason:"token_budget_continuation"}}}function zt(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 mt(t,{tools:[...e.distinctToolNames],projectRoot:e.projectRoot})}function xo(e,t){let o=[],n=[];for(let r of e){let s=t.get(r.function.name)??0;s>=Fe?n.push({call:r,failCount:s,error:`Tool "${r.function.name}" has failed ${s} times this turn with different arguments. The target likely does not exist. Stop trying variations and report the issue to the user.`}):o.push(r)}return{allowed:o,blocked:n}}function _o(){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 Mo(e){if(e.ok&&!e.softEmpty)return;let t=e.toolFailureCounts.get(e.toolName)??0;e.toolFailureCounts.set(e.toolName,t+1)}function Ao(e){let t=[];for(let[o,n]of e.toolFailureCounts)n>=Fe&&(e.snapshot.get(o)??0)<Fe&&t.push({role:"user",content:`Tool "${o}" has now failed/returned empty results ${n} times with different arguments. The target clearly does not exist. Do NOT call "${o}" again. Report the result to the user immediately.`});return t}function Os(e,t){if(e.length!==1||e[0]?.function.name!=="stt")return!1;let o=[...t].reverse().find(i=>i.role==="user");if(!o)return!1;let n=Array.isArray(o.audioUrls)&&o.audioUrls.some(i=>typeof i=="string"&&i.trim()),r=typeof o.content=="string"?o.content:"",s=/\b(?:stt|speech[-\s]?to[-\s]?text|transcribe|transcription|audio[-\s]?to[-\s]?text)\b|转写|转录|语音转文字|音频转文字|听写/i.test(r);return n&&s}function Fs(e,t){let o=Ns(t);if(!o)return null;let n=Bs(o);if(!n)return null;let r=[...e].reverse().find(a=>a.role==="user"),s=typeof r?.content=="string"?r.content:"",i=/\bAUDIO_STT_RESULT\s+([^\s<]+)\s+<transcription\b/i.exec(s);return i?.[1]?`AUDIO_STT_RESULT ${i[1]} ${n}`:n}function Ns(e){let t=[e.details?.transcription,e.details?.text,e.details?.preview];for(let n of t)if(typeof n=="string"&&n.trim())return n.trim();let o=e.message?.content;return typeof o=="string"?o.trim():""}function Bs(e){return e.toLocaleLowerCase().replace(/[^\p{L}\p{N}\s]+/gu," ").replace(/\s+/g," ").trim()}var Gt=new Set(["read","search"]),Ds=new Set(["write","edit","patch","image_generate"]);function $s(e){e.identicalSuccessfulToolResults.clear();for(let t of[...e.identicalCallCounts.keys()]){let o=t.slice(0,t.indexOf("::"));Gt.has(o)&&e.identicalCallCounts.delete(t)}}async function*vo(e,t,o,n){let{turnId:r,sessionId:s,messages:i,tools:a,model:u,apiKey:p,temperature:f=0,hooks:m,signal:C}=e,M={sessionId:s,turnId:r},g=e.maxTurns??0,T=e.querySource,b=e.runtimePorts.resolveToolEligibility(a,e.toolEligibilityContext),R=b.eligibleTools;for(let y of b.blockedTools)yield{type:"tool_blocked",turnId:r,callId:"",name:y.toolName,reason:"blocked-by-policy"};let A=Zn(e.maxRounds,i),L=Jn(e.maxToolCalls,i),xe=!(typeof e.maxRounds=="number"&&e.maxRounds>=1)&&!(typeof e.maxToolCalls=="number"&&e.maxToolCalls>=1),We=qe(i),H={contextWindowTokens:e.contextWindowTokens??Rn,responseBufferTokens:bn,maxOutputTokens:e.maxOutputTokens??xn,abortSignal:C,reactiveCompactEnabled:!0,outputEscalationEnabled:!0},w=new Set,O=0,pe=0,me=0,_e=0,W=R,Lo=Os(R,i),Me,Ke=!1,Wt=0,Kt=0,Xe=!1,Ae=!1,c={messages:[...i],maxOutputTokensRecoveryCount:0,hasAttemptedReactiveCompact:!1,maxOutputTokensOverride:void 0,turnCount:1,transition:void 0,guardState:bt(H),reactiveCompactState:vt(),toolLoopState:De({maxRounds:A,replayMessages:[...i]}).state,consecutiveFailedRounds:0,finalText:"",totalUsage:{inputTokens:0,outputTokens:0},collapseStore:at(),currentModel:u,consecutive529Errors:0,consecutiveApiRetries:0,stopHookActive:void 0,lastResponseId:void 0,snipRemovedIds:new Set,contentReplacementState:e.runtimePorts.createContentReplacementState(),budgetContinuationCount:0,finalMarkerEmptyRecoveryCount:0,repeatedToolFailureRecoveryCount:0,lastBudgetDeltaTokens:0,lastBudgetGlobalTokens:0,identicalCallCounts:new Map,identicalSuccessfulToolResults:new Map,toolFailureCounts:new Map,fileReadCounts:new Map,recoveryTrace:new Map},Ye=Math.max(g*5,200),Xt=0,I=(y,N)=>(c.recoveryTrace.set(y,(c.recoveryTrace.get(y)??0)+1),{type:"recovery",turnId:r,action:y,detail:N}),F=y=>({type:"end",turnId:r,content:y,usage:c.totalUsage,model:c.currentModel,...c.recoveryTrace.size>0?{recoveryTrace:Object.fromEntries(c.recoveryTrace)}:{}}),ve=(y,N)=>{let K=Ut({inputMessages:i,messages:y});if(K)return K;if(c.finalText.trim()===""){let U=be({inputMessages:i,reason:N});if(U)return U}return c.finalText||Et(y,n)},Oo=(y,N,K)=>{let U=ae({inputMessages:i,messages:N,reason:K});if(U)return U;if(y.trim()===""){let v=be({inputMessages:i,reason:K});if(v)return v}return y||Et(N,n)};for(;;){if(Xt++,Xt>Ye){n.info(`hard iteration cap reached (${Ye}), forcing completion`);let l=ve(c.messages,`hard iteration cap reached (${Ye}) before producing the requested final marker`);yield F(l);return}let{messages:y,maxOutputTokensRecoveryCount:N,maxOutputTokensOverride:K,turnCount:U,guardState:v,reactiveCompactState:z,collapseStore:Ve}=c,{toolLoopState:B}=c;if(Me){try{let l=await Me;l&&(yield{type:"tool_use_summary",turnId:r,summary:l})}catch{}Me=void 0}if(e.refreshTools&&U>1){let l=e.refreshTools();l!==W&&(W=l,n.debug(`tools refreshed: ${l.length} tools`))}if(At(v,H)){n.info(`turn aborted by guard at turn ${U}`),yield{type:"error",turnId:r,error:"Turn aborted",code:"ABORTED",usage:c.totalUsage};return}let ee=xt(v,H);if(ee.level==="blocking"){ee.reason==="prompt_too_long"&&ce(z)&&(z.attemptedThisTurn=!0,v.hasAttemptedReactiveCompact=!0,n.info(`token budget blocking (${ee.reason}), reactive compact needed`),yield I("reactive_compact","token budget pre-check")),n.info(`token budget blocking (${ee.reason}), ending tool loop`);break}ee.level==="warning"&&n.info(`token budget warning: ${ee.usagePercent}% used, ${ee.remainingTokens} remaining`);let Se=yield*so({messages:y,contentReplacementState:c.contentReplacementState,snipRemovedIds:c.snipRemovedIds,collapseStore:Ve,guardState:v,guardConfig:H,runtimePorts:e.runtimePorts,hooks:m,hookCtx:M,sessionId:s,currentModel:c.currentModel,log:n,recovery:I,onAutocompact:()=>{c.hasAttemptedReactiveCompact=!1}}),Fo=Xe?"required":e.toolChoice==="required"&&Ke?"auto":e.toolChoice??"auto";Xe=!1;let fe=ft({tools:W,toolChoice:Fo}),ge=De({maxRounds:A,replayMessages:Se,lastStopReason:B.lastStopReason,options:{stopReason:B.lastStopReason}}),Yt=fe.extraSystemPrompt?[{role:"system",content:fe.extraSystemPrompt},...ge.state.replayMessages]:ge.state.replayMessages;B=ge.state,ge.recoveryActions.length>0&&n.debug(`tool loop recovery: ${ge.recoveryActions.map(l=>l.detail??l.kind).join("; ")}`),n.debug(`turn ${U}, messages: ${Yt.length}`),E(m,"turn.before_inference",{...M,model:c.currentModel},n);let Ze=!1,Je=[],Vt=new Map,Zt="stop",D,x=null,Ee=!1,Jt=!1,ye=[],G=[];try{for await(let l of t.stream({model:c.currentModel,messages:Yt,...fe.tools.length>0?{tools:fe.tools,toolChoice:fe.normalizedToolChoice??"auto"}:{},temperature:f,maxTokens:(K??v.currentMaxOutputTokens)||void 0,streamRequired:e.streamRequired,previousResponseId:Ae?void 0:c.lastResponseId,reasoning:e.reasoning,promptCacheKey:e.promptCacheKey,promptCacheRetention:e.promptCacheRetention,serviceTier:e.serviceTier,openaiBuiltinTools:e.openaiBuiltinTools,maxToolCalls:e.maxToolCalls,parallelToolCalls:e.parallelToolCalls,textVerbosity:e.textVerbosity},p,C))switch(l.type){case"delta":Je.push(l.text);break;case"tool_call_delta":Ze=!0,St(Vt,l);break;case"reasoning_delta":ye.push(l.text);break;case"reasoning_block_complete":l.signature&&G.push({thinking:ye.join(""),signature:l.signature}),ye.length=0;break;case"usage":D={inputTokens:l.promptTokens,outputTokens:l.completionTokens,reasoningTokens:l.reasoningTokens,cacheRead:l.cacheReadTokens,cacheWrite:l.cacheCreationTokens};break;case"response_id":Ae||(c.lastResponseId=l.id);break;case"annotations":yield{type:"annotations",turnId:r,annotations:l.annotations};break;case"builtin_tool_status":yield{type:"heartbeat",turnId:r,message:`${l.toolType}: ${l.event}`};break;case"done":Jt=!0,Zt=l.finishReason;break}if(Ze||E(m,"turn.after_inference",{...M,model:c.currentModel},n),e.postSamplingHooks&&e.postSamplingHooks.length>0){let l=c.currentModel;for(let d of e.postSamplingHooks)try{d({messages:[...Se],model:l,sessionId:s})}catch{}}}catch(l){let d=yield*io(l,{state:c,guardState:v,fallbackModel:e.fallbackModel,signal:C,querySource:T,turnId:r,log:n,emitRecovery:I});if(d.kind==="return")return;if(d.kind==="continue"){c={...c,...d.patch};continue}x=d.streamError}if(!x&&!Jt){let l="LLM stream closed before a terminal event; the response was likely truncated upstream.";E(m,"stop.failure",{sessionId:s,reason:"RETRYABLE_TRANSIENT",error:l},n),yield{type:"error",turnId:r,error:l,code:"RETRYABLE_TRANSIENT",usage:c.totalUsage};return}if(x&&E(m,"turn.after_inference",{...M,model:c.currentModel,response:{error:x.message}},n),x){if(!Ae&&c.lastResponseId&&/previous_response_id not found/i.test(x.message)){let l=(c.consecutiveApiRetries??0)+1;if(l<=ie){n.info("previous_response_id not found \u2014 disabling response-id chaining, retrying statelessly"),yield I("stateless_retry","previous_response_id not found; replaying full history"),Ae=!0,c={...c,lastResponseId:void 0,consecutiveApiRetries:l,transition:void 0};continue}}if(Pt(x))Ee=!0,n.info(`withheld prompt_too_long error (status=${x.status})`);else if(Lt(x))Ee=!0,n.info(`withheld media_size error (status=${x.status})`);else{let l=_t({status:x.status??500,message:x.message},v,H);if(l.action==="reactive_compact"&&ce(z)&&(z.attemptedThisTurn=!0,v.hasAttemptedReactiveCompact=!0,yield I("reactive_compact",`API ${x.status??500}: ${x.message}`)),l.action==="retry"){let h=(c.consecutiveApiRetries??0)+1;if(h>ie){n.info(`API retry limit reached (${ie}), aborting`);let k=le(x.status,x.message);yield{type:"error",turnId:r,error:x.message,code:k,usage:c.totalUsage};return}yield I("retry",l.reason),c={...c,consecutiveApiRetries:h,transition:void 0};continue}let d=le(x.status,x.message);E(m,"stop.failure",{sessionId:s,reason:d,error:x.message},n),yield{type:"error",turnId:r,error:x.message,code:d,usage:c.totalUsage};return}}D&&(c.totalUsage.inputTokens+=D.inputTokens,c.totalUsage.outputTokens+=D.outputTokens,D.reasoningTokens&&(c.totalUsage.reasoningTokens=(c.totalUsage.reasoningTokens??0)+D.reasoningTokens),D.cacheRead&&(c.totalUsage.cacheRead=(c.totalUsage.cacheRead??0)+D.cacheRead),D.cacheWrite&&(c.totalUsage.cacheWrite=(c.totalUsage.cacheWrite??0)+D.cacheWrite)),D?.inputTokens&&(v.promptTokens=D.inputTokens);let we=Je.join(""),j=[...Vt.values()].map((l,d)=>({id:l.id||`tc_${r}_${d}`,type:"function",function:{name:l.name,arguments:l.arguments}}));if(j.length===0&&!Ze){if(we&&(c.finalText=we),e.toolChoice==="required"&&!Ke&&W.length>0&&Wt<2){Wt++;let _=W.map(P=>P.function.name).filter(Boolean).slice(0,8).join(", ");c={...c,messages:[...y,{role:"user",content:`You must call one available tool before answering. Available tools for this request: ${_}. Do not answer from memory, prior context, or guesses.`}],finalText:"",transition:{reason:"next_turn"}};continue}if(Ee&&x&&Pt(x)){if(c.transition?.reason!=="collapse_drain_retry"){let _=ct(Se,Ve);if(_.committed>0){n.info(`collapse drain: committed ${_.committed} stages`),yield I("collapse_drain",`${_.committed} stages committed`),c={...c,messages:_.messages,transition:{reason:"collapse_drain_retry",committed:_.committed}};continue}}if(ce(z)){z.attemptedThisTurn=!0,v.hasAttemptedReactiveCompact=!0,n.info("withheld 413: reactive compact attempt"),yield I("reactive_compact","withheld prompt_too_long"),c={...c,hasAttemptedReactiveCompact:!0,transition:{reason:"reactive_compact_retry"}};continue}n.info("withheld 413: recovery exhausted, surfacing error"),E(m,"stop.failure",{sessionId:s,reason:"prompt_too_long",error:x.message},n),yield{type:"error",turnId:r,error:x.message,code:"PROMPT_TOO_LONG",usage:c.totalUsage};return}if(Ee&&x&&Lt(x)){if(ce(z)){z.attemptedThisTurn=!0,v.hasAttemptedReactiveCompact=!0,n.info("withheld media error: reactive compact strip-retry"),yield I("reactive_compact","media error strip-retry"),c={...c,hasAttemptedReactiveCompact:!0,transition:{reason:"reactive_compact_retry"}};continue}n.info("withheld media error: recovery exhausted"),E(m,"stop.failure",{sessionId:s,reason:"media_error",error:x.message},n),yield{type:"error",turnId:r,error:x.message,code:"IMAGE_ERROR",usage:c.totalUsage};return}if(no(Zt)){v.consecutiveTruncations+=1;let _=e.modelMaxOutputTokens??_n,P=Mt(v,H,_);if(P.shouldEscalate&&K===void 0){v.currentMaxOutputTokens=P.newMax,n.info(`max_output_tokens escalate: ${P.newMax} tokens`),yield I("output_escalation",`${P.newMax} tokens`),c={...c,maxOutputTokensOverride:An,transition:{reason:"max_output_tokens_escalate"}};continue}if(N<Mn){let Y={role:"user",content:"Output token limit hit. Resume directly - no apology, no recap of what you were doing. Pick up mid-thought if that is where the cut happened. Break remaining work into smaller pieces."};n.info(`max_output_tokens recovery #${N+1}`),yield I("max_output_tokens_recovery",`attempt ${N+1}`),c={...c,messages:[...Se,Y],maxOutputTokensRecoveryCount:N+1,maxOutputTokensOverride:void 0,transition:{reason:"max_output_tokens_recovery",attempt:N+1}};continue}n.info("max_output_tokens recovery exhausted, completing with partial content")}else v.consecutiveTruncations=0;B=Be(B,{replayMessages:y,lastStopReason:"completed"});let l=await Ro({hooks:m,sessionId:s,messages:y,finalText:c.finalText,thinkingBlocks:G,log:n});if(l?.action==="end"){let _=Oo(l.content,y,"stop hook prevented continuation before producing the requested final marker");yield F(_);return}if(l?.action==="continue"){c={...c,messages:l.messages,stopHookActive:l.stopHookActive,transition:l.transition};continue}let d=bo({tokenBudget:e.tokenBudget,totalUsage:c.totalUsage,budgetContinuationCount:c.budgetContinuationCount,lastBudgetDeltaTokens:c.lastBudgetDeltaTokens,lastBudgetGlobalTokens:c.lastBudgetGlobalTokens,messages:y,finalText:c.finalText,thinkingBlocks:G,getBudgetContinuationMessage:e.runtimePorts.getBudgetContinuationMessage,log:n});if(d){yield I("budget_continuation",d.recoveryDetail),c={...c,messages:d.messages,budgetContinuationCount:d.budgetContinuationCount,lastBudgetDeltaTokens:d.lastBudgetDeltaTokens,lastBudgetGlobalTokens:d.lastBudgetGlobalTokens,transition:d.transition};continue}let h=Ht({inputMessages:i,messages:y,finalText:c.finalText,thinkingBlocks:G,stopHookActive:c.stopHookActive,totalToolCallCount:O,distinctToolNames:w,log:n});if(h){if(c.stopHookActive&&(h.reason==="final_marker_verification"||c.finalText.trim()==="")){let _=ae({inputMessages:i,messages:h.messages,reason:"final marker verification produced an empty response after tool use"});if(_){yield F(_);return}if(h.reason==="final_marker_verification"&&c.finalText.trim()===""&&c.finalMarkerEmptyRecoveryCount<1){yield I("final_marker_empty_retry","one extra retry after empty marker nudge"),c={...c,messages:h.messages,stopHookActive:h.stopHookActive,transition:h.transition,finalMarkerEmptyRecoveryCount:c.finalMarkerEmptyRecoveryCount+1};continue}let P=Ut({inputMessages:i,messages:h.messages});if(P){yield F(P);return}let Y=be({inputMessages:i,reason:"final marker verification produced an empty response after tool use"});if(Y){yield F(Y);return}}c={...c,messages:h.messages,stopHookActive:h.stopHookActive,transition:h.transition};continue}if(O===0&&W.length>0&&e.toolChoice!=="none"&&Kt<1&&Vn(we)){Kt++,Xe=!0,yield I("intent_without_action","announced but did not act; forcing a tool call"),c={...c,messages:[...y,{role:"assistant",content:we},{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 k=zt({totalToolCallCount:O,distinctToolNames:w,projectRoot:e.projectRoot});k&&(yield{type:"skill_instruction",turnId:r,instruction:k});let S=ve(y,"the model ended with an empty response after tool use before producing the requested final marker");for(let _ of Je)yield{type:"delta",turnId:r,text:_};yield F(S);return}let No=G.length===0&&ye.length>0?ye.join(""):void 0;y.push(ot(j,void 0,G.length>0?G:void 0,No)),B=Ct(B,{replayMessages:y,pendingToolCallIds:j.map(l=>l.id),completedToolCallIds:B.completedToolCallIds,lastStopReason:"tool_calls"});let Ie=c.identicalCallCounts,Qt=[],Pe=[],en=[],tn=!1;for(let l of j){let d=`${l.function.name}::${l.function.arguments}`,h=Ie.get(d)??0;if(Ie.set(d,h+1),h+1>kn){let k=Gt.has(l.function.name)?c.identicalSuccessfulToolResults.get(d):void 0;if(k){en.push({call:l,result:k,repeatCount:h+1});continue}Pe.push(l),tn||(tn=!0,n.info(`AP4 blocked: ${l.function.name} repeated ${h+1}x`))}else Qt.push(l)}let X=[];for(let l of en){let d=l.call,h=`Reused previous successful ${d.function.name} result for identical arguments (attempt ${l.repeatCount}); no additional tool execution was performed.
|
|
22
|
-
|
|
23
|
-
${l.result.content}`,k=V(d.id,{ok:!0,payload:h,imageUrls:l.result.imageUrls,toolReferences:l.result.toolReferences});y.push(k),X.push(d.id),w.add(d.function.name),O++,yield{type:"tool_result",turnId:r,callId:d.id,name:d.function.name,ok:!0,outputPreview:h.slice(0,2e3),durationMs:0,details:{type:d.function.name,reusedIdenticalCall:!0,repeatCount:l.repeatCount}}}for(let l of Pe){let d=Ie.get(`${l.function.name}::${l.function.arguments}`),h=je(y,l.function.name),k=h?`This exact tool call has been attempted ${d} times. Last error: ${h}. Do not retry. Report this error to the user.`:`This exact tool call has been attempted ${d} times and keeps failing. Do not retry it. Report the issue to the user or try a completely different approach.`,S=V(l.id,{ok:!1,error:k});y.push(S),X.push(l.id),w.add(l.function.name),O++,yield{type:"tool_result",turnId:r,callId:l.id,name:l.function.name,ok:!1,error:k}}if(Pe.length>0){let l=je(y,Pe[0].function.name),d={role:"user",content:"Tool calls were blocked because you repeated them with identical arguments too many times. "+(l?`The error was: "${l}". Tell the user about this error. `:"The operation is not working. ")+"Stop retrying and report the result to the user."};y.push(d)}let nn=[],Qe=[];for(let l of Qt){let d=ko({inputMessages:i,messages:y,toolCall:l});d?Qe.push({call:l,error:d}):nn.push(l)}for(let l of Qe){let d=l.call;y.push(V(d.id,{ok:!1,error:l.error})),X.push(d.id),w.add(d.function.name),O++,yield{type:"tool_result",turnId:r,callId:d.id,name:d.function.name,ok:!1,error:l.error},n.info(`premature completion artifact blocked: ${d.function.name}`)}Qe.length>0&&y.push({role:"user",content:"A tool attempted to write a completion artifact before all explicitly requested output files had evidence. Do not write final DONE markers or success reports into artifacts until the missing files are created or verified. If you cannot complete them, respond with the requested FAIL marker and the real reason."});let Bo=new Set(W.map(l=>l.function.name)),on=[],rn=[];for(let l of nn)Bo.has(l.function.name)?on.push(l):rn.push(l);for(let l of rn){let d=`Tool "${l.function.name}" was not offered for this turn and will not be executed. Use only the tools listed in the current request.`;y.push(V(l.id,{ok:!1,error:d})),X.push(l.id),n.warn(`unoffered tool call suppressed: ${l.function.name}`)}let et=xo(on,c.toolFailureCounts),tt=et.allowed;if(xe&&tt.length>Math.max(0,L-O)){let l=It({currentToolBudget:L,currentRoundBudget:A,toolHardCap:100,roundHardCap:100,continuationCount:me,successfulSinceLastCheck:pe-_e,fileReadCounts:c.fileReadCounts,windowTools:se,windowRounds:25});l&&(L=l.nextToolBudget,A=l.nextRoundBudget,me=l.continuationCount,_e=pe,n.info(`tool budget continuation #${l.continuationCount}: tools\u2192${L}, rounds\u2192${A} (progress detected)`))}let sn=Math.max(0,L-O),he=sn>0?tt.slice(0,sn):[],nt=tt.slice(he.length),Do=nt.length>0;if(et.blocked.length>0){for(let l of et.blocked){let d=l.call,h=V(d.id,{ok:!1,error:l.error});y.push(h),X.push(d.id),w.add(d.function.name),O++,yield{type:"tool_result",turnId:r,callId:d.id,name:d.function.name,ok:!1,error:l.error},n.info(`variant tool blocked: ${d.function.name} failed ${l.failCount}x with different args`)}y.push(_o())}if(nt.length>0){let l=`Tool call budget exhausted (${L}) for this turn. Stop requesting more tools and report what remains incomplete.`;for(let d of nt){let h=V(d.id,{ok:!1,error:l});y.push(h),X.push(d.id),w.add(d.function.name),O++,yield{type:"tool_result",turnId:r,callId:d.id,name:d.function.name,ok:!1,error:l}}y.push({role:"user",content:`${l} You reached this turn's tool budget after ${me} extension(s). Do NOT claim the task is complete or that all files were created if it is not. Be honest in your reply: (1) state plainly the turn stopped before finishing; (2) list concretely what is DONE vs what is still UNFINISHED; (3) tell the user to reply "\u7EE7\u7EED" to finish the rest. If explicitly requested output files are still missing, respond with the requested FAIL marker and the real reason.`})}for(let l of he){let d=l.function.arguments,h=W.find(k=>k.function.name===l.function.name);if(h?.backfillObservableInput)try{let k=JSON.parse(l.function.arguments),S={...k};h.backfillObservableInput(S),Object.keys(S).some(P=>!(P in k))&&(d=JSON.stringify(S))}catch{}yield{type:"tool_call",turnId:r,callId:l.id,name:l.function.name,arguments:d,inputSummary:wt(d)}}let $o=new Map(c.toolFailureCounts),Le=null;try{let l=e.runtimePorts.createStreamingToolExecutor({toolInvoker:o,hooks:m,sessionId:s,turnId:r,log:n,signal:C,maxConcurrentTools:e?.maxConcurrentTools,maxExecutionMs:Tn});for(let d of he)l.addTool(d);for await(let d of l.getRemainingResults()){d.blocked&&(yield{type:"tool_blocked",turnId:r,callId:d.callId,name:d.toolName,reason:d.blockReason??"blocked"}),y.push(d.message),X.push(d.callId),w.add(d.toolName),O++;let h=d.ok&&Kn(d);if(d.ok&&!h&&(pe+=1),Mo({toolFailureCounts:c.toolFailureCounts,toolName:d.toolName,ok:d.ok,softEmpty:h}),d.ok&&Ds.has(d.toolName)&&$s(c),d.ok&&!h&&Gt.has(d.toolName)){let k=he.find(_=>_.id===d.callId),S=typeof d.message?.content=="string"?d.message.content:"";if(k&&S){let _=Array.isArray(d.message.imageUrls)?d.message.imageUrls.filter(Y=>typeof Y=="string"):void 0,P=Array.isArray(d.message.toolReferences)?d.message.toolReferences.filter(Y=>typeof Y=="string"):void 0;c.identicalSuccessfulToolResults.set(`${k.function.name}::${k.function.arguments}`,{content:S,imageUrls:_,toolReferences:P})}}if(d.ok&&d.toolName==="read"){let k=he.find(S=>S.id===d.callId);if(k)try{let S=JSON.parse(k.function.arguments),_=S.file_path??S.path??S.filePath??"";if(_){let P=c.fileReadCounts.get(_)??0;c.fileReadCounts.set(_,P+1)}}catch{}}yield zn(r,d);for(let k of Gn(r,d))yield k;for(let k of Wn({turnId:r,result:d,toolCalls:j}))yield k;!Le&&Lo&&d.toolName==="stt"&&d.ok&&(Le=Fs(i,d))}}catch(l){let d=l instanceof Error?l.message:String(l);yield{type:"error",turnId:r,error:d,code:"TOOL_EXECUTION_ERROR",usage:c.totalUsage};return}if(Le){yield F(Le);return}if(y.push(...Ao({toolFailureCounts:c.toolFailureCounts,snapshot:$o})),Do){let l=ae({inputMessages:i,messages:y,reason:`tool call budget exhausted (${L}) before completing all required files`});if(l){yield F(l);return}}if(B=Be(B,{replayMessages:y,completedToolCallIds:[...B.completedToolCallIds,...X],lastStopReason:"tool_calls"}),e.toolChoice==="required"&&j.length>0&&(Ke=!0),e.generateToolUseSummary&&j.length>0){let l=j.map(d=>({name:d.function.name,arguments:d.function.arguments}));Me=e.generateToolUseSummary(l).catch(()=>null)}let Uo=j.length>0&&j.every(l=>{let d=y.find(k=>k?.role==="tool"&&k?.tool_call_id===l.id);if(!d)return!0;let h=d.content;return typeof h=="string"&&h.startsWith("Error: ")}),te=c.consecutiveFailedRounds;if(Uo){if(te+=1,te>=Cn){if(We>=3&&c.repeatedToolFailureRecoveryCount<1){let h=Ht({inputMessages:i,messages:y,finalText:c.finalText,thinkingBlocks:[],stopHookActive:c.stopHookActive,totalToolCallCount:O,distinctToolNames:w,log:n});if(h?.reason==="explicit_required_file_verification"||h?.reason==="explicit_extra_file_verification"){yield I("repeated_tool_failure_artifact_recovery","one recovery nudge before ending a complex explicit artifact turn after repeated tool failures"),c={...c,messages:h.messages,stopHookActive:h.stopHookActive,transition:h.transition,consecutiveFailedRounds:0,repeatedToolFailureRecoveryCount:c.repeatedToolFailureRecoveryCount+1};continue}}if(c.repeatedToolFailureRecoveryCount<1){let h=to(y);if(h){yield I("repeated_tool_failure_self_correction","one help-guided self-correction round before ending on repeated tool failures"),c={...c,messages:[...y,h],consecutiveFailedRounds:0,repeatedToolFailureRecoveryCount:c.repeatedToolFailureRecoveryCount+1};continue}}let l=`repeated tool failures (${te} rounds in a row)`,d=ae({inputMessages:i,messages:y,reason:`${l} before all required files were produced`})??(c.finalText.trim()?c.finalText:be({inputMessages:i,reason:l})??eo(y,te));n.info(`early exit: ${te} consecutive failed rounds, returning ${c.finalText?"partial":"fallback"} response`),yield F(d);return}}else te=0;let jo=3,an=[...c.fileReadCounts.entries()].filter(([,l])=>l>=jo);if(an.length>0){let l=an.map(([h])=>h).join(", ");n.info(`AP5: file read cycle detected on ${l}, injecting nudge`);let d={role:"user",content:`You are reading the same files repeatedly (${l}). This indicates a circular dependency or cycle. Stop reading files, summarize your findings so far, and explain the circular structure to the user.`};y.push(d),c.fileReadCounts.clear()}let Oe=U+1;if(g>0&&Oe>g){if(n.info(`max turns reached (${g}), completing`),m){let h=await m.invoke("stop",{sessionId:s,reason:"max_turns"});if(h.action==="abort"){let k=h.reason??"Stop hook requested continuation after max_turns",S={role:"assistant",content:c.finalText,...G.length>0&&{thinkingBlocks:[...G]}};c={...c,messages:[...y,S,{role:"user",content:k}],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}};continue}}let l=ae({inputMessages:i,messages:y,reason:`tool loop max turns reached (${g}) before completing all required files`});if(l){yield F(l);return}let d=ve(y,`tool loop max turns reached (${g}) before producing the requested final marker`);yield F(d);return}if(xe&&Oe>A){let l=It({currentToolBudget:L,currentRoundBudget:A,toolHardCap:100,roundHardCap:100,continuationCount:me,successfulSinceLastCheck:pe-_e,fileReadCounts:c.fileReadCounts,windowTools:se,windowRounds:25});l&&(A=l.nextRoundBudget,L=l.nextToolBudget,me=l.continuationCount,_e=pe,n.info(`round budget continuation #${l.continuationCount}: rounds\u2192${A}, tools\u2192${L} (progress detected)`))}if(Oe>A){n.info(`tool loop budget exhausted (${A} rounds), returning`);let l=zt({totalToolCallCount:O,distinctToolNames:w,projectRoot:e.projectRoot});l&&(yield{type:"skill_instruction",turnId:r,instruction:l});let d=ae({inputMessages:i,messages:y,reason:`tool budget exhausted (${A} rounds) before completing all required files`});if(d){yield F(d);return}let h=ve(y,`tool budget exhausted (${A} rounds) before producing the requested final marker`);yield F(h);return}c={messages:y,maxOutputTokensRecoveryCount:0,hasAttemptedReactiveCompact:!1,maxOutputTokensOverride:void 0,turnCount:Oe,transition:{reason:"next_turn"},guardState:v,reactiveCompactState:z,toolLoopState:B,consecutiveFailedRounds:te,finalText:c.finalText,totalUsage:c.totalUsage,collapseStore:Ve,currentModel:c.currentModel,consecutive529Errors:0,consecutiveApiRetries:0,stopHookActive:c.stopHookActive,lastResponseId:c.lastResponseId,snipRemovedIds:c.snipRemovedIds,contentReplacementState:c.contentReplacementState,budgetContinuationCount:c.budgetContinuationCount,finalMarkerEmptyRecoveryCount:c.finalMarkerEmptyRecoveryCount,repeatedToolFailureRecoveryCount:c.repeatedToolFailureRecoveryCount,lastBudgetDeltaTokens:c.lastBudgetDeltaTokens,lastBudgetGlobalTokens:c.lastBudgetGlobalTokens,identicalCallCounts:Ie,identicalSuccessfulToolResults:c.identicalSuccessfulToolResults,toolFailureCounts:c.toolFailureCounts,fileReadCounts:c.fileReadCounts,recoveryTrace:c.recoveryTrace}}}var Us=["\u63A5\u5355\u91D1\u989D","\u5408\u540C\u91D1\u989D","\u62A5\u4EF7","\u9884\u7B97","\u91D1\u989D","price","amount","contract amount"];function wo(e){let t=js(e),o=["[Recalled memories]","- L1 project MD is project-scoped working memory.","- L2 long-term memory is cross-project canonical memory.","- If L1 and L2 conflict on the same entity/fact, do not silently merge or choose. Surface the conflict and ask the user to confirm. For current-project operational tasks, use L1 only as a project-scoped clue until confirmed into L2."];if(t.length>0){o.push("[Memory conflict detected]");for(let n of t)o.push(`- entity: ${n.entity}; fact: ${n.predicate}; L1 project MD says: ${Eo(n.l1Amount)}; L2 long-term says: ${Eo(n.l2Amount)}; action: ask the user which value is current before using it.`)}for(let n of e){let r=zs(n);o.push(`- [${r}] ${n.text}`)}return o.join(`
|
|
24
|
-
|
|
25
|
-
|
|
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 $n(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 Un(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 jn(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 zr(e){return e==="length"||e==="max_tokens"}function qn(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 Hr(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 Gr(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*Wr(e){let{messages:t,contentReplacementState:n,snipRemovedIds:o,collapseStore:r,guardConfig:s,runtimePorts:l,hooks:a,hookCtx:u,sessionId:p,currentModel:h,log:T,recovery:k,onAutocompact:I}=e,P;{let x=await l.enforceToolResultBudget(t,n,p);P=x.messages,x.newlyReplacedCount>0&&(T.info(`tool-result-budget: persisted ${x.newlyReplacedCount} oversized tool results`),yield k("tool_result_budget",`${x.newlyReplacedCount} persisted`))}{let x=rn(P,o);P=x.messages,x.removedCount>0&&(T.info(`snip: removed ${x.removedCount} messages, freed ~${x.tokensFreed} tokens`),yield k("snip",`${x.removedCount} messages`))}{let E=new Ge().compress(P,0);E.droppedCount>0&&(P=E.messages,T.info(`microcompact: cleared ${E.droppedCount} old tool results`))}if(P=an(P,r).messages,s.contextWindowTokens>0){let x=s.contextWindowTokens*.75,E=l.getActiveContextCompressionEngine(),A;E?A=await E.compressAsync(P,x,{model:h,sessionId:p}):A=l.compressMessages(P,{budget:x,model:h}),A.droppedCount>0&&(P=A.messages,T.info(`autocompact: ${A.strategy}, dropped ${A.droppedCount}`),yield k("autocompact",`${A.strategy}: ${A.droppedCount} dropped`),yield{type:"lifecycle",turnId:u.turnId,kind:"context_compression",status:"completed",detail:`${A.strategy}: ${A.droppedCount} dropped`},I(),B(a,"context.after_compact",{...u,removedCount:A.droppedCount},T))}return P=jr(P),P}async function*Kr(e,t){let{state:n,guardState:o,fallbackModel:r,signal:s,querySource:l,turnId:a,log:u,emitRecovery:p}=t;if(e instanceof We&&r)return u.info(`model fallback triggered: ${e.originalModel} -> ${e.fallbackModel}`),yield p("model_fallback",`${e.originalModel} -> ${e.fallbackModel}`),{kind:"continue",patch:{currentModel:e.fallbackModel,consecutive529Errors:0,consecutiveApiRetries:0,transition:void 0}};let 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 I=(n.consecutiveApiRetries??0)+1;return I>xe?(u.info(`stale connection retry limit reached (${xe}), 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 p("stale_connection_retry",h.slice(0,80)),{kind:"continue",patch:{consecutiveApiRetries:I,transition:void 0}})}let k=Gr({status:T,message:h});if(k!==null)return u.info(`max_tokens overflow: adjusting to ${k}`),o.currentMaxOutputTokens=k,{kind:"continue",patch:{maxOutputTokensOverride:k,transition:void 0}};if(kn(T)){n.consecutive529Errors++;let I=2,P=r&&n.currentModel!==r;if(n.consecutive529Errors>I&&!P&&!yt())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>=nr&&r&&n.currentModel!==r)return u.info(`529 \u8133 ${n.consecutive529Errors}: triggering fallback to ${r}`),yield p("model_fallback",`529 \u8133 ${n.consecutive529Errors}`),{kind:"continue",patch:{currentModel:r,consecutive529Errors:0,transition:void 0}};if(yt()){let x=ht(n.consecutive529Errors);u.info(`persistent retry: waiting ${x}ms (attempt ${n.consecutive529Errors})`);let E=x;for(;E>0;){if(s?.aborted)return yield{type:"error",turnId:a,error:"Aborted during retry wait",code:"ABORTED",usage:n.totalUsage},{kind:"return"};yield{type:"heartbeat",turnId:a,message:`Retrying in ${Math.ceil(E/1e3)}s (${T})`};let A=Math.min(E,tr);await new Promise(O=>setTimeout(O,A)),E-=A}return{kind:"continue",patch:{transition:void 0}}}if(Cn(l)){let E=Hr({status:T,message:h})??ht(n.consecutive529Errors);return u.info(`transient ${T}: retry in ${E}ms`),yield p("retry",`${T} retry in ${E}ms`),await new Promise(A=>setTimeout(A,E)),{kind:"continue",patch:{transition:void 0}}}u.info(`background source ${l}: not retrying ${T}`)}return{kind:"streamError",streamError:{status:T,message:h}}}import{readdirSync as Jr,statSync as Rt}from"node:fs";var Ka=/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,Xa=/[A-Za-z]:[\\/](?:[^\s"'`<>|,\uFF0C\u3001;\uFF1B\u3002]+[\\/])*[^\s"'`<>|,\uFF0C\u3001;\uFF1B\u3002]+\.[A-Za-z0-9]{1,12}/g,Xr=/\s*[,\uFF0C\u3001;\uFF1B]\s*([^\s"'`<>|,\uFF0C\u3001;\uFF1B\u3002\\/]+\.[A-Za-z0-9]{1,12})/gy,Va=/\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,Ya=/(?:^|[\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,Za=/(?:^|[\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,Ja=/(?:^|[\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,Qa=/\b(?:create|generate|write|produce|save|output|deliver|deliverables?|artifacts?|required|required files?|must generate|self-verify)\b|(?:生成|创建|写入|输出|保存|交付|产物|文件|必须|自检|验证)/i,el=/\bpreviews?[\\/]\s*(?:containing|with|under|for)?[^.。;;\n]*(?:rendered|preview|previews|check|evidence|verify|verification)\b/i;function ne(e){return e.trim().replace(/[),.;:\uFF0C\u3002\uFF1B\u3001]+$/u,"").replace(/\\/g,"/").toLowerCase()}function Qr(e){return e.trim().replace(/[),.;:\uFF0C\u3002\uFF1B\u3001]+$/u,"").replace(/\\/g,"/").replace(/\/+$/u,"")}function Vr(e){return/\.[A-Za-z0-9]{1,12}$/u.test(e.replace(/[),.;:\uFF0C\u3002\uFF1B\u3001]+$/u,""))}function Yr(e,t,n){let o=Math.max(e.lastIndexOf(".",t),e.lastIndexOf(`
|
|
26
|
+
`,t),e.lastIndexOf(";",t),e.lastIndexOf("\u3002",t),e.lastIndexOf("\uFF1B",t))+1,r=e.slice(o,t).toLowerCase();if(/\b(?:do\s+not|don't|never)\s+(?:leave|create|write|include|keep|produce|add|generate)\b/i.test(r)||/\b(?:remove|delete|exclude)\b/i.test(r))return!0;let s=e.slice(Math.max(0,t-16),t+n.length);return new RegExp(`\\bno\\s+${os(n)}\\b`,"i").test(s)}function Zr(e){return e.replace(/https?:\/\/\S+/gu," ")}function Hn(e){let t=new Set,n=[],o=r=>{let s=r.replace(/[),.;:\uFF0C\u3002\uFF1B]+$/u,""),l=ne(s);t.has(l)||(t.add(l),n.push(s))};for(let r of e){if(r.role!=="user"||typeof r.content!="string")continue;let s=Zr(r.content);for(let l of s.matchAll(Xa)){let a=l[0],u=(l.index??0)+a.length;if(s[u]==="/"||s[u]==="\\")continue;o(a);let p=a.replace(/\\/g,"/"),h=p.lastIndexOf("/");if(h>=0){let T=p.slice(0,h+1);Xr.lastIndex=u;let k;for(;(k=Xr.exec(s))!==null;)o(`${T}${k[1]}`)}}}for(let r of e){if(r.role!=="user"||typeof r.content!="string")continue;let s=Zr(r.content);if(!Qa.test(s))continue;let l=Array.from(s.matchAll(Va)).map(u=>Qr(u[1]??"")).filter(u=>u&&!Vr(u));if(l.length===0)continue;let a=l[l.length-1];for(let u of s.matchAll(Ya)){let p=u[1];p&&(Yr(s,u.index??0,p)||o(`${a}/${p}`))}for(let u of s.matchAll(Za)){let p=u[1];p&&(Yr(s,u.index??0,p)||o(`${a}/${p}`))}for(let u of s.matchAll(Ja)){let p=u[1];p&&(Vr(p)||/(?:assets[\\/]generated|screenshots(?:[\\/]|$)|previews(?:[\\/]|$))/i.test(p)&&/\b(?:generated|bitmap|png|screenshots?|preview|previews|evidence|assets?|containing)\b/i.test(s)&&o(`${a}/${p}/*`))}el.test(s)&&o(`${a}/previews/*`)}return n}function xt(e){if(e.role!=="tool")return!1;let t=typeof e.content=="string"?e.content:"";return e.is_error!==!0&&!t.startsWith("Error:")}function es(e){let t=new Set,n=new Map,o=[];for(let r of e){let s=r,l=Array.isArray(s.tool_calls)?s.tool_calls:[];for(let a of l){let u=a,p=u.id,h=u.function;typeof p=="string"&&typeof h?.name=="string"&&n.set(p,h.name)}}for(let r of e){let s=r;if(xt(s)){let l=s.tool_call_id;typeof l=="string"&&t.add(l),(typeof l=="string"?n.get(l):void 0)==="exec"&&typeof s.content=="string"&&o.push(s.content)}}for(let r of e){let s=r,l=Array.isArray(s.tool_calls)?s.tool_calls:[];for(let a of l){let u=a,p=u.id;if(typeof p=="string"&&t.size>0&&!t.has(p))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 k of["path","filePath","file_path"]){let I=T[k];typeof I=="string"&&o.push(I)}continue}if(h.name==="exec"){let k=T.command;typeof k=="string"&&o.push(k)}}catch{h.name==="exec"&&o.push(h.arguments)}}}return o.join(`
|
|
27
|
+
`).replace(/\\/g,"/").toLowerCase()}function Gn(e){try{if(e.endsWith("/*")){let n=e.slice(0,-2);return Jr(n,{withFileTypes:!0}).some(r=>{if(!r.isFile())return!1;try{return Rt(`${n}/${r.name}`).size>0}catch{return!1}})}let t=Rt(e);return t.isFile()&&t.size>0}catch{return!1}}function tl(e,t){let n=ne(t);if(!n.endsWith("/*"))return e.includes(n);let o=n.slice(0,-1);return e.includes(o)}function nl(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 l=s,a=l.id,u=l.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)&&xt(o))return!0}return!1}function ol(e){let t=ns(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 rl(e){let t=Qr(e),n=t.lastIndexOf("/");return n>=0?t.slice(0,n):""}function sl(e){if(e.length===0)return"";let t=e.map(o=>rl(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 il(e,t){let n=ne(e);return t.some(o=>{let r=ne(o);return r.endsWith("/*")?n.startsWith(r.slice(0,-1)):n===r})}function al(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 l of s){let a=l,u=a.id,p=a.function;if(typeof u!="string"||p?.name!=="write"&&p?.name!=="edit"||typeof p.arguments!="string")continue;let h=Kn(p.arguments);if(!h)continue;let T=Xn(h);T&&n.set(u,T)}}for(let o of e){let r=o;if(!xt(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 ll(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 cl(e){return[...new Set([...e.matchAll(/\bGoal\s+\d+\b/gi)].map(t=>t[0].replace(/\s+/g," ").replace(/\bgoal\b/i,"Goal")))]}function ul(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 l of s){let a=l,u=a.id,p=a.function;if(typeof u!="string"||p?.name!=="write"&&p?.name!=="edit"||typeof p.arguments!="string")continue;let h=Kn(p.arguments);if(!h)continue;let T=Xn(h)??"",k=rs(h);(/\bartifact[-_\s]?index\b/i.test(T)||/\bartifact[-_\s]?index\b/i.test(k))&&n.set(u,k)}}for(let o of e){let r=o;if(!xt(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 dl(e){let t=ns(e.inputMessages);if(!ll(t))return[];let n=ul(e.messages).at(-1);if(!n)return[];let o=[],r=cl(t).filter(u=>!new RegExp(`\\b${os(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),l=/\b(?:all\s+checks\s+pass|confirmed\s*:\s*all|everything\s+(?:passes|passed)|fully\s+verified)\b/i.test(e.finalText);s&&l&&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 fl(e){let t=[],n=o=>{let r;try{r=Jr(o,{withFileTypes:!0})}catch{return}for(let s of r){let l=`${o}/${s.name}`;if(s.isDirectory()){n(l);continue}if(s.isFile())try{Rt(l).size>0&&t.push(l)}catch{}}};try{if(!Rt(e).isDirectory())return[]}catch{return[]}return n(e),t}function pl(e,t){if(!ol(e))return[];let n=Hn(e),o=n.filter(l=>!ne(l).endsWith("/*"));if(o.length<2)return[];let r=sl(o);if(!r||r.split("/").length<3)return[];let s=ne(r);return[...new Set([...al(t),...fl(r)])].filter(l=>ne(l).startsWith(`${s}/`)&&!il(l,n)&&Gn(l))}function ts(e,t){let n=Hn(e);if(n.length===0)return[];let o=es(t);return n.filter(r=>!tl(o,r))}function zn(e){return Wn(e).fail}function ml(e){return e.replace(/[.,;:,。;:、!?]+$/u,"")}function kt(e){if(!e)return!1;let t=ml(e);return/^[A-Za-z0-9_.:-]+$/u.test(t)&&/[0-9_:-]/u.test(t)}function Wn(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))kt(s[2])&&(n=`${s[1].toUpperCase()} ${t(s[2])}`);for(let s of r.content.matchAll(/\bFAIL\s+([A-Za-z0-9_.:-]+)/gi))kt(s[1])&&(o=`FAIL ${t(s[1])}`);for(let s of r.content.matchAll(/\b([A-Za-z0-9_.:-]+)\s+(DONE|PASS)\b/gi))kt(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))kt(s[1])&&(o=`${t(s[1])} FAIL`)}return{done:n,fail:o}}function ns(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 os(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function ve(e){let t=ts(e.inputMessages,e.messages).filter(o=>!Gn(o));return t.length===0?void 0:`${zn(e.inputMessages)??"FAIL"} ${e.reason}. Missing required output file evidence: ${t.join(", ")}`}function Kn(e){try{let t=JSON.parse(e);return t&&typeof t=="object"&&!Array.isArray(t)?t:null}catch{return null}}function Xn(e){for(let t of["path","filePath","file_path"]){let n=e[t];if(typeof n=="string"&&n.trim())return n}}function rs(e){for(let t of["content","newContent","replacement","text"]){let n=e[t];if(typeof n=="string")return n}return""}function ss(e){let t=e.toolCall.function.name;if(t!=="write"&&t!=="edit")return;let n=Wn(e.inputMessages);if(!n.done)return;let o=Kn(e.toolCall.function.arguments);if(!o)return;let r=Xn(o),s=rs(o);if(!r||!s.includes(n.done))return;let l=Hn(e.inputMessages);if(l.length<2)return;let a=ne(r);if(!l.some(T=>ne(T)===a))return;let p=es(e.messages),h=l.filter(T=>ne(T)!==a).filter(T=>!p.includes(ne(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 Ke(e,t){return{role:"assistant",content:e,...t.length>0&&{thinkingBlocks:[...t]}}}function gl(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 hl(e){let t=[...e].reverse().find(n=>n.role==="tool");t&&typeof t.content=="string"&&(t.content+=`
|
|
28
|
+
|
|
29
|
+
\u923F\u72C5\u7B0D NOTE: You used shell commands but did not call the write or edit tool to create/modify the file. Shell commands may fail silently or produce incorrect results on this platform. Please use the 'write' tool directly to create the requested file with the correct content.`)}function Xe(e,t,n,o){return{reason:e,messages:[...t,n,o],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}}}function Vn(e){let t=e.inputMessages.find(h=>h.role==="user"),n=typeof t?.content=="string"?t.content:"",o=Ka.test(n),r=e.distinctToolNames.has("write")||e.distinctToolNames.has("edit"),s=Wn(e.inputMessages),l=nl(e.messages),a=ts(e.inputMessages,e.messages).filter(h=>!(l&&Gn(h)));if(a.length>0&&e.totalToolCallCount>0){if(s.fail!==void 0&&e.finalText.includes(s.fail))return null;e.log.info(`explicit required file verification: ${a.length} file(s) missing`);let h=zn(e.inputMessages),T={role:"user",content:`Before completing, verify that every explicitly requested output file exists and is non-empty. Missing required output file evidence: ${a.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 Xe("explicit_required_file_verification",e.messages,Ke(e.finalText,e.thinkingBlocks),T)}let u=pl(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=zn(e.inputMessages),T={role:"user",content:`The latest request asked for exactly the listed output artifacts, but extra files were produced under the output root: ${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 Xe("explicit_extra_file_verification",e.messages,Ke(e.finalText,e.thinkingBlocks),T)}let p=dl({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(T=>T.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 Xe("artifact_index_evidence_verification",e.messages,Ke(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&&hl(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 Xe("file_action_verification",e.messages,Ke(e.finalText,e.thinkingBlocks),h)}if(e.totalToolCallCount>=3&&e.distinctToolNames.has("write")&&e.messages.filter(gl).length>=3){e.log.info("AP3 verification nudge: 3+ files created, injecting completeness check");let T={role:"user",content:"You created multiple files. Before completing, verify: (1) All imports between your files resolve to real exports. (2) No TODO, placeholder, or 'not implemented' stubs remain. (3) Functions that are imported are actually called, not just declared. If everything is correct, confirm completion. If not, fix the issues now."};return Xe("multi_file_skeleton_verification",e.messages,Ke(e.finalText,e.thinkingBlocks),T)}return null}function yl(e,t){return{role:"assistant",content:e,...t.length>0&&{thinkingBlocks:[...t]}}}async function is(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,yl(e.finalText,e.thinkingBlocks),o],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}}}return null}var Tl=5;function bl(e){return e.inputTokens+e.outputTokens+(e.reasoningTokens??0)}function Cl(e,t){return{role:"assistant",content:e,...t.length>0&&{thinkingBlocks:[...t]}}}function as(e){if(!e.tokenBudget||e.tokenBudget<=0||e.budgetContinuationCount>=Tl)return null;let t=bl(e.totalUsage),n=t/e.tokenBudget*100,o=t-e.lastBudgetGlobalTokens;if(e.budgetContinuationCount>=er&&o<cn&&e.lastBudgetDeltaTokens<cn)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,l={role:"user",content:e.getBudgetContinuationMessage(n,t,e.tokenBudget)};return e.log.info(`token budget continuation #${s}: ${Math.round(n)}% used`),{messages:[...e.messages,Cl(e.finalText,e.thinkingBlocks),l],budgetContinuationCount:s,lastBudgetDeltaTokens:o,lastBudgetGlobalTokens:t,recoveryDetail:`${Math.round(n)}% used (#${s})`,transition:{reason:"token_budget_continuation"}}}function Yn(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 fn(t,{tools:[...e.distinctToolNames],projectRoot:e.projectRoot})}var Ve="*";function ls(e,t){let n=[],o=[];for(let r of e){let s=fs(r.function.name,r.function.arguments),l=ps(r.function.name,Ve),a=Math.max(t.get(s)??0,t.get(l)??0);a>=ft?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 cs(){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 us(e){if(e.ok&&!e.softEmpty)return;let t=fs(e.toolName,e.toolArguments),n=e.toolFailureCounts.get(t)??0;e.toolFailureCounts.set(t,n+1)}function ds(e){let t=[];for(let[n,o]of e.toolFailureCounts)if(o>=ft&&(e.snapshot.get(n)??0)<ft){let{toolName:r,target:s}=xl(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 fs(e,t){return ps(e,kl(e,t))}function kl(e,t){let n=Rl(t);return e==="read"||e==="write"||e==="edit"||e==="patch"?Zn(n?.path??n?.file_path??n?.filePath):e==="search"?Zn([n?.mode,n?.path,n?.fileGlob,n?.pattern].filter(Boolean).join("|")):e==="exec"?Zn(n?.command):Ve}function Rl(e){if(e)try{let t=JSON.parse(e);return t&&typeof t=="object"&&!Array.isArray(t)?t:void 0}catch{return}}function Zn(e){return typeof e=="string"&&e.trim()?e.trim().replaceAll("\\","/").toLowerCase():Ve}function ps(e,t){return`${e}::${t}`}function xl(e){let t=e.indexOf("::");return t<0?{toolName:e,target:Ve}:{toolName:e.slice(0,t),target:e.slice(t+2)||Ve}}var _l=new Set(["find","grep","rg","ag","ack","locate","which","whereis"]),vl=new Set(["cat","head","tail","less","more","wc","stat","file","sed","strings","jq","awk","cut","sort","uniq","tr"]),Al=new Set(["ls","tree","du","dir","gci","get-childitem"]),wl=new Set(["grep","rg","ag","ack","find"]);var Sl=new Set(["mv","cp","rm","mkdir","rmdir","chmod","chown","chgrp","touch","ln","cd","export","unset","wait"]);function Ml(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 l=o[r],a=l.lastIndexOf("/");return(a>=0?l.slice(a+1):l).toLowerCase()}function El(e){return/(?:^|[;&|])\s*(?:cd|pushd|popd)\b/.test(e)}function ms(e){let t=Ml(e),n=t!==null&&_l.has(t),o=t!==null&&vl.has(t),r=t!==null&&Al.has(t),s=t!==null&&Sl.has(t),l=/(?:[^2]>|^>|\|>)/.test(e),a=El(e),u=(n||o||r)&&!l&&!a;return{firstCommand:t,isSearch:n,isRead:o,isList:r,isSilent:s,isConcurrencySafe:u,isReadOnly:u}}function gs(e){return e.isRead||e.isList?!0:e.firstCommand!==null&&wl.has(e.firstCommand)}function Ll(e,t){if(e.length!==1||e[0]?.function.name!=="stt")return!1;let n=[...t].reverse().find(l=>l.role==="user");if(!n)return!1;let o=Array.isArray(n.audioUrls)&&n.audioUrls.some(l=>typeof l=="string"&&l.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 Ol(e,t){let n=Nl(t);if(!n)return null;let o=Fl(n);if(!o)return null;let r=[...e].reverse().find(a=>a.role==="user"),s=typeof r?.content=="string"?r.content:"",l=/\bAUDIO_STT_RESULT\s+([^\s<]+)\s+<transcription\b/i.exec(s);return l?.[1]?`AUDIO_STT_RESULT ${l[1]} ${o}`:o}function Nl(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 Fl(e){return e.toLocaleLowerCase().replace(/[^\p{L}\p{N}\s]+/gu," ").replace(/\s+/g," ").trim()}function b(e){return[...new Set(e.map(t=>t.function.name))].sort()}function eo(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 Bl(e,t,n,o,r){let s=r.filter(l=>l.name===e).sort((l,a)=>hs(l.reason)-hs(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 hs(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 Dl(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 ys(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 Ae(e,t){return t.size===0?[...e]:e.filter(n=>!t.has(n.function.name))}var $l=new Set(["edit","patch","read"]);function Ts(e,t){let n=e.filter(o=>$l.has(o.function.name)&&!t.has(o.function.name));return n.length>0?eo(n):e.filter(o=>o.function.name!=="write"&&!t.has(o.function.name))}function Jn(e,t){let n=new Set(t);return e.filter(o=>!n.has(o))}function Ul(e){if(!e)return;let t=e.trim();return(t.match(/Last error:\s*(.+?)\.\s*Do not retry\./s)?.[1]?.trim()??t).slice(0,600).trim()||void 0}function bs(e){let n=ye(e)?.command;return typeof n=="string"&&n.trim()?n:void 0}var At=5174;function Cs(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 ws(e){return/(?:^|\s)--strictPort(?:\s|$)/.test(e)}function ql(e){if(ws(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 ks(e,t){let n=ye(e)??{};return JSON.stringify({...n,command:t})}function zl(e){let t=e.replace(/^(?:\s*sleep\s+\d+(?:\.\d+)?\s*(?:&&|;)\s*)+/i,"").trim();return t&&t!==e.trim()?t:null}function Hl(e){return Cs(e,At)?{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)&&Cs(e,At-1)&&!ws(e)?{action:"rewrite",command:ql(e)}:null}function wt(e){let t=[];for(let n of e.devServerUrls)if(!(!/^https?:\/\/(?:localhost|127\.0\.0\.1):\d+\b/i.test(n)||new RegExp(`:${At}\\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 Rs(e){let t=wt(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 Gl(e){let n=ye(e)?.command;return typeof n=="string"&&n.trim()?n.trim():null}function xs(e){let t=Gl(e);return t?/\b(?:npx\s+)?playwright\s+install(?:\s+--with-deps)?\s+chromium\b/i.test(t):!1}function Wl(e){let t=wt(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 Kl(e){return[`The task list still has unresolved item(s): ${e.filter(n=>n.status!=="completed").map(n=>`#${n.id} ${n.title} (${n.status})`).join("; ")}.`,"Before final response, reconcile the task list truthfully using the task tool.","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 Xl(e){let t=new Set(["completed","blocked","cancelled","canceled","failed"]);return e.some(n=>!t.has(n.status.toLowerCase()))}function Vl(){return"Command blocked: local file reads/searches/listing must use the dedicated read/search tools, not exec. Use read for file contents and search for filename or content lookup."}function _s(e,t){let n=t.blockedToolCalls.length>0?t.blockedToolCalls.map(s=>`${s.name}:${s.reason}`).join(", "):"none",r=[...new Set([...t.toolCallNames,"write","edit","patch"])].sort().map(s=>Bl(s,t.availableToolNames,t.enabledToolNames,t.toolCallNames,t.blockedToolCalls)).join(", ");return`${e}
|
|
30
|
+
|
|
31
|
+
Tool availability diagnostics:
|
|
32
|
+
availableToolNames: ${t.availableToolNames.join(", ")}
|
|
33
|
+
enabledToolNames: ${t.enabledToolNames.join(", ")}
|
|
34
|
+
toolCallNames: ${t.toolCallNames.join(", ")||"none"}
|
|
35
|
+
blockedToolCalls: ${n}
|
|
36
|
+
attribution: ${r}`}function ue(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function Yl(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=ye(t);if(!r)return`Tool "${e.function.name}" arguments must be a JSON object.`;for(let s of o){let l=r[s];if(typeof l=="string"?l.trim().length===0:l==null)return`Tool "${e.function.name}" missing required field \`${s}\`. Use the tool schema exactly instead of substituting another field.${Zl(e.function.name)}`}return null}function Zl(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 we(e,t){if(!e||typeof e!="object")return;let n=e[t];return typeof n=="string"?n:void 0}function to(e,t){if(!e||typeof e!="object")return;let n=e[t];return typeof n=="boolean"?n:void 0}function Jl(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 Ql(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 ec(e,t){if(e.function.name!=="task")return!1;let n=ye(e.function.arguments);if(n?.action!=="output")return!1;let o=n.taskId;return typeof o=="string"&&he(t).has(o)}function tc(e,t){if(e.toolName!=="task")return!1;let n=we(e.details,"taskId");return!n||!he(t).has(n)?!1:we(e.details,"action")==="output"&&to(e.details,"running")===!0}var nc=180,oc=40;function rc(e){return/\(no output yet\)|\bno output yet\b/i.test(e)}function sc(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 he(e){return e.backgroundAgentTaskIds??(e.backgroundAgentTaskIds=new Set)}function ic(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,l=r.title,a=r.status;typeof s!="number"||!Number.isFinite(s)||typeof l!="string"||!l.trim()||typeof a!="string"||!a.trim()||n.push({id:s,title:l,status:a})}return n}var no=new Set(["read","search"]),ac=new Set(["write","edit","patch","image_generate"]),lc=18e4,cc=3,Ye=1,uc=1,dc=1,fc=4,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"]),Ss=[{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}],oo=new Set(["write","edit","patch"]),pc=new Set(["read","search","exec"]);function Ms(e){let t=H(e),n=Se(t);return t.split("/").includes("context-pack")&&Z.has(n)?Ye:t.split("/").includes("benchmark-state")&&lo.has(n)?dc:t.includes("/qlogicagent-sessions/")&&t.includes("/tool-results/")?uc:cc}function Qn(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(Se(t))?"This compact benchmark-state file was already read this turn. Use the in-turn tool result, prior maintained summary, and decision state already in conversation; do not reread compact state files in a loop.":"Use the maintained index, prior tool results, or a narrow section-specific read instead of rereading the same file."}function co(e){let t=H(e);return t.split("/").includes("context-pack")&&Z.has(Se(t))}function Es(e){let t=H(e),o=t.indexOf("/context-pack/");return o<0?null:t.slice(0,o)}function mc(e){let t=[...e].filter(co).map(Es).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 Be(o)}catch{return!1}})}function gc(e){return[...Z.keys()].every(t=>e.has(t))}function Is(e){for(let t of e.values()){if(!t.path)continue;let n=Es(t.path);if(n)return`${n}/benchmark-state`}return null}function Ps(e){if(!gc(e))return[];let t=Is(e);return t?[...lo].map(n=>`${t}/${n}`).filter(n=>{try{return!Be(n)}catch{return!0}}):[]}function hc(e,t){let n=Ps(e);if(n.length===0)return null;let o=Is(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(`
|
|
37
|
+
`),l=Ss.map(a=>`${a.id}: ${a.decision}`).join(`
|
|
38
|
+
`);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.","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:",l].join(`
|
|
39
|
+
`)}function vs(e){return oo.has(e)}function yc(e){return e.benchmarkStateMaintenanceRequiredFiles.size>0&&[...e.benchmarkStateMaintenanceRequiredFiles].every(t=>Tc(e,t))}function Tc(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=ao(t,"utf8");return Ls(e,t,JSON.stringify({content:o})).ok}catch{return!1}}function Ls(e,t,n){let o=Se(t);if(o!=="document-index.json"&&o!=="context-pack-evidence.json")return{ok:!0};let r=Oc(n);if(!r)return{ok:!1,reason:`${o} write did not include JSON content`};let s=ye(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 p=e.maintainedDocuments.get(u),h=ue(a[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 l=ue(s.fileVerification);if(!l)return{ok:!1,reason:"context-pack-evidence.json missing fileVerification object"};for(let a of Z.keys()){let u=e.maintainedDocuments.get(a),p=ue(l[a]);if(!u||!p)return{ok:!1,reason:`context-pack-evidence.json missing ${a}`};if(p.contentHash!==u.contentHash)return{ok:!1,reason:`context-pack-evidence.json ${a} contentHash does not match read.details`};if(p.fileSizeBytes!==u.fileSizeBytes)return{ok:!1,reason:`context-pack-evidence.json ${a} fileSizeBytes does not match read.details`}}return{ok:!0}}function bc(e,t,n,o){if(e.filter(a=>a.name==="read"&&a.reason==="read-cycle-policy").length<fc)return!1;let s=new Set([...t].filter(co).map(Se));return[...Z.keys()].every(a=>s.has(a))?[...Z.keys()].every(a=>o.has(a))||n||mc(t):!1}function Os(e,t,n){if(e!=="write"||!n.has("edit")&&!n.has("patch"))return null;let o=Mt(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 St=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*Cc(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 St(t);if(r.done)return;yield r.value}}finally{n.return?.().catch(()=>{})}}function ro(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 Mt(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 kc(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 Rc(e){return e.flatMap(t=>{if(xc(t.function.arguments))return[t];let n=_c(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 xc(e){try{let t=JSON.parse(e);return!!t&&typeof t=="object"&&!Array.isArray(t)}catch{return!1}}function _c(e){let t=[],n=0,o=-1,r=!1,s=!1,l=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(l,a).trim())return[];o=a}n+=1;continue}if(u!=="}"||(n-=1,n!==0||o<0))continue;let p=ye(e.slice(o,a+1));if(!p)return[];t.push(p),l=a+1,o=-1}return n!==0||r||e.slice(l).trim()?[]:t}function ye(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 Se(e){let t=e.trim().replace(/\\/g,"/");return t.slice(t.lastIndexOf("/")+1).toLowerCase()}function uo(e){return`sha256:${Pl("sha256").update(e).digest("hex")}`}function vc(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,l=s.length>180?`${s.slice(0,177)}...`:s;return l.toLowerCase().includes(e.toLowerCase())?l:`${e}: ${l}`}function Ac(e){return Object.fromEntries([...e.entries()].sort(([t],[n])=>t.localeCompare(n)))}function wc(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("|"),l=Ss.map(u=>({...u,evidence:`read:long-horizon-documents:${uo(`${u.id}:${s}`)}`,lastConfirmedTurn:o})),a={strategy:"maintained-document-index",nextReadPolicy:"use maintained index before full document reread",budgetStatus:"within-budget",maxReadsPerDocument:Ye,observedReadsByPath:Ac(n)};return{type:"document_maintenance",turnId:e,checkpointId:`${e}-docs-${r.length}`,documents:r,decisionStateTable:l,readCycleFindings:[],readCycleGuard:a}}function Sc(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 Mc(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:Sc(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 Ec(e,t){let n=Mc(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 Ic(e,t,n,o,r){let s=so(t,n,o,r);if(!s)return!1;let l=s.name;return l?(e.maintainedDocuments.set(l,s),!0):!1}function so(e,t,n,o){let r=Se(e);if(!Z.has(r))return null;let s=Fc(t)??t,l=Nc(o,"contentHash"),a=Ne(o??null,"fileSizeBytes"),u=l??uo(s);return{name:r,path:H(e),indexed:!0,maintained:!0,indexVersion:u,contentHash:u,summary:vc(r,s),lastReviewedTurn:n,fileSizeBytes:a??Buffer.byteLength(s,"utf8"),recordCount:Ns(s)}}function Pc(e,t){return Os(e.function.name,e.function.arguments,t)!==null}function Lc(e,t){let n=Mt(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 Oc(e){let n=ye(e)?.content;return typeof n=="string"?n:void 0}function Nc(e,t){let n=e?.[t];return typeof n=="string"&&n.trim()?n.trim():void 0}function Ns(e){let t=e.split(/\r?\n/).map(n=>n.trim()).filter(Boolean).length;return Math.max(1,t)}function Fc(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)?ao(n,"utf8"):null}catch{return null}}function Bc(e){let t=new Map;for(let s of e)if(!(s.role!=="assistant"||!Array.isArray(s.tool_calls)))for(let l of s.tool_calls){if(l.function?.name!=="read"||typeof l.id!="string"||typeof l.function.arguments!="string")continue;let a=ro(l.function.arguments);if(!a)continue;let u=H(a);Ms(u)===Ye&&t.set(l.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 l=t.get(s.tool_call_id);if(!l)continue;let a=typeof s.content=="string"?s.content:"";if(!a||/^Error:/i.test(a.trim()))continue;n.set(l.path,(n.get(l.path)??0)+1);let u=so(l.path,a,0);u?.name&&o.set(u.name,u)}for(let s of qc(e)){r=!0;for(let l of Z.keys()){let a=H(`${s}/${l}`);if(n.set(a,Math.max(n.get(a)??0,Ye)),!o.has(l)){let u=so(a,`${l} maintained by benchmark-state/document-index.json from prior conversation history.`,0);u?.name&&o.set(u.name,u)}}}for(let s of Dc(e)){r=!0;for(let l of s.documents)!l.name||!l.path||(n.set(l.path,Math.max(n.get(l.path)??0,Ye)),o.set(l.name,l))}return{fileReadCounts:n,maintainedDocuments:o,persistedBenchmarkStateRecovered:r}}function Dc(e){let t=[];for(let n of $c(e)){let o=As(`${n}/document-index.json`),r=As(`${n}/context-pack-evidence.json`),s=Fe(o,"contextPackPath")??Uc(r);if(!s)continue;let l=jc(s,o,r);l.length===Z.size&&t.push({documents:l})}return t}function $c(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 l=H(s[1]??"");l&&t.add(l)}}return[...t]}function As(e){try{if(!Be(e))return null;let t=JSON.parse(ao(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()?H(n):void 0}function Uc(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 jc(e,t,n){let o=ue(t?.documents),r=ue(n?.fileVerification),s=[];for(let l of Z.keys()){let a=ue(o?.[l]),u=ue(r?.[l]);if(!a&&!u)return[];let p=Fe(a,"path"),T=Fe(u,"path")??(p?.includes("/context-pack/")?p:H(`${e}/${l}`)),k=Fe(a,"contentHash")??Fe(u,"contentHash")??uo(`${l}:${T}`),I=typeof a?.summary=="string"&&a.summary.trim()?a.summary.trim():`${l} maintained by persisted benchmark-state/document-index.json.`;s.push({name:l,path:H(T),indexed:!0,maintained:!0,indexVersion:String(a?.indexVersion??k),contentHash:k,summary:I,lastReviewedTurn:io(a,"lastReviewedTurn")??io(n,"turn")??0,fileSizeBytes:Ne(a,"fileSizeBytes")??Ne(u,"fileSizeBytes")??Ne(u,"sizeBytes")??Buffer.byteLength(I,"utf8"),recordCount:Ne(a,"recordCount")??Ne(u,"recordCount")??Ns(I)})}return s}function io(e,t){let n=e?.[t];return typeof n=="number"&&Number.isFinite(n)?n:void 0}function Ne(e,t){let n=io(e,t);return n&&n>0?n:void 0}function qc(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 l of s){let a=H(l[1]??"");a&&n.add(a)}}return[...n]}function zc(e){e.identicalSuccessfulToolResults.clear();for(let t of[...e.identicalCallCounts.keys()]){let n=t.slice(0,t.indexOf("::"));no.has(n)&&e.identicalCallCounts.delete(t)}}async function*Fs(e,t,n,o){let{turnId:r,sessionId:s,messages:l,availableTools:a,tools:u,model:p,apiKey:h,temperature:T=0,hooks:k,signal:I}=e,P={sessionId:s,turnId:r},x=e.maxTurns??0,E=e.querySource,A=e.runtimePorts.resolveToolEligibility(u,e.toolEligibilityContext),O=A.eligibleTools,F=[];for(let m of A.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=$r(e.maxRounds,l),oe=Ur(e.maxToolCalls,l),Et=!(typeof e.maxRounds=="number"&&e.maxRounds>=1)&&!(typeof e.maxToolCalls=="number"&&e.maxToolCalls>=1),fo=Ct(l),Me={contextWindowTokens:e.contextWindowTokens??Xo,responseBufferTokens:Vo,maxOutputTokens:e.maxOutputTokens??Yo,abortSignal:I,reactiveCompactEnabled:!0,outputEscalationEnabled:!0},L=new Set,N=0,De=0,$e=0,Ze=0,V=new Set,y=Ae(O,V),Ue=!1,It=!1,Pt,Lt=()=>b(y),qs=Ll(O,l),Ot=!1,po=0,mo=0,G=!1,Je=!1,Nt=Bc(l),c={messages:[...l],maxOutputTokensRecoveryCount:0,hasAttemptedReactiveCompact:!1,maxOutputTokensOverride:void 0,turnCount:1,transition:void 0,guardState:Rn(Me),reactiveCompactState:wn(),toolLoopState:gt({maxRounds:U,replayMessages:[...l]}).state,consecutiveFailedRounds:0,finalText:"",totalUsage:{inputTokens:0,outputTokens:0},collapseStore:sn(),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:Nt.fileReadCounts,fileReadCycleBlockedPaths:new Set,fileReadCycleNudgedPaths:new Set,maintainedDocuments:Nt.maintainedDocuments,persistedBenchmarkStateRecovered:Nt.persistedBenchmarkStateRecovered,benchmarkStateMaintenanceRequiredFiles:new Set,benchmarkStateMaintenanceWrittenFiles:new Set,recoveryTrace:new Map,artifactContract:wr(l),browserAcceptanceRecoveryCount:0,backgroundAgentTaskIds:new Set,backgroundAgentNoOutputPollCounts:new Map,stalledBackgroundAgentTasks:new Map,notOfferedToolRecoveryCount:0,existingFileUpdateRecoveryCount:0,taskListReconciliationCount:0,lastTaskList:[]},Ft=Math.max(x*5,200),zs=4,Hs=4,go=0,ho=new Map,Bt,S=(m,j)=>{let de=`${m}:${j??""}`,re=(ho.get(de)??0)+1;if(ho.set(de,re),m==="autocompact"){let D=c.recoveryTrace.get("autocompact")??0;if(re>zs||D>=Hs){let J=`Repeated context compression made no forward progress: ${j??"autocompact"}`;return Bt=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}},Gs=()=>({type:"tool_use_summary",turnId:r,availableToolNames:b(a??u),enabledToolNames:Lt(),toolCallNames:[...L].sort(),blockedToolCalls:_t(F)}),Ws=m=>Sr({content:m,inputMessages:l,messages:c.messages,totalToolCallCount:N,distinctToolNames:L,artifactContract:c.artifactContract,blockedToolCalls:_t(F),activeTasks:c.lastTaskList}),Ks=m=>({type:"end",turnId:r,content:m,usage:c.totalUsage,model:c.currentModel,...c.recoveryTrace.size>0?{recoveryTrace:Object.fromEntries(c.recoveryTrace)}:{}});function*W(m){let j=Ws(m);Nn(c.artifactContract,j),$t()&&(yield Dt()),yield Gs(),yield Ks(j)}let Dt=()=>({type:"artifact_contract",turnId:r,...On(c.artifactContract,l)}),$t=()=>{let m=On(c.artifactContract,l);return!!(m.requiresBrowserAcceptance||m.artifactRoot||m.writePaths.length>0||m.outOfRootWrites.length>0||m.devServerUrls.length>0||m.browserVerified)},Qe=(m,j)=>c.finalText||Bn(m,o),Xs=(m,j,de)=>{let re=ve({inputMessages:l,messages:j,reason:de});return re||m||Bn(j,o)};for(;;){if(go++,go>Ft){o.info(`hard iteration cap reached (${Ft}), forcing completion`);let i=Qe(c.messages,`hard iteration cap reached (${Ft}) before completing the final status contract`);yield*W(i);return}let{messages:m,maxOutputTokensRecoveryCount:j,maxOutputTokensOverride:de,turnCount:re,guardState:D,reactiveCompactState:J,collapseStore:Ut}=c,{toolLoopState:Q}=c;if(e.refreshTools&&re>1){let i=e.refreshTools(),d=Ae(i,V);d!==y&&(y=d,o.debug(`tools refreshed: ${i.length} tools`))}if(An(D,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=xn(D,Me);if(Te.level==="blocking"){Te.reason==="prompt_too_long"&&Oe(J)&&(J.attemptedThisTurn=!0,D.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*Wr({messages:m,contentReplacementState:c.contentReplacementState,snipRemovedIds:c.snipRemovedIds,collapseStore:Ut,guardState:D,guardConfig:Me,runtimePorts:e.runtimePorts,hooks:k,hookCtx:P,sessionId:s,currentModel:c.currentModel,log:o,recovery:S,onAutocompact:()=>{c.hasAttemptedReactiveCompact=!1}});if(Bt){yield*W(`${Bt}. Stop compressing the same context repeatedly; continue from the maintained document index or report the incomplete state explicitly.`);return}let Vs=G?"required":e.toolChoice==="required"&&Ot?"auto":e.toolChoice??"auto";G=!1;let Ee=mn({tools:y,toolChoice:Vs}),yo=b(Ee.tools).join("\0"),To=Pt!==void 0&&Pt!==yo;To&&c.lastResponseId&&(yield S("stateless_retry","tool schema changed; replaying full history without previous_response_id"));let Ys=Je||To?void 0:c.lastResponseId;Pt=yo;let je=gt({maxRounds:U,replayMessages:et,lastStopReason:Q.lastStopReason,options:{stopReason:Q.lastStopReason}}),bo=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(i=>i.detail??i.kind).join("; ")}`),o.debug(`turn ${re}, messages: ${bo.length}`),B(k,"turn.before_inference",{...P,model:c.currentModel},o);let jt=!1,qt=[],Co=new Map,ko="stop",ee,w=null,tt=!1,Ro=!1,qe=[],le=[];try{let i=t.stream({model:c.currentModel,messages:bo,...Ee.tools.length>0?{tools:Ee.tools,toolChoice:Ee.normalizedToolChoice??"auto"}:{},temperature:T,maxTokens:(de??D.currentMaxOutputTokens)||void 0,streamRequired:e.streamRequired,previousResponseId:Ys,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 Cc(i,e.llmStreamIdleTimeoutMs??lc))switch(d.type){case"delta":qt.push(d.text);break;case"tool_call_delta":jt=!0,Sn(Co,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":Ro=!0,ko=d.finishReason;break}if(jt||B(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(i){if(i instanceof St){B(k,"stop.failure",{sessionId:s,reason:i.code,error:i.message},o),yield{type:"error",turnId:r,error:i.message,code:i.code,usage:c.totalUsage};return}let d=yield*Kr(i,{state:c,guardState:D,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}w=d.streamError}if(!w&&!Ro){let i="LLM stream closed before a terminal event; the response was likely truncated upstream.";B(k,"stop.failure",{sessionId:s,reason:"RETRYABLE_TRANSIENT",error:i},o),yield{type:"error",turnId:r,error:i,code:"RETRYABLE_TRANSIENT",usage:c.totalUsage};return}if(w&&B(k,"turn.after_inference",{...P,model:c.currentModel,response:{error:w.message}},o),w){if(!Je&&c.lastResponseId&&/previous_response_id not found/i.test(w.message)){let i=(c.consecutiveApiRetries??0)+1;if(i<=xe){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:i,transition:void 0};continue}}if(jn(w))tt=!0,o.info(`withheld prompt_too_long error (status=${w.status})`);else if(qn(w))tt=!0,o.info(`withheld media_size error (status=${w.status})`);else{let i=_n({status:w.status??500,message:w.message},D,Me);if(i.action==="reactive_compact"&&Oe(J)&&(J.attemptedThisTurn=!0,D.hasAttemptedReactiveCompact=!0,yield S("reactive_compact",`API ${w.status??500}: ${w.message}`)),i.action==="retry"){let g=(c.consecutiveApiRetries??0)+1;if(g>xe){o.info(`API retry limit reached (${xe}), aborting`);let f=Le(w.status,w.message);yield{type:"error",turnId:r,error:w.message,code:f,usage:c.totalUsage};return}yield S("retry",i.reason),c={...c,consecutiveApiRetries:g,transition:void 0};continue}let d=Le(w.status,w.message);B(k,"stop.failure",{sessionId:s,reason:d,error:w.message},o),yield{type:"error",turnId:r,error:w.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&&(D.promptTokens=ee.inputTokens);let nt=qt.join(""),te=[...Co.values()].map((i,d)=>({id:i.id||`tc_${r}_${d}`,type:"function",function:{name:i.name,arguments:i.arguments}}));if(te=Rc(te),te.length===0&&!jt){if(nt&&(c.finalText=nt),e.toolChoice==="required"&&!Ot&&y.length>0&&po<2){po++;let C=y.map(_=>_.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(tt&&w&&jn(w)){if(c.transition?.reason!=="collapse_drain_retry"){let C=ln(et,Ut);if(C.committed>0){o.info(`collapse drain: committed ${C.committed} stages`),yield S("collapse_drain",`${C.committed} stages committed`),c={...c,messages:C.messages,transition:{reason:"collapse_drain_retry",committed:C.committed}};continue}}if(Oe(J)){J.attemptedThisTurn=!0,D.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"),B(k,"stop.failure",{sessionId:s,reason:"prompt_too_long",error:w.message},o),yield{type:"error",turnId:r,error:w.message,code:"PROMPT_TOO_LONG",usage:c.totalUsage};return}if(tt&&w&&qn(w)){if(Oe(J)){J.attemptedThisTurn=!0,D.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"),B(k,"stop.failure",{sessionId:s,reason:"media_error",error:w.message},o),yield{type:"error",turnId:r,error:w.message,code:"IMAGE_ERROR",usage:c.totalUsage};return}if(zr(ko)){D.consecutiveTruncations+=1;let C=e.modelMaxOutputTokens??Zo,_=vn(D,Me,C);if(_.shouldEscalate&&de===void 0){D.currentMaxOutputTokens=_.newMax,o.info(`max_output_tokens escalate: ${_.newMax} tokens`),yield S("output_escalation",`${_.newMax} tokens`),c={...c,maxOutputTokensOverride:Qo,transition:{reason:"max_output_tokens_escalate"}};continue}if(j<Jo){let K={role:"user",content:"Output token limit hit. Resume directly - no apology, no recap of what you were doing. Pick up mid-thought if that is where the cut happened. Break remaining work into smaller pieces."};o.info(`max_output_tokens recovery #${j+1}`),yield S("max_output_tokens_recovery",`attempt ${j+1}`),c={...c,messages:[...et,K],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 D.consecutiveTruncations=0;Q=mt(Q,{replayMessages:m,lastStopReason:"completed"});let i=await is({hooks:k,sessionId:s,messages:m,finalText:c.finalText,thinkingBlocks:le,log:o});if(i?.action==="end"){let C=Xs(i.content,m,"stop hook prevented continuation before completing the final status contract");yield*W(C);return}if(i?.action==="continue"){c={...c,messages:i.messages,stopHookActive:i.stopHookActive,transition:i.transition};continue}let d=as({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()&&Xl(c.lastTaskList)&&c.taskListReconciliationCount<2){let C=y.find(_=>_.function.name==="task")??(a??u).find(_=>_.function.name==="task");if(C){let _=Kl(c.lastTaskList),K=b(y);y=[C],c={...c,taskListReconciliationCount:c.taskListReconciliationCount+1,messages:[...m,{role:"assistant",content:c.finalText},{role:"user",content:_}],transition:{reason:"next_turn"}},G=!0,yield{type:"tool_selection_policy",turnId:r,policyId:"task_list_reconciliation_required",intent:"lifecycle_reconciliation",reason:"task-list-final-status-mismatch",availableToolNames:b(a??u),enabledToolNamesBefore:K,enabledToolNamesAfter:b(y),suppressedToolNames:K.filter(X=>X!=="task"),nextAction:"reconcile-task-list-before-final"},yield S("task_list_reconciliation_required","forcing task tool reconciliation before final response");continue}}if(ie(l)&&!c.artifactContract.browserVerified&&wt(c.artifactContract).length>0&&y.some(C=>C.function.name==="exec")&&c.browserAcceptanceRecoveryCount<4){let C=Rs(c.artifactContract);c={...c,browserAcceptanceRecoveryCount:c.browserAcceptanceRecoveryCount+1,messages:[...m,{role:"assistant",content:c.finalText},{role:"user",content:C}],transition:{reason:"next_turn"}},G=!0,yield S("browser_acceptance_required","forcing browser automation before app/frontend completion");continue}let g=Vn({inputMessages:l,messages:m,finalText:c.finalText,thinkingBlocks:le,stopHookActive:c.stopHookActive,totalToolCallCount:N,distinctToolNames:L,log:o});if(g){if(c.stopHookActive&&c.finalText.trim()===""){let C=ve({inputMessages:l,messages:g.messages,reason:"stop hook produced an empty response after tool use"});if(C){yield*W(C);return}}c={...c,messages:g.messages,stopHookActive:g.stopHookActive,transition:g.transition};continue}if(N===0&&y.length>0&&e.toolChoice!=="none"&&mo<1&&Dr(nt)){mo++,G=!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=Yn({totalToolCallCount:N,distinctToolNames:L,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 C of qt)yield{type:"delta",turnId:r,text:C};yield*W(R);return}let Zs=le.length===0&&qe.length>0?qe.join(""):void 0;m.push(tn(te,void 0,le.length>0?le:void 0,Zs)),Q=bn(Q,{replayMessages:m,pendingToolCallIds:te.map(i=>i.id),completedToolCallIds:Q.completedToolCallIds,lastStopReason:"tool_calls"});let ot=c.identicalCallCounts,ze=[],ce=[],He=[],xo=!1;for(let i of te){if(ec(i,c)){ze.push(i);continue}let d=`${i.function.name}::${i.function.arguments}`,g=ot.get(d)??0;if(ot.set(d,g+1),g+1>Ko){let f=no.has(i.function.name)||i.function.name==="exec"?c.identicalSuccessfulToolResults.get(d):void 0;if(f){He.push({call:i,result:f,repeatCount:g+1});continue}ce.push(i),xo||(xo=!0,o.info(`AP4 blocked: ${i.function.name} repeated ${g+1}x`))}else ze.push(i)}let q=[],Js=new Set(y.map(i=>i.function.name)),_o=new Set(ce.filter(i=>Pc(i,Js)).map(i=>i.id));for(let i of He){let d=i.call,g=`Reused previous successful ${d.function.name} result for identical arguments (attempt ${i.repeatCount}); no additional tool execution was performed.
|
|
40
|
+
|
|
41
|
+
${i.result.content}`,f=z(d.id,{ok:!0,payload:g,imageUrls:i.result.imageUrls,toolReferences:i.result.toolReferences});m.push(f),q.push(d.id),L.add(d.function.name),N++,yield{type:"tool_result",turnId:r,callId:d.id,name:d.function.name,ok:!0,outputPreview:g.slice(0,2e3),durationMs:0,details:{type:d.function.name,reusedIdenticalCall:!0,repeatCount:i.repeatCount}}}if(He.some(i=>i.call.function.name==="exec"&&xs(i.call.function.arguments))){let i=b(y);m.push({role:"user",content:Wl(c.artifactContract)}),yield{type:"tool_selection_policy",turnId:r,policyId:"browser_verification_after_preparation_required",intent:"verification",reason:"repeated-browser-preparation-command",availableToolNames:b(a??u),enabledToolNamesBefore:i,enabledToolNamesAfter:i,suppressedToolNames:[],nextAction:"run-browser-verification-script-not-playwright-install"},yield S("browser_verification_after_preparation_required","reused successful browser preparation command")}for(let i of ce){F.push({name:i.function.name,reason:"identical-repeat-policy"});let d=ot.get(`${i.function.name}::${i.function.arguments}`),g=bt(m,i.function.name),f=Ul(g),R=_o.has(i.id)?Lc(d,i):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.`,C=z(i.id,{ok:!1,error:R});m.push(C),q.push(i.id),L.add(i.function.name),N++,yield{type:"tool_result",turnId:r,callId:i.id,name:i.function.name,ok:!1,error:R}}if(ce.length>0&&ze.length===0&&He.length===0&&ce.every(i=>_o.has(i.id))&&c.existingFileUpdateRecoveryCount<2){let i=b(y);y=Ts(O,V);let d=b(y);Ue=!0,G=!0;let g=[...new Set(ce.map(f=>Mt(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:b(a??u),enabledToolNamesBefore:i,enabledToolNamesAfter:d,suppressedToolNames:Jn(i,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 i=bt(m,ce[0].function.name),d={role:"user",content:"Tool calls were blocked because you repeated them with identical arguments too many times. "+(i?`The error was: "${i}". Tell the user about this error. `:"The operation is not working. ")+"Stop retrying and report the result to the user."};m.push(d)}let Qs=fo>=3&&c.repeatedToolFailureRecoveryCount<1;if(ce.length>0&&ze.length===0&&He.length===0&&!Qs){let i=_s(Dn(m,1),{availableToolNames:b(a??u),enabledToolNames:Lt(),toolCallNames:[...L].sort(),blockedToolCalls:_t(F)});yield*W(i);return}let vo=[],zt=[];for(let i of ze){let d=vr({toolName:i.function.name,rawArguments:i.function.arguments});d?zt.push({call:i,...d}):vo.push(i)}for(let i of zt){let d=i.call;F.push({name:d.function.name,reason:"read-only-context-pack"}),m.push(z(d.id,{ok:!1,error:i.error})),q.push(d.id),L.add(d.function.name),N++,yield{type:"tool_result",turnId:r,callId:d.id,name:d.function.name,ok:!1,error:i.error},o.warn(`read-only context-pack blocked: ${d.function.name} ${i.path}`)}zt.length>0&&m.push({role:"user",content:"A write was blocked because context-pack is read-only evidence. Continue by writing compact indexes, checkpoints, and maintenance updates under benchmark-state; do not retry writes into context-pack."});let ei=new Set(y.map(i=>i.function.name)),Ao=[],rt=[];for(let i of vo){let d=Os(i.function.name,i.function.arguments,ei);d?rt.push({call:i,...d}):Ao.push(i)}for(let i of rt){let d=i.call;F.push({name:d.function.name,reason:"existing-file-update-tool-required"}),m.push(z(d.id,{ok:!1,error:i.error})),q.push(d.id),L.add(d.function.name),N++,yield{type:"tool_result",turnId:r,callId:d.id,name:d.function.name,ok:!1,error:i.error},o.info(`existing file update blocked: ${d.function.name} ${i.path}`)}if(rt.length>0){let i=b(y);y=Ts(O,V);let d=b(y);Ue=!0,G=!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:b(a??u),enabledToolNamesBefore:i,enabledToolNamesAfter:d,suppressedToolNames:Jn(i,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 wo=[],Ht=[];for(let i of Ao){let d=_r({state:c.artifactContract,inputMessages:l,toolName:i.function.name,rawArguments:i.function.arguments});d?Ht.push({call:i,...d}):wo.push(i)}for(let i of Ht){let d=i.call;F.push({name:d.function.name,reason:"artifact-root-contract"}),Ln(c.artifactContract,{path:i.path,artifactRoot:i.artifactRoot,toolName:d.function.name}),m.push(z(d.id,{ok:!1,error:i.error})),q.push(d.id),L.add(d.function.name),N++,yield{type:"tool_result",turnId:r,callId:d.id,name:d.function.name,ok:!1,error:i.error},$t()&&(yield Dt()),o.warn(`artifact root contract blocked: ${d.function.name}`)}Ht.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 So=[],Gt=[];for(let i of wo){let d=ss({inputMessages:l,messages:m,toolCall:i});d?Gt.push({call:i,error:d}):So.push(i)}for(let i of Gt){let d=i.call;F.push({name:d.function.name,reason:"premature-completion-artifact"}),m.push(z(d.id,{ok:!1,error:i.error})),q.push(d.id),L.add(d.function.name),N++,yield{type:"tool_result",turnId:r,callId:d.id,name:d.function.name,ok:!1,error:i.error},o.info(`premature completion artifact blocked: ${d.function.name}`)}Gt.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 ti=new Set(y.map(i=>i.function.name)),Mo=[],st=[];for(let i of So)ti.has(i.function.name)?Mo.push(i):st.push(i);for(let i of st){let d=`Tool "${i.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:i.function.name,reason:"not-offered"}),m.push(z(i.id,{ok:!1,error:d})),q.push(i.id),L.add(i.function.name),o.warn(`unoffered tool call suppressed: ${i.function.name}`)}if(st.length>0&&c.notOfferedToolRecoveryCount<1){let i=[...new Set(st.map(C=>C.function.name))].sort(),d=Ue&&i.includes("write"),g=i.filter(C=>V.has(C)),f=a??u,R=f.filter(C=>i.includes(C.function.name));if(g.length>0)c.notOfferedToolRecoveryCount+=1,G=!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, 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:b(a??u),enabledToolNamesBefore:b(y),enabledToolNamesAfter:b(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 C=b(y),_=new Map(y.map(X=>[X.function.name,X]));for(let X of R)_.set(X.function.name,X);let K=f.find(X=>X.function.name==="tool_search");K&&_.set(K.function.name,K),y=eo([..._.values()]),c.notOfferedToolRecoveryCount+=1,G=!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:b(a??u),enabledToolNamesBefore:C,enabledToolNamesAfter:b(y),suppressedToolNames:[],nextAction:"retry-with-reenabled-requested-tool-or-tool-search"},m.push({role:"user",content:`You called ${i.map(X=>`\`${X}\``).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",i.join(","))}}let Eo=[],Wt=[];for(let i of Mo){let d=y.find(f=>f.function.name===i.function.name),g=Yl(d,i.function.arguments);g?Wt.push({call:i,error:g}):Eo.push(i)}for(let i of Wt){let d=i.call;F.push({name:d.function.name,reason:"invalid-arguments"}),c.toolFailureCounts,d.function.name,m.push(z(d.id,{ok:!1,error:i.error})),q.push(d.id),L.add(d.function.name),N++,yield{type:"tool_result",turnId:r,callId:d.id,name:d.function.name,ok:!1,error:i.error,details:{type:d.function.name,error:"invalid_arguments"}},o.info(`invalid tool arguments blocked: ${d.function.name}`)}Wt.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=[],Kt=[];for(let i of Eo){if(i.function.name!=="exec"){it.push(i);continue}let d=bs(i.function.arguments);if(!d){it.push(i);continue}let g=ms(d);gs(g)&&ys(O)?Kt.push({call:i,error:Vl()}):it.push(i)}for(let i of Kt){let d=i.call;F.push({name:d.function.name,reason:"dedicated-tool-required"});let g=b(y),f=y.filter(R=>["read","search"].includes(R.function.name));f.length>0&&(y=f,It=!0,G=!0),m.push(z(d.id,{ok:!1,error:i.error})),q.push(d.id),L.add(d.function.name),N++,yield{type:"tool_result",turnId:r,callId:d.id,name:d.function.name,ok:!1,error:i.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:b(a??u),enabledToolNamesBefore:g,enabledToolNamesAfter:b(y),suppressedToolNames:g.filter(R=>!["read","search"].includes(R)),nextAction:"use-read-search-for-file-inspection-then-resume-build-run-verify-tools"}}Kt.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 Xt=[],Vt=[];for(let i of it){if(i.function.name!=="tool_search"){Xt.push(i);continue}let g=kc(i.function.arguments).filter(f=>V.has(f));g.length>0?Vt.push({call:i,selectedNames:g}):Xt.push(i)}for(let i of Vt){let d=i.call,f=`tool_search cannot activate ${i.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(z(d.id,{ok:!1,error:f})),q.push(d.id),L.add(d.function.name),N++,yield{type:"tool_result",turnId:r,callId:d.id,name:d.function.name,ok:!1,error:f,details:{type:d.function.name,error:"policy_suppressed_selection",selectedNames:i.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:b(a??u),enabledToolNamesBefore:b(y),enabledToolNamesAfter:b(y),suppressedToolNames:i.selectedNames,nextAction:"search-alternative-tool-or-use-currently-enabled-tools"}}Vt.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=[],Yt=[],Io=[],Po=[];for(let i of Xt){if(i.function.name!=="exec"){at.push(i);continue}let d=i,g=bs(d.function.arguments),f=g?zl(g):null;f&&(d={...d,function:{...d.function,arguments:ks(d.function.arguments,f)}},Po.push({originalCommand:g??"",rewrittenCommand:f}),g=f);let R=g?Hl(g):null;if(R?.action==="block")Yt.push({call:d,error:R.error});else if(R?.action==="rewrite"){let C={...d,function:{...d.function,arguments:ks(d.function.arguments,R.command)}};Io.push({call:C,originalCommand:g??"",rewrittenCommand:R.command}),at.push(C)}else at.push(d)}for(let i of Po)yield{type:"tool_selection_policy",turnId:r,policyId:"exec_sleep_prefix_guard",intent:"verification",reason:"sleep-prefix-removed",availableToolNames:b(a??u),enabledToolNamesBefore:b(y),enabledToolNamesAfter:b(y),suppressedToolNames:[],nextAction:"execute-command-without-blocking-sleep-prefix"},o.info(`blocking sleep prefix removed before exec: ${i.originalCommand} -> ${i.rewrittenCommand}`);for(let i of Io){let d=b(y);yield{type:"tool_selection_policy",turnId:r,policyId:"reserved_frontend_port_guard",intent:"verification",reason:"vite-strict-port-normalized",availableToolNames:b(a??u),enabledToolNamesBefore:d,enabledToolNamesAfter:b(y),suppressedToolNames:[],nextAction:"execute-normalized-vite-dev-server-command-with-strict-port"},o.info(`vite strict port normalized before exec: ${i.originalCommand} -> ${i.rewrittenCommand}`)}for(let i of Yt){let d=i.call;F.push({name:d.function.name,reason:"reserved-frontend-port"});let g=b(y);m.push(z(d.id,{ok:!1,error:i.error})),q.push(d.id),L.add(d.function.name),N++,yield{type:"tool_result",turnId:r,callId:d.id,name:d.function.name,ok:!1,error:i.error,details:{type:d.function.name,error:"reserved_frontend_port",reservedPort:At}},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:b(a??u),enabledToolNamesBefore:g,enabledToolNamesAfter:b(y),suppressedToolNames:[],nextAction:"restart-generated-dev-server-on-explicit-non-5174-port-with-strict-port"}}Yt.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 i of at){if(i.function.name!=="read"){lt.push(i);continue}let d=ro(i.function.arguments);if(!d){lt.push(i);continue}let g=H(d),f=Ms(g);(c.fileReadCounts.get(g)??0)>=f?Ie.push({call:i,filePath:g,maxReads:f}):lt.push(i)}for(let i of Ie){let d=i.call,g=`Read cycle policy blocked another read of "${i.filePath}" after ${i.maxReads} successful reads in this turn. Stop rereading the same large document. ${Qn(i.filePath)}`;F.push({name:d.function.name,reason:"read-cycle-policy"}),c.fileReadCycleBlockedPaths.add(i.filePath),m.push(z(d.id,{ok:!1,error:g})),q.push(d.id),L.add(d.function.name),N++,yield{type:"tool_result",turnId:r,callId:d.id,name:d.function.name,ok:!1,error:g},o.info(`read cycle blocked: ${i.filePath}`)}if(Ie.length>0){let i=[...new Set(Ie.map(f=>`${f.filePath} (max ${f.maxReads})`))].join(", "),d=[...new Set(Ie.map(f=>Qn(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: ${i}. 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=>vs(f.function.name))&&(c.persistedBenchmarkStateRecovered||Ie.some(f=>co(f.filePath)))){let f=b(y),R=f.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:b(a??u),enabledToolNamesBefore:f,enabledToolNamesAfter:b(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(bc(F,c.fileReadCycleBlockedPaths,c.persistedBenchmarkStateRecovered,c.maintainedDocuments)){yield*W("Stopped repeated long-horizon context-pack rereads after the read-cycle guard blocked every maintained source document. Continue from benchmark-state/document-index.json, decision-state-table.json, and context-pack-evidence.json; do not reread or rewrite context-pack source documents.");return}}let Zt=ls(lt,c.toolFailureCounts),Jt=Zt.allowed;if(Et&&Jt.length>Math.max(0,oe-N)){let i=Un({currentToolBudget:oe,currentRoundBudget:U,toolHardCap:100,roundHardCap:100,continuationCount:$e,successfulSinceLastCheck:De-Ze,fileReadCounts:c.fileReadCounts,windowTools:me,windowRounds:25});i&&(oe=i.nextToolBudget,U=i.nextRoundBudget,$e=i.continuationCount,Ze=De,o.info(`tool budget continuation #${i.continuationCount}: tools\u2192${oe}, rounds\u2192${U} (progress detected)`))}let Lo=Math.max(0,oe-N),fe=Lo>0?Jt.slice(0,Lo):[],Qt=Jt.slice(fe.length),ni=Qt.length>0;if(Zt.blocked.length>0){for(let i of Zt.blocked){let d=i.call;F.push({name:d.function.name,reason:"variant-failure-policy"});let g=z(d.id,{ok:!1,error:i.error});m.push(g),q.push(d.id),L.add(d.function.name),N++,yield{type:"tool_result",turnId:r,callId:d.id,name:d.function.name,ok:!1,error:i.error},o.info(`variant tool blocked: ${d.function.name} failed ${i.failCount}x with different args`)}m.push(cs())}if(Qt.length>0){let i=`Tool call budget exhausted (${oe}) for this turn. Stop requesting more tools and report what remains incomplete.`;for(let d of Qt){F.push({name:d.function.name,reason:"tool-call-budget"});let g=z(d.id,{ok:!1,error:i});m.push(g),q.push(d.id),L.add(d.function.name),N++,yield{type:"tool_result",turnId:r,callId:d.id,name:d.function.name,ok:!1,error:i}}m.push({role:"user",content:`${i} 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 i of fe){let d=i.function.arguments,g=y.find(f=>f.function.name===i.function.name);if(g?.backfillObservableInput)try{let f=JSON.parse(i.function.arguments),R={...f};g.backfillObservableInput(R),Object.keys(R).some(_=>!(_ in f))&&(d=JSON.stringify(R))}catch{}yield{type:"tool_call",turnId:r,callId:i.id,name:i.function.name,arguments:d,inputSummary:$n(d)}}let oi=new Map(c.toolFailureCounts),ct=null;try{let i=e.runtimePorts.createStreamingToolExecutor({toolInvoker:n,hooks:k,sessionId:s,turnId:r,log:o,signal:I,maxConcurrentTools:e?.maxConcurrentTools,maxExecutionMs:Go});for(let f of fe)i.addTool(f);let d=!1;for await(let f of i.getRemainingResults()){let R=Dl(f);if(R){if(F.push({name:f.toolName,reason:R}),f.toolName==="exec"&&R==="dedicated-tool-required"&&ys(O)){let v=b(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:b(a??u),enabledToolNamesBefore:v,enabledToolNamesAfter:b(y),suppressedToolNames:[],nextAction:"use-read-search-for-file-inspection-or-exec-for-build-run-verify"}}if(f.toolName==="exec"&&R==="confirmation-timeout"){let v=b(y);V.add("exec");let M=Ae(O,V);M.length>0&&(y=eo(M),G=!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:b(a??u),enabledToolNamesBefore:v,enabledToolNamesAfter:b(y),suppressedToolNames:Jn(v,b(y)),nextAction:"continue-with-non-exec-tools-or-report-confirmation-blocker"}}if(f.toolName==="exec"&&R==="global-process-kill-blocked"){let v=b(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:b(a??u),enabledToolNamesBefore:v,enabledToolNamesAfter:b(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),q.push(f.callId),L.add(f.toolName);let C=tc(f,c);C||N++;let _=f.ok&&Or(f);if(f.ok&&!_&&!C&&(De+=1),C||us({toolFailureCounts:c.toolFailureCounts,toolName:f.toolName,toolArguments:fe.find(v=>v.id===f.callId)?.function.arguments,ok:f.ok,softEmpty:_}),f.ok&&ac.has(f.toolName)&&zc(c),f.ok&&vs(f.toolName)){let v=fe.find($=>$.id===f.callId),M=v?Mt(v.function.arguments):void 0;if(M){let $=H(M);if(c.benchmarkStateMaintenanceRequiredFiles.has($)){let se=Ls(c,$,v?.function.arguments??"");se.ok?c.benchmarkStateMaintenanceWrittenFiles.add($):(F.push({name:f.toolName,reason:"benchmark-state-invalid-content"}),m.push({role:"user",content:`Benchmark-state maintenance write for ${$} 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&&!_&&(no.has(f.toolName)||f.toolName==="exec"&&f.details?.type==="exec_background"||f.toolName==="exec"&&xs(fe.find(v=>v.id===f.callId)?.function.arguments??""))){let v=fe.find($=>$.id===f.callId),M=typeof f.message?.content=="string"?f.message.content:"";if(v&&M){let $=Array.isArray(f.message.imageUrls)?f.message.imageUrls.filter(pe=>typeof pe=="string"):void 0,se=Array.isArray(f.message.toolReferences)?f.message.toolReferences.filter(pe=>typeof pe=="string"):void 0;c.identicalSuccessfulToolResults.set(`${v.function.name}::${v.function.arguments}`,{content:M,imageUrls:$,toolReferences:se})}}if(f.toolName==="agent"){let v=we(f.details,"agentId"),M=we(f.details,"status"),$=to(f.details,"background");f.ok&&v&&$===!0&&M==="running"&&he(c).add(v)}if(f.toolName==="task"){let v=ic(f.details);v&&(c.lastTaskList=v);let M=we(f.details,"taskId"),$=to(f.details,"running"),se=we(f.details,"lifecycle"),pe=we(f.details,"action");if(M&&(pe==="cancel"||$===!1||se&&se!=="running"&&se!=="pending"))he(c).delete(M),c.backgroundAgentNoOutputPollCounts.delete(M),c.stalledBackgroundAgentTasks.delete(M);else if(M&&pe==="output"&&$===!0&&he(c).has(M)){let Oo=typeof f.message?.content=="string"?f.message.content:"";if(rc(Oo)){let en=(c.backgroundAgentNoOutputPollCounts.get(M)??0)+1;c.backgroundAgentNoOutputPollCounts.set(M,en);let dt=sc(Oo);(dt!==void 0&&dt>=nc||dt===void 0&&en>=oc)&&c.stalledBackgroundAgentTasks.set(M,`no output after ${dt??"unknown"}s across ${en} poll(s)`)}else c.backgroundAgentNoOutputPollCounts.delete(M),c.stalledBackgroundAgentTasks.delete(M)}}if(f.ok&&f.toolName==="read"){let v=fe.find(M=>M.id===f.callId);if(v){let M=ro(v.function.arguments);if(M){let $=H(M),se=c.fileReadCounts.get($)??0;c.fileReadCounts.set($,se+1);let pe=typeof f.message?.content=="string"?f.message.content:"";d=Ic(c,M,pe,c.turnCount,f.details)||d}}}yield hr(r,f);for(let v of yr(r,f))yield v;for(let v of Tr({turnId:r,result:f,toolCalls:te}))yield v;let X=te.find(v=>v.id===f.callId),si=typeof f.message?.content=="string"?f.message.content:"";X&&(Ar({state:c.artifactContract,inputMessages:l,toolName:f.toolName,rawArguments:X.function.arguments,ok:f.ok,content:si}),$t()&&(yield Dt())),!ct&&qs&&f.toolName==="stt"&&f.ok&&(ct=Ol(l,f))}if(Ue&&(y=Ae(O,V),Ue=!1),It&&(y=Ae(O,V),It=!1),d){let f=wc(r,c.maintainedDocuments,c.fileReadCounts,c.turnCount);f&&(yield f);for(let _ of Ec(r,c.maintainedDocuments))yield _;let R=hc(c.maintainedDocuments,c.turnCount),C=y.some(_=>oo.has(_.function.name));if(R&&C){c.benchmarkStateMaintenanceRequiredFiles=new Set(Ps(c.maintainedDocuments).map(H));for(let _ of y)oo.has(_.function.name)||V.add(_.function.name);y=Ae(y,V),G=!0,m.push({role:"user",content:R}),yield S("benchmark_state_maintenance_required","forcing write/edit/patch after long-horizon document index")}}let g=he(c);if(g.size>0){let f=(a??u).find(R=>R.function.name==="task");if(f){let R=b(y),C=[...g].filter(_=>c.stalledBackgroundAgentTasks.has(_)).sort();if(C.length>0){y=[f],G=!0;let _=C.map(K=>`${K}: ${c.stalledBackgroundAgentTasks.get(K)}`).join("; ");m.push({role:"user",content:Ql(C,{reason:_})}),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:b(a??u),enabledToolNamesBefore:R,enabledToolNamesAfter:b(y),suppressedToolNames:R.filter(K=>K!=="task"),nextAction:"cancel-stalled-background-task"},yield S("background_agent_no_output_watchdog_cancel_required",_);continue}y=[f],G=!0,m.push({role:"user",content:Jl(g)}),yield{type:"tool_selection_policy",turnId:r,policyId:"background_agent_lifecycle_poll_required",intent:"lifecycle_reconciliation",reason:"background-agent-task-unresolved",availableToolNames:b(a??u),enabledToolNamesBefore:R,enabledToolNamesAfter:b(y),suppressedToolNames:R.filter(_=>_!=="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=Ae(O,V));if(ie(l)&&!c.artifactContract.browserVerified&&wt(c.artifactContract).length>0&&y.some(f=>f.function.name==="exec")&&c.browserAcceptanceRecoveryCount<4){let f=Rs(c.artifactContract);c={...c,browserAcceptanceRecoveryCount:c.browserAcceptanceRecoveryCount+1,messages:[...m,{role:"user",content:f}],transition:{reason:"next_turn"}},G=!0,yield S("browser_acceptance_required","forcing browser automation after localhost app URL was observed");continue}if(yc(c)){yield*W("Maintained benchmark-state files after indexing the context pack. Stopping this turn now because the required document-index.json, decision-state-table.json, and context-pack-evidence.json writes are complete; do not continue into extra writes, context-pack modifications, or repeated reads.");return}}catch(i){let d=i instanceof Error?i.message:String(i);yield{type:"error",turnId:r,error:d,code:"TOOL_EXECUTION_ERROR",usage:c.totalUsage};return}if(ct){yield*W(ct);return}if(m.push(...ds({toolFailureCounts:c.toolFailureCounts,snapshot:oi})),ni){let i=ve({inputMessages:l,messages:m,reason:`tool call budget exhausted (${oe}) before completing all required files`});if(i){yield*W(i);return}}Q=mt(Q,{replayMessages:m,completedToolCallIds:[...Q.completedToolCallIds,...q],lastStopReason:"tool_calls"}),e.toolChoice==="required"&&te.length>0&&(Ot=!0);let ri=te.length>0&&te.every(i=>{let d=m.find(f=>f?.role==="tool"&&f?.tool_call_id===i.id);if(!d)return!0;let g=d.content;return typeof g=="string"&&g.startsWith("Error: ")}),be=c.consecutiveFailedRounds;if(ri){if(be+=1,be>=Wo){if(fo>=3&&c.repeatedToolFailureRecoveryCount<1){let f=Vn({inputMessages:l,messages:m,finalText:c.finalText,thinkingBlocks:[],stopHookActive:c.stopHookActive,totalToolCallCount:N,distinctToolNames:L,log:o});if(f?.reason==="explicit_required_file_verification"||f?.reason==="explicit_extra_file_verification"){yield S("repeated_tool_failure_artifact_recovery","one recovery nudge before ending a complex explicit artifact turn after repeated tool failures"),c={...c,messages:f.messages,stopHookActive:f.stopHookActive,transition:f.transition,consecutiveFailedRounds:0,repeatedToolFailureRecoveryCount:c.repeatedToolFailureRecoveryCount+1};continue}}if(c.repeatedToolFailureRecoveryCount<1){let f=qr(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 i=`repeated tool failures (${be} rounds in a row)`,d=ve({inputMessages:l,messages:m,reason:`${i} before all required files were produced`})??(c.finalText.trim()?c.finalText:Dn(m,be)),g=_s(d,{availableToolNames:b(a??u),enabledToolNames:Lt(),toolCallNames:[...L].sort(),blockedToolCalls:_t(F)});o.info(`early exit: ${be} consecutive failed rounds, returning ${c.finalText?"partial":"fallback"} response`),yield*W(g);return}}else be=0;let ut=[...c.fileReadCycleBlockedPaths].filter(i=>!c.fileReadCycleNudgedPaths.has(i));if(ut.length>0){let i=ut.join(", "),d=[...new Set(ut.map(Qn))].join(" ");o.info(`AP5: file read cycle detected on ${i}, injecting nudge`);let g={role:"user",content:`Read-cycle guard blocked repeated reads for: ${i}. ${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 i=ve({inputMessages:l,messages:m,reason:`tool loop max turns reached (${x}) before completing all required files`});if(i){yield*W(i);return}let d=Qe(m,`tool loop max turns reached (${x}) before completing the final status contract`);yield*W(d);return}if(Et&&he(c).size>0&&Pe>U&&U<100&&(U=Math.min(100,Pe+25),o.info(`background task lifecycle wait extended round budget to ${U}`)),Et&&Pe>U){let i=Un({currentToolBudget:oe,currentRoundBudget:U,toolHardCap:100,roundHardCap:100,continuationCount:$e,successfulSinceLastCheck:De-Ze,fileReadCounts:c.fileReadCounts,windowTools:me,windowRounds:25});i&&(U=i.nextRoundBudget,oe=i.nextToolBudget,$e=i.continuationCount,Ze=De,o.info(`round budget continuation #${i.continuationCount}: rounds\u2192${U}, tools\u2192${oe} (progress detected)`))}if(Pe>U){o.info(`tool loop budget exhausted (${U} rounds), returning`);let i=Yn({totalToolCallCount:N,distinctToolNames:L,projectRoot:e.projectRoot});i&&(yield{type:"skill_instruction",turnId:r,instruction:i});let d=ve({inputMessages:l,messages:m,reason:`tool budget exhausted (${U} rounds) before completing all required files`});if(d){yield*W(d);return}let g=Qe(m,`tool budget exhausted (${U} rounds) before completing the final status contract`);yield*W(g);return}c={messages:m,maxOutputTokensRecoveryCount:0,hasAttemptedReactiveCompact:!1,maxOutputTokensOverride:void 0,turnCount:Pe,transition:{reason:"next_turn"},guardState:D,reactiveCompactState:J,toolLoopState:Q,consecutiveFailedRounds:be,finalText:c.finalText,totalUsage:c.totalUsage,collapseStore:Ut,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,backgroundAgentTaskIds:he(c),backgroundAgentNoOutputPollCounts:c.backgroundAgentNoOutputPollCounts,stalledBackgroundAgentTasks:c.stalledBackgroundAgentTasks,notOfferedToolRecoveryCount:c.notOfferedToolRecoveryCount,existingFileUpdateRecoveryCount:c.existingFileUpdateRecoveryCount,taskListReconciliationCount:c.taskListReconciliationCount,lastTaskList:c.lastTaskList}}}var Hc=["\u63A5\u5355\u91D1\u989D","\u5408\u540C\u91D1\u989D","\u62A5\u4EF7","\u9884\u7B97","\u91D1\u989D","price","amount","contract amount"];function $s(e){let t=Gc(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: ${Ds(o.l1Amount)}; L2 long-term says: ${Ds(o.l2Amount)}; action: ask the user which value is current before using it.`)}for(let o of e){let r=Xc(o);n.push(`- [${r}] ${o.text}`)}return n.join(`
|
|
42
|
+
`)}function Gc(e){let t=e.filter(r=>r.source==="l1-project-md").flatMap(r=>Bs(r.text)),n=e.filter(r=>r.source==="l2-long-term").flatMap(r=>Bs(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 Vc(o)}function Bs(e){let t=[];for(let n of e.split(/\r?\n/)){let o=n.trim();if(o)for(let r of Hc){if(r==="\u91D1\u989D"&&/(接单金额|合同金额)/u.test(o))continue;let s=new RegExp(`${Yc(r)}[^0-9.\u4E07kK,]{0,12}([0-9][0-9.,]*\\s*(?:\u4E07|k|K)?)`,"gi");for(let l of o.matchAll(s)){let a=Kc(l[1]);a!==null&&t.push({entity:Wc(o,r),predicate:r,amount:a,text:o})}}}return t}function Wc(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 Kc(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 Xc(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 Ds(e){return Number.isInteger(e)?String(e):String(Number(e.toFixed(4)))}function Vc(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 Yc(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var Zc=8192;async function Us(e){let{hooks:t,detectRecallCategories:n,log:o,sessionId:r,turnId:s,query:l}=e;try{let a=n(l),p=(await t.invoke("memory.before_recall",{sessionId:r,turnId:s,query:l,preferredCategories:a.preferred.length>0?a.preferred:void 0,deprioritizedCategories:a.deprioritized.length>0?a.deprioritized:void 0}))?.context?.recalledMemories,h=null;if(p&&p.length>0){let T=0,k=[];for(let I of p){let P=(I.text?.length??0)*2;if(T+P>Zc)break;k.push(I),T+=P}k.length>0&&(h=`[Recalled memories \u2014 context priority: project-specific facts override general user preferences when they conflict]
|
|
43
|
+
${$s(k)}`)}return B(t,"memory.after_recall",{sessionId:r,turnId:s,blockCount:p?.length??0},o),h}catch{return null}}var js=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:l,systemPrompt:a,config:u}=t,p={sessionId:t.sessionId,turnId:o};yield{type:"start",turnId:o},B(this.hooks,"turn.submitted",{...p,prompt:r[r.length-1]?.content??void 0},this.log);let h=Tn(r),T=[];if(a&&T.push({role:"system",content:a}),T.push(...h),this.hooks){let x=h.filter(A=>A.role==="user").pop(),E=typeof x?.content=="string"?x.content.slice(0,500):void 0;if(E){let A=await Us({hooks:this.hooks,detectRecallCategories:O=>this.runtimePorts.detectRecallCategories(O),log:this.log,sessionId:t.sessionId,turnId:o,query:E});A&&T.splice(a?1:0,0,{role:"system",content:A})}}let k=u?.model??"",I=typeof u?.maxRounds=="number"&&Number.isFinite(u.maxRounds)?u.maxRounds:this.configuredMaxRounds,P=I===void 0?void 0:Math.min(I,100);try{let x=u?.reasoning;u?.reasoning?.effort==="auto"&&(x={...u?.reasoning,effort:"medium"});let E={turnId:o,sessionId:t.sessionId,messages:T,availableTools:s,tools:l,refreshTools:t.refreshTools,model:k,apiKey:u?.apiKey??this.apiKey,temperature:u?.temperature,maxRounds:P,contextWindowTokens:u?.contextWindowTokens,maxOutputTokens:u?.maxOutputTokens,modelMaxOutputTokens:u?.modelMaxOutputTokens,toolChoice:u?.toolChoice,parentDepth:u?.parentDepth,hooks:this.hooks,fallbackModel:u?.fallbackModel,maxTurns:u?.maxTurns,tokenBudget:u?.tokenBudget,maxConcurrentTools:u?.maxConcurrentTools,streamRequired:u?.streamRequired,reasoning:x,promptCacheKey:u?.promptCacheKey,promptCacheRetention:u?.promptCacheRetention,serviceTier:u?.serviceTier,openaiBuiltinTools:u?.openaiBuiltinTools,maxToolCalls:u?.maxToolCalls,parallelToolCalls:u?.parallelToolCalls,textVerbosity:u?.textVerbosity,projectRoot:this.projectRoot,runtimePorts:this.runtimePorts.toolLoop,signal:n},A;for await(let O of Fs(E,this.transport,this.toolInvoker,this.log))A=O,yield O;A?.type==="end"?B(this.hooks,"turn.completed",{...p},this.log):A?.type==="error"&&B(this.hooks,"turn.failed",{...p,code:A.code,error:A.error},this.log)}catch(x){if(n?.aborted)B(this.hooks,"turn.failed",{...p,code:"ABORTED",error:"Turn aborted"},this.log),yield{type:"error",turnId:o,error:"Turn aborted",code:"ABORTED"};else{let E=x instanceof Error?x.message:String(x),A=typeof x?.status=="number"?x.status:void 0,O=Le(A,E);this.log.error(`turn ${o} error [${O}, retryable=${on(O)}]: ${E}`),B(this.hooks,"turn.failed",{...p,code:O,error:E},this.log),yield{type:"error",turnId:o,error:E,code:O}}}}};export{js as Agent};
|