blade-code 0.10.22 → 0.10.24
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-014rwj5b.js +1 -0
- package/dist/{chunk-2rbct4ks.js → chunk-0568ndm9.js} +2 -2
- package/dist/{chunk-f9tahtz6.js → chunk-1gkpjhts.js} +1 -1
- package/dist/{chunk-g1zrs8tj.js → chunk-1pkca2km.js} +1 -1
- package/dist/{chunk-haqfbgv4.js → chunk-26zhy301.js} +1 -1
- package/dist/chunk-2wpnzjme.js +1 -0
- package/dist/chunk-3ak60ndt.js +1 -0
- package/dist/{chunk-kky5ydtw.js → chunk-3fkj59nv.js} +1 -1
- package/dist/{chunk-n63thdsq.js → chunk-3qmwt188.js} +1 -1
- package/dist/{chunk-zj651nrm.js → chunk-4a02yjg9.js} +1 -1
- package/dist/{chunk-abtq0kjb.js → chunk-57q5wn4g.js} +1 -1
- package/dist/{chunk-33wheqb0.js → chunk-67ekta7b.js} +1 -1
- package/dist/chunk-6pb6zs96.js +2 -0
- package/dist/{chunk-kntre6sz.js → chunk-6vfe3409.js} +1 -1
- package/dist/chunk-7dqc10sc.js +1 -0
- package/dist/{chunk-d3kqhv5k.js → chunk-86zsjamb.js} +2 -2
- package/dist/{chunk-pefrn6n0.js → chunk-9c3jjbgd.js} +1 -1
- package/dist/{chunk-hjvdsrzb.js → chunk-ag07wwer.js} +1 -1
- package/dist/{chunk-06pbdpcg.js → chunk-aw8s1sej.js} +1 -1
- package/dist/{chunk-2kpynwxa.js → chunk-bp886b8j.js} +1 -1
- package/dist/chunk-bpz0g8ej.js +2 -0
- package/dist/{chunk-nwy1rpwf.js → chunk-bvwq5wth.js} +1 -1
- package/dist/{chunk-yqk501wp.js → chunk-bw7vknjr.js} +1 -1
- package/dist/{chunk-gwvds95j.js → chunk-c29y2s8g.js} +2 -2
- package/dist/{chunk-8472vz3s.js → chunk-c674mmtj.js} +2 -2
- package/dist/{chunk-r40fthzd.js → chunk-d2kzet1k.js} +1 -1
- package/dist/{chunk-afv2grka.js → chunk-d70mtcp4.js} +1 -1
- package/dist/chunk-e71qm105.js +1 -0
- package/dist/{chunk-qw900zg9.js → chunk-edqtngzr.js} +2 -2
- package/dist/chunk-f0mt91sr.js +1 -0
- package/dist/{chunk-5bgyskdm.js → chunk-f4ksxskk.js} +1 -1
- package/dist/{chunk-rxfmqnf7.js → chunk-f8zz4se0.js} +1 -1
- package/dist/chunk-gwe547ww.js +1 -0
- package/dist/{chunk-9ka0bdry.js → chunk-hpmxmkzc.js} +1 -1
- package/dist/{chunk-9m80tr4t.js → chunk-j8ggq1z4.js} +1 -1
- package/dist/{chunk-5ztdsaex.js → chunk-k2b95m2p.js} +1 -1
- package/dist/{chunk-s7g6jt82.js → chunk-m13jrgp9.js} +2 -2
- package/dist/chunk-m486vmtn.js +1 -0
- package/dist/{chunk-m96f2aq9.js → chunk-my2jwz6y.js} +1 -1
- package/dist/{chunk-ef8rr9eh.js → chunk-n00mknme.js} +1 -1
- package/dist/chunk-n54tp9wr.js +1 -0
- package/dist/{chunk-a3yg9fd5.js → chunk-nqpcwa0k.js} +430 -340
- package/dist/{chunk-kvd5nexw.js → chunk-p1dp2xgq.js} +1 -1
- package/dist/{chunk-698qsvyb.js → chunk-pccn8ndq.js} +2 -2
- package/dist/{chunk-18f9g8ja.js → chunk-phzy5kqq.js} +1 -1
- package/dist/{chunk-se1ef1r7.js → chunk-pq7tk058.js} +1 -1
- package/dist/chunk-q5sewfn5.js +1 -0
- package/dist/{chunk-wax3nm7t.js → chunk-qg87zezq.js} +1 -1
- package/dist/chunk-r14bz8va.js +1 -0
- package/dist/{chunk-hfveg7c1.js → chunk-rtkhyp1g.js} +1 -1
- package/dist/{chunk-czjbz0fp.js → chunk-s14wmzm3.js} +2 -2
- package/dist/{chunk-vypake1a.js → chunk-s4mqw4wa.js} +1 -1
- package/dist/{chunk-9wdg2mqh.js → chunk-sgnjekfb.js} +1 -1
- package/dist/{chunk-04gq93dx.js → chunk-t327cwnb.js} +1 -1
- package/dist/chunk-tetxqw28.js +1 -0
- package/dist/{chunk-gcsygn5a.js → chunk-vmzf4nvh.js} +1 -1
- package/dist/{chunk-c7zk9zj2.js → chunk-vns8g2rv.js} +1 -1
- package/dist/{chunk-djh79rde.js → chunk-w56y2pvk.js} +2 -2
- package/dist/{chunk-bh42pn4d.js → chunk-wjqctwyr.js} +1 -1
- package/dist/{chunk-h0q03x9f.js → chunk-x6tns9d8.js} +1 -1
- package/dist/{chunk-ksm02qjh.js → chunk-xzdpdwhz.js} +1 -1
- package/dist/{chunk-vannpbp0.js → chunk-yac1ga9w.js} +1 -1
- package/dist/{chunk-244cdt25.js → chunk-yaxapgbm.js} +1 -1
- package/dist/{chunk-y5xyh4br.js → chunk-zm3zn23k.js} +1 -1
- package/package.json +1 -1
- package/dist/chunk-1ejj4jvg.js +0 -1
- package/dist/chunk-34cqp0rx.js +0 -1
- package/dist/chunk-3bk8jveq.js +0 -1
- package/dist/chunk-7nygnmnm.js +0 -1
- package/dist/chunk-9nc6sfj4.js +0 -1
- package/dist/chunk-avtsweaa.js +0 -1
- package/dist/chunk-mrx6qkax.js +0 -1
- package/dist/chunk-p29w4zfc.js +0 -1
- package/dist/chunk-s1310gqw.js +0 -1
- package/dist/chunk-sr2stcda.js +0 -2
- package/dist/chunk-tnt2hhcg.js +0 -1
- package/dist/chunk-txqccp76.js +0 -1
- package/dist/chunk-vc2c8wkx.js +0 -2
- package/dist/chunk-vxhf2q0r.js +0 -1
package/dist/blade.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{Gc as W}from"./chunk-
|
|
2
|
+
import{Gc as W}from"./chunk-my2jwz6y.js";import{Jc as F,Kc as M}from"./chunk-j8ggq1z4.js";import"./chunk-n00mknme.js";import"./chunk-qg87zezq.js";import"./chunk-xjqcc0nt.js";import"./chunk-86zsjamb.js";import"./chunk-6pb6zs96.js";import{oe as T}from"./chunk-w56y2pvk.js";import"./chunk-edqtngzr.js";import"./chunk-vmzf4nvh.js";import"./chunk-hpmxmkzc.js";import"./chunk-bpz0g8ej.js";import{sf as N,tf as B}from"./chunk-p1dp2xgq.js";import"./chunk-c674mmtj.js";import"./chunk-1gkpjhts.js";import"./chunk-c29y2s8g.js";import"./chunk-pccn8ndq.js";import"./chunk-x6tns9d8.js";import"./chunk-s14wmzm3.js";import{Xf as J}from"./chunk-vns8g2rv.js";import v from"node:path";var E=process.argv.slice(2),I=u(E),p=I!==null;if(I!==null)T.setGlobalDebug(I);function u(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 c(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 m(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 t(){if(c(E)){let{getVersion:K}=await import("./chunk-014rwj5b.js");console.log(K());return}let Q=process.cwd(),Y=F(Q);M(Y),N(B());let U=m(E,"--plugin-dir","--pluginDir");if(U.length>0){let{configureInvocationPluginDirs:K}=await import("./chunk-e71qm105.js");K(U.map((Z)=>v.resolve(Q,Z)))}if(q(E,"--trust-workspace","--trustWorkspace")){let{WorkspaceTrustService:K}=await import("./chunk-m486vmtn.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-pq7tk058.js");if(await K())return}if(W(),q(E,"--print","-p")){let{handlePrintMode:K}=await import("./chunk-f4ksxskk.js");if(await K())return}if(E.includes("--acp")){let{runAcpIntegration:K}=await import("./chunk-6vfe3409.js");await K();return}let[{default:X},{hideBin:G},{cliConfig:z,globalOptions:$},{loadConfiguration:_,validateOutput:D,validatePermissions:R},{doctorCommands:S},{installCommands:k},{mcpCommands:O},{projectsCommands:y},{scheduleCommands:b},{serveCommand:V},{updateCommands:P},{webCommand:x}]=await Promise.all([import("yargs"),import("yargs/helpers"),import("./chunk-gwe547ww.js"),import("./chunk-2wpnzjme.js"),import("./chunk-m13jrgp9.js"),import("./chunk-yac1ga9w.js"),import("./chunk-aw8s1sej.js"),import("./chunk-67ekta7b.js"),import("./chunk-bw7vknjr.js"),import("./chunk-q5sewfn5.js"),import("./chunk-d70mtcp4.js"),import("./chunk-zm3zn23k.js")]),A=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(O).command(y).command(b).command(S).command(P).command(k).command(x).command(V).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),p&&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,h=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,h=import("./chunk-7dqc10sc.js").then(({checkVersionOnStartup:C})=>C()),[{render:w},{createElement:f},{AppWrapper:j}]=await Promise.all([import("ink"),import("react"),import("./chunk-26zhy301.js")]),H={...K,initialMessage:L,debug:K.debug,print:Boolean(K.print),versionCheckPromise:h};delete H._,delete H.$0,delete H.message,w(f(j,H),{patchConsole:!0,exitOnCtrlC:!1,alternateBuffer:!1})});try{await A.parse()}catch(K){console.error("Error: Parse error:",K),process.exit(1)}}if(J.main==J.module)t().catch(console.error);export{t as main};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Ff as a,Gf as b,Hf as c,If as d,Jf as e,Kf as f}from"./chunk-c29y2s8g.js";import"./chunk-vns8g2rv.js";export{b as getVersion,c as getPackageName,a as getPackageInfo,e as getFormattedVersion,d as getDescription,f as getCopyright};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{xb as I5}from"./chunk-4dnvydyv.js";import{$b as W1,Eb as Z5,Fb as J5,Gb as c$,Hb as u$,Ob as d1,Xb as L2,Zb as J1,_b as i0,fc as P0,yb as d2}from"./chunk-n63thdsq.js";import{gc as V2,jc as o1,kc as q2}from"./chunk-vypake1a.js";import{ld as v5}from"./chunk-xjqcc0nt.js";import{md as R5,nd as f2,od as S5,pd as h5,qd as Z1,sd as m1}from"./chunk-rxfmqnf7.js";import{Wd as v2,Xd as b2,_d as C5}from"./chunk-5xph8r1k.js";import{he as t2}from"./chunk-d3kqhv5k.js";import{ne as w2}from"./chunk-djh79rde.js";import{cf as M5}from"./chunk-gcsygn5a.js";import{rf as i}from"./chunk-kvd5nexw.js";import{Ef as $5}from"./chunk-gwvds95j.js";import{Mf as Z0,Of as M1,Pf as X2,Qf as l0,Sf as t1,Uf as e1}from"./chunk-czjbz0fp.js";import{Vf as K7}from"./chunk-c7zk9zj2.js";function a2($){return $.role==="system"&&Array.isArray($.content)}function o2($){if($.role!=="system"||!$.metadata||Array.isArray($.metadata))return!1;return typeof $.metadata==="object"&&$.metadata.contextualProjectRules===!0}class R0{systemMessages;_contextualSystemMessages;_history;_pending=[];context;constructor($,Z){this.context=$;let J=$.messages.find(a2);if(this._contextualSystemMessages=$.messages.filter(o2),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)=>!a2(W)&&!o2(W))}get historyLength(){return this._history.length}get history(){return this._history}get pending(){return this._pending}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(!o2($))throw Error("Contextual project instructions require safe metadata");this._contextualSystemMessages.push($),this.systemMessages.push($)}syncContextualSystemMessages(){let $=this.systemMessages.filter(a2);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)}appendToHistory($){this._history.push($)}commitPending(){if(this._pending.length>0)this._history.push(...this._pending),this._pending=[]}replaceHistory($){this._history=$.filter((Z)=>!a2(Z)&&!o2(Z))}restoreDurableHistory($){this._contextualSystemMessages=$.filter(o2),this._history=$.filter((Z)=>!a2(Z)&&!o2(Z)),this._pending=[],this.syncContextualSystemMessages()}removeMessages($){this._history=this._history.filter((Z)=>!$(Z)),this._pending=this._pending.filter((Z)=>!$(Z)),this._contextualSystemMessages=this._contextualSystemMessages.filter((Z)=>!$(Z)),this.syncContextualSystemMessages()}writeback(){this.commitPending(),this.context.messages=[...this._contextualSystemMessages,...this._history]}get hasSystemPrompt(){return this.systemMessages.length>0}}function G1($){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 L1($){return{budget:$.budget,usage:0,consecutiveContinuations:0,lastOutputDelta:0,isSubagent:$.isSubagent??!1}}function F1($,Z,J){return{...$,usage:$.usage+Z,lastOutputDelta:Z,consecutiveContinuations:J?$.consecutiveContinuations+1:0}}import m2 from"node:path";var o5=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"]),a5=/^(LD_.+|DYLD_.+|PATH)$/,U1=/^([A-Za-z_][A-Za-z0-9_]*)=([\w./:@-]*)$/;function U0($){let Z=$;while(!0){let J=Z.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!J)break;let W=J[1],K=J[2],Y=W.match(U1);if(!Y)break;let X=Y[1];if(!o5.has(X))break;Z=K}return Z}function q8($){let Z=$;while(!0){let J=Z.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!J)break;let W=J[1],K=J[2],Y=W.match(U1);if(!Y)break;let X=Y[1];if(a5.test(X))break;Z=K}return Z}var s5=[/^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 A$($){let Z=$,J=!0;while(J){J=!1;for(let W of s5){let K=Z.match(W);if(K){Z=Z.slice(K[0].length),J=!0;break}}if(Z.startsWith("-- "))Z=Z.slice(3),J=!0}return Z}function h0($){let Z=[],J="",W=!1,K=!1,Y=!1;for(let X=0;X<$.length;X++){let z=$[X];if(Y){J+=z,Y=!1;continue}if(z==="\\"&&!W){J+=z,Y=!0;continue}if(z==="'"&&!K){W=!W,J+=z;continue}if(z==='"'&&!W){K=!K,J+=z;continue}if(W||K){J+=z;continue}if(z==="|"){if(X+1<$.length&&$[X+1]==="|"){if(J.trim())Z.push(J.trim());J="",X++;continue}return null}if(z===">"||z==="<")return null;if(z==="&"&&X+1<$.length&&$[X+1]==="&"){if(J.trim())Z.push(J.trim());J="",X++;continue}if(z==="&")return null;if(z===";"){if(J.trim())Z.push(J.trim());J="";continue}J+=z}if(J.trim())Z.push(J.trim());return Z.length>0?Z:null}function O1($){let Z=!1,J=!1,W=!1;for(let K=0;K<$.length;K++){let Y=$[K];if(W){W=!1;continue}if(Y==="\\"&&!Z){W=!0;continue}if(Y==="'"&&!J){Z=!Z;continue}if(Y==='"'&&!Z){J=!J;continue}if(Z)continue;if(Y==="$"){let X=$[K+1];if(X&&/[A-Za-z_@*#?!$0-9({]/.test(X))return!0}if(Y==="`")return!0;if(J)continue;if(Y==="|")return!0;if(Y===">"||Y==="<")return!0;if(Y==="{"){let X=$.slice(K);if(/^\{[^}]*,[^}]*\}/.test(X)||/^\{[^}]*\.\.[^}]*\}/.test(X))return!0}}return!1}function O0($){let Z=[],J="",W=!1,K=!1,Y=!1;for(let X=0;X<$.length;X++){let z=$[X];if(Y){J+=z,Y=!1;continue}if(z==="\\"&&!W){if(Y=!0,K){let Q=$[X+1];if(Q&&'$`"\\'.includes(Q))continue;J+=z,Y=!1}continue}if(z==="'"&&!K){W=!W;continue}if(z==='"'&&!W){K=!K;continue}if(!W&&!K&&/[ \t]/.test(z)){if(J)Z.push(J),J="";continue}J+=z}if(J)Z.push(J);return Z}var t5=new Set(["npm","pnpm","yarn","bun"]),y1=new Set(["biome","eslint","jest","mypy","pyright","pytest","ruff","tsc","vitest"]),e5=new Set(["-u","--fix","--update","--update-snapshot","--updateSnapshot","--watch","--watchAll","--write"]);function $6($){return $!==void 0&&/^(?:test|lint|build|type-?check)(?::[\w.-]+)*$/i.test($)}function Z6($){return $.replace(/\s+2>&1\s*$/,"").trim()}function J6($,Z,J){if(!J||Z.length!==2)return;let W=/^(.+?)[ \t]+&&[ \t]+([\s\S]+)$/.exec($);if(!W)return;let K=O0(W[1]??"");if(K.length!==2||K[0]!=="cd")return;let Y=K[1];if(!Y||Y==="-")return;let X=m2.isAbsolute(Y)?m2.resolve(Y):m2.resolve(J,Y);if(!d2.isWithinWorkspace(X,J))return;return W[2]?.trim()||void 0}function s2($,Z){let J=U0(Z6($)),W=h0(J);if(!W||O1(J)||/[\r\n]/.test(J))return!1;let K=W.length===1?W[0]:J6(J,W,Z);if(!K)return!1;let Y=O0(K);if(Y.length===0||Y.some((H)=>[...e5].some((V)=>H===V||H.startsWith(`${V}=`))))return!1;let[X,z,Q]=Y;if(t5.has(X??""))return $6(z==="run"?Q:z)||z==="--test";if((X==="npx"||X==="bunx")&&y1.has(z??""))return!0;if(y1.has(X??""))return!0;if(X==="node"&&z==="--test")return!0;if(X==="go"&&["build","test","vet"].includes(z??""))return!0;return X==="cargo"&&["build","check","clippy","test"].includes(z??"")}function O8($,Z){if($===void 0)return!0;if(typeof $!=="string"||$.split(/[\\/]/).includes(".."))return!1;if(!Z)return!m2.isAbsolute($);let J=m2.isAbsolute($)?m2.resolve($):m2.resolve(Z,$);return d2.isWithinWorkspace(J,Z)}var x$=w2("Agent"),W6=3;function k$($,Z,J){if($!=="length")return{action:"none"};if(Z>=W6)return{action:"truncated"};if(G1(J)==="stop")return x$.info("[Loop] Token budget: diminishing returns detected, skipping recovery"),{action:"budget_stop"};return{action:"recover"}}var K6=[/:\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],Y6=/```[\s\S]{50,}```/,P1="请执行你提到的操作,不要只是描述。使用 Edit/Write/ApplyPatch/Bash 工具来实际修改文件。",X6=2;function T$($,Z,J=!0){if(!$||Z>=X6)return{action:"none"};if(!J&&Y6.test($))return{action:"retry",prompt:P1};let W=$.slice(-200),K=W.match(/```/g);if(K&&K.length%2!==0)return{action:"none"};if(K6.some((X)=>X.test(W)))return{action:"retry",prompt:P1};return{action:"none"}}var z6=[/\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}(?:测试|单测|集成测试|检查|构建)/],E1={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},Q6={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},H6="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.",B6="Required verification did not run successfully before the retry limit.",V6=3;function N1($,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&&s2(J.metadata.command,W)){$.add(J.metadata.command);return}if(!["Task","TaskOutput"].includes(Z))return;let K=J.metadata?.verificationCommands;if(!Array.isArray(K))return;for(let Y of K)if(typeof Y==="string"&&s2(Y,W))$.add(Y)}function f$($,Z,J){if(!$||!z6.some((Q)=>Q.test($)))return{action:"none"};let W=Object.keys(E1).filter((Q)=>E1[Q].test($)),K=[...Z],Y=W.filter((Q)=>!K.some((H)=>Q6[Q].test(H)));if(W.length>0?Y.length===0:K.some((Q)=>s2(Q)))return{action:"none"};if(J>=V6)return{action:"fail",message:B6};let z=W.length>1&&Y.length>0?` Missing successful verification categories: ${Y.join(", ")}.`:"";return{action:"retry",prompt:`${H6}${z}`}}var D6=[/\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|子代理|子智能体)/],_1=[/\b(?:do not|don't|never)\s+(?:delegate|call|use|invoke)\b/i,/(?:不要|禁止|无需)(?:委派|调用|使用).{0,20}(?:Task|子代理|子智能体)?/];function S1($){return typeof $==="string"&&_1.some((Z)=>Z.test($))}var j6=[/\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|子代理)/],w6=[/\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 q6($){if(typeof $!=="string")return;if(w6.some((Z)=>Z.test($)))return"multiple-allowed";return j6.some((Z)=>Z.test($))?"required":void 0}function I0($){for(let Z of $){let J=q6(Z);if(J!==void 0)return J==="required"}return!1}var G6="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.",L6="Required delegation did not complete before the retry limit.",F6=3;function A1($,Z,J){let W=(typeof $==="string"?[$]:$??[]).map((X)=>X.trim()).filter(Boolean),K=I0(W),Y=!1;if(!K)for(let X of W){if(_1.some((z)=>z.test(X)))break;if(D6.some((z)=>z.test(X))){Y=!0;break}}if(W.length===0||!K&&!Y||Z.has("Task"))return{action:"none"};if(J>=F6)return{action:"fail",message:L6};return{action:"retry",prompt:G6}}var U6=[/\b(?:use|create|enter|start|work\s+(?:in|inside))\b.{0,60}\bworktree\b/i,/(?:使用|创建|进入).{0,30}(?:worktree|工作树)/i],O6=[/\b(?:exit|leave)\b.{0,40}\bworktree\b/i,/\bworktree\b.{0,60}\b(?:action\s+)?(?:keep|remove)\b/i,/(?:退出|离开).{0,30}(?:worktree|工作树)/i],y6=[/\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 x1($){return y6.reduce((Z,J)=>Z.replace(J," "),$)}function p0($){if(typeof $!=="string")return!1;let Z=x1($);return U6.some((J)=>J.test(Z))}var P6="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.",E6="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.",b6="Required worktree lifecycle did not complete before the retry limit.",N6=3;function k1($,Z,J){if(!$)return{action:"none"};let W=x1($);if(!p0(W))return{action:"none"};let K=O6.some((X)=>X.test(W));if(Z.has("TaskWorktree"))return{action:"none"};let Y=!Z.has("EnterWorktree")?"EnterWorktree":K&&!Z.has("ExitWorktree")?"ExitWorktree":void 0;if(!Y)return{action:"none"};if(J>=N6)return{action:"fail",message:b6};return{action:"retry",tool:Y,prompt:Y==="EnterWorktree"?P6:E6}}var b1=30000;async function M$($){try{let J=t2.getInstance().executeStopHooks({projectDir:$.workspaceRoot??i(),sessionId:$.sessionId,permissionMode:$.permissionMode,reason:$.reason,abortSignal:$.abortSignal}),W,K=new Promise((Y)=>{W=setTimeout(()=>Y("timeout"),b1)});try{let Y=await Promise.race([J,K]);if(Y==="timeout")return x$.warn(`[Loop] Stop hook 超时 (${b1}ms),按 shouldStop: true 处理`),{action:"stop"};let X=Y;if(!X.shouldStop)return{action:"continue",reason:X.continueReason};return{action:"stop"}}finally{clearTimeout(W)}}catch(Z){return x$.warn("[Loop] Stop hook execution failed:",Z),{action:"stop"}}}async function _6($,Z){let J;while(!(J=await $.next()).done)if(Z)await Z(J.value);return J.value}var S6=[/<system-reminder>[\s\S]*?<\/system-reminder>/gi,/<file[^>]*>[\s\S]*?<\/file>/gi,/<hooks_context>[\s\S]*?<\/hooks_context>/gi,/<[^>]+>/g];function A6($){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 x6($){let Z=$;for(let Q of S6)Z=Z.replace(Q," ");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|$)|$)/),K=W&&W[1].length>=6?W[1]:J;if(K=K.trim().replace(/[\s.。!!??,,;;::-]+$/,""),K.length<=60)return K;let Y=K.slice(0,60),X=Y.lastIndexOf(" ");return`${(X>36?Y.slice(0,X):Y).trimEnd()}…`}function T1($){return x6(A6($))}import{EventEmitter as k6}from"events";import f1 from"node:path";function v$($){if(M1($.sessionId),!f1.isAbsolute($.projectPath))throw Error("projectPath must be absolute");return{sessionId:$.sessionId,projectPath:f1.resolve($.projectPath)}}function f8($){let Z=v$($);return JSON.stringify([Z.projectPath,Z.sessionId])}class e2 extends k6{static instance;constructor(){super();this.setMaxListeners(100)}static getInstance(){if(!e2.instance)e2.instance=new e2;return e2.instance}publish($,Z,J,W){let K=v$($);this.emit("event",{sessionId:K.sessionId,projectPath:K.projectPath,type:Z,...W!==void 0?{seq:W}:{},properties:J})}subscribe($){return this.on("event",$),()=>this.off("event",$)}}var y0=e2.getInstance();var x2=w2("Agent"),g0=new Set;async function T6($,Z){let J=$.sessionId;if(!J||$.subagentInfo)return;if(g0.has(J))return;if(g0.size>=5000)g0.clear();g0.add(J);try{let W=$.workspaceRoot,K=await P0.findSessionMetadata(J,W);if(!K)return;if(K.title&&K.title.trim())return;let Y=T1(Z);if(!Y)return;await P0.updateSessionMetadata(J,K.projectPath,{title:Y}),y0.publish({sessionId:J,projectPath:K.projectPath},"session.updated",{title:Y})}catch(W){x2.debug?.("[Loop] 自动生成会话标题失败:",W)}}var R$=`<turn_aborted>
|
|
1
|
+
import{xb as I5}from"./chunk-4dnvydyv.js";import{$b as W1,Eb as Z5,Fb as J5,Gb as c$,Hb as u$,Ob as d1,Xb as L2,Zb as J1,_b as i0,fc as P0,yb as d2}from"./chunk-3qmwt188.js";import{gc as V2,jc as o1,kc as q2}from"./chunk-s4mqw4wa.js";import{ld as v5}from"./chunk-xjqcc0nt.js";import{md as R5,nd as f2,od as S5,pd as h5,qd as Z1,sd as m1}from"./chunk-f8zz4se0.js";import{Wd as v2,Xd as b2,_d as C5}from"./chunk-5xph8r1k.js";import{he as t2}from"./chunk-86zsjamb.js";import{pe as w2}from"./chunk-w56y2pvk.js";import{ef as M5}from"./chunk-vmzf4nvh.js";import{tf as i}from"./chunk-p1dp2xgq.js";import{Gf as $5}from"./chunk-c29y2s8g.js";import{Of as Z0,Qf as M1,Rf as X2,Sf as l0,Uf as t1,Wf as e1}from"./chunk-s14wmzm3.js";import{Xf as K7}from"./chunk-vns8g2rv.js";function a2($){return $.role==="system"&&Array.isArray($.content)}function o2($){if($.role!=="system"||!$.metadata||Array.isArray($.metadata))return!1;return typeof $.metadata==="object"&&$.metadata.contextualProjectRules===!0}class R0{systemMessages;_contextualSystemMessages;_history;_pending=[];context;constructor($,Z){this.context=$;let J=$.messages.find(a2);if(this._contextualSystemMessages=$.messages.filter(o2),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)=>!a2(W)&&!o2(W))}get historyLength(){return this._history.length}get history(){return this._history}get pending(){return this._pending}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(!o2($))throw Error("Contextual project instructions require safe metadata");this._contextualSystemMessages.push($),this.systemMessages.push($)}syncContextualSystemMessages(){let $=this.systemMessages.filter(a2);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)}appendToHistory($){this._history.push($)}commitPending(){if(this._pending.length>0)this._history.push(...this._pending),this._pending=[]}replaceHistory($){this._history=$.filter((Z)=>!a2(Z)&&!o2(Z))}restoreDurableHistory($){this._contextualSystemMessages=$.filter(o2),this._history=$.filter((Z)=>!a2(Z)&&!o2(Z)),this._pending=[],this.syncContextualSystemMessages()}removeMessages($){this._history=this._history.filter((Z)=>!$(Z)),this._pending=this._pending.filter((Z)=>!$(Z)),this._contextualSystemMessages=this._contextualSystemMessages.filter((Z)=>!$(Z)),this.syncContextualSystemMessages()}writeback(){this.commitPending(),this.context.messages=[...this._contextualSystemMessages,...this._history]}get hasSystemPrompt(){return this.systemMessages.length>0}}function G1($){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 L1($){return{budget:$.budget,usage:0,consecutiveContinuations:0,lastOutputDelta:0,isSubagent:$.isSubagent??!1}}function F1($,Z,J){return{...$,usage:$.usage+Z,lastOutputDelta:Z,consecutiveContinuations:J?$.consecutiveContinuations+1:0}}import m2 from"node:path";var o5=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"]),a5=/^(LD_.+|DYLD_.+|PATH)$/,U1=/^([A-Za-z_][A-Za-z0-9_]*)=([\w./:@-]*)$/;function U0($){let Z=$;while(!0){let J=Z.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!J)break;let W=J[1],K=J[2],Y=W.match(U1);if(!Y)break;let X=Y[1];if(!o5.has(X))break;Z=K}return Z}function q8($){let Z=$;while(!0){let J=Z.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!J)break;let W=J[1],K=J[2],Y=W.match(U1);if(!Y)break;let X=Y[1];if(a5.test(X))break;Z=K}return Z}var s5=[/^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 A$($){let Z=$,J=!0;while(J){J=!1;for(let W of s5){let K=Z.match(W);if(K){Z=Z.slice(K[0].length),J=!0;break}}if(Z.startsWith("-- "))Z=Z.slice(3),J=!0}return Z}function h0($){let Z=[],J="",W=!1,K=!1,Y=!1;for(let X=0;X<$.length;X++){let z=$[X];if(Y){J+=z,Y=!1;continue}if(z==="\\"&&!W){J+=z,Y=!0;continue}if(z==="'"&&!K){W=!W,J+=z;continue}if(z==='"'&&!W){K=!K,J+=z;continue}if(W||K){J+=z;continue}if(z==="|"){if(X+1<$.length&&$[X+1]==="|"){if(J.trim())Z.push(J.trim());J="",X++;continue}return null}if(z===">"||z==="<")return null;if(z==="&"&&X+1<$.length&&$[X+1]==="&"){if(J.trim())Z.push(J.trim());J="",X++;continue}if(z==="&")return null;if(z===";"){if(J.trim())Z.push(J.trim());J="";continue}J+=z}if(J.trim())Z.push(J.trim());return Z.length>0?Z:null}function O1($){let Z=!1,J=!1,W=!1;for(let K=0;K<$.length;K++){let Y=$[K];if(W){W=!1;continue}if(Y==="\\"&&!Z){W=!0;continue}if(Y==="'"&&!J){Z=!Z;continue}if(Y==='"'&&!Z){J=!J;continue}if(Z)continue;if(Y==="$"){let X=$[K+1];if(X&&/[A-Za-z_@*#?!$0-9({]/.test(X))return!0}if(Y==="`")return!0;if(J)continue;if(Y==="|")return!0;if(Y===">"||Y==="<")return!0;if(Y==="{"){let X=$.slice(K);if(/^\{[^}]*,[^}]*\}/.test(X)||/^\{[^}]*\.\.[^}]*\}/.test(X))return!0}}return!1}function O0($){let Z=[],J="",W=!1,K=!1,Y=!1;for(let X=0;X<$.length;X++){let z=$[X];if(Y){J+=z,Y=!1;continue}if(z==="\\"&&!W){if(Y=!0,K){let Q=$[X+1];if(Q&&'$`"\\'.includes(Q))continue;J+=z,Y=!1}continue}if(z==="'"&&!K){W=!W;continue}if(z==='"'&&!W){K=!K;continue}if(!W&&!K&&/[ \t]/.test(z)){if(J)Z.push(J),J="";continue}J+=z}if(J)Z.push(J);return Z}var t5=new Set(["npm","pnpm","yarn","bun"]),y1=new Set(["biome","eslint","jest","mypy","pyright","pytest","ruff","tsc","vitest"]),e5=new Set(["-u","--fix","--update","--update-snapshot","--updateSnapshot","--watch","--watchAll","--write"]);function $6($){return $!==void 0&&/^(?:test|lint|build|type-?check)(?::[\w.-]+)*$/i.test($)}function Z6($){return $.replace(/\s+2>&1\s*$/,"").trim()}function J6($,Z,J){if(!J||Z.length!==2)return;let W=/^(.+?)[ \t]+&&[ \t]+([\s\S]+)$/.exec($);if(!W)return;let K=O0(W[1]??"");if(K.length!==2||K[0]!=="cd")return;let Y=K[1];if(!Y||Y==="-")return;let X=m2.isAbsolute(Y)?m2.resolve(Y):m2.resolve(J,Y);if(!d2.isWithinWorkspace(X,J))return;return W[2]?.trim()||void 0}function s2($,Z){let J=U0(Z6($)),W=h0(J);if(!W||O1(J)||/[\r\n]/.test(J))return!1;let K=W.length===1?W[0]:J6(J,W,Z);if(!K)return!1;let Y=O0(K);if(Y.length===0||Y.some((H)=>[...e5].some((V)=>H===V||H.startsWith(`${V}=`))))return!1;let[X,z,Q]=Y;if(t5.has(X??""))return $6(z==="run"?Q:z)||z==="--test";if((X==="npx"||X==="bunx")&&y1.has(z??""))return!0;if(y1.has(X??""))return!0;if(X==="node"&&z==="--test")return!0;if(X==="go"&&["build","test","vet"].includes(z??""))return!0;return X==="cargo"&&["build","check","clippy","test"].includes(z??"")}function O8($,Z){if($===void 0)return!0;if(typeof $!=="string"||$.split(/[\\/]/).includes(".."))return!1;if(!Z)return!m2.isAbsolute($);let J=m2.isAbsolute($)?m2.resolve($):m2.resolve(Z,$);return d2.isWithinWorkspace(J,Z)}var x$=w2("Agent"),W6=3;function k$($,Z,J){if($!=="length")return{action:"none"};if(Z>=W6)return{action:"truncated"};if(G1(J)==="stop")return x$.info("[Loop] Token budget: diminishing returns detected, skipping recovery"),{action:"budget_stop"};return{action:"recover"}}var K6=[/:\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],Y6=/```[\s\S]{50,}```/,P1="请执行你提到的操作,不要只是描述。使用 Edit/Write/ApplyPatch/Bash 工具来实际修改文件。",X6=2;function T$($,Z,J=!0){if(!$||Z>=X6)return{action:"none"};if(!J&&Y6.test($))return{action:"retry",prompt:P1};let W=$.slice(-200),K=W.match(/```/g);if(K&&K.length%2!==0)return{action:"none"};if(K6.some((X)=>X.test(W)))return{action:"retry",prompt:P1};return{action:"none"}}var z6=[/\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}(?:测试|单测|集成测试|检查|构建)/],E1={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},Q6={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},H6="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.",B6="Required verification did not run successfully before the retry limit.",V6=3;function N1($,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&&s2(J.metadata.command,W)){$.add(J.metadata.command);return}if(!["Task","TaskOutput"].includes(Z))return;let K=J.metadata?.verificationCommands;if(!Array.isArray(K))return;for(let Y of K)if(typeof Y==="string"&&s2(Y,W))$.add(Y)}function f$($,Z,J){if(!$||!z6.some((Q)=>Q.test($)))return{action:"none"};let W=Object.keys(E1).filter((Q)=>E1[Q].test($)),K=[...Z],Y=W.filter((Q)=>!K.some((H)=>Q6[Q].test(H)));if(W.length>0?Y.length===0:K.some((Q)=>s2(Q)))return{action:"none"};if(J>=V6)return{action:"fail",message:B6};let z=W.length>1&&Y.length>0?` Missing successful verification categories: ${Y.join(", ")}.`:"";return{action:"retry",prompt:`${H6}${z}`}}var D6=[/\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|子代理|子智能体)/],_1=[/\b(?:do not|don't|never)\s+(?:delegate|call|use|invoke)\b/i,/(?:不要|禁止|无需)(?:委派|调用|使用).{0,20}(?:Task|子代理|子智能体)?/];function S1($){return typeof $==="string"&&_1.some((Z)=>Z.test($))}var j6=[/\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|子代理)/],w6=[/\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 q6($){if(typeof $!=="string")return;if(w6.some((Z)=>Z.test($)))return"multiple-allowed";return j6.some((Z)=>Z.test($))?"required":void 0}function I0($){for(let Z of $){let J=q6(Z);if(J!==void 0)return J==="required"}return!1}var G6="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.",L6="Required delegation did not complete before the retry limit.",F6=3;function A1($,Z,J){let W=(typeof $==="string"?[$]:$??[]).map((X)=>X.trim()).filter(Boolean),K=I0(W),Y=!1;if(!K)for(let X of W){if(_1.some((z)=>z.test(X)))break;if(D6.some((z)=>z.test(X))){Y=!0;break}}if(W.length===0||!K&&!Y||Z.has("Task"))return{action:"none"};if(J>=F6)return{action:"fail",message:L6};return{action:"retry",prompt:G6}}var U6=[/\b(?:use|create|enter|start|work\s+(?:in|inside))\b.{0,60}\bworktree\b/i,/(?:使用|创建|进入).{0,30}(?:worktree|工作树)/i],O6=[/\b(?:exit|leave)\b.{0,40}\bworktree\b/i,/\bworktree\b.{0,60}\b(?:action\s+)?(?:keep|remove)\b/i,/(?:退出|离开).{0,30}(?:worktree|工作树)/i],y6=[/\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 x1($){return y6.reduce((Z,J)=>Z.replace(J," "),$)}function p0($){if(typeof $!=="string")return!1;let Z=x1($);return U6.some((J)=>J.test(Z))}var P6="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.",E6="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.",b6="Required worktree lifecycle did not complete before the retry limit.",N6=3;function k1($,Z,J){if(!$)return{action:"none"};let W=x1($);if(!p0(W))return{action:"none"};let K=O6.some((X)=>X.test(W));if(Z.has("TaskWorktree"))return{action:"none"};let Y=!Z.has("EnterWorktree")?"EnterWorktree":K&&!Z.has("ExitWorktree")?"ExitWorktree":void 0;if(!Y)return{action:"none"};if(J>=N6)return{action:"fail",message:b6};return{action:"retry",tool:Y,prompt:Y==="EnterWorktree"?P6:E6}}var b1=30000;async function M$($){try{let J=t2.getInstance().executeStopHooks({projectDir:$.workspaceRoot??i(),sessionId:$.sessionId,permissionMode:$.permissionMode,reason:$.reason,abortSignal:$.abortSignal}),W,K=new Promise((Y)=>{W=setTimeout(()=>Y("timeout"),b1)});try{let Y=await Promise.race([J,K]);if(Y==="timeout")return x$.warn(`[Loop] Stop hook 超时 (${b1}ms),按 shouldStop: true 处理`),{action:"stop"};let X=Y;if(!X.shouldStop)return{action:"continue",reason:X.continueReason};return{action:"stop"}}finally{clearTimeout(W)}}catch(Z){return x$.warn("[Loop] Stop hook execution failed:",Z),{action:"stop"}}}async function _6($,Z){let J;while(!(J=await $.next()).done)if(Z)await Z(J.value);return J.value}var S6=[/<system-reminder>[\s\S]*?<\/system-reminder>/gi,/<file[^>]*>[\s\S]*?<\/file>/gi,/<hooks_context>[\s\S]*?<\/hooks_context>/gi,/<[^>]+>/g];function A6($){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 x6($){let Z=$;for(let Q of S6)Z=Z.replace(Q," ");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|$)|$)/),K=W&&W[1].length>=6?W[1]:J;if(K=K.trim().replace(/[\s.。!!??,,;;::-]+$/,""),K.length<=60)return K;let Y=K.slice(0,60),X=Y.lastIndexOf(" ");return`${(X>36?Y.slice(0,X):Y).trimEnd()}…`}function T1($){return x6(A6($))}import{EventEmitter as k6}from"events";import f1 from"node:path";function v$($){if(M1($.sessionId),!f1.isAbsolute($.projectPath))throw Error("projectPath must be absolute");return{sessionId:$.sessionId,projectPath:f1.resolve($.projectPath)}}function f8($){let Z=v$($);return JSON.stringify([Z.projectPath,Z.sessionId])}class e2 extends k6{static instance;constructor(){super();this.setMaxListeners(100)}static getInstance(){if(!e2.instance)e2.instance=new e2;return e2.instance}publish($,Z,J,W){let K=v$($);this.emit("event",{sessionId:K.sessionId,projectPath:K.projectPath,type:Z,...W!==void 0?{seq:W}:{},properties:J})}subscribe($){return this.on("event",$),()=>this.off("event",$)}}var y0=e2.getInstance();var x2=w2("Agent"),g0=new Set;async function T6($,Z){let J=$.sessionId;if(!J||$.subagentInfo)return;if(g0.has(J))return;if(g0.size>=5000)g0.clear();g0.add(J);try{let W=$.workspaceRoot,K=await P0.findSessionMetadata(J,W);if(!K)return;if(K.title&&K.title.trim())return;let Y=T1(Z);if(!Y)return;await P0.updateSessionMetadata(J,K.projectPath,{title:Y}),y0.publish({sessionId:J,projectPath:K.projectPath},"session.updated",{title:Y})}catch(W){x2.debug?.("[Loop] 自动生成会话标题失败:",W)}}var R$=`<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>`,c2="Tool execution was blocked because its durable call record could not be committed. No tool side effect was started.",v1="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 $0 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 u2($){return $.executionEngine?.getContextManager()}async function W2($,Z,J,W=null,K,Y={}){let X=Y.required??$.executionEngine!==void 0;try{let z=u2($),Q=typeof J==="string"?J.trim()!=="":J.some((H)=>H.type==="text"?H.text.trim()!=="":!0);if(z&&Z.sessionId&&Q){let H=await z.saveMessage(Z.sessionId,"user",J,W,K,Z.subagentInfo);if(X&&!H)throw Error("Durable user-message commit returned no identity");return T6(Z,J),H}if(X&&Z.sessionId&&Q)throw Error("Durable user-message storage is unavailable")}catch(z){if(x2.warn("[Loop] 保存用户消息失败:",z),X)throw new $0("user_message",{cause:z})}return null}async function C($,Z,J,W,K,Y,X={}){let z=X.required??$.executionEngine!==void 0;try{let Q=u2($),H=Boolean(J.trim()||K?.trim());if(Q&&Z.sessionId&&H){let V=await Q.saveMessage(Z.sessionId,"assistant",J,W,Y,Z.subagentInfo,K);if(z&&!V)throw Error("Durable assistant-message commit returned no identity");return V}if(z&&Z.sessionId&&H)throw Error("Durable assistant-message storage is unavailable")}catch(Q){if(x2.warn("[Loop] 保存助手消息失败:",Q),z)throw new $0("assistant_message",{cause:Q})}return null}async function R1($,Z,J){try{let W=u2($);if(W&&Z.sessionId)return await W.saveMessage(Z.sessionId,"system",R$,J,void 0,Z.subagentInfo)}catch(W){x2.warn("[Loop] 保存中断边界失败:",W)}return null}async function h1($,Z,J,W,K){try{let Y=u2($);if(!Y||!Z.sessionId||J.length===0)return null;return await Y.saveMessage(Z.sessionId,"system",`<contextual-project-instructions-ref count="${J.length}" />`,K,{contextualProjectRules:!0,ruleReferences:JSON.parse(JSON.stringify(J.map((X)=>({...X})))),triggerPaths:[...W]},Z.subagentInfo)}catch(Y){x2.warn("[Loop] 保存 contextual project rules provenance 失败:",Y)}return null}async function h$($,Z,J,W,K,Y={}){try{let X=u2($);if(X&&Z.sessionId){let z=await X.saveToolUse(Z.sessionId,J,W,K,Z.subagentInfo);if(Y.required&&!z)throw Error("Durable tool-use commit returned no identity");return z}if(Y.required&&Z.sessionId)throw Error("Durable tool-use storage is unavailable")}catch(X){if(x2.warn("[Loop] 保存工具调用失败:",X),Y.required)throw X}return null}async function m0($,Z,J,W,K,Y,X,z,Q,H={}){try{let V=u2($);if(V&&Z.sessionId){let w=await V.saveToolResult(Z.sessionId,J,W,K,Y,X,Z.subagentInfo,z,Q);if(H.required&&!w)throw Error("Durable tool-result commit returned no identity");return w}if(H.required&&Z.sessionId)throw Error("Durable tool-result storage is unavailable")}catch(V){if(x2.warn("[Loop] 保存工具结果失败:",V),H.required)throw V}return null}async function E0($,Z,J,W,K={}){try{let Y=u2($);if(Y&&Z.sessionId){let X=await Y.saveCompaction(Z.sessionId,J,W,null);if(K.required&&!X)throw Error("Compaction checkpoint commit returned no identity");return X||null}if(K.required&&Z.sessionId)throw Error("Compaction checkpoint storage is unavailable")}catch(Y){if(x2.warn("[Loop] 保存压缩数据失败:",Y),K.required)throw Y}return null}import{createHash as n7}from"node:crypto";import{promises as m6}from"node:fs";import d6 from"node:path";import{nanoid as T2}from"nanoid";import*as d from"node:fs/promises";import*as l2 from"node:path";var C1={enabled:!0,maxIndexLines:200};var f6="memory",I1="MEMORY.md";class C${memoryDir;config;initialized=!1;constructor($,Z,J){if(J)this.memoryDir=J;else{let W=Z0($);this.memoryDir=l2.join(W,f6)}this.config={...C1,...Z}}async initialize(){if(this.initialized)return;await d.mkdir(this.memoryDir,{recursive:!0}),this.initialized=!0}async loadIndex(){if(!this.config.enabled)return null;await this.initialize();let $=l2.join(this.memoryDir,I1);try{let Z=await d.readFile($,"utf-8");if(!Z.trim())return null;let J=Z.split(`
|
|
4
4
|
`),K=J.slice(0,this.config.maxIndexLines).join(`
|
|
@@ -118,7 +118,7 @@ Full output saved to: ${z}`}catch{return`${Z}
|
|
|
118
118
|
|
|
119
119
|
${K}`}}import{Mutex as D7}from"async-mutex";import{nanoid as j7}from"nanoid";import*as B2 from"node:fs/promises";import*as a1 from"node:path";import{Mutex as e6}from"async-mutex";import $7 from"write-file-atomic";var u0=1,n1=8388608;function m$($,Z){return $ instanceof Error&&"code"in $&&$.code===Z}function Z7($){if(typeof $==="string")return!0;if(!Array.isArray($))return!1;return $.every((Z)=>{if(!Z||typeof Z!=="object"||!("type"in Z))return!1;if(Z.type==="text")return"text"in Z&&typeof Z.text==="string";return Z.type==="image_url"&&"image_url"in Z&&typeof Z.image_url==="object"&&Z.image_url!==null&&"url"in Z.image_url&&typeof Z.image_url.url==="string"})}function J7($,Z,J){let W;try{W=JSON.parse($)}catch(Y){throw Error(`Invalid steering inbox JSON: ${Z}`,{cause:Y})}if(!W||typeof W!=="object"||!("version"in W)||W.version!==u0||!("sessionId"in W)||W.sessionId!==J||!("messages"in W)||!Array.isArray(W.messages))throw Error(`Invalid steering inbox record: ${Z}`);let K=W.messages.map((Y)=>{if(!Y||typeof Y!=="object"||!("id"in Y)||typeof Y.id!=="string"||!("content"in Y)||!Z7(Y.content)||!("queuedAt"in Y)||typeof Y.queuedAt!=="number"||"persisted"in Y&&typeof Y.persisted!=="boolean"||"outputSchema"in Y&&Y.outputSchema!==void 0&&(!Y.outputSchema||typeof Y.outputSchema!=="object"||Array.isArray(Y.outputSchema)))throw Error(`Invalid steering inbox message: ${Z}`);let X="outputSchema"in Y&&Y.outputSchema!==void 0?i0(Y.outputSchema).schema:void 0;return{id:Y.id,content:Y.content,queuedAt:Y.queuedAt,..."persisted"in Y&&Y.persisted===!0?{persisted:!0}:{},...X?{outputSchema:X}:{}}});return{version:u0,sessionId:J,messages:K}}function W7($){return new Set($.flatMap((Z)=>Z.type==="inbox_acknowledged"?Z.data.messageIds:[]))}class r0{workspaceRoot;sessionId;filePath;mutex=new e6;messages=[];constructor($,Z,J){this.workspaceRoot=$;this.sessionId=Z;this.filePath=J}static async open($,Z){let J=new r0($,Z,l0($,Z));return await J.loadAndReconcile(),J}async enqueue($,Z){return this.mutex.runExclusive(async()=>{if(Z&&!Z(this.messages))return!1;let J=[...this.messages,{...$,recovered:!1}];return await this.persist(J),this.messages=J,!0})}async acknowledge($){if($.length===0)return;let Z=new Set($);await this.mutex.runExclusive(async()=>{let J=this.messages.filter((W)=>!Z.has(W.id));this.messages=J,await this.persist(J)})}list(){return this.messages.map(($)=>({...$,content:typeof $.content==="string"?$.content:$.content.map((Z)=>Z.type==="text"?{...Z}:{...Z,image_url:{...Z.image_url}}),...$.outputSchema?{outputSchema:JSON.parse(JSON.stringify($.outputSchema))}:{}}))}count(){return this.messages.length}recoveredCount(){return this.messages.filter(($)=>$.recovered).length}async loadAndReconcile(){await this.mutex.runExclusive(async()=>{let $={version:u0,sessionId:this.sessionId,messages:[]};try{if((await B2.stat(this.filePath)).size>n1)throw Error(`Steering inbox exceeds ${n1} bytes: ${this.filePath}`);await B2.chmod(this.filePath,384),$=J7(await B2.readFile(this.filePath,"utf8"),this.filePath,this.sessionId)}catch(K){if(!m$(K,"ENOENT"))throw K}let Z=X2(this.workspaceRoot,this.sessionId),J=new Set;try{J=W7(o1(await B2.readFile(Z,"utf8"),Z))}catch(K){if(!m$(K,"ENOENT"))throw K}let W=$.messages.filter((K)=>!J.has(K.id)).map((K)=>({...K,recovered:!0}));if(this.messages=W,W.length!==$.messages.length)await this.persist(W)})}async persist($){if(await B2.mkdir(a1.dirname(this.filePath),{recursive:!0,mode:448}),$.length===0){await B2.unlink(this.filePath).catch((J)=>{if(!m$(J,"ENOENT"))throw J});return}let Z={version:u0,sessionId:this.sessionId,messages:$.map(({recovered:J,...W})=>W)};await $7(this.filePath,`${JSON.stringify(Z)}
|
|
120
120
|
`,{encoding:"utf8",mode:384,fsync:!0})}}import*as G2 from"node:fs/promises";import*as W5 from"node:path";import{nanoid as z2}from"nanoid";class i2{sessionId;projectPath;static instances=new Map;store;subscribers=new Set;highestSeq=0;constructor($,Z){this.sessionId=$;this.projectPath=Z;this.store=new q2(X2(Z,$))}static for($,Z){let J=`${Z}\x00${$}`,W=i2.instances.get(J);if(!W)W=new i2($,Z),i2.instances.set(J,W);return W}static release($,Z){i2.instances.delete(`${Z}\x00${$}`)}get lastSeq(){return this.highestSeq}async commit($){let Z=await this.store.append($);return this.record(Z),Z}async commitBatch($){if($.length===0)return[];let Z=await this.store.appendBatch($);for(let J of Z)this.record(J);return Z}async commitValidated($){let Z=await this.store.appendValidated($);return this.record(Z),Z}async commitValidatedBatch($){let Z=await this.store.appendValidatedBatch($);for(let J of Z)this.record(J);return Z}emitDelta($){for(let Z of this.subscribers)Z.onDelta?.($);y0.publish({sessionId:this.sessionId,projectPath:this.projectPath},"delta",{delta:$})}subscribe($,Z){if(this.subscribers.add($),Z?.fromSeq!==void 0)this.replay($,Z.fromSeq);return()=>{this.subscribers.delete($)}}async replay($,Z){let J=await this.store.readFromSeq(Z);for(let W of J)$.onCommitted(W)}record($){if(typeof $.seq==="number"&&$.seq>this.highestSeq)this.highestSeq=$.seq;for(let Z of this.subscribers)Z.onCommitted($);y0.publish({sessionId:this.sessionId,projectPath:this.projectPath},`committed.${$.type}`,{event:$},$.seq)}}function _0($){let Z=null,J=null;for(let W of $){if(W.type==="turn_started"){Z=W.data;continue}if(W.type==="turn_completed")J={type:"turn_completed",data:W.data};else if(W.type==="turn_aborted")J={type:"turn_aborted",data:W.data};else continue;if(Z?.turnId===J.data.turnId)Z=null}return{active:Z,lastTerminal:J}}class E2 extends Error{}var Y7="Tool execution was interrupted by a process restart. The operation may have partially completed. Inspect the workspace, running processes, and external state before deciding whether to retry it.",X7=20,z7=1e4,Q7=1e5,H7=2592000000;function B7($,Z){let J=V2($),W=J.findLastIndex((K)=>K.type==="turn_started"&&K.data.turnId===Z);if(W<0)return;for(let K=J.length-1;K>W;K--){let Y=J[K];if(Y?.type!=="message_created")continue;let X=Y.data.metadata;if(!X||typeof X!=="object"||Array.isArray(X))continue;let z=X.turnFinalization;if(!z||typeof z!=="object"||Array.isArray(z))continue;let{inputMessageIds:Q,turnsCount:H,toolCallsCount:V,durationMs:w}=z,G=Array.isArray(Q)?Q.filter((j)=>typeof j==="string"&&j.length>0&&j.length<=128):[];if(z.turnId!==Z||Z.length===0||Z.length>128||!Array.isArray(Q)||Q.length>X7||G.length!==Q.length||typeof H!=="number"||!Number.isSafeInteger(H)||H<0||H>z7||typeof V!=="number"||!Number.isSafeInteger(V)||V<0||V>Q7||typeof w!=="number"||!Number.isSafeInteger(w)||w<0||w>H7)continue;return{turnId:Z,inputMessageIds:[...new Set(G)],turnsCount:H,toolCallsCount:V,durationMs:w}}return}function s1($,Z){let J=V2($),W=Z?J.findLastIndex((Q)=>Q.type==="turn_started"&&Q.data.turnId===Z):-1;if(Z&&W<0)return{all:[],orphaned:[]};let K=new Map,Y=new Set,X=new Set;for(let Q of J.slice(W+1)){if(Q.type==="interaction_requested"){X.add(Q.data.toolCallId);continue}if(Q.type!=="part_created")continue;let H=Q.data.payload&&typeof Q.data.payload==="object"&&!Array.isArray(Q.data.payload)?Q.data.payload:{},V=typeof H.toolCallId==="string"?H.toolCallId:Q.data.partId;if(Q.data.partType==="tool_call")K.set(V,{toolCallId:V,toolName:typeof H.toolName==="string"?H.toolName:"unknown"});else if(Q.data.partType==="tool_result")Y.add(V),Y.add(Q.data.partId),Y.add(Q.data.messageId)}let z=[...K.values()];return{all:z,orphaned:z.filter((Q)=>!Y.has(Q.toolCallId)&&!X.has(Q.toolCallId))}}class M2{projectPath;maxSessions;version;constructor($=i(),Z=100,J=$5()){this.projectPath=$,this.maxSessions=Z,this.version=J}createEvent($,Z,J){return{id:z2(),sessionId:Z,projectPath:this.projectPath,timestamp:new Date().toISOString(),type:$,cwd:this.projectPath,gitBranch:t1(this.projectPath),version:this.version,data:J}}log($){return i2.for($,this.projectPath)}async ensureSessionCreated($,Z){let J=X2(this.projectPath,$);if((await new q2(J).readAll()).length>0)return;let Y=new Date().toISOString(),X={sessionId:$,rootId:Z?.parentSessionId??$,parentId:Z?.parentSessionId,relationType:Z?"subagent":void 0,resumedFrom:Z?.resumedFrom,rootAgentId:Z?.rootAgentId,resumeDepth:Z?.resumeDepth,title:void 0,status:"running",taskStatus:Z?"running":"queued",taskFailure:null,agentType:Z?.subagentType,model:void 0,permission:void 0,createdAt:Y,updatedAt:Y},z=this.createEvent("session_created",$,X);await this.log($).commit(z)}buildCompactionMetadata($){let Z={trigger:$.trigger,preTokens:$.preTokens};if($.reason)Z.reason=$.reason;if($.strategy)Z.strategy=$.strategy;if($.postTokens!==void 0)Z.postTokens=$.postTokens;if($.filesIncluded)Z.filesIncluded=$.filesIncluded;if($.replacementMessages)Z.checkpointVersion=Z5;return Z}async initialize(){try{let $=Z0(this.projectPath);await G2.mkdir($,{recursive:!0,mode:493}),console.log(`[PersistentStore] 初始化存储目录: ${$}`)}catch($){console.warn("[PersistentStore] 无法创建持久化存储目录:",$)}}async saveMessage($,Z,J,W=null,K,Y,X){try{await this.ensureSessionCreated($,Y);let z=new Date().toISOString(),Q=z2(),H={messageId:Q,role:Z,parentMessageId:W??void 0,inboxMessageId:K?.inboxMessageId,createdAt:z,model:K?.model,usage:K?.usage,metadata:K?JSON.parse(JSON.stringify(K)):void 0},V=this.createEvent("message_created",$,H),w=Z==="assistant"&&X?.trim()?[this.createEvent("part_created",$,{partId:z2(),messageId:Q,partType:"reasoning",payload:{text:X},createdAt:z})]:[],G=typeof J==="string"?[this.createEvent("part_created",$,{partId:z2(),messageId:Q,partType:"text",payload:{text:J},createdAt:z})]:J.map((j)=>this.createEvent("part_created",$,{partId:z2(),messageId:Q,partType:j.type==="text"?"text":"image",payload:j.type==="text"?{text:j.text}:{mimeType:V7(j.image_url.url)??"image/png",dataUrl:j.image_url.url},createdAt:z}));return await this.log($).commitBatch([V,...w,...G]),Q}catch(z){throw console.error(`[PersistentStore] 保存消息失败 (session: ${$}):`,z),z}}async acknowledgeInboxMessages($,Z){if(Z.length===0)return;await this.ensureSessionCreated($);let J=new Date().toISOString();await this.log($).commit(this.createEvent("inbox_acknowledged",$,{messageIds:[...Z],acknowledgedAt:J}))}async saveTurnStart($,Z){await this.ensureSessionCreated($);try{await this.log($).commitValidated((J)=>{let W=V2(J);if(W.some((Y)=>Y.type==="turn_started"&&Y.data.turnId===Z.turnId))throw new E2;let K=_0(W).active;if(K)throw Error(`Session already has an active turn: ${K.turnId}`);return this.createEvent("turn_started",$,Z)})}catch(J){if(!(J instanceof E2))throw J}}async saveTurnCompletion($,Z,J=[]){await this.ensureSessionCreated($);try{await this.log($).commitValidatedBatch((W)=>{let K=V2(W),Y=new Set(K.flatMap((H)=>H.type==="inbox_acknowledged"?H.data.messageIds:[])),X=[...new Set(J)].filter((H)=>!Y.has(H)),z=K.findLast((H)=>(H.type==="turn_completed"||H.type==="turn_aborted")&&H.data.turnId===Z.turnId);if(z){if(z.type==="turn_aborted"||X.length===0)throw new E2;return[this.createEvent("inbox_acknowledged",$,{messageIds:X,acknowledgedAt:Z.completedAt})]}let Q=_0(K).active;if(!Q||Q.turnId!==Z.turnId)throw Error(`Turn is not active: ${Z.turnId}`);return[...X.length>0?[this.createEvent("inbox_acknowledged",$,{messageIds:X,acknowledgedAt:Z.completedAt})]:[],this.createEvent("turn_completed",$,Z)]})}catch(W){if(!(W instanceof E2))throw W}}async saveTurnAbort($,Z){await this.saveTurnTerminal($,"turn_aborted",Z)}async recoverInterruptedTurn($){await this.ensureSessionCreated($);let Z;try{await this.log($).commitValidatedBatch((J)=>{let W=V2(J),K=_0(W).active,Y=s1(W);if(!K&&Y.orphaned.length===0)throw new E2;let X=K?B7(W,K.turnId):void 0;if(K&&X&&Y.orphaned.length===0){Z={turnId:K.turnId,outcome:"completed"};let w=new Set(W.flatMap((T)=>T.type==="inbox_acknowledged"?T.data.messageIds:[])),G=X.inputMessageIds.filter((T)=>!w.has(T)),j=new Date().toISOString();return[...G.length>0?[this.createEvent("inbox_acknowledged",$,{messageIds:G,acknowledgedAt:j})]:[],this.createEvent("turn_completed",$,{turnId:K.turnId,completedAt:j,turnsCount:X.turnsCount,toolCallsCount:X.toolCallsCount,durationMs:X.durationMs})]}Z=K?{turnId:K.turnId,outcome:"aborted"}:void 0;let z=K?s1(W,K.turnId).all.length:0,Q=new Date().toISOString(),H=K?Date.parse(K.startedAt):Number.NaN,V=Y.orphaned.map((w)=>this.createEvent("part_created",$,{partId:w.toolCallId,messageId:w.toolCallId,partType:"tool_result",payload:{toolCallId:w.toolCallId,toolName:w.toolName,output:null,error:Y7,metadata:{processRestartRecovery:!0,sideEffectsUncertain:!0}},createdAt:Q}));return K?[...V,this.createEvent("turn_aborted",$,{turnId:K.turnId,cause:"process_restart",abortedAt:Q,turnsCount:0,toolCallsCount:z,durationMs:Number.isFinite(H)?Math.max(0,Date.now()-H):0})]:V})}catch(J){if(!(J instanceof E2))throw J}return Z}async saveInteractionRequest($,Z){await this.ensureSessionCreated($),await this.log($).commitValidated((J)=>{if(J.some((K)=>K.type==="interaction_requested"&&K.data.requestId===Z.requestId))throw Error(`Interaction request already exists: ${Z.requestId}`);return this.createEvent("interaction_requested",$,Z)})}async saveInteractionResponse($,Z){await this.ensureSessionCreated($),await this.log($).commitValidated((J)=>{if(!J.some((Y)=>Y.type==="interaction_requested"&&Y.data.requestId===Z.requestId))throw Error(`Interaction request not found: ${Z.requestId}`);if(J.some((Y)=>Y.type==="interaction_responded"&&Y.data.requestId===Z.requestId))throw Error(`Interaction already responded: ${Z.requestId}`);return this.createEvent("interaction_responded",$,Z)})}async saveInteractionRecovery($,Z){await this.ensureSessionCreated($),await this.log($).commitValidated((J)=>{if(!J.some((Y)=>Y.type==="interaction_responded"&&Y.data.requestId===Z.requestId))throw Error(`Interaction response not found: ${Z.requestId}`);if(J.some((Y)=>Y.type==="interaction_recovered"&&Y.data.requestId===Z.requestId))throw Error(`Interaction already recovered: ${Z.requestId}`);return this.createEvent("interaction_recovered",$,Z)})}async saveReviewStart($,Z){await this.ensureSessionCreated($),await this.log($).commitValidated((J)=>{if(J.some((Y)=>Y.type==="review_started"&&Y.data.reviewId===Z.reviewId))throw Error(`Review already exists: ${Z.reviewId}`);if(J.some((Y)=>Y.type==="review_started"&&!J.some((X)=>X.type==="review_completed"&&X.data.reviewId===Y.data.reviewId)))throw Error("Session already has an active review");return this.createEvent("review_started",$,Z)})}async saveReviewCompletion($,Z){await this.ensureSessionCreated($),await this.log($).commitValidated((J)=>{if(!J.some((Y)=>Y.type==="review_started"&&Y.data.reviewId===Z.reviewId))throw Error(`Review not found: ${Z.reviewId}`);if(J.some((Y)=>Y.type==="review_completed"&&Y.data.reviewId===Z.reviewId))throw Error(`Review already completed: ${Z.reviewId}`);return this.createEvent("review_completed",$,Z)})}async saveToolUse($,Z,J,W=null,K){try{await this.ensureSessionCreated($,K);let Y=new Date().toISOString(),X=W??z2(),z=[];if(!W){let V={messageId:X,role:"assistant",parentMessageId:void 0,createdAt:Y};z.push(this.createEvent("message_created",$,V))}let Q=z2(),H={partId:Q,messageId:X,partType:"tool_call",payload:{toolCallId:Q,toolName:Z,input:J},createdAt:Y};if(z.push(this.createEvent("part_created",$,H)),Z==="Task"&&J&&typeof J==="object"){let V=J,w=typeof V.subagent_session_id==="string"?V.subagent_session_id:void 0,G=typeof V.subagent_type==="string"?V.subagent_type:void 0;if(w&&G){let j={partId:z2(),messageId:X,partType:"subtask_ref",payload:{childSessionId:w,agentType:G,status:"running",summary:typeof V.description==="string"?V.description:"",startedAt:Y},createdAt:Y};z.push(this.createEvent("part_created",$,j))}}return await this.log($).commitBatch(z),Q}catch(Y){throw console.error(`[PersistentStore] 保存工具调用失败 (session: ${$}):`,Y),Y}}async saveToolResult($,Z,J,W,K=null,Y,X,z,Q){try{await this.ensureSessionCreated($,X);let H=new Date().toISOString(),V=K??z2(),w=[];if(!K){let j={messageId:V,role:"assistant",parentMessageId:void 0,createdAt:H};w.push(this.createEvent("message_created",$,j))}let G={partId:Z,messageId:V,partType:"tool_result",payload:{toolCallId:Z,toolName:J,output:W,error:Y??null,...Q===void 0?{}:{metadata:Q}},createdAt:H};if(w.push(this.createEvent("part_created",$,G)),z){let j=z.subagentStatus==="running"?null:H,T={partId:z2(),messageId:V,partType:"subtask_ref",payload:{childSessionId:z.subagentSessionId,agentType:z.subagentType,description:z.subagentDescription??"",status:z.subagentStatus,summary:z.subagentSummary??"",resumedFrom:z.subagentResumedFrom??null,rootAgentId:z.subagentRootId??z.subagentSessionId,resumeDepth:z.subagentResumeDepth??0,verificationVerdict:z.verificationVerdict??null,startedAt:H,finishedAt:j},createdAt:H};w.push(this.createEvent("part_created",$,T))}return await this.log($).commitBatch(w),Z}catch(H){throw console.error(`[PersistentStore] 保存工具结果失败 (session: ${$}):`,H),H}}async saveCompaction($,Z,J,W=null){try{await this.ensureSessionCreated($);let K=new Date().toISOString(),Y=z2(),X={messageId:Y,role:"system",parentMessageId:W??void 0,createdAt:K},z=this.buildCompactionMetadata(J),Q={partId:z2(),messageId:Y,partType:"summary",payload:{text:Z,metadata:z,...J.replacementMessages?{replacementMessages:J5(J.replacementMessages)}:{}},createdAt:K},H=[this.createEvent("message_created",$,X),this.createEvent("part_created",$,Q)];return await this.log($).commitBatch(H),Y}catch(K){throw console.error(`[PersistentStore] 保存压缩失败 (session: ${$}):`,K),K}}async initSession($,Z){await this.ensureSessionCreated($,Z)}async loadEvents($){try{let Z=X2(this.projectPath,$),W=await new q2(Z).readAll();return W.length>0?V2(W):null}catch{return null}}async loadSession($){try{let Z=X2(this.projectPath,$),J=new q2(Z),W=V2(await J.readAll());if(W.length===0)return null;let K=W.find((Y)=>Y.type==="session_created");return{sessionId:$,userId:void 0,preferences:{},configuration:{},startTime:new Date(K?.timestamp??W[0].timestamp).getTime()}}catch{return null}}async loadConversation($){try{let Z=X2(this.projectPath,$),J=new q2(Z),W=V2(await J.readAll());if(W.length===0)return null;let K=new Map;for(let Q of W){if(Q.type==="message_created")K.set(Q.data.messageId,{id:Q.data.messageId,role:Q.data.role,content:"",timestamp:new Date(Q.timestamp).getTime()});if(Q.type==="part_created"&&Q.data.partType==="text"){let H=K.get(Q.data.messageId);if(H){let V=Q.data.payload;H.content=V.text??""}}if(Q.type==="part_created"&&Q.data.partType==="image"){let H=K.get(Q.data.messageId);if(H)H.content=H.content?`${H.content}
|
|
121
|
-
[Image]`:"[Image]"}}let Y=Array.from(K.values()),X=W[W.length-1],z=new Date(X.timestamp).getTime();return{messages:Y,topics:[],lastActivity:z}}catch{return null}}async listSessions(){try{let $=Z0(this.projectPath);return(await G2.readdir($)).filter((J)=>J.endsWith(".jsonl")).map((J)=>J.replace(".jsonl","")).sort()}catch{return[]}}async getSessionSummary($){try{let Z=X2(this.projectPath,$),J=new q2(Z);if(!(await J.getStats()).exists)return null;let K=await J.readAll();if(K.length===0)return null;let Y=V2(K),X=K[K.length-1],z=Y.filter((Q)=>Q.type==="message_created"&&["user","assistant"].includes(Q.data.role)).length;return{sessionId:$,lastActivity:new Date(X.timestamp).getTime(),messageCount:z,topics:[]}}catch{return null}}async deleteSession($){try{let Z=X2(this.projectPath,$);await new q2(Z).delete(),await G2.unlink(l0(this.projectPath,$)).catch((W)=>{if(W.code!=="ENOENT")throw W});try{let{getProjectionDb:W,removeSessionFromProjection:K}=await import("./chunk-
|
|
121
|
+
[Image]`:"[Image]"}}let Y=Array.from(K.values()),X=W[W.length-1],z=new Date(X.timestamp).getTime();return{messages:Y,topics:[],lastActivity:z}}catch{return null}}async listSessions(){try{let $=Z0(this.projectPath);return(await G2.readdir($)).filter((J)=>J.endsWith(".jsonl")).map((J)=>J.replace(".jsonl","")).sort()}catch{return[]}}async getSessionSummary($){try{let Z=X2(this.projectPath,$),J=new q2(Z);if(!(await J.getStats()).exists)return null;let K=await J.readAll();if(K.length===0)return null;let Y=V2(K),X=K[K.length-1],z=Y.filter((Q)=>Q.type==="message_created"&&["user","assistant"].includes(Q.data.role)).length;return{sessionId:$,lastActivity:new Date(X.timestamp).getTime(),messageCount:z,topics:[]}}catch{return null}}async deleteSession($){try{let Z=X2(this.projectPath,$);await new q2(Z).delete(),await G2.unlink(l0(this.projectPath,$)).catch((W)=>{if(W.code!=="ENOENT")throw W});try{let{getProjectionDb:W,removeSessionFromProjection:K}=await import("./chunk-sgnjekfb.js"),Y=await W();if(Y)K(Y,$,this.projectPath)}catch{}}catch(Z){console.warn(`[PersistentStore] 删除会话失败 (session: ${$}):`,Z)}}async cleanupOldSessions(){try{let $=await this.listSessions();if($.length<=this.maxSessions)return;let W=(await Promise.all($.map((K)=>this.getSessionSummary(K)))).filter((K)=>K!==null).sort((K,Y)=>Y.lastActivity-K.lastActivity).slice(this.maxSessions).map((K)=>K.sessionId);await Promise.all(W.map((K)=>this.deleteSession(K))),console.log(`[PersistentStore] 已清理 ${W.length} 个旧会话`)}catch($){console.error("[PersistentStore] 清理旧会话失败:",$)}}async saveTurnTerminal($,Z,J){await this.ensureSessionCreated($);try{await this.log($).commitValidated((W)=>{let K=V2(W);if(K.some((z)=>(z.type==="turn_completed"||z.type==="turn_aborted")&&z.data.turnId===J.turnId))throw new E2;let X=_0(K).active;if(!X||X.turnId!==J.turnId)throw Error(`Turn is not active: ${J.turnId}`);return Z==="turn_completed"?this.createEvent("turn_completed",$,J):this.createEvent("turn_aborted",$,J)})}catch(W){if(!(W instanceof E2))throw W}}async getStorageStats(){try{let $=await this.listSessions(),Z=0;for(let J of $){let W=X2(this.projectPath,J),Y=await new q2(W).getStats();Z+=Y.size}return{totalSessions:$.length,totalSize:Z,projectPath:this.projectPath}}catch{return{totalSessions:0,totalSize:0,projectPath:this.projectPath}}}async checkStorageHealth(){try{let $=Z0(this.projectPath);await G2.mkdir($,{recursive:!0,mode:493});let Z=W5.join($,".health-check");return await G2.writeFile(Z,"test","utf-8"),await G2.unlink(Z),{isAvailable:!0,canWrite:!0}}catch($){return{isAvailable:!1,canWrite:!1,error:$ instanceof Error?$.message:String($)}}}static async listAllProjects(){return e1()}}function V7($){return/^data:([^;,]+)[;,]/.exec($)?.[1]??null}var K5=131072,Y5=new Map;function d$($,Z){let J=`${$}\x00${Z}`,W=Y5.get(J);if(!W)W=new D7,Y5.set(J,W);return W}function l$($,Z){let J=JSON.stringify($);if(J===void 0)throw Error(`${Z} is not JSON serializable`);if(Buffer.byteLength(J,"utf8")>K5)throw Error(`${Z} exceeds ${K5} bytes`);return JSON.parse(J)}function X5($){if($.type==="askUserQuestion")return"question";if($.type==="mcpElicitation")return"elicitation";if($.type==="permission"||$.type==="mcpSampling")return"permission";return}function w7($,Z){return JSON.stringify($)===JSON.stringify(Z)}function q7($,Z){if($.request.interactionType!=="elicitation")return l$(Z,"Interaction response");return l$({approved:Z.approved,...Z.reason?{reason:Z.reason}:{},...Z.elicitation?{elicitation:{action:Z.elicitation.action}}:{},...Z.openExternalUrl?{openExternalUrl:!0}:{}},"Interaction response")}function z5($){let Z=$.request.details;if(!Z||typeof Z!=="object"||Array.isArray(Z))throw Error(`Invalid durable interaction details: ${$.request.requestId}`);return Z}function G7($){let Z=$.response?.response;if(!Z||typeof Z!=="object"||Array.isArray(Z))throw Error(`Invalid durable interaction response: ${$.request.requestId}`);return Z}function L7($){if(!$.answers||Object.keys($.answers).length===0)return"No structured answers were provided.";return Object.entries($.answers).map(([Z,J])=>{let W=Array.isArray(J)?J.join(", "):J;return`${Z}: ${W}`}).join(`
|
|
122
122
|
`)}function F7($,Z){let{request:J}=$;if(J.interactionType==="question"){let X=L7(Z);return{toolOutput:`User answers:
|
|
123
123
|
${X}`,inbox:`The process restarted while waiting for a structured answer. The recovered user response is:
|
|
124
124
|
${X}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
var t=["auto","low","medium","high"],s=new Set(["openai-completions","openai-responses","openai-codex-responses","azure-openai-responses"]);function n(e){return/(?:^|[/.:_-])gpt-5(?:$|[/.:_-])/i.test(e.id)}function f(e){return typeof e==="string"&&t.includes(e)}function p(e){if(e.api==="openai-codex-responses"||s.has(e.api)&&n(e))return["low","medium","high"];return[]}function u(e,r){let i=p(e);if(r!=="auto"&&!i.includes(r))throw Error(`Response verbosity ${r} is not supported by ${e.name}`);if(r==="auto")return{selection:r,effective:"provider-default",supported:i};return{selection:r,effective:r,supported:i,providerValue:r}}var a=["auto","standard","fast","flex"],o=new Set(["openai-completions","openai-responses","openai-codex-responses","azure-openai-responses"]);function S(e){return typeof e==="string"&&a.includes(e)}function c(e){if(o.has(e.api))return["standard","fast","flex"];if(e.api==="anthropic-messages"&&/(?:^|-)claude-opus-4-6(?:-|$)/i.test(e.id))return["standard","fast"];return["standard"]}function l(e,r){let i=c(e);if(r!=="auto"&&!i.includes(r))throw Error(`Service tier ${r} is not supported by ${e.name}`);if(r==="auto")return{selection:r,effective:"provider-default",supported:i};if(r==="standard")return{selection:r,effective:"standard",supported:i,...o.has(e.api)?{providerValue:"default"}:{}};if(r==="fast")return{selection:r,effective:"fast",supported:i,providerValue:e.api==="anthropic-messages"?"fast":"priority"};return{selection:r,effective:"flex",supported:i,providerValue:"flex"}}
|
|
2
|
-
export{f as
|
|
2
|
+
export{f as zf,p as Af,u as Bf,S as Cf,c as Df,l as Ef};
|