blade-code 0.10.157 → 0.10.158

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.
Files changed (44) hide show
  1. package/dist/blade.js +2 -2
  2. package/dist/{chunk-p1d4ep58.js → chunk-1329rzdd.js} +1 -1
  3. package/dist/{chunk-2nnrrfte.js → chunk-25z7w7jb.js} +1 -1
  4. package/dist/{chunk-7aysjqen.js → chunk-26109k8r.js} +1 -1
  5. package/dist/{chunk-cv4h5c96.js → chunk-42y6ks44.js} +1 -1
  6. package/dist/{chunk-d6x9aqqp.js → chunk-479y73j2.js} +1 -1
  7. package/dist/{chunk-eass9t33.js → chunk-4gsjcz7t.js} +1 -1
  8. package/dist/chunk-5kb1dh44.js +1 -0
  9. package/dist/{chunk-ha8w887r.js → chunk-6htg4eyc.js} +1 -1
  10. package/dist/{chunk-rdvadyyt.js → chunk-6zzet05f.js} +1 -1
  11. package/dist/{chunk-v25d7gze.js → chunk-7h3405ty.js} +1 -1
  12. package/dist/{chunk-7mqmyhfe.js → chunk-7z31ajj4.js} +1 -1
  13. package/dist/{chunk-8brsyfkz.js → chunk-95z104ay.js} +2 -2
  14. package/dist/chunk-9hmjg0k7.js +1 -0
  15. package/dist/{chunk-j5fwzfaj.js → chunk-a9fjtdsh.js} +1 -1
  16. package/dist/{chunk-75n6cr3x.js → chunk-bgc4wts7.js} +2 -2
  17. package/dist/{chunk-1qp826p9.js → chunk-ccsgzyth.js} +1 -1
  18. package/dist/{chunk-nk1kfpz5.js → chunk-ehdsj506.js} +3 -3
  19. package/dist/{chunk-5h9q6jjv.js → chunk-ej0a0s1t.js} +1 -1
  20. package/dist/{chunk-3jqvgxnc.js → chunk-f6wx6sf2.js} +1 -1
  21. package/dist/{chunk-04vy4a4a.js → chunk-fp7ssc21.js} +1 -1
  22. package/dist/{chunk-xqzmm1bf.js → chunk-gnjsdr40.js} +1 -1
  23. package/dist/{chunk-sr61gfha.js → chunk-hamdqef9.js} +1 -1
  24. package/dist/{chunk-tfsmykk5.js → chunk-jcq3tk8c.js} +1 -1
  25. package/dist/{chunk-9cfh48md.js → chunk-jdmm68kd.js} +1 -1
  26. package/dist/{chunk-wax2788t.js → chunk-jxxvc3b0.js} +1 -1
  27. package/dist/{chunk-s9ws4xsz.js → chunk-kxz7j4a3.js} +1 -1
  28. package/dist/{chunk-nmymd2hf.js → chunk-mm5rqxam.js} +1 -1
  29. package/dist/{chunk-9svd1x6q.js → chunk-p5k6x3be.js} +1 -1
  30. package/dist/{chunk-8bm5bpa2.js → chunk-pnfeyw0g.js} +1 -1
  31. package/dist/{chunk-tbg7yrwp.js → chunk-pz0d6ne3.js} +1 -1
  32. package/dist/{chunk-96c1kd2j.js → chunk-tfebp09g.js} +1 -1
  33. package/dist/{chunk-zqn8q1b6.js → chunk-thveee78.js} +1 -1
  34. package/dist/{chunk-ra0y5drh.js → chunk-v7b7dx9j.js} +1 -1
  35. package/dist/{chunk-9rx1axgj.js → chunk-vg6m8ybn.js} +1 -1
  36. package/dist/{chunk-w5awn40e.js → chunk-vq1myd58.js} +1 -1
  37. package/dist/{chunk-pdfdj5rp.js → chunk-vs8ywzme.js} +1 -1
  38. package/dist/{chunk-q1rnvn85.js → chunk-vz13c7fr.js} +45 -45
  39. package/dist/{chunk-7r26xgk4.js → chunk-xh3bm0p0.js} +1 -1
  40. package/dist/{chunk-m268099y.js → chunk-xxd3vx1j.js} +1 -1
  41. package/dist/{chunk-46a6mzfg.js → chunk-y1t2tvmq.js} +1 -1
  42. package/package.json +1 -1
  43. package/dist/chunk-4d6d5xtp.js +0 -1
  44. package/dist/chunk-bfd4yt7c.js +0 -1
@@ -1,4 +1,4 @@
1
- import{vc as U8}from"./chunk-wm896gnx.js";import{$d as T6,Ac as i1,Cc as z$,Dd as y2,Ed as q8,Fd as G8,Gd as Q6,Hd as t1,Id as L8,Jd as F8,Kd as c1,Od as lJ,Xd as u0,Zd as S6,_d as n1,ge as W1,sd as _2,ud as A2,vd as b2,wc as U$,wd as B6,xd as D6,yc as w$,zc as N2}from"./chunk-3jqvgxnc.js";import{le as w8}from"./chunk-9xbwtjac.js";import{De as E0,oe as q0,re as V2,se as C$}from"./chunk-q1rnvn85.js";import{cg as C2}from"./chunk-7xhw74hk.js";import{dg as B8,eg as r0,fg as X8,gg as uJ,ig as d1,jg as E6,kg as mJ,lg as dJ,og as cJ}from"./chunk-k1tfry97.js";import{ah as Y$,bh as n0,eh as D8}from"./chunk-ewwrss2w.js";import{jh as n2,nh as J2}from"./chunk-53vh6vpt.js";import{yh as E$}from"./chunk-ra0y5drh.js";import{Ti as R$}from"./chunk-sd9bze9x.js";import{aj as j0}from"./chunk-jsv3e4k6.js";import{Cj as T0}from"./chunk-5q4z0sfr.js";import{Wj as P2}from"./chunk-7r26xgk4.js";import{Ak as GJ,Bk as s1,Dk as L2,Ik as F2,Jk as O2,ek as G2,tk as B2,uk as D2,xk as K1}from"./chunk-7xtxvrh8.js";import{Lk as mZ}from"./chunk-sdapqhj0.js";function y$($){return $.role==="system"&&Array.isArray($.content)}function b$($){if($.role!=="system"||!$.metadata||Array.isArray($.metadata))return!1;return typeof $.metadata==="object"&&$.metadata.contextualProjectRules===!0}class I1{systemMessages;_contextualSystemMessages;_history;_pending=[];_contextRevision=0;context;constructor($,Z){this.context=$;let J=$.messages.find(y$);if(this._contextualSystemMessages=$.messages.filter(b$),J)this.systemMessages=[J,...this._contextualSystemMessages];else if(Z)this.systemMessages=[{role:"system",content:[{type:"text",text:Z,providerOptions:{anthropic:{cacheControl:{type:"ephemeral"}}}}]},...this._contextualSystemMessages];else this.systemMessages=[...this._contextualSystemMessages];this._history=$.messages.filter((W)=>!y$(W)&&!b$(W))}get historyLength(){return this._history.length}get history(){return this._history}get pending(){return this._pending}get contextRevision(){return this._contextRevision}toLLMMessages(){return[...this.systemMessages,...this._history,...this._pending]}getMessagesForLLM(){return this.toLLMMessages()}getHistory(){return this._history}appendPending($){this._pending.push($)}appendUser($){this._pending.push($)}appendAssistant($){this._pending.push($)}appendToolResult($){this._pending.push($)}appendContextualProjectInstructions($){if(!b$($))throw Error("Contextual project instructions require safe metadata");this._contextualSystemMessages.push($),this.systemMessages.push($)}syncContextualSystemMessages(){let $=this.systemMessages.filter(y$);this.systemMessages.splice(0,this.systemMessages.length,...$,...this._contextualSystemMessages)}appendControl($,Z){if($==="system")throw Error("Cannot append system control message via appendControl. Use constructor for root system prompt.");this._pending.push({...Z,metadata:{...Z.metadata&&typeof Z.metadata==="object"&&!Array.isArray(Z.metadata)?Z.metadata:{},...E0}})}appendDurableControl($){if(!$.id||$.role!=="user")throw Error("Durable control messages require a user role and identity");if(this._history.some((Z)=>Z.id===$.id))return;this._history.push($)}appendToHistory($){this._history.push($)}commitPending(){if(this._pending.length>0)this._history.push(...this._pending),this._pending=[]}replaceHistory($){this._history=$.filter((Z)=>!y$(Z)&&!b$(Z)),this._contextRevision++}restoreDurableHistory($){this._contextualSystemMessages=$.filter(b$),this._history=$.filter((Z)=>!y$(Z)&&!b$(Z)),this._pending=[],this.syncContextualSystemMessages(),this._contextRevision++}removeMessages($){let Z=[this._history.length,this._pending.length,this._contextualSystemMessages.length];if(this._history=this._history.filter((J)=>!$(J)),this._pending=this._pending.filter((J)=>!$(J)),this._contextualSystemMessages=this._contextualSystemMessages.filter((J)=>!$(J)),this.syncContextualSystemMessages(),this._history.length!==Z[0]||this._pending.length!==Z[1]||this._contextualSystemMessages.length!==Z[2])this._contextRevision++}writeback(){this.commitPending(),this.context.messages=[...this._contextualSystemMessages,...this._history]}get hasSystemPrompt(){return this.systemMessages.length>0}}function s6($){if($.isSubagent)return"continue";if(!$.budget||$.budget<=0)return"continue";if($.consecutiveContinuations>=3&&$.lastOutputDelta<500)return"stop";if($.usage/$.budget>=0.9)return"stop";return"continue"}function t6($){return{budget:$.budget,usage:0,consecutiveContinuations:0,lastOutputDelta:0,isSubagent:$.isSubagent??!1}}function e6($,Z,J){return{...$,usage:$.usage+Z,lastOutputDelta:Z,consecutiveContinuations:J?$.consecutiveContinuations+1:0}}import V$ from"node:path";var R8=new Set(["GOEXPERIMENT","GOOS","GOARCH","CGO_ENABLED","GO111MODULE","RUST_BACKTRACE","RUST_LOG","NODE_ENV","PYTHONUNBUFFERED","PYTHONDONTWRITEBYTECODE","GIT_TERMINAL_PROMPT","LANG","LANGUAGE","LC_ALL","LC_CTYPE","LC_TIME","CHARSET","TERM","COLORTERM","NO_COLOR","FORCE_COLOR","TZ","LS_COLORS","LSCOLORS","GREP_COLOR","GREP_COLORS"]),M8=/^(LD_.+|DYLD_.+|PATH)$/,$J=/^([A-Za-z_][A-Za-z0-9_]*)=([\w./:@-]*)$/;function t$($){let Z=$;while(!0){let J=Z.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!J)break;let W=J[1],Y=J[2],K=W.match($J);if(!K)break;let X=K[1];if(!R8.has(X))break;Z=Y}return Z}function l5($){let Z=$;while(!0){let J=Z.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!J)break;let W=J[1],Y=J[2],K=W.match($J);if(!K)break;let X=K[1];if(M8.test(X))break;Z=Y}return Z}var k8=[/^timeout[ \t]+(?:--foreground[ \t]+|--preserve-status[ \t]+|-v[ \t]+|--verbose[ \t]+|-k[ \t]+\S+[ \t]+|--kill-after[= ]\S+[ \t]+|-s[ \t]+\S+[ \t]+|--signal[= ]\S+[ \t]+)*\S+[ \t]+/,/^time[ \t]+/,/^nice[ \t]+(?:-n[ \t]+\d+[ \t]+|-\d+[ \t]+)?/,/^nohup[ \t]+/];function RZ($){let Z=$,J=!0;while(J){J=!1;for(let W of k8){let Y=Z.match(W);if(Y){Z=Z.slice(Y[0].length),J=!0;break}}if(Z.startsWith("-- "))Z=Z.slice(3),J=!0}return Z}function e$($){let Z=[],J="",W=!1,Y=!1,K=!1;for(let X=0;X<$.length;X++){let Q=$[X];if(K){J+=Q,K=!1;continue}if(Q==="\\"&&!W){J+=Q,K=!0;continue}if(Q==="'"&&!Y){W=!W,J+=Q;continue}if(Q==='"'&&!W){Y=!Y,J+=Q;continue}if(W||Y){J+=Q;continue}if(Q==="|"){if(X+1<$.length&&$[X+1]==="|"){if(J.trim())Z.push(J.trim());J="",X++;continue}return null}if(Q===">"||Q==="<")return null;if(Q==="&"&&X+1<$.length&&$[X+1]==="&"){if(J.trim())Z.push(J.trim());J="",X++;continue}if(Q==="&")return null;if(Q===";"){if(J.trim())Z.push(J.trim());J="";continue}J+=Q}if(J.trim())Z.push(J.trim());return Z.length>0?Z:null}function ZJ($){let Z=!1,J=!1,W=!1;for(let Y=0;Y<$.length;Y++){let K=$[Y];if(W){W=!1;continue}if(K==="\\"&&!Z){W=!0;continue}if(K==="'"&&!J){Z=!Z;continue}if(K==='"'&&!Z){J=!J;continue}if(Z)continue;if(K==="$"){let X=$[Y+1];if(X&&/[A-Za-z_@*#?!$0-9({]/.test(X))return!0}if(K==="`")return!0;if(J)continue;if(K==="|")return!0;if(K===">"||K==="<")return!0;if(K==="{"){let X=$.slice(Y);if(/^\{[^}]*,[^}]*\}/.test(X)||/^\{[^}]*\.\.[^}]*\}/.test(X))return!0}}return!1}function H$($){let Z=[],J="",W=!1,Y=!1,K=!1;for(let X=0;X<$.length;X++){let Q=$[X];if(K){J+=Q,K=!1;continue}if(Q==="\\"&&!W){if(K=!0,Y){let H=$[X+1];if(H&&'$`"\\'.includes(H))continue;J+=Q,K=!1}continue}if(Q==="'"&&!Y){W=!W;continue}if(Q==='"'&&!W){Y=!Y;continue}if(!W&&!Y&&/[ \t]/.test(Q)){if(J)Z.push(J),J="";continue}J+=Q}if(J)Z.push(J);return Z}var x8=new Set(["npm","pnpm","yarn","bun"]),JJ=new Set(["biome","eslint","jest","mypy","pyright","pytest","ruff","tsc","vitest"]),I8=new Set(["-u","--fix","--update","--update-snapshot","--updateSnapshot","--watch","--watchAll","--write"]),h8=/[ \t]*;[ \t]*echo[ \t]+"[A-Za-z0-9 _:=.-]*(?:\$\{PIPESTATUS\[0\]\}|\$\?)[A-Za-z0-9 _:=.-]*"[ \t]*$/;function v8($){return $!==void 0&&/^(?:test|lint|build|type-?check)(?::[\w.-]+)*$/i.test($)}function WJ($){return $.replace(/\s+2>&1\s*$/,"").trim()}function C8($,Z,J){if(!J||Z.length!==2)return;let W=/^(.+?)[ \t]+&&[ \t]+([\s\S]+)$/.exec($);if(!W)return;let Y=H$(W[1]??"");if(Y.length!==2||Y[0]!=="cd")return;let K=Y[1];if(!K||K==="-")return;let X=V$.isAbsolute(K)?V$.resolve(K):V$.resolve(J,K);if(!z$.isWithinWorkspace(X,J))return;return W[2]?.trim()||void 0}function g8($){let Z=[],J=!1,W=!1,Y=!1;for(let K=0;K<$.length;K++){let X=$[K];if(Y){Y=!1;continue}if(X==="\\"&&!J){Y=!0;continue}if(X==="'"&&!W){J=!J;continue}if(X==='"'&&!J){W=!W;continue}if(X!=="|"||J||W)continue;if($[K+1]==="|")return;Z.push(K)}return Z}function p8($){let Z=H$($),[J,W,Y]=Z;if(J!=="head"&&J!=="tail")return!1;if(Z.length===1)return!0;let K=(X)=>X!==void 0&&/^[1-9]\d{0,4}$/.test(X);if(Z.length===2)return W?.startsWith("--lines=")&&K(W.slice(8))||W?.startsWith("-")&&K(W.slice(1));return Z.length===3&&(W==="-n"||W==="--lines")&&K(Y)}function u8($){let Z=WJ($.replace(h8,"").trim()),J=g8(Z);if(!J)return;if(J.length===0)return YJ(Z);if(J.length!==1)return;let W=J[0];if(W===void 0)return;let Y=WJ(Z.slice(0,W).trim()),K=Z.slice(W+1).trim();if(!Y||!p8(K))return;return YJ(Y)}function YJ($){let J=e$($)?.at(-1);if(!J)return $;let W=H$(J),[Y,K]=W;if(!(Y==="vitest"||(Y==="npx"||Y==="bunx")&&K==="vitest")||W.some((Q)=>Q==="--configLoader"||Q.startsWith("--configLoader=")))return $;return`${$} --configLoader runner`}function f$($,Z){let J=u8($);if(!J)return!1;let W=t$(J),Y=e$(W);if(!Y||ZJ(W)||/[\r\n]/.test(W))return!1;let K=Y.length===1?Y[0]:C8(W,Y,Z);if(!K)return!1;let X=H$(K);if(X.length===0||X.some((z)=>[...I8].some((B)=>z===B||z.startsWith(`${B}=`))))return!1;let[Q,H,V]=X;if(x8.has(Q??""))return v8(H==="run"?V:H)||H==="--test";if((Q==="npx"||Q==="bunx")&&JJ.has(H??""))return!0;if(JJ.has(Q??""))return!0;if(Q==="node"&&H==="--test")return!0;if(Q==="go"&&["build","test","vet"].includes(H??""))return!0;return Q==="cargo"&&["build","check","clippy","test"].includes(H??"")}function a5($,Z){if($===void 0)return!0;if(typeof $!=="string"||$.split(/[\\/]/).includes(".."))return!1;if(!Z)return!V$.isAbsolute($);let J=V$.isAbsolute($)?V$.resolve($):V$.resolve(Z,$);return z$.isWithinWorkspace(J,Z)}var MZ=T0("Agent"),m8=3;function kZ($,Z,J){if($!=="length")return{action:"none"};if(Z>=m8)return{action:"truncated"};if(s6(J)==="stop")return MZ.info("[Loop] Token budget: diminishing returns detected, skipping recovery"),{action:"budget_stop"};return{action:"recover"}}var d8=[/:\s*$/,/:\s*$/,/\.\.\.\s*$/,/让我(先|来|开始|查看|检查|修复)/,/Let me (first|start|check|look|fix)/i,/I('ll| will) (now |)(create|write|edit|update|modify|fix|add|implement)/i,/我(现在就|来|要)(创建|写入|编辑|修改|修复|添加|实现)/,/\d+\.\s+(First|Next|Then|Finally)/i],c8=/```[\s\S]{50,}```/,KJ="请执行你提到的操作,不要只是描述。使用 Edit/Write/ApplyPatch/Bash 工具来实际修改文件。",l8=2;function xZ($,Z,J=!0){if(!$||Z>=l8)return{action:"none"};if(!J&&c8.test($))return{action:"retry",prompt:KJ};let W=$.slice(-200),Y=W.match(/```/g);if(Y&&Y.length%2!==0)return{action:"none"};if(d8.some((X)=>X.test(W)))return{action:"retry",prompt:KJ};return{action:"none"}}var h1=2,i8="The model returned tool-call JSON as text instead of completing the requested tool workflow.",r8="The previous response contained tool-call JSON as ordinary text. It did not execute a tool. If the requested operation is still needed, use the native tool-call interface with an available tool. If it already succeeded, use the recorded result to answer instead of repeating the operation. Do not return another tool-call JSON envelope as your final answer.";function IZ($,Z,J,W){if(!$||$.length>65536||J.length===0)return{action:"none"};let Y=Z.replace(/```[\s\S]*?(?:```|$)/g,"").replace(/^\s*>.*$/gm,"");if(/\b(?:example|schema|serialize|serialization|quote|print|illustrate|verbatim)\b|示例|样例|序列化|引用原文/i.test(Y)||/\b(?:explain|show|return|output)\b[^.!?\n]{0,80}\b(?:json|tool.calls?)\b|(?:解释|展示|输出|返回)[^。!?\n]{0,40}(?:JSON|工具调用格式)/i.test(Y)||/\b(?:do not|don't|never)\s+(?:use|call|invoke|execute)\s+(?:any\s+)?tools?\b|不要(?:使用|调用|执行)(?:任何)?工具/i.test(Y))return{action:"none"};let K;try{K=JSON.parse($)}catch{return{action:"none"}}if(!K||typeof K!=="object"||Array.isArray(K)||Object.keys(K).length!==1||!("tool_calls"in K)||!Array.isArray(K.tool_calls)||K.tool_calls.length===0||K.tool_calls.length>32)return{action:"none"};let X=new Set;for(let Q of K.tool_calls){if(!Q||typeof Q!=="object"||Array.isArray(Q))return{action:"none"};let H="function"in Q;if(Object.keys(Q).some((L)=>!["id","type",...H?["function"]:["name","arguments"]].includes(L)))return{action:"none"};if("type"in Q&&Q.type!=="function")return{action:"none"};let V=H?Q.function:Q;if(!V||typeof V!=="object"||Array.isArray(V)||!("name"in V)||typeof V.name!=="string"||!("arguments"in V))return{action:"none"};if(H&&Object.keys(V).some((L)=>L!=="name"&&L!=="arguments"))return{action:"none"};if(!J.includes(V.name))return{action:"none"};let z=V.arguments;if(typeof z!=="string"&&(!z||typeof z!=="object"||Array.isArray(z)))return{action:"none"};let B=V.name.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),j=new RegExp(`(?:^|[.!?。!?;;\\n])\\s*(?:please\\s+)?(?:call|invoke|execute|run|use)\\s+(?:the\\s+)?(?:tool\\s+)?[\`"']?${B}(?![\\w:-])|(?:^|[。!?;\\n])\\s*(?:请)?(?:调用|使用|执行)\\s*(?:工具\\s*)?[\`"']?${B}(?![\\w:-])`,"i"),w=new RegExp(`(?:do not|don't|never)\\s+(?:call|invoke|execute|run|use)\\s+(?:the\\s+)?(?:tool\\s+)?[\`"']?${B}(?![\\w:-])|(?:不要|禁止)(?:调用|使用|执行)\\s*(?:工具\\s*)?[\`"']?${B}(?![\\w:-])`,"i");if(!j.test(Y)||w.test(Y))return{action:"none"};X.add(V.name)}return W<h1?{action:"retry",prompt:r8,...X.size===1?{toolName:[...X][0]}:{}}:{action:"fail",message:i8}}var n8=[/\b(?:run|execute|rerun|re-run)\b[\s\S]{0,60}\b(?:tests?|test suite|lint|type-?check|build)\b/i,/\b(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?(?:test|lint|build|type-?check)\b/i,/(?:运行|执行|跑|重新运行).{0,30}(?:测试|单测|集成测试|检查|构建)/],XJ={test:/\b(?:tests?|test suite)\b|(?:测试|单测|集成测试)/i,lint:/\blint(?:ing)?\b/i,"type-check":/\btype[\s-]?check(?:ing)?\b|\btsc\b|类型检查/i,build:/\bbuild\b|构建/i},o8={test:/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?test\b|(?:^|\s)(?:node|bun)\s+--test\b|(?:^|\s)(?:vitest|jest|pytest|go\s+test|cargo\s+test)\b/i,lint:/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?lint\b/i,"type-check":/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?type-?check\b|(?:^|\s)tsc\b/i,build:/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?build\b/i},a8="The user explicitly required verification, but it has not run successfully. Do not finish or explain. Your next action must be a Bash tool call that runs the requested test, lint, type-check, or build command. Inspect the command result and fix any failure before finishing.",s8="Required verification did not run successfully before the retry limit.",t8=3;function HJ($,Z,J,W){if(!J.success)return;if(["Edit","Write","ApplyPatch","NotebookEdit"].includes(Z)){$.clear();return}if(Z==="Bash"&&typeof J.metadata?.command==="string"&&J.metadata.exit_code===0&&f$(J.metadata.command,W)){$.add(J.metadata.command);return}if(!["Task","TaskOutput"].includes(Z))return;let Y=J.metadata?.verificationCommands;if(!Array.isArray(Y))return;for(let K of Y)if(typeof K==="string"&&f$(K,W))$.add(K)}function hZ($,Z,J){if(!$||!n8.some((H)=>H.test($)))return{action:"none"};let W=Object.keys(XJ).filter((H)=>XJ[H].test($)),Y=[...Z],K=W.filter((H)=>!Y.some((V)=>o8[H].test(V)));if(W.length>0?K.length===0:Y.some((H)=>f$(H)))return{action:"none"};if(J>=t8)return{action:"fail",message:s8};let Q=W.length>1&&K.length>0?` Missing successful verification categories: ${K.join(", ")}.`:"";return{action:"retry",prompt:`${a8}${Q}`}}var e8=[/\bdelegate\b[\s\S]{0,120}\b(?:Task tool|subagent|agent)\b/i,/\b(?:call|use|invoke)\b[\s\S]{0,80}\bTask tool\b/i,/(?:委派|交给|调用|使用).{0,60}(?:Task|子代理|子智能体)/],VJ=[/\b(?:do not|don't|never)\s+(?:delegate|call|use|invoke)\b/i,/(?:不要|禁止|无需)(?:委派|调用|使用).{0,20}(?:Task|子代理|子智能体)?/];function zJ($){return typeof $==="string"&&VJ.some((Z)=>Z.test($))}var $9=[/\b(?:call|use|invoke)\b[\s\S]{0,30}\bTask(?: tool)?\b[\s\S]{0,30}\bexactly once\b/i,/\bexactly once\b[\s\S]{0,30}\b(?:call|use|invoke)\b[\s\S]{0,30}\bTask(?: tool)?\b/i,/\bexactly one\b[\s\S]{0,30}\bTask(?: tool)? calls?\b/i,/(?:Task|子代理).{0,20}(?:恰好|仅|只)(?:调用|使用)?一次/,/(?:恰好|仅|只)(?:调用|使用)?一次.{0,20}(?:Task|子代理)/],Z9=[/\b(?:do not|don't|never)\s+(?:call|use|invoke)\s+(?:the\s+)?Task\b[\s\S]{0,30}\bexactly once\b/i,/\bTask\b[\s\S]{0,30}\b(?:does not|doesn't|need not)\b[\s\S]{0,30}\bexactly once\b/i,/\bmultiple\s+Task(?: tool)?\s+calls?\s+(?:are\s+)?allowed\b/i,/(?:不要|禁止).{0,12}(?:Task|子代理).{0,12}(?:恰好|仅|只)(?:调用|使用)?一次/];function J9($){if(typeof $!=="string")return;if(Z9.some((Z)=>Z.test($)))return"multiple-allowed";return $9.some((Z)=>Z.test($))?"required":void 0}function Z1($){for(let Z of $){let J=J9(Z);if(J!==void 0)return J==="required"}return!1}var W9="The user explicitly required delegation, but no Task tool call completed successfully. Do not solve the task directly or explain. Your next action must be a Task tool call using the requested subagent.",Y9="Required delegation did not complete before the retry limit.",K9=3;function jJ($,Z,J){let W=(typeof $==="string"?[$]:$??[]).map((X)=>X.trim()).filter(Boolean),Y=Z1(W),K=!1;if(!Y)for(let X of W){if(VJ.some((Q)=>Q.test(X)))break;if(e8.some((Q)=>Q.test(X))){K=!0;break}}if(W.length===0||!Y&&!K||Z.has("Task"))return{action:"none"};if(J>=K9)return{action:"fail",message:Y9};return{action:"retry",prompt:W9}}var X9=[/\b(?:use|create|enter|start|work\s+(?:in|inside))\b.{0,60}\bworktree\b/i,/(?:使用|创建|进入).{0,30}(?:worktree|工作树)/i],Q9=[/\b(?:exit|leave)\b.{0,40}\bworktree\b/i,/\bworktree\b.{0,60}\b(?:action\s+)?(?:keep|remove)\b/i,/(?:退出|离开).{0,30}(?:worktree|工作树)/i],H9=[/\b(?:do not|don't|never|must not|should not)\b[^.!?;\n]{0,80}\b(?:git\s+)?worktree\b/gi,/\bwithout\b[^.!?;\n]{0,60}\b(?:git\s+)?worktree\b/gi,/(?:不要|禁止|不得|无需)[^。!?;\n]{0,50}(?:worktree|工作树)/gi];function BJ($){return H9.reduce((Z,J)=>Z.replace(J," "),$)}function v1($){if(typeof $!=="string")return!1;let Z=BJ($);return X9.some((J)=>J.test(Z))}var V9="The user explicitly required git worktree isolation, but EnterWorktree has not completed successfully. Do not continue in the original workspace. Your next action must be an EnterWorktree tool call. Wait for its result before using file or Bash tools.",z9="The user explicitly required leaving the managed worktree, but ExitWorktree has not completed successfully. Do not finish or explain. Your next action must be an ExitWorktree tool call using the action requested by the user.",j9="Required worktree lifecycle did not complete before the retry limit.",B9=3;function DJ($,Z,J){if(!$)return{action:"none"};let W=BJ($);if(!v1(W))return{action:"none"};let Y=Q9.some((X)=>X.test(W));if(Z.has("TaskWorktree"))return{action:"none"};let K=!Z.has("EnterWorktree")?"EnterWorktree":Y&&!Z.has("ExitWorktree")?"ExitWorktree":void 0;if(!K)return{action:"none"};if(J>=B9)return{action:"fail",message:j9};return{action:"retry",tool:K,prompt:K==="EnterWorktree"?V9:z9}}var QJ=30000;async function vZ($){try{let J=E$.getInstance().executeStopHooks({projectDir:$.workspaceRoot??j0(),sessionId:$.sessionId,permissionMode:$.permissionMode,reason:$.reason,abortSignal:$.abortSignal}),W,Y=new Promise((K)=>{W=setTimeout(()=>K("timeout"),QJ)});try{let K=await Promise.race([J,Y]);if(K==="timeout")return MZ.warn(`[Loop] Stop hook 超时 (${QJ}ms),按 shouldStop: true 处理`),{action:"stop"};let X=K;if(!X.shouldStop)return{action:"continue",reason:X.continueReason};return{action:"stop"}}finally{clearTimeout(W)}}catch(Z){return MZ.warn("[Loop] Stop hook execution failed:",Z),{action:"stop"}}}async function D9($,Z){let J;while(!(J=await $.next()).done)if(Z)await Z(J.value);return J.value}var w9=[/<system-reminder>[\s\S]*?<\/system-reminder>/gi,/<file[^>]*>[\s\S]*?<\/file>/gi,/<hooks_context>[\s\S]*?<\/hooks_context>/gi,/<[^>]+>/g];function U9($){if(typeof $==="string")return $;if(Array.isArray($))return $.map((Z)=>{if(typeof Z==="string")return Z;if(Z&&typeof Z==="object"&&"text"in Z){let J=Z.text;return typeof J==="string"?J:""}return""}).join(" ");return""}function q9($){let Z=$;for(let H of w9)Z=Z.replace(H," ");Z=Z.replace(/^\s*\/[a-zA-Z][\w-]*\s+/,"");let J=Z.replace(/\s+/g," ").trim();if(!J)return"";let W=J.match(/^(.+?)(?:[.!?]\s|[。!?](?=\S|$)|$)/),Y=W&&W[1].length>=6?W[1]:J;if(Y=Y.trim().replace(/[\s.。!!??,,;;::-]+$/,""),Y.length<=60)return Y;let K=Y.slice(0,60),X=K.lastIndexOf(" ");return`${(X>36?K.slice(0,X):K).trimEnd()}…`}function wJ($){return q9(U9($))}import{EventEmitter as G9}from"events";import UJ from"node:path";function CZ($){if(GJ($.sessionId),!UJ.isAbsolute($.projectPath))throw Error("projectPath must be absolute");return{sessionId:$.sessionId,projectPath:UJ.resolve($.projectPath)}}function qJ($){let Z=CZ($);return JSON.stringify([Z.projectPath,Z.sessionId])}function V3($,Z){return qJ($)===qJ(Z)}class S$ extends G9{static instance;constructor(){super();this.setMaxListeners(100)}static getInstance(){if(!S$.instance)S$.instance=new S$;return S$.instance}publish($,Z,J,W){let Y=CZ($);this.emit("event",{sessionId:Y.sessionId,projectPath:Y.projectPath,type:Z,...W!==void 0?{seq:W}:{},properties:J})}subscribe($){return this.on("event",$),()=>this.off("event",$)}}var J1=S$.getInstance();var $$=T0("Agent"),C1=new Set;async function L9($,Z){let J=$.sessionId;if(!J||$.subagentInfo)return;if(C1.has(J))return;if(C1.size>=5000)C1.clear();C1.add(J);try{let W=$.workspaceRoot,Y=await W1.findSessionMetadata(J,W);if(!Y)return;if(Y.title&&Y.title.trim())return;let K=wJ(Z);if(!K)return;await W1.updateSessionMetadata(J,Y.projectPath,{title:K}),J1.publish({sessionId:J,projectPath:Y.projectPath},"session.updated",{title:K})}catch(W){$$.debug?.("[Loop] 自动生成会话标题失败:",W)}}var gZ=`<turn_aborted>
1
+ import{vc as U8}from"./chunk-wm896gnx.js";import{$d as T6,Ac as i1,Cc as z$,Dd as y2,Ed as q8,Fd as G8,Gd as Q6,Hd as t1,Id as L8,Jd as F8,Kd as c1,Od as lJ,Xd as u0,Zd as S6,_d as n1,ge as W1,sd as _2,ud as A2,vd as b2,wc as U$,wd as B6,xd as D6,yc as w$,zc as N2}from"./chunk-f6wx6sf2.js";import{le as w8}from"./chunk-9xbwtjac.js";import{De as E0,oe as q0,re as V2,se as C$}from"./chunk-vz13c7fr.js";import{cg as C2}from"./chunk-7xhw74hk.js";import{dg as B8,eg as r0,fg as X8,gg as uJ,ig as d1,jg as E6,kg as mJ,lg as dJ,og as cJ}from"./chunk-k1tfry97.js";import{ah as Y$,bh as n0,eh as D8}from"./chunk-ewwrss2w.js";import{jh as n2,nh as J2}from"./chunk-53vh6vpt.js";import{yh as E$}from"./chunk-v7b7dx9j.js";import{Ti as R$}from"./chunk-sd9bze9x.js";import{aj as j0}from"./chunk-jsv3e4k6.js";import{Cj as T0}from"./chunk-5q4z0sfr.js";import{Wj as P2}from"./chunk-xh3bm0p0.js";import{Ak as GJ,Bk as s1,Dk as L2,Ik as F2,Jk as O2,ek as G2,tk as B2,uk as D2,xk as K1}from"./chunk-7xtxvrh8.js";import{Lk as mZ}from"./chunk-sdapqhj0.js";function y$($){return $.role==="system"&&Array.isArray($.content)}function b$($){if($.role!=="system"||!$.metadata||Array.isArray($.metadata))return!1;return typeof $.metadata==="object"&&$.metadata.contextualProjectRules===!0}class I1{systemMessages;_contextualSystemMessages;_history;_pending=[];_contextRevision=0;context;constructor($,Z){this.context=$;let J=$.messages.find(y$);if(this._contextualSystemMessages=$.messages.filter(b$),J)this.systemMessages=[J,...this._contextualSystemMessages];else if(Z)this.systemMessages=[{role:"system",content:[{type:"text",text:Z,providerOptions:{anthropic:{cacheControl:{type:"ephemeral"}}}}]},...this._contextualSystemMessages];else this.systemMessages=[...this._contextualSystemMessages];this._history=$.messages.filter((W)=>!y$(W)&&!b$(W))}get historyLength(){return this._history.length}get history(){return this._history}get pending(){return this._pending}get contextRevision(){return this._contextRevision}toLLMMessages(){return[...this.systemMessages,...this._history,...this._pending]}getMessagesForLLM(){return this.toLLMMessages()}getHistory(){return this._history}appendPending($){this._pending.push($)}appendUser($){this._pending.push($)}appendAssistant($){this._pending.push($)}appendToolResult($){this._pending.push($)}appendContextualProjectInstructions($){if(!b$($))throw Error("Contextual project instructions require safe metadata");this._contextualSystemMessages.push($),this.systemMessages.push($)}syncContextualSystemMessages(){let $=this.systemMessages.filter(y$);this.systemMessages.splice(0,this.systemMessages.length,...$,...this._contextualSystemMessages)}appendControl($,Z){if($==="system")throw Error("Cannot append system control message via appendControl. Use constructor for root system prompt.");this._pending.push({...Z,metadata:{...Z.metadata&&typeof Z.metadata==="object"&&!Array.isArray(Z.metadata)?Z.metadata:{},...E0}})}appendDurableControl($){if(!$.id||$.role!=="user")throw Error("Durable control messages require a user role and identity");if(this._history.some((Z)=>Z.id===$.id))return;this._history.push($)}appendToHistory($){this._history.push($)}commitPending(){if(this._pending.length>0)this._history.push(...this._pending),this._pending=[]}replaceHistory($){this._history=$.filter((Z)=>!y$(Z)&&!b$(Z)),this._contextRevision++}restoreDurableHistory($){this._contextualSystemMessages=$.filter(b$),this._history=$.filter((Z)=>!y$(Z)&&!b$(Z)),this._pending=[],this.syncContextualSystemMessages(),this._contextRevision++}removeMessages($){let Z=[this._history.length,this._pending.length,this._contextualSystemMessages.length];if(this._history=this._history.filter((J)=>!$(J)),this._pending=this._pending.filter((J)=>!$(J)),this._contextualSystemMessages=this._contextualSystemMessages.filter((J)=>!$(J)),this.syncContextualSystemMessages(),this._history.length!==Z[0]||this._pending.length!==Z[1]||this._contextualSystemMessages.length!==Z[2])this._contextRevision++}writeback(){this.commitPending(),this.context.messages=[...this._contextualSystemMessages,...this._history]}get hasSystemPrompt(){return this.systemMessages.length>0}}function s6($){if($.isSubagent)return"continue";if(!$.budget||$.budget<=0)return"continue";if($.consecutiveContinuations>=3&&$.lastOutputDelta<500)return"stop";if($.usage/$.budget>=0.9)return"stop";return"continue"}function t6($){return{budget:$.budget,usage:0,consecutiveContinuations:0,lastOutputDelta:0,isSubagent:$.isSubagent??!1}}function e6($,Z,J){return{...$,usage:$.usage+Z,lastOutputDelta:Z,consecutiveContinuations:J?$.consecutiveContinuations+1:0}}import V$ from"node:path";var R8=new Set(["GOEXPERIMENT","GOOS","GOARCH","CGO_ENABLED","GO111MODULE","RUST_BACKTRACE","RUST_LOG","NODE_ENV","PYTHONUNBUFFERED","PYTHONDONTWRITEBYTECODE","GIT_TERMINAL_PROMPT","LANG","LANGUAGE","LC_ALL","LC_CTYPE","LC_TIME","CHARSET","TERM","COLORTERM","NO_COLOR","FORCE_COLOR","TZ","LS_COLORS","LSCOLORS","GREP_COLOR","GREP_COLORS"]),M8=/^(LD_.+|DYLD_.+|PATH)$/,$J=/^([A-Za-z_][A-Za-z0-9_]*)=([\w./:@-]*)$/;function t$($){let Z=$;while(!0){let J=Z.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!J)break;let W=J[1],Y=J[2],K=W.match($J);if(!K)break;let X=K[1];if(!R8.has(X))break;Z=Y}return Z}function l5($){let Z=$;while(!0){let J=Z.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!J)break;let W=J[1],Y=J[2],K=W.match($J);if(!K)break;let X=K[1];if(M8.test(X))break;Z=Y}return Z}var k8=[/^timeout[ \t]+(?:--foreground[ \t]+|--preserve-status[ \t]+|-v[ \t]+|--verbose[ \t]+|-k[ \t]+\S+[ \t]+|--kill-after[= ]\S+[ \t]+|-s[ \t]+\S+[ \t]+|--signal[= ]\S+[ \t]+)*\S+[ \t]+/,/^time[ \t]+/,/^nice[ \t]+(?:-n[ \t]+\d+[ \t]+|-\d+[ \t]+)?/,/^nohup[ \t]+/];function RZ($){let Z=$,J=!0;while(J){J=!1;for(let W of k8){let Y=Z.match(W);if(Y){Z=Z.slice(Y[0].length),J=!0;break}}if(Z.startsWith("-- "))Z=Z.slice(3),J=!0}return Z}function e$($){let Z=[],J="",W=!1,Y=!1,K=!1;for(let X=0;X<$.length;X++){let Q=$[X];if(K){J+=Q,K=!1;continue}if(Q==="\\"&&!W){J+=Q,K=!0;continue}if(Q==="'"&&!Y){W=!W,J+=Q;continue}if(Q==='"'&&!W){Y=!Y,J+=Q;continue}if(W||Y){J+=Q;continue}if(Q==="|"){if(X+1<$.length&&$[X+1]==="|"){if(J.trim())Z.push(J.trim());J="",X++;continue}return null}if(Q===">"||Q==="<")return null;if(Q==="&"&&X+1<$.length&&$[X+1]==="&"){if(J.trim())Z.push(J.trim());J="",X++;continue}if(Q==="&")return null;if(Q===";"){if(J.trim())Z.push(J.trim());J="";continue}J+=Q}if(J.trim())Z.push(J.trim());return Z.length>0?Z:null}function ZJ($){let Z=!1,J=!1,W=!1;for(let Y=0;Y<$.length;Y++){let K=$[Y];if(W){W=!1;continue}if(K==="\\"&&!Z){W=!0;continue}if(K==="'"&&!J){Z=!Z;continue}if(K==='"'&&!Z){J=!J;continue}if(Z)continue;if(K==="$"){let X=$[Y+1];if(X&&/[A-Za-z_@*#?!$0-9({]/.test(X))return!0}if(K==="`")return!0;if(J)continue;if(K==="|")return!0;if(K===">"||K==="<")return!0;if(K==="{"){let X=$.slice(Y);if(/^\{[^}]*,[^}]*\}/.test(X)||/^\{[^}]*\.\.[^}]*\}/.test(X))return!0}}return!1}function H$($){let Z=[],J="",W=!1,Y=!1,K=!1;for(let X=0;X<$.length;X++){let Q=$[X];if(K){J+=Q,K=!1;continue}if(Q==="\\"&&!W){if(K=!0,Y){let H=$[X+1];if(H&&'$`"\\'.includes(H))continue;J+=Q,K=!1}continue}if(Q==="'"&&!Y){W=!W;continue}if(Q==='"'&&!W){Y=!Y;continue}if(!W&&!Y&&/[ \t]/.test(Q)){if(J)Z.push(J),J="";continue}J+=Q}if(J)Z.push(J);return Z}var x8=new Set(["npm","pnpm","yarn","bun"]),JJ=new Set(["biome","eslint","jest","mypy","pyright","pytest","ruff","tsc","vitest"]),I8=new Set(["-u","--fix","--update","--update-snapshot","--updateSnapshot","--watch","--watchAll","--write"]),h8=/[ \t]*;[ \t]*echo[ \t]+"[A-Za-z0-9 _:=.-]*(?:\$\{PIPESTATUS\[0\]\}|\$\?)[A-Za-z0-9 _:=.-]*"[ \t]*$/;function v8($){return $!==void 0&&/^(?:test|lint|build|type-?check)(?::[\w.-]+)*$/i.test($)}function WJ($){return $.replace(/\s+2>&1\s*$/,"").trim()}function C8($,Z,J){if(!J||Z.length!==2)return;let W=/^(.+?)[ \t]+&&[ \t]+([\s\S]+)$/.exec($);if(!W)return;let Y=H$(W[1]??"");if(Y.length!==2||Y[0]!=="cd")return;let K=Y[1];if(!K||K==="-")return;let X=V$.isAbsolute(K)?V$.resolve(K):V$.resolve(J,K);if(!z$.isWithinWorkspace(X,J))return;return W[2]?.trim()||void 0}function g8($){let Z=[],J=!1,W=!1,Y=!1;for(let K=0;K<$.length;K++){let X=$[K];if(Y){Y=!1;continue}if(X==="\\"&&!J){Y=!0;continue}if(X==="'"&&!W){J=!J;continue}if(X==='"'&&!J){W=!W;continue}if(X!=="|"||J||W)continue;if($[K+1]==="|")return;Z.push(K)}return Z}function p8($){let Z=H$($),[J,W,Y]=Z;if(J!=="head"&&J!=="tail")return!1;if(Z.length===1)return!0;let K=(X)=>X!==void 0&&/^[1-9]\d{0,4}$/.test(X);if(Z.length===2)return W?.startsWith("--lines=")&&K(W.slice(8))||W?.startsWith("-")&&K(W.slice(1));return Z.length===3&&(W==="-n"||W==="--lines")&&K(Y)}function u8($){let Z=WJ($.replace(h8,"").trim()),J=g8(Z);if(!J)return;if(J.length===0)return YJ(Z);if(J.length!==1)return;let W=J[0];if(W===void 0)return;let Y=WJ(Z.slice(0,W).trim()),K=Z.slice(W+1).trim();if(!Y||!p8(K))return;return YJ(Y)}function YJ($){let J=e$($)?.at(-1);if(!J)return $;let W=H$(J),[Y,K]=W;if(!(Y==="vitest"||(Y==="npx"||Y==="bunx")&&K==="vitest")||W.some((Q)=>Q==="--configLoader"||Q.startsWith("--configLoader=")))return $;return`${$} --configLoader runner`}function f$($,Z){let J=u8($);if(!J)return!1;let W=t$(J),Y=e$(W);if(!Y||ZJ(W)||/[\r\n]/.test(W))return!1;let K=Y.length===1?Y[0]:C8(W,Y,Z);if(!K)return!1;let X=H$(K);if(X.length===0||X.some((z)=>[...I8].some((B)=>z===B||z.startsWith(`${B}=`))))return!1;let[Q,H,V]=X;if(x8.has(Q??""))return v8(H==="run"?V:H)||H==="--test";if((Q==="npx"||Q==="bunx")&&JJ.has(H??""))return!0;if(JJ.has(Q??""))return!0;if(Q==="node"&&H==="--test")return!0;if(Q==="go"&&["build","test","vet"].includes(H??""))return!0;return Q==="cargo"&&["build","check","clippy","test"].includes(H??"")}function a5($,Z){if($===void 0)return!0;if(typeof $!=="string"||$.split(/[\\/]/).includes(".."))return!1;if(!Z)return!V$.isAbsolute($);let J=V$.isAbsolute($)?V$.resolve($):V$.resolve(Z,$);return z$.isWithinWorkspace(J,Z)}var MZ=T0("Agent"),m8=3;function kZ($,Z,J){if($!=="length")return{action:"none"};if(Z>=m8)return{action:"truncated"};if(s6(J)==="stop")return MZ.info("[Loop] Token budget: diminishing returns detected, skipping recovery"),{action:"budget_stop"};return{action:"recover"}}var d8=[/:\s*$/,/:\s*$/,/\.\.\.\s*$/,/让我(先|来|开始|查看|检查|修复)/,/Let me (first|start|check|look|fix)/i,/I('ll| will) (now |)(create|write|edit|update|modify|fix|add|implement)/i,/我(现在就|来|要)(创建|写入|编辑|修改|修复|添加|实现)/,/\d+\.\s+(First|Next|Then|Finally)/i],c8=/```[\s\S]{50,}```/,KJ="请执行你提到的操作,不要只是描述。使用 Edit/Write/ApplyPatch/Bash 工具来实际修改文件。",l8=2;function xZ($,Z,J=!0){if(!$||Z>=l8)return{action:"none"};if(!J&&c8.test($))return{action:"retry",prompt:KJ};let W=$.slice(-200),Y=W.match(/```/g);if(Y&&Y.length%2!==0)return{action:"none"};if(d8.some((X)=>X.test(W)))return{action:"retry",prompt:KJ};return{action:"none"}}var h1=2,i8="The model returned tool-call JSON as text instead of completing the requested tool workflow.",r8="The previous response contained tool-call JSON as ordinary text. It did not execute a tool. If the requested operation is still needed, use the native tool-call interface with an available tool. If it already succeeded, use the recorded result to answer instead of repeating the operation. Do not return another tool-call JSON envelope as your final answer.";function IZ($,Z,J,W){if(!$||$.length>65536||J.length===0)return{action:"none"};let Y=Z.replace(/```[\s\S]*?(?:```|$)/g,"").replace(/^\s*>.*$/gm,"");if(/\b(?:example|schema|serialize|serialization|quote|print|illustrate|verbatim)\b|示例|样例|序列化|引用原文/i.test(Y)||/\b(?:explain|show|return|output)\b[^.!?\n]{0,80}\b(?:json|tool.calls?)\b|(?:解释|展示|输出|返回)[^。!?\n]{0,40}(?:JSON|工具调用格式)/i.test(Y)||/\b(?:do not|don't|never)\s+(?:use|call|invoke|execute)\s+(?:any\s+)?tools?\b|不要(?:使用|调用|执行)(?:任何)?工具/i.test(Y))return{action:"none"};let K;try{K=JSON.parse($)}catch{return{action:"none"}}if(!K||typeof K!=="object"||Array.isArray(K)||Object.keys(K).length!==1||!("tool_calls"in K)||!Array.isArray(K.tool_calls)||K.tool_calls.length===0||K.tool_calls.length>32)return{action:"none"};let X=new Set;for(let Q of K.tool_calls){if(!Q||typeof Q!=="object"||Array.isArray(Q))return{action:"none"};let H="function"in Q;if(Object.keys(Q).some((L)=>!["id","type",...H?["function"]:["name","arguments"]].includes(L)))return{action:"none"};if("type"in Q&&Q.type!=="function")return{action:"none"};let V=H?Q.function:Q;if(!V||typeof V!=="object"||Array.isArray(V)||!("name"in V)||typeof V.name!=="string"||!("arguments"in V))return{action:"none"};if(H&&Object.keys(V).some((L)=>L!=="name"&&L!=="arguments"))return{action:"none"};if(!J.includes(V.name))return{action:"none"};let z=V.arguments;if(typeof z!=="string"&&(!z||typeof z!=="object"||Array.isArray(z)))return{action:"none"};let B=V.name.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),j=new RegExp(`(?:^|[.!?。!?;;\\n])\\s*(?:please\\s+)?(?:call|invoke|execute|run|use)\\s+(?:the\\s+)?(?:tool\\s+)?[\`"']?${B}(?![\\w:-])|(?:^|[。!?;\\n])\\s*(?:请)?(?:调用|使用|执行)\\s*(?:工具\\s*)?[\`"']?${B}(?![\\w:-])`,"i"),w=new RegExp(`(?:do not|don't|never)\\s+(?:call|invoke|execute|run|use)\\s+(?:the\\s+)?(?:tool\\s+)?[\`"']?${B}(?![\\w:-])|(?:不要|禁止)(?:调用|使用|执行)\\s*(?:工具\\s*)?[\`"']?${B}(?![\\w:-])`,"i");if(!j.test(Y)||w.test(Y))return{action:"none"};X.add(V.name)}return W<h1?{action:"retry",prompt:r8,...X.size===1?{toolName:[...X][0]}:{}}:{action:"fail",message:i8}}var n8=[/\b(?:run|execute|rerun|re-run)\b[\s\S]{0,60}\b(?:tests?|test suite|lint|type-?check|build)\b/i,/\b(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?(?:test|lint|build|type-?check)\b/i,/(?:运行|执行|跑|重新运行).{0,30}(?:测试|单测|集成测试|检查|构建)/],XJ={test:/\b(?:tests?|test suite)\b|(?:测试|单测|集成测试)/i,lint:/\blint(?:ing)?\b/i,"type-check":/\btype[\s-]?check(?:ing)?\b|\btsc\b|类型检查/i,build:/\bbuild\b|构建/i},o8={test:/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?test\b|(?:^|\s)(?:node|bun)\s+--test\b|(?:^|\s)(?:vitest|jest|pytest|go\s+test|cargo\s+test)\b/i,lint:/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?lint\b/i,"type-check":/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?type-?check\b|(?:^|\s)tsc\b/i,build:/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?build\b/i},a8="The user explicitly required verification, but it has not run successfully. Do not finish or explain. Your next action must be a Bash tool call that runs the requested test, lint, type-check, or build command. Inspect the command result and fix any failure before finishing.",s8="Required verification did not run successfully before the retry limit.",t8=3;function HJ($,Z,J,W){if(!J.success)return;if(["Edit","Write","ApplyPatch","NotebookEdit"].includes(Z)){$.clear();return}if(Z==="Bash"&&typeof J.metadata?.command==="string"&&J.metadata.exit_code===0&&f$(J.metadata.command,W)){$.add(J.metadata.command);return}if(!["Task","TaskOutput"].includes(Z))return;let Y=J.metadata?.verificationCommands;if(!Array.isArray(Y))return;for(let K of Y)if(typeof K==="string"&&f$(K,W))$.add(K)}function hZ($,Z,J){if(!$||!n8.some((H)=>H.test($)))return{action:"none"};let W=Object.keys(XJ).filter((H)=>XJ[H].test($)),Y=[...Z],K=W.filter((H)=>!Y.some((V)=>o8[H].test(V)));if(W.length>0?K.length===0:Y.some((H)=>f$(H)))return{action:"none"};if(J>=t8)return{action:"fail",message:s8};let Q=W.length>1&&K.length>0?` Missing successful verification categories: ${K.join(", ")}.`:"";return{action:"retry",prompt:`${a8}${Q}`}}var e8=[/\bdelegate\b[\s\S]{0,120}\b(?:Task tool|subagent|agent)\b/i,/\b(?:call|use|invoke)\b[\s\S]{0,80}\bTask tool\b/i,/(?:委派|交给|调用|使用).{0,60}(?:Task|子代理|子智能体)/],VJ=[/\b(?:do not|don't|never)\s+(?:delegate|call|use|invoke)\b/i,/(?:不要|禁止|无需)(?:委派|调用|使用).{0,20}(?:Task|子代理|子智能体)?/];function zJ($){return typeof $==="string"&&VJ.some((Z)=>Z.test($))}var $9=[/\b(?:call|use|invoke)\b[\s\S]{0,30}\bTask(?: tool)?\b[\s\S]{0,30}\bexactly once\b/i,/\bexactly once\b[\s\S]{0,30}\b(?:call|use|invoke)\b[\s\S]{0,30}\bTask(?: tool)?\b/i,/\bexactly one\b[\s\S]{0,30}\bTask(?: tool)? calls?\b/i,/(?:Task|子代理).{0,20}(?:恰好|仅|只)(?:调用|使用)?一次/,/(?:恰好|仅|只)(?:调用|使用)?一次.{0,20}(?:Task|子代理)/],Z9=[/\b(?:do not|don't|never)\s+(?:call|use|invoke)\s+(?:the\s+)?Task\b[\s\S]{0,30}\bexactly once\b/i,/\bTask\b[\s\S]{0,30}\b(?:does not|doesn't|need not)\b[\s\S]{0,30}\bexactly once\b/i,/\bmultiple\s+Task(?: tool)?\s+calls?\s+(?:are\s+)?allowed\b/i,/(?:不要|禁止).{0,12}(?:Task|子代理).{0,12}(?:恰好|仅|只)(?:调用|使用)?一次/];function J9($){if(typeof $!=="string")return;if(Z9.some((Z)=>Z.test($)))return"multiple-allowed";return $9.some((Z)=>Z.test($))?"required":void 0}function Z1($){for(let Z of $){let J=J9(Z);if(J!==void 0)return J==="required"}return!1}var W9="The user explicitly required delegation, but no Task tool call completed successfully. Do not solve the task directly or explain. Your next action must be a Task tool call using the requested subagent.",Y9="Required delegation did not complete before the retry limit.",K9=3;function jJ($,Z,J){let W=(typeof $==="string"?[$]:$??[]).map((X)=>X.trim()).filter(Boolean),Y=Z1(W),K=!1;if(!Y)for(let X of W){if(VJ.some((Q)=>Q.test(X)))break;if(e8.some((Q)=>Q.test(X))){K=!0;break}}if(W.length===0||!Y&&!K||Z.has("Task"))return{action:"none"};if(J>=K9)return{action:"fail",message:Y9};return{action:"retry",prompt:W9}}var X9=[/\b(?:use|create|enter|start|work\s+(?:in|inside))\b.{0,60}\bworktree\b/i,/(?:使用|创建|进入).{0,30}(?:worktree|工作树)/i],Q9=[/\b(?:exit|leave)\b.{0,40}\bworktree\b/i,/\bworktree\b.{0,60}\b(?:action\s+)?(?:keep|remove)\b/i,/(?:退出|离开).{0,30}(?:worktree|工作树)/i],H9=[/\b(?:do not|don't|never|must not|should not)\b[^.!?;\n]{0,80}\b(?:git\s+)?worktree\b/gi,/\bwithout\b[^.!?;\n]{0,60}\b(?:git\s+)?worktree\b/gi,/(?:不要|禁止|不得|无需)[^。!?;\n]{0,50}(?:worktree|工作树)/gi];function BJ($){return H9.reduce((Z,J)=>Z.replace(J," "),$)}function v1($){if(typeof $!=="string")return!1;let Z=BJ($);return X9.some((J)=>J.test(Z))}var V9="The user explicitly required git worktree isolation, but EnterWorktree has not completed successfully. Do not continue in the original workspace. Your next action must be an EnterWorktree tool call. Wait for its result before using file or Bash tools.",z9="The user explicitly required leaving the managed worktree, but ExitWorktree has not completed successfully. Do not finish or explain. Your next action must be an ExitWorktree tool call using the action requested by the user.",j9="Required worktree lifecycle did not complete before the retry limit.",B9=3;function DJ($,Z,J){if(!$)return{action:"none"};let W=BJ($);if(!v1(W))return{action:"none"};let Y=Q9.some((X)=>X.test(W));if(Z.has("TaskWorktree"))return{action:"none"};let K=!Z.has("EnterWorktree")?"EnterWorktree":Y&&!Z.has("ExitWorktree")?"ExitWorktree":void 0;if(!K)return{action:"none"};if(J>=B9)return{action:"fail",message:j9};return{action:"retry",tool:K,prompt:K==="EnterWorktree"?V9:z9}}var QJ=30000;async function vZ($){try{let J=E$.getInstance().executeStopHooks({projectDir:$.workspaceRoot??j0(),sessionId:$.sessionId,permissionMode:$.permissionMode,reason:$.reason,abortSignal:$.abortSignal}),W,Y=new Promise((K)=>{W=setTimeout(()=>K("timeout"),QJ)});try{let K=await Promise.race([J,Y]);if(K==="timeout")return MZ.warn(`[Loop] Stop hook 超时 (${QJ}ms),按 shouldStop: true 处理`),{action:"stop"};let X=K;if(!X.shouldStop)return{action:"continue",reason:X.continueReason};return{action:"stop"}}finally{clearTimeout(W)}}catch(Z){return MZ.warn("[Loop] Stop hook execution failed:",Z),{action:"stop"}}}async function D9($,Z){let J;while(!(J=await $.next()).done)if(Z)await Z(J.value);return J.value}var w9=[/<system-reminder>[\s\S]*?<\/system-reminder>/gi,/<file[^>]*>[\s\S]*?<\/file>/gi,/<hooks_context>[\s\S]*?<\/hooks_context>/gi,/<[^>]+>/g];function U9($){if(typeof $==="string")return $;if(Array.isArray($))return $.map((Z)=>{if(typeof Z==="string")return Z;if(Z&&typeof Z==="object"&&"text"in Z){let J=Z.text;return typeof J==="string"?J:""}return""}).join(" ");return""}function q9($){let Z=$;for(let H of w9)Z=Z.replace(H," ");Z=Z.replace(/^\s*\/[a-zA-Z][\w-]*\s+/,"");let J=Z.replace(/\s+/g," ").trim();if(!J)return"";let W=J.match(/^(.+?)(?:[.!?]\s|[。!?](?=\S|$)|$)/),Y=W&&W[1].length>=6?W[1]:J;if(Y=Y.trim().replace(/[\s.。!!??,,;;::-]+$/,""),Y.length<=60)return Y;let K=Y.slice(0,60),X=K.lastIndexOf(" ");return`${(X>36?K.slice(0,X):K).trimEnd()}…`}function wJ($){return q9(U9($))}import{EventEmitter as G9}from"events";import UJ from"node:path";function CZ($){if(GJ($.sessionId),!UJ.isAbsolute($.projectPath))throw Error("projectPath must be absolute");return{sessionId:$.sessionId,projectPath:UJ.resolve($.projectPath)}}function qJ($){let Z=CZ($);return JSON.stringify([Z.projectPath,Z.sessionId])}function V3($,Z){return qJ($)===qJ(Z)}class S$ extends G9{static instance;constructor(){super();this.setMaxListeners(100)}static getInstance(){if(!S$.instance)S$.instance=new S$;return S$.instance}publish($,Z,J,W){let Y=CZ($);this.emit("event",{sessionId:Y.sessionId,projectPath:Y.projectPath,type:Z,...W!==void 0?{seq:W}:{},properties:J})}subscribe($){return this.on("event",$),()=>this.off("event",$)}}var J1=S$.getInstance();var $$=T0("Agent"),C1=new Set;async function L9($,Z){let J=$.sessionId;if(!J||$.subagentInfo)return;if(C1.has(J))return;if(C1.size>=5000)C1.clear();C1.add(J);try{let W=$.workspaceRoot,Y=await W1.findSessionMetadata(J,W);if(!Y)return;if(Y.title&&Y.title.trim())return;let K=wJ(Z);if(!K)return;await W1.updateSessionMetadata(J,Y.projectPath,{title:K}),J1.publish({sessionId:J,projectPath:Y.projectPath},"session.updated",{title:K})}catch(W){$$.debug?.("[Loop] 自动生成会话标题失败:",W)}}var gZ=`<turn_aborted>
2
2
  The previous turn was interrupted. Commands or tool calls may have partially completed; inspect the workspace and running processes before retrying.
3
3
  </turn_aborted>`,j$="Tool execution was blocked because its durable call record could not be committed. No tool side effect was started.",LJ="Tool execution completed, but its durable result record could not be committed. Further model and tool execution was stopped. The operation may have completed; inspect external state before retrying.";class T$ extends Error{phase;constructor($,Z){super($==="user_message"?"Conversation input could not be committed. No further model request was started.":"Model output could not be committed. The run was stopped before any further model request or successful completion.",Z);this.phase=$;this.name="DurableConversationPersistenceError"}}function B$($){return $.executionEngine?.getContextManager()}async function i0($,Z,J,W=null,Y,K={}){let X=K.required??$.executionEngine!==void 0;try{let Q=B$($),H=typeof J==="string"?J.trim()!=="":J.some((V)=>V.type==="text"?V.text.trim()!=="":!0);if(Q&&Z.sessionId&&H){let V=await Q.saveMessage(Z.sessionId,"user",J,W,Y,Z.subagentInfo);if(X&&!V)throw Error("Durable user-message commit returned no identity");if(Y?.clientVisible!==!1)L9(Z,J);return V}if(X&&Z.sessionId&&H)throw Error("Durable user-message storage is unavailable")}catch(Q){if($$.warn("[Loop] 保存用户消息失败:",Q),X)throw new T$("user_message",{cause:Q})}return null}async function C0($,Z,J,W,Y,K,X={}){let Q=X.required??$.executionEngine!==void 0;try{let H=B$($),V=Boolean(J.trim()||Y?.trim());if(H&&Z.sessionId&&V){let z=await H.saveMessage(Z.sessionId,"assistant",J,W,K,Z.subagentInfo,Y);if(Q&&!z)throw Error("Durable assistant-message commit returned no identity");return z}if(Q&&Z.sessionId&&V)throw Error("Durable assistant-message storage is unavailable")}catch(H){if($$.warn("[Loop] 保存助手消息失败:",H),Q)throw new T$("assistant_message",{cause:H})}return null}async function FJ($,Z,J){try{let W=B$($);if(W&&Z.sessionId)return await W.saveMessage(Z.sessionId,"system",gZ,J,void 0,Z.subagentInfo)}catch(W){$$.warn("[Loop] 保存中断边界失败:",W)}return null}async function OJ($,Z,J,W,Y){try{let K=B$($);if(!K||!Z.sessionId||J.length===0)return null;return await K.saveMessage(Z.sessionId,"system",`<contextual-project-instructions-ref count="${J.length}" />`,Y,{contextualProjectRules:!0,ruleReferences:JSON.parse(JSON.stringify(J.map((X)=>({...X})))),triggerPaths:[...W]},Z.subagentInfo)}catch(K){$$.warn("[Loop] 保存 contextual project rules provenance 失败:",K)}return null}async function pZ($,Z,J,W,Y,K={}){try{let X=B$($);if(X&&Z.sessionId){let Q=await X.saveToolUse(Z.sessionId,J,W,Y,Z.subagentInfo,K.providerToolCallId);if(K.required&&!Q)throw Error("Durable tool-use commit returned no identity");return Q}if(K.required&&Z.sessionId)throw Error("Durable tool-use storage is unavailable")}catch(X){if($$.warn("[Loop] 保存工具调用失败:",X),K.required)throw X}return null}async function g1($,Z,J,W,Y,K,X,Q,H,V={}){try{let z=B$($);if(z&&Z.sessionId){let B=await z.saveToolResult(Z.sessionId,J,W,Y,K,X,Z.subagentInfo,Q,H);if(V.required&&!B)throw Error("Durable tool-result commit returned no identity");return B}if(V.required&&Z.sessionId)throw Error("Durable tool-result storage is unavailable")}catch(z){if($$.warn("[Loop] 保存工具结果失败:",z),V.required)throw z}return null}async function Y1($,Z,J,W,Y={}){try{let K=B$($);if(K&&Z.sessionId){let X=await K.saveCompaction(Z.sessionId,J,W,null);if(Y.required&&!X)throw Error("Compaction checkpoint commit returned no identity");return X||null}if(Y.required&&Z.sessionId)throw Error("Compaction checkpoint storage is unavailable")}catch(K){if($$.warn("[Loop] 保存压缩数据失败:",K),Y.required)throw K}return null}async function V0($){let{deps:Z,context:J,state:W,assistantContent:Y,assistantReasoningContent:K,lastMessageUuid:X,controlPrompt:Q}=$;W.appendAssistant({role:"assistant",content:Y,reasoningContent:K});let H=X,V=await C0(Z,J,Y,H,K);if(V)H=V;if(Q!==void 0){let z={role:"user",content:Q,metadata:E0};W.appendControl("user",z);let B=await i0(Z,J,Q,H,E0);if(B)H=B}return H}import{createHash as R6}from"node:crypto";import{promises as i9}from"node:fs";import r9 from"node:path";import{nanoid as J$}from"nanoid";import*as t from"node:fs/promises";import*as Z$ from"node:path";import NJ from"write-file-atomic";var PJ={enabled:!0,maxIndexLines:200};var F9="memory",uZ="MEMORY.md",dZ="<!-- blade:auto-memory-topics:start -->",p1="<!-- blade:auto-memory-topics:end -->",O9={realpath:!1,retries:{retries:5,factor:1.2,minTimeout:20,maxTimeout:100,randomize:!0}},P9=new R$,_J;function bJ($){return $.trim().replace(/\s+/g," ")}function N9($){return bJ($.replace(/^- \[\d{4}-\d{2}-\d{2}\] /,""))}function _9($){return[dZ,"## Auto-consolidated topics",...$.map((Z)=>`- [${Z}](${Z}.md)`),p1].join(`
4
4
  `)}function A9($,Z){let J=_9(Z),W=$.indexOf(dZ),Y=$.indexOf(p1,Math.max(0,W));if(W>=0&&Y>=W)return $.slice(0,W)+J+$.slice(Y+p1.length);if(!$)return`${J}
@@ -93,7 +93,7 @@ Full output saved to: ${Q}`}catch{return`${Z}
93
93
  ${Y}`}}function W2(){return{successfulBash:!1}}function w4($){return typeof $==="string"&&J2.some((Z)=>Z===$)}function O7($){switch($){case"timeout":case"admission":case"spawn":case"finalization":return $;case"unavailable":return"terminal";default:return}}function P7($){return["<goal-execution-host-failure>",`Category: ${$.category}`,`Consecutive turns: ${$.consecutiveCount}/3`,"</goal-execution-host-failure>","","The execution host has failed in consecutive Goal turns. Do not blindly","repeat the same command path. Validate shell, sandbox, and terminal","availability, then switch to a different executable strategy or call","UpdateGoal blocked with concrete evidence if external intervention is required."].join(`
94
94
  `)}function Y2($,Z,J){if(Z!=="Bash")return;if(J.success){$.successfulBash=!0;return}let W=J.metadata?.execution_host_failure;if(w4(W))$.category=W}function K2($){return $.successfulBash?void 0:$.category}import h4 from"node:path";import{nanoid as v4}from"nanoid";import{randomUUID as j1}from"node:crypto";import*as g0 from"node:fs/promises";import*as z2 from"node:path";import{Mutex as O4}from"async-mutex";import P4 from"write-file-atomic";var X2=120,W6=128;function z1($){if(!Array.isArray($)||$.length>120||!$.every((Z)=>typeof Z==="string"&&Z.length>0&&Z.length<=128))return;return[...new Set($)]}function U4($){if(!$||typeof $!=="object"||Array.isArray($))return[];if(!("recovery"in $)||!$.recovery)return[];let Z=$.recovery;if(typeof Z!=="object"||Array.isArray(Z))return[];if(!("version"in Z)||Z.version!==1&&Z.version!==2&&Z.version!==3||!("inputMessageIds"in Z)||!("hadSuccessfulToolResult"in Z)||typeof Z.hadSuccessfulToolResult!=="boolean"||!("emptyFinalCorrectionSpent"in Z)||typeof Z.emptyFinalCorrectionSpent!=="boolean"||!("acknowledgedInputMessageIds"in $))return[];if((Z.version===2||Z.version===3)&&(!("interruptedToolCallCount"in Z)||!Number.isSafeInteger(Z.interruptedToolCallCount)||Z.interruptedToolCallCount<0))return[];if(Z.version===3&&(!("allSuccessfulToolResultsSafeForResume"in Z)||typeof Z.allSuccessfulToolResultsSafeForResume!=="boolean"))return[];let J=z1(Z.inputMessageIds),W=z1($.acknowledgedInputMessageIds);if(!J||!W)return[];let Y=new Set(J);return W.filter((K)=>Y.has(K))}function l1($,Z){let J=$[Z];if(J?.type!=="turn_aborted")return[];let W=U4(J.data);if(W.length===0)return[];let Y=-1;for(let X=Z-1;X>=0;X--){let Q=$[X];if(Q.type==="turn_started"){if(Q.data.turnId!==J.data.turnId)return[];Y=X;break}if(Q.type==="turn_completed"||Q.type==="turn_aborted")return[]}if(Y<0)return[];let K=new Set;for(let X=Y+1;X<Z;X++){let Q=$[X];if(Q.type!=="message_created"||Q.data.role!=="user")continue;let H=Q.data.metadata,V=Q.data.inboxMessageId!==void 0?Q.data.inboxMessageId:H!==null&&typeof H==="object"&&!Array.isArray(H)?H.inboxMessageId:void 0;if(typeof V==="string"&&V.length>0&&V.length<=128)K.add(V)}return W.filter((X)=>K.has(X))}import*as r1 from"node:fs/promises";import*as H2 from"node:path";var q4={realpath:!1,retries:{retries:150,factor:1.2,minTimeout:10,maxTimeout:100,randomize:!0}},G4=new R$,Q2;async function h$($,Z,J,W=F4){let Y=w$($,Z);return G4.runExclusive(Y,()=>i1($,Z,async(K)=>{let X=H2.dirname(K.inboxPath);await r1.mkdir(X,{recursive:!0,mode:448}),await r1.chmod(X,448);let Q,H=await W(K.inboxPath,{...q4,onCompromised:(V)=>{Q=V}});try{if(Q)throw Q;let V=await J(K);if(Q)throw Q;return V}finally{await H()}}))}async function L4(){return Q2??=await import("proper-lockfile"),Q2}async function F4($,Z){return(await L4()).lock($,Z)}var X6=2,v$=8388608;function Y6($,Z,J){let W={version:X6,sessionId:$,generation:Z,messages:J.map(({recovered:Y,...K})=>K)};return`${JSON.stringify(W)}
95
95
  `}function K6($,Z){return $ instanceof Error&&"code"in $&&$.code===Z}function N4($){if(typeof $==="string")return!0;if(!Array.isArray($))return!1;return $.every((Z)=>{if(!Z||typeof Z!=="object"||!("type"in Z))return!1;if(Z.type==="text")return"text"in Z&&typeof Z.text==="string";return Z.type==="image_url"&&"image_url"in Z&&typeof Z.image_url==="object"&&Z.image_url!==null&&"url"in Z.image_url&&typeof Z.image_url.url==="string"})}function _4($,Z,J){let W;try{W=JSON.parse($)}catch(K){throw Error(`Invalid steering inbox JSON: ${Z}`,{cause:K})}if(!W||typeof W!=="object"||!("version"in W)||W.version!==1&&W.version!==X6||!("sessionId"in W)||W.sessionId!==J||!("messages"in W)||!Array.isArray(W.messages))throw Error(`Invalid steering inbox record: ${Z}`);let Y=W.messages.map((K)=>{if(!K||typeof K!=="object"||!("id"in K)||typeof K.id!=="string"||!("content"in K)||!N4(K.content)||!("queuedAt"in K)||typeof K.queuedAt!=="number"||"persisted"in K&&typeof K.persisted!=="boolean"||"origin"in K&&K.origin!=="user"&&K.origin!=="background_subagent"&&K.origin!=="team_message"&&K.origin!=="interaction_recovery"&&K.origin!=="user_shell"||"metadata"in K&&(K.metadata===null||typeof K.metadata!=="object"||Array.isArray(K.metadata))||"outputSchema"in K&&K.outputSchema!==void 0&&(!K.outputSchema||typeof K.outputSchema!=="object"||Array.isArray(K.outputSchema)))throw Error(`Invalid steering inbox message: ${Z}`);let X="outputSchema"in K&&K.outputSchema!==void 0?n1(K.outputSchema).schema:void 0;return{id:K.id,content:K.content,queuedAt:K.queuedAt,..."persisted"in K&&K.persisted===!0?{persisted:!0}:{},..."origin"in K&&K.origin?{origin:K.origin}:{},..."metadata"in K&&K.metadata?{metadata:JSON.parse(JSON.stringify(K.metadata))}:{},...X?{outputSchema:X}:{}}});if(new Set(Y.map((K)=>K.id)).size!==Y.length)throw Error(`Duplicate steering inbox message: ${Z}`);if(W.version===1)return{version:1,sessionId:J,messages:Y};if(!("generation"in W)||typeof W.generation!=="string"||!/^[a-f0-9-]{36}$/.test(W.generation))throw Error(`Invalid steering inbox generation: ${Z}`);return{version:X6,sessionId:J,generation:W.generation,messages:Y}}function A4($){return new Set($.flatMap((Z,J)=>{if(Z.type==="inbox_acknowledged")return Z.data.messageIds;if(Z.type==="turn_aborted")return l1($,J);return[]}))}function b4($){return new Set($.flatMap((Z)=>{if(Z.type!=="message_created"||Z.data.role!=="user")return[];let J=Z.data.metadata,W=Z.data.inboxMessageId!==void 0?Z.data.inboxMessageId:J!==null&&typeof J==="object"&&!Array.isArray(J)?J.inboxMessageId:void 0;return typeof W==="string"?[W]:[]}))}class o1{sessionId;stateStorage;writeFile;lockFile;mutex=new O4;generation=j1();messages=[];constructor($,Z,J,W){this.sessionId=$;this.stateStorage=Z;this.writeFile=J;this.lockFile=W}static async open($,Z,J=U$($),W={}){let Y=new o1(Z,J,W.writeFile??P4,W.lockFile);return await Y.loadAndReconcile(),Y}async enqueue($,Z){return this.mutex.runExclusive(async()=>{let J=await h$(this.stateStorage,this.sessionId,async(W)=>{let Y=await this.readAndReconcileAtPath(W);if(Y.messages.some((H)=>H.id===$.id))return{accepted:!0,snapshot:Y};if(Z&&!Z(Y.messages))return{accepted:!1,snapshot:Y};let K=[...Y.messages,{...$,recovered:!1}],X=j1(),Q=Y6(this.sessionId,X,K);if(Buffer.byteLength(Q)>v$)return{accepted:!1,snapshot:Y};return await this.persistAtPath(K,X,W,Q),{accepted:!0,snapshot:{generation:X,messages:K}}},this.lockFile);return this.install(J.snapshot),J.accepted})}async acknowledge($){if($.length===0)return;let Z=new Set($);await this.mutex.runExclusive(async()=>{let J=await h$(this.stateStorage,this.sessionId,async(W)=>{let Y=await this.readAndReconcileAtPath(W),K=Y.messages.filter((Q)=>!Z.has(Q.id));if(K.length===Y.messages.length&&!Y.acknowledgedRemoved)return Y;let X=j1();return await this.persistAtPath(K,X,W),{generation:X,messages:K}},this.lockFile);this.install(J)})}snapshot(){return{generation:this.generation,messages:this.list()}}async refresh(){return this.mutex.runExclusive(async()=>{let $=await h$(this.stateStorage,this.sessionId,(Z)=>this.readAndReconcileAtPath(Z),this.lockFile);return this.install($),this.snapshot()})}async replace($,Z){return this.mutex.runExclusive(async()=>{let J=await h$(this.stateStorage,this.sessionId,async(W)=>{let Y=await this.readAndReconcileAtPath(W);if(Y.generation!==$)return{replaced:!1,snapshot:Y};let K=j1(),X=Z.map((H)=>({...H})),Q=Y6(this.sessionId,K,X);if(Buffer.byteLength(Q)>v$)return{replaced:!1,snapshot:Y};return await this.persistAtPath(X,K,W,Q),{replaced:!0,snapshot:{generation:K,messages:X}}},this.lockFile);return this.install(J.snapshot),{replaced:J.replaced,snapshot:this.snapshot()}})}list(){return this.messages.map(($)=>({...$,content:typeof $.content==="string"?$.content:$.content.map((Z)=>Z.type==="text"?{...Z}:{...Z,image_url:{...Z.image_url}}),...$.outputSchema?{outputSchema:JSON.parse(JSON.stringify($.outputSchema))}:{},...$.metadata?{metadata:JSON.parse(JSON.stringify($.metadata))}:{}}))}count(){return this.messages.length}recoveredCount(){return this.messages.filter(($)=>$.recovered).length}async loadAndReconcile(){await this.mutex.runExclusive(async()=>{let $=await h$(this.stateStorage,this.sessionId,async(Z)=>{let J=await this.readAndReconcileAtPath(Z);if(J.migrationRequired||J.acknowledgedRemoved){let W=j1();return await this.persistAtPath(J.messages,W,Z),{generation:W,messages:J.messages}}return J},this.lockFile);this.install($)})}install($){this.generation=$.generation,this.messages=$.messages}async readAndReconcileAtPath($){let Z;try{let X=await g0.open($.inboxPath,"r");try{if((await X.stat()).size>v$)throw Error(`Steering inbox exceeds ${v$} bytes: ${$.inboxPath}`);Z=_4(await X.readFile("utf8"),$.inboxPath,this.sessionId)}finally{await X.close()}await g0.chmod($.inboxPath,384)}catch(X){if(!K6(X,"ENOENT"))throw X}let J=new Set,W=new Set;try{let X=V2(await g0.readFile($.transcriptPath,"utf8"),$.transcriptPath);J=A4(X),W=b4(X)}catch(X){if(!K6(X,"ENOENT"))throw X}let Y=new Map(this.messages.map((X)=>[X.id,X.recovered])),K=(Z?.messages??[]).filter((X)=>!J.has(X.id)).map((X)=>({...X,recovered:Y.get(X.id)??!0,...X.persisted===!0||W.has(X.id)?{persisted:!0}:{}}));return{generation:Z?.version===2?Z.generation:this.generation,messages:K,...Z?.version===1&&K.length>0?{migrationRequired:!0}:{},...Z&&K.length!==Z.messages.length?{acknowledgedRemoved:!0}:{}}}async persistAtPath($,Z,J,W){if(await g0.mkdir(z2.dirname(J.inboxPath),{recursive:!0,mode:448}),$.length===0){await g0.unlink(J.inboxPath).catch((K)=>{if(!K6(K,"ENOENT"))throw K});return}let Y=W??Y6(this.sessionId,Z,$);if(Buffer.byteLength(Y)>v$)throw Error(`Steering inbox exceeds ${v$} bytes: ${J.inboxPath}`);await this.writeFile(J.inboxPath,Y,{encoding:"utf8",mode:384,fsync:!0})}}import*as p0 from"node:fs/promises";import*as f2 from"node:path";import{nanoid as B0}from"nanoid";var j2=256;class N0{sessionId;projectPath;storage;static instances=new Map;subscribers=new Set;highestSeq=0;constructor($,Z,J){this.sessionId=$;this.projectPath=Z;this.storage=J}static for($,Z,J=U$(Z)){let W=w$(J,$),Y=N0.instances.get(W);if(!Y)Y=new N0($,Z,J),N0.instances.set(W,Y),N0.pruneIdleInstances(W);else N0.instances.delete(W),N0.instances.set(W,Y);return Y}static release($,Z,J=U$(Z)){N0.instances.delete(w$(J,$))}static pruneIdleInstances($){if(N0.instances.size<=j2)return;for(let[Z,J]of N0.instances){if(Z===$||J.subscribers.size>0)continue;if(N0.instances.delete(Z),N0.instances.size<=j2)return}}get lastSeq(){return this.highestSeq}async readAll(){return this.withStore(async($,Z,J)=>{let W=Z?await $.readAllValidated(Z):await $.readAll();return J(W),W})}async commit($){let[Z]=await this.commitEntries([$]);return this.record(Z),Z}async commitBatch($){if($.length===0)return[];let Z=await this.commitEntries($);for(let J of Z)this.record(J);return Z}async commitValidated($){let Z=await this.withStore((J,W,Y)=>J.appendValidated((K)=>{return Y(K),$(K)},W));return this.record(Z),Z}async commitValidatedBatch($){let Z=await this.withStore((J,W,Y)=>J.appendValidatedBatch((K)=>{return Y(K),$(K)},W));for(let J of Z)this.record(J);return Z}emitDelta($){for(let Z of this.subscribers)Z.onDelta?.($);J1.publish({sessionId:this.sessionId,projectPath:this.projectPath},"delta",{delta:$})}subscribe($,Z){if(this.subscribers.add($),Z?.fromSeq!==void 0)this.replay($,Z.fromSeq);return()=>{this.subscribers.delete($),N0.pruneIdleInstances()}}async replay($,Z){let J=await this.withStore(async(W,Y,K)=>{let X=Y?await W.readAllValidated(Y):await W.readAll();return K(X),X.filter((Q)=>(Q.seq??0)>=Z)});for(let W of J){if(Q6(W))continue;await $.onCommitted(W)}}record($){if(typeof $.seq==="number"&&$.seq>this.highestSeq)this.highestSeq=$.seq;if(Q6($))return;for(let Z of this.subscribers){let J=Z.onCommitted($);if(J)Promise.resolve(J).catch(()=>{return})}J1.publish({sessionId:this.sessionId,projectPath:this.projectPath},`committed.${$.type}`,{event:$},$.seq)}commitEntries($){return this.withStore((Z,J,W)=>J?Z.appendValidatedBatch((Y)=>{return W(Y),$},J):Z.appendBatch($))}withStore($){return i1(this.storage,this.sessionId,async(Z)=>{let J=new C$(Z.transcriptPath);if(!Z.remoteScope)return $(J,void 0,()=>{return});let W=Z.remoteScope;return $(J,{noFollow:!0,validateHandle:async(X)=>{await B2(W,Z.transcriptPath,X)}},(X)=>{D2(X,this.sessionId,this.projectPath,this.storage.kind==="acp-remote"?this.storage.descriptor:void 0)})})}}function q$($){let Z=null,J=null;for(let W of $){if(W.type==="turn_started"){Z=W.data;continue}if(W.type==="turn_completed")J={type:"turn_completed",data:W.data};else if(W.type==="turn_aborted")J={type:"turn_aborted",data:W.data};else continue;if(Z?.turnId===J.data.turnId)Z=null}return{active:Z,lastTerminal:J}}class S0 extends Error{}var y4="Tool execution was interrupted by a process restart. The operation may have partially completed. Inspect the workspace, running processes, and external state before deciding whether to retry it.";function H6($,Z){let J=$.findLastIndex((W)=>W.type==="turn_started"&&W.data.turnId===Z);if(J<0)return!1;return $.slice(J+1).some((W)=>{if(W.type!=="message_created"||W.data.role!=="user")return!1;let Y=W.data.metadata;return Y!==null&&typeof Y==="object"&&!Array.isArray(Y)&&Y.clientVisible===!1&&Y.emptyFinalCorrection===!0})}function w2($,Z){let J=$.findLastIndex((Y)=>Y.type==="turn_started"&&Y.data.turnId===Z);if(J<0)return[];let W=[];for(let Y of $.slice(J+1)){if(Y.type==="turn_started"&&Y.data.turnId!==Z||(Y.type==="turn_completed"||Y.type==="turn_aborted")&&Y.data.turnId===Z)break;if(Y.type!=="message_created"||Y.data.role!=="user")continue;let K=Y.data.metadata,X=Y.data.inboxMessageId!==void 0?Y.data.inboxMessageId:K!==null&&typeof K==="object"&&!Array.isArray(K)?K.inboxMessageId:void 0;if(typeof X==="string"&&X.length>0&&X.length<=W6)W.push(X)}return[...new Set(W)]}function E2($){if(!$||typeof $!=="object"||Array.isArray($))return;if(!("version"in $)||$.version!==1&&$.version!==2&&$.version!==3)return;let Z="inputMessageIds"in $?z1($.inputMessageIds):void 0;if(!Z||!("hadSuccessfulToolResult"in $)||typeof $.hadSuccessfulToolResult!=="boolean"||!("emptyFinalCorrectionSpent"in $)||typeof $.emptyFinalCorrectionSpent!=="boolean")return;let J=$.version===1?0:("interruptedToolCallCount"in $)&&Number.isSafeInteger($.interruptedToolCallCount)&&$.interruptedToolCallCount>=0?$.interruptedToolCallCount:void 0;if(J===void 0)return;let W=$.version===3&&"allSuccessfulToolResultsSafeForResume"in $&&typeof $.allSuccessfulToolResultsSafeForResume==="boolean"?$.allSuccessfulToolResultsSafeForResume:!1;return{version:$.version,inputMessageIds:Z,hadSuccessfulToolResult:$.hadSuccessfulToolResult,interruptedToolCallCount:J,...$.version===3?{allSuccessfulToolResultsSafeForResume:W}:{},emptyFinalCorrectionSpent:$.emptyFinalCorrectionSpent}}function f4($,Z){let J=$.findLastIndex((Q)=>Q.type==="turn_started"&&Q.data.turnId===Z);if(J<0)return 0;let W=$.findIndex((Q,H)=>H>J&&Q.type==="turn_started"&&Q.data.turnId!==Z),Y=$.slice(J+1,W<0?void 0:W),K=new Set(Y.flatMap((Q)=>{if(Q.type!=="part_created"||Q.data.partType!=="tool_call")return[];let H=Q.data.payload;return H&&typeof H==="object"&&!Array.isArray(H)?[typeof H.toolCallId==="string"?H.toolCallId:Q.data.partId]:[Q.data.partId]})),X=new Set;for(let Q of Y){if(Q.type!=="part_created"||Q.data.partType!=="tool_result")continue;let H=Q.data.payload;if(!H||typeof H!=="object"||Array.isArray(H))continue;let V=typeof H.toolCallId==="string"?H.toolCallId:Q.data.partId,z=H.metadata;if(K.has(V)&&z&&typeof z==="object"&&!Array.isArray(z)&&z.processRestartRecovery===!0&&z.sideEffectsUncertain===!0)X.add(V)}return X.size}function S2($){return new Set($.flatMap((Z,J)=>{if(Z.type==="inbox_acknowledged")return Z.data.messageIds;if(Z.type==="turn_aborted")return l1($,J);return[]}))}function V6($,Z,J=[]){let W=E2(Z.data.recovery);if(!W)return;if($.some((Q)=>Q.type==="turn_recovery_acknowledged"&&Q.data.turnId===Z.data.turnId))return;let Y=S2($);for(let Q of J)Y.add(Q);let K=W.inputMessageIds.filter((Q)=>!Y.has(Q)),X=W.version===1?f4($,Z.data.turnId):W.interruptedToolCallCount;if(K.length===0&&!W.hadSuccessfulToolResult&&X===0)return;return{turnId:Z.data.turnId,outcome:"aborted",inputMessageIds:K,hadSuccessfulToolResult:W.hadSuccessfulToolResult,...X>0?{interruptedToolCallCount:X}:{},...W.version===3&&W.allSuccessfulToolResultsSafeForResume===!0?{allSuccessfulToolResultsSafeForResume:!0}:{},emptyFinalCorrectionSpent:W.emptyFinalCorrectionSpent}}function B1($){for(let Z=$.length-1;Z>=0;Z--){let J=$[Z];if(J.type!=="turn_aborted")continue;let W=V6($,J);if(W)return W}return}function a1($,Z){let J=$.input,W=Z?.metadata,Y=Z?.subagentRef;if($.toolName!=="Task"||Z?.toolCallId!==$.toolCallId||Z.toolName!=="Task"||J===null||typeof J!=="object"||Array.isArray(J)||W===null||typeof W!=="object"||Array.isArray(W)||!Y)return!1;let{subagent_session_id:K,subagent_type:X,description:Q}=J,H=Y.subagentStatus==="completed"&&Z.error===void 0&&typeof Z.output==="string"||Y.subagentStatus==="failed"&&typeof Z.error==="string"&&Z.error.length>0&&Z.output===null;return typeof K==="string"&&K===Y.subagentSessionId&&W.subagentSessionId===Y.subagentSessionId&&typeof Q==="string"&&Y.subagentDescription===Q&&W.description===Q&&(X===void 0||typeof X==="string"&&X===Y.subagentType)&&W.subagentType===Y.subagentType&&W.subagentStatus===Y.subagentStatus&&H&&W.processRestartRecovery===!0&&W.subagentResultAdopted===!0&&W.sideEffectsUncertain===!1}var E4=1e4,S4=1e5,T4=2592000000,U2=128,R4=1e6,M4=256;function k4($){if(!$||typeof $!=="object"||Array.isArray($))return;let Z=$;if(typeof Z.goalId!=="string"||Z.goalId.length===0||Z.goalId.length>U2||typeof Z.verificationAttempt!=="number"||!Number.isSafeInteger(Z.verificationAttempt)||Z.verificationAttempt<1||Z.verificationAttempt>R4||typeof Z.verifierSessionId!=="string"||Z.verifierSessionId.length===0||Z.verifierSessionId.length>U2||typeof Z.evidenceSha256!=="string"||!/^[a-f0-9]{64}$/.test(Z.evidenceSha256)||typeof Z.goalUpdatedAt!=="string"||!Number.isFinite(Date.parse(Z.goalUpdatedAt)))return;return{goalId:Z.goalId,verificationAttempt:Z.verificationAttempt,verifierSessionId:Z.verifierSessionId,evidenceSha256:Z.evidenceSha256,goalUpdatedAt:Z.goalUpdatedAt}}function T2($,Z){let J=$.data.metadata;if(!J||typeof J!=="object"||Array.isArray(J))return;let W=J.turnFinalization;if(!W||typeof W!=="object"||Array.isArray(W))return;let Y=W,K=Y.turnId,X=Y.inputMessageIds,Q=Y.turnsCount,H=Y.toolCallsCount,V=Y.durationMs,z=Array.isArray(X)?X.filter((j)=>typeof j==="string"&&j.length>0&&j.length<=W6):[];if(typeof K!=="string"||K.length===0||K.length>128||Z!==void 0&&K!==Z||!Array.isArray(X)||X.length>X2||z.length!==X.length||typeof Q!=="number"||!Number.isSafeInteger(Q)||Q<0||Q>E4||typeof H!=="number"||!Number.isSafeInteger(H)||H<0||H>S4||typeof V!=="number"||!Number.isSafeInteger(V)||V<0||V>T4)return;let B;if("goalFinalization"in Y){if(B=k4(Y.goalFinalization),!B)return}return{turnId:K,inputMessageIds:[...new Set(z)],turnsCount:Q,toolCallsCount:H,durationMs:V,...B?{goalFinalization:B}:{}}}function q2($,Z){let J=$.findLastIndex((W)=>W.type==="turn_started"&&W.data.turnId===Z);if(J<0)return;for(let W=$.length-1;W>J;W--){let Y=$[W];if(Y?.type!=="message_created")continue;let K=T2(Y,Z);if(K)return K}return}function x4($){for(let Z=$.length-1;Z>=0;Z--){let J=$[Z];if(J?.type!=="message_created")continue;let W=T2(J);if(!W?.goalFinalization)continue;if(!$.slice(0,Z).some((K)=>K.type==="turn_started"&&K.data.turnId===W.turnId))continue;return{turnId:W.turnId,finalization:W}}return}function g$($,Z){let J=Z?$.findLastIndex((H)=>H.type==="turn_started"&&H.data.turnId===Z):-1;if(Z&&J<0)return{all:[],orphaned:[],hadSuccessfulResult:!1};let W=new Map,Y=new Set,K=new Set,X=new Set;for(let H of $.slice(J+1)){if(H.type==="interaction_requested"){X.add(H.data.toolCallId);continue}if(H.type!=="part_created")continue;let V=H.data.payload&&typeof H.data.payload==="object"&&!Array.isArray(H.data.payload)?H.data.payload:{},z=typeof V.toolCallId==="string"?V.toolCallId:H.data.partId;if(H.data.partType==="tool_call")W.set(z,{toolCallId:z,messageId:H.data.messageId,toolName:typeof V.toolName==="string"?V.toolName:"unknown",input:V.input??null});else if(H.data.partType==="tool_result"){if(Y.add(z),Y.add(H.data.partId),Y.add(H.data.messageId),W.has(z)&&V.error===null)K.add(z)}}let Q=[...W.values()];return{all:Q,orphaned:Q.filter((H)=>!Y.has(H.toolCallId)&&!X.has(H.toolCallId)),hadSuccessfulResult:Q.some((H)=>K.has(H.toolCallId))}}class R0{static sessionInitializationRuns=new Map;projectPath;maxSessions;version;stateStorage;initializedSessions=new Set;constructor($=j0(),Z=100,J=P2(),W=U$($)){this.projectPath=$,this.maxSessions=Z,this.version=J,this.stateStorage=W}createEvent($,Z,J){return{id:B0(),sessionId:Z,projectPath:this.projectPath,timestamp:new Date().toISOString(),type:$,cwd:this.projectPath,...this.stateStorage.kind==="local"?{gitBranch:F2(this.projectPath)}:{},version:this.version,data:J}}log($){return N0.for($,this.projectPath,this.stateStorage)}async ensureSessionCreated($,Z){let J=w$(this.stateStorage,$);if(this.initializedSessions.delete($)){this.initializedSessions.add($);return}let W=R0.sessionInitializationRuns.get(J);if(!W)W=this.initializeSessionFile($,J,Z),R0.sessionInitializationRuns.set(J,W);try{await W,this.rememberInitializedSession($)}finally{if(R0.sessionInitializationRuns.get(J)===W)R0.sessionInitializationRuns.delete(J)}}rememberInitializedSession($){this.initializedSessions.delete($),this.initializedSessions.add($);while(this.initializedSessions.size>M4){let Z=this.initializedSessions.values().next().value;if(Z===void 0)return;this.initializedSessions.delete(Z)}}async initializeSessionFile($,Z,J){if((await this.log($).readAll()).length>0)return;if(this.stateStorage.kind==="acp-remote")throw Error("ACP remote session has no durable creation record");let Y=new Date().toISOString(),K={sessionId:$,rootId:J?.parentSessionId??$,parentId:J?.parentSessionId,relationType:J?"subagent":void 0,resumedFrom:J?.resumedFrom,rootAgentId:J?.rootAgentId,resumeDepth:J?.resumeDepth,title:void 0,status:"running",taskStatus:J?"running":"queued",taskFailure:null,agentType:J?.subagentType,model:void 0,permission:void 0,createdAt:Y,updatedAt:Y},X=this.createEvent("session_created",$,K);await this.log($).commit(X)}buildCompactionMetadata($){let Z={trigger:$.trigger,preTokens:$.preTokens};if($.reason)Z.reason=$.reason;if($.strategy)Z.strategy=$.strategy;if($.preTokenSource)Z.preTokenSource=$.preTokenSource;if($.estimatedPendingTokens!==void 0)Z.estimatedPendingTokens=$.estimatedPendingTokens;if($.postTokens!==void 0)Z.postTokens=$.postTokens;if($.sampleAttempts!==void 0)Z.sampleAttempts=$.sampleAttempts;if($.inputReductions!==void 0)Z.inputReductions=$.inputReductions;if($.messagesOmitted!==void 0)Z.messagesOmitted=$.messagesOmitted;if($.filesOmitted!==void 0)Z.filesOmitted=$.filesOmitted;if($.imagesOmitted!==void 0)Z.imagesOmitted=$.imagesOmitted;if($.fallbackTargetTokens!==void 0)Z.fallbackTargetTokens=$.fallbackTargetTokens;if($.fallbackMessagesOmitted!==void 0)Z.fallbackMessagesOmitted=$.fallbackMessagesOmitted;if($.fallbackMessagesTruncated!==void 0)Z.fallbackMessagesTruncated=$.fallbackMessagesTruncated;if($.failureReason)Z.failureReason=$.failureReason;if($.filesIncluded)Z.filesIncluded=$.filesIncluded;if($.replacementMessages)Z.checkpointVersion=A2;return Z}async initialize(){try{await N2(this.stateStorage,async($)=>{if(this.stateStorage.kind==="local")await p0.mkdir($,{recursive:!0,mode:493})})}catch($){console.warn("[PersistentStore] 无法创建持久化存储目录:",$)}}async saveMessage($,Z,J,W=null,Y,K,X){try{await this.ensureSessionCreated($,K);let Q=new Date().toISOString(),H=B0(),V={messageId:H,role:Z,parentMessageId:W??void 0,inboxMessageId:Y?.inboxMessageId,createdAt:Q,model:Y?.model,usage:Y?.usage,metadata:Y?JSON.parse(JSON.stringify(Y)):void 0},z=this.createEvent("message_created",$,V),B=Z==="assistant"&&X?.trim()?[this.createEvent("part_created",$,{partId:B0(),messageId:H,partType:"reasoning",payload:{text:X},createdAt:Q})]:[],j=typeof J==="string"?[this.createEvent("part_created",$,{partId:B0(),messageId:H,partType:"text",payload:{text:J},createdAt:Q})]:J.map((w)=>this.createEvent("part_created",$,{partId:B0(),messageId:H,partType:w.type==="text"?"text":"image",payload:w.type==="text"?{text:w.text}:{mimeType:I4(w.image_url.url)??"image/png",dataUrl:w.image_url.url},createdAt:Q}));return await this.log($).commitBatch([z,...B,...j]),H}catch(Q){throw console.error(`[PersistentStore] 保存消息失败 (session: ${$}):`,Q),Q}}async acknowledgeInboxMessages($,Z){if(Z.length===0)return;await this.ensureSessionCreated($);let J=new Date().toISOString();await this.log($).commit(this.createEvent("inbox_acknowledged",$,{messageIds:[...Z],acknowledgedAt:J}))}async acknowledgeTurnRecovery($,Z){await this.ensureSessionCreated($);try{await this.log($).commitValidated((J)=>{let W=q0(J);if(W.some((K)=>K.type==="turn_recovery_acknowledged"&&K.data.turnId===Z))throw new S0;let Y=W.findLast((K)=>K.type==="turn_aborted"&&K.data.turnId===Z);if(!Y||!V6(W,Y))throw new S0;return this.createEvent("turn_recovery_acknowledged",$,{turnId:Z,acknowledgedAt:new Date().toISOString()})})}catch(J){if(!(J instanceof S0))throw J}}async persistBackgroundSubagentCompletion($,Z){if(Z.inboxMessageId!==`background-subagent-completion:${Z.childSessionId}`)return{eligible:!1,acknowledged:!1,persisted:!1};await this.ensureSessionCreated($);let J={eligible:!1,acknowledged:!1,persisted:!1};return await this.log($).commitValidatedBatch((W)=>{let Y=q0(W),K=Y.some((j)=>j.type==="inbox_acknowledged"&&j.data.messageIds.includes(Z.inboxMessageId)),X=Y.find((j)=>j.type==="message_created"&&j.data.inboxMessageId===Z.inboxMessageId),Q=Y.findLast((j)=>{if(j.type!=="part_created"||j.data.partType!=="tool_call"||!j.data.payload||typeof j.data.payload!=="object"||Array.isArray(j.data.payload))return!1;let w=j.data.payload;if(w.toolName!=="Task"||!w.input||typeof w.input!=="object"||Array.isArray(w.input))return!1;let L=w.input,A=L.resume_from??L.resume;return L.run_in_background===!0&&L.subagent_session_id===Z.childSessionId&&L.description===Z.subagentRef.subagentDescription&&(L.subagent_type===void 0||L.subagent_type===Z.subagentRef.subagentType)&&(L.resume_from===void 0||L.resume===void 0||L.resume_from===L.resume)&&(A===void 0?Z.subagentRef.subagentResumedFrom===void 0:A===Z.subagentRef.subagentResumedFrom)});if(!Q)return J={eligible:!1,acknowledged:K,persisted:!1,...X?{messageId:X.data.messageId}:{}},[];if(K)return J={eligible:!0,acknowledged:!0,persisted:!1,...X?{messageId:X.data.messageId}:{}},[];let H=Y.find((j)=>j.type==="part_created"&&j.data.partType==="subtask_ref"&&j.data.payload!==null&&typeof j.data.payload==="object"&&!Array.isArray(j.data.payload)&&j.data.payload.childSessionId===Z.childSessionId&&j.data.payload.status===Z.subagentRef.subagentStatus);if(X&&H)return J={eligible:!0,acknowledged:!1,persisted:!1,messageId:X.data.messageId},[];let V=new Date().toISOString(),z=X?.data.messageId??B0(),B=[];if(!X){let j={messageId:z,role:"user",inboxMessageId:Z.inboxMessageId,createdAt:V,metadata:JSON.parse(JSON.stringify(Z.metadata))};B.push(this.createEvent("message_created",$,j)),B.push(this.createEvent("part_created",$,{partId:B0(),messageId:z,partType:"text",payload:{text:Z.content},createdAt:V}))}if(!H){let j=Y.findLast((L)=>L.type==="part_created"&&L.data.partType==="subtask_ref"&&L.data.messageId===Q.data.messageId&&L.data.payload!==null&&typeof L.data.payload==="object"&&!Array.isArray(L.data.payload)&&L.data.payload.childSessionId===Z.childSessionId),w=j?.data.payload&&typeof j.data.payload==="object"&&!Array.isArray(j.data.payload)?j.data.payload:void 0;B.push(this.createEvent("part_created",$,{partId:B0(),messageId:Q.data.messageId,partType:"subtask_ref",payload:{childSessionId:Z.subagentRef.subagentSessionId,agentType:Z.subagentRef.subagentType,description:Z.subagentRef.subagentDescription??"",status:Z.subagentRef.subagentStatus,summary:Z.subagentRef.subagentSummary??"",resumedFrom:Z.subagentRef.subagentResumedFrom??null,rootAgentId:Z.subagentRef.subagentRootId??Z.subagentRef.subagentSessionId,resumeDepth:Z.subagentRef.subagentResumeDepth??0,verificationVerdict:Z.subagentRef.verificationVerdict??null,startedAt:typeof w?.startedAt==="string"?w.startedAt:V,finishedAt:V},createdAt:V}))}return J={eligible:!0,acknowledged:!1,persisted:B.length>0,messageId:z},B}),J}async saveTurnStart($,Z){if(Z.goalLineage&&Z.goalLineage.currentTurnId!==Z.turnId)throw Error("Goal lineage current turn must match turn start");await this.ensureSessionCreated($);try{await this.log($).commitValidated((J)=>{let W=q0(J);if(W.some((K)=>K.type==="turn_started"&&K.data.turnId===Z.turnId))throw new S0;let Y=q$(W).active;if(Y)throw Error(`Session already has an active turn: ${Y.turnId}`);return this.createEvent("turn_started",$,Z)})}catch(J){if(!(J instanceof S0))throw J}}async saveTurnCompletion($,Z,J=[]){await this.ensureSessionCreated($);try{await this.log($).commitValidatedBatch((W)=>{let Y=q0(W),K=new Set(Y.flatMap((V)=>V.type==="inbox_acknowledged"?V.data.messageIds:[])),X=[...new Set(J)].filter((V)=>!K.has(V)),Q=Y.findLast((V)=>(V.type==="turn_completed"||V.type==="turn_aborted")&&V.data.turnId===Z.turnId);if(Q){if(Q.type==="turn_aborted"||X.length===0)throw new S0;return[this.createEvent("inbox_acknowledged",$,{messageIds:X,acknowledgedAt:Z.completedAt})]}let H=q$(Y).active;if(!H||H.turnId!==Z.turnId)throw Error(`Turn is not active: ${Z.turnId}`);return[...X.length>0?[this.createEvent("inbox_acknowledged",$,{messageIds:X,acknowledgedAt:Z.completedAt})]:[],this.createEvent("turn_completed",$,Z)]})}catch(W){if(!(W instanceof S0))throw W}}async saveTurnAbort($,Z,J={}){let W=J.acknowledgeInputMessageIds??[],Y=z1(W);if(!Y)throw Error("Invalid turn abort acknowledgement input message IDs");let K=Y;await this.ensureSessionCreated($);let X,Q=[];try{await this.log($).commitValidatedBatch((H)=>{let V=q0(H),z=S2(V),B=V.findLast((g)=>(g.type==="turn_completed"||g.type==="turn_aborted")&&g.data.turnId===Z.turnId);if(B){if(B.type==="turn_completed")throw X=void 0,Q=[],new S0;let g=E2(B.data.recovery),A0=g?K.filter((F0)=>g.inputMessageIds.includes(F0)):[],Z0=A0.filter((F0)=>!z.has(F0));if(Q=A0,X=V6(V,B,A0),Z0.length===0)throw new S0;return[this.createEvent("inbox_acknowledged",$,{messageIds:Z0,acknowledgedAt:Z.abortedAt})]}let j=q$(V).active;if(!j||j.turnId!==Z.turnId)throw Error(`Turn is not active: ${Z.turnId}`);let w=g$(V,j.turnId),L=w2(V,j.turnId),A=B1(V),E=new Set(Z.recovery?.inputMessageIds??[]),S=A?A.inputMessageIds.filter((g)=>E.has(g)):[],T=[...new Set([...L,...S])],p=w.hadSuccessfulResult||Z.recovery?.hadSuccessfulToolResult===!0,k={version:3,inputMessageIds:T,hadSuccessfulToolResult:p,interruptedToolCallCount:w.orphaned.length+(Z.recovery?.version===2||Z.recovery?.version===3?Z.recovery.interruptedToolCallCount:0),allSuccessfulToolResultsSafeForResume:p&&!w.hadSuccessfulResult&&Z.recovery?.version===3&&Z.recovery.hadSuccessfulToolResult&&Z.recovery.allSuccessfulToolResultsSafeForResume,emptyFinalCorrectionSpent:H6(V,j.turnId)||Z.recovery?.emptyFinalCorrectionSpent===!0};X={turnId:Z.turnId,outcome:"aborted",inputMessageIds:k.inputMessageIds,hadSuccessfulToolResult:k.hadSuccessfulToolResult,...k.interruptedToolCallCount>0?{interruptedToolCallCount:k.interruptedToolCallCount}:{},...k.allSuccessfulToolResultsSafeForResume?{allSuccessfulToolResultsSafeForResume:!0}:{},emptyFinalCorrectionSpent:k.emptyFinalCorrectionSpent};let $0=K.filter((g)=>T.includes(g)),a=$0.filter((g)=>!z.has(g));Q=$0;let R=new Set(z);for(let g of $0)R.add(g);let G=k.inputMessageIds.filter((g)=>!R.has(g)),r=k.hadSuccessfulToolResult||k.interruptedToolCallCount>0;X=G.length>0||r?{turnId:Z.turnId,outcome:"aborted",inputMessageIds:G,hadSuccessfulToolResult:k.hadSuccessfulToolResult,...k.interruptedToolCallCount>0?{interruptedToolCallCount:k.interruptedToolCallCount}:{},...k.allSuccessfulToolResultsSafeForResume?{allSuccessfulToolResultsSafeForResume:!0}:{},emptyFinalCorrectionSpent:k.emptyFinalCorrectionSpent}:void 0;let{acknowledgedInputMessageIds:L0,...v}=Z;return[this.createEvent("turn_aborted",$,{...v,...$0.length>0?{acknowledgedInputMessageIds:$0}:{},recovery:k}),...a.length>0?[this.createEvent("inbox_acknowledged",$,{messageIds:a,acknowledgedAt:Z.abortedAt})]:[]]})}catch(H){if(!(H instanceof S0))throw H}return{...X?{recovery:X}:{},acknowledgedInputMessageIds:Q}}async loadInterruptedToolCalls($){let Z=await this.loadEvents($);if(!Z)return[];let J=q0(Z),W=q$(J).active;return W?g$(J,W.turnId).orphaned.map((Y)=>({...Y,input:structuredClone(Y.input)})):[]}async hasRecoverableTurn($){let Z=await this.loadEvents($);if(!Z)return!1;let J=q0(Z),W=q$(J).active;if(W){let Y=g$(J,W.turnId);if(Y.orphaned.length>0||Y.hadSuccessfulResult)return!0;if(q2(J,W.turnId))return!0}return B1(J)!==void 0}async loadBackgroundTaskChildIds($){let Z=await this.loadEvents($);if(!Z)return new Set;let J=q0(Z).flatMap((W)=>{if(W.type!=="part_created"||W.data.partType!=="tool_call"||!W.data.payload||typeof W.data.payload!=="object"||Array.isArray(W.data.payload))return[];let Y=W.data.payload;if(Y.toolName!=="Task"||!Y.input||typeof Y.input!=="object"||Array.isArray(Y.input))return[];let K=Y.input;return K.run_in_background===!0&&typeof K.subagent_session_id==="string"?[K.subagent_session_id]:[]});return new Set(J)}async recoverInterruptedTurn($,Z={}){await this.ensureSessionCreated($);let J;try{await this.log($).commitValidatedBatch((W)=>{let Y=q0(W),K=q$(Y).active,X=g$(Y);if(!K&&X.orphaned.length===0){if(J=B1(Y),J)return[];throw new S0}let Q=K?q2(Y,K.turnId):void 0;if(K&&Q&&X.orphaned.length===0){let R=g$(Y,K.turnId);J={turnId:K.turnId,outcome:"completed",inputMessageIds:Q.inputMessageIds,hadSuccessfulToolResult:R.hadSuccessfulResult,emptyFinalCorrectionSpent:H6(Y,K.turnId),finalization:Q};let G=new Set(Y.flatMap((v)=>v.type==="inbox_acknowledged"?v.data.messageIds:[])),r=Q.inputMessageIds.filter((v)=>!G.has(v)),L0=new Date().toISOString();return[...r.length>0?[this.createEvent("inbox_acknowledged",$,{messageIds:r,acknowledgedAt:L0})]:[],this.createEvent("turn_completed",$,{turnId:K.turnId,completedAt:L0,turnsCount:Q.turnsCount,toolCallsCount:Q.toolCallsCount,durationMs:Q.durationMs})]}let H=K?g$(Y,K.turnId):void 0,V=H?.orphaned.some((R)=>{let G=Z.adoptedToolResults?.get(R.toolCallId);return a1(R,G)&&G?.error===void 0})??!1,z=H?.orphaned.filter((R)=>{let G=Z.adoptedToolResults?.get(R.toolCallId);return G?.toolCallId===R.toolCallId&&G.toolName===R.toolName&&G.error===void 0}).every((R)=>a1(R,Z.adoptedToolResults?.get(R.toolCallId)))??!0,B=new Set(K?.inputMessageIds??[]),j=K?B1(Y):void 0,w=j?j.inputMessageIds.filter((R)=>B.has(R)):[],L=w.length>0,A=K?w2(Y,K.turnId):[],E=H?H.orphaned.filter((R)=>{let G=Z.adoptedToolResults?.get(R.toolCallId);return!a1(R,G)}).length:0,S=L&&j?.hadSuccessfulToolResult===!0,T=(H?.hadSuccessfulResult??!1)||V||S;J=K?{turnId:K.turnId,outcome:"aborted",inputMessageIds:[...new Set([...A,...w])],hadSuccessfulToolResult:T,...(()=>{let R=E+(L?j?.interruptedToolCallCount??0:0);return R>0?{interruptedToolCallCount:R}:{}})(),...T&&!(H?.hadSuccessfulResult??!1)&&z&&(!S||j?.allSuccessfulToolResultsSafeForResume===!0)?{allSuccessfulToolResultsSafeForResume:!0}:{},emptyFinalCorrectionSpent:H6(Y,K.turnId)||L&&j?.emptyFinalCorrectionSpent===!0}:B1(Y);let p=K?H?.all.length??0:0,k=new Date().toISOString(),$0=K?Date.parse(K.startedAt):Number.NaN,a=X.orphaned.flatMap((R)=>{let G=Z.adoptedToolResults?.get(R.toolCallId),r=a1(R,G)?G:void 0,L0=this.createEvent("part_created",$,{partId:R.toolCallId,messageId:r?R.messageId:R.toolCallId,partType:"tool_result",payload:r?{toolCallId:R.toolCallId,toolName:R.toolName,output:r.output,error:r.error??null,...r.metadata===void 0?{}:{metadata:r.metadata}}:{toolCallId:R.toolCallId,toolName:R.toolName,output:null,error:y4,metadata:{processRestartRecovery:!0,sideEffectsUncertain:!0}},createdAt:k});if(!r?.subagentRef)return[L0];let v=r.subagentRef;return[L0,this.createEvent("part_created",$,{partId:B0(),messageId:R.messageId,partType:"subtask_ref",payload:{childSessionId:v.subagentSessionId,agentType:v.subagentType,description:v.subagentDescription??"",status:v.subagentStatus,summary:v.subagentSummary??"",resumedFrom:v.subagentResumedFrom??null,rootAgentId:v.subagentRootId??v.subagentSessionId,resumeDepth:v.subagentResumeDepth??0,verificationVerdict:v.verificationVerdict??null,startedAt:k,finishedAt:k},createdAt:k})]});return K?[...a,this.createEvent("turn_aborted",$,{turnId:K.turnId,cause:"process_restart",abortedAt:k,turnsCount:0,toolCallsCount:p,durationMs:Number.isFinite($0)?Math.max(0,Date.now()-$0):0,recovery:J?{version:3,inputMessageIds:J.inputMessageIds,hadSuccessfulToolResult:J.hadSuccessfulToolResult,interruptedToolCallCount:J.interruptedToolCallCount??0,allSuccessfulToolResultsSafeForResume:J.allSuccessfulToolResultsSafeForResume===!0,emptyFinalCorrectionSpent:J.emptyFinalCorrectionSpent}:void 0})]:a})}catch(W){if(!(W instanceof S0))throw W}return J}async loadLatestGoalFinalization($){let Z=await this.loadEvents($);return Z?x4(Z):void 0}async saveInteractionRequest($,Z){await this.ensureSessionCreated($),await this.log($).commitValidated((J)=>{if(J.some((Y)=>Y.type==="interaction_requested"&&Y.data.requestId===Z.requestId))throw Error(`Interaction request already exists: ${Z.requestId}`);return this.createEvent("interaction_requested",$,Z)})}async saveInteractionResponse($,Z){await this.ensureSessionCreated($),await this.log($).commitValidated((J)=>{if(!J.some((K)=>K.type==="interaction_requested"&&K.data.requestId===Z.requestId))throw Error(`Interaction request not found: ${Z.requestId}`);if(J.some((K)=>K.type==="interaction_responded"&&K.data.requestId===Z.requestId))throw Error(`Interaction already responded: ${Z.requestId}`);return this.createEvent("interaction_responded",$,Z)})}async saveInteractionRecovery($,Z){await this.ensureSessionCreated($),await this.log($).commitValidated((J)=>{if(!J.some((K)=>K.type==="interaction_responded"&&K.data.requestId===Z.requestId))throw Error(`Interaction response not found: ${Z.requestId}`);if(J.some((K)=>K.type==="interaction_recovered"&&K.data.requestId===Z.requestId))throw Error(`Interaction already recovered: ${Z.requestId}`);return this.createEvent("interaction_recovered",$,Z)})}async saveReviewStart($,Z){await this.ensureSessionCreated($),await this.log($).commitValidated((J)=>{if(J.some((K)=>K.type==="review_started"&&K.data.reviewId===Z.reviewId))throw Error(`Review already exists: ${Z.reviewId}`);if(J.some((K)=>K.type==="review_started"&&!J.some((X)=>X.type==="review_completed"&&X.data.reviewId===K.data.reviewId)))throw Error("Session already has an active review");return this.createEvent("review_started",$,Z)})}async saveReviewCompletion($,Z){await this.ensureSessionCreated($),await this.log($).commitValidated((J)=>{if(!J.some((K)=>K.type==="review_started"&&K.data.reviewId===Z.reviewId))throw Error(`Review not found: ${Z.reviewId}`);if(J.some((K)=>K.type==="review_completed"&&K.data.reviewId===Z.reviewId))throw Error(`Review already completed: ${Z.reviewId}`);return this.createEvent("review_completed",$,Z)})}async saveToolUse($,Z,J,W=null,Y,K){try{if(K!==void 0&&(K.length===0||K.length>512))throw Error("Provider tool call identity must contain 1-512 characters");await this.ensureSessionCreated($,Y);let X=new Date().toISOString(),Q=W??B0(),H=[];if(!W){let B={messageId:Q,role:"assistant",parentMessageId:void 0,createdAt:X};H.push(this.createEvent("message_created",$,B))}let V=K??B0(),z={partId:V,messageId:Q,partType:"tool_call",payload:{toolCallId:V,toolName:Z,input:J},createdAt:X};if(H.push(this.createEvent("part_created",$,z)),Z==="Task"&&J&&typeof J==="object"){let B=J,j=typeof B.subagent_session_id==="string"?B.subagent_session_id:void 0,w=typeof B.subagent_type==="string"?B.subagent_type:void 0;if(j&&w){let L={partId:B0(),messageId:Q,partType:"subtask_ref",payload:{childSessionId:j,agentType:w,status:"running",summary:typeof B.description==="string"?B.description:"",startedAt:X},createdAt:X};H.push(this.createEvent("part_created",$,L))}}return await this.log($).commitBatch(H),V}catch(X){throw console.error(`[PersistentStore] 保存工具调用失败 (session: ${$}):`,X),X}}async saveToolResult($,Z,J,W,Y=null,K,X,Q,H){try{await this.ensureSessionCreated($,X);let V=new Date().toISOString(),z=Y??B0();return await this.log($).commitValidatedBatch((B)=>{let j=Q?.subagentStatus==="running"?q0(B).findLast((T)=>T.type==="part_created"&&T.data.partType==="subtask_ref"&&T.data.payload!==null&&typeof T.data.payload==="object"&&!Array.isArray(T.data.payload)&&T.data.payload.childSessionId===Q.subagentSessionId&&(T.data.payload.status==="completed"||T.data.payload.status==="failed"||T.data.payload.status==="cancelled")):void 0,w=j?.data.payload,L=H&&typeof H==="object"&&!Array.isArray(H)?H:{},A=w?{...L,subagentSessionId:w.childSessionId,subagentType:w.agentType,description:w.description,subagentStatus:w.status,subagentSummary:w.summary,subagentResumedFrom:w.resumedFrom,subagentRootId:w.rootAgentId,subagentResumeDepth:w.resumeDepth,verificationVerdict:w.verificationVerdict}:H,E=[];if(!Y){let T={messageId:z,role:"assistant",parentMessageId:void 0,createdAt:V};E.push(this.createEvent("message_created",$,T))}let S={partId:Z,messageId:z,partType:"tool_result",payload:{toolCallId:Z,toolName:J,output:W,error:K??null,...A===void 0?{}:{metadata:A}},createdAt:V};if(E.push(this.createEvent("part_created",$,S)),Q&&!j){let T=Q.subagentStatus==="running"?null:V,p={partId:B0(),messageId:z,partType:"subtask_ref",payload:{childSessionId:Q.subagentSessionId,agentType:Q.subagentType,description:Q.subagentDescription??"",status:Q.subagentStatus,summary:Q.subagentSummary??"",resumedFrom:Q.subagentResumedFrom??null,rootAgentId:Q.subagentRootId??Q.subagentSessionId,resumeDepth:Q.subagentResumeDepth??0,verificationVerdict:Q.verificationVerdict??null,startedAt:V,finishedAt:T},createdAt:V};E.push(this.createEvent("part_created",$,p))}return E}),Z}catch(V){throw console.error(`[PersistentStore] 保存工具结果失败 (session: ${$}):`,V),V}}async saveCompaction($,Z,J,W=null){try{await this.ensureSessionCreated($);let Y=new Date().toISOString(),K=B0(),X={messageId:K,role:"system",parentMessageId:W??void 0,createdAt:Y},Q=this.buildCompactionMetadata(J),H={partId:B0(),messageId:K,partType:"summary",payload:{text:Z,metadata:Q,...J.replacementMessages?{replacementMessages:b2(J.replacementMessages)}:{}},createdAt:Y},V=[this.createEvent("message_created",$,X),this.createEvent("part_created",$,H)];return await this.log($).commitBatch(V),K}catch(Y){throw console.error(`[PersistentStore] 保存压缩失败 (session: ${$}):`,Y),Y}}async recordTokenBudgetHandoff($,Z){await this.ensureSessionCreated($);let J=t1([]),W=await this.log($).commitValidatedBatch((K)=>{if(J=t1(q0(K)),J.kind!=="none")return[];let X=new Date().toISOString();return[this.createEvent("token_budget_handoff_recorded",$,{...Z,messageId:`${y2}${B0()}`,createdAt:X})]});if(J.kind==="valid")return{outcome:"existing",event:J.event};if(J.kind==="suppressed")return{outcome:"suppressed",recordId:J.recordId};if(W.length!==1)throw Error("Token budget handoff commit produced an impossible result");let Y=t1(W);if(Y.kind!=="valid")throw Error("Token budget handoff commit produced an invalid event");return{outcome:"created",event:Y.event}}async initSession($,Z){await this.ensureSessionCreated($,Z)}async loadEvents($){try{let Z=await this.log($).readAll();return Z.length>0?q0(Z):null}catch{return null}}async loadSession($){try{let Z=q0(await this.log($).readAll());if(Z.length===0)return null;let J=Z.find((W)=>W.type==="session_created");return{sessionId:$,userId:void 0,preferences:{},configuration:{},startTime:new Date(J?.timestamp??Z[0].timestamp).getTime()}}catch{return null}}async loadConversation($){try{let Z=q0(await this.log($).readAll());if(Z.length===0)return null;let J=new Map;for(let X of Z){if(X.type==="message_created")J.set(X.data.messageId,{id:X.data.messageId,role:X.data.role,content:"",timestamp:new Date(X.timestamp).getTime()});if(X.type==="part_created"&&X.data.partType==="text"){let Q=J.get(X.data.messageId);if(Q){let H=X.data.payload;Q.content=H.text??""}}if(X.type==="part_created"&&X.data.partType==="image"){let Q=J.get(X.data.messageId);if(Q)Q.content=Q.content?`${Q.content}
96
- [Image]`:"[Image]"}}let W=Array.from(J.values()),Y=Z[Z.length-1],K=new Date(Y.timestamp).getTime();return{messages:W,topics:[],lastActivity:K}}catch{return null}}async listSessions(){if(this.stateStorage.kind==="acp-remote")throw Error("Remote session enumeration requires SessionService");try{let $=K1(this.projectPath);return(await p0.readdir($)).filter((J)=>J.endsWith(".jsonl")).map((J)=>J.replace(".jsonl","")).sort()}catch{return[]}}async getSessionSummary($){if(this.stateStorage.kind==="acp-remote")throw Error("Remote session summaries require SessionService");try{let Z=s1(this.projectPath,$),J=new C$(Z);if(!(await J.getStats()).exists)return null;let Y=await J.readAll();if(Y.length===0)return null;let K=q0(Y),X=Y[Y.length-1],Q=K.filter((H)=>H.type==="message_created"&&["user","assistant"].includes(H.data.role)).length;return{sessionId:$,lastActivity:new Date(X.timestamp).getTime(),messageCount:Q,topics:[]}}catch{return null}}async deleteSession($){if(this.stateStorage.kind==="acp-remote")throw Error("Remote session deletion requires SessionService");this.initializedSessions.delete($);try{let Z=s1(this.projectPath,$);await new C$(Z).delete(),await p0.unlink(L2(this.projectPath,$)).catch((W)=>{if(W.code!=="ENOENT")throw W}),await _2(this.projectPath,$,G2());try{let{getProjectionDb:W,removeSessionFromProjection:Y}=await import("./chunk-cv4h5c96.js"),K=await W();if(K)Y(K,$,this.projectPath)}catch{}}catch(Z){console.warn(`[PersistentStore] 删除会话失败 (session: ${$}):`,Z)}finally{this.initializedSessions.delete($)}}async cleanupOldSessions(){if(this.stateStorage.kind==="acp-remote")throw Error("Remote session cleanup requires SessionService");try{let $=await this.listSessions();if($.length<=this.maxSessions)return;let W=(await Promise.all($.map((Y)=>this.getSessionSummary(Y)))).filter((Y)=>Y!==null).sort((Y,K)=>K.lastActivity-Y.lastActivity).slice(this.maxSessions).map((Y)=>Y.sessionId);await Promise.all(W.map((Y)=>this.deleteSession(Y))),console.log(`[PersistentStore] 已清理 ${W.length} 个旧会话`)}catch($){console.error("[PersistentStore] 清理旧会话失败:",$)}}async getStorageStats(){if(this.stateStorage.kind==="acp-remote")throw Error("Remote storage statistics require SessionService");try{let $=await this.listSessions(),Z=0;for(let J of $){let W=s1(this.projectPath,J),K=await new C$(W).getStats();Z+=K.size}return{totalSessions:$.length,totalSize:Z,projectPath:this.projectPath}}catch{return{totalSessions:0,totalSize:0,projectPath:this.projectPath}}}async checkStorageHealth(){if(this.stateStorage.kind==="acp-remote")throw Error("Remote storage health checks require SessionService");try{let $=K1(this.projectPath);await p0.mkdir($,{recursive:!0,mode:493});let Z=f2.join($,".health-check");return await p0.writeFile(Z,"test","utf-8"),await p0.unlink(Z),{isAvailable:!0,canWrite:!0}}catch($){return{isAvailable:!1,canWrite:!1,error:$ instanceof Error?$.message:String($)}}}static async listAllProjects(){return O2()}}function I4($){return/^data:([^;,]+)[;,]/.exec($)?.[1]??null}var R2=131072,z6=new R$;function j6($,Z){return`${h4.resolve($)}\x00${Z}`}function w6($,Z){let J=JSON.stringify($);if(J===void 0)throw Error(`${Z} is not JSON serializable`);if(Buffer.byteLength(J,"utf8")>R2)throw Error(`${Z} exceeds ${R2} bytes`);return JSON.parse(J)}function M2($){if($.type==="askUserQuestion")return"question";if($.type==="mcpElicitation")return"elicitation";if($.type==="permission"||$.type==="mcpSampling")return"permission";return}function C4($,Z){return JSON.stringify($)===JSON.stringify(Z)}function g4($,Z){if($.request.interactionType!=="elicitation")return w6(Z,"Interaction response");return w6({approved:Z.approved,...Z.reason?{reason:Z.reason}:{},...Z.elicitation?{elicitation:{action:Z.elicitation.action}}:{},...Z.openExternalUrl?{openExternalUrl:!0}:{}},"Interaction response")}function k2($){let Z=$.request.details;if(!Z||typeof Z!=="object"||Array.isArray(Z))throw Error(`Invalid durable interaction details: ${$.request.requestId}`);return Z}function p4($){let Z=$.response?.response;if(!Z||typeof Z!=="object"||Array.isArray(Z))throw Error(`Invalid durable interaction response: ${$.request.requestId}`);return Z}function u4($){if(!$.answers||Object.keys($.answers).length===0)return"No structured answers were provided.";return Object.entries($.answers).map(([Z,J])=>{let W=Array.isArray(J)?J.join(", "):J;return`${Z}: ${W}`}).join(`
96
+ [Image]`:"[Image]"}}let W=Array.from(J.values()),Y=Z[Z.length-1],K=new Date(Y.timestamp).getTime();return{messages:W,topics:[],lastActivity:K}}catch{return null}}async listSessions(){if(this.stateStorage.kind==="acp-remote")throw Error("Remote session enumeration requires SessionService");try{let $=K1(this.projectPath);return(await p0.readdir($)).filter((J)=>J.endsWith(".jsonl")).map((J)=>J.replace(".jsonl","")).sort()}catch{return[]}}async getSessionSummary($){if(this.stateStorage.kind==="acp-remote")throw Error("Remote session summaries require SessionService");try{let Z=s1(this.projectPath,$),J=new C$(Z);if(!(await J.getStats()).exists)return null;let Y=await J.readAll();if(Y.length===0)return null;let K=q0(Y),X=Y[Y.length-1],Q=K.filter((H)=>H.type==="message_created"&&["user","assistant"].includes(H.data.role)).length;return{sessionId:$,lastActivity:new Date(X.timestamp).getTime(),messageCount:Q,topics:[]}}catch{return null}}async deleteSession($){if(this.stateStorage.kind==="acp-remote")throw Error("Remote session deletion requires SessionService");this.initializedSessions.delete($);try{let Z=s1(this.projectPath,$);await new C$(Z).delete(),await p0.unlink(L2(this.projectPath,$)).catch((W)=>{if(W.code!=="ENOENT")throw W}),await _2(this.projectPath,$,G2());try{let{getProjectionDb:W,removeSessionFromProjection:Y}=await import("./chunk-42y6ks44.js"),K=await W();if(K)Y(K,$,this.projectPath)}catch{}}catch(Z){console.warn(`[PersistentStore] 删除会话失败 (session: ${$}):`,Z)}finally{this.initializedSessions.delete($)}}async cleanupOldSessions(){if(this.stateStorage.kind==="acp-remote")throw Error("Remote session cleanup requires SessionService");try{let $=await this.listSessions();if($.length<=this.maxSessions)return;let W=(await Promise.all($.map((Y)=>this.getSessionSummary(Y)))).filter((Y)=>Y!==null).sort((Y,K)=>K.lastActivity-Y.lastActivity).slice(this.maxSessions).map((Y)=>Y.sessionId);await Promise.all(W.map((Y)=>this.deleteSession(Y))),console.log(`[PersistentStore] 已清理 ${W.length} 个旧会话`)}catch($){console.error("[PersistentStore] 清理旧会话失败:",$)}}async getStorageStats(){if(this.stateStorage.kind==="acp-remote")throw Error("Remote storage statistics require SessionService");try{let $=await this.listSessions(),Z=0;for(let J of $){let W=s1(this.projectPath,J),K=await new C$(W).getStats();Z+=K.size}return{totalSessions:$.length,totalSize:Z,projectPath:this.projectPath}}catch{return{totalSessions:0,totalSize:0,projectPath:this.projectPath}}}async checkStorageHealth(){if(this.stateStorage.kind==="acp-remote")throw Error("Remote storage health checks require SessionService");try{let $=K1(this.projectPath);await p0.mkdir($,{recursive:!0,mode:493});let Z=f2.join($,".health-check");return await p0.writeFile(Z,"test","utf-8"),await p0.unlink(Z),{isAvailable:!0,canWrite:!0}}catch($){return{isAvailable:!1,canWrite:!1,error:$ instanceof Error?$.message:String($)}}}static async listAllProjects(){return O2()}}function I4($){return/^data:([^;,]+)[;,]/.exec($)?.[1]??null}var R2=131072,z6=new R$;function j6($,Z){return`${h4.resolve($)}\x00${Z}`}function w6($,Z){let J=JSON.stringify($);if(J===void 0)throw Error(`${Z} is not JSON serializable`);if(Buffer.byteLength(J,"utf8")>R2)throw Error(`${Z} exceeds ${R2} bytes`);return JSON.parse(J)}function M2($){if($.type==="askUserQuestion")return"question";if($.type==="mcpElicitation")return"elicitation";if($.type==="permission"||$.type==="mcpSampling")return"permission";return}function C4($,Z){return JSON.stringify($)===JSON.stringify(Z)}function g4($,Z){if($.request.interactionType!=="elicitation")return w6(Z,"Interaction response");return w6({approved:Z.approved,...Z.reason?{reason:Z.reason}:{},...Z.elicitation?{elicitation:{action:Z.elicitation.action}}:{},...Z.openExternalUrl?{openExternalUrl:!0}:{}},"Interaction response")}function k2($){let Z=$.request.details;if(!Z||typeof Z!=="object"||Array.isArray(Z))throw Error(`Invalid durable interaction details: ${$.request.requestId}`);return Z}function p4($){let Z=$.response?.response;if(!Z||typeof Z!=="object"||Array.isArray(Z))throw Error(`Invalid durable interaction response: ${$.request.requestId}`);return Z}function u4($){if(!$.answers||Object.keys($.answers).length===0)return"No structured answers were provided.";return Object.entries($.answers).map(([Z,J])=>{let W=Array.isArray(J)?J.join(", "):J;return`${Z}: ${W}`}).join(`
97
97
  `)}function m4($,Z){let{request:J}=$;if(J.interactionType==="question"){let X=u4(Z);return{toolOutput:`User answers:
98
98
  ${X}`,inbox:`The process restarted while waiting for a structured answer. The recovered user response is:
99
99
  ${X}
@@ -1,4 +1,4 @@
1
- import{rc as Xt,sc as En,tc as yn,uc as bn}from"./chunk-wm896gnx.js";import{yh as Bt}from"./chunk-ra0y5drh.js";import{$h as Gt,Dh as xt,Eh as vi,Fh as sn,Gh as zt,Hh as U,Ih as en,Jh as gt,Kh as mt,Mh as rn,Nh as Tn,Oh as B,Ph as dn,Qh as on,Rh as pn,Sh as lt,Th as un,Uh as cn,Vh as Mn,Xh as S,_h as wn,ai as Ut,bi as h,ci as Ht}from"./chunk-eass9t33.js";import{aj as It}from"./chunk-jsv3e4k6.js";import{Ej as X,Gj as x}from"./chunk-5q4z0sfr.js";import{Wj as tn,Xj as nn}from"./chunk-7r26xgk4.js";import{Lk as ns}from"./chunk-sdapqhj0.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} 个错误):
1
+ import{rc as Xt,sc as En,tc as yn,uc as bn}from"./chunk-wm896gnx.js";import{yh as Bt}from"./chunk-v7b7dx9j.js";import{$h as Gt,Dh as xt,Eh as vi,Fh as sn,Gh as zt,Hh as U,Ih as en,Jh as gt,Kh as mt,Mh as rn,Nh as Tn,Oh as B,Ph as dn,Qh as on,Rh as pn,Sh as lt,Th as un,Uh as cn,Vh as Mn,Xh as S,_h as wn,ai as Ut,bi as h,ci as Ht}from"./chunk-4gsjcz7t.js";import{aj as It}from"./chunk-jsv3e4k6.js";import{Ej as X,Gj as x}from"./chunk-5q4z0sfr.js";import{Wj as tn,Xj as nn}from"./chunk-xh3bm0p0.js";import{Lk as ns}from"./chunk-sdapqhj0.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{Fa as z3}from"./chunk-zrgfvc4k.js";import{Ia as T,Ja as $$,Oa as Vz,Pa as RY,Qa as e0}from"./chunk-1qp826p9.js";import{Ra as Y5,Ua as pZ,Ya as tZ,Za as UX,_a as HX,ab as rz,cb as nz,db as A9,vb as az}from"./chunk-ht8epjz2.js";import{Ab as D2,Bb as BY,Cb as x1,Db as a7,Eb as KY,Fb as $Y,Gb as DY,Hb as qY,Ib as WQ,Kb as JX,Mb as W0,Ob as _2,Rb as p4,Tb as _Z,Ub as l4,Vb as i4,Xb as AJ,Yb as R$,cc as aX,dc as G8,ec as sX,fc as ZX,hc as u1,ic as SX,nc as iY,qc as rY,wb as s5,xb as h7,yb as J1,zb as c7}from"./chunk-75n6cr3x.js";import{$c as M1,Ac as T1,Bc as ZJ,Cc as _0,Dc as S2,Ec as N1,Fc as S6,Gc as f9,Hc as m4,Ic as c4,Jc as JY,Kc as YY,Lc as CX,Mc as X3,Md as W8,Nc as A1,Oc as Y3,Od as f0,Pc as i8,Pd as b$,Qc as $1,Rc as Z1,Sc as l2,Tc as p2,Uc as i2,Vc as g6,Wc as u6,Wd as Jz,Xc as d2,Xd as VX,Yc as H3,Zc as m2,_c as r8,_d as lY,ad as e1,bd as c2,cd as $2,dd as Z2,de as fX,ed as d6,ee as PX,fd as J2,gd as m6,ge as s,hd as c6,id as k$,jd as p6,kd as O3,ld as r2,md as l6,nd as i6,od as r6,pd as n6,qd as N3,rd as b3,td as j3,wc as v$,xc as MX,yc as r3,zc as k3}from"./chunk-3jqvgxnc.js";import{he as l,ie as BQ,je as GQ,ke as IJ,me as F2}from"./chunk-9xbwtjac.js";import{Fe as P9,Ge as J$,He as q2,Ie as $9,Je as TX,Ke as RX,Te as ez,ef as $W,oe as oz,re as tz}from"./chunk-q1rnvn85.js";import{Af as NJ,Bf as LJ}from"./chunk-v1mamd1x.js";import{Nf as r4,Of as q0,Pf as d,Sf as j0,Tf as P4,Uf as L2,Vf as G1,Wf as CZ,Xf as R1,Yf as cY,bg as B2}from"./chunk-8bm5bpa2.js";import{cg as d1}from"./chunk-7xhw74hk.js";import{gg as jZ,hg as pY,mg as dY,ng as mX,og as S4}from"./chunk-k1tfry97.js";import{pg as nZ}from"./chunk-f2y0gxyq.js";import{sg as m0,tg as O1}from"./chunk-k3ne93k8.js";import{ug as tX}from"./chunk-7wcxjbyg.js";import{wg as LX,xg as OX,yg as NX,zg as bX}from"./chunk-s9ws4xsz.js";import{$g as kX,Ag as I4,Bg as h4,Cg as g4,Eg as u4,Fg as d4,Gg as _1,Hg as FQ,Ig as I$,Jg as j$,Kg as G$,Lg as $5,Mg as W2,Ng as H8,Og as l1,Pg as i1,Qg as EX,Ug as J9,Wg as c0,Xg as f$,Zg as k4,_g as AX}from"./chunk-xqzmm1bf.js";import{bh as D1,dh as T$,eh as O4}from"./chunk-ewwrss2w.js";import{fh as d3,gh as z2,hh as m3,ih as s2,jh as c3,kh as p3,lh as Z4,mh as $4,nh as l3,oh as i3,ph as e6}from"./chunk-53vh6vpt.js";import{qh as _z,sh as jX,th as z8,uh as bJ}from"./chunk-hv8nt7wj.js";import{wh as L9,yh as x0}from"./chunk-ra0y5drh.js";import{Ah as R9,Bh as A6,Ch as r1,zh as E6}from"./chunk-28tzj187.js";import{Bi as PY,Ci as SY,Di as kY,Eh as XJ,Ei as vY,Fi as AZ,Gi as yY,Hi as B1,Ii as xY,Jh as zJ,Ji as IY,Ki as hY,Lh as D9,Mi as t3,Oi as yX,Pi as _X,Qh as Wz,Qi as B0,Uh as WJ,Wh as qX,Yh as UY,Zh as HY,oi as h1,ri as e7}from"./chunk-eass9t33.js";import{Ti as L$}from"./chunk-sd9bze9x.js";import{Vi as eQ,Xi as $X}from"./chunk-514va7ce.js";import{_i as X4,aj as C}from"./chunk-jsv3e4k6.js";import{Cj as e,Ej as a6,Fj as X2,Gj as K,Hj as R3,Ij as P,Jj as u}from"./chunk-5q4z0sfr.js";import{Nj as wX,Oj as FX}from"./chunk-0b67y4j1.js";import{Pj as Oz,Sj as wz}from"./chunk-9kj19a8t.js";import{Wj as Ez}from"./chunk-7r26xgk4.js";import{ak as vX,bk as a0}from"./chunk-gm2yfq3r.js";import{Ak as E$,Fk as u3,ek as t,fk as N$,gk as D$,hk as t1,ik as o9,jk as u2,kk as X$,lk as t7,ok as I6,xk as P6}from"./chunk-7xtxvrh8.js";import{Lk as Y$}from"./chunk-sdapqhj0.js";import{randomUUID as M8}from"crypto";import{randomUUID as _W}from"node:crypto";var KW=String.raw`
1
+ import{Fa as z3}from"./chunk-zrgfvc4k.js";import{Ia as T,Ja as $$,Oa as Vz,Pa as RY,Qa as e0}from"./chunk-ccsgzyth.js";import{Ra as Y5,Ua as pZ,Ya as tZ,Za as UX,_a as HX,ab as rz,cb as nz,db as A9,vb as az}from"./chunk-ht8epjz2.js";import{Ab as D2,Bb as BY,Cb as x1,Db as a7,Eb as KY,Fb as $Y,Gb as DY,Hb as qY,Ib as WQ,Kb as JX,Mb as W0,Ob as _2,Rb as p4,Tb as _Z,Ub as l4,Vb as i4,Xb as AJ,Yb as R$,cc as aX,dc as G8,ec as sX,fc as ZX,hc as u1,ic as SX,nc as iY,qc as rY,wb as s5,xb as h7,yb as J1,zb as c7}from"./chunk-bgc4wts7.js";import{$c as M1,Ac as T1,Bc as ZJ,Cc as _0,Dc as S2,Ec as N1,Fc as S6,Gc as f9,Hc as m4,Ic as c4,Jc as JY,Kc as YY,Lc as CX,Mc as X3,Md as W8,Nc as A1,Oc as Y3,Od as f0,Pc as i8,Pd as b$,Qc as $1,Rc as Z1,Sc as l2,Tc as p2,Uc as i2,Vc as g6,Wc as u6,Wd as Jz,Xc as d2,Xd as VX,Yc as H3,Zc as m2,_c as r8,_d as lY,ad as e1,bd as c2,cd as $2,dd as Z2,de as fX,ed as d6,ee as PX,fd as J2,gd as m6,ge as s,hd as c6,id as k$,jd as p6,kd as O3,ld as r2,md as l6,nd as i6,od as r6,pd as n6,qd as N3,rd as b3,td as j3,wc as v$,xc as MX,yc as r3,zc as k3}from"./chunk-f6wx6sf2.js";import{he as l,ie as BQ,je as GQ,ke as IJ,me as F2}from"./chunk-9xbwtjac.js";import{Fe as P9,Ge as J$,He as q2,Ie as $9,Je as TX,Ke as RX,Te as ez,ef as $W,oe as oz,re as tz}from"./chunk-vz13c7fr.js";import{Af as NJ,Bf as LJ}from"./chunk-v1mamd1x.js";import{Nf as r4,Of as q0,Pf as d,Sf as j0,Tf as P4,Uf as L2,Vf as G1,Wf as CZ,Xf as R1,Yf as cY,bg as B2}from"./chunk-pnfeyw0g.js";import{cg as d1}from"./chunk-7xhw74hk.js";import{gg as jZ,hg as pY,mg as dY,ng as mX,og as S4}from"./chunk-k1tfry97.js";import{pg as nZ}from"./chunk-f2y0gxyq.js";import{sg as m0,tg as O1}from"./chunk-k3ne93k8.js";import{ug as tX}from"./chunk-7wcxjbyg.js";import{wg as LX,xg as OX,yg as NX,zg as bX}from"./chunk-kxz7j4a3.js";import{$g as kX,Ag as I4,Bg as h4,Cg as g4,Eg as u4,Fg as d4,Gg as _1,Hg as FQ,Ig as I$,Jg as j$,Kg as G$,Lg as $5,Mg as W2,Ng as H8,Og as l1,Pg as i1,Qg as EX,Ug as J9,Wg as c0,Xg as f$,Zg as k4,_g as AX}from"./chunk-gnjsdr40.js";import{bh as D1,dh as T$,eh as O4}from"./chunk-ewwrss2w.js";import{fh as d3,gh as z2,hh as m3,ih as s2,jh as c3,kh as p3,lh as Z4,mh as $4,nh as l3,oh as i3,ph as e6}from"./chunk-53vh6vpt.js";import{qh as _z,sh as jX,th as z8,uh as bJ}from"./chunk-hv8nt7wj.js";import{wh as L9,yh as x0}from"./chunk-v7b7dx9j.js";import{Ah as R9,Bh as A6,Ch as r1,zh as E6}from"./chunk-28tzj187.js";import{Bi as PY,Ci as SY,Di as kY,Eh as XJ,Ei as vY,Fi as AZ,Gi as yY,Hi as B1,Ii as xY,Jh as zJ,Ji as IY,Ki as hY,Lh as D9,Mi as t3,Oi as yX,Pi as _X,Qh as Wz,Qi as B0,Uh as WJ,Wh as qX,Yh as UY,Zh as HY,oi as h1,ri as e7}from"./chunk-4gsjcz7t.js";import{Ti as L$}from"./chunk-sd9bze9x.js";import{Vi as eQ,Xi as $X}from"./chunk-514va7ce.js";import{_i as X4,aj as C}from"./chunk-jsv3e4k6.js";import{Cj as e,Ej as a6,Fj as X2,Gj as K,Hj as R3,Ij as P,Jj as u}from"./chunk-5q4z0sfr.js";import{Nj as wX,Oj as FX}from"./chunk-0b67y4j1.js";import{Pj as Oz,Sj as wz}from"./chunk-9kj19a8t.js";import{Wj as Ez}from"./chunk-xh3bm0p0.js";import{ak as vX,bk as a0}from"./chunk-gm2yfq3r.js";import{Ak as E$,Fk as u3,ek as t,fk as N$,gk as D$,hk as t1,ik as o9,jk as u2,kk as X$,lk as t7,ok as I6,xk as P6}from"./chunk-7xtxvrh8.js";import{Lk as Y$}from"./chunk-sdapqhj0.js";import{randomUUID as M8}from"crypto";import{randomUUID as _W}from"node:crypto";var KW=String.raw`
2
2
  const { spawn } = require('node:child_process');
3
3
  const [ownerPidValue, command, ...args] = process.argv.slice(1);
4
4
  const ownerPid = Number(ownerPidValue);
@@ -859,7 +859,7 @@ ${A0}
859
859
  </approved-plan>
860
860
 
861
861
  IMPORTANT: Execute according to the approved plan above. Follow the steps exactly as specified.`;if(typeof O==="string")S$=O+j6;else S$=[...O,{type:"text",text:j6}]}v=yield*this.runLoop(S$,b,{...x,inputMessageId:void 0})}if(!this.sessionRuntime||!I)return v;let p=await this.sessionRuntime.recordGoalProgress({tokens:v.metadata?.tokensUsed??0,elapsedMs:v.metadata?.duration??0,...k?{goalId:k.goalId,objective:k.objective,turnId:I.id}:{},executionHostFailureCategory:v.metadata?.executionHostFailureCategory,prematureStopPattern:v.success?VY(v.finalMessage):void 0});if(p)yield{kind:"goal_updated",goal:p};if(!v.success||b.signal?.aborted){if(p=await this.sessionRuntime.pauseActiveGoal(b.signal?.aborted?"goal paused after user cancellation":v.error?.message??"goal paused after turn failure"),p)yield{kind:"goal_updated",goal:p}}if(v.success&&!b.signal?.aborted&&h<20)await this.sessionRuntime.waitForBackgroundSubagentFollowUp(I,b.signal);let n=v.success&&!b.signal?.aborted&&h<20,p0=XG(v)||!v.success&&v.error?.type==="max_turns_exceeded";if(R=await this.sessionRuntime.finishTurn(I,{continuePending:n,...p0?{acknowledgeInput:!0}:{},outcome:v.success&&!b.signal?.aborted?{status:"completed",turnsCount:v.metadata?.turnsCount??0,toolCallsCount:v.metadata?.toolCallsCount??0,durationMs:v.metadata?.duration??0}:{status:"aborted",cause:b.signal?.aborted?"cancelled":"failed",turnsCount:v.metadata?.turnsCount??0,toolCallsCount:v.metadata?.toolCallsCount??0,durationMs:v.metadata?.duration??0}}),R){h++,N=!0,M=!1,j=null,O="",o=void 0,A="",S=void 0,E=Z0(),yield{kind:"follow_up_started",queued:this.sessionRuntime.getPendingSteeringCount(),recovered:this.sessionRuntime.getRecoveredSteeringCount(),messages:$0(),queue:await this.sessionRuntime.getFollowUpQueueSnapshot()};continue}if(yield{kind:"follow_up_queue_changed",queue:await this.sessionRuntime.getFollowUpQueueSnapshot()},!v.success||b.signal?.aborted)return v;if(p=await this.sessionRuntime.getGoal(),!p||p.status!=="active"&&p.status!=="verifying")return v;let J0=await this.sessionRuntime.prepareGoalContinuation(p);if(!J0.ok){if(J0.goal)yield{kind:"goal_updated",goal:J0.goal};return{success:!1,error:{type:"goal_frontier_unavailable",message:J0.error.message},metadata:{turnsCount:v.metadata?.turnsCount??0,toolCallsCount:v.metadata?.toolCallsCount??0,duration:v.metadata?.duration??0}}}let h0=await this.sessionRuntime.beginGoalTurn(J0.goal);if(!h0)return v;j=h0.goal,q={...J0,goal:h0.goal},R=h0.handle,N=!1,M=!0,O=S5(j),o=void 0,E=void 0,yield{kind:"goal_frontier_updated",goal:j,frontier:J0.frontier,tasks:J0.tasks},yield{kind:"goal_continuation_started",goal:j,continuation:j.continuationCount,...j.prematureStop?{prematureStopPattern:j.prematureStop.pattern,prematureStopCount:j.prematureStop.consecutiveCount}:{}},yield{kind:"goal_updated",goal:j}}}finally{if(this.sessionRuntime&&R)await this.sessionRuntime.finishTurn(R)}}let _=typeof H==="string"?H:H.filter((O)=>O.type==="text").map((O)=>O.text).join(`
862
- `),L={id:this.generateTaskId(),type:"simple",prompt:_};return{success:!0,finalMessage:(await this.executeTask(L)).content,metadata:{turnsCount:1,toolCallsCount:0,duration:0}}}async chat($,Z,J){let{drainLoop:Y}=await import("./chunk-wax2788t.js");return Y(this.chatStream($,Z,J))}async*runPlanLoop($,Z,J){a.debug("Processing Plan mode message...");let{prompt:Y}=await Y1({...Z.workspaceKind==="acp-remote"?{workspaceAccess:"none"}:{projectPath:Z.workspaceRoot||C()},mode:"plan",includeEnvironment:!0,environmentOptions:{...u1,workingDirectory:Z.executionRoot??Z.workspaceRoot??C()},language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),...Z.workspaceKind==="acp-remote"?{}:{projectInstructionSourcePath:this.sessionRuntime?.projectRoot}}),Q;if(typeof $==="string")Q=t2($);else{let X=$.filter((z)=>z.type==="text");if(X.length>0){let z=X[0];Q=$.map((W)=>W===z?{type:"text",text:t2(z.text)}:W)}else Q=[{type:"text",text:t2("")},...$]}return yield*this.executeLoop(Q,Z,J,Y)}async*runLoop($,Z,J){a.debug("Processing enhanced chat message...");let Y=Z.systemPrompt??await this.buildSystemPromptOnDemand(Z);return yield*this.executeLoop($,Z,J,Y)}async buildSystemPromptOnDemand($){let Z=this.runtimeOptions.systemPrompt,J=this.runtimeOptions.appendSystemPrompt;return(await Y1({...$.workspaceKind==="acp-remote"?{workspaceAccess:"none"}:{projectPath:$.workspaceRoot||C()},replaceDefault:Z,append:J,includeEnvironment:!0,environmentOptions:{...u1,workingDirectory:$.executionRoot??$.workspaceRoot??C()},language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),...$.workspaceKind==="acp-remote"?{}:{projectInstructionSourcePath:this.sessionRuntime?.projectRoot}})).prompt}executeLoop($,Z,J,Y){if(!this.isInitialized)throw Error("Agent未初始化");let Q=this.buildLoopDependencies();return rY(Q,$,Z,J,Y)}takeStartupAdoptedToolResultEvents(){return(this.sessionRuntime?.takeStartupAdoptedToolResults()??[]).flatMap(({call:Z,result:J})=>{let Y={id:Z.toolCallId,type:"function",function:{name:Z.toolName,arguments:JSON.stringify(Z.input)}},Q=J.metadata&&typeof J.metadata==="object"&&!Array.isArray(J.metadata)?J.metadata:void 0,X=J.error===void 0,z=J.output,W={success:X,llmContent:typeof z==="string"||z!==null&&typeof z==="object"?z:z===null?J.error?`Subagent execution failed: ${J.error}.`:"":String(z),...J.error?{error:{type:"execution_error",message:J.error}}:{},...Q?{metadata:Q}:{}},V=[{kind:"tool_result",toolCall:Y,result:W}],U=iY(Y,W);if(U)V.push(U);return V})}takeStartupRecoveryEvents(){let $=this.sessionRuntime?.getTurnRecoveryAssessment(),Z=$?.state==="requires_attention"?$:this.sessionRuntime?.takeStartupTurnRecoveryAssessment(),J=Z&&Z.state!=="none"?[{kind:"turn_recovery",assessment:Z}]:[];return J.push(...this.takeStartupAdoptedToolResultEvents()),J}buildLoopDependencies(){return{chatService:this.chatService,toolExecutor:this.toolExecutor,executionEngine:this.executionEngine,config:this.config,runtimeOptions:this.runtimeOptions,currentModelMaxContextTokens:this.currentModelMaxContextTokens,activeSkillContext:this.activeSkillContext,onSkillActivated:($)=>{this.activeSkillContext=$,a.debug(`Skill "${$.skillName}" activated`+($.allowedTools?` with allowed tools: ${$.allowedTools.join(", ")}`:""))},onModelSwitch:($)=>this.switchModelIfNeeded($),applySkillToolRestrictions:($)=>this.applySkillToolRestrictions($),staticProjectRules:this.sessionRuntime?.getStaticProjectRules(),hydrateProjectRules:this.sessionRuntime?($)=>this.sessionRuntime.hydrateProjectRules($):void 0,resolveContextualProjectRules:this.sessionRuntime?($,Z,J,Y)=>this.sessionRuntime.resolveContextualProjectRules($,Z,J,Y):void 0}}async chatWithSystem($,Z){if(!this.isInitialized)throw Error("Agent未初始化");let J=[{role:"system",content:$},{role:"user",content:Z}];return(await this.chatService.chat(J)).content}getActiveTask(){return this.activeTask}getChatService(){return this.chatService}getContextManager(){return this.executionEngine?.getContextManager()}getStats(){return{initialized:this.isInitialized,activeTask:this.activeTask?.id,components:{chatService:this.chatService?"ready":"not_loaded",executionEngine:this.executionEngine?"ready":"not_loaded"}}}getAvailableTools(){return this.toolExecutor?this.toolExecutor.getRegistry().getAll():[]}getToolRegistry(){return this.toolExecutor.getRegistry()}applyToolWhitelist($){let Z=this.toolExecutor.getRegistry(),Y=Z.getAll().filter((Q)=>!$.includes(Q.name));for(let Q of Y)Z.unregister(Q.name);a.debug(`Applied tool whitelist: ${$.join(", ")} (removed ${Y.length} tools)`)}applyToolBlacklist($){let Z=this.toolExecutor.getRegistry(),J=new Set($);for(let Y of Z.getAll())if(J.has(Y.name))Z.unregister(Y.name);a.debug(`Applied tool blacklist: ${$.join(", ")}`)}getToolStats(){let $=this.getAvailableTools(),Z=new Map;return $.forEach((J)=>{let Y=Z.get(J.kind)||0;Z.set(J.kind,Y+1)}),{totalTools:$.length,toolsByKind:Object.fromEntries(Z),toolNames:$.map((J)=>J.name)}}async destroy(){if(this.destroyPromise)return this.destroyPromise;return this.destroyPromise=(async()=>{this.log("销毁Agent..."),await this.activeOperations.shutdown("agent-destroy");try{await this.legacyMcpRegistry?.disconnectAll(),this.legacyMcpRegistry=void 0,this.log("Agent已销毁")}catch($){throw this.error("Agent销毁失败",$),$}finally{this.toolExecutor.dispose(),this.isInitialized=!1}})(),this.destroyPromise}syncRuntimeState(){if(!this.sessionRuntime)return;this.chatService=this.sessionRuntime.getChatService(),this.executionEngine=this.sessionRuntime.getExecutionEngine(),this.attachmentCollector=this.sessionRuntime.getAttachmentCollector(),this.currentModelId=this.sessionRuntime.getCurrentModelId(),this.currentModelMaxContextTokens=this.sessionRuntime.getCurrentModelMaxContextTokens()}generateTaskId(){return`task_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}log($,Z){a.debug(`[MainAgent] ${$}`,Z||"")}error($,Z){a.error(`[MainAgent] ${$}`,Z||"")}async initializeSystemPrompt(){try{let $=this.runtimeOptions.systemPrompt,Z=this.runtimeOptions.appendSystemPrompt,J=await Y1({...this.sessionRuntime?.isRemoteWorkspace()?{workspaceAccess:"none"}:{projectPath:this.sessionRuntime?.workspaceRoot??C()},replaceDefault:$,append:Z,includeEnvironment:!1,language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),...this.sessionRuntime?.isRemoteWorkspace()?{}:{projectInstructionSourcePath:this.sessionRuntime?.projectRoot},...this.sessionRuntime?{environmentOptions:{...u1,workingDirectory:this.sessionRuntime.executionRoot}}:{}});if(J.prompt)this.log("系统提示配置验证成功"),a.debug(`[SystemPrompt] 可用来源: ${J.sources.filter((Y)=>Y.loaded).map((Y)=>Y.name).join(", ")}`)}catch($){this.error("系统提示配置验证失败",$)}}async registerBuiltinTools(){try{let $=await v4({sessionId:"default",configDir:t(),workspaceRoot:C(),resourceRoot:C(),agentResources:this.agentResources});a.debug(`Registering ${$.length} builtin tools...`),this.toolExecutor.getRegistry().registerAll($);let Z=this.toolExecutor.getRegistry().getAll().length;a.debug(`Builtin tools registered: ${Z} tools`),a.debug(`[Tools] ${this.toolExecutor.getRegistry().getAll().map((J)=>J.name).join(", ")}`),await this.registerMcpTools()}catch($){throw a.error("Failed to register builtin tools:",$),$}}async registerMcpTools(){try{let $=await z4({workspaceRoot:C(),storeServers:this.config.mcpServers??{},cliConfigs:this.runtimeOptions.mcpConfig,strictCliConfig:this.runtimeOptions.strictMcpConfig});if(Object.keys($).length===0){a.debug("No MCP servers configured");return}let Z=e0.createIsolated({artifactWriter:new o2(`legacy-${QG()}`)});this.legacyMcpRegistry=Z;for(let[X,z]of Object.entries($))try{a.debug(`Connecting to MCP server: ${X}`),await Z.registerServer(X,z),a.debug(`MCP server "${X}" connected`)}catch(W){a.warn(`Warning: MCP server "${X}" connection failed:`,W)}let J=this.toolExecutor.getRegistry();J.setMcpCatalogBarrier(()=>Z.waitForCatalogIdle());let Y=Z.getCatalogSnapshot();J.replaceMcpTools(Y.tools),J.registerAll(Y6(Z));let Q=Z.getInstructionsSnapshot();if(J.queueMcpInstructionsChange({revision:Q.revision,reason:"snapshot",replace:!0,instructions:Q.instructions,removed:[]}),Z.on("catalogChanged",(X)=>{J.replaceMcpTools(X.tools,X)}),Z.on("contentCatalogChanged",(X)=>{J.queueMcpContentChange(X)}),Z.on("resourceUpdated",(X)=>{J.queueMcpResourceUpdated(X)}),Z.on("connectionLifecycleChanged",(X)=>{J.queueMcpConnectionChange(X)}),Z.on("log",(X)=>{J.queueMcpLog(X)}),Z.on("instructionsChanged",(X)=>{J.queueMcpInstructionsChange({revision:X.revision,reason:X.reason,replace:!1,instructions:X.action==="added"&&X.instruction?[{serverName:X.serverName,...X.instruction}]:[],removed:X.action==="removed"?[X.serverName]:[]})}),Y.tools.length>0)a.debug(`Registered ${Y.tools.length} MCP tools`),a.debug(`[MCP Tools] ${Y.tools.map((X)=>X.name).join(", ")}`)}catch($){a.warn("Failed to register MCP tools:",$)}}async loadSubagents(){let $=await c0(C());if(this.agentResources=k4($),this.subagentRegistry=this.agentResources.subagents,this.runtimeOptions.agents?.length)this.subagentRegistry.applyOverrides(this.runtimeOptions.agents);let Z=this.subagentRegistry.getAllNames().length;if(Z>0)a.debug(`Loaded ${Z} subagents: ${this.subagentRegistry.getAllNames().join(", ")}`);else a.debug("No subagents configured")}applySkillToolRestrictions($){if(!this.activeSkillContext?.allowedTools)return $;let Z=this.activeSkillContext.allowedTools;a.debug(`Applying Skill tool restrictions: ${Z.join(", ")}`);let J=$.filter((Y)=>{if(Y.name==="ReadPromptArtifact")return!0;return Z.some((Q)=>{if(Q===Y.name)return!0;let X=Q.match(/^(\w+)\(.*\)$/);if(X&&X[1]===Y.name)return!0;return!1})});return a.debug(`Filtered tools: ${J.map((Y)=>Y.name).join(", ")} (${J.length}/${$.length})`),J}clearSkillContext(){if(this.activeSkillContext)a.debug(`Skill "${this.activeSkillContext.skillName}" deactivated`),this.activeSkillContext=void 0}async processAtMentionsForContent($){if(!this.attachmentCollector)return $;if(typeof $==="string")return this.processAtMentions($);let Z=[];for(let Y of $)if(Y.type==="text")Z.push(Y.text);if(Z.length===0)return $;let J=Z.join(`
862
+ `),L={id:this.generateTaskId(),type:"simple",prompt:_};return{success:!0,finalMessage:(await this.executeTask(L)).content,metadata:{turnsCount:1,toolCallsCount:0,duration:0}}}async chat($,Z,J){let{drainLoop:Y}=await import("./chunk-jxxvc3b0.js");return Y(this.chatStream($,Z,J))}async*runPlanLoop($,Z,J){a.debug("Processing Plan mode message...");let{prompt:Y}=await Y1({...Z.workspaceKind==="acp-remote"?{workspaceAccess:"none"}:{projectPath:Z.workspaceRoot||C()},mode:"plan",includeEnvironment:!0,environmentOptions:{...u1,workingDirectory:Z.executionRoot??Z.workspaceRoot??C()},language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),...Z.workspaceKind==="acp-remote"?{}:{projectInstructionSourcePath:this.sessionRuntime?.projectRoot}}),Q;if(typeof $==="string")Q=t2($);else{let X=$.filter((z)=>z.type==="text");if(X.length>0){let z=X[0];Q=$.map((W)=>W===z?{type:"text",text:t2(z.text)}:W)}else Q=[{type:"text",text:t2("")},...$]}return yield*this.executeLoop(Q,Z,J,Y)}async*runLoop($,Z,J){a.debug("Processing enhanced chat message...");let Y=Z.systemPrompt??await this.buildSystemPromptOnDemand(Z);return yield*this.executeLoop($,Z,J,Y)}async buildSystemPromptOnDemand($){let Z=this.runtimeOptions.systemPrompt,J=this.runtimeOptions.appendSystemPrompt;return(await Y1({...$.workspaceKind==="acp-remote"?{workspaceAccess:"none"}:{projectPath:$.workspaceRoot||C()},replaceDefault:Z,append:J,includeEnvironment:!0,environmentOptions:{...u1,workingDirectory:$.executionRoot??$.workspaceRoot??C()},language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),...$.workspaceKind==="acp-remote"?{}:{projectInstructionSourcePath:this.sessionRuntime?.projectRoot}})).prompt}executeLoop($,Z,J,Y){if(!this.isInitialized)throw Error("Agent未初始化");let Q=this.buildLoopDependencies();return rY(Q,$,Z,J,Y)}takeStartupAdoptedToolResultEvents(){return(this.sessionRuntime?.takeStartupAdoptedToolResults()??[]).flatMap(({call:Z,result:J})=>{let Y={id:Z.toolCallId,type:"function",function:{name:Z.toolName,arguments:JSON.stringify(Z.input)}},Q=J.metadata&&typeof J.metadata==="object"&&!Array.isArray(J.metadata)?J.metadata:void 0,X=J.error===void 0,z=J.output,W={success:X,llmContent:typeof z==="string"||z!==null&&typeof z==="object"?z:z===null?J.error?`Subagent execution failed: ${J.error}.`:"":String(z),...J.error?{error:{type:"execution_error",message:J.error}}:{},...Q?{metadata:Q}:{}},V=[{kind:"tool_result",toolCall:Y,result:W}],U=iY(Y,W);if(U)V.push(U);return V})}takeStartupRecoveryEvents(){let $=this.sessionRuntime?.getTurnRecoveryAssessment(),Z=$?.state==="requires_attention"?$:this.sessionRuntime?.takeStartupTurnRecoveryAssessment(),J=Z&&Z.state!=="none"?[{kind:"turn_recovery",assessment:Z}]:[];return J.push(...this.takeStartupAdoptedToolResultEvents()),J}buildLoopDependencies(){return{chatService:this.chatService,toolExecutor:this.toolExecutor,executionEngine:this.executionEngine,config:this.config,runtimeOptions:this.runtimeOptions,currentModelMaxContextTokens:this.currentModelMaxContextTokens,activeSkillContext:this.activeSkillContext,onSkillActivated:($)=>{this.activeSkillContext=$,a.debug(`Skill "${$.skillName}" activated`+($.allowedTools?` with allowed tools: ${$.allowedTools.join(", ")}`:""))},onModelSwitch:($)=>this.switchModelIfNeeded($),applySkillToolRestrictions:($)=>this.applySkillToolRestrictions($),staticProjectRules:this.sessionRuntime?.getStaticProjectRules(),hydrateProjectRules:this.sessionRuntime?($)=>this.sessionRuntime.hydrateProjectRules($):void 0,resolveContextualProjectRules:this.sessionRuntime?($,Z,J,Y)=>this.sessionRuntime.resolveContextualProjectRules($,Z,J,Y):void 0}}async chatWithSystem($,Z){if(!this.isInitialized)throw Error("Agent未初始化");let J=[{role:"system",content:$},{role:"user",content:Z}];return(await this.chatService.chat(J)).content}getActiveTask(){return this.activeTask}getChatService(){return this.chatService}getContextManager(){return this.executionEngine?.getContextManager()}getStats(){return{initialized:this.isInitialized,activeTask:this.activeTask?.id,components:{chatService:this.chatService?"ready":"not_loaded",executionEngine:this.executionEngine?"ready":"not_loaded"}}}getAvailableTools(){return this.toolExecutor?this.toolExecutor.getRegistry().getAll():[]}getToolRegistry(){return this.toolExecutor.getRegistry()}applyToolWhitelist($){let Z=this.toolExecutor.getRegistry(),Y=Z.getAll().filter((Q)=>!$.includes(Q.name));for(let Q of Y)Z.unregister(Q.name);a.debug(`Applied tool whitelist: ${$.join(", ")} (removed ${Y.length} tools)`)}applyToolBlacklist($){let Z=this.toolExecutor.getRegistry(),J=new Set($);for(let Y of Z.getAll())if(J.has(Y.name))Z.unregister(Y.name);a.debug(`Applied tool blacklist: ${$.join(", ")}`)}getToolStats(){let $=this.getAvailableTools(),Z=new Map;return $.forEach((J)=>{let Y=Z.get(J.kind)||0;Z.set(J.kind,Y+1)}),{totalTools:$.length,toolsByKind:Object.fromEntries(Z),toolNames:$.map((J)=>J.name)}}async destroy(){if(this.destroyPromise)return this.destroyPromise;return this.destroyPromise=(async()=>{this.log("销毁Agent..."),await this.activeOperations.shutdown("agent-destroy");try{await this.legacyMcpRegistry?.disconnectAll(),this.legacyMcpRegistry=void 0,this.log("Agent已销毁")}catch($){throw this.error("Agent销毁失败",$),$}finally{this.toolExecutor.dispose(),this.isInitialized=!1}})(),this.destroyPromise}syncRuntimeState(){if(!this.sessionRuntime)return;this.chatService=this.sessionRuntime.getChatService(),this.executionEngine=this.sessionRuntime.getExecutionEngine(),this.attachmentCollector=this.sessionRuntime.getAttachmentCollector(),this.currentModelId=this.sessionRuntime.getCurrentModelId(),this.currentModelMaxContextTokens=this.sessionRuntime.getCurrentModelMaxContextTokens()}generateTaskId(){return`task_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}log($,Z){a.debug(`[MainAgent] ${$}`,Z||"")}error($,Z){a.error(`[MainAgent] ${$}`,Z||"")}async initializeSystemPrompt(){try{let $=this.runtimeOptions.systemPrompt,Z=this.runtimeOptions.appendSystemPrompt,J=await Y1({...this.sessionRuntime?.isRemoteWorkspace()?{workspaceAccess:"none"}:{projectPath:this.sessionRuntime?.workspaceRoot??C()},replaceDefault:$,append:Z,includeEnvironment:!1,language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),...this.sessionRuntime?.isRemoteWorkspace()?{}:{projectInstructionSourcePath:this.sessionRuntime?.projectRoot},...this.sessionRuntime?{environmentOptions:{...u1,workingDirectory:this.sessionRuntime.executionRoot}}:{}});if(J.prompt)this.log("系统提示配置验证成功"),a.debug(`[SystemPrompt] 可用来源: ${J.sources.filter((Y)=>Y.loaded).map((Y)=>Y.name).join(", ")}`)}catch($){this.error("系统提示配置验证失败",$)}}async registerBuiltinTools(){try{let $=await v4({sessionId:"default",configDir:t(),workspaceRoot:C(),resourceRoot:C(),agentResources:this.agentResources});a.debug(`Registering ${$.length} builtin tools...`),this.toolExecutor.getRegistry().registerAll($);let Z=this.toolExecutor.getRegistry().getAll().length;a.debug(`Builtin tools registered: ${Z} tools`),a.debug(`[Tools] ${this.toolExecutor.getRegistry().getAll().map((J)=>J.name).join(", ")}`),await this.registerMcpTools()}catch($){throw a.error("Failed to register builtin tools:",$),$}}async registerMcpTools(){try{let $=await z4({workspaceRoot:C(),storeServers:this.config.mcpServers??{},cliConfigs:this.runtimeOptions.mcpConfig,strictCliConfig:this.runtimeOptions.strictMcpConfig});if(Object.keys($).length===0){a.debug("No MCP servers configured");return}let Z=e0.createIsolated({artifactWriter:new o2(`legacy-${QG()}`)});this.legacyMcpRegistry=Z;for(let[X,z]of Object.entries($))try{a.debug(`Connecting to MCP server: ${X}`),await Z.registerServer(X,z),a.debug(`MCP server "${X}" connected`)}catch(W){a.warn(`Warning: MCP server "${X}" connection failed:`,W)}let J=this.toolExecutor.getRegistry();J.setMcpCatalogBarrier(()=>Z.waitForCatalogIdle());let Y=Z.getCatalogSnapshot();J.replaceMcpTools(Y.tools),J.registerAll(Y6(Z));let Q=Z.getInstructionsSnapshot();if(J.queueMcpInstructionsChange({revision:Q.revision,reason:"snapshot",replace:!0,instructions:Q.instructions,removed:[]}),Z.on("catalogChanged",(X)=>{J.replaceMcpTools(X.tools,X)}),Z.on("contentCatalogChanged",(X)=>{J.queueMcpContentChange(X)}),Z.on("resourceUpdated",(X)=>{J.queueMcpResourceUpdated(X)}),Z.on("connectionLifecycleChanged",(X)=>{J.queueMcpConnectionChange(X)}),Z.on("log",(X)=>{J.queueMcpLog(X)}),Z.on("instructionsChanged",(X)=>{J.queueMcpInstructionsChange({revision:X.revision,reason:X.reason,replace:!1,instructions:X.action==="added"&&X.instruction?[{serverName:X.serverName,...X.instruction}]:[],removed:X.action==="removed"?[X.serverName]:[]})}),Y.tools.length>0)a.debug(`Registered ${Y.tools.length} MCP tools`),a.debug(`[MCP Tools] ${Y.tools.map((X)=>X.name).join(", ")}`)}catch($){a.warn("Failed to register MCP tools:",$)}}async loadSubagents(){let $=await c0(C());if(this.agentResources=k4($),this.subagentRegistry=this.agentResources.subagents,this.runtimeOptions.agents?.length)this.subagentRegistry.applyOverrides(this.runtimeOptions.agents);let Z=this.subagentRegistry.getAllNames().length;if(Z>0)a.debug(`Loaded ${Z} subagents: ${this.subagentRegistry.getAllNames().join(", ")}`);else a.debug("No subagents configured")}applySkillToolRestrictions($){if(!this.activeSkillContext?.allowedTools)return $;let Z=this.activeSkillContext.allowedTools;a.debug(`Applying Skill tool restrictions: ${Z.join(", ")}`);let J=$.filter((Y)=>{if(Y.name==="ReadPromptArtifact")return!0;return Z.some((Q)=>{if(Q===Y.name)return!0;let X=Q.match(/^(\w+)\(.*\)$/);if(X&&X[1]===Y.name)return!0;return!1})});return a.debug(`Filtered tools: ${J.map((Y)=>Y.name).join(", ")} (${J.length}/${$.length})`),J}clearSkillContext(){if(this.activeSkillContext)a.debug(`Skill "${this.activeSkillContext.skillName}" deactivated`),this.activeSkillContext=void 0}async processAtMentionsForContent($){if(!this.attachmentCollector)return $;if(typeof $==="string")return this.processAtMentions($);let Z=[];for(let Y of $)if(Y.type==="text")Z.push(Y.text);if(Z.length===0)return $;let J=Z.join(`
863
863
  `);try{let Y=await this.attachmentCollector.collect(J);if(Y.length===0)return $;a.debug(`Processed ${Y.length} @ file mentions in multimodal message`);let Q=this.buildAttachmentText(Y);if(!Q)return $;return[...$,{type:"text",text:Q}]}catch(Y){return a.error("Failed to process @ mentions in multimodal message:",Y),$}}buildAttachmentText($){let Z=[],J=[];for(let Q of $)if(Q.type==="file"){let X=Q.metadata?.lineRange?` (lines ${Q.metadata.lineRange.start}${Q.metadata.lineRange.end?`-${Q.metadata.lineRange.end}`:""})`:"";Z.push(`<file path="${Q.path}"${X?` range="${X}"`:""}>`,Q.content,"</file>")}else if(Q.type==="directory")Z.push(`<directory path="${Q.path}">`,Q.content,"</directory>");else if(Q.type==="error")J.push(`- @${Q.path}: ${Q.error}`);let Y="";if(Z.length>0)Y+=`
864
864
 
865
865
  <system-reminder>
@@ -1675,7 +1675,7 @@ ${J}
1675
1675
  `)),{success:!0,message:"Schedules listed",content:V.join(`
1676
1676
  `)}}case"create":{let W=aw(X);if("error"in W)return Y.sendMessage(`创建失败:${W.error}`),{success:!1,error:W.error};let V={prompt:W.prompt,projectPath:z,trigger:W.trigger,isolation:"worktree",permissionMode:"default",enabled:!0};try{let U=await $.create(V),H=U.nextRunAt?new Date(U.nextRunAt).toLocaleString():"(无)";return Y.sendMessage(`[OK] 已创建定时任务 \`${U.id}\`
1677
1677
  ${A9(U.trigger)} · 下次运行: ${H}`),{success:!0,message:`Schedule ${U.id} created`}}catch(U){let H=U instanceof Error?U.message:String(U);return Y.sendMessage(`创建失败:${H}`),{success:!1,error:H}}}case"remove":case"rm":{let W=X[0];if(!W)return Y.sendMessage("用法:/schedule remove <id>"),{success:!1,error:"Missing schedule id"};let V=await $.remove(W);return Y.sendMessage(V?`[OK] 已删除 \`${W}\``:`未找到 \`${W}\``),{success:V,message:V?"Removed":"Not found"}}case"enable":case"disable":{let W=X[0];if(!W)return Y.sendMessage(`用法:/schedule ${Q} <id>`),{success:!1,error:"Missing schedule id"};let V=await $.setEnabled(W,Q==="enable");return Y.sendMessage(V?`[OK] 已${Q==="enable"?"启用":"停用"} \`${W}\``:`未找到 \`${W}\``),{success:Boolean(V),message:V?"Updated":"Not found"}}case"run":{let W=X[0];if(!W)return Y.sendMessage("用法:/schedule run <id>"),{success:!1,error:"Missing schedule id"};try{return await sw(W),Y.sendMessage(`[OK] 已触发 \`${W}\``),{success:!0,message:"Schedule triggered"}}catch(V){let U=V instanceof Error?V.message:String(V);return Y.sendMessage(`运行失败:${U}`),{success:!1,error:U}}}default:return Y.sendMessage(`未知子命令: ${Q}
1678
- 使用 /schedule 查看帮助`),{success:!1,error:`Unknown subcommand: ${Q}`}}}}}var sz=ow();import*as f2 from"node:fs/promises";import*as P2 from"node:path";async function ZW($,Z={}){let{maxResults:J=20,caseSensitive:Y=!1,projectPath:Q,storagePath:X}=Z,z=X??P6(Q??C());if(!X){let G=await tw($,Q??C(),J,Y);if(G)return G}let W;try{W=(await f2.readdir(z)).filter((D)=>D.endsWith(".jsonl")&&!D.startsWith("agent_")).map((D)=>P2.join(z,D))}catch{return[]}let U=(await Promise.all(W.map(async(G)=>{try{let D=await f2.stat(G);return{path:G,mtime:D.mtimeMs}}catch{return null}}))).filter((G)=>G!==null).sort((G,D)=>D.mtime-G.mtime).map((G)=>G.path),H=[],B=Y?$:$.toLowerCase();for(let G of U){if(H.length>=J)break;let D=P2.basename(G,".jsonl"),w=await ew(G,B,Y,D);if(H.push(...w),H.length>=J){H.length=J;break}}return H}async function tw($,Z,J,Y){try{let{syncAll:Q}=await import("./chunk-cv4h5c96.js"),X=await ez();if(!X)return null;let{SessionService:z}=await import("./chunk-p1d4ep58.js");await Q(X,z.projectionDeriverForSearch());let W=P2.resolve(Z),V=$W(X,$,W,J*4),U=Y?$:$.toLowerCase(),H=[];for(let B of V){if(B.role!=="user"&&B.role!=="assistant")continue;let G=M9(B.text,U,Y,B.session_id,B.role,B.timestamp??void 0,0);if(G)H.push(G);if(H.length>=J)break}return H}catch{return null}}async function ew($,Z,J,Y){try{let Q=await f2.readFile($,"utf8"),z=Q.split(`
1678
+ 使用 /schedule 查看帮助`),{success:!1,error:`Unknown subcommand: ${Q}`}}}}}var sz=ow();import*as f2 from"node:fs/promises";import*as P2 from"node:path";async function ZW($,Z={}){let{maxResults:J=20,caseSensitive:Y=!1,projectPath:Q,storagePath:X}=Z,z=X??P6(Q??C());if(!X){let G=await tw($,Q??C(),J,Y);if(G)return G}let W;try{W=(await f2.readdir(z)).filter((D)=>D.endsWith(".jsonl")&&!D.startsWith("agent_")).map((D)=>P2.join(z,D))}catch{return[]}let U=(await Promise.all(W.map(async(G)=>{try{let D=await f2.stat(G);return{path:G,mtime:D.mtimeMs}}catch{return null}}))).filter((G)=>G!==null).sort((G,D)=>D.mtime-G.mtime).map((G)=>G.path),H=[],B=Y?$:$.toLowerCase();for(let G of U){if(H.length>=J)break;let D=P2.basename(G,".jsonl"),w=await ew(G,B,Y,D);if(H.push(...w),H.length>=J){H.length=J;break}}return H}async function tw($,Z,J,Y){try{let{syncAll:Q}=await import("./chunk-42y6ks44.js"),X=await ez();if(!X)return null;let{SessionService:z}=await import("./chunk-1329rzdd.js");await Q(X,z.projectionDeriverForSearch());let W=P2.resolve(Z),V=$W(X,$,W,J*4),U=Y?$:$.toLowerCase(),H=[];for(let B of V){if(B.role!=="user"&&B.role!=="assistant")continue;let G=M9(B.text,U,Y,B.session_id,B.role,B.timestamp??void 0,0);if(G)H.push(G);if(H.length>=J)break}return H}catch{return null}}async function ew($,Z,J,Y){try{let Q=await f2.readFile($,"utf8"),z=Q.split(`
1679
1679
  `).flatMap((B,G)=>{if(!B.trim())return[];try{return[{event:JSON.parse(B),index:G}]}catch{return[]}});if(!z.some(({event:B})=>B.type==="session_created"))return $F(z,Z,J,Y);let V=new Map(z.flatMap(({event:B,index:G})=>typeof B.id==="string"?[[B.id,G+1]]:[])),U=oz(tz(Q,$)),H=new Map;for(let B of U){if(B.type==="message_created"&&(B.data.role==="user"||B.data.role==="assistant"))H.set(B.data.messageId,{role:B.data.role,content:[],timestamp:B.timestamp,lineNumber:V.get(B.id)??0});if(B.type==="part_created"&&B.data.partType==="text"){let G=H.get(B.data.messageId),D=B.data.payload.text;if(G&&typeof D==="string")G.content.push(D)}}return[...H.values()].flatMap((B)=>{let G=M9(B.content.join(" "),Z,J,Y,B.role,B.timestamp,B.lineNumber);return G?[G]:[]})}catch{return[]}}function $F($,Z,J,Y){return $.flatMap(({event:Q,index:X})=>{if(Q.type!=="message")return[];let z=Q.message;if(z?.role!=="user"&&z?.role!=="assistant"||!z.content)return[];let W=typeof z.content==="string"?z.content:Array.isArray(z.content)?z.content.filter((U)=>typeof U==="object"&&U!==null&&U.type==="text"&&typeof U.text==="string").map((U)=>U.text).join(" "):"",V=M9(W,Z,J,Y,z.role,typeof Q.timestamp==="string"?Q.timestamp:void 0,X+1);return V?[V]:[]})}function M9($,Z,J,Y,Q,X,z){if(!$)return;let W=J?$:$.toLowerCase();if(!W.includes(Z))return;let V=W.indexOf(Z),U=Math.max(0,V-80),H=Math.min($.length,V+Z.length+80);return{sessionId:Y,role:Q,content:(U>0?"...":"")+$.slice(U,H).replace(/\n/g," ")+(H<$.length?"...":""),timestamp:X,lineNumber:z}}function JW($){if($.length===0)return"没有找到匹配的历史记录";let Z=[`**找到 ${$.length} 条匹配:**
1680
1680
  `];for(let J of $){let Y=J.timestamp?new Date(J.timestamp).toLocaleString("zh-CN",{timeZone:"Asia/Shanghai"}):"?",Q=J.role==="user"?"\uD83D\uDC64":"\uD83E\uDD16";Z.push(`${Q} \`${J.sessionId.slice(0,8)}\` (${Y})`),Z.push(` ${J.content}`),Z.push("")}return Z.join(`
1681
1681
  `)}var ZF={name:"search",description:"Search past session transcripts",fullDescription:"搜索历史会话记录,查找过去的对话内容",usage:"/search <keyword>",aliases:["find","history"],category:"Session",examples:['/search 断路器 - 搜索包含"断路器"的历史对话',"/search edit tool - 搜索 edit tool 相关讨论"],async handler($,Z){let J=c(Z);if($.length===0)return J.sendMessage("**用法:** `/search <关键词>`\n\n在历史会话中搜索包含指定关键词的对话"),{success:!0,message:"显示帮助"};let Y=$.join(" ");J.sendMessage(`正在搜索: "${Y}" ...`);try{let Q=await ZW(Y,{maxResults:15,projectPath:Z.cwd}),X=JW(Q);return J.sendMessage(X),{success:!0,message:`found ${Q.length} results`,data:{matches:Q.length}}}catch(Q){let X=Q instanceof Error?Q.message:"未知错误";return J.sendMessage(`搜索失败: ${X}`),{success:!1,error:X}}}},YW=ZF;var JF={name:"skills",description:"查看所有可用的 Skills",fullDescription:"显示所有已发现的 Skills 及其详细信息,包括名称、描述、来源和允许的工具。",usage:"/skills",category:"system",examples:["/skills"],handler:async($,Z)=>{try{let J=Z.workspaceRoot??Z.cwd;return await f$(J,async(Y)=>{await Y.skills.refresh(),i1(J),await l1(J)}),{success:!0,message:"show_skills_manager",data:{action:"show_skills_manager"}}}catch(J){let Y=`获取 Skills 失败: ${J instanceof Error?J.message:"未知错误"}`;return d().addAssistantMessage(Y),{success:!1,error:Y}}}},QW=JF;import YF from"node:path";function O8($){if($<1000)return`${$}ms`;let Z=Math.floor($/1000);if(Z<60)return`${Z}s`;let J=Math.floor(Z/60);if(J<60)return`${J}m ${Z%60}s`;return`${Math.floor(J/60)}h ${J%60}m`}function XW($){switch($){case"running":return"[RUNNING]";case"completed":case"exited":return"[OK]";case"failed":case"error":return"[FAIL]";case"killed":case"cancelled":return"[STOPPED]";default:return"[?]"}}function zW($,Z){if($.length<=Z)return $;return $.slice(0,Z-3)+"..."}async function QF($,Z){let J=c(Z),Y=$[0],Q=Y0.getInstance(),X=D0.getInstance(),z=Z.sessionId??"",W=Z.sessionId?{sessionId:Z.sessionId,projectPath:YF.resolve(Z.workspaceRoot??Z.cwd)}:void 0;if(Y==="resume"){let D=$[1],w=$.slice(2).join(" ").trim();if(!D||!w)return{success:!1,error:"Usage: /tasks resume <agentId> <prompt>"};if(!Z.subagents)return{success:!1,error:"This surface does not own a subagent runtime"};let q=await Z.subagents.resume(D,w),_=`Resumed \`${D}\` as \`${q.session.id}\` (depth ${q.session.resumeDepth}).`;return J.sendMessage(_),{success:!0,message:_,data:{action:"subagent_resumed",sourceAgentId:D,subagent:q.session}}}if(Y==="clean"){let D=X.cleanupExpiredSessionsForParent(W??z,0);return J.sendMessage(`已清理 ${D} 个已完成的 Agent 会话`),{success:!0,message:`Cleaned ${D} agent sessions`}}let V=[`**后台任务列表**
@@ -1,2 +1,2 @@
1
- import{Wj as I}from"./chunk-7r26xgk4.js";import{Lk as f}from"./chunk-sdapqhj0.js";import*as j from"fs/promises";import*as S from"path";import X from"semver";import{ProxyAgent as R,fetch as k}from"undici";function x(){return process.env.HTTPS_PROXY||process.env.HTTP_PROXY||process.env.https_proxy||process.env.http_proxy}function L(){let z=x();if(z)try{return new R(z)}catch(q){console.warn(`[proxyFetch] Invalid proxy URL: ${z}`)}return}async function F(z,q,Z){let{timeout:W=30000,signal:J,...Q}=q;if(J?.aborted)throw new DOMException("The operation was aborted.","AbortError");let Y=L(),$=new AbortController,w=!1,y=setTimeout(()=>{w=!0,$.abort()},W),T=()=>$.abort();J?.addEventListener("abort",T);let D;try{let B={method:Q.method,headers:Q.headers,body:Q.body,signal:$.signal,dispatcher:Y};return D=await k(z.toString(),B),await Z(D)}catch(B){if(B instanceof Error&&B.name==="AbortError"){if(w)throw Error(`Request timeout after ${W}ms`);throw B}throw B}finally{if(clearTimeout(y),J?.removeEventListener("abort",T),$.abort(),D?.body&&!D.body.locked)await D.body.cancel().catch(()=>{return});await Y?.destroy?.().catch(()=>{return})}}var O="blade-code",G="https://cdn.jsdelivr.net/npm/blade-code@latest/CHANGELOG.md",H=S.join(process.env.HOME||process.env.USERPROFILE||".",".blade"),N=S.join(H,"version-cache.json"),_=3600000,g=`https://registry.npmjs.org/${O}/latest`,M=null;async function P(){try{if(process.env.BLADE_VERSION)return process.env.BLADE_VERSION;return I()}catch{return"unknown"}}async function b(){try{let z=await j.readFile(N,"utf-8"),q=JSON.parse(z);if(Date.now()-q.checkedAt<_)return q;return{...q,checkedAt:0}}catch{return null}}async function K(z){try{await j.mkdir(H,{recursive:!0,mode:493}),await j.writeFile(N,JSON.stringify(z,null,2))}catch{}}async function E(){try{return await F(g,{timeout:5000,headers:{Accept:"application/json"}},async(z)=>{if(!z.ok)return null;let q=await z.json();if(!q||typeof q!=="object"||!("version"in q))return null;return typeof q.version==="string"&&X.valid(q.version)?q.version:null})}catch{return null}}async function A(z=!1){let q=await P(),Z=G;if(q==="unknown")return{currentVersion:q,latestVersion:null,hasUpdate:!1,shouldPrompt:!1,releaseNotesUrl:Z,error:"Unable to determine current version"};let W=await b(),J=W?.skipUntilVersion,Q=null;if(!z&&W?.latestVersion&&W.checkedAt>0)Q=W.latestVersion;else if(Q=await E(),J=(await b())?.skipUntilVersion??J,Q)await K({latestVersion:Q,checkedAt:Date.now(),skipUntilVersion:J});else if(W?.latestVersion)await K({checkedAt:0,skipUntilVersion:J});if(!Q||!X.valid(Q))return{currentVersion:q,latestVersion:null,hasUpdate:!1,shouldPrompt:!1,releaseNotesUrl:Z,error:"Unable to check for updates"};if(X.lt(Q,q))Q=q,await K({latestVersion:Q,checkedAt:Date.now(),skipUntilVersion:J});let Y=X.gt(Q,q),$=Y;if(Y&&J)$=X.gt(Q,J);return{currentVersion:q,latestVersion:Q,hasUpdate:Y,shouldPrompt:$,releaseNotesUrl:Z}}async function V(z){let q=await b();await K({latestVersion:q?.latestVersion??z,checkedAt:q?.checkedAt||Date.now(),skipUntilVersion:z})}function v(){return`npm install -g ${O}@latest --registry https://registry.npmjs.org`}async function p(){let{spawn:z}=await import("child_process");return new Promise((q)=>{let Z=v(),W=z(Z,{stdio:"inherit",shell:!0});W.on("close",(J)=>{if(J===0)q({success:!0,message:"Upgrade successful! Please restart blade."});else q({success:!1,message:`Upgrade failed (exit code: ${J})`})}),W.on("error",(J)=>{q({success:!1,message:`Upgrade failed: ${J.message}`})})})}async function h(){try{let z=await b();if(!z?.latestVersion||!X.valid(z.latestVersion)||!z.checkedAt){if(!M)M=A(!0).then(()=>{return},()=>{return}).finally(()=>{M=null});return null}let q=await P();if(!X.valid(q)||!X.gt(z.latestVersion,q)||z.skipUntilVersion&&X.valid(z.skipUntilVersion)&&!X.gt(z.latestVersion,z.skipUntilVersion))return null;return{currentVersion:q,latestVersion:z.latestVersion,hasUpdate:!0,shouldPrompt:!0,releaseNotesUrl:G}}catch{return null}}
1
+ import{Wj as I}from"./chunk-xh3bm0p0.js";import{Lk as f}from"./chunk-sdapqhj0.js";import*as j from"fs/promises";import*as S from"path";import X from"semver";import{ProxyAgent as R,fetch as k}from"undici";function x(){return process.env.HTTPS_PROXY||process.env.HTTP_PROXY||process.env.https_proxy||process.env.http_proxy}function L(){let z=x();if(z)try{return new R(z)}catch(q){console.warn(`[proxyFetch] Invalid proxy URL: ${z}`)}return}async function F(z,q,Z){let{timeout:W=30000,signal:J,...Q}=q;if(J?.aborted)throw new DOMException("The operation was aborted.","AbortError");let Y=L(),$=new AbortController,w=!1,y=setTimeout(()=>{w=!0,$.abort()},W),T=()=>$.abort();J?.addEventListener("abort",T);let D;try{let B={method:Q.method,headers:Q.headers,body:Q.body,signal:$.signal,dispatcher:Y};return D=await k(z.toString(),B),await Z(D)}catch(B){if(B instanceof Error&&B.name==="AbortError"){if(w)throw Error(`Request timeout after ${W}ms`);throw B}throw B}finally{if(clearTimeout(y),J?.removeEventListener("abort",T),$.abort(),D?.body&&!D.body.locked)await D.body.cancel().catch(()=>{return});await Y?.destroy?.().catch(()=>{return})}}var O="blade-code",G="https://cdn.jsdelivr.net/npm/blade-code@latest/CHANGELOG.md",H=S.join(process.env.HOME||process.env.USERPROFILE||".",".blade"),N=S.join(H,"version-cache.json"),_=3600000,g=`https://registry.npmjs.org/${O}/latest`,M=null;async function P(){try{if(process.env.BLADE_VERSION)return process.env.BLADE_VERSION;return I()}catch{return"unknown"}}async function b(){try{let z=await j.readFile(N,"utf-8"),q=JSON.parse(z);if(Date.now()-q.checkedAt<_)return q;return{...q,checkedAt:0}}catch{return null}}async function K(z){try{await j.mkdir(H,{recursive:!0,mode:493}),await j.writeFile(N,JSON.stringify(z,null,2))}catch{}}async function E(){try{return await F(g,{timeout:5000,headers:{Accept:"application/json"}},async(z)=>{if(!z.ok)return null;let q=await z.json();if(!q||typeof q!=="object"||!("version"in q))return null;return typeof q.version==="string"&&X.valid(q.version)?q.version:null})}catch{return null}}async function A(z=!1){let q=await P(),Z=G;if(q==="unknown")return{currentVersion:q,latestVersion:null,hasUpdate:!1,shouldPrompt:!1,releaseNotesUrl:Z,error:"Unable to determine current version"};let W=await b(),J=W?.skipUntilVersion,Q=null;if(!z&&W?.latestVersion&&W.checkedAt>0)Q=W.latestVersion;else if(Q=await E(),J=(await b())?.skipUntilVersion??J,Q)await K({latestVersion:Q,checkedAt:Date.now(),skipUntilVersion:J});else if(W?.latestVersion)await K({checkedAt:0,skipUntilVersion:J});if(!Q||!X.valid(Q))return{currentVersion:q,latestVersion:null,hasUpdate:!1,shouldPrompt:!1,releaseNotesUrl:Z,error:"Unable to check for updates"};if(X.lt(Q,q))Q=q,await K({latestVersion:Q,checkedAt:Date.now(),skipUntilVersion:J});let Y=X.gt(Q,q),$=Y;if(Y&&J)$=X.gt(Q,J);return{currentVersion:q,latestVersion:Q,hasUpdate:Y,shouldPrompt:$,releaseNotesUrl:Z}}async function V(z){let q=await b();await K({latestVersion:q?.latestVersion??z,checkedAt:q?.checkedAt||Date.now(),skipUntilVersion:z})}function v(){return`npm install -g ${O}@latest --registry https://registry.npmjs.org`}async function p(){let{spawn:z}=await import("child_process");return new Promise((q)=>{let Z=v(),W=z(Z,{stdio:"inherit",shell:!0});W.on("close",(J)=>{if(J===0)q({success:!0,message:"Upgrade successful! Please restart blade."});else q({success:!1,message:`Upgrade failed (exit code: ${J})`})}),W.on("error",(J)=>{q({success:!1,message:`Upgrade failed: ${J.message}`})})})}async function h(){try{let z=await b();if(!z?.latestVersion||!X.valid(z.latestVersion)||!z.checkedAt){if(!M)M=A(!0).then(()=>{return},()=>{return}).finally(()=>{M=null});return null}let q=await P();if(!X.valid(q)||!X.gt(z.latestVersion,q)||z.skipUntilVersion&&X.valid(z.skipUntilVersion)&&!X.gt(z.latestVersion,z.skipUntilVersion))return null;return{currentVersion:q,latestVersion:z.latestVersion,hasUpdate:!0,shouldPrompt:!0,releaseNotesUrl:G}}catch{return null}}
2
2
  export{A as k,V as l,v as m,p as n,h as o};
@@ -1,4 +1,4 @@
1
- import{Ae as A0,Be as B1,Ce as H1,Ee as d2,Le as i2,Me as C0,Te as p_,Ve as N1,Xe as r2,Ye as o2,Ze as q1,_e as a2,ne as u2,oe as e,pe as h2,qe as Z1,re as l2,se as v,te as G1,ue as c2,ve as p2,we as V1,xe as L1,ye as n2,ze as U1}from"./chunk-q1rnvn85.js";import{ug as o_}from"./chunk-7wcxjbyg.js";import{qh as a_}from"./chunk-hv8nt7wj.js";import{Ui as v2,Vi as P2,Wi as x_,Xi as Q0,Yi as w_}from"./chunk-514va7ce.js";import{aj as f1}from"./chunk-jsv3e4k6.js";import{Cj as H0}from"./chunk-5q4z0sfr.js";import{Pj as i_,Sj as r_}from"./chunk-9kj19a8t.js";import{Wj as __}from"./chunk-7r26xgk4.js";import{Ak as A,Bk as P,Ck as I,Dk as E1,Ek as F1,Fk as M_,Gk as z1,Hk as b1,Ik as q_,ek as h,ok as o,pk as p,qk as S2,rk as n,sk as d,tk as I2,uk as K0,vk as Y1,wk as m2,xk as K_,yk as M0,zk as c_}from"./chunk-7xtxvrh8.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)}
1
+ import{Ae as A0,Be as B1,Ce as H1,Ee as d2,Le as i2,Me as C0,Te as p_,Ve as N1,Xe as r2,Ye as o2,Ze as q1,_e as a2,ne as u2,oe as e,pe as h2,qe as Z1,re as l2,se as v,te as G1,ue as c2,ve as p2,we as V1,xe as L1,ye as n2,ze as U1}from"./chunk-vz13c7fr.js";import{ug as o_}from"./chunk-7wcxjbyg.js";import{qh as a_}from"./chunk-hv8nt7wj.js";import{Ui as v2,Vi as P2,Wi as x_,Xi as Q0,Yi as w_}from"./chunk-514va7ce.js";import{aj as f1}from"./chunk-jsv3e4k6.js";import{Cj as H0}from"./chunk-5q4z0sfr.js";import{Pj as i_,Sj as r_}from"./chunk-9kj19a8t.js";import{Wj as __}from"./chunk-xh3bm0p0.js";import{Ak as A,Bk as P,Ck as I,Dk as E1,Ek as F1,Fk as M_,Gk as z1,Hk as b1,Ik as q_,ek as h,ok as o,pk as p,qk as S2,rk as n,sk as d,tk as I2,uk as K0,vk as Y1,wk as m2,xk as K_,yk as M0,zk as c_}from"./chunk-7xtxvrh8.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]...
@@ -1,4 +1,4 @@
1
- import{vf as v}from"./chunk-v67st2xb.js";import{Of as e}from"./chunk-8bm5bpa2.js";import{Bi as S,Ci as m,Di as c,Ei as p,Gi as u,Hi as d,Li as l,Qi as i,Ri as t,di as y,fi as D,gi as h,ii as A,pi as P,qi as T,si as E,ui as _,vi as f,xi as C}from"./chunk-eass9t33.js";import{Si as Y}from"./chunk-sd9bze9x.js";import{_i as X}from"./chunk-jsv3e4k6.js";import{cj as U,dj as L,jj as M,kj as O,mj as $,nj as I,oj as G,qj as N,rj as j,tj as F,uj as R}from"./chunk-n34qsnks.js";import{Cj as s,Ej as x,Gj as k,Jj as Z}from"./chunk-5q4z0sfr.js";import{promises as a}from"node:fs";import g from"node:path";var r=["systemPrompt","appendSystemPrompt","initialMessage","resumeSessionId","forkSession","allowedTools","disallowedTools","mcpConfigPaths","strictMcpConfig","model","addDirs","outputFormat","inputFormat","print","includePartialMessages","replayUserMessages","agentsConfig","settingSources"],kk=new Set([...Object.keys(l),...r,"providerRequestConcurrency","providerGlobalConcurrency","providerOwnerConcurrency"]),W=k.Number({exclusiveMinimum:0}),z=k.String({minLength:1}),b=k.Array(k.String()),qk=k.Object({currentModelId:k.Optional(k.String()),modelProviders:k.Optional(k.Record(z,k.Object({name:z,baseUrl:z,wireApi:Z(["openai-completions","anthropic-messages"]),apiKeyEnv:k.Optional(z)}))),models:k.Optional(k.Array(k.Object({id:z,displayName:k.Optional(z),provider:z,model:z,overrides:k.Optional(k.Object({baseUrl:k.Optional(k.String()),temperature:k.Optional(k.Number()),maxOutputTokens:k.Optional(W),timeout:k.Optional(W),streamIdleTimeout:k.Optional(k.Number({minimum:1000})),apiVersion:k.Optional(k.String()),customHeaders:k.Optional(k.Record(k.String(),k.String())),maxRetries:k.Optional(k.Integer({minimum:0})),enablePromptCaching:k.Optional(k.Boolean())})),fallbackModels:k.Optional(k.Array(k.Object({provider:z,model:z,configId:k.Optional(z)})))}))),temperature:k.Optional(k.Number()),maxOutputTokens:k.Optional(W),stream:k.Optional(k.Boolean()),topP:k.Optional(k.Number()),topK:k.Optional(k.Number()),timeout:k.Optional(W),bashForegroundHandoffMs:k.Optional(k.Union([k.Literal(0),k.Integer({minimum:P,maximum:T})])),providerForegroundRecoveryMs:k.Optional(k.Union([k.Literal(0),k.Integer({minimum:U,maximum:L})])),providerCircuitBreakerOpenMs:k.Optional(k.Union([k.Literal(0),k.Integer({minimum:M,maximum:O})])),providerRequestConcurrency:k.Optional(k.Integer({minimum:$,maximum:I})),providerGlobalConcurrency:k.Optional(k.Integer({minimum:$,maximum:G})),providerOwnerConcurrency:k.Optional(k.Integer({minimum:$,maximum:G})),providerRequestAdmissionMs:k.Optional(k.Union([k.Literal(0),k.Integer({minimum:N,maximum:j})])),providerRequestPendingBytes:k.Optional(k.Integer({minimum:F,maximum:R})),agentTeamsEnabled:k.Optional(k.Boolean()),codeTheme:k.Optional(k.String()),uiTheme:k.Optional(Z(["light","dark","system"])),language:k.Optional(k.String()),fontSize:k.Optional(W),autoSaveSessions:k.Optional(k.Boolean()),notifyBuild:k.Optional(k.Boolean()),notifyErrors:k.Optional(k.Boolean()),notifySounds:k.Optional(k.Boolean()),privacyTelemetry:k.Optional(k.Boolean()),privacyCrash:k.Optional(k.Boolean()),debug:k.Optional(k.Union([k.Boolean(),k.String()])),mcpEnabled:k.Optional(k.Boolean()),mcpServers:k.Optional(k.Record(k.String(),k.Record(k.String(),k.Unknown()))),lspServers:k.Optional(k.Record(z,k.Object({command:z,args:k.Optional(k.Array(k.String())),extensionToLanguage:k.Record(z,z),env:k.Optional(k.Record(k.String(),k.String())),initializationOptions:k.Optional(k.Unknown()),settings:k.Optional(k.Unknown()),enabled:k.Optional(k.Boolean()),priority:k.Optional(k.Integer()),startupTimeout:k.Optional(k.Integer({minimum:100})),shutdownTimeout:k.Optional(k.Integer({minimum:100})),requestTimeout:k.Optional(k.Integer({minimum:100})),diagnosticWaitTimeout:k.Optional(k.Integer({minimum:0})),maxRestarts:k.Optional(k.Integer({minimum:0,maximum:10}))}))),permissionMode:k.Optional(k.Enum(Y)),maxTurns:k.Optional(k.Integer({minimum:-1})),maxConcurrentTasks:k.Optional(k.Integer({minimum:S,maximum:m})),maxQueuedTasks:k.Optional(k.Integer({minimum:c,maximum:p})),maxQueuedTaskBytes:k.Optional(k.Integer({minimum:u,maximum:d})),maxResidentSessionRuntimes:k.Optional(k.Integer({minimum:E,maximum:_})),sessionRuntimeIdleMs:k.Optional(k.Integer({minimum:f,maximum:C})),maxResidentSessionProjections:k.Optional(k.Integer({minimum:y,maximum:D})),sessionProjectionIdleMs:k.Optional(k.Integer({minimum:h,maximum:A})),systemPrompt:k.Optional(k.String()),appendSystemPrompt:k.Optional(k.String()),initialMessage:k.Optional(k.String()),resumeSessionId:k.Optional(k.String()),forkSession:k.Optional(k.Boolean()),allowedTools:k.Optional(k.Array(z)),disallowedTools:k.Optional(k.Array(z)),mcpConfigPaths:k.Optional(k.Array(z)),strictMcpConfig:k.Optional(k.Boolean()),model:k.Optional(z),addDirs:k.Optional(k.Array(z)),outputFormat:k.Optional(Z(["text","json","stream-json","jsonl"])),inputFormat:k.Optional(Z(["text","stream-json"])),print:k.Optional(k.Boolean()),includePartialMessages:k.Optional(k.Boolean()),replayUserMessages:k.Optional(k.Boolean()),agentsConfig:k.Optional(k.String()),settingSources:k.Optional(k.String()),permissions:k.Optional(k.Object({allow:k.Optional(b),ask:k.Optional(b),deny:k.Optional(b)})),env:k.Optional(k.Record(k.String(),k.String())),hooks:k.Optional(k.Record(k.String(),k.Unknown())),enabledPlugins:k.Optional(k.Record(z,k.Boolean())),pluginSourcePolicy:k.Optional(k.Object({restrictToAllowedSources:k.Optional(k.Boolean()),requireGitCommitSha:k.Optional(k.Boolean()),allowedGitHosts:k.Optional(k.Array(z)),allowedMarketplaces:k.Optional(k.Array(z)),allowedLocalRoots:k.Optional(k.Array(z))})),disableAllHooks:k.Optional(k.Boolean())}),wk=[["systemPrompt","systemPrompt"],["appendSystemPrompt","appendSystemPrompt"],["initialMessage","initialMessage"],["resumeSessionId","sessionId"],["forkSession","forkSession"],["allowedTools","allowedTools"],["disallowedTools","disallowedTools"],["mcpConfigPaths","mcpConfig"],["strictMcpConfig","strictMcpConfig"],["model","model"],["addDirs","addDir"],["outputFormat","outputFormat"],["inputFormat","inputFormat"],["print","print"],["includePartialMessages","includePartialMessages"],["replayUserMessages","replayUserMessages"],["agentsConfig","agents"],["settingSources","settingSources"],["permissionMode","permissionMode"],["maxTurns","maxTurns"],["maxConcurrentTasks","maxConcurrentTasks"],["maxQueuedTasks","maxQueuedTasks"],["maxQueuedTaskBytes","maxQueuedTaskBytes"],["maxResidentSessionRuntimes","maxResidentSessionRuntimes"],["sessionRuntimeIdleMs","sessionRuntimeIdleMs"],["maxResidentSessionProjections","maxResidentSessionProjections"],["sessionProjectionIdleMs","sessionProjectionIdleMs"]];function V(q,B){let w;try{w=JSON.parse(q)}catch(H){let K=H instanceof Error?`: ${H.message}`:"";throw Error(`Invalid JSON provided to --settings (${B})${K}`)}if(!w||typeof w!=="object"||Array.isArray(w))throw Error("--settings must contain a JSON object");for(let H of Object.keys(w))if(!kk.has(H))throw Error(`Unknown --settings field: ${H}`);let J=x(qk,w);if(!J.success){let H=J.error.issues.map((K)=>`${K.path.join(".")||"settings"}: ${K.message}`).join("; ");throw Error(`Invalid --settings value: ${H}`)}return J.data}async function n(q){if(q===void 0)return;let B=q.trim();if(!B)throw Error("--settings requires a JSON object or file path");if(B.startsWith("{"))return V(B,"inline JSON");let w=g.resolve(X(),B),J;try{J=await a.readFile(w,"utf8")}catch(H){let K=H instanceof Error?`: ${H.message}`:"";throw Error(`Unable to read --settings file ${w}${K}`)}return V(J,w)}function o(q,B){if(!B)return;let w=B;for(let[J,H]of wk){if(J==="permissionMode"&&q.yolo===!0)continue;if(q[H]===void 0&&w[J]!==void 0)q[H]=w[J]}}var Q=s("General"),Uk=(q)=>{if(q.yolo){if(q.permissionMode&&q.permissionMode!=="yolo")throw Error("Cannot use both --yolo and --permission-mode with different values");q.permissionMode="yolo"}if(Array.isArray(q.allowedTools))q.allowedTools=q.allowedTools.flatMap((B)=>B.split(",").map((w)=>w.trim()).filter((w)=>w.length>0));if(Array.isArray(q.disallowedTools))q.disallowedTools=q.disallowedTools.flatMap((B)=>B.split(",").map((w)=>w.trim()).filter((w)=>w.length>0));if(Array.isArray(q.allowedTools)&&Array.isArray(q.disallowedTools)){let B=q.allowedTools.filter((w)=>q.disallowedTools.includes(w));if(B.length>0)throw Error(`Tools cannot be both allowed and disallowed: ${B.join(", ")}`)}},Lk=async(q)=>{let B=await n(typeof q.settings==="string"?q.settings:void 0);if(o(q,B),typeof q.agents==="string")v(q.agents);zk(q);try{let J=await i.getInstance().initialize(B),H=t(J,q);if(e().config.actions.setConfig(H),q.debug)Q.info("[CLI] 配置已加载到 Store")}catch(w){Q.error("[CLI] [FAIL] 配置初始化失败",w instanceof Error?w.message:w),console.error(`
1
+ import{vf as v}from"./chunk-v67st2xb.js";import{Of as e}from"./chunk-pnfeyw0g.js";import{Bi as S,Ci as m,Di as c,Ei as p,Gi as u,Hi as d,Li as l,Qi as i,Ri as t,di as y,fi as D,gi as h,ii as A,pi as P,qi as T,si as E,ui as _,vi as f,xi as C}from"./chunk-4gsjcz7t.js";import{Si as Y}from"./chunk-sd9bze9x.js";import{_i as X}from"./chunk-jsv3e4k6.js";import{cj as U,dj as L,jj as M,kj as O,mj as $,nj as I,oj as G,qj as N,rj as j,tj as F,uj as R}from"./chunk-n34qsnks.js";import{Cj as s,Ej as x,Gj as k,Jj as Z}from"./chunk-5q4z0sfr.js";import{promises as a}from"node:fs";import g from"node:path";var r=["systemPrompt","appendSystemPrompt","initialMessage","resumeSessionId","forkSession","allowedTools","disallowedTools","mcpConfigPaths","strictMcpConfig","model","addDirs","outputFormat","inputFormat","print","includePartialMessages","replayUserMessages","agentsConfig","settingSources"],kk=new Set([...Object.keys(l),...r,"providerRequestConcurrency","providerGlobalConcurrency","providerOwnerConcurrency"]),W=k.Number({exclusiveMinimum:0}),z=k.String({minLength:1}),b=k.Array(k.String()),qk=k.Object({currentModelId:k.Optional(k.String()),modelProviders:k.Optional(k.Record(z,k.Object({name:z,baseUrl:z,wireApi:Z(["openai-completions","anthropic-messages"]),apiKeyEnv:k.Optional(z)}))),models:k.Optional(k.Array(k.Object({id:z,displayName:k.Optional(z),provider:z,model:z,overrides:k.Optional(k.Object({baseUrl:k.Optional(k.String()),temperature:k.Optional(k.Number()),maxOutputTokens:k.Optional(W),timeout:k.Optional(W),streamIdleTimeout:k.Optional(k.Number({minimum:1000})),apiVersion:k.Optional(k.String()),customHeaders:k.Optional(k.Record(k.String(),k.String())),maxRetries:k.Optional(k.Integer({minimum:0})),enablePromptCaching:k.Optional(k.Boolean())})),fallbackModels:k.Optional(k.Array(k.Object({provider:z,model:z,configId:k.Optional(z)})))}))),temperature:k.Optional(k.Number()),maxOutputTokens:k.Optional(W),stream:k.Optional(k.Boolean()),topP:k.Optional(k.Number()),topK:k.Optional(k.Number()),timeout:k.Optional(W),bashForegroundHandoffMs:k.Optional(k.Union([k.Literal(0),k.Integer({minimum:P,maximum:T})])),providerForegroundRecoveryMs:k.Optional(k.Union([k.Literal(0),k.Integer({minimum:U,maximum:L})])),providerCircuitBreakerOpenMs:k.Optional(k.Union([k.Literal(0),k.Integer({minimum:M,maximum:O})])),providerRequestConcurrency:k.Optional(k.Integer({minimum:$,maximum:I})),providerGlobalConcurrency:k.Optional(k.Integer({minimum:$,maximum:G})),providerOwnerConcurrency:k.Optional(k.Integer({minimum:$,maximum:G})),providerRequestAdmissionMs:k.Optional(k.Union([k.Literal(0),k.Integer({minimum:N,maximum:j})])),providerRequestPendingBytes:k.Optional(k.Integer({minimum:F,maximum:R})),agentTeamsEnabled:k.Optional(k.Boolean()),codeTheme:k.Optional(k.String()),uiTheme:k.Optional(Z(["light","dark","system"])),language:k.Optional(k.String()),fontSize:k.Optional(W),autoSaveSessions:k.Optional(k.Boolean()),notifyBuild:k.Optional(k.Boolean()),notifyErrors:k.Optional(k.Boolean()),notifySounds:k.Optional(k.Boolean()),privacyTelemetry:k.Optional(k.Boolean()),privacyCrash:k.Optional(k.Boolean()),debug:k.Optional(k.Union([k.Boolean(),k.String()])),mcpEnabled:k.Optional(k.Boolean()),mcpServers:k.Optional(k.Record(k.String(),k.Record(k.String(),k.Unknown()))),lspServers:k.Optional(k.Record(z,k.Object({command:z,args:k.Optional(k.Array(k.String())),extensionToLanguage:k.Record(z,z),env:k.Optional(k.Record(k.String(),k.String())),initializationOptions:k.Optional(k.Unknown()),settings:k.Optional(k.Unknown()),enabled:k.Optional(k.Boolean()),priority:k.Optional(k.Integer()),startupTimeout:k.Optional(k.Integer({minimum:100})),shutdownTimeout:k.Optional(k.Integer({minimum:100})),requestTimeout:k.Optional(k.Integer({minimum:100})),diagnosticWaitTimeout:k.Optional(k.Integer({minimum:0})),maxRestarts:k.Optional(k.Integer({minimum:0,maximum:10}))}))),permissionMode:k.Optional(k.Enum(Y)),maxTurns:k.Optional(k.Integer({minimum:-1})),maxConcurrentTasks:k.Optional(k.Integer({minimum:S,maximum:m})),maxQueuedTasks:k.Optional(k.Integer({minimum:c,maximum:p})),maxQueuedTaskBytes:k.Optional(k.Integer({minimum:u,maximum:d})),maxResidentSessionRuntimes:k.Optional(k.Integer({minimum:E,maximum:_})),sessionRuntimeIdleMs:k.Optional(k.Integer({minimum:f,maximum:C})),maxResidentSessionProjections:k.Optional(k.Integer({minimum:y,maximum:D})),sessionProjectionIdleMs:k.Optional(k.Integer({minimum:h,maximum:A})),systemPrompt:k.Optional(k.String()),appendSystemPrompt:k.Optional(k.String()),initialMessage:k.Optional(k.String()),resumeSessionId:k.Optional(k.String()),forkSession:k.Optional(k.Boolean()),allowedTools:k.Optional(k.Array(z)),disallowedTools:k.Optional(k.Array(z)),mcpConfigPaths:k.Optional(k.Array(z)),strictMcpConfig:k.Optional(k.Boolean()),model:k.Optional(z),addDirs:k.Optional(k.Array(z)),outputFormat:k.Optional(Z(["text","json","stream-json","jsonl"])),inputFormat:k.Optional(Z(["text","stream-json"])),print:k.Optional(k.Boolean()),includePartialMessages:k.Optional(k.Boolean()),replayUserMessages:k.Optional(k.Boolean()),agentsConfig:k.Optional(k.String()),settingSources:k.Optional(k.String()),permissions:k.Optional(k.Object({allow:k.Optional(b),ask:k.Optional(b),deny:k.Optional(b)})),env:k.Optional(k.Record(k.String(),k.String())),hooks:k.Optional(k.Record(k.String(),k.Unknown())),enabledPlugins:k.Optional(k.Record(z,k.Boolean())),pluginSourcePolicy:k.Optional(k.Object({restrictToAllowedSources:k.Optional(k.Boolean()),requireGitCommitSha:k.Optional(k.Boolean()),allowedGitHosts:k.Optional(k.Array(z)),allowedMarketplaces:k.Optional(k.Array(z)),allowedLocalRoots:k.Optional(k.Array(z))})),disableAllHooks:k.Optional(k.Boolean())}),wk=[["systemPrompt","systemPrompt"],["appendSystemPrompt","appendSystemPrompt"],["initialMessage","initialMessage"],["resumeSessionId","sessionId"],["forkSession","forkSession"],["allowedTools","allowedTools"],["disallowedTools","disallowedTools"],["mcpConfigPaths","mcpConfig"],["strictMcpConfig","strictMcpConfig"],["model","model"],["addDirs","addDir"],["outputFormat","outputFormat"],["inputFormat","inputFormat"],["print","print"],["includePartialMessages","includePartialMessages"],["replayUserMessages","replayUserMessages"],["agentsConfig","agents"],["settingSources","settingSources"],["permissionMode","permissionMode"],["maxTurns","maxTurns"],["maxConcurrentTasks","maxConcurrentTasks"],["maxQueuedTasks","maxQueuedTasks"],["maxQueuedTaskBytes","maxQueuedTaskBytes"],["maxResidentSessionRuntimes","maxResidentSessionRuntimes"],["sessionRuntimeIdleMs","sessionRuntimeIdleMs"],["maxResidentSessionProjections","maxResidentSessionProjections"],["sessionProjectionIdleMs","sessionProjectionIdleMs"]];function V(q,B){let w;try{w=JSON.parse(q)}catch(H){let K=H instanceof Error?`: ${H.message}`:"";throw Error(`Invalid JSON provided to --settings (${B})${K}`)}if(!w||typeof w!=="object"||Array.isArray(w))throw Error("--settings must contain a JSON object");for(let H of Object.keys(w))if(!kk.has(H))throw Error(`Unknown --settings field: ${H}`);let J=x(qk,w);if(!J.success){let H=J.error.issues.map((K)=>`${K.path.join(".")||"settings"}: ${K.message}`).join("; ");throw Error(`Invalid --settings value: ${H}`)}return J.data}async function n(q){if(q===void 0)return;let B=q.trim();if(!B)throw Error("--settings requires a JSON object or file path");if(B.startsWith("{"))return V(B,"inline JSON");let w=g.resolve(X(),B),J;try{J=await a.readFile(w,"utf8")}catch(H){let K=H instanceof Error?`: ${H.message}`:"";throw Error(`Unable to read --settings file ${w}${K}`)}return V(J,w)}function o(q,B){if(!B)return;let w=B;for(let[J,H]of wk){if(J==="permissionMode"&&q.yolo===!0)continue;if(q[H]===void 0&&w[J]!==void 0)q[H]=w[J]}}var Q=s("General"),Uk=(q)=>{if(q.yolo){if(q.permissionMode&&q.permissionMode!=="yolo")throw Error("Cannot use both --yolo and --permission-mode with different values");q.permissionMode="yolo"}if(Array.isArray(q.allowedTools))q.allowedTools=q.allowedTools.flatMap((B)=>B.split(",").map((w)=>w.trim()).filter((w)=>w.length>0));if(Array.isArray(q.disallowedTools))q.disallowedTools=q.disallowedTools.flatMap((B)=>B.split(",").map((w)=>w.trim()).filter((w)=>w.length>0));if(Array.isArray(q.allowedTools)&&Array.isArray(q.disallowedTools)){let B=q.allowedTools.filter((w)=>q.disallowedTools.includes(w));if(B.length>0)throw Error(`Tools cannot be both allowed and disallowed: ${B.join(", ")}`)}},Lk=async(q)=>{let B=await n(typeof q.settings==="string"?q.settings:void 0);if(o(q,B),typeof q.agents==="string")v(q.agents);zk(q);try{let J=await i.getInstance().initialize(B),H=t(J,q);if(e().config.actions.setConfig(H),q.debug)Q.info("[CLI] 配置已加载到 Store")}catch(w){Q.error("[CLI] [FAIL] 配置初始化失败",w instanceof Error?w.message:w),console.error(`
2
2
  [FAIL] 配置初始化失败
3
3
  `),console.error("原因:",w instanceof Error?w.message:"未知错误"),console.error(`
4
4
  请检查:`),console.error(" 1. 配置文件格式是否正确 (~/.blade/config.json)"),console.error(" 2. 是否需要运行 blade 进行首次配置"),console.error(` 3. 配置文件权限是否正确
@@ -1,4 +1,4 @@
1
- import{ah as j1,bh as K0,ch as F1}from"./chunk-ewwrss2w.js";import{ih as w0}from"./chunk-53vh6vpt.js";import{rh as YO,sh as L1}from"./chunk-hv8nt7wj.js";import{vh as I1}from"./chunk-erhaedch.js";import{wh as B0,yh as $0}from"./chunk-ra0y5drh.js";import{Li as S0,Mi as $O,Qi as I0}from"./chunk-eass9t33.js";import{aj as B}from"./chunk-jsv3e4k6.js";import{Cj as P,Dj as j,Ej as p,Gj as q,Jj as k1}from"./chunk-5q4z0sfr.js";import{Wj as k0}from"./chunk-7r26xgk4.js";import{bk as D}from"./chunk-gm2yfq3r.js";import{yk as t1}from"./chunk-7xtxvrh8.js";import T0 from"node:path";import QO from"node:path";import C0 from"node:fs";import L0 from"node:os";import w from"node:path";import RO from"yaml";var G1=2000,W1=50,Y1=1000,O4={type:"object",properties:{verdict:{type:"string",enum:["pass","fail","partial"]},summary:{type:"string",minLength:1,maxLength:G1},findings:{type:"array",maxItems:W1,items:{type:"string",minLength:1,maxLength:Y1}}},required:["verdict","summary","findings"],additionalProperties:!1};function q1(O,$){let Q=O.trim().replaceAll(/\s+/g," ");if($)Q=Q.replaceAll($,".");return Q.replace(/\bBearer\s+[^\s"'`]+/gi,"Bearer [redacted]").replace(/\bsk-[A-Za-z0-9_-]{8,}\b/g,"[redacted-key]").replace(/\b(api(?:[_-]?|\s+)key|access(?:[_-]?|\s+)token|authorization|cookie|password|passwd|refresh(?:[_-]?|\s+)token|secret|session(?:[_-]?|\s+)token)\b(\s*[:=]\s*)([^\s,;]+)/gi,"$1$2[redacted]")}function NO(O){if(O.length<=w0)return O;let $=" [verification feedback truncated]",Q=O.slice(0,w0-$.length);if(/[\uD800-\uDBFF]$/.test(Q))Q=Q.slice(0,-1);return Q.trimEnd()+$}function X1(O){if(!O||typeof O!=="object"||Array.isArray(O))return;let $=O;if($.verdict!=="pass"&&$.verdict!=="fail"&&$.verdict!=="partial"||typeof $.summary!=="string"||!$.summary.trim()||$.summary.length>G1||!Array.isArray($.findings)||$.findings.length>W1||!$.findings.every((Q)=>typeof Q==="string"&&Q.trim().length>0&&Q.length<=Y1))return;return{verdict:$.verdict,summary:$.summary.trim(),findings:$.findings.map((Q)=>Q.trim())}}function $4(O,$){let Q=X1(O);if(!Q)return;let Z=q1(Q.summary,$),J=Q.findings.map((L)=>q1(L,$));return NO([Z,J.length>0?`Findings:
1
+ import{ah as j1,bh as K0,ch as F1}from"./chunk-ewwrss2w.js";import{ih as w0}from"./chunk-53vh6vpt.js";import{rh as YO,sh as L1}from"./chunk-hv8nt7wj.js";import{vh as I1}from"./chunk-erhaedch.js";import{wh as B0,yh as $0}from"./chunk-v7b7dx9j.js";import{Li as S0,Mi as $O,Qi as I0}from"./chunk-4gsjcz7t.js";import{aj as B}from"./chunk-jsv3e4k6.js";import{Cj as P,Dj as j,Ej as p,Gj as q,Jj as k1}from"./chunk-5q4z0sfr.js";import{Wj as k0}from"./chunk-xh3bm0p0.js";import{bk as D}from"./chunk-gm2yfq3r.js";import{yk as t1}from"./chunk-7xtxvrh8.js";import T0 from"node:path";import QO from"node:path";import C0 from"node:fs";import L0 from"node:os";import w from"node:path";import RO from"yaml";var G1=2000,W1=50,Y1=1000,O4={type:"object",properties:{verdict:{type:"string",enum:["pass","fail","partial"]},summary:{type:"string",minLength:1,maxLength:G1},findings:{type:"array",maxItems:W1,items:{type:"string",minLength:1,maxLength:Y1}}},required:["verdict","summary","findings"],additionalProperties:!1};function q1(O,$){let Q=O.trim().replaceAll(/\s+/g," ");if($)Q=Q.replaceAll($,".");return Q.replace(/\bBearer\s+[^\s"'`]+/gi,"Bearer [redacted]").replace(/\bsk-[A-Za-z0-9_-]{8,}\b/g,"[redacted-key]").replace(/\b(api(?:[_-]?|\s+)key|access(?:[_-]?|\s+)token|authorization|cookie|password|passwd|refresh(?:[_-]?|\s+)token|secret|session(?:[_-]?|\s+)token)\b(\s*[:=]\s*)([^\s,;]+)/gi,"$1$2[redacted]")}function NO(O){if(O.length<=w0)return O;let $=" [verification feedback truncated]",Q=O.slice(0,w0-$.length);if(/[\uD800-\uDBFF]$/.test(Q))Q=Q.slice(0,-1);return Q.trimEnd()+$}function X1(O){if(!O||typeof O!=="object"||Array.isArray(O))return;let $=O;if($.verdict!=="pass"&&$.verdict!=="fail"&&$.verdict!=="partial"||typeof $.summary!=="string"||!$.summary.trim()||$.summary.length>G1||!Array.isArray($.findings)||$.findings.length>W1||!$.findings.every((Q)=>typeof Q==="string"&&Q.trim().length>0&&Q.length<=Y1))return;return{verdict:$.verdict,summary:$.summary.trim(),findings:$.findings.map((Q)=>Q.trim())}}function $4(O,$){let Q=X1(O);if(!Q)return;let Z=q1(Q.summary,$),J=Q.findings.map((L)=>q1(L,$));return NO([Z,J.length>0?`Findings:
2
2
  ${J.map((L)=>`- ${L}`).join(`
3
3
  `)}`:""].filter(Boolean).join(`
4
4