blade-code 0.10.180 → 0.10.181
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/blade.js +2 -2
- package/dist/{chunk-fnyc55qh.js → chunk-0rqme7wf.js} +1 -1
- package/dist/{chunk-xbxk17d9.js → chunk-19t17t01.js} +1 -1
- package/dist/{chunk-7aafkkcw.js → chunk-25sph3tg.js} +1 -1
- package/dist/chunk-31gar9m8.js +1 -0
- package/dist/{chunk-h8jw7rw2.js → chunk-3834n4zw.js} +1 -1
- package/dist/{chunk-zt17d0yy.js → chunk-3mf0w32c.js} +1 -1
- package/dist/{chunk-xz1pthfb.js → chunk-58fw7r3p.js} +1 -1
- package/dist/{chunk-7e8pfma5.js → chunk-5eahvhk2.js} +1 -1
- package/dist/{chunk-tk5yhvqp.js → chunk-5pk8ym5x.js} +1 -1
- package/dist/{chunk-y4ygcr73.js → chunk-61hfyn3e.js} +3 -3
- package/dist/{chunk-m1vrv7fh.js → chunk-6egxkwda.js} +1 -1
- package/dist/{chunk-htpks2cw.js → chunk-6wf7jham.js} +1 -1
- package/dist/{chunk-z51sa3ek.js → chunk-7s5p5j3y.js} +1 -1
- package/dist/{chunk-2a6cnbss.js → chunk-7sysaeqw.js} +1 -1
- package/dist/{chunk-gyz808at.js → chunk-89865f6k.js} +1 -1
- package/dist/{chunk-bbb5hyk0.js → chunk-8zszbcn4.js} +1 -1
- package/dist/{chunk-wer9cash.js → chunk-abc2ecjy.js} +1 -1
- package/dist/{chunk-wvatwzmh.js → chunk-b9g45hy8.js} +1 -1
- package/dist/chunk-bn0kn8k3.js +1 -0
- package/dist/{chunk-mgef8nfk.js → chunk-cq0s0xy5.js} +1 -1
- package/dist/{chunk-4eah5sdc.js → chunk-cv1b7eyh.js} +1 -1
- package/dist/{chunk-cyssag2q.js → chunk-egmdn632.js} +9 -9
- package/dist/{chunk-p44nnxcq.js → chunk-f0v7zm2r.js} +1 -1
- package/dist/{chunk-c5hh137s.js → chunk-fnd2gmeg.js} +1 -1
- package/dist/{chunk-72se5srv.js → chunk-fnhq1xqg.js} +1 -1
- package/dist/{chunk-p8t4sbq5.js → chunk-fy5xxgzb.js} +1 -1
- package/dist/{chunk-qw71c44y.js → chunk-g3711t7a.js} +1 -1
- package/dist/{chunk-89vvw6az.js → chunk-h77d4vx7.js} +1 -1
- package/dist/{chunk-y7x9a53w.js → chunk-jf7gr1xw.js} +1 -1
- package/dist/{chunk-dbexmkcm.js → chunk-msgzv7x3.js} +1 -1
- package/dist/{chunk-2teay1y6.js → chunk-my2arhv0.js} +1 -1
- package/dist/{chunk-jh5shn18.js → chunk-n187rnac.js} +1 -1
- package/dist/{chunk-6m586pcf.js → chunk-pmk5f0n8.js} +1 -1
- package/dist/{chunk-e9ft9v1e.js → chunk-rrjxnjkq.js} +1 -1
- package/dist/{chunk-yfqbef1x.js → chunk-t9rrxzxe.js} +1 -1
- package/dist/{chunk-9q9kw8yk.js → chunk-tsythbm8.js} +2 -2
- package/dist/{chunk-j1w519qd.js → chunk-wkcy0was.js} +1 -1
- package/dist/{chunk-8vw0cde5.js → chunk-xg0h1hdz.js} +1 -1
- package/package.json +1 -1
- package/dist/chunk-4ed22xz8.js +0 -1
- package/dist/chunk-bpc0qfpq.js +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{wc as U8}from"./chunk-zzvs471p.js";import{$d as n1,Ac as N2,Bc as i1,Dc as z$,Ed as y2,Fd as q8,Gd as G8,Hd as Q6,Id as t1,Jd as L8,Kd as F8,Ld as c1,Pd as lJ,Yd as u0,_d as S6,ae as T6,he as W1,td as _2,vd as A2,wd as b2,xc as U$,xd as B6,yd as D6,zc as w$}from"./chunk-tk5yhvqp.js";import{me as w8}from"./chunk-53fc0yrq.js";import{Ee as E0,pe as q0,se as V2,te as C$}from"./chunk-y5wngtz0.js";import{dg as C2}from"./chunk-t0gm0pn1.js";import{eg as B8,fg as r0,gg as X8,hg as uJ,jg as d1,kg as E6,lg as mJ,mg as dJ,pg as cJ}from"./chunk-1yq72zb7.js";import{bh as Y$,ch as n0,fh as D8}from"./chunk-3kszepm6.js";import{kh as n2,oh as J2}from"./chunk-wcps5gjm.js";import{zh as E$}from"./chunk-e9ft9v1e.js";import{Ui as R$}from"./chunk-kv458q06.js";import{bj as j0}from"./chunk-2f8d0km4.js";import{Dj as T0}from"./chunk-2mk914vk.js";import{Xj as P2}from"./chunk-xbxk17d9.js";import{Bk as GJ,Ck as s1,Ek as L2,Jk as F2,Kk as O2,fk as G2,uk as B2,vk as D2,yk as K1}from"./chunk-4wx5sya5.js";import{Mk as mZ}from"./chunk-eg3ms291.js";function y$($){return $.role==="system"&&Array.isArray($.content)}function b$($){if($.role!=="system"||!$.metadata||Array.isArray($.metadata))return!1;return typeof $.metadata==="object"&&$.metadata.contextualProjectRules===!0}class I1{systemMessages;_contextualSystemMessages;_history;_pending=[];_contextRevision=0;context;constructor($,Z){this.context=$;let J=$.messages.find(y$);if(this._contextualSystemMessages=$.messages.filter(b$),J)this.systemMessages=[J,...this._contextualSystemMessages];else if(Z)this.systemMessages=[{role:"system",content:[{type:"text",text:Z,providerOptions:{anthropic:{cacheControl:{type:"ephemeral"}}}}]},...this._contextualSystemMessages];else this.systemMessages=[...this._contextualSystemMessages];this._history=$.messages.filter((W)=>!y$(W)&&!b$(W))}get historyLength(){return this._history.length}get history(){return this._history}get pending(){return this._pending}get contextRevision(){return this._contextRevision}toLLMMessages(){return[...this.systemMessages,...this._history,...this._pending]}getMessagesForLLM(){return this.toLLMMessages()}getHistory(){return this._history}appendPending($){this._pending.push($)}appendUser($){this._pending.push($)}appendAssistant($){this._pending.push($)}appendToolResult($){this._pending.push($)}appendContextualProjectInstructions($){if(!b$($))throw Error("Contextual project instructions require safe metadata");this._contextualSystemMessages.push($),this.systemMessages.push($)}syncContextualSystemMessages(){let $=this.systemMessages.filter(y$);this.systemMessages.splice(0,this.systemMessages.length,...$,...this._contextualSystemMessages)}appendControl($,Z){if($==="system")throw Error("Cannot append system control message via appendControl. Use constructor for root system prompt.");this._pending.push({...Z,metadata:{...Z.metadata&&typeof Z.metadata==="object"&&!Array.isArray(Z.metadata)?Z.metadata:{},...E0}})}appendDurableControl($){if(!$.id||$.role!=="user")throw Error("Durable control messages require a user role and identity");if(this._history.some((Z)=>Z.id===$.id))return;this._history.push($)}appendToHistory($){this._history.push($)}commitPending(){if(this._pending.length>0)this._history.push(...this._pending),this._pending=[]}replaceHistory($){this._history=$.filter((Z)=>!y$(Z)&&!b$(Z)),this._contextRevision++}restoreDurableHistory($){this._contextualSystemMessages=$.filter(b$),this._history=$.filter((Z)=>!y$(Z)&&!b$(Z)),this._pending=[],this.syncContextualSystemMessages(),this._contextRevision++}removeMessages($){let Z=[this._history.length,this._pending.length,this._contextualSystemMessages.length];if(this._history=this._history.filter((J)=>!$(J)),this._pending=this._pending.filter((J)=>!$(J)),this._contextualSystemMessages=this._contextualSystemMessages.filter((J)=>!$(J)),this.syncContextualSystemMessages(),this._history.length!==Z[0]||this._pending.length!==Z[1]||this._contextualSystemMessages.length!==Z[2])this._contextRevision++}writeback(){this.commitPending(),this.context.messages=[...this._contextualSystemMessages,...this._history]}get hasSystemPrompt(){return this.systemMessages.length>0}}function s6($){if($.isSubagent)return"continue";if(!$.budget||$.budget<=0)return"continue";if($.consecutiveContinuations>=3&&$.lastOutputDelta<500)return"stop";if($.usage/$.budget>=0.9)return"stop";return"continue"}function t6($){return{budget:$.budget,usage:0,consecutiveContinuations:0,lastOutputDelta:0,isSubagent:$.isSubagent??!1}}function e6($,Z,J){return{...$,usage:$.usage+Z,lastOutputDelta:Z,consecutiveContinuations:J?$.consecutiveContinuations+1:0}}import V$ from"node:path";var R8=new Set(["GOEXPERIMENT","GOOS","GOARCH","CGO_ENABLED","GO111MODULE","RUST_BACKTRACE","RUST_LOG","NODE_ENV","PYTHONUNBUFFERED","PYTHONDONTWRITEBYTECODE","GIT_TERMINAL_PROMPT","LANG","LANGUAGE","LC_ALL","LC_CTYPE","LC_TIME","CHARSET","TERM","COLORTERM","NO_COLOR","FORCE_COLOR","TZ","LS_COLORS","LSCOLORS","GREP_COLOR","GREP_COLORS"]),M8=/^(LD_.+|DYLD_.+|PATH)$/,$J=/^([A-Za-z_][A-Za-z0-9_]*)=([\w./:@-]*)$/;function t$($){let Z=$;while(!0){let J=Z.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!J)break;let W=J[1],Y=J[2],K=W.match($J);if(!K)break;let X=K[1];if(!R8.has(X))break;Z=Y}return Z}function l5($){let Z=$;while(!0){let J=Z.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!J)break;let W=J[1],Y=J[2],K=W.match($J);if(!K)break;let X=K[1];if(M8.test(X))break;Z=Y}return Z}var k8=[/^timeout[ \t]+(?:--foreground[ \t]+|--preserve-status[ \t]+|-v[ \t]+|--verbose[ \t]+|-k[ \t]+\S+[ \t]+|--kill-after[= ]\S+[ \t]+|-s[ \t]+\S+[ \t]+|--signal[= ]\S+[ \t]+)*\S+[ \t]+/,/^time[ \t]+/,/^nice[ \t]+(?:-n[ \t]+\d+[ \t]+|-\d+[ \t]+)?/,/^nohup[ \t]+/];function RZ($){let Z=$,J=!0;while(J){J=!1;for(let W of k8){let Y=Z.match(W);if(Y){Z=Z.slice(Y[0].length),J=!0;break}}if(Z.startsWith("-- "))Z=Z.slice(3),J=!0}return Z}function e$($){let Z=[],J="",W=!1,Y=!1,K=!1;for(let X=0;X<$.length;X++){let Q=$[X];if(K){J+=Q,K=!1;continue}if(Q==="\\"&&!W){J+=Q,K=!0;continue}if(Q==="'"&&!Y){W=!W,J+=Q;continue}if(Q==='"'&&!W){Y=!Y,J+=Q;continue}if(W||Y){J+=Q;continue}if(Q==="|"){if(X+1<$.length&&$[X+1]==="|"){if(J.trim())Z.push(J.trim());J="",X++;continue}return null}if(Q===">"||Q==="<")return null;if(Q==="&"&&X+1<$.length&&$[X+1]==="&"){if(J.trim())Z.push(J.trim());J="",X++;continue}if(Q==="&")return null;if(Q===";"){if(J.trim())Z.push(J.trim());J="";continue}J+=Q}if(J.trim())Z.push(J.trim());return Z.length>0?Z:null}function ZJ($){let Z=!1,J=!1,W=!1;for(let Y=0;Y<$.length;Y++){let K=$[Y];if(W){W=!1;continue}if(K==="\\"&&!Z){W=!0;continue}if(K==="'"&&!J){Z=!Z;continue}if(K==='"'&&!Z){J=!J;continue}if(Z)continue;if(K==="$"){let X=$[Y+1];if(X&&/[A-Za-z_@*#?!$0-9({]/.test(X))return!0}if(K==="`")return!0;if(J)continue;if(K==="|")return!0;if(K===">"||K==="<")return!0;if(K==="{"){let X=$.slice(Y);if(/^\{[^}]*,[^}]*\}/.test(X)||/^\{[^}]*\.\.[^}]*\}/.test(X))return!0}}return!1}function H$($){let Z=[],J="",W=!1,Y=!1,K=!1;for(let X=0;X<$.length;X++){let Q=$[X];if(K){J+=Q,K=!1;continue}if(Q==="\\"&&!W){if(K=!0,Y){let H=$[X+1];if(H&&'$`"\\'.includes(H))continue;J+=Q,K=!1}continue}if(Q==="'"&&!Y){W=!W;continue}if(Q==='"'&&!W){Y=!Y;continue}if(!W&&!Y&&/[ \t]/.test(Q)){if(J)Z.push(J),J="";continue}J+=Q}if(J)Z.push(J);return Z}var x8=new Set(["npm","pnpm","yarn","bun"]),JJ=new Set(["biome","eslint","jest","mypy","pyright","pytest","ruff","tsc","vitest"]),I8=new Set(["-u","--fix","--update","--update-snapshot","--updateSnapshot","--watch","--watchAll","--write"]),h8=/[ \t]*;[ \t]*echo[ \t]+"[A-Za-z0-9 _:=.-]*(?:\$\{PIPESTATUS\[0\]\}|\$\?)[A-Za-z0-9 _:=.-]*"[ \t]*$/;function v8($){return $!==void 0&&/^(?:test|lint|build|type-?check)(?::[\w.-]+)*$/i.test($)}function WJ($){return $.replace(/\s+2>&1\s*$/,"").trim()}function C8($,Z,J){if(!J||Z.length!==2)return;let W=/^(.+?)[ \t]+&&[ \t]+([\s\S]+)$/.exec($);if(!W)return;let Y=H$(W[1]??"");if(Y.length!==2||Y[0]!=="cd")return;let K=Y[1];if(!K||K==="-")return;let X=V$.isAbsolute(K)?V$.resolve(K):V$.resolve(J,K);if(!z$.isWithinWorkspace(X,J))return;return W[2]?.trim()||void 0}function g8($){let Z=[],J=!1,W=!1,Y=!1;for(let K=0;K<$.length;K++){let X=$[K];if(Y){Y=!1;continue}if(X==="\\"&&!J){Y=!0;continue}if(X==="'"&&!W){J=!J;continue}if(X==='"'&&!J){W=!W;continue}if(X!=="|"||J||W)continue;if($[K+1]==="|")return;Z.push(K)}return Z}function p8($){let Z=H$($),[J,W,Y]=Z;if(J!=="head"&&J!=="tail")return!1;if(Z.length===1)return!0;let K=(X)=>X!==void 0&&/^[1-9]\d{0,4}$/.test(X);if(Z.length===2)return W?.startsWith("--lines=")&&K(W.slice(8))||W?.startsWith("-")&&K(W.slice(1));return Z.length===3&&(W==="-n"||W==="--lines")&&K(Y)}function u8($){let Z=WJ($.replace(h8,"").trim()),J=g8(Z);if(!J)return;if(J.length===0)return YJ(Z);if(J.length!==1)return;let W=J[0];if(W===void 0)return;let Y=WJ(Z.slice(0,W).trim()),K=Z.slice(W+1).trim();if(!Y||!p8(K))return;return YJ(Y)}function YJ($){let J=e$($)?.at(-1);if(!J)return $;let W=H$(J),[Y,K]=W;if(!(Y==="vitest"||(Y==="npx"||Y==="bunx")&&K==="vitest")||W.some((Q)=>Q==="--configLoader"||Q.startsWith("--configLoader=")))return $;return`${$} --configLoader runner`}function f$($,Z){let J=u8($);if(!J)return!1;let W=t$(J),Y=e$(W);if(!Y||ZJ(W)||/[\r\n]/.test(W))return!1;let K=Y.length===1?Y[0]:C8(W,Y,Z);if(!K)return!1;let X=H$(K);if(X.length===0||X.some((z)=>[...I8].some((B)=>z===B||z.startsWith(`${B}=`))))return!1;let[Q,H,V]=X;if(x8.has(Q??""))return v8(H==="run"?V:H)||H==="--test";if((Q==="npx"||Q==="bunx")&&JJ.has(H??""))return!0;if(JJ.has(Q??""))return!0;if(Q==="node"&&H==="--test")return!0;if(Q==="go"&&["build","test","vet"].includes(H??""))return!0;return Q==="cargo"&&["build","check","clippy","test"].includes(H??"")}function a5($,Z){if($===void 0)return!0;if(typeof $!=="string"||$.split(/[\\/]/).includes(".."))return!1;if(!Z)return!V$.isAbsolute($);let J=V$.isAbsolute($)?V$.resolve($):V$.resolve(Z,$);return z$.isWithinWorkspace(J,Z)}var MZ=T0("Agent"),m8=3;function kZ($,Z,J){if($!=="length")return{action:"none"};if(Z>=m8)return{action:"truncated"};if(s6(J)==="stop")return MZ.info("[Loop] Token budget: diminishing returns detected, skipping recovery"),{action:"budget_stop"};return{action:"recover"}}var d8=[/:\s*$/,/:\s*$/,/\.\.\.\s*$/,/让我(先|来|开始|查看|检查|修复)/,/Let me (first|start|check|look|fix)/i,/I('ll| will) (now |)(create|write|edit|update|modify|fix|add|implement)/i,/我(现在就|来|要)(创建|写入|编辑|修改|修复|添加|实现)/,/\d+\.\s+(First|Next|Then|Finally)/i],c8=/```[\s\S]{50,}```/,KJ="请执行你提到的操作,不要只是描述。使用 Edit/Write/ApplyPatch/Bash 工具来实际修改文件。",l8=2;function xZ($,Z,J=!0){if(!$||Z>=l8)return{action:"none"};if(!J&&c8.test($))return{action:"retry",prompt:KJ};let W=$.slice(-200),Y=W.match(/```/g);if(Y&&Y.length%2!==0)return{action:"none"};if(d8.some((X)=>X.test(W)))return{action:"retry",prompt:KJ};return{action:"none"}}var h1=2,i8="The model returned tool-call JSON as text instead of completing the requested tool workflow.",r8="The previous response contained tool-call JSON as ordinary text. It did not execute a tool. If the requested operation is still needed, use the native tool-call interface with an available tool. If it already succeeded, use the recorded result to answer instead of repeating the operation. Do not return another tool-call JSON envelope as your final answer.";function IZ($,Z,J,W){if(!$||$.length>65536||J.length===0)return{action:"none"};let Y=Z.replace(/```[\s\S]*?(?:```|$)/g,"").replace(/^\s*>.*$/gm,"");if(/\b(?:example|schema|serialize|serialization|quote|print|illustrate|verbatim)\b|示例|样例|序列化|引用原文/i.test(Y)||/\b(?:explain|show|return|output)\b[^.!?\n]{0,80}\b(?:json|tool.calls?)\b|(?:解释|展示|输出|返回)[^。!?\n]{0,40}(?:JSON|工具调用格式)/i.test(Y)||/\b(?:do not|don't|never)\s+(?:use|call|invoke|execute)\s+(?:any\s+)?tools?\b|不要(?:使用|调用|执行)(?:任何)?工具/i.test(Y))return{action:"none"};let K;try{K=JSON.parse($)}catch{return{action:"none"}}if(!K||typeof K!=="object"||Array.isArray(K)||Object.keys(K).length!==1||!("tool_calls"in K)||!Array.isArray(K.tool_calls)||K.tool_calls.length===0||K.tool_calls.length>32)return{action:"none"};let X=new Set;for(let Q of K.tool_calls){if(!Q||typeof Q!=="object"||Array.isArray(Q))return{action:"none"};let H="function"in Q;if(Object.keys(Q).some((L)=>!["id","type",...H?["function"]:["name","arguments"]].includes(L)))return{action:"none"};if("type"in Q&&Q.type!=="function")return{action:"none"};let V=H?Q.function:Q;if(!V||typeof V!=="object"||Array.isArray(V)||!("name"in V)||typeof V.name!=="string"||!("arguments"in V))return{action:"none"};if(H&&Object.keys(V).some((L)=>L!=="name"&&L!=="arguments"))return{action:"none"};if(!J.includes(V.name))return{action:"none"};let z=V.arguments;if(typeof z!=="string"&&(!z||typeof z!=="object"||Array.isArray(z)))return{action:"none"};let B=V.name.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),j=new RegExp(`(?:^|[.!?。!?;;\\n])\\s*(?:please\\s+)?(?:call|invoke|execute|run|use)\\s+(?:the\\s+)?(?:tool\\s+)?[\`"']?${B}(?![\\w:-])|(?:^|[。!?;\\n])\\s*(?:请)?(?:调用|使用|执行)\\s*(?:工具\\s*)?[\`"']?${B}(?![\\w:-])`,"i"),w=new RegExp(`(?:do not|don't|never)\\s+(?:call|invoke|execute|run|use)\\s+(?:the\\s+)?(?:tool\\s+)?[\`"']?${B}(?![\\w:-])|(?:不要|禁止)(?:调用|使用|执行)\\s*(?:工具\\s*)?[\`"']?${B}(?![\\w:-])`,"i");if(!j.test(Y)||w.test(Y))return{action:"none"};X.add(V.name)}return W<h1?{action:"retry",prompt:r8,...X.size===1?{toolName:[...X][0]}:{}}:{action:"fail",message:i8}}var n8=[/\b(?:run|execute|rerun|re-run)\b[\s\S]{0,60}\b(?:tests?|test suite|lint|type-?check|build)\b/i,/\b(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?(?:test|lint|build|type-?check)\b/i,/(?:运行|执行|跑|重新运行).{0,30}(?:测试|单测|集成测试|检查|构建)/],XJ={test:/\b(?:tests?|test suite)\b|(?:测试|单测|集成测试)/i,lint:/\blint(?:ing)?\b/i,"type-check":/\btype[\s-]?check(?:ing)?\b|\btsc\b|类型检查/i,build:/\bbuild\b|构建/i},o8={test:/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?test\b|(?:^|\s)(?:node|bun)\s+--test\b|(?:^|\s)(?:vitest|jest|pytest|go\s+test|cargo\s+test)\b/i,lint:/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?lint\b/i,"type-check":/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?type-?check\b|(?:^|\s)tsc\b/i,build:/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?build\b/i},a8="The user explicitly required verification, but it has not run successfully. Do not finish or explain. Your next action must be a Bash tool call that runs the requested test, lint, type-check, or build command. Inspect the command result and fix any failure before finishing.",s8="Required verification did not run successfully before the retry limit.",t8=3;function HJ($,Z,J,W){if(!J.success)return;if(["Edit","Write","ApplyPatch","NotebookEdit"].includes(Z)){$.clear();return}if(Z==="Bash"&&typeof J.metadata?.command==="string"&&J.metadata.exit_code===0&&f$(J.metadata.command,W)){$.add(J.metadata.command);return}if(!["Task","TaskOutput"].includes(Z))return;let Y=J.metadata?.verificationCommands;if(!Array.isArray(Y))return;for(let K of Y)if(typeof K==="string"&&f$(K,W))$.add(K)}function hZ($,Z,J){if(!$||!n8.some((H)=>H.test($)))return{action:"none"};let W=Object.keys(XJ).filter((H)=>XJ[H].test($)),Y=[...Z],K=W.filter((H)=>!Y.some((V)=>o8[H].test(V)));if(W.length>0?K.length===0:Y.some((H)=>f$(H)))return{action:"none"};if(J>=t8)return{action:"fail",message:s8};let Q=W.length>1&&K.length>0?` Missing successful verification categories: ${K.join(", ")}.`:"";return{action:"retry",prompt:`${a8}${Q}`}}var e8=[/\bdelegate\b[\s\S]{0,120}\b(?:Task tool|subagent|agent)\b/i,/\b(?:call|use|invoke)\b[\s\S]{0,80}\bTask tool\b/i,/(?:委派|交给|调用|使用).{0,60}(?:Task|子代理|子智能体)/],VJ=[/\b(?:do not|don't|never)\s+(?:delegate|call|use|invoke)\b/i,/(?:不要|禁止|无需)(?:委派|调用|使用).{0,20}(?:Task|子代理|子智能体)?/];function zJ($){return typeof $==="string"&&VJ.some((Z)=>Z.test($))}var $9=[/\b(?:call|use|invoke)\b[\s\S]{0,30}\bTask(?: tool)?\b[\s\S]{0,30}\bexactly once\b/i,/\bexactly once\b[\s\S]{0,30}\b(?:call|use|invoke)\b[\s\S]{0,30}\bTask(?: tool)?\b/i,/\bexactly one\b[\s\S]{0,30}\bTask(?: tool)? calls?\b/i,/(?:Task|子代理).{0,20}(?:恰好|仅|只)(?:调用|使用)?一次/,/(?:恰好|仅|只)(?:调用|使用)?一次.{0,20}(?:Task|子代理)/],Z9=[/\b(?:do not|don't|never)\s+(?:call|use|invoke)\s+(?:the\s+)?Task\b[\s\S]{0,30}\bexactly once\b/i,/\bTask\b[\s\S]{0,30}\b(?:does not|doesn't|need not)\b[\s\S]{0,30}\bexactly once\b/i,/\bmultiple\s+Task(?: tool)?\s+calls?\s+(?:are\s+)?allowed\b/i,/(?:不要|禁止).{0,12}(?:Task|子代理).{0,12}(?:恰好|仅|只)(?:调用|使用)?一次/];function J9($){if(typeof $!=="string")return;if(Z9.some((Z)=>Z.test($)))return"multiple-allowed";return $9.some((Z)=>Z.test($))?"required":void 0}function Z1($){for(let Z of $){let J=J9(Z);if(J!==void 0)return J==="required"}return!1}var W9="The user explicitly required delegation, but no Task tool call completed successfully. Do not solve the task directly or explain. Your next action must be a Task tool call using the requested subagent.",Y9="Required delegation did not complete before the retry limit.",K9=3;function jJ($,Z,J){let W=(typeof $==="string"?[$]:$??[]).map((X)=>X.trim()).filter(Boolean),Y=Z1(W),K=!1;if(!Y)for(let X of W){if(VJ.some((Q)=>Q.test(X)))break;if(e8.some((Q)=>Q.test(X))){K=!0;break}}if(W.length===0||!Y&&!K||Z.has("Task"))return{action:"none"};if(J>=K9)return{action:"fail",message:Y9};return{action:"retry",prompt:W9}}var X9=[/\b(?:use|create|enter|start|work\s+(?:in|inside))\b.{0,60}\bworktree\b/i,/(?:使用|创建|进入).{0,30}(?:worktree|工作树)/i],Q9=[/\b(?:exit|leave)\b.{0,40}\bworktree\b/i,/\bworktree\b.{0,60}\b(?:action\s+)?(?:keep|remove)\b/i,/(?:退出|离开).{0,30}(?:worktree|工作树)/i],H9=[/\b(?:do not|don't|never|must not|should not)\b[^.!?;\n]{0,80}\b(?:git\s+)?worktree\b/gi,/\bwithout\b[^.!?;\n]{0,60}\b(?:git\s+)?worktree\b/gi,/(?:不要|禁止|不得|无需)[^。!?;\n]{0,50}(?:worktree|工作树)/gi];function BJ($){return H9.reduce((Z,J)=>Z.replace(J," "),$)}function v1($){if(typeof $!=="string")return!1;let Z=BJ($);return X9.some((J)=>J.test(Z))}var V9="The user explicitly required git worktree isolation, but EnterWorktree has not completed successfully. Do not continue in the original workspace. Your next action must be an EnterWorktree tool call. Wait for its result before using file or Bash tools.",z9="The user explicitly required leaving the managed worktree, but ExitWorktree has not completed successfully. Do not finish or explain. Your next action must be an ExitWorktree tool call using the action requested by the user.",j9="Required worktree lifecycle did not complete before the retry limit.",B9=3;function DJ($,Z,J){if(!$)return{action:"none"};let W=BJ($);if(!v1(W))return{action:"none"};let Y=Q9.some((X)=>X.test(W));if(Z.has("TaskWorktree"))return{action:"none"};let K=!Z.has("EnterWorktree")?"EnterWorktree":Y&&!Z.has("ExitWorktree")?"ExitWorktree":void 0;if(!K)return{action:"none"};if(J>=B9)return{action:"fail",message:j9};return{action:"retry",tool:K,prompt:K==="EnterWorktree"?V9:z9}}var QJ=30000;async function vZ($){try{let J=E$.getInstance().executeStopHooks({projectDir:$.workspaceRoot??j0(),sessionId:$.sessionId,permissionMode:$.permissionMode,reason:$.reason,abortSignal:$.abortSignal}),W,Y=new Promise((K)=>{W=setTimeout(()=>K("timeout"),QJ)});try{let K=await Promise.race([J,Y]);if(K==="timeout")return MZ.warn(`[Loop] Stop hook 超时 (${QJ}ms),按 shouldStop: true 处理`),{action:"stop"};let X=K;if(!X.shouldStop)return{action:"continue",reason:X.continueReason};return{action:"stop"}}finally{clearTimeout(W)}}catch(Z){return MZ.warn("[Loop] Stop hook execution failed:",Z),{action:"stop"}}}async function D9($,Z){let J;while(!(J=await $.next()).done)if(Z)await Z(J.value);return J.value}var w9=[/<system-reminder>[\s\S]*?<\/system-reminder>/gi,/<file[^>]*>[\s\S]*?<\/file>/gi,/<hooks_context>[\s\S]*?<\/hooks_context>/gi,/<[^>]+>/g];function U9($){if(typeof $==="string")return $;if(Array.isArray($))return $.map((Z)=>{if(typeof Z==="string")return Z;if(Z&&typeof Z==="object"&&"text"in Z){let J=Z.text;return typeof J==="string"?J:""}return""}).join(" ");return""}function q9($){let Z=$;for(let H of w9)Z=Z.replace(H," ");Z=Z.replace(/^\s*\/[a-zA-Z][\w-]*\s+/,"");let J=Z.replace(/\s+/g," ").trim();if(!J)return"";let W=J.match(/^(.+?)(?:[.!?]\s|[。!?](?=\S|$)|$)/),Y=W&&W[1].length>=6?W[1]:J;if(Y=Y.trim().replace(/[\s.。!!??,,;;::-]+$/,""),Y.length<=60)return Y;let K=Y.slice(0,60),X=K.lastIndexOf(" ");return`${(X>36?K.slice(0,X):K).trimEnd()}…`}function wJ($){return q9(U9($))}import{EventEmitter as G9}from"events";import UJ from"node:path";function CZ($){if(GJ($.sessionId),!UJ.isAbsolute($.projectPath))throw Error("projectPath must be absolute");return{sessionId:$.sessionId,projectPath:UJ.resolve($.projectPath)}}function qJ($){let Z=CZ($);return JSON.stringify([Z.projectPath,Z.sessionId])}function V3($,Z){return qJ($)===qJ(Z)}class S$ extends G9{static instance;constructor(){super();this.setMaxListeners(100)}static getInstance(){if(!S$.instance)S$.instance=new S$;return S$.instance}publish($,Z,J,W){let Y=CZ($);this.emit("event",{sessionId:Y.sessionId,projectPath:Y.projectPath,type:Z,...W!==void 0?{seq:W}:{},properties:J})}subscribe($){return this.on("event",$),()=>this.off("event",$)}}var J1=S$.getInstance();var $$=T0("Agent"),C1=new Set;async function L9($,Z){let J=$.sessionId;if(!J||$.subagentInfo)return;if(C1.has(J))return;if(C1.size>=5000)C1.clear();C1.add(J);try{let W=$.workspaceRoot,Y=await W1.findSessionMetadata(J,W);if(!Y)return;if(Y.title&&Y.title.trim())return;let K=wJ(Z);if(!K)return;await W1.updateSessionMetadata(J,Y.projectPath,{title:K}),J1.publish({sessionId:J,projectPath:Y.projectPath},"session.updated",{title:K})}catch(W){$$.debug?.("[Loop] 自动生成会话标题失败:",W)}}var gZ=`<turn_aborted>
|
|
1
|
+
import{wc as U8}from"./chunk-zzvs471p.js";import{$d as n1,Ac as N2,Bc as i1,Dc as z$,Ed as y2,Fd as q8,Gd as G8,Hd as Q6,Id as t1,Jd as L8,Kd as F8,Ld as c1,Pd as lJ,Yd as u0,_d as S6,ae as T6,he as W1,td as _2,vd as A2,wd as b2,xc as U$,xd as B6,yd as D6,zc as w$}from"./chunk-5pk8ym5x.js";import{me as w8}from"./chunk-53fc0yrq.js";import{Ee as E0,pe as q0,se as V2,te as C$}from"./chunk-y5wngtz0.js";import{dg as C2}from"./chunk-t0gm0pn1.js";import{eg as B8,fg as r0,gg as X8,hg as uJ,jg as d1,kg as E6,lg as mJ,mg as dJ,pg as cJ}from"./chunk-1yq72zb7.js";import{bh as Y$,ch as n0,fh as D8}from"./chunk-3kszepm6.js";import{kh as n2,oh as J2}from"./chunk-wcps5gjm.js";import{zh as E$}from"./chunk-rrjxnjkq.js";import{Ui as R$}from"./chunk-kv458q06.js";import{bj as j0}from"./chunk-2f8d0km4.js";import{Dj as T0}from"./chunk-2mk914vk.js";import{Xj as P2}from"./chunk-19t17t01.js";import{Bk as GJ,Ck as s1,Ek as L2,Jk as F2,Kk as O2,fk as G2,uk as B2,vk as D2,yk as K1}from"./chunk-4wx5sya5.js";import{Mk as mZ}from"./chunk-eg3ms291.js";function y$($){return $.role==="system"&&Array.isArray($.content)}function b$($){if($.role!=="system"||!$.metadata||Array.isArray($.metadata))return!1;return typeof $.metadata==="object"&&$.metadata.contextualProjectRules===!0}class I1{systemMessages;_contextualSystemMessages;_history;_pending=[];_contextRevision=0;context;constructor($,Z){this.context=$;let J=$.messages.find(y$);if(this._contextualSystemMessages=$.messages.filter(b$),J)this.systemMessages=[J,...this._contextualSystemMessages];else if(Z)this.systemMessages=[{role:"system",content:[{type:"text",text:Z,providerOptions:{anthropic:{cacheControl:{type:"ephemeral"}}}}]},...this._contextualSystemMessages];else this.systemMessages=[...this._contextualSystemMessages];this._history=$.messages.filter((W)=>!y$(W)&&!b$(W))}get historyLength(){return this._history.length}get history(){return this._history}get pending(){return this._pending}get contextRevision(){return this._contextRevision}toLLMMessages(){return[...this.systemMessages,...this._history,...this._pending]}getMessagesForLLM(){return this.toLLMMessages()}getHistory(){return this._history}appendPending($){this._pending.push($)}appendUser($){this._pending.push($)}appendAssistant($){this._pending.push($)}appendToolResult($){this._pending.push($)}appendContextualProjectInstructions($){if(!b$($))throw Error("Contextual project instructions require safe metadata");this._contextualSystemMessages.push($),this.systemMessages.push($)}syncContextualSystemMessages(){let $=this.systemMessages.filter(y$);this.systemMessages.splice(0,this.systemMessages.length,...$,...this._contextualSystemMessages)}appendControl($,Z){if($==="system")throw Error("Cannot append system control message via appendControl. Use constructor for root system prompt.");this._pending.push({...Z,metadata:{...Z.metadata&&typeof Z.metadata==="object"&&!Array.isArray(Z.metadata)?Z.metadata:{},...E0}})}appendDurableControl($){if(!$.id||$.role!=="user")throw Error("Durable control messages require a user role and identity");if(this._history.some((Z)=>Z.id===$.id))return;this._history.push($)}appendToHistory($){this._history.push($)}commitPending(){if(this._pending.length>0)this._history.push(...this._pending),this._pending=[]}replaceHistory($){this._history=$.filter((Z)=>!y$(Z)&&!b$(Z)),this._contextRevision++}restoreDurableHistory($){this._contextualSystemMessages=$.filter(b$),this._history=$.filter((Z)=>!y$(Z)&&!b$(Z)),this._pending=[],this.syncContextualSystemMessages(),this._contextRevision++}removeMessages($){let Z=[this._history.length,this._pending.length,this._contextualSystemMessages.length];if(this._history=this._history.filter((J)=>!$(J)),this._pending=this._pending.filter((J)=>!$(J)),this._contextualSystemMessages=this._contextualSystemMessages.filter((J)=>!$(J)),this.syncContextualSystemMessages(),this._history.length!==Z[0]||this._pending.length!==Z[1]||this._contextualSystemMessages.length!==Z[2])this._contextRevision++}writeback(){this.commitPending(),this.context.messages=[...this._contextualSystemMessages,...this._history]}get hasSystemPrompt(){return this.systemMessages.length>0}}function s6($){if($.isSubagent)return"continue";if(!$.budget||$.budget<=0)return"continue";if($.consecutiveContinuations>=3&&$.lastOutputDelta<500)return"stop";if($.usage/$.budget>=0.9)return"stop";return"continue"}function t6($){return{budget:$.budget,usage:0,consecutiveContinuations:0,lastOutputDelta:0,isSubagent:$.isSubagent??!1}}function e6($,Z,J){return{...$,usage:$.usage+Z,lastOutputDelta:Z,consecutiveContinuations:J?$.consecutiveContinuations+1:0}}import V$ from"node:path";var R8=new Set(["GOEXPERIMENT","GOOS","GOARCH","CGO_ENABLED","GO111MODULE","RUST_BACKTRACE","RUST_LOG","NODE_ENV","PYTHONUNBUFFERED","PYTHONDONTWRITEBYTECODE","GIT_TERMINAL_PROMPT","LANG","LANGUAGE","LC_ALL","LC_CTYPE","LC_TIME","CHARSET","TERM","COLORTERM","NO_COLOR","FORCE_COLOR","TZ","LS_COLORS","LSCOLORS","GREP_COLOR","GREP_COLORS"]),M8=/^(LD_.+|DYLD_.+|PATH)$/,$J=/^([A-Za-z_][A-Za-z0-9_]*)=([\w./:@-]*)$/;function t$($){let Z=$;while(!0){let J=Z.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!J)break;let W=J[1],Y=J[2],K=W.match($J);if(!K)break;let X=K[1];if(!R8.has(X))break;Z=Y}return Z}function l5($){let Z=$;while(!0){let J=Z.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!J)break;let W=J[1],Y=J[2],K=W.match($J);if(!K)break;let X=K[1];if(M8.test(X))break;Z=Y}return Z}var k8=[/^timeout[ \t]+(?:--foreground[ \t]+|--preserve-status[ \t]+|-v[ \t]+|--verbose[ \t]+|-k[ \t]+\S+[ \t]+|--kill-after[= ]\S+[ \t]+|-s[ \t]+\S+[ \t]+|--signal[= ]\S+[ \t]+)*\S+[ \t]+/,/^time[ \t]+/,/^nice[ \t]+(?:-n[ \t]+\d+[ \t]+|-\d+[ \t]+)?/,/^nohup[ \t]+/];function RZ($){let Z=$,J=!0;while(J){J=!1;for(let W of k8){let Y=Z.match(W);if(Y){Z=Z.slice(Y[0].length),J=!0;break}}if(Z.startsWith("-- "))Z=Z.slice(3),J=!0}return Z}function e$($){let Z=[],J="",W=!1,Y=!1,K=!1;for(let X=0;X<$.length;X++){let Q=$[X];if(K){J+=Q,K=!1;continue}if(Q==="\\"&&!W){J+=Q,K=!0;continue}if(Q==="'"&&!Y){W=!W,J+=Q;continue}if(Q==='"'&&!W){Y=!Y,J+=Q;continue}if(W||Y){J+=Q;continue}if(Q==="|"){if(X+1<$.length&&$[X+1]==="|"){if(J.trim())Z.push(J.trim());J="",X++;continue}return null}if(Q===">"||Q==="<")return null;if(Q==="&"&&X+1<$.length&&$[X+1]==="&"){if(J.trim())Z.push(J.trim());J="",X++;continue}if(Q==="&")return null;if(Q===";"){if(J.trim())Z.push(J.trim());J="";continue}J+=Q}if(J.trim())Z.push(J.trim());return Z.length>0?Z:null}function ZJ($){let Z=!1,J=!1,W=!1;for(let Y=0;Y<$.length;Y++){let K=$[Y];if(W){W=!1;continue}if(K==="\\"&&!Z){W=!0;continue}if(K==="'"&&!J){Z=!Z;continue}if(K==='"'&&!Z){J=!J;continue}if(Z)continue;if(K==="$"){let X=$[Y+1];if(X&&/[A-Za-z_@*#?!$0-9({]/.test(X))return!0}if(K==="`")return!0;if(J)continue;if(K==="|")return!0;if(K===">"||K==="<")return!0;if(K==="{"){let X=$.slice(Y);if(/^\{[^}]*,[^}]*\}/.test(X)||/^\{[^}]*\.\.[^}]*\}/.test(X))return!0}}return!1}function H$($){let Z=[],J="",W=!1,Y=!1,K=!1;for(let X=0;X<$.length;X++){let Q=$[X];if(K){J+=Q,K=!1;continue}if(Q==="\\"&&!W){if(K=!0,Y){let H=$[X+1];if(H&&'$`"\\'.includes(H))continue;J+=Q,K=!1}continue}if(Q==="'"&&!Y){W=!W;continue}if(Q==='"'&&!W){Y=!Y;continue}if(!W&&!Y&&/[ \t]/.test(Q)){if(J)Z.push(J),J="";continue}J+=Q}if(J)Z.push(J);return Z}var x8=new Set(["npm","pnpm","yarn","bun"]),JJ=new Set(["biome","eslint","jest","mypy","pyright","pytest","ruff","tsc","vitest"]),I8=new Set(["-u","--fix","--update","--update-snapshot","--updateSnapshot","--watch","--watchAll","--write"]),h8=/[ \t]*;[ \t]*echo[ \t]+"[A-Za-z0-9 _:=.-]*(?:\$\{PIPESTATUS\[0\]\}|\$\?)[A-Za-z0-9 _:=.-]*"[ \t]*$/;function v8($){return $!==void 0&&/^(?:test|lint|build|type-?check)(?::[\w.-]+)*$/i.test($)}function WJ($){return $.replace(/\s+2>&1\s*$/,"").trim()}function C8($,Z,J){if(!J||Z.length!==2)return;let W=/^(.+?)[ \t]+&&[ \t]+([\s\S]+)$/.exec($);if(!W)return;let Y=H$(W[1]??"");if(Y.length!==2||Y[0]!=="cd")return;let K=Y[1];if(!K||K==="-")return;let X=V$.isAbsolute(K)?V$.resolve(K):V$.resolve(J,K);if(!z$.isWithinWorkspace(X,J))return;return W[2]?.trim()||void 0}function g8($){let Z=[],J=!1,W=!1,Y=!1;for(let K=0;K<$.length;K++){let X=$[K];if(Y){Y=!1;continue}if(X==="\\"&&!J){Y=!0;continue}if(X==="'"&&!W){J=!J;continue}if(X==='"'&&!J){W=!W;continue}if(X!=="|"||J||W)continue;if($[K+1]==="|")return;Z.push(K)}return Z}function p8($){let Z=H$($),[J,W,Y]=Z;if(J!=="head"&&J!=="tail")return!1;if(Z.length===1)return!0;let K=(X)=>X!==void 0&&/^[1-9]\d{0,4}$/.test(X);if(Z.length===2)return W?.startsWith("--lines=")&&K(W.slice(8))||W?.startsWith("-")&&K(W.slice(1));return Z.length===3&&(W==="-n"||W==="--lines")&&K(Y)}function u8($){let Z=WJ($.replace(h8,"").trim()),J=g8(Z);if(!J)return;if(J.length===0)return YJ(Z);if(J.length!==1)return;let W=J[0];if(W===void 0)return;let Y=WJ(Z.slice(0,W).trim()),K=Z.slice(W+1).trim();if(!Y||!p8(K))return;return YJ(Y)}function YJ($){let J=e$($)?.at(-1);if(!J)return $;let W=H$(J),[Y,K]=W;if(!(Y==="vitest"||(Y==="npx"||Y==="bunx")&&K==="vitest")||W.some((Q)=>Q==="--configLoader"||Q.startsWith("--configLoader=")))return $;return`${$} --configLoader runner`}function f$($,Z){let J=u8($);if(!J)return!1;let W=t$(J),Y=e$(W);if(!Y||ZJ(W)||/[\r\n]/.test(W))return!1;let K=Y.length===1?Y[0]:C8(W,Y,Z);if(!K)return!1;let X=H$(K);if(X.length===0||X.some((z)=>[...I8].some((B)=>z===B||z.startsWith(`${B}=`))))return!1;let[Q,H,V]=X;if(x8.has(Q??""))return v8(H==="run"?V:H)||H==="--test";if((Q==="npx"||Q==="bunx")&&JJ.has(H??""))return!0;if(JJ.has(Q??""))return!0;if(Q==="node"&&H==="--test")return!0;if(Q==="go"&&["build","test","vet"].includes(H??""))return!0;return Q==="cargo"&&["build","check","clippy","test"].includes(H??"")}function a5($,Z){if($===void 0)return!0;if(typeof $!=="string"||$.split(/[\\/]/).includes(".."))return!1;if(!Z)return!V$.isAbsolute($);let J=V$.isAbsolute($)?V$.resolve($):V$.resolve(Z,$);return z$.isWithinWorkspace(J,Z)}var MZ=T0("Agent"),m8=3;function kZ($,Z,J){if($!=="length")return{action:"none"};if(Z>=m8)return{action:"truncated"};if(s6(J)==="stop")return MZ.info("[Loop] Token budget: diminishing returns detected, skipping recovery"),{action:"budget_stop"};return{action:"recover"}}var d8=[/:\s*$/,/:\s*$/,/\.\.\.\s*$/,/让我(先|来|开始|查看|检查|修复)/,/Let me (first|start|check|look|fix)/i,/I('ll| will) (now |)(create|write|edit|update|modify|fix|add|implement)/i,/我(现在就|来|要)(创建|写入|编辑|修改|修复|添加|实现)/,/\d+\.\s+(First|Next|Then|Finally)/i],c8=/```[\s\S]{50,}```/,KJ="请执行你提到的操作,不要只是描述。使用 Edit/Write/ApplyPatch/Bash 工具来实际修改文件。",l8=2;function xZ($,Z,J=!0){if(!$||Z>=l8)return{action:"none"};if(!J&&c8.test($))return{action:"retry",prompt:KJ};let W=$.slice(-200),Y=W.match(/```/g);if(Y&&Y.length%2!==0)return{action:"none"};if(d8.some((X)=>X.test(W)))return{action:"retry",prompt:KJ};return{action:"none"}}var h1=2,i8="The model returned tool-call JSON as text instead of completing the requested tool workflow.",r8="The previous response contained tool-call JSON as ordinary text. It did not execute a tool. If the requested operation is still needed, use the native tool-call interface with an available tool. If it already succeeded, use the recorded result to answer instead of repeating the operation. Do not return another tool-call JSON envelope as your final answer.";function IZ($,Z,J,W){if(!$||$.length>65536||J.length===0)return{action:"none"};let Y=Z.replace(/```[\s\S]*?(?:```|$)/g,"").replace(/^\s*>.*$/gm,"");if(/\b(?:example|schema|serialize|serialization|quote|print|illustrate|verbatim)\b|示例|样例|序列化|引用原文/i.test(Y)||/\b(?:explain|show|return|output)\b[^.!?\n]{0,80}\b(?:json|tool.calls?)\b|(?:解释|展示|输出|返回)[^。!?\n]{0,40}(?:JSON|工具调用格式)/i.test(Y)||/\b(?:do not|don't|never)\s+(?:use|call|invoke|execute)\s+(?:any\s+)?tools?\b|不要(?:使用|调用|执行)(?:任何)?工具/i.test(Y))return{action:"none"};let K;try{K=JSON.parse($)}catch{return{action:"none"}}if(!K||typeof K!=="object"||Array.isArray(K)||Object.keys(K).length!==1||!("tool_calls"in K)||!Array.isArray(K.tool_calls)||K.tool_calls.length===0||K.tool_calls.length>32)return{action:"none"};let X=new Set;for(let Q of K.tool_calls){if(!Q||typeof Q!=="object"||Array.isArray(Q))return{action:"none"};let H="function"in Q;if(Object.keys(Q).some((L)=>!["id","type",...H?["function"]:["name","arguments"]].includes(L)))return{action:"none"};if("type"in Q&&Q.type!=="function")return{action:"none"};let V=H?Q.function:Q;if(!V||typeof V!=="object"||Array.isArray(V)||!("name"in V)||typeof V.name!=="string"||!("arguments"in V))return{action:"none"};if(H&&Object.keys(V).some((L)=>L!=="name"&&L!=="arguments"))return{action:"none"};if(!J.includes(V.name))return{action:"none"};let z=V.arguments;if(typeof z!=="string"&&(!z||typeof z!=="object"||Array.isArray(z)))return{action:"none"};let B=V.name.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),j=new RegExp(`(?:^|[.!?。!?;;\\n])\\s*(?:please\\s+)?(?:call|invoke|execute|run|use)\\s+(?:the\\s+)?(?:tool\\s+)?[\`"']?${B}(?![\\w:-])|(?:^|[。!?;\\n])\\s*(?:请)?(?:调用|使用|执行)\\s*(?:工具\\s*)?[\`"']?${B}(?![\\w:-])`,"i"),w=new RegExp(`(?:do not|don't|never)\\s+(?:call|invoke|execute|run|use)\\s+(?:the\\s+)?(?:tool\\s+)?[\`"']?${B}(?![\\w:-])|(?:不要|禁止)(?:调用|使用|执行)\\s*(?:工具\\s*)?[\`"']?${B}(?![\\w:-])`,"i");if(!j.test(Y)||w.test(Y))return{action:"none"};X.add(V.name)}return W<h1?{action:"retry",prompt:r8,...X.size===1?{toolName:[...X][0]}:{}}:{action:"fail",message:i8}}var n8=[/\b(?:run|execute|rerun|re-run)\b[\s\S]{0,60}\b(?:tests?|test suite|lint|type-?check|build)\b/i,/\b(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?(?:test|lint|build|type-?check)\b/i,/(?:运行|执行|跑|重新运行).{0,30}(?:测试|单测|集成测试|检查|构建)/],XJ={test:/\b(?:tests?|test suite)\b|(?:测试|单测|集成测试)/i,lint:/\blint(?:ing)?\b/i,"type-check":/\btype[\s-]?check(?:ing)?\b|\btsc\b|类型检查/i,build:/\bbuild\b|构建/i},o8={test:/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?test\b|(?:^|\s)(?:node|bun)\s+--test\b|(?:^|\s)(?:vitest|jest|pytest|go\s+test|cargo\s+test)\b/i,lint:/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?lint\b/i,"type-check":/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?type-?check\b|(?:^|\s)tsc\b/i,build:/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?build\b/i},a8="The user explicitly required verification, but it has not run successfully. Do not finish or explain. Your next action must be a Bash tool call that runs the requested test, lint, type-check, or build command. Inspect the command result and fix any failure before finishing.",s8="Required verification did not run successfully before the retry limit.",t8=3;function HJ($,Z,J,W){if(!J.success)return;if(["Edit","Write","ApplyPatch","NotebookEdit"].includes(Z)){$.clear();return}if(Z==="Bash"&&typeof J.metadata?.command==="string"&&J.metadata.exit_code===0&&f$(J.metadata.command,W)){$.add(J.metadata.command);return}if(!["Task","TaskOutput"].includes(Z))return;let Y=J.metadata?.verificationCommands;if(!Array.isArray(Y))return;for(let K of Y)if(typeof K==="string"&&f$(K,W))$.add(K)}function hZ($,Z,J){if(!$||!n8.some((H)=>H.test($)))return{action:"none"};let W=Object.keys(XJ).filter((H)=>XJ[H].test($)),Y=[...Z],K=W.filter((H)=>!Y.some((V)=>o8[H].test(V)));if(W.length>0?K.length===0:Y.some((H)=>f$(H)))return{action:"none"};if(J>=t8)return{action:"fail",message:s8};let Q=W.length>1&&K.length>0?` Missing successful verification categories: ${K.join(", ")}.`:"";return{action:"retry",prompt:`${a8}${Q}`}}var e8=[/\bdelegate\b[\s\S]{0,120}\b(?:Task tool|subagent|agent)\b/i,/\b(?:call|use|invoke)\b[\s\S]{0,80}\bTask tool\b/i,/(?:委派|交给|调用|使用).{0,60}(?:Task|子代理|子智能体)/],VJ=[/\b(?:do not|don't|never)\s+(?:delegate|call|use|invoke)\b/i,/(?:不要|禁止|无需)(?:委派|调用|使用).{0,20}(?:Task|子代理|子智能体)?/];function zJ($){return typeof $==="string"&&VJ.some((Z)=>Z.test($))}var $9=[/\b(?:call|use|invoke)\b[\s\S]{0,30}\bTask(?: tool)?\b[\s\S]{0,30}\bexactly once\b/i,/\bexactly once\b[\s\S]{0,30}\b(?:call|use|invoke)\b[\s\S]{0,30}\bTask(?: tool)?\b/i,/\bexactly one\b[\s\S]{0,30}\bTask(?: tool)? calls?\b/i,/(?:Task|子代理).{0,20}(?:恰好|仅|只)(?:调用|使用)?一次/,/(?:恰好|仅|只)(?:调用|使用)?一次.{0,20}(?:Task|子代理)/],Z9=[/\b(?:do not|don't|never)\s+(?:call|use|invoke)\s+(?:the\s+)?Task\b[\s\S]{0,30}\bexactly once\b/i,/\bTask\b[\s\S]{0,30}\b(?:does not|doesn't|need not)\b[\s\S]{0,30}\bexactly once\b/i,/\bmultiple\s+Task(?: tool)?\s+calls?\s+(?:are\s+)?allowed\b/i,/(?:不要|禁止).{0,12}(?:Task|子代理).{0,12}(?:恰好|仅|只)(?:调用|使用)?一次/];function J9($){if(typeof $!=="string")return;if(Z9.some((Z)=>Z.test($)))return"multiple-allowed";return $9.some((Z)=>Z.test($))?"required":void 0}function Z1($){for(let Z of $){let J=J9(Z);if(J!==void 0)return J==="required"}return!1}var W9="The user explicitly required delegation, but no Task tool call completed successfully. Do not solve the task directly or explain. Your next action must be a Task tool call using the requested subagent.",Y9="Required delegation did not complete before the retry limit.",K9=3;function jJ($,Z,J){let W=(typeof $==="string"?[$]:$??[]).map((X)=>X.trim()).filter(Boolean),Y=Z1(W),K=!1;if(!Y)for(let X of W){if(VJ.some((Q)=>Q.test(X)))break;if(e8.some((Q)=>Q.test(X))){K=!0;break}}if(W.length===0||!Y&&!K||Z.has("Task"))return{action:"none"};if(J>=K9)return{action:"fail",message:Y9};return{action:"retry",prompt:W9}}var X9=[/\b(?:use|create|enter|start|work\s+(?:in|inside))\b.{0,60}\bworktree\b/i,/(?:使用|创建|进入).{0,30}(?:worktree|工作树)/i],Q9=[/\b(?:exit|leave)\b.{0,40}\bworktree\b/i,/\bworktree\b.{0,60}\b(?:action\s+)?(?:keep|remove)\b/i,/(?:退出|离开).{0,30}(?:worktree|工作树)/i],H9=[/\b(?:do not|don't|never|must not|should not)\b[^.!?;\n]{0,80}\b(?:git\s+)?worktree\b/gi,/\bwithout\b[^.!?;\n]{0,60}\b(?:git\s+)?worktree\b/gi,/(?:不要|禁止|不得|无需)[^。!?;\n]{0,50}(?:worktree|工作树)/gi];function BJ($){return H9.reduce((Z,J)=>Z.replace(J," "),$)}function v1($){if(typeof $!=="string")return!1;let Z=BJ($);return X9.some((J)=>J.test(Z))}var V9="The user explicitly required git worktree isolation, but EnterWorktree has not completed successfully. Do not continue in the original workspace. Your next action must be an EnterWorktree tool call. Wait for its result before using file or Bash tools.",z9="The user explicitly required leaving the managed worktree, but ExitWorktree has not completed successfully. Do not finish or explain. Your next action must be an ExitWorktree tool call using the action requested by the user.",j9="Required worktree lifecycle did not complete before the retry limit.",B9=3;function DJ($,Z,J){if(!$)return{action:"none"};let W=BJ($);if(!v1(W))return{action:"none"};let Y=Q9.some((X)=>X.test(W));if(Z.has("TaskWorktree"))return{action:"none"};let K=!Z.has("EnterWorktree")?"EnterWorktree":Y&&!Z.has("ExitWorktree")?"ExitWorktree":void 0;if(!K)return{action:"none"};if(J>=B9)return{action:"fail",message:j9};return{action:"retry",tool:K,prompt:K==="EnterWorktree"?V9:z9}}var QJ=30000;async function vZ($){try{let J=E$.getInstance().executeStopHooks({projectDir:$.workspaceRoot??j0(),sessionId:$.sessionId,permissionMode:$.permissionMode,reason:$.reason,abortSignal:$.abortSignal}),W,Y=new Promise((K)=>{W=setTimeout(()=>K("timeout"),QJ)});try{let K=await Promise.race([J,Y]);if(K==="timeout")return MZ.warn(`[Loop] Stop hook 超时 (${QJ}ms),按 shouldStop: true 处理`),{action:"stop"};let X=K;if(!X.shouldStop)return{action:"continue",reason:X.continueReason};return{action:"stop"}}finally{clearTimeout(W)}}catch(Z){return MZ.warn("[Loop] Stop hook execution failed:",Z),{action:"stop"}}}async function D9($,Z){let J;while(!(J=await $.next()).done)if(Z)await Z(J.value);return J.value}var w9=[/<system-reminder>[\s\S]*?<\/system-reminder>/gi,/<file[^>]*>[\s\S]*?<\/file>/gi,/<hooks_context>[\s\S]*?<\/hooks_context>/gi,/<[^>]+>/g];function U9($){if(typeof $==="string")return $;if(Array.isArray($))return $.map((Z)=>{if(typeof Z==="string")return Z;if(Z&&typeof Z==="object"&&"text"in Z){let J=Z.text;return typeof J==="string"?J:""}return""}).join(" ");return""}function q9($){let Z=$;for(let H of w9)Z=Z.replace(H," ");Z=Z.replace(/^\s*\/[a-zA-Z][\w-]*\s+/,"");let J=Z.replace(/\s+/g," ").trim();if(!J)return"";let W=J.match(/^(.+?)(?:[.!?]\s|[。!?](?=\S|$)|$)/),Y=W&&W[1].length>=6?W[1]:J;if(Y=Y.trim().replace(/[\s.。!!??,,;;::-]+$/,""),Y.length<=60)return Y;let K=Y.slice(0,60),X=K.lastIndexOf(" ");return`${(X>36?K.slice(0,X):K).trimEnd()}…`}function wJ($){return q9(U9($))}import{EventEmitter as G9}from"events";import UJ from"node:path";function CZ($){if(GJ($.sessionId),!UJ.isAbsolute($.projectPath))throw Error("projectPath must be absolute");return{sessionId:$.sessionId,projectPath:UJ.resolve($.projectPath)}}function qJ($){let Z=CZ($);return JSON.stringify([Z.projectPath,Z.sessionId])}function V3($,Z){return qJ($)===qJ(Z)}class S$ extends G9{static instance;constructor(){super();this.setMaxListeners(100)}static getInstance(){if(!S$.instance)S$.instance=new S$;return S$.instance}publish($,Z,J,W){let Y=CZ($);this.emit("event",{sessionId:Y.sessionId,projectPath:Y.projectPath,type:Z,...W!==void 0?{seq:W}:{},properties:J})}subscribe($){return this.on("event",$),()=>this.off("event",$)}}var J1=S$.getInstance();var $$=T0("Agent"),C1=new Set;async function L9($,Z){let J=$.sessionId;if(!J||$.subagentInfo)return;if(C1.has(J))return;if(C1.size>=5000)C1.clear();C1.add(J);try{let W=$.workspaceRoot,Y=await W1.findSessionMetadata(J,W);if(!Y)return;if(Y.title&&Y.title.trim())return;let K=wJ(Z);if(!K)return;await W1.updateSessionMetadata(J,Y.projectPath,{title:K}),J1.publish({sessionId:J,projectPath:Y.projectPath},"session.updated",{title:K})}catch(W){$$.debug?.("[Loop] 自动生成会话标题失败:",W)}}var gZ=`<turn_aborted>
|
|
2
2
|
The previous turn was interrupted. Commands or tool calls may have partially completed; inspect the workspace and running processes before retrying.
|
|
3
3
|
</turn_aborted>`,j$="Tool execution was blocked because its durable call record could not be committed. No tool side effect was started.",LJ="Tool execution completed, but its durable result record could not be committed. Further model and tool execution was stopped. The operation may have completed; inspect external state before retrying.";class T$ extends Error{phase;constructor($,Z){super($==="user_message"?"Conversation input could not be committed. No further model request was started.":"Model output could not be committed. The run was stopped before any further model request or successful completion.",Z);this.phase=$;this.name="DurableConversationPersistenceError"}}function B$($){return $.executionEngine?.getContextManager()}async function i0($,Z,J,W=null,Y,K={}){let X=K.required??$.executionEngine!==void 0;try{let Q=B$($),H=typeof J==="string"?J.trim()!=="":J.some((V)=>V.type==="text"?V.text.trim()!=="":!0);if(Q&&Z.sessionId&&H){let V=await Q.saveMessage(Z.sessionId,"user",J,W,Y,Z.subagentInfo);if(X&&!V)throw Error("Durable user-message commit returned no identity");if(Y?.clientVisible!==!1)L9(Z,J);return V}if(X&&Z.sessionId&&H)throw Error("Durable user-message storage is unavailable")}catch(Q){if($$.warn("[Loop] 保存用户消息失败:",Q),X)throw new T$("user_message",{cause:Q})}return null}async function C0($,Z,J,W,Y,K,X={}){let Q=X.required??$.executionEngine!==void 0;try{let H=B$($),V=Boolean(J.trim()||Y?.trim());if(H&&Z.sessionId&&V){let z=await H.saveMessage(Z.sessionId,"assistant",J,W,K,Z.subagentInfo,Y);if(Q&&!z)throw Error("Durable assistant-message commit returned no identity");return z}if(Q&&Z.sessionId&&V)throw Error("Durable assistant-message storage is unavailable")}catch(H){if($$.warn("[Loop] 保存助手消息失败:",H),Q)throw new T$("assistant_message",{cause:H})}return null}async function FJ($,Z,J){try{let W=B$($);if(W&&Z.sessionId)return await W.saveMessage(Z.sessionId,"system",gZ,J,void 0,Z.subagentInfo)}catch(W){$$.warn("[Loop] 保存中断边界失败:",W)}return null}async function OJ($,Z,J,W,Y){try{let K=B$($);if(!K||!Z.sessionId||J.length===0)return null;return await K.saveMessage(Z.sessionId,"system",`<contextual-project-instructions-ref count="${J.length}" />`,Y,{contextualProjectRules:!0,ruleReferences:JSON.parse(JSON.stringify(J.map((X)=>({...X})))),triggerPaths:[...W]},Z.subagentInfo)}catch(K){$$.warn("[Loop] 保存 contextual project rules provenance 失败:",K)}return null}async function pZ($,Z,J,W,Y,K={}){try{let X=B$($);if(X&&Z.sessionId){let Q=await X.saveToolUse(Z.sessionId,J,W,Y,Z.subagentInfo,K.providerToolCallId);if(K.required&&!Q)throw Error("Durable tool-use commit returned no identity");return Q}if(K.required&&Z.sessionId)throw Error("Durable tool-use storage is unavailable")}catch(X){if($$.warn("[Loop] 保存工具调用失败:",X),K.required)throw X}return null}async function g1($,Z,J,W,Y,K,X,Q,H,V={}){try{let z=B$($);if(z&&Z.sessionId){let B=await z.saveToolResult(Z.sessionId,J,W,Y,K,X,Z.subagentInfo,Q,H);if(V.required&&!B)throw Error("Durable tool-result commit returned no identity");return B}if(V.required&&Z.sessionId)throw Error("Durable tool-result storage is unavailable")}catch(z){if($$.warn("[Loop] 保存工具结果失败:",z),V.required)throw z}return null}async function Y1($,Z,J,W,Y={}){try{let K=B$($);if(K&&Z.sessionId){let X=await K.saveCompaction(Z.sessionId,J,W,null);if(Y.required&&!X)throw Error("Compaction checkpoint commit returned no identity");return X||null}if(Y.required&&Z.sessionId)throw Error("Compaction checkpoint storage is unavailable")}catch(K){if($$.warn("[Loop] 保存压缩数据失败:",K),Y.required)throw K}return null}async function V0($){let{deps:Z,context:J,state:W,assistantContent:Y,assistantReasoningContent:K,lastMessageUuid:X,controlPrompt:Q}=$;W.appendAssistant({role:"assistant",content:Y,reasoningContent:K});let H=X,V=await C0(Z,J,Y,H,K);if(V)H=V;if(Q!==void 0){let z={role:"user",content:Q,metadata:E0};W.appendControl("user",z);let B=await i0(Z,J,Q,H,E0);if(B)H=B}return H}import{createHash as R6}from"node:crypto";import{promises as i9}from"node:fs";import r9 from"node:path";import{nanoid as J$}from"nanoid";import*as t from"node:fs/promises";import*as Z$ from"node:path";import NJ from"write-file-atomic";var PJ={enabled:!0,maxIndexLines:200};var F9="memory",uZ="MEMORY.md",dZ="<!-- blade:auto-memory-topics:start -->",p1="<!-- blade:auto-memory-topics:end -->",O9={realpath:!1,retries:{retries:5,factor:1.2,minTimeout:20,maxTimeout:100,randomize:!0}},P9=new R$,_J;function bJ($){return $.trim().replace(/\s+/g," ")}function N9($){return bJ($.replace(/^- \[\d{4}-\d{2}-\d{2}\] /,""))}function _9($){return[dZ,"## Auto-consolidated topics",...$.map((Z)=>`- [${Z}](${Z}.md)`),p1].join(`
|
|
4
4
|
`)}function A9($,Z){let J=_9(Z),W=$.indexOf(dZ),Y=$.indexOf(p1,Math.max(0,W));if(W>=0&&Y>=W)return $.slice(0,W)+J+$.slice(Y+p1.length);if(!$)return`${J}
|
|
@@ -119,14 +119,14 @@ When facing complex multi-step tasks:
|
|
|
119
119
|
3. If a step fails, diagnose the root cause rather than repeating the same approach.
|
|
120
120
|
4. When uncertain about file paths or project structure, use Grep/Glob/Read to gather facts first.
|
|
121
121
|
5. Prefer the smallest change that achieves the goal — avoid unnecessary refactoring.`}`}var G$=T0("Agent"),N5=new Set(["Read","Glob","Grep","WebFetch","WebSearch","MemoryRead","ReadPromptArtifact","GetSpecContext","ValidateSpec","TaskOutput"]);class XZ{pipeline;execContext;registry;contextMgr;sessionId;lastMessageUuid;subagentInfo;progressSink;requireDurableToolUse;pending=new Map;completed=new Map;queued=[];order=[];dispatched=new Set;abortController=new AbortController;hasExclusiveBarrier=!1;epoch=0;activeAborts=new Map;executeTool;admitTool;rollbackAdmission;turnAdmission=new D1;toolUsePersistenceTail=Promise.resolve();constructor($,Z,J,W,Y,K,X,Q,H=!1){this.pipeline=$;this.execContext=Z;this.registry=J;this.contextMgr=W;this.sessionId=Y;this.lastMessageUuid=K;this.subagentInfo=X;this.progressSink=Q;this.requireDurableToolUse=H}setExecutionPolicy($){this.executeTool=$}setAdmissionPolicy($){this.admitTool=$}setAdmissionRollback($){this.rollbackAdmission=$}addTool($,Z){if(this.dispatched.has($.id))return G$.debug(`[StreamingToolExecutor] 跳过已分发工具: ${$.function.name} (${$.id})`),"rejected";this.dispatched.add($.id),this.order.push($.id);let J=this.turnAdmission.admit();if(J)return this.completed.set($.id,{toolCall:$,result:J,toolUseUuid:null}),"rejected";w1($.function.name,Z),$.function.arguments=JSON.stringify(Z);let W=this.admitTool?.($.function.name,Z);if(W)return this.completed.set($.id,{toolCall:$,result:W,toolUseUuid:null}),"rejected";let Y=this.registry.get($.function.name),K=Y?.isConcurrencySafe===!0,X=Y?.parallelism==="shared"||Y?.parallelism===void 0&&K;if(N5.has($.function.name)&&K&&!this.hasExclusiveBarrier){G$.debug(`[StreamingToolExecutor] 立即执行预启动工具: ${$.function.name}`);let H=this.executeOne($,Z);return this.pending.set($.id,H),"prelaunched"}else{if(G$.debug(`[StreamingToolExecutor] 排队非预启动工具: ${$.function.name}`),this.queued.push({toolCall:$,params:Z}),!X)this.hasExclusiveBarrier=!0;return"queued"}}getQueuedToolCalls(){return this.queued.map(($)=>$.toolCall)}async*getRemainingResults(){this.dispatchQueuedTools();for(let $ of this.order){if(this.completed.has($)){yield this.completed.get($),this.completed.delete($);continue}if(this.pending.has($)){let Z=await this.pending.get($);this.pending.delete($),yield Z;continue}}}getCompletedResults(){let $=Array.from(this.completed.values());return this.completed.clear(),$}discard(){for(let $ of this.queued)this.rollbackAdmission?.($.toolCall.function.name);this.epoch++,this.abortController.abort(),this.abortController=new AbortController;for(let[,$]of this.activeAborts)$.abort();this.activeAborts.clear(),this.queued=[],this.order=[],this.dispatched.clear(),this.completed.clear(),this.pending.clear(),this.hasExclusiveBarrier=!1,this.turnAdmission.reset(),this.toolUsePersistenceTail=Promise.resolve(),G$.debug(`[StreamingToolExecutor] 已丢弃所有挂起工作并重置状态 (epoch=${this.epoch})`)}hasTools(){return this.order.length>0}getEpoch(){return this.epoch}makeAbortResult($,Z,J=null){return{toolCall:$,result:{success:!1,llmContent:"",error:{type:"execution_error",message:Z},metadata:{abortedBeforeLaunch:!0}},toolUseUuid:J}}dispatchQueuedTools(){let $=this.queued;this.queued=[],this.hasExclusiveBarrier=!1;let Z=this.epoch;for(let{toolCall:J,params:W}of $){if(this.execContext.signal?.aborted){this.completed.set(J.id,this.makeAbortResult(J,"Tool execution skipped: task aborted before launch"));continue}let Y=this.executeQueued(J,W,Z);this.pending.set(J.id,Y)}}async executeQueued($,Z,J){if(J!==this.epoch)return this.makeAbortResult($,"Tool execution aborted due to epoch mismatch (discard)");if(this.execContext.signal?.aborted)return this.makeAbortResult($,"Tool execution skipped: task aborted before launch");return this.executeOne($,Z)}async executeOne($,Z){let J=this.epoch,W=new AbortController;this.activeAborts.set($.id,W);let Y=null,K=this.abortController.signal;try{if(K.aborted||W.signal.aborted)return this.makeAbortResult($,"Tool execution aborted due to discard");try{if(this.contextMgr&&this.sessionId)Y=await this.persistToolUseInOrder($,Z);else if(this.requireDurableToolUse&&this.sessionId)throw Error("Durable tool-use storage is unavailable")}catch(j){if(G$.warn("[StreamingToolExecutor] 保存工具调用失败:",j),!this.requireDurableToolUse)Y=null;else return{toolCall:$,result:{success:!1,llmContent:j$,error:{type:"execution_error",message:j$},metadata:{durableToolUseFailed:!0,summary:"Blocked tool before execution"}},toolUseUuid:null,error:j instanceof Error?j:Error(String(j))}}let X=[K,W.signal],Q=this.execContext.signal;if(Q)X.push(Q);let H=X8(...X),V={...this.execContext,messageId:Y??$.id,signal:H,confirmationHandler:this.execContext.sessionId&&this.execContext.workspaceRoot&&this.execContext.workspaceKind!=="acp-remote"?G0.createConfirmationHandler(this.execContext.confirmationHandler,{sessionId:this.execContext.sessionId,projectPath:this.execContext.workspaceRoot,toolCallId:Y??$.id,toolName:$.function.name}):this.execContext.confirmationHandler,onProgress:(j)=>{this.execContext.onProgress?.(j),this.progressSink?.($,{message:j.slice(0,1000)})},onProgressUpdate:(j)=>{this.execContext.onProgressUpdate?.(j),this.progressSink?.($,j)}},z=this.executeTool?await this.executeTool($.function.name,Z,V):await this.pipeline.execute($.function.name,Z,V);if(J!==this.epoch)return G$.debug(`[StreamingToolExecutor] 丢弃旧世代工具结果: ${$.function.name} (startEpoch=${J}, currentEpoch=${this.epoch})`),this.makeAbortResult($,"Tool execution aborted due to epoch mismatch (discard)",Y);let B={toolCall:$,result:z,toolUseUuid:Y};if(this.pending.has($.id))this.pending.delete($.id),this.completed.set($.id,B);return B}catch(X){if(J!==this.epoch)return this.makeAbortResult($,"Tool execution aborted due to epoch mismatch (discard)",Y);G$.error(`[StreamingToolExecutor] 工具执行失败: ${$.function.name}`,X);let Q={success:!1,llmContent:"",error:{type:"execution_error",message:X instanceof Error?X.message:"Unknown error"},metadata:void 0},H={toolCall:$,result:Q,toolUseUuid:Y,error:X instanceof Error?X:Error("Unknown error")};if(this.pending.has($.id))this.pending.delete($.id),this.completed.set($.id,H);return H}finally{this.activeAborts.delete($.id)}}persistToolUseInOrder($,Z){let J=this.contextMgr,W=this.sessionId;if(!J||!W)return Promise.resolve(null);let Y=this.toolUsePersistenceTail.then(()=>J.saveToolUse(W,$.function.name,Z,this.lastMessageUuid??null,this.subagentInfo,$.id));return this.toolUsePersistenceTail=Y.then(()=>{return},()=>{return}),Y}}class b6{pending=[];waiters=[];closed=!1;push($){if(this.closed)return;let Z=this.waiters.shift();if(Z){Z($);return}if(this.pending.length>=256)this.pending.shift();this.pending.push($)}shift(){return this.pending.shift()}next(){let $=this.shift();if($)return Promise.resolve($);if(this.closed)return Promise.resolve(void 0);return new Promise((Z)=>{this.waiters.push(Z)})}get hasPending(){return this.pending.length>0}close(){if(this.closed)return;this.closed=!0;for(let $ of this.waiters.splice(0))$(void 0)}}function Q8($,Z){if(!["TaskCreate","TaskUpdate","TaskList"].includes($.function.name)||!Z.success||!Z.llmContent&&!Z.metadata)return null;let J=typeof Z.llmContent==="object"?Z.llmContent:{};return{kind:"task_update",tasks:Z.metadata?.tasks||J.tasks||[]}}function H8($,Z,J){if($.function.name!=="Skill"||!Z.success||!Z.metadata)return;let W=Z.metadata;if(W.skillName)J.onSkillActivated?.({skillName:W.skillName,allowedTools:W.allowedTools,basePath:W.basePath||""})}function V8($){let Z=$.metadata;if(!Z)return;return Z.modelId?.toString().trim()||Z.model?.toString().trim()||void 0||void 0}function _5($,Z,J){if(!["EnterWorktree","ExitWorktree"].includes($.function.name)||!Z.success)return;let W=Z.metadata,Y=W?.workspaceRoot;if(!["enter","exit"].includes(String(W?.workspaceTransition))||typeof Y!=="string"||Y.trim()==="")return;return E$.getInstance().inheritProjectConfig(J.workspaceRoot,Y,J.sessionId),J.workspaceRoot=Y,J.worktreeActive=W?.workspaceTransition==="enter",Y}function A5($,Z){if($.function.name!=="Task")return null;let J=Z.metadata;if(!J?.subagentSessionId)return null;let W=J.subagentSessionId,Y=J.subagentType||"Task",K=J.subagentStatus,X=typeof J.subagentResumedFrom==="string"?J.subagentResumedFrom:void 0,Q=typeof J.subagentRootId==="string"?J.subagentRootId:void 0,H=typeof J.subagentResumeDepth==="number"?J.subagentResumeDepth:void 0;if(K==="completed"||K==="failed"||K==="cancelled")return{kind:"subagent_completed",sessionId:W,type:Y,success:K==="completed",summary:J.subagentSummary,...J.verificationVerdict==="pass"||J.verificationVerdict==="fail"||J.verificationVerdict==="partial"?{verificationVerdict:J.verificationVerdict}:{},...X?{resumedFrom:X}:{},...Q?{rootAgentId:Q}:{},...H!==void 0?{resumeDepth:H}:{}};if(K==="running"){let V="";try{V=JSON.parse($.function.arguments).prompt||""}catch{}return{kind:"subagent_spawned",sessionId:W,type:Y,prompt:V,resumedFrom:X,rootAgentId:Q,resumeDepth:H}}return null}async function y6($,Z,J,W){let Y=Q8($,Z),K=A5($,Z);H8($,Z,J);let X=V8(Z);if(X)await J.onModelSwitch?.(X);if(W)_5($,Z,W);return K||Y}var i=T0("Agent");function QZ($,Z){return{inputTokens:$.promptTokens??0,outputTokens:$.completionTokens??0,totalTokens:sZ($)??0,maxContextTokens:Z,cacheReadTokens:$.cacheReadInputTokens??0,cacheWriteTokens:$.cacheCreationInputTokens??0,...$.promptCacheBreak?{cacheBreak:$.promptCacheBreak}:{},costUsd:$.costUsd}}function K$($){return JSON.stringify($).replaceAll("<","\\u003c").replaceAll(">","\\u003e")}function z8($){let Z=$.trim();if(Z=Z.replace(/,\s*([}\]])/g,"$1"),Z.startsWith("{")&&!Z.endsWith("}"))Z+="}";Z=Z.replace(/,\s*([}\]])/g,"$1");try{let J=JSON.parse(Z);if(typeof J==="object"&&J!==null&&!Array.isArray(J))return J;return null}catch{return null}}function U1($){let Z=z8($);if(Z)return Z;try{let J=JSON.parse($);return typeof J==="string"?z8(J):null}catch{return null}}function b5($){let Z=$.metadata&&typeof $.metadata==="object"&&!Array.isArray($.metadata)?$.metadata:void 0;if(Z?.contextualProjectRules!==!0)return[];if(!Array.isArray(Z.ruleReferences))throw Error("Invalid contextual project rule provenance");return Z.ruleReferences.map((J)=>{if(!J||typeof J!=="object"||Array.isArray(J))throw Error("Invalid contextual project rule reference");let W=J;if(typeof W.id!=="string"||typeof W.relativePath!=="string"||!["project","local"].includes(String(W.source))||typeof W.contentSha256!=="string"||!/^[a-f0-9]{64}$/u.test(W.contentSha256))throw Error("Invalid contextual project rule reference");return{id:W.id,relativePath:W.relativePath,source:W.source,contentSha256:W.contentSha256}})}function u$($){if(typeof $==="string")return $;try{return JSON.parse(JSON.stringify($))}catch{return String($)}}function y5($){let Z=new Set,J=!1;for(let W of $){if(W.role==="assistant"){if(W.tool_calls&&W.tool_calls.length>0){for(let K of W.tool_calls)if("function"in K&&K.function.name==="Task")Z.add(K.id)}else if(J)J=!1;continue}if(W.role!=="tool"||W.name!=="Task"||!W.tool_call_id||!Z.has(W.tool_call_id)||typeof W.metadata!=="object"||W.metadata===null||Array.isArray(W.metadata))continue;let Y=W.metadata;if(Y.toolCallId===W.tool_call_id&&Y.toolName==="Task"&&Y.error===null)J=!0}return J}function f5($){if(!($ instanceof Error))return"未知错误";let W=$.lastError??$;if(W.responseBody)try{let Q=JSON.parse(W.responseBody)?.error?.message;if(Q){let H=W.statusCode?` (HTTP ${W.statusCode})`:"";return`${Q}${H}`}}catch{}let Y=$.message,K=Y.match(/Last error:\s*(.+)$/);if(K)return K[1];return Y}function E5($){if(!($ instanceof Error))return!1;return["stream not supported","streaming is not available","sse not supported","does not support streaming"].some((J)=>$.message.toLowerCase().includes(J.toLowerCase()))}function S5($,Z){if(!Z)return"Tool execution failed (no details).";let J=[`Error: ${Z.message||"Unknown error"}`];if(Z.type==="validation_error")J.push("Hint: Check the tool parameters — a required field may be missing or have the wrong type.");else if(Z.type==="permission_denied")J.push("Hint: This operation requires user approval. Try a different approach or ask the user.");else if(Z.type==="timeout_error")J.push("Hint: The operation timed out. Consider breaking it into smaller steps or increasing timeout.");else if(Z.type==="execution_error"){let W=Z.message??"";if(W.includes("ENOENT")||W.includes("no such file"))J.push("Hint: File or directory not found. Use Glob or Grep to find the correct path first.");else if(W.includes("EACCES")||W.includes("permission"))J.push("Hint: Permission denied. The file may be read-only or owned by another user.");else if(W.includes("not found in file")||W.includes("old_string"))J.push(`Hint: The target text was not found. Use Read to view the current file content, then retry ${$} with the exact text.`);else if(W.includes("ENOTDIR"))J.push("Hint: A path component is not a directory. Verify the full path with Glob.")}return J.join(`
|
|
122
|
-
`)}function f6($){if(!($ instanceof Error))return!1;return d1($)||$.status===413}function T5($,Z){let J=Z,W=J.index??0;if(!$.has(W))$.set(W,{id:J.id||"",name:J.function?.name||"",arguments:""});let Y=$.get(W);if(J.id&&!Y.id)Y.id=J.id;if(J.function?.name&&!Y.name)Y.name=J.function.name;if(J.function?.arguments)Y.arguments+=J.function.arguments}function R5($){if($.size===0)return;return Array.from($.values()).filter((Z)=>Z.id&&Z.name).map((Z)=>({id:Z.id,type:"function",function:{name:Z.name,arguments:Z.arguments}}))}async function*M5($,Z,J,W,Y,K){let X="",Q="",H,V,z=new Map;try{let B=$.chatService.streamChat(Z,J,W,Y),j=0;for await(let w of B){if(W?.aborted)break;if(w.providerAdmission){yield{kind:"provider_admission",...w.providerAdmission};continue}if(w.providerCircuit){yield{kind:"provider_circuit",...w.providerCircuit};continue}if(w.providerRetry){yield{kind:"provider_retry",...w.providerRetry};continue}if(w.providerStall){yield{kind:"provider_stall",...w.providerStall};continue}if(j++,w.modelFallback){K?.discard(),X="",Q="",H=void 0,V=void 0,z.clear(),j=0,yield{kind:"model_fallback",...w.modelFallback};continue}if(w.content)X+=w.content,yield{kind:"content_delta",delta:w.content};if(w.reasoningContent)Q+=w.reasoningContent,yield{kind:"thinking_delta",delta:w.reasoningContent};if(w.usage)H=w.usage;if(w.toolCalls){for(let L of w.toolCalls)if(T5(z,L),K){let E=L.index??0,S=z.get(E);if(S&&S.id&&S.name)try{let T=U1(S.arguments);if(T===null)continue;let p={id:S.id,type:"function",function:{name:S.name,arguments:S.arguments}},$0=$.toolExecutor.getRegistry().get(S.name)?.kind,a=K.addTool(p,T);if(S.arguments=p.function.arguments,a==="prelaunched")yield{kind:"tool_start",toolCall:p,toolKind:$0}}catch{}}}if(w.finishReason){V=w.finishReason;break}}if(j===0&&!W?.aborted&&X.length===0&&z.size===0)return i.warn("[Loop] 流式响应返回0个chunk,回退到非流式模式"),K?.discard(),{...await $.chatService.chat(Z,J,W,Y),_nonStreamingFallback:!0};return{content:X,reasoningContent:Q||void 0,toolCalls:R5(z),usage:H,finishReason:V}}catch(B){if(E5(B))return i.warn("[Loop] 流式请求失败,降级到非流式模式"),K?.discard(),{...await $.chatService.chat(Z,J,W,Y),_nonStreamingFallback:!0};throw B}}async function M6($,Z,J){if(!$)return;if(!J)return{outcome:"disabled",entries:0,topics:[]};try{return await SJ($,{workspaceRoot:Z.workspaceRoot||j0(),workspaceAccess:Z.workspaceKind==="acp-remote"?"none":"full"})}catch{return{outcome:"failed",entries:0,topics:[]}}}function k5($){return R6("sha256").update($).digest("hex").slice(0,16)}var x5=new Set(["AbortError","Error","RangeError","TypeError"]),I5=new Set(["EACCES","EEXIST","EIO","EMFILE","ENFILE","ENOENT","ENOSPC","EPERM","EROFS"]);function h5($){if($ instanceof Error){let Z=$,J=x5.has($.name)?$.name:"Error",W=typeof Z.code==="string"&&I5.has(Z.code)?Z.code:"unknown";return`${J}:${W}`}return"UnknownError:unknown"}async function v5($){let{deps:Z,context:J,state:W,snapshot:Y,attemptSpent:K}=$;if(Y.phase!=="handoff_band")return{kind:"failed"};if(W.getHistory().find((H)=>typeof H.id==="string"&&F8(H)))return{kind:"already_present"};if(K)return{kind:"failed"};let Q=Z.executionEngine?.getContextManager();if(!Q)return{kind:"failed"};try{let H=await Q.recordTokenBudgetHandoff(J.sessionId,{version:1,observedPromptTokens:Y.contextTokens??0,availableForInput:Y.availableForInput??0,handoffThreshold:Y.handoffThreshold??0,compactionThreshold:Y.compactionThreshold??0});if(H.outcome==="suppressed")return{kind:"suppressed"};let V=L8(H.event);if(!V)return{kind:"failed"};return W.appendDurableControl(V),{kind:"appended",message:V}}catch(H){let V=`token_budget_handoff_persist_failed session=${k5(J.sessionId)} error=${h5(H)}`;return i.warn(V),{kind:"failed"}}}async function*O8($,Z,J,W,Y,K,X,Q){let H=W.contextTokens,V=sJ(Z.messages,K),z=V!==null;if(V)Z.messages=V.messages,i.debug(`[Loop] [轮次 ${J}] MicroCompact: 清理 ${V.snippedCount} 轮旧工具结果(缓存已过期)`);let B=H1(Z.messages),j=!1;if(B.snippedCount>0)j=!0,i.debug(`[Loop] [轮次 ${J}] Snip 压缩: 移除 ${B.snippedCount} 轮旧工具调用,释放约 ${B.estimatedTokensFreed} tokens`);if(W.phase==="unknown"){if(j)Z.messages=B.messages;return i.debug(`[Loop] [轮次 ${J}] 压缩检查: 跳过(无历史 usage 数据)`),z||j?{kind:"snipped"}:{kind:"none"}}let w=$.chatService.getConfig(),L=w.model,A=W.maxContextTokens??0,E=W.maxOutputTokens??0,S=W.availableForInput??0;if(A<=0||S<=0){if(j)Z.messages=B.messages;return i.debug(`[Loop] [轮次 ${J}] 压缩检查: 跳过(模型上下文窗口未知)`),z||j?{kind:"snipped"}:{kind:"none"}}if(i.debug(`[Loop] [轮次 ${J}] 压缩检查:`,{contextTokens:H,tokenSource:W.tokenSource,estimatedPendingTokens:W.estimatedPendingTokens,maxContextTokens:A,maxOutputTokens:E,availableForInput:S,threshold:W.compactionThreshold,shouldCompact:W.phase==="compaction_due"}),W.phase!=="compaction_due"){if(j)Z.messages=B.messages;return z||j?{kind:"snipped"}:{kind:"none"}}i.debug(J===0?"[Loop] 触发自动压缩":`[Loop] [轮次 ${J}] 触发循环内自动压缩`);let T="failed",p,k,$0,a,R,G,r,L0,v,D0,g,A0,Z0,F0="compaction";yield{kind:"compaction",phase:"start",reason:"threshold"};try{let
|
|
122
|
+
`)}function f6($){if(!($ instanceof Error))return!1;return d1($)||$.status===413}function T5($,Z){let J=Z,W=J.index??0;if(!$.has(W))$.set(W,{id:J.id||"",name:J.function?.name||"",arguments:""});let Y=$.get(W);if(J.id&&!Y.id)Y.id=J.id;if(J.function?.name&&!Y.name)Y.name=J.function.name;if(J.function?.arguments)Y.arguments+=J.function.arguments}function R5($){if($.size===0)return;return Array.from($.values()).filter((Z)=>Z.id&&Z.name).map((Z)=>({id:Z.id,type:"function",function:{name:Z.name,arguments:Z.arguments}}))}async function*M5($,Z,J,W,Y,K){let X="",Q="",H,V,z=new Map;try{let B=$.chatService.streamChat(Z,J,W,Y),j=0;for await(let w of B){if(W?.aborted)break;if(w.providerAdmission){yield{kind:"provider_admission",...w.providerAdmission};continue}if(w.providerCircuit){yield{kind:"provider_circuit",...w.providerCircuit};continue}if(w.providerRetry){yield{kind:"provider_retry",...w.providerRetry};continue}if(w.providerStall){yield{kind:"provider_stall",...w.providerStall};continue}if(j++,w.modelFallback){K?.discard(),X="",Q="",H=void 0,V=void 0,z.clear(),j=0,yield{kind:"model_fallback",...w.modelFallback};continue}if(w.content)X+=w.content,yield{kind:"content_delta",delta:w.content};if(w.reasoningContent)Q+=w.reasoningContent,yield{kind:"thinking_delta",delta:w.reasoningContent};if(w.usage)H=w.usage;if(w.toolCalls){for(let L of w.toolCalls)if(T5(z,L),K){let E=L.index??0,S=z.get(E);if(S&&S.id&&S.name)try{let T=U1(S.arguments);if(T===null)continue;let p={id:S.id,type:"function",function:{name:S.name,arguments:S.arguments}},$0=$.toolExecutor.getRegistry().get(S.name)?.kind,a=K.addTool(p,T);if(S.arguments=p.function.arguments,a==="prelaunched")yield{kind:"tool_start",toolCall:p,toolKind:$0}}catch{}}}if(w.finishReason){V=w.finishReason;break}}if(j===0&&!W?.aborted&&X.length===0&&z.size===0)return i.warn("[Loop] 流式响应返回0个chunk,回退到非流式模式"),K?.discard(),{...await $.chatService.chat(Z,J,W,Y),_nonStreamingFallback:!0};return{content:X,reasoningContent:Q||void 0,toolCalls:R5(z),usage:H,finishReason:V}}catch(B){if(E5(B))return i.warn("[Loop] 流式请求失败,降级到非流式模式"),K?.discard(),{...await $.chatService.chat(Z,J,W,Y),_nonStreamingFallback:!0};throw B}}async function M6($,Z,J){if(!$)return;if(!J)return{outcome:"disabled",entries:0,topics:[]};try{return await SJ($,{workspaceRoot:Z.workspaceRoot||j0(),workspaceAccess:Z.workspaceKind==="acp-remote"?"none":"full"})}catch{return{outcome:"failed",entries:0,topics:[]}}}function k5($){return R6("sha256").update($).digest("hex").slice(0,16)}var x5=new Set(["AbortError","Error","RangeError","TypeError"]),I5=new Set(["EACCES","EEXIST","EIO","EMFILE","ENFILE","ENOENT","ENOSPC","EPERM","EROFS"]);function h5($){if($ instanceof Error){let Z=$,J=x5.has($.name)?$.name:"Error",W=typeof Z.code==="string"&&I5.has(Z.code)?Z.code:"unknown";return`${J}:${W}`}return"UnknownError:unknown"}async function v5($){let{deps:Z,context:J,state:W,snapshot:Y,attemptSpent:K}=$;if(Y.phase!=="handoff_band")return{kind:"failed"};if(W.getHistory().find((H)=>typeof H.id==="string"&&F8(H)))return{kind:"already_present"};if(K)return{kind:"failed"};let Q=Z.executionEngine?.getContextManager();if(!Q)return{kind:"failed"};try{let H=await Q.recordTokenBudgetHandoff(J.sessionId,{version:1,observedPromptTokens:Y.contextTokens??0,availableForInput:Y.availableForInput??0,handoffThreshold:Y.handoffThreshold??0,compactionThreshold:Y.compactionThreshold??0});if(H.outcome==="suppressed")return{kind:"suppressed"};let V=L8(H.event);if(!V)return{kind:"failed"};return W.appendDurableControl(V),{kind:"appended",message:V}}catch(H){let V=`token_budget_handoff_persist_failed session=${k5(J.sessionId)} error=${h5(H)}`;return i.warn(V),{kind:"failed"}}}async function*O8($,Z,J,W,Y,K,X,Q){let H=W.contextTokens,V=sJ(Z.messages,K),z=V!==null;if(V)Z.messages=V.messages,i.debug(`[Loop] [轮次 ${J}] MicroCompact: 清理 ${V.snippedCount} 轮旧工具结果(缓存已过期)`);let B=H1(Z.messages),j=!1;if(B.snippedCount>0)j=!0,i.debug(`[Loop] [轮次 ${J}] Snip 压缩: 移除 ${B.snippedCount} 轮旧工具调用,释放约 ${B.estimatedTokensFreed} tokens`);if(W.phase==="unknown"){if(j)Z.messages=B.messages;return i.debug(`[Loop] [轮次 ${J}] 压缩检查: 跳过(无历史 usage 数据)`),z||j?{kind:"snipped"}:{kind:"none"}}let w=$.chatService.getConfig(),L=w.model,A=W.maxContextTokens??0,E=W.maxOutputTokens??0,S=W.availableForInput??0;if(A<=0||S<=0){if(j)Z.messages=B.messages;return i.debug(`[Loop] [轮次 ${J}] 压缩检查: 跳过(模型上下文窗口未知)`),z||j?{kind:"snipped"}:{kind:"none"}}if(i.debug(`[Loop] [轮次 ${J}] 压缩检查:`,{contextTokens:H,tokenSource:W.tokenSource,estimatedPendingTokens:W.estimatedPendingTokens,maxContextTokens:A,maxOutputTokens:E,availableForInput:S,threshold:W.compactionThreshold,shouldCompact:W.phase==="compaction_due"}),W.phase!=="compaction_due"){if(j)Z.messages=B.messages;return z||j?{kind:"snipped"}:{kind:"none"}}i.debug(J===0?"[Loop] 触发自动压缩":`[Loop] [轮次 ${J}] 触发循环内自动压缩`);let T="failed",p,k,$0,a,R,G,r,L0,v,D0,g,A0,Z0,F0="compaction";yield{kind:"compaction",phase:"start",reason:"threshold"};try{let u=j?B.messages:Z.messages,M=await k$.compact(u,{trigger:"auto",modelName:L,modelProvider:w.provider,maxContextTokens:A,apiKey:w.apiKey,baseURL:w.baseUrl,actualPreTokens:H,signal:Y,activeTask:X,workspaceRoot:Z.workspaceRoot||j0(),workspaceAccess:Z.workspaceKind==="acp-remote"?"none":"full",sessionId:Z.sessionId});if(M.usage)yield{kind:"token_usage",usage:QZ(M.usage,A)};if(p=M.success?"llm":"fallback",k=M.preTokens,$0=M.postTokens,a=M.sampleAttempts,R=M.inputReductions,G=M.messagesOmitted,r=M.filesOmitted,L0=M.imagesOmitted,v=M.fallbackTargetTokens,D0=M.fallbackMessagesOmitted,g=M.fallbackMessagesTruncated,A0=M.failureReason,M.success)i.debug(`[Loop] [轮次 ${J}] 压缩完成: ${M.preTokens} -> ${M.postTokens} tokens`);else i.warn(`[Loop] [轮次 ${J}] 压缩使用降级策略: ${M.preTokens} -> ${M.postTokens} tokens`);F0="checkpoint";let q1=await Y1($,Z,M.summary,{trigger:"auto",reason:"threshold",strategy:p,preTokens:M.preTokens,...W.tokenSource?{preTokenSource:W.tokenSource}:{},...W.estimatedPendingTokens!==void 0?{estimatedPendingTokens:W.estimatedPendingTokens}:{},postTokens:M.postTokens,sampleAttempts:M.sampleAttempts,inputReductions:M.inputReductions,messagesOmitted:M.messagesOmitted,filesOmitted:M.filesOmitted,imagesOmitted:M.imagesOmitted,fallbackTargetTokens:M.fallbackTargetTokens,fallbackMessagesOmitted:M.fallbackMessagesOmitted,fallbackMessagesTruncated:M.fallbackMessagesTruncated,failureReason:M.failureReason,filesIncluded:M.filesIncluded,replacementMessages:M.compactedMessages},{required:$.executionEngine!==void 0});if(Z0=await M6(M.memoryPlan,Z,q1),Z.messages=M.compactedMessages,Q)Q.lastCompactionTurn=J;return T=M.success?"completed":"fallback",{kind:"compacted",postTokens:M.postTokens}}catch(u){if(r0(u))return i.debug(`[Loop] [轮次 ${J}] 压缩被中止`),{kind:"none"};return i.error(`[Loop] [轮次 ${J}] 压缩失败,停止执行`,u),{kind:"failed",phase:F0}}finally{yield{kind:"compaction",phase:"end",reason:"threshold",outcome:T,strategy:p,preTokens:k,...W.tokenSource?{preTokenSource:W.tokenSource}:{},...W.estimatedPendingTokens!==void 0?{estimatedPendingTokens:W.estimatedPendingTokens}:{},postTokens:$0,sampleAttempts:a,inputReductions:R,messagesOmitted:G,filesOmitted:r,imagesOmitted:L0,fallbackTargetTokens:v,fallbackMessagesOmitted:D0,fallbackMessagesTruncated:g,failureReason:A0,memory:Z0}}}function C5($,Z,J,W){let Y=W?B8(W):"user-cancel";return{success:!1,error:{type:"aborted",message:(Y==="interrupt"?void 0:"任务已被用户中止")??"任务已中断"},metadata:{turnsCount:$,toolCallsCount:Z,duration:Date.now()-J,abortReason:Y}}}function j8($,Z,J){return{success:!1,error:{type:"tool_persistence_failed",message:LJ},metadata:{turnsCount:$,toolCallsCount:Z,duration:Date.now()-J}}}function g5($,Z,J,W){return{success:!1,error:{type:"context_compaction_failed",message:"Context compaction could not cross the hard budget boundary.",details:{phase:W}},metadata:{turnsCount:$,toolCallsCount:Z,duration:Date.now()-J}}}async function*p5($,Z,J,W,Y){let K=Date.now(),X=0,Q=[],H=null,V=!1,z=(B,j,w)=>{return V=!0,C5(B,j,K,w)};try{let B=$.toolExecutor.getRegistry(),j=J.permissionMode,w=W?.outputSchema?n1(W.outputSchema):void 0,L=()=>{let F=$.applySkillToolRestrictions(B.getFunctionDeclarationsByMode(j));if(!w)return F;return[...F.filter((O)=>O.name!==u0),w.declaration]},A=g2(),E=W2(),S=()=>{let F=K2(E);return F?{executionHostFailureCategory:F}:{}},T=l2(),p=h2(),k=K8(Y,B);if(w)k=`${k??""}
|
|
123
123
|
|
|
124
124
|
# Structured Final Output
|
|
125
125
|
This turn has a required JSON Schema final-output contract. Complete the user's
|
|
126
126
|
work normally, including all required tool use and verification. Then call the
|
|
127
127
|
reserved ${u0} tool exactly once with the final object.
|
|
128
128
|
Do not substitute JSON prose or a fenced code block for the tool call. The host
|
|
129
|
-
validates the object and may return a bounded corrective error.`;let $0=J.messages.length===0,a=new Set($.staticProjectRules?.references.map((F)=>F.id)??[]);for(let F of J.messages){let O=b5(F);if(O.length===0)continue;if(!$.hydrateProjectRules)throw Error("Contextual project rule catalog is unavailable");let K0=$.hydrateProjectRules(O);F.content=K0.content;for(let z0 of O)a.add(z0.id)}let R=[...J.messages],G=new I1(J,k),r=async(F)=>{let O=W?.turnFinalization;if(!O)return;return{turnId:O.turnId,inputMessageIds:await O.getInputMessageIds(),turnsCount:X,toolCallsCount:Q.length,durationMs:Math.max(0,Date.now()-K),...F?{goalFinalization:F}:{}}};if($0&&$.staticProjectRules&&$.staticProjectRules.files.length>0)yield{kind:"project_rules_loaded",files:$.staticProjectRules.files.map((F)=>({id:F.id,relativePath:F.relativePath,source:F.source,conditional:F.conditional,contentSha256:F.contentSha256})),triggerPaths:[],blockedWrite:!1};let L0=W?.pendingInputOnly===!0;if(!L0){let F=W?.inputMessageId?{...W.inputPersistenceMetadata,inboxMessageId:W.inputMessageId}:void 0,O=(F?JSON.parse(JSON.stringify(F)):void 0)??(W?.transientInput==="goal_continuation"?{transientGoalContinuation:!0}:void 0);if(G.appendUser({role:"user",content:Z,metadata:O}),W?.transientInput!=="goal_continuation")H=await i0($,J,Z,null,F);if(W?.inputMessageId&&!H)throw Error(`Failed to persist durable input before applying it: ${W.inputMessageId}`)}let v=!!J.subagentInfo,D0=D8(J.subagentInfo?.subagentType),g=W?.builtinVerification!==!1,A0=$.runtimeOptions.maxTurns??W?.maxTurns??$.config.maxTurns??-1,Z0=A0>=0;if(A0===0)return{success:!1,error:{type:"chat_disabled",message:"对话功能已被禁用 (maxTurns=0)"},metadata:{turnsCount:0,toolCallsCount:0,duration:0}};let F0=A0===-1?1/0:A0,
|
|
129
|
+
validates the object and may return a bounded corrective error.`;let $0=J.messages.length===0,a=new Set($.staticProjectRules?.references.map((F)=>F.id)??[]);for(let F of J.messages){let O=b5(F);if(O.length===0)continue;if(!$.hydrateProjectRules)throw Error("Contextual project rule catalog is unavailable");let K0=$.hydrateProjectRules(O);F.content=K0.content;for(let z0 of O)a.add(z0.id)}let R=[...J.messages],G=new I1(J,k),r=async(F)=>{let O=W?.turnFinalization;if(!O)return;return{turnId:O.turnId,inputMessageIds:await O.getInputMessageIds(),turnsCount:X,toolCallsCount:Q.length,durationMs:Math.max(0,Date.now()-K),...F?{goalFinalization:F}:{}}};if($0&&$.staticProjectRules&&$.staticProjectRules.files.length>0)yield{kind:"project_rules_loaded",files:$.staticProjectRules.files.map((F)=>({id:F.id,relativePath:F.relativePath,source:F.source,conditional:F.conditional,contentSha256:F.contentSha256})),triggerPaths:[],blockedWrite:!1};let L0=W?.pendingInputOnly===!0;if(!L0){let F=W?.inputMessageId?{...W.inputPersistenceMetadata,inboxMessageId:W.inputMessageId}:void 0,O=(F?JSON.parse(JSON.stringify(F)):void 0)??(W?.transientInput==="goal_continuation"?{transientGoalContinuation:!0}:void 0);if(G.appendUser({role:"user",content:Z,metadata:O}),W?.transientInput!=="goal_continuation")H=await i0($,J,Z,null,F);if(W?.inputMessageId&&!H)throw Error(`Failed to persist durable input before applying it: ${W.inputMessageId}`)}let v=!!J.subagentInfo,D0=D8(J.subagentInfo?.subagentType),g=W?.builtinVerification!==!1,A0=$.runtimeOptions.maxTurns??W?.maxTurns??$.config.maxTurns??-1,Z0=A0>=0;if(A0===0)return{success:!1,error:{type:"chat_disabled",message:"对话功能已被禁用 (maxTurns=0)"},metadata:{turnsCount:0,toolCallsCount:0,duration:0}};let F0=A0===-1?1/0:A0,u=0,M,q1=!1,o0=0,HZ=0,k6=0,VZ=!1,x6=!1,I6=!1,zZ=0,jZ=0,h0,L$,BZ=0,G1=0,m$=!1,DZ=!1,L1=0,m0=!1,d$=!1,F1=!1,c$=-1,_0,M0=W?.goalLifecycle?.snapshot?.status==="verifying",O1=W?.goalLifecycle?.snapshot?.completionVerification?.attempt,wZ=W?.goalLifecycle?.snapshot?.completionVerification?.requestedAt,l$=W?.goalLifecycle?.snapshot?.goalId,P1=W?.goalLifecycle?.snapshot?.objective??"",k0,F$,N1,i$=W?.goalLifecycle?.snapshot?.verificationStall?.consecutiveCount,v0,d0,c0=0,r$=w?T6(G.getHistory(),w):void 0,Q0=r$?.output,a0=r$?.completed===!0,h6=!1,v6=()=>{if(!Q0||!w)return;let F=Q0,O=w.schemaDigest;return{finalMessage:JSON.stringify(F),persistenceMetadata:{structuredOutput:{output:F,schemaDigest:O},structuredOutputSchemaDigest:O},resultMetadata:{structuredOutput:F,structuredOutputSchemaDigest:O},event:{kind:"structured_output",output:F,schemaDigest:O}}},C6=async(F)=>{if(Q0!==void 0||F.content?.trim()||(F.toolCalls?.length??0)>0)return{action:"none"};let O=Q.some((J0)=>J0.success);if(!x6){let J0=await W?.getRecoveredEmptyFinalState?.();I6=J0?.hadSuccessfulToolResult===!0,VZ||=J0?.correctionSpent===!0,x6=!0}if(!O&&!I6){if(F.finishReason==="length")return{action:"none"};return{action:"fail",result:{success:!1,error:{type:"intent_fulfillment_failed",message:"The model returned an empty final response."},metadata:{turnsCount:X,toolCallsCount:Q.length,duration:Date.now()-K,tokensUsed:u}}}}if(VZ)return{action:"fail",result:{success:!1,error:{type:"intent_fulfillment_failed",message:"The model returned an empty final response after successful tool execution."},metadata:{turnsCount:X,toolCallsCount:Q.length,duration:Date.now()-K,tokensUsed:u}}};VZ=!0;let K0={...E0,emptyFinalCorrection:!0},z0={role:"user",content:"The previous response was empty after successful tool execution. Return a non-empty final response that directly completes the user's request. Do not call tools unless unfinished work requires another tool action.",metadata:K0};G.appendControl("user",z0);let x0=await i0($,J,z0.content,H,K0);if(x0)H=x0;return{action:"continue"}},_1=W8(J.messages),O$=_1.mutationRevision,n$=_1.verificationRevision,s0=_1.verificationVerdict;if(M0)n$=-1,s0=void 0;let o$=_1.modifiedFiles,UZ=new Set,w0=new Set(J.worktreeActive?["EnterWorktree","TaskWorktree"]:[]),qZ=W?.policyUserMessage??Z,g6=typeof qZ==="string"?qZ:qZ.filter((F)=>F.type==="text").map((F)=>F.text).join(`
|
|
130
130
|
`),b0=g6,GZ=[b0,J.completionRequirements?.trim()].filter(Boolean).join(`
|
|
131
131
|
`),LZ=b0.trim()?[b0]:[],P$=[$.runtimeOptions.appendSystemPrompt?.trim(),J.completionRequirements?.trim(),...LZ].filter((F)=>Boolean(F)),A1=v1(b0),FZ=!L0,N$=y5(J.messages);if(N$)w0.add("Task");let OZ=()=>Z1(P$),P8=()=>{let F="The exactly-once Task delegation has already been started. Do not call Task again; return the final answer after its result.";return{success:!1,llmContent:F,error:{type:"validation_error",message:F},metadata:{summary:"Blocked duplicate exactly-once Task delegation"}}},a$=async(F)=>{if(!M0||!W?.goalLifecycle)return;n$=-1,s0=void 0,c$=-1,_0=void 0,k0=void 0,F$=void 0,v0=void 0,d0=void 0,await W.goalLifecycle.invalidateVerification(F)},p6=(F,O)=>{if(F===u0){if(!w)return{success:!1,llmContent:"No structured output contract is active for this turn.",error:{type:"validation_error",message:"Structured output contract is unavailable"},metadata:{summary:"Rejected unavailable structured output"}};if(Q0)return{success:!1,llmContent:"Structured output was already accepted. Do not submit it more than once.",error:{type:"validation_error",message:"Duplicate structured output submission"},metadata:{summary:"Rejected duplicate structured output"}};return}if(g&&m$||m0){if(F!=="Task")return{success:!1,llmContent:m0?"Goal completion verification requires the Task tool.":"Independent verification requires the Task tool.",error:{type:"validation_error",message:m0?"Goal completion verification requires the Task tool":"Independent verification requires the Task tool"},metadata:{summary:m0?"Blocked non-goal-verification tool":"Blocked non-verification tool"}}}if(m0&&F==="Task"){d$=!0,m0=!1;return}let K0=F==="Task"&&O.subagent_type===n0,z0=F==="Task"&&O.subagent_type===Y$;if(z0&&!g)return{success:!1,llmContent:"The built-in independent verification agent is disabled for this run. Use the project verification commands directly and finish.",error:{type:"validation_error",message:"Built-in independent verification is disabled"},metadata:{summary:"Rejected disabled verification agent"}};if(K0&&!M0)return{success:!1,llmContent:"The reserved goal verifier is available only for a host-owned completion candidate.",error:{type:"validation_error",message:"Goal completion verification is not active"},metadata:{summary:"Rejected unavailable goal verifier"}};let x0=g&&z0&&A6(o$);if(m$||K0||x0){let J0=K0?n0:Y$;if(O.subagent_type!==J0||O.run_in_background===!0||O.isolation!==void 0&&O.isolation!=="none"||O.resume!==void 0||O.resume_from!==void 0)return{success:!1,llmContent:`Verification requires a fresh synchronous Task with subagent_type="${J0}", run_in_background=false, and isolation="none".`,error:{type:"validation_error",message:"Invalid independent verification Task parameters"},metadata:{summary:"Blocked invalid verification Task"}};if(J0===n0)d$=!0;else DZ=!0;m$=!1}if(F!=="Task"||O.subagent_type===Y$||O.subagent_type===n0||!OZ())return;if(N$)return P8();N$=!0;return},N8=(F)=>{if(F==="Task"&&OZ())N$=!1},u6=(F,O,K0)=>$.resolveContextualProjectRules?.(F,O,K0,a),m6=async(F,O,K0)=>{if(F===u0&&w){let d=w.validate(O);if(!d.success){c0++;let s=Math.max(0,S6-c0+1),y1=`Structured output validation failed: ${d.message}. `+(s>0?`Correct the object and call ${u0} again (${s} corrective attempt${s===1?"":"s"} remaining).`:"The corrective retry budget is exhausted.");return{success:!1,llmContent:y1,error:{type:"validation_error",message:y1},metadata:{summary:"Structured output validation failed",structuredOutputRetryExhausted:s===0}}}return Q0=d.output,a0=!1,{success:!0,llmContent:"Structured output accepted. Return no additional prose; finish the turn.",metadata:{summary:"Structured output accepted",structuredOutputAccepted:!0,structuredOutputSchemaDigest:w.schemaDigest,structuredOutput:{output:d.output,schemaDigest:w.schemaDigest}}}}let z0=B.get(F)?.kind,x0=F==="Task"&&(O.subagent_type===Y$||O.subagent_type===n0);if(M0&&!x0&&(z0==="write"||z0==="execute"))await a$(`Goal completion evidence invalidated before ${F}`);if(F==="Task"&&d$){let d=[...o$].filter((s)=>s!=="<bash-mutation>").slice(0,50);O.subagent_type=n0,O.description="Verify goal completion",O.prompt=s2(P1,d),O.run_in_background=!1,O.isolation="none",delete O.resume,delete O.resume_from,d$=!1,F1=!0}else if(F==="Task"&&DZ&&O.subagent_type===Y$){let d=[...o$].filter((s)=>s!=="<bash-mutation>").slice(0,50);O.prompt=["Independently verify the current implementation against the original request.",`Original request:
|
|
132
132
|
${g6}`,`Changed files:
|
|
@@ -136,9 +136,9 @@ ${d.map((s)=>`- ${s}`).join(`
|
|
|
136
136
|
`),DZ=!1}let J0=u6(F,O);if(J0&&J0.files.length>0&&B.get(F)?.kind==="write"){let d="Applicable project instructions were loaded before this write. Review the newly supplied rules, then retry the write.";return{success:!1,llmContent:d,error:{type:"validation_error",message:d},metadata:{contextualProjectRulesRequired:!0,projectRuleReferences:J0.references,summary:"Blocked write until contextual project rules are applied"}}}return $.toolExecutor.execute(F,O,K0)},PZ=t6({budget:$.currentModelMaxContextTokens,isSubagent:v}),NZ=new $6,_$=new eZ,_8={},t0=W?.turnSteering,b1=async(F)=>{for(let O of F){let K0={...O.metadata,inboxMessageId:O.id},z0=JSON.parse(JSON.stringify(K0));if(!(O.persisted===!0||G.getHistory().some((d)=>{let s=d.metadata;return s!==null&&typeof s==="object"&&!Array.isArray(s)&&s.inboxMessageId===O.id}))){let d=await i0($,J,O.content,H,K0);if(!d)throw Error(`Failed to persist steering message before applying it: ${O.id}`);H=d,G.appendUser({role:"user",content:O.content,metadata:z0})}else if(!G.getHistory().some((d)=>{let s=d.metadata;return s!==null&&typeof s==="object"&&!Array.isArray(s)&&s.inboxMessageId===O.id}))G.appendUser({role:"user",content:O.content,metadata:z0});let J0=O.policyText??(typeof O.content==="string"?O.content:O.content.filter((d)=>d.type==="text").map((d)=>d.text).join(`
|
|
137
137
|
`));if(O.origin!=="background_subagent"&&J0.trim())L$=void 0,b0=[b0,J0].join(`
|
|
138
138
|
`),LZ.push(J0),GZ=[b0,J.completionRequirements?.trim()].filter(Boolean).join(`
|
|
139
|
-
`),P$=[$.runtimeOptions.appendSystemPrompt?.trim(),J.completionRequirements?.trim(),...LZ].filter((d)=>Boolean(d)),A1=A1||v1(J0)}return{messageIds:F.map((O)=>O.id),count:F.length,recovered:F.filter((O)=>O.recovered).length,messages:F}};try{if(M0&&W?.goalLifecycle?.snapshot?.completionVerification?.status!=="pending"){await a$("A fresh host run requires new independent completion evidence");let F=await W?.goalLifecycle?.getSnapshot();if(F)yield{kind:"goal_updated",goal:F}}while(!0){if(W?.signal?.aborted)return z(X,Q.length,W.signal);if(X>=F0&&(Z0||v)){if(i.info(`Warning: 达到轮次上限 ${F0} 轮`),W?.onTurnLimitReached){let U=await W.onTurnLimitReached({turnsCount:X});if(W.signal?.aborted)return z(X,Q.length,W.signal);if(U?.continue){G.writeback();let D="failed",y,_,c,f,P,
|
|
139
|
+
`),P$=[$.runtimeOptions.appendSystemPrompt?.trim(),J.completionRequirements?.trim(),...LZ].filter((d)=>Boolean(d)),A1=A1||v1(J0)}return{messageIds:F.map((O)=>O.id),count:F.length,recovered:F.filter((O)=>O.recovered).length,messages:F}};try{if(M0&&W?.goalLifecycle?.snapshot?.completionVerification?.status!=="pending"){await a$("A fresh host run requires new independent completion evidence");let F=await W?.goalLifecycle?.getSnapshot();if(F)yield{kind:"goal_updated",goal:F}}while(!0){if(W?.signal?.aborted)return z(X,Q.length,W.signal);if(X>=F0&&(Z0||v)){if(i.info(`Warning: 达到轮次上限 ${F0} 轮`),W?.onTurnLimitReached){let U=await W.onTurnLimitReached({turnsCount:X});if(W.signal?.aborted)return z(X,Q.length,W.signal);if(U?.continue){G.writeback();let D="failed",y,_,c,f,P,m,x,y0,O0,h,b,X0,n,P0,l;yield{kind:"compaction",phase:"start",reason:"turn_limit"};try{let N=$.chatService.getConfig(),U0=L(),H0=N$&&Z1(P$)?U0.filter((TZ)=>TZ.name!=="Task"):U0,f0=h0?H0.filter((TZ)=>TZ.name===h0):H0,I=tZ(G.systemMessages,f0,N.model),l0=_$.project({history:G.getHistory(),contextRevision:G.contextRevision,modelName:N.model,requestProfile:I});c=l0.source,f=l0.estimatedPendingTokens;let C=await k$.compact(J.messages,{trigger:"auto",modelName:N.model,modelProvider:N.provider,maxContextTokens:N.maxContextTokens??0,apiKey:N.apiKey,baseURL:N.baseUrl,actualPreTokens:l0.contextTokens,signal:W?.signal,activeTask:b0,workspaceRoot:J.workspaceRoot||j0(),workspaceAccess:J.workspaceKind==="acp-remote"?"none":"full",sessionId:J.sessionId});if(C.usage)yield{kind:"token_usage",usage:QZ(C.usage,N.maxContextTokens??0)};let S8={role:"user",metadata:E0,content:`This session is being continued from a previous conversation. The conversation is summarized above.
|
|
140
140
|
|
|
141
|
-
Please continue the conversation from where we left it off without asking the user any further questions. Continue with the last task that you were asked to work on.`},a6=[...C.compactedMessages,S8];y=C.success?"llm":"fallback",_=C.preTokens,P=C.postTokens,
|
|
141
|
+
Please continue the conversation from where we left it off without asking the user any further questions. Continue with the last task that you were asked to work on.`},a6=[...C.compactedMessages,S8];y=C.success?"llm":"fallback",_=C.preTokens,P=C.postTokens,m=C.sampleAttempts,x=C.inputReductions,y0=C.messagesOmitted,O0=C.filesOmitted,h=C.imagesOmitted,b=C.fallbackTargetTokens,X0=C.fallbackMessagesOmitted,n=C.fallbackMessagesTruncated,P0=C.failureReason;let T8=await Y1($,J,C.summary,{trigger:"auto",reason:"turn_limit",strategy:y,preTokens:C.preTokens,preTokenSource:l0.source,...l0.estimatedPendingTokens!==void 0?{estimatedPendingTokens:l0.estimatedPendingTokens}:{},postTokens:C.postTokens,sampleAttempts:C.sampleAttempts,inputReductions:C.inputReductions,messagesOmitted:C.messagesOmitted,filesOmitted:C.filesOmitted,imagesOmitted:C.imagesOmitted,fallbackTargetTokens:C.fallbackTargetTokens,fallbackMessagesOmitted:C.fallbackMessagesOmitted,fallbackMessagesTruncated:C.fallbackMessagesTruncated,failureReason:C.failureReason,filesIncluded:C.filesIncluded,replacementMessages:a6},{required:$.executionEngine!==void 0});l=await M6(C.memoryPlan,J,T8),J.messages=a6,G.replaceHistory(J.messages),_$.reset(),D=C.success?"completed":"fallback"}catch(N){throw i.error("[Loop] 轮次上限压缩失败,停止继续执行:",N),N}finally{yield{kind:"compaction",phase:"end",reason:"turn_limit",outcome:D,strategy:y,preTokens:_,preTokenSource:c,estimatedPendingTokens:f,postTokens:P,sampleAttempts:m,inputReductions:x,messagesOmitted:y0,filesOmitted:O0,imagesOmitted:h,fallbackTargetTokens:b,fallbackMessagesOmitted:X0,fallbackMessagesTruncated:n,failureReason:P0,memory:l}}X=0;continue}return{success:!0,finalMessage:U?.reason||"已达到对话轮次上限,用户选择停止",metadata:{turnsCount:X,toolCallsCount:Q.length,duration:Date.now()-K,tokensUsed:u}}}return{success:!1,error:{type:"max_turns_exceeded",message:v?`子代理已达到轮次上限 (${F0} 轮)。`:`已达到轮次上限 (${F0} 轮)。`},metadata:{turnsCount:X,toolCallsCount:Q.length,duration:Date.now()-K,tokensUsed:u}}}if(await B.waitForMcpCatalogIdle(W?.signal),W?.signal?.aborted)return z(X,Q.length,W.signal);let O=await t0?.drain()??[];if(O.length>0)Q0=void 0,a0=!1,c0=0,yield{kind:"steering_applied",...await b1(O),delivery:FZ?"current_turn":"next_turn",queue:await t0.getSnapshot()},r$=w?T6(G.getHistory(),w):void 0,Q0=r$?.output,a0=r$?.completed===!0,FZ=!0;else if(!FZ)return{success:!0,finalMessage:"",metadata:{turnsCount:0,toolCallsCount:0,duration:Date.now()-K}};if(w&&Q0&&a0){let U=JSON.stringify(Q0);return yield{kind:"structured_output",output:Q0,schemaDigest:w.schemaDigest},{success:!0,finalMessage:U,metadata:{turnsCount:X,toolCallsCount:Q.length,duration:Date.now()-K,tokensUsed:u,structuredOutput:Q0,structuredOutputSchemaDigest:w.schemaDigest}}}let K0=B.drainMcpCatalogChanges();if(K0.length>0){for(let D of K0)yield{kind:"mcp_catalog_changed",...D};let U=K0.map((D)=>{let y=[D.added.length>0?`added=${D.added.join(",")}`:"",D.removed.length>0?`removed=${D.removed.join(",")}`:"",D.updated.length>0?`updated=${D.updated.join(",")}`:""].filter(Boolean).join(" ");return`revision=${D.revision} server=${K$(D.serverName)} ${y}`}).join(`
|
|
142
142
|
`);G.appendControl("user",{role:"user",content:`<system-reminder>
|
|
143
143
|
The MCP tool catalog changed. Newly added tools are deferred; use ToolSearch to load their schemas before calling them. Removed tools are no longer available.
|
|
144
144
|
${U}
|
|
@@ -160,11 +160,11 @@ MCP task ${K$(U.taskId)} for ${K$(U.serverName)}/${K$(U.toolName)} is ${U.status
|
|
|
160
160
|
|
|
161
161
|
<system-reminder>
|
|
162
162
|
${c2(f1,A.totalFailures)}
|
|
163
|
-
</system-reminder>`}:void 0,d6=L(),_Z=N$&&Z1(P$)?d6.filter((U)=>U.name!=="Task"):d6,S1=L$&&_Z.some((U)=>U.name===L$)?L$:void 0,T1=h0??S1,s$=T1?_Z.filter((U)=>U.name===T1):_Z;G.writeback();let A$=$.chatService.getConfig(),c6=tZ(G.systemMessages,s$,A$.model),AZ=_$.project({history:G.getHistory(),pendingMessages:E1?[E1]:[],contextRevision:G.contextRevision,modelName:A$.model,requestProfile:c6}),bZ=G8({contextTokens:AZ.contextTokens,tokenSource:AZ.source,estimatedPendingTokens:AZ.estimatedPendingTokens,maxContextTokens:A$.maxContextTokens,maxOutputTokens:q8({maxContextTokens:A$.maxContextTokens,maxOutputTokens:A$.maxOutputTokens,configuredMaxOutputTokens:$.config.maxOutputTokens})}),R1=yield*O8($,J,X,bZ,W?.signal,M,b0,_8);if(R1.kind==="failed")return g5(X,Q.length,K,R1.phase);if(R1.kind==="snipped"||R1.kind==="compacted")G.replaceHistory(J.messages),_$.reset();if(bZ.phase==="handoff_band"){let U=await v5({deps:$,context:J,state:G,snapshot:bZ,attemptSpent:q1});if(U.kind==="failed"||U.kind==="suppressed")q1=!0}if(G.writeback(),X=f1,yield{kind:"turn_start",turn:X,maxTurns:F0},W?.signal?.aborted)return z(X-1,Q.length,W.signal);if(E1)G.appendControl("user",E1);let l6=W?.stream!==!1,A8=h0;h0=void 0;let b8=G.historyLength+G.pending.length,i6=!v&&($.config.providerForegroundRecoveryMs??0)>0?{mode:"bounded_foreground",budgetMs:$.config.providerForegroundRecoveryMs}:void 0,yZ=J.subagentInfo?.providerAdmissionOwnerId??J.subagentInfo?.parentSessionId??J.sessionId,r6={providerSessionId:J.sessionId,...T1?{toolChoice:{type:"tool",toolName:T1}}:{},...i6?{providerRecovery:i6}:{},providerAdmission:{sessionId:J.sessionId,ownerId:yZ,requestClass:v?"background":"foreground"}},q,e0,X$=new b6;try{if(l6)e0=new XZ($.toolExecutor,{sessionId:J.sessionId,turnId:W?.turnFinalization?.turnId,taskListId:J.taskListId,goalTaskListId:J.goalTaskListId,userId:J.userId||"default",modelId:$.config.currentModelId,providerAdmissionOwnerId:yZ,workspaceRoot:J.workspaceRoot||j0(),executionRoot:J.executionRoot??J.workspaceRoot??j0(),workspaceKind:J.workspaceKind??"local",environment:$.config.env,worktreeIsolationRequired:A1,worktreeActive:w0.has("EnterWorktree")&&!w0.has("ExitWorktree"),subagentType:J.subagentInfo?.subagentType,signal:W?.signal,confirmationHandler:J.confirmationHandler,permissionMode:J.permissionMode,toolRegistry:B,deferredToolManager:B.deferredToolManager},$.toolExecutor.getRegistry(),$.executionEngine?.getContextManager(),J.sessionId,H,J.subagentInfo,(U,D)=>{X$.push({toolCall:U,update:D})},$.executionEngine!==void 0),e0.setAdmissionPolicy(p6),e0.setAdmissionRollback(N8),e0.setExecutionPolicy(m6),q=yield*M5($,G.toLLMMessages(),s$,W?.signal,r6,e0);else q=await $.chatService.chat(G.toLLMMessages(),s$,W?.signal,r6)}catch(U){if(f6(U)&&!E6(U)&&NZ.canAttempt()){i.warn("[Loop] 检测到 prompt_too_long 错误,尝试反应式压缩");let D=$.chatService.getConfig(),y=!1,_="failed",c,f,P,u,x,y0,O0,h,b,X0,n,P0,l;yield{kind:"compaction",phase:"start",reason:"context_limit"};try{e0?.discard();let N=await NZ.tryReactiveCompact(J.messages,{modelName:D.model,modelProvider:D.provider,maxContextTokens:D.maxContextTokens??0,apiKey:D.apiKey,baseURL:D.baseUrl,signal:W?.signal,activeTask:b0,workspaceRoot:J.workspaceRoot||j0(),workspaceAccess:J.workspaceKind==="acp-remote"?"none":"full",sessionId:J.sessionId});if(c=N.strategy,f=N.preTokens,P=N.postTokens,u=N.sampleAttempts,x=N.inputReductions,y0=N.messagesOmitted,O0=N.filesOmitted,h=N.imagesOmitted,b=N.fallbackTargetTokens,X0=N.fallbackMessagesOmitted,n=N.fallbackMessagesTruncated,P0=N.failureReason,N.success&&N.strategy&&N.summary!==void 0&&N.preTokens!==void 0){if(N.usage)yield{kind:"token_usage",usage:QZ(N.usage,D.maxContextTokens??0)};let U0=await Y1($,J,N.summary,{trigger:"auto",reason:"context_limit",strategy:N.strategy,preTokens:N.preTokens,postTokens:N.postTokens,sampleAttempts:N.sampleAttempts,inputReductions:N.inputReductions,messagesOmitted:N.messagesOmitted,filesOmitted:N.filesOmitted,imagesOmitted:N.imagesOmitted,fallbackTargetTokens:N.fallbackTargetTokens,fallbackMessagesOmitted:N.fallbackMessagesOmitted,fallbackMessagesTruncated:N.fallbackMessagesTruncated,failureReason:N.failureReason,filesIncluded:N.filesIncluded,replacementMessages:N.messages},{required:$.executionEngine!==void 0});l=await M6(N.memoryPlan,J,U0),J.messages=N.messages,G.replaceHistory(J.messages),_$.reset(),h0=A8,_=N.strategy==="llm"?"completed":"fallback",y=!0,i.info("[Loop] 反应式压缩成功,重试 LLM 调用")}}catch(N){if(r0(N))throw N;i.error("[Loop] 反应式压缩失败,不重放 Provider 请求",N)}finally{yield{kind:"compaction",phase:"end",reason:"context_limit",outcome:_,strategy:c,preTokens:f,postTokens:P,sampleAttempts:u,inputReductions:x,messagesOmitted:y0,filesOmitted:O0,imagesOmitted:h,fallbackTargetTokens:b,fallbackMessagesOmitted:X0,fallbackMessagesTruncated:n,failureReason:P0,memory:l}}if(y){X--;continue}}else if(f6(U)&&E6(U))i.warn("[Loop] prompt_too_long arrived after Provider output; refusing replay");else if(f6(U))i.warn("[Loop] reactive context recovery already attempted; refusing another replay");throw U}for(let U of q.toolCalls??[]){if(U.type!=="function")continue;let D=U1(U.function.arguments);if(D===null)continue;w1(U.function.name,D),U.function.arguments=JSON.stringify(D)}if(NZ.reset(),M=Date.now(),q.usage){if(q.usage.totalTokens)m+=q.usage.totalTokens;yield{kind:"token_usage",usage:QZ(q.usage,$.currentModelMaxContextTokens)}}_$.recordProviderUsage({usage:q.usage,contextRevision:G.contextRevision,historyLength:b8,modelName:A$.model,requestProfile:c6});let y8=q.usage?.completionTokens??0;if(PZ=e6(PZ,y8,o0>0),W?.signal?.aborted)return z(X-1,Q.length,W.signal);if(!l6||!!q._nonStreamingFallback){if(q.reasoningContent&&q.reasoningContent.trim())yield{kind:"thinking_delta",delta:q.reasoningContent};if(q.content&&q.content.trim())yield{kind:"content_delta",delta:q.content}}yield{kind:"stream_end"};let M1=kZ(q.finishReason,o0,PZ),fZ=M1.action!=="none"&&Q0!==void 0&&w!==void 0&&(q.toolCalls?.length??0)===0;if(fZ){let U=await t0?.drainOrSeal();if(U&&U.messages.length>0){Q0=void 0,a0=!1,c0=0,G.appendAssistant({role:"assistant",content:q.content||"",reasoningContent:q.reasoningContent});let D=await C0($,J,q.content||"",H,q.reasoningContent);if(D)H=D;yield{kind:"steering_applied",...await b1(U.messages),delivery:"current_turn",queue:await t0.getSnapshot()};continue}h6=!0}if(M1.action==="recover"&&!fZ){let U=await C6(q);if(U.action==="continue")continue;if(U.action==="fail")return U.result;o0++,i.warn(`[Loop] Max output tokens hit (recovery ${o0}/3)`);let D={role:"assistant",content:q.content||"",reasoningContent:q.reasoningContent,tool_calls:q.toolCalls};G.appendToHistory(D);let y=await C0($,J,q.content||"",H,q.reasoningContent);if(y)H=y;let _={role:"user",metadata:E0,content:"Output token limit hit. Resume directly — no apology, no recap. "+"Pick up mid-thought if that is where the cut happened. Break remaining work into smaller pieces."};G.appendToHistory(_);let c=await i0($,J,_.content,H,E0);if(c)H=c;continue}if(!fZ&&(M1.action==="truncated"||M1.action==="budget_stop")){let U=!w&&!q.toolCalls?.length?IZ(q.content,b0,s$.map((P)=>P.name),h1):{action:"none"};if(U.action==="fail"||S1)return H=await V0({deps:$,context:J,state:G,assistantContent:q.content||"",assistantReasoningContent:q.reasoningContent,lastMessageUuid:H}),{success:!1,error:{type:"intent_fulfillment_failed",message:U.action==="fail"?U.message:"The model exhausted its output budget before invoking the required native tool."},metadata:{turnsCount:X,toolCallsCount:Q.length,duration:Date.now()-K,tokensUsed:m,outputTruncated:!0}};if(!q.content?.trim()&&!Q0)return{success:!1,error:{type:"intent_fulfillment_failed",message:"The model exhausted its output budget without a non-empty final response."},metadata:{turnsCount:X,toolCallsCount:Q.length,duration:Date.now()-K,tokensUsed:m,outputTruncated:!0}};let D=v6(),y=D?.finalMessage??q.content??"",_=await r(),c=D||_?{...D?.persistenceMetadata,..._?{turnFinalization:_}:{}}:void 0;G.appendAssistant({role:"assistant",content:y,reasoningContent:D?void 0:q.reasoningContent,tool_calls:D?void 0:q.toolCalls,...c?{metadata:u$(c)}:{}});let f=await C0($,J,y,H,D?void 0:q.reasoningContent,c);if(f)H=f;if(w&&!D)return{success:!1,error:{type:"structured_output_failed",message:"The model reached its output budget before submitting a schema-valid structured response."},metadata:{turnsCount:X,toolCallsCount:Q.length,duration:Date.now()-K,tokensUsed:m,outputTruncated:!0,structuredOutputSchemaDigest:w.schemaDigest}};if(D)yield D.event;return{success:!0,finalMessage:y,metadata:{turnsCount:X,toolCallsCount:Q.length,duration:Date.now()-K,tokensUsed:m,outputTruncated:!0,...D?.resultMetadata}}}if(!q.toolCalls||q.toolCalls.length===0){let U=G6(p,[],[]);if(U)yield{kind:"action_stationarity",...U};let D=await t0?.drain()??[];if(D.length>0){if(q.finishReason!=="length")o0=0;Q0=void 0,a0=!1,c0=0,G.appendAssistant({role:"assistant",content:q.content||"",reasoningContent:q.reasoningContent});let I=await C0($,J,q.content||"",H,q.reasoningContent);if(I)H=I;yield{kind:"steering_applied",...await b1(D),delivery:"current_turn",queue:await t0.getSnapshot()};continue}if(w&&!Q0){if(q.finishReason!=="length")o0=0;if(H=await V0({deps:$,context:J,state:G,assistantContent:q.content||"",assistantReasoningContent:q.reasoningContent,lastMessageUuid:H}),c0>=S6)return{success:!1,error:{type:"structured_output_failed",message:`The model did not call ${u0} with a schema-valid object before the corrective retry budget was exhausted.`},metadata:{turnsCount:X,toolCallsCount:Q.length,duration:Date.now()-K,tokensUsed:m,structuredOutputSchemaDigest:w.schemaDigest}};c0++;let I=`The final response is invalid because this turn requires the ${u0} tool. Complete any remaining work, then call ${u0} exactly once with an object matching its schema. Do not return JSON as prose.`;G.appendControl("user",{role:"user",content:I});let l0=await i0($,J,I,H,E0);if(l0)H=l0;continue}let y=IZ(q.content,b0,s$.map((I)=>I.name),X>=F0?h1:k6);if(!w&&y.action!=="none"){if(H=await V0({deps:$,context:J,state:G,assistantContent:q.content||"",assistantReasoningContent:q.reasoningContent,lastMessageUuid:H,...y.action==="retry"?{controlPrompt:y.prompt}:{}}),y.action==="fail")return{success:!1,error:{type:"intent_fulfillment_failed",message:y.message},metadata:{turnsCount:X,toolCallsCount:Q.length,duration:Date.now()-K,tokensUsed:m}};k6++,L$=y.toolName&&!w0.has(y.toolName)?y.toolName:void 0;continue}if(S1)return H=await V0({deps:$,context:J,state:G,assistantContent:q.content||"",assistantReasoningContent:q.reasoningContent,lastMessageUuid:H}),{success:!1,error:{type:"intent_fulfillment_failed",message:"The model did not invoke the required native tool after correcting a textual tool call."},metadata:{turnsCount:X,toolCallsCount:Q.length,duration:Date.now()-K,tokensUsed:m}};let _=await C6(q);if(_.action==="continue")continue;if(_.action==="fail")return _.result;if(q.finishReason!=="length")o0=0;if(q.content&&i2(T,q.content)){H=await V0({deps:$,context:J,state:G,assistantContent:q.content||"",assistantReasoningContent:q.reasoningContent,lastMessageUuid:H,controlPrompt:`
|
|
163
|
+
</system-reminder>`}:void 0,d6=L(),_Z=N$&&Z1(P$)?d6.filter((U)=>U.name!=="Task"):d6,S1=L$&&_Z.some((U)=>U.name===L$)?L$:void 0,T1=h0??S1,s$=T1?_Z.filter((U)=>U.name===T1):_Z;G.writeback();let A$=$.chatService.getConfig(),c6=tZ(G.systemMessages,s$,A$.model),AZ=_$.project({history:G.getHistory(),pendingMessages:E1?[E1]:[],contextRevision:G.contextRevision,modelName:A$.model,requestProfile:c6}),bZ=G8({contextTokens:AZ.contextTokens,tokenSource:AZ.source,estimatedPendingTokens:AZ.estimatedPendingTokens,maxContextTokens:A$.maxContextTokens,maxOutputTokens:q8({maxContextTokens:A$.maxContextTokens,maxOutputTokens:A$.maxOutputTokens,configuredMaxOutputTokens:$.config.maxOutputTokens})}),R1=yield*O8($,J,X,bZ,W?.signal,M,b0,_8);if(R1.kind==="failed")return g5(X,Q.length,K,R1.phase);if(R1.kind==="snipped"||R1.kind==="compacted")G.replaceHistory(J.messages),_$.reset();if(bZ.phase==="handoff_band"){let U=await v5({deps:$,context:J,state:G,snapshot:bZ,attemptSpent:q1});if(U.kind==="failed"||U.kind==="suppressed")q1=!0}if(G.writeback(),X=f1,yield{kind:"turn_start",turn:X,maxTurns:F0},W?.signal?.aborted)return z(X-1,Q.length,W.signal);if(E1)G.appendControl("user",E1);let l6=W?.stream!==!1,A8=h0;h0=void 0;let b8=G.historyLength+G.pending.length,i6=!v&&($.config.providerForegroundRecoveryMs??0)>0?{mode:"bounded_foreground",budgetMs:$.config.providerForegroundRecoveryMs}:void 0,yZ=J.subagentInfo?.providerAdmissionOwnerId??J.subagentInfo?.parentSessionId??J.sessionId,r6={providerSessionId:J.sessionId,...T1?{toolChoice:{type:"tool",toolName:T1}}:{},...i6?{providerRecovery:i6}:{},providerAdmission:{sessionId:J.sessionId,ownerId:yZ,requestClass:v?"background":"foreground"}},q,e0,X$=new b6;try{if(l6)e0=new XZ($.toolExecutor,{sessionId:J.sessionId,turnId:W?.turnFinalization?.turnId,taskListId:J.taskListId,goalTaskListId:J.goalTaskListId,userId:J.userId||"default",modelId:$.config.currentModelId,providerAdmissionOwnerId:yZ,workspaceRoot:J.workspaceRoot||j0(),executionRoot:J.executionRoot??J.workspaceRoot??j0(),workspaceKind:J.workspaceKind??"local",environment:$.config.env,worktreeIsolationRequired:A1,worktreeActive:w0.has("EnterWorktree")&&!w0.has("ExitWorktree"),subagentType:J.subagentInfo?.subagentType,signal:W?.signal,confirmationHandler:J.confirmationHandler,permissionMode:J.permissionMode,toolRegistry:B,deferredToolManager:B.deferredToolManager},$.toolExecutor.getRegistry(),$.executionEngine?.getContextManager(),J.sessionId,H,J.subagentInfo,(U,D)=>{X$.push({toolCall:U,update:D})},$.executionEngine!==void 0),e0.setAdmissionPolicy(p6),e0.setAdmissionRollback(N8),e0.setExecutionPolicy(m6),q=yield*M5($,G.toLLMMessages(),s$,W?.signal,r6,e0);else q=await $.chatService.chat(G.toLLMMessages(),s$,W?.signal,r6)}catch(U){if(f6(U)&&!E6(U)&&NZ.canAttempt()){i.warn("[Loop] 检测到 prompt_too_long 错误,尝试反应式压缩");let D=$.chatService.getConfig(),y=!1,_="failed",c,f,P,m,x,y0,O0,h,b,X0,n,P0,l;yield{kind:"compaction",phase:"start",reason:"context_limit"};try{e0?.discard();let N=await NZ.tryReactiveCompact(J.messages,{modelName:D.model,modelProvider:D.provider,maxContextTokens:D.maxContextTokens??0,apiKey:D.apiKey,baseURL:D.baseUrl,signal:W?.signal,activeTask:b0,workspaceRoot:J.workspaceRoot||j0(),workspaceAccess:J.workspaceKind==="acp-remote"?"none":"full",sessionId:J.sessionId});if(c=N.strategy,f=N.preTokens,P=N.postTokens,m=N.sampleAttempts,x=N.inputReductions,y0=N.messagesOmitted,O0=N.filesOmitted,h=N.imagesOmitted,b=N.fallbackTargetTokens,X0=N.fallbackMessagesOmitted,n=N.fallbackMessagesTruncated,P0=N.failureReason,N.success&&N.strategy&&N.summary!==void 0&&N.preTokens!==void 0){if(N.usage)yield{kind:"token_usage",usage:QZ(N.usage,D.maxContextTokens??0)};let U0=await Y1($,J,N.summary,{trigger:"auto",reason:"context_limit",strategy:N.strategy,preTokens:N.preTokens,postTokens:N.postTokens,sampleAttempts:N.sampleAttempts,inputReductions:N.inputReductions,messagesOmitted:N.messagesOmitted,filesOmitted:N.filesOmitted,imagesOmitted:N.imagesOmitted,fallbackTargetTokens:N.fallbackTargetTokens,fallbackMessagesOmitted:N.fallbackMessagesOmitted,fallbackMessagesTruncated:N.fallbackMessagesTruncated,failureReason:N.failureReason,filesIncluded:N.filesIncluded,replacementMessages:N.messages},{required:$.executionEngine!==void 0});l=await M6(N.memoryPlan,J,U0),J.messages=N.messages,G.replaceHistory(J.messages),_$.reset(),h0=A8,_=N.strategy==="llm"?"completed":"fallback",y=!0,i.info("[Loop] 反应式压缩成功,重试 LLM 调用")}}catch(N){if(r0(N))throw N;i.error("[Loop] 反应式压缩失败,不重放 Provider 请求",N)}finally{yield{kind:"compaction",phase:"end",reason:"context_limit",outcome:_,strategy:c,preTokens:f,postTokens:P,sampleAttempts:m,inputReductions:x,messagesOmitted:y0,filesOmitted:O0,imagesOmitted:h,fallbackTargetTokens:b,fallbackMessagesOmitted:X0,fallbackMessagesTruncated:n,failureReason:P0,memory:l}}if(y){X--;continue}}else if(f6(U)&&E6(U))i.warn("[Loop] prompt_too_long arrived after Provider output; refusing replay");else if(f6(U))i.warn("[Loop] reactive context recovery already attempted; refusing another replay");throw U}for(let U of q.toolCalls??[]){if(U.type!=="function")continue;let D=U1(U.function.arguments);if(D===null)continue;w1(U.function.name,D),U.function.arguments=JSON.stringify(D)}if(NZ.reset(),M=Date.now(),q.usage){if(q.usage.totalTokens)u+=q.usage.totalTokens;yield{kind:"token_usage",usage:QZ(q.usage,$.currentModelMaxContextTokens)}}_$.recordProviderUsage({usage:q.usage,contextRevision:G.contextRevision,historyLength:b8,modelName:A$.model,requestProfile:c6});let y8=q.usage?.completionTokens??0;if(PZ=e6(PZ,y8,o0>0),W?.signal?.aborted)return z(X-1,Q.length,W.signal);if(!l6||!!q._nonStreamingFallback){if(q.reasoningContent&&q.reasoningContent.trim())yield{kind:"thinking_delta",delta:q.reasoningContent};if(q.content&&q.content.trim())yield{kind:"content_delta",delta:q.content}}yield{kind:"stream_end"};let M1=kZ(q.finishReason,o0,PZ),fZ=M1.action!=="none"&&Q0!==void 0&&w!==void 0&&(q.toolCalls?.length??0)===0;if(fZ){let U=await t0?.drainOrSeal();if(U&&U.messages.length>0){Q0=void 0,a0=!1,c0=0,G.appendAssistant({role:"assistant",content:q.content||"",reasoningContent:q.reasoningContent});let D=await C0($,J,q.content||"",H,q.reasoningContent);if(D)H=D;yield{kind:"steering_applied",...await b1(U.messages),delivery:"current_turn",queue:await t0.getSnapshot()};continue}h6=!0}if(M1.action==="recover"&&!fZ){let U=await C6(q);if(U.action==="continue")continue;if(U.action==="fail")return U.result;o0++,i.warn(`[Loop] Max output tokens hit (recovery ${o0}/3)`);let D={role:"assistant",content:q.content||"",reasoningContent:q.reasoningContent,tool_calls:q.toolCalls};G.appendToHistory(D);let y=await C0($,J,q.content||"",H,q.reasoningContent);if(y)H=y;let _={role:"user",metadata:E0,content:"Output token limit hit. Resume directly — no apology, no recap. "+"Pick up mid-thought if that is where the cut happened. Break remaining work into smaller pieces."};G.appendToHistory(_);let c=await i0($,J,_.content,H,E0);if(c)H=c;continue}if(!fZ&&(M1.action==="truncated"||M1.action==="budget_stop")){let U=!w&&!q.toolCalls?.length?IZ(q.content,b0,s$.map((P)=>P.name),h1):{action:"none"};if(U.action==="fail"||S1)return H=await V0({deps:$,context:J,state:G,assistantContent:q.content||"",assistantReasoningContent:q.reasoningContent,lastMessageUuid:H}),{success:!1,error:{type:"intent_fulfillment_failed",message:U.action==="fail"?U.message:"The model exhausted its output budget before invoking the required native tool."},metadata:{turnsCount:X,toolCallsCount:Q.length,duration:Date.now()-K,tokensUsed:u,outputTruncated:!0}};if(!q.content?.trim()&&!Q0)return{success:!1,error:{type:"intent_fulfillment_failed",message:"The model exhausted its output budget without a non-empty final response."},metadata:{turnsCount:X,toolCallsCount:Q.length,duration:Date.now()-K,tokensUsed:u,outputTruncated:!0}};let D=v6(),y=D?.finalMessage??q.content??"",_=await r(),c=D||_?{...D?.persistenceMetadata,..._?{turnFinalization:_}:{}}:void 0;G.appendAssistant({role:"assistant",content:y,reasoningContent:D?void 0:q.reasoningContent,tool_calls:D?void 0:q.toolCalls,...c?{metadata:u$(c)}:{}});let f=await C0($,J,y,H,D?void 0:q.reasoningContent,c);if(f)H=f;if(w&&!D)return{success:!1,error:{type:"structured_output_failed",message:"The model reached its output budget before submitting a schema-valid structured response."},metadata:{turnsCount:X,toolCallsCount:Q.length,duration:Date.now()-K,tokensUsed:u,outputTruncated:!0,structuredOutputSchemaDigest:w.schemaDigest}};if(D)yield D.event;return{success:!0,finalMessage:y,metadata:{turnsCount:X,toolCallsCount:Q.length,duration:Date.now()-K,tokensUsed:u,outputTruncated:!0,...D?.resultMetadata}}}if(!q.toolCalls||q.toolCalls.length===0){let U=G6(p,[],[]);if(U)yield{kind:"action_stationarity",...U};let D=await t0?.drain()??[];if(D.length>0){if(q.finishReason!=="length")o0=0;Q0=void 0,a0=!1,c0=0,G.appendAssistant({role:"assistant",content:q.content||"",reasoningContent:q.reasoningContent});let I=await C0($,J,q.content||"",H,q.reasoningContent);if(I)H=I;yield{kind:"steering_applied",...await b1(D),delivery:"current_turn",queue:await t0.getSnapshot()};continue}if(w&&!Q0){if(q.finishReason!=="length")o0=0;if(H=await V0({deps:$,context:J,state:G,assistantContent:q.content||"",assistantReasoningContent:q.reasoningContent,lastMessageUuid:H}),c0>=S6)return{success:!1,error:{type:"structured_output_failed",message:`The model did not call ${u0} with a schema-valid object before the corrective retry budget was exhausted.`},metadata:{turnsCount:X,toolCallsCount:Q.length,duration:Date.now()-K,tokensUsed:u,structuredOutputSchemaDigest:w.schemaDigest}};c0++;let I=`The final response is invalid because this turn requires the ${u0} tool. Complete any remaining work, then call ${u0} exactly once with an object matching its schema. Do not return JSON as prose.`;G.appendControl("user",{role:"user",content:I});let l0=await i0($,J,I,H,E0);if(l0)H=l0;continue}let y=IZ(q.content,b0,s$.map((I)=>I.name),X>=F0?h1:k6);if(!w&&y.action!=="none"){if(H=await V0({deps:$,context:J,state:G,assistantContent:q.content||"",assistantReasoningContent:q.reasoningContent,lastMessageUuid:H,...y.action==="retry"?{controlPrompt:y.prompt}:{}}),y.action==="fail")return{success:!1,error:{type:"intent_fulfillment_failed",message:y.message},metadata:{turnsCount:X,toolCallsCount:Q.length,duration:Date.now()-K,tokensUsed:u}};k6++,L$=y.toolName&&!w0.has(y.toolName)?y.toolName:void 0;continue}if(S1)return H=await V0({deps:$,context:J,state:G,assistantContent:q.content||"",assistantReasoningContent:q.reasoningContent,lastMessageUuid:H}),{success:!1,error:{type:"intent_fulfillment_failed",message:"The model did not invoke the required native tool after correcting a textual tool call."},metadata:{turnsCount:X,toolCallsCount:Q.length,duration:Date.now()-K,tokensUsed:u}};let _=await C6(q);if(_.action==="continue")continue;if(_.action==="fail")return _.result;if(q.finishReason!=="length")o0=0;if(q.content&&i2(T,q.content)){H=await V0({deps:$,context:J,state:G,assistantContent:q.content||"",assistantReasoningContent:q.reasoningContent,lastMessageUuid:H,controlPrompt:`
|
|
164
164
|
|
|
165
165
|
<system-reminder>
|
|
166
166
|
${r2()}
|
|
167
|
-
</system-reminder>`});continue}let c=D0?{action:"none"}:xZ(q.content,HZ,!1);if(c.action==="retry"){HZ++,H=await V0({deps:$,context:J,state:G,assistantContent:q.content||"",assistantReasoningContent:q.reasoningContent,lastMessageUuid:H,controlPrompt:c.prompt});continue}HZ=0;let f=D0?{action:"none"}:jJ(P$,w0,zZ);if(f.action==="retry"){zZ++,h0="Task",H=await V0({deps:$,context:J,state:G,assistantContent:q.content||"",assistantReasoningContent:q.reasoningContent,lastMessageUuid:H,controlPrompt:f.prompt});continue}if(f.action==="fail")return H=await V0({deps:$,context:J,state:G,assistantContent:q.content||"",assistantReasoningContent:q.reasoningContent,lastMessageUuid:H}),{success:!1,error:{type:"delegation_protocol_failed",message:f.message},metadata:{turnsCount:X,toolCallsCount:Q.length,duration:Date.now()-K,tokensUsed:
|
|
167
|
+
</system-reminder>`});continue}let c=D0?{action:"none"}:xZ(q.content,HZ,!1);if(c.action==="retry"){HZ++,H=await V0({deps:$,context:J,state:G,assistantContent:q.content||"",assistantReasoningContent:q.reasoningContent,lastMessageUuid:H,controlPrompt:c.prompt});continue}HZ=0;let f=D0?{action:"none"}:jJ(P$,w0,zZ);if(f.action==="retry"){zZ++,h0="Task",H=await V0({deps:$,context:J,state:G,assistantContent:q.content||"",assistantReasoningContent:q.reasoningContent,lastMessageUuid:H,controlPrompt:f.prompt});continue}if(f.action==="fail")return H=await V0({deps:$,context:J,state:G,assistantContent:q.content||"",assistantReasoningContent:q.reasoningContent,lastMessageUuid:H}),{success:!1,error:{type:"delegation_protocol_failed",message:f.message},metadata:{turnsCount:X,toolCallsCount:Q.length,duration:Date.now()-K,tokensUsed:u}};zZ=0;let P=D0?{action:"none"}:DJ(b0,w0,BZ);if(P.action==="retry"){BZ++,H=await V0({deps:$,context:J,state:G,assistantContent:q.content||"",assistantReasoningContent:q.reasoningContent,lastMessageUuid:H,controlPrompt:P.prompt});continue}if(P.action==="fail")return H=await V0({deps:$,context:J,state:G,assistantContent:q.content||"",assistantReasoningContent:q.reasoningContent,lastMessageUuid:H}),{success:!1,error:{type:"worktree_protocol_failed",message:P.message},metadata:{turnsCount:X,toolCallsCount:Q.length,duration:Date.now()-K,tokensUsed:u}};BZ=0;let m=Y8({enabled:g,isSubagent:v,taskAvailable:g&&L().some((I)=>I.name==="Task"),delegationForbidden:P$.some(zJ),singleTaskDelegationRequired:OZ(),modifiedFiles:o$,mutationRevision:O$,verificationRevision:n$,verificationVerdict:s0,retryCount:G1});if(m.action==="retry"){if(G1++,m$=m.requireVerificationTask,m$)h0="Task";H=await V0({deps:$,context:J,state:G,assistantContent:q.content||"",assistantReasoningContent:q.reasoningContent,lastMessageUuid:H,controlPrompt:m.prompt});continue}if(m.action==="fail")return H=await V0({deps:$,context:J,state:G,assistantContent:q.content||"",assistantReasoningContent:q.reasoningContent,lastMessageUuid:H}),{success:!1,error:{type:"verification_failed",message:m.message},metadata:{turnsCount:X,toolCallsCount:Q.length,duration:Date.now()-K,tokensUsed:u}};G1=0;let x=D0?{action:"none"}:hZ(GZ,UZ,jZ);if(x.action==="retry"){jZ++,h0="Bash",H=await V0({deps:$,context:J,state:G,assistantContent:q.content||"",assistantReasoningContent:q.reasoningContent,lastMessageUuid:H,controlPrompt:x.prompt});continue}if(x.action==="fail")return H=await V0({deps:$,context:J,state:G,assistantContent:q.content||"",assistantReasoningContent:q.reasoningContent,lastMessageUuid:H}),{success:!1,error:{type:"verification_failed",message:x.message},metadata:{turnsCount:X,toolCallsCount:Q.length,duration:Date.now()-K,tokensUsed:u}};jZ=0;let y0=D0||J.workspaceKind==="acp-remote"?{action:"stop"}:await vZ({sessionId:J.sessionId,workspaceRoot:J.workspaceRoot,permissionMode:J.permissionMode,reason:q.content,abortSignal:W?.signal});if(y0.action==="continue"){await a$("Goal completion evidence invalidated by a Stop hook continuation");let I=y0.reason?`
|
|
168
168
|
|
|
169
169
|
<system-reminder>
|
|
170
170
|
${y0.reason}
|
|
@@ -172,9 +172,9 @@ ${y0.reason}
|
|
|
172
172
|
|
|
173
173
|
<system-reminder>
|
|
174
174
|
Please continue the conversation from where we left it off without asking the user any further questions. Continue with the last task that you were asked to work on.
|
|
175
|
-
</system-reminder>`;H=await V0({deps:$,context:J,state:G,assistantContent:q.content||"",assistantReasoningContent:q.reasoningContent,lastMessageUuid:H,controlPrompt:I});continue}let O0=await t0?.drainOrSeal();if(O0&&O0.messages.length>0){await a$("Goal completion evidence invalidated by new user steering"),Q0=void 0,a0=!1,c0=0,G.appendAssistant({role:"assistant",content:q.content||"",reasoningContent:q.reasoningContent});let I=await C0($,J,q.content||"",H,q.reasoningContent);if(I)H=I;yield{kind:"steering_applied",...await b1(O0.messages),delivery:"current_turn",queue:await t0.getSnapshot()};continue}let h=a2({requested:M0,taskAvailable:L().some((I)=>I.name==="Task"),mutationRevision:O$,verificationRevision:c$,verificationVerdict:_0,verificationFeedback:F$,verificationStallCount:i$,retryCount:L1});if(h.action==="retry"){if(L1++,m0=h.requireVerificationTask,m0)h0="Task";H=await V0({deps:$,context:J,state:G,assistantContent:q.content||"",assistantReasoningContent:q.reasoningContent,lastMessageUuid:H,controlPrompt:h.prompt});continue}if(h.action==="fail")return H=await V0({deps:$,context:J,state:G,assistantContent:q.content||"",assistantReasoningContent:q.reasoningContent,lastMessageUuid:H}),{success:!1,error:{type:"goal_verification_failed",message:h.message},metadata:{turnsCount:X,toolCallsCount:Q.length,duration:Date.now()-K,tokensUsed:m,goalVerificationVerdict:_0,goalVerifierSessionId:k0,goalVerificationEvidenceSha256:v0}};let b=!1,X0=!1;if(M0){if(!W?.goalLifecycle||_0!=="pass")return{success:!1,error:{type:"goal_verification_failed",message:"Goal completion reached the final boundary without host-owned verification authority and a fresh PASS."},metadata:{turnsCount:X,toolCallsCount:Q.length,duration:Date.now()-K,tokensUsed:m,goalVerificationVerdict:_0,goalVerifierSessionId:k0,goalVerificationEvidenceSha256:v0}};X0=!0}let n=v6(),P0=n?.finalMessage??q.content??"",l=n?.persistenceMetadata,N;if(X0){let I=d0?.completionVerification;if(d0?.status!=="verifying"||d0.goalId!==l$||I?.status!=="pass"||I.attempt!==O1||typeof I.verifierSessionId!=="string"||I.verifierSessionId!==k0||typeof I.evidenceSha256!=="string"||I.evidenceSha256!==v0)throw Error("Goal completion lost its persisted verification receipt before finalization");N={goalId:d0.goalId,verificationAttempt:I.attempt,verifierSessionId:I.verifierSessionId,evidenceSha256:I.evidenceSha256,goalUpdatedAt:d0.updatedAt}}let U0=await r(N),H0=l||U0?{...l,...U0?{turnFinalization:U0}:{}}:void 0;G.appendAssistant({role:"assistant",content:P0,...H0?{metadata:u$(H0)}:{}});let f0=await C0($,J,P0,H,l?void 0:q.reasoningContent,H0);if(f0)H=f0;if(X0&&W?.goalLifecycle){let I=await W.goalLifecycle.finalizeCompletion();M0=!1,b=!0,yield{kind:"goal_updated",goal:I}}if(n)yield n.event;return{success:!0,finalMessage:P0,metadata:{turnsCount:X,toolCallsCount:Q.length,duration:Date.now()-K,tokensUsed:m,toolSuccessRate:Q.length>0?Q.filter((I)=>I.success).length/Q.length:void 0,totalToolFailures:A.totalFailures||void 0,...S(),...b?{goalCompletionVerified:!0,goalVerificationVerdict:"pass",...k0?{goalVerifierSessionId:k0}:{},...v0?{goalVerificationEvidenceSha256:v0}:{}}:{},...h6?{outputTruncated:!0}:{},...n?.resultMetadata}}}if(q.finishReason!=="length")o0=0;G.appendAssistant({role:"assistant",content:q.content||"",reasoningContent:q.reasoningContent,tool_calls:q.toolCalls});{let U=await C0($,J,q.content||"",H,q.reasoningContent);if(U)H=U}if(W?.signal?.aborted)return z(X,Q.length,W.signal);let k1=q.toolCalls.filter((U)=>U.type==="function"),EZ;if(e0?.hasTools()){i.debug(`[Loop] 使用 StreamingToolExecutor 收集 ${k1.length} 个工具结果`);let U=e0;for(let D of U.getQueuedToolCalls()){let _=B.get(D.function.name)?.kind;yield{kind:"tool_start",toolCall:D,toolKind:_}}EZ=(async()=>{let D=[];for await(let y of U.getRemainingResults())D.push(y);return D})()}else{let U=new Map,D=new D1;for(let f of k1){let P=D.admit();if(P){U.set(f.id,P);continue}let u=U1(f.function.arguments),x=u===null?void 0:p6(f.function.name,u);if(x){U.set(f.id,x);continue}let O0=B.get(f.function.name)?.kind;yield{kind:"tool_start",toolCall:f,toolKind:O0}}let y=Promise.resolve(),_=(f,P,u)=>{let x=y.then(()=>pZ($,J,f,P,H,{required:$.executionEngine!==void 0,providerToolCallId:u}));return y=x.then(()=>{return},()=>{return}),x},c=async(f)=>{let P=null;try{let u=U.get(f.id);if(u)return{toolCall:f,result:u,toolUseUuid:null};let x=U1(f.function.arguments);if(x===null)return{toolCall:f,result:{success:!1,llmContent:"",error:{type:"validation_error",message:`Invalid JSON object in tool arguments. Raw: ${f.function.arguments.slice(0,200)}`},metadata:void 0},toolUseUuid:null};w1(f.function.name,x);try{P=await _(f.function.name,x,f.id)}catch(h){return{toolCall:f,result:{success:!1,llmContent:j$,error:{type:"execution_error",message:j$},metadata:{durableToolUseFailed:!0,summary:"Blocked tool before execution"}},toolUseUuid:null,error:h instanceof Error?h:Error(String(h))}}if(f.function.name==="ExitWorktree"&&w0.has("EnterWorktree")&&!w0.has("ExitWorktree")&&hZ(GZ,UZ,0).action!=="none"){let h="Run the requested verification before ExitWorktree. The worktree remains active so Bash can run in isolation.";return{toolCall:f,result:{success:!1,llmContent:h,error:{type:"validation_error",message:h},metadata:{summary:"Blocked ExitWorktree until verification succeeds"}},toolUseUuid:P}}let O0=await m6(f.function.name,x,{sessionId:J.sessionId,turnId:W?.turnFinalization?.turnId,taskListId:J.taskListId,goalTaskListId:J.goalTaskListId,userId:J.userId||"default",modelId:$.config.currentModelId,providerAdmissionOwnerId:yZ,workspaceRoot:J.workspaceRoot||j0(),executionRoot:J.executionRoot??J.workspaceRoot??j0(),workspaceKind:J.workspaceKind??"local",environment:$.config.env,worktreeIsolationRequired:A1,worktreeActive:w0.has("EnterWorktree")&&!w0.has("ExitWorktree"),subagentType:J.subagentInfo?.subagentType,signal:W?.signal,confirmationHandler:J.sessionId&&J.workspaceKind!=="acp-remote"?G0.createConfirmationHandler(J.confirmationHandler,{sessionId:J.sessionId,projectPath:J.workspaceRoot||j0(),toolCallId:P??f.id,toolName:f.function.name}):J.confirmationHandler,permissionMode:J.permissionMode,toolRegistry:B,deferredToolManager:B.deferredToolManager,onProgress:(h)=>{X$.push({toolCall:f,update:{message:h.slice(0,1000)}})},onProgressUpdate:(h)=>{X$.push({toolCall:f,update:h})}});return{toolCall:f,result:O0,toolUseUuid:P}}catch(u){return i.error(`Tool execution failed for ${f.function.name}:`,u),{toolCall:f,result:{success:!1,llmContent:"",error:{type:"execution_error",message:u instanceof Error?u.message:"Unknown error"},metadata:void 0},toolUseUuid:P,error:u instanceof Error?u:Error("Unknown error")}}};EZ=Promise.all(k1.map(c))}let x1,n6,o6=!1,SZ=!1,f8=EZ.then((U)=>{x1=U},(U)=>{o6=!0,n6=U}).finally(()=>{SZ=!0,X$.close()});while(!SZ||X$.hasPending){let U=X$.shift()??(SZ?void 0:await X$.next());if(U)yield{kind:"tool_progress",toolCall:U.toolCall,update:U.update}}if(await f8,o6)throw n6;if(!x1)throw Error("Tool execution completed without results");let E8=new J6;for(let{toolCall:U,result:D,toolUseUuid:y}of x1){let _=U;if(Q.push(D),_.function.name===S1)L$=void 0;if(D.metadata?.abortedBeforeLaunch){let b=D.error?.message??"任务已被用户中止";if(y)try{let X0=await g1($,J,y,_.function.name,null,y,b,void 0,void 0,{required:$.executionEngine!==void 0});if(X0)H=X0}catch{return j8(X,Q.length,K)}return G.appendToolResult({role:"tool",tool_call_id:_.id,name:_.function.name,content:`Error: ${b}`}),z(X,Q.length,W?.signal)}{let b=D.metadata&&typeof D.metadata==="object"?D.metadata:void 0,n=((H0)=>H0==="running"||H0==="completed"||H0==="failed"||H0==="cancelled")(b?.subagentStatus)?b.subagentStatus:"completed",P0=b?.verificationVerdict==="pass"||b?.verificationVerdict==="fail"||b?.verificationVerdict==="partial"?b.verificationVerdict:void 0,l=b&&typeof b.subagentSessionId==="string"?{subagentSessionId:b.subagentSessionId,subagentType:typeof b.subagentType==="string"?b.subagentType:_.function.name,subagentDescription:typeof b.description==="string"?b.description:void 0,subagentStatus:n,subagentSummary:typeof b.subagentSummary==="string"?b.subagentSummary:void 0,subagentResumedFrom:typeof b.subagentResumedFrom==="string"?b.subagentResumedFrom:void 0,subagentRootId:typeof b.subagentRootId==="string"?b.subagentRootId:void 0,subagentResumeDepth:typeof b.subagentResumeDepth==="number"?b.subagentResumeDepth:void 0,verificationVerdict:P0}:void 0,N=b?(()=>{let{oldContent:H0,newContent:f0,...I}=b;return u$(I)})():void 0;if(b?.durableToolUseFailed!==!0&&(y!==null||$.executionEngine===void 0))try{let H0=await g1($,J,y??_.id,_.function.name,D.success?u$(D.llmContent):null,y,D.success?void 0:D.error?.message,l,N,{required:$.executionEngine!==void 0});if(H0)H=H0}catch{return j8(X,Q.length,K)}}yield{kind:"tool_result",toolCall:_,result:D};let c=await y6(_,D,$,J);if(c){if(yield c,!J.taskListId&&W?.goalLifecycle?.refreshFrontier){let b=await W.goalLifecycle.refreshFrontier();if(b?.ok)yield{kind:"goal_frontier_updated",goal:b.goal,frontier:b.frontier,tasks:b.tasks};else if(b){if(b.goal)yield{kind:"goal_updated",goal:b.goal};return{success:!1,error:{type:"goal_frontier_unavailable",message:b.error.message},metadata:{turnsCount:X,toolCallsCount:Q.length,duration:Date.now()-K,tokensUsed:m}}}}}let f,P=D.metadata&&typeof D.metadata==="object"?D.metadata:void 0,u=_.function.name==="Task"&&P?{subagentSessionId:P.subagentSessionId,subagentType:P.subagentType,subagentStatus:P.subagentStatus,subagentSummary:P.subagentSummary,subagentResumedFrom:P.subagentResumedFrom,subagentRootId:P.subagentRootId,subagentResumeDepth:P.subagentResumeDepth,verificationVerdict:P.verificationVerdict,verificationFeedback:P.verificationFeedback}:void 0;if(D.success){if(p2(A,_.function.name),P?.goalCompletionRequested===!0){if(!W?.goalLifecycle)throw Error("Goal completion candidate has no host lifecycle authority");M0=!0;let l=typeof P.goalCompletionAttempt==="number"?P.goalCompletionAttempt:void 0,N=typeof P.goalCompletionRequestedAt==="string"?P.goalCompletionRequestedAt:void 0,U0=typeof P.goalId==="string"?P.goalId:void 0;if(o2({goalId:l$,attempt:O1,requestedAt:wZ},{goalId:U0,attempt:l,requestedAt:N}))L1=0,c$=-1,_0=void 0,k0=void 0,F$=void 0,N1=void 0,v0=void 0,d0=void 0;O1=l??O1,wZ=N??wZ,l$=U0??l$,P1=typeof P.goalObjective==="string"?P.goalObjective:P1;let f0=await W?.goalLifecycle?.getSnapshot();if(f0)i$=f0.verificationStall?.consecutiveCount,yield{kind:"goal_updated",goal:f0}}else if(_.function.name==="UpdateGoal"&&P?.goalStatus==="blocked"){M0=!1,m0=!1,d$=!1,F1=!1,_0=void 0,c$=-1,k0=void 0,F$=void 0,N1=void 0,i$=void 0,v0=void 0,d0=void 0;let l=await W?.goalLifecycle?.getSnapshot();if(l)yield{kind:"goal_updated",goal:l}}let b=J8(o$,_.function.name,D,J.workspaceRoot);if(b.length>0){if(Q0=void 0,a0=!1,c0=0,O$++,n$=-1,s0=void 0,G1=0,M0){L1=0,await a$("Goal completion evidence invalidated by a workspace mutation");let l=await W?.goalLifecycle?.getSnapshot();if(l)i$=l.verificationStall?.consecutiveCount,yield{kind:"goal_updated",goal:l}}if(W?.goalLifecycle?.clearFrontierStall){let l=await W.goalLifecycle.clearFrontierStall();if(l)yield{kind:"goal_updated",goal:l}}}let X0=typeof P?.subagentType==="string"?P.subagentType:typeof P?.subagent_type==="string"?P.subagent_type:void 0,n=X0===n0,P0=_.function.name==="Task"&&P?.verificationAgentBuiltin===!0&&(X0===Y$||n)&&(P?.subagentStatus==="completed"||P?.status==="completed");if(P0){if(s0=(P?.verificationVerdict==="pass"||P?.verificationVerdict==="fail"||P?.verificationVerdict==="partial"?P.verificationVerdict:void 0)??$8(typeof D.llmContent==="string"?D.llmContent:P?.subagentSummary&&typeof P.subagentSummary==="string"?P.subagentSummary:void 0),n$=O$,F1&&n){F1=!1,_0=s0,c$=O$,k0=typeof P?.subagentSessionId==="string"?P.subagentSessionId:void 0;let N=typeof D.llmContent==="string"?D.llmContent.slice(0,4000):typeof P?.subagentSummary==="string"?P.subagentSummary:void 0,U0=typeof P?.verificationFeedback==="string"&&P.verificationFeedback.trim()?P.verificationFeedback.trim():void 0;if(F$=_0?U0??`Independent verifier returned ${_0.toUpperCase()}.`:void 0,N1=_0!=="pass"&&U0?R6("sha256").update(U0,"utf8").digest("hex"):void 0,_0&&W?.goalLifecycle){let H0=JSON.stringify({goalId:l$,objective:P1,mutationRevision:O$,verdict:_0,verifierSessionId:k0,evidence:N});v0=R6("sha256").update(H0).digest("hex");let f0=await W.goalLifecycle.recordVerification({verdict:_0,verifierSessionId:k0,summary:F$,evidenceSha256:v0,feedbackSha256:N1});d0=f0,i$=f0.verificationStall?.consecutiveCount,yield{kind:"goal_updated",goal:f0}}}}if(b.length>0||P0)f={...b.length>0?{modifiedFiles:b}:{},...P0?{verificationAttempted:!0,verificationAgentBuiltin:!0,...s0?{verificationVerdict:s0}:{}}:{}};if(_.function.name==="EnterWorktree"&&D.metadata?.workspaceTransition==="enter")w0.add("EnterWorktree"),w0.delete("ExitWorktree");else if(_.function.name==="ExitWorktree"&&D.metadata?.workspaceTransition==="exit"&&w0.has("EnterWorktree"))w0.add("ExitWorktree");else if(!["EnterWorktree","ExitWorktree"].includes(_.function.name))w0.add(_.function.name);if(_.function.name==="Task"&&D.metadata?.isolation==="worktree")w0.add("TaskWorktree");HJ(UZ,_.function.name,D,J.workspaceRoot)}else u2(A,_.function.name);Y2(E,_.function.name,D);let x=D.success?D.llmContent||"":S5(_.function.name,D.error);if(!D.success){let b=m2(A,_.function.name);if(b&&typeof x==="string")x=`${x}
|
|
175
|
+
</system-reminder>`;H=await V0({deps:$,context:J,state:G,assistantContent:q.content||"",assistantReasoningContent:q.reasoningContent,lastMessageUuid:H,controlPrompt:I});continue}let O0=await t0?.drainOrSeal();if(O0&&O0.messages.length>0){await a$("Goal completion evidence invalidated by new user steering"),Q0=void 0,a0=!1,c0=0,G.appendAssistant({role:"assistant",content:q.content||"",reasoningContent:q.reasoningContent});let I=await C0($,J,q.content||"",H,q.reasoningContent);if(I)H=I;yield{kind:"steering_applied",...await b1(O0.messages),delivery:"current_turn",queue:await t0.getSnapshot()};continue}let h=a2({requested:M0,taskAvailable:L().some((I)=>I.name==="Task"),mutationRevision:O$,verificationRevision:c$,verificationVerdict:_0,verificationFeedback:F$,verificationStallCount:i$,retryCount:L1});if(h.action==="retry"){if(L1++,m0=h.requireVerificationTask,m0)h0="Task";H=await V0({deps:$,context:J,state:G,assistantContent:q.content||"",assistantReasoningContent:q.reasoningContent,lastMessageUuid:H,controlPrompt:h.prompt});continue}if(h.action==="fail")return H=await V0({deps:$,context:J,state:G,assistantContent:q.content||"",assistantReasoningContent:q.reasoningContent,lastMessageUuid:H}),{success:!1,error:{type:"goal_verification_failed",message:h.message},metadata:{turnsCount:X,toolCallsCount:Q.length,duration:Date.now()-K,tokensUsed:u,goalVerificationVerdict:_0,goalVerifierSessionId:k0,goalVerificationEvidenceSha256:v0}};let b=!1,X0=!1;if(M0){if(!W?.goalLifecycle||_0!=="pass")return{success:!1,error:{type:"goal_verification_failed",message:"Goal completion reached the final boundary without host-owned verification authority and a fresh PASS."},metadata:{turnsCount:X,toolCallsCount:Q.length,duration:Date.now()-K,tokensUsed:u,goalVerificationVerdict:_0,goalVerifierSessionId:k0,goalVerificationEvidenceSha256:v0}};X0=!0}let n=v6(),P0=n?.finalMessage??q.content??"",l=n?.persistenceMetadata,N;if(X0){let I=d0?.completionVerification;if(d0?.status!=="verifying"||d0.goalId!==l$||I?.status!=="pass"||I.attempt!==O1||typeof I.verifierSessionId!=="string"||I.verifierSessionId!==k0||typeof I.evidenceSha256!=="string"||I.evidenceSha256!==v0)throw Error("Goal completion lost its persisted verification receipt before finalization");N={goalId:d0.goalId,verificationAttempt:I.attempt,verifierSessionId:I.verifierSessionId,evidenceSha256:I.evidenceSha256,goalUpdatedAt:d0.updatedAt}}let U0=await r(N),H0=l||U0?{...l,...U0?{turnFinalization:U0}:{}}:void 0;G.appendAssistant({role:"assistant",content:P0,...H0?{metadata:u$(H0)}:{}});let f0=await C0($,J,P0,H,l?void 0:q.reasoningContent,H0);if(f0)H=f0;if(X0&&W?.goalLifecycle){let I=await W.goalLifecycle.finalizeCompletion();M0=!1,b=!0,yield{kind:"goal_updated",goal:I}}if(n)yield n.event;return{success:!0,finalMessage:P0,metadata:{turnsCount:X,toolCallsCount:Q.length,duration:Date.now()-K,tokensUsed:u,toolSuccessRate:Q.length>0?Q.filter((I)=>I.success).length/Q.length:void 0,totalToolFailures:A.totalFailures||void 0,...S(),...b?{goalCompletionVerified:!0,goalVerificationVerdict:"pass",...k0?{goalVerifierSessionId:k0}:{},...v0?{goalVerificationEvidenceSha256:v0}:{}}:{},...h6?{outputTruncated:!0}:{},...n?.resultMetadata}}}if(q.finishReason!=="length")o0=0;G.appendAssistant({role:"assistant",content:q.content||"",reasoningContent:q.reasoningContent,tool_calls:q.toolCalls});{let U=await C0($,J,q.content||"",H,q.reasoningContent);if(U)H=U}if(W?.signal?.aborted)return z(X,Q.length,W.signal);let k1=q.toolCalls.filter((U)=>U.type==="function"),EZ;if(e0?.hasTools()){i.debug(`[Loop] 使用 StreamingToolExecutor 收集 ${k1.length} 个工具结果`);let U=e0;for(let D of U.getQueuedToolCalls()){let _=B.get(D.function.name)?.kind;yield{kind:"tool_start",toolCall:D,toolKind:_}}EZ=(async()=>{let D=[];for await(let y of U.getRemainingResults())D.push(y);return D})()}else{let U=new Map,D=new D1;for(let f of k1){let P=D.admit();if(P){U.set(f.id,P);continue}let m=U1(f.function.arguments),x=m===null?void 0:p6(f.function.name,m);if(x){U.set(f.id,x);continue}let O0=B.get(f.function.name)?.kind;yield{kind:"tool_start",toolCall:f,toolKind:O0}}let y=Promise.resolve(),_=(f,P,m)=>{let x=y.then(()=>pZ($,J,f,P,H,{required:$.executionEngine!==void 0,providerToolCallId:m}));return y=x.then(()=>{return},()=>{return}),x},c=async(f)=>{let P=null;try{let m=U.get(f.id);if(m)return{toolCall:f,result:m,toolUseUuid:null};let x=U1(f.function.arguments);if(x===null)return{toolCall:f,result:{success:!1,llmContent:"",error:{type:"validation_error",message:`Invalid JSON object in tool arguments. Raw: ${f.function.arguments.slice(0,200)}`},metadata:void 0},toolUseUuid:null};w1(f.function.name,x);try{P=await _(f.function.name,x,f.id)}catch(h){return{toolCall:f,result:{success:!1,llmContent:j$,error:{type:"execution_error",message:j$},metadata:{durableToolUseFailed:!0,summary:"Blocked tool before execution"}},toolUseUuid:null,error:h instanceof Error?h:Error(String(h))}}if(f.function.name==="ExitWorktree"&&w0.has("EnterWorktree")&&!w0.has("ExitWorktree")&&hZ(GZ,UZ,0).action!=="none"){let h="Run the requested verification before ExitWorktree. The worktree remains active so Bash can run in isolation.";return{toolCall:f,result:{success:!1,llmContent:h,error:{type:"validation_error",message:h},metadata:{summary:"Blocked ExitWorktree until verification succeeds"}},toolUseUuid:P}}let O0=await m6(f.function.name,x,{sessionId:J.sessionId,turnId:W?.turnFinalization?.turnId,taskListId:J.taskListId,goalTaskListId:J.goalTaskListId,userId:J.userId||"default",modelId:$.config.currentModelId,providerAdmissionOwnerId:yZ,workspaceRoot:J.workspaceRoot||j0(),executionRoot:J.executionRoot??J.workspaceRoot??j0(),workspaceKind:J.workspaceKind??"local",environment:$.config.env,worktreeIsolationRequired:A1,worktreeActive:w0.has("EnterWorktree")&&!w0.has("ExitWorktree"),subagentType:J.subagentInfo?.subagentType,signal:W?.signal,confirmationHandler:J.sessionId&&J.workspaceKind!=="acp-remote"?G0.createConfirmationHandler(J.confirmationHandler,{sessionId:J.sessionId,projectPath:J.workspaceRoot||j0(),toolCallId:P??f.id,toolName:f.function.name}):J.confirmationHandler,permissionMode:J.permissionMode,toolRegistry:B,deferredToolManager:B.deferredToolManager,onProgress:(h)=>{X$.push({toolCall:f,update:{message:h.slice(0,1000)}})},onProgressUpdate:(h)=>{X$.push({toolCall:f,update:h})}});return{toolCall:f,result:O0,toolUseUuid:P}}catch(m){return i.error(`Tool execution failed for ${f.function.name}:`,m),{toolCall:f,result:{success:!1,llmContent:"",error:{type:"execution_error",message:m instanceof Error?m.message:"Unknown error"},metadata:void 0},toolUseUuid:P,error:m instanceof Error?m:Error("Unknown error")}}};EZ=Promise.all(k1.map(c))}let x1,n6,o6=!1,SZ=!1,f8=EZ.then((U)=>{x1=U},(U)=>{o6=!0,n6=U}).finally(()=>{SZ=!0,X$.close()});while(!SZ||X$.hasPending){let U=X$.shift()??(SZ?void 0:await X$.next());if(U)yield{kind:"tool_progress",toolCall:U.toolCall,update:U.update}}if(await f8,o6)throw n6;if(!x1)throw Error("Tool execution completed without results");let E8=new J6;for(let{toolCall:U,result:D,toolUseUuid:y}of x1){let _=U;if(Q.push(D),_.function.name===S1)L$=void 0;if(D.metadata?.abortedBeforeLaunch){let b=D.error?.message??"任务已被用户中止";if(y)try{let X0=await g1($,J,y,_.function.name,null,y,b,void 0,void 0,{required:$.executionEngine!==void 0});if(X0)H=X0}catch{return j8(X,Q.length,K)}return G.appendToolResult({role:"tool",tool_call_id:_.id,name:_.function.name,content:`Error: ${b}`}),z(X,Q.length,W?.signal)}{let b=D.metadata&&typeof D.metadata==="object"?D.metadata:void 0,n=((H0)=>H0==="running"||H0==="completed"||H0==="failed"||H0==="cancelled")(b?.subagentStatus)?b.subagentStatus:"completed",P0=b?.verificationVerdict==="pass"||b?.verificationVerdict==="fail"||b?.verificationVerdict==="partial"?b.verificationVerdict:void 0,l=b&&typeof b.subagentSessionId==="string"?{subagentSessionId:b.subagentSessionId,subagentType:typeof b.subagentType==="string"?b.subagentType:_.function.name,subagentDescription:typeof b.description==="string"?b.description:void 0,subagentStatus:n,subagentSummary:typeof b.subagentSummary==="string"?b.subagentSummary:void 0,subagentResumedFrom:typeof b.subagentResumedFrom==="string"?b.subagentResumedFrom:void 0,subagentRootId:typeof b.subagentRootId==="string"?b.subagentRootId:void 0,subagentResumeDepth:typeof b.subagentResumeDepth==="number"?b.subagentResumeDepth:void 0,verificationVerdict:P0}:void 0,N=b?(()=>{let{oldContent:H0,newContent:f0,...I}=b;return u$(I)})():void 0;if(b?.durableToolUseFailed!==!0&&(y!==null||$.executionEngine===void 0))try{let H0=await g1($,J,y??_.id,_.function.name,D.success?u$(D.llmContent):null,y,D.success?void 0:D.error?.message,l,N,{required:$.executionEngine!==void 0});if(H0)H=H0}catch{return j8(X,Q.length,K)}}yield{kind:"tool_result",toolCall:_,result:D};let c=await y6(_,D,$,J);if(c){if(yield c,!J.taskListId&&W?.goalLifecycle?.refreshFrontier){let b=await W.goalLifecycle.refreshFrontier();if(b?.ok)yield{kind:"goal_frontier_updated",goal:b.goal,frontier:b.frontier,tasks:b.tasks};else if(b){if(b.goal)yield{kind:"goal_updated",goal:b.goal};return{success:!1,error:{type:"goal_frontier_unavailable",message:b.error.message},metadata:{turnsCount:X,toolCallsCount:Q.length,duration:Date.now()-K,tokensUsed:u}}}}}let f,P=D.metadata&&typeof D.metadata==="object"?D.metadata:void 0,m=_.function.name==="Task"&&P?{subagentSessionId:P.subagentSessionId,subagentType:P.subagentType,subagentStatus:P.subagentStatus,subagentSummary:P.subagentSummary,subagentResumedFrom:P.subagentResumedFrom,subagentRootId:P.subagentRootId,subagentResumeDepth:P.subagentResumeDepth,verificationVerdict:P.verificationVerdict,verificationFeedback:P.verificationFeedback}:void 0;if(D.success){if(p2(A,_.function.name),P?.goalCompletionRequested===!0){if(!W?.goalLifecycle)throw Error("Goal completion candidate has no host lifecycle authority");M0=!0;let l=typeof P.goalCompletionAttempt==="number"?P.goalCompletionAttempt:void 0,N=typeof P.goalCompletionRequestedAt==="string"?P.goalCompletionRequestedAt:void 0,U0=typeof P.goalId==="string"?P.goalId:void 0;if(o2({goalId:l$,attempt:O1,requestedAt:wZ},{goalId:U0,attempt:l,requestedAt:N}))L1=0,c$=-1,_0=void 0,k0=void 0,F$=void 0,N1=void 0,v0=void 0,d0=void 0;O1=l??O1,wZ=N??wZ,l$=U0??l$,P1=typeof P.goalObjective==="string"?P.goalObjective:P1;let f0=await W?.goalLifecycle?.getSnapshot();if(f0)i$=f0.verificationStall?.consecutiveCount,yield{kind:"goal_updated",goal:f0}}else if(_.function.name==="UpdateGoal"&&P?.goalStatus==="blocked"){M0=!1,m0=!1,d$=!1,F1=!1,_0=void 0,c$=-1,k0=void 0,F$=void 0,N1=void 0,i$=void 0,v0=void 0,d0=void 0;let l=await W?.goalLifecycle?.getSnapshot();if(l)yield{kind:"goal_updated",goal:l}}let b=J8(o$,_.function.name,D,J.workspaceRoot);if(b.length>0){if(Q0=void 0,a0=!1,c0=0,O$++,n$=-1,s0=void 0,G1=0,M0){L1=0,await a$("Goal completion evidence invalidated by a workspace mutation");let l=await W?.goalLifecycle?.getSnapshot();if(l)i$=l.verificationStall?.consecutiveCount,yield{kind:"goal_updated",goal:l}}if(W?.goalLifecycle?.clearFrontierStall){let l=await W.goalLifecycle.clearFrontierStall();if(l)yield{kind:"goal_updated",goal:l}}}let X0=typeof P?.subagentType==="string"?P.subagentType:typeof P?.subagent_type==="string"?P.subagent_type:void 0,n=X0===n0,P0=_.function.name==="Task"&&P?.verificationAgentBuiltin===!0&&(X0===Y$||n)&&(P?.subagentStatus==="completed"||P?.status==="completed");if(P0){if(s0=(P?.verificationVerdict==="pass"||P?.verificationVerdict==="fail"||P?.verificationVerdict==="partial"?P.verificationVerdict:void 0)??$8(typeof D.llmContent==="string"?D.llmContent:P?.subagentSummary&&typeof P.subagentSummary==="string"?P.subagentSummary:void 0),n$=O$,F1&&n){F1=!1,_0=s0,c$=O$,k0=typeof P?.subagentSessionId==="string"?P.subagentSessionId:void 0;let N=typeof D.llmContent==="string"?D.llmContent.slice(0,4000):typeof P?.subagentSummary==="string"?P.subagentSummary:void 0,U0=typeof P?.verificationFeedback==="string"&&P.verificationFeedback.trim()?P.verificationFeedback.trim():void 0;if(F$=_0?U0??`Independent verifier returned ${_0.toUpperCase()}.`:void 0,N1=_0!=="pass"&&U0?R6("sha256").update(U0,"utf8").digest("hex"):void 0,_0&&W?.goalLifecycle){let H0=JSON.stringify({goalId:l$,objective:P1,mutationRevision:O$,verdict:_0,verifierSessionId:k0,evidence:N});v0=R6("sha256").update(H0).digest("hex");let f0=await W.goalLifecycle.recordVerification({verdict:_0,verifierSessionId:k0,summary:F$,evidenceSha256:v0,feedbackSha256:N1});d0=f0,i$=f0.verificationStall?.consecutiveCount,yield{kind:"goal_updated",goal:f0}}}}if(b.length>0||P0)f={...b.length>0?{modifiedFiles:b}:{},...P0?{verificationAttempted:!0,verificationAgentBuiltin:!0,...s0?{verificationVerdict:s0}:{}}:{}};if(_.function.name==="EnterWorktree"&&D.metadata?.workspaceTransition==="enter")w0.add("EnterWorktree"),w0.delete("ExitWorktree");else if(_.function.name==="ExitWorktree"&&D.metadata?.workspaceTransition==="exit"&&w0.has("EnterWorktree"))w0.add("ExitWorktree");else if(!["EnterWorktree","ExitWorktree"].includes(_.function.name))w0.add(_.function.name);if(_.function.name==="Task"&&D.metadata?.isolation==="worktree")w0.add("TaskWorktree");HJ(UZ,_.function.name,D,J.workspaceRoot)}else u2(A,_.function.name);Y2(E,_.function.name,D);let x=D.success?D.llmContent||"":S5(_.function.name,D.error);if(!D.success){let b=m2(A,_.function.name);if(b&&typeof x==="string")x=`${x}
|
|
176
176
|
|
|
177
|
-
${b}`}if(typeof x==="object"&&x!==null)x=JSON.stringify(x,null,2);if(typeof x==="string")x=Z2(x,_.function.name,{messageBudget:E8});let y0=typeof x==="string"?x:JSON.stringify(x);if(G.appendToolResult({role:"tool",tool_call_id:_.id,name:_.function.name,content:w8(D,y0),..._.function.name==="Task"||f?{metadata:u$({toolCallId:_.id,toolName:_.function.name,error:D.success?null:D.error?.message??null,...
|
|
177
|
+
${b}`}if(typeof x==="object"&&x!==null)x=JSON.stringify(x,null,2);if(typeof x==="string")x=Z2(x,_.function.name,{messageBudget:E8});let y0=typeof x==="string"?x:JSON.stringify(x);if(G.appendToolResult({role:"tool",tool_call_id:_.id,name:_.function.name,content:w8(D,y0),..._.function.name==="Task"||f?{metadata:u$({toolCallId:_.id,toolName:_.function.name,error:D.success?null:D.error?.message??null,...m?{metadata:m}:{},...f?{independentVerification:f}:{}})}:{}}),P?.durableToolUseFailed===!0)return{success:!1,error:{type:"tool_persistence_failed",message:j$,details:D.error},metadata:{turnsCount:X,toolCallsCount:Q.length,duration:Date.now()-K}};let O0=U1(_.function.arguments)??{},h=u6(_.function.name,O0,D);if(h&&h.files.length>0){for(let n of h.references)a.add(n.id);let b={role:"system",content:h.content,metadata:u$({contextualProjectRules:!0,ruleReferences:h.references,triggerPaths:h.triggerPaths})};G.appendContextualProjectInstructions(b);let X0=await OJ($,J,h.references,h.triggerPaths,H);if(X0)H=X0;yield{kind:"project_rules_loaded",files:h.files.map((n)=>({id:n.id,relativePath:n.relativePath,source:n.source,conditional:n.conditional,contentSha256:n.contentSha256})),triggerPaths:h.triggerPaths,blockedWrite:D.metadata?.contextualProjectRulesRequired===!0}}if(_.function.name===u0&&D.metadata?.structuredOutputRetryExhausted===!0)return{success:!1,error:{type:"structured_output_failed",message:D.error?.message??"Structured output validation retry budget was exhausted."},metadata:{turnsCount:X,toolCallsCount:Q.length,duration:Date.now()-K,tokensUsed:u,structuredOutputSchemaDigest:w?.schemaDigest}};if(W?.signal?.aborted)return z(X,Q.length,W.signal);if(D.metadata?.shouldExitLoop){let b=typeof D.llmContent==="string"?D.llmContent:"循环已退出";return{success:D.success,finalMessage:b,metadata:{turnsCount:X,toolCallsCount:Q.length,duration:Date.now()-K,shouldExitLoop:!0,targetMode:D.metadata?.targetMode,planContent:typeof D.metadata?.planContent==="string"?D.metadata.planContent:void 0}}}}let Q$=G6(p,k1,x1.map(({result:U})=>U));if(Q$){if(yield{kind:"action_stationarity",...Q$},Q$.phase==="halted")return{success:!1,error:{type:"loop_detected",message:`Stopped after ${Q$.runLength} repeated ${Q$.toolName} calls without observable progress.`},metadata:{turnsCount:X,toolCallsCount:Q.length,duration:Date.now()-K,tokensUsed:u}};if(Q$.phase==="detected"){let U={role:"user",content:`
|
|
178
178
|
|
|
179
179
|
<system-reminder>
|
|
180
180
|
${v2(Q$)}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{e as U3,f as H3,g as R3,h as s0,i as q3}from"./chunk-
|
|
1
|
+
import{e as U3,f as H3,g as R3,h as s0,i as q3}from"./chunk-6egxkwda.js";import{j as o1}from"./chunk-zj1g4nbq.js";import{v as a0,w as y2}from"./chunk-3mf0w32c.js";import{A as m0,x as g2,y as p2,z as v2}from"./chunk-fnd2gmeg.js";import{B as C2,C as U$,D as H$,E as F$,F as z0,G as N$}from"./chunk-msgzv7x3.js";import{$ as I2,Ea as u3,J as B2,K as u1,L as v3,O as D2,P as e0,Q as d4,R as i1,S as g$,T as A4,U as j4,V as K0,W as L2,X as M2,Y as D$,Z as w1,aa as R2,ba as b4,ca as j0,da as H0,ga as q1,ha as E1,ia as O5,ja as q2,ka as E2,la as r2,ma as e2,na as O3,oa as $3,pa as Q3,qa as Z3,ra as J3,sa as Y3,ta as X3,wa as w3,za as W5}from"./chunk-61hfyn3e.js";import{La as q$,Ra as uO}from"./chunk-7s5p5j3y.js";import{Ua as A2,Wa as j2,Xa as b2,Ya as T2,cb as V4,fb as c3,gb as c4,hb as S2,ib as f2,jb as i3,kb as l3,lb as i4,mb as a3,nb as g0,ob as N3,pb as B3,qb as D3,rb as P2,sb as k2,tb as m2,ub as h2,vb as W$,wb as r4}from"./chunk-30x3mcsb.js";import{Kb as dO,Lb as a,Nb as P,Ob as x2,Zb as M4,hc as y0}from"./chunk-egmdn632.js";import{sc as T4}from"./chunk-zzvs471p.js";import{$c as W2,$d as D4,Cd as w2,Ic as V2,Md as A1,Nd as h0,Sc as z2,Ud as I1,Vd as I4,Wd as R1,Yd as o0,Zc as G2,_c as B4,ad as D1,bd as K2,ed as U4,ee as N2,fe as x4,ge as L4,he as g,rd as _2}from"./chunk-5pk8ym5x.js";import{Fe as U2,Me as H2,Ne as F2}from"./chunk-y5wngtz0.js";import{gf as L3,kf as M3,lf as A3,mf as j3,nf as b3,of as y4,pf as T3,qf as I3}from"./chunk-w33zjw8m.js";import{Pf as r3,Tf as MO,Xf as f$,cg as nO}from"./chunk-25sph3tg.js";import{dg as c1}from"./chunk-t0gm0pn1.js";import{wg as J2}from"./chunk-50vwafn5.js";import{yg as B1}from"./chunk-0rqme7wf.js";import{Hg as e3,Lg as s2,Pg as H1,Qg as F1,Ug as B5,Xg as eO,Yg as N1,_g as X2,ah as s4}from"./chunk-wkcy0was.js";import{th as P$,uh as Y2}from"./chunk-vbjgcn49.js";import{yh as b$,zh as l0}from"./chunk-rrjxnjkq.js";import{Mi as T$,Rh as R$,Ri as U1,fi as s$,ii as r$,ki as e$,li as O2,mi as h$,ni as y$,oi as K$,ui as $2,xi as Q2,zi as Z2}from"./chunk-89865f6k.js";import{Ui as F4}from"./chunk-kv458q06.js";import{Wi as a1,Zi as N4}from"./chunk-5v0jcyea.js";import{bj as GO}from"./chunk-2f8d0km4.js";import{Dj as ZO,Fj as y,Hj as G,Ij as oO,Kj as zO}from"./chunk-2mk914vk.js";import{Pj as f0}from"./chunk-j8hbddjp.js";import{Rj as C$,Sj as o$,Uj as S$,Vj as t$}from"./chunk-4cdk4mds.js";import{Xj as i0}from"./chunk-19t17t01.js";import{ck as t4}from"./chunk-rvs364rz.js";import{Bk as g1,Jk as L$,fk as l1,zk as wO}from"./chunk-4wx5sya5.js";import{Mk as a4}from"./chunk-eg3ms291.js";var H8={port:{type:"number",describe:"Port to listen on (0 for auto)",default:0},hostname:{type:"string",describe:"Hostname to listen on",default:"127.0.0.1"},cors:{type:"array",describe:"Additional domains to allow for CORS",default:[]}};function F8(O){return{port:O.port??0,hostname:O.hostname??"127.0.0.1",cors:O.cors??[]}}import{existsSync as e4,readFileSync as f1}from"node:fs";import{createServer as c6}from"node:http";import{networkInterfaces as i6}from"node:os";import{dirname as l6,extname as a6,join as E0}from"node:path";import{fileURLToPath as n6}from"node:url";import{brotliCompressSync as o6,gzipSync as t6,constants as s6}from"node:zlib";import{Hono as r6}from"hono";import{cors as e6}from"hono/cors";import{WebSocketServer as O8}from"ws";var c0=ZO("Service"),f5=30000,P5=new Set(["completed","failed","cancelled","interrupted"]);class z4{dispatch;store;tickMs;timer;unsubscribeBus;ticking=!1;inFlight=new Set;constructor(O){this.dispatch=O.dispatch,this.store=O.store??W$.getInstance(),this.tickMs=O.tickMs??f5}start(){if(this.timer)return;c0.info("[TaskScheduler] Starting scheduler tick loop"),this.timer=setInterval(()=>{this.tick()},this.tickMs),this.timer.unref?.(),this.unsubscribeBus=P.subscribe((O)=>{if(O.type!=="task.status")return;let $=O.properties.taskStatus;if(typeof $!=="string"||!P5.has($))return;this.recordTerminalStatus(O.sessionId,$,typeof O.properties.taskStatusReason==="string"?O.properties.taskStatusReason:void 0)}),this.tick()}stop(){if(this.timer)clearInterval(this.timer),this.timer=void 0,this.unsubscribeBus?.(),this.unsubscribeBus=void 0,c0.info("[TaskScheduler] Stopped scheduler tick loop")}async tick(O=new Date){if(this.ticking)return;this.ticking=!0;try{let $=await this.store.list();for(let Q of $)await this.evaluate(Q,O)}catch($){c0.warn("[TaskScheduler] Tick failed:",$)}finally{this.ticking=!1}}async evaluate(O,$){if(!O.enabled)return;if(this.inFlight.has(O.id))return;if(O.expiresAt&&new Date(O.expiresAt).getTime()<=$.getTime()){await this.store.update(O.id,{enabled:!1,nextRunAt:null}),c0.info(`[TaskScheduler] Schedule ${O.id} expired; disabled`);return}if(!O.nextRunAt)return;if(!(new Date(O.nextRunAt).getTime()<=$.getTime()))return;await this.fire(O,$)}async fire(O,$=new Date,Q={}){if(this.inFlight.has(O.id))throw Error(`Schedule ${O.id} is already dispatching`);this.inFlight.add(O.id);let Z=$.toISOString();try{let J=await this.dispatch({prompt:O.prompt,title:O.title??k5(O),sourceProjectPath:O.projectPath,isolation:O.dispatch.isolation??"worktree",permissionMode:O.dispatch.permissionMode??"default",modelId:O.dispatch.modelId,reasoningEffort:O.dispatch.reasoningEffort,serviceTier:O.dispatch.serviceTier,responseVerbosity:O.dispatch.responseVerbosity,communicationStyle:O.dispatch.communicationStyle}),X=O.trigger.kind==="once"?null:Q.manual?O.nextRunAt?new Date(O.nextRunAt):null:V4(O.trigger,$,$);await this.store.update(O.id,{lastRunAt:Z,lastRunSessionId:J.session.sessionId,lastStatus:J.status,lastError:void 0,runCount:O.runCount+1,nextRunAt:X?X.toISOString():null,enabled:O.trigger.kind==="once"?!1:O.enabled}),P.publish({sessionId:J.session.sessionId,projectPath:O.projectPath},"schedule.fired",{scheduleId:O.id,firedAt:Z,sessionId:J.session.sessionId,runId:J.runId,status:J.status}),c0.info(`[TaskScheduler] Fired schedule ${O.id} -> session ${J.session.sessionId} (${J.status})`)}catch(J){let X=J instanceof Error?J.message:String(J);c0.warn(`[TaskScheduler] Schedule ${O.id} dispatch failed:`,J);let V=O.trigger.kind==="once"?null:Q.manual?O.nextRunAt?new Date(O.nextRunAt):null:V4(O.trigger,$,$);await this.store.update(O.id,{lastRunAt:Z,lastStatus:"error",lastError:X,nextRunAt:V?V.toISOString():null,enabled:O.trigger.kind==="once"?!1:O.enabled})}finally{this.inFlight.delete(O.id)}}async recordTerminalStatus(O,$,Q){let J=(await this.store.list()).find((X)=>X.lastRunSessionId===O);if(!J)return;await this.store.update(J.id,{lastStatus:$,...Q?{lastError:Q}:{lastError:void 0}})}}function k5(O){return`Scheduled: ${O.prompt.trim().replace(/\s+/g," ").slice(0,60)}`}class _O extends Error{code;statusCode;details;constructor(O,$,Q=500,Z){super($);this.code=O;this.statusCode=Q;this.details=Z;this.name="BladeServerError"}toObject(){return{error:{code:this.code,message:this.message,...this.details?{details:this.details}:{}}}}}class i extends _O{constructor(O,$){super("NOT_FOUND",$?`${O} not found: ${$}`:`${O} not found`,404)}}class F extends _O{constructor(O){super("BAD_REQUEST",O,400)}}class v extends _O{constructor(O){super("CONFLICT",O,409)}}class rO extends _O{constructor(O,$){super("TOO_MANY_REQUESTS",O,429,$)}}class LO extends _O{constructor(O="Server is shutting down"){super("SERVICE_UNAVAILABLE",O,503)}}class A0 extends _O{constructor(O){super("SESSION_WORKSPACE_UNAVAILABLE","This session workspace is no longer available",409,{reason:O})}}class vO extends _O{constructor(){super("AMBIGUOUS_SESSION","Multiple workspaces contain this session ID; projectPath is required",409)}}class VO extends _O{constructor(O="Internal server error"){super("INTERNAL_ERROR",O,500)}}var j8=G.Object({error:G.Object({code:G.String(),message:G.String(),details:G.Optional(G.Record(G.String(),G.Unknown()))})});import{Hono as m5}from"hono";var G4=ZO("Service"),h5=G.Object({updates:G.Record(G.String(),G.Any()),options:G.Optional(G.Object({scope:G.Optional(zO(["local","project","global"])),immediate:G.Optional(G.Boolean())}))});function y5(O){return{currentModelId:O.currentModelId,permissionMode:O.permissionMode,language:O.language,codeTheme:O.codeTheme,uiTheme:O.uiTheme,autoSaveSessions:O.autoSaveSessions,notifyBuild:O.notifyBuild,notifyErrors:O.notifyErrors,notifySounds:O.notifySounds,privacyTelemetry:O.privacyTelemetry,privacyCrash:O.privacyCrash,agentTeamsEnabled:O.agentTeamsEnabled===!0,communicationStyle:O.communicationStyle,maxConcurrentTasks:O.maxConcurrentTasks,maxQueuedTasks:O.maxQueuedTasks,maxQueuedTaskBytes:O.maxQueuedTaskBytes,maxResidentSessionRuntimes:O.maxResidentSessionRuntimes,sessionRuntimeIdleMs:O.sessionRuntimeIdleMs,maxResidentSessionProjections:O.maxResidentSessionProjections,sessionProjectionIdleMs:O.sessionProjectionIdleMs}}var _$=()=>{let O=new m5;return O.get("/",async($)=>{try{let Q=MO();return $.json(Q?y5(Q):{})}catch(Q){return G4.error("[ConfigRoutes] Failed to get config:",Q),$.json({})}}),O.put("/",async($)=>{try{let Q=await $.req.json(),Z=y(h5,Q);if(!Z.success)throw new F("Invalid config update format");let{updates:J,options:X}=Z.data;return await nO().updateConfig(J,X),$.json({success:!0,updates:J})}catch(Q){if(Q instanceof K$)throw new F(Q.message);throw G4.error("[ConfigRoutes] Failed to update config:",Q),Q}}),O.get("/permissions",async($)=>{try{let Q=MO();return $.json(Q?.permissions||{})}catch(Q){return G4.error("[ConfigRoutes] Failed to get permissions:",Q),$.json({})}}),O};import{Hono as g5}from"hono";import{streamSSE as p5}from"hono/streaming";function w$(O){let $="";if(O.id!==void 0)$+=`id: ${O.id}
|
|
2
2
|
`;if(O.event!==void 0)$+=`event: ${O.event}
|
|
3
3
|
`;for(let Q of O.data.split(/\r\n|\r|\n/))$+=`data: ${Q}
|
|
4
4
|
`;if(O.retry!==void 0)$+=`retry: ${O.retry}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{ea as p}from"./chunk-
|
|
1
|
+
import{ea as p}from"./chunk-61hfyn3e.js";import{Pb as _}from"./chunk-egmdn632.js";import{Ad as U,Bd as I,Cd as A,Dd as z,Od as q,he as O,zd as N}from"./chunk-5pk8ym5x.js";import{te as o}from"./chunk-y5wngtz0.js";import{dg as P}from"./chunk-t0gm0pn1.js";import{Eg as e}from"./chunk-wkcy0was.js";import{Ck as j}from"./chunk-4wx5sya5.js";import{createHash as ff}from"node:crypto";var af=4,cf=1000,E=4000,wf=120000,M=0.2;function $f(a){try{return q(a)&&a.retryable}catch{return!1}}function gf(a,c){let f=Number.isSafeInteger(c)&&c>0?c:1,w=f-1,h=Math.min(cf*2**w,E),$=ff("sha256").update(`${a}\x00${f}`).digest().readUInt32BE(0)/4294967295,k=1-M+2*M*$;return Math.min(E,Math.max(0,Math.round(h*k)))}function Tf(a){let c=gf(a.sessionIdentity,a.failedAttempt),f=a.evidence,w=a.workStillPending===!0&&f!==void 0&&$f(f.taskFailure)&&f.outputStarted===!1&&f.toolExecutionStarted===!1&&Number.isInteger(f.toolCallsCount)&&f.toolCallsCount===0,h=Number.isSafeInteger(a.failedAttempt)&&a.failedAttempt>0&&a.failedAttempt<af,g=a.now??Date.now(),$=g-a.recoveryStartedAt,k=Number.isFinite(g)&&Number.isFinite(a.recoveryStartedAt)&&Number.isFinite($)&&$>=0&&$+c<=wf;return{phase:w?h&&k?"retry_scheduled":"exhausted":"failed",delayMs:c,retryable:w,withinAttemptBudget:h,withinTimeBudget:k}}import R from"node:path";import{nanoid as Lf}from"nanoid";import{execFile as hf}from"node:child_process";import{createHash as xf}from"node:crypto";import{lstat as bf,readFile as mf,realpath as i}from"node:fs/promises";import n from"node:path";import{promisify as kf}from"node:util";var lf=kf(hf),T=8388608,s=500,u=200;async function C(a,c){try{return(await lf("git",["-c","core.pager=cat",...c],{cwd:a,encoding:"utf8",timeout:30000,maxBuffer:T+1024,env:{...process.env,GIT_CONFIG_NOSYSTEM:"1",GIT_PAGER:"cat",GIT_OPTIONAL_LOCKS:"0"}})).stdout}catch(f){let w=f instanceof Error&&f.message.includes("maxBuffer")?`Review target exceeds the ${T} byte limit`:f instanceof Error?f.message:String(f);throw Error(`Git review target failed: ${w}`)}}function d(a,c){let f=a?.trim();if(!f||f.length>u||f.includes("\x00")||f.includes(`
|
|
2
2
|
`)||f.includes("\r"))throw Error(`${c} must contain 1-${u} characters`);return f}function Q(a){return a.split("\x00").filter(Boolean)}async function X(a,c){return(await C(a,["rev-parse","--verify",`${c}^{commit}`])).trim()}async function Ff(a,c,f,w,h){let g=h,$=await i(a);for(let k of c){let l=n.resolve($,k),x=n.relative($,l);if(!x||x.startsWith("..")||n.isAbsolute(x))throw Error(`Untracked review path escapes the workspace: ${k}`);let b=await bf(l);if(!b.isFile()||b.isSymbolicLink())throw Error(`Untracked review target must be a regular file: ${k}`);if(g+=b.size,g>T)throw Error(`Review target exceeds ${T} bytes`);f.update("\x00untracked\x00"),f.update(x.replaceAll(n.sep,"/")),f.update("\x00");let F=await mf(l);f.update(F);let m=Math.max(1,F.toString("utf8").split(`
|
|
3
3
|
`).length);w.set(x.replaceAll(n.sep,"/"),[{start:1,end:m}])}}function Y(a,c){let f=new Map,w,h,g,$,k=!1,l=(x,b)=>{let F=f.get(x)??[],m=F.at(-1);if(m&&b<=m.end+1)m.end=Math.max(m.end,b);else F.push({start:b,end:b});f.set(x,F)};for(let x of a.split(`
|
|
4
4
|
`)){if(x.startsWith("--- ")){let b=x.slice(4).split("\t")[0]?.trim();w=b&&b!=="/dev/null"?b.replace(/^a\//,"").replaceAll("\\","/"):void 0;continue}if(x.startsWith("+++ ")){let b=x.slice(4).split("\t")[0]?.trim();k=b==="/dev/null",h=k?w:b?b.replace(/^b\//,"").replaceAll("\\","/"):void 0,g=void 0,$=void 0;continue}if(x.startsWith("@@ ")){let b=/-(\d+)(?:,\d+)? \+(\d+)(?:,\d+)?/.exec(x);g=b?Math.max(1,Number(b[1])):void 0,$=b?Math.max(1,Number(b[2])):void 0;continue}if(!h||g===void 0||$===void 0)continue;if(x.startsWith("+")&&!x.startsWith("+++"))l(h,$),$++;else if(x.startsWith("-")&&!x.startsWith("---"))l(h,k?g:$),g++;else if(!x.startsWith("\\"))g++,$++}for(let x of c)if(!f.has(x))f.set(x,[{start:1,end:1}]);return f}function D(a){if(a.length>s)throw Error(`Review target exceeds the ${s} file limit`)}class K{static async resolve(a,c){let f=await i(a);await C(f,["rev-parse","--is-inside-work-tree"]);let w=await X(f,"HEAD"),h=xf("sha256");h.update(`kind\x00${c.kind}\x00head\x00${w}\x00`);let g="",$=[],k,l,x,b,F=new Map;switch(c.kind){case"uncommitted":{g=await C(f,["diff","--binary","--no-ext-diff","--relative","HEAD","--","."]);let m=Q(await C(f,["diff","--name-only","-z","--relative","HEAD","--","."])),L=Q(await C(f,["ls-files","--others","--exclude-standard","-z","--","."]));if($=[...new Set([...m,...L])].sort(),D($),$.length===0)throw Error("No uncommitted changes to review");h.update(g),F=Y(g,m),await Ff(f,L,h,F,Buffer.byteLength(g)),x="uncommitted changes",b=["Review the uncommitted working tree against HEAD.","Use git status --short, git diff --cached, and git diff, then inspect","every relevant untracked file listed by git status."].join(" ");break}case"base":{let m=d(c.ref,"Base ref");k=await X(f,m);let L=(await C(f,["merge-base",k,w])).trim();if(g=await C(f,["diff","--binary","--no-ext-diff","--relative",`${L}..${w}`,"--","."]),$=Q(await C(f,["diff","--name-only","-z","--relative",`${L}..${w}`,"--","."])),D($),$.length===0)throw Error(`No changes between ${m} and HEAD`);h.update(g),h.update(`\x00merge-base\x00${L}`),F=Y(g,$),x=`changes against ${m}`,b=`Review changes introduced by ${L}..${w}.`;break}case"commit":{let m=d(c.ref,"Commit ref");if(l=await X(f,m),g=await C(f,["show","--format=","--binary","--no-ext-diff","--relative",l,"--","."]),$=Q(await C(f,["diff-tree","--root","--no-commit-id","--name-only","-r","-z",l,"--","."])),D($),$.length===0)throw Error(`Commit has no changes in this workspace: ${m}`);h.update(g),h.update(`\x00commit\x00${l}`),F=Y(g,$),x=`commit ${m}`,b=`Review only the changes introduced by commit ${l}.`;break}}if(Buffer.byteLength(g)>T)throw Error(`Review diff exceeds ${T} bytes`);return{info:{kind:c.kind,label:x,headSha:w,...k?{baseSha:k}:{},...l?{commitSha:l}:{},digest:h.digest("hex"),fileCount:$.length},instruction:b,changedLines:F}}}var Wf=131072,t=50,Z=new Set;function v(a,c){return`${R.resolve(a)}\x00${c}`}function S(a){return`/review ${a.kind}${a.kind==="uncommitted"?"":` ${a.ref?.trim()??""}`}`}function V(a,c,f,w=!1){if(typeof a!=="string")throw Error(`${c} must be a string`);let h=a.trim();if(!w&&!h||h.length>f)throw Error(`${c} exceeds its allowed length`);return h}function Hf(a,c,f){if(!a||typeof a!=="object"||Array.isArray(a))throw Error("Review finding must be an object");let w=a,h=typeof w.line==="number"&&Number.isInteger(w.line)?w.line:void 0,g=w.code_location??(typeof w.file==="string"&&h!==void 0?{path:w.file,line_start:h,line_end:h}:void 0);if(!g||typeof g!=="object"||Array.isArray(g))throw Error("Review finding has no code_location");let $=g,k=V($.path,"Finding path",1000),l=R.posix.normalize(k.replaceAll("\\","/"));if(R.posix.isAbsolute(l)||l===".."||l.startsWith("../"))throw Error("Review finding path must be workspace-relative");let x=R.resolve(c,l),b=R.relative(R.resolve(c),x);if(b.startsWith("..")||R.isAbsolute(b))throw Error("Review finding path escapes the workspace");let F=typeof w.severity==="string"?w.severity.toLowerCase():"",m=F==="critical"?0:F==="high"?1:F==="medium"?2:F==="low"?3:void 0,L=w.priority??m;if(L!==0&&L!==1&&L!==2&&L!==3)throw Error("Review finding priority must be 0-3");let W=w.confidence_score??w.confidence??0.8;if(typeof W!=="number"||!Number.isFinite(W)||W<0||W>1)throw Error("Review finding confidence_score must be between 0 and 1");let{line_start:H,line_end:r}=$;if(!Number.isInteger(H)||!Number.isInteger(r)||H<1||r<H||r-H>=10)throw Error("Review finding line range is invalid");let G=f.changedLines.get(l);if(!G)throw Error("Review finding path is outside the review target");if(!G.some((y)=>H<=y.end&&r>=y.start))throw Error("Review finding line range does not overlap the changed lines");let B=V(w.title??`[P${L}] ${String(w.type??"Review finding").replaceAll("-"," ").replace(/\b\w/g,(y)=>y.toUpperCase())}`,"Finding title",120);if(!B.startsWith(`[P${L}] `))throw Error("Review finding title priority does not match priority");return{title:B,body:V(w.body??w.description,"Finding body",4000),priority:L,confidenceScore:W,codeLocation:{path:l,lineStart:H,lineEnd:r}}}function Rf(a,c,f){if(Buffer.byteLength(a)>Wf)throw Error("Review output exceeds the 128 KiB limit");let w=a.indexOf("{"),h=a.lastIndexOf("}");if(w<0||h<=w)throw Error("Reviewer did not return a JSON object");let g;try{g=JSON.parse(a.slice(w,h+1))}catch{throw Error("Reviewer returned invalid JSON")}if(!g||typeof g!=="object"||Array.isArray(g))throw Error("Reviewer output must be an object");let $=g;if(!Array.isArray($.findings))throw Error("Reviewer output must contain findings");if($.findings.length>t)throw Error(`Reviewer returned more than ${t} findings`);return{overallExplanation:V($.overall_explanation??$.summary,"Review explanation",1e4,!0),findings:$.findings.map((k)=>Hf(k,c,f))}}async function J(a,c){return new o(j(a,c)).readAll()}class rf{static async start(a){let{sessionId:c,projectPath:f,runtime:w,request:h,onEvent:g}=a;if(w.sessionId!==c||R.resolve(w.workspaceRoot)!==R.resolve(f))throw Error("Review runtime does not own the requested Session");if(w.hasTurnOwner())throw Error("Cannot start a review during an active turn");await O.assertSessionWritable(c,f);let $=v(f,c);if(Z.has($))throw Error("Session already has an active review");let k=await J(f,c);if(U(k))throw Error("Session has an interrupted review that must be recovered");let l=h.instructions?.trim();if(l&&l.length>4000)throw Error("Review instructions exceed 4,000 characters");let x=await K.resolve(f,h),b=Lf(16),F=P("review"),m=new Date().toISOString(),L={reviewId:b,reviewerSessionId:F,target:x.info,startedAt:m},W=new _(f);await W.saveReviewStart(c,L),await W.saveMessage(c,"user",S(h),null,{codeReview:{reviewId:b,phase:"started",targetKind:x.info.kind,targetDigest:x.info.digest}}),await O.updateSessionMetadata(c,f,{taskStatus:"running",taskStatusReason:`Reviewing ${x.info.label}`,taskPromptSummary:S(h),taskStartedAt:m,taskCompletedAt:null,taskFailure:null}),Z.add($);let H=this.execute({...a,target:x,reviewId:b,reviewerSessionId:F,instructions:l,store:W,onEvent:g}).finally(()=>{Z.delete($)});return{reviewId:b,completion:H}}static async execute(a){let{sessionId:c,projectPath:f,runtime:w,request:h,signal:g,onEvent:$,target:k,reviewId:l,reviewerSessionId:x,instructions:b,store:F}=a,m;try{let W=[k.instruction,"Bash already starts in the review workspace. Never prefix a command with cd.",`Authoritative target digest: ${k.info.digest}`,`Changed file count: ${k.info.fileCount}`,b?`Additional review instructions:
|