blade-code 0.10.105 → 0.10.107
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-yeq7qzdb.js → chunk-0gcq7bn0.js} +4 -4
- package/dist/{chunk-xm8nyj5z.js → chunk-23v8c9b8.js} +2 -2
- package/dist/chunk-25ps9fxw.js +1 -0
- package/dist/chunk-2adsynk7.js +1 -0
- package/dist/{chunk-151cz9k4.js → chunk-3mf8b8p8.js} +2 -2
- package/dist/{chunk-7fz3w4rk.js → chunk-3pwq56je.js} +1 -1
- package/dist/{chunk-sy117k4g.js → chunk-4n3nqwcb.js} +1 -1
- package/dist/{chunk-sdbbyagy.js → chunk-4w4wjm49.js} +1 -1
- package/dist/{chunk-gz4h2y7j.js → chunk-4x2p8ygk.js} +1 -1
- package/dist/{chunk-s0tq8gyx.js → chunk-53h87fmt.js} +1 -1
- package/dist/chunk-53mma826.js +1 -0
- package/dist/{chunk-f3426b1c.js → chunk-6k5k40p8.js} +1 -1
- package/dist/{chunk-szxajr6e.js → chunk-76f8ms39.js} +1 -1
- package/dist/{chunk-139frcak.js → chunk-772ehgbx.js} +2 -2
- package/dist/{chunk-2mck84gx.js → chunk-783yxe58.js} +1 -1
- package/dist/chunk-7wpr236t.js +1 -0
- package/dist/{chunk-41ympwz1.js → chunk-935v0gpc.js} +1 -1
- package/dist/{chunk-p39mmmbt.js → chunk-97xt0nq6.js} +2 -2
- package/dist/{chunk-fva7jnjy.js → chunk-9g64g1np.js} +1 -1
- package/dist/{chunk-szdz1jmj.js → chunk-a9cmwynx.js} +2 -2
- package/dist/{chunk-26t2mg1v.js → chunk-b97v6fr0.js} +1 -1
- package/dist/chunk-bdgq4k40.js +1 -0
- package/dist/{chunk-3gf34fv5.js → chunk-be5x9ed5.js} +2 -2
- package/dist/{chunk-j2dyprdy.js → chunk-bksfg23m.js} +2 -2
- package/dist/{chunk-4bwr3rcj.js → chunk-brebh2tm.js} +2 -2
- package/dist/{chunk-bcbssqsn.js → chunk-bsyg9npn.js} +1 -1
- package/dist/{chunk-181ef74x.js → chunk-c3jb4xg7.js} +1 -1
- package/dist/chunk-ca9cbkf2.js +118 -0
- package/dist/{chunk-8hprmrd5.js → chunk-cnhw5mqv.js} +1 -1
- package/dist/chunk-cp4cnbcd.js +23 -0
- package/dist/{chunk-kf7whgr7.js → chunk-cqqmkwvn.js} +1 -1
- package/dist/chunk-df00ys8n.js +1 -0
- package/dist/{chunk-s10pmnrd.js → chunk-dgf2xzzd.js} +2 -2
- package/dist/{chunk-n7mzxa8h.js → chunk-dvv28pkc.js} +2 -2
- package/dist/{chunk-6j482w6k.js → chunk-e7h4wb45.js} +3 -3
- package/dist/{chunk-0hr050ck.js → chunk-ecd727xh.js} +1 -1
- package/dist/{chunk-xzjhfw7y.js → chunk-ef4csfmf.js} +1 -1
- package/dist/{chunk-brjjvs4d.js → chunk-es9rwqx8.js} +1 -1
- package/dist/{chunk-41cg66y0.js → chunk-eyb9psbc.js} +1 -1
- package/dist/chunk-fhxabxs5.js +1 -0
- package/dist/chunk-fqnqeca5.js +1 -0
- package/dist/{chunk-xvg14dkr.js → chunk-g491cknj.js} +2 -2
- package/dist/{chunk-2hb222re.js → chunk-hv6hrsnk.js} +1 -1
- package/dist/chunk-jdkfytez.js +1 -0
- package/dist/{chunk-6wsvgk20.js → chunk-jp4j9tnn.js} +1 -1
- package/dist/chunk-jxy1p5at.js +2 -0
- package/dist/{chunk-48vc39mb.js → chunk-mpawab9w.js} +2 -2
- package/dist/{chunk-946wkbmw.js → chunk-mqekerck.js} +1 -1
- package/dist/{chunk-p6prp8zc.js → chunk-n1ghwh6q.js} +2 -2
- package/dist/{chunk-z9gd9spf.js → chunk-ng96f4xd.js} +2 -2
- package/dist/chunk-p3m1jyg5.js +2 -0
- package/dist/chunk-p86wzk44.js +1 -0
- package/dist/chunk-pcm46gkz.js +1 -0
- package/dist/{chunk-dg0d3303.js → chunk-pshyn3yy.js} +1 -1
- package/dist/{chunk-rchz6j90.js → chunk-q2exry0f.js} +2 -2
- package/dist/{chunk-5y38cfk9.js → chunk-q7hqzp81.js} +2 -2
- package/dist/{chunk-x3cxmwnz.js → chunk-qdv0n8yt.js} +2 -2
- package/dist/{chunk-tgdhsm5t.js → chunk-rkdxqx8m.js} +2 -2
- package/dist/{chunk-djqbqaxn.js → chunk-rvyk4d6t.js} +2 -2
- package/dist/{chunk-rvk9r2cm.js → chunk-sr10jsjs.js} +1 -1
- package/dist/{chunk-7g984trn.js → chunk-t5b18tf6.js} +2 -2
- package/dist/{chunk-fhfzdyba.js → chunk-tf7ezqew.js} +1 -1
- package/dist/chunk-thqwrw4a.js +8 -0
- package/dist/{chunk-w7hy5wh1.js → chunk-tj2efrs1.js} +2 -2
- package/dist/{chunk-wyhyw9rq.js → chunk-vbwvsgs1.js} +2 -2
- package/dist/{chunk-8hp650gn.js → chunk-wf19bys8.js} +3 -3
- package/dist/chunk-wrbqcdqk.js +1 -0
- package/dist/chunk-wyw17nfy.js +1 -0
- package/dist/{chunk-q69fzq4y.js → chunk-x05zyqzf.js} +1 -1
- package/dist/{chunk-47e6tdbb.js → chunk-xv3a1se1.js} +1 -1
- package/dist/{chunk-abd57h72.js → chunk-ypbnczjp.js} +2 -2
- package/dist/chunk-ys285f8c.js +10 -0
- package/dist/chunk-z46ydgcs.js +1 -0
- package/dist/{chunk-9p20hhs0.js → chunk-z52s82k7.js} +1 -1
- package/package.json +1 -1
- package/dist/chunk-0pj7d25e.js +0 -23
- package/dist/chunk-1x13nzwe.js +0 -1
- package/dist/chunk-25n07173.js +0 -1
- package/dist/chunk-3vqdyer3.js +0 -1
- package/dist/chunk-4z79mh8y.js +0 -1
- package/dist/chunk-9dba1pyq.js +0 -1
- package/dist/chunk-bt18xsc6.js +0 -1
- package/dist/chunk-c0m2vw2q.js +0 -1
- package/dist/chunk-c133kq05.js +0 -1
- package/dist/chunk-c475tfqf.js +0 -2
- package/dist/chunk-jqqqg8kv.js +0 -10
- package/dist/chunk-kdjtxpxw.js +0 -1
- package/dist/chunk-n1qxq9kv.js +0 -1
- package/dist/chunk-najk5ty4.js +0 -118
- package/dist/chunk-pf4je2g7.js +0 -8
- package/dist/chunk-q0fv0efv.js +0 -1
- package/dist/chunk-v4w5b2cq.js +0 -1
- package/dist/chunk-vk4xbek0.js +0 -1
- package/dist/chunk-x6z05rfz.js +0 -1
- package/dist/chunk-zmfm07hj.js +0 -2
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{$b as M4}from"./chunk-8hprmrd5.js";import{Fd as u0,Hd as K6,Id as h1,Jd as Q6,Qd as o$,Tc as vJ,Vc as IJ,Wc as uJ,Xc as m2,Yc as c2,bc as X$,cd as gJ,dd as T4,ed as R4,fd as I2,gd as k1,hd as h4,id as x4,jd as S1,nd as DJ,vd as K1}from"./chunk-najk5ty4.js";import{Vd as S4}from"./chunk-s0tq8gyx.js";import{$d as v0,Xd as H0,_d as bJ}from"./chunk-x3cxmwnz.js";import{af as eJ}from"./chunk-dg0d3303.js";import{bf as b4,cf as i0,df as f4,ef as zJ,hf as E1,if as V6,jf as BJ,kf as jJ,mf as UJ}from"./chunk-rchz6j90.js";import{$f as E4,Xf as J$,Yf as r0,dg as H4}from"./chunk-kf7whgr7.js";import{qg as N$}from"./chunk-6j482w6k.js";import{Ah as nJ}from"./chunk-sdbbyagy.js";import{Ph as X0}from"./chunk-0hr050ck.js";import{pi as k0}from"./chunk-n7mzxa8h.js";import{Di as CJ}from"./chunk-4bwr3rcj.js";import{Oi as b$,Qi as r6,Ri as P0,Si as R1,Ui as hJ,Vi as xJ,Wi as kJ}from"./chunk-tgdhsm5t.js";import{Xi as L8}from"./chunk-fhfzdyba.js";function A$($){return $.role==="system"&&Array.isArray($.content)}function f$($){if($.role!=="system"||!$.metadata||Array.isArray($.metadata))return!1;return typeof $.metadata==="object"&&$.metadata.contextualProjectRules===!0}class A1{systemMessages;_contextualSystemMessages;_history;_pending=[];_contextRevision=0;context;constructor($,J){this.context=$;let Z=$.messages.find(A$);if(this._contextualSystemMessages=$.messages.filter(f$),Z)this.systemMessages=[Z,...this._contextualSystemMessages];else if(J)this.systemMessages=[{role:"system",content:[{type:"text",text:J,providerOptions:{anthropic:{cacheControl:{type:"ephemeral"}}}}]},...this._contextualSystemMessages];else this.systemMessages=[...this._contextualSystemMessages];this._history=$.messages.filter((W)=>!A$(W)&&!f$(W))}get historyLength(){return this._history.length}get history(){return this._history}get pending(){return this._pending}get contextRevision(){return this._contextRevision}toLLMMessages(){return[...this.systemMessages,...this._history,...this._pending]}getMessagesForLLM(){return this.toLLMMessages()}getHistory(){return this._history}appendPending($){this._pending.push($)}appendUser($){this._pending.push($)}appendAssistant($){this._pending.push($)}appendToolResult($){this._pending.push($)}appendContextualProjectInstructions($){if(!f$($))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($,J){if($==="system")throw Error("Cannot append system control message via appendControl. Use constructor for root system prompt.");this._pending.push(J)}appendDurableControl($){if(!$.id||$.role!=="user")throw Error("Durable control messages require a user role and identity");if(this._history.some((J)=>J.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((J)=>!A$(J)&&!f$(J)),this._contextRevision++}restoreDurableHistory($){this._contextualSystemMessages=$.filter(f$),this._history=$.filter((J)=>!A$(J)&&!f$(J)),this._pending=[],this.syncContextualSystemMessages(),this._contextRevision++}removeMessages($){let J=[this._history.length,this._pending.length,this._contextualSystemMessages.length];if(this._history=this._history.filter((Z)=>!$(Z)),this._pending=this._pending.filter((Z)=>!$(Z)),this._contextualSystemMessages=this._contextualSystemMessages.filter((Z)=>!$(Z)),this.syncContextualSystemMessages(),this._history.length!==J[0]||this._pending.length!==J[1]||this._contextualSystemMessages.length!==J[2])this._contextRevision++}writeback(){this.commitPending(),this.context.messages=[...this._contextualSystemMessages,...this._history]}get hasSystemPrompt(){return this.systemMessages.length>0}}function b6($){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 E6($){return{budget:$.budget,usage:0,consecutiveContinuations:0,lastOutputDelta:0,isSubagent:$.isSubagent??!1}}function S6($,J,Z){return{...$,usage:$.usage+J,lastOutputDelta:J,consecutiveContinuations:Z?$.consecutiveContinuations+1:0}}import Q$ from"node:path";var c4=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"]),l4=/^(LD_.+|DYLD_.+|PATH)$/,M6=/^([A-Za-z_][A-Za-z0-9_]*)=([\w./:@-]*)$/;function l$($){let J=$;while(!0){let Z=J.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!Z)break;let W=Z[1],Y=Z[2],V=W.match(M6);if(!V)break;let K=V[1];if(!c4.has(K))break;J=Y}return J}function uZ($){let J=$;while(!0){let Z=J.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!Z)break;let W=Z[1],Y=Z[2],V=W.match(M6);if(!V)break;let K=V[1];if(l4.test(K))break;J=Y}return J}var i4=[/^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 D2($){let J=$,Z=!0;while(Z){Z=!1;for(let W of i4){let Y=J.match(W);if(Y){J=J.slice(Y[0].length),Z=!0;break}}if(J.startsWith("-- "))J=J.slice(3),Z=!0}return J}function i$($){let J=[],Z="",W=!1,Y=!1,V=!1;for(let K=0;K<$.length;K++){let Q=$[K];if(V){Z+=Q,V=!1;continue}if(Q==="\\"&&!W){Z+=Q,V=!0;continue}if(Q==="'"&&!Y){W=!W,Z+=Q;continue}if(Q==='"'&&!W){Y=!Y,Z+=Q;continue}if(W||Y){Z+=Q;continue}if(Q==="|"){if(K+1<$.length&&$[K+1]==="|"){if(Z.trim())J.push(Z.trim());Z="",K++;continue}return null}if(Q===">"||Q==="<")return null;if(Q==="&"&&K+1<$.length&&$[K+1]==="&"){if(Z.trim())J.push(Z.trim());Z="",K++;continue}if(Q==="&")return null;if(Q===";"){if(Z.trim())J.push(Z.trim());Z="";continue}Z+=Q}if(Z.trim())J.push(Z.trim());return J.length>0?J:null}function T6($){let J=!1,Z=!1,W=!1;for(let Y=0;Y<$.length;Y++){let V=$[Y];if(W){W=!1;continue}if(V==="\\"&&!J){W=!0;continue}if(V==="'"&&!Z){J=!J;continue}if(V==='"'&&!J){Z=!Z;continue}if(J)continue;if(V==="$"){let K=$[Y+1];if(K&&/[A-Za-z_@*#?!$0-9({]/.test(K))return!0}if(V==="`")return!0;if(Z)continue;if(V==="|")return!0;if(V===">"||V==="<")return!0;if(V==="{"){let K=$.slice(Y);if(/^\{[^}]*,[^}]*\}/.test(K)||/^\{[^}]*\.\.[^}]*\}/.test(K))return!0}}return!1}function K$($){let J=[],Z="",W=!1,Y=!1,V=!1;for(let K=0;K<$.length;K++){let Q=$[K];if(V){Z+=Q,V=!1;continue}if(Q==="\\"&&!W){if(V=!0,Y){let X=$[K+1];if(X&&'$`"\\'.includes(X))continue;Z+=Q,V=!1}continue}if(Q==="'"&&!Y){W=!W;continue}if(Q==='"'&&!W){Y=!Y;continue}if(!W&&!Y&&/[ \t]/.test(Q)){if(Z)J.push(Z),Z="";continue}Z+=Q}if(Z)J.push(Z);return J}var r4=new Set(["npm","pnpm","yarn","bun"]),R6=new Set(["biome","eslint","jest","mypy","pyright","pytest","ruff","tsc","vitest"]),n4=new Set(["-u","--fix","--update","--update-snapshot","--updateSnapshot","--watch","--watchAll","--write"]),o4=/[ \t]*;[ \t]*echo[ \t]+"[A-Za-z0-9 _:=.-]*(?:\$\{PIPESTATUS\[0\]\}|\$\?)[A-Za-z0-9 _:=.-]*"[ \t]*$/;function a4($){return $!==void 0&&/^(?:test|lint|build|type-?check)(?::[\w.-]+)*$/i.test($)}function h6($){return $.replace(/\s+2>&1\s*$/,"").trim()}function s4($,J,Z){if(!Z||J.length!==2)return;let W=/^(.+?)[ \t]+&&[ \t]+([\s\S]+)$/.exec($);if(!W)return;let Y=K$(W[1]??"");if(Y.length!==2||Y[0]!=="cd")return;let V=Y[1];if(!V||V==="-")return;let K=Q$.isAbsolute(V)?Q$.resolve(V):Q$.resolve(Z,V);if(!X$.isWithinWorkspace(K,Z))return;return W[2]?.trim()||void 0}function t4($){let J=[],Z=!1,W=!1,Y=!1;for(let V=0;V<$.length;V++){let K=$[V];if(Y){Y=!1;continue}if(K==="\\"&&!Z){Y=!0;continue}if(K==="'"&&!W){Z=!Z;continue}if(K==='"'&&!Z){W=!W;continue}if(K!=="|"||Z||W)continue;if($[V+1]==="|")return;J.push(V)}return J}function e4($){let J=K$($),[Z,W,Y]=J;if(Z!=="head"&&Z!=="tail")return!1;if(J.length===1)return!0;let V=(K)=>K!==void 0&&/^[1-9]\d{0,4}$/.test(K);if(J.length===2)return W?.startsWith("--lines=")&&V(W.slice(8))||W?.startsWith("-")&&V(W.slice(1));return J.length===3&&(W==="-n"||W==="--lines")&&V(Y)}function $5($){let J=h6($.replace(o4,"").trim()),Z=t4(J);if(!Z)return;if(Z.length===0)return x6(J);if(Z.length!==1)return;let W=Z[0];if(W===void 0)return;let Y=h6(J.slice(0,W).trim()),V=J.slice(W+1).trim();if(!Y||!e4(V))return;return x6(Y)}function x6($){let Z=i$($)?.at(-1);if(!Z)return $;let W=K$(Z),[Y,V]=W;if(!(Y==="vitest"||(Y==="npx"||Y==="bunx")&&V==="vitest")||W.some((Q)=>Q==="--configLoader"||Q.startsWith("--configLoader=")))return $;return`${$} --configLoader runner`}function y$($,J){let Z=$5($);if(!Z)return!1;let W=l$(Z),Y=i$(W);if(!Y||T6(W)||/[\r\n]/.test(W))return!1;let V=Y.length===1?Y[0]:s4(W,Y,J);if(!V)return!1;let K=K$(V);if(K.length===0||K.some((B)=>[...n4].some((j)=>B===j||B.startsWith(`${j}=`))))return!1;let[Q,X,H]=K;if(r4.has(Q??""))return a4(X==="run"?H:X)||X==="--test";if((Q==="npx"||Q==="bunx")&&R6.has(X??""))return!0;if(R6.has(Q??""))return!0;if(Q==="node"&&X==="--test")return!0;if(Q==="go"&&["build","test","vet"].includes(X??""))return!0;return Q==="cargo"&&["build","check","clippy","test"].includes(X??"")}function cZ($,J){if($===void 0)return!0;if(typeof $!=="string"||$.split(/[\\/]/).includes(".."))return!1;if(!J)return!Q$.isAbsolute($);let Z=Q$.isAbsolute($)?Q$.resolve($):Q$.resolve(J,$);return X$.isWithinWorkspace(Z,J)}var w2=k0("Agent"),J5=3;function q2($,J,Z){if($!=="length")return{action:"none"};if(J>=J5)return{action:"truncated"};if(b6(Z)==="stop")return w2.info("[Loop] Token budget: diminishing returns detected, skipping recovery"),{action:"budget_stop"};return{action:"recover"}}var Z5=[/:\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],W5=/```[\s\S]{50,}```/,k6="请执行你提到的操作,不要只是描述。使用 Edit/Write/ApplyPatch/Bash 工具来实际修改文件。",Y5=2;function G2($,J,Z=!0){if(!$||J>=Y5)return{action:"none"};if(!Z&&W5.test($))return{action:"retry",prompt:k6};let W=$.slice(-200),Y=W.match(/```/g);if(Y&&Y.length%2!==0)return{action:"none"};if(Z5.some((K)=>K.test(W)))return{action:"retry",prompt:k6};return{action:"none"}}var V5=[/\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}(?:测试|单测|集成测试|检查|构建)/],C6={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},K5={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},Q5="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.",X5="Required verification did not run successfully before the retry limit.",H5=3;function I6($,J,Z,W){if(!Z.success)return;if(["Edit","Write","ApplyPatch","NotebookEdit"].includes(J)){$.clear();return}if(J==="Bash"&&typeof Z.metadata?.command==="string"&&Z.metadata.exit_code===0&&y$(Z.metadata.command,W)){$.add(Z.metadata.command);return}if(!["Task","TaskOutput"].includes(J))return;let Y=Z.metadata?.verificationCommands;if(!Array.isArray(Y))return;for(let V of Y)if(typeof V==="string"&&y$(V,W))$.add(V)}function F2($,J,Z){if(!$||!V5.some((X)=>X.test($)))return{action:"none"};let W=Object.keys(C6).filter((X)=>C6[X].test($)),Y=[...J],V=W.filter((X)=>!Y.some((H)=>K5[X].test(H)));if(W.length>0?V.length===0:Y.some((X)=>y$(X)))return{action:"none"};if(Z>=H5)return{action:"fail",message:X5};let Q=W.length>1&&V.length>0?` Missing successful verification categories: ${V.join(", ")}.`:"";return{action:"retry",prompt:`${Q5}${Q}`}}var z5=[/\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|子代理|子智能体)/],u6=[/\b(?:do not|don't|never)\s+(?:delegate|call|use|invoke)\b/i,/(?:不要|禁止|无需)(?:委派|调用|使用).{0,20}(?:Task|子代理|子智能体)?/];function g6($){return typeof $==="string"&&u6.some((J)=>J.test($))}var B5=[/\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|子代理)/],j5=[/\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 U5($){if(typeof $!=="string")return;if(j5.some((J)=>J.test($)))return"multiple-allowed";return B5.some((J)=>J.test($))?"required":void 0}function r$($){for(let J of $){let Z=U5(J);if(Z!==void 0)return Z==="required"}return!1}var D5="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.",w5="Required delegation did not complete before the retry limit.",q5=3;function p6($,J,Z){let W=(typeof $==="string"?[$]:$??[]).map((K)=>K.trim()).filter(Boolean),Y=r$(W),V=!1;if(!Y)for(let K of W){if(u6.some((Q)=>Q.test(K)))break;if(z5.some((Q)=>Q.test(K))){V=!0;break}}if(W.length===0||!Y&&!V||J.has("Task"))return{action:"none"};if(Z>=q5)return{action:"fail",message:w5};return{action:"retry",prompt:D5}}var G5=[/\b(?:use|create|enter|start|work\s+(?:in|inside))\b.{0,60}\bworktree\b/i,/(?:使用|创建|进入).{0,30}(?:worktree|工作树)/i],F5=[/\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 d6($){return L5.reduce((J,Z)=>J.replace(Z," "),$)}function N1($){if(typeof $!=="string")return!1;let J=d6($);return G5.some((Z)=>Z.test(J))}var O5="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.",A5="Required worktree lifecycle did not complete before the retry limit.",y5=3;function m6($,J,Z){if(!$)return{action:"none"};let W=d6($);if(!N1(W))return{action:"none"};let Y=F5.some((K)=>K.test(W));if(J.has("TaskWorktree"))return{action:"none"};let V=!J.has("EnterWorktree")?"EnterWorktree":Y&&!J.has("ExitWorktree")?"ExitWorktree":void 0;if(!V)return{action:"none"};if(Z>=y5)return{action:"fail",message:A5};return{action:"retry",tool:V,prompt:V==="EnterWorktree"?O5:f5}}var v6=30000;async function L2($){try{let Z=N$.getInstance().executeStopHooks({projectDir:$.workspaceRoot??X0(),sessionId:$.sessionId,permissionMode:$.permissionMode,reason:$.reason,abortSignal:$.abortSignal}),W,Y=new Promise((V)=>{W=setTimeout(()=>V("timeout"),v6)});try{let V=await Promise.race([Z,Y]);if(V==="timeout")return w2.warn(`[Loop] Stop hook 超时 (${v6}ms),按 shouldStop: true 处理`),{action:"stop"};let K=V;if(!K.shouldStop)return{action:"continue",reason:K.continueReason};return{action:"stop"}}finally{clearTimeout(W)}}catch(J){return w2.warn("[Loop] Stop hook execution failed:",J),{action:"stop"}}}async function N5($,J){let Z;while(!(Z=await $.next()).done)if(J)await J(Z.value);return Z.value}var P5=[/<system-reminder>[\s\S]*?<\/system-reminder>/gi,/<file[^>]*>[\s\S]*?<\/file>/gi,/<hooks_context>[\s\S]*?<\/hooks_context>/gi,/<[^>]+>/g];function _5($){if(typeof $==="string")return $;if(Array.isArray($))return $.map((J)=>{if(typeof J==="string")return J;if(J&&typeof J==="object"&&"text"in J){let Z=J.text;return typeof Z==="string"?Z:""}return""}).join(" ");return""}function b5($){let J=$;for(let X of P5)J=J.replace(X," ");J=J.replace(/^\s*\/[a-zA-Z][\w-]*\s+/,"");let Z=J.replace(/\s+/g," ").trim();if(!Z)return"";let W=Z.match(/^(.+?)(?:[.!?]\s|[。!?](?=\S|$)|$)/),Y=W&&W[1].length>=6?W[1]:Z;if(Y=Y.trim().replace(/[\s.。!!??,,;;::-]+$/,""),Y.length<=60)return Y;let V=Y.slice(0,60),K=V.lastIndexOf(" ");return`${(K>36?V.slice(0,K):V).trimEnd()}…`}function c6($){return b5(_5($))}import{EventEmitter as E5}from"events";import l6 from"node:path";function O2($){if(r6($.sessionId),!l6.isAbsolute($.projectPath))throw Error("projectPath must be absolute");return{sessionId:$.sessionId,projectPath:l6.resolve($.projectPath)}}function i6($){let J=O2($);return JSON.stringify([J.projectPath,J.sessionId])}function Z3($,J){return i6($)===i6(J)}class P$ extends E5{static instance;constructor(){super();this.setMaxListeners(100)}static getInstance(){if(!P$.instance)P$.instance=new P$;return P$.instance}publish($,J,Z,W){let Y=O2($);this.emit("event",{sessionId:Y.sessionId,projectPath:Y.projectPath,type:J,...W!==void 0?{seq:W}:{},properties:Z})}subscribe($){return this.on("event",$),()=>this.off("event",$)}}var n$=P$.getInstance();var t0=k0("Agent"),P1=new Set;async function S5($,J){let Z=$.sessionId;if(!Z||$.subagentInfo)return;if(P1.has(Z))return;if(P1.size>=5000)P1.clear();P1.add(Z);try{let W=$.workspaceRoot,Y=await o$.findSessionMetadata(Z,W);if(!Y)return;if(Y.title&&Y.title.trim())return;let V=c6(J);if(!V)return;await o$.updateSessionMetadata(Z,Y.projectPath,{title:V}),n$.publish({sessionId:Z,projectPath:Y.projectPath},"session.updated",{title:V})}catch(W){t0.debug?.("[Loop] 自动生成会话标题失败:",W)}}var f2=`<turn_aborted>
|
|
1
|
+
import{cc as M4}from"./chunk-cnhw5mqv.js";import{$c as c2,Id as u0,Kd as K6,Ld as h1,Md as Q6,Td as o$,Wc as vJ,Yc as IJ,Zc as uJ,_c as m2,ec as X$,fd as gJ,gd as T4,hd as R4,id as I2,jd as k1,kd as h4,ld as x4,md as S1,qd as DJ,yd as K1}from"./chunk-ca9cbkf2.js";import{Yd as S4}from"./chunk-53h87fmt.js";import{_d as H0,be as bJ,ce as v0}from"./chunk-qdv0n8yt.js";import{df as eJ}from"./chunk-pshyn3yy.js";import{ef as b4,ff as i0,gf as f4,hf as zJ,kf as E1,lf as V6,mf as BJ,nf as jJ,pf as UJ}from"./chunk-q2exry0f.js";import{$f as r0,_f as J$,cg as E4,gg as H4}from"./chunk-cqqmkwvn.js";import{tg as N$}from"./chunk-e7h4wb45.js";import{Dh as nJ}from"./chunk-4w4wjm49.js";import{Sh as X0}from"./chunk-ecd727xh.js";import{si as k0}from"./chunk-dvv28pkc.js";import{Gi as CJ}from"./chunk-brebh2tm.js";import{Ri as b$,Ti as r6,Ui as P0,Vi as R1,Xi as hJ,Yi as xJ,Zi as kJ}from"./chunk-rkdxqx8m.js";import{_i as L8}from"./chunk-tf7ezqew.js";function A$($){return $.role==="system"&&Array.isArray($.content)}function f$($){if($.role!=="system"||!$.metadata||Array.isArray($.metadata))return!1;return typeof $.metadata==="object"&&$.metadata.contextualProjectRules===!0}class A1{systemMessages;_contextualSystemMessages;_history;_pending=[];_contextRevision=0;context;constructor($,J){this.context=$;let Z=$.messages.find(A$);if(this._contextualSystemMessages=$.messages.filter(f$),Z)this.systemMessages=[Z,...this._contextualSystemMessages];else if(J)this.systemMessages=[{role:"system",content:[{type:"text",text:J,providerOptions:{anthropic:{cacheControl:{type:"ephemeral"}}}}]},...this._contextualSystemMessages];else this.systemMessages=[...this._contextualSystemMessages];this._history=$.messages.filter((W)=>!A$(W)&&!f$(W))}get historyLength(){return this._history.length}get history(){return this._history}get pending(){return this._pending}get contextRevision(){return this._contextRevision}toLLMMessages(){return[...this.systemMessages,...this._history,...this._pending]}getMessagesForLLM(){return this.toLLMMessages()}getHistory(){return this._history}appendPending($){this._pending.push($)}appendUser($){this._pending.push($)}appendAssistant($){this._pending.push($)}appendToolResult($){this._pending.push($)}appendContextualProjectInstructions($){if(!f$($))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($,J){if($==="system")throw Error("Cannot append system control message via appendControl. Use constructor for root system prompt.");this._pending.push(J)}appendDurableControl($){if(!$.id||$.role!=="user")throw Error("Durable control messages require a user role and identity");if(this._history.some((J)=>J.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((J)=>!A$(J)&&!f$(J)),this._contextRevision++}restoreDurableHistory($){this._contextualSystemMessages=$.filter(f$),this._history=$.filter((J)=>!A$(J)&&!f$(J)),this._pending=[],this.syncContextualSystemMessages(),this._contextRevision++}removeMessages($){let J=[this._history.length,this._pending.length,this._contextualSystemMessages.length];if(this._history=this._history.filter((Z)=>!$(Z)),this._pending=this._pending.filter((Z)=>!$(Z)),this._contextualSystemMessages=this._contextualSystemMessages.filter((Z)=>!$(Z)),this.syncContextualSystemMessages(),this._history.length!==J[0]||this._pending.length!==J[1]||this._contextualSystemMessages.length!==J[2])this._contextRevision++}writeback(){this.commitPending(),this.context.messages=[...this._contextualSystemMessages,...this._history]}get hasSystemPrompt(){return this.systemMessages.length>0}}function b6($){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 E6($){return{budget:$.budget,usage:0,consecutiveContinuations:0,lastOutputDelta:0,isSubagent:$.isSubagent??!1}}function S6($,J,Z){return{...$,usage:$.usage+J,lastOutputDelta:J,consecutiveContinuations:Z?$.consecutiveContinuations+1:0}}import Q$ from"node:path";var c4=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"]),l4=/^(LD_.+|DYLD_.+|PATH)$/,M6=/^([A-Za-z_][A-Za-z0-9_]*)=([\w./:@-]*)$/;function l$($){let J=$;while(!0){let Z=J.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!Z)break;let W=Z[1],Y=Z[2],V=W.match(M6);if(!V)break;let K=V[1];if(!c4.has(K))break;J=Y}return J}function uZ($){let J=$;while(!0){let Z=J.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!Z)break;let W=Z[1],Y=Z[2],V=W.match(M6);if(!V)break;let K=V[1];if(l4.test(K))break;J=Y}return J}var i4=[/^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 D2($){let J=$,Z=!0;while(Z){Z=!1;for(let W of i4){let Y=J.match(W);if(Y){J=J.slice(Y[0].length),Z=!0;break}}if(J.startsWith("-- "))J=J.slice(3),Z=!0}return J}function i$($){let J=[],Z="",W=!1,Y=!1,V=!1;for(let K=0;K<$.length;K++){let Q=$[K];if(V){Z+=Q,V=!1;continue}if(Q==="\\"&&!W){Z+=Q,V=!0;continue}if(Q==="'"&&!Y){W=!W,Z+=Q;continue}if(Q==='"'&&!W){Y=!Y,Z+=Q;continue}if(W||Y){Z+=Q;continue}if(Q==="|"){if(K+1<$.length&&$[K+1]==="|"){if(Z.trim())J.push(Z.trim());Z="",K++;continue}return null}if(Q===">"||Q==="<")return null;if(Q==="&"&&K+1<$.length&&$[K+1]==="&"){if(Z.trim())J.push(Z.trim());Z="",K++;continue}if(Q==="&")return null;if(Q===";"){if(Z.trim())J.push(Z.trim());Z="";continue}Z+=Q}if(Z.trim())J.push(Z.trim());return J.length>0?J:null}function T6($){let J=!1,Z=!1,W=!1;for(let Y=0;Y<$.length;Y++){let V=$[Y];if(W){W=!1;continue}if(V==="\\"&&!J){W=!0;continue}if(V==="'"&&!Z){J=!J;continue}if(V==='"'&&!J){Z=!Z;continue}if(J)continue;if(V==="$"){let K=$[Y+1];if(K&&/[A-Za-z_@*#?!$0-9({]/.test(K))return!0}if(V==="`")return!0;if(Z)continue;if(V==="|")return!0;if(V===">"||V==="<")return!0;if(V==="{"){let K=$.slice(Y);if(/^\{[^}]*,[^}]*\}/.test(K)||/^\{[^}]*\.\.[^}]*\}/.test(K))return!0}}return!1}function K$($){let J=[],Z="",W=!1,Y=!1,V=!1;for(let K=0;K<$.length;K++){let Q=$[K];if(V){Z+=Q,V=!1;continue}if(Q==="\\"&&!W){if(V=!0,Y){let X=$[K+1];if(X&&'$`"\\'.includes(X))continue;Z+=Q,V=!1}continue}if(Q==="'"&&!Y){W=!W;continue}if(Q==='"'&&!W){Y=!Y;continue}if(!W&&!Y&&/[ \t]/.test(Q)){if(Z)J.push(Z),Z="";continue}Z+=Q}if(Z)J.push(Z);return J}var r4=new Set(["npm","pnpm","yarn","bun"]),R6=new Set(["biome","eslint","jest","mypy","pyright","pytest","ruff","tsc","vitest"]),n4=new Set(["-u","--fix","--update","--update-snapshot","--updateSnapshot","--watch","--watchAll","--write"]),o4=/[ \t]*;[ \t]*echo[ \t]+"[A-Za-z0-9 _:=.-]*(?:\$\{PIPESTATUS\[0\]\}|\$\?)[A-Za-z0-9 _:=.-]*"[ \t]*$/;function a4($){return $!==void 0&&/^(?:test|lint|build|type-?check)(?::[\w.-]+)*$/i.test($)}function h6($){return $.replace(/\s+2>&1\s*$/,"").trim()}function s4($,J,Z){if(!Z||J.length!==2)return;let W=/^(.+?)[ \t]+&&[ \t]+([\s\S]+)$/.exec($);if(!W)return;let Y=K$(W[1]??"");if(Y.length!==2||Y[0]!=="cd")return;let V=Y[1];if(!V||V==="-")return;let K=Q$.isAbsolute(V)?Q$.resolve(V):Q$.resolve(Z,V);if(!X$.isWithinWorkspace(K,Z))return;return W[2]?.trim()||void 0}function t4($){let J=[],Z=!1,W=!1,Y=!1;for(let V=0;V<$.length;V++){let K=$[V];if(Y){Y=!1;continue}if(K==="\\"&&!Z){Y=!0;continue}if(K==="'"&&!W){Z=!Z;continue}if(K==='"'&&!Z){W=!W;continue}if(K!=="|"||Z||W)continue;if($[V+1]==="|")return;J.push(V)}return J}function e4($){let J=K$($),[Z,W,Y]=J;if(Z!=="head"&&Z!=="tail")return!1;if(J.length===1)return!0;let V=(K)=>K!==void 0&&/^[1-9]\d{0,4}$/.test(K);if(J.length===2)return W?.startsWith("--lines=")&&V(W.slice(8))||W?.startsWith("-")&&V(W.slice(1));return J.length===3&&(W==="-n"||W==="--lines")&&V(Y)}function $5($){let J=h6($.replace(o4,"").trim()),Z=t4(J);if(!Z)return;if(Z.length===0)return x6(J);if(Z.length!==1)return;let W=Z[0];if(W===void 0)return;let Y=h6(J.slice(0,W).trim()),V=J.slice(W+1).trim();if(!Y||!e4(V))return;return x6(Y)}function x6($){let Z=i$($)?.at(-1);if(!Z)return $;let W=K$(Z),[Y,V]=W;if(!(Y==="vitest"||(Y==="npx"||Y==="bunx")&&V==="vitest")||W.some((Q)=>Q==="--configLoader"||Q.startsWith("--configLoader=")))return $;return`${$} --configLoader runner`}function y$($,J){let Z=$5($);if(!Z)return!1;let W=l$(Z),Y=i$(W);if(!Y||T6(W)||/[\r\n]/.test(W))return!1;let V=Y.length===1?Y[0]:s4(W,Y,J);if(!V)return!1;let K=K$(V);if(K.length===0||K.some((B)=>[...n4].some((j)=>B===j||B.startsWith(`${j}=`))))return!1;let[Q,X,H]=K;if(r4.has(Q??""))return a4(X==="run"?H:X)||X==="--test";if((Q==="npx"||Q==="bunx")&&R6.has(X??""))return!0;if(R6.has(Q??""))return!0;if(Q==="node"&&X==="--test")return!0;if(Q==="go"&&["build","test","vet"].includes(X??""))return!0;return Q==="cargo"&&["build","check","clippy","test"].includes(X??"")}function cZ($,J){if($===void 0)return!0;if(typeof $!=="string"||$.split(/[\\/]/).includes(".."))return!1;if(!J)return!Q$.isAbsolute($);let Z=Q$.isAbsolute($)?Q$.resolve($):Q$.resolve(J,$);return X$.isWithinWorkspace(Z,J)}var w2=k0("Agent"),J5=3;function q2($,J,Z){if($!=="length")return{action:"none"};if(J>=J5)return{action:"truncated"};if(b6(Z)==="stop")return w2.info("[Loop] Token budget: diminishing returns detected, skipping recovery"),{action:"budget_stop"};return{action:"recover"}}var Z5=[/:\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],W5=/```[\s\S]{50,}```/,k6="请执行你提到的操作,不要只是描述。使用 Edit/Write/ApplyPatch/Bash 工具来实际修改文件。",Y5=2;function G2($,J,Z=!0){if(!$||J>=Y5)return{action:"none"};if(!Z&&W5.test($))return{action:"retry",prompt:k6};let W=$.slice(-200),Y=W.match(/```/g);if(Y&&Y.length%2!==0)return{action:"none"};if(Z5.some((K)=>K.test(W)))return{action:"retry",prompt:k6};return{action:"none"}}var V5=[/\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}(?:测试|单测|集成测试|检查|构建)/],C6={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},K5={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},Q5="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.",X5="Required verification did not run successfully before the retry limit.",H5=3;function I6($,J,Z,W){if(!Z.success)return;if(["Edit","Write","ApplyPatch","NotebookEdit"].includes(J)){$.clear();return}if(J==="Bash"&&typeof Z.metadata?.command==="string"&&Z.metadata.exit_code===0&&y$(Z.metadata.command,W)){$.add(Z.metadata.command);return}if(!["Task","TaskOutput"].includes(J))return;let Y=Z.metadata?.verificationCommands;if(!Array.isArray(Y))return;for(let V of Y)if(typeof V==="string"&&y$(V,W))$.add(V)}function F2($,J,Z){if(!$||!V5.some((X)=>X.test($)))return{action:"none"};let W=Object.keys(C6).filter((X)=>C6[X].test($)),Y=[...J],V=W.filter((X)=>!Y.some((H)=>K5[X].test(H)));if(W.length>0?V.length===0:Y.some((X)=>y$(X)))return{action:"none"};if(Z>=H5)return{action:"fail",message:X5};let Q=W.length>1&&V.length>0?` Missing successful verification categories: ${V.join(", ")}.`:"";return{action:"retry",prompt:`${Q5}${Q}`}}var z5=[/\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|子代理|子智能体)/],u6=[/\b(?:do not|don't|never)\s+(?:delegate|call|use|invoke)\b/i,/(?:不要|禁止|无需)(?:委派|调用|使用).{0,20}(?:Task|子代理|子智能体)?/];function g6($){return typeof $==="string"&&u6.some((J)=>J.test($))}var B5=[/\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|子代理)/],j5=[/\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 U5($){if(typeof $!=="string")return;if(j5.some((J)=>J.test($)))return"multiple-allowed";return B5.some((J)=>J.test($))?"required":void 0}function r$($){for(let J of $){let Z=U5(J);if(Z!==void 0)return Z==="required"}return!1}var D5="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.",w5="Required delegation did not complete before the retry limit.",q5=3;function p6($,J,Z){let W=(typeof $==="string"?[$]:$??[]).map((K)=>K.trim()).filter(Boolean),Y=r$(W),V=!1;if(!Y)for(let K of W){if(u6.some((Q)=>Q.test(K)))break;if(z5.some((Q)=>Q.test(K))){V=!0;break}}if(W.length===0||!Y&&!V||J.has("Task"))return{action:"none"};if(Z>=q5)return{action:"fail",message:w5};return{action:"retry",prompt:D5}}var G5=[/\b(?:use|create|enter|start|work\s+(?:in|inside))\b.{0,60}\bworktree\b/i,/(?:使用|创建|进入).{0,30}(?:worktree|工作树)/i],F5=[/\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 d6($){return L5.reduce((J,Z)=>J.replace(Z," "),$)}function N1($){if(typeof $!=="string")return!1;let J=d6($);return G5.some((Z)=>Z.test(J))}var O5="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.",A5="Required worktree lifecycle did not complete before the retry limit.",y5=3;function m6($,J,Z){if(!$)return{action:"none"};let W=d6($);if(!N1(W))return{action:"none"};let Y=F5.some((K)=>K.test(W));if(J.has("TaskWorktree"))return{action:"none"};let V=!J.has("EnterWorktree")?"EnterWorktree":Y&&!J.has("ExitWorktree")?"ExitWorktree":void 0;if(!V)return{action:"none"};if(Z>=y5)return{action:"fail",message:A5};return{action:"retry",tool:V,prompt:V==="EnterWorktree"?O5:f5}}var v6=30000;async function L2($){try{let Z=N$.getInstance().executeStopHooks({projectDir:$.workspaceRoot??X0(),sessionId:$.sessionId,permissionMode:$.permissionMode,reason:$.reason,abortSignal:$.abortSignal}),W,Y=new Promise((V)=>{W=setTimeout(()=>V("timeout"),v6)});try{let V=await Promise.race([Z,Y]);if(V==="timeout")return w2.warn(`[Loop] Stop hook 超时 (${v6}ms),按 shouldStop: true 处理`),{action:"stop"};let K=V;if(!K.shouldStop)return{action:"continue",reason:K.continueReason};return{action:"stop"}}finally{clearTimeout(W)}}catch(J){return w2.warn("[Loop] Stop hook execution failed:",J),{action:"stop"}}}async function N5($,J){let Z;while(!(Z=await $.next()).done)if(J)await J(Z.value);return Z.value}var P5=[/<system-reminder>[\s\S]*?<\/system-reminder>/gi,/<file[^>]*>[\s\S]*?<\/file>/gi,/<hooks_context>[\s\S]*?<\/hooks_context>/gi,/<[^>]+>/g];function _5($){if(typeof $==="string")return $;if(Array.isArray($))return $.map((J)=>{if(typeof J==="string")return J;if(J&&typeof J==="object"&&"text"in J){let Z=J.text;return typeof Z==="string"?Z:""}return""}).join(" ");return""}function b5($){let J=$;for(let X of P5)J=J.replace(X," ");J=J.replace(/^\s*\/[a-zA-Z][\w-]*\s+/,"");let Z=J.replace(/\s+/g," ").trim();if(!Z)return"";let W=Z.match(/^(.+?)(?:[.!?]\s|[。!?](?=\S|$)|$)/),Y=W&&W[1].length>=6?W[1]:Z;if(Y=Y.trim().replace(/[\s.。!!??,,;;::-]+$/,""),Y.length<=60)return Y;let V=Y.slice(0,60),K=V.lastIndexOf(" ");return`${(K>36?V.slice(0,K):V).trimEnd()}…`}function c6($){return b5(_5($))}import{EventEmitter as E5}from"events";import l6 from"node:path";function O2($){if(r6($.sessionId),!l6.isAbsolute($.projectPath))throw Error("projectPath must be absolute");return{sessionId:$.sessionId,projectPath:l6.resolve($.projectPath)}}function i6($){let J=O2($);return JSON.stringify([J.projectPath,J.sessionId])}function Z3($,J){return i6($)===i6(J)}class P$ extends E5{static instance;constructor(){super();this.setMaxListeners(100)}static getInstance(){if(!P$.instance)P$.instance=new P$;return P$.instance}publish($,J,Z,W){let Y=O2($);this.emit("event",{sessionId:Y.sessionId,projectPath:Y.projectPath,type:J,...W!==void 0?{seq:W}:{},properties:Z})}subscribe($){return this.on("event",$),()=>this.off("event",$)}}var n$=P$.getInstance();var t0=k0("Agent"),P1=new Set;async function S5($,J){let Z=$.sessionId;if(!Z||$.subagentInfo)return;if(P1.has(Z))return;if(P1.size>=5000)P1.clear();P1.add(Z);try{let W=$.workspaceRoot,Y=await o$.findSessionMetadata(Z,W);if(!Y)return;if(Y.title&&Y.title.trim())return;let V=c6(J);if(!V)return;await o$.updateSessionMetadata(Z,Y.projectPath,{title:V}),n$.publish({sessionId:Z,projectPath:Y.projectPath},"session.updated",{title:V})}catch(W){t0.debug?.("[Loop] 自动生成会话标题失败:",W)}}var f2=`<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>`,H$="Tool execution was blocked because its durable call record could not be committed. No tool side effect was started.",n6="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 _$ extends Error{phase;constructor($,J){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.",J);this.phase=$;this.name="DurableConversationPersistenceError"}}function z$($){return $.executionEngine?.getContextManager()}async function l0($,J,Z,W=null,Y,V={}){let K=V.required??$.executionEngine!==void 0;try{let Q=z$($),X=typeof Z==="string"?Z.trim()!=="":Z.some((H)=>H.type==="text"?H.text.trim()!=="":!0);if(Q&&J.sessionId&&X){let H=await Q.saveMessage(J.sessionId,"user",Z,W,Y,J.subagentInfo);if(K&&!H)throw Error("Durable user-message commit returned no identity");if(Y?.clientVisible!==!1)S5(J,Z);return H}if(K&&J.sessionId&&X)throw Error("Durable user-message storage is unavailable")}catch(Q){if(t0.warn("[Loop] 保存用户消息失败:",Q),K)throw new _$("user_message",{cause:Q})}return null}async function C0($,J,Z,W,Y,V,K={}){let Q=K.required??$.executionEngine!==void 0;try{let X=z$($),H=Boolean(Z.trim()||Y?.trim());if(X&&J.sessionId&&H){let B=await X.saveMessage(J.sessionId,"assistant",Z,W,V,J.subagentInfo,Y);if(Q&&!B)throw Error("Durable assistant-message commit returned no identity");return B}if(Q&&J.sessionId&&H)throw Error("Durable assistant-message storage is unavailable")}catch(X){if(t0.warn("[Loop] 保存助手消息失败:",X),Q)throw new _$("assistant_message",{cause:X})}return null}async function o6($,J,Z){try{let W=z$($);if(W&&J.sessionId)return await W.saveMessage(J.sessionId,"system",f2,Z,void 0,J.subagentInfo)}catch(W){t0.warn("[Loop] 保存中断边界失败:",W)}return null}async function a6($,J,Z,W,Y){try{let V=z$($);if(!V||!J.sessionId||Z.length===0)return null;return await V.saveMessage(J.sessionId,"system",`<contextual-project-instructions-ref count="${Z.length}" />`,Y,{contextualProjectRules:!0,ruleReferences:JSON.parse(JSON.stringify(Z.map((K)=>({...K})))),triggerPaths:[...W]},J.subagentInfo)}catch(V){t0.warn("[Loop] 保存 contextual project rules provenance 失败:",V)}return null}async function A2($,J,Z,W,Y,V={}){try{let K=z$($);if(K&&J.sessionId){let Q=await K.saveToolUse(J.sessionId,Z,W,Y,J.subagentInfo,V.providerToolCallId);if(V.required&&!Q)throw Error("Durable tool-use commit returned no identity");return Q}if(V.required&&J.sessionId)throw Error("Durable tool-use storage is unavailable")}catch(K){if(t0.warn("[Loop] 保存工具调用失败:",K),V.required)throw K}return null}async function _1($,J,Z,W,Y,V,K,Q,X,H={}){try{let B=z$($);if(B&&J.sessionId){let j=await B.saveToolResult(J.sessionId,Z,W,Y,V,K,J.subagentInfo,Q,X);if(H.required&&!j)throw Error("Durable tool-result commit returned no identity");return j}if(H.required&&J.sessionId)throw Error("Durable tool-result storage is unavailable")}catch(B){if(t0.warn("[Loop] 保存工具结果失败:",B),H.required)throw B}return null}async function a$($,J,Z,W,Y={}){try{let V=z$($);if(V&&J.sessionId){let K=await V.saveCompaction(J.sessionId,Z,W,null);if(Y.required&&!K)throw Error("Compaction checkpoint commit returned no identity");return K||null}if(Y.required&&J.sessionId)throw Error("Compaction checkpoint storage is unavailable")}catch(V){if(t0.warn("[Loop] 保存压缩数据失败:",V),Y.required)throw V}return null}async function D0($){let{deps:J,context:Z,state:W,assistantContent:Y,assistantReasoningContent:V,lastMessageUuid:K,controlPrompt:Q,controlMetadata:X}=$;W.appendAssistant({role:"assistant",content:Y,reasoningContent:V});let H=K,B=await C0(J,Z,Y,H,V);if(B)H=B;if(Q!==void 0){let j={role:"user",content:Q};if(X)j.metadata=X;W.appendControl("user",j);let z=await l0(J,Z,j.content,H,X);if(z)H=z}return H}import{createHash as X6}from"node:crypto";import{promises as l5}from"node:fs";import i5 from"node:path";import{nanoid as e0}from"nanoid";import*as J0 from"node:fs/promises";import*as B$ from"node:path";var s6={enabled:!0,maxIndexLines:200};var M5="memory",t6="MEMORY.md";class y2{memoryDir;config;initialized=!1;constructor($,J,Z){if(Z)this.memoryDir=Z;else{let W=b$($);this.memoryDir=B$.join(W,M5)}this.config={...s6,...J}}async initialize(){if(this.initialized)return;await J0.mkdir(this.memoryDir,{recursive:!0}),this.initialized=!0}async loadIndex(){if(!this.config.enabled)return null;await this.initialize();let $=B$.join(this.memoryDir,t6);try{let J=await J0.readFile($,"utf-8");if(!J.trim())return null;let Z=J.split(`
|
|
4
4
|
`),Y=Z.slice(0,this.config.maxIndexLines).join(`
|
|
@@ -83,7 +83,7 @@ Full output saved to: ${Q}`}catch{return`${J}
|
|
|
83
83
|
|
|
84
84
|
${Y}`}}import M8 from"node:path";import{nanoid as T8}from"nanoid";import*as h0 from"node:fs/promises";import*as EJ from"node:path";import{Mutex as D8}from"async-mutex";import w8 from"write-file-atomic";var PJ=120,C2=128;function J1($){if(!Array.isArray($)||$.length>120||!$.every((J)=>typeof J==="string"&&J.length>0&&J.length<=128))return;return[...new Set($)]}function U8($){if(!$||typeof $!=="object"||Array.isArray($))return[];if(!("recovery"in $)||!$.recovery)return[];let J=$.recovery;if(typeof J!=="object"||Array.isArray(J))return[];if(!("version"in J)||J.version!==1&&J.version!==2||!("inputMessageIds"in J)||!("hadSuccessfulToolResult"in J)||typeof J.hadSuccessfulToolResult!=="boolean"||!("emptyFinalCorrectionSpent"in J)||typeof J.emptyFinalCorrectionSpent!=="boolean"||!("acknowledgedInputMessageIds"in $))return[];if(J.version===2&&(!("interruptedToolCallCount"in J)||!Number.isSafeInteger(J.interruptedToolCallCount)||J.interruptedToolCallCount<0))return[];let Z=J1(J.inputMessageIds),W=J1($.acknowledgedInputMessageIds);if(!Z||!W)return[];let Y=new Set(Z);return W.filter((V)=>Y.has(V))}function M1($,J){let Z=$[J];if(Z?.type!=="turn_aborted")return[];let W=U8(Z.data);if(W.length===0)return[];let Y=-1;for(let K=J-1;K>=0;K--){let Q=$[K];if(Q.type==="turn_started"){if(Q.data.turnId!==Z.data.turnId)return[];Y=K;break}if(Q.type==="turn_completed"||Q.type==="turn_aborted")return[]}if(Y<0)return[];let V=new Set;for(let K=Y+1;K<J;K++){let Q=$[K];if(Q.type!=="message_created"||Q.data.role!=="user")continue;let X=Q.data.metadata,H=Q.data.inboxMessageId!==void 0?Q.data.inboxMessageId:X!==null&&typeof X==="object"&&!Array.isArray(X)?X.inboxMessageId:void 0;if(typeof H==="string"&&H.length>0&&H.length<=128)V.add(H)}return W.filter((K)=>V.has(K))}var T1=1,Z1=8388608;function _J($,J){let Z={version:T1,sessionId:$,messages:J.map(({recovered:W,...Y})=>Y)};return`${JSON.stringify(Z)}
|
|
85
85
|
`}function v2($,J){return $ instanceof Error&&"code"in $&&$.code===J}function q8($){if(typeof $==="string")return!0;if(!Array.isArray($))return!1;return $.every((J)=>{if(!J||typeof J!=="object"||!("type"in J))return!1;if(J.type==="text")return"text"in J&&typeof J.text==="string";return J.type==="image_url"&&"image_url"in J&&typeof J.image_url==="object"&&J.image_url!==null&&"url"in J.image_url&&typeof J.image_url.url==="string"})}function G8($,J,Z){let W;try{W=JSON.parse($)}catch(V){throw Error(`Invalid steering inbox JSON: ${J}`,{cause:V})}if(!W||typeof W!=="object"||!("version"in W)||W.version!==T1||!("sessionId"in W)||W.sessionId!==Z||!("messages"in W)||!Array.isArray(W.messages))throw Error(`Invalid steering inbox record: ${J}`);let Y=W.messages.map((V)=>{if(!V||typeof V!=="object"||!("id"in V)||typeof V.id!=="string"||!("content"in V)||!q8(V.content)||!("queuedAt"in V)||typeof V.queuedAt!=="number"||"persisted"in V&&typeof V.persisted!=="boolean"||"origin"in V&&V.origin!=="user"&&V.origin!=="background_subagent"&&V.origin!=="team_message"||"metadata"in V&&(V.metadata===null||typeof V.metadata!=="object"||Array.isArray(V.metadata))||"outputSchema"in V&&V.outputSchema!==void 0&&(!V.outputSchema||typeof V.outputSchema!=="object"||Array.isArray(V.outputSchema)))throw Error(`Invalid steering inbox message: ${J}`);let K="outputSchema"in V&&V.outputSchema!==void 0?h1(V.outputSchema).schema:void 0;return{id:V.id,content:V.content,queuedAt:V.queuedAt,..."persisted"in V&&V.persisted===!0?{persisted:!0}:{},..."origin"in V&&V.origin?{origin:V.origin}:{},..."metadata"in V&&V.metadata?{metadata:JSON.parse(JSON.stringify(V.metadata))}:{},...K?{outputSchema:K}:{}}});return{version:T1,sessionId:Z,messages:Y}}function F8($){return new Set($.flatMap((J,Z)=>{if(J.type==="inbox_acknowledged")return J.data.messageIds;if(J.type==="turn_aborted")return M1($,Z);return[]}))}class x1{workspaceRoot;sessionId;filePath;mutex=new D8;messages=[];constructor($,J,Z){this.workspaceRoot=$;this.sessionId=J;this.filePath=Z}static async open($,J){let Z=new x1($,J,R1($,J));return await Z.loadAndReconcile(),Z}async enqueue($,J){return this.mutex.runExclusive(async()=>{if(J&&!J(this.messages))return!1;let Z=[...this.messages,{...$,recovered:!1}],W=_J(this.sessionId,Z);if(Buffer.byteLength(W)>Z1)return!1;return await this.persist(Z,W),this.messages=Z,!0})}async acknowledge($){if($.length===0)return;let J=new Set($);await this.mutex.runExclusive(async()=>{let Z=this.messages.filter((W)=>!J.has(W.id));this.messages=Z,await this.persist(Z)})}list(){return this.messages.map(($)=>({...$,content:typeof $.content==="string"?$.content:$.content.map((J)=>J.type==="text"?{...J}:{...J,image_url:{...J.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 $={version:T1,sessionId:this.sessionId,messages:[]};try{if((await h0.stat(this.filePath)).size>Z1)throw Error(`Steering inbox exceeds ${Z1} bytes: ${this.filePath}`);await h0.chmod(this.filePath,384),$=G8(await h0.readFile(this.filePath,"utf8"),this.filePath,this.sessionId)}catch(Y){if(!v2(Y,"ENOENT"))throw Y}let J=P0(this.workspaceRoot,this.sessionId),Z=new Set;try{Z=F8(bJ(await h0.readFile(J,"utf8"),J))}catch(Y){if(!v2(Y,"ENOENT"))throw Y}let W=$.messages.filter((Y)=>!Z.has(Y.id)).map((Y)=>({...Y,recovered:!0}));if(this.messages=W,W.length!==$.messages.length)await this.persist(W)})}async persist($,J){if(await h0.mkdir(EJ.dirname(this.filePath),{recursive:!0,mode:448}),$.length===0){await h0.unlink(this.filePath).catch((W)=>{if(!v2(W,"ENOENT"))throw W});return}let Z=J??_J(this.sessionId,$);if(Buffer.byteLength(Z)>Z1)throw Error(`Steering inbox exceeds ${Z1} bytes: ${this.filePath}`);await w8(this.filePath,Z,{encoding:"utf8",mode:384,fsync:!0})}}import*as I0 from"node:fs/promises";import*as pJ from"node:path";import{nanoid as V0}from"nanoid";var SJ=256;class w0{sessionId;projectPath;static instances=new Map;store;subscribers=new Set;highestSeq=0;constructor($,J){this.sessionId=$;this.projectPath=J;this.store=new v0(P0(J,$))}static for($,J){let Z=`${J}\x00${$}`,W=w0.instances.get(Z);if(!W)W=new w0($,J),w0.instances.set(Z,W),w0.pruneIdleInstances(Z);else w0.instances.delete(Z),w0.instances.set(Z,W);return W}static release($,J){w0.instances.delete(`${J}\x00${$}`)}static pruneIdleInstances($){if(w0.instances.size<=SJ)return;for(let[J,Z]of w0.instances){if(J===$||Z.subscribers.size>0)continue;if(w0.instances.delete(J),w0.instances.size<=SJ)return}}get lastSeq(){return this.highestSeq}async commit($){let J=await this.store.append($);return this.record(J),J}async commitBatch($){if($.length===0)return[];let J=await this.store.appendBatch($);for(let Z of J)this.record(Z);return J}async commitValidated($){let J=await this.store.appendValidated($);return this.record(J),J}async commitValidatedBatch($){let J=await this.store.appendValidatedBatch($);for(let Z of J)this.record(Z);return J}emitDelta($){for(let J of this.subscribers)J.onDelta?.($);n$.publish({sessionId:this.sessionId,projectPath:this.projectPath},"delta",{delta:$})}subscribe($,J){if(this.subscribers.add($),J?.fromSeq!==void 0)this.replay($,J.fromSeq);return()=>{this.subscribers.delete($),w0.pruneIdleInstances()}}async replay($,J){let Z=await this.store.readFromSeq(J);for(let W of Z){if(I2(W))continue;await $.onCommitted(W)}}record($){if(typeof $.seq==="number"&&$.seq>this.highestSeq)this.highestSeq=$.seq;if(I2($))return;for(let J of this.subscribers){let Z=J.onCommitted($);if(Z)Promise.resolve(Z).catch(()=>{return})}n$.publish({sessionId:this.sessionId,projectPath:this.projectPath},`committed.${$.type}`,{event:$},$.seq)}}function U$($){let J=null,Z=null;for(let W of $){if(W.type==="turn_started"){J=W.data;continue}if(W.type==="turn_completed")Z={type:"turn_completed",data:W.data};else if(W.type==="turn_aborted")Z={type:"turn_aborted",data:W.data};else continue;if(J?.turnId===Z.data.turnId)J=null}return{active:J,lastTerminal:Z}}class A0 extends Error{}var O8="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 u2($,J){let Z=$.findLastIndex((W)=>W.type==="turn_started"&&W.data.turnId===J);if(Z<0)return!1;return $.slice(Z+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 MJ($,J){let Z=$.findLastIndex((Y)=>Y.type==="turn_started"&&Y.data.turnId===J);if(Z<0)return[];let W=[];for(let Y of $.slice(Z+1)){if(Y.type==="turn_started"&&Y.data.turnId!==J||(Y.type==="turn_completed"||Y.type==="turn_aborted")&&Y.data.turnId===J)break;if(Y.type!=="message_created"||Y.data.role!=="user")continue;let V=Y.data.metadata,K=Y.data.inboxMessageId!==void 0?Y.data.inboxMessageId:V!==null&&typeof V==="object"&&!Array.isArray(V)?V.inboxMessageId:void 0;if(typeof K==="string"&&K.length>0&&K.length<=C2)W.push(K)}return[...new Set(W)]}function dJ($){if(!$||typeof $!=="object"||Array.isArray($))return;if(!("version"in $)||$.version!==1&&$.version!==2)return;let J="inputMessageIds"in $?J1($.inputMessageIds):void 0;if(!J||!("hadSuccessfulToolResult"in $)||typeof $.hadSuccessfulToolResult!=="boolean"||!("emptyFinalCorrectionSpent"in $)||typeof $.emptyFinalCorrectionSpent!=="boolean")return;let Z=$.version===1?0:("interruptedToolCallCount"in $)&&Number.isSafeInteger($.interruptedToolCallCount)&&$.interruptedToolCallCount>=0?$.interruptedToolCallCount:void 0;if(Z===void 0)return;return{version:$.version,inputMessageIds:J,hadSuccessfulToolResult:$.hadSuccessfulToolResult,interruptedToolCallCount:Z,emptyFinalCorrectionSpent:$.emptyFinalCorrectionSpent}}function f8($,J){let Z=$.findLastIndex((Q)=>Q.type==="turn_started"&&Q.data.turnId===J);if(Z<0)return 0;let W=$.findIndex((Q,X)=>X>Z&&Q.type==="turn_started"&&Q.data.turnId!==J),Y=$.slice(Z+1,W<0?void 0:W),V=new Set(Y.flatMap((Q)=>{if(Q.type!=="part_created"||Q.data.partType!=="tool_call")return[];let X=Q.data.payload;return X&&typeof X==="object"&&!Array.isArray(X)?[typeof X.toolCallId==="string"?X.toolCallId:Q.data.partId]:[Q.data.partId]})),K=new Set;for(let Q of Y){if(Q.type!=="part_created"||Q.data.partType!=="tool_result")continue;let X=Q.data.payload;if(!X||typeof X!=="object"||Array.isArray(X))continue;let H=typeof X.toolCallId==="string"?X.toolCallId:Q.data.partId,B=X.metadata;if(V.has(H)&&B&&typeof B==="object"&&!Array.isArray(B)&&B.processRestartRecovery===!0&&B.sideEffectsUncertain===!0)K.add(H)}return K.size}function mJ($){return new Set($.flatMap((J,Z)=>{if(J.type==="inbox_acknowledged")return J.data.messageIds;if(J.type==="turn_aborted")return M1($,Z);return[]}))}function g2($,J,Z=[]){let W=dJ(J.data.recovery);if(!W)return;if($.some((Q)=>Q.type==="turn_recovery_acknowledged"&&Q.data.turnId===J.data.turnId))return;let Y=mJ($);for(let Q of Z)Y.add(Q);let V=W.inputMessageIds.filter((Q)=>!Y.has(Q)),K=W.version===1?f8($,J.data.turnId):W.interruptedToolCallCount;if(V.length===0&&!W.hadSuccessfulToolResult&&K===0)return;return{turnId:J.data.turnId,outcome:"aborted",inputMessageIds:V,hadSuccessfulToolResult:W.hadSuccessfulToolResult,...K>0?{interruptedToolCallCount:K}:{},emptyFinalCorrectionSpent:W.emptyFinalCorrectionSpent}}function W1($){for(let J=$.length-1;J>=0;J--){let Z=$[J];if(Z.type!=="turn_aborted")continue;let W=g2($,Z);if(W)return W}return}var A8=1e4,y8=1e5,N8=2592000000,TJ=128,P8=1e6,_8=256;function b8($){if(!$||typeof $!=="object"||Array.isArray($))return;let J=$;if(typeof J.goalId!=="string"||J.goalId.length===0||J.goalId.length>TJ||typeof J.verificationAttempt!=="number"||!Number.isSafeInteger(J.verificationAttempt)||J.verificationAttempt<1||J.verificationAttempt>P8||typeof J.verifierSessionId!=="string"||J.verifierSessionId.length===0||J.verifierSessionId.length>TJ||typeof J.evidenceSha256!=="string"||!/^[a-f0-9]{64}$/.test(J.evidenceSha256)||typeof J.goalUpdatedAt!=="string"||!Number.isFinite(Date.parse(J.goalUpdatedAt)))return;return{goalId:J.goalId,verificationAttempt:J.verificationAttempt,verifierSessionId:J.verifierSessionId,evidenceSha256:J.evidenceSha256,goalUpdatedAt:J.goalUpdatedAt}}function cJ($,J){let Z=$.data.metadata;if(!Z||typeof Z!=="object"||Array.isArray(Z))return;let W=Z.turnFinalization;if(!W||typeof W!=="object"||Array.isArray(W))return;let Y=W,V=Y.turnId,K=Y.inputMessageIds,Q=Y.turnsCount,X=Y.toolCallsCount,H=Y.durationMs,B=Array.isArray(K)?K.filter((z)=>typeof z==="string"&&z.length>0&&z.length<=C2):[];if(typeof V!=="string"||V.length===0||V.length>128||J!==void 0&&V!==J||!Array.isArray(K)||K.length>PJ||B.length!==K.length||typeof Q!=="number"||!Number.isSafeInteger(Q)||Q<0||Q>A8||typeof X!=="number"||!Number.isSafeInteger(X)||X<0||X>y8||typeof H!=="number"||!Number.isSafeInteger(H)||H<0||H>N8)return;let j;if("goalFinalization"in Y){if(j=b8(Y.goalFinalization),!j)return}return{turnId:V,inputMessageIds:[...new Set(B)],turnsCount:Q,toolCallsCount:X,durationMs:H,...j?{goalFinalization:j}:{}}}function RJ($,J){let Z=$.findLastIndex((W)=>W.type==="turn_started"&&W.data.turnId===J);if(Z<0)return;for(let W=$.length-1;W>Z;W--){let Y=$[W];if(Y?.type!=="message_created")continue;let V=cJ(Y,J);if(V)return V}return}function E8($){for(let J=$.length-1;J>=0;J--){let Z=$[J];if(Z?.type!=="message_created")continue;let W=cJ(Z);if(!W?.goalFinalization)continue;if(!$.slice(0,J).some((V)=>V.type==="turn_started"&&V.data.turnId===W.turnId))continue;return{turnId:W.turnId,finalization:W}}return}function R$($,J){let Z=J?$.findLastIndex((X)=>X.type==="turn_started"&&X.data.turnId===J):-1;if(J&&Z<0)return{all:[],orphaned:[],hadSuccessfulResult:!1};let W=new Map,Y=new Set,V=new Set,K=new Set;for(let X of $.slice(Z+1)){if(X.type==="interaction_requested"){K.add(X.data.toolCallId);continue}if(X.type!=="part_created")continue;let H=X.data.payload&&typeof X.data.payload==="object"&&!Array.isArray(X.data.payload)?X.data.payload:{},B=typeof H.toolCallId==="string"?H.toolCallId:X.data.partId;if(X.data.partType==="tool_call")W.set(B,{toolCallId:B,messageId:X.data.messageId,toolName:typeof H.toolName==="string"?H.toolName:"unknown",input:H.input??null});else if(X.data.partType==="tool_result"){if(Y.add(B),Y.add(X.data.partId),Y.add(X.data.messageId),W.has(B)&&H.error===null)V.add(B)}}let Q=[...W.values()];return{all:Q,orphaned:Q.filter((X)=>!Y.has(X.toolCallId)&&!K.has(X.toolCallId)),hadSuccessfulResult:Q.some((X)=>V.has(X.toolCallId))}}class _0{static sessionInitializationRuns=new Map;projectPath;maxSessions;version;initializedSessions=new Set;constructor($=X0(),J=100,Z=CJ()){this.projectPath=$,this.maxSessions=J,this.version=Z}createEvent($,J,Z){return{id:V0(),sessionId:J,projectPath:this.projectPath,timestamp:new Date().toISOString(),type:$,cwd:this.projectPath,gitBranch:hJ(this.projectPath),version:this.version,data:Z}}log($){return w0.for($,this.projectPath)}async ensureSessionCreated($,J){let Z=P0(this.projectPath,$);if(this.initializedSessions.delete($)){this.initializedSessions.add($);return}let W=_0.sessionInitializationRuns.get(Z);if(!W)W=this.initializeSessionFile($,Z,J),_0.sessionInitializationRuns.set(Z,W);try{await W,this.rememberInitializedSession($)}finally{if(_0.sessionInitializationRuns.get(Z)===W)_0.sessionInitializationRuns.delete(Z)}}rememberInitializedSession($){this.initializedSessions.delete($),this.initializedSessions.add($);while(this.initializedSessions.size>_8){let J=this.initializedSessions.values().next().value;if(J===void 0)return;this.initializedSessions.delete(J)}}async initializeSessionFile($,J,Z){if((await new v0(J).readAll()).length>0)return;let V=new Date().toISOString(),K={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:V,updatedAt:V},Q=this.createEvent("session_created",$,K);await this.log($).commit(Q)}buildCompactionMetadata($){let J={trigger:$.trigger,preTokens:$.preTokens};if($.reason)J.reason=$.reason;if($.strategy)J.strategy=$.strategy;if($.preTokenSource)J.preTokenSource=$.preTokenSource;if($.estimatedPendingTokens!==void 0)J.estimatedPendingTokens=$.estimatedPendingTokens;if($.postTokens!==void 0)J.postTokens=$.postTokens;if($.sampleAttempts!==void 0)J.sampleAttempts=$.sampleAttempts;if($.inputReductions!==void 0)J.inputReductions=$.inputReductions;if($.messagesOmitted!==void 0)J.messagesOmitted=$.messagesOmitted;if($.filesOmitted!==void 0)J.filesOmitted=$.filesOmitted;if($.imagesOmitted!==void 0)J.imagesOmitted=$.imagesOmitted;if($.fallbackTargetTokens!==void 0)J.fallbackTargetTokens=$.fallbackTargetTokens;if($.fallbackMessagesOmitted!==void 0)J.fallbackMessagesOmitted=$.fallbackMessagesOmitted;if($.fallbackMessagesTruncated!==void 0)J.fallbackMessagesTruncated=$.fallbackMessagesTruncated;if($.failureReason)J.failureReason=$.failureReason;if($.filesIncluded)J.filesIncluded=$.filesIncluded;if($.replacementMessages)J.checkpointVersion=IJ;return J}async initialize(){try{let $=b$(this.projectPath);await I0.mkdir($,{recursive:!0,mode:493}),console.log(`[PersistentStore] 初始化存储目录: ${$}`)}catch($){console.warn("[PersistentStore] 无法创建持久化存储目录:",$)}}async saveMessage($,J,Z,W=null,Y,V,K){try{await this.ensureSessionCreated($,V);let Q=new Date().toISOString(),X=V0(),H={messageId:X,role:J,parentMessageId:W??void 0,inboxMessageId:Y?.inboxMessageId,createdAt:Q,model:Y?.model,usage:Y?.usage,metadata:Y?JSON.parse(JSON.stringify(Y)):void 0},B=this.createEvent("message_created",$,H),j=J==="assistant"&&K?.trim()?[this.createEvent("part_created",$,{partId:V0(),messageId:X,partType:"reasoning",payload:{text:K},createdAt:Q})]:[],z=typeof Z==="string"?[this.createEvent("part_created",$,{partId:V0(),messageId:X,partType:"text",payload:{text:Z},createdAt:Q})]:Z.map((U)=>this.createEvent("part_created",$,{partId:V0(),messageId:X,partType:U.type==="text"?"text":"image",payload:U.type==="text"?{text:U.text}:{mimeType:S8(U.image_url.url)??"image/png",dataUrl:U.image_url.url},createdAt:Q}));return await this.log($).commitBatch([B,...j,...z]),X}catch(Q){throw console.error(`[PersistentStore] 保存消息失败 (session: ${$}):`,Q),Q}}async acknowledgeInboxMessages($,J){if(J.length===0)return;await this.ensureSessionCreated($);let Z=new Date().toISOString();await this.log($).commit(this.createEvent("inbox_acknowledged",$,{messageIds:[...J],acknowledgedAt:Z}))}async acknowledgeTurnRecovery($,J){await this.ensureSessionCreated($);try{await this.log($).commitValidated((Z)=>{let W=H0(Z);if(W.some((V)=>V.type==="turn_recovery_acknowledged"&&V.data.turnId===J))throw new A0;let Y=W.findLast((V)=>V.type==="turn_aborted"&&V.data.turnId===J);if(!Y||!g2(W,Y))throw new A0;return this.createEvent("turn_recovery_acknowledged",$,{turnId:J,acknowledgedAt:new Date().toISOString()})})}catch(Z){if(!(Z instanceof A0))throw Z}}async persistBackgroundSubagentCompletion($,J){if(J.inboxMessageId!==`background-subagent-completion:${J.childSessionId}`)return{eligible:!1,acknowledged:!1,persisted:!1};await this.ensureSessionCreated($);let Z={eligible:!1,acknowledged:!1,persisted:!1};return await this.log($).commitValidatedBatch((W)=>{let Y=H0(W),V=Y.some((z)=>z.type==="inbox_acknowledged"&&z.data.messageIds.includes(J.inboxMessageId)),K=Y.find((z)=>z.type==="message_created"&&z.data.inboxMessageId===J.inboxMessageId),Q=Y.findLast((z)=>{if(z.type!=="part_created"||z.data.partType!=="tool_call"||!z.data.payload||typeof z.data.payload!=="object"||Array.isArray(z.data.payload))return!1;let U=z.data.payload;if(U.toolName!=="Task"||!U.input||typeof U.input!=="object"||Array.isArray(U.input))return!1;let N=U.input,b=N.resume_from??N.resume;return N.run_in_background===!0&&N.subagent_session_id===J.childSessionId&&N.description===J.subagentRef.subagentDescription&&(N.subagent_type===void 0||N.subagent_type===J.subagentRef.subagentType)&&(N.resume_from===void 0||N.resume===void 0||N.resume_from===N.resume)&&(b===void 0?J.subagentRef.subagentResumedFrom===void 0:b===J.subagentRef.subagentResumedFrom)});if(!Q)return Z={eligible:!1,acknowledged:V,persisted:!1,...K?{messageId:K.data.messageId}:{}},[];if(V)return Z={eligible:!0,acknowledged:!0,persisted:!1,...K?{messageId:K.data.messageId}:{}},[];let X=Y.find((z)=>z.type==="part_created"&&z.data.partType==="subtask_ref"&&z.data.payload!==null&&typeof z.data.payload==="object"&&!Array.isArray(z.data.payload)&&z.data.payload.childSessionId===J.childSessionId&&z.data.payload.status===J.subagentRef.subagentStatus);if(K&&X)return Z={eligible:!0,acknowledged:!1,persisted:!1,messageId:K.data.messageId},[];let H=new Date().toISOString(),B=K?.data.messageId??V0(),j=[];if(!K){let z={messageId:B,role:"user",inboxMessageId:J.inboxMessageId,createdAt:H,metadata:JSON.parse(JSON.stringify(J.metadata))};j.push(this.createEvent("message_created",$,z)),j.push(this.createEvent("part_created",$,{partId:V0(),messageId:B,partType:"text",payload:{text:J.content},createdAt:H}))}if(!X){let z=Y.findLast((N)=>N.type==="part_created"&&N.data.partType==="subtask_ref"&&N.data.messageId===Q.data.messageId&&N.data.payload!==null&&typeof N.data.payload==="object"&&!Array.isArray(N.data.payload)&&N.data.payload.childSessionId===J.childSessionId),U=z?.data.payload&&typeof z.data.payload==="object"&&!Array.isArray(z.data.payload)?z.data.payload:void 0;j.push(this.createEvent("part_created",$,{partId:V0(),messageId:Q.data.messageId,partType:"subtask_ref",payload:{childSessionId:J.subagentRef.subagentSessionId,agentType:J.subagentRef.subagentType,description:J.subagentRef.subagentDescription??"",status:J.subagentRef.subagentStatus,summary:J.subagentRef.subagentSummary??"",resumedFrom:J.subagentRef.subagentResumedFrom??null,rootAgentId:J.subagentRef.subagentRootId??J.subagentRef.subagentSessionId,resumeDepth:J.subagentRef.subagentResumeDepth??0,verificationVerdict:J.subagentRef.verificationVerdict??null,startedAt:typeof U?.startedAt==="string"?U.startedAt:H,finishedAt:H},createdAt:H}))}return Z={eligible:!0,acknowledged:!1,persisted:j.length>0,messageId:B},j}),Z}async saveTurnStart($,J){await this.ensureSessionCreated($);try{await this.log($).commitValidated((Z)=>{let W=H0(Z);if(W.some((V)=>V.type==="turn_started"&&V.data.turnId===J.turnId))throw new A0;let Y=U$(W).active;if(Y)throw Error(`Session already has an active turn: ${Y.turnId}`);return this.createEvent("turn_started",$,J)})}catch(Z){if(!(Z instanceof A0))throw Z}}async saveTurnCompletion($,J,Z=[]){await this.ensureSessionCreated($);try{await this.log($).commitValidatedBatch((W)=>{let Y=H0(W),V=new Set(Y.flatMap((H)=>H.type==="inbox_acknowledged"?H.data.messageIds:[])),K=[...new Set(Z)].filter((H)=>!V.has(H)),Q=Y.findLast((H)=>(H.type==="turn_completed"||H.type==="turn_aborted")&&H.data.turnId===J.turnId);if(Q){if(Q.type==="turn_aborted"||K.length===0)throw new A0;return[this.createEvent("inbox_acknowledged",$,{messageIds:K,acknowledgedAt:J.completedAt})]}let X=U$(Y).active;if(!X||X.turnId!==J.turnId)throw Error(`Turn is not active: ${J.turnId}`);return[...K.length>0?[this.createEvent("inbox_acknowledged",$,{messageIds:K,acknowledgedAt:J.completedAt})]:[],this.createEvent("turn_completed",$,J)]})}catch(W){if(!(W instanceof A0))throw W}}async saveTurnAbort($,J,Z={}){let W=Z.acknowledgeInputMessageIds??[],Y=J1(W);if(!Y)throw Error("Invalid turn abort acknowledgement input message IDs");let V=Y;await this.ensureSessionCreated($);let K,Q=[];try{await this.log($).commitValidatedBatch((X)=>{let H=H0(X),B=mJ(H),j=H.findLast((v)=>(v.type==="turn_completed"||v.type==="turn_aborted")&&v.data.turnId===J.turnId);if(j){if(j.type==="turn_completed")throw K=void 0,Q=[],new A0;let v=dJ(j.data.recovery),N0=v?V.filter((S)=>v.inputMessageIds.includes(S)):[],L0=N0.filter((S)=>!B.has(S));if(Q=N0,K=g2(H,j,N0),L0.length===0)throw new A0;return[this.createEvent("inbox_acknowledged",$,{messageIds:L0,acknowledgedAt:J.abortedAt})]}let z=U$(H).active;if(!z||z.turnId!==J.turnId)throw Error(`Turn is not active: ${J.turnId}`);let U=R$(H,z.turnId),N=MJ(H,z.turnId),b=W1(H),x=new Set(J.recovery?.inputMessageIds??[]),M=b?b.inputMessageIds.filter((v)=>x.has(v)):[],k=[...new Set([...N,...M])],h={version:2,inputMessageIds:k,hadSuccessfulToolResult:U.hadSuccessfulResult||J.recovery?.hadSuccessfulToolResult===!0,interruptedToolCallCount:U.orphaned.length+(J.recovery?.version===2?J.recovery.interruptedToolCallCount:0),emptyFinalCorrectionSpent:u2(H,z.turnId)||J.recovery?.emptyFinalCorrectionSpent===!0};K={turnId:J.turnId,outcome:"aborted",inputMessageIds:h.inputMessageIds,hadSuccessfulToolResult:h.hadSuccessfulToolResult,...h.interruptedToolCallCount>0?{interruptedToolCallCount:h.interruptedToolCallCount}:{},emptyFinalCorrectionSpent:h.emptyFinalCorrectionSpent};let _=V.filter((v)=>k.includes(v)),u=_.filter((v)=>!B.has(v));Q=_;let q=new Set(B);for(let v of _)q.add(v);let K0=h.inputMessageIds.filter((v)=>!q.has(v)),d=h.hadSuccessfulToolResult||h.interruptedToolCallCount>0;K=K0.length>0||d?{turnId:J.turnId,outcome:"aborted",inputMessageIds:K0,hadSuccessfulToolResult:h.hadSuccessfulToolResult,...h.interruptedToolCallCount>0?{interruptedToolCallCount:h.interruptedToolCallCount}:{},emptyFinalCorrectionSpent:h.emptyFinalCorrectionSpent}:void 0;let{acknowledgedInputMessageIds:B0,...F0}=J;return[this.createEvent("turn_aborted",$,{...F0,..._.length>0?{acknowledgedInputMessageIds:_}:{},recovery:h}),...u.length>0?[this.createEvent("inbox_acknowledged",$,{messageIds:u,acknowledgedAt:J.abortedAt})]:[]]})}catch(X){if(!(X instanceof A0))throw X}return{...K?{recovery:K}:{},acknowledgedInputMessageIds:Q}}async loadInterruptedToolCalls($){let J=await this.loadEvents($);if(!J)return[];let Z=H0(J),W=U$(Z).active;return W?R$(Z,W.turnId).orphaned.map((Y)=>({...Y,input:structuredClone(Y.input)})):[]}async hasRecoverableTurn($){let J=await this.loadEvents($);if(!J)return!1;let Z=H0(J),W=U$(Z).active;if(W){let Y=R$(Z,W.turnId);if(Y.orphaned.length>0||Y.hadSuccessfulResult)return!0;if(RJ(Z,W.turnId))return!0}return W1(Z)!==void 0}async loadBackgroundTaskChildIds($){let J=await this.loadEvents($);if(!J)return new Set;let Z=H0(J).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 V=Y.input;return V.run_in_background===!0&&typeof V.subagent_session_id==="string"?[V.subagent_session_id]:[]});return new Set(Z)}async recoverInterruptedTurn($,J={}){await this.ensureSessionCreated($);let Z;try{await this.log($).commitValidatedBatch((W)=>{let Y=H0(W),V=U$(Y).active,K=R$(Y);if(!V&&K.orphaned.length===0){if(Z=W1(Y),Z)return[];throw new A0}let Q=V?RJ(Y,V.turnId):void 0;if(V&&Q&&K.orphaned.length===0){let _=R$(Y,V.turnId);Z={turnId:V.turnId,outcome:"completed",inputMessageIds:Q.inputMessageIds,hadSuccessfulToolResult:_.hadSuccessfulResult,emptyFinalCorrectionSpent:u2(Y,V.turnId),finalization:Q};let u=new Set(Y.flatMap((d)=>d.type==="inbox_acknowledged"?d.data.messageIds:[])),q=Q.inputMessageIds.filter((d)=>!u.has(d)),K0=new Date().toISOString();return[...q.length>0?[this.createEvent("inbox_acknowledged",$,{messageIds:q,acknowledgedAt:K0})]:[],this.createEvent("turn_completed",$,{turnId:V.turnId,completedAt:K0,turnsCount:Q.turnsCount,toolCallsCount:Q.toolCallsCount,durationMs:Q.durationMs})]}let X=V?R$(Y,V.turnId):void 0,H=X?.orphaned.some((_)=>{let u=J.adoptedToolResults?.get(_.toolCallId);return u?.toolCallId===_.toolCallId&&u.toolName===_.toolName&&u.error===void 0})??!1,B=new Set(V?.inputMessageIds??[]),j=V?W1(Y):void 0,z=j?j.inputMessageIds.filter((_)=>B.has(_)):[],U=z.length>0,N=V?MJ(Y,V.turnId):[],b=X?X.orphaned.filter((_)=>{let u=J.adoptedToolResults?.get(_.toolCallId);return!(u?.toolCallId===_.toolCallId&&u.toolName===_.toolName)}).length:0;Z=V?{turnId:V.turnId,outcome:"aborted",inputMessageIds:[...new Set([...N,...z])],hadSuccessfulToolResult:(X?.hadSuccessfulResult??!1)||H||U&&j?.hadSuccessfulToolResult===!0,...(()=>{let _=b+(U?j?.interruptedToolCallCount??0:0);return _>0?{interruptedToolCallCount:_}:{}})(),emptyFinalCorrectionSpent:u2(Y,V.turnId)||U&&j?.emptyFinalCorrectionSpent===!0}:W1(Y);let x=V?X?.all.length??0:0,M=new Date().toISOString(),k=V?Date.parse(V.startedAt):Number.NaN,h=K.orphaned.flatMap((_)=>{let u=J.adoptedToolResults?.get(_.toolCallId),q=u?.toolCallId===_.toolCallId&&u.toolName===_.toolName?u:void 0,K0=this.createEvent("part_created",$,{partId:_.toolCallId,messageId:q?_.messageId:_.toolCallId,partType:"tool_result",payload:q?{toolCallId:_.toolCallId,toolName:_.toolName,output:q.output,error:q.error??null,...q.metadata===void 0?{}:{metadata:q.metadata}}:{toolCallId:_.toolCallId,toolName:_.toolName,output:null,error:O8,metadata:{processRestartRecovery:!0,sideEffectsUncertain:!0}},createdAt:M});if(!q?.subagentRef)return[K0];let d=q.subagentRef;return[K0,this.createEvent("part_created",$,{partId:V0(),messageId:_.messageId,partType:"subtask_ref",payload:{childSessionId:d.subagentSessionId,agentType:d.subagentType,description:d.subagentDescription??"",status:d.subagentStatus,summary:d.subagentSummary??"",resumedFrom:d.subagentResumedFrom??null,rootAgentId:d.subagentRootId??d.subagentSessionId,resumeDepth:d.subagentResumeDepth??0,verificationVerdict:d.verificationVerdict??null,startedAt:M,finishedAt:M},createdAt:M})]});return V?[...h,this.createEvent("turn_aborted",$,{turnId:V.turnId,cause:"process_restart",abortedAt:M,turnsCount:0,toolCallsCount:x,durationMs:Number.isFinite(k)?Math.max(0,Date.now()-k):0,recovery:Z?{version:2,inputMessageIds:Z.inputMessageIds,hadSuccessfulToolResult:Z.hadSuccessfulToolResult,interruptedToolCallCount:Z.interruptedToolCallCount??0,emptyFinalCorrectionSpent:Z.emptyFinalCorrectionSpent}:void 0})]:h})}catch(W){if(!(W instanceof A0))throw W}return Z}async loadLatestGoalFinalization($){let J=await this.loadEvents($);return J?E8(J):void 0}async saveInteractionRequest($,J){await this.ensureSessionCreated($),await this.log($).commitValidated((Z)=>{if(Z.some((Y)=>Y.type==="interaction_requested"&&Y.data.requestId===J.requestId))throw Error(`Interaction request already exists: ${J.requestId}`);return this.createEvent("interaction_requested",$,J)})}async saveInteractionResponse($,J){await this.ensureSessionCreated($),await this.log($).commitValidated((Z)=>{if(!Z.some((V)=>V.type==="interaction_requested"&&V.data.requestId===J.requestId))throw Error(`Interaction request not found: ${J.requestId}`);if(Z.some((V)=>V.type==="interaction_responded"&&V.data.requestId===J.requestId))throw Error(`Interaction already responded: ${J.requestId}`);return this.createEvent("interaction_responded",$,J)})}async saveInteractionRecovery($,J){await this.ensureSessionCreated($),await this.log($).commitValidated((Z)=>{if(!Z.some((V)=>V.type==="interaction_responded"&&V.data.requestId===J.requestId))throw Error(`Interaction response not found: ${J.requestId}`);if(Z.some((V)=>V.type==="interaction_recovered"&&V.data.requestId===J.requestId))throw Error(`Interaction already recovered: ${J.requestId}`);return this.createEvent("interaction_recovered",$,J)})}async saveReviewStart($,J){await this.ensureSessionCreated($),await this.log($).commitValidated((Z)=>{if(Z.some((V)=>V.type==="review_started"&&V.data.reviewId===J.reviewId))throw Error(`Review already exists: ${J.reviewId}`);if(Z.some((V)=>V.type==="review_started"&&!Z.some((K)=>K.type==="review_completed"&&K.data.reviewId===V.data.reviewId)))throw Error("Session already has an active review");return this.createEvent("review_started",$,J)})}async saveReviewCompletion($,J){await this.ensureSessionCreated($),await this.log($).commitValidated((Z)=>{if(!Z.some((V)=>V.type==="review_started"&&V.data.reviewId===J.reviewId))throw Error(`Review not found: ${J.reviewId}`);if(Z.some((V)=>V.type==="review_completed"&&V.data.reviewId===J.reviewId))throw Error(`Review already completed: ${J.reviewId}`);return this.createEvent("review_completed",$,J)})}async saveToolUse($,J,Z,W=null,Y,V){try{if(V!==void 0&&(V.length===0||V.length>512))throw Error("Provider tool call identity must contain 1-512 characters");await this.ensureSessionCreated($,Y);let K=new Date().toISOString(),Q=W??V0(),X=[];if(!W){let j={messageId:Q,role:"assistant",parentMessageId:void 0,createdAt:K};X.push(this.createEvent("message_created",$,j))}let H=V??V0(),B={partId:H,messageId:Q,partType:"tool_call",payload:{toolCallId:H,toolName:J,input:Z},createdAt:K};if(X.push(this.createEvent("part_created",$,B)),J==="Task"&&Z&&typeof Z==="object"){let j=Z,z=typeof j.subagent_session_id==="string"?j.subagent_session_id:void 0,U=typeof j.subagent_type==="string"?j.subagent_type:void 0;if(z&&U){let N={partId:V0(),messageId:Q,partType:"subtask_ref",payload:{childSessionId:z,agentType:U,status:"running",summary:typeof j.description==="string"?j.description:"",startedAt:K},createdAt:K};X.push(this.createEvent("part_created",$,N))}}return await this.log($).commitBatch(X),H}catch(K){throw console.error(`[PersistentStore] 保存工具调用失败 (session: ${$}):`,K),K}}async saveToolResult($,J,Z,W,Y=null,V,K,Q,X){try{await this.ensureSessionCreated($,K);let H=new Date().toISOString(),B=Y??V0();return await this.log($).commitValidatedBatch((j)=>{let z=Q?.subagentStatus==="running"?H0(j).findLast((k)=>k.type==="part_created"&&k.data.partType==="subtask_ref"&&k.data.payload!==null&&typeof k.data.payload==="object"&&!Array.isArray(k.data.payload)&&k.data.payload.childSessionId===Q.subagentSessionId&&(k.data.payload.status==="completed"||k.data.payload.status==="failed"||k.data.payload.status==="cancelled")):void 0,U=z?.data.payload,N=X&&typeof X==="object"&&!Array.isArray(X)?X:{},b=U?{...N,subagentSessionId:U.childSessionId,subagentType:U.agentType,description:U.description,subagentStatus:U.status,subagentSummary:U.summary,subagentResumedFrom:U.resumedFrom,subagentRootId:U.rootAgentId,subagentResumeDepth:U.resumeDepth,verificationVerdict:U.verificationVerdict}:X,x=[];if(!Y){let k={messageId:B,role:"assistant",parentMessageId:void 0,createdAt:H};x.push(this.createEvent("message_created",$,k))}let M={partId:J,messageId:B,partType:"tool_result",payload:{toolCallId:J,toolName:Z,output:W,error:V??null,...b===void 0?{}:{metadata:b}},createdAt:H};if(x.push(this.createEvent("part_created",$,M)),Q&&!z){let k=Q.subagentStatus==="running"?null:H,h={partId:V0(),messageId:B,partType:"subtask_ref",payload:{childSessionId:Q.subagentSessionId,agentType:Q.subagentType,description:Q.subagentDescription??"",status:Q.subagentStatus,summary:Q.subagentSummary??"",resumedFrom:Q.subagentResumedFrom??null,rootAgentId:Q.subagentRootId??Q.subagentSessionId,resumeDepth:Q.subagentResumeDepth??0,verificationVerdict:Q.verificationVerdict??null,startedAt:H,finishedAt:k},createdAt:H};x.push(this.createEvent("part_created",$,h))}return x}),J}catch(H){throw console.error(`[PersistentStore] 保存工具结果失败 (session: ${$}):`,H),H}}async saveCompaction($,J,Z,W=null){try{await this.ensureSessionCreated($);let Y=new Date().toISOString(),V=V0(),K={messageId:V,role:"system",parentMessageId:W??void 0,createdAt:Y},Q=this.buildCompactionMetadata(Z),X={partId:V0(),messageId:V,partType:"summary",payload:{text:J,metadata:Q,...Z.replacementMessages?{replacementMessages:uJ(Z.replacementMessages)}:{}},createdAt:Y},H=[this.createEvent("message_created",$,K),this.createEvent("part_created",$,X)];return await this.log($).commitBatch(H),V}catch(Y){throw console.error(`[PersistentStore] 保存压缩失败 (session: ${$}):`,Y),Y}}async recordTokenBudgetHandoff($,J){await this.ensureSessionCreated($);let Z=k1([]),W=await this.log($).commitValidatedBatch((V)=>{if(Z=k1(H0(V)),Z.kind!=="none")return[];let K=new Date().toISOString();return[this.createEvent("token_budget_handoff_recorded",$,{...J,messageId:`${gJ}${V0()}`,createdAt:K})]});if(Z.kind==="valid")return{outcome:"existing",event:Z.event};if(Z.kind==="suppressed")return{outcome:"suppressed",recordId:Z.recordId};if(W.length!==1)throw Error("Token budget handoff commit produced an impossible result");let Y=k1(W);if(Y.kind!=="valid")throw Error("Token budget handoff commit produced an invalid event");return{outcome:"created",event:Y.event}}async initSession($,J){await this.ensureSessionCreated($,J)}async loadEvents($){try{let J=P0(this.projectPath,$),W=await new v0(J).readAll();return W.length>0?H0(W):null}catch{return null}}async loadSession($){try{let J=P0(this.projectPath,$),Z=new v0(J),W=H0(await Z.readAll());if(W.length===0)return null;let Y=W.find((V)=>V.type==="session_created");return{sessionId:$,userId:void 0,preferences:{},configuration:{},startTime:new Date(Y?.timestamp??W[0].timestamp).getTime()}}catch{return null}}async loadConversation($){try{let J=P0(this.projectPath,$),Z=new v0(J),W=H0(await Z.readAll());if(W.length===0)return null;let Y=new Map;for(let X of W){if(X.type==="message_created")Y.set(X.data.messageId,{id:X.data.messageId,role:X.data.role,content:"",timestamp:new Date(X.timestamp).getTime()});if(X.type==="part_created"&&X.data.partType==="text"){let H=Y.get(X.data.messageId);if(H){let B=X.data.payload;H.content=B.text??""}}if(X.type==="part_created"&&X.data.partType==="image"){let H=Y.get(X.data.messageId);if(H)H.content=H.content?`${H.content}
|
|
86
|
-
[Image]`:"[Image]"}}let V=Array.from(Y.values()),K=W[W.length-1],Q=new Date(K.timestamp).getTime();return{messages:V,topics:[],lastActivity:Q}}catch{return null}}async listSessions(){try{let $=b$(this.projectPath);return(await I0.readdir($)).filter((Z)=>Z.endsWith(".jsonl")).map((Z)=>Z.replace(".jsonl","")).sort()}catch{return[]}}async getSessionSummary($){try{let J=P0(this.projectPath,$),Z=new v0(J);if(!(await Z.getStats()).exists)return null;let Y=await Z.readAll();if(Y.length===0)return null;let V=H0(Y),K=Y[Y.length-1],Q=V.filter((X)=>X.type==="message_created"&&["user","assistant"].includes(X.data.role)).length;return{sessionId:$,lastActivity:new Date(K.timestamp).getTime(),messageCount:Q,topics:[]}}catch{return null}}async deleteSession($){this.initializedSessions.delete($);try{let J=P0(this.projectPath,$);await new v0(J).delete(),await I0.unlink(R1(this.projectPath,$)).catch((W)=>{if(W.code!=="ENOENT")throw W}),await vJ(this.projectPath,$,xJ());try{let{getProjectionDb:W,removeSessionFromProjection:Y}=await import("./chunk-
|
|
86
|
+
[Image]`:"[Image]"}}let V=Array.from(Y.values()),K=W[W.length-1],Q=new Date(K.timestamp).getTime();return{messages:V,topics:[],lastActivity:Q}}catch{return null}}async listSessions(){try{let $=b$(this.projectPath);return(await I0.readdir($)).filter((Z)=>Z.endsWith(".jsonl")).map((Z)=>Z.replace(".jsonl","")).sort()}catch{return[]}}async getSessionSummary($){try{let J=P0(this.projectPath,$),Z=new v0(J);if(!(await Z.getStats()).exists)return null;let Y=await Z.readAll();if(Y.length===0)return null;let V=H0(Y),K=Y[Y.length-1],Q=V.filter((X)=>X.type==="message_created"&&["user","assistant"].includes(X.data.role)).length;return{sessionId:$,lastActivity:new Date(K.timestamp).getTime(),messageCount:Q,topics:[]}}catch{return null}}async deleteSession($){this.initializedSessions.delete($);try{let J=P0(this.projectPath,$);await new v0(J).delete(),await I0.unlink(R1(this.projectPath,$)).catch((W)=>{if(W.code!=="ENOENT")throw W}),await vJ(this.projectPath,$,xJ());try{let{getProjectionDb:W,removeSessionFromProjection:Y}=await import("./chunk-fqnqeca5.js"),V=await W();if(V)Y(V,$,this.projectPath)}catch{}}catch(J){console.warn(`[PersistentStore] 删除会话失败 (session: ${$}):`,J)}finally{this.initializedSessions.delete($)}}async cleanupOldSessions(){try{let $=await this.listSessions();if($.length<=this.maxSessions)return;let W=(await Promise.all($.map((Y)=>this.getSessionSummary(Y)))).filter((Y)=>Y!==null).sort((Y,V)=>V.lastActivity-Y.lastActivity).slice(this.maxSessions).map((Y)=>Y.sessionId);await Promise.all(W.map((Y)=>this.deleteSession(Y))),console.log(`[PersistentStore] 已清理 ${W.length} 个旧会话`)}catch($){console.error("[PersistentStore] 清理旧会话失败:",$)}}async getStorageStats(){try{let $=await this.listSessions(),J=0;for(let Z of $){let W=P0(this.projectPath,Z),V=await new v0(W).getStats();J+=V.size}return{totalSessions:$.length,totalSize:J,projectPath:this.projectPath}}catch{return{totalSessions:0,totalSize:0,projectPath:this.projectPath}}}async checkStorageHealth(){try{let $=b$(this.projectPath);await I0.mkdir($,{recursive:!0,mode:493});let J=pJ.join($,".health-check");return await I0.writeFile(J,"test","utf-8"),await I0.unlink(J),{isAvailable:!0,canWrite:!0}}catch($){return{isAvailable:!1,canWrite:!1,error:$ instanceof Error?$.message:String($)}}}static async listAllProjects(){return kJ()}}function S8($){return/^data:([^;,]+)[;,]/.exec($)?.[1]??null}var lJ=131072,p2=new nJ;function d2($,J){return`${M8.resolve($)}\x00${J}`}function l2($,J){let Z=JSON.stringify($);if(Z===void 0)throw Error(`${J} is not JSON serializable`);if(Buffer.byteLength(Z,"utf8")>lJ)throw Error(`${J} exceeds ${lJ} bytes`);return JSON.parse(Z)}function iJ($){if($.type==="askUserQuestion")return"question";if($.type==="mcpElicitation")return"elicitation";if($.type==="permission"||$.type==="mcpSampling")return"permission";return}function R8($,J){return JSON.stringify($)===JSON.stringify(J)}function h8($,J){if($.request.interactionType!=="elicitation")return l2(J,"Interaction response");return l2({approved:J.approved,...J.reason?{reason:J.reason}:{},...J.elicitation?{elicitation:{action:J.elicitation.action}}:{},...J.openExternalUrl?{openExternalUrl:!0}:{}},"Interaction response")}function rJ($){let J=$.request.details;if(!J||typeof J!=="object"||Array.isArray(J))throw Error(`Invalid durable interaction details: ${$.request.requestId}`);return J}function x8($){let J=$.response?.response;if(!J||typeof J!=="object"||Array.isArray(J))throw Error(`Invalid durable interaction response: ${$.request.requestId}`);return J}function k8($){if(!$.answers||Object.keys($.answers).length===0)return"No structured answers were provided.";return Object.entries($.answers).map(([J,Z])=>{let W=Array.isArray(Z)?Z.join(", "):Z;return`${J}: ${W}`}).join(`
|
|
87
87
|
`)}function C8($,J){let{request:Z}=$;if(Z.interactionType==="question"){let K=k8(J);return{toolOutput:`User answers:
|
|
88
88
|
${K}`,inbox:`The process restarted while waiting for a structured answer. The recovered user response is:
|
|
89
89
|
${K}
|
|
@@ -168,4 +168,4 @@ ${y}`}if(typeof C==="object"&&C!==null)C=JSON.stringify(C,null,2);if(typeof C===
|
|
|
168
168
|
${tJ(V$)}
|
|
169
169
|
</system-reminder>`,metadata:K1};q.appendControl("user",w);let D=await l0($,Z,w.content,X,K1);if(D)X=D}}if(W?.signal?.aborted)return B(K,Q.length,W.signal);if(K>=L0&&(N0||B0)){if(l.info(`Warning: 达到轮次上限 ${L0} 轮`),W?.onTurnLimitReached){let w=await W.onTurnLimitReached({turnsCount:K});if(w?.continue){q.writeback();let D="failed",P,A,c,E,f,p,C,O0,Y0,I,y,a,n,U0;yield{kind:"compaction",phase:"start",reason:"turn_limit"};try{let O=$.chatService.getConfig(),f0=N(),G0=F$&&r$(G$)?f0.filter((U2)=>U2.name!=="Task"):f0,Q0=p0?G0.filter((U2)=>U2.name===p0):G0,R=T2(q.systemMessages,Q0,O.model),T0=L$.project({history:q.getHistory(),contextRevision:q.contextRevision,modelName:O.model,requestProfile:R});c=T0.source,E=T0.estimatedPendingTokens;let g=await S$.compact(Z.messages,{trigger:"auto",modelName:O.model,modelProvider:O.provider,maxContextTokens:O.maxContextTokens??0,apiKey:O.apiKey,baseURL:O.baseUrl,actualPreTokens:T0.contextTokens,signal:W?.signal,activeTask:S0,workspaceRoot:Z.workspaceRoot||X0(),sessionId:Z.sessionId});if(g.usage)yield{kind:"token_usage",usage:c1(g.usage,O.maxContextTokens??0)};let m4={role:"user",content:`This session is being continued from a previous conversation. The conversation is summarized above.
|
|
170
170
|
|
|
171
|
-
Please continue the conversation from where we left it off without asking the user any further questions. Continue with the last task that you were asked to work on.`},_6=[...g.compactedMessages,m4];P=g.success?"llm":"fallback",A=g.preTokens,f=g.postTokens,p=g.sampleAttempts,C=g.inputReductions,O0=g.messagesOmitted,Y0=g.filesOmitted,I=g.imagesOmitted,y=g.fallbackTargetTokens,a=g.fallbackMessagesOmitted,n=g.fallbackMessagesTruncated,U0=g.failureReason,await a$($,Z,g.summary,{trigger:"auto",reason:"turn_limit",strategy:P,preTokens:g.preTokens,preTokenSource:T0.source,...T0.estimatedPendingTokens!==void 0?{estimatedPendingTokens:T0.estimatedPendingTokens}:{},postTokens:g.postTokens,sampleAttempts:g.sampleAttempts,inputReductions:g.inputReductions,messagesOmitted:g.messagesOmitted,filesOmitted:g.filesOmitted,imagesOmitted:g.imagesOmitted,fallbackTargetTokens:g.fallbackTargetTokens,fallbackMessagesOmitted:g.fallbackMessagesOmitted,fallbackMessagesTruncated:g.fallbackMessagesTruncated,failureReason:g.failureReason,filesIncluded:g.filesIncluded,replacementMessages:_6},{required:$.executionEngine!==void 0}),Z.messages=_6,q.replaceHistory(Z.messages),L$.reset(),D=g.success?"completed":"fallback"}catch(O){throw l.error("[Loop] 轮次上限压缩失败,停止继续执行:",O),O}finally{yield{kind:"compaction",phase:"end",reason:"turn_limit",outcome:D,strategy:P,preTokens:A,preTokenSource:c,estimatedPendingTokens:E,postTokens:f,sampleAttempts:p,inputReductions:C,messagesOmitted:O0,filesOmitted:Y0,imagesOmitted:I,fallbackTargetTokens:y,fallbackMessagesOmitted:a,fallbackMessagesTruncated:n,failureReason:U0}}K=0;continue}return{success:!0,finalMessage:w?.reason||"已达到对话轮次上限,用户选择停止",metadata:{turnsCount:K,toolCallsCount:Q.length,duration:Date.now()-V,tokensUsed:S}}}return{success:!1,error:{type:"max_turns_exceeded",message:B0?`子代理已达到轮次上限 (${L0} 轮)。`:`已达到轮次上限 (${L0} 轮)。`},metadata:{turnsCount:K,toolCallsCount:Q.length,duration:Date.now()-V,tokensUsed:S}}}}}catch(L){if(L instanceof _$)try{let F=Z.sessionId?await o$.loadSessionModelContext(Z.sessionId,Z.workspaceRoot):u;q.restoreDurableHistory(F)}catch(F){l.error("[Loop] Failed to reload durable context after message commit failure:",F),q.restoreDurableHistory(u)}throw L}finally{if(W?.transientInput==="goal_continuation")q.removeMessages((L)=>{let F=L.metadata;return F!==null&&typeof F==="object"&&!Array.isArray(F)&&F.transientGoalContinuation===!0});q.writeback()}}catch(j){if(i0(j))return B(K,Q.length,W?.signal);if(j instanceof _$)return{success:!1,error:{type:"message_persistence_failed",message:j.message},metadata:{turnsCount:K,toolCallsCount:Q.length,duration:Date.now()-V}};let z=fZ(j);return l.error(`API 调用失败: ${z}`),{success:!1,error:{type:"api_error",message:z,details:j},metadata:{turnsCount:K,toolCallsCount:Q.length,duration:Date.now()-V}}}finally{if(H)Z.messages.push({role:"system",content:f2}),await o6($,Z,X)}}export{y2 as
|
|
171
|
+
Please continue the conversation from where we left it off without asking the user any further questions. Continue with the last task that you were asked to work on.`},_6=[...g.compactedMessages,m4];P=g.success?"llm":"fallback",A=g.preTokens,f=g.postTokens,p=g.sampleAttempts,C=g.inputReductions,O0=g.messagesOmitted,Y0=g.filesOmitted,I=g.imagesOmitted,y=g.fallbackTargetTokens,a=g.fallbackMessagesOmitted,n=g.fallbackMessagesTruncated,U0=g.failureReason,await a$($,Z,g.summary,{trigger:"auto",reason:"turn_limit",strategy:P,preTokens:g.preTokens,preTokenSource:T0.source,...T0.estimatedPendingTokens!==void 0?{estimatedPendingTokens:T0.estimatedPendingTokens}:{},postTokens:g.postTokens,sampleAttempts:g.sampleAttempts,inputReductions:g.inputReductions,messagesOmitted:g.messagesOmitted,filesOmitted:g.filesOmitted,imagesOmitted:g.imagesOmitted,fallbackTargetTokens:g.fallbackTargetTokens,fallbackMessagesOmitted:g.fallbackMessagesOmitted,fallbackMessagesTruncated:g.fallbackMessagesTruncated,failureReason:g.failureReason,filesIncluded:g.filesIncluded,replacementMessages:_6},{required:$.executionEngine!==void 0}),Z.messages=_6,q.replaceHistory(Z.messages),L$.reset(),D=g.success?"completed":"fallback"}catch(O){throw l.error("[Loop] 轮次上限压缩失败,停止继续执行:",O),O}finally{yield{kind:"compaction",phase:"end",reason:"turn_limit",outcome:D,strategy:P,preTokens:A,preTokenSource:c,estimatedPendingTokens:E,postTokens:f,sampleAttempts:p,inputReductions:C,messagesOmitted:O0,filesOmitted:Y0,imagesOmitted:I,fallbackTargetTokens:y,fallbackMessagesOmitted:a,fallbackMessagesTruncated:n,failureReason:U0}}K=0;continue}return{success:!0,finalMessage:w?.reason||"已达到对话轮次上限,用户选择停止",metadata:{turnsCount:K,toolCallsCount:Q.length,duration:Date.now()-V,tokensUsed:S}}}return{success:!1,error:{type:"max_turns_exceeded",message:B0?`子代理已达到轮次上限 (${L0} 轮)。`:`已达到轮次上限 (${L0} 轮)。`},metadata:{turnsCount:K,toolCallsCount:Q.length,duration:Date.now()-V,tokensUsed:S}}}}}catch(L){if(L instanceof _$)try{let F=Z.sessionId?await o$.loadSessionModelContext(Z.sessionId,Z.workspaceRoot):u;q.restoreDurableHistory(F)}catch(F){l.error("[Loop] Failed to reload durable context after message commit failure:",F),q.restoreDurableHistory(u)}throw L}finally{if(W?.transientInput==="goal_continuation")q.removeMessages((L)=>{let F=L.metadata;return F!==null&&typeof F==="object"&&!Array.isArray(F)&&F.transientGoalContinuation===!0});q.writeback()}}catch(j){if(i0(j))return B(K,Q.length,W?.signal);if(j instanceof _$)return{success:!1,error:{type:"message_persistence_failed",message:j.message},metadata:{turnsCount:K,toolCallsCount:Q.length,duration:Date.now()-V}};let z=fZ(j);return l.error(`API 调用失败: ${z}`),{success:!1,error:{type:"api_error",message:z,details:j},metadata:{turnsCount:K,toolCallsCount:Q.length,duration:Date.now()-V}}}finally{if(H)Z.messages.push({role:"system",content:f2}),await o6($,Z,X)}}export{y2 as hb,l$ as ib,uZ as jb,D2 as kb,i$ as lb,h6 as mb,$5 as nb,y$ as ob,cZ as pb,U$ as qb,O2 as rb,i6 as sb,Z3 as tb,n$ as ub,w0 as vb,_0 as wb,q2 as xb,G2 as yb,I6 as zb,L2 as Ab,D4 as Bb,w4 as Cb,G4 as Db,A$ as Eb,A1 as Fb,N5 as Gb,l0 as Hb,C0 as Ib,A2 as Jb,_1 as Kb,a$ as Lb,i as Mb,S$ as Nb,x1 as Ob,z0 as Pb,W9 as Qb,O4 as Rb,m1 as Sb,A4 as Tb,y4 as Ub,N4 as Vb,FZ as Wb,W6 as Xb,k4 as Yb,xZ as Zb};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Ab as c,Eb as d,Fb as e,Gb as f,Hb as g,Ib as h,Jb as i,Kb as j,Lb as k,Sb as l,Tb as m,Ub as n,Vb as o,Xb as p,Yb as q,Zb as r,xb as a,yb as b}from"./chunk-wf19bys8.js";import"./chunk-cnhw5mqv.js";import"./chunk-ca9cbkf2.js";import"./chunk-53h87fmt.js";import"./chunk-qdv0n8yt.js";import"./chunk-pshyn3yy.js";import"./chunk-q2exry0f.js";import"./chunk-hv6hrsnk.js";import"./chunk-cqqmkwvn.js";import"./chunk-9g64g1np.js";import"./chunk-e7h4wb45.js";import"./chunk-eyb9psbc.js";import"./chunk-4w4wjm49.js";import"./chunk-6k5k40p8.js";import"./chunk-p3m1jyg5.js";import"./chunk-ecd727xh.js";import"./chunk-x05zyqzf.js";import"./chunk-dvv28pkc.js";import"./chunk-dgf2xzzd.js";import"./chunk-z52s82k7.js";import"./chunk-brebh2tm.js";import"./chunk-sr10jsjs.js";import"./chunk-rkdxqx8m.js";import"./chunk-tf7ezqew.js";export{g as saveUserMessage,i as saveToolUse,j as saveToolResult,k as saveCompaction,h as saveAssistantMessage,d as isRootSystemPrompt,m as handleTaskListUpdate,n as handleSkillActivation,o as extractModelSwitch,r as executeLoopGenerator,f as drainLoop,c as checkStopHook,a as checkOutputRecovery,b as checkIncompleteIntent,q as checkAndCompactInLoop,p as applyToolDomainEffects,l as StreamingToolExecutor,e as ConversationState};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{pf as a}from"./chunk-q2exry0f.js";import"./chunk-x05zyqzf.js";import"./chunk-dvv28pkc.js";import"./chunk-dgf2xzzd.js";import"./chunk-z52s82k7.js";import"./chunk-rkdxqx8m.js";import"./chunk-tf7ezqew.js";export{a as createChatServiceAsync};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
var I=600000,r=30000,t=3600000,o=12,O=15000,P=60000;function R(_){return _===0||typeof _==="number"&&Number.isSafeInteger(_)&&_>=30000&&_<=3600000}var C=1e4,M=1000,p=300000;function E(_){return _===0||typeof _==="number"&&Number.isSafeInteger(_)&&_>=1000&&_<=300000}var T=1,s=16,n=Number.MAX_SAFE_INTEGER,D=180000,m=1000,x=600000,S=134217728,U=65536,V=134217728;function A(_){return typeof _==="number"&&Number.isSafeInteger(_)&&_>=1&&_<=16}function w(_){return typeof _==="number"&&Number.isSafeInteger(_)&&_>=1&&_<=n}function z(_){return _===0||typeof _==="number"&&Number.isSafeInteger(_)&&_>=1000&&_<=600000}function F(_){return typeof _==="number"&&Number.isSafeInteger(_)&&_>=65536&&_<=134217728}
|
|
2
|
-
export{I as
|
|
2
|
+
export{I as Th,r as Uh,t as Vh,o as Wh,O as Xh,P as Yh,R as Zh,C as _h,M as $h,p as ai,E as bi,T as ci,s as di,n as ei,D as fi,m as gi,x as hi,S as ii,U as ji,V as ki,A as li,w as mi,z as ni,F as oi};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{Xi as $,Yi as F}from"./chunk-rkdxqx8m.js";import{promises as J}from"node:fs";import Q from"node:path";import{Mutex as U}from"async-mutex";import w from"write-file-atomic";var X=1;function D(k){if(!k||typeof k!=="object"||Array.isArray(k))return!1;let q=k;return typeof q.path==="string"&&Q.isAbsolute(q.path)&&typeof q.boundAt==="string"}async function Z(k){if(!Q.isAbsolute(k))throw Error("Project path must be absolute");let q=await J.realpath(k);if(!(await J.stat(q)).isDirectory())throw Error("Project path must be a directory");return q}class K{filePath;mutex=new U;constructor(k=Q.join(F(),"bound-projects.json")){this.filePath=k}async list(k){let q=await this.read(),z=await Z(k),H=new Map;for(let C of q.projects)H.set(C.path,C);if(!H.has(z))H.set(z,{path:z,boundAt:new Date(0).toISOString()});return(await Promise.all([...H.values()].map(async(C)=>{let L=!1;try{L=(await J.stat(C.path)).isDirectory()}catch{}return{path:C.path,name:Q.basename(C.path)||C.path,...L?{gitBranch:$(C.path)}:{},available:L,isCurrent:C.path===z,boundAt:C.boundAt}}))).sort((C,L)=>{if(C.isCurrent!==L.isCurrent)return C.isCurrent?-1:1;return C.name.localeCompare(L.name)})}async bind(k,q){return this.mutex.runExclusive(async()=>{let z=await Z(k),H=await this.read(),W=H.projects.find((M)=>M.path===z),C=W??{path:z,boundAt:new Date().toISOString()};if(!W)H.projects.push(C),await this.write(H);let L=await Z(q),A=$(z);return{path:z,name:Q.basename(z)||z,...A?{gitBranch:A}:{},available:!0,isCurrent:z===L,boundAt:C.boundAt}})}async unbind(k){return this.mutex.runExclusive(async()=>{if(!Q.isAbsolute(k))throw Error("Project path must be absolute");let q=await J.realpath(k).catch(()=>Q.resolve(k)),z=await this.read(),H=z.projects.filter((W)=>W.path!==q);if(H.length===z.projects.length)return!1;return z.projects=H,await this.write(z),!0})}async read(){try{let k=await J.readFile(this.filePath,"utf8"),q=JSON.parse(k);if(q.version!==X||!Array.isArray(q.projects))return{version:X,projects:[]};return{version:X,projects:q.projects.filter(D)}}catch(k){if(k.code==="ENOENT"||k instanceof SyntaxError)return{version:X,projects:[]};throw k}}async write(k){let q=Q.dirname(this.filePath);await J.mkdir(q,{recursive:!0,mode:448}),await J.chmod(q,448),await w(this.filePath,`${JSON.stringify(k,null,2)}
|
|
2
2
|
`,{mode:384}),await J.chmod(this.filePath,384)}}var _=new K;
|
|
3
3
|
export{_ as g};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
2
|
-
export{P as
|
|
1
|
+
import{_i as K}from"./chunk-tf7ezqew.js";import{spawn as Y}from"node:child_process";import{constants as j}from"node:fs";import{access as x,readFile as B}from"node:fs/promises";import{createRequire as L}from"node:module";import C from"node:path";var P="blade browser install";var D=["PATH","Path","PATHEXT","HOME","USERPROFILE","LOCALAPPDATA","PROGRAMDATA","TMPDIR","TMP","TEMP","LANG","LC_ALL","LC_CTYPE","TZ","SystemRoot","SYSTEMROOT","WINDIR","COMSPEC","XDG_RUNTIME_DIR","CHROME_DEVEL_SANDBOX"],A=[...D,"PLAYWRIGHT_BROWSERS_PATH","PLAYWRIGHT_DOWNLOAD_CONNECTION_TIMEOUT","PLAYWRIGHT_DOWNLOAD_HOST","PLAYWRIGHT_CHROMIUM_DOWNLOAD_HOST","HTTP_PROXY","HTTPS_PROXY","NO_PROXY","http_proxy","https_proxy","no_proxy","NODE_EXTRA_CA_CERTS","SSL_CERT_FILE","SSL_CERT_DIR"],J=32768,M=4096;function U(f,F){let $={};for(let Z of F){let q=f[Z];if(q!==void 0&&q.length<=J)$[Z]=q}return $}function V(f=process.env){return U(f,D)}function S(f=process.env){return U(f,A)}function W(){return L(import.meta.url).resolve("playwright/package.json")}function y(f=W){return C.join(C.dirname(f()),"cli.js")}async function T(){return await import("playwright")}async function m(f){let F=JSON.parse(await B(f,"utf8"));if(typeof F.version!=="string"||F.version.length===0)throw Error("Playwright package version is invalid");return F.version}function I(f){return(f instanceof Error?f.message:String(f)).replace(/[\r\n]+/g," ").slice(0,M)}async function R(f={}){let $=(f.resolvePackageJson??W)(),Z=await m($),q=await(f.loadPlaywright??T)(),G=q.chromium.executablePath(),H=f.access??x,z;try{await H(G,j.X_OK),z=await q.chromium.launch({executablePath:G,headless:!0,chromiumSandbox:!0,env:V(f.environment)});let Q=z.version();return await z.close(),z=void 0,{playwrightVersion:Z,executablePath:G,installed:!0,browserVersion:Q}}catch(Q){return{playwrightVersion:Z,executablePath:G,installed:!1,error:I(Q)}}finally{await z?.close().catch(()=>{return})}}async function N(f={}){let F=f.resolvePackageJson??W,$=y(F),Z=f.spawn??((q,G,H)=>Y(q,[...G],H));await new Promise((q,G)=>{let H=Z(f.execPath??process.execPath,[$,"install","chromium"],{env:S(f.environment),shell:!1,stdio:"inherit"}),z=!1;H.once("error",(Q)=>{if(z)return;z=!0,G(Q)}),H.once("close",(Q,X)=>{if(z)return;if(z=!0,Q===0){q();return}G(Error(X?`Playwright browser installer stopped by ${X}`:`Playwright browser installer exited with code ${Q??1}`))})})}
|
|
2
|
+
export{P as ya,V as za,R as Aa,N as Ba};
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import{a as T,b as W,c as X,d as Y}from"./chunk-thqwrw4a.js";import"./chunk-3pwq56je.js";import"./chunk-xv3a1se1.js";import"./chunk-jxy1p5at.js";import"./chunk-be5x9ed5.js";import"./chunk-g491cknj.js";import"./chunk-0gcq7bn0.js";import"./chunk-ypbnczjp.js";import"./chunk-n1ghwh6q.js";import"./chunk-23v8c9b8.js";import"./chunk-wf19bys8.js";import"./chunk-cnhw5mqv.js";import"./chunk-ca9cbkf2.js";import"./chunk-53h87fmt.js";import"./chunk-qdv0n8yt.js";import{ye as R}from"./chunk-t5b18tf6.js";import"./chunk-ng96f4xd.js";import{Ue as Q}from"./chunk-q7hqzp81.js";import"./chunk-v508x7cg.js";import"./chunk-pshyn3yy.js";import"./chunk-q2exry0f.js";import"./chunk-tj2efrs1.js";import"./chunk-hv6hrsnk.js";import"./chunk-97xt0nq6.js";import"./chunk-3mf8b8p8.js";import"./chunk-cqqmkwvn.js";import"./chunk-9g64g1np.js";import"./chunk-935v0gpc.js";import"./chunk-e7h4wb45.js";import"./chunk-eyb9psbc.js";import"./chunk-772ehgbx.js";import"./chunk-4w4wjm49.js";import"./chunk-6k5k40p8.js";import"./chunk-p3m1jyg5.js";import"./chunk-ecd727xh.js";import"./chunk-x05zyqzf.js";import"./chunk-dvv28pkc.js";import"./chunk-dgf2xzzd.js";import"./chunk-z52s82k7.js";import{Gi as M}from"./chunk-brebh2tm.js";import"./chunk-vbwvsgs1.js";import"./chunk-sr10jsjs.js";import"./chunk-rkdxqx8m.js";import"./chunk-tf7ezqew.js";import m from"chalk";import K from"open";var A=`
|
|
2
|
+
____ _ _
|
|
3
|
+
| __ )| | __ _ __| | ___
|
|
4
|
+
| _ \\| |/ _\` |/ _\` |/ _ \\
|
|
5
|
+
| |_) | | (_| | (_| | __/
|
|
6
|
+
|____/|_|\\__,_|\\__,_|\\___|
|
|
7
|
+
`,C={command:"web",describe:"Start Blade server and open web interface",builder:T,handler:async(Z)=>{let H=W(Z);if(await Q(),!process.env.BLADE_SERVER_PASSWORD)console.log(m.yellow("[WARN] BLADE_SERVER_PASSWORD is not set; server is unsecured.")),console.log(m.gray(` Set this environment variable to enable Basic Auth.
|
|
8
|
+
`));let F=await Y.listenAsync(H);if(console.log(m.cyan(A)),console.log(m.gray(` v${M()}
|
|
9
|
+
`)),H.hostname==="0.0.0.0"){let q=`http://localhost:${F.port}`;console.log(m.blue.bold(" Local access: "),m.white(q));let x=X();for(let z of x)console.log(m.blue.bold(" Network access: "),m.white(`http://${z}:${F.port}`));K(q).catch(()=>{})}else{let q=F.url.toString();console.log(m.blue.bold(" Web interface: "),m.white(q)),K(q).catch(()=>{})}console.log(""),console.log(m.gray(` Press Ctrl+C to stop the server.
|
|
10
|
+
`));let J,$=new Promise((q)=>{J=q}),b=R(async()=>{await F.stop(),J()});try{await $}finally{b(),await F.stop()}}};export{C as webCommand};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Fi as a,Gi as b,Hi as c,Ii as d,Ji as e,Ki as f}from"./chunk-brebh2tm.js";import"./chunk-tf7ezqew.js";export{b as getVersion,c as getPackageName,a as getPackageInfo,e as getFormattedVersion,d as getDescription,f as getCopyright};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
var t=["auto","low","medium","high"],s=new Set(["openai-completions","openai-responses","openai-codex-responses","azure-openai-responses"]);function n(e){return/(?:^|[/.:_-])gpt-5(?:$|[/.:_-])/i.test(e.id)}function f(e){return typeof e==="string"&&t.includes(e)}function p(e){if(e.api==="openai-codex-responses"||s.has(e.api)&&n(e))return["low","medium","high"];return[]}function u(e,r){let i=p(e);if(r!=="auto"&&!i.includes(r))throw Error(`Response verbosity ${r} is not supported by ${e.name}`);if(r==="auto")return{selection:r,effective:"provider-default",supported:i};return{selection:r,effective:r,supported:i,providerValue:r}}var a=["auto","standard","fast","flex"],o=new Set(["openai-completions","openai-responses","openai-codex-responses","azure-openai-responses"]);function S(e){return typeof e==="string"&&a.includes(e)}function c(e){if(o.has(e.api))return["standard","fast","flex"];if(e.api==="anthropic-messages"&&/(?:^|-)claude-opus-4-6(?:-|$)/i.test(e.id))return["standard","fast"];return["standard"]}function l(e,r){let i=c(e);if(r!=="auto"&&!i.includes(r))throw Error(`Service tier ${r} is not supported by ${e.name}`);if(r==="auto")return{selection:r,effective:"provider-default",supported:i};if(r==="standard")return{selection:r,effective:"standard",supported:i,...o.has(e.api)?{providerValue:"default"}:{}};if(r==="fast")return{selection:r,effective:"fast",supported:i,providerValue:e.api==="anthropic-messages"?"fast":"priority"};return{selection:r,effective:"flex",supported:i,providerValue:"flex"}}
|
|
2
|
-
export{f as
|
|
2
|
+
export{f as zi,p as Ai,u as Bi,S as Ci,c as Di,l as Ei};
|
package/package.json
CHANGED
package/dist/chunk-0pj7d25e.js
DELETED
|
@@ -1,23 +0,0 @@
|
|
|
1
|
-
import{s as pz,t as mz}from"./chunk-zmfm07hj.js";import{u as h}from"./chunk-3gf34fv5.js";import{A as Nz,v as cz,w as Dz,x as _z,y as Oz,z as qz}from"./chunk-xvg14dkr.js";import{H as x,Q as Bz,R as Vz,V as Gz,Y as Kz,Z as Uz,aa as wz,qa as Pz,ra as Rz,sa as Az,ta as xz}from"./chunk-yeq7qzdb.js";import"./chunk-abd57h72.js";import{Ha as gz}from"./chunk-p6prp8zc.js";import{Ja as Fz}from"./chunk-xm8nyj5z.js";import{Db as Lz,Mb as jz,rb as Xz}from"./chunk-8hp650gn.js";import{Xb as c}from"./chunk-8hprmrd5.js";import{Cd as m,Dd as Hz,Fd as E,Id as Yz,Nd as R,Qd as G,ad as Zz,kd as S,ld as p,md as T,rd as $z,ud as Qz,wd as Wz}from"./chunk-najk5ty4.js";import"./chunk-s0tq8gyx.js";import"./chunk-x3cxmwnz.js";import{ve as dz}from"./chunk-7g984trn.js";import"./chunk-z9gd9spf.js";import{Qe as Iz,Re as Cz}from"./chunk-5y38cfk9.js";import"./chunk-v508x7cg.js";import{af as d}from"./chunk-dg0d3303.js";import{ff as Jz}from"./chunk-rchz6j90.js";import"./chunk-w7hy5wh1.js";import{qf as fz}from"./chunk-2hb222re.js";import"./chunk-p39mmmbt.js";import"./chunk-151cz9k4.js";import"./chunk-kf7whgr7.js";import{ig as uz}from"./chunk-fva7jnjy.js";import"./chunk-41ympwz1.js";import"./chunk-6j482w6k.js";import"./chunk-41cg66y0.js";import{ah as kz,dh as Mz}from"./chunk-139frcak.js";import"./chunk-sdbbyagy.js";import"./chunk-f3426b1c.js";import{Hh as f,Ih as zz,Kh as u,Lh as g}from"./chunk-c475tfqf.js";import{Ph as hz}from"./chunk-0hr050ck.js";import"./chunk-q69fzq4y.js";import{pi as y}from"./chunk-n7mzxa8h.js";import"./chunk-s10pmnrd.js";import{wi as Sz,zi as yz}from"./chunk-9p20hhs0.js";import"./chunk-4bwr3rcj.js";import"./chunk-wyhyw9rq.js";import"./chunk-rvk9r2cm.js";import{Vi as e}from"./chunk-tgdhsm5t.js";import"./chunk-fhfzdyba.js";import{Readable as QJ,Writable as WJ}from"node:stream";import*as k from"@agentclientprotocol/sdk";import Ez from"node:path";import{PROTOCOL_VERSION as ZJ,RequestError as $J}from"@agentclientprotocol/sdk";import{RequestError as bz}from"@agentclientprotocol/sdk";import{nanoid as C}from"nanoid";import{createHash as lz}from"node:crypto";var M=4,iz=1000,o=4000,I=120000,n=0.2;function rz(z){try{return T(z)&&z.retryable}catch{return!1}}function az(z,Z){let J=Number.isSafeInteger(Z)&&Z>0?Z:1,H=J-1,Y=Math.min(iz*2**H,o),Q=lz("sha256").update(`${z}\x00${J}`).digest().readUInt32BE(0)/4294967295,W=1-n+2*n*Q;return Math.min(o,Math.max(0,Math.round(Y*W)))}function s(z){let Z=az(z.sessionIdentity,z.failedAttempt),J=z.evidence,H=z.workStillPending===!0&&J!==void 0&&rz(J.taskFailure)&&J.outputStarted===!1&&J.toolExecutionStarted===!1&&Number.isInteger(J.toolCallsCount)&&J.toolCallsCount===0,Y=Number.isSafeInteger(z.failedAttempt)&&z.failedAttempt>0&&z.failedAttempt<M,X=z.now??Date.now(),Q=X-z.recoveryStartedAt,W=Number.isFinite(X)&&Number.isFinite(z.recoveryStartedAt)&&Number.isFinite(Q)&&Q>=0&&Q+Z<=I;return{phase:H?Y&&W?"retry_scheduled":"exhausted":"failed",delayMs:Z,retryable:H,withinAttemptBudget:Y,withinTimeBudget:W}}var V=y("Agent");function t(z){if(!z)return{};return Object.fromEntries(z.map((Z)=>[Z.name,Z.value]))}function nz(z){if("command"in z)return{type:"stdio",command:z.command,args:z.args,env:t(z.env)};if("url"in z)return{type:z.type,url:z.url,headers:t("headers"in z?z.headers:void 0)};return null}function sz(z){let Z={};for(let J of z){let H=nz(J);if(H)Z[J.name]=H}return Z}function Tz(z){if(typeof z==="string")return z?[{type:"text",text:z}]:[];return z.flatMap((Z)=>{if(Z.type==="text")return Z.text?[{type:"text",text:Z.text}]:[];let J=Z.image_url.url,H=/^data:([^;,]+);base64,(.+)$/s.exec(J);if(!H)return[{type:"text",text:"[Image]"}];return[{type:"image",mimeType:H[1]??"image/png",data:H[2]??""}]})}function tz(z){let Z=Hz(z.metadata);return Z?[{type:"text",text:m(Z)}]:Tz(z.content)}function ez(z){return[`Status: ${z.status}`,`Exit code: ${z.exitCode??"null"}`,`Duration: ${(z.durationMs/1000).toFixed(3)} seconds`].join(`
|
|
2
|
-
`)}function zJ(z){if(!Jz(z)||z.reason!=="queue_full"||z.resource!=="pending_count"&&z.resource!=="pending_bytes")return;return{...S("capacity"),resource:z.resource}}function JJ(z){if(!(z instanceof bz)||!z.data||typeof z.data!=="object")return;let Z=z.data;if(!T(Z.taskFailure)||Z.toolExecutionStarted!==!1||!Number.isInteger(Z.toolCallsCount)||Z.toolCallsCount<0||Z.outputStarted!==!1)return;return{taskFailure:Z.taskFailure,toolExecutionStarted:Z.toolExecutionStarted,toolCallsCount:Z.toolCallsCount,outputStarted:Z.outputStarted}}class b{id;cwd;connection;clientCapabilities;options;agent=null;runtime=null;pendingPrompt=null;pendingPromptCompletion=null;pendingUserShell=null;pendingUserShellCompletion=null;pendingSideConversation=null;pendingSideConversationCompletion=null;pendingResumeRequested=!1;pendingResumeAttempt=0;projectedPendingResumeInputIds=new Set;pendingResumeRecoveryStartedAt=0;pendingResumeInFlight=!1;pendingResumeScheduled=!1;pendingResumeGeneration=0;pendingResumeTimer=null;availableCommandsTimer=null;taskStatusUnsubscribe;destroyed=!1;destroyFinished=!1;destroyPromise;messages;contextMessages;mode;updateEgress;constructor(z,Z,J,H,Y={}){this.id=z;this.cwd=Z;this.connection=J;this.clientCapabilities=H;this.options=Y;this.messages=[...Y.initialMessages??[]],this.contextMessages=[...this.messages],this.mode=this.mapPermissionModeToMode(Y.permissionMode),this.updateEgress=new Nz({maxPendingItems:Dz,maxPendingBytes:_z,writeTimeoutMs:Oz,signal:J.signal,sizeOf:(X)=>Buffer.byteLength(JSON.stringify(X)),write:async(X)=>{await J.sessionUpdate(X)},onFailure:(X)=>this.handleUpdateEgressFailure(X)})}async refreshPersistedMessages(){let[z,Z]=await Promise.all([G.loadSession(this.id,this.cwd),G.loadSessionModelContext(this.id,this.cwd)]);if(z.length>0)this.messages=z;if(Z.length>0)this.contextMessages=Z}async loadModelContextOr(z){let Z=await G.loadSessionModelContext(this.id,this.cwd);return Z.length>0?Z:[...z]}mapPermissionModeToMode(z){switch(z){case"yolo":return"yolo";case"autoEdit":return"auto-edit";case"plan":return"plan";case"default":default:return"default"}}createAgent(){if(!this.runtime)throw Error("Session runtime is unavailable");return wz.createWithRuntime(this.runtime,{sessionId:this.id,...this.options.taskWorktree?{toolBlacklist:["EnterWorktree","ExitWorktree"]}:{}})}async initialize(){if(V.debug(`[AcpSession ${this.id}] Initializing...`),await G.setSessionPermissionMode(this.id,this.cwd,this.mapModeToPermissionMode()??"default"),x.initializeSession(this.connection,this.id,this.clientCapabilities,this.cwd,async(W)=>{await this.sendUpdateAndWait(W)}),V.debug(`[AcpSession ${this.id}] ACP service context initialized`),await jz.resolvePendingWithHandler(this.cwd,this.id,{requestConfirmation:(W)=>this.requestPermission(W)}))await this.refreshPersistedMessages();else if((this.options.initialMessages?.length??0)>0)this.contextMessages=await this.loadModelContextOr(this.options.initialMessages??[]);let Z=this.options.mcpServers?sz(this.options.mcpServers):void 0,J=x.getInstance().getTerminalService(this.id);if(this.runtime=await Gz.create({sessionId:this.id,workspaceRoot:this.cwd,permissionMode:this.mapModeToPermissionMode(),...Z?{mcpServers:Z}:{},...this.options.taskWorktree?{taskWorktree:this.options.taskWorktree}:{},...this.options.taskIsolation?{taskIsolation:this.options.taskIsolation}:{},userShellExecutor:{execute:async(W,j)=>{let L=await J.execute(W,{cwd:j.cwd,env:j.env,timeout:j.timeoutMs,signal:j.signal,allowLocalFallback:!1,onOutput:(F)=>j.onOutput?.("stdout",F)});return{exitCode:L.exitCode,stdout:L.stdout,stderr:L.stderr,...L.error?{error:L.error}:{},timedOut:L.failureKind==="timeout",aborted:L.failureKind==="aborted"}}},...(this.options.initialMessages?.length??0)>0?{sessionStart:{isResume:!0,resumeSessionId:this.id}}:{}}),await h.recoverInterrupted(this.cwd,this.id,this.runtime))await this.refreshPersistedMessages();this.agent=await this.createAgent(),await Rz(this.cwd),V.debug(`[AcpSession ${this.id}] Agent created successfully`),this.taskStatusUnsubscribe?.(),this.taskStatusUnsubscribe=Xz.subscribe((W)=>{if(W.sessionId!==this.id||W.projectPath!==this.cwd)return;if(W.type==="subagent.completion.queued"){this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/backgroundSubagentCompletion":W.properties}}),this.requestPendingResume();return}if(W.type==="task.delivery"){if(!W.properties.taskDelivery||typeof W.properties.taskDelivery!=="object")return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:typeof W.properties.updatedAt==="string"?W.properties.updatedAt:new Date().toISOString(),_meta:{"blade/taskDelivery":W.properties.taskDelivery,...W.properties.taskWorktreeRemoved===!0?{"blade/taskWorktreeRemoved":!0}:{}}});return}if(W.type.startsWith("team.")){let{teamName:j,messageId:L,content:F}=W.properties,B=W.properties.metadata;if(W.type==="team.message.received"&&typeof j==="string"&&typeof L==="string"&&typeof F==="string"&&Vz(B,{messageId:L,teamName:j}))(async()=>{let K=await this.runtime?.enqueueSteering(F,{allowBeforeTurn:!0,messageId:L,origin:"team_message",metadata:B});if(!K?.accepted)return;if(await new Bz(j,e()).markDelivered([L]),K.delivery==="next_turn")this.requestPendingResume()})().catch((K)=>{V.warn(`[AcpSession ${this.id}] Failed to deliver teammate message`,K)});this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/teamEvent":{type:W.type,...W.properties}}});return}if(W.type!=="task.status")return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:typeof W.properties.updatedAt==="string"?W.properties.updatedAt:new Date().toISOString(),_meta:{"blade/taskStatus":W.properties.taskStatus,...typeof W.properties.taskStatusReason==="string"?{"blade/taskStatusReason":W.properties.taskStatusReason}:{},...W.properties.taskFailure&&typeof W.properties.taskFailure==="object"?{"blade/taskFailure":W.properties.taskFailure}:{},...typeof W.properties.taskStartedAt==="string"?{"blade/taskStartedAt":W.properties.taskStartedAt}:{},...typeof W.properties.taskCompletedAt==="string"?{"blade/taskCompletedAt":W.properties.taskCompletedAt}:{},...W.properties.taskDiffStat&&typeof W.properties.taskDiffStat==="object"?{"blade/taskDiffStat":W.properties.taskDiffStat}:{},...typeof W.properties.taskQueuePosition==="number"?{"blade/taskQueuePosition":W.properties.taskQueuePosition}:{},...typeof W.properties.taskQueueDepth==="number"?{"blade/taskQueueDepth":W.properties.taskQueueDepth}:{},...typeof W.properties.taskConcurrencyLimit==="number"?{"blade/taskConcurrencyLimit":W.properties.taskConcurrencyLimit}:{},...typeof W.properties.taskInFlight==="number"?{"blade/taskInFlight":W.properties.taskInFlight}:{}}})});let Y=await this.runtime.getGoal(),X=this.runtime.getPendingSteeringCount()>0,Q=Y?.status==="active"||Y?.status==="verifying";if(X||Q)this.requestPendingResume({defer:this.options.initialMessages!==void 0});else{let W=this.runtime.getTurnRecoveryAssessment();if(W.state!=="none")this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/turnRecovery":W}})}}async replayHistory(){for(let Z of this.messages){if(!this.canSendUpdates())return;if(!Wz(Z))continue;let J=Z.role==="user"?"user_message_chunk":Z.role==="assistant"?"agent_message_chunk":void 0;if(!J)continue;for(let H of tz(Z)){if(!this.canSendUpdates())return;if(!await this.sendUpdateAndWait({sessionUpdate:J,content:H}))return}}let z=await this.runtime?.getGoal();if(z&&!await this.sendUpdateAndWait(this.goalSessionUpdate(z)))return;if(this.pendingResumeRequested)this.ensurePendingResumeScheduled()}sendAvailableCommandsDelayed(){if(this.destroyed||this.connection.signal.aborted)return;if(this.availableCommandsTimer!==null)clearTimeout(this.availableCommandsTimer);V.debug(`[AcpSession ${this.id}] Scheduling available commands update (500ms delay)`),this.availableCommandsTimer=setTimeout(()=>{if(this.availableCommandsTimer=null,this.destroyed||this.connection.signal.aborted)return;this.sendAvailableCommands()},500)}async handleSlashCommand(z,Z){try{V.debug(`[AcpSession ${this.id}] Executing slash command: ${z}`);let J={cwd:this.cwd,surface:"acp",workspaceRoot:this.cwd,sessionId:this.id,messages:[...this.contextMessages],rewind:{listCheckpoints:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listRewindCheckpoints()},execute:async(Q)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let W=await this.runtime.rewindSession(Q);return this.messages=[...W.messages],this.contextMessages=await this.loadModelContextOr(W.messages),await this.agent?.destroy(),this.agent=await this.createAgent(),W}},reasoning:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getReasoningConfiguration()},set:async(Q)=>{if(await this.setReasoningEffort(Q),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getReasoningConfiguration()}},serviceTier:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getServiceTierConfiguration()},set:async(Q)=>{if(await this.setServiceTier(Q),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getServiceTierConfiguration()}},responseVerbosity:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getResponseVerbosityConfiguration()},set:async(Q)=>{if(await this.setResponseVerbosity(Q),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getResponseVerbosityConfiguration()}},communicationStyle:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getCommunicationStyleConfiguration()},set:async(Q)=>{if(await this.setCommunicationStyle(Q),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getCommunicationStyleConfiguration()}},subagents:{list:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listSubagents()},resume:async(Q,W)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let j=!1,L,F=(K)=>{this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:K.id,status:K.status==="completed"?"completed":"failed",content:[{type:"content",content:{type:"text",text:K.result?.message||K.result?.error||`Subagent ${K.status}`}}]})},B=this.runtime.resumeSubagent({agentId:Q,prompt:W,onCompleted:(K)=>{if(j)F(K);else L=K}});if(this.sendUpdate({sessionUpdate:"tool_call",toolCallId:B.session.id,status:"in_progress",title:`Resuming ${B.session.subagentType} subagent`,content:[{type:"content",content:{type:"text",text:`Resumed from ${B.source.id} at depth ${B.session.resumeDepth}`}}],kind:this.mapToolKind("readonly")}),j=!0,L)F(L);return B}},mcp:{getCatalog:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpContentCatalog()},refresh:async(Q)=>{if(!this.runtime)throw Error("Session runtime is unavailable");await this.runtime.refreshMcpContentCatalogs(Q)},getPrompt:async(Q,W,j)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpPrompt(Q,W,j)},complete:async(Q,W,j)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.completeMcpArgument(Q,W,j)},listTasks:async(Q)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listMcpTasks(Q)},getTask:async(Q)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpTask(Q)},cancelTask:async(Q,W)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.cancelMcpTask(Q,W)},getLogs:async(Q,W)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpLogs(Q,W)},setLoggingLevel:async(Q,W)=>{if(!this.runtime)throw Error("Session runtime is unavailable");await this.runtime.setMcpLoggingLevel(Q,W)},getInstructions:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpInstructions()}},sideConversation:{ask:async(Q,W)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.askSideQuestion(Q,{signal:W})}},codeReview:{run:async(Q,W)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let j=await h.start({sessionId:this.id,projectPath:this.cwd,runtime:this.runtime,request:Q,signal:W,onEvent:(B)=>{if(B.kind==="tool_start")this.sendUpdate({sessionUpdate:"tool_call",toolCallId:B.toolCall.id,status:"in_progress",title:`Review: ${B.toolCall.function.name}`,content:[],kind:this.mapToolKind(B.toolKind)});else if(B.kind==="tool_result")this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:B.toolCall.id,status:B.result.success?"completed":"failed",content:[]})}}),L=await j.completion,F=(await h.list(this.cwd,this.id)).find((B)=>B.start.reviewId===j.reviewId);if(!F)throw Error(`Review not found: ${j.reviewId}`);return await this.refreshPersistedMessages(),{reviewId:j.reviewId,status:L.status,findings:L.findings.length,content:Zz(F.start,L)}}},signal:Z,acp:{sendMessage:(Q)=>{this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:Q}})},sendToolStart:(Q,W,j)=>{let L=`tool_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,F=this.mapToolKind(j);this.sendUpdate({sessionUpdate:"tool_call",toolCallId:L,status:"in_progress",title:`${Q}`,content:[{type:"content",content:{type:"text",text:JSON.stringify(W,null,2)}}],kind:F})},sendToolResult:(Q,W)=>{if(W.summary)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:W.summary}})}}},H=await Az(z,J),Y=H.data?.action;if(Y==="start_goal"||Y==="resume_goal")this.requestPendingResume();if(Y==="rewind_session"&&Array.isArray(H.data?.messages))this.messages=[...H.data.messages],this.contextMessages=await this.loadModelContextOr(H.data.messages);if((H.message==="compact_completed"||H.message==="compact_fallback")&&H.data?.compactedMessages){this.contextMessages=[...H.data.compactedMessages];let Q=await G.loadSession(this.id,this.cwd);if(Q.length>0)this.messages=Q}let X=H.content||H.message;if(X)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:X}});if(H.error)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] ${H.error}`}});return await this.flushUpdates(),{stopReason:H.success?"end_turn":"cancelled"}}catch(J){if(Z.aborted||J instanceof Error&&J.name==="AbortError")return{stopReason:"cancelled"};return V.error(`[AcpSession ${this.id}] Slash command error:`,J),this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] 命令执行失败: ${J instanceof Error?J.message:"未知错误"}`}}),{stopReason:"cancelled"}}}async handleSideConversationCommand(z){if(this.pendingSideConversation)throw Error("A side conversation is already running");let Z=new AbortController,J,H=new Promise((Y)=>{J=Y});this.pendingSideConversation=Z,this.pendingSideConversationCompletion=H;try{return await this.handleSlashCommand(z,Z.signal)}catch(Y){if(Z.signal.aborted||Y instanceof Error&&Y.name==="AbortError")return{stopReason:"cancelled"};throw Y}finally{if(J(),this.pendingSideConversationCompletion===H)this.pendingSideConversationCompletion=null;if(this.pendingSideConversation===Z){if(this.pendingSideConversation=null,!this.destroyed&&this.pendingResumeRequested)this.ensurePendingResumeScheduled()}}}async sendAvailableCommands(){try{let z=xz(this.cwd,this.runtime?.getAgentResources()),Z=["model","permissions","theme","config","exit","ide"],H=z.filter((Y)=>!Z.includes(Y.name)&&(Y.name!=="team"||this.runtime?.getConfig().agentTeamsEnabled===!0)).map((Y)=>{let X;if(Y.usage){let Q=Y.usage.replace(/^\/\w+\s*/,"").trim();if(Q)X=Q}if(Y.aliases?.length){let Q=`Aliases: ${Y.aliases.join(", ")}`;X=X?`${X} | ${Q}`:Q}return{name:Y.name,description:Y.description,input:X?{hint:X}:void 0}});V.info(`[AcpSession ${this.id}] Sending available commands: ${JSON.stringify(H.map((Y)=>Y.name))}`),this.sendUpdate({sessionUpdate:"available_commands_update",availableCommands:H}),V.info(`[AcpSession ${this.id}] Sent ${H.length} available commands`)}catch(z){V.error(`[AcpSession ${this.id}] Failed to send available commands:`,z)}}async prompt(z,Z={}){if(x.setCurrentSession(this.id),!this.agent||!this.runtime)throw Error("Session not initialized");let J=this.resolvePrompt(z.prompt),H=J.content,Y=J.displayText,X=z._meta?.outputSchema??(Z.pendingInputOnly?this.runtime.getPendingSteeringMessages().find((w)=>w.outputSchema)?.outputSchema:void 0),Q;if(X!==void 0)Q=Yz(X).schema;if(Y.trimStart().startsWith("!")){if(Q)throw Error("Output schemas cannot be combined with user shell commands");return this.handleUserShellCommand(Y)}let W=Fz(Y);if(W){if(Q)throw Error("Output schemas cannot be combined with slash commands");if(Array.isArray(H)&&H.some((w)=>w.type==="image_url"))throw Error("Side conversations do not accept image attachments");return this.handleSideConversationCommand(W.question?`/btw ${W.question}`:"/btw")}if(this.pendingPrompt){if(Q)throw Error("Wait for the active turn to finish before setting an output schema");if(/^\/goal(?:\s|$)/i.test(Y.trim()))return this.handleSlashCommand(Y,this.pendingPrompt.signal);let w=await this.runtime.enqueueSteering(H,{allowBeforeTurn:!0});if(!w.accepted)throw Error(w.reason==="queue_full"?"Active turn steering queue is full":"Active turn is no longer steerable");if(V.debug(`[AcpSession ${this.id}] Queued steering for active turn (${w.queued})`),w.delivery==="next_turn")this.requestPendingResume();return{stopReason:"end_turn"}}let j=new AbortController,L=()=>{j.abort(Z.abortSignal?.reason)};if(Z.abortSignal?.aborted)L();else Z.abortSignal?.addEventListener("abort",L,{once:!0});let F=!1,B=!1,K=!1,l,i=new Promise((w)=>{l=w});this.pendingPrompt=j,this.pendingPromptCompletion=i;try{if(V.debug(`[AcpSession ${this.id}] Received prompt: ${Y.slice(0,100)}...`),Pz(Y)){if(Q)throw Error("Output schemas cannot be combined with slash commands");return await this.handleSlashCommand(Y,j.signal)}let w={sessionId:this.id,userId:"acp-user",workspaceRoot:this.cwd,messages:[...this.contextMessages],signal:j.signal,permissionMode:this.mapModeToPermissionMode(),onPermissionModeChange:async($)=>{this.mode=this.mapPermissionModeToMode($),this.sendUpdate({sessionUpdate:"current_mode_update",currentModeId:this.mode})},...this.options.taskWorktree?{worktreeActive:!0}:{},confirmationHandler:{requestConfirmation:async($)=>{return this.requestPermission($)}}},O=await Lz(this.agent.chatStream(H,w,{pendingInputOnly:Z.pendingInputOnly,goalContinuationOnly:Z.goalContinuationOnly,outputSchema:Q}),async($)=>{switch($.kind){case"content_delta":if(Q)break;if($.delta.length>0)B=!0;this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:$.delta}});break;case"thinking_delta":if($.delta.length>0)B=!0;this.sendUpdate({sessionUpdate:"agent_thought_chunk",content:{type:"text",text:$.delta}});break;case"tool_start":{K=!0;let U=$.toolCall,q=U.function.name;if(q===E)break;let P=this.mapToolKind($.toolKind),D=`Executing ${q}`;if(q==="Task"&&"function"in U)try{let A=JSON.parse(U.function.arguments),_=A.resume_from??A.resume;if(typeof _==="string")D=`Resuming ${String(A.subagent_type||"subagent")} from ${_}`}catch{}this.sendUpdate({sessionUpdate:"tool_call",toolCallId:U.id,status:"in_progress",title:D,content:[],kind:P});break}case"tool_progress":{K=!0;let U=$.toolCall;if(U.function.name===E)break;this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:U.id,status:"in_progress",content:[{type:"content",content:{type:"text",text:$.update.message}}]});break}case"tool_result":{K=!0;let U=$.toolCall;if(U.function.name===E)break;let q=$.result,P=[],D=q.metadata;if(D?.kind==="patch"&&Array.isArray(D.changes))for(let _ of D.changes){if(!_||typeof _!=="object"||!("path"in _)||typeof _.path!=="string")continue;P.push({type:"diff",path:_.path,oldText:"oldContent"in _&&typeof _.oldContent==="string"?_.oldContent:null,newText:"newContent"in _&&typeof _.newContent==="string"?_.newContent:null})}else if(D?.kind==="edit"&&typeof D.file_path==="string"&&typeof D.oldContent==="string"&&(typeof D.newContent==="string"||D.newContent===void 0))P.push({type:"diff",path:D.file_path,oldText:D.oldContent,newText:D.newContent??null});else{let _=U.function.name,vz=Uz(Qz(Kz(_,q),$z));P.push({type:"content",content:{type:"text",text:vz}})}if(U.function.name==="Task"&&(D?.verificationVerdict==="pass"||D?.verificationVerdict==="fail"||D?.verificationVerdict==="partial"))P.unshift({type:"content",content:{type:"text",text:`Verification result: ${D.verificationVerdict.toUpperCase()}`}});let A=q.success?"completed":"failed";this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:U.id,status:A,content:P});break}case"structured_output":B=!0,this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:JSON.stringify($.output)}});break;case"mcp_catalog_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP catalog r${$.revision} (${$.serverName}): +${$.added.length} -${$.removed.length} ~${$.updated.length}
|
|
3
|
-
`}});break;case"mcp_content_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP ${$.contentKind} r${$.revision} (${$.serverName}): +${$.added.length} -${$.removed.length} ~${$.updated.length}
|
|
4
|
-
`}});break;case"mcp_resource_updated":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP resource updated r${$.revision} (${$.serverName}): ${$.uri}
|
|
5
|
-
`}});break;case"mcp_connection_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP connection r${$.revision} (${$.serverName}): ${$.phase} ${$.attempt}/${$.maxAttempts}
|
|
6
|
-
`}});break;case"mcp_log":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP log r${$.revision} (${$.serverName}) ${$.level}${$.logger?` logger=${$.logger}`:""}: ${$.message}
|
|
7
|
-
`}});break;case"mcp_instructions_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP instructions r${$.revision} (${$.serverName}): ${$.action}${$.detailsOmitted?" details-omitted":""}
|
|
8
|
-
`}});break;case"mcp_task_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP task r${$.revision} ${$.taskId} (${$.serverName}/${$.toolName}): ${$.status}${$.hasResult?" result-available":""}
|
|
9
|
-
`}});break;case"project_rules_loaded":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`Project rules loaded: ${$.files.length}${$.blockedWrite?" (write retry required)":""}
|
|
10
|
-
`}});break;case"provider_admission":F=$.phase!=="admitted",this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/providerAdmission":$.phase!=="admitted"?{phase:$.phase,requestClass:$.requestClass,resource:$.resource,scope:$.scope,...$.reason!==void 0?{reason:$.reason}:{},queuePosition:$.queuePosition,queueDepth:$.queueDepth,inFlight:$.inFlight,limit:$.limit,waitMs:$.waitMs,maxWaitMs:$.maxWaitMs,...$.recoveryRemainingMs!==void 0?{recoveryRemainingMs:$.recoveryRemainingMs}:{}}:null}});break;case"provider_circuit":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/providerCircuit":{phase:$.phase,reason:$.reason,...$.statusCode!==void 0?{statusCode:$.statusCode}:{},...$.retryAfterMs!==void 0?{retryAfterMs:$.retryAfterMs}:{},...$.nextProbeAt!==void 0?{nextProbeAt:$.nextProbeAt}:{},openDurationMs:$.openDurationMs,...$.sampleCount!==void 0?{sampleCount:$.sampleCount}:{},...$.failureCount!==void 0?{failureCount:$.failureCount}:{},...$.recoveryRemainingMs!==void 0?{recoveryRemainingMs:$.recoveryRemainingMs}:{}}}});break;case"provider_retry":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/providerRetry":{phase:$.phase,attempt:$.attempt,maxRetries:$.maxRetries,reason:$.reason,...$.statusCode!==void 0?{statusCode:$.statusCode}:{},...$.delayMs!==void 0?{delayMs:$.delayMs}:{},...$.nextRetryAt!==void 0?{nextRetryAt:$.nextRetryAt}:{},...$.mode!==void 0?{mode:$.mode}:{},...$.recoveryBudgetMs!==void 0?{recoveryBudgetMs:$.recoveryBudgetMs}:{},...$.recoveryElapsedMs!==void 0?{recoveryElapsedMs:$.recoveryElapsedMs}:{},...$.recoveryRemainingMs!==void 0?{recoveryRemainingMs:$.recoveryRemainingMs}:{},...$.exhaustedBy!==void 0?{exhaustedBy:$.exhaustedBy}:{}}}});break;case"turn_recovery":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/turnRecovery":$.assessment}});break;case"provider_stall":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/providerStall":{phase:$.phase,stallCount:$.stallCount,durationMs:$.durationMs,warningAfterMs:$.warningAfterMs,timeoutMs:$.timeoutMs,outputStarted:$.outputStarted}}});break;case"action_stationarity":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/actionStationarity":{phase:$.phase,toolName:$.toolName,runLength:$.runLength,nudgeThreshold:$.nudgeThreshold,haltThreshold:$.haltThreshold,progressAware:$.progressAware}}});break;case"task_update":this.sendPlanUpdate($.tasks);break;case"goal_frontier_updated":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:$.frontier.observedAt,_meta:{"blade/goalFrontier":{goalId:$.goal.goalId,status:$.goal.status,taskListId:$.frontier.taskListId,total:$.frontier.total,completed:$.frontier.completed,inProgress:$.frontier.inProgress,pending:$.frontier.pending,blocked:$.frontier.blocked,nextTask:$.frontier.nextTask,digestSha256:$.frontier.digestSha256,...$.goal.frontierStall?{stall:{category:$.goal.frontierStall.category,consecutiveCount:$.goal.frontierStall.consecutiveCount}}:{}}}}),this.sendPlanUpdate($.tasks);break;case"steering_applied":break;case"follow_up_started":{let U=0;for(let q of $.messages){if(!q.recovered||q.persisted)continue;if(Z.projectedRecoveredInputIds?.has(q.id))continue;for(let P of Tz(q.content))this.sendUpdate({sessionUpdate:"user_message_chunk",content:P});Z.projectedRecoveredInputIds?.add(q.id),U++}if(U>0)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[Resuming ${U} queued instruction${U===1?"":"s"} recovered after restart]
|
|
11
|
-
`}});break}case"goal_updated":if($.goal)this.sendUpdate(this.goalSessionUpdate($.goal));if($.goal&&$.goal.status!=="active")this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[Goal ${$.goal.status}: ${$.goal.objective}]
|
|
12
|
-
`}});break;case"goal_continuation_started":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/goalContinuation":{goalId:$.goal.goalId,continuation:$.continuation,...$.prematureStopPattern?{prematureStopPattern:$.prematureStopPattern}:{},...$.prematureStopCount!==void 0?{prematureStopCount:$.prematureStopCount}:{}}}});break;case"compaction":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/compaction":{phase:$.phase,...$.reason?{reason:$.reason}:{},...$.strategy?{strategy:$.strategy}:{},...$.outcome?{outcome:$.outcome}:{},...$.preTokens!==void 0?{preTokens:$.preTokens}:{},...$.preTokenSource?{preTokenSource:$.preTokenSource}:{},...$.estimatedPendingTokens!==void 0?{estimatedPendingTokens:$.estimatedPendingTokens}:{},...$.postTokens!==void 0?{postTokens:$.postTokens}:{},...$.sampleAttempts!==void 0?{sampleAttempts:$.sampleAttempts}:{},...$.inputReductions!==void 0?{inputReductions:$.inputReductions}:{},...$.messagesOmitted!==void 0?{messagesOmitted:$.messagesOmitted}:{},...$.filesOmitted!==void 0?{filesOmitted:$.filesOmitted}:{},...$.imagesOmitted!==void 0?{imagesOmitted:$.imagesOmitted}:{},...$.fallbackTargetTokens!==void 0?{fallbackTargetTokens:$.fallbackTargetTokens}:{},...$.fallbackMessagesOmitted!==void 0?{fallbackMessagesOmitted:$.fallbackMessagesOmitted}:{},...$.fallbackMessagesTruncated!==void 0?{fallbackMessagesTruncated:$.fallbackMessagesTruncated}:{},...$.failureReason?{failureReason:$.failureReason}:{}}}});break;default:break}if(!await this.flushUpdates())j.abort("acp-egress-failed")});if(!await this.flushUpdates())j.abort("acp-egress-failed");this.contextMessages=[...w.messages];let r=await G.loadSession(this.id,this.cwd);if(this.messages=r.length>0?r:[...w.messages],!O.success){let $=O.error?.type??"unknown",U=O.error?.details??O.error?.message??"Agent execution failed",q=zJ(U)??p(U);throw bz.internalError({failureType:$,modelId:this.runtime.getCurrentModelId(),taskFailure:q,outputStarted:B,toolExecutionStarted:K,...Number.isInteger(O.metadata?.toolCallsCount)?{toolCallsCount:O.metadata.toolCallsCount}:{}},`Agent turn failed (${$})`)}if(j.signal.aborted)return{stopReason:"cancelled"};let a={...O.metadata?.structuredOutput?{structuredOutput:O.metadata.structuredOutput,outputSchemaDigest:O.metadata.structuredOutputSchemaDigest}:{},...O.metadata?.goalCompletionVerified?{goalCompletion:{verified:!0,verdict:O.metadata.goalVerificationVerdict,...O.metadata.goalVerifierSessionId?{verifierSessionId:O.metadata.goalVerifierSessionId}:{},...O.metadata.goalVerificationEvidenceSha256?{evidenceSha256:O.metadata.goalVerificationEvidenceSha256}:{}}}:{}};return{stopReason:"end_turn",...Object.keys(a).length>0?{_meta:a}:{}}}catch(w){if(j.signal.aborted||w instanceof Error&&w.name==="AbortError")return{stopReason:"cancelled"};throw V.error(`[AcpSession ${this.id}] Prompt error:`,w),w}finally{if(Z.abortSignal?.removeEventListener("abort",L),F&&!this.destroyed)this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/providerAdmission":null}}),await this.flushUpdates();if(l(),this.pendingPromptCompletion===i)this.pendingPromptCompletion=null;if(this.pendingPrompt===j){if(this.pendingPrompt=null,!this.destroyed&&this.pendingResumeRequested)this.ensurePendingResumeScheduled()}}}async handleUserShellCommand(z){if(!this.runtime)throw Error("Session runtime is unavailable");if(this.pendingUserShell)throw Error("A user shell command is already running");let Z=z.trimStart().slice(1).trim();if(!Z)throw Error("User shell command cannot be empty");let J=new AbortController,H,Y=new Promise((W)=>{H=W});this.pendingUserShell=J,this.pendingUserShellCompletion=Y;let X,Q="";try{let W=await this.runtime.executeUserShellCommand(Z,{signal:J.signal,onEvent:async(L)=>{if(X=L.executionId,L.type==="started"){this.sendUpdate({sessionUpdate:"tool_call",toolCallId:L.executionId,status:"in_progress",title:`! ${L.command}`,content:[],kind:"execute"});return}if(L.type==="output"){Q+=L.chunk,this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:L.executionId,status:"in_progress",content:[{type:"content",content:{type:"text",text:L.chunk}}]});return}let F=m(L.record);this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:L.executionId,status:L.record.status==="completed"?"completed":"failed",content:[{type:"content",content:{type:"text",text:Q?ez(L.record):F}}]})}}),j={role:"user",content:W.modelContent,metadata:{userShellCommand:JSON.parse(JSON.stringify(W.record))}};if(this.messages.push(j),this.contextMessages.push(j),W.delivery==="next_turn")this.requestPendingResume();if(!await this.flushUpdates())return J.abort("acp-egress-failed"),{stopReason:"cancelled"};return{stopReason:W.record.status==="aborted"?"cancelled":"end_turn"}}catch(W){if(X)this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:X,status:"failed",content:[{type:"content",content:{type:"text",text:W instanceof Error?W.message:String(W)}}]});if(J.signal.aborted)return{stopReason:"cancelled"};throw W}finally{if(H(),this.pendingUserShellCompletion===Y)this.pendingUserShellCompletion=null;if(this.pendingUserShell===J){if(this.pendingUserShell=null,!this.destroyed&&this.pendingResumeRequested)this.ensurePendingResumeScheduled()}}}requestPendingResume(z={}){if(!this.canSendUpdates())return;if(!this.pendingResumeRequested){if(this.pendingResumeRequested=!0,!this.pendingResumeInFlight)this.pendingResumeAttempt=0,this.projectedPendingResumeInputIds.clear(),this.pendingResumeRecoveryStartedAt=0}if(!z.defer)this.ensurePendingResumeScheduled()}ensurePendingResumeScheduled(z=0){if(!this.pendingResumeRequested||!this.canSendUpdates()||this.pendingResumeScheduled||this.pendingResumeInFlight)return;this.pendingResumeScheduled=!0;let Z=this.pendingResumeGeneration,J=()=>{if(Z!==this.pendingResumeGeneration)return;this.pendingResumeScheduled=!1,this.pendingResumeTimer=null,this.resumePendingIfIdle()};if(z>0)this.pendingResumeTimer=setTimeout(J,z),this.pendingResumeTimer.unref?.();else queueMicrotask(J)}clearPendingResumeRequest(){let z=this.pendingResumeRequested||this.pendingResumeScheduled||this.pendingResumeInFlight||this.pendingResumeTimer!==null;if(this.pendingResumeRequested=!1,this.pendingResumeAttempt=0,this.projectedPendingResumeInputIds.clear(),this.pendingResumeRecoveryStartedAt=0,this.pendingResumeGeneration++,this.pendingResumeScheduled=!1,this.pendingResumeTimer!==null)clearTimeout(this.pendingResumeTimer),this.pendingResumeTimer=null;return z}preserveNewPendingInput(z){if(z==="pending_input"||!this.pendingResumeRequested||!this.runtime||this.runtime.getPendingSteeringCount()===0)return!1;return this.pendingResumeAttempt=0,this.projectedPendingResumeInputIds.clear(),this.pendingResumeRecoveryStartedAt=0,!0}pendingResumeSessionUpdate(z,Z){return{sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/pendingResume":{phase:z,kind:Z.kind,attempt:Z.attempt,maxAttempts:M,...Z.delayMs!==void 0?{delayMs:Z.delayMs,nextRetryAt:Date.now()+Z.delayMs}:{},...Z.taskFailure?{failure:{code:Z.taskFailure.code,retryable:Z.taskFailure.retryable,...Z.taskFailure.resource?{resource:Z.taskFailure.resource}:{}}}:{}}}}}async resumePendingIfIdle(){if(!this.pendingResumeRequested)return;if(!this.canSendUpdates()){this.clearPendingResumeRequest();return}if(this.pendingResumeInFlight||this.pendingPrompt||this.pendingUserShell||this.pendingSideConversation||!this.runtime||!this.agent)return;this.pendingResumeInFlight=!0,this.pendingResumeRequested=!1;let z=this.pendingResumeGeneration,Z=this.pendingResumeAttempt+1;if(this.pendingResumeAttempt=Z,this.pendingResumeRecoveryStartedAt===0)this.pendingResumeRecoveryStartedAt=Date.now();let J="preflight",H=!1,Y,X=null;try{let Q=this.runtime.getPendingSteeringCount()>0,W=Q?null:await this.runtime.getGoal();if(z!==this.pendingResumeGeneration)return;let j=W?.status==="active"||W?.status==="verifying",L=this.runtime.getTurnRecoveryAssessment();if(L.state!=="none"&&(L.state==="requires_attention"||!Q&&!j))this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/turnRecovery":L}});if(!Q&&!j){if(this.pendingResumeRequested){this.pendingResumeAttempt=0,this.projectedPendingResumeInputIds.clear(),this.pendingResumeRecoveryStartedAt=0;return}this.clearPendingResumeRequest();return}if(L.state==="requires_attention"){this.clearPendingResumeRequest();return}J=Q?"pending_input":"goal",H=!0;let F=I-(Date.now()-this.pendingResumeRecoveryStartedAt);if(F<=0){if(this.sendUpdate(this.pendingResumeSessionUpdate("exhausted",{attempt:Z,kind:J,taskFailure:S("timeout")})),!this.preserveNewPendingInput(J))this.clearPendingResumeRequest();return}let B=new AbortController;X=setTimeout(()=>{B.abort("acp-pending-resume-budget-exhausted")},F),X.unref?.();let K=await this.prompt({sessionId:this.id,prompt:[]},{pendingInputOnly:Q,goalContinuationOnly:j,projectedRecoveredInputIds:J==="pending_input"?this.projectedPendingResumeInputIds:void 0,abortSignal:B.signal});if(z!==this.pendingResumeGeneration)return;if(B.signal.aborted){if(this.sendUpdate(this.pendingResumeSessionUpdate("exhausted",{attempt:Z,kind:J,taskFailure:S("timeout")})),!this.preserveNewPendingInput(J))this.clearPendingResumeRequest();return}if(K.stopReason!=="end_turn"){this.clearPendingResumeRequest();return}if(Z>1)this.sendUpdate(this.pendingResumeSessionUpdate("recovered",{attempt:Z,kind:J}));this.pendingResumeAttempt=0,this.projectedPendingResumeInputIds.clear(),this.pendingResumeRecoveryStartedAt=0}catch(Q){if(z!==this.pendingResumeGeneration)return;let W=H?JJ(Q):{taskFailure:p(Q),toolExecutionStarted:!1,toolCallsCount:0,outputStarted:!1},j=J==="preflight"||J==="pending_input"&&this.runtime.getPendingSteeringCount()>0,L=s({sessionIdentity:this.id,failedAttempt:Z,recoveryStartedAt:this.pendingResumeRecoveryStartedAt,workStillPending:j,evidence:W});if(L.phase==="retry_scheduled")this.pendingResumeRequested=!0,Y=L.delayMs,this.sendUpdate(this.pendingResumeSessionUpdate("retry_scheduled",{attempt:Z+1,kind:J,taskFailure:W?.taskFailure,delayMs:L.delayMs})),V.warn(`[AcpSession ${this.id}] Pending resume attempt ${Z} failed; retrying in ${L.delayMs}ms`);else{let F=L.phase;if(this.sendUpdate(this.pendingResumeSessionUpdate(F,{attempt:Z,kind:J,taskFailure:W?.taskFailure})),V.error(`[AcpSession ${this.id}] Failed to resume pending input (attempt=${Z}, retryable=${L.retryable}, phase=${F})`,Q),!this.preserveNewPendingInput(J))this.clearPendingResumeRequest()}}finally{if(X!==null)clearTimeout(X);if(this.pendingResumeInFlight=!1,this.pendingResumeRequested)this.ensurePendingResumeScheduled(Y)}}cancel(){V.info(`[AcpSession ${this.id}] Cancel requested`);let z=this.clearPendingResumeRequest();if(this.pendingPrompt)this.pendingPrompt.abort(),this.pendingPrompt=null,z=!0;if(this.pendingUserShell)this.pendingUserShell.abort(),this.pendingUserShell=null,z=!0;if(this.pendingSideConversation)this.pendingSideConversation.abort(),this.pendingSideConversation=null,z=!0;if(!z)V.warn(`[AcpSession ${this.id}] No pending prompt to cancel`)}async setMode(z){let J=["default","auto-edit","yolo","plan"].includes(z)?z:"default",H=this.mapModeIdToPermissionMode(J);await G.setSessionPermissionMode(this.id,this.cwd,H),this.mode=J,V.info(`[AcpSession ${this.id}] Mode set to: ${this.mode}`),this.sendUpdate({sessionUpdate:"current_mode_update",currentModeId:this.mode})}mapModeToPermissionMode(){return this.mapModeIdToPermissionMode(this.mode)}mapModeIdToPermissionMode(z){switch(z){case"yolo":return"yolo";case"auto-edit":return"autoEdit";case"plan":return"plan";case"default":default:return"default"}}shouldAutoApprove(z){switch(this.mode){case"yolo":return!0;case"auto-edit":return z==="readonly"||z==="write";case"plan":return z==="readonly";case"default":default:return!1}}async setModel(z){if(V.info(`[AcpSession ${this.id}] Model set to: ${z}`),this.pendingPrompt)throw Error("Cannot switch models while a prompt is active");if(!this.agent)throw Error("Session not initialized");if(!this.runtime)throw Error("Session runtime is unavailable");let Z=this.runtime.getCurrentModelId();await this.agent.switchModel(z);try{try{await G.updateSessionMetadata(this.id,this.cwd,{selectedModelId:z})}catch(J){if(!(J instanceof R)&&J.code!=="ENOENT")throw J;await G.createSessionMetadata(this.id,this.cwd,{taskStatus:"completed",selectedModelId:z})}}catch(J){if(Z&&Z!==z)await this.agent.switchModel(Z).catch((H)=>{V.error(`[AcpSession ${this.id}] Failed to roll back a non-durable model switch:`,H)});throw J}}getCurrentModelId(){return this.runtime?.getCurrentModelId()}async setReasoningEffort(z){if(this.pendingPrompt)throw Error("Cannot switch reasoning effort while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let Z=this.runtime.getReasoningConfiguration();try{this.runtime.resolveReasoningConfiguration(z)}catch(J){throw Error(J instanceof Error?J.message:"Invalid reasoning effort")}if(Z.selection===z)return;await this.runtime.refresh({reasoningEffort:z});try{try{await G.updateSessionMetadata(this.id,this.cwd,{reasoningEffort:z})}catch(J){if(!(J instanceof R)&&J.code!=="ENOENT")throw J;await G.createSessionMetadata(this.id,this.cwd,{taskStatus:"completed",selectedModelId:this.runtime.getCurrentModelId(),reasoningEffort:z})}}catch(J){throw await this.runtime.refresh({reasoningEffort:Z.selection}),J}}async setServiceTier(z){if(this.pendingPrompt)throw Error("Cannot switch service tier while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let Z=this.runtime.getServiceTierConfiguration();try{this.runtime.resolveServiceTierConfiguration(z)}catch(J){throw Error(J instanceof Error?J.message:"Invalid service tier")}if(Z.selection===z)return;await this.runtime.refresh({serviceTier:z});try{try{await G.updateSessionMetadata(this.id,this.cwd,{serviceTier:z})}catch(J){if(!(J instanceof R)&&J.code!=="ENOENT")throw J;await G.createSessionMetadata(this.id,this.cwd,{taskStatus:"completed",selectedModelId:this.runtime.getCurrentModelId(),serviceTier:z})}}catch(J){throw await this.runtime.refresh({serviceTier:Z.selection}),J}}async setResponseVerbosity(z){if(this.pendingPrompt)throw Error("Cannot switch response verbosity while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let Z=this.runtime.getResponseVerbosityConfiguration();try{this.runtime.resolveResponseVerbosityConfiguration(z)}catch(J){throw Error(J instanceof Error?J.message:"Invalid response verbosity")}if(Z.selection===z)return;await this.runtime.refresh({responseVerbosity:z});try{try{await G.updateSessionMetadata(this.id,this.cwd,{responseVerbosity:z})}catch(J){if(!(J instanceof R)&&J.code!=="ENOENT")throw J;await G.createSessionMetadata(this.id,this.cwd,{taskStatus:"completed",selectedModelId:this.runtime.getCurrentModelId(),responseVerbosity:z})}}catch(J){throw await this.runtime.refresh({responseVerbosity:Z.selection}),J}}async setCommunicationStyle(z){if(this.pendingPrompt)throw Error("Cannot switch communication style while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let Z=this.runtime.getCommunicationStyleConfiguration(),J=this.runtime.resolveCommunicationStyleConfiguration(z);if(J.source!=="built-in"&&!J.contentSha256)throw Error("Custom communication style has no provenance");if(Z.selection===z)return;await this.runtime.refresh({communicationStyle:z});try{try{await G.updateSessionMetadata(this.id,this.cwd,{communicationStyle:z,communicationStyleDigest:J.source==="built-in"?null:J.contentSha256})}catch(H){if(!(H instanceof R)&&H.code!=="ENOENT")throw H;await G.createSessionMetadata(this.id,this.cwd,{taskStatus:"completed",selectedModelId:this.runtime.getCurrentModelId(),communicationStyle:z,...J.source!=="built-in"&&J.contentSha256?{communicationStyleDigest:J.contentSha256}:{}})}}catch(H){throw await this.runtime.refresh({communicationStyle:Z.selection}),H}}getModelConfiguration(){if(!this.runtime)return;let z=this.runtime.getConfig();return{currentModelId:this.runtime.getCurrentModelId()??z.currentModelId,models:z.models.map((Z)=>structuredClone(Z)),modelProviders:structuredClone(z.modelProviders),reasoning:this.runtime.getReasoningConfiguration(),serviceTier:this.runtime.getServiceTierConfiguration(),responseVerbosity:this.runtime.getResponseVerbosityConfiguration(),communicationStyle:this.runtime.getCommunicationStyleConfiguration()}}getMode(){return this.mode}isIdleForResidency(){return!this.destroyed&&this.pendingPrompt===null&&this.pendingUserShell===null&&this.pendingSideConversation===null&&(this.runtime?.isIdleForResidency()??!1)}destroy(z={}){if(this.destroyPromise)return this.destroyFinished?Promise.resolve():this.destroyPromise;return this.destroyPromise=this.destroyOwnedResources(z.discardPendingInput===!0).finally(()=>{this.destroyFinished=!0}),this.destroyPromise}async destroyOwnedResources(z){if(this.destroyed=!0,this.clearPendingResumeRequest(),this.updateEgress.close(new qz("closed","ACP Session was destroyed")),this.availableCommandsTimer!==null)clearTimeout(this.availableCommandsTimer),this.availableCommandsTimer=null;this.taskStatusUnsubscribe?.(),this.taskStatusUnsubscribe=void 0;let Z=this.agent,J=this.runtime,H=this.pendingPromptCompletion,Y=this.pendingUserShellCompletion,X=this.pendingSideConversationCompletion;this.agent=null,this.runtime=null;let Q,W=async(j)=>{try{await j()}catch(L){Q??=L}};if(await W(()=>this.cancel()),H)await W(()=>H);if(Y)await W(()=>Y);if(X)await W(()=>X);if(z&&H&&J)await W(()=>J.discardPendingInput());if(Z)await W(()=>Z.destroy());if(J)await W(()=>J.dispose());if(await W(()=>x.destroySession(this.id)),V.debug(`[AcpSession ${this.id}] Destroyed`),Q!==void 0)throw Q}resolvePrompt(z){let Z=[],J=[],H=0,Y=0,X=0,Q=(L)=>{if(J.length>0)J.push({type:"text",text:`
|
|
13
|
-
`}),X+=1;if(J.push(L),L.type==="text")X+=L.text.length};for(let L of z)if(L.type==="text")Z.push(L.text),Q({type:"text",text:L.text});else if(L.type==="image"){let F=`data:${L.mimeType};base64,${L.data}`;H+=1,Y+=F.length,Z.push(`[Image: ${L.mimeType}]`),Q({type:"image_url",image_url:{url:F}})}else if(L.type==="resource"){let F=L.resource;if("text"in F){let B=`<file path="${F.uri}">
|
|
14
|
-
${F.text}
|
|
15
|
-
</file>`;Z.push(B),Q({type:"text",text:B})}}else if(L.type==="resource_link"){let F=`[Resource: ${L.uri}]`;Z.push(F),Q({type:"text",text:F})}if(H>f)throw Error(`ACP prompt contains more than ${f} images`);if(Y>zz)throw Error("ACP prompt images exceed the 5 MiB limit");if(X>u)throw Error(`ACP prompt text exceeds ${u} characters`);if(Buffer.byteLength(Z.join(`
|
|
16
|
-
`),"utf8")>g)throw Error(`ACP prompt text exceeds ${g} bytes`);let j=Z.join(`
|
|
17
|
-
`);return{content:H>0?J:j,displayText:j}}canSendUpdates(){return!this.destroyed&&!this.connection.signal.aborted&&!this.updateEgress.stats().closed}async sendUpdateAndWait(z){if(!this.canSendUpdates())return!1;let Z=this.updateEgress.offer({sessionId:this.id,update:z});if(!Z.accepted)return!1;try{return await Z.completion,this.canSendUpdates()}catch{return!1}}goalSessionUpdate(z){return{sessionUpdate:"session_info_update",updatedAt:z.updatedAt,_meta:{"blade/goal":{goalId:z.goalId,status:z.status,verificationAttempt:z.completionVerification?.attempt,verificationStatus:z.completionVerification?.status,verifierSessionId:z.completionVerification?.verifierSessionId,verificationEvidenceSha256:z.completionVerification?.evidenceSha256,verificationSummary:z.completionVerification?.summary,verificationStallCount:z.verificationStall?.consecutiveCount}}}}sendUpdate(z){if(!this.canSendUpdates())return;this.updateEgress.offer({sessionId:this.id,update:z})}async flushUpdates(){if(!this.canSendUpdates())return!1;try{return await this.updateEgress.flush(),this.canSendUpdates()}catch{return!1}}handleUpdateEgressFailure(z){if(this.destroyed)return;V.warn(`[AcpSession ${this.id}] Update egress closed: kind=${z.kind}`),this.clearPendingResumeRequest(),this.pendingPrompt?.abort("acp-egress-failed"),this.pendingUserShell?.abort("acp-egress-failed"),this.pendingSideConversation?.abort("acp-egress-failed")}sendPlanUpdate(z){let Z=z.map((J)=>({content:J.subject,priority:J.priority,status:J.status}));V.debug(`[AcpSession ${this.id}] Sending plan update with ${Z.length} entries`),this.sendUpdate({sessionUpdate:"plan",entries:Z})}async requestPermission(z){let Z=this.pendingPrompt?.signal;if(z.type==="askUserQuestion")return this.requestUserQuestions(z,Z);if(z.type==="mcpElicitation")return this.requestMcpElicitation(z,Z);let J=z.kind?.toLowerCase()||"execute";if(z.type!=="mcpSampling"&&this.shouldAutoApprove(J))return V.debug(`[AcpSession ${this.id}] Auto-approving ${J} in mode: ${this.mode}`),{approved:!0};if(this.mode==="plan"&&(J==="write"||J==="execute"))return V.debug(`[AcpSession ${this.id}] Rejecting ${J} in plan mode`),{approved:!1,reason:"Write and execute operations are not allowed in Plan mode"};try{let H=C(),Y=[];if(z.message)Y.push({type:"content",content:{type:"text",text:z.message}});if(z.details)Y.push({type:"content",content:{type:"text",text:z.details}});if(z.risks&&z.risks.length>0)Y.push({type:"content",content:{type:"text",text:`Risks:
|
|
18
|
-
- ${z.risks.join(`
|
|
19
|
-
- `)}`}});let X=this.mapToolKind(J),Q={sessionId:this.id,options:z.type==="mcpSampling"?[{optionId:"allow_once",name:"Allow this sampling request",kind:"allow_once"},{optionId:"reject_once",name:"Deny",kind:"reject_once"}]:[{optionId:"allow_once",name:"Allow once",kind:"allow_once"},{optionId:"allow_always",name:"Always allow",kind:"allow_always"},{optionId:"reject_once",name:"Deny once",kind:"reject_once"},{optionId:"reject_always",name:"Always deny",kind:"reject_always"}],toolCall:{toolCallId:H,status:"pending",title:z.title||"Permission Required",content:Y,kind:X}},W=await this.waitForClientInteraction(this.connection.requestPermission(Q),Z);if(!W)return{approved:!1,reason:c};let j=W.outcome;if(j.outcome==="cancelled")return{approved:!1,reason:"User cancelled the permission request"};let L=j.optionId;if(L==="allow_always")return{approved:!0,scope:"project"};if(L==="reject_always")return{approved:!1,scope:"project",reason:"User permanently denied the permission request"};let F=L==="allow_once";return{approved:F,scope:"once",reason:F?void 0:"User denied the operation"}}catch(H){return V.warn(`[AcpSession ${this.id}] Permission request failed:`,H),{approved:!1,reason:"Permission request failed"}}}async requestUserQuestions(z,Z){let J=z.questions??[];if(J.length===0)return{approved:!1,reason:"No structured questions were provided"};if(J.some((Y)=>Y.multiSelect))return{approved:!1,reason:"ACP does not support multi-select question responses"};let H={};try{for(let[Y,X]of J.entries()){let Q=X.options.map((F,B)=>`answer:${Y}:${B}`),W=`answer:${Y}:cancel`,j=await this.waitForClientInteraction(this.connection.requestPermission({sessionId:this.id,options:[...X.options.map((F,B)=>({optionId:Q[B],name:F.label,kind:"allow_once"})),{optionId:W,name:"Cancel",kind:"reject_once"}],toolCall:{toolCallId:C(),status:"pending",title:X.header,kind:"think",content:[{type:"content",content:{type:"text",text:[X.question,...X.options.map((F)=>`${F.label}: ${F.description}`)].join(`
|
|
20
|
-
`)}}]}}),Z);if(!j)return{approved:!1,reason:c};if(j.outcome.outcome!=="selected")return{approved:!1,reason:"User cancelled the question prompt"};let L=Q.indexOf(j.outcome.optionId);if(L<0)return{approved:!1,reason:"User cancelled the question prompt"};H[X.header]=X.options[L].label}return{approved:!0,answers:H}}catch(Y){return V.warn(`[AcpSession ${this.id}] Question request failed:`,Y),{approved:!1,reason:"Question request failed"}}}async requestMcpElicitation(z,Z){let J=z.mcpElicitation;if(!J)return{approved:!1,reason:"MCP elicitation details are missing",elicitation:{action:"cancel"}};try{if(J.mode==="url"){let Y=await this.requestElicitationChoice("MCP external authorization",[J.message,`Server: ${J.serverName}`,`Domain: ${J.domain??"unknown"}`,`URL: ${J.url??""}`,"Open this URL yourself only if you trust the MCP server."].join(`
|
|
21
|
-
`),[{id:"accept",label:"I will open this URL"},{id:"decline",label:"Decline"}],Z);if(Y==="accept")return{approved:!0,elicitation:{action:"accept"}};return{approved:!1,reason:Y==="decline"?"User declined URL":"User cancelled",elicitation:{action:Y==="decline"?"decline":"cancel"}}}let H=Object.create(null);for(let Y of J.fields??[]){let X=await this.collectAcpElicitationField(Y,Z);if(X.cancelled)return{approved:!1,reason:X.reason,elicitation:{action:"cancel"}};if(X.value!==void 0)H[Y.name]=X.value}return{approved:!0,elicitation:{action:"accept",content:H}}}catch(H){return V.warn(`[AcpSession ${this.id}] MCP elicitation failed:`,H),{approved:!1,reason:"MCP elicitation failed",elicitation:{action:"cancel"}}}}async collectAcpElicitationField(z,Z){if(z.type==="select"||z.type==="boolean"){let J=z.type==="boolean"?[{id:"true",label:"Yes",value:!0},{id:"false",label:"No",value:!1}]:(z.options??[]).map((X,Q)=>({id:`option:${Q}`,label:X.label,value:X.value})),H=await this.requestElicitationChoice(z.title,[z.description,z.required?"Required":"Optional"].filter(Boolean).join(`
|
|
22
|
-
`),[...J.map((X)=>({id:X.id,label:X.label})),...!z.required?[{id:"skip",label:"Skip"}]:[]],Z);if(H==="skip")return{cancelled:!1};let Y=J.find((X)=>X.id===H);if(!Y)return{cancelled:!0,reason:"User cancelled MCP elicitation"};return{cancelled:!1,value:Y.value}}if(z.defaultValue!==void 0){let J=await this.requestElicitationChoice(z.title,[z.description,`ACP cannot collect ${z.type} input. Use the server default: ${String(z.defaultValue)}?`].filter(Boolean).join(`
|
|
23
|
-
`),[{id:"default",label:"Use default"},...!z.required?[{id:"skip",label:"Skip"}]:[]],Z);if(J==="default")return{cancelled:!1,value:z.defaultValue};if(J==="skip")return{cancelled:!1};return{cancelled:!0,reason:"User cancelled MCP elicitation"}}if(!z.required)return{cancelled:!1};return{cancelled:!0,reason:`ACP cannot collect required ${z.type} field "${z.name}"`}}async requestElicitationChoice(z,Z,J,H){let Y=await this.waitForClientInteraction(this.connection.requestPermission({sessionId:this.id,options:[...J.map((X)=>({optionId:X.id,name:X.label,kind:"allow_once"})),{optionId:"cancel",name:"Cancel",kind:"reject_once"}],toolCall:{toolCallId:C(),status:"pending",title:z,kind:"think",content:[{type:"content",content:{type:"text",text:Z}}]}}),H);return Y?.outcome.outcome==="selected"?Y.outcome.optionId:void 0}async waitForClientInteraction(z,Z){if(!Z)return z;if(Z.aborted)return;return new Promise((J,H)=>{let Y=!1,X=(W)=>{if(Y)return;Y=!0,Z.removeEventListener("abort",Q),W()},Q=()=>X(()=>J(void 0));if(Z.addEventListener("abort",Q,{once:!0}),Z.aborted)Q();z.then((W)=>X(()=>J(W)),(W)=>X(()=>H(W)))})}mapToolKind(z){return{readonly:"read",write:"edit",execute:"execute",read:"read",edit:"edit",delete:"delete",move:"move",search:"search",think:"think",fetch:"fetch"}[z||""]||"other"}}var N=y("Agent");class v{connection;sessions=new Map;sessionLoadQueues=new Map;runtimeResidencyValue;clientCapabilities;destroyed=!1;destroyPromise;constructor(z){this.connection=z}get runtimeResidency(){if(!this.runtimeResidencyValue){let z=Iz();this.runtimeResidencyValue=new mz({maxResident:z?.maxResidentSessionRuntimes??kz,idleMs:z?.sessionRuntimeIdleMs??Mz})}return this.runtimeResidencyValue}async reserveSessionRuntime(z){try{return await this.runtimeResidency.reserve(z,{surface:"acp",allowEviction:!1})}catch(Z){if(Z instanceof pz)throw $J.internalError({resource:Z.resource,limit:Z.limit,retryable:Z.retryable},Z.message);throw Z}}async initialize(z){return N.info("[BladeAgent] Initializing ACP connection"),N.debug(`[BladeAgent] Client capabilities: ${JSON.stringify(z.clientCapabilities)}`),this.clientCapabilities=z.clientCapabilities,await Cz(),{protocolVersion:ZJ,agentCapabilities:{loadSession:!0,sessionCapabilities:{list:{},fork:{},close:{}},promptCapabilities:{image:!0,audio:!1,embeddedContext:!0},mcpCapabilities:{http:!0,sse:!0}}}}async authenticate(z){return}async newSession(z){this.assertNotDestroyed();let Z=d("acp"),J=await this.reserveSessionRuntime(Z),H=z.cwd||hz(),Y=z._meta?.["blade/taskIsolation"],X=Y==="local"||Y==="worktree"?Y:void 0,Q=z._meta?.["blade/taskPrompt"],W;try{let j=X?await cz.createSessionTask({sessionId:Z,prompt:typeof Q==="string"&&Q.trim()?Q:"ACP task session",sourceProjectPath:H,isolation:X}):void 0,L=j?.metadata.projectPath??H;return N.info(`[BladeAgent] Creating new session: ${Z}`),N.debug(`[BladeAgent] Session cwd: ${L}`),W=new b(Z,L,this.connection,this.clientCapabilities,{mcpServers:z.mcpServers,...j?.taskWorktree?{taskWorktree:j.taskWorktree}:{},...j?.metadata.taskIsolation?{taskIsolation:j.metadata.taskIsolation}:{}}),await W.initialize(),this.assertNotDestroyed(),this.commitSession(Z,W,J),N.info(`[BladeAgent] Session ${Z} created, scheduling available commands update`),W.sendAvailableCommandsDelayed(),this.buildChildSessionResponse(Z,j?.metadata,W.getModelConfiguration())}catch(j){throw J.cancel(),await W?.destroy().catch(()=>{return}),j}}async listSessions(z){if(z.cwd!=null&&!Ez.isAbsolute(z.cwd))throw Error("ACP session list cwd must be absolute");let Z=await G.listSessionPage({cwd:z.cwd??void 0,cursor:z.cursor??void 0,limit:50,includeSubagents:!1});return{sessions:Z.sessions.map((J)=>({sessionId:J.sessionId,cwd:J.projectPath,title:J.title??null,updatedAt:J.lastMessageTime,_meta:{"blade/taskStatus":J.taskStatus,...J.taskStatusReason?{"blade/taskStatusReason":J.taskStatusReason}:{},...J.taskFailure?{"blade/taskFailure":J.taskFailure}:{},...J.taskStartedAt?{"blade/taskStartedAt":J.taskStartedAt}:{},...J.taskCompletedAt?{"blade/taskCompletedAt":J.taskCompletedAt}:{},...J.taskModelId?{"blade/taskModelId":J.taskModelId}:{},...J.taskRetryAvailable?{"blade/taskRetryAvailable":!0}:{},...J.taskRetriedFrom?{"blade/taskRetriedFrom":J.taskRetriedFrom}:{},...J.taskDelivery?{"blade/taskDelivery":J.taskDelivery}:{},...J.taskIsolation?{"blade/taskIsolation":J.taskIsolation}:{},...J.taskSourceProjectPath?{"blade/taskSourceProjectPath":J.taskSourceProjectPath}:{},...J.taskWorktreeBranch?{"blade/taskWorktreeBranch":J.taskWorktreeBranch}:{},...J.taskBaseCommit?{"blade/taskBaseCommit":J.taskBaseCommit}:{},...J.taskDiffStat?{"blade/taskDiffStat":J.taskDiffStat}:{},...J.taskQueuePosition?{"blade/taskQueuePosition":J.taskQueuePosition}:{},...J.taskQueueDepth!==void 0?{"blade/taskQueueDepth":J.taskQueueDepth}:{},...J.taskConcurrencyLimit!==void 0?{"blade/taskConcurrencyLimit":J.taskConcurrencyLimit}:{}}})),nextCursor:Z.nextCursor}}async unstable_forkSession(z){if(this.assertNotDestroyed(),!Ez.isAbsolute(z.cwd))throw Error("ACP session fork cwd must be absolute");let Z=d("fork"),J=await this.reserveSessionRuntime(Z),H;try{let Y=await G.forkSession(z.sessionId,{sourceProjectPath:z.cwd,targetProjectPath:z.cwd,newSessionId:Z});return this.assertNotDestroyed(),H=new b(Y.sessionId,z.cwd,this.connection,this.clientCapabilities,{initialMessages:Y.messages,permissionMode:Y.metadata.permissionMode,mcpServers:z.mcpServers}),await H.initialize(),this.assertNotDestroyed(),this.commitSession(Y.sessionId,H,J),H.sendAvailableCommandsDelayed(),this.buildChildSessionResponse(Y.sessionId,Y.metadata,H.getModelConfiguration())}catch(Y){throw J.cancel(),await H?.destroy().catch(()=>{return}),Y}}async loadSession(z){this.assertNotDestroyed(),N.info(`[BladeAgent] Loading session: ${z.sessionId}`);let J=(this.sessionLoadQueues.get(z.sessionId)??Promise.resolve()).then(()=>this.replaceSession(z)),H=J.then(()=>{return},()=>{return});this.sessionLoadQueues.set(z.sessionId,H);try{return await J}finally{if(this.sessionLoadQueues.get(z.sessionId)===H)this.sessionLoadQueues.delete(z.sessionId)}}async replaceSession(z){this.assertNotDestroyed(),await G.assertSessionWritable(z.sessionId,z.cwd),await this.closeResidentSession(z.sessionId);let Z=await this.reserveSessionRuntime(z.sessionId),J;try{let[H,Y]=await Promise.all([G.loadSession(z.sessionId,z.cwd),G.findSessionMetadata(z.sessionId,z.cwd)]);if(!Y)throw Error(`Session not found: ${z.sessionId}`);return J=new b(z.sessionId,z.cwd,this.connection,this.clientCapabilities,{initialMessages:H,permissionMode:Y.permissionMode,mcpServers:z.mcpServers}),await J.initialize(),await J.replayHistory(),this.assertNotDestroyed(),this.commitSession(z.sessionId,J,Z),J.sendAvailableCommandsDelayed(),this.buildSessionSetup(J.getModelConfiguration(),J.getMode())}catch(H){throw Z.cancel(),await J?.destroy().catch(()=>{return}),H}}commitSession(z,Z,J){let H=J.commit({key:z,surface:"acp",value:Z,canEvict:()=>Z.isIdleForResidency(),dispose:async()=>{if(this.sessions.get(z)===Z)this.sessions.delete(z);await Z.destroy()}});this.sessions.set(z,Z),H.release()}async closeResidentSession(z,Z={}){let J=this.sessions.get(z);if(!J)return;let H=this.runtimeResidency.owns(z,J),Y;try{await J.destroy(Z)}catch(Q){Y=Q}let X=await this.runtimeResidency.forget(z,J);if(this.sessions.get(z)===J)this.sessions.delete(z);if(H&&!X&&Y===void 0)throw Error(`ACP Session is still active: ${z}`);if(Y!==void 0)throw Y}buildChildSessionResponse(z,Z,J){return{sessionId:z,...this.buildSessionSetup(J,Z?.permissionMode==="autoEdit"?"auto-edit":Z?.permissionMode),...Z?{_meta:{"blade/taskIsolation":Z.taskIsolation,"blade/taskSourceProjectPath":Z.taskSourceProjectPath,"blade/taskProjectPath":Z.projectPath,...Z.taskModelId?{"blade/taskModelId":Z.taskModelId}:{},...Z.taskRetryAvailable?{"blade/taskRetryAvailable":!0}:{},...Z.taskRetriedFrom?{"blade/taskRetriedFrom":Z.taskRetriedFrom}:{},...Z.taskDelivery?{"blade/taskDelivery":Z.taskDelivery}:{},...Z.taskWorktreeBranch?{"blade/taskWorktreeBranch":Z.taskWorktreeBranch}:{},...Z.taskBaseCommit?{"blade/taskBaseCommit":Z.taskBaseCommit}:{}}}:{}}}assertNotDestroyed(){if(this.destroyed)throw Error("BladeAgent is destroyed")}getRuntimeResidencyStats(){return this.runtimeResidency.getStats()}buildSessionSetup(z,Z="default"){let J=z?.models??[],H=(z?.currentModelId&&J.some((Q)=>Q.id===z.currentModelId)?z.currentModelId:void 0)??J[0]?.id,Y=[{id:"default",name:"Default",description:"Ask for confirmation before all file edits and commands"},{id:"auto-edit",name:"Auto Edit",description:"Auto-approve file edits, ask for shell commands"},{id:"yolo",name:"Full Auto",description:"Auto-approve everything without confirmation"},{id:"plan",name:"Plan Only",description:"Read-only mode, no file changes or commands"}],X=[];if(J.length>0)X.push({type:"select",id:"model",name:"Model",description:"Active language model",category:"model",currentValue:H,options:J.map((Q)=>({value:Q.id,name:Q.displayName??Q.model,description:`${z?.modelProviders[Q.provider]?.name??Q.provider} · ${Q.model}`}))});if(z?.reasoning)X.push({type:"select",id:"reasoning_effort",name:"Reasoning effort",description:"Session-owned model reasoning intensity",category:"model",currentValue:z.reasoning.selection,options:[{value:"auto",name:"Auto",description:`Resolve near high for this model (currently ${z.reasoning.effective})`},...z.reasoning.supported.map((Q)=>({value:Q,name:Q[0].toUpperCase()+Q.slice(1),description:Q==="off"?"Disable model reasoning":`Use ${Q} reasoning effort`}))]});if(z?.serviceTier)X.push({type:"select",id:"service_tier",name:"Service tier",description:"Session-owned provider latency and pricing tier",category:"model",currentValue:z.serviceTier.selection,options:[{value:"auto",name:"Auto",description:"Use the provider or model default tier"},...z.serviceTier.supported.map((Q)=>({value:Q,name:Q[0].toUpperCase()+Q.slice(1),description:Q==="fast"?"Use the provider priority tier":Q==="flex"?"Use the lower-cost flexible tier":"Use the standard provider tier"}))]});if(z?.responseVerbosity)X.push({type:"select",id:"response_verbosity",name:"Response verbosity",description:"Session-owned model response detail",category:"model",currentValue:z.responseVerbosity.selection,options:[{value:"auto",name:"Auto",description:"Use the provider or model default verbosity"},...z.responseVerbosity.supported.map((Q)=>({value:Q,name:Q[0].toUpperCase()+Q.slice(1),description:`Use ${Q} response verbosity`}))]});if(z?.communicationStyle)X.push({type:"select",id:"communication_style",name:"Communication style",description:"Session-owned tone and explanatory framing",category:"model",currentValue:z.communicationStyle.selection,options:z.communicationStyle.supported.map((Q)=>({value:Q.id,name:Q.name,description:`${Q.description} · ${Q.source}`}))});return{modes:{availableModes:Y,currentModeId:Z},configOptions:X.length>0?X:void 0}}async closeSession(z){this.assertNotDestroyed();let J=(this.sessionLoadQueues.get(z.sessionId)??Promise.resolve()).then(()=>this.closeResidentSession(z.sessionId,{discardPendingInput:!0})),H=J.then(()=>{return},()=>{return});this.sessionLoadQueues.set(z.sessionId,H);try{await J}finally{if(this.sessionLoadQueues.get(z.sessionId)===H)this.sessionLoadQueues.delete(z.sessionId)}}async prompt(z){let Z=this.runtimeResidency.acquire(z.sessionId);if(!Z)throw Error(`Session not found: ${z.sessionId}`);try{return await Z.value.prompt(z)}finally{Z.release()}}async cancel(z){N.info(`[BladeAgent] Cancel notification received for session: ${z.sessionId}`);let Z=this.runtimeResidency.acquire(z.sessionId);if(Z){N.info("[BladeAgent] Found session, calling session.cancel()");try{Z.value.cancel()}finally{Z.release()}}else N.warn(`[BladeAgent] Session not found for cancel: ${z.sessionId}`)}async setSessionMode(z){N.info(`[BladeAgent] Setting session mode: ${z.modeId}`);let Z=this.runtimeResidency.acquire(z.sessionId);if(Z)try{await Z.value.setMode(z.modeId)}finally{Z.release()}return{}}async setSessionConfigOption(z){let Z=this.runtimeResidency.acquire(z.sessionId);if(!Z)throw Error(`Session not found: ${z.sessionId}`);try{let J=Z.value;if(z.configId==="model"&&"value"in z&&typeof z.value==="string")N.info(`[BladeAgent] Setting session model: ${z.value}`),await J.setModel(z.value);else if(z.configId==="reasoning_effort"&&"value"in z&&fz(z.value))N.info(`[BladeAgent] Setting reasoning effort: ${z.value}`),await J.setReasoningEffort(z.value);else if(z.configId==="service_tier"&&"value"in z&&yz(z.value))N.info(`[BladeAgent] Setting service tier: ${z.value}`),await J.setServiceTier(z.value);else if(z.configId==="response_verbosity"&&"value"in z&&Sz(z.value))N.info(`[BladeAgent] Setting response verbosity: ${z.value}`),await J.setResponseVerbosity(z.value);else if(z.configId==="communication_style"&&"value"in z&&uz(z.value))N.info(`[BladeAgent] Setting communication style: ${z.value}`),await J.setCommunicationStyle(z.value);else throw Error(`Invalid session config option: ${z.configId}`);return{configOptions:this.buildSessionSetup(J.getModelConfiguration(),J.getMode()).configOptions??[]}}finally{Z.release()}}destroy(){if(this.destroyPromise)return this.destroyPromise;return this.destroyPromise=this.destroyOwnedResources(),this.destroyPromise}async destroyOwnedResources(){this.destroyed=!0,await Promise.all([...this.sessionLoadQueues.values()]),this.sessionLoadQueues.clear();let z;for(let Z of[...this.sessions.keys()])try{await this.closeResidentSession(Z)}catch(J){z??=J}try{await this.runtimeResidency.disposeAll()}catch(Z){z??=Z}this.sessions.clear();try{await gz.getInstance().disconnectAll()}catch(Z){z??=Z}if(z!==void 0)throw z}}async function QZ(){let z=WJ.toWeb(process.stdout),Z=QJ.toWeb(process.stdin),J=k.ndJsonStream(z,Z),H,Y=new k.AgentSideConnection((Q)=>{return H=new v(Q),H},J),X=dz(async()=>{await H?.destroy()});try{await Y.closed}finally{X(),await H?.destroy()}}export{QZ as runAcpIntegration};
|
package/dist/chunk-1x13nzwe.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{qe as a,re as b,se as c}from"./chunk-szdz1jmj.js";import"./chunk-j2dyprdy.js";import"./chunk-5y38cfk9.js";import"./chunk-v508x7cg.js";import"./chunk-dg0d3303.js";import"./chunk-41ympwz1.js";import"./chunk-139frcak.js";import"./chunk-sdbbyagy.js";import"./chunk-f3426b1c.js";import"./chunk-c475tfqf.js";import"./chunk-0hr050ck.js";import"./chunk-q69fzq4y.js";import"./chunk-n7mzxa8h.js";import"./chunk-s10pmnrd.js";import"./chunk-9p20hhs0.js";import"./chunk-4bwr3rcj.js";import"./chunk-wyhyw9rq.js";import"./chunk-rvk9r2cm.js";import"./chunk-tgdhsm5t.js";import"./chunk-fhfzdyba.js";export{a as validatePermissions,c as validateOutput,b as loadConfiguration};
|
package/dist/chunk-25n07173.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{h as a,i as b,j as c,k as d,l as e}from"./chunk-2mck84gx.js";import"./chunk-4bwr3rcj.js";import"./chunk-fhfzdyba.js";export{b as setSkipUntilVersion,d as performUpgrade,c as getUpgradeCommand,e as checkVersionOnStartup,a as checkVersion};
|
package/dist/chunk-3vqdyer3.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{$e as q,Le as a,Me as b,Ne as c,Oe as d,Pe as e,Qe as f,Re as g,Se as h,Te as i,Ue as j,Ve as k,We as l,Xe as m,Ye as n,Ze as o,_e as p}from"./chunk-5y38cfk9.js";import"./chunk-v508x7cg.js";import"./chunk-dg0d3303.js";import"./chunk-139frcak.js";import"./chunk-sdbbyagy.js";import"./chunk-f3426b1c.js";import"./chunk-c475tfqf.js";import"./chunk-0hr050ck.js";import"./chunk-q69fzq4y.js";import"./chunk-n7mzxa8h.js";import"./chunk-s10pmnrd.js";import"./chunk-9p20hhs0.js";import"./chunk-4bwr3rcj.js";import"./chunk-wyhyw9rq.js";import"./chunk-rvk9r2cm.js";import"./chunk-tgdhsm5t.js";import"./chunk-fhfzdyba.js";export{a as vanillaStore,c as sessionActions,l as getThinkingModeEnabled,b as getState,n as getServiceTier,o as getResponseVerbosity,m as getReasoningEffort,j as getModelById,e as getMessages,k as getMcpServers,i as getCurrentModel,f as getConfig,p as getCommunicationStyle,h as getAllModels,g as ensureStoreInitialized,q as configActions,d as appActions};
|
package/dist/chunk-4z79mh8y.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{oe as a,pe as b}from"./chunk-djqbqaxn.js";import"./chunk-4bwr3rcj.js";import"./chunk-fhfzdyba.js";export{a as globalOptions,b as cliConfig};
|
package/dist/chunk-9dba1pyq.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{Nf as a,Of as b,Pf as c,Qf as d,Rf as e,Sf as f,Tf as g,Uf as h,Vf as i,Wf as j}from"./chunk-151cz9k4.js";import"./chunk-kf7whgr7.js";import"./chunk-fva7jnjy.js";import"./chunk-41ympwz1.js";import"./chunk-6j482w6k.js";import"./chunk-41cg66y0.js";import"./chunk-139frcak.js";import"./chunk-sdbbyagy.js";import"./chunk-f3426b1c.js";import"./chunk-c475tfqf.js";import"./chunk-0hr050ck.js";import"./chunk-q69fzq4y.js";import"./chunk-n7mzxa8h.js";import"./chunk-s10pmnrd.js";import"./chunk-9p20hhs0.js";import"./chunk-4bwr3rcj.js";import"./chunk-wyhyw9rq.js";import"./chunk-rvk9r2cm.js";import"./chunk-tgdhsm5t.js";import"./chunk-fhfzdyba.js";export{g as withWorkspaceAgentResources,i as snapshotWorkspaceAgentResources,f as resolveWorkspaceAgentResources,j as resetWorkspaceAgentResources,d as refreshWorkspaceCommunicationStyles,h as getWorkspaceAgentResourceCacheStats,e as configureInvocationPluginDirs,c as WorkspaceAgentResourceCapacityError,a as MAX_RESIDENT_WORKSPACE_AGENT_RESOURCES,b as MAX_ACTIVE_WORKSPACE_AGENT_RESOURCES};
|