blade-code 0.10.174 → 0.10.175

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 (42) hide show
  1. package/dist/blade.js +2 -2
  2. package/dist/{chunk-m9jgeshx.js → chunk-0advddh9.js} +1 -1
  3. package/dist/{chunk-f69mpn2r.js → chunk-0ppqneyk.js} +1 -1
  4. package/dist/{chunk-j2fb3jwe.js → chunk-1158v0bc.js} +1 -1
  5. package/dist/{chunk-teth5343.js → chunk-2cg1j0c0.js} +1 -1
  6. package/dist/{chunk-20x62wa4.js → chunk-3nv8d8tt.js} +1 -1
  7. package/dist/{chunk-adzzwn5t.js → chunk-3wg5e3jd.js} +1 -1
  8. package/dist/{chunk-5h0xq9f7.js → chunk-6vajt0xv.js} +1 -1
  9. package/dist/{chunk-hbhf4bnq.js → chunk-af9b48ds.js} +1 -1
  10. package/dist/{chunk-wjegeerz.js → chunk-b7wm88hh.js} +1 -1
  11. package/dist/{chunk-bjda9w4s.js → chunk-bb1yzej5.js} +1 -1
  12. package/dist/{chunk-sx68f8yz.js → chunk-bd5qs9c2.js} +1 -1
  13. package/dist/{chunk-vep4e9bn.js → chunk-bfv4myk9.js} +1 -1
  14. package/dist/{chunk-26g3nrdr.js → chunk-cgjzvp4b.js} +3 -3
  15. package/dist/{chunk-3rrcg0es.js → chunk-cp33mrea.js} +1 -1
  16. package/dist/{chunk-a3ejtsq6.js → chunk-ctzd23k7.js} +1 -1
  17. package/dist/{chunk-c9cwxadd.js → chunk-d8z2rzvm.js} +1 -1
  18. package/dist/{chunk-p3sgmn1h.js → chunk-drq0562t.js} +1 -1
  19. package/dist/{chunk-mw0xx44s.js → chunk-g0wyp0xf.js} +1 -1
  20. package/dist/{chunk-5s7dzv39.js → chunk-ge067qxz.js} +1 -1
  21. package/dist/{chunk-66d27d7t.js → chunk-gzq114cz.js} +1 -1
  22. package/dist/{chunk-1ajrbxsv.js → chunk-hb9r3g8w.js} +1 -1
  23. package/dist/chunk-htby1hak.js +1 -0
  24. package/dist/{chunk-12jy6zwj.js → chunk-jg5y7fx8.js} +1 -1
  25. package/dist/{chunk-38arrd1h.js → chunk-kcd6msyx.js} +1 -1
  26. package/dist/{chunk-fr0pnytg.js → chunk-kye8e0hy.js} +1 -1
  27. package/dist/{chunk-f2qs07mx.js → chunk-kzb3kpsc.js} +1 -1
  28. package/dist/{chunk-rejsff7v.js → chunk-q7xg2zvr.js} +1 -1
  29. package/dist/{chunk-0qtf9sss.js → chunk-qcj107rj.js} +1 -1
  30. package/dist/{chunk-0ba55nvt.js → chunk-qrn27pnc.js} +1 -1
  31. package/dist/{chunk-3cvycxre.js → chunk-qtvp638b.js} +1 -1
  32. package/dist/{chunk-dpv615sg.js → chunk-qzy09dk8.js} +1 -1
  33. package/dist/chunk-s7tgs14n.js +1 -0
  34. package/dist/{chunk-962xet8h.js → chunk-te7pky9c.js} +1 -1
  35. package/dist/{chunk-w95gvhvw.js → chunk-tjesqwfm.js} +1 -1
  36. package/dist/{chunk-6fqewq0m.js → chunk-tqxdc1jr.js} +2 -2
  37. package/dist/{chunk-jn2j7fgw.js → chunk-w4bjnh36.js} +1 -1
  38. package/dist/{chunk-7ytweagc.js → chunk-wr8tjvp8.js} +1 -1
  39. package/dist/{chunk-bx3d9jae.js → chunk-yay3bfba.js} +1 -1
  40. package/package.json +1 -1
  41. package/dist/chunk-42ec0wep.js +0 -1
  42. package/dist/chunk-x2h8hz5w.js +0 -1
package/dist/blade.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{zf as W}from"./chunk-20x62wa4.js";import{Cf as F,Df as M}from"./chunk-jj4ggb04.js";import"./chunk-3cvycxre.js";import"./chunk-v508x7cg.js";import"./chunk-t0gm0pn1.js";import"./chunk-m9jgeshx.js";import"./chunk-3y2x6fb6.js";import"./chunk-962xet8h.js";import"./chunk-kv458q06.js";import"./chunk-5v0jcyea.js";import{aj as N,bj as B}from"./chunk-2f8d0km4.js";import"./chunk-ddvdc2p0.js";import{Cj as T}from"./chunk-2mk914vk.js";import"./chunk-j8hbddjp.js";import"./chunk-4cdk4mds.js";import"./chunk-rejsff7v.js";import"./chunk-rvs364rz.js";import"./chunk-vw9paban.js";import"./chunk-4wx5sya5.js";import{Mk as J}from"./chunk-eg3ms291.js";import p from"node:path";var E=process.argv.slice(2),I=c(E),u=I!==null;if(I!==null)T.setGlobalDebug(I);function c(Q){for(let Y=0;Y<Q.length;Y+=1){let U=Q[Y];if(U==="--debug"||U==="-d"){let X=Q[Y+1];return X&&!X.startsWith("-")?X:!0}if(U.startsWith("--debug="))return U.slice(8)||!0}return null}function m(Q){return Q.length===1&&(Q[0]==="--version"||Q[0]==="-V")}function q(Q,...Y){return Q.some((U)=>Y.some((X)=>U===X||U.startsWith(`${X}=`)))}function t(Q,...Y){let U=[];for(let X=0;X<Q.length;X+=1){let G=Q[X],z=Y.find(($)=>G.startsWith(`${$}=`));if(z){let $=G.slice(z.length+1);if($)U.push($);continue}if(Y.includes(G)){let $=Q[X+1];if($&&!$.startsWith("-"))U.push($),X+=1}}return U}async function l(){if(m(E)){let{getVersion:K}=await import("./chunk-bjda9w4s.js");console.log(K());return}let Q=process.cwd(),Y=F(Q);M(Y),N(B());let U=t(E,"--plugin-dir","--pluginDir");if(U.length>0){let{configureInvocationPluginDirs:K}=await import("./chunk-adzzwn5t.js");K(U.map((Z)=>p.resolve(Q,Z)))}if(q(E,"--trust-workspace","--trustWorkspace")){let{WorkspaceTrustService:K}=await import("./chunk-66wk3exc.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-c9cwxadd.js");if(await K())return}if(W(),q(E,"--print","-p")){let{handlePrintMode:K}=await import("./chunk-f69mpn2r.js");if(await K())return}if(E.includes("--acp")){let{runAcpIntegration:K}=await import("./chunk-j2fb3jwe.js");await K();return}let[{default:X},{hideBin:G},{cliConfig:z,globalOptions:$},{loadConfiguration:_,validateOutput:D,validatePermissions:R},{browserCommands:S},{doctorCommands:k},{installCommands:O},{mcpCommands:y},{projectsCommands:V},{scheduleCommands:b},{serveCommand:P},{updateCommands:x},{webCommand:A}]=await Promise.all([import("yargs"),import("yargs/helpers"),import("./chunk-42ec0wep.js"),import("./chunk-bx3d9jae.js"),import("./chunk-kvp523gt.js"),import("./chunk-6fqewq0m.js"),import("./chunk-xmymx75h.js"),import("./chunk-sx68f8yz.js"),import("./chunk-0tzecdv3.js"),import("./chunk-a6wkam4s.js"),import("./chunk-7ytweagc.js"),import("./chunk-5h0xq9f7.js"),import("./chunk-wjegeerz.js")]),h=X(G(process.argv)).scriptName(z.scriptName).usage(z.usage).version(z.version).locale(z.locale).showHelpOnFail(z.showHelpOnFail).demandCommand(0,"").recommendCommands().strict(z.strict).parserConfiguration({"populate--":!0}).options($).middleware([_,R,D]).command(S).command(y).command(V).command(b).command(k).command(x).command(O).command(A).command(P).completion("completion",!1).help("help","Show help").alias("help","h").alias("version","V").fail((K,Z,L)=>{if(Z){if(console.error("An error occurred:"),console.error(Z.message),u&&Z.stack)console.error(`
2
+ import{zf as W}from"./chunk-3nv8d8tt.js";import{Cf as F,Df as M}from"./chunk-jj4ggb04.js";import"./chunk-qtvp638b.js";import"./chunk-v508x7cg.js";import"./chunk-t0gm0pn1.js";import"./chunk-0advddh9.js";import"./chunk-3y2x6fb6.js";import"./chunk-te7pky9c.js";import"./chunk-kv458q06.js";import"./chunk-5v0jcyea.js";import{aj as N,bj as B}from"./chunk-2f8d0km4.js";import"./chunk-ddvdc2p0.js";import{Cj as T}from"./chunk-2mk914vk.js";import"./chunk-j8hbddjp.js";import"./chunk-4cdk4mds.js";import"./chunk-q7xg2zvr.js";import"./chunk-rvs364rz.js";import"./chunk-vw9paban.js";import"./chunk-4wx5sya5.js";import{Mk as J}from"./chunk-eg3ms291.js";import p from"node:path";var E=process.argv.slice(2),I=c(E),u=I!==null;if(I!==null)T.setGlobalDebug(I);function c(Q){for(let Y=0;Y<Q.length;Y+=1){let U=Q[Y];if(U==="--debug"||U==="-d"){let X=Q[Y+1];return X&&!X.startsWith("-")?X:!0}if(U.startsWith("--debug="))return U.slice(8)||!0}return null}function m(Q){return Q.length===1&&(Q[0]==="--version"||Q[0]==="-V")}function q(Q,...Y){return Q.some((U)=>Y.some((X)=>U===X||U.startsWith(`${X}=`)))}function t(Q,...Y){let U=[];for(let X=0;X<Q.length;X+=1){let G=Q[X],z=Y.find(($)=>G.startsWith(`${$}=`));if(z){let $=G.slice(z.length+1);if($)U.push($);continue}if(Y.includes(G)){let $=Q[X+1];if($&&!$.startsWith("-"))U.push($),X+=1}}return U}async function l(){if(m(E)){let{getVersion:K}=await import("./chunk-bb1yzej5.js");console.log(K());return}let Q=process.cwd(),Y=F(Q);M(Y),N(B());let U=t(E,"--plugin-dir","--pluginDir");if(U.length>0){let{configureInvocationPluginDirs:K}=await import("./chunk-3wg5e3jd.js");K(U.map((Z)=>p.resolve(Q,Z)))}if(q(E,"--trust-workspace","--trustWorkspace")){let{WorkspaceTrustService:K}=await import("./chunk-66wk3exc.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-d8z2rzvm.js");if(await K())return}if(W(),q(E,"--print","-p")){let{handlePrintMode:K}=await import("./chunk-0ppqneyk.js");if(await K())return}if(E.includes("--acp")){let{runAcpIntegration:K}=await import("./chunk-1158v0bc.js");await K();return}let[{default:X},{hideBin:G},{cliConfig:z,globalOptions:$},{loadConfiguration:_,validateOutput:D,validatePermissions:R},{browserCommands:S},{doctorCommands:k},{installCommands:O},{mcpCommands:y},{projectsCommands:V},{scheduleCommands:b},{serveCommand:P},{updateCommands:x},{webCommand:A}]=await Promise.all([import("yargs"),import("yargs/helpers"),import("./chunk-s7tgs14n.js"),import("./chunk-yay3bfba.js"),import("./chunk-kvp523gt.js"),import("./chunk-tqxdc1jr.js"),import("./chunk-xmymx75h.js"),import("./chunk-bd5qs9c2.js"),import("./chunk-0tzecdv3.js"),import("./chunk-a6wkam4s.js"),import("./chunk-wr8tjvp8.js"),import("./chunk-6vajt0xv.js"),import("./chunk-b7wm88hh.js")]),h=X(G(process.argv)).scriptName(z.scriptName).usage(z.usage).version(z.version).locale(z.locale).showHelpOnFail(z.showHelpOnFail).demandCommand(0,"").recommendCommands().strict(z.strict).parserConfiguration({"populate--":!0}).options($).middleware([_,R,D]).command(S).command(y).command(V).command(b).command(k).command(x).command(O).command(A).command(P).completion("completion",!1).help("help","Show help").alias("help","h").alias("version","V").fail((K,Z,L)=>{if(Z){if(console.error("An error occurred:"),console.error(Z.message),u&&Z.stack)console.error(`
3
3
  Stack trace:`),console.error(Z.stack);else console.error(`
4
4
  Run with --debug to show the stack trace.`);process.exit(1)}if(K)console.error("Error: Invalid arguments:"),console.error(K),console.error(`
5
- Hint: Did you mean:`),L.showHelp(),process.exit(1)}).command("$0",!1,()=>{},async(K)=>{let Z=K._.slice(1),L=Z.length>0?Z.join(" "):void 0,f=import("./chunk-x2h8hz5w.js").then(({checkVersionOnStartup:v})=>v()),[{render:w},{createElement:j},{AppWrapper:C}]=await Promise.all([import("ink"),import("react"),import("./chunk-fr0pnytg.js")]),H={...K,initialMessage:L,debug:K.debug,print:Boolean(K.print),versionCheckPromise:f};delete H._,delete H.$0,delete H.message,w(j(C,H),{patchConsole:!0,exitOnCtrlC:!1,alternateBuffer:!1})});try{await h.parse()}catch(K){console.error("Error: Parse error:",K),process.exit(1)}}if(J.main==J.module)l().catch(console.error);export{l as main};
5
+ Hint: Did you mean:`),L.showHelp(),process.exit(1)}).command("$0",!1,()=>{},async(K)=>{let Z=K._.slice(1),L=Z.length>0?Z.join(" "):void 0,f=import("./chunk-htby1hak.js").then(({checkVersionOnStartup:v})=>v()),[{render:w},{createElement:j},{AppWrapper:C}]=await Promise.all([import("ink"),import("react"),import("./chunk-kye8e0hy.js")]),H={...K,initialMessage:L,debug:K.debug,print:Boolean(K.print),versionCheckPromise:f};delete H._,delete H.$0,delete H.message,w(j(C,H),{patchConsole:!0,exitOnCtrlC:!1,alternateBuffer:!1})});try{await h.parse()}catch(K){console.error("Error: Parse error:",K),process.exit(1)}}if(J.main==J.module)l().catch(console.error);export{l as main};
@@ -25,7 +25,7 @@ import{Dh as YO}from"./chunk-3y2x6fb6.js";import{bj as P}from"./chunk-2f8d0km4.j
25
25
  `):void 0}}async executeNotificationHooks(O,q,Q){let Z="message"in q?q.message:"";if(O.length===0)return{suppress:!1,message:Z};let Y=[],$=!1,X=Z;for(let W of O)try{let J=await this.executeHook(W,q,Q);if(!J.success){if(J.warning)Y.push(J.warning);continue}if(J.output?.suppressOutput){$=!0;break}if(J.stdout&&J.stdout.trim())X=J.stdout.trim()}catch(J){let G=J instanceof Error?J.message:String(J);Y.push(`Hook failed: ${G}`)}return{suppress:$,message:X,warning:Y.length>0?Y.join(`
26
26
  `):void 0}}async executeCompactionHooks(O,q,Q){if(O.length===0)return{blockCompaction:!1};let Z=[];for(let Y of O)try{let $=await this.executeHook(Y,q,Q);if(!$.success){if($.warning)Z.push($.warning);continue}let X=$.output?.hookSpecificOutput;if(X&&"blockCompaction"in X&&X.blockCompaction)return{blockCompaction:!0,blockReason:X.blockReason,warning:Z.length>0?Z.join(`
27
27
  `):void 0}}catch($){let X=$ instanceof Error?$.message:String($);Z.push(`Hook failed: ${X}`)}return{blockCompaction:!1,warning:Z.length>0?Z.join(`
28
- `):void 0}}async executeHook(O,q,Q){if(O.type!=="function"){let Y=await A.getInstance().getStatus(Q.projectDir,Q.config);if(Y.state!=="trusted"){let $=`${Y.trustRoot}:${Y.currentDigest}:${Y.state}`;if(!this.trustWarnings.has($)){if(this.trustWarnings.size>=512)this.trustWarnings.clear();this.trustWarnings.add($),$O.warn(`[HookTrust] Skipping configured hooks for ${Y.trustRoot}: ${Y.state}`)}return{success:!0,hook:O,warning:`Hook skipped: project hook trust is ${Y.state}`}}}let Z=this.withHookEnvironment(Q,O);if(O.type==="command")return this.executeCommandHook(O,q,Z);if(O.type==="prompt")return this.executePromptHook(O,q,Z);if(O.type==="function")return this.executeFunctionHook(O,q,Z);if(O.type==="http")return this.executeHttpHook(O,q,Z);throw Error(`Hook type ${O.type} not supported`)}async executeCommandHook(O,q,Q){let Z=(O.timeout??Q.config.defaultTimeout??60)*1000;try{let Y=await this.processExecutor.execute(O.command,q,Q,Z);return this.outputParser.parse(Y,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(Y){return{success:!1,blocking:!1,error:Y instanceof Error?Y.message:String(Y),hook:O}}}async executePromptHook(O,q,Q){let Z=(O.timeout??Q.config.defaultTimeout??60)*1000;try{let Y=await this.getOrCreateChatService(O.model,Q),$="hook_event_name"in q?String(q.hook_event_name):"Unknown",X=this.buildPromptHookSystemMessage(O,$),W=JSON.stringify(q,null,2),J=new AbortController,G=setTimeout(()=>J.abort(),Z),L;try{L=(await Y.chat([{role:"system",content:X},{role:"user",content:W}],void 0,J.signal,{providerAdmission:{sessionId:Q.sessionId,ownerId:Q.sessionId,requestClass:"background"}})).content}catch(z){if(J.signal.aborted||z instanceof Error&&z.name==="AbortError")return this.outputParser.parse({stdout:"",stderr:"",exitCode:0,timedOut:!0},O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior});throw z}finally{clearTimeout(G)}let F=this.extractJsonFromLLMResponse(L);return this.outputParser.parse({stdout:F,stderr:"",exitCode:0,timedOut:!1},O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(Y){return $O.warn(`[PromptHook] 执行失败: ${Y instanceof Error?Y.message:String(Y)}`),{success:!1,blocking:!1,error:Y instanceof Error?Y.message:String(Y),hook:O}}}async executeFunctionHook(O,q,Q){let Z=(O.timeout??10)*1000;try{let Y=await this.runFunctionWithTimeout(O.handler,q,Q,Z);if(Y===void 0||Y===null)return{success:!0,hook:O};let $={stdout:JSON.stringify(Y),stderr:"",exitCode:0,timedOut:!1};return this.outputParser.parse($,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(Y){if(Y.isTimeout){let $={stdout:"",stderr:`Function hook timeout after ${Z}ms`,exitCode:124,timedOut:!0};return this.outputParser.parse($,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}return{success:!1,blocking:!1,error:Y instanceof Error?Y.message:String(Y),hook:O}}}runFunctionWithTimeout(O,q,Q,Z){return new Promise((Y,$)=>{let X=!1,W=setTimeout(()=>{if(X)return;X=!0;let G=Object.assign(Error(`Function hook timed out after ${Z}ms`),{isTimeout:!0});$(G)},Z),J=()=>{if(X)return;X=!0,clearTimeout(W),$(Error("Function hook aborted"))};Q.abortSignal?.addEventListener("abort",J,{once:!0}),Promise.resolve().then(()=>O(q,Q)).then((G)=>{if(X)return;X=!0,clearTimeout(W),Q.abortSignal?.removeEventListener("abort",J),Y(G)},(G)=>{if(X)return;X=!0,clearTimeout(W),Q.abortSignal?.removeEventListener("abort",J),$(G)})})}async executeHttpHook(O,q,Q){let Z=(O.timeout??10)*1000,Y=O.maxResponseBytes??262144,$=Math.max(1,(O.retries??0)+1);try{e(O.url,Q.config.httpPolicy)}catch(G){return{success:!1,blocking:!0,error:G instanceof Error?G.message:String(G),hook:O}}let X={"Content-Type":"application/json",...OO(O.headers)},W=JSON.stringify(q),J;for(let G=0;G<$;G++){if(G>0){let V=Math.min(2**G*200,5000);await new Promise((B)=>setTimeout(B,V))}let L=new AbortController,F=setTimeout(()=>L.abort(),Z),z=()=>L.abort();Q.abortSignal?.addEventListener("abort",z,{once:!0});try{let V=await fetch(O.url,{method:"POST",headers:X,body:W,redirect:"manual",signal:L.signal});if(V.status>=300&&V.status<400){J=Error(`HTTP hook received redirect (${V.status}); redirects are disabled`);continue}if(!V.ok){if(J=Error(`HTTP hook returned ${V.status} ${V.statusText}`),V.status>=400&&V.status<500)break;continue}let U={stdout:await HO(V,Y),stderr:"",exitCode:0,timedOut:!1};return this.outputParser.parse(U,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(V){let B=V.name==="AbortError"||V.code==="ABORT_ERR";if(B&&Q.abortSignal?.aborted){J=Error("HTTP hook aborted by caller");break}if(B){let U={stdout:"",stderr:`HTTP hook timeout after ${Z}ms`,exitCode:124,timedOut:!0};if(G===$-1)return this.outputParser.parse(U,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior});J=Error(`HTTP hook timeout attempt ${G+1}`);continue}J=V}finally{clearTimeout(F),Q.abortSignal?.removeEventListener("abort",z)}}return{success:!1,blocking:!1,error:J?.message??"HTTP hook failed",hook:O}}async getOrCreateChatService(O,q){let Q=this.sessionResourceKey(q.sessionId,q.projectDir),Z=`${Q}\x00${O||"__default__"}`,Y=this.chatServiceCache.get(Z);if(Y)return Y;let{ensureStoreInitialized:$,getConfig:X}=await import("./chunk-1ajrbxsv.js"),{createChatServiceAsync:W}=await import("./chunk-n6mv8p83.js"),{resolveModelConfig:J}=await import("./chunk-pzqy0x7r.js"),{resolveWorkspaceModelResources:G}=await import("./chunk-66d27d7t.js");await $();let L=X();if(!L)throw Error("PromptHook: 配置未初始化");let F=this.sessionModelResources.get(Q)??await G(q.projectDir,L),z=O?F.config.models.find((B)=>B.id===O):F.config.models.find((B)=>B.id===F.config.currentModelId)??F.config.models[0];if(!z)throw Error("PromptHook: 无法获取模型配置。请确保至少配置了一个模型。");let V=await W(J(z,F.config,"off",F.catalog).chat);return this.chatServiceCache.set(Z,V),V}sessionResourceKey(O,q){return`${O}\x00${DO.resolve(q)}`}withSessionEnvironment(O){let q=this.sessionEnvironments.get(this.sessionResourceKey(O.sessionId,O.projectDir));return q?{...O,environment:q}:O}withHookEnvironment(O,q){let Q=this.withSessionEnvironment(O);if(!q.source)return Q;return{...Q,environment:{...Q.environment,BLADE_PLUGIN_ROOT:q.source.pluginRoot,CLAUDE_PLUGIN_ROOT:q.source.pluginRoot,BLADE_PLUGIN_NAME:q.source.pluginName}}}buildPromptHookSystemMessage(O,q){let Q=yO[q]||"{ ... 根据事件类型返回相应字段 }";return`你是一个代码质量评估器,作为 Hook 在 ${q} 事件中被触发。
28
+ `):void 0}}async executeHook(O,q,Q){if(O.type!=="function"){let Y=await A.getInstance().getStatus(Q.projectDir,Q.config);if(Y.state!=="trusted"){let $=`${Y.trustRoot}:${Y.currentDigest}:${Y.state}`;if(!this.trustWarnings.has($)){if(this.trustWarnings.size>=512)this.trustWarnings.clear();this.trustWarnings.add($),$O.warn(`[HookTrust] Skipping configured hooks for ${Y.trustRoot}: ${Y.state}`)}return{success:!0,hook:O,warning:`Hook skipped: project hook trust is ${Y.state}`}}}let Z=this.withHookEnvironment(Q,O);if(O.type==="command")return this.executeCommandHook(O,q,Z);if(O.type==="prompt")return this.executePromptHook(O,q,Z);if(O.type==="function")return this.executeFunctionHook(O,q,Z);if(O.type==="http")return this.executeHttpHook(O,q,Z);throw Error(`Hook type ${O.type} not supported`)}async executeCommandHook(O,q,Q){let Z=(O.timeout??Q.config.defaultTimeout??60)*1000;try{let Y=await this.processExecutor.execute(O.command,q,Q,Z);return this.outputParser.parse(Y,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(Y){return{success:!1,blocking:!1,error:Y instanceof Error?Y.message:String(Y),hook:O}}}async executePromptHook(O,q,Q){let Z=(O.timeout??Q.config.defaultTimeout??60)*1000;try{let Y=await this.getOrCreateChatService(O.model,Q),$="hook_event_name"in q?String(q.hook_event_name):"Unknown",X=this.buildPromptHookSystemMessage(O,$),W=JSON.stringify(q,null,2),J=new AbortController,G=setTimeout(()=>J.abort(),Z),L;try{L=(await Y.chat([{role:"system",content:X},{role:"user",content:W}],void 0,J.signal,{providerAdmission:{sessionId:Q.sessionId,ownerId:Q.sessionId,requestClass:"background"}})).content}catch(z){if(J.signal.aborted||z instanceof Error&&z.name==="AbortError")return this.outputParser.parse({stdout:"",stderr:"",exitCode:0,timedOut:!0},O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior});throw z}finally{clearTimeout(G)}let F=this.extractJsonFromLLMResponse(L);return this.outputParser.parse({stdout:F,stderr:"",exitCode:0,timedOut:!1},O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(Y){return $O.warn(`[PromptHook] 执行失败: ${Y instanceof Error?Y.message:String(Y)}`),{success:!1,blocking:!1,error:Y instanceof Error?Y.message:String(Y),hook:O}}}async executeFunctionHook(O,q,Q){let Z=(O.timeout??10)*1000;try{let Y=await this.runFunctionWithTimeout(O.handler,q,Q,Z);if(Y===void 0||Y===null)return{success:!0,hook:O};let $={stdout:JSON.stringify(Y),stderr:"",exitCode:0,timedOut:!1};return this.outputParser.parse($,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(Y){if(Y.isTimeout){let $={stdout:"",stderr:`Function hook timeout after ${Z}ms`,exitCode:124,timedOut:!0};return this.outputParser.parse($,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}return{success:!1,blocking:!1,error:Y instanceof Error?Y.message:String(Y),hook:O}}}runFunctionWithTimeout(O,q,Q,Z){return new Promise((Y,$)=>{let X=!1,W=setTimeout(()=>{if(X)return;X=!0;let G=Object.assign(Error(`Function hook timed out after ${Z}ms`),{isTimeout:!0});$(G)},Z),J=()=>{if(X)return;X=!0,clearTimeout(W),$(Error("Function hook aborted"))};Q.abortSignal?.addEventListener("abort",J,{once:!0}),Promise.resolve().then(()=>O(q,Q)).then((G)=>{if(X)return;X=!0,clearTimeout(W),Q.abortSignal?.removeEventListener("abort",J),Y(G)},(G)=>{if(X)return;X=!0,clearTimeout(W),Q.abortSignal?.removeEventListener("abort",J),$(G)})})}async executeHttpHook(O,q,Q){let Z=(O.timeout??10)*1000,Y=O.maxResponseBytes??262144,$=Math.max(1,(O.retries??0)+1);try{e(O.url,Q.config.httpPolicy)}catch(G){return{success:!1,blocking:!0,error:G instanceof Error?G.message:String(G),hook:O}}let X={"Content-Type":"application/json",...OO(O.headers)},W=JSON.stringify(q),J;for(let G=0;G<$;G++){if(G>0){let V=Math.min(2**G*200,5000);await new Promise((B)=>setTimeout(B,V))}let L=new AbortController,F=setTimeout(()=>L.abort(),Z),z=()=>L.abort();Q.abortSignal?.addEventListener("abort",z,{once:!0});try{let V=await fetch(O.url,{method:"POST",headers:X,body:W,redirect:"manual",signal:L.signal});if(V.status>=300&&V.status<400){J=Error(`HTTP hook received redirect (${V.status}); redirects are disabled`);continue}if(!V.ok){if(J=Error(`HTTP hook returned ${V.status} ${V.statusText}`),V.status>=400&&V.status<500)break;continue}let U={stdout:await HO(V,Y),stderr:"",exitCode:0,timedOut:!1};return this.outputParser.parse(U,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(V){let B=V.name==="AbortError"||V.code==="ABORT_ERR";if(B&&Q.abortSignal?.aborted){J=Error("HTTP hook aborted by caller");break}if(B){let U={stdout:"",stderr:`HTTP hook timeout after ${Z}ms`,exitCode:124,timedOut:!0};if(G===$-1)return this.outputParser.parse(U,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior});J=Error(`HTTP hook timeout attempt ${G+1}`);continue}J=V}finally{clearTimeout(F),Q.abortSignal?.removeEventListener("abort",z)}}return{success:!1,blocking:!1,error:J?.message??"HTTP hook failed",hook:O}}async getOrCreateChatService(O,q){let Q=this.sessionResourceKey(q.sessionId,q.projectDir),Z=`${Q}\x00${O||"__default__"}`,Y=this.chatServiceCache.get(Z);if(Y)return Y;let{ensureStoreInitialized:$,getConfig:X}=await import("./chunk-hb9r3g8w.js"),{createChatServiceAsync:W}=await import("./chunk-n6mv8p83.js"),{resolveModelConfig:J}=await import("./chunk-pzqy0x7r.js"),{resolveWorkspaceModelResources:G}=await import("./chunk-gzq114cz.js");await $();let L=X();if(!L)throw Error("PromptHook: 配置未初始化");let F=this.sessionModelResources.get(Q)??await G(q.projectDir,L),z=O?F.config.models.find((B)=>B.id===O):F.config.models.find((B)=>B.id===F.config.currentModelId)??F.config.models[0];if(!z)throw Error("PromptHook: 无法获取模型配置。请确保至少配置了一个模型。");let V=await W(J(z,F.config,"off",F.catalog).chat);return this.chatServiceCache.set(Z,V),V}sessionResourceKey(O,q){return`${O}\x00${DO.resolve(q)}`}withSessionEnvironment(O){let q=this.sessionEnvironments.get(this.sessionResourceKey(O.sessionId,O.projectDir));return q?{...O,environment:q}:O}withHookEnvironment(O,q){let Q=this.withSessionEnvironment(O);if(!q.source)return Q;return{...Q,environment:{...Q.environment,BLADE_PLUGIN_ROOT:q.source.pluginRoot,CLAUDE_PLUGIN_ROOT:q.source.pluginRoot,BLADE_PLUGIN_NAME:q.source.pluginName}}}buildPromptHookSystemMessage(O,q){let Q=yO[q]||"{ ... 根据事件类型返回相应字段 }";return`你是一个代码质量评估器,作为 Hook 在 ${q} 事件中被触发。
29
29
 
30
30
  `+`## 评估指令
31
31
  ${O.prompt}
@@ -1,4 +1,4 @@
1
- import{p as c,q as v,r as d,s as m,t as l,u as a}from"./chunk-a3ejtsq6.js";import{da as O,ka as S}from"./chunk-26g3nrdr.js";import"./chunk-g01mth5d.js";import"./chunk-teth5343.js";import"./chunk-30x3mcsb.js";import{Zb as M,hc as E}from"./chunk-f2qs07mx.js";import"./chunk-zzvs471p.js";import{he as f}from"./chunk-3rrcg0es.js";import"./chunk-53fc0yrq.js";import{Me as h}from"./chunk-y5wngtz0.js";import"./chunk-w33zjw8m.js";import{rf as I}from"./chunk-dpv615sg.js";import{tf as y,uf as R,vf as g}from"./chunk-p3sgmn1h.js";import{wf as C}from"./chunk-nheny8xp.js";import"./chunk-jj4ggb04.js";import{Tf as w}from"./chunk-3cvycxre.js";import"./chunk-v508x7cg.js";import"./chunk-t0gm0pn1.js";import"./chunk-1yq72zb7.js";import"./chunk-kqvzmnja.js";import"./chunk-0mr8nexh.js";import"./chunk-50vwafn5.js";import"./chunk-vep4e9bn.js";import"./chunk-38arrd1h.js";import"./chunk-3kszepm6.js";import"./chunk-wcps5gjm.js";import"./chunk-vbjgcn49.js";import"./chunk-06hkf59s.js";import"./chunk-m9jgeshx.js";import"./chunk-3y2x6fb6.js";import"./chunk-962xet8h.js";import{Ti as A}from"./chunk-kv458q06.js";import"./chunk-5v0jcyea.js";import{bj as P}from"./chunk-2f8d0km4.js";import"./chunk-ddvdc2p0.js";import"./chunk-2mk914vk.js";import"./chunk-j8hbddjp.js";import"./chunk-4cdk4mds.js";import"./chunk-rejsff7v.js";import"./chunk-rvs364rz.js";import"./chunk-vw9paban.js";import"./chunk-4wx5sya5.js";import"./chunk-eg3ms291.js";import s from"yargs";import{hideBin as e}from"yargs/helpers";var i=new Set(Object.values(A));function t(j){if(j&&i.has(j))return j;return}function z(j){if(j.options.outputFormat==="json")j.io.stdout.write(`${JSON.stringify({response:j.response,...j.structuredOutput?{structured_output:j.structuredOutput,output_schema_digest:j.structuredOutputSchemaDigest}:{},input:j.requestInput,model:j.options.model,timestamp:new Date().toISOString()},null,2)}
1
+ import{p as c,q as v,r as d,s as m,t as l,u as a}from"./chunk-ctzd23k7.js";import{da as O,ka as S}from"./chunk-cgjzvp4b.js";import"./chunk-g01mth5d.js";import"./chunk-2cg1j0c0.js";import"./chunk-30x3mcsb.js";import{Zb as M,hc as E}from"./chunk-kzb3kpsc.js";import"./chunk-zzvs471p.js";import{he as f}from"./chunk-cp33mrea.js";import"./chunk-53fc0yrq.js";import{Me as h}from"./chunk-y5wngtz0.js";import"./chunk-w33zjw8m.js";import{rf as I}from"./chunk-qzy09dk8.js";import{tf as y,uf as R,vf as g}from"./chunk-drq0562t.js";import{wf as C}from"./chunk-nheny8xp.js";import"./chunk-jj4ggb04.js";import{Tf as w}from"./chunk-qtvp638b.js";import"./chunk-v508x7cg.js";import"./chunk-t0gm0pn1.js";import"./chunk-1yq72zb7.js";import"./chunk-kqvzmnja.js";import"./chunk-0mr8nexh.js";import"./chunk-50vwafn5.js";import"./chunk-bfv4myk9.js";import"./chunk-kcd6msyx.js";import"./chunk-3kszepm6.js";import"./chunk-wcps5gjm.js";import"./chunk-vbjgcn49.js";import"./chunk-06hkf59s.js";import"./chunk-0advddh9.js";import"./chunk-3y2x6fb6.js";import"./chunk-te7pky9c.js";import{Ti as A}from"./chunk-kv458q06.js";import"./chunk-5v0jcyea.js";import{bj as P}from"./chunk-2f8d0km4.js";import"./chunk-ddvdc2p0.js";import"./chunk-2mk914vk.js";import"./chunk-j8hbddjp.js";import"./chunk-4cdk4mds.js";import"./chunk-q7xg2zvr.js";import"./chunk-rvs364rz.js";import"./chunk-vw9paban.js";import"./chunk-4wx5sya5.js";import"./chunk-eg3ms291.js";import s from"yargs";import{hideBin as e}from"yargs/helpers";var i=new Set(Object.values(A));function t(j){if(j&&i.has(j))return j;return}function z(j){if(j.options.outputFormat==="json")j.io.stdout.write(`${JSON.stringify({response:j.response,...j.structuredOutput?{structured_output:j.structuredOutput,output_schema_digest:j.structuredOutputSchemaDigest}:{},input:j.requestInput,model:j.options.model,timestamp:new Date().toISOString()},null,2)}
2
2
  `);else if(j.options.outputFormat==="stream-json")j.io.stdout.write(`${JSON.stringify(j.structuredOutput?{type:"structured_output",output:j.structuredOutput,schema_digest:j.structuredOutputSchemaDigest}:{type:"response",content:j.response})}
3
3
  `);else j.io.stdout.write(`${j.response}
4
4
  `)}function n(j){return j.command("* [message]","Print response and exit (useful for pipes)",(B)=>B.positional("message",{describe:"Message to process",type:"string"}).option("p",{alias:"print",describe:"Print response and exit (useful for pipes)",type:"boolean"}).option("output-format",{describe:'Output format: "text", "json", "stream-json"',type:"string",default:"text"}).option("include-partial-messages",{describe:"Include partial message chunks as they arrive",type:"boolean"}).option("input-format",{describe:'Input format: "text", "stream-json"',type:"string",default:"text"}).option("json-schema",{alias:["jsonSchema"],describe:"Inline JSON Schema for the structured final response",type:"string"}).option("output-schema",{alias:["outputSchema"],describe:"Path to a JSON Schema file for the structured final response",type:"string"}).option("model",{describe:"Model for the current session",type:"string"}).option("append-system-prompt",{describe:"Append a system prompt to the default system prompt",type:"string"}).option("system-prompt",{describe:"Replace the default system prompt",type:"string"}).option("max-turns",{alias:["maxTurns"],describe:"Maximum conversation turns (-1: unlimited, N>0: limit to N turns)",type:"number"}),async(B)=>{if(!B.p)return;let q=await o(B);process.exit(q)})}async function o(j,B=process){let q;try{await c();let D=j.forkSession!==!0&&(j.continue===!0||typeof j.resume==="string"&&j.resume.length>0)?await d({message:j.message,_:j._}):await v({message:j.message,_:j._,defaultMessage:"Hello"}),K=D===void 0,T=K?{mode:"agent",content:""}:await m(D);if(T.mode==="output"){if(T.content)B.stdout.write(`${T.content}
@@ -1,4 +1,4 @@
1
- import{v as HH,w as JH}from"./chunk-0qtf9sss.js";import{A as S,x as Cz,y as fz,z as uz}from"./chunk-jn2j7fgw.js";import{B as zH,C as xz,D as bz,E as Rz,F as Sz,G as Mz}from"./chunk-mw0xx44s.js";import{Aa as Iz,Ba as yz,Ca as hz,Da as kz,N as R,W as Az,X as Oz,da as Ez,ga as qz,ha as Tz,ka as Pz}from"./chunk-26g3nrdr.js";import"./chunk-g01mth5d.js";import{Ra as ez}from"./chunk-teth5343.js";import{Ta as Nz,Xa as i,_a as a}from"./chunk-30x3mcsb.js";import{Nb as Kz,Zb as wz,hc as l}from"./chunk-f2qs07mx.js";import{sc as d}from"./chunk-zzvs471p.js";import{$d as Dz,Cd as Bz,Md as I,Nd as v,Od as Gz,Td as Vz,Wd as jz,Yd as M,ee as Fz,he as F}from"./chunk-3rrcg0es.js";import"./chunk-53fc0yrq.js";import{Fe as _z,Me as r,Ne as Uz}from"./chunk-y5wngtz0.js";import"./chunk-w33zjw8m.js";import{yf as LH}from"./chunk-20x62wa4.js";import"./chunk-jj4ggb04.js";import{Tf as oz,Uf as nz}from"./chunk-3cvycxre.js";import"./chunk-v508x7cg.js";import{dg as e}from"./chunk-t0gm0pn1.js";import{ig as Wz}from"./chunk-1yq72zb7.js";import{qg as m}from"./chunk-kqvzmnja.js";import"./chunk-0mr8nexh.js";import{vg as sz}from"./chunk-50vwafn5.js";import"./chunk-vep4e9bn.js";import"./chunk-38arrd1h.js";import"./chunk-3kszepm6.js";import"./chunk-wcps5gjm.js";import{rh as tz}from"./chunk-vbjgcn49.js";import"./chunk-06hkf59s.js";import"./chunk-m9jgeshx.js";import"./chunk-3y2x6fb6.js";import{ui as az,xi as rz}from"./chunk-962xet8h.js";import"./chunk-kv458q06.js";import{Vi as g,Wi as Xz,Yi as c,Zi as p}from"./chunk-5v0jcyea.js";import{bj as t}from"./chunk-2f8d0km4.js";import"./chunk-ddvdc2p0.js";import{Dj as y}from"./chunk-2mk914vk.js";import"./chunk-j8hbddjp.js";import{Qj as lz,Tj as iz}from"./chunk-4cdk4mds.js";import"./chunk-rejsff7v.js";import"./chunk-rvs364rz.js";import"./chunk-vw9paban.js";import{fk as $z,gk as dz,kk as zz,ok as Hz,pk as vz,qk as Jz}from"./chunk-4wx5sya5.js";import"./chunk-eg3ms291.js";import{Readable as KH,Writable as wH}from"node:stream";import*as f from"@agentclientprotocol/sdk";import o from"node:path";import{PROTOCOL_VERSION as GH,RequestError as C}from"@agentclientprotocol/sdk";import{RequestError as gz}from"@agentclientprotocol/sdk";import{nanoid as u}from"nanoid";var G=y("Agent");function P(z){return Object.freeze({kind:"local",hostStateRoot:z,executionRoot:z,hostResourceRoot:z})}function Zz(z){if(!z)return{};return Object.fromEntries(z.map((H)=>[H.name,H.value]))}function ZH(z){if("command"in z)return{type:"stdio",command:z.command,args:z.args,env:Zz(z.env)};if("url"in z)return{type:z.type,url:z.url,headers:Zz("headers"in z?z.headers:void 0)};return null}function $H(z){let H={};for(let L of z){let Y=ZH(L);if(Y)H[L.name]=Y}return H}function cz(z){if(typeof z==="string")return z?[{type:"text",text:z}]:[];return z.flatMap((H)=>{if(H.type==="text")return H.text?[{type:"text",text:H.text}]:[];let L=H.image_url.url,Y=/^data:([^;,]+);base64,(.+)$/s.exec(L);if(!Y)return[{type:"text",text:"[Image]"}];return[{type:"image",mimeType:Y[1]??"image/png",data:Y[2]??""}]})}function XH(z){let H=Uz(z.metadata);return H?[{type:"text",text:r(H)}]:cz(z.content)}function WH(z){return[`Status: ${z.status}`,`Exit code: ${z.exitCode??"null"}`,`Duration: ${(z.durationMs/1000).toFixed(3)} seconds`].join(`
1
+ import{v as HH,w as JH}from"./chunk-qcj107rj.js";import{A as S,x as Cz,y as fz,z as uz}from"./chunk-w4bjnh36.js";import{B as zH,C as xz,D as bz,E as Rz,F as Sz,G as Mz}from"./chunk-g0wyp0xf.js";import{Aa as Iz,Ba as yz,Ca as hz,Da as kz,N as R,W as Az,X as Oz,da as Ez,ga as qz,ha as Tz,ka as Pz}from"./chunk-cgjzvp4b.js";import"./chunk-g01mth5d.js";import{Ra as ez}from"./chunk-2cg1j0c0.js";import{Ta as Nz,Xa as i,_a as a}from"./chunk-30x3mcsb.js";import{Nb as Kz,Zb as wz,hc as l}from"./chunk-kzb3kpsc.js";import{sc as d}from"./chunk-zzvs471p.js";import{$d as Dz,Cd as Bz,Md as I,Nd as v,Od as Gz,Td as Vz,Wd as jz,Yd as M,ee as Fz,he as F}from"./chunk-cp33mrea.js";import"./chunk-53fc0yrq.js";import{Fe as _z,Me as r,Ne as Uz}from"./chunk-y5wngtz0.js";import"./chunk-w33zjw8m.js";import{yf as LH}from"./chunk-3nv8d8tt.js";import"./chunk-jj4ggb04.js";import{Tf as oz,Uf as nz}from"./chunk-qtvp638b.js";import"./chunk-v508x7cg.js";import{dg as e}from"./chunk-t0gm0pn1.js";import{ig as Wz}from"./chunk-1yq72zb7.js";import{qg as m}from"./chunk-kqvzmnja.js";import"./chunk-0mr8nexh.js";import{vg as sz}from"./chunk-50vwafn5.js";import"./chunk-bfv4myk9.js";import"./chunk-kcd6msyx.js";import"./chunk-3kszepm6.js";import"./chunk-wcps5gjm.js";import{rh as tz}from"./chunk-vbjgcn49.js";import"./chunk-06hkf59s.js";import"./chunk-0advddh9.js";import"./chunk-3y2x6fb6.js";import{ui as az,xi as rz}from"./chunk-te7pky9c.js";import"./chunk-kv458q06.js";import{Vi as g,Wi as Xz,Yi as c,Zi as p}from"./chunk-5v0jcyea.js";import{bj as t}from"./chunk-2f8d0km4.js";import"./chunk-ddvdc2p0.js";import{Dj as y}from"./chunk-2mk914vk.js";import"./chunk-j8hbddjp.js";import{Qj as lz,Tj as iz}from"./chunk-4cdk4mds.js";import"./chunk-q7xg2zvr.js";import"./chunk-rvs364rz.js";import"./chunk-vw9paban.js";import{fk as $z,gk as dz,kk as zz,ok as Hz,pk as vz,qk as Jz}from"./chunk-4wx5sya5.js";import"./chunk-eg3ms291.js";import{Readable as KH,Writable as wH}from"node:stream";import*as f from"@agentclientprotocol/sdk";import o from"node:path";import{PROTOCOL_VERSION as GH,RequestError as C}from"@agentclientprotocol/sdk";import{RequestError as gz}from"@agentclientprotocol/sdk";import{nanoid as u}from"nanoid";var G=y("Agent");function P(z){return Object.freeze({kind:"local",hostStateRoot:z,executionRoot:z,hostResourceRoot:z})}function Zz(z){if(!z)return{};return Object.fromEntries(z.map((H)=>[H.name,H.value]))}function ZH(z){if("command"in z)return{type:"stdio",command:z.command,args:z.args,env:Zz(z.env)};if("url"in z)return{type:z.type,url:z.url,headers:Zz("headers"in z?z.headers:void 0)};return null}function $H(z){let H={};for(let L of z){let Y=ZH(L);if(Y)H[L.name]=Y}return H}function cz(z){if(typeof z==="string")return z?[{type:"text",text:z}]:[];return z.flatMap((H)=>{if(H.type==="text")return H.text?[{type:"text",text:H.text}]:[];let L=H.image_url.url,Y=/^data:([^;,]+);base64,(.+)$/s.exec(L);if(!Y)return[{type:"text",text:"[Image]"}];return[{type:"image",mimeType:Y[1]??"image/png",data:Y[2]??""}]})}function XH(z){let H=Uz(z.metadata);return H?[{type:"text",text:r(H)}]:cz(z.content)}function WH(z){return[`Status: ${z.status}`,`Exit code: ${z.exitCode??"null"}`,`Duration: ${(z.durationMs/1000).toFixed(3)} seconds`].join(`
2
2
  `)}function BH(z){if(!Wz(z)||z.reason!=="queue_full"||z.resource!=="pending_count"&&z.resource!=="pending_bytes")return;return{...I("capacity"),resource:z.resource}}function _H(z){if(!(z instanceof gz)||!z.data||typeof z.data!=="object")return;let H=z.data;if(!Gz(H.taskFailure)||H.toolExecutionStarted!==!1||!Number.isInteger(H.toolCallsCount)||H.toolCallsCount<0||H.outputStarted!==!1)return;return{taskFailure:H.taskFailure,toolExecutionStarted:H.toolExecutionStarted,toolCallsCount:H.toolCallsCount,outputStarted:H.outputStarted}}function UH(z){return{version:z.version,pending:z.pending,mutable:z.mutable,locked:z.locked,internal:z.internal}}class x{id;roots;connection;clientCapabilities;options;agent=null;runtime=null;pendingPrompt=null;pendingPromptCompletion=null;pendingUserShell=null;pendingUserShellCompletion=null;pendingSideConversation=null;pendingSideConversationCompletion=null;pendingResumeRequested=!1;pendingResumeAttempt=0;projectedPendingResumeInputIds=new Set;pendingResumeRecoveryStartedAt=0;pendingResumeInFlight=!1;pendingResumeScheduled=!1;pendingResumeGeneration=0;pendingResumeTimer=null;pendingResumeCompletion=null;pendingResumeNextDelayMs=null;availableCommandsTimer=null;taskStatusUnsubscribe;lastTurnActivityGeneration;lastTurnActivityRevision=-1;destroyed=!1;destroyFinished=!1;destroyPromise;serviceRegistration;messages;contextMessages;mode;updateEgress;constructor(z,H,L,Y,$={}){this.id=z;this.roots=H;this.connection=L;this.clientCapabilities=Y;this.options=$;this.messages=[...$.initialMessages??[]],this.contextMessages=[...this.messages],this.mode=this.mapPermissionModeToMode($.permissionMode),this.updateEgress=new Mz({maxPendingItems:xz,maxPendingBytes:bz,writeTimeoutMs:Rz,signal:L.signal,sizeOf:(X)=>Buffer.byteLength(JSON.stringify(X)),write:async(X)=>{await L.sessionUpdate(X)},onFailure:(X)=>this.handleUpdateEgressFailure(X)})}async refreshPersistedMessages(){let[z,H]=await Promise.all([this.loadPersistedMessages(),this.loadPersistedModelContext()]);if(z.length>0)this.messages=z;if(H.length>0)this.contextMessages=H}async loadModelContextOr(z){let H=await this.loadPersistedModelContext();return H.length>0?H:[...z]}loadPersistedMessages(){return this.roots.kind==="acp-remote"?F.loadRemoteSession(this.id,this.roots.hostStateRoot,this.roots.descriptor):F.loadSession(this.id,this.roots.hostStateRoot)}loadPersistedModelContext(){return this.roots.kind==="acp-remote"?F.loadRemoteSessionModelContext(this.id,this.roots.hostStateRoot,this.roots.descriptor):F.loadSessionModelContext(this.id,this.roots.hostStateRoot)}async persistMetadataUpdate(z,H=z){if(this.roots.kind==="acp-remote"){await F.updateRemoteSessionMetadata(this.id,this.roots.hostStateRoot,this.roots.descriptor,z);return}try{await F.updateSessionMetadata(this.id,this.roots.hostStateRoot,z)}catch(L){if(!(L instanceof Fz)&&L.code!=="ENOENT")throw L;await F.createSessionMetadata(this.id,this.roots.hostStateRoot,{taskStatus:"completed",...H})}}async persistPermissionMode(z){if(this.roots.kind==="acp-remote"){await F.updateRemoteSessionMetadata(this.id,this.roots.hostStateRoot,this.roots.descriptor,{permissionMode:z});return}await F.setSessionPermissionMode(this.id,this.roots.hostStateRoot,z)}mapPermissionModeToMode(z){switch(z){case"yolo":return"yolo";case"autoEdit":return"auto-edit";case"plan":return"plan";case"default":default:return"default"}}createAgent(){if(!this.runtime)throw Error("Session runtime is unavailable");return Pz.createWithRuntime(this.runtime,{sessionId:this.id,...this.options.taskWorktree?{toolBlacklist:["EnterWorktree","ExitWorktree"]}:{}})}async initialize(){G.debug(`[AcpSession ${this.id}] Initializing...`),await this.persistPermissionMode(this.mapModeToPermissionMode()??"default");let z=R.initializeSession(this.connection,this.id,this.clientCapabilities,this.roots.executionRoot,async(Z)=>{await this.sendUpdateAndWait(Z)},this.roots.kind==="acp-remote"?this.roots.profile:void 0);if(z)this.serviceRegistration=z;if(G.debug(`[AcpSession ${this.id}] ACP service context initialized`),this.roots.kind==="local"?await l.resolvePendingWithHandler(this.roots.hostStateRoot,this.id,{requestConfirmation:(Z)=>this.requestPermission(Z)}):!1)await this.refreshPersistedMessages();else if((this.options.initialMessages?.length??0)>0)this.contextMessages=await this.loadModelContextOr(this.options.initialMessages??[]);let L=this.options.mcpServers?$H(this.options.mcpServers):void 0,Y=R.getInstance().getTerminalService(this.id),$=this.roots.kind==="acp-remote"?{kind:"acp-remote",executionRoot:this.roots.executionRoot,resourceRoot:this.roots.hostResourceRoot,readTextFile:this.clientCapabilities?.fs?.readTextFile===!0,writeTextFile:this.clientCapabilities?.fs?.writeTextFile===!0,terminal:this.clientCapabilities?.terminal===!0,descriptor:this.roots.descriptor}:void 0;if(this.runtime=await Ez.create({sessionId:this.id,workspaceRoot:this.roots.hostStateRoot,...$?{workspace:$}:{},permissionMode:this.mapModeToPermissionMode(),...L?{mcpServers:L}:{},...this.options.taskWorktree?{taskWorktree:this.options.taskWorktree}:{},...this.options.taskIsolation?{taskIsolation:this.options.taskIsolation}:{},userShellExecutor:{execute:async(Z,_)=>{let U=await Y.execute(Z,{cwd:_.cwd,env:_.env,timeout:_.timeoutMs,signal:_.signal,allowLocalFallback:!1,onOutput:(V)=>_.onOutput?.("stdout",V)});return{exitCode:U.exitCode,stdout:U.stdout,stderr:U.stderr,...U.error?{error:U.error}:{},timedOut:U.failureKind==="timeout",aborted:U.failureKind==="aborted"}}},...(this.options.initialMessages?.length??0)>0?{sessionStart:{isResume:!0,resumeSessionId:this.id}}:{}}),this.roots.kind==="local"?await S.recoverInterrupted(this.roots.hostStateRoot,this.id,this.runtime):!1)await this.refreshPersistedMessages();if(this.agent=await this.createAgent(),this.roots.kind==="local")await yz(this.roots.hostStateRoot);G.debug(`[AcpSession ${this.id}] Agent created successfully`),this.taskStatusUnsubscribe?.(),this.taskStatusUnsubscribe=Kz.subscribe((Z)=>{if(Z.sessionId!==this.id||Z.projectPath!==this.roots.hostStateRoot)return;if(Z.type==="subagent.completion.queued"){this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/backgroundSubagentCompletion":Z.properties}}),this.requestPendingResume();return}if(Z.type==="follow_up.queue.changed"){let _=i.safeParse(Z.properties.queue);if(_.success)this.sendFollowUpQueueSnapshot(_.data);return}if(Z.type==="provider.recovery"){let _=m.safeParse(Z.properties.recovery);if(!_.success)return;this.sendProviderRecoveryProjection(_.data);return}if(Z.type==="turn.activity"){let _=a.safeParse(Z.properties.activity);if(!_.success)return;this.sendTurnActivityProjection(_.data);return}if(Z.type==="task.delivery"){if(!Z.properties.taskDelivery||typeof Z.properties.taskDelivery!=="object")return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:typeof Z.properties.updatedAt==="string"?Z.properties.updatedAt:new Date().toISOString(),_meta:{"blade/taskDelivery":Z.properties.taskDelivery,...Z.properties.taskWorktreeRemoved===!0?{"blade/taskWorktreeRemoved":!0}:{}}});return}if(Z.type.startsWith("team.")){let{teamName:_,messageId:U,content:V}=Z.properties,T=Z.properties.metadata;if(Z.type==="team.message.received"&&typeof _==="string"&&typeof U==="string"&&typeof V==="string"&&Oz(T,{messageId:U,teamName:_}))(async()=>{let E=await this.runtime?.enqueueSteering(V,{allowBeforeTurn:!0,messageId:U,origin:"team_message",metadata:T});if(!E?.accepted)return;if(E.queue)this.sendFollowUpQueueSnapshot(E.queue);if(await new Az(_,$z()).markDelivered([U]),E.delivery==="next_turn")this.requestPendingResume()})().catch((E)=>{G.warn(`[AcpSession ${this.id}] Failed to deliver teammate message`,E)});this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/teamEvent":{type:Z.type,...Z.properties}}});return}if(Z.type!=="task.status")return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:typeof Z.properties.updatedAt==="string"?Z.properties.updatedAt:new Date().toISOString(),_meta:{"blade/taskStatus":Z.properties.taskStatus,...typeof Z.properties.taskStatusReason==="string"?{"blade/taskStatusReason":Z.properties.taskStatusReason}:{},...Z.properties.taskFailure&&typeof Z.properties.taskFailure==="object"?{"blade/taskFailure":Z.properties.taskFailure}:{},...typeof Z.properties.taskStartedAt==="string"?{"blade/taskStartedAt":Z.properties.taskStartedAt}:{},...typeof Z.properties.taskCompletedAt==="string"?{"blade/taskCompletedAt":Z.properties.taskCompletedAt}:{},...Z.properties.taskDiffStat&&typeof Z.properties.taskDiffStat==="object"?{"blade/taskDiffStat":Z.properties.taskDiffStat}:{},...typeof Z.properties.taskQueuePosition==="number"?{"blade/taskQueuePosition":Z.properties.taskQueuePosition}:{},...typeof Z.properties.taskQueueDepth==="number"?{"blade/taskQueueDepth":Z.properties.taskQueueDepth}:{},...typeof Z.properties.taskConcurrencyLimit==="number"?{"blade/taskConcurrencyLimit":Z.properties.taskConcurrencyLimit}:{},...typeof Z.properties.taskInFlight==="number"?{"blade/taskInFlight":Z.properties.taskInFlight}:{}}})});let Q=await this.runtime.getGoal(),W=this.runtime.getPendingSteeringCount()>0,B=Q?.status==="active"||Q?.status==="verifying";if(W||B)this.requestPendingResume({defer:this.options.initialMessages!==void 0});else{let Z=this.runtime.getTurnRecoveryAssessment();if(Z.state!=="none")this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/turnRecovery":Z}})}}async replayHistory(){for(let H of this.messages){if(!this.canSendUpdates())return;if(!_z(H))continue;let L=H.role==="user"?"user_message_chunk":H.role==="assistant"?"agent_message_chunk":void 0;if(!L)continue;for(let Y of XH(H)){if(!this.canSendUpdates())return;if(!await this.sendUpdateAndWait({sessionUpdate:L,content:Y}))return}}let z=await this.runtime?.getGoal();if(z&&!await this.sendUpdateAndWait(this.goalSessionUpdate(z)))return;if(this.pendingResumeRequested)this.ensurePendingResumeScheduled()}sendAvailableCommandsDelayed(){if(this.destroyed||this.connection.signal.aborted)return;if(this.availableCommandsTimer!==null)clearTimeout(this.availableCommandsTimer);G.debug(`[AcpSession ${this.id}] Scheduling available commands update (500ms delay)`),this.availableCommandsTimer=setTimeout(()=>{if(this.availableCommandsTimer=null,this.destroyed||this.connection.signal.aborted)return;this.sendInitialSessionUpdates()},500)}async sendInitialSessionUpdates(){try{let z=this.runtime;if(z)this.sendFollowUpQueueSnapshot(await z.getFollowUpQueueSnapshot()),this.sendProviderRecoveryProjection(z.getProviderRecoveryProjection()),this.sendTurnActivityProjection(z.getTurnActivityProjection())}catch{G.warn("[AcpSession "+this.id+"] Initial follow-up queue unavailable")}await this.sendAvailableCommands()}async handleSlashCommand(z,H){try{G.debug(`[AcpSession ${this.id}] Executing slash command: ${z}`);let L={cwd:this.roots.hostStateRoot,workspaceKind:this.roots.kind,surface:"acp",workspaceRoot:this.roots.hostStateRoot,sessionId:this.id,messages:[...this.contextMessages],rewind:{listCheckpoints:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listRewindCheckpoints()},execute:async(Q)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let W=await this.runtime.rewindSession(Q);return this.messages=[...W.messages],this.contextMessages=await this.loadModelContextOr(W.messages),await this.agent?.destroy(),this.agent=await this.createAgent(),W}},reasoning:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getReasoningConfiguration()},set:async(Q)=>{if(await this.setReasoningEffort(Q),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getReasoningConfiguration()}},serviceTier:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getServiceTierConfiguration()},set:async(Q)=>{if(await this.setServiceTier(Q),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getServiceTierConfiguration()}},responseVerbosity:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getResponseVerbosityConfiguration()},set:async(Q)=>{if(await this.setResponseVerbosity(Q),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getResponseVerbosityConfiguration()}},communicationStyle:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getCommunicationStyleConfiguration()},set:async(Q)=>{if(await this.setCommunicationStyle(Q),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getCommunicationStyleConfiguration()}},...this.roots.kind==="local"?{subagents:{list:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listSubagents()},resume:async(Q,W)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let B=!1,Z,_=(V)=>{this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:V.id,status:V.status==="completed"?"completed":"failed",content:[{type:"content",content:{type:"text",text:V.result?.message||V.result?.error||`Subagent ${V.status}`}}]})},U=this.runtime.resumeSubagent({agentId:Q,prompt:W,onCompleted:(V)=>{if(B)_(V);else Z=V}});if(this.sendUpdate({sessionUpdate:"tool_call",toolCallId:U.session.id,status:"in_progress",title:`Resuming ${U.session.subagentType} subagent`,content:[{type:"content",content:{type:"text",text:`Resumed from ${U.source.id} at depth ${U.session.resumeDepth}`}}],kind:this.mapToolKind("readonly")}),B=!0,Z)_(Z);return U}}}:{},...this.roots.kind==="local"?{mcp:{getCatalog:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpContentCatalog()},refresh:async(Q)=>{if(!this.runtime)throw Error("Session runtime is unavailable");await this.runtime.refreshMcpContentCatalogs(Q)},getPrompt:async(Q,W,B)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpPrompt(Q,W,B)},complete:async(Q,W,B)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.completeMcpArgument(Q,W,B)},listTasks:async(Q)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listMcpTasks(Q)},getTask:async(Q)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpTask(Q)},cancelTask:async(Q,W)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.cancelMcpTask(Q,W)},getLogs:async(Q,W)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpLogs(Q,W)},setLoggingLevel:async(Q,W)=>{if(!this.runtime)throw Error("Session runtime is unavailable");await this.runtime.setMcpLoggingLevel(Q,W)},getInstructions:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpInstructions()}}}:{},sideConversation:{ask:async(Q,W)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.askSideQuestion(Q,{signal:W})}},...this.roots.kind==="local"?{codeReview:{run:async(Q,W)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let B=await S.start({sessionId:this.id,projectPath:this.roots.hostStateRoot,runtime:this.runtime,request:Q,signal:W,onEvent:(U)=>{if(U.kind==="tool_start")this.sendUpdate({sessionUpdate:"tool_call",toolCallId:U.toolCall.id,status:"in_progress",title:`Review: ${U.toolCall.function.name}`,content:[],kind:this.mapToolKind(U.toolKind)});else if(U.kind==="tool_result")this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:U.toolCall.id,status:U.result.success?"completed":"failed",content:[]})}}),Z=await B.completion,_=(await S.list(this.roots.hostStateRoot,this.id)).find((U)=>U.start.reviewId===B.reviewId);if(!_)throw Error(`Review not found: ${B.reviewId}`);return await this.refreshPersistedMessages(),{reviewId:B.reviewId,status:Z.status,findings:Z.findings.length,content:Bz(_.start,Z)}}}}:{},signal:H,acp:{sendMessage:(Q)=>{this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:Q}})},sendToolStart:(Q,W,B)=>{let Z=`tool_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,_=this.mapToolKind(B);this.sendUpdate({sessionUpdate:"tool_call",toolCallId:Z,status:"in_progress",title:`${Q}`,content:[{type:"content",content:{type:"text",text:JSON.stringify(W,null,2)}}],kind:_})},sendToolResult:(Q,W)=>{if(W.summary)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:W.summary}})}}},Y=await hz(z,L),$=Y.data?.action;if($==="start_goal"||$==="resume_goal")this.requestPendingResume();if($==="rewind_session"&&Array.isArray(Y.data?.messages))this.messages=[...Y.data.messages],this.contextMessages=await this.loadModelContextOr(Y.data.messages);if((Y.message==="compact_completed"||Y.message==="compact_fallback")&&Y.data?.compactedMessages){this.contextMessages=[...Y.data.compactedMessages];let Q=await this.loadPersistedMessages();if(Q.length>0)this.messages=Q}let X=Y.content||Y.message;if(X)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:X}});if(Y.error)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] ${Y.error}`}});return await this.flushUpdates(),{stopReason:Y.success?"end_turn":"cancelled"}}catch(L){if(H.aborted||L instanceof Error&&L.name==="AbortError")return{stopReason:"cancelled"};return G.error(`[AcpSession ${this.id}] Slash command error:`,L),this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] 命令执行失败: ${L instanceof Error?L.message:"未知错误"}`}}),{stopReason:"cancelled"}}}async handleSideConversationCommand(z){if(this.pendingSideConversation)throw Error("A side conversation is already running");let H=new AbortController,L,Y=new Promise(($)=>{L=$});this.pendingSideConversation=H,this.pendingSideConversationCompletion=Y;try{return await this.handleSlashCommand(z,H.signal)}catch($){if(H.signal.aborted||$ instanceof Error&&$.name==="AbortError")return{stopReason:"cancelled"};throw $}finally{if(L(),this.pendingSideConversationCompletion===Y)this.pendingSideConversationCompletion=null;if(this.pendingSideConversation===H){if(this.pendingSideConversation=null,!this.destroyed&&this.pendingResumeRequested)this.ensurePendingResumeScheduled()}}}async sendAvailableCommands(){try{let z=kz(this.roots.hostStateRoot,this.runtime?.getAgentResources(),this.roots.kind),H=["model","permissions","theme","config","exit","ide"],Y=z.filter(($)=>!H.includes($.name)&&($.name!=="team"||this.runtime?.getConfig().agentTeamsEnabled===!0)).map(($)=>{let X;if($.usage){let Q=$.usage.replace(/^\/\w+\s*/,"").trim();if(Q)X=Q}if($.aliases?.length){let Q=`Aliases: ${$.aliases.join(", ")}`;X=X?`${X} | ${Q}`:Q}return{name:$.name,description:$.description,input:X?{hint:X}:void 0}});G.info(`[AcpSession ${this.id}] Sending available commands: ${JSON.stringify(Y.map(($)=>$.name))}`),this.sendUpdate({sessionUpdate:"available_commands_update",availableCommands:Y}),G.info(`[AcpSession ${this.id}] Sent ${Y.length} available commands`)}catch(z){G.error(`[AcpSession ${this.id}] Failed to send available commands:`,z)}}async prompt(z,H={}){if(R.setCurrentSession(this.id),!this.agent||!this.runtime)throw Error("Session not initialized");let L=this.resolvePrompt(z.prompt),Y=L.content,$=L.displayText,X=z._meta?.outputSchema??(H.pendingInputOnly?this.runtime.getPendingSteeringMessages().find((j)=>j.outputSchema)?.outputSchema:void 0),Q;if(X!==void 0)Q=Dz(X).schema;if($.trimStart().startsWith("!")){if(Q)throw Error("Output schemas cannot be combined with user shell commands");return this.handleUserShellCommand($)}let W=Nz($);if(W){if(Q)throw Error("Output schemas cannot be combined with slash commands");if(Array.isArray(Y)&&Y.some((j)=>j.type==="image_url"))throw Error("Side conversations do not accept image attachments");return this.handleSideConversationCommand(W.question?`/btw ${W.question}`:"/btw")}if(this.pendingPrompt){if(Q)throw Error("Wait for the active turn to finish before setting an output schema");if(/^\/goal(?:\s|$)/i.test($.trim()))return this.handleSlashCommand($,this.pendingPrompt.signal);let j=await this.runtime.enqueueSteering(Y,{allowBeforeTurn:!0});if(!j.accepted)throw Error(j.reason==="queue_full"?"Active turn steering queue is full":"Active turn is no longer steerable");if(G.debug(`[AcpSession ${this.id}] Queued steering for active turn (${j.queued})`),this.sendFollowUpQueueSnapshot(j.queue??await this.runtime.getFollowUpQueueSnapshot()),j.delivery==="next_turn")this.requestPendingResume();return{stopReason:"end_turn"}}let B=new AbortController,Z=()=>{B.abort(H.abortSignal?.reason)};if(H.abortSignal?.aborted)Z();else H.abortSignal?.addEventListener("abort",Z,{once:!0});let _=!1,U=!1,V=!1,T,E=new Promise((j)=>{T=j});this.pendingPrompt=B,this.pendingPromptCompletion=E;try{if(G.debug(`[AcpSession ${this.id}] Received prompt: ${$.slice(0,100)}...`),Iz($)){if(Q)throw Error("Output schemas cannot be combined with slash commands");return await this.handleSlashCommand($,B.signal)}let j={sessionId:this.id,userId:"acp-user",workspaceRoot:this.roots.hostStateRoot,executionRoot:this.roots.executionRoot,workspaceKind:this.roots.kind,messages:[...this.contextMessages],signal:B.signal,permissionMode:this.mapModeToPermissionMode(),onPermissionModeChange:async(J)=>{this.mode=this.mapPermissionModeToMode(J),this.sendUpdate({sessionUpdate:"current_mode_update",currentModeId:this.mode})},...this.options.taskWorktree?{worktreeActive:!0}:{},confirmationHandler:{requestConfirmation:async(J)=>{return this.requestPermission(J)}}},N=await wz(this.agent.chatStream(Y,j,{pendingInputOnly:H.pendingInputOnly,goalContinuationOnly:H.goalContinuationOnly,outputSchema:Q}),async(J)=>{switch(J.kind){case"content_delta":if(Q)break;if(J.delta.length>0)U=!0;this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:J.delta}});break;case"thinking_delta":if(J.delta.length>0)U=!0;this.sendUpdate({sessionUpdate:"agent_thought_chunk",content:{type:"text",text:J.delta}});break;case"tool_start":{V=!0;let D=J.toolCall,A=D.function.name;if(A===M)break;let q=this.mapToolKind(J.toolKind),K=`Executing ${A}`;if(A==="Task"&&"function"in D)try{let b=JSON.parse(D.function.arguments),w=b.resume_from??b.resume;if(typeof w==="string")K=`Resuming ${String(b.subagent_type||"subagent")} from ${w}`}catch{}this.sendUpdate({sessionUpdate:"tool_call",toolCallId:D.id,status:"in_progress",title:K,content:[],kind:q});break}case"tool_progress":{V=!0;let D=J.toolCall;if(D.function.name===M)break;this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:D.id,status:"in_progress",content:[{type:"content",content:{type:"text",text:J.update.message}}]});break}case"tool_result":{V=!0;let D=J.toolCall;if(D.function.name===M)break;let A=J.result,q=[],K=A.metadata;if(K?.kind==="patch"&&Array.isArray(K.changes))for(let w of K.changes){if(!w||typeof w!=="object"||!("path"in w)||typeof w.path!=="string")continue;q.push({type:"diff",path:w.path,oldText:"oldContent"in w&&typeof w.oldContent==="string"?w.oldContent:null,newText:"newContent"in w&&typeof w.newContent==="string"?w.newContent:null})}else if(K?.kind==="edit"&&typeof K.file_path==="string"&&typeof K.oldContent==="string"&&(typeof K.newContent==="string"||K.newContent===void 0))q.push({type:"diff",path:K.file_path,oldText:K.oldContent,newText:K.newContent??null});else{let w=D.function.name,QH=Tz(jz(qz(w,A),Vz));q.push({type:"content",content:{type:"text",text:QH}})}if(D.function.name==="Task"&&(K?.verificationVerdict==="pass"||K?.verificationVerdict==="fail"||K?.verificationVerdict==="partial"))q.unshift({type:"content",content:{type:"text",text:`Verification result: ${K.verificationVerdict.toUpperCase()}`}});let b=A.success?"completed":"failed";this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:D.id,status:b,content:q});break}case"structured_output":U=!0,this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:JSON.stringify(J.output)}});break;case"mcp_catalog_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP catalog r${J.revision} (${J.serverName}): +${J.added.length} -${J.removed.length} ~${J.updated.length}
3
3
  `}});break;case"mcp_content_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP ${J.contentKind} r${J.revision} (${J.serverName}): +${J.added.length} -${J.removed.length} ~${J.updated.length}
4
4
  `}});break;case"mcp_resource_updated":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP resource updated r${J.revision} (${J.serverName}): ${J.uri}
@@ -1,4 +1,4 @@
1
- import{sc as Xt,tc as En,uc as yn,vc as bn}from"./chunk-zzvs471p.js";import{zh as Bt}from"./chunk-m9jgeshx.js";import{$h as wn,Eh as xt,Fh as vi,Gh as sn,Hh as zt,Ih as U,Jh as en,Kh as gt,Lh as mt,Nh as rn,Oh as Tn,Ph as B,Qh as dn,Rh as on,Sh as pn,Th as lt,Uh as un,Vh as cn,Wh as Mn,Yh as S,ai as Gt,bi as Ut,ci as h,di as Ht}from"./chunk-962xet8h.js";import{bj as It}from"./chunk-2f8d0km4.js";import{Fj as X,Hj as x}from"./chunk-2mk914vk.js";import{Xj as tn,Yj as nn}from"./chunk-rejsff7v.js";import{Mk as ns}from"./chunk-eg3ms291.js";import{EventEmitter as fs}from"events";import Un from"node:path";function hn(t){if(t===void 0)return"undefined";if(typeof t==="string")return t;try{let i=JSON.stringify(t);return i===void 0?String(t):i}catch{return String(t)}}function An(t){let i=t;switch(t.code){case"type":return`类型错误:${t.message}`;case"required":return"缺少必需参数";case"minLength":return`字符串过短:${t.message}`;case"maxLength":return`字符串过长:${t.message}`;case"minimum":case"exclusiveMinimum":return`数值太小:${t.message}`;case"maximum":case"exclusiveMaximum":return`数值太大:${t.message}`;case"minItems":return`数组元素过少:${t.message}`;case"maxItems":return`数组元素过多:${t.message}`;case"format":return`格式错误:${t.message}`;case"enum":return`必须是枚举允许的值之一:${t.message}`;case"const":return`必须是指定的字面量值:${t.message}`;case"additionalProperties":case"unevaluatedProperties":return`包含未知参数:${t.message}`;case"anyOf":case"oneOf":return"不符合任何有效的类型定义";case"~refine":return t.message||"自定义验证失败";default:return t.message||`验证失败:${hn(i)}`}}class Jt extends Error{issues;type;constructor(t,i,n="validation_error"){super(t);this.issues=i;this.type=n;this.name="ToolValidationError"}}function Vt(t,i){let n=X(t,i);if(n.success)return n.data;let s=n.error.issues.map((r)=>({field:r.path.length>0?r.path.join("."):"root",message:An(r),value:r.value})),e=s.length===1?`参数验证失败 [${s[0].field}]: ${s[0].message}`:`参数验证失败 (${s.length} 个错误):
1
+ import{sc as Xt,tc as En,uc as yn,vc as bn}from"./chunk-zzvs471p.js";import{zh as Bt}from"./chunk-0advddh9.js";import{$h as wn,Eh as xt,Fh as vi,Gh as sn,Hh as zt,Ih as U,Jh as en,Kh as gt,Lh as mt,Nh as rn,Oh as Tn,Ph as B,Qh as dn,Rh as on,Sh as pn,Th as lt,Uh as un,Vh as cn,Wh as Mn,Yh as S,ai as Gt,bi as Ut,ci as h,di as Ht}from"./chunk-te7pky9c.js";import{bj as It}from"./chunk-2f8d0km4.js";import{Fj as X,Hj as x}from"./chunk-2mk914vk.js";import{Xj as tn,Yj as nn}from"./chunk-q7xg2zvr.js";import{Mk as ns}from"./chunk-eg3ms291.js";import{EventEmitter as fs}from"events";import Un from"node:path";function hn(t){if(t===void 0)return"undefined";if(typeof t==="string")return t;try{let i=JSON.stringify(t);return i===void 0?String(t):i}catch{return String(t)}}function An(t){let i=t;switch(t.code){case"type":return`类型错误:${t.message}`;case"required":return"缺少必需参数";case"minLength":return`字符串过短:${t.message}`;case"maxLength":return`字符串过长:${t.message}`;case"minimum":case"exclusiveMinimum":return`数值太小:${t.message}`;case"maximum":case"exclusiveMaximum":return`数值太大:${t.message}`;case"minItems":return`数组元素过少:${t.message}`;case"maxItems":return`数组元素过多:${t.message}`;case"format":return`格式错误:${t.message}`;case"enum":return`必须是枚举允许的值之一:${t.message}`;case"const":return`必须是指定的字面量值:${t.message}`;case"additionalProperties":case"unevaluatedProperties":return`包含未知参数:${t.message}`;case"anyOf":case"oneOf":return"不符合任何有效的类型定义";case"~refine":return t.message||"自定义验证失败";default:return t.message||`验证失败:${hn(i)}`}}class Jt extends Error{issues;type;constructor(t,i,n="validation_error"){super(t);this.issues=i;this.type=n;this.name="ToolValidationError"}}function Vt(t,i){let n=X(t,i);if(n.success)return n.data;let s=n.error.issues.map((r)=>({field:r.path.length>0?r.path.join("."):"root",message:An(r),value:r.value})),e=s.length===1?`参数验证失败 [${s[0].field}]: ${s[0].message}`:`参数验证失败 (${s.length} 个错误):
2
2
  ${s.map((r)=>` - ${r.field}: ${r.message}`).join(`
3
3
  `)}`;throw new Jt(e,s)}function st(t){if(!t||typeof t!=="object")return;let i=t;if(i.type==="object"&&i.properties)i.required??=[],i.additionalProperties??=!1;for(let n of Object.values(i))if(Array.isArray(n))for(let s of n)st(s);else st(n)}function et(t){let i=JSON.parse(JSON.stringify(t,(n,s)=>n.startsWith("~")?void 0:s));return st(i),i}class rt{toolName;params;executeFn;descriptionFn;affectedPathsFn;isRetrySafe;constructor(t,i,n,s,e,r=!1){this.toolName=t;this.params=i;this.executeFn=n;this.descriptionFn=s;this.affectedPathsFn=e;this.isRetrySafe=r}getDescription(){if(this.descriptionFn)return this.descriptionFn(this.params);return`执行工具: ${this.toolName}`}getAffectedPaths(){if(this.affectedPathsFn)return this.affectedPathsFn(this.params);return[]}async execute(t,i,n){let s={signal:t,updateOutput:i,...n};return this.executeFn(this.params,s)}}function jt(t){return{name:t.name,displayName:t.displayName,kind:t.kind,isConcurrencySafe:t.isConcurrencySafe??!1,isRetrySafe:t.isRetrySafe??!1,parallelism:t.parallelism??(t.isConcurrencySafe?"shared":"exclusive"),strict:t.strict??!1,description:t.description,version:t.version||"1.0.0",category:t.category,tags:t.tags||[],getFunctionDeclaration(){let i=et(t.schema),n=t.description.short;if(t.description.long)n+=`
4
4
 
@@ -1,4 +1,4 @@
1
- import{Pf as N}from"./chunk-3cvycxre.js";import{zh as $}from"./chunk-m9jgeshx.js";import{bj as _}from"./chunk-2f8d0km4.js";import{Bj as Y,Dj as Z}from"./chunk-2mk914vk.js";function X(){if(process.stdin.isTTY&&typeof process.stdin.setRawMode==="function")try{process.stdin.setRawMode(!1)}catch{}process.stdout.write("\x1B[<u"),process.stdout.write("\x1B[>4;0m"),process.stdout.write("\x1B[?2004l"),process.stdout.write("\x1B[?1004l"),process.stdout.write("\x1B[?1l\x1B>"),process.stdout.write("\x1B[?25h"),process.stdout.write("\x1B[0m")}var z=Z("Service");function E(b){switch(b){case"SIGINT":return"ctrl_c";case"esc":return"esc";case"uncaughtException":case"unhandledRejection":return"error";case"SIGTERM":case"normal":default:return"user_exit"}}class B{static instance=null;cleanupHandlers=[];isShuttingDown=!1;initialized=!1;lastSigintTime=0;SIGINT_DOUBLE_CLICK_WINDOW=3000;constructor(){}static getInstance(){if(!B.instance)B.instance=new B;return B.instance}initialize(){if(this.initialized){z.debug("[GracefulShutdown] 已初始化,跳过重复初始化");return}process.on("uncaughtException",(b)=>{this.handleFatalError("uncaughtException",b)}),process.on("unhandledRejection",(b)=>{let q=b instanceof Error?b:Error(String(b));this.handleFatalError("unhandledRejection",q)}),process.on("SIGTERM",()=>{z.info("[GracefulShutdown] 收到 SIGTERM 信号"),this.shutdown("SIGTERM",0)}),process.on("SIGINT",()=>{let b=Date.now();if(b-this.lastSigintTime<this.SIGINT_DOUBLE_CLICK_WINDOW)z.info("[GracefulShutdown] 收到第二次 SIGINT 信号,执行退出"),this.shutdown("SIGINT",0);else z.info("[GracefulShutdown] 收到第一次 SIGINT 信号,再按一次退出"),this.lastSigintTime=b,console.log(`
1
+ import{Pf as N}from"./chunk-qtvp638b.js";import{zh as $}from"./chunk-0advddh9.js";import{bj as _}from"./chunk-2f8d0km4.js";import{Bj as Y,Dj as Z}from"./chunk-2mk914vk.js";function X(){if(process.stdin.isTTY&&typeof process.stdin.setRawMode==="function")try{process.stdin.setRawMode(!1)}catch{}process.stdout.write("\x1B[<u"),process.stdout.write("\x1B[>4;0m"),process.stdout.write("\x1B[?2004l"),process.stdout.write("\x1B[?1004l"),process.stdout.write("\x1B[?1l\x1B>"),process.stdout.write("\x1B[?25h"),process.stdout.write("\x1B[0m")}var z=Z("Service");function E(b){switch(b){case"SIGINT":return"ctrl_c";case"esc":return"esc";case"uncaughtException":case"unhandledRejection":return"error";case"SIGTERM":case"normal":default:return"user_exit"}}class B{static instance=null;cleanupHandlers=[];isShuttingDown=!1;initialized=!1;lastSigintTime=0;SIGINT_DOUBLE_CLICK_WINDOW=3000;constructor(){}static getInstance(){if(!B.instance)B.instance=new B;return B.instance}initialize(){if(this.initialized){z.debug("[GracefulShutdown] 已初始化,跳过重复初始化");return}process.on("uncaughtException",(b)=>{this.handleFatalError("uncaughtException",b)}),process.on("unhandledRejection",(b)=>{let q=b instanceof Error?b:Error(String(b));this.handleFatalError("unhandledRejection",q)}),process.on("SIGTERM",()=>{z.info("[GracefulShutdown] 收到 SIGTERM 信号"),this.shutdown("SIGTERM",0)}),process.on("SIGINT",()=>{let b=Date.now();if(b-this.lastSigintTime<this.SIGINT_DOUBLE_CLICK_WINDOW)z.info("[GracefulShutdown] 收到第二次 SIGINT 信号,执行退出"),this.shutdown("SIGINT",0);else z.info("[GracefulShutdown] 收到第一次 SIGINT 信号,再按一次退出"),this.lastSigintTime=b,console.log(`
2
2
  再按一次 Ctrl+C 退出
3
3
  `)}),this.initialized=!0,z.debug("[GracefulShutdown] 全局错误处理器已初始化")}registerCleanup(b){return this.cleanupHandlers.push(b),z.debug(`[GracefulShutdown] 注册清理函数,当前共 ${this.cleanupHandlers.length} 个`),()=>{let q=this.cleanupHandlers.indexOf(b);if(q!==-1)this.cleanupHandlers.splice(q,1),z.debug(`[GracefulShutdown] 取消注册清理函数,剩余 ${this.cleanupHandlers.length} 个`)}}handleFatalError(b,q){if(this.isShuttingDown){console.error(`[GracefulShutdown] 退出过程中发生额外错误 (${b}):`,q);return}if(console.error(""),console.error("═".repeat(60)),console.error(`Uncaught error (${b})`),console.error("═".repeat(60)),console.error(""),console.error("错误信息:",q.message),console.error(""),q.stack)console.error("堆栈跟踪:"),console.error(q.stack);console.error(""),console.error("═".repeat(60)),console.error(""),this.shutdown(b,1)}async shutdown(b,q=0){if(this.isShuttingDown){z.debug("[GracefulShutdown] 已在退出过程中,跳过重复退出");return}this.isShuttingDown=!0;try{N().command.actions.abort("process-shutdown")}catch(A){z.warn("[GracefulShutdown] Failed to abort the active command",A)}z.info(`[GracefulShutdown] 开始优雅退出 (原因: ${b})`);let Q=setTimeout(()=>{X(),process.exit(q)},5000);Q.unref?.();let U=4000,K;try{await Promise.race([this.runCleanupHandlers(),new Promise((A,J)=>{K=setTimeout(()=>{J(Error(`清理超时 (${U}ms)`))},U),K.unref?.()})])}catch(A){console.error("[GracefulShutdown] 清理过程中发生错误:",A)}finally{if(K)clearTimeout(K)}try{let A=$.getInstance(),J=N(),V=J.session?.sessionId||"unknown",W=J.session?.workspaceRoot||_();if(A.isEnabled(W,V)){let v=J.config?.config?.permissionMode||"default";await A.executeSessionEndHooks(E(b),{projectDir:W,sessionId:V,permissionMode:v})}}catch(A){console.error("[GracefulShutdown] SessionEnd hooks 执行失败:",A)}try{await Y()}catch{}clearTimeout(Q),X(),setTimeout(()=>{process.exit(q)},100)}async runCleanupHandlers(){let b=[...this.cleanupHandlers].reverse();for(let q of b)try{let F=q();if(F instanceof Promise)await F}catch(F){console.error("[GracefulShutdown] 清理函数执行失败:",F)}}isExiting(){return this.isShuttingDown}reset(){this.isShuttingDown=!1,this.cleanupHandlers=[],this.initialized=!1}}var O=()=>{return B.getInstance()},y=(b)=>{return O().registerCleanup(b)},j=()=>{O().initialize()},C=(b=0)=>{O().shutdown("normal",b)};
4
4
  export{O as xf,y as yf,j as zf,C as Af};
@@ -1 +1 @@
1
- import{$g as j,Sg as a,Tg as b,Ug as c,Vg as d,Wg as e,Xg as f,Yg as g,Zg as h,_g as i,ah as k}from"./chunk-38arrd1h.js";import"./chunk-3kszepm6.js";import"./chunk-wcps5gjm.js";import"./chunk-vbjgcn49.js";import"./chunk-06hkf59s.js";import"./chunk-m9jgeshx.js";import"./chunk-3y2x6fb6.js";import"./chunk-962xet8h.js";import"./chunk-kv458q06.js";import"./chunk-5v0jcyea.js";import"./chunk-2f8d0km4.js";import"./chunk-ddvdc2p0.js";import"./chunk-2mk914vk.js";import"./chunk-j8hbddjp.js";import"./chunk-4cdk4mds.js";import"./chunk-rejsff7v.js";import"./chunk-rvs364rz.js";import"./chunk-vw9paban.js";import"./chunk-4wx5sya5.js";import"./chunk-eg3ms291.js";export{g as withWorkspaceAgentResources,i as snapshotWorkspaceAgentResources,f as resolveWorkspaceAgentResources,k as resetWorkspaceAgentResources,d as refreshWorkspaceCommunicationStyles,h as getWorkspaceAgentResourceCacheStats,j as createEmptySessionAgentResources,e as configureInvocationPluginDirs,c as WorkspaceAgentResourceCapacityError,a as MAX_RESIDENT_WORKSPACE_AGENT_RESOURCES,b as MAX_ACTIVE_WORKSPACE_AGENT_RESOURCES};
1
+ import{$g as j,Sg as a,Tg as b,Ug as c,Vg as d,Wg as e,Xg as f,Yg as g,Zg as h,_g as i,ah as k}from"./chunk-kcd6msyx.js";import"./chunk-3kszepm6.js";import"./chunk-wcps5gjm.js";import"./chunk-vbjgcn49.js";import"./chunk-06hkf59s.js";import"./chunk-0advddh9.js";import"./chunk-3y2x6fb6.js";import"./chunk-te7pky9c.js";import"./chunk-kv458q06.js";import"./chunk-5v0jcyea.js";import"./chunk-2f8d0km4.js";import"./chunk-ddvdc2p0.js";import"./chunk-2mk914vk.js";import"./chunk-j8hbddjp.js";import"./chunk-4cdk4mds.js";import"./chunk-q7xg2zvr.js";import"./chunk-rvs364rz.js";import"./chunk-vw9paban.js";import"./chunk-4wx5sya5.js";import"./chunk-eg3ms291.js";export{g as withWorkspaceAgentResources,i as snapshotWorkspaceAgentResources,f as resolveWorkspaceAgentResources,k as resetWorkspaceAgentResources,d as refreshWorkspaceCommunicationStyles,h as getWorkspaceAgentResourceCacheStats,j as createEmptySessionAgentResources,e as configureInvocationPluginDirs,c as WorkspaceAgentResourceCapacityError,a as MAX_RESIDENT_WORKSPACE_AGENT_RESOURCES,b as MAX_ACTIVE_WORKSPACE_AGENT_RESOURCES};
@@ -1 +1 @@
1
- import{k as o}from"./chunk-hbhf4bnq.js";import"./chunk-rejsff7v.js";import"./chunk-eg3ms291.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{k as o}from"./chunk-af9b48ds.js";import"./chunk-q7xg2zvr.js";import"./chunk-eg3ms291.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,2 +1,2 @@
1
- import{Xj as I}from"./chunk-rejsff7v.js";import{Mk as f}from"./chunk-eg3ms291.js";import*as j from"fs/promises";import*as S from"path";import X from"semver";import{ProxyAgent as R,fetch as k}from"undici";function x(){return process.env.HTTPS_PROXY||process.env.HTTP_PROXY||process.env.https_proxy||process.env.http_proxy}function L(){let z=x();if(z)try{return new R(z)}catch(q){console.warn(`[proxyFetch] Invalid proxy URL: ${z}`)}return}async function F(z,q,Z){let{timeout:W=30000,signal:J,...Q}=q;if(J?.aborted)throw new DOMException("The operation was aborted.","AbortError");let Y=L(),$=new AbortController,w=!1,y=setTimeout(()=>{w=!0,$.abort()},W),T=()=>$.abort();J?.addEventListener("abort",T);let D;try{let B={method:Q.method,headers:Q.headers,body:Q.body,signal:$.signal,dispatcher:Y};return D=await k(z.toString(),B),await Z(D)}catch(B){if(B instanceof Error&&B.name==="AbortError"){if(w)throw Error(`Request timeout after ${W}ms`);throw B}throw B}finally{if(clearTimeout(y),J?.removeEventListener("abort",T),$.abort(),D?.body&&!D.body.locked)await D.body.cancel().catch(()=>{return});await Y?.destroy?.().catch(()=>{return})}}var O="blade-code",G="https://cdn.jsdelivr.net/npm/blade-code@latest/CHANGELOG.md",H=S.join(process.env.HOME||process.env.USERPROFILE||".",".blade"),N=S.join(H,"version-cache.json"),_=3600000,g=`https://registry.npmjs.org/${O}/latest`,M=null;async function P(){try{if(process.env.BLADE_VERSION)return process.env.BLADE_VERSION;return I()}catch{return"unknown"}}async function b(){try{let z=await j.readFile(N,"utf-8"),q=JSON.parse(z);if(Date.now()-q.checkedAt<_)return q;return{...q,checkedAt:0}}catch{return null}}async function K(z){try{await j.mkdir(H,{recursive:!0,mode:493}),await j.writeFile(N,JSON.stringify(z,null,2))}catch{}}async function E(){try{return await F(g,{timeout:5000,headers:{Accept:"application/json"}},async(z)=>{if(!z.ok)return null;let q=await z.json();if(!q||typeof q!=="object"||!("version"in q))return null;return typeof q.version==="string"&&X.valid(q.version)?q.version:null})}catch{return null}}async function A(z=!1){let q=await P(),Z=G;if(q==="unknown")return{currentVersion:q,latestVersion:null,hasUpdate:!1,shouldPrompt:!1,releaseNotesUrl:Z,error:"Unable to determine current version"};let W=await b(),J=W?.skipUntilVersion,Q=null;if(!z&&W?.latestVersion&&W.checkedAt>0)Q=W.latestVersion;else if(Q=await E(),J=(await b())?.skipUntilVersion??J,Q)await K({latestVersion:Q,checkedAt:Date.now(),skipUntilVersion:J});else if(W?.latestVersion)await K({checkedAt:0,skipUntilVersion:J});if(!Q||!X.valid(Q))return{currentVersion:q,latestVersion:null,hasUpdate:!1,shouldPrompt:!1,releaseNotesUrl:Z,error:"Unable to check for updates"};if(X.lt(Q,q))Q=q,await K({latestVersion:Q,checkedAt:Date.now(),skipUntilVersion:J});let Y=X.gt(Q,q),$=Y;if(Y&&J)$=X.gt(Q,J);return{currentVersion:q,latestVersion:Q,hasUpdate:Y,shouldPrompt:$,releaseNotesUrl:Z}}async function V(z){let q=await b();await K({latestVersion:q?.latestVersion??z,checkedAt:q?.checkedAt||Date.now(),skipUntilVersion:z})}function v(){return`npm install -g ${O}@latest --registry https://registry.npmjs.org`}async function p(){let{spawn:z}=await import("child_process");return new Promise((q)=>{let Z=v(),W=z(Z,{stdio:"inherit",shell:!0});W.on("close",(J)=>{if(J===0)q({success:!0,message:"Upgrade successful! Please restart blade."});else q({success:!1,message:`Upgrade failed (exit code: ${J})`})}),W.on("error",(J)=>{q({success:!1,message:`Upgrade failed: ${J.message}`})})})}async function h(){try{let z=await b();if(!z?.latestVersion||!X.valid(z.latestVersion)||!z.checkedAt){if(!M)M=A(!0).then(()=>{return},()=>{return}).finally(()=>{M=null});return null}let q=await P();if(!X.valid(q)||!X.gt(z.latestVersion,q)||z.skipUntilVersion&&X.valid(z.skipUntilVersion)&&!X.gt(z.latestVersion,z.skipUntilVersion))return null;return{currentVersion:q,latestVersion:z.latestVersion,hasUpdate:!0,shouldPrompt:!0,releaseNotesUrl:G}}catch{return null}}
1
+ import{Xj as I}from"./chunk-q7xg2zvr.js";import{Mk as f}from"./chunk-eg3ms291.js";import*as j from"fs/promises";import*as S from"path";import X from"semver";import{ProxyAgent as R,fetch as k}from"undici";function x(){return process.env.HTTPS_PROXY||process.env.HTTP_PROXY||process.env.https_proxy||process.env.http_proxy}function L(){let z=x();if(z)try{return new R(z)}catch(q){console.warn(`[proxyFetch] Invalid proxy URL: ${z}`)}return}async function F(z,q,Z){let{timeout:W=30000,signal:J,...Q}=q;if(J?.aborted)throw new DOMException("The operation was aborted.","AbortError");let Y=L(),$=new AbortController,w=!1,y=setTimeout(()=>{w=!0,$.abort()},W),T=()=>$.abort();J?.addEventListener("abort",T);let D;try{let B={method:Q.method,headers:Q.headers,body:Q.body,signal:$.signal,dispatcher:Y};return D=await k(z.toString(),B),await Z(D)}catch(B){if(B instanceof Error&&B.name==="AbortError"){if(w)throw Error(`Request timeout after ${W}ms`);throw B}throw B}finally{if(clearTimeout(y),J?.removeEventListener("abort",T),$.abort(),D?.body&&!D.body.locked)await D.body.cancel().catch(()=>{return});await Y?.destroy?.().catch(()=>{return})}}var O="blade-code",G="https://cdn.jsdelivr.net/npm/blade-code@latest/CHANGELOG.md",H=S.join(process.env.HOME||process.env.USERPROFILE||".",".blade"),N=S.join(H,"version-cache.json"),_=3600000,g=`https://registry.npmjs.org/${O}/latest`,M=null;async function P(){try{if(process.env.BLADE_VERSION)return process.env.BLADE_VERSION;return I()}catch{return"unknown"}}async function b(){try{let z=await j.readFile(N,"utf-8"),q=JSON.parse(z);if(Date.now()-q.checkedAt<_)return q;return{...q,checkedAt:0}}catch{return null}}async function K(z){try{await j.mkdir(H,{recursive:!0,mode:493}),await j.writeFile(N,JSON.stringify(z,null,2))}catch{}}async function E(){try{return await F(g,{timeout:5000,headers:{Accept:"application/json"}},async(z)=>{if(!z.ok)return null;let q=await z.json();if(!q||typeof q!=="object"||!("version"in q))return null;return typeof q.version==="string"&&X.valid(q.version)?q.version:null})}catch{return null}}async function A(z=!1){let q=await P(),Z=G;if(q==="unknown")return{currentVersion:q,latestVersion:null,hasUpdate:!1,shouldPrompt:!1,releaseNotesUrl:Z,error:"Unable to determine current version"};let W=await b(),J=W?.skipUntilVersion,Q=null;if(!z&&W?.latestVersion&&W.checkedAt>0)Q=W.latestVersion;else if(Q=await E(),J=(await b())?.skipUntilVersion??J,Q)await K({latestVersion:Q,checkedAt:Date.now(),skipUntilVersion:J});else if(W?.latestVersion)await K({checkedAt:0,skipUntilVersion:J});if(!Q||!X.valid(Q))return{currentVersion:q,latestVersion:null,hasUpdate:!1,shouldPrompt:!1,releaseNotesUrl:Z,error:"Unable to check for updates"};if(X.lt(Q,q))Q=q,await K({latestVersion:Q,checkedAt:Date.now(),skipUntilVersion:J});let Y=X.gt(Q,q),$=Y;if(Y&&J)$=X.gt(Q,J);return{currentVersion:q,latestVersion:Q,hasUpdate:Y,shouldPrompt:$,releaseNotesUrl:Z}}async function V(z){let q=await b();await K({latestVersion:q?.latestVersion??z,checkedAt:q?.checkedAt||Date.now(),skipUntilVersion:z})}function v(){return`npm install -g ${O}@latest --registry https://registry.npmjs.org`}async function p(){let{spawn:z}=await import("child_process");return new Promise((q)=>{let Z=v(),W=z(Z,{stdio:"inherit",shell:!0});W.on("close",(J)=>{if(J===0)q({success:!0,message:"Upgrade successful! Please restart blade."});else q({success:!1,message:`Upgrade failed (exit code: ${J})`})}),W.on("error",(J)=>{q({success:!1,message:`Upgrade failed: ${J.message}`})})})}async function h(){try{let z=await b();if(!z?.latestVersion||!X.valid(z.latestVersion)||!z.checkedAt){if(!M)M=A(!0).then(()=>{return},()=>{return}).finally(()=>{M=null});return null}let q=await P();if(!X.valid(q)||!X.gt(z.latestVersion,q)||z.skipUntilVersion&&X.valid(z.skipUntilVersion)&&!X.gt(z.latestVersion,z.skipUntilVersion))return null;return{currentVersion:q,latestVersion:z.latestVersion,hasUpdate:!0,shouldPrompt:!0,releaseNotesUrl:G}}catch{return null}}
2
2
  export{A as k,V as l,v as m,p as n,h as o};
@@ -1,4 +1,4 @@
1
- import{a as T,b as W,c as X,d as Y}from"./chunk-5s7dzv39.js";import"./chunk-w95gvhvw.js";import"./chunk-zj1g4nbq.js";import"./chunk-0qtf9sss.js";import"./chunk-jn2j7fgw.js";import"./chunk-mw0xx44s.js";import"./chunk-26g3nrdr.js";import"./chunk-g01mth5d.js";import"./chunk-teth5343.js";import"./chunk-30x3mcsb.js";import"./chunk-f2qs07mx.js";import"./chunk-zzvs471p.js";import"./chunk-3rrcg0es.js";import"./chunk-53fc0yrq.js";import"./chunk-y5wngtz0.js";import"./chunk-w33zjw8m.js";import{yf as R}from"./chunk-20x62wa4.js";import"./chunk-jj4ggb04.js";import{Uf as Q}from"./chunk-3cvycxre.js";import"./chunk-v508x7cg.js";import"./chunk-t0gm0pn1.js";import"./chunk-1yq72zb7.js";import"./chunk-kqvzmnja.js";import"./chunk-0mr8nexh.js";import"./chunk-50vwafn5.js";import"./chunk-vep4e9bn.js";import"./chunk-38arrd1h.js";import"./chunk-3kszepm6.js";import"./chunk-wcps5gjm.js";import"./chunk-vbjgcn49.js";import"./chunk-06hkf59s.js";import"./chunk-m9jgeshx.js";import"./chunk-3y2x6fb6.js";import"./chunk-962xet8h.js";import"./chunk-kv458q06.js";import"./chunk-5v0jcyea.js";import"./chunk-2f8d0km4.js";import"./chunk-ddvdc2p0.js";import"./chunk-2mk914vk.js";import"./chunk-j8hbddjp.js";import"./chunk-4cdk4mds.js";import{Xj as M}from"./chunk-rejsff7v.js";import"./chunk-rvs364rz.js";import"./chunk-vw9paban.js";import"./chunk-4wx5sya5.js";import"./chunk-eg3ms291.js";import m from"chalk";import K from"open";var A=`
1
+ import{a as T,b as W,c as X,d as Y}from"./chunk-ge067qxz.js";import"./chunk-tjesqwfm.js";import"./chunk-zj1g4nbq.js";import"./chunk-qcj107rj.js";import"./chunk-w4bjnh36.js";import"./chunk-g0wyp0xf.js";import"./chunk-cgjzvp4b.js";import"./chunk-g01mth5d.js";import"./chunk-2cg1j0c0.js";import"./chunk-30x3mcsb.js";import"./chunk-kzb3kpsc.js";import"./chunk-zzvs471p.js";import"./chunk-cp33mrea.js";import"./chunk-53fc0yrq.js";import"./chunk-y5wngtz0.js";import"./chunk-w33zjw8m.js";import{yf as R}from"./chunk-3nv8d8tt.js";import"./chunk-jj4ggb04.js";import{Uf as Q}from"./chunk-qtvp638b.js";import"./chunk-v508x7cg.js";import"./chunk-t0gm0pn1.js";import"./chunk-1yq72zb7.js";import"./chunk-kqvzmnja.js";import"./chunk-0mr8nexh.js";import"./chunk-50vwafn5.js";import"./chunk-bfv4myk9.js";import"./chunk-kcd6msyx.js";import"./chunk-3kszepm6.js";import"./chunk-wcps5gjm.js";import"./chunk-vbjgcn49.js";import"./chunk-06hkf59s.js";import"./chunk-0advddh9.js";import"./chunk-3y2x6fb6.js";import"./chunk-te7pky9c.js";import"./chunk-kv458q06.js";import"./chunk-5v0jcyea.js";import"./chunk-2f8d0km4.js";import"./chunk-ddvdc2p0.js";import"./chunk-2mk914vk.js";import"./chunk-j8hbddjp.js";import"./chunk-4cdk4mds.js";import{Xj as M}from"./chunk-q7xg2zvr.js";import"./chunk-rvs364rz.js";import"./chunk-vw9paban.js";import"./chunk-4wx5sya5.js";import"./chunk-eg3ms291.js";import m from"chalk";import K from"open";var A=`
2
2
  ____ _ _
3
3
  | __ )| | __ _ __| | ___
4
4
  | _ \\| |/ _\` |/ _\` |/ _ \\
@@ -1 +1 @@
1
- import{$j as f,Wj as a,Xj as b,Yj as c,Zj as d,_j as e}from"./chunk-rejsff7v.js";import"./chunk-eg3ms291.js";export{b as getVersion,c as getPackageName,a as getPackageInfo,e as getFormattedVersion,d as getDescription,f as getCopyright};
1
+ import{$j as f,Wj as a,Xj as b,Yj as c,Zj as d,_j as e}from"./chunk-q7xg2zvr.js";import"./chunk-eg3ms291.js";export{b as getVersion,c as getPackageName,a as getPackageInfo,e as getFormattedVersion,d as getDescription,f as getCopyright};
@@ -1,4 +1,4 @@
1
- import{Ra as H}from"./chunk-teth5343.js";import"./chunk-zzvs471p.js";import"./chunk-53fc0yrq.js";import{Yf as $,cg as T}from"./chunk-3cvycxre.js";import"./chunk-v508x7cg.js";import"./chunk-t0gm0pn1.js";import"./chunk-m9jgeshx.js";import"./chunk-3y2x6fb6.js";import"./chunk-962xet8h.js";import"./chunk-kv458q06.js";import"./chunk-5v0jcyea.js";import{bj as k}from"./chunk-2f8d0km4.js";import"./chunk-ddvdc2p0.js";import"./chunk-2mk914vk.js";import"./chunk-j8hbddjp.js";import"./chunk-4cdk4mds.js";import"./chunk-rejsff7v.js";import"./chunk-rvs364rz.js";import"./chunk-vw9paban.js";import"./chunk-4wx5sya5.js";import"./chunk-eg3ms291.js";import U from"os";import J from"path";function X(z){return typeof z==="string"?z:void 0}function N(z){if(!Array.isArray(z))return;let q=[];for(let K of z)if(typeof K==="string")q.push(K);else if(K!=null)q.push(String(K));return q}function b(){console.log(`
1
+ import{Ra as H}from"./chunk-2cg1j0c0.js";import"./chunk-zzvs471p.js";import"./chunk-53fc0yrq.js";import{Yf as $,cg as T}from"./chunk-qtvp638b.js";import"./chunk-v508x7cg.js";import"./chunk-t0gm0pn1.js";import"./chunk-0advddh9.js";import"./chunk-3y2x6fb6.js";import"./chunk-te7pky9c.js";import"./chunk-kv458q06.js";import"./chunk-5v0jcyea.js";import{bj as k}from"./chunk-2f8d0km4.js";import"./chunk-ddvdc2p0.js";import"./chunk-2mk914vk.js";import"./chunk-j8hbddjp.js";import"./chunk-4cdk4mds.js";import"./chunk-q7xg2zvr.js";import"./chunk-rvs364rz.js";import"./chunk-vw9paban.js";import"./chunk-4wx5sya5.js";import"./chunk-eg3ms291.js";import U from"os";import J from"path";function X(z){return typeof z==="string"?z:void 0}function N(z){if(!Array.isArray(z))return;let q=[];for(let K of z)if(typeof K==="string")q.push(K);else if(K!=null)q.push(String(K));return q}function b(){console.log(`
2
2
  blade mcp
3
3
  `),console.log(`管理 MCP 服务器
4
4
  `),console.log("Commands:"),console.log(" blade mcp add <name> <commandOrUrl> [args...] 添加 MCP 服务器"),console.log(" blade mcp remove <name> 删除 MCP 服务器 [aliases: rm]"),console.log(" blade mcp list 列出所有 MCP 服务器并检查健康状态 [aliases: ls]"),console.log(" blade mcp get <name> 获取服务器详情"),console.log(" blade mcp login <name> 登录远程 MCP OAuth"),console.log(" blade mcp logout <name> 清除远程 MCP OAuth 凭证"),console.log(` blade mcp add-json <name> <json> 从 JSON 字符串添加服务器
@@ -1,2 +1,2 @@
1
- import{Ri as I}from"./chunk-962xet8h.js";import{Oj as G,Pj as H}from"./chunk-j8hbddjp.js";import B 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 D(b){return A(b)}function E(b,q){let w=new G(q?.credentials??H().credentials);return w.configureModelProviders(b.modelProviders,b.models),w}async function Q(b,q){let w=B.resolve(b),x=I.getInstance(),[J,K]=await Promise.all([x.loadWorkspaceModelConfig(w,q),x.loadWorkspaceRuntimeSettings(w,q)]),z={...D(q),...J,...K},F=E(z);return x.validateConfig(z,F),{projectRoot:w,config:z,catalog:F}}function T(b){let q=D(b.config);return{projectRoot:B.resolve(b.projectRoot),config:q,catalog:E(q,b.catalog)}}function U(b,q){let w=D(q);return{projectRoot:B.resolve(b),config:w,catalog:E(w)}}
1
+ import{Ri as I}from"./chunk-te7pky9c.js";import{Oj as G,Pj as H}from"./chunk-j8hbddjp.js";import B 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 D(b){return A(b)}function E(b,q){let w=new G(q?.credentials??H().credentials);return w.configureModelProviders(b.modelProviders,b.models),w}async function Q(b,q){let w=B.resolve(b),x=I.getInstance(),[J,K]=await Promise.all([x.loadWorkspaceModelConfig(w,q),x.loadWorkspaceRuntimeSettings(w,q)]),z={...D(q),...J,...K},F=E(z);return x.validateConfig(z,F),{projectRoot:w,config:z,catalog:F}}function T(b){let q=D(b.config);return{projectRoot:B.resolve(b.projectRoot),config:q,catalog:E(q,b.catalog)}}function U(b,q){let w=D(q);return{projectRoot:B.resolve(b),config:w,catalog:E(w)}}
2
2
  export{D as xg,Q as yg,T as zg,U as Ag};
@@ -1,4 +1,4 @@
1
- import{Ga as W3}from"./chunk-g01mth5d.js";import{Ja as T,Ka as $$,Pa as UW,Qa as fY,Ra as e0}from"./chunk-teth5343.js";import{$a as BX,Sa as Y5,Va as pZ,Za as tZ,_a as HX,bb as nW,db as aW,eb as A9,wb as sW}from"./chunk-30x3mcsb.js";import{Ab as p7,Bb as D2,Cb as GY,Db as x1,Eb as s7,Fb as DY,Gb as ZY,Hb as qY,Ib as wY,Jb as zQ,Lb as YX,Nb as V0,Pb as _2,Sb as p4,Ub as _Z,Vb as l4,Wb as i4,Yb as MJ,Zb as R$,dc as sX,ec as G8,fc as oX,gc as JX,ic as u1,jc as kX,oc as rY,rc as nY,xb as s5,yb as g7,zb as J1}from"./chunk-f2qs07mx.js";import{$c as r8,$d as iY,Ac as k3,Bc as T1,Cc as ZJ,Dc as _0,Ec as S2,Fc as N1,Gc as S6,Hc as f9,Ic as m4,Jc as c4,Kc as YY,Lc as QY,Mc as TX,Nc as X3,Nd as V8,Oc as A1,Pc as Y3,Pd as f0,Qc as i8,Qd as b$,Rc as $1,Sc as Z1,Tc as l2,Uc as p2,Vc as i2,Wc as g6,Xc as u6,Xd as YW,Yc as d2,Yd as UX,Zc as H3,_c as m2,ad as M1,bd as e1,cd as c2,dd as $2,ed as Z2,ee as PX,fd as d6,fe as SX,gd as J2,hd as m6,he as s,id as c6,jd as k$,kd as p6,ld as O3,md as r2,nd as l6,od as i6,pd as r6,qd as n6,rd as N3,sd as b3,ud as j3,xc as v$,yc as CX,zc as r3}from"./chunk-3rrcg0es.js";import{ie as l,je as GQ,ke as KQ,le as hJ,ne as F2}from"./chunk-53fc0yrq.js";import{Ge as P9,He as J$,Ie as q2,Je as $9,Ke as RX,Le as fX,Ue as $V,ff as ZV,pe as tW,se as eW}from"./chunk-y5wngtz0.js";import{Bf as NJ,Cf as LJ}from"./chunk-jj4ggb04.js";import{Of as r4,Pf as q0,Qf as d,Tf as j0,Uf as P4,Vf as L2,Wf as G1,Xf as CZ,Yf as R1,Zf as pY,cg as B2}from"./chunk-3cvycxre.js";import{dg as d1}from"./chunk-t0gm0pn1.js";import{hg as jZ,ig as lY,ng as mY,og as cX,pg as S4}from"./chunk-1yq72zb7.js";import{qg as nZ}from"./chunk-kqvzmnja.js";import{tg as m0,ug as O1}from"./chunk-0mr8nexh.js";import{vg as eX}from"./chunk-50vwafn5.js";import{Ag as jX,xg as OX,yg as NX,zg as bX}from"./chunk-vep4e9bn.js";import{$g as MX,Bg as I4,Cg as h4,Dg as g4,Fg as u4,Gg as d4,Hg as _1,Ig as _Q,Jg as I$,Kg as j$,Lg as G$,Mg as $5,Ng as V2,Og as H8,Pg as l1,Qg as i1,Rg as AX,Vg as J9,Xg as c0,Yg as f$,_g as k4,ah as vX}from"./chunk-38arrd1h.js";import{ch as D1,eh as T$,fh as O4}from"./chunk-3kszepm6.js";import{gh as d3,hh as W2,ih as m3,jh as s2,kh as c3,lh as p3,mh as Z4,nh as $4,oh as l3,ph as i3,qh as e6}from"./chunk-wcps5gjm.js";import{rh as LW,th as EX,uh as W8,vh as bJ}from"./chunk-vbjgcn49.js";import{xh as L9,zh as x0}from"./chunk-m9jgeshx.js";import{Ah as E6,Bh as R9,Ch as A6,Dh as r1}from"./chunk-3y2x6fb6.js";import{Ci as SY,Di as kY,Ei as vY,Fh as XJ,Fi as yY,Gi as AZ,Hi as xY,Ii as B1,Ji as IY,Kh as WJ,Ki as hY,Li as gY,Mh as D9,Ni as t3,Pi as xX,Qi as LX,Rh as zW,Ri as B0,Vh as VJ,Xh as wX,Zh as HY,_h as BY,pi as h1,si as $Y}from"./chunk-962xet8h.js";import{Ui as L$}from"./chunk-kv458q06.js";import{Wi as $X,Yi as ZX}from"./chunk-5v0jcyea.js";import{$i as X4,bj as C}from"./chunk-2f8d0km4.js";import{Dj as e,Fj as a6,Gj as X2,Hj as K,Ij as R3,Jj as P,Kj as u}from"./chunk-2mk914vk.js";import{Oj as FX,Pj as _X}from"./chunk-j8hbddjp.js";import{Qj as NW,Tj as FW}from"./chunk-4cdk4mds.js";import{Xj as AW}from"./chunk-rejsff7v.js";import{bk as yX,ck as a0}from"./chunk-rvs364rz.js";import{Bk as E$,Gk as u3,fk as t,gk as N$,hk as D$,ik as t1,jk as o9,kk as u2,lk as X$,mk as e7,pk as I6,yk as P6}from"./chunk-4wx5sya5.js";import{Mk as Y$}from"./chunk-eg3ms291.js";import{randomUUID as M8}from"crypto";import{randomUUID as LV}from"node:crypto";var DV=String.raw`
1
+ import{Ga as W3}from"./chunk-g01mth5d.js";import{Ja as T,Ka as $$,Pa as UW,Qa as fY,Ra as e0}from"./chunk-2cg1j0c0.js";import{$a as BX,Sa as Y5,Va as pZ,Za as tZ,_a as HX,bb as nW,db as aW,eb as A9,wb as sW}from"./chunk-30x3mcsb.js";import{Ab as p7,Bb as D2,Cb as GY,Db as x1,Eb as s7,Fb as DY,Gb as ZY,Hb as qY,Ib as wY,Jb as zQ,Lb as YX,Nb as V0,Pb as _2,Sb as p4,Ub as _Z,Vb as l4,Wb as i4,Yb as MJ,Zb as R$,dc as sX,ec as G8,fc as oX,gc as JX,ic as u1,jc as kX,oc as rY,rc as nY,xb as s5,yb as g7,zb as J1}from"./chunk-kzb3kpsc.js";import{$c as r8,$d as iY,Ac as k3,Bc as T1,Cc as ZJ,Dc as _0,Ec as S2,Fc as N1,Gc as S6,Hc as f9,Ic as m4,Jc as c4,Kc as YY,Lc as QY,Mc as TX,Nc as X3,Nd as V8,Oc as A1,Pc as Y3,Pd as f0,Qc as i8,Qd as b$,Rc as $1,Sc as Z1,Tc as l2,Uc as p2,Vc as i2,Wc as g6,Xc as u6,Xd as YW,Yc as d2,Yd as UX,Zc as H3,_c as m2,ad as M1,bd as e1,cd as c2,dd as $2,ed as Z2,ee as PX,fd as d6,fe as SX,gd as J2,hd as m6,he as s,id as c6,jd as k$,kd as p6,ld as O3,md as r2,nd as l6,od as i6,pd as r6,qd as n6,rd as N3,sd as b3,ud as j3,xc as v$,yc as CX,zc as r3}from"./chunk-cp33mrea.js";import{ie as l,je as GQ,ke as KQ,le as hJ,ne as F2}from"./chunk-53fc0yrq.js";import{Ge as P9,He as J$,Ie as q2,Je as $9,Ke as RX,Le as fX,Ue as $V,ff as ZV,pe as tW,se as eW}from"./chunk-y5wngtz0.js";import{Bf as NJ,Cf as LJ}from"./chunk-jj4ggb04.js";import{Of as r4,Pf as q0,Qf as d,Tf as j0,Uf as P4,Vf as L2,Wf as G1,Xf as CZ,Yf as R1,Zf as pY,cg as B2}from"./chunk-qtvp638b.js";import{dg as d1}from"./chunk-t0gm0pn1.js";import{hg as jZ,ig as lY,ng as mY,og as cX,pg as S4}from"./chunk-1yq72zb7.js";import{qg as nZ}from"./chunk-kqvzmnja.js";import{tg as m0,ug as O1}from"./chunk-0mr8nexh.js";import{vg as eX}from"./chunk-50vwafn5.js";import{Ag as jX,xg as OX,yg as NX,zg as bX}from"./chunk-bfv4myk9.js";import{$g as MX,Bg as I4,Cg as h4,Dg as g4,Fg as u4,Gg as d4,Hg as _1,Ig as _Q,Jg as I$,Kg as j$,Lg as G$,Mg as $5,Ng as V2,Og as H8,Pg as l1,Qg as i1,Rg as AX,Vg as J9,Xg as c0,Yg as f$,_g as k4,ah as vX}from"./chunk-kcd6msyx.js";import{ch as D1,eh as T$,fh as O4}from"./chunk-3kszepm6.js";import{gh as d3,hh as W2,ih as m3,jh as s2,kh as c3,lh as p3,mh as Z4,nh as $4,oh as l3,ph as i3,qh as e6}from"./chunk-wcps5gjm.js";import{rh as LW,th as EX,uh as W8,vh as bJ}from"./chunk-vbjgcn49.js";import{xh as L9,zh as x0}from"./chunk-0advddh9.js";import{Ah as E6,Bh as R9,Ch as A6,Dh as r1}from"./chunk-3y2x6fb6.js";import{Ci as SY,Di as kY,Ei as vY,Fh as XJ,Fi as yY,Gi as AZ,Hi as xY,Ii as B1,Ji as IY,Kh as WJ,Ki as hY,Li as gY,Mh as D9,Ni as t3,Pi as xX,Qi as LX,Rh as zW,Ri as B0,Vh as VJ,Xh as wX,Zh as HY,_h as BY,pi as h1,si as $Y}from"./chunk-te7pky9c.js";import{Ui as L$}from"./chunk-kv458q06.js";import{Wi as $X,Yi as ZX}from"./chunk-5v0jcyea.js";import{$i as X4,bj as C}from"./chunk-2f8d0km4.js";import{Dj as e,Fj as a6,Gj as X2,Hj as K,Ij as R3,Jj as P,Kj as u}from"./chunk-2mk914vk.js";import{Oj as FX,Pj as _X}from"./chunk-j8hbddjp.js";import{Qj as NW,Tj as FW}from"./chunk-4cdk4mds.js";import{Xj as AW}from"./chunk-q7xg2zvr.js";import{bk as yX,ck as a0}from"./chunk-rvs364rz.js";import{Bk as E$,Gk as u3,fk as t,gk as N$,hk as D$,ik as t1,jk as o9,kk as u2,lk as X$,mk as e7,pk as I6,yk as P6}from"./chunk-4wx5sya5.js";import{Mk as Y$}from"./chunk-eg3ms291.js";import{randomUUID as M8}from"crypto";import{randomUUID as LV}from"node:crypto";var DV=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);
@@ -861,7 +861,7 @@ ${A0}
861
861
  </approved-plan>
862
862
 
863
863
  IMPORTANT: Execute according to the approved plan above. Follow the steps exactly as specified.`;if(typeof O==="string")S$=O+j6;else S$=[...O,{type:"text",text:j6}]}k=yield*this.runLoop(S$,b,{...x,inputMessageId:void 0})}if(!this.sessionRuntime||!I)return k;let p=await this.sessionRuntime.recordGoalProgress({tokens:k.metadata?.tokensUsed??0,elapsedMs:k.metadata?.duration??0,...v?{goalId:v.goalId,objective:v.objective,turnId:I.id}:{},executionHostFailureCategory:k.metadata?.executionHostFailureCategory,prematureStopPattern:k.success?UY(k.finalMessage):void 0});if(p)yield{kind:"goal_updated",goal:p};if(!k.success||b.signal?.aborted){if(p=await this.sessionRuntime.pauseActiveGoal(b.signal?.aborted?"goal paused after user cancellation":k.error?.message??"goal paused after turn failure"),p)yield{kind:"goal_updated",goal:p}}if(k.success&&!b.signal?.aborted&&h<20)await this.sessionRuntime.waitForBackgroundSubagentFollowUp(I,b.signal);let n=k.success&&!b.signal?.aborted&&h<20,p0=WG(k)||!k.success&&k.error?.type==="max_turns_exceeded";if(R=await this.sessionRuntime.finishTurn(I,{continuePending:n,...p0?{acknowledgeInput:!0}:{},outcome:k.success&&!b.signal?.aborted?{status:"completed",turnsCount:k.metadata?.turnsCount??0,toolCallsCount:k.metadata?.toolCallsCount??0,durationMs:k.metadata?.duration??0}:{status:"aborted",cause:b.signal?.aborted?"cancelled":"failed",turnsCount:k.metadata?.turnsCount??0,toolCallsCount:k.metadata?.toolCallsCount??0,durationMs:k.metadata?.duration??0}}),R){h++,N=!0,M=!1,j=null,O="",o=void 0,A="",S=void 0,E=Z0(),yield{kind:"follow_up_started",queued:this.sessionRuntime.getPendingSteeringCount(),recovered:this.sessionRuntime.getRecoveredSteeringCount(),messages:$0(),queue:await this.sessionRuntime.getFollowUpQueueSnapshot()};continue}if(yield{kind:"follow_up_queue_changed",queue:await this.sessionRuntime.getFollowUpQueueSnapshot()},!k.success||b.signal?.aborted)return k;if(p=await this.sessionRuntime.getGoal(),!p||p.status!=="active"&&p.status!=="verifying")return k;let J0=await this.sessionRuntime.prepareGoalContinuation(p);if(!J0.ok){if(J0.goal)yield{kind:"goal_updated",goal:J0.goal};return{success:!1,error:{type:"goal_frontier_unavailable",message:J0.error.message},metadata:{turnsCount:k.metadata?.turnsCount??0,toolCallsCount:k.metadata?.toolCallsCount??0,duration:k.metadata?.duration??0}}}let h0=await this.sessionRuntime.beginGoalTurn(J0.goal);if(!h0)return k;j=h0.goal,q={...J0,goal:h0.goal},R=h0.handle,N=!1,M=!0,O=S5(j),o=void 0,E=void 0,yield{kind:"goal_frontier_updated",goal:j,frontier:J0.frontier,tasks:J0.tasks},yield{kind:"goal_continuation_started",goal:j,continuation:j.continuationCount,...j.prematureStop?{prematureStopPattern:j.prematureStop.pattern,prematureStopCount:j.prematureStop.consecutiveCount}:{}},yield{kind:"goal_updated",goal:j}}}finally{if(this.sessionRuntime&&R)await this.sessionRuntime.finishTurn(R)}}let _=typeof H==="string"?H:H.filter((O)=>O.type==="text").map((O)=>O.text).join(`
864
- `),L={id:this.generateTaskId(),type:"simple",prompt:_};return{success:!0,finalMessage:(await this.executeTask(L)).content,metadata:{turnsCount:1,toolCallsCount:0,duration:0}}}async chat($,Z,J){let{drainLoop:Y}=await import("./chunk-0ba55nvt.js");return Y(this.chatStream($,Z,J))}async*runPlanLoop($,Z,J){a.debug("Processing Plan mode message...");let{prompt:Y}=await Y1({...Z.workspaceKind==="acp-remote"?{workspaceAccess:"none"}:{projectPath:Z.workspaceRoot||C()},mode:"plan",includeEnvironment:!0,environmentOptions:{...u1,workingDirectory:Z.executionRoot??Z.workspaceRoot??C()},language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),...Z.workspaceKind==="acp-remote"?{}:{projectInstructionSourcePath:this.sessionRuntime?.projectRoot}}),Q;if(typeof $==="string")Q=t2($);else{let X=$.filter((W)=>W.type==="text");if(X.length>0){let W=X[0];Q=$.map((V)=>V===W?{type:"text",text:t2(W.text)}:V)}else Q=[{type:"text",text:t2("")},...$]}return yield*this.executeLoop(Q,Z,J,Y)}async*runLoop($,Z,J){a.debug("Processing enhanced chat message...");let Y=Z.systemPrompt??await this.buildSystemPromptOnDemand(Z);return yield*this.executeLoop($,Z,J,Y)}async buildSystemPromptOnDemand($){let Z=this.runtimeOptions.systemPrompt,J=this.runtimeOptions.appendSystemPrompt;return(await Y1({...$.workspaceKind==="acp-remote"?{workspaceAccess:"none"}:{projectPath:$.workspaceRoot||C()},replaceDefault:Z,append:J,includeEnvironment:!0,environmentOptions:{...u1,workingDirectory:$.executionRoot??$.workspaceRoot??C()},language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),...$.workspaceKind==="acp-remote"?{}:{projectInstructionSourcePath:this.sessionRuntime?.projectRoot}})).prompt}executeLoop($,Z,J,Y){if(!this.isInitialized)throw Error("Agent未初始化");let Q=this.buildLoopDependencies();return nY(Q,$,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)}},Q=J.metadata&&typeof J.metadata==="object"&&!Array.isArray(J.metadata)?J.metadata:void 0,X=J.error===void 0,W=J.output,V={success:X,llmContent:typeof W==="string"||W!==null&&typeof W==="object"?W:W===null?J.error?`Subagent execution failed: ${J.error}.`:"":String(W),...J.error?{error:{type:"execution_error",message:J.error}}:{},...Q?{metadata:Q}:{}},z=[{kind:"tool_result",toolCall:Y,result:V}],U=rY(Y,V);if(U)z.push(U);return z})}takeStartupRecoveryEvents(){let $=this.sessionRuntime?.getTurnRecoveryAssessment(),Z=$?.state==="requires_attention"?$:this.sessionRuntime?.takeStartupTurnRecoveryAssessment(),J=Z&&Z.state!=="none"?[{kind:"turn_recovery",assessment:Z}]:[];return J.push(...this.takeStartupAdoptedToolResultEvents()),J}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=$,a.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((Q)=>!$.includes(Q.name));for(let Q of Y)Z.unregister(Q.name);a.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);a.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){a.debug(`[MainAgent] ${$}`,Z||"")}error($,Z){a.error(`[MainAgent] ${$}`,Z||"")}async initializeSystemPrompt(){try{let $=this.runtimeOptions.systemPrompt,Z=this.runtimeOptions.appendSystemPrompt,J=await Y1({...this.sessionRuntime?.isRemoteWorkspace()?{workspaceAccess:"none"}:{projectPath:this.sessionRuntime?.workspaceRoot??C()},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(),...this.sessionRuntime?.isRemoteWorkspace()?{}:{projectInstructionSourcePath:this.sessionRuntime?.projectRoot},...this.sessionRuntime?{environmentOptions:{...u1,workingDirectory:this.sessionRuntime.executionRoot}}:{}});if(J.prompt)this.log("系统提示配置验证成功"),a.debug(`[SystemPrompt] 可用来源: ${J.sources.filter((Y)=>Y.loaded).map((Y)=>Y.name).join(", ")}`)}catch($){this.error("系统提示配置验证失败",$)}}async registerBuiltinTools(){try{let $=await v4({sessionId:"default",configDir:t(),workspaceRoot:C(),resourceRoot:C(),agentResources:this.agentResources});a.debug(`Registering ${$.length} builtin tools...`),this.toolExecutor.getRegistry().registerAll($);let Z=this.toolExecutor.getRegistry().getAll().length;a.debug(`Builtin tools registered: ${Z} tools`),a.debug(`[Tools] ${this.toolExecutor.getRegistry().getAll().map((J)=>J.name).join(", ")}`),await this.registerMcpTools()}catch($){throw a.error("Failed to register builtin tools:",$),$}}async registerMcpTools(){try{let $=await W4({workspaceRoot:C(),storeServers:this.config.mcpServers??{},cliConfigs:this.runtimeOptions.mcpConfig,strictCliConfig:this.runtimeOptions.strictMcpConfig});if(Object.keys($).length===0){a.debug("No MCP servers configured");return}let Z=e0.createIsolated({artifactWriter:new o2(`legacy-${XG()}`)});this.legacyMcpRegistry=Z;for(let[X,W]of Object.entries($))try{a.debug(`Connecting to MCP server: ${X}`),await Z.registerServer(X,W),a.debug(`MCP server "${X}" connected`)}catch(V){a.warn(`Warning: MCP server "${X}" connection failed:`,V)}let J=this.toolExecutor.getRegistry();J.setMcpCatalogBarrier(()=>Z.waitForCatalogIdle());let Y=Z.getCatalogSnapshot();J.replaceMcpTools(Y.tools),J.registerAll(Y6(Z));let Q=Z.getInstructionsSnapshot();if(J.queueMcpInstructionsChange({revision:Q.revision,reason:"snapshot",replace:!0,instructions:Q.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)a.debug(`Registered ${Y.tools.length} MCP tools`),a.debug(`[MCP Tools] ${Y.tools.map((X)=>X.name).join(", ")}`)}catch($){a.warn("Failed to register MCP tools:",$)}}async loadSubagents(){let $=await c0(C());if(this.agentResources=k4($),this.subagentRegistry=this.agentResources.subagents,this.runtimeOptions.agents?.length)this.subagentRegistry.applyOverrides(this.runtimeOptions.agents);let Z=this.subagentRegistry.getAllNames().length;if(Z>0)a.debug(`Loaded ${Z} subagents: ${this.subagentRegistry.getAllNames().join(", ")}`);else a.debug("No subagents configured")}applySkillToolRestrictions($){if(!this.activeSkillContext?.allowedTools)return $;let Z=this.activeSkillContext.allowedTools;a.debug(`Applying Skill tool restrictions: ${Z.join(", ")}`);let J=$.filter((Y)=>{if(Y.name==="ReadPromptArtifact")return!0;return Z.some((Q)=>{if(Q===Y.name)return!0;let X=Q.match(/^(\w+)\(.*\)$/);if(X&&X[1]===Y.name)return!0;return!1})});return a.debug(`Filtered tools: ${J.map((Y)=>Y.name).join(", ")} (${J.length}/${$.length})`),J}clearSkillContext(){if(this.activeSkillContext)a.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(`
864
+ `),L={id:this.generateTaskId(),type:"simple",prompt:_};return{success:!0,finalMessage:(await this.executeTask(L)).content,metadata:{turnsCount:1,toolCallsCount:0,duration:0}}}async chat($,Z,J){let{drainLoop:Y}=await import("./chunk-qrn27pnc.js");return Y(this.chatStream($,Z,J))}async*runPlanLoop($,Z,J){a.debug("Processing Plan mode message...");let{prompt:Y}=await Y1({...Z.workspaceKind==="acp-remote"?{workspaceAccess:"none"}:{projectPath:Z.workspaceRoot||C()},mode:"plan",includeEnvironment:!0,environmentOptions:{...u1,workingDirectory:Z.executionRoot??Z.workspaceRoot??C()},language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),...Z.workspaceKind==="acp-remote"?{}:{projectInstructionSourcePath:this.sessionRuntime?.projectRoot}}),Q;if(typeof $==="string")Q=t2($);else{let X=$.filter((W)=>W.type==="text");if(X.length>0){let W=X[0];Q=$.map((V)=>V===W?{type:"text",text:t2(W.text)}:V)}else Q=[{type:"text",text:t2("")},...$]}return yield*this.executeLoop(Q,Z,J,Y)}async*runLoop($,Z,J){a.debug("Processing enhanced chat message...");let Y=Z.systemPrompt??await this.buildSystemPromptOnDemand(Z);return yield*this.executeLoop($,Z,J,Y)}async buildSystemPromptOnDemand($){let Z=this.runtimeOptions.systemPrompt,J=this.runtimeOptions.appendSystemPrompt;return(await Y1({...$.workspaceKind==="acp-remote"?{workspaceAccess:"none"}:{projectPath:$.workspaceRoot||C()},replaceDefault:Z,append:J,includeEnvironment:!0,environmentOptions:{...u1,workingDirectory:$.executionRoot??$.workspaceRoot??C()},language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),...$.workspaceKind==="acp-remote"?{}:{projectInstructionSourcePath:this.sessionRuntime?.projectRoot}})).prompt}executeLoop($,Z,J,Y){if(!this.isInitialized)throw Error("Agent未初始化");let Q=this.buildLoopDependencies();return nY(Q,$,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)}},Q=J.metadata&&typeof J.metadata==="object"&&!Array.isArray(J.metadata)?J.metadata:void 0,X=J.error===void 0,W=J.output,V={success:X,llmContent:typeof W==="string"||W!==null&&typeof W==="object"?W:W===null?J.error?`Subagent execution failed: ${J.error}.`:"":String(W),...J.error?{error:{type:"execution_error",message:J.error}}:{},...Q?{metadata:Q}:{}},z=[{kind:"tool_result",toolCall:Y,result:V}],U=rY(Y,V);if(U)z.push(U);return z})}takeStartupRecoveryEvents(){let $=this.sessionRuntime?.getTurnRecoveryAssessment(),Z=$?.state==="requires_attention"?$:this.sessionRuntime?.takeStartupTurnRecoveryAssessment(),J=Z&&Z.state!=="none"?[{kind:"turn_recovery",assessment:Z}]:[];return J.push(...this.takeStartupAdoptedToolResultEvents()),J}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=$,a.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((Q)=>!$.includes(Q.name));for(let Q of Y)Z.unregister(Q.name);a.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);a.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){a.debug(`[MainAgent] ${$}`,Z||"")}error($,Z){a.error(`[MainAgent] ${$}`,Z||"")}async initializeSystemPrompt(){try{let $=this.runtimeOptions.systemPrompt,Z=this.runtimeOptions.appendSystemPrompt,J=await Y1({...this.sessionRuntime?.isRemoteWorkspace()?{workspaceAccess:"none"}:{projectPath:this.sessionRuntime?.workspaceRoot??C()},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(),...this.sessionRuntime?.isRemoteWorkspace()?{}:{projectInstructionSourcePath:this.sessionRuntime?.projectRoot},...this.sessionRuntime?{environmentOptions:{...u1,workingDirectory:this.sessionRuntime.executionRoot}}:{}});if(J.prompt)this.log("系统提示配置验证成功"),a.debug(`[SystemPrompt] 可用来源: ${J.sources.filter((Y)=>Y.loaded).map((Y)=>Y.name).join(", ")}`)}catch($){this.error("系统提示配置验证失败",$)}}async registerBuiltinTools(){try{let $=await v4({sessionId:"default",configDir:t(),workspaceRoot:C(),resourceRoot:C(),agentResources:this.agentResources});a.debug(`Registering ${$.length} builtin tools...`),this.toolExecutor.getRegistry().registerAll($);let Z=this.toolExecutor.getRegistry().getAll().length;a.debug(`Builtin tools registered: ${Z} tools`),a.debug(`[Tools] ${this.toolExecutor.getRegistry().getAll().map((J)=>J.name).join(", ")}`),await this.registerMcpTools()}catch($){throw a.error("Failed to register builtin tools:",$),$}}async registerMcpTools(){try{let $=await W4({workspaceRoot:C(),storeServers:this.config.mcpServers??{},cliConfigs:this.runtimeOptions.mcpConfig,strictCliConfig:this.runtimeOptions.strictMcpConfig});if(Object.keys($).length===0){a.debug("No MCP servers configured");return}let Z=e0.createIsolated({artifactWriter:new o2(`legacy-${XG()}`)});this.legacyMcpRegistry=Z;for(let[X,W]of Object.entries($))try{a.debug(`Connecting to MCP server: ${X}`),await Z.registerServer(X,W),a.debug(`MCP server "${X}" connected`)}catch(V){a.warn(`Warning: MCP server "${X}" connection failed:`,V)}let J=this.toolExecutor.getRegistry();J.setMcpCatalogBarrier(()=>Z.waitForCatalogIdle());let Y=Z.getCatalogSnapshot();J.replaceMcpTools(Y.tools),J.registerAll(Y6(Z));let Q=Z.getInstructionsSnapshot();if(J.queueMcpInstructionsChange({revision:Q.revision,reason:"snapshot",replace:!0,instructions:Q.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)a.debug(`Registered ${Y.tools.length} MCP tools`),a.debug(`[MCP Tools] ${Y.tools.map((X)=>X.name).join(", ")}`)}catch($){a.warn("Failed to register MCP tools:",$)}}async loadSubagents(){let $=await c0(C());if(this.agentResources=k4($),this.subagentRegistry=this.agentResources.subagents,this.runtimeOptions.agents?.length)this.subagentRegistry.applyOverrides(this.runtimeOptions.agents);let Z=this.subagentRegistry.getAllNames().length;if(Z>0)a.debug(`Loaded ${Z} subagents: ${this.subagentRegistry.getAllNames().join(", ")}`);else a.debug("No subagents configured")}applySkillToolRestrictions($){if(!this.activeSkillContext?.allowedTools)return $;let Z=this.activeSkillContext.allowedTools;a.debug(`Applying Skill tool restrictions: ${Z.join(", ")}`);let J=$.filter((Y)=>{if(Y.name==="ReadPromptArtifact")return!0;return Z.some((Q)=>{if(Q===Y.name)return!0;let X=Q.match(/^(\w+)\(.*\)$/);if(X&&X[1]===Y.name)return!0;return!1})});return a.debug(`Filtered tools: ${J.map((Y)=>Y.name).join(", ")} (${J.length}/${$.length})`),J}clearSkillContext(){if(this.activeSkillContext)a.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(`
865
865
  `);try{let Y=await this.attachmentCollector.collect(J);if(Y.length===0)return $;a.debug(`Processed ${Y.length} @ file mentions in multimodal message`);let Q=this.buildAttachmentText(Y);if(!Q)return $;return[...$,{type:"text",text:Q}]}catch(Y){return a.error("Failed to process @ mentions in multimodal message:",Y),$}}buildAttachmentText($){let Z=[],J=[];for(let Q of $)if(Q.type==="file"){let X=Q.metadata?.lineRange?` (lines ${Q.metadata.lineRange.start}${Q.metadata.lineRange.end?`-${Q.metadata.lineRange.end}`:""})`:"";Z.push(`<file path="${Q.path}"${X?` range="${X}"`:""}>`,Q.content,"</file>")}else if(Q.type==="directory")Z.push(`<directory path="${Q.path}">`,Q.content,"</directory>");else if(Q.type==="error")J.push(`- @${Q.path}: ${Q.error}`);let Y="";if(Z.length>0)Y+=`
866
866
 
867
867
  <system-reminder>
@@ -1677,7 +1677,7 @@ ${J}
1677
1677
  `)),{success:!0,message:"Schedules listed",content:z.join(`
1678
1678
  `)}}case"create":{let V=sw(X);if("error"in V)return Y.sendMessage(`创建失败:${V.error}`),{success:!1,error:V.error};let z={prompt:V.prompt,projectPath:W,trigger:V.trigger,isolation:"worktree",permissionMode:"default",enabled:!0};try{let U=await $.create(z),H=U.nextRunAt?new Date(U.nextRunAt).toLocaleString():"(无)";return Y.sendMessage(`[OK] 已创建定时任务 \`${U.id}\`
1679
1679
  ${A9(U.trigger)} · 下次运行: ${H}`),{success:!0,message:`Schedule ${U.id} created`}}catch(U){let H=U instanceof Error?U.message:String(U);return Y.sendMessage(`创建失败:${H}`),{success:!1,error:H}}}case"remove":case"rm":{let V=X[0];if(!V)return Y.sendMessage("用法:/schedule remove <id>"),{success:!1,error:"Missing schedule id"};let z=await $.remove(V);return Y.sendMessage(z?`[OK] 已删除 \`${V}\``:`未找到 \`${V}\``),{success:z,message:z?"Removed":"Not found"}}case"enable":case"disable":{let V=X[0];if(!V)return Y.sendMessage(`用法:/schedule ${Q} <id>`),{success:!1,error:"Missing schedule id"};let z=await $.setEnabled(V,Q==="enable");return Y.sendMessage(z?`[OK] 已${Q==="enable"?"启用":"停用"} \`${V}\``:`未找到 \`${V}\``),{success:Boolean(z),message:z?"Updated":"Not found"}}case"run":{let V=X[0];if(!V)return Y.sendMessage("用法:/schedule run <id>"),{success:!1,error:"Missing schedule id"};try{return await ow(V),Y.sendMessage(`[OK] 已触发 \`${V}\``),{success:!0,message:"Schedule triggered"}}catch(z){let U=z instanceof Error?z.message:String(z);return Y.sendMessage(`运行失败:${U}`),{success:!1,error:U}}}default:return Y.sendMessage(`未知子命令: ${Q}
1680
- 使用 /schedule 查看帮助`),{success:!1,error:`Unknown subcommand: ${Q}`}}}}}var oW=tw();import*as f2 from"node:fs/promises";import*as P2 from"node:path";async function JV($,Z={}){let{maxResults:J=20,caseSensitive:Y=!1,projectPath:Q,storagePath:X}=Z,W=X??P6(Q??C());if(!X){let G=await ew($,Q??C(),J,Y);if(G)return G}let V;try{V=(await f2.readdir(W)).filter((D)=>D.endsWith(".jsonl")&&!D.startsWith("agent_")).map((D)=>P2.join(W,D))}catch{return[]}let U=(await Promise.all(V.map(async(G)=>{try{let D=await f2.stat(G);return{path:G,mtime:D.mtimeMs}}catch{return null}}))).filter((G)=>G!==null).sort((G,D)=>D.mtime-G.mtime).map((G)=>G.path),H=[],B=Y?$:$.toLowerCase();for(let G of U){if(H.length>=J)break;let D=P2.basename(G,".jsonl"),w=await $F(G,B,Y,D);if(H.push(...w),H.length>=J){H.length=J;break}}return H}async function ew($,Z,J,Y){try{let{syncAll:Q}=await import("./chunk-d420fs8m.js"),X=await $V();if(!X)return null;let{SessionService:W}=await import("./chunk-12jy6zwj.js");await Q(X,W.projectionDeriverForSearch());let V=P2.resolve(Z),z=ZV(X,$,V,J*4),U=Y?$:$.toLowerCase(),H=[];for(let B of z){if(B.role!=="user"&&B.role!=="assistant")continue;let G=M9(B.text,U,Y,B.session_id,B.role,B.timestamp??void 0,0);if(G)H.push(G);if(H.length>=J)break}return H}catch{return null}}async function $F($,Z,J,Y){try{let Q=await f2.readFile($,"utf8"),W=Q.split(`
1680
+ 使用 /schedule 查看帮助`),{success:!1,error:`Unknown subcommand: ${Q}`}}}}}var oW=tw();import*as f2 from"node:fs/promises";import*as P2 from"node:path";async function JV($,Z={}){let{maxResults:J=20,caseSensitive:Y=!1,projectPath:Q,storagePath:X}=Z,W=X??P6(Q??C());if(!X){let G=await ew($,Q??C(),J,Y);if(G)return G}let V;try{V=(await f2.readdir(W)).filter((D)=>D.endsWith(".jsonl")&&!D.startsWith("agent_")).map((D)=>P2.join(W,D))}catch{return[]}let U=(await Promise.all(V.map(async(G)=>{try{let D=await f2.stat(G);return{path:G,mtime:D.mtimeMs}}catch{return null}}))).filter((G)=>G!==null).sort((G,D)=>D.mtime-G.mtime).map((G)=>G.path),H=[],B=Y?$:$.toLowerCase();for(let G of U){if(H.length>=J)break;let D=P2.basename(G,".jsonl"),w=await $F(G,B,Y,D);if(H.push(...w),H.length>=J){H.length=J;break}}return H}async function ew($,Z,J,Y){try{let{syncAll:Q}=await import("./chunk-d420fs8m.js"),X=await $V();if(!X)return null;let{SessionService:W}=await import("./chunk-jg5y7fx8.js");await Q(X,W.projectionDeriverForSearch());let V=P2.resolve(Z),z=ZV(X,$,V,J*4),U=Y?$:$.toLowerCase(),H=[];for(let B of z){if(B.role!=="user"&&B.role!=="assistant")continue;let G=M9(B.text,U,Y,B.session_id,B.role,B.timestamp??void 0,0);if(G)H.push(G);if(H.length>=J)break}return H}catch{return null}}async function $F($,Z,J,Y){try{let Q=await f2.readFile($,"utf8"),W=Q.split(`
1681
1681
  `).flatMap((B,G)=>{if(!B.trim())return[];try{return[{event:JSON.parse(B),index:G}]}catch{return[]}});if(!W.some(({event:B})=>B.type==="session_created"))return ZF(W,Z,J,Y);let z=new Map(W.flatMap(({event:B,index:G})=>typeof B.id==="string"?[[B.id,G+1]]:[])),U=tW(eW(Q,$)),H=new Map;for(let B of U){if(B.type==="message_created"&&(B.data.role==="user"||B.data.role==="assistant"))H.set(B.data.messageId,{role:B.data.role,content:[],timestamp:B.timestamp,lineNumber:z.get(B.id)??0});if(B.type==="part_created"&&B.data.partType==="text"){let G=H.get(B.data.messageId),D=B.data.payload.text;if(G&&typeof D==="string")G.content.push(D)}}return[...H.values()].flatMap((B)=>{let G=M9(B.content.join(" "),Z,J,Y,B.role,B.timestamp,B.lineNumber);return G?[G]:[]})}catch{return[]}}function ZF($,Z,J,Y){return $.flatMap(({event:Q,index:X})=>{if(Q.type!=="message")return[];let W=Q.message;if(W?.role!=="user"&&W?.role!=="assistant"||!W.content)return[];let V=typeof W.content==="string"?W.content:Array.isArray(W.content)?W.content.filter((U)=>typeof U==="object"&&U!==null&&U.type==="text"&&typeof U.text==="string").map((U)=>U.text).join(" "):"",z=M9(V,Z,J,Y,W.role,typeof Q.timestamp==="string"?Q.timestamp:void 0,X+1);return z?[z]:[]})}function M9($,Z,J,Y,Q,X,W){if(!$)return;let V=J?$:$.toLowerCase();if(!V.includes(Z))return;let z=V.indexOf(Z),U=Math.max(0,z-80),H=Math.min($.length,z+Z.length+80);return{sessionId:Y,role:Q,content:(U>0?"...":"")+$.slice(U,H).replace(/\n/g," ")+(H<$.length?"...":""),timestamp:X,lineNumber:W}}function YV($){if($.length===0)return"没有找到匹配的历史记录";let Z=[`**找到 ${$.length} 条匹配:**
1682
1682
  `];for(let J of $){let Y=J.timestamp?new Date(J.timestamp).toLocaleString("zh-CN",{timeZone:"Asia/Shanghai"}):"?",Q=J.role==="user"?"\uD83D\uDC64":"\uD83E\uDD16";Z.push(`${Q} \`${J.sessionId.slice(0,8)}\` (${Y})`),Z.push(` ${J.content}`),Z.push("")}return Z.join(`
1683
1683
  `)}var JF={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=c(Z);if($.length===0)return J.sendMessage("**用法:** `/search <关键词>`\n\n在历史会话中搜索包含指定关键词的对话"),{success:!0,message:"显示帮助"};let Y=$.join(" ");J.sendMessage(`正在搜索: "${Y}" ...`);try{let Q=await JV(Y,{maxResults:15,projectPath:Z.cwd}),X=YV(Q);return J.sendMessage(X),{success:!0,message:`found ${Q.length} results`,data:{matches:Q.length}}}catch(Q){let X=Q instanceof Error?Q.message:"未知错误";return J.sendMessage(`搜索失败: ${X}`),{success:!1,error:X}}}},QV=JF;var YF={name:"skills",description:"查看所有可用的 Skills",fullDescription:"显示所有已发现的 Skills 及其详细信息,包括名称、描述、来源和允许的工具。",usage:"/skills",category:"system",examples:["/skills"],handler:async($,Z)=>{try{let J=Z.workspaceRoot??Z.cwd;return await f$(J,async(Y)=>{await Y.skills.refresh(),i1(J),await l1(J)}),{success:!0,message:"show_skills_manager",data:{action:"show_skills_manager"}}}catch(J){let Y=`获取 Skills 失败: ${J instanceof Error?J.message:"未知错误"}`;return d().addAssistantMessage(Y),{success:!1,error:Y}}}},XV=YF;import QF from"node:path";function O8($){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 WV($){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 VV($,Z){if($.length<=Z)return $;return $.slice(0,Z-3)+"..."}async function XF($,Z){let J=c(Z),Y=$[0],Q=Y0.getInstance(),X=D0.getInstance(),W=Z.sessionId??"",V=Z.sessionId?{sessionId:Z.sessionId,projectPath:QF.resolve(Z.workspaceRoot??Z.cwd)}:void 0;if(Y==="resume"){let D=$[1],w=$.slice(2).join(" ").trim();if(!D||!w)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 q=await Z.subagents.resume(D,w),_=`Resumed \`${D}\` as \`${q.session.id}\` (depth ${q.session.resumeDepth}).`;return J.sendMessage(_),{success:!0,message:_,data:{action:"subagent_resumed",sourceAgentId:D,subagent:q.session}}}if(Y==="clean"){let D=X.cleanupExpiredSessionsForParent(V??W,0);return J.sendMessage(`已清理 ${D} 个已完成的 Agent 会话`),{success:!0,message:`Cleaned ${D} agent sessions`}}let z=[`**后台任务列表**
@@ -1,4 +1,4 @@
1
- import{$e as a2,Ae as U1,Be as A0,Ce as B1,De as H1,Fe as d2,Me as i2,Ne as C0,Ue as p_,We as N1,Ye as r2,Ze as o2,_e as q1,oe as u2,pe as e,qe as h2,re as Z1,se as l2,te as v,ue as G1,ve as c2,we as p2,xe as V1,ye as L1,ze as n2}from"./chunk-y5wngtz0.js";import{vg as o_}from"./chunk-50vwafn5.js";import{rh as a_}from"./chunk-vbjgcn49.js";import{Vi as v2,Wi as P2,Xi as x_,Yi as Q0,Zi as w_}from"./chunk-5v0jcyea.js";import{bj as f1}from"./chunk-2f8d0km4.js";import{Dj as H0}from"./chunk-2mk914vk.js";import{Qj as i_,Tj as r_}from"./chunk-4cdk4mds.js";import{Xj as __}from"./chunk-rejsff7v.js";import{Ak as c_,Bk as A,Ck as P,Dk as I,Ek as E1,Fk as F1,Gk as M_,Hk as z1,Ik as b1,Jk as q_,fk as h,pk as o,qk as p,rk as S2,sk as n,tk as d,uk as I2,vk as K0,wk as Y1,xk as m2,yk as K_,zk as M0}from"./chunk-4wx5sya5.js";import{readdir as b_,readFile as V_,rm as f_,stat as E0}from"node:fs/promises";import*as N from"node:path";import{nanoid as m}from"nanoid";import{createHash as F4,randomUUID as z4}from"node:crypto";import*as W_ from"node:fs/promises";import*as W0 from"node:path";import D4 from"proper-lockfile";function cX(_){return Object.freeze({kind:"local",root:_})}function pX(_,X){let $=o(X);if(p($.collisionIdentity)!==_)throw Error("ACP remote workspace durable state is invalid");return Object.freeze({kind:"acp-remote",root:_,descriptor:$})}function nX(_,X){return _.kind==="acp-remote"?`${_.kind}\x00${_.root}\x00${_.descriptor.exactIdentity}\x00${X}`:`${_.kind}\x00${_.root}\x00${X}`}async function H_(_,X){if(_.kind==="local")return X(K_(_.root));return n(_.root,($)=>X(String($),$))}async function dX(_,X,$){return H_(_,(W,J)=>$(J?{storageRoot:W,transcriptPath:I(J,X),inboxPath:F1(J,X),goalPath:z1(J,X),remoteScope:J}:{storageRoot:W,transcriptPath:P(_.root,X),inboxPath:E1(_.root,X),goalPath:M_(_.root,X)}))}import{execFileSync as T4}from"node:child_process";import{createHash as C4}from"node:crypto";import{readFileSync as K4}from"node:fs";var M4=/^[a-f0-9]{64}$/;function D1(_){if(!_||typeof _!=="object")return!1;let X=_;return(X.platform==="linux"||X.platform==="darwin"||X.platform==="win32")&&typeof X.fingerprint==="string"&&M4.test(X.fingerprint)}var R1={readFile:(_)=>K4(_,"utf8"),execFile:(_,X)=>T4(_,X,{encoding:"utf8",timeout:_==="powershell.exe"?3000:2000,windowsHide:!0})},A4=(_)=>{try{return process.kill(_,0),!0}catch(X){return X instanceof Error&&"code"in X&&X.code==="EPERM"}};function x0(_,X){return{platform:_,fingerprint:C4("sha256").update(`${_}\x00${X}`).digest("hex")}}function E4(_,X){let $=X.readFile(`/proc/${_}/stat`).trim(),W=$.lastIndexOf(")");if(W<0)throw Error("Invalid /proc process stat");let O=$.slice(W+2).split(/\s+/)[19];if(!O||!/^\d+$/.test(O))throw Error("Missing process start ticks");return O}function m_(_,X=process.platform,$=R1){if(!Number.isInteger(_)||_<=1)return;try{if(X==="linux")return x0(X,E4(_,$));if(X==="darwin"){let W=$.execFile("ps",["-o","lstart=","-p",String(_)]).trim();return W?x0(X,W):void 0}if(X==="win32"){let W=`(Get-CimInstance Win32_Process -Filter "ProcessId = ${_}").CreationDate.ToUniversalTime().ToString('O')`,J=$.execFile("powershell.exe",["-NoProfile","-NonInteractive","-Command",W]).trim();return J?x0(X,J):void 0}}catch{return}return}function tX(_,X){return m_(_,X.platform)?.fingerprint===X.fingerprint}function sX(_,X,$=R1,W=A4){if(!Number.isInteger(_)||_<=1)return!1;let J=m_(_,X.platform,$);if(J)return J.fingerprint===X.fingerprint;return!W(_)}var j1=1;function R4(_,X){let $=F4("sha256").update(X).digest("hex");return W0.join(K_(_),".locks",`${$}.lock`)}function R_(_,X){return _ instanceof Error&&"code"in _&&_.code===X}async function k0(_){try{let X=JSON.parse(await W_.readFile(_,"utf8"));if(X.version!==j1||typeof X.sessionId!=="string"||typeof X.ownerId!=="string"||!Number.isInteger(X.pid)||(X.pid??0)<=0||X.processIdentity!==void 0&&!D1(X.processIdentity)||typeof X.acquiredAt!=="string")return;return X}catch(X){if(R_(X,"ENOENT")||X instanceof SyntaxError)return;throw X}}async function w1(_){let X=await k0(_);if(X)return X;return await new Promise(($)=>setTimeout($,10)),k0(_)}function w4(_){try{return process.kill(_,0),!0}catch(X){return!R_(X,"ESRCH")}}async function x1(_,X){let $;try{return $=await W_.open(_,"wx",384),await $.writeFile(`${JSON.stringify(X)}
1
+ import{$e as a2,Ae as U1,Be as A0,Ce as B1,De as H1,Fe as d2,Me as i2,Ne as C0,Ue as p_,We as N1,Ye as r2,Ze as o2,_e as q1,oe as u2,pe as e,qe as h2,re as Z1,se as l2,te as v,ue as G1,ve as c2,we as p2,xe as V1,ye as L1,ze as n2}from"./chunk-y5wngtz0.js";import{vg as o_}from"./chunk-50vwafn5.js";import{rh as a_}from"./chunk-vbjgcn49.js";import{Vi as v2,Wi as P2,Xi as x_,Yi as Q0,Zi as w_}from"./chunk-5v0jcyea.js";import{bj as f1}from"./chunk-2f8d0km4.js";import{Dj as H0}from"./chunk-2mk914vk.js";import{Qj as i_,Tj as r_}from"./chunk-4cdk4mds.js";import{Xj as __}from"./chunk-q7xg2zvr.js";import{Ak as c_,Bk as A,Ck as P,Dk as I,Ek as E1,Fk as F1,Gk as M_,Hk as z1,Ik as b1,Jk as q_,fk as h,pk as o,qk as p,rk as S2,sk as n,tk as d,uk as I2,vk as K0,wk as Y1,xk as m2,yk as K_,zk as M0}from"./chunk-4wx5sya5.js";import{readdir as b_,readFile as V_,rm as f_,stat as E0}from"node:fs/promises";import*as N from"node:path";import{nanoid as m}from"nanoid";import{createHash as F4,randomUUID as z4}from"node:crypto";import*as W_ from"node:fs/promises";import*as W0 from"node:path";import D4 from"proper-lockfile";function cX(_){return Object.freeze({kind:"local",root:_})}function pX(_,X){let $=o(X);if(p($.collisionIdentity)!==_)throw Error("ACP remote workspace durable state is invalid");return Object.freeze({kind:"acp-remote",root:_,descriptor:$})}function nX(_,X){return _.kind==="acp-remote"?`${_.kind}\x00${_.root}\x00${_.descriptor.exactIdentity}\x00${X}`:`${_.kind}\x00${_.root}\x00${X}`}async function H_(_,X){if(_.kind==="local")return X(K_(_.root));return n(_.root,($)=>X(String($),$))}async function dX(_,X,$){return H_(_,(W,J)=>$(J?{storageRoot:W,transcriptPath:I(J,X),inboxPath:F1(J,X),goalPath:z1(J,X),remoteScope:J}:{storageRoot:W,transcriptPath:P(_.root,X),inboxPath:E1(_.root,X),goalPath:M_(_.root,X)}))}import{execFileSync as T4}from"node:child_process";import{createHash as C4}from"node:crypto";import{readFileSync as K4}from"node:fs";var M4=/^[a-f0-9]{64}$/;function D1(_){if(!_||typeof _!=="object")return!1;let X=_;return(X.platform==="linux"||X.platform==="darwin"||X.platform==="win32")&&typeof X.fingerprint==="string"&&M4.test(X.fingerprint)}var R1={readFile:(_)=>K4(_,"utf8"),execFile:(_,X)=>T4(_,X,{encoding:"utf8",timeout:_==="powershell.exe"?3000:2000,windowsHide:!0})},A4=(_)=>{try{return process.kill(_,0),!0}catch(X){return X instanceof Error&&"code"in X&&X.code==="EPERM"}};function x0(_,X){return{platform:_,fingerprint:C4("sha256").update(`${_}\x00${X}`).digest("hex")}}function E4(_,X){let $=X.readFile(`/proc/${_}/stat`).trim(),W=$.lastIndexOf(")");if(W<0)throw Error("Invalid /proc process stat");let O=$.slice(W+2).split(/\s+/)[19];if(!O||!/^\d+$/.test(O))throw Error("Missing process start ticks");return O}function m_(_,X=process.platform,$=R1){if(!Number.isInteger(_)||_<=1)return;try{if(X==="linux")return x0(X,E4(_,$));if(X==="darwin"){let W=$.execFile("ps",["-o","lstart=","-p",String(_)]).trim();return W?x0(X,W):void 0}if(X==="win32"){let W=`(Get-CimInstance Win32_Process -Filter "ProcessId = ${_}").CreationDate.ToUniversalTime().ToString('O')`,J=$.execFile("powershell.exe",["-NoProfile","-NonInteractive","-Command",W]).trim();return J?x0(X,J):void 0}}catch{return}return}function tX(_,X){return m_(_,X.platform)?.fingerprint===X.fingerprint}function sX(_,X,$=R1,W=A4){if(!Number.isInteger(_)||_<=1)return!1;let J=m_(_,X.platform,$);if(J)return J.fingerprint===X.fingerprint;return!W(_)}var j1=1;function R4(_,X){let $=F4("sha256").update(X).digest("hex");return W0.join(K_(_),".locks",`${$}.lock`)}function R_(_,X){return _ instanceof Error&&"code"in _&&_.code===X}async function k0(_){try{let X=JSON.parse(await W_.readFile(_,"utf8"));if(X.version!==j1||typeof X.sessionId!=="string"||typeof X.ownerId!=="string"||!Number.isInteger(X.pid)||(X.pid??0)<=0||X.processIdentity!==void 0&&!D1(X.processIdentity)||typeof X.acquiredAt!=="string")return;return X}catch(X){if(R_(X,"ENOENT")||X instanceof SyntaxError)return;throw X}}async function w1(_){let X=await k0(_);if(X)return X;return await new Promise(($)=>setTimeout($,10)),k0(_)}function w4(_){try{return process.kill(_,0),!0}catch(X){return!R_(X,"ESRCH")}}async function x1(_,X){let $;try{return $=await W_.open(_,"wx",384),await $.writeFile(`${JSON.stringify(X)}
2
2
  `,"utf8"),!0}catch(W){if(R_(W,"EEXIST"))return!1;if($)await W_.unlink(_).catch(()=>{return});throw W}finally{await $?.close().catch(()=>{return})}}class $_ extends Error{code="BLADE_SESSION_IN_USE";constructor(_){super(_?`Session is already active in another Blade process (PID ${_}). Stop that process or choose a different session.`:"Session is already active in another Blade process. Stop that process or choose a different session.");this.name="SessionInUseError"}}async function k1(_,X,$=!1){let W,J;try{J=await D4.lock(_,{realpath:!1,retries:$?{retries:50,minTimeout:10,maxTimeout:100,factor:1.2}:0,onCompromised:(Q)=>{W=Q}})}catch(Q){if(R_(Q,"ELOCKED"))throw new $_;throw Q}let O=()=>{if(W)throw W};try{O();let Q=await X(O);return O(),Q}finally{await J()}}class u{filePath;record;stateStorage;released=!1;constructor(_,X,$){this.filePath=_;this.record=X;this.stateStorage=$}static async acquireForStorage(_,X){if(X.kind==="local")return u.acquire(_,X.root);return H_(X,($,W)=>{if(!W||$!==X.root)throw Error("ACP remote session lease scope is invalid");return u.acquireRemote(_,W,X)})}static async acquire(_,X=f1()){return u.acquireAtPath(_,R4(X,_))}static async acquireRemote(_,X,$){let W=b1(X,_);try{await d(X,W)}catch(O){if(O.code!=="ENOENT")throw O}let J=await u.acquireAtPath(_,W);try{return await d(X,W),new u(W,J.record,$)}catch(O){throw await J.release(),O}}static async acquireAtPath(_,X){return await W_.mkdir(W0.dirname(X),{recursive:!0,mode:448}),k1(X,async($)=>{let W={version:j1,sessionId:_,ownerId:z4(),pid:process.pid,processIdentity:m_(process.pid),acquiredAt:new Date().toISOString()};if($(),await x1(X,W))return new u(X,W);let J=await w1(X);if(!J||J.sessionId!==_)throw new $_;if(w4(J.pid)){let O=J.processIdentity?m_(J.pid,J.processIdentity.platform):void 0;if(!O||O.fingerprint===J.processIdentity?.fingerprint)throw new $_(J.pid)}if($(),await W_.unlink(X).catch((O)=>{if(!R_(O,"ENOENT"))throw O}),$(),await x1(X,W))return new u(X,W);throw new $_((await w1(X))?.pid)})}async release(){if(this.released)return;let _=()=>k1(this.filePath,async(X)=>{if((await k0(this.filePath))?.ownerId!==this.record.ownerId)return;X(),await W_.unlink(this.filePath).catch((W)=>{if(!R_(W,"ENOENT"))throw W})},!0);if(this.stateStorage?.kind==="acp-remote")await H_(this.stateStorage,_);else await _();this.released=!0}}import{createHash as O0}from"node:crypto";import{constants as A_,promises as O_}from"node:fs";import G_ from"node:path";import{Mutex as x4}from"async-mutex";var y1=128,g1=67108864,k4=24576,S1=65536,f0=1,h1=/^[a-f0-9]{64}$/,b4=/^[a-f0-9]{64}\.txt$/,l1=64,f4=new Set(["EBUSY","EAGAIN","EMFILE","ENFILE"]),Y0=`
3
3
 
4
4
  ...[middle omitted; read the private prompt artifact for the complete request]...
@@ -1,4 +1,4 @@
1
- import{Aa as F,Ca as L}from"./chunk-26g3nrdr.js";import{$d as B,Zd as $,he as Q}from"./chunk-3rrcg0es.js";import{Xg as y}from"./chunk-38arrd1h.js";import{bj as V}from"./chunk-2f8d0km4.js";async function j(){await y(V())}async function I(b){let q=b.message||b._?.[0];if(typeof q==="string"&&q.trim())return q;let z=b.stdin??process.stdin;if(!z.isTTY){let G=[];for await(let K of z)G.push(K);return Buffer.concat(G).toString("utf-8").trim()}if(b.defaultMessage!==void 0)return b.defaultMessage;throw Error("No input provided")}async function M(b){let q=b.message||b._?.[0];if(typeof q==="string"&&q.trim())return q;let z=b.stdin??process.stdin;if(z.isTTY)return;let G=[];for await(let Z of z)G.push(Buffer.isBuffer(Z)?Z:Buffer.from(Z));return Buffer.concat(G).toString("utf-8").trim()||void 0}async function R(b){if(!F(b))return{mode:"agent",content:b};let q=await L(b,{cwd:V(),surface:"headless",workspaceRoot:V()});if(!q.success)return{mode:"output",content:`Error: ${q.error||"未知错误"}`,exitCode:1};let z=q.data;if(z?.action==="invoke_skill"){let{skillName:G,skillArgs:K}=z;return{mode:"agent",content:K?`Please use the "${G}" skill to help me with: ${K}`:`Please use the "${G}" skill.`}}if(z?.action==="invoke_custom_command"||z?.action==="invoke_plugin_command"){let G=z.processedContent;return{mode:"agent",content:`# Custom Command: /${z.commandName}
1
+ import{Aa as F,Ca as L}from"./chunk-cgjzvp4b.js";import{$d as B,Zd as $,he as Q}from"./chunk-cp33mrea.js";import{Xg as y}from"./chunk-kcd6msyx.js";import{bj as V}from"./chunk-2f8d0km4.js";async function j(){await y(V())}async function I(b){let q=b.message||b._?.[0];if(typeof q==="string"&&q.trim())return q;let z=b.stdin??process.stdin;if(!z.isTTY){let G=[];for await(let K of z)G.push(K);return Buffer.concat(G).toString("utf-8").trim()}if(b.defaultMessage!==void 0)return b.defaultMessage;throw Error("No input provided")}async function M(b){let q=b.message||b._?.[0];if(typeof q==="string"&&q.trim())return q;let z=b.stdin??process.stdin;if(z.isTTY)return;let G=[];for await(let Z of z)G.push(Buffer.isBuffer(Z)?Z:Buffer.from(Z));return Buffer.concat(G).toString("utf-8").trim()||void 0}async function R(b){if(!F(b))return{mode:"agent",content:b};let q=await L(b,{cwd:V(),surface:"headless",workspaceRoot:V()});if(!q.success)return{mode:"output",content:`Error: ${q.error||"未知错误"}`,exitCode:1};let z=q.data;if(z?.action==="invoke_skill"){let{skillName:G,skillArgs:K}=z;return{mode:"agent",content:K?`Please use the "${G}" skill to help me with: ${K}`:`Please use the "${G}" skill.`}}if(z?.action==="invoke_custom_command"||z?.action==="invoke_plugin_command"){let G=z.processedContent;return{mode:"agent",content:`# Custom Command: /${z.commandName}
2
2
 
3
3
  ${G}`}}return{mode:"output",content:q.content||q.message||"",exitCode:0}}import{readFile as D,stat as H}from"node:fs/promises";import J from"node:path";function x(b,q){let z;try{z=JSON.parse(b)}catch(G){throw Error(`Invalid JSON output schema from ${q}`,{cause:G})}return B(z).schema}async function _(b){if(b.jsonSchema!==void 0&&b.outputSchema!==void 0)throw Error("--json-schema cannot be combined with --output-schema");if(b.jsonSchema!==void 0)return x(b.jsonSchema,"--json-schema");if(b.outputSchema===void 0)return;let q=J.resolve(b.outputSchema),z=await H(q);if(!z.isFile())throw Error(`Output schema path is not a regular file: ${q}`);if(z.size>$)throw Error(`Output schema exceeds ${$} bytes: ${q}`);return x(await D(q,"utf8"),q)}function N(b){if(!(b instanceof Error))return!1;return b.message.includes("未找到会话")||b.message.includes("ENOENT")||b.message.includes("no such file")}async function W(b){try{return await Q.loadSessionModelContext(b,V())}catch(q){if(N(q))return null;throw q}}async function C(b){if(b.resume===!0||b.resume==="true")throw Error("--resume without a session ID is only supported in interactive UI mode");if(typeof b.resume==="string"&&b.resume.length>0){if(b.forkSession){let G=V(),K=await Q.forkSession(b.resume,{newSessionId:b.sessionId,sourceProjectPath:G,targetProjectPath:G});return{...K,messages:await Q.loadSessionModelContext(K.sessionId,G)}}let[q,z]=await Promise.all([Q.loadSessionModelContext(b.resume),Q.findSessionMetadata(b.resume)]);return{sessionId:b.resume,messages:q,metadata:z}}if(b.continue){let q=b.forkSession?await Q.listSessions({cwd:V()}):await Q.listSessions();if(q.length>0){let z=q[0].sessionId;if(b.forkSession){let G=V(),K=await Q.forkSession(z,{newSessionId:b.sessionId,sourceProjectPath:G,targetProjectPath:G});return{...K,messages:await Q.loadSessionModelContext(K.sessionId,G)}}return{sessionId:z,messages:await Q.loadSessionModelContext(z),metadata:q[0]}}if(b.forkSession)throw Error("Cannot fork: no sessions are available to continue")}if(b.sessionId){let q=await W(b.sessionId);return{sessionId:b.sessionId,messages:q??[],...q?{metadata:await Q.findSessionMetadata(b.sessionId,V())}:{}}}return{sessionId:`${b.fallbackSessionPrefix}-${Date.now()}`,messages:[]}}
4
4
  export{j as p,I as q,M as r,R as s,_ as t,C as u};