blade-code 0.10.130 → 0.10.132

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 (76) hide show
  1. package/dist/blade.js +2 -2
  2. package/dist/{chunk-hhg1zcbq.js → chunk-0bkhpd72.js} +1 -1
  3. package/dist/{chunk-sn71fsm5.js → chunk-0gmbvtpp.js} +1 -1
  4. package/dist/{chunk-bcre3557.js → chunk-14z94k0r.js} +1 -1
  5. package/dist/{chunk-s2atpv23.js → chunk-3e0t25rq.js} +2 -2
  6. package/dist/{chunk-h1wphqkc.js → chunk-53j6nh8j.js} +1 -1
  7. package/dist/{chunk-51qc7n8t.js → chunk-64kg5a9r.js} +1 -1
  8. package/dist/{chunk-9yqadjea.js → chunk-6q3g5e3m.js} +1 -1
  9. package/dist/{chunk-pk11fexz.js → chunk-749jzrbk.js} +1 -1
  10. package/dist/{chunk-e1d0e6t6.js → chunk-7dy3mzgz.js} +1 -1
  11. package/dist/{chunk-ss4sncn3.js → chunk-8y08fytr.js} +1 -1
  12. package/dist/{chunk-v5hzk7j2.js → chunk-9d49tj9y.js} +1 -1
  13. package/dist/{chunk-gfbkrk60.js → chunk-b5z1rec4.js} +29 -29
  14. package/dist/{chunk-xa9k5pjt.js → chunk-bavzm721.js} +1 -1
  15. package/dist/{chunk-te6203yf.js → chunk-dhzbac1c.js} +1 -1
  16. package/dist/{chunk-t4apxzp1.js → chunk-dvb89529.js} +1 -1
  17. package/dist/{chunk-8a6nrqdc.js → chunk-e371f7xk.js} +1 -1
  18. package/dist/{chunk-p2sp2e0a.js → chunk-fag8rk53.js} +1 -1
  19. package/dist/{chunk-4sxxvtn4.js → chunk-g12kqs1b.js} +1 -1
  20. package/dist/{chunk-42h7kj6p.js → chunk-g1bqjdeq.js} +1 -1
  21. package/dist/{chunk-zc91c7b5.js → chunk-j3nmt09e.js} +1 -1
  22. package/dist/{chunk-2bnpn8be.js → chunk-mg1s861p.js} +1 -1
  23. package/dist/{chunk-fjv2vede.js → chunk-pkg1bvzc.js} +1 -1
  24. package/dist/{chunk-hw1gbr11.js → chunk-pqsvz99n.js} +1 -1
  25. package/dist/{chunk-kfkvdj49.js → chunk-prt6y5fv.js} +1 -1
  26. package/dist/chunk-q7m0tvhw.js +1 -0
  27. package/dist/{chunk-5a17mdjd.js → chunk-qcydkn1n.js} +1 -1
  28. package/dist/{chunk-r9tawy93.js → chunk-r7kevfd3.js} +1 -1
  29. package/dist/{chunk-7jj607dg.js → chunk-rj8mmwc6.js} +1 -1
  30. package/dist/{chunk-tw5fr07c.js → chunk-sbc90z9j.js} +1 -1
  31. package/dist/{chunk-gzz0gnmv.js → chunk-sf9sbm6y.js} +1 -1
  32. package/dist/{chunk-qahz5x5c.js → chunk-sm9p1fkf.js} +1 -1
  33. package/dist/{chunk-a4jetpj8.js → chunk-t8rjxqp2.js} +1 -1
  34. package/dist/{chunk-55hq1ps4.js → chunk-td2jk2xn.js} +2 -2
  35. package/dist/{chunk-v94ztjtp.js → chunk-xjrmq0pg.js} +3 -3
  36. package/dist/{chunk-ss86eq2h.js → chunk-xyxjcehh.js} +1 -1
  37. package/dist/{chunk-9et78e3v.js → chunk-y0kqkewg.js} +1 -1
  38. package/dist/{chunk-dkgaxmsp.js → chunk-z28dcrr9.js} +1 -1
  39. package/dist/chunk-z83xk6jn.js +1 -0
  40. package/dist/{chunk-b8m7zc7t.js → chunk-znqt5g8v.js} +1 -1
  41. package/dist/{chunk-agda17kj.js → chunk-zssz8hc4.js} +1 -1
  42. package/dist/web/assets/{ChatView-Bg36FUaj.js → ChatView-CkmlibKO.js} +4 -4
  43. package/dist/web/assets/{CodeBlockHighlighter-D5rB73Eo.js → CodeBlockHighlighter-DR5RLA1_.js} +1 -1
  44. package/dist/web/assets/{FilePreview-BxaBSmap.js → FilePreview-C4tqzUOM.js} +1 -1
  45. package/dist/web/assets/{KanbanBoard-B4gx3JMo.js → KanbanBoard-D7HJQXE2.js} +1 -1
  46. package/dist/web/assets/{MarkdownRenderer-BRH7LHhN.js → MarkdownRenderer-Ct8vtONO.js} +3 -3
  47. package/dist/web/assets/{ScrollArea-DikU3QeQ.js → ScrollArea-CMSE6nO4.js} +1 -1
  48. package/dist/web/assets/{SessionHistorySurface-DG80d6-F.js → SessionHistorySurface-BPwnF9ND.js} +1 -1
  49. package/dist/web/assets/{SettingsModal-Bxqkok81.js → SettingsModal-KW5WYAov.js} +1 -1
  50. package/dist/web/assets/{Sidebar-DGaHGcHx.js → Sidebar-8BUNEHHQ.js} +1 -1
  51. package/dist/web/assets/{TaskSwitcher-DOnLPurk.js → TaskSwitcher-CZfkp2L_.js} +1 -1
  52. package/dist/web/assets/{TerminalPanel-BzhCF9vw.js → TerminalPanel-DBBMaU_6.js} +1 -1
  53. package/dist/web/assets/{archive-BiDGrqry.js → archive-tBd5snSF.js} +1 -1
  54. package/dist/web/assets/{arrow-left-BY-esOAP.js → arrow-left-Cs_sFMp-.js} +1 -1
  55. package/dist/web/assets/{calendar-clock-BCyxvfVt.js → calendar-clock-C0ue6XTy.js} +1 -1
  56. package/dist/web/assets/{chevron-right-Bg-10yuN.js → chevron-right-DZHCUfAH.js} +1 -1
  57. package/dist/web/assets/{chevrons-up-down-M5SAJq7T.js → chevrons-up-down-BSa16Scz.js} +1 -1
  58. package/dist/web/assets/{clock-3-v-nHTA0A.js → clock-3-DstAM2AR.js} +1 -1
  59. package/dist/web/assets/{copy-p1zc_rjZ.js → copy-BfnFXTgG.js} +1 -1
  60. package/dist/web/assets/{download-D_-kbJXR.js → download-XKyNtMnj.js} +1 -1
  61. package/dist/web/assets/{external-link-wSGTIqe3.js → external-link-3bcWFMya.js} +1 -1
  62. package/dist/web/assets/{folder-Ltm9jCS5.js → folder-D7hQLvy7.js} +1 -1
  63. package/dist/web/assets/index-CCdnLriX.js +210 -0
  64. package/dist/web/assets/{pause-_LvCZkxM.js → pause-CBR55GXy.js} +1 -1
  65. package/dist/web/assets/{pencil-DB6ICr_h.js → pencil-8yqeFHC4.js} +1 -1
  66. package/dist/web/assets/{play-BRXP1rHJ.js → play-F_Spkp4p.js} +1 -1
  67. package/dist/web/assets/{plus-BqvjEpLw.js → plus-CJCqq3rG.js} +1 -1
  68. package/dist/web/assets/{session-events-AGMXvPey.js → session-events-C6fPz20c.js} +4 -4
  69. package/dist/web/assets/{settings-LfQbDvBA.js → settings-G6riyt4S.js} +1 -1
  70. package/dist/web/assets/{teamService-B5FnUcet.js → teamService-Cixkq48S.js} +1 -1
  71. package/dist/web/assets/{terminal-By4sO9Gw.js → terminal-_Nebc2yj.js} +1 -1
  72. package/dist/web/index.html +1 -1
  73. package/package.json +1 -1
  74. package/dist/chunk-1bb4h5gf.js +0 -1
  75. package/dist/chunk-saedy6bj.js +0 -1
  76. package/dist/web/assets/index-_xnlrekR.js +0 -210
@@ -25,7 +25,7 @@ import{ih as YO}from"./chunk-g4xny949.js";import{Ii as P}from"./chunk-44jtpg8y.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-gzz0gnmv.js"),{createChatServiceAsync:W}=await import("./chunk-kd3k1q9z.js"),{resolveModelConfig:J}=await import("./chunk-m9mw8ppy.js"),{resolveWorkspaceModelResources:G}=await import("./chunk-te6203yf.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-sf9sbm6y.js"),{createChatServiceAsync:W}=await import("./chunk-kd3k1q9z.js"),{resolveModelConfig:J}=await import("./chunk-m9mw8ppy.js"),{resolveWorkspaceModelResources:G}=await import("./chunk-dhzbac1c.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{$d as e,Ee as l_,Ge as N1,Ie as o2,Je as a2,Ke as q1,Le as t2,_d as h2,ae as l2,be as Z1,ce as c2,de as m,ee as G1,fe as p2,ge as n2,he as V1,ie as L1,je as d2,ke as H1,le as A0,me as U1,ne as B1,pe as i2,we as r2,xe as C0}from"./chunk-gfbkrk60.js";import{cg as i_}from"./chunk-edtxcqxa.js";import{Yg as r_}from"./chunk-aaxc81jc.js";import{Ai as P2,Bi as u2,Ci as w_,Di as Q0,Ei as R_}from"./chunk-f8gb685p.js";import{Ii as f1}from"./chunk-44jtpg8y.js";import{oj as B0}from"./chunk-ar5np5h5.js";import{vj as n_,yj as d_}from"./chunk-tkydv9k8.js";import{Cj as __}from"./chunk-v5hzk7j2.js";import{$j as m2,Mj as h,Wj as o,Xj as p,Yj as I2,Zj as n,_j as d,ak as K0,bk as Y1,ck as v2,dk as K_,ek as M0,fk as h_,gk as A,hk as P,ik as S,jk as E1,kk as F1,lk as M_,mk as z1,nk as b1,ok as q_}from"./chunk-pj69j4zp.js";import{readdir as k_,readFile as G_,rm as b_,stat as E0}from"node:fs/promises";import*as N from"node:path";import{nanoid as I}from"nanoid";import{createHash as z4,randomUUID as D4}from"node:crypto";import*as $_ from"node:fs/promises";import*as W0 from"node:path";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 U_(_,X){if(_.kind==="local")return X(K_(_.root));return n(_.root,($)=>X(String($),$))}async function dX(_,X,$){return U_(_,(W,J)=>$(J?{storageRoot:W,transcriptPath:S(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 C4}from"node:child_process";import{createHash as K4}from"node:crypto";import{readFileSync as M4}from"node:fs";var A4=/^[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"&&A4.test(X.fingerprint)}var R1={readFile:(_)=>M4(_,"utf8"),execFile:(_,X)=>C4(_,X,{encoding:"utf8",timeout:_==="powershell.exe"?3000:2000,windowsHide:!0})},E4=(_)=>{try{return process.kill(_,0),!0}catch(X){return X instanceof Error&&"code"in X&&X.code==="EPERM"}};function x0(_,X){return{platform:_,fingerprint:K4("sha256").update(`${_}\x00${X}`).digest("hex")}}function F4(_,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 X0(_,X=process.platform,$=R1){if(!Number.isInteger(_)||_<=1)return;try{if(X==="linux")return x0(X,F4(_,$));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 w1(_,X){return X0(_,X.platform)?.fingerprint===X.fingerprint}function tX(_,X,$=R1,W=E4){if(!Number.isInteger(_)||_<=1)return!1;let J=X0(_,X.platform,$);if(J)return J.fingerprint===X.fingerprint;return!W(_)}var j1=1;function R4(_,X){let $=z4("sha256").update(X).digest("hex");return W0.join(K_(_),".locks",`${$}.lock`)}function $0(_,X){return _ instanceof Error&&"code"in _&&_.code===X}async function k0(_){try{let X=JSON.parse(await $_.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{return}}async function x1(_){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 $0(X,"EPERM")}}async function k1(_,X){let $;try{return $=await $_.open(_,"wx",384),await $.writeFile(`${JSON.stringify(X)}
1
+ import{$d as e,Ee as l_,Ge as N1,Ie as o2,Je as a2,Ke as q1,Le as t2,_d as h2,ae as l2,be as Z1,ce as c2,de as m,ee as G1,fe as p2,ge as n2,he as V1,ie as L1,je as d2,ke as H1,le as A0,me as U1,ne as B1,pe as i2,we as r2,xe as C0}from"./chunk-b5z1rec4.js";import{cg as i_}from"./chunk-edtxcqxa.js";import{Yg as r_}from"./chunk-aaxc81jc.js";import{Ai as P2,Bi as u2,Ci as w_,Di as Q0,Ei as R_}from"./chunk-f8gb685p.js";import{Ii as f1}from"./chunk-44jtpg8y.js";import{oj as B0}from"./chunk-ar5np5h5.js";import{vj as n_,yj as d_}from"./chunk-tkydv9k8.js";import{Cj as __}from"./chunk-9d49tj9y.js";import{$j as m2,Mj as h,Wj as o,Xj as p,Yj as I2,Zj as n,_j as d,ak as K0,bk as Y1,ck as v2,dk as K_,ek as M0,fk as h_,gk as A,hk as P,ik as S,jk as E1,kk as F1,lk as M_,mk as z1,nk as b1,ok as q_}from"./chunk-pj69j4zp.js";import{readdir as k_,readFile as G_,rm as b_,stat as E0}from"node:fs/promises";import*as N from"node:path";import{nanoid as I}from"nanoid";import{createHash as z4,randomUUID as D4}from"node:crypto";import*as $_ from"node:fs/promises";import*as W0 from"node:path";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 U_(_,X){if(_.kind==="local")return X(K_(_.root));return n(_.root,($)=>X(String($),$))}async function dX(_,X,$){return U_(_,(W,J)=>$(J?{storageRoot:W,transcriptPath:S(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 C4}from"node:child_process";import{createHash as K4}from"node:crypto";import{readFileSync as M4}from"node:fs";var A4=/^[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"&&A4.test(X.fingerprint)}var R1={readFile:(_)=>M4(_,"utf8"),execFile:(_,X)=>C4(_,X,{encoding:"utf8",timeout:_==="powershell.exe"?3000:2000,windowsHide:!0})},E4=(_)=>{try{return process.kill(_,0),!0}catch(X){return X instanceof Error&&"code"in X&&X.code==="EPERM"}};function x0(_,X){return{platform:_,fingerprint:K4("sha256").update(`${_}\x00${X}`).digest("hex")}}function F4(_,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 X0(_,X=process.platform,$=R1){if(!Number.isInteger(_)||_<=1)return;try{if(X==="linux")return x0(X,F4(_,$));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 w1(_,X){return X0(_,X.platform)?.fingerprint===X.fingerprint}function tX(_,X,$=R1,W=E4){if(!Number.isInteger(_)||_<=1)return!1;let J=X0(_,X.platform,$);if(J)return J.fingerprint===X.fingerprint;return!W(_)}var j1=1;function R4(_,X){let $=z4("sha256").update(X).digest("hex");return W0.join(K_(_),".locks",`${$}.lock`)}function $0(_,X){return _ instanceof Error&&"code"in _&&_.code===X}async function k0(_){try{let X=JSON.parse(await $_.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{return}}async function x1(_){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 $0(X,"EPERM")}}async function k1(_,X){let $;try{return $=await $_.open(_,"wx",384),await $.writeFile(`${JSON.stringify(X)}
2
2
  `,"utf8"),!0}catch(W){if($0(W,"EEXIST"))return!1;if($)await $_.unlink(_).catch(()=>{return});throw W}finally{await $?.close().catch(()=>{return})}}class B_ 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"}}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 U_(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){let $={version:j1,sessionId:_,ownerId:D4(),pid:process.pid,processIdentity:X0(process.pid),acquiredAt:new Date().toISOString()};if(await $_.mkdir(W0.dirname(X),{recursive:!0,mode:448}),await k1(X,$))return new u(X,$);let W=await x1(X);if(W&&w4(W.pid)&&(!W.processIdentity||w1(W.pid,W.processIdentity)))throw new B_(W.pid);if(await $_.unlink(X).catch((J)=>{if(!$0(J,"ENOENT"))throw J}),await k1(X,$))return new u(X,$);throw new B_((await x1(X))?.pid)}async release(){if(this.released)return;let _=async()=>{if((await k0(this.filePath))?.ownerId!==this.record.ownerId)return;await $_.unlink(this.filePath).catch(($)=>{if(!$0($,"ENOENT"))throw $})};if(this.stateStorage?.kind==="acp-remote")await U_(this.stateStorage,_);else await _();this.released=!0}}import{createHash as O0}from"node:crypto";import{constants as A_,promises as W_}from"node:fs";import Z_ 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{cc as Xt,dc as En,ec as yn,fc as bn}from"./chunk-77efqpdc.js";import{eh as Bt}from"./chunk-r9tawy93.js";import{Ah as cn,Bh as Mn,Dh as S,Gh as wn,Hh as Gt,Ih as Ut,Jh as h,Kh as Ht,jh as xt,kh as vi,lh as sn,mh as zt,nh as U,oh as en,ph as gt,qh as mt,sh as rn,th as Tn,uh as B,vh as dn,wh as on,xh as pn,yh as lt,zh as un}from"./chunk-hhg1zcbq.js";import{Ii as It}from"./chunk-44jtpg8y.js";import{Ji as X,Li as x}from"./chunk-sj1dzeta.js";import{Cj as tn,Dj as nn}from"./chunk-v5hzk7j2.js";import{rk as ns}from"./chunk-zkzhm39s.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{cc as Xt,dc as En,ec as yn,fc as bn}from"./chunk-77efqpdc.js";import{eh as Bt}from"./chunk-r7kevfd3.js";import{Ah as cn,Bh as Mn,Dh as S,Gh as wn,Hh as Gt,Ih as Ut,Jh as h,Kh as Ht,jh as xt,kh as vi,lh as sn,mh as zt,nh as U,oh as en,ph as gt,qh as mt,sh as rn,th as Tn,uh as B,vh as dn,wh as on,xh as pn,yh as lt,zh as un}from"./chunk-0bkhpd72.js";import{Ii as It}from"./chunk-44jtpg8y.js";import{Ji as X,Li as x}from"./chunk-sj1dzeta.js";import{Cj as tn,Dj as nn}from"./chunk-9d49tj9y.js";import{rk as ns}from"./chunk-zkzhm39s.js";import{EventEmitter as fs}from"events";import Un from"node:path";function hn(t){if(t===void 0)return"undefined";if(typeof t==="string")return t;try{let i=JSON.stringify(t);return i===void 0?String(t):i}catch{return String(t)}}function An(t){let i=t;switch(t.code){case"type":return`类型错误:${t.message}`;case"required":return"缺少必需参数";case"minLength":return`字符串过短:${t.message}`;case"maxLength":return`字符串过长:${t.message}`;case"minimum":case"exclusiveMinimum":return`数值太小:${t.message}`;case"maximum":case"exclusiveMaximum":return`数值太大:${t.message}`;case"minItems":return`数组元素过少:${t.message}`;case"maxItems":return`数组元素过多:${t.message}`;case"format":return`格式错误:${t.message}`;case"enum":return`必须是枚举允许的值之一:${t.message}`;case"const":return`必须是指定的字面量值:${t.message}`;case"additionalProperties":case"unevaluatedProperties":return`包含未知参数:${t.message}`;case"anyOf":case"oneOf":return"不符合任何有效的类型定义";case"~refine":return t.message||"自定义验证失败";default:return t.message||`验证失败:${hn(i)}`}}class Jt extends Error{issues;type;constructor(t,i,n="validation_error"){super(t);this.issues=i;this.type=n;this.name="ToolValidationError"}}function Vt(t,i){let n=X(t,i);if(n.success)return n.data;let s=n.error.issues.map((r)=>({field:r.path.length>0?r.path.join("."):"root",message:An(r),value:r.value})),e=s.length===1?`参数验证失败 [${s[0].field}]: ${s[0].message}`:`参数验证失败 (${s.length} 个错误):
2
2
  ${s.map((r)=>` - ${r.field}: ${r.message}`).join(`
3
3
  `)}`;throw new Jt(e,s)}function st(t){if(!t||typeof t!=="object")return;let i=t;if(i.type==="object"&&i.properties)i.required??=[],i.additionalProperties??=!1;for(let n of Object.values(i))if(Array.isArray(n))for(let s of n)st(s);else st(n)}function et(t){let i=JSON.parse(JSON.stringify(t,(n,s)=>n.startsWith("~")?void 0:s));return st(i),i}class rt{toolName;params;executeFn;descriptionFn;affectedPathsFn;isRetrySafe;constructor(t,i,n,s,e,r=!1){this.toolName=t;this.params=i;this.executeFn=n;this.descriptionFn=s;this.affectedPathsFn=e;this.isRetrySafe=r}getDescription(){if(this.descriptionFn)return this.descriptionFn(this.params);return`执行工具: ${this.toolName}`}getAffectedPaths(){if(this.affectedPathsFn)return this.affectedPathsFn(this.params);return[]}async execute(t,i,n){let s={signal:t,updateOutput:i,...n};return this.executeFn(this.params,s)}}function jt(t){return{name:t.name,displayName:t.displayName,kind:t.kind,isConcurrencySafe:t.isConcurrencySafe??!1,isRetrySafe:t.isRetrySafe??!1,parallelism:t.parallelism??(t.isConcurrencySafe?"shared":"exclusive"),strict:t.strict??!1,description:t.description,version:t.version||"1.0.0",category:t.category,tags:t.tags||[],getFunctionDeclaration(){let i=et(t.schema),n=t.description.short;if(t.description.long)n+=`
4
4
 
@@ -1 +1 @@
1
- import{Af as d,Bf as e,Cf as f,Df as g,Ef as h,Ff as i,Gf as j,Hf as k,If as l,Jf as m,Kf as n,Lf as o,Mf as p,Nf as q,xf as a,yf as b,zf as c}from"./chunk-zc91c7b5.js";import"./chunk-v508x7cg.js";import"./chunk-mdew58v9.js";import"./chunk-hhg1zcbq.js";import"./chunk-jkfkyedn.js";import"./chunk-f8gb685p.js";import"./chunk-44jtpg8y.js";import"./chunk-sj1dzeta.js";import"./chunk-2y1qngw7.js";import"./chunk-ar5np5h5.js";import"./chunk-dfjmvj3d.js";import"./chunk-tkydv9k8.js";import"./chunk-v5hzk7j2.js";import"./chunk-qcvxff27.js";import"./chunk-zwjrensv.js";import"./chunk-pj69j4zp.js";import"./chunk-zkzhm39s.js";export{a as vanillaStore,c as sessionActions,l as getThinkingModeEnabled,b as getState,n as getServiceTier,o as getResponseVerbosity,m as getReasoningEffort,j as getModelById,e as getMessages,k as getMcpServers,i as getCurrentModel,f as getConfig,p as getCommunicationStyle,h as getAllModels,g as ensureStoreInitialized,q as configActions,d as appActions};
1
+ import{Af as d,Bf as e,Cf as f,Df as g,Ef as h,Ff as i,Gf as j,Hf as k,If as l,Jf as m,Kf as n,Lf as o,Mf as p,Nf as q,xf as a,yf as b,zf as c}from"./chunk-j3nmt09e.js";import"./chunk-v508x7cg.js";import"./chunk-mdew58v9.js";import"./chunk-0bkhpd72.js";import"./chunk-jkfkyedn.js";import"./chunk-f8gb685p.js";import"./chunk-44jtpg8y.js";import"./chunk-sj1dzeta.js";import"./chunk-2y1qngw7.js";import"./chunk-ar5np5h5.js";import"./chunk-dfjmvj3d.js";import"./chunk-tkydv9k8.js";import"./chunk-9d49tj9y.js";import"./chunk-qcvxff27.js";import"./chunk-zwjrensv.js";import"./chunk-pj69j4zp.js";import"./chunk-zkzhm39s.js";export{a as vanillaStore,c as sessionActions,l as getThinkingModeEnabled,b as getState,n as getServiceTier,o as getResponseVerbosity,m as getReasoningEffort,j as getModelById,e as getMessages,k as getMcpServers,i as getCurrentModel,f as getConfig,p as getCommunicationStyle,h as getAllModels,g as ensureStoreInitialized,q as configActions,d as appActions};
@@ -1,4 +1,4 @@
1
- import{e as i2,f as c2,g as Y3,h as l0,i as N3}from"./chunk-t4apxzp1.js";import{j as u1}from"./chunk-grhsv55v.js";import{v as p0,w as w2}from"./chunk-xa9k5pjt.js";import{A as E0,x as H2,y as B2,z as D2}from"./chunk-5a17mdjd.js";import{B as z2,C as O$,D as $$,E as Q$,F as $0,G as Z$}from"./chunk-9yqadjea.js";import{$ as w0,Ba as H3,J as $2,K as k1,L as w3,O as Q2,P as c0,Q as S4,R as y1,S as T$,T as K4,U as J2,V as J0,W as Y2,X as N2,Y as Y$,Z as Y1,_ as F4,aa as q0,da as x1,ea as L1,fa as q3,ga as X2,ha as V2,ia as q2,ja as E2,ka as S2,la as C2,ma as f2,na as P2,oa as k2,pa as m2,qa as h2,ta as l2,wa as g3}from"./chunk-v94ztjtp.js";import{Ia as F$,Oa as PO}from"./chunk-tw5fr07c.js";import{$a as f4,Sa as r1,Va as D3,Wa as C4,Xa as G2,Ya as U2,Za as x3,_a as L3,ab as M3,bb as P0,cb as n2,db as o2,eb as t2,fb as W2,gb as _2,hb as K2,ib as F2,jb as t4,kb as p4}from"./chunk-v52wc8yg.js";import{Kb as _4,Tb as f0,vb as kO,wb as o,yb as k,zb as Z2}from"./chunk-s2atpv23.js";import{cc as H4}from"./chunk-77efqpdc.js";import{Cc as i$,Ed as B1,Fd as B4,Gd as D1,Id as u0,Jc as c$,Kc as z4,Lc as a$,Ld as G4,Mc as G1,Nc as n$,Qc as Y4,Qd as O2,Rd as U4,Sd as W4,Td as v,bd as o$,md as t$,wd as K1,xd as C0}from"./chunk-7jj607dg.js";import{pe as s$,we as r$,xe as e$}from"./chunk-gfbkrk60.js";import{$e as J3,Se as r2,Ve as e2,We as O3,Xe as $3,Ye as Q3,Ze as q4,_e as Z3}from"./chunk-0z9nqbd0.js";import{Cf as DO,Gf as D$,Nf as uO,yf as I3}from"./chunk-zc91c7b5.js";import{Of as h1}from"./chunk-mdew58v9.js";import{dg as d$}from"./chunk-edtxcqxa.js";import{fg as P1}from"./chunk-8a6nrqdc.js";import{Cg as a3,Fg as tO,Gg as z1,Kg as g4,og as R3,qg as z3,tg as R2,xg as X1,yg as V1}from"./chunk-a4jetpj8.js";import{$g as l$,_g as x$}from"./chunk-aaxc81jc.js";import{dh as U$,eh as g0}from"./chunk-r9tawy93.js";import{$h as p$,Mh as m$,Ph as h$,Rh as y$,Sh as g$,Th as A$,Uh as b$,Vh as s4,ci as v$,ei as u$,ri as W$,wh as K$,wi as N1}from"./chunk-hhg1zcbq.js";import{zi as X4}from"./chunk-jkfkyedn.js";import{Bi as p1,Ei as V4}from"./chunk-f8gb685p.js";import{Ii as NO}from"./chunk-44jtpg8y.js";import{Ji as y,Li as z,Mi as rO,Oi as YO}from"./chunk-sj1dzeta.js";import{oj as $O}from"./chunk-ar5np5h5.js";import{uj as j0}from"./chunk-dfjmvj3d.js";import{Aj as k$,wj as H$,xj as P$,zj as B$}from"./chunk-tkydv9k8.js";import{Cj as y0}from"./chunk-v5hzk7j2.js";import{Jj as y4}from"./chunk-qcvxff27.js";import{Mj as g1,ek as _O,gk as S1,ok as X$}from"./chunk-pj69j4zp.js";import{rk as k4}from"./chunk-zkzhm39s.js";var h6={port:{type:"number",describe:"Port to listen on (0 for auto)",default:0},hostname:{type:"string",describe:"Hostname to listen on",default:"127.0.0.1"},cors:{type:"array",describe:"Additional domains to allow for CORS",default:[]}};function y6(O){return{port:O.port??0,hostname:O.hostname??"127.0.0.1",cors:O.cors??[]}}import{existsSync as v4,readFileSync as b1}from"node:fs";import{createServer as W6}from"node:http";import{networkInterfaces as _6}from"node:os";import{dirname as K6,extname as F6,join as L0}from"node:path";import{fileURLToPath as w6}from"node:url";import{brotliCompressSync as H6,gzipSync as B6,constants as D6}from"node:zlib";import{Hono as x6}from"hono";import{cors as L6}from"hono/cors";import{WebSocketServer as M6}from"ws";var h0=$O("Service"),V5=30000,z5=new Set(["completed","failed","cancelled","interrupted"]);class e1{dispatch;store;tickMs;timer;unsubscribeBus;ticking=!1;inFlight=new Set;constructor(O){this.dispatch=O.dispatch,this.store=O.store??t4.getInstance(),this.tickMs=O.tickMs??V5}start(){if(this.timer)return;h0.info("[TaskScheduler] Starting scheduler tick loop"),this.timer=setInterval(()=>{this.tick()},this.tickMs),this.timer.unref?.(),this.unsubscribeBus=k.subscribe((O)=>{if(O.type!=="task.status")return;let $=O.properties.taskStatus;if(typeof $!=="string"||!z5.has($))return;this.recordTerminalStatus(O.sessionId,$,typeof O.properties.taskStatusReason==="string"?O.properties.taskStatusReason:void 0)}),this.tick()}stop(){if(this.timer)clearInterval(this.timer),this.timer=void 0,this.unsubscribeBus?.(),this.unsubscribeBus=void 0,h0.info("[TaskScheduler] Stopped scheduler tick loop")}async tick(O=new Date){if(this.ticking)return;this.ticking=!0;try{let $=await this.store.list();for(let Q of $)await this.evaluate(Q,O)}catch($){h0.warn("[TaskScheduler] Tick failed:",$)}finally{this.ticking=!1}}async evaluate(O,$){if(!O.enabled)return;if(this.inFlight.has(O.id))return;if(O.expiresAt&&new Date(O.expiresAt).getTime()<=$.getTime()){await this.store.update(O.id,{enabled:!1,nextRunAt:null}),h0.info(`[TaskScheduler] Schedule ${O.id} expired; disabled`);return}if(!O.nextRunAt)return;if(!(new Date(O.nextRunAt).getTime()<=$.getTime()))return;await this.fire(O,$)}async fire(O,$=new Date,Q={}){if(this.inFlight.has(O.id))throw Error(`Schedule ${O.id} is already dispatching`);this.inFlight.add(O.id);let Z=$.toISOString();try{let J=await this.dispatch({prompt:O.prompt,title:O.title??G5(O),sourceProjectPath:O.projectPath,isolation:O.dispatch.isolation??"worktree",permissionMode:O.dispatch.permissionMode??"default",modelId:O.dispatch.modelId,reasoningEffort:O.dispatch.reasoningEffort,serviceTier:O.dispatch.serviceTier,responseVerbosity:O.dispatch.responseVerbosity,communicationStyle:O.dispatch.communicationStyle}),N=O.trigger.kind==="once"?null:Q.manual?O.nextRunAt?new Date(O.nextRunAt):null:r1(O.trigger,$,$);await this.store.update(O.id,{lastRunAt:Z,lastRunSessionId:J.session.sessionId,lastStatus:J.status,lastError:void 0,runCount:O.runCount+1,nextRunAt:N?N.toISOString():null,enabled:O.trigger.kind==="once"?!1:O.enabled}),k.publish({sessionId:J.session.sessionId,projectPath:O.projectPath},"schedule.fired",{scheduleId:O.id,firedAt:Z,sessionId:J.session.sessionId,runId:J.runId,status:J.status}),h0.info(`[TaskScheduler] Fired schedule ${O.id} -> session ${J.session.sessionId} (${J.status})`)}catch(J){let N=J instanceof Error?J.message:String(J);h0.warn(`[TaskScheduler] Schedule ${O.id} dispatch failed:`,J);let X=O.trigger.kind==="once"?null:Q.manual?O.nextRunAt?new Date(O.nextRunAt):null:r1(O.trigger,$,$);await this.store.update(O.id,{lastRunAt:Z,lastStatus:"error",lastError:N,nextRunAt:X?X.toISOString():null,enabled:O.trigger.kind==="once"?!1:O.enabled})}finally{this.inFlight.delete(O.id)}}async recordTerminalStatus(O,$,Q){let J=(await this.store.list()).find((N)=>N.lastRunSessionId===O);if(!J)return;await this.store.update(J.id,{lastStatus:$,...Q?{lastError:Q}:{lastError:void 0}})}}function G5(O){return`Scheduled: ${O.prompt.trim().replace(/\s+/g," ").slice(0,60)}`}class zO extends Error{code;statusCode;details;constructor(O,$,Q=500,Z){super($);this.code=O;this.statusCode=Q;this.details=Z;this.name="BladeServerError"}toObject(){return{error:{code:this.code,message:this.message,...this.details?{details:this.details}:{}}}}}class l extends zO{constructor(O,$){super("NOT_FOUND",$?`${O} not found: ${$}`:`${O} not found`,404)}}class w extends zO{constructor(O){super("BAD_REQUEST",O,400)}}class u extends zO{constructor(O){super("CONFLICT",O,409)}}class cO extends zO{constructor(O,$){super("TOO_MANY_REQUESTS",O,429,$)}}class BO extends zO{constructor(O="Server is shutting down"){super("SERVICE_UNAVAILABLE",O,503)}}class q1 extends zO{constructor(O){super("SESSION_WORKSPACE_UNAVAILABLE","This session workspace is no longer available",409,{reason:O})}}class fO extends zO{constructor(){super("AMBIGUOUS_SESSION","Multiple workspaces contain this session ID; projectPath is required",409)}}class JO extends zO{constructor(O="Internal server error"){super("INTERNAL_ERROR",O,500)}}var c6=z.Object({error:z.Object({code:z.String(),message:z.String(),details:z.Optional(z.Record(z.String(),z.Unknown()))})});import{Hono as U5}from"hono";var O4=$O("Service"),W5=z.Object({updates:z.Record(z.String(),z.Any()),options:z.Optional(z.Object({scope:z.Optional(YO(["local","project","global"])),immediate:z.Optional(z.Boolean())}))});function _5(O){return{currentModelId:O.currentModelId,permissionMode:O.permissionMode,language:O.language,codeTheme:O.codeTheme,uiTheme:O.uiTheme,autoSaveSessions:O.autoSaveSessions,notifyBuild:O.notifyBuild,notifyErrors:O.notifyErrors,notifySounds:O.notifySounds,privacyTelemetry:O.privacyTelemetry,privacyCrash:O.privacyCrash,agentTeamsEnabled:O.agentTeamsEnabled===!0,communicationStyle:O.communicationStyle,maxConcurrentTasks:O.maxConcurrentTasks,maxQueuedTasks:O.maxQueuedTasks,maxQueuedTaskBytes:O.maxQueuedTaskBytes,maxResidentSessionRuntimes:O.maxResidentSessionRuntimes,sessionRuntimeIdleMs:O.sessionRuntimeIdleMs,maxResidentSessionProjections:O.maxResidentSessionProjections,sessionProjectionIdleMs:O.sessionProjectionIdleMs}}var r4=()=>{let O=new U5;return O.get("/",async($)=>{try{let Q=DO();return $.json(Q?_5(Q):{})}catch(Q){return O4.error("[ConfigRoutes] Failed to get config:",Q),$.json({})}}),O.put("/",async($)=>{try{let Q=await $.req.json(),Z=y(W5,Q);if(!Z.success)throw new w("Invalid config update format");let{updates:J,options:N}=Z.data;return await uO().updateConfig(J,N),$.json({success:!0,updates:J})}catch(Q){if(Q instanceof s4)throw new w(Q.message);throw O4.error("[ConfigRoutes] Failed to update config:",Q),Q}}),O.get("/permissions",async($)=>{try{let Q=DO();return $.json(Q?.permissions||{})}catch(Q){return O4.error("[ConfigRoutes] Failed to get permissions:",Q),$.json({})}}),O};import{Hono as K5}from"hono";import{streamSSE as F5}from"hono/streaming";function e4(O){let $="";if(O.id!==void 0)$+=`id: ${O.id}
1
+ import{e as i2,f as c2,g as Y3,h as l0,i as N3}from"./chunk-dvb89529.js";import{j as u1}from"./chunk-grhsv55v.js";import{v as p0,w as w2}from"./chunk-bavzm721.js";import{A as E0,x as H2,y as B2,z as D2}from"./chunk-qcydkn1n.js";import{B as z2,C as O$,D as $$,E as Q$,F as $0,G as Z$}from"./chunk-6q3g5e3m.js";import{$ as w0,Ba as H3,J as $2,K as k1,L as w3,O as Q2,P as c0,Q as S4,R as y1,S as T$,T as K4,U as J2,V as J0,W as Y2,X as N2,Y as Y$,Z as Y1,_ as F4,aa as q0,da as x1,ea as L1,fa as q3,ga as X2,ha as V2,ia as q2,ja as E2,ka as S2,la as C2,ma as f2,na as P2,oa as k2,pa as m2,qa as h2,ta as l2,wa as g3}from"./chunk-xjrmq0pg.js";import{Ia as F$,Oa as PO}from"./chunk-sbc90z9j.js";import{$a as f4,Sa as r1,Va as D3,Wa as C4,Xa as G2,Ya as U2,Za as x3,_a as L3,ab as M3,bb as P0,cb as n2,db as o2,eb as t2,fb as W2,gb as _2,hb as K2,ib as F2,jb as t4,kb as p4}from"./chunk-v52wc8yg.js";import{Kb as _4,Tb as f0,vb as kO,wb as o,yb as k,zb as Z2}from"./chunk-3e0t25rq.js";import{cc as H4}from"./chunk-77efqpdc.js";import{Cc as i$,Ed as B1,Fd as B4,Gd as D1,Id as u0,Jc as c$,Kc as z4,Lc as a$,Ld as G4,Mc as G1,Nc as n$,Qc as Y4,Qd as O2,Rd as U4,Sd as W4,Td as v,bd as o$,md as t$,wd as K1,xd as C0}from"./chunk-rj8mmwc6.js";import{pe as s$,we as r$,xe as e$}from"./chunk-b5z1rec4.js";import{$e as J3,Se as r2,Ve as e2,We as O3,Xe as $3,Ye as Q3,Ze as q4,_e as Z3}from"./chunk-0z9nqbd0.js";import{Cf as DO,Gf as D$,Nf as uO,yf as I3}from"./chunk-j3nmt09e.js";import{Of as h1}from"./chunk-mdew58v9.js";import{dg as d$}from"./chunk-edtxcqxa.js";import{fg as P1}from"./chunk-e371f7xk.js";import{Cg as a3,Fg as tO,Gg as z1,Kg as g4,og as R3,qg as z3,tg as R2,xg as X1,yg as V1}from"./chunk-t8rjxqp2.js";import{$g as l$,_g as x$}from"./chunk-aaxc81jc.js";import{dh as U$,eh as g0}from"./chunk-r7kevfd3.js";import{$h as p$,Mh as m$,Ph as h$,Rh as y$,Sh as g$,Th as A$,Uh as b$,Vh as s4,ci as v$,ei as u$,ri as W$,wh as K$,wi as N1}from"./chunk-0bkhpd72.js";import{zi as X4}from"./chunk-jkfkyedn.js";import{Bi as p1,Ei as V4}from"./chunk-f8gb685p.js";import{Ii as NO}from"./chunk-44jtpg8y.js";import{Ji as y,Li as z,Mi as rO,Oi as YO}from"./chunk-sj1dzeta.js";import{oj as $O}from"./chunk-ar5np5h5.js";import{uj as j0}from"./chunk-dfjmvj3d.js";import{Aj as k$,wj as H$,xj as P$,zj as B$}from"./chunk-tkydv9k8.js";import{Cj as y0}from"./chunk-9d49tj9y.js";import{Jj as y4}from"./chunk-qcvxff27.js";import{Mj as g1,ek as _O,gk as S1,ok as X$}from"./chunk-pj69j4zp.js";import{rk as k4}from"./chunk-zkzhm39s.js";var h6={port:{type:"number",describe:"Port to listen on (0 for auto)",default:0},hostname:{type:"string",describe:"Hostname to listen on",default:"127.0.0.1"},cors:{type:"array",describe:"Additional domains to allow for CORS",default:[]}};function y6(O){return{port:O.port??0,hostname:O.hostname??"127.0.0.1",cors:O.cors??[]}}import{existsSync as v4,readFileSync as b1}from"node:fs";import{createServer as W6}from"node:http";import{networkInterfaces as _6}from"node:os";import{dirname as K6,extname as F6,join as L0}from"node:path";import{fileURLToPath as w6}from"node:url";import{brotliCompressSync as H6,gzipSync as B6,constants as D6}from"node:zlib";import{Hono as x6}from"hono";import{cors as L6}from"hono/cors";import{WebSocketServer as M6}from"ws";var h0=$O("Service"),V5=30000,z5=new Set(["completed","failed","cancelled","interrupted"]);class e1{dispatch;store;tickMs;timer;unsubscribeBus;ticking=!1;inFlight=new Set;constructor(O){this.dispatch=O.dispatch,this.store=O.store??t4.getInstance(),this.tickMs=O.tickMs??V5}start(){if(this.timer)return;h0.info("[TaskScheduler] Starting scheduler tick loop"),this.timer=setInterval(()=>{this.tick()},this.tickMs),this.timer.unref?.(),this.unsubscribeBus=k.subscribe((O)=>{if(O.type!=="task.status")return;let $=O.properties.taskStatus;if(typeof $!=="string"||!z5.has($))return;this.recordTerminalStatus(O.sessionId,$,typeof O.properties.taskStatusReason==="string"?O.properties.taskStatusReason:void 0)}),this.tick()}stop(){if(this.timer)clearInterval(this.timer),this.timer=void 0,this.unsubscribeBus?.(),this.unsubscribeBus=void 0,h0.info("[TaskScheduler] Stopped scheduler tick loop")}async tick(O=new Date){if(this.ticking)return;this.ticking=!0;try{let $=await this.store.list();for(let Q of $)await this.evaluate(Q,O)}catch($){h0.warn("[TaskScheduler] Tick failed:",$)}finally{this.ticking=!1}}async evaluate(O,$){if(!O.enabled)return;if(this.inFlight.has(O.id))return;if(O.expiresAt&&new Date(O.expiresAt).getTime()<=$.getTime()){await this.store.update(O.id,{enabled:!1,nextRunAt:null}),h0.info(`[TaskScheduler] Schedule ${O.id} expired; disabled`);return}if(!O.nextRunAt)return;if(!(new Date(O.nextRunAt).getTime()<=$.getTime()))return;await this.fire(O,$)}async fire(O,$=new Date,Q={}){if(this.inFlight.has(O.id))throw Error(`Schedule ${O.id} is already dispatching`);this.inFlight.add(O.id);let Z=$.toISOString();try{let J=await this.dispatch({prompt:O.prompt,title:O.title??G5(O),sourceProjectPath:O.projectPath,isolation:O.dispatch.isolation??"worktree",permissionMode:O.dispatch.permissionMode??"default",modelId:O.dispatch.modelId,reasoningEffort:O.dispatch.reasoningEffort,serviceTier:O.dispatch.serviceTier,responseVerbosity:O.dispatch.responseVerbosity,communicationStyle:O.dispatch.communicationStyle}),N=O.trigger.kind==="once"?null:Q.manual?O.nextRunAt?new Date(O.nextRunAt):null:r1(O.trigger,$,$);await this.store.update(O.id,{lastRunAt:Z,lastRunSessionId:J.session.sessionId,lastStatus:J.status,lastError:void 0,runCount:O.runCount+1,nextRunAt:N?N.toISOString():null,enabled:O.trigger.kind==="once"?!1:O.enabled}),k.publish({sessionId:J.session.sessionId,projectPath:O.projectPath},"schedule.fired",{scheduleId:O.id,firedAt:Z,sessionId:J.session.sessionId,runId:J.runId,status:J.status}),h0.info(`[TaskScheduler] Fired schedule ${O.id} -> session ${J.session.sessionId} (${J.status})`)}catch(J){let N=J instanceof Error?J.message:String(J);h0.warn(`[TaskScheduler] Schedule ${O.id} dispatch failed:`,J);let X=O.trigger.kind==="once"?null:Q.manual?O.nextRunAt?new Date(O.nextRunAt):null:r1(O.trigger,$,$);await this.store.update(O.id,{lastRunAt:Z,lastStatus:"error",lastError:N,nextRunAt:X?X.toISOString():null,enabled:O.trigger.kind==="once"?!1:O.enabled})}finally{this.inFlight.delete(O.id)}}async recordTerminalStatus(O,$,Q){let J=(await this.store.list()).find((N)=>N.lastRunSessionId===O);if(!J)return;await this.store.update(J.id,{lastStatus:$,...Q?{lastError:Q}:{lastError:void 0}})}}function G5(O){return`Scheduled: ${O.prompt.trim().replace(/\s+/g," ").slice(0,60)}`}class zO extends Error{code;statusCode;details;constructor(O,$,Q=500,Z){super($);this.code=O;this.statusCode=Q;this.details=Z;this.name="BladeServerError"}toObject(){return{error:{code:this.code,message:this.message,...this.details?{details:this.details}:{}}}}}class l extends zO{constructor(O,$){super("NOT_FOUND",$?`${O} not found: ${$}`:`${O} not found`,404)}}class w extends zO{constructor(O){super("BAD_REQUEST",O,400)}}class u extends zO{constructor(O){super("CONFLICT",O,409)}}class cO extends zO{constructor(O,$){super("TOO_MANY_REQUESTS",O,429,$)}}class BO extends zO{constructor(O="Server is shutting down"){super("SERVICE_UNAVAILABLE",O,503)}}class q1 extends zO{constructor(O){super("SESSION_WORKSPACE_UNAVAILABLE","This session workspace is no longer available",409,{reason:O})}}class fO extends zO{constructor(){super("AMBIGUOUS_SESSION","Multiple workspaces contain this session ID; projectPath is required",409)}}class JO extends zO{constructor(O="Internal server error"){super("INTERNAL_ERROR",O,500)}}var c6=z.Object({error:z.Object({code:z.String(),message:z.String(),details:z.Optional(z.Record(z.String(),z.Unknown()))})});import{Hono as U5}from"hono";var O4=$O("Service"),W5=z.Object({updates:z.Record(z.String(),z.Any()),options:z.Optional(z.Object({scope:z.Optional(YO(["local","project","global"])),immediate:z.Optional(z.Boolean())}))});function _5(O){return{currentModelId:O.currentModelId,permissionMode:O.permissionMode,language:O.language,codeTheme:O.codeTheme,uiTheme:O.uiTheme,autoSaveSessions:O.autoSaveSessions,notifyBuild:O.notifyBuild,notifyErrors:O.notifyErrors,notifySounds:O.notifySounds,privacyTelemetry:O.privacyTelemetry,privacyCrash:O.privacyCrash,agentTeamsEnabled:O.agentTeamsEnabled===!0,communicationStyle:O.communicationStyle,maxConcurrentTasks:O.maxConcurrentTasks,maxQueuedTasks:O.maxQueuedTasks,maxQueuedTaskBytes:O.maxQueuedTaskBytes,maxResidentSessionRuntimes:O.maxResidentSessionRuntimes,sessionRuntimeIdleMs:O.sessionRuntimeIdleMs,maxResidentSessionProjections:O.maxResidentSessionProjections,sessionProjectionIdleMs:O.sessionProjectionIdleMs}}var r4=()=>{let O=new U5;return O.get("/",async($)=>{try{let Q=DO();return $.json(Q?_5(Q):{})}catch(Q){return O4.error("[ConfigRoutes] Failed to get config:",Q),$.json({})}}),O.put("/",async($)=>{try{let Q=await $.req.json(),Z=y(W5,Q);if(!Z.success)throw new w("Invalid config update format");let{updates:J,options:N}=Z.data;return await uO().updateConfig(J,N),$.json({success:!0,updates:J})}catch(Q){if(Q instanceof s4)throw new w(Q.message);throw O4.error("[ConfigRoutes] Failed to update config:",Q),Q}}),O.get("/permissions",async($)=>{try{let Q=DO();return $.json(Q?.permissions||{})}catch(Q){return O4.error("[ConfigRoutes] Failed to get permissions:",Q),$.json({})}}),O};import{Hono as K5}from"hono";import{streamSSE as F5}from"hono/streaming";function e4(O){let $="";if(O.id!==void 0)$+=`id: ${O.id}
2
2
  `;if(O.event!==void 0)$+=`event: ${O.event}
3
3
  `;for(let Q of O.data.split(/\r\n|\r|\n/))$+=`data: ${Q}
4
4
  `;if(O.retry!==void 0)$+=`retry: ${O.retry}
@@ -1,4 +1,4 @@
1
- import{Lg as A1,Mg as L0,Ng as M1,Sg as v0}from"./chunk-sx77dpxw.js";import{Zg as SO,_g as F1}from"./chunk-aaxc81jc.js";import{bh as x1}from"./chunk-93x9xbew.js";import{ch as A0,eh as J0}from"./chunk-r9tawy93.js";import{ri as z0,si as WO,wi as b0}from"./chunk-hhg1zcbq.js";import{Ii as M}from"./chunk-44jtpg8y.js";import{Ji as u,Li as L,Oi as l1}from"./chunk-sj1dzeta.js";import{oj as P,pj as S}from"./chunk-ar5np5h5.js";import{Cj as c0}from"./chunk-v5hzk7j2.js";import{Jj as N}from"./chunk-qcvxff27.js";import{ek as qO}from"./chunk-pj69j4zp.js";import N0 from"node:path";import YO from"node:path";import y0 from"node:fs";import W0 from"node:os";import E from"node:path";import pO from"yaml";var V1=2000,j1=50,B1=1000,X4={type:"object",properties:{verdict:{type:"string",enum:["pass","fail","partial"]},summary:{type:"string",minLength:1,maxLength:V1},findings:{type:"array",maxItems:j1,items:{type:"string",minLength:1,maxLength:B1}}},required:["verdict","summary","findings"],additionalProperties:!1};function U1(O,$){let Q=O.trim().replaceAll(/\s+/g," ");if($)Q=Q.replaceAll($,".");return Q.replace(/\bBearer\s+[^\s"'`]+/gi,"Bearer [redacted]").replace(/\bsk-[A-Za-z0-9_-]{8,}\b/g,"[redacted-key]").replace(/\b(api(?:[_-]?|\s+)key|access(?:[_-]?|\s+)token|authorization|cookie|password|passwd|refresh(?:[_-]?|\s+)token|secret|session(?:[_-]?|\s+)token)\b(\s*[:=]\s*)([^\s,;]+)/gi,"$1$2[redacted]")}function kO(O){if(O.length<=v0)return O;let $=" [verification feedback truncated]",Q=O.slice(0,v0-$.length);if(/[\uD800-\uDBFF]$/.test(Q))Q=Q.slice(0,-1);return Q.trimEnd()+$}function S1(O){if(!O||typeof O!=="object"||Array.isArray(O))return;let $=O;if($.verdict!=="pass"&&$.verdict!=="fail"&&$.verdict!=="partial"||typeof $.summary!=="string"||!$.summary.trim()||$.summary.length>V1||!Array.isArray($.findings)||$.findings.length>j1||!$.findings.every((Q)=>typeof Q==="string"&&Q.trim().length>0&&Q.length<=B1))return;return{verdict:$.verdict,summary:$.summary.trim(),findings:$.findings.map((Q)=>Q.trim())}}function H4(O,$){let Q=S1(O);if(!Q)return;let Z=U1(Q.summary,$),J=Q.findings.map((K)=>U1(K,$));return kO([Z,J.length>0?`Findings:
1
+ import{Lg as A1,Mg as L0,Ng as M1,Sg as v0}from"./chunk-sx77dpxw.js";import{Zg as SO,_g as F1}from"./chunk-aaxc81jc.js";import{bh as x1}from"./chunk-93x9xbew.js";import{ch as A0,eh as J0}from"./chunk-r7kevfd3.js";import{ri as z0,si as WO,wi as b0}from"./chunk-0bkhpd72.js";import{Ii as M}from"./chunk-44jtpg8y.js";import{Ji as u,Li as L,Oi as l1}from"./chunk-sj1dzeta.js";import{oj as P,pj as S}from"./chunk-ar5np5h5.js";import{Cj as c0}from"./chunk-9d49tj9y.js";import{Jj as N}from"./chunk-qcvxff27.js";import{ek as qO}from"./chunk-pj69j4zp.js";import N0 from"node:path";import YO from"node:path";import y0 from"node:fs";import W0 from"node:os";import E from"node:path";import pO from"yaml";var V1=2000,j1=50,B1=1000,X4={type:"object",properties:{verdict:{type:"string",enum:["pass","fail","partial"]},summary:{type:"string",minLength:1,maxLength:V1},findings:{type:"array",maxItems:j1,items:{type:"string",minLength:1,maxLength:B1}}},required:["verdict","summary","findings"],additionalProperties:!1};function U1(O,$){let Q=O.trim().replaceAll(/\s+/g," ");if($)Q=Q.replaceAll($,".");return Q.replace(/\bBearer\s+[^\s"'`]+/gi,"Bearer [redacted]").replace(/\bsk-[A-Za-z0-9_-]{8,}\b/g,"[redacted-key]").replace(/\b(api(?:[_-]?|\s+)key|access(?:[_-]?|\s+)token|authorization|cookie|password|passwd|refresh(?:[_-]?|\s+)token|secret|session(?:[_-]?|\s+)token)\b(\s*[:=]\s*)([^\s,;]+)/gi,"$1$2[redacted]")}function kO(O){if(O.length<=v0)return O;let $=" [verification feedback truncated]",Q=O.slice(0,v0-$.length);if(/[\uD800-\uDBFF]$/.test(Q))Q=Q.slice(0,-1);return Q.trimEnd()+$}function S1(O){if(!O||typeof O!=="object"||Array.isArray(O))return;let $=O;if($.verdict!=="pass"&&$.verdict!=="fail"&&$.verdict!=="partial"||typeof $.summary!=="string"||!$.summary.trim()||$.summary.length>V1||!Array.isArray($.findings)||$.findings.length>j1||!$.findings.every((Q)=>typeof Q==="string"&&Q.trim().length>0&&Q.length<=B1))return;return{verdict:$.verdict,summary:$.summary.trim(),findings:$.findings.map((Q)=>Q.trim())}}function H4(O,$){let Q=S1(O);if(!Q)return;let Z=U1(Q.summary,$),J=Q.findings.map((K)=>U1(K,$));return kO([Z,J.length>0?`Findings:
2
2
  ${J.map((K)=>`- ${K}`).join(`
3
3
  `)}`:""].filter(Boolean).join(`
4
4
 
@@ -1,4 +1,4 @@
1
- import"./chunk-v508x7cg.js";import{wi as Q}from"./chunk-hhg1zcbq.js";import"./chunk-jkfkyedn.js";import"./chunk-f8gb685p.js";import{Ii as L}from"./chunk-44jtpg8y.js";import"./chunk-sj1dzeta.js";import"./chunk-2y1qngw7.js";import"./chunk-ar5np5h5.js";import"./chunk-dfjmvj3d.js";import"./chunk-tkydv9k8.js";import"./chunk-v5hzk7j2.js";import"./chunk-qcvxff27.js";import"./chunk-zwjrensv.js";import"./chunk-pj69j4zp.js";import{rk as F}from"./chunk-zkzhm39s.js";var K=[22,19,0];function T(G){let A=/^v?(\d+)\.(\d+)\.(\d+)/.exec(G);if(!A)return!1;let H=A.slice(1).map(Number);for(let z=0;z<K.length;z++){let B=H[z]??0,J=K[z];if(B!==J)return B>J}return!0}var X={command:"doctor",describe:"Check the health of your Blade installation",builder:(G)=>G.option("rebuild-index",{type:"boolean",default:!1,describe:"Rebuild the SQLite session index from JSONL transcripts"}),handler:async(G)=>{if(G.rebuildIndex){console.log(`Rebuilding session index from JSONL transcripts...
2
- `);try{let{rebuildProjectionIndex:z}=await import("./chunk-2bnpn8be.js"),{SessionService:B}=await import("./chunk-h1wphqkc.js"),J=await z(B.projectionDeriverForSearch());if(J===null)console.log("[WARN] Session index unavailable (SQLite driver missing); reads fall back to JSONL scan.");else console.log(`[OK] Session index rebuilt: ${J} session(s) indexed.`)}catch(z){console.log("[FAIL] Session index rebuild failed"),console.log(` Error: ${z instanceof Error?z.message:"未知错误"}`),process.exit(1)}return}console.log(`Running Blade health check...
1
+ import"./chunk-v508x7cg.js";import{wi as Q}from"./chunk-0bkhpd72.js";import"./chunk-jkfkyedn.js";import"./chunk-f8gb685p.js";import{Ii as L}from"./chunk-44jtpg8y.js";import"./chunk-sj1dzeta.js";import"./chunk-2y1qngw7.js";import"./chunk-ar5np5h5.js";import"./chunk-dfjmvj3d.js";import"./chunk-tkydv9k8.js";import"./chunk-9d49tj9y.js";import"./chunk-qcvxff27.js";import"./chunk-zwjrensv.js";import"./chunk-pj69j4zp.js";import{rk as F}from"./chunk-zkzhm39s.js";var K=[22,19,0];function T(G){let A=/^v?(\d+)\.(\d+)\.(\d+)/.exec(G);if(!A)return!1;let H=A.slice(1).map(Number);for(let z=0;z<K.length;z++){let B=H[z]??0,J=K[z];if(B!==J)return B>J}return!0}var X={command:"doctor",describe:"Check the health of your Blade installation",builder:(G)=>G.option("rebuild-index",{type:"boolean",default:!1,describe:"Rebuild the SQLite session index from JSONL transcripts"}),handler:async(G)=>{if(G.rebuildIndex){console.log(`Rebuilding session index from JSONL transcripts...
2
+ `);try{let{rebuildProjectionIndex:z}=await import("./chunk-mg1s861p.js"),{SessionService:B}=await import("./chunk-53j6nh8j.js"),J=await z(B.projectionDeriverForSearch());if(J===null)console.log("[WARN] Session index unavailable (SQLite driver missing); reads fall back to JSONL scan.");else console.log(`[OK] Session index rebuilt: ${J} session(s) indexed.`)}catch(z){console.log("[FAIL] Session index rebuild failed"),console.log(` Error: ${z instanceof Error?z.message:"未知错误"}`),process.exit(1)}return}console.log(`Running Blade health check...
3
3
  `);let A=0;try{await Q.getInstance().initialize(),console.log("[OK] Configuration: OK")}catch(z){console.log("[FAIL] Configuration: FAILED"),console.log(` Error: ${z instanceof Error?z.message:"未知错误"}`),A++}let H=process.version;if(T(H))console.log(`[OK] Node.js version: ${H}`);else console.log(`[WARN] Node.js version: ${H} (required: >=22.19.0)`),A++;try{let z=await import("fs/promises"),B=L();await z.access(B,(await import("fs")).constants.R_OK|(await import("fs")).constants.W_OK),console.log("[OK] File system permissions: OK")}catch(z){console.log("[FAIL] File system permissions: FAILED"),console.log(" Error: Cannot read/write in current directory"),A++}try{await import("ink"),console.log("[OK] Dependencies: OK")}catch(z){console.log("[FAIL] Dependencies: FAILED"),console.log(" Error: Missing required dependencies"),A++}if(console.log(`
4
4
  Health Check Summary:`),A===0)console.log("All checks passed! Blade is ready to use.");else console.log(`Warning: Found ${A} issue(s). Please resolve them for optimal performance.`),process.exit(1)}};export{T as isSupportedNodeVersion,X as doctorCommands};
@@ -1,4 +1,4 @@
1
- import{Da as m9}from"./chunk-6p6ts4kv.js";import{Ga as T,Ha as t0,Ma as SX,Na as WY,Oa as o0}from"./chunk-tw5fr07c.js";import{Pa as a8,Ra as wU,Ta as FU,Ua as V9,kb as _U}from"./chunk-v52wc8yg.js";import{Ab as K2,Db as h4,Fb as zZ,Gb as g4,Hb as u4,Jb as UJ,Kb as M$,Qb as X8,Rb as OX,Sb as PQ,Ub as h1,Vb as YX,_b as AY,bc as MY,lb as e$,mb as z2,nb as c7,ob as y1,pb as T7,qb as i7,rb as v7,sb as r7,tb as n7,ub as uY,wb as SQ,yb as z0}from"./chunk-s2atpv23.js";import{$c as u6,Ac as g8,Ad as L$,Bc as s$,Cc as o$,Dc as u2,Ec as g2,Fc as d2,Gc as S6,Hc as v6,Hd as MX,Ic as x2,Jc as i9,Kc as I2,Lc as u8,Ld as EY,Mc as A1,Nc as s1,Oc as h2,Pc as o1,Qc as t1,Qd as ZX,Rc as y6,Rd as JX,Sc as e1,Tc as k6,Td as s,Uc as x6,Vc as f$,Wc as I6,Xc as J3,Yc as m2,Zc as h6,_c as g6,ad as d6,bd as Y3,cd as Q3,ed as X3,hc as t$,ic as oQ,jc as T3,kc as q3,lc as Z2,mc as x3,nc as _0,oc as C2,pc as L1,qc as A6,rc as G9,sc as x4,tc as I4,uc as k7,vc as x7,wc as tQ,xc as d9,xd as $8,yc as E1,zc as g9,zd as f0}from"./chunk-7jj607dg.js";import{Ud as p,Vd as cY,Wd as lY,Xd as _J,Zd as G2}from"./chunk-53h87fmt.js";import{$d as OU,Ee as bU,Re as jU,ce as NU,qe as K9,re as e0,se as H2,te as xZ,ue as eQ,ve as $X}from"./chunk-gfbkrk60.js";import{kf as JJ,lf as $J}from"./chunk-a60cmnmz.js";import{Cf as E0,Df as A4,Ef as D2,Ff as z1,Gf as _Z,Hf as C1,If as bY,Nf as U2,xf as d4,yf as q0,zf as g}from"./chunk-zc91c7b5.js";import{Of as g1}from"./chunk-mdew58v9.js";import{Sf as DZ,Tf as jY,Uf as OY,Zf as KX,_f as M4}from"./chunk-ajsw4te2.js";import{ag as d0,bg as F1}from"./chunk-mvm1rzc4.js";import{cg as bX}from"./chunk-edtxcqxa.js";import{eg as cQ,fg as lQ,gg as iQ,hg as rQ}from"./chunk-8a6nrqdc.js";import{Dg as hZ,Fg as m0,Gg as C$,Ig as C4,Jg as sQ,Kg as QX,ig as P4,jg as S4,kg as v4,mg as y4,ng as k4,og as q1,pg as sY,rg as v$,sg as O$,tg as z$,ug as i8,vg as J2,wg as Y8,xg as p1,yg as c1,zg as aQ}from"./chunk-a4jetpj8.js";import{Mg as B1,Og as A$,Pg as D4,Qg as j3,Rg as E3,Sg as l2,Tg as A3,Ug as M3,Vg as a6,Wg as C3,Xg as i6}from"./chunk-sx77dpxw.js";import{$g as e4,Yg as mX,_g as nQ,ah as YJ}from"./chunk-aaxc81jc.js";import{ch as Z9,eh as x0}from"./chunk-r9tawy93.js";import{fh as F6,gh as B9,hh as _6,ih as l1}from"./chunk-g4xny949.js";import{Ah as m3,Ch as uQ,Eh as m7,Fh as p7,Wh as x1,Zh as S7,hi as HY,ii as BY,ji as GY,kh as u3,ki as KY,li as wZ,mi as DY,ni as W1,oi as qY,ph as d3,pi as wY,qi as FY,rh as sZ,si as v3,ui as UX,vi as pQ,wh as PX,wi as H0}from"./chunk-hhg1zcbq.js";import{zi as w$}from"./chunk-jkfkyedn.js";import{Bi as RQ,Di as fQ}from"./chunk-f8gb685p.js";import{Gi as e6,Ii as C}from"./chunk-44jtpg8y.js";import{Ji as m6,Ki as n6,Li as K,Mi as B3,Ni as P,Oi as u}from"./chunk-sj1dzeta.js";import{oj as t}from"./chunk-ar5np5h5.js";import{tj as dQ,uj as mQ}from"./chunk-dfjmvj3d.js";import{vj as cX,yj as uX}from"./chunk-tkydv9k8.js";import{Cj as nX}from"./chunk-v5hzk7j2.js";import{Ij as XX,Jj as r0}from"./chunk-qcvxff27.js";import{Mj as o,Nj as _$,Oj as B$,Pj as a1,Qj as v9,Rj as k2,Sj as J$,Tj as P7,Wj as f6,dk as E6,gk as N$,lk as b3}from"./chunk-pj69j4zp.js";import{rk as $$}from"./chunk-zkzhm39s.js";import{randomUUID as L8}from"crypto";import{randomUUID as mU}from"node:crypto";var IU=String.raw`
1
+ import{Da as m9}from"./chunk-6p6ts4kv.js";import{Ga as T,Ha as t0,Ma as SX,Na as WY,Oa as o0}from"./chunk-sbc90z9j.js";import{Pa as a8,Ra as wU,Ta as FU,Ua as V9,kb as _U}from"./chunk-v52wc8yg.js";import{Ab as K2,Db as h4,Fb as zZ,Gb as g4,Hb as u4,Jb as UJ,Kb as M$,Qb as X8,Rb as OX,Sb as PQ,Ub as h1,Vb as YX,_b as AY,bc as MY,lb as e$,mb as z2,nb as c7,ob as y1,pb as T7,qb as i7,rb as v7,sb as r7,tb as n7,ub as uY,wb as SQ,yb as z0}from"./chunk-3e0t25rq.js";import{$c as u6,Ac as g8,Ad as L$,Bc as s$,Cc as o$,Dc as u2,Ec as g2,Fc as d2,Gc as S6,Hc as v6,Hd as MX,Ic as x2,Jc as i9,Kc as I2,Lc as u8,Ld as EY,Mc as A1,Nc as s1,Oc as h2,Pc as o1,Qc as t1,Qd as ZX,Rc as y6,Rd as JX,Sc as e1,Tc as k6,Td as s,Uc as x6,Vc as f$,Wc as I6,Xc as J3,Yc as m2,Zc as h6,_c as g6,ad as d6,bd as Y3,cd as Q3,ed as X3,hc as t$,ic as oQ,jc as T3,kc as q3,lc as Z2,mc as x3,nc as _0,oc as C2,pc as L1,qc as A6,rc as G9,sc as x4,tc as I4,uc as k7,vc as x7,wc as tQ,xc as d9,xd as $8,yc as E1,zc as g9,zd as f0}from"./chunk-rj8mmwc6.js";import{Ud as p,Vd as cY,Wd as lY,Xd as _J,Zd as G2}from"./chunk-53h87fmt.js";import{$d as OU,Ee as bU,Re as jU,ce as NU,qe as K9,re as e0,se as H2,te as xZ,ue as eQ,ve as $X}from"./chunk-b5z1rec4.js";import{kf as JJ,lf as $J}from"./chunk-a60cmnmz.js";import{Cf as E0,Df as A4,Ef as D2,Ff as z1,Gf as _Z,Hf as C1,If as bY,Nf as U2,xf as d4,yf as q0,zf as g}from"./chunk-j3nmt09e.js";import{Of as g1}from"./chunk-mdew58v9.js";import{Sf as DZ,Tf as jY,Uf as OY,Zf as KX,_f as M4}from"./chunk-ajsw4te2.js";import{ag as d0,bg as F1}from"./chunk-mvm1rzc4.js";import{cg as bX}from"./chunk-edtxcqxa.js";import{eg as cQ,fg as lQ,gg as iQ,hg as rQ}from"./chunk-e371f7xk.js";import{Dg as hZ,Fg as m0,Gg as C$,Ig as C4,Jg as sQ,Kg as QX,ig as P4,jg as S4,kg as v4,mg as y4,ng as k4,og as q1,pg as sY,rg as v$,sg as O$,tg as z$,ug as i8,vg as J2,wg as Y8,xg as p1,yg as c1,zg as aQ}from"./chunk-t8rjxqp2.js";import{Mg as B1,Og as A$,Pg as D4,Qg as j3,Rg as E3,Sg as l2,Tg as A3,Ug as M3,Vg as a6,Wg as C3,Xg as i6}from"./chunk-sx77dpxw.js";import{$g as e4,Yg as mX,_g as nQ,ah as YJ}from"./chunk-aaxc81jc.js";import{ch as Z9,eh as x0}from"./chunk-r7kevfd3.js";import{fh as F6,gh as B9,hh as _6,ih as l1}from"./chunk-g4xny949.js";import{Ah as m3,Ch as uQ,Eh as m7,Fh as p7,Wh as x1,Zh as S7,hi as HY,ii as BY,ji as GY,kh as u3,ki as KY,li as wZ,mi as DY,ni as W1,oi as qY,ph as d3,pi as wY,qi as FY,rh as sZ,si as v3,ui as UX,vi as pQ,wh as PX,wi as H0}from"./chunk-0bkhpd72.js";import{zi as w$}from"./chunk-jkfkyedn.js";import{Bi as RQ,Di as fQ}from"./chunk-f8gb685p.js";import{Gi as e6,Ii as C}from"./chunk-44jtpg8y.js";import{Ji as m6,Ki as n6,Li as K,Mi as B3,Ni as P,Oi as u}from"./chunk-sj1dzeta.js";import{oj as t}from"./chunk-ar5np5h5.js";import{tj as dQ,uj as mQ}from"./chunk-dfjmvj3d.js";import{vj as cX,yj as uX}from"./chunk-tkydv9k8.js";import{Cj as nX}from"./chunk-9d49tj9y.js";import{Ij as XX,Jj as r0}from"./chunk-qcvxff27.js";import{Mj as o,Nj as _$,Oj as B$,Pj as a1,Qj as v9,Rj as k2,Sj as J$,Tj as P7,Wj as f6,dk as E6,gk as N$,lk as b3}from"./chunk-pj69j4zp.js";import{rk as $$}from"./chunk-zkzhm39s.js";import{randomUUID as L8}from"crypto";import{randomUUID as mU}from"node:crypto";var IU=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);
@@ -853,7 +853,7 @@ ${_1}
853
853
  </approved-plan>
854
854
 
855
855
  IMPORTANT: Execute according to the approved plan above. Follow the steps exactly as specified.`;if(typeof F==="string")N0=F+d$;else N0=[...F,{type:"text",text:d$}]}S=yield*this.runLoop(N0,O,{...k,inputMessageId:void 0})}if(!this.sessionRuntime||!y)return S;let n=await this.sessionRuntime.recordGoalProgress({tokens:S.metadata?.tokensUsed??0,elapsedMs:S.metadata?.duration??0,prematureStopPattern:S.success?d7(S.finalMessage):void 0});if(n)yield{kind:"goal_updated",goal:n};if(!S.success||O.signal?.aborted){if(n=await this.sessionRuntime.pauseActiveGoal(O.signal?.aborted?"goal paused after user cancellation":S.error?.message??"goal paused after turn failure"),n)yield{kind:"goal_updated",goal:n}}if(S.success&&!O.signal?.aborted&&f<20)await this.sessionRuntime.waitForBackgroundSubagentFollowUp(y,O.signal);let $0=S.success&&!O.signal?.aborted&&f<20,l=TB(S);if(r=await this.sessionRuntime.finishTurn(y,{continuePending:$0,...l?{acknowledgeInput:!0}:{},outcome:S.success&&!O.signal?.aborted?{status:"completed",turnsCount:S.metadata?.turnsCount??0,toolCallsCount:S.metadata?.toolCallsCount??0,durationMs:S.metadata?.duration??0}:{status:"aborted",cause:O.signal?.aborted?"cancelled":"failed",turnsCount:S.metadata?.turnsCount??0,toolCallsCount:S.metadata?.toolCallsCount??0,durationMs:S.metadata?.duration??0}}),r){f++,j=!0,N=!1,b=null,F="",v=void 0,E="",A=void 0,M=e(),yield{kind:"follow_up_started",queued:this.sessionRuntime.getPendingSteeringCount(),recovered:this.sessionRuntime.getRecoveredSteeringCount(),messages:I()};continue}if(!S.success||O.signal?.aborted)return S;if(n=await this.sessionRuntime.getGoal(),!n||n.status!=="active"&&n.status!=="verifying")return S;let R$=await this.sessionRuntime.beginGoalContinuation();if(!R$)return S;let J0=await this.sessionRuntime.prepareGoalContinuation(R$);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:S.metadata?.turnsCount??0,toolCallsCount:S.metadata?.toolCallsCount??0,duration:S.metadata?.duration??0}}}b=J0.goal,q=J0,r=await this.sessionRuntime.beginTurn("goal"),j=!1,N=!0,F=E5(b),v=void 0,M=void 0,yield{kind:"goal_frontier_updated",goal:J0.goal,frontier:J0.frontier,tasks:J0.tasks},yield{kind:"goal_continuation_started",goal:b,continuation:b.continuationCount,...b.prematureStop?{prematureStopPattern:b.prematureStop.pattern,prematureStopCount:b.prematureStop.consecutiveCount}:{}},yield{kind:"goal_updated",goal:b}}}finally{if(this.sessionRuntime&&r)await this.sessionRuntime.finishTurn(r)}}let w=typeof H==="string"?H:H.filter((F)=>F.type==="text").map((F)=>F.text).join(`
856
- `),_={id:this.generateTaskId(),type:"simple",prompt:w};return{success:!0,finalMessage:(await this.executeTask(_)).content,metadata:{turnsCount:1,toolCallsCount:0,duration:0}}}async chat($,Z,J){let{drainLoop:Y}=await import("./chunk-51qc7n8t.js");return Y(this.chatStream($,Z,J))}async*runPlanLoop($,Z,J){a.debug("Processing Plan mode message...");let{prompt:Y}=await $1({...Z.workspaceKind==="acp-remote"?{workspaceAccess:"none"}:{projectPath:Z.workspaceRoot||C()},mode:"plan",includeEnvironment:!0,environmentOptions:{...h1,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=r2($);else{let X=$.filter((U)=>U.type==="text");if(X.length>0){let U=X[0];Q=$.map((V)=>V===U?{type:"text",text:r2(U.text)}:V)}else Q=[{type:"text",text:r2("")},...$]}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 $1({...$.workspaceKind==="acp-remote"?{workspaceAccess:"none"}:{projectPath:$.workspaceRoot||C()},replaceDefault:Z,append:J,includeEnvironment:!0,environmentOptions:{...h1,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 MY(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,U=J.output,V={success:X,llmContent:typeof U==="string"||U!==null&&typeof U==="object"?U:U===null?J.error?`Subagent execution failed: ${J.error}.`:"":String(U),...J.error?{error:{type:"execution_error",message:J.error}}:{},...Q?{metadata:Q}:{}},W=[{kind:"tool_result",toolCall:Y,result:V}],z=AY(Y,V);if(z)W.push(z);return W})}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 $1({...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:{...h1,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 T4({sessionId:"default",configDir:o(),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 $4({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=o0.createIsolated({artifactWriter:new i2(`legacy-${CB()}`)});this.legacyMcpRegistry=Z;for(let[X,U]of Object.entries($))try{a.debug(`Connecting to MCP server: ${X}`),await Z.registerServer(X,U),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(t2(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 m0(C());if(this.agentResources=C4($),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(`
856
+ `),_={id:this.generateTaskId(),type:"simple",prompt:w};return{success:!0,finalMessage:(await this.executeTask(_)).content,metadata:{turnsCount:1,toolCallsCount:0,duration:0}}}async chat($,Z,J){let{drainLoop:Y}=await import("./chunk-64kg5a9r.js");return Y(this.chatStream($,Z,J))}async*runPlanLoop($,Z,J){a.debug("Processing Plan mode message...");let{prompt:Y}=await $1({...Z.workspaceKind==="acp-remote"?{workspaceAccess:"none"}:{projectPath:Z.workspaceRoot||C()},mode:"plan",includeEnvironment:!0,environmentOptions:{...h1,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=r2($);else{let X=$.filter((U)=>U.type==="text");if(X.length>0){let U=X[0];Q=$.map((V)=>V===U?{type:"text",text:r2(U.text)}:V)}else Q=[{type:"text",text:r2("")},...$]}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 $1({...$.workspaceKind==="acp-remote"?{workspaceAccess:"none"}:{projectPath:$.workspaceRoot||C()},replaceDefault:Z,append:J,includeEnvironment:!0,environmentOptions:{...h1,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 MY(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,U=J.output,V={success:X,llmContent:typeof U==="string"||U!==null&&typeof U==="object"?U:U===null?J.error?`Subagent execution failed: ${J.error}.`:"":String(U),...J.error?{error:{type:"execution_error",message:J.error}}:{},...Q?{metadata:Q}:{}},W=[{kind:"tool_result",toolCall:Y,result:V}],z=AY(Y,V);if(z)W.push(z);return W})}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 $1({...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:{...h1,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 T4({sessionId:"default",configDir:o(),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 $4({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=o0.createIsolated({artifactWriter:new i2(`legacy-${CB()}`)});this.legacyMcpRegistry=Z;for(let[X,U]of Object.entries($))try{a.debug(`Connecting to MCP server: ${X}`),await Z.registerServer(X,U),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(t2(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 m0(C());if(this.agentResources=C4($),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(`
857
857
  `);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+=`
858
858
 
859
859
  <system-reminder>
@@ -1666,7 +1666,7 @@ ${J}
1666
1666
  `)),{success:!0,message:"Schedules listed",content:W.join(`
1667
1667
  `)}}case"create":{let V=Zw(X);if("error"in V)return Y.sendMessage(`创建失败:${V.error}`),{success:!1,error:V.error};let W={prompt:V.prompt,projectPath:U,trigger:V.trigger,isolation:"worktree",permissionMode:"default",enabled:!0};try{let z=await $.create(W),H=z.nextRunAt?new Date(z.nextRunAt).toLocaleString():"(无)";return Y.sendMessage(`[OK] 已创建定时任务 \`${z.id}\`
1668
1668
  ${V9(z.trigger)} · 下次运行: ${H}`),{success:!0,message:`Schedule ${z.id} created`}}catch(z){let H=z instanceof Error?z.message:String(z);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 W=await $.remove(V);return Y.sendMessage(W?`[OK] 已删除 \`${V}\``:`未找到 \`${V}\``),{success:W,message:W?"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 W=await $.setEnabled(V,Q==="enable");return Y.sendMessage(W?`[OK] 已${Q==="enable"?"启用":"停用"} \`${V}\``:`未找到 \`${V}\``),{success:Boolean(W),message:W?"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 Jw(V),Y.sendMessage(`[OK] 已触发 \`${V}\``),{success:!0,message:"Schedule triggered"}}catch(W){let z=W instanceof Error?W.message:String(W);return Y.sendMessage(`运行失败:${z}`),{success:!1,error:z}}}default:return Y.sendMessage(`未知子命令: ${Q}
1669
- 使用 /schedule 查看帮助`),{success:!1,error:`Unknown subcommand: ${Q}`}}}}}var LU=Yw();import*as A2 from"node:fs/promises";import*as M2 from"node:path";async function EU($,Z={}){let{maxResults:J=20,caseSensitive:Y=!1,projectPath:Q,storagePath:X}=Z,U=X??E6(Q??C());if(!X){let G=await Qw($,Q??C(),J,Y);if(G)return G}let V;try{V=(await A2.readdir(U)).filter((D)=>D.endsWith(".jsonl")&&!D.startsWith("agent_")).map((D)=>M2.join(U,D))}catch{return[]}let z=(await Promise.all(V.map(async(G)=>{try{let D=await A2.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 z){if(H.length>=J)break;let D=M2.basename(G,".jsonl"),q=await Xw(G,B,Y,D);if(H.push(...q),H.length>=J){H.length=J;break}}return H}async function Qw($,Z,J,Y){try{let{syncAll:Q}=await import("./chunk-2bnpn8be.js"),X=await bU();if(!X)return null;let{SessionService:U}=await import("./chunk-h1wphqkc.js");await Q(X,U.projectionDeriverForSearch());let V=M2.resolve(Z),W=jU(X,$,V,J*4),z=Y?$:$.toLowerCase(),H=[];for(let B of W){if(B.role!=="user"&&B.role!=="assistant")continue;let G=W9(B.text,z,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 Xw($,Z,J,Y){try{let Q=await A2.readFile($,"utf8"),U=Q.split(`
1669
+ 使用 /schedule 查看帮助`),{success:!1,error:`Unknown subcommand: ${Q}`}}}}}var LU=Yw();import*as A2 from"node:fs/promises";import*as M2 from"node:path";async function EU($,Z={}){let{maxResults:J=20,caseSensitive:Y=!1,projectPath:Q,storagePath:X}=Z,U=X??E6(Q??C());if(!X){let G=await Qw($,Q??C(),J,Y);if(G)return G}let V;try{V=(await A2.readdir(U)).filter((D)=>D.endsWith(".jsonl")&&!D.startsWith("agent_")).map((D)=>M2.join(U,D))}catch{return[]}let z=(await Promise.all(V.map(async(G)=>{try{let D=await A2.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 z){if(H.length>=J)break;let D=M2.basename(G,".jsonl"),q=await Xw(G,B,Y,D);if(H.push(...q),H.length>=J){H.length=J;break}}return H}async function Qw($,Z,J,Y){try{let{syncAll:Q}=await import("./chunk-mg1s861p.js"),X=await bU();if(!X)return null;let{SessionService:U}=await import("./chunk-53j6nh8j.js");await Q(X,U.projectionDeriverForSearch());let V=M2.resolve(Z),W=jU(X,$,V,J*4),z=Y?$:$.toLowerCase(),H=[];for(let B of W){if(B.role!=="user"&&B.role!=="assistant")continue;let G=W9(B.text,z,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 Xw($,Z,J,Y){try{let Q=await A2.readFile($,"utf8"),U=Q.split(`
1670
1670
  `).flatMap((B,G)=>{if(!B.trim())return[];try{return[{event:JSON.parse(B),index:G}]}catch{return[]}});if(!U.some(({event:B})=>B.type==="session_created"))return Uw(U,Z,J,Y);let W=new Map(U.flatMap(({event:B,index:G})=>typeof B.id==="string"?[[B.id,G+1]]:[])),z=OU(NU(Q,$)),H=new Map;for(let B of z){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:W.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=W9(B.content.join(" "),Z,J,Y,B.role,B.timestamp,B.lineNumber);return G?[G]:[]})}catch{return[]}}function Uw($,Z,J,Y){return $.flatMap(({event:Q,index:X})=>{if(Q.type!=="message")return[];let U=Q.message;if(U?.role!=="user"&&U?.role!=="assistant"||!U.content)return[];let V=typeof U.content==="string"?U.content:Array.isArray(U.content)?U.content.filter((z)=>typeof z==="object"&&z!==null&&z.type==="text"&&typeof z.text==="string").map((z)=>z.text).join(" "):"",W=W9(V,Z,J,Y,U.role,typeof Q.timestamp==="string"?Q.timestamp:void 0,X+1);return W?[W]:[]})}function W9($,Z,J,Y,Q,X,U){if(!$)return;let V=J?$:$.toLowerCase();if(!V.includes(Z))return;let W=V.indexOf(Z),z=Math.max(0,W-80),H=Math.min($.length,W+Z.length+80);return{sessionId:Y,role:Q,content:(z>0?"...":"")+$.slice(z,H).replace(/\n/g," ")+(H<$.length?"...":""),timestamp:X,lineNumber:U}}function AU($){if($.length===0)return"没有找到匹配的历史记录";let Z=[`**找到 ${$.length} 条匹配:**
1671
1671
  `];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(`
1672
1672
  `)}var Vw={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=m(Z);if($.length===0)return J.sendMessage("**用法:** `/search <关键词>`\n\n在历史会话中搜索包含指定关键词的对话"),{success:!0,message:"显示帮助"};let Y=$.join(" ");J.sendMessage(`正在搜索: "${Y}" ...`);try{let Q=await EU(Y,{maxResults:15,projectPath:Z.cwd}),X=AU(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}}}},MU=Vw;var Ww={name:"skills",description:"查看所有可用的 Skills",fullDescription:"显示所有已发现的 Skills 及其详细信息,包括名称、描述、来源和允许的工具。",usage:"/skills",category:"system",examples:["/skills"],handler:async($,Z)=>{try{let J=Z.workspaceRoot??Z.cwd;return await C$(J,async(Y)=>{await Y.skills.refresh(),c1(J),await p1(J)}),{success:!0,message:"show_skills_manager",data:{action:"show_skills_manager"}}}catch(J){let Y=`获取 Skills 失败: ${J instanceof Error?J.message:"未知错误"}`;return g().addAssistantMessage(Y),{success:!1,error:Y}}}},CU=Ww;import zw from"node:path";function K8($){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 TU($){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 RU($,Z){if($.length<=Z)return $;return $.slice(0,Z-3)+"..."}async function Hw($,Z){let J=m(Z),Y=$[0],Q=Y0.getInstance(),X=K0.getInstance(),U=Z.sessionId??"",V=Z.sessionId?{sessionId:Z.sessionId,projectPath:zw.resolve(Z.workspaceRoot??Z.cwd)}:void 0;if(Y==="resume"){let D=$[1],q=$.slice(2).join(" ").trim();if(!D||!q)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 w=await Z.subagents.resume(D,q),_=`Resumed \`${D}\` as \`${w.session.id}\` (depth ${w.session.resumeDepth}).`;return J.sendMessage(_),{success:!0,message:_,data:{action:"subagent_resumed",sourceAgentId:D,subagent:w.session}}}if(Y==="clean"){let D=X.cleanupExpiredSessionsForParent(V??U,0);return J.sendMessage(`已清理 ${D} 个已完成的 Agent 会话`),{success:!0,message:`Cleaned ${D} agent sessions`}}let W=[`**后台任务列表**
@@ -1,4 +1,4 @@
1
- import{v as tz,w as ez}from"./chunk-xa9k5pjt.js";import{A as S,x as yz,y as Iz,z as kz}from"./chunk-5a17mdjd.js";import{B as sz,C as Pz,D as Ez,E as Tz,F as xz,G as bz}from"./chunk-9yqadjea.js";import{Aa as Mz,N as R,W as wz,X as Fz,aa as Oz,da as Nz,ea as Az,ha as qz,xa as Rz,ya as Sz,za as hz}from"./chunk-v94ztjtp.js";import"./chunk-6p6ts4kv.js";import{Oa as nz}from"./chunk-tw5fr07c.js";import{Qa as Dz}from"./chunk-v52wc8yg.js";import{Kb as Kz,Tb as d,yb as _z}from"./chunk-s2atpv23.js";import{cc as m}from"./chunk-77efqpdc.js";import{Dd as Uz,Gd as jz,Id as h,Ld as Gz,Qd as Vz,Td as K,md as Wz,wd as M,xd as v,yd as Bz}from"./chunk-7jj607dg.js";import"./chunk-53h87fmt.js";import{pe as Hz,we as l,xe as Xz}from"./chunk-gfbkrk60.js";import"./chunk-0z9nqbd0.js";import{hf as zJ}from"./chunk-9et78e3v.js";import"./chunk-a60cmnmz.js";import{Cf as iz,Df as az}from"./chunk-zc91c7b5.js";import"./chunk-v508x7cg.js";import{Of as n}from"./chunk-mdew58v9.js";import{Tf as Lz}from"./chunk-ajsw4te2.js";import"./chunk-mvm1rzc4.js";import{cg as rz}from"./chunk-edtxcqxa.js";import"./chunk-8a6nrqdc.js";import"./chunk-a4jetpj8.js";import"./chunk-sx77dpxw.js";import{Yg as oz}from"./chunk-aaxc81jc.js";import"./chunk-93x9xbew.js";import"./chunk-r9tawy93.js";import"./chunk-g4xny949.js";import{$h as dz,ci as lz}from"./chunk-hhg1zcbq.js";import"./chunk-jkfkyedn.js";import{Ai as g,Bi as Yz,Di as c,Ei as p}from"./chunk-f8gb685p.js";import{Ii as o}from"./chunk-44jtpg8y.js";import"./chunk-sj1dzeta.js";import"./chunk-2y1qngw7.js";import{oj as y}from"./chunk-ar5np5h5.js";import"./chunk-dfjmvj3d.js";import{vj as mz,yj as vz}from"./chunk-tkydv9k8.js";import"./chunk-v5hzk7j2.js";import"./chunk-qcvxff27.js";import"./chunk-zwjrensv.js";import{Mj as Qz,Nj as cz,Rj as s,Vj as t,Wj as pz,Xj as e}from"./chunk-pj69j4zp.js";import"./chunk-zkzhm39s.js";import{Readable as VJ,Writable as _J}from"node:stream";import*as f from"@agentclientprotocol/sdk";import i from"node:path";import{PROTOCOL_VERSION as XJ,RequestError as C}from"@agentclientprotocol/sdk";import{RequestError as Cz}from"@agentclientprotocol/sdk";import{nanoid as u}from"nanoid";var V=y("Agent");function T(z){return Object.freeze({kind:"local",hostStateRoot:z,executionRoot:z,hostResourceRoot:z})}function $z(z){if(!z)return{};return Object.fromEntries(z.map((J)=>[J.name,J.value]))}function $J(z){if("command"in z)return{type:"stdio",command:z.command,args:z.args,env:$z(z.env)};if("url"in z)return{type:z.type,url:z.url,headers:$z("headers"in z?z.headers:void 0)};return null}function QJ(z){let J={};for(let Z of z){let Y=$J(Z);if(Y)J[Z.name]=Y}return J}function fz(z){if(typeof z==="string")return z?[{type:"text",text:z}]:[];return z.flatMap((J)=>{if(J.type==="text")return J.text?[{type:"text",text:J.text}]:[];let Z=J.image_url.url,Y=/^data:([^;,]+);base64,(.+)$/s.exec(Z);if(!Y)return[{type:"text",text:"[Image]"}];return[{type:"image",mimeType:Y[1]??"image/png",data:Y[2]??""}]})}function YJ(z){let J=Xz(z.metadata);return J?[{type:"text",text:l(J)}]:fz(z.content)}function LJ(z){return[`Status: ${z.status}`,`Exit code: ${z.exitCode??"null"}`,`Duration: ${(z.durationMs/1000).toFixed(3)} seconds`].join(`
1
+ import{v as tz,w as ez}from"./chunk-bavzm721.js";import{A as S,x as yz,y as Iz,z as kz}from"./chunk-qcydkn1n.js";import{B as sz,C as Pz,D as Ez,E as Tz,F as xz,G as bz}from"./chunk-6q3g5e3m.js";import{Aa as Mz,N as R,W as wz,X as Fz,aa as Oz,da as Nz,ea as Az,ha as qz,xa as Rz,ya as Sz,za as hz}from"./chunk-xjrmq0pg.js";import"./chunk-6p6ts4kv.js";import{Oa as nz}from"./chunk-sbc90z9j.js";import{Qa as Dz}from"./chunk-v52wc8yg.js";import{Kb as Kz,Tb as d,yb as _z}from"./chunk-3e0t25rq.js";import{cc as m}from"./chunk-77efqpdc.js";import{Dd as Uz,Gd as jz,Id as h,Ld as Gz,Qd as Vz,Td as K,md as Wz,wd as M,xd as v,yd as Bz}from"./chunk-rj8mmwc6.js";import"./chunk-53h87fmt.js";import{pe as Hz,we as l,xe as Xz}from"./chunk-b5z1rec4.js";import"./chunk-0z9nqbd0.js";import{hf as zJ}from"./chunk-y0kqkewg.js";import"./chunk-a60cmnmz.js";import{Cf as iz,Df as az}from"./chunk-j3nmt09e.js";import"./chunk-v508x7cg.js";import{Of as n}from"./chunk-mdew58v9.js";import{Tf as Lz}from"./chunk-ajsw4te2.js";import"./chunk-mvm1rzc4.js";import{cg as rz}from"./chunk-edtxcqxa.js";import"./chunk-e371f7xk.js";import"./chunk-t8rjxqp2.js";import"./chunk-sx77dpxw.js";import{Yg as oz}from"./chunk-aaxc81jc.js";import"./chunk-93x9xbew.js";import"./chunk-r7kevfd3.js";import"./chunk-g4xny949.js";import{$h as dz,ci as lz}from"./chunk-0bkhpd72.js";import"./chunk-jkfkyedn.js";import{Ai as g,Bi as Yz,Di as c,Ei as p}from"./chunk-f8gb685p.js";import{Ii as o}from"./chunk-44jtpg8y.js";import"./chunk-sj1dzeta.js";import"./chunk-2y1qngw7.js";import{oj as y}from"./chunk-ar5np5h5.js";import"./chunk-dfjmvj3d.js";import{vj as mz,yj as vz}from"./chunk-tkydv9k8.js";import"./chunk-9d49tj9y.js";import"./chunk-qcvxff27.js";import"./chunk-zwjrensv.js";import{Mj as Qz,Nj as cz,Rj as s,Vj as t,Wj as pz,Xj as e}from"./chunk-pj69j4zp.js";import"./chunk-zkzhm39s.js";import{Readable as VJ,Writable as _J}from"node:stream";import*as f from"@agentclientprotocol/sdk";import i from"node:path";import{PROTOCOL_VERSION as XJ,RequestError as C}from"@agentclientprotocol/sdk";import{RequestError as Cz}from"@agentclientprotocol/sdk";import{nanoid as u}from"nanoid";var V=y("Agent");function T(z){return Object.freeze({kind:"local",hostStateRoot:z,executionRoot:z,hostResourceRoot:z})}function $z(z){if(!z)return{};return Object.fromEntries(z.map((J)=>[J.name,J.value]))}function $J(z){if("command"in z)return{type:"stdio",command:z.command,args:z.args,env:$z(z.env)};if("url"in z)return{type:z.type,url:z.url,headers:$z("headers"in z?z.headers:void 0)};return null}function QJ(z){let J={};for(let Z of z){let Y=$J(Z);if(Y)J[Z.name]=Y}return J}function fz(z){if(typeof z==="string")return z?[{type:"text",text:z}]:[];return z.flatMap((J)=>{if(J.type==="text")return J.text?[{type:"text",text:J.text}]:[];let Z=J.image_url.url,Y=/^data:([^;,]+);base64,(.+)$/s.exec(Z);if(!Y)return[{type:"text",text:"[Image]"}];return[{type:"image",mimeType:Y[1]??"image/png",data:Y[2]??""}]})}function YJ(z){let J=Xz(z.metadata);return J?[{type:"text",text:l(J)}]:fz(z.content)}function LJ(z){return[`Status: ${z.status}`,`Exit code: ${z.exitCode??"null"}`,`Duration: ${(z.durationMs/1000).toFixed(3)} seconds`].join(`
2
2
  `)}function WJ(z){if(!Lz(z)||z.reason!=="queue_full"||z.resource!=="pending_count"&&z.resource!=="pending_bytes")return;return{...M("capacity"),resource:z.resource}}function HJ(z){if(!(z instanceof Cz)||!z.data||typeof z.data!=="object")return;let J=z.data;if(!Bz(J.taskFailure)||J.toolExecutionStarted!==!1||!Number.isInteger(J.toolCallsCount)||J.toolCallsCount<0||J.outputStarted!==!1)return;return{taskFailure:J.taskFailure,toolExecutionStarted:J.toolExecutionStarted,toolCallsCount:J.toolCallsCount,outputStarted:J.outputStarted}}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;destroyed=!1;destroyFinished=!1;destroyPromise;serviceRegistration;messages;contextMessages;mode;updateEgress;constructor(z,J,Z,Y,W={}){this.id=z;this.roots=J;this.connection=Z;this.clientCapabilities=Y;this.options=W;this.messages=[...W.initialMessages??[]],this.contextMessages=[...this.messages],this.mode=this.mapPermissionModeToMode(W.permissionMode),this.updateEgress=new bz({maxPendingItems:Pz,maxPendingBytes:Ez,writeTimeoutMs:Tz,signal:Z.signal,sizeOf:(H)=>Buffer.byteLength(JSON.stringify(H)),write:async(H)=>{await Z.sessionUpdate(H)},onFailure:(H)=>this.handleUpdateEgressFailure(H)})}async refreshPersistedMessages(){let[z,J]=await Promise.all([this.loadPersistedMessages(),this.loadPersistedModelContext()]);if(z.length>0)this.messages=z;if(J.length>0)this.contextMessages=J}async loadModelContextOr(z){let J=await this.loadPersistedModelContext();return J.length>0?J:[...z]}loadPersistedMessages(){return this.roots.kind==="acp-remote"?K.loadRemoteSession(this.id,this.roots.hostStateRoot,this.roots.descriptor):K.loadSession(this.id,this.roots.hostStateRoot)}loadPersistedModelContext(){return this.roots.kind==="acp-remote"?K.loadRemoteSessionModelContext(this.id,this.roots.hostStateRoot,this.roots.descriptor):K.loadSessionModelContext(this.id,this.roots.hostStateRoot)}async persistMetadataUpdate(z,J=z){if(this.roots.kind==="acp-remote"){await K.updateRemoteSessionMetadata(this.id,this.roots.hostStateRoot,this.roots.descriptor,z);return}try{await K.updateSessionMetadata(this.id,this.roots.hostStateRoot,z)}catch(Z){if(!(Z instanceof Vz)&&Z.code!=="ENOENT")throw Z;await K.createSessionMetadata(this.id,this.roots.hostStateRoot,{taskStatus:"completed",...J})}}async persistPermissionMode(z){if(this.roots.kind==="acp-remote"){await K.updateRemoteSessionMetadata(this.id,this.roots.hostStateRoot,this.roots.descriptor,{permissionMode:z});return}await K.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 qz.createWithRuntime(this.runtime,{sessionId:this.id,...this.options.taskWorktree?{toolBlacklist:["EnterWorktree","ExitWorktree"]}:{}})}async initialize(){V.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(L)=>{await this.sendUpdateAndWait(L)},this.roots.kind==="acp-remote"?this.roots.profile:void 0);if(z)this.serviceRegistration=z;if(V.debug(`[AcpSession ${this.id}] ACP service context initialized`),this.roots.kind==="local"?await d.resolvePendingWithHandler(this.roots.hostStateRoot,this.id,{requestConfirmation:(L)=>this.requestPermission(L)}):!1)await this.refreshPersistedMessages();else if((this.options.initialMessages?.length??0)>0)this.contextMessages=await this.loadModelContextOr(this.options.initialMessages??[]);let Z=this.options.mcpServers?QJ(this.options.mcpServers):void 0,Y=R.getInstance().getTerminalService(this.id),W=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 Oz.create({sessionId:this.id,workspaceRoot:this.roots.hostStateRoot,...W?{workspace:W}:{},permissionMode:this.mapModeToPermissionMode(),...Z?{mcpServers:Z}:{},...this.options.taskWorktree?{taskWorktree:this.options.taskWorktree}:{},...this.options.taskIsolation?{taskIsolation:this.options.taskIsolation}:{},userShellExecutor:{execute:async(L,U)=>{let j=await Y.execute(L,{cwd:U.cwd,env:U.env,timeout:U.timeoutMs,signal:U.signal,allowLocalFallback:!1,onOutput:(G)=>U.onOutput?.("stdout",G)});return{exitCode:j.exitCode,stdout:j.stdout,stderr:j.stderr,...j.error?{error:j.error}:{},timedOut:j.failureKind==="timeout",aborted:j.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 Sz(this.roots.hostStateRoot);V.debug(`[AcpSession ${this.id}] Agent created successfully`),this.taskStatusUnsubscribe?.(),this.taskStatusUnsubscribe=_z.subscribe((L)=>{if(L.sessionId!==this.id||L.projectPath!==this.roots.hostStateRoot)return;if(L.type==="subagent.completion.queued"){this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/backgroundSubagentCompletion":L.properties}}),this.requestPendingResume();return}if(L.type==="task.delivery"){if(!L.properties.taskDelivery||typeof L.properties.taskDelivery!=="object")return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:typeof L.properties.updatedAt==="string"?L.properties.updatedAt:new Date().toISOString(),_meta:{"blade/taskDelivery":L.properties.taskDelivery,...L.properties.taskWorktreeRemoved===!0?{"blade/taskWorktreeRemoved":!0}:{}}});return}if(L.type.startsWith("team.")){let{teamName:U,messageId:j,content:G}=L.properties,P=L.properties.metadata;if(L.type==="team.message.received"&&typeof U==="string"&&typeof j==="string"&&typeof G==="string"&&Fz(P,{messageId:j,teamName:U}))(async()=>{let E=await this.runtime?.enqueueSteering(G,{allowBeforeTurn:!0,messageId:j,origin:"team_message",metadata:P});if(!E?.accepted)return;if(await new wz(U,Qz()).markDelivered([j]),E.delivery==="next_turn")this.requestPendingResume()})().catch((E)=>{V.warn(`[AcpSession ${this.id}] Failed to deliver teammate message`,E)});this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/teamEvent":{type:L.type,...L.properties}}});return}if(L.type!=="task.status")return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:typeof L.properties.updatedAt==="string"?L.properties.updatedAt:new Date().toISOString(),_meta:{"blade/taskStatus":L.properties.taskStatus,...typeof L.properties.taskStatusReason==="string"?{"blade/taskStatusReason":L.properties.taskStatusReason}:{},...L.properties.taskFailure&&typeof L.properties.taskFailure==="object"?{"blade/taskFailure":L.properties.taskFailure}:{},...typeof L.properties.taskStartedAt==="string"?{"blade/taskStartedAt":L.properties.taskStartedAt}:{},...typeof L.properties.taskCompletedAt==="string"?{"blade/taskCompletedAt":L.properties.taskCompletedAt}:{},...L.properties.taskDiffStat&&typeof L.properties.taskDiffStat==="object"?{"blade/taskDiffStat":L.properties.taskDiffStat}:{},...typeof L.properties.taskQueuePosition==="number"?{"blade/taskQueuePosition":L.properties.taskQueuePosition}:{},...typeof L.properties.taskQueueDepth==="number"?{"blade/taskQueueDepth":L.properties.taskQueueDepth}:{},...typeof L.properties.taskConcurrencyLimit==="number"?{"blade/taskConcurrencyLimit":L.properties.taskConcurrencyLimit}:{},...typeof L.properties.taskInFlight==="number"?{"blade/taskInFlight":L.properties.taskInFlight}:{}}})});let Q=await this.runtime.getGoal(),X=this.runtime.getPendingSteeringCount()>0,B=Q?.status==="active"||Q?.status==="verifying";if(X||B)this.requestPendingResume({defer:this.options.initialMessages!==void 0});else{let L=this.runtime.getTurnRecoveryAssessment();if(L.state!=="none")this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/turnRecovery":L}})}}async replayHistory(){for(let J of this.messages){if(!this.canSendUpdates())return;if(!Hz(J))continue;let Z=J.role==="user"?"user_message_chunk":J.role==="assistant"?"agent_message_chunk":void 0;if(!Z)continue;for(let Y of YJ(J)){if(!this.canSendUpdates())return;if(!await this.sendUpdateAndWait({sessionUpdate:Z,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);V.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.sendAvailableCommands()},500)}async handleSlashCommand(z,J){try{V.debug(`[AcpSession ${this.id}] Executing slash command: ${z}`);let Z={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 X=await this.runtime.rewindSession(Q);return this.messages=[...X.messages],this.contextMessages=await this.loadModelContextOr(X.messages),await this.agent?.destroy(),this.agent=await this.createAgent(),X}},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,X)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let B=!1,L,U=(G)=>{this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:G.id,status:G.status==="completed"?"completed":"failed",content:[{type:"content",content:{type:"text",text:G.result?.message||G.result?.error||`Subagent ${G.status}`}}]})},j=this.runtime.resumeSubagent({agentId:Q,prompt:X,onCompleted:(G)=>{if(B)U(G);else L=G}});if(this.sendUpdate({sessionUpdate:"tool_call",toolCallId:j.session.id,status:"in_progress",title:`Resuming ${j.session.subagentType} subagent`,content:[{type:"content",content:{type:"text",text:`Resumed from ${j.source.id} at depth ${j.session.resumeDepth}`}}],kind:this.mapToolKind("readonly")}),B=!0,L)U(L);return j}}}:{},...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,X,B)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpPrompt(Q,X,B)},complete:async(Q,X,B)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.completeMcpArgument(Q,X,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,X)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.cancelMcpTask(Q,X)},getLogs:async(Q,X)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpLogs(Q,X)},setLoggingLevel:async(Q,X)=>{if(!this.runtime)throw Error("Session runtime is unavailable");await this.runtime.setMcpLoggingLevel(Q,X)},getInstructions:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpInstructions()}}}:{},sideConversation:{ask:async(Q,X)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.askSideQuestion(Q,{signal:X})}},...this.roots.kind==="local"?{codeReview:{run:async(Q,X)=>{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:X,onEvent:(j)=>{if(j.kind==="tool_start")this.sendUpdate({sessionUpdate:"tool_call",toolCallId:j.toolCall.id,status:"in_progress",title:`Review: ${j.toolCall.function.name}`,content:[],kind:this.mapToolKind(j.toolKind)});else if(j.kind==="tool_result")this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:j.toolCall.id,status:j.result.success?"completed":"failed",content:[]})}}),L=await B.completion,U=(await S.list(this.roots.hostStateRoot,this.id)).find((j)=>j.start.reviewId===B.reviewId);if(!U)throw Error(`Review not found: ${B.reviewId}`);return await this.refreshPersistedMessages(),{reviewId:B.reviewId,status:L.status,findings:L.findings.length,content:Wz(U.start,L)}}}}:{},signal:J,acp:{sendMessage:(Q)=>{this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:Q}})},sendToolStart:(Q,X,B)=>{let L=`tool_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,U=this.mapToolKind(B);this.sendUpdate({sessionUpdate:"tool_call",toolCallId:L,status:"in_progress",title:`${Q}`,content:[{type:"content",content:{type:"text",text:JSON.stringify(X,null,2)}}],kind:U})},sendToolResult:(Q,X)=>{if(X.summary)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:X.summary}})}}},Y=await hz(z,Z),W=Y.data?.action;if(W==="start_goal"||W==="resume_goal")this.requestPendingResume();if(W==="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 H=Y.content||Y.message;if(H)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:H}});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(Z){if(J.aborted||Z instanceof Error&&Z.name==="AbortError")return{stopReason:"cancelled"};return V.error(`[AcpSession ${this.id}] Slash command error:`,Z),this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] 命令执行失败: ${Z instanceof Error?Z.message:"未知错误"}`}}),{stopReason:"cancelled"}}}async handleSideConversationCommand(z){if(this.pendingSideConversation)throw Error("A side conversation is already running");let J=new AbortController,Z,Y=new Promise((W)=>{Z=W});this.pendingSideConversation=J,this.pendingSideConversationCompletion=Y;try{return await this.handleSlashCommand(z,J.signal)}catch(W){if(J.signal.aborted||W instanceof Error&&W.name==="AbortError")return{stopReason:"cancelled"};throw W}finally{if(Z(),this.pendingSideConversationCompletion===Y)this.pendingSideConversationCompletion=null;if(this.pendingSideConversation===J){if(this.pendingSideConversation=null,!this.destroyed&&this.pendingResumeRequested)this.ensurePendingResumeScheduled()}}}async sendAvailableCommands(){try{let z=Mz(this.roots.hostStateRoot,this.runtime?.getAgentResources(),this.roots.kind),J=["model","permissions","theme","config","exit","ide"],Y=z.filter((W)=>!J.includes(W.name)&&(W.name!=="team"||this.runtime?.getConfig().agentTeamsEnabled===!0)).map((W)=>{let H;if(W.usage){let Q=W.usage.replace(/^\/\w+\s*/,"").trim();if(Q)H=Q}if(W.aliases?.length){let Q=`Aliases: ${W.aliases.join(", ")}`;H=H?`${H} | ${Q}`:Q}return{name:W.name,description:W.description,input:H?{hint:H}:void 0}});V.info(`[AcpSession ${this.id}] Sending available commands: ${JSON.stringify(Y.map((W)=>W.name))}`),this.sendUpdate({sessionUpdate:"available_commands_update",availableCommands:Y}),V.info(`[AcpSession ${this.id}] Sent ${Y.length} available commands`)}catch(z){V.error(`[AcpSession ${this.id}] Failed to send available commands:`,z)}}async prompt(z,J={}){if(R.setCurrentSession(this.id),!this.agent||!this.runtime)throw Error("Session not initialized");let Z=this.resolvePrompt(z.prompt),Y=Z.content,W=Z.displayText,H=z._meta?.outputSchema??(J.pendingInputOnly?this.runtime.getPendingSteeringMessages().find((D)=>D.outputSchema)?.outputSchema:void 0),Q;if(H!==void 0)Q=Gz(H).schema;if(W.trimStart().startsWith("!")){if(Q)throw Error("Output schemas cannot be combined with user shell commands");return this.handleUserShellCommand(W)}let X=Dz(W);if(X){if(Q)throw Error("Output schemas cannot be combined with slash commands");if(Array.isArray(Y)&&Y.some((D)=>D.type==="image_url"))throw Error("Side conversations do not accept image attachments");return this.handleSideConversationCommand(X.question?`/btw ${X.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(W.trim()))return this.handleSlashCommand(W,this.pendingPrompt.signal);let D=await this.runtime.enqueueSteering(Y,{allowBeforeTurn:!0});if(!D.accepted)throw Error(D.reason==="queue_full"?"Active turn steering queue is full":"Active turn is no longer steerable");if(V.debug(`[AcpSession ${this.id}] Queued steering for active turn (${D.queued})`),D.delivery==="next_turn")this.requestPendingResume();return{stopReason:"end_turn"}}let B=new AbortController,L=()=>{B.abort(J.abortSignal?.reason)};if(J.abortSignal?.aborted)L();else J.abortSignal?.addEventListener("abort",L,{once:!0});let U=!1,j=!1,G=!1,P,E=new Promise((D)=>{P=D});this.pendingPrompt=B,this.pendingPromptCompletion=E;try{if(V.debug(`[AcpSession ${this.id}] Received prompt: ${W.slice(0,100)}...`),Rz(W)){if(Q)throw Error("Output schemas cannot be combined with slash commands");return await this.handleSlashCommand(W,B.signal)}let D={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($)=>{this.mode=this.mapPermissionModeToMode($),this.sendUpdate({sessionUpdate:"current_mode_update",currentModeId:this.mode})},...this.options.taskWorktree?{worktreeActive:!0}:{},confirmationHandler:{requestConfirmation:async($)=>{return this.requestPermission($)}}},O=await Kz(this.agent.chatStream(Y,D,{pendingInputOnly:J.pendingInputOnly,goalContinuationOnly:J.goalContinuationOnly,outputSchema:Q}),async($)=>{switch($.kind){case"content_delta":if(Q)break;if($.delta.length>0)j=!0;this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:$.delta}});break;case"thinking_delta":if($.delta.length>0)j=!0;this.sendUpdate({sessionUpdate:"agent_thought_chunk",content:{type:"text",text:$.delta}});break;case"tool_start":{G=!0;let _=$.toolCall,N=_.function.name;if(N===h)break;let q=this.mapToolKind($.toolKind),w=`Executing ${N}`;if(N==="Task"&&"function"in _)try{let b=JSON.parse(_.function.arguments),F=b.resume_from??b.resume;if(typeof F==="string")w=`Resuming ${String(b.subagent_type||"subagent")} from ${F}`}catch{}this.sendUpdate({sessionUpdate:"tool_call",toolCallId:_.id,status:"in_progress",title:w,content:[],kind:q});break}case"tool_progress":{G=!0;let _=$.toolCall;if(_.function.name===h)break;this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:_.id,status:"in_progress",content:[{type:"content",content:{type:"text",text:$.update.message}}]});break}case"tool_result":{G=!0;let _=$.toolCall;if(_.function.name===h)break;let N=$.result,q=[],w=N.metadata;if(w?.kind==="patch"&&Array.isArray(w.changes))for(let F of w.changes){if(!F||typeof F!=="object"||!("path"in F)||typeof F.path!=="string")continue;q.push({type:"diff",path:F.path,oldText:"oldContent"in F&&typeof F.oldContent==="string"?F.oldContent:null,newText:"newContent"in F&&typeof F.newContent==="string"?F.newContent:null})}else if(w?.kind==="edit"&&typeof w.file_path==="string"&&typeof w.oldContent==="string"&&(typeof w.newContent==="string"||w.newContent===void 0))q.push({type:"diff",path:w.file_path,oldText:w.oldContent,newText:w.newContent??null});else{let F=_.function.name,JJ=Az(jz(Nz(F,N),Uz));q.push({type:"content",content:{type:"text",text:JJ}})}if(_.function.name==="Task"&&(w?.verificationVerdict==="pass"||w?.verificationVerdict==="fail"||w?.verificationVerdict==="partial"))q.unshift({type:"content",content:{type:"text",text:`Verification result: ${w.verificationVerdict.toUpperCase()}`}});let b=N.success?"completed":"failed";this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:_.id,status:b,content:q});break}case"structured_output":j=!0,this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:JSON.stringify($.output)}});break;case"mcp_catalog_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP catalog r${$.revision} (${$.serverName}): +${$.added.length} -${$.removed.length} ~${$.updated.length}
3
3
  `}});break;case"mcp_content_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP ${$.contentKind} r${$.revision} (${$.serverName}): +${$.added.length} -${$.removed.length} ~${$.updated.length}
4
4
  `}});break;case"mcp_resource_updated":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP resource updated r${$.revision} (${$.serverName}): ${$.uri}
@@ -1,4 +1,4 @@
1
- import{yf as N}from"./chunk-zc91c7b5.js";import{eh as $}from"./chunk-r9tawy93.js";import{Ii as _}from"./chunk-44jtpg8y.js";import{mj as Y,oj as Z}from"./chunk-ar5np5h5.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{yf as N}from"./chunk-j3nmt09e.js";import{eh as $}from"./chunk-r7kevfd3.js";import{Ii as _}from"./chunk-44jtpg8y.js";import{mj as Y,oj as Z}from"./chunk-ar5np5h5.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 gf,y as hf,j as if,C as jf};
@@ -1,4 +1,4 @@
1
- import{a as T,b as W,c as X,d as Y}from"./chunk-qahz5x5c.js";import"./chunk-t4apxzp1.js";import"./chunk-grhsv55v.js";import"./chunk-xa9k5pjt.js";import"./chunk-5a17mdjd.js";import"./chunk-9yqadjea.js";import"./chunk-v94ztjtp.js";import"./chunk-6p6ts4kv.js";import"./chunk-tw5fr07c.js";import"./chunk-v52wc8yg.js";import"./chunk-s2atpv23.js";import"./chunk-77efqpdc.js";import"./chunk-7jj607dg.js";import"./chunk-53h87fmt.js";import"./chunk-gfbkrk60.js";import"./chunk-0z9nqbd0.js";import{hf as R}from"./chunk-9et78e3v.js";import"./chunk-a60cmnmz.js";import{Df as Q}from"./chunk-zc91c7b5.js";import"./chunk-v508x7cg.js";import"./chunk-mdew58v9.js";import"./chunk-ajsw4te2.js";import"./chunk-mvm1rzc4.js";import"./chunk-edtxcqxa.js";import"./chunk-8a6nrqdc.js";import"./chunk-a4jetpj8.js";import"./chunk-sx77dpxw.js";import"./chunk-aaxc81jc.js";import"./chunk-93x9xbew.js";import"./chunk-r9tawy93.js";import"./chunk-g4xny949.js";import"./chunk-hhg1zcbq.js";import"./chunk-jkfkyedn.js";import"./chunk-f8gb685p.js";import"./chunk-44jtpg8y.js";import"./chunk-sj1dzeta.js";import"./chunk-2y1qngw7.js";import"./chunk-ar5np5h5.js";import"./chunk-dfjmvj3d.js";import"./chunk-tkydv9k8.js";import{Cj as M}from"./chunk-v5hzk7j2.js";import"./chunk-qcvxff27.js";import"./chunk-zwjrensv.js";import"./chunk-pj69j4zp.js";import"./chunk-zkzhm39s.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-sm9p1fkf.js";import"./chunk-dvb89529.js";import"./chunk-grhsv55v.js";import"./chunk-bavzm721.js";import"./chunk-qcydkn1n.js";import"./chunk-6q3g5e3m.js";import"./chunk-xjrmq0pg.js";import"./chunk-6p6ts4kv.js";import"./chunk-sbc90z9j.js";import"./chunk-v52wc8yg.js";import"./chunk-3e0t25rq.js";import"./chunk-77efqpdc.js";import"./chunk-rj8mmwc6.js";import"./chunk-53h87fmt.js";import"./chunk-b5z1rec4.js";import"./chunk-0z9nqbd0.js";import{hf as R}from"./chunk-y0kqkewg.js";import"./chunk-a60cmnmz.js";import{Df as Q}from"./chunk-j3nmt09e.js";import"./chunk-v508x7cg.js";import"./chunk-mdew58v9.js";import"./chunk-ajsw4te2.js";import"./chunk-mvm1rzc4.js";import"./chunk-edtxcqxa.js";import"./chunk-e371f7xk.js";import"./chunk-t8rjxqp2.js";import"./chunk-sx77dpxw.js";import"./chunk-aaxc81jc.js";import"./chunk-93x9xbew.js";import"./chunk-r7kevfd3.js";import"./chunk-g4xny949.js";import"./chunk-0bkhpd72.js";import"./chunk-jkfkyedn.js";import"./chunk-f8gb685p.js";import"./chunk-44jtpg8y.js";import"./chunk-sj1dzeta.js";import"./chunk-2y1qngw7.js";import"./chunk-ar5np5h5.js";import"./chunk-dfjmvj3d.js";import"./chunk-tkydv9k8.js";import{Cj as M}from"./chunk-9d49tj9y.js";import"./chunk-qcvxff27.js";import"./chunk-zwjrensv.js";import"./chunk-pj69j4zp.js";import"./chunk-zkzhm39s.js";import m from"chalk";import K from"open";var A=`
2
2
  ____ _ _
3
3
  | __ )| | __ _ __| | ___
4
4
  | _ \\| |/ _\` |/ _\` |/ _ \\
@@ -0,0 +1 @@
1
+ import{k as a,l as b,m as c,n as d,o as e}from"./chunk-fag8rk53.js";import"./chunk-9d49tj9y.js";import"./chunk-zkzhm39s.js";export{b as setSkipUntilVersion,d as performUpgrade,c as getUpgradeCommand,e as checkVersionOnStartup,a as checkVersion};
@@ -1,4 +1,4 @@
1
- import{e as o3,f as n3,h as S$,i as X6}from"./chunk-t4apxzp1.js";import{l as oZ,m as nZ,n as tZ}from"./chunk-p2sp2e0a.js";import{A as h8,y as p9,z as x9}from"./chunk-5a17mdjd.js";import{Ba as oY,I as iY,M as zX,O as JJ,P as r4,Q as mY,W as CY,X as RY,aa as x$,ca as r9,da as a9,fa as IY,ha as c2,ia as OZ,ja as NZ,ma as FZ,na as WZ,ra as q9,sa as B6,ua as H6,va as L6,wa as _X,xa as zY,za as _Y}from"./chunk-v94ztjtp.js";import"./chunk-6p6ts4kv.js";import{Ja as D3,Ka as f3,La as V3,Oa as qX}from"./chunk-tw5fr07c.js";import{Qa as TY}from"./chunk-v52wc8yg.js";import{Kb as yY,Tb as x4,xb as bY,yb as MY}from"./chunk-s2atpv23.js";import{cc as a2}from"./chunk-77efqpdc.js";import{Bd as d9,Gd as l9,Id as k8,Qd as u2,Td as i0,md as HY,wd as m9,xd as L2}from"./chunk-7jj607dg.js";import"./chunk-53h87fmt.js";import{ve as n9,we as p4,xe as t9}from"./chunk-gfbkrk60.js";import{Ue as V8}from"./chunk-0z9nqbd0.js";import{ff as aZ}from"./chunk-gmqpfm52.js";import{gf as i2,hf as g8,jf as n$}from"./chunk-9et78e3v.js";import"./chunk-a60cmnmz.js";import{Af as H$,Bf as rZ,Cf as L4,Df as l2,Gf as UY,Nf as q$,nf as K2,of as W$,pf as v1,qf as CJ,rf as R8,sf as u9,tf as t6,uf as lJ,vf as x3,wf as s6,xf as O2,yf as U$,zf as GX}from"./chunk-zc91c7b5.js";import"./chunk-v508x7cg.js";import"./chunk-mdew58v9.js";import"./chunk-ajsw4te2.js";import{bg as rJ}from"./chunk-mvm1rzc4.js";import"./chunk-edtxcqxa.js";import"./chunk-8a6nrqdc.js";import{Fg as KX,og as x8,rg as VZ,wg as _Z}from"./chunk-a4jetpj8.js";import"./chunk-sx77dpxw.js";import"./chunk-aaxc81jc.js";import"./chunk-93x9xbew.js";import{ch as kJ,eh as j$}from"./chunk-r9tawy93.js";import"./chunk-g4xny949.js";import{ri as QX,wi as zZ,xi as UX}from"./chunk-hhg1zcbq.js";import"./chunk-jkfkyedn.js";import{Ai as w2,Bi as S8,Di as SJ}from"./chunk-f8gb685p.js";import{Ii as K$}from"./chunk-44jtpg8y.js";import"./chunk-sj1dzeta.js";import"./chunk-2y1qngw7.js";import{lj as XX,oj as V1}from"./chunk-ar5np5h5.js";import{qj as r3,rj as a3,uj as W1}from"./chunk-dfjmvj3d.js";import"./chunk-tkydv9k8.js";import{Gj as E3}from"./chunk-v5hzk7j2.js";import{Jj as K9}from"./chunk-qcvxff27.js";import"./chunk-zwjrensv.js";import{Mj as m4,ek as QY}from"./chunk-pj69j4zp.js";import{rk as IJ}from"./chunk-zkzhm39s.js";import{useMemoizedFn as k4}from"ahooks";import{useEffect as yG,useState as S4}from"react";import{useMemoizedFn as _$}from"ahooks";import dZ from"ansi-escapes";import{Box as R1,useStdout as LG}from"ink";import{useEffect as o$,useMemo as wG,useRef as g2,useState as lZ}from"react";import{useShallow as FX}from"zustand/react/shallow";import{useStore as NX}from"zustand";function z0($){return NX(O2,$)}var WX=[],N2=()=>z0(($)=>$.session.sessionId),U1=()=>z0(($)=>$.session.workspaceRoot),N8=()=>z0(($)=>$.session.messages),z9=()=>z0(($)=>$.session.clearCount),_9=()=>z0(($)=>$.session.isCompacting),O9=()=>z0(($)=>$.session.tokenUsage.estimatedCostUsd),N9=()=>z0(($)=>{let{totalInputTokens:J,cacheReadTokens:Z,cacheWriteTokens:Y}=$.session.tokenUsage;return q9({totalInputTokens:J,cacheReadTokens:Z,cacheWriteTokens:Y}).hitRate}),F9=()=>z0(($)=>$.session.providerCircuit),W9=()=>z0(($)=>$.session.providerAdmission),H9=()=>z0(($)=>$.session.providerRetry),L9=()=>z0(($)=>$.session.providerStall),w9=()=>z0(($)=>$.session.actionStationarity),D1=()=>z0(($)=>$.session.actions),B9=()=>z0(($)=>{let{totalTokens:J,maxContextTokens:Z}=$.session.tokenUsage;if(Z<=0)return 100;let Y=Math.max(0,100-J/Z*100);return Math.round(Y)}),A9=()=>z0(($)=>$.app.initializationStatus),P9=()=>z0(($)=>$.app.initializationError),F8=()=>z0(($)=>$.app.activeModal),b9=()=>z0(($)=>$.app.tasks),M9=()=>z0(($)=>$.app.modelEditorTarget),y9=()=>z0(($)=>$.app.sessionSelectorData),T9=()=>z0(($)=>$.app.sessionHistoryViewerData),C9=()=>z0(($)=>$.app.awaitingSecondCtrlC),f1=()=>z0(($)=>$.app.actions),W8=()=>z0(($)=>$.app.sideConversation),R9=()=>z0(($)=>$.app.teams),H8=()=>z0(($)=>$.app.initializationStatus==="ready"),I9=()=>z0(($)=>$.app.tasks.length>0),F2=()=>z0(($)=>$.config.config?.permissionMode||"default"),k9=()=>z0(($)=>$.config.config?.models??WX),L8=()=>z0(($)=>{let J=$.config.config;if(!J)return;let Z=J.currentModelId;return J.models.find((X)=>X.id===Z)??J.models[0]}),w8=()=>z0(($)=>$.config.config?.currentModelId),S9=()=>z0(($)=>$.config.config?.agentTeamsEnabled===!0),V0=()=>z0(($)=>{return W$.getTheme()}),D9=()=>z0(($)=>$.config.config?.codeTheme??"default"),X$=()=>z0(($)=>$.focus.currentFocus),f9=()=>z0(($)=>$.focus.actions),W2=()=>z0(($)=>$.command.isProcessing),V9=()=>z0(($)=>$.command.actions),H2=()=>z0(($)=>$.command.pendingCommands),v9=()=>z0(($)=>$.command.recoveredSteeringCount),B8=()=>z0(($)=>$.app.reasoningEffort!=="off"),A8=()=>z0(($)=>$.app.reasoningEffort),P8=()=>z0(($)=>$.app.serviceTier),b8=()=>z0(($)=>$.app.responseVerbosity),M8=()=>z0(($)=>$.app.communicationStyle),y8=()=>z0(($)=>$.session.currentThinkingContent),j9=()=>z0(($)=>$.session.thinkingExpanded),T8=()=>z0(($)=>$.session.currentStreamingMessageId),C8=()=>z0(FX(($)=>({lines:$.session.currentStreamingLines,tail:$.session.currentStreamingTail,lineCount:$.session.currentStreamingLineCount,version:$.session.currentStreamingVersion}))),E9=()=>z0(($)=>$.session.finalizingStreamingMessageId),h9=()=>z0(($)=>$.session.historyExpanded),g9=()=>z0(($)=>$.session.expandedMessageCount);import{useMemoizedFn as F1}from"ahooks";import{useEffect as a1,useMemo as uX,useRef as p8}from"react";function HX($,J){try{return $.code===J.code&&$.message===J.message&&$.retryable===J.retryable&&$.resource===J.resource}catch{return!1}}class D4{options;requested=!1;waitingForIdle=!1;disposed=!1;generation=0;wakeEpoch=0;idleEpoch=0;attempt=0;recoveryStartedAt=null;scheduledToken=null;activeAttemptToken=null;activeRunController=null;retryTimer=null;deadlineTimer=null;now;scheduleCallback;setTimerCallback;clearTimerCallback;constructor($){this.options=$;this.now=$.now??Date.now,this.scheduleCallback=$.scheduleMicrotask??queueMicrotask,this.setTimerCallback=$.setTimer??setTimeout,this.clearTimerCallback=$.clearTimer??clearTimeout}request(){if(this.disposed)return;if(this.wakeEpoch++,this.requested=!0,this.waitingForIdle||this.retryTimer)return;this.scheduleIfRunnable()}notifyIdle(){if(this.disposed)return;if(this.idleEpoch++,this.retryTimer)return;this.waitingForIdle=!1,this.scheduleIfRunnable()}dispose(){if(this.disposed)return;this.disposed=!0,this.generation++,this.requested=!1,this.waitingForIdle=!1,this.scheduledToken=null,this.clearOwnedTimer("retry"),this.clearOwnedTimer("deadline"),this.activeAttemptToken=null;let $=this.activeRunController;this.activeRunController=null,$?.abort("pending-resume-coordinator-disposed"),this.resetEpisodeBudget()}scheduleIfRunnable(){if(this.disposed||!this.requested||this.scheduledToken||this.activeAttemptToken||this.retryTimer||this.waitingForIdle)return;if(!this.options.canRun()){this.waitingForIdle=!0;return}let $=this.generation,J={};this.scheduledToken=J;try{this.scheduleCallback(()=>{if(this.disposed||$!==this.generation||this.scheduledToken!==J)return;this.scheduledToken=null,this.flush($).catch((Z)=>{this.handleUnexpectedFailure(Z,$)})})}catch(Z){this.handleUnexpectedFailure(Z,$)}}async flush($){if(this.disposed||$!==this.generation||this.activeAttemptToken||!this.requested||this.retryTimer||this.waitingForIdle)return;if(!this.options.canRun()){this.waitingForIdle=!0;return}let J={},Z=new AbortController,Y=this.wakeEpoch,X=this.idleEpoch;if(this.attempt++,this.recoveryStartedAt===null)this.recoveryStartedAt=this.now(),this.installDeadlineTimer($);this.activeAttemptToken=J,this.activeRunController=Z;let Q=await this.options.run(Z.signal);if(this.disposed||$!==this.generation||this.activeAttemptToken!==J)return;if(this.activeAttemptToken=null,this.activeRunController=null,Q.status==="completed"){let U=this.wakeEpoch!==Y;if(this.clearEpisode(),U)this.requested=!0,this.scheduleIfRunnable();return}if(Q.status==="deferred"){if(this.attempt--,this.attempt===0)this.clearOwnedTimer("deadline"),this.resetEpisodeBudget();if(this.requested=!0,this.idleEpoch!==X)this.waitingForIdle=!1,this.scheduleIfRunnable();else this.waitingForIdle=!0;return}this.handleFailure(Q,$)}handleFailure($,J){let Z=L2($.taskFailure),Y=this.options.sessionIdentity;if($.workKind!=="pending_input"||!$.evidence||!Y||!HX($.taskFailure,$.evidence.taskFailure)){this.terminate("failed",this.attempt,Z);return}let X=x9({sessionIdentity:Y,failedAttempt:this.attempt,recoveryStartedAt:this.recoveryStartedAt??this.now(),now:this.now(),workStillPending:$.workStillPending,evidence:$.evidence});if(X.phase!=="retry_scheduled"){this.terminate(X.phase,this.attempt,Z);return}this.requested=!0,this.waitingForIdle=!1;let Q={},U=this.setTimerCallback(()=>{if(this.disposed||J!==this.generation||this.retryTimer?.token!==Q)return;this.retryTimer=null,this.scheduleIfRunnable()},X.delayMs);this.retryTimer={handle:U,token:Q},U.unref?.()}handleUnexpectedFailure($,J){if(this.disposed||J!==this.generation)return;this.terminate("failed",Math.max(1,this.attempt),L2($),"pending-resume-coordinator-failed")}installDeadlineTimer($){let J={},Z=this.setTimerCallback(()=>{if(this.disposed||$!==this.generation||this.deadlineTimer?.token!==J)return;this.deadlineTimer=null,this.terminate("exhausted",Math.max(1,this.attempt),m9("timeout"),"pending-resume-recovery-deadline-exceeded")},p9);this.deadlineTimer={handle:Z,token:J},Z.unref?.()}terminate($,J,Z,Y){let X=this.activeRunController;if(this.generation++,this.requested=!1,this.waitingForIdle=!1,this.scheduledToken=null,this.activeAttemptToken=null,this.activeRunController=null,this.clearOwnedTimer("retry"),this.clearOwnedTimer("deadline"),this.resetEpisodeBudget(),Y)X?.abort(Y);try{this.options.onTerminalFailure?.({phase:$,attempt:J,taskFailure:Z})}catch{}}clearEpisode(){this.requested=!1,this.waitingForIdle=!1,this.clearOwnedTimer("retry"),this.clearOwnedTimer("deadline"),this.resetEpisodeBudget()}resetEpisodeBudget(){this.attempt=0,this.recoveryStartedAt=null}clearOwnedTimer($){let J=$==="retry"?this.retryTimer:this.deadlineTimer;if(!J)return;if($==="retry")this.retryTimer=null;else this.deadlineTimer=null;this.clearTimerCallback(J.handle)}}class p2{options;finalized=!1;constructor($){this.options=$}get isFinalized(){return this.finalized}acceptsDeltas(){return!this.finalized&&!this.options.signal.aborted}startTurn(){this.finalized=!1}finalize(){if(!this.acceptsDeltas())return!1;return this.finalized=!0,this.commit(this.options.streamingBuffer.drainPendingBuffers()),!0}abortAndFinalize($){if(this.finalized)return $(),!1;this.finalized=!0;let J=this.options.streamingBuffer.drainPendingBuffers();return $(),this.commit(J),!0}discard(){this.finalized=!0,this.options.streamingBuffer.resetStreamingBuffers(),this.options.discardStreamingMessage(),this.options.clearThinking()}commit($){let J=this.options.getStreamingMessageId();if(J){if($.extraContent)R8(J,$.extraContent);u9(J)}this.options.finalizeStreamingMessage($.extraContent,$.extraThinking)}}function LX($){if(!($ instanceof Error))return"未知错误";let Y=$.lastError??$;if(Y.responseBody)try{let U=JSON.parse(Y.responseBody)?.error?.message;if(U){let q=Y.statusCode?` (HTTP ${Y.statusCode})`:"";return`${U}${q}`}}catch{}let X=$.message.match(/Last error:\s*(.+)$/);if(X)return X[1];return $.message}function wX($){if(!($ instanceof Error))return!1;return $.name==="AbortError"||$.message.includes("aborted")}function BX($){if(!($ instanceof Error))return!1;let J=$.message;return J.includes("can only concatenate str")||J.includes("image_url")||J.includes("multimodal")||J.includes("vision")||J.includes("does not support images")}function I8($){let J=wX($),Z=BX($),Y;if(Z)Y="当前模型不支持图片理解功能。请切换到支持视觉能力的模型(如 Claude 4.5、GPT-5.2、Gemini 3 Pro、Qwen3-VL-Plus 等)后重试。";else Y=LX($);return{displayMessage:Y,isAbort:J,isVisionNotSupported:Z}}import{appendFileSync as AX,mkdirSync as PX,writeFileSync as bX}from"node:fs";import MX from"node:os";import f4 from"node:path";var c9=null;function yX(){let $=process.env.BLADE_STORAGE_ROOT||f4.join(MX.homedir(),".blade");return f4.join($,"logs","stream-debug.log")}function TX($){if(c9===$)return;let J=f4.dirname($);PX(J,{recursive:!0,mode:493}),bX($,`=== Stream Debug Log Started: ${new Date().toISOString()} ===
1
+ import{e as o3,f as n3,h as S$,i as X6}from"./chunk-dvb89529.js";import{l as oZ,m as nZ,n as tZ}from"./chunk-fag8rk53.js";import{A as h8,y as p9,z as x9}from"./chunk-qcydkn1n.js";import{Ba as oY,I as iY,M as zX,O as JJ,P as r4,Q as mY,W as CY,X as RY,aa as x$,ca as r9,da as a9,fa as IY,ha as c2,ia as OZ,ja as NZ,ma as FZ,na as WZ,ra as q9,sa as B6,ua as H6,va as L6,wa as _X,xa as zY,za as _Y}from"./chunk-xjrmq0pg.js";import"./chunk-6p6ts4kv.js";import{Ja as D3,Ka as f3,La as V3,Oa as qX}from"./chunk-sbc90z9j.js";import{Qa as TY}from"./chunk-v52wc8yg.js";import{Kb as yY,Tb as x4,xb as bY,yb as MY}from"./chunk-3e0t25rq.js";import{cc as a2}from"./chunk-77efqpdc.js";import{Bd as d9,Gd as l9,Id as k8,Qd as u2,Td as i0,md as HY,wd as m9,xd as L2}from"./chunk-rj8mmwc6.js";import"./chunk-53h87fmt.js";import{ve as n9,we as p4,xe as t9}from"./chunk-b5z1rec4.js";import{Ue as V8}from"./chunk-0z9nqbd0.js";import{ff as aZ}from"./chunk-gmqpfm52.js";import{gf as i2,hf as g8,jf as n$}from"./chunk-y0kqkewg.js";import"./chunk-a60cmnmz.js";import{Af as H$,Bf as rZ,Cf as L4,Df as l2,Gf as UY,Nf as q$,nf as K2,of as W$,pf as v1,qf as CJ,rf as R8,sf as u9,tf as t6,uf as lJ,vf as x3,wf as s6,xf as O2,yf as U$,zf as GX}from"./chunk-j3nmt09e.js";import"./chunk-v508x7cg.js";import"./chunk-mdew58v9.js";import"./chunk-ajsw4te2.js";import{bg as rJ}from"./chunk-mvm1rzc4.js";import"./chunk-edtxcqxa.js";import"./chunk-e371f7xk.js";import{Fg as KX,og as x8,rg as VZ,wg as _Z}from"./chunk-t8rjxqp2.js";import"./chunk-sx77dpxw.js";import"./chunk-aaxc81jc.js";import"./chunk-93x9xbew.js";import{ch as kJ,eh as j$}from"./chunk-r7kevfd3.js";import"./chunk-g4xny949.js";import{ri as QX,wi as zZ,xi as UX}from"./chunk-0bkhpd72.js";import"./chunk-jkfkyedn.js";import{Ai as w2,Bi as S8,Di as SJ}from"./chunk-f8gb685p.js";import{Ii as K$}from"./chunk-44jtpg8y.js";import"./chunk-sj1dzeta.js";import"./chunk-2y1qngw7.js";import{lj as XX,oj as V1}from"./chunk-ar5np5h5.js";import{qj as r3,rj as a3,uj as W1}from"./chunk-dfjmvj3d.js";import"./chunk-tkydv9k8.js";import{Gj as E3}from"./chunk-9d49tj9y.js";import{Jj as K9}from"./chunk-qcvxff27.js";import"./chunk-zwjrensv.js";import{Mj as m4,ek as QY}from"./chunk-pj69j4zp.js";import{rk as IJ}from"./chunk-zkzhm39s.js";import{useMemoizedFn as k4}from"ahooks";import{useEffect as yG,useState as S4}from"react";import{useMemoizedFn as _$}from"ahooks";import dZ from"ansi-escapes";import{Box as R1,useStdout as LG}from"ink";import{useEffect as o$,useMemo as wG,useRef as g2,useState as lZ}from"react";import{useShallow as FX}from"zustand/react/shallow";import{useStore as NX}from"zustand";function z0($){return NX(O2,$)}var WX=[],N2=()=>z0(($)=>$.session.sessionId),U1=()=>z0(($)=>$.session.workspaceRoot),N8=()=>z0(($)=>$.session.messages),z9=()=>z0(($)=>$.session.clearCount),_9=()=>z0(($)=>$.session.isCompacting),O9=()=>z0(($)=>$.session.tokenUsage.estimatedCostUsd),N9=()=>z0(($)=>{let{totalInputTokens:J,cacheReadTokens:Z,cacheWriteTokens:Y}=$.session.tokenUsage;return q9({totalInputTokens:J,cacheReadTokens:Z,cacheWriteTokens:Y}).hitRate}),F9=()=>z0(($)=>$.session.providerCircuit),W9=()=>z0(($)=>$.session.providerAdmission),H9=()=>z0(($)=>$.session.providerRetry),L9=()=>z0(($)=>$.session.providerStall),w9=()=>z0(($)=>$.session.actionStationarity),D1=()=>z0(($)=>$.session.actions),B9=()=>z0(($)=>{let{totalTokens:J,maxContextTokens:Z}=$.session.tokenUsage;if(Z<=0)return 100;let Y=Math.max(0,100-J/Z*100);return Math.round(Y)}),A9=()=>z0(($)=>$.app.initializationStatus),P9=()=>z0(($)=>$.app.initializationError),F8=()=>z0(($)=>$.app.activeModal),b9=()=>z0(($)=>$.app.tasks),M9=()=>z0(($)=>$.app.modelEditorTarget),y9=()=>z0(($)=>$.app.sessionSelectorData),T9=()=>z0(($)=>$.app.sessionHistoryViewerData),C9=()=>z0(($)=>$.app.awaitingSecondCtrlC),f1=()=>z0(($)=>$.app.actions),W8=()=>z0(($)=>$.app.sideConversation),R9=()=>z0(($)=>$.app.teams),H8=()=>z0(($)=>$.app.initializationStatus==="ready"),I9=()=>z0(($)=>$.app.tasks.length>0),F2=()=>z0(($)=>$.config.config?.permissionMode||"default"),k9=()=>z0(($)=>$.config.config?.models??WX),L8=()=>z0(($)=>{let J=$.config.config;if(!J)return;let Z=J.currentModelId;return J.models.find((X)=>X.id===Z)??J.models[0]}),w8=()=>z0(($)=>$.config.config?.currentModelId),S9=()=>z0(($)=>$.config.config?.agentTeamsEnabled===!0),V0=()=>z0(($)=>{return W$.getTheme()}),D9=()=>z0(($)=>$.config.config?.codeTheme??"default"),X$=()=>z0(($)=>$.focus.currentFocus),f9=()=>z0(($)=>$.focus.actions),W2=()=>z0(($)=>$.command.isProcessing),V9=()=>z0(($)=>$.command.actions),H2=()=>z0(($)=>$.command.pendingCommands),v9=()=>z0(($)=>$.command.recoveredSteeringCount),B8=()=>z0(($)=>$.app.reasoningEffort!=="off"),A8=()=>z0(($)=>$.app.reasoningEffort),P8=()=>z0(($)=>$.app.serviceTier),b8=()=>z0(($)=>$.app.responseVerbosity),M8=()=>z0(($)=>$.app.communicationStyle),y8=()=>z0(($)=>$.session.currentThinkingContent),j9=()=>z0(($)=>$.session.thinkingExpanded),T8=()=>z0(($)=>$.session.currentStreamingMessageId),C8=()=>z0(FX(($)=>({lines:$.session.currentStreamingLines,tail:$.session.currentStreamingTail,lineCount:$.session.currentStreamingLineCount,version:$.session.currentStreamingVersion}))),E9=()=>z0(($)=>$.session.finalizingStreamingMessageId),h9=()=>z0(($)=>$.session.historyExpanded),g9=()=>z0(($)=>$.session.expandedMessageCount);import{useMemoizedFn as F1}from"ahooks";import{useEffect as a1,useMemo as uX,useRef as p8}from"react";function HX($,J){try{return $.code===J.code&&$.message===J.message&&$.retryable===J.retryable&&$.resource===J.resource}catch{return!1}}class D4{options;requested=!1;waitingForIdle=!1;disposed=!1;generation=0;wakeEpoch=0;idleEpoch=0;attempt=0;recoveryStartedAt=null;scheduledToken=null;activeAttemptToken=null;activeRunController=null;retryTimer=null;deadlineTimer=null;now;scheduleCallback;setTimerCallback;clearTimerCallback;constructor($){this.options=$;this.now=$.now??Date.now,this.scheduleCallback=$.scheduleMicrotask??queueMicrotask,this.setTimerCallback=$.setTimer??setTimeout,this.clearTimerCallback=$.clearTimer??clearTimeout}request(){if(this.disposed)return;if(this.wakeEpoch++,this.requested=!0,this.waitingForIdle||this.retryTimer)return;this.scheduleIfRunnable()}notifyIdle(){if(this.disposed)return;if(this.idleEpoch++,this.retryTimer)return;this.waitingForIdle=!1,this.scheduleIfRunnable()}dispose(){if(this.disposed)return;this.disposed=!0,this.generation++,this.requested=!1,this.waitingForIdle=!1,this.scheduledToken=null,this.clearOwnedTimer("retry"),this.clearOwnedTimer("deadline"),this.activeAttemptToken=null;let $=this.activeRunController;this.activeRunController=null,$?.abort("pending-resume-coordinator-disposed"),this.resetEpisodeBudget()}scheduleIfRunnable(){if(this.disposed||!this.requested||this.scheduledToken||this.activeAttemptToken||this.retryTimer||this.waitingForIdle)return;if(!this.options.canRun()){this.waitingForIdle=!0;return}let $=this.generation,J={};this.scheduledToken=J;try{this.scheduleCallback(()=>{if(this.disposed||$!==this.generation||this.scheduledToken!==J)return;this.scheduledToken=null,this.flush($).catch((Z)=>{this.handleUnexpectedFailure(Z,$)})})}catch(Z){this.handleUnexpectedFailure(Z,$)}}async flush($){if(this.disposed||$!==this.generation||this.activeAttemptToken||!this.requested||this.retryTimer||this.waitingForIdle)return;if(!this.options.canRun()){this.waitingForIdle=!0;return}let J={},Z=new AbortController,Y=this.wakeEpoch,X=this.idleEpoch;if(this.attempt++,this.recoveryStartedAt===null)this.recoveryStartedAt=this.now(),this.installDeadlineTimer($);this.activeAttemptToken=J,this.activeRunController=Z;let Q=await this.options.run(Z.signal);if(this.disposed||$!==this.generation||this.activeAttemptToken!==J)return;if(this.activeAttemptToken=null,this.activeRunController=null,Q.status==="completed"){let U=this.wakeEpoch!==Y;if(this.clearEpisode(),U)this.requested=!0,this.scheduleIfRunnable();return}if(Q.status==="deferred"){if(this.attempt--,this.attempt===0)this.clearOwnedTimer("deadline"),this.resetEpisodeBudget();if(this.requested=!0,this.idleEpoch!==X)this.waitingForIdle=!1,this.scheduleIfRunnable();else this.waitingForIdle=!0;return}this.handleFailure(Q,$)}handleFailure($,J){let Z=L2($.taskFailure),Y=this.options.sessionIdentity;if($.workKind!=="pending_input"||!$.evidence||!Y||!HX($.taskFailure,$.evidence.taskFailure)){this.terminate("failed",this.attempt,Z);return}let X=x9({sessionIdentity:Y,failedAttempt:this.attempt,recoveryStartedAt:this.recoveryStartedAt??this.now(),now:this.now(),workStillPending:$.workStillPending,evidence:$.evidence});if(X.phase!=="retry_scheduled"){this.terminate(X.phase,this.attempt,Z);return}this.requested=!0,this.waitingForIdle=!1;let Q={},U=this.setTimerCallback(()=>{if(this.disposed||J!==this.generation||this.retryTimer?.token!==Q)return;this.retryTimer=null,this.scheduleIfRunnable()},X.delayMs);this.retryTimer={handle:U,token:Q},U.unref?.()}handleUnexpectedFailure($,J){if(this.disposed||J!==this.generation)return;this.terminate("failed",Math.max(1,this.attempt),L2($),"pending-resume-coordinator-failed")}installDeadlineTimer($){let J={},Z=this.setTimerCallback(()=>{if(this.disposed||$!==this.generation||this.deadlineTimer?.token!==J)return;this.deadlineTimer=null,this.terminate("exhausted",Math.max(1,this.attempt),m9("timeout"),"pending-resume-recovery-deadline-exceeded")},p9);this.deadlineTimer={handle:Z,token:J},Z.unref?.()}terminate($,J,Z,Y){let X=this.activeRunController;if(this.generation++,this.requested=!1,this.waitingForIdle=!1,this.scheduledToken=null,this.activeAttemptToken=null,this.activeRunController=null,this.clearOwnedTimer("retry"),this.clearOwnedTimer("deadline"),this.resetEpisodeBudget(),Y)X?.abort(Y);try{this.options.onTerminalFailure?.({phase:$,attempt:J,taskFailure:Z})}catch{}}clearEpisode(){this.requested=!1,this.waitingForIdle=!1,this.clearOwnedTimer("retry"),this.clearOwnedTimer("deadline"),this.resetEpisodeBudget()}resetEpisodeBudget(){this.attempt=0,this.recoveryStartedAt=null}clearOwnedTimer($){let J=$==="retry"?this.retryTimer:this.deadlineTimer;if(!J)return;if($==="retry")this.retryTimer=null;else this.deadlineTimer=null;this.clearTimerCallback(J.handle)}}class p2{options;finalized=!1;constructor($){this.options=$}get isFinalized(){return this.finalized}acceptsDeltas(){return!this.finalized&&!this.options.signal.aborted}startTurn(){this.finalized=!1}finalize(){if(!this.acceptsDeltas())return!1;return this.finalized=!0,this.commit(this.options.streamingBuffer.drainPendingBuffers()),!0}abortAndFinalize($){if(this.finalized)return $(),!1;this.finalized=!0;let J=this.options.streamingBuffer.drainPendingBuffers();return $(),this.commit(J),!0}discard(){this.finalized=!0,this.options.streamingBuffer.resetStreamingBuffers(),this.options.discardStreamingMessage(),this.options.clearThinking()}commit($){let J=this.options.getStreamingMessageId();if(J){if($.extraContent)R8(J,$.extraContent);u9(J)}this.options.finalizeStreamingMessage($.extraContent,$.extraThinking)}}function LX($){if(!($ instanceof Error))return"未知错误";let Y=$.lastError??$;if(Y.responseBody)try{let U=JSON.parse(Y.responseBody)?.error?.message;if(U){let q=Y.statusCode?` (HTTP ${Y.statusCode})`:"";return`${U}${q}`}}catch{}let X=$.message.match(/Last error:\s*(.+)$/);if(X)return X[1];return $.message}function wX($){if(!($ instanceof Error))return!1;return $.name==="AbortError"||$.message.includes("aborted")}function BX($){if(!($ instanceof Error))return!1;let J=$.message;return J.includes("can only concatenate str")||J.includes("image_url")||J.includes("multimodal")||J.includes("vision")||J.includes("does not support images")}function I8($){let J=wX($),Z=BX($),Y;if(Z)Y="当前模型不支持图片理解功能。请切换到支持视觉能力的模型(如 Claude 4.5、GPT-5.2、Gemini 3 Pro、Qwen3-VL-Plus 等)后重试。";else Y=LX($);return{displayMessage:Y,isAbort:J,isVisionNotSupported:Z}}import{appendFileSync as AX,mkdirSync as PX,writeFileSync as bX}from"node:fs";import MX from"node:os";import f4 from"node:path";var c9=null;function yX(){let $=process.env.BLADE_STORAGE_ROOT||f4.join(MX.homedir(),".blade");return f4.join($,"logs","stream-debug.log")}function TX($){if(c9===$)return;let J=f4.dirname($);PX(J,{recursive:!0,mode:493}),bX($,`=== Stream Debug Log Started: ${new Date().toISOString()} ===
2
2
  `),c9=$}function V4($,J,Z){try{let Y=yX();TX(Y);let X=new Date().toISOString(),Q=Z?` | ${JSON.stringify(Z)}`:"",U=`[${X}] [${$}] ${J}${Q}
3
3
  `;AX(Y,U)}catch{}}var x2=V1("UI");function j4($,J){if(J.state==="requires_attention"){let Z=J.reason==="interrupted_tool_call";$.addToolMessage("Turn recovery requires attention",{toolName:"Runtime Recovery",phase:"complete",summary:Z?"An interrupted tool may have partially completed":"A completed tool may already have changed external state",detail:`${J.turnId} · inspect workspace, processes, and external state before retrying`});return}$.addToolMessage(J.state==="completed"?"Recovered completed turn":"Resuming interrupted turn",{toolName:"Runtime Recovery",phase:"complete",summary:J.state==="completed"?"The durable final response was recovered":"No tool execution was recorded before interruption",detail:J.turnId})}function i9($,J){let Z=$.streamSession??new p2({signal:$.signal,streamingBuffer:$.streamingBuffer,getStreamingMessageId:$.getStreamingMessageId,finalizeStreamingMessage:$.sessionActions.finalizeStreamingMessage,discardStreamingMessage:$.sessionActions.discardStreamingMessage,clearThinking:()=>$.sessionActions.setCurrentThinkingContent(null)});return(Y)=>{switch(Y.kind){case"content_delta":if(Y.delta.length>0)J.outputStarted=!0;if(!Z.acceptsDeltas())break;J.contentDeltaCount++,J.contentDeltaTotalLen+=Y.delta.length,V4("loopEventHandler","onContentDelta",{callCount:J.contentDeltaCount,deltaLen:Y.delta.length,totalLen:J.contentDeltaTotalLen}),$.streamingBuffer.batchAppendContent(Y.delta);break;case"thinking_delta":if(Y.delta.length>0)J.outputStarted=!0;if(!Z.acceptsDeltas())break;if($.thinkingModeEnabled)$.streamingBuffer.batchAppendThinking(Y.delta);break;case"stream_end":{$.sessionActions.setProviderCircuit(null),$.sessionActions.setProviderRetry(null),$.sessionActions.setProviderStall(null),x2.debug("[loopEventHandler] stream_end",{contentDeltaCount:J.contentDeltaCount,contentDeltaTotalLen:J.contentDeltaTotalLen,streamFinalized:Z.isFinalized,signalAborted:$.signal.aborted}),V4("loopEventHandler","onStreamEnd",{contentDeltaCallCount:J.contentDeltaCount,contentDeltaTotalLen:J.contentDeltaTotalLen,streamFinalized:Z.isFinalized,signalAborted:$.signal.aborted}),Z.finalize();break}case"model_fallback":$.sessionActions.setProviderAdmission(null),$.sessionActions.setProviderCircuit(null),$.sessionActions.setProviderRetry(null),$.sessionActions.setProviderStall(null),Z.discard();break;case"provider_admission":{let{kind:X,...Q}=Y;$.sessionActions.setProviderAdmission(Y.phase==="queued"?Q:null);break}case"provider_circuit":{let{kind:X,...Q}=Y;$.sessionActions.setProviderCircuit(Y.phase==="closed"?null:Q);break}case"provider_retry":{let{kind:X,...Q}=Y;$.sessionActions.setProviderRetry(Y.phase==="recovered"?null:Q);break}case"provider_stall":{let{kind:X,...Q}=Y;$.sessionActions.setProviderStall(Y.phase==="detected"?Q:null);break}case"action_stationarity":{let{kind:X,...Q}=Y;$.sessionActions.setActionStationarity(Y.phase==="recovered"?null:Q);break}case"turn_recovery":{j4($.sessionActions,Y.assessment);break}case"tool_start":{J.toolExecutionStarted=!0;let X=Y.toolCall;if(!("function"in X))break;if(X.function.name===k8)break;if(x2.debug("[loopEventHandler] tool_start",{toolName:X.function.name,toolKind:Y.toolKind}),["TaskCreate","TaskUpdate","TaskList"].includes(X.function.name))break;try{let Q=JSON.parse(X.function.arguments),U=r9(X.function.name,Q);$.sessionActions.addToolMessage(U,{toolCallId:X.id,toolName:X.function.name,phase:"start",summary:U,params:Q})}catch(Q){x2.error("[loopEventHandler] onToolStart error:",Q)}break}case"tool_progress":{J.toolExecutionStarted=!0;let X=Y.toolCall;if(!("function"in X))break;if(X.function.name===k8)break;let Q=Y.update.total!==void 0?` ${Math.max(0,Math.min(100,Math.round((Y.update.progress??0)/Y.update.total*100)))}%`:"",U=`${X.function.name}${Q}: ${Y.update.message}`;$.sessionActions.addToolMessage(U,{toolCallId:X.id,toolName:X.function.name,phase:"progress",summary:U,...Y.update.admission?{admission:Y.update.admission}:{}});break}case"tool_result":{J.toolExecutionStarted=!0;let X=Y.toolCall;if(!("function"in X))break;if(X.function.name===k8)break;x2.debug("[loopEventHandler] tool_result",{toolName:X.function.name,success:Y.result.success});let Q=l9(a9(X.function.name,Y.result),d9);$.sessionActions.addToolMessage(Q.summary,{toolCallId:X.id,toolName:X.function.name,phase:"complete",summary:Q.summary,detail:Q.detail});break}case"structured_output":J.outputStarted=!0,$.sessionActions.replaceLastAssistantMessage(JSON.stringify(Y.output,null,2));break;case"token_usage":$.sessionActions.updateTokenUsage(Y.usage);break;case"compaction":if($.sessionActions.setCompacting(Y.phase==="start"),Y.phase==="end"){if($.sessionActions.resetContextUsage(),Y.outcome!=="failed")J.compactionCount=(J.compactionCount??0)+1}break;case"turn_start":x2.debug("[loopEventHandler] turn_start",{turn:Y.turn,maxTurns:Y.maxTurns}),$.sessionActions.updateTokenUsage({turnCount:Y.turn}),$.sessionActions.setProviderCircuit(null),$.sessionActions.setProviderRetry(null),$.sessionActions.setProviderStall(null),Z.startTurn();break;case"task_update":$.appActions.setTasks(Y.tasks);break;case"goal_frontier_updated":$.appActions.setTasks(Y.tasks);break;case"mcp_catalog_changed":{let X=`MCP catalog r${Y.revision}: +${Y.added.length} -${Y.removed.length} ~${Y.updated.length}`;$.sessionActions.addToolMessage(X,{toolName:"MCP Catalog",phase:"complete",summary:X,detail:[Y.added.length>0?`Added: ${Y.added.join(", ")}`:"",Y.removed.length>0?`Removed: ${Y.removed.join(", ")}`:"",Y.updated.length>0?`Updated: ${Y.updated.join(", ")}`:""].filter(Boolean).join(`
4
4
  `)});break}case"mcp_content_changed":{let X=`MCP ${Y.contentKind} r${Y.revision}: +${Y.added.length} -${Y.removed.length} ~${Y.updated.length}`;$.sessionActions.addToolMessage(X,{toolName:"MCP Content",phase:"complete",summary:X,detail:[Y.added.length>0?`Added: ${Y.added.join(", ")}`:"",Y.removed.length>0?`Removed: ${Y.removed.join(", ")}`:"",Y.updated.length>0?`Updated: ${Y.updated.join(", ")}`:""].filter(Boolean).join(`
@@ -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-ss4sncn3.js";import{aa as O,ha as S}from"./chunk-v94ztjtp.js";import"./chunk-6p6ts4kv.js";import"./chunk-tw5fr07c.js";import"./chunk-v52wc8yg.js";import{Kb as M,Tb as E}from"./chunk-s2atpv23.js";import"./chunk-77efqpdc.js";import{Td as f}from"./chunk-7jj607dg.js";import"./chunk-53h87fmt.js";import{we as h}from"./chunk-gfbkrk60.js";import"./chunk-0z9nqbd0.js";import{af as I}from"./chunk-e1d0e6t6.js";import{cf as y,df as R,ef as g}from"./chunk-pk11fexz.js";import{ff as C}from"./chunk-gmqpfm52.js";import"./chunk-a60cmnmz.js";import{Cf as w}from"./chunk-zc91c7b5.js";import"./chunk-v508x7cg.js";import"./chunk-mdew58v9.js";import"./chunk-ajsw4te2.js";import"./chunk-mvm1rzc4.js";import"./chunk-edtxcqxa.js";import"./chunk-8a6nrqdc.js";import"./chunk-a4jetpj8.js";import"./chunk-sx77dpxw.js";import"./chunk-aaxc81jc.js";import"./chunk-93x9xbew.js";import"./chunk-r9tawy93.js";import"./chunk-g4xny949.js";import"./chunk-hhg1zcbq.js";import{yi as A}from"./chunk-jkfkyedn.js";import"./chunk-f8gb685p.js";import{Ii as P}from"./chunk-44jtpg8y.js";import"./chunk-sj1dzeta.js";import"./chunk-2y1qngw7.js";import"./chunk-ar5np5h5.js";import"./chunk-dfjmvj3d.js";import"./chunk-tkydv9k8.js";import"./chunk-v5hzk7j2.js";import"./chunk-qcvxff27.js";import"./chunk-zwjrensv.js";import"./chunk-pj69j4zp.js";import"./chunk-zkzhm39s.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-8y08fytr.js";import{aa as O,ha as S}from"./chunk-xjrmq0pg.js";import"./chunk-6p6ts4kv.js";import"./chunk-sbc90z9j.js";import"./chunk-v52wc8yg.js";import{Kb as M,Tb as E}from"./chunk-3e0t25rq.js";import"./chunk-77efqpdc.js";import{Td as f}from"./chunk-rj8mmwc6.js";import"./chunk-53h87fmt.js";import{we as h}from"./chunk-b5z1rec4.js";import"./chunk-0z9nqbd0.js";import{af as I}from"./chunk-7dy3mzgz.js";import{cf as y,df as R,ef as g}from"./chunk-749jzrbk.js";import{ff as C}from"./chunk-gmqpfm52.js";import"./chunk-a60cmnmz.js";import{Cf as w}from"./chunk-j3nmt09e.js";import"./chunk-v508x7cg.js";import"./chunk-mdew58v9.js";import"./chunk-ajsw4te2.js";import"./chunk-mvm1rzc4.js";import"./chunk-edtxcqxa.js";import"./chunk-e371f7xk.js";import"./chunk-t8rjxqp2.js";import"./chunk-sx77dpxw.js";import"./chunk-aaxc81jc.js";import"./chunk-93x9xbew.js";import"./chunk-r7kevfd3.js";import"./chunk-g4xny949.js";import"./chunk-0bkhpd72.js";import{yi as A}from"./chunk-jkfkyedn.js";import"./chunk-f8gb685p.js";import{Ii as P}from"./chunk-44jtpg8y.js";import"./chunk-sj1dzeta.js";import"./chunk-2y1qngw7.js";import"./chunk-ar5np5h5.js";import"./chunk-dfjmvj3d.js";import"./chunk-tkydv9k8.js";import"./chunk-9d49tj9y.js";import"./chunk-qcvxff27.js";import"./chunk-zwjrensv.js";import"./chunk-pj69j4zp.js";import"./chunk-zkzhm39s.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}