blade-code 0.10.198 → 0.10.199
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-m7cv44cg.js → chunk-0wrz9qv8.js} +1 -1
- package/dist/{chunk-pxmskd21.js → chunk-1nt1vdf1.js} +1 -1
- package/dist/{chunk-r2ev8kdg.js → chunk-2kx9ygzc.js} +1 -1
- package/dist/{chunk-w2xgdqvw.js → chunk-5ht22rny.js} +1 -1
- package/dist/{chunk-v2bcvfch.js → chunk-6ey3qfx1.js} +1 -1
- package/dist/{chunk-spsnc7ey.js → chunk-6fwpq2xw.js} +1 -1
- package/dist/{chunk-pfjg8bjg.js → chunk-6qp15s2m.js} +1 -1
- package/dist/{chunk-afq14p8m.js → chunk-76zhkyhk.js} +1 -1
- package/dist/{chunk-p6g53dbp.js → chunk-8pytaed9.js} +1 -1
- package/dist/{chunk-vd58pp9k.js → chunk-9e91xz28.js} +1 -1
- package/dist/{chunk-vw2be560.js → chunk-9vvky5ma.js} +1 -1
- package/dist/{chunk-mrft8qep.js → chunk-ae3mp8vh.js} +1 -1
- package/dist/chunk-as9s05vj.js +1 -0
- package/dist/chunk-b6c2yk3m.js +1 -0
- package/dist/{chunk-evq5ke3s.js → chunk-c4zs4014.js} +1 -1
- package/dist/{chunk-zh4w88j6.js → chunk-d4agyayp.js} +1 -1
- package/dist/{chunk-7m1bf6zd.js → chunk-d86vygx0.js} +1 -1
- package/dist/{chunk-vnbyb9dq.js → chunk-f1x80zky.js} +1 -1
- package/dist/{chunk-bh3e2gt1.js → chunk-fdtpv5zn.js} +1 -1
- package/dist/{chunk-hhey2zgy.js → chunk-g12ar2df.js} +1 -1
- package/dist/{chunk-pq9v80gg.js → chunk-h1e37bta.js} +1 -1
- package/dist/{chunk-dzz3mzg1.js → chunk-hn2d9why.js} +1 -1
- package/dist/{chunk-n87apqe7.js → chunk-k28sxv3p.js} +1 -1
- package/dist/{chunk-0hzq6sr3.js → chunk-kj03348q.js} +1 -1
- package/dist/{chunk-wernns90.js → chunk-ntazpz2y.js} +1 -1
- package/dist/{chunk-hasgf62t.js → chunk-nxtj07c4.js} +1 -1
- package/dist/{chunk-pbw10pjv.js → chunk-pq98yvgq.js} +2 -2
- package/dist/{chunk-0h301azx.js → chunk-q4adhq22.js} +1 -1
- package/dist/{chunk-x5f2d1n2.js → chunk-rf3eeens.js} +1 -1
- package/dist/{chunk-4bfndh72.js → chunk-rt5bfj3z.js} +1 -1
- package/dist/{chunk-25ma8vb3.js → chunk-rytpfm4a.js} +1 -1
- package/dist/{chunk-sqrhdczm.js → chunk-s9g7t23a.js} +1 -1
- package/dist/{chunk-6d9d2cyk.js → chunk-sp02zbss.js} +1 -1
- package/dist/{chunk-jscwac0k.js → chunk-tf7sdr77.js} +1 -1
- package/dist/{chunk-yc59atrw.js → chunk-wmcrvqne.js} +1 -1
- package/dist/{chunk-0qfm5awe.js → chunk-wzxxjj1a.js} +3 -3
- package/dist/{chunk-s8cx6pzp.js → chunk-z9jxsh6w.js} +1 -1
- package/dist/{chunk-g88adq1a.js → chunk-zmbknsyr.js} +1 -1
- package/package.json +1 -1
- package/dist/chunk-bp1n4k48.js +0 -1
- package/dist/chunk-ksf9bywt.js +0 -1
package/dist/blade.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{Af as W}from"./chunk-
|
|
2
|
+
import{Af as W}from"./chunk-h1e37bta.js";import{Df as F,Ef as M}from"./chunk-p0wyhp5a.js";import"./chunk-d86vygx0.js";import"./chunk-v508x7cg.js";import"./chunk-5yyp6njq.js";import"./chunk-f1x80zky.js";import"./chunk-ys8gysg8.js";import"./chunk-6qp15s2m.js";import"./chunk-qpmvp4q2.js";import"./chunk-tm3789m3.js";import{bj as N,cj as B}from"./chunk-qdbbke8f.js";import"./chunk-wezr6wfq.js";import{Dj as T}from"./chunk-rmfzym94.js";import"./chunk-j89qk7bp.js";import"./chunk-0eajnhrj.js";import"./chunk-rytpfm4a.js";import"./chunk-ggdgk3gy.js";import"./chunk-ky592ay9.js";import"./chunk-n52n2w5v.js";import{Nk as J}from"./chunk-cjfb4kjp.js";import p from"node:path";var E=process.argv.slice(2),I=c(E),u=I!==null;if(I!==null)T.setGlobalDebug(I);function c(Q){for(let Y=0;Y<Q.length;Y+=1){let U=Q[Y];if(U==="--debug"||U==="-d"){let X=Q[Y+1];return X&&!X.startsWith("-")?X:!0}if(U.startsWith("--debug="))return U.slice(8)||!0}return null}function m(Q){return Q.length===1&&(Q[0]==="--version"||Q[0]==="-V")}function q(Q,...Y){return Q.some((U)=>Y.some((X)=>U===X||U.startsWith(`${X}=`)))}function t(Q,...Y){let U=[];for(let X=0;X<Q.length;X+=1){let G=Q[X],z=Y.find(($)=>G.startsWith(`${$}=`));if(z){let $=G.slice(z.length+1);if($)U.push($);continue}if(Y.includes(G)){let $=Q[X+1];if($&&!$.startsWith("-"))U.push($),X+=1}}return U}async function l(){if(m(E)){let{getVersion:K}=await import("./chunk-sp02zbss.js");console.log(K());return}let Q=process.cwd(),Y=F(Q);M(Y),N(B());let U=t(E,"--plugin-dir","--pluginDir");if(U.length>0){let{configureInvocationPluginDirs:K}=await import("./chunk-fdtpv5zn.js");K(U.map((Z)=>p.resolve(Q,Z)))}if(q(E,"--trust-workspace","--trustWorkspace")){let{WorkspaceTrustService:K}=await import("./chunk-6ax5dpd3.js");await K.getInstance().trust(B())}if(process.getuid&&process.getuid()===0){let K=!!process.env.SUDO_USER,Z=!!process.env.BLADE_ALLOW_ROOT;if(K&&!Z)console.error(""),console.error("Error: 请不要使用 sudo 运行 blade"),console.error(""),console.error("原因:"),console.error(" 使用 sudo 会创建属于 root 的配置文件,"),console.error(" 导致普通用户无法访问。"),console.error(""),console.error("正确用法:"),console.error(" blade # 直接运行,不要加 sudo"),console.error(""),console.error("如果遇到权限错误,请运行:"),console.error(" sudo chown -R $USER:$USER ~/.blade/"),console.error(""),console.error("如果你确实需要以 root 运行(容器/CI),设置环境变量:"),console.error(" BLADE_ALLOW_ROOT=1 blade"),console.error(""),process.exit(1)}if(q(E,"--headless")){let{handleHeadlessMode:K}=await import("./chunk-9vvky5ma.js");if(await K())return}if(W(),q(E,"--print","-p")){let{handlePrintMode:K}=await import("./chunk-c4zs4014.js");if(await K())return}if(E.includes("--acp")){let{runAcpIntegration:K}=await import("./chunk-76zhkyhk.js");await K();return}let[{default:X},{hideBin:G},{cliConfig:z,globalOptions:$},{loadConfiguration:_,validateOutput:D,validatePermissions:R},{browserCommands:S},{doctorCommands:k},{installCommands:O},{mcpCommands:y},{projectsCommands:V},{scheduleCommands:b},{serveCommand:P},{updateCommands:x},{webCommand:A}]=await Promise.all([import("yargs"),import("yargs/helpers"),import("./chunk-as9s05vj.js"),import("./chunk-ae3mp8vh.js"),import("./chunk-wk869s65.js"),import("./chunk-pq98yvgq.js"),import("./chunk-0xf70s5c.js"),import("./chunk-k28sxv3p.js"),import("./chunk-x49bw41v.js"),import("./chunk-g383afnv.js"),import("./chunk-ntazpz2y.js"),import("./chunk-9e91xz28.js"),import("./chunk-5ht22rny.js")]),h=X(G(process.argv)).scriptName(z.scriptName).usage(z.usage).version(z.version).locale(z.locale).showHelpOnFail(z.showHelpOnFail).demandCommand(0,"").recommendCommands().strict(z.strict).parserConfiguration({"populate--":!0}).options($).middleware([_,R,D]).command(S).command(y).command(V).command(b).command(k).command(x).command(O).command(A).command(P).completion("completion",!1).help("help","Show help").alias("help","h").alias("version","V").fail((K,Z,L)=>{if(Z){if(console.error("An error occurred:"),console.error(Z.message),u&&Z.stack)console.error(`
|
|
3
3
|
Stack trace:`),console.error(Z.stack);else console.error(`
|
|
4
4
|
Run with --debug to show the stack trace.`);process.exit(1)}if(K)console.error("Error: Invalid arguments:"),console.error(K),console.error(`
|
|
5
|
-
Hint: Did you mean:`),L.showHelp(),process.exit(1)}).command("$0",!1,()=>{},async(K)=>{let Z=K._.slice(1),L=Z.length>0?Z.join(" "):void 0,f=import("./chunk-
|
|
5
|
+
Hint: Did you mean:`),L.showHelp(),process.exit(1)}).command("$0",!1,()=>{},async(K)=>{let Z=K._.slice(1),L=Z.length>0?Z.join(" "):void 0,f=import("./chunk-b6c2yk3m.js").then(({checkVersionOnStartup:v})=>v()),[{render:w},{createElement:j},{AppWrapper:C}]=await Promise.all([import("ink"),import("react"),import("./chunk-6fwpq2xw.js")]),H={...K,initialMessage:L,debug:K.debug,print:Boolean(K.print),versionCheckPromise:f};delete H._,delete H.$0,delete H.message,w(j(C,H),{patchConsole:!0,exitOnCtrlC:!1,alternateBuffer:!1})});try{await h.parse()}catch(K){console.error("Error: Parse error:",K),process.exit(1)}}if(J.main==J.module)l().catch(console.error);export{l as main};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{xc as G8}from"./chunk-fdr4fcrf.js";import{$d as R6,Ac as U$,Bc as A2,Cc as a1,Ec as j$,Fd as E2,Gd as L8,Hd as F8,Id as V6,Jd as JZ,Kd as O8,Ld as P8,Md as r1,Qd as rJ,Zd as u0,ae as t1,be as M6,ie as X1,ud as b2,wd as y2,xd as f2,yc as q$,yd as w6,zd as U6}from"./chunk-r2ev8kdg.js";import{ne as q8}from"./chunk-egss0m1x.js";import{Fe as f0,qe as q0,te as j2,ue as u$}from"./chunk-ztreczac.js";import{eg as p2}from"./chunk-5yyp6njq.js";import{fg as w8,gg as C0,hg as H8,ig as dJ,kg as i1,lg as T6,mg as cJ,ng as lJ,qg as iJ}from"./chunk-myvt7yjm.js";import{ch as K$,dh as n0,gh as U8}from"./chunk-kehgewqh.js";import{lh as a2,ph as Y2}from"./chunk-kkzznz4w.js";import{Ah as R$}from"./chunk-vnbyb9dq.js";import{Vi as x$}from"./chunk-qpmvp4q2.js";import{cj as j0}from"./chunk-qdbbke8f.js";import{Ej as S0}from"./chunk-rmfzym94.js";import{Yj as _2}from"./chunk-25ma8vb3.js";import{Ck as FJ,Dk as ZZ,Fk as O2,Kk as P2,Lk as N2,gk as F2,vk as w2,wk as U2,zk as H1}from"./chunk-n52n2w5v.js";import{Nk as lZ}from"./chunk-cjfb4kjp.js";function S$($){return $.role==="system"&&Array.isArray($.content)}function E$($){if($.role!=="system"||!$.metadata||Array.isArray($.metadata))return!1;return typeof $.metadata==="object"&&$.metadata.contextualProjectRules===!0}class C1{systemMessages;_contextualSystemMessages;_history;_pending=[];_contextRevision=0;context;constructor($,Z){this.context=$;let J=$.messages.find(S$);if(this._contextualSystemMessages=$.messages.filter(E$),J)this.systemMessages=[J,...this._contextualSystemMessages];else if(Z)this.systemMessages=[{role:"system",content:[{type:"text",text:Z,providerOptions:{anthropic:{cacheControl:{type:"ephemeral"}}}}]},...this._contextualSystemMessages];else this.systemMessages=[...this._contextualSystemMessages];this._history=$.messages.filter((W)=>!S$(W)&&!E$(W))}get historyLength(){return this._history.length}get history(){return this._history}get pending(){return this._pending}get contextRevision(){return this._contextRevision}toLLMMessages(){return[...this.systemMessages,...this._history,...this._pending]}getMessagesForLLM(){return this.toLLMMessages()}getHistory(){return this._history}appendPending($){this._pending.push($)}appendUser($){this._pending.push($)}appendAssistant($){this._pending.push($)}appendToolResult($){this._pending.push($)}appendContextualProjectInstructions($){if(!E$($))throw Error("Contextual project instructions require safe metadata");this._contextualSystemMessages.push($),this.systemMessages.push($)}syncContextualSystemMessages(){let $=this.systemMessages.filter(S$);this.systemMessages.splice(0,this.systemMessages.length,...$,...this._contextualSystemMessages)}appendControl($,Z){if($==="system")throw Error("Cannot append system control message via appendControl. Use constructor for root system prompt.");this._pending.push({...Z,metadata:{...Z.metadata&&typeof Z.metadata==="object"&&!Array.isArray(Z.metadata)?Z.metadata:{},...f0}})}appendDurableControl($){if(!$.id||$.role!=="user")throw Error("Durable control messages require a user role and identity");if(this._history.some((Z)=>Z.id===$.id))return;this._history.push($)}appendToHistory($){this._history.push($)}commitPending(){if(this._pending.length>0)this._history.push(...this._pending),this._pending=[]}replaceHistory($){this._history=$.filter((Z)=>!S$(Z)&&!E$(Z)),this._contextRevision++}restoreDurableHistory($){this._contextualSystemMessages=$.filter(E$),this._history=$.filter((Z)=>!S$(Z)&&!E$(Z)),this._pending=[],this.syncContextualSystemMessages(),this._contextRevision++}removeMessages($){let Z=[this._history.length,this._pending.length,this._contextualSystemMessages.length];if(this._history=this._history.filter((J)=>!$(J)),this._pending=this._pending.filter((J)=>!$(J)),this._contextualSystemMessages=this._contextualSystemMessages.filter((J)=>!$(J)),this.syncContextualSystemMessages(),this._history.length!==Z[0]||this._pending.length!==Z[1]||this._contextualSystemMessages.length!==Z[2])this._contextRevision++}writeback(){this.commitPending(),this.context.messages=[...this._contextualSystemMessages,...this._history]}get hasSystemPrompt(){return this.systemMessages.length>0}}function e6($){if($.isSubagent)return"continue";if(!$.budget||$.budget<=0)return"continue";if($.consecutiveContinuations>=3&&$.lastOutputDelta<500)return"stop";if($.usage/$.budget>=0.9)return"stop";return"continue"}function $J($){return{budget:$.budget,usage:0,consecutiveContinuations:0,lastOutputDelta:0,isSubagent:$.isSubagent??!1}}function ZJ($,Z,J){return{...$,usage:$.usage+Z,lastOutputDelta:Z,consecutiveContinuations:J?$.consecutiveContinuations+1:0}}import z$ from"node:path";var k8=new Set(["GOEXPERIMENT","GOOS","GOARCH","CGO_ENABLED","GO111MODULE","RUST_BACKTRACE","RUST_LOG","NODE_ENV","PYTHONUNBUFFERED","PYTHONDONTWRITEBYTECODE","GIT_TERMINAL_PROMPT","LANG","LANGUAGE","LC_ALL","LC_CTYPE","LC_TIME","CHARSET","TERM","COLORTERM","NO_COLOR","FORCE_COLOR","TZ","LS_COLORS","LSCOLORS","GREP_COLOR","GREP_COLORS"]),x8=/^(LD_.+|DYLD_.+|PATH)$/,JJ=/^([A-Za-z_][A-Za-z0-9_]*)=([\w./:@-]*)$/;function Z1($){let Z=$;while(!0){let J=Z.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!J)break;let W=J[1],Y=J[2],K=W.match(JJ);if(!K)break;let X=K[1];if(!k8.has(X))break;Z=Y}return Z}function r5($){let Z=$;while(!0){let J=Z.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!J)break;let W=J[1],Y=J[2],K=W.match(JJ);if(!K)break;let X=K[1];if(x8.test(X))break;Z=Y}return Z}var I8=[/^timeout[ \t]+(?:--foreground[ \t]+|--preserve-status[ \t]+|-v[ \t]+|--verbose[ \t]+|-k[ \t]+\S+[ \t]+|--kill-after[= ]\S+[ \t]+|-s[ \t]+\S+[ \t]+|--signal[= ]\S+[ \t]+)*\S+[ \t]+/,/^time[ \t]+/,/^nice[ \t]+(?:-n[ \t]+\d+[ \t]+|-\d+[ \t]+)?/,/^nohup[ \t]+/];function xZ($){let Z=$,J=!0;while(J){J=!1;for(let W of I8){let Y=Z.match(W);if(Y){Z=Z.slice(Y[0].length),J=!0;break}}if(Z.startsWith("-- "))Z=Z.slice(3),J=!0}return Z}function J1($){let Z=[],J="",W=!1,Y=!1,K=!1;for(let X=0;X<$.length;X++){let Q=$[X];if(K){J+=Q,K=!1;continue}if(Q==="\\"&&!W){J+=Q,K=!0;continue}if(Q==="'"&&!Y){W=!W,J+=Q;continue}if(Q==='"'&&!W){Y=!Y,J+=Q;continue}if(W||Y){J+=Q;continue}if(Q==="|"){if(X+1<$.length&&$[X+1]==="|"){if(J.trim())Z.push(J.trim());J="",X++;continue}return null}if(Q===">"||Q==="<")return null;if(Q==="&"&&X+1<$.length&&$[X+1]==="&"){if(J.trim())Z.push(J.trim());J="",X++;continue}if(Q==="&")return null;if(Q===";"){if(J.trim())Z.push(J.trim());J="";continue}J+=Q}if(J.trim())Z.push(J.trim());return Z.length>0?Z:null}function WJ($){let Z=!1,J=!1,W=!1;for(let Y=0;Y<$.length;Y++){let K=$[Y];if(W){W=!1;continue}if(K==="\\"&&!Z){W=!0;continue}if(K==="'"&&!J){Z=!Z;continue}if(K==='"'&&!Z){J=!J;continue}if(Z)continue;if(K==="$"){let X=$[Y+1];if(X&&/[A-Za-z_@*#?!$0-9({]/.test(X))return!0}if(K==="`")return!0;if(J)continue;if(K==="|")return!0;if(K===">"||K==="<")return!0;if(K==="{"){let X=$.slice(Y);if(/^\{[^}]*,[^}]*\}/.test(X)||/^\{[^}]*\.\.[^}]*\}/.test(X))return!0}}return!1}function V$($){let Z=[],J="",W=!1,Y=!1,K=!1;for(let X=0;X<$.length;X++){let Q=$[X];if(K){J+=Q,K=!1;continue}if(Q==="\\"&&!W){if(K=!0,Y){let H=$[X+1];if(H&&'$`"\\'.includes(H))continue;J+=Q,K=!1}continue}if(Q==="'"&&!Y){W=!W;continue}if(Q==='"'&&!W){Y=!Y;continue}if(!W&&!Y&&/[ \t]/.test(Q)){if(J)Z.push(J),J="";continue}J+=Q}if(J)Z.push(J);return Z}var h8=new Set(["npm","pnpm","yarn","bun"]),YJ=new Set(["biome","eslint","jest","mypy","pyright","pytest","ruff","tsc","vitest"]),v8=new Set(["-u","--fix","--update","--update-snapshot","--updateSnapshot","--watch","--watchAll","--write"]),C8=/[ \t]*;[ \t]*echo[ \t]+"[A-Za-z0-9 _:=.-]*(?:\$\{PIPESTATUS\[0\]\}|\$\?)[A-Za-z0-9 _:=.-]*"[ \t]*$/;function g8($){return $!==void 0&&/^(?:test|lint|build|type-?check)(?::[\w.-]+)*$/i.test($)}function KJ($){return $.replace(/\s+2>&1\s*$/,"").trim()}function p8($,Z,J){if(!J||Z.length!==2)return;let W=/^(.+?)[ \t]+&&[ \t]+([\s\S]+)$/.exec($);if(!W)return;let Y=V$(W[1]??"");if(Y.length!==2||Y[0]!=="cd")return;let K=Y[1];if(!K||K==="-")return;let X=z$.isAbsolute(K)?z$.resolve(K):z$.resolve(J,K);if(!j$.isWithinWorkspace(X,J))return;return W[2]?.trim()||void 0}function u8($){let Z=[],J=!1,W=!1,Y=!1;for(let K=0;K<$.length;K++){let X=$[K];if(Y){Y=!1;continue}if(X==="\\"&&!J){Y=!0;continue}if(X==="'"&&!W){J=!J;continue}if(X==='"'&&!J){W=!W;continue}if(X!=="|"||J||W)continue;if($[K+1]==="|")return;Z.push(K)}return Z}function m8($){let Z=V$($),[J,W,Y]=Z;if(J!=="head"&&J!=="tail")return!1;if(Z.length===1)return!0;let K=(X)=>X!==void 0&&/^[1-9]\d{0,4}$/.test(X);if(Z.length===2)return W?.startsWith("--lines=")&&K(W.slice(8))||W?.startsWith("-")&&K(W.slice(1));return Z.length===3&&(W==="-n"||W==="--lines")&&K(Y)}function d8($){let Z=KJ($.replace(C8,"").trim()),J=u8(Z);if(!J)return;if(J.length===0)return XJ(Z);if(J.length!==1)return;let W=J[0];if(W===void 0)return;let Y=KJ(Z.slice(0,W).trim()),K=Z.slice(W+1).trim();if(!Y||!m8(K))return;return XJ(Y)}function XJ($){let J=J1($)?.at(-1);if(!J)return $;let W=V$(J),[Y,K]=W;if(!(Y==="vitest"||(Y==="npx"||Y==="bunx")&&K==="vitest")||W.some((Q)=>Q==="--configLoader"||Q.startsWith("--configLoader=")))return $;return`${$} --configLoader runner`}function T$($,Z){let J=d8($);if(!J)return!1;let W=Z1(J),Y=J1(W);if(!Y||WJ(W)||/[\r\n]/.test(W))return!1;let K=Y.length===1?Y[0]:p8(W,Y,Z);if(!K)return!1;let X=V$(K);if(X.length===0||X.some((z)=>[...v8].some((w)=>z===w||z.startsWith(`${w}=`))))return!1;let[Q,H,V]=X;if(h8.has(Q??""))return g8(H==="run"?V:H)||H==="--test";if((Q==="npx"||Q==="bunx")&&YJ.has(H??""))return!0;if(YJ.has(Q??""))return!0;if(Q==="node"&&H==="--test")return!0;if(Q==="go"&&["build","test","vet"].includes(H??""))return!0;return Q==="cargo"&&["build","check","clippy","test"].includes(H??"")}function t5($,Z){if($===void 0)return!0;if(typeof $!=="string"||$.split(/[\\/]/).includes(".."))return!1;if(!Z)return!z$.isAbsolute($);let J=z$.isAbsolute($)?z$.resolve($):z$.resolve(Z,$);return j$.isWithinWorkspace(J,Z)}var IZ=S0("Agent"),c8=3;function hZ($,Z,J){if($!=="length")return{action:"none"};if(Z>=c8)return{action:"truncated"};if(e6(J)==="stop")return IZ.info("[Loop] Token budget: diminishing returns detected, skipping recovery"),{action:"budget_stop"};return{action:"recover"}}var l8=[/:\s*$/,/:\s*$/,/\.\.\.\s*$/,/让我(先|来|开始|查看|检查|修复)/,/Let me (first|start|check|look|fix)/i,/I('ll| will) (now |)(create|write|edit|update|modify|fix|add|implement)/i,/我(现在就|来|要)(创建|写入|编辑|修改|修复|添加|实现)/,/\d+\.\s+(First|Next|Then|Finally)/i],i8=/```[\s\S]{50,}```/,QJ="请执行你提到的操作,不要只是描述。使用 Edit/Write/ApplyPatch/Bash 工具来实际修改文件。",r8=2;function vZ($,Z,J=!0){if(!$||Z>=r8)return{action:"none"};if(!J&&i8.test($))return{action:"retry",prompt:QJ};let W=$.slice(-200),Y=W.match(/```/g);if(Y&&Y.length%2!==0)return{action:"none"};if(l8.some((X)=>X.test(W)))return{action:"retry",prompt:QJ};return{action:"none"}}var g1=2,n8="The model returned tool-call JSON as text instead of completing the requested tool workflow.",o8="The previous response contained tool-call JSON as ordinary text. It did not execute a tool. If the requested operation is still needed, use the native tool-call interface with an available tool. If it already succeeded, use the recorded result to answer instead of repeating the operation. Do not return another tool-call JSON envelope as your final answer.";function CZ($,Z,J,W){if(!$||$.length>65536||J.length===0)return{action:"none"};let Y=Z.replace(/```[\s\S]*?(?:```|$)/g,"").replace(/^\s*>.*$/gm,"");if(/\b(?:example|schema|serialize|serialization|quote|print|illustrate|verbatim)\b|示例|样例|序列化|引用原文/i.test(Y)||/\b(?:explain|show|return|output)\b[^.!?\n]{0,80}\b(?:json|tool.calls?)\b|(?:解释|展示|输出|返回)[^。!?\n]{0,40}(?:JSON|工具调用格式)/i.test(Y)||/\b(?:do not|don't|never)\s+(?:use|call|invoke|execute)\s+(?:any\s+)?tools?\b|不要(?:使用|调用|执行)(?:任何)?工具/i.test(Y))return{action:"none"};let K;try{K=JSON.parse($)}catch{return{action:"none"}}if(!K||typeof K!=="object"||Array.isArray(K)||Object.keys(K).length!==1||!("tool_calls"in K)||!Array.isArray(K.tool_calls)||K.tool_calls.length===0||K.tool_calls.length>32)return{action:"none"};let X=new Set;for(let Q of K.tool_calls){if(!Q||typeof Q!=="object"||Array.isArray(Q))return{action:"none"};let H="function"in Q;if(Object.keys(Q).some((G)=>!["id","type",...H?["function"]:["name","arguments"]].includes(G)))return{action:"none"};if("type"in Q&&Q.type!=="function")return{action:"none"};let V=H?Q.function:Q;if(!V||typeof V!=="object"||Array.isArray(V)||!("name"in V)||typeof V.name!=="string"||!("arguments"in V))return{action:"none"};if(H&&Object.keys(V).some((G)=>G!=="name"&&G!=="arguments"))return{action:"none"};if(!J.includes(V.name))return{action:"none"};let z=V.arguments;if(typeof z!=="string"&&(!z||typeof z!=="object"||Array.isArray(z)))return{action:"none"};let w=V.name.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),B=new RegExp(`(?:^|[.!?。!?;;\\n])\\s*(?:please\\s+)?(?:call|invoke|execute|run|use)\\s+(?:the\\s+)?(?:tool\\s+)?[\`"']?${w}(?![\\w:-])|(?:^|[。!?;\\n])\\s*(?:请)?(?:调用|使用|执行)\\s*(?:工具\\s*)?[\`"']?${w}(?![\\w:-])`,"i"),j=new RegExp(`(?:do not|don't|never)\\s+(?:call|invoke|execute|run|use)\\s+(?:the\\s+)?(?:tool\\s+)?[\`"']?${w}(?![\\w:-])|(?:不要|禁止)(?:调用|使用|执行)\\s*(?:工具\\s*)?[\`"']?${w}(?![\\w:-])`,"i");if(!B.test(Y)||j.test(Y))return{action:"none"};X.add(V.name)}return W<g1?{action:"retry",prompt:o8,...X.size===1?{toolName:[...X][0]}:{}}:{action:"fail",message:n8}}var a8=[/\b(?:run|execute|rerun|re-run)\b[\s\S]{0,60}\b(?:tests?|test suite|lint|type-?check|build)\b/i,/\b(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?(?:test|lint|build|type-?check)\b/i,/(?:运行|执行|跑|重新运行).{0,30}(?:测试|单测|集成测试|检查|构建)/],HJ={test:/\b(?:tests?|test suite)\b|(?:测试|单测|集成测试)/i,lint:/\blint(?:ing)?\b/i,"type-check":/\btype[\s-]?check(?:ing)?\b|\btsc\b|类型检查/i,build:/\bbuild\b|构建/i},s8={test:/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?test\b|(?:^|\s)(?:node|bun)\s+--test\b|(?:^|\s)(?:vitest|jest|pytest|go\s+test|cargo\s+test)\b/i,lint:/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?lint\b/i,"type-check":/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?type-?check\b|(?:^|\s)tsc\b/i,build:/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?build\b/i},t8="The user explicitly required verification, but it has not run successfully. Do not finish or explain. Your next action must be a Bash tool call that runs the requested test, lint, type-check, or build command. Inspect the command result and fix any failure before finishing.",e8="Required verification did not run successfully before the retry limit.",$9=3;function zJ($,Z,J,W){if(!J.success)return;if(["Edit","Write","ApplyPatch","NotebookEdit"].includes(Z)){$.clear();return}if(Z==="Bash"&&typeof J.metadata?.command==="string"&&J.metadata.exit_code===0&&T$(J.metadata.command,W)){$.add(J.metadata.command);return}if(!["Task","TaskOutput"].includes(Z))return;let Y=J.metadata?.verificationCommands;if(!Array.isArray(Y))return;for(let K of Y)if(typeof K==="string"&&T$(K,W))$.add(K)}function gZ($,Z,J){if(!$||!a8.some((H)=>H.test($)))return{action:"none"};let W=Object.keys(HJ).filter((H)=>HJ[H].test($)),Y=[...Z],K=W.filter((H)=>!Y.some((V)=>s8[H].test(V)));if(W.length>0?K.length===0:Y.some((H)=>T$(H)))return{action:"none"};if(J>=$9)return{action:"fail",message:e8};let Q=W.length>1&&K.length>0?` Missing successful verification categories: ${K.join(", ")}.`:"";return{action:"retry",prompt:`${t8}${Q}`}}var Z9=[/\bdelegate\b[\s\S]{0,120}\b(?:Task tool|subagent|agent)\b/i,/\b(?:call|use|invoke)\b[\s\S]{0,80}\bTask tool\b/i,/(?:委派|交给|调用|使用).{0,60}(?:Task|子代理|子智能体)/],jJ=[/\b(?:do not|don't|never)\s+(?:delegate|call|use|invoke)\b/i,/(?:不要|禁止|无需)(?:委派|调用|使用).{0,20}(?:Task|子代理|子智能体)?/];function BJ($){return typeof $==="string"&&jJ.some((Z)=>Z.test($))}var J9=[/\b(?:call|use|invoke)\b[\s\S]{0,30}\bTask(?: tool)?\b[\s\S]{0,30}\bexactly once\b/i,/\bexactly once\b[\s\S]{0,30}\b(?:call|use|invoke)\b[\s\S]{0,30}\bTask(?: tool)?\b/i,/\bexactly one\b[\s\S]{0,30}\bTask(?: tool)? calls?\b/i,/(?:Task|子代理).{0,20}(?:恰好|仅|只)(?:调用|使用)?一次/,/(?:恰好|仅|只)(?:调用|使用)?一次.{0,20}(?:Task|子代理)/],W9=[/\b(?:do not|don't|never)\s+(?:call|use|invoke)\s+(?:the\s+)?Task\b[\s\S]{0,30}\bexactly once\b/i,/\bTask\b[\s\S]{0,30}\b(?:does not|doesn't|need not)\b[\s\S]{0,30}\bexactly once\b/i,/\bmultiple\s+Task(?: tool)?\s+calls?\s+(?:are\s+)?allowed\b/i,/(?:不要|禁止).{0,12}(?:Task|子代理).{0,12}(?:恰好|仅|只)(?:调用|使用)?一次/];function Y9($){if(typeof $!=="string")return;if(W9.some((Z)=>Z.test($)))return"multiple-allowed";return J9.some((Z)=>Z.test($))?"required":void 0}function Y1($){for(let Z of $){let J=Y9(Z);if(J!==void 0)return J==="required"}return!1}var K9="The user explicitly required delegation, but no Task tool call completed successfully. Do not solve the task directly or explain. Your next action must be a Task tool call using the requested subagent.",X9="Required delegation did not complete before the retry limit.",Q9=3;function DJ($,Z,J){let W=(typeof $==="string"?[$]:$??[]).map((X)=>X.trim()).filter(Boolean),Y=Y1(W),K=!1;if(!Y)for(let X of W){if(jJ.some((Q)=>Q.test(X)))break;if(Z9.some((Q)=>Q.test(X))){K=!0;break}}if(W.length===0||!Y&&!K||Z.has("Task"))return{action:"none"};if(J>=Q9)return{action:"fail",message:X9};return{action:"retry",prompt:K9}}var H9=[/\b(?:use|create|enter|start|work\s+(?:in|inside))\b.{0,60}\bworktree\b/i,/(?:使用|创建|进入).{0,30}(?:worktree|工作树)/i],V9=[/\b(?:exit|leave)\b.{0,40}\bworktree\b/i,/\bworktree\b.{0,60}\b(?:action\s+)?(?:keep|remove)\b/i,/(?:退出|离开).{0,30}(?:worktree|工作树)/i],z9=[/\b(?:do not|don't|never|must not|should not)\b[^.!?;\n]{0,80}\b(?:git\s+)?worktree\b/gi,/\bwithout\b[^.!?;\n]{0,60}\b(?:git\s+)?worktree\b/gi,/(?:不要|禁止|不得|无需)[^。!?;\n]{0,50}(?:worktree|工作树)/gi];function wJ($){return z9.reduce((Z,J)=>Z.replace(J," "),$)}function p1($){if(typeof $!=="string")return!1;let Z=wJ($);return H9.some((J)=>J.test(Z))}var j9="The user explicitly required git worktree isolation, but EnterWorktree has not completed successfully. Do not continue in the original workspace. Your next action must be an EnterWorktree tool call. Wait for its result before using file or Bash tools.",B9="The user explicitly required leaving the managed worktree, but ExitWorktree has not completed successfully. Do not finish or explain. Your next action must be an ExitWorktree tool call using the action requested by the user.",D9="Required worktree lifecycle did not complete before the retry limit.",w9=3;function UJ($,Z,J){if(!$)return{action:"none"};let W=wJ($);if(!p1(W))return{action:"none"};let Y=V9.some((X)=>X.test(W));if(Z.has("TaskWorktree"))return{action:"none"};let K=!Z.has("EnterWorktree")?"EnterWorktree":Y&&!Z.has("ExitWorktree")?"ExitWorktree":void 0;if(!K)return{action:"none"};if(J>=w9)return{action:"fail",message:D9};return{action:"retry",tool:K,prompt:K==="EnterWorktree"?j9:B9}}var VJ=30000;async function pZ($){try{let J=R$.getInstance().executeStopHooks({projectDir:$.workspaceRoot??j0(),sessionId:$.sessionId,permissionMode:$.permissionMode,reason:$.reason,abortSignal:$.abortSignal}),W,Y=new Promise((K)=>{W=setTimeout(()=>K("timeout"),VJ)});try{let K=await Promise.race([J,Y]);if(K==="timeout")return IZ.warn(`[Loop] Stop hook 超时 (${VJ}ms),按 shouldStop: true 处理`),{action:"stop"};let X=K;if(!X.shouldStop)return{action:"continue",reason:X.continueReason};return{action:"stop"}}finally{clearTimeout(W)}}catch(Z){return IZ.warn("[Loop] Stop hook execution failed:",Z),{action:"stop"}}}async function U9($,Z){let J;while(!(J=await $.next()).done)if(Z)await Z(J.value);return J.value}var q9=[/<system-reminder>[\s\S]*?<\/system-reminder>/gi,/<file[^>]*>[\s\S]*?<\/file>/gi,/<hooks_context>[\s\S]*?<\/hooks_context>/gi,/<[^>]+>/g];function G9($){if(typeof $==="string")return $;if(Array.isArray($))return $.map((Z)=>{if(typeof Z==="string")return Z;if(Z&&typeof Z==="object"&&"text"in Z){let J=Z.text;return typeof J==="string"?J:""}return""}).join(" ");return""}function L9($){let Z=$;for(let H of q9)Z=Z.replace(H," ");Z=Z.replace(/^\s*\/[a-zA-Z][\w-]*\s+/,"");let J=Z.replace(/\s+/g," ").trim();if(!J)return"";let W=J.match(/^(.+?)(?:[.!?]\s|[。!?](?=\S|$)|$)/),Y=W&&W[1].length>=6?W[1]:J;if(Y=Y.trim().replace(/[\s.。!!??,,;;::-]+$/,""),Y.length<=60)return Y;let K=Y.slice(0,60),X=K.lastIndexOf(" ");return`${(X>36?K.slice(0,X):K).trimEnd()}…`}function qJ($){return L9(G9($))}import{EventEmitter as F9}from"events";import GJ from"node:path";function uZ($){if(FJ($.sessionId),!GJ.isAbsolute($.projectPath))throw Error("projectPath must be absolute");return{sessionId:$.sessionId,projectPath:GJ.resolve($.projectPath)}}function LJ($){let Z=uZ($);return JSON.stringify([Z.projectPath,Z.sessionId])}function j3($,Z){return LJ($)===LJ(Z)}class M$ extends F9{static instance;constructor(){super();this.setMaxListeners(100)}static getInstance(){if(!M$.instance)M$.instance=new M$;return M$.instance}publish($,Z,J,W){let Y=uZ($);this.emit("event",{sessionId:Y.sessionId,projectPath:Y.projectPath,type:Z,...W!==void 0?{seq:W}:{},properties:J})}subscribe($){return this.on("event",$),()=>this.off("event",$)}}var K1=M$.getInstance();var $$=S0("Agent"),u1=new Set;async function O9($,Z){let J=$.sessionId;if(!J||$.subagentInfo)return;if(u1.has(J))return;if(u1.size>=5000)u1.clear();u1.add(J);try{let W=$.workspaceRoot,Y=await X1.findSessionMetadata(J,W);if(!Y)return;if(Y.title&&Y.title.trim())return;let K=qJ(Z);if(!K)return;await X1.updateSessionMetadata(J,Y.projectPath,{title:K}),K1.publish({sessionId:J,projectPath:Y.projectPath},"session.updated",{title:K})}catch(W){$$.debug?.("[Loop] 自动生成会话标题失败:",W)}}var mZ=`<turn_aborted>
|
|
1
|
+
import{xc as G8}from"./chunk-fdr4fcrf.js";import{$d as R6,Ac as U$,Bc as A2,Cc as a1,Ec as j$,Fd as E2,Gd as L8,Hd as F8,Id as V6,Jd as JZ,Kd as O8,Ld as P8,Md as r1,Qd as rJ,Zd as u0,ae as t1,be as M6,ie as X1,ud as b2,wd as y2,xd as f2,yc as q$,yd as w6,zd as U6}from"./chunk-2kx9ygzc.js";import{ne as q8}from"./chunk-egss0m1x.js";import{Fe as f0,qe as q0,te as j2,ue as u$}from"./chunk-ztreczac.js";import{eg as p2}from"./chunk-5yyp6njq.js";import{fg as w8,gg as C0,hg as H8,ig as dJ,kg as i1,lg as T6,mg as cJ,ng as lJ,qg as iJ}from"./chunk-myvt7yjm.js";import{ch as K$,dh as n0,gh as U8}from"./chunk-kehgewqh.js";import{lh as a2,ph as Y2}from"./chunk-kkzznz4w.js";import{Ah as R$}from"./chunk-f1x80zky.js";import{Vi as x$}from"./chunk-qpmvp4q2.js";import{cj as j0}from"./chunk-qdbbke8f.js";import{Ej as S0}from"./chunk-rmfzym94.js";import{Yj as _2}from"./chunk-rytpfm4a.js";import{Ck as FJ,Dk as ZZ,Fk as O2,Kk as P2,Lk as N2,gk as F2,vk as w2,wk as U2,zk as H1}from"./chunk-n52n2w5v.js";import{Nk as lZ}from"./chunk-cjfb4kjp.js";function S$($){return $.role==="system"&&Array.isArray($.content)}function E$($){if($.role!=="system"||!$.metadata||Array.isArray($.metadata))return!1;return typeof $.metadata==="object"&&$.metadata.contextualProjectRules===!0}class C1{systemMessages;_contextualSystemMessages;_history;_pending=[];_contextRevision=0;context;constructor($,Z){this.context=$;let J=$.messages.find(S$);if(this._contextualSystemMessages=$.messages.filter(E$),J)this.systemMessages=[J,...this._contextualSystemMessages];else if(Z)this.systemMessages=[{role:"system",content:[{type:"text",text:Z,providerOptions:{anthropic:{cacheControl:{type:"ephemeral"}}}}]},...this._contextualSystemMessages];else this.systemMessages=[...this._contextualSystemMessages];this._history=$.messages.filter((W)=>!S$(W)&&!E$(W))}get historyLength(){return this._history.length}get history(){return this._history}get pending(){return this._pending}get contextRevision(){return this._contextRevision}toLLMMessages(){return[...this.systemMessages,...this._history,...this._pending]}getMessagesForLLM(){return this.toLLMMessages()}getHistory(){return this._history}appendPending($){this._pending.push($)}appendUser($){this._pending.push($)}appendAssistant($){this._pending.push($)}appendToolResult($){this._pending.push($)}appendContextualProjectInstructions($){if(!E$($))throw Error("Contextual project instructions require safe metadata");this._contextualSystemMessages.push($),this.systemMessages.push($)}syncContextualSystemMessages(){let $=this.systemMessages.filter(S$);this.systemMessages.splice(0,this.systemMessages.length,...$,...this._contextualSystemMessages)}appendControl($,Z){if($==="system")throw Error("Cannot append system control message via appendControl. Use constructor for root system prompt.");this._pending.push({...Z,metadata:{...Z.metadata&&typeof Z.metadata==="object"&&!Array.isArray(Z.metadata)?Z.metadata:{},...f0}})}appendDurableControl($){if(!$.id||$.role!=="user")throw Error("Durable control messages require a user role and identity");if(this._history.some((Z)=>Z.id===$.id))return;this._history.push($)}appendToHistory($){this._history.push($)}commitPending(){if(this._pending.length>0)this._history.push(...this._pending),this._pending=[]}replaceHistory($){this._history=$.filter((Z)=>!S$(Z)&&!E$(Z)),this._contextRevision++}restoreDurableHistory($){this._contextualSystemMessages=$.filter(E$),this._history=$.filter((Z)=>!S$(Z)&&!E$(Z)),this._pending=[],this.syncContextualSystemMessages(),this._contextRevision++}removeMessages($){let Z=[this._history.length,this._pending.length,this._contextualSystemMessages.length];if(this._history=this._history.filter((J)=>!$(J)),this._pending=this._pending.filter((J)=>!$(J)),this._contextualSystemMessages=this._contextualSystemMessages.filter((J)=>!$(J)),this.syncContextualSystemMessages(),this._history.length!==Z[0]||this._pending.length!==Z[1]||this._contextualSystemMessages.length!==Z[2])this._contextRevision++}writeback(){this.commitPending(),this.context.messages=[...this._contextualSystemMessages,...this._history]}get hasSystemPrompt(){return this.systemMessages.length>0}}function e6($){if($.isSubagent)return"continue";if(!$.budget||$.budget<=0)return"continue";if($.consecutiveContinuations>=3&&$.lastOutputDelta<500)return"stop";if($.usage/$.budget>=0.9)return"stop";return"continue"}function $J($){return{budget:$.budget,usage:0,consecutiveContinuations:0,lastOutputDelta:0,isSubagent:$.isSubagent??!1}}function ZJ($,Z,J){return{...$,usage:$.usage+Z,lastOutputDelta:Z,consecutiveContinuations:J?$.consecutiveContinuations+1:0}}import z$ from"node:path";var k8=new Set(["GOEXPERIMENT","GOOS","GOARCH","CGO_ENABLED","GO111MODULE","RUST_BACKTRACE","RUST_LOG","NODE_ENV","PYTHONUNBUFFERED","PYTHONDONTWRITEBYTECODE","GIT_TERMINAL_PROMPT","LANG","LANGUAGE","LC_ALL","LC_CTYPE","LC_TIME","CHARSET","TERM","COLORTERM","NO_COLOR","FORCE_COLOR","TZ","LS_COLORS","LSCOLORS","GREP_COLOR","GREP_COLORS"]),x8=/^(LD_.+|DYLD_.+|PATH)$/,JJ=/^([A-Za-z_][A-Za-z0-9_]*)=([\w./:@-]*)$/;function Z1($){let Z=$;while(!0){let J=Z.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!J)break;let W=J[1],Y=J[2],K=W.match(JJ);if(!K)break;let X=K[1];if(!k8.has(X))break;Z=Y}return Z}function r5($){let Z=$;while(!0){let J=Z.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!J)break;let W=J[1],Y=J[2],K=W.match(JJ);if(!K)break;let X=K[1];if(x8.test(X))break;Z=Y}return Z}var I8=[/^timeout[ \t]+(?:--foreground[ \t]+|--preserve-status[ \t]+|-v[ \t]+|--verbose[ \t]+|-k[ \t]+\S+[ \t]+|--kill-after[= ]\S+[ \t]+|-s[ \t]+\S+[ \t]+|--signal[= ]\S+[ \t]+)*\S+[ \t]+/,/^time[ \t]+/,/^nice[ \t]+(?:-n[ \t]+\d+[ \t]+|-\d+[ \t]+)?/,/^nohup[ \t]+/];function xZ($){let Z=$,J=!0;while(J){J=!1;for(let W of I8){let Y=Z.match(W);if(Y){Z=Z.slice(Y[0].length),J=!0;break}}if(Z.startsWith("-- "))Z=Z.slice(3),J=!0}return Z}function J1($){let Z=[],J="",W=!1,Y=!1,K=!1;for(let X=0;X<$.length;X++){let Q=$[X];if(K){J+=Q,K=!1;continue}if(Q==="\\"&&!W){J+=Q,K=!0;continue}if(Q==="'"&&!Y){W=!W,J+=Q;continue}if(Q==='"'&&!W){Y=!Y,J+=Q;continue}if(W||Y){J+=Q;continue}if(Q==="|"){if(X+1<$.length&&$[X+1]==="|"){if(J.trim())Z.push(J.trim());J="",X++;continue}return null}if(Q===">"||Q==="<")return null;if(Q==="&"&&X+1<$.length&&$[X+1]==="&"){if(J.trim())Z.push(J.trim());J="",X++;continue}if(Q==="&")return null;if(Q===";"){if(J.trim())Z.push(J.trim());J="";continue}J+=Q}if(J.trim())Z.push(J.trim());return Z.length>0?Z:null}function WJ($){let Z=!1,J=!1,W=!1;for(let Y=0;Y<$.length;Y++){let K=$[Y];if(W){W=!1;continue}if(K==="\\"&&!Z){W=!0;continue}if(K==="'"&&!J){Z=!Z;continue}if(K==='"'&&!Z){J=!J;continue}if(Z)continue;if(K==="$"){let X=$[Y+1];if(X&&/[A-Za-z_@*#?!$0-9({]/.test(X))return!0}if(K==="`")return!0;if(J)continue;if(K==="|")return!0;if(K===">"||K==="<")return!0;if(K==="{"){let X=$.slice(Y);if(/^\{[^}]*,[^}]*\}/.test(X)||/^\{[^}]*\.\.[^}]*\}/.test(X))return!0}}return!1}function V$($){let Z=[],J="",W=!1,Y=!1,K=!1;for(let X=0;X<$.length;X++){let Q=$[X];if(K){J+=Q,K=!1;continue}if(Q==="\\"&&!W){if(K=!0,Y){let H=$[X+1];if(H&&'$`"\\'.includes(H))continue;J+=Q,K=!1}continue}if(Q==="'"&&!Y){W=!W;continue}if(Q==='"'&&!W){Y=!Y;continue}if(!W&&!Y&&/[ \t]/.test(Q)){if(J)Z.push(J),J="";continue}J+=Q}if(J)Z.push(J);return Z}var h8=new Set(["npm","pnpm","yarn","bun"]),YJ=new Set(["biome","eslint","jest","mypy","pyright","pytest","ruff","tsc","vitest"]),v8=new Set(["-u","--fix","--update","--update-snapshot","--updateSnapshot","--watch","--watchAll","--write"]),C8=/[ \t]*;[ \t]*echo[ \t]+"[A-Za-z0-9 _:=.-]*(?:\$\{PIPESTATUS\[0\]\}|\$\?)[A-Za-z0-9 _:=.-]*"[ \t]*$/;function g8($){return $!==void 0&&/^(?:test|lint|build|type-?check)(?::[\w.-]+)*$/i.test($)}function KJ($){return $.replace(/\s+2>&1\s*$/,"").trim()}function p8($,Z,J){if(!J||Z.length!==2)return;let W=/^(.+?)[ \t]+&&[ \t]+([\s\S]+)$/.exec($);if(!W)return;let Y=V$(W[1]??"");if(Y.length!==2||Y[0]!=="cd")return;let K=Y[1];if(!K||K==="-")return;let X=z$.isAbsolute(K)?z$.resolve(K):z$.resolve(J,K);if(!j$.isWithinWorkspace(X,J))return;return W[2]?.trim()||void 0}function u8($){let Z=[],J=!1,W=!1,Y=!1;for(let K=0;K<$.length;K++){let X=$[K];if(Y){Y=!1;continue}if(X==="\\"&&!J){Y=!0;continue}if(X==="'"&&!W){J=!J;continue}if(X==='"'&&!J){W=!W;continue}if(X!=="|"||J||W)continue;if($[K+1]==="|")return;Z.push(K)}return Z}function m8($){let Z=V$($),[J,W,Y]=Z;if(J!=="head"&&J!=="tail")return!1;if(Z.length===1)return!0;let K=(X)=>X!==void 0&&/^[1-9]\d{0,4}$/.test(X);if(Z.length===2)return W?.startsWith("--lines=")&&K(W.slice(8))||W?.startsWith("-")&&K(W.slice(1));return Z.length===3&&(W==="-n"||W==="--lines")&&K(Y)}function d8($){let Z=KJ($.replace(C8,"").trim()),J=u8(Z);if(!J)return;if(J.length===0)return XJ(Z);if(J.length!==1)return;let W=J[0];if(W===void 0)return;let Y=KJ(Z.slice(0,W).trim()),K=Z.slice(W+1).trim();if(!Y||!m8(K))return;return XJ(Y)}function XJ($){let J=J1($)?.at(-1);if(!J)return $;let W=V$(J),[Y,K]=W;if(!(Y==="vitest"||(Y==="npx"||Y==="bunx")&&K==="vitest")||W.some((Q)=>Q==="--configLoader"||Q.startsWith("--configLoader=")))return $;return`${$} --configLoader runner`}function T$($,Z){let J=d8($);if(!J)return!1;let W=Z1(J),Y=J1(W);if(!Y||WJ(W)||/[\r\n]/.test(W))return!1;let K=Y.length===1?Y[0]:p8(W,Y,Z);if(!K)return!1;let X=V$(K);if(X.length===0||X.some((z)=>[...v8].some((w)=>z===w||z.startsWith(`${w}=`))))return!1;let[Q,H,V]=X;if(h8.has(Q??""))return g8(H==="run"?V:H)||H==="--test";if((Q==="npx"||Q==="bunx")&&YJ.has(H??""))return!0;if(YJ.has(Q??""))return!0;if(Q==="node"&&H==="--test")return!0;if(Q==="go"&&["build","test","vet"].includes(H??""))return!0;return Q==="cargo"&&["build","check","clippy","test"].includes(H??"")}function t5($,Z){if($===void 0)return!0;if(typeof $!=="string"||$.split(/[\\/]/).includes(".."))return!1;if(!Z)return!z$.isAbsolute($);let J=z$.isAbsolute($)?z$.resolve($):z$.resolve(Z,$);return j$.isWithinWorkspace(J,Z)}var IZ=S0("Agent"),c8=3;function hZ($,Z,J){if($!=="length")return{action:"none"};if(Z>=c8)return{action:"truncated"};if(e6(J)==="stop")return IZ.info("[Loop] Token budget: diminishing returns detected, skipping recovery"),{action:"budget_stop"};return{action:"recover"}}var l8=[/:\s*$/,/:\s*$/,/\.\.\.\s*$/,/让我(先|来|开始|查看|检查|修复)/,/Let me (first|start|check|look|fix)/i,/I('ll| will) (now |)(create|write|edit|update|modify|fix|add|implement)/i,/我(现在就|来|要)(创建|写入|编辑|修改|修复|添加|实现)/,/\d+\.\s+(First|Next|Then|Finally)/i],i8=/```[\s\S]{50,}```/,QJ="请执行你提到的操作,不要只是描述。使用 Edit/Write/ApplyPatch/Bash 工具来实际修改文件。",r8=2;function vZ($,Z,J=!0){if(!$||Z>=r8)return{action:"none"};if(!J&&i8.test($))return{action:"retry",prompt:QJ};let W=$.slice(-200),Y=W.match(/```/g);if(Y&&Y.length%2!==0)return{action:"none"};if(l8.some((X)=>X.test(W)))return{action:"retry",prompt:QJ};return{action:"none"}}var g1=2,n8="The model returned tool-call JSON as text instead of completing the requested tool workflow.",o8="The previous response contained tool-call JSON as ordinary text. It did not execute a tool. If the requested operation is still needed, use the native tool-call interface with an available tool. If it already succeeded, use the recorded result to answer instead of repeating the operation. Do not return another tool-call JSON envelope as your final answer.";function CZ($,Z,J,W){if(!$||$.length>65536||J.length===0)return{action:"none"};let Y=Z.replace(/```[\s\S]*?(?:```|$)/g,"").replace(/^\s*>.*$/gm,"");if(/\b(?:example|schema|serialize|serialization|quote|print|illustrate|verbatim)\b|示例|样例|序列化|引用原文/i.test(Y)||/\b(?:explain|show|return|output)\b[^.!?\n]{0,80}\b(?:json|tool.calls?)\b|(?:解释|展示|输出|返回)[^。!?\n]{0,40}(?:JSON|工具调用格式)/i.test(Y)||/\b(?:do not|don't|never)\s+(?:use|call|invoke|execute)\s+(?:any\s+)?tools?\b|不要(?:使用|调用|执行)(?:任何)?工具/i.test(Y))return{action:"none"};let K;try{K=JSON.parse($)}catch{return{action:"none"}}if(!K||typeof K!=="object"||Array.isArray(K)||Object.keys(K).length!==1||!("tool_calls"in K)||!Array.isArray(K.tool_calls)||K.tool_calls.length===0||K.tool_calls.length>32)return{action:"none"};let X=new Set;for(let Q of K.tool_calls){if(!Q||typeof Q!=="object"||Array.isArray(Q))return{action:"none"};let H="function"in Q;if(Object.keys(Q).some((G)=>!["id","type",...H?["function"]:["name","arguments"]].includes(G)))return{action:"none"};if("type"in Q&&Q.type!=="function")return{action:"none"};let V=H?Q.function:Q;if(!V||typeof V!=="object"||Array.isArray(V)||!("name"in V)||typeof V.name!=="string"||!("arguments"in V))return{action:"none"};if(H&&Object.keys(V).some((G)=>G!=="name"&&G!=="arguments"))return{action:"none"};if(!J.includes(V.name))return{action:"none"};let z=V.arguments;if(typeof z!=="string"&&(!z||typeof z!=="object"||Array.isArray(z)))return{action:"none"};let w=V.name.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),B=new RegExp(`(?:^|[.!?。!?;;\\n])\\s*(?:please\\s+)?(?:call|invoke|execute|run|use)\\s+(?:the\\s+)?(?:tool\\s+)?[\`"']?${w}(?![\\w:-])|(?:^|[。!?;\\n])\\s*(?:请)?(?:调用|使用|执行)\\s*(?:工具\\s*)?[\`"']?${w}(?![\\w:-])`,"i"),j=new RegExp(`(?:do not|don't|never)\\s+(?:call|invoke|execute|run|use)\\s+(?:the\\s+)?(?:tool\\s+)?[\`"']?${w}(?![\\w:-])|(?:不要|禁止)(?:调用|使用|执行)\\s*(?:工具\\s*)?[\`"']?${w}(?![\\w:-])`,"i");if(!B.test(Y)||j.test(Y))return{action:"none"};X.add(V.name)}return W<g1?{action:"retry",prompt:o8,...X.size===1?{toolName:[...X][0]}:{}}:{action:"fail",message:n8}}var a8=[/\b(?:run|execute|rerun|re-run)\b[\s\S]{0,60}\b(?:tests?|test suite|lint|type-?check|build)\b/i,/\b(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?(?:test|lint|build|type-?check)\b/i,/(?:运行|执行|跑|重新运行).{0,30}(?:测试|单测|集成测试|检查|构建)/],HJ={test:/\b(?:tests?|test suite)\b|(?:测试|单测|集成测试)/i,lint:/\blint(?:ing)?\b/i,"type-check":/\btype[\s-]?check(?:ing)?\b|\btsc\b|类型检查/i,build:/\bbuild\b|构建/i},s8={test:/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?test\b|(?:^|\s)(?:node|bun)\s+--test\b|(?:^|\s)(?:vitest|jest|pytest|go\s+test|cargo\s+test)\b/i,lint:/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?lint\b/i,"type-check":/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?type-?check\b|(?:^|\s)tsc\b/i,build:/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?build\b/i},t8="The user explicitly required verification, but it has not run successfully. Do not finish or explain. Your next action must be a Bash tool call that runs the requested test, lint, type-check, or build command. Inspect the command result and fix any failure before finishing.",e8="Required verification did not run successfully before the retry limit.",$9=3;function zJ($,Z,J,W){if(!J.success)return;if(["Edit","Write","ApplyPatch","NotebookEdit"].includes(Z)){$.clear();return}if(Z==="Bash"&&typeof J.metadata?.command==="string"&&J.metadata.exit_code===0&&T$(J.metadata.command,W)){$.add(J.metadata.command);return}if(!["Task","TaskOutput"].includes(Z))return;let Y=J.metadata?.verificationCommands;if(!Array.isArray(Y))return;for(let K of Y)if(typeof K==="string"&&T$(K,W))$.add(K)}function gZ($,Z,J){if(!$||!a8.some((H)=>H.test($)))return{action:"none"};let W=Object.keys(HJ).filter((H)=>HJ[H].test($)),Y=[...Z],K=W.filter((H)=>!Y.some((V)=>s8[H].test(V)));if(W.length>0?K.length===0:Y.some((H)=>T$(H)))return{action:"none"};if(J>=$9)return{action:"fail",message:e8};let Q=W.length>1&&K.length>0?` Missing successful verification categories: ${K.join(", ")}.`:"";return{action:"retry",prompt:`${t8}${Q}`}}var Z9=[/\bdelegate\b[\s\S]{0,120}\b(?:Task tool|subagent|agent)\b/i,/\b(?:call|use|invoke)\b[\s\S]{0,80}\bTask tool\b/i,/(?:委派|交给|调用|使用).{0,60}(?:Task|子代理|子智能体)/],jJ=[/\b(?:do not|don't|never)\s+(?:delegate|call|use|invoke)\b/i,/(?:不要|禁止|无需)(?:委派|调用|使用).{0,20}(?:Task|子代理|子智能体)?/];function BJ($){return typeof $==="string"&&jJ.some((Z)=>Z.test($))}var J9=[/\b(?:call|use|invoke)\b[\s\S]{0,30}\bTask(?: tool)?\b[\s\S]{0,30}\bexactly once\b/i,/\bexactly once\b[\s\S]{0,30}\b(?:call|use|invoke)\b[\s\S]{0,30}\bTask(?: tool)?\b/i,/\bexactly one\b[\s\S]{0,30}\bTask(?: tool)? calls?\b/i,/(?:Task|子代理).{0,20}(?:恰好|仅|只)(?:调用|使用)?一次/,/(?:恰好|仅|只)(?:调用|使用)?一次.{0,20}(?:Task|子代理)/],W9=[/\b(?:do not|don't|never)\s+(?:call|use|invoke)\s+(?:the\s+)?Task\b[\s\S]{0,30}\bexactly once\b/i,/\bTask\b[\s\S]{0,30}\b(?:does not|doesn't|need not)\b[\s\S]{0,30}\bexactly once\b/i,/\bmultiple\s+Task(?: tool)?\s+calls?\s+(?:are\s+)?allowed\b/i,/(?:不要|禁止).{0,12}(?:Task|子代理).{0,12}(?:恰好|仅|只)(?:调用|使用)?一次/];function Y9($){if(typeof $!=="string")return;if(W9.some((Z)=>Z.test($)))return"multiple-allowed";return J9.some((Z)=>Z.test($))?"required":void 0}function Y1($){for(let Z of $){let J=Y9(Z);if(J!==void 0)return J==="required"}return!1}var K9="The user explicitly required delegation, but no Task tool call completed successfully. Do not solve the task directly or explain. Your next action must be a Task tool call using the requested subagent.",X9="Required delegation did not complete before the retry limit.",Q9=3;function DJ($,Z,J){let W=(typeof $==="string"?[$]:$??[]).map((X)=>X.trim()).filter(Boolean),Y=Y1(W),K=!1;if(!Y)for(let X of W){if(jJ.some((Q)=>Q.test(X)))break;if(Z9.some((Q)=>Q.test(X))){K=!0;break}}if(W.length===0||!Y&&!K||Z.has("Task"))return{action:"none"};if(J>=Q9)return{action:"fail",message:X9};return{action:"retry",prompt:K9}}var H9=[/\b(?:use|create|enter|start|work\s+(?:in|inside))\b.{0,60}\bworktree\b/i,/(?:使用|创建|进入).{0,30}(?:worktree|工作树)/i],V9=[/\b(?:exit|leave)\b.{0,40}\bworktree\b/i,/\bworktree\b.{0,60}\b(?:action\s+)?(?:keep|remove)\b/i,/(?:退出|离开).{0,30}(?:worktree|工作树)/i],z9=[/\b(?:do not|don't|never|must not|should not)\b[^.!?;\n]{0,80}\b(?:git\s+)?worktree\b/gi,/\bwithout\b[^.!?;\n]{0,60}\b(?:git\s+)?worktree\b/gi,/(?:不要|禁止|不得|无需)[^。!?;\n]{0,50}(?:worktree|工作树)/gi];function wJ($){return z9.reduce((Z,J)=>Z.replace(J," "),$)}function p1($){if(typeof $!=="string")return!1;let Z=wJ($);return H9.some((J)=>J.test(Z))}var j9="The user explicitly required git worktree isolation, but EnterWorktree has not completed successfully. Do not continue in the original workspace. Your next action must be an EnterWorktree tool call. Wait for its result before using file or Bash tools.",B9="The user explicitly required leaving the managed worktree, but ExitWorktree has not completed successfully. Do not finish or explain. Your next action must be an ExitWorktree tool call using the action requested by the user.",D9="Required worktree lifecycle did not complete before the retry limit.",w9=3;function UJ($,Z,J){if(!$)return{action:"none"};let W=wJ($);if(!p1(W))return{action:"none"};let Y=V9.some((X)=>X.test(W));if(Z.has("TaskWorktree"))return{action:"none"};let K=!Z.has("EnterWorktree")?"EnterWorktree":Y&&!Z.has("ExitWorktree")?"ExitWorktree":void 0;if(!K)return{action:"none"};if(J>=w9)return{action:"fail",message:D9};return{action:"retry",tool:K,prompt:K==="EnterWorktree"?j9:B9}}var VJ=30000;async function pZ($){try{let J=R$.getInstance().executeStopHooks({projectDir:$.workspaceRoot??j0(),sessionId:$.sessionId,permissionMode:$.permissionMode,reason:$.reason,abortSignal:$.abortSignal}),W,Y=new Promise((K)=>{W=setTimeout(()=>K("timeout"),VJ)});try{let K=await Promise.race([J,Y]);if(K==="timeout")return IZ.warn(`[Loop] Stop hook 超时 (${VJ}ms),按 shouldStop: true 处理`),{action:"stop"};let X=K;if(!X.shouldStop)return{action:"continue",reason:X.continueReason};return{action:"stop"}}finally{clearTimeout(W)}}catch(Z){return IZ.warn("[Loop] Stop hook execution failed:",Z),{action:"stop"}}}async function U9($,Z){let J;while(!(J=await $.next()).done)if(Z)await Z(J.value);return J.value}var q9=[/<system-reminder>[\s\S]*?<\/system-reminder>/gi,/<file[^>]*>[\s\S]*?<\/file>/gi,/<hooks_context>[\s\S]*?<\/hooks_context>/gi,/<[^>]+>/g];function G9($){if(typeof $==="string")return $;if(Array.isArray($))return $.map((Z)=>{if(typeof Z==="string")return Z;if(Z&&typeof Z==="object"&&"text"in Z){let J=Z.text;return typeof J==="string"?J:""}return""}).join(" ");return""}function L9($){let Z=$;for(let H of q9)Z=Z.replace(H," ");Z=Z.replace(/^\s*\/[a-zA-Z][\w-]*\s+/,"");let J=Z.replace(/\s+/g," ").trim();if(!J)return"";let W=J.match(/^(.+?)(?:[.!?]\s|[。!?](?=\S|$)|$)/),Y=W&&W[1].length>=6?W[1]:J;if(Y=Y.trim().replace(/[\s.。!!??,,;;::-]+$/,""),Y.length<=60)return Y;let K=Y.slice(0,60),X=K.lastIndexOf(" ");return`${(X>36?K.slice(0,X):K).trimEnd()}…`}function qJ($){return L9(G9($))}import{EventEmitter as F9}from"events";import GJ from"node:path";function uZ($){if(FJ($.sessionId),!GJ.isAbsolute($.projectPath))throw Error("projectPath must be absolute");return{sessionId:$.sessionId,projectPath:GJ.resolve($.projectPath)}}function LJ($){let Z=uZ($);return JSON.stringify([Z.projectPath,Z.sessionId])}function j3($,Z){return LJ($)===LJ(Z)}class M$ extends F9{static instance;constructor(){super();this.setMaxListeners(100)}static getInstance(){if(!M$.instance)M$.instance=new M$;return M$.instance}publish($,Z,J,W){let Y=uZ($);this.emit("event",{sessionId:Y.sessionId,projectPath:Y.projectPath,type:Z,...W!==void 0?{seq:W}:{},properties:J})}subscribe($){return this.on("event",$),()=>this.off("event",$)}}var K1=M$.getInstance();var $$=S0("Agent"),u1=new Set;async function O9($,Z){let J=$.sessionId;if(!J||$.subagentInfo)return;if(u1.has(J))return;if(u1.size>=5000)u1.clear();u1.add(J);try{let W=$.workspaceRoot,Y=await X1.findSessionMetadata(J,W);if(!Y)return;if(Y.title&&Y.title.trim())return;let K=qJ(Z);if(!K)return;await X1.updateSessionMetadata(J,Y.projectPath,{title:K}),K1.publish({sessionId:J,projectPath:Y.projectPath},"session.updated",{title:K})}catch(W){$$.debug?.("[Loop] 自动生成会话标题失败:",W)}}var mZ=`<turn_aborted>
|
|
2
2
|
The previous turn was interrupted. Commands or tool calls may have partially completed; inspect the workspace and running processes before retrying.
|
|
3
3
|
</turn_aborted>`,B$="Tool execution was blocked because its durable call record could not be committed. No tool side effect was started.",OJ="Tool execution completed, but its durable result record could not be committed. Further model and tool execution was stopped. The operation may have completed; inspect external state before retrying.";class k$ extends Error{phase;constructor($,Z){super($==="user_message"?"Conversation input could not be committed. No further model request was started.":"Model output could not be committed. The run was stopped before any further model request or successful completion.",Z);this.phase=$;this.name="DurableConversationPersistenceError"}}function D$($){return $.executionEngine?.getContextManager()}async function r0($,Z,J,W=null,Y,K={}){let X=K.required??$.executionEngine!==void 0;try{let Q=D$($),H=typeof J==="string"?J.trim()!=="":J.some((V)=>V.type==="text"?V.text.trim()!=="":!0);if(Q&&Z.sessionId&&H){let V=await Q.saveMessage(Z.sessionId,"user",J,W,Y,Z.subagentInfo);if(X&&!V)throw Error("Durable user-message commit returned no identity");if(Y?.clientVisible!==!1)O9(Z,J);return V}if(X&&Z.sessionId&&H)throw Error("Durable user-message storage is unavailable")}catch(Q){if($$.warn("[Loop] 保存用户消息失败:",Q),X)throw new k$("user_message",{cause:Q})}return null}async function v0($,Z,J,W,Y,K,X={}){let Q=X.required??$.executionEngine!==void 0;try{let H=D$($),V=Boolean(J.trim()||Y?.trim());if(H&&Z.sessionId&&V){let z=await H.saveMessage(Z.sessionId,"assistant",J,W,K,Z.subagentInfo,Y);if(Q&&!z)throw Error("Durable assistant-message commit returned no identity");return z}if(Q&&Z.sessionId&&V)throw Error("Durable assistant-message storage is unavailable")}catch(H){if($$.warn("[Loop] 保存助手消息失败:",H),Q)throw new k$("assistant_message",{cause:H})}return null}async function PJ($,Z,J){try{let W=D$($);if(W&&Z.sessionId)return await W.saveMessage(Z.sessionId,"system",mZ,J,void 0,Z.subagentInfo)}catch(W){$$.warn("[Loop] 保存中断边界失败:",W)}return null}async function NJ($,Z,J,W,Y){try{let K=D$($);if(!K||!Z.sessionId||J.length===0)return null;return await K.saveMessage(Z.sessionId,"system",`<contextual-project-instructions-ref count="${J.length}" />`,Y,{contextualProjectRules:!0,ruleReferences:JSON.parse(JSON.stringify(J.map((X)=>({...X})))),triggerPaths:[...W]},Z.subagentInfo)}catch(K){$$.warn("[Loop] 保存 contextual project rules provenance 失败:",K)}return null}async function dZ($,Z,J,W,Y,K={}){try{let X=D$($);if(X&&Z.sessionId){let Q=await X.saveToolUse(Z.sessionId,J,W,Y,Z.subagentInfo,K.providerToolCallId);if(K.required&&!Q)throw Error("Durable tool-use commit returned no identity");return Q}if(K.required&&Z.sessionId)throw Error("Durable tool-use storage is unavailable")}catch(X){if($$.warn("[Loop] 保存工具调用失败:",X),K.required)throw X}return null}async function m1($,Z,J,W,Y,K,X,Q,H,V={}){try{let z=D$($);if(z&&Z.sessionId){let w=await z.saveToolResult(Z.sessionId,J,W,Y,K,X,Z.subagentInfo,Q,H);if(V.required&&!w)throw Error("Durable tool-result commit returned no identity");return w}if(V.required&&Z.sessionId)throw Error("Durable tool-result storage is unavailable")}catch(z){if($$.warn("[Loop] 保存工具结果失败:",z),V.required)throw z}return null}async function Q1($,Z,J,W,Y={}){try{let K=D$($);if(K&&Z.sessionId){let X=await K.saveCompaction(Z.sessionId,J,W,null);if(Y.required&&!X)throw Error("Compaction checkpoint commit returned no identity");return X||null}if(Y.required&&Z.sessionId)throw Error("Compaction checkpoint storage is unavailable")}catch(K){if($$.warn("[Loop] 保存压缩数据失败:",K),Y.required)throw K}return null}async function V0($){let{deps:Z,context:J,state:W,assistantContent:Y,assistantReasoningContent:K,lastMessageUuid:X,controlPrompt:Q}=$;W.appendAssistant({role:"assistant",content:Y,reasoningContent:K});let H=X,V=await v0(Z,J,Y,H,K);if(V)H=V;if(Q!==void 0){let z={role:"user",content:Q,metadata:f0};W.appendControl("user",z);let w=await r0(Z,J,Q,H,f0);if(w)H=w}return H}import{createHash as k6}from"node:crypto";import{promises as n9}from"node:fs";import o9 from"node:path";import{nanoid as J$}from"nanoid";import*as $0 from"node:fs/promises";import*as Z$ from"node:path";import AJ from"write-file-atomic";var _J={enabled:!0,maxIndexLines:200};var P9="memory",cZ="MEMORY.md",iZ="<!-- blade:auto-memory-topics:start -->",d1="<!-- blade:auto-memory-topics:end -->",N9={realpath:!1,retries:{retries:5,factor:1.2,minTimeout:20,maxTimeout:100,randomize:!0}},_9=new x$,bJ;function fJ($){return $.trim().replace(/\s+/g," ")}function A9($){return fJ($.replace(/^- \[\d{4}-\d{2}-\d{2}\] /,""))}function b9($){return[iZ,"## Auto-consolidated topics",...$.map((Z)=>`- [${Z}](${Z}.md)`),d1].join(`
|
|
4
4
|
`)}function y9($,Z){let J=b9(Z),W=$.indexOf(iZ),Y=$.indexOf(d1,Math.max(0,W));if(W>=0&&Y>=W)return $.slice(0,W)+J+$.slice(Y+d1.length);if(!$)return`${J}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{e as U3,f as H3,g as R3,h as s0,i as q3}from"./chunk-
|
|
1
|
+
import{e as U3,f as H3,g as R3,h as s0,i as q3}from"./chunk-zmbknsyr.js";import{j as o1}from"./chunk-hnvvve5d.js";import{v as a0,w as y2}from"./chunk-d4agyayp.js";import{A as m0,x as g2,y as p2,z as v2}from"./chunk-z9jxsh6w.js";import{B as C2,C as U$,D as H$,E as F$,F as z0,G as N$}from"./chunk-q4adhq22.js";import{$ as I2,Ea as u3,J as B2,K as u1,L as v3,O as D2,P as e0,Q as d4,R as i1,S as g$,T as A4,U as j4,V as K0,W as L2,X as M2,Y as D$,Z as w1,aa as R2,ba as b4,ca as j0,da as H0,ga as q1,ha as E1,ia as O5,ja as q2,ka as E2,la as r2,ma as e2,na as O3,oa as $3,pa as Q3,qa as Z3,ra as J3,sa as Y3,ta as X3,wa as w3,za as W5}from"./chunk-wzxxjj1a.js";import{La as q$,Ra as uO}from"./chunk-8pytaed9.js";import{Ua as A2,Wa as j2,Xa as b2,Ya as T2,cb as V4,fb as c3,gb as c4,hb as S2,ib as f2,jb as i3,kb as l3,lb as i4,mb as a3,nb as g0,ob as N3,pb as B3,qb as D3,rb as P2,sb as k2,tb as m2,ub as h2,vb as W$,wb as r4}from"./chunk-9fyjyk2f.js";import{Kb as dO,Lb as a,Nb as P,Ob as x2,Zb as M4,ic as y0}from"./chunk-0wrz9qv8.js";import{tc as T4}from"./chunk-fdr4fcrf.js";import{$c as B4,Dd as w2,Jc as V2,Nd as A1,Od as h0,Tc as z2,Vd as I1,Wd as I4,Xd as R1,Zd as o0,_c as G2,ad as W2,ae as D4,bd as D1,cd as K2,fd as U4,fe as N2,ge as x4,he as L4,ie as g,sd as _2}from"./chunk-2kx9ygzc.js";import{Ge as U2,Ne as H2,Oe as F2}from"./chunk-ztreczac.js";import{hf as L3,lf as M3,mf as A3,nf as j3,of as b3,pf as y4,qf as T3,rf as I3}from"./chunk-p6586ftx.js";import{Qf as r3,Uf as MO,Yf as f$,dg as nO}from"./chunk-d86vygx0.js";import{eg as c1}from"./chunk-5yyp6njq.js";import{xg as J2}from"./chunk-zfxcef0z.js";import{zg as B1}from"./chunk-rf3eeens.js";import{$g as X2,Ig as e3,Mg as s2,Qg as H1,Rg as F1,Vg as B5,Yg as eO,Zg as N1,bh as s4}from"./chunk-s9g7t23a.js";import{uh as P$,vh as Y2}from"./chunk-1cy4ab77.js";import{Ah as l0,zh as b$}from"./chunk-f1x80zky.js";import{Ai as Z2,Ni as T$,Sh as R$,Si as U1,gi as s$,ji as r$,li as e$,mi as O2,ni as h$,oi as y$,pi as K$,vi as $2,yi as Q2}from"./chunk-6qp15s2m.js";import{Vi as F4}from"./chunk-qpmvp4q2.js";import{Xi as a1,_i as N4}from"./chunk-tm3789m3.js";import{cj as GO}from"./chunk-qdbbke8f.js";import{Ej as ZO,Gj as y,Ij as G,Jj as oO,Lj as zO}from"./chunk-rmfzym94.js";import{Qj as f0}from"./chunk-j89qk7bp.js";import{Sj as C$,Tj as o$,Vj as S$,Wj as t$}from"./chunk-0eajnhrj.js";import{Yj as i0}from"./chunk-rytpfm4a.js";import{dk as t4}from"./chunk-ggdgk3gy.js";import{Ak as wO,Ck as g1,Kk as L$,gk as l1}from"./chunk-n52n2w5v.js";import{Nk as a4}from"./chunk-cjfb4kjp.js";var H8={port:{type:"number",describe:"Port to listen on (0 for auto)",default:0},hostname:{type:"string",describe:"Hostname to listen on",default:"127.0.0.1"},cors:{type:"array",describe:"Additional domains to allow for CORS",default:[]}};function F8(O){return{port:O.port??0,hostname:O.hostname??"127.0.0.1",cors:O.cors??[]}}import{existsSync as e4,readFileSync as f1}from"node:fs";import{createServer as c6}from"node:http";import{networkInterfaces as i6}from"node:os";import{dirname as l6,extname as a6,join as E0}from"node:path";import{fileURLToPath as n6}from"node:url";import{brotliCompressSync as o6,gzipSync as t6,constants as s6}from"node:zlib";import{Hono as r6}from"hono";import{cors as e6}from"hono/cors";import{WebSocketServer as O8}from"ws";var c0=ZO("Service"),f5=30000,P5=new Set(["completed","failed","cancelled","interrupted"]);class z4{dispatch;store;tickMs;timer;unsubscribeBus;ticking=!1;inFlight=new Set;constructor(O){this.dispatch=O.dispatch,this.store=O.store??W$.getInstance(),this.tickMs=O.tickMs??f5}start(){if(this.timer)return;c0.info("[TaskScheduler] Starting scheduler tick loop"),this.timer=setInterval(()=>{this.tick()},this.tickMs),this.timer.unref?.(),this.unsubscribeBus=P.subscribe((O)=>{if(O.type!=="task.status")return;let $=O.properties.taskStatus;if(typeof $!=="string"||!P5.has($))return;this.recordTerminalStatus(O.sessionId,$,typeof O.properties.taskStatusReason==="string"?O.properties.taskStatusReason:void 0)}),this.tick()}stop(){if(this.timer)clearInterval(this.timer),this.timer=void 0,this.unsubscribeBus?.(),this.unsubscribeBus=void 0,c0.info("[TaskScheduler] Stopped scheduler tick loop")}async tick(O=new Date){if(this.ticking)return;this.ticking=!0;try{let $=await this.store.list();for(let Q of $)await this.evaluate(Q,O)}catch($){c0.warn("[TaskScheduler] Tick failed:",$)}finally{this.ticking=!1}}async evaluate(O,$){if(!O.enabled)return;if(this.inFlight.has(O.id))return;if(O.expiresAt&&new Date(O.expiresAt).getTime()<=$.getTime()){await this.store.update(O.id,{enabled:!1,nextRunAt:null}),c0.info(`[TaskScheduler] Schedule ${O.id} expired; disabled`);return}if(!O.nextRunAt)return;if(!(new Date(O.nextRunAt).getTime()<=$.getTime()))return;await this.fire(O,$)}async fire(O,$=new Date,Q={}){if(this.inFlight.has(O.id))throw Error(`Schedule ${O.id} is already dispatching`);this.inFlight.add(O.id);let Z=$.toISOString();try{let J=await this.dispatch({prompt:O.prompt,title:O.title??k5(O),sourceProjectPath:O.projectPath,isolation:O.dispatch.isolation??"worktree",permissionMode:O.dispatch.permissionMode??"default",modelId:O.dispatch.modelId,reasoningEffort:O.dispatch.reasoningEffort,serviceTier:O.dispatch.serviceTier,responseVerbosity:O.dispatch.responseVerbosity,communicationStyle:O.dispatch.communicationStyle}),X=O.trigger.kind==="once"?null:Q.manual?O.nextRunAt?new Date(O.nextRunAt):null:V4(O.trigger,$,$);await this.store.update(O.id,{lastRunAt:Z,lastRunSessionId:J.session.sessionId,lastStatus:J.status,lastError:void 0,runCount:O.runCount+1,nextRunAt:X?X.toISOString():null,enabled:O.trigger.kind==="once"?!1:O.enabled}),P.publish({sessionId:J.session.sessionId,projectPath:O.projectPath},"schedule.fired",{scheduleId:O.id,firedAt:Z,sessionId:J.session.sessionId,runId:J.runId,status:J.status}),c0.info(`[TaskScheduler] Fired schedule ${O.id} -> session ${J.session.sessionId} (${J.status})`)}catch(J){let X=J instanceof Error?J.message:String(J);c0.warn(`[TaskScheduler] Schedule ${O.id} dispatch failed:`,J);let V=O.trigger.kind==="once"?null:Q.manual?O.nextRunAt?new Date(O.nextRunAt):null:V4(O.trigger,$,$);await this.store.update(O.id,{lastRunAt:Z,lastStatus:"error",lastError:X,nextRunAt:V?V.toISOString():null,enabled:O.trigger.kind==="once"?!1:O.enabled})}finally{this.inFlight.delete(O.id)}}async recordTerminalStatus(O,$,Q){let J=(await this.store.list()).find((X)=>X.lastRunSessionId===O);if(!J)return;await this.store.update(J.id,{lastStatus:$,...Q?{lastError:Q}:{lastError:void 0}})}}function k5(O){return`Scheduled: ${O.prompt.trim().replace(/\s+/g," ").slice(0,60)}`}class _O extends Error{code;statusCode;details;constructor(O,$,Q=500,Z){super($);this.code=O;this.statusCode=Q;this.details=Z;this.name="BladeServerError"}toObject(){return{error:{code:this.code,message:this.message,...this.details?{details:this.details}:{}}}}}class i extends _O{constructor(O,$){super("NOT_FOUND",$?`${O} not found: ${$}`:`${O} not found`,404)}}class F extends _O{constructor(O){super("BAD_REQUEST",O,400)}}class v extends _O{constructor(O){super("CONFLICT",O,409)}}class rO extends _O{constructor(O,$){super("TOO_MANY_REQUESTS",O,429,$)}}class LO extends _O{constructor(O="Server is shutting down"){super("SERVICE_UNAVAILABLE",O,503)}}class A0 extends _O{constructor(O){super("SESSION_WORKSPACE_UNAVAILABLE","This session workspace is no longer available",409,{reason:O})}}class vO extends _O{constructor(){super("AMBIGUOUS_SESSION","Multiple workspaces contain this session ID; projectPath is required",409)}}class VO extends _O{constructor(O="Internal server error"){super("INTERNAL_ERROR",O,500)}}var j8=G.Object({error:G.Object({code:G.String(),message:G.String(),details:G.Optional(G.Record(G.String(),G.Unknown()))})});import{Hono as m5}from"hono";var G4=ZO("Service"),h5=G.Object({updates:G.Record(G.String(),G.Any()),options:G.Optional(G.Object({scope:G.Optional(zO(["local","project","global"])),immediate:G.Optional(G.Boolean())}))});function y5(O){return{currentModelId:O.currentModelId,permissionMode:O.permissionMode,language:O.language,codeTheme:O.codeTheme,uiTheme:O.uiTheme,autoSaveSessions:O.autoSaveSessions,notifyBuild:O.notifyBuild,notifyErrors:O.notifyErrors,notifySounds:O.notifySounds,privacyTelemetry:O.privacyTelemetry,privacyCrash:O.privacyCrash,agentTeamsEnabled:O.agentTeamsEnabled===!0,communicationStyle:O.communicationStyle,maxConcurrentTasks:O.maxConcurrentTasks,maxQueuedTasks:O.maxQueuedTasks,maxQueuedTaskBytes:O.maxQueuedTaskBytes,maxResidentSessionRuntimes:O.maxResidentSessionRuntimes,sessionRuntimeIdleMs:O.sessionRuntimeIdleMs,maxResidentSessionProjections:O.maxResidentSessionProjections,sessionProjectionIdleMs:O.sessionProjectionIdleMs}}var _$=()=>{let O=new m5;return O.get("/",async($)=>{try{let Q=MO();return $.json(Q?y5(Q):{})}catch(Q){return G4.error("[ConfigRoutes] Failed to get config:",Q),$.json({})}}),O.put("/",async($)=>{try{let Q=await $.req.json(),Z=y(h5,Q);if(!Z.success)throw new F("Invalid config update format");let{updates:J,options:X}=Z.data;return await nO().updateConfig(J,X),$.json({success:!0,updates:J})}catch(Q){if(Q instanceof K$)throw new F(Q.message);throw G4.error("[ConfigRoutes] Failed to update config:",Q),Q}}),O.get("/permissions",async($)=>{try{let Q=MO();return $.json(Q?.permissions||{})}catch(Q){return G4.error("[ConfigRoutes] Failed to get permissions:",Q),$.json({})}}),O};import{Hono as g5}from"hono";import{streamSSE as p5}from"hono/streaming";function w$(O){let $="";if(O.id!==void 0)$+=`id: ${O.id}
|
|
2
2
|
`;if(O.event!==void 0)$+=`event: ${O.event}
|
|
3
3
|
`;for(let Q of O.data.split(/\r\n|\r|\n/))$+=`data: ${Q}
|
|
4
4
|
`;if(O.retry!==void 0)$+=`retry: ${O.retry}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{$e as q1,Ae as n2,Be as U1,Ce as A0,De as B1,Ee as H1,Ge as d2,Ne as i2,Oe as C0,Ve as p_,Xe as N1,Ze as r2,_e as o2,af as a2,pe as u2,qe as e,re as h2,se as Z1,te as l2,ue as v,ve as G1,we as c2,xe as p2,ye as V1,ze as L1}from"./chunk-ztreczac.js";import{wg as o_}from"./chunk-zfxcef0z.js";import{sh as a_}from"./chunk-1cy4ab77.js";import{Wi as v2,Xi as P2,Yi as x_,Zi as Q0,_i as w_}from"./chunk-tm3789m3.js";import{cj as f1}from"./chunk-qdbbke8f.js";import{Ej as H0}from"./chunk-rmfzym94.js";import{Rj as i_,Uj as r_}from"./chunk-0eajnhrj.js";import{Yj as __}from"./chunk-
|
|
1
|
+
import{$e as q1,Ae as n2,Be as U1,Ce as A0,De as B1,Ee as H1,Ge as d2,Ne as i2,Oe as C0,Ve as p_,Xe as N1,Ze as r2,_e as o2,af as a2,pe as u2,qe as e,re as h2,se as Z1,te as l2,ue as v,ve as G1,we as c2,xe as p2,ye as V1,ze as L1}from"./chunk-ztreczac.js";import{wg as o_}from"./chunk-zfxcef0z.js";import{sh as a_}from"./chunk-1cy4ab77.js";import{Wi as v2,Xi as P2,Yi as x_,Zi as Q0,_i as w_}from"./chunk-tm3789m3.js";import{cj as f1}from"./chunk-qdbbke8f.js";import{Ej as H0}from"./chunk-rmfzym94.js";import{Rj as i_,Uj as r_}from"./chunk-0eajnhrj.js";import{Yj as __}from"./chunk-rytpfm4a.js";import{Ak as M0,Bk as c_,Ck as A,Dk as P,Ek as I,Fk as E1,Gk as F1,Hk as M_,Ik as z1,Jk as b1,Kk as q_,gk as h,qk as o,rk as p,sk as S2,tk as n,uk as d,vk as I2,wk as K0,xk as Y1,yk as m2,zk as K_}from"./chunk-n52n2w5v.js";import{readdir as b_,readFile as V_,rm as f_,stat as E0}from"node:fs/promises";import*as N from"node:path";import{nanoid as m}from"nanoid";import{createHash as F4,randomUUID as z4}from"node:crypto";import*as W_ from"node:fs/promises";import*as W0 from"node:path";import D4 from"proper-lockfile";function cX(_){return Object.freeze({kind:"local",root:_})}function pX(_,X){let $=o(X);if(p($.collisionIdentity)!==_)throw Error("ACP remote workspace durable state is invalid");return Object.freeze({kind:"acp-remote",root:_,descriptor:$})}function nX(_,X){return _.kind==="acp-remote"?`${_.kind}\x00${_.root}\x00${_.descriptor.exactIdentity}\x00${X}`:`${_.kind}\x00${_.root}\x00${X}`}async function H_(_,X){if(_.kind==="local")return X(K_(_.root));return n(_.root,($)=>X(String($),$))}async function dX(_,X,$){return H_(_,(W,J)=>$(J?{storageRoot:W,transcriptPath:I(J,X),inboxPath:F1(J,X),goalPath:z1(J,X),remoteScope:J}:{storageRoot:W,transcriptPath:P(_.root,X),inboxPath:E1(_.root,X),goalPath:M_(_.root,X)}))}import{execFileSync as T4}from"node:child_process";import{createHash as C4}from"node:crypto";import{readFileSync as K4}from"node:fs";var M4=/^[a-f0-9]{64}$/;function D1(_){if(!_||typeof _!=="object")return!1;let X=_;return(X.platform==="linux"||X.platform==="darwin"||X.platform==="win32")&&typeof X.fingerprint==="string"&&M4.test(X.fingerprint)}var R1={readFile:(_)=>K4(_,"utf8"),execFile:(_,X)=>T4(_,X,{encoding:"utf8",timeout:_==="powershell.exe"?3000:2000,windowsHide:!0})},A4=(_)=>{try{return process.kill(_,0),!0}catch(X){return X instanceof Error&&"code"in X&&X.code==="EPERM"}};function x0(_,X){return{platform:_,fingerprint:C4("sha256").update(`${_}\x00${X}`).digest("hex")}}function E4(_,X){let $=X.readFile(`/proc/${_}/stat`).trim(),W=$.lastIndexOf(")");if(W<0)throw Error("Invalid /proc process stat");let O=$.slice(W+2).split(/\s+/)[19];if(!O||!/^\d+$/.test(O))throw Error("Missing process start ticks");return O}function m_(_,X=process.platform,$=R1){if(!Number.isInteger(_)||_<=1)return;try{if(X==="linux")return x0(X,E4(_,$));if(X==="darwin"){let W=$.execFile("ps",["-o","lstart=","-p",String(_)]).trim();return W?x0(X,W):void 0}if(X==="win32"){let W=`(Get-CimInstance Win32_Process -Filter "ProcessId = ${_}").CreationDate.ToUniversalTime().ToString('O')`,J=$.execFile("powershell.exe",["-NoProfile","-NonInteractive","-Command",W]).trim();return J?x0(X,J):void 0}}catch{return}return}function tX(_,X){return m_(_,X.platform)?.fingerprint===X.fingerprint}function sX(_,X,$=R1,W=A4){if(!Number.isInteger(_)||_<=1)return!1;let J=m_(_,X.platform,$);if(J)return J.fingerprint===X.fingerprint;return!W(_)}var j1=1;function R4(_,X){let $=F4("sha256").update(X).digest("hex");return W0.join(K_(_),".locks",`${$}.lock`)}function R_(_,X){return _ instanceof Error&&"code"in _&&_.code===X}async function k0(_){try{let X=JSON.parse(await W_.readFile(_,"utf8"));if(X.version!==j1||typeof X.sessionId!=="string"||typeof X.ownerId!=="string"||!Number.isInteger(X.pid)||(X.pid??0)<=0||X.processIdentity!==void 0&&!D1(X.processIdentity)||typeof X.acquiredAt!=="string")return;return X}catch(X){if(R_(X,"ENOENT")||X instanceof SyntaxError)return;throw X}}async function w1(_){let X=await k0(_);if(X)return X;return await new Promise(($)=>setTimeout($,10)),k0(_)}function w4(_){try{return process.kill(_,0),!0}catch(X){return!R_(X,"ESRCH")}}async function x1(_,X){let $;try{return $=await W_.open(_,"wx",384),await $.writeFile(`${JSON.stringify(X)}
|
|
2
2
|
`,"utf8"),!0}catch(W){if(R_(W,"EEXIST"))return!1;if($)await W_.unlink(_).catch(()=>{return});throw W}finally{await $?.close().catch(()=>{return})}}class $_ extends Error{code="BLADE_SESSION_IN_USE";constructor(_){super(_?`Session is already active in another Blade process (PID ${_}). Stop that process or choose a different session.`:"Session is already active in another Blade process. Stop that process or choose a different session.");this.name="SessionInUseError"}}async function k1(_,X,$=!1){let W,J;try{J=await D4.lock(_,{realpath:!1,retries:$?{retries:50,minTimeout:10,maxTimeout:100,factor:1.2}:0,onCompromised:(Q)=>{W=Q}})}catch(Q){if(R_(Q,"ELOCKED"))throw new $_;throw Q}let O=()=>{if(W)throw W};try{O();let Q=await X(O);return O(),Q}finally{await J()}}class u{filePath;record;stateStorage;released=!1;constructor(_,X,$){this.filePath=_;this.record=X;this.stateStorage=$}static async acquireForStorage(_,X){if(X.kind==="local")return u.acquire(_,X.root);return H_(X,($,W)=>{if(!W||$!==X.root)throw Error("ACP remote session lease scope is invalid");return u.acquireRemote(_,W,X)})}static async acquire(_,X=f1()){return u.acquireAtPath(_,R4(X,_))}static async acquireRemote(_,X,$){let W=b1(X,_);try{await d(X,W)}catch(O){if(O.code!=="ENOENT")throw O}let J=await u.acquireAtPath(_,W);try{return await d(X,W),new u(W,J.record,$)}catch(O){throw await J.release(),O}}static async acquireAtPath(_,X){return await W_.mkdir(W0.dirname(X),{recursive:!0,mode:448}),k1(X,async($)=>{let W={version:j1,sessionId:_,ownerId:z4(),pid:process.pid,processIdentity:m_(process.pid),acquiredAt:new Date().toISOString()};if($(),await x1(X,W))return new u(X,W);let J=await w1(X);if(!J||J.sessionId!==_)throw new $_;if(w4(J.pid)){let O=J.processIdentity?m_(J.pid,J.processIdentity.platform):void 0;if(!O||O.fingerprint===J.processIdentity?.fingerprint)throw new $_(J.pid)}if($(),await W_.unlink(X).catch((O)=>{if(!R_(O,"ENOENT"))throw O}),$(),await x1(X,W))return new u(X,W);throw new $_((await w1(X))?.pid)})}async release(){if(this.released)return;let _=()=>k1(this.filePath,async(X)=>{if((await k0(this.filePath))?.ownerId!==this.record.ownerId)return;X(),await W_.unlink(this.filePath).catch((W)=>{if(!R_(W,"ENOENT"))throw W})},!0);if(this.stateStorage?.kind==="acp-remote")await H_(this.stateStorage,_);else await _();this.released=!0}}import{createHash as O0}from"node:crypto";import{constants as A_,promises as O_}from"node:fs";import G_ from"node:path";import{Mutex as x4}from"async-mutex";var y1=128,g1=67108864,k4=24576,S1=65536,f0=1,h1=/^[a-f0-9]{64}$/,b4=/^[a-f0-9]{64}\.txt$/,l1=64,f4=new Set(["EBUSY","EAGAIN","EMFILE","ENFILE"]),Y0=`
|
|
3
3
|
|
|
4
4
|
...[middle omitted; read the private prompt artifact for the complete request]...
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as T,b as W,c as X,d as Y}from"./chunk-
|
|
1
|
+
import{a as T,b as W,c as X,d as Y}from"./chunk-1nt1vdf1.js";import"./chunk-zmbknsyr.js";import"./chunk-hnvvve5d.js";import"./chunk-d4agyayp.js";import"./chunk-z9jxsh6w.js";import"./chunk-q4adhq22.js";import"./chunk-wzxxjj1a.js";import"./chunk-vzdsext4.js";import"./chunk-8pytaed9.js";import"./chunk-9fyjyk2f.js";import"./chunk-0wrz9qv8.js";import"./chunk-fdr4fcrf.js";import"./chunk-2kx9ygzc.js";import"./chunk-egss0m1x.js";import"./chunk-ztreczac.js";import"./chunk-p6586ftx.js";import{zf as R}from"./chunk-h1e37bta.js";import"./chunk-p0wyhp5a.js";import{Vf as Q}from"./chunk-d86vygx0.js";import"./chunk-v508x7cg.js";import"./chunk-5yyp6njq.js";import"./chunk-myvt7yjm.js";import"./chunk-4fbpydtn.js";import"./chunk-3cas6rv5.js";import"./chunk-zfxcef0z.js";import"./chunk-rf3eeens.js";import"./chunk-s9g7t23a.js";import"./chunk-kehgewqh.js";import"./chunk-kkzznz4w.js";import"./chunk-1cy4ab77.js";import"./chunk-7ajvrtb3.js";import"./chunk-f1x80zky.js";import"./chunk-ys8gysg8.js";import"./chunk-6qp15s2m.js";import"./chunk-qpmvp4q2.js";import"./chunk-tm3789m3.js";import"./chunk-qdbbke8f.js";import"./chunk-wezr6wfq.js";import"./chunk-rmfzym94.js";import"./chunk-j89qk7bp.js";import"./chunk-0eajnhrj.js";import{Yj as M}from"./chunk-rytpfm4a.js";import"./chunk-ggdgk3gy.js";import"./chunk-ky592ay9.js";import"./chunk-n52n2w5v.js";import"./chunk-cjfb4kjp.js";import m from"chalk";import K from"open";var A=`
|
|
2
2
|
____ _ _
|
|
3
3
|
| __ )| | __ _ __| | ___
|
|
4
4
|
| _ \\| |/ _\` |/ _\` |/ _ \\
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{ce as a,de as b,ee as c,fe as d,ge as e,he as f,ie as g}from"./chunk-
|
|
1
|
+
import{ce as a,de as b,ee as c,fe as d,ge as e,he as f,ie as g}from"./chunk-2kx9ygzc.js";import"./chunk-egss0m1x.js";import"./chunk-ztreczac.js";import"./chunk-p6586ftx.js";import"./chunk-zfxcef0z.js";import"./chunk-1cy4ab77.js";import"./chunk-ys8gysg8.js";import"./chunk-tm3789m3.js";import"./chunk-qdbbke8f.js";import"./chunk-rmfzym94.js";import"./chunk-0eajnhrj.js";import"./chunk-rytpfm4a.js";import"./chunk-n52n2w5v.js";import"./chunk-cjfb4kjp.js";export{b as __setSessionSnapshotIOForTesting,c as __resetSessionSnapshotIOForTesting,g as SessionService,d as SessionMissingCreationError,e as SessionArchivedError,f as SessionArchiveConflictError,a as STALE_EMPTY_SESSION_AGE_MS};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{e as JX,f as YX,h as S$,i as T4}from"./chunk-g88adq1a.js";import{l as YZ,m as XZ,n as ZZ}from"./chunk-hasgf62t.js";import{A as q4,y as MJ,z as TJ}from"./chunk-s8cx6pzp.js";import{Aa as QY,Ca as UY,Ea as lY,I as dY,M as LZ,O as m6,P as y6,Q as jY,W as AY,X as bY,_ as MY,da as i$,fa as SJ,ga as kJ,ia as TY,ka as q8,la as BX,ma as wX,pa as PX,qa as AX,ua as a9,va as w3,xa as F3,ya as L3,za as BZ}from"./chunk-0qfm5awe.js";import"./chunk-vzdsext4.js";import{Ma as E5,Na as g5,Oa as m5,Ra as FZ}from"./chunk-p6g53dbp.js";import{Ta as PY}from"./chunk-9fyjyk2f.js";import{Mb as BY,Nb as F4,Zb as wY,ic as b6}from"./chunk-m7cv44cg.js";import{tc as H8}from"./chunk-fdr4fcrf.js";import{Dd as _Y,Nd as bJ,Od as m2,Sd as yJ,Xd as IJ,Zd as t8,fe as z8,ie as a0}from"./chunk-r2ev8kdg.js";import"./chunk-egss0m1x.js";import{Me as vJ,Ne as A6,Oe as VJ}from"./chunk-ztreczac.js";import{jf as JY,kf as U4}from"./chunk-p6586ftx.js";import{xf as $Z}from"./chunk-je908ygr.js";import{Bf as Y1,yf as W8,zf as _4}from"./chunk-pq9v80gg.js";import"./chunk-p0wyhp5a.js";import{Ff as R2,Gf as L$,Hf as a1,If as z9,Jf as o8,Kf as CJ,Lf as s3,Mf as I9,Nf as a5,Of as e3,Pf as v2,Qf as m0,Rf as HZ,Sf as B$,Tf as eX,Uf as i4,Vf as O8,Yf as $Y,dg as z$}from"./chunk-7m1bf6zd.js";import"./chunk-v508x7cg.js";import"./chunk-5yyp6njq.js";import"./chunk-myvt7yjm.js";import"./chunk-4fbpydtn.js";import{vg as S9}from"./chunk-3cas6rv5.js";import"./chunk-zfxcef0z.js";import"./chunk-x5f2d1n2.js";import{Ig as W4,Kg as pX,Pg as LX,Yg as WZ}from"./chunk-sqrhdczm.js";import"./chunk-kehgewqh.js";import"./chunk-kkzznz4w.js";import"./chunk-1cy4ab77.js";import"./chunk-7ajvrtb3.js";import{Ah as h$,yh as O9}from"./chunk-vnbyb9dq.js";import"./chunk-ys8gysg8.js";import{Ni as OZ,Si as FX,Ti as NZ}from"./chunk-pfjg8bjg.js";import{Vi as mJ}from"./chunk-qpmvp4q2.js";import{Wi as p2,Xi as e8,Zi as N9}from"./chunk-tm3789m3.js";import{cj as K$}from"./chunk-qdbbke8f.js";import"./chunk-wezr6wfq.js";import{Bj as _Z,Ej as H1}from"./chunk-rmfzym94.js";import{Mj as s5,Nj as e5,Qj as R1}from"./chunk-j89qk7bp.js";import"./chunk-0eajnhrj.js";import{ak as c5}from"./chunk-25ma8vb3.js";import{dk as l9}from"./chunk-ggdgk3gy.js";import"./chunk-ky592ay9.js";import{Ak as eJ,gk as K8}from"./chunk-n52n2w5v.js";import{Nk as Y4}from"./chunk-cjfb4kjp.js";import{useMemoizedFn as G6}from"ahooks";import{useEffect as _z,useState as K6}from"react";import{useMemoizedFn as i0}from"ahooks";import tX from"ansi-escapes";import{Box as m1,useStdout as Zz}from"ink";import{useEffect as J1,useMemo as Qz,useRef as I2,useState as sX}from"react";import{useShallow as AZ}from"zustand/react/shallow";import{useStore as PZ}from"zustand";function z0($){return PZ(v2,$)}var bZ=[],V2=()=>z0(($)=>$.session.sessionId),O1=()=>z0(($)=>$.session.workspaceRoot),V8=()=>z0(($)=>$.session.messages),i9=()=>z0(($)=>$.session.clearCount),o9=()=>z0(($)=>$.session.isCompacting),n9=()=>z0(($)=>$.session.tokenUsage.estimatedCostUsd),t9=()=>z0(($)=>{let{totalInputTokens:J,cacheReadTokens:Y,cacheWriteTokens:Z}=$.session.tokenUsage;return a9({totalInputTokens:J,cacheReadTokens:Y,cacheWriteTokens:Z}).hitRate});var j8=()=>z0(($)=>$.session.providerRecovery),s9=()=>z0(($)=>$.session.turnActivity),e9=()=>z0(($)=>$.session.actionStationarity),d1=()=>z0(($)=>$.session.actions),$J=()=>z0(($)=>{let{totalTokens:J,maxContextTokens:Y}=$.session.tokenUsage;if(Y<=0)return 100;let Z=Math.max(0,100-J/Y*100);return Math.round(Z)}),JJ=()=>z0(($)=>$.app.initializationStatus),YJ=()=>z0(($)=>$.app.initializationError),j2=()=>z0(($)=>$.app.activeModal),XJ=()=>z0(($)=>$.app.tasks),ZJ=()=>z0(($)=>$.app.modelEditorTarget),QJ=()=>z0(($)=>$.app.sessionSelectorData),UJ=()=>z0(($)=>$.app.sessionHistoryViewerData),GJ=()=>z0(($)=>$.app.taskAttentionStatus),h8=()=>z0(($)=>$.app.taskAttentionUnreadKeys),KJ=()=>z0(($)=>$.app.awaitingSecondCtrlC),N1=()=>z0(($)=>$.app.actions),h2=()=>z0(($)=>$.app.sideConversation),zJ=()=>z0(($)=>$.app.teams),E8=()=>z0(($)=>$.app.initializationStatus==="ready"),qJ=()=>z0(($)=>$.app.tasks.length>0),E2=()=>z0(($)=>$.config.config?.permissionMode||"default"),_J=()=>z0(($)=>$.config.config?.models??bZ),g8=()=>z0(($)=>{let J=$.config.config;if(!J)return;let Y=J.currentModelId;return J.models.find((X)=>X.id===Y)??J.models[0]}),m8=()=>z0(($)=>$.config.config?.currentModelId),OJ=()=>z0(($)=>$.config.config?.agentTeamsEnabled===!0),D0=()=>z0(($)=>{return L$.getTheme()}),NJ=()=>z0(($)=>$.config.config?.codeTheme??"default"),s0=()=>z0(($)=>$.focus.currentFocus),HJ=()=>z0(($)=>$.focus.actions),g2=()=>z0(($)=>$.command.isProcessing),WJ=()=>z0(($)=>$.command.actions),p8=()=>z0(($)=>$.app.followUpQueue),FJ=()=>z0(($)=>$.app.followUpQueueMutation),LJ=()=>z0(($)=>$.command.recoveredSteeringCount),x8=()=>z0(($)=>$.app.reasoningEffort!=="off"),c8=()=>z0(($)=>$.app.reasoningEffort),u8=()=>z0(($)=>$.app.serviceTier),d8=()=>z0(($)=>$.app.responseVerbosity),l8=()=>z0(($)=>$.app.communicationStyle),r8=()=>z0(($)=>$.session.currentThinkingContent),BJ=()=>z0(($)=>$.session.thinkingExpanded),a8=()=>z0(($)=>$.session.currentStreamingMessageId),i8=()=>z0(AZ(($)=>({lines:$.session.currentStreamingLines,tail:$.session.currentStreamingTail,lineCount:$.session.currentStreamingLineCount,version:$.session.currentStreamingVersion}))),wJ=()=>z0(($)=>$.session.finalizingStreamingMessageId),PJ=()=>z0(($)=>$.session.historyExpanded),AJ=()=>z0(($)=>$.session.expandedMessageCount);import{randomUUID as H7}from"node:crypto";import{useMemoizedFn as X1}from"ahooks";import{useEffect as l1,useMemo as FY,useRef as N4}from"react";function MZ($,J){try{return $.code===J.code&&$.message===J.message&&$.retryable===J.retryable&&$.resource===J.resource}catch{return!1}}class q6{options;requested=!1;waitingForIdle=!1;disposed=!1;generation=0;wakeEpoch=0;idleEpoch=0;attempt=0;recoveryStartedAt=null;scheduledToken=null;activeAttemptToken=null;activeRunController=null;retryTimer=null;deadlineTimer=null;now;scheduleCallback;setTimerCallback;clearTimerCallback;constructor($){this.options=$;this.now=$.now??Date.now,this.scheduleCallback=$.scheduleMicrotask??queueMicrotask,this.setTimerCallback=$.setTimer??setTimeout,this.clearTimerCallback=$.clearTimer??clearTimeout}request(){if(this.disposed)return;if(this.wakeEpoch++,this.requested=!0,this.waitingForIdle||this.retryTimer)return;this.scheduleIfRunnable()}notifyIdle(){if(this.disposed)return;if(this.idleEpoch++,this.retryTimer)return;this.waitingForIdle=!1,this.scheduleIfRunnable()}dispose(){if(this.disposed)return;this.disposed=!0,this.generation++,this.requested=!1,this.waitingForIdle=!1,this.scheduledToken=null,this.clearOwnedTimer("retry"),this.clearOwnedTimer("deadline"),this.activeAttemptToken=null;let $=this.activeRunController;this.activeRunController=null,$?.abort("pending-resume-coordinator-disposed"),this.resetEpisodeBudget()}scheduleIfRunnable(){if(this.disposed||!this.requested||this.scheduledToken||this.activeAttemptToken||this.retryTimer||this.waitingForIdle)return;if(!this.options.canRun()){this.waitingForIdle=!0;return}let $=this.generation,J={};this.scheduledToken=J;try{this.scheduleCallback(()=>{if(this.disposed||$!==this.generation||this.scheduledToken!==J)return;this.scheduledToken=null,this.flush($).catch((Y)=>{this.handleUnexpectedFailure(Y,$)})})}catch(Y){this.handleUnexpectedFailure(Y,$)}}async flush($){if(this.disposed||$!==this.generation||this.activeAttemptToken||!this.requested||this.retryTimer||this.waitingForIdle)return;if(!this.options.canRun()){this.waitingForIdle=!0;return}let J={},Y=new AbortController,Z=this.wakeEpoch,X=this.idleEpoch;if(this.attempt++,this.recoveryStartedAt===null)this.recoveryStartedAt=this.now(),this.installDeadlineTimer($);this.activeAttemptToken=J,this.activeRunController=Y;let Q;try{Q=await this.options.run(Y.signal)}finally{if(this.activeAttemptToken===J){if(this.activeAttemptToken=null,this.activeRunController=null,!this.disposed&&$!==this.generation)this.scheduleIfRunnable()}}if(this.disposed||$!==this.generation)return;if(Q.status==="completed"){let U=this.wakeEpoch!==Z;if(this.clearEpisode(),U)this.requested=!0,this.scheduleIfRunnable();return}if(Q.status==="deferred"){if(this.attempt--,this.attempt===0)this.clearOwnedTimer("deadline"),this.resetEpisodeBudget();if(this.requested=!0,this.idleEpoch!==X)this.waitingForIdle=!1,this.scheduleIfRunnable();else this.waitingForIdle=!0;return}this.handleFailure(Q,$)}handleFailure($,J){let Y=m2($.taskFailure),Z=this.options.sessionIdentity;if($.workKind!=="pending_input"||!$.evidence||!Z||!MZ($.taskFailure,$.evidence.taskFailure)){this.terminate("failed",this.attempt,Y);return}let X=TJ({sessionIdentity:Z,failedAttempt:this.attempt,recoveryStartedAt:this.recoveryStartedAt??this.now(),now:this.now(),workStillPending:$.workStillPending,evidence:$.evidence});if(X.phase!=="retry_scheduled"){this.terminate(X.phase,this.attempt,Y);return}this.requested=!0,this.waitingForIdle=!1;let Q={},U=this.setTimerCallback(()=>{if(this.disposed||J!==this.generation||this.retryTimer?.token!==Q)return;this.retryTimer=null,this.scheduleIfRunnable()},X.delayMs);this.retryTimer={handle:U,token:Q},U.unref?.()}handleUnexpectedFailure($,J){if(this.disposed||J!==this.generation)return;this.terminate("failed",Math.max(1,this.attempt),m2($),"pending-resume-coordinator-failed")}installDeadlineTimer($){let J={},Y=this.setTimerCallback(()=>{if(this.disposed||$!==this.generation||this.deadlineTimer?.token!==J)return;this.deadlineTimer=null,this.terminate("exhausted",Math.max(1,this.attempt),bJ("timeout"),"pending-resume-recovery-deadline-exceeded")},MJ);this.deadlineTimer={handle:Y,token:J},Y.unref?.()}terminate($,J,Y,Z){let X=this.activeRunController;if(this.generation++,this.requested=!1,this.waitingForIdle=!1,this.scheduledToken=null,this.clearOwnedTimer("retry"),this.clearOwnedTimer("deadline"),this.resetEpisodeBudget(),Z)X?.abort(Z);try{this.options.onTerminalFailure?.({phase:$,attempt:J,taskFailure:Y})}catch{}}clearEpisode(){this.requested=!1,this.waitingForIdle=!1,this.clearOwnedTimer("retry"),this.clearOwnedTimer("deadline"),this.resetEpisodeBudget()}resetEpisodeBudget(){this.attempt=0,this.recoveryStartedAt=null}clearOwnedTimer($){let J=$==="retry"?this.retryTimer:this.deadlineTimer;if(!J)return;if($==="retry")this.retryTimer=null;else this.deadlineTimer=null;this.clearTimerCallback(J.handle)}}class U8{options;finalized=!1;constructor($){this.options=$}get isFinalized(){return this.finalized}acceptsDeltas(){return!this.finalized&&!this.options.signal.aborted}startTurn(){this.finalized=!1}finalize(){if(!this.acceptsDeltas())return!1;return this.finalized=!0,this.commit(this.options.streamingBuffer.drainPendingBuffers()),!0}abortAndFinalize($){if(this.finalized)return $(),!1;this.finalized=!0;let J=this.options.streamingBuffer.drainPendingBuffers();return $(),this.commit(J),!0}discard(){this.finalized=!0,this.options.streamingBuffer.resetStreamingBuffers(),this.options.discardStreamingMessage(),this.options.clearThinking()}commit($){let J=this.options.getStreamingMessageId();if(J){if($.extraContent)o8(J,$.extraContent);CJ(J)}this.options.finalizeStreamingMessage($.extraContent,$.extraThinking)}}function TZ($){if(!($ instanceof Error))return"未知错误";let Z=$.lastError??$;if(Z.responseBody)try{let U=JSON.parse(Z.responseBody)?.error?.message;if(U){let G=Z.statusCode?` (HTTP ${Z.statusCode})`:"";return`${U}${G}`}}catch{}let X=$.message.match(/Last error:\s*(.+)$/);if(X)return X[1];return $.message}function CZ($){if(!($ instanceof Error))return!1;return $.name==="AbortError"||$.message.includes("aborted")}function RZ($){if(!($ instanceof Error))return!1;let J=$.message;return J.includes("can only concatenate str")||J.includes("image_url")||J.includes("multimodal")||J.includes("vision")||J.includes("does not support images")}function n8($){let J=CZ($),Y=RZ($),Z;if(Y)Z="当前模型不支持图片理解功能。请切换到支持视觉能力的模型(如 Claude 4.5、GPT-5.2、Gemini 3 Pro、Qwen3-VL-Plus 等)后重试。";else Z=TZ($);return{displayMessage:Z,isAbort:J,isVisionNotSupported:Y}}import{appendFileSync as yZ,mkdirSync as IZ,writeFileSync as SZ}from"node:fs";import kZ from"node:os";import _6 from"node:path";var RJ=null;function DZ(){let $=process.env.BLADE_STORAGE_ROOT||_6.join(kZ.homedir(),".blade");return _6.join($,"logs","stream-debug.log")}function fZ($){if(RJ===$)return;let J=_6.dirname($);IZ(J,{recursive:!0,mode:493}),SZ($,`=== Stream Debug Log Started: ${new Date().toISOString()} ===
|
|
1
|
+
import{e as JX,f as YX,h as S$,i as T4}from"./chunk-zmbknsyr.js";import{l as YZ,m as XZ,n as ZZ}from"./chunk-nxtj07c4.js";import{A as q4,y as MJ,z as TJ}from"./chunk-z9jxsh6w.js";import{Aa as QY,Ca as UY,Ea as lY,I as dY,M as LZ,O as m6,P as y6,Q as jY,W as AY,X as bY,_ as MY,da as i$,fa as SJ,ga as kJ,ia as TY,ka as q8,la as BX,ma as wX,pa as PX,qa as AX,ua as a9,va as w3,xa as F3,ya as L3,za as BZ}from"./chunk-wzxxjj1a.js";import"./chunk-vzdsext4.js";import{Ma as E5,Na as g5,Oa as m5,Ra as FZ}from"./chunk-8pytaed9.js";import{Ta as PY}from"./chunk-9fyjyk2f.js";import{Mb as BY,Nb as F4,Zb as wY,ic as b6}from"./chunk-0wrz9qv8.js";import{tc as H8}from"./chunk-fdr4fcrf.js";import{Dd as _Y,Nd as bJ,Od as m2,Sd as yJ,Xd as IJ,Zd as t8,fe as z8,ie as a0}from"./chunk-2kx9ygzc.js";import"./chunk-egss0m1x.js";import{Me as vJ,Ne as A6,Oe as VJ}from"./chunk-ztreczac.js";import{jf as JY,kf as U4}from"./chunk-p6586ftx.js";import{xf as $Z}from"./chunk-je908ygr.js";import{Bf as Y1,yf as W8,zf as _4}from"./chunk-h1e37bta.js";import"./chunk-p0wyhp5a.js";import{Ff as R2,Gf as L$,Hf as a1,If as z9,Jf as o8,Kf as CJ,Lf as s3,Mf as I9,Nf as a5,Of as e3,Pf as v2,Qf as m0,Rf as HZ,Sf as B$,Tf as eX,Uf as i4,Vf as O8,Yf as $Y,dg as z$}from"./chunk-d86vygx0.js";import"./chunk-v508x7cg.js";import"./chunk-5yyp6njq.js";import"./chunk-myvt7yjm.js";import"./chunk-4fbpydtn.js";import{vg as S9}from"./chunk-3cas6rv5.js";import"./chunk-zfxcef0z.js";import"./chunk-rf3eeens.js";import{Ig as W4,Kg as pX,Pg as LX,Yg as WZ}from"./chunk-s9g7t23a.js";import"./chunk-kehgewqh.js";import"./chunk-kkzznz4w.js";import"./chunk-1cy4ab77.js";import"./chunk-7ajvrtb3.js";import{Ah as h$,yh as O9}from"./chunk-f1x80zky.js";import"./chunk-ys8gysg8.js";import{Ni as OZ,Si as FX,Ti as NZ}from"./chunk-6qp15s2m.js";import{Vi as mJ}from"./chunk-qpmvp4q2.js";import{Wi as p2,Xi as e8,Zi as N9}from"./chunk-tm3789m3.js";import{cj as K$}from"./chunk-qdbbke8f.js";import"./chunk-wezr6wfq.js";import{Bj as _Z,Ej as H1}from"./chunk-rmfzym94.js";import{Mj as s5,Nj as e5,Qj as R1}from"./chunk-j89qk7bp.js";import"./chunk-0eajnhrj.js";import{ak as c5}from"./chunk-rytpfm4a.js";import{dk as l9}from"./chunk-ggdgk3gy.js";import"./chunk-ky592ay9.js";import{Ak as eJ,gk as K8}from"./chunk-n52n2w5v.js";import{Nk as Y4}from"./chunk-cjfb4kjp.js";import{useMemoizedFn as G6}from"ahooks";import{useEffect as _z,useState as K6}from"react";import{useMemoizedFn as i0}from"ahooks";import tX from"ansi-escapes";import{Box as m1,useStdout as Zz}from"ink";import{useEffect as J1,useMemo as Qz,useRef as I2,useState as sX}from"react";import{useShallow as AZ}from"zustand/react/shallow";import{useStore as PZ}from"zustand";function z0($){return PZ(v2,$)}var bZ=[],V2=()=>z0(($)=>$.session.sessionId),O1=()=>z0(($)=>$.session.workspaceRoot),V8=()=>z0(($)=>$.session.messages),i9=()=>z0(($)=>$.session.clearCount),o9=()=>z0(($)=>$.session.isCompacting),n9=()=>z0(($)=>$.session.tokenUsage.estimatedCostUsd),t9=()=>z0(($)=>{let{totalInputTokens:J,cacheReadTokens:Y,cacheWriteTokens:Z}=$.session.tokenUsage;return a9({totalInputTokens:J,cacheReadTokens:Y,cacheWriteTokens:Z}).hitRate});var j8=()=>z0(($)=>$.session.providerRecovery),s9=()=>z0(($)=>$.session.turnActivity),e9=()=>z0(($)=>$.session.actionStationarity),d1=()=>z0(($)=>$.session.actions),$J=()=>z0(($)=>{let{totalTokens:J,maxContextTokens:Y}=$.session.tokenUsage;if(Y<=0)return 100;let Z=Math.max(0,100-J/Y*100);return Math.round(Z)}),JJ=()=>z0(($)=>$.app.initializationStatus),YJ=()=>z0(($)=>$.app.initializationError),j2=()=>z0(($)=>$.app.activeModal),XJ=()=>z0(($)=>$.app.tasks),ZJ=()=>z0(($)=>$.app.modelEditorTarget),QJ=()=>z0(($)=>$.app.sessionSelectorData),UJ=()=>z0(($)=>$.app.sessionHistoryViewerData),GJ=()=>z0(($)=>$.app.taskAttentionStatus),h8=()=>z0(($)=>$.app.taskAttentionUnreadKeys),KJ=()=>z0(($)=>$.app.awaitingSecondCtrlC),N1=()=>z0(($)=>$.app.actions),h2=()=>z0(($)=>$.app.sideConversation),zJ=()=>z0(($)=>$.app.teams),E8=()=>z0(($)=>$.app.initializationStatus==="ready"),qJ=()=>z0(($)=>$.app.tasks.length>0),E2=()=>z0(($)=>$.config.config?.permissionMode||"default"),_J=()=>z0(($)=>$.config.config?.models??bZ),g8=()=>z0(($)=>{let J=$.config.config;if(!J)return;let Y=J.currentModelId;return J.models.find((X)=>X.id===Y)??J.models[0]}),m8=()=>z0(($)=>$.config.config?.currentModelId),OJ=()=>z0(($)=>$.config.config?.agentTeamsEnabled===!0),D0=()=>z0(($)=>{return L$.getTheme()}),NJ=()=>z0(($)=>$.config.config?.codeTheme??"default"),s0=()=>z0(($)=>$.focus.currentFocus),HJ=()=>z0(($)=>$.focus.actions),g2=()=>z0(($)=>$.command.isProcessing),WJ=()=>z0(($)=>$.command.actions),p8=()=>z0(($)=>$.app.followUpQueue),FJ=()=>z0(($)=>$.app.followUpQueueMutation),LJ=()=>z0(($)=>$.command.recoveredSteeringCount),x8=()=>z0(($)=>$.app.reasoningEffort!=="off"),c8=()=>z0(($)=>$.app.reasoningEffort),u8=()=>z0(($)=>$.app.serviceTier),d8=()=>z0(($)=>$.app.responseVerbosity),l8=()=>z0(($)=>$.app.communicationStyle),r8=()=>z0(($)=>$.session.currentThinkingContent),BJ=()=>z0(($)=>$.session.thinkingExpanded),a8=()=>z0(($)=>$.session.currentStreamingMessageId),i8=()=>z0(AZ(($)=>({lines:$.session.currentStreamingLines,tail:$.session.currentStreamingTail,lineCount:$.session.currentStreamingLineCount,version:$.session.currentStreamingVersion}))),wJ=()=>z0(($)=>$.session.finalizingStreamingMessageId),PJ=()=>z0(($)=>$.session.historyExpanded),AJ=()=>z0(($)=>$.session.expandedMessageCount);import{randomUUID as H7}from"node:crypto";import{useMemoizedFn as X1}from"ahooks";import{useEffect as l1,useMemo as FY,useRef as N4}from"react";function MZ($,J){try{return $.code===J.code&&$.message===J.message&&$.retryable===J.retryable&&$.resource===J.resource}catch{return!1}}class q6{options;requested=!1;waitingForIdle=!1;disposed=!1;generation=0;wakeEpoch=0;idleEpoch=0;attempt=0;recoveryStartedAt=null;scheduledToken=null;activeAttemptToken=null;activeRunController=null;retryTimer=null;deadlineTimer=null;now;scheduleCallback;setTimerCallback;clearTimerCallback;constructor($){this.options=$;this.now=$.now??Date.now,this.scheduleCallback=$.scheduleMicrotask??queueMicrotask,this.setTimerCallback=$.setTimer??setTimeout,this.clearTimerCallback=$.clearTimer??clearTimeout}request(){if(this.disposed)return;if(this.wakeEpoch++,this.requested=!0,this.waitingForIdle||this.retryTimer)return;this.scheduleIfRunnable()}notifyIdle(){if(this.disposed)return;if(this.idleEpoch++,this.retryTimer)return;this.waitingForIdle=!1,this.scheduleIfRunnable()}dispose(){if(this.disposed)return;this.disposed=!0,this.generation++,this.requested=!1,this.waitingForIdle=!1,this.scheduledToken=null,this.clearOwnedTimer("retry"),this.clearOwnedTimer("deadline"),this.activeAttemptToken=null;let $=this.activeRunController;this.activeRunController=null,$?.abort("pending-resume-coordinator-disposed"),this.resetEpisodeBudget()}scheduleIfRunnable(){if(this.disposed||!this.requested||this.scheduledToken||this.activeAttemptToken||this.retryTimer||this.waitingForIdle)return;if(!this.options.canRun()){this.waitingForIdle=!0;return}let $=this.generation,J={};this.scheduledToken=J;try{this.scheduleCallback(()=>{if(this.disposed||$!==this.generation||this.scheduledToken!==J)return;this.scheduledToken=null,this.flush($).catch((Y)=>{this.handleUnexpectedFailure(Y,$)})})}catch(Y){this.handleUnexpectedFailure(Y,$)}}async flush($){if(this.disposed||$!==this.generation||this.activeAttemptToken||!this.requested||this.retryTimer||this.waitingForIdle)return;if(!this.options.canRun()){this.waitingForIdle=!0;return}let J={},Y=new AbortController,Z=this.wakeEpoch,X=this.idleEpoch;if(this.attempt++,this.recoveryStartedAt===null)this.recoveryStartedAt=this.now(),this.installDeadlineTimer($);this.activeAttemptToken=J,this.activeRunController=Y;let Q;try{Q=await this.options.run(Y.signal)}finally{if(this.activeAttemptToken===J){if(this.activeAttemptToken=null,this.activeRunController=null,!this.disposed&&$!==this.generation)this.scheduleIfRunnable()}}if(this.disposed||$!==this.generation)return;if(Q.status==="completed"){let U=this.wakeEpoch!==Z;if(this.clearEpisode(),U)this.requested=!0,this.scheduleIfRunnable();return}if(Q.status==="deferred"){if(this.attempt--,this.attempt===0)this.clearOwnedTimer("deadline"),this.resetEpisodeBudget();if(this.requested=!0,this.idleEpoch!==X)this.waitingForIdle=!1,this.scheduleIfRunnable();else this.waitingForIdle=!0;return}this.handleFailure(Q,$)}handleFailure($,J){let Y=m2($.taskFailure),Z=this.options.sessionIdentity;if($.workKind!=="pending_input"||!$.evidence||!Z||!MZ($.taskFailure,$.evidence.taskFailure)){this.terminate("failed",this.attempt,Y);return}let X=TJ({sessionIdentity:Z,failedAttempt:this.attempt,recoveryStartedAt:this.recoveryStartedAt??this.now(),now:this.now(),workStillPending:$.workStillPending,evidence:$.evidence});if(X.phase!=="retry_scheduled"){this.terminate(X.phase,this.attempt,Y);return}this.requested=!0,this.waitingForIdle=!1;let Q={},U=this.setTimerCallback(()=>{if(this.disposed||J!==this.generation||this.retryTimer?.token!==Q)return;this.retryTimer=null,this.scheduleIfRunnable()},X.delayMs);this.retryTimer={handle:U,token:Q},U.unref?.()}handleUnexpectedFailure($,J){if(this.disposed||J!==this.generation)return;this.terminate("failed",Math.max(1,this.attempt),m2($),"pending-resume-coordinator-failed")}installDeadlineTimer($){let J={},Y=this.setTimerCallback(()=>{if(this.disposed||$!==this.generation||this.deadlineTimer?.token!==J)return;this.deadlineTimer=null,this.terminate("exhausted",Math.max(1,this.attempt),bJ("timeout"),"pending-resume-recovery-deadline-exceeded")},MJ);this.deadlineTimer={handle:Y,token:J},Y.unref?.()}terminate($,J,Y,Z){let X=this.activeRunController;if(this.generation++,this.requested=!1,this.waitingForIdle=!1,this.scheduledToken=null,this.clearOwnedTimer("retry"),this.clearOwnedTimer("deadline"),this.resetEpisodeBudget(),Z)X?.abort(Z);try{this.options.onTerminalFailure?.({phase:$,attempt:J,taskFailure:Y})}catch{}}clearEpisode(){this.requested=!1,this.waitingForIdle=!1,this.clearOwnedTimer("retry"),this.clearOwnedTimer("deadline"),this.resetEpisodeBudget()}resetEpisodeBudget(){this.attempt=0,this.recoveryStartedAt=null}clearOwnedTimer($){let J=$==="retry"?this.retryTimer:this.deadlineTimer;if(!J)return;if($==="retry")this.retryTimer=null;else this.deadlineTimer=null;this.clearTimerCallback(J.handle)}}class U8{options;finalized=!1;constructor($){this.options=$}get isFinalized(){return this.finalized}acceptsDeltas(){return!this.finalized&&!this.options.signal.aborted}startTurn(){this.finalized=!1}finalize(){if(!this.acceptsDeltas())return!1;return this.finalized=!0,this.commit(this.options.streamingBuffer.drainPendingBuffers()),!0}abortAndFinalize($){if(this.finalized)return $(),!1;this.finalized=!0;let J=this.options.streamingBuffer.drainPendingBuffers();return $(),this.commit(J),!0}discard(){this.finalized=!0,this.options.streamingBuffer.resetStreamingBuffers(),this.options.discardStreamingMessage(),this.options.clearThinking()}commit($){let J=this.options.getStreamingMessageId();if(J){if($.extraContent)o8(J,$.extraContent);CJ(J)}this.options.finalizeStreamingMessage($.extraContent,$.extraThinking)}}function TZ($){if(!($ instanceof Error))return"未知错误";let Z=$.lastError??$;if(Z.responseBody)try{let U=JSON.parse(Z.responseBody)?.error?.message;if(U){let G=Z.statusCode?` (HTTP ${Z.statusCode})`:"";return`${U}${G}`}}catch{}let X=$.message.match(/Last error:\s*(.+)$/);if(X)return X[1];return $.message}function CZ($){if(!($ instanceof Error))return!1;return $.name==="AbortError"||$.message.includes("aborted")}function RZ($){if(!($ instanceof Error))return!1;let J=$.message;return J.includes("can only concatenate str")||J.includes("image_url")||J.includes("multimodal")||J.includes("vision")||J.includes("does not support images")}function n8($){let J=CZ($),Y=RZ($),Z;if(Y)Z="当前模型不支持图片理解功能。请切换到支持视觉能力的模型(如 Claude 4.5、GPT-5.2、Gemini 3 Pro、Qwen3-VL-Plus 等)后重试。";else Z=TZ($);return{displayMessage:Z,isAbort:J,isVisionNotSupported:Y}}import{appendFileSync as yZ,mkdirSync as IZ,writeFileSync as SZ}from"node:fs";import kZ from"node:os";import _6 from"node:path";var RJ=null;function DZ(){let $=process.env.BLADE_STORAGE_ROOT||_6.join(kZ.homedir(),".blade");return _6.join($,"logs","stream-debug.log")}function fZ($){if(RJ===$)return;let J=_6.dirname($);IZ(J,{recursive:!0,mode:493}),SZ($,`=== Stream Debug Log Started: ${new Date().toISOString()} ===
|
|
2
2
|
`),RJ=$}function O6($,J,Y){try{let Z=DZ();fZ(Z);let X=new Date().toISOString(),Q=Y?` | ${JSON.stringify(Y)}`:"",U=`[${X}] [${$}] ${J}${Q}
|
|
3
3
|
`;yZ(Z,U)}catch{}}var G8=H1("UI");function N6($,J){if(J.state==="requires_attention"){let Y=J.reason==="interrupted_tool_call";$.addToolMessage("Turn recovery requires attention",{toolName:"Runtime Recovery",phase:"complete",summary:Y?"An interrupted tool may have partially completed":"A completed tool may already have changed external state",detail:`${J.turnId} · inspect workspace, processes, and external state before retrying`});return}$.addToolMessage(J.state==="completed"?"Recovered completed turn":"Resuming interrupted turn",{toolName:"Runtime Recovery",phase:"complete",summary:J.state==="completed"?"The durable final response was recovered":"No tool execution was recorded before interruption",detail:J.turnId})}function DJ($,J){let Y=$.streamSession??new U8({signal:$.signal,streamingBuffer:$.streamingBuffer,getStreamingMessageId:$.getStreamingMessageId,finalizeStreamingMessage:$.sessionActions.finalizeStreamingMessage,discardStreamingMessage:$.sessionActions.discardStreamingMessage,clearThinking:()=>$.sessionActions.setCurrentThinkingContent(null)}),Z=(X)=>{for(let Q of X){if((Q.origin??"user")!=="user")continue;let U=$.commandActions.takeFollowUpPresentation(Q.id);if(U){$.sessionActions.addUserMessage(U.displayText);continue}if(!Q.recovered||Q.persisted)continue;let G=typeof Q.content==="string"?Q.content:Q.content.map((z)=>z.type==="text"?z.text:"[Image]").join(`
|
|
4
4
|
`);$.sessionActions.addUserMessage(G)}};return(X)=>{switch(X.kind){case"content_delta":if(X.delta.length>0)J.outputStarted=!0;if(!Y.acceptsDeltas())break;J.contentDeltaCount++,J.contentDeltaTotalLen+=X.delta.length,O6("loopEventHandler","onContentDelta",{callCount:J.contentDeltaCount,deltaLen:X.delta.length,totalLen:J.contentDeltaTotalLen}),$.streamingBuffer.batchAppendContent(X.delta);break;case"thinking_delta":if(X.delta.length>0)J.outputStarted=!0;if(!Y.acceptsDeltas())break;if($.thinkingModeEnabled)$.streamingBuffer.batchAppendThinking(X.delta);break;case"stream_end":{$.sessionActions.setProviderCircuit(null),$.sessionActions.setProviderRetry(null),$.sessionActions.setProviderStall(null),G8.debug("[loopEventHandler] stream_end",{contentDeltaCount:J.contentDeltaCount,contentDeltaTotalLen:J.contentDeltaTotalLen,streamFinalized:Y.isFinalized,signalAborted:$.signal.aborted}),O6("loopEventHandler","onStreamEnd",{contentDeltaCallCount:J.contentDeltaCount,contentDeltaTotalLen:J.contentDeltaTotalLen,streamFinalized:Y.isFinalized,signalAborted:$.signal.aborted}),Y.finalize();break}case"model_fallback":$.sessionActions.setProviderAdmission(null),$.sessionActions.setProviderCircuit(null),$.sessionActions.setProviderRetry(null),$.sessionActions.setProviderStall(null),Y.discard();break;case"provider_admission":{let{kind:Q,...U}=X;$.sessionActions.setProviderAdmission(X.phase==="queued"?U:null);break}case"provider_circuit":{let{kind:Q,...U}=X;$.sessionActions.setProviderCircuit(X.phase==="closed"?null:U);break}case"provider_retry":{let{kind:Q,...U}=X;$.sessionActions.setProviderRetry(X.phase==="recovered"?null:U);break}case"provider_stall":{let{kind:Q,...U}=X;$.sessionActions.setProviderStall(X.phase==="detected"?U:null);break}case"provider_recovery":$.sessionActions.setProviderRecovery(X.recovery);break;case"action_stationarity":{let{kind:Q,...U}=X;$.sessionActions.setActionStationarity(X.phase==="recovered"?null:U);break}case"turn_recovery":{N6($.sessionActions,X.assessment);break}case"tool_start":{J.toolExecutionStarted=!0;let Q=X.toolCall;if(!("function"in Q))break;if(Q.function.name===t8)break;if(G8.debug("[loopEventHandler] tool_start",{toolName:Q.function.name,toolKind:X.toolKind}),["TaskCreate","TaskUpdate","TaskList"].includes(Q.function.name))break;try{let U=JSON.parse(Q.function.arguments),G=SJ(Q.function.name,U);$.sessionActions.addToolMessage(G,{toolCallId:Q.id,toolName:Q.function.name,phase:"start",summary:G,params:U})}catch(U){G8.error("[loopEventHandler] onToolStart error:",U)}break}case"tool_progress":{J.toolExecutionStarted=!0;let Q=X.toolCall;if(!("function"in Q))break;if(Q.function.name===t8)break;let U=X.update.total!==void 0?` ${Math.max(0,Math.min(100,Math.round((X.update.progress??0)/X.update.total*100)))}%`:"",G=`${Q.function.name}${U}: ${X.update.message}`;$.sessionActions.addToolMessage(G,{toolCallId:Q.id,toolName:Q.function.name,phase:"progress",summary:G,...X.update.admission?{admission:X.update.admission}:{}});break}case"tool_result":{J.toolExecutionStarted=!0;let Q=X.toolCall;if(!("function"in Q))break;if(Q.function.name===t8)break;G8.debug("[loopEventHandler] tool_result",{toolName:Q.function.name,success:X.result.success});let U=IJ(kJ(Q.function.name,X.result),yJ);$.sessionActions.addToolMessage(U.summary,{toolCallId:Q.id,toolName:Q.function.name,phase:"complete",summary:U.summary,detail:U.detail});break}case"structured_output":J.outputStarted=!0,$.sessionActions.replaceLastAssistantMessage(JSON.stringify(X.output,null,2));break;case"token_usage":$.sessionActions.updateTokenUsage(X.usage);break;case"compaction":if($.sessionActions.setCompacting(X.phase==="start"),X.phase==="end"){if(X.outcome!=="failed")$.sessionActions.resetContextUsage(),J.compactionCount=(J.compactionCount??0)+1;if(X.memory?.outcome==="written"){let Q=`Saved ${X.memory.entries} project memories`;$.sessionActions.addToolMessage(Q,{toolName:"Project Memory",phase:"complete",summary:Q})}}break;case"turn_start":G8.debug("[loopEventHandler] turn_start",{turn:X.turn,maxTurns:X.maxTurns}),$.sessionActions.updateTokenUsage({turnCount:X.turn}),$.sessionActions.setProviderCircuit(null),$.sessionActions.setProviderRetry(null),$.sessionActions.setProviderStall(null),Y.startTurn();break;case"task_update":$.appActions.setTasks(X.tasks);break;case"goal_frontier_updated":$.appActions.setTasks(X.tasks);break;case"mcp_catalog_changed":{let Q=`MCP catalog r${X.revision}: +${X.added.length} -${X.removed.length} ~${X.updated.length}`;$.sessionActions.addToolMessage(Q,{toolName:"MCP Catalog",phase:"complete",summary:Q,detail:[X.added.length>0?`Added: ${X.added.join(", ")}`:"",X.removed.length>0?`Removed: ${X.removed.join(", ")}`:"",X.updated.length>0?`Updated: ${X.updated.join(", ")}`:""].filter(Boolean).join(`
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{Vi as K}from"./chunk-qpmvp4q2.js";import{Wi as wt,Xi as ft}from"./chunk-tm3789m3.js";import{cj as I}from"./chunk-qdbbke8f.js";import{Aj as yt,dj as tt,ej as Dt,fj as Bt,jj as Gt,kj as et,lj as Kt,mj as Ht,nj as Yt,oj as cn,pj as Ft,qj as qt,rj as Mt,sj as Vt,tj as Jt,uj as _t,vj as Qt,wj as jt,xj as Wt,yj as Zt,zj as kt}from"./chunk-wezr6wfq.js";import{Ej as Un,Gj as bn,Hj as _n,Ij as T}from"./chunk-rmfzym94.js";import{Nj as zt,Qj as v}from"./chunk-j89qk7bp.js";import{Yj as xn,Zj as Cn}from"./chunk-
|
|
1
|
+
import{Vi as K}from"./chunk-qpmvp4q2.js";import{Wi as wt,Xi as ft}from"./chunk-tm3789m3.js";import{cj as I}from"./chunk-qdbbke8f.js";import{Aj as yt,dj as tt,ej as Dt,fj as Bt,jj as Gt,kj as et,lj as Kt,mj as Ht,nj as Yt,oj as cn,pj as Ft,qj as qt,rj as Mt,sj as Vt,tj as Jt,uj as _t,vj as Qt,wj as jt,xj as Wt,yj as Zt,zj as kt}from"./chunk-wezr6wfq.js";import{Ej as Un,Gj as bn,Hj as _n,Ij as T}from"./chunk-rmfzym94.js";import{Nj as zt,Qj as v}from"./chunk-j89qk7bp.js";import{Yj as xn,Zj as Cn}from"./chunk-rytpfm4a.js";import{dk as a}from"./chunk-ggdgk3gy.js";import{gk as Ln}from"./chunk-n52n2w5v.js";var lt=/^[\x21\x23-\x5b\x5d-\x7e]+$/;function vt(n){return n==="127.0.0.1"||n==="[::1]"||n.toLowerCase()==="localhost"}function p(n,t="MCP OAuth URL"){let e=new URL(n);if(e.username||e.password)throw Error(`${t} must not contain credentials`);if(e.protocol!=="https:"&&!(e.protocol==="http:"&&vt(e.hostname)))throw Error(`${t} requires HTTPS; HTTP is allowed only for loopback servers`);return e}var B=async(n,t)=>{p(n,"MCP OAuth request URL");let e=await fetch(n,{...t,redirect:"manual"});if(e.status>=300&&e.status<400)throw await e.body?.cancel(),Error("MCP OAuth network requests must not follow redirects");return e};function nn(n){let t=n.oauth;if(!t)return;let e=t;for(let E of["clientSecret","authorizationUrl","tokenUrl","redirectUri"])if(e[E]!==void 0)throw Error(`MCP OAuth "${E}" is not supported; use standards-based discovery`);if(t.enabled!==!0)return{enabled:!1};if(n.type!=="http"&&n.type!=="sse")throw Error("MCP OAuth is supported only for HTTP and SSE transports");if(!n.url)throw Error("MCP OAuth requires an MCP server URL");if(p(n.url,"MCP OAuth server URL"),Object.keys(n.headers??{}).find((E)=>E.toLowerCase()==="authorization"))throw Error("MCP OAuth cannot be combined with a configured Authorization header");let _=t.clientId?.trim();if(_&&_.length>4096)throw Error("MCP OAuth clientId exceeds 4096 characters");let S=t.scopes?.map((E)=>E.trim());if(S){if(S.length>32)throw Error("MCP OAuth supports at most 32 scopes");if(S.some((E)=>!E||E.length>128||!lt.test(E)))throw Error("MCP OAuth scopes contain an invalid value");if(new Set(S).size!==S.length)throw Error("MCP OAuth scopes must not contain duplicates")}let r=t.callbackPort;if(r!==void 0&&(!Number.isInteger(r)||r<1024||r>65535))throw Error("MCP OAuth callbackPort must be between 1024 and 65535");return{enabled:!0,..._?{clientId:_}:{},...S?.length?{scopes:S}:{},...r!==void 0?{callbackPort:r}:{}}}import{randomUUID as Sn}from"node:crypto";import Te from"node:http";import{auth as dn}from"@modelcontextprotocol/sdk/client/auth.js";import se from"open";import{createHash as ne,randomUUID as te}from"node:crypto";import{constants as tn,promises as b}from"node:fs";import en from"node:path";import ee from"write-file-atomic";var Nn=1,Me=1048576,_e=5000,re=50,Se=/^[a-f0-9]{64}$/,Ee=T.Object({client_id:T.String({minLength:1,maxLength:4096})},{additionalProperties:!0}),ue=T.Object({access_token:T.String({minLength:1,maxLength:65536}),token_type:T.String({minLength:1,maxLength:64}),expires_in:T.Optional(T.Number({minimum:0})),refresh_token:T.Optional(T.String({minLength:1,maxLength:65536})),scope:T.Optional(T.String({maxLength:16384})),id_token:T.Optional(T.String({minLength:1,maxLength:262144}))},{additionalProperties:!1}),oe=T.Unsafe({type:"object",properties:{authorizationServerUrl:T.String({format:"uri"}),resourceMetadataUrl:T.Optional(T.String({format:"uri"})),resourceMetadata:T.Optional(T.Unknown()),authorizationServerMetadata:T.Optional(T.Unknown())},required:["authorizationServerUrl"],additionalProperties:!1}),an=T.Object({serverUrl:T.String({format:"uri"}),clientId:T.Optional(T.String({minLength:1,maxLength:4096})),clientInformation:T.Optional(Ee),tokens:T.Optional(ue),tokenExpiresAt:T.Optional(T.Number({minimum:0})),discoveryState:T.Optional(oe),updatedAt:T.String({format:"date-time"})},{additionalProperties:!1}),gn=T.Object({version:T.Literal(Nn),credentials:T.Record(T.String(),an)},{additionalProperties:!1});function G(n,t){return n instanceof Error&&"code"in n&&n.code===t}function me(n){if(!Number.isInteger(n)||n<=0)return!1;try{return process.kill(n,0),!0}catch(t){return G(t,"EPERM")}}function Mn(n){return structuredClone(n)}function In(n){if(Object.keys(n.credentials).some((t)=>!Se.test(t)))throw Error("MCP OAuth credential store contains an invalid identity")}function H(n){let t=new URL(n);return t.hash="",t.toString()}function rn(n,t,e=[]){return ne("sha256").update(JSON.stringify({serverUrl:H(n),clientId:t?.trim()||null,scopes:[...e].sort()})).digest("hex")}class f{static locks=new K;stateRoot;tokenFilePath;constructor(n=Ln()){this.stateRoot=en.join(n,"mcp"),this.tokenFilePath=en.join(this.stateRoot,"oauth-credentials.json")}static coordinationStatsForTests(){return this.locks.getStats()}async getCredential(n){return f.locks.runExclusive(this.tokenFilePath,async()=>{let e=(await this.readStore()).credentials[n];return e?Mn(e):null})}async updateCredential(n,t){return this.runMutation(async(e)=>{let M=e.credentials[n],_=await t(M?Mn(M):null);if(_)e.credentials[n]=_n(an,_);else delete e.credentials[n];return _?Mn(e.credentials[n]):null})}async deleteCredential(n){await this.updateCredential(n,()=>null)}async listCredentialIds(){return f.locks.runExclusive(this.tokenFilePath,async()=>Object.keys((await this.readStore()).credentials).sort())}async runMutation(n){return f.locks.runExclusive(this.tokenFilePath,async()=>{let t=await this.acquireStoreLock();try{let e=await this.readStore(),M=await n(e);return await this.writeStore(e),M}finally{await t()}})}async ensureStateRoot(){await b.mkdir(this.stateRoot,{recursive:!0,mode:448});let n=await b.lstat(this.stateRoot);if(!n.isDirectory()||n.isSymbolicLink())throw Error("MCP OAuth credential root must be a regular directory");if(process.getuid&&n.uid!==process.getuid())throw Error("MCP OAuth credential root must be owned by the current user");if((n.mode&63)!==0)throw Error("MCP OAuth credential root permissions must not allow group access")}async readStore(){try{let n=await b.lstat(this.tokenFilePath);if(!n.isFile()||n.isSymbolicLink())throw Error("MCP OAuth credential store must be a regular file");if(process.getuid&&n.uid!==process.getuid())throw Error("MCP OAuth credential store must be owned by the current user");if((n.mode&511)!==384)throw Error("MCP OAuth credential store permissions must be 0600");if(n.size>Me)throw Error("MCP OAuth credential store exceeds the 1 MiB limit");let t=JSON.parse(await b.readFile(this.tokenFilePath,"utf8")),e=bn(gn,t);if(!e.success)throw Error("MCP OAuth credential store has an invalid schema");return In(e.data),e.data}catch(n){if(G(n,"ENOENT"))return{version:Nn,credentials:{}};throw n}}async writeStore(n){await this.ensureStateRoot();let t=_n(gn,n);In(t),await ee(this.tokenFilePath,`${JSON.stringify(t,null,2)}
|
|
2
2
|
`,{mode:384,encoding:"utf8"}),await b.chmod(this.tokenFilePath,384)}async acquireStoreLock(){await this.ensureStateRoot();let n=en.join(this.stateRoot,".oauth-credentials.lock"),t=te(),e=Date.now()+_e;while(Date.now()<e)try{let M=await b.open(n,tn.O_CREAT|tn.O_EXCL|tn.O_WRONLY,384);return await M.writeFile(`${JSON.stringify({version:1,pid:process.pid,token:t,createdAt:new Date().toISOString()})}
|
|
3
3
|
`,"utf8"),await M.close(),async()=>{try{if(JSON.parse(await b.readFile(n,"utf8")).token===t)await b.unlink(n)}catch(_){if(!G(_,"ENOENT"))throw _}}}catch(M){if(!G(M,"EEXIST"))throw M;await this.removeDeadLock(n),await new Promise((_)=>setTimeout(_,re))}throw Error("MCP OAuth credential store is busy; retry the operation")}async removeDeadLock(n){let t=await b.lstat(n);if(!t.isFile()||t.isSymbolicLink())throw Error("MCP OAuth credential lock must be a regular file");if(process.getuid&&t.uid!==process.getuid()||(t.mode&511)!==384)throw Error("MCP OAuth credential lock ownership or permissions are invalid");let e=JSON.parse(await b.readFile(n,"utf8"));if(typeof e.pid!=="number"||!Number.isInteger(e.pid)||e.pid<=0)throw Error("MCP OAuth credential lock owner is invalid");if(!me(e.pid))await b.unlink(n)}}var wn="127.0.0.1",fn=7777,Pn="/oauth/callback",Ae=300000;class En extends Error{constructor(n){super(`MCP server "${n}" requires OAuth authorization; run "blade mcp login ${n}" or use the Web MCP panel`);this.name="McpOAuthAuthorizationRequiredError"}}class hn extends Error{constructor(n){super(`MCP OAuth credentials are unavailable in this runtime for server "${n}"`);this.name="McpOAuthUnavailableError"}}function ce(n){let t=n?"Authentication complete":"Authentication failed";return`<!doctype html>
|
|
4
4
|
<html lang="en">
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{v as HH,w as JH}from"./chunk-
|
|
1
|
+
import{v as HH,w as JH}from"./chunk-d4agyayp.js";import{A as S,x as Cz,y as fz,z as uz}from"./chunk-z9jxsh6w.js";import{B as zH,C as xz,D as bz,E as Rz,F as Sz,G as Mz}from"./chunk-q4adhq22.js";import{Aa as Iz,Ba as yz,Ca as hz,Da as kz,N as R,W as Az,X as Oz,da as Ez,ga as qz,ha as Tz,ka as Pz}from"./chunk-wzxxjj1a.js";import"./chunk-vzdsext4.js";import{Ra as ez}from"./chunk-8pytaed9.js";import{Ta as Nz,Xa as i,_a as a}from"./chunk-9fyjyk2f.js";import{Nb as Kz,Zb as wz,ic as l}from"./chunk-0wrz9qv8.js";import{tc as d}from"./chunk-fdr4fcrf.js";import{Dd as Bz,Nd as I,Od as v,Pd as Gz,Ud as Vz,Xd as jz,Zd as M,ae as Dz,fe as Fz,ie as F}from"./chunk-2kx9ygzc.js";import"./chunk-egss0m1x.js";import{Ge as _z,Ne as r,Oe as Uz}from"./chunk-ztreczac.js";import"./chunk-p6586ftx.js";import{zf as LH}from"./chunk-h1e37bta.js";import"./chunk-p0wyhp5a.js";import{Uf as oz,Vf as nz}from"./chunk-d86vygx0.js";import"./chunk-v508x7cg.js";import{eg as e}from"./chunk-5yyp6njq.js";import{jg as Wz}from"./chunk-myvt7yjm.js";import{rg as m}from"./chunk-4fbpydtn.js";import"./chunk-3cas6rv5.js";import{wg as sz}from"./chunk-zfxcef0z.js";import"./chunk-rf3eeens.js";import"./chunk-s9g7t23a.js";import"./chunk-kehgewqh.js";import"./chunk-kkzznz4w.js";import{sh as tz}from"./chunk-1cy4ab77.js";import"./chunk-7ajvrtb3.js";import"./chunk-f1x80zky.js";import"./chunk-ys8gysg8.js";import{vi as az,yi as rz}from"./chunk-6qp15s2m.js";import"./chunk-qpmvp4q2.js";import{Wi as g,Xi as Xz,Zi as c,_i as p}from"./chunk-tm3789m3.js";import{cj as t}from"./chunk-qdbbke8f.js";import"./chunk-wezr6wfq.js";import{Ej as y}from"./chunk-rmfzym94.js";import"./chunk-j89qk7bp.js";import{Rj as lz,Uj as iz}from"./chunk-0eajnhrj.js";import"./chunk-rytpfm4a.js";import"./chunk-ggdgk3gy.js";import"./chunk-ky592ay9.js";import{gk as $z,hk as dz,lk as zz,pk as Hz,qk as vz,rk as Jz}from"./chunk-n52n2w5v.js";import"./chunk-cjfb4kjp.js";import{Readable as KH,Writable as wH}from"node:stream";import*as f from"@agentclientprotocol/sdk";import o from"node:path";import{PROTOCOL_VERSION as GH,RequestError as C}from"@agentclientprotocol/sdk";import{RequestError as gz}from"@agentclientprotocol/sdk";import{nanoid as u}from"nanoid";var G=y("Agent");function P(z){return Object.freeze({kind:"local",hostStateRoot:z,executionRoot:z,hostResourceRoot:z})}function Zz(z){if(!z)return{};return Object.fromEntries(z.map((H)=>[H.name,H.value]))}function ZH(z){if("command"in z)return{type:"stdio",command:z.command,args:z.args,env:Zz(z.env)};if("url"in z)return{type:z.type,url:z.url,headers:Zz("headers"in z?z.headers:void 0)};return null}function $H(z){let H={};for(let L of z){let Y=ZH(L);if(Y)H[L.name]=Y}return H}function cz(z){if(typeof z==="string")return z?[{type:"text",text:z}]:[];return z.flatMap((H)=>{if(H.type==="text")return H.text?[{type:"text",text:H.text}]:[];let L=H.image_url.url,Y=/^data:([^;,]+);base64,(.+)$/s.exec(L);if(!Y)return[{type:"text",text:"[Image]"}];return[{type:"image",mimeType:Y[1]??"image/png",data:Y[2]??""}]})}function XH(z){let H=Uz(z.metadata);return H?[{type:"text",text:r(H)}]:cz(z.content)}function WH(z){return[`Status: ${z.status}`,`Exit code: ${z.exitCode??"null"}`,`Duration: ${(z.durationMs/1000).toFixed(3)} seconds`].join(`
|
|
2
2
|
`)}function BH(z){if(!Wz(z)||z.reason!=="queue_full"||z.resource!=="pending_count"&&z.resource!=="pending_bytes")return;return{...I("capacity"),resource:z.resource}}function _H(z){if(!(z instanceof gz)||!z.data||typeof z.data!=="object")return;let H=z.data;if(!Gz(H.taskFailure)||H.toolExecutionStarted!==!1||!Number.isInteger(H.toolCallsCount)||H.toolCallsCount<0||H.outputStarted!==!1)return;return{taskFailure:H.taskFailure,toolExecutionStarted:H.toolExecutionStarted,toolCallsCount:H.toolCallsCount,outputStarted:H.outputStarted}}function UH(z){return{version:z.version,pending:z.pending,mutable:z.mutable,locked:z.locked,internal:z.internal}}class x{id;roots;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;pendingResumeCompletion=null;pendingResumeNextDelayMs=null;availableCommandsTimer=null;taskStatusUnsubscribe;lastTurnActivityGeneration;lastTurnActivityRevision=-1;destroyed=!1;destroyFinished=!1;destroyPromise;serviceRegistration;messages;contextMessages;mode;updateEgress;constructor(z,H,L,Y,$={}){this.id=z;this.roots=H;this.connection=L;this.clientCapabilities=Y;this.options=$;this.messages=[...$.initialMessages??[]],this.contextMessages=[...this.messages],this.mode=this.mapPermissionModeToMode($.permissionMode),this.updateEgress=new Mz({maxPendingItems:xz,maxPendingBytes:bz,writeTimeoutMs:Rz,signal:L.signal,sizeOf:(X)=>Buffer.byteLength(JSON.stringify(X)),write:async(X)=>{await L.sessionUpdate(X)},onFailure:(X)=>this.handleUpdateEgressFailure(X)})}async refreshPersistedMessages(){let[z,H]=await Promise.all([this.loadPersistedMessages(),this.loadPersistedModelContext()]);if(z.length>0)this.messages=z;if(H.length>0)this.contextMessages=H}async loadModelContextOr(z){let H=await this.loadPersistedModelContext();return H.length>0?H:[...z]}loadPersistedMessages(){return this.roots.kind==="acp-remote"?F.loadRemoteSession(this.id,this.roots.hostStateRoot,this.roots.descriptor):F.loadSession(this.id,this.roots.hostStateRoot)}loadPersistedModelContext(){return this.roots.kind==="acp-remote"?F.loadRemoteSessionModelContext(this.id,this.roots.hostStateRoot,this.roots.descriptor):F.loadSessionModelContext(this.id,this.roots.hostStateRoot)}async persistMetadataUpdate(z,H=z){if(this.roots.kind==="acp-remote"){await F.updateRemoteSessionMetadata(this.id,this.roots.hostStateRoot,this.roots.descriptor,z);return}try{await F.updateSessionMetadata(this.id,this.roots.hostStateRoot,z)}catch(L){if(!(L instanceof Fz)&&L.code!=="ENOENT")throw L;await F.createSessionMetadata(this.id,this.roots.hostStateRoot,{taskStatus:"completed",...H})}}async persistPermissionMode(z){if(this.roots.kind==="acp-remote"){await F.updateRemoteSessionMetadata(this.id,this.roots.hostStateRoot,this.roots.descriptor,{permissionMode:z});return}await F.setSessionPermissionMode(this.id,this.roots.hostStateRoot,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 Pz.createWithRuntime(this.runtime,{sessionId:this.id,...this.options.taskWorktree?{toolBlacklist:["EnterWorktree","ExitWorktree"]}:{}})}async initialize(){G.debug(`[AcpSession ${this.id}] Initializing...`),await this.persistPermissionMode(this.mapModeToPermissionMode()??"default");let z=R.initializeSession(this.connection,this.id,this.clientCapabilities,this.roots.executionRoot,async(Z)=>{await this.sendUpdateAndWait(Z)},this.roots.kind==="acp-remote"?this.roots.profile:void 0);if(z)this.serviceRegistration=z;if(G.debug(`[AcpSession ${this.id}] ACP service context initialized`),this.roots.kind==="local"?await l.resolvePendingWithHandler(this.roots.hostStateRoot,this.id,{requestConfirmation:(Z)=>this.requestPermission(Z)}):!1)await this.refreshPersistedMessages();else if((this.options.initialMessages?.length??0)>0)this.contextMessages=await this.loadModelContextOr(this.options.initialMessages??[]);let L=this.options.mcpServers?$H(this.options.mcpServers):void 0,Y=R.getInstance().getTerminalService(this.id),$=this.roots.kind==="acp-remote"?{kind:"acp-remote",executionRoot:this.roots.executionRoot,resourceRoot:this.roots.hostResourceRoot,readTextFile:this.clientCapabilities?.fs?.readTextFile===!0,writeTextFile:this.clientCapabilities?.fs?.writeTextFile===!0,terminal:this.clientCapabilities?.terminal===!0,descriptor:this.roots.descriptor}:void 0;if(this.runtime=await Ez.create({sessionId:this.id,workspaceRoot:this.roots.hostStateRoot,...$?{workspace:$}:{},permissionMode:this.mapModeToPermissionMode(),...L?{mcpServers:L}:{},...this.options.taskWorktree?{taskWorktree:this.options.taskWorktree}:{},...this.options.taskIsolation?{taskIsolation:this.options.taskIsolation}:{},userShellExecutor:{execute:async(Z,_)=>{let U=await Y.execute(Z,{cwd:_.cwd,env:_.env,timeout:_.timeoutMs,signal:_.signal,allowLocalFallback:!1,onOutput:(V)=>_.onOutput?.("stdout",V)});return{exitCode:U.exitCode,stdout:U.stdout,stderr:U.stderr,...U.error?{error:U.error}:{},timedOut:U.failureKind==="timeout",aborted:U.failureKind==="aborted"}}},...(this.options.initialMessages?.length??0)>0?{sessionStart:{isResume:!0,resumeSessionId:this.id}}:{}}),this.roots.kind==="local"?await S.recoverInterrupted(this.roots.hostStateRoot,this.id,this.runtime):!1)await this.refreshPersistedMessages();if(this.agent=await this.createAgent(),this.roots.kind==="local")await yz(this.roots.hostStateRoot);G.debug(`[AcpSession ${this.id}] Agent created successfully`),this.taskStatusUnsubscribe?.(),this.taskStatusUnsubscribe=Kz.subscribe((Z)=>{if(Z.sessionId!==this.id||Z.projectPath!==this.roots.hostStateRoot)return;if(Z.type==="subagent.completion.queued"){this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/backgroundSubagentCompletion":Z.properties}}),this.requestPendingResume();return}if(Z.type==="follow_up.queue.changed"){let _=i.safeParse(Z.properties.queue);if(_.success)this.sendFollowUpQueueSnapshot(_.data);return}if(Z.type==="provider.recovery"){let _=m.safeParse(Z.properties.recovery);if(!_.success)return;this.sendProviderRecoveryProjection(_.data);return}if(Z.type==="turn.activity"){let _=a.safeParse(Z.properties.activity);if(!_.success)return;this.sendTurnActivityProjection(_.data);return}if(Z.type==="task.delivery"){if(!Z.properties.taskDelivery||typeof Z.properties.taskDelivery!=="object")return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:typeof Z.properties.updatedAt==="string"?Z.properties.updatedAt:new Date().toISOString(),_meta:{"blade/taskDelivery":Z.properties.taskDelivery,...Z.properties.taskWorktreeRemoved===!0?{"blade/taskWorktreeRemoved":!0}:{}}});return}if(Z.type.startsWith("team.")){let{teamName:_,messageId:U,content:V}=Z.properties,T=Z.properties.metadata;if(Z.type==="team.message.received"&&typeof _==="string"&&typeof U==="string"&&typeof V==="string"&&Oz(T,{messageId:U,teamName:_}))(async()=>{let E=await this.runtime?.enqueueSteering(V,{allowBeforeTurn:!0,messageId:U,origin:"team_message",metadata:T});if(!E?.accepted)return;if(E.queue)this.sendFollowUpQueueSnapshot(E.queue);if(await new Az(_,$z()).markDelivered([U]),E.delivery==="next_turn")this.requestPendingResume()})().catch((E)=>{G.warn(`[AcpSession ${this.id}] Failed to deliver teammate message`,E)});this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/teamEvent":{type:Z.type,...Z.properties}}});return}if(Z.type!=="task.status")return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:typeof Z.properties.updatedAt==="string"?Z.properties.updatedAt:new Date().toISOString(),_meta:{"blade/taskStatus":Z.properties.taskStatus,...typeof Z.properties.taskStatusReason==="string"?{"blade/taskStatusReason":Z.properties.taskStatusReason}:{},...Z.properties.taskFailure&&typeof Z.properties.taskFailure==="object"?{"blade/taskFailure":Z.properties.taskFailure}:{},...typeof Z.properties.taskStartedAt==="string"?{"blade/taskStartedAt":Z.properties.taskStartedAt}:{},...typeof Z.properties.taskCompletedAt==="string"?{"blade/taskCompletedAt":Z.properties.taskCompletedAt}:{},...Z.properties.taskDiffStat&&typeof Z.properties.taskDiffStat==="object"?{"blade/taskDiffStat":Z.properties.taskDiffStat}:{},...typeof Z.properties.taskQueuePosition==="number"?{"blade/taskQueuePosition":Z.properties.taskQueuePosition}:{},...typeof Z.properties.taskQueueDepth==="number"?{"blade/taskQueueDepth":Z.properties.taskQueueDepth}:{},...typeof Z.properties.taskConcurrencyLimit==="number"?{"blade/taskConcurrencyLimit":Z.properties.taskConcurrencyLimit}:{},...typeof Z.properties.taskInFlight==="number"?{"blade/taskInFlight":Z.properties.taskInFlight}:{}}})});let Q=await this.runtime.getGoal(),W=this.runtime.getPendingSteeringCount()>0,B=Q?.status==="active"||Q?.status==="verifying";if(W||B)this.requestPendingResume({defer:this.options.initialMessages!==void 0});else{let Z=this.runtime.getTurnRecoveryAssessment();if(Z.state!=="none")this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/turnRecovery":Z}})}}async replayHistory(){for(let H of this.messages){if(!this.canSendUpdates())return;if(!_z(H))continue;let L=H.role==="user"?"user_message_chunk":H.role==="assistant"?"agent_message_chunk":void 0;if(!L)continue;for(let Y of XH(H)){if(!this.canSendUpdates())return;if(!await this.sendUpdateAndWait({sessionUpdate:L,content:Y}))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);G.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.sendInitialSessionUpdates()},500)}async sendInitialSessionUpdates(){try{let z=this.runtime;if(z)this.sendFollowUpQueueSnapshot(await z.getFollowUpQueueSnapshot()),this.sendProviderRecoveryProjection(z.getProviderRecoveryProjection()),this.sendTurnActivityProjection(z.getTurnActivityProjection())}catch{G.warn("[AcpSession "+this.id+"] Initial follow-up queue unavailable")}await this.sendAvailableCommands()}async handleSlashCommand(z,H){try{G.debug(`[AcpSession ${this.id}] Executing slash command: ${z}`);let L={cwd:this.roots.hostStateRoot,workspaceKind:this.roots.kind,surface:"acp",workspaceRoot:this.roots.hostStateRoot,sessionId:this.id,messages:[...this.contextMessages],model:{getChatConfig:()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getChatService().getConfig()}},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()}},...this.roots.kind==="local"?{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 B=!1,Z,_=(V)=>{this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:V.id,status:V.status==="completed"?"completed":"failed",content:[{type:"content",content:{type:"text",text:V.result?.message||V.result?.error||`Subagent ${V.status}`}}]})},U=this.runtime.resumeSubagent({agentId:Q,prompt:W,onCompleted:(V)=>{if(B)_(V);else Z=V}});if(this.sendUpdate({sessionUpdate:"tool_call",toolCallId:U.session.id,status:"in_progress",title:`Resuming ${U.session.subagentType} subagent`,content:[{type:"content",content:{type:"text",text:`Resumed from ${U.source.id} at depth ${U.session.resumeDepth}`}}],kind:this.mapToolKind("readonly")}),B=!0,Z)_(Z);return U}}}:{},...this.roots.kind==="local"?{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,B)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpPrompt(Q,W,B)},complete:async(Q,W,B)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.completeMcpArgument(Q,W,B)},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})}},...this.roots.kind==="local"?{codeReview:{run:async(Q,W)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let B=await S.start({sessionId:this.id,projectPath:this.roots.hostStateRoot,runtime:this.runtime,request:Q,signal:W,onEvent:(U)=>{if(U.kind==="tool_start")this.sendUpdate({sessionUpdate:"tool_call",toolCallId:U.toolCall.id,status:"in_progress",title:`Review: ${U.toolCall.function.name}`,content:[],kind:this.mapToolKind(U.toolKind)});else if(U.kind==="tool_result")this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:U.toolCall.id,status:U.result.success?"completed":"failed",content:[]})}}),Z=await B.completion,_=(await S.list(this.roots.hostStateRoot,this.id)).find((U)=>U.start.reviewId===B.reviewId);if(!_)throw Error(`Review not found: ${B.reviewId}`);return await this.refreshPersistedMessages(),{reviewId:B.reviewId,status:Z.status,findings:Z.findings.length,content:Bz(_.start,Z)}}}}:{},signal:H,acp:{sendMessage:(Q)=>{this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:Q}})},sendToolStart:(Q,W,B)=>{let Z=`tool_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,_=this.mapToolKind(B);this.sendUpdate({sessionUpdate:"tool_call",toolCallId:Z,status:"in_progress",title:`${Q}`,content:[{type:"content",content:{type:"text",text:JSON.stringify(W,null,2)}}],kind:_})},sendToolResult:(Q,W)=>{if(W.summary)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:W.summary}})}}},Y=await hz(z,L),$=Y.data?.action;if($==="start_goal"||$==="resume_goal")this.requestPendingResume();if($==="rewind_session"&&Array.isArray(Y.data?.messages))this.messages=[...Y.data.messages],this.contextMessages=await this.loadModelContextOr(Y.data.messages);if((Y.message==="compact_completed"||Y.message==="compact_fallback")&&Y.data?.compactedMessages){this.contextMessages=[...Y.data.compactedMessages];let Q=await this.loadPersistedMessages();if(Q.length>0)this.messages=Q}let X=Y.content||Y.message;if(X)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:X}});if(Y.error)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] ${Y.error}`}});return await this.flushUpdates(),{stopReason:Y.success?"end_turn":"cancelled"}}catch(L){if(H.aborted||L instanceof Error&&L.name==="AbortError")return{stopReason:"cancelled"};return G.error(`[AcpSession ${this.id}] Slash command error:`,L),this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] 命令执行失败: ${L instanceof Error?L.message:"未知错误"}`}}),{stopReason:"cancelled"}}}async handleSideConversationCommand(z){if(this.pendingSideConversation)throw Error("A side conversation is already running");let H=new AbortController,L,Y=new Promise(($)=>{L=$});this.pendingSideConversation=H,this.pendingSideConversationCompletion=Y;try{return await this.handleSlashCommand(z,H.signal)}catch($){if(H.signal.aborted||$ instanceof Error&&$.name==="AbortError")return{stopReason:"cancelled"};throw $}finally{if(L(),this.pendingSideConversationCompletion===Y)this.pendingSideConversationCompletion=null;if(this.pendingSideConversation===H){if(this.pendingSideConversation=null,!this.destroyed&&this.pendingResumeRequested)this.ensurePendingResumeScheduled()}}}async sendAvailableCommands(){try{let z=kz(this.roots.hostStateRoot,this.runtime?.getAgentResources(),this.roots.kind),H=["model","permissions","theme","config","exit","ide"],Y=z.filter(($)=>!H.includes($.name)&&($.name!=="team"||this.runtime?.getConfig().agentTeamsEnabled===!0)).map(($)=>{let X;if($.usage){let Q=$.usage.replace(/^\/\w+\s*/,"").trim();if(Q)X=Q}if($.aliases?.length){let Q=`Aliases: ${$.aliases.join(", ")}`;X=X?`${X} | ${Q}`:Q}return{name:$.name,description:$.description,input:X?{hint:X}:void 0}});G.info(`[AcpSession ${this.id}] Sending available commands: ${JSON.stringify(Y.map(($)=>$.name))}`),this.sendUpdate({sessionUpdate:"available_commands_update",availableCommands:Y}),G.info(`[AcpSession ${this.id}] Sent ${Y.length} available commands`)}catch(z){G.error(`[AcpSession ${this.id}] Failed to send available commands:`,z)}}async prompt(z,H={}){if(R.setCurrentSession(this.id),!this.agent||!this.runtime)throw Error("Session not initialized");let L=this.resolvePrompt(z.prompt),Y=L.content,$=L.displayText,X=z._meta?.outputSchema??(H.pendingInputOnly?this.runtime.getPendingSteeringMessages().find((j)=>j.outputSchema)?.outputSchema:void 0),Q;if(X!==void 0)Q=Dz(X).schema;if($.trimStart().startsWith("!")){if(Q)throw Error("Output schemas cannot be combined with user shell commands");return this.handleUserShellCommand($)}let W=Nz($);if(W){if(Q)throw Error("Output schemas cannot be combined with slash commands");if(Array.isArray(Y)&&Y.some((j)=>j.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($.trim()))return this.handleSlashCommand($,this.pendingPrompt.signal);let j=await this.runtime.enqueueSteering(Y,{allowBeforeTurn:!0});if(!j.accepted)throw Error(j.reason==="queue_full"?"Active turn steering queue is full":"Active turn is no longer steerable");if(G.debug(`[AcpSession ${this.id}] Queued steering for active turn (${j.queued})`),this.sendFollowUpQueueSnapshot(j.queue??await this.runtime.getFollowUpQueueSnapshot()),j.delivery==="next_turn")this.requestPendingResume();return{stopReason:"end_turn"}}let B=new AbortController,Z=()=>{B.abort(H.abortSignal?.reason)};if(H.abortSignal?.aborted)Z();else H.abortSignal?.addEventListener("abort",Z,{once:!0});let _=!1,U=!1,V=!1,T,E=new Promise((j)=>{T=j});this.pendingPrompt=B,this.pendingPromptCompletion=E;try{if(G.debug(`[AcpSession ${this.id}] Received prompt: ${$.slice(0,100)}...`),Iz($)){if(Q)throw Error("Output schemas cannot be combined with slash commands");return await this.handleSlashCommand($,B.signal)}let j={sessionId:this.id,userId:"acp-user",workspaceRoot:this.roots.hostStateRoot,executionRoot:this.roots.executionRoot,workspaceKind:this.roots.kind,messages:[...this.contextMessages],signal:B.signal,permissionMode:this.mapModeToPermissionMode(),onPermissionModeChange:async(J)=>{this.mode=this.mapPermissionModeToMode(J),this.sendUpdate({sessionUpdate:"current_mode_update",currentModeId:this.mode})},...this.options.taskWorktree?{worktreeActive:!0}:{},confirmationHandler:{requestConfirmation:async(J)=>{return this.requestPermission(J)}}},N=await wz(this.agent.chatStream(Y,j,{pendingInputOnly:H.pendingInputOnly,goalContinuationOnly:H.goalContinuationOnly,outputSchema:Q}),async(J)=>{switch(J.kind){case"content_delta":if(Q)break;if(J.delta.length>0)U=!0;this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:J.delta}});break;case"thinking_delta":if(J.delta.length>0)U=!0;this.sendUpdate({sessionUpdate:"agent_thought_chunk",content:{type:"text",text:J.delta}});break;case"tool_start":{V=!0;let D=J.toolCall,A=D.function.name;if(A===M)break;let q=this.mapToolKind(J.toolKind),K=`Executing ${A}`;if(A==="Task"&&"function"in D)try{let b=JSON.parse(D.function.arguments),w=b.resume_from??b.resume;if(typeof w==="string")K=`Resuming ${String(b.subagent_type||"subagent")} from ${w}`}catch{}this.sendUpdate({sessionUpdate:"tool_call",toolCallId:D.id,status:"in_progress",title:K,content:[],kind:q});break}case"tool_progress":{V=!0;let D=J.toolCall;if(D.function.name===M)break;this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:D.id,status:"in_progress",content:[{type:"content",content:{type:"text",text:J.update.message}}]});break}case"tool_result":{V=!0;let D=J.toolCall;if(D.function.name===M)break;let A=J.result,q=[],K=A.metadata;if(K?.kind==="patch"&&Array.isArray(K.changes))for(let w of K.changes){if(!w||typeof w!=="object"||!("path"in w)||typeof w.path!=="string")continue;q.push({type:"diff",path:w.path,oldText:"oldContent"in w&&typeof w.oldContent==="string"?w.oldContent:null,newText:"newContent"in w&&typeof w.newContent==="string"?w.newContent:null})}else if(K?.kind==="edit"&&typeof K.file_path==="string"&&typeof K.oldContent==="string"&&(typeof K.newContent==="string"||K.newContent===void 0))q.push({type:"diff",path:K.file_path,oldText:K.oldContent,newText:K.newContent??null});else{let w=D.function.name,QH=Tz(jz(qz(w,A),Vz));q.push({type:"content",content:{type:"text",text:QH}})}if(D.function.name==="Task"&&(K?.verificationVerdict==="pass"||K?.verificationVerdict==="fail"||K?.verificationVerdict==="partial"))q.unshift({type:"content",content:{type:"text",text:`Verification result: ${K.verificationVerdict.toUpperCase()}`}});let b=A.success?"completed":"failed";this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:D.id,status:b,content:q});break}case"structured_output":U=!0,this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:JSON.stringify(J.output)}});break;case"mcp_catalog_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP catalog r${J.revision} (${J.serverName}): +${J.added.length} -${J.removed.length} ~${J.updated.length}
|
|
3
3
|
`}});break;case"mcp_content_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP ${J.contentKind} r${J.revision} (${J.serverName}): +${J.added.length} -${J.removed.length} ~${J.updated.length}
|
|
4
4
|
`}});break;case"mcp_resource_updated":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP resource updated r${J.revision} (${J.serverName}): ${J.uri}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{tc as Xt,uc as En,vc as yn,wc as bn}from"./chunk-fdr4fcrf.js";import{Ah as Bt}from"./chunk-
|
|
1
|
+
import{tc as Xt,uc as En,vc as yn,wc as bn}from"./chunk-fdr4fcrf.js";import{Ah as Bt}from"./chunk-f1x80zky.js";import{Fh as xt,Gh as vi,Hh as sn,Ih as zt,Jh as U,Kh as en,Lh as gt,Mh as mt,Oh as rn,Ph as Tn,Qh as B,Rh as dn,Sh as on,Th as pn,Uh as lt,Vh as un,Wh as cn,Xh as Mn,Zh as S,ai as wn,bi as Gt,ci as Ut,di as h,ei as Ht}from"./chunk-6qp15s2m.js";import{cj as It}from"./chunk-qdbbke8f.js";import{Gj as X,Ij as x}from"./chunk-rmfzym94.js";import{Yj as tn,Zj as nn}from"./chunk-rytpfm4a.js";import{Nk as ns}from"./chunk-cjfb4kjp.js";import{EventEmitter as fs}from"events";import Un from"node:path";function hn(t){if(t===void 0)return"undefined";if(typeof t==="string")return t;try{let i=JSON.stringify(t);return i===void 0?String(t):i}catch{return String(t)}}function An(t){let i=t;switch(t.code){case"type":return`类型错误:${t.message}`;case"required":return"缺少必需参数";case"minLength":return`字符串过短:${t.message}`;case"maxLength":return`字符串过长:${t.message}`;case"minimum":case"exclusiveMinimum":return`数值太小:${t.message}`;case"maximum":case"exclusiveMaximum":return`数值太大:${t.message}`;case"minItems":return`数组元素过少:${t.message}`;case"maxItems":return`数组元素过多:${t.message}`;case"format":return`格式错误:${t.message}`;case"enum":return`必须是枚举允许的值之一:${t.message}`;case"const":return`必须是指定的字面量值:${t.message}`;case"additionalProperties":case"unevaluatedProperties":return`包含未知参数:${t.message}`;case"anyOf":case"oneOf":return"不符合任何有效的类型定义";case"~refine":return t.message||"自定义验证失败";default:return t.message||`验证失败:${hn(i)}`}}class Jt extends Error{issues;type;constructor(t,i,n="validation_error"){super(t);this.issues=i;this.type=n;this.name="ToolValidationError"}}function Vt(t,i){let n=X(t,i);if(n.success)return n.data;let s=n.error.issues.map((r)=>({field:r.path.length>0?r.path.join("."):"root",message:An(r),value:r.value})),e=s.length===1?`参数验证失败 [${s[0].field}]: ${s[0].message}`:`参数验证失败 (${s.length} 个错误):
|
|
2
2
|
${s.map((r)=>` - ${r.field}: ${r.message}`).join(`
|
|
3
3
|
`)}`;throw new Jt(e,s)}function st(t){if(!t||typeof t!=="object")return;let i=t;if(i.type==="object"&&i.properties)i.required??=[],i.additionalProperties??=!1;for(let n of Object.values(i))if(Array.isArray(n))for(let s of n)st(s);else st(n)}function et(t){let i=JSON.parse(JSON.stringify(t,(n,s)=>n.startsWith("~")?void 0:s));return st(i),i}class rt{toolName;params;executeFn;descriptionFn;affectedPathsFn;isRetrySafe;constructor(t,i,n,s,e,r=!1){this.toolName=t;this.params=i;this.executeFn=n;this.descriptionFn=s;this.affectedPathsFn=e;this.isRetrySafe=r}getDescription(){if(this.descriptionFn)return this.descriptionFn(this.params);return`执行工具: ${this.toolName}`}getAffectedPaths(){if(this.affectedPathsFn)return this.affectedPathsFn(this.params);return[]}async execute(t,i,n){let s={signal:t,updateOutput:i,...n};return this.executeFn(this.params,s)}}function jt(t){return{name:t.name,displayName:t.displayName,kind:t.kind,isConcurrencySafe:t.isConcurrencySafe??!1,isRetrySafe:t.isRetrySafe??!1,parallelism:t.parallelism??(t.isConcurrencySafe?"shared":"exclusive"),strict:t.strict??!1,description:t.description,version:t.version||"1.0.0",category:t.category,tags:t.tags||[],getFunctionDeclaration(){let i=et(t.schema),n=t.description.short;if(t.description.long)n+=`
|
|
4
4
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{k as o}from"./chunk-
|
|
1
|
+
import{k as o}from"./chunk-nxtj07c4.js";import"./chunk-rytpfm4a.js";import"./chunk-cjfb4kjp.js";import{execSync as r}from"child_process";var l={command:"update",describe:"Check for updates and install if available",handler:async()=>{console.log("Checking for updates...");try{let e=await o(!0);if(console.log(`Current version: ${e.currentVersion}`),e.error){console.log(`Warning: ${e.error}`);return}if(e.latestVersion)console.log(`Latest version: ${e.latestVersion}`);if(e.hasUpdate&&e.latestVersion){console.log(""),console.log(`\x1B[33mUpdate available: ${e.currentVersion} -> ${e.latestVersion}\x1B[0m`),console.log(""),console.log("Updating...");try{r("npm install -g blade-code@latest --registry https://registry.npmjs.org",{stdio:"inherit"}),console.log(""),console.log("Update complete!")}catch(t){console.error("Error: Update failed. Please run manually:"),console.error(" npm install -g blade-code@latest"),process.exit(1)}}else console.log("You are running the latest version of Blade")}catch(e){console.error(`Error: Failed to check for updates: ${e instanceof Error?e.message:"未知错误"}`),process.exit(1)}}};export{l as updateCommands};
|