blade-code 0.10.24 → 0.10.25

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 (102) hide show
  1. package/dist/blade.js +2 -2
  2. package/dist/chunk-0qayfsc9.js +2 -0
  3. package/dist/{chunk-f8zz4se0.js → chunk-0t0dsepx.js} +1 -1
  4. package/dist/{chunk-nqpcwa0k.js → chunk-10yas08a.js} +5 -4
  5. package/dist/{chunk-bp886b8j.js → chunk-15edqtyv.js} +1 -1
  6. package/dist/chunk-37bxrzq5.js +1 -0
  7. package/dist/chunk-38pr3rjg.js +1 -0
  8. package/dist/chunk-3mgfa96q.js +1 -0
  9. package/dist/chunk-4vwyhhjt.js +6 -0
  10. package/dist/chunk-565weg3f.js +44 -0
  11. package/dist/chunk-584eewzf.js +1 -0
  12. package/dist/chunk-58wxa5cj.js +2 -0
  13. package/dist/{chunk-3fkj59nv.js → chunk-5dr18jzd.js} +1 -1
  14. package/dist/{chunk-m13jrgp9.js → chunk-5k02rk0f.js} +2 -2
  15. package/dist/{chunk-67ekta7b.js → chunk-5tb28pxt.js} +1 -1
  16. package/dist/{chunk-9c3jjbgd.js → chunk-65pe5x3a.js} +1 -1
  17. package/dist/{chunk-pccn8ndq.js → chunk-6vhc5gdf.js} +2 -2
  18. package/dist/{chunk-xzdpdwhz.js → chunk-763aam58.js} +1 -1
  19. package/dist/chunk-7cgbnp1m.js +1 -0
  20. package/dist/{chunk-c674mmtj.js → chunk-7tea6e9y.js} +2 -2
  21. package/dist/{chunk-vns8g2rv.js → chunk-86g3xxx7.js} +1 -1
  22. package/dist/chunk-9e244cxx.js +1 -0
  23. package/dist/chunk-9gtc0kd2.js +2 -0
  24. package/dist/{chunk-1gkpjhts.js → chunk-9tp00s2z.js} +1 -1
  25. package/dist/{chunk-0568ndm9.js → chunk-a0ga35qv.js} +43 -43
  26. package/dist/{chunk-w56y2pvk.js → chunk-awwe1rqb.js} +2 -2
  27. package/dist/chunk-axrwmx6e.js +1 -0
  28. package/dist/{chunk-yaxapgbm.js → chunk-b22x3h7k.js} +1 -1
  29. package/dist/{chunk-zm3zn23k.js → chunk-bt6xqnbx.js} +1 -1
  30. package/dist/chunk-d6qktf17.js +1 -0
  31. package/dist/{chunk-p1dp2xgq.js → chunk-dbb20rxh.js} +1 -1
  32. package/dist/{chunk-bw7vknjr.js → chunk-eeet612j.js} +1 -1
  33. package/dist/chunk-eh8gdgfb.js +1 -0
  34. package/dist/chunk-f769xhg0.js +1 -0
  35. package/dist/{chunk-57q5wn4g.js → chunk-fg1t369y.js} +1 -1
  36. package/dist/chunk-fgy8pbk6.js +1 -0
  37. package/dist/{chunk-my2jwz6y.js → chunk-h61xsxmy.js} +2 -2
  38. package/dist/{chunk-6vfe3409.js → chunk-jx1q1f88.js} +1 -1
  39. package/dist/{chunk-t327cwnb.js → chunk-k89zf5h1.js} +1 -1
  40. package/dist/{chunk-yac1ga9w.js → chunk-kjwc997q.js} +1 -1
  41. package/dist/chunk-kmf716yy.js +1 -0
  42. package/dist/chunk-m3ya6rtr.js +2 -0
  43. package/dist/chunk-mbxffehd.js +1 -0
  44. package/dist/{chunk-d2kzet1k.js → chunk-mmw7jbxg.js} +1 -1
  45. package/dist/chunk-nwg0bpex.js +116 -0
  46. package/dist/{chunk-rtkhyp1g.js → chunk-pserj9y9.js} +1 -1
  47. package/dist/{chunk-x6tns9d8.js → chunk-qdngw7h1.js} +1 -1
  48. package/dist/chunk-qnsj1pp3.js +3 -0
  49. package/dist/{chunk-26zhy301.js → chunk-qvthjzt5.js} +2 -2
  50. package/dist/{chunk-k2b95m2p.js → chunk-qy36y9xc.js} +2 -2
  51. package/dist/{chunk-hpmxmkzc.js → chunk-r561wfcz.js} +1 -1
  52. package/dist/{chunk-wjqctwyr.js → chunk-rb7aayp5.js} +6 -5
  53. package/dist/{chunk-aw8s1sej.js → chunk-rc9rfrws.js} +1 -1
  54. package/dist/chunk-rhcts0qe.js +2 -0
  55. package/dist/{chunk-phzy5kqq.js → chunk-saneyjmy.js} +1 -1
  56. package/dist/chunk-v508x7cg.js +0 -0
  57. package/dist/chunk-vbsk6mjn.js +100 -0
  58. package/dist/{chunk-f4ksxskk.js → chunk-ve4wkta1.js} +1 -1
  59. package/dist/{chunk-s14wmzm3.js → chunk-vjrn667c.js} +2 -2
  60. package/dist/chunk-w0z7cn13.js +1 -0
  61. package/dist/chunk-wbvs2tv5.js +25 -0
  62. package/dist/chunk-whxmvh0n.js +6 -0
  63. package/dist/{chunk-86zsjamb.js → chunk-wyq21fev.js} +2 -2
  64. package/dist/{chunk-j8ggq1z4.js → chunk-xjq1htyt.js} +2 -2
  65. package/dist/web/assets/{ChatView-CCxjYDmJ.js → ChatView-Crna6-ID.js} +2 -2
  66. package/dist/web/assets/{CodeBlockHighlighter-D9MqsrZP.js → CodeBlockHighlighter-coWjWCyT.js} +1 -1
  67. package/dist/web/assets/{FilePreview-Cn5HOlPw.js → FilePreview-BKcCbpvz.js} +2 -2
  68. package/dist/web/assets/{MarkdownRenderer-ALTOCdfi.js → MarkdownRenderer-BqV1nvf1.js} +3 -3
  69. package/dist/web/assets/{SettingsModal-Dk69F1bS.js → SettingsModal-BOMswk9P.js} +2 -2
  70. package/dist/web/assets/{TaskSwitcher-DRZZocE1.js → TaskSwitcher-BEW2DhW3.js} +1 -1
  71. package/dist/web/assets/{TerminalPanel-ByAqKZ47.js → TerminalPanel-BXzypTz6.js} +1 -1
  72. package/dist/web/assets/index-DqXKkjcp.js +11 -0
  73. package/dist/web/index.html +1 -1
  74. package/package.json +2 -1
  75. package/dist/chunk-014rwj5b.js +0 -1
  76. package/dist/chunk-1pkca2km.js +0 -3
  77. package/dist/chunk-2wpnzjme.js +0 -1
  78. package/dist/chunk-3ak60ndt.js +0 -1
  79. package/dist/chunk-3qmwt188.js +0 -100
  80. package/dist/chunk-4a02yjg9.js +0 -2
  81. package/dist/chunk-7dqc10sc.js +0 -1
  82. package/dist/chunk-ag07wwer.js +0 -2
  83. package/dist/chunk-bpz0g8ej.js +0 -2
  84. package/dist/chunk-bvwq5wth.js +0 -6
  85. package/dist/chunk-c29y2s8g.js +0 -2
  86. package/dist/chunk-d70mtcp4.js +0 -1
  87. package/dist/chunk-e71qm105.js +0 -1
  88. package/dist/chunk-edqtngzr.js +0 -44
  89. package/dist/chunk-f0mt91sr.js +0 -1
  90. package/dist/chunk-gwe547ww.js +0 -1
  91. package/dist/chunk-m486vmtn.js +0 -1
  92. package/dist/chunk-n00mknme.js +0 -25
  93. package/dist/chunk-n54tp9wr.js +0 -1
  94. package/dist/chunk-pq7tk058.js +0 -6
  95. package/dist/chunk-q5sewfn5.js +0 -1
  96. package/dist/chunk-qg87zezq.js +0 -1
  97. package/dist/chunk-r14bz8va.js +0 -1
  98. package/dist/chunk-s4mqw4wa.js +0 -116
  99. package/dist/chunk-sgnjekfb.js +0 -1
  100. package/dist/chunk-tetxqw28.js +0 -1
  101. package/dist/chunk-vmzf4nvh.js +0 -2
  102. package/dist/web/assets/index-CRCirUK7.js +0 -11
package/dist/blade.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{Gc as W}from"./chunk-my2jwz6y.js";import{Jc as F,Kc as M}from"./chunk-j8ggq1z4.js";import"./chunk-n00mknme.js";import"./chunk-qg87zezq.js";import"./chunk-xjqcc0nt.js";import"./chunk-86zsjamb.js";import"./chunk-6pb6zs96.js";import{oe as T}from"./chunk-w56y2pvk.js";import"./chunk-edqtngzr.js";import"./chunk-vmzf4nvh.js";import"./chunk-hpmxmkzc.js";import"./chunk-bpz0g8ej.js";import{sf as N,tf as B}from"./chunk-p1dp2xgq.js";import"./chunk-c674mmtj.js";import"./chunk-1gkpjhts.js";import"./chunk-c29y2s8g.js";import"./chunk-pccn8ndq.js";import"./chunk-x6tns9d8.js";import"./chunk-s14wmzm3.js";import{Xf as J}from"./chunk-vns8g2rv.js";import v from"node:path";var E=process.argv.slice(2),I=u(E),p=I!==null;if(I!==null)T.setGlobalDebug(I);function u(Q){for(let Y=0;Y<Q.length;Y+=1){let U=Q[Y];if(U==="--debug"||U==="-d"){let X=Q[Y+1];return X&&!X.startsWith("-")?X:!0}if(U.startsWith("--debug="))return U.slice(8)||!0}return null}function c(Q){return Q.length===1&&(Q[0]==="--version"||Q[0]==="-V")}function q(Q,...Y){return Q.some((U)=>Y.some((X)=>U===X||U.startsWith(`${X}=`)))}function m(Q,...Y){let U=[];for(let X=0;X<Q.length;X+=1){let G=Q[X],z=Y.find(($)=>G.startsWith(`${$}=`));if(z){let $=G.slice(z.length+1);if($)U.push($);continue}if(Y.includes(G)){let $=Q[X+1];if($&&!$.startsWith("-"))U.push($),X+=1}}return U}async function t(){if(c(E)){let{getVersion:K}=await import("./chunk-014rwj5b.js");console.log(K());return}let Q=process.cwd(),Y=F(Q);M(Y),N(B());let U=m(E,"--plugin-dir","--pluginDir");if(U.length>0){let{configureInvocationPluginDirs:K}=await import("./chunk-e71qm105.js");K(U.map((Z)=>v.resolve(Q,Z)))}if(q(E,"--trust-workspace","--trustWorkspace")){let{WorkspaceTrustService:K}=await import("./chunk-m486vmtn.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-pq7tk058.js");if(await K())return}if(W(),q(E,"--print","-p")){let{handlePrintMode:K}=await import("./chunk-f4ksxskk.js");if(await K())return}if(E.includes("--acp")){let{runAcpIntegration:K}=await import("./chunk-6vfe3409.js");await K();return}let[{default:X},{hideBin:G},{cliConfig:z,globalOptions:$},{loadConfiguration:_,validateOutput:D,validatePermissions:R},{doctorCommands:S},{installCommands:k},{mcpCommands:O},{projectsCommands:y},{scheduleCommands:b},{serveCommand:V},{updateCommands:P},{webCommand:x}]=await Promise.all([import("yargs"),import("yargs/helpers"),import("./chunk-gwe547ww.js"),import("./chunk-2wpnzjme.js"),import("./chunk-m13jrgp9.js"),import("./chunk-yac1ga9w.js"),import("./chunk-aw8s1sej.js"),import("./chunk-67ekta7b.js"),import("./chunk-bw7vknjr.js"),import("./chunk-q5sewfn5.js"),import("./chunk-d70mtcp4.js"),import("./chunk-zm3zn23k.js")]),A=X(G(process.argv)).scriptName(z.scriptName).usage(z.usage).version(z.version).locale(z.locale).showHelpOnFail(z.showHelpOnFail).demandCommand(0,"").recommendCommands().strict(z.strict).parserConfiguration({"populate--":!0}).options($).middleware([_,R,D]).command(O).command(y).command(b).command(S).command(P).command(k).command(x).command(V).completion("completion",!1).help("help","Show help").alias("help","h").alias("version","V").fail((K,Z,L)=>{if(Z){if(console.error("An error occurred:"),console.error(Z.message),p&&Z.stack)console.error(`
2
+ import{Hc as W}from"./chunk-h61xsxmy.js";import{Kc as F,Lc as M}from"./chunk-xjq1htyt.js";import"./chunk-wbvs2tv5.js";import"./chunk-v508x7cg.js";import"./chunk-xjqcc0nt.js";import"./chunk-wyq21fev.js";import"./chunk-6pb6zs96.js";import"./chunk-565weg3f.js";import"./chunk-58wxa5cj.js";import"./chunk-r561wfcz.js";import"./chunk-0qayfsc9.js";import{mf as N,nf as B}from"./chunk-dbb20rxh.js";import{qf as T}from"./chunk-awwe1rqb.js";import"./chunk-7tea6e9y.js";import"./chunk-9tp00s2z.js";import"./chunk-9gtc0kd2.js";import"./chunk-6vhc5gdf.js";import"./chunk-qdngw7h1.js";import"./chunk-vjrn667c.js";import{Wf as J}from"./chunk-86g3xxx7.js";import v from"node:path";var E=process.argv.slice(2),I=u(E),p=I!==null;if(I!==null)T.setGlobalDebug(I);function u(Q){for(let Y=0;Y<Q.length;Y+=1){let U=Q[Y];if(U==="--debug"||U==="-d"){let X=Q[Y+1];return X&&!X.startsWith("-")?X:!0}if(U.startsWith("--debug="))return U.slice(8)||!0}return null}function c(Q){return Q.length===1&&(Q[0]==="--version"||Q[0]==="-V")}function q(Q,...Y){return Q.some((U)=>Y.some((X)=>U===X||U.startsWith(`${X}=`)))}function m(Q,...Y){let U=[];for(let X=0;X<Q.length;X+=1){let G=Q[X],z=Y.find(($)=>G.startsWith(`${$}=`));if(z){let $=G.slice(z.length+1);if($)U.push($);continue}if(Y.includes(G)){let $=Q[X+1];if($&&!$.startsWith("-"))U.push($),X+=1}}return U}async function t(){if(c(E)){let{getVersion:K}=await import("./chunk-fgy8pbk6.js");console.log(K());return}let Q=process.cwd(),Y=F(Q);M(Y),N(B());let U=m(E,"--plugin-dir","--pluginDir");if(U.length>0){let{configureInvocationPluginDirs:K}=await import("./chunk-kmf716yy.js");K(U.map((Z)=>v.resolve(Q,Z)))}if(q(E,"--trust-workspace","--trustWorkspace")){let{WorkspaceTrustService:K}=await import("./chunk-37bxrzq5.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-4vwyhhjt.js");if(await K())return}if(W(),q(E,"--print","-p")){let{handlePrintMode:K}=await import("./chunk-ve4wkta1.js");if(await K())return}if(E.includes("--acp")){let{runAcpIntegration:K}=await import("./chunk-jx1q1f88.js");await K();return}let[{default:X},{hideBin:G},{cliConfig:z,globalOptions:$},{loadConfiguration:_,validateOutput:D,validatePermissions:R},{doctorCommands:S},{installCommands:k},{mcpCommands:O},{projectsCommands:y},{scheduleCommands:b},{serveCommand:V},{updateCommands:P},{webCommand:x}]=await Promise.all([import("yargs"),import("yargs/helpers"),import("./chunk-584eewzf.js"),import("./chunk-axrwmx6e.js"),import("./chunk-5k02rk0f.js"),import("./chunk-kjwc997q.js"),import("./chunk-rc9rfrws.js"),import("./chunk-5tb28pxt.js"),import("./chunk-eeet612j.js"),import("./chunk-3mgfa96q.js"),import("./chunk-38pr3rjg.js"),import("./chunk-bt6xqnbx.js")]),A=X(G(process.argv)).scriptName(z.scriptName).usage(z.usage).version(z.version).locale(z.locale).showHelpOnFail(z.showHelpOnFail).demandCommand(0,"").recommendCommands().strict(z.strict).parserConfiguration({"populate--":!0}).options($).middleware([_,R,D]).command(O).command(y).command(b).command(S).command(P).command(k).command(x).command(V).completion("completion",!1).help("help","Show help").alias("help","h").alias("version","V").fail((K,Z,L)=>{if(Z){if(console.error("An error occurred:"),console.error(Z.message),p&&Z.stack)console.error(`
3
3
  Stack trace:`),console.error(Z.stack);else console.error(`
4
4
  Run with --debug to show the stack trace.`);process.exit(1)}if(K)console.error("Error: Invalid arguments:"),console.error(K),console.error(`
5
- Hint: Did you mean:`),L.showHelp(),process.exit(1)}).command("$0",!1,()=>{},async(K)=>{let Z=K._.slice(1),L=Z.length>0?Z.join(" "):void 0,h=import("./chunk-7dqc10sc.js").then(({checkVersionOnStartup:C})=>C()),[{render:w},{createElement:f},{AppWrapper:j}]=await Promise.all([import("ink"),import("react"),import("./chunk-26zhy301.js")]),H={...K,initialMessage:L,debug:K.debug,print:Boolean(K.print),versionCheckPromise:h};delete H._,delete H.$0,delete H.message,w(f(j,H),{patchConsole:!0,exitOnCtrlC:!1,alternateBuffer:!1})});try{await A.parse()}catch(K){console.error("Error: Parse error:",K),process.exit(1)}}if(J.main==J.module)t().catch(console.error);export{t as main};
5
+ Hint: Did you mean:`),L.showHelp(),process.exit(1)}).command("$0",!1,()=>{},async(K)=>{let Z=K._.slice(1),L=Z.length>0?Z.join(" "):void 0,h=import("./chunk-7cgbnp1m.js").then(({checkVersionOnStartup:C})=>C()),[{render:w},{createElement:f},{AppWrapper:j}]=await Promise.all([import("ink"),import("react"),import("./chunk-qvthjzt5.js")]),H={...K,initialMessage:L,debug:K.debug,print:Boolean(K.print),versionCheckPromise:h};delete H._,delete H.$0,delete H.message,w(f(j,H),{patchConsole:!0,exitOnCtrlC:!1,alternateBuffer:!1})});try{await A.parse()}catch(K){console.error("Error: Parse error:",K),process.exit(1)}}if(J.main==J.module)t().catch(console.error);export{t as main};
@@ -0,0 +1,2 @@
1
+ var _=20,T=5242880,A=32000;
2
+ export{_ as hf,T as if,A as jf};
@@ -1,4 +1,4 @@
1
- import{pe as R}from"./chunk-w56y2pvk.js";import{wf as q,yf as _}from"./chunk-c674mmtj.js";import{Bf as K}from"./chunk-1gkpjhts.js";var ie={openrouter:{"HTTP-Referer":"https://github.com/echoVic/blade-code","X-Title":"Blade"},cerebras:{"X-Cerebras-3rd-Party-Integration":"blade"}},N=(e)=>ie[e]||{};var se=new Set(["user-cancel","interrupt","sibling-error","timeout"]);function A(e){return typeof e==="string"&&se.has(e)}function Ne(e){if(!e.aborted)return;if(A(e.reason))return e.reason;return"user-cancel"}function je(e){if(A(e))return!0;if(!(e instanceof Error))return!1;if(e.name==="AbortError")return!0;if(e instanceof DOMException&&e.name==="AbortError")return!0;if(e.message.includes("aborted"))return!0;return!1}function U(...e){let t=e.filter(Boolean);if(t.length===0)return new AbortController().signal;if(t.length===1)return t[0];let o=AbortSignal;if(typeof o.any==="function")return o.any(t);for(let i of t)if(i.aborted)return i;let r=new AbortController,n=new Map;for(let i of t){let a=()=>{r.abort(i.reason);for(let[u,s]of n)u.removeEventListener("abort",s)};n.set(i,a)}for(let[i,a]of n)i.addEventListener("abort",a,{once:!0});return r.signal}function P(e,t,o){let r=o?.throwOnAbort??!1;if(t?.aborted){if(r)return Promise.reject(new DOMException("Aborted","AbortError"));return Promise.resolve()}return new Promise((n,i)=>{let a,u=setTimeout(()=>{if(t&&a)t.removeEventListener("abort",a);n()},e);if(t)a=()=>{if(clearTimeout(u),r)i(new DOMException("Aborted","AbortError"));else n()},t.addEventListener("abort",a,{once:!0})})}var ae=R("Chat"),ue={input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}};function E(e){if(typeof e==="string")return e;return e.filter((t)=>t.type==="text").map((t)=>t.text).join(`
1
+ import{rf as R}from"./chunk-awwe1rqb.js";import{vf as q,xf as _}from"./chunk-7tea6e9y.js";import{Af as K}from"./chunk-9tp00s2z.js";var ie={openrouter:{"HTTP-Referer":"https://github.com/echoVic/blade-code","X-Title":"Blade"},cerebras:{"X-Cerebras-3rd-Party-Integration":"blade"}},N=(e)=>ie[e]||{};var se=new Set(["user-cancel","interrupt","sibling-error","timeout"]);function A(e){return typeof e==="string"&&se.has(e)}function Ne(e){if(!e.aborted)return;if(A(e.reason))return e.reason;return"user-cancel"}function je(e){if(A(e))return!0;if(!(e instanceof Error))return!1;if(e.name==="AbortError")return!0;if(e instanceof DOMException&&e.name==="AbortError")return!0;if(e.message.includes("aborted"))return!0;return!1}function U(...e){let t=e.filter(Boolean);if(t.length===0)return new AbortController().signal;if(t.length===1)return t[0];let o=AbortSignal;if(typeof o.any==="function")return o.any(t);for(let i of t)if(i.aborted)return i;let r=new AbortController,n=new Map;for(let i of t){let a=()=>{r.abort(i.reason);for(let[u,s]of n)u.removeEventListener("abort",s)};n.set(i,a)}for(let[i,a]of n)i.addEventListener("abort",a,{once:!0});return r.signal}function P(e,t,o){let r=o?.throwOnAbort??!1;if(t?.aborted){if(r)return Promise.reject(new DOMException("Aborted","AbortError"));return Promise.resolve()}return new Promise((n,i)=>{let a,u=setTimeout(()=>{if(t&&a)t.removeEventListener("abort",a);n()},e);if(t)a=()=>{if(clearTimeout(u),r)i(new DOMException("Aborted","AbortError"));else n()},t.addEventListener("abort",a,{once:!0})})}var ae=R("Chat"),ue={input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}};function E(e){if(typeof e==="string")return e;return e.filter((t)=>t.type==="text").map((t)=>t.text).join(`
2
2
  `)}function de(e){if(!e)return{};try{let t=JSON.parse(e);return t&&typeof t==="object"&&!Array.isArray(t)?t:{}}catch{return ae.warn("[PiAIChatService] Invalid historical tool arguments",{value:e}),{}}}function ce(e){let t=e.match(/^data:([^;,]+);base64,(.+)$/s);return t?{mimeType:t[1],data:t[2]}:void 0}async function le(e,t){let o=ce(e);if(o)return{type:"image",...o};if(!/^https?:\/\//i.test(e))return{type:"text",text:`[Unsupported image source: ${e}]`};let r=await fetch(e,{signal:t});if(!r.ok)throw Error(`Failed to load image ${e}: HTTP ${r.status}`);return{type:"image",mimeType:r.headers.get("content-type")?.split(";")[0]??"image/png",data:Buffer.from(await r.arrayBuffer()).toString("base64")}}async function j(e,t,o,r,n){let i=e.filter((s)=>s.role==="system").map((s)=>E(s.content)).filter(Boolean).join(`
3
3
 
4
4
  `),a=[];for(let s of e){if(s.role==="system")continue;if(s.role==="user"){let c=t.input.includes("image"),d=typeof s.content==="string"?s.content:await Promise.all(s.content.map((l)=>l.type==="text"?Promise.resolve({type:"text",text:l.text}):c?le(l.image_url.url,r):Promise.resolve({type:"text",text:"[Image omitted: current model does not support image input]"})));a.push({role:"user",content:d,timestamp:Date.now()});continue}if(s.role==="assistant"){let c=[];if(s.reasoningContent?.trim())c.push({type:"thinking",thinking:s.reasoningContent});let d=E(s.content);if(d)c.push({type:"text",text:d});for(let l of s.tool_calls??[]){if(!("function"in l))continue;c.push({type:"toolCall",id:l.id,name:l.function.name,arguments:de(l.function.arguments)})}a.push({role:"assistant",content:c,api:t.api,provider:t.provider,model:t.id,usage:ue,stopReason:s.tool_calls?.length?"toolUse":"stop",timestamp:Date.now()});continue}a.push({role:"toolResult",toolCallId:s.tool_call_id??"",toolName:s.name??"unknown",content:[{type:"text",text:E(s.content)}],isError:!1,timestamp:Date.now()})}let u=o?.filter((s)=>!n||s.name===n).map((s)=>({name:s.name,description:s.description,parameters:s.parameters,constrainedSampling:s.constrainedSampling}));return{...i?{systemPrompt:i}:{},messages:a,...u?.length?{tools:u}:{}}}function B(e){let t=[];for(let o=0;o<e.length;o++){let r=e[o];if(r.role==="tool")continue;let n=r.role==="assistant"&&r.tool_calls?.length?r.tool_calls:void 0;if(!n){t.push(r);continue}let i=[],a=o+1;while(a<e.length&&e[a].role==="tool")i.push(e[a++]);let u=new Set(n.map((d)=>d.id)),s=i.filter((d)=>d.tool_call_id&&u.has(d.tool_call_id)),c=new Set(s.map((d)=>d.tool_call_id));if(u.size===n.length&&s.length===u.size&&c.size===u.size)t.push(r,...s);o=a-1}return t}function F(e){return e.some((t)=>t.role==="assistant"&&Boolean(t.tool_calls?.length)&&!t.reasoningContent?.trim())}function z(e,t){return{...e,...t.baseUrl?{baseUrl:q(e.api,t.baseUrl)}:{},...t.maxOutputTokens?{maxTokens:t.maxOutputTokens}:{}}}function S(e){let t=e.modelCatalog??_();return{models:t.models,model:z(t.getModel(e.provider,e.model),e)}}function V(e,t){let o=e.modelCatalog??_();return z(o.getModel(t.provider,t.model),e)}var Y=new WeakSet,me=["gousagelimiterror","freeusagelimiterror","monthly usage limit reached","available balance","insufficient_quota","out of budget","quota exceeded","billing"],pe=["prompt_too_long","prompt is too long","maximum context length","context length exceeded","context_length_exceeded","request too large"],fe=["econnreset","econnrefused","enotfound","eai_again","etimedout","fetch failed","network error","connection error","connection refused","connection lost","other side closed","socket hang up","socket connection was closed","upstream connect","reset before headers","websocket closed","websocket error","http2 request did not get a response"];function H(e){return(e instanceof Error?e.message:String(e)).toLowerCase()}function he(e){let t=H(e);return pe.some((o)=>t.includes(o))}function X(e){if(e!==null&&typeof e==="object")Y.add(e)}function Xe(e){return e!==null&&typeof e==="object"&&Y.has(e)}function ye(e){return e!==null&&typeof e==="object"&&"code"in e?e.code:void 0}function ge(e){if(e===null||typeof e!=="object")return;let t=e;for(let o of["status","statusCode"]){let r=t[o];if(typeof r==="number"&&Number.isInteger(r))return r}return}function be(e){let t=e.match(/^(?:error:\s*)?(\d{3})\b/),o=e.match(/\b(?:status(?:\s+code)?|http)[:\s]+(\d{3})\b/),r=Number(t?.[1]??o?.[1]);return Number.isInteger(r)?r:void 0}function T(e,t){let o=H(e),r=ye(e);if(r==="STREAM_IDLE_TIMEOUT"||e instanceof Error&&e.name==="AbortError"||o.includes("request aborted")||o==="aborted")return{retryable:!1};if(me.some((i)=>o.includes(i))||he(e))return{retryable:!1};if(t?.shouldRetry==="false")return{retryable:!1,statusCode:t.statusCode};let n=t?.statusCode??ge(e)??be(o);if(t?.shouldRetry==="true")return{retryable:!0,reason:n===429?"rate_limit":n===408||n===409?"timeout":"server_error",statusCode:n};if(n===429)return{retryable:!0,reason:"rate_limit",statusCode:n};if(n===408||n===409)return{retryable:!0,reason:"timeout",statusCode:n};if(n!==void 0&&n>=500&&n<=599)return{retryable:!0,reason:"server_error",statusCode:n};if(r==="PROVIDER_STREAM_CLOSED"||o.includes("stream closed before completion")||o.includes("ended without")||o.includes("stream ended before"))return{retryable:!0,reason:"stream_closed",statusCode:n};if(fe.some((i)=>o.includes(i)))return{retryable:!0,reason:"transport",statusCode:n};if(o.includes("timeout")||o.includes("timed out")||o.includes("temporarily unavailable")||o.includes("upstream_error")||o.includes("overloaded")||o.includes("rate limit")||o.includes("too many requests")||o.includes("service unavailable")||o.includes("server error")||o.includes("internal error")||o.includes("please retry")||o.includes("try your request again"))return{retryable:!0,reason:o.includes("rate")||o.includes("too many")?"rate_limit":o.includes("timeout")||o.includes("timed out")?"timeout":"server_error",statusCode:n};return{retryable:!1,statusCode:n}}function Ce(e,t){if(!e)return;if(e.retryAfterMs!==void 0){let n=Number.parseFloat(e.retryAfterMs);if(Number.isFinite(n))return Math.max(0,n)}if(e.retryAfter===void 0)return;let o=Number.parseFloat(e.retryAfter);if(Number.isFinite(o))return Math.max(0,o*1000);let r=Date.parse(e.retryAfter);return Number.isFinite(r)?Math.max(0,r-t):void 0}function G(e,t,o={}){let r=o.now??Date.now(),n=o.maxDelayMs??60000,i=Ce(t,r);if(i!==void 0)return Math.min(Math.ceil(i),n);let a=Math.max(0,e-1),u=Math.min(500*2**a,8000),s=Math.max(0,Math.min(1,o.random??Math.random())),c=u*(0.75+s*0.25);return Math.min(Math.round(c),n)}function J(e,t){let o=e.onPayload;e.onPayload=async(r,n)=>{let i=o?await o(r,n):r;return t(i===void 0?r:i,n)}}function Me(e){if(!e.reasoningEnabled)return;return e.reasoningEffort??e.reasoningLevel??"high"}function Re(e){switch(e){case"minimal":return"MINIMAL";case"low":return"LOW";case"medium":return"MEDIUM";default:return"HIGH"}}function xe(e,t,o,r){let n=r?void 0:Me(o);if(!n){if(t.api==="anthropic-messages")e.thinkingEnabled=!1;if(t.api==="google-generative-ai"||t.api==="google-vertex")e.thinking={enabled:!1};return}switch(t.api){case"anthropic-messages":e.thinkingEnabled=!0,e.effort=n;break;case"google-generative-ai":case"google-vertex":e.thinking={enabled:!0,level:Re(n)};break;case"mistral-conversations":e.reasoningEffort="high";break;case"bedrock-converse-stream":case"pi-messages":e.reasoning=n;break;default:e.reasoningEffort=n}}function ve(e,t,o){if(!o)return;switch(t){case"anthropic-messages":case"bedrock-converse-stream":e.toolChoice={type:"tool",name:o};break;case"openai-completions":case"mistral-conversations":case"pi-messages":e.toolChoice={type:"function",function:{name:o}};break;case"openai-responses":case"openai-codex-responses":case"azure-openai-responses":e.toolChoice={type:"function",name:o};break;case"google-generative-ai":case"google-vertex":e.toolChoice="any";break}}function Te(e,t,o){let r=o.serviceTier;if(!r)return;if(t.api==="openai-responses"||t.api==="openai-codex-responses"||t.api==="azure-openai-responses"){e.serviceTier=r;return}if(t.api!=="openai-completions"&&!(t.api==="anthropic-messages"&&r==="fast"))return;J(e,(n)=>{if(!n||typeof n!=="object"||Array.isArray(n))return n;return t.api==="anthropic-messages"?{...n,speed:"fast"}:{...n,service_tier:r}})}function ke(e,t,o){let r=o.responseVerbosity;if(!r)return;if(K(t,r),t.api==="openai-codex-responses"){e.textVerbosity=r;return}J(e,(n)=>{if(!n||typeof n!=="object"||Array.isArray(n))return n;if(t.api==="openai-completions")return{...n,verbosity:r};let i="text"in n&&n.text&&typeof n.text==="object"&&!Array.isArray(n.text)?n.text:{};return{...n,text:{...i,verbosity:r}}})}function Z(e,t,o,r,n=!1){let i={apiKey:e.apiKey,headers:e.customHeaders,signal:o,temperature:r?.temperature??e.temperature??0,maxTokens:r?.maxOutputTokens??e.maxOutputTokens,timeoutMs:e.timeout,maxRetries:0,cacheRetention:e.enablePromptCaching?"short":"none"};if(xe(i,t,e,n),ve(i,t.api,r?.toolChoice?.toolName),Te(i,t,e),ke(i,t,e),t.api==="azure-openai-responses")i.azureBaseUrl=e.baseUrl,i.azureApiVersion=e.apiVersion,i.azureDeploymentName=t.id;return i}function $(e,t){let o=t.get("x-should-retry");return{statusCode:e,...t.get("retry-after")!==null?{retryAfter:t.get("retry-after")??void 0}:{},...t.get("retry-after-ms")!==null?{retryAfterMs:t.get("retry-after-ms")??void 0}:{},...o==="true"||o==="false"?{shouldRetry:o}:{}}}var we=new Set(["anthropic-messages","openai-completions","openai-responses","openai-codex-responses","azure-openai-responses","pi-messages"]);function Q(e,t,o){let r=e.onResponse;if(e.onResponse=async(i,a)=>{let u=new Headers(i.headers);o($(i.status,u)),await r?.(i,a)},!we.has(t.api)||typeof globalThis.fetch!=="function")return;let n=typeof e.fetch==="function"?e.fetch:globalThis.fetch.bind(globalThis);e.fetch=async(i,a)=>{let u=await n(i,a);return o($(u.status,u.headers)),u}}function ee(e){return{promptTokens:e.input+e.cacheRead+e.cacheWrite,completionTokens:e.output,totalTokens:e.totalTokens,costUsd:e.cost.total,...e.reasoning!==void 0?{reasoningTokens:e.reasoning}:{},...e.cacheWrite>0?{cacheCreationInputTokens:e.cacheWrite}:{},...e.cacheRead>0?{cacheReadInputTokens:e.cacheRead}:{}}}var O=300000,Ae=30000;class te extends Error{timeoutMs;code="STREAM_IDLE_TIMEOUT";constructor(e){super(`Provider stream idle timeout after ${e}ms without an event`);this.timeoutMs=e;this.name="StreamIdleTimeoutError"}}class oe extends Error{code="PROVIDER_STREAM_CLOSED";constructor(){super("Provider stream closed before completion");this.name="ProviderStreamClosedError"}}function I(e){return e.reason instanceof Error?e.reason:new DOMException("Aborted","AbortError")}function Pe(e){return e.idleTimeoutMs&&e.idleTimeoutMs>0?e.idleTimeoutMs:O}function Ee(e,t){if(t===0)return;let o=t!==void 0&&t>0?t:Ae;return Math.max(1,Math.min(o,Math.floor(e/2)))}function _e(e,t,o){if(o?.aborted)return Promise.reject(I(o));return new Promise((r,n)=>{let i=!1,a=()=>{clearTimeout(d),o?.removeEventListener("abort",c)},u=(l)=>{if(i)return;i=!0,a(),r(l)},s=(l)=>{if(i)return;i=!0,a(),n(l instanceof Error?l:Error(String(l)))},c=()=>{if(o)s(I(o))},d=setTimeout(()=>u({kind:"timer"}),Math.max(0,t));if(o?.addEventListener("abort",c,{once:!0}),o?.aborted){c();return}e.then((l)=>u({kind:"next",result:l}),s)})}async function*Se(e,t,o){let r=Pe(t),n=Ee(r,t.stallWarningMs);if(t.signal?.aborted)throw I(t.signal);let i=Date.now(),a=Promise.resolve().then(()=>e.next()),u;for(;;){let c=await _e(a,(u?r:n??r)-(Date.now()-i),t.signal);if(c.kind==="next"){if(u)yield{...u,phase:"recovered",durationMs:Math.max(u.durationMs,Date.now()-i)};return c.result}if(!u&&n!==void 0){o.stallCount++,u={phase:"detected",stallCount:o.stallCount,durationMs:n,warningAfterMs:n,timeoutMs:r,outputStarted:o.outputStarted},yield u;continue}let d=new te(r);throw t.abort?.(d),d}}async function*ne(e,t,o,r,n={}){let a=e.stream(t,o,r)[Symbol.asyncIterator](),u=0,s=!1,c={stallCount:0,outputStarted:!1};try{while(!0){let d=Se(a,n,c),l=await d.next();while(!l.done)yield{providerStall:l.value},l=await d.next();let x=l.value;if(x.done)throw new oe;let f=x.value;switch(f.type){case"text_delta":c.outputStarted=!0,yield{content:f.delta};break;case"thinking_delta":c.outputStarted=!0,yield{reasoningContent:f.delta};break;case"toolcall_end":c.outputStarted=!0,yield{toolCalls:[{index:u++,id:f.toolCall.id,type:"function",function:{name:f.toolCall.name,arguments:JSON.stringify(f.toolCall.arguments)}}]};break;case"done":s=!0,yield{finishReason:f.reason,usage:ee(f.message.usage)};return;case"error":throw Error(f.error.errorMessage??`Request ${f.reason==="aborted"?"aborted":"failed"}`)}}}finally{if(!s)Promise.resolve(a.return?.()).catch(()=>{return})}}var re=R("Chat");function Ie(e){return Boolean(e&&e.role==="user"&&Array.isArray(e.content)&&e.content.some((t)=>t.type==="image_url"))}class D{config;models;model;constructor(e){let t=S(e);this.config={...e,maxContextTokens:t.model.contextWindow,maxOutputTokens:e.maxOutputTokens??t.model.maxTokens},this.models=t.models,this.model=t.model,re.debug("[PiAIChatService] Initialized",{provider:this.model.provider,model:this.model.id,api:this.model.api})}async chat(e,t,o,r){let n="",i="",a=[],u,s;for await(let c of this.streamChat(e,t,o,r)){n+=c.content??"",i+=c.reasoningContent??"";for(let d of c.toolCalls??[])if(d.id&&d.type==="function"&&d.function?.name)a.push(d);u=c.usage??u,s=c.finishReason??s}return{content:n,...i?{reasoningContent:i}:{},...a.length>0?{toolCalls:a}:{},usage:u,finishReason:s}}async*streamChat(e,t,o,r){let n=r?.toolChoice?.toolName;if(n&&!t?.some((m)=>m.name===n))throw Error(`Required tool is unavailable: ${n}`);let i=B(e);if(i.some((m)=>Ie(m))&&!this.model.input.includes("image"))throw Error(`${this.model.name} does not support image input`);let a=Boolean(n)||F(i),u=await j(i,this.model,t,o,n),s,c=(m)=>{s=void 0;let C=new AbortController,h=o?U(o,C.signal):C.signal,M=Z(this.config,m,h,r,a);return Q(M,m,(y)=>{s=y}),ne(this.models,m,u,M,{idleTimeoutMs:this.config.streamIdleTimeout??O,signal:h,abort:(y)=>C.abort(y)})},d=this.config.maxRetries??2,l=this,x=async function*(m,C){let h,M=!1,y,v;for(let g=0;g<=d;g++)try{let b=!1;for await(let p of c(m)){if(p.providerStall){yield p;continue}if(g>0&&y&&!b)b=!0,yield{providerRetry:{phase:"recovered",attempt:g,maxRetries:d,reason:y,...v!==void 0?{statusCode:v}:{}}};M=!0,C(),yield p}return}catch(b){h=b,l.logIdleTimeout(b,M,m),await l.handleAbort(o);let p=T(b,s);if(M)throw X(b),b;if(!p.retryable||!p.reason){if(g>0&&y)yield{providerRetry:{phase:"exhausted",attempt:g,maxRetries:d,reason:y,...v!==void 0?{statusCode:v}:{}}};throw b}if(y=p.reason,v=p.statusCode,g<d){let k=g+1,w=G(k,s);yield{providerRetry:{phase:"scheduled",attempt:k,maxRetries:d,reason:p.reason,...p.statusCode!==void 0?{statusCode:p.statusCode}:{},delayMs:w,nextRetryAt:Date.now()+w}},await P(w,o,{throwOnAbort:!0}),yield{providerRetry:{phase:"attempt",attempt:k,maxRetries:d,reason:p.reason,...p.statusCode!==void 0?{statusCode:p.statusCode}:{}}}}else yield{providerRetry:{phase:"exhausted",attempt:g,maxRetries:d,reason:p.reason,...p.statusCode!==void 0?{statusCode:p.statusCode}:{}}}}throw h},f,L=!1;try{for await(let m of x(this.model,()=>{L=!0}))yield m;return}catch(m){if(f=m,L||!T(m,s).retryable)throw m}for(let m of this.config.fallbackModels??[]){yield{modelFallback:!0};let C=!1;try{let h=V(this.config,m);for await(let M of x(h,()=>{C=!0}))yield M;return}catch(h){if(f=h,C||!T(h,s).retryable)throw h}}throw f}async handleAbort(e){if(e?.aborted)await P(0,e,{throwOnAbort:!0})}logIdleTimeout(e,t,o){if(e===null||typeof e!=="object"||!("code"in e)||e.code!=="STREAM_IDLE_TIMEOUT"||!("timeoutMs"in e)||typeof e.timeoutMs!=="number")return;re.warn("[PiAIChatService] Provider stream idle timeout",{provider:o.provider,model:o.id,timeoutMs:e.timeoutMs,replayBoundaryCrossed:t})}getConfig(){return{...this.config}}updateConfig(e){let t={...this.config,...e},o=S(t);this.config={...t,maxContextTokens:o.model.contextWindow,maxOutputTokens:t.maxOutputTokens??o.model.maxTokens},this.models=o.models,this.model=o.model}}var Oe=R("Service");async function mt(e){let t=e;if(t.provider){let o=N(t.provider);if(Object.keys(o).length>0)t={...t,customHeaders:{...o,...t.customHeaders}},Oe.debug(`Injected ${t.provider} specific headers:`,Object.keys(o))}return De(t)}function De(e){return new D(e)}
@@ -1,4 +1,4 @@
1
- import{ca as j,da as d0,ia as xJ,ja as y8,ka as I0}from"./chunk-yaxapgbm.js";import{Ea as A7,la as b7,na as L7,oa as G4}from"./chunk-3fkj59nv.js";import{$a as s0,Fa as z$,Ga as z2,Ha as b8,Ia as F1,Ja as V9,Ma as O0,Oa as L2,Pa as A8,Qa as N8,Ra as T8,Ua as P2,Wa as D6,Xa as k2,Ya as I2,fb as a2,gb as jJ,hb as t9,pb as a8}from"./chunk-0568ndm9.js";import{qb as _9,rb as z9,sb as D2}from"./chunk-4dnvydyv.js";import{Ab as f$,Bb as c$,Cb as R2,Db as S2,Nb as i2,Ob as z0,Pb as c0,Qb as V5,Rb as s$,Sb as BJ,Tb as VJ,Wb as PJ,_b as r8,cc as _J,dc as zJ,fc as i,yb as H0,zb as O1}from"./chunk-3qmwt188.js";import{gc as T7,jc as j7,rc as f7,xc as M7}from"./chunk-s4mqw4wa.js";import{Ic as BZ,Jc as QZ}from"./chunk-j8ggq1z4.js";import{$c as A2,Vc as v2,Wc as Q0,Xc as P,_c as V0,ad as t$,bd as w$,cd as R6,dd as S$,ed as n8,jd as r$}from"./chunk-n00mknme.js";import{kd as x$}from"./chunk-qg87zezq.js";import{ld as Y$}from"./chunk-xjqcc0nt.js";import{rd as FJ,sd as N2}from"./chunk-f8zz4se0.js";import{ud as N0,vd as j$}from"./chunk-xzdpdwhz.js";import{wd as MJ}from"./chunk-m27w377p.js";import{Ad as WJ,yd as YJ,zd as HJ}from"./chunk-d2kzet1k.js";import{Bd as M2,Cd as C2,Ed as A$,Fd as q9,Hd as S0,Id as h7,Jd as k0,Kd as m0,Ld as K5,Md as c2,Nd as $$,Od as g$,Pd as p$,Qd as OJ,Rd as r6,Td as Z0,Ud as T2,Vd as EJ}from"./chunk-wjqctwyr.js";import{Xd as e$,Zd as F$,_d as _2}from"./chunk-5xph8r1k.js";import{$d as nJ,be as QJ,ce as p2,de as VZ}from"./chunk-5sw8j9ae.js";import{fe as Q4,he as q0}from"./chunk-86zsjamb.js";import{ie as h1,je as q4,ke as u1,le as i$}from"./chunk-6pb6zs96.js";import{pe as p}from"./chunk-w56y2pvk.js";import{$e as g8,Ee as yJ,Ie as o4,Ke as ZJ,Me as F8,Ne as D8,Ue as h4,Ve as KJ,We as XJ,Xe as h8,Ye as u8,Ze as d8,_e as m8,af as p8,bf as $0,se as a4,xe as s4,ze as U4}from"./chunk-edqtngzr.js";import{hf as a1,if as P4,jf as z,kf as F9,lf as S,mf as g}from"./chunk-hpmxmkzc.js";import{of as s9,pf as o9}from"./chunk-bpz0g8ej.js";import{rf as Z2,tf as L}from"./chunk-p1dp2xgq.js";import{xf as JJ,yf as UJ}from"./chunk-c674mmtj.js";import{Cf as cJ,zf as aJ}from"./chunk-1gkpjhts.js";import{Gf as eJ}from"./chunk-c29y2s8g.js";import{Lf as C0}from"./chunk-pccn8ndq.js";import{Of as i1,Qf as v$,Sf as $J,Tf as S4,Vf as K0}from"./chunk-s14wmzm3.js";import{Xf as t0}from"./chunk-vns8g2rv.js";import{randomUUID as o7}from"crypto";var d7=String.raw`
1
+ import{ca as j,da as d0,ia as xJ,ja as y8,ka as I0}from"./chunk-b22x3h7k.js";import{Ea as A7,la as b7,na as L7,oa as G4}from"./chunk-5dr18jzd.js";import{$a as s0,Fa as z$,Ga as z2,Ha as b8,Ia as F1,Ja as V9,Ma as O0,Oa as L2,Pa as A8,Qa as N8,Ra as T8,Ua as P2,Wa as D6,Xa as k2,Ya as I2,fb as a2,gb as jJ,hb as t9,pb as a8}from"./chunk-a0ga35qv.js";import{qb as _9,rb as z9,sb as D2}from"./chunk-4dnvydyv.js";import{Ab as f$,Bb as c$,Cb as R2,Db as S2,Nb as i2,Ob as z0,Pb as c0,Qb as V5,Rb as s$,Sb as BJ,Tb as VJ,Wb as PJ,_b as r8,dc as _J,ec as zJ,gc as i,yb as H0,zb as O1}from"./chunk-vbsk6mjn.js";import{hc as T7,kc as j7,sc as f7,yc as M7}from"./chunk-nwg0bpex.js";import{Jc as BZ,Kc as QZ}from"./chunk-xjq1htyt.js";import{$c as V0,Wc as v2,Xc as Q0,Yc as P,ad as A2,bd as t$,cd as w$,dd as R6,ed as S$,fd as n8,kd as r$}from"./chunk-wbvs2tv5.js";import{ld as Y$}from"./chunk-xjqcc0nt.js";import{rd as FJ,sd as N2}from"./chunk-0t0dsepx.js";import{ud as N0,vd as j$}from"./chunk-763aam58.js";import{wd as MJ}from"./chunk-m27w377p.js";import{Ad as WJ,yd as YJ,zd as HJ}from"./chunk-mmw7jbxg.js";import{Bd as M2,Cd as C2,Ed as A$,Fd as q9,Hd as S0,Id as h7,Jd as k0,Kd as m0,Ld as K5,Md as c2,Nd as $$,Od as g$,Pd as p$,Qd as OJ,Rd as r6,Td as Z0,Ud as T2,Vd as EJ}from"./chunk-rb7aayp5.js";import{Xd as e$,Zd as F$,_d as _2}from"./chunk-5xph8r1k.js";import{$d as nJ,be as QJ,ce as p2,de as VZ}from"./chunk-5sw8j9ae.js";import{fe as Q4,he as q0}from"./chunk-wyq21fev.js";import{ie as h1,je as q4,ke as u1,le as i$}from"./chunk-6pb6zs96.js";import{De as o4,Fe as ZJ,He as F8,Ie as D8,Oe as x$,Qe as h4,Se as KJ,Te as XJ,Ue as h8,Ve as u8,We as d8,Xe as m8,Ye as g8,Ze as p8,_e as $0,ne as a4,se as s4,ue as U4,ze as yJ}from"./chunk-565weg3f.js";import{bf as a1,cf as P4,df as z,ef as F9,ff as S,gf as g}from"./chunk-r561wfcz.js";import{if as s9,jf as o9}from"./chunk-0qayfsc9.js";import{lf as Z2,nf as L}from"./chunk-dbb20rxh.js";import{rf as p}from"./chunk-awwe1rqb.js";import{wf as JJ,xf as UJ}from"./chunk-7tea6e9y.js";import{Bf as cJ,yf as aJ}from"./chunk-9tp00s2z.js";import{Ff as eJ}from"./chunk-9gtc0kd2.js";import{Kf as C0}from"./chunk-6vhc5gdf.js";import{Nf as i1,Pf as v$,Rf as $J,Sf as S4,Uf as K0}from"./chunk-vjrn667c.js";import{Wf as t0}from"./chunk-86g3xxx7.js";import{randomUUID as o7}from"crypto";var d7=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);
@@ -130,6 +130,7 @@ IMPORTANT: You must NEVER generate or guess URLs for the user unless you are con
130
130
  - The user will primarily request you to perform software engineering tasks. These may include solving bugs, adding new functionality, refactoring code, explaining code, and more. When given an unclear or generic instruction, consider it in the context of these software engineering tasks and the current working directory. For example, if the user asks you to change "methodName" to snake case, do not reply with just "method_name", instead find the method in the code and modify the code.
131
131
  - You are highly capable and often allow users to complete ambitious tasks that would otherwise be too complex or take too long. You should defer to user judgement about whether a task is too large to attempt.
132
132
  - In general, do not propose changes to code you haven't read. If a user asks about or wants you to modify a file, read it first. Understand existing code before suggesting modifications.
133
+ - Preserve API sync/async contracts. A conventionally synchronous method such as \`get()\` must not silently return a \`T | Promise<T>\` union when optional asynchronous behavior is added. Prefer a separate explicitly asynchronous method such as \`fetch()\`, or an explicit option/overload requested by the user. When the contract is ambiguous, inspect existing types and tests, follow established ecosystem conventions, or ask before changing call-site semantics.
133
134
  - Do not create files unless they're absolutely necessary for achieving your goal. Generally prefer editing an existing file to creating a new one, as this prevents file bloat and builds on existing work more effectively.
134
135
  - If an approach fails, diagnose why before switching tactics—read the error, check your assumptions, try a focused fix. Don't retry the identical action blindly, but don't abandon a viable approach after a single failure either. Escalate to the user with AskUserQuestion only when you're genuinely stuck after investigation, not as a first response to friction.
135
136
  - Be careful not to introduce security vulnerabilities such as command injection, XSS, SQL injection, and other OWASP top 10 vulnerabilities. If you notice that you wrote insecure code, immediately fix it. Prioritize writing safe, secure, and correct code.
@@ -299,7 +300,7 @@ ${O.content}`).join(`
299
300
 
300
301
  [... and ${Z.length-J} more files matched]`:"";return{type:"file",path:$,content:W+Q,metadata:{lines:Y.reduce((O,B)=>O+B.lines,0),truncated:Z.length>J||Y.some((O)=>O.truncated)}}}clearExpiredCache(){let $=Date.now(),Z=0;for(let[J,U]of this.fileCache.entries())if($-U.timestamp>60000)this.fileCache.delete(J),Z++;if(Z>0)h0.debug(`Cleared ${Z} expired cache entries`)}clearCache(){this.fileCache.clear(),h0.debug("Cleared all cache")}getCacheStats(){return{size:this.fileCache.size,keys:Array.from(this.fileCache.keys())}}}import{createHash as b5,randomUUID as IU}from"node:crypto";import{constants as D5,promises as r}from"node:fs";import u0 from"node:path";import vU from"write-file-atomic";import{realpathSync as kU}from"node:fs";import Y2 from"node:path";var F5=p("Execution");class P0{static instance=null;locks=new Map;constructor(){}static getInstance(){if(!P0.instance)P0.instance=new P0;return P0.instance}async acquireLock($,Z){let J=H2($),U=this.locks.get(J),X,Y=new Promise((H)=>{X=H});if(this.locks.set(J,Y),U)await U;try{return await this.executeWithLock(J,Z)}finally{if(X(),this.locks.get(J)===Y)this.locks.delete(J)}}acquireLocks($,Z){let J=[...new Set($.map(H2))].sort((X,Y)=>X.localeCompare(Y)),U=(X)=>X>=J.length?Z():this.acquireLock(J[X],()=>U(X+1));return U(0)}async executeWithLock($,Z){F5.debug(`获取文件锁: ${$}`);try{let J=await Z();return F5.debug(`释放文件锁: ${$}`),J}catch(J){throw F5.debug(`操作失败,释放文件锁: ${$}`),J}}isLocked($){return this.locks.has(H2($))}clearLock($){this.locks.delete(H2($))}clearAll(){this.locks.clear()}getLockedFiles(){return Array.from(this.locks.keys())}getLockedFileCount(){return this.locks.size}static resetInstance(){P0.instance=null}}function H2($){let Z=Y2.resolve($),J=[],U=Z;while(!0){try{return Y2.join(kU.native(U),...J.reverse())}catch(Y){let H=Y.code;if(H!=="ENOENT"&&H!=="ENOTDIR")return Z}let X=Y2.dirname(U);if(X===U)return Z;J.push(Y2.basename(U)),U=X}}var KZ=1,yU=1e4,xU=50,hU=30000;async function L5($,Z){let J=T5($);await j5(J);let U=u0.join(J,".operation.lock"),X=IU(),Y=Date.now()+yU;while(Date.now()<Y){let H;try{H=await r.open(U,D5.O_CREAT|D5.O_EXCL|D5.O_WRONLY,384),await H.writeFile(`${JSON.stringify({version:1,pid:process.pid,token:X,createdAt:new Date().toISOString()})}
301
302
  `,"utf8"),await H.sync(),await H.close(),H=void 0}catch(W){if(await H?.close().catch(()=>{return}),W.code!=="EEXIST")throw await r.rm(U,{force:!0}).catch(()=>{return}),W;await gU(U),await new Promise((Q)=>setTimeout(Q,xU));continue}try{return await Z()}finally{await mU(U,X)}}throw Error("ApplyPatch workspace is busy in another Blade process")}async function wZ($,Z,J,U,X){let Y=T5($);await j5(Y);let H={version:KZ,transactionId:Z,workspaceRoot:$,phase:"preparing",ownerPid:process.pid,createdAt:new Date().toISOString(),entries:J.changes.map((Q)=>({path:Q.path,...U.get(Q.path)?{stagePath:U.get(Q.path)}:{},...X.get(Q.path)?{backupPath:X.get(Q.path)}:{},oldExisted:Q.oldContent!==null,...Q.newContent!==null?{newContentHash:b5("sha256").update(Q.newContent).digest("hex")}:{}}))},W=u0.join(Y,`${Z}.json`);return await DZ(W,H),{filePath:W,journal:H}}async function qZ($){$.journal.phase="committed",await DZ($.filePath,$.journal)}async function A5($){await r.rm($.filePath,{force:!0})}async function FZ($){let Z;try{Z=await r.realpath($)}catch{return 0}return L5(Z,()=>N5(Z))}async function N5($){let Z=T5($),J;try{J=await r.readdir(Z)}catch(X){if(X.code==="ENOENT")return 0;throw X}let U=0;for(let X of J.filter((Y)=>Y.endsWith(".json"))){let Y=u0.join(Z,X),H=await dU(Y,$);await P0.getInstance().acquireLocks(H.entries.map((W)=>W.path),()=>uU(H)),await r.rm(Y,{force:!0}),U++}return U}async function uU($){let Z=[];for(let J of[...$.entries].reverse())try{if($.phase==="preparing"){if(J.backupPath&&await EZ(J.backupPath))await r.rm(J.path,{force:!0}),await r.rename(J.backupPath,J.path);else if(!J.oldExisted&&J.newContentHash&&!(J.stagePath&&await EZ(J.stagePath))&&await iU(J.path)===J.newContentHash)await r.rm(J.path,{force:!0})}if(J.stagePath)await r.rm(J.stagePath,{force:!0});if(J.backupPath)await r.rm(J.backupPath,{force:!0})}catch(U){Z.push(U)}if(Z.length>0)throw AggregateError(Z,`Failed to recover ApplyPatch transaction ${$.transactionId}`)}async function dU($,Z){let J=await r.lstat($);if(!J.isFile()||J.isSymbolicLink()||(J.mode&511)!==384||process.getuid&&J.uid!==process.getuid())throw Error("ApplyPatch journal ownership or permissions are invalid");let U=JSON.parse(await r.readFile($,"utf8"));if(U.version!==KZ||typeof U.transactionId!=="string"||!/^[A-Za-z0-9_-]{1,64}$/.test(U.transactionId)||U.workspaceRoot!==Z||U.phase!=="preparing"&&U.phase!=="committed"||!Array.isArray(U.entries))throw Error("ApplyPatch journal is invalid");for(let X of U.entries)if(!X||typeof X.path!=="string"||!u0.isAbsolute(X.path)||typeof X.oldExisted!=="boolean"||X.stagePath!==void 0&&typeof X.stagePath!=="string"||X.backupPath!==void 0&&typeof X.backupPath!=="string"||X.newContentHash!==void 0&&(typeof X.newContentHash!=="string"||!/^[a-f0-9]{64}$/.test(X.newContentHash))||!H0.isWithinWorkspace(X.path,Z)||!GZ(X.path,X.stagePath,U.transactionId,"stage")||!GZ(X.path,X.backupPath,U.transactionId,"backup"))throw Error("ApplyPatch journal contains an invalid path");return U}function GZ($,Z,J,U){if(!Z)return!0;return u0.dirname(Z)===u0.dirname($)&&Z===u0.join(u0.dirname($),`.${u0.basename($)}.blade-patch-${J}.${U}`)}async function DZ($,Z){await j5(u0.dirname($)),await vU($,`${JSON.stringify(Z)}
302
- `,{mode:384}),await r.chmod($,384)}function T5($){let Z=b5("sha256").update($).digest("hex").slice(0,32);return u0.join(K0(),"patch-transactions",Z)}async function j5($){await r.mkdir($,{recursive:!0,mode:448});let Z=await r.lstat($);if(!Z.isDirectory()||Z.isSymbolicLink()||(Z.mode&511)!==448||process.getuid&&Z.uid!==process.getuid())throw Error("ApplyPatch transaction directory ownership or permissions are invalid")}async function mU($,Z){try{if(JSON.parse(await r.readFile($,"utf8")).token===Z)await r.rm($,{force:!0})}catch(J){if(J.code!=="ENOENT")throw J}}async function gU($){let Z;try{Z=await r.lstat($)}catch(U){if(U.code==="ENOENT")return;throw U}if(!Z.isFile()||Z.isSymbolicLink()||(Z.mode&511)!==384||process.getuid&&Z.uid!==process.getuid())throw Error("ApplyPatch workspace lock ownership or permissions are invalid");let J;try{let U=JSON.parse(await r.readFile($,"utf8"));if(typeof U.pid==="number"&&Number.isInteger(U.pid))J=U.pid}catch{}if(J&&pU(J))return;if(!J&&Date.now()-Z.mtimeMs<hU)return;await r.rm($,{force:!0})}function pU($){try{return process.kill($,0),!0}catch(Z){return Z.code==="EPERM"}}async function EZ($){try{return await r.lstat($),!0}catch(Z){if(Z.code==="ENOENT")return!1;throw Z}}async function iU($){try{return b5("sha256").update(await r.readFile($)).digest("hex")}catch(Z){if(Z.code==="ENOENT")return;throw Z}}import*as m9 from"os";import*as g9 from"path";var AZ=new Set(["temperature","maxOutputTokens","timeout","theme","uiTheme","language","fontSize","debug","autoSaveSessions","maxTurns","disableAllHooks","permissions","hooks","env","mcpServers"]),cU=new Set(["systemPrompt","appendSystemPrompt","initialMessage","resumeSessionId","forkSession","allowedTools","disallowedTools","mcpConfigPaths","strictMcpConfig","addDirs","outputFormat","inputFormat","print","includePartialMessages","replayUserMessages","agentsConfig","settingSources"]),lU=z.Object({operation:g(["get","set","list"],{description:"操作类型: get(读取)/ set(设置)/ list(列举可配置项)"}),key:z.Optional(z.String({description:'配置键名,支持点号嵌套(如 hooks.PreToolUse)。get 时用 "*" 获取全部配置'})),value:z.Optional(z.Unknown({description:"要设置的值(仅 set 操作需要)"})),scope:z.Optional(g(["local","project","global"],{description:"持久化范围: local(.blade/settings.local.json)/ project(.blade/settings.json)/ global(~/.blade/)"}))});function bZ($){return{...$}}function LZ($,Z){let J=Z.split("."),U=$;for(let X of J){if(U===null||U===void 0||typeof U!=="object")return;U=U[X]}return U}function nU($){let Z=["可配置项列表(白名单):",""];for(let J of AZ){let U=$[J],X=U===void 0?"(未设置)":JSON.stringify(U,null,2),Y=X.length>200?`${X.slice(0,197)}...`:X;Z.push(`- ${J}: ${Y}`)}return Z.join(`
303
+ `,{mode:384}),await r.chmod($,384)}function T5($){let Z=b5("sha256").update($).digest("hex").slice(0,32);return u0.join(K0(),"patch-transactions",Z)}async function j5($){await r.mkdir($,{recursive:!0,mode:448});let Z=await r.lstat($);if(!Z.isDirectory()||Z.isSymbolicLink()||(Z.mode&511)!==448||process.getuid&&Z.uid!==process.getuid())throw Error("ApplyPatch transaction directory ownership or permissions are invalid")}async function mU($,Z){try{if(JSON.parse(await r.readFile($,"utf8")).token===Z)await r.rm($,{force:!0})}catch(J){if(J.code!=="ENOENT")throw J}}async function gU($){let Z;try{Z=await r.lstat($)}catch(U){if(U.code==="ENOENT")return;throw U}if(!Z.isFile()||Z.isSymbolicLink()||(Z.mode&511)!==384||process.getuid&&Z.uid!==process.getuid())throw Error("ApplyPatch workspace lock ownership or permissions are invalid");let J;try{let U=JSON.parse(await r.readFile($,"utf8"));if(typeof U.pid==="number"&&Number.isInteger(U.pid))J=U.pid}catch{}if(J&&pU(J))return;if(!J&&Date.now()-Z.mtimeMs<hU)return;await r.rm($,{force:!0})}function pU($){try{return process.kill($,0),!0}catch(Z){return Z.code==="EPERM"}}async function EZ($){try{return await r.lstat($),!0}catch(Z){if(Z.code==="ENOENT")return!1;throw Z}}async function iU($){try{return b5("sha256").update(await r.readFile($)).digest("hex")}catch(Z){if(Z.code==="ENOENT")return;throw Z}}import*as m9 from"os";import*as g9 from"path";var AZ=new Set(["temperature","maxOutputTokens","timeout","codeTheme","uiTheme","language","fontSize","debug","autoSaveSessions","maxTurns","disableAllHooks","permissions","hooks","env","mcpServers"]),cU=new Set(["systemPrompt","appendSystemPrompt","initialMessage","resumeSessionId","forkSession","allowedTools","disallowedTools","mcpConfigPaths","strictMcpConfig","addDirs","outputFormat","inputFormat","print","includePartialMessages","replayUserMessages","agentsConfig","settingSources"]),lU=z.Object({operation:g(["get","set","list"],{description:"操作类型: get(读取)/ set(设置)/ list(列举可配置项)"}),key:z.Optional(z.String({description:'配置键名,支持点号嵌套(如 hooks.PreToolUse)。get 时用 "*" 获取全部配置'})),value:z.Optional(z.Unknown({description:"要设置的值(仅 set 操作需要)"})),scope:z.Optional(g(["local","project","global"],{description:"持久化范围: local(.blade/settings.local.json)/ project(.blade/settings.json)/ global(~/.blade/)"}))});function bZ($){return{...$}}function LZ($,Z){let J=Z.split("."),U=$;for(let X of J){if(U===null||U===void 0||typeof U!=="object")return;U=U[X]}return U}function nU($){let Z=["可配置项列表(白名单):",""];for(let J of AZ){let U=$[J],X=U===void 0?"(未设置)":JSON.stringify(U,null,2),Y=X.length>200?`${X.slice(0,197)}...`:X;Z.push(`- ${J}: ${Y}`)}return Z.join(`
303
304
  `)}var f5=j({name:"ConfigTool",displayName:"Config",kind:"execute",isConcurrencySafe:!1,schema:lU,description:{short:"Read, update, or list Blade configuration",long:"Manage Blade configuration: get reads a config value, set updates a whitelisted config field (with persistence), list enumerates all settable keys and their current values.",usageNotes:['Use operation="get" with key="*" to dump all config','Use operation="get" with a dotted key like "hooks.PreToolUse"','Use operation="set" with key and value to update config','Use operation="list" to see all settable keys',"The scope option controls persistence: local/project/global","models and currentModelId must be modified through model management"],examples:[{description:"Get all configuration",params:{operation:"get",key:"*"}},{description:"Get a specific config value",params:{operation:"get",key:"hooks"}},{description:"Set temperature",params:{operation:"set",key:"temperature",value:0.7,scope:"global"}},{description:"List all settable keys",params:{operation:"list"}}]},async execute($,Z){let{operation:J,key:U,value:X,scope:Y}=$,H=V0();if(!H)return{success:!1,llmContent:"Config not initialized. Please wait for Blade to finish starting.",error:{message:"Config not initialized",type:"execution_error"},metadata:{summary:"配置未初始化"}};switch(J){case"get":{if(!U)return{success:!1,llmContent:'Missing "key" parameter for get operation. Use key="*" to get all config.',error:{message:"Missing key",type:"validation_error"},metadata:{summary:"缺少 key 参数"}};if(U==="*"){let B=bZ(H);return{success:!0,llmContent:JSON.stringify(B,null,2),metadata:{summary:"获取全部配置"}}}let W=H;if(U.split(".")[0]==="models"){let B=bZ(W),V=LZ(B,U);return{success:!0,llmContent:JSON.stringify(V,null,2),metadata:{summary:`获取配置: ${U}`}}}let O=LZ(W,U);if(O===void 0)return{success:!0,llmContent:`Config key "${U}" is not set or does not exist.`,metadata:{summary:`配置项 ${U} 不存在`}};return{success:!0,llmContent:JSON.stringify(O,null,2),metadata:{summary:`获取配置: ${U}`}}}case"set":{if(!U)return{success:!1,llmContent:'Missing "key" parameter for set operation.',error:{message:"Missing key",type:"validation_error"},metadata:{summary:"缺少 key 参数"}};if(X===void 0)return{success:!1,llmContent:'Missing "value" parameter for set operation.',error:{message:"Missing value",type:"validation_error"},metadata:{summary:"缺少 value 参数"}};let W=U.split(".")[0];if(W==="models"||W==="currentModelId")return{success:!1,llmContent:'Refused: "models" and "currentModelId" cannot be modified via ConfigTool to protect API keys. Use the /model slash command instead.',error:{message:"Forbidden key: models",type:"permission_denied"},metadata:{summary:"拒绝修改 models"}};if(cU.has(W))return{success:!1,llmContent:`Refused: "${W}" is a runtime-only field and cannot be persisted via ConfigTool.`,error:{message:`Forbidden runtime key: ${W}`,type:"permission_denied"},metadata:{summary:`拒绝修改运行时字段: ${W}`}};if(!AZ.has(W))return{success:!1,llmContent:`Key "${W}" is not in the settable whitelist. Use operation="list" to see all allowed keys.`,error:{message:`Key not settable: ${W}`,type:"validation_error"},metadata:{summary:`不可设置的 key: ${W}`}};let Q;if(U.includes(".")){let O=U.split(".");if(Q={[O[0]]:X},O.length===2){let B=H[O[0]];if(typeof B==="object"&&B!==null)Q={[O[0]]:{...B,[O[1]]:X}};else Q={[O[0]]:{[O[1]]:X}}}}else Q={[U]:X};try{await r$().updateConfig(Q,Y?{scope:Y}:{});let O=JSON.stringify(X).length>200?`${JSON.stringify(X).slice(0,197)}...`:JSON.stringify(X);return{success:!0,llmContent:`Config updated: ${U} = ${O}`+(Y?` (scope: ${Y})`:""),metadata:{summary:`配置已更新: ${U}`}}}catch(O){let B=O instanceof Error?O.message:String(O);return{success:!1,llmContent:`Failed to update config: ${B}`,error:{message:B,type:"execution_error"},metadata:{summary:`配置更新失败: ${U}`}}}}case"list":return{success:!0,llmContent:nU(H),metadata:{summary:"列举可配置项"}};default:return{success:!1,llmContent:`Unknown operation: ${J}`,error:{message:`Unknown operation: ${J}`,type:"validation_error"},metadata:{summary:`未知操作: ${J}`}}}}});import{promises as Y3}from"node:fs";import k$ from"node:path";import*as nZ from"diff";import NZ from"node:path";var TZ="*** Begin Patch",jZ="*** End Patch",C5="*** Add File: ",R5="*** Delete File: ",S5="*** Update File: ",fZ="*** Move to: ",rU="*** End of File",MZ=1048576,CZ=100,RZ=1000,SZ=50000;class U0 extends Error{line;constructor($,Z){super(Z?`Invalid patch at line ${Z}: ${$}`:`Invalid patch: ${$}`);this.line=Z;this.name="ApplyPatchParseError"}}function P5($){if($.includes("\x00"))throw new U0("null bytes are not allowed");if(Buffer.byteLength($,"utf8")>MZ)throw new U0(`patch exceeds the ${MZ} byte limit`);let J=$.replace(/\r\n/g,`
304
305
  `).split(`
305
306
  `);if(J.at(-1)==="")J.pop();if(J.length>SZ)throw new U0(`patch exceeds the ${SZ} line limit`);if(J[0]!==TZ)throw new U0(`first line must be "${TZ}"`,1);if(J.at(-1)!==jZ)throw new U0(`last line must be "${jZ}"`,J.length);let U=[],X=0,Y=1;while(Y<J.length-1){if(U.length>=CZ)throw new U0(`patch exceeds the ${CZ} file operation limit`,Y+1);let H=J[Y],W=Y+1;if(H.startsWith(C5)){let Q=W2(H.slice(C5.length),W);Y++;let O=[];while(Y<J.length-1&&!M5(J[Y])){let B=J[Y];if(!B.startsWith("+"))throw new U0('every Add File content line must start with "+"',Y+1);O.push(B.slice(1)),Y++}if(O.length===0)throw new U0('Add File requires at least one "+" content line',W);U.push({kind:"add",path:Q,content:`${O.join(`
@@ -768,7 +769,7 @@ ${o}
768
769
  </approved-plan>
769
770
 
770
771
  IMPORTANT: Execute according to the approved plan above. Follow the steps exactly as specified.`;if(typeof _==="string")B0=_+a;else B0=[..._,{type:"text",text:a}]}N=yield*this.runLoop(B0,G,{...M,inputMessageId:void 0})}if(!this.sessionRuntime||!C)return N;let v=await this.sessionRuntime.recordGoalProgress({tokens:N.metadata?.tokensUsed??0,elapsedMs:N.metadata?.duration??0});if(v)yield{kind:"goal_updated",goal:v};if(!N.success||G.signal?.aborted){if(v=await this.sessionRuntime.pauseActiveGoal(G.signal?.aborted?"goal paused after user cancellation":N.error?.message??"goal paused after turn failure"),v)yield{kind:"goal_updated",goal:v}}let y=N.success&&!G.signal?.aborted&&D<20;if(b=await this.sessionRuntime.finishTurn(C,{continuePending:y,outcome:N.success&&!G.signal?.aborted?{status:"completed",turnsCount:N.metadata?.turnsCount??0,toolCallsCount:N.metadata?.toolCallsCount??0,durationMs:N.metadata?.duration??0}:{status:"aborted",cause:G.signal?.aborted?"cancelled":"failed",turnsCount:N.metadata?.turnsCount??0,toolCallsCount:N.metadata?.toolCallsCount??0,durationMs:N.metadata?.duration??0}}),b){D++,E=!0,K=!1,q=null,_="",F=void 0,w=T(),yield{kind:"follow_up_started",queued:this.sessionRuntime.getPendingSteeringCount(),recovered:this.sessionRuntime.getRecoveredSteeringCount(),messages:A()};continue}if(!N.success||G.signal?.aborted)return N;if(v=await this.sessionRuntime.getGoal(),!v||v.status!=="active"&&v.status!=="verifying")return N;if(q=await this.sessionRuntime.beginGoalContinuation(),!q)return N;b=await this.sessionRuntime.beginTurn("goal"),E=!1,K=!0,_=m5(q),F=void 0,w=void 0,yield{kind:"goal_continuation_started",goal:q,continuation:q.continuationCount},yield{kind:"goal_updated",goal:q}}}finally{if(this.sessionRuntime&&b)await this.sessionRuntime.finishTurn(b)}}let O=typeof W==="string"?W:W.filter((_)=>_.type==="text").map((_)=>_.text).join(`
771
- `),B={id:this.generateTaskId(),type:"simple",prompt:O};return{success:!0,finalMessage:(await this.executeTask(B)).content,metadata:{turnsCount:1,toolCallsCount:0,duration:0}}}async chat($,Z,J){let{drainLoop:U}=await import("./chunk-rtkhyp1g.js");return U(this.chatStream($,Z,J))}async*runPlanLoop($,Z,J){u.debug("Processing Plan mode message...");let{prompt:U}=await P$({projectPath:Z.workspaceRoot||L(),mode:"plan",includeEnvironment:!0,language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),projectInstructionSourcePath:this.sessionRuntime?.projectRoot}),X;if(typeof $==="string")X=E1($);else{let Y=$.filter((H)=>H.type==="text");if(Y.length>0){let H=Y[0];X=$.map((W)=>W===H?{type:"text",text:E1(H.text)}:W)}else X=[{type:"text",text:E1("")},...$]}return yield*this.executeLoop(X,Z,J,U)}async*runLoop($,Z,J){u.debug("Processing enhanced chat message...");let U=Z.systemPrompt??await this.buildSystemPromptOnDemand(Z.workspaceRoot||L());return yield*this.executeLoop($,Z,J,U)}async buildSystemPromptOnDemand($){let Z=this.runtimeOptions.systemPrompt,J=this.runtimeOptions.appendSystemPrompt;return(await P$({projectPath:$,replaceDefault:Z,append:J,includeEnvironment:!0,language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),projectInstructionSourcePath:this.sessionRuntime?.projectRoot})).prompt}executeLoop($,Z,J,U){if(!this.isInitialized)throw Error("Agent未初始化");let X=this.buildLoopDependencies();return a8(X,$,Z,J,U)}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=$,u.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,U)=>this.sessionRuntime.resolveContextualProjectRules($,Z,J,U):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(),U=Z.getAll().filter((X)=>!$.includes(X.name));for(let X of U)Z.unregister(X.name);u.debug(`Applied tool whitelist: ${$.join(", ")} (removed ${U.length} tools)`)}applyToolBlacklist($){let Z=this.toolExecutor.getRegistry(),J=new Set($);for(let U of Z.getAll())if(J.has(U.name))Z.unregister(U.name);u.debug(`Applied tool blacklist: ${$.join(", ")}`)}getToolStats(){let $=this.getAvailableTools(),Z=new Map;return $.forEach((J)=>{let U=Z.get(J.kind)||0;Z.set(J.kind,U+1)}),{totalTools:$.length,toolsByKind:Object.fromEntries(Z),toolNames:$.map((J)=>J.name)}}async destroy(){this.log("销毁Agent...");try{await this.legacyMcpRegistry?.disconnectAll(),this.legacyMcpRegistry=void 0,this.log("Agent已销毁")}catch($){throw this.error("Agent销毁失败",$),$}finally{this.toolExecutor.dispose(),this.isInitialized=!1}}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){u.debug(`[MainAgent] ${$}`,Z||"")}error($,Z){u.error(`[MainAgent] ${$}`,Z||"")}async initializeSystemPrompt(){try{let $=this.runtimeOptions.systemPrompt,Z=this.runtimeOptions.appendSystemPrompt,J=await P$({projectPath:this.sessionRuntime?.workspaceRoot??L(),replaceDefault:$,append:Z,includeEnvironment:!1,language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),projectInstructionSourcePath:this.sessionRuntime?.projectRoot});if(J.prompt)this.log("系统提示配置验证成功"),u.debug(`[SystemPrompt] 可用来源: ${J.sources.filter((U)=>U.loaded).map((U)=>U.name).join(", ")}`)}catch($){this.error("系统提示配置验证失败",$)}}async registerBuiltinTools(){try{let $=await j2({sessionId:"default",configDir:o8.join(s8.homedir(),".blade"),workspaceRoot:L(),resourceRoot:L(),agentResources:this.agentResources});u.debug(`Registering ${$.length} builtin tools...`),this.toolExecutor.getRegistry().registerAll($);let Z=this.toolExecutor.getRegistry().getAll().length;u.debug(`Builtin tools registered: ${Z} tools`),u.debug(`[Tools] ${this.toolExecutor.getRegistry().getAll().map((J)=>J.name).join(", ")}`),await this.registerMcpTools()}catch($){throw u.error("Failed to register builtin tools:",$),$}}async registerMcpTools(){try{let $=await J2({workspaceRoot:L(),storeServers:this.config.mcpServers??{},cliConfigs:this.runtimeOptions.mcpConfig,strictCliConfig:this.runtimeOptions.strictMcpConfig});if(Object.keys($).length===0){u.debug("No MCP servers configured");return}let Z=I0.createIsolated({artifactWriter:new G1(`legacy-${tX()}`)});this.legacyMcpRegistry=Z;for(let[Y,H]of Object.entries($))try{u.debug(`Connecting to MCP server: ${Y}`),await Z.registerServer(Y,H),u.debug(`MCP server "${Y}" connected`)}catch(W){u.warn(`Warning: MCP server "${Y}" connection failed:`,W)}let J=this.toolExecutor.getRegistry();J.setMcpCatalogBarrier(()=>Z.waitForCatalogIdle());let U=Z.getCatalogSnapshot();J.replaceMcpTools(U.tools),J.registerAll(b1(Z));let X=Z.getInstructionsSnapshot();if(J.queueMcpInstructionsChange({revision:X.revision,reason:"snapshot",replace:!0,instructions:X.instructions,removed:[]}),Z.on("catalogChanged",(Y)=>{J.replaceMcpTools(Y.tools,Y)}),Z.on("contentCatalogChanged",(Y)=>{J.queueMcpContentChange(Y)}),Z.on("resourceUpdated",(Y)=>{J.queueMcpResourceUpdated(Y)}),Z.on("connectionLifecycleChanged",(Y)=>{J.queueMcpConnectionChange(Y)}),Z.on("log",(Y)=>{J.queueMcpLog(Y)}),Z.on("instructionsChanged",(Y)=>{J.queueMcpInstructionsChange({revision:Y.revision,reason:Y.reason,replace:!1,instructions:Y.action==="added"&&Y.instruction?[{serverName:Y.serverName,...Y.instruction}]:[],removed:Y.action==="removed"?[Y.serverName]:[]})}),U.tools.length>0)u.debug(`Registered ${U.tools.length} MCP tools`),u.debug(`[MCP Tools] ${U.tools.map((Y)=>Y.name).join(", ")}`)}catch($){u.warn("Failed to register MCP tools:",$)}}async loadSubagents(){let $=await Z0(L());if(this.agentResources=T2($),this.subagentRegistry=this.agentResources.subagents,this.runtimeOptions.agents?.length)this.subagentRegistry.applyOverrides(this.runtimeOptions.agents);let Z=this.subagentRegistry.getAllNames().length;if(Z>0)u.debug(`Loaded ${Z} subagents: ${this.subagentRegistry.getAllNames().join(", ")}`);else u.debug("No subagents configured")}applySkillToolRestrictions($){if(!this.activeSkillContext?.allowedTools)return $;let Z=this.activeSkillContext.allowedTools;u.debug(`Applying Skill tool restrictions: ${Z.join(", ")}`);let J=$.filter((U)=>{return Z.some((X)=>{if(X===U.name)return!0;let Y=X.match(/^(\w+)\(.*\)$/);if(Y&&Y[1]===U.name)return!0;return!1})});return u.debug(`Filtered tools: ${J.map((U)=>U.name).join(", ")} (${J.length}/${$.length})`),J}clearSkillContext(){if(this.activeSkillContext)u.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 U of $)if(U.type==="text")Z.push(U.text);if(Z.length===0)return $;let J=Z.join(`
772
+ `),B={id:this.generateTaskId(),type:"simple",prompt:O};return{success:!0,finalMessage:(await this.executeTask(B)).content,metadata:{turnsCount:1,toolCallsCount:0,duration:0}}}async chat($,Z,J){let{drainLoop:U}=await import("./chunk-pserj9y9.js");return U(this.chatStream($,Z,J))}async*runPlanLoop($,Z,J){u.debug("Processing Plan mode message...");let{prompt:U}=await P$({projectPath:Z.workspaceRoot||L(),mode:"plan",includeEnvironment:!0,language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),projectInstructionSourcePath:this.sessionRuntime?.projectRoot}),X;if(typeof $==="string")X=E1($);else{let Y=$.filter((H)=>H.type==="text");if(Y.length>0){let H=Y[0];X=$.map((W)=>W===H?{type:"text",text:E1(H.text)}:W)}else X=[{type:"text",text:E1("")},...$]}return yield*this.executeLoop(X,Z,J,U)}async*runLoop($,Z,J){u.debug("Processing enhanced chat message...");let U=Z.systemPrompt??await this.buildSystemPromptOnDemand(Z.workspaceRoot||L());return yield*this.executeLoop($,Z,J,U)}async buildSystemPromptOnDemand($){let Z=this.runtimeOptions.systemPrompt,J=this.runtimeOptions.appendSystemPrompt;return(await P$({projectPath:$,replaceDefault:Z,append:J,includeEnvironment:!0,language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),projectInstructionSourcePath:this.sessionRuntime?.projectRoot})).prompt}executeLoop($,Z,J,U){if(!this.isInitialized)throw Error("Agent未初始化");let X=this.buildLoopDependencies();return a8(X,$,Z,J,U)}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=$,u.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,U)=>this.sessionRuntime.resolveContextualProjectRules($,Z,J,U):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(),U=Z.getAll().filter((X)=>!$.includes(X.name));for(let X of U)Z.unregister(X.name);u.debug(`Applied tool whitelist: ${$.join(", ")} (removed ${U.length} tools)`)}applyToolBlacklist($){let Z=this.toolExecutor.getRegistry(),J=new Set($);for(let U of Z.getAll())if(J.has(U.name))Z.unregister(U.name);u.debug(`Applied tool blacklist: ${$.join(", ")}`)}getToolStats(){let $=this.getAvailableTools(),Z=new Map;return $.forEach((J)=>{let U=Z.get(J.kind)||0;Z.set(J.kind,U+1)}),{totalTools:$.length,toolsByKind:Object.fromEntries(Z),toolNames:$.map((J)=>J.name)}}async destroy(){this.log("销毁Agent...");try{await this.legacyMcpRegistry?.disconnectAll(),this.legacyMcpRegistry=void 0,this.log("Agent已销毁")}catch($){throw this.error("Agent销毁失败",$),$}finally{this.toolExecutor.dispose(),this.isInitialized=!1}}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){u.debug(`[MainAgent] ${$}`,Z||"")}error($,Z){u.error(`[MainAgent] ${$}`,Z||"")}async initializeSystemPrompt(){try{let $=this.runtimeOptions.systemPrompt,Z=this.runtimeOptions.appendSystemPrompt,J=await P$({projectPath:this.sessionRuntime?.workspaceRoot??L(),replaceDefault:$,append:Z,includeEnvironment:!1,language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),projectInstructionSourcePath:this.sessionRuntime?.projectRoot});if(J.prompt)this.log("系统提示配置验证成功"),u.debug(`[SystemPrompt] 可用来源: ${J.sources.filter((U)=>U.loaded).map((U)=>U.name).join(", ")}`)}catch($){this.error("系统提示配置验证失败",$)}}async registerBuiltinTools(){try{let $=await j2({sessionId:"default",configDir:o8.join(s8.homedir(),".blade"),workspaceRoot:L(),resourceRoot:L(),agentResources:this.agentResources});u.debug(`Registering ${$.length} builtin tools...`),this.toolExecutor.getRegistry().registerAll($);let Z=this.toolExecutor.getRegistry().getAll().length;u.debug(`Builtin tools registered: ${Z} tools`),u.debug(`[Tools] ${this.toolExecutor.getRegistry().getAll().map((J)=>J.name).join(", ")}`),await this.registerMcpTools()}catch($){throw u.error("Failed to register builtin tools:",$),$}}async registerMcpTools(){try{let $=await J2({workspaceRoot:L(),storeServers:this.config.mcpServers??{},cliConfigs:this.runtimeOptions.mcpConfig,strictCliConfig:this.runtimeOptions.strictMcpConfig});if(Object.keys($).length===0){u.debug("No MCP servers configured");return}let Z=I0.createIsolated({artifactWriter:new G1(`legacy-${tX()}`)});this.legacyMcpRegistry=Z;for(let[Y,H]of Object.entries($))try{u.debug(`Connecting to MCP server: ${Y}`),await Z.registerServer(Y,H),u.debug(`MCP server "${Y}" connected`)}catch(W){u.warn(`Warning: MCP server "${Y}" connection failed:`,W)}let J=this.toolExecutor.getRegistry();J.setMcpCatalogBarrier(()=>Z.waitForCatalogIdle());let U=Z.getCatalogSnapshot();J.replaceMcpTools(U.tools),J.registerAll(b1(Z));let X=Z.getInstructionsSnapshot();if(J.queueMcpInstructionsChange({revision:X.revision,reason:"snapshot",replace:!0,instructions:X.instructions,removed:[]}),Z.on("catalogChanged",(Y)=>{J.replaceMcpTools(Y.tools,Y)}),Z.on("contentCatalogChanged",(Y)=>{J.queueMcpContentChange(Y)}),Z.on("resourceUpdated",(Y)=>{J.queueMcpResourceUpdated(Y)}),Z.on("connectionLifecycleChanged",(Y)=>{J.queueMcpConnectionChange(Y)}),Z.on("log",(Y)=>{J.queueMcpLog(Y)}),Z.on("instructionsChanged",(Y)=>{J.queueMcpInstructionsChange({revision:Y.revision,reason:Y.reason,replace:!1,instructions:Y.action==="added"&&Y.instruction?[{serverName:Y.serverName,...Y.instruction}]:[],removed:Y.action==="removed"?[Y.serverName]:[]})}),U.tools.length>0)u.debug(`Registered ${U.tools.length} MCP tools`),u.debug(`[MCP Tools] ${U.tools.map((Y)=>Y.name).join(", ")}`)}catch($){u.warn("Failed to register MCP tools:",$)}}async loadSubagents(){let $=await Z0(L());if(this.agentResources=T2($),this.subagentRegistry=this.agentResources.subagents,this.runtimeOptions.agents?.length)this.subagentRegistry.applyOverrides(this.runtimeOptions.agents);let Z=this.subagentRegistry.getAllNames().length;if(Z>0)u.debug(`Loaded ${Z} subagents: ${this.subagentRegistry.getAllNames().join(", ")}`);else u.debug("No subagents configured")}applySkillToolRestrictions($){if(!this.activeSkillContext?.allowedTools)return $;let Z=this.activeSkillContext.allowedTools;u.debug(`Applying Skill tool restrictions: ${Z.join(", ")}`);let J=$.filter((U)=>{return Z.some((X)=>{if(X===U.name)return!0;let Y=X.match(/^(\w+)\(.*\)$/);if(Y&&Y[1]===U.name)return!0;return!1})});return u.debug(`Filtered tools: ${J.map((U)=>U.name).join(", ")} (${J.length}/${$.length})`),J}clearSkillContext(){if(this.activeSkillContext)u.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 U of $)if(U.type==="text")Z.push(U.text);if(Z.length===0)return $;let J=Z.join(`
772
773
  `);try{let U=await this.attachmentCollector.collect(J);if(U.length===0)return $;u.debug(`Processed ${U.length} @ file mentions in multimodal message`);let X=this.buildAttachmentText(U);if(!X)return $;return[...$,{type:"text",text:X}]}catch(U){return u.error("Failed to process @ mentions in multimodal message:",U),$}}buildAttachmentText($){let Z=[],J=[];for(let X of $)if(X.type==="file"){let Y=X.metadata?.lineRange?` (lines ${X.metadata.lineRange.start}${X.metadata.lineRange.end?`-${X.metadata.lineRange.end}`:""})`:"";Z.push(`<file path="${X.path}"${Y?` range="${Y}"`:""}>`,X.content,"</file>")}else if(X.type==="directory")Z.push(`<directory path="${X.path}">`,X.content,"</directory>");else if(X.type==="error")J.push(`- @${X.path}: ${X.error}`);let U="";if(Z.length>0)U+=`
773
774
 
774
775
  <system-reminder>
@@ -1560,7 +1561,7 @@ ${J}
1560
1561
  `)),{success:!0,message:"Schedules listed",content:Q.join(`
1561
1562
  `)}}case"create":{let W=UO(Y);if("error"in W)return U.sendMessage(`创建失败:${W.error}`),{success:!1,error:W.error};let Q={prompt:W.prompt,projectPath:H,trigger:W.trigger,isolation:"worktree",permissionMode:"default",enabled:!0};try{let O=await $.create(Q),B=O.nextRunAt?new Date(O.nextRunAt).toLocaleString():"(无)";return U.sendMessage(`[OK] 已创建定时任务 \`${O.id}\`
1562
1563
  ${G4(O.trigger)} · 下次运行: ${B}`),{success:!0,message:`Schedule ${O.id} created`}}catch(O){let B=O instanceof Error?O.message:String(O);return U.sendMessage(`创建失败:${B}`),{success:!1,error:B}}}case"remove":case"rm":{let W=Y[0];if(!W)return U.sendMessage("用法:/schedule remove <id>"),{success:!1,error:"Missing schedule id"};let Q=await $.remove(W);return U.sendMessage(Q?`[OK] 已删除 \`${W}\``:`未找到 \`${W}\``),{success:Q,message:Q?"Removed":"Not found"}}case"enable":case"disable":{let W=Y[0];if(!W)return U.sendMessage(`用法:/schedule ${X} <id>`),{success:!1,error:"Missing schedule id"};let Q=await $.setEnabled(W,X==="enable");return U.sendMessage(Q?`[OK] 已${X==="enable"?"启用":"停用"} \`${W}\``:`未找到 \`${W}\``),{success:Boolean(Q),message:Q?"Updated":"Not found"}}case"run":{let W=Y[0];if(!W)return U.sendMessage("用法:/schedule run <id>"),{success:!1,error:"Missing schedule id"};try{return await XO(W),U.sendMessage(`[OK] 已触发 \`${W}\``),{success:!0,message:"Schedule triggered"}}catch(Q){let O=Q instanceof Error?Q.message:String(Q);return U.sendMessage(`运行失败:${O}`),{success:!1,error:O}}}default:return U.sendMessage(`未知子命令: ${X}
1563
- 使用 /schedule 查看帮助`),{success:!1,error:`Unknown subcommand: ${X}`}}}}}var N7=YO();import*as H1 from"node:fs/promises";import*as W1 from"node:path";async function C7($,Z={}){let{maxResults:J=20,caseSensitive:U=!1,projectPath:X,storagePath:Y}=Z,H=Y??i1(X??L());if(!Y){let _=await HO($,X??L(),J,U);if(_)return _}let W;try{W=(await H1.readdir(H)).filter((G)=>G.endsWith(".jsonl")&&!G.startsWith("agent_")).map((G)=>W1.join(H,G))}catch{return[]}let O=(await Promise.all(W.map(async(_)=>{try{let G=await H1.stat(_);return{path:_,mtime:G.mtimeMs}}catch{return null}}))).filter((_)=>_!==null).sort((_,G)=>G.mtime-_.mtime).map((_)=>_.path),B=[],V=U?$:$.toLowerCase();for(let _ of O){if(B.length>=J)break;let G=W1.basename(_,".jsonl"),E=await WO(_,V,U,G);if(B.push(...E),B.length>=J){B.length=J;break}}return B}async function HO($,Z,J,U){try{let{syncAll:X}=await import("./chunk-sgnjekfb.js"),Y=await f7();if(!Y)return null;let{SessionService:H}=await import("./chunk-r14bz8va.js");await X(Y,H.projectionDeriverForSearch());let W=W1.resolve(Z),Q=M7(Y,$,W,J*4),O=U?$:$.toLowerCase(),B=[];for(let V of Q){if(V.role!=="user"&&V.role!=="assistant")continue;let _=E4(V.text,O,U,V.session_id,V.role,V.timestamp??void 0,0);if(_)B.push(_);if(B.length>=J)break}return B}catch{return null}}async function WO($,Z,J,U){try{let X=await H1.readFile($,"utf8"),H=X.split(`
1564
+ 使用 /schedule 查看帮助`),{success:!1,error:`Unknown subcommand: ${X}`}}}}}var N7=YO();import*as H1 from"node:fs/promises";import*as W1 from"node:path";async function C7($,Z={}){let{maxResults:J=20,caseSensitive:U=!1,projectPath:X,storagePath:Y}=Z,H=Y??i1(X??L());if(!Y){let _=await HO($,X??L(),J,U);if(_)return _}let W;try{W=(await H1.readdir(H)).filter((G)=>G.endsWith(".jsonl")&&!G.startsWith("agent_")).map((G)=>W1.join(H,G))}catch{return[]}let O=(await Promise.all(W.map(async(_)=>{try{let G=await H1.stat(_);return{path:_,mtime:G.mtimeMs}}catch{return null}}))).filter((_)=>_!==null).sort((_,G)=>G.mtime-_.mtime).map((_)=>_.path),B=[],V=U?$:$.toLowerCase();for(let _ of O){if(B.length>=J)break;let G=W1.basename(_,".jsonl"),E=await WO(_,V,U,G);if(B.push(...E),B.length>=J){B.length=J;break}}return B}async function HO($,Z,J,U){try{let{syncAll:X}=await import("./chunk-d6qktf17.js"),Y=await f7();if(!Y)return null;let{SessionService:H}=await import("./chunk-w0z7cn13.js");await X(Y,H.projectionDeriverForSearch());let W=W1.resolve(Z),Q=M7(Y,$,W,J*4),O=U?$:$.toLowerCase(),B=[];for(let V of Q){if(V.role!=="user"&&V.role!=="assistant")continue;let _=E4(V.text,O,U,V.session_id,V.role,V.timestamp??void 0,0);if(_)B.push(_);if(B.length>=J)break}return B}catch{return null}}async function WO($,Z,J,U){try{let X=await H1.readFile($,"utf8"),H=X.split(`
1564
1565
  `).flatMap((V,_)=>{if(!V.trim())return[];try{return[{event:JSON.parse(V),index:_}]}catch{return[]}});if(!H.some(({event:V})=>V.type==="session_created"))return QO(H,Z,J,U);let Q=new Map(H.flatMap(({event:V,index:_})=>typeof V.id==="string"?[[V.id,_+1]]:[])),O=T7(j7(X,$)),B=new Map;for(let V of O){if(V.type==="message_created"&&(V.data.role==="user"||V.data.role==="assistant"))B.set(V.data.messageId,{role:V.data.role,content:[],timestamp:V.timestamp,lineNumber:Q.get(V.id)??0});if(V.type==="part_created"&&V.data.partType==="text"){let _=B.get(V.data.messageId),G=V.data.payload.text;if(_&&typeof G==="string")_.content.push(G)}}return[...B.values()].flatMap((V)=>{let _=E4(V.content.join(" "),Z,J,U,V.role,V.timestamp,V.lineNumber);return _?[_]:[]})}catch{return[]}}function QO($,Z,J,U){return $.flatMap(({event:X,index:Y})=>{if(X.type!=="message")return[];let H=X.message;if(H?.role!=="user"&&H?.role!=="assistant"||!H.content)return[];let W=typeof H.content==="string"?H.content:Array.isArray(H.content)?H.content.filter((O)=>typeof O==="object"&&O!==null&&O.type==="text"&&typeof O.text==="string").map((O)=>O.text).join(" "):"",Q=E4(W,Z,J,U,H.role,typeof X.timestamp==="string"?X.timestamp:void 0,Y+1);return Q?[Q]:[]})}function E4($,Z,J,U,X,Y,H){if(!$)return;let W=J?$:$.toLowerCase();if(!W.includes(Z))return;let Q=W.indexOf(Z),O=Math.max(0,Q-80),B=Math.min($.length,Q+Z.length+80);return{sessionId:U,role:X,content:(O>0?"...":"")+$.slice(O,B).replace(/\n/g," ")+(B<$.length?"...":""),timestamp:Y,lineNumber:H}}function R7($){if($.length===0)return"没有找到匹配的历史记录";let Z=[`**找到 ${$.length} 条匹配:**
1565
1566
  `];for(let J of $){let U=J.timestamp?new Date(J.timestamp).toLocaleString("zh-CN",{timeZone:"Asia/Shanghai"}):"?",X=J.role==="user"?"\uD83D\uDC64":"\uD83E\uDD16";Z.push(`${X} \`${J.sessionId.slice(0,8)}\` (${U})`),Z.push(` ${J.content}`),Z.push("")}return Z.join(`
1566
1567
  `)}var OO={name:"search",description:"Search past session transcripts",fullDescription:"搜索历史会话记录,查找过去的对话内容",usage:"/search <keyword>",aliases:["find","history"],category:"Session",examples:['/search 断路器 - 搜索包含"断路器"的历史对话',"/search edit tool - 搜索 edit tool 相关讨论"],async handler($,Z){let J=I(Z);if($.length===0)return J.sendMessage("**用法:** `/search <关键词>`\n\n在历史会话中搜索包含指定关键词的对话"),{success:!0,message:"显示帮助"};let U=$.join(" ");J.sendMessage(`正在搜索: "${U}" ...`);try{let X=await C7(U,{maxResults:15,projectPath:Z.cwd}),Y=R7(X);return J.sendMessage(Y),{success:!0,message:`found ${X.length} results`,data:{matches:X.length}}}catch(X){let Y=X instanceof Error?X.message:"未知错误";return J.sendMessage(`搜索失败: ${Y}`),{success:!1,error:Y}}}},S7=OO;var BO={name:"skills",description:"查看所有可用的 Skills",fullDescription:"显示所有已发现的 Skills 及其详细信息,包括名称、描述、来源和允许的工具。",usage:"/skills",category:"system",examples:["/skills"],handler:async($,Z)=>{try{return await S0({cwd:Z.workspaceRoot??Z.cwd}).refresh(),p$(Z.workspaceRoot??Z.cwd),await g$(Z.workspaceRoot??Z.cwd),{success:!0,message:"show_skills_manager",data:{action:"show_skills_manager"}}}catch(J){let U=`获取 Skills 失败: ${J instanceof Error?J.message:"未知错误"}`;return P().addAssistantMessage(U),{success:!1,error:U}}}},P7=BO;import VO from"node:path";function U5($){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 k7($){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 I7($,Z){if($.length<=Z)return $;return $.slice(0,Z-3)+"..."}async function _O($,Z){let J=I(Z),U=$[0],X=s.getInstance(),Y=t.getInstance(),H=Z.sessionId??"",W=Z.sessionId?{sessionId:Z.sessionId,projectPath:VO.resolve(Z.workspaceRoot??Z.cwd)}:void 0;if(U==="resume"){let G=$[1],E=$.slice(2).join(" ").trim();if(!G||!E)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 K=await Z.subagents.resume(G,E),w=`Resumed \`${G}\` as \`${K.session.id}\` (depth ${K.session.resumeDepth}).`;return J.sendMessage(w),{success:!0,message:w,data:{action:"subagent_resumed",sourceAgentId:G,subagent:K.session}}}if(U==="clean"){let G=Y.cleanupExpiredSessionsForParent(W??H,0);return J.sendMessage(`已清理 ${G} 个已完成的 Agent 会话`),{success:!0,message:`Cleaned ${G} agent sessions`}}let Q=[`**后台任务列表**
@@ -1,3 +1,3 @@
1
- import{Uf as $,Vf as F}from"./chunk-s14wmzm3.js";import{promises as J}from"node:fs";import Q from"node:path";import{Mutex as U}from"async-mutex";import w from"write-file-atomic";var X=1;function D(k){if(!k||typeof k!=="object"||Array.isArray(k))return!1;let q=k;return typeof q.path==="string"&&Q.isAbsolute(q.path)&&typeof q.boundAt==="string"}async function Z(k){if(!Q.isAbsolute(k))throw Error("Project path must be absolute");let q=await J.realpath(k);if(!(await J.stat(q)).isDirectory())throw Error("Project path must be a directory");return q}class K{filePath;mutex=new U;constructor(k=Q.join(F(),"bound-projects.json")){this.filePath=k}async list(k){let q=await this.read(),z=await Z(k),H=new Map;for(let C of q.projects)H.set(C.path,C);if(!H.has(z))H.set(z,{path:z,boundAt:new Date(0).toISOString()});return(await Promise.all([...H.values()].map(async(C)=>{let L=!1;try{L=(await J.stat(C.path)).isDirectory()}catch{}return{path:C.path,name:Q.basename(C.path)||C.path,...L?{gitBranch:$(C.path)}:{},available:L,isCurrent:C.path===z,boundAt:C.boundAt}}))).sort((C,L)=>{if(C.isCurrent!==L.isCurrent)return C.isCurrent?-1:1;return C.name.localeCompare(L.name)})}async bind(k,q){return this.mutex.runExclusive(async()=>{let z=await Z(k),H=await this.read(),W=H.projects.find((M)=>M.path===z),C=W??{path:z,boundAt:new Date().toISOString()};if(!W)H.projects.push(C),await this.write(H);let L=await Z(q),A=$(z);return{path:z,name:Q.basename(z)||z,...A?{gitBranch:A}:{},available:!0,isCurrent:z===L,boundAt:C.boundAt}})}async unbind(k){return this.mutex.runExclusive(async()=>{if(!Q.isAbsolute(k))throw Error("Project path must be absolute");let q=await J.realpath(k).catch(()=>Q.resolve(k)),z=await this.read(),H=z.projects.filter((W)=>W.path!==q);if(H.length===z.projects.length)return!1;return z.projects=H,await this.write(z),!0})}async read(){try{let k=await J.readFile(this.filePath,"utf8"),q=JSON.parse(k);if(q.version!==X||!Array.isArray(q.projects))return{version:X,projects:[]};return{version:X,projects:q.projects.filter(D)}}catch(k){if(k.code==="ENOENT"||k instanceof SyntaxError)return{version:X,projects:[]};throw k}}async write(k){let q=Q.dirname(this.filePath);await J.mkdir(q,{recursive:!0,mode:448}),await J.chmod(q,448),await w(this.filePath,`${JSON.stringify(k,null,2)}
1
+ import{Tf as $,Uf as F}from"./chunk-vjrn667c.js";import{promises as J}from"node:fs";import Q from"node:path";import{Mutex as U}from"async-mutex";import w from"write-file-atomic";var X=1;function D(k){if(!k||typeof k!=="object"||Array.isArray(k))return!1;let q=k;return typeof q.path==="string"&&Q.isAbsolute(q.path)&&typeof q.boundAt==="string"}async function Z(k){if(!Q.isAbsolute(k))throw Error("Project path must be absolute");let q=await J.realpath(k);if(!(await J.stat(q)).isDirectory())throw Error("Project path must be a directory");return q}class K{filePath;mutex=new U;constructor(k=Q.join(F(),"bound-projects.json")){this.filePath=k}async list(k){let q=await this.read(),z=await Z(k),H=new Map;for(let C of q.projects)H.set(C.path,C);if(!H.has(z))H.set(z,{path:z,boundAt:new Date(0).toISOString()});return(await Promise.all([...H.values()].map(async(C)=>{let L=!1;try{L=(await J.stat(C.path)).isDirectory()}catch{}return{path:C.path,name:Q.basename(C.path)||C.path,...L?{gitBranch:$(C.path)}:{},available:L,isCurrent:C.path===z,boundAt:C.boundAt}}))).sort((C,L)=>{if(C.isCurrent!==L.isCurrent)return C.isCurrent?-1:1;return C.name.localeCompare(L.name)})}async bind(k,q){return this.mutex.runExclusive(async()=>{let z=await Z(k),H=await this.read(),W=H.projects.find((M)=>M.path===z),C=W??{path:z,boundAt:new Date().toISOString()};if(!W)H.projects.push(C),await this.write(H);let L=await Z(q),A=$(z);return{path:z,name:Q.basename(z)||z,...A?{gitBranch:A}:{},available:!0,isCurrent:z===L,boundAt:C.boundAt}})}async unbind(k){return this.mutex.runExclusive(async()=>{if(!Q.isAbsolute(k))throw Error("Project path must be absolute");let q=await J.realpath(k).catch(()=>Q.resolve(k)),z=await this.read(),H=z.projects.filter((W)=>W.path!==q);if(H.length===z.projects.length)return!1;return z.projects=H,await this.write(z),!0})}async read(){try{let k=await J.readFile(this.filePath,"utf8"),q=JSON.parse(k);if(q.version!==X||!Array.isArray(q.projects))return{version:X,projects:[]};return{version:X,projects:q.projects.filter(D)}}catch(k){if(k.code==="ENOENT"||k instanceof SyntaxError)return{version:X,projects:[]};throw k}}async write(k){let q=Q.dirname(this.filePath);await J.mkdir(q,{recursive:!0,mode:448}),await J.chmod(q,448),await w(this.filePath,`${JSON.stringify(k,null,2)}
2
2
  `,{mode:384}),await J.chmod(this.filePath,384)}}var _=new K;
3
3
  export{_ as l};
@@ -0,0 +1 @@
1
+ import{Kf as a}from"./chunk-6vhc5gdf.js";import"./chunk-qdngw7h1.js";import"./chunk-vjrn667c.js";import"./chunk-86g3xxx7.js";export{a as WorkspaceTrustService};
@@ -0,0 +1 @@
1
+ import{a as o}from"./chunk-rhcts0qe.js";import"./chunk-9gtc0kd2.js";import"./chunk-86g3xxx7.js";import{execSync as r}from"child_process";var l={command:"update",describe:"Check for updates and install if available",handler:async()=>{console.log("Checking for updates...");try{let e=await o(!0);if(console.log(`Current version: ${e.currentVersion}`),e.error){console.log(`Warning: ${e.error}`);return}if(e.latestVersion)console.log(`Latest version: ${e.latestVersion}`);if(e.hasUpdate&&e.latestVersion){console.log(""),console.log(`\x1B[33mUpdate available: ${e.currentVersion} -> ${e.latestVersion}\x1B[0m`),console.log(""),console.log("Updating...");try{r("npm install -g blade-code@latest --registry https://registry.npmjs.org",{stdio:"inherit"}),console.log(""),console.log("Update complete!")}catch(t){console.error("Error: Update failed. Please run manually:"),console.error(" npm install -g blade-code@latest"),process.exit(1)}}else console.log("You are running the latest version of Blade")}catch(e){console.error(`Error: Failed to check for updates: ${e instanceof Error?e.message:"未知错误"}`),process.exit(1)}}};export{l as updateCommands};
@@ -0,0 +1 @@
1
+ import{f as y,g as A,h as C,i as D}from"./chunk-qnsj1pp3.js";import"./chunk-fg1t369y.js";import"./chunk-15edqtyv.js";import"./chunk-65pe5x3a.js";import"./chunk-saneyjmy.js";import"./chunk-10yas08a.js";import"./chunk-b22x3h7k.js";import"./chunk-5dr18jzd.js";import"./chunk-a0ga35qv.js";import"./chunk-4dnvydyv.js";import"./chunk-vbsk6mjn.js";import"./chunk-nwg0bpex.js";import"./chunk-xjq1htyt.js";import{ad as q}from"./chunk-wbvs2tv5.js";import"./chunk-v508x7cg.js";import"./chunk-xjqcc0nt.js";import"./chunk-0t0dsepx.js";import"./chunk-763aam58.js";import"./chunk-m27w377p.js";import"./chunk-mmw7jbxg.js";import"./chunk-rb7aayp5.js";import"./chunk-5xph8r1k.js";import"./chunk-5sw8j9ae.js";import"./chunk-18n15nn8.js";import"./chunk-wyq21fev.js";import"./chunk-6pb6zs96.js";import"./chunk-565weg3f.js";import"./chunk-58wxa5cj.js";import"./chunk-r561wfcz.js";import"./chunk-0qayfsc9.js";import"./chunk-dbb20rxh.js";import"./chunk-awwe1rqb.js";import"./chunk-7tea6e9y.js";import"./chunk-9tp00s2z.js";import"./chunk-9gtc0kd2.js";import"./chunk-6vhc5gdf.js";import"./chunk-qdngw7h1.js";import"./chunk-vjrn667c.js";import"./chunk-86g3xxx7.js";import H from"chalk";var R={command:"serve",describe:"Start a headless Blade server (no browser)",builder:y,handler:async(E)=>{let f=A(E);if(await q(),!process.env.BLADE_SERVER_PASSWORD)console.log(H.yellow("Warning: BLADE_SERVER_PASSWORD is not set; server is unsecured."));let b=await D.listenAsync(f);if(console.log(`Blade server listening on http://${b.hostname}:${b.port}`),f.hostname==="0.0.0.0"){let F=C();for(let G of F)console.log(` Network: http://${G}:${b.port}`)}await new Promise(()=>{}),await b.stop()}};export{R as serveCommand};
@@ -0,0 +1,6 @@
1
+ import{m as Yq,n as Zq,o as $q,p as Vq,q as Bq}from"./chunk-k89zf5h1.js";import{s as Xq}from"./chunk-saneyjmy.js";import{F as r,H as a,I as o,K as y,L as n}from"./chunk-10yas08a.js";import"./chunk-b22x3h7k.js";import"./chunk-5dr18jzd.js";import{$a as i,Ma as v,ib as s}from"./chunk-a0ga35qv.js";import"./chunk-4dnvydyv.js";import{Xb as S,gc as h}from"./chunk-vbsk6mjn.js";import"./chunk-nwg0bpex.js";import{zc as e}from"./chunk-qy36y9xc.js";import{Bc as qq,Cc as Gq,Dc as Qq}from"./chunk-whxmvh0n.js";import{Ec as t}from"./chunk-m3ya6rtr.js";import"./chunk-xjq1htyt.js";import{cd as l}from"./chunk-wbvs2tv5.js";import"./chunk-v508x7cg.js";import"./chunk-xjqcc0nt.js";import"./chunk-0t0dsepx.js";import"./chunk-763aam58.js";import"./chunk-m27w377p.js";import"./chunk-mmw7jbxg.js";import"./chunk-rb7aayp5.js";import"./chunk-5xph8r1k.js";import"./chunk-5sw8j9ae.js";import"./chunk-18n15nn8.js";import"./chunk-wyq21fev.js";import"./chunk-6pb6zs96.js";import"./chunk-565weg3f.js";import{af as m}from"./chunk-58wxa5cj.js";import{bf as u,df as G,ef as w,gf as j}from"./chunk-r561wfcz.js";import"./chunk-0qayfsc9.js";import{nf as I}from"./chunk-dbb20rxh.js";import"./chunk-awwe1rqb.js";import"./chunk-7tea6e9y.js";import"./chunk-9tp00s2z.js";import"./chunk-9gtc0kd2.js";import"./chunk-6vhc5gdf.js";import"./chunk-qdngw7h1.js";import"./chunk-vjrn667c.js";import"./chunk-86g3xxx7.js";import oq from"yargs";import{hideBin as nq}from"yargs/helpers";var g=1;function K(Q){return G.Object({event_version:G.Literal(g),...Q})}var zq=K({type:G.Literal("content_delta"),delta:G.String()}),Uq=K({type:G.Literal("thinking_delta"),delta:G.String()}),Rq=K({type:G.Literal("thinking"),content:G.String()}),Mq=K({type:G.Literal("stream_end")}),Pq=K({type:G.Literal("content"),content:G.String()}),Nq=K({type:G.Literal("structured_output"),output:G.Record(G.String(),G.Unknown()),schema_digest:G.String({pattern:"^[a-f0-9]{64}$"})}),T=j(["readonly","write","execute"]),fq=K({type:G.Literal("tool_start"),tool_name:G.String(),summary:G.String(),target:G.Optional(G.String()),tool_kind:G.Optional(T)}),Eq=K({type:G.Literal("tool_progress"),tool_name:G.String(),message:G.String(),progress:G.Optional(G.Number()),total:G.Optional(G.Number())}),xq=K({type:G.Literal("tool_result"),tool_name:G.String(),summary:G.String(),target:G.Optional(G.String()),tool_kind:G.Optional(T),success:G.Optional(G.Boolean()),error_type:G.Optional(G.String()),error_message:G.Optional(G.String())}),Iq=K({type:G.Literal("mcp_catalog_changed"),revision:G.Integer({minimum:1}),server_name:G.String(),added:G.Array(G.String()),removed:G.Array(G.String()),updated:G.Array(G.String())}),Jq=K({type:G.Literal("mcp_content_changed"),revision:G.Integer({minimum:1}),server_name:G.String(),content_kind:j(["resources","resource_templates","prompts"]),added:G.Array(G.String()),removed:G.Array(G.String()),updated:G.Array(G.String())}),Lq=K({type:G.Literal("mcp_resource_updated"),revision:G.Integer({minimum:1}),server_name:G.String(),uri:G.String()}),Wq=K({type:G.Literal("mcp_connection_changed"),revision:G.Integer({minimum:1}),server_name:G.String(),phase:j(["reconnecting","recovered","failed"]),reason:G.String(),attempt:G.Integer({minimum:0}),max_attempts:G.Integer({minimum:0}),next_retry_at:G.Optional(G.Integer({minimum:0})),error:G.Optional(G.String())}),Sq=K({type:G.Literal("mcp_log"),revision:G.Integer({minimum:1}),server_name:G.String(),level:j(["debug","info","notice","warning","error","critical","alert","emergency"]),logger:G.Optional(G.String()),message:G.String(),projected_bytes:G.Integer({minimum:0}),data_sha256:G.String(),truncated:G.Boolean(),details_omitted:G.Boolean(),timestamp:G.Integer({minimum:0}),synthetic:G.Optional(G.Boolean())}),Oq=K({type:G.Literal("mcp_instructions_changed"),revision:G.Integer({minimum:0}),server_name:G.String(),action:j(["added","removed"]),reason:j(["snapshot","connection","disconnection"]),text:G.Optional(G.String()),source_bytes:G.Optional(G.Integer({minimum:0})),projected_bytes:G.Optional(G.Integer({minimum:0})),sha256:G.Optional(G.String()),truncated:G.Optional(G.Boolean()),details_omitted:G.Optional(G.Boolean())}),hq=K({type:G.Literal("mcp_task_changed"),revision:G.Integer({minimum:0}),task_id:G.String(),server_name:G.String(),tool_name:G.String(),status:j(["working","input_required","interrupted","completed","failed","cancelled"]),status_message:G.Optional(G.String()),created_at:G.Integer({minimum:0}),updated_at:G.Integer({minimum:0}),completed_at:G.Optional(G.Integer({minimum:0})),has_result:G.Boolean(),error:G.Optional(G.String())}),Cq=K({type:G.Literal("project_rules_loaded"),files:G.Array(G.Object({id:G.String(),relative_path:G.String(),source:j(["project","local"]),conditional:G.Boolean(),content_sha256:G.String({pattern:"^[a-f0-9]{64}$"})})),trigger_paths:G.Array(G.String()),blocked_write:G.Boolean()}),kq=K({type:G.Literal("user_shell_started"),execution_id:G.String(),command:G.String(),auxiliary:G.Boolean()}),Fq=K({type:G.Literal("user_shell_output"),execution_id:G.String(),stream:j(["stdout","stderr"]),chunk:G.String(),stream_truncated:G.Boolean()}),wq=K({type:G.Literal("user_shell_completed"),execution_id:G.String(),message_id:G.String(),status:j(["completed","failed","aborted","timed_out","spawn_error"]),exit_code:G.Union([G.Integer(),G.Null()]),duration_ms:G.Number({minimum:0}),stdout:G.String(),stderr:G.String(),truncated:G.Boolean(),auxiliary:G.Boolean()}),yq=K({type:G.Literal("phase"),phase:j(["turn","searching","inspecting","target_hit","executing","completed"]),status:j(["ongoing","hit","done"]),message:G.String(),turn:G.Optional(G.Number()),tool_name:G.Optional(G.String()),target:G.Optional(G.String())}),gq=K({type:G.Literal("tool_detail"),tool_name:G.String(),detail:G.String()}),Tq=K({type:G.Literal("task_update"),tasks:G.Array(y)}),cq=K({type:G.Literal("goal"),state:j(["updated","cleared"]),goal_id:G.Optional(G.String()),status:G.Optional(j(["active","verifying","paused","blocked","usage_limited","budget_limited","complete"])),verification_attempt:G.Optional(G.Integer({minimum:1})),verification_status:G.Optional(j(["pending","pass","fail","partial"])),verifier_session_id:G.Optional(G.String()),verification_evidence_sha256:G.Optional(G.String({pattern:"^[a-f0-9]{64}$"}))}),dq=K({type:G.Literal("subagent"),state:j(["spawned","completed"]),session_id:G.String(),subagent_type:G.Optional(G.String()),success:G.Optional(G.Boolean()),summary:G.Optional(G.String()),verification_verdict:G.Optional(j(["pass","fail","partial"])),resumed_from:G.Optional(G.String()),root_agent_id:G.Optional(G.String()),resume_depth:G.Optional(G.Integer({minimum:0}))}),pq=K({type:G.Literal("token_usage"),input_tokens:G.Number(),output_tokens:G.Number(),total_tokens:G.Number(),max_context_tokens:G.Number(),cache_read_tokens:G.Optional(G.Number()),cache_write_tokens:G.Optional(G.Number()),cost_usd:G.Optional(G.Number())}),mq=K({type:G.Literal("compacting"),state:j(["started","completed"]),reason:G.Optional(j(["threshold","context_limit","turn_limit","manual"])),strategy:G.Optional(j(["llm","fallback","snip"])),outcome:G.Optional(j(["completed","fallback","failed"])),pre_tokens:G.Optional(G.Number({minimum:0})),post_tokens:G.Optional(G.Number({minimum:0}))}),uq=K({type:G.Literal("provider_retry"),phase:j(["scheduled","attempt","recovered","exhausted"]),attempt:G.Integer({minimum:0}),max_retries:G.Integer({minimum:0}),reason:j(["rate_limit","server_error","timeout","transport","stream_closed"]),status_code:G.Optional(G.Integer({minimum:100,maximum:599})),delay_ms:G.Optional(G.Integer({minimum:0})),next_retry_at:G.Optional(G.Integer({minimum:0}))}),lq=K({type:G.Literal("provider_stall"),phase:j(["detected","recovered"]),stall_count:G.Integer({minimum:1}),duration_ms:G.Integer({minimum:0}),warning_after_ms:G.Integer({minimum:1}),timeout_ms:G.Integer({minimum:1}),output_started:G.Boolean()}),vq=K({type:G.Literal("turn_limit"),turns_count:G.Number(),action:G.Literal("continue")}),iq=K({type:G.Literal("task_session"),session_id:G.String(),project_path:G.String(),source_project_path:G.String(),isolation:j(["local","worktree"]),worktree_branch:G.Optional(G.String()),base_commit:G.Optional(G.String())}),sq=K({type:G.Literal("task_admission"),state:j(["queued","running"]),queue_position:G.Optional(G.Integer({minimum:1})),queue_depth:G.Integer({minimum:0}),in_flight:G.Integer({minimum:0}),max_concurrent_tasks:G.Integer({minimum:1})}),rq=K({type:G.Literal("output"),content:G.String(),exit_code:G.Number()}),aq=K({type:G.Literal("error"),message:G.String()}),HG=w(G.Union([zq,Uq,Rq,Mq,Pq,Nq,fq,Eq,xq,Iq,Jq,Lq,Wq,Sq,Oq,hq,Cq,kq,Fq,wq,yq,gq,Tq,cq,dq,pq,mq,uq,lq,vq,iq,sq,rq,aq]));function c(Q,X){return{event_version:g,type:Q,...X}}function tq(Q){if(Q?.signal)return{signal:Q.signal,dispose:()=>{return}};let X=new AbortController,H=()=>X.abort("interrupt");return process.once("SIGINT",H),process.once("SIGTERM",H),{signal:X.signal,dispose:()=>{process.removeListener("SIGINT",H),process.removeListener("SIGTERM",H)}}}var eq=j(["text","jsonl"]),qG=G.Object({headless:G.Optional(G.Boolean()),message:G.Optional(G.String()),_:G.Optional(G.Array(G.Union([G.String(),G.Number()]))),model:G.Optional(G.String()),systemPrompt:G.Optional(G.String()),appendSystemPrompt:G.Optional(G.String()),verificationAgent:G.Optional(G.Boolean()),maxTurns:G.Optional(G.Refine(G.Integer(),(Q)=>Q===-1||Q>0,()=>"must be -1 (unlimited) or a positive integer")),permissionMode:G.Optional(G.Enum(m)),mcpConfig:G.Optional(G.Array(G.String())),strictMcpConfig:G.Optional(G.Boolean()),sessionId:G.Optional(G.String()),allowedTools:G.Optional(G.Array(G.String())),disallowedTools:G.Optional(G.Array(G.String())),agents:G.Optional(G.String()),continue:G.Optional(G.Boolean()),resume:G.Optional(G.Union([G.String(),G.Boolean()])),forkSession:G.Optional(G.Boolean()),taskIsolation:G.Optional(j(["local","worktree"])),outputFormat:G.Optional(eq),jsonSchema:G.Optional(G.String()),outputSchema:G.Optional(G.String())});class Kq{openedThinking=!1;wroteAssistantContent=!1;markAssistantContent(){this.wroteAssistantContent=!0}setThinkingOpened(Q){this.openedThinking=Q}hasOpenThinking(){return this.openedThinking}completeStream(){let Q={openedThinking:this.openedThinking,wroteAssistantContent:this.wroteAssistantContent};return this.openedThinking=!1,this.wroteAssistantContent=!1,Q}}function GG(Q){return Q.issues.map((X)=>`${X.path.join(".")||"options"}: ${X.message}`).join("; ")}function QG(Q){let X=u(qG,Q);if(!X.success)throw Error(`Invalid headless options: ${GG(X.error)}`);return X.data}function XG(Q){return Q.command("* [message]","Run full agent loop without Ink UI and print events to the terminal",(X)=>X.positional("message",{describe:"Message to process",type:"string"}).option("headless",{type:"boolean",describe:"Run full agent loop without Ink UI and print events to the terminal"}).option("model",{describe:"Model ID for this run",type:"string"}).option("system-prompt",{describe:"Replace the default system prompt",type:"string"}).option("append-system-prompt",{describe:"Append a system prompt to the default system prompt",type:"string"}).option("verification-agent",{describe:"Run the built-in independent verification agent after non-trivial changes",type:"boolean",default:!0}).option("max-turns",{alias:["maxTurns"],describe:"Maximum conversation turns (-1: unlimited, N>0: limit to N turns)",type:"number"}).option("output-format",{alias:["outputFormat"],choices:["text","jsonl"],describe:"Headless output format",type:"string"}).option("json-schema",{alias:["jsonSchema"],describe:"Inline JSON Schema for the structured final response",type:"string"}).option("output-schema",{alias:["outputSchema"],describe:"Path to a JSON Schema file for the structured final response",type:"string"}).option("task-isolation",{alias:["taskIsolation"],choices:["local","worktree"],describe:"Dispatch a new durable task in the selected workspace mode",type:"string"}),async(X)=>{if(!X.headless)return;let H=await KG(X);process.exit(H)})}function D(Q,X=""){Q.write(`${X}
2
+ `)}function YG(Q){return`[task] [${Q.status}] ${Q.subject}`}function ZG(){return{requestConfirmation:async(Q)=>Q.type==="mcpElicitation"?{approved:!1,reason:"headless-mcp-elicitation-unavailable",elicitation:{action:"cancel"}}:Q.type==="mcpSampling"?{approved:!1,reason:"headless-mcp-sampling-unavailable"}:{approved:!0,reason:"headless-auto-approved",scope:"session"}}}function $G(Q){if(!(Q instanceof Error))return"Unknown error";let $=Q.lastError??Q;if($.responseBody)try{let b=JSON.parse($.responseBody)?.error?.message;if(b)return $.statusCode?`${b} (HTTP ${$.statusCode})`:b}catch{}let q=Q.message.match(/Last error:\s*(.+)$/);if(q)return q[1];return Q.message}function VG(Q){return Q==="jsonl"?"jsonl":"text"}function d(Q,X){let H=(...$)=>{for(let q of $){let Y=X[q];if(typeof Y==="string"&&Y.trim()!=="")return Y}return};switch(Q){case"Read":case"Edit":case"Write":case"UndoEdit":return H("file_path");case"ApplyPatch":return"multi-file patch";case"NotebookEdit":return H("notebook_path");case"Grep":return H("path","pattern");case"Glob":return H("pattern");case"WebFetch":return H("url");case"WebSearch":return H("query");case"Bash":return H("command","description");case"Task":return H("description");case"LSP":return H("filePath","operation");case"EnterWorktree":return H("name");case"ExitWorktree":return H("action");default:return}}function BG(Q,X,H,$){let q=new Set(["Glob","Grep","WebSearch","LS"]),Y=new Set(["Read","WebFetch"]);if(new Set(["Edit","Write","ApplyPatch","NotebookEdit","Bash","LSP","UndoEdit","EnterWorktree","ExitWorktree"]).has(Q)&&!$.targetLocked)return{phase:"target_hit",status:"hit",message:`Target locked: ${X}`,shouldLockTarget:!0};if($.targetLocked)return{phase:"executing",status:"hit",message:H?`Working within target: ${X}`:`Executing: ${X}`,shouldLockTarget:!1};if(q.has(Q))return{phase:"searching",status:"ongoing",message:`Still searching: ${X}`,shouldLockTarget:!1};if(Y.has(Q))return{phase:"inspecting",status:"ongoing",message:`Inspecting candidate: ${X}`,shouldLockTarget:!1};return{phase:"executing",status:$.targetLocked?"hit":"ongoing",message:`Executing: ${X}`,shouldLockTarget:!1}}function p(Q,X,H=!1){let $=(q,Y)=>{Q.stdout.write(`${JSON.stringify(c(q,Y))}
3
+ `)};return{contentDelta(q){if(X==="jsonl"){$("content_delta",{delta:q});return}if(H)return;Q.stdout.write(q)},thinkingDelta(q,Y){if(X==="jsonl")return $("thinking_delta",{delta:q}),Y;if(!Y)Q.stderr.write("[thinking] ");return Q.stderr.write(q),!0},thinking(q){if(X==="jsonl"){$("thinking",{content:q});return}D(Q.stderr,`[thinking] ${q}`)},streamEnd(q,Y){if(X==="jsonl"){$("stream_end",{});return}if(Y)Q.stderr.write(`
4
+ `);if(q)Q.stdout.write(`
5
+ `)},content(q){if(X==="jsonl"){$("content",{content:q});return}D(Q.stdout,q)},structuredOutput(q){if(X==="jsonl"){$("structured_output",{output:q.output,schema_digest:q.schemaDigest});return}D(Q.stdout,JSON.stringify(q.output))},toolStart(q,Y,b,_){if(X==="jsonl"){$("tool_start",{tool_name:q,summary:Y,target:b,tool_kind:_});return}D(Q.stderr,`[tool:start] ${Y}`)},toolProgress(q,Y,b,_){if(X==="jsonl"){$("tool_progress",{tool_name:q,message:Y,progress:b,total:_});return}D(Q.stderr,`[tool:progress] ${q}: ${Y}`)},toolResult(q,Y,b,_,R){if(X==="jsonl"){$("tool_result",{tool_name:q,summary:Y,target:b,tool_kind:_,success:R?.success,error_type:R?.errorType,error_message:R?.errorMessage});return}D(Q.stderr,`[tool:result] ${Y}`)},mcpCatalogChanged(q){if(X==="jsonl"){$("mcp_catalog_changed",{revision:q.revision,server_name:q.serverName,added:q.added,removed:q.removed,updated:q.updated});return}D(Q.stderr,`[mcp:catalog] r${q.revision} ${q.serverName} +${q.added.length} -${q.removed.length} ~${q.updated.length}`)},mcpContentChanged(q){if(X==="jsonl"){$("mcp_content_changed",{revision:q.revision,server_name:q.serverName,content_kind:q.contentKind==="resourceTemplates"?"resource_templates":q.contentKind,added:q.added,removed:q.removed,updated:q.updated});return}D(Q.stderr,`[mcp:${q.contentKind}] r${q.revision} ${q.serverName} +${q.added.length} -${q.removed.length} ~${q.updated.length}`)},mcpResourceUpdated(q){if(X==="jsonl"){$("mcp_resource_updated",{revision:q.revision,server_name:q.serverName,uri:q.uri});return}D(Q.stderr,`[mcp:resource] r${q.revision} ${q.serverName} updated ${q.uri}`)},mcpConnectionChanged(q){if(X==="jsonl"){$("mcp_connection_changed",{revision:q.revision,server_name:q.serverName,phase:q.phase,reason:q.reason,attempt:q.attempt,max_attempts:q.maxAttempts,...q.nextRetryAt!==void 0?{next_retry_at:q.nextRetryAt}:{},...q.error?{error:q.error}:{}});return}D(Q.stderr,`[mcp:connection] r${q.revision} ${q.serverName} ${q.phase} ${q.attempt}/${q.maxAttempts}`)},mcpLog(q){if(X==="jsonl"){$("mcp_log",{revision:q.revision,server_name:q.serverName,level:q.level,logger:q.logger,message:q.message,projected_bytes:q.projectedBytes,data_sha256:q.dataSha256,truncated:q.truncated,details_omitted:q.detailsOmitted,timestamp:q.timestamp,synthetic:q.synthetic});return}D(Q.stderr,`[mcp:log] ${q.level} ${q.serverName}${q.logger?` logger=${q.logger}`:""}: ${q.message}`)},mcpInstructionsChanged(q){if(X==="jsonl"){$("mcp_instructions_changed",{revision:q.revision,server_name:q.serverName,action:q.action,reason:q.reason,text:q.text,source_bytes:q.sourceBytes,projected_bytes:q.projectedBytes,sha256:q.sha256,truncated:q.truncated,details_omitted:q.detailsOmitted});return}D(Q.stderr,`[mcp:instructions] ${q.action} ${q.serverName}${q.truncated?" (truncated)":""}`)},mcpTaskChanged(q){if(X==="jsonl"){$("mcp_task_changed",{revision:q.revision,task_id:q.taskId,server_name:q.serverName,tool_name:q.toolName,status:q.status,status_message:q.statusMessage,created_at:q.createdAt,updated_at:q.updatedAt,completed_at:q.completedAt,has_result:q.hasResult,error:q.error});return}D(Q.stderr,`[mcp:task] ${q.taskId} ${q.serverName}/${q.toolName} `+q.status)},projectRulesLoaded(q){if(X==="jsonl"){$("project_rules_loaded",{files:q.files.map((Y)=>({id:Y.id,relative_path:Y.relativePath,source:Y.source,conditional:Y.conditional,content_sha256:Y.contentSha256})),trigger_paths:q.triggerPaths,blocked_write:q.blockedWrite});return}D(Q.stderr,`[project-rules] loaded ${q.files.length} file(s)${q.blockedWrite?" before write":""}`)},userShellStarted(q,Y,b){if(X==="jsonl"){$("user_shell_started",{execution_id:q,command:Y,auxiliary:b});return}D(Q.stderr,`[user-shell:start] ${Y}`)},userShellOutput(q,Y,b,_){if(X==="jsonl"){$("user_shell_output",{execution_id:q,stream:Y,chunk:b,stream_truncated:_});return}(Y==="stderr"?Q.stderr:Q.stdout).write(b)},userShellCompleted(q){if(X==="jsonl"){$("user_shell_completed",{execution_id:q.executionId,message_id:q.messageId,status:q.record.status,exit_code:q.record.exitCode,duration_ms:q.record.durationMs,stdout:q.record.stdout,stderr:q.record.stderr,truncated:q.record.truncated,auxiliary:q.auxiliary});return}D(Q.stderr,`[user-shell:${q.record.status}] exit=${q.record.exitCode??"null"} ${q.record.durationMs}ms`)},phase(q,Y,b,_={}){if(X==="jsonl"){$("phase",{phase:q,status:Y,message:b,turn:_.turn,tool_name:_.toolName,target:_.target});return}D(Q.stderr,`[phase:${q}] ${b}`)},toolDetail(q,Y){if(X==="jsonl"){$("tool_detail",{tool_name:q,detail:Y});return}D(Q.stderr,Y)},taskUpdate(q){if(X==="jsonl"){$("task_update",{tasks:q});return}for(let Y of q)D(Q.stderr,YG(Y))},goal(q){if(X==="jsonl"){$("goal",{state:q.goal?"updated":"cleared",goal_id:q.goal?.goalId,status:q.goal?.status,verification_attempt:q.goal?.completionVerification?.attempt,verification_status:q.goal?.completionVerification?.status,verifier_session_id:q.goal?.completionVerification?.verifierSessionId,verification_evidence_sha256:q.goal?.completionVerification?.evidenceSha256});return}if(q.goal)D(Q.stderr,`[goal:${q.goal.status}] ${q.goal.objective}`);else D(Q.stderr,"[goal:cleared]")},subagent(q){let Y=q.kind==="subagent_spawned";if(X==="jsonl"){$("subagent",{state:Y?"spawned":"completed",session_id:q.sessionId,subagent_type:q.type,success:Y?void 0:q.success,summary:Y?void 0:q.summary,verification_verdict:Y?void 0:q.verificationVerdict,resumed_from:q.resumedFrom,root_agent_id:q.rootAgentId,resume_depth:q.resumeDepth});return}D(Q.stderr,`[subagent:${Y?"spawned":"completed"}] ${q.sessionId}${q.resumedFrom?` resumed from ${q.resumedFrom}`:""}`)},tokenUsage(q){if(X==="jsonl"){$("token_usage",{input_tokens:q.inputTokens,output_tokens:q.outputTokens,total_tokens:q.totalTokens,max_context_tokens:q.maxContextTokens,cache_read_tokens:q.cacheReadTokens,cache_write_tokens:q.cacheWriteTokens,cost_usd:q.costUsd});return}D(Q.stderr,`[tokens] in=${q.inputTokens} out=${q.outputTokens} total=${q.totalTokens} / ${q.maxContextTokens}`)},compacting(q){let Y=q.phase==="start";if(X==="jsonl"){$("compacting",{state:Y?"started":"completed",reason:q.reason,strategy:q.strategy,outcome:q.outcome,pre_tokens:q.preTokens,post_tokens:q.postTokens});return}D(Q.stderr,Y?`[context] compacting started${q.reason?` (${q.reason})`:""}`:`[context] compacting ${q.outcome??"completed"}`)},providerRetry(q){if(X==="jsonl"){$("provider_retry",{phase:q.phase,attempt:q.attempt,max_retries:q.maxRetries,reason:q.reason,status_code:q.statusCode,delay_ms:q.delayMs,next_retry_at:q.nextRetryAt});return}let Y=q.delayMs!==void 0?` in ${Math.max(0,Math.ceil(q.delayMs/1000))}s`:"";D(Q.stderr,`[provider-retry:${q.phase}] ${q.attempt}/${q.maxRetries} ${q.reason}${Y}`)},providerStall(q){if(X==="jsonl"){$("provider_stall",{phase:q.phase,stall_count:q.stallCount,duration_ms:q.durationMs,warning_after_ms:q.warningAfterMs,timeout_ms:q.timeoutMs,output_started:q.outputStarted});return}D(Q.stderr,`[provider-stall:${q.phase}] ${q.durationMs}ms / ${q.timeoutMs}ms`)},turnLimit(q){if(X==="jsonl"){$("turn_limit",{turns_count:q,action:"continue"});return}D(Q.stderr,`[turn-limit] continuing after ${q} turns`)},taskSession(q){if(X==="jsonl"){$("task_session",{session_id:q.sessionId,project_path:q.projectPath,source_project_path:q.sourceProjectPath,isolation:q.isolation,worktree_branch:q.worktreeBranch,base_commit:q.baseCommit});return}D(Q.stderr,`[task:${q.isolation}] ${q.sessionId} ${q.sourceProjectPath} -> ${q.projectPath}${q.worktreeBranch?` (${q.worktreeBranch})`:""}`)},taskAdmission(q){if(X==="jsonl"){$("task_admission",{state:q.state,queue_position:q.queuePosition,queue_depth:q.queueDepth,in_flight:q.inFlight,max_concurrent_tasks:q.maxConcurrentTasks});return}D(Q.stderr,q.state==="queued"?`[task:queued] position ${q.queuePosition??1}/${q.queueDepth} (running ${q.inFlight}/${q.maxConcurrentTasks})`:`[task:running] admitted (running ${q.inFlight}/${q.maxConcurrentTasks})`)},output(q,Y=0){if(X==="jsonl"){$("output",{content:q,exit_code:Y});return}D(Y===0?Q.stdout:Q.stderr,q)},error(q){if(X==="jsonl"){$("error",{message:q});return}D(Q.stderr,q)}}}async function KG(Q,X={stdout:process.stdout,stderr:process.stderr},H){let $="text",q=p(X,$),Y=new Kq,b={targetLocked:!1},_,R,J=tq(H);try{let B=QG(Q);$=VG(B.outputFormat);let P=await Vq(B);q=p(X,$,Boolean(P)),await Yq();let Dq=await Zq(B),z=await $q(Dq);if(z.mode==="output"){if(z.content)q.output(z.content,z.exitCode??0);return z.exitCode??0}let L=z.content.trimStart().startsWith("!")?z.content.trimStart().slice(1).trim():void 0;if(L!==void 0&&B.taskIsolation)throw Error("User shell commands cannot be combined with --task-isolation");if(L!==void 0&&P)throw Error("Output schemas cannot be combined with user shell commands");if(B.taskIsolation&&(B.continue||B.resume||B.forkSession))throw Error("--task-isolation cannot be combined with --continue, --resume, or --fork-session");let{sessionId:U,messages:C,metadata:k}=await Bq({sessionId:B.sessionId,continue:B.continue,resume:B.resume,forkSession:B.forkSession,fallbackSessionPrefix:"headless"}),E=B.permissionMode??k?.permissionMode??"yolo",F=B.model&&B.model!=="inherit"?B.model:l()?.id,A=B.taskIsolation?await Xq.createSessionTask({sessionId:U,prompt:z.content,sourceProjectPath:I(),isolation:B.taskIsolation,dispatch:{version:1,prompt:z.content,sourceProjectPath:I(),isolation:B.taskIsolation,permissionMode:E,...F?{modelId:F}:{},...P?{outputSchema:P}:{}}}):void 0,M=A?.metadata.projectPath??k?.projectPath??I();if(!A)await h.setSessionPermissionMode(U,M,E);let jq=A?!1:await s.cancelPendingNonInteractive(M,U);if(A)q.taskSession({sessionId:U,projectPath:M,sourceProjectPath:A.metadata.taskSourceProjectPath??I(),isolation:B.taskIsolation,worktreeBranch:A.metadata.taskWorktreeBranch,baseCommit:A.metadata.taskBaseCommit}),R=v.subscribe((Z)=>{if(Z.type!=="task.status"||Z.sessionId!==U||Z.projectPath!==M||!["queued","running"].includes(String(Z.properties.taskStatus))||typeof Z.properties.taskQueueDepth!=="number"||typeof Z.properties.taskInFlight!=="number"||typeof Z.properties.taskConcurrencyLimit!=="number")return;q.taskAdmission({state:Z.properties.taskStatus,queuePosition:typeof Z.properties.taskQueuePosition==="number"?Z.properties.taskQueuePosition:void 0,queueDepth:Z.properties.taskQueueDepth,inFlight:Z.properties.taskInFlight,maxConcurrentTasks:Z.properties.taskConcurrencyLimit})});let bq={messages:jq?await h.loadSessionModelContext(U,M):[...C],userId:"cli-user",sessionId:U,workspaceRoot:M,permissionMode:E,signal:J.signal,...A?.taskWorktree?{worktreeActive:!0}:{},confirmationHandler:ZG()};if(_=await r.create({sessionId:U,workspaceRoot:M,modelId:B.model,permissionMode:E,mcpConfig:B.mcpConfig,strictMcpConfig:B.strictMcpConfig,agents:B.agents?t(B.agents):void 0,...A?.taskWorktree?{taskWorktree:A.taskWorktree}:{},...A?.metadata.taskIsolation?{taskIsolation:A.metadata.taskIsolation}:{},...C.length>0?{sessionStart:{isResume:!0,resumeSessionId:U}}:{}}),L!==void 0){let Z=await _.executeUserShellCommand(L,{signal:J.signal,onEvent:(V)=>{if(V.type==="started")q.userShellStarted(V.executionId,V.command,V.auxiliary);else if(V.type==="output")q.userShellOutput(V.executionId,V.stream,V.chunk,V.streamTruncated)}});return q.userShellCompleted(Z),Z.record.status==="completed"?0:Z.record.status==="aborted"?130:Z.record.exitCode??1}let Hq=B.maxTurns??_.getConfig().maxTurns,_q=A?.taskWorktree?[...new Set([...B.disallowedTools??[],"EnterWorktree","ExitWorktree"])]:B.disallowedTools,Aq=await n.createWithRuntime(_,{sessionId:U,systemPrompt:B.systemPrompt,appendSystemPrompt:B.appendSystemPrompt,maxTurns:B.maxTurns,modelId:B.model,permissionMode:E,toolWhitelist:B.allowedTools,toolBlacklist:_q,mcpConfig:B.mcpConfig,strictMcpConfig:B.strictMcpConfig}),O=await i(Aq.chatStream(z.content,bq,{stream:!0,signal:J.signal,maxTurns:B.maxTurns,builtinVerification:B.verificationAgent!==!1,outputSchema:P,...Hq===-1?{onTurnLimitReached:async(Z)=>{return q.turnLimit(Z.turnsCount),{continue:!0,reason:"headless-auto-continue"}}}:{}}),async(Z)=>{switch(Z.kind){case"content_delta":if(!P||$==="jsonl")Y.markAssistantContent();q.contentDelta(Z.delta);break;case"thinking_delta":Y.setThinkingOpened(q.thinkingDelta(Z.delta,Y.hasOpenThinking()));break;case"stream_end":{let V=Y.completeStream();q.streamEnd(V.wroteAssistantContent,V.openedThinking);break}case"tool_start":{let V=Z.toolCall;if(!("function"in V))break;if(V.function.name===S)break;if(["TaskCreate","TaskUpdate","TaskList"].includes(V.function.name))break;try{let N=JSON.parse(V.function.arguments),f=a(V.function.name,N),x=d(V.function.name,N),W=BG(V.function.name,f,x,b);if(W.shouldLockTarget)b.targetLocked=!0;q.phase(W.phase,W.status,W.message,{toolName:V.function.name,target:x}),q.toolStart(V.function.name,f,x,Z.toolKind)}catch{q.phase(b.targetLocked?"executing":"searching",b.targetLocked?"hit":"ongoing",b.targetLocked?`Working within target: ${V.function.name}`:`Still searching: ${V.function.name}`,{toolName:V.function.name}),q.toolStart(V.function.name,V.function.name,void 0,Z.toolKind)}break}case"tool_progress":{let V=Z.toolCall;if(!("function"in V))break;if(V.function.name===S)break;q.toolProgress(V.function.name,Z.update.message,Z.update.progress,Z.update.total);break}case"tool_result":{let V=Z.toolCall;if(!("function"in V))break;if(V.function.name===S)break;let N;try{let x=JSON.parse(V.function.arguments);N=d(V.function.name,x)}catch{N=void 0}let f=o(V.function.name,Z.result);if(q.toolResult(V.function.name,f.summary,N,void 0,{success:Z.result.success,errorType:Z.result.error?.type,errorMessage:Z.result.error?.message}),f.detail)q.toolDetail(V.function.name,f.detail);break}case"token_usage":q.tokenUsage(Z.usage);break;case"compaction":q.compacting(Z);break;case"task_update":q.taskUpdate(Z.tasks);break;case"structured_output":q.structuredOutput(Z);break;case"mcp_catalog_changed":q.mcpCatalogChanged(Z);break;case"mcp_content_changed":q.mcpContentChanged(Z);break;case"mcp_resource_updated":q.mcpResourceUpdated(Z);break;case"mcp_connection_changed":q.mcpConnectionChanged(Z);break;case"mcp_log":q.mcpLog(Z);break;case"mcp_instructions_changed":q.mcpInstructionsChanged(Z);break;case"mcp_task_changed":q.mcpTaskChanged(Z);break;case"project_rules_loaded":q.projectRulesLoaded(Z);break;case"steering_applied":case"follow_up_started":case"goal_continuation_started":break;case"goal_updated":q.goal(Z);break;case"subagent_spawned":case"subagent_completed":q.subagent(Z);break;case"model_fallback":break;case"provider_retry":q.providerRetry(Z);break;case"provider_stall":q.providerStall(Z);break;case"turn_start":if(Z.turn===1)b.targetLocked=!1;q.phase("turn",b.targetLocked?"hit":"ongoing",`Turn ${Z.turn} started`,{turn:Z.turn});break;default:{let V=Z}}});if(O.metadata?.outputTruncated)q.error("[warning] 输出因达到 token 上限被截断,部分内容可能不完整。");if(!O.success)return q.error(`Error: ${O.error?.message??"Agent execution failed"}`),1;return q.phase("completed","done","Headless run completed"),0}catch(B){if(Y.hasOpenThinking()&&$==="text")X.stderr.write(`
6
+ `);return q.error(`Error: ${$G(B)}`),1}finally{R?.();try{await _?.dispose()}finally{J.dispose()}}}async function gG(){if(!process.argv.slice(2).includes("--headless"))return!1;let{headless:H,"output-format":$,"system-prompt":q,"append-system-prompt":Y,"max-turns":b,..._}=e,R=oq(nq(process.argv)).scriptName("blade").strict(!1).options(_).middleware([Gq,qq,Qq]);return XG(R),await R.parse(),!0}export{KG as runHeadless,gG as handleHeadlessMode,qG as HeadlessOptionsSchema};