blade-code 0.10.102 → 0.10.103
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-03qymy9e.js +1 -0
- package/dist/{chunk-cpk84yrx.js → chunk-07w0qapm.js} +1 -1
- package/dist/{chunk-9n5ystr6.js → chunk-0aa40zbs.js} +3 -3
- package/dist/{chunk-9sx3vsyj.js → chunk-0hr050ck.js} +1 -1
- package/dist/chunk-0kdrgmyy.js +1 -0
- package/dist/{chunk-qw57eqns.js → chunk-14bs89sm.js} +2 -2
- package/dist/{chunk-kwkkcs4y.js → chunk-181ef74x.js} +1 -1
- package/dist/{chunk-c6tq09mt.js → chunk-41cg66y0.js} +1 -1
- package/dist/{chunk-p0rvgzpx.js → chunk-41ympwz1.js} +1 -1
- package/dist/{chunk-anez8ekm.js → chunk-42bcht8b.js} +2 -2
- package/dist/{chunk-39qzk9nm.js → chunk-47e6tdbb.js} +1 -1
- package/dist/{chunk-enwtex3j.js → chunk-4qfke0gd.js} +2 -2
- package/dist/chunk-5sk7q6pw.js +1 -0
- package/dist/chunk-6v10cs0h.js +1 -0
- package/dist/{chunk-4fmtv329.js → chunk-6wsvgk20.js} +1 -1
- package/dist/chunk-7ab7jcvn.js +1 -0
- package/dist/{chunk-j00px1es.js → chunk-7fz3w4rk.js} +1 -1
- package/dist/chunk-8zjn51fr.js +1 -0
- package/dist/{chunk-ykkqywtq.js → chunk-946wkbmw.js} +1 -1
- package/dist/{chunk-k7vv9vne.js → chunk-9p20hhs0.js} +1 -1
- package/dist/{chunk-vw328ehw.js → chunk-a7ejfmtc.js} +1 -1
- package/dist/chunk-a8x3xygs.js +1 -0
- package/dist/{chunk-6kb69vkx.js → chunk-aa5zmwd9.js} +3 -3
- package/dist/{chunk-0zhdjaen.js → chunk-abd57h72.js} +1 -1
- package/dist/{chunk-rkk39efr.js → chunk-afa35v3f.js} +1 -1
- package/dist/{chunk-6r6yzw44.js → chunk-b0j9v359.js} +267 -265
- package/dist/{chunk-qjeadpj2.js → chunk-bt18xsc6.js} +1 -1
- package/dist/chunk-bx82y5ce.js +1 -0
- package/dist/chunk-c475tfqf.js +2 -0
- package/dist/{chunk-9b0896bm.js → chunk-c479s9v2.js} +1 -1
- package/dist/{chunk-a5jv8pn9.js → chunk-cpex23zk.js} +1 -1
- package/dist/{chunk-v6hffjwc.js → chunk-e1tt6b1w.js} +2 -2
- package/dist/{chunk-czcxx8tb.js → chunk-f3426b1c.js} +1 -1
- package/dist/{chunk-19xfer55.js → chunk-f945dzj6.js} +2 -2
- package/dist/{chunk-w9xfks7f.js → chunk-fhfzdyba.js} +1 -1
- package/dist/{chunk-qcy79mva.js → chunk-fva7jnjy.js} +1 -1
- package/dist/chunk-fw2x9p4c.js +6 -0
- package/dist/{chunk-pdqczfn3.js → chunk-gr80w0vh.js} +1 -1
- package/dist/{chunk-zxhv8xfp.js → chunk-gxgq70gm.js} +1 -1
- package/dist/{chunk-10taec1j.js → chunk-j2dyprdy.js} +1 -1
- package/dist/{chunk-ffp2rn7f.js → chunk-jaswqpe7.js} +1 -1
- package/dist/{chunk-1wgese5c.js → chunk-k9fveqq6.js} +1 -1
- package/dist/chunk-kdjtxpxw.js +1 -0
- package/dist/chunk-kf7whgr7.js +2 -0
- package/dist/{chunk-fn9cse83.js → chunk-khtxprbv.js} +1 -1
- package/dist/{chunk-m4wnqx0e.js → chunk-mgsvn9v4.js} +2 -2
- package/dist/{chunk-d8wzc602.js → chunk-n7mzxa8h.js} +2 -2
- package/dist/chunk-nz7kjzc0.js +1 -0
- package/dist/{chunk-70hwyc2w.js → chunk-q69fzq4y.js} +1 -1
- package/dist/{chunk-b8n5mx53.js → chunk-q6eb20fz.js} +1 -1
- package/dist/{chunk-hexj26gw.js → chunk-rahch228.js} +1 -1
- package/dist/{chunk-3awjdsef.js → chunk-rchz6j90.js} +1 -1
- package/dist/{chunk-2va6ex5v.js → chunk-rvk9r2cm.js} +1 -1
- package/dist/{chunk-425p4nwx.js → chunk-s10pmnrd.js} +2 -2
- package/dist/{chunk-na3jmz7f.js → chunk-s66fwx1p.js} +1 -1
- package/dist/chunk-s6vzjear.js +10 -0
- package/dist/{chunk-f9asjkfz.js → chunk-sdbbyagy.js} +1 -1
- package/dist/{chunk-9hsbjy6a.js → chunk-szxajr6e.js} +1 -1
- package/dist/{chunk-q3vza5gt.js → chunk-tgdhsm5t.js} +2 -2
- package/dist/chunk-v4w5b2cq.js +1 -0
- package/dist/chunk-vk4xbek0.js +1 -0
- package/dist/{chunk-53xtssbf.js → chunk-w7hy5wh1.js} +1 -1
- package/dist/{chunk-cp7xsjj2.js → chunk-wyhyw9rq.js} +2 -2
- package/dist/{chunk-6yezrqe7.js → chunk-wzmqkam9.js} +1 -1
- package/dist/{chunk-hpjnk87v.js → chunk-x3cxmwnz.js} +1 -1
- package/dist/chunk-xm8nyj5z.js +2 -0
- package/dist/{chunk-fpx3462x.js → chunk-xtb84adp.js} +1 -1
- package/dist/chunk-yr56ttgw.js +1 -0
- package/dist/{chunk-kt5jqaxp.js → chunk-ywarj5j9.js} +1 -1
- package/dist/{chunk-rej5bbbs.js → chunk-z9gd9spf.js} +1 -1
- package/dist/web/assets/{ChatView-C5kVDWL0.js → ChatView-_4ut_-Jh.js} +16 -16
- package/dist/web/assets/{CodeBlockHighlighter-BxJu15oF.js → CodeBlockHighlighter-DkDr6wE9.js} +1 -1
- package/dist/web/assets/{FilePreview-BDNq89O6.js → FilePreview-DCI-oqhJ.js} +1 -1
- package/dist/web/assets/{KanbanBoard-CCn0j1Ow.js → KanbanBoard-CB5C4tJC.js} +1 -1
- package/dist/web/assets/{MarkdownRenderer-15FrKNPV.js → MarkdownRenderer-ychfmIQK.js} +3 -3
- package/dist/web/assets/{SettingsModal-DCL04xT_.js → SettingsModal-SSdk0Bjr.js} +1 -1
- package/dist/web/assets/{TaskSwitcher-Gyn_K98p.js → TaskSwitcher-EnaUhn3o.js} +1 -1
- package/dist/web/assets/{TerminalPanel-Cbh0NmHM.js → TerminalPanel-BcWxLSV3.js} +1 -1
- package/dist/web/assets/{arrow-left-wfNAFD9Y.js → arrow-left-Ob5r20g7.js} +1 -1
- package/dist/web/assets/{calendar-clock-BbbqqtLj.js → calendar-clock-eOALT8DB.js} +1 -1
- package/dist/web/assets/{chevrons-up-down-uCUY_a67.js → chevrons-up-down-BkZBwmbt.js} +1 -1
- package/dist/web/assets/{clock-3-DfiIeEEf.js → clock-3-DQp9SzYc.js} +1 -1
- package/dist/web/assets/{external-link-CilEshFB.js → external-link-BuGUowPD.js} +1 -1
- package/dist/web/assets/{folder-D9K0ykgI.js → folder-c92kw1oI.js} +1 -1
- package/dist/web/assets/{index-BKBXGV6s.js → index-CS8jtO_A.js} +16 -16
- package/dist/web/assets/{pause-D4a4_iHl.js → pause-DP_CXoH7.js} +1 -1
- package/dist/web/assets/{play-D9guMjPv.js → play-DcRwtohz.js} +1 -1
- package/dist/web/assets/{session-events-DelJesUm.js → session-events-CrAgnaj2.js} +1 -1
- package/dist/web/assets/{teamService-CAVeS_dL.js → teamService-JyVbGQhi.js} +1 -1
- package/dist/web/index.html +2 -2
- package/package.json +1 -1
- package/dist/chunk-00rps629.js +0 -2
- package/dist/chunk-4t3h306m.js +0 -6
- package/dist/chunk-9018357g.js +0 -1
- package/dist/chunk-a8mgzsh7.js +0 -1
- package/dist/chunk-c3zcqqb7.js +0 -1
- package/dist/chunk-cwnaydst.js +0 -1
- package/dist/chunk-d7rg6t0n.js +0 -1
- package/dist/chunk-gdp02sqp.js +0 -1
- package/dist/chunk-kfmh3t1r.js +0 -1
- package/dist/chunk-kvdk0pfk.js +0 -1
- package/dist/chunk-maebpz1j.js +0 -2
- package/dist/chunk-n4cw6vt1.js +0 -1
- package/dist/chunk-p7t010gq.js +0 -1
- package/dist/chunk-ryemn19e.js +0 -10
- package/dist/chunk-xy5fmskp.js +0 -1
- package/dist/chunk-y3anmree.js +0 -1
- package/dist/chunk-yx4802a0.js +0 -2
- package/dist/chunk-zy6vm5jm.js +0 -1
package/dist/blade.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{we as W}from"./chunk-
|
|
2
|
+
import{we as W}from"./chunk-gr80w0vh.js";import{Ae as M,ze as F}from"./chunk-z9gd9spf.js";import"./chunk-q6eb20fz.js";import"./chunk-v508x7cg.js";import"./chunk-dg0d3303.js";import"./chunk-aa5zmwd9.js";import"./chunk-41cg66y0.js";import"./chunk-f945dzj6.js";import"./chunk-sdbbyagy.js";import"./chunk-f3426b1c.js";import"./chunk-c475tfqf.js";import{Oh as N,Ph as B}from"./chunk-0hr050ck.js";import"./chunk-q69fzq4y.js";import{oi as T}from"./chunk-n7mzxa8h.js";import"./chunk-s10pmnrd.js";import"./chunk-9p20hhs0.js";import"./chunk-14bs89sm.js";import"./chunk-wyhyw9rq.js";import"./chunk-rvk9r2cm.js";import"./chunk-tgdhsm5t.js";import{Xi as J}from"./chunk-fhfzdyba.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-8zjn51fr.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-bx82y5ce.js");K(U.map((Z)=>p.resolve(Q,Z)))}if(q(E,"--trust-workspace","--trustWorkspace")){let{WorkspaceTrustService:K}=await import("./chunk-v4w5b2cq.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-fw2x9p4c.js");if(await K())return}if(W(),q(E,"--print","-p")){let{handlePrintMode:K}=await import("./chunk-c479s9v2.js");if(await K())return}if(E.includes("--acp")){let{runAcpIntegration:K}=await import("./chunk-4qfke0gd.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-nz7kjzc0.js"),import("./chunk-a8x3xygs.js"),import("./chunk-946wkbmw.js"),import("./chunk-e1tt6b1w.js"),import("./chunk-szxajr6e.js"),import("./chunk-s66fwx1p.js"),import("./chunk-6wsvgk20.js"),import("./chunk-181ef74x.js"),import("./chunk-0kdrgmyy.js"),import("./chunk-rahch228.js"),import("./chunk-s6vzjear.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-7ab7jcvn.js").then(({checkVersionOnStartup:v})=>v()),[{render:w},{createElement:j},{AppWrapper:C}]=await Promise.all([import("ink"),import("react"),import("./chunk-42bcht8b.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};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Kd as a,Ld as b,Md as c,Nd as d,Od as e,Pd as f,Qd as g}from"./chunk-wzmqkam9.js";import"./chunk-s0tq8gyx.js";import"./chunk-x3cxmwnz.js";import"./chunk-2hb222re.js";import"./chunk-fva7jnjy.js";import"./chunk-41cg66y0.js";import"./chunk-c475tfqf.js";import"./chunk-0hr050ck.js";import"./chunk-n7mzxa8h.js";import"./chunk-9p20hhs0.js";import"./chunk-14bs89sm.js";import"./chunk-tgdhsm5t.js";import"./chunk-fhfzdyba.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,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{xh as F}from"./chunk-f945dzj6.js";import{ui as D,vi as E}from"./chunk-s10pmnrd.js";import G from"node:path";function A(b){if(Array.isArray(b))return b.map((q)=>A(q));if(b!==null&&typeof b==="object"&&Object.getPrototypeOf(b)===Object.prototype)return Object.fromEntries(Object.entries(b).map(([q,w])=>[q,A(w)]));return b}function H(b){return A(b)}function I(b,q){let w=new D(q?.credentials??E().credentials);return w.configureModelProviders(b.modelProviders,b.models),w}async function Q(b,q){let w=G.resolve(b),x=F.getInstance(),[J,K]=await Promise.all([x.loadWorkspaceModelConfig(w,q),x.loadWorkspaceRuntimeSettings(w,q)]),z={...H(q),...J,...K},B=I(z);return x.validateConfig(z,B),{projectRoot:w,config:z,catalog:B}}function T(b){let q=H(b.config);return{projectRoot:G.resolve(b.projectRoot),config:q,catalog:I(q,b.catalog)}}
|
|
2
2
|
export{H as sf,Q as tf,T as uf};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{$b as M4}from"./chunk-8hprmrd5.js";import{Fd as u0,Hd as K6,Id as h1,Jd as Q6,Qd as o$,Tc as vJ,Vc as IJ,Wc as uJ,Xc as m2,Yc as c2,bc as X$,cd as gJ,dd as T4,ed as R4,fd as I2,gd as k1,hd as h4,id as x4,jd as S1,nd as DJ,vd as K1}from"./chunk-6yezrqe7.js";import{Vd as S4}from"./chunk-s0tq8gyx.js";import{$d as v0,Xd as H0,_d as bJ}from"./chunk-hpjnk87v.js";import{af as eJ}from"./chunk-dg0d3303.js";import{bf as b4,cf as i0,df as f4,ef as zJ,hf as E1,if as V6,jf as BJ,kf as jJ,mf as UJ}from"./chunk-3awjdsef.js";import{$f as E4,Xf as J$,Yf as r0,dg as H4}from"./chunk-00rps629.js";import{og as N$}from"./chunk-6kb69vkx.js";import{yh as nJ}from"./chunk-f9asjkfz.js";import{Nh as X0}from"./chunk-9sx3vsyj.js";import{ni as k0}from"./chunk-d8wzc602.js";import{Bi as CJ}from"./chunk-qw57eqns.js";import{Mi as b$,Oi as r6,Pi as P0,Qi as R1,Si as hJ,Ti as xJ,Ui as kJ}from"./chunk-q3vza5gt.js";import{Vi as L8}from"./chunk-w9xfks7f.js";function A$($){return $.role==="system"&&Array.isArray($.content)}function f$($){if($.role!=="system"||!$.metadata||Array.isArray($.metadata))return!1;return typeof $.metadata==="object"&&$.metadata.contextualProjectRules===!0}class A1{systemMessages;_contextualSystemMessages;_history;_pending=[];_contextRevision=0;context;constructor($,J){this.context=$;let Z=$.messages.find(A$);if(this._contextualSystemMessages=$.messages.filter(f$),Z)this.systemMessages=[Z,...this._contextualSystemMessages];else if(J)this.systemMessages=[{role:"system",content:[{type:"text",text:J,providerOptions:{anthropic:{cacheControl:{type:"ephemeral"}}}}]},...this._contextualSystemMessages];else this.systemMessages=[...this._contextualSystemMessages];this._history=$.messages.filter((W)=>!A$(W)&&!f$(W))}get historyLength(){return this._history.length}get history(){return this._history}get pending(){return this._pending}get contextRevision(){return this._contextRevision}toLLMMessages(){return[...this.systemMessages,...this._history,...this._pending]}getMessagesForLLM(){return this.toLLMMessages()}getHistory(){return this._history}appendPending($){this._pending.push($)}appendUser($){this._pending.push($)}appendAssistant($){this._pending.push($)}appendToolResult($){this._pending.push($)}appendContextualProjectInstructions($){if(!f$($))throw Error("Contextual project instructions require safe metadata");this._contextualSystemMessages.push($),this.systemMessages.push($)}syncContextualSystemMessages(){let $=this.systemMessages.filter(A$);this.systemMessages.splice(0,this.systemMessages.length,...$,...this._contextualSystemMessages)}appendControl($,J){if($==="system")throw Error("Cannot append system control message via appendControl. Use constructor for root system prompt.");this._pending.push(J)}appendDurableControl($){if(!$.id||$.role!=="user")throw Error("Durable control messages require a user role and identity");if(this._history.some((J)=>J.id===$.id))return;this._history.push($)}appendToHistory($){this._history.push($)}commitPending(){if(this._pending.length>0)this._history.push(...this._pending),this._pending=[]}replaceHistory($){this._history=$.filter((J)=>!A$(J)&&!f$(J)),this._contextRevision++}restoreDurableHistory($){this._contextualSystemMessages=$.filter(f$),this._history=$.filter((J)=>!A$(J)&&!f$(J)),this._pending=[],this.syncContextualSystemMessages(),this._contextRevision++}removeMessages($){let J=[this._history.length,this._pending.length,this._contextualSystemMessages.length];if(this._history=this._history.filter((Z)=>!$(Z)),this._pending=this._pending.filter((Z)=>!$(Z)),this._contextualSystemMessages=this._contextualSystemMessages.filter((Z)=>!$(Z)),this.syncContextualSystemMessages(),this._history.length!==J[0]||this._pending.length!==J[1]||this._contextualSystemMessages.length!==J[2])this._contextRevision++}writeback(){this.commitPending(),this.context.messages=[...this._contextualSystemMessages,...this._history]}get hasSystemPrompt(){return this.systemMessages.length>0}}function b6($){if($.isSubagent)return"continue";if(!$.budget||$.budget<=0)return"continue";if($.consecutiveContinuations>=3&&$.lastOutputDelta<500)return"stop";if($.usage/$.budget>=0.9)return"stop";return"continue"}function E6($){return{budget:$.budget,usage:0,consecutiveContinuations:0,lastOutputDelta:0,isSubagent:$.isSubagent??!1}}function S6($,J,Z){return{...$,usage:$.usage+J,lastOutputDelta:J,consecutiveContinuations:Z?$.consecutiveContinuations+1:0}}import Q$ from"node:path";var c4=new Set(["GOEXPERIMENT","GOOS","GOARCH","CGO_ENABLED","GO111MODULE","RUST_BACKTRACE","RUST_LOG","NODE_ENV","PYTHONUNBUFFERED","PYTHONDONTWRITEBYTECODE","GIT_TERMINAL_PROMPT","LANG","LANGUAGE","LC_ALL","LC_CTYPE","LC_TIME","CHARSET","TERM","COLORTERM","NO_COLOR","FORCE_COLOR","TZ","LS_COLORS","LSCOLORS","GREP_COLOR","GREP_COLORS"]),l4=/^(LD_.+|DYLD_.+|PATH)$/,M6=/^([A-Za-z_][A-Za-z0-9_]*)=([\w./:@-]*)$/;function l$($){let J=$;while(!0){let Z=J.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!Z)break;let W=Z[1],Y=Z[2],V=W.match(M6);if(!V)break;let K=V[1];if(!c4.has(K))break;J=Y}return J}function uZ($){let J=$;while(!0){let Z=J.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!Z)break;let W=Z[1],Y=Z[2],V=W.match(M6);if(!V)break;let K=V[1];if(l4.test(K))break;J=Y}return J}var i4=[/^timeout[ \t]+(?:--foreground[ \t]+|--preserve-status[ \t]+|-v[ \t]+|--verbose[ \t]+|-k[ \t]+\S+[ \t]+|--kill-after[= ]\S+[ \t]+|-s[ \t]+\S+[ \t]+|--signal[= ]\S+[ \t]+)*\S+[ \t]+/,/^time[ \t]+/,/^nice[ \t]+(?:-n[ \t]+\d+[ \t]+|-\d+[ \t]+)?/,/^nohup[ \t]+/];function D2($){let J=$,Z=!0;while(Z){Z=!1;for(let W of i4){let Y=J.match(W);if(Y){J=J.slice(Y[0].length),Z=!0;break}}if(J.startsWith("-- "))J=J.slice(3),Z=!0}return J}function i$($){let J=[],Z="",W=!1,Y=!1,V=!1;for(let K=0;K<$.length;K++){let Q=$[K];if(V){Z+=Q,V=!1;continue}if(Q==="\\"&&!W){Z+=Q,V=!0;continue}if(Q==="'"&&!Y){W=!W,Z+=Q;continue}if(Q==='"'&&!W){Y=!Y,Z+=Q;continue}if(W||Y){Z+=Q;continue}if(Q==="|"){if(K+1<$.length&&$[K+1]==="|"){if(Z.trim())J.push(Z.trim());Z="",K++;continue}return null}if(Q===">"||Q==="<")return null;if(Q==="&"&&K+1<$.length&&$[K+1]==="&"){if(Z.trim())J.push(Z.trim());Z="",K++;continue}if(Q==="&")return null;if(Q===";"){if(Z.trim())J.push(Z.trim());Z="";continue}Z+=Q}if(Z.trim())J.push(Z.trim());return J.length>0?J:null}function T6($){let J=!1,Z=!1,W=!1;for(let Y=0;Y<$.length;Y++){let V=$[Y];if(W){W=!1;continue}if(V==="\\"&&!J){W=!0;continue}if(V==="'"&&!Z){J=!J;continue}if(V==='"'&&!J){Z=!Z;continue}if(J)continue;if(V==="$"){let K=$[Y+1];if(K&&/[A-Za-z_@*#?!$0-9({]/.test(K))return!0}if(V==="`")return!0;if(Z)continue;if(V==="|")return!0;if(V===">"||V==="<")return!0;if(V==="{"){let K=$.slice(Y);if(/^\{[^}]*,[^}]*\}/.test(K)||/^\{[^}]*\.\.[^}]*\}/.test(K))return!0}}return!1}function K$($){let J=[],Z="",W=!1,Y=!1,V=!1;for(let K=0;K<$.length;K++){let Q=$[K];if(V){Z+=Q,V=!1;continue}if(Q==="\\"&&!W){if(V=!0,Y){let X=$[K+1];if(X&&'$`"\\'.includes(X))continue;Z+=Q,V=!1}continue}if(Q==="'"&&!Y){W=!W;continue}if(Q==='"'&&!W){Y=!Y;continue}if(!W&&!Y&&/[ \t]/.test(Q)){if(Z)J.push(Z),Z="";continue}Z+=Q}if(Z)J.push(Z);return J}var r4=new Set(["npm","pnpm","yarn","bun"]),R6=new Set(["biome","eslint","jest","mypy","pyright","pytest","ruff","tsc","vitest"]),n4=new Set(["-u","--fix","--update","--update-snapshot","--updateSnapshot","--watch","--watchAll","--write"]),o4=/[ \t]*;[ \t]*echo[ \t]+"[A-Za-z0-9 _:=.-]*(?:\$\{PIPESTATUS\[0\]\}|\$\?)[A-Za-z0-9 _:=.-]*"[ \t]*$/;function a4($){return $!==void 0&&/^(?:test|lint|build|type-?check)(?::[\w.-]+)*$/i.test($)}function h6($){return $.replace(/\s+2>&1\s*$/,"").trim()}function s4($,J,Z){if(!Z||J.length!==2)return;let W=/^(.+?)[ \t]+&&[ \t]+([\s\S]+)$/.exec($);if(!W)return;let Y=K$(W[1]??"");if(Y.length!==2||Y[0]!=="cd")return;let V=Y[1];if(!V||V==="-")return;let K=Q$.isAbsolute(V)?Q$.resolve(V):Q$.resolve(Z,V);if(!X$.isWithinWorkspace(K,Z))return;return W[2]?.trim()||void 0}function t4($){let J=[],Z=!1,W=!1,Y=!1;for(let V=0;V<$.length;V++){let K=$[V];if(Y){Y=!1;continue}if(K==="\\"&&!Z){Y=!0;continue}if(K==="'"&&!W){Z=!Z;continue}if(K==='"'&&!Z){W=!W;continue}if(K!=="|"||Z||W)continue;if($[V+1]==="|")return;J.push(V)}return J}function e4($){let J=K$($),[Z,W,Y]=J;if(Z!=="head"&&Z!=="tail")return!1;if(J.length===1)return!0;let V=(K)=>K!==void 0&&/^[1-9]\d{0,4}$/.test(K);if(J.length===2)return W?.startsWith("--lines=")&&V(W.slice(8))||W?.startsWith("-")&&V(W.slice(1));return J.length===3&&(W==="-n"||W==="--lines")&&V(Y)}function $5($){let J=h6($.replace(o4,"").trim()),Z=t4(J);if(!Z)return;if(Z.length===0)return x6(J);if(Z.length!==1)return;let W=Z[0];if(W===void 0)return;let Y=h6(J.slice(0,W).trim()),V=J.slice(W+1).trim();if(!Y||!e4(V))return;return x6(Y)}function x6($){let Z=i$($)?.at(-1);if(!Z)return $;let W=K$(Z),[Y,V]=W;if(!(Y==="vitest"||(Y==="npx"||Y==="bunx")&&V==="vitest")||W.some((Q)=>Q==="--configLoader"||Q.startsWith("--configLoader=")))return $;return`${$} --configLoader runner`}function y$($,J){let Z=$5($);if(!Z)return!1;let W=l$(Z),Y=i$(W);if(!Y||T6(W)||/[\r\n]/.test(W))return!1;let V=Y.length===1?Y[0]:s4(W,Y,J);if(!V)return!1;let K=K$(V);if(K.length===0||K.some((B)=>[...n4].some((j)=>B===j||B.startsWith(`${j}=`))))return!1;let[Q,X,H]=K;if(r4.has(Q??""))return a4(X==="run"?H:X)||X==="--test";if((Q==="npx"||Q==="bunx")&&R6.has(X??""))return!0;if(R6.has(Q??""))return!0;if(Q==="node"&&X==="--test")return!0;if(Q==="go"&&["build","test","vet"].includes(X??""))return!0;return Q==="cargo"&&["build","check","clippy","test"].includes(X??"")}function cZ($,J){if($===void 0)return!0;if(typeof $!=="string"||$.split(/[\\/]/).includes(".."))return!1;if(!J)return!Q$.isAbsolute($);let Z=Q$.isAbsolute($)?Q$.resolve($):Q$.resolve(J,$);return X$.isWithinWorkspace(Z,J)}var w2=k0("Agent"),J5=3;function q2($,J,Z){if($!=="length")return{action:"none"};if(J>=J5)return{action:"truncated"};if(b6(Z)==="stop")return w2.info("[Loop] Token budget: diminishing returns detected, skipping recovery"),{action:"budget_stop"};return{action:"recover"}}var Z5=[/:\s*$/,/:\s*$/,/\.\.\.\s*$/,/让我(先|来|开始|查看|检查|修复)/,/Let me (first|start|check|look|fix)/i,/I('ll| will) (now |)(create|write|edit|update|modify|fix|add|implement)/i,/我(现在就|来|要)(创建|写入|编辑|修改|修复|添加|实现)/,/\d+\.\s+(First|Next|Then|Finally)/i],W5=/```[\s\S]{50,}```/,k6="请执行你提到的操作,不要只是描述。使用 Edit/Write/ApplyPatch/Bash 工具来实际修改文件。",Y5=2;function G2($,J,Z=!0){if(!$||J>=Y5)return{action:"none"};if(!Z&&W5.test($))return{action:"retry",prompt:k6};let W=$.slice(-200),Y=W.match(/```/g);if(Y&&Y.length%2!==0)return{action:"none"};if(Z5.some((K)=>K.test(W)))return{action:"retry",prompt:k6};return{action:"none"}}var V5=[/\b(?:run|execute|rerun|re-run)\b[\s\S]{0,60}\b(?:tests?|test suite|lint|type-?check|build)\b/i,/\b(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?(?:test|lint|build|type-?check)\b/i,/(?:运行|执行|跑|重新运行).{0,30}(?:测试|单测|集成测试|检查|构建)/],C6={test:/\b(?:tests?|test suite)\b|(?:测试|单测|集成测试)/i,lint:/\blint(?:ing)?\b/i,"type-check":/\btype[\s-]?check(?:ing)?\b|\btsc\b|类型检查/i,build:/\bbuild\b|构建/i},K5={test:/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?test\b|(?:^|\s)(?:node|bun)\s+--test\b|(?:^|\s)(?:vitest|jest|pytest|go\s+test|cargo\s+test)\b/i,lint:/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?lint\b/i,"type-check":/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?type-?check\b|(?:^|\s)tsc\b/i,build:/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?build\b/i},Q5="The user explicitly required verification, but it has not run successfully. Do not finish or explain. Your next action must be a Bash tool call that runs the requested test, lint, type-check, or build command. Inspect the command result and fix any failure before finishing.",X5="Required verification did not run successfully before the retry limit.",H5=3;function I6($,J,Z,W){if(!Z.success)return;if(["Edit","Write","ApplyPatch","NotebookEdit"].includes(J)){$.clear();return}if(J==="Bash"&&typeof Z.metadata?.command==="string"&&Z.metadata.exit_code===0&&y$(Z.metadata.command,W)){$.add(Z.metadata.command);return}if(!["Task","TaskOutput"].includes(J))return;let Y=Z.metadata?.verificationCommands;if(!Array.isArray(Y))return;for(let V of Y)if(typeof V==="string"&&y$(V,W))$.add(V)}function F2($,J,Z){if(!$||!V5.some((X)=>X.test($)))return{action:"none"};let W=Object.keys(C6).filter((X)=>C6[X].test($)),Y=[...J],V=W.filter((X)=>!Y.some((H)=>K5[X].test(H)));if(W.length>0?V.length===0:Y.some((X)=>y$(X)))return{action:"none"};if(Z>=H5)return{action:"fail",message:X5};let Q=W.length>1&&V.length>0?` Missing successful verification categories: ${V.join(", ")}.`:"";return{action:"retry",prompt:`${Q5}${Q}`}}var z5=[/\bdelegate\b[\s\S]{0,120}\b(?:Task tool|subagent|agent)\b/i,/\b(?:call|use|invoke)\b[\s\S]{0,80}\bTask tool\b/i,/(?:委派|交给|调用|使用).{0,60}(?:Task|子代理|子智能体)/],u6=[/\b(?:do not|don't|never)\s+(?:delegate|call|use|invoke)\b/i,/(?:不要|禁止|无需)(?:委派|调用|使用).{0,20}(?:Task|子代理|子智能体)?/];function g6($){return typeof $==="string"&&u6.some((J)=>J.test($))}var B5=[/\b(?:call|use|invoke)\b[\s\S]{0,30}\bTask(?: tool)?\b[\s\S]{0,30}\bexactly once\b/i,/\bexactly once\b[\s\S]{0,30}\b(?:call|use|invoke)\b[\s\S]{0,30}\bTask(?: tool)?\b/i,/\bexactly one\b[\s\S]{0,30}\bTask(?: tool)? calls?\b/i,/(?:Task|子代理).{0,20}(?:恰好|仅|只)(?:调用|使用)?一次/,/(?:恰好|仅|只)(?:调用|使用)?一次.{0,20}(?:Task|子代理)/],j5=[/\b(?:do not|don't|never)\s+(?:call|use|invoke)\s+(?:the\s+)?Task\b[\s\S]{0,30}\bexactly once\b/i,/\bTask\b[\s\S]{0,30}\b(?:does not|doesn't|need not)\b[\s\S]{0,30}\bexactly once\b/i,/\bmultiple\s+Task(?: tool)?\s+calls?\s+(?:are\s+)?allowed\b/i,/(?:不要|禁止).{0,12}(?:Task|子代理).{0,12}(?:恰好|仅|只)(?:调用|使用)?一次/];function U5($){if(typeof $!=="string")return;if(j5.some((J)=>J.test($)))return"multiple-allowed";return B5.some((J)=>J.test($))?"required":void 0}function r$($){for(let J of $){let Z=U5(J);if(Z!==void 0)return Z==="required"}return!1}var D5="The user explicitly required delegation, but no Task tool call completed successfully. Do not solve the task directly or explain. Your next action must be a Task tool call using the requested subagent.",w5="Required delegation did not complete before the retry limit.",q5=3;function p6($,J,Z){let W=(typeof $==="string"?[$]:$??[]).map((K)=>K.trim()).filter(Boolean),Y=r$(W),V=!1;if(!Y)for(let K of W){if(u6.some((Q)=>Q.test(K)))break;if(z5.some((Q)=>Q.test(K))){V=!0;break}}if(W.length===0||!Y&&!V||J.has("Task"))return{action:"none"};if(Z>=q5)return{action:"fail",message:w5};return{action:"retry",prompt:D5}}var G5=[/\b(?:use|create|enter|start|work\s+(?:in|inside))\b.{0,60}\bworktree\b/i,/(?:使用|创建|进入).{0,30}(?:worktree|工作树)/i],F5=[/\b(?:exit|leave)\b.{0,40}\bworktree\b/i,/\bworktree\b.{0,60}\b(?:action\s+)?(?:keep|remove)\b/i,/(?:退出|离开).{0,30}(?:worktree|工作树)/i],L5=[/\b(?:do not|don't|never|must not|should not)\b[^.!?;\n]{0,80}\b(?:git\s+)?worktree\b/gi,/\bwithout\b[^.!?;\n]{0,60}\b(?:git\s+)?worktree\b/gi,/(?:不要|禁止|不得|无需)[^。!?;\n]{0,50}(?:worktree|工作树)/gi];function d6($){return L5.reduce((J,Z)=>J.replace(Z," "),$)}function N1($){if(typeof $!=="string")return!1;let J=d6($);return G5.some((Z)=>Z.test(J))}var O5="The user explicitly required git worktree isolation, but EnterWorktree has not completed successfully. Do not continue in the original workspace. Your next action must be an EnterWorktree tool call. Wait for its result before using file or Bash tools.",f5="The user explicitly required leaving the managed worktree, but ExitWorktree has not completed successfully. Do not finish or explain. Your next action must be an ExitWorktree tool call using the action requested by the user.",A5="Required worktree lifecycle did not complete before the retry limit.",y5=3;function m6($,J,Z){if(!$)return{action:"none"};let W=d6($);if(!N1(W))return{action:"none"};let Y=F5.some((K)=>K.test(W));if(J.has("TaskWorktree"))return{action:"none"};let V=!J.has("EnterWorktree")?"EnterWorktree":Y&&!J.has("ExitWorktree")?"ExitWorktree":void 0;if(!V)return{action:"none"};if(Z>=y5)return{action:"fail",message:A5};return{action:"retry",tool:V,prompt:V==="EnterWorktree"?O5:f5}}var v6=30000;async function L2($){try{let Z=N$.getInstance().executeStopHooks({projectDir:$.workspaceRoot??X0(),sessionId:$.sessionId,permissionMode:$.permissionMode,reason:$.reason,abortSignal:$.abortSignal}),W,Y=new Promise((V)=>{W=setTimeout(()=>V("timeout"),v6)});try{let V=await Promise.race([Z,Y]);if(V==="timeout")return w2.warn(`[Loop] Stop hook 超时 (${v6}ms),按 shouldStop: true 处理`),{action:"stop"};let K=V;if(!K.shouldStop)return{action:"continue",reason:K.continueReason};return{action:"stop"}}finally{clearTimeout(W)}}catch(J){return w2.warn("[Loop] Stop hook execution failed:",J),{action:"stop"}}}async function N5($,J){let Z;while(!(Z=await $.next()).done)if(J)await J(Z.value);return Z.value}var P5=[/<system-reminder>[\s\S]*?<\/system-reminder>/gi,/<file[^>]*>[\s\S]*?<\/file>/gi,/<hooks_context>[\s\S]*?<\/hooks_context>/gi,/<[^>]+>/g];function _5($){if(typeof $==="string")return $;if(Array.isArray($))return $.map((J)=>{if(typeof J==="string")return J;if(J&&typeof J==="object"&&"text"in J){let Z=J.text;return typeof Z==="string"?Z:""}return""}).join(" ");return""}function b5($){let J=$;for(let X of P5)J=J.replace(X," ");J=J.replace(/^\s*\/[a-zA-Z][\w-]*\s+/,"");let Z=J.replace(/\s+/g," ").trim();if(!Z)return"";let W=Z.match(/^(.+?)(?:[.!?]\s|[。!?](?=\S|$)|$)/),Y=W&&W[1].length>=6?W[1]:Z;if(Y=Y.trim().replace(/[\s.。!!??,,;;::-]+$/,""),Y.length<=60)return Y;let V=Y.slice(0,60),K=V.lastIndexOf(" ");return`${(K>36?V.slice(0,K):V).trimEnd()}…`}function c6($){return b5(_5($))}import{EventEmitter as E5}from"events";import l6 from"node:path";function O2($){if(r6($.sessionId),!l6.isAbsolute($.projectPath))throw Error("projectPath must be absolute");return{sessionId:$.sessionId,projectPath:l6.resolve($.projectPath)}}function i6($){let J=O2($);return JSON.stringify([J.projectPath,J.sessionId])}function Z3($,J){return i6($)===i6(J)}class P$ extends E5{static instance;constructor(){super();this.setMaxListeners(100)}static getInstance(){if(!P$.instance)P$.instance=new P$;return P$.instance}publish($,J,Z,W){let Y=O2($);this.emit("event",{sessionId:Y.sessionId,projectPath:Y.projectPath,type:J,...W!==void 0?{seq:W}:{},properties:Z})}subscribe($){return this.on("event",$),()=>this.off("event",$)}}var n$=P$.getInstance();var t0=k0("Agent"),P1=new Set;async function S5($,J){let Z=$.sessionId;if(!Z||$.subagentInfo)return;if(P1.has(Z))return;if(P1.size>=5000)P1.clear();P1.add(Z);try{let W=$.workspaceRoot,Y=await o$.findSessionMetadata(Z,W);if(!Y)return;if(Y.title&&Y.title.trim())return;let V=c6(J);if(!V)return;await o$.updateSessionMetadata(Z,Y.projectPath,{title:V}),n$.publish({sessionId:Z,projectPath:Y.projectPath},"session.updated",{title:V})}catch(W){t0.debug?.("[Loop] 自动生成会话标题失败:",W)}}var f2=`<turn_aborted>
|
|
1
|
+
import{$b as M4}from"./chunk-8hprmrd5.js";import{Fd as u0,Hd as K6,Id as h1,Jd as Q6,Qd as o$,Tc as vJ,Vc as IJ,Wc as uJ,Xc as m2,Yc as c2,bc as X$,cd as gJ,dd as T4,ed as R4,fd as I2,gd as k1,hd as h4,id as x4,jd as S1,nd as DJ,vd as K1}from"./chunk-wzmqkam9.js";import{Vd as S4}from"./chunk-s0tq8gyx.js";import{$d as v0,Xd as H0,_d as bJ}from"./chunk-x3cxmwnz.js";import{af as eJ}from"./chunk-dg0d3303.js";import{bf as b4,cf as i0,df as f4,ef as zJ,hf as E1,if as V6,jf as BJ,kf as jJ,mf as UJ}from"./chunk-rchz6j90.js";import{$f as E4,Xf as J$,Yf as r0,dg as H4}from"./chunk-kf7whgr7.js";import{qg as N$}from"./chunk-aa5zmwd9.js";import{Ah as nJ}from"./chunk-sdbbyagy.js";import{Ph as X0}from"./chunk-0hr050ck.js";import{pi as k0}from"./chunk-n7mzxa8h.js";import{Di as CJ}from"./chunk-14bs89sm.js";import{Oi as b$,Qi as r6,Ri as P0,Si as R1,Ui as hJ,Vi as xJ,Wi as kJ}from"./chunk-tgdhsm5t.js";import{Xi as L8}from"./chunk-fhfzdyba.js";function A$($){return $.role==="system"&&Array.isArray($.content)}function f$($){if($.role!=="system"||!$.metadata||Array.isArray($.metadata))return!1;return typeof $.metadata==="object"&&$.metadata.contextualProjectRules===!0}class A1{systemMessages;_contextualSystemMessages;_history;_pending=[];_contextRevision=0;context;constructor($,J){this.context=$;let Z=$.messages.find(A$);if(this._contextualSystemMessages=$.messages.filter(f$),Z)this.systemMessages=[Z,...this._contextualSystemMessages];else if(J)this.systemMessages=[{role:"system",content:[{type:"text",text:J,providerOptions:{anthropic:{cacheControl:{type:"ephemeral"}}}}]},...this._contextualSystemMessages];else this.systemMessages=[...this._contextualSystemMessages];this._history=$.messages.filter((W)=>!A$(W)&&!f$(W))}get historyLength(){return this._history.length}get history(){return this._history}get pending(){return this._pending}get contextRevision(){return this._contextRevision}toLLMMessages(){return[...this.systemMessages,...this._history,...this._pending]}getMessagesForLLM(){return this.toLLMMessages()}getHistory(){return this._history}appendPending($){this._pending.push($)}appendUser($){this._pending.push($)}appendAssistant($){this._pending.push($)}appendToolResult($){this._pending.push($)}appendContextualProjectInstructions($){if(!f$($))throw Error("Contextual project instructions require safe metadata");this._contextualSystemMessages.push($),this.systemMessages.push($)}syncContextualSystemMessages(){let $=this.systemMessages.filter(A$);this.systemMessages.splice(0,this.systemMessages.length,...$,...this._contextualSystemMessages)}appendControl($,J){if($==="system")throw Error("Cannot append system control message via appendControl. Use constructor for root system prompt.");this._pending.push(J)}appendDurableControl($){if(!$.id||$.role!=="user")throw Error("Durable control messages require a user role and identity");if(this._history.some((J)=>J.id===$.id))return;this._history.push($)}appendToHistory($){this._history.push($)}commitPending(){if(this._pending.length>0)this._history.push(...this._pending),this._pending=[]}replaceHistory($){this._history=$.filter((J)=>!A$(J)&&!f$(J)),this._contextRevision++}restoreDurableHistory($){this._contextualSystemMessages=$.filter(f$),this._history=$.filter((J)=>!A$(J)&&!f$(J)),this._pending=[],this.syncContextualSystemMessages(),this._contextRevision++}removeMessages($){let J=[this._history.length,this._pending.length,this._contextualSystemMessages.length];if(this._history=this._history.filter((Z)=>!$(Z)),this._pending=this._pending.filter((Z)=>!$(Z)),this._contextualSystemMessages=this._contextualSystemMessages.filter((Z)=>!$(Z)),this.syncContextualSystemMessages(),this._history.length!==J[0]||this._pending.length!==J[1]||this._contextualSystemMessages.length!==J[2])this._contextRevision++}writeback(){this.commitPending(),this.context.messages=[...this._contextualSystemMessages,...this._history]}get hasSystemPrompt(){return this.systemMessages.length>0}}function b6($){if($.isSubagent)return"continue";if(!$.budget||$.budget<=0)return"continue";if($.consecutiveContinuations>=3&&$.lastOutputDelta<500)return"stop";if($.usage/$.budget>=0.9)return"stop";return"continue"}function E6($){return{budget:$.budget,usage:0,consecutiveContinuations:0,lastOutputDelta:0,isSubagent:$.isSubagent??!1}}function S6($,J,Z){return{...$,usage:$.usage+J,lastOutputDelta:J,consecutiveContinuations:Z?$.consecutiveContinuations+1:0}}import Q$ from"node:path";var c4=new Set(["GOEXPERIMENT","GOOS","GOARCH","CGO_ENABLED","GO111MODULE","RUST_BACKTRACE","RUST_LOG","NODE_ENV","PYTHONUNBUFFERED","PYTHONDONTWRITEBYTECODE","GIT_TERMINAL_PROMPT","LANG","LANGUAGE","LC_ALL","LC_CTYPE","LC_TIME","CHARSET","TERM","COLORTERM","NO_COLOR","FORCE_COLOR","TZ","LS_COLORS","LSCOLORS","GREP_COLOR","GREP_COLORS"]),l4=/^(LD_.+|DYLD_.+|PATH)$/,M6=/^([A-Za-z_][A-Za-z0-9_]*)=([\w./:@-]*)$/;function l$($){let J=$;while(!0){let Z=J.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!Z)break;let W=Z[1],Y=Z[2],V=W.match(M6);if(!V)break;let K=V[1];if(!c4.has(K))break;J=Y}return J}function uZ($){let J=$;while(!0){let Z=J.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!Z)break;let W=Z[1],Y=Z[2],V=W.match(M6);if(!V)break;let K=V[1];if(l4.test(K))break;J=Y}return J}var i4=[/^timeout[ \t]+(?:--foreground[ \t]+|--preserve-status[ \t]+|-v[ \t]+|--verbose[ \t]+|-k[ \t]+\S+[ \t]+|--kill-after[= ]\S+[ \t]+|-s[ \t]+\S+[ \t]+|--signal[= ]\S+[ \t]+)*\S+[ \t]+/,/^time[ \t]+/,/^nice[ \t]+(?:-n[ \t]+\d+[ \t]+|-\d+[ \t]+)?/,/^nohup[ \t]+/];function D2($){let J=$,Z=!0;while(Z){Z=!1;for(let W of i4){let Y=J.match(W);if(Y){J=J.slice(Y[0].length),Z=!0;break}}if(J.startsWith("-- "))J=J.slice(3),Z=!0}return J}function i$($){let J=[],Z="",W=!1,Y=!1,V=!1;for(let K=0;K<$.length;K++){let Q=$[K];if(V){Z+=Q,V=!1;continue}if(Q==="\\"&&!W){Z+=Q,V=!0;continue}if(Q==="'"&&!Y){W=!W,Z+=Q;continue}if(Q==='"'&&!W){Y=!Y,Z+=Q;continue}if(W||Y){Z+=Q;continue}if(Q==="|"){if(K+1<$.length&&$[K+1]==="|"){if(Z.trim())J.push(Z.trim());Z="",K++;continue}return null}if(Q===">"||Q==="<")return null;if(Q==="&"&&K+1<$.length&&$[K+1]==="&"){if(Z.trim())J.push(Z.trim());Z="",K++;continue}if(Q==="&")return null;if(Q===";"){if(Z.trim())J.push(Z.trim());Z="";continue}Z+=Q}if(Z.trim())J.push(Z.trim());return J.length>0?J:null}function T6($){let J=!1,Z=!1,W=!1;for(let Y=0;Y<$.length;Y++){let V=$[Y];if(W){W=!1;continue}if(V==="\\"&&!J){W=!0;continue}if(V==="'"&&!Z){J=!J;continue}if(V==='"'&&!J){Z=!Z;continue}if(J)continue;if(V==="$"){let K=$[Y+1];if(K&&/[A-Za-z_@*#?!$0-9({]/.test(K))return!0}if(V==="`")return!0;if(Z)continue;if(V==="|")return!0;if(V===">"||V==="<")return!0;if(V==="{"){let K=$.slice(Y);if(/^\{[^}]*,[^}]*\}/.test(K)||/^\{[^}]*\.\.[^}]*\}/.test(K))return!0}}return!1}function K$($){let J=[],Z="",W=!1,Y=!1,V=!1;for(let K=0;K<$.length;K++){let Q=$[K];if(V){Z+=Q,V=!1;continue}if(Q==="\\"&&!W){if(V=!0,Y){let X=$[K+1];if(X&&'$`"\\'.includes(X))continue;Z+=Q,V=!1}continue}if(Q==="'"&&!Y){W=!W;continue}if(Q==='"'&&!W){Y=!Y;continue}if(!W&&!Y&&/[ \t]/.test(Q)){if(Z)J.push(Z),Z="";continue}Z+=Q}if(Z)J.push(Z);return J}var r4=new Set(["npm","pnpm","yarn","bun"]),R6=new Set(["biome","eslint","jest","mypy","pyright","pytest","ruff","tsc","vitest"]),n4=new Set(["-u","--fix","--update","--update-snapshot","--updateSnapshot","--watch","--watchAll","--write"]),o4=/[ \t]*;[ \t]*echo[ \t]+"[A-Za-z0-9 _:=.-]*(?:\$\{PIPESTATUS\[0\]\}|\$\?)[A-Za-z0-9 _:=.-]*"[ \t]*$/;function a4($){return $!==void 0&&/^(?:test|lint|build|type-?check)(?::[\w.-]+)*$/i.test($)}function h6($){return $.replace(/\s+2>&1\s*$/,"").trim()}function s4($,J,Z){if(!Z||J.length!==2)return;let W=/^(.+?)[ \t]+&&[ \t]+([\s\S]+)$/.exec($);if(!W)return;let Y=K$(W[1]??"");if(Y.length!==2||Y[0]!=="cd")return;let V=Y[1];if(!V||V==="-")return;let K=Q$.isAbsolute(V)?Q$.resolve(V):Q$.resolve(Z,V);if(!X$.isWithinWorkspace(K,Z))return;return W[2]?.trim()||void 0}function t4($){let J=[],Z=!1,W=!1,Y=!1;for(let V=0;V<$.length;V++){let K=$[V];if(Y){Y=!1;continue}if(K==="\\"&&!Z){Y=!0;continue}if(K==="'"&&!W){Z=!Z;continue}if(K==='"'&&!Z){W=!W;continue}if(K!=="|"||Z||W)continue;if($[V+1]==="|")return;J.push(V)}return J}function e4($){let J=K$($),[Z,W,Y]=J;if(Z!=="head"&&Z!=="tail")return!1;if(J.length===1)return!0;let V=(K)=>K!==void 0&&/^[1-9]\d{0,4}$/.test(K);if(J.length===2)return W?.startsWith("--lines=")&&V(W.slice(8))||W?.startsWith("-")&&V(W.slice(1));return J.length===3&&(W==="-n"||W==="--lines")&&V(Y)}function $5($){let J=h6($.replace(o4,"").trim()),Z=t4(J);if(!Z)return;if(Z.length===0)return x6(J);if(Z.length!==1)return;let W=Z[0];if(W===void 0)return;let Y=h6(J.slice(0,W).trim()),V=J.slice(W+1).trim();if(!Y||!e4(V))return;return x6(Y)}function x6($){let Z=i$($)?.at(-1);if(!Z)return $;let W=K$(Z),[Y,V]=W;if(!(Y==="vitest"||(Y==="npx"||Y==="bunx")&&V==="vitest")||W.some((Q)=>Q==="--configLoader"||Q.startsWith("--configLoader=")))return $;return`${$} --configLoader runner`}function y$($,J){let Z=$5($);if(!Z)return!1;let W=l$(Z),Y=i$(W);if(!Y||T6(W)||/[\r\n]/.test(W))return!1;let V=Y.length===1?Y[0]:s4(W,Y,J);if(!V)return!1;let K=K$(V);if(K.length===0||K.some((B)=>[...n4].some((j)=>B===j||B.startsWith(`${j}=`))))return!1;let[Q,X,H]=K;if(r4.has(Q??""))return a4(X==="run"?H:X)||X==="--test";if((Q==="npx"||Q==="bunx")&&R6.has(X??""))return!0;if(R6.has(Q??""))return!0;if(Q==="node"&&X==="--test")return!0;if(Q==="go"&&["build","test","vet"].includes(X??""))return!0;return Q==="cargo"&&["build","check","clippy","test"].includes(X??"")}function cZ($,J){if($===void 0)return!0;if(typeof $!=="string"||$.split(/[\\/]/).includes(".."))return!1;if(!J)return!Q$.isAbsolute($);let Z=Q$.isAbsolute($)?Q$.resolve($):Q$.resolve(J,$);return X$.isWithinWorkspace(Z,J)}var w2=k0("Agent"),J5=3;function q2($,J,Z){if($!=="length")return{action:"none"};if(J>=J5)return{action:"truncated"};if(b6(Z)==="stop")return w2.info("[Loop] Token budget: diminishing returns detected, skipping recovery"),{action:"budget_stop"};return{action:"recover"}}var Z5=[/:\s*$/,/:\s*$/,/\.\.\.\s*$/,/让我(先|来|开始|查看|检查|修复)/,/Let me (first|start|check|look|fix)/i,/I('ll| will) (now |)(create|write|edit|update|modify|fix|add|implement)/i,/我(现在就|来|要)(创建|写入|编辑|修改|修复|添加|实现)/,/\d+\.\s+(First|Next|Then|Finally)/i],W5=/```[\s\S]{50,}```/,k6="请执行你提到的操作,不要只是描述。使用 Edit/Write/ApplyPatch/Bash 工具来实际修改文件。",Y5=2;function G2($,J,Z=!0){if(!$||J>=Y5)return{action:"none"};if(!Z&&W5.test($))return{action:"retry",prompt:k6};let W=$.slice(-200),Y=W.match(/```/g);if(Y&&Y.length%2!==0)return{action:"none"};if(Z5.some((K)=>K.test(W)))return{action:"retry",prompt:k6};return{action:"none"}}var V5=[/\b(?:run|execute|rerun|re-run)\b[\s\S]{0,60}\b(?:tests?|test suite|lint|type-?check|build)\b/i,/\b(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?(?:test|lint|build|type-?check)\b/i,/(?:运行|执行|跑|重新运行).{0,30}(?:测试|单测|集成测试|检查|构建)/],C6={test:/\b(?:tests?|test suite)\b|(?:测试|单测|集成测试)/i,lint:/\blint(?:ing)?\b/i,"type-check":/\btype[\s-]?check(?:ing)?\b|\btsc\b|类型检查/i,build:/\bbuild\b|构建/i},K5={test:/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?test\b|(?:^|\s)(?:node|bun)\s+--test\b|(?:^|\s)(?:vitest|jest|pytest|go\s+test|cargo\s+test)\b/i,lint:/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?lint\b/i,"type-check":/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?type-?check\b|(?:^|\s)tsc\b/i,build:/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?build\b/i},Q5="The user explicitly required verification, but it has not run successfully. Do not finish or explain. Your next action must be a Bash tool call that runs the requested test, lint, type-check, or build command. Inspect the command result and fix any failure before finishing.",X5="Required verification did not run successfully before the retry limit.",H5=3;function I6($,J,Z,W){if(!Z.success)return;if(["Edit","Write","ApplyPatch","NotebookEdit"].includes(J)){$.clear();return}if(J==="Bash"&&typeof Z.metadata?.command==="string"&&Z.metadata.exit_code===0&&y$(Z.metadata.command,W)){$.add(Z.metadata.command);return}if(!["Task","TaskOutput"].includes(J))return;let Y=Z.metadata?.verificationCommands;if(!Array.isArray(Y))return;for(let V of Y)if(typeof V==="string"&&y$(V,W))$.add(V)}function F2($,J,Z){if(!$||!V5.some((X)=>X.test($)))return{action:"none"};let W=Object.keys(C6).filter((X)=>C6[X].test($)),Y=[...J],V=W.filter((X)=>!Y.some((H)=>K5[X].test(H)));if(W.length>0?V.length===0:Y.some((X)=>y$(X)))return{action:"none"};if(Z>=H5)return{action:"fail",message:X5};let Q=W.length>1&&V.length>0?` Missing successful verification categories: ${V.join(", ")}.`:"";return{action:"retry",prompt:`${Q5}${Q}`}}var z5=[/\bdelegate\b[\s\S]{0,120}\b(?:Task tool|subagent|agent)\b/i,/\b(?:call|use|invoke)\b[\s\S]{0,80}\bTask tool\b/i,/(?:委派|交给|调用|使用).{0,60}(?:Task|子代理|子智能体)/],u6=[/\b(?:do not|don't|never)\s+(?:delegate|call|use|invoke)\b/i,/(?:不要|禁止|无需)(?:委派|调用|使用).{0,20}(?:Task|子代理|子智能体)?/];function g6($){return typeof $==="string"&&u6.some((J)=>J.test($))}var B5=[/\b(?:call|use|invoke)\b[\s\S]{0,30}\bTask(?: tool)?\b[\s\S]{0,30}\bexactly once\b/i,/\bexactly once\b[\s\S]{0,30}\b(?:call|use|invoke)\b[\s\S]{0,30}\bTask(?: tool)?\b/i,/\bexactly one\b[\s\S]{0,30}\bTask(?: tool)? calls?\b/i,/(?:Task|子代理).{0,20}(?:恰好|仅|只)(?:调用|使用)?一次/,/(?:恰好|仅|只)(?:调用|使用)?一次.{0,20}(?:Task|子代理)/],j5=[/\b(?:do not|don't|never)\s+(?:call|use|invoke)\s+(?:the\s+)?Task\b[\s\S]{0,30}\bexactly once\b/i,/\bTask\b[\s\S]{0,30}\b(?:does not|doesn't|need not)\b[\s\S]{0,30}\bexactly once\b/i,/\bmultiple\s+Task(?: tool)?\s+calls?\s+(?:are\s+)?allowed\b/i,/(?:不要|禁止).{0,12}(?:Task|子代理).{0,12}(?:恰好|仅|只)(?:调用|使用)?一次/];function U5($){if(typeof $!=="string")return;if(j5.some((J)=>J.test($)))return"multiple-allowed";return B5.some((J)=>J.test($))?"required":void 0}function r$($){for(let J of $){let Z=U5(J);if(Z!==void 0)return Z==="required"}return!1}var D5="The user explicitly required delegation, but no Task tool call completed successfully. Do not solve the task directly or explain. Your next action must be a Task tool call using the requested subagent.",w5="Required delegation did not complete before the retry limit.",q5=3;function p6($,J,Z){let W=(typeof $==="string"?[$]:$??[]).map((K)=>K.trim()).filter(Boolean),Y=r$(W),V=!1;if(!Y)for(let K of W){if(u6.some((Q)=>Q.test(K)))break;if(z5.some((Q)=>Q.test(K))){V=!0;break}}if(W.length===0||!Y&&!V||J.has("Task"))return{action:"none"};if(Z>=q5)return{action:"fail",message:w5};return{action:"retry",prompt:D5}}var G5=[/\b(?:use|create|enter|start|work\s+(?:in|inside))\b.{0,60}\bworktree\b/i,/(?:使用|创建|进入).{0,30}(?:worktree|工作树)/i],F5=[/\b(?:exit|leave)\b.{0,40}\bworktree\b/i,/\bworktree\b.{0,60}\b(?:action\s+)?(?:keep|remove)\b/i,/(?:退出|离开).{0,30}(?:worktree|工作树)/i],L5=[/\b(?:do not|don't|never|must not|should not)\b[^.!?;\n]{0,80}\b(?:git\s+)?worktree\b/gi,/\bwithout\b[^.!?;\n]{0,60}\b(?:git\s+)?worktree\b/gi,/(?:不要|禁止|不得|无需)[^。!?;\n]{0,50}(?:worktree|工作树)/gi];function d6($){return L5.reduce((J,Z)=>J.replace(Z," "),$)}function N1($){if(typeof $!=="string")return!1;let J=d6($);return G5.some((Z)=>Z.test(J))}var O5="The user explicitly required git worktree isolation, but EnterWorktree has not completed successfully. Do not continue in the original workspace. Your next action must be an EnterWorktree tool call. Wait for its result before using file or Bash tools.",f5="The user explicitly required leaving the managed worktree, but ExitWorktree has not completed successfully. Do not finish or explain. Your next action must be an ExitWorktree tool call using the action requested by the user.",A5="Required worktree lifecycle did not complete before the retry limit.",y5=3;function m6($,J,Z){if(!$)return{action:"none"};let W=d6($);if(!N1(W))return{action:"none"};let Y=F5.some((K)=>K.test(W));if(J.has("TaskWorktree"))return{action:"none"};let V=!J.has("EnterWorktree")?"EnterWorktree":Y&&!J.has("ExitWorktree")?"ExitWorktree":void 0;if(!V)return{action:"none"};if(Z>=y5)return{action:"fail",message:A5};return{action:"retry",tool:V,prompt:V==="EnterWorktree"?O5:f5}}var v6=30000;async function L2($){try{let Z=N$.getInstance().executeStopHooks({projectDir:$.workspaceRoot??X0(),sessionId:$.sessionId,permissionMode:$.permissionMode,reason:$.reason,abortSignal:$.abortSignal}),W,Y=new Promise((V)=>{W=setTimeout(()=>V("timeout"),v6)});try{let V=await Promise.race([Z,Y]);if(V==="timeout")return w2.warn(`[Loop] Stop hook 超时 (${v6}ms),按 shouldStop: true 处理`),{action:"stop"};let K=V;if(!K.shouldStop)return{action:"continue",reason:K.continueReason};return{action:"stop"}}finally{clearTimeout(W)}}catch(J){return w2.warn("[Loop] Stop hook execution failed:",J),{action:"stop"}}}async function N5($,J){let Z;while(!(Z=await $.next()).done)if(J)await J(Z.value);return Z.value}var P5=[/<system-reminder>[\s\S]*?<\/system-reminder>/gi,/<file[^>]*>[\s\S]*?<\/file>/gi,/<hooks_context>[\s\S]*?<\/hooks_context>/gi,/<[^>]+>/g];function _5($){if(typeof $==="string")return $;if(Array.isArray($))return $.map((J)=>{if(typeof J==="string")return J;if(J&&typeof J==="object"&&"text"in J){let Z=J.text;return typeof Z==="string"?Z:""}return""}).join(" ");return""}function b5($){let J=$;for(let X of P5)J=J.replace(X," ");J=J.replace(/^\s*\/[a-zA-Z][\w-]*\s+/,"");let Z=J.replace(/\s+/g," ").trim();if(!Z)return"";let W=Z.match(/^(.+?)(?:[.!?]\s|[。!?](?=\S|$)|$)/),Y=W&&W[1].length>=6?W[1]:Z;if(Y=Y.trim().replace(/[\s.。!!??,,;;::-]+$/,""),Y.length<=60)return Y;let V=Y.slice(0,60),K=V.lastIndexOf(" ");return`${(K>36?V.slice(0,K):V).trimEnd()}…`}function c6($){return b5(_5($))}import{EventEmitter as E5}from"events";import l6 from"node:path";function O2($){if(r6($.sessionId),!l6.isAbsolute($.projectPath))throw Error("projectPath must be absolute");return{sessionId:$.sessionId,projectPath:l6.resolve($.projectPath)}}function i6($){let J=O2($);return JSON.stringify([J.projectPath,J.sessionId])}function Z3($,J){return i6($)===i6(J)}class P$ extends E5{static instance;constructor(){super();this.setMaxListeners(100)}static getInstance(){if(!P$.instance)P$.instance=new P$;return P$.instance}publish($,J,Z,W){let Y=O2($);this.emit("event",{sessionId:Y.sessionId,projectPath:Y.projectPath,type:J,...W!==void 0?{seq:W}:{},properties:Z})}subscribe($){return this.on("event",$),()=>this.off("event",$)}}var n$=P$.getInstance();var t0=k0("Agent"),P1=new Set;async function S5($,J){let Z=$.sessionId;if(!Z||$.subagentInfo)return;if(P1.has(Z))return;if(P1.size>=5000)P1.clear();P1.add(Z);try{let W=$.workspaceRoot,Y=await o$.findSessionMetadata(Z,W);if(!Y)return;if(Y.title&&Y.title.trim())return;let V=c6(J);if(!V)return;await o$.updateSessionMetadata(Z,Y.projectPath,{title:V}),n$.publish({sessionId:Z,projectPath:Y.projectPath},"session.updated",{title:V})}catch(W){t0.debug?.("[Loop] 自动生成会话标题失败:",W)}}var f2=`<turn_aborted>
|
|
2
2
|
The previous turn was interrupted. Commands or tool calls may have partially completed; inspect the workspace and running processes before retrying.
|
|
3
3
|
</turn_aborted>`,H$="Tool execution was blocked because its durable call record could not be committed. No tool side effect was started.",n6="Tool execution completed, but its durable result record could not be committed. Further model and tool execution was stopped. The operation may have completed; inspect external state before retrying.";class _$ extends Error{phase;constructor($,J){super($==="user_message"?"Conversation input could not be committed. No further model request was started.":"Model output could not be committed. The run was stopped before any further model request or successful completion.",J);this.phase=$;this.name="DurableConversationPersistenceError"}}function z$($){return $.executionEngine?.getContextManager()}async function l0($,J,Z,W=null,Y,V={}){let K=V.required??$.executionEngine!==void 0;try{let Q=z$($),X=typeof Z==="string"?Z.trim()!=="":Z.some((H)=>H.type==="text"?H.text.trim()!=="":!0);if(Q&&J.sessionId&&X){let H=await Q.saveMessage(J.sessionId,"user",Z,W,Y,J.subagentInfo);if(K&&!H)throw Error("Durable user-message commit returned no identity");if(Y?.clientVisible!==!1)S5(J,Z);return H}if(K&&J.sessionId&&X)throw Error("Durable user-message storage is unavailable")}catch(Q){if(t0.warn("[Loop] 保存用户消息失败:",Q),K)throw new _$("user_message",{cause:Q})}return null}async function C0($,J,Z,W,Y,V,K={}){let Q=K.required??$.executionEngine!==void 0;try{let X=z$($),H=Boolean(Z.trim()||Y?.trim());if(X&&J.sessionId&&H){let B=await X.saveMessage(J.sessionId,"assistant",Z,W,V,J.subagentInfo,Y);if(Q&&!B)throw Error("Durable assistant-message commit returned no identity");return B}if(Q&&J.sessionId&&H)throw Error("Durable assistant-message storage is unavailable")}catch(X){if(t0.warn("[Loop] 保存助手消息失败:",X),Q)throw new _$("assistant_message",{cause:X})}return null}async function o6($,J,Z){try{let W=z$($);if(W&&J.sessionId)return await W.saveMessage(J.sessionId,"system",f2,Z,void 0,J.subagentInfo)}catch(W){t0.warn("[Loop] 保存中断边界失败:",W)}return null}async function a6($,J,Z,W,Y){try{let V=z$($);if(!V||!J.sessionId||Z.length===0)return null;return await V.saveMessage(J.sessionId,"system",`<contextual-project-instructions-ref count="${Z.length}" />`,Y,{contextualProjectRules:!0,ruleReferences:JSON.parse(JSON.stringify(Z.map((K)=>({...K})))),triggerPaths:[...W]},J.subagentInfo)}catch(V){t0.warn("[Loop] 保存 contextual project rules provenance 失败:",V)}return null}async function A2($,J,Z,W,Y,V={}){try{let K=z$($);if(K&&J.sessionId){let Q=await K.saveToolUse(J.sessionId,Z,W,Y,J.subagentInfo,V.providerToolCallId);if(V.required&&!Q)throw Error("Durable tool-use commit returned no identity");return Q}if(V.required&&J.sessionId)throw Error("Durable tool-use storage is unavailable")}catch(K){if(t0.warn("[Loop] 保存工具调用失败:",K),V.required)throw K}return null}async function _1($,J,Z,W,Y,V,K,Q,X,H={}){try{let B=z$($);if(B&&J.sessionId){let j=await B.saveToolResult(J.sessionId,Z,W,Y,V,K,J.subagentInfo,Q,X);if(H.required&&!j)throw Error("Durable tool-result commit returned no identity");return j}if(H.required&&J.sessionId)throw Error("Durable tool-result storage is unavailable")}catch(B){if(t0.warn("[Loop] 保存工具结果失败:",B),H.required)throw B}return null}async function a$($,J,Z,W,Y={}){try{let V=z$($);if(V&&J.sessionId){let K=await V.saveCompaction(J.sessionId,Z,W,null);if(Y.required&&!K)throw Error("Compaction checkpoint commit returned no identity");return K||null}if(Y.required&&J.sessionId)throw Error("Compaction checkpoint storage is unavailable")}catch(V){if(t0.warn("[Loop] 保存压缩数据失败:",V),Y.required)throw V}return null}async function D0($){let{deps:J,context:Z,state:W,assistantContent:Y,assistantReasoningContent:V,lastMessageUuid:K,controlPrompt:Q,controlMetadata:X}=$;W.appendAssistant({role:"assistant",content:Y,reasoningContent:V});let H=K,B=await C0(J,Z,Y,H,V);if(B)H=B;if(Q!==void 0){let j={role:"user",content:Q};if(X)j.metadata=X;W.appendControl("user",j);let z=await l0(J,Z,j.content,H,X);if(z)H=z}return H}import{createHash as X6}from"node:crypto";import{promises as l5}from"node:fs";import i5 from"node:path";import{nanoid as e0}from"nanoid";import*as J0 from"node:fs/promises";import*as B$ from"node:path";var s6={enabled:!0,maxIndexLines:200};var M5="memory",t6="MEMORY.md";class y2{memoryDir;config;initialized=!1;constructor($,J,Z){if(Z)this.memoryDir=Z;else{let W=b$($);this.memoryDir=B$.join(W,M5)}this.config={...s6,...J}}async initialize(){if(this.initialized)return;await J0.mkdir(this.memoryDir,{recursive:!0}),this.initialized=!0}async loadIndex(){if(!this.config.enabled)return null;await this.initialize();let $=B$.join(this.memoryDir,t6);try{let J=await J0.readFile($,"utf-8");if(!J.trim())return null;let Z=J.split(`
|
|
4
4
|
`),Y=Z.slice(0,this.config.maxIndexLines).join(`
|
|
@@ -83,7 +83,7 @@ Full output saved to: ${Q}`}catch{return`${J}
|
|
|
83
83
|
|
|
84
84
|
${Y}`}}import M8 from"node:path";import{nanoid as T8}from"nanoid";import*as h0 from"node:fs/promises";import*as EJ from"node:path";import{Mutex as D8}from"async-mutex";import w8 from"write-file-atomic";var PJ=120,C2=128;function J1($){if(!Array.isArray($)||$.length>120||!$.every((J)=>typeof J==="string"&&J.length>0&&J.length<=128))return;return[...new Set($)]}function U8($){if(!$||typeof $!=="object"||Array.isArray($))return[];if(!("recovery"in $)||!$.recovery)return[];let J=$.recovery;if(typeof J!=="object"||Array.isArray(J))return[];if(!("version"in J)||J.version!==1&&J.version!==2||!("inputMessageIds"in J)||!("hadSuccessfulToolResult"in J)||typeof J.hadSuccessfulToolResult!=="boolean"||!("emptyFinalCorrectionSpent"in J)||typeof J.emptyFinalCorrectionSpent!=="boolean"||!("acknowledgedInputMessageIds"in $))return[];if(J.version===2&&(!("interruptedToolCallCount"in J)||!Number.isSafeInteger(J.interruptedToolCallCount)||J.interruptedToolCallCount<0))return[];let Z=J1(J.inputMessageIds),W=J1($.acknowledgedInputMessageIds);if(!Z||!W)return[];let Y=new Set(Z);return W.filter((V)=>Y.has(V))}function M1($,J){let Z=$[J];if(Z?.type!=="turn_aborted")return[];let W=U8(Z.data);if(W.length===0)return[];let Y=-1;for(let K=J-1;K>=0;K--){let Q=$[K];if(Q.type==="turn_started"){if(Q.data.turnId!==Z.data.turnId)return[];Y=K;break}if(Q.type==="turn_completed"||Q.type==="turn_aborted")return[]}if(Y<0)return[];let V=new Set;for(let K=Y+1;K<J;K++){let Q=$[K];if(Q.type!=="message_created"||Q.data.role!=="user")continue;let X=Q.data.metadata,H=Q.data.inboxMessageId!==void 0?Q.data.inboxMessageId:X!==null&&typeof X==="object"&&!Array.isArray(X)?X.inboxMessageId:void 0;if(typeof H==="string"&&H.length>0&&H.length<=128)V.add(H)}return W.filter((K)=>V.has(K))}var T1=1,Z1=8388608;function _J($,J){let Z={version:T1,sessionId:$,messages:J.map(({recovered:W,...Y})=>Y)};return`${JSON.stringify(Z)}
|
|
85
85
|
`}function v2($,J){return $ instanceof Error&&"code"in $&&$.code===J}function q8($){if(typeof $==="string")return!0;if(!Array.isArray($))return!1;return $.every((J)=>{if(!J||typeof J!=="object"||!("type"in J))return!1;if(J.type==="text")return"text"in J&&typeof J.text==="string";return J.type==="image_url"&&"image_url"in J&&typeof J.image_url==="object"&&J.image_url!==null&&"url"in J.image_url&&typeof J.image_url.url==="string"})}function G8($,J,Z){let W;try{W=JSON.parse($)}catch(V){throw Error(`Invalid steering inbox JSON: ${J}`,{cause:V})}if(!W||typeof W!=="object"||!("version"in W)||W.version!==T1||!("sessionId"in W)||W.sessionId!==Z||!("messages"in W)||!Array.isArray(W.messages))throw Error(`Invalid steering inbox record: ${J}`);let Y=W.messages.map((V)=>{if(!V||typeof V!=="object"||!("id"in V)||typeof V.id!=="string"||!("content"in V)||!q8(V.content)||!("queuedAt"in V)||typeof V.queuedAt!=="number"||"persisted"in V&&typeof V.persisted!=="boolean"||"origin"in V&&V.origin!=="user"&&V.origin!=="background_subagent"&&V.origin!=="team_message"||"metadata"in V&&(V.metadata===null||typeof V.metadata!=="object"||Array.isArray(V.metadata))||"outputSchema"in V&&V.outputSchema!==void 0&&(!V.outputSchema||typeof V.outputSchema!=="object"||Array.isArray(V.outputSchema)))throw Error(`Invalid steering inbox message: ${J}`);let K="outputSchema"in V&&V.outputSchema!==void 0?h1(V.outputSchema).schema:void 0;return{id:V.id,content:V.content,queuedAt:V.queuedAt,..."persisted"in V&&V.persisted===!0?{persisted:!0}:{},..."origin"in V&&V.origin?{origin:V.origin}:{},..."metadata"in V&&V.metadata?{metadata:JSON.parse(JSON.stringify(V.metadata))}:{},...K?{outputSchema:K}:{}}});return{version:T1,sessionId:Z,messages:Y}}function F8($){return new Set($.flatMap((J,Z)=>{if(J.type==="inbox_acknowledged")return J.data.messageIds;if(J.type==="turn_aborted")return M1($,Z);return[]}))}class x1{workspaceRoot;sessionId;filePath;mutex=new D8;messages=[];constructor($,J,Z){this.workspaceRoot=$;this.sessionId=J;this.filePath=Z}static async open($,J){let Z=new x1($,J,R1($,J));return await Z.loadAndReconcile(),Z}async enqueue($,J){return this.mutex.runExclusive(async()=>{if(J&&!J(this.messages))return!1;let Z=[...this.messages,{...$,recovered:!1}],W=_J(this.sessionId,Z);if(Buffer.byteLength(W)>Z1)return!1;return await this.persist(Z,W),this.messages=Z,!0})}async acknowledge($){if($.length===0)return;let J=new Set($);await this.mutex.runExclusive(async()=>{let Z=this.messages.filter((W)=>!J.has(W.id));this.messages=Z,await this.persist(Z)})}list(){return this.messages.map(($)=>({...$,content:typeof $.content==="string"?$.content:$.content.map((J)=>J.type==="text"?{...J}:{...J,image_url:{...J.image_url}}),...$.outputSchema?{outputSchema:JSON.parse(JSON.stringify($.outputSchema))}:{},...$.metadata?{metadata:JSON.parse(JSON.stringify($.metadata))}:{}}))}count(){return this.messages.length}recoveredCount(){return this.messages.filter(($)=>$.recovered).length}async loadAndReconcile(){await this.mutex.runExclusive(async()=>{let $={version:T1,sessionId:this.sessionId,messages:[]};try{if((await h0.stat(this.filePath)).size>Z1)throw Error(`Steering inbox exceeds ${Z1} bytes: ${this.filePath}`);await h0.chmod(this.filePath,384),$=G8(await h0.readFile(this.filePath,"utf8"),this.filePath,this.sessionId)}catch(Y){if(!v2(Y,"ENOENT"))throw Y}let J=P0(this.workspaceRoot,this.sessionId),Z=new Set;try{Z=F8(bJ(await h0.readFile(J,"utf8"),J))}catch(Y){if(!v2(Y,"ENOENT"))throw Y}let W=$.messages.filter((Y)=>!Z.has(Y.id)).map((Y)=>({...Y,recovered:!0}));if(this.messages=W,W.length!==$.messages.length)await this.persist(W)})}async persist($,J){if(await h0.mkdir(EJ.dirname(this.filePath),{recursive:!0,mode:448}),$.length===0){await h0.unlink(this.filePath).catch((W)=>{if(!v2(W,"ENOENT"))throw W});return}let Z=J??_J(this.sessionId,$);if(Buffer.byteLength(Z)>Z1)throw Error(`Steering inbox exceeds ${Z1} bytes: ${this.filePath}`);await w8(this.filePath,Z,{encoding:"utf8",mode:384,fsync:!0})}}import*as I0 from"node:fs/promises";import*as pJ from"node:path";import{nanoid as V0}from"nanoid";var SJ=256;class w0{sessionId;projectPath;static instances=new Map;store;subscribers=new Set;highestSeq=0;constructor($,J){this.sessionId=$;this.projectPath=J;this.store=new v0(P0(J,$))}static for($,J){let Z=`${J}\x00${$}`,W=w0.instances.get(Z);if(!W)W=new w0($,J),w0.instances.set(Z,W),w0.pruneIdleInstances(Z);else w0.instances.delete(Z),w0.instances.set(Z,W);return W}static release($,J){w0.instances.delete(`${J}\x00${$}`)}static pruneIdleInstances($){if(w0.instances.size<=SJ)return;for(let[J,Z]of w0.instances){if(J===$||Z.subscribers.size>0)continue;if(w0.instances.delete(J),w0.instances.size<=SJ)return}}get lastSeq(){return this.highestSeq}async commit($){let J=await this.store.append($);return this.record(J),J}async commitBatch($){if($.length===0)return[];let J=await this.store.appendBatch($);for(let Z of J)this.record(Z);return J}async commitValidated($){let J=await this.store.appendValidated($);return this.record(J),J}async commitValidatedBatch($){let J=await this.store.appendValidatedBatch($);for(let Z of J)this.record(Z);return J}emitDelta($){for(let J of this.subscribers)J.onDelta?.($);n$.publish({sessionId:this.sessionId,projectPath:this.projectPath},"delta",{delta:$})}subscribe($,J){if(this.subscribers.add($),J?.fromSeq!==void 0)this.replay($,J.fromSeq);return()=>{this.subscribers.delete($),w0.pruneIdleInstances()}}async replay($,J){let Z=await this.store.readFromSeq(J);for(let W of Z){if(I2(W))continue;await $.onCommitted(W)}}record($){if(typeof $.seq==="number"&&$.seq>this.highestSeq)this.highestSeq=$.seq;if(I2($))return;for(let J of this.subscribers){let Z=J.onCommitted($);if(Z)Promise.resolve(Z).catch(()=>{return})}n$.publish({sessionId:this.sessionId,projectPath:this.projectPath},`committed.${$.type}`,{event:$},$.seq)}}function U$($){let J=null,Z=null;for(let W of $){if(W.type==="turn_started"){J=W.data;continue}if(W.type==="turn_completed")Z={type:"turn_completed",data:W.data};else if(W.type==="turn_aborted")Z={type:"turn_aborted",data:W.data};else continue;if(J?.turnId===Z.data.turnId)J=null}return{active:J,lastTerminal:Z}}class A0 extends Error{}var O8="Tool execution was interrupted by a process restart. The operation may have partially completed. Inspect the workspace, running processes, and external state before deciding whether to retry it.";function u2($,J){let Z=$.findLastIndex((W)=>W.type==="turn_started"&&W.data.turnId===J);if(Z<0)return!1;return $.slice(Z+1).some((W)=>{if(W.type!=="message_created"||W.data.role!=="user")return!1;let Y=W.data.metadata;return Y!==null&&typeof Y==="object"&&!Array.isArray(Y)&&Y.clientVisible===!1&&Y.emptyFinalCorrection===!0})}function MJ($,J){let Z=$.findLastIndex((Y)=>Y.type==="turn_started"&&Y.data.turnId===J);if(Z<0)return[];let W=[];for(let Y of $.slice(Z+1)){if(Y.type==="turn_started"&&Y.data.turnId!==J||(Y.type==="turn_completed"||Y.type==="turn_aborted")&&Y.data.turnId===J)break;if(Y.type!=="message_created"||Y.data.role!=="user")continue;let V=Y.data.metadata,K=Y.data.inboxMessageId!==void 0?Y.data.inboxMessageId:V!==null&&typeof V==="object"&&!Array.isArray(V)?V.inboxMessageId:void 0;if(typeof K==="string"&&K.length>0&&K.length<=C2)W.push(K)}return[...new Set(W)]}function dJ($){if(!$||typeof $!=="object"||Array.isArray($))return;if(!("version"in $)||$.version!==1&&$.version!==2)return;let J="inputMessageIds"in $?J1($.inputMessageIds):void 0;if(!J||!("hadSuccessfulToolResult"in $)||typeof $.hadSuccessfulToolResult!=="boolean"||!("emptyFinalCorrectionSpent"in $)||typeof $.emptyFinalCorrectionSpent!=="boolean")return;let Z=$.version===1?0:("interruptedToolCallCount"in $)&&Number.isSafeInteger($.interruptedToolCallCount)&&$.interruptedToolCallCount>=0?$.interruptedToolCallCount:void 0;if(Z===void 0)return;return{version:$.version,inputMessageIds:J,hadSuccessfulToolResult:$.hadSuccessfulToolResult,interruptedToolCallCount:Z,emptyFinalCorrectionSpent:$.emptyFinalCorrectionSpent}}function f8($,J){let Z=$.findLastIndex((Q)=>Q.type==="turn_started"&&Q.data.turnId===J);if(Z<0)return 0;let W=$.findIndex((Q,X)=>X>Z&&Q.type==="turn_started"&&Q.data.turnId!==J),Y=$.slice(Z+1,W<0?void 0:W),V=new Set(Y.flatMap((Q)=>{if(Q.type!=="part_created"||Q.data.partType!=="tool_call")return[];let X=Q.data.payload;return X&&typeof X==="object"&&!Array.isArray(X)?[typeof X.toolCallId==="string"?X.toolCallId:Q.data.partId]:[Q.data.partId]})),K=new Set;for(let Q of Y){if(Q.type!=="part_created"||Q.data.partType!=="tool_result")continue;let X=Q.data.payload;if(!X||typeof X!=="object"||Array.isArray(X))continue;let H=typeof X.toolCallId==="string"?X.toolCallId:Q.data.partId,B=X.metadata;if(V.has(H)&&B&&typeof B==="object"&&!Array.isArray(B)&&B.processRestartRecovery===!0&&B.sideEffectsUncertain===!0)K.add(H)}return K.size}function mJ($){return new Set($.flatMap((J,Z)=>{if(J.type==="inbox_acknowledged")return J.data.messageIds;if(J.type==="turn_aborted")return M1($,Z);return[]}))}function g2($,J,Z=[]){let W=dJ(J.data.recovery);if(!W)return;if($.some((Q)=>Q.type==="turn_recovery_acknowledged"&&Q.data.turnId===J.data.turnId))return;let Y=mJ($);for(let Q of Z)Y.add(Q);let V=W.inputMessageIds.filter((Q)=>!Y.has(Q)),K=W.version===1?f8($,J.data.turnId):W.interruptedToolCallCount;if(V.length===0&&!W.hadSuccessfulToolResult&&K===0)return;return{turnId:J.data.turnId,outcome:"aborted",inputMessageIds:V,hadSuccessfulToolResult:W.hadSuccessfulToolResult,...K>0?{interruptedToolCallCount:K}:{},emptyFinalCorrectionSpent:W.emptyFinalCorrectionSpent}}function W1($){for(let J=$.length-1;J>=0;J--){let Z=$[J];if(Z.type!=="turn_aborted")continue;let W=g2($,Z);if(W)return W}return}var A8=1e4,y8=1e5,N8=2592000000,TJ=128,P8=1e6,_8=256;function b8($){if(!$||typeof $!=="object"||Array.isArray($))return;let J=$;if(typeof J.goalId!=="string"||J.goalId.length===0||J.goalId.length>TJ||typeof J.verificationAttempt!=="number"||!Number.isSafeInteger(J.verificationAttempt)||J.verificationAttempt<1||J.verificationAttempt>P8||typeof J.verifierSessionId!=="string"||J.verifierSessionId.length===0||J.verifierSessionId.length>TJ||typeof J.evidenceSha256!=="string"||!/^[a-f0-9]{64}$/.test(J.evidenceSha256)||typeof J.goalUpdatedAt!=="string"||!Number.isFinite(Date.parse(J.goalUpdatedAt)))return;return{goalId:J.goalId,verificationAttempt:J.verificationAttempt,verifierSessionId:J.verifierSessionId,evidenceSha256:J.evidenceSha256,goalUpdatedAt:J.goalUpdatedAt}}function cJ($,J){let Z=$.data.metadata;if(!Z||typeof Z!=="object"||Array.isArray(Z))return;let W=Z.turnFinalization;if(!W||typeof W!=="object"||Array.isArray(W))return;let Y=W,V=Y.turnId,K=Y.inputMessageIds,Q=Y.turnsCount,X=Y.toolCallsCount,H=Y.durationMs,B=Array.isArray(K)?K.filter((z)=>typeof z==="string"&&z.length>0&&z.length<=C2):[];if(typeof V!=="string"||V.length===0||V.length>128||J!==void 0&&V!==J||!Array.isArray(K)||K.length>PJ||B.length!==K.length||typeof Q!=="number"||!Number.isSafeInteger(Q)||Q<0||Q>A8||typeof X!=="number"||!Number.isSafeInteger(X)||X<0||X>y8||typeof H!=="number"||!Number.isSafeInteger(H)||H<0||H>N8)return;let j;if("goalFinalization"in Y){if(j=b8(Y.goalFinalization),!j)return}return{turnId:V,inputMessageIds:[...new Set(B)],turnsCount:Q,toolCallsCount:X,durationMs:H,...j?{goalFinalization:j}:{}}}function RJ($,J){let Z=$.findLastIndex((W)=>W.type==="turn_started"&&W.data.turnId===J);if(Z<0)return;for(let W=$.length-1;W>Z;W--){let Y=$[W];if(Y?.type!=="message_created")continue;let V=cJ(Y,J);if(V)return V}return}function E8($){for(let J=$.length-1;J>=0;J--){let Z=$[J];if(Z?.type!=="message_created")continue;let W=cJ(Z);if(!W?.goalFinalization)continue;if(!$.slice(0,J).some((V)=>V.type==="turn_started"&&V.data.turnId===W.turnId))continue;return{turnId:W.turnId,finalization:W}}return}function R$($,J){let Z=J?$.findLastIndex((X)=>X.type==="turn_started"&&X.data.turnId===J):-1;if(J&&Z<0)return{all:[],orphaned:[],hadSuccessfulResult:!1};let W=new Map,Y=new Set,V=new Set,K=new Set;for(let X of $.slice(Z+1)){if(X.type==="interaction_requested"){K.add(X.data.toolCallId);continue}if(X.type!=="part_created")continue;let H=X.data.payload&&typeof X.data.payload==="object"&&!Array.isArray(X.data.payload)?X.data.payload:{},B=typeof H.toolCallId==="string"?H.toolCallId:X.data.partId;if(X.data.partType==="tool_call")W.set(B,{toolCallId:B,messageId:X.data.messageId,toolName:typeof H.toolName==="string"?H.toolName:"unknown",input:H.input??null});else if(X.data.partType==="tool_result"){if(Y.add(B),Y.add(X.data.partId),Y.add(X.data.messageId),W.has(B)&&H.error===null)V.add(B)}}let Q=[...W.values()];return{all:Q,orphaned:Q.filter((X)=>!Y.has(X.toolCallId)&&!K.has(X.toolCallId)),hadSuccessfulResult:Q.some((X)=>V.has(X.toolCallId))}}class _0{static sessionInitializationRuns=new Map;projectPath;maxSessions;version;initializedSessions=new Set;constructor($=X0(),J=100,Z=CJ()){this.projectPath=$,this.maxSessions=J,this.version=Z}createEvent($,J,Z){return{id:V0(),sessionId:J,projectPath:this.projectPath,timestamp:new Date().toISOString(),type:$,cwd:this.projectPath,gitBranch:hJ(this.projectPath),version:this.version,data:Z}}log($){return w0.for($,this.projectPath)}async ensureSessionCreated($,J){let Z=P0(this.projectPath,$);if(this.initializedSessions.delete($)){this.initializedSessions.add($);return}let W=_0.sessionInitializationRuns.get(Z);if(!W)W=this.initializeSessionFile($,Z,J),_0.sessionInitializationRuns.set(Z,W);try{await W,this.rememberInitializedSession($)}finally{if(_0.sessionInitializationRuns.get(Z)===W)_0.sessionInitializationRuns.delete(Z)}}rememberInitializedSession($){this.initializedSessions.delete($),this.initializedSessions.add($);while(this.initializedSessions.size>_8){let J=this.initializedSessions.values().next().value;if(J===void 0)return;this.initializedSessions.delete(J)}}async initializeSessionFile($,J,Z){if((await new v0(J).readAll()).length>0)return;let V=new Date().toISOString(),K={sessionId:$,rootId:Z?.parentSessionId??$,parentId:Z?.parentSessionId,relationType:Z?"subagent":void 0,resumedFrom:Z?.resumedFrom,rootAgentId:Z?.rootAgentId,resumeDepth:Z?.resumeDepth,title:void 0,status:"running",taskStatus:Z?"running":"queued",taskFailure:null,agentType:Z?.subagentType,model:void 0,permission:void 0,createdAt:V,updatedAt:V},Q=this.createEvent("session_created",$,K);await this.log($).commit(Q)}buildCompactionMetadata($){let J={trigger:$.trigger,preTokens:$.preTokens};if($.reason)J.reason=$.reason;if($.strategy)J.strategy=$.strategy;if($.preTokenSource)J.preTokenSource=$.preTokenSource;if($.estimatedPendingTokens!==void 0)J.estimatedPendingTokens=$.estimatedPendingTokens;if($.postTokens!==void 0)J.postTokens=$.postTokens;if($.sampleAttempts!==void 0)J.sampleAttempts=$.sampleAttempts;if($.inputReductions!==void 0)J.inputReductions=$.inputReductions;if($.messagesOmitted!==void 0)J.messagesOmitted=$.messagesOmitted;if($.filesOmitted!==void 0)J.filesOmitted=$.filesOmitted;if($.imagesOmitted!==void 0)J.imagesOmitted=$.imagesOmitted;if($.fallbackTargetTokens!==void 0)J.fallbackTargetTokens=$.fallbackTargetTokens;if($.fallbackMessagesOmitted!==void 0)J.fallbackMessagesOmitted=$.fallbackMessagesOmitted;if($.fallbackMessagesTruncated!==void 0)J.fallbackMessagesTruncated=$.fallbackMessagesTruncated;if($.failureReason)J.failureReason=$.failureReason;if($.filesIncluded)J.filesIncluded=$.filesIncluded;if($.replacementMessages)J.checkpointVersion=IJ;return J}async initialize(){try{let $=b$(this.projectPath);await I0.mkdir($,{recursive:!0,mode:493}),console.log(`[PersistentStore] 初始化存储目录: ${$}`)}catch($){console.warn("[PersistentStore] 无法创建持久化存储目录:",$)}}async saveMessage($,J,Z,W=null,Y,V,K){try{await this.ensureSessionCreated($,V);let Q=new Date().toISOString(),X=V0(),H={messageId:X,role:J,parentMessageId:W??void 0,inboxMessageId:Y?.inboxMessageId,createdAt:Q,model:Y?.model,usage:Y?.usage,metadata:Y?JSON.parse(JSON.stringify(Y)):void 0},B=this.createEvent("message_created",$,H),j=J==="assistant"&&K?.trim()?[this.createEvent("part_created",$,{partId:V0(),messageId:X,partType:"reasoning",payload:{text:K},createdAt:Q})]:[],z=typeof Z==="string"?[this.createEvent("part_created",$,{partId:V0(),messageId:X,partType:"text",payload:{text:Z},createdAt:Q})]:Z.map((U)=>this.createEvent("part_created",$,{partId:V0(),messageId:X,partType:U.type==="text"?"text":"image",payload:U.type==="text"?{text:U.text}:{mimeType:S8(U.image_url.url)??"image/png",dataUrl:U.image_url.url},createdAt:Q}));return await this.log($).commitBatch([B,...j,...z]),X}catch(Q){throw console.error(`[PersistentStore] 保存消息失败 (session: ${$}):`,Q),Q}}async acknowledgeInboxMessages($,J){if(J.length===0)return;await this.ensureSessionCreated($);let Z=new Date().toISOString();await this.log($).commit(this.createEvent("inbox_acknowledged",$,{messageIds:[...J],acknowledgedAt:Z}))}async acknowledgeTurnRecovery($,J){await this.ensureSessionCreated($);try{await this.log($).commitValidated((Z)=>{let W=H0(Z);if(W.some((V)=>V.type==="turn_recovery_acknowledged"&&V.data.turnId===J))throw new A0;let Y=W.findLast((V)=>V.type==="turn_aborted"&&V.data.turnId===J);if(!Y||!g2(W,Y))throw new A0;return this.createEvent("turn_recovery_acknowledged",$,{turnId:J,acknowledgedAt:new Date().toISOString()})})}catch(Z){if(!(Z instanceof A0))throw Z}}async persistBackgroundSubagentCompletion($,J){if(J.inboxMessageId!==`background-subagent-completion:${J.childSessionId}`)return{eligible:!1,acknowledged:!1,persisted:!1};await this.ensureSessionCreated($);let Z={eligible:!1,acknowledged:!1,persisted:!1};return await this.log($).commitValidatedBatch((W)=>{let Y=H0(W),V=Y.some((z)=>z.type==="inbox_acknowledged"&&z.data.messageIds.includes(J.inboxMessageId)),K=Y.find((z)=>z.type==="message_created"&&z.data.inboxMessageId===J.inboxMessageId),Q=Y.findLast((z)=>{if(z.type!=="part_created"||z.data.partType!=="tool_call"||!z.data.payload||typeof z.data.payload!=="object"||Array.isArray(z.data.payload))return!1;let U=z.data.payload;if(U.toolName!=="Task"||!U.input||typeof U.input!=="object"||Array.isArray(U.input))return!1;let N=U.input,b=N.resume_from??N.resume;return N.run_in_background===!0&&N.subagent_session_id===J.childSessionId&&N.description===J.subagentRef.subagentDescription&&(N.subagent_type===void 0||N.subagent_type===J.subagentRef.subagentType)&&(N.resume_from===void 0||N.resume===void 0||N.resume_from===N.resume)&&(b===void 0?J.subagentRef.subagentResumedFrom===void 0:b===J.subagentRef.subagentResumedFrom)});if(!Q)return Z={eligible:!1,acknowledged:V,persisted:!1,...K?{messageId:K.data.messageId}:{}},[];if(V)return Z={eligible:!0,acknowledged:!0,persisted:!1,...K?{messageId:K.data.messageId}:{}},[];let X=Y.find((z)=>z.type==="part_created"&&z.data.partType==="subtask_ref"&&z.data.payload!==null&&typeof z.data.payload==="object"&&!Array.isArray(z.data.payload)&&z.data.payload.childSessionId===J.childSessionId&&z.data.payload.status===J.subagentRef.subagentStatus);if(K&&X)return Z={eligible:!0,acknowledged:!1,persisted:!1,messageId:K.data.messageId},[];let H=new Date().toISOString(),B=K?.data.messageId??V0(),j=[];if(!K){let z={messageId:B,role:"user",inboxMessageId:J.inboxMessageId,createdAt:H,metadata:JSON.parse(JSON.stringify(J.metadata))};j.push(this.createEvent("message_created",$,z)),j.push(this.createEvent("part_created",$,{partId:V0(),messageId:B,partType:"text",payload:{text:J.content},createdAt:H}))}if(!X){let z=Y.findLast((N)=>N.type==="part_created"&&N.data.partType==="subtask_ref"&&N.data.messageId===Q.data.messageId&&N.data.payload!==null&&typeof N.data.payload==="object"&&!Array.isArray(N.data.payload)&&N.data.payload.childSessionId===J.childSessionId),U=z?.data.payload&&typeof z.data.payload==="object"&&!Array.isArray(z.data.payload)?z.data.payload:void 0;j.push(this.createEvent("part_created",$,{partId:V0(),messageId:Q.data.messageId,partType:"subtask_ref",payload:{childSessionId:J.subagentRef.subagentSessionId,agentType:J.subagentRef.subagentType,description:J.subagentRef.subagentDescription??"",status:J.subagentRef.subagentStatus,summary:J.subagentRef.subagentSummary??"",resumedFrom:J.subagentRef.subagentResumedFrom??null,rootAgentId:J.subagentRef.subagentRootId??J.subagentRef.subagentSessionId,resumeDepth:J.subagentRef.subagentResumeDepth??0,verificationVerdict:J.subagentRef.verificationVerdict??null,startedAt:typeof U?.startedAt==="string"?U.startedAt:H,finishedAt:H},createdAt:H}))}return Z={eligible:!0,acknowledged:!1,persisted:j.length>0,messageId:B},j}),Z}async saveTurnStart($,J){await this.ensureSessionCreated($);try{await this.log($).commitValidated((Z)=>{let W=H0(Z);if(W.some((V)=>V.type==="turn_started"&&V.data.turnId===J.turnId))throw new A0;let Y=U$(W).active;if(Y)throw Error(`Session already has an active turn: ${Y.turnId}`);return this.createEvent("turn_started",$,J)})}catch(Z){if(!(Z instanceof A0))throw Z}}async saveTurnCompletion($,J,Z=[]){await this.ensureSessionCreated($);try{await this.log($).commitValidatedBatch((W)=>{let Y=H0(W),V=new Set(Y.flatMap((H)=>H.type==="inbox_acknowledged"?H.data.messageIds:[])),K=[...new Set(Z)].filter((H)=>!V.has(H)),Q=Y.findLast((H)=>(H.type==="turn_completed"||H.type==="turn_aborted")&&H.data.turnId===J.turnId);if(Q){if(Q.type==="turn_aborted"||K.length===0)throw new A0;return[this.createEvent("inbox_acknowledged",$,{messageIds:K,acknowledgedAt:J.completedAt})]}let X=U$(Y).active;if(!X||X.turnId!==J.turnId)throw Error(`Turn is not active: ${J.turnId}`);return[...K.length>0?[this.createEvent("inbox_acknowledged",$,{messageIds:K,acknowledgedAt:J.completedAt})]:[],this.createEvent("turn_completed",$,J)]})}catch(W){if(!(W instanceof A0))throw W}}async saveTurnAbort($,J,Z={}){let W=Z.acknowledgeInputMessageIds??[],Y=J1(W);if(!Y)throw Error("Invalid turn abort acknowledgement input message IDs");let V=Y;await this.ensureSessionCreated($);let K,Q=[];try{await this.log($).commitValidatedBatch((X)=>{let H=H0(X),B=mJ(H),j=H.findLast((v)=>(v.type==="turn_completed"||v.type==="turn_aborted")&&v.data.turnId===J.turnId);if(j){if(j.type==="turn_completed")throw K=void 0,Q=[],new A0;let v=dJ(j.data.recovery),N0=v?V.filter((S)=>v.inputMessageIds.includes(S)):[],L0=N0.filter((S)=>!B.has(S));if(Q=N0,K=g2(H,j,N0),L0.length===0)throw new A0;return[this.createEvent("inbox_acknowledged",$,{messageIds:L0,acknowledgedAt:J.abortedAt})]}let z=U$(H).active;if(!z||z.turnId!==J.turnId)throw Error(`Turn is not active: ${J.turnId}`);let U=R$(H,z.turnId),N=MJ(H,z.turnId),b=W1(H),x=new Set(J.recovery?.inputMessageIds??[]),M=b?b.inputMessageIds.filter((v)=>x.has(v)):[],k=[...new Set([...N,...M])],h={version:2,inputMessageIds:k,hadSuccessfulToolResult:U.hadSuccessfulResult||J.recovery?.hadSuccessfulToolResult===!0,interruptedToolCallCount:U.orphaned.length+(J.recovery?.version===2?J.recovery.interruptedToolCallCount:0),emptyFinalCorrectionSpent:u2(H,z.turnId)||J.recovery?.emptyFinalCorrectionSpent===!0};K={turnId:J.turnId,outcome:"aborted",inputMessageIds:h.inputMessageIds,hadSuccessfulToolResult:h.hadSuccessfulToolResult,...h.interruptedToolCallCount>0?{interruptedToolCallCount:h.interruptedToolCallCount}:{},emptyFinalCorrectionSpent:h.emptyFinalCorrectionSpent};let _=V.filter((v)=>k.includes(v)),u=_.filter((v)=>!B.has(v));Q=_;let q=new Set(B);for(let v of _)q.add(v);let K0=h.inputMessageIds.filter((v)=>!q.has(v)),d=h.hadSuccessfulToolResult||h.interruptedToolCallCount>0;K=K0.length>0||d?{turnId:J.turnId,outcome:"aborted",inputMessageIds:K0,hadSuccessfulToolResult:h.hadSuccessfulToolResult,...h.interruptedToolCallCount>0?{interruptedToolCallCount:h.interruptedToolCallCount}:{},emptyFinalCorrectionSpent:h.emptyFinalCorrectionSpent}:void 0;let{acknowledgedInputMessageIds:B0,...F0}=J;return[this.createEvent("turn_aborted",$,{...F0,..._.length>0?{acknowledgedInputMessageIds:_}:{},recovery:h}),...u.length>0?[this.createEvent("inbox_acknowledged",$,{messageIds:u,acknowledgedAt:J.abortedAt})]:[]]})}catch(X){if(!(X instanceof A0))throw X}return{...K?{recovery:K}:{},acknowledgedInputMessageIds:Q}}async loadInterruptedToolCalls($){let J=await this.loadEvents($);if(!J)return[];let Z=H0(J),W=U$(Z).active;return W?R$(Z,W.turnId).orphaned.map((Y)=>({...Y,input:structuredClone(Y.input)})):[]}async hasRecoverableTurn($){let J=await this.loadEvents($);if(!J)return!1;let Z=H0(J),W=U$(Z).active;if(W){let Y=R$(Z,W.turnId);if(Y.orphaned.length>0||Y.hadSuccessfulResult)return!0;if(RJ(Z,W.turnId))return!0}return W1(Z)!==void 0}async loadBackgroundTaskChildIds($){let J=await this.loadEvents($);if(!J)return new Set;let Z=H0(J).flatMap((W)=>{if(W.type!=="part_created"||W.data.partType!=="tool_call"||!W.data.payload||typeof W.data.payload!=="object"||Array.isArray(W.data.payload))return[];let Y=W.data.payload;if(Y.toolName!=="Task"||!Y.input||typeof Y.input!=="object"||Array.isArray(Y.input))return[];let V=Y.input;return V.run_in_background===!0&&typeof V.subagent_session_id==="string"?[V.subagent_session_id]:[]});return new Set(Z)}async recoverInterruptedTurn($,J={}){await this.ensureSessionCreated($);let Z;try{await this.log($).commitValidatedBatch((W)=>{let Y=H0(W),V=U$(Y).active,K=R$(Y);if(!V&&K.orphaned.length===0){if(Z=W1(Y),Z)return[];throw new A0}let Q=V?RJ(Y,V.turnId):void 0;if(V&&Q&&K.orphaned.length===0){let _=R$(Y,V.turnId);Z={turnId:V.turnId,outcome:"completed",inputMessageIds:Q.inputMessageIds,hadSuccessfulToolResult:_.hadSuccessfulResult,emptyFinalCorrectionSpent:u2(Y,V.turnId),finalization:Q};let u=new Set(Y.flatMap((d)=>d.type==="inbox_acknowledged"?d.data.messageIds:[])),q=Q.inputMessageIds.filter((d)=>!u.has(d)),K0=new Date().toISOString();return[...q.length>0?[this.createEvent("inbox_acknowledged",$,{messageIds:q,acknowledgedAt:K0})]:[],this.createEvent("turn_completed",$,{turnId:V.turnId,completedAt:K0,turnsCount:Q.turnsCount,toolCallsCount:Q.toolCallsCount,durationMs:Q.durationMs})]}let X=V?R$(Y,V.turnId):void 0,H=X?.orphaned.some((_)=>{let u=J.adoptedToolResults?.get(_.toolCallId);return u?.toolCallId===_.toolCallId&&u.toolName===_.toolName&&u.error===void 0})??!1,B=new Set(V?.inputMessageIds??[]),j=V?W1(Y):void 0,z=j?j.inputMessageIds.filter((_)=>B.has(_)):[],U=z.length>0,N=V?MJ(Y,V.turnId):[],b=X?X.orphaned.filter((_)=>{let u=J.adoptedToolResults?.get(_.toolCallId);return!(u?.toolCallId===_.toolCallId&&u.toolName===_.toolName)}).length:0;Z=V?{turnId:V.turnId,outcome:"aborted",inputMessageIds:[...new Set([...N,...z])],hadSuccessfulToolResult:(X?.hadSuccessfulResult??!1)||H||U&&j?.hadSuccessfulToolResult===!0,...(()=>{let _=b+(U?j?.interruptedToolCallCount??0:0);return _>0?{interruptedToolCallCount:_}:{}})(),emptyFinalCorrectionSpent:u2(Y,V.turnId)||U&&j?.emptyFinalCorrectionSpent===!0}:W1(Y);let x=V?X?.all.length??0:0,M=new Date().toISOString(),k=V?Date.parse(V.startedAt):Number.NaN,h=K.orphaned.flatMap((_)=>{let u=J.adoptedToolResults?.get(_.toolCallId),q=u?.toolCallId===_.toolCallId&&u.toolName===_.toolName?u:void 0,K0=this.createEvent("part_created",$,{partId:_.toolCallId,messageId:q?_.messageId:_.toolCallId,partType:"tool_result",payload:q?{toolCallId:_.toolCallId,toolName:_.toolName,output:q.output,error:q.error??null,...q.metadata===void 0?{}:{metadata:q.metadata}}:{toolCallId:_.toolCallId,toolName:_.toolName,output:null,error:O8,metadata:{processRestartRecovery:!0,sideEffectsUncertain:!0}},createdAt:M});if(!q?.subagentRef)return[K0];let d=q.subagentRef;return[K0,this.createEvent("part_created",$,{partId:V0(),messageId:_.messageId,partType:"subtask_ref",payload:{childSessionId:d.subagentSessionId,agentType:d.subagentType,description:d.subagentDescription??"",status:d.subagentStatus,summary:d.subagentSummary??"",resumedFrom:d.subagentResumedFrom??null,rootAgentId:d.subagentRootId??d.subagentSessionId,resumeDepth:d.subagentResumeDepth??0,verificationVerdict:d.verificationVerdict??null,startedAt:M,finishedAt:M},createdAt:M})]});return V?[...h,this.createEvent("turn_aborted",$,{turnId:V.turnId,cause:"process_restart",abortedAt:M,turnsCount:0,toolCallsCount:x,durationMs:Number.isFinite(k)?Math.max(0,Date.now()-k):0,recovery:Z?{version:2,inputMessageIds:Z.inputMessageIds,hadSuccessfulToolResult:Z.hadSuccessfulToolResult,interruptedToolCallCount:Z.interruptedToolCallCount??0,emptyFinalCorrectionSpent:Z.emptyFinalCorrectionSpent}:void 0})]:h})}catch(W){if(!(W instanceof A0))throw W}return Z}async loadLatestGoalFinalization($){let J=await this.loadEvents($);return J?E8(J):void 0}async saveInteractionRequest($,J){await this.ensureSessionCreated($),await this.log($).commitValidated((Z)=>{if(Z.some((Y)=>Y.type==="interaction_requested"&&Y.data.requestId===J.requestId))throw Error(`Interaction request already exists: ${J.requestId}`);return this.createEvent("interaction_requested",$,J)})}async saveInteractionResponse($,J){await this.ensureSessionCreated($),await this.log($).commitValidated((Z)=>{if(!Z.some((V)=>V.type==="interaction_requested"&&V.data.requestId===J.requestId))throw Error(`Interaction request not found: ${J.requestId}`);if(Z.some((V)=>V.type==="interaction_responded"&&V.data.requestId===J.requestId))throw Error(`Interaction already responded: ${J.requestId}`);return this.createEvent("interaction_responded",$,J)})}async saveInteractionRecovery($,J){await this.ensureSessionCreated($),await this.log($).commitValidated((Z)=>{if(!Z.some((V)=>V.type==="interaction_responded"&&V.data.requestId===J.requestId))throw Error(`Interaction response not found: ${J.requestId}`);if(Z.some((V)=>V.type==="interaction_recovered"&&V.data.requestId===J.requestId))throw Error(`Interaction already recovered: ${J.requestId}`);return this.createEvent("interaction_recovered",$,J)})}async saveReviewStart($,J){await this.ensureSessionCreated($),await this.log($).commitValidated((Z)=>{if(Z.some((V)=>V.type==="review_started"&&V.data.reviewId===J.reviewId))throw Error(`Review already exists: ${J.reviewId}`);if(Z.some((V)=>V.type==="review_started"&&!Z.some((K)=>K.type==="review_completed"&&K.data.reviewId===V.data.reviewId)))throw Error("Session already has an active review");return this.createEvent("review_started",$,J)})}async saveReviewCompletion($,J){await this.ensureSessionCreated($),await this.log($).commitValidated((Z)=>{if(!Z.some((V)=>V.type==="review_started"&&V.data.reviewId===J.reviewId))throw Error(`Review not found: ${J.reviewId}`);if(Z.some((V)=>V.type==="review_completed"&&V.data.reviewId===J.reviewId))throw Error(`Review already completed: ${J.reviewId}`);return this.createEvent("review_completed",$,J)})}async saveToolUse($,J,Z,W=null,Y,V){try{if(V!==void 0&&(V.length===0||V.length>512))throw Error("Provider tool call identity must contain 1-512 characters");await this.ensureSessionCreated($,Y);let K=new Date().toISOString(),Q=W??V0(),X=[];if(!W){let j={messageId:Q,role:"assistant",parentMessageId:void 0,createdAt:K};X.push(this.createEvent("message_created",$,j))}let H=V??V0(),B={partId:H,messageId:Q,partType:"tool_call",payload:{toolCallId:H,toolName:J,input:Z},createdAt:K};if(X.push(this.createEvent("part_created",$,B)),J==="Task"&&Z&&typeof Z==="object"){let j=Z,z=typeof j.subagent_session_id==="string"?j.subagent_session_id:void 0,U=typeof j.subagent_type==="string"?j.subagent_type:void 0;if(z&&U){let N={partId:V0(),messageId:Q,partType:"subtask_ref",payload:{childSessionId:z,agentType:U,status:"running",summary:typeof j.description==="string"?j.description:"",startedAt:K},createdAt:K};X.push(this.createEvent("part_created",$,N))}}return await this.log($).commitBatch(X),H}catch(K){throw console.error(`[PersistentStore] 保存工具调用失败 (session: ${$}):`,K),K}}async saveToolResult($,J,Z,W,Y=null,V,K,Q,X){try{await this.ensureSessionCreated($,K);let H=new Date().toISOString(),B=Y??V0();return await this.log($).commitValidatedBatch((j)=>{let z=Q?.subagentStatus==="running"?H0(j).findLast((k)=>k.type==="part_created"&&k.data.partType==="subtask_ref"&&k.data.payload!==null&&typeof k.data.payload==="object"&&!Array.isArray(k.data.payload)&&k.data.payload.childSessionId===Q.subagentSessionId&&(k.data.payload.status==="completed"||k.data.payload.status==="failed"||k.data.payload.status==="cancelled")):void 0,U=z?.data.payload,N=X&&typeof X==="object"&&!Array.isArray(X)?X:{},b=U?{...N,subagentSessionId:U.childSessionId,subagentType:U.agentType,description:U.description,subagentStatus:U.status,subagentSummary:U.summary,subagentResumedFrom:U.resumedFrom,subagentRootId:U.rootAgentId,subagentResumeDepth:U.resumeDepth,verificationVerdict:U.verificationVerdict}:X,x=[];if(!Y){let k={messageId:B,role:"assistant",parentMessageId:void 0,createdAt:H};x.push(this.createEvent("message_created",$,k))}let M={partId:J,messageId:B,partType:"tool_result",payload:{toolCallId:J,toolName:Z,output:W,error:V??null,...b===void 0?{}:{metadata:b}},createdAt:H};if(x.push(this.createEvent("part_created",$,M)),Q&&!z){let k=Q.subagentStatus==="running"?null:H,h={partId:V0(),messageId:B,partType:"subtask_ref",payload:{childSessionId:Q.subagentSessionId,agentType:Q.subagentType,description:Q.subagentDescription??"",status:Q.subagentStatus,summary:Q.subagentSummary??"",resumedFrom:Q.subagentResumedFrom??null,rootAgentId:Q.subagentRootId??Q.subagentSessionId,resumeDepth:Q.subagentResumeDepth??0,verificationVerdict:Q.verificationVerdict??null,startedAt:H,finishedAt:k},createdAt:H};x.push(this.createEvent("part_created",$,h))}return x}),J}catch(H){throw console.error(`[PersistentStore] 保存工具结果失败 (session: ${$}):`,H),H}}async saveCompaction($,J,Z,W=null){try{await this.ensureSessionCreated($);let Y=new Date().toISOString(),V=V0(),K={messageId:V,role:"system",parentMessageId:W??void 0,createdAt:Y},Q=this.buildCompactionMetadata(Z),X={partId:V0(),messageId:V,partType:"summary",payload:{text:J,metadata:Q,...Z.replacementMessages?{replacementMessages:uJ(Z.replacementMessages)}:{}},createdAt:Y},H=[this.createEvent("message_created",$,K),this.createEvent("part_created",$,X)];return await this.log($).commitBatch(H),V}catch(Y){throw console.error(`[PersistentStore] 保存压缩失败 (session: ${$}):`,Y),Y}}async recordTokenBudgetHandoff($,J){await this.ensureSessionCreated($);let Z=k1([]),W=await this.log($).commitValidatedBatch((V)=>{if(Z=k1(H0(V)),Z.kind!=="none")return[];let K=new Date().toISOString();return[this.createEvent("token_budget_handoff_recorded",$,{...J,messageId:`${gJ}${V0()}`,createdAt:K})]});if(Z.kind==="valid")return{outcome:"existing",event:Z.event};if(Z.kind==="suppressed")return{outcome:"suppressed",recordId:Z.recordId};if(W.length!==1)throw Error("Token budget handoff commit produced an impossible result");let Y=k1(W);if(Y.kind!=="valid")throw Error("Token budget handoff commit produced an invalid event");return{outcome:"created",event:Y.event}}async initSession($,J){await this.ensureSessionCreated($,J)}async loadEvents($){try{let J=P0(this.projectPath,$),W=await new v0(J).readAll();return W.length>0?H0(W):null}catch{return null}}async loadSession($){try{let J=P0(this.projectPath,$),Z=new v0(J),W=H0(await Z.readAll());if(W.length===0)return null;let Y=W.find((V)=>V.type==="session_created");return{sessionId:$,userId:void 0,preferences:{},configuration:{},startTime:new Date(Y?.timestamp??W[0].timestamp).getTime()}}catch{return null}}async loadConversation($){try{let J=P0(this.projectPath,$),Z=new v0(J),W=H0(await Z.readAll());if(W.length===0)return null;let Y=new Map;for(let X of W){if(X.type==="message_created")Y.set(X.data.messageId,{id:X.data.messageId,role:X.data.role,content:"",timestamp:new Date(X.timestamp).getTime()});if(X.type==="part_created"&&X.data.partType==="text"){let H=Y.get(X.data.messageId);if(H){let B=X.data.payload;H.content=B.text??""}}if(X.type==="part_created"&&X.data.partType==="image"){let H=Y.get(X.data.messageId);if(H)H.content=H.content?`${H.content}
|
|
86
|
-
[Image]`:"[Image]"}}let V=Array.from(Y.values()),K=W[W.length-1],Q=new Date(K.timestamp).getTime();return{messages:V,topics:[],lastActivity:Q}}catch{return null}}async listSessions(){try{let $=b$(this.projectPath);return(await I0.readdir($)).filter((Z)=>Z.endsWith(".jsonl")).map((Z)=>Z.replace(".jsonl","")).sort()}catch{return[]}}async getSessionSummary($){try{let J=P0(this.projectPath,$),Z=new v0(J);if(!(await Z.getStats()).exists)return null;let Y=await Z.readAll();if(Y.length===0)return null;let V=H0(Y),K=Y[Y.length-1],Q=V.filter((X)=>X.type==="message_created"&&["user","assistant"].includes(X.data.role)).length;return{sessionId:$,lastActivity:new Date(K.timestamp).getTime(),messageCount:Q,topics:[]}}catch{return null}}async deleteSession($){this.initializedSessions.delete($);try{let J=P0(this.projectPath,$);await new v0(J).delete(),await I0.unlink(R1(this.projectPath,$)).catch((W)=>{if(W.code!=="ENOENT")throw W}),await vJ(this.projectPath,$,xJ());try{let{getProjectionDb:W,removeSessionFromProjection:Y}=await import("./chunk-
|
|
86
|
+
[Image]`:"[Image]"}}let V=Array.from(Y.values()),K=W[W.length-1],Q=new Date(K.timestamp).getTime();return{messages:V,topics:[],lastActivity:Q}}catch{return null}}async listSessions(){try{let $=b$(this.projectPath);return(await I0.readdir($)).filter((Z)=>Z.endsWith(".jsonl")).map((Z)=>Z.replace(".jsonl","")).sort()}catch{return[]}}async getSessionSummary($){try{let J=P0(this.projectPath,$),Z=new v0(J);if(!(await Z.getStats()).exists)return null;let Y=await Z.readAll();if(Y.length===0)return null;let V=H0(Y),K=Y[Y.length-1],Q=V.filter((X)=>X.type==="message_created"&&["user","assistant"].includes(X.data.role)).length;return{sessionId:$,lastActivity:new Date(K.timestamp).getTime(),messageCount:Q,topics:[]}}catch{return null}}async deleteSession($){this.initializedSessions.delete($);try{let J=P0(this.projectPath,$);await new v0(J).delete(),await I0.unlink(R1(this.projectPath,$)).catch((W)=>{if(W.code!=="ENOENT")throw W}),await vJ(this.projectPath,$,xJ());try{let{getProjectionDb:W,removeSessionFromProjection:Y}=await import("./chunk-bt18xsc6.js"),V=await W();if(V)Y(V,$,this.projectPath)}catch{}}catch(J){console.warn(`[PersistentStore] 删除会话失败 (session: ${$}):`,J)}finally{this.initializedSessions.delete($)}}async cleanupOldSessions(){try{let $=await this.listSessions();if($.length<=this.maxSessions)return;let W=(await Promise.all($.map((Y)=>this.getSessionSummary(Y)))).filter((Y)=>Y!==null).sort((Y,V)=>V.lastActivity-Y.lastActivity).slice(this.maxSessions).map((Y)=>Y.sessionId);await Promise.all(W.map((Y)=>this.deleteSession(Y))),console.log(`[PersistentStore] 已清理 ${W.length} 个旧会话`)}catch($){console.error("[PersistentStore] 清理旧会话失败:",$)}}async getStorageStats(){try{let $=await this.listSessions(),J=0;for(let Z of $){let W=P0(this.projectPath,Z),V=await new v0(W).getStats();J+=V.size}return{totalSessions:$.length,totalSize:J,projectPath:this.projectPath}}catch{return{totalSessions:0,totalSize:0,projectPath:this.projectPath}}}async checkStorageHealth(){try{let $=b$(this.projectPath);await I0.mkdir($,{recursive:!0,mode:493});let J=pJ.join($,".health-check");return await I0.writeFile(J,"test","utf-8"),await I0.unlink(J),{isAvailable:!0,canWrite:!0}}catch($){return{isAvailable:!1,canWrite:!1,error:$ instanceof Error?$.message:String($)}}}static async listAllProjects(){return kJ()}}function S8($){return/^data:([^;,]+)[;,]/.exec($)?.[1]??null}var lJ=131072,p2=new nJ;function d2($,J){return`${M8.resolve($)}\x00${J}`}function l2($,J){let Z=JSON.stringify($);if(Z===void 0)throw Error(`${J} is not JSON serializable`);if(Buffer.byteLength(Z,"utf8")>lJ)throw Error(`${J} exceeds ${lJ} bytes`);return JSON.parse(Z)}function iJ($){if($.type==="askUserQuestion")return"question";if($.type==="mcpElicitation")return"elicitation";if($.type==="permission"||$.type==="mcpSampling")return"permission";return}function R8($,J){return JSON.stringify($)===JSON.stringify(J)}function h8($,J){if($.request.interactionType!=="elicitation")return l2(J,"Interaction response");return l2({approved:J.approved,...J.reason?{reason:J.reason}:{},...J.elicitation?{elicitation:{action:J.elicitation.action}}:{},...J.openExternalUrl?{openExternalUrl:!0}:{}},"Interaction response")}function rJ($){let J=$.request.details;if(!J||typeof J!=="object"||Array.isArray(J))throw Error(`Invalid durable interaction details: ${$.request.requestId}`);return J}function x8($){let J=$.response?.response;if(!J||typeof J!=="object"||Array.isArray(J))throw Error(`Invalid durable interaction response: ${$.request.requestId}`);return J}function k8($){if(!$.answers||Object.keys($.answers).length===0)return"No structured answers were provided.";return Object.entries($.answers).map(([J,Z])=>{let W=Array.isArray(Z)?Z.join(", "):Z;return`${J}: ${W}`}).join(`
|
|
87
87
|
`)}function C8($,J){let{request:Z}=$;if(Z.interactionType==="question"){let K=k8(J);return{toolOutput:`User answers:
|
|
88
88
|
${K}`,inbox:`The process restarted while waiting for a structured answer. The recovered user response is:
|
|
89
89
|
${K}
|
|
@@ -160,7 +160,7 @@ ${C.reason}
|
|
|
160
160
|
|
|
161
161
|
<system-reminder>
|
|
162
162
|
Please continue the conversation from where we left it off without asking the user any further questions. Continue with the last task that you were asked to work on.
|
|
163
|
-
</system-reminder>`;X=await D0({deps:$,context:Z,state:q,assistantContent:G.content||"",assistantReasoningContent:G.reasoningContent,lastMessageUuid:X,controlPrompt:R});continue}let O0=await W?.turnSteering?.drainOrSeal();if(O0&&O0.messages.length>0){await m$("Goal completion evidence invalidated by new user steering"),Z0=void 0,o0=!1,c0=0,q.appendAssistant({role:"assistant",content:G.content||"",reasoningContent:G.reasoningContent});let R=await C0($,Z,G.content||"",X,G.reasoningContent);if(R)X=R;yield{kind:"steering_applied",...await q1(O0.messages),delivery:"current_turn"};continue}let Y0=B4({requested:b0,taskAvailable:N().some((R)=>R.name==="Task"),mutationRevision:q$,verificationRevision:v$,verificationVerdict:q0,verificationFeedback:w$,verificationStallCount:u$,retryCount:H1});if(Y0.action==="retry"){if(H1++,d0=Y0.requireVerificationTask,d0)p0="Task";X=await D0({deps:$,context:Z,state:q,assistantContent:G.content||"",assistantReasoningContent:G.reasoningContent,lastMessageUuid:X,controlPrompt:Y0.prompt});continue}if(Y0.action==="fail")return X=await D0({deps:$,context:Z,state:q,assistantContent:G.content||"",assistantReasoningContent:G.reasoningContent,lastMessageUuid:X}),{success:!1,error:{type:"goal_verification_failed",message:Y0.message},metadata:{turnsCount:K,toolCallsCount:Q.length,duration:Date.now()-V,tokensUsed:S,goalVerificationVerdict:q0,goalVerifierSessionId:E0,goalVerificationEvidenceSha256:x0}};let I=!1,y=!1;if(b0){if(!W?.goalLifecycle||q0!=="pass")return{success:!1,error:{type:"goal_verification_failed",message:"Goal completion reached the final boundary without host-owned verification authority and a fresh PASS."},metadata:{turnsCount:K,toolCallsCount:Q.length,duration:Date.now()-V,tokensUsed:S,goalVerificationVerdict:q0,goalVerifierSessionId:E0,goalVerificationEvidenceSha256:x0}};y=!0}let a=j6(),n=a?.finalMessage??G.content??"",U0=a?.persistenceMetadata,O;if(y){let R=m0?.completionVerification;if(m0?.status!=="verifying"||m0.goalId!==I$||R?.status!=="pass"||R.attempt!==B1||typeof R.verifierSessionId!=="string"||R.verifierSessionId!==E0||typeof R.evidenceSha256!=="string"||R.evidenceSha256!==x0)throw Error("Goal completion lost its persisted verification receipt before finalization");O={goalId:m0.goalId,verificationAttempt:R.attempt,verifierSessionId:R.verifierSessionId,evidenceSha256:R.evidenceSha256,goalUpdatedAt:m0.updatedAt}}let f0=await K0(O),G0=U0||f0?{...U0,...f0?{turnFinalization:f0}:{}}:void 0;q.appendAssistant({role:"assistant",content:n,...G0?{metadata:x$(G0)}:{}});let Q0=await C0($,Z,n,X,U0?void 0:G.reasoningContent,G0);if(Q0)X=Q0;if(y&&W?.goalLifecycle){let R=await W.goalLifecycle.finalizeCompletion();b0=!1,I=!0,yield{kind:"goal_updated",goal:R}}if(a)yield a.event;return{success:!0,finalMessage:n,metadata:{turnsCount:K,toolCallsCount:Q.length,duration:Date.now()-V,tokensUsed:S,toolSuccessRate:Q.length>0?Q.filter((R)=>R.success).length/Q.length:void 0,totalToolFailures:b.totalFailures||void 0,...I?{goalCompletionVerified:!0,goalVerificationVerdict:"pass",...E0?{goalVerifierSessionId:E0}:{},...x0?{goalVerificationEvidenceSha256:x0}:{}}:{},...B6?{outputTruncated:!0}:{},...a?.resultMetadata}}}if(G.finishReason!=="length")n0=0;q.appendAssistant({role:"assistant",content:G.content||"",reasoningContent:G.reasoningContent,tool_calls:G.toolCalls});{let w=await C0($,Z,G.content||"",X,G.reasoningContent);if(w)X=w}if(W?.signal?.aborted)return B(K,Q.length,W.signal);let O1=G.toolCalls.filter((w)=>w.type==="function"),B2;if(s0?.hasTools()){l.debug(`[Loop] 使用 StreamingToolExecutor 收集 ${O1.length} 个工具结果`);let w=s0;for(let D of w.getQueuedToolCalls()){let A=j.get(D.function.name)?.kind;yield{kind:"tool_start",toolCall:D,toolKind:A}}B2=(async()=>{let D=[];for await(let P of w.getRemainingResults())D.push(P);return D})()}else{let w=new Map,D=new Y1;for(let E of O1){let f=D.admit();if(f){w.set(E.id,f);continue}let p=Q1(E.function.arguments),C=p===null?void 0:w6(E.function.name,p);if(C){w.set(E.id,C);continue}let Y0=j.get(E.function.name)?.kind;yield{kind:"tool_start",toolCall:E,toolKind:Y0}}let P=Promise.resolve(),A=(E,f,p)=>{let C=P.then(()=>A2($,Z,E,f,X,{required:$.executionEngine!==void 0,providerToolCallId:p}));return P=C.then(()=>{return},()=>{return}),C},c=async(E)=>{let f=null;try{let p=w.get(E.id);if(p)return{toolCall:E,result:p,toolUseUuid:null};let C=Q1(E.function.arguments);if(C===null)return{toolCall:E,result:{success:!1,llmContent:"",error:{type:"validation_error",message:`Invalid JSON object in tool arguments. Raw: ${E.function.arguments.slice(0,200)}`},metadata:void 0},toolUseUuid:null};V1(E.function.name,C);try{f=await A(E.function.name,C,E.id)}catch(I){return{toolCall:E,result:{success:!1,llmContent:H$,error:{type:"execution_error",message:H$},metadata:{durableToolUseFailed:!0,summary:"Blocked tool before execution"}},toolUseUuid:null,error:I instanceof Error?I:Error(String(I))}}if(E.function.name==="ExitWorktree"&&j0.has("EnterWorktree")&&!j0.has("ExitWorktree")&&F2($2,t1,0).action!=="none"){let I="Run the requested verification before ExitWorktree. The worktree remains active so Bash can run in isolation.";return{toolCall:E,result:{success:!1,llmContent:I,error:{type:"validation_error",message:I},metadata:{summary:"Blocked ExitWorktree until verification succeeds"}},toolUseUuid:f}}let Y0=await G6(E.function.name,C,{sessionId:Z.sessionId,taskListId:Z.taskListId,goalTaskListId:Z.goalTaskListId,userId:Z.userId||"default",modelId:$.config.currentModelId,providerAdmissionOwnerId:H2,workspaceRoot:Z.workspaceRoot||X0(),environment:$.config.env,worktreeIsolationRequired:w1,worktreeActive:j0.has("EnterWorktree")&&!j0.has("ExitWorktree"),subagentType:Z.subagentInfo?.subagentType,signal:W?.signal,confirmationHandler:Z.sessionId?z0.createConfirmationHandler(Z.confirmationHandler,{sessionId:Z.sessionId,projectPath:Z.workspaceRoot||X0(),toolCallId:f??E.id,toolName:E.function.name}):Z.confirmationHandler,permissionMode:Z.permissionMode,toolRegistry:j,deferredToolManager:j.deferredToolManager,onProgress:(I)=>{Y$.push({toolCall:E,update:{message:I.slice(0,1000)}})},onProgressUpdate:(I)=>{Y$.push({toolCall:E,update:I})}});return{toolCall:E,result:Y0,toolUseUuid:f}}catch(p){return l.error(`Tool execution failed for ${E.function.name}:`,p),{toolCall:E,result:{success:!1,llmContent:"",error:{type:"execution_error",message:p instanceof Error?p.message:"Unknown error"},metadata:void 0},toolUseUuid:f,error:p instanceof Error?p:Error("Unknown error")}}};B2=Promise.all(O1.map(c))}let f1,N6,P6=!1,j2=!1,p4=B2.then((w)=>{f1=w},(w)=>{P6=!0,N6=w}).finally(()=>{j2=!0,Y$.close()});while(!j2||Y$.hasPending){let w=Y$.shift()??(j2?void 0:await Y$.next());if(w)yield{kind:"tool_progress",toolCall:w.toolCall,update:w.update}}if(await p4,P6)throw N6;if(!f1)throw Error("Tool execution completed without results");let d4=new k2;for(let{toolCall:w,result:D,toolUseUuid:P}of f1){let A=w;if(Q.push(D),D.metadata?.abortedBeforeLaunch){let y=D.error?.message??"任务已被用户中止";if(P)try{let a=await _1($,Z,P,A.function.name,null,P,y,void 0,void 0,{required:$.executionEngine!==void 0});if(a)X=a}catch{return _4(K,Q.length,V)}return q.appendToolResult({role:"tool",tool_call_id:A.id,name:A.function.name,content:`Error: ${y}`}),B(K,Q.length,W?.signal)}{let y=D.metadata&&typeof D.metadata==="object"?D.metadata:void 0,n=((Q0)=>Q0==="running"||Q0==="completed"||Q0==="failed"||Q0==="cancelled")(y?.subagentStatus)?y.subagentStatus:"completed",U0=y?.verificationVerdict==="pass"||y?.verificationVerdict==="fail"||y?.verificationVerdict==="partial"?y.verificationVerdict:void 0,O=y&&typeof y.subagentSessionId==="string"?{subagentSessionId:y.subagentSessionId,subagentType:typeof y.subagentType==="string"?y.subagentType:A.function.name,subagentDescription:typeof y.description==="string"?y.description:void 0,subagentStatus:n,subagentSummary:typeof y.subagentSummary==="string"?y.subagentSummary:void 0,subagentResumedFrom:typeof y.subagentResumedFrom==="string"?y.subagentResumedFrom:void 0,subagentRootId:typeof y.subagentRootId==="string"?y.subagentRootId:void 0,subagentResumeDepth:typeof y.subagentResumeDepth==="number"?y.subagentResumeDepth:void 0,verificationVerdict:U0}:void 0,f0=y?(()=>{let{oldContent:Q0,newContent:R,...T0}=y;return x$(T0)})():void 0;if(y?.durableToolUseFailed!==!0&&(P!==null||$.executionEngine===void 0))try{let Q0=await _1($,Z,P??A.id,A.function.name,D.success?x$(D.llmContent):null,P,D.success?void 0:D.error?.message,O,f0,{required:$.executionEngine!==void 0});if(Q0)X=Q0}catch{return _4(K,Q.length,V)}}yield{kind:"tool_result",toolCall:A,result:D};let c=await W6(A,D,$,Z);if(c){if(yield c,!Z.taskListId&&W?.goalLifecycle?.refreshFrontier){let y=await W.goalLifecycle.refreshFrontier();if(y?.ok)yield{kind:"goal_frontier_updated",goal:y.goal,frontier:y.frontier,tasks:y.tasks};else if(y){if(y.goal)yield{kind:"goal_updated",goal:y.goal};return{success:!1,error:{type:"goal_frontier_unavailable",message:y.error.message},metadata:{turnsCount:K,toolCallsCount:Q.length,duration:Date.now()-V,tokensUsed:S}}}}}let E,f=D.metadata&&typeof D.metadata==="object"?D.metadata:void 0,p=A.function.name==="Task"&&f?{subagentSessionId:f.subagentSessionId,subagentType:f.subagentType,subagentStatus:f.subagentStatus,subagentSummary:f.subagentSummary,subagentResumedFrom:f.subagentResumedFrom,subagentRootId:f.subagentRootId,subagentResumeDepth:f.subagentResumeDepth,verificationVerdict:f.verificationVerdict,verificationFeedback:f.verificationFeedback}:void 0;if(D.success){if(J4(b,A.function.name),f?.goalCompletionRequested===!0){if(!W?.goalLifecycle)throw Error("Goal completion candidate has no host lifecycle authority");b0=!0;let O=typeof f.goalCompletionAttempt==="number"?f.goalCompletionAttempt:void 0,f0=typeof f.goalCompletionRequestedAt==="string"?f.goalCompletionRequestedAt:void 0,G0=typeof f.goalId==="string"?f.goalId:void 0;if(z4({goalId:I$,attempt:B1,requestedAt:s1},{goalId:G0,attempt:O,requestedAt:f0}))H1=0,v$=-1,q0=void 0,E0=void 0,w$=void 0,U1=void 0,x0=void 0,m0=void 0;B1=O??B1,s1=f0??s1,I$=G0??I$,j1=typeof f.goalObjective==="string"?f.goalObjective:j1;let R=await W?.goalLifecycle?.getSnapshot();if(R)u$=R.verificationStall?.consecutiveCount,yield{kind:"goal_updated",goal:R}}else if(A.function.name==="UpdateGoal"&&f?.goalStatus==="blocked"){b0=!1,d0=!1,C$=!1,z1=!1,q0=void 0,v$=-1,E0=void 0,w$=void 0,U1=void 0,u$=void 0,x0=void 0,m0=void 0;let O=await W?.goalLifecycle?.getSnapshot();if(O)yield{kind:"goal_updated",goal:O}}let y=G4(d$,A.function.name,D,Z.workspaceRoot);if(y.length>0){if(Z0=void 0,o0=!1,c0=0,q$++,p$=-1,a0=void 0,X1=0,b0){H1=0,await m$("Goal completion evidence invalidated by a workspace mutation");let O=await W?.goalLifecycle?.getSnapshot();if(O)u$=O.verificationStall?.consecutiveCount,yield{kind:"goal_updated",goal:O}}}let a=typeof f?.subagentType==="string"?f.subagentType:typeof f?.subagent_type==="string"?f.subagent_type:void 0,n=a===r0,U0=A.function.name==="Task"&&f?.verificationAgentBuiltin===!0&&(a===J$||n)&&(f?.subagentStatus==="completed"||f?.status==="completed");if(U0){if(a0=(f?.verificationVerdict==="pass"||f?.verificationVerdict==="fail"||f?.verificationVerdict==="partial"?f.verificationVerdict:void 0)??w4(typeof D.llmContent==="string"?D.llmContent:f?.subagentSummary&&typeof f.subagentSummary==="string"?f.subagentSummary:void 0),p$=q$,z1&&n){z1=!1,q0=a0,v$=q$,E0=typeof f?.subagentSessionId==="string"?f.subagentSessionId:void 0;let f0=typeof D.llmContent==="string"?D.llmContent.slice(0,4000):typeof f?.subagentSummary==="string"?f.subagentSummary:void 0,G0=typeof f?.verificationFeedback==="string"&&f.verificationFeedback.trim()?f.verificationFeedback.trim():void 0;if(w$=q0?G0??`Independent verifier returned ${q0.toUpperCase()}.`:void 0,U1=q0!=="pass"&&G0?X6("sha256").update(G0,"utf8").digest("hex"):void 0,q0&&W?.goalLifecycle){let Q0=JSON.stringify({goalId:I$,objective:j1,mutationRevision:q$,verdict:q0,verifierSessionId:E0,evidence:f0});x0=X6("sha256").update(Q0).digest("hex");let R=await W.goalLifecycle.recordVerification({verdict:q0,verifierSessionId:E0,summary:w$,evidenceSha256:x0,feedbackSha256:U1});m0=R,u$=R.verificationStall?.consecutiveCount,yield{kind:"goal_updated",goal:R}}}}if(y.length>0||U0)E={...y.length>0?{modifiedFiles:y}:{},...U0?{verificationAttempted:!0,verificationAgentBuiltin:!0,...a0?{verificationVerdict:a0}:{}}:{}};if(A.function.name==="EnterWorktree"&&D.metadata?.workspaceTransition==="enter")j0.add("EnterWorktree"),j0.delete("ExitWorktree");else if(A.function.name==="ExitWorktree"&&D.metadata?.workspaceTransition==="exit"&&j0.has("EnterWorktree"))j0.add("ExitWorktree");else if(!["EnterWorktree","ExitWorktree"].includes(A.function.name))j0.add(A.function.name);if(A.function.name==="Task"&&D.metadata?.isolation==="worktree")j0.add("TaskWorktree");I6(t1,A.function.name,D,Z.workspaceRoot)}else Z4(b,A.function.name);let C=D.success?D.llmContent||"":yZ(A.function.name,D.error);if(!D.success){let y=W4(b,A.function.name);if(y&&typeof C==="string")C=`${C}
|
|
163
|
+
</system-reminder>`;X=await D0({deps:$,context:Z,state:q,assistantContent:G.content||"",assistantReasoningContent:G.reasoningContent,lastMessageUuid:X,controlPrompt:R});continue}let O0=await W?.turnSteering?.drainOrSeal();if(O0&&O0.messages.length>0){await m$("Goal completion evidence invalidated by new user steering"),Z0=void 0,o0=!1,c0=0,q.appendAssistant({role:"assistant",content:G.content||"",reasoningContent:G.reasoningContent});let R=await C0($,Z,G.content||"",X,G.reasoningContent);if(R)X=R;yield{kind:"steering_applied",...await q1(O0.messages),delivery:"current_turn"};continue}let Y0=B4({requested:b0,taskAvailable:N().some((R)=>R.name==="Task"),mutationRevision:q$,verificationRevision:v$,verificationVerdict:q0,verificationFeedback:w$,verificationStallCount:u$,retryCount:H1});if(Y0.action==="retry"){if(H1++,d0=Y0.requireVerificationTask,d0)p0="Task";X=await D0({deps:$,context:Z,state:q,assistantContent:G.content||"",assistantReasoningContent:G.reasoningContent,lastMessageUuid:X,controlPrompt:Y0.prompt});continue}if(Y0.action==="fail")return X=await D0({deps:$,context:Z,state:q,assistantContent:G.content||"",assistantReasoningContent:G.reasoningContent,lastMessageUuid:X}),{success:!1,error:{type:"goal_verification_failed",message:Y0.message},metadata:{turnsCount:K,toolCallsCount:Q.length,duration:Date.now()-V,tokensUsed:S,goalVerificationVerdict:q0,goalVerifierSessionId:E0,goalVerificationEvidenceSha256:x0}};let I=!1,y=!1;if(b0){if(!W?.goalLifecycle||q0!=="pass")return{success:!1,error:{type:"goal_verification_failed",message:"Goal completion reached the final boundary without host-owned verification authority and a fresh PASS."},metadata:{turnsCount:K,toolCallsCount:Q.length,duration:Date.now()-V,tokensUsed:S,goalVerificationVerdict:q0,goalVerifierSessionId:E0,goalVerificationEvidenceSha256:x0}};y=!0}let a=j6(),n=a?.finalMessage??G.content??"",U0=a?.persistenceMetadata,O;if(y){let R=m0?.completionVerification;if(m0?.status!=="verifying"||m0.goalId!==I$||R?.status!=="pass"||R.attempt!==B1||typeof R.verifierSessionId!=="string"||R.verifierSessionId!==E0||typeof R.evidenceSha256!=="string"||R.evidenceSha256!==x0)throw Error("Goal completion lost its persisted verification receipt before finalization");O={goalId:m0.goalId,verificationAttempt:R.attempt,verifierSessionId:R.verifierSessionId,evidenceSha256:R.evidenceSha256,goalUpdatedAt:m0.updatedAt}}let f0=await K0(O),G0=U0||f0?{...U0,...f0?{turnFinalization:f0}:{}}:void 0;q.appendAssistant({role:"assistant",content:n,...G0?{metadata:x$(G0)}:{}});let Q0=await C0($,Z,n,X,U0?void 0:G.reasoningContent,G0);if(Q0)X=Q0;if(y&&W?.goalLifecycle){let R=await W.goalLifecycle.finalizeCompletion();b0=!1,I=!0,yield{kind:"goal_updated",goal:R}}if(a)yield a.event;return{success:!0,finalMessage:n,metadata:{turnsCount:K,toolCallsCount:Q.length,duration:Date.now()-V,tokensUsed:S,toolSuccessRate:Q.length>0?Q.filter((R)=>R.success).length/Q.length:void 0,totalToolFailures:b.totalFailures||void 0,...I?{goalCompletionVerified:!0,goalVerificationVerdict:"pass",...E0?{goalVerifierSessionId:E0}:{},...x0?{goalVerificationEvidenceSha256:x0}:{}}:{},...B6?{outputTruncated:!0}:{},...a?.resultMetadata}}}if(G.finishReason!=="length")n0=0;q.appendAssistant({role:"assistant",content:G.content||"",reasoningContent:G.reasoningContent,tool_calls:G.toolCalls});{let w=await C0($,Z,G.content||"",X,G.reasoningContent);if(w)X=w}if(W?.signal?.aborted)return B(K,Q.length,W.signal);let O1=G.toolCalls.filter((w)=>w.type==="function"),B2;if(s0?.hasTools()){l.debug(`[Loop] 使用 StreamingToolExecutor 收集 ${O1.length} 个工具结果`);let w=s0;for(let D of w.getQueuedToolCalls()){let A=j.get(D.function.name)?.kind;yield{kind:"tool_start",toolCall:D,toolKind:A}}B2=(async()=>{let D=[];for await(let P of w.getRemainingResults())D.push(P);return D})()}else{let w=new Map,D=new Y1;for(let E of O1){let f=D.admit();if(f){w.set(E.id,f);continue}let p=Q1(E.function.arguments),C=p===null?void 0:w6(E.function.name,p);if(C){w.set(E.id,C);continue}let Y0=j.get(E.function.name)?.kind;yield{kind:"tool_start",toolCall:E,toolKind:Y0}}let P=Promise.resolve(),A=(E,f,p)=>{let C=P.then(()=>A2($,Z,E,f,X,{required:$.executionEngine!==void 0,providerToolCallId:p}));return P=C.then(()=>{return},()=>{return}),C},c=async(E)=>{let f=null;try{let p=w.get(E.id);if(p)return{toolCall:E,result:p,toolUseUuid:null};let C=Q1(E.function.arguments);if(C===null)return{toolCall:E,result:{success:!1,llmContent:"",error:{type:"validation_error",message:`Invalid JSON object in tool arguments. Raw: ${E.function.arguments.slice(0,200)}`},metadata:void 0},toolUseUuid:null};V1(E.function.name,C);try{f=await A(E.function.name,C,E.id)}catch(I){return{toolCall:E,result:{success:!1,llmContent:H$,error:{type:"execution_error",message:H$},metadata:{durableToolUseFailed:!0,summary:"Blocked tool before execution"}},toolUseUuid:null,error:I instanceof Error?I:Error(String(I))}}if(E.function.name==="ExitWorktree"&&j0.has("EnterWorktree")&&!j0.has("ExitWorktree")&&F2($2,t1,0).action!=="none"){let I="Run the requested verification before ExitWorktree. The worktree remains active so Bash can run in isolation.";return{toolCall:E,result:{success:!1,llmContent:I,error:{type:"validation_error",message:I},metadata:{summary:"Blocked ExitWorktree until verification succeeds"}},toolUseUuid:f}}let Y0=await G6(E.function.name,C,{sessionId:Z.sessionId,taskListId:Z.taskListId,goalTaskListId:Z.goalTaskListId,userId:Z.userId||"default",modelId:$.config.currentModelId,providerAdmissionOwnerId:H2,workspaceRoot:Z.workspaceRoot||X0(),environment:$.config.env,worktreeIsolationRequired:w1,worktreeActive:j0.has("EnterWorktree")&&!j0.has("ExitWorktree"),subagentType:Z.subagentInfo?.subagentType,signal:W?.signal,confirmationHandler:Z.sessionId?z0.createConfirmationHandler(Z.confirmationHandler,{sessionId:Z.sessionId,projectPath:Z.workspaceRoot||X0(),toolCallId:f??E.id,toolName:E.function.name}):Z.confirmationHandler,permissionMode:Z.permissionMode,toolRegistry:j,deferredToolManager:j.deferredToolManager,onProgress:(I)=>{Y$.push({toolCall:E,update:{message:I.slice(0,1000)}})},onProgressUpdate:(I)=>{Y$.push({toolCall:E,update:I})}});return{toolCall:E,result:Y0,toolUseUuid:f}}catch(p){return l.error(`Tool execution failed for ${E.function.name}:`,p),{toolCall:E,result:{success:!1,llmContent:"",error:{type:"execution_error",message:p instanceof Error?p.message:"Unknown error"},metadata:void 0},toolUseUuid:f,error:p instanceof Error?p:Error("Unknown error")}}};B2=Promise.all(O1.map(c))}let f1,N6,P6=!1,j2=!1,p4=B2.then((w)=>{f1=w},(w)=>{P6=!0,N6=w}).finally(()=>{j2=!0,Y$.close()});while(!j2||Y$.hasPending){let w=Y$.shift()??(j2?void 0:await Y$.next());if(w)yield{kind:"tool_progress",toolCall:w.toolCall,update:w.update}}if(await p4,P6)throw N6;if(!f1)throw Error("Tool execution completed without results");let d4=new k2;for(let{toolCall:w,result:D,toolUseUuid:P}of f1){let A=w;if(Q.push(D),D.metadata?.abortedBeforeLaunch){let y=D.error?.message??"任务已被用户中止";if(P)try{let a=await _1($,Z,P,A.function.name,null,P,y,void 0,void 0,{required:$.executionEngine!==void 0});if(a)X=a}catch{return _4(K,Q.length,V)}return q.appendToolResult({role:"tool",tool_call_id:A.id,name:A.function.name,content:`Error: ${y}`}),B(K,Q.length,W?.signal)}{let y=D.metadata&&typeof D.metadata==="object"?D.metadata:void 0,n=((Q0)=>Q0==="running"||Q0==="completed"||Q0==="failed"||Q0==="cancelled")(y?.subagentStatus)?y.subagentStatus:"completed",U0=y?.verificationVerdict==="pass"||y?.verificationVerdict==="fail"||y?.verificationVerdict==="partial"?y.verificationVerdict:void 0,O=y&&typeof y.subagentSessionId==="string"?{subagentSessionId:y.subagentSessionId,subagentType:typeof y.subagentType==="string"?y.subagentType:A.function.name,subagentDescription:typeof y.description==="string"?y.description:void 0,subagentStatus:n,subagentSummary:typeof y.subagentSummary==="string"?y.subagentSummary:void 0,subagentResumedFrom:typeof y.subagentResumedFrom==="string"?y.subagentResumedFrom:void 0,subagentRootId:typeof y.subagentRootId==="string"?y.subagentRootId:void 0,subagentResumeDepth:typeof y.subagentResumeDepth==="number"?y.subagentResumeDepth:void 0,verificationVerdict:U0}:void 0,f0=y?(()=>{let{oldContent:Q0,newContent:R,...T0}=y;return x$(T0)})():void 0;if(y?.durableToolUseFailed!==!0&&(P!==null||$.executionEngine===void 0))try{let Q0=await _1($,Z,P??A.id,A.function.name,D.success?x$(D.llmContent):null,P,D.success?void 0:D.error?.message,O,f0,{required:$.executionEngine!==void 0});if(Q0)X=Q0}catch{return _4(K,Q.length,V)}}yield{kind:"tool_result",toolCall:A,result:D};let c=await W6(A,D,$,Z);if(c){if(yield c,!Z.taskListId&&W?.goalLifecycle?.refreshFrontier){let y=await W.goalLifecycle.refreshFrontier();if(y?.ok)yield{kind:"goal_frontier_updated",goal:y.goal,frontier:y.frontier,tasks:y.tasks};else if(y){if(y.goal)yield{kind:"goal_updated",goal:y.goal};return{success:!1,error:{type:"goal_frontier_unavailable",message:y.error.message},metadata:{turnsCount:K,toolCallsCount:Q.length,duration:Date.now()-V,tokensUsed:S}}}}}let E,f=D.metadata&&typeof D.metadata==="object"?D.metadata:void 0,p=A.function.name==="Task"&&f?{subagentSessionId:f.subagentSessionId,subagentType:f.subagentType,subagentStatus:f.subagentStatus,subagentSummary:f.subagentSummary,subagentResumedFrom:f.subagentResumedFrom,subagentRootId:f.subagentRootId,subagentResumeDepth:f.subagentResumeDepth,verificationVerdict:f.verificationVerdict,verificationFeedback:f.verificationFeedback}:void 0;if(D.success){if(J4(b,A.function.name),f?.goalCompletionRequested===!0){if(!W?.goalLifecycle)throw Error("Goal completion candidate has no host lifecycle authority");b0=!0;let O=typeof f.goalCompletionAttempt==="number"?f.goalCompletionAttempt:void 0,f0=typeof f.goalCompletionRequestedAt==="string"?f.goalCompletionRequestedAt:void 0,G0=typeof f.goalId==="string"?f.goalId:void 0;if(z4({goalId:I$,attempt:B1,requestedAt:s1},{goalId:G0,attempt:O,requestedAt:f0}))H1=0,v$=-1,q0=void 0,E0=void 0,w$=void 0,U1=void 0,x0=void 0,m0=void 0;B1=O??B1,s1=f0??s1,I$=G0??I$,j1=typeof f.goalObjective==="string"?f.goalObjective:j1;let R=await W?.goalLifecycle?.getSnapshot();if(R)u$=R.verificationStall?.consecutiveCount,yield{kind:"goal_updated",goal:R}}else if(A.function.name==="UpdateGoal"&&f?.goalStatus==="blocked"){b0=!1,d0=!1,C$=!1,z1=!1,q0=void 0,v$=-1,E0=void 0,w$=void 0,U1=void 0,u$=void 0,x0=void 0,m0=void 0;let O=await W?.goalLifecycle?.getSnapshot();if(O)yield{kind:"goal_updated",goal:O}}let y=G4(d$,A.function.name,D,Z.workspaceRoot);if(y.length>0){if(Z0=void 0,o0=!1,c0=0,q$++,p$=-1,a0=void 0,X1=0,b0){H1=0,await m$("Goal completion evidence invalidated by a workspace mutation");let O=await W?.goalLifecycle?.getSnapshot();if(O)u$=O.verificationStall?.consecutiveCount,yield{kind:"goal_updated",goal:O}}if(W?.goalLifecycle?.clearFrontierStall)yield{kind:"goal_updated",goal:await W.goalLifecycle.clearFrontierStall()}}let a=typeof f?.subagentType==="string"?f.subagentType:typeof f?.subagent_type==="string"?f.subagent_type:void 0,n=a===r0,U0=A.function.name==="Task"&&f?.verificationAgentBuiltin===!0&&(a===J$||n)&&(f?.subagentStatus==="completed"||f?.status==="completed");if(U0){if(a0=(f?.verificationVerdict==="pass"||f?.verificationVerdict==="fail"||f?.verificationVerdict==="partial"?f.verificationVerdict:void 0)??w4(typeof D.llmContent==="string"?D.llmContent:f?.subagentSummary&&typeof f.subagentSummary==="string"?f.subagentSummary:void 0),p$=q$,z1&&n){z1=!1,q0=a0,v$=q$,E0=typeof f?.subagentSessionId==="string"?f.subagentSessionId:void 0;let f0=typeof D.llmContent==="string"?D.llmContent.slice(0,4000):typeof f?.subagentSummary==="string"?f.subagentSummary:void 0,G0=typeof f?.verificationFeedback==="string"&&f.verificationFeedback.trim()?f.verificationFeedback.trim():void 0;if(w$=q0?G0??`Independent verifier returned ${q0.toUpperCase()}.`:void 0,U1=q0!=="pass"&&G0?X6("sha256").update(G0,"utf8").digest("hex"):void 0,q0&&W?.goalLifecycle){let Q0=JSON.stringify({goalId:I$,objective:j1,mutationRevision:q$,verdict:q0,verifierSessionId:E0,evidence:f0});x0=X6("sha256").update(Q0).digest("hex");let R=await W.goalLifecycle.recordVerification({verdict:q0,verifierSessionId:E0,summary:w$,evidenceSha256:x0,feedbackSha256:U1});m0=R,u$=R.verificationStall?.consecutiveCount,yield{kind:"goal_updated",goal:R}}}}if(y.length>0||U0)E={...y.length>0?{modifiedFiles:y}:{},...U0?{verificationAttempted:!0,verificationAgentBuiltin:!0,...a0?{verificationVerdict:a0}:{}}:{}};if(A.function.name==="EnterWorktree"&&D.metadata?.workspaceTransition==="enter")j0.add("EnterWorktree"),j0.delete("ExitWorktree");else if(A.function.name==="ExitWorktree"&&D.metadata?.workspaceTransition==="exit"&&j0.has("EnterWorktree"))j0.add("ExitWorktree");else if(!["EnterWorktree","ExitWorktree"].includes(A.function.name))j0.add(A.function.name);if(A.function.name==="Task"&&D.metadata?.isolation==="worktree")j0.add("TaskWorktree");I6(t1,A.function.name,D,Z.workspaceRoot)}else Z4(b,A.function.name);let C=D.success?D.llmContent||"":yZ(A.function.name,D.error);if(!D.success){let y=W4(b,A.function.name);if(y&&typeof C==="string")C=`${C}
|
|
164
164
|
|
|
165
165
|
${y}`}if(typeof C==="object"&&C!==null)C=JSON.stringify(C,null,2);if(typeof C==="string")C=NJ(C,A.function.name,{messageBudget:d4});let O0=typeof C==="string"?C:JSON.stringify(C);if(q.appendToolResult({role:"tool",tool_call_id:A.id,name:A.function.name,content:S4(D,O0),...A.function.name==="Task"||E?{metadata:x$({toolCallId:A.id,toolName:A.function.name,error:D.success?null:D.error?.message??null,...p?{metadata:p}:{},...E?{independentVerification:E}:{}})}:{}}),f?.durableToolUseFailed===!0)return{success:!1,error:{type:"tool_persistence_failed",message:H$,details:D.error},metadata:{turnsCount:K,toolCallsCount:Q.length,duration:Date.now()-V}};let Y0=Q1(A.function.arguments)??{},I=q6(A.function.name,Y0,D);if(I&&I.files.length>0){for(let n of I.references)_.add(n.id);let y={role:"system",content:I.content,metadata:x$({contextualProjectRules:!0,ruleReferences:I.references,triggerPaths:I.triggerPaths})};q.appendContextualProjectInstructions(y);let a=await a6($,Z,I.references,I.triggerPaths,X);if(a)X=a;yield{kind:"project_rules_loaded",files:I.files.map((n)=>({id:n.id,relativePath:n.relativePath,source:n.source,conditional:n.conditional,contentSha256:n.contentSha256})),triggerPaths:I.triggerPaths,blockedWrite:D.metadata?.contextualProjectRulesRequired===!0}}if(A.function.name===u0&&D.metadata?.structuredOutputRetryExhausted===!0)return{success:!1,error:{type:"structured_output_failed",message:D.error?.message??"Structured output validation retry budget was exhausted."},metadata:{turnsCount:K,toolCallsCount:Q.length,duration:Date.now()-V,tokensUsed:S,structuredOutputSchemaDigest:U?.schemaDigest}};if(W?.signal?.aborted)return B(K,Q.length,W.signal);if(D.metadata?.shouldExitLoop){let y=typeof D.llmContent==="string"?D.llmContent:"循环已退出";return{success:D.success,finalMessage:y,metadata:{turnsCount:K,toolCallsCount:Q.length,duration:Date.now()-V,shouldExitLoop:!0,targetMode:D.metadata?.targetMode,planContent:typeof D.metadata?.planContent==="string"?D.metadata.planContent:void 0}}}}let V$=n2(M,O1,f1.map(({result:w})=>w));if(V$){if(yield{kind:"action_stationarity",...V$},V$.phase==="halted")return{success:!1,error:{type:"loop_detected",message:`Stopped after ${V$.runLength} repeated ${V$.toolName} calls without observable progress.`},metadata:{turnsCount:K,toolCallsCount:Q.length,duration:Date.now()-V,tokensUsed:S}};if(V$.phase==="detected"){let w={role:"user",content:`
|
|
166
166
|
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import{realpathSync as z}from"fs";import{cwd as F}from"process";var u=null;function G(){let m="";if(typeof process<"u"&&typeof process.cwd==="function"&&typeof z==="function"){let x=F();try{m=z(x).normalize("NFC")}catch{m=x.normalize("NFC")}}return{cwd:m,originalCwd:m,projectRoot:m}}function q(){if(!u)u=G();return u}function B(){return q().cwd}function N(m){q().cwd=m.normalize("NFC")}function D(){return q().originalCwd}function P(m){q().projectRoot=m.normalize("NFC")}import{AsyncLocalStorage as H}from"async_hooks";var I=new H;function J(){return I.getStore()??B()}function V(){try{return J()}catch{return D()}}
|
|
2
|
-
export{N as
|
|
2
|
+
export{N as Mh,D as Nh,P as Oh,V as Ph};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a,b as i,c as l,d as m}from"./chunk-mgsvn9v4.js";import"./chunk-7fz3w4rk.js";import"./chunk-47e6tdbb.js";import"./chunk-afa35v3f.js";import"./chunk-khtxprbv.js";import"./chunk-k9fveqq6.js";import"./chunk-b0j9v359.js";import"./chunk-abd57h72.js";import"./chunk-xtb84adp.js";import"./chunk-xm8nyj5z.js";import"./chunk-0aa40zbs.js";import"./chunk-8hprmrd5.js";import"./chunk-wzmqkam9.js";import"./chunk-s0tq8gyx.js";import"./chunk-x3cxmwnz.js";import{ve as n}from"./chunk-gr80w0vh.js";import"./chunk-z9gd9spf.js";import{Re as s}from"./chunk-q6eb20fz.js";import"./chunk-v508x7cg.js";import"./chunk-dg0d3303.js";import"./chunk-rchz6j90.js";import"./chunk-w7hy5wh1.js";import"./chunk-2hb222re.js";import"./chunk-07w0qapm.js";import"./chunk-ywarj5j9.js";import"./chunk-kf7whgr7.js";import"./chunk-fva7jnjy.js";import"./chunk-41ympwz1.js";import"./chunk-aa5zmwd9.js";import"./chunk-41cg66y0.js";import"./chunk-f945dzj6.js";import"./chunk-sdbbyagy.js";import"./chunk-f3426b1c.js";import"./chunk-c475tfqf.js";import"./chunk-0hr050ck.js";import"./chunk-q69fzq4y.js";import"./chunk-n7mzxa8h.js";import"./chunk-s10pmnrd.js";import"./chunk-9p20hhs0.js";import"./chunk-14bs89sm.js";import"./chunk-wyhyw9rq.js";import"./chunk-rvk9r2cm.js";import"./chunk-tgdhsm5t.js";import"./chunk-fhfzdyba.js";import v from"chalk";var C={command:"serve",describe:"Start a headless Blade server (no browser)",builder:a,handler:async(p)=>{let r=i(p);if(await s(),!process.env.BLADE_SERVER_PASSWORD)console.log(v.yellow("Warning: BLADE_SERVER_PASSWORD is not set; server is unsecured."));let e=await m.listenAsync(r);if(console.log(`Blade server listening on http://${e.hostname}:${e.port}`),r.hostname==="0.0.0.0"){let o=l();for(let g of o)console.log(` Network: http://${g}:${e.port}`)}let t,c=new Promise((o)=>{t=o}),d=n(async()=>{await e.stop(),t()});try{await c}finally{d(),await e.stop()}}};export{C as serveCommand};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{readFileSync as l}from"node:fs";import{dirname as o,join as u}from"node:path";import{fileURLToPath as a}from"node:url";var e={name:"blade-code",version:"0.10.
|
|
2
|
-
export{y as
|
|
1
|
+
import{readFileSync as l}from"node:fs";import{dirname as o,join as u}from"node:path";import{fileURLToPath as a}from"node:url";var e={name:"blade-code",version:"0.10.103",private:!1,description:"🗡️ Blade Code - 智能代码助手命令行工具",type:"module",bin:{blade:"dist/blade.js"},files:["dist","vendor/ripgrep/**","README.md"],scripts:{dev:"node scripts/run-bun.js --watch src/blade.tsx","dev:serve":"node scripts/run-bun.js --watch src/blade.tsx serve --port 4097",build:"rm -rf dist && node scripts/run-bun.js run scripts/build.ts",start:"node scripts/run-bun.js run dist/blade.js",test:"node scripts/test.js","test:all":"vitest run --config vitest.config.ts --project='!performance' && vitest run --config vitest.config.ts --project=performance","test:unit":"node scripts/test.js unit","test:integration":"node scripts/test.js integration","test:real-api":"node scripts/test.js realApi","test:real-api:qualification":"node scripts/test.js realApiQualification","test:cli":"node scripts/test.js cli","test:headless-core":"node scripts/test.js headlessCore","test:e2e":"node scripts/test.js e2e","test:performance":"node scripts/test.js performance","test:snapshot":"node scripts/test.js snapshot","test:security":"node scripts/test.js security","browser:install":"playwright install chromium","browser:check":"node scripts/run-bun.js run scripts/browser-check.ts","test:coverage":"node scripts/test.js all --coverage","test:watch":"vitest --watch --config vitest.config.ts","qualify:local":"node scripts/run-bun.js run scripts/qualify.ts local","qualify:production":"node scripts/run-bun.js run scripts/qualify.ts production","benchmark:repo":"node scripts/run-bun.js run scripts/run-real-repo-benchmark.ts","test:update-snapshots":"node scripts/test.js snapshot --update",lint:"biome lint src tests","lint:fix":"biome lint --write src tests","type-check":"tsc --noEmit","format:check":"biome format src tests",ready:"node scripts/run-bun.js run scripts/qualify.ts production","detect-unused":"node scripts/run-bun.js run scripts/detect-unused.ts",prepack:"node scripts/run-bun.js run build",release:"node scripts/release.js","release:dry":"node scripts/release.js --dry-run","release:major":"node scripts/release.js --major","release:minor":"node scripts/release.js --minor","release:patch":"node scripts/release.js --patch"},keywords:["cli","blade","ai","assistant","agent","llm"],author:"echoVic",license:"MIT",repository:{type:"git",url:"git+https://github.com/echoVic/blade-code.git"},homepage:"https://github.com/echoVic/blade-code#readme",bugs:{url:"https://github.com/echoVic/blade-code/issues"},engines:{node:">=22.19.0"},optionalDependencies:{"@vscode/ripgrep":"^1.18.0","better-sqlite3":"^11.8.1","bun-pty":"^0.4.8","node-pty":"1.1.0"},dependencies:{"@agentclientprotocol/sdk":"^1.3.0","@anthropic-ai/sandbox-runtime":"0.0.67","@earendil-works/pi-ai":"0.84.2","@inkjs/ui":"^2.0.0","@modelcontextprotocol/sdk":"^1.30.0",ahooks:"^3.9.7",ajv:"^8.17.1","ansi-escapes":"^7.3.0","async-mutex":"^0.5.0",axios:"^1.19.0",chalk:"^5.4.1",diff:"^8.0.2","fast-glob":"^3.3.3","fuse.js":"^7.5.0","gray-matter":"^4.0.3",hono:"^4.13.0",ink:"npm:@jrichman/ink@6.4.10","ink-big-text":"^2.0.0","ink-gradient":"^3.0.0","ink-select-input":"^6.2.0","ink-spinner":"^5.0.0","ink-text-input":"^6.0.0","js-tiktoken":"^1.0.21","lodash-es":"^4.18.1",lowlight:"^3.3.0","lru-cache":"^11.5.2",nanoid:"^5.1.6",open:"^10.1.2",picomatch:"^4.0.5",playwright:"1.62.1","proper-lockfile":"^4.1.2",react:"19.2.4","react-dom":"19.2.4",semver:"^7.8.5","string-width":"^8.2.2",typebox:"1.3.10",undici:"^7.16.0","vscode-jsonrpc":"8.2.1","vscode-languageserver-protocol":"3.17.5","vscode-languageserver-types":"3.17.5","write-file-atomic":"^7.0.0",ws:"^8.21.2",yaml:"^2.9.0",yargs:"^18.1.0",zustand:"^5.0.14"},devDependencies:{"@biomejs/biome":"2.5.7","@types/bun":"^1.3.14","@types/json-schema":"^7.0.15","@types/lodash-es":"^4.17.12","@types/node":"^22.15.24","@types/picomatch":"^4.0.3","@types/proper-lockfile":"^4.1.4","@types/react":"19.2.10","@types/react-dom":"19.2.3","@types/semver":"^7.8.0","@types/write-file-atomic":"^4.0.3","@types/ws":"^8.18.1","@types/yargs":"^17.0.35","@vitest/coverage-v8":"^4.1.10",jsdom:"^26.0.0",typescript:"^5.9.2",vitest:"^4.1.10"}};var s;function r(){if(s)return s;let i=o(a(import.meta.url));for(let n=0;n<5;n++){try{let t=JSON.parse(l(u(i,"package.json"),"utf8"));if(t.name===e.name&&typeof t.version==="string"&&typeof t.description==="string")return s=t,s}catch{}i=o(i)}return s={name:e.name,version:process.env.BLADE_VERSION??e.version,description:e.description},s}function y(){return{...r()}}function p(){return r().version}function v(){return r().name}function g(){return r().description}function f(){return`v${p()}`}function w(){return`v${p()} © 2025 Blade Code`}
|
|
2
|
+
export{y as Ci,p as Di,v as Ei,g as Fi,f as Gi,w as Hi};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Ka as V,Ma as W,Na as O,db as J}from"./chunk-
|
|
1
|
+
import{Ka as V,Ma as W,Na as O,db as J}from"./chunk-xm8nyj5z.js";import"./chunk-f3426b1c.js";import"./chunk-c475tfqf.js";import{Ph as Q}from"./chunk-0hr050ck.js";import"./chunk-n7mzxa8h.js";import"./chunk-tgdhsm5t.js";import"./chunk-fhfzdyba.js";import F from"chalk";var K=(f)=>typeof f==="string"&&f.length>0?f:void 0;function X(f){let z=K(f.cron),G=K(f.every),H=K(f.at);if([z,G,H].filter(Boolean).length!==1)throw Error("Provide exactly one of --cron, --every, or --at");if(z)return{kind:"cron",cron:z};if(G){let P=V(G);if(!P)throw Error(`Invalid --every value "${G}" (use e.g. 30m, 2h, 1d)`);return{kind:"interval",intervalMs:P}}let N=new Date(H);if(Number.isNaN(N.getTime()))throw Error(`Invalid --at value "${H}" (use an ISO timestamp)`);return{kind:"once",runAt:N.toISOString()}}var Y={command:"create <prompt>",describe:"创建定时任务",builder:(f)=>f.positional("prompt",{type:"string",describe:"定时任务运行时发送给 Agent 的提示词",demandOption:!0}).option("cron",{type:"string",describe:"5 段 cron 表达式(本地时区)"}).option("every",{type:"string",describe:"间隔(如 30m、2h、1d)"}).option("at",{type:"string",describe:"一次性运行的 ISO 时间点"}).option("project-path",{alias:["projectPath","project"],type:"string",describe:"目标项目路径(默认当前目录)"}).option("title",{type:"string",describe:"定时任务标题"}).option("model",{alias:"m",type:"string",describe:"模型 ID"}).option("permission-mode",{type:"string",choices:["default","autoEdit","yolo","plan"],default:"default",describe:"权限模式"}).option("isolation",{type:"string",choices:["local","worktree"],default:"worktree",describe:"执行隔离方式"}).example([['$0 schedule create "跑测试并汇报失败" --every 1h',"每小时运行一次"],['$0 schedule create "生成每日站会摘要" --cron "0 9 * * 1-5"',"工作日 9 点运行"]]),handler:async(f)=>{try{let z=X(f),G=W(z);if(G)throw Error(G);let H={prompt:f.prompt,projectPath:K(f.projectPath)??Q(),title:K(f.title),trigger:z,modelId:K(f.model),isolation:K(f.isolation)??"worktree",permissionMode:K(f.permissionMode)??"default",enabled:!0},B=await J.create(H);console.log(F.green(`✓ 已创建定时任务 ${B.id}`)),console.log(` ${O(B.trigger)}`),console.log(` 项目: ${B.projectPath}`),console.log(` 下次运行: ${B.nextRunAt?new Date(B.nextRunAt).toLocaleString():"(无)"}`),process.exit(0)}catch(z){console.error(F.red(`创建定时任务失败: ${z instanceof Error?z.message:z}`)),process.exit(1)}}},Z={command:"list",aliases:["ls"],describe:"列出所有定时任务",handler:async()=>{let f=await J.list();if(f.length===0)console.log(F.dim("尚无定时任务。使用 `blade schedule create` 创建。")),process.exit(0);for(let z of f){let G=z.enabled?F.green("启用"):F.dim("停用"),H=z.nextRunAt?new Date(z.nextRunAt).toLocaleString():"—",B=z.lastRunAt?`${new Date(z.lastRunAt).toLocaleString()} (${z.lastStatus??"?"})`:"从未";console.log(`${F.cyan(z.id)} [${G}] ${z.title??z.prompt.slice(0,40)}`),console.log(` ${O(z.trigger)} · 下次: ${H} · 上次: ${B} · 运行 ${z.runCount} 次`),console.log(F.dim(` 项目: ${z.projectPath}`))}process.exit(0)}},_={command:"show <id>",describe:"查看定时任务详情",builder:(f)=>f.positional("id",{type:"string",describe:"定时任务 ID",demandOption:!0}),handler:async(f)=>{let z=await J.get(f.id);if(!z)console.error(F.red(`未找到定时任务 ${f.id}`)),process.exit(1);console.log(JSON.stringify(z,null,2)),process.exit(0)}},$={command:"remove <id>",aliases:["rm"],describe:"删除定时任务",builder:(f)=>f.positional("id",{type:"string",describe:"定时任务 ID",demandOption:!0}),handler:async(f)=>{if(!await J.remove(f.id))console.error(F.red(`未找到定时任务 ${f.id}`)),process.exit(1);console.log(F.green(`✓ 已删除定时任务 ${f.id}`)),process.exit(0)}},q={command:"enable <id>",describe:"启用定时任务",builder:(f)=>f.positional("id",{type:"string",describe:"定时任务 ID",demandOption:!0}),handler:async(f)=>{if(!await J.setEnabled(f.id,!0))console.error(F.red(`未找到定时任务 ${f.id}`)),process.exit(1);console.log(F.green(`✓ 已启用定时任务 ${f.id}`)),process.exit(0)}},x={command:"disable <id>",describe:"停用定时任务",builder:(f)=>f.positional("id",{type:"string",describe:"定时任务 ID",demandOption:!0}),handler:async(f)=>{if(!await J.setEnabled(f.id,!1))console.error(F.red(`未找到定时任务 ${f.id}`)),process.exit(1);console.log(F.green(`✓ 已停用定时任务 ${f.id}`)),process.exit(0)}},D={command:"run <id>",describe:"立即运行定时任务(需要 blade serve)",builder:(f)=>f.positional("id",{type:"string",describe:"定时任务 ID",demandOption:!0}).option("server",{type:"string",default:process.env.BLADE_SERVER_URL??"http://127.0.0.1:4097",describe:"Blade server 地址"}),handler:async(f)=>{let z=f.id,G=(K(f.server)??"http://127.0.0.1:4097").replace(/\/$/,""),H={};if(process.env.BLADE_SERVER_PASSWORD){let B=process.env.BLADE_SERVER_USERNAME??"blade";H.Authorization=`Basic ${Buffer.from(`${B}:${process.env.BLADE_SERVER_PASSWORD}`).toString("base64")}`}try{let B=await fetch(`${G}/schedules/${encodeURIComponent(z)}/run`,{method:"POST",headers:H});if(!B.ok){let N=await B.json().catch(()=>{return});throw Error(N?.error?.message??`Schedule run failed (${B.status})`)}console.log(F.green(`✓ 已触发定时任务 ${z}`)),process.exit(0)}catch(B){console.error(F.red(`运行定时任务失败: ${B instanceof Error?B.message:B}`)),process.exit(1)}}},R={command:"schedule",describe:"管理定时任务",builder:(f)=>f.command(Y).command(Z).command(_).command($).command(q).command(x).command(D).demandCommand(1,"请提供子命令:create | list | show | remove | enable | disable | run"),handler:()=>{}};export{R as scheduleCommands};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import{spawn as I}from"node:child_process";var X=500;function x(j){return new Promise((q)=>setTimeout(q,j))}function Z(j){return j&&typeof j==="object"&&"code"in j?String(j.code):void 0}function L(j){return j()||j()}function G(j,q=process.platform,y=process.kill.bind(process)){if(q==="win32"||!Number.isInteger(j)||j<=1||j===process.pid)return!1;try{return y(-j,0),!0}catch(z){let B=Z(z);if(B==="ESRCH")return!1;if(B==="EPERM")return!0;throw z}}function N(j,q){return new Promise((y)=>{let z=["/PID",String(j),"/T"];if(q)z.push("/F");let B=I("taskkill",z,{stdio:"ignore",windowsHide:!0}),K=!1,J=(H)=>{if(K)return;K=!0,y(H)};B.once("error",()=>J(!1)),B.once("close",(H)=>J(H===0))})}async function F(j,q={}){if(!Number.isInteger(j)||j<=1||j===process.pid)return{success:!1,alreadyExited:!1,forced:!1};let y=q.platform??process.platform,z=q.gracePeriodMs??X,B=q.killProcess??process.kill.bind(process),K=q.taskkill??N,J=q.wait??x,H=q.validatePidOwnership??(()=>!0);if(!L(H))return{success:!1,alreadyExited:!1,forced:!1};if(y==="win32"){let V=await K(j,!1);if(await J(z),!H())return{success:V,alreadyExited:!1,forced:!1};let Y=await K(j,!0);return{success:V||Y,alreadyExited:!V&&!Y,forced:Y}}let Q=(V,Y)=>{try{return B(V,Y)}catch(D){return Z(D)==="ESRCH"}},W=Q(-j,"SIGTERM")||Q(j,"SIGTERM");if(await J(z),!H())return{success:W,alreadyExited:!1,forced:!1};let $=Q(-j,"SIGKILL")||Q(j,"SIGKILL");return{success:W||$,alreadyExited:!1,forced:$}}async function R(j,q={}){if(!Number.isInteger(j)||j<=1||j===process.pid)return{success:!1,alreadyExited:!1,forced:!1};if((q.platform??process.platform)==="win32")return{success:!1,alreadyExited:!1,forced:!1};let z=q.gracePeriodMs??X,B=q.killProcess??process.kill.bind(process),K=q.wait??x,J=q.validatePidOwnership??(()=>!0);if(!J())return{success:!1,alreadyExited:!1,forced:!1};let H=($)=>{try{return B(-j,$),"sent"}catch(V){return Z(V)==="ESRCH"?"missing":"failed"}},Q=H("SIGTERM");if(Q==="missing")return{success:!0,alreadyExited:!0,forced:!1};if(Q==="failed")return{success:!1,alreadyExited:!1,forced:!1};if(await K(z),!J())return{success:!1,alreadyExited:!1,forced:!1};let W=H("SIGKILL");return{success:W!=="failed",alreadyExited:W==="missing",forced:W==="sent"}}class b{child;state="owned";terminationPromise;terminationResult;platform;gracePeriodMs;killProcess;taskkill;wait;constructor(j,q={}){this.child=j;if(this.platform=q.platform??process.platform,this.gracePeriodMs=q.gracePeriodMs??X,this.killProcess=q.killProcess??process.kill.bind(process),this.taskkill=q.taskkill??N,this.wait=q.wait??x,q.releaseOnExit!==!1){let y=()=>{if(this.state==="owned")this.state="released"};j.once("close",y),j.once("error",y)}}release(){if(this.state==="owned")this.state="released"}terminate(){if(this.terminationPromise)return this.terminationPromise;if(this.terminationResult)return Promise.resolve(this.terminationResult);if(this.state==="released")return this.terminationResult={success:!0,alreadyExited:!0,forced:!1},Promise.resolve(this.terminationResult);return this.state="terminating",this.terminationPromise=this.terminateOwnedTree().then((j)=>{return this.state="released",this.terminationResult=j,j}),this.terminationPromise}async terminateOwnedTree(){let j=this.child.pid;if(!j)return{success:!1,alreadyExited:!0,forced:!1};if(this.platform==="win32"){let z=await this.taskkill(j,!1);await this.wait(this.gracePeriodMs);let B=await this.taskkill(j,!0);if(!z&&!B)return{success:this.signalDirectChild("SIGKILL"),alreadyExited:!1,forced:!0};return{success:!0,alreadyExited:!1,forced:!0}}let q=this.signalPosixTree(j,"SIGTERM");await this.wait(this.gracePeriodMs);let y=this.signalPosixTree(j,"SIGKILL");return{success:q||y,alreadyExited:!1,forced:y}}signalPosixTree(j,q){if(j<=1||j===process.pid)return this.signalDirectChild(q);try{return this.killProcess(-j,q)}catch(y){if(Z(y)==="ESRCH")return!0;return this.signalDirectChild(q)}}signalDirectChild(j){try{return this.child.kill(j)}catch(q){return Z(q)==="ESRCH"}}}function v(j,q,y={},z={}){let B=I(j,q,{...y,detached:process.platform==="win32"?y.detached:!0,windowsHide:y.windowsHide??!0});return{child:B,processTree:new b(B,z)}}
|
|
2
|
-
export{G as
|
|
2
|
+
export{G as rg,F as sg,R as tg,v as ug};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
function v(b){switch(b){case"default":case"ignore":case void 0:return"default";case"acceptEdits":return"autoEdit";case"dontAsk":case"bypassPermissions":return"yolo";case"plan":return"plan";default:return"default"}}
|
|
2
|
-
export{v as
|
|
2
|
+
export{v as ng};
|