blade-code 0.11.3 → 0.11.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/blade.js +2 -2
- package/dist/{chunk-g0xtk1yy.js → chunk-1g7c3f82.js} +1 -1
- package/dist/chunk-1hknjamx.js +1 -0
- package/dist/{chunk-5qrw9g8c.js → chunk-3gbteqvh.js} +1 -1
- package/dist/{chunk-q6sr4979.js → chunk-3v9epq9s.js} +1 -1
- package/dist/{chunk-gqypt03h.js → chunk-4077g2fm.js} +1 -1
- package/dist/{chunk-nvj4da2w.js → chunk-49jbxty9.js} +1 -1
- package/dist/{chunk-prqtwzxd.js → chunk-5ce8ydjq.js} +1 -1
- package/dist/{chunk-dv5ts9ae.js → chunk-5kmxe14c.js} +1 -1
- package/dist/{chunk-cmpxdek8.js → chunk-6m81sxfz.js} +1 -1
- package/dist/chunk-6p0hkf4f.js +1 -0
- package/dist/{chunk-yeandcre.js → chunk-77n1drhv.js} +1 -1
- package/dist/{chunk-hzz27w5w.js → chunk-7m07qp5c.js} +1 -1
- package/dist/{chunk-6v23hdt8.js → chunk-870szc6v.js} +1 -1
- package/dist/{chunk-v0eanse2.js → chunk-8d8wsqam.js} +1 -1
- package/dist/{chunk-b8hm4td5.js → chunk-a1vvg4yf.js} +1 -1
- package/dist/{chunk-px45q235.js → chunk-asgmmaec.js} +2 -2
- package/dist/{chunk-n30najxq.js → chunk-b5cz00mt.js} +1 -1
- package/dist/{chunk-33w0b9r4.js → chunk-bw3920qg.js} +1 -1
- package/dist/chunk-c33wff11.js +2 -0
- package/dist/chunk-d7frbjn7.js +1 -0
- package/dist/{chunk-jbpasjg9.js → chunk-e0ft3vwg.js} +1 -1
- package/dist/{chunk-crbt25b4.js → chunk-e4q0rcmz.js} +1 -1
- package/dist/chunk-eb10zapp.js +1 -0
- package/dist/{chunk-a95jmx2j.js → chunk-ed2hdrwe.js} +1 -1
- package/dist/{chunk-g2295k8s.js → chunk-eexs73bz.js} +1 -1
- package/dist/{chunk-mqfayxf7.js → chunk-egqep8py.js} +2 -2
- package/dist/chunk-g2kqz1mm.js +1 -0
- package/dist/{chunk-sdapqhj0.js → chunk-gmpsfkgg.js} +1 -1
- package/dist/chunk-gwf872nm.js +1 -0
- package/dist/{chunk-p36k2e96.js → chunk-hb680ebj.js} +1 -1
- package/dist/{chunk-faedrfhd.js → chunk-hbkpavbp.js} +1 -1
- package/dist/{chunk-b3kvf23h.js → chunk-hfbw50pk.js} +2 -2
- package/dist/{chunk-ffq1k7q5.js → chunk-hfwn38rm.js} +1 -1
- package/dist/{chunk-kdtj92em.js → chunk-js7fre4w.js} +1 -1
- package/dist/chunk-kj20ad32.js +1 -0
- package/dist/chunk-m61cx42n.js +1 -0
- package/dist/{chunk-qvew5nk3.js → chunk-myznexy5.js} +1 -1
- package/dist/chunk-n62b30d1.js +164 -0
- package/dist/{chunk-wnzr9h84.js → chunk-nad5spvc.js} +1 -1
- package/dist/{chunk-0pcrccgp.js → chunk-nfdtrn3t.js} +1 -1
- package/dist/{chunk-zc8erdkc.js → chunk-p4j7gxjk.js} +1 -1
- package/dist/{chunk-r9nyzqzb.js → chunk-phch3t6v.js} +77 -77
- package/dist/{chunk-3rxs9vxm.js → chunk-q534f3j5.js} +1 -1
- package/dist/{chunk-t0swttvj.js → chunk-qzsmbk13.js} +2 -2
- package/dist/chunk-r8rvkas8.js +1 -0
- package/dist/{chunk-qy6p8bpr.js → chunk-r9egmztq.js} +1 -1
- package/dist/{chunk-s3pnhdqk.js → chunk-rswfbvay.js} +1 -1
- package/dist/{chunk-x2crj6jq.js → chunk-rwm2e0r4.js} +1 -1
- package/dist/{chunk-wan9q99y.js → chunk-s14zayxp.js} +1 -1
- package/dist/{chunk-4e4qtpca.js → chunk-saz6mwpq.js} +1 -1
- package/dist/{chunk-0759ckbc.js → chunk-ty3gwnwq.js} +1 -1
- package/dist/{chunk-kb4hwa5a.js → chunk-v5t3kcac.js} +1 -1
- package/dist/{chunk-mmpcq1yh.js → chunk-vmhcc7f9.js} +1 -1
- package/dist/{chunk-nts19h6v.js → chunk-vsmnzhhz.js} +1 -1
- package/dist/{chunk-45xdp95z.js → chunk-vv6r417h.js} +1 -1
- package/dist/{chunk-dyf12wbv.js → chunk-w8dxjbm8.js} +1 -1
- package/dist/{chunk-r5svk833.js → chunk-whxkwaz1.js} +1 -1
- package/dist/{chunk-5s2x98rx.js → chunk-xhwdac1j.js} +1 -1
- package/dist/chunk-ydtsh19k.js +1 -0
- package/dist/{chunk-0wxnrjes.js → chunk-yjdyzb5z.js} +1 -1
- package/package.json +2 -2
- package/dist/chunk-3d4wgfkr.js +0 -1
- package/dist/chunk-7p8r4q6f.js +0 -1
- package/dist/chunk-b7pn03pb.js +0 -1
- package/dist/chunk-fa5sebe2.js +0 -1
- package/dist/chunk-fnvh22vc.js +0 -1
- package/dist/chunk-gfhb2h6z.js +0 -1
- package/dist/chunk-hn2p1296.js +0 -1
- package/dist/chunk-hnnhpv75.js +0 -1
- package/dist/chunk-jm1chm6x.js +0 -171
- package/dist/chunk-pbckwd41.js +0 -2
- package/dist/chunk-sqsfztrv.js +0 -1
- package/dist/chunk-yw3achrm.js +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{Bc as b4}from"./chunk-9qxch6sy.js";import{Ad as f2,Bd as k2,Cc as D$,Cd as w6,Dd as U6,Ec as j$,Fc as S2,Gc as r1,Ic as H$,Jd as M2,Kd as A4,Ld as E4,Md as V6,Nd as e1,Od as S4,Pd as T4,Qd as d1,Ud as sJ,ae as i2,ce as h0,ee as k6,fe as o1,ge as M6,ne as W1,yd as T2}from"./chunk-faedrfhd.js";import{se as y4}from"./chunk-skktstg8.js";import{Ke as q0,Le as c2,ve as F0,ye as U2,ze as s1}from"./chunk-wan9q99y.js";import{fg as n2}from"./chunk-x6k5ye1z.js";import{gg as N4,hg as x0,ig as G4,jg as rJ,lg as u1,mg as f6,ng as nJ,og as oJ,rg as aJ}from"./chunk-g0xtk1yy.js";import{ch as Z$,dh as c0,gh as _4}from"./chunk-kehgewqh.js";import{lh as Y4,ph as H2}from"./chunk-kkzznz4w.js";import{Ah as T$}from"./chunk-mqfayxf7.js";import{Ih as M$}from"./chunk-qy6p8bpr.js";import{Zi as H0}from"./chunk-b22ab7yw.js";import{Ej as G0}from"./chunk-4e4qtpca.js";import{Yj as E2}from"./chunk-pbckwd41.js";import{Bk as NJ,Ck as y2,Ek as b2,Jk as A2,fk as _2,uk as q2,vk as F2,yk as fJ}from"./chunk-a95jmx2j.js";import{Lk as dZ}from"./chunk-sdapqhj0.js";function A$($){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 x1{systemMessages;_contextualSystemMessages;_history;_pending=[];_contextRevision=0;context;constructor($,Z){this.context=$;let J=$.messages.find(A$);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)=>!A$(W)&&!b$(W))}get historyLength(){return this._history.length}get pending(){return this._pending}get contextRevision(){return this._contextRevision}toLLMMessages(){return[...this.systemMessages,...this._history,...this._pending]}getHistory(){return this._history}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(A$);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:{},...q0}})}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)=>!A$(Z)&&!b$(Z)),this._contextRevision++}restoreDurableHistory($){this._contextualSystemMessages=$.filter(b$),this._history=$.filter((Z)=>!A$(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]}}function JJ($){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 WJ($){return{budget:$.budget,usage:0,consecutiveContinuations:0,lastOutputDelta:0,isSubagent:$.isSubagent??!1}}function YJ($,Z,J){return{...$,usage:$.usage+Z,lastOutputDelta:Z,consecutiveContinuations:J?$.consecutiveContinuations+1:0}}import X$ from"node:path";var g4=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"]),m4=/^(LD_.+|DYLD_.+|PATH)$/,KJ=/^([A-Za-z_][A-Za-z0-9_]*)=([\w./:@-]*)$/;function e$($){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(KJ);if(!K)break;let Q=K[1];if(!g4.has(Q))break;Z=Y}return Z}function jW($){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(KJ);if(!K)break;let Q=K[1];if(m4.test(Q))break;Z=Y}return Z}var u4=[/^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 MZ($){let Z=$,J=!0;while(J){J=!1;for(let W of u4){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 $1($){let Z=[],J="",W=!1,Y=!1,K=!1;for(let Q=0;Q<$.length;Q++){let X=$[Q];if(K){J+=X,K=!1;continue}if(X==="\\"&&!W){J+=X,K=!0;continue}if(X==="'"&&!Y){W=!W,J+=X;continue}if(X==='"'&&!W){Y=!Y,J+=X;continue}if(W||Y){J+=X;continue}if(X==="|"){if(Q+1<$.length&&$[Q+1]==="|"){if(J.trim())Z.push(J.trim());J="",Q++;continue}return null}if(X===">"||X==="<")return null;if(X==="&"&&Q+1<$.length&&$[Q+1]==="&"){if(J.trim())Z.push(J.trim());J="",Q++;continue}if(X==="&")return null;if(X===";"){if(J.trim())Z.push(J.trim());J="";continue}J+=X}if(J.trim())Z.push(J.trim());return Z.length>0?Z:null}function QJ($){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 Q=$[Y+1];if(Q&&/[A-Za-z_@*#?!$0-9({]/.test(Q))return!0}if(K==="`")return!0;if(J)continue;if(K==="|")return!0;if(K===">"||K==="<")return!0;if(K==="{"){let Q=$.slice(Y);if(/^\{[^}]*,[^}]*\}/.test(Q)||/^\{[^}]*\.\.[^}]*\}/.test(Q))return!0}}return!1}function Q$($){let Z=[],J="",W=!1,Y=!1,K=!1;for(let Q=0;Q<$.length;Q++){let X=$[Q];if(K){J+=X,K=!1;continue}if(X==="\\"&&!W){if(K=!0,Y){let H=$[Q+1];if(H&&'$`"\\'.includes(H))continue;J+=X,K=!1}continue}if(X==="'"&&!Y){W=!W;continue}if(X==='"'&&!W){Y=!Y;continue}if(!W&&!Y&&/[ \t]/.test(X)){if(J)Z.push(J),J="";continue}J+=X}if(J)Z.push(J);return Z}var d4=new Set(["npm","pnpm","yarn","bun"]),XJ=new Set(["biome","eslint","jest","mypy","pyright","pytest","ruff","tsc","vitest"]),c4=new Set(["-u","--fix","--update","--update-snapshot","--updateSnapshot","--watch","--watchAll","--write"]),i4=/[ \t]*;[ \t]*echo[ \t]+"[A-Za-z0-9 _:=.-]*(?:\$\{PIPESTATUS\[0\]\}|\$\?)[A-Za-z0-9 _:=.-]*"[ \t]*$/;function l4($){return $!==void 0&&/^(?:test|lint|build|type-?check)(?::[\w.-]+)*$/i.test($)}function HJ($){return $.replace(/\s+2>&1\s*$/,"").trim()}function r4($,Z,J){if(!J||Z.length!==2)return;let W=/^(.+?)[ \t]+&&[ \t]+([\s\S]+)$/.exec($);if(!W)return;let Y=Q$(W[1]??"");if(Y.length!==2||Y[0]!=="cd")return;let K=Y[1];if(!K||K==="-")return;let Q=X$.isAbsolute(K)?X$.resolve(K):X$.resolve(J,K);if(!H$.isWithinWorkspace(Q,J))return;return W[2]?.trim()||void 0}function n4($){let Z=[],J=!1,W=!1,Y=!1;for(let K=0;K<$.length;K++){let Q=$[K];if(Y){Y=!1;continue}if(Q==="\\"&&!J){Y=!0;continue}if(Q==="'"&&!W){J=!J;continue}if(Q==='"'&&!J){W=!W;continue}if(Q!=="|"||J||W)continue;if($[K+1]==="|")return;Z.push(K)}return Z}function o4($){let Z=Q$($),[J,W,Y]=Z;if(J!=="head"&&J!=="tail")return!1;if(Z.length===1)return!0;let K=(Q)=>Q!==void 0&&/^[1-9]\d{0,4}$/.test(Q);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 a4($){let Z=HJ($.replace(i4,"").trim()),J=n4(Z);if(!J)return;if(J.length===0)return VJ(Z);if(J.length!==1)return;let W=J[0];if(W===void 0)return;let Y=HJ(Z.slice(0,W).trim()),K=Z.slice(W+1).trim();if(!Y||!o4(K))return;return VJ(Y)}function VJ($){let J=$1($)?.at(-1);if(!J)return $;let W=Q$(J),[Y,K]=W;if(!(Y==="vitest"||(Y==="npx"||Y==="bunx")&&K==="vitest")||W.some((X)=>X==="--configLoader"||X.startsWith("--configLoader=")))return $;return`${$} --configLoader runner`}function E$($,Z){let J=a4($);if(!J)return!1;let W=e$(J),Y=$1(W);if(!Y||QJ(W)||/[\r\n]/.test(W))return!1;let K=Y.length===1?Y[0]:r4(W,Y,Z);if(!K)return!1;let Q=Q$(K);if(Q.length===0||Q.some((V)=>[...c4].some((j)=>V===j||V.startsWith(`${j}=`))))return!1;let[X,H,z]=Q;if(d4.has(X??""))return l4(H==="run"?z:H)||H==="--test";if((X==="npx"||X==="bunx")&&XJ.has(H??""))return!0;if(XJ.has(X??""))return!0;if(X==="node"&&H==="--test")return!0;if(X==="go"&&["build","test","vet"].includes(H??""))return!0;return X==="cargo"&&["build","check","clippy","test"].includes(H??"")}function LW($,Z){if($===void 0)return!0;if(typeof $!=="string"||$.split(/[\\/]/).includes(".."))return!1;if(!Z)return!X$.isAbsolute($);let J=X$.isAbsolute($)?X$.resolve($):X$.resolve(Z,$);return H$.isWithinWorkspace(J,Z)}var RZ=G0("Agent"),s4=3;function xZ($,Z,J){if($!=="length")return{action:"none"};if(Z>=s4)return{action:"truncated"};if(JJ(J)==="stop")return RZ.info("[Loop] Token budget: diminishing returns detected, skipping recovery"),{action:"budget_stop"};return{action:"recover"}}var t4=[/:\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],e4=/```[\s\S]{50,}```/,zJ="请执行你提到的操作,不要只是描述。使用 Edit/Write/ApplyPatch/Bash 工具来实际修改文件。",$5=2;function IZ($,Z,J=!0){if(!$||Z>=$5)return{action:"none"};if(!J&&e4.test($))return{action:"retry",prompt:zJ};let W=$.slice(-200),Y=W.match(/```/g);if(Y&&Y.length%2!==0)return{action:"none"};if(t4.some((Q)=>Q.test(W)))return{action:"retry",prompt:zJ};return{action:"none"}}var I1=2,Z5="The model returned tool-call JSON as text instead of completing the requested tool workflow.",J5="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 hZ($,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 Q=new Set;for(let X of K.tool_calls){if(!X||typeof X!=="object"||Array.isArray(X))return{action:"none"};let H="function"in X;if(Object.keys(X).some((G)=>!["id","type",...H?["function"]:["name","arguments"]].includes(G)))return{action:"none"};if("type"in X&&X.type!=="function")return{action:"none"};let z=H?X.function:X;if(!z||typeof z!=="object"||Array.isArray(z)||!("name"in z)||typeof z.name!=="string"||!("arguments"in z))return{action:"none"};if(H&&Object.keys(z).some((G)=>G!=="name"&&G!=="arguments"))return{action:"none"};if(!J.includes(z.name))return{action:"none"};let V=z.arguments;if(typeof V!=="string"&&(!V||typeof V!=="object"||Array.isArray(V)))return{action:"none"};let j=z.name.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),B=new RegExp(`(?:^|[.!?。!?;;\\n])\\s*(?:please\\s+)?(?:call|invoke|execute|run|use)\\s+(?:the\\s+)?(?:tool\\s+)?[\`"']?${j}(?![\\w:-])|(?:^|[。!?;\\n])\\s*(?:请)?(?:调用|使用|执行)\\s*(?:工具\\s*)?[\`"']?${j}(?![\\w:-])`,"i"),w=new RegExp(`(?:do not|don't|never)\\s+(?:call|invoke|execute|run|use)\\s+(?:the\\s+)?(?:tool\\s+)?[\`"']?${j}(?![\\w:-])|(?:不要|禁止)(?:调用|使用|执行)\\s*(?:工具\\s*)?[\`"']?${j}(?![\\w:-])`,"i");if(!B.test(Y)||w.test(Y))return{action:"none"};Q.add(z.name)}return W<I1?{action:"retry",prompt:J5,...Q.size===1?{toolName:[...Q][0]}:{}}:{action:"fail",message:Z5}}var W5=[/\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}(?:测试|单测|集成测试|检查|构建)/],BJ={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},Y5={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},K5="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.",Q5="Required verification did not run successfully before the retry limit.",X5=3;function DJ($,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&&E$(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"&&E$(K,W))$.add(K)}function vZ($,Z,J){if(!$||!W5.some((H)=>H.test($)))return{action:"none"};let W=Object.keys(BJ).filter((H)=>BJ[H].test($)),Y=[...Z],K=W.filter((H)=>!Y.some((z)=>Y5[H].test(z)));if(W.length>0?K.length===0:Y.some((H)=>E$(H)))return{action:"none"};if(J>=X5)return{action:"fail",message:Q5};let X=W.length>1&&K.length>0?` Missing successful verification categories: ${K.join(", ")}.`:"";return{action:"retry",prompt:`${K5}${X}`}}var H5=[/\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|子代理|子智能体)/],wJ=[/\b(?:do not|don't|never)\s+(?:delegate|call|use|invoke)\b/i,/(?:不要|禁止|无需)(?:委派|调用|使用).{0,20}(?:Task|子代理|子智能体)?/];function UJ($){return typeof $==="string"&&wJ.some((Z)=>Z.test($))}var V5=[/\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|子代理)/],z5=[/\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 B5($){if(typeof $!=="string")return;if(z5.some((Z)=>Z.test($)))return"multiple-allowed";return V5.some((Z)=>Z.test($))?"required":void 0}function Z1($){for(let Z of $){let J=B5(Z);if(J!==void 0)return J==="required"}return!1}var j5="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.",D5="Required delegation did not complete before the retry limit.",w5=3;function GJ($,Z,J){let W=(typeof $==="string"?[$]:$??[]).map((Q)=>Q.trim()).filter(Boolean),Y=Z1(W),K=!1;if(!Y)for(let Q of W){if(wJ.some((X)=>X.test(Q)))break;if(H5.some((X)=>X.test(Q))){K=!0;break}}if(W.length===0||!Y&&!K||Z.has("Task"))return{action:"none"};if(J>=w5)return{action:"fail",message:D5};return{action:"retry",prompt:j5}}var U5=[/\b(?:use|create|enter|start|work\s+(?:in|inside))\b.{0,60}\bworktree\b/i,/(?:使用|创建|进入).{0,30}(?:worktree|工作树)/i],G5=[/\b(?:exit|leave)\b.{0,40}\bworktree\b/i,/\bworktree\b.{0,60}\b(?:action\s+)?(?:keep|remove)\b/i,/(?:退出|离开).{0,30}(?:worktree|工作树)/i],L5=[/\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 LJ($){return L5.reduce((Z,J)=>Z.replace(J," "),$)}function h1($){if(typeof $!=="string")return!1;let Z=LJ($);return U5.some((J)=>J.test(Z))}var q5="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.",F5="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.",O5="Required worktree lifecycle did not complete before the retry limit.",P5=3;function qJ($,Z,J){if(!$)return{action:"none"};let W=LJ($);if(!h1(W))return{action:"none"};let Y=G5.some((Q)=>Q.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>=P5)return{action:"fail",message:O5};return{action:"retry",tool:K,prompt:K==="EnterWorktree"?q5:F5}}var jJ=30000;async function CZ($){try{let J=T$.getInstance().executeStopHooks({projectDir:$.workspaceRoot??H0(),sessionId:$.sessionId,permissionMode:$.permissionMode,reason:$.reason,abortSignal:$.abortSignal}),W,Y=new Promise((K)=>{W=setTimeout(()=>K("timeout"),jJ)});try{let K=await Promise.race([J,Y]);if(K==="timeout")return RZ.warn(`[Loop] Stop hook 超时 (${jJ}ms),按 shouldStop: true 处理`),{action:"stop"};let Q=K;if(!Q.shouldStop)return{action:"continue",reason:Q.continueReason};return{action:"stop"}}finally{clearTimeout(W)}}catch(Z){return RZ.warn("[Loop] Stop hook execution failed:",Z),{action:"stop"}}}async function N5($,Z){let J;while(!(J=await $.next()).done)if(Z)await Z(J.value);return J.value}var _5=[/<system-reminder>[\s\S]*?<\/system-reminder>/gi,/<file[^>]*>[\s\S]*?<\/file>/gi,/<hooks_context>[\s\S]*?<\/hooks_context>/gi,/<[^>]+>/g];function y5($){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 b5($){let Z=$;for(let H of _5)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),Q=K.lastIndexOf(" ");return`${(Q>36?K.slice(0,Q):K).trimEnd()}…`}function FJ($){return b5(y5($))}import{EventEmitter as A5}from"events";import OJ from"node:path";function pZ($){if(NJ($.sessionId),!OJ.isAbsolute($.projectPath))throw Error("projectPath must be absolute");return{sessionId:$.sessionId,projectPath:OJ.resolve($.projectPath)}}function PJ($){let Z=pZ($);return JSON.stringify([Z.projectPath,Z.sessionId])}function fW($,Z){return PJ($)===PJ(Z)}class f$ extends A5{static instance;constructor(){super();this.setMaxListeners(100)}static getInstance(){if(!f$.instance)f$.instance=new f$;return f$.instance}publish($,Z,J,W){let Y=pZ($);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=f$.getInstance();var a0=G0("Agent"),v1=new Set;async function E5($,Z){let J=$.sessionId;if(!J||$.subagentInfo)return;if(v1.has(J))return;if(v1.size>=5000)v1.clear();v1.add(J);try{let W=$.workspaceRoot,Y=await W1.findSessionMetadata(J,W);if(!Y)return;if(Y.title&&Y.title.trim())return;let K=FJ(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){a0.debug?.("[Loop] 自动生成会话标题失败:",W)}}var gZ=`<turn_aborted>
|
|
1
|
+
import{Bc as b4}from"./chunk-9qxch6sy.js";import{Ad as f2,Bd as k2,Cc as D$,Cd as w6,Dd as U6,Ec as j$,Fc as S2,Gc as r1,Ic as H$,Jd as M2,Kd as A4,Ld as E4,Md as V6,Nd as e1,Od as S4,Pd as T4,Qd as d1,Ud as sJ,ae as i2,ce as h0,ee as k6,fe as o1,ge as M6,ne as W1,yd as T2}from"./chunk-hbkpavbp.js";import{se as y4}from"./chunk-skktstg8.js";import{Ke as q0,Le as c2,ve as F0,ye as U2,ze as s1}from"./chunk-s14zayxp.js";import{fg as n2}from"./chunk-x6k5ye1z.js";import{gg as N4,hg as x0,ig as G4,jg as rJ,lg as u1,mg as f6,ng as nJ,og as oJ,rg as aJ}from"./chunk-1g7c3f82.js";import{ch as Z$,dh as c0,gh as _4}from"./chunk-kehgewqh.js";import{lh as Y4,ph as H2}from"./chunk-kkzznz4w.js";import{Ah as T$}from"./chunk-egqep8py.js";import{Ih as M$}from"./chunk-r9egmztq.js";import{Zi as H0}from"./chunk-b22ab7yw.js";import{Ej as G0}from"./chunk-saz6mwpq.js";import{Xj as E2}from"./chunk-c33wff11.js";import{Ak as y2,Ck as b2,Hk as A2,dk as _2,sk as q2,tk as F2,wk as fJ,zk as NJ}from"./chunk-ed2hdrwe.js";import{Jk as dZ}from"./chunk-gmpsfkgg.js";function A$($){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 x1{systemMessages;_contextualSystemMessages;_history;_pending=[];_contextRevision=0;context;constructor($,Z){this.context=$;let J=$.messages.find(A$);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)=>!A$(W)&&!b$(W))}get historyLength(){return this._history.length}get pending(){return this._pending}get contextRevision(){return this._contextRevision}toLLMMessages(){return[...this.systemMessages,...this._history,...this._pending]}getHistory(){return this._history}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(A$);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:{},...q0}})}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)=>!A$(Z)&&!b$(Z)),this._contextRevision++}restoreDurableHistory($){this._contextualSystemMessages=$.filter(b$),this._history=$.filter((Z)=>!A$(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]}}function JJ($){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 WJ($){return{budget:$.budget,usage:0,consecutiveContinuations:0,lastOutputDelta:0,isSubagent:$.isSubagent??!1}}function YJ($,Z,J){return{...$,usage:$.usage+Z,lastOutputDelta:Z,consecutiveContinuations:J?$.consecutiveContinuations+1:0}}import X$ from"node:path";var g4=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"]),m4=/^(LD_.+|DYLD_.+|PATH)$/,KJ=/^([A-Za-z_][A-Za-z0-9_]*)=([\w./:@-]*)$/;function e$($){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(KJ);if(!K)break;let Q=K[1];if(!g4.has(Q))break;Z=Y}return Z}function jW($){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(KJ);if(!K)break;let Q=K[1];if(m4.test(Q))break;Z=Y}return Z}var u4=[/^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 MZ($){let Z=$,J=!0;while(J){J=!1;for(let W of u4){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 $1($){let Z=[],J="",W=!1,Y=!1,K=!1;for(let Q=0;Q<$.length;Q++){let X=$[Q];if(K){J+=X,K=!1;continue}if(X==="\\"&&!W){J+=X,K=!0;continue}if(X==="'"&&!Y){W=!W,J+=X;continue}if(X==='"'&&!W){Y=!Y,J+=X;continue}if(W||Y){J+=X;continue}if(X==="|"){if(Q+1<$.length&&$[Q+1]==="|"){if(J.trim())Z.push(J.trim());J="",Q++;continue}return null}if(X===">"||X==="<")return null;if(X==="&"&&Q+1<$.length&&$[Q+1]==="&"){if(J.trim())Z.push(J.trim());J="",Q++;continue}if(X==="&")return null;if(X===";"){if(J.trim())Z.push(J.trim());J="";continue}J+=X}if(J.trim())Z.push(J.trim());return Z.length>0?Z:null}function QJ($){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 Q=$[Y+1];if(Q&&/[A-Za-z_@*#?!$0-9({]/.test(Q))return!0}if(K==="`")return!0;if(J)continue;if(K==="|")return!0;if(K===">"||K==="<")return!0;if(K==="{"){let Q=$.slice(Y);if(/^\{[^}]*,[^}]*\}/.test(Q)||/^\{[^}]*\.\.[^}]*\}/.test(Q))return!0}}return!1}function Q$($){let Z=[],J="",W=!1,Y=!1,K=!1;for(let Q=0;Q<$.length;Q++){let X=$[Q];if(K){J+=X,K=!1;continue}if(X==="\\"&&!W){if(K=!0,Y){let H=$[Q+1];if(H&&'$`"\\'.includes(H))continue;J+=X,K=!1}continue}if(X==="'"&&!Y){W=!W;continue}if(X==='"'&&!W){Y=!Y;continue}if(!W&&!Y&&/[ \t]/.test(X)){if(J)Z.push(J),J="";continue}J+=X}if(J)Z.push(J);return Z}var d4=new Set(["npm","pnpm","yarn","bun"]),XJ=new Set(["biome","eslint","jest","mypy","pyright","pytest","ruff","tsc","vitest"]),c4=new Set(["-u","--fix","--update","--update-snapshot","--updateSnapshot","--watch","--watchAll","--write"]),i4=/[ \t]*;[ \t]*echo[ \t]+"[A-Za-z0-9 _:=.-]*(?:\$\{PIPESTATUS\[0\]\}|\$\?)[A-Za-z0-9 _:=.-]*"[ \t]*$/;function l4($){return $!==void 0&&/^(?:test|lint|build|type-?check)(?::[\w.-]+)*$/i.test($)}function HJ($){return $.replace(/\s+2>&1\s*$/,"").trim()}function r4($,Z,J){if(!J||Z.length!==2)return;let W=/^(.+?)[ \t]+&&[ \t]+([\s\S]+)$/.exec($);if(!W)return;let Y=Q$(W[1]??"");if(Y.length!==2||Y[0]!=="cd")return;let K=Y[1];if(!K||K==="-")return;let Q=X$.isAbsolute(K)?X$.resolve(K):X$.resolve(J,K);if(!H$.isWithinWorkspace(Q,J))return;return W[2]?.trim()||void 0}function n4($){let Z=[],J=!1,W=!1,Y=!1;for(let K=0;K<$.length;K++){let Q=$[K];if(Y){Y=!1;continue}if(Q==="\\"&&!J){Y=!0;continue}if(Q==="'"&&!W){J=!J;continue}if(Q==='"'&&!J){W=!W;continue}if(Q!=="|"||J||W)continue;if($[K+1]==="|")return;Z.push(K)}return Z}function o4($){let Z=Q$($),[J,W,Y]=Z;if(J!=="head"&&J!=="tail")return!1;if(Z.length===1)return!0;let K=(Q)=>Q!==void 0&&/^[1-9]\d{0,4}$/.test(Q);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 a4($){let Z=HJ($.replace(i4,"").trim()),J=n4(Z);if(!J)return;if(J.length===0)return VJ(Z);if(J.length!==1)return;let W=J[0];if(W===void 0)return;let Y=HJ(Z.slice(0,W).trim()),K=Z.slice(W+1).trim();if(!Y||!o4(K))return;return VJ(Y)}function VJ($){let J=$1($)?.at(-1);if(!J)return $;let W=Q$(J),[Y,K]=W;if(!(Y==="vitest"||(Y==="npx"||Y==="bunx")&&K==="vitest")||W.some((X)=>X==="--configLoader"||X.startsWith("--configLoader=")))return $;return`${$} --configLoader runner`}function E$($,Z){let J=a4($);if(!J)return!1;let W=e$(J),Y=$1(W);if(!Y||QJ(W)||/[\r\n]/.test(W))return!1;let K=Y.length===1?Y[0]:r4(W,Y,Z);if(!K)return!1;let Q=Q$(K);if(Q.length===0||Q.some((V)=>[...c4].some((j)=>V===j||V.startsWith(`${j}=`))))return!1;let[X,H,z]=Q;if(d4.has(X??""))return l4(H==="run"?z:H)||H==="--test";if((X==="npx"||X==="bunx")&&XJ.has(H??""))return!0;if(XJ.has(X??""))return!0;if(X==="node"&&H==="--test")return!0;if(X==="go"&&["build","test","vet"].includes(H??""))return!0;return X==="cargo"&&["build","check","clippy","test"].includes(H??"")}function LW($,Z){if($===void 0)return!0;if(typeof $!=="string"||$.split(/[\\/]/).includes(".."))return!1;if(!Z)return!X$.isAbsolute($);let J=X$.isAbsolute($)?X$.resolve($):X$.resolve(Z,$);return H$.isWithinWorkspace(J,Z)}var RZ=G0("Agent"),s4=3;function xZ($,Z,J){if($!=="length")return{action:"none"};if(Z>=s4)return{action:"truncated"};if(JJ(J)==="stop")return RZ.info("[Loop] Token budget: diminishing returns detected, skipping recovery"),{action:"budget_stop"};return{action:"recover"}}var t4=[/:\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],e4=/```[\s\S]{50,}```/,zJ="请执行你提到的操作,不要只是描述。使用 Edit/Write/ApplyPatch/Bash 工具来实际修改文件。",$5=2;function IZ($,Z,J=!0){if(!$||Z>=$5)return{action:"none"};if(!J&&e4.test($))return{action:"retry",prompt:zJ};let W=$.slice(-200),Y=W.match(/```/g);if(Y&&Y.length%2!==0)return{action:"none"};if(t4.some((Q)=>Q.test(W)))return{action:"retry",prompt:zJ};return{action:"none"}}var I1=2,Z5="The model returned tool-call JSON as text instead of completing the requested tool workflow.",J5="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 hZ($,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 Q=new Set;for(let X of K.tool_calls){if(!X||typeof X!=="object"||Array.isArray(X))return{action:"none"};let H="function"in X;if(Object.keys(X).some((G)=>!["id","type",...H?["function"]:["name","arguments"]].includes(G)))return{action:"none"};if("type"in X&&X.type!=="function")return{action:"none"};let z=H?X.function:X;if(!z||typeof z!=="object"||Array.isArray(z)||!("name"in z)||typeof z.name!=="string"||!("arguments"in z))return{action:"none"};if(H&&Object.keys(z).some((G)=>G!=="name"&&G!=="arguments"))return{action:"none"};if(!J.includes(z.name))return{action:"none"};let V=z.arguments;if(typeof V!=="string"&&(!V||typeof V!=="object"||Array.isArray(V)))return{action:"none"};let j=z.name.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),B=new RegExp(`(?:^|[.!?。!?;;\\n])\\s*(?:please\\s+)?(?:call|invoke|execute|run|use)\\s+(?:the\\s+)?(?:tool\\s+)?[\`"']?${j}(?![\\w:-])|(?:^|[。!?;\\n])\\s*(?:请)?(?:调用|使用|执行)\\s*(?:工具\\s*)?[\`"']?${j}(?![\\w:-])`,"i"),w=new RegExp(`(?:do not|don't|never)\\s+(?:call|invoke|execute|run|use)\\s+(?:the\\s+)?(?:tool\\s+)?[\`"']?${j}(?![\\w:-])|(?:不要|禁止)(?:调用|使用|执行)\\s*(?:工具\\s*)?[\`"']?${j}(?![\\w:-])`,"i");if(!B.test(Y)||w.test(Y))return{action:"none"};Q.add(z.name)}return W<I1?{action:"retry",prompt:J5,...Q.size===1?{toolName:[...Q][0]}:{}}:{action:"fail",message:Z5}}var W5=[/\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}(?:测试|单测|集成测试|检查|构建)/],BJ={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},Y5={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},K5="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.",Q5="Required verification did not run successfully before the retry limit.",X5=3;function DJ($,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&&E$(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"&&E$(K,W))$.add(K)}function vZ($,Z,J){if(!$||!W5.some((H)=>H.test($)))return{action:"none"};let W=Object.keys(BJ).filter((H)=>BJ[H].test($)),Y=[...Z],K=W.filter((H)=>!Y.some((z)=>Y5[H].test(z)));if(W.length>0?K.length===0:Y.some((H)=>E$(H)))return{action:"none"};if(J>=X5)return{action:"fail",message:Q5};let X=W.length>1&&K.length>0?` Missing successful verification categories: ${K.join(", ")}.`:"";return{action:"retry",prompt:`${K5}${X}`}}var H5=[/\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|子代理|子智能体)/],wJ=[/\b(?:do not|don't|never)\s+(?:delegate|call|use|invoke)\b/i,/(?:不要|禁止|无需)(?:委派|调用|使用).{0,20}(?:Task|子代理|子智能体)?/];function UJ($){return typeof $==="string"&&wJ.some((Z)=>Z.test($))}var V5=[/\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|子代理)/],z5=[/\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 B5($){if(typeof $!=="string")return;if(z5.some((Z)=>Z.test($)))return"multiple-allowed";return V5.some((Z)=>Z.test($))?"required":void 0}function Z1($){for(let Z of $){let J=B5(Z);if(J!==void 0)return J==="required"}return!1}var j5="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.",D5="Required delegation did not complete before the retry limit.",w5=3;function GJ($,Z,J){let W=(typeof $==="string"?[$]:$??[]).map((Q)=>Q.trim()).filter(Boolean),Y=Z1(W),K=!1;if(!Y)for(let Q of W){if(wJ.some((X)=>X.test(Q)))break;if(H5.some((X)=>X.test(Q))){K=!0;break}}if(W.length===0||!Y&&!K||Z.has("Task"))return{action:"none"};if(J>=w5)return{action:"fail",message:D5};return{action:"retry",prompt:j5}}var U5=[/\b(?:use|create|enter|start|work\s+(?:in|inside))\b.{0,60}\bworktree\b/i,/(?:使用|创建|进入).{0,30}(?:worktree|工作树)/i],G5=[/\b(?:exit|leave)\b.{0,40}\bworktree\b/i,/\bworktree\b.{0,60}\b(?:action\s+)?(?:keep|remove)\b/i,/(?:退出|离开).{0,30}(?:worktree|工作树)/i],L5=[/\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 LJ($){return L5.reduce((Z,J)=>Z.replace(J," "),$)}function h1($){if(typeof $!=="string")return!1;let Z=LJ($);return U5.some((J)=>J.test(Z))}var q5="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.",F5="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.",O5="Required worktree lifecycle did not complete before the retry limit.",P5=3;function qJ($,Z,J){if(!$)return{action:"none"};let W=LJ($);if(!h1(W))return{action:"none"};let Y=G5.some((Q)=>Q.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>=P5)return{action:"fail",message:O5};return{action:"retry",tool:K,prompt:K==="EnterWorktree"?q5:F5}}var jJ=30000;async function CZ($){try{let J=T$.getInstance().executeStopHooks({projectDir:$.workspaceRoot??H0(),sessionId:$.sessionId,permissionMode:$.permissionMode,reason:$.reason,abortSignal:$.abortSignal}),W,Y=new Promise((K)=>{W=setTimeout(()=>K("timeout"),jJ)});try{let K=await Promise.race([J,Y]);if(K==="timeout")return RZ.warn(`[Loop] Stop hook 超时 (${jJ}ms),按 shouldStop: true 处理`),{action:"stop"};let Q=K;if(!Q.shouldStop)return{action:"continue",reason:Q.continueReason};return{action:"stop"}}finally{clearTimeout(W)}}catch(Z){return RZ.warn("[Loop] Stop hook execution failed:",Z),{action:"stop"}}}async function N5($,Z){let J;while(!(J=await $.next()).done)if(Z)await Z(J.value);return J.value}var _5=[/<system-reminder>[\s\S]*?<\/system-reminder>/gi,/<file[^>]*>[\s\S]*?<\/file>/gi,/<hooks_context>[\s\S]*?<\/hooks_context>/gi,/<[^>]+>/g];function y5($){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 b5($){let Z=$;for(let H of _5)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),Q=K.lastIndexOf(" ");return`${(Q>36?K.slice(0,Q):K).trimEnd()}…`}function FJ($){return b5(y5($))}import{EventEmitter as A5}from"events";import OJ from"node:path";function pZ($){if(NJ($.sessionId),!OJ.isAbsolute($.projectPath))throw Error("projectPath must be absolute");return{sessionId:$.sessionId,projectPath:OJ.resolve($.projectPath)}}function PJ($){let Z=pZ($);return JSON.stringify([Z.projectPath,Z.sessionId])}function fW($,Z){return PJ($)===PJ(Z)}class f$ extends A5{static instance;constructor(){super();this.setMaxListeners(100)}static getInstance(){if(!f$.instance)f$.instance=new f$;return f$.instance}publish($,Z,J,W){let Y=pZ($);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=f$.getInstance();var a0=G0("Agent"),v1=new Set;async function E5($,Z){let J=$.sessionId;if(!J||$.subagentInfo)return;if(v1.has(J))return;if(v1.size>=5000)v1.clear();v1.add(J);try{let W=$.workspaceRoot,Y=await W1.findSessionMetadata(J,W);if(!Y)return;if(Y.title&&Y.title.trim())return;let K=FJ(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){a0.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>`,V$="Tool execution was blocked because its durable call record could not be committed. No tool side effect was started.",_J="Tool execution completed, but its durable result record could not be committed. Further model and tool execution was stopped. The operation may have completed; inspect external state before retrying.";class k$ extends Error{phase;constructor($,Z){super($==="user_message"?"Conversation input could not be committed. No further model request was started.":"Model output could not be committed. The run was stopped before any further model request or successful completion.",Z);this.phase=$;this.name="DurableConversationPersistenceError"}}function z$($){return $.executionEngine?.getContextManager()}async function d0($,Z,J,W=null,Y,K={}){let Q=K.required??$.executionEngine!==void 0;try{let X=z$($),H=typeof J==="string"?J.trim()!=="":J.some((z)=>z.type==="text"?z.text.trim()!=="":!0);if(X&&Z.sessionId&&H){let z=await X.saveMessage(Z.sessionId,"user",J,W,Y,Z.subagentInfo);if(Q&&!z)throw Error("Durable user-message commit returned no identity");if(Y?.clientVisible!==!1)E5(Z,J);return z}if(Q&&Z.sessionId&&H)throw Error("Durable user-message storage is unavailable")}catch(X){if(a0.warn("[Loop] 保存用户消息失败:",X),Q)throw new k$("user_message",{cause:X})}return null}async function _0($,Z,J,W,Y,K,Q={}){let X=Q.required??$.executionEngine!==void 0;try{let H=z$($),z=Boolean(J.trim()||Y?.trim());if(H&&Z.sessionId&&z){let V=await H.saveMessage(Z.sessionId,"assistant",J,W,K,Z.subagentInfo,Y);if(X&&!V)throw Error("Durable assistant-message commit returned no identity");return V}if(X&&Z.sessionId&&z)throw Error("Durable assistant-message storage is unavailable")}catch(H){if(a0.warn("[Loop] 保存助手消息失败:",H),X)throw new k$("assistant_message",{cause:H})}return null}async function yJ($,Z,J){try{let W=z$($);if(W&&Z.sessionId)return await W.saveMessage(Z.sessionId,"system",gZ,J,void 0,Z.subagentInfo)}catch(W){a0.warn("[Loop] 保存中断边界失败:",W)}return null}async function bJ($,Z,J,W,Y){try{let K=z$($);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((Q)=>({...Q})))),triggerPaths:[...W]},Z.subagentInfo)}catch(K){a0.warn("[Loop] 保存 contextual project rules provenance 失败:",K)}return null}async function mZ($,Z,J,W,Y,K={}){try{let Q=z$($);if(Q&&Z.sessionId){let X=await Q.saveToolUse(Z.sessionId,J,W,Y,Z.subagentInfo,K.providerToolCallId);if(K.required&&!X)throw Error("Durable tool-use commit returned no identity");return X}if(K.required&&Z.sessionId)throw Error("Durable tool-use storage is unavailable")}catch(Q){if(a0.warn("[Loop] 保存工具调用失败:",Q),K.required)throw Q}return null}async function C1($,Z,J,W,Y,K,Q,X,H,z={}){try{let V=z$($);if(V&&Z.sessionId){let j=await V.saveToolResult(Z.sessionId,J,W,Y,K,Q,Z.subagentInfo,X,H);if(z.required&&!j)throw Error("Durable tool-result commit returned no identity");return j}if(z.required&&Z.sessionId)throw Error("Durable tool-result storage is unavailable")}catch(V){if(a0.warn("[Loop] 保存工具结果失败:",V),z.required)throw V}return null}async function Y1($,Z,J,W,Y={}){try{let K=z$($);if(K&&Z.sessionId){let Q=await K.saveCompaction(Z.sessionId,J,W,null);if(Y.required&&!Q)throw Error("Compaction checkpoint commit returned no identity");return Q||null}if(Y.required&&Z.sessionId)throw Error("Compaction checkpoint storage is unavailable")}catch(K){if(a0.warn("[Loop] 保存压缩数据失败:",K),Y.required)throw K}return null}async function Q0($){let{deps:Z,context:J,state:W,assistantContent:Y,assistantReasoningContent:K,lastMessageUuid:Q,controlPrompt:X}=$;W.appendAssistant({role:"assistant",content:Y,reasoningContent:K});let H=Q,z=await _0(Z,J,Y,H,K);if(z)H=z;if(X!==void 0){let V={role:"user",content:X,metadata:q0};W.appendControl("user",V);let j=await d0(Z,J,X,H,q0);if(j)H=j}return H}import{createHash as R6}from"node:crypto";import{promises as J8}from"node:fs";import W8 from"node:path";import{nanoid as t0}from"nanoid";import*as a from"node:fs/promises";import*as s0 from"node:path";import EJ from"write-file-atomic";var AJ={enabled:!0,maxIndexLines:200};var S5="memory",uZ="MEMORY.md",cZ="<!-- blade:auto-memory-topics:start -->",p1="<!-- blade:auto-memory-topics:end -->",T5={realpath:!1,retries:{retries:5,factor:1.2,minTimeout:20,maxTimeout:100,randomize:!0}},f5=new M$,SJ;function kJ($){return $.trim().replace(/\s+/g," ")}function k5($){return kJ($.replace(/^- \[\d{4}-\d{2}-\d{2}\] /,""))}function M5($){return[cZ,"## Auto-consolidated topics",...$.map((Z)=>`- [${Z}](${Z}.md)`),p1].join(`
|
|
4
4
|
`)}function R5($,Z){let J=M5(Z),W=$.indexOf(cZ),Y=$.indexOf(p1,Math.max(0,W));if(W>=0&&Y>=W)return $.slice(0,W)+J+$.slice(Y+p1.length);if(!$)return`${J}
|
|
@@ -92,7 +92,7 @@ Full output saved to: ${X}`}catch{return`${Z}
|
|
|
92
92
|
|
|
93
93
|
${Y}`}}function i1($){if($===void 0||!Number.isFinite($))return 0;return Math.max(0,Math.trunc($))}function b8($){if($===void 0||!Number.isFinite($))return 0;return Math.max(0,$)}function V1($,Z){return Math.min(Number.MAX_SAFE_INTEGER,$+Z)}function W6($,Z){let J=i1(Z.inputTokens),W=Math.min(i1(Z.cacheReadTokens),J),Y=Math.min(i1(Z.cacheWriteTokens),Math.max(0,J-W)),K={inputTokens:J,outputTokens:i1(Z.outputTokens),cacheReadTokens:W,cacheWriteTokens:Y,uncachedInputTokens:Math.max(0,J-W-Y),estimatedCostUsd:b8(Z.costUsd)};if(!$)return K;return{inputTokens:V1($.inputTokens,K.inputTokens),outputTokens:V1($.outputTokens,K.outputTokens),cacheReadTokens:V1($.cacheReadTokens,K.cacheReadTokens),cacheWriteTokens:V1($.cacheWriteTokens,K.cacheWriteTokens),uncachedInputTokens:V1($.uncachedInputTokens,K.uncachedInputTokens),estimatedCostUsd:$.estimatedCostUsd+K.estimatedCostUsd}}function X2($){if(!$||typeof $!=="object"||Array.isArray($))return;let Z=$,{inputTokens:J,outputTokens:W,cacheReadTokens:Y,cacheWriteTokens:K,uncachedInputTokens:Q,estimatedCostUsd:X}=Z;if(typeof J!=="number"||!Number.isSafeInteger(J)||J<0||typeof W!=="number"||!Number.isSafeInteger(W)||W<0||typeof Y!=="number"||!Number.isSafeInteger(Y)||Y<0||typeof K!=="number"||!Number.isSafeInteger(K)||K<0||typeof Q!=="number"||!Number.isSafeInteger(Q)||Q<0||typeof X!=="number"||!Number.isFinite(X)||X<0)return;return{inputTokens:J,outputTokens:W,cacheReadTokens:Y,cacheWriteTokens:K,uncachedInputTokens:Q,estimatedCostUsd:X}}function V2(){return{successfulBash:!1}}function A8($){return typeof $==="string"&&H2.some((Z)=>Z===$)}function m3($){switch($){case"timeout":case"admission":case"spawn":case"finalization":return $;case"unavailable":return"terminal";default:return}}function u3($){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 z2($,Z,J){if(Z!=="Bash")return;if(J.success){$.successfulBash=!0;return}let W=J.metadata?.execution_host_failure;if(A8(W))$.category=W}function B2($){return $.successfulBash?void 0:$.category}class Y6{lastAttemptAt;lastRound=0;constructor($){this.lastAttemptAt=$}claim($,Z,J=!1){if(Z-this.lastAttemptAt<120000)return!1;if($<=this.lastRound)return!1;if(!J&&$-this.lastRound<5)return!1;return this.lastRound=$,this.lastAttemptAt=Z,!0}}import n8 from"node:path";import{nanoid as o8}from"nanoid";import{randomUUID as B1}from"node:crypto";import*as I0 from"node:fs/promises";import*as G2 from"node:path";import{Mutex as M8}from"async-mutex";import R8 from"write-file-atomic";var j2=120,K6=128;function z1($){if(!Array.isArray($)||$.length>120||!$.every((Z)=>typeof Z==="string"&&Z.length>0&&Z.length<=128))return;return[...new Set($)]}function E8($){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=E8(J.data);if(W.length===0)return[];let Y=-1;for(let Q=Z-1;Q>=0;Q--){let X=$[Q];if(X.type==="turn_started"){if(X.data.turnId!==J.data.turnId)return[];Y=Q;break}if(X.type==="turn_completed"||X.type==="turn_aborted")return[]}if(Y<0)return[];let K=new Set;for(let Q=Y+1;Q<Z;Q++){let X=$[Q];if(X.type!=="message_created"||X.data.role!=="user")continue;let H=X.data.metadata,z=X.data.inboxMessageId!==void 0?X.data.inboxMessageId:H!==null&&typeof H==="object"&&!Array.isArray(H)?H.inboxMessageId:void 0;if(typeof z==="string"&&z.length>0&&z.length<=128)K.add(z)}return W.filter((Q)=>K.has(Q))}import*as n1 from"node:fs/promises";import*as w2 from"node:path";var S8={realpath:!1,retries:{retries:150,factor:1.2,minTimeout:10,maxTimeout:100,randomize:!0}},T8=new M$,D2;async function v$($,Z,J,W=k8){let Y=j$($,Z);return T8.runExclusive(Y,()=>r1($,Z,async(K)=>{let Q=w2.dirname(K.inboxPath);await n1.mkdir(Q,{recursive:!0,mode:448}),await n1.chmod(Q,448);let X,H=await W(K.inboxPath,{...S8,onCompromised:(z)=>{X=z}});try{if(X)throw X;let z=await J(K);if(X)throw X;return z}finally{await H()}}))}async function f8(){return D2??=await import("proper-lockfile"),D2}async function k8($,Z){return(await f8()).lock($,Z)}var H6=2,C$=8388608;function Q6($,Z,J){let W={version:H6,sessionId:$,generation:Z,messages:J.map(({recovered:Y,...K})=>K)};return`${JSON.stringify(W)}
|
|
95
|
-
`}function X6($,Z){return $ instanceof Error&&"code"in $&&$.code===Z}function x8($){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 I8($,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!==H6||!("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)||!x8(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 Q="outputSchema"in K&&K.outputSchema!==void 0?o1(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))}:{},...Q?{outputSchema:Q}:{}}});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:H6,sessionId:J,generation:W.generation,messages:Y}}function h8($){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 v8($){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 a1{sessionId;stateStorage;writeFile;lockFile;mutex=new M8;generation=B1();messages=[];constructor($,Z,J,W){this.sessionId=$;this.stateStorage=Z;this.writeFile=J;this.lockFile=W}static async open($,Z,J=D$($),W={}){let Y=new a1(Z,J,W.writeFile??R8,W.lockFile);return await Y.loadAndReconcile(),Y}async enqueue($,Z){return this.mutex.runExclusive(async()=>{let J=await v$(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}],Q=B1(),X=Q6(this.sessionId,Q,K);if(Buffer.byteLength(X)>C$)return{accepted:!1,snapshot:Y};return await this.persistAtPath(K,Q,W,X),{accepted:!0,snapshot:{generation:Q,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 v$(this.stateStorage,this.sessionId,async(W)=>{let Y=await this.readAndReconcileAtPath(W),K=Y.messages.filter((X)=>!Z.has(X.id));if(K.length===Y.messages.length&&!Y.acknowledgedRemoved)return Y;let Q=B1();return await this.persistAtPath(K,Q,W),{generation:Q,messages:K}},this.lockFile);this.install(J)})}snapshot(){return{generation:this.generation,messages:this.list()}}async refresh(){return this.mutex.runExclusive(async()=>{let $=await v$(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 v$(this.stateStorage,this.sessionId,async(W)=>{let Y=await this.readAndReconcileAtPath(W);if(Y.generation!==$)return{replaced:!1,snapshot:Y};let K=B1(),Q=Z.map((H)=>({...H})),X=Q6(this.sessionId,K,Q);if(Buffer.byteLength(X)>C$)return{replaced:!1,snapshot:Y};return await this.persistAtPath(Q,K,W,X),{replaced:!0,snapshot:{generation:K,messages:Q}}},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 v$(this.stateStorage,this.sessionId,async(Z)=>{let J=await this.readAndReconcileAtPath(Z);if(J.migrationRequired||J.acknowledgedRemoved){let W=B1();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 Q=await I0.open($.inboxPath,"r");try{if((await Q.stat()).size>C$)throw Error(`Steering inbox exceeds ${C$} bytes: ${$.inboxPath}`);Z=I8(await Q.readFile("utf8"),$.inboxPath,this.sessionId)}finally{await Q.close()}await I0.chmod($.inboxPath,384)}catch(Q){if(!X6(Q,"ENOENT"))throw Q}let J=new Set,W=new Set;try{let Q=U2(await I0.readFile($.transcriptPath,"utf8"),$.transcriptPath);J=h8(Q),W=v8(Q)}catch(Q){if(!X6(Q,"ENOENT"))throw Q}let Y=new Map(this.messages.map((Q)=>[Q.id,Q.recovered])),K=(Z?.messages??[]).filter((Q)=>!J.has(Q.id)).map((Q)=>({...Q,recovered:Y.get(Q.id)??!0,...Q.persisted===!0||W.has(Q.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 I0.mkdir(G2.dirname(J.inboxPath),{recursive:!0,mode:448}),$.length===0){await I0.unlink(J.inboxPath).catch((K)=>{if(!X6(K,"ENOENT"))throw K});return}let Y=W??Q6(this.sessionId,Z,$);if(Buffer.byteLength(Y)>C$)throw Error(`Steering inbox exceeds ${C$} bytes: ${J.inboxPath}`);await this.writeFile(J.inboxPath,Y,{encoding:"utf8",mode:384,fsync:!0})}}import*as $Z from"node:fs/promises";import{nanoid as V0}from"nanoid";var L2=256;class w0{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=D$(Z)){let W=j$(J,$),Y=w0.instances.get(W);if(!Y)Y=new w0($,Z,J),w0.instances.set(W,Y),w0.pruneIdleInstances(W);else w0.instances.delete(W),w0.instances.set(W,Y);return Y}static release($,Z,J=D$(Z)){w0.instances.delete(j$(J,$))}static pruneIdleInstances($){if(w0.instances.size<=L2)return;for(let[Z,J]of w0.instances){if(Z===$||J.subscribers.size>0)continue;if(w0.instances.delete(Z),w0.instances.size<=L2)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($),w0.pruneIdleInstances()}}async replay($,Z){let J=await this.withStore(async(W,Y,K)=>{let Q=Y?await W.readAllValidated(Y):await W.readAll();return K(Q),Q.filter((X)=>(X.seq??0)>=Z)});for(let W of J){if(V6(W))continue;await $.onCommitted(W)}}record($){if(typeof $.seq==="number"&&$.seq>this.highestSeq)this.highestSeq=$.seq;if(V6($))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 r1(this.storage,this.sessionId,async(Z)=>{let J=new s1(Z.transcriptPath);if(!Z.remoteScope)return $(J,void 0,()=>{return});let W=Z.remoteScope;return $(J,{noFollow:!0,validateHandle:async(Q)=>{await q2(W,Z.transcriptPath,Q)}},(Q)=>{F2(Q,this.sessionId,this.projectPath,this.storage.kind==="acp-remote"?this.storage.descriptor:void 0)})})}}function w$($){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 O0 extends Error{}var C8="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 z6($,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 O2($,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,Q=Y.data.inboxMessageId!==void 0?Y.data.inboxMessageId:K!==null&&typeof K==="object"&&!Array.isArray(K)?K.inboxMessageId:void 0;if(typeof Q==="string"&&Q.length>0&&Q.length<=K6)W.push(Q)}return[...new Set(W)]}function R2($){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 p8($,Z){let J=$.findLastIndex((X)=>X.type==="turn_started"&&X.data.turnId===Z);if(J<0)return 0;let W=$.findIndex((X,H)=>H>J&&X.type==="turn_started"&&X.data.turnId!==Z),Y=$.slice(J+1,W<0?void 0:W),K=new Set(Y.flatMap((X)=>{if(X.type!=="part_created"||X.data.partType!=="tool_call")return[];let H=X.data.payload;return H&&typeof H==="object"&&!Array.isArray(H)?[typeof H.toolCallId==="string"?H.toolCallId:X.data.partId]:[X.data.partId]})),Q=new Set;for(let X of Y){if(X.type!=="part_created"||X.data.partType!=="tool_result")continue;let H=X.data.payload;if(!H||typeof H!=="object"||Array.isArray(H))continue;let z=typeof H.toolCallId==="string"?H.toolCallId:X.data.partId,V=H.metadata;if(K.has(z)&&V&&typeof V==="object"&&!Array.isArray(V)&&V.processRestartRecovery===!0&&V.sideEffectsUncertain===!0)Q.add(z)}return Q.size}function x2($){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 B6($,Z,J=[]){let W=R2(Z.data.recovery);if(!W)return;if($.some((X)=>X.type==="turn_recovery_acknowledged"&&X.data.turnId===Z.data.turnId))return;let Y=x2($);for(let X of J)Y.add(X);let K=W.inputMessageIds.filter((X)=>!Y.has(X)),Q=W.version===1?p8($,Z.data.turnId):W.interruptedToolCallCount;if(K.length===0&&!W.hadSuccessfulToolResult&&Q===0)return;return{turnId:Z.data.turnId,outcome:"aborted",inputMessageIds:K,hadSuccessfulToolResult:W.hadSuccessfulToolResult,...Q>0?{interruptedToolCallCount:Q}:{},...W.version===3&&W.allSuccessfulToolResultsSafeForResume===!0?{allSuccessfulToolResultsSafeForResume:!0}:{},emptyFinalCorrectionSpent:W.emptyFinalCorrectionSpent}}function j1($){for(let Z=$.length-1;Z>=0;Z--){let J=$[Z];if(J.type!=="turn_aborted")continue;let W=B6($,J);if(W)return W}return}function t1($,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:Q,description:X}=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 X==="string"&&Y.subagentDescription===X&&W.description===X&&(Q===void 0||typeof Q==="string"&&Q===Y.subagentType)&&W.subagentType===Y.subagentType&&W.subagentStatus===Y.subagentStatus&&H&&W.processRestartRecovery===!0&&W.subagentResultAdopted===!0&&W.sideEffectsUncertain===!1}var g8=1e4,m8=1e5,u8=2592000000,P2=128,d8=1e6,c8=256;function i8($){if(!$||typeof $!=="object"||Array.isArray($))return;let Z=$;if(typeof Z.goalId!=="string"||Z.goalId.length===0||Z.goalId.length>P2||typeof Z.verificationAttempt!=="number"||!Number.isSafeInteger(Z.verificationAttempt)||Z.verificationAttempt<1||Z.verificationAttempt>d8||typeof Z.verifierSessionId!=="string"||Z.verifierSessionId.length===0||Z.verifierSessionId.length>P2||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 I2($,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,Q=Y.inputMessageIds,X=Y.turnsCount,H=Y.toolCallsCount,z=Y.durationMs,V=Array.isArray(Q)?Q.filter((w)=>typeof w==="string"&&w.length>0&&w.length<=K6):[];if(typeof K!=="string"||K.length===0||K.length>128||Z!==void 0&&K!==Z||!Array.isArray(Q)||Q.length>j2||V.length!==Q.length||typeof X!=="number"||!Number.isSafeInteger(X)||X<0||X>g8||typeof H!=="number"||!Number.isSafeInteger(H)||H<0||H>m8||typeof z!=="number"||!Number.isSafeInteger(z)||z<0||z>u8)return;let j;if("goalFinalization"in Y){if(j=i8(Y.goalFinalization),!j)return}let B=X2(Y.usage);return{turnId:K,inputMessageIds:[...new Set(V)],turnsCount:X,toolCallsCount:H,durationMs:z,...B?{usage:B}:{},...j?{goalFinalization:j}:{}}}function N2($,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=I2(Y,Z);if(K)return K}return}function l8($){for(let Z=$.length-1;Z>=0;Z--){let J=$[Z];if(J?.type!=="message_created")continue;let W=I2(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 p$($,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,Q=new Set;for(let H of $.slice(J+1)){if(H.type==="interaction_requested"){Q.add(H.data.toolCallId);continue}if(H.type!=="part_created")continue;let z=H.data.payload&&typeof H.data.payload==="object"&&!Array.isArray(H.data.payload)?H.data.payload:{},V=typeof z.toolCallId==="string"?z.toolCallId:H.data.partId;if(H.data.partType==="tool_call")W.set(V,{toolCallId:V,messageId:H.data.messageId,toolName:typeof z.toolName==="string"?z.toolName:"unknown",input:z.input??null});else if(H.data.partType==="tool_result"){if(Y.add(V),Y.add(H.data.partId),Y.add(H.data.messageId),W.has(V)&&z.error===null)K.add(V)}}let X=[...W.values()];return{all:X,orphaned:X.filter((H)=>!Y.has(H.toolCallId)&&!Q.has(H.toolCallId)),hadSuccessfulResult:X.some((H)=>K.has(H.toolCallId))}}class b0{static sessionInitializationRuns=new Map;projectPath;version;stateStorage;initializedSessions=new Set;constructor($=H0(),Z=E2(),J=D$($)){this.projectPath=$,this.version=Z,this.stateStorage=J}createEvent($,Z,J){return{id:V0(),sessionId:Z,projectPath:this.projectPath,timestamp:new Date().toISOString(),type:$,cwd:this.projectPath,...this.stateStorage.kind==="local"?{gitBranch:A2(this.projectPath)}:{},version:this.version,data:J}}log($){return w0.for($,this.projectPath,this.stateStorage)}async ensureSessionCreated($,Z){let J=j$(this.stateStorage,$);if(this.initializedSessions.delete($)){this.initializedSessions.add($);return}let W=b0.sessionInitializationRuns.get(J);if(!W)W=this.initializeSessionFile($,Z),b0.sessionInitializationRuns.set(J,W);try{await W,this.rememberInitializedSession($)}finally{if(b0.sessionInitializationRuns.get(J)===W)b0.sessionInitializationRuns.delete(J)}}rememberInitializedSession($){this.initializedSessions.delete($),this.initializedSessions.add($);while(this.initializedSessions.size>c8){let Z=this.initializedSessions.values().next().value;if(Z===void 0)return;this.initializedSessions.delete(Z)}}async initializeSessionFile($,Z){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 W=new Date().toISOString(),Y={sessionId:$,rootId:Z?.parentSessionId??$,parentId:Z?.parentSessionId,relationType:Z?"subagent":void 0,resumedFrom:Z?.resumedFrom,rootAgentId:Z?.rootAgentId,resumeDepth:Z?.resumeDepth,title:void 0,status:"running",taskStatus:Z?"running":"queued",taskFailure:null,agentType:Z?.subagentType,model:void 0,permission:void 0,createdAt:W,updatedAt:W},K=this.createEvent("session_created",$,Y);await this.log($).commit(K)}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=f2;return Z}async initialize(){try{await S2(this.stateStorage,async($)=>{if(this.stateStorage.kind==="local")await $Z.mkdir($,{recursive:!0,mode:493})})}catch($){console.warn("[PersistentStore] 无法创建持久化存储目录:",$)}}async saveMessage($,Z,J,W=null,Y,K,Q){try{await this.ensureSessionCreated($,K);let X=new Date().toISOString(),H=V0(),z={messageId:H,role:Z,parentMessageId:W??void 0,inboxMessageId:Y?.inboxMessageId,createdAt:X,model:Y?.model,usage:Y?.usage,metadata:Y?JSON.parse(JSON.stringify(Y)):void 0},V=this.createEvent("message_created",$,z),j=Z==="assistant"&&Q?.trim()?[this.createEvent("part_created",$,{partId:V0(),messageId:H,partType:"reasoning",payload:{text:Q},createdAt:X})]:[],B=typeof J==="string"?[this.createEvent("part_created",$,{partId:V0(),messageId:H,partType:"text",payload:{text:J,...Y?.conversationRecap?{conversationRecap:!0}:{}},createdAt:X})]:J.map((w)=>this.createEvent("part_created",$,{partId:V0(),messageId:H,partType:w.type==="text"?"text":"image",payload:w.type==="text"?{text:w.text}:{mimeType:r8(w.image_url.url)??"image/png",dataUrl:w.image_url.url},createdAt:X}));return await this.log($).commitBatch([V,...j,...B]),H}catch(X){throw console.error(`[PersistentStore] 保存消息失败 (session: ${$}):`,X),X}}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=F0(J);if(W.some((K)=>K.type==="turn_recovery_acknowledged"&&K.data.turnId===Z))throw new O0;let Y=W.findLast((K)=>K.type==="turn_aborted"&&K.data.turnId===Z);if(!Y||!B6(W,Y))throw new O0;return this.createEvent("turn_recovery_acknowledged",$,{turnId:Z,acknowledgedAt:new Date().toISOString()})})}catch(J){if(!(J instanceof O0))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=F0(W),K=Y.some((B)=>B.type==="inbox_acknowledged"&&B.data.messageIds.includes(Z.inboxMessageId)),Q=Y.find((B)=>B.type==="message_created"&&B.data.inboxMessageId===Z.inboxMessageId),X=Y.findLast((B)=>{if(B.type!=="part_created"||B.data.partType!=="tool_call"||!B.data.payload||typeof B.data.payload!=="object"||Array.isArray(B.data.payload))return!1;let w=B.data.payload;if(w.toolName!=="Task"||!w.input||typeof w.input!=="object"||Array.isArray(w.input))return!1;let G=w.input,q=G.resume_from??G.resume;return G.run_in_background===!0&&G.subagent_session_id===Z.childSessionId&&G.description===Z.subagentRef.subagentDescription&&(G.subagent_type===void 0||G.subagent_type===Z.subagentRef.subagentType)&&(G.resume_from===void 0||G.resume===void 0||G.resume_from===G.resume)&&(q===void 0?Z.subagentRef.subagentResumedFrom===void 0:q===Z.subagentRef.subagentResumedFrom)});if(!X)return J={eligible:!1,acknowledged:K,persisted:!1,...Q?{messageId:Q.data.messageId}:{}},[];if(K)return J={eligible:!0,acknowledged:!0,persisted:!1,...Q?{messageId:Q.data.messageId}:{}},[];let H=Y.find((B)=>B.type==="part_created"&&B.data.partType==="subtask_ref"&&B.data.payload!==null&&typeof B.data.payload==="object"&&!Array.isArray(B.data.payload)&&B.data.payload.childSessionId===Z.childSessionId&&B.data.payload.status===Z.subagentRef.subagentStatus);if(Q&&H)return J={eligible:!0,acknowledged:!1,persisted:!1,messageId:Q.data.messageId},[];let z=new Date().toISOString(),V=Q?.data.messageId??V0(),j=[];if(!Q){let B={messageId:V,role:"user",inboxMessageId:Z.inboxMessageId,createdAt:z,metadata:JSON.parse(JSON.stringify(Z.metadata))};j.push(this.createEvent("message_created",$,B)),j.push(this.createEvent("part_created",$,{partId:V0(),messageId:V,partType:"text",payload:{text:Z.content},createdAt:z}))}if(!H){let B=Y.findLast((G)=>G.type==="part_created"&&G.data.partType==="subtask_ref"&&G.data.messageId===X.data.messageId&&G.data.payload!==null&&typeof G.data.payload==="object"&&!Array.isArray(G.data.payload)&&G.data.payload.childSessionId===Z.childSessionId),w=B?.data.payload&&typeof B.data.payload==="object"&&!Array.isArray(B.data.payload)?B.data.payload:void 0;j.push(this.createEvent("part_created",$,{partId:V0(),messageId:X.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:z,finishedAt:z},createdAt:z}))}return J={eligible:!0,acknowledged:!1,persisted:j.length>0,messageId:V},j}),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=F0(J);if(W.some((K)=>K.type==="turn_started"&&K.data.turnId===Z.turnId))throw new O0;let Y=w$(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 O0))throw J}}async saveTurnCompletion($,Z,J=[]){await this.ensureSessionCreated($);try{await this.log($).commitValidatedBatch((W)=>{let Y=F0(W),K=new Set(Y.flatMap((z)=>z.type==="inbox_acknowledged"?z.data.messageIds:[])),Q=[...new Set(J)].filter((z)=>!K.has(z)),X=Y.findLast((z)=>(z.type==="turn_completed"||z.type==="turn_aborted")&&z.data.turnId===Z.turnId);if(X){if(X.type==="turn_aborted"||Q.length===0)throw new O0;return[this.createEvent("inbox_acknowledged",$,{messageIds:Q,acknowledgedAt:Z.completedAt})]}let H=w$(Y).active;if(!H||H.turnId!==Z.turnId)throw Error(`Turn is not active: ${Z.turnId}`);return[...Q.length>0?[this.createEvent("inbox_acknowledged",$,{messageIds:Q,acknowledgedAt:Z.completedAt})]:[],this.createEvent("turn_completed",$,Z)]})}catch(W){if(!(W instanceof O0))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 Q,X=[];try{await this.log($).commitValidatedBatch((H)=>{let z=F0(H),V=x2(z),j=z.findLast((u)=>(u.type==="turn_completed"||u.type==="turn_aborted")&&u.data.turnId===Z.turnId);if(j){if(j.type==="turn_completed")throw Q=void 0,X=[],new O0;let u=R2(j.data.recovery),k0=u?K.filter((r)=>u.inputMessageIds.includes(r)):[],P0=k0.filter((r)=>!V.has(r));if(X=k0,Q=B6(z,j,k0),P0.length===0)throw new O0;return[this.createEvent("inbox_acknowledged",$,{messageIds:P0,acknowledgedAt:Z.abortedAt})]}let B=w$(z).active;if(!B||B.turnId!==Z.turnId)throw Error(`Turn is not active: ${Z.turnId}`);let w=p$(z,B.turnId),G=O2(z,B.turnId),q=j1(z),y=new Set(Z.recovery?.inputMessageIds??[]),_=q?q.inputMessageIds.filter((u)=>y.has(u)):[],f=[...new Set([...G,..._])],h=w.hadSuccessfulResult||Z.recovery?.hadSuccessfulToolResult===!0,I={version:3,inputMessageIds:f,hadSuccessfulToolResult:h,interruptedToolCallCount:w.orphaned.length+(Z.recovery?.version===2||Z.recovery?.version===3?Z.recovery.interruptedToolCallCount:0),allSuccessfulToolResultsSafeForResume:h&&!w.hadSuccessfulResult&&Z.recovery?.version===3&&Z.recovery.hadSuccessfulToolResult&&Z.recovery.allSuccessfulToolResultsSafeForResume,emptyFinalCorrectionSpent:z6(z,B.turnId)||Z.recovery?.emptyFinalCorrectionSpent===!0};Q={turnId:Z.turnId,outcome:"aborted",inputMessageIds:I.inputMessageIds,hadSuccessfulToolResult:I.hadSuccessfulToolResult,...I.interruptedToolCallCount>0?{interruptedToolCallCount:I.interruptedToolCallCount}:{},...I.allSuccessfulToolResultsSafeForResume?{allSuccessfulToolResultsSafeForResume:!0}:{},emptyFinalCorrectionSpent:I.emptyFinalCorrectionSpent};let g=K.filter((u)=>f.includes(u)),x=g.filter((u)=>!V.has(u));X=g;let R=new Set(V);for(let u of g)R.add(u);let i=I.inputMessageIds.filter((u)=>!R.has(u)),W0=I.hadSuccessfulToolResult||I.interruptedToolCallCount>0;Q=i.length>0||W0?{turnId:Z.turnId,outcome:"aborted",inputMessageIds:i,hadSuccessfulToolResult:I.hadSuccessfulToolResult,...I.interruptedToolCallCount>0?{interruptedToolCallCount:I.interruptedToolCallCount}:{},...I.allSuccessfulToolResultsSafeForResume?{allSuccessfulToolResultsSafeForResume:!0}:{},emptyFinalCorrectionSpent:I.emptyFinalCorrectionSpent}:void 0;let{acknowledgedInputMessageIds:j0,...l}=Z;return[this.createEvent("turn_aborted",$,{...l,...g.length>0?{acknowledgedInputMessageIds:g}:{},recovery:I}),...x.length>0?[this.createEvent("inbox_acknowledged",$,{messageIds:x,acknowledgedAt:Z.abortedAt})]:[]]})}catch(H){if(!(H instanceof O0))throw H}return{...Q?{recovery:Q}:{},acknowledgedInputMessageIds:X}}async loadInterruptedToolCalls($){let Z=await this.loadEvents($);if(!Z)return[];let J=F0(Z),W=w$(J).active;return W?p$(J,W.turnId).orphaned.map((Y)=>({...Y,input:structuredClone(Y.input)})):[]}async hasRecoverableTurn($){let Z=await this.loadEvents($);if(!Z)return!1;let J=F0(Z),W=w$(J).active;if(W){let Y=p$(J,W.turnId);if(Y.orphaned.length>0||Y.hadSuccessfulResult)return!0;if(N2(J,W.turnId))return!0}return j1(J)!==void 0}async loadBackgroundTaskChildIds($){let Z=await this.loadEvents($);if(!Z)return new Set;let J=F0(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=F0(W),K=w$(Y).active,Q=p$(Y);if(!K&&Q.orphaned.length===0){if(J=j1(Y),J)return[];throw new O0}let X=K?N2(Y,K.turnId):void 0;if(K&&X&&Q.orphaned.length===0){let R=p$(Y,K.turnId);J={turnId:K.turnId,outcome:"completed",inputMessageIds:X.inputMessageIds,hadSuccessfulToolResult:R.hadSuccessfulResult,emptyFinalCorrectionSpent:z6(Y,K.turnId),finalization:X};let i=new Set(Y.flatMap((l)=>l.type==="inbox_acknowledged"?l.data.messageIds:[])),W0=X.inputMessageIds.filter((l)=>!i.has(l)),j0=new Date().toISOString();return[...W0.length>0?[this.createEvent("inbox_acknowledged",$,{messageIds:W0,acknowledgedAt:j0})]:[],this.createEvent("turn_completed",$,{turnId:K.turnId,completedAt:j0,turnsCount:X.turnsCount,toolCallsCount:X.toolCallsCount,durationMs:X.durationMs,...X.usage?{usage:X.usage}:{}})]}let H=K?p$(Y,K.turnId):void 0,z=H?.orphaned.some((R)=>{let i=Z.adoptedToolResults?.get(R.toolCallId);return t1(R,i)&&i?.error===void 0})??!1,V=H?.orphaned.filter((R)=>{let i=Z.adoptedToolResults?.get(R.toolCallId);return i?.toolCallId===R.toolCallId&&i.toolName===R.toolName&&i.error===void 0}).every((R)=>t1(R,Z.adoptedToolResults?.get(R.toolCallId)))??!0,j=new Set(K?.inputMessageIds??[]),B=K?j1(Y):void 0,w=B?B.inputMessageIds.filter((R)=>j.has(R)):[],G=w.length>0,q=K?O2(Y,K.turnId):[],y=H?H.orphaned.filter((R)=>{let i=Z.adoptedToolResults?.get(R.toolCallId);return!t1(R,i)}).length:0,_=G&&B?.hadSuccessfulToolResult===!0,f=(H?.hadSuccessfulResult??!1)||z||_;J=K?{turnId:K.turnId,outcome:"aborted",inputMessageIds:[...new Set([...q,...w])],hadSuccessfulToolResult:f,...(()=>{let R=y+(G?B?.interruptedToolCallCount??0:0);return R>0?{interruptedToolCallCount:R}:{}})(),...f&&!(H?.hadSuccessfulResult??!1)&&V&&(!_||B?.allSuccessfulToolResultsSafeForResume===!0)?{allSuccessfulToolResultsSafeForResume:!0}:{},emptyFinalCorrectionSpent:z6(Y,K.turnId)||G&&B?.emptyFinalCorrectionSpent===!0}:j1(Y);let h=K?H?.all.length??0:0,I=new Date().toISOString(),g=K?Date.parse(K.startedAt):Number.NaN,x=Q.orphaned.flatMap((R)=>{let i=Z.adoptedToolResults?.get(R.toolCallId),W0=t1(R,i)?i:void 0,j0=this.createEvent("part_created",$,{partId:R.toolCallId,messageId:W0?R.messageId:R.toolCallId,partType:"tool_result",payload:W0?{toolCallId:R.toolCallId,toolName:R.toolName,output:W0.output,error:W0.error??null,...W0.metadata===void 0?{}:{metadata:W0.metadata}}:{toolCallId:R.toolCallId,toolName:R.toolName,output:null,error:C8,metadata:{processRestartRecovery:!0,sideEffectsUncertain:!0}},createdAt:I});if(!W0?.subagentRef)return[j0];let l=W0.subagentRef;return[j0,this.createEvent("part_created",$,{partId:V0(),messageId:R.messageId,partType:"subtask_ref",payload:{childSessionId:l.subagentSessionId,agentType:l.subagentType,description:l.subagentDescription??"",status:l.subagentStatus,summary:l.subagentSummary??"",resumedFrom:l.subagentResumedFrom??null,rootAgentId:l.subagentRootId??l.subagentSessionId,resumeDepth:l.subagentResumeDepth??0,verificationVerdict:l.verificationVerdict??null,startedAt:I,finishedAt:I},createdAt:I})]});return K?[...x,this.createEvent("turn_aborted",$,{turnId:K.turnId,cause:"process_restart",abortedAt:I,turnsCount:0,toolCallsCount:h,durationMs:Number.isFinite(g)?Math.max(0,Date.now()-g):0,recovery:J?{version:3,inputMessageIds:J.inputMessageIds,hadSuccessfulToolResult:J.hadSuccessfulToolResult,interruptedToolCallCount:J.interruptedToolCallCount??0,allSuccessfulToolResultsSafeForResume:J.allSuccessfulToolResultsSafeForResume===!0,emptyFinalCorrectionSpent:J.emptyFinalCorrectionSpent}:void 0})]:x})}catch(W){if(!(W instanceof O0))throw W}return J}async loadLatestGoalFinalization($){let Z=await this.loadEvents($);return Z?l8(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((Q)=>Q.type==="review_completed"&&Q.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 Q=new Date().toISOString(),X=W??V0(),H=[];if(!W){let j={messageId:X,role:"assistant",parentMessageId:void 0,createdAt:Q};H.push(this.createEvent("message_created",$,j))}let z=K??V0(),V={partId:z,messageId:X,partType:"tool_call",payload:{toolCallId:z,toolName:Z,input:J},createdAt:Q};if(H.push(this.createEvent("part_created",$,V)),Z==="Task"&&J&&typeof J==="object"){let j=J,B=typeof j.subagent_session_id==="string"?j.subagent_session_id:void 0,w=typeof j.subagent_type==="string"?j.subagent_type:void 0;if(B&&w){let G={partId:V0(),messageId:X,partType:"subtask_ref",payload:{childSessionId:B,agentType:w,status:"running",summary:typeof j.description==="string"?j.description:"",startedAt:Q},createdAt:Q};H.push(this.createEvent("part_created",$,G))}}return await this.log($).commitBatch(H),z}catch(Q){throw console.error(`[PersistentStore] 保存工具调用失败 (session: ${$}):`,Q),Q}}async saveToolResult($,Z,J,W,Y=null,K,Q,X,H){try{await this.ensureSessionCreated($,Q);let z=new Date().toISOString(),V=Y??V0();return await this.log($).commitValidatedBatch((j)=>{let B=X?.subagentStatus==="running"?F0(j).findLast((f)=>f.type==="part_created"&&f.data.partType==="subtask_ref"&&f.data.payload!==null&&typeof f.data.payload==="object"&&!Array.isArray(f.data.payload)&&f.data.payload.childSessionId===X.subagentSessionId&&(f.data.payload.status==="completed"||f.data.payload.status==="failed"||f.data.payload.status==="cancelled")):void 0,w=B?.data.payload,G=H&&typeof H==="object"&&!Array.isArray(H)?H:{},q=w?{...G,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,y=[];if(!Y){let f={messageId:V,role:"assistant",parentMessageId:void 0,createdAt:z};y.push(this.createEvent("message_created",$,f))}let _={partId:Z,messageId:V,partType:"tool_result",payload:{toolCallId:Z,toolName:J,output:W,error:K??null,...q===void 0?{}:{metadata:q}},createdAt:z};if(y.push(this.createEvent("part_created",$,_)),X&&!B){let f=X.subagentStatus==="running"?null:z,h={partId:V0(),messageId:V,partType:"subtask_ref",payload:{childSessionId:X.subagentSessionId,agentType:X.subagentType,description:X.subagentDescription??"",status:X.subagentStatus,summary:X.subagentSummary??"",resumedFrom:X.subagentResumedFrom??null,rootAgentId:X.subagentRootId??X.subagentSessionId,resumeDepth:X.subagentResumeDepth??0,verificationVerdict:X.verificationVerdict??null,startedAt:z,finishedAt:f},createdAt:z};y.push(this.createEvent("part_created",$,h))}return y}),Z}catch(z){throw console.error(`[PersistentStore] 保存工具结果失败 (session: ${$}):`,z),z}}async saveCompaction($,Z,J,W=null){try{await this.ensureSessionCreated($);let Y=new Date().toISOString(),K=V0(),Q={messageId:K,role:"system",parentMessageId:W??void 0,createdAt:Y},X=this.buildCompactionMetadata(J),H={partId:V0(),messageId:K,partType:"summary",payload:{text:Z,metadata:X,...J.replacementMessages?{replacementMessages:k2(J.replacementMessages)}:{}},createdAt:Y},z=[this.createEvent("message_created",$,Q),this.createEvent("part_created",$,H)];return await this.log($).commitBatch(z),K}catch(Y){throw console.error(`[PersistentStore] 保存压缩失败 (session: ${$}):`,Y),Y}}async recordTokenBudgetHandoff($,Z){await this.ensureSessionCreated($);let J=e1([]),W=await this.log($).commitValidatedBatch((K)=>{if(J=e1(F0(K)),J.kind!=="none")return[];let Q=new Date().toISOString();return[this.createEvent("token_budget_handoff_recorded",$,{...Z,messageId:`${M2}${V0()}`,createdAt:Q})]});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=e1(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?F0(Z):null}catch{return null}}async deleteSession($){if(this.stateStorage.kind==="acp-remote")throw Error("Remote session deletion requires SessionService");this.initializedSessions.delete($);try{let Z=y2(this.projectPath,$);await new s1(Z).delete(),await $Z.unlink(b2(this.projectPath,$)).catch((W)=>{if(W.code!=="ENOENT")throw W}),await T2(this.projectPath,$,_2());try{let{getProjectionDb:W,removeSessionFromProjection:Y}=await import("./chunk-p36k2e96.js"),K=await W();if(K)Y(K,$,this.projectPath)}catch{}}catch(Z){console.warn(`[PersistentStore] 删除会话失败 (session: ${$}):`,Z)}finally{this.initializedSessions.delete($)}}}function r8($){return/^data:([^;,]+)[;,]/.exec($)?.[1]??null}var h2=131072,j6=new M$;function D6($,Z){return`${n8.resolve($)}\x00${Z}`}function G6($,Z){let J=JSON.stringify($);if(J===void 0)throw Error(`${Z} is not JSON serializable`);if(Buffer.byteLength(J,"utf8")>h2)throw Error(`${Z} exceeds ${h2} bytes`);return JSON.parse(J)}function v2($){if($.type==="askUserQuestion")return"question";if($.type==="mcpElicitation")return"elicitation";if($.type==="permission"||$.type==="mcpSampling")return"permission";return}function a8($,Z){return JSON.stringify($)===JSON.stringify(Z)}function s8($,Z){if($.request.interactionType!=="elicitation")return G6(Z,"Interaction response");return G6({approved:Z.approved,...Z.reason?{reason:Z.reason}:{},...Z.elicitation?{elicitation:{action:Z.elicitation.action}}:{},...Z.openExternalUrl?{openExternalUrl:!0}:{}},"Interaction response")}function C2($){let Z=$.request.details;if(!Z||typeof Z!=="object"||Array.isArray(Z))throw Error(`Invalid durable interaction details: ${$.request.requestId}`);return Z}function t8($){let Z=$.response?.response;if(!Z||typeof Z!=="object"||Array.isArray(Z))throw Error(`Invalid durable interaction response: ${$.request.requestId}`);return Z}function e8($){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(`
|
|
95
|
+
`}function X6($,Z){return $ instanceof Error&&"code"in $&&$.code===Z}function x8($){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 I8($,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!==H6||!("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)||!x8(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 Q="outputSchema"in K&&K.outputSchema!==void 0?o1(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))}:{},...Q?{outputSchema:Q}:{}}});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:H6,sessionId:J,generation:W.generation,messages:Y}}function h8($){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 v8($){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 a1{sessionId;stateStorage;writeFile;lockFile;mutex=new M8;generation=B1();messages=[];constructor($,Z,J,W){this.sessionId=$;this.stateStorage=Z;this.writeFile=J;this.lockFile=W}static async open($,Z,J=D$($),W={}){let Y=new a1(Z,J,W.writeFile??R8,W.lockFile);return await Y.loadAndReconcile(),Y}async enqueue($,Z){return this.mutex.runExclusive(async()=>{let J=await v$(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}],Q=B1(),X=Q6(this.sessionId,Q,K);if(Buffer.byteLength(X)>C$)return{accepted:!1,snapshot:Y};return await this.persistAtPath(K,Q,W,X),{accepted:!0,snapshot:{generation:Q,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 v$(this.stateStorage,this.sessionId,async(W)=>{let Y=await this.readAndReconcileAtPath(W),K=Y.messages.filter((X)=>!Z.has(X.id));if(K.length===Y.messages.length&&!Y.acknowledgedRemoved)return Y;let Q=B1();return await this.persistAtPath(K,Q,W),{generation:Q,messages:K}},this.lockFile);this.install(J)})}snapshot(){return{generation:this.generation,messages:this.list()}}async refresh(){return this.mutex.runExclusive(async()=>{let $=await v$(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 v$(this.stateStorage,this.sessionId,async(W)=>{let Y=await this.readAndReconcileAtPath(W);if(Y.generation!==$)return{replaced:!1,snapshot:Y};let K=B1(),Q=Z.map((H)=>({...H})),X=Q6(this.sessionId,K,Q);if(Buffer.byteLength(X)>C$)return{replaced:!1,snapshot:Y};return await this.persistAtPath(Q,K,W,X),{replaced:!0,snapshot:{generation:K,messages:Q}}},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 v$(this.stateStorage,this.sessionId,async(Z)=>{let J=await this.readAndReconcileAtPath(Z);if(J.migrationRequired||J.acknowledgedRemoved){let W=B1();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 Q=await I0.open($.inboxPath,"r");try{if((await Q.stat()).size>C$)throw Error(`Steering inbox exceeds ${C$} bytes: ${$.inboxPath}`);Z=I8(await Q.readFile("utf8"),$.inboxPath,this.sessionId)}finally{await Q.close()}await I0.chmod($.inboxPath,384)}catch(Q){if(!X6(Q,"ENOENT"))throw Q}let J=new Set,W=new Set;try{let Q=U2(await I0.readFile($.transcriptPath,"utf8"),$.transcriptPath);J=h8(Q),W=v8(Q)}catch(Q){if(!X6(Q,"ENOENT"))throw Q}let Y=new Map(this.messages.map((Q)=>[Q.id,Q.recovered])),K=(Z?.messages??[]).filter((Q)=>!J.has(Q.id)).map((Q)=>({...Q,recovered:Y.get(Q.id)??!0,...Q.persisted===!0||W.has(Q.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 I0.mkdir(G2.dirname(J.inboxPath),{recursive:!0,mode:448}),$.length===0){await I0.unlink(J.inboxPath).catch((K)=>{if(!X6(K,"ENOENT"))throw K});return}let Y=W??Q6(this.sessionId,Z,$);if(Buffer.byteLength(Y)>C$)throw Error(`Steering inbox exceeds ${C$} bytes: ${J.inboxPath}`);await this.writeFile(J.inboxPath,Y,{encoding:"utf8",mode:384,fsync:!0})}}import*as $Z from"node:fs/promises";import{nanoid as V0}from"nanoid";var L2=256;class w0{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=D$(Z)){let W=j$(J,$),Y=w0.instances.get(W);if(!Y)Y=new w0($,Z,J),w0.instances.set(W,Y),w0.pruneIdleInstances(W);else w0.instances.delete(W),w0.instances.set(W,Y);return Y}static release($,Z,J=D$(Z)){w0.instances.delete(j$(J,$))}static pruneIdleInstances($){if(w0.instances.size<=L2)return;for(let[Z,J]of w0.instances){if(Z===$||J.subscribers.size>0)continue;if(w0.instances.delete(Z),w0.instances.size<=L2)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($),w0.pruneIdleInstances()}}async replay($,Z){let J=await this.withStore(async(W,Y,K)=>{let Q=Y?await W.readAllValidated(Y):await W.readAll();return K(Q),Q.filter((X)=>(X.seq??0)>=Z)});for(let W of J){if(V6(W))continue;await $.onCommitted(W)}}record($){if(typeof $.seq==="number"&&$.seq>this.highestSeq)this.highestSeq=$.seq;if(V6($))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 r1(this.storage,this.sessionId,async(Z)=>{let J=new s1(Z.transcriptPath);if(!Z.remoteScope)return $(J,void 0,()=>{return});let W=Z.remoteScope;return $(J,{noFollow:!0,validateHandle:async(Q)=>{await q2(W,Z.transcriptPath,Q)}},(Q)=>{F2(Q,this.sessionId,this.projectPath,this.storage.kind==="acp-remote"?this.storage.descriptor:void 0)})})}}function w$($){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 O0 extends Error{}var C8="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 z6($,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 O2($,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,Q=Y.data.inboxMessageId!==void 0?Y.data.inboxMessageId:K!==null&&typeof K==="object"&&!Array.isArray(K)?K.inboxMessageId:void 0;if(typeof Q==="string"&&Q.length>0&&Q.length<=K6)W.push(Q)}return[...new Set(W)]}function R2($){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 p8($,Z){let J=$.findLastIndex((X)=>X.type==="turn_started"&&X.data.turnId===Z);if(J<0)return 0;let W=$.findIndex((X,H)=>H>J&&X.type==="turn_started"&&X.data.turnId!==Z),Y=$.slice(J+1,W<0?void 0:W),K=new Set(Y.flatMap((X)=>{if(X.type!=="part_created"||X.data.partType!=="tool_call")return[];let H=X.data.payload;return H&&typeof H==="object"&&!Array.isArray(H)?[typeof H.toolCallId==="string"?H.toolCallId:X.data.partId]:[X.data.partId]})),Q=new Set;for(let X of Y){if(X.type!=="part_created"||X.data.partType!=="tool_result")continue;let H=X.data.payload;if(!H||typeof H!=="object"||Array.isArray(H))continue;let z=typeof H.toolCallId==="string"?H.toolCallId:X.data.partId,V=H.metadata;if(K.has(z)&&V&&typeof V==="object"&&!Array.isArray(V)&&V.processRestartRecovery===!0&&V.sideEffectsUncertain===!0)Q.add(z)}return Q.size}function x2($){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 B6($,Z,J=[]){let W=R2(Z.data.recovery);if(!W)return;if($.some((X)=>X.type==="turn_recovery_acknowledged"&&X.data.turnId===Z.data.turnId))return;let Y=x2($);for(let X of J)Y.add(X);let K=W.inputMessageIds.filter((X)=>!Y.has(X)),Q=W.version===1?p8($,Z.data.turnId):W.interruptedToolCallCount;if(K.length===0&&!W.hadSuccessfulToolResult&&Q===0)return;return{turnId:Z.data.turnId,outcome:"aborted",inputMessageIds:K,hadSuccessfulToolResult:W.hadSuccessfulToolResult,...Q>0?{interruptedToolCallCount:Q}:{},...W.version===3&&W.allSuccessfulToolResultsSafeForResume===!0?{allSuccessfulToolResultsSafeForResume:!0}:{},emptyFinalCorrectionSpent:W.emptyFinalCorrectionSpent}}function j1($){for(let Z=$.length-1;Z>=0;Z--){let J=$[Z];if(J.type!=="turn_aborted")continue;let W=B6($,J);if(W)return W}return}function t1($,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:Q,description:X}=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 X==="string"&&Y.subagentDescription===X&&W.description===X&&(Q===void 0||typeof Q==="string"&&Q===Y.subagentType)&&W.subagentType===Y.subagentType&&W.subagentStatus===Y.subagentStatus&&H&&W.processRestartRecovery===!0&&W.subagentResultAdopted===!0&&W.sideEffectsUncertain===!1}var g8=1e4,m8=1e5,u8=2592000000,P2=128,d8=1e6,c8=256;function i8($){if(!$||typeof $!=="object"||Array.isArray($))return;let Z=$;if(typeof Z.goalId!=="string"||Z.goalId.length===0||Z.goalId.length>P2||typeof Z.verificationAttempt!=="number"||!Number.isSafeInteger(Z.verificationAttempt)||Z.verificationAttempt<1||Z.verificationAttempt>d8||typeof Z.verifierSessionId!=="string"||Z.verifierSessionId.length===0||Z.verifierSessionId.length>P2||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 I2($,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,Q=Y.inputMessageIds,X=Y.turnsCount,H=Y.toolCallsCount,z=Y.durationMs,V=Array.isArray(Q)?Q.filter((w)=>typeof w==="string"&&w.length>0&&w.length<=K6):[];if(typeof K!=="string"||K.length===0||K.length>128||Z!==void 0&&K!==Z||!Array.isArray(Q)||Q.length>j2||V.length!==Q.length||typeof X!=="number"||!Number.isSafeInteger(X)||X<0||X>g8||typeof H!=="number"||!Number.isSafeInteger(H)||H<0||H>m8||typeof z!=="number"||!Number.isSafeInteger(z)||z<0||z>u8)return;let j;if("goalFinalization"in Y){if(j=i8(Y.goalFinalization),!j)return}let B=X2(Y.usage);return{turnId:K,inputMessageIds:[...new Set(V)],turnsCount:X,toolCallsCount:H,durationMs:z,...B?{usage:B}:{},...j?{goalFinalization:j}:{}}}function N2($,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=I2(Y,Z);if(K)return K}return}function l8($){for(let Z=$.length-1;Z>=0;Z--){let J=$[Z];if(J?.type!=="message_created")continue;let W=I2(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 p$($,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,Q=new Set;for(let H of $.slice(J+1)){if(H.type==="interaction_requested"){Q.add(H.data.toolCallId);continue}if(H.type!=="part_created")continue;let z=H.data.payload&&typeof H.data.payload==="object"&&!Array.isArray(H.data.payload)?H.data.payload:{},V=typeof z.toolCallId==="string"?z.toolCallId:H.data.partId;if(H.data.partType==="tool_call")W.set(V,{toolCallId:V,messageId:H.data.messageId,toolName:typeof z.toolName==="string"?z.toolName:"unknown",input:z.input??null});else if(H.data.partType==="tool_result"){if(Y.add(V),Y.add(H.data.partId),Y.add(H.data.messageId),W.has(V)&&z.error===null)K.add(V)}}let X=[...W.values()];return{all:X,orphaned:X.filter((H)=>!Y.has(H.toolCallId)&&!Q.has(H.toolCallId)),hadSuccessfulResult:X.some((H)=>K.has(H.toolCallId))}}class b0{static sessionInitializationRuns=new Map;projectPath;version;stateStorage;initializedSessions=new Set;constructor($=H0(),Z=E2(),J=D$($)){this.projectPath=$,this.version=Z,this.stateStorage=J}createEvent($,Z,J){return{id:V0(),sessionId:Z,projectPath:this.projectPath,timestamp:new Date().toISOString(),type:$,cwd:this.projectPath,...this.stateStorage.kind==="local"?{gitBranch:A2(this.projectPath)}:{},version:this.version,data:J}}log($){return w0.for($,this.projectPath,this.stateStorage)}async ensureSessionCreated($,Z){let J=j$(this.stateStorage,$);if(this.initializedSessions.delete($)){this.initializedSessions.add($);return}let W=b0.sessionInitializationRuns.get(J);if(!W)W=this.initializeSessionFile($,Z),b0.sessionInitializationRuns.set(J,W);try{await W,this.rememberInitializedSession($)}finally{if(b0.sessionInitializationRuns.get(J)===W)b0.sessionInitializationRuns.delete(J)}}rememberInitializedSession($){this.initializedSessions.delete($),this.initializedSessions.add($);while(this.initializedSessions.size>c8){let Z=this.initializedSessions.values().next().value;if(Z===void 0)return;this.initializedSessions.delete(Z)}}async initializeSessionFile($,Z){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 W=new Date().toISOString(),Y={sessionId:$,rootId:Z?.parentSessionId??$,parentId:Z?.parentSessionId,relationType:Z?"subagent":void 0,resumedFrom:Z?.resumedFrom,rootAgentId:Z?.rootAgentId,resumeDepth:Z?.resumeDepth,title:void 0,status:"running",taskStatus:Z?"running":"queued",taskFailure:null,agentType:Z?.subagentType,model:void 0,permission:void 0,createdAt:W,updatedAt:W},K=this.createEvent("session_created",$,Y);await this.log($).commit(K)}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=f2;return Z}async initialize(){try{await S2(this.stateStorage,async($)=>{if(this.stateStorage.kind==="local")await $Z.mkdir($,{recursive:!0,mode:493})})}catch($){console.warn("[PersistentStore] 无法创建持久化存储目录:",$)}}async saveMessage($,Z,J,W=null,Y,K,Q){try{await this.ensureSessionCreated($,K);let X=new Date().toISOString(),H=V0(),z={messageId:H,role:Z,parentMessageId:W??void 0,inboxMessageId:Y?.inboxMessageId,createdAt:X,model:Y?.model,usage:Y?.usage,metadata:Y?JSON.parse(JSON.stringify(Y)):void 0},V=this.createEvent("message_created",$,z),j=Z==="assistant"&&Q?.trim()?[this.createEvent("part_created",$,{partId:V0(),messageId:H,partType:"reasoning",payload:{text:Q},createdAt:X})]:[],B=typeof J==="string"?[this.createEvent("part_created",$,{partId:V0(),messageId:H,partType:"text",payload:{text:J,...Y?.conversationRecap?{conversationRecap:!0}:{}},createdAt:X})]:J.map((w)=>this.createEvent("part_created",$,{partId:V0(),messageId:H,partType:w.type==="text"?"text":"image",payload:w.type==="text"?{text:w.text}:{mimeType:r8(w.image_url.url)??"image/png",dataUrl:w.image_url.url},createdAt:X}));return await this.log($).commitBatch([V,...j,...B]),H}catch(X){throw console.error(`[PersistentStore] 保存消息失败 (session: ${$}):`,X),X}}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=F0(J);if(W.some((K)=>K.type==="turn_recovery_acknowledged"&&K.data.turnId===Z))throw new O0;let Y=W.findLast((K)=>K.type==="turn_aborted"&&K.data.turnId===Z);if(!Y||!B6(W,Y))throw new O0;return this.createEvent("turn_recovery_acknowledged",$,{turnId:Z,acknowledgedAt:new Date().toISOString()})})}catch(J){if(!(J instanceof O0))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=F0(W),K=Y.some((B)=>B.type==="inbox_acknowledged"&&B.data.messageIds.includes(Z.inboxMessageId)),Q=Y.find((B)=>B.type==="message_created"&&B.data.inboxMessageId===Z.inboxMessageId),X=Y.findLast((B)=>{if(B.type!=="part_created"||B.data.partType!=="tool_call"||!B.data.payload||typeof B.data.payload!=="object"||Array.isArray(B.data.payload))return!1;let w=B.data.payload;if(w.toolName!=="Task"||!w.input||typeof w.input!=="object"||Array.isArray(w.input))return!1;let G=w.input,q=G.resume_from??G.resume;return G.run_in_background===!0&&G.subagent_session_id===Z.childSessionId&&G.description===Z.subagentRef.subagentDescription&&(G.subagent_type===void 0||G.subagent_type===Z.subagentRef.subagentType)&&(G.resume_from===void 0||G.resume===void 0||G.resume_from===G.resume)&&(q===void 0?Z.subagentRef.subagentResumedFrom===void 0:q===Z.subagentRef.subagentResumedFrom)});if(!X)return J={eligible:!1,acknowledged:K,persisted:!1,...Q?{messageId:Q.data.messageId}:{}},[];if(K)return J={eligible:!0,acknowledged:!0,persisted:!1,...Q?{messageId:Q.data.messageId}:{}},[];let H=Y.find((B)=>B.type==="part_created"&&B.data.partType==="subtask_ref"&&B.data.payload!==null&&typeof B.data.payload==="object"&&!Array.isArray(B.data.payload)&&B.data.payload.childSessionId===Z.childSessionId&&B.data.payload.status===Z.subagentRef.subagentStatus);if(Q&&H)return J={eligible:!0,acknowledged:!1,persisted:!1,messageId:Q.data.messageId},[];let z=new Date().toISOString(),V=Q?.data.messageId??V0(),j=[];if(!Q){let B={messageId:V,role:"user",inboxMessageId:Z.inboxMessageId,createdAt:z,metadata:JSON.parse(JSON.stringify(Z.metadata))};j.push(this.createEvent("message_created",$,B)),j.push(this.createEvent("part_created",$,{partId:V0(),messageId:V,partType:"text",payload:{text:Z.content},createdAt:z}))}if(!H){let B=Y.findLast((G)=>G.type==="part_created"&&G.data.partType==="subtask_ref"&&G.data.messageId===X.data.messageId&&G.data.payload!==null&&typeof G.data.payload==="object"&&!Array.isArray(G.data.payload)&&G.data.payload.childSessionId===Z.childSessionId),w=B?.data.payload&&typeof B.data.payload==="object"&&!Array.isArray(B.data.payload)?B.data.payload:void 0;j.push(this.createEvent("part_created",$,{partId:V0(),messageId:X.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:z,finishedAt:z},createdAt:z}))}return J={eligible:!0,acknowledged:!1,persisted:j.length>0,messageId:V},j}),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=F0(J);if(W.some((K)=>K.type==="turn_started"&&K.data.turnId===Z.turnId))throw new O0;let Y=w$(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 O0))throw J}}async saveTurnCompletion($,Z,J=[]){await this.ensureSessionCreated($);try{await this.log($).commitValidatedBatch((W)=>{let Y=F0(W),K=new Set(Y.flatMap((z)=>z.type==="inbox_acknowledged"?z.data.messageIds:[])),Q=[...new Set(J)].filter((z)=>!K.has(z)),X=Y.findLast((z)=>(z.type==="turn_completed"||z.type==="turn_aborted")&&z.data.turnId===Z.turnId);if(X){if(X.type==="turn_aborted"||Q.length===0)throw new O0;return[this.createEvent("inbox_acknowledged",$,{messageIds:Q,acknowledgedAt:Z.completedAt})]}let H=w$(Y).active;if(!H||H.turnId!==Z.turnId)throw Error(`Turn is not active: ${Z.turnId}`);return[...Q.length>0?[this.createEvent("inbox_acknowledged",$,{messageIds:Q,acknowledgedAt:Z.completedAt})]:[],this.createEvent("turn_completed",$,Z)]})}catch(W){if(!(W instanceof O0))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 Q,X=[];try{await this.log($).commitValidatedBatch((H)=>{let z=F0(H),V=x2(z),j=z.findLast((u)=>(u.type==="turn_completed"||u.type==="turn_aborted")&&u.data.turnId===Z.turnId);if(j){if(j.type==="turn_completed")throw Q=void 0,X=[],new O0;let u=R2(j.data.recovery),k0=u?K.filter((r)=>u.inputMessageIds.includes(r)):[],P0=k0.filter((r)=>!V.has(r));if(X=k0,Q=B6(z,j,k0),P0.length===0)throw new O0;return[this.createEvent("inbox_acknowledged",$,{messageIds:P0,acknowledgedAt:Z.abortedAt})]}let B=w$(z).active;if(!B||B.turnId!==Z.turnId)throw Error(`Turn is not active: ${Z.turnId}`);let w=p$(z,B.turnId),G=O2(z,B.turnId),q=j1(z),y=new Set(Z.recovery?.inputMessageIds??[]),_=q?q.inputMessageIds.filter((u)=>y.has(u)):[],f=[...new Set([...G,..._])],h=w.hadSuccessfulResult||Z.recovery?.hadSuccessfulToolResult===!0,I={version:3,inputMessageIds:f,hadSuccessfulToolResult:h,interruptedToolCallCount:w.orphaned.length+(Z.recovery?.version===2||Z.recovery?.version===3?Z.recovery.interruptedToolCallCount:0),allSuccessfulToolResultsSafeForResume:h&&!w.hadSuccessfulResult&&Z.recovery?.version===3&&Z.recovery.hadSuccessfulToolResult&&Z.recovery.allSuccessfulToolResultsSafeForResume,emptyFinalCorrectionSpent:z6(z,B.turnId)||Z.recovery?.emptyFinalCorrectionSpent===!0};Q={turnId:Z.turnId,outcome:"aborted",inputMessageIds:I.inputMessageIds,hadSuccessfulToolResult:I.hadSuccessfulToolResult,...I.interruptedToolCallCount>0?{interruptedToolCallCount:I.interruptedToolCallCount}:{},...I.allSuccessfulToolResultsSafeForResume?{allSuccessfulToolResultsSafeForResume:!0}:{},emptyFinalCorrectionSpent:I.emptyFinalCorrectionSpent};let g=K.filter((u)=>f.includes(u)),x=g.filter((u)=>!V.has(u));X=g;let R=new Set(V);for(let u of g)R.add(u);let i=I.inputMessageIds.filter((u)=>!R.has(u)),W0=I.hadSuccessfulToolResult||I.interruptedToolCallCount>0;Q=i.length>0||W0?{turnId:Z.turnId,outcome:"aborted",inputMessageIds:i,hadSuccessfulToolResult:I.hadSuccessfulToolResult,...I.interruptedToolCallCount>0?{interruptedToolCallCount:I.interruptedToolCallCount}:{},...I.allSuccessfulToolResultsSafeForResume?{allSuccessfulToolResultsSafeForResume:!0}:{},emptyFinalCorrectionSpent:I.emptyFinalCorrectionSpent}:void 0;let{acknowledgedInputMessageIds:j0,...l}=Z;return[this.createEvent("turn_aborted",$,{...l,...g.length>0?{acknowledgedInputMessageIds:g}:{},recovery:I}),...x.length>0?[this.createEvent("inbox_acknowledged",$,{messageIds:x,acknowledgedAt:Z.abortedAt})]:[]]})}catch(H){if(!(H instanceof O0))throw H}return{...Q?{recovery:Q}:{},acknowledgedInputMessageIds:X}}async loadInterruptedToolCalls($){let Z=await this.loadEvents($);if(!Z)return[];let J=F0(Z),W=w$(J).active;return W?p$(J,W.turnId).orphaned.map((Y)=>({...Y,input:structuredClone(Y.input)})):[]}async hasRecoverableTurn($){let Z=await this.loadEvents($);if(!Z)return!1;let J=F0(Z),W=w$(J).active;if(W){let Y=p$(J,W.turnId);if(Y.orphaned.length>0||Y.hadSuccessfulResult)return!0;if(N2(J,W.turnId))return!0}return j1(J)!==void 0}async loadBackgroundTaskChildIds($){let Z=await this.loadEvents($);if(!Z)return new Set;let J=F0(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=F0(W),K=w$(Y).active,Q=p$(Y);if(!K&&Q.orphaned.length===0){if(J=j1(Y),J)return[];throw new O0}let X=K?N2(Y,K.turnId):void 0;if(K&&X&&Q.orphaned.length===0){let R=p$(Y,K.turnId);J={turnId:K.turnId,outcome:"completed",inputMessageIds:X.inputMessageIds,hadSuccessfulToolResult:R.hadSuccessfulResult,emptyFinalCorrectionSpent:z6(Y,K.turnId),finalization:X};let i=new Set(Y.flatMap((l)=>l.type==="inbox_acknowledged"?l.data.messageIds:[])),W0=X.inputMessageIds.filter((l)=>!i.has(l)),j0=new Date().toISOString();return[...W0.length>0?[this.createEvent("inbox_acknowledged",$,{messageIds:W0,acknowledgedAt:j0})]:[],this.createEvent("turn_completed",$,{turnId:K.turnId,completedAt:j0,turnsCount:X.turnsCount,toolCallsCount:X.toolCallsCount,durationMs:X.durationMs,...X.usage?{usage:X.usage}:{}})]}let H=K?p$(Y,K.turnId):void 0,z=H?.orphaned.some((R)=>{let i=Z.adoptedToolResults?.get(R.toolCallId);return t1(R,i)&&i?.error===void 0})??!1,V=H?.orphaned.filter((R)=>{let i=Z.adoptedToolResults?.get(R.toolCallId);return i?.toolCallId===R.toolCallId&&i.toolName===R.toolName&&i.error===void 0}).every((R)=>t1(R,Z.adoptedToolResults?.get(R.toolCallId)))??!0,j=new Set(K?.inputMessageIds??[]),B=K?j1(Y):void 0,w=B?B.inputMessageIds.filter((R)=>j.has(R)):[],G=w.length>0,q=K?O2(Y,K.turnId):[],y=H?H.orphaned.filter((R)=>{let i=Z.adoptedToolResults?.get(R.toolCallId);return!t1(R,i)}).length:0,_=G&&B?.hadSuccessfulToolResult===!0,f=(H?.hadSuccessfulResult??!1)||z||_;J=K?{turnId:K.turnId,outcome:"aborted",inputMessageIds:[...new Set([...q,...w])],hadSuccessfulToolResult:f,...(()=>{let R=y+(G?B?.interruptedToolCallCount??0:0);return R>0?{interruptedToolCallCount:R}:{}})(),...f&&!(H?.hadSuccessfulResult??!1)&&V&&(!_||B?.allSuccessfulToolResultsSafeForResume===!0)?{allSuccessfulToolResultsSafeForResume:!0}:{},emptyFinalCorrectionSpent:z6(Y,K.turnId)||G&&B?.emptyFinalCorrectionSpent===!0}:j1(Y);let h=K?H?.all.length??0:0,I=new Date().toISOString(),g=K?Date.parse(K.startedAt):Number.NaN,x=Q.orphaned.flatMap((R)=>{let i=Z.adoptedToolResults?.get(R.toolCallId),W0=t1(R,i)?i:void 0,j0=this.createEvent("part_created",$,{partId:R.toolCallId,messageId:W0?R.messageId:R.toolCallId,partType:"tool_result",payload:W0?{toolCallId:R.toolCallId,toolName:R.toolName,output:W0.output,error:W0.error??null,...W0.metadata===void 0?{}:{metadata:W0.metadata}}:{toolCallId:R.toolCallId,toolName:R.toolName,output:null,error:C8,metadata:{processRestartRecovery:!0,sideEffectsUncertain:!0}},createdAt:I});if(!W0?.subagentRef)return[j0];let l=W0.subagentRef;return[j0,this.createEvent("part_created",$,{partId:V0(),messageId:R.messageId,partType:"subtask_ref",payload:{childSessionId:l.subagentSessionId,agentType:l.subagentType,description:l.subagentDescription??"",status:l.subagentStatus,summary:l.subagentSummary??"",resumedFrom:l.subagentResumedFrom??null,rootAgentId:l.subagentRootId??l.subagentSessionId,resumeDepth:l.subagentResumeDepth??0,verificationVerdict:l.verificationVerdict??null,startedAt:I,finishedAt:I},createdAt:I})]});return K?[...x,this.createEvent("turn_aborted",$,{turnId:K.turnId,cause:"process_restart",abortedAt:I,turnsCount:0,toolCallsCount:h,durationMs:Number.isFinite(g)?Math.max(0,Date.now()-g):0,recovery:J?{version:3,inputMessageIds:J.inputMessageIds,hadSuccessfulToolResult:J.hadSuccessfulToolResult,interruptedToolCallCount:J.interruptedToolCallCount??0,allSuccessfulToolResultsSafeForResume:J.allSuccessfulToolResultsSafeForResume===!0,emptyFinalCorrectionSpent:J.emptyFinalCorrectionSpent}:void 0})]:x})}catch(W){if(!(W instanceof O0))throw W}return J}async loadLatestGoalFinalization($){let Z=await this.loadEvents($);return Z?l8(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((Q)=>Q.type==="review_completed"&&Q.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 Q=new Date().toISOString(),X=W??V0(),H=[];if(!W){let j={messageId:X,role:"assistant",parentMessageId:void 0,createdAt:Q};H.push(this.createEvent("message_created",$,j))}let z=K??V0(),V={partId:z,messageId:X,partType:"tool_call",payload:{toolCallId:z,toolName:Z,input:J},createdAt:Q};if(H.push(this.createEvent("part_created",$,V)),Z==="Task"&&J&&typeof J==="object"){let j=J,B=typeof j.subagent_session_id==="string"?j.subagent_session_id:void 0,w=typeof j.subagent_type==="string"?j.subagent_type:void 0;if(B&&w){let G={partId:V0(),messageId:X,partType:"subtask_ref",payload:{childSessionId:B,agentType:w,status:"running",summary:typeof j.description==="string"?j.description:"",startedAt:Q},createdAt:Q};H.push(this.createEvent("part_created",$,G))}}return await this.log($).commitBatch(H),z}catch(Q){throw console.error(`[PersistentStore] 保存工具调用失败 (session: ${$}):`,Q),Q}}async saveToolResult($,Z,J,W,Y=null,K,Q,X,H){try{await this.ensureSessionCreated($,Q);let z=new Date().toISOString(),V=Y??V0();return await this.log($).commitValidatedBatch((j)=>{let B=X?.subagentStatus==="running"?F0(j).findLast((f)=>f.type==="part_created"&&f.data.partType==="subtask_ref"&&f.data.payload!==null&&typeof f.data.payload==="object"&&!Array.isArray(f.data.payload)&&f.data.payload.childSessionId===X.subagentSessionId&&(f.data.payload.status==="completed"||f.data.payload.status==="failed"||f.data.payload.status==="cancelled")):void 0,w=B?.data.payload,G=H&&typeof H==="object"&&!Array.isArray(H)?H:{},q=w?{...G,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,y=[];if(!Y){let f={messageId:V,role:"assistant",parentMessageId:void 0,createdAt:z};y.push(this.createEvent("message_created",$,f))}let _={partId:Z,messageId:V,partType:"tool_result",payload:{toolCallId:Z,toolName:J,output:W,error:K??null,...q===void 0?{}:{metadata:q}},createdAt:z};if(y.push(this.createEvent("part_created",$,_)),X&&!B){let f=X.subagentStatus==="running"?null:z,h={partId:V0(),messageId:V,partType:"subtask_ref",payload:{childSessionId:X.subagentSessionId,agentType:X.subagentType,description:X.subagentDescription??"",status:X.subagentStatus,summary:X.subagentSummary??"",resumedFrom:X.subagentResumedFrom??null,rootAgentId:X.subagentRootId??X.subagentSessionId,resumeDepth:X.subagentResumeDepth??0,verificationVerdict:X.verificationVerdict??null,startedAt:z,finishedAt:f},createdAt:z};y.push(this.createEvent("part_created",$,h))}return y}),Z}catch(z){throw console.error(`[PersistentStore] 保存工具结果失败 (session: ${$}):`,z),z}}async saveCompaction($,Z,J,W=null){try{await this.ensureSessionCreated($);let Y=new Date().toISOString(),K=V0(),Q={messageId:K,role:"system",parentMessageId:W??void 0,createdAt:Y},X=this.buildCompactionMetadata(J),H={partId:V0(),messageId:K,partType:"summary",payload:{text:Z,metadata:X,...J.replacementMessages?{replacementMessages:k2(J.replacementMessages)}:{}},createdAt:Y},z=[this.createEvent("message_created",$,Q),this.createEvent("part_created",$,H)];return await this.log($).commitBatch(z),K}catch(Y){throw console.error(`[PersistentStore] 保存压缩失败 (session: ${$}):`,Y),Y}}async recordTokenBudgetHandoff($,Z){await this.ensureSessionCreated($);let J=e1([]),W=await this.log($).commitValidatedBatch((K)=>{if(J=e1(F0(K)),J.kind!=="none")return[];let Q=new Date().toISOString();return[this.createEvent("token_budget_handoff_recorded",$,{...Z,messageId:`${M2}${V0()}`,createdAt:Q})]});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=e1(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?F0(Z):null}catch{return null}}async deleteSession($){if(this.stateStorage.kind==="acp-remote")throw Error("Remote session deletion requires SessionService");this.initializedSessions.delete($);try{let Z=y2(this.projectPath,$);await new s1(Z).delete(),await $Z.unlink(b2(this.projectPath,$)).catch((W)=>{if(W.code!=="ENOENT")throw W}),await T2(this.projectPath,$,_2());try{let{getProjectionDb:W,removeSessionFromProjection:Y}=await import("./chunk-hb680ebj.js"),K=await W();if(K)Y(K,$,this.projectPath)}catch{}}catch(Z){console.warn(`[PersistentStore] 删除会话失败 (session: ${$}):`,Z)}finally{this.initializedSessions.delete($)}}}function r8($){return/^data:([^;,]+)[;,]/.exec($)?.[1]??null}var h2=131072,j6=new M$;function D6($,Z){return`${n8.resolve($)}\x00${Z}`}function G6($,Z){let J=JSON.stringify($);if(J===void 0)throw Error(`${Z} is not JSON serializable`);if(Buffer.byteLength(J,"utf8")>h2)throw Error(`${Z} exceeds ${h2} bytes`);return JSON.parse(J)}function v2($){if($.type==="askUserQuestion")return"question";if($.type==="mcpElicitation")return"elicitation";if($.type==="permission"||$.type==="mcpSampling")return"permission";return}function a8($,Z){return JSON.stringify($)===JSON.stringify(Z)}function s8($,Z){if($.request.interactionType!=="elicitation")return G6(Z,"Interaction response");return G6({approved:Z.approved,...Z.reason?{reason:Z.reason}:{},...Z.elicitation?{elicitation:{action:Z.elicitation.action}}:{},...Z.openExternalUrl?{openExternalUrl:!0}:{}},"Interaction response")}function C2($){let Z=$.request.details;if(!Z||typeof Z!=="object"||Array.isArray(Z))throw Error(`Invalid durable interaction details: ${$.request.requestId}`);return Z}function t8($){let Z=$.response?.response;if(!Z||typeof Z!=="object"||Array.isArray(Z))throw Error(`Invalid durable interaction response: ${$.request.requestId}`);return Z}function e8($){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
96
|
`)}function $9($,Z){let{request:J}=$;if(J.interactionType==="question"){let Q=e8(Z);return{toolOutput:`User answers:
|
|
97
97
|
${Q}`,inbox:`The process restarted while waiting for a structured answer. The recovered user response is:
|
|
98
98
|
${Q}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as T,b as W,c as X,d as Y}from"./chunk-
|
|
1
|
+
import{a as T,b as W,c as X,d as Y}from"./chunk-7m07qp5c.js";import"./chunk-5ce8ydjq.js";import"./chunk-870szc6v.js";import"./chunk-js7fre4w.js";import"./chunk-49jbxty9.js";import"./chunk-vv6r417h.js";import"./chunk-phch3t6v.js";import"./chunk-nad5spvc.js";import"./chunk-v5t3kcac.js";import"./chunk-whxkwaz1.js";import"./chunk-hfbw50pk.js";import"./chunk-9qxch6sy.js";import"./chunk-hbkpavbp.js";import"./chunk-skktstg8.js";import"./chunk-s14zayxp.js";import"./chunk-b5cz00mt.js";import{Ef as R}from"./chunk-rwm2e0r4.js";import"./chunk-crv3sghv.js";import{_f as Q}from"./chunk-5kmxe14c.js";import"./chunk-x6k5ye1z.js";import"./chunk-v508x7cg.js";import"./chunk-1g7c3f82.js";import"./chunk-3v9epq9s.js";import"./chunk-eexs73bz.js";import"./chunk-pm163dfm.js";import"./chunk-w8dxjbm8.js";import"./chunk-e4q0rcmz.js";import"./chunk-kehgewqh.js";import"./chunk-kkzznz4w.js";import"./chunk-1cy4ab77.js";import"./chunk-7ajvrtb3.js";import"./chunk-egqep8py.js";import"./chunk-ys8gysg8.js";import"./chunk-r9egmztq.js";import"./chunk-b22ab7yw.js";import"./chunk-amabfzc8.js";import"./chunk-m2x6pb4f.js";import"./chunk-saz6mwpq.js";import"./chunk-xhwdac1j.js";import"./chunk-0eajnhrj.js";import{Xj as M}from"./chunk-c33wff11.js";import"./chunk-asgmmaec.js";import"./chunk-ed2hdrwe.js";import"./chunk-gmpsfkgg.js";import m from"chalk";import K from"open";var A=`
|
|
2
2
|
____ _ _
|
|
3
3
|
| __ )| | __ _ __| | ___
|
|
4
4
|
| _ \\| |/ _\` |/ _\` |/ _ \\
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{M as N,ka as _,la as z}from"./chunk-r9nyzqzb.js";import{$d as R,Xc as I,Zd as g,cd as x,dd as X,ed as B,fd as V,gd as b,wd as A}from"./chunk-faedrfhd.js";import{Di as M,Ei as O}from"./chunk-qy6p8bpr.js";import{Mutex as j}from"async-mutex";class C extends Error{limit;resource="resident_runtimes";retryable=!0;constructor(q){super("Session runtime capacity is full");this.limit=q;this.name="SessionRuntimeCapacityError"}}class W extends Error{constructor(){super("Session runtime residency is closed");this.name="SessionRuntimeResidencyClosedError"}}class Y extends Error{constructor(q){super(`Session runtime residency already owns key: ${q}`);this.name="SessionRuntimeResidencyConflictError"}}class k{maxResident;idleMs;now;residents=new Map;reservations=new Map;operations=new j;nextGeneration=1;closed=!1;constructor(q){if(!M(q.maxResident))throw Error("Invalid max resident Session Runtime limit");if(!O(q.idleMs))throw Error("Invalid Session Runtime idle timeout");this.maxResident=q.maxResident,this.idleMs=q.idleMs,this.now=q.now??Date.now}acquire(q){let $=this.residents.get(q);if(!$||$.poisoned)return;return $.pins++,$.lastUsedAt=this.now(),this.createLease($)}owns(q,$){let Q=this.residents.get(q);return Boolean(Q&&($===void 0||Q.value===$))}async reserve(q,$){if(!q.trim())throw Error("Session runtime residency key must not be blank");return this.operations.runExclusive(async()=>{if(this.closed)throw new W;if(this.residents.has(q)||this.reservations.has(q))throw new Y(q);while(this.retainedCount()>=this.maxResident){if(!$.allowEviction)throw new C(this.maxResident);let P=this.oldestEvictableWebResident();if(!P)throw new C(this.maxResident);await this.disposeResident(P,!0)}let Q={generation:this.allocateGeneration(),surface:$.surface};return this.reservations.set(q,Q),this.createReservation(q,Q)})}async remove(q,$){return this.operations.runExclusive(async()=>{let Q=this.residents.get(q);if(!Q||$!==void 0&&Q.value!==$)return!1;if(Q.pins>0)return!1;return await this.disposeResident(Q,!0),!0})}async forget(q,$){return this.operations.runExclusive(async()=>{let Q=this.residents.get(q);if(!Q||$!==void 0&&Q.value!==$||Q.pins>0)return!1;return this.residents.delete(q),!0})}async sweepIdle(){return this.operations.runExclusive(async()=>{if(this.closed)return 0;let q=0;while(!0){let $=this.oldestIdleWebResident();if(!$)return q;await this.disposeResident($,!0),q++}})}async disposeAll(){await this.operations.runExclusive(async()=>{this.closed=!0,this.reservations.clear();let q;for(let $ of[...this.residents.values()])try{await this.disposeResident($,!1)}catch(Q){q??=Q}if(this.residents.clear(),q!==void 0)throw q})}getStats(){let q=0;for(let $ of this.residents.values())if($.pins>0)q++;return{resident:this.residents.size,reserved:this.reservations.size,pinned:q,maxResident:this.maxResident}}retainedCount(){return this.residents.size+this.reservations.size}allocateGeneration(){let q=this.nextGeneration;return this.nextGeneration=this.nextGeneration===Number.MAX_SAFE_INTEGER?1:this.nextGeneration+1,q}createReservation(q,$){let Q=!1;return{commit:(P)=>{if(Q)throw new Y(q);if(P.key!==q||P.surface!==$.surface||this.reservations.get(q)!==$||this.closed)throw this.reservations.delete(q),Q=!0,this.closed?new W:new Y(q);this.reservations.delete(q);let L={...P,generation:$.generation,pins:1,lastUsedAt:this.now(),poisoned:!1};return this.residents.set(q,L),Q=!0,this.createLease(L)},cancel:()=>{if(Q)return;if(this.reservations.get(q)===$)this.reservations.delete(q);Q=!0}}}createLease(q){let $=!1;return{value:q.value,release:()=>{if($)return;$=!0;let Q=this.residents.get(q.key);if(Q!==q||Q.generation!==q.generation)return;Q.pins=Math.max(0,Q.pins-1),Q.lastUsedAt=this.now()}}}oldestEvictableWebResident(){return this.sortedWebResidents().find((q)=>this.canEvict(q))}oldestIdleWebResident(){let q=this.now();return this.sortedWebResidents().find(($)=>q-$.lastUsedAt>=this.idleMs&&this.canEvict($))}sortedWebResidents(){return[...this.residents.values()].filter((q)=>q.surface==="web").sort((q,$)=>q.lastUsedAt-$.lastUsedAt||q.generation-$.generation)}canEvict(q){if(q.pins>0||q.poisoned)return!1;try{return q.canEvict()}catch{return!1}}async disposeResident(q,$){if(this.residents.get(q.key)!==q)return;this.residents.delete(q.key);try{await q.dispose()}catch(Q){if($&&!this.closed&&!this.residents.has(q.key))q.lastUsedAt=this.now(),q.poisoned=!0,this.residents.set(q.key,q);throw Q}}}function f(q){if(!q||typeof q!=="object"||Array.isArray(q))return;let $=q,{code:Q,kind:P,limit:L,reason:D,scope:J}=$;if(Q!=="tool_busy"&&Q!=="tool_batch_full"||D!=="queue_full"&&D!=="wait_timeout"&&D!=="turn_limit"||J!=="global"&&J!=="session"||typeof $.retryable!=="boolean"||!Number.isSafeInteger(L)||L<=0||P!==void 0&&P!=="readonly"&&P!=="write"&&P!=="execute")return;return{code:Q,reason:D,scope:J,retryable:$.retryable,...P===void 0?{}:{kind:P},limit:L}}function T(q,$){if(!$||typeof $!=="object")return $;let Q={...$},P=f(Q.tool_admission);if(P)Q.tool_admission=P;else delete Q.tool_admission;if(N(q)){let J=Q.browser&&typeof Q.browser==="object"&&!Array.isArray(Q.browser)?Q.browser:{},h={},G=(Z,F,K)=>{let H=J[Z];if(typeof H==="string"&&Buffer.byteLength(H)<=F&&(!K||K.test(H)))h[Z]=H};if(G("action",64),G("status",16,/^(?:ok|warning|error)$/),G("pageId",V,/^browser_page_[a-f0-9-]+$/),G("snapshotId",V,/^browser_snapshot_[a-f0-9-]+$/),G("origin",X),G("candidateOrigin",X),G("url",x),G("title",B),G("errorCode",64,/^browser_[a-z_]+$/),typeof J.truncated==="boolean")h.truncated=J.truncated;if(typeof J.actionApplied==="boolean"||J.actionApplied==="unknown")h.actionApplied=J.actionApplied;if(typeof J.sideEffectsUncertain==="boolean")h.sideEffectsUncertain=J.sideEffectsUncertain;if(typeof J.diagnosticCount==="number"&&Number.isSafeInteger(J.diagnosticCount)&&J.diagnosticCount>=0&&J.diagnosticCount<=I)h.diagnosticCount=J.diagnosticCount;if(J.interaction&&typeof J.interaction==="object"&&!Array.isArray(J.interaction)){let Z=J.interaction,F=new Set(["click","hover","fill","type","press","select","check","uncheck","scroll"]);if(typeof Z.action==="string"&&F.has(Z.action)){let K={action:Z.action};if(typeof Z.ref==="string"&&Buffer.byteLength(Z.ref)<=b&&/^[a-z][a-z0-9]*$/.test(Z.ref))K.ref=Z.ref;let H=(U,E,S)=>typeof U==="number"&&Number.isFinite(U)&&U>=E&&U<=S;if(Z.viewport&&typeof Z.viewport==="object"&&!Array.isArray(Z.viewport)){let U=Z.viewport;if(H(U.width,1,16384)&&H(U.height,1,16384))K.viewport={width:U.width,height:U.height}}if(Z.targetBox&&typeof Z.targetBox==="object"&&!Array.isArray(Z.targetBox)){let U=Z.targetBox;if(H(U.x,-16384,32768)&&H(U.y,-16384,32768)&&H(U.width,0,16384)&&H(U.height,0,16384))K.targetBox={x:U.x,y:U.y,width:U.width,height:U.height}}h.interaction=K}}if(J.artifact&&typeof J.artifact==="object"&&!Array.isArray(J.artifact)){let Z=J.artifact;if(typeof Z.id==="string"&&/^[a-f0-9]{64}$/.test(Z.id)&&Z.sha256===Z.id&&Z.kind==="image"&&Z.mimeType==="image/png"&&typeof Z.size==="number"&&Number.isSafeInteger(Z.size)&&Z.size>=0&&Z.size<=A&&Z.persisted===!0)h.artifact={id:Z.id,sha256:Z.sha256,kind:Z.kind,mimeType:Z.mimeType,size:Z.size,persisted:!0,...typeof Z.path==="string"&&Buffer.byteLength(Z.path)<=8192?{path:Z.path}:{}}}return{...typeof Q.summary==="string"?{summary:Q.summary.slice(0,512)}:{},browser:h,...P?{tool_admission:P}:{}}}if(q==="Bash"){let J={},h=["message","signal","status","summary"],G=["aborted","acp_mode","admission_failed","auto_backgrounded","background","capture_truncated","finalization_failed","has_stderr","output_accounting_complete","output_truncated","projection_truncated","sandbox_required","sandboxed","stderr_projection_truncated","stdout_projection_truncated","terminal_output_merged","timeout"],Z=["execution_time","foreground_budget_ms","pid","raw_output_bytes","stderr_length","stderr_omitted_bytes","stderr_retained_bytes","stderr_total_bytes","stdout_length","stdout_omitted_bytes","stdout_retained_bytes","stdout_total_bytes"];for(let K of h){let H=Q[K];if(typeof H==="string")J[K]=H.slice(0,8192)}for(let K of G){let H=Q[K];if(typeof H==="boolean")J[K]=H}for(let K of Z){let H=Q[K];if(typeof H==="number"&&Number.isSafeInteger(H)&&H>=0)J[K]=H}if(Q.exit_code===null||typeof Q.exit_code==="number"&&Number.isSafeInteger(Q.exit_code))J.exit_code=Q.exit_code;if(Q.terminal_transport==="local"||Q.terminal_transport==="acp"||Q.terminal_transport==="local_fallback")J.terminal_transport=Q.terminal_transport;if(Q.background_reason==="explicit"||Q.background_reason==="foreground_budget")J.background_reason=Q.background_reason;for(let K of["bash_id","shell_id"]){let H=Q[K];if(typeof H==="string"&&H.length<=128&&/^bash_[A-Za-z0-9-]+$/.test(H))J[K]=H}if(P)J.tool_admission=P;let F=Q.background_shell_admission;if(F&&typeof F==="object"&&!Array.isArray(F)){let K=F;if(K.code==="background_shell_busy"&&(K.scope==="session"||K.scope==="global")&&K.retryable===!0&&Number.isSafeInteger(K.limit)&&K.limit>0)J.background_shell_admission={code:K.code,scope:K.scope,retryable:K.retryable,limit:K.limit}}return J}let L=200000,D=(J,h)=>typeof J==="number"&&Number.isSafeInteger(J)&&J>=0&&J<=h?J:0;if(typeof Q.oldContent==="string"&&Q.oldContent.length>L)delete Q.oldContent;if(typeof Q.newContent==="string"&&Q.newContent.length>L)delete Q.newContent;if(Q.mcpResult&&typeof Q.mcpResult==="object"&&!Array.isArray(Q.mcpResult)){let J=Q.mcpResult,h=Array.isArray(J.artifacts)?J.artifacts.slice(0,64).flatMap((G)=>{if(!G||typeof G!=="object"||Array.isArray(G))return[];let Z=G,F=new Set(["text","image","audio","resource"]);if(typeof Z.id!=="string"||!/^[a-f0-9]{64}$/.test(Z.id)||typeof Z.sha256!=="string"||Z.sha256!==Z.id||typeof Z.kind!=="string"||!F.has(Z.kind)||D(Z.size,67108864)!==Z.size||typeof Z.persisted!=="boolean")return[];return[{id:Z.id.slice(0,128),sha256:Z.sha256.slice(0,128),kind:Z.kind,size:Z.size,persisted:Z.persisted,...typeof Z.mimeType==="string"?{mimeType:Z.mimeType.slice(0,256)}:{},...typeof Z.sourceUri==="string"?{sourceUri:Z.sourceUri.slice(0,8192)}:{},...typeof Z.path==="string"?{path:Z.path.slice(0,8192)}:{}}]}):[];Q.mcpResult={isError:J.isError===!0,contentCount:D(J.contentCount,64),textBytes:D(J.textBytes,4194304),structuredBytes:D(J.structuredBytes,4194304),artifactCount:D(J.artifactCount,64),truncated:J.truncated===!0,binaryOmitted:J.binaryOmitted===!0,artifacts:h}}else delete Q.mcpResult;return Q}var y=(q,$)=>Object.fromEntries($.map((Q)=>[String(Q),q[Q]])),w=(q,$,Q,P=!1)=>({type:$,messageScoped:P,properties:y(q,Q)});function m(q){switch(q.kind){case"tool_start":if(!("function"in q.toolCall))return;return{type:"tool.start",messageScoped:!0,toolName:q.toolCall.function.name,properties:{toolName:q.toolCall.function.name,toolCallId:q.toolCall.id,arguments:q.toolCall.function.arguments,toolKind:q.toolKind}};case"tool_progress":if(!("function"in q.toolCall))return;return{type:"tool.progress",messageScoped:!0,toolName:q.toolCall.function.name,properties:{toolName:q.toolCall.function.name,toolCallId:q.toolCall.id,...q.update}};case"tool_result":{if(!("function"in q.toolCall))return;let $=q.toolCall.function.name;return{type:"tool.result",messageScoped:!0,toolName:$,properties:{toolName:$,toolCallId:q.toolCall.id,success:q.result.success,summary:q.result.metadata?.summary,output:z(R(_($,q.result),g)),metadata:T($,q.result.metadata)}}}case"provider_admission":return w(q,"provider.admission",["phase","requestClass","resource","scope","reason","queuePosition","queueDepth","inFlight","limit","waitMs","maxWaitMs","recoveryRemainingMs"]);case"provider_circuit":return w(q,"provider.circuit",["phase","reason","statusCode","retryAfterMs","nextProbeAt","openDurationMs","sampleCount","failureCount","recoveryRemainingMs"]);case"provider_retry":return w(q,"provider.retry",["phase","attempt","maxRetries","reason","statusCode","delayMs","nextRetryAt","mode","recoveryBudgetMs","recoveryElapsedMs","recoveryRemainingMs","exhaustedBy"]);case"provider_stall":return w(q,"provider.stall",["phase","stallCount","durationMs","warningAfterMs","timeoutMs","outputStarted"]);case"action_stationarity":return w(q,"action.stationarity",["phase","toolName","runLength","nudgeThreshold","haltThreshold","progressAware"]);case"mcp_catalog_changed":return w(q,"mcp.catalog.changed",["revision","serverName","added","removed","updated"],!0);case"mcp_content_changed":return w(q,"mcp.content.changed",["revision","serverName","contentKind","added","removed","updated"],!0);case"mcp_resource_updated":return w(q,"mcp.resource.updated",["revision","serverName","uri"],!0);case"mcp_connection_changed":return w(q,"mcp.connection.changed",["revision","serverName","phase","reason","attempt","maxAttempts","nextRetryAt","error"],!0);case"mcp_log":return w(q,"mcp.log",["revision","serverName","level","logger","message","projectedBytes","dataSha256","truncated","detailsOmitted","timestamp","synthetic"],!0);case"mcp_instructions_changed":return w(q,"mcp.instructions.changed",["revision","serverName","action","reason","text","sourceBytes","projectedBytes","sha256","truncated","detailsOmitted"],!0);case"mcp_task_changed":return w(q,"mcp.task.changed",["revision","taskId","serverName","toolName","status","statusMessage","createdAt","updatedAt","completedAt","hasResult","error"],!0);case"project_rules_loaded":return w(q,"project.rules.loaded",["files","triggerPaths","blockedWrite"],!0);default:return}}function a(q,$={}){let Q=m(q);if(!Q||!$.omitUndefined)return Q;return{...Q,properties:Object.fromEntries(Object.entries(Q.properties).filter(([,P])=>P!==void 0))}}
|
|
1
|
+
import{M as N,ka as _,la as z}from"./chunk-phch3t6v.js";import{$d as R,Xc as I,Zd as g,cd as x,dd as X,ed as B,fd as V,gd as b,wd as A}from"./chunk-hbkpavbp.js";import{Di as M,Ei as O}from"./chunk-r9egmztq.js";import{Mutex as j}from"async-mutex";class C extends Error{limit;resource="resident_runtimes";retryable=!0;constructor(q){super("Session runtime capacity is full");this.limit=q;this.name="SessionRuntimeCapacityError"}}class W extends Error{constructor(){super("Session runtime residency is closed");this.name="SessionRuntimeResidencyClosedError"}}class Y extends Error{constructor(q){super(`Session runtime residency already owns key: ${q}`);this.name="SessionRuntimeResidencyConflictError"}}class k{maxResident;idleMs;now;residents=new Map;reservations=new Map;operations=new j;nextGeneration=1;closed=!1;constructor(q){if(!M(q.maxResident))throw Error("Invalid max resident Session Runtime limit");if(!O(q.idleMs))throw Error("Invalid Session Runtime idle timeout");this.maxResident=q.maxResident,this.idleMs=q.idleMs,this.now=q.now??Date.now}acquire(q){let $=this.residents.get(q);if(!$||$.poisoned)return;return $.pins++,$.lastUsedAt=this.now(),this.createLease($)}owns(q,$){let Q=this.residents.get(q);return Boolean(Q&&($===void 0||Q.value===$))}async reserve(q,$){if(!q.trim())throw Error("Session runtime residency key must not be blank");return this.operations.runExclusive(async()=>{if(this.closed)throw new W;if(this.residents.has(q)||this.reservations.has(q))throw new Y(q);while(this.retainedCount()>=this.maxResident){if(!$.allowEviction)throw new C(this.maxResident);let P=this.oldestEvictableWebResident();if(!P)throw new C(this.maxResident);await this.disposeResident(P,!0)}let Q={generation:this.allocateGeneration(),surface:$.surface};return this.reservations.set(q,Q),this.createReservation(q,Q)})}async remove(q,$){return this.operations.runExclusive(async()=>{let Q=this.residents.get(q);if(!Q||$!==void 0&&Q.value!==$)return!1;if(Q.pins>0)return!1;return await this.disposeResident(Q,!0),!0})}async forget(q,$){return this.operations.runExclusive(async()=>{let Q=this.residents.get(q);if(!Q||$!==void 0&&Q.value!==$||Q.pins>0)return!1;return this.residents.delete(q),!0})}async sweepIdle(){return this.operations.runExclusive(async()=>{if(this.closed)return 0;let q=0;while(!0){let $=this.oldestIdleWebResident();if(!$)return q;await this.disposeResident($,!0),q++}})}async disposeAll(){await this.operations.runExclusive(async()=>{this.closed=!0,this.reservations.clear();let q;for(let $ of[...this.residents.values()])try{await this.disposeResident($,!1)}catch(Q){q??=Q}if(this.residents.clear(),q!==void 0)throw q})}getStats(){let q=0;for(let $ of this.residents.values())if($.pins>0)q++;return{resident:this.residents.size,reserved:this.reservations.size,pinned:q,maxResident:this.maxResident}}retainedCount(){return this.residents.size+this.reservations.size}allocateGeneration(){let q=this.nextGeneration;return this.nextGeneration=this.nextGeneration===Number.MAX_SAFE_INTEGER?1:this.nextGeneration+1,q}createReservation(q,$){let Q=!1;return{commit:(P)=>{if(Q)throw new Y(q);if(P.key!==q||P.surface!==$.surface||this.reservations.get(q)!==$||this.closed)throw this.reservations.delete(q),Q=!0,this.closed?new W:new Y(q);this.reservations.delete(q);let L={...P,generation:$.generation,pins:1,lastUsedAt:this.now(),poisoned:!1};return this.residents.set(q,L),Q=!0,this.createLease(L)},cancel:()=>{if(Q)return;if(this.reservations.get(q)===$)this.reservations.delete(q);Q=!0}}}createLease(q){let $=!1;return{value:q.value,release:()=>{if($)return;$=!0;let Q=this.residents.get(q.key);if(Q!==q||Q.generation!==q.generation)return;Q.pins=Math.max(0,Q.pins-1),Q.lastUsedAt=this.now()}}}oldestEvictableWebResident(){return this.sortedWebResidents().find((q)=>this.canEvict(q))}oldestIdleWebResident(){let q=this.now();return this.sortedWebResidents().find(($)=>q-$.lastUsedAt>=this.idleMs&&this.canEvict($))}sortedWebResidents(){return[...this.residents.values()].filter((q)=>q.surface==="web").sort((q,$)=>q.lastUsedAt-$.lastUsedAt||q.generation-$.generation)}canEvict(q){if(q.pins>0||q.poisoned)return!1;try{return q.canEvict()}catch{return!1}}async disposeResident(q,$){if(this.residents.get(q.key)!==q)return;this.residents.delete(q.key);try{await q.dispose()}catch(Q){if($&&!this.closed&&!this.residents.has(q.key))q.lastUsedAt=this.now(),q.poisoned=!0,this.residents.set(q.key,q);throw Q}}}function f(q){if(!q||typeof q!=="object"||Array.isArray(q))return;let $=q,{code:Q,kind:P,limit:L,reason:D,scope:J}=$;if(Q!=="tool_busy"&&Q!=="tool_batch_full"||D!=="queue_full"&&D!=="wait_timeout"&&D!=="turn_limit"||J!=="global"&&J!=="session"||typeof $.retryable!=="boolean"||!Number.isSafeInteger(L)||L<=0||P!==void 0&&P!=="readonly"&&P!=="write"&&P!=="execute")return;return{code:Q,reason:D,scope:J,retryable:$.retryable,...P===void 0?{}:{kind:P},limit:L}}function T(q,$){if(!$||typeof $!=="object")return $;let Q={...$},P=f(Q.tool_admission);if(P)Q.tool_admission=P;else delete Q.tool_admission;if(N(q)){let J=Q.browser&&typeof Q.browser==="object"&&!Array.isArray(Q.browser)?Q.browser:{},h={},G=(Z,F,K)=>{let H=J[Z];if(typeof H==="string"&&Buffer.byteLength(H)<=F&&(!K||K.test(H)))h[Z]=H};if(G("action",64),G("status",16,/^(?:ok|warning|error)$/),G("pageId",V,/^browser_page_[a-f0-9-]+$/),G("snapshotId",V,/^browser_snapshot_[a-f0-9-]+$/),G("origin",X),G("candidateOrigin",X),G("url",x),G("title",B),G("errorCode",64,/^browser_[a-z_]+$/),typeof J.truncated==="boolean")h.truncated=J.truncated;if(typeof J.actionApplied==="boolean"||J.actionApplied==="unknown")h.actionApplied=J.actionApplied;if(typeof J.sideEffectsUncertain==="boolean")h.sideEffectsUncertain=J.sideEffectsUncertain;if(typeof J.diagnosticCount==="number"&&Number.isSafeInteger(J.diagnosticCount)&&J.diagnosticCount>=0&&J.diagnosticCount<=I)h.diagnosticCount=J.diagnosticCount;if(J.interaction&&typeof J.interaction==="object"&&!Array.isArray(J.interaction)){let Z=J.interaction,F=new Set(["click","hover","fill","type","press","select","check","uncheck","scroll"]);if(typeof Z.action==="string"&&F.has(Z.action)){let K={action:Z.action};if(typeof Z.ref==="string"&&Buffer.byteLength(Z.ref)<=b&&/^[a-z][a-z0-9]*$/.test(Z.ref))K.ref=Z.ref;let H=(U,E,S)=>typeof U==="number"&&Number.isFinite(U)&&U>=E&&U<=S;if(Z.viewport&&typeof Z.viewport==="object"&&!Array.isArray(Z.viewport)){let U=Z.viewport;if(H(U.width,1,16384)&&H(U.height,1,16384))K.viewport={width:U.width,height:U.height}}if(Z.targetBox&&typeof Z.targetBox==="object"&&!Array.isArray(Z.targetBox)){let U=Z.targetBox;if(H(U.x,-16384,32768)&&H(U.y,-16384,32768)&&H(U.width,0,16384)&&H(U.height,0,16384))K.targetBox={x:U.x,y:U.y,width:U.width,height:U.height}}h.interaction=K}}if(J.artifact&&typeof J.artifact==="object"&&!Array.isArray(J.artifact)){let Z=J.artifact;if(typeof Z.id==="string"&&/^[a-f0-9]{64}$/.test(Z.id)&&Z.sha256===Z.id&&Z.kind==="image"&&Z.mimeType==="image/png"&&typeof Z.size==="number"&&Number.isSafeInteger(Z.size)&&Z.size>=0&&Z.size<=A&&Z.persisted===!0)h.artifact={id:Z.id,sha256:Z.sha256,kind:Z.kind,mimeType:Z.mimeType,size:Z.size,persisted:!0,...typeof Z.path==="string"&&Buffer.byteLength(Z.path)<=8192?{path:Z.path}:{}}}return{...typeof Q.summary==="string"?{summary:Q.summary.slice(0,512)}:{},browser:h,...P?{tool_admission:P}:{}}}if(q==="Bash"){let J={},h=["message","signal","status","summary"],G=["aborted","acp_mode","admission_failed","auto_backgrounded","background","capture_truncated","finalization_failed","has_stderr","output_accounting_complete","output_truncated","projection_truncated","sandbox_required","sandboxed","stderr_projection_truncated","stdout_projection_truncated","terminal_output_merged","timeout"],Z=["execution_time","foreground_budget_ms","pid","raw_output_bytes","stderr_length","stderr_omitted_bytes","stderr_retained_bytes","stderr_total_bytes","stdout_length","stdout_omitted_bytes","stdout_retained_bytes","stdout_total_bytes"];for(let K of h){let H=Q[K];if(typeof H==="string")J[K]=H.slice(0,8192)}for(let K of G){let H=Q[K];if(typeof H==="boolean")J[K]=H}for(let K of Z){let H=Q[K];if(typeof H==="number"&&Number.isSafeInteger(H)&&H>=0)J[K]=H}if(Q.exit_code===null||typeof Q.exit_code==="number"&&Number.isSafeInteger(Q.exit_code))J.exit_code=Q.exit_code;if(Q.terminal_transport==="local"||Q.terminal_transport==="acp"||Q.terminal_transport==="local_fallback")J.terminal_transport=Q.terminal_transport;if(Q.background_reason==="explicit"||Q.background_reason==="foreground_budget")J.background_reason=Q.background_reason;for(let K of["bash_id","shell_id"]){let H=Q[K];if(typeof H==="string"&&H.length<=128&&/^bash_[A-Za-z0-9-]+$/.test(H))J[K]=H}if(P)J.tool_admission=P;let F=Q.background_shell_admission;if(F&&typeof F==="object"&&!Array.isArray(F)){let K=F;if(K.code==="background_shell_busy"&&(K.scope==="session"||K.scope==="global")&&K.retryable===!0&&Number.isSafeInteger(K.limit)&&K.limit>0)J.background_shell_admission={code:K.code,scope:K.scope,retryable:K.retryable,limit:K.limit}}return J}let L=200000,D=(J,h)=>typeof J==="number"&&Number.isSafeInteger(J)&&J>=0&&J<=h?J:0;if(typeof Q.oldContent==="string"&&Q.oldContent.length>L)delete Q.oldContent;if(typeof Q.newContent==="string"&&Q.newContent.length>L)delete Q.newContent;if(Q.mcpResult&&typeof Q.mcpResult==="object"&&!Array.isArray(Q.mcpResult)){let J=Q.mcpResult,h=Array.isArray(J.artifacts)?J.artifacts.slice(0,64).flatMap((G)=>{if(!G||typeof G!=="object"||Array.isArray(G))return[];let Z=G,F=new Set(["text","image","audio","resource"]);if(typeof Z.id!=="string"||!/^[a-f0-9]{64}$/.test(Z.id)||typeof Z.sha256!=="string"||Z.sha256!==Z.id||typeof Z.kind!=="string"||!F.has(Z.kind)||D(Z.size,67108864)!==Z.size||typeof Z.persisted!=="boolean")return[];return[{id:Z.id.slice(0,128),sha256:Z.sha256.slice(0,128),kind:Z.kind,size:Z.size,persisted:Z.persisted,...typeof Z.mimeType==="string"?{mimeType:Z.mimeType.slice(0,256)}:{},...typeof Z.sourceUri==="string"?{sourceUri:Z.sourceUri.slice(0,8192)}:{},...typeof Z.path==="string"?{path:Z.path.slice(0,8192)}:{}}]}):[];Q.mcpResult={isError:J.isError===!0,contentCount:D(J.contentCount,64),textBytes:D(J.textBytes,4194304),structuredBytes:D(J.structuredBytes,4194304),artifactCount:D(J.artifactCount,64),truncated:J.truncated===!0,binaryOmitted:J.binaryOmitted===!0,artifacts:h}}else delete Q.mcpResult;return Q}var y=(q,$)=>Object.fromEntries($.map((Q)=>[String(Q),q[Q]])),w=(q,$,Q,P=!1)=>({type:$,messageScoped:P,properties:y(q,Q)});function m(q){switch(q.kind){case"tool_start":if(!("function"in q.toolCall))return;return{type:"tool.start",messageScoped:!0,toolName:q.toolCall.function.name,properties:{toolName:q.toolCall.function.name,toolCallId:q.toolCall.id,arguments:q.toolCall.function.arguments,toolKind:q.toolKind}};case"tool_progress":if(!("function"in q.toolCall))return;return{type:"tool.progress",messageScoped:!0,toolName:q.toolCall.function.name,properties:{toolName:q.toolCall.function.name,toolCallId:q.toolCall.id,...q.update}};case"tool_result":{if(!("function"in q.toolCall))return;let $=q.toolCall.function.name;return{type:"tool.result",messageScoped:!0,toolName:$,properties:{toolName:$,toolCallId:q.toolCall.id,success:q.result.success,summary:q.result.metadata?.summary,output:z(R(_($,q.result),g)),metadata:T($,q.result.metadata)}}}case"provider_admission":return w(q,"provider.admission",["phase","requestClass","resource","scope","reason","queuePosition","queueDepth","inFlight","limit","waitMs","maxWaitMs","recoveryRemainingMs"]);case"provider_circuit":return w(q,"provider.circuit",["phase","reason","statusCode","retryAfterMs","nextProbeAt","openDurationMs","sampleCount","failureCount","recoveryRemainingMs"]);case"provider_retry":return w(q,"provider.retry",["phase","attempt","maxRetries","reason","statusCode","delayMs","nextRetryAt","mode","recoveryBudgetMs","recoveryElapsedMs","recoveryRemainingMs","exhaustedBy"]);case"provider_stall":return w(q,"provider.stall",["phase","stallCount","durationMs","warningAfterMs","timeoutMs","outputStarted"]);case"action_stationarity":return w(q,"action.stationarity",["phase","toolName","runLength","nudgeThreshold","haltThreshold","progressAware"]);case"mcp_catalog_changed":return w(q,"mcp.catalog.changed",["revision","serverName","added","removed","updated"],!0);case"mcp_content_changed":return w(q,"mcp.content.changed",["revision","serverName","contentKind","added","removed","updated"],!0);case"mcp_resource_updated":return w(q,"mcp.resource.updated",["revision","serverName","uri"],!0);case"mcp_connection_changed":return w(q,"mcp.connection.changed",["revision","serverName","phase","reason","attempt","maxAttempts","nextRetryAt","error"],!0);case"mcp_log":return w(q,"mcp.log",["revision","serverName","level","logger","message","projectedBytes","dataSha256","truncated","detailsOmitted","timestamp","synthetic"],!0);case"mcp_instructions_changed":return w(q,"mcp.instructions.changed",["revision","serverName","action","reason","text","sourceBytes","projectedBytes","sha256","truncated","detailsOmitted"],!0);case"mcp_task_changed":return w(q,"mcp.task.changed",["revision","taskId","serverName","toolName","status","statusMessage","createdAt","updatedAt","completedAt","hasResult","error"],!0);case"project_rules_loaded":return w(q,"project.rules.loaded",["files","triggerPaths","blockedWrite"],!0);default:return}}function a(q,$={}){let Q=m(q);if(!Q||!$.omitUndefined)return Q;return{...Q,properties:Object.fromEntries(Object.entries(Q.properties).filter(([,P])=>P!==void 0))}}
|
|
2
2
|
export{C as w,k as x,T as y,a as z};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a,b as i,c as l,d as m}from"./chunk-7m07qp5c.js";import"./chunk-5ce8ydjq.js";import"./chunk-870szc6v.js";import"./chunk-js7fre4w.js";import"./chunk-49jbxty9.js";import"./chunk-vv6r417h.js";import"./chunk-phch3t6v.js";import"./chunk-nad5spvc.js";import"./chunk-v5t3kcac.js";import"./chunk-whxkwaz1.js";import"./chunk-hfbw50pk.js";import"./chunk-9qxch6sy.js";import"./chunk-hbkpavbp.js";import"./chunk-skktstg8.js";import"./chunk-s14zayxp.js";import"./chunk-b5cz00mt.js";import{Ef as n}from"./chunk-rwm2e0r4.js";import"./chunk-crv3sghv.js";import{_f as s}from"./chunk-5kmxe14c.js";import"./chunk-x6k5ye1z.js";import"./chunk-v508x7cg.js";import"./chunk-1g7c3f82.js";import"./chunk-3v9epq9s.js";import"./chunk-eexs73bz.js";import"./chunk-pm163dfm.js";import"./chunk-w8dxjbm8.js";import"./chunk-e4q0rcmz.js";import"./chunk-kehgewqh.js";import"./chunk-kkzznz4w.js";import"./chunk-1cy4ab77.js";import"./chunk-7ajvrtb3.js";import"./chunk-egqep8py.js";import"./chunk-ys8gysg8.js";import"./chunk-r9egmztq.js";import"./chunk-b22ab7yw.js";import"./chunk-amabfzc8.js";import"./chunk-m2x6pb4f.js";import"./chunk-saz6mwpq.js";import"./chunk-xhwdac1j.js";import"./chunk-0eajnhrj.js";import"./chunk-c33wff11.js";import"./chunk-asgmmaec.js";import"./chunk-ed2hdrwe.js";import"./chunk-gmpsfkgg.js";import v from"chalk";var C={command:"serve",describe:"Start a headless Blade server (no browser)",builder:a,handler:async(p)=>{let r=i(p);if(await s(),!process.env.BLADE_SERVER_PASSWORD)console.log(v.yellow("Warning: BLADE_SERVER_PASSWORD is not set; server is unsecured."));let e=await m.listenAsync(r);if(console.log(`Blade server listening on http://${e.hostname}:${e.port}`),r.hostname==="0.0.0.0"){let o=l();for(let g of o)console.log(` Network: http://${g}:${e.port}`)}let t,c=new Promise((o)=>{t=o}),d=n(async()=>{await e.stop(),t()});try{await c}finally{d(),await e.stop()}}};export{C as serveCommand};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Af as b,Bf as c,zf as a}from"./chunk-myznexy5.js";import"./chunk-yjdyzb5z.js";import"./chunk-5kmxe14c.js";import"./chunk-x6k5ye1z.js";import"./chunk-v508x7cg.js";import"./chunk-7ajvrtb3.js";import"./chunk-r9egmztq.js";import"./chunk-b22ab7yw.js";import"./chunk-amabfzc8.js";import"./chunk-m2x6pb4f.js";import"./chunk-saz6mwpq.js";import"./chunk-xhwdac1j.js";import"./chunk-0eajnhrj.js";import"./chunk-c33wff11.js";import"./chunk-asgmmaec.js";import"./chunk-ed2hdrwe.js";import"./chunk-gmpsfkgg.js";export{a as validatePermissions,c as validateOutput,b as loadConfiguration};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{Cf as v}from"./chunk-
|
|
1
|
+
import{Cf as v}from"./chunk-yjdyzb5z.js";import{Vf as e}from"./chunk-5kmxe14c.js";import{Bi as C,Fh as Y,Fi as S,Gi as m,Hi as c,Ii as p,Ki as u,Li as d,Pi as l,Ui as i,Vi as t,hi as y,ji as D,ki as h,mi as A,ti as P,ui as T,wi as E,yi as _,zi as f}from"./chunk-r9egmztq.js";import{Xi as X}from"./chunk-b22ab7yw.js";import{$i as U,aj as L,gj as M,hj as O,jj as $,kj as I,lj as G,nj as N,oj as j,qj as F,rj as R}from"./chunk-amabfzc8.js";import{Ej as s,Gj as x,Ij as k,Lj as Z}from"./chunk-saz6mwpq.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. 配置文件权限是否正确
|