blade-code 0.10.77 → 0.10.79

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.
Files changed (43) hide show
  1. package/dist/blade.js +2 -2
  2. package/dist/{chunk-geam96gd.js → chunk-15d37a9g.js} +1 -1
  3. package/dist/{chunk-b86m3bpv.js → chunk-2avf4cje.js} +1 -1
  4. package/dist/{chunk-c8td6vaa.js → chunk-2bnyt7cf.js} +1 -1
  5. package/dist/{chunk-pq4fjmnj.js → chunk-2rmvmn9z.js} +2 -2
  6. package/dist/{chunk-mb3htbeh.js → chunk-4d2n8s9t.js} +1 -1
  7. package/dist/{chunk-28drv25s.js → chunk-6c4na2qt.js} +1 -1
  8. package/dist/{chunk-b9hdp0n4.js → chunk-6kw4vt7f.js} +1 -1
  9. package/dist/{chunk-hchn7baz.js → chunk-70xvj0fk.js} +1 -1
  10. package/dist/chunk-77dgfccy.js +1 -0
  11. package/dist/{chunk-b948f9w9.js → chunk-7myqyckn.js} +1 -1
  12. package/dist/{chunk-n3amyjrd.js → chunk-7nqgs7ks.js} +10 -6
  13. package/dist/{chunk-qz5xm4cr.js → chunk-7qw60vp3.js} +1 -1
  14. package/dist/{chunk-0hpenwph.js → chunk-839wmh6x.js} +1 -1
  15. package/dist/{chunk-yqkyhp0e.js → chunk-8zqh039s.js} +1 -1
  16. package/dist/{chunk-69s3e453.js → chunk-amt7zcwa.js} +1 -1
  17. package/dist/{chunk-72kqnntm.js → chunk-avgr2zqg.js} +2 -2
  18. package/dist/{chunk-9tb7cwem.js → chunk-b8d24zwc.js} +1 -1
  19. package/dist/{chunk-nx4z7pxk.js → chunk-bnazr3xq.js} +1 -1
  20. package/dist/{chunk-mctkgv0d.js → chunk-bxd1sgkn.js} +2 -2
  21. package/dist/{chunk-cq5gtwxb.js → chunk-caze72pr.js} +1 -1
  22. package/dist/{chunk-dshgm836.js → chunk-evzyvfpf.js} +1 -1
  23. package/dist/{chunk-zwbv30np.js → chunk-g8f7aeez.js} +1 -1
  24. package/dist/{chunk-phgcgfv1.js → chunk-gdyw5ns9.js} +1 -1
  25. package/dist/chunk-gjsbq683.js +1 -0
  26. package/dist/{chunk-3ekj5azv.js → chunk-jab5sse7.js} +1 -1
  27. package/dist/{chunk-2herdn98.js → chunk-jh6e9k2e.js} +1 -1
  28. package/dist/{chunk-3j0dhewn.js → chunk-mjfgsz1s.js} +1 -1
  29. package/dist/{chunk-nqcpyazv.js → chunk-qcvmgzwv.js} +1 -1
  30. package/dist/{chunk-5e56atqj.js → chunk-ramasfqv.js} +19 -19
  31. package/dist/{chunk-xrt796d6.js → chunk-reb7gmf8.js} +1 -1
  32. package/dist/{chunk-je4xvy93.js → chunk-sa1pvsfw.js} +1 -1
  33. package/dist/{chunk-cr1xp3re.js → chunk-te9ymjg6.js} +1 -1
  34. package/dist/chunk-w8ym5eps.js +6 -0
  35. package/dist/chunk-wvprjxna.js +169 -0
  36. package/dist/{chunk-pr8c6qef.js → chunk-wyww8q65.js} +1 -1
  37. package/dist/{chunk-dj99h8ca.js → chunk-ybr0g37q.js} +1 -1
  38. package/dist/{chunk-7ffdedgc.js → chunk-zby4p535.js} +1 -1
  39. package/package.json +1 -1
  40. package/dist/chunk-0cbr2gs7.js +0 -168
  41. package/dist/chunk-8k4jza38.js +0 -1
  42. package/dist/chunk-nxmssc56.js +0 -1
  43. package/dist/chunk-rdvm8zvw.js +0 -6
package/dist/blade.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{zd as W}from"./chunk-2herdn98.js";import{Cd as F,Dd as M}from"./chunk-h3w814js.js";import"./chunk-yqkyhp0e.js";import"./chunk-v508x7cg.js";import"./chunk-c9e0fbyh.js";import"./chunk-je4xvy93.js";import"./chunk-zkhb55jz.js";import"./chunk-dj99h8ca.js";import"./chunk-pfvgkexe.js";import"./chunk-qxn5bg5k.js";import"./chunk-reakyamv.js";import{Ng as N,Og as B}from"./chunk-0141jad7.js";import"./chunk-eeb2945p.js";import{nh as T}from"./chunk-b9vm7gns.js";import"./chunk-5nezhmnq.js";import"./chunk-h6a0nct6.js";import"./chunk-7ffdedgc.js";import"./chunk-0a0sj79a.js";import"./chunk-sj0k8cdf.js";import"./chunk-0ra945vt.js";import{Wh as J}from"./chunk-h0fh3j9w.js";import v from"node:path";var E=process.argv.slice(2),I=u(E),p=I!==null;if(I!==null)T.setGlobalDebug(I);function u(Q){for(let Y=0;Y<Q.length;Y+=1){let U=Q[Y];if(U==="--debug"||U==="-d"){let X=Q[Y+1];return X&&!X.startsWith("-")?X:!0}if(U.startsWith("--debug="))return U.slice(8)||!0}return null}function c(Q){return Q.length===1&&(Q[0]==="--version"||Q[0]==="-V")}function q(Q,...Y){return Q.some((U)=>Y.some((X)=>U===X||U.startsWith(`${X}=`)))}function m(Q,...Y){let U=[];for(let X=0;X<Q.length;X+=1){let G=Q[X],z=Y.find(($)=>G.startsWith(`${$}=`));if(z){let $=G.slice(z.length+1);if($)U.push($);continue}if(Y.includes(G)){let $=Q[X+1];if($&&!$.startsWith("-"))U.push($),X+=1}}return U}async function t(){if(c(E)){let{getVersion:K}=await import("./chunk-b9hdp0n4.js");console.log(K());return}let Q=process.cwd(),Y=F(Q);M(Y),N(B());let U=m(E,"--plugin-dir","--pluginDir");if(U.length>0){let{configureInvocationPluginDirs:K}=await import("./chunk-9tb7cwem.js");K(U.map((Z)=>v.resolve(Q,Z)))}if(q(E,"--trust-workspace","--trustWorkspace")){let{WorkspaceTrustService:K}=await import("./chunk-6adxyred.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-rdvm8zvw.js");if(await K())return}if(W(),q(E,"--print","-p")){let{handlePrintMode:K}=await import("./chunk-pr8c6qef.js");if(await K())return}if(E.includes("--acp")){let{runAcpIntegration:K}=await import("./chunk-72kqnntm.js");await K();return}let[{default:X},{hideBin:G},{cliConfig:z,globalOptions:$},{loadConfiguration:_,validateOutput:D,validatePermissions:R},{doctorCommands:S},{installCommands:k},{mcpCommands:O},{projectsCommands:y},{scheduleCommands:b},{serveCommand:V},{updateCommands:P},{webCommand:x}]=await Promise.all([import("yargs"),import("yargs/helpers"),import("./chunk-nxmssc56.js"),import("./chunk-3ekj5azv.js"),import("./chunk-pq4fjmnj.js"),import("./chunk-fsm3fb2m.js"),import("./chunk-cq5gtwxb.js"),import("./chunk-gre57x9m.js"),import("./chunk-091qx62q.js"),import("./chunk-zwbv30np.js"),import("./chunk-mb3htbeh.js"),import("./chunk-cr1xp3re.js")]),A=X(G(process.argv)).scriptName(z.scriptName).usage(z.usage).version(z.version).locale(z.locale).showHelpOnFail(z.showHelpOnFail).demandCommand(0,"").recommendCommands().strict(z.strict).parserConfiguration({"populate--":!0}).options($).middleware([_,R,D]).command(O).command(y).command(b).command(S).command(P).command(k).command(x).command(V).completion("completion",!1).help("help","Show help").alias("help","h").alias("version","V").fail((K,Z,L)=>{if(Z){if(console.error("An error occurred:"),console.error(Z.message),p&&Z.stack)console.error(`
2
+ import{zd as W}from"./chunk-jh6e9k2e.js";import{Cd as F,Dd as M}from"./chunk-h3w814js.js";import"./chunk-8zqh039s.js";import"./chunk-v508x7cg.js";import"./chunk-c9e0fbyh.js";import"./chunk-sa1pvsfw.js";import"./chunk-zkhb55jz.js";import"./chunk-ybr0g37q.js";import"./chunk-pfvgkexe.js";import"./chunk-qxn5bg5k.js";import"./chunk-reakyamv.js";import{Ng as N,Og as B}from"./chunk-0141jad7.js";import"./chunk-eeb2945p.js";import{nh as T}from"./chunk-b9vm7gns.js";import"./chunk-5nezhmnq.js";import"./chunk-h6a0nct6.js";import"./chunk-zby4p535.js";import"./chunk-0a0sj79a.js";import"./chunk-sj0k8cdf.js";import"./chunk-0ra945vt.js";import{Wh as J}from"./chunk-h0fh3j9w.js";import v from"node:path";var E=process.argv.slice(2),I=u(E),p=I!==null;if(I!==null)T.setGlobalDebug(I);function u(Q){for(let Y=0;Y<Q.length;Y+=1){let U=Q[Y];if(U==="--debug"||U==="-d"){let X=Q[Y+1];return X&&!X.startsWith("-")?X:!0}if(U.startsWith("--debug="))return U.slice(8)||!0}return null}function c(Q){return Q.length===1&&(Q[0]==="--version"||Q[0]==="-V")}function q(Q,...Y){return Q.some((U)=>Y.some((X)=>U===X||U.startsWith(`${X}=`)))}function m(Q,...Y){let U=[];for(let X=0;X<Q.length;X+=1){let G=Q[X],z=Y.find(($)=>G.startsWith(`${$}=`));if(z){let $=G.slice(z.length+1);if($)U.push($);continue}if(Y.includes(G)){let $=Q[X+1];if($&&!$.startsWith("-"))U.push($),X+=1}}return U}async function t(){if(c(E)){let{getVersion:K}=await import("./chunk-6kw4vt7f.js");console.log(K());return}let Q=process.cwd(),Y=F(Q);M(Y),N(B());let U=m(E,"--plugin-dir","--pluginDir");if(U.length>0){let{configureInvocationPluginDirs:K}=await import("./chunk-b8d24zwc.js");K(U.map((Z)=>v.resolve(Q,Z)))}if(q(E,"--trust-workspace","--trustWorkspace")){let{WorkspaceTrustService:K}=await import("./chunk-6adxyred.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-w8ym5eps.js");if(await K())return}if(W(),q(E,"--print","-p")){let{handlePrintMode:K}=await import("./chunk-wyww8q65.js");if(await K())return}if(E.includes("--acp")){let{runAcpIntegration:K}=await import("./chunk-avgr2zqg.js");await K();return}let[{default:X},{hideBin:G},{cliConfig:z,globalOptions:$},{loadConfiguration:_,validateOutput:D,validatePermissions:R},{doctorCommands:S},{installCommands:k},{mcpCommands:O},{projectsCommands:y},{scheduleCommands:b},{serveCommand:V},{updateCommands:P},{webCommand:x}]=await Promise.all([import("yargs"),import("yargs/helpers"),import("./chunk-77dgfccy.js"),import("./chunk-jab5sse7.js"),import("./chunk-2rmvmn9z.js"),import("./chunk-fsm3fb2m.js"),import("./chunk-caze72pr.js"),import("./chunk-gre57x9m.js"),import("./chunk-091qx62q.js"),import("./chunk-g8f7aeez.js"),import("./chunk-4d2n8s9t.js"),import("./chunk-te9ymjg6.js")]),A=X(G(process.argv)).scriptName(z.scriptName).usage(z.usage).version(z.version).locale(z.locale).showHelpOnFail(z.showHelpOnFail).demandCommand(0,"").recommendCommands().strict(z.strict).parserConfiguration({"populate--":!0}).options($).middleware([_,R,D]).command(O).command(y).command(b).command(S).command(P).command(k).command(x).command(V).completion("completion",!1).help("help","Show help").alias("help","h").alias("version","V").fail((K,Z,L)=>{if(Z){if(console.error("An error occurred:"),console.error(Z.message),p&&Z.stack)console.error(`
3
3
  Stack trace:`),console.error(Z.stack);else console.error(`
4
4
  Run with --debug to show the stack trace.`);process.exit(1)}if(K)console.error("Error: Invalid arguments:"),console.error(K),console.error(`
5
- Hint: Did you mean:`),L.showHelp(),process.exit(1)}).command("$0",!1,()=>{},async(K)=>{let Z=K._.slice(1),L=Z.length>0?Z.join(" "):void 0,h=import("./chunk-8k4jza38.js").then(({checkVersionOnStartup:C})=>C()),[{render:w},{createElement:f},{AppWrapper:j}]=await Promise.all([import("ink"),import("react"),import("./chunk-0hpenwph.js")]),H={...K,initialMessage:L,debug:K.debug,print:Boolean(K.print),versionCheckPromise:h};delete H._,delete H.$0,delete H.message,w(f(j,H),{patchConsole:!0,exitOnCtrlC:!1,alternateBuffer:!1})});try{await A.parse()}catch(K){console.error("Error: Parse error:",K),process.exit(1)}}if(J.main==J.module)t().catch(console.error);export{t as main};
5
+ Hint: Did you mean:`),L.showHelp(),process.exit(1)}).command("$0",!1,()=>{},async(K)=>{let Z=K._.slice(1),L=Z.length>0?Z.join(" "):void 0,h=import("./chunk-gjsbq683.js").then(({checkVersionOnStartup:C})=>C()),[{render:w},{createElement:f},{AppWrapper:j}]=await Promise.all([import("ink"),import("react"),import("./chunk-839wmh6x.js")]),H={...K,initialMessage:L,debug:K.debug,print:Boolean(K.print),versionCheckPromise:h};delete H._,delete H.$0,delete H.message,w(f(j,H),{patchConsole:!0,exitOnCtrlC:!1,alternateBuffer:!1})});try{await A.parse()}catch(K){console.error("Error: Parse error:",K),process.exit(1)}}if(J.main==J.module)t().catch(console.error);export{t as main};
@@ -1,2 +1,2 @@
1
- import{K as I}from"./chunk-n3amyjrd.js";import{Vc as M}from"./chunk-5e56atqj.js";import P from"node:path";function w(s){let a=s.replace(/\s+/g," ").trim();return a.length<=72?a:`${a.slice(0,69)}...`}function W(s){let a=s.replace(/\s+/g," ").trim();return a.length<=500?a:`${a.slice(0,497)}...`}function A(s){return`task/${s.replace(/[^a-zA-Z0-9_-]/g,"-").slice(0,40)}`}class C{static async createSessionTask(s){if(!s.prompt.trim())throw Error("Task prompt must not be blank");if(!P.isAbsolute(s.sourceProjectPath))throw Error("Task source project path must be absolute");let a=P.resolve(s.sourceProjectPath),t;try{return t=s.isolation==="worktree"?await I.enter({sessionId:s.sessionId,workspaceRoot:a,name:A(s.sessionId)}):void 0,{metadata:await M.createSessionMetadata(s.sessionId,t?.workspaceRoot??a,{title:s.title?.trim()||w(s.prompt),taskPromptSummary:W(s.prompt),taskPriority:s.taskPriority,taskKind:s.taskKind,taskDueAt:s.taskDueAt,taskDispatch:s.dispatch,taskModelId:s.dispatch?.modelId,selectedModelId:s.dispatch?.modelId,permissionMode:s.dispatch?.permissionMode,reasoningEffort:s.dispatch?.reasoningEffort,serviceTier:s.dispatch?.serviceTier,responseVerbosity:s.dispatch?.responseVerbosity,communicationStyle:s.dispatch?.communicationStyle,communicationStyleDigest:s.dispatch?.communicationStyleDigest,projectInstructionsDigest:s.dispatch?.projectInstructionsDigest,taskRetriedFrom:s.retriedFrom,taskIsolation:s.isolation,taskSourceProjectPath:a,taskWorktree:t}),taskWorktree:t}}catch(k){if(t)await I.exit({sessionId:s.sessionId,action:"remove",discardChanges:!0}).catch(()=>{return});throw k}}}var $=256,V=8388608,x=30000;class i extends Error{kind;pendingItems;pendingBytes;constructor(s,a,t){super(a,t);this.kind=s;this.name="BoundedSerialEgressError",this.pendingItems=t?.pendingItems,this.pendingBytes=t?.pendingBytes}}function T(s){s.catch(()=>{return})}class K{options;pending=[];flushWaiters=[];pendingBytes=0;nextSequence=0;completedSequence=0;draining=!1;closed=!1;failure;activeWriteAbort;activeWriteStop;activeWriteTimeout;constructor(s){this.options=s;if(this.assertPositiveInteger(s.maxPendingItems,"maxPendingItems"),this.assertPositiveInteger(s.maxPendingBytes,"maxPendingBytes"),this.assertPositiveInteger(s.writeTimeoutMs,"writeTimeoutMs"),s.signal?.addEventListener("abort",this.handleAbort,{once:!0}),s.signal?.aborted)this.handleAbort()}offer(s){if(this.closed)return{accepted:!1,error:this.failure??new i("closed","Egress is already closed")};let a;try{a=this.options.sizeOf(s)}catch(h){return this.rejectAdmission(new i("invalid_size","Egress size calculation failed",{cause:h}))}if(!Number.isSafeInteger(a)||a<0)return this.rejectAdmission(new i("invalid_size","Egress size must be a non-negative safe integer"));if(a>this.options.maxPendingBytes)return this.rejectAdmission(new i("oversized",`Egress value requires ${a} bytes; limit is ${this.options.maxPendingBytes}`));if(this.pending.length>=this.options.maxPendingItems||this.pendingBytes+a>this.options.maxPendingBytes)return this.rejectAdmission(new i("overflow",`Egress pending limit exceeded (${this.pending.length} items, ${this.pendingBytes} bytes)`));let t,k,c=new Promise((h,m)=>{t=h,k=m});return T(c),this.nextSequence+=1,this.pending.push({value:s,bytes:a,sequence:this.nextSequence,resolve:t,reject:k,completion:c}),this.pendingBytes+=a,this.startDrain(),{accepted:!0,completion:c}}flush(){if(this.failure){let c=Promise.reject(this.failure);return T(c),c}let s=this.nextSequence;if(s<=this.completedSequence)return Promise.resolve();let a,t,k=new Promise((c,h)=>{a=c,t=h});return T(k),this.flushWaiters.push({targetSequence:s,resolve:a,reject:t}),k}close(s){let a=s instanceof i?s:new i("closed","Egress was closed",{cause:s});this.fail(a)}stats(){return{closed:this.closed,pendingItems:this.pending.length,pendingBytes:this.pendingBytes}}handleAbort=()=>{this.fail(new i("aborted","Egress was aborted",{cause:this.options.signal?.reason}))};rejectAdmission(s){return this.fail(s),{accepted:!1,error:s}}startDrain(){if(this.draining||this.closed)return;this.draining=!0;let s=this.drain();T(s)}async drain(){try{while(!this.closed){let s=this.pending[0];if(!s)return;try{await this.writeOne(s.value)}catch(a){this.fail(this.normalizeWriteError(a));return}if(this.closed||this.pending[0]!==s)return;this.pending.shift(),this.pendingBytes-=s.bytes,this.completedSequence=s.sequence,s.resolve(),this.settleFlushWaiters()}}finally{if(this.draining=!1,!this.closed&&this.pending.length>0)this.startDrain()}}async writeOne(s){let a=new AbortController;this.activeWriteAbort=a;let t,k,c=new Promise((S,f)=>{k=f});T(c),this.activeWriteStop=k;let h=Promise.resolve().then(()=>this.options.write(s,a.signal));T(h);let m=new Promise((S,f)=>{t=setTimeout(()=>{let D=new i("write_timeout",`Egress write timed out after ${this.options.writeTimeoutMs}ms`);a.abort(D),f(D)},this.options.writeTimeoutMs),this.activeWriteTimeout=t});T(m);try{await Promise.race([h,m,c])}finally{if(t!==void 0)clearTimeout(t);if(this.activeWriteTimeout===t)this.activeWriteTimeout=void 0;if(this.activeWriteAbort===a)this.activeWriteAbort=void 0;if(this.activeWriteStop===k)this.activeWriteStop=void 0}}normalizeWriteError(s){if(s instanceof i)return s;return new i("write_failed","Egress write failed",{cause:s})}fail(s){if(this.closed)return;if(s.pendingItems??=this.pending.length,s.pendingBytes??=this.pendingBytes,this.closed=!0,this.failure=s,this.options.signal?.removeEventListener("abort",this.handleAbort),this.activeWriteTimeout!==void 0)clearTimeout(this.activeWriteTimeout),this.activeWriteTimeout=void 0;this.activeWriteAbort?.abort(s),this.activeWriteStop?.(s),this.activeWriteAbort=void 0,this.activeWriteStop=void 0;let a=this.pending.splice(0);this.pendingBytes=0;for(let t of a)t.reject(s);for(let t of this.flushWaiters.splice(0))t.reject(s);try{this.options.onFailure?.(s)}catch{}}settleFlushWaiters(){for(let s=0;s<this.flushWaiters.length;){let a=this.flushWaiters[s];if(a.targetSequence>this.completedSequence){s+=1;continue}this.flushWaiters.splice(s,1),a.resolve()}}assertPositiveInteger(s,a){if(!Number.isSafeInteger(s)||s<=0)throw RangeError(`${a} must be a positive safe integer`)}}
1
+ import{K as I}from"./chunk-7nqgs7ks.js";import{Vc as M}from"./chunk-ramasfqv.js";import P from"node:path";function w(s){let a=s.replace(/\s+/g," ").trim();return a.length<=72?a:`${a.slice(0,69)}...`}function W(s){let a=s.replace(/\s+/g," ").trim();return a.length<=500?a:`${a.slice(0,497)}...`}function A(s){return`task/${s.replace(/[^a-zA-Z0-9_-]/g,"-").slice(0,40)}`}class C{static async createSessionTask(s){if(!s.prompt.trim())throw Error("Task prompt must not be blank");if(!P.isAbsolute(s.sourceProjectPath))throw Error("Task source project path must be absolute");let a=P.resolve(s.sourceProjectPath),t;try{return t=s.isolation==="worktree"?await I.enter({sessionId:s.sessionId,workspaceRoot:a,name:A(s.sessionId)}):void 0,{metadata:await M.createSessionMetadata(s.sessionId,t?.workspaceRoot??a,{title:s.title?.trim()||w(s.prompt),taskPromptSummary:W(s.prompt),taskPriority:s.taskPriority,taskKind:s.taskKind,taskDueAt:s.taskDueAt,taskDispatch:s.dispatch,taskModelId:s.dispatch?.modelId,selectedModelId:s.dispatch?.modelId,permissionMode:s.dispatch?.permissionMode,reasoningEffort:s.dispatch?.reasoningEffort,serviceTier:s.dispatch?.serviceTier,responseVerbosity:s.dispatch?.responseVerbosity,communicationStyle:s.dispatch?.communicationStyle,communicationStyleDigest:s.dispatch?.communicationStyleDigest,projectInstructionsDigest:s.dispatch?.projectInstructionsDigest,taskRetriedFrom:s.retriedFrom,taskIsolation:s.isolation,taskSourceProjectPath:a,taskWorktree:t}),taskWorktree:t}}catch(k){if(t)await I.exit({sessionId:s.sessionId,action:"remove",discardChanges:!0}).catch(()=>{return});throw k}}}var $=256,V=8388608,x=30000;class i extends Error{kind;pendingItems;pendingBytes;constructor(s,a,t){super(a,t);this.kind=s;this.name="BoundedSerialEgressError",this.pendingItems=t?.pendingItems,this.pendingBytes=t?.pendingBytes}}function T(s){s.catch(()=>{return})}class K{options;pending=[];flushWaiters=[];pendingBytes=0;nextSequence=0;completedSequence=0;draining=!1;closed=!1;failure;activeWriteAbort;activeWriteStop;activeWriteTimeout;constructor(s){this.options=s;if(this.assertPositiveInteger(s.maxPendingItems,"maxPendingItems"),this.assertPositiveInteger(s.maxPendingBytes,"maxPendingBytes"),this.assertPositiveInteger(s.writeTimeoutMs,"writeTimeoutMs"),s.signal?.addEventListener("abort",this.handleAbort,{once:!0}),s.signal?.aborted)this.handleAbort()}offer(s){if(this.closed)return{accepted:!1,error:this.failure??new i("closed","Egress is already closed")};let a;try{a=this.options.sizeOf(s)}catch(h){return this.rejectAdmission(new i("invalid_size","Egress size calculation failed",{cause:h}))}if(!Number.isSafeInteger(a)||a<0)return this.rejectAdmission(new i("invalid_size","Egress size must be a non-negative safe integer"));if(a>this.options.maxPendingBytes)return this.rejectAdmission(new i("oversized",`Egress value requires ${a} bytes; limit is ${this.options.maxPendingBytes}`));if(this.pending.length>=this.options.maxPendingItems||this.pendingBytes+a>this.options.maxPendingBytes)return this.rejectAdmission(new i("overflow",`Egress pending limit exceeded (${this.pending.length} items, ${this.pendingBytes} bytes)`));let t,k,c=new Promise((h,m)=>{t=h,k=m});return T(c),this.nextSequence+=1,this.pending.push({value:s,bytes:a,sequence:this.nextSequence,resolve:t,reject:k,completion:c}),this.pendingBytes+=a,this.startDrain(),{accepted:!0,completion:c}}flush(){if(this.failure){let c=Promise.reject(this.failure);return T(c),c}let s=this.nextSequence;if(s<=this.completedSequence)return Promise.resolve();let a,t,k=new Promise((c,h)=>{a=c,t=h});return T(k),this.flushWaiters.push({targetSequence:s,resolve:a,reject:t}),k}close(s){let a=s instanceof i?s:new i("closed","Egress was closed",{cause:s});this.fail(a)}stats(){return{closed:this.closed,pendingItems:this.pending.length,pendingBytes:this.pendingBytes}}handleAbort=()=>{this.fail(new i("aborted","Egress was aborted",{cause:this.options.signal?.reason}))};rejectAdmission(s){return this.fail(s),{accepted:!1,error:s}}startDrain(){if(this.draining||this.closed)return;this.draining=!0;let s=this.drain();T(s)}async drain(){try{while(!this.closed){let s=this.pending[0];if(!s)return;try{await this.writeOne(s.value)}catch(a){this.fail(this.normalizeWriteError(a));return}if(this.closed||this.pending[0]!==s)return;this.pending.shift(),this.pendingBytes-=s.bytes,this.completedSequence=s.sequence,s.resolve(),this.settleFlushWaiters()}}finally{if(this.draining=!1,!this.closed&&this.pending.length>0)this.startDrain()}}async writeOne(s){let a=new AbortController;this.activeWriteAbort=a;let t,k,c=new Promise((S,f)=>{k=f});T(c),this.activeWriteStop=k;let h=Promise.resolve().then(()=>this.options.write(s,a.signal));T(h);let m=new Promise((S,f)=>{t=setTimeout(()=>{let D=new i("write_timeout",`Egress write timed out after ${this.options.writeTimeoutMs}ms`);a.abort(D),f(D)},this.options.writeTimeoutMs),this.activeWriteTimeout=t});T(m);try{await Promise.race([h,m,c])}finally{if(t!==void 0)clearTimeout(t);if(this.activeWriteTimeout===t)this.activeWriteTimeout=void 0;if(this.activeWriteAbort===a)this.activeWriteAbort=void 0;if(this.activeWriteStop===k)this.activeWriteStop=void 0}}normalizeWriteError(s){if(s instanceof i)return s;return new i("write_failed","Egress write failed",{cause:s})}fail(s){if(this.closed)return;if(s.pendingItems??=this.pending.length,s.pendingBytes??=this.pendingBytes,this.closed=!0,this.failure=s,this.options.signal?.removeEventListener("abort",this.handleAbort),this.activeWriteTimeout!==void 0)clearTimeout(this.activeWriteTimeout),this.activeWriteTimeout=void 0;this.activeWriteAbort?.abort(s),this.activeWriteStop?.(s),this.activeWriteAbort=void 0,this.activeWriteStop=void 0;let a=this.pending.splice(0);this.pendingBytes=0;for(let t of a)t.reject(s);for(let t of this.flushWaiters.splice(0))t.reject(s);try{this.options.onFailure?.(s)}catch{}}settleFlushWaiters(){for(let s=0;s<this.flushWaiters.length;){let a=this.flushWaiters[s];if(a.targetSequence>this.completedSequence){s+=1;continue}this.flushWaiters.splice(s,1),a.resolve()}}assertPositiveInteger(s,a){if(!Number.isSafeInteger(s)||s<=0)throw RangeError(`${a} must be a positive safe integer`)}}
2
2
  export{C as v,$ as w,V as x,x as y,i as z,K as A};
@@ -1,4 +1,4 @@
1
- import{Pb as Xt,Qb as fn,Rb as yn,Sb as En}from"./chunk-r8wbvxn7.js";import{rf as Bt}from"./chunk-je4xvy93.js";import{Af as U,Bf as en,Cf as xt,Df as mt,Ff as rn,Gf as Tn,Hf as B,If as dn,Jf as on,Kf as pn,Lf as lt,Mf as cn,Nf as un,Of as Mn,Qf as S,Tf as wn,Uf as Gt,Vf as Ut,Wf as h,Xf as Ht,wf as gt,xf as vi,yf as sn,zf as zt}from"./chunk-dj99h8ca.js";import{Cg as X,Eg as g}from"./chunk-qxn5bg5k.js";import{Og as It}from"./chunk-0141jad7.js";import{Ch as tn,Dh as nn}from"./chunk-7ffdedgc.js";import{Wh as ns}from"./chunk-h0fh3j9w.js";import{EventEmitter as bs}from"events";import Un from"node:path";function hn(t){if(t===void 0)return"undefined";if(typeof t==="string")return t;try{let i=JSON.stringify(t);return i===void 0?String(t):i}catch{return String(t)}}function An(t){let i=t;switch(t.code){case"type":return`类型错误:${t.message}`;case"required":return"缺少必需参数";case"minLength":return`字符串过短:${t.message}`;case"maxLength":return`字符串过长:${t.message}`;case"minimum":case"exclusiveMinimum":return`数值太小:${t.message}`;case"maximum":case"exclusiveMaximum":return`数值太大:${t.message}`;case"minItems":return`数组元素过少:${t.message}`;case"maxItems":return`数组元素过多:${t.message}`;case"format":return`格式错误:${t.message}`;case"enum":return`必须是枚举允许的值之一:${t.message}`;case"const":return`必须是指定的字面量值:${t.message}`;case"additionalProperties":case"unevaluatedProperties":return`包含未知参数:${t.message}`;case"anyOf":case"oneOf":return"不符合任何有效的类型定义";case"~refine":return t.message||"自定义验证失败";default:return t.message||`验证失败:${hn(i)}`}}class Jt extends Error{issues;type;constructor(t,i,n="validation_error"){super(t);this.issues=i;this.type=n;this.name="ToolValidationError"}}function Vt(t,i){let n=X(t,i);if(n.success)return n.data;let s=n.error.issues.map((r)=>({field:r.path.length>0?r.path.join("."):"root",message:An(r),value:r.value})),e=s.length===1?`参数验证失败 [${s[0].field}]: ${s[0].message}`:`参数验证失败 (${s.length} 个错误):
1
+ import{Pb as Xt,Qb as fn,Rb as yn,Sb as En}from"./chunk-r8wbvxn7.js";import{rf as Bt}from"./chunk-sa1pvsfw.js";import{Af as U,Bf as en,Cf as xt,Df as mt,Ff as rn,Gf as Tn,Hf as B,If as dn,Jf as on,Kf as pn,Lf as lt,Mf as cn,Nf as un,Of as Mn,Qf as S,Tf as wn,Uf as Gt,Vf as Ut,Wf as h,Xf as Ht,wf as gt,xf as vi,yf as sn,zf as zt}from"./chunk-ybr0g37q.js";import{Cg as X,Eg as g}from"./chunk-qxn5bg5k.js";import{Og as It}from"./chunk-0141jad7.js";import{Ch as tn,Dh as nn}from"./chunk-zby4p535.js";import{Wh as ns}from"./chunk-h0fh3j9w.js";import{EventEmitter as bs}from"events";import Un from"node:path";function hn(t){if(t===void 0)return"undefined";if(typeof t==="string")return t;try{let i=JSON.stringify(t);return i===void 0?String(t):i}catch{return String(t)}}function An(t){let i=t;switch(t.code){case"type":return`类型错误:${t.message}`;case"required":return"缺少必需参数";case"minLength":return`字符串过短:${t.message}`;case"maxLength":return`字符串过长:${t.message}`;case"minimum":case"exclusiveMinimum":return`数值太小:${t.message}`;case"maximum":case"exclusiveMaximum":return`数值太大:${t.message}`;case"minItems":return`数组元素过少:${t.message}`;case"maxItems":return`数组元素过多:${t.message}`;case"format":return`格式错误:${t.message}`;case"enum":return`必须是枚举允许的值之一:${t.message}`;case"const":return`必须是指定的字面量值:${t.message}`;case"additionalProperties":case"unevaluatedProperties":return`包含未知参数:${t.message}`;case"anyOf":case"oneOf":return"不符合任何有效的类型定义";case"~refine":return t.message||"自定义验证失败";default:return t.message||`验证失败:${hn(i)}`}}class Jt extends Error{issues;type;constructor(t,i,n="validation_error"){super(t);this.issues=i;this.type=n;this.name="ToolValidationError"}}function Vt(t,i){let n=X(t,i);if(n.success)return n.data;let s=n.error.issues.map((r)=>({field:r.path.length>0?r.path.join("."):"root",message:An(r),value:r.value})),e=s.length===1?`参数验证失败 [${s[0].field}]: ${s[0].message}`:`参数验证失败 (${s.length} 个错误):
2
2
  ${s.map((r)=>` - ${r.field}: ${r.message}`).join(`
3
3
  `)}`;throw new Jt(e,s)}function st(t){if(!t||typeof t!=="object")return;let i=t;if(i.type==="object"&&i.properties)i.required??=[],i.additionalProperties??=!1;for(let n of Object.values(i))if(Array.isArray(n))for(let s of n)st(s);else st(n)}function et(t){let i=JSON.parse(JSON.stringify(t,(n,s)=>n.startsWith("~")?void 0:s));return st(i),i}class rt{toolName;params;executeFn;descriptionFn;affectedPathsFn;constructor(t,i,n,s,e){this.toolName=t;this.params=i;this.executeFn=n;this.descriptionFn=s;this.affectedPathsFn=e}getDescription(){if(this.descriptionFn)return this.descriptionFn(this.params);return`执行工具: ${this.toolName}`}getAffectedPaths(){if(this.affectedPathsFn)return this.affectedPathsFn(this.params);return[]}async execute(t,i,n){let s={signal:t,updateOutput:i,...n};return this.executeFn(this.params,s)}}function jt(t){return{name:t.name,displayName:t.displayName,kind:t.kind,isConcurrencySafe:t.isConcurrencySafe??!1,parallelism:t.parallelism??(t.isConcurrencySafe?"shared":"exclusive"),strict:t.strict??!1,description:t.description,version:t.version||"1.0.0",category:t.category,tags:t.tags||[],getFunctionDeclaration(){let i=et(t.schema),n=t.description.short;if(t.description.long)n+=`
4
4
 
@@ -1,4 +1,4 @@
1
- import{wd as s}from"./chunk-jdb2mwbn.js";import{Pd as o}from"./chunk-yqkyhp0e.js";import{Zf as y,_f as D,ag as N,cg as j,dg as F,fg as R,jg as E,kg as _,lg as f,mg as C,og as S,pg as m,tg as c,yg as l,zg as n}from"./chunk-dj99h8ca.js";import{Ag as Y}from"./chunk-pfvgkexe.js";import{Cg as x,Eg as k,Hg as Z}from"./chunk-qxn5bg5k.js";import{Mg as X}from"./chunk-0141jad7.js";import{$g as U,Qg as h,Rg as A,Xg as P,Yg as T,_g as $,ah as G,ch as L,dh as M,fh as O,gh as I}from"./chunk-eeb2945p.js";import{oh as d}from"./chunk-b9vm7gns.js";import{promises as i}from"node:fs";import t from"node:path";var e=["systemPrompt","appendSystemPrompt","initialMessage","resumeSessionId","forkSession","allowedTools","disallowedTools","mcpConfigPaths","strictMcpConfig","model","addDirs","outputFormat","inputFormat","print","includePartialMessages","replayUserMessages","agentsConfig","settingSources"],v=new Set([...Object.keys(c),...e,"providerRequestConcurrency","providerGlobalConcurrency","providerOwnerConcurrency"]),W=k.Number({exclusiveMinimum:0}),z=k.String({minLength:1}),b=k.Array(k.String()),a=k.Object({currentModelId:k.Optional(k.String()),modelProviders:k.Optional(k.Record(z,k.Object({name:z,baseUrl:z,wireApi:Z(["openai-completions","anthropic-messages"]),apiKeyEnv:k.Optional(z)}))),models:k.Optional(k.Array(k.Object({id:z,displayName:k.Optional(z),provider:z,model:z,overrides:k.Optional(k.Object({baseUrl:k.Optional(k.String()),temperature:k.Optional(k.Number()),maxOutputTokens:k.Optional(W),timeout:k.Optional(W),streamIdleTimeout:k.Optional(k.Number({minimum:1000})),apiVersion:k.Optional(k.String()),customHeaders:k.Optional(k.Record(k.String(),k.String())),maxRetries:k.Optional(k.Integer({minimum:0})),enablePromptCaching:k.Optional(k.Boolean())})),fallbackModels:k.Optional(k.Array(k.Object({provider:z,model:z,configId:k.Optional(z)})))}))),temperature:k.Optional(k.Number()),maxOutputTokens:k.Optional(W),stream:k.Optional(k.Boolean()),topP:k.Optional(k.Number()),topK:k.Optional(k.Number()),timeout:k.Optional(W),bashForegroundHandoffMs:k.Optional(k.Union([k.Literal(0),k.Integer({minimum:y,maximum:D})])),providerForegroundRecoveryMs:k.Optional(k.Union([k.Literal(0),k.Integer({minimum:h,maximum:A})])),providerCircuitBreakerOpenMs:k.Optional(k.Union([k.Literal(0),k.Integer({minimum:P,maximum:T})])),providerRequestConcurrency:k.Optional(k.Integer({minimum:$,maximum:U})),providerGlobalConcurrency:k.Optional(k.Integer({minimum:$,maximum:G})),providerOwnerConcurrency:k.Optional(k.Integer({minimum:$,maximum:G})),providerRequestAdmissionMs:k.Optional(k.Union([k.Literal(0),k.Integer({minimum:L,maximum:M})])),providerRequestPendingBytes:k.Optional(k.Integer({minimum:O,maximum:I})),agentTeamsEnabled:k.Optional(k.Boolean()),codeTheme:k.Optional(k.String()),uiTheme:k.Optional(Z(["light","dark","system"])),language:k.Optional(k.String()),fontSize:k.Optional(W),autoSaveSessions:k.Optional(k.Boolean()),notifyBuild:k.Optional(k.Boolean()),notifyErrors:k.Optional(k.Boolean()),notifySounds:k.Optional(k.Boolean()),privacyTelemetry:k.Optional(k.Boolean()),privacyCrash:k.Optional(k.Boolean()),debug:k.Optional(k.Union([k.Boolean(),k.String()])),mcpEnabled:k.Optional(k.Boolean()),mcpServers:k.Optional(k.Record(k.String(),k.Record(k.String(),k.Unknown()))),lspServers:k.Optional(k.Record(z,k.Object({command:z,args:k.Optional(k.Array(k.String())),extensionToLanguage:k.Record(z,z),env:k.Optional(k.Record(k.String(),k.String())),initializationOptions:k.Optional(k.Unknown()),settings:k.Optional(k.Unknown()),enabled:k.Optional(k.Boolean()),priority:k.Optional(k.Integer()),startupTimeout:k.Optional(k.Integer({minimum:100})),shutdownTimeout:k.Optional(k.Integer({minimum:100})),requestTimeout:k.Optional(k.Integer({minimum:100})),diagnosticWaitTimeout:k.Optional(k.Integer({minimum:0})),maxRestarts:k.Optional(k.Integer({minimum:0,maximum:10}))}))),permissionMode:k.Optional(k.Enum(Y)),maxTurns:k.Optional(k.Integer({minimum:-1})),maxConcurrentTasks:k.Optional(k.Integer({minimum:E,maximum:_})),maxQueuedTasks:k.Optional(k.Integer({minimum:f,maximum:C})),maxQueuedTaskBytes:k.Optional(k.Integer({minimum:S,maximum:m})),maxResidentSessionRuntimes:k.Optional(k.Integer({minimum:N,maximum:j})),sessionRuntimeIdleMs:k.Optional(k.Integer({minimum:F,maximum:R})),systemPrompt:k.Optional(k.String()),appendSystemPrompt:k.Optional(k.String()),initialMessage:k.Optional(k.String()),resumeSessionId:k.Optional(k.String()),forkSession:k.Optional(k.Boolean()),allowedTools:k.Optional(k.Array(z)),disallowedTools:k.Optional(k.Array(z)),mcpConfigPaths:k.Optional(k.Array(z)),strictMcpConfig:k.Optional(k.Boolean()),model:k.Optional(z),addDirs:k.Optional(k.Array(z)),outputFormat:k.Optional(Z(["text","json","stream-json","jsonl"])),inputFormat:k.Optional(Z(["text","stream-json"])),print:k.Optional(k.Boolean()),includePartialMessages:k.Optional(k.Boolean()),replayUserMessages:k.Optional(k.Boolean()),agentsConfig:k.Optional(k.String()),settingSources:k.Optional(k.String()),permissions:k.Optional(k.Object({allow:k.Optional(b),ask:k.Optional(b),deny:k.Optional(b)})),env:k.Optional(k.Record(k.String(),k.String())),hooks:k.Optional(k.Record(k.String(),k.Unknown())),enabledPlugins:k.Optional(k.Record(z,k.Boolean())),pluginSourcePolicy:k.Optional(k.Object({restrictToAllowedSources:k.Optional(k.Boolean()),requireGitCommitSha:k.Optional(k.Boolean()),allowedGitHosts:k.Optional(k.Array(z)),allowedMarketplaces:k.Optional(k.Array(z)),allowedLocalRoots:k.Optional(k.Array(z))})),disableAllHooks:k.Optional(k.Boolean())}),g=[["systemPrompt","systemPrompt"],["appendSystemPrompt","appendSystemPrompt"],["initialMessage","initialMessage"],["resumeSessionId","sessionId"],["forkSession","forkSession"],["allowedTools","allowedTools"],["disallowedTools","disallowedTools"],["mcpConfigPaths","mcpConfig"],["strictMcpConfig","strictMcpConfig"],["model","model"],["addDirs","addDir"],["outputFormat","outputFormat"],["inputFormat","inputFormat"],["print","print"],["includePartialMessages","includePartialMessages"],["replayUserMessages","replayUserMessages"],["agentsConfig","agents"],["settingSources","settingSources"],["permissionMode","permissionMode"],["maxTurns","maxTurns"],["maxConcurrentTasks","maxConcurrentTasks"],["maxQueuedTasks","maxQueuedTasks"],["maxQueuedTaskBytes","maxQueuedTaskBytes"],["maxResidentSessionRuntimes","maxResidentSessionRuntimes"],["sessionRuntimeIdleMs","sessionRuntimeIdleMs"]];function V(q,B){let w;try{w=JSON.parse(q)}catch(H){let K=H instanceof Error?`: ${H.message}`:"";throw Error(`Invalid JSON provided to --settings (${B})${K}`)}if(!w||typeof w!=="object"||Array.isArray(w))throw Error("--settings must contain a JSON object");for(let H of Object.keys(w))if(!v.has(H))throw Error(`Unknown --settings field: ${H}`);let J=x(a,w);if(!J.success){let H=J.error.issues.map((K)=>`${K.path.join(".")||"settings"}: ${K.message}`).join("; ");throw Error(`Invalid --settings value: ${H}`)}return J.data}async function p(q){if(q===void 0)return;let B=q.trim();if(!B)throw Error("--settings requires a JSON object or file path");if(B.startsWith("{"))return V(B,"inline JSON");let w=t.resolve(X(),B),J;try{J=await i.readFile(w,"utf8")}catch(H){let K=H instanceof Error?`: ${H.message}`:"";throw Error(`Unable to read --settings file ${w}${K}`)}return V(J,w)}function u(q,B){if(!B)return;let w=B;for(let[J,H]of g){if(J==="permissionMode"&&q.yolo===!0)continue;if(q[H]===void 0&&w[J]!==void 0)q[H]=w[J]}}var Q=d("General"),Dk=(q)=>{if(q.yolo){if(q.permissionMode&&q.permissionMode!=="yolo")throw Error("Cannot use both --yolo and --permission-mode with different values");q.permissionMode="yolo"}if(Array.isArray(q.allowedTools))q.allowedTools=q.allowedTools.flatMap((B)=>B.split(",").map((w)=>w.trim()).filter((w)=>w.length>0));if(Array.isArray(q.disallowedTools))q.disallowedTools=q.disallowedTools.flatMap((B)=>B.split(",").map((w)=>w.trim()).filter((w)=>w.length>0));if(Array.isArray(q.allowedTools)&&Array.isArray(q.disallowedTools)){let B=q.allowedTools.filter((w)=>q.disallowedTools.includes(w));if(B.length>0)throw Error(`Tools cannot be both allowed and disallowed: ${B.join(", ")}`)}},hk=async(q)=>{let B=await p(typeof q.settings==="string"?q.settings:void 0);if(u(q,B),typeof q.agents==="string")s(q.agents);r(q);try{let J=await l.getInstance().initialize(B),H=n(J,q);if(o().config.actions.setConfig(H),q.debug)Q.info("[CLI] 配置已加载到 Store")}catch(w){Q.error("[CLI] [FAIL] 配置初始化失败",w instanceof Error?w.message:w),console.error(`
1
+ import{wd as s}from"./chunk-jdb2mwbn.js";import{Pd as o}from"./chunk-8zqh039s.js";import{Zf as y,_f as D,ag as N,cg as j,dg as F,fg as R,jg as E,kg as _,lg as f,mg as C,og as S,pg as m,tg as c,yg as l,zg as n}from"./chunk-ybr0g37q.js";import{Ag as Y}from"./chunk-pfvgkexe.js";import{Cg as x,Eg as k,Hg as Z}from"./chunk-qxn5bg5k.js";import{Mg as X}from"./chunk-0141jad7.js";import{$g as U,Qg as h,Rg as A,Xg as P,Yg as T,_g as $,ah as G,ch as L,dh as M,fh as O,gh as I}from"./chunk-eeb2945p.js";import{oh as d}from"./chunk-b9vm7gns.js";import{promises as i}from"node:fs";import t from"node:path";var e=["systemPrompt","appendSystemPrompt","initialMessage","resumeSessionId","forkSession","allowedTools","disallowedTools","mcpConfigPaths","strictMcpConfig","model","addDirs","outputFormat","inputFormat","print","includePartialMessages","replayUserMessages","agentsConfig","settingSources"],v=new Set([...Object.keys(c),...e,"providerRequestConcurrency","providerGlobalConcurrency","providerOwnerConcurrency"]),W=k.Number({exclusiveMinimum:0}),z=k.String({minLength:1}),b=k.Array(k.String()),a=k.Object({currentModelId:k.Optional(k.String()),modelProviders:k.Optional(k.Record(z,k.Object({name:z,baseUrl:z,wireApi:Z(["openai-completions","anthropic-messages"]),apiKeyEnv:k.Optional(z)}))),models:k.Optional(k.Array(k.Object({id:z,displayName:k.Optional(z),provider:z,model:z,overrides:k.Optional(k.Object({baseUrl:k.Optional(k.String()),temperature:k.Optional(k.Number()),maxOutputTokens:k.Optional(W),timeout:k.Optional(W),streamIdleTimeout:k.Optional(k.Number({minimum:1000})),apiVersion:k.Optional(k.String()),customHeaders:k.Optional(k.Record(k.String(),k.String())),maxRetries:k.Optional(k.Integer({minimum:0})),enablePromptCaching:k.Optional(k.Boolean())})),fallbackModels:k.Optional(k.Array(k.Object({provider:z,model:z,configId:k.Optional(z)})))}))),temperature:k.Optional(k.Number()),maxOutputTokens:k.Optional(W),stream:k.Optional(k.Boolean()),topP:k.Optional(k.Number()),topK:k.Optional(k.Number()),timeout:k.Optional(W),bashForegroundHandoffMs:k.Optional(k.Union([k.Literal(0),k.Integer({minimum:y,maximum:D})])),providerForegroundRecoveryMs:k.Optional(k.Union([k.Literal(0),k.Integer({minimum:h,maximum:A})])),providerCircuitBreakerOpenMs:k.Optional(k.Union([k.Literal(0),k.Integer({minimum:P,maximum:T})])),providerRequestConcurrency:k.Optional(k.Integer({minimum:$,maximum:U})),providerGlobalConcurrency:k.Optional(k.Integer({minimum:$,maximum:G})),providerOwnerConcurrency:k.Optional(k.Integer({minimum:$,maximum:G})),providerRequestAdmissionMs:k.Optional(k.Union([k.Literal(0),k.Integer({minimum:L,maximum:M})])),providerRequestPendingBytes:k.Optional(k.Integer({minimum:O,maximum:I})),agentTeamsEnabled:k.Optional(k.Boolean()),codeTheme:k.Optional(k.String()),uiTheme:k.Optional(Z(["light","dark","system"])),language:k.Optional(k.String()),fontSize:k.Optional(W),autoSaveSessions:k.Optional(k.Boolean()),notifyBuild:k.Optional(k.Boolean()),notifyErrors:k.Optional(k.Boolean()),notifySounds:k.Optional(k.Boolean()),privacyTelemetry:k.Optional(k.Boolean()),privacyCrash:k.Optional(k.Boolean()),debug:k.Optional(k.Union([k.Boolean(),k.String()])),mcpEnabled:k.Optional(k.Boolean()),mcpServers:k.Optional(k.Record(k.String(),k.Record(k.String(),k.Unknown()))),lspServers:k.Optional(k.Record(z,k.Object({command:z,args:k.Optional(k.Array(k.String())),extensionToLanguage:k.Record(z,z),env:k.Optional(k.Record(k.String(),k.String())),initializationOptions:k.Optional(k.Unknown()),settings:k.Optional(k.Unknown()),enabled:k.Optional(k.Boolean()),priority:k.Optional(k.Integer()),startupTimeout:k.Optional(k.Integer({minimum:100})),shutdownTimeout:k.Optional(k.Integer({minimum:100})),requestTimeout:k.Optional(k.Integer({minimum:100})),diagnosticWaitTimeout:k.Optional(k.Integer({minimum:0})),maxRestarts:k.Optional(k.Integer({minimum:0,maximum:10}))}))),permissionMode:k.Optional(k.Enum(Y)),maxTurns:k.Optional(k.Integer({minimum:-1})),maxConcurrentTasks:k.Optional(k.Integer({minimum:E,maximum:_})),maxQueuedTasks:k.Optional(k.Integer({minimum:f,maximum:C})),maxQueuedTaskBytes:k.Optional(k.Integer({minimum:S,maximum:m})),maxResidentSessionRuntimes:k.Optional(k.Integer({minimum:N,maximum:j})),sessionRuntimeIdleMs:k.Optional(k.Integer({minimum:F,maximum:R})),systemPrompt:k.Optional(k.String()),appendSystemPrompt:k.Optional(k.String()),initialMessage:k.Optional(k.String()),resumeSessionId:k.Optional(k.String()),forkSession:k.Optional(k.Boolean()),allowedTools:k.Optional(k.Array(z)),disallowedTools:k.Optional(k.Array(z)),mcpConfigPaths:k.Optional(k.Array(z)),strictMcpConfig:k.Optional(k.Boolean()),model:k.Optional(z),addDirs:k.Optional(k.Array(z)),outputFormat:k.Optional(Z(["text","json","stream-json","jsonl"])),inputFormat:k.Optional(Z(["text","stream-json"])),print:k.Optional(k.Boolean()),includePartialMessages:k.Optional(k.Boolean()),replayUserMessages:k.Optional(k.Boolean()),agentsConfig:k.Optional(k.String()),settingSources:k.Optional(k.String()),permissions:k.Optional(k.Object({allow:k.Optional(b),ask:k.Optional(b),deny:k.Optional(b)})),env:k.Optional(k.Record(k.String(),k.String())),hooks:k.Optional(k.Record(k.String(),k.Unknown())),enabledPlugins:k.Optional(k.Record(z,k.Boolean())),pluginSourcePolicy:k.Optional(k.Object({restrictToAllowedSources:k.Optional(k.Boolean()),requireGitCommitSha:k.Optional(k.Boolean()),allowedGitHosts:k.Optional(k.Array(z)),allowedMarketplaces:k.Optional(k.Array(z)),allowedLocalRoots:k.Optional(k.Array(z))})),disableAllHooks:k.Optional(k.Boolean())}),g=[["systemPrompt","systemPrompt"],["appendSystemPrompt","appendSystemPrompt"],["initialMessage","initialMessage"],["resumeSessionId","sessionId"],["forkSession","forkSession"],["allowedTools","allowedTools"],["disallowedTools","disallowedTools"],["mcpConfigPaths","mcpConfig"],["strictMcpConfig","strictMcpConfig"],["model","model"],["addDirs","addDir"],["outputFormat","outputFormat"],["inputFormat","inputFormat"],["print","print"],["includePartialMessages","includePartialMessages"],["replayUserMessages","replayUserMessages"],["agentsConfig","agents"],["settingSources","settingSources"],["permissionMode","permissionMode"],["maxTurns","maxTurns"],["maxConcurrentTasks","maxConcurrentTasks"],["maxQueuedTasks","maxQueuedTasks"],["maxQueuedTaskBytes","maxQueuedTaskBytes"],["maxResidentSessionRuntimes","maxResidentSessionRuntimes"],["sessionRuntimeIdleMs","sessionRuntimeIdleMs"]];function V(q,B){let w;try{w=JSON.parse(q)}catch(H){let K=H instanceof Error?`: ${H.message}`:"";throw Error(`Invalid JSON provided to --settings (${B})${K}`)}if(!w||typeof w!=="object"||Array.isArray(w))throw Error("--settings must contain a JSON object");for(let H of Object.keys(w))if(!v.has(H))throw Error(`Unknown --settings field: ${H}`);let J=x(a,w);if(!J.success){let H=J.error.issues.map((K)=>`${K.path.join(".")||"settings"}: ${K.message}`).join("; ");throw Error(`Invalid --settings value: ${H}`)}return J.data}async function p(q){if(q===void 0)return;let B=q.trim();if(!B)throw Error("--settings requires a JSON object or file path");if(B.startsWith("{"))return V(B,"inline JSON");let w=t.resolve(X(),B),J;try{J=await i.readFile(w,"utf8")}catch(H){let K=H instanceof Error?`: ${H.message}`:"";throw Error(`Unable to read --settings file ${w}${K}`)}return V(J,w)}function u(q,B){if(!B)return;let w=B;for(let[J,H]of g){if(J==="permissionMode"&&q.yolo===!0)continue;if(q[H]===void 0&&w[J]!==void 0)q[H]=w[J]}}var Q=d("General"),Dk=(q)=>{if(q.yolo){if(q.permissionMode&&q.permissionMode!=="yolo")throw Error("Cannot use both --yolo and --permission-mode with different values");q.permissionMode="yolo"}if(Array.isArray(q.allowedTools))q.allowedTools=q.allowedTools.flatMap((B)=>B.split(",").map((w)=>w.trim()).filter((w)=>w.length>0));if(Array.isArray(q.disallowedTools))q.disallowedTools=q.disallowedTools.flatMap((B)=>B.split(",").map((w)=>w.trim()).filter((w)=>w.length>0));if(Array.isArray(q.allowedTools)&&Array.isArray(q.disallowedTools)){let B=q.allowedTools.filter((w)=>q.disallowedTools.includes(w));if(B.length>0)throw Error(`Tools cannot be both allowed and disallowed: ${B.join(", ")}`)}},hk=async(q)=>{let B=await p(typeof q.settings==="string"?q.settings:void 0);if(u(q,B),typeof q.agents==="string")s(q.agents);r(q);try{let J=await l.getInstance().initialize(B),H=n(J,q);if(o().config.actions.setConfig(H),q.debug)Q.info("[CLI] 配置已加载到 Store")}catch(w){Q.error("[CLI] [FAIL] 配置初始化失败",w instanceof Error?w.message:w),console.error(`
2
2
  [FAIL] 配置初始化失败
3
3
  `),console.error("原因:",w instanceof Error?w.message:"未知错误"),console.error(`
4
4
  请检查:`),console.error(" 1. 配置文件格式是否正确 (~/.blade/config.json)"),console.error(" 2. 是否需要运行 blade 进行首次配置"),console.error(` 3. 配置文件权限是否正确
@@ -1,4 +1,4 @@
1
- import"./chunk-v508x7cg.js";import{yg as Q}from"./chunk-dj99h8ca.js";import"./chunk-pfvgkexe.js";import"./chunk-qxn5bg5k.js";import"./chunk-reakyamv.js";import{Og as L}from"./chunk-0141jad7.js";import"./chunk-eeb2945p.js";import"./chunk-b9vm7gns.js";import"./chunk-5nezhmnq.js";import"./chunk-h6a0nct6.js";import"./chunk-7ffdedgc.js";import"./chunk-0a0sj79a.js";import"./chunk-sj0k8cdf.js";import"./chunk-0ra945vt.js";import{Wh as F}from"./chunk-h0fh3j9w.js";var K=[22,19,0];function T(G){let A=/^v?(\d+)\.(\d+)\.(\d+)/.exec(G);if(!A)return!1;let H=A.slice(1).map(Number);for(let z=0;z<K.length;z++){let B=H[z]??0,J=K[z];if(B!==J)return B>J}return!0}var X={command:"doctor",describe:"Check the health of your Blade installation",builder:(G)=>G.option("rebuild-index",{type:"boolean",default:!1,describe:"Rebuild the SQLite session index from JSONL transcripts"}),handler:async(G)=>{if(G.rebuildIndex){console.log(`Rebuilding session index from JSONL transcripts...
2
- `);try{let{rebuildProjectionIndex:z}=await import("./chunk-h9xayrwp.js"),{SessionService:B}=await import("./chunk-3j0dhewn.js"),J=await z(B.projectionDeriverForSearch());if(J===null)console.log("[WARN] Session index unavailable (SQLite driver missing); reads fall back to JSONL scan.");else console.log(`[OK] Session index rebuilt: ${J} session(s) indexed.`)}catch(z){console.log("[FAIL] Session index rebuild failed"),console.log(` Error: ${z instanceof Error?z.message:"未知错误"}`),process.exit(1)}return}console.log(`Running Blade health check...
1
+ import"./chunk-v508x7cg.js";import{yg as Q}from"./chunk-ybr0g37q.js";import"./chunk-pfvgkexe.js";import"./chunk-qxn5bg5k.js";import"./chunk-reakyamv.js";import{Og as L}from"./chunk-0141jad7.js";import"./chunk-eeb2945p.js";import"./chunk-b9vm7gns.js";import"./chunk-5nezhmnq.js";import"./chunk-h6a0nct6.js";import"./chunk-zby4p535.js";import"./chunk-0a0sj79a.js";import"./chunk-sj0k8cdf.js";import"./chunk-0ra945vt.js";import{Wh as F}from"./chunk-h0fh3j9w.js";var K=[22,19,0];function T(G){let A=/^v?(\d+)\.(\d+)\.(\d+)/.exec(G);if(!A)return!1;let H=A.slice(1).map(Number);for(let z=0;z<K.length;z++){let B=H[z]??0,J=K[z];if(B!==J)return B>J}return!0}var X={command:"doctor",describe:"Check the health of your Blade installation",builder:(G)=>G.option("rebuild-index",{type:"boolean",default:!1,describe:"Rebuild the SQLite session index from JSONL transcripts"}),handler:async(G)=>{if(G.rebuildIndex){console.log(`Rebuilding session index from JSONL transcripts...
2
+ `);try{let{rebuildProjectionIndex:z}=await import("./chunk-h9xayrwp.js"),{SessionService:B}=await import("./chunk-mjfgsz1s.js"),J=await z(B.projectionDeriverForSearch());if(J===null)console.log("[WARN] Session index unavailable (SQLite driver missing); reads fall back to JSONL scan.");else console.log(`[OK] Session index rebuilt: ${J} session(s) indexed.`)}catch(z){console.log("[FAIL] Session index rebuild failed"),console.log(` Error: ${z instanceof Error?z.message:"未知错误"}`),process.exit(1)}return}console.log(`Running Blade health check...
3
3
  `);let A=0;try{await Q.getInstance().initialize(),console.log("[OK] Configuration: OK")}catch(z){console.log("[FAIL] Configuration: FAILED"),console.log(` Error: ${z instanceof Error?z.message:"未知错误"}`),A++}let H=process.version;if(T(H))console.log(`[OK] Node.js version: ${H}`);else console.log(`[WARN] Node.js version: ${H} (required: >=22.19.0)`),A++;try{let z=await import("fs/promises"),B=L();await z.access(B,(await import("fs")).constants.R_OK|(await import("fs")).constants.W_OK),console.log("[OK] File system permissions: OK")}catch(z){console.log("[FAIL] File system permissions: FAILED"),console.log(" Error: Cannot read/write in current directory"),A++}try{await import("ink"),console.log("[OK] Dependencies: OK")}catch(z){console.log("[FAIL] Dependencies: FAILED"),console.log(" Error: Missing required dependencies"),A++}if(console.log(`
4
4
  Health Check Summary:`),A===0)console.log("All checks passed! Blade is ready to use.");else console.log(`Warning: Found ${A} issue(s). Please resolve them for optimal performance.`),process.exit(1)}};export{T as isSupportedNodeVersion,X as doctorCommands};
@@ -1 +1 @@
1
- import{a as o}from"./chunk-phgcgfv1.js";import"./chunk-7ffdedgc.js";import"./chunk-h0fh3j9w.js";import{execSync as r}from"child_process";var l={command:"update",describe:"Check for updates and install if available",handler:async()=>{console.log("Checking for updates...");try{let e=await o(!0);if(console.log(`Current version: ${e.currentVersion}`),e.error){console.log(`Warning: ${e.error}`);return}if(e.latestVersion)console.log(`Latest version: ${e.latestVersion}`);if(e.hasUpdate&&e.latestVersion){console.log(""),console.log(`\x1B[33mUpdate available: ${e.currentVersion} -> ${e.latestVersion}\x1B[0m`),console.log(""),console.log("Updating...");try{r("npm install -g blade-code@latest --registry https://registry.npmjs.org",{stdio:"inherit"}),console.log(""),console.log("Update complete!")}catch(t){console.error("Error: Update failed. Please run manually:"),console.error(" npm install -g blade-code@latest"),process.exit(1)}}else console.log("You are running the latest version of Blade")}catch(e){console.error(`Error: Failed to check for updates: ${e instanceof Error?e.message:"未知错误"}`),process.exit(1)}}};export{l as updateCommands};
1
+ import{a as o}from"./chunk-gdyw5ns9.js";import"./chunk-zby4p535.js";import"./chunk-h0fh3j9w.js";import{execSync as r}from"child_process";var l={command:"update",describe:"Check for updates and install if available",handler:async()=>{console.log("Checking for updates...");try{let e=await o(!0);if(console.log(`Current version: ${e.currentVersion}`),e.error){console.log(`Warning: ${e.error}`);return}if(e.latestVersion)console.log(`Latest version: ${e.latestVersion}`);if(e.hasUpdate&&e.latestVersion){console.log(""),console.log(`\x1B[33mUpdate available: ${e.currentVersion} -> ${e.latestVersion}\x1B[0m`),console.log(""),console.log("Updating...");try{r("npm install -g blade-code@latest --registry https://registry.npmjs.org",{stdio:"inherit"}),console.log(""),console.log("Update complete!")}catch(t){console.error("Error: Update failed. Please run manually:"),console.error(" npm install -g blade-code@latest"),process.exit(1)}}else console.log("You are running the latest version of Blade")}catch(e){console.error(`Error: Failed to check for updates: ${e instanceof Error?e.message:"未知错误"}`),process.exit(1)}}};export{l as updateCommands};
@@ -1 +1 @@
1
- import{$d as n,Od as a,Pd as b,Qd as c,Rd as d,Sd as e,Td as f,Ud as g,Vd as h,Wd as i,Xd as j,Yd as k,Zd as l,_d as m,ae as o,be as p,ce as q}from"./chunk-yqkyhp0e.js";import"./chunk-v508x7cg.js";import"./chunk-c9e0fbyh.js";import"./chunk-dj99h8ca.js";import"./chunk-pfvgkexe.js";import"./chunk-qxn5bg5k.js";import"./chunk-reakyamv.js";import"./chunk-0141jad7.js";import"./chunk-eeb2945p.js";import"./chunk-b9vm7gns.js";import"./chunk-5nezhmnq.js";import"./chunk-h6a0nct6.js";import"./chunk-7ffdedgc.js";import"./chunk-0a0sj79a.js";import"./chunk-sj0k8cdf.js";import"./chunk-0ra945vt.js";import"./chunk-h0fh3j9w.js";export{a as vanillaStore,c as sessionActions,l as getThinkingModeEnabled,b as getState,n as getServiceTier,o as getResponseVerbosity,m as getReasoningEffort,j as getModelById,e as getMessages,k as getMcpServers,i as getCurrentModel,f as getConfig,p as getCommunicationStyle,h as getAllModels,g as ensureStoreInitialized,q as configActions,d as appActions};
1
+ import{$d as n,Od as a,Pd as b,Qd as c,Rd as d,Sd as e,Td as f,Ud as g,Vd as h,Wd as i,Xd as j,Yd as k,Zd as l,_d as m,ae as o,be as p,ce as q}from"./chunk-8zqh039s.js";import"./chunk-v508x7cg.js";import"./chunk-c9e0fbyh.js";import"./chunk-ybr0g37q.js";import"./chunk-pfvgkexe.js";import"./chunk-qxn5bg5k.js";import"./chunk-reakyamv.js";import"./chunk-0141jad7.js";import"./chunk-eeb2945p.js";import"./chunk-b9vm7gns.js";import"./chunk-5nezhmnq.js";import"./chunk-h6a0nct6.js";import"./chunk-zby4p535.js";import"./chunk-0a0sj79a.js";import"./chunk-sj0k8cdf.js";import"./chunk-0ra945vt.js";import"./chunk-h0fh3j9w.js";export{a as vanillaStore,c as sessionActions,l as getThinkingModeEnabled,b as getState,n as getServiceTier,o as getResponseVerbosity,m as getReasoningEffort,j as getModelById,e as getMessages,k as getMcpServers,i as getCurrentModel,f as getConfig,p as getCommunicationStyle,h as getAllModels,g as ensureStoreInitialized,q as configActions,d as appActions};
@@ -1 +1 @@
1
- import{Bh as a,Ch as b,Dh as c,Eh as d,Fh as e,Gh as f}from"./chunk-7ffdedgc.js";import"./chunk-h0fh3j9w.js";export{b as getVersion,c as getPackageName,a as getPackageInfo,e as getFormattedVersion,d as getDescription,f as getCopyright};
1
+ import{Bh as a,Ch as b,Dh as c,Eh as d,Fh as e,Gh as f}from"./chunk-zby4p535.js";import"./chunk-h0fh3j9w.js";export{b as getVersion,c as getPackageName,a as getPackageInfo,e as getFormattedVersion,d as getDescription,f as getCopyright};
@@ -1 +1 @@
1
- import{Ab as k,Hb as l,Ib as m,Jb as n,Kb as o,Mb as p,Nb as q,Ob as r,mb as a,nb as b,pb as c,tb as d,ub as e,vb as f,wb as g,xb as h,yb as i,zb as j}from"./chunk-0cbr2gs7.js";import"./chunk-r8wbvxn7.js";import"./chunk-5e56atqj.js";import"./chunk-skw3b17a.js";import"./chunk-jwx10h5z.js";import"./chunk-c9e0fbyh.js";import"./chunk-seamt0j3.js";import"./chunk-mygw13zd.js";import"./chunk-jzvbjn6e.js";import"./chunk-7nx0pzfk.js";import"./chunk-je4xvy93.js";import"./chunk-zkhb55jz.js";import"./chunk-pfvgkexe.js";import"./chunk-qxn5bg5k.js";import"./chunk-reakyamv.js";import"./chunk-0141jad7.js";import"./chunk-eeb2945p.js";import"./chunk-b9vm7gns.js";import"./chunk-5nezhmnq.js";import"./chunk-h6a0nct6.js";import"./chunk-7ffdedgc.js";import"./chunk-sj0k8cdf.js";import"./chunk-0ra945vt.js";import"./chunk-h0fh3j9w.js";export{g as saveUserMessage,i as saveToolUse,j as saveToolResult,k as saveCompaction,h as saveAssistantMessage,d as isRootSystemPrompt,m as handleTaskListUpdate,n as handleSkillActivation,o as extractModelSwitch,r as executeLoopGenerator,f as drainLoop,c as checkStopHook,a as checkOutputRecovery,b as checkIncompleteIntent,q as checkAndCompactInLoop,p as applyToolDomainEffects,l as StreamingToolExecutor,e as ConversationState};
1
+ import{Ab as k,Hb as l,Ib as m,Jb as n,Kb as o,Mb as p,Nb as q,Ob as r,mb as a,nb as b,pb as c,tb as d,ub as e,vb as f,wb as g,xb as h,yb as i,zb as j}from"./chunk-wvprjxna.js";import"./chunk-r8wbvxn7.js";import"./chunk-ramasfqv.js";import"./chunk-skw3b17a.js";import"./chunk-jwx10h5z.js";import"./chunk-c9e0fbyh.js";import"./chunk-seamt0j3.js";import"./chunk-mygw13zd.js";import"./chunk-jzvbjn6e.js";import"./chunk-7nx0pzfk.js";import"./chunk-sa1pvsfw.js";import"./chunk-zkhb55jz.js";import"./chunk-pfvgkexe.js";import"./chunk-qxn5bg5k.js";import"./chunk-reakyamv.js";import"./chunk-0141jad7.js";import"./chunk-eeb2945p.js";import"./chunk-b9vm7gns.js";import"./chunk-5nezhmnq.js";import"./chunk-h6a0nct6.js";import"./chunk-zby4p535.js";import"./chunk-sj0k8cdf.js";import"./chunk-0ra945vt.js";import"./chunk-h0fh3j9w.js";export{g as saveUserMessage,i as saveToolUse,j as saveToolResult,k as saveCompaction,h as saveAssistantMessage,d as isRootSystemPrompt,m as handleTaskListUpdate,n as handleSkillActivation,o as extractModelSwitch,r as executeLoopGenerator,f as drainLoop,c as checkStopHook,a as checkOutputRecovery,b as checkIncompleteIntent,q as checkAndCompactInLoop,p as applyToolDomainEffects,l as StreamingToolExecutor,e as ConversationState};
@@ -0,0 +1 @@
1
+ import{rd as a,sd as b}from"./chunk-amt7zcwa.js";import"./chunk-zby4p535.js";import"./chunk-h0fh3j9w.js";export{a as globalOptions,b as cliConfig};
@@ -1,2 +1,2 @@
1
- import{yg as F}from"./chunk-dj99h8ca.js";import{th as D,uh as E}from"./chunk-5nezhmnq.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)}}
1
+ import{yg as F}from"./chunk-ybr0g37q.js";import{th as D,uh as E}from"./chunk-5nezhmnq.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 ve,Q as we,T as xe};
@@ -1,4 +1,4 @@
1
- import{ra as R,sa as m0,xa as Q3,ya as h9,za as u0}from"./chunk-b86m3bpv.js";import{Aa as W6,Ca as c3,Ea as l3,Fa as QZ,Xa as i3}from"./chunk-ky9q53m7.js";import{$a as a$,Bb as v5,Cb as aJ,Db as FJ,Fb as Z2,Gb as fJ,Lb as Z7,Ob as J7,Ya as b$,Za as F1,_a as b9,ab as H9,bb as j9,cb as F9,db as M9,eb as C9,fb as B7,jb as W0,lb as $5,ob as O5,qb as K4,rb as F5,sb as D5,ub as Q8,vb as Q$}from"./chunk-0cbr2gs7.js";import{Cc as GZ,Dc as d0,Ec as D1,Fc as TJ,Gc as RJ,Jc as Z3,Nc as $7,Sc as PJ,Tc as SJ,Ub as O0,Vb as f1,Vc as r,Wb as m$,Xb as N2,Yb as KZ,Zb as K5,_b as G5,rc as P5,sc as L0,tc as $$}from"./chunk-5e56atqj.js";import{Wc as x,Xc as E7,Yc as w7,Zc as t$}from"./chunk-skw3b17a.js";import{_c as n3,bd as a3,kd as o3,qd as t3}from"./chunk-jwx10h5z.js";import{Bd as J8,Cd as $8}from"./chunk-h3w814js.js";import{Od as B5,Pd as H0,Qd as f,Td as B0,Ud as Z5,Vd as B1,Wd as P$,Xd as E4,Yd as i$,Zd as s9,ce as G1}from"./chunk-yqkyhp0e.js";import{de as $1}from"./chunk-c9e0fbyh.js";import{ie as e9,je as o9,oe as dJ,pe as J5}from"./chunk-seamt0j3.js";import{re as P0,se as g$}from"./chunk-33bpwkyk.js";import{te as tJ}from"./chunk-mygw13zd.js";import{ve as bJ,we as AJ,xe as jJ}from"./chunk-b948f9w9.js";import{Ae as z5,Ce as V5,De as H5,Ee as I$,Fe as M7,He as K$,Ie as Z$,Je as a0,Ke as Z6,Le as H1,Me as k5,Ne as W1,Oe as X1,Pe as CJ,Te as g4,Ve as S0,We as U$,Ye as Y5,Ze as kJ,ye as Q5,ze as U5}from"./chunk-xrt796d6.js";import{$e as f$,bf as X$,cf as c2,df as NZ,ef as bZ,ff as g1,gf as AZ,hf as jZ,if as M2}from"./chunk-jzvbjn6e.js";import{jf as B3,lf as MJ,mf as R5,nf as Y8}from"./chunk-7nx0pzfk.js";import{pf as $Z,rf as j0}from"./chunk-je4xvy93.js";import{sf as F2,tf as HZ,uf as D2,vf as U1}from"./chunk-zkhb55jz.js";import{$f as O9,Cf as dZ,Ef as a4,Jf as X3,Nf as pZ,Pf as LJ,Rf as w9,Sf as N9,Yf as s$,jg as u9,kg as m9,lg as d9,mg as p9,ng as q4,og as c9,pg as R$,qg as l9,rg as i9,sg as r9,ug as PZ,wg as vJ,xf as mZ,xg as NJ,yg as Q0}from"./chunk-dj99h8ca.js";import{Bg as N$}from"./chunk-pfvgkexe.js";import{Cg as j2,Dg as t5,Eg as O,Fg as S7,Gg as S,Hg as m}from"./chunk-qxn5bg5k.js";import{Jg as GJ,Kg as OJ}from"./chunk-reakyamv.js";import{Mg as f2,Og as T}from"./chunk-0141jad7.js";import{oh as l}from"./chunk-b9vm7gns.js";import{th as EJ,uh as wJ}from"./chunk-5nezhmnq.js";import{vh as q3,yh as F3}from"./chunk-h6a0nct6.js";import{Ch as N3}from"./chunk-7ffdedgc.js";import{Ih as yJ,Jh as v0}from"./chunk-0a0sj79a.js";import{Nh as w2,Ph as C$,Rh as qJ,Sh as wZ,Uh as e}from"./chunk-0ra945vt.js";import{Wh as t0}from"./chunk-h0fh3j9w.js";import{randomUUID as a5}from"crypto";import{randomUUID as BY}from"node:crypto";var KY=String.raw`
1
+ import{ra as R,sa as m0,xa as Q3,ya as h9,za as u0}from"./chunk-2avf4cje.js";import{Aa as W6,Ca as c3,Ea as l3,Fa as QZ,Xa as i3}from"./chunk-ky9q53m7.js";import{$a as a$,Bb as v5,Cb as aJ,Db as FJ,Fb as Z2,Gb as fJ,Lb as Z7,Ob as J7,Ya as b$,Za as F1,_a as b9,ab as H9,bb as j9,cb as F9,db as M9,eb as C9,fb as B7,jb as W0,lb as $5,ob as O5,qb as K4,rb as F5,sb as D5,ub as Q8,vb as Q$}from"./chunk-wvprjxna.js";import{Cc as GZ,Dc as d0,Ec as D1,Fc as TJ,Gc as RJ,Jc as Z3,Nc as $7,Sc as PJ,Tc as SJ,Ub as O0,Vb as f1,Vc as r,Wb as m$,Xb as N2,Yb as KZ,Zb as K5,_b as G5,rc as P5,sc as L0,tc as $$}from"./chunk-ramasfqv.js";import{Wc as x,Xc as E7,Yc as w7,Zc as t$}from"./chunk-skw3b17a.js";import{_c as n3,bd as a3,kd as o3,qd as t3}from"./chunk-jwx10h5z.js";import{Bd as J8,Cd as $8}from"./chunk-h3w814js.js";import{Od as B5,Pd as H0,Qd as f,Td as B0,Ud as Z5,Vd as B1,Wd as P$,Xd as E4,Yd as i$,Zd as s9,ce as G1}from"./chunk-8zqh039s.js";import{de as $1}from"./chunk-c9e0fbyh.js";import{ie as e9,je as o9,oe as dJ,pe as J5}from"./chunk-seamt0j3.js";import{re as P0,se as g$}from"./chunk-33bpwkyk.js";import{te as tJ}from"./chunk-mygw13zd.js";import{ve as bJ,we as AJ,xe as jJ}from"./chunk-7myqyckn.js";import{Ae as z5,Ce as V5,De as H5,Ee as I$,Fe as M7,He as K$,Ie as Z$,Je as a0,Ke as Z6,Le as H1,Me as k5,Ne as W1,Oe as X1,Pe as CJ,Te as g4,Ve as S0,We as U$,Ye as Y5,Ze as kJ,ye as Q5,ze as U5}from"./chunk-reb7gmf8.js";import{$e as f$,bf as X$,cf as c2,df as NZ,ef as bZ,ff as g1,gf as AZ,hf as jZ,if as M2}from"./chunk-jzvbjn6e.js";import{jf as B3,lf as MJ,mf as R5,nf as Y8}from"./chunk-7nx0pzfk.js";import{pf as $Z,rf as j0}from"./chunk-sa1pvsfw.js";import{sf as F2,tf as HZ,uf as D2,vf as U1}from"./chunk-zkhb55jz.js";import{$f as O9,Cf as dZ,Ef as a4,Jf as X3,Nf as pZ,Pf as LJ,Rf as w9,Sf as N9,Yf as s$,jg as u9,kg as m9,lg as d9,mg as p9,ng as q4,og as c9,pg as R$,qg as l9,rg as i9,sg as r9,ug as PZ,wg as vJ,xf as mZ,xg as NJ,yg as Q0}from"./chunk-ybr0g37q.js";import{Bg as N$}from"./chunk-pfvgkexe.js";import{Cg as j2,Dg as t5,Eg as O,Fg as S7,Gg as S,Hg as m}from"./chunk-qxn5bg5k.js";import{Jg as GJ,Kg as OJ}from"./chunk-reakyamv.js";import{Mg as f2,Og as T}from"./chunk-0141jad7.js";import{oh as l}from"./chunk-b9vm7gns.js";import{th as EJ,uh as wJ}from"./chunk-5nezhmnq.js";import{vh as q3,yh as F3}from"./chunk-h6a0nct6.js";import{Ch as N3}from"./chunk-zby4p535.js";import{Ih as yJ,Jh as v0}from"./chunk-0a0sj79a.js";import{Nh as w2,Ph as C$,Rh as qJ,Sh as wZ,Uh as e}from"./chunk-0ra945vt.js";import{Wh as t0}from"./chunk-h0fh3j9w.js";import{randomUUID as a5}from"crypto";import{randomUUID as BY}from"node:crypto";var KY=String.raw`
2
2
  const { spawn } = require('node:child_process');
3
3
  const [ownerPidValue, command, ...args] = process.argv.slice(1);
4
4
  const ownerPid = Number(ownerPidValue);
@@ -816,7 +816,7 @@ ${n}
816
816
  </approved-plan>
817
817
 
818
818
  IMPORTANT: Execute according to the approved plan above. Follow the steps exactly as specified.`;if(typeof G==="string")s=G+y;else s=[...G,{type:"text",text:y}]}P=yield*this.runLoop(s,F,{...C,inputMessageId:void 0})}if(!this.sessionRuntime||!b)return P;let k=await this.sessionRuntime.recordGoalProgress({tokens:P.metadata?.tokensUsed??0,elapsedMs:P.metadata?.duration??0,prematureStopPattern:P.success?E9(P.finalMessage):void 0});if(k)yield{kind:"goal_updated",goal:k};if(!P.success||F.signal?.aborted){if(k=await this.sessionRuntime.pauseActiveGoal(F.signal?.aborted?"goal paused after user cancellation":P.error?.message??"goal paused after turn failure"),k)yield{kind:"goal_updated",goal:k}}if(P.success&&!F.signal?.aborted&&w<20)await this.sessionRuntime.waitForBackgroundSubagentFollowUp(b,F.signal);let a=P.success&&!F.signal?.aborted&&w<20,g=uQ(P);if(N=await this.sessionRuntime.finishTurn(b,{continuePending:a,...g?{acknowledgeInput:!0}:{},outcome:P.success&&!F.signal?.aborted?{status:"completed",turnsCount:P.metadata?.turnsCount??0,toolCallsCount:P.metadata?.toolCallsCount??0,durationMs:P.metadata?.duration??0}:{status:"aborted",cause:F.signal?.aborted?"cancelled":"failed",turnsCount:P.metadata?.turnsCount??0,toolCallsCount:P.metadata?.toolCallsCount??0,durationMs:P.metadata?.duration??0}}),N){w++,B=!0,D=!1,L=null,G="",q=void 0,_=M(),yield{kind:"follow_up_started",queued:this.sessionRuntime.getPendingSteeringCount(),recovered:this.sessionRuntime.getRecoveredSteeringCount(),messages:A()};continue}if(!P.success||F.signal?.aborted)return P;if(k=await this.sessionRuntime.getGoal(),!k||k.status!=="active"&&k.status!=="verifying")return P;if(L=await this.sessionRuntime.beginGoalContinuation(),!L)return P;N=await this.sessionRuntime.beginTurn("goal"),B=!1,D=!0,G=C6(L),q=void 0,_=void 0,yield{kind:"goal_continuation_started",goal:L,continuation:L.continuationCount,...L.prematureStop?{prematureStopPattern:L.prematureStop.pattern,prematureStopCount:L.prematureStop.consecutiveCount}:{}},yield{kind:"goal_updated",goal:L}}}finally{if(this.sessionRuntime&&N)await this.sessionRuntime.finishTurn(N)}}let V=typeof U==="string"?U:U.filter((G)=>G.type==="text").map((G)=>G.text).join(`
819
- `),H={id:this.generateTaskId(),type:"simple",prompt:V};return{success:!0,finalMessage:(await this.executeTask(H)).content,metadata:{turnsCount:1,toolCallsCount:0,duration:0}}}async chat($,Z,J){let{drainLoop:Y}=await import("./chunk-hchn7baz.js");return Y(this.chatStream($,Z,J))}async*runPlanLoop($,Z,J){p.debug("Processing Plan mode message...");let{prompt:Y}=await A$({projectPath:Z.workspaceRoot||T(),mode:"plan",includeEnvironment:!0,environmentOptions:Z2,language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),projectInstructionSourcePath:this.sessionRuntime?.projectRoot}),W;if(typeof $==="string")W=d1($);else{let X=$.filter((Q)=>Q.type==="text");if(X.length>0){let Q=X[0];W=$.map((U)=>U===Q?{type:"text",text:d1(Q.text)}:U)}else W=[{type:"text",text:d1("")},...$]}return yield*this.executeLoop(W,Z,J,Y)}async*runLoop($,Z,J){p.debug("Processing enhanced chat message...");let Y=Z.systemPrompt??await this.buildSystemPromptOnDemand(Z.workspaceRoot||T());return yield*this.executeLoop($,Z,J,Y)}async buildSystemPromptOnDemand($){let Z=this.runtimeOptions.systemPrompt,J=this.runtimeOptions.appendSystemPrompt;return(await A$({projectPath:$,replaceDefault:Z,append:J,includeEnvironment:!0,environmentOptions:Z2,language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),projectInstructionSourcePath:this.sessionRuntime?.projectRoot})).prompt}executeLoop($,Z,J,Y){if(!this.isInitialized)throw Error("Agent未初始化");let W=this.buildLoopDependencies();return J7(W,$,Z,J,Y)}takeStartupAdoptedToolResultEvents(){return(this.sessionRuntime?.takeStartupAdoptedToolResults()??[]).flatMap(({call:Z,result:J})=>{let Y={id:Z.toolCallId,type:"function",function:{name:Z.toolName,arguments:JSON.stringify(Z.input)}},W=J.metadata&&typeof J.metadata==="object"&&!Array.isArray(J.metadata)?J.metadata:void 0,X=J.error===void 0,Q=J.output,U={success:X,llmContent:typeof Q==="string"||Q!==null&&typeof Q==="object"?Q:Q===null?J.error?`Subagent execution failed: ${J.error}.`:"":String(Q),...J.error?{error:{type:"execution_error",message:J.error}}:{},...W?{metadata:W}:{}},z=[{kind:"tool_result",toolCall:Y,result:U}],V=Z7(Y,U);if(V)z.push(V);return z})}buildLoopDependencies(){return{chatService:this.chatService,toolExecutor:this.toolExecutor,executionEngine:this.executionEngine,config:this.config,runtimeOptions:this.runtimeOptions,currentModelMaxContextTokens:this.currentModelMaxContextTokens,activeSkillContext:this.activeSkillContext,onSkillActivated:($)=>{this.activeSkillContext=$,p.debug(`Skill "${$.skillName}" activated`+($.allowedTools?` with allowed tools: ${$.allowedTools.join(", ")}`:""))},onModelSwitch:($)=>this.switchModelIfNeeded($),applySkillToolRestrictions:($)=>this.applySkillToolRestrictions($),staticProjectRules:this.sessionRuntime?.getStaticProjectRules(),hydrateProjectRules:this.sessionRuntime?($)=>this.sessionRuntime.hydrateProjectRules($):void 0,resolveContextualProjectRules:this.sessionRuntime?($,Z,J,Y)=>this.sessionRuntime.resolveContextualProjectRules($,Z,J,Y):void 0}}async chatWithSystem($,Z){if(!this.isInitialized)throw Error("Agent未初始化");let J=[{role:"system",content:$},{role:"user",content:Z}];return(await this.chatService.chat(J)).content}getActiveTask(){return this.activeTask}getChatService(){return this.chatService}getContextManager(){return this.executionEngine?.getContextManager()}getStats(){return{initialized:this.isInitialized,activeTask:this.activeTask?.id,components:{chatService:this.chatService?"ready":"not_loaded",executionEngine:this.executionEngine?"ready":"not_loaded"}}}getAvailableTools(){return this.toolExecutor?this.toolExecutor.getRegistry().getAll():[]}getToolRegistry(){return this.toolExecutor.getRegistry()}applyToolWhitelist($){let Z=this.toolExecutor.getRegistry(),Y=Z.getAll().filter((W)=>!$.includes(W.name));for(let W of Y)Z.unregister(W.name);p.debug(`Applied tool whitelist: ${$.join(", ")} (removed ${Y.length} tools)`)}applyToolBlacklist($){let Z=this.toolExecutor.getRegistry(),J=new Set($);for(let Y of Z.getAll())if(J.has(Y.name))Z.unregister(Y.name);p.debug(`Applied tool blacklist: ${$.join(", ")}`)}getToolStats(){let $=this.getAvailableTools(),Z=new Map;return $.forEach((J)=>{let Y=Z.get(J.kind)||0;Z.set(J.kind,Y+1)}),{totalTools:$.length,toolsByKind:Object.fromEntries(Z),toolNames:$.map((J)=>J.name)}}async destroy(){if(this.destroyPromise)return this.destroyPromise;return this.destroyPromise=(async()=>{this.log("销毁Agent..."),await this.activeOperations.shutdown("agent-destroy");try{await this.legacyMcpRegistry?.disconnectAll(),this.legacyMcpRegistry=void 0,this.log("Agent已销毁")}catch($){throw this.error("Agent销毁失败",$),$}finally{this.toolExecutor.dispose(),this.isInitialized=!1}})(),this.destroyPromise}syncRuntimeState(){if(!this.sessionRuntime)return;this.chatService=this.sessionRuntime.getChatService(),this.executionEngine=this.sessionRuntime.getExecutionEngine(),this.attachmentCollector=this.sessionRuntime.getAttachmentCollector(),this.currentModelId=this.sessionRuntime.getCurrentModelId(),this.currentModelMaxContextTokens=this.sessionRuntime.getCurrentModelMaxContextTokens()}generateTaskId(){return`task_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}log($,Z){p.debug(`[MainAgent] ${$}`,Z||"")}error($,Z){p.error(`[MainAgent] ${$}`,Z||"")}async initializeSystemPrompt(){try{let $=this.runtimeOptions.systemPrompt,Z=this.runtimeOptions.appendSystemPrompt,J=await A$({projectPath:this.sessionRuntime?.workspaceRoot??T(),replaceDefault:$,append:Z,includeEnvironment:!1,language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),projectInstructionSourcePath:this.sessionRuntime?.projectRoot});if(J.prompt)this.log("系统提示配置验证成功"),p.debug(`[SystemPrompt] 可用来源: ${J.sources.filter((Y)=>Y.loaded).map((Y)=>Y.name).join(", ")}`)}catch($){this.error("系统提示配置验证失败",$)}}async registerBuiltinTools(){try{let $=await W5({sessionId:"default",configDir:e(),workspaceRoot:T(),resourceRoot:T(),agentResources:this.agentResources});p.debug(`Registering ${$.length} builtin tools...`),this.toolExecutor.getRegistry().registerAll($);let Z=this.toolExecutor.getRegistry().getAll().length;p.debug(`Builtin tools registered: ${Z} tools`),p.debug(`[Tools] ${this.toolExecutor.getRegistry().getAll().map((J)=>J.name).join(", ")}`),await this.registerMcpTools()}catch($){throw p.error("Failed to register builtin tools:",$),$}}async registerMcpTools(){try{let $=await k2({workspaceRoot:T(),storeServers:this.config.mcpServers??{},cliConfigs:this.runtimeOptions.mcpConfig,strictCliConfig:this.runtimeOptions.strictMcpConfig});if(Object.keys($).length===0){p.debug("No MCP servers configured");return}let Z=u0.createIsolated({artifactWriter:new m1(`legacy-${gQ()}`)});this.legacyMcpRegistry=Z;for(let[X,Q]of Object.entries($))try{p.debug(`Connecting to MCP server: ${X}`),await Z.registerServer(X,Q),p.debug(`MCP server "${X}" connected`)}catch(U){p.warn(`Warning: MCP server "${X}" connection failed:`,U)}let J=this.toolExecutor.getRegistry();J.setMcpCatalogBarrier(()=>Z.waitForCatalogIdle());let Y=Z.getCatalogSnapshot();J.replaceMcpTools(Y.tools),J.registerAll(r1(Z));let W=Z.getInstructionsSnapshot();if(J.queueMcpInstructionsChange({revision:W.revision,reason:"snapshot",replace:!0,instructions:W.instructions,removed:[]}),Z.on("catalogChanged",(X)=>{J.replaceMcpTools(X.tools,X)}),Z.on("contentCatalogChanged",(X)=>{J.queueMcpContentChange(X)}),Z.on("resourceUpdated",(X)=>{J.queueMcpResourceUpdated(X)}),Z.on("connectionLifecycleChanged",(X)=>{J.queueMcpConnectionChange(X)}),Z.on("log",(X)=>{J.queueMcpLog(X)}),Z.on("instructionsChanged",(X)=>{J.queueMcpInstructionsChange({revision:X.revision,reason:X.reason,replace:!1,instructions:X.action==="added"&&X.instruction?[{serverName:X.serverName,...X.instruction}]:[],removed:X.action==="removed"?[X.serverName]:[]})}),Y.tools.length>0)p.debug(`Registered ${Y.tools.length} MCP tools`),p.debug(`[MCP Tools] ${Y.tools.map((X)=>X.name).join(", ")}`)}catch($){p.warn("Failed to register MCP tools:",$)}}async loadSubagents(){let $=await S0(T());if(this.agentResources=Y5($),this.subagentRegistry=this.agentResources.subagents,this.runtimeOptions.agents?.length)this.subagentRegistry.applyOverrides(this.runtimeOptions.agents);let Z=this.subagentRegistry.getAllNames().length;if(Z>0)p.debug(`Loaded ${Z} subagents: ${this.subagentRegistry.getAllNames().join(", ")}`);else p.debug("No subagents configured")}applySkillToolRestrictions($){if(!this.activeSkillContext?.allowedTools)return $;let Z=this.activeSkillContext.allowedTools;p.debug(`Applying Skill tool restrictions: ${Z.join(", ")}`);let J=$.filter((Y)=>{return Z.some((W)=>{if(W===Y.name)return!0;let X=W.match(/^(\w+)\(.*\)$/);if(X&&X[1]===Y.name)return!0;return!1})});return p.debug(`Filtered tools: ${J.map((Y)=>Y.name).join(", ")} (${J.length}/${$.length})`),J}clearSkillContext(){if(this.activeSkillContext)p.debug(`Skill "${this.activeSkillContext.skillName}" deactivated`),this.activeSkillContext=void 0}async processAtMentionsForContent($){if(!this.attachmentCollector)return $;if(typeof $==="string")return this.processAtMentions($);let Z=[];for(let Y of $)if(Y.type==="text")Z.push(Y.text);if(Z.length===0)return $;let J=Z.join(`
819
+ `),H={id:this.generateTaskId(),type:"simple",prompt:V};return{success:!0,finalMessage:(await this.executeTask(H)).content,metadata:{turnsCount:1,toolCallsCount:0,duration:0}}}async chat($,Z,J){let{drainLoop:Y}=await import("./chunk-70xvj0fk.js");return Y(this.chatStream($,Z,J))}async*runPlanLoop($,Z,J){p.debug("Processing Plan mode message...");let{prompt:Y}=await A$({projectPath:Z.workspaceRoot||T(),mode:"plan",includeEnvironment:!0,environmentOptions:Z2,language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),projectInstructionSourcePath:this.sessionRuntime?.projectRoot}),W;if(typeof $==="string")W=d1($);else{let X=$.filter((Q)=>Q.type==="text");if(X.length>0){let Q=X[0];W=$.map((U)=>U===Q?{type:"text",text:d1(Q.text)}:U)}else W=[{type:"text",text:d1("")},...$]}return yield*this.executeLoop(W,Z,J,Y)}async*runLoop($,Z,J){p.debug("Processing enhanced chat message...");let Y=Z.systemPrompt??await this.buildSystemPromptOnDemand(Z.workspaceRoot||T());return yield*this.executeLoop($,Z,J,Y)}async buildSystemPromptOnDemand($){let Z=this.runtimeOptions.systemPrompt,J=this.runtimeOptions.appendSystemPrompt;return(await A$({projectPath:$,replaceDefault:Z,append:J,includeEnvironment:!0,environmentOptions:Z2,language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),projectInstructionSourcePath:this.sessionRuntime?.projectRoot})).prompt}executeLoop($,Z,J,Y){if(!this.isInitialized)throw Error("Agent未初始化");let W=this.buildLoopDependencies();return J7(W,$,Z,J,Y)}takeStartupAdoptedToolResultEvents(){return(this.sessionRuntime?.takeStartupAdoptedToolResults()??[]).flatMap(({call:Z,result:J})=>{let Y={id:Z.toolCallId,type:"function",function:{name:Z.toolName,arguments:JSON.stringify(Z.input)}},W=J.metadata&&typeof J.metadata==="object"&&!Array.isArray(J.metadata)?J.metadata:void 0,X=J.error===void 0,Q=J.output,U={success:X,llmContent:typeof Q==="string"||Q!==null&&typeof Q==="object"?Q:Q===null?J.error?`Subagent execution failed: ${J.error}.`:"":String(Q),...J.error?{error:{type:"execution_error",message:J.error}}:{},...W?{metadata:W}:{}},z=[{kind:"tool_result",toolCall:Y,result:U}],V=Z7(Y,U);if(V)z.push(V);return z})}buildLoopDependencies(){return{chatService:this.chatService,toolExecutor:this.toolExecutor,executionEngine:this.executionEngine,config:this.config,runtimeOptions:this.runtimeOptions,currentModelMaxContextTokens:this.currentModelMaxContextTokens,activeSkillContext:this.activeSkillContext,onSkillActivated:($)=>{this.activeSkillContext=$,p.debug(`Skill "${$.skillName}" activated`+($.allowedTools?` with allowed tools: ${$.allowedTools.join(", ")}`:""))},onModelSwitch:($)=>this.switchModelIfNeeded($),applySkillToolRestrictions:($)=>this.applySkillToolRestrictions($),staticProjectRules:this.sessionRuntime?.getStaticProjectRules(),hydrateProjectRules:this.sessionRuntime?($)=>this.sessionRuntime.hydrateProjectRules($):void 0,resolveContextualProjectRules:this.sessionRuntime?($,Z,J,Y)=>this.sessionRuntime.resolveContextualProjectRules($,Z,J,Y):void 0}}async chatWithSystem($,Z){if(!this.isInitialized)throw Error("Agent未初始化");let J=[{role:"system",content:$},{role:"user",content:Z}];return(await this.chatService.chat(J)).content}getActiveTask(){return this.activeTask}getChatService(){return this.chatService}getContextManager(){return this.executionEngine?.getContextManager()}getStats(){return{initialized:this.isInitialized,activeTask:this.activeTask?.id,components:{chatService:this.chatService?"ready":"not_loaded",executionEngine:this.executionEngine?"ready":"not_loaded"}}}getAvailableTools(){return this.toolExecutor?this.toolExecutor.getRegistry().getAll():[]}getToolRegistry(){return this.toolExecutor.getRegistry()}applyToolWhitelist($){let Z=this.toolExecutor.getRegistry(),Y=Z.getAll().filter((W)=>!$.includes(W.name));for(let W of Y)Z.unregister(W.name);p.debug(`Applied tool whitelist: ${$.join(", ")} (removed ${Y.length} tools)`)}applyToolBlacklist($){let Z=this.toolExecutor.getRegistry(),J=new Set($);for(let Y of Z.getAll())if(J.has(Y.name))Z.unregister(Y.name);p.debug(`Applied tool blacklist: ${$.join(", ")}`)}getToolStats(){let $=this.getAvailableTools(),Z=new Map;return $.forEach((J)=>{let Y=Z.get(J.kind)||0;Z.set(J.kind,Y+1)}),{totalTools:$.length,toolsByKind:Object.fromEntries(Z),toolNames:$.map((J)=>J.name)}}async destroy(){if(this.destroyPromise)return this.destroyPromise;return this.destroyPromise=(async()=>{this.log("销毁Agent..."),await this.activeOperations.shutdown("agent-destroy");try{await this.legacyMcpRegistry?.disconnectAll(),this.legacyMcpRegistry=void 0,this.log("Agent已销毁")}catch($){throw this.error("Agent销毁失败",$),$}finally{this.toolExecutor.dispose(),this.isInitialized=!1}})(),this.destroyPromise}syncRuntimeState(){if(!this.sessionRuntime)return;this.chatService=this.sessionRuntime.getChatService(),this.executionEngine=this.sessionRuntime.getExecutionEngine(),this.attachmentCollector=this.sessionRuntime.getAttachmentCollector(),this.currentModelId=this.sessionRuntime.getCurrentModelId(),this.currentModelMaxContextTokens=this.sessionRuntime.getCurrentModelMaxContextTokens()}generateTaskId(){return`task_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}log($,Z){p.debug(`[MainAgent] ${$}`,Z||"")}error($,Z){p.error(`[MainAgent] ${$}`,Z||"")}async initializeSystemPrompt(){try{let $=this.runtimeOptions.systemPrompt,Z=this.runtimeOptions.appendSystemPrompt,J=await A$({projectPath:this.sessionRuntime?.workspaceRoot??T(),replaceDefault:$,append:Z,includeEnvironment:!1,language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),projectInstructionSourcePath:this.sessionRuntime?.projectRoot});if(J.prompt)this.log("系统提示配置验证成功"),p.debug(`[SystemPrompt] 可用来源: ${J.sources.filter((Y)=>Y.loaded).map((Y)=>Y.name).join(", ")}`)}catch($){this.error("系统提示配置验证失败",$)}}async registerBuiltinTools(){try{let $=await W5({sessionId:"default",configDir:e(),workspaceRoot:T(),resourceRoot:T(),agentResources:this.agentResources});p.debug(`Registering ${$.length} builtin tools...`),this.toolExecutor.getRegistry().registerAll($);let Z=this.toolExecutor.getRegistry().getAll().length;p.debug(`Builtin tools registered: ${Z} tools`),p.debug(`[Tools] ${this.toolExecutor.getRegistry().getAll().map((J)=>J.name).join(", ")}`),await this.registerMcpTools()}catch($){throw p.error("Failed to register builtin tools:",$),$}}async registerMcpTools(){try{let $=await k2({workspaceRoot:T(),storeServers:this.config.mcpServers??{},cliConfigs:this.runtimeOptions.mcpConfig,strictCliConfig:this.runtimeOptions.strictMcpConfig});if(Object.keys($).length===0){p.debug("No MCP servers configured");return}let Z=u0.createIsolated({artifactWriter:new m1(`legacy-${gQ()}`)});this.legacyMcpRegistry=Z;for(let[X,Q]of Object.entries($))try{p.debug(`Connecting to MCP server: ${X}`),await Z.registerServer(X,Q),p.debug(`MCP server "${X}" connected`)}catch(U){p.warn(`Warning: MCP server "${X}" connection failed:`,U)}let J=this.toolExecutor.getRegistry();J.setMcpCatalogBarrier(()=>Z.waitForCatalogIdle());let Y=Z.getCatalogSnapshot();J.replaceMcpTools(Y.tools),J.registerAll(r1(Z));let W=Z.getInstructionsSnapshot();if(J.queueMcpInstructionsChange({revision:W.revision,reason:"snapshot",replace:!0,instructions:W.instructions,removed:[]}),Z.on("catalogChanged",(X)=>{J.replaceMcpTools(X.tools,X)}),Z.on("contentCatalogChanged",(X)=>{J.queueMcpContentChange(X)}),Z.on("resourceUpdated",(X)=>{J.queueMcpResourceUpdated(X)}),Z.on("connectionLifecycleChanged",(X)=>{J.queueMcpConnectionChange(X)}),Z.on("log",(X)=>{J.queueMcpLog(X)}),Z.on("instructionsChanged",(X)=>{J.queueMcpInstructionsChange({revision:X.revision,reason:X.reason,replace:!1,instructions:X.action==="added"&&X.instruction?[{serverName:X.serverName,...X.instruction}]:[],removed:X.action==="removed"?[X.serverName]:[]})}),Y.tools.length>0)p.debug(`Registered ${Y.tools.length} MCP tools`),p.debug(`[MCP Tools] ${Y.tools.map((X)=>X.name).join(", ")}`)}catch($){p.warn("Failed to register MCP tools:",$)}}async loadSubagents(){let $=await S0(T());if(this.agentResources=Y5($),this.subagentRegistry=this.agentResources.subagents,this.runtimeOptions.agents?.length)this.subagentRegistry.applyOverrides(this.runtimeOptions.agents);let Z=this.subagentRegistry.getAllNames().length;if(Z>0)p.debug(`Loaded ${Z} subagents: ${this.subagentRegistry.getAllNames().join(", ")}`);else p.debug("No subagents configured")}applySkillToolRestrictions($){if(!this.activeSkillContext?.allowedTools)return $;let Z=this.activeSkillContext.allowedTools;p.debug(`Applying Skill tool restrictions: ${Z.join(", ")}`);let J=$.filter((Y)=>{return Z.some((W)=>{if(W===Y.name)return!0;let X=W.match(/^(\w+)\(.*\)$/);if(X&&X[1]===Y.name)return!0;return!1})});return p.debug(`Filtered tools: ${J.map((Y)=>Y.name).join(", ")} (${J.length}/${$.length})`),J}clearSkillContext(){if(this.activeSkillContext)p.debug(`Skill "${this.activeSkillContext.skillName}" deactivated`),this.activeSkillContext=void 0}async processAtMentionsForContent($){if(!this.attachmentCollector)return $;if(typeof $==="string")return this.processAtMentions($);let Z=[];for(let Y of $)if(Y.type==="text")Z.push(Y.text);if(Z.length===0)return $;let J=Z.join(`
820
820
  `);try{let Y=await this.attachmentCollector.collect(J);if(Y.length===0)return $;p.debug(`Processed ${Y.length} @ file mentions in multimodal message`);let W=this.buildAttachmentText(Y);if(!W)return $;return[...$,{type:"text",text:W}]}catch(Y){return p.error("Failed to process @ mentions in multimodal message:",Y),$}}buildAttachmentText($){let Z=[],J=[];for(let W of $)if(W.type==="file"){let X=W.metadata?.lineRange?` (lines ${W.metadata.lineRange.start}${W.metadata.lineRange.end?`-${W.metadata.lineRange.end}`:""})`:"";Z.push(`<file path="${W.path}"${X?` range="${X}"`:""}>`,W.content,"</file>")}else if(W.type==="directory")Z.push(`<directory path="${W.path}">`,W.content,"</directory>");else if(W.type==="error")J.push(`- @${W.path}: ${W.error}`);let Y="";if(Z.length>0)Y+=`
821
821
 
822
822
  <system-reminder>
@@ -1118,27 +1118,31 @@ ${Y.response}`,data:{action:"show_side_conversation",question:J,response:Y.respo
1118
1118
  • Token 数量: ${V.toLocaleString()}
1119
1119
  • Token 限制: ${K.toLocaleString()}
1120
1120
  • 使用率: ${G}%`),V<K*0.5)return J.sendMessage(`提示: 当前 token 使用率较低(${G}%),可以暂时不压缩。
1121
- 系统会在达到 80% 时自动触发压缩。`),{success:!0,message:"无需压缩"};J.sendMessage("**正在压缩上下文...**");let F=await aJ.compact(z,{trigger:"manual",modelName:W.model,modelProvider:W.provider,maxContextTokens:K,apiKey:H.chat.apiKey,baseURL:H.chat.baseUrl,workspaceRoot:Z.workspaceRoot??Z.cwd,sessionId:U});if(U)await new t1({projectPath:Z.workspaceRoot??Z.cwd}).saveCompaction(U,F.summary,{trigger:"manual",reason:"manual",strategy:F.success?"llm":"fallback",preTokens:F.preTokens,postTokens:F.postTokens,sampleAttempts:F.sampleAttempts,failureReason:F.failureReason,filesIncluded:F.filesIncluded,replacementMessages:F.compactedMessages},null),console.log("[/compact] 压缩数据已保存到 JSONL");if(F.success){let B=`[OK] **压缩完成!**
1121
+ 系统会在达到 80% 时自动触发压缩。`),{success:!0,message:"无需压缩"};J.sendMessage("**正在压缩上下文...**");let F=await aJ.compact(z,{trigger:"manual",modelName:W.model,modelProvider:W.provider,maxContextTokens:K,apiKey:H.chat.apiKey,baseURL:H.chat.baseUrl,workspaceRoot:Z.workspaceRoot??Z.cwd,sessionId:U});if(U)await new t1({projectPath:Z.workspaceRoot??Z.cwd}).saveCompaction(U,F.summary,{trigger:"manual",reason:"manual",strategy:F.success?"llm":"fallback",preTokens:F.preTokens,postTokens:F.postTokens,sampleAttempts:F.sampleAttempts,inputReductions:F.inputReductions,messagesOmitted:F.messagesOmitted,filesOmitted:F.filesOmitted,imagesOmitted:F.imagesOmitted,failureReason:F.failureReason,filesIncluded:F.filesIncluded,replacementMessages:F.compactedMessages},null),console.log("[/compact] 压缩数据已保存到 JSONL");if(F.success){let B=`[OK] **压缩完成!**
1122
1122
 
1123
1123
  **Token 变化**
1124
1124
  • 压缩前: ${F.preTokens.toLocaleString()} tokens
1125
1125
  • 压缩后: ${F.postTokens.toLocaleString()} tokens
1126
1126
  • 摘要尝试: ${F.sampleAttempts??0}
1127
+ • 输入缩减: ${F.inputReductions??0}
1128
+ • 省略图片: ${F.imagesOmitted??0}
1127
1129
  • 压缩率: ${((1-F.postTokens/F.preTokens)*100).toFixed(1)}%`;if(F.filesIncluded.length>0)B+=`
1128
1130
 
1129
1131
  **包含文件** (${F.filesIncluded.length})`,F.filesIncluded.forEach((D,_)=>{B+=`
1130
1132
  ${_+1}. ${D}`});return B+=`
1131
1133
 
1132
- 对话历史已压缩,但完整记录仍保存在会话文件中。`,J.sendMessage(B),{success:!0,message:"compact_completed",data:{compactedMessages:F.compactedMessages,boundaryMessage:F.boundaryMessage,summaryMessage:F.summaryMessage,preTokens:F.preTokens,postTokens:F.postTokens,filesIncluded:F.filesIncluded,usage:F.usage,maxContextTokens:K}}}else return J.sendMessage(`[WARN] **压缩使用降级策略**
1134
+ 对话历史已压缩,但完整记录仍保存在会话文件中。`,J.sendMessage(B),{success:!0,message:"compact_completed",data:{compactedMessages:F.compactedMessages,boundaryMessage:F.boundaryMessage,summaryMessage:F.summaryMessage,preTokens:F.preTokens,postTokens:F.postTokens,filesIncluded:F.filesIncluded,usage:F.usage,sampleAttempts:F.sampleAttempts,inputReductions:F.inputReductions,messagesOmitted:F.messagesOmitted,filesOmitted:F.filesOmitted,imagesOmitted:F.imagesOmitted,maxContextTokens:K}}}else return J.sendMessage(`[WARN] **压缩使用降级策略**
1133
1135
 
1134
1136
  **Token 变化**
1135
1137
  • 压缩前: ${F.preTokens.toLocaleString()} tokens
1136
1138
  • 压缩后: ${F.postTokens.toLocaleString()} tokens
1137
1139
  • 摘要尝试: ${F.sampleAttempts??0}
1140
+ • 输入缩减: ${F.inputReductions??0}
1141
+ • 省略图片: ${F.imagesOmitted??0}
1138
1142
 
1139
1143
  由于压缩过程出现错误,已使用简单截断策略。
1140
1144
  失败分类: ${F.failureReason??"deterministic"}
1141
- 错误信息: ${F.error}`),{success:!1,message:"compact_fallback",error:F.error,data:{compactedMessages:F.compactedMessages,boundaryMessage:F.boundaryMessage,summaryMessage:F.summaryMessage,preTokens:F.preTokens,postTokens:F.postTokens,sampleAttempts:F.sampleAttempts,failureReason:F.failureReason}}}catch(Y){let W=Y instanceof Error?Y.message:String(Y);return J.sendMessage(`[FAIL] **压缩失败**: ${W}`),{success:!1,error:W}}}var AV={name:"compact",description:"手动压缩当前会话的上下文",fullDescription:"压缩当前对话历史,生成详细的技术总结,保留最近的消息。压缩后的上下文可以节省 token 使用量,同时保留关键信息。",usage:"/compact",examples:["/compact"],category:"context",handler:bV},oJ=AV;function jV($){return`Reasoning effort: ${$.selection===$.effective?$.selection:`${$.selection} (${$.effective})`}
1145
+ 错误信息: ${F.error}`),{success:!1,message:"compact_fallback",error:F.error,data:{compactedMessages:F.compactedMessages,boundaryMessage:F.boundaryMessage,summaryMessage:F.summaryMessage,preTokens:F.preTokens,postTokens:F.postTokens,sampleAttempts:F.sampleAttempts,inputReductions:F.inputReductions,messagesOmitted:F.messagesOmitted,filesOmitted:F.filesOmitted,imagesOmitted:F.imagesOmitted,failureReason:F.failureReason}}}catch(Y){let W=Y instanceof Error?Y.message:String(Y);return J.sendMessage(`[FAIL] **压缩失败**: ${W}`),{success:!1,error:W}}}var AV={name:"compact",description:"手动压缩当前会话的上下文",fullDescription:"压缩当前对话历史,生成详细的技术总结,保留最近的消息。压缩后的上下文可以节省 token 使用量,同时保留关键信息。",usage:"/compact",examples:["/compact"],category:"context",handler:bV},oJ=AV;function jV($){return`Reasoning effort: ${$.selection===$.effective?$.selection:`${$.selection} (${$.effective})`}
1142
1146
  Supported: auto, ${$.supported.join(", ")}`}var MV={name:"effort",description:"查看或设置当前 Session 的推理强度",fullDescription:"推理强度由当前 Session 持有并持久化。auto 会按模型能力在 high 附近解析;显式不支持的级别会被拒绝。",usage:"/effort [auto|off|minimal|low|medium|high|xhigh|max]",category:"Session",examples:["/effort","/effort low","/effort auto","/effort off"],async handler($,Z){if(!Z.reasoning)return{success:!1,error:"This surface has no active Session reasoning boundary"};if($.length>1)return{success:!1,error:"Usage: /effort [auto|off|minimal|low|medium|high|xhigh|max]"};let J=$[0]?.toLowerCase();if(J!==void 0&&!tJ(J))return{success:!1,error:`Invalid reasoning effort: ${J}`};try{let Y=J?await Z.reasoning.set(J):await Z.reasoning.get();return{success:!0,message:jV(Y),data:{reasoningEffort:Y.selection,effectiveReasoningEffort:Y.effective,supportedReasoningEfforts:Y.supported}}}catch(Y){return{success:!1,error:Y instanceof Error?Y.message:"Failed to update reasoning effort"}}}},sJ=MV;import{mkdir as CV,open as TV,unlink as RV}from"node:fs/promises";import eJ from"node:os";import j1 from"node:path";function PV($,Z,J){let Y=Z?.trim()||J;if(Y.includes("\x00"))throw Error("Session export path contains a null byte");if(Y==="~")return j1.join(eJ.homedir(),J);if(Y.startsWith(`~${j1.sep}`)||Y.startsWith("~/"))return j1.resolve(eJ.homedir(),Y.slice(2));return j1.resolve($,Y)}async function $3($,Z,J){if(!j1.isAbsolute($))throw Error("Session export cwd must be absolute");let Y=PV($,J,Z.filename);await CV(j1.dirname(Y),{recursive:!0,mode:448});let W,X=!1;try{return W=await TV(Y,"wx",384),X=!0,await W.writeFile(Z.markdown,"utf8"),await W.sync(),Y}catch(Q){if(await W?.close().catch(()=>{return}),W=void 0,X)await RV(Y).catch(()=>{return});if(Q.code==="EEXIST")throw Error(`Session export already exists: ${Y}`);throw Q}finally{await W?.close().catch(()=>{return})}}function SV($){let Z=!1,J=[];for(let Y of $){if(Y==="--reasoning"){Z=!0;continue}if(Y.startsWith("--"))throw Error(`Unknown export option: ${Y}`);J.push(Y)}if(J.length>1)throw Error("Usage: /export [path] [--reasoning]");return{includeReasoning:Z,...J[0]?{outputPath:J[0]}:{}}}var fV={name:"export",description:"Export the current durable conversation as safe Markdown",fullDescription:"将当前完整 durable history 导出为 Markdown。工具活动经过凭证、二进制、宿主路径和体积清理;reasoning 仅在显式 --reasoning 时包含。",usage:"/export [path] [--reasoning]",category:"Session",examples:["/export","/export reports/conversation.md","/export --reasoning"],async handler($,Z){if(!Z.sessionId)return{success:!1,error:"No active session to export"};let J=Z.workspaceRoot??Z.cwd;try{let{includeReasoning:Y,outputPath:W}=SV($),X=await r.exportSessionMarkdown(Z.sessionId,J,{includeReasoning:Y});if(Z.surface==="acp"){if(W)return{success:!1,error:"ACP export does not write host paths; omit the path to receive Markdown"};if(Buffer.byteLength(X.markdown,"utf8")>Z3)return{success:!1,error:"Session export exceeds the ACP inline limit; use the Web export endpoint"};return{success:!0,message:"Session export ready",content:X.markdown,data:{action:"session_exported",filename:X.filename,contentSha256:X.contentSha256,contentBytes:X.contentBytes}}}let Q=await $3(J,X,W);return{success:!0,message:`Saved conversation to ${Q}
1143
1147
  SHA-256 ${X.contentSha256}`,data:{action:"session_exported",filePath:Q,filename:X.filename,contentSha256:X.contentSha256,contentBytes:X.contentBytes,redactionCount:X.redactionCount}}}catch(Y){return{success:!1,error:Y instanceof Error?Y.message:"Session export failed"}}}},J3=fV;function kV($){return $.filter((Z)=>Z.relationType!=="subagent")}var yV={name:"fork",description:"Fork a conversation into an independent session branch",fullDescription:"从任意工作区的历史会话创建独立分支。可以指定唯一 sessionId 直接 fork,或不带参数打开会话选择器。",usage:"/fork [sessionId]",category:"Session",examples:["/fork - 打开会话选择器","/fork parent-session - 直接 fork 指定会话"],async handler($,Z){if($.length>1)return{success:!1,error:"Usage: /fork [sessionId]"};try{let J=await r.listSessions({includeSubagents:!1}),Y=kV(J);if($.length===0){if(Y.length===0)return{success:!1,error:"No forkable sessions found"};return{success:!0,data:{action:"select_session",intent:"fork",sessions:Y}}}let W=$[0],X=J.filter((U)=>U.sessionId===W);if(X.length>0&&X.every((U)=>U.relationType==="subagent"))return{success:!1,error:`Cannot fork subagent session: ${W}`};let Q=Y.filter((U)=>U.sessionId===W);if(Q.length===0)return{success:!1,error:`Session not found: ${W}`};if(Q.length>1)return{success:!1,error:`Multiple workspaces contain session ${W}; use /fork to select one`};return{success:!0,data:{action:"activate_session",intent:"fork",session:Q[0]}}}catch(J){return{success:!1,error:J instanceof Error?J.message:"Failed to list sessions"}}}},Y3=yV;function U3($){let Z=Math.floor((Date.now()-$.getTime())/1000);if(Z<60)return`${Z}s ago`;let J=Math.floor(Z/60);if(J<60)return`${J}m ago`;let Y=Math.floor(J/60);if(Y<24)return`${Y}h ago`;return`${Math.floor(Y/24)}d ago`}async function vV($){let Z=u0.getInstance(),J=i$();if(Object.keys(J).length===0){$.sendMessage(`**MCP 服务器状态**
1144
1148
 
@@ -1619,7 +1623,7 @@ ${J}
1619
1623
  `)),{success:!0,message:"Schedules listed",content:z.join(`
1620
1624
  `)}}case"create":{let U=qK(X);if("error"in U)return Y.sendMessage(`创建失败:${U.error}`),{success:!1,error:U.error};let z={prompt:U.prompt,projectPath:Q,trigger:U.trigger,isolation:"worktree",permissionMode:"default",enabled:!0};try{let V=await $.create(z),H=V.nextRunAt?new Date(V.nextRunAt).toLocaleString():"(无)";return Y.sendMessage(`[OK] 已创建定时任务 \`${V.id}\`
1621
1625
  ${QZ(V.trigger)} · 下次运行: ${H}`),{success:!0,message:`Schedule ${V.id} created`}}catch(V){let H=V instanceof Error?V.message:String(V);return Y.sendMessage(`创建失败:${H}`),{success:!1,error:H}}}case"remove":case"rm":{let U=X[0];if(!U)return Y.sendMessage("用法:/schedule remove <id>"),{success:!1,error:"Missing schedule id"};let z=await $.remove(U);return Y.sendMessage(z?`[OK] 已删除 \`${U}\``:`未找到 \`${U}\``),{success:z,message:z?"Removed":"Not found"}}case"enable":case"disable":{let U=X[0];if(!U)return Y.sendMessage(`用法:/schedule ${W} <id>`),{success:!1,error:"Missing schedule id"};let z=await $.setEnabled(U,W==="enable");return Y.sendMessage(z?`[OK] 已${W==="enable"?"启用":"停用"} \`${U}\``:`未找到 \`${U}\``),{success:Boolean(z),message:z?"Updated":"Not found"}}case"run":{let U=X[0];if(!U)return Y.sendMessage("用法:/schedule run <id>"),{success:!1,error:"Missing schedule id"};try{return await LK(U),Y.sendMessage(`[OK] 已触发 \`${U}\``),{success:!0,message:"Schedule triggered"}}catch(z){let V=z instanceof Error?z.message:String(z);return Y.sendMessage(`运行失败:${V}`),{success:!1,error:V}}}default:return Y.sendMessage(`未知子命令: ${W}
1622
- 使用 /schedule 查看帮助`),{success:!1,error:`Unknown subcommand: ${W}`}}}}}var r3=EK();import*as R1 from"node:fs/promises";import*as P1 from"node:path";async function s3($,Z={}){let{maxResults:J=20,caseSensitive:Y=!1,projectPath:W,storagePath:X}=Z,Q=X??w2(W??T());if(!X){let G=await wK($,W??T(),J,Y);if(G)return G}let U;try{U=(await R1.readdir(Q)).filter((F)=>F.endsWith(".jsonl")&&!F.startsWith("agent_")).map((F)=>P1.join(Q,F))}catch{return[]}let V=(await Promise.all(U.map(async(G)=>{try{let F=await R1.stat(G);return{path:G,mtime:F.mtimeMs}}catch{return null}}))).filter((G)=>G!==null).sort((G,F)=>F.mtime-G.mtime).map((G)=>G.path),H=[],K=Y?$:$.toLowerCase();for(let G of V){if(H.length>=J)break;let F=P1.basename(G,".jsonl"),B=await NK(G,K,Y,F);if(H.push(...B),H.length>=J){H.length=J;break}}return H}async function wK($,Z,J,Y){try{let{syncAll:W}=await import("./chunk-h9xayrwp.js"),X=await o3();if(!X)return null;let{SessionService:Q}=await import("./chunk-3j0dhewn.js");await W(X,Q.projectionDeriverForSearch());let U=P1.resolve(Z),z=t3(X,$,U,J*4),V=Y?$:$.toLowerCase(),H=[];for(let K of z){if(K.role!=="user"&&K.role!=="assistant")continue;let G=UZ(K.text,V,Y,K.session_id,K.role,K.timestamp??void 0,0);if(G)H.push(G);if(H.length>=J)break}return H}catch{return null}}async function NK($,Z,J,Y){try{let W=await R1.readFile($,"utf8"),Q=W.split(`
1626
+ 使用 /schedule 查看帮助`),{success:!1,error:`Unknown subcommand: ${W}`}}}}}var r3=EK();import*as R1 from"node:fs/promises";import*as P1 from"node:path";async function s3($,Z={}){let{maxResults:J=20,caseSensitive:Y=!1,projectPath:W,storagePath:X}=Z,Q=X??w2(W??T());if(!X){let G=await wK($,W??T(),J,Y);if(G)return G}let U;try{U=(await R1.readdir(Q)).filter((F)=>F.endsWith(".jsonl")&&!F.startsWith("agent_")).map((F)=>P1.join(Q,F))}catch{return[]}let V=(await Promise.all(U.map(async(G)=>{try{let F=await R1.stat(G);return{path:G,mtime:F.mtimeMs}}catch{return null}}))).filter((G)=>G!==null).sort((G,F)=>F.mtime-G.mtime).map((G)=>G.path),H=[],K=Y?$:$.toLowerCase();for(let G of V){if(H.length>=J)break;let F=P1.basename(G,".jsonl"),B=await NK(G,K,Y,F);if(H.push(...B),H.length>=J){H.length=J;break}}return H}async function wK($,Z,J,Y){try{let{syncAll:W}=await import("./chunk-h9xayrwp.js"),X=await o3();if(!X)return null;let{SessionService:Q}=await import("./chunk-mjfgsz1s.js");await W(X,Q.projectionDeriverForSearch());let U=P1.resolve(Z),z=t3(X,$,U,J*4),V=Y?$:$.toLowerCase(),H=[];for(let K of z){if(K.role!=="user"&&K.role!=="assistant")continue;let G=UZ(K.text,V,Y,K.session_id,K.role,K.timestamp??void 0,0);if(G)H.push(G);if(H.length>=J)break}return H}catch{return null}}async function NK($,Z,J,Y){try{let W=await R1.readFile($,"utf8"),Q=W.split(`
1623
1627
  `).flatMap((K,G)=>{if(!K.trim())return[];try{return[{event:JSON.parse(K),index:G}]}catch{return[]}});if(!Q.some(({event:K})=>K.type==="session_created"))return bK(Q,Z,J,Y);let z=new Map(Q.flatMap(({event:K,index:G})=>typeof K.id==="string"?[[K.id,G+1]]:[])),V=n3(a3(W,$)),H=new Map;for(let K of V){if(K.type==="message_created"&&(K.data.role==="user"||K.data.role==="assistant"))H.set(K.data.messageId,{role:K.data.role,content:[],timestamp:K.timestamp,lineNumber:z.get(K.id)??0});if(K.type==="part_created"&&K.data.partType==="text"){let G=H.get(K.data.messageId),F=K.data.payload.text;if(G&&typeof F==="string")G.content.push(F)}}return[...H.values()].flatMap((K)=>{let G=UZ(K.content.join(" "),Z,J,Y,K.role,K.timestamp,K.lineNumber);return G?[G]:[]})}catch{return[]}}function bK($,Z,J,Y){return $.flatMap(({event:W,index:X})=>{if(W.type!=="message")return[];let Q=W.message;if(Q?.role!=="user"&&Q?.role!=="assistant"||!Q.content)return[];let U=typeof Q.content==="string"?Q.content:Array.isArray(Q.content)?Q.content.filter((V)=>typeof V==="object"&&V!==null&&V.type==="text"&&typeof V.text==="string").map((V)=>V.text).join(" "):"",z=UZ(U,Z,J,Y,Q.role,typeof W.timestamp==="string"?W.timestamp:void 0,X+1);return z?[z]:[]})}function UZ($,Z,J,Y,W,X,Q){if(!$)return;let U=J?$:$.toLowerCase();if(!U.includes(Z))return;let z=U.indexOf(Z),V=Math.max(0,z-80),H=Math.min($.length,z+Z.length+80);return{sessionId:Y,role:W,content:(V>0?"...":"")+$.slice(V,H).replace(/\n/g," ")+(H<$.length?"...":""),timestamp:X,lineNumber:Q}}function e3($){if($.length===0)return"没有找到匹配的历史记录";let Z=[`**找到 ${$.length} 条匹配:**
1624
1628
  `];for(let J of $){let Y=J.timestamp?new Date(J.timestamp).toLocaleString("zh-CN",{timeZone:"Asia/Shanghai"}):"?",W=J.role==="user"?"\uD83D\uDC64":"\uD83E\uDD16";Z.push(`${W} \`${J.sessionId.slice(0,8)}\` (${Y})`),Z.push(` ${J.content}`),Z.push("")}return Z.join(`
1625
1629
  `)}var AK={name:"search",description:"Search past session transcripts",fullDescription:"搜索历史会话记录,查找过去的对话内容",usage:"/search <keyword>",aliases:["find","history"],category:"Session",examples:['/search 断路器 - 搜索包含"断路器"的历史对话',"/search edit tool - 搜索 edit tool 相关讨论"],async handler($,Z){let J=I(Z);if($.length===0)return J.sendMessage("**用法:** `/search <关键词>`\n\n在历史会话中搜索包含指定关键词的对话"),{success:!0,message:"显示帮助"};let Y=$.join(" ");J.sendMessage(`正在搜索: "${Y}" ...`);try{let W=await s3(Y,{maxResults:15,projectPath:Z.cwd}),X=e3(W);return J.sendMessage(X),{success:!0,message:`found ${W.length} results`,data:{matches:W.length}}}catch(W){let X=W instanceof Error?W.message:"未知错误";return J.sendMessage(`搜索失败: ${X}`),{success:!1,error:X}}}},$Y=AK;var jK={name:"skills",description:"查看所有可用的 Skills",fullDescription:"显示所有已发现的 Skills 及其详细信息,包括名称、描述、来源和允许的工具。",usage:"/skills",category:"system",examples:["/skills"],handler:async($,Z)=>{try{let J=Z.workspaceRoot??Z.cwd;return await U$(J,async(Y)=>{await Y.skills.refresh(),X1(J),await W1(J)}),{success:!0,message:"show_skills_manager",data:{action:"show_skills_manager"}}}catch(J){let Y=`获取 Skills 失败: ${J instanceof Error?J.message:"未知错误"}`;return f().addAssistantMessage(Y),{success:!1,error:Y}}}},ZY=jK;import MK from"node:path";function p5($){if($<1000)return`${$}ms`;let Z=Math.floor($/1000);if(Z<60)return`${Z}s`;let J=Math.floor(Z/60);if(J<60)return`${J}m ${Z%60}s`;return`${Math.floor(J/60)}h ${J%60}m`}function JY($){switch($){case"running":return"[RUNNING]";case"completed":case"exited":return"[OK]";case"failed":case"error":return"[FAIL]";case"killed":case"cancelled":return"[STOPPED]";default:return"[?]"}}function YY($,Z){if($.length<=Z)return $;return $.slice(0,Z-3)+"..."}async function CK($,Z){let J=I(Z),Y=$[0],W=o.getInstance(),X=U0.getInstance(),Q=Z.sessionId??"",U=Z.sessionId?{sessionId:Z.sessionId,projectPath:MK.resolve(Z.workspaceRoot??Z.cwd)}:void 0;if(Y==="resume"){let F=$[1],B=$.slice(2).join(" ").trim();if(!F||!B)return{success:!1,error:"Usage: /tasks resume <agentId> <prompt>"};if(!Z.subagents)return{success:!1,error:"This surface does not own a subagent runtime"};let D=await Z.subagents.resume(F,B),_=`Resumed \`${F}\` as \`${D.session.id}\` (depth ${D.session.resumeDepth}).`;return J.sendMessage(_),{success:!0,message:_,data:{action:"subagent_resumed",sourceAgentId:F,subagent:D.session}}}if(Y==="clean"){let F=X.cleanupExpiredSessionsForParent(U??Q,0);return J.sendMessage(`已清理 ${F} 个已完成的 Agent 会话`),{success:!0,message:`Cleaned ${F} agent sessions`}}let z=[`**后台任务列表**
@@ -1,2 +1,2 @@
1
- import{hg as H,ig as I}from"./chunk-dj99h8ca.js";import{Mutex as J}from"async-mutex";class B extends Error{limit;resource="resident_runtimes";retryable=!0;constructor(b){super("Session runtime capacity is full");this.limit=b;this.name="SessionRuntimeCapacityError"}}class D extends Error{constructor(){super("Session runtime residency is closed");this.name="SessionRuntimeResidencyClosedError"}}class A extends Error{constructor(b){super(`Session runtime residency already owns key: ${b}`);this.name="SessionRuntimeResidencyConflictError"}}class K{maxResident;idleMs;now;residents=new Map;reservations=new Map;operations=new J;nextGeneration=1;closed=!1;constructor(b){if(!H(b.maxResident))throw Error("Invalid max resident Session Runtime limit");if(!I(b.idleMs))throw Error("Invalid Session Runtime idle timeout");this.maxResident=b.maxResident,this.idleMs=b.idleMs,this.now=b.now??Date.now}acquire(b){let j=this.residents.get(b);if(!j||j.poisoned)return;return j.pins++,j.lastUsedAt=this.now(),this.createLease(j)}owns(b,j){let q=this.residents.get(b);return Boolean(q&&(j===void 0||q.value===j))}async reserve(b,j){if(!b.trim())throw Error("Session runtime residency key must not be blank");return this.operations.runExclusive(async()=>{if(this.closed)throw new D;if(this.residents.has(b)||this.reservations.has(b))throw new A(b);while(this.retainedCount()>=this.maxResident){if(!j.allowEviction)throw new B(this.maxResident);let z=this.oldestEvictableWebResident();if(!z)throw new B(this.maxResident);await this.disposeResident(z,!0)}let q={generation:this.allocateGeneration(),surface:j.surface};return this.reservations.set(b,q),this.createReservation(b,q)})}async remove(b,j){return this.operations.runExclusive(async()=>{let q=this.residents.get(b);if(!q||j!==void 0&&q.value!==j)return!1;if(q.pins>0)return!1;return await this.disposeResident(q,!0),!0})}async forget(b,j){return this.operations.runExclusive(async()=>{let q=this.residents.get(b);if(!q||j!==void 0&&q.value!==j||q.pins>0)return!1;return this.residents.delete(b),!0})}async sweepIdle(){return this.operations.runExclusive(async()=>{if(this.closed)return 0;let b=0;while(!0){let j=this.oldestIdleWebResident();if(!j)return b;await this.disposeResident(j,!0),b++}})}async disposeAll(){await this.operations.runExclusive(async()=>{this.closed=!0,this.reservations.clear();let b;for(let j of[...this.residents.values()])try{await this.disposeResident(j,!1)}catch(q){b??=q}if(this.residents.clear(),b!==void 0)throw b})}getStats(){let b=0;for(let j of this.residents.values())if(j.pins>0)b++;return{resident:this.residents.size,reserved:this.reservations.size,pinned:b,maxResident:this.maxResident}}retainedCount(){return this.residents.size+this.reservations.size}allocateGeneration(){let b=this.nextGeneration;return this.nextGeneration=this.nextGeneration===Number.MAX_SAFE_INTEGER?1:this.nextGeneration+1,b}createReservation(b,j){let q=!1;return{commit:(z)=>{if(q)throw new A(b);if(z.key!==b||z.surface!==j.surface||this.reservations.get(b)!==j||this.closed)throw this.reservations.delete(b),q=!0,this.closed?new D:new A(b);this.reservations.delete(b);let G={...z,generation:j.generation,pins:1,lastUsedAt:this.now(),poisoned:!1};return this.residents.set(b,G),q=!0,this.createLease(G)},cancel:()=>{if(q)return;if(this.reservations.get(b)===j)this.reservations.delete(b);q=!0}}}createLease(b){let j=!1;return{value:b.value,release:()=>{if(j)return;j=!0;let q=this.residents.get(b.key);if(q!==b||q.generation!==b.generation)return;q.pins=Math.max(0,q.pins-1),q.lastUsedAt=this.now()}}}oldestEvictableWebResident(){return this.sortedWebResidents().find((b)=>this.canEvict(b))}oldestIdleWebResident(){let b=this.now();return this.sortedWebResidents().find((j)=>b-j.lastUsedAt>=this.idleMs&&this.canEvict(j))}sortedWebResidents(){return[...this.residents.values()].filter((b)=>b.surface==="web").sort((b,j)=>b.lastUsedAt-j.lastUsedAt||b.generation-j.generation)}canEvict(b){if(b.pins>0||b.poisoned)return!1;try{return b.canEvict()}catch{return!1}}async disposeResident(b,j){if(this.residents.get(b.key)!==b)return;this.residents.delete(b.key);try{await b.dispose()}catch(q){if(j&&!this.closed&&!this.residents.has(b.key))b.lastUsedAt=this.now(),b.poisoned=!0,this.residents.set(b.key,b);throw q}}}
1
+ import{hg as H,ig as I}from"./chunk-ybr0g37q.js";import{Mutex as J}from"async-mutex";class B extends Error{limit;resource="resident_runtimes";retryable=!0;constructor(b){super("Session runtime capacity is full");this.limit=b;this.name="SessionRuntimeCapacityError"}}class D extends Error{constructor(){super("Session runtime residency is closed");this.name="SessionRuntimeResidencyClosedError"}}class A extends Error{constructor(b){super(`Session runtime residency already owns key: ${b}`);this.name="SessionRuntimeResidencyConflictError"}}class K{maxResident;idleMs;now;residents=new Map;reservations=new Map;operations=new J;nextGeneration=1;closed=!1;constructor(b){if(!H(b.maxResident))throw Error("Invalid max resident Session Runtime limit");if(!I(b.idleMs))throw Error("Invalid Session Runtime idle timeout");this.maxResident=b.maxResident,this.idleMs=b.idleMs,this.now=b.now??Date.now}acquire(b){let j=this.residents.get(b);if(!j||j.poisoned)return;return j.pins++,j.lastUsedAt=this.now(),this.createLease(j)}owns(b,j){let q=this.residents.get(b);return Boolean(q&&(j===void 0||q.value===j))}async reserve(b,j){if(!b.trim())throw Error("Session runtime residency key must not be blank");return this.operations.runExclusive(async()=>{if(this.closed)throw new D;if(this.residents.has(b)||this.reservations.has(b))throw new A(b);while(this.retainedCount()>=this.maxResident){if(!j.allowEviction)throw new B(this.maxResident);let z=this.oldestEvictableWebResident();if(!z)throw new B(this.maxResident);await this.disposeResident(z,!0)}let q={generation:this.allocateGeneration(),surface:j.surface};return this.reservations.set(b,q),this.createReservation(b,q)})}async remove(b,j){return this.operations.runExclusive(async()=>{let q=this.residents.get(b);if(!q||j!==void 0&&q.value!==j)return!1;if(q.pins>0)return!1;return await this.disposeResident(q,!0),!0})}async forget(b,j){return this.operations.runExclusive(async()=>{let q=this.residents.get(b);if(!q||j!==void 0&&q.value!==j||q.pins>0)return!1;return this.residents.delete(b),!0})}async sweepIdle(){return this.operations.runExclusive(async()=>{if(this.closed)return 0;let b=0;while(!0){let j=this.oldestIdleWebResident();if(!j)return b;await this.disposeResident(j,!0),b++}})}async disposeAll(){await this.operations.runExclusive(async()=>{this.closed=!0,this.reservations.clear();let b;for(let j of[...this.residents.values()])try{await this.disposeResident(j,!1)}catch(q){b??=q}if(this.residents.clear(),b!==void 0)throw b})}getStats(){let b=0;for(let j of this.residents.values())if(j.pins>0)b++;return{resident:this.residents.size,reserved:this.reservations.size,pinned:b,maxResident:this.maxResident}}retainedCount(){return this.residents.size+this.reservations.size}allocateGeneration(){let b=this.nextGeneration;return this.nextGeneration=this.nextGeneration===Number.MAX_SAFE_INTEGER?1:this.nextGeneration+1,b}createReservation(b,j){let q=!1;return{commit:(z)=>{if(q)throw new A(b);if(z.key!==b||z.surface!==j.surface||this.reservations.get(b)!==j||this.closed)throw this.reservations.delete(b),q=!0,this.closed?new D:new A(b);this.reservations.delete(b);let G={...z,generation:j.generation,pins:1,lastUsedAt:this.now(),poisoned:!1};return this.residents.set(b,G),q=!0,this.createLease(G)},cancel:()=>{if(q)return;if(this.reservations.get(b)===j)this.reservations.delete(b);q=!0}}}createLease(b){let j=!1;return{value:b.value,release:()=>{if(j)return;j=!0;let q=this.residents.get(b.key);if(q!==b||q.generation!==b.generation)return;q.pins=Math.max(0,q.pins-1),q.lastUsedAt=this.now()}}}oldestEvictableWebResident(){return this.sortedWebResidents().find((b)=>this.canEvict(b))}oldestIdleWebResident(){let b=this.now();return this.sortedWebResidents().find((j)=>b-j.lastUsedAt>=this.idleMs&&this.canEvict(j))}sortedWebResidents(){return[...this.residents.values()].filter((b)=>b.surface==="web").sort((b,j)=>b.lastUsedAt-j.lastUsedAt||b.generation-j.generation)}canEvict(b){if(b.pins>0||b.poisoned)return!1;try{return b.canEvict()}catch{return!1}}async disposeResident(b,j){if(this.residents.get(b.key)!==b)return;this.residents.delete(b.key);try{await b.dispose()}catch(q){if(j&&!this.closed&&!this.residents.has(b.key))b.lastUsedAt=this.now(),b.poisoned=!0,this.residents.set(b.key,b);throw q}}}
2
2
  export{B as s,K as t};
@@ -1,4 +1,4 @@
1
- import{b as RY,c as MY,d as TY}from"./chunk-phgcgfv1.js";import{j as DJ,k as VJ}from"./chunk-1mc7nfb4.js";import{u as s2}from"./chunk-dshgm836.js";import{B as c6,D as gY,F as OQ,G as XQ,H as v6,L as A6,M as P6,Q as j1,S as e4,T as $6,W as y6,Y as z2,Z as nJ,_ as tJ,ba as sJ,ca as eJ,ga as L4,ha as $9,ja as t6,ka as s6,la as mY,ma as O6,oa as z6,qa as x6}from"./chunk-n3amyjrd.js";import{ua as qJ,va as OJ,wa as zJ,za as EY}from"./chunk-b86m3bpv.js";import{Ba as b6}from"./chunk-ky9q53m7.js";import{Eb as QQ,ib as L6,jb as B6,vb as w6}from"./chunk-0cbr2gs7.js";import{Pb as W2}from"./chunk-r8wbvxn7.js";import{Gc as Y6,Hc as $Q,Ic as Z6,Kc as d2,Sc as O2,Vc as C0,gc as _6,uc as t4,zc as s4}from"./chunk-5e56atqj.js";import"./chunk-skw3b17a.js";import"./chunk-jwx10h5z.js";import{wd as PY}from"./chunk-jdb2mwbn.js";import{Ad as C1,xd as H2,yd as e2}from"./chunk-2herdn98.js";import"./chunk-h3w814js.js";import{Ed as k$,Fd as a0,Gd as Q$,Hd as jQ,Id as g$,Jd as r2,Kd as v9,Ld as Q4,Md as MJ,Nd as D9,Od as V$,Pd as l0,Qd as jY,Rd as o0,Sd as AY,Td as D8,Ud as N2,Xd as U6,ce as p0}from"./chunk-yqkyhp0e.js";import"./chunk-v508x7cg.js";import"./chunk-c9e0fbyh.js";import"./chunk-seamt0j3.js";import{se as J4}from"./chunk-33bpwkyk.js";import"./chunk-mygw13zd.js";import"./chunk-b948f9w9.js";import{Ee as Q8,He as _Y,Me as iJ,Ve as hY}from"./chunk-xrt796d6.js";import"./chunk-jzvbjn6e.js";import"./chunk-7nx0pzfk.js";import"./chunk-b9nhnzaj.js";import{pf as gQ,rf as q1}from"./chunk-je4xvy93.js";import"./chunk-zkhb55jz.js";import{tg as DY,yg as oJ,zg as VY}from"./chunk-dj99h8ca.js";import"./chunk-pfvgkexe.js";import"./chunk-qxn5bg5k.js";import{Ig as m$,Jg as a2,Kg as mQ}from"./chunk-reakyamv.js";import{Og as d0}from"./chunk-0141jad7.js";import"./chunk-eeb2945p.js";import{lh as vY,oh as t1}from"./chunk-b9vm7gns.js";import{qh as kJ,rh as SJ,uh as h1}from"./chunk-5nezhmnq.js";import"./chunk-h6a0nct6.js";import{Gh as bJ}from"./chunk-7ffdedgc.js";import{Jh as F4}from"./chunk-0a0sj79a.js";import"./chunk-sj0k8cdf.js";import{Uh as e8}from"./chunk-0ra945vt.js";import{Wh as EQ}from"./chunk-h0fh3j9w.js";import{useMemoizedFn as u8}from"ahooks";import{useEffect as S7,useState as l8}from"react";import{useMemoizedFn as s0}from"ahooks";import{Box as z$}from"ink";import{useEffect as _$,useMemo as R7,useRef as p8}from"react";import{useShallow as uY}from"zustand/react/shallow";import{useStore as xY}from"zustand";function t($){return xY(V$,$)}var lY=[],j$=()=>t(($)=>$.session.sessionId),T1=()=>t(($)=>$.session.workspaceRoot),B4=()=>t(($)=>$.session.messages),w4=()=>t(($)=>$.session.clearCount),b4=()=>t(($)=>$.session.isCompacting),A4=()=>t(($)=>$.session.tokenUsage.estimatedCostUsd),P4=()=>t(($)=>{let{totalInputTokens:Q,cacheReadTokens:Y,cacheWriteTokens:J}=$.session.tokenUsage;return L4({totalInputTokens:Q,cacheReadTokens:Y,cacheWriteTokens:J}).hitRate}),y4=()=>t(($)=>$.session.providerCircuit),R4=()=>t(($)=>$.session.providerAdmission),M4=()=>t(($)=>$.session.providerRetry),T4=()=>t(($)=>$.session.providerStall),C4=()=>t(($)=>$.session.actionStationarity),i1=()=>t(($)=>$.session.actions),I4=()=>t(($)=>{let{inputTokens:Q,maxContextTokens:Y}=$.session.tokenUsage;if(Y<=0)return 100;let J=Math.max(0,100-Q/Y*100);return Math.round(J)}),f4=()=>t(($)=>$.app.initializationStatus),k4=()=>t(($)=>$.app.initializationError),D2=()=>t(($)=>$.app.activeModal),S4=()=>t(($)=>$.app.tasks),v4=()=>t(($)=>$.app.modelEditorTarget),D4=()=>t(($)=>$.app.sessionSelectorData),V4=()=>t(($)=>$.app.awaitingSecondCtrlC),n1=()=>t(($)=>$.app.actions),V2=()=>t(($)=>$.app.sideConversation),j4=()=>t(($)=>$.app.teams),j2=()=>t(($)=>$.app.initializationStatus==="ready"),h4=()=>t(($)=>$.app.tasks.length>0),h$=()=>t(($)=>$.config.config?.permissionMode||"default"),E4=()=>t(($)=>$.config.config?.models??lY),h2=()=>t(($)=>{let Q=$.config.config;if(!Q)return;let Y=Q.currentModelId;return Q.models.find((Z)=>Z.id===Y)??Q.models[0]}),E2=()=>t(($)=>$.config.config?.currentModelId),g4=()=>t(($)=>$.config.config?.agentTeamsEnabled===!0),b0=()=>t(($)=>{return a0.getTheme()}),m4=()=>t(($)=>$.config.config?.codeTheme??"default"),e0=()=>t(($)=>$.focus.currentFocus),p4=()=>t(($)=>$.focus.actions),E$=()=>t(($)=>$.command.isProcessing),c4=()=>t(($)=>$.command.actions),g2=()=>t(($)=>$.command.pendingCommands),x4=()=>t(($)=>$.command.recoveredSteeringCount),m2=()=>t(($)=>$.app.reasoningEffort!=="off"),p2=()=>t(($)=>$.app.reasoningEffort),c2=()=>t(($)=>$.app.serviceTier),x2=()=>t(($)=>$.app.responseVerbosity),u2=()=>t(($)=>$.app.communicationStyle),u4=()=>t(($)=>$.session.currentThinkingContent),l4=()=>t(($)=>$.session.thinkingExpanded),d4=()=>t(($)=>$.session.currentStreamingMessageId),r4=()=>t(uY(($)=>({lines:$.session.currentStreamingLines,tail:$.session.currentStreamingTail,lineCount:$.session.currentStreamingLineCount,version:$.session.currentStreamingVersion}))),a4=()=>t(($)=>$.session.finalizingStreamingMessageId),o4=()=>t(($)=>$.session.historyExpanded),i4=()=>t(($)=>$.session.expandedMessageCount);import{useMemoizedFn as s1}from"ahooks";import{useEffect as c$,useRef as s8}from"react";function dY($){if(!($ instanceof Error))return"未知错误";let J=$.lastError??$;if(J.responseBody)try{let K=JSON.parse(J.responseBody)?.error?.message;if(K){let U=J.statusCode?` (HTTP ${J.statusCode})`:"";return`${K}${U}`}}catch{}let Z=$.message.match(/Last error:\s*(.+)$/);if(Z)return Z[1];return $.message}function rY($){if(!($ instanceof Error))return!1;return $.name==="AbortError"||$.message.includes("aborted")}function aY($){if(!($ instanceof Error))return!1;let Q=$.message;return Q.includes("can only concatenate str")||Q.includes("image_url")||Q.includes("multimodal")||Q.includes("vision")||Q.includes("does not support images")}function l2($){let Q=rY($),Y=aY($),J;if(Y)J="当前模型不支持图片理解功能。请切换到支持视觉能力的模型(如 Claude 4.5、GPT-5.2、Gemini 3 Pro、Qwen3-VL-Plus 等)后重试。";else J=dY($);return{displayMessage:J,isAbort:Q,isVisionNotSupported:Y}}import{appendFileSync as oY,mkdirSync as iY,writeFileSync as nY}from"node:fs";import tY from"node:os";import a8 from"node:path";var n4=null;function sY(){let $=process.env.BLADE_STORAGE_ROOT||a8.join(tY.homedir(),".blade");return a8.join($,"logs","stream-debug.log")}function eY($){if(n4===$)return;let Q=a8.dirname($);iY(Q,{recursive:!0,mode:493}),nY($,`=== Stream Debug Log Started: ${new Date().toISOString()} ===
1
+ import{b as RY,c as MY,d as TY}from"./chunk-gdyw5ns9.js";import{j as DJ,k as VJ}from"./chunk-1mc7nfb4.js";import{u as s2}from"./chunk-evzyvfpf.js";import{B as c6,D as gY,F as OQ,G as XQ,H as v6,L as A6,M as P6,Q as j1,S as e4,T as $6,W as y6,Y as z2,Z as nJ,_ as tJ,ba as sJ,ca as eJ,ga as L4,ha as $9,ja as t6,ka as s6,la as mY,ma as O6,oa as z6,qa as x6}from"./chunk-7nqgs7ks.js";import{ua as qJ,va as OJ,wa as zJ,za as EY}from"./chunk-2avf4cje.js";import{Ba as b6}from"./chunk-ky9q53m7.js";import{Eb as QQ,ib as L6,jb as B6,vb as w6}from"./chunk-wvprjxna.js";import{Pb as W2}from"./chunk-r8wbvxn7.js";import{Gc as Y6,Hc as $Q,Ic as Z6,Kc as d2,Sc as O2,Vc as C0,gc as _6,uc as t4,zc as s4}from"./chunk-ramasfqv.js";import"./chunk-skw3b17a.js";import"./chunk-jwx10h5z.js";import{wd as PY}from"./chunk-jdb2mwbn.js";import{Ad as C1,xd as H2,yd as e2}from"./chunk-jh6e9k2e.js";import"./chunk-h3w814js.js";import{Ed as k$,Fd as a0,Gd as Q$,Hd as jQ,Id as g$,Jd as r2,Kd as v9,Ld as Q4,Md as MJ,Nd as D9,Od as V$,Pd as l0,Qd as jY,Rd as o0,Sd as AY,Td as D8,Ud as N2,Xd as U6,ce as p0}from"./chunk-8zqh039s.js";import"./chunk-v508x7cg.js";import"./chunk-c9e0fbyh.js";import"./chunk-seamt0j3.js";import{se as J4}from"./chunk-33bpwkyk.js";import"./chunk-mygw13zd.js";import"./chunk-7myqyckn.js";import{Ee as Q8,He as _Y,Me as iJ,Ve as hY}from"./chunk-reb7gmf8.js";import"./chunk-jzvbjn6e.js";import"./chunk-7nx0pzfk.js";import"./chunk-b9nhnzaj.js";import{pf as gQ,rf as q1}from"./chunk-sa1pvsfw.js";import"./chunk-zkhb55jz.js";import{tg as DY,yg as oJ,zg as VY}from"./chunk-ybr0g37q.js";import"./chunk-pfvgkexe.js";import"./chunk-qxn5bg5k.js";import{Ig as m$,Jg as a2,Kg as mQ}from"./chunk-reakyamv.js";import{Og as d0}from"./chunk-0141jad7.js";import"./chunk-eeb2945p.js";import{lh as vY,oh as t1}from"./chunk-b9vm7gns.js";import{qh as kJ,rh as SJ,uh as h1}from"./chunk-5nezhmnq.js";import"./chunk-h6a0nct6.js";import{Gh as bJ}from"./chunk-zby4p535.js";import{Jh as F4}from"./chunk-0a0sj79a.js";import"./chunk-sj0k8cdf.js";import{Uh as e8}from"./chunk-0ra945vt.js";import{Wh as EQ}from"./chunk-h0fh3j9w.js";import{useMemoizedFn as u8}from"ahooks";import{useEffect as S7,useState as l8}from"react";import{useMemoizedFn as s0}from"ahooks";import{Box as z$}from"ink";import{useEffect as _$,useMemo as R7,useRef as p8}from"react";import{useShallow as uY}from"zustand/react/shallow";import{useStore as xY}from"zustand";function t($){return xY(V$,$)}var lY=[],j$=()=>t(($)=>$.session.sessionId),T1=()=>t(($)=>$.session.workspaceRoot),B4=()=>t(($)=>$.session.messages),w4=()=>t(($)=>$.session.clearCount),b4=()=>t(($)=>$.session.isCompacting),A4=()=>t(($)=>$.session.tokenUsage.estimatedCostUsd),P4=()=>t(($)=>{let{totalInputTokens:Q,cacheReadTokens:Y,cacheWriteTokens:J}=$.session.tokenUsage;return L4({totalInputTokens:Q,cacheReadTokens:Y,cacheWriteTokens:J}).hitRate}),y4=()=>t(($)=>$.session.providerCircuit),R4=()=>t(($)=>$.session.providerAdmission),M4=()=>t(($)=>$.session.providerRetry),T4=()=>t(($)=>$.session.providerStall),C4=()=>t(($)=>$.session.actionStationarity),i1=()=>t(($)=>$.session.actions),I4=()=>t(($)=>{let{inputTokens:Q,maxContextTokens:Y}=$.session.tokenUsage;if(Y<=0)return 100;let J=Math.max(0,100-Q/Y*100);return Math.round(J)}),f4=()=>t(($)=>$.app.initializationStatus),k4=()=>t(($)=>$.app.initializationError),D2=()=>t(($)=>$.app.activeModal),S4=()=>t(($)=>$.app.tasks),v4=()=>t(($)=>$.app.modelEditorTarget),D4=()=>t(($)=>$.app.sessionSelectorData),V4=()=>t(($)=>$.app.awaitingSecondCtrlC),n1=()=>t(($)=>$.app.actions),V2=()=>t(($)=>$.app.sideConversation),j4=()=>t(($)=>$.app.teams),j2=()=>t(($)=>$.app.initializationStatus==="ready"),h4=()=>t(($)=>$.app.tasks.length>0),h$=()=>t(($)=>$.config.config?.permissionMode||"default"),E4=()=>t(($)=>$.config.config?.models??lY),h2=()=>t(($)=>{let Q=$.config.config;if(!Q)return;let Y=Q.currentModelId;return Q.models.find((Z)=>Z.id===Y)??Q.models[0]}),E2=()=>t(($)=>$.config.config?.currentModelId),g4=()=>t(($)=>$.config.config?.agentTeamsEnabled===!0),b0=()=>t(($)=>{return a0.getTheme()}),m4=()=>t(($)=>$.config.config?.codeTheme??"default"),e0=()=>t(($)=>$.focus.currentFocus),p4=()=>t(($)=>$.focus.actions),E$=()=>t(($)=>$.command.isProcessing),c4=()=>t(($)=>$.command.actions),g2=()=>t(($)=>$.command.pendingCommands),x4=()=>t(($)=>$.command.recoveredSteeringCount),m2=()=>t(($)=>$.app.reasoningEffort!=="off"),p2=()=>t(($)=>$.app.reasoningEffort),c2=()=>t(($)=>$.app.serviceTier),x2=()=>t(($)=>$.app.responseVerbosity),u2=()=>t(($)=>$.app.communicationStyle),u4=()=>t(($)=>$.session.currentThinkingContent),l4=()=>t(($)=>$.session.thinkingExpanded),d4=()=>t(($)=>$.session.currentStreamingMessageId),r4=()=>t(uY(($)=>({lines:$.session.currentStreamingLines,tail:$.session.currentStreamingTail,lineCount:$.session.currentStreamingLineCount,version:$.session.currentStreamingVersion}))),a4=()=>t(($)=>$.session.finalizingStreamingMessageId),o4=()=>t(($)=>$.session.historyExpanded),i4=()=>t(($)=>$.session.expandedMessageCount);import{useMemoizedFn as s1}from"ahooks";import{useEffect as c$,useRef as s8}from"react";function dY($){if(!($ instanceof Error))return"未知错误";let J=$.lastError??$;if(J.responseBody)try{let K=JSON.parse(J.responseBody)?.error?.message;if(K){let U=J.statusCode?` (HTTP ${J.statusCode})`:"";return`${K}${U}`}}catch{}let Z=$.message.match(/Last error:\s*(.+)$/);if(Z)return Z[1];return $.message}function rY($){if(!($ instanceof Error))return!1;return $.name==="AbortError"||$.message.includes("aborted")}function aY($){if(!($ instanceof Error))return!1;let Q=$.message;return Q.includes("can only concatenate str")||Q.includes("image_url")||Q.includes("multimodal")||Q.includes("vision")||Q.includes("does not support images")}function l2($){let Q=rY($),Y=aY($),J;if(Y)J="当前模型不支持图片理解功能。请切换到支持视觉能力的模型(如 Claude 4.5、GPT-5.2、Gemini 3 Pro、Qwen3-VL-Plus 等)后重试。";else J=dY($);return{displayMessage:J,isAbort:Q,isVisionNotSupported:Y}}import{appendFileSync as oY,mkdirSync as iY,writeFileSync as nY}from"node:fs";import tY from"node:os";import a8 from"node:path";var n4=null;function sY(){let $=process.env.BLADE_STORAGE_ROOT||a8.join(tY.homedir(),".blade");return a8.join($,"logs","stream-debug.log")}function eY($){if(n4===$)return;let Q=a8.dirname($);iY(Q,{recursive:!0,mode:493}),nY($,`=== Stream Debug Log Started: ${new Date().toISOString()} ===
2
2
  `),n4=$}function o8($,Q,Y){try{let J=sY();eY(J);let Z=new Date().toISOString(),X=Y?` | ${JSON.stringify(Y)}`:"",K=`[${Z}] [${$}] ${Q}${X}
3
3
  `;oY(J,K)}catch{}}var q2=t1("UI");function Q6($,Q){let Y=!1;return(J)=>{switch(J.kind){case"content_delta":if(Y||$.signal.aborted)break;Q.contentDeltaCount++,Q.contentDeltaTotalLen+=J.delta.length,o8("loopEventHandler","onContentDelta",{callCount:Q.contentDeltaCount,deltaLen:J.delta.length,totalLen:Q.contentDeltaTotalLen}),$.streamingBuffer.batchAppendContent(J.delta);break;case"thinking_delta":if(Y||$.signal.aborted)break;if($.thinkingModeEnabled)$.streamingBuffer.batchAppendThinking(J.delta);break;case"stream_end":{if($.sessionActions.setProviderCircuit(null),$.sessionActions.setProviderRetry(null),$.sessionActions.setProviderStall(null),q2.debug("[loopEventHandler] stream_end",{contentDeltaCount:Q.contentDeltaCount,contentDeltaTotalLen:Q.contentDeltaTotalLen,streamFinalized:Y,signalAborted:$.signal.aborted}),o8("loopEventHandler","onStreamEnd",{contentDeltaCallCount:Q.contentDeltaCount,contentDeltaTotalLen:Q.contentDeltaTotalLen,streamFinalized:Y,signalAborted:$.signal.aborted}),Y||$.signal.aborted){Y=!0;break}let{extraContent:Z,extraThinking:X}=$.streamingBuffer.drainPendingBuffers(),K=$.getStreamingMessageId();if(K){if(Z)g$(K,Z);r2(K)}$.sessionActions.finalizeStreamingMessage(Z,X),Y=!0;break}case"model_fallback":Y=!0,$.sessionActions.setProviderAdmission(null),$.sessionActions.setProviderCircuit(null),$.sessionActions.setProviderRetry(null),$.sessionActions.setProviderStall(null),$.streamingBuffer.resetStreamingBuffers(),$.sessionActions.discardStreamingMessage(),$.sessionActions.setCurrentThinkingContent(null);break;case"provider_admission":{let{kind:Z,...X}=J;$.sessionActions.setProviderAdmission(J.phase==="queued"?X:null);break}case"provider_circuit":{let{kind:Z,...X}=J;$.sessionActions.setProviderCircuit(J.phase==="closed"?null:X);break}case"provider_retry":{let{kind:Z,...X}=J;$.sessionActions.setProviderRetry(J.phase==="recovered"?null:X);break}case"provider_stall":{let{kind:Z,...X}=J;$.sessionActions.setProviderStall(J.phase==="detected"?X:null);break}case"action_stationarity":{let{kind:Z,...X}=J;$.sessionActions.setActionStationarity(J.phase==="recovered"?null:X);break}case"tool_start":{let Z=J.toolCall;if(!("function"in Z))break;if(Z.function.name===d2)break;if(q2.debug("[loopEventHandler] tool_start",{toolName:Z.function.name,toolKind:J.toolKind}),["TaskCreate","TaskUpdate","TaskList"].includes(Z.function.name))break;try{let X=JSON.parse(Z.function.arguments),K=e4(Z.function.name,X);$.sessionActions.addToolMessage(K,{toolCallId:Z.id,toolName:Z.function.name,phase:"start",summary:K,params:X})}catch(X){q2.error("[loopEventHandler] onToolStart error:",X)}break}case"tool_progress":{let Z=J.toolCall;if(!("function"in Z))break;if(Z.function.name===d2)break;let X=J.update.total!==void 0?` ${Math.max(0,Math.min(100,Math.round((J.update.progress??0)/J.update.total*100)))}%`:"",K=`${Z.function.name}${X}: ${J.update.message}`;$.sessionActions.addToolMessage(K,{toolCallId:Z.id,toolName:Z.function.name,phase:"progress",summary:K,...J.update.admission?{admission:J.update.admission}:{}});break}case"tool_result":{let Z=J.toolCall;if(!("function"in Z))break;if(Z.function.name===d2)break;q2.debug("[loopEventHandler] tool_result",{toolName:Z.function.name,success:J.result.success});let X=s4($6(Z.function.name,J.result),t4);$.sessionActions.addToolMessage(X.summary,{toolCallId:Z.id,toolName:Z.function.name,phase:"complete",summary:X.summary,detail:X.detail});break}case"structured_output":$.sessionActions.replaceLastAssistantMessage(JSON.stringify(J.output,null,2));break;case"token_usage":$.sessionActions.updateTokenUsage(J.usage);break;case"compaction":if($.sessionActions.setCompacting(J.phase==="start"),J.phase==="end"){if($.sessionActions.resetContextUsage(),J.outcome!=="failed")Q.compactionCount=(Q.compactionCount??0)+1}break;case"turn_start":q2.debug("[loopEventHandler] turn_start",{turn:J.turn,maxTurns:J.maxTurns}),$.sessionActions.updateTokenUsage({turnCount:J.turn}),$.sessionActions.setProviderCircuit(null),$.sessionActions.setProviderRetry(null),$.sessionActions.setProviderStall(null),Y=!1;break;case"task_update":$.appActions.setTasks(J.tasks);break;case"mcp_catalog_changed":{let Z=`MCP catalog r${J.revision}: +${J.added.length} -${J.removed.length} ~${J.updated.length}`;$.sessionActions.addToolMessage(Z,{toolName:"MCP Catalog",phase:"complete",summary:Z,detail:[J.added.length>0?`Added: ${J.added.join(", ")}`:"",J.removed.length>0?`Removed: ${J.removed.join(", ")}`:"",J.updated.length>0?`Updated: ${J.updated.join(", ")}`:""].filter(Boolean).join(`
4
4
  `)});break}case"mcp_content_changed":{let Z=`MCP ${J.contentKind} r${J.revision}: +${J.added.length} -${J.removed.length} ~${J.updated.length}`;$.sessionActions.addToolMessage(Z,{toolName:"MCP Content",phase:"complete",summary:Z,detail:[J.added.length>0?`Added: ${J.added.join(", ")}`:"",J.removed.length>0?`Removed: ${J.removed.join(", ")}`:"",J.updated.length>0?`Updated: ${J.updated.join(", ")}`:""].filter(Boolean).join(`