qlogicagent 2.17.9 → 2.18.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 +21 -21
- package/dist/cli.js +1 -1566
- package/dist/index.js +445 -421
- package/dist/orchestration.js +7 -7
- package/dist/protocol.js +1 -1
- package/dist/skills/builtin/desktop-screenshot/SKILL.md +62 -0
- package/dist/skills/builtin/office-doc-reading/SKILL.md +19 -0
- package/dist/skills/mcp/astraclaw-native-mcp-server.js +7 -6
- package/dist/types/agent/tool-loop/artifact-final-contract.d.ts +18 -0
- package/dist/types/agent/tool-loop/loop-helpers.d.ts +9 -0
- package/dist/types/agent/tool-loop.d.ts +14 -5
- package/dist/types/agent/types.d.ts +5 -0
- package/dist/types/cli/acp-session-handlers.d.ts +8 -1
- package/dist/types/cli/acp-session-host.d.ts +5 -1
- package/dist/types/cli/default-project-bootstrap.d.ts +33 -0
- package/dist/types/cli/handlers/agents-handler.d.ts +9 -0
- package/dist/types/cli/handlers/config-handler.d.ts +5 -0
- package/dist/types/cli/handlers/files-handler.d.ts +7 -0
- package/dist/types/cli/handlers/session-handler.d.ts +49 -0
- package/dist/types/cli/handlers/turn-handler.d.ts +77 -0
- package/dist/types/cli/media-understanding.d.ts +45 -0
- package/dist/types/cli/permission-rule-persistence.d.ts +16 -0
- package/dist/types/cli/session-context.d.ts +5 -1
- package/dist/types/cli/stdio-acp-request-host.d.ts +1 -1
- package/dist/types/cli/stdio-rpc-handler-hosts.d.ts +4 -0
- package/dist/types/cli/stdio-server.d.ts +17 -1
- package/dist/types/cli/tool-bootstrap-core-registration.d.ts +2 -0
- package/dist/types/cli/turn-core.d.ts +2 -0
- package/dist/types/orchestration/agent-instance.d.ts +4 -0
- package/dist/types/orchestration/delegation-coordinator.d.ts +10 -0
- package/dist/types/orchestration/product-persistence.d.ts +4 -0
- package/dist/types/orchestration/workflow/capability-catalog.d.ts +1 -1
- package/dist/types/orchestration/workflow/workflow-controller.d.ts +1 -1
- package/dist/types/orchestration/workflow/workflow-runtime.d.ts +1 -1
- package/dist/types/protocol/notifications.d.ts +1 -1
- package/dist/types/protocol/wire/acp-agent-management.d.ts +16 -0
- package/dist/types/protocol/wire/agent-events.d.ts +2 -2
- package/dist/types/protocol/wire/agent-methods.d.ts +3 -0
- package/dist/types/protocol/wire/index.d.ts +1 -1
- package/dist/types/protocol/wire/notification-payloads.d.ts +26 -0
- package/dist/types/runtime/execution/turn-progress-notifier.d.ts +16 -0
- package/dist/types/runtime/infra/acp-detector.d.ts +40 -6
- package/dist/types/runtime/infra/acp-protocol-adapter.d.ts +14 -0
- package/dist/types/runtime/infra/agent-process.d.ts +16 -0
- package/dist/types/runtime/infra/astraclaw-capabilities.d.ts +2 -2
- package/dist/types/runtime/infra/builtin-skills-seed.d.ts +31 -0
- package/dist/types/runtime/infra/llmrouter-catalog.d.ts +26 -6
- package/dist/types/runtime/infra/model-registry.d.ts +43 -2
- package/dist/types/runtime/infra/project-data-gc.d.ts +7 -1
- package/dist/types/runtime/infra/skill-resolver.d.ts +15 -0
- package/dist/types/runtime/infra/user-dirs.d.ts +21 -0
- package/dist/types/runtime/permission-model.d.ts +1 -1
- package/dist/types/runtime/ports/permission-contracts.d.ts +5 -2
- package/dist/types/runtime/prompt/environment-context.d.ts +24 -2
- package/dist/types/runtime/prompt/fresh-workspace-evidence.d.ts +1 -2
- package/dist/types/runtime/prompt/identity-section.d.ts +17 -0
- package/dist/types/runtime/session/inbound-upload-persistence.d.ts +20 -0
- package/dist/types/runtime/session/native/claude-session-source.d.ts +23 -0
- package/dist/types/runtime/session/native/codex-index.d.ts +21 -0
- package/dist/types/runtime/session/native/codex-session-source.d.ts +31 -0
- package/dist/types/runtime/session/native/cwd-normalize.d.ts +53 -0
- package/dist/types/runtime/session/native/ephemeral-rollout-sweep.d.ts +13 -0
- package/dist/types/runtime/session/native/native-cwd-agents.d.ts +17 -0
- package/dist/types/runtime/session/native/native-session-source.d.ts +89 -0
- package/dist/types/runtime/session/native/native-title.d.ts +1 -0
- package/dist/types/runtime/session/native/register-builtin-sources.d.ts +1 -0
- package/dist/types/runtime/session/session-recovery.d.ts +58 -0
- package/dist/types/runtime/session/session-types.d.ts +30 -0
- package/dist/types/skills/permissions/hook-runner.d.ts +9 -0
- package/dist/types/skills/permissions/settings-watcher.d.ts +7 -0
- package/dist/types/skills/tools/exec-tool.d.ts +1 -1
- package/dist/types/skills/tools/shell/command-classification.d.ts +1 -0
- package/dist/types/skills/tools/shell/index.d.ts +3 -3
- package/dist/types/skills/tools/shell/powershell-provider.d.ts +8 -3
- package/dist/types/skills/tools/shell/shell-exec.d.ts +18 -0
- package/dist/types/skills/tools/shell/shell-provider.d.ts +67 -5
- package/dist/types/transport/acp-server.d.ts +6 -0
- package/package.json +4 -1
package/dist/agent.js
CHANGED
|
@@ -1,47 +1,47 @@
|
|
|
1
|
-
function fn(e,t,n,o){return{role:"assistant",content:t||null,tool_calls:e,...n&&n.length>0?{thinkingBlocks:n}:{},...o?{reasoning_content:o}:{}}}function X(e,t){let n=t.ok?typeof t.payload=="string"?t.payload:JSON.stringify(t.payload??""):`Error: ${t.error??"Tool execution failed"}`;return{role:"tool",tool_call_id:e,content:n,...!t.ok&&{is_error:!0},...t.toolReferences?.length?{toolReferences:t.toolReferences}:{},...t.imageUrls?.length?{imageUrls:t.imageUrls}:{}}}var Ii=/\b(?:daily|weekly|monthly)(?:\/(?:daily|weekly|monthly))* (?:usage )?limit(?:s)?(?: (?:exhausted|reached|exceeded))?\b/i,ve={rateLimit:[/rate[_ ]limit|too many requests|429/,"model_cooldown","exceeded your current quota","resource has been exhausted","quota exceeded","resource_exhausted","usage limit",/\btpm\b/i,"tokens per minute","tokens per day"],overloaded:[/overloaded_error|"type"\s*:\s*"overloaded_error"/i,"overloaded",/service[_ ]unavailable.*(?:overload|capacity|high[_ ]demand)|(?:overload|capacity|high[_ ]demand).*service[_ ]unavailable/i,"high demand"],timeout:["timeout","timed out","service unavailable","deadline exceeded","context deadline exceeded","connection error","network error","network request failed","fetch failed","socket hang up",/\beconn(?:refused|reset|aborted)\b/i,/\benotfound\b/i,/\beai_again\b/i,/without sending (?:any )?chunks?/i,/\bstop reason:\s*(?:abort|error|network_error)\b/i,/\breason:\s*(?:abort|error|network_error)\b/i,/\bunhandled stop reason:\s*(?:abort|error|network_error)\b/i],billing:[/["']?(?:status|code)["']?\s*[:=]\s*402\b|\bhttp\s*402\b|\berror(?:\s+code)?\s*[:=]?\s*402\b|\b(?:got|returned|received)\s+(?:a\s+)?402\b|^\s*402\s+payment/i,"payment required","insufficient credits",/insufficient[_ ]quota/i,"credit balance","plans & billing","insufficient balance"],authPermanent:[/api[_ ]?key[_ ]?(?:revoked|invalid|deactivated|deleted)/i,"invalid_api_key","key has been disabled","key has been revoked","account has been deactivated",/could not (?:authenticate|validate).*(?:api[_ ]?key|credentials)/i,"permission_error","not allowed for this organization"],auth:[/invalid[_ ]?api[_ ]?key/,"incorrect api key","invalid token","authentication","re-authenticate","oauth token refresh failed","unauthorized","forbidden","access denied","insufficient permissions","insufficient permission",/missing scopes?:/i,"expired","token has expired",/\b401\b/,/\b403\b/,"no credentials found","no api key found"],format:["string should match pattern","tool_use.id","tool_use_id","messages.1.content.1.tool_use.id","invalid request format",/tool call id was.*must be/i]},Pi=/^(?:error[:\s-]+)?billing(?:\s+error)?(?:[:\s-]+|$)|^(?:error[:\s-]+)?(?:credit balance|insufficient credits?|payment required|http\s*402\b)/i,Oi=/["']?(?:status|code)["']?\s*[:=]\s*402\b|\bhttp\s*402\b|\berror(?:\s+code)?\s*[:=]?\s*402\b|^\s*402\s+payment/i,Ni=512,Li=/^(?:http\s*)?(\d{3})(?:\s+([\s\S]+))?$/i;var Fi=new Set([500,502,503,504,521,522,523,524,529]),Bi=["insufficient credits","insufficient quota","credit balance","insufficient balance","plans & billing","add more credits","top up"],Di=["upgrade your plan","upgrade plan","current plan","subscription"],$i=["daily","weekly","monthly"],Ui=["try again","retry","temporary","cooldown"],ji=["usage limit","rate limit","organization usage"],qi=["organization","workspace"],zi=["billing period","exceeded","reached","exhausted"],Hi=/["']?(?:status|code)["']?\s*[:=]\s*402\b|\bhttp\s*402\b|\berror(?:\s+code)?\s*[:=]?\s*402\b|\b(?:got|returned|received)\s+(?:a\s+)?402\b|^\s*402\s+payment required\b/i,Gi=/^(?:error[:\s-]+)?(?:(?:http\s*)?402(?:\s+payment required)?|payment required)(?:[:\s-]+|$)/i;function Ae(e,t){if(!e)return!1;let n=e.toLowerCase();return t.some(o=>o instanceof RegExp?o.test(n):n.includes(o))}function Wi(e){return Ae(e,ve.format)}function Jo(e){return Ae(e,ve.rateLimit)}function Vi(e){return Ae(e,ve.timeout)}function Xi(e){return Ii.test(e)}function pn(e){let t=e.toLowerCase();return t?e.length>Ni?Oi.test(t):Ae(t,ve.billing)?!0:Pi.test(e)?t.includes("upgrade")||t.includes("credits")||t.includes("payment")||t.includes("plan"):!1:!1}function Qo(e){return Ae(e,ve.authPermanent)}function Ki(e){return Ae(e,ve.auth)}function er(e){return Ae(e,ve.overloaded)}function _e(e,t){return t.some(n=>e.includes(n))}function Yi(e){return _e(e,Bi)||_e(e,Di)&&e.includes("limit")||e.includes("billing hard limit")||e.includes("hard limit reached")||e.includes("maximum allowed")&&e.includes("limit")}function Zi(e){let t=_e(e,$i),n=e.includes("spend limit")||e.includes("spending limit"),o=_e(e,qi);return _e(e,Ui)&&_e(e,ji)||t&&(e.includes("usage limit")||n)||t&&e.includes("limit")&&e.includes("reset")||o&&e.includes("limit")&&(n||_e(e,zi))}function Ji(e){return e.trim().toLowerCase().replace(Gi,"").trim()}function tr(e){let t=Ji(e);return!t||Yi(t)?"billing":Jo(t)||Zi(t)?"rate_limit":"billing"}function Qi(e){return Hi.test(e)?tr(e):null}function nr(e){let t=e.match(Li);if(!t)return null;let n=Number(t[1]);return Number.isFinite(n)?{code:n,rest:(t[2]??"").trim()}:null}function ea(e){if(!e)return!1;let t=e.toLowerCase();return t.includes('"type":"api_error"')&&t.includes("internal server error")}function ta(e){let t=e.trim();if(!t)return!1;let n=nr(t);return n?Fi.has(n.code):!1}function or(e,t){return typeof e!="number"||!Number.isFinite(e)?null:e===402?t?tr(t):"billing":e===429?"rate_limit":e===401||e===403?t&&Qo(t)?"auth_permanent":"auth":e===408?"timeout":e===503?t&&er(t)?"overloaded":"timeout":e===502||e===504?"timeout":e===529?"overloaded":e===400?t&&pn(t)?"billing":"format":null}function na(e){if(!e)return!1;let t=e.toLowerCase();return!!(t.includes("unknown model")||t.includes("model not found")||t.includes("model_not_found")||t.includes("not_found_error")||t.includes("does not exist")&&t.includes("model")||t.includes("invalid model")&&!t.includes("invalid model reference")||/models\/[^\s]+ is not found/i.test(e)||/\b404\b/.test(e)&&/not[-_ ]?found/i.test(e))}function oa(e){if(!e)return!1;let t=e.toLowerCase();return t.includes("session not found")||t.includes("session does not exist")||t.includes("session expired")||t.includes("session invalid")||t.includes("conversation not found")||t.includes("conversation does not exist")||t.includes("conversation expired")||t.includes("conversation invalid")||t.includes("no such session")||t.includes("invalid session")||t.includes("session id not found")||t.includes("conversation id not found")}function rr(e){if(oa(e))return"session_expired";if(na(e))return"model_not_found";let t=Qi(e);return t||(Xi(e)?pn(e)?"billing":"rate_limit":Jo(e)?"rate_limit":er(e)?"overloaded":ta(e)?nr(e.trim())?.code===529?"overloaded":"timeout":ea(e)?"timeout":Wi(e)?"format":pn(e)?"billing":Vi(e)?"timeout":Qo(e)?"auth_permanent":Ki(e)?"auth":null)}var ra={timeout:"RETRYABLE_TRANSIENT",overloaded:"RETRYABLE_TRANSIENT",rate_limit:"RETRYABLE_DEGRADED",auth:"NON_RETRYABLE_AUTH",auth_permanent:"NON_RETRYABLE_AUTH",billing:"NON_RETRYABLE_QUOTA",format:"NON_RETRYABLE_CONTENT",model_not_found:"NON_RETRYABLE_CONTENT",session_expired:"NON_RETRYABLE_CONTENT",unknown:"RETRYABLE_TRANSIENT"},sa=new Set(["RETRYABLE_TRANSIENT","RETRYABLE_DEGRADED","TOOL_EXECUTION_FAILED"]);function De(e,t){let n=or(e,t)??(t?rr(t):null);return n?ra[n]:typeof e=="number"&&e>=400&&e<500?"NON_RETRYABLE_CONTENT":"RETRYABLE_TRANSIENT"}function mn(e){return sa.has(e)}function sr(e){let t=typeof e.content=="string"?e.content:e.content!=null?JSON.stringify(e.content):"";return Math.ceil(t.length/4)}var ia=new Set(["file_read","read","Read","bash","shell","Bash","grep","search","Grep","grep_search","glob","Glob","file_search","web_search","WebSearch","web_fetch","WebFetch","file_edit","edit","Edit","file_write","write","Write"]),Je=class{constructor(t=20,n=sr){this.preserveRecentCount=t;this.estimateTokens=n}preserveRecentCount;estimateTokens;compress(t,n){if(t.length<=this.preserveRecentCount)return{messages:t,droppedCount:0,strategy:"micro-compact"};let o=t.length-this.preserveRecentCount,r=0,s=0;return{messages:t.map((a,c)=>{if(c>=o||a.role!=="tool"||typeof a.content!="string"||!a.name||!ia.has(a.name)||a.content.length<=200)return a;let f=this.estimateTokens(a);return s+=f,r++,{...a,content:`[result cleared \u2014 ${a.content.length} chars]`}}),droppedCount:r,strategy:"micro-compact",metrics:r>0?{tokensBefore:0,tokensAfter:0,compressionRatio:0,latencyMs:0,usedLlm:!1,cacheInvalidated:!1}:void 0}}};function gn(e,t,n=sr){if(t.size===0)return{messages:e,tokensFreed:0,removedCount:0};let o=0,r=0,s=[];for(let a of e){let c=a.tool_call_id??"";if(c&&t.has(c)){o+=n(a),r++,t.delete(c);continue}s.push(a)}let i=r>0?{role:"system",content:`[${r} messages removed by snip]`}:void 0;return{messages:s,tokensFreed:o,removedCount:r,boundaryMessage:i}}function hn(){return{stages:[]}}function yn(e,t,n){let o=n?.thresholdMessages??40;if(e.filter(a=>a.role!=="system").length<=o)return{messages:e,stagedCount:0};let s=ir(e,t),i=aa(s,t,o);if(i.length===0)return{messages:s,stagedCount:0};for(let a of i)t.stages.push(a);return s=ir(e,t),{messages:s,stagedCount:i.length}}function bn(e,t){let n=0;for(let o of t.stages)o.committed||(o.committed=!0,n++);return n===0?{messages:e,committed:0}:{messages:ar(e,t),committed:n}}function ir(e,t){return t.stages.filter(o=>o.committed).length===0?e:ar(e,t)}function ar(e,t){let n=t.stages.filter(r=>r.committed).sort((r,s)=>s.range[0]-r.range[0]),o=[...e];for(let r of n){let[s,i]=r.range;if(s>=o.length)continue;let a=Math.min(i,o.length),c={role:"system",content:r.summary};o.splice(s,a-s,c)}return o}function aa(e,t,n){let o=Math.max(0,e.length-Math.floor(n/2)),r=[],s=new Set(t.stages.map(c=>`${c.range[0]}-${c.range[1]}`)),i=-1,a=0;for(let c=0;c<o;c++){let f=e[c];if(f.role==="tool"||f.role==="assistant"&&typeof f.content=="string"&&f.content==="")i<0&&(i=c),a++;else{if(a>=3){let y=`${i}-${i+a}`;s.has(y)||r.push({id:`collapse_${i}_${i+a}`,range:[i,i+a],summary:`[${a} tool results collapsed]`,committed:!1})}i=-1,a=0}}if(a>=3){let c=`${i}-${i+a}`;s.has(c)||r.push({id:`collapse_${i}_${i+a}`,range:[i,i+a],summary:`[${a} tool results collapsed]`,committed:!1})}return r}import{readFileSync as la,writeFileSync as ca,mkdirSync as ua}from"node:fs";import{join as da,dirname as fa}from"node:path";var be=Math.min(Math.max(1,Number(process.env.TOOL_LOOP_DEFAULT_BUDGET)||25),100),lr=Math.max(1e3,Number(process.env.TOOL_LOOP_TOOL_TIMEOUT_MS)||24e4),cr=3,ur=2,Ct=2,dr=128e3,fr=13e3,pr=16384,mr=65536,gr=3,hr=65536,Tn=500,yr=3;var br=3e4,Tr=3,we=2;var Cr=3,kr=2,Rr=300*1e3,xr=3,_r=720*60*60*1e3;var ed=3600*1e3;var td=50*1024,nd=500*1024,od=500*1024*1024,rd=50*1024*1024;var sd=60*1024;var Ar=0;var pa="skill-patterns.json";function wr(e){return da(e,".qlogicagent",pa)}function ma(e){let t=wr(e);try{return JSON.parse(la(t,"utf8"))}catch{return{version:1,patterns:{}}}}function vr(e,t){let n=wr(e);ua(fa(n),{recursive:!0}),ca(n,JSON.stringify(t,null,2),"utf8")}function ga(e){let t=Date.now()-_r;for(let[n,o]of Object.entries(e.patterns))new Date(o.lastSeen).getTime()<t&&delete e.patterns[n]}function Sr(e,t){if(t.length===0)return!1;let n=Mr(t),o=ma(e);ga(o);let r=new Date().toISOString(),s=o.patterns[n];if(s||(s={signature:n,count:0,firstSeen:r,lastSeen:r,promoted:!1},o.patterns[n]=s),s.promoted)return vr(e,o),!1;s.count++,s.lastSeen=r;let i=s.count>=xr;return i&&(s.promoted=!0),vr(e,o),i}function Mr(e){return[...e].sort().join("+")}function ha(e,t){return!(!e.ok||e.existingSkillName||!e.multiStep||e.toolCallCount<Cr||e.distinctToolCount<kr||Date.now()-Ar<Rr||t?.projectRoot&&t.tools.length>0&&!Sr(t.projectRoot,t.tools))}function ya(e){return e.existingSkillName?e.feedback==="negative":!1}function Cn(e,t){return ya(e)?{type:"skill.improve",skillName:e.existingSkillName,reason:"negative user feedback on existing skill execution"}:ha(e,t)?(Ar=Date.now(),{type:"skill.create",suggestedName:t.suggestedName??`auto-skill-${t.tools.slice(0,3).join("-")}`,description:`Multi-step orchestration using ${t.tools.join(", ")}`,tools:t.tools,stepCount:e.toolCallCount}):null}function ba(e){return[...new Set(e.map(kt).filter(Boolean))].sort((t,n)=>t.localeCompare(n))}function Er(e){let t=ba(e);return t.length===0?"":`Available tools for this round: ${t.join(", ")}. Do not mention, invent, or attempt any tool that is not in this list.`}function Ta(e){let t=[...new Set(e.map(kt).filter(Boolean))].sort((i,a)=>i.localeCompare(a)),n=new Set(t),o=Er(e),r=n.has("exec"),s=["read","search","write","edit","patch"].some(i=>n.has(i));return!r||!s?"You must call one of the available tools before responding. "+o:"You must call one of the available tools before responding. "+o+' Tool selection is part of correctness. Use read/search/write/edit/patch for file paths and file maintenance. For search, always include `mode` and `pattern`; examples: {"mode":"filename","pattern":"**/*.md"} or {"mode":"content","pattern":"TODO","fileGlob":"*.ts"}. Use exec only for shell commands with the required `command` field; never pass `path`, `filePath`, or file content to exec.'}function kt(e){return e.function&&typeof e.function=="object"&&typeof e.function.name=="string"?e.function.name.trim():typeof e.name=="string"?e.name.trim():""}function Ca(e){return e==="enabled-eligible"||e==="installed-awaiting-approval"}function ka(e){return new Map((e??[]).map(t=>[t.toolName,t]))}function Ra(e){if(!e.eligibility?.length)return[...e.tools];let t=ka(e.eligibility);return e.tools.filter(n=>{let o=kt(n);if(!o)return!1;let r=t.get(o);return!r||Ca(r.status)})}function xa(e){let t=[],n=e.compatibility??{},o=e.toolChoice;if(e.thinkingEnabled&&n.requireAutoWhenThinking){let r=typeof o=="object"&&o&&!Array.isArray(o)?String(o.type??""):o;r&&r!=="auto"&&r!=="none"&&(t.push("tool_choice downgraded to auto because thinking mode requires auto/none compatibility."),o="auto")}if(o==="required"&&n.allowRequiredToolChoice===!1){let r=n.requiredFallback??"auto";t.push(`tool_choice=required is not supported by this provider; downgraded to ${r}.`),o=r}if(o&&typeof o=="object"&&!Array.isArray(o)&&o.type==="function"&&n.allowNamedToolChoice===!1){let r=n.namedFallback??"required";t.push(`named tool_choice is not supported by this provider; downgraded to ${r}.`),o=r}return{normalizedToolChoice:o,warnings:t}}function kn(e){let t=xa({toolChoice:e.toolChoice,thinkingEnabled:e.thinkingEnabled,compatibility:e.compatibility}),n=t.normalizedToolChoice,o=[...t.warnings],r=Ra({tools:e.tools,eligibility:e.eligibility});if(!n||n==="auto")return{tools:r,normalizedToolChoice:n,...r.length>0?{extraSystemPrompt:Er(r)}:{},warnings:o};if(n==="none")return{tools:[],normalizedToolChoice:"none",warnings:o};if(n==="required"){if(r.length===0)throw new Error("tool_choice=required but no tools were provided");return{tools:r,normalizedToolChoice:"required",extraSystemPrompt:Ta(r),warnings:o}}if(typeof n=="object"&&!Array.isArray(n)&&n.type==="function"){let s=n.function??void 0,i=typeof s?.name=="string"?s.name.trim():"";if(!i)throw new Error("tool_choice.function.name is required");let a=r.filter(c=>kt(c)===i);if(a.length===0)throw new Error(`tool_choice requested unknown tool: ${i}`);return{tools:a,normalizedToolChoice:{type:"function",function:{name:i}},extraSystemPrompt:`You must call the ${i} tool before responding.`,warnings:o}}return{tools:r,normalizedToolChoice:n,warnings:o}}var _a=["stop","aborted","timeout","cancelled","interrupted","error"],va=["tool_calls","toolCalls","function_call","functionCall","raw_tool_calls","rawToolCalls"];function Ir(e){return e==null?[]:typeof e=="string"?e.length>0?[{type:"text",text:e}]:[]:Array.isArray(e)?e:[{type:"text",text:String(e)}]}function Aa(e,t){return{...e,content:[...Ir(e.content),...Ir(t.content)]}}function wa(e){let t=new Set;if(e.role!=="assistant"||!Array.isArray(e.tool_calls))return t;for(let n of e.tool_calls)typeof n.id=="string"&&n.id&&t.add(n.id);return t}function Sa(e){let t=new Set,n=[];for(let o=0;o<e.length;o+=1){if(t.has(o))continue;let r=e[o];if(!r)continue;n.push(r);let s=wa(r);if(s.size!==0)for(let i=o+1;i<e.length;i+=1){if(t.has(i))continue;let a=e[i];a?.role==="tool"&&typeof a.tool_call_id=="string"&&s.has(a.tool_call_id)&&(n.push(a),t.add(i))}}return n}function Ma(e){if(!e||typeof e!="object")return!1;if(e.function&&typeof e.function=="object"){let t=e.function.name;if(typeof t=="string"&&t.length>0)return!0}return typeof e.name=="string"&&e.name.length>0}function Ea(e){return new Set((e??_a).map(t=>t.trim().toLowerCase()))}function Ia(e,t){return e?Ea(t).has(e.trim().toLowerCase()):!1}function Rn(e){if(!Array.isArray(e)||e.length===0)return[...e];let t=e.map(c=>{if(c.role==="assistant"&&Array.isArray(c.tool_calls)){let f=c.tool_calls.filter(h=>Ma(h));return{...c,...f.length>0?{tool_calls:f}:{tool_calls:void 0}}}return{...c}}),n=new Set;for(let c of t)if(!(c.role!=="assistant"||!Array.isArray(c.tool_calls)))for(let f of c.tool_calls)typeof f.id=="string"&&f.id&&n.add(f.id);let o=t.filter(c=>c.role!=="tool"?!0:!!(c.tool_call_id&&n.has(c.tool_call_id))),r=new Set;for(let c of o)c.role==="tool"&&typeof c.tool_call_id=="string"&&c.tool_call_id&&r.add(c.tool_call_id);let s=[];for(let c of o){if(c.role==="assistant"&&Array.isArray(c.tool_calls)&&c.tool_calls.length>0){let f=c.tool_calls.filter(h=>typeof h.id=="string"&&r.has(h.id));if(f.length===0){let{tool_calls:h,...y}=c;y.content!=null&&y.content!==""&&s.push(y);continue}if(f.length<c.tool_calls.length){s.push({...c,tool_calls:f});continue}}s.push(c)}let i=Sa(s),a=[];for(let c of i){let f=a.length>0?a[a.length-1]:void 0;if(c.role==="user"&&f?.role==="user"){a[a.length-1]=Aa(f,c);continue}a.push(c)}return a}function xn(e,t){return Ia(t?.stopReason,t?.forcedStopReasons)?e.map(n=>{if(n.role!=="assistant")return{...n};let o={...n};for(let r of va)delete o[r];return o}):[...e]}function _n(e,t){let n=t?.placeholderToolResult??"Error: Tool loop interrupted before the tool result was replayed.",o=new Set;for(let s of e)s.role==="tool"&&typeof s.tool_call_id=="string"&&s.tool_call_id&&o.add(s.tool_call_id);let r=[];for(let s of e)if(r.push({...s}),!(s.role!=="assistant"||!Array.isArray(s.tool_calls)||s.tool_calls.length===0))for(let i of s.tool_calls)typeof i.id!="string"||!i.id||o.has(i.id)||(o.add(i.id),r.push({role:"tool",tool_call_id:i.id,content:n}));return r}function vn(e,t){let n=Rn(e),o=xn(n,t);return _n(o,t)}function Pa(e){let t=new Set,n=new Set;for(let o of e){if(o.role==="assistant"&&Array.isArray(o.tool_calls))for(let r of o.tool_calls)typeof r.id=="string"&&r.id&&t.add(r.id);o.role==="tool"&&typeof o.tool_call_id=="string"&&o.tool_call_id&&n.add(o.tool_call_id)}return[...t].filter(o=>!n.has(o))}function Oa(e){let t=new Set;for(let n of e)n.role==="tool"&&typeof n.tool_call_id=="string"&&n.tool_call_id&&t.add(n.tool_call_id);return[...t]}function Na(e){return{round:e.round??0,maxRounds:e.maxRounds,pendingToolCallIds:[...e.pendingToolCallIds??[]],completedToolCallIds:[...e.completedToolCallIds??[]],lastStopReason:e.lastStopReason,replayMessages:[...e.replayMessages??[]]}}function An(e,t){return{round:e.round+1,maxRounds:e.maxRounds,pendingToolCallIds:[...t.pendingToolCallIds??e.pendingToolCallIds],completedToolCallIds:[...t.completedToolCallIds??e.completedToolCallIds],lastStopReason:t.lastStopReason??e.lastStopReason,replayMessages:[...t.replayMessages??e.replayMessages]}}function Rt(e,t){return{round:e.round,maxRounds:e.maxRounds,pendingToolCallIds:[],completedToolCallIds:[...t.completedToolCallIds??e.completedToolCallIds],lastStopReason:t.lastStopReason??e.lastStopReason,replayMessages:[...t.replayMessages??e.replayMessages]}}function xt(e){let t=[],n=Rn(e.replayMessages);n.length!==e.replayMessages.length&&t.push({kind:"drop-orphan-tool-result",detail:"Removed orphan tool results or invalid assistant tool calls."});let o=xn(n,e.options);o.some((s,i)=>s!==n[i])&&t.push({kind:"strip-forced-stop-tool-metadata",detail:"Removed assistant tool-call metadata after forced stop."});let r=_n(o,e.options);return r.length>o.length&&t.push({kind:"inject-placeholder-tool-result",detail:"Injected placeholder tool result for pending tool calls."}),{state:Na({maxRounds:e.maxRounds,round:e.round,lastStopReason:e.lastStopReason,replayMessages:r,pendingToolCallIds:Pa(r),completedToolCallIds:Oa(r)}),recoveryActions:t}}var La=new Set(["main","sdk","agent","compact","hook","verification","side_question"]);function wn(e){return e?La.has(e):!0}function Sn(e){return e===429||e===529}function _t(e,t=500,n=32e3){let o=Math.min(t*Math.pow(2,e-1),n);return o+Math.floor(Math.random()*o*.25)}var bd={maxBackoffMs:300*1e3,resetCapMs:360*60*1e3,heartbeatIntervalMs:3e4};function vt(){let e=process.env.QLOGICAGENT_PERSISTENT_RETRY;return e==="1"||e==="true"}var Qe=class extends Error{constructor(n,o){super(`Model fallback triggered: ${n} -> ${o}`);this.originalModel=n;this.fallbackModel=o;this.name="FallbackTriggeredError"}originalModel;fallbackModel};function Mn(e){return{promptTokens:0,hasAttemptedReactiveCompact:!1,currentMaxOutputTokens:e.maxOutputTokens,consecutiveTruncations:0,aborted:e.abortSignal?.aborted??!1}}function En(e,t){if(e.aborted)return{level:"blocking",usagePercent:100,reason:"budget_exhausted"};let n=t.contextWindowTokens-t.responseBufferTokens-e.currentMaxOutputTokens,o=n>0?e.promptTokens/n*100:100;return e.promptTokens>=n?e.hasAttemptedReactiveCompact||!t.reactiveCompactEnabled?{level:"blocking",usagePercent:o,reason:"prompt_too_long"}:{level:"blocking",usagePercent:o,reason:"prompt_too_long"}:o>=85?{level:"warning",usagePercent:o,remainingTokens:n-e.promptTokens}:{level:"ok"}}function In(e,t,n){let o=e.message?.toLowerCase()??"",r=e.status??0;return r===413||o.includes("prompt_too_long")||o.includes("context_length_exceeded")?!t.hasAttemptedReactiveCompact&&n.reactiveCompactEnabled?{action:"reactive_compact"}:{action:"abort",reason:"prompt_too_long_unrecoverable"}:r>=500&&r<600?{action:"retry",reason:`server_error_${r}`}:r===429?{action:"retry",reason:"rate_limited"}:r===401||r===403?{action:"abort",reason:"auth_error"}:r===404?{action:"abort",reason:"model_not_found"}:{action:"abort",reason:o||"unknown_error"}}function Pn(e,t,n){if(!t.outputEscalationEnabled)return{shouldEscalate:!1,newMax:e.currentMaxOutputTokens};if(e.consecutiveTruncations>=3)return{shouldEscalate:!1,newMax:e.currentMaxOutputTokens};let o=Math.min(e.currentMaxOutputTokens*2,n);return o<=e.currentMaxOutputTokens?{shouldEscalate:!1,newMax:e.currentMaxOutputTokens}:{shouldEscalate:!0,newMax:o}}function On(e,t){return e.aborted?!0:t.abortSignal?.aborted?(e.aborted=!0,!0):!1}var Ba={maxConsecutiveFailures:3,minMessagesAfterCompact:4,targetUsagePercent:50};function Nn(){return{consecutiveFailures:0,attemptedThisTurn:!1,lastCompactAt:null,toolsAtLastCompact:[]}}function $e(e,t=Ba){return!(e.attemptedThisTurn||e.consecutiveFailures>=t.maxConsecutiveFailures)}import{createHash as hc}from"node:crypto";import{existsSync as Ne,readFileSync as jt}from"node:fs";function Ln(e,t){let n=e.get(t.index)??{id:"",name:"",arguments:""};t.id&&(n.id=t.id),t.name&&(n.name=t.name),n.arguments+=t.arguments??"",e.set(t.index,n)}function $(e,t,n,o){e?.invoke(t,n).catch(r=>{let s=r instanceof Error?r.message:String(r);o.warn(`[hook:${t}] handler failed: ${s}`)})}function Pr(e,t){let n=typeof t.message?.content=="string"?t.message.content:"",o=n?n.slice(0,2e3):void 0,r=t.details,s=typeof r?.stdout=="string"?r.stdout.slice(0,8e3):void 0,i=typeof r?.stderr=="string"?r.stderr.slice(0,4e3):void 0,a=typeof r?.exitCode=="number"?r.exitCode:void 0;return{type:"tool_result",turnId:e,callId:t.callId,name:t.toolName,ok:t.ok,error:t.error,outputPreview:o,durationMs:t.durationMs,exitCode:a,stdout:s,stderr:i,details:r}}function Or(e,t){if(!t.ok)return[];let n=t.details;if(!n)return[];let o=Da(n);return o?(Array.isArray(n.mediaUrls)?n.mediaUrls.filter(s=>typeof s=="string"&&s.trim().length>0):[]).map(s=>({type:"media_result",turnId:e,mediaType:o,url:s,model:typeof n.model=="string"?n.model:void 0,provider:typeof n.provider=="string"?n.provider:void 0,durationSeconds:typeof n.durationMs=="number"?n.durationMs/1e3:void 0,taskId:typeof n.taskId=="string"?n.taskId:void 0})):[]}function Da(e){let t=typeof e.type=="string"?e.type:"";if(!t)return null;if(t==="three_d_generate")return"3d";let n=t.split("_")[0];return n==="image"||n==="tts"||n==="video"||n==="music"?n:null}var $a=new Set(["write","edit","patch"]);function Nr(e){let{turnId:t,result:n,toolCalls:o}=e;if(!n.ok)return[];let r=o.find(a=>a.id===n.callId);if(!r)return[];let s=[],i=Ua(r.function.arguments);if(!i)return s;if($a.has(n.toolName)){let a=ja(i);a&&s.push({type:"artifact",turnId:t,artifactId:`artifact-${n.callId}`,artifactType:qa(a),title:a.split(/[\\/]/).pop()||a,filePath:a,language:za(a)})}return s}function Ua(e){try{return JSON.parse(e)}catch{return null}}function ja(e){return typeof e.file_path=="string"?e.file_path:typeof e.filePath=="string"?e.filePath:typeof e.path=="string"?e.path:void 0}function qa(e){let t=e.split(".").pop()?.toLowerCase()??"";return["png","jpg","jpeg","gif","webp","svg","bmp","ico"].includes(t)?"image":["md","txt","pdf","doc","docx","rtf","html"].includes(t)?"document":["mermaid","mmd","dot","puml","plantuml"].includes(t)?"diagram":["csv","tsv","xlsx","xls"].includes(t)?"table":["ts","tsx","js","jsx","py","rs","go","java","c","cpp","h","cs","rb","sh","sql","json","yaml","yml","toml","xml","css","scss","vue","svelte"].includes(t)?"code":"file"}function za(e){let t=e.split(".").pop()?.toLowerCase()??"";return{ts:"typescript",tsx:"typescriptreact",js:"javascript",jsx:"javascriptreact",py:"python",rs:"rust",go:"go",java:"java",c:"c",cpp:"cpp",h:"c",cs:"csharp",rb:"ruby",sh:"shellscript",sql:"sql",json:"json",yaml:"yaml",yml:"yaml",toml:"toml",xml:"xml",html:"html",css:"css",scss:"scss",vue:"vue",svelte:"svelte",md:"markdown"}[t]}var $r=new Set(["write","edit","patch"]),Ur=new Set(["image_generate"]),Ha=/\b(?:verify|test|check|validate)\b[\s\S]{0,48}\b(?:browser|browser-visible|playwright|visible ui)\b|\b(?:browser|browser-visible|playwright|visible ui)\b[\s\S]{0,48}\b(?:verify|test|check|validate)\b/i,Ga=/\b(?:build|create|make|develop|implement|scaffold|generate)\b[\s\S]{0,80}\b(?:app|application|web ?app|website|site|dashboard|frontend|react|vite|vue|next|svelte|game)\b|\b(?:vite|react|vue|next\.js|frontend|browser-visible)\b|(?:构建|创建|开发|实现|生成|搭建)[\s\S]{0,24}(?:应用|网站|网页|前端|页面|项目|游戏|看板|仪表盘|app)/i,Wa=/\b(?:under|inside|in|at|to|root|directory|folder|output directory|output folder)\s+([A-Za-z]:[\\/][^\s"'`<>|]+)|(?:目录|文件夹|根目录|输出到|放到|位于)\s*([A-Za-z]:[\\/][^\s"'`<>|]+)/gi,Bn=/https?:\/\/[^\s"'`<>),;]+/gi,Va=/\b(?:fatal|timeout|timed out|waitforselector|waiting for locator|strict mode violation|exception|traceback|eaddrinuse|page crashed|browser closed|target closed)\b|无法访问|错误|失败|超时/i,Xa=/\b(?:default vite|vite \+ react|edit src\/app|click on the vite|vite page)\b|默认\s*Vite/i,Lr=/\b(?:browser|playwright|puppeteer|screenshot|opened|loaded|navigated|visible|locator|page\.goto|http:\/\/127\.0\.0\.1|http:\/\/localhost)\b|(?:浏览器|截图|页面可见|打开页面|加载页面|内置浏览器|自动化)/i;function Ka(e){let t=qn(e);return{artifactRoot:t,rootSource:t?"explicit":void 0,writePaths:[],outOfRootWrites:[],devServerUrls:[],browserVerified:!1,browserEvidence:[],browserFailureEvidence:[],buildVerified:!1,buildEvidence:[],buildFailureEvidence:[]}}function de(e){return e.some(t=>t.role==="user"&&typeof t.content=="string"&&(Ga.test(t.content)||Ha.test(t.content)))}var Ya=new RegExp(["\\b(?:tests?|test suite|unit tests?|the suite|build|compiles?|compilation|typecheck|lint)\\b[\\s\\S]{0,24}\\b(?:pass(?:es|ing)?|green|succeed(?:s|ed)?|clean|work(?:s|ing)?)\\b","\\b(?:pass(?:es|ing)?|green|succeed(?:s|ed)?)\\b[\\s\\S]{0,16}\\b(?:tests?|the suite|build)\\b","\\bfix(?:es|ing)?\\b[\\s\\S]{0,24}\\b(?:failing|broken)\\b[\\s\\S]{0,12}\\b(?:tests?|build|spec)\\b","\\bmake it (?:build|compile|pass)\\b","\\b(?:run|rerun|re-run) (?:the )?(?:tests?|test suite|build|spec)\\b","\\b(?:npm (?:test|run build)|pnpm (?:test|build)|yarn (?:test|build)|pytest|go test|cargo (?:test|build)|vitest|jest|gradle|mvn)\\b","(?:\u8BA9|\u4F7F|\u786E\u4FDD)[\\s\\S]{0,12}(?:\u6D4B\u8BD5|\u5355\u6D4B|\u7528\u4F8B|\u6784\u5EFA|\u7F16\u8BD1)[\\s\\S]{0,8}(?:\u901A\u8FC7|\u8DD1\u901A|\u6210\u529F|\u7EFF)","(?:\u4FEE\u590D|\u4FEE\u597D|\u89E3\u51B3)[\\s\\S]{0,12}(?:\u5931\u8D25\u7684?\u6D4B\u8BD5|\u6D4B\u8BD5\u5931\u8D25|\u7F16\u8BD1\u9519\u8BEF|\u6784\u5EFA\u9519\u8BEF|\u7F16\u8BD1\u62A5\u9519|\u62A5\u9519)","\u6D4B\u8BD5\u901A\u8FC7|\u8DD1\u901A\u6D4B\u8BD5|\u7F16\u8BD1\u901A\u8FC7|\u6784\u5EFA\u901A\u8FC7|\u901A\u8FC7(?:\u5168\u90E8|\u6240\u6709)?\u6D4B\u8BD5|\u8BA9\u6D4B\u8BD5\u53D8\u7EFF"].join("|"),"i");function jr(e){return e.some(t=>t.role==="user"&&typeof t.content=="string"&&Ya.test(t.content))}var Fn=/```final-status[ \t]*\r?\n([\s\S]*?)\r?\n[ \t]*```/g,Za=new Set([...$r,...Ur,"exec","bash","shell","powershell","terminal","playwright","browser","computer"]);function qr(e){for(let t of e)if(Za.has(t))return!0;return!1}var zr=["## Final status block","When this turn produced artifacts (files written, apps served), asserted verification (browser/build/tests), left requested work incomplete or blocked, or the user explicitly asked for a final status or an evidence audit, end your final message with exactly one fenced block:","","```final-status",'{"schema":1,"done":["\u2026"],"notDone":["\u2026"],"artifacts":{"root":"\u2026","files":["\u2026"],"urls":["\u2026"]},"verification":{"browser":"verified|failed|not-run","build":"passed|failed|not-run"},"sources":{"cited":["https://\u2026"]},"blockers":["\u2026"],"nextAction":"\u2026"}',"```","","Every field must reflect actual tool activity from this turn; the engine cross-checks the block against its own tool records and strips unsupported claims. Omit fields that do not apply. Omit the whole block for ordinary conversation."].join(`
|
|
2
|
-
`);function
|
|
3
|
-
${e.content}`;for(let o of n.matchAll(
|
|
4
|
-
`),{claim:f,notices:
|
|
1
|
+
function mn(e,t,n,o){return{role:"assistant",content:t||null,tool_calls:e,...n&&n.length>0?{thinkingBlocks:n}:{},...o?{reasoning_content:o}:{}}}function X(e,t){let n=t.ok?typeof t.payload=="string"?t.payload:JSON.stringify(t.payload??""):`Error: ${t.error??"Tool execution failed"}`;return{role:"tool",tool_call_id:e,content:n,...!t.ok&&{is_error:!0},...t.toolReferences?.length?{toolReferences:t.toolReferences}:{},...t.imageUrls?.length?{imageUrls:t.imageUrls}:{}}}var Fi=/\b(?:daily|weekly|monthly)(?:\/(?:daily|weekly|monthly))* (?:usage )?limit(?:s)?(?: (?:exhausted|reached|exceeded))?\b/i,Ae={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]},Bi=/^(?:error[:\s-]+)?billing(?:\s+error)?(?:[:\s-]+|$)|^(?:error[:\s-]+)?(?:credit balance|insufficient credits?|payment required|http\s*402\b)/i,Di=/["']?(?:status|code)["']?\s*[:=]\s*402\b|\bhttp\s*402\b|\berror(?:\s+code)?\s*[:=]?\s*402\b|^\s*402\s+payment/i,$i=512,Ui=/^(?:http\s*)?(\d{3})(?:\s+([\s\S]+))?$/i;var ji=new Set([500,502,503,504,521,522,523,524,529]),zi=["insufficient credits","insufficient quota","credit balance","insufficient balance","plans & billing","add more credits","top up"],Hi=["upgrade your plan","upgrade plan","current plan","subscription"],qi=["daily","weekly","monthly"],Gi=["try again","retry","temporary","cooldown"],Wi=["usage limit","rate limit","organization usage"],Vi=["organization","workspace"],Xi=["billing period","exceeded","reached","exhausted"],Ki=/["']?(?: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,Yi=/^(?:error[:\s-]+)?(?:(?:http\s*)?402(?:\s+payment required)?|payment required)(?:[:\s-]+|$)/i;function we(e,t){if(!e)return!1;let n=e.toLowerCase();return t.some(o=>o instanceof RegExp?o.test(n):n.includes(o))}function Zi(e){return we(e,Ae.format)}function Jo(e){return we(e,Ae.rateLimit)}function Ji(e){return we(e,Ae.timeout)}function Qi(e){return Fi.test(e)}function gn(e){let t=e.toLowerCase();return t?e.length>$i?Di.test(t):we(t,Ae.billing)?!0:Bi.test(e)?t.includes("upgrade")||t.includes("credits")||t.includes("payment")||t.includes("plan"):!1:!1}function Qo(e){return we(e,Ae.authPermanent)}function ea(e){return we(e,Ae.auth)}function er(e){return we(e,Ae.overloaded)}function ve(e,t){return t.some(n=>e.includes(n))}function ta(e){return ve(e,zi)||ve(e,Hi)&&e.includes("limit")||e.includes("billing hard limit")||e.includes("hard limit reached")||e.includes("maximum allowed")&&e.includes("limit")}function na(e){let t=ve(e,qi),n=e.includes("spend limit")||e.includes("spending limit"),o=ve(e,Vi);return ve(e,Gi)&&ve(e,Wi)||t&&(e.includes("usage limit")||n)||t&&e.includes("limit")&&e.includes("reset")||o&&e.includes("limit")&&(n||ve(e,Xi))}function oa(e){return e.trim().toLowerCase().replace(Yi,"").trim()}function tr(e){let t=oa(e);return!t||ta(t)?"billing":Jo(t)||na(t)?"rate_limit":"billing"}function ra(e){return Ki.test(e)?tr(e):null}function nr(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 sa(e){if(!e)return!1;let t=e.toLowerCase();return t.includes('"type":"api_error"')&&t.includes("internal server error")}function ia(e){let t=e.trim();if(!t)return!1;let n=nr(t);return n?ji.has(n.code):!1}function or(e,t){return typeof e!="number"||!Number.isFinite(e)?null:e===402?t?tr(t):"billing":e===429?"rate_limit":e===401||e===403?t&&Qo(t)?"auth_permanent":"auth":e===408?"timeout":e===503?t&&er(t)?"overloaded":"timeout":e===502||e===504?"timeout":e===529?"overloaded":e===400?t&&gn(t)?"billing":"format":null}function aa(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 la(e){if(!e)return!1;let t=e.toLowerCase();return t.includes("session not found")||t.includes("session does not exist")||t.includes("session expired")||t.includes("session invalid")||t.includes("conversation not found")||t.includes("conversation does not exist")||t.includes("conversation expired")||t.includes("conversation invalid")||t.includes("no such session")||t.includes("invalid session")||t.includes("session id not found")||t.includes("conversation id not found")}function rr(e){if(la(e))return"session_expired";if(aa(e))return"model_not_found";let t=ra(e);return t||(Qi(e)?gn(e)?"billing":"rate_limit":Jo(e)?"rate_limit":er(e)?"overloaded":ia(e)?nr(e.trim())?.code===529?"overloaded":"timeout":sa(e)?"timeout":Zi(e)?"format":gn(e)?"billing":Ji(e)?"timeout":Qo(e)?"auth_permanent":ea(e)?"auth":null)}var ca={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"},ua=new Set(["RETRYABLE_TRANSIENT","RETRYABLE_DEGRADED","TOOL_EXECUTION_FAILED"]);function $e(e,t){let n=or(e,t)??(t?rr(t):null);return n?ca[n]:typeof e=="number"&&e>=400&&e<500?"NON_RETRYABLE_CONTENT":"RETRYABLE_TRANSIENT"}function hn(e){return ua.has(e)}function sr(e){let t=typeof e.content=="string"?e.content:e.content!=null?JSON.stringify(e.content):"";return Math.ceil(t.length/4)}var da=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"]),et=class{constructor(t=20,n=sr){this.preserveRecentCount=t;this.estimateTokens=n}preserveRecentCount;estimateTokens;compress(t,n){if(t.length<=this.preserveRecentCount)return{messages:t,droppedCount:0,strategy:"micro-compact"};let o=new Map;for(let c of t){let f=c.tool_calls;if(Array.isArray(f))for(let g of f)g?.id&&g.function?.name&&o.set(g.id,g.function.name)}let r=t.length-this.preserveRecentCount,s=0,i=0;return{messages:t.map((c,f)=>{if(f>=r||c.role!=="tool"||typeof c.content!="string")return c;let g=c.name??o.get(c.tool_call_id??"");if(!g||!da.has(g)||c.content.length<=200)return c;let y=this.estimateTokens(c);return i+=y,s++,{...c,content:`[result cleared \u2014 ${c.content.length} chars]`}}),droppedCount:s,strategy:"micro-compact",metrics:s>0?{tokensBefore:0,tokensAfter:0,compressionRatio:0,latencyMs:0,usedLlm:!1,cacheInvalidated:!1}:void 0}}};function yn(e,t,n=sr){if(t.size===0)return{messages:e,tokensFreed:0,removedCount:0};let o=0,r=0,s=[];for(let a of e){let c=a.tool_call_id??"";if(c&&t.has(c)){o+=n(a),r++,t.delete(c);continue}s.push(a)}let i=r>0?{role:"system",content:`[${r} messages removed by snip]`}:void 0;return{messages:s,tokensFreed:o,removedCount:r,boundaryMessage:i}}function bn(){return{stages:[]}}function Tn(e,t,n){let o=n?.thresholdMessages??40;if(e.filter(a=>a.role!=="system").length<=o)return{messages:e,stagedCount:0};let s=ir(e,t),i=fa(s,t,o);if(i.length===0)return{messages:s,stagedCount:0};for(let a of i)t.stages.push(a);return s=ir(e,t),{messages:s,stagedCount:i.length}}function Cn(e,t){let n=0;for(let o of t.stages)o.committed||(o.committed=!0,n++);return n===0?{messages:e,committed:0}:{messages:ar(e,t),committed:n}}function ir(e,t){return t.stages.filter(o=>o.committed).length===0?e:ar(e,t)}function ar(e,t){let n=t.stages.filter(r=>r.committed).sort((r,s)=>s.range[0]-r.range[0]),o=[...e];for(let r of n){let[s,i]=r.range;if(s>=o.length)continue;let a=Math.min(i,o.length),c={role:"system",content:r.summary};o.splice(s,a-s,c)}return o}function fa(e,t,n){let o=Math.max(0,e.length-Math.floor(n/2)),r=[],s=new Set(t.stages.map(c=>`${c.range[0]}-${c.range[1]}`)),i=-1,a=0;for(let c=0;c<o;c++){let f=e[c];if(f.role==="tool"||f.role==="assistant"&&typeof f.content=="string"&&f.content==="")i<0&&(i=c),a++;else{if(a>=3){let y=`${i}-${i+a}`;s.has(y)||r.push({id:`collapse_${i}_${i+a}`,range:[i,i+a],summary:`[${a} tool results collapsed]`,committed:!1})}i=-1,a=0}}if(a>=3){let c=`${i}-${i+a}`;s.has(c)||r.push({id:`collapse_${i}_${i+a}`,range:[i,i+a],summary:`[${a} tool results collapsed]`,committed:!1})}return r}import{readFileSync as pa,writeFileSync as ma,mkdirSync as ga}from"node:fs";import{join as ha,dirname as ya}from"node:path";var Ce=Math.min(Math.max(1,Number(process.env.TOOL_LOOP_DEFAULT_BUDGET)||25),100),lr=Math.max(1e3,Number(process.env.TOOL_LOOP_TOOL_TIMEOUT_MS)||24e4),cr=3,ur=2,Rt=2,dr=128e3,fr=13e3,pr=16384,mr=65536,gr=3,hr=65536,kn=500,yr=3;var br=3e4,Tr=3,Se=2;var Cr=3,kr=2,Rr=300*1e3,xr=3,_r=720*60*60*1e3;var rd=3600*1e3;var sd=50*1024,id=500*1024,ad=500*1024*1024,ld=50*1024*1024;var cd=60*1024;var Ar=0;var ba="skill-patterns.json";function wr(e){return ha(e,".qlogicagent",ba)}function Ta(e){let t=wr(e);try{return JSON.parse(pa(t,"utf8"))}catch{return{version:1,patterns:{}}}}function vr(e,t){let n=wr(e);ga(ya(n),{recursive:!0}),ma(n,JSON.stringify(t,null,2),"utf8")}function Ca(e){let t=Date.now()-_r;for(let[n,o]of Object.entries(e.patterns))new Date(o.lastSeen).getTime()<t&&delete e.patterns[n]}function Sr(e,t){if(t.length===0)return!1;let n=Er(t),o=Ta(e);Ca(o);let r=new Date().toISOString(),s=o.patterns[n];if(s||(s={signature:n,count:0,firstSeen:r,lastSeen:r,promoted:!1},o.patterns[n]=s),s.promoted)return vr(e,o),!1;s.count++,s.lastSeen=r;let i=s.count>=xr;return i&&(s.promoted=!0),vr(e,o),i}function Er(e){return[...e].sort().join("+")}function ka(e,t){return!(!e.ok||e.existingSkillName||!e.multiStep||e.toolCallCount<Cr||e.distinctToolCount<kr||Date.now()-Ar<Rr||t?.projectRoot&&t.tools.length>0&&!Sr(t.projectRoot,t.tools))}function Ra(e){return e.existingSkillName?e.feedback==="negative":!1}function Rn(e,t){return Ra(e)?{type:"skill.improve",skillName:e.existingSkillName,reason:"negative user feedback on existing skill execution"}:ka(e,t)?(Ar=Date.now(),{type:"skill.create",suggestedName:t.suggestedName??`auto-skill-${t.tools.slice(0,3).join("-")}`,description:`Multi-step orchestration using ${t.tools.join(", ")}`,tools:t.tools,stepCount:e.toolCallCount}):null}function xa(e){return[...new Set(e.map(xt).filter(Boolean))].sort((t,n)=>t.localeCompare(n))}function Mr(e){let t=xa(e);return t.length===0?"":`Available tools for this round: ${t.join(", ")}. Do not invent or attempt any tool outside this list. If the request needs a capability none of these tools cover, do not silently refuse: consider exec-based scripts/OS commands, use community_seek (when listed) to find an installable capability, and otherwise state plainly which capability is missing.`}function _a(e){let t=[...new Set(e.map(xt).filter(Boolean))].sort((i,a)=>i.localeCompare(a)),n=new Set(t),o=Mr(e),r=n.has("exec"),s=["read","search","write","edit","patch"].some(i=>n.has(i));return!r||!s?"You must call one of the available tools before responding. "+o:"You must call one of the available tools before responding. "+o+' Tool selection is part of correctness. Use read/search/write/edit/patch for file paths and file maintenance. For search, always include `mode` and `pattern`; examples: {"mode":"filename","pattern":"**/*.md"} or {"mode":"content","pattern":"TODO","fileGlob":"*.ts"}. Use exec only for shell commands with the required `command` field; never pass `path`, `filePath`, or file content to exec.'}function xt(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 va(e){return e==="enabled-eligible"||e==="installed-awaiting-approval"}function Aa(e){return new Map((e??[]).map(t=>[t.toolName,t]))}function wa(e){if(!e.eligibility?.length)return[...e.tools];let t=Aa(e.eligibility);return e.tools.filter(n=>{let o=xt(n);if(!o)return!1;let r=t.get(o);return!r||va(r.status)})}function Sa(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 xn(e){let t=Sa({toolChoice:e.toolChoice,thinkingEnabled:e.thinkingEnabled,compatibility:e.compatibility}),n=t.normalizedToolChoice,o=[...t.warnings],r=wa({tools:e.tools,eligibility:e.eligibility});if(!n||n==="auto")return{tools:r,normalizedToolChoice:n,...r.length>0?{extraSystemPrompt:Mr(r)}:{},warnings:o};if(n==="none")return{tools:[],normalizedToolChoice:"none",warnings:o};if(n==="required"){if(r.length===0)throw new Error("tool_choice=required but no tools were provided");return{tools:r,normalizedToolChoice:"required",extraSystemPrompt:_a(r),warnings:o}}if(typeof n=="object"&&!Array.isArray(n)&&n.type==="function"){let s=n.function??void 0,i=typeof s?.name=="string"?s.name.trim():"";if(!i)throw new Error("tool_choice.function.name is required");let a=r.filter(c=>xt(c)===i);if(a.length===0)throw new Error(`tool_choice requested unknown tool: ${i}`);return{tools:a,normalizedToolChoice:{type:"function",function:{name:i}},extraSystemPrompt:`You must call the ${i} tool before responding.`,warnings:o}}return{tools:r,normalizedToolChoice:n,warnings:o}}var Ea=["stop","aborted","timeout","cancelled","interrupted","error"],Ma=["tool_calls","toolCalls","function_call","functionCall","raw_tool_calls","rawToolCalls"];function Ir(e){return e==null?[]:typeof e=="string"?e.length>0?[{type:"text",text:e}]:[]:Array.isArray(e)?e:[{type:"text",text:String(e)}]}function Ia(e,t){return{...e,content:[...Ir(e.content),...Ir(t.content)]}}function Pa(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 Oa(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=Pa(r);if(s.size!==0)for(let i=o+1;i<e.length;i+=1){if(t.has(i))continue;let a=e[i];a?.role==="tool"&&typeof a.tool_call_id=="string"&&s.has(a.tool_call_id)&&(n.push(a),t.add(i))}}return n}function Na(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 La(e){return new Set((e??Ea).map(t=>t.trim().toLowerCase()))}function Fa(e,t){return e?La(t).has(e.trim().toLowerCase()):!1}function _n(e){if(!Array.isArray(e)||e.length===0)return[...e];let t=e.map(c=>{if(c.role==="assistant"&&Array.isArray(c.tool_calls)){let f=c.tool_calls.filter(g=>Na(g));return{...c,...f.length>0?{tool_calls:f}:{tool_calls:void 0}}}return{...c}}),n=new Set;for(let c of t)if(!(c.role!=="assistant"||!Array.isArray(c.tool_calls)))for(let f of c.tool_calls)typeof f.id=="string"&&f.id&&n.add(f.id);let o=t.filter(c=>c.role!=="tool"?!0:!!(c.tool_call_id&&n.has(c.tool_call_id))),r=new Set;for(let c of o)c.role==="tool"&&typeof c.tool_call_id=="string"&&c.tool_call_id&&r.add(c.tool_call_id);let s=[];for(let c of o){if(c.role==="assistant"&&Array.isArray(c.tool_calls)&&c.tool_calls.length>0){let f=c.tool_calls.filter(g=>typeof g.id=="string"&&r.has(g.id));if(f.length===0){let{tool_calls:g,...y}=c;y.content!=null&&y.content!==""&&s.push(y);continue}if(f.length<c.tool_calls.length){s.push({...c,tool_calls:f});continue}}s.push(c)}let i=Oa(s),a=[];for(let c of i){let f=a.length>0?a[a.length-1]:void 0;if(c.role==="user"&&f?.role==="user"){a[a.length-1]=Ia(f,c);continue}a.push(c)}return a}function vn(e,t){return Fa(t?.stopReason,t?.forcedStopReasons)?e.map(n=>{if(n.role!=="assistant")return{...n};let o={...n};for(let r of Ma)delete o[r];return o}):[...e]}function An(e,t){let n=t?.placeholderToolResult??"Error: Tool loop interrupted before the tool result was replayed.",o=new Set;for(let s of e)s.role==="tool"&&typeof s.tool_call_id=="string"&&s.tool_call_id&&o.add(s.tool_call_id);let r=[];for(let s of e)if(r.push({...s}),!(s.role!=="assistant"||!Array.isArray(s.tool_calls)||s.tool_calls.length===0))for(let i of s.tool_calls)typeof i.id!="string"||!i.id||o.has(i.id)||(o.add(i.id),r.push({role:"tool",tool_call_id:i.id,content:n}));return r}function wn(e,t){let n=_n(e),o=vn(n,t);return An(o,t)}function Ba(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 Da(e){let t=new Set;for(let n of e)n.role==="tool"&&typeof n.tool_call_id=="string"&&n.tool_call_id&&t.add(n.tool_call_id);return[...t]}function $a(e){return{round:e.round??0,maxRounds:e.maxRounds,pendingToolCallIds:[...e.pendingToolCallIds??[]],completedToolCallIds:[...e.completedToolCallIds??[]],lastStopReason:e.lastStopReason,replayMessages:[...e.replayMessages??[]]}}function Sn(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 _t(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 vt(e){let t=[],n=_n(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=vn(n,e.options);o.some((s,i)=>s!==n[i])&&t.push({kind:"strip-forced-stop-tool-metadata",detail:"Removed assistant tool-call metadata after forced stop."});let r=An(o,e.options);return r.length>o.length&&t.push({kind:"inject-placeholder-tool-result",detail:"Injected placeholder tool result for pending tool calls."}),{state:$a({maxRounds:e.maxRounds,round:e.round,lastStopReason:e.lastStopReason,replayMessages:r,pendingToolCallIds:Ba(r),completedToolCallIds:Da(r)}),recoveryActions:t}}var Ua=new Set(["main","sdk","agent","compact","hook","verification","side_question"]);function En(e){return e?Ua.has(e):!0}function Mn(e){return e===429||e===529}function At(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 Rd={maxBackoffMs:300*1e3,resetCapMs:360*60*1e3,heartbeatIntervalMs:3e4};function wt(){let e=process.env.QLOGICAGENT_PERSISTENT_RETRY;return e==="1"||e==="true"}var tt=class extends Error{constructor(n,o){super(`Model fallback triggered: ${n} -> ${o}`);this.originalModel=n;this.fallbackModel=o;this.name="FallbackTriggeredError"}originalModel;fallbackModel};function In(e){return{promptTokens:0,hasAttemptedReactiveCompact:!1,currentMaxOutputTokens:e.maxOutputTokens,consecutiveTruncations:0,aborted:e.abortSignal?.aborted??!1}}function Pn(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 On(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 Nn(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 Ln(e,t){return e.aborted?!0:t.abortSignal?.aborted?(e.aborted=!0,!0):!1}var za={maxConsecutiveFailures:3,minMessagesAfterCompact:4,targetUsagePercent:50};function Fn(){return{consecutiveFailures:0,attemptedThisTurn:!1,lastCompactAt:null,toolsAtLastCompact:[]}}function Ue(e,t=za){return!(e.attemptedThisTurn||e.consecutiveFailures>=t.maxConsecutiveFailures)}import{createHash as Sc}from"node:crypto";import{existsSync as Le,readFileSync as Ht}from"node:fs";function Bn(e,t){let n=e.get(t.index)??{id:"",name:"",arguments:""};t.id&&(n.id=t.id),t.name&&(n.name=t.name),n.arguments+=t.arguments??"",e.set(t.index,n)}function $(e,t,n,o){e?.invoke(t,n).catch(r=>{let s=r instanceof Error?r.message:String(r);o.warn(`[hook:${t}] handler failed: ${s}`)})}function Pr(e,t){let n=typeof t.message?.content=="string"?t.message.content:"",o=n?n.slice(0,2e3):void 0,r=t.details,s=typeof r?.stdout=="string"?r.stdout.slice(0,8e3):void 0,i=typeof r?.stderr=="string"?r.stderr.slice(0,4e3):void 0,a=typeof r?.exitCode=="number"?r.exitCode:void 0;return{type:"tool_result",turnId:e,callId:t.callId,name:t.toolName,ok:t.ok,error:t.error,outputPreview:o,durationMs:t.durationMs,exitCode:a,stdout:s,stderr:i,details:r}}function Or(e,t){if(!t.ok)return[];let n=t.details;if(!n)return[];let o=Ha(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 Ha(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 qa=new Set(["write","edit","patch"]);function Nr(e){let{turnId:t,result:n,toolCalls:o}=e;if(!n.ok)return[];let r=o.find(a=>a.id===n.callId);if(!r)return[];let s=[],i=Ga(r.function.arguments);if(!i)return s;if(qa.has(n.toolName)){let a=Wa(i);a&&s.push({type:"artifact",turnId:t,artifactId:`artifact-${n.callId}`,artifactType:Va(a),title:a.split(/[\\/]/).pop()||a,filePath:a,language:Xa(a)})}return s}function Ga(e){try{return JSON.parse(e)}catch{return null}}function Wa(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 Va(e){let t=e.split(".").pop()?.toLowerCase()??"";return["png","jpg","jpeg","gif","webp","svg","bmp","ico"].includes(t)?"image":["md","txt","pdf","doc","docx","rtf","html"].includes(t)?"document":["mermaid","mmd","dot","puml","plantuml"].includes(t)?"diagram":["csv","tsv","xlsx","xls"].includes(t)?"table":["ts","tsx","js","jsx","py","rs","go","java","c","cpp","h","cs","rb","sh","sql","json","yaml","yml","toml","xml","css","scss","vue","svelte"].includes(t)?"code":"file"}function Xa(e){let t=e.split(".").pop()?.toLowerCase()??"";return{ts:"typescript",tsx:"typescriptreact",js:"javascript",jsx:"javascriptreact",py:"python",rs:"rust",go:"go",java:"java",c:"c",cpp:"cpp",h:"c",cs:"csharp",rb:"ruby",sh:"shellscript",sql:"sql",json:"json",yaml:"yaml",yml:"yaml",toml:"toml",xml:"xml",html:"html",css:"css",scss:"scss",vue:"vue",svelte:"svelte",md:"markdown"}[t]}var $r=new Set(["write","edit","patch"]),Ur=new Set(["image_generate"]),Ka=/\b(?:verify|test|check|validate)\b[\s\S]{0,48}\b(?:browser|browser-visible|playwright|visible ui)\b|\b(?:browser|browser-visible|playwright|visible ui)\b[\s\S]{0,48}\b(?:verify|test|check|validate)\b/i,Ya=/\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,Za=/\b(?:under|inside|in|at|to|root|directory|folder|output directory|output folder)\s+([A-Za-z]:[\\/][^\s"'`<>|]+)|(?:目录|文件夹|根目录|输出到|放到|位于)\s*([A-Za-z]:[\\/][^\s"'`<>|]+)/gi,$n=/https?:\/\/[^\s"'`<>),;]+/gi,Ja=/\b(?:fatal|timeout|timed out|waitforselector|waiting for locator|strict mode violation|exception|traceback|eaddrinuse|page crashed|browser closed|target closed)\b|无法访问|错误|失败|超时/i,Qa=/\b(?:default vite|vite \+ react|edit src\/app|click on the vite|vite page)\b|默认\s*Vite/i,Lr=/\b(?:browser|playwright|puppeteer|screenshot|opened|loaded|navigated|visible|locator|page\.goto|http:\/\/127\.0\.0\.1|http:\/\/localhost)\b|(?:浏览器|截图|页面可见|打开页面|加载页面|内置浏览器|自动化)/i;function el(e){let t=qn(e);return{artifactRoot:t,rootSource:t?"explicit":void 0,writePaths:[],outOfRootWrites:[],devServerUrls:[],browserVerified:!1,browserEvidence:[],browserFailureEvidence:[],buildVerified:!1,buildEvidence:[],buildFailureEvidence:[]}}function me(e){return e.some(t=>t.role==="user"&&typeof t.content=="string"&&(Ya.test(t.content)||Ka.test(t.content)))}var tl=new RegExp(["\\b(?:tests?|test suite|unit tests?|the suite|build|compiles?|compilation|typecheck|lint)\\b[\\s\\S]{0,24}\\b(?:pass(?:es|ing)?|green|succeed(?:s|ed)?|clean|work(?:s|ing)?)\\b","\\b(?:pass(?:es|ing)?|green|succeed(?:s|ed)?)\\b[\\s\\S]{0,16}\\b(?:tests?|the suite|build)\\b","\\bfix(?:es|ing)?\\b[\\s\\S]{0,24}\\b(?:failing|broken)\\b[\\s\\S]{0,12}\\b(?:tests?|build|spec)\\b","\\bmake it (?:build|compile|pass)\\b","\\b(?:run|rerun|re-run) (?:the )?(?:tests?|test suite|build|spec)\\b","\\b(?:npm (?:test|run build)|pnpm (?:test|build)|yarn (?:test|build)|pytest|go test|cargo (?:test|build)|vitest|jest|gradle|mvn)\\b","(?:\u8BA9|\u4F7F|\u786E\u4FDD)[\\s\\S]{0,12}(?:\u6D4B\u8BD5|\u5355\u6D4B|\u7528\u4F8B|\u6784\u5EFA|\u7F16\u8BD1)[\\s\\S]{0,8}(?:\u901A\u8FC7|\u8DD1\u901A|\u6210\u529F|\u7EFF)","(?:\u4FEE\u590D|\u4FEE\u597D|\u89E3\u51B3)[\\s\\S]{0,12}(?:\u5931\u8D25\u7684?\u6D4B\u8BD5|\u6D4B\u8BD5\u5931\u8D25|\u7F16\u8BD1\u9519\u8BEF|\u6784\u5EFA\u9519\u8BEF|\u7F16\u8BD1\u62A5\u9519|\u62A5\u9519)","\u6D4B\u8BD5\u901A\u8FC7|\u8DD1\u901A\u6D4B\u8BD5|\u7F16\u8BD1\u901A\u8FC7|\u6784\u5EFA\u901A\u8FC7|\u901A\u8FC7(?:\u5168\u90E8|\u6240\u6709)?\u6D4B\u8BD5|\u8BA9\u6D4B\u8BD5\u53D8\u7EFF"].join("|"),"i");function jr(e){return e.some(t=>t.role==="user"&&typeof t.content=="string"&&tl.test(t.content))}var Dn=/```final-status[ \t]*\r?\n([\s\S]*?)\r?\n[ \t]*```/g,nl=new Set([...$r,...Ur,"exec","bash","shell","powershell","terminal","playwright","browser","computer"]);function zr(e){for(let t of e)if(nl.has(t))return!0;return!1}var Hr=["## Final status block","When this turn produced artifacts (files written, apps served), asserted verification (browser/build/tests), left requested work incomplete or blocked, or the user explicitly asked for a final status or an evidence audit, end your final message with exactly one fenced block:","","```final-status",'{"schema":1,"done":["\u2026"],"notDone":["\u2026"],"artifacts":{"root":"\u2026","files":["\u2026"],"urls":["\u2026"]},"verification":{"browser":"verified|failed|not-run","build":"passed|failed|not-run"},"sources":{"cited":["https://\u2026"]},"blockers":["\u2026"],"nextAction":"\u2026"}',"```","","Every field must reflect actual tool activity from this turn; the engine cross-checks the block against its own tool records and strips unsupported claims. Omit fields that do not apply. Omit the whole block for ordinary conversation."].join(`
|
|
2
|
+
`);function qr(e){Dn.lastIndex=0;let t=null;for(let o=Dn.exec(e);o;o=Dn.exec(e))t=o;if(!t)return null;let n={start:t.index,end:t.index+t[0].length};try{let o=JSON.parse(t[1]);if(!o||typeof o!="object"||Array.isArray(o))return{claim:null,...n};let r=o;return r.schema!==1?{claim:null,...n}:{claim:r,...n}}catch{return{claim:null,...n}}}function Fr(e){return"```final-status\n"+JSON.stringify(e,null,2)+"\n```"}function Un(e,t){let n=Qr(t);return n?$r.has(e)?Br(n.path,n.file_path,n.filePath,n.filename,n.file):Ur.has(e)?Br(n.output_path,Array.isArray(n.output_paths)?n.output_paths[0]:void 0):null:null}function Gr(e){let t=Un(e.toolName,e.rawArguments);if(!t||!me(e.inputMessages))return null;if(!e.state.artifactRoot){let r=qn(e.inputMessages);r?(e.state.artifactRoot=r,e.state.rootSource="explicit"):(e.state.artifactRoot=es(t),e.state.rootSource=e.state.artifactRoot?"inferred":void 0)}let n=e.state.artifactRoot;if(!n||e.state.rootSource!=="explicit"||ns(t,n))return null;let o=`Artifact root contract blocked ${e.toolName}: attempted to write ${t}, but this deliverable root is ${n}. Keep generated app/project files inside the declared artifactRoot, or ask for explicit approval before changing scope.`;return{path:t,artifactRoot:n,error:o}}function Wr(e){let t=Un(e.toolName,e.rawArguments);return!t||!yl(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 jn(e,t){e.writePaths.includes(t.path)||e.writePaths.push(t.path),e.outOfRootWrites.some(n=>n.path===t.path&&n.toolName===t.toolName)||e.outOfRootWrites.push(t)}function Vr(e){let t=Un(e.toolName,e.rawArguments);if(t){if(!e.state.artifactRoot){let o=qn(e.inputMessages);e.state.artifactRoot=o??es(t),e.state.rootSource=o?"explicit":e.state.artifactRoot?"inferred":void 0}e.state.writePaths.includes(t)||e.state.writePaths.push(t),me(e.inputMessages)&&e.state.artifactRoot&&e.state.rootSource==="explicit"&&!ns(t,e.state.artifactRoot)&&jn(e.state,{path:t,artifactRoot:e.state.artifactRoot,toolName:e.toolName})}let n=`${e.rawArguments}
|
|
3
|
+
${e.content}`;for(let o of n.matchAll($n)){let r=nt(o[0]);r&&(e.state.devServerUrls.includes(r)||e.state.devServerUrls.push(r))}if(dl(e.toolName,e.rawArguments,e.content)&&ts(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&&ul(e.toolName,e.rawArguments,e.content)){e.state.browserVerified=!0;let o=e.content.trim().slice(0,500);o&&!e.state.browserEvidence.includes(o)&&e.state.browserEvidence.push(o)}if(ml(e.toolName,e.rawArguments))if(!e.ok||gl(e.content)){e.state.buildVerified=!1;let r=e.content.trim().slice(0,500);r&&!e.state.buildFailureEvidence.includes(r)&&e.state.buildFailureEvidence.push(r)}else{e.state.buildVerified=!0,e.state.buildFailureEvidence=[];let r=e.content.trim().slice(0,300);r&&!e.state.buildEvidence.includes(r)&&e.state.buildEvidence.push(r)}}function zn(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:me(t)}}function Xr(e){let t=el(e);for(let n of e)n.role!=="assistant"||typeof n.content!="string"||Hn(t,n.content);return t.recoveredBaseline={writePaths:t.writePaths.length,devServerUrls:t.devServerUrls.length,artifactRoot:!!t.artifactRoot},t}function Hn(e,t){let n=qr(t)?.claim?.artifacts;if(n){typeof n.root=="string"&&n.root&&!e.artifactRoot&&(e.artifactRoot=Ee(n.root),e.rootSource="inferred");for(let o of n.files??[]){if(typeof o!="string")continue;let r=Ee(o.trim());r&&!e.writePaths.includes(r)&&e.writePaths.push(r)}for(let o of n.urls??[]){if(typeof o!="string")continue;let r=nt(o);r&&!e.devServerUrls.includes(r)&&e.devServerUrls.push(r)}}for(let o of t.matchAll($n)){let r=nt(o[0]);r&&/^https?:\/\/(?:localhost|127\.0\.0\.1):\d+\//i.test(r)&&(e.devServerUrls.includes(r)||e.devServerUrls.push(r))}}var ol=/[一-鿿]/;function Kr(e){for(let t=e.length-1;t>=0;t-=1){let n=e[t];if(!(n.role!=="user"||typeof n.content!="string"))return ol.test(n.content)?"zh":"en"}return"en"}var rl={en:{doneRan:(e,t)=>`Ran ${e} tool call${e===1?"":"s"} (${t}).`,doneNoToolCalls:"No tool calls were executed; blocked requests are listed under blockers.",doneNoToolWork:"No tool work was recorded.",notDoneUnresolvedTasks:(e,t)=>`Task list still has ${e} unresolved item(s): ${t}.`,blockerResolveTasks:"Update unresolved task items to completed, cancelled, or an explicit blocker before claiming completion.",notDoneOutOfRoot:"At least one write landed outside the declared deliverable root.",blockerOutOfRoot:(e,t,n)=>`${e} attempted ${t} outside ${n}.`,notDoneBuildFailing:"A test/build run is failing; no passing test/build evidence was recorded.",blockerFixBuild:e=>`Fix the code and re-run the test/build until it passes: ${e}`,notDoneTerminalBlockers:"The turn stopped with unresolved tool-call blockers instead of completing all requested work.",blockerToolBlocked:(e,t)=>`${e} blocked by ${t}.`,nextActionResolveBlockers:"Resolve the blocker(s), then rerun verification and issue a new final status.",nextActionProceed:"Proceed with user review or requested follow-up."},zh:{doneRan:(e,t)=>`\u6267\u884C\u4E86 ${e} \u6B21\u5DE5\u5177\u8C03\u7528(${t})\u3002`,doneNoToolCalls:"\u672A\u6267\u884C\u4EFB\u4F55\u5DE5\u5177\u8C03\u7528\uFF1B\u88AB\u963B\u585E\u7684\u8BF7\u6C42\u5217\u5728\u963B\u585E\u9879\u4E2D\u3002",doneNoToolWork:"\u672A\u8BB0\u5F55\u5230\u4EFB\u4F55\u5DE5\u5177\u5DE5\u4F5C\u3002",notDoneUnresolvedTasks:(e,t)=>`\u4EFB\u52A1\u6E05\u5355\u4ECD\u6709 ${e} \u9879\u672A\u5904\u7406\uFF1A${t}\u3002`,blockerResolveTasks:"\u5728\u58F0\u660E\u5B8C\u6210\u524D\uFF0C\u5C06\u672A\u5904\u7406\u7684\u4EFB\u52A1\u9879\u66F4\u65B0\u4E3A\u5DF2\u5B8C\u6210\u3001\u5DF2\u53D6\u6D88\u6216\u660E\u786E\u7684\u963B\u585E\u9879\u3002",notDoneOutOfRoot:"\u81F3\u5C11\u6709\u4E00\u6B21\u5199\u5165\u843D\u5728\u58F0\u660E\u7684\u4EA4\u4ED8\u6839\u76EE\u5F55\u4E4B\u5916\u3002",blockerOutOfRoot:(e,t,n)=>`${e} \u5C1D\u8BD5\u5199\u5165 ${t}\uFF0C\u8D85\u51FA ${n}\u3002`,notDoneBuildFailing:"\u6D4B\u8BD5/\u6784\u5EFA\u8FD0\u884C\u5931\u8D25\uFF1B\u672A\u8BB0\u5F55\u5230\u901A\u8FC7\u7684\u6D4B\u8BD5/\u6784\u5EFA\u8BC1\u636E\u3002",blockerFixBuild:e=>`\u4FEE\u590D\u4EE3\u7801\u5E76\u91CD\u65B0\u8FD0\u884C\u6D4B\u8BD5/\u6784\u5EFA\u76F4\u5230\u901A\u8FC7\uFF1A${e}`,notDoneTerminalBlockers:"\u672C\u8F6E\u5728\u5B58\u5728\u672A\u89E3\u51B3\u7684\u5DE5\u5177\u8C03\u7528\u963B\u585E\u65F6\u505C\u6B62\uFF0C\u672A\u5B8C\u6210\u5168\u90E8\u8BF7\u6C42\u7684\u5DE5\u4F5C\u3002",blockerToolBlocked:(e,t)=>`${e} \u88AB ${t} \u963B\u585E\u3002`,nextActionResolveBlockers:"\u89E3\u51B3\u963B\u585E\u9879\u540E\uFF0C\u91CD\u65B0\u8FD0\u884C\u9A8C\u8BC1\u5E76\u7ED9\u51FA\u65B0\u7684\u6700\u7EC8\u72B6\u6001\u3002",nextActionProceed:"\u53EF\u4EE5\u8FDB\u884C\u7528\u6237\u5BA1\u9605\u6216\u6309\u9700\u8DDF\u8FDB\u3002"}};function Yr(e){let t=e.content.trim();if(!e.contractActive)return{content:t,malformedBlock:!1};let n=qr(t);if(n?.claim){let i=t.slice(0,n.start).trimEnd(),a=t.slice(n.end).trim(),c=[i,a].filter(Boolean).join(`
|
|
4
|
+
`),{claim:f,notices:g}=sl(n.claim,c,e),y=[i,Fr(f),a];return g.length>0&&y.push(g.map(k=>`Engine notice: ${k}`).join(`
|
|
5
5
|
`)),{content:y.filter(Boolean).join(`
|
|
6
6
|
|
|
7
|
-
`),malformedBlock:!1}}let o=n!==null;if(
|
|
7
|
+
`),malformedBlock:!1}}let o=n!==null;if(bl(t)&&e.totalToolCallCount===0)return{content:t,malformedBlock:o};let r=il(e);if(!r)return{content:t,malformedBlock:o};let s=Fr(r);return{content:t?`${t}
|
|
8
8
|
|
|
9
|
-
${s}`:s,malformedBlock:o}}function
|
|
10
|
-
${n}`),s=
|
|
9
|
+
${s}`:s,malformedBlock:o}}function sl(e,t,n){let o=n.artifactContract,r=[],s={...e,schema:1,author:"model"};if(s.verification){let a={...s.verification};a.browser==="verified"&&o.browserEvidence.length===0&&(a.browser=o.browserFailureEvidence.length>0?"failed":"not-run",r.push(`browser "verified" claim corrected to "${a.browser}" \u2014 no passing browser evidence was recorded this turn.`)),a.build==="passed"&&!o.buildVerified&&(a.build=o.buildFailureEvidence.length>0?"failed":"not-run",r.push(`build "passed" claim corrected to "${a.build}" \u2014 no passing test/build run was recorded this turn.`)),s.verification=a}let i=Zr(n.activeTasks??[]);if(i.length>0&&(s.done?.length??0)>0){let a=[...s.notDone??[]];for(let c of i){let f=`Task ${Jr(c)} is unresolved.`;a.includes(f)||a.push(f)}s.notDone=a,r.push(`${i.length} task item(s) remain unresolved; completion is not confirmed.`)}if(s.artifacts?.files?.length){let a=o.writePaths.map(je),c=typeof s.artifacts.root=="string"&&s.artifacts.root?s.artifacts.root:o.artifactRoot,f=k=>{let x=je(k);return x?a.includes(x)||c&&a.includes(je(`${c}/${k}`))?!0:a.some(_=>_.endsWith(`/${x}`)):!1},g=s.artifacts.files.filter(k=>typeof k=="string"&&f(k)),y=s.artifacts.files.length-g.length;y>0&&(s.artifacts={...s.artifacts,files:g},r.push(`${y} artifact file claim(s) removed \u2014 not recorded as written this turn.`))}if(s.sources?.cited?.length){let a=new Set([...cl(t),...o.devServerUrls]),c=[];for(let g of s.sources.cited){if(typeof g!="string")continue;let y=nt(g);y&&a.has(y)&&!c.includes(y)&&c.push(y)}let f=s.sources.cited.length-c.length;f>0&&(s.sources={...s.sources,cited:c},r.push(`${f} cited source(s) removed \u2014 not seen in this turn's response or tool results.`))}return{claim:s,notices:r}}function il(e){let t=e.artifactContract,n=rl[e.locale??"en"],o=Zr(e.activeTasks??[]),r=e.forcedStop?ll(e.blockedToolCalls??[]):[],s=t.recoveredBaseline??{writePaths:0,devServerUrls:0,artifactRoot:!1},i=t.writePaths.slice(s.writePaths),a=t.devServerUrls.slice(s.devServerUrls);if(!(!!t.artifactRoot&&!s.artifactRoot||i.length>0||a.length>0||t.browserVerified||t.outOfRootWrites.length>0||t.buildVerified||t.buildFailureEvidence.length>0)&&o.length===0&&r.length===0)return null;let f=[],g=[];o.length>0&&(f.push(n.notDoneUnresolvedTasks(o.length,o.map(Jr).join("; "))),g.push(n.blockerResolveTasks)),t.outOfRootWrites.length>0&&(f.push(n.notDoneOutOfRoot),g.push(...t.outOfRootWrites.slice(0,3).map(S=>n.blockerOutOfRoot(S.toolName,S.path,S.artifactRoot)))),!t.buildVerified&&t.buildFailureEvidence.length>0&&(f.push(n.notDoneBuildFailing),g.push(n.blockerFixBuild(t.buildFailureEvidence[0].slice(0,200)))),r.length>0&&(f.push(n.notDoneTerminalBlockers),g.push(...r.slice(0,5).map(S=>n.blockerToolBlocked(S.name,S.reason))));let y=e.visibleToolCallCount??e.totalToolCallCount,k=[...e.visibleToolNames??e.distinctToolNames],_={schema:1,author:"engine",done:[y>0?n.doneRan(y,k.join(", ")||"unknown tools"):e.totalToolCallCount>0?n.doneNoToolCalls:n.doneNoToolWork],verification:{browser:t.browserVerified?"verified":t.browserFailureEvidence.length>0?"failed":"not-run",build:t.buildVerified?"passed":t.buildFailureEvidence.length>0?"failed":"not-run"},nextAction:g.length>0?n.nextActionResolveBlockers:n.nextActionProceed};f.length>0&&(_.notDone=f),g.length>0&&(_.blockers=g);let v={};return t.artifactRoot&&(v.root=Ee(t.artifactRoot)),i.length>0&&(v.files=i.slice(0,8).map(Ee)),a.length>0&&(v.urls=[...a]),Object.keys(v).length>0&&(_.artifacts=v),_}function Zr(e){return e.filter(t=>t.status!=="completed")}function Jr(e){return`#${e.id} ${e.title} (${e.status})`}var al=new Set(["artifact-root-contract","dedicated-tool-required","identical-repeat-policy","invalid-arguments","not-offered","read-only-context-pack","tool-call-budget","variant-failure-policy"]);function ll(e){return e.filter(t=>al.has(t.reason))}function cl(e){let t=[];for(let n of e.matchAll($n)){let o=nt(n[0]);o&&!t.includes(o)&&t.push(o)}return t}function Qr(e){try{return JSON.parse(e)}catch{return null}}function Br(...e){for(let t of e)if(typeof t=="string"&&t.trim())return t.trim();return null}function qn(e){for(let t of e)if(!(t.role!=="user"||typeof t.content!="string"))for(let n of t.content.matchAll(Za)){let o=n[1]??n[2],r=St(o??"");if(r&&!hl(r))return Ee(r)}}function es(e){let t=Ee(St(e));if(!t)return;let n=t.toLowerCase();if(n.endsWith("/package.json"))return Dr(t);let o=n.lastIndexOf("/src/");if(o>0)return t.slice(0,o);if(n.endsWith("/index.html")||n.endsWith("/vite.config.ts")||n.endsWith("/vite.config.js"))return Dr(t)}function ul(e,t,n){if(/^read$/i.test(e)||n.includes("<persisted-output>")||ts(n)||/\b(?:syntax error|command not found|cannot find|not recognized|failed|failure|exception|traceback|eaddrinuse)\b|无法将|错误|失败/i.test(n))return!1;let o=Lr.test(n),r=/\b(?:playwright|puppeteer|browser|screenshot|locator|page\.goto|dom snapshot|visible text|assertion)\b|浏览器|截图|可见|定位器/i.test(`${t}
|
|
10
|
+
${n}`),s=Gn(e)&&Lr.test(t)&&o&&r&&/\b(?:ok|success|passed|loaded|visible|rendered|found|present|assertion passed)\b|可见|加载成功|通过/i.test(n),i=/\b(?:200|ok|success|passed|loaded|visible|rendered|found|present|assertion passed)\b|可见|加载成功|通过/i.test(n);return!(!s&&!(o&&r&&i)||Qa.test(n)&&!/\b(?:absent|removed|not present|gone|没有|不是默认|已移除)\b/i.test(n))}function dl(e,t,n){return/^read$/i.test(e)||!Gn(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 ts(e){return/\b(?:no failed|0 failed|without failed|no failures|failure:? none|failed checks?:? none)\b/i.test(e)?!1:Ja.test(e)?!0:/\b(?:fail|failed|failure|error)\b/i.test(e)}function Gn(e){return/^(?:exec|bash|shell|powershell|terminal|playwright|browser|computer)$/i.test(e)}var fl=new RegExp(["(?:^|[\\s;&|(])(?:npm|pnpm|yarn|bun)\\s+(?:run\\s+)?(?:test|t|build|lint|typecheck|tsc|check)\\b","(?:^|[\\s;&|(])npx\\s+(?:-y\\s+)?(?:vitest|jest|mocha|tsc|playwright|ava|tap)\\b","(?:^|[\\s;&|(])(?:vitest|jest|mocha|ava|pytest|py\\.test|ctest|tsc)\\b","(?:^|[\\s;&|(])python\\s+-m\\s+(?:pytest|unittest)\\b","(?:^|[\\s;&|(])go\\s+test\\b","(?:^|[\\s;&|(])cargo\\s+(?:test|build|check)\\b","(?:^|[\\s;&|(])(?:mvn|gradle|gradlew|make|cmake)\\s+\\S","(?:^|[\\s;&|(])node\\s+(?:--test\\b|[^\\n;&|]*test[^\\n;&|]*\\.[cm]?js)"].join("|"),"i");function pl(e){let t=Qr(e);return t&&typeof t.command=="string"?t.command:""}function ml(e,t){return Gn(e)?fl.test(pl(t)):!1}function gl(e){return/\[exit [1-9]\d*\b|\(exit code [1-9]\d*\b|\[interrupted — exit code [1-9]\d*/.test(e)}function hl(e){return/\.[A-Za-z0-9]{1,12}$/.test(e)}function ns(e,t){let n=je(e),o=je(t);return n===o||n.startsWith(`${o}/`)}function yl(e){return je(e).split("/").includes("context-pack")}function je(e){return St(e).replace(/\\/g,"/").replace(/\/+/g,"/").replace(/\/$/u,"").toLowerCase()}function Ee(e){return St(e).replace(/\\/g,"/").replace(/\/+/g,"/").replace(/\/$/u,"")}function nt(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 St(e){return e.trim().replace(/[).,;:,。;、:]+$/u,"")}function bl(e){return/^[A-Z0-9_ -]{6,80}$/.test(e.trim())}function Dr(e){let t=Ee(e),n=t.lastIndexOf("/");return n>0?t.slice(0,n):t}var Tl=/^no (matches|files|results) found(?:\s+for:.*)?\.?$|^file not found|^not found|^0 results|^\(exit code \d+, no output\)$/i,Cl=new Set(["search","web_search","grep","glob","find","list","read","exec"]);function Wn(e){if(!Cl.has(e.toolName))return!1;let t=typeof e.message?.content=="string"?kl(e.message.content).trim():"";return t.length>0&&t.length<200&&Tl.test(t)}function kl(e){return e.match(/<untrusted_tool_result\b[^>]*>\s*([\s\S]*?)\s*<\/untrusted_tool_result>/i)?.[1]??e}var Rl=/[A-Za-z]:[\\/](?:[^\s"'`<>|,\uFF0C\u3001;\uFF1B\u3002]+[\\/])*[^\s"'`<>|,\uFF0C\u3001;\uFF1B\u3002]+\.[A-Za-z0-9]{1,12}/g,xl=/(?:^|[\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,_l=/(?:^|[\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,vl=/\b(?:create|generate|write|produce|save|output|deliver|deliverables?|artifacts?|required|required files?|must generate|self-verify)\b|(?:生成|创建|写入|输出|保存|交付|产物|文件|必须|自检|验证)/i;function Et(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 Al=/\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,os=50,rs=90;function ss(e){if(!e)return!1;for(let t of e)if(t.role==="user"&&typeof t.content=="string"&&Al.test(t.content))return!0;return!1}var wl=/(?:我来|我先|我现在就?|让我先?|接下来我?|我帮你|我这就|我会|我将|我去|我看)[^。.!?!?\n]{0,12}(?:做|搭建?|写|开发|实现|构建|生成|创建|新建|建立|改|修复?|检查|读取?|运行|跑|执行|看一?下?|查看|配置|安装|部署|分析|整理|定位|排查|找)/,Sl=/\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 is(e){let t=e.trim();return t.length===0||t.length>200||t.includes("```")?!1:wl.test(t)||Sl.test(t)}var El=/(?:^|[,。!?;:、,.!?;:()()"'「」『』])(?:我们?)?(?:目前|暂时|现在|当前)?(?:无法|不能|没有办法|做不到|不具备|暂不支持|不支持)[^。.!?!?\n]{0,24}(?:能力|权限|功能|工具|截图|截屏|访问|操作)|我们?(?:目前|暂时|现在)?没有[^。.!?!?\n]{0,24}(?:能力|权限|功能|工具|截图|截屏|访问|操作)/,Ml=/\b(?:i\s+(?:can(?:no|')t|cannot|am unable to|don['’]?t have|do not have|lack))\b[^.!?\n]{0,60}\b(?:ability|capability|permission|access|tool|feature|screenshot|support)\b|\bno such (?:tool|capability)\b/i;function as(e){let t=e.trim();return t.length===0||t.length>600?!1:El.test(t)||Ml.test(t)}function ls(e,t){if(typeof e=="number"&&Number.isFinite(e)&&e>=1)return Math.min(Math.round(e),100);let n=Mt(t);return n>=3?Math.min(Math.max(25,20+n*15),100):me(t??[])?Math.min(Math.max(25,rs),100):ss(t)?Math.min(Math.max(25,os),100):25}function Mt(e){if(!e)return 0;let t=new Set,n=new Set,o=r=>{let s=r.replace(/[),.;:\uFF0C\u3002\uFF1B\u3001]+$/u,"").replace(/\\/g,"/").toLowerCase();t.add(`path:${s}`);let i=s.split("/").pop();i&&n.add(i)};for(let r of e){if(r.role!=="user"||typeof r.content!="string")continue;let s=r.content;for(let i of r.content.matchAll(Rl))o(i[0]);if(vl.test(s)){for(let i of s.matchAll(xl)){let a=i[1]?.toLowerCase();if(!a)continue;t.add(`relative:${a.replace(/\\/g,"/")}`);let c=a.replace(/\\/g,"/").split("/").pop();c&&n.add(c)}for(let i of s.matchAll(_l)){let a=i[1]?.toLowerCase();!a||n.has(a)||t.add(`name:${a}`)}}}return t.size}function cs(e,t){if(typeof e=="number"&&Number.isFinite(e)&&e>=1)return Math.min(Math.round(e),100);let n=Mt(t);return n>=3?Math.min(Math.max(Ce,20+n*15),100):me(t??[])?Math.min(Math.max(Ce,rs),100):ss(t)?Math.min(Math.max(Ce,os),100):Ce}function us(e){return e.filter(t=>t.role!=="assistant"?!0:!(typeof t.content=="string"&&t.content.trim()===""))}function Vn(e,t){let n=[];for(let o=e.length-1;o>=0;o--){let r=e[o];if(r.role==="tool"&&typeof r.content=="string")n.unshift(r.content.slice(0,500));else if(r.role==="assistant"){if(typeof r.content=="string"&&r.content.trim())return t.info("synthesizeFallbackContent: found assistant text, using it"),r.content;break}else break}return n.length>0?(t.info(`synthesizeFallbackContent: synthesized from ${n.length} tool result(s)`),n.join(`
|
|
11
11
|
|
|
12
|
-
`)):""}function
|
|
12
|
+
`)):""}function Xn(e,t){let n=Et(e,"")?.slice(0,600).trim(),o=`\u5DF2\u505C\u6B62\u672C\u8F6E\uFF1A\u5DE5\u5177\u8FDE\u7EED ${t} \u8F6E\u8C03\u7528\u5931\u8D25\uFF0C\u7EE7\u7EED\u91CD\u8BD5\u6CA1\u6709\u610F\u4E49\u3002`;return n?`${o}
|
|
13
13
|
|
|
14
14
|
\u6700\u540E\u4E00\u6B21\u5DE5\u5177\u9519\u8BEF\uFF1A
|
|
15
15
|
${n}
|
|
16
16
|
|
|
17
17
|
\u8BF7\u6839\u636E\u4E0A\u9762\u7684\u9519\u8BEF\u4FEE\u6B63\u540E\u91CD\u8BD5\uFF0C\u6216\u6362\u4E00\u79CD\u5B9E\u73B0\u65B9\u5F0F\u3002`:`${o}
|
|
18
18
|
|
|
19
|
-
\u8BF7\u91CD\u8BD5\uFF0C\u6216\u6362\u4E00\u79CD\u5B9E\u73B0\u65B9\u5F0F\u3002`}function
|
|
19
|
+
\u8BF7\u91CD\u8BD5\uFF0C\u6216\u6362\u4E00\u79CD\u5B9E\u73B0\u65B9\u5F0F\u3002`}function ds(e){let t,n;for(let r=e.length-1;r>=0;r--){let s=e[r];if(s?.role==="tool"&&typeof s.content=="string"&&s.content.startsWith("Error: ")){t=s.content.slice(7,807).trim(),n=typeof s.tool_call_id=="string"?s.tool_call_id:void 0;break}}if(!t)return null;let o;if(n)for(let r of e){let s=r.tool_calls;if(Array.isArray(s))for(let i of s){let a=i;if(a.id!==n)continue;let c=a.function;typeof c?.arguments=="string"&&(o=Kn(c.arguments)??c.arguments.slice(0,200))}}return{role:"user",content:`\u4F60\u6700\u8FD1\u7684\u5DE5\u5177\u8C03\u7528\u8FDE\u7EED\u5931\u8D25\u4E86\u3002\u653E\u5F03\u4E4B\u524D\u5148\u505C\u4E0B\u6765\u7EA0\u6B63\u2014\u2014**\u4E0D\u8981\u518D\u91CD\u590D\u540C\u6837\u7684\u5931\u8D25\u547D\u4EE4**\u3002
|
|
20
20
|
|
|
21
21
|
`+(o?`\u6700\u540E\u4E00\u6B21\u8C03\u7528\uFF1A${o}
|
|
22
22
|
`:"")+`\u6700\u540E\u4E00\u6B21\u9519\u8BEF\uFF1A
|
|
23
23
|
${t}
|
|
24
24
|
|
|
25
|
-
\u8BF7\u6309\u9519\u8BEF\u4FE1\u606F\u7EA0\u6B63\u540E\u518D\u91CD\u8BD5\uFF1A\u5982\u679C\u662F\u547D\u4EE4\u884C\u5DE5\u5177\uFF0C\u5148\u7528\u5B83\u81EA\u5E26\u7684\u5E2E\u52A9\u786E\u8BA4\u6B63\u786E\u7684\u5B50\u547D\u4EE4/\u53C2\u6570/\u8BED\u6CD5\uFF08\u5982 \`<\u5DE5\u5177> --help\` \u6216 \`<\u5DE5\u5177> help <\u5B50\u547D\u4EE4>\`\uFF09\uFF0C\u4E0D\u8981\u51ED\u76F4\u89C9\u62FC\u547D\u4EE4\uFF1B\u6216\u6362\u4E00\u79CD\u5B9E\u73B0\u65B9\u5F0F\u3002`}}function
|
|
26
|
-
`,t),e.lastIndexOf(";",t),e.lastIndexOf("\u3002",t),e.lastIndexOf("\uFF1B",t))+1,r=e.slice(o,t).toLowerCase();if(/\b(?:do\s+not|don't|never)\s+(?:leave|create|write|include|keep|produce|add|generate)\b/i.test(r)||/\b(?:remove|delete|exclude)\b/i.test(r))return!0;let s=e.slice(Math.max(0,t-16),t+n.length);return new RegExp(`\\bno\\s+${
|
|
27
|
-
`).replace(/\\/g,"/").toLowerCase()}function
|
|
25
|
+
\u8BF7\u6309\u9519\u8BEF\u4FE1\u606F\u7EA0\u6B63\u540E\u518D\u91CD\u8BD5\uFF1A\u5982\u679C\u662F\u547D\u4EE4\u884C\u5DE5\u5177\uFF0C\u5148\u7528\u5B83\u81EA\u5E26\u7684\u5E2E\u52A9\u786E\u8BA4\u6B63\u786E\u7684\u5B50\u547D\u4EE4/\u53C2\u6570/\u8BED\u6CD5\uFF08\u5982 \`<\u5DE5\u5177> --help\` \u6216 \`<\u5DE5\u5177> help <\u5B50\u547D\u4EE4>\`\uFF09\uFF0C\u4E0D\u8981\u51ED\u76F4\u89C9\u62FC\u547D\u4EE4\uFF1B\u6216\u6362\u4E00\u79CD\u5B9E\u73B0\u65B9\u5F0F\u3002`}}function ot(e){let t=e.replace(/\s+/g," ").trim().split(" "),n=(t[0]??"").replace(/^.*[\\/]/,"").toLowerCase(),o=(t[1]??"").replace(/^.*[\\/]/,"").toLowerCase(),r=/^[a-z][\w.-]*$/i.test(o)?o:"";return[n,r].filter(Boolean).join(" ")}var Il=/^(?:npx )?(?:vitest|jest|mocha|playwright|pytest|tsc|eslint|oxlint)\b|^(?:pnpm|npm|yarn) (?:test|run|build|lint|check)\b|^(?:go|cargo) (?:test|build|check)\b|^git (?:status|diff|log|add|commit)\b/;function fs(e){return Il.test(e)}var Pl=/^(?:pip3?|pipx|uv|conda|npm|pnpm|yarn|apt(?:-get)?|brew|choco|winget)(?:\.\w+)?$/i;function ps(e){if(!e)return!1;let t=ot(e),[n,o]=t.split(" ");return!n||!Pl.test(n)?!1:o==="install"||o==="add"}function Kn(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 Yn(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 Zn(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 ms(e){return e==="length"||e==="max_tokens"}function Jn(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 gs(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 hs(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*ys(e){let{messages:t,contentReplacementState:n,snipRemovedIds:o,collapseStore:r,guardConfig:s,runtimePorts:i,hooks:a,hookCtx:c,sessionId:f,currentModel:g,log:y,recovery:k,onAutocompact:x}=e,_;{let v=await i.enforceToolResultBudget(t,n,f);_=v.messages,v.newlyReplacedCount>0&&(y.info(`tool-result-budget: persisted ${v.newlyReplacedCount} oversized tool results`),yield k("tool_result_budget",`${v.newlyReplacedCount} persisted`))}{let v=yn(_,o);_=v.messages,v.removedCount>0&&(y.info(`snip: removed ${v.removedCount} messages, freed ~${v.tokensFreed} tokens`),yield k("snip",`${v.removedCount} messages`))}{let S=new et().compress(_,0);S.droppedCount>0&&(_=S.messages,y.info(`microcompact: cleared ${S.droppedCount} old tool results`))}if(_=Tn(_,r).messages,s.contextWindowTokens>0){let v=s.contextWindowTokens*.75,S=i.getActiveContextCompressionEngine(),M;S?M=await S.compressAsync(_,v,{model:g,sessionId:f}):M=i.compressMessages(_,{budget:v,model:g}),M.droppedCount>0&&(_=M.messages,y.info(`autocompact: ${M.strategy}, dropped ${M.droppedCount}`),yield k("autocompact",`${M.strategy}: ${M.droppedCount} dropped`),yield{type:"lifecycle",turnId:c.turnId,kind:"context_compression",status:"completed",detail:`${M.strategy}: ${M.droppedCount} dropped`},x(),$(a,"context.after_compact",{...c,removedCount:M.droppedCount},y))}return _=us(_),_}async function*bs(e,t){let{state:n,guardState:o,fallbackModel:r,signal:s,querySource:i,turnId:a,log:c,emitRecovery:f}=t;if(e instanceof tt&&r)return c.info(`model fallback triggered: ${e.originalModel} -> ${e.fallbackModel}`),yield f("model_fallback",`${e.originalModel} -> ${e.fallbackModel}`),{kind:"continue",patch:{currentModel:e.fallbackModel,consecutive529Errors:0,consecutiveApiRetries:0,transition:void 0}};let g=e instanceof Error?e.message:String(e),y=typeof e?.status=="number"?e.status:void 0;if(!y&&g&&(g.includes("ECONNRESET")||g.includes("EPIPE"))){let x=(n.consecutiveApiRetries??0)+1;return x>Se?(c.info(`stale connection retry limit reached (${Se}), aborting`),yield{type:"error",turnId:a,error:g,code:"RETRIES_EXHAUSTED",usage:n.totalUsage},{kind:"return"}):(c.info(`stale connection (${g.includes("ECONNRESET")?"ECONNRESET":"EPIPE"}): retrying`),yield f("stale_connection_retry",g.slice(0,80)),{kind:"continue",patch:{consecutiveApiRetries:x,transition:void 0}})}let k=hs({status:y,message:g});if(k!==null)return c.info(`max_tokens overflow: adjusting to ${k}`),o.currentMaxOutputTokens=k,{kind:"continue",patch:{maxOutputTokensOverride:k,transition:void 0}};if(Mn(y)){n.consecutive529Errors++;let x=2,_=r&&n.currentModel!==r;if(n.consecutive529Errors>x&&!_&&!wt())return c.info(`transient ${y} \xD7 ${n.consecutive529Errors}: hard limit reached, aborting`),yield{type:"error",turnId:a,error:`API unavailable after ${n.consecutive529Errors} consecutive ${y} errors`,code:"API_ERROR",usage:n.totalUsage},{kind:"return"};if(n.consecutive529Errors>=Tr&&r&&n.currentModel!==r)return c.info(`529 \xD7 ${n.consecutive529Errors}: triggering fallback to ${r}`),yield f("model_fallback",`529 \xD7 ${n.consecutive529Errors}`),{kind:"continue",patch:{currentModel:r,consecutive529Errors:0,transition:void 0}};if(wt()){let v=At(n.consecutive529Errors);c.info(`persistent retry: waiting ${v}ms (attempt ${n.consecutive529Errors})`);let S=v;for(;S>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(S/1e3)}s (${y})`};let M=Math.min(S,br);await new Promise(N=>setTimeout(N,M)),S-=M}return{kind:"continue",patch:{transition:void 0}}}if(En(i)){let S=gs({status:y,message:g})??At(n.consecutive529Errors);return c.info(`transient ${y}: retry in ${S}ms`),yield f("retry",`${y} retry in ${S}ms`),await new Promise(M=>setTimeout(M,S)),{kind:"continue",patch:{transition:void 0}}}c.info(`background source ${i}: not retrying ${y}`)}return{kind:"streamError",streamError:{status:y,message:g}}}import{readdirSync as xs,statSync as st}from"node:fs";var Ol=/create\s+(?:a\s+)?file|write\s+(?:a\s+)?file|make\s+(?:a\s+)?file|generate\s+(?:a\s+)?file|new\s+file/i,Nl=/\bfix\b|implement|modify|update|repair/i,_s=/[A-Za-z]:[\\/](?:[^\s"'`<>|,\uFF0C\u3001;\uFF1B\u3002]+[\\/])*[^\s"'`<>|,\uFF0C\u3001;\uFF1B\u3002]+\.[A-Za-z0-9]{1,12}/g,Ts=/\s*[,\uFF0C\u3001;\uFF1B]\s*([^\s"'`<>|,\uFF0C\u3001;\uFF1B\u3002\\/]+\.[A-Za-z0-9]{1,12})/gy,Ll=/\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,Fl=/(?:^|[\s"'`([{,;:\uFF0C\u3001\uFF1B])([A-Za-z0-9][A-Za-z0-9._-]*\.(?:xlsx|xls|pptx|ppt|docx|pdf|md|markdown|html|css|js|jsx|ts|tsx|json|csv|tsv|png|jpg|jpeg|webp|svg|gif|mp4|mov|wav|mp3|m4a|zip|petdex))(?:$|[\s"'`\])},.;:\uFF0C\u3001\uFF1B\u3002])/gi,Bl=/(?:^|[\s"'`([{,;:\uFF0C\u3001\uFF1B])([A-Za-z0-9][A-Za-z0-9._-]*(?:[\\/][A-Za-z0-9][A-Za-z0-9._-]*)+\.(?:xlsx|xls|pptx|ppt|docx|pdf|md|markdown|html|css|js|jsx|ts|tsx|json|csv|tsv|png|jpg|jpeg|webp|svg|gif|mp4|mov|wav|mp3|m4a|zip|petdex))(?:$|[\s"'`\])},.;:\uFF0C\u3001\uFF1B\u3002])/gi,Dl=/(?:^|[\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,$l=/\b(?:create|generate|write|produce|save|output|deliver|deliverables?|artifacts?|required|required files?|must generate|self-verify)\b|(?:生成|创建|写入|输出|保存|交付|产物|文件|必须|自检|验证)/i,Ul=/\bpreviews?[\\/]\s*(?:containing|with|under|for)?[^.。;;\n]*(?:rendered|preview|previews|check|evidence|verify|verification)\b/i,jl=/(?:do\s*not|don'?t|never|不要|不能|别|勿|禁止|不准|不得)[^.。;;\n]{0,14}(?:create|write|make|produce|generate|生成|创建|写入|写出|建立|新建)/i;function Y(e){return e.trim().replace(/[),.;:\uFF0C\u3002\uFF1B\u3001]+$/u,"").replace(/\\/g,"/").toLowerCase()}function vs(e){return e.trim().replace(/[),.;:\uFF0C\u3002\uFF1B\u3001]+$/u,"").replace(/\\/g,"/").replace(/\/+$/u,"")}function Cs(e){return/\.[A-Za-z0-9]{1,12}$/u.test(e.replace(/[),.;:\uFF0C\u3002\uFF1B\u3001]+$/u,""))}function ks(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+${Es(n)}\\b`,"i").test(s)}function Qn(e){return e.replace(/https?:\/\/\S+/gu," ")}function Pt(e){let t=new Set,n=[],o=r=>{let s=r.replace(/[),.;:\uFF0C\u3002\uFF1B]+$/u,""),i=Y(s);t.has(i)||(t.add(i),n.push(s))};for(let r of e){if(r.role!=="user"||typeof r.content!="string")continue;let s=Qn(r.content);for(let i of s.matchAll(_s)){let a=i[0],c=(i.index??0)+a.length;if(s[c]==="/"||s[c]==="\\")continue;o(a);let f=a.replace(/\\/g,"/"),g=f.lastIndexOf("/");if(g>=0){let y=f.slice(0,g+1);Ts.lastIndex=c;let k;for(;(k=Ts.exec(s))!==null;)o(`${y}${k[1]}`)}}}for(let r of e){if(r.role!=="user"||typeof r.content!="string")continue;let s=Qn(r.content);if(!$l.test(s))continue;let i=Array.from(s.matchAll(Ll)).map(c=>vs(c[1]??"")).filter(c=>c&&!Cs(c));if(i.length===0)continue;let a=i[i.length-1];for(let c of s.matchAll(Fl)){let f=c[1];f&&(ks(s,c.index??0,f)||o(`${a}/${f}`))}for(let c of s.matchAll(Bl)){let f=c[1];f&&(ks(s,c.index??0,f)||o(`${a}/${f}`))}for(let c of s.matchAll(Dl)){let f=c[1];f&&(Cs(f)||/(?:assets[\\/]generated|screenshots(?:[\\/]|$)|previews(?:[\\/]|$))/i.test(f)&&/\b(?:generated|bitmap|png|screenshots?|preview|previews|evidence|assets?|containing)\b/i.test(s)&&o(`${a}/${f}/*`))}Ul.test(s)&&o(`${a}/previews/*`)}return n}function Ot(e){if(e.role!=="tool")return!1;let t=typeof e.content=="string"?e.content:"";return e.is_error!==!0&&!t.startsWith("Error:")}function eo(e){let t=new Set,n=new Map,o=[];for(let r of e){let s=r,i=Array.isArray(s.tool_calls)?s.tool_calls:[];for(let a of i){let c=a,f=c.id,g=c.function;typeof f=="string"&&typeof g?.name=="string"&&n.set(f,g.name)}}for(let r of e){let s=r;if(Ot(s)){let i=s.tool_call_id;typeof i=="string"&&t.add(i),(typeof i=="string"?n.get(i):void 0)==="exec"&&typeof s.content=="string"&&o.push(s.content)}}for(let r of e){let s=r,i=Array.isArray(s.tool_calls)?s.tool_calls:[];for(let a of i){let c=a,f=c.id;if(typeof f=="string"&&t.size>0&&!t.has(f))continue;let g=c.function;if(!(typeof g?.name!="string"||typeof g.arguments!="string"))try{let y=JSON.parse(g.arguments);if(g.name==="write"||g.name==="edit"){for(let k of["path","filePath","file_path"]){let x=y[k];typeof x=="string"&&o.push(x)}continue}if(g.name==="exec"){let k=y.command;typeof k=="string"&&o.push(k)}}catch{g.name==="exec"&&o.push(g.arguments)}}}return o.join(`
|
|
27
|
+
`).replace(/\\/g,"/").toLowerCase()}function to(e){try{if(e.endsWith("/*")){let n=e.slice(0,-2);return xs(n,{withFileTypes:!0}).some(r=>{if(!r.isFile())return!1;try{return st(`${n}/${r.name}`).size>0}catch{return!1}})}let t=st(e);return t.isFile()&&t.size>0}catch{return!1}}function zl(e,t){let n=Y(t);if(!n.endsWith("/*"))return e.includes(n);let o=n.slice(0,-1);return e.includes(o)}function Hl(e){let t=new Set;for(let n of e){let o=n,r=Array.isArray(o.tool_calls)?o.tool_calls:[];for(let s of r){let i=s,a=i.id,c=i.function;typeof a=="string"&&c?.name==="agent"&&t.add(a)}}for(let n of e){let o=n,r=o.tool_call_id;if(typeof r=="string"&&t.has(r)&&Ot(o))return!0}return!1}function ql(e){let t=Ss(e);return/\b(?:exactly|only)\b[^.\n]*(?:artifacts?|files?|outputs?|deliverables?)/i.test(t)||/(?:artifacts?|files?|outputs?|deliverables?)[^.\n]*\b(?:exactly|only)\b/i.test(t)}function Gl(e){let t=vs(e),n=t.lastIndexOf("/");return n>=0?t.slice(0,n):""}function Wl(e){if(e.length===0)return"";let t=e.map(o=>Gl(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 Vl(e,t){let n=Y(e);return t.some(o=>{let r=Y(o);return r.endsWith("/*")?n.startsWith(r.slice(0,-1)):n===r})}function As(e){let t=new Set,n=new Map;for(let o of e){let r=o,s=Array.isArray(r.tool_calls)?r.tool_calls:[];for(let i of s){let a=i,c=a.id,f=a.function;if(typeof c!="string"||f?.name!=="write"&&f?.name!=="edit"||typeof f.arguments!="string")continue;let g=Nt(f.arguments);if(!g)continue;let y=Lt(g);y&&n.set(c,y)}}for(let o of e){let r=o;if(!Ot(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 Xl(e){return/\bartifact[-_\s]?index\b/i.test(e)&&(/\b(?:evidence|status|failed|partial|passed|verified)\b/i.test(e)||/\bGoal\s+\d+\b/i.test(e))}function Kl(e){return[...new Set([...e.matchAll(/\bGoal\s+\d+\b/gi)].map(t=>t[0].replace(/\s+/g," ").replace(/\bgoal\b/i,"Goal")))]}function Yl(e){let t=new Set,n=new Map;for(let o of e){let r=o,s=Array.isArray(r.tool_calls)?r.tool_calls:[];for(let i of s){let a=i,c=a.id,f=a.function;if(typeof c!="string"||f?.name!=="write"&&f?.name!=="edit"||typeof f.arguments!="string")continue;let g=Nt(f.arguments);if(!g)continue;let y=Lt(g)??"",k=Ms(g);(/\bartifact[-_\s]?index\b/i.test(y)||/\bartifact[-_\s]?index\b/i.test(k))&&n.set(c,k)}}for(let o of e){let r=o;if(!Ot(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 Zl(e){let t=Ss(e.inputMessages);if(!Xl(t))return[];let n=Yl(e.messages).at(-1);if(!n)return[];let o=[],r=Kl(t).filter(c=>!new RegExp(`\\b${Es(c)}\\b`,"i").test(n));r.length>0&&o.push({type:"missing_goal_labels",detail:`Missing requested row labels in the generated index: ${r.join(", ")}`});let s=/\b(?:failed|partial|missing|not\s+found|no\s+[^.\n|]*evidence)\b/i.test(n),i=/\b(?:all\s+checks\s+pass|confirmed\s*:\s*all|everything\s+(?:passes|passed)|fully\s+verified)\b/i.test(e.finalText);s&&i&&o.push({type:"overconfident_final",detail:"Final response claimed all checks pass while the generated index contains failed, partial, missing, or no-evidence rows."});let a=n.split(/\r?\n/u).filter(c=>/\bno\s+[^|\n]*(?:found|evidence|files?)\b/i.test(c)&&!/\b(?:not\s+verified|unverified|unknown|not\s+checked|search\s+scope|checked\s+path)\b/i.test(c));return a.length>0&&o.push({type:"unsupported_absence",detail:`Absence claims need scoped evidence or must be marked unverified: ${a.slice(0,3).join(" ; ")}`}),o}function Jl(e){let t=[],n=o=>{let r;try{r=xs(o,{withFileTypes:!0})}catch{return}for(let s of r){let i=`${o}/${s.name}`;if(s.isDirectory()){n(i);continue}if(s.isFile())try{st(i).size>0&&t.push(i)}catch{}}};try{if(!st(e).isDirectory())return[]}catch{return[]}return n(e),t}function Ql(e,t){if(!ql(e))return[];let n=Pt(e),o=n.filter(i=>!Y(i).endsWith("/*"));if(o.length<2)return[];let r=Wl(o);if(!r||r.split("/").length<3)return[];let s=Y(r);return[...new Set([...As(t),...Jl(r)])].filter(i=>Y(i).startsWith(`${s}/`)&&!Vl(i,n)&&to(i))}function ws(e,t){let n=Pt(e);if(n.length===0)return[];let o=eo(t);return n.filter(r=>!zl(o,r))}function rt(e){return no(e).fail}function ec(e){return e.replace(/[.,;:,。;:、!?]+$/u,"")}function It(e){if(!e)return!1;let t=ec(e);return/^[A-Za-z0-9_.:-]+$/u.test(t)&&/[0-9_:-]/u.test(t)}function no(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))It(s[2])&&(n=`${s[1].toUpperCase()} ${t(s[2])}`);for(let s of r.content.matchAll(/\bFAIL\s+([A-Za-z0-9_.:-]+)/gi))It(s[1])&&(o=`FAIL ${t(s[1])}`);for(let s of r.content.matchAll(/\b([A-Za-z0-9_.:-]+)\s+(DONE|PASS)\b/gi))It(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))It(s[1])&&(o=`${t(s[1])} FAIL`)}return{done:n,fail:o}}function Ss(e){for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.role==="user"&&typeof n.content=="string")return n.content}return""}function Es(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Oe(e){let t=ws(e.inputMessages,e.messages).filter(o=>!to(o));return t.length===0?void 0:`${rt(e.inputMessages)??"FAIL"} ${e.reason}. Missing required output file evidence: ${t.join(", ")}`}function Nt(e){try{let t=JSON.parse(e);return t&&typeof t=="object"&&!Array.isArray(t)?t:null}catch{return null}}function Lt(e){for(let t of["path","filePath","file_path"]){let n=e[t];if(typeof n=="string"&&n.trim())return n}}function Ms(e){for(let t of["content","newContent","replacement","text"]){let n=e[t];if(typeof n=="string")return n}return""}function Is(e){let t=e.toolCall.function.name;if(t!=="write"&&t!=="edit")return;let n=no(e.inputMessages);if(!n.done)return;let o=Nt(e.toolCall.function.arguments);if(!o)return;let r=Lt(o),s=Ms(o);if(!r||!s.includes(n.done))return;let i=Pt(e.inputMessages);if(i.length<2)return;let a=Y(r);if(!i.some(y=>Y(y)===a))return;let f=eo(e.messages),g=i.filter(y=>Y(y)!==a).filter(y=>!f.includes(Y(y)));if(g.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: ${g.join(", ")}. Create or verify the missing files first, or report the requested FAIL marker with the real reason.`}function Ie(e,t){return{role:"assistant",content:e,...t.length>0&&{thinkingBlocks:[...t]}}}function tc(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 nc(e){let t=[...e].reverse().find(n=>n.role==="tool");t&&typeof t.content=="string"&&(t.content+=`
|
|
28
28
|
|
|
29
|
-
\u26A0\uFE0F NOTE: You used shell commands but did not call the write or edit tool to create/modify the file. Shell commands may fail silently or produce incorrect results on this platform. Please use the 'write' tool directly to create the requested file with the correct content.`)}function Ie(e,t,n,o){return{reason:e,messages:[...t,n,o],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}}}function Ss(e){try{return nt(e).isFile()}catch{return!1}}function Wl(e,t){let n=new Map;for(let s of e){if(s.role!=="user"||typeof s.content!="string")continue;let i=Zn(s.content);if(El.test(i))for(let a of i.matchAll(Cs)){let c=a[0].replace(/[),.;:,。;]+$/u,""),f=K(c);f&&n.set(f,c)}}if(n.size===0)return[];let o=Jn(t),r=[];for(let[s,i]of n)(o.includes(s)||Ss(i))&&r.push(s);return r}var Vl="File not found:",bs=/\b(?:create|write|make|generate|produce|save|output|deliver|initialize|init|ensure|touch|scaffold|build|set\s+up)\b|生成|创建|写入|写出|新建|建立|保存|输出|交付|初始化|确保/i,Xl=/\b(?:if|when|unless)\b[^.。;;\n]{0,40}(?:missing|not\s+exist|does\s*n['o]?t\s+exist|absent|no\s+such)|(?:如果|若|要是|倘若)[^.。;;\n]{0,24}(?:不存在|没有|缺失|不在|未创建)/i;function Kl(e,t){let n=t.slice(t.lastIndexOf("/")+1),o=/[.。;;!?!?\n]/u;for(let r of e){if(r.role!=="user"||typeof r.content!="string")continue;let s=r.content.replace(/\\/g,"/").toLowerCase(),i=n.length>3&&n!==t?[t,n]:[t];for(let a of i){let c=0;for(;;){let f=s.indexOf(a,c);if(f===-1)break;c=f+1;let h=f;for(;h>0&&!o.test(s[h-1]);)h--;let y=f+a.length;for(;y<s.length&&!o.test(s[y]);)y++;let C=r.content.slice(h,y);if(bs.test(C))return!0}}}for(let r of e){if(r.role!=="user"||typeof r.content!="string")continue;let s=r.content.replace(/\\/g,"/").toLowerCase();if((s.includes(t)||n.length>3&&n!==t&&s.includes(n))&&bs.test(r.content)&&Xl.test(r.content))return!0}return!1}function Yl(e){let t=new Map;for(let o of e){let r=o,s=Array.isArray(r.tool_calls)?r.tool_calls:[];for(let i of s){let a=i,c=a.id,f=a.function;if(typeof c!="string"||f?.name!=="read"||typeof f.arguments!="string")continue;let h=Pt(f.arguments),y=h?Ot(h):void 0;y&&t.set(c,y)}}let n=new Map;for(let o of e){let r=o;if(r.role!=="tool")continue;let s=r.tool_call_id;if(typeof s!="string")continue;let i=t.get(s);if(!i)continue;let a=typeof r.content=="string"?r.content:"";(r.is_error===!0||a.startsWith("Error:"))&&a.includes(Vl)&&n.set(K(i),i)}return n}function Zl(e,t){let n=Yl(t);if(n.size===0)return[];let o=new Set(Rs(t).map(K)),r=[];for(let[s,i]of n)Kl(e,s)||(o.has(s)||Ss(i))&&r.push(s);return r}function to(e){let t=e.inputMessages.find(x=>x.role==="user"),n=typeof t?.content=="string"?t.content:"",o=Rl.test(n)||xl.test(n)&&Et(e.inputMessages).length>0,r=e.distinctToolNames.has("write")||e.distinctToolNames.has("edit"),s=eo(e.inputMessages),i=Wl(e.inputMessages,e.messages);if(i.length>0){e.log.info(`forbidden-file-creation guard: agent wrote ${i.length} file(s) the user forbade creating`);let x=tt(e.inputMessages),v={role:"user",content:`You created a file the request explicitly forbade creating: ${i.join(", ")}. That is a constraint violation, not success \u2014 do NOT claim "completed" or "handled". Delete the file you wrongly created, then report ${x??"FAILED"} with the real reason: the task could not be done without violating the stated constraint. Do not fabricate a successful outcome.`};return Ie("forbidden_file_creation",e.messages,Ee(e.finalText,e.thinkingBlocks),v)}let a=Zl(e.inputMessages,e.messages),c=s.fail!==void 0&&e.finalText.includes(s.fail);if(a.length>0&&!c){e.log.info(`self-created-read-target guard: agent created ${a.length} file(s) it had read as not-found`);let x=tt(e.inputMessages),v={role:"user",content:"You were asked to read "+a.join(", ")+`, but your read showed the file did not exist; you then created it yourself. Manufacturing an input you were told to read is not success \u2014 do NOT claim "completed" or "handled". Delete the file you wrongly created, then report ${x??"FAILED"} with the real reason: the file does not exist and the task cannot be done without fabricating it.`};return Ie("self_created_read_target",e.messages,Ee(e.finalText,e.thinkingBlocks),v)}let f=Pl(e.messages),h=xs(e.inputMessages,e.messages).filter(x=>!(f&&Qn(x)));if(h.length>0&&e.totalToolCallCount>0){if(s.fail!==void 0&&e.finalText.includes(s.fail))return null;e.log.info(`explicit required file verification: ${h.length} file(s) missing`);let x=tt(e.inputMessages),v={role:"user",content:`Before completing, verify that every explicitly requested output file exists and is non-empty. Missing required output file evidence: ${h.join(", ")}. Create the missing files now, or if you cannot complete them, respond with ${x??"FAIL"} and the real reason. Do not claim completion until the missing files are handled.`};return Ie("explicit_required_file_verification",e.messages,Ee(e.finalText,e.thinkingBlocks),v)}let y=ql(e.inputMessages,e.messages);if(y.length>0&&e.totalToolCallCount>0){if(s.fail!==void 0&&e.finalText.includes(s.fail))return null;e.log.info(`explicit extra file verification: ${y.length} unexpected file(s)`);let x=tt(e.inputMessages),v={role:"user",content:`The latest request asked for exactly the listed output artifacts, but extra files were produced under the output root: ${y.join(", ")}. Remove the extra files now, move scratch work outside the deliverable directory, or if you cannot make the output exact, respond with ${x??"FAIL"} and the real reason. Do not claim completion while extra deliverables remain.`};return Ie("explicit_extra_file_verification",e.messages,Ee(e.finalText,e.thinkingBlocks),v)}let C=Ul({inputMessages:e.inputMessages,messages:e.messages,finalText:e.finalText});if(C.length>0&&e.totalToolCallCount>0){if(s.fail!==void 0&&e.finalText.includes(s.fail))return null;e.log.info(`artifact index evidence verification: ${C.length} issue(s)`);let x={role:"user",content:"Before completing, correct the artifact index against the actual evidence scope. "+C.map(v=>v.detail).join(" ")+" Use the exact requested Goal row labels, cite concrete evidence names/paths for status claims, and mark a row as not verified/unknown instead of claiming exhaustive absence without scoped evidence. Do not claim all checks pass while any row is failed, partial, missing, or unverified. After correcting and verifying the file, finish with the final status contract."};return Ie("artifact_index_evidence_verification",e.messages,Ee(e.finalText,e.thinkingBlocks),x)}if(e.stopHookActive)return null;if(o&&!r){e.log.info("AP1 action-verification: user requested file action but no write/edit tool was called, injecting nudge"),e.totalToolCallCount>0&&Gl(e.messages);let x={role:"user",content:e.totalToolCallCount===0?"You described what to do but did not actually call any tool to write or edit a file. Please use the write or edit tool now to perform the requested action. Do not just describe the changes - actually make them.":"You used shell commands but did not call the write or edit tool to create/modify the file. Shell commands may fail on this platform. Please use the write tool directly to create the requested file with the correct content."};return Ie("file_action_verification",e.messages,Ee(e.finalText,e.thinkingBlocks),x)}if(e.totalToolCallCount>=3&&e.distinctToolNames.has("write")&&e.messages.filter(Hl).length>=3){e.log.info("AP3 verification nudge: 3+ files created, injecting completeness check");let v={role:"user",content:"You created multiple files. Before completing, verify: (1) All imports between your files resolve to real exports. (2) No TODO, placeholder, or 'not implemented' stubs remain. (3) Functions that are imported are actually called, not just declared. If everything is correct, confirm completion. If not, fix the issues now."};return Ie("multi_file_skeleton_verification",e.messages,Ee(e.finalText,e.thinkingBlocks),v)}return null}function Jl(e,t){return{role:"assistant",content:e,...t.length>0&&{thinkingBlocks:[...t]}}}async function Ms(e){if(!e.hooks)return null;let t=await e.hooks.invoke("stop",{sessionId:e.sessionId,reason:"completed"});if(t.action==="prevent")return e.log.info(`stop hook prevented continuation: ${t.reason??"no reason"}`),{action:"end",content:e.finalText};if(t.action==="abort"){let n=t.reason??"Stop hook requested continuation";e.log.info(`stop hook blocking: ${n}`);let o={role:"user",content:n};return{action:"continue",messages:[...e.messages,Jl(e.finalText,e.thinkingBlocks),o],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}}}return null}var Ql=5;function ec(e){return e.inputTokens+e.outputTokens+(e.reasoningTokens??0)}function tc(e,t){return{role:"assistant",content:e,...t.length>0&&{thinkingBlocks:[...t]}}}function Es(e){if(!e.tokenBudget||e.tokenBudget<=0||e.budgetContinuationCount>=Ql)return null;let t=ec(e.totalUsage),n=t/e.tokenBudget*100,o=t-e.lastBudgetGlobalTokens;if(e.budgetContinuationCount>=yr&&o<Tn&&e.lastBudgetDeltaTokens<Tn)return e.log.info(`token budget early stop: diminishing returns at ${Math.round(n)}% (delta=${o})`),null;if(n>=90)return null;let s=e.budgetContinuationCount+1,i={role:"user",content:e.getBudgetContinuationMessage(n,t,e.tokenBudget)};return e.log.info(`token budget continuation #${s}: ${Math.round(n)}% used`),{messages:[...e.messages,tc(e.finalText,e.thinkingBlocks),i],budgetContinuationCount:s,lastBudgetDeltaTokens:o,lastBudgetGlobalTokens:t,recoveryDetail:`${Math.round(n)}% used (#${s})`,transition:{reason:"token_budget_continuation"}}}function no(e){if(e.totalToolCallCount<=0)return null;let t={ok:!0,toolCallCount:e.totalToolCallCount,distinctToolCount:e.distinctToolNames.size,multiStep:e.totalToolCallCount>=2,hasSubAgent:!1,feedback:null,existingSkillName:null};return Cn(t,{tools:[...e.distinctToolNames],projectRoot:e.projectRoot})}function Is(e){let t=nc(e.text);if(!t.trim())return null;let n=[...new Set(e.enabledToolNames.filter(o=>o.trim()))].sort((o,r)=>r.length-o.length);for(let o of n)if(oc(t,o)||rc(t,o))return{toolName:o};return null}function nc(e){return e.replace(/```[\s\S]*?```/g,"")}function oc(e,t){let n=Ps(t);return new RegExp(`<\\s*${n}\\b[\\s\\S]*?<\\s*\\/\\s*${n}\\s*>`,"i").test(e)}function rc(e,t){let n=Ps(t);return new RegExp(`\\b(?:call|use|invoke|run)\\s+${n}\\s*\\(|\\b${n}\\s*\\(`,"i").test(e)}function Ps(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var ot="*";function Os(e,t){let n=[],o=[];for(let r of e){let s=Bs(r.function.name,r.function.arguments),i=Ds(r.function.name,ot),a=Math.max(t.get(s)??0,t.get(i)??0);a>=Ct?o.push({call:r,failCount:a,error:`Tool "${r.function.name}" has failed ${a} times this turn for this target. The target likely does not exist. Stop trying variations of the same target and switch to a verified target or report the issue to the user.`}):n.push(r)}return{allowed:n,blocked:o}}function Ns(){return{role:"user",content:"Tool calls were blocked because the tool has failed too many times with different arguments. The resource you are looking for does not exist. Stop trying variations and tell the user what happened."}}function Ls(e){if(e.ok&&!e.softEmpty)return;let t=Bs(e.toolName,e.toolArguments),n=e.toolFailureCounts.get(t)??0;e.toolFailureCounts.set(t,n+1)}function Fs(e){let t=[];for(let[n,o]of e.toolFailureCounts)if(o>=Ct&&(e.snapshot.get(n)??0)<Ct){let{toolName:r,target:s}=ac(n);t.push({role:"user",content:`Tool "${r}" has now failed/returned empty results ${o} times for target "${s}". That target clearly does not exist or is not useful. Do NOT retry variations of the same target. Report the result to the user immediately.`})}return t}function Bs(e,t){return Ds(e,sc(e,t))}function sc(e,t){let n=ic(t);return e==="read"||e==="write"||e==="edit"||e==="patch"?oo(n?.path??n?.file_path??n?.filePath):e==="search"?oo([n?.mode,n?.path,n?.fileGlob,n?.pattern].filter(Boolean).join("|")):e==="exec"?oo(n?.command):ot}function ic(e){if(e)try{let t=JSON.parse(e);return t&&typeof t=="object"&&!Array.isArray(t)?t:void 0}catch{return}}function oo(e){return typeof e=="string"&&e.trim()?e.trim().replaceAll("\\","/").toLowerCase():ot}function Ds(e,t){return`${e}::${t}`}function ac(e){let t=e.indexOf("::");return t<0?{toolName:e,target:ot}:{toolName:e.slice(0,t),target:e.slice(t+2)||ot}}var lc=new Set(["find","grep","rg","ag","ack","locate","which","whereis"]),cc=new Set(["cat","head","tail","less","more","wc","stat","file","sed","strings","jq","awk","cut","sort","uniq","tr"]),uc=new Set(["ls","tree","du","dir","gci","get-childitem"]),dc=new Set(["grep","rg","ag","ack","find"]);var fc=new Set(["mv","cp","rm","mkdir","rmdir","chmod","chown","chgrp","touch","ln","cd","export","unset","wait"]);function pc(e){let n=e.replace(/\\\n/g," ").trim().split(/[|;&]/).shift()?.trim()??"";if(!n)return null;let o=n.split(/\s+/),r=0;for(;r<o.length&&/^[A-Za-z_]\w*=/.test(o[r]);)r++;let s=/^(?:timeout|time|nice|nohup|stdbuf|command|builtin|exec)$/;for(;r<o.length;){let f=o[r];if(s.test(f)){for(r++;r<o.length&&/^[-+]/.test(o[r]);)r++;r<o.length&&/^\d+(?:\.\d+)?[smhd]?$/.test(o[r])&&r++;continue}break}if(r>=o.length)return null;let i=o[r],a=i.lastIndexOf("/");return(a>=0?i.slice(a+1):i).toLowerCase()}function mc(e){return/(?:^|[;&|])\s*(?:cd|pushd|popd)\b/.test(e)}function $s(e){let t=pc(e),n=t!==null&&lc.has(t),o=t!==null&&cc.has(t),r=t!==null&&uc.has(t),s=t!==null&&fc.has(t),i=/(?:[^2]>|^>|\|>)/.test(e),a=mc(e),c=(n||o||r)&&!i&&!a;return{firstCommand:t,isSearch:n,isRead:o,isList:r,isSilent:s,isConcurrencySafe:c,isReadOnly:c}}function Us(e){return e.isRead?!0:e.firstCommand!==null&&dc.has(e.firstCommand)}function js(e){return e.isRead?"Command blocked: read local file contents with the read tool, not exec (cat/head/tail/sed/etc.). Reserve exec for system/build/test commands.":'Command blocked: search local file contents with the search tool (mode "content"), not exec (grep/find/rg/etc.). Reserve exec for system/build/test commands.'}function yc(e,t){if(e.length!==1||e[0]?.function.name!=="stt")return!1;let n=[...t].reverse().find(i=>i.role==="user");if(!n)return!1;let o=Array.isArray(n.audioUrls)&&n.audioUrls.some(i=>typeof i=="string"&&i.trim()),r=typeof n.content=="string"?n.content:"",s=/\b(?:stt|speech[-\s]?to[-\s]?text|transcribe|transcription|audio[-\s]?to[-\s]?text)\b|转写|转录|语音转文字|音频转文字|听写/i.test(r);return o&&s}function bc(e,t){let n=Tc(t);if(!n)return null;let o=Cc(n);if(!o)return null;let r=[...e].reverse().find(a=>a.role==="user"),s=typeof r?.content=="string"?r.content:"",i=/\bAUDIO_STT_RESULT\s+([^\s<]+)\s+<transcription\b/i.exec(s);return i?.[1]?`AUDIO_STT_RESULT ${i[1]} ${o}`:o}function Tc(e){let t=[e.details?.transcription,e.details?.text,e.details?.preview];for(let o of t)if(typeof o=="string"&&o.trim())return o.trim();let n=e.message?.content;return typeof n=="string"?n.trim():""}function Cc(e){return e.toLocaleLowerCase().replace(/[^\p{L}\p{N}\s]+/gu," ").replace(/\s+/g," ").trim()}var Qs=/\b(?:only\s+(?:answer|return|output)|answer\s+only|return\s+only|output\s+only)\b[\s\S]{0,80}\b(?:token|contents?|content|value|result)\b|(?:\u53ea|\u4ec5|\u50c5)(?:\u56de\u7b54|\u56de\u590d|\u56de\u8986|\u8f93\u51fa|\u8fd4\u56de)[^\n\u3002\uff1b;]{0,40}(?:token|\u5185\u5bb9|\u503c|\u7ed3\u679c)/i,kc=/(?:JSON|json)[\s\S]{0,120}(?:top[- ]level|\u9876\u5c42)[\s\S]{0,80}\b([A-Za-z_$][\w$.-]*)\b[\s\S]{0,40}(?:field|key|property|\u5b57\u6bb5|\u5c5e\u6027)/i,Rc=/(?:\bonly\s+(?:answer|return|output)\b|(?:\u53ea|\u4ec5|\u50c5)(?:\u56de\u7b54|\u56de\u590d|\u56de\u8986|\u8f93\u51fa|\u8fd4\u56de))\s*[::]\s*([A-Za-z0-9_.:-]+:\s*)<[^>\n]+>/i,xc=/(?:memory\s+graph|MCP\s+memory\s+graph|\u8bb0\u5fc6\u56fe\u8c31|\u5f53\u524d\u56fe\u8c31)[\s\S]{0,120}(?:entity|\u5b9e\u4f53)\s+([A-Za-z0-9_.:-]+)/i,_c=/\b([A-Z0-9_]*MCP_GRAPH_CHECK[A-Z0-9_]*_20260626)\b/;function ei(e){for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.role==="user"&&typeof n.content=="string")return n.content}return""}function ti(e,t){let n=new Map;for(let o of e){if(o.role!=="assistant")continue;let r=o.tool_calls;if(Array.isArray(r))for(let s of r){if(!s||typeof s!="object")continue;let i=s,a=typeof i.id=="string"?i.id:"",c=i.function&&typeof i.function=="object"?i.function:void 0,f=typeof c?.name=="string"?c.name:"";a&&f&&n.set(a,f)}}for(let o=e.length-1;o>=0;o--){let r=e[o];if(r?.role!=="tool")continue;let s=typeof r.tool_call_id=="string"?r.tool_call_id:"";if(n.get(s)!==t)continue;let i=typeof r.content=="string"?r.content.trim():"";if(!(!i||i.startsWith("Error: ")))return i}return null}function vc(e,t){let n=ei(e),o=ti(t,"read");if(!o||o.length>4e3)return null;let r=Ac(n,o);return r||(Qs.test(n)?o:null)}function Ac(e,t){let n=kc.exec(e)?.[1];if(!n)return null;let o=Rc.exec(e)?.[1]??"";if(!o&&!Qs.test(e))return null;let r;try{r=JSON.parse(t)}catch{return null}if(!r||typeof r!="object"||Array.isArray(r))return null;let s=r;if(!Object.hasOwn(s,n))return null;let i=s[n],a=typeof i=="string"?i:JSON.stringify(i);return typeof a!="string"?null:`${o}${a}`}function wc(e,t){let n=ei(e),o=xc.exec(n)?.[1],r=_c.exec(n)?.[1];if(!o||!r)return null;let s=ti(t,"mcp__memory__read_graph");if(!s)return null;let i=s.toLowerCase().includes(o.toLowerCase());return`${r}: ${i?"yes":"no"}`}function k(e){return[...new Set(e.map(t=>t.function.name))].sort()}function je(e){return[...e].sort((t,n)=>t.function.name.localeCompare(n.function.name))}function Nt(e){let t=new Set,n=[];for(let o of e){let r=`${o.name}\0${o.reason}`;t.has(r)||(t.add(r),n.push(o))}return n.sort((o,r)=>`${o.name}:${o.reason}`.localeCompare(`${r.name}:${r.reason}`))}function Sc(e,t,n,o,r){let s=r.filter(i=>i.name===e).sort((i,a)=>qs(i.reason)-qs(a.reason))[0];return t.includes(e)?s?`${e}=policy-filtered:${s.reason}`:n.includes(e)?o.includes(e)?`${e}=called`:`${e}=enabled-not-used`:`${e}=policy-filtered:not-enabled`:`${e}=not-exposed`}function qs(e){return e==="invalid-arguments"?0:e==="blocked-by-policy"||e.startsWith("policy-suppressed:")?1:e==="confirmation-timeout"?2:e==="dedicated-tool-required"?3:e==="read-only-context-pack"?4:e==="not-offered"?5:e==="read-cycle-policy"?6:e==="identical-repeat-policy"?7:e==="variant-failure-policy"?8:10}function Mc(e){let t=typeof e.blockReason=="string"?e.blockReason:void 0;if(e.blocked&&/confirmation timed out/i.test(t??""))return"confirmation-timeout";if(e.blocked)return"blocked-by-policy";let n=typeof e.details?.error=="string"?e.details.error:void 0;if(n==="dedicated_tool_required")return"dedicated-tool-required";if(n==="existing_file_update_tool_required")return"existing-file-update-tool-required";if(n==="invalid_arguments")return"invalid-arguments";if(n==="blocked_global_process_kill")return"global-process-kill-blocked";if(n==="blocked_by_guard")return"blocked-by-policy"}function zs(e){let t=new Set(e.map(n=>n.function.name));return t.has("read")||t.has("search")||t.has("write")||t.has("edit")||t.has("patch")}function Te(e,t){return t.size===0?[...e]:e.filter(n=>!t.has(n.function.name))}var Ec=new Set(["edit","patch","read"]);function Hs(e,t){let n=e.filter(o=>Ec.has(o.function.name)&&!t.has(o.function.name));return n.length>0?je(n):e.filter(o=>o.function.name!=="write"&&!t.has(o.function.name))}function ro(e,t){let n=new Set(t);return e.filter(o=>!n.has(o))}function Ic(e){if(!e)return;let t=e.trim();return(t.match(/Last error:\s*(.+?)\.\s*Do not retry\./s)?.[1]?.trim()??t).slice(0,600).trim()||void 0}function Gs(e){let n=pe(e)?.command;return typeof n=="string"&&n.trim()?n:void 0}var Bt=5174;function Ws(e,t){let n=String(t);return[new RegExp(`(?:^|\\s)--port(?:=|\\s+)${n}(?:\\s|$)`),new RegExp(`(?:^|\\s)-p(?:=|\\s+)${n}(?:\\s|$)`),new RegExp(`(?:localhost|127\\.0\\.0\\.1|0\\.0\\.0\\.0|\\[?::1\\]?):${n}\\b`,"i")].some(r=>r.test(e))}function Pc(e){return/\b(vite|npx\s+vite|pnpm\s+(?:run\s+)?dev|npm\s+(?:run\s+)?dev|yarn\s+(?:run\s+)?dev)\b/i.test(e)}function ni(e){return/(?:^|\s)--strictPort(?:\s|$)/.test(e)}function Oc(e){if(ni(e))return e;let t=/\s+(?:\d?>&\d|\d?>\s*\S+|>\s*\S+|<\s*\S+).*$/.exec(e);return!t||t.index===void 0?`${e.trim()} --strictPort`:`${e.slice(0,t.index).trim()} --strictPort${e.slice(t.index)}`}function Vs(e,t){let n=pe(e)??{};return JSON.stringify({...n,command:t})}function Nc(e){let t=e.replace(/^(?:\s*sleep\s+\d+(?:\.\d+)?\s*(?:&&|;)\s*)+/i,"").trim();return t&&t!==e.trim()?t:null}function Lc(e){return Ws(e,Bt)?{action:"block",error:"Command blocked: port 5174 is reserved for the Xiaozhi Claw frontend. Start generated apps on an explicit non-5174 port and include --strictPort when using Vite."}:Pc(e)&&Ws(e,Bt-1)&&!ni(e)?{action:"rewrite",command:Oc(e)}:null}function Dt(e){let t=[];for(let n of e.devServerUrls)if(!(!/^https?:\/\/(?:localhost|127\.0\.0\.1):\d+\b/i.test(n)||new RegExp(`:${Bt}\\b`).test(n)))try{let o=new URL(n);if(/^\/api(?:\/|$)/i.test(o.pathname))continue;let r=`${o.protocol}//${o.host}${o.pathname==="/"?"":o.pathname}`;t.includes(r)||t.push(r)}catch{continue}return t}function Xs(e){let t=Dt(e);return`Browser-visible acceptance is still missing. Do not finish from source inspection or web_fetch output. Use exec to run real browser automation (Playwright or an equivalent browser runner) against ${t.length>0?t.join(", "):"the generated localhost dev server URL"}. Do not run a plain \`node verify.js\` script that imports \`@playwright/test\` unless that package is installed in the target project. Prefer one of these reliable forms: (a) if \`node -e "require.resolve('playwright')"\` succeeds, run a plain Node script importing \`chromium\` from \`playwright\`; or (b) write a Playwright spec and run it with \`npx -y playwright@latest test <spec-file>\` instead of \`node <spec-file>\`. If a localhost URL responds, reuse that running service for browser verification; do not treat a later EADDRINUSE restart attempt as proof that the app is unavailable. Only switch to a new explicit non-5174 port when the observed localhost URL is unreachable or serves the wrong app. Verify rendered visible UI, app-specific routes/screens, and requested interactions; default HTML fetches, bundled JS inspection, and static source review do not count as browser evidence. After the browser automation succeeds, report the exact visible assertions from the tool result.`}function Fc(e){let t=e.buildFailureEvidence[0];return"The test/build you ran is still FAILING, so the task is not complete. "+(t?`Last failing output:
|
|
29
|
+
\u26A0\uFE0F NOTE: You used shell commands but did not call the write or edit tool to create/modify the file. Shell commands may fail silently or produce incorrect results on this platform. Please use the 'write' tool directly to create the requested file with the correct content.`)}function Pe(e,t,n,o){return{reason:e,messages:[...t,n,o],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}}}function Ps(e){try{return st(e).isFile()}catch{return!1}}function oc(e,t){let n=new Map;for(let s of e){if(s.role!=="user"||typeof s.content!="string")continue;let i=Qn(s.content);if(jl.test(i))for(let a of i.matchAll(_s)){let c=a[0].replace(/[),.;:,。;]+$/u,""),f=Y(c);f&&n.set(f,c)}}if(n.size===0)return[];let o=eo(t),r=[];for(let[s,i]of n)(o.includes(s)||Ps(i))&&r.push(s);return r}var rc="File not found:",Rs=/\b(?:create|write|make|generate|produce|save|output|deliver|initialize|init|ensure|touch|scaffold|build|set\s+up)\b|生成|创建|写入|写出|新建|建立|保存|输出|交付|初始化|确保/i,sc=/\b(?:if|when|unless)\b[^.。;;\n]{0,40}(?:missing|not\s+exist|does\s*n['o]?t\s+exist|absent|no\s+such)|(?:如果|若|要是|倘若)[^.。;;\n]{0,24}(?:不存在|没有|缺失|不在|未创建)/i;function ic(e,t){let n=t.slice(t.lastIndexOf("/")+1),o=/[.。;;!?!?\n]/u;for(let r of e){if(r.role!=="user"||typeof r.content!="string")continue;let s=r.content.replace(/\\/g,"/").toLowerCase(),i=n.length>3&&n!==t?[t,n]:[t];for(let a of i){let c=0;for(;;){let f=s.indexOf(a,c);if(f===-1)break;c=f+1;let g=f;for(;g>0&&!o.test(s[g-1]);)g--;let y=f+a.length;for(;y<s.length&&!o.test(s[y]);)y++;let k=r.content.slice(g,y);if(Rs.test(k))return!0}}}for(let r of e){if(r.role!=="user"||typeof r.content!="string")continue;let s=r.content.replace(/\\/g,"/").toLowerCase();if((s.includes(t)||n.length>3&&n!==t&&s.includes(n))&&Rs.test(r.content)&&sc.test(r.content))return!0}return!1}function ac(e){let t=new Map;for(let o of e){let r=o,s=Array.isArray(r.tool_calls)?r.tool_calls:[];for(let i of s){let a=i,c=a.id,f=a.function;if(typeof c!="string"||f?.name!=="read"||typeof f.arguments!="string")continue;let g=Nt(f.arguments),y=g?Lt(g):void 0;y&&t.set(c,y)}}let n=new Map;for(let o of e){let r=o;if(r.role!=="tool")continue;let s=r.tool_call_id;if(typeof s!="string")continue;let i=t.get(s);if(!i)continue;let a=typeof r.content=="string"?r.content:"";(r.is_error===!0||a.startsWith("Error:"))&&a.includes(rc)&&n.set(Y(i),i)}return n}function lc(e,t){let n=ac(t);if(n.size===0)return[];let o=new Set(As(t).map(Y)),r=[];for(let[s,i]of n)ic(e,s)||(o.has(s)||Ps(i))&&r.push(s);return r}function oo(e){let t=e.inputMessages.find(x=>x.role==="user"),n=typeof t?.content=="string"?t.content:"",o=Ol.test(n)||Nl.test(n)&&Pt(e.inputMessages).length>0,r=e.distinctToolNames.has("write")||e.distinctToolNames.has("edit"),s=no(e.inputMessages),i=oc(e.inputMessages,e.messages);if(i.length>0){e.log.info(`forbidden-file-creation guard: agent wrote ${i.length} file(s) the user forbade creating`);let x=rt(e.inputMessages),_={role:"user",content:`You created a file the request explicitly forbade creating: ${i.join(", ")}. That is a constraint violation, not success \u2014 do NOT claim "completed" or "handled". Delete the file you wrongly created, then report ${x??"FAILED"} with the real reason: the task could not be done without violating the stated constraint. Do not fabricate a successful outcome.`};return Pe("forbidden_file_creation",e.messages,Ie(e.finalText,e.thinkingBlocks),_)}let a=lc(e.inputMessages,e.messages),c=s.fail!==void 0&&e.finalText.includes(s.fail);if(a.length>0&&!c){e.log.info(`self-created-read-target guard: agent created ${a.length} file(s) it had read as not-found`);let x=rt(e.inputMessages),_={role:"user",content:"You were asked to read "+a.join(", ")+`, but your read showed the file did not exist; you then created it yourself. Manufacturing an input you were told to read is not success \u2014 do NOT claim "completed" or "handled". Delete the file you wrongly created, then report ${x??"FAILED"} with the real reason: the file does not exist and the task cannot be done without fabricating it.`};return Pe("self_created_read_target",e.messages,Ie(e.finalText,e.thinkingBlocks),_)}let f=Hl(e.messages),g=ws(e.inputMessages,e.messages).filter(x=>!(f&&to(x)));if(g.length>0&&e.totalToolCallCount>0){if(s.fail!==void 0&&e.finalText.includes(s.fail))return null;e.log.info(`explicit required file verification: ${g.length} file(s) missing`);let x=rt(e.inputMessages),_={role:"user",content:`Before completing, verify that every explicitly requested output file exists and is non-empty. Missing required output file evidence: ${g.join(", ")}. Create the missing files now, or if you cannot complete them, respond with ${x??"FAIL"} and the real reason. Do not claim completion until the missing files are handled.`};return Pe("explicit_required_file_verification",e.messages,Ie(e.finalText,e.thinkingBlocks),_)}let y=Ql(e.inputMessages,e.messages);if(y.length>0&&e.totalToolCallCount>0){if(s.fail!==void 0&&e.finalText.includes(s.fail))return null;e.log.info(`explicit extra file verification: ${y.length} unexpected file(s)`);let x=rt(e.inputMessages),_={role:"user",content:`The latest request asked for exactly the listed output artifacts, but extra files were produced under the output root: ${y.join(", ")}. Remove the extra files now, move scratch work outside the deliverable directory, or if you cannot make the output exact, respond with ${x??"FAIL"} and the real reason. Do not claim completion while extra deliverables remain.`};return Pe("explicit_extra_file_verification",e.messages,Ie(e.finalText,e.thinkingBlocks),_)}let k=Zl({inputMessages:e.inputMessages,messages:e.messages,finalText:e.finalText});if(k.length>0&&e.totalToolCallCount>0){if(s.fail!==void 0&&e.finalText.includes(s.fail))return null;e.log.info(`artifact index evidence verification: ${k.length} issue(s)`);let x={role:"user",content:"Before completing, correct the artifact index against the actual evidence scope. "+k.map(_=>_.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 Pe("artifact_index_evidence_verification",e.messages,Ie(e.finalText,e.thinkingBlocks),x)}if(e.stopHookActive)return null;if(o&&!r){e.log.info("AP1 action-verification: user requested file action but no write/edit tool was called, injecting nudge"),e.totalToolCallCount>0&&nc(e.messages);let x={role:"user",content:e.totalToolCallCount===0?"You described what to do but did not actually call any tool to write or edit a file. Please use the write or edit tool now to perform the requested action. Do not just describe the changes - actually make them.":"You used shell commands but did not call the write or edit tool to create/modify the file. Shell commands may fail on this platform. Please use the write tool directly to create the requested file with the correct content."};return Pe("file_action_verification",e.messages,Ie(e.finalText,e.thinkingBlocks),x)}if(e.totalToolCallCount>=3&&e.distinctToolNames.has("write")&&e.messages.filter(tc).length>=3){e.log.info("AP3 verification nudge: 3+ files created, injecting completeness check");let _={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 Pe("multi_file_skeleton_verification",e.messages,Ie(e.finalText,e.thinkingBlocks),_)}return null}function cc(e,t){return{role:"assistant",content:e,...t.length>0&&{thinkingBlocks:[...t]}}}async function Os(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,cc(e.finalText,e.thinkingBlocks),o],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}}}return null}var uc=5;function dc(e){return e.inputTokens+e.outputTokens+(e.reasoningTokens??0)}function fc(e,t){return{role:"assistant",content:e,...t.length>0&&{thinkingBlocks:[...t]}}}function Ns(e){if(!e.tokenBudget||e.tokenBudget<=0||e.budgetContinuationCount>=uc)return null;let t=dc(e.totalUsage),n=t/e.tokenBudget*100,o=t-e.lastBudgetGlobalTokens;if(e.budgetContinuationCount>=yr&&o<kn&&e.lastBudgetDeltaTokens<kn)return e.log.info(`token budget early stop: diminishing returns at ${Math.round(n)}% (delta=${o})`),null;if(n>=90)return null;let s=e.budgetContinuationCount+1,i={role:"user",content:e.getBudgetContinuationMessage(n,t,e.tokenBudget)};return e.log.info(`token budget continuation #${s}: ${Math.round(n)}% used`),{messages:[...e.messages,fc(e.finalText,e.thinkingBlocks),i],budgetContinuationCount:s,lastBudgetDeltaTokens:o,lastBudgetGlobalTokens:t,recoveryDetail:`${Math.round(n)}% used (#${s})`,transition:{reason:"token_budget_continuation"}}}function ro(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 Rn(t,{tools:[...e.distinctToolNames],projectRoot:e.projectRoot})}function Ls(e){let t=pc(e.text);if(!t.trim())return null;let n=[...new Set(e.enabledToolNames.filter(o=>o.trim()))].sort((o,r)=>r.length-o.length);for(let o of n)if(mc(t,o)||gc(t,o))return{toolName:o};return null}function pc(e){return e.replace(/```[\s\S]*?```/g,"")}function mc(e,t){let n=Fs(t);return new RegExp(`<\\s*${n}\\b[\\s\\S]*?<\\s*\\/\\s*${n}\\s*>`,"i").test(e)}function gc(e,t){let n=Fs(t);return new RegExp(`\\b(?:call|use|invoke|run)\\s+${n}\\s*\\(|\\b${n}\\s*\\(`,"i").test(e)}function Fs(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var it="*";function Bs(e,t){let n=[],o=[];for(let r of e){let s=js(r.function.name,r.function.arguments),i=zs(r.function.name,it),a=Math.max(t.get(s)??0,t.get(i)??0);a>=Rt?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 Ds(){return{role:"user",content:"Tool calls were blocked because the tool has failed too many times with different arguments. The resource you are looking for does not exist. Stop trying variations and tell the user what happened."}}function $s(e){if(e.ok&&!e.softEmpty)return;let t=js(e.toolName,e.toolArguments),n=e.toolFailureCounts.get(t)??0;e.toolFailureCounts.set(t,n+1)}function Us(e){let t=[];for(let[n,o]of e.toolFailureCounts)if(o>=Rt&&(e.snapshot.get(n)??0)<Rt){let{toolName:r,target:s}=bc(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 js(e,t){return zs(e,hc(e,t))}function hc(e,t){let n=yc(t);if(e==="read"||e==="write"||e==="edit"||e==="patch")return so(n?.path??n?.file_path??n?.filePath);if(e==="search")return so([n?.mode,n?.path,n?.fileGlob,n?.pattern].filter(Boolean).join("|"));if(e==="exec"){let o=typeof n?.command=="string"?n.command:void 0;return so(o?ot(o):void 0)}return it}function yc(e){if(e)try{let t=JSON.parse(e);return t&&typeof t=="object"&&!Array.isArray(t)?t:void 0}catch{return}}function so(e){return typeof e=="string"&&e.trim()?e.trim().replaceAll("\\","/").toLowerCase():it}function zs(e,t){return`${e}::${t}`}function bc(e){let t=e.indexOf("::");return t<0?{toolName:e,target:it}:{toolName:e.slice(0,t),target:e.slice(t+2)||it}}var Tc=new Set(["find","grep","rg","ag","ack","locate","which","whereis"]),Cc=new Set(["cat","head","tail","less","more","wc","stat","file","sed","strings","jq","awk","cut","sort","uniq","tr"]),kc=new Set(["ls","tree","du","dir","gci","get-childitem"]),Rc=new Set(["grep","rg","ag","ack","find"]);var xc=new Set(["mv","cp","rm","mkdir","rmdir","chmod","chown","chgrp","touch","ln","cd","export","unset","wait"]);function _c(e){let n=e.replace(/\\\n/g," ").trim().split(/[|;&]/).shift()?.trim()??"";if(!n)return null;let o=n.split(/\s+/),r=0;for(;r<o.length&&/^[A-Za-z_]\w*=/.test(o[r]);)r++;let s=/^(?:timeout|time|nice|nohup|stdbuf|command|builtin|exec)$/;for(;r<o.length;){let f=o[r];if(s.test(f)){for(r++;r<o.length&&/^[-+]/.test(o[r]);)r++;r<o.length&&/^\d+(?:\.\d+)?[smhd]?$/.test(o[r])&&r++;continue}break}if(r>=o.length)return null;let i=o[r],a=i.lastIndexOf("/");return(a>=0?i.slice(a+1):i).toLowerCase()}function vc(e){return/(?:^|[;&|])\s*(?:cd|pushd|popd)\b/.test(e)}function Hs(e){let t=_c(e),n=t!==null&&Tc.has(t),o=t!==null&&Cc.has(t),r=t!==null&&kc.has(t),s=t!==null&&xc.has(t),i=/(?:[^2]>|^>|\|>)/.test(e),a=vc(e),c=(n||o||r)&&!i&&!a;return{firstCommand:t,isSearch:n,isRead:o,isList:r,isSilent:s,isConcurrencySafe:c,isReadOnly:c}}function qs(e){return e.isRead?!0:e.firstCommand!==null&&Rc.has(e.firstCommand)}function Gs(e){return e.isRead?"Command blocked: read local file contents with the read tool, not exec (cat/head/tail/sed/etc.). Reserve exec for system/build/test commands.":'Command blocked: search local file contents with the search tool (mode "content"), not exec (grep/find/rg/etc.). Reserve exec for system/build/test commands.'}var Ac=/\.(?:pdf|docx?|xlsx?|pptx?|zip|tar|gz|7z|rar|exe|dll|so|dylib|wasm|class|png|jpe?g|gif|webp|bmp|mp[34]|mov|avi|mkv|wav|m4a|flac|ogg)\b(?:["'\s]|$)/i;function Ws(e){return e!==null&&Ac.test(e)}function Ec(e,t){if(e.length!==1||e[0]?.function.name!=="stt")return!1;let n=[...t].reverse().find(i=>i.role==="user");if(!n)return!1;let o=Array.isArray(n.audioUrls)&&n.audioUrls.some(i=>typeof i=="string"&&i.trim()),r=typeof n.content=="string"?n.content:"",s=/\b(?:stt|speech[-\s]?to[-\s]?text|transcribe|transcription|audio[-\s]?to[-\s]?text)\b|转写|转录|语音转文字|音频转文字|听写/i.test(r);return o&&s}function Mc(e,t){let n=Ic(t);if(!n)return null;let o=Pc(n);if(!o)return null;let r=[...e].reverse().find(a=>a.role==="user"),s=typeof r?.content=="string"?r.content:"",i=/\bAUDIO_STT_RESULT\s+([^\s<]+)\s+<transcription\b/i.exec(s);return i?.[1]?`AUDIO_STT_RESULT ${i[1]} ${o}`:o}function Ic(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 Pc(e){return e.toLocaleLowerCase().replace(/[^\p{L}\p{N}\s]+/gu," ").replace(/\s+/g," ").trim()}function R(e){return[...new Set(e.map(t=>t.function.name))].sort()}function ze(e){return[...e].sort((t,n)=>t.function.name.localeCompare(n.function.name))}function Ft(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 Oc(e,t,n,o,r){let s=r.filter(i=>i.name===e).sort((i,a)=>Vs(i.reason)-Vs(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 Vs(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 Nc(e){let t=typeof e.blockReason=="string"?e.blockReason:void 0;if(e.blocked&&/confirmation timed out/i.test(t??""))return"confirmation-timeout";if(e.blocked)return"blocked-by-policy";let n=typeof e.details?.error=="string"?e.details.error:void 0;if(n==="dedicated_tool_required")return"dedicated-tool-required";if(n==="existing_file_update_tool_required")return"existing-file-update-tool-required";if(n==="invalid_arguments")return"invalid-arguments";if(n==="blocked_global_process_kill")return"global-process-kill-blocked";if(n==="blocked_by_guard")return"blocked-by-policy"}function Xs(e){let t=new Set(e.map(n=>n.function.name));return t.has("read")||t.has("search")||t.has("write")||t.has("edit")||t.has("patch")}function ke(e,t){return t.size===0?[...e]:e.filter(n=>!t.has(n.function.name))}var Lc=new Set(["edit","patch","read"]);function Ks(e,t){let n=e.filter(o=>Lc.has(o.function.name)&&!t.has(o.function.name));return n.length>0?ze(n):e.filter(o=>o.function.name!=="write"&&!t.has(o.function.name))}function io(e,t){let n=new Set(t);return e.filter(o=>!n.has(o))}function Fc(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 Ys(e){let n=he(e)?.command;return typeof n=="string"&&n.trim()?n:void 0}var $t=5174;function Zs(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 Bc(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 si(e){return/(?:^|\s)--strictPort(?:\s|$)/.test(e)}function Dc(e){if(si(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 Js(e,t){let n=he(e)??{};return JSON.stringify({...n,command:t})}function $c(e){let t=e.replace(/^(?:\s*sleep\s+\d+(?:\.\d+)?\s*(?:&&|;)\s*)+/i,"").trim();return t&&t!==e.trim()?t:null}function Uc(e){return Zs(e,$t)?{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."}:Bc(e)&&Zs(e,$t-1)&&!si(e)?{action:"rewrite",command:Dc(e)}:null}function Ut(e){let t=[];for(let n of e.devServerUrls)if(!(!/^https?:\/\/(?:localhost|127\.0\.0\.1):\d+\b/i.test(n)||new RegExp(`:${$t}\\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 Qs(e){let t=Ut(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 jc(e){let t=e.buildFailureEvidence[0];return"The test/build you ran is still FAILING, so the task is not complete. "+(t?`Last failing output:
|
|
30
30
|
${t.slice(0,600)}
|
|
31
|
-
`:"")+"Do not finish or claim success from source inspection. Diagnose the failure, edit the source to fix the root cause, then RE-RUN the same test/build command via exec. Repeat until the command exits 0 (passes), then report the passing output. Do NOT modify, weaken, or delete the test/assertions to force a pass."}function
|
|
31
|
+
`:"")+"Do not finish or claim success from source inspection. Diagnose the failure, edit the source to fix the root cause, then RE-RUN the same test/build command via exec. Repeat until the command exits 0 (passes), then report the passing output. Do NOT modify, weaken, or delete the test/assertions to force a pass."}function mo(e){let n=he(e)?.command;return typeof n=="string"&&n.trim()?n.trim():null}var ei=4;function zc(e,t){if(/^(?:write|edit|patch)$/i.test(e)){let n=he(t),o=n?["path","file_path","filePath","filename","file"].map(r=>n[r]).find(r=>typeof r=="string"):void 0;return o?`edit:${o.replace(/\\/g,"/").toLowerCase()}`:null}if(/^exec$/i.test(e)){let n=mo(t);if(!n)return null;let o=ot(n);return fs(o)?null:`exec:${o}`}return null}function ti(e){let t=mo(e);return t?/\b(?:npx\s+)?playwright\s+install(?:\s+--with-deps)?\s+chromium\b/i.test(t):!1}function Hc(e){let t=Ut(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 qc(e){return[`Quick task-list status sync: the list still shows unresolved item(s): ${e.filter(n=>n.status!=="completed").map(n=>`#${n.id} ${n.title} (${n.status})`).join("; ")}.`,"If your final answer already shows these are done, just mark them completed with the task tool to match \u2014 this is a status sync, not a request to redo work.","Mark items completed only if the work is actually done and verified; otherwise mark them blocked/cancelled if the task tool supports that status, or keep them unresolved and report the blocker.","Do not produce a final completion claim until task status and the final answer agree."].join(" ")}function Gc(e){let t=new Set(["completed","blocked","cancelled","canceled","failed"]);return e.some(n=>!t.has(n.status.toLowerCase()))}function Wc(e){return e?Gs(e):"Command blocked: local file reads/searches/listing must use the dedicated read/search tools, not exec. Use read for file contents and search for filename or content lookup."}function ni(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=>Oc(s,t.availableToolNames,t.enabledToolNames,t.toolCallNames,t.blockedToolCalls)).join(", ");return`${e}
|
|
32
32
|
|
|
33
33
|
Tool availability diagnostics:
|
|
34
34
|
availableToolNames: ${t.availableToolNames.join(", ")}
|
|
35
35
|
enabledToolNames: ${t.enabledToolNames.join(", ")}
|
|
36
36
|
toolCallNames: ${t.toolCallNames.join(", ")||"none"}
|
|
37
37
|
blockedToolCalls: ${n}
|
|
38
|
-
attribution: ${r}`}function
|
|
39
|
-
`),i=
|
|
38
|
+
attribution: ${r}`}function ge(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function Vc(e,t){if(!e)return null;let n=ge(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=he(t);if(!r)return`Tool "${e.function.name}" arguments must be a JSON object.`;for(let s of o){let i=r[s];if(typeof i=="string"?i.trim().length===0:i==null)return`Tool "${e.function.name}" missing required field \`${s}\`. Use the tool schema exactly instead of substituting another field.${Xc(e.function.name)}`}return null}function Xc(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 Ne(e,t){if(!e||typeof e!="object")return;let n=e[t];return typeof n=="string"?n:void 0}function Dt(e,t){if(!e||typeof e!="object")return;let n=e[t];return typeof n=="boolean"?n:void 0}function Kc(e,t){if(!e||typeof e!="object")return;let n=e[t];return typeof n=="number"&&Number.isFinite(n)?n:void 0}function Yc(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 Zc(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 Jc(e,t){if(e.function.name!=="task")return!1;let n=he(e.function.arguments);if(n?.action!=="output")return!1;let o=n.taskId;return typeof o=="string"&&Re(t).has(o)}function Qc(e,t){if(e.toolName!=="task")return!1;let n=Ne(e.details,"taskId");return!n||!Re(t).has(n)?!1:Ne(e.details,"action")==="output"&&Dt(e.details,"running")===!0}var eu=180,tu=40;function nu(e){return/\(no output yet\)|\bno output yet\b/i.test(e)}function ou(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 Re(e){return e.backgroundAgentTaskIds??(e.backgroundAgentTaskIds=new Set)}function ru(e){if(!e||typeof e!="object")return null;let t=e.taskList;if(!Array.isArray(t))return null;let n=[];for(let o of t){if(!o||typeof o!="object")continue;let r=o,s=r.id,i=r.title,a=r.status;typeof s!="number"||!Number.isFinite(s)||typeof i!="string"||!i.trim()||typeof a!="string"||!a.trim()||n.push({id:s,title:i,status:a})}return n}var lo=new Set(["read","search"]),su=new Set(["write","edit","patch","image_generate"]),iu=18e4,au=3,at=1,lu=1,cu=1,uu=4,du=2,Q=new Map([["requirements.md","requirements"],["decisions.md","decisions"],["defects.md","defects"],["acceptance.md","acceptance"]]),go=new Set(["document-index.json","decision-state-table.json","context-pack-evidence.json"]),ii=[{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}],co=new Set(["write","edit","patch"]),fu=new Set(["read","search","exec"]);function ai(e){let t=W(e),n=xe(t);return t.split("/").includes("context-pack")&&Q.has(n)?at:t.split("/").includes("benchmark-state")&&go.has(n)?cu:t.includes("/qlogicagent-sessions/")&&t.includes("/tool-results/")?lu:au}function ao(e){let t=W(e);if(t.split("/").includes("context-pack")){let n=t.split("/context-pack/")[0];return`Use benchmark-state summaries instead: ${n}/benchmark-state/document-index.json, ${n}/benchmark-state/decision-state-table.json, and ${n}/benchmark-state/context-pack-evidence.json. If those summaries are stale, update compact checkpoint files under benchmark-state; do not reread or rewrite context-pack.`}return t.includes("/qlogicagent-sessions/")&&t.includes("/tool-results/")?"This is a persisted large tool-result preview. Use the first read, the original tool_result preview, and maintained benchmark-state summaries; do not reread tool-result cache files.":t.split("/").includes("benchmark-state")&&go.has(xe(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 ho(e){let t=W(e);return t.split("/").includes("context-pack")&&Q.has(xe(t))}function li(e){let t=W(e),o=t.indexOf("/context-pack/");return o<0?null:t.slice(0,o)}function pu(e){let t=[...e].filter(ho).map(li).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 Le(o)}catch{return!1}})}function ci(e){return[...Q.keys()].every(t=>e.has(t))}function yo(e){for(let t of e.values()){if(!t.path)continue;let n=li(t.path);if(n)return`${n}/benchmark-state`}return null}function ui(e){if(!ci(e))return[];let t=yo(e);return t?[...go].map(n=>`${t}/${n}`).filter(n=>{try{return!Le(n)}catch{return!0}}):[]}function mu(e,t){let n=ui(e);if(n.length===0)return null;let o=yo(e);if(!o)return null;let s=[...Q.keys()].map(a=>{let c=e.get(a);return`${a}: path=${c?.path??"unknown"}, contentHash=${c?.contentHash??"unknown"}, fileSizeBytes=${c?.fileSizeBytes??"unknown"}, recordCount=${c?.recordCount??"unknown"}, summary=${c?.summary??""}`}).join(`
|
|
39
|
+
`),i=ii.map(a=>`${a.id}: ${a.decision}`).join(`
|
|
40
40
|
`);return["You have already read and indexed requirements.md, decisions.md, defects.md, and acceptance.md for this long-horizon benchmark.","Do not read context-pack, persisted tool-result previews, or compact benchmark-state files again in this turn.","Before any more analysis or final answer, maintain the benchmark state files using write/edit/patch only.",`Benchmark-state directory: ${o}.`,`Missing files: ${n.join(", ")}.`,"Create missing files with write. If any target already exists, update it with edit or patch instead of write.","For every contentHash and fileSizeBytes you write, copy the EXACT value from the 'Document evidence already available' section below. Do NOT compute, approximate, or invent a hash \u2014 you must not re-read the large read-only context-pack files to produce one.","The context-pack inputs (requirements.md, decisions.md, defects.md, acceptance.md) are READ-ONLY and immutable: their content and contentHash cannot change between turns. If a hash ever appears to differ from what you recorded, the source did NOT change \u2014 suspect your own recorded value first (stale, or never tool-derived). Never raise a 'source changed' blocker for these files.","Acceptance verdicts are monotonic unless re-derived from primary evidence: do NOT flip a previously-PASSing criterion to FAIL on a derived/secondary signal such as a hash diff. Change a PASS to FAIL only after re-checking the actual acceptance condition against primary evidence, and cite that evidence.","Required files:","- document-index.json: include contextPackPath and a documents object keyed by requirements.md, decisions.md, defects.md, acceptance.md with path, contentHash, fileSizeBytes, recordCount, indexVersion, summary, and lastReviewedTurn.","- decision-state-table.json: include D001-D006 with id, decision, status, evidence, and lastConfirmedTurn.","- context-pack-evidence.json: include turn and fileVerification for requirements.md, decisions.md, defects.md, acceptance.md with path, contentHash, and fileSizeBytes.",`Current turn: ${t}.`,"Document evidence already available:",s,"Decision records to preserve:",i].join(`
|
|
41
|
-
`)}function Zs(e){return ao.has(e)}function du(e){return e.benchmarkStateMaintenanceRequiredFiles.size>0&&[...e.benchmarkStateMaintenanceRequiredFiles].every(t=>fu(e,t))}function fu(e,t){if(e.benchmarkStateMaintenanceWrittenFiles.has(t))return!0;try{if(!Ne(t))return!1;let n=ke(t);if(n!=="document-index.json"&&n!=="context-pack-evidence.json")return!0;let o=jt(t,"utf8");return go(e.maintainedDocuments,t,JSON.stringify({content:o})).ok}catch{return!1}}function go(e,t,n){let o=ke(t);if(o!=="document-index.json"&&o!=="context-pack-evidence.json")return{ok:!0};let r=Su(n);if(!r)return{ok:!1,reason:`${o} write did not include JSON content`};let s=pe(r);if(!s)return{ok:!1,reason:`${o} content is not a JSON object`};if(o==="document-index.json"){let a=fe(s.documents);if(!a)return{ok:!1,reason:"document-index.json missing documents object"};for(let c of J.keys()){let f=e.get(c),h=fe(a[c]);if(!f||!h)return{ok:!1,reason:`document-index.json missing ${c}`};if(h.contentHash!==f.contentHash)return{ok:!1,reason:`document-index.json ${c} contentHash does not match read.details`};if(h.fileSizeBytes!==f.fileSizeBytes)return{ok:!1,reason:`document-index.json ${c} fileSizeBytes does not match read.details`}}return{ok:!0}}let i=fe(s.fileVerification);if(!i)return{ok:!1,reason:"context-pack-evidence.json missing fileVerification object"};for(let a of J.keys()){let c=e.get(a),f=fe(i[a]);if(!c||!f)return{ok:!1,reason:`context-pack-evidence.json missing ${a}`};if(f.contentHash!==c.contentHash)return{ok:!1,reason:`context-pack-evidence.json ${a} contentHash does not match read.details`};if(f.fileSizeBytes!==c.fileSizeBytes)return{ok:!1,reason:`context-pack-evidence.json ${a} fileSizeBytes does not match read.details`}}return{ok:!0}}function pu(e){if(!ai(e))return[];let t=mo(e);if(!t)return[];let n=[];for(let o of["document-index.json","context-pack-evidence.json"]){let r=`${t}/${o}`,s;try{if(!Ne(r))continue;s=jt(r,"utf8")}catch{continue}let i=go(e,r,JSON.stringify({content:s}));i.ok||n.push({path:r,reason:i.reason})}return n}function mu(e,t,n,o){if(e.filter(a=>a.name==="read"&&a.reason==="read-cycle-policy").length<iu)return!1;let s=new Set([...t].filter(po).map(ke));return[...J.keys()].every(a=>s.has(a))?[...J.keys()].every(a=>o.has(a))||n||cu(t):!1}function ci(e,t,n){if(e!=="write"||!n.has("edit")&&!n.has("patch"))return null;let o=Ut(t);if(!o)return null;try{if(!Ne(o))return null}catch{return null}return{path:o,error:`Existing file update blocked for "${o}". Use edit or patch for existing files so the event stream can distinguish file creation from incremental maintenance.`}}var $t=class extends Error{constructor(n){super(`LLM stream idle timeout after ${n}ms without a chunk.`);this.timeoutMs=n;this.name="LLMStreamIdleTimeoutError"}timeoutMs;code="LLM_STREAM_TIMEOUT"};async function*gu(e,t){if(!Number.isFinite(t)||t<=0){yield*e;return}let n=e[Symbol.asyncIterator]();try{for(;;){let o,r=await Promise.race([n.next(),new Promise(s=>{o=setTimeout(()=>s("timeout"),t)})]);if(o&&clearTimeout(o),r==="timeout")throw new $t(t);if(r.done)return;yield r.value}}finally{n.return?.().catch(()=>{})}}function lo(e){try{let t=JSON.parse(e),n=t.file_path??t.path??t.filePath;return typeof n=="string"&&n.trim()?n:void 0}catch{return}}function Ut(e){try{let t=JSON.parse(e),n=t.file_path??t.path??t.filePath;return typeof n=="string"&&n.trim()?n:void 0}catch{return}}function hu(e){return e.flatMap(t=>{if(yu(t.function.arguments))return[t];let n=bu(t.function.arguments);return n.length<2?[t]:n.map((o,r)=>({...t,id:`${t.id}__json_${r+1}`,function:{...t.function,arguments:JSON.stringify(o)}}))})}function yu(e){try{let t=JSON.parse(e);return!!t&&typeof t=="object"&&!Array.isArray(t)}catch{return!1}}function bu(e){let t=[],n=0,o=-1,r=!1,s=!1,i=0;for(let a=0;a<e.length;a+=1){let c=e[a];if(r){s?s=!1:c==="\\"?s=!0:c==='"'&&(r=!1);continue}if(c==='"'){r=!0;continue}if(c==="{"){if(n===0){if(e.slice(i,a).trim())return[];o=a}n+=1;continue}if(c!=="}"||(n-=1,n!==0||o<0))continue;let f=pe(e.slice(o,a+1));if(!f)return[];t.push(f),i=a+1,o=-1}return n!==0||r||e.slice(i).trim()?[]:t}function pe(e){try{let t=JSON.parse(e);return t&&typeof t=="object"&&!Array.isArray(t)?t:null}catch{return null}}function G(e){let t=e.trim().replace(/\\/g,"/");for(t=t.replace(/\/{2,}/g,"/");t.includes("/./");)t=t.replace(/\/\.\//g,"/");return t=t.replace(/\/\.$/,""),/^[a-z]:\//i.test(t)&&(t=t.toLowerCase()),t.replace(/\/$/,"")}function ke(e){let t=e.trim().replace(/\\/g,"/");return t.slice(t.lastIndexOf("/")+1).toLowerCase()}function ho(e){return`sha256:${hc("sha256").update(e).digest("hex")}`}function Tu(e,t){let n=t.split(/\r?\n/).map(a=>a.trim()).filter(Boolean),o=n[0]??e,r=n.find(a=>/record\s+0*1\b/i.test(a)),s=r&&r!==o?`${o}; ${r}`:o,i=s.length>180?`${s.slice(0,177)}...`:s;return i.toLowerCase().includes(e.toLowerCase())?i:`${e}: ${i}`}function Cu(e){return Object.fromEntries([...e.entries()].sort(([t],[n])=>t.localeCompare(n)))}function ku(e,t,n,o){let r=[...t.values()].sort((c,f)=>(c.name??"").localeCompare(f.name??""));if(r.length===0)return null;let s=r.map(c=>`${c.name??"document"}:${c.contentHash??"unknown"}`).join("|"),i=ri.map(c=>({...c,evidence:`read:long-horizon-documents:${ho(`${c.id}:${s}`)}`,lastConfirmedTurn:o})),a={strategy:"maintained-document-index",nextReadPolicy:"use maintained index before full document reread",budgetStatus:"within-budget",maxReadsPerDocument:rt,observedReadsByPath:Cu(n)};return{type:"document_maintenance",turnId:e,checkpointId:`${e}-docs-${r.length}`,documents:r,decisionStateTable:i,readCycleFindings:[],readCycleGuard:a}}function Ru(e){let t=e.find(o=>o.path)?.path??"",n=t.lastIndexOf("/");return n>0?t.slice(0,n):t}function Lt(e,t){return e.get(t)??null}function xu(e){let t=Lt(e,"requirements.md"),n=Lt(e,"decisions.md"),o=Lt(e,"defects.md"),r=Lt(e,"acceptance.md");if(!t||!n||!o||!r)return null;let s=[t,n,o,r];return{goal:`Maintain long-horizon project state from ${t.name}, ${n.name}, ${o.name}, and ${r.name}`,artifactRoot:Ru(s),decisions:[n.summary],defects:[o.summary],acceptanceCriteria:[r.summary],blockers:[],nextAction:"Continue from the maintained document index and read only explicitly missing sections"}}function _u(e,t){let n=xu(t);return n?[{type:"lifecycle",turnId:e,kind:"goal_reconstruction",reconstruction:n},{type:"lifecycle",turnId:e,kind:"memory_drift",status:"none",detail:"No memory drift detected against the maintained document index."}]:[]}function vu(e,t,n,o,r){let s=co(t,n,o,r);if(!s)return!1;let i=s.name;return i?(e.maintainedDocuments.set(i,s),!0):!1}function co(e,t,n,o){let r=ke(e);if(!J.has(r))return null;let s=Eu(t)??t,i=Mu(o,"contentHash"),a=qe(o??null,"fileSizeBytes"),c=i??ho(s);return{name:r,path:G(e),indexed:!0,maintained:!0,indexVersion:c,contentHash:c,summary:Tu(r,s),lastReviewedTurn:n,fileSizeBytes:a??Buffer.byteLength(s,"utf8"),recordCount:ui(s)}}function Au(e,t){return ci(e.function.name,e.function.arguments,t)!==null}function wu(e,t){let n=Ut(t.function.arguments);return`This exact write call to an existing file has been attempted ${e} times${n?` for "${n}"`:""}. Do not call write again for this existing file. Use edit or patch for the existing-file update, then continue verification.`}function Su(e){let n=pe(e)?.content;return typeof n=="string"?n:void 0}function Mu(e,t){let n=e?.[t];return typeof n=="string"&&n.trim()?n.trim():void 0}function ui(e){let t=e.split(/\r?\n/).map(n=>n.trim()).filter(Boolean).length;return Math.max(1,t)}function Eu(e){if(!e.includes("<persisted-output>"))return null;let n=e.match(/Full output saved to:\s*(.+?)(?:\r?\n|$)/)?.[1]?.trim();if(!n)return null;try{return Ne(n)?jt(n,"utf8"):null}catch{return null}}function Iu(e){let t=new Map;for(let s of e)if(!(s.role!=="assistant"||!Array.isArray(s.tool_calls)))for(let i of s.tool_calls){if(i.function?.name!=="read"||typeof i.id!="string"||typeof i.function.arguments!="string")continue;let a=lo(i.function.arguments);if(!a)continue;let c=G(a);si(c)===rt&&t.set(i.id,{path:c})}let n=new Map,o=new Map,r=!1;for(let s of e){if(s.role!=="tool"||typeof s.tool_call_id!="string"||s.is_error===!0)continue;let i=t.get(s.tool_call_id);if(!i)continue;let a=typeof s.content=="string"?s.content:"";if(!a||/^Error:/i.test(a.trim()))continue;n.set(i.path,(n.get(i.path)??0)+1);let c=co(i.path,a,0);c?.name&&o.set(c.name,c)}for(let s of Fu(e)){r=!0;for(let i of J.keys()){let a=G(`${s}/${i}`);if(n.set(a,Math.max(n.get(a)??0,rt)),!o.has(i)){let c=co(a,`${i} maintained by benchmark-state/document-index.json from prior conversation history.`,0);c?.name&&o.set(c.name,c)}}}for(let s of Pu(e)){r=!0;for(let i of s.documents)!i.name||!i.path||(n.set(i.path,Math.max(n.get(i.path)??0,rt)),o.set(i.name,i))}return{fileReadCounts:n,maintainedDocuments:o,persistedBenchmarkStateRecovered:r}}function Pu(e){let t=[];for(let n of Ou(e)){let o=Js(`${n}/document-index.json`),r=Js(`${n}/context-pack-evidence.json`),s=ze(o,"contextPackPath")??Nu(r);if(!s)continue;let i=Lu(s,o,r);i.length===J.size&&t.push({documents:i})}return t}function Ou(e){let t=new Set;for(let n of e){if(typeof n.content!="string")continue;let r=n.content.replace(/\\/g,"/").matchAll(/([a-zA-Z]:\/[^\s"'`<>]*?\/benchmark-state)(?=\/|[\s.,;:)\]}]|$)/g);for(let s of r){let i=G(s[1]??"");i&&t.add(i)}}return[...t]}function Js(e){try{if(!Ne(e))return null;let t=JSON.parse(jt(e,"utf8"));return t&&typeof t=="object"&&!Array.isArray(t)?t:null}catch{return null}}function ze(e,t){let n=e?.[t];return typeof n=="string"&&n.trim()?G(n):void 0}function Nu(e){let t=e?.fileVerification;if(!(!t||typeof t!="object"||Array.isArray(t)))for(let n of J.keys()){let o=t[n];if(!o||typeof o!="object"||Array.isArray(o))continue;let r=ze(o,"path");if(!r)continue;let s=`/${n}`;if(r.endsWith(s))return r.slice(0,-s.length)}}function Lu(e,t,n){let o=fe(t?.documents),r=fe(n?.fileVerification),s=[];for(let i of J.keys()){let a=fe(o?.[i]),c=fe(r?.[i]);if(!a&&!c)return[];let f=ze(a,"path"),y=ze(c,"path")??(f?.includes("/context-pack/")?f:G(`${e}/${i}`)),C=ze(a,"contentHash")??ze(c,"contentHash")??ho(`${i}:${y}`),x=typeof a?.summary=="string"&&a.summary.trim()?a.summary.trim():`${i} maintained by persisted benchmark-state/document-index.json.`;s.push({name:i,path:G(y),indexed:!0,maintained:!0,indexVersion:String(a?.indexVersion??C),contentHash:C,summary:x,lastReviewedTurn:uo(a,"lastReviewedTurn")??uo(n,"turn")??0,fileSizeBytes:qe(a,"fileSizeBytes")??qe(c,"fileSizeBytes")??qe(c,"sizeBytes")??Buffer.byteLength(x,"utf8"),recordCount:qe(a,"recordCount")??qe(c,"recordCount")??ui(x)})}return s}function uo(e,t){let n=e?.[t];return typeof n=="number"&&Number.isFinite(n)?n:void 0}function qe(e,t){let n=uo(e,t);return n&&n>0?n:void 0}function Fu(e){let t=e.slice(0,Math.max(0,e.length-1)),n=new Set;for(let o of t){if(typeof o.content!="string")continue;let r=o.content.replace(/\\/g,"/").toLowerCase();if(!r.includes("benchmark-state/document-index")&&!r.includes("benchmark-state/context-pack-evidence")&&!r.includes("maintained document index"))continue;let s=r.matchAll(/([a-z]:\/[^\s"'`<>]*?\/context-pack)(?=\/|[\s.,;:)\]}]|$)/gi);for(let i of s){let a=G(i[1]??"");a&&n.add(a)}}return[...n]}function Bu(e){e.identicalSuccessfulToolResults.clear();for(let t of[...e.identicalCallCounts.keys()]){let n=t.slice(0,t.indexOf("::"));io.has(n)&&e.identicalCallCounts.delete(t)}}async function*di(e,t,n,o){let{turnId:r,sessionId:s,messages:i,availableTools:a,tools:c,model:f,apiKey:h,temperature:y=0,hooks:C,signal:x}=e,v={sessionId:s,turnId:r},A=e.maxTurns??0,P=e.querySource,S=e.runtimePorts.resolveToolEligibility(c,e.toolEligibilityContext),O=S.eligibleTools,D=[];for(let m of S.blockedTools)D.push({name:m.toolName,reason:"blocked-by-policy"}),yield{type:"tool_blocked",turnId:r,callId:"",name:m.toolName,reason:"blocked-by-policy"};let q=is(e.maxRounds,i),se=as(e.maxToolCalls,i),qt=!(typeof e.maxRounds=="number"&&e.maxRounds>=1)&&!(typeof e.maxToolCalls=="number"&&e.maxToolCalls>=1),yo=St(i),Le={contextWindowTokens:e.contextWindowTokens??dr,responseBufferTokens:fr,maxOutputTokens:e.maxOutputTokens??pr,abortSignal:x,reactiveCompactEnabled:!0,outputEscalationEnabled:!0},L=new Set,F=0,bo=new Set,To=0,He=0,Ge=0,st=0,Co=new Map,Y=new Set,b=Te(O,Y),We=!1,zt=!1,Ht,Gt=()=>k(b),yi=yc(O,i),Wt=!1,ko=0,Ro=0,xo=0,U=!1,it=!1,Vt=Iu(i),u={messages:[...i],maxOutputTokensRecoveryCount:0,hasAttemptedReactiveCompact:!1,maxOutputTokensOverride:void 0,turnCount:1,transition:void 0,guardState:Mn(Le),reactiveCompactState:Nn(),toolLoopState:xt({maxRounds:q,replayMessages:[...i]}).state,consecutiveFailedRounds:0,finalText:"",totalUsage:{inputTokens:0,outputTokens:0},collapseStore:hn(),currentModel:f,consecutive529Errors:0,consecutiveApiRetries:0,stopHookActive:void 0,lastResponseId:void 0,snipRemovedIds:new Set,contentReplacementState:e.runtimePorts.createContentReplacementState(),budgetContinuationCount:0,repeatedToolFailureRecoveryCount:0,lastBudgetDeltaTokens:0,lastBudgetGlobalTokens:0,identicalCallCounts:new Map,identicalSuccessfulToolResults:new Map,toolFailureCounts:new Map,fileReadCounts:Vt.fileReadCounts,fileReadCycleBlockedPaths:new Set,fileReadCycleNudgedPaths:new Set,maintainedDocuments:Vt.maintainedDocuments,persistedBenchmarkStateRecovered:Vt.persistedBenchmarkStateRecovered,benchmarkStateMaintenanceRequiredFiles:new Set,benchmarkStateMaintenanceWrittenFiles:new Set,recoveryTrace:new Map,artifactContract:Xr(i),browserAcceptanceRecoveryCount:0,buildVerificationRecoveryCount:0,benchmarkStateIntegrityRecoveryCount:0,backgroundAgentTaskIds:new Set,backgroundAgentNoOutputPollCounts:new Map,stalledBackgroundAgentTasks:new Map,notOfferedToolRecoveryCount:0,existingFileUpdateRecoveryCount:0,taskListReconciliationCount:0,lastTaskList:[]},Xt=Math.max(A*5,200),bi=4,Ti=4,_o=0,vo=new Map,Kt,M=(m,z)=>{let Q=`${m}:${z??""}`,ie=(vo.get(Q)??0)+1;if(vo.set(Q,ie),m==="autocompact"){let j=u.recoveryTrace.get("autocompact")??0;if(ie>bi||j>=Ti){let ee=`Repeated context compression made no forward progress: ${z??"autocompact"}`;return Kt=ee,u.recoveryTrace.set("compression_loop_guard",(u.recoveryTrace.get("compression_loop_guard")??0)+1),{type:"recovery",turnId:r,action:"compression_loop_guard",detail:ee}}}return u.recoveryTrace.set(m,(u.recoveryTrace.get(m)??0)+1),{type:"recovery",turnId:r,action:m,detail:z}},Ao=()=>({type:"tool_use_summary",turnId:r,availableToolNames:k(a??c),enabledToolNames:Gt(),toolCallNames:[...L].sort(),blockedToolCalls:Nt(D)}),wo=qr((a??c).map(m=>m.function.name)),Yt=!1,So=m=>({type:"end",turnId:r,content:m,usage:u.totalUsage,model:u.currentModel,...u.recoveryTrace.size>0?{recoveryTrace:Object.fromEntries(u.recoveryTrace)}:{}});function*W(m,z){let Q=Kr({content:m,contractActive:wo,totalToolCallCount:F,distinctToolNames:L,visibleToolCallCount:To,visibleToolNames:bo,artifactContract:u.artifactContract,blockedToolCalls:Nt(D),activeTasks:u.lastTaskList,forcedStop:z?.forcedStop??Yt});Q.malformedBlock&&(yield M("final_status_block_malformed","final-status block was not valid schema-1 JSON; treated as absent")),jn(u.artifactContract,Q.content),Jt()&&(yield Zt()),yield Ao(),yield So(Q.content)}function*Mo(m){yield Ao(),yield So(m)}let Zt=()=>({type:"artifact_contract",turnId:r,...Un(u.artifactContract,i)}),Jt=()=>{let m=Un(u.artifactContract,i);return!!(m.requiresBrowserAcceptance||m.artifactRoot||m.writePaths.length>0||m.outOfRootWrites.length>0||m.devServerUrls.length>0||m.browserVerified)},at=(m,z)=>(Yt=!0,u.finalText||Gn(m,o)),Ci=(m,z,Q)=>{Yt=!0;let ie=Pe({inputMessages:i,messages:z,reason:Q});return ie||m||Gn(z,o)};for(;;){if(_o++,_o>Xt){o.info(`hard iteration cap reached (${Xt}), forcing completion`);let l=at(u.messages,`hard iteration cap reached (${Xt}) before completing the final status contract`);yield*W(l);return}let{messages:m,maxOutputTokensRecoveryCount:z,maxOutputTokensOverride:Q,turnCount:ie,guardState:j,reactiveCompactState:ee,collapseStore:Qt}=u,{toolLoopState:te}=u;if(e.refreshTools&&ie>1){let l=e.refreshTools(),d=Te(l,Y);d!==b&&(b=d,o.debug(`tools refreshed: ${l.length} tools`))}if(On(j,Le)){o.info(`turn aborted by guard at turn ${ie}`),yield{type:"error",turnId:r,error:"Turn aborted",code:"ABORTED",usage:u.totalUsage};return}let Re=En(j,Le);if(Re.level==="blocking"){Re.reason==="prompt_too_long"&&$e(ee)&&(ee.attemptedThisTurn=!0,j.hasAttemptedReactiveCompact=!0,o.info(`token budget blocking (${Re.reason}), reactive compact needed`),yield M("reactive_compact","token budget pre-check")),o.info(`token budget blocking (${Re.reason}), ending tool loop`);break}Re.level==="warning"&&o.info(`token budget warning: ${Re.usagePercent}% used, ${Re.remainingTokens} remaining`);let lt=yield*ps({messages:m,contentReplacementState:u.contentReplacementState,snipRemovedIds:u.snipRemovedIds,collapseStore:Qt,guardState:j,guardConfig:Le,runtimePorts:e.runtimePorts,hooks:C,hookCtx:v,sessionId:s,currentModel:u.currentModel,log:o,recovery:M,onAutocompact:()=>{u.hasAttemptedReactiveCompact=!1}});if(Kt){yield*W(`${Kt}. Stop compressing the same context repeatedly; continue from the maintained document index or report the incomplete state explicitly.`,{forcedStop:!0});return}let ki=U?"required":e.toolChoice==="required"&&Wt?"auto":e.toolChoice??"auto";U=!1;let Ve=kn({tools:b,toolChoice:ki}),Eo=k(Ve.tools).join("\0"),Io=Ht!==void 0&&Ht!==Eo;Io&&u.lastResponseId&&(yield M("stateless_retry","tool schema changed; replaying full history without previous_response_id"));let Ri=it||Io?void 0:u.lastResponseId;Ht=Eo;let Xe=xt({maxRounds:q,replayMessages:lt,lastStopReason:te.lastStopReason,options:{stopReason:te.lastStopReason}}),Po=[Ve.extraSystemPrompt,wo?zr:void 0].filter(l=>!!l).join(`
|
|
41
|
+
`)}function oi(e){return co.has(e)}function gu(e){return e.longHorizonStateMaintenanceRequiredFiles.size>0&&[...e.longHorizonStateMaintenanceRequiredFiles].every(t=>hu(e,t))}function hu(e,t){if(e.longHorizonStateMaintenanceWrittenFiles.has(t))return!0;try{if(!Le(t))return!1;let n=xe(t);if(n!=="document-index.json"&&n!=="context-pack-evidence.json")return!0;let o=Ht(t,"utf8");return bo(e.maintainedDocuments,t,JSON.stringify({content:o})).ok}catch{return!1}}function bo(e,t,n){let o=xe(t);if(o!=="document-index.json"&&o!=="context-pack-evidence.json")return{ok:!0};let r=Pu(n);if(!r)return{ok:!1,reason:`${o} write did not include JSON content`};let s=he(r);if(!s)return{ok:!1,reason:`${o} content is not a JSON object`};if(o==="document-index.json"){let a=ge(s.documents);if(!a)return{ok:!1,reason:"document-index.json missing documents object"};for(let c of Q.keys()){let f=e.get(c),g=ge(a[c]);if(!f||!g)return{ok:!1,reason:`document-index.json missing ${c}`};if(g.contentHash!==f.contentHash)return{ok:!1,reason:`document-index.json ${c} contentHash does not match read.details`};if(g.fileSizeBytes!==f.fileSizeBytes)return{ok:!1,reason:`document-index.json ${c} fileSizeBytes does not match read.details`}}return{ok:!0}}let i=ge(s.fileVerification);if(!i)return{ok:!1,reason:"context-pack-evidence.json missing fileVerification object"};for(let a of Q.keys()){let c=e.get(a),f=ge(i[a]);if(!c||!f)return{ok:!1,reason:`context-pack-evidence.json missing ${a}`};if(f.contentHash!==c.contentHash)return{ok:!1,reason:`context-pack-evidence.json ${a} contentHash does not match read.details`};if(f.fileSizeBytes!==c.fileSizeBytes)return{ok:!1,reason:`context-pack-evidence.json ${a} fileSizeBytes does not match read.details`}}return{ok:!0}}function yu(e){if(!ci(e))return[];let t=yo(e);if(!t)return[];let n=[];for(let o of["document-index.json","context-pack-evidence.json"]){let r=`${t}/${o}`,s;try{if(!Le(r))continue;s=Ht(r,"utf8")}catch{continue}let i=bo(e,r,JSON.stringify({content:s}));i.ok||n.push({path:r,reason:i.reason})}return n}function bu(e,t,n,o){if(e.filter(a=>a.name==="read"&&a.reason==="read-cycle-policy").length<uu)return!1;let s=new Set([...t].filter(ho).map(xe));return[...Q.keys()].every(a=>s.has(a))?[...Q.keys()].every(a=>o.has(a))||n||pu(t):!1}function di(e,t,n){if(e!=="write"||!n.has("edit")&&!n.has("patch"))return null;let o=zt(t);if(!o)return null;try{if(!Le(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 jt=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*Tu(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 jt(t);if(r.done)return;yield r.value}}finally{n.return?.().catch(()=>{})}}function uo(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 zt(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 Cu(e){return e.flatMap(t=>{if(ku(t.function.arguments))return[t];let n=Ru(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 ku(e){try{let t=JSON.parse(e);return!!t&&typeof t=="object"&&!Array.isArray(t)}catch{return!1}}function Ru(e){let t=[],n=0,o=-1,r=!1,s=!1,i=0;for(let a=0;a<e.length;a+=1){let c=e[a];if(r){s?s=!1:c==="\\"?s=!0:c==='"'&&(r=!1);continue}if(c==='"'){r=!0;continue}if(c==="{"){if(n===0){if(e.slice(i,a).trim())return[];o=a}n+=1;continue}if(c!=="}"||(n-=1,n!==0||o<0))continue;let f=he(e.slice(o,a+1));if(!f)return[];t.push(f),i=a+1,o=-1}return n!==0||r||e.slice(i).trim()?[]:t}function he(e){try{let t=JSON.parse(e);return t&&typeof t=="object"&&!Array.isArray(t)?t:null}catch{return null}}function W(e){let t=e.trim().replace(/\\/g,"/");for(t=t.replace(/\/{2,}/g,"/");t.includes("/./");)t=t.replace(/\/\.\//g,"/");return t=t.replace(/\/\.$/,""),/^[a-z]:\//i.test(t)&&(t=t.toLowerCase()),t.replace(/\/$/,"")}function xe(e){let t=e.trim().replace(/\\/g,"/");return t.slice(t.lastIndexOf("/")+1).toLowerCase()}function To(e){return`sha256:${Sc("sha256").update(e).digest("hex")}`}function xu(e,t){let n=t.split(/\r?\n/).map(a=>a.trim()).filter(Boolean),o=n[0]??e,r=n.find(a=>/record\s+0*1\b/i.test(a)),s=r&&r!==o?`${o}; ${r}`:o,i=s.length>180?`${s.slice(0,177)}...`:s;return i.toLowerCase().includes(e.toLowerCase())?i:`${e}: ${i}`}function _u(e){return Object.fromEntries([...e.entries()].sort(([t],[n])=>t.localeCompare(n)))}function vu(e,t,n,o){let r=[...t.values()].sort((c,f)=>(c.name??"").localeCompare(f.name??""));if(r.length===0)return null;let s=r.map(c=>`${c.name??"document"}:${c.contentHash??"unknown"}`).join("|"),i=ii.map(c=>({...c,evidence:`read:long-horizon-documents:${To(`${c.id}:${s}`)}`,lastConfirmedTurn:o})),a={strategy:"maintained-document-index",nextReadPolicy:"use maintained index before full document reread",budgetStatus:"within-budget",maxReadsPerDocument:at,observedReadsByPath:_u(n)};return{type:"document_maintenance",turnId:e,checkpointId:`${e}-docs-${r.length}`,documents:r,decisionStateTable:i,readCycleFindings:[],readCycleGuard:a}}function Au(e){let t=e.find(o=>o.path)?.path??"",n=t.lastIndexOf("/");return n>0?t.slice(0,n):t}function Bt(e,t){return e.get(t)??null}function wu(e){let t=Bt(e,"requirements.md"),n=Bt(e,"decisions.md"),o=Bt(e,"defects.md"),r=Bt(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:Au(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 Su(e,t){let n=wu(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 Eu(e,t,n,o,r){let s=fo(t,n,o,r);if(!s)return!1;let i=s.name;return i?(e.maintainedDocuments.set(i,s),!0):!1}function fo(e,t,n,o){let r=xe(e);if(!Q.has(r))return null;let s=Nu(t)??t,i=Ou(o,"contentHash"),a=He(o??null,"fileSizeBytes"),c=i??To(s);return{name:r,path:W(e),indexed:!0,maintained:!0,indexVersion:c,contentHash:c,summary:xu(r,s),lastReviewedTurn:n,fileSizeBytes:a??Buffer.byteLength(s,"utf8"),recordCount:fi(s)}}function Mu(e,t){return di(e.function.name,e.function.arguments,t)!==null}function Iu(e,t){let n=zt(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 Pu(e){let n=he(e)?.content;return typeof n=="string"?n:void 0}function Ou(e,t){let n=e?.[t];return typeof n=="string"&&n.trim()?n.trim():void 0}function fi(e){let t=e.split(/\r?\n/).map(n=>n.trim()).filter(Boolean).length;return Math.max(1,t)}function Nu(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 Le(n)?Ht(n,"utf8"):null}catch{return null}}function Lu(e){let t=new Map;for(let s of e)if(!(s.role!=="assistant"||!Array.isArray(s.tool_calls)))for(let i of s.tool_calls){if(i.function?.name!=="read"||typeof i.id!="string"||typeof i.function.arguments!="string")continue;let a=uo(i.function.arguments);if(!a)continue;let c=W(a);ai(c)===at&&t.set(i.id,{path:c})}let n=new Map,o=new Map,r=!1;for(let s of e){if(s.role!=="tool"||typeof s.tool_call_id!="string"||s.is_error===!0)continue;let i=t.get(s.tool_call_id);if(!i)continue;let a=typeof s.content=="string"?s.content:"";if(!a||/^Error:/i.test(a.trim()))continue;n.set(i.path,(n.get(i.path)??0)+1);let c=fo(i.path,a,0);c?.name&&o.set(c.name,c)}for(let s of Uu(e)){r=!0;for(let i of Q.keys()){let a=W(`${s}/${i}`);if(n.set(a,Math.max(n.get(a)??0,at)),!o.has(i)){let c=fo(a,`${i} maintained by benchmark-state/document-index.json from prior conversation history.`,0);c?.name&&o.set(c.name,c)}}}for(let s of Fu(e)){r=!0;for(let i of s.documents)!i.name||!i.path||(n.set(i.path,Math.max(n.get(i.path)??0,at)),o.set(i.name,i))}return{fileReadCounts:n,maintainedDocuments:o,persistedLongHorizonStateRecovered:r}}function Fu(e){let t=[];for(let n of Bu(e)){let o=ri(`${n}/document-index.json`),r=ri(`${n}/context-pack-evidence.json`),s=qe(o,"contextPackPath")??Du(r);if(!s)continue;let i=$u(s,o,r);i.length===Q.size&&t.push({documents:i})}return t}function Bu(e){let t=new Set;for(let n of e){if(typeof n.content!="string")continue;let r=n.content.replace(/\\/g,"/").matchAll(/([a-zA-Z]:\/[^\s"'`<>]*?\/benchmark-state)(?=\/|[\s.,;:)\]}]|$)/g);for(let s of r){let i=W(s[1]??"");i&&t.add(i)}}return[...t]}function ri(e){try{if(!Le(e))return null;let t=JSON.parse(Ht(e,"utf8"));return t&&typeof t=="object"&&!Array.isArray(t)?t:null}catch{return null}}function qe(e,t){let n=e?.[t];return typeof n=="string"&&n.trim()?W(n):void 0}function Du(e){let t=e?.fileVerification;if(!(!t||typeof t!="object"||Array.isArray(t)))for(let n of Q.keys()){let o=t[n];if(!o||typeof o!="object"||Array.isArray(o))continue;let r=qe(o,"path");if(!r)continue;let s=`/${n}`;if(r.endsWith(s))return r.slice(0,-s.length)}}function $u(e,t,n){let o=ge(t?.documents),r=ge(n?.fileVerification),s=[];for(let i of Q.keys()){let a=ge(o?.[i]),c=ge(r?.[i]);if(!a&&!c)return[];let f=qe(a,"path"),y=qe(c,"path")??(f?.includes("/context-pack/")?f:W(`${e}/${i}`)),k=qe(a,"contentHash")??qe(c,"contentHash")??To(`${i}:${y}`),x=typeof a?.summary=="string"&&a.summary.trim()?a.summary.trim():`${i} maintained by persisted benchmark-state/document-index.json.`;s.push({name:i,path:W(y),indexed:!0,maintained:!0,indexVersion:String(a?.indexVersion??k),contentHash:k,summary:x,lastReviewedTurn:po(a,"lastReviewedTurn")??po(n,"turn")??0,fileSizeBytes:He(a,"fileSizeBytes")??He(c,"fileSizeBytes")??He(c,"sizeBytes")??Buffer.byteLength(x,"utf8"),recordCount:He(a,"recordCount")??He(c,"recordCount")??fi(x)})}return s}function po(e,t){let n=e?.[t];return typeof n=="number"&&Number.isFinite(n)?n:void 0}function He(e,t){let n=po(e,t);return n&&n>0?n:void 0}function Uu(e){let t=e.slice(0,Math.max(0,e.length-1)),n=new Set;for(let o of t){if(typeof o.content!="string")continue;let r=o.content.replace(/\\/g,"/").toLowerCase();if(!r.includes("benchmark-state/document-index")&&!r.includes("benchmark-state/context-pack-evidence")&&!r.includes("maintained document index"))continue;let s=r.matchAll(/([a-z]:\/[^\s"'`<>]*?\/context-pack)(?=\/|[\s.,;:)\]}]|$)/gi);for(let i of s){let a=W(i[1]??"");a&&n.add(a)}}return[...n]}function ju(e){e.identicalSuccessfulToolResults.clear();for(let t of[...e.identicalCallCounts.keys()]){let n=t.slice(0,t.indexOf("::"));lo.has(n)&&e.identicalCallCounts.delete(t)}}async function*pi(e,t,n,o){let{turnId:r,sessionId:s,messages:i,availableTools:a,tools:c,model:f,apiKey:g,temperature:y=0,hooks:k,signal:x}=e,_={sessionId:s,turnId:r},v=e.maxTurns??0,S=e.querySource,M=e.runtimePorts.resolveToolEligibility(c,e.toolEligibilityContext),N=M.eligibleTools,D=[];for(let m of M.blockedTools)D.push({name:m.toolName,reason:"blocked-by-policy"}),yield{type:"tool_blocked",turnId:r,callId:"",name:m.toolName,reason:"blocked-by-policy"};let z=ls(e.maxRounds,i),se=cs(e.maxToolCalls,i),qt=!(typeof e.maxRounds=="number"&&e.maxRounds>=1)&&!(typeof e.maxToolCalls=="number"&&e.maxToolCalls>=1),Co=Mt(i),Fe={contextWindowTokens:e.contextWindowTokens??dr,responseBufferTokens:fr,maxOutputTokens:e.maxOutputTokens??pr,abortSignal:x,reactiveCompactEnabled:!0,outputEscalationEnabled:!0},L=new Set,F=0,ko=new Set,Ro=0,Ge=0,We=0,lt=0,xo=new Map,_o=new Set,Z=new Set,b=ke(N,Z),Ve=!1,Gt=!1,Wt,Vt=()=>R(b),Ti=Ec(N,i),Xt=!1,vo=0,Ao=0,wo=0,So=0,U=!1,ct=!1,Kt=Lu(i),u={messages:[...i],maxOutputTokensRecoveryCount:0,hasAttemptedReactiveCompact:!1,maxOutputTokensOverride:void 0,turnCount:1,transition:void 0,guardState:In(Fe),reactiveCompactState:Fn(),toolLoopState:vt({maxRounds:z,replayMessages:[...i]}).state,consecutiveFailedRounds:0,finalText:"",totalUsage:{inputTokens:0,outputTokens:0},collapseStore:bn(),currentModel:f,consecutive529Errors:0,consecutiveApiRetries:0,stopHookActive:void 0,lastResponseId:void 0,snipRemovedIds:new Set,contentReplacementState:e.runtimePorts.createContentReplacementState(),budgetContinuationCount:0,repeatedToolFailureRecoveryCount:0,lastBudgetDeltaTokens:0,lastBudgetGlobalTokens:0,identicalCallCounts:new Map,identicalSuccessfulToolResults:new Map,toolFailureCounts:new Map,fileReadCounts:Kt.fileReadCounts,fileReadCycleBlockedPaths:new Set,fileReadCycleNudgedPaths:new Set,maintainedDocuments:Kt.maintainedDocuments,persistedLongHorizonStateRecovered:Kt.persistedLongHorizonStateRecovered,longHorizonStateMaintenanceRequiredFiles:new Set,longHorizonStateMaintenanceWrittenFiles:new Set,recoveryTrace:new Map,artifactContract:Xr(i),browserAcceptanceRecoveryCount:0,buildVerificationRecoveryCount:0,longHorizonStateIntegrityRecoveryCount:0,backgroundAgentTaskIds:new Set,backgroundAgentNoOutputPollCounts:new Map,stalledBackgroundAgentTasks:new Map,notOfferedToolRecoveryCount:0,existingFileUpdateRecoveryCount:0,taskListReconciliationCount:0,lastTaskList:[]},Yt=Math.max(v*5,200),Ci=4,ki=4,Eo=0,Mo=new Map,Zt,E=(m,q)=>{let K=`${m}:${q??""}`,ce=(Mo.get(K)??0)+1;if(Mo.set(K,ce),m==="autocompact"){let j=u.recoveryTrace.get("autocompact")??0;if(ce>Ci||j>=ki){let ee=`Repeated context compression made no forward progress: ${q??"autocompact"}`;return Zt=ee,u.recoveryTrace.set("compression_loop_guard",(u.recoveryTrace.get("compression_loop_guard")??0)+1),{type:"recovery",turnId:r,action:"compression_loop_guard",detail:ee}}}return u.recoveryTrace.set(m,(u.recoveryTrace.get(m)??0)+1),{type:"recovery",turnId:r,action:m,detail:q}},Ri=()=>({type:"tool_use_summary",turnId:r,availableToolNames:R(a??c),enabledToolNames:Vt(),toolCallNames:[...L].sort(),blockedToolCalls:Ft(D)}),Io=zr((a??c).map(m=>m.function.name)),Jt=!1,xi=Kr(i),_i=m=>({type:"end",turnId:r,content:m,usage:u.totalUsage,model:u.currentModel,...u.recoveryTrace.size>0?{recoveryTrace:Object.fromEntries(u.recoveryTrace)}:{}});function*H(m,q){let K=Yr({content:m,contractActive:Io,totalToolCallCount:F,distinctToolNames:L,visibleToolCallCount:Ro,visibleToolNames:ko,artifactContract:u.artifactContract,blockedToolCalls:Ft(D),activeTasks:u.lastTaskList,forcedStop:q?.forcedStop??Jt,locale:xi});K.malformedBlock&&(yield E("final_status_block_malformed","final-status block was not valid schema-1 JSON; treated as absent")),Hn(u.artifactContract,K.content),en()&&(yield Qt()),yield Ri(),yield _i(K.content)}let Qt=()=>({type:"artifact_contract",turnId:r,...zn(u.artifactContract,i)}),en=()=>{let m=zn(u.artifactContract,i);return!!(m.requiresBrowserAcceptance||m.artifactRoot||m.writePaths.length>0||m.outOfRootWrites.length>0||m.devServerUrls.length>0||m.browserVerified)},Xe=(m,q,K)=>K?.cleanStopWithFinalText&&u.finalText?u.finalText:(Jt=!0,u.finalText||Vn(m,o)),vi=(m,q,K)=>{Jt=!0;let ce=Oe({inputMessages:i,messages:q,reason:K});return ce||m||Vn(q,o)};for(;;){if(Eo++,Eo>Yt){o.info(`hard iteration cap reached (${Yt}), forcing completion`);let l=Xe(u.messages,`hard iteration cap reached (${Yt}) before completing the final status contract`);yield*H(l);return}let{messages:m,maxOutputTokensRecoveryCount:q,maxOutputTokensOverride:K,turnCount:ce,guardState:j,reactiveCompactState:ee,collapseStore:tn}=u,{toolLoopState:te}=u;if(e.refreshTools){let l=e.refreshTools(),d=ke(l,Z);d!==b&&(b=d,o.debug(`tools refreshed: ${l.length} tools`))}if(e.drainPendingGuidance)for(let l of e.drainPendingGuidance()){let d=l.trim();d&&(m.push({role:"user",content:d}),o.info(`mid-turn guidance injected (${d.length} chars)`))}if(Ln(j,Fe)){o.info(`turn aborted by guard at turn ${ce}`),yield{type:"error",turnId:r,error:"Turn aborted",code:"ABORTED",usage:u.totalUsage};return}let ye=Pn(j,Fe);if(ye.level==="blocking"){ye.reason==="prompt_too_long"&&Ue(ee)&&(ee.attemptedThisTurn=!0,j.hasAttemptedReactiveCompact=!0,o.info(`token budget blocking (${ye.reason}), reactive compact needed`),yield E("reactive_compact","token budget pre-check")),o.info(`token budget blocking (${ye.reason}), ending tool loop`);let l=Xe(u.messages,`token budget exhausted (${ye.reason}) before the request could be completed`);yield*H(l);return}ye.level==="warning"&&o.info(`token budget warning: ${ye.usagePercent}% used, ${ye.remainingTokens} remaining`);let ut=yield*ys({messages:m,contentReplacementState:u.contentReplacementState,snipRemovedIds:u.snipRemovedIds,collapseStore:tn,guardState:j,guardConfig:Fe,runtimePorts:e.runtimePorts,hooks:k,hookCtx:_,sessionId:s,currentModel:u.currentModel,log:o,recovery:E,onAutocompact:()=>{u.hasAttemptedReactiveCompact=!1}});if(Zt){yield*H(`${Zt}. Stop compressing the same context repeatedly; continue from the maintained document index or report the incomplete state explicitly.`,{forcedStop:!0});return}let Ai=U?"required":e.toolChoice==="required"&&Xt?"auto":e.toolChoice??"auto";U=!1;let Ke=xn({tools:b,toolChoice:Ai}),Po=R(Ke.tools).join("\0"),Oo=Wt!==void 0&&Wt!==Po;Oo&&u.lastResponseId&&(yield E("stateless_retry","tool schema changed; replaying full history without previous_response_id"));let wi=ct||Oo?void 0:u.lastResponseId;Wt=Po;let Ye=vt({maxRounds:z,replayMessages:ut,lastStopReason:te.lastStopReason,options:{stopReason:te.lastStopReason}}),No=[Ke.extraSystemPrompt,Io?Hr:void 0].filter(l=>!!l).join(`
|
|
42
42
|
|
|
43
|
-
`),Oo=Po?[{role:"system",content:Po},...Xe.state.replayMessages]:Xe.state.replayMessages;te=Xe.state,Xe.recoveryActions.length>0&&o.debug(`tool loop recovery: ${Xe.recoveryActions.map(l=>l.detail??l.kind).join("; ")}`),o.debug(`turn ${ie}, messages: ${Oo.length}`),$(C,"turn.before_inference",{...v,model:u.currentModel},o);let en=!1,ct=[],No=new Map,Lo="stop",ne,I=null,ut=!1,Fo=!1,Ke=[],ce=[];try{let l=t.stream({model:u.currentModel,messages:Oo,...Ve.tools.length>0?{tools:Ve.tools,toolChoice:Ve.normalizedToolChoice??"auto"}:{},temperature:y,maxTokens:(Q??j.currentMaxOutputTokens)||void 0,streamRequired:e.streamRequired,previousResponseId:Ri,reasoning:e.reasoning,promptCacheKey:e.promptCacheKey,promptCacheRetention:e.promptCacheRetention,serviceTier:e.serviceTier,openaiBuiltinTools:e.openaiBuiltinTools,maxToolCalls:e.maxToolCalls,parallelToolCalls:e.parallelToolCalls,textVerbosity:e.textVerbosity},h,x);for await(let d of gu(l,e.llmStreamIdleTimeoutMs??nu))switch(d.type){case"delta":ct.push(d.text);break;case"tool_call_delta":en=!0,Ln(No,d);break;case"reasoning_delta":Ke.push(d.text);break;case"reasoning_block_complete":d.signature&&ce.push({thinking:Ke.join(""),signature:d.signature}),Ke.length=0;break;case"usage":ne={inputTokens:d.promptTokens,outputTokens:d.completionTokens,reasoningTokens:d.reasoningTokens,cacheRead:d.cacheReadTokens,cacheWrite:d.cacheCreationTokens};break;case"response_id":it||(u.lastResponseId=d.id);break;case"annotations":yield{type:"annotations",turnId:r,annotations:d.annotations};break;case"builtin_tool_status":yield{type:"heartbeat",turnId:r,message:`${d.toolType}: ${d.event}`};break;case"done":Fo=!0,Lo=d.finishReason;break}if(en||$(C,"turn.after_inference",{...v,model:u.currentModel},o),e.postSamplingHooks&&e.postSamplingHooks.length>0){let d=u.currentModel;for(let g of e.postSamplingHooks)try{g({messages:[...lt],model:d,sessionId:s})}catch{}}}catch(l){if(l instanceof $t){$(C,"stop.failure",{sessionId:s,reason:l.code,error:l.message},o),yield{type:"error",turnId:r,error:l.message,code:l.code,usage:u.totalUsage};return}let d=yield*ms(l,{state:u,guardState:j,fallbackModel:e.fallbackModel,signal:x,querySource:P,turnId:r,log:o,emitRecovery:M});if(d.kind==="return")return;if(d.kind==="continue"){u={...u,...d.patch};continue}I=d.streamError}if(!I&&!Fo){let l="LLM stream closed before a terminal event; the response was likely truncated upstream.";$(C,"stop.failure",{sessionId:s,reason:"RETRYABLE_TRANSIENT",error:l},o),yield{type:"error",turnId:r,error:l,code:"RETRYABLE_TRANSIENT",usage:u.totalUsage};return}if(I&&$(C,"turn.after_inference",{...v,model:u.currentModel,response:{error:I.message}},o),I){if(!it&&u.lastResponseId&&/previous_response_id not found/i.test(I.message)){let l=(u.consecutiveApiRetries??0)+1;if(l<=we){o.info("previous_response_id not found \u2014 disabling response-id chaining, retrying statelessly"),yield M("stateless_retry","previous_response_id not found; replaying full history"),it=!0,u={...u,lastResponseId:void 0,consecutiveApiRetries:l,transition:void 0};continue}}if(Kn(I))ut=!0,o.info(`withheld prompt_too_long error (status=${I.status})`);else if(Yn(I))ut=!0,o.info(`withheld media_size error (status=${I.status})`);else{let l=In({status:I.status??500,message:I.message},j,Le);if(l.action==="reactive_compact"&&$e(ee)&&(ee.attemptedThisTurn=!0,j.hasAttemptedReactiveCompact=!0,yield M("reactive_compact",`API ${I.status??500}: ${I.message}`)),l.action==="retry"){let g=(u.consecutiveApiRetries??0)+1;if(g>we){o.info(`API retry limit reached (${we}), aborting`);let T=De(I.status,I.message);yield{type:"error",turnId:r,error:I.message,code:T,usage:u.totalUsage};return}yield M("retry",l.reason),u={...u,consecutiveApiRetries:g,transition:void 0};continue}let d=De(I.status,I.message);$(C,"stop.failure",{sessionId:s,reason:d,error:I.message},o),yield{type:"error",turnId:r,error:I.message,code:d,usage:u.totalUsage};return}}ne&&(u.totalUsage.inputTokens+=ne.inputTokens,u.totalUsage.outputTokens+=ne.outputTokens,ne.reasoningTokens&&(u.totalUsage.reasoningTokens=(u.totalUsage.reasoningTokens??0)+ne.reasoningTokens),ne.cacheRead&&(u.totalUsage.cacheRead=(u.totalUsage.cacheRead??0)+ne.cacheRead),ne.cacheWrite&&(u.totalUsage.cacheWrite=(u.totalUsage.cacheWrite??0)+ne.cacheWrite)),ne?.inputTokens&&(j.promptTokens=ne.inputTokens);let me=ct.join(""),oe=[...No.values()].map((l,d)=>({id:l.id||`tc_${r}_${d}`,type:"function",function:{name:l.name,arguments:l.arguments}}));if(oe=hu(oe),oe.length===0&&!en){me&&(u.finalText=me);let l=je([...b,...a??c]),d=e.toolChoice==="none"?null:Is({text:me,enabledToolNames:k(l)});if(d&&Ro<2){if(Ro++,!new Set(b.map(N=>N.function.name)).has(d.toolName)){let N=(a??c).filter(re=>re.function.name===d.toolName);if(N.length>0){let re=k(b),he=new Map(b.map(_=>[_.function.name,_]));for(let _ of N)he.set(_.function.name,_);b=je([...he.values()]),yield{type:"tool_selection_policy",turnId:r,policyId:"available_tool_reenabled_after_pseudo_output",intent:"tool_recovery",reason:"pseudo-tool-output-named-available-tool",availableToolNames:k(a??c),enabledToolNamesBefore:re,enabledToolNamesAfter:k(b),suppressedToolNames:[],nextAction:"retry-with-native-tool-call"}}}u={...u,messages:[...m,{role:"assistant",content:me},{role:"user",content:`Your last response printed a pseudo tool invocation for ${d.toolName} instead of making a real tool call. Do not write XML tags, function-call prose, or placeholder tool syntax. Call the real ${d.toolName} tool now using the native tool-call channel, or explain why it cannot be used.`}],finalText:"",transition:{reason:"next_turn"}},U=!0,yield M("pseudo_tool_output_retry",d.toolName);continue}if(e.toolChoice==="required"&&!Wt&&b.length>0&&ko<2){ko++;let R=b.map(N=>N.function.name).filter(Boolean).slice(0,8).join(", ");u={...u,messages:[...m,{role:"user",content:`You must call one available tool before answering. Available tools for this request: ${R}. Do not answer from memory, prior context, or guesses.`}],finalText:"",transition:{reason:"next_turn"}};continue}if(ut&&I&&Kn(I)){if(u.transition?.reason!=="collapse_drain_retry"){let R=bn(lt,Qt);if(R.committed>0){o.info(`collapse drain: committed ${R.committed} stages`),yield M("collapse_drain",`${R.committed} stages committed`),u={...u,messages:R.messages,transition:{reason:"collapse_drain_retry",committed:R.committed}};continue}}if($e(ee)){ee.attemptedThisTurn=!0,j.hasAttemptedReactiveCompact=!0,o.info("withheld 413: reactive compact attempt"),yield M("reactive_compact","withheld prompt_too_long"),u={...u,hasAttemptedReactiveCompact:!0,transition:{reason:"reactive_compact_retry"}};continue}o.info("withheld 413: recovery exhausted, surfacing error"),$(C,"stop.failure",{sessionId:s,reason:"prompt_too_long",error:I.message},o),yield{type:"error",turnId:r,error:I.message,code:"PROMPT_TOO_LONG",usage:u.totalUsage};return}if(ut&&I&&Yn(I)){if($e(ee)){ee.attemptedThisTurn=!0,j.hasAttemptedReactiveCompact=!0,o.info("withheld media error: reactive compact strip-retry"),yield M("reactive_compact","media error strip-retry"),u={...u,hasAttemptedReactiveCompact:!0,transition:{reason:"reactive_compact_retry"}};continue}o.info("withheld media error: recovery exhausted"),$(C,"stop.failure",{sessionId:s,reason:"media_error",error:I.message},o),yield{type:"error",turnId:r,error:I.message,code:"IMAGE_ERROR",usage:u.totalUsage};return}if(us(Lo)){j.consecutiveTruncations+=1;let R=e.modelMaxOutputTokens??mr,N=Pn(j,Le,R);if(N.shouldEscalate&&Q===void 0){j.currentMaxOutputTokens=N.newMax,o.info(`max_output_tokens escalate: ${N.newMax} tokens`),yield M("output_escalation",`${N.newMax} tokens`),u={...u,maxOutputTokensOverride:hr,transition:{reason:"max_output_tokens_escalate"}};continue}if(z<gr){let re={role:"user",content:"Output token limit hit. Resume directly - no apology, no recap of what you were doing. Pick up mid-thought if that is where the cut happened. Break remaining work into smaller pieces."};o.info(`max_output_tokens recovery #${z+1}`),yield M("max_output_tokens_recovery",`attempt ${z+1}`),u={...u,messages:[...lt,re],maxOutputTokensRecoveryCount:z+1,maxOutputTokensOverride:void 0,transition:{reason:"max_output_tokens_recovery",attempt:z+1}};continue}o.info("max_output_tokens recovery exhausted, completing with partial content")}else j.consecutiveTruncations=0;te=Rt(te,{replayMessages:m,lastStopReason:"completed"});let g=await Ms({hooks:C,sessionId:s,messages:m,finalText:u.finalText,thinkingBlocks:ce,log:o});if(g?.action==="end"){let R=Ci(g.content,m,"stop hook prevented continuation before completing the final status contract");yield*W(R);return}if(g?.action==="continue"){u={...u,messages:g.messages,stopHookActive:g.stopHookActive,transition:g.transition};continue}let T=Es({tokenBudget:e.tokenBudget,totalUsage:u.totalUsage,budgetContinuationCount:u.budgetContinuationCount,lastBudgetDeltaTokens:u.lastBudgetDeltaTokens,lastBudgetGlobalTokens:u.lastBudgetGlobalTokens,messages:m,finalText:u.finalText,thinkingBlocks:ce,getBudgetContinuationMessage:e.runtimePorts.getBudgetContinuationMessage,log:o});if(T){yield M("budget_continuation",T.recoveryDetail),u={...u,messages:T.messages,budgetContinuationCount:T.budgetContinuationCount,lastBudgetDeltaTokens:T.lastBudgetDeltaTokens,lastBudgetGlobalTokens:T.lastBudgetGlobalTokens,transition:T.transition};continue}if(u.finalText.trim()&&jc(u.lastTaskList)&&u.taskListReconciliationCount<1){let R=b.find(N=>N.function.name==="task")??(a??c).find(N=>N.function.name==="task");if(R){let N=Uc(u.lastTaskList),re=k(b),he=Te(O,Y);b=he.some(_=>_.function.name==="task")?he:je([...he,R]),u={...u,taskListReconciliationCount:u.taskListReconciliationCount+1,messages:[...m,{role:"assistant",content:u.finalText},{role:"user",content:N}],transition:{reason:"next_turn"}},U=!0,yield{type:"tool_selection_policy",turnId:r,policyId:"task_list_reconciliation_required",intent:"lifecycle_reconciliation",reason:"task-list-final-status-mismatch",availableToolNames:k(a??c),enabledToolNamesBefore:re,enabledToolNamesAfter:k(b),suppressedToolNames:[],nextAction:"reconcile-task-list-before-final"},yield M("task_list_reconciliation_required","nudging task-list status sync before the final response");continue}}if(de(i)&&!u.artifactContract.browserVerified&&Dt(u.artifactContract).length>0&&b.some(R=>R.function.name==="exec")&&u.browserAcceptanceRecoveryCount<4){let R=Xs(u.artifactContract);u={...u,browserAcceptanceRecoveryCount:u.browserAcceptanceRecoveryCount+1,messages:[...m,{role:"assistant",content:u.finalText},{role:"user",content:R}],transition:{reason:"next_turn"}},U=!0,yield M("browser_acceptance_required","forcing browser automation before app/frontend completion");continue}if((e.buildVerificationGate??!0)&&jr(i)&&!u.artifactContract.buildVerified&&u.artifactContract.buildFailureEvidence.length>0&&b.some(R=>R.function.name==="exec")&&u.buildVerificationRecoveryCount<3){let R=Fc(u.artifactContract);u={...u,buildVerificationRecoveryCount:u.buildVerificationRecoveryCount+1,messages:[...m,{role:"assistant",content:u.finalText},{role:"user",content:R}],transition:{reason:"next_turn"}},U=!0,yield M("build_verification_required","test/build still failing; forcing a fix+rerun before completion");continue}let p=to({inputMessages:i,messages:m,finalText:u.finalText,thinkingBlocks:ce,stopHookActive:u.stopHookActive,totalToolCallCount:F,distinctToolNames:L,log:o});if(p){if(u.stopHookActive&&u.finalText.trim()===""){let R=Pe({inputMessages:i,messages:p.messages,reason:"stop hook produced an empty response after tool use"});if(R){yield*W(R,{forcedStop:!0});return}}u={...u,messages:p.messages,stopHookActive:p.stopHookActive,transition:p.transition};continue}if(F===0&&b.length>0&&e.toolChoice!=="none"&&xo<1&&ss(me)){xo++,U=!0,yield M("intent_without_action","announced but did not act; forcing a tool call"),u={...u,messages:[...m,{role:"assistant",content:me},{role:"user",content:"You announced an action but did not take it. Carry it out NOW, in this response: call the appropriate tool to actually do what you just said you would do. Do not restate your intention or describe a plan \u2014 perform it."}],finalText:"",transition:{reason:"next_turn"}};continue}let w=no({totalToolCallCount:F,distinctToolNames:L,projectRoot:e.projectRoot});w&&(yield{type:"skill_instruction",turnId:r,instruction:w});let H=at(m,"the model ended with an empty response after tool use before completing the final status contract");for(let R of ct)yield{type:"delta",turnId:r,text:R};yield*W(H);return}let xi=ce.length===0&&Ke.length>0?Ke.join(""):void 0;if(me)for(let l of ct)yield{type:"delta",turnId:r,text:l};m.push(fn(oe,me||void 0,ce.length>0?ce:void 0,xi)),te=An(te,{replayMessages:m,pendingToolCallIds:oe.map(l=>l.id),completedToolCallIds:te.completedToolCallIds,lastStopReason:"tool_calls"});let dt=u.identicalCallCounts,Ye=[],ue=[],Ze=[],Bo=!1;for(let l of oe){if(Xc(l,u)){Ye.push(l);continue}let d=`${l.function.name}::${l.function.arguments}`,g=dt.get(d)??0;if(dt.set(d,g+1),g+1>ur){let T=io.has(l.function.name)||l.function.name==="exec"?u.identicalSuccessfulToolResults.get(d):void 0;if(T){Ze.push({call:l,result:T,repeatCount:g+1});continue}ue.push(l),Bo||(Bo=!0,o.info(`AP4 blocked: ${l.function.name} repeated ${g+1}x`))}else Ye.push(l)}let V=[],_i=new Set(b.map(l=>l.function.name)),Do=new Set(ue.filter(l=>Au(l,_i)).map(l=>l.id));for(let l of Ze){let d=l.call,g=`Reused previous successful ${d.function.name} result for identical arguments (attempt ${l.repeatCount}); no additional tool execution was performed.
|
|
43
|
+
`),Lo=No?[{role:"system",content:No},...Ye.state.replayMessages]:Ye.state.replayMessages;te=Ye.state,Ye.recoveryActions.length>0&&o.debug(`tool loop recovery: ${Ye.recoveryActions.map(l=>l.detail??l.kind).join("; ")}`),o.debug(`turn ${ce}, messages: ${Lo.length}`),$(k,"turn.before_inference",{..._,model:u.currentModel},o);let nn=!1,dt=[],Fo=new Map,Bo="stop",ne,P=null,ft=!1,Do=!1,Ze=[],ue=[];try{let l=t.stream({model:u.currentModel,messages:Lo,...Ke.tools.length>0?{tools:Ke.tools,toolChoice:Ke.normalizedToolChoice??"auto"}:{},temperature:y,maxTokens:(K??j.currentMaxOutputTokens)||void 0,streamRequired:e.streamRequired,previousResponseId:wi,reasoning:e.reasoning,promptCacheKey:e.promptCacheKey,promptCacheRetention:e.promptCacheRetention,serviceTier:e.serviceTier,openaiBuiltinTools:e.openaiBuiltinTools,maxToolCalls:e.maxToolCalls,parallelToolCalls:e.parallelToolCalls,textVerbosity:e.textVerbosity},g,x);for await(let d of Tu(l,e.llmStreamIdleTimeoutMs??iu))switch(d.type){case"delta":dt.push(d.text);break;case"tool_call_delta":nn=!0,Bn(Fo,d);break;case"reasoning_delta":Ze.push(d.text);break;case"reasoning_block_complete":d.signature&&ue.push({thinking:Ze.join(""),signature:d.signature}),Ze.length=0;break;case"usage":ne={inputTokens:d.promptTokens,outputTokens:d.completionTokens,reasoningTokens:d.reasoningTokens,cacheRead:d.cacheReadTokens,cacheWrite:d.cacheCreationTokens};break;case"response_id":ct||(u.lastResponseId=d.id);break;case"annotations":yield{type:"annotations",turnId:r,annotations:d.annotations};break;case"builtin_tool_status":yield{type:"heartbeat",turnId:r,message:`${d.toolType}: ${d.event}`};break;case"done":Do=!0,Bo=d.finishReason;break}if(nn||$(k,"turn.after_inference",{..._,model:u.currentModel},o),e.postSamplingHooks&&e.postSamplingHooks.length>0){let d=u.currentModel;for(let h of e.postSamplingHooks)try{h({messages:[...ut],model:d,sessionId:s})}catch{}}}catch(l){if(l instanceof jt){$(k,"stop.failure",{sessionId:s,reason:l.code,error:l.message},o),yield{type:"error",turnId:r,error:l.message,code:l.code,usage:u.totalUsage};return}let d=yield*bs(l,{state:u,guardState:j,fallbackModel:e.fallbackModel,signal:x,querySource:S,turnId:r,log:o,emitRecovery:E});if(d.kind==="return")return;if(d.kind==="continue"){u={...u,...d.patch};continue}P=d.streamError}if(!P&&!Do){let l="LLM stream closed before a terminal event; the response was likely truncated upstream.";$(k,"stop.failure",{sessionId:s,reason:"RETRYABLE_TRANSIENT",error:l},o),yield{type:"error",turnId:r,error:l,code:"RETRYABLE_TRANSIENT",usage:u.totalUsage};return}if(P&&$(k,"turn.after_inference",{..._,model:u.currentModel,response:{error:P.message}},o),P){if(!ct&&u.lastResponseId&&/previous_response_id not found/i.test(P.message)){let l=(u.consecutiveApiRetries??0)+1;if(l<=Se){o.info("previous_response_id not found \u2014 disabling response-id chaining, retrying statelessly"),yield E("stateless_retry","previous_response_id not found; replaying full history"),ct=!0,u={...u,lastResponseId:void 0,consecutiveApiRetries:l,transition:void 0};continue}}if(Zn(P))ft=!0,o.info(`withheld prompt_too_long error (status=${P.status})`);else if(Jn(P))ft=!0,o.info(`withheld media_size error (status=${P.status})`);else{let l=On({status:P.status??500,message:P.message},j,Fe);if(l.action==="reactive_compact"&&Ue(ee)&&(ee.attemptedThisTurn=!0,j.hasAttemptedReactiveCompact=!0,yield E("reactive_compact",`API ${P.status??500}: ${P.message}`)),l.action==="retry"){let h=(u.consecutiveApiRetries??0)+1;if(h>Se){o.info(`API retry limit reached (${Se}), aborting`);let T=$e(P.status,P.message);yield{type:"error",turnId:r,error:P.message,code:T,usage:u.totalUsage};return}yield E("retry",l.reason),u={...u,consecutiveApiRetries:h,transition:void 0};continue}let d=$e(P.status,P.message);$(k,"stop.failure",{sessionId:s,reason:d,error:P.message},o),yield{type:"error",turnId:r,error:P.message,code:d,usage:u.totalUsage};return}}ne&&(u.totalUsage.inputTokens+=ne.inputTokens,u.totalUsage.outputTokens+=ne.outputTokens,ne.reasoningTokens&&(u.totalUsage.reasoningTokens=(u.totalUsage.reasoningTokens??0)+ne.reasoningTokens),ne.cacheRead&&(u.totalUsage.cacheRead=(u.totalUsage.cacheRead??0)+ne.cacheRead),ne.cacheWrite&&(u.totalUsage.cacheWrite=(u.totalUsage.cacheWrite??0)+ne.cacheWrite)),ne?.inputTokens&&(j.promptTokens=ne.inputTokens);let oe=dt.join(""),re=[...Fo.values()].map((l,d)=>({id:l.id||`tc_${r}_${d}`,type:"function",function:{name:l.name,arguments:l.arguments}}));if(re=Cu(re),re.length===0&&!nn){if(e.drainPendingGuidance){let C=e.drainPendingGuidance().map(O=>O.trim()).filter(Boolean);if(C.length>0){u={...u,messages:[...m,...oe?[{role:"assistant",content:oe}]:[],...C.map(O=>({role:"user",content:O}))]},o.info(`late mid-turn guidance consumed at completion (${C.length} item(s)) \u2014 running another round`);continue}}oe&&(u.finalText=oe);let l=ze([...b,...a??c]),d=e.toolChoice==="none"?null:Ls({text:oe,enabledToolNames:R(l)});if(d&&Ao<2){if(Ao++,!new Set(b.map(O=>O.function.name)).has(d.toolName)){let O=(a??c).filter(be=>be.function.name===d.toolName);if(O.length>0){let be=R(b),ie=new Map(b.map(pe=>[pe.function.name,pe]));for(let pe of O)ie.set(pe.function.name,pe);b=ze([...ie.values()]),yield{type:"tool_selection_policy",turnId:r,policyId:"available_tool_reenabled_after_pseudo_output",intent:"tool_recovery",reason:"pseudo-tool-output-named-available-tool",availableToolNames:R(a??c),enabledToolNamesBefore:be,enabledToolNamesAfter:R(b),suppressedToolNames:[],nextAction:"retry-with-native-tool-call"}}}u={...u,messages:[...m,{role:"assistant",content:oe},{role:"user",content:`Your last response printed a pseudo tool invocation for ${d.toolName} instead of making a real tool call. Do not write XML tags, function-call prose, or placeholder tool syntax. Call the real ${d.toolName} tool now using the native tool-call channel, or explain why it cannot be used.`}],finalText:"",transition:{reason:"next_turn"}},U=!0,yield E("pseudo_tool_output_retry",d.toolName);continue}if(e.toolChoice==="required"&&!Xt&&b.length>0&&vo<2){vo++;let C=b.map(O=>O.function.name).filter(Boolean).slice(0,8).join(", ");u={...u,messages:[...m,{role:"user",content:`You must call one available tool before answering. Available tools for this request: ${C}. Do not answer from memory, prior context, or guesses.`}],finalText:"",transition:{reason:"next_turn"}};continue}if(ft&&P&&Zn(P)){if(u.transition?.reason!=="collapse_drain_retry"){let C=Cn(ut,tn);if(C.committed>0){o.info(`collapse drain: committed ${C.committed} stages`),yield E("collapse_drain",`${C.committed} stages committed`),u={...u,messages:C.messages,transition:{reason:"collapse_drain_retry",committed:C.committed}};continue}}if(Ue(ee)){ee.attemptedThisTurn=!0,j.hasAttemptedReactiveCompact=!0,o.info("withheld 413: reactive compact attempt"),yield E("reactive_compact","withheld prompt_too_long"),u={...u,hasAttemptedReactiveCompact:!0,transition:{reason:"reactive_compact_retry"}};continue}o.info("withheld 413: recovery exhausted, surfacing error"),$(k,"stop.failure",{sessionId:s,reason:"prompt_too_long",error:P.message},o),yield{type:"error",turnId:r,error:P.message,code:"PROMPT_TOO_LONG",usage:u.totalUsage};return}if(ft&&P&&Jn(P)){if(Ue(ee)){ee.attemptedThisTurn=!0,j.hasAttemptedReactiveCompact=!0,o.info("withheld media error: reactive compact strip-retry"),yield E("reactive_compact","media error strip-retry"),u={...u,hasAttemptedReactiveCompact:!0,transition:{reason:"reactive_compact_retry"}};continue}o.info("withheld media error: recovery exhausted"),$(k,"stop.failure",{sessionId:s,reason:"media_error",error:P.message},o),yield{type:"error",turnId:r,error:P.message,code:"IMAGE_ERROR",usage:u.totalUsage};return}if(ms(Bo)){j.consecutiveTruncations+=1;let C=e.modelMaxOutputTokens??mr,O=Nn(j,Fe,C);if(O.shouldEscalate&&K===void 0){j.currentMaxOutputTokens=O.newMax,o.info(`max_output_tokens escalate: ${O.newMax} tokens`),yield E("output_escalation",`${O.newMax} tokens`),u={...u,maxOutputTokensOverride:hr,transition:{reason:"max_output_tokens_escalate"}};continue}if(q<gr){let be={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 #${q+1}`),yield E("max_output_tokens_recovery",`attempt ${q+1}`),u={...u,messages:[...ut,be],maxOutputTokensRecoveryCount:q+1,maxOutputTokensOverride:void 0,transition:{reason:"max_output_tokens_recovery",attempt:q+1}};continue}o.info("max_output_tokens recovery exhausted, completing with partial content")}else j.consecutiveTruncations=0;te=_t(te,{replayMessages:m,lastStopReason:"completed"});let h=await Os({hooks:k,sessionId:s,messages:m,finalText:u.finalText,thinkingBlocks:ue,log:o});if(h?.action==="end"){let C=vi(h.content,m,"stop hook prevented continuation before completing the final status contract");yield*H(C);return}if(h?.action==="continue"){u={...u,messages:h.messages,stopHookActive:h.stopHookActive,transition:h.transition};continue}let T=Ns({tokenBudget:e.tokenBudget,totalUsage:u.totalUsage,budgetContinuationCount:u.budgetContinuationCount,lastBudgetDeltaTokens:u.lastBudgetDeltaTokens,lastBudgetGlobalTokens:u.lastBudgetGlobalTokens,messages:m,finalText:u.finalText,thinkingBlocks:ue,getBudgetContinuationMessage:e.runtimePorts.getBudgetContinuationMessage,log:o});if(T){yield E("budget_continuation",T.recoveryDetail),u={...u,messages:T.messages,budgetContinuationCount:T.budgetContinuationCount,lastBudgetDeltaTokens:T.lastBudgetDeltaTokens,lastBudgetGlobalTokens:T.lastBudgetGlobalTokens,transition:T.transition};continue}if(u.finalText.trim()&&Gc(u.lastTaskList)&&u.taskListReconciliationCount<1){let C=b.find(O=>O.function.name==="task")??(a??c).find(O=>O.function.name==="task");if(C){let O=qc(u.lastTaskList),be=R(b),ie=ke(N,Z);b=ie.some(pe=>pe.function.name==="task")?ie:ze([...ie,C]),u={...u,taskListReconciliationCount:u.taskListReconciliationCount+1,messages:[...m,{role:"assistant",content:u.finalText},{role:"user",content:O}],transition:{reason:"next_turn"}},U=!0,yield{type:"tool_selection_policy",turnId:r,policyId:"task_list_reconciliation_required",intent:"lifecycle_reconciliation",reason:"task-list-final-status-mismatch",availableToolNames:R(a??c),enabledToolNamesBefore:be,enabledToolNamesAfter:R(b),suppressedToolNames:[],nextAction:"reconcile-task-list-before-final"},yield E("task_list_reconciliation_required","nudging task-list status sync before the final response");continue}}if(me(i)&&!u.artifactContract.browserVerified&&Ut(u.artifactContract).length>0&&b.some(C=>C.function.name==="exec")&&u.browserAcceptanceRecoveryCount<4){let C=Qs(u.artifactContract);u={...u,browserAcceptanceRecoveryCount:u.browserAcceptanceRecoveryCount+1,messages:[...m,{role:"assistant",content:u.finalText},{role:"user",content:C}],transition:{reason:"next_turn"}},U=!0,yield E("browser_acceptance_required","forcing browser automation before app/frontend completion");continue}if((e.buildVerificationGate??!0)&&jr(i)&&!u.artifactContract.buildVerified&&u.artifactContract.buildFailureEvidence.length>0&&b.some(C=>C.function.name==="exec")&&u.buildVerificationRecoveryCount<3){let C=jc(u.artifactContract);u={...u,buildVerificationRecoveryCount:u.buildVerificationRecoveryCount+1,messages:[...m,{role:"assistant",content:u.finalText},{role:"user",content:C}],transition:{reason:"next_turn"}},U=!0,yield E("build_verification_required","test/build still failing; forcing a fix+rerun before completion");continue}let p=oo({inputMessages:i,messages:m,finalText:u.finalText,thinkingBlocks:ue,stopHookActive:u.stopHookActive,totalToolCallCount:F,distinctToolNames:L,log:o});if(p){if(u.stopHookActive&&u.finalText.trim()===""){let C=Oe({inputMessages:i,messages:p.messages,reason:"stop hook produced an empty response after tool use"});if(C){yield*H(C,{forcedStop:!0});return}}u={...u,messages:p.messages,stopHookActive:p.stopHookActive,transition:p.transition};continue}if(F===0&&e.toolChoice!=="none"&&So<1&&as(oe)){So++;let C=R(a??c).join(", ");yield E("capability_denial_review","unverified capability denial; asking for verification or honest escalation"),u={...u,messages:[...m,{role:"assistant",content:oe},{role:"user",content:`Before declaring a capability missing, verify it. Your full tool list: [${C}]. If any tool there can fulfil the request \u2014 including exec running a script or OS command (e.g. PowerShell) \u2014 use it NOW. If community_seek is in the list, call it to look for an installable capability. Only if none of these can work, state plainly WHICH capability is missing and what the user could enable \u2014 do not just refuse.`}],finalText:"",transition:{reason:"next_turn"}};continue}if(F===0&&b.length>0&&e.toolChoice!=="none"&&wo<1&&is(oe)){wo++,U=!0,yield E("intent_without_action","announced but did not act; forcing a tool call"),u={...u,messages:[...m,{role:"assistant",content:oe},{role:"user",content:"You announced an action but did not take it. Carry it out NOW, in this response: call the appropriate tool to actually do what you just said you would do. Do not restate your intention or describe a plan \u2014 perform it."}],finalText:"",transition:{reason:"next_turn"}};continue}let w=ro({totalToolCallCount:F,distinctToolNames:L,projectRoot:e.projectRoot});w&&(yield{type:"skill_instruction",turnId:r,instruction:w});let G=Xe(m,"the model ended with an empty response after tool use before completing the final status contract",{cleanStopWithFinalText:!0});for(let C of dt)yield{type:"delta",turnId:r,text:C};yield*H(G);return}let Si=ue.length===0&&Ze.length>0?Ze.join(""):void 0;if(oe)for(let l of dt)yield{type:"delta",turnId:r,text:l};m.push(mn(re,oe||void 0,ue.length>0?ue:void 0,Si)),te=Sn(te,{replayMessages:m,pendingToolCallIds:re.map(l=>l.id),completedToolCallIds:te.completedToolCallIds,lastStopReason:"tool_calls"});let pt=u.identicalCallCounts,Je=[],de=[],Qe=[],$o=!1;for(let l of re){if(Jc(l,u)){Je.push(l);continue}let d=`${l.function.name}::${l.function.arguments}`,h=pt.get(d)??0;if(pt.set(d,h+1),h+1>ur){let T=lo.has(l.function.name)||l.function.name==="exec"?u.identicalSuccessfulToolResults.get(d):void 0;if(T){Qe.push({call:l,result:T,repeatCount:h+1});continue}de.push(l),$o||($o=!0,o.info(`AP4 blocked: ${l.function.name} repeated ${h+1}x`))}else Je.push(l)}let V=[],Ei=new Set(b.map(l=>l.function.name)),Uo=new Set(de.filter(l=>Mu(l,Ei)).map(l=>l.id));for(let l of Qe){let d=l.call,h=`Reused previous successful ${d.function.name} result for identical arguments (attempt ${l.repeatCount}); no additional tool execution was performed.
|
|
44
44
|
|
|
45
|
-
${l.result.content}`,T=X(d.id,{ok:!0,payload:g,imageUrls:l.result.imageUrls,toolReferences:l.result.toolReferences});m.push(T),V.push(d.id),L.add(d.function.name),F++,yield{type:"tool_result",turnId:r,callId:d.id,name:d.function.name,ok:!0,outputPreview:g.slice(0,2e3),durationMs:0,details:{type:d.function.name,reusedIdenticalCall:!0,repeatCount:l.repeatCount}}}if(Ze.some(l=>l.call.function.name==="exec"&&Ks(l.call.function.arguments))){let l=k(b);m.push({role:"user",content:$c(u.artifactContract)}),yield{type:"tool_selection_policy",turnId:r,policyId:"browser_verification_after_preparation_required",intent:"verification",reason:"repeated-browser-preparation-command",availableToolNames:k(a??c),enabledToolNamesBefore:l,enabledToolNamesAfter:l,suppressedToolNames:[],nextAction:"run-browser-verification-script-not-playwright-install"},yield M("browser_verification_after_preparation_required","reused successful browser preparation command")}for(let l of ue){D.push({name:l.function.name,reason:"identical-repeat-policy"});let d=dt.get(`${l.function.name}::${l.function.arguments}`),g=wt(m,l.function.name),T=Ic(g),p=Do.has(l.id)?wu(d,l):T?`This exact tool call has been attempted ${d} times. Last error: ${T}. Do not retry. Report this error to the user.`:`This exact tool call has been attempted ${d} times and keeps failing. Do not retry it. Report the issue to the user or try a completely different approach.`,w=X(l.id,{ok:!1,error:p});m.push(w),V.push(l.id),L.add(l.function.name),F++,yield{type:"tool_result",turnId:r,callId:l.id,name:l.function.name,ok:!1,error:p}}if(ue.length>0&&Ye.length===0&&Ze.length===0&&ue.every(l=>Do.has(l.id))&&u.existingFileUpdateRecoveryCount<2){let l=k(b);b=Hs(O,Y);let d=k(b);We=!0,U=!0;let g=[...new Set(ue.map(T=>Ut(T.function.arguments)).filter(T=>!!T))];m.push({role:"user",content:`Existing-file maintenance recovery: the same write call was repeatedly attempted for an existing file. Do not use write for these existing path(s): ${g.join(", ")||"(unknown)"}. Do not delete, remove, or recreate an existing file to make write succeed; that is artifact path drift, not maintenance. Use read only if you need the current contents, then use edit or patch for the smallest valid change. After the edit/patch succeeds, continue build/browser verification normally.`}),yield{type:"tool_selection_policy",turnId:r,policyId:"existing_file_update_recovery",intent:"tool_recovery",reason:"repeated-existing-file-write",availableToolNames:k(a??c),enabledToolNamesBefore:l,enabledToolNamesAfter:d,suppressedToolNames:ro(l,d),nextAction:"use-read-edit-or-patch-for-existing-file-update"},yield M("existing_file_update_recovery",g.join(",")||"unknown"),u={...u,messages:m,existingFileUpdateRecoveryCount:u.existingFileUpdateRecoveryCount+1,transition:{reason:"next_turn"}};continue}if(ue.length>0){let l=wt(m,ue[0].function.name),d={role:"user",content:"Tool calls were blocked because you repeated them with identical arguments too many times. "+(l?`The error was: "${l}". Tell the user about this error. `:"The operation is not working. ")+"Stop retrying and report the result to the user."};m.push(d)}let vi=yo>=3&&u.repeatedToolFailureRecoveryCount<1;if(ue.length>0&&Ye.length===0&&Ze.length===0&&!vi){let l=Ys(Wn(m,1),{availableToolNames:k(a??c),enabledToolNames:Gt(),toolCallNames:[...L].sort(),blockedToolCalls:Nt(D)});yield*W(l);return}let $o=[],tn=[];for(let l of Ye){let d=Wr({toolName:l.function.name,rawArguments:l.function.arguments});d?tn.push({call:l,...d}):$o.push(l)}for(let l of tn){let d=l.call;D.push({name:d.function.name,reason:"read-only-context-pack"}),m.push(X(d.id,{ok:!1,error:l.error})),V.push(d.id),L.add(d.function.name),F++,yield{type:"tool_result",turnId:r,callId:d.id,name:d.function.name,ok:!1,error:l.error},o.warn(`read-only context-pack blocked: ${d.function.name} ${l.path}`)}tn.length>0&&m.push({role:"user",content:"A write was blocked because context-pack is read-only evidence. Continue by writing compact indexes, checkpoints, and maintenance updates under benchmark-state; do not retry writes into context-pack."});let Ai=new Set(b.map(l=>l.function.name)),Uo=[],ft=[];for(let l of $o){let d=ci(l.function.name,l.function.arguments,Ai);d?ft.push({call:l,...d}):Uo.push(l)}for(let l of ft){let d=l.call;D.push({name:d.function.name,reason:"existing-file-update-tool-required"}),m.push(X(d.id,{ok:!1,error:l.error})),V.push(d.id),L.add(d.function.name),F++,yield{type:"tool_result",turnId:r,callId:d.id,name:d.function.name,ok:!1,error:l.error},o.info(`existing file update blocked: ${d.function.name} ${l.path}`)}if(ft.length>0){let l=k(b);b=Hs(O,Y);let d=k(b);We=!0,U=!0;let g=[...new Set(ft.map(T=>T.path))];m.push({role:"user",content:`Existing-file maintenance recovery: a write was blocked because the target file already exists and edit/patch are enabled. Do not use write for these existing path(s): ${g.join(", ")||"(unknown)"}. Do not delete, remove, or recreate an existing file to make write succeed; that is artifact path drift, not maintenance. Use read only if you need the current contents, then use edit or patch for the smallest valid change. After the edit/patch succeeds, continue build/browser verification normally.`}),yield{type:"tool_selection_policy",turnId:r,policyId:"existing_file_update_recovery",intent:"tool_recovery",reason:"existing-file-write-blocked",availableToolNames:k(a??c),enabledToolNamesBefore:l,enabledToolNamesAfter:d,suppressedToolNames:ro(l,d),nextAction:"use-read-edit-or-patch-for-existing-file-update"},yield M("existing_file_update_recovery",g.join(",")||"unknown"),u={...u,messages:m,existingFileUpdateRecoveryCount:u.existingFileUpdateRecoveryCount+1,transition:{reason:"next_turn"}};continue}let jo=[],nn=[];for(let l of Uo){let d=Gr({state:u.artifactContract,inputMessages:i,toolName:l.function.name,rawArguments:l.function.arguments});d?nn.push({call:l,...d}):jo.push(l)}for(let l of nn){let d=l.call;D.push({name:d.function.name,reason:"artifact-root-contract"}),$n(u.artifactContract,{path:l.path,artifactRoot:l.artifactRoot,toolName:d.function.name}),m.push(X(d.id,{ok:!1,error:l.error})),V.push(d.id),L.add(d.function.name),F++,yield{type:"tool_result",turnId:r,callId:d.id,name:d.function.name,ok:!1,error:l.error},Jt()&&(yield Zt()),o.warn(`artifact root contract blocked: ${d.function.name}`)}nn.length>0&&m.push({role:"user",content:"A write was blocked by the artifactRoot contract. Continue inside the declared artifactRoot, or stop with an honest final status that lists the root drift as Not done."});let qo=[],on=[];for(let l of jo){let d=ws({inputMessages:i,messages:m,toolCall:l});d?on.push({call:l,error:d}):qo.push(l)}for(let l of on){let d=l.call;D.push({name:d.function.name,reason:"premature-completion-artifact"}),m.push(X(d.id,{ok:!1,error:l.error})),V.push(d.id),L.add(d.function.name),F++,yield{type:"tool_result",turnId:r,callId:d.id,name:d.function.name,ok:!1,error:l.error},o.info(`premature completion artifact blocked: ${d.function.name}`)}on.length>0&&m.push({role:"user",content:"A tool attempted to write a completion artifact before all explicitly requested output files had evidence. Do not write final DONE markers or success reports into artifacts until the missing files are created or verified. If you cannot complete them, respond with the requested FAIL marker and the real reason."});let wi=new Set(b.map(l=>l.function.name)),zo=[],pt=[];for(let l of qo)wi.has(l.function.name)?zo.push(l):pt.push(l);for(let l of pt){let d=`Tool "${l.function.name}" was not offered for this turn and will not be executed. Use only the tools listed in the current request.`;D.push({name:l.function.name,reason:"not-offered"}),m.push(X(l.id,{ok:!1,error:d})),V.push(l.id),L.add(l.function.name),o.warn(`unoffered tool call suppressed: ${l.function.name}`)}if(pt.length>0&&u.notOfferedToolRecoveryCount<1){let l=[...new Set(pt.map(w=>w.function.name))].sort(),d=We&&l.includes("write"),g=l.filter(w=>Y.has(w)),p=(a??c).filter(w=>l.includes(w.function.name));if(g.length>0)u.notOfferedToolRecoveryCount+=1,U=!0,m.push({role:"user",content:`You retried ${g.map(w=>`\`${w}\``).join(", ")} after it was disabled by this turn's tool-selection policy. Do not retry policy-suppressed tools in this turn. Continue using only the currently enabled tools, or stop with a clear blocker.`}),yield{type:"tool_selection_policy",turnId:r,policyId:"policy_suppressed_tool_retry_blocked",intent:"tool_recovery",reason:"requested-tool-disabled-by-turn-policy",availableToolNames:k(a??c),enabledToolNamesBefore:k(b),enabledToolNamesAfter:k(b),suppressedToolNames:g,nextAction:"continue-with-currently-enabled-tools-or-report-blocker"},yield M("policy_suppressed_tool_retry_blocked",g.join(","));else if(!d&&p.length>0){let w=k(b),H=new Map(b.map(R=>[R.function.name,R]));for(let R of p)H.set(R.function.name,R);b=je([...H.values()]),u.notOfferedToolRecoveryCount+=1,U=!0,yield{type:"tool_selection_policy",turnId:r,policyId:"available_tool_reenabled_after_not_offered_call",intent:"tool_recovery",reason:"requested-tool-available-but-disabled",availableToolNames:k(a??c),enabledToolNamesBefore:w,enabledToolNamesAfter:k(b),suppressedToolNames:[],nextAction:"retry-with-reenabled-requested-tool"},m.push({role:"user",content:`You called ${l.map(R=>`\`${R}\``).join(", ")} but it was not enabled for that round even though it is available. The requested available tool has now been re-enabled. Use the re-enabled tool once with valid arguments; do not repeat a disabled-tool call.`}),yield M("available_tool_reenabled_after_not_offered_call",l.join(","))}}let Ho=[],rn=[];for(let l of zo){let d=b.find(T=>T.function.name===l.function.name),g=zc(d,l.function.arguments);g?rn.push({call:l,error:g}):Ho.push(l)}for(let l of rn){let d=l.call;D.push({name:d.function.name,reason:"invalid-arguments"}),m.push(X(d.id,{ok:!1,error:l.error})),V.push(d.id),L.add(d.function.name),F++,yield{type:"tool_result",turnId:r,callId:d.id,name:d.function.name,ok:!1,error:l.error,details:{type:d.function.name,error:"invalid_arguments"}},o.info(`invalid tool arguments blocked: ${d.function.name}`)}rn.length>0&&m.push({role:"user",content:"Some tool calls were blocked before execution because they did not match the tool schema. Do not retry the same tool with substituted fields. Use the required field names exactly, switch to the correct tool, or stop and report the invalid tool input."});let mt=[],sn=[];for(let l of Ho){if(l.function.name!=="exec"){mt.push(l);continue}let d=Gs(l.function.arguments);if(!d){mt.push(l);continue}let g=$s(d);Us(g)&&zs(O)?sn.push({call:l,error:qc(g)}):mt.push(l)}for(let l of sn){let d=l.call;D.push({name:d.function.name,reason:"dedicated-tool-required"});let g=k(b),T=b.filter(p=>["read","search"].includes(p.function.name));T.length>0&&(b=T,zt=!0,U=!0),m.push(X(d.id,{ok:!1,error:l.error})),V.push(d.id),L.add(d.function.name),F++,yield{type:"tool_result",turnId:r,callId:d.id,name:d.function.name,ok:!1,error:l.error,details:{type:d.function.name,error:"dedicated_tool_required",dedicatedTool:"read/search"}},o.info(`dedicated file tool preflight blocked: ${d.function.name}`),yield{type:"tool_selection_policy",turnId:r,policyId:"dedicated_file_tool_required",intent:"fresh_evidence",reason:"exec-file-read-search-list-blocked",availableToolNames:k(a??c),enabledToolNamesBefore:g,enabledToolNamesAfter:k(b),suppressedToolNames:g.filter(p=>!["read","search"].includes(p)),nextAction:"use-read-search-for-file-inspection-then-resume-build-run-verify-tools"}}sn.length>0&&m.push({role:"user",content:"Exec was blocked because it attempted local file reading/searching/listing. Use read/search for the next local file inspection step. After that, resume exec only for non-inspection commands such as installs, builds, dev servers, and verification scripts."});let gt=[],an=[],Go=[],Wo=[];for(let l of mt){if(l.function.name!=="exec"){gt.push(l);continue}let d=l,g=Gs(d.function.arguments),T=g?Nc(g):null;T&&(d={...d,function:{...d.function,arguments:Vs(d.function.arguments,T)}},Wo.push({originalCommand:g??"",rewrittenCommand:T}),g=T);let p=g?Lc(g):null;if(p?.action==="block")an.push({call:d,error:p.error});else if(p?.action==="rewrite"){let w={...d,function:{...d.function,arguments:Vs(d.function.arguments,p.command)}};Go.push({call:w,originalCommand:g??"",rewrittenCommand:p.command}),gt.push(w)}else gt.push(d)}for(let l of Wo)yield{type:"tool_selection_policy",turnId:r,policyId:"exec_sleep_prefix_guard",intent:"verification",reason:"sleep-prefix-removed",availableToolNames:k(a??c),enabledToolNamesBefore:k(b),enabledToolNamesAfter:k(b),suppressedToolNames:[],nextAction:"execute-command-without-blocking-sleep-prefix"},o.info(`blocking sleep prefix removed before exec: ${l.originalCommand} -> ${l.rewrittenCommand}`);for(let l of Go){let d=k(b);yield{type:"tool_selection_policy",turnId:r,policyId:"reserved_frontend_port_guard",intent:"verification",reason:"vite-strict-port-normalized",availableToolNames:k(a??c),enabledToolNamesBefore:d,enabledToolNamesAfter:k(b),suppressedToolNames:[],nextAction:"execute-normalized-vite-dev-server-command-with-strict-port"},o.info(`vite strict port normalized before exec: ${l.originalCommand} -> ${l.rewrittenCommand}`)}for(let l of an){let d=l.call;D.push({name:d.function.name,reason:"reserved-frontend-port"});let g=k(b);m.push(X(d.id,{ok:!1,error:l.error})),V.push(d.id),L.add(d.function.name),F++,yield{type:"tool_result",turnId:r,callId:d.id,name:d.function.name,ok:!1,error:l.error,details:{type:d.function.name,error:"reserved_frontend_port",reservedPort:Bt}},o.info(`reserved frontend port preflight blocked: ${d.function.name}`),yield{type:"tool_selection_policy",turnId:r,policyId:"reserved_frontend_port_guard",intent:"verification",reason:"reserved-frontend-port",availableToolNames:k(a??c),enabledToolNamesBefore:g,enabledToolNamesAfter:k(b),suppressedToolNames:[],nextAction:"restart-generated-dev-server-on-explicit-non-5174-port-with-strict-port"}}an.length>0&&m.push({role:"user",content:"A dev server command was blocked because it could occupy or fallback onto port 5174, which is reserved for the Xiaozhi Claw frontend. Retry with an explicit generated-app port other than 5174 and use --strictPort for Vite so browser evidence cannot be polluted."});let ht=[],Fe=[];for(let l of gt){if(l.function.name!=="read"){ht.push(l);continue}let d=lo(l.function.arguments);if(!d){ht.push(l);continue}let g=G(d),T=si(g);(u.fileReadCounts.get(g)??0)>=T?Fe.push({call:l,filePath:g,maxReads:T}):ht.push(l)}for(let l of Fe){let d=l.call,g=`Read cycle policy blocked another read of "${l.filePath}" after ${l.maxReads} successful reads in this turn. Stop rereading the same large document. ${so(l.filePath)}`;D.push({name:d.function.name,reason:"read-cycle-policy"}),u.fileReadCycleBlockedPaths.add(l.filePath),m.push(X(d.id,{ok:!1,error:g})),V.push(d.id),L.add(d.function.name),F++,yield{type:"tool_result",turnId:r,callId:d.id,name:d.function.name,ok:!1,error:g},o.info(`read cycle blocked: ${l.filePath}`)}if(Fe.length>0){let l=[...new Set(Fe.map(T=>`${T.filePath} (max ${T.maxReads})`))].join(", "),d=[...new Set(Fe.map(T=>so(T.filePath)))].join(" ");if(m.push({role:"user",content:`Further reads were blocked because these large/context documents already reached their per-turn read limit: ${l}. Do not retry the read with a different path spelling. ${d} Continue from maintained requirements/defects/decisions/acceptance evidence and report any truly missing section explicitly.`}),b.some(T=>Zs(T.function.name))&&(u.persistedBenchmarkStateRecovered||Fe.some(T=>po(T.filePath)))){let T=k(b),p=T.filter(w=>lu.has(w)).sort();yield{type:"tool_selection_policy",turnId:r,policyId:"long_horizon_benchmark_state_maintenance",intent:"benchmark_state_maintenance",reason:"read-cycle-guard-retains-evidence-tools",availableToolNames:k(a??c),enabledToolNamesBefore:T,enabledToolNamesAfter:k(b),suppressedToolNames:[],nextAction:"maintenance-or-final-answer"},m.push({role:"user",content:`Do not reread the blocked large/context document paths again. Evidence tools still enabled: ${p.join(", ")||"none"}. Use read/search only for targeted verification of generated artifacts, file names, and missing sections; use edit/patch/write only if benchmark-state maintenance needs an update; otherwise stop tool use and answer from the maintained benchmark-state evidence. Classify any unused edit/patch/write tools as not needed, not missing.`}),yield M("benchmark_state_maintenance_tool_bias","retaining targeted evidence tools after long-horizon read-cycle guard")}if(mu(D,u.fileReadCycleBlockedPaths,u.persistedBenchmarkStateRecovered,u.maintainedDocuments)){yield*W("Stopped repeated long-horizon context-pack rereads after the read-cycle guard blocked every maintained source document. Continue from benchmark-state/document-index.json, decision-state-table.json, and context-pack-evidence.json; do not reread or rewrite context-pack source documents.",{forcedStop:!0});return}}let ln=Os(ht,u.toolFailureCounts),cn=ln.allowed;if(qt&&cn.length>Math.max(0,se-F)){let l=Xn({currentToolBudget:se,currentRoundBudget:q,toolHardCap:100,roundHardCap:100,continuationCount:Ge,successfulSinceLastCheck:He-st,fileReadCounts:u.fileReadCounts,windowTools:be,windowRounds:25});l&&(se=l.nextToolBudget,q=l.nextRoundBudget,Ge=l.continuationCount,st=He,o.info(`tool budget continuation #${l.continuationCount}: tools\u2192${se}, rounds\u2192${q} (progress detected)`))}let Vo=Math.max(0,se-F),ge=Vo>0?cn.slice(0,Vo):[],un=cn.slice(ge.length),Si=un.length>0;if(ln.blocked.length>0){for(let l of ln.blocked){let d=l.call;D.push({name:d.function.name,reason:"variant-failure-policy"});let g=X(d.id,{ok:!1,error:l.error});m.push(g),V.push(d.id),L.add(d.function.name),F++,yield{type:"tool_result",turnId:r,callId:d.id,name:d.function.name,ok:!1,error:l.error},o.info(`variant tool blocked: ${d.function.name} failed ${l.failCount}x with different args`)}m.push(Ns())}if(un.length>0){let l=`Tool call budget exhausted (${se}) for this turn. Stop requesting more tools and report what remains incomplete.`;for(let d of un){D.push({name:d.function.name,reason:"tool-call-budget"});let g=X(d.id,{ok:!1,error:l});m.push(g),V.push(d.id),L.add(d.function.name),F++,yield{type:"tool_result",turnId:r,callId:d.id,name:d.function.name,ok:!1,error:l}}m.push({role:"user",content:`${l} You reached this turn's tool budget after ${Ge} extension(s). Do NOT claim the task is complete or that all files were created if it is not. Be honest in your reply: (1) state plainly the turn stopped before finishing; (2) list concretely what is DONE vs what is still UNFINISHED; (3) tell the user to reply "\u7EE7\u7EED" to finish the rest. If explicitly requested output files are still missing, respond with the requested FAIL marker and the real reason.`})}for(let l of ge){let d=l.function.arguments,g=b.find(T=>T.function.name===l.function.name);if(g?.backfillObservableInput)try{let T=JSON.parse(l.function.arguments),p={...T};g.backfillObservableInput(p),Object.keys(p).some(H=>!(H in T))&&(d=JSON.stringify(p))}catch{}yield{type:"tool_call",turnId:r,callId:l.id,name:l.function.name,arguments:d,inputSummary:Vn(d)},bo.add(l.function.name),To++}let Mi=new Map(u.toolFailureCounts),yt=null;try{let l=e.runtimePorts.createStreamingToolExecutor({toolInvoker:n,hooks:C,sessionId:s,turnId:r,log:o,signal:x,maxConcurrentTools:e?.maxConcurrentTools,maxExecutionMs:lr});for(let p of ge)l.addTool(p);let d=!1;for await(let p of l.getRemainingResults()){let w=Mc(p);if(w){if(D.push({name:p.toolName,reason:w}),p.toolName==="exec"&&w==="dedicated-tool-required"&&zs(O)){let _=k(b);m.push({role:"user",content:"Exec was blocked because it attempted local file reading/searching/listing. Use read/search for local file inspection. Exec remains available only for non-inspection commands such as installs, builds, dev servers, and verification scripts."}),yield{type:"tool_selection_policy",turnId:r,policyId:"dedicated_file_tool_required",intent:"fresh_evidence",reason:"exec-file-read-search-list-blocked",availableToolNames:k(a??c),enabledToolNamesBefore:_,enabledToolNamesAfter:k(b),suppressedToolNames:[],nextAction:"use-read-search-for-file-inspection-or-exec-for-build-run-verify"}}if(p.toolName==="exec"&&w==="confirmation-timeout"){let _=k(b);Y.add("exec");let E=Te(O,Y);E.length>0&&(b=je(E),U=!0),m.push({role:"user",content:"Exec confirmation timed out, so exec is disabled for the rest of this turn. Do not retry exec. Use read/search for inspection, edit/patch/write for file updates, ask_user only for missing user input, or stop with a clear blocker if no non-exec tool can complete the request."}),yield{type:"tool_selection_policy",turnId:r,policyId:"exec_confirmation_timeout_recovery",intent:"tool_recovery",reason:"exec-confirmation-timeout",availableToolNames:k(a??c),enabledToolNamesBefore:_,enabledToolNamesAfter:k(b),suppressedToolNames:ro(_,k(b)),nextAction:"continue-with-non-exec-tools-or-report-confirmation-blocker"}}if(p.toolName==="exec"&&w==="global-process-kill-blocked"){let _=k(b);m.push({role:"user",content:"Exec was blocked because it attempted to terminate every node process. Do not retry taskkill/killall/pkill/Stop-Process by process name. If a generated app server conflicts with another process, start the generated app on a new explicit non-5174 port with strict port behavior, or stop only an owned background task by its task id. Continue by verifying the app on the reachable generated-app URL."}),yield{type:"tool_selection_policy",turnId:r,policyId:"global_process_kill_recovery",intent:"verification",reason:"global-node-process-kill-blocked",availableToolNames:k(a??c),enabledToolNamesBefore:_,enabledToolNamesAfter:k(b),suppressedToolNames:[],nextAction:"use-owned-task-cancel-or-new-explicit-port"}}}p.blocked&&(yield{type:"tool_blocked",turnId:r,callId:p.callId,name:p.toolName,reason:p.blockReason??"blocked"}),m.push(p.message),V.push(p.callId),L.add(p.toolName);let H=Kc(p,u);H||F++;let R=p.ok&&Hn(p);if(p.ok&&!R&&!H&&(He+=1),H||Ls({toolFailureCounts:u.toolFailureCounts,toolName:p.toolName,toolArguments:ge.find(_=>_.id===p.callId)?.function.arguments,ok:p.ok,softEmpty:R}),p.ok&&tu.has(p.toolName)&&Bu(u),p.ok&&Zs(p.toolName)){let _=ge.find(B=>B.id===p.callId),E=_?Ut(_.function.arguments):void 0;if(E){let B=G(E);if(u.benchmarkStateMaintenanceRequiredFiles.has(B)){let ae=go(u.maintainedDocuments,B,_?.function.arguments??"");ae.ok?u.benchmarkStateMaintenanceWrittenFiles.add(B):(D.push({name:p.toolName,reason:"benchmark-state-invalid-content"}),m.push({role:"user",content:`Benchmark-state maintenance write for ${B} is incomplete: ${ae.reason}. Rewrite or patch the file using the document evidence already provided; do not reread context-pack source documents.`}))}}}if(p.ok&&!R&&(io.has(p.toolName)||p.toolName==="exec"&&p.details?.type==="exec_background"||p.toolName==="exec"&&Ks(ge.find(_=>_.id===p.callId)?.function.arguments??""))){let _=ge.find(B=>B.id===p.callId),E=typeof p.message?.content=="string"?p.message.content:"";if(_&&E){let B=Array.isArray(p.message.imageUrls)?p.message.imageUrls.filter(ye=>typeof ye=="string"):void 0,ae=Array.isArray(p.message.toolReferences)?p.message.toolReferences.filter(ye=>typeof ye=="string"):void 0;u.identicalSuccessfulToolResults.set(`${_.function.name}::${_.function.arguments}`,{content:E,imageUrls:B,toolReferences:ae})}}if(p.toolName==="agent"){let _=Oe(p.details,"agentId"),E=Oe(p.details,"status"),B=Ft(p.details,"background");p.ok&&_&&B===!0&&E==="running"&&Ce(u).add(_)}if(p.toolName==="task"){let _=eu(p.details);_&&(u.lastTaskList=_);let E=Oe(p.details,"taskId"),B=Ft(p.details,"running"),ae=Oe(p.details,"lifecycle"),ye=Oe(p.details,"action");if(E&&(ye==="cancel"||B===!1||ae&&ae!=="running"&&ae!=="pending"))Ce(u).delete(E),u.backgroundAgentNoOutputPollCounts.delete(E),u.stalledBackgroundAgentTasks.delete(E);else if(E&&ye==="output"&&B===!0&&Ce(u).has(E)){let Yo=typeof p.message?.content=="string"?p.message.content:"",Zo=Ft(p.details,"hasOutput");if(Zo!==void 0?Zo===!1:Jc(Yo)){let dn=(u.backgroundAgentNoOutputPollCounts.get(E)??0)+1;u.backgroundAgentNoOutputPollCounts.set(E,dn);let Tt=Gc(p.details,"elapsedSeconds")??Qc(Yo);(Tt!==void 0&&Tt>=Yc||Tt===void 0&&dn>=Zc)&&u.stalledBackgroundAgentTasks.set(E,`no output after ${Tt??"unknown"}s across ${dn} poll(s)`)}else u.backgroundAgentNoOutputPollCounts.delete(E),u.stalledBackgroundAgentTasks.delete(E)}}if(p.ok&&p.toolName==="read"){let _=ge.find(E=>E.id===p.callId);if(_){let E=lo(_.function.arguments);if(E){let B=G(E),ae=u.fileReadCounts.get(B)??0;u.fileReadCounts.set(B,ae+1);let ye=typeof p.message?.content=="string"?p.message.content:"";d=vu(u,E,ye,u.turnCount,p.details)||d}}}yield Pr(r,p);for(let _ of Or(r,p))yield _;for(let _ of Nr({turnId:r,result:p,toolCalls:oe}))yield _;let re=oe.find(_=>_.id===p.callId),he=typeof p.message?.content=="string"?p.message.content:"";if(re){Vr({state:u.artifactContract,inputMessages:i,toolName:p.toolName,rawArguments:re.function.arguments,ok:p.ok,content:he}),Jt()&&(yield Zt());let _=Dc(p.toolName,re.function.arguments);if(_){let E=(Co.get(_)??0)+1;if(Co.set(_,E),E===Bc){let B=_.startsWith("exec:")?"exec":"edit";u.recoveryTrace.set(`no_progress_observed:${B}`,(u.recoveryTrace.get(`no_progress_observed:${B}`)??0)+1)}}}!yt&&yi&&p.toolName==="stt"&&p.ok&&(yt=bc(i,p))}if(We&&(b=Te(O,Y),We=!1),zt&&(b=Te(O,Y),zt=!1),d){let p=ku(r,u.maintainedDocuments,u.fileReadCounts,u.turnCount);p&&(yield p);for(let R of _u(r,u.maintainedDocuments))yield R;let w=uu(u.maintainedDocuments,u.turnCount),H=b.some(R=>ao.has(R.function.name));if(w&&H){u.benchmarkStateMaintenanceRequiredFiles=new Set(li(u.maintainedDocuments).map(G));for(let R of b)ao.has(R.function.name)||Y.add(R.function.name);b=Te(b,Y),U=!0,m.push({role:"user",content:w}),yield M("benchmark_state_maintenance_required","forcing write/edit/patch after long-horizon document index")}}let g=Ce(u);if(g.size>0){let p=(a??c).find(w=>w.function.name==="task");if(p){let w=k(b),H=[...g].filter(R=>u.stalledBackgroundAgentTasks.has(R)).sort();if(H.length>0){b=[p],U=!0;let R=H.map(N=>`${N}: ${u.stalledBackgroundAgentTasks.get(N)}`).join("; ");m.push({role:"user",content:Vc(H,{reason:R})}),yield{type:"tool_selection_policy",turnId:r,policyId:"background_agent_no_output_watchdog_cancel_required",intent:"lifecycle_reconciliation",reason:"background-agent-no-output-watchdog",availableToolNames:k(a??c),enabledToolNamesBefore:w,enabledToolNamesAfter:k(b),suppressedToolNames:w.filter(N=>N!=="task"),nextAction:"cancel-stalled-background-task"},yield M("background_agent_no_output_watchdog_cancel_required",R);continue}b=[p],U=!0,m.push({role:"user",content:Wc(g)}),yield{type:"tool_selection_policy",turnId:r,policyId:"background_agent_lifecycle_poll_required",intent:"lifecycle_reconciliation",reason:"background-agent-task-unresolved",availableToolNames:k(a??c),enabledToolNamesBefore:w,enabledToolNamesAfter:k(b),suppressedToolNames:w.filter(R=>R!=="task"),nextAction:"poll-existing-background-task-output"},yield M("background_agent_lifecycle_poll_required",[...g].sort().join(","));continue}}else b.length===1&&b[0]?.function.name==="task"&&(b=Te(O,Y));if(de(i)&&!u.artifactContract.browserVerified&&Dt(u.artifactContract).length>0&&b.some(p=>p.function.name==="exec")&&u.browserAcceptanceRecoveryCount<4){let p=Xs(u.artifactContract);u={...u,browserAcceptanceRecoveryCount:u.browserAcceptanceRecoveryCount+1,messages:[...m,{role:"user",content:p}],transition:{reason:"next_turn"}},U=!0,yield M("browser_acceptance_required","forcing browser automation after localhost app URL was observed");continue}let T=pu(u.maintainedDocuments);if(T.length>0&&u.benchmarkStateIntegrityRecoveryCount<au){let p=T.map(w=>`${ke(w.path)}: ${w.reason}`).join("; ");u={...u,benchmarkStateIntegrityRecoveryCount:u.benchmarkStateIntegrityRecoveryCount+1,messages:[...m,{role:"user",content:"Your maintained benchmark-state hash files no longer match the tool-derived ground truth: "+p+". The context-pack inputs are read-only and immutable \u2014 the source did NOT change. Restore the exact recorded contentHash/fileSizeBytes; do NOT flip any acceptance verdict on this phantom drift."}],transition:{reason:"next_turn"}},U=!0,yield M("benchmark_state_integrity_required","on-disk benchmark-state hash file contradicts tool-derived ground truth; forcing a correction before completion");continue}if(du(u)){yield*W("Maintained benchmark-state files after indexing the context pack. Stopping this turn now because the required document-index.json, decision-state-table.json, and context-pack-evidence.json writes are complete; do not continue into extra writes, context-pack modifications, or repeated reads.");return}}catch(l){let d=l instanceof Error?l.message:String(l);yield{type:"error",turnId:r,error:d,code:"TOOL_EXECUTION_ERROR",usage:u.totalUsage};return}if(yt){yield*W(yt);return}let Xo=vc(i,m);if(Xo){yield*Mo(Xo);return}let Ko=wc(i,m);if(Ko){yield*Mo(Ko);return}if(m.push(...Fs({toolFailureCounts:u.toolFailureCounts,snapshot:Mi})),Si){let l=Pe({inputMessages:i,messages:m,reason:`tool call budget exhausted (${se}) before completing all required files`});if(l){yield*W(l,{forcedStop:!0});return}}te=Rt(te,{replayMessages:m,completedToolCallIds:[...te.completedToolCallIds,...V],lastStopReason:"tool_calls"}),e.toolChoice==="required"&&oe.length>0&&(Wt=!0);let Ei=oe.length>0&&oe.every(l=>{let d=m.find(T=>T?.role==="tool"&&T?.tool_call_id===l.id);if(!d)return!0;let g=d.content;return typeof g=="string"&&g.startsWith("Error: ")}),xe=u.consecutiveFailedRounds;if(Ei){if(xe+=1,xe>=cr){if(yo>=3&&u.repeatedToolFailureRecoveryCount<1){let T=to({inputMessages:i,messages:m,finalText:u.finalText,thinkingBlocks:[],stopHookActive:u.stopHookActive,totalToolCallCount:F,distinctToolNames:L,log:o});if(T?.reason==="explicit_required_file_verification"||T?.reason==="explicit_extra_file_verification"){yield M("repeated_tool_failure_artifact_recovery","one recovery nudge before ending a complex explicit artifact turn after repeated tool failures"),u={...u,messages:T.messages,stopHookActive:T.stopHookActive,transition:T.transition,consecutiveFailedRounds:0,repeatedToolFailureRecoveryCount:u.repeatedToolFailureRecoveryCount+1};continue}}if(u.repeatedToolFailureRecoveryCount<1){let T=cs(m);if(T){yield M("repeated_tool_failure_self_correction","one help-guided self-correction round before ending on repeated tool failures"),u={...u,messages:[...m,T],consecutiveFailedRounds:0,repeatedToolFailureRecoveryCount:u.repeatedToolFailureRecoveryCount+1};continue}}let l=`repeated tool failures (${xe} rounds in a row)`,d=Pe({inputMessages:i,messages:m,reason:`${l} before all required files were produced`})??(u.finalText.trim()?u.finalText:Wn(m,xe)),g=Ys(d,{availableToolNames:k(a??c),enabledToolNames:Gt(),toolCallNames:[...L].sort(),blockedToolCalls:Nt(D)});o.info(`early exit: ${xe} consecutive failed rounds, returning ${u.finalText?"partial":"fallback"} response`),yield*W(g,{forcedStop:!0});return}}else xe=0;let bt=[...u.fileReadCycleBlockedPaths].filter(l=>!u.fileReadCycleNudgedPaths.has(l));if(bt.length>0){let l=bt.join(", "),d=[...new Set(bt.map(so))].join(" ");o.info(`AP5: file read cycle detected on ${l}, injecting nudge`);let g={role:"user",content:`Read-cycle guard blocked repeated reads for: ${l}. ${d} Stop reading these source files this turn; summarize from maintained evidence and explain any remaining uncertainty.`};m.push(g);for(let T of bt)u.fileReadCycleNudgedPaths.add(T)}let Be=ie+1;if(A>0&&Be>A){if(o.info(`max turns reached (${A}), completing`),C){let g=await C.invoke("stop",{sessionId:s,reason:"max_turns"});if(g.action==="abort"){let T=g.reason??"Stop hook requested continuation after max_turns",p={role:"assistant",content:u.finalText,...ce.length>0&&{thinkingBlocks:[...ce]}};u={...u,messages:[...m,p,{role:"user",content:T}],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}};continue}}let l=Pe({inputMessages:i,messages:m,reason:`tool loop max turns reached (${A}) before completing all required files`});if(l){yield*W(l,{forcedStop:!0});return}let d=at(m,`tool loop max turns reached (${A}) before completing the final status contract`);yield*W(d);return}if(qt&&Ce(u).size>0&&Be>q&&q<100&&(q=Math.min(100,Be+25),o.info(`background task lifecycle wait extended round budget to ${q}`)),qt&&Be>q){let l=Xn({currentToolBudget:se,currentRoundBudget:q,toolHardCap:100,roundHardCap:100,continuationCount:Ge,successfulSinceLastCheck:He-st,fileReadCounts:u.fileReadCounts,windowTools:be,windowRounds:25});l&&(q=l.nextRoundBudget,se=l.nextToolBudget,Ge=l.continuationCount,st=He,o.info(`round budget continuation #${l.continuationCount}: rounds\u2192${q}, tools\u2192${se} (progress detected)`))}if(Be>q){o.info(`tool loop budget exhausted (${q} rounds), returning`);let l=no({totalToolCallCount:F,distinctToolNames:L,projectRoot:e.projectRoot});l&&(yield{type:"skill_instruction",turnId:r,instruction:l});let d=Pe({inputMessages:i,messages:m,reason:`tool budget exhausted (${q} rounds) before completing all required files`});if(d){yield*W(d,{forcedStop:!0});return}let g=at(m,`tool budget exhausted (${q} rounds) before completing the final status contract`);yield*W(g);return}u={messages:m,maxOutputTokensRecoveryCount:0,hasAttemptedReactiveCompact:!1,maxOutputTokensOverride:void 0,turnCount:Be,transition:{reason:"next_turn"},guardState:j,reactiveCompactState:ee,toolLoopState:te,consecutiveFailedRounds:xe,finalText:u.finalText,totalUsage:u.totalUsage,collapseStore:Qt,currentModel:u.currentModel,consecutive529Errors:0,consecutiveApiRetries:0,stopHookActive:u.stopHookActive,lastResponseId:u.lastResponseId,snipRemovedIds:u.snipRemovedIds,contentReplacementState:u.contentReplacementState,budgetContinuationCount:u.budgetContinuationCount,repeatedToolFailureRecoveryCount:u.repeatedToolFailureRecoveryCount,lastBudgetDeltaTokens:u.lastBudgetDeltaTokens,lastBudgetGlobalTokens:u.lastBudgetGlobalTokens,identicalCallCounts:dt,identicalSuccessfulToolResults:u.identicalSuccessfulToolResults,artifactContract:u.artifactContract,toolFailureCounts:u.toolFailureCounts,fileReadCounts:u.fileReadCounts,fileReadCycleBlockedPaths:u.fileReadCycleBlockedPaths,fileReadCycleNudgedPaths:u.fileReadCycleNudgedPaths,maintainedDocuments:u.maintainedDocuments,persistedBenchmarkStateRecovered:u.persistedBenchmarkStateRecovered,benchmarkStateMaintenanceRequiredFiles:u.benchmarkStateMaintenanceRequiredFiles,benchmarkStateMaintenanceWrittenFiles:u.benchmarkStateMaintenanceWrittenFiles,recoveryTrace:u.recoveryTrace,browserAcceptanceRecoveryCount:u.browserAcceptanceRecoveryCount,buildVerificationRecoveryCount:u.buildVerificationRecoveryCount,benchmarkStateIntegrityRecoveryCount:u.benchmarkStateIntegrityRecoveryCount,backgroundAgentTaskIds:Ce(u),backgroundAgentNoOutputPollCounts:u.backgroundAgentNoOutputPollCounts,stalledBackgroundAgentTasks:u.stalledBackgroundAgentTasks,notOfferedToolRecoveryCount:u.notOfferedToolRecoveryCount,existingFileUpdateRecoveryCount:u.existingFileUpdateRecoveryCount,taskListReconciliationCount:u.taskListReconciliationCount,lastTaskList:u.lastTaskList}}}var Du=["\u63A5\u5355\u91D1\u989D","\u5408\u540C\u91D1\u989D","\u62A5\u4EF7","\u9884\u7B97","\u91D1\u989D","price","amount","contract amount"];function mi(e){let t=$u(e),n=["[Recalled memories]","- L1 project MD is project-scoped working memory.","- L2 long-term memory is cross-project canonical memory.","- If L1 and L2 conflict on the same entity/fact, do not silently merge or choose. Surface the conflict and ask the user to confirm. For current-project operational tasks, use L1 only as a project-scoped clue until confirmed into L2."];if(t.length>0){n.push("[Memory conflict detected]");for(let o of t)n.push(`- entity: ${o.entity}; fact: ${o.predicate}; L1 project MD says: ${pi(o.l1Amount)}; L2 long-term says: ${pi(o.l2Amount)}; action: ask the user which value is current before using it.`)}for(let o of e){let r=qu(o);n.push(`- [${r}] ${o.text}`)}return n.join(`
|
|
46
|
-
`)}function
|
|
47
|
-
${
|
|
45
|
+
${l.result.content}`,T=X(d.id,{ok:!0,payload:h,imageUrls:l.result.imageUrls,toolReferences:l.result.toolReferences});m.push(T),V.push(d.id),L.add(d.function.name),F++,yield{type:"tool_result",turnId:r,callId:d.id,name:d.function.name,ok:!0,outputPreview:h.slice(0,2e3),durationMs:0,details:{type:d.function.name,reusedIdenticalCall:!0,repeatCount:l.repeatCount}}}if(Qe.some(l=>l.call.function.name==="exec"&&ti(l.call.function.arguments))){let l=R(b);m.push({role:"user",content:Hc(u.artifactContract)}),yield{type:"tool_selection_policy",turnId:r,policyId:"browser_verification_after_preparation_required",intent:"verification",reason:"repeated-browser-preparation-command",availableToolNames:R(a??c),enabledToolNamesBefore:l,enabledToolNamesAfter:l,suppressedToolNames:[],nextAction:"run-browser-verification-script-not-playwright-install"},yield E("browser_verification_after_preparation_required","reused successful browser preparation command")}for(let l of de){D.push({name:l.function.name,reason:"identical-repeat-policy"});let d=pt.get(`${l.function.name}::${l.function.arguments}`),h=Et(m,l.function.name),T=Fc(h),p=Uo.has(l.id)?Iu(d,l):T?`This exact tool call has been attempted ${d} times. Last error: ${T}. Do not retry. Report this error to the user.`:`This exact tool call has been attempted ${d} times and keeps failing. Do not retry it. Report the issue to the user or try a completely different approach.`,w=X(l.id,{ok:!1,error:p});m.push(w),V.push(l.id),L.add(l.function.name),F++,yield{type:"tool_result",turnId:r,callId:l.id,name:l.function.name,ok:!1,error:p}}if(de.length>0&&Je.length===0&&Qe.length===0&&de.every(l=>Uo.has(l.id))&&u.existingFileUpdateRecoveryCount<2){let l=R(b);b=Ks(N,Z);let d=R(b);Ve=!0,U=!0;let h=[...new Set(de.map(T=>zt(T.function.arguments)).filter(T=>!!T))];m.push({role:"user",content:`Existing-file maintenance recovery: the same write call was repeatedly attempted for an existing file. Do not use write for these existing path(s): ${h.join(", ")||"(unknown)"}. Do not delete, remove, or recreate an existing file to make write succeed; that is artifact path drift, not maintenance. Use read only if you need the current contents, then use edit or patch for the smallest valid change. After the edit/patch succeeds, continue build/browser verification normally.`}),yield{type:"tool_selection_policy",turnId:r,policyId:"existing_file_update_recovery",intent:"tool_recovery",reason:"repeated-existing-file-write",availableToolNames:R(a??c),enabledToolNamesBefore:l,enabledToolNamesAfter:d,suppressedToolNames:io(l,d),nextAction:"use-read-edit-or-patch-for-existing-file-update"},yield E("existing_file_update_recovery",h.join(",")||"unknown"),u={...u,messages:m,existingFileUpdateRecoveryCount:u.existingFileUpdateRecoveryCount+1,transition:{reason:"next_turn"}};continue}if(de.length>0){let l=Et(m,de[0].function.name),d={role:"user",content:"Tool calls were blocked because you repeated them with identical arguments too many times. "+(l?`The error was: "${l}". Tell the user about this error. `:"The operation is not working. ")+"Stop retrying and report the result to the user."};m.push(d)}let Mi=Co>=3&&u.repeatedToolFailureRecoveryCount<1;if(de.length>0&&Je.length===0&&Qe.length===0&&!Mi){let l=ni(Xn(m,1),{availableToolNames:R(a??c),enabledToolNames:Vt(),toolCallNames:[...L].sort(),blockedToolCalls:Ft(D)});yield*H(l);return}let jo=[],on=[];for(let l of Je){let d=Wr({toolName:l.function.name,rawArguments:l.function.arguments});d?on.push({call:l,...d}):jo.push(l)}for(let l of on){let d=l.call;D.push({name:d.function.name,reason:"read-only-context-pack"}),m.push(X(d.id,{ok:!1,error:l.error})),V.push(d.id),L.add(d.function.name),F++,yield{type:"tool_result",turnId:r,callId:d.id,name:d.function.name,ok:!1,error:l.error},o.warn(`read-only context-pack blocked: ${d.function.name} ${l.path}`)}on.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 Ii=new Set(b.map(l=>l.function.name)),zo=[],mt=[];for(let l of jo){let d=di(l.function.name,l.function.arguments,Ii);d?mt.push({call:l,...d}):zo.push(l)}for(let l of mt){let d=l.call;D.push({name:d.function.name,reason:"existing-file-update-tool-required"}),m.push(X(d.id,{ok:!1,error:l.error})),V.push(d.id),L.add(d.function.name),F++,yield{type:"tool_result",turnId:r,callId:d.id,name:d.function.name,ok:!1,error:l.error},o.info(`existing file update blocked: ${d.function.name} ${l.path}`)}if(mt.length>0){let l=R(b);b=Ks(N,Z);let d=R(b);Ve=!0,U=!0;let h=[...new Set(mt.map(T=>T.path))];m.push({role:"user",content:`Existing-file maintenance recovery: a write was blocked because the target file already exists and edit/patch are enabled. Do not use write for these existing path(s): ${h.join(", ")||"(unknown)"}. Do not delete, remove, or recreate an existing file to make write succeed; that is artifact path drift, not maintenance. Use read only if you need the current contents, then use edit or patch for the smallest valid change. After the edit/patch succeeds, continue build/browser verification normally.`}),yield{type:"tool_selection_policy",turnId:r,policyId:"existing_file_update_recovery",intent:"tool_recovery",reason:"existing-file-write-blocked",availableToolNames:R(a??c),enabledToolNamesBefore:l,enabledToolNamesAfter:d,suppressedToolNames:io(l,d),nextAction:"use-read-edit-or-patch-for-existing-file-update"},yield E("existing_file_update_recovery",h.join(",")||"unknown"),u={...u,messages:m,existingFileUpdateRecoveryCount:u.existingFileUpdateRecoveryCount+1,transition:{reason:"next_turn"}};continue}let Ho=[],rn=[];for(let l of zo){let d=Gr({state:u.artifactContract,inputMessages:i,toolName:l.function.name,rawArguments:l.function.arguments});d?rn.push({call:l,...d}):Ho.push(l)}for(let l of rn){let d=l.call;D.push({name:d.function.name,reason:"artifact-root-contract"}),jn(u.artifactContract,{path:l.path,artifactRoot:l.artifactRoot,toolName:d.function.name}),m.push(X(d.id,{ok:!1,error:l.error})),V.push(d.id),L.add(d.function.name),F++,yield{type:"tool_result",turnId:r,callId:d.id,name:d.function.name,ok:!1,error:l.error},en()&&(yield Qt()),o.warn(`artifact root contract blocked: ${d.function.name}`)}rn.length>0&&m.push({role:"user",content:"A write was blocked by the artifactRoot contract. Continue inside the declared artifactRoot, or stop with an honest final status that lists the root drift as Not done."});let qo=[],sn=[];for(let l of Ho){let d=Is({inputMessages:i,messages:m,toolCall:l});d?sn.push({call:l,error:d}):qo.push(l)}for(let l of sn){let d=l.call;D.push({name:d.function.name,reason:"premature-completion-artifact"}),m.push(X(d.id,{ok:!1,error:l.error})),V.push(d.id),L.add(d.function.name),F++,yield{type:"tool_result",turnId:r,callId:d.id,name:d.function.name,ok:!1,error:l.error},o.info(`premature completion artifact blocked: ${d.function.name}`)}sn.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 Pi=new Set(b.map(l=>l.function.name)),Go=[],gt=[];for(let l of qo)Pi.has(l.function.name)?Go.push(l):gt.push(l);for(let l of gt){let d=`Tool "${l.function.name}" was not offered for this turn and will not be executed. Use only the tools listed in the current request.`;D.push({name:l.function.name,reason:"not-offered"}),m.push(X(l.id,{ok:!1,error:d})),V.push(l.id),L.add(l.function.name),o.warn(`unoffered tool call suppressed: ${l.function.name}`)}if(gt.length>0&&u.notOfferedToolRecoveryCount<1){let l=[...new Set(gt.map(w=>w.function.name))].sort(),d=Ve&&l.includes("write"),h=l.filter(w=>Z.has(w)),p=(a??c).filter(w=>l.includes(w.function.name));if(h.length>0)u.notOfferedToolRecoveryCount+=1,U=!0,m.push({role:"user",content:`You retried ${h.map(w=>`\`${w}\``).join(", ")} after it was disabled by this turn's tool-selection policy. Do not retry policy-suppressed tools in this turn. Continue using only the currently enabled tools, or stop with a clear blocker.`}),yield{type:"tool_selection_policy",turnId:r,policyId:"policy_suppressed_tool_retry_blocked",intent:"tool_recovery",reason:"requested-tool-disabled-by-turn-policy",availableToolNames:R(a??c),enabledToolNamesBefore:R(b),enabledToolNamesAfter:R(b),suppressedToolNames:h,nextAction:"continue-with-currently-enabled-tools-or-report-blocker"},yield E("policy_suppressed_tool_retry_blocked",h.join(","));else if(!d&&p.length>0){let w=R(b),G=new Map(b.map(C=>[C.function.name,C]));for(let C of p)G.set(C.function.name,C);b=ze([...G.values()]),u.notOfferedToolRecoveryCount+=1,U=!0,yield{type:"tool_selection_policy",turnId:r,policyId:"available_tool_reenabled_after_not_offered_call",intent:"tool_recovery",reason:"requested-tool-available-but-disabled",availableToolNames:R(a??c),enabledToolNamesBefore:w,enabledToolNamesAfter:R(b),suppressedToolNames:[],nextAction:"retry-with-reenabled-requested-tool"},m.push({role:"user",content:`You called ${l.map(C=>`\`${C}\``).join(", ")} but it was not enabled for that round even though it is available. The requested available tool has now been re-enabled. Use the re-enabled tool once with valid arguments; do not repeat a disabled-tool call.`}),yield E("available_tool_reenabled_after_not_offered_call",l.join(","))}}let Wo=[],an=[];for(let l of Go){let d=b.find(T=>T.function.name===l.function.name),h=Vc(d,l.function.arguments);h?an.push({call:l,error:h}):Wo.push(l)}for(let l of an){let d=l.call;D.push({name:d.function.name,reason:"invalid-arguments"}),m.push(X(d.id,{ok:!1,error:l.error})),V.push(d.id),L.add(d.function.name),F++,yield{type:"tool_result",turnId:r,callId:d.id,name:d.function.name,ok:!1,error:l.error,details:{type:d.function.name,error:"invalid_arguments"}},o.info(`invalid tool arguments blocked: ${d.function.name}`)}an.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 ht=[],ln=[];for(let l of Wo){if(l.function.name!=="exec"){ht.push(l);continue}let d=Ys(l.function.arguments);if(!d){ht.push(l);continue}let h=Hs(d);qs(h)&&!Ws(d)&&Xs(N)?ln.push({call:l,error:Wc(h)}):ht.push(l)}for(let l of ln){let d=l.call;D.push({name:d.function.name,reason:"dedicated-tool-required"});let h=R(b),T=b.filter(p=>["read","search"].includes(p.function.name));T.length>0&&(b=T,Gt=!0,U=!0),m.push(X(d.id,{ok:!1,error:l.error})),V.push(d.id),L.add(d.function.name),F++,yield{type:"tool_result",turnId:r,callId:d.id,name:d.function.name,ok:!1,error:l.error,details:{type:d.function.name,error:"dedicated_tool_required",dedicatedTool:"read/search"}},o.info(`dedicated file tool preflight blocked: ${d.function.name}`),yield{type:"tool_selection_policy",turnId:r,policyId:"dedicated_file_tool_required",intent:"fresh_evidence",reason:"exec-file-read-search-list-blocked",availableToolNames:R(a??c),enabledToolNamesBefore:h,enabledToolNamesAfter:R(b),suppressedToolNames:h.filter(p=>!["read","search"].includes(p)),nextAction:"use-read-search-for-file-inspection-then-resume-build-run-verify-tools"}}ln.length>0&&m.push({role:"user",content:"Exec was blocked because it attempted local file reading/searching/listing. Use read/search for the next local file inspection step. After that, resume exec only for non-inspection commands such as installs, builds, dev servers, and verification scripts."});let yt=[],cn=[],Vo=[],Xo=[];for(let l of ht){if(l.function.name!=="exec"){yt.push(l);continue}let d=l,h=Ys(d.function.arguments),T=h?$c(h):null;T&&(d={...d,function:{...d.function,arguments:Js(d.function.arguments,T)}},Xo.push({originalCommand:h??"",rewrittenCommand:T}),h=T);let p=h?Uc(h):null;if(p?.action==="block")cn.push({call:d,error:p.error});else if(p?.action==="rewrite"){let w={...d,function:{...d.function,arguments:Js(d.function.arguments,p.command)}};Vo.push({call:w,originalCommand:h??"",rewrittenCommand:p.command}),yt.push(w)}else yt.push(d)}for(let l of Xo)yield{type:"tool_selection_policy",turnId:r,policyId:"exec_sleep_prefix_guard",intent:"verification",reason:"sleep-prefix-removed",availableToolNames:R(a??c),enabledToolNamesBefore:R(b),enabledToolNamesAfter:R(b),suppressedToolNames:[],nextAction:"execute-command-without-blocking-sleep-prefix"},o.info(`blocking sleep prefix removed before exec: ${l.originalCommand} -> ${l.rewrittenCommand}`);for(let l of Vo){let d=R(b);yield{type:"tool_selection_policy",turnId:r,policyId:"reserved_frontend_port_guard",intent:"verification",reason:"vite-strict-port-normalized",availableToolNames:R(a??c),enabledToolNamesBefore:d,enabledToolNamesAfter:R(b),suppressedToolNames:[],nextAction:"execute-normalized-vite-dev-server-command-with-strict-port"},o.info(`vite strict port normalized before exec: ${l.originalCommand} -> ${l.rewrittenCommand}`)}for(let l of cn){let d=l.call;D.push({name:d.function.name,reason:"reserved-frontend-port"});let h=R(b);m.push(X(d.id,{ok:!1,error:l.error})),V.push(d.id),L.add(d.function.name),F++,yield{type:"tool_result",turnId:r,callId:d.id,name:d.function.name,ok:!1,error:l.error,details:{type:d.function.name,error:"reserved_frontend_port",reservedPort:$t}},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:R(a??c),enabledToolNamesBefore:h,enabledToolNamesAfter:R(b),suppressedToolNames:[],nextAction:"restart-generated-dev-server-on-explicit-non-5174-port-with-strict-port"}}cn.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 bt=[],Be=[];for(let l of yt){if(l.function.name!=="read"){bt.push(l);continue}let d=uo(l.function.arguments);if(!d){bt.push(l);continue}let h=W(d),T=ai(h);(u.fileReadCounts.get(h)??0)>=T?Be.push({call:l,filePath:h,maxReads:T}):bt.push(l)}for(let l of Be){let d=l.call,h=`Read cycle policy blocked another read of "${l.filePath}" after ${l.maxReads} successful reads in this turn. Stop rereading the same large document. ${ao(l.filePath)}`;D.push({name:d.function.name,reason:"read-cycle-policy"}),u.fileReadCycleBlockedPaths.add(l.filePath),m.push(X(d.id,{ok:!1,error:h})),V.push(d.id),L.add(d.function.name),F++,yield{type:"tool_result",turnId:r,callId:d.id,name:d.function.name,ok:!1,error:h},o.info(`read cycle blocked: ${l.filePath}`)}if(Be.length>0){let l=[...new Set(Be.map(T=>`${T.filePath} (max ${T.maxReads})`))].join(", "),d=[...new Set(Be.map(T=>ao(T.filePath)))].join(" ");if(m.push({role:"user",content:`Further reads were blocked because these large/context documents already reached their per-turn read limit: ${l}. Do not retry the read with a different path spelling. ${d} Continue from maintained requirements/defects/decisions/acceptance evidence and report any truly missing section explicitly.`}),b.some(T=>oi(T.function.name))&&(u.persistedLongHorizonStateRecovered||Be.some(T=>ho(T.filePath)))){let T=R(b),p=T.filter(w=>fu.has(w)).sort();yield{type:"tool_selection_policy",turnId:r,policyId:"long_horizon_benchmark_state_maintenance",intent:"benchmark_state_maintenance",reason:"read-cycle-guard-retains-evidence-tools",availableToolNames:R(a??c),enabledToolNamesBefore:T,enabledToolNamesAfter:R(b),suppressedToolNames:[],nextAction:"maintenance-or-final-answer"},m.push({role:"user",content:`Do not reread the blocked large/context document paths again. Evidence tools still enabled: ${p.join(", ")||"none"}. Use read/search only for targeted verification of generated artifacts, file names, and missing sections; use edit/patch/write only if benchmark-state maintenance needs an update; otherwise stop tool use and answer from the maintained benchmark-state evidence. Classify any unused edit/patch/write tools as not needed, not missing.`}),yield E("benchmark_state_maintenance_tool_bias","retaining targeted evidence tools after long-horizon read-cycle guard")}if(bu(D,u.fileReadCycleBlockedPaths,u.persistedLongHorizonStateRecovered,u.maintainedDocuments)){yield*H("Stopped repeated long-horizon context-pack rereads after the read-cycle guard blocked every maintained source document. Continue from benchmark-state/document-index.json, decision-state-table.json, and context-pack-evidence.json; do not reread or rewrite context-pack source documents.",{forcedStop:!0});return}}let un=Bs(bt,u.toolFailureCounts),dn=un.allowed;if(qt&&dn.length>Math.max(0,se-F)){let l=Yn({currentToolBudget:se,currentRoundBudget:z,toolHardCap:100,roundHardCap:100,continuationCount:We,successfulSinceLastCheck:Ge-lt,fileReadCounts:u.fileReadCounts,windowTools:Ce,windowRounds:25});l&&(se=l.nextToolBudget,z=l.nextRoundBudget,We=l.continuationCount,lt=Ge,o.info(`tool budget continuation #${l.continuationCount}: tools\u2192${se}, rounds\u2192${z} (progress detected)`))}let Ko=Math.max(0,se-F),fe=Ko>0?dn.slice(0,Ko):[],fn=dn.slice(fe.length),Oi=fn.length>0;if(un.blocked.length>0){for(let l of un.blocked){let d=l.call;D.push({name:d.function.name,reason:"variant-failure-policy"});let h=X(d.id,{ok:!1,error:l.error});m.push(h),V.push(d.id),L.add(d.function.name),F++,yield{type:"tool_result",turnId:r,callId:d.id,name:d.function.name,ok:!1,error:l.error},o.info(`variant tool blocked: ${d.function.name} failed ${l.failCount}x with different args`)}m.push(Ds())}if(fn.length>0){let l=`Tool call budget exhausted (${se}) for this turn. Stop requesting more tools and report what remains incomplete.`;for(let d of fn){D.push({name:d.function.name,reason:"tool-call-budget"});let h=X(d.id,{ok:!1,error:l});m.push(h),V.push(d.id),L.add(d.function.name),F++,yield{type:"tool_result",turnId:r,callId:d.id,name:d.function.name,ok:!1,error:l}}m.push({role:"user",content:`${l} You reached this turn's tool budget after ${We} 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 fe){let d=l.function.arguments,h=b.find(T=>T.function.name===l.function.name);if(h?.backfillObservableInput)try{let T=JSON.parse(l.function.arguments),p={...T};h.backfillObservableInput(p),Object.keys(p).some(G=>!(G in T))&&(d=JSON.stringify(p))}catch{}yield{type:"tool_call",turnId:r,callId:l.id,name:l.function.name,arguments:d,inputSummary:Kn(d)},ko.add(l.function.name),Ro++}let Ni=new Map(u.toolFailureCounts),Tt=null;try{let l=e.runtimePorts.createStreamingToolExecutor({toolInvoker:n,hooks:k,sessionId:s,turnId:r,log:o,signal:x,maxConcurrentTools:e?.maxConcurrentTools,maxExecutionMs:lr});for(let p of fe)l.addTool(p);let d=!1;for await(let p of l.getRemainingResults()){let w=Nc(p);if(w){if(D.push({name:p.toolName,reason:w}),p.toolName==="exec"&&w==="dedicated-tool-required"&&Xs(N)){let A=R(b);m.push({role:"user",content:"Exec was blocked because it attempted local file reading/searching/listing. Use read/search for local file inspection. Exec remains available only for non-inspection commands such as installs, builds, dev servers, and verification scripts."}),yield{type:"tool_selection_policy",turnId:r,policyId:"dedicated_file_tool_required",intent:"fresh_evidence",reason:"exec-file-read-search-list-blocked",availableToolNames:R(a??c),enabledToolNamesBefore:A,enabledToolNamesAfter:R(b),suppressedToolNames:[],nextAction:"use-read-search-for-file-inspection-or-exec-for-build-run-verify"}}if(p.toolName==="exec"&&w==="confirmation-timeout"){let A=R(b);Z.add("exec");let I=ke(N,Z);I.length>0&&(b=ze(I),U=!0),m.push({role:"user",content:"Exec confirmation timed out, so exec is disabled for the rest of this turn. Do not retry exec. Use read/search for inspection, edit/patch/write for file updates, ask_user only for missing user input, or stop with a clear blocker if no non-exec tool can complete the request."}),yield{type:"tool_selection_policy",turnId:r,policyId:"exec_confirmation_timeout_recovery",intent:"tool_recovery",reason:"exec-confirmation-timeout",availableToolNames:R(a??c),enabledToolNamesBefore:A,enabledToolNamesAfter:R(b),suppressedToolNames:io(A,R(b)),nextAction:"continue-with-non-exec-tools-or-report-confirmation-blocker"}}if(p.toolName==="exec"&&w==="global-process-kill-blocked"){let A=R(b);m.push({role:"user",content:"Exec was blocked because it attempted to terminate every node process. Do not retry taskkill/killall/pkill/Stop-Process by process name. If a generated app server conflicts with another process, start the generated app on a new explicit non-5174 port with strict port behavior, or stop only an owned background task by its task id. Continue by verifying the app on the reachable generated-app URL."}),yield{type:"tool_selection_policy",turnId:r,policyId:"global_process_kill_recovery",intent:"verification",reason:"global-node-process-kill-blocked",availableToolNames:R(a??c),enabledToolNamesBefore:A,enabledToolNamesAfter:R(b),suppressedToolNames:[],nextAction:"use-owned-task-cancel-or-new-explicit-port"}}}p.blocked&&(yield{type:"tool_blocked",turnId:r,callId:p.callId,name:p.toolName,reason:p.blockReason??"blocked"}),m.push(p.message),V.push(p.callId),L.add(p.toolName);let G=Qc(p,u);G||F++;let C=p.ok&&Wn(p),O=p.toolName==="exec"&&ps(mo(fe.find(A=>A.id===p.callId)?.function.arguments??""));if(p.ok&&!C&&!G&&!O&&(Ge+=1),G||$s({toolFailureCounts:u.toolFailureCounts,toolName:p.toolName,toolArguments:fe.find(A=>A.id===p.callId)?.function.arguments,ok:p.ok,softEmpty:C}),p.ok&&su.has(p.toolName)&&ju(u),p.ok&&oi(p.toolName)){let A=fe.find(B=>B.id===p.callId),I=A?zt(A.function.arguments):void 0;if(I){let B=W(I);if(u.longHorizonStateMaintenanceRequiredFiles.has(B)){let ae=bo(u.maintainedDocuments,B,A?.function.arguments??"");ae.ok?u.longHorizonStateMaintenanceWrittenFiles.add(B):(D.push({name:p.toolName,reason:"benchmark-state-invalid-content"}),m.push({role:"user",content:`Benchmark-state maintenance write for ${B} is incomplete: ${ae.reason}. Rewrite or patch the file using the document evidence already provided; do not reread context-pack source documents.`}))}}}if(p.ok&&!C&&(lo.has(p.toolName)||p.toolName==="exec"&&p.details?.type==="exec_background"||p.toolName==="exec"&&ti(fe.find(A=>A.id===p.callId)?.function.arguments??""))){let A=fe.find(B=>B.id===p.callId),I=typeof p.message?.content=="string"?p.message.content:"";if(A&&I){let B=Array.isArray(p.message.imageUrls)?p.message.imageUrls.filter(Te=>typeof Te=="string"):void 0,ae=Array.isArray(p.message.toolReferences)?p.message.toolReferences.filter(Te=>typeof Te=="string"):void 0;u.identicalSuccessfulToolResults.set(`${A.function.name}::${A.function.arguments}`,{content:I,imageUrls:B,toolReferences:ae})}}if(p.toolName==="agent"){let A=Ne(p.details,"agentId"),I=Ne(p.details,"status"),B=Dt(p.details,"background");p.ok&&A&&B===!0&&I==="running"&&Re(u).add(A)}if(p.toolName==="task"){let A=ru(p.details);A&&(u.lastTaskList=A);let I=Ne(p.details,"taskId"),B=Dt(p.details,"running"),ae=Ne(p.details,"lifecycle"),Te=Ne(p.details,"action");if(I&&(Te==="cancel"||B===!1||ae&&ae!=="running"&&ae!=="pending"))Re(u).delete(I),u.backgroundAgentNoOutputPollCounts.delete(I),u.stalledBackgroundAgentTasks.delete(I);else if(I&&Te==="output"&&B===!0&&Re(u).has(I)){let Yo=typeof p.message?.content=="string"?p.message.content:"",Zo=Dt(p.details,"hasOutput");if(Zo!==void 0?Zo===!1:nu(Yo)){let pn=(u.backgroundAgentNoOutputPollCounts.get(I)??0)+1;u.backgroundAgentNoOutputPollCounts.set(I,pn);let kt=Kc(p.details,"elapsedSeconds")??ou(Yo);(kt!==void 0&&kt>=eu||kt===void 0&&pn>=tu)&&u.stalledBackgroundAgentTasks.set(I,`no output after ${kt??"unknown"}s across ${pn} poll(s)`)}else u.backgroundAgentNoOutputPollCounts.delete(I),u.stalledBackgroundAgentTasks.delete(I)}}if(p.ok&&p.toolName==="read"){let A=fe.find(I=>I.id===p.callId);if(A){let I=uo(A.function.arguments);if(I){let B=W(I),ae=u.fileReadCounts.get(B)??0;u.fileReadCounts.set(B,ae+1);let Te=typeof p.message?.content=="string"?p.message.content:"";d=Eu(u,I,Te,u.turnCount,p.details)||d}}}yield Pr(r,p);for(let A of Or(r,p))yield A;for(let A of Nr({turnId:r,result:p,toolCalls:re}))yield A;let ie=re.find(A=>A.id===p.callId),pe=typeof p.message?.content=="string"?p.message.content:"";if(ie){Vr({state:u.artifactContract,inputMessages:i,toolName:p.toolName,rawArguments:ie.function.arguments,ok:p.ok,content:pe}),en()&&(yield Qt());let A=zc(p.toolName,ie.function.arguments);if(A){let I=(xo.get(A)??0)+1;if(xo.set(A,I),I===ei){let B=A.startsWith("exec:")?"exec":"edit";u.recoveryTrace.set(`no_progress_observed:${B}`,(u.recoveryTrace.get(`no_progress_observed:${B}`)??0)+1),_o.has(A)||(_o.add(A),m.push({role:"user",content:`You have now run ${ei} variations of the same action (${A}) without completing the user's request. Stop this approach: summarize what you tried and why it failed, then either take a FUNDAMENTALLY different route or report the blocker honestly. Do not run another variation of the same command family.`}),yield E("no_progress_nudge",A))}}}!Tt&&Ti&&p.toolName==="stt"&&p.ok&&(Tt=Mc(i,p))}if(Ve&&(b=ke(N,Z),Ve=!1),Gt&&(b=ke(N,Z),Gt=!1),d){let p=vu(r,u.maintainedDocuments,u.fileReadCounts,u.turnCount);p&&(yield p);for(let C of Su(r,u.maintainedDocuments))yield C;let w=mu(u.maintainedDocuments,u.turnCount),G=b.some(C=>co.has(C.function.name));if(w&&G){u.longHorizonStateMaintenanceRequiredFiles=new Set(ui(u.maintainedDocuments).map(W));for(let C of b)co.has(C.function.name)||Z.add(C.function.name);b=ke(b,Z),U=!0,m.push({role:"user",content:w}),yield E("benchmark_state_maintenance_required","forcing write/edit/patch after long-horizon document index")}}let h=Re(u);if(h.size>0){let p=(a??c).find(w=>w.function.name==="task");if(p){let w=R(b),G=[...h].filter(C=>u.stalledBackgroundAgentTasks.has(C)).sort();if(G.length>0){b=[p],U=!0;let C=G.map(O=>`${O}: ${u.stalledBackgroundAgentTasks.get(O)}`).join("; ");m.push({role:"user",content:Zc(G,{reason:C})}),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:R(a??c),enabledToolNamesBefore:w,enabledToolNamesAfter:R(b),suppressedToolNames:w.filter(O=>O!=="task"),nextAction:"cancel-stalled-background-task"},yield E("background_agent_no_output_watchdog_cancel_required",C);continue}b=[p],U=!0,m.push({role:"user",content:Yc(h)}),yield{type:"tool_selection_policy",turnId:r,policyId:"background_agent_lifecycle_poll_required",intent:"lifecycle_reconciliation",reason:"background-agent-task-unresolved",availableToolNames:R(a??c),enabledToolNamesBefore:w,enabledToolNamesAfter:R(b),suppressedToolNames:w.filter(C=>C!=="task"),nextAction:"poll-existing-background-task-output"},yield E("background_agent_lifecycle_poll_required",[...h].sort().join(","));continue}}else b.length===1&&b[0]?.function.name==="task"&&(b=ke(N,Z));if(me(i)&&!u.artifactContract.browserVerified&&Ut(u.artifactContract).length>0&&b.some(p=>p.function.name==="exec")&&u.browserAcceptanceRecoveryCount<4){let p=Qs(u.artifactContract);u={...u,browserAcceptanceRecoveryCount:u.browserAcceptanceRecoveryCount+1,messages:[...m,{role:"user",content:p}],transition:{reason:"next_turn"}},U=!0,yield E("browser_acceptance_required","forcing browser automation after localhost app URL was observed");continue}let T=yu(u.maintainedDocuments);if(T.length>0&&u.longHorizonStateIntegrityRecoveryCount<du){let p=T.map(w=>`${xe(w.path)}: ${w.reason}`).join("; ");u={...u,longHorizonStateIntegrityRecoveryCount:u.longHorizonStateIntegrityRecoveryCount+1,messages:[...m,{role:"user",content:"Your maintained benchmark-state hash files no longer match the tool-derived ground truth: "+p+". The context-pack inputs are read-only and immutable \u2014 the source did NOT change. Restore the exact recorded contentHash/fileSizeBytes; do NOT flip any acceptance verdict on this phantom drift."}],transition:{reason:"next_turn"}},U=!0,yield E("benchmark_state_integrity_required","on-disk benchmark-state hash file contradicts tool-derived ground truth; forcing a correction before completion");continue}if(gu(u)){yield*H("Maintained benchmark-state files after indexing the context pack. Stopping this turn now because the required document-index.json, decision-state-table.json, and context-pack-evidence.json writes are complete; do not continue into extra writes, context-pack modifications, or repeated reads.");return}}catch(l){let d=l instanceof Error?l.message:String(l);yield{type:"error",turnId:r,error:d,code:"TOOL_EXECUTION_ERROR",usage:u.totalUsage};return}if(Tt){yield*H(Tt);return}if(m.push(...Us({toolFailureCounts:u.toolFailureCounts,snapshot:Ni})),Oi){let l=Oe({inputMessages:i,messages:m,reason:`tool call budget exhausted (${se}) before completing all required files`});if(l){yield*H(l,{forcedStop:!0});return}}te=_t(te,{replayMessages:m,completedToolCallIds:[...te.completedToolCallIds,...V],lastStopReason:"tool_calls"}),e.toolChoice==="required"&&re.length>0&&(Xt=!0);let Li=re.length>0&&re.every(l=>{let d=m.find(T=>T?.role==="tool"&&T?.tool_call_id===l.id);if(!d)return!0;let h=d.content;return typeof h=="string"&&h.startsWith("Error: ")}),_e=u.consecutiveFailedRounds;if(Li){if(_e+=1,_e>=cr){if(Co>=3&&u.repeatedToolFailureRecoveryCount<1){let T=oo({inputMessages:i,messages:m,finalText:u.finalText,thinkingBlocks:[],stopHookActive:u.stopHookActive,totalToolCallCount:F,distinctToolNames:L,log:o});if(T?.reason==="explicit_required_file_verification"||T?.reason==="explicit_extra_file_verification"){yield E("repeated_tool_failure_artifact_recovery","one recovery nudge before ending a complex explicit artifact turn after repeated tool failures"),u={...u,messages:T.messages,stopHookActive:T.stopHookActive,transition:T.transition,consecutiveFailedRounds:0,repeatedToolFailureRecoveryCount:u.repeatedToolFailureRecoveryCount+1};continue}}if(u.repeatedToolFailureRecoveryCount<1){let T=ds(m);if(T){yield E("repeated_tool_failure_self_correction","one help-guided self-correction round before ending on repeated tool failures"),u={...u,messages:[...m,T],consecutiveFailedRounds:0,repeatedToolFailureRecoveryCount:u.repeatedToolFailureRecoveryCount+1};continue}}let l=`repeated tool failures (${_e} rounds in a row)`,d=Oe({inputMessages:i,messages:m,reason:`${l} before all required files were produced`})??(u.finalText.trim()?u.finalText:Xn(m,_e)),h=ni(d,{availableToolNames:R(a??c),enabledToolNames:Vt(),toolCallNames:[...L].sort(),blockedToolCalls:Ft(D)});o.info(`early exit: ${_e} consecutive failed rounds, returning ${u.finalText?"partial":"fallback"} response`),yield*H(h,{forcedStop:!0});return}}else _e=0;let Ct=[...u.fileReadCycleBlockedPaths].filter(l=>!u.fileReadCycleNudgedPaths.has(l));if(Ct.length>0){let l=Ct.join(", "),d=[...new Set(Ct.map(ao))].join(" ");o.info(`AP5: file read cycle detected on ${l}, injecting nudge`);let h={role:"user",content:`Read-cycle guard blocked repeated reads for: ${l}. ${d} Stop reading these source files this turn; summarize from maintained evidence and explain any remaining uncertainty.`};m.push(h);for(let T of Ct)u.fileReadCycleNudgedPaths.add(T)}let De=ce+1;if(v>0&&De>v){if(o.info(`max turns reached (${v}), completing`),k){let h=await k.invoke("stop",{sessionId:s,reason:"max_turns"});if(h.action==="abort"){let T=h.reason??"Stop hook requested continuation after max_turns",p={role:"assistant",content:u.finalText,...ue.length>0&&{thinkingBlocks:[...ue]}};u={...u,messages:[...m,p,{role:"user",content:T}],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}};continue}}let l=Oe({inputMessages:i,messages:m,reason:`tool loop max turns reached (${v}) before completing all required files`});if(l){yield*H(l,{forcedStop:!0});return}let d=Xe(m,`tool loop max turns reached (${v}) before completing the final status contract`);yield*H(d);return}if(qt&&Re(u).size>0&&De>z&&z<100&&(z=Math.min(100,De+25),o.info(`background task lifecycle wait extended round budget to ${z}`)),qt&&De>z){let l=Yn({currentToolBudget:se,currentRoundBudget:z,toolHardCap:100,roundHardCap:100,continuationCount:We,successfulSinceLastCheck:Ge-lt,fileReadCounts:u.fileReadCounts,windowTools:Ce,windowRounds:25});l&&(z=l.nextRoundBudget,se=l.nextToolBudget,We=l.continuationCount,lt=Ge,o.info(`round budget continuation #${l.continuationCount}: rounds\u2192${z}, tools\u2192${se} (progress detected)`))}if(De>z){o.info(`tool loop budget exhausted (${z} rounds), returning`);let l=ro({totalToolCallCount:F,distinctToolNames:L,projectRoot:e.projectRoot});l&&(yield{type:"skill_instruction",turnId:r,instruction:l});let d=Oe({inputMessages:i,messages:m,reason:`tool budget exhausted (${z} rounds) before completing all required files`});if(d){yield*H(d,{forcedStop:!0});return}let h=Xe(m,`tool budget exhausted (${z} rounds) before completing the final status contract`);yield*H(h);return}u={messages:m,maxOutputTokensRecoveryCount:0,hasAttemptedReactiveCompact:!1,maxOutputTokensOverride:void 0,turnCount:De,transition:{reason:"next_turn"},guardState:j,reactiveCompactState:ee,toolLoopState:te,consecutiveFailedRounds:_e,finalText:u.finalText,totalUsage:u.totalUsage,collapseStore:tn,currentModel:u.currentModel,consecutive529Errors:0,consecutiveApiRetries:0,stopHookActive:u.stopHookActive,lastResponseId:u.lastResponseId,snipRemovedIds:u.snipRemovedIds,contentReplacementState:u.contentReplacementState,budgetContinuationCount:u.budgetContinuationCount,repeatedToolFailureRecoveryCount:u.repeatedToolFailureRecoveryCount,lastBudgetDeltaTokens:u.lastBudgetDeltaTokens,lastBudgetGlobalTokens:u.lastBudgetGlobalTokens,identicalCallCounts:pt,identicalSuccessfulToolResults:u.identicalSuccessfulToolResults,artifactContract:u.artifactContract,toolFailureCounts:u.toolFailureCounts,fileReadCounts:u.fileReadCounts,fileReadCycleBlockedPaths:u.fileReadCycleBlockedPaths,fileReadCycleNudgedPaths:u.fileReadCycleNudgedPaths,maintainedDocuments:u.maintainedDocuments,persistedLongHorizonStateRecovered:u.persistedLongHorizonStateRecovered,longHorizonStateMaintenanceRequiredFiles:u.longHorizonStateMaintenanceRequiredFiles,longHorizonStateMaintenanceWrittenFiles:u.longHorizonStateMaintenanceWrittenFiles,recoveryTrace:u.recoveryTrace,browserAcceptanceRecoveryCount:u.browserAcceptanceRecoveryCount,buildVerificationRecoveryCount:u.buildVerificationRecoveryCount,longHorizonStateIntegrityRecoveryCount:u.longHorizonStateIntegrityRecoveryCount,backgroundAgentTaskIds:Re(u),backgroundAgentNoOutputPollCounts:u.backgroundAgentNoOutputPollCounts,stalledBackgroundAgentTasks:u.stalledBackgroundAgentTasks,notOfferedToolRecoveryCount:u.notOfferedToolRecoveryCount,existingFileUpdateRecoveryCount:u.existingFileUpdateRecoveryCount,taskListReconciliationCount:u.taskListReconciliationCount,lastTaskList:u.lastTaskList}}}var zu=["\u63A5\u5355\u91D1\u989D","\u5408\u540C\u91D1\u989D","\u62A5\u4EF7","\u9884\u7B97","\u91D1\u989D","price","amount","contract amount"];function hi(e){let t=Hu(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: ${gi(o.l1Amount)}; L2 long-term says: ${gi(o.l2Amount)}; action: ask the user which value is current before using it.`)}for(let o of e){let r=Wu(o);n.push(`- [${r}] ${o.text}`)}return n.join(`
|
|
46
|
+
`)}function Hu(e){let t=e.filter(r=>r.source==="l1-project-md").flatMap(r=>mi(r.text)),n=e.filter(r=>r.source==="l2-long-term").flatMap(r=>mi(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 Vu(o)}function mi(e){let t=[];for(let n of e.split(/\r?\n/)){let o=n.trim();if(o)for(let r of zu){if(r==="\u91D1\u989D"&&/(接单金额|合同金额)/u.test(o))continue;let s=new RegExp(`${Xu(r)}[^0-9.\u4E07kK,]{0,12}([0-9][0-9.,]*\\s*(?:\u4E07|k|K)?)`,"gi");for(let i of o.matchAll(s)){let a=Gu(i[1]);a!==null&&t.push({entity:qu(o,r),predicate:r,amount:a,text:o})}}}return t}function qu(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 Gu(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 Wu(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 gi(e){return Number.isInteger(e)?String(e):String(Number(e.toFixed(4)))}function Vu(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 Xu(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var Ku=8192;async function yi(e){let{hooks:t,detectRecallCategories:n,log:o,sessionId:r,turnId:s,query:i}=e;try{let a=n(i),f=(await t.invoke("memory.before_recall",{sessionId:r,turnId:s,query:i,preferredCategories:a.preferred.length>0?a.preferred:void 0,deprioritizedCategories:a.deprioritized.length>0?a.deprioritized:void 0}))?.context?.recalledMemories,g=null;if(f&&f.length>0){let y=0,k=[];for(let x of f){let _=(x.text?.length??0)*2;if(y+_>Ku)break;k.push(x),y+=_}k.length>0&&(g=`[Recalled memories \u2014 context priority: project-specific facts override general user preferences when they conflict]
|
|
47
|
+
${hi(k)}`)}return $(t,"memory.after_recall",{sessionId:r,turnId:s,blockCount:f?.length??0},o),g}catch{return null}}var bi=class{transport;apiKey;toolInvoker;log;hooks;maxRounds;configuredMaxRounds;projectRoot;runtimePorts;constructor(t){this.transport=t.llmTransport,this.apiKey=t.apiKey,this.toolInvoker=t.toolInvoker,this.log=t.log,this.hooks=t.hooks,this.projectRoot=t.projectRoot,this.runtimePorts=t.runtimePorts,this.configuredMaxRounds=typeof t.maxRounds=="number"&&Number.isFinite(t.maxRounds)?Math.min(t.maxRounds,100):void 0,this.maxRounds=Math.min(this.configuredMaxRounds??25,100)}async*run(t,n){let{turnId:o,messages:r,availableTools:s,tools:i,systemPrompt:a,config:c}=t,f={sessionId:t.sessionId,turnId:o};yield{type:"start",turnId:o},$(this.hooks,"turn.submitted",{...f,prompt:r[r.length-1]?.content??void 0},this.log);let g=wn(r),y=[];if(a&&y.push({role:"system",content:a}),y.push(...g),this.hooks){let v=g.filter(M=>M.role==="user").pop(),S=typeof v?.content=="string"?v.content.slice(0,500):void 0;if(S){let M=await yi({hooks:this.hooks,detectRecallCategories:N=>this.runtimePorts.detectRecallCategories(N),log:this.log,sessionId:t.sessionId,turnId:o,query:S});M&&y.splice(a?1:0,0,{role:"system",content:M})}}let k=c?.model??"",x=typeof c?.maxRounds=="number"&&Number.isFinite(c.maxRounds)?c.maxRounds:this.configuredMaxRounds,_=x===void 0?void 0:Math.min(x,100);try{let v=c?.reasoning;c?.reasoning?.effort==="auto"&&(v={...c?.reasoning,effort:"medium"});let S={turnId:o,sessionId:t.sessionId,messages:y,availableTools:s,tools:i,refreshTools:t.refreshTools,drainPendingGuidance:t.drainPendingGuidance,model:k,apiKey:c?.apiKey??this.apiKey,temperature:c?.temperature,maxRounds:_,contextWindowTokens:c?.contextWindowTokens,maxOutputTokens:c?.maxOutputTokens,modelMaxOutputTokens:c?.modelMaxOutputTokens,toolChoice:c?.toolChoice,parentDepth:c?.parentDepth,hooks:this.hooks,fallbackModel:c?.fallbackModel,maxTurns:c?.maxTurns,tokenBudget:c?.tokenBudget,maxConcurrentTools:c?.maxConcurrentTools,streamRequired:c?.streamRequired,reasoning:v,promptCacheKey:c?.promptCacheKey,promptCacheRetention:c?.promptCacheRetention,serviceTier:c?.serviceTier,openaiBuiltinTools:c?.openaiBuiltinTools,maxToolCalls:c?.maxToolCalls,parallelToolCalls:c?.parallelToolCalls,textVerbosity:c?.textVerbosity,projectRoot:this.projectRoot,runtimePorts:this.runtimePorts.toolLoop,signal:n},M;for await(let N of pi(S,this.transport,this.toolInvoker,this.log))M=N,yield N;M?.type==="end"?$(this.hooks,"turn.completed",{...f},this.log):M?.type==="error"&&$(this.hooks,"turn.failed",{...f,code:M.code,error:M.error},this.log)}catch(v){if(n?.aborted)$(this.hooks,"turn.failed",{...f,code:"ABORTED",error:"Turn aborted"},this.log),yield{type:"error",turnId:o,error:"Turn aborted",code:"ABORTED"};else{let S=v instanceof Error?v.message:String(v),M=typeof v?.status=="number"?v.status:void 0,N=$e(M,S);this.log.error(`turn ${o} error [${N}, retryable=${hn(N)}]: ${S}`),$(this.hooks,"turn.failed",{...f,code:N,error:S},this.log),yield{type:"error",turnId:o,error:S,code:N}}}}};export{bi as Agent};
|