blade-code 0.7.1 → 0.7.3

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 (73) hide show
  1. package/dist/blade.js +2 -2
  2. package/dist/{chunk-xmdpc0y5.js → chunk-06awrjgg.js} +2 -2
  3. package/dist/chunk-1vngdr7p.js +1 -0
  4. package/dist/{chunk-2dvn9y9f.js → chunk-29pqj0tb.js} +1 -1
  5. package/dist/{chunk-56frm8dx.js → chunk-373pmz70.js} +1 -1
  6. package/dist/{chunk-zxddgwsb.js → chunk-38h3yh6z.js} +1 -1
  7. package/dist/{chunk-bmxgshct.js → chunk-5n7h04jg.js} +1 -1
  8. package/dist/chunk-5smacbk0.js +24 -0
  9. package/dist/chunk-63dzf6hr.js +2 -0
  10. package/dist/{chunk-f8mjpmdx.js → chunk-87gff8b7.js} +1 -1
  11. package/dist/chunk-98fvxsvc.js +6 -0
  12. package/dist/chunk-98jpdmgc.js +9 -0
  13. package/dist/chunk-aevyre2t.js +1 -0
  14. package/dist/chunk-avebc3bj.js +2 -0
  15. package/dist/chunk-b4hmtjec.js +1 -0
  16. package/dist/{chunk-zm4jr1k2.js → chunk-bmcc85nj.js} +1 -1
  17. package/dist/chunk-cqrg2pp7.js +1 -0
  18. package/dist/{chunk-zvk6ktj1.js → chunk-cw125vv3.js} +1 -1
  19. package/dist/{chunk-f76d6jxg.js → chunk-cyxb6fxe.js} +1 -1
  20. package/dist/{chunk-a7dw8fwn.js → chunk-d0fata6n.js} +1 -1
  21. package/dist/{chunk-qyfdt8h1.js → chunk-e21htmg4.js} +1 -1
  22. package/dist/chunk-e9kfbbpm.js +1 -0
  23. package/dist/chunk-eady1q1w.js +150 -0
  24. package/dist/{chunk-dzmrdtpc.js → chunk-gb0x14v5.js} +37 -34
  25. package/dist/{chunk-7v7s2aag.js → chunk-gjf2d2yg.js} +1 -1
  26. package/dist/chunk-hs4j2fcr.js +6 -0
  27. package/dist/{chunk-qds0yxfy.js → chunk-jf48kahn.js} +3 -3
  28. package/dist/{chunk-h7qab07x.js → chunk-k4behavv.js} +1 -1
  29. package/dist/chunk-k63hr1eg.js +7 -0
  30. package/dist/{chunk-0afbeec0.js → chunk-kfg3vx5z.js} +1 -1
  31. package/dist/{chunk-v1d0d4b4.js → chunk-pvxp2gzr.js} +1 -1
  32. package/dist/{chunk-7z6ba6t9.js → chunk-qxvp127d.js} +1 -1
  33. package/dist/{chunk-867h27ke.js → chunk-rkhhzc4r.js} +2 -2
  34. package/dist/{chunk-b0q2q0ax.js → chunk-rtn0rb16.js} +2 -2
  35. package/dist/chunk-txjvy8qp.js +1 -0
  36. package/dist/{chunk-1dt2y16n.js → chunk-vw3f4mbt.js} +1 -1
  37. package/dist/chunk-w1zb8zac.js +3 -0
  38. package/dist/chunk-wev2rke6.js +1 -0
  39. package/dist/chunk-wp67n9q7.js +1534 -0
  40. package/dist/{chunk-aam53te2.js → chunk-y50fy1gq.js} +2 -2
  41. package/dist/web/assets/{FilePreview-DLnUh-wQ.js → FilePreview-IDRQBiWa.js} +1 -1
  42. package/dist/web/assets/{MarkdownRenderer-C5KTk9XG.js → MarkdownRenderer-BgDKGD2u.js} +1 -1
  43. package/dist/web/assets/{McpModal-B9qJ4ewt.js → McpModal-CJ2l7j-5.js} +1 -1
  44. package/dist/web/assets/{SettingsModal-DpeZ6cJb.js → SettingsModal-BWpbIioU.js} +1 -1
  45. package/dist/web/assets/{SettingsStore-IzKtyAnM.js → SettingsStore-BZjkLZcL.js} +1 -1
  46. package/dist/web/assets/{SkillsModal-BDfzgJIj.js → SkillsModal-CRuRJrN-.js} +1 -1
  47. package/dist/web/assets/{TerminalPanel-B2iTF_CR.js → TerminalPanel-BnZPkS19.js} +1 -1
  48. package/dist/web/assets/{dialog-sI3ihAze.js → dialog-DYRMhlp_.js} +1 -1
  49. package/dist/web/assets/index-Bu13aXyE.css +1 -0
  50. package/dist/web/assets/index-D4CAglTd.js +10 -0
  51. package/dist/web/index.html +2 -2
  52. package/package.json +1 -1
  53. package/dist/chunk-0k8js58t.js +0 -6
  54. package/dist/chunk-0vd9antx.js +0 -1
  55. package/dist/chunk-6jezjq4h.js +0 -6
  56. package/dist/chunk-6k4vs71p.js +0 -1
  57. package/dist/chunk-70ya127f.js +0 -1
  58. package/dist/chunk-7ycmx7c2.js +0 -2
  59. package/dist/chunk-92qcc3gj.js +0 -2138
  60. package/dist/chunk-a2nshjdc.js +0 -49
  61. package/dist/chunk-a8eedntd.js +0 -6
  62. package/dist/chunk-d3db8wrw.js +0 -1
  63. package/dist/chunk-e06p3dkw.js +0 -157
  64. package/dist/chunk-k9h9bw13.js +0 -76
  65. package/dist/chunk-m51xzgwt.js +0 -1
  66. package/dist/chunk-mt1c5da4.js +0 -3
  67. package/dist/chunk-qdnx9x5g.js +0 -2
  68. package/dist/chunk-r6paqm6d.js +0 -1
  69. package/dist/chunk-v0rjbvky.js +0 -9
  70. package/dist/chunk-vs915jzz.js +0 -1
  71. package/dist/chunk-zbtb3jxm.js +0 -1
  72. package/dist/web/assets/index-D8mo0jzF.js +0 -10
  73. package/dist/web/assets/index-DmXmCQOW.css +0 -1
@@ -1,76 +0,0 @@
1
- import{Ea as q0,Ga as A}from"./chunk-867h27ke.js";import{Ob as K0}from"./chunk-mt1c5da4.js";import{nanoid as i0}from"nanoid";import{devtools as o0,subscribeWithSelector as n0}from"zustand/middleware";import{createStore as s0}from"zustand/vanilla";var x0={name:"ayu-dark",colors:{primary:"#ffcc66",secondary:"#bae67e",accent:"#73d0ff",success:"#bae67e",warning:"#ffcc66",error:"#ff3333",info:"#73d0ff",light:"#f0f0f0",dark:"#000000",muted:"#5c6773",highlight:"#2d323b",text:{primary:"#e6e1cf",secondary:"#bae67e",muted:"#5c6773",light:"#ffffff"},background:{primary:"#0f1419",secondary:"#14191f",dark:"#000000"},border:{light:"#2d323b",dark:"#000000"},syntax:{comment:"#5c6773",string:"#bae67e",number:"#ffcc66",keyword:"#ff8f40",function:"#73d0ff",variable:"#e6e1cf",operator:"#f29e74",type:"#73d0ff",tag:"#ff8f40",attr:"#ffd580",default:"#e6e1cf"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(0, 0, 0, 0.2)",base:"0 1px 3px 0 rgba(0, 0, 0, 0.3), 0 1px 2px 0 rgba(0, 0, 0, 0.2)",lg:"0 10px 15px -3px rgba(0, 0, 0, 0.3), 0 4px 6px -2px rgba(0, 0, 0, 0.2)"}},B0={name:"dracula",colors:{primary:"#bd93f9",secondary:"#ffb86c",accent:"#ff79c6",success:"#50fa7b",warning:"#f1fa8c",error:"#ff5555",info:"#8be9fd",light:"#f8f8f2",dark:"#282a36",muted:"#6272a4",highlight:"#44475a",text:{primary:"#f8f8f2",secondary:"#f1fa8c",muted:"#6272a4",light:"#ffffff"},background:{primary:"#282a36",secondary:"#44475a",dark:"#21222c"},border:{light:"#44475a",dark:"#000000"},syntax:{comment:"#6272a4",string:"#f1fa8c",number:"#bd93f9",keyword:"#ff79c6",function:"#50fa7b",variable:"#f8f8f2",operator:"#ff79c6",type:"#8be9fd",tag:"#ff79c6",attr:"#50fa7b",default:"#f8f8f2"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(40, 42, 54, 0.2)",base:"0 1px 3px 0 rgba(40, 42, 54, 0.3), 0 1px 2px 0 rgba(40, 42, 54, 0.2)",lg:"0 10px 15px -3px rgba(40, 42, 54, 0.3), 0 4px 6px -2px rgba(40, 42, 54, 0.2)"}},w0={name:"monokai",colors:{primary:"#66d9ef",secondary:"#a6e22e",accent:"#f92672",success:"#a6e22e",warning:"#e6db74",error:"#f92672",info:"#66d9ef",light:"#f8f8f2",dark:"#272822",muted:"#75715e",highlight:"#3e3d32",text:{primary:"#f8f8f2",secondary:"#e6db74",muted:"#75715e",light:"#ffffff"},background:{primary:"#272822",secondary:"#3e3d32",dark:"#1e1f1c"},border:{light:"#3e3d32",dark:"#000000"},syntax:{comment:"#75715e",string:"#e6db74",number:"#ae81ff",keyword:"#f92672",function:"#a6e22e",variable:"#f8f8f2",operator:"#f92672",type:"#66d9ef",tag:"#f92672",attr:"#a6e22e",default:"#f8f8f2"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(39, 40, 34, 0.2)",base:"0 1px 3px 0 rgba(39, 40, 34, 0.3), 0 1px 2px 0 rgba(39, 40, 34, 0.2)",lg:"0 10px 15px -3px rgba(39, 40, 34, 0.3), 0 4px 6px -2px rgba(39, 40, 34, 0.2)"}},A0={name:"nord",colors:{primary:"#88c0d0",secondary:"#81a1c1",accent:"#b48ead",success:"#a3be8c",warning:"#ebcb8b",error:"#bf616a",info:"#88c0d0",light:"#eceff4",dark:"#2e3440",muted:"#4c566a",highlight:"#434c5e",text:{primary:"#eceff4",secondary:"#d8dee9",muted:"#4c566a",light:"#ffffff"},background:{primary:"#2e3440",secondary:"#3b4252",dark:"#242933"},border:{light:"#434c5e",dark:"#000000"},syntax:{comment:"#616e88",string:"#a3be8c",number:"#b48ead",keyword:"#81a1c1",function:"#88c0d0",variable:"#d8dee9",operator:"#81a1c1",type:"#8fbcbb",tag:"#81a1c1",attr:"#8fbcbb",default:"#eceff4"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(46, 52, 64, 0.2)",base:"0 1px 3px 0 rgba(46, 52, 64, 0.3), 0 1px 2px 0 rgba(46, 52, 64, 0.2)",lg:"0 10px 15px -3px rgba(46, 52, 64, 0.3), 0 4px 6px -2px rgba(46, 52, 64, 0.2)"}},D0={name:"solarized-light",colors:{primary:"#268bd2",secondary:"#2aa198",accent:"#d33682",success:"#859900",warning:"#cb4b16",error:"#dc322f",info:"#268bd2",light:"#fdf6e3",dark:"#073642",muted:"#93a1a1",highlight:"#eee8d5",text:{primary:"#586e75",secondary:"#657b83",muted:"#93a1a1",light:"#002b36"},background:{primary:"#fdf6e3",secondary:"#eee8d5",dark:"#073642"},border:{light:"#eee8d5",dark:"#073642"},syntax:{comment:"#93a1a1",string:"#2aa198",number:"#d33682",keyword:"#859900",function:"#268bd2",variable:"#657b83",operator:"#859900",type:"#b58900",tag:"#268bd2",attr:"#93a1a1",default:"#657b83"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(253, 246, 227, 0.2)",base:"0 1px 3px 0 rgba(253, 246, 227, 0.3), 0 1px 2px 0 rgba(253, 246, 227, 0.2)",lg:"0 10px 15px -3px rgba(253, 246, 227, 0.3), 0 4px 6px -2px rgba(253, 246, 227, 0.2)"}},L0={name:"solarized-dark",colors:{primary:"#268bd2",secondary:"#2aa198",accent:"#d33682",success:"#859900",warning:"#b58900",error:"#dc322f",info:"#268bd2",light:"#fdf6e3",dark:"#073642",muted:"#586e75",highlight:"#073642",text:{primary:"#839496",secondary:"#93a1a1",muted:"#586e75",light:"#fdf6e3"},background:{primary:"#002b36",secondary:"#073642",dark:"#001f29"},border:{light:"#073642",dark:"#000000"},syntax:{comment:"#586e75",string:"#2aa198",number:"#d33682",keyword:"#859900",function:"#268bd2",variable:"#839496",operator:"#859900",type:"#b58900",tag:"#268bd2",attr:"#93a1a1",default:"#839496"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(0, 43, 54, 0.2)",base:"0 1px 3px 0 rgba(0, 43, 54, 0.3), 0 1px 2px 0 rgba(0, 43, 54, 0.2)",lg:"0 10px 15px -3px rgba(0, 43, 54, 0.3), 0 4px 6px -2px rgba(0, 43, 54, 0.2)"}},v0={name:"tokyo-night",colors:{primary:"#7aa2f7",secondary:"#7dcfff",accent:"#bb9af7",success:"#9ece6a",warning:"#e0af68",error:"#f7768e",info:"#7aa2f7",light:"#c0caf5",dark:"#1a1b26",muted:"#565f89",highlight:"#292e42",text:{primary:"#a9b1d6",secondary:"#c0caf5",muted:"#565f89",light:"#ffffff"},background:{primary:"#1a1b26",secondary:"#292e42",dark:"#16161e"},border:{light:"#292e42",dark:"#000000"},syntax:{comment:"#565f89",string:"#9ece6a",number:"#ff9e64",keyword:"#bb9af7",function:"#7aa2f7",variable:"#c0caf5",operator:"#89ddff",type:"#7dcfff",tag:"#f7768e",attr:"#7aa2f7",default:"#a9b1d6"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(26, 27, 38, 0.2)",base:"0 1px 3px 0 rgba(26, 27, 38, 0.3), 0 1px 2px 0 rgba(26, 27, 38, 0.2)",lg:"0 10px 15px -3px rgba(26, 27, 38, 0.3), 0 4px 6px -2px rgba(26, 27, 38, 0.2)"}},E0={name:"github",colors:{primary:"#0969da",secondary:"#8250df",accent:"#bc4c00",success:"#1a7f37",warning:"#bc4c00",error:"#d1242f",info:"#0969da",light:"#f6f8fa",dark:"#24292f",muted:"#6e7781",highlight:"#ddf4ff",text:{primary:"#24292f",secondary:"#57606a",muted:"#6e7781",light:"#ffffff"},background:{primary:"#ffffff",secondary:"#f6f8fa",dark:"#24292f"},border:{light:"#d0d7de",dark:"#24292f"},syntax:{comment:"#6e7781",string:"#0a3069",number:"#0550ae",keyword:"#cf222e",function:"#8250df",variable:"#24292f",operator:"#cf222e",type:"#0550ae",tag:"#116329",attr:"#0550ae",default:"#24292f"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(255, 255, 255, 0.2)",base:"0 1px 3px 0 rgba(255, 255, 255, 0.3), 0 1px 2px 0 rgba(255, 255, 255, 0.2)",lg:"0 10px 15px -3px rgba(255, 255, 255, 0.3), 0 4px 6px -2px rgba(255, 255, 255, 0.2)"}},y0={name:"gruvbox",colors:{primary:"#83a598",secondary:"#8ec07c",accent:"#d3869b",success:"#b8bb26",warning:"#fabd2f",error:"#fb4934",info:"#83a598",light:"#fbf1c7",dark:"#282828",muted:"#928374",highlight:"#3c3836",text:{primary:"#ebdbb2",secondary:"#d5c4a1",muted:"#928374",light:"#ffffff"},background:{primary:"#282828",secondary:"#3c3836",dark:"#1d2021"},border:{light:"#3c3836",dark:"#000000"},syntax:{comment:"#928374",string:"#b8bb26",number:"#d3869b",keyword:"#fb4934",function:"#8ec07c",variable:"#ebdbb2",operator:"#fe8019",type:"#fabd2f",tag:"#fb4934",attr:"#b8bb26",default:"#ebdbb2"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(40, 40, 40, 0.2)",base:"0 1px 3px 0 rgba(40, 40, 40, 0.3), 0 1px 2px 0 rgba(40, 40, 40, 0.2)",lg:"0 10px 15px -3px rgba(40, 40, 40, 0.3), 0 4px 6px -2px rgba(40, 40, 40, 0.2)"}},R0={name:"one-dark",colors:{primary:"#61afef",secondary:"#c678dd",accent:"#e5c07b",success:"#98c379",warning:"#e5c07b",error:"#e06c75",info:"#56b6c2",light:"#abb2bf",dark:"#282c34",muted:"#5c6370",highlight:"#3e4451",text:{primary:"#abb2bf",secondary:"#c6c8d0",muted:"#5c6370",light:"#ffffff"},background:{primary:"#282c34",secondary:"#3e4451",dark:"#21252b"},border:{light:"#3e4451",dark:"#000000"},syntax:{comment:"#5c6370",string:"#98c379",number:"#d19a66",keyword:"#c678dd",function:"#61afef",variable:"#e06c75",operator:"#56b6c2",type:"#e5c07b",tag:"#e06c75",attr:"#d19a66",default:"#abb2bf"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(40, 44, 52, 0.2)",base:"0 1px 3px 0 rgba(40, 44, 52, 0.3), 0 1px 2px 0 rgba(40, 44, 52, 0.2)",lg:"0 10px 15px -3px rgba(40, 44, 52, 0.3), 0 4px 6px -2px rgba(40, 44, 52, 0.2)"}},P0={name:"catppuccin",colors:{primary:"#89b4fa",secondary:"#cba6f7",accent:"#f5c2e7",success:"#a6e3a1",warning:"#f9e2af",error:"#f38ba8",info:"#89dceb",light:"#cdd6f4",dark:"#11111b",muted:"#6c7086",highlight:"#181825",text:{primary:"#cdd6f4",secondary:"#bac2de",muted:"#6c7086",light:"#ffffff"},background:{primary:"#1e1e2e",secondary:"#181825",dark:"#11111b"},border:{light:"#181825",dark:"#000000"},syntax:{comment:"#6c7086",string:"#a6e3a1",number:"#fab387",keyword:"#cba6f7",function:"#89b4fa",variable:"#cdd6f4",operator:"#89dceb",type:"#f5c2e7",tag:"#f38ba8",attr:"#89b4fa",default:"#cdd6f4"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(30, 30, 46, 0.2)",base:"0 1px 3px 0 rgba(30, 30, 46, 0.3), 0 1px 2px 0 rgba(30, 30, 46, 0.2)",lg:"0 10px 15px -3px rgba(30, 30, 46, 0.3), 0 4px 6px -2px rgba(30, 30, 46, 0.2)"}},C0={name:"rose-pine",colors:{primary:"#9ccfd8",secondary:"#c4a7e7",accent:"#f6c177",success:"#31748f",warning:"#f6c177",error:"#eb6f92",info:"#9ccfd8",light:"#e0def4",dark:"#191724",muted:"#6e6a86",highlight:"#1f1d2e",text:{primary:"#e0def4",secondary:"#cecacd",muted:"#6e6a86",light:"#ffffff"},background:{primary:"#191724",secondary:"#1f1d2e",dark:"#12101a"},border:{light:"#1f1d2e",dark:"#000000"},syntax:{comment:"#6e6a86",string:"#9ccfd8",number:"#ea9a97",keyword:"#c4a7e7",function:"#31748f",variable:"#e0def4",operator:"#f6c177",type:"#9ccfd8",tag:"#eb6f92",attr:"#f6c177",default:"#e0def4"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(25, 23, 36, 0.2)",base:"0 1px 3px 0 rgba(25, 23, 36, 0.3), 0 1px 2px 0 rgba(25, 23, 36, 0.2)",lg:"0 10px 15px -3px rgba(25, 23, 36, 0.3), 0 4px 6px -2px rgba(25, 23, 36, 0.2)"}},I0={name:"kanagawa",colors:{primary:"#8ba4b0",secondary:"#a292a3",accent:"#c47fd5",success:"#76946a",warning:"#c0a36e",error:"#c34043",info:"#7e9cd8",light:"#dcd7ba",dark:"#1f1f28",muted:"#727169",highlight:"#2a2a37",text:{primary:"#dcd7ba",secondary:"#c8c093",muted:"#727169",light:"#ffffff"},background:{primary:"#1f1f28",secondary:"#2a2a37",dark:"#16161d"},border:{light:"#2a2a37",dark:"#000000"},syntax:{comment:"#727169",string:"#98bb6c",number:"#d27e99",keyword:"#957fb8",function:"#7e9cd8",variable:"#dcd7ba",operator:"#c0a36e",type:"#7aa89f",tag:"#c34043",attr:"#7fb4ca",default:"#dcd7ba"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(31, 31, 40, 0.2)",base:"0 1px 3px 0 rgba(31, 31, 40, 0.3), 0 1px 2px 0 rgba(31, 31, 40, 0.2)",lg:"0 10px 15px -3px rgba(31, 31, 40, 0.3), 0 4px 6px -2px rgba(31, 31, 40, 0.2)"}},t=[{id:"ayu-dark",label:"Ayu Dark",theme:x0,tags:["dark","popular"]},{id:"dracula",label:"Dracula",theme:B0,tags:["dark","popular"]},{id:"monokai",label:"Monokai",theme:w0,tags:["dark","classic"]},{id:"nord",label:"Nord",theme:A0,tags:["dark","minimal"]},{id:"solarized-light",label:"Solarized Light",theme:D0,tags:["light"]},{id:"solarized-dark",label:"Solarized Dark",theme:L0,tags:["dark"]},{id:"tokyo-night",label:"Tokyo Night",theme:v0,tags:["dark","popular"]},{id:"github",label:"GitHub",theme:E0,tags:["light","minimal"]},{id:"gruvbox",label:"Gruvbox",theme:y0,tags:["dark","warm"]},{id:"one-dark",label:"One Dark",theme:R0,tags:["dark","popular"]},{id:"catppuccin",label:"Catppuccin",theme:P0,tags:["dark","pastel"]},{id:"rose-pine",label:"Rose Pine",theme:C0,tags:["dark","elegant"]},{id:"kanagawa",label:"Kanagawa",theme:I0,tags:["dark","japanese"]}];var e={primary:"#0066cc",secondary:"#6c757d",accent:"#e83e8c",success:"#28a745",warning:"#ffc107",error:"#dc3545",info:"#17a2b8",light:"#f8f9fa",dark:"#343a40",muted:"#6c757d",highlight:"#fff3cd",text:{primary:"#212529",secondary:"#6c757d",muted:"#6c757d",light:"#ffffff"},background:{primary:"#ffffff",secondary:"#f8f9fa",dark:"#343a40"},border:{light:"#dee2e6",dark:"#495057"},syntax:{comment:"#6c757d",string:"#28a745",number:"#e83e8c",keyword:"#007bff",function:"#17a2b8",variable:"#495057",operator:"#ffc107",type:"#007bff",tag:"#dc3545",attr:"#ffc107",default:"#212529"}},p={name:"default",colors:e,spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(0, 0, 0, 0.05)",base:"0 1px 3px 0 rgba(0, 0, 0, 0.1), 0 1px 2px 0 rgba(0, 0, 0, 0.06)",lg:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05)"}},b0={...p,name:"dark",colors:{...e,text:{primary:"#ffffff",secondary:"#e2e8f0",muted:"#94a3b8",light:"#000000"},background:{primary:"#1e293b",secondary:"#334155",dark:"#0f172a"},border:{light:"#475569",dark:"#64748b"},syntax:{comment:"#94a3b8",string:"#34d399",number:"#f472b6",keyword:"#60a5fa",function:"#06b6d4",variable:"#e2e8f0",operator:"#fbbf24",type:"#60a5fa",tag:"#fb7185",attr:"#fbbf24",default:"#ffffff"}}};class Q0{currentTheme=p;themes=new Map;constructor(){this.themes.set("default",p),this.themes.set("dark",b0);for(let X of t)this.themes.set(X.id,X.theme)}setTheme(X){let Z=this.themes.get(X);if(Z)this.currentTheme=Z;else throw Error(`Theme '${X}' not found`)}getTheme(){return this.currentTheme}getAvailableThemes(){return Array.from(this.themes.keys())}getCurrentThemeName(){return this.currentTheme.name}getThemeByName(X){return this.themes.get(X)}hasTheme(X){return this.themes.has(X)}}var X0=new Q0;var M0={initializationStatus:"idle",initializationError:null,activeModal:"none",sessionSelectorData:void 0,modelEditorTarget:null,tasks:[],awaitingSecondCtrlC:!1,thinkingModeEnabled:!1,subagentProgress:null},g=(X)=>({...M0,actions:{setInitializationStatus:(Z)=>{X((Q)=>({app:{...Q.app,initializationStatus:Z}}))},setInitializationError:(Z)=>{X((Q)=>({app:{...Q.app,initializationError:Z}}))},setActiveModal:(Z)=>{X((Q)=>({app:{...Q.app,activeModal:Z}}))},showSessionSelector:(Z)=>{X((Q)=>({app:{...Q.app,activeModal:"sessionSelector",sessionSelectorData:Z}}))},showModelEditWizard:(Z)=>{X((Q)=>({app:{...Q.app,activeModal:"modelEditWizard",modelEditorTarget:Z}}))},closeModal:()=>{X((Z)=>({app:{...Z.app,activeModal:"none",sessionSelectorData:void 0,modelEditorTarget:null}}))},setTasks:(Z)=>{X((Q)=>({app:{...Q.app,tasks:Z}}))},updateTask:(Z)=>{X((Q)=>({app:{...Q.app,tasks:Q.app.tasks.map(($)=>$.id===Z.id?Z:$)}}))},setAwaitingSecondCtrlC:(Z)=>{X((Q)=>({app:{...Q.app,awaitingSecondCtrlC:Z}}))},setThinkingModeEnabled:(Z)=>{X((Q)=>({app:{...Q.app,thinkingModeEnabled:Z}}))},toggleThinkingMode:()=>{X((Z)=>({app:{...Z.app,thinkingModeEnabled:!Z.app.thinkingModeEnabled}}))},startSubagentProgress:(Z,Q,$)=>{X((Y)=>({app:{...Y.app,subagentProgress:{id:Z,type:Q,description:$,status:"running",startTime:Date.now()}}}))},updateSubagentTool:(Z)=>{X((Q)=>{if(!Q.app.subagentProgress)return Q;return{app:{...Q.app,subagentProgress:{...Q.app.subagentProgress,currentTool:Z}}}})},completeSubagentProgress:(Z)=>{X((Q)=>{if(!Q.app.subagentProgress)return Q;return{app:{...Q.app,subagentProgress:{...Q.app.subagentProgress,status:Z?"completed":"failed",currentTool:void 0}}}}),setTimeout(()=>{X((Q)=>({app:{...Q.app,subagentProgress:null}}))},1500)}}});var T0={isProcessing:!1,abortController:null,pendingCommands:[]},d=(X,Z)=>({...T0,actions:{setProcessing:(Q)=>{X(($)=>({command:{...$.command,isProcessing:Q}}))},createAbortController:()=>{let Q=Z().command.abortController;if(Q&&!Q.signal.aborted)Q.abort("interrupted-by-new-command");let $=new AbortController;return X((Y)=>({command:{...Y.command,abortController:$}})),$},getAbortController:()=>{return Z().command.abortController},clearAbortController:(Q)=>{let $=Z().command.abortController;if(Q!==void 0&&$!==Q)return;X((Y)=>({command:{...Y.command,abortController:null}}))},abort:(Q)=>{let{abortController:$}=Z().command;if($&&!$.signal.aborted)$.abort(Q??"user-cancel");X((Y)=>({command:{...Y.command,isProcessing:!1,pendingCommands:[]}}))},enqueueCommand:(Q)=>{X(($)=>({command:{...$.command,pendingCommands:[...$.command.pendingCommands,Q]}}))},dequeueCommand:()=>{let{pendingCommands:Q}=Z().command;if(Q.length===0)return;let[$,...Y]=Q;return X((V)=>({command:{...V.command,pendingCommands:Y}})),$},clearQueue:()=>{X((Q)=>({command:{...Q.command,pendingCommands:[]}}))}}});var N0={config:null},m=(X)=>({...N0,actions:{setConfig:(Z)=>{X((Q)=>({config:{...Q.config,config:Z}}))},updateConfig:(Z)=>{X((Q)=>{if(!Q.config.config)throw Error(`[ConfigSlice] Config not initialized. Cannot update: ${JSON.stringify(Z)}`);return{config:{...Q.config,config:{...Q.config.config,...Z}}}})}}});var u0={currentFocus:"main-input",previousFocus:null},r=(X)=>({...u0,actions:{setFocus:(Z)=>{X((Q)=>({focus:{...Q.focus,currentFocus:Z,previousFocus:Q.focus.currentFocus}}))},restorePreviousFocus:()=>{X((Z)=>({focus:{...Z.focus,currentFocus:Z.focus.previousFocus||"main-input",previousFocus:null}}))}}});import{nanoid as p0}from"nanoid";var c={"deepseek-chat":{input:0.27,output:1.1},"deepseek-coder":{input:0.14,output:0.28},"deepseek-reasoner":{input:0.55,output:2.19},"deepseek-v3":{input:0.27,output:1.1},"deepseek-v4":{input:0.27,output:1.1},"deepseek-v4-pro":{input:0.27,output:1.1},"deepseek-v4-0724":{input:0.27,output:1.1},"gpt-4o":{input:2.5,output:10},"gpt-4o-mini":{input:0.15,output:0.6},"gpt-4.1":{input:2,output:8},"gpt-4.1-mini":{input:0.4,output:1.6},"gpt-4.1-nano":{input:0.1,output:0.4},"gpt-4-turbo":{input:10,output:30},"gpt-4":{input:30,output:60},"gpt-3.5-turbo":{input:0.5,output:1.5},o1:{input:15,output:60},"o1-mini":{input:3,output:12},"o1-pro":{input:150,output:600},o3:{input:10,output:40},"o3-mini":{input:1.1,output:4.4},"o4-mini":{input:1.1,output:4.4},"claude-3.5-sonnet":{input:3,output:15,cacheRead:0.3,cacheWrite:3.75},"claude-3.5-haiku":{input:0.8,output:4,cacheRead:0.08,cacheWrite:1},"claude-sonnet-4":{input:3,output:15,cacheRead:0.3,cacheWrite:3.75},"claude-4-opus":{input:15,output:75,cacheRead:1.5,cacheWrite:18.75},"claude-opus-4":{input:15,output:75,cacheRead:1.5,cacheWrite:18.75},"qwen-plus":{input:0.8,output:2},"qwen-max":{input:2,output:6},"qwen-turbo":{input:0.3,output:0.6},"qwen3-235b":{input:2,output:8},"gemini-2.5-pro":{input:1.25,output:10},"gemini-2.5-flash":{input:0.15,output:0.6}};function h0(X){let Z=X.toLowerCase();if(c[Z])return c[Z];for(let[Q,$]of Object.entries(c))if(Z.includes(Q)||Q.includes(Z))return $;return}function Z0(X,Z,Q,$,Y){let V=h0(X);if(!V)return 0;let J=Z/1e6*V.input+Q/1e6*V.output;if($&&V.cacheRead)J+=$/1e6*V.cacheRead;if(Y&&V.cacheWrite)J+=Y/1e6*V.cacheWrite;return Math.round(J*1e6)/1e6}var K={codeBlock:/^```(\w+)?\s*$/,heading:/^ *(#{1,4}) +(.+)/,blockquote:/^(>+)\s?(.*)/,ulItem:/^([ \t]*)([-*+]) +(.+)/,olItem:/^([ \t]*)(\d+)\. +(.+)/,hr:/^ *([-*_] *){3,} *$/,table:/^\|(.+)\|$/,tableSeparator:/^\|[\s]*:?-+:?[\s]*(\|[\s]*:?-+:?[\s]*)+\|?$/,diffStart:/^<<<DIFF>>>$/,diffEnd:/^<<<\/DIFF>>>$/,commandMessage:/<command-message>(.*?)<\/command-message>/};function G1(X){let Z=[],Q=X.split(/\r?\n/),$=!1,Y=[],V=null,J=0,G=!1,U=[],H=[],W=!1,D=[],v=!1,O=[],z=0,j=!0;for(let L=0;L<Q.length;L++){let _=Q[L];if(W){if(_.match(K.diffEnd)){try{let B=JSON.parse(D.join(`
2
- `));Z.push({type:"diff",content:"",diffData:{patch:B.patch,startLine:B.startLine,matchLine:B.matchLine}})}catch(B){Z.push({type:"text",content:D.join(`
3
- `)})}W=!1,D=[],j=!1;continue}D.push(_);continue}if(_.match(K.diffStart)){W=!0,D=[],j=!1;continue}if($){let B=_.match(K.codeBlock),E=_.trim()==="```";if(B&&B[1])J++,Y.push(_);else if(E)if(J>0)J--,Y.push(_);else{let _0=Y.join(`
4
- `);Z.push({type:"code",content:_0,language:V||void 0}),$=!1,Y=[],V=null,J=0,j=!1}else Y.push(_);continue}let s=_.match(K.codeBlock);if(s){$=!0,V=s[1]||null,J=0,j=!1;continue}let b=_.match(K.table),O0=_.match(K.tableSeparator);if(b&&!G){if(L+1<Q.length){if(Q[L+1].match(K.tableSeparator)){G=!0,U=b[1].split("|").map((E)=>E.trim()).filter((E)=>E.length>0),H=[],j=!1;continue}}}if(G&&O0)continue;if(G&&b){let B=b[1].split("|").map((E)=>E.trim()).filter((E)=>E.length>0);while(B.length<U.length)B.push("");if(B.length>U.length)B.length=U.length;H.push(B);continue}if(G&&!b){if(U.length>0&&H.length>0)Z.push({type:"table",content:"",tableData:{headers:U,rows:H}});G=!1,U=[],H=[]}let f=_.match(K.blockquote);if(f){let B=f[1].length,E=f[2]||"";if(v&&B===z)O.push(E);else{if(v)Z.push({type:"blockquote",content:O.join(`
5
- `),blockquoteLevel:z,blockquoteLines:[...O]});v=!0,z=B,O=[E]}j=!1;continue}if(v)Z.push({type:"blockquote",content:O.join(`
6
- `),blockquoteLevel:z,blockquoteLines:[...O]}),v=!1,O=[],z=0;let S=_.match(K.heading);if(S){Z.push({type:"heading",content:S[2],level:S[1].length}),j=!1;continue}let u=_.match(K.ulItem);if(u){Z.push({type:"list",content:u[3],listType:"ul",marker:u[2],indentation:u[1].length}),j=!1;continue}let h=_.match(K.olItem);if(h){Z.push({type:"list",content:h[3],listType:"ol",marker:h[2],indentation:h[1].length}),j=!1;continue}if(_.match(K.hr)){Z.push({type:"hr",content:""}),j=!1;continue}if(_.trim().length===0){if(!j)Z.push({type:"empty",content:""}),j=!0;continue}let a=_.match(K.commandMessage);if(a){Z.push({type:"command-message",content:a[1]}),j=!1;continue}Z.push({type:"text",content:_}),j=!1}if($){let L=Y.join(`
7
- `);Z.push({type:"code",content:L,language:V||void 0})}if(G&&U.length>0&&H.length>0)Z.push({type:"table",content:"",tableData:{headers:U,rows:H}});if(v&&O.length>0)Z.push({type:"blockquote",content:O.join(`
8
- `),blockquoteLevel:z,blockquoteLines:[...O]});while(Z.length>0&&Z[Z.length-1].type==="empty")Z.pop();return Z}var R=new Map;function k0(){return{inCodeBlock:!1,codeBlockContent:[],codeBlockLang:null,codeBlockDepth:0,inTable:!1,tableHeaders:[],tableRows:[],inDiff:!1,diffContent:[],inBlockquote:!1,blockquoteLines:[],blockquoteLevel:0,lastLineEmpty:!0,pendingTableHeader:null}}function f0(X){let Z=R.get(X);if(Z)return Z;let Q={state:k0(),blocks:[],pendingLine:"",finalized:!1};return R.set(X,Q),Q}function $0(X){return X.endsWith("\r")?X.slice(0,-1):X}function Y0(X,Z){if(X.tableHeaders.length>0&&X.tableRows.length>0)Z.push({type:"table",content:"",tableData:{headers:X.tableHeaders,rows:X.tableRows}});X.inTable=!1,X.tableHeaders=[],X.tableRows=[]}function l(X,Z){if(X.blockquoteLines.length>0)Z.push({type:"blockquote",content:X.blockquoteLines.join(`
9
- `),blockquoteLevel:X.blockquoteLevel,blockquoteLines:[...X.blockquoteLines]});X.inBlockquote=!1,X.blockquoteLines=[],X.blockquoteLevel=0}function V0(X,Z){let Q=X.codeBlockContent.join(`
10
- `);Z.push({type:"code",content:Q,language:X.codeBlockLang||void 0}),X.inCodeBlock=!1,X.codeBlockContent=[],X.codeBlockLang=null,X.codeBlockDepth=0,X.lastLineEmpty=!1}function i(X,Z,Q=!0){let{state:$,blocks:Y}=Z;if($.pendingTableHeader!==null){if(X.match(K.tableSeparator)){$.inTable=!0,$.tableHeaders=$.pendingTableHeader.slice(1,-1).split("|").map((z)=>z.trim()).filter((z)=>z.length>0),$.tableRows=[],$.pendingTableHeader=null,$.lastLineEmpty=!1;return}Y.push({type:"text",content:$.pendingTableHeader}),$.pendingTableHeader=null,$.lastLineEmpty=!1}if($.inDiff){if(X.match(K.diffEnd)){try{let z=JSON.parse($.diffContent.join(`
11
- `));Y.push({type:"diff",content:"",diffData:{patch:z.patch,startLine:z.startLine,matchLine:z.matchLine}})}catch(z){Y.push({type:"text",content:$.diffContent.join(`
12
- `)})}$.inDiff=!1,$.diffContent=[],$.lastLineEmpty=!1;return}$.diffContent.push(X);return}if(X.match(K.diffStart)){$.inDiff=!0,$.diffContent=[],$.lastLineEmpty=!1;return}if($.inCodeBlock){let z=X.match(K.codeBlock),j=X.trim()==="```";if(z&&z[1])$.codeBlockDepth++,$.codeBlockContent.push(X);else if(j)if($.codeBlockDepth>0)$.codeBlockDepth--,$.codeBlockContent.push(X);else V0($,Y);else $.codeBlockContent.push(X);return}let V=X.match(K.codeBlock);if(V){$.inCodeBlock=!0,$.codeBlockLang=V[1]||null,$.codeBlockDepth=0,$.lastLineEmpty=!1;return}let J=X.match(K.table),G=X.match(K.tableSeparator);if(J&&!$.inTable){$.pendingTableHeader=X;return}if($.inTable&&G)return;if($.inTable&&J){let z=J[1].split("|").map((j)=>j.trim()).filter((j)=>j.length>0);while(z.length<$.tableHeaders.length)z.push("");if(z.length>$.tableHeaders.length)z.length=$.tableHeaders.length;$.tableRows.push(z);return}if($.inTable&&!J){if(Y0($,Y),Q){i(X,Z,!1);return}}let U=X.match(K.blockquote);if(U){let z=U[1].length,j=U[2]||"";if($.inBlockquote&&z===$.blockquoteLevel)$.blockquoteLines.push(j);else{if($.inBlockquote)l($,Y);$.inBlockquote=!0,$.blockquoteLevel=z,$.blockquoteLines=[j]}$.lastLineEmpty=!1;return}if($.inBlockquote)l($,Y);let H=X.match(K.heading);if(H){Y.push({type:"heading",content:H[2],level:H[1].length}),$.lastLineEmpty=!1;return}let W=X.match(K.ulItem);if(W){Y.push({type:"list",content:W[3],listType:"ul",marker:W[2],indentation:W[1].length}),$.lastLineEmpty=!1;return}let D=X.match(K.olItem);if(D){Y.push({type:"list",content:D[3],listType:"ol",marker:D[2],indentation:D[1].length}),$.lastLineEmpty=!1;return}if(X.match(K.hr)){Y.push({type:"hr",content:""}),$.lastLineEmpty=!1;return}if(X.trim().length===0){if(!$.lastLineEmpty)Y.push({type:"empty",content:""}),$.lastLineEmpty=!0;return}let O=X.match(K.commandMessage);if(O){Y.push({type:"command-message",content:O[1]}),$.lastLineEmpty=!1;return}Y.push({type:"text",content:X}),$.lastLineEmpty=!1}function H1(X,Z){if(!X||!Z)return;let Q=f0(X);if(Q.finalized)return;let $=Q.pendingLine+Z,Y=$.split(`
13
- `),V=$.endsWith(`
14
- `),J=V?Y:Y.slice(0,-1);Q.pendingLine=V?"":Y[Y.length-1]??"";for(let G of J)i($0(G),Q)}function z1(X){let Z=R.get(X);if(!Z||Z.finalized)return;if(Z.pendingLine)i($0(Z.pendingLine),Z),Z.pendingLine="";if(Z.state.pendingTableHeader!==null)Z.blocks.push({type:"text",content:Z.state.pendingTableHeader}),Z.state.pendingTableHeader=null;if(Z.state.inCodeBlock)V0(Z.state,Z.blocks);if(Z.state.inTable)Y0(Z.state,Z.blocks);if(Z.state.inBlockquote)l(Z.state,Z.blocks);if(Z.state.inDiff)Z.blocks.push({type:"text",content:Z.state.diffContent.join(`
15
- `)}),Z.state.inDiff=!1,Z.state.diffContent=[];while(Z.blocks.length>0&&Z.blocks[Z.blocks.length-1].type==="empty")Z.blocks.pop();Z.finalized=!0}function W1(X){let Z=R.get(X);if(!Z||!Z.finalized)return null;return Z.blocks}function F1(X){let Z=R.get(X);if(!Z)return null;return Z.blocks}function S0(X){let Z=R.get(X);if(!Z)return null;let Q=[],$=Z.state;if($.inDiff)Q.push("<<<DIFF>>>"),Q.push(...$.diffContent);else if($.inCodeBlock){let Y=$.codeBlockLang?`\`\`\`${$.codeBlockLang}`:"```";Q.push(Y),Q.push(...$.codeBlockContent)}else if($.inTable){if($.tableHeaders.length>0){Q.push(`| ${$.tableHeaders.join(" | ")} |`),Q.push(`| ${$.tableHeaders.map(()=>"---").join(" | ")} |`);for(let Y of $.tableRows)Q.push(`| ${Y.join(" | ")} |`)}}else if($.inBlockquote){let Y=">".repeat($.blockquoteLevel)+" ";for(let V of $.blockquoteLines)Q.push(Y+V)}else if($.pendingTableHeader)Q.push($.pendingTableHeader);if(Z.pendingLine)Q.push(Z.pendingLine);return Q.length>0?Q:null}function K1(X){let Z=R.get(X);if(!Z)return null;let Q="text";if(Z.state.inDiff)Q="diff";else if(Z.state.inCodeBlock)Q="code";else if(Z.state.inTable||Z.state.pendingTableHeader)Q="table";let $=S0(X);if(!$||$.length===0)return null;return{lines:$,mode:Q}}function q1(X){R.delete(X)}function k(){R.clear()}var J0=2000,M=[];function g0(){let X=M;return M=[],X}var U0={inputTokens:0,outputTokens:0,totalTokens:0,maxContextTokens:200000,totalInputTokens:0,totalOutputTokens:0,cacheReadTokens:0,cacheWriteTokens:0,turnCount:0,estimatedCostUsd:0},G0={sessionId:p0(),messages:[],restoredContextMessages:null,restoredVisibleMessageCount:0,isCompacting:!1,currentCommand:null,error:null,isActive:!0,tokenUsage:{...U0},currentThinkingContent:null,thinkingExpanded:!1,clearCount:0,historyExpanded:!1,expandedMessageCount:100,currentStreamingMessageId:null,currentStreamingChunks:[],currentStreamingLines:[],currentStreamingTail:"",currentStreamingLineCount:0,currentStreamingVersion:0,finalizingStreamingMessageId:null},o=(X,Z)=>({...G0,actions:{addMessage:(Q)=>{X(($)=>({session:{...$.session,messages:[...$.session.messages,Q],error:null}}))},addUserMessage:(Q)=>{let $={id:`user-${Date.now()}-${Math.random()}`,role:"user",content:Q,timestamp:Date.now()};Z().session.actions.addMessage($)},addAssistantMessage:(Q,$)=>{let Y={id:`assistant-${Date.now()}-${Math.random()}`,role:"assistant",content:Q,timestamp:Date.now(),thinkingContent:$};Z().session.actions.addMessage(Y)},addAssistantMessageAndClearThinking:(Q)=>{let $=Z().session.currentThinkingContent,Y={id:`assistant-${Date.now()}-${Math.random()}`,role:"assistant",content:Q,timestamp:Date.now(),thinkingContent:$||void 0};X((V)=>({session:{...V.session,messages:[...V.session.messages,Y],currentThinkingContent:null,error:null}}))},addToolMessage:(Q,$)=>{let Y={id:`tool-${Date.now()}-${Math.random()}`,role:"tool",content:Q,timestamp:Date.now(),metadata:$};Z().session.actions.addMessage(Y)},setCompacting:(Q)=>{X(($)=>({session:{...$.session,isCompacting:Q}}))},setCommand:(Q)=>{X(($)=>({session:{...$.session,currentCommand:Q}}))},setError:(Q)=>{X(($)=>({session:{...$.session,error:Q}}))},clearMessages:()=>{k(),X((Q)=>({session:{...Q.session,messages:[],restoredContextMessages:null,restoredVisibleMessageCount:0,error:null,clearCount:Q.session.clearCount+1}}))},resetSession:()=>{k(),X((Q)=>({session:{...Q.session,...G0,sessionId:Q.session.sessionId,isActive:!0}}))},restoreSession:(Q,$,Y)=>{k(),X((V)=>({session:{...V.session,sessionId:Q,messages:$,restoredContextMessages:Y??null,restoredVisibleMessageCount:Y?$.length:0,error:null,isActive:!0}}))},updateTokenUsage:(Q)=>{X(($)=>{let Y=$.session.tokenUsage,V=(Q.inputTokens??0)-(Q.inputTokens!==void 0?Y.inputTokens:0),J=(Q.outputTokens??0)-(Q.outputTokens!==void 0?Y.outputTokens:0),G=Y.totalInputTokens+Math.max(0,V),U=Y.totalOutputTokens+Math.max(0,J),H=Y.cacheReadTokens+(Q.cacheReadTokens??0),W=Y.cacheWriteTokens+(Q.cacheWriteTokens??0),D=$.config?.config,O=D?.models?.find((j)=>j.id===D.currentModelId)?.model??"",z=Z0(O,G,U,H,W);return{session:{...$.session,tokenUsage:{...Y,...Q,totalInputTokens:G,totalOutputTokens:U,cacheReadTokens:H,cacheWriteTokens:W,estimatedCostUsd:z}}}})},resetTokenUsage:()=>{X((Q)=>({session:{...Q.session,tokenUsage:{...U0}}}))},setCurrentThinkingContent:(Q)=>{if(Z().session.currentThinkingContent===Q)return;X(($)=>({session:{...$.session,currentThinkingContent:Q}}))},appendThinkingContent:(Q)=>{X(($)=>({session:{...$.session,currentThinkingContent:($.session.currentThinkingContent||"")+Q}}))},setThinkingExpanded:(Q)=>{X(($)=>({session:{...$.session,thinkingExpanded:Q}}))},toggleThinkingExpanded:()=>{X((Q)=>({session:{...Q.session,thinkingExpanded:!Q.session.thinkingExpanded}}))},setHistoryExpanded:(Q)=>{X(($)=>({session:{...$.session,historyExpanded:Q}}))},toggleHistoryExpanded:()=>{X((Q)=>({session:{...Q.session,historyExpanded:!Q.session.historyExpanded}}))},setExpandedMessageCount:(Q)=>{X(($)=>({session:{...$.session,expandedMessageCount:Q}}))},incrementClearCount:()=>{X((Q)=>({session:{...Q.session,clearCount:Q.session.clearCount+1}}))},startStreamingAssistantMessage:()=>{let Q=`assistant-${Date.now()}-${Math.random()}`,$={id:Q,role:"assistant",content:"",timestamp:Date.now()};return M=[],X((Y)=>({session:{...Y.session,messages:[...Y.session.messages,$],currentStreamingMessageId:Q,currentStreamingChunks:[],currentStreamingLines:[],currentStreamingTail:"",currentStreamingLineCount:0,currentStreamingVersion:0,error:null}})),Q},appendAssistantContent:(Q)=>{let $=Z().session.currentStreamingMessageId,Y=$??`assistant-${Date.now()}-${Math.random()}`;return M.push(Q),X((V)=>{let J=(L)=>L.endsWith("\r")?L.slice(0,-1):L,G=$?V.session.currentStreamingLines:[],U=$?V.session.currentStreamingTail:"",H=$?V.session.currentStreamingLineCount:0,W=$?V.session.currentStreamingVersion:0,v=(U+Q).split(`
16
- `),O=v.slice(0,-1).map(J),z=J(v[v.length-1]??""),j=G;if(O.length>0){if(j=[...G,...O],j.length>J0){let L=j.length-J0;j=j.slice(L)}}return{session:{...V.session,currentStreamingMessageId:Y,currentStreamingLines:j,currentStreamingTail:z,currentStreamingLineCount:H+O.length,currentStreamingVersion:W+1,error:null}}}),Y},finalizeStreamingMessage:(Q,$)=>{let Y=g0();X((V)=>{let J=V.session.currentStreamingMessageId,U=Y.join("")+(Q||""),H=(V.session.currentThinkingContent||"")+($||"");if(U.length>0){let W={id:J||`assistant-${Date.now()}-${Math.random()}`,role:"assistant",content:U,timestamp:Date.now(),thinkingContent:H||void 0};return{session:{...V.session,messages:[...V.session.messages,W],currentStreamingMessageId:null,currentStreamingChunks:[],currentStreamingLines:[],currentStreamingTail:"",currentStreamingLineCount:0,currentStreamingVersion:0,currentThinkingContent:null,finalizingStreamingMessageId:W.id}}}return{session:{...V.session,currentStreamingMessageId:null,currentStreamingChunks:[],currentStreamingLines:[],currentStreamingTail:"",currentStreamingLineCount:0,currentStreamingVersion:0,currentThinkingContent:null,finalizingStreamingMessageId:null}}})},clearFinalizingStreamingMessageId:()=>{X((Q)=>({session:{...Q.session,finalizingStreamingMessageId:null}}))},discardStreamingMessage:()=>{M=[],X((Q)=>({session:{...Q.session,currentStreamingMessageId:null,currentStreamingChunks:[],currentStreamingLines:[],currentStreamingTail:"",currentStreamingLineCount:0,currentStreamingVersion:0,finalizingStreamingMessageId:null}}))}}});import{nanoid as l0}from"nanoid";import{promises as w}from"node:fs";import*as F from"node:path";import{fileURLToPath as d0}from"node:url";import{nanoid as m0}from"nanoid";var j0={proposal:"proposal.md",spec:"spec.md",requirements:"requirements.md",design:"design.md",tasks:"tasks.md",meta:".meta.json"},P={SPECS:"specs",CHANGES:"changes",ARCHIVE:"archive",STEERING:"steering",SPEC_DELTA:"specs"},C={CONSTITUTION:"constitution.md",PRODUCT:"product.md",TECH:"tech.md",STRUCTURE:"structure.md"};var T={init:["requirements"],requirements:["design","tasks"],design:["tasks"],tasks:["implementation"],implementation:["done","tasks"],done:[]},A1={init:"初始化",requirements:"需求定义",design:"架构设计",tasks:"任务分解",implementation:"实现中",done:"已完成"},H0={init:"proposal",requirements:"requirements",design:"design",tasks:"tasks",implementation:"tasks",done:null};var r0=d0(import.meta.url),c0=F.dirname(r0),z0=F.join(c0,"templates");class N{workspaceRoot;bladeDir;constructor(X){this.workspaceRoot=X,this.bladeDir=F.join(X,".blade")}getSpecsDir(){return F.join(this.bladeDir,P.SPECS)}getChangesDir(){return F.join(this.bladeDir,P.CHANGES)}getArchiveDir(){return F.join(this.bladeDir,P.ARCHIVE)}getSteeringDir(){return F.join(this.bladeDir,P.STEERING)}getChangePath(X){return F.join(this.getChangesDir(),X)}getChangeFilePath(X,Z){return F.join(this.getChangePath(X),j0[Z])}async initializeDirectories(){await w.mkdir(this.getChangesDir(),{recursive:!0,mode:493})}async createChangeDir(X){let Z=this.getChangePath(X);return await w.mkdir(Z,{recursive:!0,mode:493}),await w.mkdir(F.join(Z,P.SPEC_DELTA),{recursive:!0,mode:493}),Z}async readFile(X){try{return await w.readFile(X,"utf-8")}catch(Z){if(Z.code==="ENOENT")return null;throw Z}}async writeFile(X,Z){let Q=F.dirname(X);await w.mkdir(Q,{recursive:!0,mode:493}),await w.writeFile(X,Z,"utf-8")}async fileExists(X){try{return await w.access(X),!0}catch{return!1}}async dirExists(X){try{return(await w.stat(X)).isDirectory()}catch{return!1}}createMetadata(X,Z){let Q=new Date().toISOString();return{id:m0(),name:X,description:Z,phase:"init",createdAt:Q,updatedAt:Q,tasks:[]}}async readMetadata(X){let Z=this.getChangeFilePath(X,"meta"),Q=await this.readFile(Z);if(!Q)return null;try{return JSON.parse(Q)}catch{return null}}async writeMetadata(X,Z){let Q=this.getChangeFilePath(X,"meta");Z.updatedAt=new Date().toISOString(),await this.writeFile(Q,JSON.stringify(Z,null,2))}async updatePhase(X,Z){let Q=await this.readMetadata(X);if(!Q)return null;return Q.phase=Z,await this.writeMetadata(X,Q),Q}async readSpecFile(X,Z){let Q=this.getChangeFilePath(X,Z);return this.readFile(Q)}async writeSpecFile(X,Z,Q){let $=this.getChangeFilePath(X,Z);await this.writeFile($,Q);let Y=await this.readMetadata(X);if(Y)await this.writeMetadata(X,Y)}async getPhaseContent(X,Z){let Q=H0[Z];if(!Q)return null;return this.readSpecFile(X,Q)}async readSteeringContext(){let X=this.getSteeringDir(),[Z,Q,$,Y]=await Promise.all([this.readFile(F.join(X,C.CONSTITUTION)),this.readFile(F.join(X,C.PRODUCT)),this.readFile(F.join(X,C.TECH)),this.readFile(F.join(X,C.STRUCTURE))]);return{constitution:Z||void 0,product:Q||void 0,tech:$||void 0,structure:Y||void 0}}async writeSteeringFile(X,Z){let Q=F.join(this.getSteeringDir(),C[X]);await this.writeFile(Q,Z)}async hasSteeringDocs(){let X=this.getSteeringDir();if(!await this.dirExists(X))return!1;return(await w.readdir(X)).length>0}async listActiveChanges(){let X=this.getChangesDir();if(!await this.dirExists(X))return[];return(await w.readdir(X,{withFileTypes:!0})).filter((Q)=>Q.isDirectory()).map((Q)=>Q.name)}async listArchivedChanges(){let X=this.getArchiveDir();if(!await this.dirExists(X))return[];return(await w.readdir(X,{withFileTypes:!0})).filter((Q)=>Q.isDirectory()).map((Q)=>Q.name)}async changeExists(X){return this.dirExists(this.getChangePath(X))}async archiveChange(X){let Z=this.getChangePath(X),Q=F.join(this.getArchiveDir(),X);await w.mkdir(F.dirname(Q),{recursive:!0,mode:493}),await w.rename(Z,Q)}async restoreChange(X){let Z=F.join(this.getArchiveDir(),X),Q=this.getChangePath(X);await w.rename(Z,Q)}async listSpecDomains(){let X=this.getSpecsDir();if(!await this.dirExists(X))return[];return(await w.readdir(X,{withFileTypes:!0})).filter((Q)=>Q.isDirectory()).map((Q)=>Q.name)}async readAuthorativeSpec(X){let Z=F.join(this.getSpecsDir(),X,"spec.md");return this.readFile(Z)}async writeAuthorativeSpec(X,Z){let Q=F.join(this.getSpecsDir(),X,"spec.md");await this.writeFile(Q,Z)}async mergeSpecDeltas(X){let Z=F.join(this.getChangePath(X),P.SPEC_DELTA);if(!await this.dirExists(Z))return[];let Q=[],$=await w.readdir(Z,{withFileTypes:!0});for(let Y of $){if(!Y.isDirectory())continue;let V=F.join(Z,Y.name,"spec.md"),J=await this.readFile(V);if(J){let G=await this.readAuthorativeSpec(Y.name),U=G?`${G}
17
-
18
- ---
19
-
20
- <!-- Merged from ${X} -->
21
-
22
- ${J}`:J;await this.writeAuthorativeSpec(Y.name,U),Q.push(Y.name)}}return Q}static TEMPLATE_NAMES={proposal:"proposal.md.template",spec:"spec.md.template",requirements:"requirements.md.template",design:"design.md.template",tasks:"tasks.md.template",meta:""};static STEERING_TEMPLATE_NAMES={CONSTITUTION:"steering/constitution.md.template",PRODUCT:"steering/product.md.template",TECH:"steering/tech.md.template",STRUCTURE:"steering/structure.md.template"};async readTemplate(X){let Z=N.TEMPLATE_NAMES[X];if(!Z)return null;let Q=F.join(z0,Z);return this.readFile(Q)}async readSteeringTemplate(X){let Z=N.STEERING_TEMPLATE_NAMES[X],Q=F.join(z0,Z);return this.readFile(Q)}fillTemplate(X,Z){let Q=X;for(let[$,Y]of Object.entries(Z))Q=Q.replace(new RegExp(`\\{\\{${$}\\}\\}`,"g"),Y);return Q}async createFromTemplate(X,Z,Q){let $=await this.readTemplate(Z);if(!$)return null;let Y=this.fillTemplate($,{name:X,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString(),...Q});return await this.writeSpecFile(X,Z,Y),Y}async createSteeringFromTemplate(X,Z={}){let Q=await this.readSteeringTemplate(X);if(!Q)return null;let $=this.fillTemplate(Q,{createdAt:new Date().toISOString(),...Z});return await this.writeSteeringFile(X,$),$}async initializeSteeringDocs(){let X=[],Z=this.getSteeringDir();for(let[Q,$]of Object.entries(C)){let Y=F.join(Z,$);if(!await this.fileExists(Y))await this.createSteeringFromTemplate(Q),X.push($)}return X}}class x{static instance=null;fileManager=null;workspaceRoot=null;constructor(){}static getInstance(){if(!x.instance)x.instance=new x;return x.instance}static resetInstance(){x.instance=null}async initialize(X){if(this.workspaceRoot===X&&this.fileManager)return;this.workspaceRoot=X,this.fileManager=new N(X),await this.fileManager.initializeDirectories()}getFileManager(){if(!this.fileManager)throw Error("SpecService not initialized. Call initialize() first.");return this.fileManager}async readSteeringContext(){return this.getFileManager().readSteeringContext()}async readSpecMetadata(X){return this.getFileManager().readMetadata(X)}async specExists(X){return this.getFileManager().changeExists(X)}getSpecPath(X){return this.getFileManager().getChangePath(X)}async createSpec(X,Z){let Q=this.getFileManager();if(await Q.changeExists(X))return{success:!1,message:`Spec "${X}" already exists`,error:"SPEC_EXISTS"};let $=await Q.createChangeDir(X),Y=Q.createMetadata(X,Z);await Q.writeMetadata(X,Y);let V=this.generateProposalTemplate(X,Z);return await Q.writeSpecFile(X,"proposal",V),{success:!0,message:`Spec "${X}" created successfully`,data:{spec:Y,path:$}}}async loadSpec(X){let Z=this.getFileManager(),Q=await Z.readMetadata(X);if(!Q)return{success:!1,message:`Spec "${X}" not found`,error:"SPEC_NOT_FOUND"};let $=Z.getChangePath(X);return{success:!0,message:`Spec "${X}" loaded successfully`,data:{spec:Q,path:$}}}canTransitionPhase(X,Z){return T[X].includes(Z)}getAllowedTransitions(X){return T[X]}async updatePhase(X,Z){return this.getFileManager().updatePhase(X,Z)}createTask(X,Z,Q){return{id:l0(8),title:X,description:Z,status:"pending",dependencies:Q?.dependencies||[],affectedFiles:Q?.affectedFiles||[],complexity:Q?.complexity||"medium"}}async saveMetadata(X,Z){await this.getFileManager().writeMetadata(X,Z)}getNextTask(X){return X.find((Z)=>{if(Z.status!=="pending")return!1;return Z.dependencies.every((Q)=>{return X.find((Y)=>Y.id===Q)?.status==="completed"})})||null}getTaskProgress(X){if(X.length===0)return{total:0,completed:0,percentage:0};let Z=X.length,Q=X.filter((Y)=>Y.status==="completed").length,$=Math.round(Q/Z*100);return{total:Z,completed:Q,percentage:$}}async listActiveSpecs(){return this.getFileManager().listActiveChanges()}async listArchivedSpecs(){return this.getFileManager().listArchivedChanges()}async archiveSpec(X){let Z=this.getFileManager();return await Z.mergeSpecDeltas(X),await Z.updatePhase(X,"done"),await Z.archiveChange(X),{success:!0,message:`Spec "${X}" archived successfully`}}async validateSpec(X){let Z=this.getFileManager(),Q=[],$=[],[Y,V,J,G,U]=await Promise.all([Z.readSpecFile(X.name,"proposal"),Z.readSpecFile(X.name,"spec"),Z.readSpecFile(X.name,"requirements"),Z.readSpecFile(X.name,"design"),Z.readSpecFile(X.name,"tasks")]),H={proposal:!!Y,spec:!!V,requirements:!!J,design:!!G,tasks:!!U};if(X.phase==="requirements"&&!H.requirements)Q.push({severity:"warning",file:"requirements",message:"Requirements document is missing"}),$.push("Generate requirements using EARS format");if(X.phase==="design"&&!H.design)Q.push({severity:"warning",file:"design",message:"Design document is missing"}),$.push("Create architecture diagrams and API contracts");if(X.phase==="tasks"&&X.tasks.length===0)Q.push({severity:"warning",file:"tasks",message:"No tasks defined"}),$.push("Break down the spec into atomic tasks");if(X.phase==="implementation"){let W=this.getTaskProgress(X.tasks);if(W.completed<W.total)Q.push({severity:"info",file:"tasks",message:`${W.total-W.completed} tasks remaining`})}return{valid:Q.filter((W)=>W.severity==="error").length===0,phase:X.phase,completeness:H,issues:Q,suggestions:$}}generateProposalTemplate(X,Z){return`# ${X}
23
-
24
- ## Summary
25
-
26
- ${Z}
27
-
28
- ## Background
29
-
30
- <!-- Why is this change needed? What problem does it solve? -->
31
-
32
- ## Goals
33
-
34
- <!-- What are the specific objectives of this change? -->
35
-
36
- - [ ] Goal 1
37
- - [ ] Goal 2
38
-
39
- ## Non-Goals
40
-
41
- <!-- What is explicitly out of scope? -->
42
-
43
- ## Risks and Mitigations
44
-
45
- <!-- What could go wrong? How will you address it? -->
46
-
47
- | Risk | Mitigation |
48
- |------|------------|
49
- | | |
50
-
51
- ## Open Questions
52
-
53
- <!-- What needs to be clarified before proceeding? -->
54
-
55
- 1.
56
- `}}var W0=K0("Spec"),F0={currentSpec:null,specPath:null,isActive:!1,steeringContext:null,recentSpecs:[],isLoading:!1,error:null,workspaceRoot:null},n=(X,Z)=>({...F0,actions:{initialize:async(Q)=>{let $=x.getInstance();await $.initialize(Q);let Y=await $.readSteeringContext();X((V)=>({spec:{...V.spec,workspaceRoot:Q,steeringContext:Y}}))},createSpec:async(Q,$)=>{let V=await x.getInstance().createSpec(Q,$);if(V.success&&V.data){let{spec:J,path:G}=V.data,U=Z().spec.recentSpecs.filter((H)=>H!==Q);U.unshift(Q),X((H)=>({spec:{...H.spec,currentSpec:J,specPath:G,isActive:!0,recentSpecs:U.slice(0,10)}}))}return V},loadSpec:async(Q)=>{let Y=await x.getInstance().loadSpec(Q);if(Y.success&&Y.data){let{spec:V,path:J}=Y.data,G=Z().spec.recentSpecs.filter((U)=>U!==Q);G.unshift(Q),X((U)=>({spec:{...U.spec,currentSpec:V,specPath:J,isActive:!0,recentSpecs:G.slice(0,10)}}))}return Y},closeSpec:()=>{X((Q)=>({spec:{...Q.spec,currentSpec:null,specPath:null,isActive:!1}}))},exitSpecMode:()=>{Z().spec.actions.closeSpec()},transitionPhase:async(Q)=>{let $=Z().spec.currentSpec;if(!$)return{success:!1,message:"No active spec",error:"NO_ACTIVE_SPEC"};let Y=x.getInstance();if(!Y.canTransitionPhase($.phase,Q))return{success:!1,message:`Cannot transition from "${$.phase}" to "${Q}"`,error:"INVALID_TRANSITION"};let V=await Y.updatePhase($.name,Q);if(!V)return{success:!1,message:"Failed to update phase",error:"UPDATE_FAILED"};if(X((J)=>({spec:{...J.spec,currentSpec:V}})),Q==="done")try{let{config:J}=Z();if(J.actions)J.actions.updateConfig({permissionMode:"default"});W0.info("Spec 已完成,已自动退出 Spec 模式")}catch(J){W0.error("自动退出 Spec 模式失败:",J)}return{success:!0,message:`Transitioned to "${Q}" phase`,data:{spec:V,phase:Q}}},getAllowedTransitions:()=>{let Q=Z().spec.currentSpec;if(!Q)return[];return T[Q.phase]},addTask:async(Q,$,Y)=>{let V=Z().spec.currentSpec;if(!V)return{success:!1,message:"No active spec",error:"NO_ACTIVE_SPEC"};let J=x.getInstance(),G=J.createTask(Q,$,Y),U={...V,tasks:[...V.tasks,G],updatedAt:new Date().toISOString()};return await J.saveMetadata(V.name,U),X((H)=>({spec:{...H.spec,currentSpec:U}})),{success:!0,message:`Task "${Q}" added`,data:{task:G}}},updateTaskStatus:async(Q,$)=>{let Y=Z().spec.currentSpec;if(!Y)return{success:!1,message:"No active spec",error:"NO_ACTIVE_SPEC"};let V=Y.tasks.find((W)=>W.id===Q);if(!V)return{success:!1,message:`Task "${Q}" not found`,error:"TASK_NOT_FOUND"};let J={...V,status:$,completedAt:$==="completed"?new Date().toISOString():V.completedAt},G=Y.tasks.map((W)=>W.id===Q?J:W),U={...Y,tasks:G,currentTaskId:$==="in_progress"?Q:Y.currentTaskId===Q?void 0:Y.currentTaskId,updatedAt:new Date().toISOString()};return await x.getInstance().saveMetadata(Y.name,U),X((W)=>({spec:{...W.spec,currentSpec:U}})),{success:!0,message:`Task status updated to "${$}"`,data:{task:J}}},getNextTask:()=>{let Q=Z().spec.currentSpec;if(!Q)return null;return x.getInstance().getNextTask(Q.tasks)},getTaskProgress:()=>{let Q=Z().spec.currentSpec;if(!Q)return{total:0,completed:0,percentage:0};return x.getInstance().getTaskProgress(Q.tasks)},listSpecs:async(Q)=>{let $=x.getInstance(),Y=[],V=await $.listActiveSpecs();for(let J of V){let G=await $.readSpecMetadata(J);if(!G)continue;if(Q?.phase&&G.phase!==Q.phase)continue;if(Q?.tags&&!Q.tags.some((H)=>G.tags?.includes(H)))continue;if(Q?.query&&!G.name.toLowerCase().includes(Q.query.toLowerCase())&&!G.description.toLowerCase().includes(Q.query.toLowerCase()))continue;let U=$.getTaskProgress(G.tasks);Y.push({name:G.name,description:G.description,phase:G.phase,updatedAt:G.updatedAt,path:$.getSpecPath(J),isArchived:!1,taskProgress:{total:U.total,completed:U.completed}})}if(Q?.includeArchived){let J=await $.listArchivedSpecs();for(let G of J)Y.push({name:G,description:"(archived)",phase:"done",updatedAt:"",path:`archive/${G}`,isArchived:!0,taskProgress:{total:0,completed:0}})}return Y.sort((J,G)=>{if(J.isArchived!==G.isArchived)return J.isArchived?1:-1;return new Date(G.updatedAt).getTime()-new Date(J.updatedAt).getTime()}),Y},archiveCurrentSpec:async()=>{let Q=Z().spec.currentSpec;if(!Q)return{success:!1,message:"No active spec",error:"NO_ACTIVE_SPEC"};let Y=await x.getInstance().archiveSpec(Q.name);if(Y.success)Z().spec.actions.closeSpec();return Y},validateCurrentSpec:async()=>{let Q=Z().spec.currentSpec;if(!Q)return{valid:!1,phase:"init",completeness:{proposal:!1,spec:!1,requirements:!1,design:!1,tasks:!1},issues:[{severity:"error",file:"meta",message:"No active spec"}],suggestions:["Create a new spec with /spec proposal <name>"]};return x.getInstance().validateSpec(Q)},getSteeringContextString:async()=>{let Q=Z().spec.steeringContext;if(!Q)return null;let $=[];if(Q.constitution)$.push(`## Constitution (Project Governance)
57
-
58
- ${Q.constitution}`);if(Q.product)$.push(`## Product Vision
59
-
60
- ${Q.product}`);if(Q.tech)$.push(`## Technology Stack
61
-
62
- ${Q.tech}`);if(Q.structure)$.push(`## Code Structure
63
-
64
- ${Q.structure}`);return $.length>0?$.join(`
65
-
66
- ---
67
-
68
- `):null},setError:(Q)=>{X(($)=>({spec:{...$.spec,error:Q}}))},setLoading:(Q)=>{X(($)=>({spec:{...$.spec,isLoading:Q}}))},reset:()=>{X((Q)=>({spec:{...F0,actions:Q.spec.actions}}))}}});var a0=s0()(o0(n0((...X)=>({session:o(...X),app:g(...X),config:m(...X),focus:r(...X),command:d(...X),spec:n(...X)})),{name:"BladeStore",enabled:!0})),q=()=>a0.getState(),t1=()=>q().session.actions,e1=()=>q().app.actions,Q5=()=>q().session.messages,y=()=>q().config.config,I=null;async function X5(){if(y()!==null)return;if(I)return I;return I=(async()=>{try{let Q=await q0.getInstance().initialize();q().config.actions.setConfig(Q)}catch(Z){throw I=null,Error(`[FAIL] Store 未初始化且无法自动初始化
69
-
70
- `+`原因: ${Z instanceof Error?Z.message:"未知错误"}
71
-
72
- `+`请确保:
73
- `+`1. 配置文件格式正确 (~/.blade/config.json)
74
- `+`2. 运行 blade 进行首次配置
75
- `+"3. 配置文件权限正确")}finally{I=null}})(),I}var Z5=()=>q().config.config?.models??[],$5=()=>{let X=y();if(!X)return;let Z=X.currentModelId;return X.models.find(($)=>$.id===Z)??X.models[0]},Y5=(X)=>{let Z=y();if(!Z)return;return Z.models.find((Q)=>Q.id===X)},V5=()=>q().config.config?.mcpServers??{},J5=()=>q().app.thinkingModeEnabled,G5=()=>({setPermissionMode:async(X)=>{q().config.actions.updateConfig({permissionMode:X})},setTheme:async(X,Z={})=>{try{X0.setTheme(X)}catch{return}q().config.actions.updateConfig({theme:X}),await A().save({theme:X},{scope:"global",...Z})},setLanguage:async(X,Z={})=>{q().config.actions.updateConfig({language:X}),await A().save({language:X},{scope:"global",...Z})},setDebug:async(X,Z={})=>{q().config.actions.updateConfig({debug:X}),await A().save({debug:X},{scope:"global",...Z})},setTemperature:async(X,Z={})=>{q().config.actions.updateConfig({temperature:X}),await A().save({temperature:X},{scope:"global",...Z})},updateConfig:async(X,Z={})=>{let Q=y();if(!Q)throw Error("Config not initialized");let $={...Q};q().config.actions.updateConfig(X);try{await A().save(X,Z)}catch(Y){throw q().config.actions.setConfig($),Y}},flush:async()=>{await A().flush()},appendPermissionAllowRule:async(X,Z={})=>{let Q=y();if(!Q)throw Error("Config not initialized");let $=Q.permissions?.allow||[];if(!$.includes(X)){let Y=[...$,X];q().config.actions.updateConfig({permissions:{...Q.permissions,allow:Y}})}await A().appendPermissionRule(X,Z)},appendLocalPermissionAllowRule:async(X,Z={})=>{let Q=y();if(!Q)throw Error("Config not initialized");let $=Q.permissions?.allow||[];if(!$.includes(X)){let Y=[...$,X];q().config.actions.updateConfig({permissions:{...Q.permissions,allow:Y}})}await A().appendLocalPermissionRule(X,Z)},setCurrentModel:async(X,Z={})=>{let Q=y();if(!Q)throw Error("Config not initialized");if(!Q.models.find((Y)=>Y.id===X))throw Error(`Model not found: ${X}`);q().config.actions.updateConfig({currentModelId:X}),await A().save({currentModelId:X},{scope:"global",...Z})},addModel:async(X,Z={})=>{let Q=y();if(!Q)throw Error("Config not initialized");let $="id"in X?X:{id:i0(),...X},V={models:[...Q.models,$]};if(Q.models.length===0)V.currentModelId=$.id;return q().config.actions.updateConfig(V),await A().save(V,{scope:"global",...Z}),$},updateModel:async(X,Z,Q={})=>{let $=y();if(!$)throw Error("Config not initialized");let Y=$.models.findIndex((J)=>J.id===X);if(Y===-1)throw Error(`Model not found: ${X}`);let V=[...$.models];V[Y]={...V[Y],...Z},q().config.actions.updateConfig({models:V}),await A().save({models:V},{scope:"global",...Q})},removeModel:async(X,Z={})=>{let Q=y();if(!Q)throw Error("Config not initialized");if(Q.models.length===1)throw Error("Cannot remove the only model");let $=Q.models.filter((V)=>V.id!==X),Y={models:$};if(Q.currentModelId===X)Y.currentModelId=$[0].id;q().config.actions.updateConfig(Y),await A().save(Y,{scope:"global",...Z})},addMcpServer:async(X,Z,Q={})=>{let $=y();if(!$)throw Error("Config not initialized");let V={...$.mcpServers??{},[X]:Z};q().config.actions.updateConfig({mcpServers:V}),await A().save({mcpServers:V},{scope:"project",...Q})},removeMcpServer:async(X,Z={})=>{let Q=y();if(!Q)throw Error("Config not initialized");let Y={...Q.mcpServers??{}};delete Y[X],q().config.actions.updateConfig({mcpServers:Y}),await A().save({mcpServers:Y},{scope:"project",...Z})}});
76
- export{t as da,X0 as ea,K as fa,G1 as ga,H1 as ha,z1 as ia,W1 as ja,F1 as ka,K1 as la,q1 as ma,T as na,A1 as oa,N as pa,a0 as qa,q as ra,t1 as sa,e1 as ta,Q5 as ua,y as va,X5 as wa,Z5 as xa,$5 as ya,Y5 as za,V5 as Aa,J5 as Ba,G5 as Ca};
@@ -1 +0,0 @@
1
- import{v as a,w as b,x as c}from"./chunk-zvk6ktj1.js";import"./chunk-h7qab07x.js";import"./chunk-qyfdt8h1.js";import"./chunk-k9h9bw13.js";import"./chunk-867h27ke.js";import"./chunk-7ycmx7c2.js";import"./chunk-mt1c5da4.js";import"./chunk-0afbeec0.js";export{a as validatePermissions,c as validateOutput,b as loadConfiguration};
@@ -1,3 +0,0 @@
1
- import{Qb as w}from"./chunk-0afbeec0.js";import{appendFileSync as B,existsSync as N,mkdirSync as R,readdirSync as x,statSync as k,unlinkSync as j}from"node:fs";import Y from"node:path";import{execSync as z}from"node:child_process";import*as O from"node:os";import*as Q from"node:path";function F(q){return Q.resolve(q).replace(/[/\\]/g,"-").replace(/:/g,"_")}function S(q){let G=q.replace(/_/g,":");if(G.startsWith("-"))G="/"+G.slice(1);return G.replace(/-/g,"/")}function A(q){let G=F(q);return Q.join(W(),"projects",G)}function D(q,G){return Q.join(A(q),`${G}.jsonl`)}function P(q){try{return z("git rev-parse --abbrev-ref HEAD",{cwd:q,encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim()||void 0}catch{return}}function W(){return process.env.BLADE_STORAGE_ROOT||Q.join(O.homedir(),".blade")}async function v(){let{readdir:q}=await import("node:fs/promises");try{let G=Q.join(W(),"projects");return(await q(G,{withFileTypes:!0})).filter((H)=>H.isDirectory()).map((H)=>H.name)}catch{return[]}}var Z;((J)=>{J[J.DEBUG=0]="DEBUG";J[J.INFO=1]="INFO";J[J.WARN=2]="WARN";J[J.ERROR=3]="ERROR"})(Z||={});var X=null,U=null,_=!1;function y(q){if(X!==q)X=q}async function c(){}function V(){if(_)return U;_=!0;try{let q=Y.join(W(),"logs");if(!N(q))R(q,{recursive:!0,mode:493});if(k(q).uid===0&&process.getuid&&process.getuid()!==0)return console.error(""),console.error("[FAIL] 权限错误:~/.blade/logs 目录属于 root 用户"),console.error(""),console.error("这通常是因为您曾经使用 sudo 运行过 blade。"),console.error(""),console.error("解决方法:"),console.error(" sudo chown -R $USER:$USER ~/.blade/"),console.error(""),console.error("然后重新运行 blade(不要使用 sudo)"),console.error(""),null;return m(q,30),U=q,q}catch(q){return console.error("[Logger] 无法创建日志目录:",q),null}}function m(q,G){try{let K=x(q),H=Date.now(),J=G*24*60*60*1000;for(let T of K){if(!T.startsWith("blade-")||!T.endsWith(".log")&&!T.endsWith(".jsonl"))continue;let $=Y.join(q,T);try{let E=k($);if(H-E.mtimeMs>J)j($)}catch(E){}}}catch(K){}}function I(){let q=V();if(!q)return null;let G=X||"default";return Y.join(q,`blade-${G}.jsonl`)}function C(q,G,K){let H=I();if(!H)return;try{let J={timestamp:new Date().toISOString(),level:Z[G],category:q,message:K};B(H,JSON.stringify(J)+`
2
- `)}catch(J){}}class M{static globalDebugConfig=null;enabled;minLevel;category;constructor(q={}){if(q.enabled!==void 0)this.enabled=q.enabled;else if(M.globalDebugConfig!==null)this.enabled=Boolean(M.globalDebugConfig);else this.enabled=!1;this.minLevel=q.minLevel??0,this.category=q.category??"General"}static setGlobalDebug(q){M.globalDebugConfig=q}static clearGlobalDebug(){M.globalDebugConfig=null}setEnabled(q){this.enabled=q}parseDebugFilter(q){if(!q)return{enabled:!1};if(q===!0||q==="true"||q==="1")return{enabled:!0};let G=String(q).trim();if(!G)return{enabled:!0};if(G.startsWith("!"))return{enabled:!0,filter:{mode:"exclude",categories:G.split(",").map((J)=>J.trim().replace(/^!/,"")).filter(Boolean)}};return{enabled:!0,filter:{mode:"include",categories:G.split(",").map((H)=>H.trim()).filter(Boolean)}}}shouldLogCategory(q){if(!q)return!0;let G=this.category.toLowerCase();if(q.mode==="include")return q.categories.some((K)=>G.includes(K.toLowerCase()));return!q.categories.some((K)=>G.includes(K.toLowerCase()))}shouldLogToConsole(q){if(M.globalDebugConfig!==null){let{enabled:G,filter:K}=this.parseDebugFilter(M.globalDebugConfig);if(!G)return!1;if(q<this.minLevel)return!1;return this.shouldLogCategory(K)}return this.enabled&&q>=this.minLevel}log(q,...G){let K=G.map((H)=>typeof H==="object"?JSON.stringify(H):String(H)).join(" ");if(C(this.category,q,K),this.shouldLogToConsole(q)){let H=Z[q],J=`[${this.category}] [${H}]`;console.error(J,...G)}}debug(...q){this.log(0,...q)}info(...q){this.log(1,...q)}warn(...q){this.log(2,...q)}error(...q){this.log(3,...q)}}function d(q,G){return new M({...G,category:q})}var L=new M({category:"General"});
3
- export{S as Fb,A as Gb,D as Hb,P as Ib,W as Jb,v as Kb,y as Lb,c as Mb,M as Nb,d as Ob,L as Pb};
@@ -1,2 +0,0 @@
1
- import{j as zf,k as Tf}from"./chunk-v1d0d4b4.js";import{A as wf,C as s,D as Mf,H as Ff,I as g,K as Uf,L as qf,N as Bf,Q as h,X as Lf}from"./chunk-92qcc3gj.js";import{$ as T}from"./chunk-aam53te2.js";import{Ca as z,va as S,xa as Rf,ya as Xf}from"./chunk-k9h9bw13.js";import{Ia as u}from"./chunk-xmdpc0y5.js";import{Oa as _f,Qa as t,Za as mf}from"./chunk-dzmrdtpc.js";import{xb as X}from"./chunk-7ycmx7c2.js";import{Ob as R}from"./chunk-mt1c5da4.js";import{Qb as Jf}from"./chunk-0afbeec0.js";var I0={port:{type:"number",describe:"Port to listen on (0 for auto)",default:0},hostname:{type:"string",describe:"Hostname to listen on",default:"127.0.0.1"},cors:{type:"array",describe:"Additional domains to allow for CORS",default:[]}};function v0(V){return{port:V.port??0,hostname:V.hostname??"127.0.0.1",cors:V.cors??[]}}import{Hono as T0}from"hono";import{cors as y0}from"hono/cors";import{existsSync as gf,readFileSync as e}from"node:fs";import{createServer as _0}from"node:http";import{networkInterfaces as D0}from"node:os";import{dirname as b0,extname as w0,join as w}from"node:path";import{fileURLToPath as L0}from"node:url";import{WebSocketServer as P0}from"ws";import{z as c}from"zod";class p extends Error{code;statusCode;constructor(V,$,f=500){super($);this.code=V;this.statusCode=f;this.name="BladeServerError"}toObject(){return{error:{code:this.code,message:this.message}}}}class P extends p{constructor(V,$){super("NOT_FOUND",$?`${V} not found: ${$}`:`${V} not found`,404)}}class A extends p{constructor(V){super("BAD_REQUEST",V,400)}}var g0=c.object({error:c.object({code:c.string(),message:c.string()})});import{Hono as cf}from"hono";import{z as k}from"zod";var $f=R("Service"),af=k.object({updates:k.record(k.any()),options:k.object({scope:k.enum(["local","project","global"]).optional(),immediate:k.boolean().optional()}).optional()}),Gf=()=>{let V=new cf;return V.get("/",async($)=>{try{let f=S();return $.json(f||{})}catch(f){return $f.error("[ConfigRoutes] Failed to get config:",f),$.json({})}}),V.put("/",async($)=>{try{let f=await $.req.json(),O=af.safeParse(f);if(!O.success)throw new A("Invalid config update format");let{updates:M,options:Q}=O.data;return await z().updateConfig(M,Q),$.json({success:!0,updates:M})}catch(f){throw $f.error("[ConfigRoutes] Failed to update config:",f),f}}),V.get("/permissions",async($)=>{try{let f=S();return $.json(f?.permissions||{})}catch(f){return $f.error("[ConfigRoutes] Failed to get permissions:",f),$.json({})}}),V};import{Hono as tf}from"hono";var Nf=()=>{let V=new tf;return V.get("/health",($)=>{return $.json({healthy:!0,version:u()})}),V.get("/info",($)=>{return $.json({version:u(),platform:process.platform,arch:process.arch,nodeVersion:process.version,cwd:X()})}),V};import{Hono as nf}from"hono";var o=R("Service"),xf=()=>{let V=new nf;return V.get("/",async($)=>{try{let O=T.getInstance().getAllServers(),M=Array.from(O.entries()).map(([Q,J])=>({id:Q,name:Q,status:J.status==="connected"?"connected":J.status==="connecting"?"connecting":J.lastError?"error":"offline",endpoint:J.config.command?`${J.config.command} ${(J.config.args||[]).join(" ")}`.trim():J.config.url||"Unknown",description:`MCP server: ${Q}`,tools:J.tools.map((Z)=>Z.name),connectedAt:J.connectedAt?.toISOString(),error:J.lastError?.message}));return $.json(M)}catch(f){return o.error("[McpRoutes] Failed to get MCP servers:",f),$.json([])}}),V.post("/:name/connect",async($)=>{try{let f=$.req.param("name");return await T.getInstance().connectServer(f),$.json({success:!0})}catch(f){return o.error("[McpRoutes] Failed to connect MCP server:",f),$.json({success:!1,error:f.message},500)}}),V.post("/:name/disconnect",async($)=>{try{let f=$.req.param("name");return await T.getInstance().disconnectServer(f),$.json({success:!0})}catch(f){return o.error("[McpRoutes] Failed to disconnect MCP server:",f),$.json({success:!1,error:f.message},500)}}),V.delete("/:name",async($)=>{try{let f=$.req.param("name");await T.getInstance().unregisterServer(f);let M=S();if(M?.mcpServers){let{[f]:Q,...J}=M.mcpServers;await z().updateConfig({mcpServers:J})}return $.json({success:!0})}catch(f){return o.error("[McpRoutes] Failed to delete MCP server:",f),$.json({success:!1,error:f.message},500)}}),V.post("/",async($)=>{try{let f=await $.req.json(),{name:O,config:M}=f;if(!O||!M)return $.json({success:!1,error:"Missing name or config"},400);await T.getInstance().registerServer(O,M);let J=S();return await z().updateConfig({mcpServers:{...J?.mcpServers,[O]:M}}),$.json({success:!0})}catch(f){return o.error("[McpRoutes] Failed to add MCP server:",f),$.json({success:!1,error:f.message},500)}}),V};import{Hono as sf}from"hono";var a=R("Service"),Ef=()=>{let V=new sf;return V.get("/",async($)=>{try{let f=Rf(),O=Xf();return $.json({configured:f,current:O})}catch(f){return a.error("[ModelsRoutes] Failed to get models:",f),$.json({configured:[],current:null})}}),V.post("/",async($)=>{try{let f=await $.req.json(),{provider:O,name:M,model:Q,baseUrl:J,apiKey:Z}=f;if(!Q)throw new A("model is required");let j=await z().addModel({provider:O||"openai-compatible",name:M||Q,model:Q,baseUrl:J||void 0,apiKey:Z||void 0});return $.json({success:!0,model:j})}catch(f){throw a.error("[ModelsRoutes] Failed to add model:",f),f}}),V.put("/:modelId",async($)=>{try{let f=$.req.param("modelId"),O=await $.req.json(),{baseUrl:M,apiKey:Q,model:J}=O;return await z().updateModel(f,{baseUrl:M||void 0,apiKey:Q||void 0,model:J||void 0}),$.json({success:!0})}catch(f){throw a.error("[ModelsRoutes] Failed to update model:",f),f}}),V.delete("/:modelId",async($)=>{try{let f=$.req.param("modelId");return await z().removeModel(f),$.json({success:!0})}catch(f){throw a.error("[ModelsRoutes] Failed to delete model:",f),f}}),V};import{Hono as K0}from"hono";import{z as C}from"zod";import{Hono as ef}from"hono";import{streamSSE as f0}from"hono/streaming";import{LRUCache as $0}from"lru-cache";import{nanoid as d}from"nanoid";import{z as U}from"zod";var E=R("Service"),V0=U.object({title:U.string().optional(),projectPath:U.string().optional()}),O0=U.object({content:U.string(),attachments:U.array(U.object({type:U.enum(["file","image","url"]),path:U.string().optional(),url:U.string().optional(),content:U.string().optional(),mimeType:U.string().optional(),name:U.string().optional()})).optional(),permissionMode:U.enum(["default","autoEdit","plan","spec","yolo"]).optional()}),M0=U.object({title:U.string().optional()}),B=new Map,D=new $0({max:100,ttl:1800000,dispose:(V,$)=>{if(V.status==="running"||V.status==="waiting_permission")V.abortController.abort(),E.debug(`[SessionRoutes] Run ${$} disposed due to cache eviction`)}}),J0=(V)=>{if(!V||typeof V!=="object")return V;let $={...V},f=200000;if(typeof $.oldContent==="string"&&$.oldContent.length>f)delete $.oldContent;if(typeof $.newContent==="string"&&$.newContent.length>f)delete $.newContent;return $};function Q0(V){if(typeof V==="string")return V;return V.filter(($)=>$.type==="text").map(($)=>$.text).join(`
2
- `)}function Y0(V,$){let f=($??[]).filter((M)=>M.type==="image"&&typeof M.content==="string").map((M)=>({type:"image_url",image_url:{url:M.content}}));if(f.length===0)return V;let O=[];if(V.trim())O.push({type:"text",text:V});return O.push(...f),O}var Wf=()=>{let V=new ef,$=new Map;return V.get("/",async(f)=>{try{let O=await h.listSessions(),M=new Set(O.filter((G)=>G.relationType==="subagent").map((G)=>G.sessionId)),Q=Array.from(B.values()).filter((G)=>!M.has(G.id)&&G.relationType!=="subagent").map((G)=>({sessionId:G.id,projectPath:G.projectPath,title:G.title,parentId:void 0,relationType:void 0,status:void 0,agentType:void 0,model:void 0,messageCount:G.messages.length,firstMessageTime:G.createdAt.toISOString(),lastMessageTime:new Date().toISOString(),hasErrors:!1,isActive:!0})),J=new Set(Q.map((G)=>G.sessionId)),Z=O.filter((G)=>!B.has(G.sessionId)&&!J.has(G.sessionId)&&G.relationType!=="subagent"),j=new Set(J),Y=Z.filter((G)=>{if(j.has(G.sessionId))return!1;return j.add(G.sessionId),!0}),K=[...Q,...Y];return f.json(K)}catch(O){return E.error("[SessionRoutes] Failed to list sessions:",O),f.json([])}}),V.post("/",async(f)=>{try{let O=await f.req.json(),M=V0.safeParse(O);if(!M.success)throw new A("Invalid request body");let{title:Q,projectPath:J}=M.data,Z=d(12),j=J||f.get("directory")||X(),Y={id:Z,projectPath:j,title:Q||`Session ${Z.slice(0,6)}`,createdAt:new Date,messages:[]};return B.set(Z,Y),f.json({sessionId:Z,projectPath:j,title:Y.title,parentId:void 0,relationType:void 0,status:void 0,agentType:void 0,model:void 0,messageCount:0,firstMessageTime:Y.createdAt.toISOString(),lastMessageTime:Y.createdAt.toISOString(),hasErrors:!1})}catch(O){throw E.error("[SessionRoutes] Failed to create session:",O),O}}),V.get("/:sessionId",async(f)=>{let O=f.req.param("sessionId"),M=B.get(O);if(M)return f.json({sessionId:M.id,projectPath:M.projectPath,title:M.title,messageCount:M.messages.length,firstMessageTime:M.createdAt.toISOString(),lastMessageTime:new Date().toISOString(),hasErrors:!1,isActive:!0});try{let J=(await h.listSessions()).find((Z)=>Z.sessionId===O);if(!J)throw new P("Session",O);return f.json(J)}catch(Q){if(Q instanceof P)throw Q;throw E.error("[SessionRoutes] Failed to get session:",Q),Q}}),V.patch("/:sessionId",async(f)=>{let O=f.req.param("sessionId");try{let M=await f.req.json(),Q=M0.safeParse(M);if(!Q.success)throw new A("Invalid request body");let{title:J}=Q.data,Z=B.get(O);if(Z&&J)Z.title=J;return f.json({success:!0,title:J})}catch(M){throw E.error("[SessionRoutes] Failed to update session:",M),M}}),V.delete("/:sessionId",async(f)=>{let O=f.req.param("sessionId"),M=B.get(O);if(M?.currentRunId){let J=D.get(M.currentRunId);if(J)J.abortController.abort(),g.publish(O,"run.cancelled",{runId:J.id}),D.delete(M.currentRunId)}try{await h.deleteSession(O)}catch(J){E.warn("[SessionRoutes] Failed to delete session file:",J)}B.delete(O);let Q=$.get(O);if(Q){if(await Q.dispose(),$.delete(O),$.size===0)await T.getInstance().disconnectAll()}return f.json({success:!0})}),V.get("/:sessionId/message",async(f)=>{let O=f.req.param("sessionId");try{let M=await h.loadSession(O);return f.json(M)}catch(M){return E.error("[SessionRoutes] Failed to get messages:",M),f.json([])}}),V.get("/:sessionId/events",async(f)=>{let O=f.req.param("sessionId"),M=B.get(O);if(!M){let Q=f.get("directory")||X();M={id:O,projectPath:Q,title:`Session ${O.slice(0,6)}`,createdAt:new Date,messages:[]},B.set(O,M)}return f0(f,async(Q)=>{await Q.writeSSE({data:JSON.stringify({type:"connected",properties:{sessionId:O,timestamp:Date.now()}})});let Z=g.subscribe((Y)=>{if(Y.sessionId!==O)return;Q.writeSSE({data:JSON.stringify({type:Y.type,properties:{sessionId:Y.sessionId,...Y.properties}})}).catch(()=>{})}),j=setInterval(()=>{if(!Q.aborted)Q.writeSSE({data:JSON.stringify({type:"heartbeat",properties:{timestamp:Date.now()}})}).catch(()=>{})},15000);Q.onAbort(()=>{clearInterval(j),Z()});while(!0)if(await new Promise((Y)=>setTimeout(Y,1000)),Q.aborted)break})}),V.post("/:sessionId/message",async(f)=>{let O=f.req.param("sessionId"),M=await f.req.json(),Q=O0.safeParse(M);if(!Q.success)throw new A("Invalid message format");let{content:J,attachments:Z,permissionMode:j}=Q.data,Y=j||"default",K=f.get("directory")||X(),G=Y0(J,Z),x=B.get(O);if(!x){let N=await h.loadSession(O).catch(()=>[]);x={id:O,projectPath:K,title:`Session ${O.slice(0,6)}`,createdAt:new Date,messages:N},B.set(O,x)}let q=d(12),L=new AbortController,m={id:q,sessionId:O,status:"running",abortController:L,createdAt:new Date};return D.set(q,m),x.currentRunId=q,Z0(m,x,G,Y,$).catch((N)=>{E.error(`[SessionRoutes] Run ${q} failed:`,N)}),f.json({runId:q,status:"running"},202)}),V.post("/:sessionId/abort",async(f)=>{let O=f.req.param("sessionId"),M=B.get(O);if(M?.currentRunId){let Q=D.get(M.currentRunId);if(Q)Q.abortController.abort(),Q.status="cancelled",g.publish(O,"run.cancelled",{runId:Q.id})}return f.json({success:!0})}),V.get("/:sessionId/status",async(f)=>{let O=f.req.param("sessionId"),M=B.get(O);if(!M?.currentRunId)return f.json({sessionId:O,status:"idle"});let Q=D.get(M.currentRunId);return f.json({sessionId:O,runId:M.currentRunId,status:Q?.status||"idle"})}),V};async function Z0(V,$,f,O,M){let{abortController:Q,sessionId:J,id:Z}=V,j=d(12),Y=d(12),K=(G,x)=>{g.publish(J,G,x)};try{K("message.created",{messageId:j,role:"user",content:Q0(f)}),K("session.status",{status:"running"}),K("message.created",{messageId:Y,role:"assistant",content:""});let G=M.get(J);if(!G)G=await Ff.create({sessionId:J}),M.set(J,G);let x=await Bf.createWithRuntime(G,{sessionId:J}),q=async(N)=>{let F=d(12),l=300000;V.status="waiting_permission";let ff=new Promise((jf)=>{let rf=setTimeout(()=>{E.warn(`[SessionRoutes] Permission ${F} timed out after 300000ms`),K("permission.timeout",{requestId:F}),jf({approved:!1,reason:"timeout"})},300000);V.pendingPermission={permissionId:F,resolve:(lf)=>{clearTimeout(rf),jf(lf)},details:N}});K("permission.asked",{requestId:F,toolName:N.toolName,description:N.message,args:N.args,details:N}),E.info(`[SessionRoutes] Permission request created: ${F}, runId: ${Z}`);let Kf=await ff;return E.info(`[SessionRoutes] Permission response received: ${F}, approved: ${Kf.approved}`),V.status="running",V.pendingPermission=void 0,Kf},L={messages:[...$.messages],userId:"web-user",sessionId:J,workspaceRoot:$.projectPath,signal:Q.signal,permissionMode:O,confirmationHandler:{requestConfirmation:q}},m=await mf(x.chatStream(f,L,{stream:!0}),async(N)=>{switch(N.kind){case"content_delta":K("message.delta",{messageId:Y,delta:N.delta});break;case"thinking_delta":K("thinking.delta",{delta:N.delta});break;case"tool_start":if("function"in N.toolCall)K("tool.start",{messageId:Y,toolName:N.toolCall.function.name,toolCallId:N.toolCall.id,arguments:N.toolCall.function.arguments,toolKind:N.toolKind});break;case"tool_result":if("function"in N.toolCall)K("tool.result",{messageId:Y,toolName:N.toolCall.function.name,toolCallId:N.toolCall.id,success:N.result.success,summary:N.result.metadata?.summary,output:qf(Uf(N.toolCall.function.name,N.result)),metadata:J0(N.result.metadata)});break;case"token_usage":K("token.usage",{...N.usage});break;case"turn_start":K("turn.started",{turn:N.turn,maxTurns:N.maxTurns});break;case"compaction":K(N.phase==="start"?"compaction.started":"compaction.completed",{});break;case"model_fallback":K("model.fallback",{});break;case"task_update":K("task.updated",{tasks:N.tasks});break;default:break}});$.messages=[...L.messages],K("message.complete",{messageId:Y}),K("thinking.completed",{}),V.status="completed",K("session.completed",{runId:Z,outputTruncated:m.metadata?.outputTruncated??!1}),K("session.status",{status:"idle"})}catch(G){E.error("[SessionRoutes] Agent execution error:",G),V.status="failed",K("session.error",{error:G instanceof Error?G.message:"Unknown error"}),K("session.status",{status:"error"})}}function Af(V,$,f){E.info(`[SessionRoutes] Looking for permission ${$} in session ${V}`),E.info(`[SessionRoutes] Active runs: ${D.size}`);for(let[O,M]of D.entries())if(E.info(`[SessionRoutes] Checking run ${O}: sessionId=${M.sessionId}, pendingPermission=${M.pendingPermission?.permissionId}`),M.sessionId===V&&M.pendingPermission?.permissionId===$)return M.pendingPermission.resolve(f),E.info(`[SessionRoutes] Permission ${$} responded, runId: ${M.id}`),!0;return E.error(`[SessionRoutes] Permission not found: ${$}`),!1}var Vf=R("Service"),j0=C.object({approved:C.boolean(),remember:C.boolean().optional(),scope:C.enum(["once","session"]).optional(),targetMode:C.enum(["default","autoEdit","plan","spec","yolo"]).optional(),feedback:C.string().optional(),answers:C.record(C.union([C.string(),C.array(C.string())])).optional()}),Cf=()=>{let V=new K0;return V.post("/:permissionId",async($)=>{let f=$.req.param("permissionId"),O=$.req.query("sessionId");Vf.info(`[PermissionRoutes] Received permission response: permissionId=${f}, sessionId=${O}`);try{let M=await $.req.json(),Q=j0.safeParse(M);if(!Q.success)throw new A("Invalid permission response format");let{approved:J,remember:Z,scope:j,targetMode:Y,feedback:K,answers:G}=Q.data;if(!O)throw new A("sessionId query parameter is required");if(!Af(O,f,{approved:J,reason:K,scope:j,targetMode:Y,feedback:K,answers:G}))throw new P("Permission request",f);return Vf.info(`[PermissionRoutes] Permission ${f} ${J?"approved":"denied"}`),$.json({success:!0,approved:J,remember:Z})}catch(M){throw Vf.error("[PermissionRoutes] Failed to respond to permission:",M),M}}),V};import{Hono as G0}from"hono";var Hf=R("Service"),yf=()=>{let V=new G0;return V.get("/",async($)=>{try{let f=await zf();return $.json(f)}catch(f){return Hf.error("[ProviderRoutes] Failed to list providers:",f),$.json([])}}),V.get("/:provider/models",async($)=>{let f=$.req.param("provider");try{let O=await Tf(f);return $.json(O)}catch(O){return Hf.error("[ProviderRoutes] Failed to list models:",O),$.json([])}}),V};import{Hono as N0}from"hono";import*as y from"node:fs/promises";import{homedir as x0}from"node:os";import*as n from"node:path";var b=R("Service"),Of=n.join(x0(),".blade","skills-config.json");async function Df(){try{let V=await y.readFile(Of,"utf-8");return JSON.parse(V)}catch{return{disabled:[]}}}async function R0(V){await y.mkdir(n.dirname(Of),{recursive:!0}),await y.writeFile(Of,JSON.stringify(V,null,2))}async function X0(V,$){let f=await Df();if($)f.disabled=f.disabled.filter((O)=>O!==V);else if(!f.disabled.includes(V))f.disabled.push(V);await R0(f)}var I=null,E0=300000;async function m0(){if(I&&Date.now()-I.timestamp<E0)return I.data;try{let V=await fetch("https://api.github.com/repos/anthropics/skills/contents/skills",{headers:{Accept:"application/vnd.github.v3+json","User-Agent":"Blade-Skills-Catalog"}});if(!V.ok)return b.warn(`GitHub API returned ${V.status}`),I?.data||[];let $=await V.json(),f=[];for(let O of $){if(O.type!=="dir")continue;let M=`Official ${O.name} skill`;try{let Q=await fetch(`https://raw.githubusercontent.com/anthropics/skills/main/skills/${O.name}/SKILL.md`,{headers:{"User-Agent":"Blade-Skills-Catalog"}});if(Q.ok){let Z=(await Q.text()).match(/^#[^\n]*\n+([^\n#]+)/);if(Z)M=Z[1].trim().slice(0,100)}}catch{}f.push({name:O.name,description:M,tag:"Official",author:"Anthropic"})}return I={data:f,timestamp:Date.now()},f}catch(V){return b.warn("Failed to fetch skills catalog from GitHub:",V),I?.data||[]}}var bf=()=>{let V=new N0;return V.get("/",async($)=>{try{let f=t();await f.initialize();let O=f.getAll(),M=await Df(),Q=O.map((J)=>({id:J.name,name:J.name,enabled:!M.disabled.includes(J.name),description:J.description||"",version:J.version||"1.0.0",provider:"Local",location:J.source==="builtin"?"Built-in":J.basePath,capabilities:["prompts"],allowedTools:J.allowedTools||[]}));return $.json(Q)}catch(f){return b.error("[SkillsRoutes] Failed to get skills:",f),$.json([])}}),V.post("/:name/toggle",async($)=>{try{let f=$.req.param("name"),O=await $.req.json();return await X0(f,O.enabled),$.json({success:!0,enabled:O.enabled})}catch(f){return b.error("[SkillsRoutes] Failed to toggle skill:",f),$.json({success:!1,error:f.message},500)}}),V.delete("/:name",async($)=>{try{let f=$.req.param("name"),O=`${process.env.HOME}/.blade/skills/${f}`;return await y.rm(O,{recursive:!0,force:!0}),await t().refresh(),$.json({success:!0})}catch(f){return b.error("[SkillsRoutes] Failed to uninstall skill:",f),$.json({success:!1,error:f.message},500)}}),V.post("/install",async($)=>{try{let f=await $.req.json(),O=_f(),M=t(),Q=!1;if(f.source==="catalog"&&f.name){if(Q=await O.installOfficialSkill(f.name),!Q)return $.json({success:!1,error:"Failed to install skill from catalog"},500)}else if(f.source==="repo"&&f.url){if(Q=await O.installFromRepo(f.url,f.name),!Q)return $.json({success:!1,error:"Failed to install skill from repository. Make sure the repo contains a SKILL.md file."},500)}else if(f.source==="local"&&f.path){if(Q=await O.installFromLocal(f.path,f.name),!Q)return $.json({success:!1,error:"Failed to install skill from local path. Make sure the path exists and contains a SKILL.md file."},500)}else return $.json({success:!1,error:"Invalid install parameters. Required: source with corresponding url/path/name"},400);return await M.refresh(),$.json({success:!0})}catch(f){return b.error("[SkillsRoutes] Failed to install skill:",f),$.json({success:!1,error:f.message},500)}}),V.get("/catalog",async($)=>{try{let f=await m0();return $.json(f)}catch(f){return b.error("[SkillsRoutes] Failed to get catalog:",f),$.json([])}}),V};import F0 from"fast-glob";import{Hono as U0}from"hono";import{execSync as q0}from"node:child_process";import{readdir as B0}from"node:fs/promises";import i from"node:path";var r=R("Service"),W0=(V)=>{try{return q0("git rev-parse --abbrev-ref HEAD",{cwd:V,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null}catch{return null}},A0=[...s.map((V)=>`${V}/**`),...s,...Mf.map((V)=>`**/${V}`)],C0=new Set(["/theme","/model","/permissions","/mcp","/skills","/exit","/resume","/ide","/login","/logout"]),Pf=()=>{let V=new U0;return V.get("/commands",async($)=>{try{let f=$.req.query("q")||"",O=Lf(f).filter((M)=>!C0.has(M.command));return $.json(O)}catch(f){return r.error("[SuggestionsRoutes] Failed to get command suggestions:",f),$.json([])}}),V.get("/files",async($)=>{try{let f=$.req.query("q")||"",O=$.get("directory")||X(),M=Math.min(Number($.req.query("limit"))||100,1000),J=(await F0("**/*",{cwd:O,dot:!1,followSymbolicLinks:!1,onlyFiles:!1,markDirectories:!0,unique:!0,ignore:A0})).map((Y)=>Y.replace(/\\/g,"/"));if(!f)return $.json(J.slice(0,M));let Z=f.toLowerCase(),j=J.filter((Y)=>Y.toLowerCase().includes(Z)).slice(0,M);return $.json(j)}catch(f){return r.error("[SuggestionsRoutes] Failed to get file suggestions:",f),$.json([])}}),V.get("/files/tree",async($)=>{try{let f=$.get("directory")||X(),O=$.req.query("path")||"",M=O?i.join(f,O):f,J=(await B0(M,{withFileTypes:!0})).map((Y)=>({name:Y.name,path:O?`${O}/${Y.name}`:Y.name,type:Y.isDirectory()?"dir":"file"}));J.sort((Y,K)=>{if(Y.type!==K.type)return Y.type==="dir"?-1:1;return Y.name.localeCompare(K.name)});let Z=new Set(s),j=J.filter((Y)=>{let K=Y.name;if(K.startsWith("."))return!1;if(Z.has(K))return!1;for(let G of Mf)if(K.match(new RegExp(G.replace("*",".*"))))return!1;return!0});return $.json(j)}catch(f){return r.error("[SuggestionsRoutes] Failed to get file tree:",f),$.json([])}}),V.get("/files/content",async($)=>{try{let f=$.req.query("path");if(!f)return $.json({error:"Missing file path"},400);let O=$.get("directory")||X(),M=i.resolve(O,f),Q=i.relative(O,M);if(Q.startsWith("..")||i.isAbsolute(Q))return $.json({error:"Invalid file path"},400);let J=wf(),Z=await J.stat(M);if(!Z?.isFile)return $.json({error:"File not found"},404);let j=200000,Y=await J.readTextFile(M),K=Y.length>j;return $.json({path:f,content:K?Y.slice(0,j):Y,truncated:K,size:Z.size})}catch(f){return r.error("[SuggestionsRoutes] Failed to get file content:",f),$.json({error:"Failed to read file"},500)}}),V.get("/git-info",async($)=>{try{let f=$.get("directory")||X(),O=W0(f);return $.json({branch:O})}catch(f){return r.error("[SuggestionsRoutes] Failed to get git info:",f),$.json({branch:null})}}),V};import{Hono as H0}from"hono";var _=R("Service"),v=new Map,kf=2097152,Sf=65536;function uf(){return typeof globalThis.Bun<"u"}async function z0(V,$,f){if(uf()){let{spawn:Q}=await import("bun-pty"),J=Q(V,$,{name:"xterm-256color",cwd:f.cwd,env:f.env});return{pid:J.pid,write:(Z)=>J.write(Z),resize:(Z,j)=>J.resize(Z,j),kill:()=>J.kill(),onData:(Z)=>J.onData(Z),onExit:(Z)=>J.onExit(Z)}}let M=(await import("node-pty")).spawn(V,$,{name:"xterm-256color",cwd:f.cwd,env:f.env,cols:80,rows:24});return{pid:M.pid,write:(Q)=>M.write(Q),resize:(Q,J)=>M.resize(Q,J),kill:()=>M.kill(),onData:(Q)=>{M.onData(Q)},onExit:(Q)=>{M.onExit(Q)}}}var Yf=void 0,Qf;if(uf())try{let{createBunWebSocket:V}=await import("hono/bun"),$=V();Qf=$.upgradeWebSocket,Yf=$.websocket}catch(V){_.warn("[Terminal] Failed to initialize Bun WebSocket support:",V)}async function hf(V,$){let f=`term-${Date.now()}`;_.info(`[Terminal] New connection: ${f}, cwd: ${V}`);let O=process.platform==="win32"?"powershell.exe":process.env.SHELL||"/bin/zsh",M=O.endsWith("sh")?["-l"]:[],Q=await z0(O,M,{cwd:V,env:{...process.env,TERM:"xterm-256color",COLORTERM:"truecolor"}}),J={id:f,process:Q,cwd:V,buffer:"",subscribers:new Set};if(v.set(f,J),J.subscribers.add($),Q.onData((Z)=>{let j=!1;for(let Y of J.subscribers)try{Y.send(Z),j=!0}catch{J.subscribers.delete(Y)}if(j)return;if(J.buffer+=Z,J.buffer.length>kf)J.buffer=J.buffer.slice(-kf)}),Q.onExit(({exitCode:Z})=>{_.info(`[Terminal] Process exited: ${f}, code: ${Z}`);for(let j of J.subscribers)try{j.close()}catch{}v.delete(f)}),J.buffer){let Z=J.buffer;J.buffer="";for(let j=0;j<Z.length;j+=Sf)$.send(Z.slice(j,j+Sf))}return{session:J,cleanup:()=>{if(_.info(`[Terminal] Connection closed: ${f}`),J.subscribers.delete($),J.subscribers.size===0){try{J.process.kill()}catch{}v.delete(f)}}}}function If(V,$){V.on("connection",async(f,O)=>{let M=new URL(O.url||"/",`http://${O.headers.host}`);if(!M.pathname.endsWith("/terminal/ws")){f.close();return}let Q=M.searchParams.get("cwd")||$()||X();try{let{session:J,cleanup:Z}=await hf(Q,{send:(j)=>f.send(j),close:()=>f.close()});f.on("message",(j)=>{try{J.process.write(String(j))}catch(Y){_.error("[Terminal] Failed to write to PTY:",Y)}}),f.on("close",Z),f.on("error",Z)}catch(J){_.error("[Terminal] Failed to spawn PTY:",J),f.close()}})}var vf=()=>{let V=new H0;if(V.get("/status",($)=>{let f=Array.from(v.values()).map((O)=>({id:O.id,cwd:O.cwd}));return $.json({active:f.length,terminals:f})}),V.post("/kill/:terminalId",($)=>{let f=$.req.param("terminalId"),O=v.get(f);if(O){try{O.process.kill()}catch{}for(let M of O.subscribers)M.close();return v.delete(f),$.json({success:!0})}return $.json({success:!1,error:"Terminal not found"},404)}),Qf)V.get("/ws",Qf(($)=>{let f=$.req.query("cwd")||$.get("directory")||X(),O;return{async onOpen(M,Q){try{O=await hf(f,{send:(J)=>Q.send(J),close:()=>Q.close()})}catch(J){_.error("[Terminal] Failed to spawn PTY:",J),Q.close()}},onMessage(M){if(!O)return;try{O.session.process.write(String(M.data))}catch(Q){_.error("[Terminal] Failed to write to PTY:",Q)}},onClose(){O?.cleanup()}}}));else V.get("/ws",($)=>{return $.json({message:"WebSocket endpoint - connect via ws:// protocol",hint:"Use WebSocket client to connect to this endpoint"})});return V};var W=R("Service"),Zf=[];function k0(){let V=b0(L0(import.meta.url)),$=[w(V,"web"),w(X(),"dist/web"),w(X(),"packages/cli/dist/web")];for(let f of $){let O=w(f,"index.html");if(gf(O)){if(e(O,"utf-8").includes("/assets/"))return W.debug(`[Server] Found web dist at: ${f}`),f}}return null}function S0(){let V=new T0;V.onError((f,O)=>{if(W.error("[Server] Request error:",f),f instanceof p)return O.json(f.toObject(),f.statusCode);let M=f instanceof Error?f.message:String(f);return O.json({error:{code:"INTERNAL_ERROR",message:M}},500)}),V.use(async(f,O)=>{let M=process.env.BLADE_SERVER_PASSWORD;if(!M)return O();let Q=f.req.path;if(Q==="/"||Q.startsWith("/assets/")||Q.endsWith(".html")||Q.endsWith(".js")||Q.endsWith(".css"))return O();let J=f.req.header("Authorization");if(!J?.startsWith("Basic "))return f.header("WWW-Authenticate",'Basic realm="Blade Server"'),f.json({error:{code:"UNAUTHORIZED",message:"Authentication required"}},401);let Z=Buffer.from(J.slice(6),"base64").toString(),[j,Y]=Z.split(":"),K=process.env.BLADE_SERVER_USERNAME??"blade";if(j!==K||Y!==M)return f.json({error:{code:"UNAUTHORIZED",message:"Invalid credentials"}},401);return O()}),V.use(async(f,O)=>{let M=f.req.path==="/health"||f.req.path==="/global/health"||f.req.path.startsWith("/assets/");if(!M)W.debug(`[Server] ${f.req.method} ${f.req.path}`);let Q=Date.now();if(await O(),!M){let J=Date.now()-Q;W.debug(`[Server] ${f.req.method} ${f.req.path} - ${f.res.status} (${J}ms)`)}}),V.use(y0({origin(f){if(!f)return;if(f.startsWith("http://localhost:"))return f;if(f.startsWith("http://127.0.0.1:"))return f;if(f==="tauri://localhost"||f==="http://tauri.localhost")return f;if(Zf.includes(f))return f;return}})),V.use(async(f,O)=>{let M=f.req.query("directory")||f.req.header("x-blade-directory")||X();try{M=decodeURIComponent(M)}catch{}return f.set("directory",M),O()}),V.route("/global",Nf()),V.route("/sessions",Wf()),V.route("/configs",Gf()),V.route("/permissions",Cf()),V.route("/providers",yf()),V.route("/models",Ef()),V.route("/suggestions",Pf()),V.route("/terminal",vf()),V.route("/mcp",xf()),V.route("/skills",bf()),V.get("/health",(f)=>{return f.json({healthy:!0,version:u()})});let $=k0();if($)W.info(`[Server] Serving static files from ${$}`),V.get("/assets/*",(f)=>{let O=w($,f.req.path);if(!gf(O))return f.json({error:{code:"NOT_FOUND",message:`File not found: ${f.req.path}`}},404);let M=e(O),Q=w0(O).toLowerCase(),Z={".js":"application/javascript",".css":"text/css",".html":"text/html",".json":"application/json",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".svg":"image/svg+xml",".ico":"image/x-icon",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".eot":"application/vnd.ms-fontobject"}[Q]||"application/octet-stream";return new Response(M,{headers:{"Content-Type":Z,"Cache-Control":"public, max-age=31536000, immutable"}})}),V.get("/",(f)=>{let O=w($,"index.html"),M=e(O,"utf-8");return f.html(M)}),V.get("*",(f)=>{let O=f.req.path;if(O.includes("."))return f.json({error:{code:"NOT_FOUND",message:`File not found: ${O}`}},404);let M=w($,"index.html"),Q=e(M,"utf-8");return f.html(Q)});else W.warn('[Server] Web UI not found. Run "cd packages/cli/web && bun run build" to enable web interface.'),V.get("/",(f)=>{return f.json({message:"Blade API Server",version:u(),webUI:!1,hint:'Web UI not built. Run "cd packages/cli/web && bun run build" to enable.',endpoints:{health:"/health",sessions:"/sessions",configs:"/configs",permissions:"/permissions",providers:"/providers"}})}),V.all("*",(f)=>{return f.json({error:{code:"NOT_FOUND",message:`Route not found: ${f.req.path}`}},404)});return V}function u0(){let V=D0(),$=[];for(let f of Object.keys(V)){let O=V[f];if(!O)continue;for(let M of O){if(M.internal||M.family!=="IPv4")continue;if(M.address.startsWith("172."))continue;$.push(M.address)}}return $}function pf(){return typeof globalThis.Bun<"u"}function of(V,$){let f=globalThis.Bun,O=(Q)=>{try{return f.serve({hostname:$.hostname,port:Q,fetch:V.fetch,idleTimeout:0,websocket:Yf})}catch(J){W.error("Failed to start Bun server:",J);return}},M=$.port===0?O(4096)??O(0):O($.port);if(!M)throw Error(`Failed to start Bun server on port ${$.port}`);return{url:M.url,port:M.port,hostname:M.hostname,stop:async()=>{M.stop(!0)}}}function h0(V,$){return new Promise((f,O)=>{let M=_0(async(Y,K)=>{let G=new URL(Y.url||"/",`http://${Y.headers.host}`),x=new Headers;for(let[m,N]of Object.entries(Y.headers))if(N)if(Array.isArray(N))for(let F of N)x.append(m,F);else x.set(m,N);let q;if(Y.method!=="GET"&&Y.method!=="HEAD")q=(await new Promise((N)=>{let F=[];Y.on("data",(l)=>F.push(l)),Y.on("end",()=>N(Buffer.concat(F)))})).toString();let L=new Request(G.toString(),{method:Y.method,headers:x,body:q});try{let m=await V.fetch(L);if(K.statusCode=m.status,m.headers.forEach((N,F)=>{K.setHeader(F,N)}),m.body){let N=m.body.getReader(),F=async()=>{let{done:l,value:ff}=await N.read();if(l){K.end();return}return K.write(ff),F()};await F()}else{let N=await m.text();K.end(N)}}catch(m){W.error("[Server] Node request error:",m),K.statusCode=500,K.end(JSON.stringify({error:{code:"INTERNAL_ERROR",message:"Internal server error"}}))}}),Q=new P0({noServer:!0}),J=X();If(Q,()=>J),M.on("upgrade",(Y,K,G)=>{if(new URL(Y.url||"/",`http://${Y.headers.host}`).pathname==="/terminal/ws")Q.handleUpgrade(Y,K,G,(q)=>{Q.emit("connection",q,Y)});else K.destroy()});let Z=(Y)=>{return new Promise((K,G)=>{M.once("error",(x)=>{if(x.code==="EADDRINUSE")G(x);else G(x)}),M.listen(Y,$.hostname,()=>{let x=M.address();if(x&&typeof x==="object")K(x.port);else K(Y)})})};(async()=>{let Y;if($.port===0)try{Y=await Z(4096)}catch{Y=await Z(0)}else Y=await Z($.port);let K=new URL(`http://${$.hostname==="0.0.0.0"?"localhost":$.hostname}:${Y}`);f({url:K,port:Y,hostname:$.hostname,stop:async()=>{return new Promise((G)=>{Q.close(()=>{M.close(()=>G())})})}})})().catch(O)})}var df;((DV)=>{let V,$;function f(){if(!$)$=S0();return $}DV.getApp=f;function O(J){Zf=J.cors??[];let Z=f();if(pf())V=of(Z,J),W.info(`[Server] Blade server listening on ${V.url} (Bun runtime)`);else throw Error("Blade web server requires Bun runtime. Please run with Bun: `bun run blade web` or install Bun from https://bun.sh");let j=V;return{url:j.url,port:j.port,hostname:j.hostname,stop:async()=>{if(V)await V.stop(),V=void 0,$=void 0,W.info("[Server] Blade server stopped")}}}DV.listen=O;async function M(J){Zf=J.cors??[];let Z=f();if(pf())V=of(Z,J),W.info(`[Server] Blade server listening on ${V.url} (Bun runtime)`);else V=await h0(Z,J),W.info(`[Server] Blade server listening on ${V.url} (Node.js runtime)`);let j=V;return{url:j.url,port:j.port,hostname:j.hostname,stop:async()=>{if(V)await V.stop(),V=void 0,$=void 0,W.info("[Server] Blade server stopped")}}}DV.listenAsync=M;function Q(){return V!==void 0}DV.isRunning=Q})(df||={});export{I0 as f,v0 as g,u0 as h,df as i};
@@ -1 +0,0 @@
1
- import{f as y,g as A,h as C,i as D}from"./chunk-qdnx9x5g.js";import"./chunk-v1d0d4b4.js";import"./chunk-92qcc3gj.js";import"./chunk-a2nshjdc.js";import"./chunk-qyfdt8h1.js";import"./chunk-aam53te2.js";import"./chunk-b0q2q0ax.js";import{wa as q}from"./chunk-k9h9bw13.js";import"./chunk-867h27ke.js";import"./chunk-xmdpc0y5.js";import"./chunk-dzmrdtpc.js";import"./chunk-f76d6jxg.js";import"./chunk-qds0yxfy.js";import"./chunk-7ycmx7c2.js";import"./chunk-v0rjbvky.js";import"./chunk-mt1c5da4.js";import"./chunk-0afbeec0.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};
@@ -1,9 +0,0 @@
1
- import{Ob as H}from"./chunk-mt1c5da4.js";var m=["anthropic","openai","deepseek","google-generative-ai","groq","openrouter"],d={anthropic:"",openai:"","google-generative-ai":"",deepseek:"",groq:"",openrouter:"",azure:"",ollama:"",together:"",fireworks:"",mistral:"",cohere:"",perplexity:"",xai:"",default:""},g={anthropic:"https://api.anthropic.com",openai:"https://api.openai.com/v1",google:"https://generativelanguage.googleapis.com/v1beta",deepseek:"https://api.deepseek.com/v1",groq:"https://api.groq.com/openai/v1",openrouter:"https://openrouter.ai/api/v1",togetherai:"https://api.together.xyz/v1","fireworks-ai":"https://api.fireworks.ai/inference/v1",mistral:"https://api.mistral.ai/v1",cohere:"https://api.cohere.ai/v1",perplexity:"https://api.perplexity.ai",xai:"https://api.x.ai/v1",cerebras:"https://api.cerebras.ai/v1","novita-ai":"https://api.novita.ai/v3/openai",nvidia:"https://integrate.api.nvidia.com/v1"},h={anthropic:{"anthropic-beta":"claude-code-20250219,interleaved-thinking-2025-05-14,fine-grained-tool-streaming-2025-05-14"},openrouter:{"HTTP-Referer":"https://github.com/anthropics/blade","X-Title":"Blade"},cerebras:{"X-Cerebras-3rd-Party-Integration":"blade"},vercel:{"http-referer":"https://github.com/anthropics/blade","x-title":"blade"},zenmux:{"HTTP-Referer":"https://github.com/anthropics/blade","X-Title":"blade"}},T=(Q)=>{return h[Q]||{}};import{createAnthropic as k}from"@ai-sdk/anthropic";import{createAzure as I}from"@ai-sdk/azure";import{createDeepSeek as A}from"@ai-sdk/deepseek";import{createGoogleGenerativeAI as U}from"@ai-sdk/google";import{createOpenAI as C}from"@ai-sdk/openai";import{createOpenAICompatible as R}from"@ai-sdk/openai-compatible";import{generateText as v,jsonSchema as f,streamText as b}from"ai";var M=new Set(["user-cancel","interrupt","sibling-error","timeout"]);function E(Q){return typeof Q==="string"&&M.has(Q)}function i(Q){if(!Q.aborted)return;if(E(Q.reason))return Q.reason;return"user-cancel"}function t(Q){if(E(Q))return!0;if(!(Q instanceof Error))return!1;if(Q.name==="AbortError")return!0;if(Q instanceof DOMException&&Q.name==="AbortError")return!0;if(Q.message.includes("aborted"))return!0;return!1}function r(...Q){let q=Q.filter(Boolean);if(q.length===0)return new AbortController().signal;if(q.length===1)return q[0];let Y=AbortSignal;if(typeof Y.any==="function")return Y.any(q);for(let J of q)if(J.aborted)return J;let X=new AbortController,Z=new Map;for(let J of q){let B=()=>{X.abort(J.reason);for(let[$,F]of Z)$.removeEventListener("abort",F)};Z.set(J,B)}for(let[J,B]of Z)J.addEventListener("abort",B,{once:!0});return X.signal}function D(Q,q,Y){let X=Y?.throwOnAbort??!1;if(q?.aborted){if(X)return Promise.reject(new DOMException("Aborted","AbortError"));return Promise.resolve()}return new Promise((Z,J)=>{let B,$=setTimeout(()=>{if(q&&B)q.removeEventListener("abort",B);Z()},Q);if(q)B=()=>{if(clearTimeout($),X)J(new DOMException("Aborted","AbortError"));else Z()},q.addEventListener("abort",B,{once:!0})})}var G=H("Chat");function x(Q){let q=new Set;for(let Y of Q)if(Y.role==="assistant"&&Y.tool_calls)for(let X of Y.tool_calls)q.add(X.id);return Q.filter((Y)=>{if(Y.role==="tool"){if(!Y.tool_call_id)return!1;return q.has(Y.tool_call_id)}return!0})}function V(Q){if(typeof Q==="string")return Q;return Q.filter((q)=>q.type==="text").map((q)=>q.text).join(`
2
- `)}function y(Q){let q=Q;return q.text??q.textDelta??q.delta}function u(Q,q={}){try{return JSON.parse(Q)}catch{return G.warn("[VercelAIChatService] Failed to parse JSON, using fallback",{str:Q}),q}}class O{model;config;constructor(Q){this.config=Q,this.model=this.createModel(Q),G.debug("[VercelAIChatService] Initialized",{provider:Q.provider,model:Q.model})}createModel(Q){let{provider:q,apiKey:Y,baseUrl:X,model:Z,customHeaders:J,apiVersion:B}=Q;switch(q){case"openai":return C({apiKey:Y,baseURL:X||void 0,headers:J})(Z);case"anthropic":return k({apiKey:Y,baseURL:X||void 0,headers:J})(Z);case"gemini":{if(X&&!this.isGeminiOfficialUrl(X))return R({name:"gemini",apiKey:Y,baseURL:X,headers:J})(Z);return U({apiKey:Y,baseURL:X||void 0})(Z)}case"google":case"google-generative-ai":case"google-vertex":{if(X&&!this.isGeminiOfficialUrl(X))return R({name:q,apiKey:Y,baseURL:X,headers:J})(Z);return U({apiKey:Y,baseURL:X||void 0})(Z)}case"azure-openai":{let $=this.extractAzureResourceName(X);if($)return I({apiKey:Y,resourceName:$,apiVersion:B||"2024-08-01-preview"})(Z);let F=this.buildAzureBaseUrl(X,Z);return R({name:"azure-openai",apiKey:Y,baseURL:F,headers:{...J,"api-key":Y},queryParams:{"api-version":B||"2024-08-01-preview"}})(Z)}case"azure":{let $=this.extractAzureResourceName(X);if($)return I({apiKey:Y,resourceName:$,apiVersion:B||"2024-08-01-preview"})(Z);let F=this.buildAzureBaseUrl(X,Z);return R({name:"azure-openai",apiKey:Y,baseURL:F,headers:{...J,"api-key":Y},queryParams:{"api-version":B||"2024-08-01-preview"}})(Z)}case"deepseek":return A({apiKey:Y,baseURL:X||void 0,headers:J})(Z);default:return R({name:q,apiKey:Y,baseURL:X,headers:J})(Z)}}extractAzureResourceName(Q){if(!Q)return;let q=Q.match(/https:\/\/([^.]+)\.openai\.azure(?:\.com|\.us|\.cn|\.de)/);return q?q[1]:void 0}buildAzureBaseUrl(Q,q){if(!Q)return"";let Y=Q.replace(/\/$/,"").replace(/\?.*$/,"");if(Y.includes("/openai/deployments/"))return Y;return`${Y}/openai/deployments/${q}`}isGeminiOfficialUrl(Q){return Q.includes("generativelanguage.googleapis.com")||Q.includes("aiplatform.googleapis.com")}needsThinkingReplayMetadata(){return/deepseek/i.test([this.config.provider,this.config.model,this.config.baseUrl].join(" "))}getThinkingReplayProviderOptions(Q){let q=Q?.trim();if(!q||!this.needsThinkingReplayMetadata())return;return{openaiCompatible:{reasoning_content:q}}}shouldFlattenDeepSeekThinkingToolHistory(){return this.needsThinkingReplayMetadata()}flattenDeepSeekThinkingToolHistory(Q){let q=[],Y,X=()=>{if(!Y)return;q.push({role:"assistant",content:V(Y.content).trim()||"I will use the requested tool and continue from its result."}),Y=void 0};for(let Z of Q){if(Z.role==="system"){X(),q.push({role:"user",content:`<system>
3
- ${V(Z.content)}
4
- </system>`});continue}if(Z.role==="assistant"&&Z.tool_calls&&Z.tool_calls.length>0&&Z.reasoningContent?.trim()){X(),Y=Z;continue}if(Z.role==="tool"&&Y){let J=Y.tool_calls?.find(($)=>$.id===Z.tool_call_id),B=J?.type==="function"?J.function:void 0;q.push({role:"user",content:`Tool result for ${Z.name||B?.name||"tool"}${B?.arguments?`(${B.arguments})`:""}:
5
- ${V(Z.content)}
6
-
7
- Continue from this tool result.`});continue}X(),q.push(Z)}return X(),q}convertMessages(Q){let q=[],Y=this.shouldFlattenDeepSeekThinkingToolHistory()?this.flattenDeepSeekThinkingToolHistory(Q):Q;for(let X of Y)if(X.role==="system")if(Array.isArray(X.content)){let Z=X.content.find((B)=>B.type==="text"),J={role:"system",content:V(X.content)};if(Z?.providerOptions)J.providerOptions=Z.providerOptions;q.push(J)}else q.push({role:"system",content:X.content});else if(X.role==="user")if(Array.isArray(X.content)){let Z=X.content.map((J)=>{if(J.type==="text"){let B={type:"text",text:J.text};if(J.providerOptions)B.providerOptions=J.providerOptions;return B}return{type:"image",image:J.image_url.url}});q.push({role:"user",content:Z})}else q.push({role:"user",content:X.content});else if(X.role==="assistant")if(X.tool_calls&&X.tool_calls.length>0){let Z=X.tool_calls.map((F)=>{let W=F.function;return{type:"tool-call",toolCallId:F.id,toolName:W?.name||"",input:u(W?.arguments||"{}",{})}}),J=V(X.content),B=X.reasoningContent?.trim()?[{type:"reasoning",text:X.reasoningContent}]:[],$=this.getThinkingReplayProviderOptions(X.reasoningContent);if(J){let F={role:"assistant",content:[...B,{type:"text",text:J},...Z]};if($)F.providerOptions=$;q.push(F)}else if(B.length>0){let F={role:"assistant",content:[...B,...Z]};if($)F.providerOptions=$;q.push(F)}else q.push({role:"assistant",content:Z})}else if(X.reasoningContent?.trim()){let Z=V(X.content),J=[{type:"reasoning",text:X.reasoningContent}];if(Z)J.push({type:"text",text:Z});let B={role:"assistant",content:J},$=this.getThinkingReplayProviderOptions(X.reasoningContent);if($)B.providerOptions=$;q.push(B)}else q.push({role:"assistant",content:V(X.content)});else if(X.role==="tool")q.push({role:"tool",content:[{type:"tool-result",toolCallId:X.tool_call_id,toolName:X.name||"unknown",output:{type:"text",value:V(X.content)}}]});if(this.config.enablePromptCaching&&this.config.provider==="anthropic"){let X=0;for(let Z of q)if(Z.role==="system"&&X<2)Z.providerOptions={anthropic:{cacheControl:{type:"ephemeral"}}},X++;for(let Z=q.length-1;Z>=0;Z--)if(q[Z].role==="user"){q[Z].providerOptions={anthropic:{cacheControl:{type:"ephemeral"}}};break}}return q}convertTools(Q){if(!Q||Q.length===0)return;let q={};for(let Y of Q)q[Y.name]={description:Y.description,inputSchema:f(Y.parameters)};return q}convertToolCalls(Q){return Q.map((q)=>({id:q.toolCallId,type:"function",function:{name:q.toolName,arguments:JSON.stringify(q.args??q.input??{})}}))}convertUsage(Q,q){if(!Q)return;let Y=Q.promptTokens??Q.inputTokens??0,X=Q.completionTokens??Q.outputTokens??0,Z={promptTokens:Y,completionTokens:X,totalTokens:Q.totalTokens??Y+X};if(Q.reasoningTokens)Z.reasoningTokens=Q.reasoningTokens;if(q?.anthropic){if(q.anthropic.cacheCreationInputTokens!==void 0)Z.cacheCreationInputTokens=q.anthropic.cacheCreationInputTokens;if(q.anthropic.cacheReadInputTokens!==void 0)Z.cacheReadInputTokens=q.anthropic.cacheReadInputTokens}return Z}isFallbackableError(Q){let q=[],Y=new Set,X=Q;while(X&&!Y.has(X)){if(q.push(X),Y.add(X),typeof X!=="object")break;let $=X;X=$.lastError??$.cause}let Z=q.filter(($)=>$ instanceof Error).map(($)=>$.message.toLowerCase()),J=Z.join(`
8
- `);if(["prompt_too_long","prompt is too long","maximum context length","context length exceeded","context_length_exceeded","request too large"].some(($)=>J.includes($)))return!1;let B=["timeout","timed out","econnreset","econnrefused","enotfound","eai_again","etimedout","fetch failed","network error","socket hang up","connection reset","connection refused"];if(B.some(($)=>J.includes($)))return!0;for(let $ of q){if(!$||typeof $!=="object")continue;let F=$,W=F.status??F.statusCode??F.response?.status??F.response?.statusCode;if(W!==void 0&&([408,409,429].includes(W)||W>=500))return!0;let z=F.code;if(typeof z==="string"&&B.some((L)=>z.toLowerCase().includes(L)))return!0}for(let $ of Z){let F=$.match(/\bstatus(?:\s+code)?[:\s]*(\d{3})\b/),W=F?Number(F[1]):void 0;if(W!==void 0&&([408,409,429].includes(W)||W>=500))return!0}return!1}async retryWithBackoff(Q,q,Y=2,X=1000){let Z;for(let J=0;J<=Y;J++)try{return await Q()}catch(B){if(Z=B,q?.aborted)await D(0,q,{throwOnAbort:!0});if(J>=Y)break;if(!this.isFallbackableError(B))throw B;let $=X*Math.pow(2,J);G.debug(`[VercelAIChatService] Retry ${J+1}/${Y} after ${$}ms`),await D($,q,{throwOnAbort:!0})}throw Z}getFallbackModelIds(){let Q=[];if(this.config.fallbackModels&&this.config.fallbackModels.length>0)Q.push(...this.config.fallbackModels);else if(this.config.fallbackModel)Q.push(this.config.fallbackModel);return Q}getThinkingProviderOptions(){if(!this.config.supportsThinking)return;let Q=this.config.thinkingMode??"budget";if(Q==="off")return;let q=Q==="adaptive",Y=this.config.thinkingBudget??1e4;if(this.config.provider==="anthropic")return{anthropic:{thinking:q?{type:"enabled",budgetTokens:0}:{type:"enabled",budgetTokens:Y}}};if(this.config.provider==="deepseek"||/deepseek/i.test(this.config.model))return{deepseek:{thinking:q?{type:"enabled",budgetTokens:0}:{type:"enabled",budgetTokens:Y}}};return}getStreamTextOptions(Q,q,Y,X){let Z=X;if(this.config.timeout&&this.config.timeout>0){let $=AbortSignal.timeout(this.config.timeout);if(X)Z=AbortSignal.any([X,$]);else Z=$}let J={model:Q,messages:q,tools:Y,maxOutputTokens:this.config.maxOutputTokens,maxRetries:0,temperature:this.config.temperature??0,abortSignal:Z,allowSystemInMessages:!0},B=this.getThinkingProviderOptions();if(B)J.providerOptions=B;return J}async chat(Q,q,Y){let X=Date.now();G.debug("[VercelAIChatService] Starting chat request");let Z=x(Q),J=this.convertMessages(Z),B=this.convertTools(q),$=async(F)=>{let W=await v(this.getStreamTextOptions(F,J,B,Y)),z=W.toolCalls&&W.toolCalls.length>0?this.convertToolCalls(W.toolCalls):void 0,L=Array.isArray(W.reasoning)?W.reasoning.map((P)=>P.text).join(""):void 0;return{content:W.text,reasoningContent:L,toolCalls:z,usage:this.convertUsage(W.usage,W.providerMetadata),finishReason:W.finishReason}};try{return await this.retryWithBackoff(()=>$(this.model),Y,this.config.maxRetries)}catch(F){let W=Date.now()-X;if(G.error("[VercelAIChatService] Chat failed after",W,"ms"),Y?.aborted)await D(0,Y,{throwOnAbort:!0});if(!this.isFallbackableError(F))throw F;let z=this.getFallbackModelIds();if(z.length===0)throw F;for(let L of z){G.warn(`[VercelAIChatService] Trying fallback model: ${L}`);let P=this.createModel({...this.config,model:L});try{return await $(P)}catch(_){if(G.warn(`[VercelAIChatService] Fallback ${L} failed: ${_ instanceof Error?_.message:_}`),Y?.aborted)await D(0,Y,{throwOnAbort:!0});if(!this.isFallbackableError(_))throw _}}throw F}}async*streamChat(Q,q,Y){let X=Date.now();G.debug("[VercelAIChatService] Starting stream request");let Z=x(Q),J=this.convertMessages(Z),B=this.convertTools(q),$=async function*(_,N){let j=b(_.getStreamTextOptions(N,J,B,Y)),K=0;for await(let w of j.fullStream)switch(w.type){case"text-delta":yield{content:y(w)};break;case"reasoning-delta":yield{reasoningContent:y(w)};break;case"tool-call":yield{toolCalls:[{index:K++,id:w.toolCallId,type:"function",function:{name:w.toolName,arguments:JSON.stringify(w.args??w.input??{})}}]};break;case"finish":yield{finishReason:w.finishReason,usage:_.convertUsage(w.totalUsage,w.providerMetadata)};break}},F=this.config.maxRetries??2,W,z=!1;for(let _=0;_<=F;_++)try{for await(let j of $(this,this.model))z=!0,yield j;let N=Date.now()-X;G.debug("[VercelAIChatService] Stream completed in",N,"ms");return}catch(N){if(W=N,Y?.aborted)await D(0,Y,{throwOnAbort:!0});if(z)throw N;if(!this.isFallbackableError(N))throw N;if(_<F){let j=1000*Math.pow(2,_);G.debug(`[VercelAIChatService] Stream retry ${_+1}/${F} after ${j}ms`),await D(j,Y,{throwOnAbort:!0});continue}}let L=Date.now()-X;G.error("[VercelAIChatService] Stream failed after",L,"ms");let P=this.getFallbackModelIds();if(P.length===0)throw W;for(let _ of P){G.warn(`[VercelAIChatService] Stream fallback: ${_}`),yield{modelFallback:!0};let N=this.createModel({...this.config,model:_}),j=!1;try{for await(let K of $(this,N))j=!0,yield K;return}catch(K){if(G.warn(`[VercelAIChatService] Stream fallback ${_} failed`),Y?.aborted)await D(0,Y,{throwOnAbort:!0});if(j)throw K;if(!this.isFallbackableError(K))throw K}}throw W}getConfig(){return{...this.config}}updateConfig(Q){G.debug("[VercelAIChatService] Updating configuration"),this.config={...this.config,...Q},this.model=this.createModel(this.config),G.debug("[VercelAIChatService] Configuration updated")}}var c=H("Service");async function Gq(Q){let q=Q;if(q.provider){let Y=T(q.provider);if(Object.keys(Y).length>0)q={...q,customHeaders:{...Y,...q.customHeaders}},c.debug(`Injected ${q.provider} specific headers:`,Object.keys(Y))}return p(q)}function p(Q){return new O(Q)}
9
- export{m as yb,d as zb,g as Ab,i as Bb,t as Cb,r as Db,Gq as Eb};
@@ -1 +0,0 @@
1
- import{Eb as a}from"./chunk-v0rjbvky.js";import"./chunk-mt1c5da4.js";import"./chunk-0afbeec0.js";export{a as createChatServiceAsync};
@@ -1 +0,0 @@
1
- import{t as a,u as b}from"./chunk-1dt2y16n.js";import"./chunk-xmdpc0y5.js";import"./chunk-0afbeec0.js";export{a as globalOptions,b as cliConfig};