blade-code 0.10.138 → 0.10.139

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 (77) hide show
  1. package/dist/blade.js +2 -2
  2. package/dist/{chunk-5v1pjexj.js → chunk-04t21rey.js} +1 -1
  3. package/dist/{chunk-k10d8t4f.js → chunk-05cv54r8.js} +1 -1
  4. package/dist/{chunk-y66f1t18.js → chunk-1h3736q2.js} +3 -3
  5. package/dist/{chunk-7vdf66jp.js → chunk-25r1v5rn.js} +2 -2
  6. package/dist/{chunk-303b3x5q.js → chunk-2agbk8ef.js} +1 -1
  7. package/dist/{chunk-pty1ncam.js → chunk-2bty4510.js} +1 -1
  8. package/dist/{chunk-8cnxy251.js → chunk-2f7nr9hh.js} +1 -1
  9. package/dist/{chunk-2m79vd9p.js → chunk-2jq9ed09.js} +1 -1
  10. package/dist/{chunk-n2tfj82m.js → chunk-2t9vtt75.js} +1 -1
  11. package/dist/{chunk-8cqm87j5.js → chunk-3aaehgva.js} +1 -1
  12. package/dist/{chunk-92n2p24j.js → chunk-3ekz3zms.js} +1 -1
  13. package/dist/{chunk-atdq9btn.js → chunk-40pd090k.js} +1 -1
  14. package/dist/{chunk-56py3ryh.js → chunk-5qwpdx3n.js} +1 -1
  15. package/dist/{chunk-14j2dbd6.js → chunk-5w8pmsqe.js} +1 -1
  16. package/dist/{chunk-j21hez8g.js → chunk-6j5v5emj.js} +1 -1
  17. package/dist/{chunk-byeq45rv.js → chunk-7pg5y3pg.js} +1 -1
  18. package/dist/{chunk-he0f6h5q.js → chunk-bgzj85za.js} +1 -1
  19. package/dist/{chunk-nqts5by0.js → chunk-cefmcwyv.js} +1 -1
  20. package/dist/{chunk-gcg56vaw.js → chunk-dw0mewc2.js} +1 -1
  21. package/dist/{chunk-23c4pys6.js → chunk-esff371k.js} +1 -1
  22. package/dist/{chunk-nnas8tdt.js → chunk-f4cn6v8t.js} +1 -1
  23. package/dist/{chunk-r7bv1hmq.js → chunk-gc4kj295.js} +1 -1
  24. package/dist/{chunk-e71y87zg.js → chunk-gjc1hhhv.js} +1 -1
  25. package/dist/chunk-grx6fv9w.js +5 -0
  26. package/dist/{chunk-03zfvfen.js → chunk-gx4seq5c.js} +1 -1
  27. package/dist/{chunk-egadh3e9.js → chunk-mec8yedz.js} +1 -1
  28. package/dist/{chunk-nyw686sf.js → chunk-mh3ne2sf.js} +1 -1
  29. package/dist/{chunk-qdjqbgts.js → chunk-mkckss82.js} +1 -1
  30. package/dist/{chunk-2t0wp7gm.js → chunk-mtfjwsn2.js} +1 -1
  31. package/dist/{chunk-wv1mnf2m.js → chunk-ntpwqfy3.js} +1 -1
  32. package/dist/chunk-q82ntq7t.js +1 -0
  33. package/dist/{chunk-5bfvdy62.js → chunk-qrv72yy6.js} +2 -2
  34. package/dist/{chunk-j58wrt5n.js → chunk-recafw5r.js} +1 -1
  35. package/dist/{chunk-ec7ykyqz.js → chunk-sdhdn0yx.js} +1 -1
  36. package/dist/{chunk-d11mqbqk.js → chunk-sj4gz23a.js} +1 -1
  37. package/dist/{chunk-ddcz0nwv.js → chunk-smjfqtws.js} +1 -1
  38. package/dist/{chunk-59980a8h.js → chunk-wazhd8bm.js} +1 -1
  39. package/dist/chunk-wf4s1hp2.js +1 -0
  40. package/dist/{chunk-mjnkxem3.js → chunk-x3c718v5.js} +1 -1
  41. package/dist/{chunk-fndqbf45.js → chunk-zz5n2qxk.js} +1 -1
  42. package/dist/web/assets/{ChatView-CZLmEMBO.js → ChatView-CQnuGDqk.js} +9 -9
  43. package/dist/web/assets/{CodeBlockHighlighter-6-iPmomS.js → CodeBlockHighlighter-CYhxXWvb.js} +1 -1
  44. package/dist/web/assets/{FilePreview-D0aSwNF3.js → FilePreview-ByTaE1GR.js} +1 -1
  45. package/dist/web/assets/{KanbanBoard-xPziptbY.js → KanbanBoard-KMmGvNPc.js} +1 -1
  46. package/dist/web/assets/{MarkdownRenderer-TWNqhwrr.js → MarkdownRenderer-C6lKOJaG.js} +3 -3
  47. package/dist/web/assets/{ScrollArea-CSQyGeWr.js → ScrollArea-Bo6cZ3PH.js} +1 -1
  48. package/dist/web/assets/{SessionHistorySurface-PRpOrUav.js → SessionHistorySurface-Cymc4xw0.js} +1 -1
  49. package/dist/web/assets/{SettingsModal-Ds-Uf-3r.js → SettingsModal-D36xhHwa.js} +1 -1
  50. package/dist/web/assets/{Sidebar-D6VyjkRY.js → Sidebar-DEGQINYb.js} +1 -1
  51. package/dist/web/assets/{TaskSwitcher-BEsAgt0k.js → TaskSwitcher-BEISb7-8.js} +1 -1
  52. package/dist/web/assets/{TerminalPanel-C_2lnmKH.js → TerminalPanel-B7PXaRGh.js} +1 -1
  53. package/dist/web/assets/{archive-CPBIxP8f.js → archive-Dyn5Oz68.js} +1 -1
  54. package/dist/web/assets/{arrow-left-z3DhPgf-.js → arrow-left-mWU3P1zb.js} +1 -1
  55. package/dist/web/assets/{calendar-clock-tYt1E6zR.js → calendar-clock-B6b0Cb3d.js} +1 -1
  56. package/dist/web/assets/{chevron-right-BGTvSaVS.js → chevron-right-Cl6g5_0e.js} +1 -1
  57. package/dist/web/assets/{chevrons-up-down-Jw3ElnjQ.js → chevrons-up-down-FKryGzO4.js} +1 -1
  58. package/dist/web/assets/{clock-3-v0h4RrLK.js → clock-3-CfVjvMmA.js} +1 -1
  59. package/dist/web/assets/{copy-CF3TUa0u.js → copy-CIYuf7du.js} +1 -1
  60. package/dist/web/assets/{download-ZG8PfhmH.js → download-DecDFX8n.js} +1 -1
  61. package/dist/web/assets/{external-link-BKCjDDt-.js → external-link-DaSwvjf7.js} +1 -1
  62. package/dist/web/assets/{folder-M-NM2bQG.js → folder-DZtlKvFm.js} +1 -1
  63. package/dist/web/assets/index-DQaqO-lw.js +203 -0
  64. package/dist/web/assets/{pause-CP_wlUro.js → pause-Bd-STGLc.js} +1 -1
  65. package/dist/web/assets/{pencil-U3n9D8ed.js → pencil-BoTIqqxX.js} +1 -1
  66. package/dist/web/assets/{play-NBWnc2gU.js → play-C4ctis0t.js} +1 -1
  67. package/dist/web/assets/{plus-CmPqJgff.js → plus-D08TlGJu.js} +1 -1
  68. package/dist/web/assets/{settings-CVFpbh_y.js → settings-BGRhMFaU.js} +1 -1
  69. package/dist/web/assets/{team-B9Na0Ocd.js → team-CPme0l2K.js} +1 -1
  70. package/dist/web/assets/{teamService-ZQZLqsjy.js → teamService-CVCtTVfY.js} +1 -1
  71. package/dist/web/assets/{terminal-BdmigqIS.js → terminal-D7GsyYki.js} +1 -1
  72. package/dist/web/index.html +1 -1
  73. package/package.json +1 -1
  74. package/dist/chunk-3g2z6hae.js +0 -1
  75. package/dist/chunk-5gy3x011.js +0 -1
  76. package/dist/chunk-ar85hxx2.js +0 -5
  77. package/dist/web/assets/index-VQVOzFZT.js +0 -203
package/dist/blade.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{tf as W}from"./chunk-92n2p24j.js";import{wf as F,xf as M}from"./chunk-6qhbdcse.js";import"./chunk-mjnkxem3.js";import"./chunk-v508x7cg.js";import"./chunk-5j68055h.js";import"./chunk-ec7ykyqz.js";import"./chunk-1bqatrxs.js";import"./chunk-atdq9btn.js";import"./chunk-npc7jt96.js";import"./chunk-mc2mr1kn.js";import{Ui as N,Vi as B}from"./chunk-dv2m2xe5.js";import"./chunk-fbrdcveb.js";import{uj as T}from"./chunk-ft1bdqbs.js";import"./chunk-jb4hmk56.js";import"./chunk-65c3vjwm.js";import"./chunk-2t0wp7gm.js";import"./chunk-jy7k2dwm.js";import"./chunk-earhezc8.js";import"./chunk-t88sfhjj.js";import{Ek as J}from"./chunk-516adpx6.js";import p from"node:path";var E=process.argv.slice(2),I=c(E),u=I!==null;if(I!==null)T.setGlobalDebug(I);function c(Q){for(let Y=0;Y<Q.length;Y+=1){let U=Q[Y];if(U==="--debug"||U==="-d"){let X=Q[Y+1];return X&&!X.startsWith("-")?X:!0}if(U.startsWith("--debug="))return U.slice(8)||!0}return null}function m(Q){return Q.length===1&&(Q[0]==="--version"||Q[0]==="-V")}function q(Q,...Y){return Q.some((U)=>Y.some((X)=>U===X||U.startsWith(`${X}=`)))}function t(Q,...Y){let U=[];for(let X=0;X<Q.length;X+=1){let G=Q[X],z=Y.find(($)=>G.startsWith(`${$}=`));if(z){let $=G.slice(z.length+1);if($)U.push($);continue}if(Y.includes(G)){let $=Q[X+1];if($&&!$.startsWith("-"))U.push($),X+=1}}return U}async function l(){if(m(E)){let{getVersion:K}=await import("./chunk-8cnxy251.js");console.log(K());return}let Q=process.cwd(),Y=F(Q);M(Y),N(B());let U=t(E,"--plugin-dir","--pluginDir");if(U.length>0){let{configureInvocationPluginDirs:K}=await import("./chunk-e71y87zg.js");K(U.map((Z)=>p.resolve(Q,Z)))}if(q(E,"--trust-workspace","--trustWorkspace")){let{WorkspaceTrustService:K}=await import("./chunk-3t5r41yh.js");await K.getInstance().trust(B())}if(process.getuid&&process.getuid()===0){let K=!!process.env.SUDO_USER,Z=!!process.env.BLADE_ALLOW_ROOT;if(K&&!Z)console.error(""),console.error("Error: 请不要使用 sudo 运行 blade"),console.error(""),console.error("原因:"),console.error(" 使用 sudo 会创建属于 root 的配置文件,"),console.error(" 导致普通用户无法访问。"),console.error(""),console.error("正确用法:"),console.error(" blade # 直接运行,不要加 sudo"),console.error(""),console.error("如果遇到权限错误,请运行:"),console.error(" sudo chown -R $USER:$USER ~/.blade/"),console.error(""),console.error("如果你确实需要以 root 运行(容器/CI),设置环境变量:"),console.error(" BLADE_ALLOW_ROOT=1 blade"),console.error(""),process.exit(1)}if(q(E,"--headless")){let{handleHeadlessMode:K}=await import("./chunk-pty1ncam.js");if(await K())return}if(W(),q(E,"--print","-p")){let{handlePrintMode:K}=await import("./chunk-r7bv1hmq.js");if(await K())return}if(E.includes("--acp")){let{runAcpIntegration:K}=await import("./chunk-23c4pys6.js");await K();return}let[{default:X},{hideBin:G},{cliConfig:z,globalOptions:$},{loadConfiguration:_,validateOutput:D,validatePermissions:R},{browserCommands:S},{doctorCommands:k},{installCommands:O},{mcpCommands:y},{projectsCommands:V},{scheduleCommands:b},{serveCommand:P},{updateCommands:x},{webCommand:A}]=await Promise.all([import("yargs"),import("yargs/helpers"),import("./chunk-3g2z6hae.js"),import("./chunk-59980a8h.js"),import("./chunk-6ezffjq1.js"),import("./chunk-5bfvdy62.js"),import("./chunk-8rccn1y2.js"),import("./chunk-byeq45rv.js"),import("./chunk-7j4s1nrc.js"),import("./chunk-z9qv0d6k.js"),import("./chunk-qdjqbgts.js"),import("./chunk-egadh3e9.js"),import("./chunk-03zfvfen.js")]),h=X(G(process.argv)).scriptName(z.scriptName).usage(z.usage).version(z.version).locale(z.locale).showHelpOnFail(z.showHelpOnFail).demandCommand(0,"").recommendCommands().strict(z.strict).parserConfiguration({"populate--":!0}).options($).middleware([_,R,D]).command(S).command(y).command(V).command(b).command(k).command(x).command(O).command(A).command(P).completion("completion",!1).help("help","Show help").alias("help","h").alias("version","V").fail((K,Z,L)=>{if(Z){if(console.error("An error occurred:"),console.error(Z.message),u&&Z.stack)console.error(`
2
+ import{tf as W}from"./chunk-3ekz3zms.js";import{wf as F,xf as M}from"./chunk-6qhbdcse.js";import"./chunk-x3c718v5.js";import"./chunk-v508x7cg.js";import"./chunk-5j68055h.js";import"./chunk-sdhdn0yx.js";import"./chunk-1bqatrxs.js";import"./chunk-40pd090k.js";import"./chunk-npc7jt96.js";import"./chunk-mc2mr1kn.js";import{Ui as N,Vi as B}from"./chunk-dv2m2xe5.js";import"./chunk-fbrdcveb.js";import{uj as T}from"./chunk-ft1bdqbs.js";import"./chunk-jb4hmk56.js";import"./chunk-65c3vjwm.js";import"./chunk-mtfjwsn2.js";import"./chunk-jy7k2dwm.js";import"./chunk-earhezc8.js";import"./chunk-t88sfhjj.js";import{Ek as J}from"./chunk-516adpx6.js";import p from"node:path";var E=process.argv.slice(2),I=c(E),u=I!==null;if(I!==null)T.setGlobalDebug(I);function c(Q){for(let Y=0;Y<Q.length;Y+=1){let U=Q[Y];if(U==="--debug"||U==="-d"){let X=Q[Y+1];return X&&!X.startsWith("-")?X:!0}if(U.startsWith("--debug="))return U.slice(8)||!0}return null}function m(Q){return Q.length===1&&(Q[0]==="--version"||Q[0]==="-V")}function q(Q,...Y){return Q.some((U)=>Y.some((X)=>U===X||U.startsWith(`${X}=`)))}function t(Q,...Y){let U=[];for(let X=0;X<Q.length;X+=1){let G=Q[X],z=Y.find(($)=>G.startsWith(`${$}=`));if(z){let $=G.slice(z.length+1);if($)U.push($);continue}if(Y.includes(G)){let $=Q[X+1];if($&&!$.startsWith("-"))U.push($),X+=1}}return U}async function l(){if(m(E)){let{getVersion:K}=await import("./chunk-2f7nr9hh.js");console.log(K());return}let Q=process.cwd(),Y=F(Q);M(Y),N(B());let U=t(E,"--plugin-dir","--pluginDir");if(U.length>0){let{configureInvocationPluginDirs:K}=await import("./chunk-gjc1hhhv.js");K(U.map((Z)=>p.resolve(Q,Z)))}if(q(E,"--trust-workspace","--trustWorkspace")){let{WorkspaceTrustService:K}=await import("./chunk-3t5r41yh.js");await K.getInstance().trust(B())}if(process.getuid&&process.getuid()===0){let K=!!process.env.SUDO_USER,Z=!!process.env.BLADE_ALLOW_ROOT;if(K&&!Z)console.error(""),console.error("Error: 请不要使用 sudo 运行 blade"),console.error(""),console.error("原因:"),console.error(" 使用 sudo 会创建属于 root 的配置文件,"),console.error(" 导致普通用户无法访问。"),console.error(""),console.error("正确用法:"),console.error(" blade # 直接运行,不要加 sudo"),console.error(""),console.error("如果遇到权限错误,请运行:"),console.error(" sudo chown -R $USER:$USER ~/.blade/"),console.error(""),console.error("如果你确实需要以 root 运行(容器/CI),设置环境变量:"),console.error(" BLADE_ALLOW_ROOT=1 blade"),console.error(""),process.exit(1)}if(q(E,"--headless")){let{handleHeadlessMode:K}=await import("./chunk-2bty4510.js");if(await K())return}if(W(),q(E,"--print","-p")){let{handlePrintMode:K}=await import("./chunk-gc4kj295.js");if(await K())return}if(E.includes("--acp")){let{runAcpIntegration:K}=await import("./chunk-esff371k.js");await K();return}let[{default:X},{hideBin:G},{cliConfig:z,globalOptions:$},{loadConfiguration:_,validateOutput:D,validatePermissions:R},{browserCommands:S},{doctorCommands:k},{installCommands:O},{mcpCommands:y},{projectsCommands:V},{scheduleCommands:b},{serveCommand:P},{updateCommands:x},{webCommand:A}]=await Promise.all([import("yargs"),import("yargs/helpers"),import("./chunk-wf4s1hp2.js"),import("./chunk-wazhd8bm.js"),import("./chunk-6ezffjq1.js"),import("./chunk-qrv72yy6.js"),import("./chunk-8rccn1y2.js"),import("./chunk-7pg5y3pg.js"),import("./chunk-7j4s1nrc.js"),import("./chunk-z9qv0d6k.js"),import("./chunk-mkckss82.js"),import("./chunk-mec8yedz.js"),import("./chunk-gx4seq5c.js")]),h=X(G(process.argv)).scriptName(z.scriptName).usage(z.usage).version(z.version).locale(z.locale).showHelpOnFail(z.showHelpOnFail).demandCommand(0,"").recommendCommands().strict(z.strict).parserConfiguration({"populate--":!0}).options($).middleware([_,R,D]).command(S).command(y).command(V).command(b).command(k).command(x).command(O).command(A).command(P).completion("completion",!1).help("help","Show help").alias("help","h").alias("version","V").fail((K,Z,L)=>{if(Z){if(console.error("An error occurred:"),console.error(Z.message),u&&Z.stack)console.error(`
3
3
  Stack trace:`),console.error(Z.stack);else console.error(`
4
4
  Run with --debug to show the stack trace.`);process.exit(1)}if(K)console.error("Error: Invalid arguments:"),console.error(K),console.error(`
5
- Hint: Did you mean:`),L.showHelp(),process.exit(1)}).command("$0",!1,()=>{},async(K)=>{let Z=K._.slice(1),L=Z.length>0?Z.join(" "):void 0,f=import("./chunk-5gy3x011.js").then(({checkVersionOnStartup:v})=>v()),[{render:w},{createElement:j},{AppWrapper:C}]=await Promise.all([import("ink"),import("react"),import("./chunk-7vdf66jp.js")]),H={...K,initialMessage:L,debug:K.debug,print:Boolean(K.print),versionCheckPromise:f};delete H._,delete H.$0,delete H.message,w(j(C,H),{patchConsole:!0,exitOnCtrlC:!1,alternateBuffer:!1})});try{await h.parse()}catch(K){console.error("Error: Parse error:",K),process.exit(1)}}if(J.main==J.module)l().catch(console.error);export{l as main};
5
+ Hint: Did you mean:`),L.showHelp(),process.exit(1)}).command("$0",!1,()=>{},async(K)=>{let Z=K._.slice(1),L=Z.length>0?Z.join(" "):void 0,f=import("./chunk-q82ntq7t.js").then(({checkVersionOnStartup:v})=>v()),[{render:w},{createElement:j},{AppWrapper:C}]=await Promise.all([import("ink"),import("react"),import("./chunk-25r1v5rn.js")]),H={...K,initialMessage:L,debug:K.debug,print:Boolean(K.print),versionCheckPromise:f};delete H._,delete H.$0,delete H.message,w(j(C,H),{patchConsole:!0,exitOnCtrlC:!1,alternateBuffer:!1})});try{await h.parse()}catch(K){console.error("Error: Parse error:",K),process.exit(1)}}if(J.main==J.module)l().catch(console.error);export{l as main};
@@ -1,2 +1,2 @@
1
- import{Pj as S}from"./chunk-2t0wp7gm.js";import{Ek as f}from"./chunk-516adpx6.js";import*as $ from"fs/promises";import*as K from"path";import j from"semver";import{ProxyAgent as H,fetch as I}from"undici";function R(){return process.env.HTTPS_PROXY||process.env.HTTP_PROXY||process.env.https_proxy||process.env.http_proxy}function N(){let q=R();if(q)try{return new H(q)}catch(z){console.warn(`[proxyFetch] Invalid proxy URL: ${q}`)}return}async function M(q,z={}){let{timeout:W=30000,signal:Q,...B}=z;if(Q?.aborted)throw new DOMException("The operation was aborted.","AbortError");let J=N(),X=new AbortController,Y=!1,F=setTimeout(()=>{Y=!0,X.abort()},W),b=()=>X.abort();Q?.addEventListener("abort",b);try{let Z={method:B.method,headers:B.headers,body:B.body,signal:X.signal,dispatcher:J};return await I(q.toString(),Z)}catch(Z){if(Z instanceof Error&&Z.name==="AbortError"){if(Y)throw Error(`Request timeout after ${W}ms`);throw Z}throw Z}finally{clearTimeout(F),Q?.removeEventListener("abort",b)}}var w="blade-code",y="https://cdn.jsdelivr.net/npm/blade-code@latest/CHANGELOG.md",G=K.join(process.env.HOME||process.env.USERPROFILE||".",".blade"),O=K.join(G,"version-cache.json"),P=3600000,k=`https://registry.npmjs.org/${w}/latest`;async function L(){try{if(process.env.BLADE_VERSION)return process.env.BLADE_VERSION;return S()}catch{return"unknown"}}async function T(){try{let q=await $.readFile(O,"utf-8"),z=JSON.parse(q);if(Date.now()-z.checkedAt<P)return z;return{...z,checkedAt:0}}catch{return null}}async function D(q){try{await $.mkdir(G,{recursive:!0,mode:493}),await $.writeFile(O,JSON.stringify(q,null,2))}catch{}}async function x(){try{let q=await M(k,{timeout:5000,headers:{Accept:"application/json"}});if(!q.ok)return null;return(await q.json()).version||null}catch{return null}}async function _(q=!1){let z=await L(),W=y;if(z==="unknown")return{currentVersion:z,latestVersion:null,hasUpdate:!1,shouldPrompt:!1,releaseNotesUrl:W,error:"Unable to determine current version"};let Q=await T(),B=Q?.skipUntilVersion,J=null;if(!q&&Q?.latestVersion&&Q.checkedAt>0)J=Q.latestVersion;else if(J=await x(),J)await D({latestVersion:J,checkedAt:Date.now(),skipUntilVersion:B});else if(Q?.latestVersion)await D({checkedAt:0,skipUntilVersion:B});if(!J||!j.valid(J))return{currentVersion:z,latestVersion:null,hasUpdate:!1,shouldPrompt:!1,releaseNotesUrl:W,error:"Unable to check for updates"};if(j.lt(J,z))J=z,await D({latestVersion:J,checkedAt:Date.now(),skipUntilVersion:B});let X=j.gt(J,z),Y=X;if(X&&B)Y=j.gt(J,B);return{currentVersion:z,latestVersion:J,hasUpdate:X,shouldPrompt:Y,releaseNotesUrl:W}}async function u(q){let z=await T();await D({latestVersion:z?.latestVersion??q,checkedAt:z?.checkedAt||Date.now(),skipUntilVersion:q})}function g(){return`npm install -g ${w}@latest --registry https://registry.npmjs.org`}async function C(){let{spawn:q}=await import("child_process");return new Promise((z)=>{let W=g(),Q=q(W,{stdio:"inherit",shell:!0});Q.on("close",(B)=>{if(B===0)z({success:!0,message:"Upgrade successful! Please restart blade."});else z({success:!1,message:`Upgrade failed (exit code: ${B})`})}),Q.on("error",(B)=>{z({success:!1,message:`Upgrade failed: ${B.message}`})})})}async function V(){try{let q=await _();return q.shouldPrompt?q:null}catch{return null}}
1
+ import{Pj as S}from"./chunk-mtfjwsn2.js";import{Ek as f}from"./chunk-516adpx6.js";import*as $ from"fs/promises";import*as K from"path";import j from"semver";import{ProxyAgent as H,fetch as I}from"undici";function R(){return process.env.HTTPS_PROXY||process.env.HTTP_PROXY||process.env.https_proxy||process.env.http_proxy}function N(){let q=R();if(q)try{return new H(q)}catch(z){console.warn(`[proxyFetch] Invalid proxy URL: ${q}`)}return}async function M(q,z={}){let{timeout:W=30000,signal:Q,...B}=z;if(Q?.aborted)throw new DOMException("The operation was aborted.","AbortError");let J=N(),X=new AbortController,Y=!1,F=setTimeout(()=>{Y=!0,X.abort()},W),b=()=>X.abort();Q?.addEventListener("abort",b);try{let Z={method:B.method,headers:B.headers,body:B.body,signal:X.signal,dispatcher:J};return await I(q.toString(),Z)}catch(Z){if(Z instanceof Error&&Z.name==="AbortError"){if(Y)throw Error(`Request timeout after ${W}ms`);throw Z}throw Z}finally{clearTimeout(F),Q?.removeEventListener("abort",b)}}var w="blade-code",y="https://cdn.jsdelivr.net/npm/blade-code@latest/CHANGELOG.md",G=K.join(process.env.HOME||process.env.USERPROFILE||".",".blade"),O=K.join(G,"version-cache.json"),P=3600000,k=`https://registry.npmjs.org/${w}/latest`;async function L(){try{if(process.env.BLADE_VERSION)return process.env.BLADE_VERSION;return S()}catch{return"unknown"}}async function T(){try{let q=await $.readFile(O,"utf-8"),z=JSON.parse(q);if(Date.now()-z.checkedAt<P)return z;return{...z,checkedAt:0}}catch{return null}}async function D(q){try{await $.mkdir(G,{recursive:!0,mode:493}),await $.writeFile(O,JSON.stringify(q,null,2))}catch{}}async function x(){try{let q=await M(k,{timeout:5000,headers:{Accept:"application/json"}});if(!q.ok)return null;return(await q.json()).version||null}catch{return null}}async function _(q=!1){let z=await L(),W=y;if(z==="unknown")return{currentVersion:z,latestVersion:null,hasUpdate:!1,shouldPrompt:!1,releaseNotesUrl:W,error:"Unable to determine current version"};let Q=await T(),B=Q?.skipUntilVersion,J=null;if(!q&&Q?.latestVersion&&Q.checkedAt>0)J=Q.latestVersion;else if(J=await x(),J)await D({latestVersion:J,checkedAt:Date.now(),skipUntilVersion:B});else if(Q?.latestVersion)await D({checkedAt:0,skipUntilVersion:B});if(!J||!j.valid(J))return{currentVersion:z,latestVersion:null,hasUpdate:!1,shouldPrompt:!1,releaseNotesUrl:W,error:"Unable to check for updates"};if(j.lt(J,z))J=z,await D({latestVersion:J,checkedAt:Date.now(),skipUntilVersion:B});let X=j.gt(J,z),Y=X;if(X&&B)Y=j.gt(J,B);return{currentVersion:z,latestVersion:J,hasUpdate:X,shouldPrompt:Y,releaseNotesUrl:W}}async function u(q){let z=await T();await D({latestVersion:z?.latestVersion??q,checkedAt:z?.checkedAt||Date.now(),skipUntilVersion:q})}function g(){return`npm install -g ${w}@latest --registry https://registry.npmjs.org`}async function C(){let{spawn:q}=await import("child_process");return new Promise((z)=>{let W=g(),Q=q(W,{stdio:"inherit",shell:!0});Q.on("close",(B)=>{if(B===0)z({success:!0,message:"Upgrade successful! Please restart blade."});else z({success:!1,message:`Upgrade failed (exit code: ${B})`})}),Q.on("error",(B)=>{z({success:!1,message:`Upgrade failed: ${B.message}`})})})}async function V(){try{let q=await _();return q.shouldPrompt?q:null}catch{return null}}
2
2
  export{_ as k,u as l,g as m,C as n,V as o};
@@ -1,4 +1,4 @@
1
- import{Ba as L,za as F}from"./chunk-y66f1t18.js";import{Td as $,Vd as B,be as Q}from"./chunk-nqts5by0.js";import{Sg as y}from"./chunk-nnas8tdt.js";import{Vi as V}from"./chunk-dv2m2xe5.js";async function j(){await y(V())}async function I(b){let q=b.message||b._?.[0];if(typeof q==="string"&&q.trim())return q;let z=b.stdin??process.stdin;if(!z.isTTY){let G=[];for await(let K of z)G.push(K);return Buffer.concat(G).toString("utf-8").trim()}if(b.defaultMessage!==void 0)return b.defaultMessage;throw Error("No input provided")}async function M(b){let q=b.message||b._?.[0];if(typeof q==="string"&&q.trim())return q;let z=b.stdin??process.stdin;if(z.isTTY)return;let G=[];for await(let Z of z)G.push(Buffer.isBuffer(Z)?Z:Buffer.from(Z));return Buffer.concat(G).toString("utf-8").trim()||void 0}async function R(b){if(!F(b))return{mode:"agent",content:b};let q=await L(b,{cwd:V(),surface:"headless",workspaceRoot:V()});if(!q.success)return{mode:"output",content:`Error: ${q.error||"未知错误"}`,exitCode:1};let z=q.data;if(z?.action==="invoke_skill"){let{skillName:G,skillArgs:K}=z;return{mode:"agent",content:K?`Please use the "${G}" skill to help me with: ${K}`:`Please use the "${G}" skill.`}}if(z?.action==="invoke_custom_command"||z?.action==="invoke_plugin_command"){let G=z.processedContent;return{mode:"agent",content:`# Custom Command: /${z.commandName}
1
+ import{Ba as L,za as F}from"./chunk-1h3736q2.js";import{Td as $,Vd as B,be as Q}from"./chunk-cefmcwyv.js";import{Sg as y}from"./chunk-f4cn6v8t.js";import{Vi as V}from"./chunk-dv2m2xe5.js";async function j(){await y(V())}async function I(b){let q=b.message||b._?.[0];if(typeof q==="string"&&q.trim())return q;let z=b.stdin??process.stdin;if(!z.isTTY){let G=[];for await(let K of z)G.push(K);return Buffer.concat(G).toString("utf-8").trim()}if(b.defaultMessage!==void 0)return b.defaultMessage;throw Error("No input provided")}async function M(b){let q=b.message||b._?.[0];if(typeof q==="string"&&q.trim())return q;let z=b.stdin??process.stdin;if(z.isTTY)return;let G=[];for await(let Z of z)G.push(Buffer.isBuffer(Z)?Z:Buffer.from(Z));return Buffer.concat(G).toString("utf-8").trim()||void 0}async function R(b){if(!F(b))return{mode:"agent",content:b};let q=await L(b,{cwd:V(),surface:"headless",workspaceRoot:V()});if(!q.success)return{mode:"output",content:`Error: ${q.error||"未知错误"}`,exitCode:1};let z=q.data;if(z?.action==="invoke_skill"){let{skillName:G,skillArgs:K}=z;return{mode:"agent",content:K?`Please use the "${G}" skill to help me with: ${K}`:`Please use the "${G}" skill.`}}if(z?.action==="invoke_custom_command"||z?.action==="invoke_plugin_command"){let G=z.processedContent;return{mode:"agent",content:`# Custom Command: /${z.commandName}
2
2
 
3
3
  ${G}`}}return{mode:"output",content:q.content||q.message||"",exitCode:0}}import{readFile as D,stat as H}from"node:fs/promises";import J from"node:path";function x(b,q){let z;try{z=JSON.parse(b)}catch(G){throw Error(`Invalid JSON output schema from ${q}`,{cause:G})}return B(z).schema}async function _(b){if(b.jsonSchema!==void 0&&b.outputSchema!==void 0)throw Error("--json-schema cannot be combined with --output-schema");if(b.jsonSchema!==void 0)return x(b.jsonSchema,"--json-schema");if(b.outputSchema===void 0)return;let q=J.resolve(b.outputSchema),z=await H(q);if(!z.isFile())throw Error(`Output schema path is not a regular file: ${q}`);if(z.size>$)throw Error(`Output schema exceeds ${$} bytes: ${q}`);return x(await D(q,"utf8"),q)}function N(b){if(!(b instanceof Error))return!1;return b.message.includes("未找到会话")||b.message.includes("ENOENT")||b.message.includes("no such file")}async function W(b){try{return await Q.loadSessionModelContext(b,V())}catch(q){if(N(q))return null;throw q}}async function C(b){if(b.resume===!0||b.resume==="true")throw Error("--resume without a session ID is only supported in interactive UI mode");if(typeof b.resume==="string"&&b.resume.length>0){if(b.forkSession){let G=V(),K=await Q.forkSession(b.resume,{newSessionId:b.sessionId,sourceProjectPath:G,targetProjectPath:G});return{...K,messages:await Q.loadSessionModelContext(K.sessionId,G)}}let[q,z]=await Promise.all([Q.loadSessionModelContext(b.resume),Q.findSessionMetadata(b.resume)]);return{sessionId:b.resume,messages:q,metadata:z}}if(b.continue){let q=b.forkSession?await Q.listSessions({cwd:V()}):await Q.listSessions();if(q.length>0){let z=q[0].sessionId;if(b.forkSession){let G=V(),K=await Q.forkSession(z,{newSessionId:b.sessionId,sourceProjectPath:G,targetProjectPath:G});return{...K,messages:await Q.loadSessionModelContext(K.sessionId,G)}}return{sessionId:z,messages:await Q.loadSessionModelContext(z),metadata:q[0]}}if(b.forkSession)throw Error("Cannot fork: no sessions are available to continue")}if(b.sessionId){let q=await W(b.sessionId);return{sessionId:b.sessionId,messages:q??[],...q?{metadata:await Q.findSessionMetadata(b.sessionId,V())}:{}}}return{sessionId:`${b.fallbackSessionPrefix}-${Date.now()}`,messages:[]}}
4
4
  export{j as p,I as q,M as r,R as s,_ as t,C as u};
@@ -1,4 +1,4 @@
1
- import{Fa as $3}from"./chunk-16648v5c.js";import{Ia as T,Ja as t0,Oa as tX,Pa as OY,Qa as o0}from"./chunk-2m79vd9p.js";import{$a as Iz,Ra as t8,Ua as hZ,Ya as iZ,Za as $X,_a as ZX,bb as hz,cb as L9,ub as gz}from"./chunk-5xgyx25z.js";import{$b as uX,Ab as QY,Bb as l7,Cb as XY,Db as zY,Eb as tY,Gb as rQ,Ib as W0,Kb as D2,Nb as u4,Pb as GZ,Qb as d4,Rb as m4,Tb as _J,Ub as C$,_b as W8,ac as iQ,cc as u1,dc as jX,ic as IY,lc as hY,vb as $1,wb as U2,xb as JY,yb as y1,zb as u7}from"./chunk-j58wrt5n.js";import{$c as y6,$d as bX,Ac as C6,Bc as E9,Cc as h4,Dc as g4,Ec as r7,Fc as n7,Gc as _X,Hc as e9,Hd as Y8,Ic as A1,Jc as o9,Jd as f0,Kc as m8,Kd as O$,Lc as t$,Mc as e$,Nc as d2,Oc as u2,Pc as m2,Qc as v6,Rc as x6,Rd as iX,Sc as I2,Sd as eQ,Tc as Q3,Uc as h2,Vc as c8,Vd as yY,Wc as M1,Xc as t1,Yc as g2,Zc as e1,_c as $2,_d as NX,ad as Z2,bd as I6,be as s,cd as h6,dd as P$,ed as g6,fd as D3,gd as c2,hd as u6,id as d6,jd as m6,kd as c6,ld as q3,md as w3,od as F3,rc as S$,sc as FX,tc as u3,uc as C3,vc as T1,wc as n3,xc as _0,yc as T2,zc as O1}from"./chunk-nqts5by0.js";import{ce as c,de as JQ,ee as YQ,fe as fJ,he as K2}from"./chunk-zx78c1an.js";import{$e as pz,Ae as A9,Be as $$,Ce as B2,De as nZ,Ee as LX,Fe as OX,Oe as cz,je as dz,me as mz}from"./chunk-a5hkv8er.js";import{vf as DJ,wf as GJ}from"./chunk-6qhbdcse.js";import{If as c4,Jf as q0,Kf as g,Nf as E0,Of as C4,Pf as q2,Qf as U1,Rf as NZ,Sf as R1,Tf as vY,Yf as H2}from"./chunk-mjnkxem3.js";import{Zf as d1}from"./chunk-5j68055h.js";import{bg as FZ,cg as xY,hg as SY,ig as kX,jg as T4}from"./chunk-ar85hxx2.js";import{kg as mZ}from"./chunk-bq6d0v5b.js";import{ng as d0,og as _1}from"./chunk-hrcz179j.js";import{pg as mX}from"./chunk-d64b7wta.js";import{rg as UX,sg as BX,tg as GX,ug as KX}from"./chunk-14j2dbd6.js";import{Ag as I4,Bg as w1,Cg as WQ,Eg as x$,Fg as N$,Gg as U$,Hg as a8,Ig as Y2,Jg as z8,Kg as l1,Lg as i1,Mg as qX,Qg as sZ,Sg as m0,Tg as T$,Vg as R4,Wg as wX,Xg as EX,vg as k4,wg as v4,xg as x4,zg as y4}from"./chunk-nnas8tdt.js";import{$g as M$,Zg as G1,ah as w4,bh as x3,ch as y3,dh as i2,eh as I3,fh as h3,gh as o6,hh as g3,ih as n6}from"./chunk-yvmexv2c.js";import{jh as Wz,lh as DX,mh as J8,nh as qJ}from"./chunk-rhwkvx96.js";import{ph as K9,rh as y0}from"./chunk-ec7ykyqz.js";import{sh as L6,th as j9,uh as O6,vh as r1}from"./chunk-1bqatrxs.js";import{Ai as V1,Bi as CY,Ch as e3,Ci as TY,Di as RY,Eh as W9,Fi as l3,Hi as MX,Ii as VX,Jh as oX,Ji as U0,Nh as $J,Ph as zX,Rh as $Y,Sh as ZY,hi as h1,ki as p7,ui as bY,vi as jY,wi as EY,xh as t3,xi as AY,yi as LZ,zi as MY}from"./chunk-atdq9btn.js";import{Mi as F$}from"./chunk-npc7jt96.js";import{Oi as pQ,Qi as lQ}from"./chunk-mc2mr1kn.js";import{Ti as Z4,Vi as C}from"./chunk-dv2m2xe5.js";import{Aj as j3,Bj as P,Cj as u,vj as t,xj as p6,yj as s6,zj as K}from"./chunk-ft1bdqbs.js";import{Gj as HX,Hj as WX}from"./chunk-jb4hmk56.js";import{Ij as Uz,Lj as zz}from"./chunk-65c3vjwm.js";import{Pj as Dz}from"./chunk-2t0wp7gm.js";import{Vj as AX,Wj as r0}from"./chunk-jy7k2dwm.js";import{$j as G$,Zj as o,_j as L$,ak as o1,bk as l9,ck as y2,dk as Y$,ek as c7,hk as S6,qk as M6,tk as b$,yk as v3}from"./chunk-t88sfhjj.js";import{Ek as Z$}from"./chunk-516adpx6.js";import{randomUUID as b8}from"crypto";import{randomUUID as VH}from"node:crypto";var QH=String.raw`
1
+ import{Fa as $3}from"./chunk-16648v5c.js";import{Ia as T,Ja as t0,Oa as tX,Pa as OY,Qa as o0}from"./chunk-2jq9ed09.js";import{$a as Iz,Ra as t8,Ua as hZ,Ya as iZ,Za as $X,_a as ZX,bb as hz,cb as L9,ub as gz}from"./chunk-5xgyx25z.js";import{$b as uX,Ab as QY,Bb as l7,Cb as XY,Db as zY,Eb as tY,Gb as rQ,Ib as W0,Kb as D2,Nb as u4,Pb as GZ,Qb as d4,Rb as m4,Tb as _J,Ub as C$,_b as W8,ac as iQ,cc as u1,dc as jX,ic as IY,lc as hY,vb as $1,wb as U2,xb as JY,yb as y1,zb as u7}from"./chunk-recafw5r.js";import{$c as y6,$d as bX,Ac as C6,Bc as E9,Cc as h4,Dc as g4,Ec as r7,Fc as n7,Gc as _X,Hc as e9,Hd as Y8,Ic as A1,Jc as o9,Jd as f0,Kc as m8,Kd as O$,Lc as t$,Mc as e$,Nc as d2,Oc as u2,Pc as m2,Qc as v6,Rc as x6,Rd as iX,Sc as I2,Sd as eQ,Tc as Q3,Uc as h2,Vc as c8,Vd as yY,Wc as M1,Xc as t1,Yc as g2,Zc as e1,_c as $2,_d as NX,ad as Z2,bd as I6,be as s,cd as h6,dd as P$,ed as g6,fd as D3,gd as c2,hd as u6,id as d6,jd as m6,kd as c6,ld as q3,md as w3,od as F3,rc as S$,sc as FX,tc as u3,uc as C3,vc as T1,wc as n3,xc as _0,yc as T2,zc as O1}from"./chunk-cefmcwyv.js";import{ce as c,de as JQ,ee as YQ,fe as fJ,he as K2}from"./chunk-zx78c1an.js";import{$e as pz,Ae as A9,Be as $$,Ce as B2,De as nZ,Ee as LX,Fe as OX,Oe as cz,je as dz,me as mz}from"./chunk-a5hkv8er.js";import{vf as DJ,wf as GJ}from"./chunk-6qhbdcse.js";import{If as c4,Jf as q0,Kf as g,Nf as E0,Of as C4,Pf as q2,Qf as U1,Rf as NZ,Sf as R1,Tf as vY,Yf as H2}from"./chunk-x3c718v5.js";import{Zf as d1}from"./chunk-5j68055h.js";import{bg as FZ,cg as xY,hg as SY,ig as kX,jg as T4}from"./chunk-grx6fv9w.js";import{kg as mZ}from"./chunk-bq6d0v5b.js";import{ng as d0,og as _1}from"./chunk-hrcz179j.js";import{pg as mX}from"./chunk-d64b7wta.js";import{rg as UX,sg as BX,tg as GX,ug as KX}from"./chunk-5w8pmsqe.js";import{Ag as I4,Bg as w1,Cg as WQ,Eg as x$,Fg as N$,Gg as U$,Hg as a8,Ig as Y2,Jg as z8,Kg as l1,Lg as i1,Mg as qX,Qg as sZ,Sg as m0,Tg as T$,Vg as R4,Wg as wX,Xg as EX,vg as k4,wg as v4,xg as x4,zg as y4}from"./chunk-f4cn6v8t.js";import{$g as M$,Zg as G1,ah as w4,bh as x3,ch as y3,dh as i2,eh as I3,fh as h3,gh as o6,hh as g3,ih as n6}from"./chunk-yvmexv2c.js";import{jh as Wz,lh as DX,mh as J8,nh as qJ}from"./chunk-rhwkvx96.js";import{ph as K9,rh as y0}from"./chunk-sdhdn0yx.js";import{sh as L6,th as j9,uh as O6,vh as r1}from"./chunk-1bqatrxs.js";import{Ai as V1,Bi as CY,Ch as e3,Ci as TY,Di as RY,Eh as W9,Fi as l3,Hi as MX,Ii as VX,Jh as oX,Ji as U0,Nh as $J,Ph as zX,Rh as $Y,Sh as ZY,hi as h1,ki as p7,ui as bY,vi as jY,wi as EY,xh as t3,xi as AY,yi as LZ,zi as MY}from"./chunk-40pd090k.js";import{Mi as F$}from"./chunk-npc7jt96.js";import{Oi as pQ,Qi as lQ}from"./chunk-mc2mr1kn.js";import{Ti as Z4,Vi as C}from"./chunk-dv2m2xe5.js";import{Aj as j3,Bj as P,Cj as u,vj as t,xj as p6,yj as s6,zj as K}from"./chunk-ft1bdqbs.js";import{Gj as HX,Hj as WX}from"./chunk-jb4hmk56.js";import{Ij as Uz,Lj as zz}from"./chunk-65c3vjwm.js";import{Pj as Dz}from"./chunk-mtfjwsn2.js";import{Vj as AX,Wj as r0}from"./chunk-jy7k2dwm.js";import{$j as G$,Zj as o,_j as L$,ak as o1,bk as l9,ck as y2,dk as Y$,ek as c7,hk as S6,qk as M6,tk as b$,yk as v3}from"./chunk-t88sfhjj.js";import{Ek as Z$}from"./chunk-516adpx6.js";import{randomUUID as b8}from"crypto";import{randomUUID as VH}from"node:crypto";var QH=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 @@ ${L1}
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+c$;else N0=[...F,{type:"text",text:c$}]}S=yield*this.runLoop(N0,O,{...x,inputMessageId:void 0})}if(!this.sessionRuntime||!v)return S;let n=await this.sessionRuntime.recordGoalProgress({tokens:S.metadata?.tokensUsed??0,elapsedMs:S.metadata?.duration??0,prematureStopPattern:S.success?e7(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(v,O.signal);let $0=S.success&&!O.signal?.aborted&&f<20,l=aB(S);if(r=await this.sessionRuntime.finishTurn(v,{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="",k=void 0,E="",A=void 0,M=e(),yield{kind:"follow_up_started",queued:this.sessionRuntime.getPendingSteeringCount(),recovered:this.sessionRuntime.getRecoveredSteeringCount(),messages:I(),queue:await this.sessionRuntime.getFollowUpQueueSnapshot()};continue}if(yield{kind:"follow_up_queue_changed",queue:await this.sessionRuntime.getFollowUpQueueSnapshot()},!S.success||O.signal?.aborted)return S;if(n=await this.sessionRuntime.getGoal(),!n||n.status!=="active"&&n.status!=="verifying")return S;let f$=await this.sessionRuntime.beginGoalContinuation();if(!f$)return S;let J0=await this.sessionRuntime.prepareGoalContinuation(f$);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=C5(b),k=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 U==="string"?U:U.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-wv1mnf2m.js");return Y(this.chatStream($,Z,J))}async*runPlanLoop($,Z,J){a.debug("Processing Plan mode message...");let{prompt:Y}=await Z1({...Z.workspaceKind==="acp-remote"?{workspaceAccess:"none"}:{projectPath:Z.workspaceRoot||C()},mode:"plan",includeEnvironment:!0,environmentOptions:{...u1,workingDirectory:Z.executionRoot??Z.workspaceRoot??C()},language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),...Z.workspaceKind==="acp-remote"?{}:{projectInstructionSourcePath:this.sessionRuntime?.projectRoot}}),Q;if(typeof $==="string")Q=n2($);else{let X=$.filter((z)=>z.type==="text");if(X.length>0){let z=X[0];Q=$.map((H)=>H===z?{type:"text",text:n2(z.text)}:H)}else Q=[{type:"text",text:n2("")},...$]}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 Z1({...$.workspaceKind==="acp-remote"?{workspaceAccess:"none"}:{projectPath:$.workspaceRoot||C()},replaceDefault:Z,append:J,includeEnvironment:!0,environmentOptions:{...u1,workingDirectory:$.executionRoot??$.workspaceRoot??C()},language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),...$.workspaceKind==="acp-remote"?{}:{projectInstructionSourcePath:this.sessionRuntime?.projectRoot}})).prompt}executeLoop($,Z,J,Y){if(!this.isInitialized)throw Error("Agent未初始化");let Q=this.buildLoopDependencies();return hY(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,z=J.output,H={success:X,llmContent:typeof z==="string"||z!==null&&typeof z==="object"?z:z===null?J.error?`Subagent execution failed: ${J.error}.`:"":String(z),...J.error?{error:{type:"execution_error",message:J.error}}:{},...Q?{metadata:Q}:{}},W=[{kind:"tool_result",toolCall:Y,result:H}],V=IY(Y,H);if(V)W.push(V);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 Z1({...this.sessionRuntime?.isRemoteWorkspace()?{workspaceAccess:"none"}:{projectPath:this.sessionRuntime?.workspaceRoot??C()},replaceDefault:$,append:Z,includeEnvironment:!1,language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),...this.sessionRuntime?.isRemoteWorkspace()?{}:{projectInstructionSourcePath:this.sessionRuntime?.projectRoot},...this.sessionRuntime?{environmentOptions:{...u1,workingDirectory:this.sessionRuntime.executionRoot}}:{}});if(J.prompt)this.log("系统提示配置验证成功"),a.debug(`[SystemPrompt] 可用来源: ${J.sources.filter((Y)=>Y.loaded).map((Y)=>Y.name).join(", ")}`)}catch($){this.error("系统提示配置验证失败",$)}}async registerBuiltinTools(){try{let $=await f4({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 J4({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 r2(`legacy-${nB()}`)});this.legacyMcpRegistry=Z;for(let[X,z]of Object.entries($))try{a.debug(`Connecting to MCP server: ${X}`),await Z.registerServer(X,z),a.debug(`MCP server "${X}" connected`)}catch(H){a.warn(`Warning: MCP server "${X}" connection failed:`,H)}let J=this.toolExecutor.getRegistry();J.setMcpCatalogBarrier(()=>Z.waitForCatalogIdle());let Y=Z.getCatalogSnapshot();J.replaceMcpTools(Y.tools),J.registerAll(e2(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=R4($),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-ntpwqfy3.js");return Y(this.chatStream($,Z,J))}async*runPlanLoop($,Z,J){a.debug("Processing Plan mode message...");let{prompt:Y}=await Z1({...Z.workspaceKind==="acp-remote"?{workspaceAccess:"none"}:{projectPath:Z.workspaceRoot||C()},mode:"plan",includeEnvironment:!0,environmentOptions:{...u1,workingDirectory:Z.executionRoot??Z.workspaceRoot??C()},language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),...Z.workspaceKind==="acp-remote"?{}:{projectInstructionSourcePath:this.sessionRuntime?.projectRoot}}),Q;if(typeof $==="string")Q=n2($);else{let X=$.filter((z)=>z.type==="text");if(X.length>0){let z=X[0];Q=$.map((H)=>H===z?{type:"text",text:n2(z.text)}:H)}else Q=[{type:"text",text:n2("")},...$]}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 Z1({...$.workspaceKind==="acp-remote"?{workspaceAccess:"none"}:{projectPath:$.workspaceRoot||C()},replaceDefault:Z,append:J,includeEnvironment:!0,environmentOptions:{...u1,workingDirectory:$.executionRoot??$.workspaceRoot??C()},language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),...$.workspaceKind==="acp-remote"?{}:{projectInstructionSourcePath:this.sessionRuntime?.projectRoot}})).prompt}executeLoop($,Z,J,Y){if(!this.isInitialized)throw Error("Agent未初始化");let Q=this.buildLoopDependencies();return hY(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,z=J.output,H={success:X,llmContent:typeof z==="string"||z!==null&&typeof z==="object"?z:z===null?J.error?`Subagent execution failed: ${J.error}.`:"":String(z),...J.error?{error:{type:"execution_error",message:J.error}}:{},...Q?{metadata:Q}:{}},W=[{kind:"tool_result",toolCall:Y,result:H}],V=IY(Y,H);if(V)W.push(V);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 Z1({...this.sessionRuntime?.isRemoteWorkspace()?{workspaceAccess:"none"}:{projectPath:this.sessionRuntime?.workspaceRoot??C()},replaceDefault:$,append:Z,includeEnvironment:!1,language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),...this.sessionRuntime?.isRemoteWorkspace()?{}:{projectInstructionSourcePath:this.sessionRuntime?.projectRoot},...this.sessionRuntime?{environmentOptions:{...u1,workingDirectory:this.sessionRuntime.executionRoot}}:{}});if(J.prompt)this.log("系统提示配置验证成功"),a.debug(`[SystemPrompt] 可用来源: ${J.sources.filter((Y)=>Y.loaded).map((Y)=>Y.name).join(", ")}`)}catch($){this.error("系统提示配置验证失败",$)}}async registerBuiltinTools(){try{let $=await f4({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 J4({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 r2(`legacy-${nB()}`)});this.legacyMcpRegistry=Z;for(let[X,z]of Object.entries($))try{a.debug(`Connecting to MCP server: ${X}`),await Z.registerServer(X,z),a.debug(`MCP server "${X}" connected`)}catch(H){a.warn(`Warning: MCP server "${X}" connection failed:`,H)}let J=this.toolExecutor.getRegistry();J.setMcpCatalogBarrier(()=>Z.waitForCatalogIdle());let Y=Z.getCatalogSnapshot();J.replaceMcpTools(Y.tools),J.registerAll(e2(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=R4($),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>
@@ -1668,7 +1668,7 @@ ${J}
1668
1668
  `)),{success:!0,message:"Schedules listed",content:W.join(`
1669
1669
  `)}}case"create":{let H=gw(X);if("error"in H)return Y.sendMessage(`创建失败:${H.error}`),{success:!1,error:H.error};let W={prompt:H.prompt,projectPath:z,trigger:H.trigger,isolation:"worktree",permissionMode:"default",enabled:!0};try{let V=await $.create(W),U=V.nextRunAt?new Date(V.nextRunAt).toLocaleString():"(无)";return Y.sendMessage(`[OK] 已创建定时任务 \`${V.id}\`
1670
1670
  ${L9(V.trigger)} · 下次运行: ${U}`),{success:!0,message:`Schedule ${V.id} created`}}catch(V){let U=V instanceof Error?V.message:String(V);return Y.sendMessage(`创建失败:${U}`),{success:!1,error:U}}}case"remove":case"rm":{let H=X[0];if(!H)return Y.sendMessage("用法:/schedule remove <id>"),{success:!1,error:"Missing schedule id"};let W=await $.remove(H);return Y.sendMessage(W?`[OK] 已删除 \`${H}\``:`未找到 \`${H}\``),{success:W,message:W?"Removed":"Not found"}}case"enable":case"disable":{let H=X[0];if(!H)return Y.sendMessage(`用法:/schedule ${Q} <id>`),{success:!1,error:"Missing schedule id"};let W=await $.setEnabled(H,Q==="enable");return Y.sendMessage(W?`[OK] 已${Q==="enable"?"启用":"停用"} \`${H}\``:`未找到 \`${H}\``),{success:Boolean(W),message:W?"Updated":"Not found"}}case"run":{let H=X[0];if(!H)return Y.sendMessage("用法:/schedule run <id>"),{success:!1,error:"Missing schedule id"};try{return await uw(H),Y.sendMessage(`[OK] 已触发 \`${H}\``),{success:!0,message:"Schedule triggered"}}catch(W){let V=W instanceof Error?W.message:String(W);return Y.sendMessage(`运行失败:${V}`),{success:!1,error:V}}}default:return Y.sendMessage(`未知子命令: ${Q}
1671
- 使用 /schedule 查看帮助`),{success:!1,error:`Unknown subcommand: ${Q}`}}}}}var uz=dw();import*as M2 from"node:fs/promises";import*as C2 from"node:path";async function lz($,Z={}){let{maxResults:J=20,caseSensitive:Y=!1,projectPath:Q,storagePath:X}=Z,z=X??M6(Q??C());if(!X){let G=await mw($,Q??C(),J,Y);if(G)return G}let H;try{H=(await M2.readdir(z)).filter((D)=>D.endsWith(".jsonl")&&!D.startsWith("agent_")).map((D)=>C2.join(z,D))}catch{return[]}let V=(await Promise.all(H.map(async(G)=>{try{let D=await M2.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),U=[],B=Y?$:$.toLowerCase();for(let G of V){if(U.length>=J)break;let D=C2.basename(G,".jsonl"),q=await cw(G,B,Y,D);if(U.push(...q),U.length>=J){U.length=J;break}}return U}async function mw($,Z,J,Y){try{let{syncAll:Q}=await import("./chunk-8py443a5.js"),X=await cz();if(!X)return null;let{SessionService:z}=await import("./chunk-303b3x5q.js");await Q(X,z.projectionDeriverForSearch());let H=C2.resolve(Z),W=pz(X,$,H,J*4),V=Y?$:$.toLowerCase(),U=[];for(let B of W){if(B.role!=="user"&&B.role!=="assistant")continue;let G=O9(B.text,V,Y,B.session_id,B.role,B.timestamp??void 0,0);if(G)U.push(G);if(U.length>=J)break}return U}catch{return null}}async function cw($,Z,J,Y){try{let Q=await M2.readFile($,"utf8"),z=Q.split(`
1671
+ 使用 /schedule 查看帮助`),{success:!1,error:`Unknown subcommand: ${Q}`}}}}}var uz=dw();import*as M2 from"node:fs/promises";import*as C2 from"node:path";async function lz($,Z={}){let{maxResults:J=20,caseSensitive:Y=!1,projectPath:Q,storagePath:X}=Z,z=X??M6(Q??C());if(!X){let G=await mw($,Q??C(),J,Y);if(G)return G}let H;try{H=(await M2.readdir(z)).filter((D)=>D.endsWith(".jsonl")&&!D.startsWith("agent_")).map((D)=>C2.join(z,D))}catch{return[]}let V=(await Promise.all(H.map(async(G)=>{try{let D=await M2.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),U=[],B=Y?$:$.toLowerCase();for(let G of V){if(U.length>=J)break;let D=C2.basename(G,".jsonl"),q=await cw(G,B,Y,D);if(U.push(...q),U.length>=J){U.length=J;break}}return U}async function mw($,Z,J,Y){try{let{syncAll:Q}=await import("./chunk-8py443a5.js"),X=await cz();if(!X)return null;let{SessionService:z}=await import("./chunk-2agbk8ef.js");await Q(X,z.projectionDeriverForSearch());let H=C2.resolve(Z),W=pz(X,$,H,J*4),V=Y?$:$.toLowerCase(),U=[];for(let B of W){if(B.role!=="user"&&B.role!=="assistant")continue;let G=O9(B.text,V,Y,B.session_id,B.role,B.timestamp??void 0,0);if(G)U.push(G);if(U.length>=J)break}return U}catch{return null}}async function cw($,Z,J,Y){try{let Q=await M2.readFile($,"utf8"),z=Q.split(`
1672
1672
  `).flatMap((B,G)=>{if(!B.trim())return[];try{return[{event:JSON.parse(B),index:G}]}catch{return[]}});if(!z.some(({event:B})=>B.type==="session_created"))return pw(z,Z,J,Y);let W=new Map(z.flatMap(({event:B,index:G})=>typeof B.id==="string"?[[B.id,G+1]]:[])),V=dz(mz(Q,$)),U=new Map;for(let B of V){if(B.type==="message_created"&&(B.data.role==="user"||B.data.role==="assistant"))U.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=U.get(B.data.messageId),D=B.data.payload.text;if(G&&typeof D==="string")G.content.push(D)}}return[...U.values()].flatMap((B)=>{let G=O9(B.content.join(" "),Z,J,Y,B.role,B.timestamp,B.lineNumber);return G?[G]:[]})}catch{return[]}}function pw($,Z,J,Y){return $.flatMap(({event:Q,index:X})=>{if(Q.type!=="message")return[];let z=Q.message;if(z?.role!=="user"&&z?.role!=="assistant"||!z.content)return[];let H=typeof z.content==="string"?z.content:Array.isArray(z.content)?z.content.filter((V)=>typeof V==="object"&&V!==null&&V.type==="text"&&typeof V.text==="string").map((V)=>V.text).join(" "):"",W=O9(H,Z,J,Y,z.role,typeof Q.timestamp==="string"?Q.timestamp:void 0,X+1);return W?[W]:[]})}function O9($,Z,J,Y,Q,X,z){if(!$)return;let H=J?$:$.toLowerCase();if(!H.includes(Z))return;let W=H.indexOf(Z),V=Math.max(0,W-80),U=Math.min($.length,W+Z.length+80);return{sessionId:Y,role:Q,content:(V>0?"...":"")+$.slice(V,U).replace(/\n/g," ")+(U<$.length?"...":""),timestamp:X,lineNumber:z}}function iz($){if($.length===0)return"没有找到匹配的历史记录";let Z=[`**找到 ${$.length} 条匹配:**
1673
1673
  `];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(`
1674
1674
  `)}var lw={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 lz(Y,{maxResults:15,projectPath:Z.cwd}),X=iz(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}}}},rz=lw;var iw={name:"skills",description:"查看所有可用的 Skills",fullDescription:"显示所有已发现的 Skills 及其详细信息,包括名称、描述、来源和允许的工具。",usage:"/skills",category:"system",examples:["/skills"],handler:async($,Z)=>{try{let J=Z.workspaceRoot??Z.cwd;return await T$(J,async(Y)=>{await Y.skills.refresh(),i1(J),await l1(J)}),{success:!0,message:"show_skills_manager",data:{action:"show_skills_manager"}}}catch(J){let Y=`获取 Skills 失败: ${J instanceof Error?J.message:"未知错误"}`;return g().addAssistantMessage(Y),{success:!1,error:Y}}}},nz=iw;import rw from"node:path";function w8($){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 az($){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 sz($,Z){if($.length<=Z)return $;return $.slice(0,Z-3)+"..."}async function nw($,Z){let J=m(Z),Y=$[0],Q=Y0.getInstance(),X=K0.getInstance(),z=Z.sessionId??"",H=Z.sessionId?{sessionId:Z.sessionId,projectPath:rw.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(H??z,0);return J.sendMessage(`已清理 ${D} 个已完成的 Agent 会话`),{success:!0,message:`Cleaned ${D} agent sessions`}}let W=[`**后台任务列表**
@@ -1,4 +1,4 @@
1
- import{e as $5,f as J5,h as S$,i as M4}from"./chunk-fndqbf45.js";import{l as $X,m as JX,n as YX}from"./chunk-5v1pjexj.js";import{A as q4,y as A9,z as b9}from"./chunk-he0f6h5q.js";import{Ba as XY,Da as uY,I as cY,M as HX,O as h6,P as C6,Q as vY,W as wY,X as PY,_ as AY,ca as l$,ea as y9,fa as I9,ha as bY,ja as Q8,ka as L5,la as B5,oa as w5,pa as P5,ta as lJ,ua as B3,wa as H3,xa as F3,ya as FX,za as ZY}from"./chunk-y66f1t18.js";import"./chunk-16648v5c.js";import{La as EZ,Ma as hZ,Na as gZ,Qa as WX}from"./chunk-2m79vd9p.js";import{Sa as BY}from"./chunk-5xgyx25z.js";import{Hb as FY,Ib as F4,Ub as LY,bc as P6}from"./chunk-j58wrt5n.js";import{mc as z8}from"./chunk-3eskgvpy.js";import{Gd as P9,Hd as V2,Ld as C9,Qd as R9,Sd as t8,_d as X8,be as a0,wd as zY}from"./chunk-nqts5by0.js";import"./chunk-zx78c1an.js";import{Fe as D9,Ge as w6,He as f9}from"./chunk-a5hkv8er.js";import{cf as e9,df as G4}from"./chunk-awheqy52.js";import{qf as s5}from"./chunk-v2fewxvw.js";import{rf as q8,sf as _4,uf as $1}from"./chunk-92n2p24j.js";import"./chunk-6qhbdcse.js";import{Af as l1,Bf as UJ,Cf as o8,Df as M9,Ef as t3,Ff as RJ,Gf as rZ,Hf as s3,If as k2,Jf as m0,Kf as OX,Lf as L$,Mf as t5,Nf as a4,Of as U8,Rf as s9,Yf as z$,yf as M2,zf as F$}from"./chunk-mjnkxem3.js";import"./chunk-v508x7cg.js";import"./chunk-5j68055h.js";import"./chunk-ar85hxx2.js";import"./chunk-bq6d0v5b.js";import{og as yJ}from"./chunk-hrcz179j.js";import"./chunk-d64b7wta.js";import"./chunk-14j2dbd6.js";import{Bg as H4,Eg as g5,Jg as F5,Sg as NX}from"./chunk-nnas8tdt.js";import"./chunk-yvmexv2c.js";import"./chunk-rhwkvx96.js";import"./chunk-az08pq83.js";import{ph as qJ,rh as E$}from"./chunk-ec7ykyqz.js";import"./chunk-1bqatrxs.js";import{Ei as qX,Ji as H5,Ki as _X}from"./chunk-atdq9btn.js";import{Mi as h9}from"./chunk-npc7jt96.js";import{Ni as j2,Oi as e8,Qi as _J}from"./chunk-mc2mr1kn.js";import{Vi as K$}from"./chunk-dv2m2xe5.js";import"./chunk-fbrdcveb.js";import{sj as zX,vj as _1}from"./chunk-ft1bdqbs.js";import{Dj as tZ,Ej as sZ,Hj as b1}from"./chunk-jb4hmk56.js";import"./chunk-65c3vjwm.js";import{Tj as xZ}from"./chunk-2t0wp7gm.js";import{Wj as uJ}from"./chunk-jy7k2dwm.js";import"./chunk-earhezc8.js";import{Zj as Z8,rk as t9}from"./chunk-t88sfhjj.js";import{Ek as Y4}from"./chunk-516adpx6.js";import{useMemoizedFn as Q6}from"ahooks";import{useEffect as Qz,useState as G6}from"react";import{useMemoizedFn as i0}from"ahooks";import o5 from"ansi-escapes";import{Box as j1,useStdout as sK}from"ink";import{useEffect as e$,useMemo as eK,useRef as C2,useState as n5}from"react";import{useShallow as wX}from"zustand/react/shallow";import{useStore as BX}from"zustand";function q0($){return BX(k2,$)}var PX=[],D2=()=>q0(($)=>$.session.sessionId),q1=()=>q0(($)=>$.session.workspaceRoot),f8=()=>q0(($)=>$.session.messages),rJ=()=>q0(($)=>$.session.clearCount),aJ=()=>q0(($)=>$.session.isCompacting),iJ=()=>q0(($)=>$.session.tokenUsage.estimatedCostUsd),oJ=()=>q0(($)=>{let{totalInputTokens:J,cacheReadTokens:Y,cacheWriteTokens:X}=$.session.tokenUsage;return lJ({totalInputTokens:J,cacheReadTokens:Y,cacheWriteTokens:X}).hitRate});var v8=()=>q0(($)=>$.session.providerRecovery),nJ=()=>q0(($)=>$.session.turnActivity),tJ=()=>q0(($)=>$.session.actionStationarity),p1=()=>q0(($)=>$.session.actions),sJ=()=>q0(($)=>{let{totalTokens:J,maxContextTokens:Y}=$.session.tokenUsage;if(Y<=0)return 100;let X=Math.max(0,100-J/Y*100);return Math.round(X)}),eJ=()=>q0(($)=>$.app.initializationStatus),$9=()=>q0(($)=>$.app.initializationError),V8=()=>q0(($)=>$.app.activeModal),J9=()=>q0(($)=>$.app.tasks),Y9=()=>q0(($)=>$.app.modelEditorTarget),Z9=()=>q0(($)=>$.app.sessionSelectorData),X9=()=>q0(($)=>$.app.sessionHistoryViewerData),Q9=()=>q0(($)=>$.app.taskAttentionStatus),j8=()=>q0(($)=>$.app.taskAttentionUnreadKeys),G9=()=>q0(($)=>$.app.awaitingSecondCtrlC),x1=()=>q0(($)=>$.app.actions),E8=()=>q0(($)=>$.app.sideConversation),U9=()=>q0(($)=>$.app.teams),h8=()=>q0(($)=>$.app.initializationStatus==="ready"),K9=()=>q0(($)=>$.app.tasks.length>0),f2=()=>q0(($)=>$.config.config?.permissionMode||"default"),z9=()=>q0(($)=>$.config.config?.models??PX),g8=()=>q0(($)=>{let J=$.config.config;if(!J)return;let Y=J.currentModelId;return J.models.find((Z)=>Z.id===Y)??J.models[0]}),m8=()=>q0(($)=>$.config.config?.currentModelId),q9=()=>q0(($)=>$.config.config?.agentTeamsEnabled===!0),D0=()=>q0(($)=>{return F$.getTheme()}),_9=()=>q0(($)=>$.config.config?.codeTheme??"default"),X$=()=>q0(($)=>$.focus.currentFocus),O9=()=>q0(($)=>$.focus.actions),v2=()=>q0(($)=>$.command.isProcessing),N9=()=>q0(($)=>$.command.actions),p8=()=>q0(($)=>$.app.followUpQueue),W9=()=>q0(($)=>$.app.followUpQueueMutation),H9=()=>q0(($)=>$.command.recoveredSteeringCount),x8=()=>q0(($)=>$.app.reasoningEffort!=="off"),c8=()=>q0(($)=>$.app.reasoningEffort),u8=()=>q0(($)=>$.app.serviceTier),d8=()=>q0(($)=>$.app.responseVerbosity),l8=()=>q0(($)=>$.app.communicationStyle),r8=()=>q0(($)=>$.session.currentThinkingContent),F9=()=>q0(($)=>$.session.thinkingExpanded),a8=()=>q0(($)=>$.session.currentStreamingMessageId),i8=()=>q0(wX(($)=>({lines:$.session.currentStreamingLines,tail:$.session.currentStreamingTail,lineCount:$.session.currentStreamingLineCount,version:$.session.currentStreamingVersion}))),L9=()=>q0(($)=>$.session.finalizingStreamingMessageId),B9=()=>q0(($)=>$.session.historyExpanded),w9=()=>q0(($)=>$.session.expandedMessageCount);import{randomUUID as O7}from"node:crypto";import{useMemoizedFn as J1}from"ahooks";import{useEffect as u1,useMemo as WY,useRef as N4}from"react";function AX($,J){try{return $.code===J.code&&$.message===J.message&&$.retryable===J.retryable&&$.resource===J.resource}catch{return!1}}class K6{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((Y)=>{this.handleUnexpectedFailure(Y,$)})})}catch(Y){this.handleUnexpectedFailure(Y,$)}}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={},Y=new AbortController,X=this.wakeEpoch,Z=this.idleEpoch;if(this.attempt++,this.recoveryStartedAt===null)this.recoveryStartedAt=this.now(),this.installDeadlineTimer($);this.activeAttemptToken=J,this.activeRunController=Y;let Q=await this.options.run(Y.signal);if(this.disposed||$!==this.generation||this.activeAttemptToken!==J)return;if(this.activeAttemptToken=null,this.activeRunController=null,Q.status==="completed"){let G=this.wakeEpoch!==X;if(this.clearEpisode(),G)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!==Z)this.waitingForIdle=!1,this.scheduleIfRunnable();else this.waitingForIdle=!0;return}this.handleFailure(Q,$)}handleFailure($,J){let Y=V2($.taskFailure),X=this.options.sessionIdentity;if($.workKind!=="pending_input"||!$.evidence||!X||!AX($.taskFailure,$.evidence.taskFailure)){this.terminate("failed",this.attempt,Y);return}let Z=b9({sessionIdentity:X,failedAttempt:this.attempt,recoveryStartedAt:this.recoveryStartedAt??this.now(),now:this.now(),workStillPending:$.workStillPending,evidence:$.evidence});if(Z.phase!=="retry_scheduled"){this.terminate(Z.phase,this.attempt,Y);return}this.requested=!0,this.waitingForIdle=!1;let Q={},G=this.setTimerCallback(()=>{if(this.disposed||J!==this.generation||this.retryTimer?.token!==Q)return;this.retryTimer=null,this.scheduleIfRunnable()},Z.delayMs);this.retryTimer={handle:G,token:Q},G.unref?.()}handleUnexpectedFailure($,J){if(this.disposed||J!==this.generation)return;this.terminate("failed",Math.max(1,this.attempt),V2($),"pending-resume-coordinator-failed")}installDeadlineTimer($){let J={},Y=this.setTimerCallback(()=>{if(this.disposed||$!==this.generation||this.deadlineTimer?.token!==J)return;this.deadlineTimer=null,this.terminate("exhausted",Math.max(1,this.attempt),P9("timeout"),"pending-resume-recovery-deadline-exceeded")},A9);this.deadlineTimer={handle:Y,token:J},Y.unref?.()}terminate($,J,Y,X){let Z=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(),X)Z?.abort(X);try{this.options.onTerminalFailure?.({phase:$,attempt:J,taskFailure:Y})}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 J8{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)o8(J,$.extraContent);M9(J)}this.options.finalizeStreamingMessage($.extraContent,$.extraThinking)}}function bX($){if(!($ instanceof Error))return"未知错误";let X=$.lastError??$;if(X.responseBody)try{let G=JSON.parse(X.responseBody)?.error?.message;if(G){let U=X.statusCode?` (HTTP ${X.statusCode})`:"";return`${G}${U}`}}catch{}let Z=$.message.match(/Last error:\s*(.+)$/);if(Z)return Z[1];return $.message}function MX($){if(!($ instanceof Error))return!1;return $.name==="AbortError"||$.message.includes("aborted")}function TX($){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 n8($){let J=MX($),Y=TX($),X;if(Y)X="当前模型不支持图片理解功能。请切换到支持视觉能力的模型(如 Claude 4.5、GPT-5.2、Gemini 3 Pro、Qwen3-VL-Plus 等)后重试。";else X=bX($);return{displayMessage:X,isAbort:J,isVisionNotSupported:Y}}import{appendFileSync as CX,mkdirSync as RX,writeFileSync as yX}from"node:fs";import IX from"node:os";import z6 from"node:path";var T9=null;function SX(){let $=process.env.BLADE_STORAGE_ROOT||z6.join(IX.homedir(),".blade");return z6.join($,"logs","stream-debug.log")}function kX($){if(T9===$)return;let J=z6.dirname($);RX(J,{recursive:!0,mode:493}),yX($,`=== Stream Debug Log Started: ${new Date().toISOString()} ===
1
+ import{e as $5,f as J5,h as S$,i as M4}from"./chunk-zz5n2qxk.js";import{l as $X,m as JX,n as YX}from"./chunk-04t21rey.js";import{A as q4,y as A9,z as b9}from"./chunk-bgzj85za.js";import{Ba as XY,Da as uY,I as cY,M as HX,O as h6,P as C6,Q as vY,W as wY,X as PY,_ as AY,ca as l$,ea as y9,fa as I9,ha as bY,ja as Q8,ka as L5,la as B5,oa as w5,pa as P5,ta as lJ,ua as B3,wa as H3,xa as F3,ya as FX,za as ZY}from"./chunk-1h3736q2.js";import"./chunk-16648v5c.js";import{La as EZ,Ma as hZ,Na as gZ,Qa as WX}from"./chunk-2jq9ed09.js";import{Sa as BY}from"./chunk-5xgyx25z.js";import{Hb as FY,Ib as F4,Ub as LY,bc as P6}from"./chunk-recafw5r.js";import{mc as z8}from"./chunk-3eskgvpy.js";import{Gd as P9,Hd as V2,Ld as C9,Qd as R9,Sd as t8,_d as X8,be as a0,wd as zY}from"./chunk-cefmcwyv.js";import"./chunk-zx78c1an.js";import{Fe as D9,Ge as w6,He as f9}from"./chunk-a5hkv8er.js";import{cf as e9,df as G4}from"./chunk-awheqy52.js";import{qf as s5}from"./chunk-v2fewxvw.js";import{rf as q8,sf as _4,uf as $1}from"./chunk-3ekz3zms.js";import"./chunk-6qhbdcse.js";import{Af as l1,Bf as UJ,Cf as o8,Df as M9,Ef as t3,Ff as RJ,Gf as rZ,Hf as s3,If as k2,Jf as m0,Kf as OX,Lf as L$,Mf as t5,Nf as a4,Of as U8,Rf as s9,Yf as z$,yf as M2,zf as F$}from"./chunk-x3c718v5.js";import"./chunk-v508x7cg.js";import"./chunk-5j68055h.js";import"./chunk-grx6fv9w.js";import"./chunk-bq6d0v5b.js";import{og as yJ}from"./chunk-hrcz179j.js";import"./chunk-d64b7wta.js";import"./chunk-5w8pmsqe.js";import{Bg as H4,Eg as g5,Jg as F5,Sg as NX}from"./chunk-f4cn6v8t.js";import"./chunk-yvmexv2c.js";import"./chunk-rhwkvx96.js";import"./chunk-az08pq83.js";import{ph as qJ,rh as E$}from"./chunk-sdhdn0yx.js";import"./chunk-1bqatrxs.js";import{Ei as qX,Ji as H5,Ki as _X}from"./chunk-40pd090k.js";import{Mi as h9}from"./chunk-npc7jt96.js";import{Ni as j2,Oi as e8,Qi as _J}from"./chunk-mc2mr1kn.js";import{Vi as K$}from"./chunk-dv2m2xe5.js";import"./chunk-fbrdcveb.js";import{sj as zX,vj as _1}from"./chunk-ft1bdqbs.js";import{Dj as tZ,Ej as sZ,Hj as b1}from"./chunk-jb4hmk56.js";import"./chunk-65c3vjwm.js";import{Tj as xZ}from"./chunk-mtfjwsn2.js";import{Wj as uJ}from"./chunk-jy7k2dwm.js";import"./chunk-earhezc8.js";import{Zj as Z8,rk as t9}from"./chunk-t88sfhjj.js";import{Ek as Y4}from"./chunk-516adpx6.js";import{useMemoizedFn as Q6}from"ahooks";import{useEffect as Qz,useState as G6}from"react";import{useMemoizedFn as i0}from"ahooks";import o5 from"ansi-escapes";import{Box as j1,useStdout as sK}from"ink";import{useEffect as e$,useMemo as eK,useRef as C2,useState as n5}from"react";import{useShallow as wX}from"zustand/react/shallow";import{useStore as BX}from"zustand";function q0($){return BX(k2,$)}var PX=[],D2=()=>q0(($)=>$.session.sessionId),q1=()=>q0(($)=>$.session.workspaceRoot),f8=()=>q0(($)=>$.session.messages),rJ=()=>q0(($)=>$.session.clearCount),aJ=()=>q0(($)=>$.session.isCompacting),iJ=()=>q0(($)=>$.session.tokenUsage.estimatedCostUsd),oJ=()=>q0(($)=>{let{totalInputTokens:J,cacheReadTokens:Y,cacheWriteTokens:X}=$.session.tokenUsage;return lJ({totalInputTokens:J,cacheReadTokens:Y,cacheWriteTokens:X}).hitRate});var v8=()=>q0(($)=>$.session.providerRecovery),nJ=()=>q0(($)=>$.session.turnActivity),tJ=()=>q0(($)=>$.session.actionStationarity),p1=()=>q0(($)=>$.session.actions),sJ=()=>q0(($)=>{let{totalTokens:J,maxContextTokens:Y}=$.session.tokenUsage;if(Y<=0)return 100;let X=Math.max(0,100-J/Y*100);return Math.round(X)}),eJ=()=>q0(($)=>$.app.initializationStatus),$9=()=>q0(($)=>$.app.initializationError),V8=()=>q0(($)=>$.app.activeModal),J9=()=>q0(($)=>$.app.tasks),Y9=()=>q0(($)=>$.app.modelEditorTarget),Z9=()=>q0(($)=>$.app.sessionSelectorData),X9=()=>q0(($)=>$.app.sessionHistoryViewerData),Q9=()=>q0(($)=>$.app.taskAttentionStatus),j8=()=>q0(($)=>$.app.taskAttentionUnreadKeys),G9=()=>q0(($)=>$.app.awaitingSecondCtrlC),x1=()=>q0(($)=>$.app.actions),E8=()=>q0(($)=>$.app.sideConversation),U9=()=>q0(($)=>$.app.teams),h8=()=>q0(($)=>$.app.initializationStatus==="ready"),K9=()=>q0(($)=>$.app.tasks.length>0),f2=()=>q0(($)=>$.config.config?.permissionMode||"default"),z9=()=>q0(($)=>$.config.config?.models??PX),g8=()=>q0(($)=>{let J=$.config.config;if(!J)return;let Y=J.currentModelId;return J.models.find((Z)=>Z.id===Y)??J.models[0]}),m8=()=>q0(($)=>$.config.config?.currentModelId),q9=()=>q0(($)=>$.config.config?.agentTeamsEnabled===!0),D0=()=>q0(($)=>{return F$.getTheme()}),_9=()=>q0(($)=>$.config.config?.codeTheme??"default"),X$=()=>q0(($)=>$.focus.currentFocus),O9=()=>q0(($)=>$.focus.actions),v2=()=>q0(($)=>$.command.isProcessing),N9=()=>q0(($)=>$.command.actions),p8=()=>q0(($)=>$.app.followUpQueue),W9=()=>q0(($)=>$.app.followUpQueueMutation),H9=()=>q0(($)=>$.command.recoveredSteeringCount),x8=()=>q0(($)=>$.app.reasoningEffort!=="off"),c8=()=>q0(($)=>$.app.reasoningEffort),u8=()=>q0(($)=>$.app.serviceTier),d8=()=>q0(($)=>$.app.responseVerbosity),l8=()=>q0(($)=>$.app.communicationStyle),r8=()=>q0(($)=>$.session.currentThinkingContent),F9=()=>q0(($)=>$.session.thinkingExpanded),a8=()=>q0(($)=>$.session.currentStreamingMessageId),i8=()=>q0(wX(($)=>({lines:$.session.currentStreamingLines,tail:$.session.currentStreamingTail,lineCount:$.session.currentStreamingLineCount,version:$.session.currentStreamingVersion}))),L9=()=>q0(($)=>$.session.finalizingStreamingMessageId),B9=()=>q0(($)=>$.session.historyExpanded),w9=()=>q0(($)=>$.session.expandedMessageCount);import{randomUUID as O7}from"node:crypto";import{useMemoizedFn as J1}from"ahooks";import{useEffect as u1,useMemo as WY,useRef as N4}from"react";function AX($,J){try{return $.code===J.code&&$.message===J.message&&$.retryable===J.retryable&&$.resource===J.resource}catch{return!1}}class K6{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((Y)=>{this.handleUnexpectedFailure(Y,$)})})}catch(Y){this.handleUnexpectedFailure(Y,$)}}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={},Y=new AbortController,X=this.wakeEpoch,Z=this.idleEpoch;if(this.attempt++,this.recoveryStartedAt===null)this.recoveryStartedAt=this.now(),this.installDeadlineTimer($);this.activeAttemptToken=J,this.activeRunController=Y;let Q=await this.options.run(Y.signal);if(this.disposed||$!==this.generation||this.activeAttemptToken!==J)return;if(this.activeAttemptToken=null,this.activeRunController=null,Q.status==="completed"){let G=this.wakeEpoch!==X;if(this.clearEpisode(),G)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!==Z)this.waitingForIdle=!1,this.scheduleIfRunnable();else this.waitingForIdle=!0;return}this.handleFailure(Q,$)}handleFailure($,J){let Y=V2($.taskFailure),X=this.options.sessionIdentity;if($.workKind!=="pending_input"||!$.evidence||!X||!AX($.taskFailure,$.evidence.taskFailure)){this.terminate("failed",this.attempt,Y);return}let Z=b9({sessionIdentity:X,failedAttempt:this.attempt,recoveryStartedAt:this.recoveryStartedAt??this.now(),now:this.now(),workStillPending:$.workStillPending,evidence:$.evidence});if(Z.phase!=="retry_scheduled"){this.terminate(Z.phase,this.attempt,Y);return}this.requested=!0,this.waitingForIdle=!1;let Q={},G=this.setTimerCallback(()=>{if(this.disposed||J!==this.generation||this.retryTimer?.token!==Q)return;this.retryTimer=null,this.scheduleIfRunnable()},Z.delayMs);this.retryTimer={handle:G,token:Q},G.unref?.()}handleUnexpectedFailure($,J){if(this.disposed||J!==this.generation)return;this.terminate("failed",Math.max(1,this.attempt),V2($),"pending-resume-coordinator-failed")}installDeadlineTimer($){let J={},Y=this.setTimerCallback(()=>{if(this.disposed||$!==this.generation||this.deadlineTimer?.token!==J)return;this.deadlineTimer=null,this.terminate("exhausted",Math.max(1,this.attempt),P9("timeout"),"pending-resume-recovery-deadline-exceeded")},A9);this.deadlineTimer={handle:Y,token:J},Y.unref?.()}terminate($,J,Y,X){let Z=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(),X)Z?.abort(X);try{this.options.onTerminalFailure?.({phase:$,attempt:J,taskFailure:Y})}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 J8{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)o8(J,$.extraContent);M9(J)}this.options.finalizeStreamingMessage($.extraContent,$.extraThinking)}}function bX($){if(!($ instanceof Error))return"未知错误";let X=$.lastError??$;if(X.responseBody)try{let G=JSON.parse(X.responseBody)?.error?.message;if(G){let U=X.statusCode?` (HTTP ${X.statusCode})`:"";return`${G}${U}`}}catch{}let Z=$.message.match(/Last error:\s*(.+)$/);if(Z)return Z[1];return $.message}function MX($){if(!($ instanceof Error))return!1;return $.name==="AbortError"||$.message.includes("aborted")}function TX($){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 n8($){let J=MX($),Y=TX($),X;if(Y)X="当前模型不支持图片理解功能。请切换到支持视觉能力的模型(如 Claude 4.5、GPT-5.2、Gemini 3 Pro、Qwen3-VL-Plus 等)后重试。";else X=bX($);return{displayMessage:X,isAbort:J,isVisionNotSupported:Y}}import{appendFileSync as CX,mkdirSync as RX,writeFileSync as yX}from"node:fs";import IX from"node:os";import z6 from"node:path";var T9=null;function SX(){let $=process.env.BLADE_STORAGE_ROOT||z6.join(IX.homedir(),".blade");return z6.join($,"logs","stream-debug.log")}function kX($){if(T9===$)return;let J=z6.dirname($);RX(J,{recursive:!0,mode:493}),yX($,`=== Stream Debug Log Started: ${new Date().toISOString()} ===
2
2
  `),T9=$}function q6($,J,Y){try{let X=SX();kX(X);let Z=new Date().toISOString(),Q=Y?` | ${JSON.stringify(Y)}`:"",G=`[${Z}] [${$}] ${J}${Q}
3
3
  `;CX(X,G)}catch{}}var Y8=_1("UI");function _6($,J){if(J.state==="requires_attention"){let Y=J.reason==="interrupted_tool_call";$.addToolMessage("Turn recovery requires attention",{toolName:"Runtime Recovery",phase:"complete",summary:Y?"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 S9($,J){let Y=$.streamSession??new J8({signal:$.signal,streamingBuffer:$.streamingBuffer,getStreamingMessageId:$.getStreamingMessageId,finalizeStreamingMessage:$.sessionActions.finalizeStreamingMessage,discardStreamingMessage:$.sessionActions.discardStreamingMessage,clearThinking:()=>$.sessionActions.setCurrentThinkingContent(null)}),X=(Z)=>{for(let Q of Z){if((Q.origin??"user")!=="user")continue;let G=$.commandActions.takeFollowUpPresentation(Q.id);if(G){$.sessionActions.addUserMessage(G.displayText);continue}if(!Q.recovered||Q.persisted)continue;let U=typeof Q.content==="string"?Q.content:Q.content.map((z)=>z.type==="text"?z.text:"[Image]").join(`
4
4
  `);$.sessionActions.addUserMessage(U)}};return(Z)=>{switch(Z.kind){case"content_delta":if(Z.delta.length>0)J.outputStarted=!0;if(!Y.acceptsDeltas())break;J.contentDeltaCount++,J.contentDeltaTotalLen+=Z.delta.length,q6("loopEventHandler","onContentDelta",{callCount:J.contentDeltaCount,deltaLen:Z.delta.length,totalLen:J.contentDeltaTotalLen}),$.streamingBuffer.batchAppendContent(Z.delta);break;case"thinking_delta":if(Z.delta.length>0)J.outputStarted=!0;if(!Y.acceptsDeltas())break;if($.thinkingModeEnabled)$.streamingBuffer.batchAppendThinking(Z.delta);break;case"stream_end":{$.sessionActions.setProviderCircuit(null),$.sessionActions.setProviderRetry(null),$.sessionActions.setProviderStall(null),Y8.debug("[loopEventHandler] stream_end",{contentDeltaCount:J.contentDeltaCount,contentDeltaTotalLen:J.contentDeltaTotalLen,streamFinalized:Y.isFinalized,signalAborted:$.signal.aborted}),q6("loopEventHandler","onStreamEnd",{contentDeltaCallCount:J.contentDeltaCount,contentDeltaTotalLen:J.contentDeltaTotalLen,streamFinalized:Y.isFinalized,signalAborted:$.signal.aborted}),Y.finalize();break}case"model_fallback":$.sessionActions.setProviderAdmission(null),$.sessionActions.setProviderCircuit(null),$.sessionActions.setProviderRetry(null),$.sessionActions.setProviderStall(null),Y.discard();break;case"provider_admission":{let{kind:Q,...G}=Z;$.sessionActions.setProviderAdmission(Z.phase==="queued"?G:null);break}case"provider_circuit":{let{kind:Q,...G}=Z;$.sessionActions.setProviderCircuit(Z.phase==="closed"?null:G);break}case"provider_retry":{let{kind:Q,...G}=Z;$.sessionActions.setProviderRetry(Z.phase==="recovered"?null:G);break}case"provider_stall":{let{kind:Q,...G}=Z;$.sessionActions.setProviderStall(Z.phase==="detected"?G:null);break}case"provider_recovery":$.sessionActions.setProviderRecovery(Z.recovery);break;case"action_stationarity":{let{kind:Q,...G}=Z;$.sessionActions.setActionStationarity(Z.phase==="recovered"?null:G);break}case"turn_recovery":{_6($.sessionActions,Z.assessment);break}case"tool_start":{J.toolExecutionStarted=!0;let Q=Z.toolCall;if(!("function"in Q))break;if(Q.function.name===t8)break;if(Y8.debug("[loopEventHandler] tool_start",{toolName:Q.function.name,toolKind:Z.toolKind}),["TaskCreate","TaskUpdate","TaskList"].includes(Q.function.name))break;try{let G=JSON.parse(Q.function.arguments),U=y9(Q.function.name,G);$.sessionActions.addToolMessage(U,{toolCallId:Q.id,toolName:Q.function.name,phase:"start",summary:U,params:G})}catch(G){Y8.error("[loopEventHandler] onToolStart error:",G)}break}case"tool_progress":{J.toolExecutionStarted=!0;let Q=Z.toolCall;if(!("function"in Q))break;if(Q.function.name===t8)break;let G=Z.update.total!==void 0?` ${Math.max(0,Math.min(100,Math.round((Z.update.progress??0)/Z.update.total*100)))}%`:"",U=`${Q.function.name}${G}: ${Z.update.message}`;$.sessionActions.addToolMessage(U,{toolCallId:Q.id,toolName:Q.function.name,phase:"progress",summary:U,...Z.update.admission?{admission:Z.update.admission}:{}});break}case"tool_result":{J.toolExecutionStarted=!0;let Q=Z.toolCall;if(!("function"in Q))break;if(Q.function.name===t8)break;Y8.debug("[loopEventHandler] tool_result",{toolName:Q.function.name,success:Z.result.success});let G=R9(I9(Q.function.name,Z.result),C9);$.sessionActions.addToolMessage(G.summary,{toolCallId:Q.id,toolName:Q.function.name,phase:"complete",summary:G.summary,detail:G.detail});break}case"structured_output":J.outputStarted=!0,$.sessionActions.replaceLastAssistantMessage(JSON.stringify(Z.output,null,2));break;case"token_usage":$.sessionActions.updateTokenUsage(Z.usage);break;case"compaction":if($.sessionActions.setCompacting(Z.phase==="start"),Z.phase==="end"){if($.sessionActions.resetContextUsage(),Z.outcome!=="failed")J.compactionCount=(J.compactionCount??0)+1}break;case"turn_start":Y8.debug("[loopEventHandler] turn_start",{turn:Z.turn,maxTurns:Z.maxTurns}),$.sessionActions.updateTokenUsage({turnCount:Z.turn}),$.sessionActions.setProviderCircuit(null),$.sessionActions.setProviderRetry(null),$.sessionActions.setProviderStall(null),Y.startTurn();break;case"task_update":$.appActions.setTasks(Z.tasks);break;case"goal_frontier_updated":$.appActions.setTasks(Z.tasks);break;case"mcp_catalog_changed":{let Q=`MCP catalog r${Z.revision}: +${Z.added.length} -${Z.removed.length} ~${Z.updated.length}`;$.sessionActions.addToolMessage(Q,{toolName:"MCP Catalog",phase:"complete",summary:Q,detail:[Z.added.length>0?`Added: ${Z.added.join(", ")}`:"",Z.removed.length>0?`Removed: ${Z.removed.join(", ")}`:"",Z.updated.length>0?`Updated: ${Z.updated.join(", ")}`:""].filter(Boolean).join(`
@@ -120,7 +120,7 @@ ${c0}`}]}}let P0=O6(r),l0=await P(P0);if(!l0.accepted){let c0=l0.reason==="queue
120
120
 
121
121
  **重要**:请直接返回 JSON,不要添加任何额外的解释或文字。`,U)).trim(),I=T.match(/```(?:json)?\s*\n([\s\S]*?)\n```/);if(I)T=I[1];let P=JSON.parse(T);if(!P.name||!P.description||!P.systemPrompt)throw Error("Missing required fields: name, description, or systemPrompt");if(!/^[a-z0-9]+(-[a-z0-9]+)*$/.test(P.name))throw Error("Invalid name format. Must be kebab-case (lowercase, numbers, hyphens only)");G({name:P.name,description:P.description,tools:Array.isArray(P.tools)?P.tools:[],color:P.color||"blue",location:"project",systemPrompt:P.systemPrompt}),Z("confirm")}catch(L){N(L instanceof Error?L.message:String(L))}finally{O(!1)}});_3(()=>{if(X==="aiGenerating"&&!K&&!q)R()},[X,K,q,R]);let F=R4(async()=>{try{let L=Q.location==="project"?V6.join(K$(),".blade","agents"):V6.join(UQ.homedir(),".blade","agents");await q3.promises.mkdir(L,{recursive:!0});let C=["---",`name: ${Q.name}`,`description: ${Q.description}`];if(Q.tools.length>0&&!Q.tools.includes("all")){C.push("tools:");for(let I of Q.tools)C.push(` - ${I}`)}if(Q.color)C.push(`color: ${Q.color}`);C.push("---");let k=[C.join(`
122
122
  `),"",`# ${Q.name} Subagent`,"",Q.systemPrompt||"你是一个专门的代理,负责执行特定任务。",""].join(`
123
- `),T=V6.join(L,`${Q.name}.md`);await q3.promises.writeFile(T,k,"utf-8"),$()}catch(L){console.error("保存配置失败:",L)}}),A=s0(!1,J);if(N0((L,C)=>{if(C.escape)B();else if(C.ctrl&&L==="c"||C.meta&&L==="c")A()},{isActive:X!=="tools"}),X==="mode")return h(b0,{flexDirection:"column",paddingY:1,children:[h(b0,{marginBottom:1,children:h(H0,{bold:!0,color:"cyan",children:"选择创建方式"},void 0,!1,void 0,this)},void 0,!1,void 0,this),h(b0,{marginBottom:1,children:h(H0,{dimColor:!0,children:"你可以手动配置每个细节,或让 AI 根据你的描述自动生成配置"},void 0,!1,void 0,this)},void 0,!1,void 0,this),h(y4,{items:[{label:"AI 智能生成 - 根据描述自动生成完整配置",value:"ai"},{label:"手动配置 - 逐步配置每个选项",value:"manual"}],onSelect:(L)=>{if(L.value==="ai")H("ai"),Z("aiPrompt");else H("manual"),Z("name")}},void 0,!1,void 0,this),h(b0,{marginTop:1,children:h(H0,{dimColor:!0,children:"使用方向键选择 | Enter 确认 | ESC 取消"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this);if(X==="aiPrompt")return h(b0,{flexDirection:"column",paddingY:1,children:[h(b0,{marginBottom:1,children:h(H0,{bold:!0,color:"cyan",children:"AI 智能生成"},void 0,!1,void 0,this)},void 0,!1,void 0,this),h(b0,{marginBottom:1,children:h(H0,{dimColor:!0,children:'描述你想要创建的 Agent(例如:"一个专门用于代码审查的 agent,能够分析代码质量和潜在bug")'},void 0,!1,void 0,this)},void 0,!1,void 0,this),h(b0,{marginBottom:1,children:[h(H0,{color:"green",children:"描述: "},void 0,!1,void 0,this),h(O8,{value:U,onChange:z,onSubmit:(L)=>{if(!L.trim())return;Z("aiGenerating")}},void 0,!1,void 0,this)]},void 0,!0,void 0,this),h(b0,{children:h(H0,{dimColor:!0,children:"按 Enter 开始生成 | ESC 返回"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this);if(X==="aiGenerating"){if(q)return h(b0,{flexDirection:"column",paddingY:1,children:[h(b0,{marginBottom:1,children:h(H0,{bold:!0,color:"red",children:"AI 生成失败"},void 0,!1,void 0,this)},void 0,!1,void 0,this),h(b0,{marginBottom:1,children:h(H0,{color:"red",children:q},void 0,!1,void 0,this)},void 0,!1,void 0,this),h(b0,{marginBottom:1,children:h(H0,{dimColor:!0,children:"按 ESC 返回修改描述"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this);return h(b0,{flexDirection:"column",paddingY:1,children:[h(b0,{marginBottom:1,children:h(H0,{bold:!0,color:"yellow",children:[h(_Q,{type:"dots"},void 0,!1,void 0,this)," AI 正在生成配置..."]},void 0,!0,void 0,this)},void 0,!1,void 0,this),h(b0,{marginBottom:1,children:h(H0,{dimColor:!0,children:['根据你的描述:"',U,'"']},void 0,!0,void 0,this)},void 0,!1,void 0,this),h(b0,{marginBottom:1,children:h(H0,{color:"gray",children:"正在调用 LLM 生成 agent 配置,请稍候..."},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}if(X==="name"){let L=_==="edit";return h(b0,{flexDirection:"column",paddingY:1,children:[h(b0,{marginBottom:1,children:h(H0,{bold:!0,color:"cyan",children:["Step 1/7: ",L?"Agent 名称(不可修改)":"输入 Agent 名称"]},void 0,!0,void 0,this)},void 0,!1,void 0,this),h(b0,{marginBottom:1,children:h(H0,{dimColor:!0,children:L?"编辑模式下名称不可修改(修改名称相当于创建新 Agent)":"名称只能包含小写字母、数字和连字符(例如:code-reviewer)"},void 0,!1,void 0,this)},void 0,!1,void 0,this),h(b0,{marginBottom:1,children:[h(H0,{color:"green",children:"名称: "},void 0,!1,void 0,this),L?h(H0,{children:Q.name},void 0,!1,void 0,this):h(O8,{value:Q.name,onChange:(C)=>G({...Q,name:C}),onSubmit:(C)=>{if(WQ(C))return;w()}},void 0,!1,void 0,this)]},void 0,!0,void 0,this),h(b0,{children:h(H0,{dimColor:!0,children:L?"按 Enter 继续 | ESC 返回":"按 Enter 继续 | ESC 返回"},void 0,!1,void 0,this)},void 0,!1,void 0,this),L&&h(O8,{value:"",onChange:()=>{},onSubmit:w,showCursor:!1},"edit-mode-dummy-input",!1,void 0,this)]},void 0,!0,void 0,this)}if(X==="description")return h(b0,{flexDirection:"column",paddingY:1,children:[h(b0,{marginBottom:1,children:h(H0,{bold:!0,color:"cyan",children:"Step 2/7: 输入描述信息"},void 0,!1,void 0,this)},void 0,!1,void 0,this),h(b0,{marginBottom:1,children:h(H0,{dimColor:!0,children:"简短描述这个 Agent 的用途和使用场景(这将帮助主 Agent 决定何时使用它)"},void 0,!1,void 0,this)},void 0,!1,void 0,this),h(b0,{marginBottom:1,children:[h(H0,{color:"green",children:"描述: "},void 0,!1,void 0,this),h(O8,{value:Q.description,onChange:(L)=>G({...Q,description:L}),onSubmit:(L)=>{if(!L.trim())return;w()}},void 0,!1,void 0,this)]},void 0,!0,void 0,this),h(b0,{children:h(H0,{dimColor:!0,children:"按 Enter 继续 | ESC 返回"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this);if(X==="tools")return h(HQ,{config:Q,setConfig:G,onNext:w,onPrev:B},void 0,!1,void 0,this);if(X==="color")return h(b0,{flexDirection:"column",paddingY:1,children:[h(b0,{marginBottom:1,children:h(H0,{bold:!0,color:"cyan",children:"Step 4/7: 选择背景颜色"},void 0,!1,void 0,this)},void 0,!1,void 0,this),h(b0,{marginBottom:1,children:h(H0,{dimColor:!0,children:"为 Agent 选择一个颜色标识(用于在 UI 中区分不同的 Agents)"},void 0,!1,void 0,this)},void 0,!1,void 0,this),h(y4,{items:NQ,onSelect:(L)=>{let C=L.value==="none"?void 0:L.value;G({...Q,color:C}),w()}},void 0,!1,void 0,this),h(b0,{marginTop:1,children:h(H0,{dimColor:!0,children:"使用方向键选择 | Enter 确认 | ESC 返回"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this);if(X==="location")return h(b0,{flexDirection:"column",paddingY:1,children:[h(b0,{marginBottom:1,children:h(H0,{bold:!0,color:"cyan",children:"Step 5/7: 选择保存位置"},void 0,!1,void 0,this)},void 0,!1,void 0,this),h(b0,{marginBottom:1,children:h(H0,{dimColor:!0,children:"项目级配置仅在当前项目生效,用户级配置全局可用"},void 0,!1,void 0,this)},void 0,!1,void 0,this),h(y4,{items:[{label:"项目级 (.blade/agents/) - 仅当前项目",value:"project"},{label:"用户级 (~/.blade/agents/) - 全局可用",value:"user"}],onSelect:(L)=>{G({...Q,location:L.value}),w()}},void 0,!1,void 0,this),h(b0,{marginTop:1,children:h(H0,{dimColor:!0,children:"使用方向键选择 | Enter 确认 | ESC 返回"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this);if(X==="systemPrompt")return h(b0,{flexDirection:"column",paddingY:1,children:[h(b0,{marginBottom:1,children:h(H0,{bold:!0,color:"cyan",children:"Step 6/7: 输入系统提示词"},void 0,!1,void 0,this)},void 0,!1,void 0,this),h(b0,{marginBottom:1,children:h(H0,{dimColor:!0,children:"定义 Agent 的行为和职责(可选,留空将使用默认提示)"},void 0,!1,void 0,this)},void 0,!1,void 0,this),h(b0,{marginBottom:1,children:[h(H0,{color:"green",children:"提示词: "},void 0,!1,void 0,this),h(O8,{value:Q.systemPrompt,onChange:(L)=>G({...Q,systemPrompt:L}),onSubmit:()=>w()},void 0,!1,void 0,this)]},void 0,!0,void 0,this),h(b0,{children:h(H0,{dimColor:!0,children:"按 Enter 继续 | ESC 返回"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this);if(X==="confirm")return h(b0,{flexDirection:"column",paddingY:1,children:[h(b0,{marginBottom:1,children:h(H0,{bold:!0,color:"cyan",children:"Step 7/7: 确认配置"},void 0,!1,void 0,this)},void 0,!1,void 0,this),h(b0,{flexDirection:"column",paddingLeft:2,marginBottom:1,children:[h(H0,{children:[h(H0,{bold:!0,color:"green",children:["名称:"," "]},void 0,!0,void 0,this),h(H0,{children:Q.name},void 0,!1,void 0,this)]},void 0,!0,void 0,this),h(H0,{children:[h(H0,{bold:!0,color:"green",children:["描述:"," "]},void 0,!0,void 0,this),h(H0,{children:Q.description},void 0,!1,void 0,this)]},void 0,!0,void 0,this),h(H0,{children:[h(H0,{bold:!0,color:"green",children:["工具:"," "]},void 0,!0,void 0,this),h(H0,{children:Q.tools.includes("all")?"所有工具":Q.tools.join(", ")||"所有工具"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),h(H0,{children:[h(H0,{bold:!0,color:"green",children:["颜色:"," "]},void 0,!0,void 0,this),h(H0,{children:Q.color||"默认"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),h(H0,{children:[h(H0,{bold:!0,color:"green",children:["位置:"," "]},void 0,!0,void 0,this),h(H0,{children:Q.location==="project"?"项目级":"用户级"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),h(H0,{children:[h(H0,{bold:!0,color:"green",children:["提示词:"," "]},void 0,!0,void 0,this),h(H0,{children:Q.systemPrompt||"(使用默认)"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),h(y4,{items:[{label:"确认并保存",value:"save"},{label:"返回上一步",value:"back"},{label:"取消",value:"cancel"}],onSelect:(L)=>{if(L.value==="save")F();else if(L.value==="back")B();else J()}},void 0,!1,void 0,this)]},void 0,!0,void 0,this);return null}function HQ({config:$,setConfig:J,onNext:Y,onPrev:X}){let{isFocused:Z}=zQ({id:"step-tools"});N0((G,U)=>{if(U.escape)X()},{isActive:Z});let Q=(G)=>{if(G.includes("all"))J({...$,tools:["all"]});else J({...$,tools:G});Y()};return h(b0,{flexDirection:"column",paddingY:1,children:[h(b0,{marginBottom:1,children:h(H0,{bold:!0,color:"cyan",children:"Step 3/7: 选择可用工具"},void 0,!1,void 0,this)},void 0,!1,void 0,this),h(b0,{marginBottom:1,children:h(H0,{dimColor:!0,children:"方向键导航,空格切换勾选,Enter 确认进入下一步 | ESC 返回上一步"},void 0,!1,void 0,this)},void 0,!1,void 0,this),h(KQ,{options:OQ,defaultValue:$.tools,onSubmit:Q},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}import FQ from"node:fs";import{useMemoizedFn as K2}from"ahooks";import{Box as o0,Text as e0}from"ink";import j6 from"ink-select-input";import{useEffect as LQ,useMemo as O3,useState as I4}from"react";import{jsxDEV as _0}from"react/jsx-dev-runtime";var E6=10;function N3({workspaceRoot:$,initialMode:J="menu",onComplete:Y,onCancel:X}){let Z=H4($),[Q,G]=I4(J),[U,z]=I4(null),[K,O]=I4(0),[q,N]=I4(0),_=K2(()=>{Z.clear(),Z.loadFromStandardLocations(),O((T)=>T+1)}),H=O3(()=>{return Z.getAllSubagents()},[K]),W=Math.ceil(H.length/E6)||1,b=O3(()=>{let T=q*E6;return H.slice(T,T+E6)},[H,q]);LQ(()=>{let T=Math.max(0,W-1);if(q>T)N(T)},[W,q]);let M=K2(()=>{if(q<W-1)N((T)=>T+1)}),w=K2(()=>{if(q>0)N((T)=>T-1)}),B=[{key:"list",label:"查看所有 Agents",value:"list"},{key:"create",label:"创建新 Agent",value:"create"},{key:"edit",label:"编辑 Agent",value:"edit"},{key:"delete",label:"删除 Agent",value:"delete"},{key:"cancel",label:"取消",value:"cancel"}],R=K2((T)=>{if(T.value==="cancel"){X?.();return}G(T.value)}),F=K2((T)=>{if(z(T.value),Q==="edit")G("editWizard");else if(Q==="delete")G("deleteConfirm")}),A=K2(async()=>{if(!U?.configPath)return;try{await FQ.promises.unlink(U.configPath),_(),L()}catch(T){console.error("删除失败:",T)}}),L=K2(()=>{G("menu"),z(null)}),C=s0(!1,X);if(N0((T,I)=>{if(I.escape){if(Q==="menu")X?.();else if(Q==="list"||Q==="edit"||Q==="delete")N(0),L();else if(Q==="deleteConfirm")L()}else if(I.ctrl&&T==="c"||I.meta&&T==="c")C();else if(Q==="list"){if(I.leftArrow||T==="h")w();else if(I.rightArrow||T==="l")M()}},{isActive:Q!=="create"&&Q!=="editWizard"}),Q==="menu")return _0(o0,{flexDirection:"column",paddingY:1,children:[_0(o0,{marginBottom:1,children:_0(e0,{bold:!0,color:"cyan",children:"Agents 管理"},void 0,!1,void 0,this)},void 0,!1,void 0,this),_0(j6,{items:B,onSelect:R},void 0,!1,void 0,this),_0(o0,{marginTop:1,children:_0(e0,{dimColor:!0,children:"使用方向键选择 | Enter 确认 | ESC 退出"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this);if(Q==="list"){if(H.length===0)return _0(o0,{flexDirection:"column",paddingY:1,children:[_0(o0,{marginBottom:1,children:_0(e0,{bold:!0,color:"cyan",children:"所有 Agents"},void 0,!1,void 0,this)},void 0,!1,void 0,this),_0(o0,{paddingLeft:2,children:_0(e0,{color:"gray",children:"没有找到任何 agent 配置"},void 0,!1,void 0,this)},void 0,!1,void 0,this),_0(o0,{marginTop:1,paddingLeft:2,children:_0(e0,{color:"gray",children:"配置文件位置: .blade/agents/ 或 ~/.blade/agents/"},void 0,!1,void 0,this)},void 0,!1,void 0,this),_0(o0,{marginTop:1,paddingLeft:2,children:_0(e0,{dimColor:!0,children:"按 ESC 返回菜单"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this);return _0(o0,{flexDirection:"column",paddingY:1,children:[_0(o0,{marginBottom:1,children:[_0(e0,{bold:!0,color:"cyan",children:"所有 Agents"},void 0,!1,void 0,this),_0(e0,{color:"gray",children:[" (共 ",H.length," 个)"]},void 0,!0,void 0,this),W>1&&_0(e0,{color:"yellow",children:[" ","第 ",q+1,"/",W," 页"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),b.map((T)=>_0(o0,{flexDirection:"column",paddingLeft:2,children:[_0(o0,{children:_0(e0,{children:[_0(e0,{bold:!0,color:T.color||"white",children:["• ",T.name]},void 0,!0,void 0,this),_0(e0,{color:"gray",children:[" - ",T.description]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this),T.tools&&T.tools.length>0&&_0(o0,{paddingLeft:2,children:_0(e0,{color:"gray",children:["工具: ",T.tools.join(", ")]},void 0,!0,void 0,this)},void 0,!1,void 0,this),T.configPath&&_0(o0,{paddingLeft:2,children:_0(e0,{color:"gray",dimColor:!0,children:T.configPath},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},T.name,!0,void 0,this)),_0(o0,{marginTop:1,paddingLeft:2,children:W>1?_0(e0,{dimColor:!0,children:"Left/Right to page | ESC 返回菜单"},void 0,!1,void 0,this):_0(e0,{dimColor:!0,children:"按 ESC 返回菜单"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}let k=(T)=>{if(H.length===0)return _0(o0,{flexDirection:"column",paddingY:1,children:[_0(o0,{marginBottom:1,children:_0(e0,{bold:!0,color:"cyan",children:T},void 0,!1,void 0,this)},void 0,!1,void 0,this),_0(o0,{paddingLeft:2,children:_0(e0,{color:"gray",children:"没有找到任何 agent 配置"},void 0,!1,void 0,this)},void 0,!1,void 0,this),_0(o0,{marginTop:1,paddingLeft:2,children:_0(e0,{dimColor:!0,children:"按 ESC 返回菜单"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this);let I=H.map((P)=>({key:P.name,label:`${P.name} - ${P.description}`,value:P}));return _0(o0,{flexDirection:"column",paddingY:1,children:[_0(o0,{marginBottom:1,children:_0(e0,{bold:!0,color:"cyan",children:T},void 0,!1,void 0,this)},void 0,!1,void 0,this),_0(j6,{items:I,onSelect:F},void 0,!1,void 0,this),_0(o0,{marginTop:1,children:_0(e0,{dimColor:!0,children:"使用方向键选择 | Enter 确认 | ESC 返回"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)};if(Q==="create")return _0(N8,{onComplete:()=>{_(),L()},onCancel:L},void 0,!1,void 0,this);if(Q==="edit")return k("编辑 Agent");if(Q==="editWizard"&&U){let T={name:U.name,description:U.description,tools:U.tools||[],color:U.color,location:U.configPath?.includes(".blade/agents")?"project":"user",systemPrompt:U.systemPrompt||""};return _0(N8,{initialConfig:T,onComplete:()=>{_(),L()},onCancel:L},void 0,!1,void 0,this)}if(Q==="delete")return k("删除 Agent");if(Q==="deleteConfirm"&&U)return _0(o0,{flexDirection:"column",paddingY:1,children:[_0(o0,{marginBottom:1,children:_0(e0,{bold:!0,color:"red",children:"确认删除"},void 0,!1,void 0,this)},void 0,!1,void 0,this),_0(o0,{marginBottom:1,paddingLeft:2,children:_0(e0,{children:["你确定要删除 Agent"," ",_0(e0,{bold:!0,color:"yellow",children:U.name},void 0,!1,void 0,this)," ","吗?"]},void 0,!0,void 0,this)},void 0,!1,void 0,this),_0(o0,{marginBottom:1,paddingLeft:2,children:_0(e0,{dimColor:!0,children:["文件路径: ",U.configPath]},void 0,!0,void 0,this)},void 0,!1,void 0,this),_0(o0,{marginBottom:1,paddingLeft:2,children:_0(e0,{color:"red",children:"此操作无法撤销!"},void 0,!1,void 0,this)},void 0,!1,void 0,this),_0(j6,{items:[{label:"确认删除",value:"confirm"},{label:"取消",value:"cancel"}],onSelect:(T)=>{if(T.value==="confirm")A();else L()}},void 0,!1,void 0,this)]},void 0,!0,void 0,this);return null}import{Box as x2,Text as M0}from"ink";import PQ,{useEffect as AQ,useState as bQ}from"react";import{useEffect as BQ,useState as W3}from"react";function L3($=K$(),J=5000){let[Y,X]=W3(null),[Z,Q]=W3(!0);return BQ(()=>{let G=!0,U=async()=>{try{let K=await H3($);if(!G)return;if(!K){X(null),Q(!1);return}let O=await F3($);if(!G)return;X(O)}catch{if(G)X(null)}finally{if(G)Q(!1)}};U();let z=null;if(J>0)z=setInterval(U,J);return()=>{if(G=!1,z)clearInterval(z)}},[$,J]),{branch:Y,loading:Z}}function z2($){let J=Math.max(0,Math.ceil($/1000)),Y=Math.floor(J/60),X=J%60;return Y>0?`${Y}m ${X}s`:`${X}s`}function wQ($,J=Date.now()){let Y=$.snapshot?.nextActionAt;return Y===void 0?void 0:Math.max(0,Y-J)}function S4($,J=Date.now()){let Y=$?.snapshot;if(!Y)return null;let X=wQ($,J),Z=X===void 0?void 0:z2(X);switch(Y.activity){case"admission_wait":{let Q=Y.admission;return{primary:"等待 Provider 容量",secondary:Q?`队列 ${Q.queuePosition}/${Math.max(Q.queueDepth,Q.queuePosition)} · ${Q.scope} · 已等待 ${z2(Q.waitMs)}`:"等待可用请求容量",compact:Q?`Provider 排队 · ${Q.queuePosition}/${Math.max(Q.queueDepth,Q.queuePosition)}`:"Provider 排队"}}case"retry_wait":{let Q=Y.retry,G=Y.reason==="rate_limit"?`Provider 请求受限${Z?`,${Z} 后重试`:""}`:`Provider 暂时不可用${Z?`,${Z} 后重试`:""}`,U=Q?[`尝试 ${Q.attempt}/${Q.maxRetries}`,Q.recoveryRemainingMs!==void 0?`剩余预算 ${z2(Q.recoveryRemainingMs)}`:void 0].filter((z)=>z!==void 0):[];return{primary:G,secondary:U.join(" · "),compact:`${Y.reason==="rate_limit"?"Provider 限流":"Provider 恢复"}${Z?` · ${Z}`:""}${Q?` · ${Q.attempt}/${Q.maxRetries}`:""}`}}case"retry_attempt":{let Q=Y.retry;return{primary:"正在重试 Provider",secondary:Q?`尝试 ${Q.attempt}/${Q.maxRetries}`:"",compact:`Provider 重试${Q?` · ${Q.attempt}/${Q.maxRetries}`:""}`}}case"circuit_open":return{primary:`Provider 故障已隔离,等待恢复探测${Z?`(${Z})`:""}`,secondary:Y.circuit?.recoveryRemainingMs!==void 0?`剩余预算 ${z2(Y.circuit.recoveryRemainingMs)}`:"",compact:`Provider 熔断${Z?` · ${Z}`:""}`};case"circuit_probe":return{primary:"Provider 正在执行恢复探测",secondary:"",compact:"Provider 恢复探测"};case"stream_stall":{let Q=Y.stall;return{primary:Q?.outputStarted?"Provider 流暂时停滞":"Provider 尚未返回流数据",secondary:Q?`已等待 ${z2(Q.durationMs)} · 超时上限 ${z2(Q.timeoutMs)}`:"",compact:Q?`Provider 等待 · ${z2(Q.durationMs)}`:"Provider 等待"}}case"fallback":{let Q=Y.fallback;return{primary:Q?`正在切换到 ${Q.to.model}`:"正在切换模型",secondary:Q?`候选 ${Q.candidate}/${Q.candidateCount} · 来源 ${Q.from.model}`:"",compact:Q?`Provider 切换 · ${Q.to.model}`:"Provider 切换"}}}}import{jsxDEV as G0,Fragment as h$}from"react/jsx-dev-runtime";var w3=PQ.memo(()=>{let $=h8(),J=f2(),X=V8()==="shortcuts",Z=G9(),Q=q1(),{branch:G}=L3(Q),U=g8(),z=sJ(),K=aJ(),O=x8(),q=c8(),N=u8(),_=d8(),H=l8(),W=iJ(),b=oJ(),M=v8(),w=p8(),B=H9(),R=Q9(),F=j8(),A=D2(),[L,C]=bQ(null),k=S4(M);AQ(()=>{let u=!1;new h6(Q,A).get().then((J0)=>{if(!u)C(J0)}).catch(()=>{if(!u)C(null)});let z0=h6.subscribe((J0)=>{if(!u&&J0.sessionId===A&&J0.workspaceRoot===Q)C(J0.goal)});return()=>{u=!0,z0()}},[A,Q]);let T=U?w4(U):!1,P=(()=>{if(J==="default")return null;if(J==="autoEdit")return G0(M0,{color:"magenta",children:[">> ","auto edit on ",G0(M0,{color:"gray",children:"(shift+tab to cycle)"},void 0,!1,void 0,this)]},void 0,!0,void 0,this);if(J==="plan")return G0(M0,{color:"cyan",children:["‖ plan mode on ",G0(M0,{color:"gray",children:"(shift+tab to cycle)"},void 0,!1,void 0,this)]},void 0,!0,void 0,this);if(J==="yolo")return G0(M0,{color:"red",children:["yolo mode on ",G0(M0,{color:"gray",children:"(all tools auto-approved)"},void 0,!1,void 0,this)]},void 0,!0,void 0,this);return null})(),j=P!==null,o=[["Enter:发送","Shift+Enter:换行","Esc:中止"],["Shift+Tab:切换模式","Up/Down:历史","Tab:补全"],["Ctrl+A:行首","Ctrl+E:行尾","Ctrl+K:删到尾"],["Ctrl+U:删到首","Ctrl+W:删单词","Ctrl+C:退出"],["Ctrl+O:浏览记录","PgUp/PgDn:翻页","g/G:首尾"]];return G0(x2,{flexDirection:"row",justifyContent:"space-between",paddingX:2,paddingY:0,children:[X?G0(x2,{flexDirection:"column",gap:0,children:o.map((u,Z0)=>G0(x2,{flexDirection:"row",children:[u.map((z0,J0)=>{let[f,E]=z0.split(":");return G0(x2,{flexDirection:"row",width:20,children:[G0(M0,{color:"yellow",children:f},void 0,!1,void 0,this),G0(M0,{color:"gray",children:":"},void 0,!1,void 0,this),G0(M0,{color:"white",children:E},void 0,!1,void 0,this)]},J0,!0,void 0,this)}),Z0===o.length-1&&G0(M0,{color:"cyan",children:" ? 关闭"},void 0,!1,void 0,this)]},Z0,!0,void 0,this))},void 0,!1,void 0,this):G0(x2,{flexDirection:"row",gap:1,children:[G&&G0(h$,{children:[G0(M0,{color:"gray",children:[" ",G]},void 0,!0,void 0,this),G0(M0,{color:"gray",children:"·"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),P,j&&G0(M0,{color:"gray",children:"·"},void 0,!1,void 0,this),L&&G0(h$,{children:[G0(M0,{color:L.status==="active"?"green":L.status==="verifying"?"cyan":L.status==="blocked"||L.status==="budget_limited"?"yellow":"gray",children:["goal:",L.status," ",L.objective.slice(0,32),L.prematureStop?` recovery:${L.prematureStop.consecutiveCount}`:"",L.verificationStall?` verify-gap:${L.verificationStall.consecutiveCount}`:"",L.frontierStall?` frontier:${L.frontierStall.category}:${L.frontierStall.consecutiveCount}`:""]},void 0,!0,void 0,this),G0(M0,{color:"gray",children:"·"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),G0(M0,{color:"gray",children:"? for shortcuts"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),G0(x2,{flexDirection:"row",gap:1,children:!$?G0(M0,{color:"red",children:"[WARN] API 密钥未配置"},void 0,!1,void 0,this):G0(h$,{children:[T&&G0(h$,{children:[O?G0(M0,{color:"cyan",children:["Effort ",q]},void 0,!0,void 0,this):G0(M0,{color:"gray",children:"Tab:Effort"},void 0,!1,void 0,this),G0(M0,{color:"gray",children:"·"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),N!=="auto"&&G0(h$,{children:[G0(M0,{color:N==="fast"?"yellow":"gray",children:["Speed ",N]},void 0,!0,void 0,this),G0(M0,{color:"gray",children:"·"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),_!=="auto"&&G0(h$,{children:[G0(M0,{color:"gray",children:["Output ",_]},void 0,!0,void 0,this),G0(M0,{color:"gray",children:"·"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),H!=="auto"&&G0(h$,{children:[G0(M0,{color:"gray",children:["Style ",H]},void 0,!0,void 0,this),G0(M0,{color:"gray",children:"·"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),U&&G0(M0,{color:"gray",children:U.model},void 0,!1,void 0,this),k&&G0(h$,{children:[G0(M0,{color:"gray",children:"·"},void 0,!1,void 0,this),G0(M0,{color:"yellow",children:k.compact},void 0,!1,void 0,this)]},void 0,!0,void 0,this),G0(M0,{color:"gray",children:"·"},void 0,!1,void 0,this),K?G0(M0,{color:"yellow",children:"压缩中..."},void 0,!1,void 0,this):G0(M0,{color:z<20?"red":z<50?"yellow":"gray",children:[z,"%"]},void 0,!0,void 0,this),G0(M0,{color:"gray",children:"·"},void 0,!1,void 0,this),G0(M0,{color:b===void 0?"gray":"cyan",children:["Cache ",B3(b)]},void 0,!0,void 0,this),W>0.001&&G0(h$,{children:[G0(M0,{color:"gray",children:"·"},void 0,!1,void 0,this),G0(M0,{color:"green",children:["$",W<0.01?W.toFixed(4):W.toFixed(3)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),(w?.pending??0)>0&&G0(h$,{children:[G0(M0,{color:"gray",children:"·"},void 0,!1,void 0,this),G0(M0,{color:"yellow",children:["Queued ",w?.pending??0," · /queue"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),B>0&&G0(h$,{children:[G0(M0,{color:"gray",children:"·"},void 0,!1,void 0,this),G0(M0,{color:"cyan",children:["已恢复 ",B," 条指令"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),F.length>0&&G0(h$,{children:[G0(M0,{color:"gray",children:"·"},void 0,!1,void 0,this),G0(M0,{color:"cyan",children:["New tasks ",F.length," · /resume"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),R==="error"&&G0(h$,{children:[G0(M0,{color:"gray",children:"·"},void 0,!1,void 0,this),G0(M0,{color:"yellow",children:"Task sync unavailable"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),Z&&G0(h$,{children:[G0(M0,{color:"gray",children:"·"},void 0,!1,void 0,this),G0(M0,{color:"yellow",children:"再按一次 Ctrl+C 退出"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)});import{Box as g6,Text as m6}from"ink";import MQ from"react";import{jsxDEV as c2}from"react/jsx-dev-runtime";var P3=MQ.memo(({suggestions:$,selectedIndex:J,visible:Y,maxDisplay:X=8})=>{if(!Y||$.length===0)return null;let Z=0,Q=Math.min(X,$.length),G=J>=$.length;if(J>=X&&!G)Z=J-X+1,Q=J+1;let U=$.slice(Z,Q),z=$.length>X;return c2(g6,{flexDirection:"column",paddingX:2,paddingY:0,children:[U.map((K,O)=>{let N=Z+O===J;return c2(g6,{flexDirection:"row",paddingX:1,gap:2,children:[c2(m6,{color:N?"cyan":"white",bold:N,children:K.command},void 0,!1,void 0,this),c2(m6,{color:N?"cyan":"gray",dimColor:!N,children:["- ",K.description]},void 0,!0,void 0,this)]},K.command,!0,void 0,this)}),z&&c2(g6,{paddingX:1,children:c2(m6,{color:G?"cyan":"gray",bold:G,dimColor:!G,children:["... and ",$.length-X," more"]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)});import{Box as o$,Text as O1,useStdout as bG}from"ink";import MG from"ink-select-input";import KJ,{useMemo as e3}from"react";import{Box as I0,Text as u0}from"ink";import _2,{useEffect as GJ,useMemo as q2,useRef as n3}from"react";import{Box as n6,Text as v3}from"ink";import hQ from"react";import{Text as Z1}from"ink";import VQ from"react";import S3 from"string-width";import W8 from"string-width";function p6({onlyFirst:$=!1}={}){return new RegExp("(?:\\u001B\\][\\s\\S]*?(?:\\u0007|\\u001B\\u005C|\\u009C))|[\\u001B\\u009B][[\\]()#;?]*(?:\\d{1,4}(?:[;:]\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]",$?void 0:"g")}var TQ=p6();function x6($){if(typeof $!=="string")throw TypeError(`Expected a \`string\`, got \`${typeof $}\``);if(!$.includes("\x1B")&&!$.includes("›"))return $;return $.replace(TQ,"")}var A3=($=0)=>(J)=>`\x1B[${J+$}m`,b3=($=0)=>(J)=>`\x1B[${38+$};5;${J}m`,M3=($=0)=>(J,Y,X)=>`\x1B[${38+$};2;${J};${Y};${X}m`,Q$={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],gray:[90,39],grey:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgGray:[100,49],bgGrey:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}},NN=Object.keys(Q$.modifier),CQ=Object.keys(Q$.color),RQ=Object.keys(Q$.bgColor),WN=[...CQ,...RQ];function yQ(){let $=new Map;for(let[J,Y]of Object.entries(Q$)){for(let[X,Z]of Object.entries(Y))Q$[X]={open:`\x1B[${Z[0]}m`,close:`\x1B[${Z[1]}m`},Y[X]=Q$[X],$.set(Z[0],Z[1]);Object.defineProperty(Q$,J,{value:Y,enumerable:!1})}return Object.defineProperty(Q$,"codes",{value:$,enumerable:!1}),Q$.color.close="\x1B[39m",Q$.bgColor.close="\x1B[49m",Q$.color.ansi=A3(),Q$.color.ansi256=b3(),Q$.color.ansi16m=M3(),Q$.bgColor.ansi=A3(10),Q$.bgColor.ansi256=b3(10),Q$.bgColor.ansi16m=M3(10),Object.defineProperties(Q$,{rgbToAnsi256:{value(J,Y,X){if(J===Y&&Y===X){if(J<8)return 16;if(J>248)return 231;return Math.round((J-8)/247*24)+232}return 16+36*Math.round(J/255*5)+6*Math.round(Y/255*5)+Math.round(X/255*5)},enumerable:!1},hexToRgb:{value(J){let Y=/[a-f\d]{6}|[a-f\d]{3}/i.exec(J.toString(16));if(!Y)return[0,0,0];let[X]=Y;if(X.length===3)X=[...X].map((Q)=>Q+Q).join("");let Z=Number.parseInt(X,16);return[Z>>16&255,Z>>8&255,Z&255]},enumerable:!1},hexToAnsi256:{value:(J)=>Q$.rgbToAnsi256(...Q$.hexToRgb(J)),enumerable:!1},ansi256ToAnsi:{value(J){if(J<8)return 30+J;if(J<16)return 90+(J-8);let Y,X,Z;if(J>=232)Y=((J-232)*10+8)/255,X=Y,Z=Y;else{J-=16;let U=J%36;Y=Math.floor(J/36)/5,X=Math.floor(U/6)/5,Z=U%6/5}let Q=Math.max(Y,X,Z)*2;if(Q===0)return 30;let G=30+(Math.round(Z)<<2|Math.round(X)<<1|Math.round(Y));if(Q===2)G+=60;return G},enumerable:!1},rgbToAnsi:{value:(J,Y,X)=>Q$.ansi256ToAnsi(Q$.rgbToAnsi256(J,Y,X)),enumerable:!1},hexToAnsi:{value:(J)=>Q$.ansi256ToAnsi(Q$.hexToAnsi256(J)),enumerable:!1}}),Q$}var IQ=yQ(),T3=IQ;var D4=new Set(["\x1B","›"]),SQ=39,u6="\x07",y3="[",kQ="]",I3="m",k4=`${kQ}8;;`,C3=($)=>`${D4.values().next().value}${y3}${$}${I3}`,R3=($)=>`${D4.values().next().value}${k4}${$}${u6}`,DQ=($)=>$.split(" ").map((J)=>W8(J)),c6=($,J,Y)=>{let X=[...J],Z=!1,Q=!1,G=W8(x6($.at(-1)));for(let[U,z]of X.entries()){let K=W8(z);if(G+K<=Y)$[$.length-1]+=z;else $.push(z),G=0;if(D4.has(z))Z=!0,Q=X.slice(U+1,U+1+k4.length).join("")===k4;if(Z){if(Q){if(z===u6)Z=!1,Q=!1}else if(z===I3)Z=!1;continue}if(G+=K,G===Y&&U<X.length-1)$.push(""),G=0}if(!G&&$.at(-1).length>0&&$.length>1)$[$.length-2]+=$.pop()},fQ=($)=>{let J=$.split(" "),Y=J.length;while(Y>0){if(W8(J[Y-1])>0)break;Y--}if(Y===J.length)return $;return J.slice(0,Y).join(" ")+J.slice(Y).join("")},vQ=($,J,Y={})=>{if(Y.trim!==!1&&$.trim()==="")return"";let X="",Z,Q,G=DQ($),U=[""];for(let[q,N]of $.split(" ").entries()){if(Y.trim!==!1)U[U.length-1]=U.at(-1).trimStart();let _=W8(U.at(-1));if(q!==0){if(_>=J&&(Y.wordWrap===!1||Y.trim===!1))U.push(""),_=0;if(_>0||Y.trim===!1)U[U.length-1]+=" ",_++}if(Y.hard&&G[q]>J){let H=J-_,W=1+Math.floor((G[q]-H-1)/J);if(Math.floor((G[q]-1)/J)<W)U.push("");c6(U,N,J);continue}if(_+G[q]>J&&_>0&&G[q]>0){if(Y.wordWrap===!1&&_<J){c6(U,N,J);continue}U.push("")}if(_+G[q]>J&&Y.wordWrap===!1){c6(U,N,J);continue}U[U.length-1]+=N}if(Y.trim!==!1)U=U.map((q)=>fQ(q));let z=U.join(`
123
+ `),T=V6.join(L,`${Q.name}.md`);await q3.promises.writeFile(T,k,"utf-8"),$()}catch(L){console.error("保存配置失败:",L)}}),A=s0(!1,J);if(N0((L,C)=>{if(C.escape)B();else if(C.ctrl&&L==="c"||C.meta&&L==="c")A()},{isActive:X!=="tools"}),X==="mode")return h(b0,{flexDirection:"column",paddingY:1,children:[h(b0,{marginBottom:1,children:h(H0,{bold:!0,color:"cyan",children:"选择创建方式"},void 0,!1,void 0,this)},void 0,!1,void 0,this),h(b0,{marginBottom:1,children:h(H0,{dimColor:!0,children:"你可以手动配置每个细节,或让 AI 根据你的描述自动生成配置"},void 0,!1,void 0,this)},void 0,!1,void 0,this),h(y4,{items:[{label:"AI 智能生成 - 根据描述自动生成完整配置",value:"ai"},{label:"手动配置 - 逐步配置每个选项",value:"manual"}],onSelect:(L)=>{if(L.value==="ai")H("ai"),Z("aiPrompt");else H("manual"),Z("name")}},void 0,!1,void 0,this),h(b0,{marginTop:1,children:h(H0,{dimColor:!0,children:"使用方向键选择 | Enter 确认 | ESC 取消"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this);if(X==="aiPrompt")return h(b0,{flexDirection:"column",paddingY:1,children:[h(b0,{marginBottom:1,children:h(H0,{bold:!0,color:"cyan",children:"AI 智能生成"},void 0,!1,void 0,this)},void 0,!1,void 0,this),h(b0,{marginBottom:1,children:h(H0,{dimColor:!0,children:'描述你想要创建的 Agent(例如:"一个专门用于代码审查的 agent,能够分析代码质量和潜在bug")'},void 0,!1,void 0,this)},void 0,!1,void 0,this),h(b0,{marginBottom:1,children:[h(H0,{color:"green",children:"描述: "},void 0,!1,void 0,this),h(O8,{value:U,onChange:z,onSubmit:(L)=>{if(!L.trim())return;Z("aiGenerating")}},void 0,!1,void 0,this)]},void 0,!0,void 0,this),h(b0,{children:h(H0,{dimColor:!0,children:"按 Enter 开始生成 | ESC 返回"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this);if(X==="aiGenerating"){if(q)return h(b0,{flexDirection:"column",paddingY:1,children:[h(b0,{marginBottom:1,children:h(H0,{bold:!0,color:"red",children:"AI 生成失败"},void 0,!1,void 0,this)},void 0,!1,void 0,this),h(b0,{marginBottom:1,children:h(H0,{color:"red",children:q},void 0,!1,void 0,this)},void 0,!1,void 0,this),h(b0,{marginBottom:1,children:h(H0,{dimColor:!0,children:"按 ESC 返回修改描述"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this);return h(b0,{flexDirection:"column",paddingY:1,children:[h(b0,{marginBottom:1,children:h(H0,{bold:!0,color:"yellow",children:[h(_Q,{type:"dots"},void 0,!1,void 0,this)," AI 正在生成配置..."]},void 0,!0,void 0,this)},void 0,!1,void 0,this),h(b0,{marginBottom:1,children:h(H0,{dimColor:!0,children:['根据你的描述:"',U,'"']},void 0,!0,void 0,this)},void 0,!1,void 0,this),h(b0,{marginBottom:1,children:h(H0,{color:"gray",children:"正在调用 LLM 生成 agent 配置,请稍候..."},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}if(X==="name"){let L=_==="edit";return h(b0,{flexDirection:"column",paddingY:1,children:[h(b0,{marginBottom:1,children:h(H0,{bold:!0,color:"cyan",children:["Step 1/7: ",L?"Agent 名称(不可修改)":"输入 Agent 名称"]},void 0,!0,void 0,this)},void 0,!1,void 0,this),h(b0,{marginBottom:1,children:h(H0,{dimColor:!0,children:L?"编辑模式下名称不可修改(修改名称相当于创建新 Agent)":"名称只能包含小写字母、数字和连字符(例如:code-reviewer)"},void 0,!1,void 0,this)},void 0,!1,void 0,this),h(b0,{marginBottom:1,children:[h(H0,{color:"green",children:"名称: "},void 0,!1,void 0,this),L?h(H0,{children:Q.name},void 0,!1,void 0,this):h(O8,{value:Q.name,onChange:(C)=>G({...Q,name:C}),onSubmit:(C)=>{if(WQ(C))return;w()}},void 0,!1,void 0,this)]},void 0,!0,void 0,this),h(b0,{children:h(H0,{dimColor:!0,children:L?"按 Enter 继续 | ESC 返回":"按 Enter 继续 | ESC 返回"},void 0,!1,void 0,this)},void 0,!1,void 0,this),L&&h(O8,{value:"",onChange:()=>{},onSubmit:w,showCursor:!1},"edit-mode-dummy-input",!1,void 0,this)]},void 0,!0,void 0,this)}if(X==="description")return h(b0,{flexDirection:"column",paddingY:1,children:[h(b0,{marginBottom:1,children:h(H0,{bold:!0,color:"cyan",children:"Step 2/7: 输入描述信息"},void 0,!1,void 0,this)},void 0,!1,void 0,this),h(b0,{marginBottom:1,children:h(H0,{dimColor:!0,children:"简短描述这个 Agent 的用途和使用场景(这将帮助主 Agent 决定何时使用它)"},void 0,!1,void 0,this)},void 0,!1,void 0,this),h(b0,{marginBottom:1,children:[h(H0,{color:"green",children:"描述: "},void 0,!1,void 0,this),h(O8,{value:Q.description,onChange:(L)=>G({...Q,description:L}),onSubmit:(L)=>{if(!L.trim())return;w()}},void 0,!1,void 0,this)]},void 0,!0,void 0,this),h(b0,{children:h(H0,{dimColor:!0,children:"按 Enter 继续 | ESC 返回"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this);if(X==="tools")return h(HQ,{config:Q,setConfig:G,onNext:w,onPrev:B},void 0,!1,void 0,this);if(X==="color")return h(b0,{flexDirection:"column",paddingY:1,children:[h(b0,{marginBottom:1,children:h(H0,{bold:!0,color:"cyan",children:"Step 4/7: 选择背景颜色"},void 0,!1,void 0,this)},void 0,!1,void 0,this),h(b0,{marginBottom:1,children:h(H0,{dimColor:!0,children:"为 Agent 选择一个颜色标识(用于在 UI 中区分不同的 Agents)"},void 0,!1,void 0,this)},void 0,!1,void 0,this),h(y4,{items:NQ,onSelect:(L)=>{let C=L.value==="none"?void 0:L.value;G({...Q,color:C}),w()}},void 0,!1,void 0,this),h(b0,{marginTop:1,children:h(H0,{dimColor:!0,children:"使用方向键选择 | Enter 确认 | ESC 返回"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this);if(X==="location")return h(b0,{flexDirection:"column",paddingY:1,children:[h(b0,{marginBottom:1,children:h(H0,{bold:!0,color:"cyan",children:"Step 5/7: 选择保存位置"},void 0,!1,void 0,this)},void 0,!1,void 0,this),h(b0,{marginBottom:1,children:h(H0,{dimColor:!0,children:"项目级配置仅在当前项目生效,用户级配置全局可用"},void 0,!1,void 0,this)},void 0,!1,void 0,this),h(y4,{items:[{label:"项目级 (.blade/agents/) - 仅当前项目",value:"project"},{label:"用户级 (~/.blade/agents/) - 全局可用",value:"user"}],onSelect:(L)=>{G({...Q,location:L.value}),w()}},void 0,!1,void 0,this),h(b0,{marginTop:1,children:h(H0,{dimColor:!0,children:"使用方向键选择 | Enter 确认 | ESC 返回"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this);if(X==="systemPrompt")return h(b0,{flexDirection:"column",paddingY:1,children:[h(b0,{marginBottom:1,children:h(H0,{bold:!0,color:"cyan",children:"Step 6/7: 输入系统提示词"},void 0,!1,void 0,this)},void 0,!1,void 0,this),h(b0,{marginBottom:1,children:h(H0,{dimColor:!0,children:"定义 Agent 的行为和职责(可选,留空将使用默认提示)"},void 0,!1,void 0,this)},void 0,!1,void 0,this),h(b0,{marginBottom:1,children:[h(H0,{color:"green",children:"提示词: "},void 0,!1,void 0,this),h(O8,{value:Q.systemPrompt,onChange:(L)=>G({...Q,systemPrompt:L}),onSubmit:()=>w()},void 0,!1,void 0,this)]},void 0,!0,void 0,this),h(b0,{children:h(H0,{dimColor:!0,children:"按 Enter 继续 | ESC 返回"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this);if(X==="confirm")return h(b0,{flexDirection:"column",paddingY:1,children:[h(b0,{marginBottom:1,children:h(H0,{bold:!0,color:"cyan",children:"Step 7/7: 确认配置"},void 0,!1,void 0,this)},void 0,!1,void 0,this),h(b0,{flexDirection:"column",paddingLeft:2,marginBottom:1,children:[h(H0,{children:[h(H0,{bold:!0,color:"green",children:["名称:"," "]},void 0,!0,void 0,this),h(H0,{children:Q.name},void 0,!1,void 0,this)]},void 0,!0,void 0,this),h(H0,{children:[h(H0,{bold:!0,color:"green",children:["描述:"," "]},void 0,!0,void 0,this),h(H0,{children:Q.description},void 0,!1,void 0,this)]},void 0,!0,void 0,this),h(H0,{children:[h(H0,{bold:!0,color:"green",children:["工具:"," "]},void 0,!0,void 0,this),h(H0,{children:Q.tools.includes("all")?"所有工具":Q.tools.join(", ")||"所有工具"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),h(H0,{children:[h(H0,{bold:!0,color:"green",children:["颜色:"," "]},void 0,!0,void 0,this),h(H0,{children:Q.color||"默认"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),h(H0,{children:[h(H0,{bold:!0,color:"green",children:["位置:"," "]},void 0,!0,void 0,this),h(H0,{children:Q.location==="project"?"项目级":"用户级"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),h(H0,{children:[h(H0,{bold:!0,color:"green",children:["提示词:"," "]},void 0,!0,void 0,this),h(H0,{children:Q.systemPrompt||"(使用默认)"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),h(y4,{items:[{label:"确认并保存",value:"save"},{label:"返回上一步",value:"back"},{label:"取消",value:"cancel"}],onSelect:(L)=>{if(L.value==="save")F();else if(L.value==="back")B();else J()}},void 0,!1,void 0,this)]},void 0,!0,void 0,this);return null}function HQ({config:$,setConfig:J,onNext:Y,onPrev:X}){let{isFocused:Z}=zQ({id:"step-tools"});N0((G,U)=>{if(U.escape)X()},{isActive:Z});let Q=(G)=>{if(G.includes("all"))J({...$,tools:["all"]});else J({...$,tools:G});Y()};return h(b0,{flexDirection:"column",paddingY:1,children:[h(b0,{marginBottom:1,children:h(H0,{bold:!0,color:"cyan",children:"Step 3/7: 选择可用工具"},void 0,!1,void 0,this)},void 0,!1,void 0,this),h(b0,{marginBottom:1,children:h(H0,{dimColor:!0,children:"方向键导航,空格切换勾选,Enter 确认进入下一步 | ESC 返回上一步"},void 0,!1,void 0,this)},void 0,!1,void 0,this),h(KQ,{options:OQ,defaultValue:$.tools,onSubmit:Q},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}import FQ from"node:fs";import{useMemoizedFn as K2}from"ahooks";import{Box as o0,Text as e0}from"ink";import j6 from"ink-select-input";import{useEffect as LQ,useMemo as O3,useState as I4}from"react";import{jsxDEV as _0}from"react/jsx-dev-runtime";var E6=10;function N3({workspaceRoot:$,initialMode:J="menu",onComplete:Y,onCancel:X}){let Z=H4($),[Q,G]=I4(J),[U,z]=I4(null),[K,O]=I4(0),[q,N]=I4(0),_=K2(()=>{Z.clear(),Z.loadFromStandardLocations(),O((T)=>T+1)}),H=O3(()=>{return Z.getAllSubagents()},[K]),W=Math.ceil(H.length/E6)||1,b=O3(()=>{let T=q*E6;return H.slice(T,T+E6)},[H,q]);LQ(()=>{let T=Math.max(0,W-1);if(q>T)N(T)},[W,q]);let M=K2(()=>{if(q<W-1)N((T)=>T+1)}),w=K2(()=>{if(q>0)N((T)=>T-1)}),B=[{key:"list",label:"查看所有 Agents",value:"list"},{key:"create",label:"创建新 Agent",value:"create"},{key:"edit",label:"编辑 Agent",value:"edit"},{key:"delete",label:"删除 Agent",value:"delete"},{key:"cancel",label:"取消",value:"cancel"}],R=K2((T)=>{if(T.value==="cancel"){X?.();return}G(T.value)}),F=K2((T)=>{if(z(T.value),Q==="edit")G("editWizard");else if(Q==="delete")G("deleteConfirm")}),A=K2(async()=>{if(!U?.configPath)return;try{await FQ.promises.unlink(U.configPath),_(),L()}catch(T){console.error("删除失败:",T)}}),L=K2(()=>{G("menu"),z(null)}),C=s0(!1,X);if(N0((T,I)=>{if(I.escape){if(Q==="menu")X?.();else if(Q==="list"||Q==="edit"||Q==="delete")N(0),L();else if(Q==="deleteConfirm")L()}else if(I.ctrl&&T==="c"||I.meta&&T==="c")C();else if(Q==="list"){if(I.leftArrow||T==="h")w();else if(I.rightArrow||T==="l")M()}},{isActive:Q!=="create"&&Q!=="editWizard"}),Q==="menu")return _0(o0,{flexDirection:"column",paddingY:1,children:[_0(o0,{marginBottom:1,children:_0(e0,{bold:!0,color:"cyan",children:"Agents 管理"},void 0,!1,void 0,this)},void 0,!1,void 0,this),_0(j6,{items:B,onSelect:R},void 0,!1,void 0,this),_0(o0,{marginTop:1,children:_0(e0,{dimColor:!0,children:"使用方向键选择 | Enter 确认 | ESC 退出"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this);if(Q==="list"){if(H.length===0)return _0(o0,{flexDirection:"column",paddingY:1,children:[_0(o0,{marginBottom:1,children:_0(e0,{bold:!0,color:"cyan",children:"所有 Agents"},void 0,!1,void 0,this)},void 0,!1,void 0,this),_0(o0,{paddingLeft:2,children:_0(e0,{color:"gray",children:"没有找到任何 agent 配置"},void 0,!1,void 0,this)},void 0,!1,void 0,this),_0(o0,{marginTop:1,paddingLeft:2,children:_0(e0,{color:"gray",children:"配置文件位置: .blade/agents/ 或 ~/.blade/agents/"},void 0,!1,void 0,this)},void 0,!1,void 0,this),_0(o0,{marginTop:1,paddingLeft:2,children:_0(e0,{dimColor:!0,children:"按 ESC 返回菜单"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this);return _0(o0,{flexDirection:"column",paddingY:1,children:[_0(o0,{marginBottom:1,children:[_0(e0,{bold:!0,color:"cyan",children:"所有 Agents"},void 0,!1,void 0,this),_0(e0,{color:"gray",children:[" (共 ",H.length," 个)"]},void 0,!0,void 0,this),W>1&&_0(e0,{color:"yellow",children:[" ","第 ",q+1,"/",W," 页"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),b.map((T)=>_0(o0,{flexDirection:"column",paddingLeft:2,children:[_0(o0,{children:_0(e0,{children:[_0(e0,{bold:!0,color:T.color||"white",children:["• ",T.name]},void 0,!0,void 0,this),_0(e0,{color:"gray",children:[" - ",T.description]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this),T.tools&&T.tools.length>0&&_0(o0,{paddingLeft:2,children:_0(e0,{color:"gray",children:["工具: ",T.tools.join(", ")]},void 0,!0,void 0,this)},void 0,!1,void 0,this),T.configPath&&_0(o0,{paddingLeft:2,children:_0(e0,{color:"gray",dimColor:!0,children:T.configPath},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},T.name,!0,void 0,this)),_0(o0,{marginTop:1,paddingLeft:2,children:W>1?_0(e0,{dimColor:!0,children:"Left/Right to page | ESC 返回菜单"},void 0,!1,void 0,this):_0(e0,{dimColor:!0,children:"按 ESC 返回菜单"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}let k=(T)=>{if(H.length===0)return _0(o0,{flexDirection:"column",paddingY:1,children:[_0(o0,{marginBottom:1,children:_0(e0,{bold:!0,color:"cyan",children:T},void 0,!1,void 0,this)},void 0,!1,void 0,this),_0(o0,{paddingLeft:2,children:_0(e0,{color:"gray",children:"没有找到任何 agent 配置"},void 0,!1,void 0,this)},void 0,!1,void 0,this),_0(o0,{marginTop:1,paddingLeft:2,children:_0(e0,{dimColor:!0,children:"按 ESC 返回菜单"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this);let I=H.map((P)=>({key:P.name,label:`${P.name} - ${P.description}`,value:P}));return _0(o0,{flexDirection:"column",paddingY:1,children:[_0(o0,{marginBottom:1,children:_0(e0,{bold:!0,color:"cyan",children:T},void 0,!1,void 0,this)},void 0,!1,void 0,this),_0(j6,{items:I,onSelect:F},void 0,!1,void 0,this),_0(o0,{marginTop:1,children:_0(e0,{dimColor:!0,children:"使用方向键选择 | Enter 确认 | ESC 返回"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)};if(Q==="create")return _0(N8,{onComplete:()=>{_(),L()},onCancel:L},void 0,!1,void 0,this);if(Q==="edit")return k("编辑 Agent");if(Q==="editWizard"&&U){let T={name:U.name,description:U.description,tools:U.tools||[],color:U.color,location:U.configPath?.includes(".blade/agents")?"project":"user",systemPrompt:U.systemPrompt||""};return _0(N8,{initialConfig:T,onComplete:()=>{_(),L()},onCancel:L},void 0,!1,void 0,this)}if(Q==="delete")return k("删除 Agent");if(Q==="deleteConfirm"&&U)return _0(o0,{flexDirection:"column",paddingY:1,children:[_0(o0,{marginBottom:1,children:_0(e0,{bold:!0,color:"red",children:"确认删除"},void 0,!1,void 0,this)},void 0,!1,void 0,this),_0(o0,{marginBottom:1,paddingLeft:2,children:_0(e0,{children:["你确定要删除 Agent"," ",_0(e0,{bold:!0,color:"yellow",children:U.name},void 0,!1,void 0,this)," ","吗?"]},void 0,!0,void 0,this)},void 0,!1,void 0,this),_0(o0,{marginBottom:1,paddingLeft:2,children:_0(e0,{dimColor:!0,children:["文件路径: ",U.configPath]},void 0,!0,void 0,this)},void 0,!1,void 0,this),_0(o0,{marginBottom:1,paddingLeft:2,children:_0(e0,{color:"red",children:"此操作无法撤销!"},void 0,!1,void 0,this)},void 0,!1,void 0,this),_0(j6,{items:[{label:"确认删除",value:"confirm"},{label:"取消",value:"cancel"}],onSelect:(T)=>{if(T.value==="confirm")A();else L()}},void 0,!1,void 0,this)]},void 0,!0,void 0,this);return null}import{Box as x2,Text as M0}from"ink";import PQ,{useEffect as AQ,useState as bQ}from"react";import{useEffect as BQ,useState as W3}from"react";function L3($=K$(),J=5000){let[Y,X]=W3(null),[Z,Q]=W3(!0);return BQ(()=>{let G=!0,U=async()=>{try{let K=await H3($);if(!G)return;if(!K){X(null),Q(!1);return}let O=await F3($);if(!G)return;X(O)}catch{if(G)X(null)}finally{if(G)Q(!1)}};U();let z=null;if(J>0)z=setInterval(U,J);return()=>{if(G=!1,z)clearInterval(z)}},[$,J]),{branch:Y,loading:Z}}function z2($){let J=Math.max(0,Math.ceil($/1000)),Y=Math.floor(J/60),X=J%60;return Y>0?`${Y}m ${X}s`:`${X}s`}function wQ($,J=Date.now()){let Y=$.snapshot?.nextActionAt;return Y===void 0?void 0:Math.max(0,Y-J)}function S4($,J=Date.now()){let Y=$?.snapshot;if(!Y)return null;let X=wQ($,J),Z=X===void 0?void 0:z2(X);switch(Y.activity){case"admission_wait":{let Q=Y.admission;return{primary:"等待 Provider 容量",secondary:Q?`队列 ${Q.queuePosition}/${Math.max(Q.queueDepth,Q.queuePosition)} · ${Q.scope} · 已等待 ${z2(Q.waitMs)}`:"等待可用请求容量",compact:Q?`Provider 排队 · ${Q.queuePosition}/${Math.max(Q.queueDepth,Q.queuePosition)}`:"Provider 排队"}}case"retry_wait":{let Q=Y.retry,G=Y.reason==="rate_limit"?`Provider 请求受限${Z?`,${Z} 后重试`:""}`:`Provider 暂时不可用${Z?`,${Z} 后重试`:""}`,U=Q?[`尝试 ${Q.attempt}/${Q.maxRetries}`,Q.recoveryRemainingMs!==void 0?`剩余预算 ${z2(Q.recoveryRemainingMs)}`:void 0].filter((z)=>z!==void 0):[];return{primary:G,secondary:U.join(" · "),compact:`${Y.reason==="rate_limit"?"Provider 限流":"Provider 恢复"}${Z?` · ${Z}`:""}${Q?` · ${Q.attempt}/${Q.maxRetries}`:""}`}}case"retry_attempt":{let Q=Y.retry;return{primary:"正在重试 Provider",secondary:Q?`尝试 ${Q.attempt}/${Q.maxRetries}`:"",compact:`Provider 重试${Q?` · ${Q.attempt}/${Q.maxRetries}`:""}`}}case"circuit_open":return{primary:`${Y.reason==="rate_limit"?"Provider 请求受限":"Provider 故障已隔离"},等待恢复探测${Z?`(${Z})`:""}`,secondary:Y.circuit?.recoveryRemainingMs!==void 0?`剩余预算 ${z2(Y.circuit.recoveryRemainingMs)}`:"",compact:`Provider ${Y.reason==="rate_limit"?"限流":"熔断"}${Z?` · ${Z}`:""}`};case"circuit_probe":return{primary:"Provider 正在执行恢复探测",secondary:"",compact:"Provider 恢复探测"};case"stream_stall":{let Q=Y.stall;return{primary:Q?.outputStarted?"Provider 流暂时停滞":"Provider 尚未返回流数据",secondary:Q?`已等待 ${z2(Q.durationMs)} · 超时上限 ${z2(Q.timeoutMs)}`:"",compact:Q?`Provider 等待 · ${z2(Q.durationMs)}`:"Provider 等待"}}case"fallback":{let Q=Y.fallback;return{primary:Q?`正在切换到 ${Q.to.model}`:"正在切换模型",secondary:Q?`候选 ${Q.candidate}/${Q.candidateCount} · 来源 ${Q.from.model}`:"",compact:Q?`Provider 切换 · ${Q.to.model}`:"Provider 切换"}}}}import{jsxDEV as G0,Fragment as h$}from"react/jsx-dev-runtime";var w3=PQ.memo(()=>{let $=h8(),J=f2(),X=V8()==="shortcuts",Z=G9(),Q=q1(),{branch:G}=L3(Q),U=g8(),z=sJ(),K=aJ(),O=x8(),q=c8(),N=u8(),_=d8(),H=l8(),W=iJ(),b=oJ(),M=v8(),w=p8(),B=H9(),R=Q9(),F=j8(),A=D2(),[L,C]=bQ(null),k=S4(M);AQ(()=>{let u=!1;new h6(Q,A).get().then((J0)=>{if(!u)C(J0)}).catch(()=>{if(!u)C(null)});let z0=h6.subscribe((J0)=>{if(!u&&J0.sessionId===A&&J0.workspaceRoot===Q)C(J0.goal)});return()=>{u=!0,z0()}},[A,Q]);let T=U?w4(U):!1,P=(()=>{if(J==="default")return null;if(J==="autoEdit")return G0(M0,{color:"magenta",children:[">> ","auto edit on ",G0(M0,{color:"gray",children:"(shift+tab to cycle)"},void 0,!1,void 0,this)]},void 0,!0,void 0,this);if(J==="plan")return G0(M0,{color:"cyan",children:["‖ plan mode on ",G0(M0,{color:"gray",children:"(shift+tab to cycle)"},void 0,!1,void 0,this)]},void 0,!0,void 0,this);if(J==="yolo")return G0(M0,{color:"red",children:["yolo mode on ",G0(M0,{color:"gray",children:"(all tools auto-approved)"},void 0,!1,void 0,this)]},void 0,!0,void 0,this);return null})(),j=P!==null,o=[["Enter:发送","Shift+Enter:换行","Esc:中止"],["Shift+Tab:切换模式","Up/Down:历史","Tab:补全"],["Ctrl+A:行首","Ctrl+E:行尾","Ctrl+K:删到尾"],["Ctrl+U:删到首","Ctrl+W:删单词","Ctrl+C:退出"],["Ctrl+O:浏览记录","PgUp/PgDn:翻页","g/G:首尾"]];return G0(x2,{flexDirection:"row",justifyContent:"space-between",paddingX:2,paddingY:0,children:[X?G0(x2,{flexDirection:"column",gap:0,children:o.map((u,Z0)=>G0(x2,{flexDirection:"row",children:[u.map((z0,J0)=>{let[f,E]=z0.split(":");return G0(x2,{flexDirection:"row",width:20,children:[G0(M0,{color:"yellow",children:f},void 0,!1,void 0,this),G0(M0,{color:"gray",children:":"},void 0,!1,void 0,this),G0(M0,{color:"white",children:E},void 0,!1,void 0,this)]},J0,!0,void 0,this)}),Z0===o.length-1&&G0(M0,{color:"cyan",children:" ? 关闭"},void 0,!1,void 0,this)]},Z0,!0,void 0,this))},void 0,!1,void 0,this):G0(x2,{flexDirection:"row",gap:1,children:[G&&G0(h$,{children:[G0(M0,{color:"gray",children:[" ",G]},void 0,!0,void 0,this),G0(M0,{color:"gray",children:"·"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),P,j&&G0(M0,{color:"gray",children:"·"},void 0,!1,void 0,this),L&&G0(h$,{children:[G0(M0,{color:L.status==="active"?"green":L.status==="verifying"?"cyan":L.status==="blocked"||L.status==="budget_limited"?"yellow":"gray",children:["goal:",L.status," ",L.objective.slice(0,32),L.prematureStop?` recovery:${L.prematureStop.consecutiveCount}`:"",L.verificationStall?` verify-gap:${L.verificationStall.consecutiveCount}`:"",L.frontierStall?` frontier:${L.frontierStall.category}:${L.frontierStall.consecutiveCount}`:""]},void 0,!0,void 0,this),G0(M0,{color:"gray",children:"·"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),G0(M0,{color:"gray",children:"? for shortcuts"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),G0(x2,{flexDirection:"row",gap:1,children:!$?G0(M0,{color:"red",children:"[WARN] API 密钥未配置"},void 0,!1,void 0,this):G0(h$,{children:[T&&G0(h$,{children:[O?G0(M0,{color:"cyan",children:["Effort ",q]},void 0,!0,void 0,this):G0(M0,{color:"gray",children:"Tab:Effort"},void 0,!1,void 0,this),G0(M0,{color:"gray",children:"·"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),N!=="auto"&&G0(h$,{children:[G0(M0,{color:N==="fast"?"yellow":"gray",children:["Speed ",N]},void 0,!0,void 0,this),G0(M0,{color:"gray",children:"·"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),_!=="auto"&&G0(h$,{children:[G0(M0,{color:"gray",children:["Output ",_]},void 0,!0,void 0,this),G0(M0,{color:"gray",children:"·"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),H!=="auto"&&G0(h$,{children:[G0(M0,{color:"gray",children:["Style ",H]},void 0,!0,void 0,this),G0(M0,{color:"gray",children:"·"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),U&&G0(M0,{color:"gray",children:U.model},void 0,!1,void 0,this),k&&G0(h$,{children:[G0(M0,{color:"gray",children:"·"},void 0,!1,void 0,this),G0(M0,{color:"yellow",children:k.compact},void 0,!1,void 0,this)]},void 0,!0,void 0,this),G0(M0,{color:"gray",children:"·"},void 0,!1,void 0,this),K?G0(M0,{color:"yellow",children:"压缩中..."},void 0,!1,void 0,this):G0(M0,{color:z<20?"red":z<50?"yellow":"gray",children:[z,"%"]},void 0,!0,void 0,this),G0(M0,{color:"gray",children:"·"},void 0,!1,void 0,this),G0(M0,{color:b===void 0?"gray":"cyan",children:["Cache ",B3(b)]},void 0,!0,void 0,this),W>0.001&&G0(h$,{children:[G0(M0,{color:"gray",children:"·"},void 0,!1,void 0,this),G0(M0,{color:"green",children:["$",W<0.01?W.toFixed(4):W.toFixed(3)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),(w?.pending??0)>0&&G0(h$,{children:[G0(M0,{color:"gray",children:"·"},void 0,!1,void 0,this),G0(M0,{color:"yellow",children:["Queued ",w?.pending??0," · /queue"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),B>0&&G0(h$,{children:[G0(M0,{color:"gray",children:"·"},void 0,!1,void 0,this),G0(M0,{color:"cyan",children:["已恢复 ",B," 条指令"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),F.length>0&&G0(h$,{children:[G0(M0,{color:"gray",children:"·"},void 0,!1,void 0,this),G0(M0,{color:"cyan",children:["New tasks ",F.length," · /resume"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),R==="error"&&G0(h$,{children:[G0(M0,{color:"gray",children:"·"},void 0,!1,void 0,this),G0(M0,{color:"yellow",children:"Task sync unavailable"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),Z&&G0(h$,{children:[G0(M0,{color:"gray",children:"·"},void 0,!1,void 0,this),G0(M0,{color:"yellow",children:"再按一次 Ctrl+C 退出"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)});import{Box as g6,Text as m6}from"ink";import MQ from"react";import{jsxDEV as c2}from"react/jsx-dev-runtime";var P3=MQ.memo(({suggestions:$,selectedIndex:J,visible:Y,maxDisplay:X=8})=>{if(!Y||$.length===0)return null;let Z=0,Q=Math.min(X,$.length),G=J>=$.length;if(J>=X&&!G)Z=J-X+1,Q=J+1;let U=$.slice(Z,Q),z=$.length>X;return c2(g6,{flexDirection:"column",paddingX:2,paddingY:0,children:[U.map((K,O)=>{let N=Z+O===J;return c2(g6,{flexDirection:"row",paddingX:1,gap:2,children:[c2(m6,{color:N?"cyan":"white",bold:N,children:K.command},void 0,!1,void 0,this),c2(m6,{color:N?"cyan":"gray",dimColor:!N,children:["- ",K.description]},void 0,!0,void 0,this)]},K.command,!0,void 0,this)}),z&&c2(g6,{paddingX:1,children:c2(m6,{color:G?"cyan":"gray",bold:G,dimColor:!G,children:["... and ",$.length-X," more"]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)});import{Box as o$,Text as O1,useStdout as bG}from"ink";import MG from"ink-select-input";import KJ,{useMemo as e3}from"react";import{Box as I0,Text as u0}from"ink";import _2,{useEffect as GJ,useMemo as q2,useRef as n3}from"react";import{Box as n6,Text as v3}from"ink";import hQ from"react";import{Text as Z1}from"ink";import VQ from"react";import S3 from"string-width";import W8 from"string-width";function p6({onlyFirst:$=!1}={}){return new RegExp("(?:\\u001B\\][\\s\\S]*?(?:\\u0007|\\u001B\\u005C|\\u009C))|[\\u001B\\u009B][[\\]()#;?]*(?:\\d{1,4}(?:[;:]\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]",$?void 0:"g")}var TQ=p6();function x6($){if(typeof $!=="string")throw TypeError(`Expected a \`string\`, got \`${typeof $}\``);if(!$.includes("\x1B")&&!$.includes("›"))return $;return $.replace(TQ,"")}var A3=($=0)=>(J)=>`\x1B[${J+$}m`,b3=($=0)=>(J)=>`\x1B[${38+$};5;${J}m`,M3=($=0)=>(J,Y,X)=>`\x1B[${38+$};2;${J};${Y};${X}m`,Q$={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],gray:[90,39],grey:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgGray:[100,49],bgGrey:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}},NN=Object.keys(Q$.modifier),CQ=Object.keys(Q$.color),RQ=Object.keys(Q$.bgColor),WN=[...CQ,...RQ];function yQ(){let $=new Map;for(let[J,Y]of Object.entries(Q$)){for(let[X,Z]of Object.entries(Y))Q$[X]={open:`\x1B[${Z[0]}m`,close:`\x1B[${Z[1]}m`},Y[X]=Q$[X],$.set(Z[0],Z[1]);Object.defineProperty(Q$,J,{value:Y,enumerable:!1})}return Object.defineProperty(Q$,"codes",{value:$,enumerable:!1}),Q$.color.close="\x1B[39m",Q$.bgColor.close="\x1B[49m",Q$.color.ansi=A3(),Q$.color.ansi256=b3(),Q$.color.ansi16m=M3(),Q$.bgColor.ansi=A3(10),Q$.bgColor.ansi256=b3(10),Q$.bgColor.ansi16m=M3(10),Object.defineProperties(Q$,{rgbToAnsi256:{value(J,Y,X){if(J===Y&&Y===X){if(J<8)return 16;if(J>248)return 231;return Math.round((J-8)/247*24)+232}return 16+36*Math.round(J/255*5)+6*Math.round(Y/255*5)+Math.round(X/255*5)},enumerable:!1},hexToRgb:{value(J){let Y=/[a-f\d]{6}|[a-f\d]{3}/i.exec(J.toString(16));if(!Y)return[0,0,0];let[X]=Y;if(X.length===3)X=[...X].map((Q)=>Q+Q).join("");let Z=Number.parseInt(X,16);return[Z>>16&255,Z>>8&255,Z&255]},enumerable:!1},hexToAnsi256:{value:(J)=>Q$.rgbToAnsi256(...Q$.hexToRgb(J)),enumerable:!1},ansi256ToAnsi:{value(J){if(J<8)return 30+J;if(J<16)return 90+(J-8);let Y,X,Z;if(J>=232)Y=((J-232)*10+8)/255,X=Y,Z=Y;else{J-=16;let U=J%36;Y=Math.floor(J/36)/5,X=Math.floor(U/6)/5,Z=U%6/5}let Q=Math.max(Y,X,Z)*2;if(Q===0)return 30;let G=30+(Math.round(Z)<<2|Math.round(X)<<1|Math.round(Y));if(Q===2)G+=60;return G},enumerable:!1},rgbToAnsi:{value:(J,Y,X)=>Q$.ansi256ToAnsi(Q$.rgbToAnsi256(J,Y,X)),enumerable:!1},hexToAnsi:{value:(J)=>Q$.ansi256ToAnsi(Q$.hexToAnsi256(J)),enumerable:!1}}),Q$}var IQ=yQ(),T3=IQ;var D4=new Set(["\x1B","›"]),SQ=39,u6="\x07",y3="[",kQ="]",I3="m",k4=`${kQ}8;;`,C3=($)=>`${D4.values().next().value}${y3}${$}${I3}`,R3=($)=>`${D4.values().next().value}${k4}${$}${u6}`,DQ=($)=>$.split(" ").map((J)=>W8(J)),c6=($,J,Y)=>{let X=[...J],Z=!1,Q=!1,G=W8(x6($.at(-1)));for(let[U,z]of X.entries()){let K=W8(z);if(G+K<=Y)$[$.length-1]+=z;else $.push(z),G=0;if(D4.has(z))Z=!0,Q=X.slice(U+1,U+1+k4.length).join("")===k4;if(Z){if(Q){if(z===u6)Z=!1,Q=!1}else if(z===I3)Z=!1;continue}if(G+=K,G===Y&&U<X.length-1)$.push(""),G=0}if(!G&&$.at(-1).length>0&&$.length>1)$[$.length-2]+=$.pop()},fQ=($)=>{let J=$.split(" "),Y=J.length;while(Y>0){if(W8(J[Y-1])>0)break;Y--}if(Y===J.length)return $;return J.slice(0,Y).join(" ")+J.slice(Y).join("")},vQ=($,J,Y={})=>{if(Y.trim!==!1&&$.trim()==="")return"";let X="",Z,Q,G=DQ($),U=[""];for(let[q,N]of $.split(" ").entries()){if(Y.trim!==!1)U[U.length-1]=U.at(-1).trimStart();let _=W8(U.at(-1));if(q!==0){if(_>=J&&(Y.wordWrap===!1||Y.trim===!1))U.push(""),_=0;if(_>0||Y.trim===!1)U[U.length-1]+=" ",_++}if(Y.hard&&G[q]>J){let H=J-_,W=1+Math.floor((G[q]-H-1)/J);if(Math.floor((G[q]-1)/J)<W)U.push("");c6(U,N,J);continue}if(_+G[q]>J&&_>0&&G[q]>0){if(Y.wordWrap===!1&&_<J){c6(U,N,J);continue}U.push("")}if(_+G[q]>J&&Y.wordWrap===!1){c6(U,N,J);continue}U[U.length-1]+=N}if(Y.trim!==!1)U=U.map((q)=>fQ(q));let z=U.join(`
124
124
  `),K=[...z],O=0;for(let[q,N]of K.entries()){if(X+=N,D4.has(N)){let{groups:H}=new RegExp(`(?:\\${y3}(?<code>\\d+)m|\\${k4}(?<uri>.*)${u6})`).exec(z.slice(O))||{groups:{}};if(H.code!==void 0){let W=Number.parseFloat(H.code);Z=W===SQ?void 0:W}else if(H.uri!==void 0)Q=H.uri.length===0?void 0:H.uri}let _=T3.codes.get(Number(Z));if(K[q+1]===`
125
125
  `){if(Q)X+=R3("");if(Z&&_)X+=C3(_)}else if(N===`
126
126
  `){if(Z&&_)X+=C3(Z);if(Q)X+=R3(Q)}O+=N.length}return X};function d6($,J,Y){return String($).normalize().replaceAll(`\r
@@ -1 +1 @@
1
- import{$d as e,Xd as a,Yd as b,Zd as c,_d as d,ae as f,be as g}from"./chunk-nqts5by0.js";import"./chunk-zx78c1an.js";import"./chunk-a5hkv8er.js";import"./chunk-awheqy52.js";import"./chunk-d64b7wta.js";import"./chunk-rhwkvx96.js";import"./chunk-1bqatrxs.js";import"./chunk-mc2mr1kn.js";import"./chunk-dv2m2xe5.js";import"./chunk-ft1bdqbs.js";import"./chunk-65c3vjwm.js";import"./chunk-2t0wp7gm.js";import"./chunk-t88sfhjj.js";import"./chunk-516adpx6.js";export{b as __setSessionSnapshotIOForTesting,c as __resetSessionSnapshotIOForTesting,g as SessionService,d as SessionMissingCreationError,e as SessionArchivedError,f as SessionArchiveConflictError,a as STALE_EMPTY_SESSION_AGE_MS};
1
+ import{$d as e,Xd as a,Yd as b,Zd as c,_d as d,ae as f,be as g}from"./chunk-cefmcwyv.js";import"./chunk-zx78c1an.js";import"./chunk-a5hkv8er.js";import"./chunk-awheqy52.js";import"./chunk-d64b7wta.js";import"./chunk-rhwkvx96.js";import"./chunk-1bqatrxs.js";import"./chunk-mc2mr1kn.js";import"./chunk-dv2m2xe5.js";import"./chunk-ft1bdqbs.js";import"./chunk-65c3vjwm.js";import"./chunk-mtfjwsn2.js";import"./chunk-t88sfhjj.js";import"./chunk-516adpx6.js";export{b as __setSessionSnapshotIOForTesting,c as __resetSessionSnapshotIOForTesting,g as SessionService,d as SessionMissingCreationError,e as SessionArchivedError,f as SessionArchiveConflictError,a as STALE_EMPTY_SESSION_AGE_MS};