blade-code 0.10.196 → 0.10.198
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-9dwdhka9.js → chunk-0h301azx.js} +1 -1
- package/dist/{chunk-nj35kwht.js → chunk-0hzq6sr3.js} +1 -1
- package/dist/{chunk-hkz1z544.js → chunk-0qfm5awe.js} +312 -312
- package/dist/{chunk-8yvtknsk.js → chunk-25ma8vb3.js} +1 -1
- package/dist/{chunk-xv8h6611.js → chunk-4bfndh72.js} +1 -1
- package/dist/{chunk-mcpkk1ce.js → chunk-6d9d2cyk.js} +1 -1
- package/dist/{chunk-4k8d018f.js → chunk-7m1bf6zd.js} +1 -1
- package/dist/{chunk-fck48bw1.js → chunk-afq14p8m.js} +1 -1
- package/dist/{chunk-267tf0ts.js → chunk-bh3e2gt1.js} +1 -1
- package/dist/chunk-bp1n4k48.js +1 -0
- package/dist/{chunk-8y61xj8b.js → chunk-dzz3mzg1.js} +1 -1
- package/dist/{chunk-zvyh95x9.js → chunk-evq5ke3s.js} +1 -1
- package/dist/{chunk-9sn36cs0.js → chunk-g88adq1a.js} +1 -1
- package/dist/{chunk-dtnd5zkh.js → chunk-hasgf62t.js} +1 -1
- package/dist/{chunk-827nqwm8.js → chunk-hhey2zgy.js} +1 -1
- package/dist/{chunk-f04jgx3j.js → chunk-jscwac0k.js} +1 -1
- package/dist/chunk-ksf9bywt.js +1 -0
- package/dist/{chunk-7vc0j8m6.js → chunk-m7cv44cg.js} +6 -6
- package/dist/{chunk-nh67db73.js → chunk-mrft8qep.js} +1 -1
- package/dist/{chunk-k40zgmnb.js → chunk-n87apqe7.js} +1 -1
- package/dist/{chunk-af78d1nn.js → chunk-p6g53dbp.js} +1 -1
- package/dist/{chunk-ywfa7fhr.js → chunk-pbw10pjv.js} +2 -2
- package/dist/{chunk-hypy2t78.js → chunk-pfjg8bjg.js} +1 -1
- package/dist/{chunk-ajv12d9b.js → chunk-pq9v80gg.js} +1 -1
- package/dist/{chunk-2nzmdf86.js → chunk-pxmskd21.js} +1 -1
- package/dist/{chunk-tcgb56tp.js → chunk-r2ev8kdg.js} +1 -1
- package/dist/{chunk-c54t12bm.js → chunk-s8cx6pzp.js} +1 -1
- package/dist/{chunk-3036tv7v.js → chunk-spsnc7ey.js} +2 -2
- package/dist/{chunk-zyvxts23.js → chunk-sqrhdczm.js} +1 -1
- package/dist/{chunk-b6qsc6jm.js → chunk-v2bcvfch.js} +1 -1
- package/dist/{chunk-zme6ydm6.js → chunk-vd58pp9k.js} +1 -1
- package/dist/{chunk-w50pdxnm.js → chunk-vnbyb9dq.js} +1 -1
- package/dist/chunk-vw2be560.js +6 -0
- package/dist/{chunk-byat3xec.js → chunk-w2xgdqvw.js} +1 -1
- package/dist/{chunk-bfv4rp3j.js → chunk-wernns90.js} +1 -1
- package/dist/{chunk-kvst0ysv.js → chunk-x5f2d1n2.js} +1 -1
- package/dist/{chunk-bc3nsr8k.js → chunk-yc59atrw.js} +1 -1
- package/dist/{chunk-m4zazwzr.js → chunk-zh4w88j6.js} +1 -1
- package/dist/web/assets/{ChatView-DYA3np_l.js → ChatView-BF6HUrBw.js} +4 -4
- package/dist/web/assets/{CodeBlockHighlighter-B9sgXWAy.js → CodeBlockHighlighter-C4CgCiRf.js} +1 -1
- package/dist/web/assets/{FilePreview-PKalr8bi.js → FilePreview-BS4PgFKb.js} +1 -1
- package/dist/web/assets/{KanbanBoard-GjH7MyZk.js → KanbanBoard-DDXB-yq1.js} +1 -1
- package/dist/web/assets/{MarkdownRenderer-C03DrI8Q.js → MarkdownRenderer-DS7RznBE.js} +3 -3
- package/dist/web/assets/{ScrollArea-CbOr9e7X.js → ScrollArea-BM9NzGZM.js} +1 -1
- package/dist/web/assets/{SessionHistorySurface-BZEOUN2M.js → SessionHistorySurface-DnRySeLE.js} +1 -1
- package/dist/web/assets/{SettingsModal-DAMGwO-E.js → SettingsModal-D5YLUtIo.js} +1 -1
- package/dist/web/assets/{Sidebar-CiCsK7EK.js → Sidebar-BZC6OkDJ.js} +1 -1
- package/dist/web/assets/{TaskSwitcher-BLdgv--U.js → TaskSwitcher-WewOkw5m.js} +1 -1
- package/dist/web/assets/{TerminalPanel-uctuzvle.js → TerminalPanel-C5SGdRNr.js} +1 -1
- package/dist/web/assets/{archive-BHntc9gt.js → archive-DkczUU08.js} +1 -1
- package/dist/web/assets/{arrow-left-DkXe02NZ.js → arrow-left-9pBiQwu7.js} +1 -1
- package/dist/web/assets/{calendar-clock-_-EyQ_16.js → calendar-clock-BFnUlxrU.js} +1 -1
- package/dist/web/assets/{chevron-right-DXuaFbE2.js → chevron-right-yCVkAEcj.js} +1 -1
- package/dist/web/assets/{clock-3-DHOWUt-Y.js → clock-3-CcoWoRQs.js} +1 -1
- package/dist/web/assets/{copy-wCV3sjrM.js → copy-HJF0oQBS.js} +1 -1
- package/dist/web/assets/{download-CEXHgQhj.js → download-DSBCIqk3.js} +1 -1
- package/dist/web/assets/{external-link-D5pUXtvQ.js → external-link-zIgEO0KB.js} +1 -1
- package/dist/web/assets/{folder-Bm-uBrFM.js → folder-BdRo64o3.js} +1 -1
- package/dist/web/assets/{index-E1WG_htm.js → index-BVDkKudh.js} +4 -4
- package/dist/web/assets/{message-square-plus-ChP8ZEgZ.js → message-square-plus-3klTXO0S.js} +1 -1
- package/dist/web/assets/{pause-D8MeccMe.js → pause-B9Q5JWvH.js} +1 -1
- package/dist/web/assets/{pencil-DNEy8lVY.js → pencil-CbYIz1b1.js} +1 -1
- package/dist/web/assets/{play-DhdTbY0j.js → play-CZMTj43e.js} +1 -1
- package/dist/web/assets/{plus-B2PxWoNi.js → plus-Cc7I8fhb.js} +1 -1
- package/dist/web/assets/{session-events-aq2qdB3u.js → session-events-NEjosinC.js} +2 -2
- package/dist/web/assets/{settings-D9Kkb31b.js → settings-DSF3exX2.js} +1 -1
- package/dist/web/assets/{team-ktBP7cND.js → team-qfeJHL9s.js} +1 -1
- package/dist/web/assets/{teamService-CxPZcCrA.js → teamService-Bs9qBKI8.js} +1 -1
- package/dist/web/assets/{terminal-DcSGZkEA.js → terminal-DQLqe-Ed.js} +1 -1
- package/dist/web/index.html +1 -1
- package/package.json +1 -1
- package/dist/chunk-2wq1zztd.js +0 -1
- package/dist/chunk-akbsgbww.js +0 -6
- package/dist/chunk-xvx0t011.js +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{xc as G8}from"./chunk-fdr4fcrf.js";import{$d as R6,Ac as U$,Bc as A2,Cc as a1,Ec as j$,Fd as E2,Gd as L8,Hd as F8,Id as V6,Jd as JZ,Kd as O8,Ld as P8,Md as r1,Qd as rJ,Zd as u0,ae as t1,be as M6,ie as X1,ud as b2,wd as y2,xd as f2,yc as q$,yd as w6,zd as U6}from"./chunk-tcgb56tp.js";import{ne as q8}from"./chunk-egss0m1x.js";import{Fe as f0,qe as q0,te as j2,ue as u$}from"./chunk-ztreczac.js";import{eg as p2}from"./chunk-5yyp6njq.js";import{fg as w8,gg as C0,hg as H8,ig as dJ,kg as i1,lg as T6,mg as cJ,ng as lJ,qg as iJ}from"./chunk-myvt7yjm.js";import{ch as K$,dh as n0,gh as U8}from"./chunk-kehgewqh.js";import{lh as a2,ph as Y2}from"./chunk-kkzznz4w.js";import{Ah as R$}from"./chunk-w50pdxnm.js";import{Vi as x$}from"./chunk-qpmvp4q2.js";import{cj as j0}from"./chunk-qdbbke8f.js";import{Ej as S0}from"./chunk-rmfzym94.js";import{Yj as _2}from"./chunk-8yvtknsk.js";import{Ck as FJ,Dk as ZZ,Fk as O2,Kk as P2,Lk as N2,gk as F2,vk as w2,wk as U2,zk as H1}from"./chunk-n52n2w5v.js";import{Nk as lZ}from"./chunk-cjfb4kjp.js";function S$($){return $.role==="system"&&Array.isArray($.content)}function E$($){if($.role!=="system"||!$.metadata||Array.isArray($.metadata))return!1;return typeof $.metadata==="object"&&$.metadata.contextualProjectRules===!0}class C1{systemMessages;_contextualSystemMessages;_history;_pending=[];_contextRevision=0;context;constructor($,Z){this.context=$;let J=$.messages.find(S$);if(this._contextualSystemMessages=$.messages.filter(E$),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)=>!S$(W)&&!E$(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(!E$($))throw Error("Contextual project instructions require safe metadata");this._contextualSystemMessages.push($),this.systemMessages.push($)}syncContextualSystemMessages(){let $=this.systemMessages.filter(S$);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:{},...f0}})}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)=>!S$(Z)&&!E$(Z)),this._contextRevision++}restoreDurableHistory($){this._contextualSystemMessages=$.filter(E$),this._history=$.filter((Z)=>!S$(Z)&&!E$(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 e6($){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 $J($){return{budget:$.budget,usage:0,consecutiveContinuations:0,lastOutputDelta:0,isSubagent:$.isSubagent??!1}}function ZJ($,Z,J){return{...$,usage:$.usage+Z,lastOutputDelta:Z,consecutiveContinuations:J?$.consecutiveContinuations+1:0}}import z$ from"node:path";var k8=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"]),x8=/^(LD_.+|DYLD_.+|PATH)$/,JJ=/^([A-Za-z_][A-Za-z0-9_]*)=([\w./:@-]*)$/;function Z1($){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(JJ);if(!K)break;let X=K[1];if(!k8.has(X))break;Z=Y}return Z}function r5($){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(JJ);if(!K)break;let X=K[1];if(x8.test(X))break;Z=Y}return Z}var I8=[/^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 xZ($){let Z=$,J=!0;while(J){J=!1;for(let W of I8){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 J1($){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 WJ($){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 V$($){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 h8=new Set(["npm","pnpm","yarn","bun"]),YJ=new Set(["biome","eslint","jest","mypy","pyright","pytest","ruff","tsc","vitest"]),v8=new Set(["-u","--fix","--update","--update-snapshot","--updateSnapshot","--watch","--watchAll","--write"]),C8=/[ \t]*;[ \t]*echo[ \t]+"[A-Za-z0-9 _:=.-]*(?:\$\{PIPESTATUS\[0\]\}|\$\?)[A-Za-z0-9 _:=.-]*"[ \t]*$/;function g8($){return $!==void 0&&/^(?:test|lint|build|type-?check)(?::[\w.-]+)*$/i.test($)}function KJ($){return $.replace(/\s+2>&1\s*$/,"").trim()}function p8($,Z,J){if(!J||Z.length!==2)return;let W=/^(.+?)[ \t]+&&[ \t]+([\s\S]+)$/.exec($);if(!W)return;let Y=V$(W[1]??"");if(Y.length!==2||Y[0]!=="cd")return;let K=Y[1];if(!K||K==="-")return;let X=z$.isAbsolute(K)?z$.resolve(K):z$.resolve(J,K);if(!j$.isWithinWorkspace(X,J))return;return W[2]?.trim()||void 0}function u8($){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 m8($){let Z=V$($),[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 d8($){let Z=KJ($.replace(C8,"").trim()),J=u8(Z);if(!J)return;if(J.length===0)return XJ(Z);if(J.length!==1)return;let W=J[0];if(W===void 0)return;let Y=KJ(Z.slice(0,W).trim()),K=Z.slice(W+1).trim();if(!Y||!m8(K))return;return XJ(Y)}function XJ($){let J=J1($)?.at(-1);if(!J)return $;let W=V$(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 T$($,Z){let J=d8($);if(!J)return!1;let W=Z1(J),Y=J1(W);if(!Y||WJ(W)||/[\r\n]/.test(W))return!1;let K=Y.length===1?Y[0]:p8(W,Y,Z);if(!K)return!1;let X=V$(K);if(X.length===0||X.some((z)=>[...v8].some((w)=>z===w||z.startsWith(`${w}=`))))return!1;let[Q,H,V]=X;if(h8.has(Q??""))return g8(H==="run"?V:H)||H==="--test";if((Q==="npx"||Q==="bunx")&&YJ.has(H??""))return!0;if(YJ.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 t5($,Z){if($===void 0)return!0;if(typeof $!=="string"||$.split(/[\\/]/).includes(".."))return!1;if(!Z)return!z$.isAbsolute($);let J=z$.isAbsolute($)?z$.resolve($):z$.resolve(Z,$);return j$.isWithinWorkspace(J,Z)}var IZ=S0("Agent"),c8=3;function hZ($,Z,J){if($!=="length")return{action:"none"};if(Z>=c8)return{action:"truncated"};if(e6(J)==="stop")return IZ.info("[Loop] Token budget: diminishing returns detected, skipping recovery"),{action:"budget_stop"};return{action:"recover"}}var l8=[/:\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],i8=/```[\s\S]{50,}```/,QJ="请执行你提到的操作,不要只是描述。使用 Edit/Write/ApplyPatch/Bash 工具来实际修改文件。",r8=2;function vZ($,Z,J=!0){if(!$||Z>=r8)return{action:"none"};if(!J&&i8.test($))return{action:"retry",prompt:QJ};let W=$.slice(-200),Y=W.match(/```/g);if(Y&&Y.length%2!==0)return{action:"none"};if(l8.some((X)=>X.test(W)))return{action:"retry",prompt:QJ};return{action:"none"}}var g1=2,n8="The model returned tool-call JSON as text instead of completing the requested tool workflow.",o8="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 CZ($,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((G)=>!["id","type",...H?["function"]:["name","arguments"]].includes(G)))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((G)=>G!=="name"&&G!=="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 w=V.name.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),B=new RegExp(`(?:^|[.!?。!?;;\\n])\\s*(?:please\\s+)?(?:call|invoke|execute|run|use)\\s+(?:the\\s+)?(?:tool\\s+)?[\`"']?${w}(?![\\w:-])|(?:^|[。!?;\\n])\\s*(?:请)?(?:调用|使用|执行)\\s*(?:工具\\s*)?[\`"']?${w}(?![\\w:-])`,"i"),j=new RegExp(`(?:do not|don't|never)\\s+(?:call|invoke|execute|run|use)\\s+(?:the\\s+)?(?:tool\\s+)?[\`"']?${w}(?![\\w:-])|(?:不要|禁止)(?:调用|使用|执行)\\s*(?:工具\\s*)?[\`"']?${w}(?![\\w:-])`,"i");if(!B.test(Y)||j.test(Y))return{action:"none"};X.add(V.name)}return W<g1?{action:"retry",prompt:o8,...X.size===1?{toolName:[...X][0]}:{}}:{action:"fail",message:n8}}var a8=[/\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}(?:测试|单测|集成测试|检查|构建)/],HJ={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},s8={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},t8="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.",e8="Required verification did not run successfully before the retry limit.",$9=3;function zJ($,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&&T$(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"&&T$(K,W))$.add(K)}function gZ($,Z,J){if(!$||!a8.some((H)=>H.test($)))return{action:"none"};let W=Object.keys(HJ).filter((H)=>HJ[H].test($)),Y=[...Z],K=W.filter((H)=>!Y.some((V)=>s8[H].test(V)));if(W.length>0?K.length===0:Y.some((H)=>T$(H)))return{action:"none"};if(J>=$9)return{action:"fail",message:e8};let Q=W.length>1&&K.length>0?` Missing successful verification categories: ${K.join(", ")}.`:"";return{action:"retry",prompt:`${t8}${Q}`}}var Z9=[/\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|子代理|子智能体)/],jJ=[/\b(?:do not|don't|never)\s+(?:delegate|call|use|invoke)\b/i,/(?:不要|禁止|无需)(?:委派|调用|使用).{0,20}(?:Task|子代理|子智能体)?/];function BJ($){return typeof $==="string"&&jJ.some((Z)=>Z.test($))}var J9=[/\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|子代理)/],W9=[/\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 Y9($){if(typeof $!=="string")return;if(W9.some((Z)=>Z.test($)))return"multiple-allowed";return J9.some((Z)=>Z.test($))?"required":void 0}function Y1($){for(let Z of $){let J=Y9(Z);if(J!==void 0)return J==="required"}return!1}var K9="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.",X9="Required delegation did not complete before the retry limit.",Q9=3;function DJ($,Z,J){let W=(typeof $==="string"?[$]:$??[]).map((X)=>X.trim()).filter(Boolean),Y=Y1(W),K=!1;if(!Y)for(let X of W){if(jJ.some((Q)=>Q.test(X)))break;if(Z9.some((Q)=>Q.test(X))){K=!0;break}}if(W.length===0||!Y&&!K||Z.has("Task"))return{action:"none"};if(J>=Q9)return{action:"fail",message:X9};return{action:"retry",prompt:K9}}var H9=[/\b(?:use|create|enter|start|work\s+(?:in|inside))\b.{0,60}\bworktree\b/i,/(?:使用|创建|进入).{0,30}(?:worktree|工作树)/i],V9=[/\b(?:exit|leave)\b.{0,40}\bworktree\b/i,/\bworktree\b.{0,60}\b(?:action\s+)?(?:keep|remove)\b/i,/(?:退出|离开).{0,30}(?:worktree|工作树)/i],z9=[/\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 wJ($){return z9.reduce((Z,J)=>Z.replace(J," "),$)}function p1($){if(typeof $!=="string")return!1;let Z=wJ($);return H9.some((J)=>J.test(Z))}var j9="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.",B9="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.",D9="Required worktree lifecycle did not complete before the retry limit.",w9=3;function UJ($,Z,J){if(!$)return{action:"none"};let W=wJ($);if(!p1(W))return{action:"none"};let Y=V9.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>=w9)return{action:"fail",message:D9};return{action:"retry",tool:K,prompt:K==="EnterWorktree"?j9:B9}}var VJ=30000;async function pZ($){try{let J=R$.getInstance().executeStopHooks({projectDir:$.workspaceRoot??j0(),sessionId:$.sessionId,permissionMode:$.permissionMode,reason:$.reason,abortSignal:$.abortSignal}),W,Y=new Promise((K)=>{W=setTimeout(()=>K("timeout"),VJ)});try{let K=await Promise.race([J,Y]);if(K==="timeout")return IZ.warn(`[Loop] Stop hook 超时 (${VJ}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 IZ.warn("[Loop] Stop hook execution failed:",Z),{action:"stop"}}}async function U9($,Z){let J;while(!(J=await $.next()).done)if(Z)await Z(J.value);return J.value}var q9=[/<system-reminder>[\s\S]*?<\/system-reminder>/gi,/<file[^>]*>[\s\S]*?<\/file>/gi,/<hooks_context>[\s\S]*?<\/hooks_context>/gi,/<[^>]+>/g];function G9($){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 L9($){let Z=$;for(let H of q9)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 qJ($){return L9(G9($))}import{EventEmitter as F9}from"events";import GJ from"node:path";function uZ($){if(FJ($.sessionId),!GJ.isAbsolute($.projectPath))throw Error("projectPath must be absolute");return{sessionId:$.sessionId,projectPath:GJ.resolve($.projectPath)}}function LJ($){let Z=uZ($);return JSON.stringify([Z.projectPath,Z.sessionId])}function j3($,Z){return LJ($)===LJ(Z)}class M$ extends F9{static instance;constructor(){super();this.setMaxListeners(100)}static getInstance(){if(!M$.instance)M$.instance=new M$;return M$.instance}publish($,Z,J,W){let Y=uZ($);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 K1=M$.getInstance();var $$=S0("Agent"),u1=new Set;async function O9($,Z){let J=$.sessionId;if(!J||$.subagentInfo)return;if(u1.has(J))return;if(u1.size>=5000)u1.clear();u1.add(J);try{let W=$.workspaceRoot,Y=await X1.findSessionMetadata(J,W);if(!Y)return;if(Y.title&&Y.title.trim())return;let K=qJ(Z);if(!K)return;await X1.updateSessionMetadata(J,Y.projectPath,{title:K}),K1.publish({sessionId:J,projectPath:Y.projectPath},"session.updated",{title:K})}catch(W){$$.debug?.("[Loop] 自动生成会话标题失败:",W)}}var mZ=`<turn_aborted>
|
|
1
|
+
import{xc as G8}from"./chunk-fdr4fcrf.js";import{$d as R6,Ac as U$,Bc as A2,Cc as a1,Ec as j$,Fd as E2,Gd as L8,Hd as F8,Id as V6,Jd as JZ,Kd as O8,Ld as P8,Md as r1,Qd as rJ,Zd as u0,ae as t1,be as M6,ie as X1,ud as b2,wd as y2,xd as f2,yc as q$,yd as w6,zd as U6}from"./chunk-r2ev8kdg.js";import{ne as q8}from"./chunk-egss0m1x.js";import{Fe as f0,qe as q0,te as j2,ue as u$}from"./chunk-ztreczac.js";import{eg as p2}from"./chunk-5yyp6njq.js";import{fg as w8,gg as C0,hg as H8,ig as dJ,kg as i1,lg as T6,mg as cJ,ng as lJ,qg as iJ}from"./chunk-myvt7yjm.js";import{ch as K$,dh as n0,gh as U8}from"./chunk-kehgewqh.js";import{lh as a2,ph as Y2}from"./chunk-kkzznz4w.js";import{Ah as R$}from"./chunk-vnbyb9dq.js";import{Vi as x$}from"./chunk-qpmvp4q2.js";import{cj as j0}from"./chunk-qdbbke8f.js";import{Ej as S0}from"./chunk-rmfzym94.js";import{Yj as _2}from"./chunk-25ma8vb3.js";import{Ck as FJ,Dk as ZZ,Fk as O2,Kk as P2,Lk as N2,gk as F2,vk as w2,wk as U2,zk as H1}from"./chunk-n52n2w5v.js";import{Nk as lZ}from"./chunk-cjfb4kjp.js";function S$($){return $.role==="system"&&Array.isArray($.content)}function E$($){if($.role!=="system"||!$.metadata||Array.isArray($.metadata))return!1;return typeof $.metadata==="object"&&$.metadata.contextualProjectRules===!0}class C1{systemMessages;_contextualSystemMessages;_history;_pending=[];_contextRevision=0;context;constructor($,Z){this.context=$;let J=$.messages.find(S$);if(this._contextualSystemMessages=$.messages.filter(E$),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)=>!S$(W)&&!E$(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(!E$($))throw Error("Contextual project instructions require safe metadata");this._contextualSystemMessages.push($),this.systemMessages.push($)}syncContextualSystemMessages(){let $=this.systemMessages.filter(S$);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:{},...f0}})}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)=>!S$(Z)&&!E$(Z)),this._contextRevision++}restoreDurableHistory($){this._contextualSystemMessages=$.filter(E$),this._history=$.filter((Z)=>!S$(Z)&&!E$(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 e6($){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 $J($){return{budget:$.budget,usage:0,consecutiveContinuations:0,lastOutputDelta:0,isSubagent:$.isSubagent??!1}}function ZJ($,Z,J){return{...$,usage:$.usage+Z,lastOutputDelta:Z,consecutiveContinuations:J?$.consecutiveContinuations+1:0}}import z$ from"node:path";var k8=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"]),x8=/^(LD_.+|DYLD_.+|PATH)$/,JJ=/^([A-Za-z_][A-Za-z0-9_]*)=([\w./:@-]*)$/;function Z1($){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(JJ);if(!K)break;let X=K[1];if(!k8.has(X))break;Z=Y}return Z}function r5($){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(JJ);if(!K)break;let X=K[1];if(x8.test(X))break;Z=Y}return Z}var I8=[/^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 xZ($){let Z=$,J=!0;while(J){J=!1;for(let W of I8){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 J1($){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 WJ($){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 V$($){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 h8=new Set(["npm","pnpm","yarn","bun"]),YJ=new Set(["biome","eslint","jest","mypy","pyright","pytest","ruff","tsc","vitest"]),v8=new Set(["-u","--fix","--update","--update-snapshot","--updateSnapshot","--watch","--watchAll","--write"]),C8=/[ \t]*;[ \t]*echo[ \t]+"[A-Za-z0-9 _:=.-]*(?:\$\{PIPESTATUS\[0\]\}|\$\?)[A-Za-z0-9 _:=.-]*"[ \t]*$/;function g8($){return $!==void 0&&/^(?:test|lint|build|type-?check)(?::[\w.-]+)*$/i.test($)}function KJ($){return $.replace(/\s+2>&1\s*$/,"").trim()}function p8($,Z,J){if(!J||Z.length!==2)return;let W=/^(.+?)[ \t]+&&[ \t]+([\s\S]+)$/.exec($);if(!W)return;let Y=V$(W[1]??"");if(Y.length!==2||Y[0]!=="cd")return;let K=Y[1];if(!K||K==="-")return;let X=z$.isAbsolute(K)?z$.resolve(K):z$.resolve(J,K);if(!j$.isWithinWorkspace(X,J))return;return W[2]?.trim()||void 0}function u8($){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 m8($){let Z=V$($),[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 d8($){let Z=KJ($.replace(C8,"").trim()),J=u8(Z);if(!J)return;if(J.length===0)return XJ(Z);if(J.length!==1)return;let W=J[0];if(W===void 0)return;let Y=KJ(Z.slice(0,W).trim()),K=Z.slice(W+1).trim();if(!Y||!m8(K))return;return XJ(Y)}function XJ($){let J=J1($)?.at(-1);if(!J)return $;let W=V$(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 T$($,Z){let J=d8($);if(!J)return!1;let W=Z1(J),Y=J1(W);if(!Y||WJ(W)||/[\r\n]/.test(W))return!1;let K=Y.length===1?Y[0]:p8(W,Y,Z);if(!K)return!1;let X=V$(K);if(X.length===0||X.some((z)=>[...v8].some((w)=>z===w||z.startsWith(`${w}=`))))return!1;let[Q,H,V]=X;if(h8.has(Q??""))return g8(H==="run"?V:H)||H==="--test";if((Q==="npx"||Q==="bunx")&&YJ.has(H??""))return!0;if(YJ.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 t5($,Z){if($===void 0)return!0;if(typeof $!=="string"||$.split(/[\\/]/).includes(".."))return!1;if(!Z)return!z$.isAbsolute($);let J=z$.isAbsolute($)?z$.resolve($):z$.resolve(Z,$);return j$.isWithinWorkspace(J,Z)}var IZ=S0("Agent"),c8=3;function hZ($,Z,J){if($!=="length")return{action:"none"};if(Z>=c8)return{action:"truncated"};if(e6(J)==="stop")return IZ.info("[Loop] Token budget: diminishing returns detected, skipping recovery"),{action:"budget_stop"};return{action:"recover"}}var l8=[/:\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],i8=/```[\s\S]{50,}```/,QJ="请执行你提到的操作,不要只是描述。使用 Edit/Write/ApplyPatch/Bash 工具来实际修改文件。",r8=2;function vZ($,Z,J=!0){if(!$||Z>=r8)return{action:"none"};if(!J&&i8.test($))return{action:"retry",prompt:QJ};let W=$.slice(-200),Y=W.match(/```/g);if(Y&&Y.length%2!==0)return{action:"none"};if(l8.some((X)=>X.test(W)))return{action:"retry",prompt:QJ};return{action:"none"}}var g1=2,n8="The model returned tool-call JSON as text instead of completing the requested tool workflow.",o8="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 CZ($,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((G)=>!["id","type",...H?["function"]:["name","arguments"]].includes(G)))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((G)=>G!=="name"&&G!=="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 w=V.name.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),B=new RegExp(`(?:^|[.!?。!?;;\\n])\\s*(?:please\\s+)?(?:call|invoke|execute|run|use)\\s+(?:the\\s+)?(?:tool\\s+)?[\`"']?${w}(?![\\w:-])|(?:^|[。!?;\\n])\\s*(?:请)?(?:调用|使用|执行)\\s*(?:工具\\s*)?[\`"']?${w}(?![\\w:-])`,"i"),j=new RegExp(`(?:do not|don't|never)\\s+(?:call|invoke|execute|run|use)\\s+(?:the\\s+)?(?:tool\\s+)?[\`"']?${w}(?![\\w:-])|(?:不要|禁止)(?:调用|使用|执行)\\s*(?:工具\\s*)?[\`"']?${w}(?![\\w:-])`,"i");if(!B.test(Y)||j.test(Y))return{action:"none"};X.add(V.name)}return W<g1?{action:"retry",prompt:o8,...X.size===1?{toolName:[...X][0]}:{}}:{action:"fail",message:n8}}var a8=[/\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}(?:测试|单测|集成测试|检查|构建)/],HJ={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},s8={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},t8="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.",e8="Required verification did not run successfully before the retry limit.",$9=3;function zJ($,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&&T$(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"&&T$(K,W))$.add(K)}function gZ($,Z,J){if(!$||!a8.some((H)=>H.test($)))return{action:"none"};let W=Object.keys(HJ).filter((H)=>HJ[H].test($)),Y=[...Z],K=W.filter((H)=>!Y.some((V)=>s8[H].test(V)));if(W.length>0?K.length===0:Y.some((H)=>T$(H)))return{action:"none"};if(J>=$9)return{action:"fail",message:e8};let Q=W.length>1&&K.length>0?` Missing successful verification categories: ${K.join(", ")}.`:"";return{action:"retry",prompt:`${t8}${Q}`}}var Z9=[/\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|子代理|子智能体)/],jJ=[/\b(?:do not|don't|never)\s+(?:delegate|call|use|invoke)\b/i,/(?:不要|禁止|无需)(?:委派|调用|使用).{0,20}(?:Task|子代理|子智能体)?/];function BJ($){return typeof $==="string"&&jJ.some((Z)=>Z.test($))}var J9=[/\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|子代理)/],W9=[/\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 Y9($){if(typeof $!=="string")return;if(W9.some((Z)=>Z.test($)))return"multiple-allowed";return J9.some((Z)=>Z.test($))?"required":void 0}function Y1($){for(let Z of $){let J=Y9(Z);if(J!==void 0)return J==="required"}return!1}var K9="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.",X9="Required delegation did not complete before the retry limit.",Q9=3;function DJ($,Z,J){let W=(typeof $==="string"?[$]:$??[]).map((X)=>X.trim()).filter(Boolean),Y=Y1(W),K=!1;if(!Y)for(let X of W){if(jJ.some((Q)=>Q.test(X)))break;if(Z9.some((Q)=>Q.test(X))){K=!0;break}}if(W.length===0||!Y&&!K||Z.has("Task"))return{action:"none"};if(J>=Q9)return{action:"fail",message:X9};return{action:"retry",prompt:K9}}var H9=[/\b(?:use|create|enter|start|work\s+(?:in|inside))\b.{0,60}\bworktree\b/i,/(?:使用|创建|进入).{0,30}(?:worktree|工作树)/i],V9=[/\b(?:exit|leave)\b.{0,40}\bworktree\b/i,/\bworktree\b.{0,60}\b(?:action\s+)?(?:keep|remove)\b/i,/(?:退出|离开).{0,30}(?:worktree|工作树)/i],z9=[/\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 wJ($){return z9.reduce((Z,J)=>Z.replace(J," "),$)}function p1($){if(typeof $!=="string")return!1;let Z=wJ($);return H9.some((J)=>J.test(Z))}var j9="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.",B9="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.",D9="Required worktree lifecycle did not complete before the retry limit.",w9=3;function UJ($,Z,J){if(!$)return{action:"none"};let W=wJ($);if(!p1(W))return{action:"none"};let Y=V9.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>=w9)return{action:"fail",message:D9};return{action:"retry",tool:K,prompt:K==="EnterWorktree"?j9:B9}}var VJ=30000;async function pZ($){try{let J=R$.getInstance().executeStopHooks({projectDir:$.workspaceRoot??j0(),sessionId:$.sessionId,permissionMode:$.permissionMode,reason:$.reason,abortSignal:$.abortSignal}),W,Y=new Promise((K)=>{W=setTimeout(()=>K("timeout"),VJ)});try{let K=await Promise.race([J,Y]);if(K==="timeout")return IZ.warn(`[Loop] Stop hook 超时 (${VJ}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 IZ.warn("[Loop] Stop hook execution failed:",Z),{action:"stop"}}}async function U9($,Z){let J;while(!(J=await $.next()).done)if(Z)await Z(J.value);return J.value}var q9=[/<system-reminder>[\s\S]*?<\/system-reminder>/gi,/<file[^>]*>[\s\S]*?<\/file>/gi,/<hooks_context>[\s\S]*?<\/hooks_context>/gi,/<[^>]+>/g];function G9($){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 L9($){let Z=$;for(let H of q9)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 qJ($){return L9(G9($))}import{EventEmitter as F9}from"events";import GJ from"node:path";function uZ($){if(FJ($.sessionId),!GJ.isAbsolute($.projectPath))throw Error("projectPath must be absolute");return{sessionId:$.sessionId,projectPath:GJ.resolve($.projectPath)}}function LJ($){let Z=uZ($);return JSON.stringify([Z.projectPath,Z.sessionId])}function j3($,Z){return LJ($)===LJ(Z)}class M$ extends F9{static instance;constructor(){super();this.setMaxListeners(100)}static getInstance(){if(!M$.instance)M$.instance=new M$;return M$.instance}publish($,Z,J,W){let Y=uZ($);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 K1=M$.getInstance();var $$=S0("Agent"),u1=new Set;async function O9($,Z){let J=$.sessionId;if(!J||$.subagentInfo)return;if(u1.has(J))return;if(u1.size>=5000)u1.clear();u1.add(J);try{let W=$.workspaceRoot,Y=await X1.findSessionMetadata(J,W);if(!Y)return;if(Y.title&&Y.title.trim())return;let K=qJ(Z);if(!K)return;await X1.updateSessionMetadata(J,Y.projectPath,{title:K}),K1.publish({sessionId:J,projectPath:Y.projectPath},"session.updated",{title:K})}catch(W){$$.debug?.("[Loop] 自动生成会话标题失败:",W)}}var mZ=`<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>`,B$="Tool execution was blocked because its durable call record could not be committed. No tool side effect was started.",OJ="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 k$ 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 D$($){return $.executionEngine?.getContextManager()}async function r0($,Z,J,W=null,Y,K={}){let X=K.required??$.executionEngine!==void 0;try{let Q=D$($),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)O9(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 k$("user_message",{cause:Q})}return null}async function v0($,Z,J,W,Y,K,X={}){let Q=X.required??$.executionEngine!==void 0;try{let H=D$($),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 k$("assistant_message",{cause:H})}return null}async function PJ($,Z,J){try{let W=D$($);if(W&&Z.sessionId)return await W.saveMessage(Z.sessionId,"system",mZ,J,void 0,Z.subagentInfo)}catch(W){$$.warn("[Loop] 保存中断边界失败:",W)}return null}async function NJ($,Z,J,W,Y){try{let K=D$($);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 dZ($,Z,J,W,Y,K={}){try{let X=D$($);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 m1($,Z,J,W,Y,K,X,Q,H,V={}){try{let z=D$($);if(z&&Z.sessionId){let w=await z.saveToolResult(Z.sessionId,J,W,Y,K,X,Z.subagentInfo,Q,H);if(V.required&&!w)throw Error("Durable tool-result commit returned no identity");return w}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 Q1($,Z,J,W,Y={}){try{let K=D$($);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 v0(Z,J,Y,H,K);if(V)H=V;if(Q!==void 0){let z={role:"user",content:Q,metadata:f0};W.appendControl("user",z);let w=await r0(Z,J,Q,H,f0);if(w)H=w}return H}import{createHash as k6}from"node:crypto";import{promises as n9}from"node:fs";import o9 from"node:path";import{nanoid as J$}from"nanoid";import*as $0 from"node:fs/promises";import*as Z$ from"node:path";import AJ from"write-file-atomic";var _J={enabled:!0,maxIndexLines:200};var P9="memory",cZ="MEMORY.md",iZ="<!-- blade:auto-memory-topics:start -->",d1="<!-- blade:auto-memory-topics:end -->",N9={realpath:!1,retries:{retries:5,factor:1.2,minTimeout:20,maxTimeout:100,randomize:!0}},_9=new x$,bJ;function fJ($){return $.trim().replace(/\s+/g," ")}function A9($){return fJ($.replace(/^- \[\d{4}-\d{2}-\d{2}\] /,""))}function b9($){return[iZ,"## Auto-consolidated topics",...$.map((Z)=>`- [${Z}](${Z}.md)`),d1].join(`
|
|
4
4
|
`)}function y9($,Z){let J=b9(Z),W=$.indexOf(iZ),Y=$.indexOf(d1,Math.max(0,W));if(W>=0&&Y>=W)return $.slice(0,W)+J+$.slice(Y+d1.length);if(!$)return`${J}
|
|
@@ -118,8 +118,8 @@ When facing complex multi-step tasks:
|
|
|
118
118
|
2. Execute one step at a time — verify each step succeeded before moving to the next.
|
|
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
|
-
5. Prefer the smallest change that achieves the goal — avoid unnecessary refactoring.`}`}var L$=S0("Agent"),A5=new Set(["Read","Glob","Grep","WebFetch","WebSearch","MemoryRead","ReadPromptArtifact","GetSpecContext","ValidateSpec","TaskOutput"]);class zZ{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 q1;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 L$.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";G1($.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(A5.has($.function.name)&&K&&!this.hasExclusiveBarrier){L$.debug(`[StreamingToolExecutor] 立即执行预启动工具: ${$.function.name}`);let H=this.executeOne($,Z);return this.pending.set($.id,H),"prelaunched"}else{if(L$.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(),L$.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(B){if(L$.warn("[StreamingToolExecutor] 保存工具调用失败:",B),!this.requireDurableToolUse)Y=null;else return{toolCall:$,result:{success:!1,llmContent:B$,error:{type:"execution_error",message:B$},metadata:{durableToolUseFailed:!0,summary:"Blocked tool before execution"}},toolUseUuid:null,error:B instanceof Error?B:Error(String(B))}}let X=[K,W.signal],Q=this.execContext.signal;if(Q)X.push(Q);let H=H8(...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:(B)=>{this.execContext.onProgress?.(B),this.progressSink?.($,{message:B.slice(0,1000)})},onProgressUpdate:(B)=>{this.execContext.onProgressUpdate?.(B),this.progressSink?.($,B)}},z=this.executeTool?await this.executeTool($.function.name,Z,V):await this.pipeline.execute($.function.name,Z,V);if(J!==this.epoch)return L$.debug(`[StreamingToolExecutor] 丢弃旧世代工具结果: ${$.function.name} (startEpoch=${J}, currentEpoch=${this.epoch})`),this.makeAbortResult($,"Tool execution aborted due to epoch mismatch (discard)",Y);let w={toolCall:$,result:z,toolUseUuid:Y};if(this.pending.has($.id))this.pending.delete($.id),this.completed.set($.id,w);return w}catch(X){if(J!==this.epoch)return this.makeAbortResult($,"Tool execution aborted due to epoch mismatch (discard)",Y);L$.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 f6{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 V8($,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 z8($,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 j8($){let Z=$.metadata;if(!Z)return;return Z.modelId?.toString().trim()||Z.model?.toString().trim()||void 0||void 0}function b5($,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 R$.getInstance().inheritProjectConfig(J.workspaceRoot,Y,J.sessionId),J.workspaceRoot=Y,J.worktreeActive=W?.workspaceTransition==="enter",Y}function y5($,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 E6($,Z,J,W){let Y=V8($,Z),K=y5($,Z);z8($,Z,J);let X=j8(Z);if(X)await J.onModelSwitch?.(X);if(W)b5($,Z,W);return K||Y}var r=S0("Agent");function F$($,Z){return{inputTokens:$.promptTokens??0,outputTokens:$.completionTokens??0,totalTokens:n1($)??0,maxContextTokens:Z,cacheReadTokens:$.cacheReadInputTokens??0,cacheWriteTokens:$.cacheCreationInputTokens??0,...$.promptCacheBreak?{cacheBreak:$.promptCacheBreak}:{},costUsd:$.costUsd}}function X$($){return JSON.stringify($).replaceAll("<","\\u003c").replaceAll(">","\\u003e")}function B8($){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 L1($){let Z=B8($);if(Z)return Z;try{let J=JSON.parse($);return typeof J==="string"?B8(J):null}catch{return null}}function f5($){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 c$($){if(typeof $==="string")return $;try{return JSON.parse(JSON.stringify($))}catch{return String($)}}function E5($){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 S5($){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 T5($){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 R5($,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 S6($){if(!($ instanceof Error))return!1;return i1($)||$.status===413}function M5($,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 k5($){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*x5($,Z,J,W,Y,K){let X="",Q="",H,V,z=new Map;try{let w=$.chatService.streamChat(Z,J,W,Y),B=0;for await(let j of w){if(W?.aborted)break;if(j.providerAdmission){yield{kind:"provider_admission",...j.providerAdmission};continue}if(j.providerCircuit){yield{kind:"provider_circuit",...j.providerCircuit};continue}if(j.providerRetry){yield{kind:"provider_retry",...j.providerRetry};continue}if(j.providerStall){yield{kind:"provider_stall",...j.providerStall};continue}if(B++,j.modelFallback){K?.discard(),X="",Q="",H=void 0,V=void 0,z.clear(),B=0,yield{kind:"model_fallback",...j.modelFallback};continue}if(j.content)X+=j.content,yield{kind:"content_delta",delta:j.content};if(j.reasoningContent)Q+=j.reasoningContent,yield{kind:"thinking_delta",delta:j.reasoningContent};if(j.usage)H=j.usage;if(j.toolCalls){for(let G of j.toolCalls)if(M5(z,G),K){let A=G.index??0,S=z.get(A);if(S&&S.id&&S.name)try{let T=L1(S.arguments);if(T===null)continue;let p={id:S.id,type:"function",function:{name:S.name,arguments:S.arguments}},o=$.toolExecutor.getRegistry().get(S.name)?.kind,s=K.addTool(p,T);if(S.arguments=p.function.arguments,s==="prelaunched")yield{kind:"tool_start",toolCall:p,toolKind:o}}catch{}}}if(j.finishReason){V=j.finishReason;break}}if(B===0&&!W?.aborted&&X.length===0&&z.size===0)return r.warn("[Loop] 流式响应返回0个chunk,回退到非流式模式"),K?.discard(),{...await $.chatService.chat(Z,J,W,Y),_nonStreamingFallback:!0};return{content:X,reasoningContent:Q||void 0,toolCalls:k5(z),usage:H,finishReason:V}}catch(w){if(T5(w))return r.warn("[Loop] 流式请求失败,降级到非流式模式"),K?.discard(),{...await $.chatService.chat(Z,J,W,Y),_nonStreamingFallback:!0};throw w}}async function x6($,Z,J){if(!$)return;if(!J)return{outcome:"disabled",entries:0,topics:[]};try{return await RJ($,{workspaceRoot:Z.workspaceRoot||j0(),workspaceAccess:Z.workspaceKind==="acp-remote"?"none":"full"})}catch{return{outcome:"failed",entries:0,topics:[]}}}function I5($){return k6("sha256").update($).digest("hex").slice(0,16)}var h5=new Set(["AbortError","Error","RangeError","TypeError"]),v5=new Set(["EACCES","EEXIST","EIO","EMFILE","ENFILE","ENOENT","ENOSPC","EPERM","EROFS"]);function C5($){if($ instanceof Error){let Z=$,J=h5.has($.name)?$.name:"Error",W=typeof Z.code==="string"&&v5.has(Z.code)?Z.code:"unknown";return`${J}:${W}`}return"UnknownError:unknown"}async function g5($){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"&&P8(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=O8(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=${I5(J.sessionId)} error=${C5(H)}`;return r.warn(V),{kind:"failed"}}}async function*N8($,Z,J,W,Y,K,X,Q,H){let V=W.contextTokens,z=eJ(Z.messages,K),w=z!==null;if(z)Z.messages=z.messages,r.debug(`[Loop] [轮次 ${J}] MicroCompact: 清理 ${z.snippedCount} 轮旧工具结果(缓存已过期)`);let B=j1(Z.messages),j=!1;if(B.snippedCount>0)j=!0,r.debug(`[Loop] [轮次 ${J}] Snip 压缩: 移除 ${B.snippedCount} 轮旧工具调用,释放约 ${B.estimatedTokensFreed} tokens`);if(W.phase==="unknown"){if(j)Z.messages=B.messages;return r.debug(`[Loop] [轮次 ${J}] 压缩检查: 跳过(无历史 usage 数据)`),w||j?{kind:"snipped"}:{kind:"none"}}let G=$.chatService.getConfig(),N=G.model,A=W.maxContextTokens??0,S=W.maxOutputTokens??0,T=W.availableForInput??0;if(A<=0||T<=0){if(j)Z.messages=B.messages;return r.debug(`[Loop] [轮次 ${J}] 压缩检查: 跳过(模型上下文窗口未知)`),w||j?{kind:"snipped"}:{kind:"none"}}if(r.debug(`[Loop] [轮次 ${J}] 压缩检查:`,{contextTokens:V,tokenSource:W.tokenSource,estimatedPendingTokens:W.estimatedPendingTokens,maxContextTokens:A,maxOutputTokens:S,availableForInput:T,threshold:W.compactionThreshold,shouldCompact:W.phase==="compaction_due"}),W.phase!=="compaction_due"){if(j)Z.messages=B.messages;return w||j?{kind:"snipped"}:{kind:"none"}}r.debug(J===0?"[Loop] 触发自动压缩":`[Loop] [轮次 ${J}] 触发循环内自动压缩`);let p="failed",x,o,s,M,d,t,L,u,m0,h,D0,_0,c,O$="compaction";yield{kind:"compaction",phase:"start",reason:"threshold"};try{let P0=j?B.messages:Z.messages,R=await h$.compact(P0,{trigger:"auto",modelName:N,modelProvider:G.provider,maxContextTokens:A,apiKey:G.apiKey,baseURL:G.baseUrl,chatConfig:G,actualPreTokens:V,signal:Y,activeTask:X,workspaceRoot:Z.workspaceRoot||j0(),workspaceAccess:Z.workspaceKind==="acp-remote"?"none":"full",sessionId:Z.sessionId});if(R.usage)H?.(R.usage),yield{kind:"token_usage",usage:F$(R.usage,A)};if(x=R.success?"llm":"fallback",o=R.preTokens,s=R.postTokens,M=R.sampleAttempts,d=R.inputReductions,t=R.messagesOmitted,L=R.filesOmitted,u=R.imagesOmitted,m0=R.fallbackTargetTokens,h=R.fallbackMessagesOmitted,D0=R.fallbackMessagesTruncated,_0=R.failureReason,R.success)r.debug(`[Loop] [轮次 ${J}] 压缩完成: ${R.preTokens} -> ${R.postTokens} tokens`);else r.warn(`[Loop] [轮次 ${J}] 压缩使用降级策略: ${R.preTokens} -> ${R.postTokens} tokens`);O$="checkpoint";let F1=await Q1($,Z,R.summary,{trigger:"auto",reason:"threshold",strategy:x,preTokens:R.preTokens,...W.tokenSource?{preTokenSource:W.tokenSource}:{},...W.estimatedPendingTokens!==void 0?{estimatedPendingTokens:W.estimatedPendingTokens}:{},postTokens:R.postTokens,sampleAttempts:R.sampleAttempts,inputReductions:R.inputReductions,messagesOmitted:R.messagesOmitted,filesOmitted:R.filesOmitted,imagesOmitted:R.imagesOmitted,fallbackTargetTokens:R.fallbackTargetTokens,fallbackMessagesOmitted:R.fallbackMessagesOmitted,fallbackMessagesTruncated:R.fallbackMessagesTruncated,failureReason:R.failureReason,filesIncluded:R.filesIncluded,replacementMessages:R.compactedMessages},{required:$.executionEngine!==void 0});if(c=await x6(R.memoryPlan,Z,F1),Z.messages=R.compactedMessages,Q)Q.lastCompactionTurn=J;return p=R.success?"completed":"fallback",{kind:"compacted",postTokens:R.postTokens}}catch(P0){if(C0(P0)){if(P0 instanceof Y$)H?.(P0.usage),yield{kind:"token_usage",usage:F$(P0.usage,A)};return r.debug(`[Loop] [轮次 ${J}] 压缩被中止`),{kind:"none"}}return r.error(`[Loop] [轮次 ${J}] 压缩失败,停止执行`,P0),{kind:"failed",phase:O$}}finally{yield{kind:"compaction",phase:"end",reason:"threshold",outcome:p,strategy:x,preTokens:o,...W.tokenSource?{preTokenSource:W.tokenSource}:{},...W.estimatedPendingTokens!==void 0?{estimatedPendingTokens:W.estimatedPendingTokens}:{},postTokens:s,sampleAttempts:M,inputReductions:d,messagesOmitted:t,filesOmitted:L,imagesOmitted:u,fallbackTargetTokens:m0,fallbackMessagesOmitted:h,fallbackMessagesTruncated:D0,failureReason:_0,memory:c}}}function p5($,Z,J,W,Y){let K=Y?w8(Y):"user-cancel";return{success:!1,error:{type:"aborted",message:(K==="interrupt"?void 0:"任务已被用户中止")??"任务已中断"},metadata:{turnsCount:$,toolCallsCount:Z,duration:Date.now()-J,tokensUsed:W,abortReason:K}}}function D8($,Z,J,W){return{success:!1,error:{type:"tool_persistence_failed",message:OJ},metadata:{turnsCount:$,toolCallsCount:Z,duration:Date.now()-J,tokensUsed:W}}}function u5($,Z,J,W,Y){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,tokensUsed:Y}}}async function*m5($,Z,J,W,Y){let K=Date.now(),X=0,Q=(j)=>{X=Math.min(Number.MAX_SAFE_INTEGER,X+(n1(j)??0))},H=0,V=[],z=null,w=!1,B=(j,G,N)=>{return w=!0,p5(j,G,K,X,N)};try{let j=$.toolExecutor.getRegistry(),G=J.permissionMode,N=W?.outputSchema?t1(W.outputSchema):void 0,A=()=>{let F=$.applySkillToolRestrictions(j.getFunctionDeclarationsByMode(G));if(!N)return F;return[...F.filter((O)=>O.name!==u0),N.declaration]},S=u2(),T=K2(),p=()=>{let F=Q2(T);return F?{executionHostFailureCategory:F}:{}},x=r2(),o=C2(),s=Q8(Y,j);if(N)s=`${s??""}
|
|
121
|
+
5. Prefer the smallest change that achieves the goal — avoid unnecessary refactoring.`}`}var L$=S0("Agent"),A5=new Set(["Read","Glob","Grep","WebFetch","WebSearch","MemoryRead","ReadPromptArtifact","GetSpecContext","ValidateSpec","TaskOutput"]);class zZ{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 q1;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 L$.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";G1($.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(A5.has($.function.name)&&K&&!this.hasExclusiveBarrier){L$.debug(`[StreamingToolExecutor] 立即执行预启动工具: ${$.function.name}`);let H=this.executeOne($,Z);return this.pending.set($.id,H),"prelaunched"}else{if(L$.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(),L$.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(B){if(L$.warn("[StreamingToolExecutor] 保存工具调用失败:",B),!this.requireDurableToolUse)Y=null;else return{toolCall:$,result:{success:!1,llmContent:B$,error:{type:"execution_error",message:B$},metadata:{durableToolUseFailed:!0,summary:"Blocked tool before execution"}},toolUseUuid:null,error:B instanceof Error?B:Error(String(B))}}let X=[K,W.signal],Q=this.execContext.signal;if(Q)X.push(Q);let H=H8(...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:(B)=>{this.execContext.onProgress?.(B),this.progressSink?.($,{message:B.slice(0,1000)})},onProgressUpdate:(B)=>{this.execContext.onProgressUpdate?.(B),this.progressSink?.($,B)}},z=this.executeTool?await this.executeTool($.function.name,Z,V):await this.pipeline.execute($.function.name,Z,V);if(J!==this.epoch)return L$.debug(`[StreamingToolExecutor] 丢弃旧世代工具结果: ${$.function.name} (startEpoch=${J}, currentEpoch=${this.epoch})`),this.makeAbortResult($,"Tool execution aborted due to epoch mismatch (discard)",Y);let w={toolCall:$,result:z,toolUseUuid:Y};if(this.pending.has($.id))this.pending.delete($.id),this.completed.set($.id,w);return w}catch(X){if(J!==this.epoch)return this.makeAbortResult($,"Tool execution aborted due to epoch mismatch (discard)",Y);L$.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 f6{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 V8($,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 z8($,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 j8($){let Z=$.metadata;if(!Z)return;return Z.modelId?.toString().trim()||Z.model?.toString().trim()||void 0||void 0}function b5($,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 R$.getInstance().inheritProjectConfig(J.workspaceRoot,Y,J.sessionId),J.workspaceRoot=Y,J.worktreeActive=W?.workspaceTransition==="enter",Y}function y5($,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 E6($,Z,J,W){let Y=V8($,Z),K=y5($,Z);z8($,Z,J);let X=j8(Z);if(X)await J.onModelSwitch?.(X);if(W)b5($,Z,W);return K||Y}var r=S0("Agent");function F$($,Z,J){return{...J?{scope:J}:{},inputTokens:$.promptTokens??0,outputTokens:$.completionTokens??0,totalTokens:n1($)??0,maxContextTokens:Z,cacheReadTokens:$.cacheReadInputTokens??0,cacheWriteTokens:$.cacheCreationInputTokens??0,...$.promptCacheBreak?{cacheBreak:$.promptCacheBreak}:{},costUsd:$.costUsd}}function X$($){return JSON.stringify($).replaceAll("<","\\u003c").replaceAll(">","\\u003e")}function B8($){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 L1($){let Z=B8($);if(Z)return Z;try{let J=JSON.parse($);return typeof J==="string"?B8(J):null}catch{return null}}function f5($){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 c$($){if(typeof $==="string")return $;try{return JSON.parse(JSON.stringify($))}catch{return String($)}}function E5($){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 S5($){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 T5($){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 R5($,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 S6($){if(!($ instanceof Error))return!1;return i1($)||$.status===413}function M5($,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 k5($){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*x5($,Z,J,W,Y,K){let X="",Q="",H,V,z=new Map;try{let w=$.chatService.streamChat(Z,J,W,Y),B=0;for await(let j of w){if(W?.aborted)break;if(j.providerAdmission){yield{kind:"provider_admission",...j.providerAdmission};continue}if(j.providerCircuit){yield{kind:"provider_circuit",...j.providerCircuit};continue}if(j.providerRetry){yield{kind:"provider_retry",...j.providerRetry};continue}if(j.providerStall){yield{kind:"provider_stall",...j.providerStall};continue}if(B++,j.modelFallback){K?.discard(),X="",Q="",H=void 0,V=void 0,z.clear(),B=0,yield{kind:"model_fallback",...j.modelFallback};continue}if(j.content)X+=j.content,yield{kind:"content_delta",delta:j.content};if(j.reasoningContent)Q+=j.reasoningContent,yield{kind:"thinking_delta",delta:j.reasoningContent};if(j.usage)H=j.usage;if(j.toolCalls){for(let G of j.toolCalls)if(M5(z,G),K){let A=G.index??0,S=z.get(A);if(S&&S.id&&S.name)try{let T=L1(S.arguments);if(T===null)continue;let p={id:S.id,type:"function",function:{name:S.name,arguments:S.arguments}},o=$.toolExecutor.getRegistry().get(S.name)?.kind,s=K.addTool(p,T);if(S.arguments=p.function.arguments,s==="prelaunched")yield{kind:"tool_start",toolCall:p,toolKind:o}}catch{}}}if(j.finishReason){V=j.finishReason;break}}if(B===0&&!W?.aborted&&X.length===0&&z.size===0)return r.warn("[Loop] 流式响应返回0个chunk,回退到非流式模式"),K?.discard(),{...await $.chatService.chat(Z,J,W,Y),_nonStreamingFallback:!0};return{content:X,reasoningContent:Q||void 0,toolCalls:k5(z),usage:H,finishReason:V}}catch(w){if(T5(w))return r.warn("[Loop] 流式请求失败,降级到非流式模式"),K?.discard(),{...await $.chatService.chat(Z,J,W,Y),_nonStreamingFallback:!0};throw w}}async function x6($,Z,J){if(!$)return;if(!J)return{outcome:"disabled",entries:0,topics:[]};try{return await RJ($,{workspaceRoot:Z.workspaceRoot||j0(),workspaceAccess:Z.workspaceKind==="acp-remote"?"none":"full"})}catch{return{outcome:"failed",entries:0,topics:[]}}}function I5($){return k6("sha256").update($).digest("hex").slice(0,16)}var h5=new Set(["AbortError","Error","RangeError","TypeError"]),v5=new Set(["EACCES","EEXIST","EIO","EMFILE","ENFILE","ENOENT","ENOSPC","EPERM","EROFS"]);function C5($){if($ instanceof Error){let Z=$,J=h5.has($.name)?$.name:"Error",W=typeof Z.code==="string"&&v5.has(Z.code)?Z.code:"unknown";return`${J}:${W}`}return"UnknownError:unknown"}async function g5($){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"&&P8(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=O8(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=${I5(J.sessionId)} error=${C5(H)}`;return r.warn(V),{kind:"failed"}}}async function*N8($,Z,J,W,Y,K,X,Q,H){let V=W.contextTokens,z=eJ(Z.messages,K),w=z!==null;if(z)Z.messages=z.messages,r.debug(`[Loop] [轮次 ${J}] MicroCompact: 清理 ${z.snippedCount} 轮旧工具结果(缓存已过期)`);let B=j1(Z.messages),j=!1;if(B.snippedCount>0)j=!0,r.debug(`[Loop] [轮次 ${J}] Snip 压缩: 移除 ${B.snippedCount} 轮旧工具调用,释放约 ${B.estimatedTokensFreed} tokens`);if(W.phase==="unknown"){if(j)Z.messages=B.messages;return r.debug(`[Loop] [轮次 ${J}] 压缩检查: 跳过(无历史 usage 数据)`),w||j?{kind:"snipped"}:{kind:"none"}}let G=$.chatService.getConfig(),N=G.model,A=W.maxContextTokens??0,S=W.maxOutputTokens??0,T=W.availableForInput??0;if(A<=0||T<=0){if(j)Z.messages=B.messages;return r.debug(`[Loop] [轮次 ${J}] 压缩检查: 跳过(模型上下文窗口未知)`),w||j?{kind:"snipped"}:{kind:"none"}}if(r.debug(`[Loop] [轮次 ${J}] 压缩检查:`,{contextTokens:V,tokenSource:W.tokenSource,estimatedPendingTokens:W.estimatedPendingTokens,maxContextTokens:A,maxOutputTokens:S,availableForInput:T,threshold:W.compactionThreshold,shouldCompact:W.phase==="compaction_due"}),W.phase!=="compaction_due"){if(j)Z.messages=B.messages;return w||j?{kind:"snipped"}:{kind:"none"}}r.debug(J===0?"[Loop] 触发自动压缩":`[Loop] [轮次 ${J}] 触发循环内自动压缩`);let p="failed",x,o,s,M,d,t,L,u,m0,h,D0,_0,c,O$="compaction";yield{kind:"compaction",phase:"start",reason:"threshold"};try{let P0=j?B.messages:Z.messages,R=await h$.compact(P0,{trigger:"auto",modelName:N,modelProvider:G.provider,maxContextTokens:A,apiKey:G.apiKey,baseURL:G.baseUrl,chatConfig:G,actualPreTokens:V,signal:Y,activeTask:X,workspaceRoot:Z.workspaceRoot||j0(),workspaceAccess:Z.workspaceKind==="acp-remote"?"none":"full",sessionId:Z.sessionId});if(R.usage)H?.(R.usage),yield{kind:"token_usage",usage:F$(R.usage,A,"auxiliary")};if(x=R.success?"llm":"fallback",o=R.preTokens,s=R.postTokens,M=R.sampleAttempts,d=R.inputReductions,t=R.messagesOmitted,L=R.filesOmitted,u=R.imagesOmitted,m0=R.fallbackTargetTokens,h=R.fallbackMessagesOmitted,D0=R.fallbackMessagesTruncated,_0=R.failureReason,R.success)r.debug(`[Loop] [轮次 ${J}] 压缩完成: ${R.preTokens} -> ${R.postTokens} tokens`);else r.warn(`[Loop] [轮次 ${J}] 压缩使用降级策略: ${R.preTokens} -> ${R.postTokens} tokens`);O$="checkpoint";let F1=await Q1($,Z,R.summary,{trigger:"auto",reason:"threshold",strategy:x,preTokens:R.preTokens,...W.tokenSource?{preTokenSource:W.tokenSource}:{},...W.estimatedPendingTokens!==void 0?{estimatedPendingTokens:W.estimatedPendingTokens}:{},postTokens:R.postTokens,sampleAttempts:R.sampleAttempts,inputReductions:R.inputReductions,messagesOmitted:R.messagesOmitted,filesOmitted:R.filesOmitted,imagesOmitted:R.imagesOmitted,fallbackTargetTokens:R.fallbackTargetTokens,fallbackMessagesOmitted:R.fallbackMessagesOmitted,fallbackMessagesTruncated:R.fallbackMessagesTruncated,failureReason:R.failureReason,filesIncluded:R.filesIncluded,replacementMessages:R.compactedMessages},{required:$.executionEngine!==void 0});if(c=await x6(R.memoryPlan,Z,F1),Z.messages=R.compactedMessages,Q)Q.lastCompactionTurn=J;return p=R.success?"completed":"fallback",{kind:"compacted",postTokens:R.postTokens}}catch(P0){if(C0(P0)){if(P0 instanceof Y$)H?.(P0.usage),yield{kind:"token_usage",usage:F$(P0.usage,A,"auxiliary")};return r.debug(`[Loop] [轮次 ${J}] 压缩被中止`),{kind:"none"}}return r.error(`[Loop] [轮次 ${J}] 压缩失败,停止执行`,P0),{kind:"failed",phase:O$}}finally{yield{kind:"compaction",phase:"end",reason:"threshold",outcome:p,strategy:x,preTokens:o,...W.tokenSource?{preTokenSource:W.tokenSource}:{},...W.estimatedPendingTokens!==void 0?{estimatedPendingTokens:W.estimatedPendingTokens}:{},postTokens:s,sampleAttempts:M,inputReductions:d,messagesOmitted:t,filesOmitted:L,imagesOmitted:u,fallbackTargetTokens:m0,fallbackMessagesOmitted:h,fallbackMessagesTruncated:D0,failureReason:_0,memory:c}}}function p5($,Z,J,W,Y){let K=Y?w8(Y):"user-cancel";return{success:!1,error:{type:"aborted",message:(K==="interrupt"?void 0:"任务已被用户中止")??"任务已中断"},metadata:{turnsCount:$,toolCallsCount:Z,duration:Date.now()-J,tokensUsed:W,abortReason:K}}}function D8($,Z,J,W){return{success:!1,error:{type:"tool_persistence_failed",message:OJ},metadata:{turnsCount:$,toolCallsCount:Z,duration:Date.now()-J,tokensUsed:W}}}function u5($,Z,J,W,Y){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,tokensUsed:Y}}}async function*m5($,Z,J,W,Y){let K=Date.now(),X=0,Q=(j)=>{X=Math.min(Number.MAX_SAFE_INTEGER,X+(n1(j)??0))},H=0,V=[],z=null,w=!1,B=(j,G,N)=>{return w=!0,p5(j,G,K,X,N)};try{let j=$.toolExecutor.getRegistry(),G=J.permissionMode,N=W?.outputSchema?t1(W.outputSchema):void 0,A=()=>{let F=$.applySkillToolRestrictions(j.getFunctionDeclarationsByMode(G));if(!N)return F;return[...F.filter((O)=>O.name!==u0),N.declaration]},S=u2(),T=K2(),p=()=>{let F=Q2(T);return F?{executionHostFailureCategory:F}:{}},x=r2(),o=C2(),s=Q8(Y,j);if(N)s=`${s??""}
|
|
123
123
|
|
|
124
124
|
# Structured Final Output
|
|
125
125
|
This turn has a required JSON Schema final-output contract. Complete the user's
|
|
@@ -136,9 +136,9 @@ ${m.map((e)=>`- ${e}`).join(`
|
|
|
136
136
|
`),qZ=!1}let J0=d6(F,O);if(J0&&J0.files.length>0&&j.get(F)?.kind==="write"){let m="Applicable project instructions were loaded before this write. Review the newly supplied rules, then retry the write.";return{success:!1,llmContent:m,error:{type:"validation_error",message:m},metadata:{contextualProjectRulesRequired:!0,projectRuleReferences:J0.references,summary:"Blocked write until contextual project rules are applied"}}}return $.toolExecutor.execute(F,O,K0)},AZ=$J({budget:$.currentModelMaxContextTokens,isSubagent:h}),bZ=new J6,y$=new Z6,b8={},t0=W?.turnSteering,E1=async(F)=>{for(let O of F){let K0={...O.metadata,inboxMessageId:O.id},z0=JSON.parse(JSON.stringify(K0));if(!(O.persisted===!0||L.getHistory().some((m)=>{let e=m.metadata;return e!==null&&typeof e==="object"&&!Array.isArray(e)&&e.inboxMessageId===O.id}))){let m=await r0($,J,O.content,z,K0);if(!m)throw Error(`Failed to persist steering message before applying it: ${O.id}`);z=m,L.appendUser({role:"user",content:O.content,metadata:z0})}else if(!L.getHistory().some((m)=>{let e=m.metadata;return e!==null&&typeof e==="object"&&!Array.isArray(e)&&e.inboxMessageId===O.id}))L.appendUser({role:"user",content:O.content,metadata:z0});let J0=O.policyText??(typeof O.content==="string"?O.content:O.content.filter((m)=>m.type==="text").map((m)=>m.text).join(`
|
|
137
137
|
`));if(O.origin!=="background_subagent"&&J0.trim())P$=void 0,A0=[A0,J0].join(`
|
|
138
138
|
`),PZ.push(J0),OZ=[A0,J.completionRequirements?.trim()].filter(Boolean).join(`
|
|
139
|
-
`),A$=[$.runtimeOptions.appendSystemPrompt?.trim(),J.completionRequirements?.trim(),...PZ].filter((m)=>Boolean(m)),f1=f1||p1(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 e$("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 B(H,V.length,W.signal);if(H>=P0&&(O$||h)){if(r.info(`Warning: 达到轮次上限 ${P0} 轮`),W?.onTurnLimitReached){let U=await W.onTurnLimitReached({turnsCount:H});if(W.signal?.aborted)return B(H,V.length,W.signal);if(U?.continue){L.writeback();let D="failed",f,b,l,E,_,g,k,b0,L0,v,y,X0,n,F0,i;yield{kind:"compaction",phase:"start",reason:"turn_limit"};try{let P=$.chatService.getConfig(),U0=A(),H0=b$&&Y1(A$)?U0.filter((kZ)=>kZ.name!=="Task"):U0,y0=I0?H0.filter((kZ)=>kZ.name===I0):H0,I=$6(L.systemMessages,y0,P.model),i0=y$.project({history:L.getHistory(),contextRevision:L.contextRevision,modelName:P.model,requestProfile:I});l=i0.source,E=i0.estimatedPendingTokens;let C=await h$.compact(J.messages,{trigger:"auto",modelName:P.model,modelProvider:P.provider,maxContextTokens:P.maxContextTokens??0,apiKey:P.apiKey,baseURL:P.baseUrl,chatConfig:P,actualPreTokens:i0.contextTokens,signal:W?.signal,activeTask:A0,workspaceRoot:J.workspaceRoot||j0(),workspaceAccess:J.workspaceKind==="acp-remote"?"none":"full",sessionId:J.sessionId});if(C.usage)Q(C.usage),yield{kind:"token_usage",usage:F$(C.usage,P.maxContextTokens??0)};let R8={role:"user",metadata:f0,content:`This session is being continued from a previous conversation. The conversation is summarized above.
|
|
139
|
+
`),A$=[$.runtimeOptions.appendSystemPrompt?.trim(),J.completionRequirements?.trim(),...PZ].filter((m)=>Boolean(m)),f1=f1||p1(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 e$("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 B(H,V.length,W.signal);if(H>=P0&&(O$||h)){if(r.info(`Warning: 达到轮次上限 ${P0} 轮`),W?.onTurnLimitReached){let U=await W.onTurnLimitReached({turnsCount:H});if(W.signal?.aborted)return B(H,V.length,W.signal);if(U?.continue){L.writeback();let D="failed",f,b,l,E,_,g,k,b0,L0,v,y,X0,n,F0,i;yield{kind:"compaction",phase:"start",reason:"turn_limit"};try{let P=$.chatService.getConfig(),U0=A(),H0=b$&&Y1(A$)?U0.filter((kZ)=>kZ.name!=="Task"):U0,y0=I0?H0.filter((kZ)=>kZ.name===I0):H0,I=$6(L.systemMessages,y0,P.model),i0=y$.project({history:L.getHistory(),contextRevision:L.contextRevision,modelName:P.model,requestProfile:I});l=i0.source,E=i0.estimatedPendingTokens;let C=await h$.compact(J.messages,{trigger:"auto",modelName:P.model,modelProvider:P.provider,maxContextTokens:P.maxContextTokens??0,apiKey:P.apiKey,baseURL:P.baseUrl,chatConfig:P,actualPreTokens:i0.contextTokens,signal:W?.signal,activeTask:A0,workspaceRoot:J.workspaceRoot||j0(),workspaceAccess:J.workspaceKind==="acp-remote"?"none":"full",sessionId:J.sessionId});if(C.usage)Q(C.usage),yield{kind:"token_usage",usage:F$(C.usage,P.maxContextTokens??0,"auxiliary")};let R8={role:"user",metadata:f0,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.`},t6=[...C.compactedMessages,R8];f=C.success?"llm":"fallback",b=C.preTokens,_=C.postTokens,g=C.sampleAttempts,k=C.inputReductions,b0=C.messagesOmitted,L0=C.filesOmitted,v=C.imagesOmitted,y=C.fallbackTargetTokens,X0=C.fallbackMessagesOmitted,n=C.fallbackMessagesTruncated,F0=C.failureReason;let M8=await Q1($,J,C.summary,{trigger:"auto",reason:"turn_limit",strategy:f,preTokens:C.preTokens,preTokenSource:i0.source,...i0.estimatedPendingTokens!==void 0?{estimatedPendingTokens:i0.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:t6},{required:$.executionEngine!==void 0});i=await x6(C.memoryPlan,J,M8),J.messages=t6,L.replaceHistory(J.messages),y$.reset(),D=C.success?"completed":"fallback"}catch(P){if(P instanceof Y$)Q(P.usage),yield{kind:"token_usage",usage:F$(P.usage,$.chatService.getConfig().maxContextTokens??0)};throw r.error("[Loop] 轮次上限压缩失败,停止继续执行:",P),P}finally{yield{kind:"compaction",phase:"end",reason:"turn_limit",outcome:D,strategy:f,preTokens:b,preTokenSource:l,estimatedPendingTokens:E,postTokens:_,sampleAttempts:g,inputReductions:k,messagesOmitted:b0,filesOmitted:L0,imagesOmitted:v,fallbackTargetTokens:y,fallbackMessagesOmitted:X0,fallbackMessagesTruncated:n,failureReason:F0,memory:i}}H=0;continue}return{success:!0,finalMessage:U?.reason||"已达到对话轮次上限,用户选择停止",metadata:{turnsCount:H,toolCallsCount:V.length,duration:Date.now()-K,tokensUsed:X}}}return{success:!1,error:{type:"max_turns_exceeded",message:h?`子代理已达到轮次上限 (${P0} 轮)。`:`已达到轮次上限 (${P0} 轮)。`},metadata:{turnsCount:H,toolCallsCount:V.length,duration:Date.now()-K,tokensUsed:X}}}if(await j.waitForMcpCatalogIdle(W?.signal),W?.signal?.aborted)return B(H,V.length,W.signal);let O=await t0?.drain()??[];if(O.length>0)Q0=void 0,a0=!1,l0=0,yield{kind:"steering_applied",...await E1(O),delivery:NZ?"current_turn":"next_turn",queue:await t0.getSnapshot()},a$=N?M6(L.getHistory(),N):void 0,Q0=a$?.output,a0=a$?.completed===!0,NZ=!0;else if(!NZ)return{success:!0,finalMessage:"",metadata:{turnsCount:0,toolCallsCount:0,duration:Date.now()-K}};if(N&&Q0&&a0){let U=JSON.stringify(Q0);return yield{kind:"structured_output",output:Q0,schemaDigest:N.schemaDigest},{success:!0,finalMessage:U,metadata:{turnsCount:H,toolCallsCount:V.length,duration:Date.now()-K,tokensUsed:X,structuredOutput:Q0,structuredOutputSchemaDigest:N.schemaDigest}}}let K0=j.drainMcpCatalogChanges();if(K0.length>0){for(let D of K0)yield{kind:"mcp_catalog_changed",...D};let U=K0.map((D)=>{let f=[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=${X$(D.serverName)} ${f}`}).join(`
|
|
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.`},t6=[...C.compactedMessages,R8];f=C.success?"llm":"fallback",b=C.preTokens,_=C.postTokens,g=C.sampleAttempts,k=C.inputReductions,b0=C.messagesOmitted,L0=C.filesOmitted,v=C.imagesOmitted,y=C.fallbackTargetTokens,X0=C.fallbackMessagesOmitted,n=C.fallbackMessagesTruncated,F0=C.failureReason;let M8=await Q1($,J,C.summary,{trigger:"auto",reason:"turn_limit",strategy:f,preTokens:C.preTokens,preTokenSource:i0.source,...i0.estimatedPendingTokens!==void 0?{estimatedPendingTokens:i0.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:t6},{required:$.executionEngine!==void 0});i=await x6(C.memoryPlan,J,M8),J.messages=t6,L.replaceHistory(J.messages),y$.reset(),D=C.success?"completed":"fallback"}catch(P){if(P instanceof Y$)Q(P.usage),yield{kind:"token_usage",usage:F$(P.usage,$.chatService.getConfig().maxContextTokens??0,"auxiliary")};throw r.error("[Loop] 轮次上限压缩失败,停止继续执行:",P),P}finally{yield{kind:"compaction",phase:"end",reason:"turn_limit",outcome:D,strategy:f,preTokens:b,preTokenSource:l,estimatedPendingTokens:E,postTokens:_,sampleAttempts:g,inputReductions:k,messagesOmitted:b0,filesOmitted:L0,imagesOmitted:v,fallbackTargetTokens:y,fallbackMessagesOmitted:X0,fallbackMessagesTruncated:n,failureReason:F0,memory:i}}H=0;continue}return{success:!0,finalMessage:U?.reason||"已达到对话轮次上限,用户选择停止",metadata:{turnsCount:H,toolCallsCount:V.length,duration:Date.now()-K,tokensUsed:X}}}return{success:!1,error:{type:"max_turns_exceeded",message:h?`子代理已达到轮次上限 (${P0} 轮)。`:`已达到轮次上限 (${P0} 轮)。`},metadata:{turnsCount:H,toolCallsCount:V.length,duration:Date.now()-K,tokensUsed:X}}}if(await j.waitForMcpCatalogIdle(W?.signal),W?.signal?.aborted)return B(H,V.length,W.signal);let O=await t0?.drain()??[];if(O.length>0)Q0=void 0,a0=!1,l0=0,yield{kind:"steering_applied",...await E1(O),delivery:NZ?"current_turn":"next_turn",queue:await t0.getSnapshot()},a$=N?M6(L.getHistory(),N):void 0,Q0=a$?.output,a0=a$?.completed===!0,NZ=!0;else if(!NZ)return{success:!0,finalMessage:"",metadata:{turnsCount:0,toolCallsCount:0,duration:Date.now()-K}};if(N&&Q0&&a0){let U=JSON.stringify(Q0);return yield{kind:"structured_output",output:Q0,schemaDigest:N.schemaDigest},{success:!0,finalMessage:U,metadata:{turnsCount:H,toolCallsCount:V.length,duration:Date.now()-K,tokensUsed:X,structuredOutput:Q0,structuredOutputSchemaDigest:N.schemaDigest}}}let K0=j.drainMcpCatalogChanges();if(K0.length>0){for(let D of K0)yield{kind:"mcp_catalog_changed",...D};let U=K0.map((D)=>{let f=[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=${X$(D.serverName)} ${f}`}).join(`
|
|
142
142
|
`);L.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,7 +160,7 @@ MCP task ${X$(U.taskId)} for ${X$(U.serverName)}/${X$(U.toolName)} is ${U.status
|
|
|
160
160
|
|
|
161
161
|
<system-reminder>
|
|
162
162
|
${i2(T1,S.totalFailures)}
|
|
163
|
-
</system-reminder>`}:void 0,l6=A(),yZ=b$&&Y1(A$)?l6.filter((U)=>U.name!=="Task"):l6,M1=P$&&yZ.some((U)=>U.name===P$)?P$:void 0,k1=I0??M1,$1=k1?yZ.filter((U)=>U.name===k1):yZ;L.writeback();let f$=$.chatService.getConfig(),i6=$6(L.systemMessages,$1,f$.model),fZ=y$.project({history:L.getHistory(),pendingMessages:R1?[R1]:[],contextRevision:L.contextRevision,modelName:f$.model,requestProfile:i6}),EZ=F8({contextTokens:fZ.contextTokens,tokenSource:fZ.source,estimatedPendingTokens:fZ.estimatedPendingTokens,maxContextTokens:f$.maxContextTokens,maxOutputTokens:L8({maxContextTokens:f$.maxContextTokens,maxOutputTokens:f$.maxOutputTokens,configuredMaxOutputTokens:$.config.maxOutputTokens})}),x1=yield*N8($,J,H,EZ,W?.signal,R,A0,b8,Q);if(x1.kind==="failed")return u5(H,V.length,K,x1.phase,X);if(x1.kind==="snipped"||x1.kind==="compacted")L.replaceHistory(J.messages),y$.reset();if(EZ.phase==="handoff_band"){let U=await g5({deps:$,context:J,state:L,snapshot:EZ,attemptSpent:F1});if(U.kind==="failed"||U.kind==="suppressed")F1=!0}if(L.writeback(),H=T1,yield{kind:"turn_start",turn:H,maxTurns:P0},W?.signal?.aborted)return B(H-1,V.length,W.signal);if(R1)L.appendControl("user",R1);let r6=W?.stream!==!1,y8=I0;I0=void 0;let f8=L.historyLength+L.pending.length,n6=!h&&($.config.providerForegroundRecoveryMs??0)>0?{mode:"bounded_foreground",budgetMs:$.config.providerForegroundRecoveryMs}:void 0,SZ=J.subagentInfo?.providerAdmissionOwnerId??J.subagentInfo?.parentSessionId??J.sessionId,o6={providerSessionId:J.sessionId,...k1?{toolChoice:{type:"tool",toolName:k1}}:{},...n6?{providerRecovery:n6}:{},providerAdmission:{sessionId:J.sessionId,ownerId:SZ,requestClass:h?"background":"foreground"}},q,e0,Q$=new f6;try{if(r6)e0=new zZ($.toolExecutor,{sessionId:J.sessionId,turnId:W?.turnFinalization?.turnId,taskListId:J.taskListId,goalTaskListId:J.goalTaskListId,userId:J.userId||"default",modelId:$.config.currentModelId,providerAdmissionOwnerId:SZ,workspaceRoot:J.workspaceRoot||j0(),executionRoot:J.executionRoot??J.workspaceRoot??j0(),workspaceKind:J.workspaceKind??"local",environment:$.config.env,worktreeIsolationRequired:f1,worktreeActive:w0.has("EnterWorktree")&&!w0.has("ExitWorktree"),subagentType:J.subagentInfo?.subagentType,signal:W?.signal,confirmationHandler:J.confirmationHandler,permissionMode:J.permissionMode,toolRegistry:j,deferredToolManager:j.deferredToolManager},$.toolExecutor.getRegistry(),$.executionEngine?.getContextManager(),J.sessionId,z,J.subagentInfo,(U,D)=>{Q$.push({toolCall:U,update:D})},$.executionEngine!==void 0),e0.setAdmissionPolicy(m6),e0.setAdmissionRollback(A8),e0.setExecutionPolicy(c6),q=yield*x5($,L.toLLMMessages(),$1,W?.signal,o6,e0);else q=await $.chatService.chat(L.toLLMMessages(),$1,W?.signal,o6)}catch(U){if(S6(U)&&!T6(U)&&bZ.canAttempt()){r.warn("[Loop] 检测到 prompt_too_long 错误,尝试反应式压缩");let D=$.chatService.getConfig(),f=!1,b="failed",l,E,_,g,k,b0,L0,v,y,X0,n,F0,i;yield{kind:"compaction",phase:"start",reason:"context_limit"};try{e0?.discard();let P=await bZ.tryReactiveCompact(J.messages,{modelName:D.model,modelProvider:D.provider,maxContextTokens:D.maxContextTokens??0,apiKey:D.apiKey,baseURL:D.baseUrl,chatConfig:D,signal:W?.signal,activeTask:A0,workspaceRoot:J.workspaceRoot||j0(),workspaceAccess:J.workspaceKind==="acp-remote"?"none":"full",sessionId:J.sessionId});if(l=P.strategy,E=P.preTokens,_=P.postTokens,g=P.sampleAttempts,k=P.inputReductions,b0=P.messagesOmitted,L0=P.filesOmitted,v=P.imagesOmitted,y=P.fallbackTargetTokens,X0=P.fallbackMessagesOmitted,n=P.fallbackMessagesTruncated,F0=P.failureReason,P.usage)Q(P.usage),yield{kind:"token_usage",usage:F$(P.usage,D.maxContextTokens??0)};if(P.success&&P.strategy&&P.summary!==void 0&&P.preTokens!==void 0){let U0=await Q1($,J,P.summary,{trigger:"auto",reason:"context_limit",strategy:P.strategy,preTokens:P.preTokens,postTokens:P.postTokens,sampleAttempts:P.sampleAttempts,inputReductions:P.inputReductions,messagesOmitted:P.messagesOmitted,filesOmitted:P.filesOmitted,imagesOmitted:P.imagesOmitted,fallbackTargetTokens:P.fallbackTargetTokens,fallbackMessagesOmitted:P.fallbackMessagesOmitted,fallbackMessagesTruncated:P.fallbackMessagesTruncated,failureReason:P.failureReason,filesIncluded:P.filesIncluded,replacementMessages:P.messages},{required:$.executionEngine!==void 0});i=await x6(P.memoryPlan,J,U0),J.messages=P.messages,L.replaceHistory(J.messages),y$.reset(),I0=y8,b=P.strategy==="llm"?"completed":"fallback",f=!0,r.info("[Loop] 反应式压缩成功,重试 LLM 调用")}}catch(P){if(P instanceof Y$)Q(P.usage),yield{kind:"token_usage",usage:F$(P.usage,D.maxContextTokens??0)};if(C0(P))throw P;r.error("[Loop] 反应式压缩失败,不重放 Provider 请求",P)}finally{yield{kind:"compaction",phase:"end",reason:"context_limit",outcome:b,strategy:l,preTokens:E,postTokens:_,sampleAttempts:g,inputReductions:k,messagesOmitted:b0,filesOmitted:L0,imagesOmitted:v,fallbackTargetTokens:y,fallbackMessagesOmitted:X0,fallbackMessagesTruncated:n,failureReason:F0,memory:i}}if(f){H--;continue}}else if(S6(U)&&T6(U))r.warn("[Loop] prompt_too_long arrived after Provider output; refusing replay");else if(S6(U))r.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=L1(U.function.arguments);if(D===null)continue;G1(U.function.name,D),U.function.arguments=JSON.stringify(D)}if(bZ.reset(),R=Date.now(),q.usage)Q(q.usage),yield{kind:"token_usage",usage:F$(q.usage,$.currentModelMaxContextTokens)};y$.recordProviderUsage({usage:q.usage,contextRevision:L.contextRevision,historyLength:f8,modelName:f$.model,requestProfile:i6});let E8=q.usage?.completionTokens??0;if(AZ=ZJ(AZ,E8,o0>0),W?.signal?.aborted)return B(H-1,V.length,W.signal);if(!r6||!!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 I1=hZ(q.finishReason,o0,AZ),TZ=I1.action!=="none"&&Q0!==void 0&&N!==void 0&&(q.toolCalls?.length??0)===0;if(TZ){let U=await t0?.drainOrSeal();if(U&&U.messages.length>0){Q0=void 0,a0=!1,l0=0,L.appendAssistant({role:"assistant",content:q.content||"",reasoningContent:q.reasoningContent});let D=await v0($,J,q.content||"",z,q.reasoningContent);if(D)z=D;yield{kind:"steering_applied",...await E1(U.messages),delivery:"current_turn",queue:await t0.getSnapshot()};continue}C6=!0}if(I1.action==="recover"&&!TZ){let U=await p6(q);if(U.action==="continue")continue;if(U.action==="fail")return U.result;o0++,r.warn(`[Loop] Max output tokens hit (recovery ${o0}/3)`);let D={role:"assistant",content:q.content||"",reasoningContent:q.reasoningContent,tool_calls:q.toolCalls};L.appendToHistory(D);let f=await v0($,J,q.content||"",z,q.reasoningContent);if(f)z=f;let b={role:"user",metadata:f0,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."};L.appendToHistory(b);let l=await r0($,J,b.content,z,f0);if(l)z=l;continue}if(!TZ&&(I1.action==="truncated"||I1.action==="budget_stop")){let U=!N&&!q.toolCalls?.length?CZ(q.content,A0,$1.map((_)=>_.name),g1):{action:"none"};if(U.action==="fail"||M1)return z=await V0({deps:$,context:J,state:L,assistantContent:q.content||"",assistantReasoningContent:q.reasoningContent,lastMessageUuid:z}),{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:H,toolCallsCount:V.length,duration:Date.now()-K,tokensUsed:X,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:H,toolCallsCount:V.length,duration:Date.now()-K,tokensUsed:X,outputTruncated:!0}};let D=g6(),f=D?.finalMessage??q.content??"",b=await u(),l=D||b?{...D?.persistenceMetadata,...b?{turnFinalization:b}:{}}:void 0;L.appendAssistant({role:"assistant",content:f,reasoningContent:D?void 0:q.reasoningContent,tool_calls:D?void 0:q.toolCalls,...l?{metadata:c$(l)}:{}});let E=await v0($,J,f,z,D?void 0:q.reasoningContent,l);if(E)z=E;if(N&&!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:H,toolCallsCount:V.length,duration:Date.now()-K,tokensUsed:X,outputTruncated:!0,structuredOutputSchemaDigest:N.schemaDigest}};if(D)yield D.event;return{success:!0,finalMessage:f,metadata:{turnsCount:H,toolCallsCount:V.length,duration:Date.now()-K,tokensUsed:X,outputTruncated:!0,...D?.resultMetadata}}}if(!q.toolCalls||q.toolCalls.length===0){let U=F6(o,[],[]);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,l0=0,L.appendAssistant({role:"assistant",content:q.content||"",reasoningContent:q.reasoningContent});let I=await v0($,J,q.content||"",z,q.reasoningContent);if(I)z=I;yield{kind:"steering_applied",...await E1(D),delivery:"current_turn",queue:await t0.getSnapshot()};continue}if(N&&!Q0){if(q.finishReason!=="length")o0=0;if(z=await V0({deps:$,context:J,state:L,assistantContent:q.content||"",assistantReasoningContent:q.reasoningContent,lastMessageUuid:z}),l0>=R6)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:H,toolCallsCount:V.length,duration:Date.now()-K,tokensUsed:X,structuredOutputSchemaDigest:N.schemaDigest}};l0++;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.`;L.appendControl("user",{role:"user",content:I});let i0=await r0($,J,I,z,f0);if(i0)z=i0;continue}let f=CZ(q.content,A0,$1.map((I)=>I.name),H>=P0?g1:I6);if(!N&&f.action!=="none"){if(z=await V0({deps:$,context:J,state:L,assistantContent:q.content||"",assistantReasoningContent:q.reasoningContent,lastMessageUuid:z,...f.action==="retry"?{controlPrompt:f.prompt}:{}}),f.action==="fail")return{success:!1,error:{type:"intent_fulfillment_failed",message:f.message},metadata:{turnsCount:H,toolCallsCount:V.length,duration:Date.now()-K,tokensUsed:X}};I6++,P$=f.toolName&&!w0.has(f.toolName)?f.toolName:void 0;continue}if(M1)return z=await V0({deps:$,context:J,state:L,assistantContent:q.content||"",assistantReasoningContent:q.reasoningContent,lastMessageUuid:z}),{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:H,toolCallsCount:V.length,duration:Date.now()-K,tokensUsed:X}};let b=await p6(q);if(b.action==="continue")continue;if(b.action==="fail")return b.result;if(q.finishReason!=="length")o0=0;if(q.content&&n2(x,q.content)){z=await V0({deps:$,context:J,state:L,assistantContent:q.content||"",assistantReasoningContent:q.reasoningContent,lastMessageUuid:z,controlPrompt:`
|
|
163
|
+
</system-reminder>`}:void 0,l6=A(),yZ=b$&&Y1(A$)?l6.filter((U)=>U.name!=="Task"):l6,M1=P$&&yZ.some((U)=>U.name===P$)?P$:void 0,k1=I0??M1,$1=k1?yZ.filter((U)=>U.name===k1):yZ;L.writeback();let f$=$.chatService.getConfig(),i6=$6(L.systemMessages,$1,f$.model),fZ=y$.project({history:L.getHistory(),pendingMessages:R1?[R1]:[],contextRevision:L.contextRevision,modelName:f$.model,requestProfile:i6}),EZ=F8({contextTokens:fZ.contextTokens,tokenSource:fZ.source,estimatedPendingTokens:fZ.estimatedPendingTokens,maxContextTokens:f$.maxContextTokens,maxOutputTokens:L8({maxContextTokens:f$.maxContextTokens,maxOutputTokens:f$.maxOutputTokens,configuredMaxOutputTokens:$.config.maxOutputTokens})}),x1=yield*N8($,J,H,EZ,W?.signal,R,A0,b8,Q);if(x1.kind==="failed")return u5(H,V.length,K,x1.phase,X);if(x1.kind==="snipped"||x1.kind==="compacted")L.replaceHistory(J.messages),y$.reset();if(EZ.phase==="handoff_band"){let U=await g5({deps:$,context:J,state:L,snapshot:EZ,attemptSpent:F1});if(U.kind==="failed"||U.kind==="suppressed")F1=!0}if(L.writeback(),H=T1,yield{kind:"turn_start",turn:H,maxTurns:P0},W?.signal?.aborted)return B(H-1,V.length,W.signal);if(R1)L.appendControl("user",R1);let r6=W?.stream!==!1,y8=I0;I0=void 0;let f8=L.historyLength+L.pending.length,n6=!h&&($.config.providerForegroundRecoveryMs??0)>0?{mode:"bounded_foreground",budgetMs:$.config.providerForegroundRecoveryMs}:void 0,SZ=J.subagentInfo?.providerAdmissionOwnerId??J.subagentInfo?.parentSessionId??J.sessionId,o6={providerSessionId:J.sessionId,...k1?{toolChoice:{type:"tool",toolName:k1}}:{},...n6?{providerRecovery:n6}:{},providerAdmission:{sessionId:J.sessionId,ownerId:SZ,requestClass:h?"background":"foreground"}},q,e0,Q$=new f6;try{if(r6)e0=new zZ($.toolExecutor,{sessionId:J.sessionId,turnId:W?.turnFinalization?.turnId,taskListId:J.taskListId,goalTaskListId:J.goalTaskListId,userId:J.userId||"default",modelId:$.config.currentModelId,providerAdmissionOwnerId:SZ,workspaceRoot:J.workspaceRoot||j0(),executionRoot:J.executionRoot??J.workspaceRoot??j0(),workspaceKind:J.workspaceKind??"local",environment:$.config.env,worktreeIsolationRequired:f1,worktreeActive:w0.has("EnterWorktree")&&!w0.has("ExitWorktree"),subagentType:J.subagentInfo?.subagentType,signal:W?.signal,confirmationHandler:J.confirmationHandler,permissionMode:J.permissionMode,toolRegistry:j,deferredToolManager:j.deferredToolManager},$.toolExecutor.getRegistry(),$.executionEngine?.getContextManager(),J.sessionId,z,J.subagentInfo,(U,D)=>{Q$.push({toolCall:U,update:D})},$.executionEngine!==void 0),e0.setAdmissionPolicy(m6),e0.setAdmissionRollback(A8),e0.setExecutionPolicy(c6),q=yield*x5($,L.toLLMMessages(),$1,W?.signal,o6,e0);else q=await $.chatService.chat(L.toLLMMessages(),$1,W?.signal,o6)}catch(U){if(S6(U)&&!T6(U)&&bZ.canAttempt()){r.warn("[Loop] 检测到 prompt_too_long 错误,尝试反应式压缩");let D=$.chatService.getConfig(),f=!1,b="failed",l,E,_,g,k,b0,L0,v,y,X0,n,F0,i;yield{kind:"compaction",phase:"start",reason:"context_limit"};try{e0?.discard();let P=await bZ.tryReactiveCompact(J.messages,{modelName:D.model,modelProvider:D.provider,maxContextTokens:D.maxContextTokens??0,apiKey:D.apiKey,baseURL:D.baseUrl,chatConfig:D,signal:W?.signal,activeTask:A0,workspaceRoot:J.workspaceRoot||j0(),workspaceAccess:J.workspaceKind==="acp-remote"?"none":"full",sessionId:J.sessionId});if(l=P.strategy,E=P.preTokens,_=P.postTokens,g=P.sampleAttempts,k=P.inputReductions,b0=P.messagesOmitted,L0=P.filesOmitted,v=P.imagesOmitted,y=P.fallbackTargetTokens,X0=P.fallbackMessagesOmitted,n=P.fallbackMessagesTruncated,F0=P.failureReason,P.usage)Q(P.usage),yield{kind:"token_usage",usage:F$(P.usage,D.maxContextTokens??0,"auxiliary")};if(P.success&&P.strategy&&P.summary!==void 0&&P.preTokens!==void 0){let U0=await Q1($,J,P.summary,{trigger:"auto",reason:"context_limit",strategy:P.strategy,preTokens:P.preTokens,postTokens:P.postTokens,sampleAttempts:P.sampleAttempts,inputReductions:P.inputReductions,messagesOmitted:P.messagesOmitted,filesOmitted:P.filesOmitted,imagesOmitted:P.imagesOmitted,fallbackTargetTokens:P.fallbackTargetTokens,fallbackMessagesOmitted:P.fallbackMessagesOmitted,fallbackMessagesTruncated:P.fallbackMessagesTruncated,failureReason:P.failureReason,filesIncluded:P.filesIncluded,replacementMessages:P.messages},{required:$.executionEngine!==void 0});i=await x6(P.memoryPlan,J,U0),J.messages=P.messages,L.replaceHistory(J.messages),y$.reset(),I0=y8,b=P.strategy==="llm"?"completed":"fallback",f=!0,r.info("[Loop] 反应式压缩成功,重试 LLM 调用")}}catch(P){if(P instanceof Y$)Q(P.usage),yield{kind:"token_usage",usage:F$(P.usage,D.maxContextTokens??0,"auxiliary")};if(C0(P))throw P;r.error("[Loop] 反应式压缩失败,不重放 Provider 请求",P)}finally{yield{kind:"compaction",phase:"end",reason:"context_limit",outcome:b,strategy:l,preTokens:E,postTokens:_,sampleAttempts:g,inputReductions:k,messagesOmitted:b0,filesOmitted:L0,imagesOmitted:v,fallbackTargetTokens:y,fallbackMessagesOmitted:X0,fallbackMessagesTruncated:n,failureReason:F0,memory:i}}if(f){H--;continue}}else if(S6(U)&&T6(U))r.warn("[Loop] prompt_too_long arrived after Provider output; refusing replay");else if(S6(U))r.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=L1(U.function.arguments);if(D===null)continue;G1(U.function.name,D),U.function.arguments=JSON.stringify(D)}if(bZ.reset(),R=Date.now(),q.usage)Q(q.usage),yield{kind:"token_usage",usage:F$(q.usage,$.currentModelMaxContextTokens)};y$.recordProviderUsage({usage:q.usage,contextRevision:L.contextRevision,historyLength:f8,modelName:f$.model,requestProfile:i6});let E8=q.usage?.completionTokens??0;if(AZ=ZJ(AZ,E8,o0>0),W?.signal?.aborted)return B(H-1,V.length,W.signal);if(!r6||!!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 I1=hZ(q.finishReason,o0,AZ),TZ=I1.action!=="none"&&Q0!==void 0&&N!==void 0&&(q.toolCalls?.length??0)===0;if(TZ){let U=await t0?.drainOrSeal();if(U&&U.messages.length>0){Q0=void 0,a0=!1,l0=0,L.appendAssistant({role:"assistant",content:q.content||"",reasoningContent:q.reasoningContent});let D=await v0($,J,q.content||"",z,q.reasoningContent);if(D)z=D;yield{kind:"steering_applied",...await E1(U.messages),delivery:"current_turn",queue:await t0.getSnapshot()};continue}C6=!0}if(I1.action==="recover"&&!TZ){let U=await p6(q);if(U.action==="continue")continue;if(U.action==="fail")return U.result;o0++,r.warn(`[Loop] Max output tokens hit (recovery ${o0}/3)`);let D={role:"assistant",content:q.content||"",reasoningContent:q.reasoningContent,tool_calls:q.toolCalls};L.appendToHistory(D);let f=await v0($,J,q.content||"",z,q.reasoningContent);if(f)z=f;let b={role:"user",metadata:f0,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."};L.appendToHistory(b);let l=await r0($,J,b.content,z,f0);if(l)z=l;continue}if(!TZ&&(I1.action==="truncated"||I1.action==="budget_stop")){let U=!N&&!q.toolCalls?.length?CZ(q.content,A0,$1.map((_)=>_.name),g1):{action:"none"};if(U.action==="fail"||M1)return z=await V0({deps:$,context:J,state:L,assistantContent:q.content||"",assistantReasoningContent:q.reasoningContent,lastMessageUuid:z}),{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:H,toolCallsCount:V.length,duration:Date.now()-K,tokensUsed:X,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:H,toolCallsCount:V.length,duration:Date.now()-K,tokensUsed:X,outputTruncated:!0}};let D=g6(),f=D?.finalMessage??q.content??"",b=await u(),l=D||b?{...D?.persistenceMetadata,...b?{turnFinalization:b}:{}}:void 0;L.appendAssistant({role:"assistant",content:f,reasoningContent:D?void 0:q.reasoningContent,tool_calls:D?void 0:q.toolCalls,...l?{metadata:c$(l)}:{}});let E=await v0($,J,f,z,D?void 0:q.reasoningContent,l);if(E)z=E;if(N&&!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:H,toolCallsCount:V.length,duration:Date.now()-K,tokensUsed:X,outputTruncated:!0,structuredOutputSchemaDigest:N.schemaDigest}};if(D)yield D.event;return{success:!0,finalMessage:f,metadata:{turnsCount:H,toolCallsCount:V.length,duration:Date.now()-K,tokensUsed:X,outputTruncated:!0,...D?.resultMetadata}}}if(!q.toolCalls||q.toolCalls.length===0){let U=F6(o,[],[]);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,l0=0,L.appendAssistant({role:"assistant",content:q.content||"",reasoningContent:q.reasoningContent});let I=await v0($,J,q.content||"",z,q.reasoningContent);if(I)z=I;yield{kind:"steering_applied",...await E1(D),delivery:"current_turn",queue:await t0.getSnapshot()};continue}if(N&&!Q0){if(q.finishReason!=="length")o0=0;if(z=await V0({deps:$,context:J,state:L,assistantContent:q.content||"",assistantReasoningContent:q.reasoningContent,lastMessageUuid:z}),l0>=R6)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:H,toolCallsCount:V.length,duration:Date.now()-K,tokensUsed:X,structuredOutputSchemaDigest:N.schemaDigest}};l0++;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.`;L.appendControl("user",{role:"user",content:I});let i0=await r0($,J,I,z,f0);if(i0)z=i0;continue}let f=CZ(q.content,A0,$1.map((I)=>I.name),H>=P0?g1:I6);if(!N&&f.action!=="none"){if(z=await V0({deps:$,context:J,state:L,assistantContent:q.content||"",assistantReasoningContent:q.reasoningContent,lastMessageUuid:z,...f.action==="retry"?{controlPrompt:f.prompt}:{}}),f.action==="fail")return{success:!1,error:{type:"intent_fulfillment_failed",message:f.message},metadata:{turnsCount:H,toolCallsCount:V.length,duration:Date.now()-K,tokensUsed:X}};I6++,P$=f.toolName&&!w0.has(f.toolName)?f.toolName:void 0;continue}if(M1)return z=await V0({deps:$,context:J,state:L,assistantContent:q.content||"",assistantReasoningContent:q.reasoningContent,lastMessageUuid:z}),{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:H,toolCallsCount:V.length,duration:Date.now()-K,tokensUsed:X}};let b=await p6(q);if(b.action==="continue")continue;if(b.action==="fail")return b.result;if(q.finishReason!=="length")o0=0;if(q.content&&n2(x,q.content)){z=await V0({deps:$,context:J,state:L,assistantContent:q.content||"",assistantReasoningContent:q.reasoningContent,lastMessageUuid:z,controlPrompt:`
|
|
164
164
|
|
|
165
165
|
<system-reminder>
|
|
166
166
|
${o2()}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{uf as a,vf as b,wf as c}from"./chunk-
|
|
1
|
+
import{uf as a,vf as b,wf as c}from"./chunk-yc59atrw.js";import"./chunk-je908ygr.js";import"./chunk-7m1bf6zd.js";import"./chunk-v508x7cg.js";import"./chunk-5yyp6njq.js";import"./chunk-7ajvrtb3.js";import"./chunk-pfjg8bjg.js";import"./chunk-qpmvp4q2.js";import"./chunk-tm3789m3.js";import"./chunk-qdbbke8f.js";import"./chunk-wezr6wfq.js";import"./chunk-rmfzym94.js";import"./chunk-j89qk7bp.js";import"./chunk-0eajnhrj.js";import"./chunk-25ma8vb3.js";import"./chunk-ggdgk3gy.js";import"./chunk-ky592ay9.js";import"./chunk-n52n2w5v.js";import"./chunk-cjfb4kjp.js";export{a as validatePermissions,c as validateOutput,b as loadConfiguration};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{Ra as H}from"./chunk-
|
|
1
|
+
import{Ra as H}from"./chunk-p6g53dbp.js";import"./chunk-fdr4fcrf.js";import"./chunk-egss0m1x.js";import{Zf as $,dg as T}from"./chunk-7m1bf6zd.js";import"./chunk-v508x7cg.js";import"./chunk-5yyp6njq.js";import"./chunk-vnbyb9dq.js";import"./chunk-ys8gysg8.js";import"./chunk-pfjg8bjg.js";import"./chunk-qpmvp4q2.js";import"./chunk-tm3789m3.js";import{cj as k}from"./chunk-qdbbke8f.js";import"./chunk-wezr6wfq.js";import"./chunk-rmfzym94.js";import"./chunk-j89qk7bp.js";import"./chunk-0eajnhrj.js";import"./chunk-25ma8vb3.js";import"./chunk-ggdgk3gy.js";import"./chunk-ky592ay9.js";import"./chunk-n52n2w5v.js";import"./chunk-cjfb4kjp.js";import U from"os";import J from"path";function X(z){return typeof z==="string"?z:void 0}function N(z){if(!Array.isArray(z))return;let q=[];for(let K of z)if(typeof K==="string")q.push(K);else if(K!=null)q.push(String(K));return q}function b(){console.log(`
|
|
2
2
|
blade mcp
|
|
3
3
|
`),console.log(`管理 MCP 服务器
|
|
4
4
|
`),console.log("Commands:"),console.log(" blade mcp add <name> <commandOrUrl> [args...] 添加 MCP 服务器"),console.log(" blade mcp remove <name> 删除 MCP 服务器 [aliases: rm]"),console.log(" blade mcp list 列出所有 MCP 服务器并检查健康状态 [aliases: ls]"),console.log(" blade mcp get <name> 获取服务器详情"),console.log(" blade mcp login <name> 登录远程 MCP OAuth"),console.log(" blade mcp logout <name> 清除远程 MCP OAuth 凭证"),console.log(` blade mcp add-json <name> <json> 从 JSON 字符串添加服务器
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{tc as Xt,uc as En,vc as yn,wc as bn}from"./chunk-fdr4fcrf.js";import{Ah as Bt}from"./chunk-
|
|
1
|
+
import{tc as Xt,uc as En,vc as yn,wc as bn}from"./chunk-fdr4fcrf.js";import{Ah as Bt}from"./chunk-vnbyb9dq.js";import{Fh as xt,Gh as vi,Hh as sn,Ih as zt,Jh as U,Kh as en,Lh as gt,Mh as mt,Oh as rn,Ph as Tn,Qh as B,Rh as dn,Sh as on,Th as pn,Uh as lt,Vh as un,Wh as cn,Xh as Mn,Zh as S,ai as wn,bi as Gt,ci as Ut,di as h,ei as Ht}from"./chunk-pfjg8bjg.js";import{cj as It}from"./chunk-qdbbke8f.js";import{Gj as X,Ij as x}from"./chunk-rmfzym94.js";import{Yj as tn,Zj as nn}from"./chunk-25ma8vb3.js";import{Nk as ns}from"./chunk-cjfb4kjp.js";import{EventEmitter as fs}from"events";import Un from"node:path";function hn(t){if(t===void 0)return"undefined";if(typeof t==="string")return t;try{let i=JSON.stringify(t);return i===void 0?String(t):i}catch{return String(t)}}function An(t){let i=t;switch(t.code){case"type":return`类型错误:${t.message}`;case"required":return"缺少必需参数";case"minLength":return`字符串过短:${t.message}`;case"maxLength":return`字符串过长:${t.message}`;case"minimum":case"exclusiveMinimum":return`数值太小:${t.message}`;case"maximum":case"exclusiveMaximum":return`数值太大:${t.message}`;case"minItems":return`数组元素过少:${t.message}`;case"maxItems":return`数组元素过多:${t.message}`;case"format":return`格式错误:${t.message}`;case"enum":return`必须是枚举允许的值之一:${t.message}`;case"const":return`必须是指定的字面量值:${t.message}`;case"additionalProperties":case"unevaluatedProperties":return`包含未知参数:${t.message}`;case"anyOf":case"oneOf":return"不符合任何有效的类型定义";case"~refine":return t.message||"自定义验证失败";default:return t.message||`验证失败:${hn(i)}`}}class Jt extends Error{issues;type;constructor(t,i,n="validation_error"){super(t);this.issues=i;this.type=n;this.name="ToolValidationError"}}function Vt(t,i){let n=X(t,i);if(n.success)return n.data;let s=n.error.issues.map((r)=>({field:r.path.length>0?r.path.join("."):"root",message:An(r),value:r.value})),e=s.length===1?`参数验证失败 [${s[0].field}]: ${s[0].message}`:`参数验证失败 (${s.length} 个错误):
|
|
2
2
|
${s.map((r)=>` - ${r.field}: ${r.message}`).join(`
|
|
3
3
|
`)}`;throw new Jt(e,s)}function st(t){if(!t||typeof t!=="object")return;let i=t;if(i.type==="object"&&i.properties)i.required??=[],i.additionalProperties??=!1;for(let n of Object.values(i))if(Array.isArray(n))for(let s of n)st(s);else st(n)}function et(t){let i=JSON.parse(JSON.stringify(t,(n,s)=>n.startsWith("~")?void 0:s));return st(i),i}class rt{toolName;params;executeFn;descriptionFn;affectedPathsFn;isRetrySafe;constructor(t,i,n,s,e,r=!1){this.toolName=t;this.params=i;this.executeFn=n;this.descriptionFn=s;this.affectedPathsFn=e;this.isRetrySafe=r}getDescription(){if(this.descriptionFn)return this.descriptionFn(this.params);return`执行工具: ${this.toolName}`}getAffectedPaths(){if(this.affectedPathsFn)return this.affectedPathsFn(this.params);return[]}async execute(t,i,n){let s={signal:t,updateOutput:i,...n};return this.executeFn(this.params,s)}}function jt(t){return{name:t.name,displayName:t.displayName,kind:t.kind,isConcurrencySafe:t.isConcurrencySafe??!1,isRetrySafe:t.isRetrySafe??!1,parallelism:t.parallelism??(t.isConcurrencySafe?"shared":"exclusive"),strict:t.strict??!1,description:t.description,version:t.version||"1.0.0",category:t.category,tags:t.tags||[],getFunctionDeclaration(){let i=et(t.schema),n=t.description.short;if(t.description.long)n+=`
|
|
4
4
|
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import"./chunk-v508x7cg.js";import{Si as Q}from"./chunk-
|
|
2
|
-
`);try{let{rebuildProjectionIndex:z}=await import("./chunk-2xpjy0ef.js"),{SessionService:B}=await import("./chunk-
|
|
1
|
+
import"./chunk-v508x7cg.js";import{Si as Q}from"./chunk-pfjg8bjg.js";import"./chunk-qpmvp4q2.js";import"./chunk-tm3789m3.js";import{cj as L}from"./chunk-qdbbke8f.js";import"./chunk-wezr6wfq.js";import"./chunk-rmfzym94.js";import"./chunk-j89qk7bp.js";import"./chunk-0eajnhrj.js";import"./chunk-25ma8vb3.js";import"./chunk-ggdgk3gy.js";import"./chunk-ky592ay9.js";import"./chunk-n52n2w5v.js";import{Nk as F}from"./chunk-cjfb4kjp.js";var K=[22,19,0];function T(G){let A=/^v?(\d+)\.(\d+)\.(\d+)/.exec(G);if(!A)return!1;let H=A.slice(1).map(Number);for(let z=0;z<K.length;z++){let B=H[z]??0,J=K[z];if(B!==J)return B>J}return!0}var X={command:"doctor",describe:"Check the health of your Blade installation",builder:(G)=>G.option("rebuild-index",{type:"boolean",default:!1,describe:"Rebuild the SQLite session index from JSONL transcripts"}),handler:async(G)=>{if(G.rebuildIndex){console.log(`Rebuilding session index from JSONL transcripts...
|
|
2
|
+
`);try{let{rebuildProjectionIndex:z}=await import("./chunk-2xpjy0ef.js"),{SessionService:B}=await import("./chunk-v2bcvfch.js"),J=await z(B.projectionDeriverForSearch());if(J===null)console.log("[WARN] Session index unavailable (SQLite driver missing); reads fall back to JSONL scan.");else console.log(`[OK] Session index rebuilt: ${J} session(s) indexed.`)}catch(z){console.log("[FAIL] Session index rebuild failed"),console.log(` Error: ${z instanceof Error?z.message:"未知错误"}`),process.exit(1)}return}console.log(`Running Blade health check...
|
|
3
3
|
`);let A=0;try{await Q.getInstance().initialize(),console.log("[OK] Configuration: OK")}catch(z){console.log("[FAIL] Configuration: FAILED"),console.log(` Error: ${z instanceof Error?z.message:"未知错误"}`),A++}let H=process.version;if(T(H))console.log(`[OK] Node.js version: ${H}`);else console.log(`[WARN] Node.js version: ${H} (required: >=22.19.0)`),A++;try{let z=await import("fs/promises"),B=L();await z.access(B,(await import("fs")).constants.R_OK|(await import("fs")).constants.W_OK),console.log("[OK] File system permissions: OK")}catch(z){console.log("[FAIL] File system permissions: FAILED"),console.log(" Error: Cannot read/write in current directory"),A++}try{await import("ink"),console.log("[OK] Dependencies: OK")}catch(z){console.log("[FAIL] Dependencies: FAILED"),console.log(" Error: Missing required dependencies"),A++}if(console.log(`
|
|
4
4
|
Health Check Summary:`),A===0)console.log("All checks passed! Blade is ready to use.");else console.log(`Warning: Found ${A} issue(s). Please resolve them for optimal performance.`),process.exit(1)}};export{T as isSupportedNodeVersion,X as doctorCommands};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{Vi as K}from"./chunk-qpmvp4q2.js";import{Wi as wt,Xi as ft}from"./chunk-tm3789m3.js";import{cj as I}from"./chunk-qdbbke8f.js";import{Aj as yt,dj as tt,ej as Dt,fj as Bt,jj as Gt,kj as et,lj as Kt,mj as Ht,nj as Yt,oj as cn,pj as Ft,qj as qt,rj as Mt,sj as Vt,tj as Jt,uj as _t,vj as Qt,wj as jt,xj as Wt,yj as Zt,zj as kt}from"./chunk-wezr6wfq.js";import{Ej as Un,Gj as bn,Hj as _n,Ij as T}from"./chunk-rmfzym94.js";import{Nj as zt,Qj as v}from"./chunk-j89qk7bp.js";import{Yj as xn,Zj as Cn}from"./chunk-
|
|
1
|
+
import{Vi as K}from"./chunk-qpmvp4q2.js";import{Wi as wt,Xi as ft}from"./chunk-tm3789m3.js";import{cj as I}from"./chunk-qdbbke8f.js";import{Aj as yt,dj as tt,ej as Dt,fj as Bt,jj as Gt,kj as et,lj as Kt,mj as Ht,nj as Yt,oj as cn,pj as Ft,qj as qt,rj as Mt,sj as Vt,tj as Jt,uj as _t,vj as Qt,wj as jt,xj as Wt,yj as Zt,zj as kt}from"./chunk-wezr6wfq.js";import{Ej as Un,Gj as bn,Hj as _n,Ij as T}from"./chunk-rmfzym94.js";import{Nj as zt,Qj as v}from"./chunk-j89qk7bp.js";import{Yj as xn,Zj as Cn}from"./chunk-25ma8vb3.js";import{dk as a}from"./chunk-ggdgk3gy.js";import{gk as Ln}from"./chunk-n52n2w5v.js";var lt=/^[\x21\x23-\x5b\x5d-\x7e]+$/;function vt(n){return n==="127.0.0.1"||n==="[::1]"||n.toLowerCase()==="localhost"}function p(n,t="MCP OAuth URL"){let e=new URL(n);if(e.username||e.password)throw Error(`${t} must not contain credentials`);if(e.protocol!=="https:"&&!(e.protocol==="http:"&&vt(e.hostname)))throw Error(`${t} requires HTTPS; HTTP is allowed only for loopback servers`);return e}var B=async(n,t)=>{p(n,"MCP OAuth request URL");let e=await fetch(n,{...t,redirect:"manual"});if(e.status>=300&&e.status<400)throw await e.body?.cancel(),Error("MCP OAuth network requests must not follow redirects");return e};function nn(n){let t=n.oauth;if(!t)return;let e=t;for(let E of["clientSecret","authorizationUrl","tokenUrl","redirectUri"])if(e[E]!==void 0)throw Error(`MCP OAuth "${E}" is not supported; use standards-based discovery`);if(t.enabled!==!0)return{enabled:!1};if(n.type!=="http"&&n.type!=="sse")throw Error("MCP OAuth is supported only for HTTP and SSE transports");if(!n.url)throw Error("MCP OAuth requires an MCP server URL");if(p(n.url,"MCP OAuth server URL"),Object.keys(n.headers??{}).find((E)=>E.toLowerCase()==="authorization"))throw Error("MCP OAuth cannot be combined with a configured Authorization header");let _=t.clientId?.trim();if(_&&_.length>4096)throw Error("MCP OAuth clientId exceeds 4096 characters");let S=t.scopes?.map((E)=>E.trim());if(S){if(S.length>32)throw Error("MCP OAuth supports at most 32 scopes");if(S.some((E)=>!E||E.length>128||!lt.test(E)))throw Error("MCP OAuth scopes contain an invalid value");if(new Set(S).size!==S.length)throw Error("MCP OAuth scopes must not contain duplicates")}let r=t.callbackPort;if(r!==void 0&&(!Number.isInteger(r)||r<1024||r>65535))throw Error("MCP OAuth callbackPort must be between 1024 and 65535");return{enabled:!0,..._?{clientId:_}:{},...S?.length?{scopes:S}:{},...r!==void 0?{callbackPort:r}:{}}}import{randomUUID as Sn}from"node:crypto";import Te from"node:http";import{auth as dn}from"@modelcontextprotocol/sdk/client/auth.js";import se from"open";import{createHash as ne,randomUUID as te}from"node:crypto";import{constants as tn,promises as b}from"node:fs";import en from"node:path";import ee from"write-file-atomic";var Nn=1,Me=1048576,_e=5000,re=50,Se=/^[a-f0-9]{64}$/,Ee=T.Object({client_id:T.String({minLength:1,maxLength:4096})},{additionalProperties:!0}),ue=T.Object({access_token:T.String({minLength:1,maxLength:65536}),token_type:T.String({minLength:1,maxLength:64}),expires_in:T.Optional(T.Number({minimum:0})),refresh_token:T.Optional(T.String({minLength:1,maxLength:65536})),scope:T.Optional(T.String({maxLength:16384})),id_token:T.Optional(T.String({minLength:1,maxLength:262144}))},{additionalProperties:!1}),oe=T.Unsafe({type:"object",properties:{authorizationServerUrl:T.String({format:"uri"}),resourceMetadataUrl:T.Optional(T.String({format:"uri"})),resourceMetadata:T.Optional(T.Unknown()),authorizationServerMetadata:T.Optional(T.Unknown())},required:["authorizationServerUrl"],additionalProperties:!1}),an=T.Object({serverUrl:T.String({format:"uri"}),clientId:T.Optional(T.String({minLength:1,maxLength:4096})),clientInformation:T.Optional(Ee),tokens:T.Optional(ue),tokenExpiresAt:T.Optional(T.Number({minimum:0})),discoveryState:T.Optional(oe),updatedAt:T.String({format:"date-time"})},{additionalProperties:!1}),gn=T.Object({version:T.Literal(Nn),credentials:T.Record(T.String(),an)},{additionalProperties:!1});function G(n,t){return n instanceof Error&&"code"in n&&n.code===t}function me(n){if(!Number.isInteger(n)||n<=0)return!1;try{return process.kill(n,0),!0}catch(t){return G(t,"EPERM")}}function Mn(n){return structuredClone(n)}function In(n){if(Object.keys(n.credentials).some((t)=>!Se.test(t)))throw Error("MCP OAuth credential store contains an invalid identity")}function H(n){let t=new URL(n);return t.hash="",t.toString()}function rn(n,t,e=[]){return ne("sha256").update(JSON.stringify({serverUrl:H(n),clientId:t?.trim()||null,scopes:[...e].sort()})).digest("hex")}class f{static locks=new K;stateRoot;tokenFilePath;constructor(n=Ln()){this.stateRoot=en.join(n,"mcp"),this.tokenFilePath=en.join(this.stateRoot,"oauth-credentials.json")}static coordinationStatsForTests(){return this.locks.getStats()}async getCredential(n){return f.locks.runExclusive(this.tokenFilePath,async()=>{let e=(await this.readStore()).credentials[n];return e?Mn(e):null})}async updateCredential(n,t){return this.runMutation(async(e)=>{let M=e.credentials[n],_=await t(M?Mn(M):null);if(_)e.credentials[n]=_n(an,_);else delete e.credentials[n];return _?Mn(e.credentials[n]):null})}async deleteCredential(n){await this.updateCredential(n,()=>null)}async listCredentialIds(){return f.locks.runExclusive(this.tokenFilePath,async()=>Object.keys((await this.readStore()).credentials).sort())}async runMutation(n){return f.locks.runExclusive(this.tokenFilePath,async()=>{let t=await this.acquireStoreLock();try{let e=await this.readStore(),M=await n(e);return await this.writeStore(e),M}finally{await t()}})}async ensureStateRoot(){await b.mkdir(this.stateRoot,{recursive:!0,mode:448});let n=await b.lstat(this.stateRoot);if(!n.isDirectory()||n.isSymbolicLink())throw Error("MCP OAuth credential root must be a regular directory");if(process.getuid&&n.uid!==process.getuid())throw Error("MCP OAuth credential root must be owned by the current user");if((n.mode&63)!==0)throw Error("MCP OAuth credential root permissions must not allow group access")}async readStore(){try{let n=await b.lstat(this.tokenFilePath);if(!n.isFile()||n.isSymbolicLink())throw Error("MCP OAuth credential store must be a regular file");if(process.getuid&&n.uid!==process.getuid())throw Error("MCP OAuth credential store must be owned by the current user");if((n.mode&511)!==384)throw Error("MCP OAuth credential store permissions must be 0600");if(n.size>Me)throw Error("MCP OAuth credential store exceeds the 1 MiB limit");let t=JSON.parse(await b.readFile(this.tokenFilePath,"utf8")),e=bn(gn,t);if(!e.success)throw Error("MCP OAuth credential store has an invalid schema");return In(e.data),e.data}catch(n){if(G(n,"ENOENT"))return{version:Nn,credentials:{}};throw n}}async writeStore(n){await this.ensureStateRoot();let t=_n(gn,n);In(t),await ee(this.tokenFilePath,`${JSON.stringify(t,null,2)}
|
|
2
2
|
`,{mode:384,encoding:"utf8"}),await b.chmod(this.tokenFilePath,384)}async acquireStoreLock(){await this.ensureStateRoot();let n=en.join(this.stateRoot,".oauth-credentials.lock"),t=te(),e=Date.now()+_e;while(Date.now()<e)try{let M=await b.open(n,tn.O_CREAT|tn.O_EXCL|tn.O_WRONLY,384);return await M.writeFile(`${JSON.stringify({version:1,pid:process.pid,token:t,createdAt:new Date().toISOString()})}
|
|
3
3
|
`,"utf8"),await M.close(),async()=>{try{if(JSON.parse(await b.readFile(n,"utf8")).token===t)await b.unlink(n)}catch(_){if(!G(_,"ENOENT"))throw _}}}catch(M){if(!G(M,"EEXIST"))throw M;await this.removeDeadLock(n),await new Promise((_)=>setTimeout(_,re))}throw Error("MCP OAuth credential store is busy; retry the operation")}async removeDeadLock(n){let t=await b.lstat(n);if(!t.isFile()||t.isSymbolicLink())throw Error("MCP OAuth credential lock must be a regular file");if(process.getuid&&t.uid!==process.getuid()||(t.mode&511)!==384)throw Error("MCP OAuth credential lock ownership or permissions are invalid");let e=JSON.parse(await b.readFile(n,"utf8"));if(typeof e.pid!=="number"||!Number.isInteger(e.pid)||e.pid<=0)throw Error("MCP OAuth credential lock owner is invalid");if(!me(e.pid))await b.unlink(n)}}var wn="127.0.0.1",fn=7777,Pn="/oauth/callback",Ae=300000;class En extends Error{constructor(n){super(`MCP server "${n}" requires OAuth authorization; run "blade mcp login ${n}" or use the Web MCP panel`);this.name="McpOAuthAuthorizationRequiredError"}}class hn extends Error{constructor(n){super(`MCP OAuth credentials are unavailable in this runtime for server "${n}"`);this.name="McpOAuthUnavailableError"}}function ce(n){let t=n?"Authentication complete":"Authentication failed";return`<!doctype html>
|
|
4
4
|
<html lang="en">
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{Qf as N}from"./chunk-
|
|
1
|
+
import{Qf as N}from"./chunk-7m1bf6zd.js";import{Ah as $}from"./chunk-vnbyb9dq.js";import{cj as _}from"./chunk-qdbbke8f.js";import{Cj as Y,Ej as Z}from"./chunk-rmfzym94.js";function X(){if(process.stdin.isTTY&&typeof process.stdin.setRawMode==="function")try{process.stdin.setRawMode(!1)}catch{}process.stdout.write("\x1B[<u"),process.stdout.write("\x1B[>4;0m"),process.stdout.write("\x1B[?2004l"),process.stdout.write("\x1B[?1004l"),process.stdout.write("\x1B[?1l\x1B>"),process.stdout.write("\x1B[?25h"),process.stdout.write("\x1B[0m")}var z=Z("Service");function E(b){switch(b){case"SIGINT":return"ctrl_c";case"esc":return"esc";case"uncaughtException":case"unhandledRejection":return"error";case"SIGTERM":case"normal":default:return"user_exit"}}class B{static instance=null;cleanupHandlers=[];isShuttingDown=!1;initialized=!1;lastSigintTime=0;SIGINT_DOUBLE_CLICK_WINDOW=3000;constructor(){}static getInstance(){if(!B.instance)B.instance=new B;return B.instance}initialize(){if(this.initialized){z.debug("[GracefulShutdown] 已初始化,跳过重复初始化");return}process.on("uncaughtException",(b)=>{this.handleFatalError("uncaughtException",b)}),process.on("unhandledRejection",(b)=>{let q=b instanceof Error?b:Error(String(b));this.handleFatalError("unhandledRejection",q)}),process.on("SIGTERM",()=>{z.info("[GracefulShutdown] 收到 SIGTERM 信号"),this.shutdown("SIGTERM",0)}),process.on("SIGINT",()=>{let b=Date.now();if(b-this.lastSigintTime<this.SIGINT_DOUBLE_CLICK_WINDOW)z.info("[GracefulShutdown] 收到第二次 SIGINT 信号,执行退出"),this.shutdown("SIGINT",0);else z.info("[GracefulShutdown] 收到第一次 SIGINT 信号,再按一次退出"),this.lastSigintTime=b,console.log(`
|
|
2
2
|
再按一次 Ctrl+C 退出
|
|
3
3
|
`)}),this.initialized=!0,z.debug("[GracefulShutdown] 全局错误处理器已初始化")}registerCleanup(b){return this.cleanupHandlers.push(b),z.debug(`[GracefulShutdown] 注册清理函数,当前共 ${this.cleanupHandlers.length} 个`),()=>{let q=this.cleanupHandlers.indexOf(b);if(q!==-1)this.cleanupHandlers.splice(q,1),z.debug(`[GracefulShutdown] 取消注册清理函数,剩余 ${this.cleanupHandlers.length} 个`)}}handleFatalError(b,q){if(this.isShuttingDown){console.error(`[GracefulShutdown] 退出过程中发生额外错误 (${b}):`,q);return}if(console.error(""),console.error("═".repeat(60)),console.error(`Uncaught error (${b})`),console.error("═".repeat(60)),console.error(""),console.error("错误信息:",q.message),console.error(""),q.stack)console.error("堆栈跟踪:"),console.error(q.stack);console.error(""),console.error("═".repeat(60)),console.error(""),this.shutdown(b,1)}async shutdown(b,q=0){if(this.isShuttingDown){z.debug("[GracefulShutdown] 已在退出过程中,跳过重复退出");return}this.isShuttingDown=!0;try{N().command.actions.abort("process-shutdown")}catch(A){z.warn("[GracefulShutdown] Failed to abort the active command",A)}z.info(`[GracefulShutdown] 开始优雅退出 (原因: ${b})`);let Q=setTimeout(()=>{X(),process.exit(q)},5000);Q.unref?.();let U=4000,K;try{await Promise.race([this.runCleanupHandlers(),new Promise((A,J)=>{K=setTimeout(()=>{J(Error(`清理超时 (${U}ms)`))},U),K.unref?.()})])}catch(A){console.error("[GracefulShutdown] 清理过程中发生错误:",A)}finally{if(K)clearTimeout(K)}try{let A=$.getInstance(),J=N(),V=J.session?.sessionId||"unknown",W=J.session?.workspaceRoot||_();if(A.isEnabled(W,V)){let v=J.config?.config?.permissionMode||"default";await A.executeSessionEndHooks(E(b),{projectDir:W,sessionId:V,permissionMode:v})}}catch(A){console.error("[GracefulShutdown] SessionEnd hooks 执行失败:",A)}try{await Y()}catch{}clearTimeout(Q),X(),setTimeout(()=>{process.exit(q)},100)}async runCleanupHandlers(){let b=[...this.cleanupHandlers].reverse();for(let q of b)try{let F=q();if(F instanceof Promise)await F}catch(F){console.error("[GracefulShutdown] 清理函数执行失败:",F)}}isExiting(){return this.isShuttingDown}reset(){this.isShuttingDown=!1,this.cleanupHandlers=[],this.initialized=!1}}var O=()=>{return B.getInstance()},y=(b)=>{return O().registerCleanup(b)},j=()=>{O().initialize()},C=(b=0)=>{O().shutdown("normal",b)};
|
|
4
4
|
export{O as yf,y as zf,j as Af,C as Bf};
|
|
@@ -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-g88adq1a.js";import{j as o1}from"./chunk-hnvvve5d.js";import{v as a0,w as y2}from"./chunk-zh4w88j6.js";import{A as m0,x as g2,y as p2,z as v2}from"./chunk-s8cx6pzp.js";import{B as C2,C as U$,D as H$,E as F$,F as z0,G as N$}from"./chunk-0h301azx.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-0qfm5awe.js";import{La as q$,Ra as uO}from"./chunk-p6g53dbp.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-9fyjyk2f.js";import{Kb as dO,Lb as a,Nb as P,Ob as x2,Zb as M4,ic as y0}from"./chunk-m7cv44cg.js";import{tc as T4}from"./chunk-fdr4fcrf.js";import{$c as B4,Dd as w2,Jc as V2,Nd as A1,Od as h0,Tc as z2,Vd as I1,Wd as I4,Xd as R1,Zd as o0,_c as G2,ad as W2,ae as D4,bd as D1,cd as K2,fd as U4,fe as N2,ge as x4,he as L4,ie as g,sd as _2}from"./chunk-r2ev8kdg.js";import{Ge as U2,Ne as H2,Oe as F2}from"./chunk-ztreczac.js";import{hf as L3,lf as M3,mf as A3,nf as j3,of as b3,pf as y4,qf as T3,rf as I3}from"./chunk-p6586ftx.js";import{Qf as r3,Uf as MO,Yf as f$,dg as nO}from"./chunk-7m1bf6zd.js";import{eg as c1}from"./chunk-5yyp6njq.js";import{xg as J2}from"./chunk-zfxcef0z.js";import{zg as B1}from"./chunk-x5f2d1n2.js";import{$g as X2,Ig as e3,Mg as s2,Qg as H1,Rg as F1,Vg as B5,Yg as eO,Zg as N1,bh as s4}from"./chunk-sqrhdczm.js";import{uh as P$,vh as Y2}from"./chunk-1cy4ab77.js";import{Ah as l0,zh as b$}from"./chunk-vnbyb9dq.js";import{Ai as Z2,Ni as T$,Sh as R$,Si as U1,gi as s$,ji as r$,li as e$,mi as O2,ni as h$,oi as y$,pi as K$,vi as $2,yi as Q2}from"./chunk-pfjg8bjg.js";import{Vi as F4}from"./chunk-qpmvp4q2.js";import{Xi as a1,_i as N4}from"./chunk-tm3789m3.js";import{cj as GO}from"./chunk-qdbbke8f.js";import{Ej as ZO,Gj as y,Ij as G,Jj as oO,Lj as zO}from"./chunk-rmfzym94.js";import{Qj as f0}from"./chunk-j89qk7bp.js";import{Sj as C$,Tj as o$,Vj as S$,Wj as t$}from"./chunk-0eajnhrj.js";import{Yj as i0}from"./chunk-25ma8vb3.js";import{dk as t4}from"./chunk-ggdgk3gy.js";import{Ak as wO,Ck as g1,Kk as L$,gk as l1}from"./chunk-n52n2w5v.js";import{Nk as a4}from"./chunk-cjfb4kjp.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{$e as q1,Ae as n2,Be as U1,Ce as A0,De as B1,Ee as H1,Ge as d2,Ne as i2,Oe as C0,Ve as p_,Xe as N1,Ze as r2,_e as o2,af as a2,pe as u2,qe as e,re as h2,se as Z1,te as l2,ue as v,ve as G1,we as c2,xe as p2,ye as V1,ze as L1}from"./chunk-ztreczac.js";import{wg as o_}from"./chunk-zfxcef0z.js";import{sh as a_}from"./chunk-1cy4ab77.js";import{Wi as v2,Xi as P2,Yi as x_,Zi as Q0,_i as w_}from"./chunk-tm3789m3.js";import{cj as f1}from"./chunk-qdbbke8f.js";import{Ej as H0}from"./chunk-rmfzym94.js";import{Rj as i_,Uj as r_}from"./chunk-0eajnhrj.js";import{Yj as __}from"./chunk-
|
|
1
|
+
import{$e as q1,Ae as n2,Be as U1,Ce as A0,De as B1,Ee as H1,Ge as d2,Ne as i2,Oe as C0,Ve as p_,Xe as N1,Ze as r2,_e as o2,af as a2,pe as u2,qe as e,re as h2,se as Z1,te as l2,ue as v,ve as G1,we as c2,xe as p2,ye as V1,ze as L1}from"./chunk-ztreczac.js";import{wg as o_}from"./chunk-zfxcef0z.js";import{sh as a_}from"./chunk-1cy4ab77.js";import{Wi as v2,Xi as P2,Yi as x_,Zi as Q0,_i as w_}from"./chunk-tm3789m3.js";import{cj as f1}from"./chunk-qdbbke8f.js";import{Ej as H0}from"./chunk-rmfzym94.js";import{Rj as i_,Uj as r_}from"./chunk-0eajnhrj.js";import{Yj as __}from"./chunk-25ma8vb3.js";import{Ak as M0,Bk as c_,Ck as A,Dk as P,Ek as I,Fk as E1,Gk as F1,Hk as M_,Ik as z1,Jk as b1,Kk as q_,gk as h,qk as o,rk as p,sk as S2,tk as n,uk as d,vk as I2,wk as K0,xk as Y1,yk as m2,zk as K_}from"./chunk-n52n2w5v.js";import{readdir as b_,readFile as V_,rm as f_,stat as E0}from"node:fs/promises";import*as N from"node:path";import{nanoid as m}from"nanoid";import{createHash as F4,randomUUID as z4}from"node:crypto";import*as W_ from"node:fs/promises";import*as W0 from"node:path";import D4 from"proper-lockfile";function cX(_){return Object.freeze({kind:"local",root:_})}function pX(_,X){let $=o(X);if(p($.collisionIdentity)!==_)throw Error("ACP remote workspace durable state is invalid");return Object.freeze({kind:"acp-remote",root:_,descriptor:$})}function nX(_,X){return _.kind==="acp-remote"?`${_.kind}\x00${_.root}\x00${_.descriptor.exactIdentity}\x00${X}`:`${_.kind}\x00${_.root}\x00${X}`}async function H_(_,X){if(_.kind==="local")return X(K_(_.root));return n(_.root,($)=>X(String($),$))}async function dX(_,X,$){return H_(_,(W,J)=>$(J?{storageRoot:W,transcriptPath:I(J,X),inboxPath:F1(J,X),goalPath:z1(J,X),remoteScope:J}:{storageRoot:W,transcriptPath:P(_.root,X),inboxPath:E1(_.root,X),goalPath:M_(_.root,X)}))}import{execFileSync as T4}from"node:child_process";import{createHash as C4}from"node:crypto";import{readFileSync as K4}from"node:fs";var M4=/^[a-f0-9]{64}$/;function D1(_){if(!_||typeof _!=="object")return!1;let X=_;return(X.platform==="linux"||X.platform==="darwin"||X.platform==="win32")&&typeof X.fingerprint==="string"&&M4.test(X.fingerprint)}var R1={readFile:(_)=>K4(_,"utf8"),execFile:(_,X)=>T4(_,X,{encoding:"utf8",timeout:_==="powershell.exe"?3000:2000,windowsHide:!0})},A4=(_)=>{try{return process.kill(_,0),!0}catch(X){return X instanceof Error&&"code"in X&&X.code==="EPERM"}};function x0(_,X){return{platform:_,fingerprint:C4("sha256").update(`${_}\x00${X}`).digest("hex")}}function E4(_,X){let $=X.readFile(`/proc/${_}/stat`).trim(),W=$.lastIndexOf(")");if(W<0)throw Error("Invalid /proc process stat");let O=$.slice(W+2).split(/\s+/)[19];if(!O||!/^\d+$/.test(O))throw Error("Missing process start ticks");return O}function m_(_,X=process.platform,$=R1){if(!Number.isInteger(_)||_<=1)return;try{if(X==="linux")return x0(X,E4(_,$));if(X==="darwin"){let W=$.execFile("ps",["-o","lstart=","-p",String(_)]).trim();return W?x0(X,W):void 0}if(X==="win32"){let W=`(Get-CimInstance Win32_Process -Filter "ProcessId = ${_}").CreationDate.ToUniversalTime().ToString('O')`,J=$.execFile("powershell.exe",["-NoProfile","-NonInteractive","-Command",W]).trim();return J?x0(X,J):void 0}}catch{return}return}function tX(_,X){return m_(_,X.platform)?.fingerprint===X.fingerprint}function sX(_,X,$=R1,W=A4){if(!Number.isInteger(_)||_<=1)return!1;let J=m_(_,X.platform,$);if(J)return J.fingerprint===X.fingerprint;return!W(_)}var j1=1;function R4(_,X){let $=F4("sha256").update(X).digest("hex");return W0.join(K_(_),".locks",`${$}.lock`)}function R_(_,X){return _ instanceof Error&&"code"in _&&_.code===X}async function k0(_){try{let X=JSON.parse(await W_.readFile(_,"utf8"));if(X.version!==j1||typeof X.sessionId!=="string"||typeof X.ownerId!=="string"||!Number.isInteger(X.pid)||(X.pid??0)<=0||X.processIdentity!==void 0&&!D1(X.processIdentity)||typeof X.acquiredAt!=="string")return;return X}catch(X){if(R_(X,"ENOENT")||X instanceof SyntaxError)return;throw X}}async function w1(_){let X=await k0(_);if(X)return X;return await new Promise(($)=>setTimeout($,10)),k0(_)}function w4(_){try{return process.kill(_,0),!0}catch(X){return!R_(X,"ESRCH")}}async function x1(_,X){let $;try{return $=await W_.open(_,"wx",384),await $.writeFile(`${JSON.stringify(X)}
|
|
2
2
|
`,"utf8"),!0}catch(W){if(R_(W,"EEXIST"))return!1;if($)await W_.unlink(_).catch(()=>{return});throw W}finally{await $?.close().catch(()=>{return})}}class $_ extends Error{code="BLADE_SESSION_IN_USE";constructor(_){super(_?`Session is already active in another Blade process (PID ${_}). Stop that process or choose a different session.`:"Session is already active in another Blade process. Stop that process or choose a different session.");this.name="SessionInUseError"}}async function k1(_,X,$=!1){let W,J;try{J=await D4.lock(_,{realpath:!1,retries:$?{retries:50,minTimeout:10,maxTimeout:100,factor:1.2}:0,onCompromised:(Q)=>{W=Q}})}catch(Q){if(R_(Q,"ELOCKED"))throw new $_;throw Q}let O=()=>{if(W)throw W};try{O();let Q=await X(O);return O(),Q}finally{await J()}}class u{filePath;record;stateStorage;released=!1;constructor(_,X,$){this.filePath=_;this.record=X;this.stateStorage=$}static async acquireForStorage(_,X){if(X.kind==="local")return u.acquire(_,X.root);return H_(X,($,W)=>{if(!W||$!==X.root)throw Error("ACP remote session lease scope is invalid");return u.acquireRemote(_,W,X)})}static async acquire(_,X=f1()){return u.acquireAtPath(_,R4(X,_))}static async acquireRemote(_,X,$){let W=b1(X,_);try{await d(X,W)}catch(O){if(O.code!=="ENOENT")throw O}let J=await u.acquireAtPath(_,W);try{return await d(X,W),new u(W,J.record,$)}catch(O){throw await J.release(),O}}static async acquireAtPath(_,X){return await W_.mkdir(W0.dirname(X),{recursive:!0,mode:448}),k1(X,async($)=>{let W={version:j1,sessionId:_,ownerId:z4(),pid:process.pid,processIdentity:m_(process.pid),acquiredAt:new Date().toISOString()};if($(),await x1(X,W))return new u(X,W);let J=await w1(X);if(!J||J.sessionId!==_)throw new $_;if(w4(J.pid)){let O=J.processIdentity?m_(J.pid,J.processIdentity.platform):void 0;if(!O||O.fingerprint===J.processIdentity?.fingerprint)throw new $_(J.pid)}if($(),await W_.unlink(X).catch((O)=>{if(!R_(O,"ENOENT"))throw O}),$(),await x1(X,W))return new u(X,W);throw new $_((await w1(X))?.pid)})}async release(){if(this.released)return;let _=()=>k1(this.filePath,async(X)=>{if((await k0(this.filePath))?.ownerId!==this.record.ownerId)return;X(),await W_.unlink(this.filePath).catch((W)=>{if(!R_(W,"ENOENT"))throw W})},!0);if(this.stateStorage?.kind==="acp-remote")await H_(this.stateStorage,_);else await _();this.released=!0}}import{createHash as O0}from"node:crypto";import{constants as A_,promises as O_}from"node:fs";import G_ from"node:path";import{Mutex as x4}from"async-mutex";var y1=128,g1=67108864,k4=24576,S1=65536,f0=1,h1=/^[a-f0-9]{64}$/,b4=/^[a-f0-9]{64}\.txt$/,l1=64,f4=new Set(["EBUSY","EAGAIN","EMFILE","ENFILE"]),Y0=`
|
|
3
3
|
|
|
4
4
|
...[middle omitted; read the private prompt artifact for the complete request]...
|