howtocode 0.0.0-stage → 0.7.56

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 (94) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +248 -2
  3. package/dist/chunk-27TRKD65.js +2 -0
  4. package/dist/chunk-2SHU7WQ5.js +10 -0
  5. package/dist/chunk-3FYCFLNK.js +1 -0
  6. package/dist/chunk-4BWBQ4HV.js +1 -0
  7. package/dist/chunk-7IUWRCVT.js +197 -0
  8. package/dist/chunk-7LA2AMZB.js +1 -0
  9. package/dist/chunk-A3LZMZ3C.js +2 -0
  10. package/dist/chunk-ADJLVYL3.js +1 -0
  11. package/dist/chunk-AEDSISJB.js +1 -0
  12. package/dist/chunk-AEWC7NIN.js +5 -0
  13. package/dist/chunk-AYBGCIQH.js +8 -0
  14. package/dist/chunk-DML5JQIR.js +1 -0
  15. package/dist/chunk-DT7VRY24.js +1 -0
  16. package/dist/chunk-EZNNALD3.js +1 -0
  17. package/dist/chunk-FGKA3GGW.js +6 -0
  18. package/dist/chunk-FJBHQI6Q.js +6 -0
  19. package/dist/chunk-JWPDIJUV.js +1 -0
  20. package/dist/chunk-KA2CULSQ.js +2 -0
  21. package/dist/chunk-KTS2F755.js +2 -0
  22. package/dist/chunk-LYLJZVZ7.js +1 -0
  23. package/dist/chunk-MCAAX33K.js +2 -0
  24. package/dist/chunk-MCDEIIEN.js +1 -0
  25. package/dist/chunk-MVVEYKN6.js +6 -0
  26. package/dist/chunk-MWSWXDNN.js +5 -0
  27. package/dist/chunk-ORJ2QZBG.js +3 -0
  28. package/dist/chunk-PH72JBBL.js +4 -0
  29. package/dist/chunk-PVFHAKN6.js +1 -0
  30. package/dist/chunk-QOYTPACU.js +3 -0
  31. package/dist/chunk-RGYXELNI.js +140 -0
  32. package/dist/chunk-SDO33XPR.js +4 -0
  33. package/dist/chunk-SZPFD4XF.js +47 -0
  34. package/dist/chunk-TOV557ET.js +12 -0
  35. package/dist/chunk-TSEKPGK4.js +1 -0
  36. package/dist/chunk-TUXY64DT.js +2 -0
  37. package/dist/chunk-U3GZBLTM.js +2 -0
  38. package/dist/chunk-UTYFLLSM.js +1 -0
  39. package/dist/chunk-V3R4FYTJ.js +1 -0
  40. package/dist/chunk-VWAUPT4A.js +1 -0
  41. package/dist/chunk-WKUJ7CFO.js +1 -0
  42. package/dist/chunk-WOT6VMZA.js +1 -0
  43. package/dist/chunk-XBVWQC7P.js +1 -0
  44. package/dist/chunk-XHHNV7A5.js +2 -0
  45. package/dist/chunk-YNMLRZJK.js +2 -0
  46. package/dist/chunk-YX2QDCVK.js +1 -0
  47. package/dist/main.js +102 -0
  48. package/dist/presets/backend/api/preset.json +17 -0
  49. package/dist/presets/backend/api/prompt.md +9 -0
  50. package/dist/presets/backend/api/skills/api-contract/SKILL.md +35 -0
  51. package/dist/presets/data/sql/preset.json +17 -0
  52. package/dist/presets/data/sql/prompt.md +9 -0
  53. package/dist/presets/data/sql/skills/query-hygiene/SKILL.md +48 -0
  54. package/dist/presets/devops/containers/preset.json +17 -0
  55. package/dist/presets/devops/containers/prompt.md +9 -0
  56. package/dist/presets/devops/containers/skills/image-discipline/SKILL.md +59 -0
  57. package/dist/presets/frontend/web-ui/preset.json +17 -0
  58. package/dist/presets/frontend/web-ui/prompt.md +11 -0
  59. package/dist/presets/frontend/web-ui/skills/responsive-check/SKILL.md +46 -0
  60. package/dist/presets/gamedev/rotoolbox/preset.json +31 -0
  61. package/dist/presets/gamedev/rotoolbox/prompt.md +34 -0
  62. package/dist/presets/gamedev/rotoolbox/skills/rotoolbox/SKILL.md +129 -0
  63. package/dist/presets/hub.json +14582 -0
  64. package/dist/presets/lang/typescript/preset.json +16 -0
  65. package/dist/presets/lang/typescript/prompt.md +5 -0
  66. package/dist/presets/lang/typescript/skills/ts-strict/SKILL.md +48 -0
  67. package/dist/presets/mcp/filesystem/preset.json +27 -0
  68. package/dist/presets/mcp/filesystem/prompt.md +8 -0
  69. package/dist/presets/mcp/filesystem/skills/mcp-files/SKILL.md +27 -0
  70. package/dist/presets/mcp/memory/preset.json +25 -0
  71. package/dist/presets/mcp/memory/skills/mcp-memory/SKILL.md +31 -0
  72. package/dist/presets/mcp/rea/preset.json +28 -0
  73. package/dist/presets/mcp/rea/prompt.md +5 -0
  74. package/dist/presets/mcp/rea/skills/mcp-rea/SKILL.md +6 -0
  75. package/dist/presets/mcp/remotion/preset.json +27 -0
  76. package/dist/presets/mcp/remotion/prompt.md +7 -0
  77. package/dist/presets/mcp/remotion/skills/mcp-remotion/SKILL.md +6 -0
  78. package/dist/presets/mcp-hub.json +157 -0
  79. package/dist/presets/mobile/app/preset.json +17 -0
  80. package/dist/presets/mobile/app/prompt.md +7 -0
  81. package/dist/presets/mobile/app/skills/touch-targets/SKILL.md +47 -0
  82. package/dist/presets/quality/antislop/preset.json +25 -0
  83. package/dist/presets/quality/antislop/prompt.md +16 -0
  84. package/dist/presets/quality/antislop/skills/antislop/SKILL.md +595 -0
  85. package/dist/presets/quality/antislop/skills/antislop/references/gate.md +84 -0
  86. package/dist/presets/quality/antislop/skills/antislop-code/SKILL.md +128 -0
  87. package/dist/presets/quality/antislop/skills/antislop-copywriting/SKILL.md +413 -0
  88. package/dist/presets/quality/antislop/skills/antislop-human/SKILL.md +147 -0
  89. package/dist/presets/quality/antislop/skills/antislop-human/contrast-check.py +165 -0
  90. package/dist/presets/quality/antislop/skills/antislop-layoutmobile/SKILL.md +170 -0
  91. package/dist/presets/quality/antislop/skills/antislop-ui/SKILL.md +313 -0
  92. package/dist/presets/quality/antislop/skills/antislop-ui/references/motion.md +34 -0
  93. package/dist/presets/quality/antislop/skills/antislop-ui/references/states.md +49 -0
  94. package/package.json +34 -4
@@ -0,0 +1,140 @@
1
+ import{$a as cs,A as Ro,Aa as Vo,Ba as qo,Ca as zo,D as Mt,Da as Yo,E as Io,Ea as Jo,G as _o,Ga as de,Ha as E,Ia as J,J as Lo,Ja as A,K as Oo,Ka as Xo,L as Rt,La as Zo,M as No,Ma as Qo,N as Fo,Na as es,O as jo,Oa as Kn,P as Dn,Pa as ts,Qa as ns,Sa as Gn,Ta as rs,Va as is,X as Wn,Xa as os,Ya as ss,Z as Un,Za as as,_a as ls,aa as Qe,ab as ds,bb as us,c as vo,e as xo,g as So,h as Co,ha as Do,ia as et,ka as It,n as Eo,oa as Wo,pa as Uo,ra as Bo,sa as Ko,ta as Go,v as Po,wa as Ho,x as Mo,z as jn,za as Bn}from"./chunk-7IUWRCVT.js";import{b as fs,c as ms}from"./chunk-MWSWXDNN.js";import{b as Ee,c as Ze,e as Ao,f as Et,g as To,h as Pt}from"./chunk-27TRKD65.js";import{A as io,B as St,C as oo,b as Rn,c as ye,d as zi,e as Yi,h as Ji,n as In,o as Xi,q as oe,s as Zi,t as Ie,v as Qi,w as eo,x as to,y as no,z as ro}from"./chunk-FGKA3GGW.js";import{a as so,b as ao,c as lo,d as co,f as uo,g as fo,h as mo,i as po,l as go}from"./chunk-XHHNV7A5.js";import{a as Ct,b as _n,c as Ln,d as ho,e as At}from"./chunk-3FYCFLNK.js";import{u as bo}from"./chunk-SDO33XPR.js";import{a as wo}from"./chunk-ORJ2QZBG.js";import{a as yo,c as Tt,d as On,j as ko,l as Nn,m as Fn,n as $o}from"./chunk-YNMLRZJK.js";import{a as Pn,b as Mn,c as Di,d as Wi}from"./chunk-EZNNALD3.js";import{b as xt}from"./chunk-7LA2AMZB.js";import{A as Li,B as $t,C as vt,D as Oi,E as Sn,F as Cn,G as Ni,H as R,M as Xe,N as An,O as Fi,Q as ji,c as vn,d as wt,g as yt,i as xi,j as Si,k as Ci,l as Ai,m as kt,n as Ti,o as xn,p as Ei,s as se,t as Pi,u as Mi,x as Ri,y as Ii,z as _i}from"./chunk-2SHU7WQ5.js";import{a as ie}from"./chunk-UTYFLLSM.js";import{j as Tn,k as En}from"./chunk-MVVEYKN6.js";import{b as Ui,c as Bi,d as Ki,e as Gi,f as Hi}from"./chunk-TUXY64DT.js";import{h as Vi,i as qi}from"./chunk-KA2CULSQ.js";import{a as $n,b as bt,e as vi}from"./chunk-AEWC7NIN.js";import"./chunk-WOT6VMZA.js";import{execFile as cd}from"node:child_process";import{promisify as dd}from"node:util";import{appendFileSync as ud,existsSync as Vt,mkdirSync as yr,readFileSync as qt,rmSync as fd,statSync as Va,writeFileSync as kr}from"node:fs";import{basename as md,dirname as pd,join as me,resolve as gd}from"node:path";function ps(e){if(e==="")return!0;let t=/^\x1b\[(\d+);(\d+)u$/.exec(e);if(t&&Number(t[1])===99&&(Number(t[2])&5)!==0)return!0;let n=/^\x1b\[27;(\d+);(\d+)~$/.exec(e);return!!(n&&Number(n[2])===99&&(Number(n[1])&5)!==0)}function gs(e){let t=!1;process.on("SIGINT",()=>{t||(t=!0,e())})}function xl(e){if(!e||typeof e!="object")return;let t=e;if(!(typeof t.input!="number"&&typeof t.cacheRead!="number"&&typeof t.cacheWrite!="number"))return t}function Sl(e){let t=e?.input??0,n=e?.cacheRead??0,i=e?.cacheWrite??0;return{input:t,cacheRead:n,cacheWrite:i,prompt:t+n+i}}function Cl(e){if(typeof e!="string")return null;let t=Date.parse(e);return Number.isNaN(t)?null:t}function Al(e){if(!e||typeof e!="object")return;let t=e,i=(t.message&&typeof t.message=="object"?t.message:void 0)??t,o=xl(i.usage);if(!o)return;let u=typeof i.provider=="string"?i.provider:"",a=typeof i.model=="string"?i.model:"";return{usage:o,model:[u,a].filter(Boolean).join("/")}}function hs(e){let t=0,n=0,i=[],o=0,u=null;for(let g of e){let b=Al(g);if(!b)continue;let{input:k,cacheRead:C,cacheWrite:_,prompt:O}=Sl(b.usage);if(O===0)continue;t+=C,n+=k+_;let F=Cl(g.timestamp),W=u,G=W?W.at:null;if(W!==null&&C===0&&k>=1e3){let Q=F!==null&&G!==null?Math.max(0,F-G):0;i.push({missedTokens:k,idleMs:Q,modelChanged:b.model!==""&&W.model!==""&&b.model!==W.model}),o+=k}u={prompt:O,at:F??G??null,model:b.model}}let a=t+n;return{cachedTokens:t,billedTokens:n,hitRate:a>0?t/a*100:null,misses:i,missedTokens:o}}function bs(e){return e.modelChanged?"model changed, so its cache had to be built":e.idleMs>=3e5?`cache expired after ${Math.round(e.idleMs/1e3)}s idle`:e.idleMs>0?"prompt changed too early in the prefix to hit":"reason not recorded"}import{copyToClipboard as hd,ProjectTrustStore as bd,SessionManager as wd}from"@netrodev/hxf-coding-agent";import{CombinedAutocompleteProvider as qa,Container as yd,Editor as kd,matchesKey as q,ProcessTerminal as $d,ScrollView as vd,KeybindingsManager as Xa,setKeybindings as Za,isKeyRelease as xd,parseColor as Yt,TUI_KEYBINDINGS as Qa,SelectList as Sd,TuiAltScreen as Cd,truncateToWidth as We,VStack as Ad,visibleWidth as Sr,wrapTextWithAnsi as el}from"@netrodev/hxf-tui";import{spawn as Tl}from"node:child_process";function El(e,t,n=2e3){return new Promise(i=>{let o=!1,u,a=k=>{o||(o=!0,u!==void 0&&clearTimeout(u),i(k))},g;try{g=Tl(e,[...t],{stdio:["ignore","pipe","ignore"]})}catch{a({ok:!1,stdout:""});return}u=setTimeout(()=>{g.kill("SIGKILL"),a({ok:!1,stdout:""})},n);let b=[];g.stdout?.on("data",k=>b.push(k)),g.on("error",()=>a({ok:!1,stdout:""})),g.on("close",k=>{a({ok:k===0,stdout:Buffer.concat(b).toString("utf8")})})})}function Hn(){return process.env.XDG_SESSION_TYPE==="wayland"||(process.env.WAYLAND_DISPLAY?.length??0)>0}async function Pl(){let e=[];process.platform==="darwin"?e.push({command:"pbpaste",args:[]}):process.platform==="win32"?e.push({command:"powershell.exe",args:["-NoProfile","-Command","Get-Clipboard -Raw"]}):(Hn()&&(e.push({command:"wl-paste",args:["--no-newline","--type","text/plain;charset=utf-8"]}),e.push({command:"wl-paste",args:["--no-newline","--type","text/plain"]}),e.push({command:"wl-paste",args:["--no-newline"]})),((process.env.DISPLAY?.length??0)>0||!Hn())&&(e.push({command:"xclip",args:["-selection","clipboard","-o"]}),e.push({command:"xsel",args:["--clipboard","--output"]})),e.push({command:"termux-clipboard-get",args:[]}));for(let t of e){let n=await El(t.command,t.args);if(n.ok&&n.stdout.length>0)return n.stdout}}async function ws(){let e;try{let{getNativeClipboard:i}=await import("@netrodev/hxf-tui");e=i()}catch{e=void 0}if(e)try{let i=await e.getText();if(typeof i=="string"&&i.length>0)return{ok:!0,text:i}}catch{}let t=await Pl();return t!==void 0?{ok:!0,text:t}:{ok:!1,reason:`no clipboard tool could read it \u2014 ${Hn()?"install wl-clipboard (wl-paste)":process.platform==="darwin"?"pbpaste should be present on macOS":process.platform==="win32"?"Get-Clipboard should be present on Windows":"install xclip or xsel, or run under a display"}`}}import{spawn as Ml}from"node:child_process";import{mkdirSync as Rl,writeFileSync as Il}from"node:fs";import{join as _l}from"node:path";import{getNativeClipboard as Ll}from"@netrodev/hxf-tui";async function _e(e,t,n=4e3){let{promise:i,resolve:o}=Promise.withResolvers(),u=!1,a,g=C=>{u||(u=!0,clearTimeout(a),o(C))},b;try{b=Ml(e,[...t],{stdio:["ignore","pipe","ignore"]})}catch{return g(void 0),i}a=setTimeout(()=>{b.kill("SIGKILL"),g(void 0)},n);let k=[];return b.stdout?.on("data",C=>k.push(C)),b.on("error",()=>g(void 0)),b.on("close",C=>{let _=Buffer.concat(k);g(C===0&&_.length>0?_:void 0)}),i}function ys(){return process.env.XDG_SESSION_TYPE==="wayland"||(process.env.WAYLAND_DISPLAY?.length??0)>0}function Ol(e){return e.length>8&&e[0]===137&&e[1]===80&&e[2]===78&&e[3]===71}function Nl(e){return e.length>3&&e[0]===255&&e[1]===216&&e[2]===255}async function Fl(){try{let e=await Ll()?.getImage();if(e&&e.length>0)return Buffer.from(e)}catch{}if(process.platform==="darwin"){let e=await _e("pngpaste",["-"]);return e||await _e("osascript",["-e",`set d to the clipboard as \xABclass PNGf\xBB
2
+ return d`])}if(process.platform==="win32"){let e=["Add-Type -AssemblyName System.Windows.Forms","$img = [System.Windows.Forms.Clipboard]::GetImage()","if ($img -ne $null) {"," $ms = New-Object System.IO.MemoryStream"," $img.Save($ms, [System.Drawing.Imaging.ImageFormat]::Png)"," [Console]::OpenStandardOutput().Write($ms.ToArray(), 0, $ms.Length)","}"].join("; ");return _e("powershell.exe",["-NoProfile","-Command",e])}if(ys()){let e=await _e("wl-paste",["--type","image/png"]);if(e)return e}if((process.env.DISPLAY?.length??0)>0||!ys()){let e=await _e("xclip",["-selection","clipboard","-t","image/png","-o"]);if(e)return e;let t=await _e("xclip",["-selection","clipboard","-t","image/jpeg","-o"]);if(t)return t}}function jl(e,t){let n=t==="image/jpeg"?"jpg":"png";return`pasted-${new Date(e).toISOString().replace(/[:.]/g,"-")}.${n}`}async function Vn(e=ji,t=Date.now()){let n=await Fl();if(!n)return{ok:!1,reason:"the clipboard holds no image"};let i=Ol(n)?"image/png":Nl(n)?"image/jpeg":void 0;if(!i)return{ok:!1,reason:"the clipboard image is not PNG or JPEG"};try{Rl(e,{recursive:!0});let o=_l(e,jl(t,i));return Il(o,n,{mode:384}),{ok:!0,image:{path:o,data:n.toString("base64"),mimeType:i}}}catch(o){return{ok:!1,reason:`could not store the image: ${o instanceof Error?o.message:String(o)}`}}}import{TreeSelectorComponent as Td,initTheme as Ed}from"@netrodev/hxf-coding-agent";import{getKeybindings as za}from"@netrodev/hxf-tui";import{mixColors as Dl,parseColor as Wl,styleText as he}from"@netrodev/hxf-tui";var ue=process.env.HOWTOCODE_NO_MOTION!=="1",Ul=45,ks=5,$s=8,qn=1e4,vs=6e4,xs=3,Ss=4,zn=e=>e<0?0:e>1?1:e;function ke(e,t,n){let i=zn(n);return i>=1?t:i<=0?e:Dl(e,t,i)}var _t=class{value;velocity=0;last=Date.now();target;constructor(t,n=t){this.value=t,this.target=n}set(t){this.target=t}get moving(){return Math.abs(this.target-this.value)>.15}snap(t){this.value=t,this.target=t,this.velocity=0,this.last=Date.now()}step(t=Date.now()){let n=Math.max(0,t-this.last),i=Math.min(250,n)/1e3;if(this.last=t,!ue)return this.value=this.target,this.velocity=0,this.value;n>250&&(this.velocity=0);let o=150,u=2*Math.sqrt(o),a=Math.max(1,Math.ceil(i/.008)),g=i/a;for(let b=0;b<a;b+=1)this.velocity+=(this.target-this.value)*o*g-this.velocity*u*g,this.value+=this.velocity*g;return this.moving||(this.value=this.target,this.velocity=0),this.value}};function Yn(e,t,n,i){return!ue||e<=qn?t:e>=vs?i:ke(n,i,(e-qn)/(vs-qn))}function Cs(e,t){return!ue||t<=0||e<0?1:1-(1-zn(e/t))**3}var As=260,Bl=45;function Ts(e,t,n=Bl,i=400){return!ue||n<=0||e<0||e>=i?t:Math.min(t,Math.floor(e/n)+1)}function Es(e,t,n=Date.now(),i=1400){if(!ue||i<=0)return e;let o=n%i/i;return ke(e,t,o<.5?o*2:(1-o)*2)}function Lt(e,t,n){let i=he(e,{fg:t.rest},de);if(!ue||e.length===0)return i;let o=zn(n);if(o>=1)return i;let u=t.band??1,a=e.length+Ss*2,b=Math.min(a-1,Math.floor(o*a))-Ss,k=G=>{let Q=Math.abs(G-b);return Q>u?0:1-Q/(u+1)},C="",_=0,O=null,F=0,W=0;for(let G of e){let Q=k(W);O===null?O=Q:Q!==O&&(C+=he(e.slice(_,F),{fg:ke(t.rest,t.lit,O)},de),_=F,O=Q),F+=G.length,W+=1}return C+he(e.slice(_),{fg:ke(t.rest,t.lit,O??0)},de)}function Jn(e,t,n=Date.now(),i=90){let o=t[0]??Wl("#e6e6e6");if(t.length===0||e.length===0)return he(e,{fg:o},de);if(!ue||i<=0)return he(e,{fg:t[t.length-1]??o},de);let u=t.length*i,a=(n%u+u)%u,g="",b=0,k=null,C=0,_=0,O=F=>{let W=(a+F*i)/u%1*t.length,G=Math.floor(W)%t.length,Q=(G+1)%t.length;return ke(t[G]??o,t[Q]??o,W-Math.floor(W))};for(let F of e){let W=O(_);k===null?k=W:W!==k&&(g+=he(e.slice(b,C),{fg:k},de),b=C,k=W),C+=F.length,_+=1}return g+he(e.slice(b),{fg:k??o},de)}function Kl(e,t){let n=Math.abs(e-t);return n>=ks?0:Math.ceil((1-n/ks)*xs)/xs}function Ps(e,t,n=Date.now()){let i=t.charMs??Ul;if(!ue||e.length===0||i<=0)return he(e,{fg:t.base},de);let o=e.length+$s*2,u=n/i%o-$s,a=(O,F)=>he(O,{fg:ke(t.base,t.bright,F)},de),g="",b=0,k=null,C=0,_=0;for(let O of e){let F=Kl(_,u);k===null?k=F:F!==k&&(g+=a(e.slice(b,C),k),b=C,k=F),C+=O.length,_+=1}return g+a(e.slice(b),k??0)}import{readFileSync as Gl,statSync as Hl}from"node:fs";import{homedir as Vl}from"node:os";import{extname as ql}from"node:path";var Xn="\x1B[200~",Zn="\x1B[201~",zl={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp"},Ms=10*1024*1024,Yl=256*1024,Jl=20;function Rs(e){if(!e.startsWith(Xn)||!e.endsWith(Zn))return;let t=e.slice(Xn.length,e.length-Zn.length);if(!(t.includes(Xn)||t.includes(Zn)))return t}function Is(e){return e.trim()===""}function Xl(e){return/^[a-zA-Z]:[\\/]/.test(e)||e.startsWith("\\\\")||e.startsWith("/")||e==="~"||e.startsWith("~/")}function Zl(e,t=Vl()){let n=e.trim();return n.startsWith("file://")&&(n=decodeURIComponent(n.slice(7)),/^\/[a-zA-Z]:\//.test(n)&&(n=n.slice(1))),!/^[a-zA-Z]:[\\/]/.test(n)&&!n.startsWith("\\\\")&&(n=n.replace(/\\([ ()'&])/g,"$1")),n==="~"?t:n.startsWith("~/")?t+n.slice(1):n}function _s(e,t){let n=e.trim();if(!n||n.length>8192)return;let i,o=[...n.matchAll(/"([^"]+)"|'([^']+)'/g)].map(a=>a[1]??a[2]??"");if(o.length>0&&n.replace(/"[^"]+"|'[^']+'/g,"").trim()===""?i=o:i=n.split(/\r?\n/).map(a=>a.trim()).filter(a=>a.length>0),i.length===0||i.length>Jl||!i.every(a=>Xl(a)||a.startsWith("file://")))return;let u=i.map(a=>Zl(a));return u.every(t)?u:void 0}function Ls(e){return zl[ql(e).toLowerCase()]}function Os(e){return`[file ${e}]`}function Qn(e){return`[image ${e}]`}function Ns(e,t){return e.replace(/\[file ([^\]\n]+)\]/g,(n,i)=>{let o=t(i);return o===void 0?n:`<file name="${i}">
3
+ ${o.trimEnd()}
4
+ </file>`})}function Fs(e){try{let t=Hl(e);if(!t.isFile()||t.size===0||t.size>Yl)return;let n=Gl(e);return n.includes(0)?void 0:n.toString("utf8")}catch{return}}import{Markdown as wc,wrapTextWithAnsi as yc}from"@netrodev/hxf-tui";import{homedir as Ql}from"node:os";import{isAbsolute as ec,relative as tc,resolve as nc,sep as js}from"node:path";import{getImageDimensions as rc,imageFallback as Ds,renderImage as ic}from"@netrodev/hxf-tui";var oc="\u25CF",nr="\u2514",Nt="\u22EF",er=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"];function rt(e=1e3/30){let t=Math.floor(Date.now()/e)%er.length;return er[t]??er[0]}var sc="\u25B2";var ac="\u25CB",lc=["create_object","set_properties","delete_object","clone_instance","reparent_instance","set_script_source","edit_script_lines","insert_script_lines","execute_luau","generate_mesh","generate_material","generate_procedural_model"];function rr(e){return e.includes("__")?e.slice(e.lastIndexOf("__")+2):e}function Ks(e){return lc.includes(rr(e))}function tt(e,t=process.cwd()){if(!e||!ec(e))return e;let n=nc(e),i=tc(t,n);if(i==="")return".";if(i&&!i.startsWith(`..${js}`)&&i!=="..")return i;let o=Ql();return o&&(n===o||n.startsWith(o+js))?`~${n.slice(o.length)}`:n}function ae(e,t){let n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,Math.max(1,t-1))}\u2026`:n}function U(e,t){if(e&&typeof e=="object"){let n=e[t];if(typeof n=="string"&&n.length>0)return n;if(typeof n=="number")return String(n)}}function cc(e,t=160){if(!e||typeof e!="object")return"";try{let n=JSON.stringify(e);return n&&n!=="{}"?ae(n,t):""}catch{return""}}function dc(e,t){switch(e){case"read":{let n=tt(U(t,"path")??""),i=[U(t,"offset"),U(t,"limit")].filter(Boolean);return i.length>0?`${n} ${i.length===1?`offset=${i[0]}`:`offset=${i[0]}, limit=${i[1]}`}`:n}case"edit":case"write":return tt(U(t,"path")??"");case"bash":case"powershell":{let n=U(t,"command")??"";return t?.run_in_background===!0?`${n} [background]`:n}case"bash_output":{let n=U(t,"task_id"),i=U(t,"filter");return n?i?`${n} filter=${i}`:n:"all tasks"}case"kill_shell":return U(t,"task_id")??"";case"compress":{let n=U(t,"topic")??"",i=Array.isArray(t.content)?t.content.length:0;return i>1?`${n} (${i} ranges)`:n}case"grep":{let n=U(t,"pattern")??"",i=U(t,"path");return i?`${n} in ${tt(i)}`:n}case"find":case"glob":{let n=U(t,"pattern")??U(t,"glob")??"",i=U(t,"path");return i?`${n} in ${tt(i)}`:n}case"ls":return tt(U(t,"path")??".");case"task":return U(t,"agent")??"task";case"ask":return U(t,"question")??"";case"web_search":return U(t,"query")??"";case"web_fetch":return U(t,"url")??"";case"lsp":{let n=U(t,"action")??"lsp",i=U(t,"file")??"",o=U(t,"line");return o?`${n} ${i}:${o}`:`${n} ${i}`}case"quality":return U(t,"path")??"changed files";case"think":return"private";case"todo":{let n=U(t,"op")??"view",i=U(t,"task"),o=t?.items;return n==="init"&&Array.isArray(o)?`init ${o.length} task${o.length===1?"":"s"}`:i?`${n} ${i}`:n}case"context":{let n=U(t,"op")??"list",i=U(t,"key");return i?`${n} ${i}`:n}case"workflow":{let n=U(t,"path");if(n)return n;let i=U(t,"code")??"",o=/export\s+const\s+meta\s*=\s*\{[\s\S]*?name\s*:\s*["'`]([^"'`]+)/.exec(i)?.[1];if(o)return o;let u=i.trim().split(`
5
+ `)[0]??"";return u.length>40?`${u.slice(0,40)}\u2026`:u}default:return cc(t)}}function Pe(e,t,n=100){let i=rr(e),u=i!==e?i:i.charAt(0).toUpperCase()+i.slice(1),a=Ks(e)?sc:oc,g=ae(dc(i,t),n);return g?`${a} ${u}(${g})`:`${a} ${u}`}function uc(e){let t=0,n=0;for(let i of e.split(`
6
+ `))i.startsWith("+")&&!i.startsWith("+++")?t+=1:i.startsWith("-")&&!i.startsWith("---")&&(n+=1);return{additions:t,removals:n}}function Gs(e){let t=e?.content;if(!Array.isArray(t))return[];let n=[];for(let i of t){if(!i||typeof i!="object")continue;let o=i;if(o.type!=="image"||typeof o.data!="string")continue;let u=typeof o.mimeType=="string"?o.mimeType:"image/png";try{let a=rc(o.data,u),g=a?ic(o.data,a,{maxWidthCells:60,maxHeightCells:24}):null;n.push(g?g.sequence:Ds(u,a??void 0))}catch{n.push(Ds(u,void 0))}}return n}function Le(e){let t=e?.content;return typeof t=="string"?t:Array.isArray(t)?t.map(n=>n&&typeof n=="object"&&n.type==="text"?String(n.text??""):"").join(""):""}function it(e){let t=e?.details;return t&&typeof t=="object"?t:{}}function ir(e){let t=e?.structuredContent;return t&&typeof t=="object"?t:{}}function Ws(e){let t=e.exit_code;return typeof t=="number"&&Number.isFinite(t)?t:void 0}function fc(e){let t=[];if(e&&typeof e=="object"){t.push(e);let i=e.content;if(Array.isArray(i))for(let o of i){let u=o?.text;if(typeof u=="string")try{let a=JSON.parse(u);a&&typeof a=="object"&&t.push(a)}catch{}}}let n=[];for(let i of t){let o=["instances","instanceCount","count","parts","partsCreated"].map(b=>i[b]).find(b=>typeof b=="number"&&Number.isFinite(b));typeof o=="number"&&n.push(`${o} instance${o===1?"":"s"}`);let u=tr(i,["files","written","paths"]);u&&n.push(u.join(", "));let a=tr(i,["images","renders","screenshots"]);a&&n.push(`renders ${ac} ${a.join(", ")}`);let g=tr(i,["findings","warnings","errors"]);if(g&&n.push(`${g.length} finding${g.length===1?"":"s"}`),n.length>0)break}return n.length>0?n.join(" \xB7 "):void 0}function tr(e,t){for(let n of t){let i=e[n];if(!Array.isArray(i))continue;let o=i.filter(u=>typeof u=="string"&&u!=="");if(o.length>0)return o}}function Us(e){return e.trim().split(`
7
+ `).find(t=>t.trim())??""}function mc(e,t){let n=typeof e.output=="string"?e.output:t.replace(/\n*Command exited with code \d+\s*$/,""),i=nt(n);return i>0?` (${i} line${i===1?"":"s"})`:""}function pc(e,t,n){return e===1?t:n}function nt(e){let t=e.trim();return t?t.split(`
8
+ `).length:0}function Bs(e){return e<1e3?`${e} tokens`:`${(e/1e3).toFixed(1)}k tokens`}function Ft(e,t,n){let i=Le(t),o=it(t),u=ir(t);if(n){let a=Ws(u);if(a!==void 0&&(e==="bash"||e==="powershell"))return`exit ${a}`;let g=i.trim().split(`
9
+ `).find(b=>b.trim());return ae(g??"failed",120)}if(Ks(e)){let a=fc(t);if(a)return a;let g=rr(e);return g==="execute_luau"?"ran":ae(g.replace(/_/g," "),120)}switch(e){case"task":{let a=i.split(`
10
+ `).filter(g=>g.startsWith("## ")).map(g=>g.replace(/^##\s*/,"").trim());if(a.length===0){let g=i.trim().split(`
11
+ `).find(b=>b.trim());return ae(g??"done",120)}return a.map(g=>ae(g,120)).join(`
12
+ `)}case"read":{let a=o.truncation,g=nt(i.replace(/\n*\[[^\]]*\]\s*$/,"")),b=g===0?"empty":`${g} line${g===1?"":"s"}`;return a?.truncated?`${b} (truncated from ${a.totalLines??"?"})`:b}case"compress":{let a=Array.isArray(o.blockIds)?o.blockIds:[],g=typeof o.compressedTokens=="number"?o.compressedTokens:0,b=typeof o.summaryTokens=="number"?o.summaryTokens:0,k=a.length===1?`b${String(a[0])}`:`${a.length} blocks`;if(g===0)return k;let C=g-b;return C<0?`${k} \xB7 ${Bs(-C)} LARGER than the range`:`${k} \xB7 ${Bs(C)} saved`}case"edit":{let a=typeof o.diff=="string"?o.diff:"";if(!a)return"applied";let{additions:g,removals:b}=uc(a);return`+${g} / -${b}`}case"write":{let a=nt(i);return a===0?"written":`written (${a} ${pc(a,"line","lines")})`}case"bash":case"powershell":{let a=Ws(u);if(a===void 0)return i.trim()?ae(Us(i),120):"done";let g=mc(u,i);return a===0?`exit 0${g}`:`exit ${a}`}case"grep":{let a=nt(i);return a===0?"no matches":`${a} match${a===1?"":"es"}`}case"web_search":{let a=typeof o.count=="number"?o.count:nt(i);return a===0?"no results":`${a} result${a===1?"":"s"}`}case"web_fetch":return`${typeof o.chars=="number"?o.chars:i.length} chars`;case"lsp":{let a=typeof o.count=="number"?o.count:void 0;return typeof o.error=="string"?ae(o.error,120):a===void 0?ae(Us(i),120):`${a} location${a===1?"":"s"}`}case"quality":{if(typeof o.error=="string")return ae(o.error,120);if(o.off===!0)return"off";let a=typeof o.files=="number"?o.files:0,g=typeof o.functions=="number"?o.functions:0,b=typeof o.findings=="number"?o.findings:0,k=typeof o.score=="number"?` \xB7 ${Math.round(o.score)}`:"";return a===0?"no files":`${a} file${a===1?"":"s"} \xB7 ${g} fn \xB7 ${b} finding${b===1?"":"s"}${k}`}case"todo":{let a=o.todos??[];if(!Array.isArray(a)||a.length===0)return"list cleared";let g=a.filter(k=>k.status==="completed").length,b=a.filter(k=>k.status==="pending"||k.status==="in_progress").length;return`${g}/${a.length} done, ${b} open`}case"context":{let a=o.notes,g=a?Object.keys(a).length:0;return g===0?"no notes":`${g} note${g===1?"":"s"} held`}case"workflow":{let a=typeof o.agents=="number"?o.agents:0,g=typeof o.outputTokens=="number"?o.outputTokens:0,b=Array.isArray(o.steps)?o.steps.filter(C=>C.status==="failed").length:0;if(typeof o.error=="string")return`failed after ${a} agent(s)`;let k=typeof o.startedAt=="number"&&typeof o.endedAt=="number"?`, ${Qo(o.endedAt-o.startedAt)}`:"";return`${a} agent(s), ${g} tokens${k}${b>0?`, ${b} failed`:""}`}case"bash_output":{let a=i.trim().split(`
13
+ `)[0]??"",g=/running/.test(a)?"running":/finished/.test(a)?"finished":"task",b=i.trim().split(`
14
+ `).slice(2).filter(k=>k.trim()).length;return b===0?g:`${g} \xB7 ${b} line${b===1?"":"s"}`}case"kill_shell":{let a=i.trim().split(`
15
+ `)[0]??"";return a.startsWith("Stopped")?"stopped":ae(a,120)}default:{let a=i.trim().split(`
16
+ `).find(g=>g.trim());return a?ae(a,120):"done"}}}function Hs(e,t){let n=it(t);if(e==="edit"&&typeof n.diff=="string")return n.diff.split(`
17
+ `).filter(i=>i.length>0).slice(0,12);if(e==="bash"||e==="powershell"){if(Le(t).startsWith("Started bash_"))return[];let o=ir(t);return(typeof o.output=="string"?o.output:Le(t).replace(/\n*Command exited with code \d+\s*$/,"")).trimEnd().split(`
18
+ `).filter(g=>g.trim()).slice(-4)}if(e==="bash_output")return Le(t).split(`
19
+ `).slice(2).filter(o=>o.trim()).slice(-6);if(e==="todo"){let i=n.todos??[],o={pending:"[ ]",in_progress:"[>]",completed:"[x]",dropped:"[-]"};return i.slice(0,6).map(u=>`${o[u.status??"pending"]??"[ ]"} ${u.content??""}`)}return e==="task"?Le(t).split(`
20
+ `).filter(i=>i.trim()&&!i.startsWith("## ")).slice(0,6):e==="workflow"?(n.steps??[]).map(u=>{let a=u.status==="running"?"\u25B8":u.status==="failed"?"\xD7":"\u2713",g=u.phase?`${u.phase} \xB7 `:"";return`${a} ${g}${u.label??"agent"}`}).slice(-6):[]}var Ot=400;function Vs(e,t){let n=it(t);if(e==="edit"&&typeof n.diff=="string")return n.diff.split(`
21
+ `).filter(g=>g.length>0).slice(0,Ot);let i=ir(t),u=(typeof i.output=="string"?i.output:Le(t).replace(/\n*Command exited with code \d+\s*$/,"")).trimEnd().split(`
22
+ `),a=u.slice(0,Ot);return u.length>Ot&&a.push(`\u2026 ${u.length-Ot} more line(s)`),a}var gc={read:{active:"Reading",done:"Read",one:"file",many:"files"},search:{active:"Searching for",done:"Searched for",one:"pattern",many:"patterns"},list:{active:"Listing",done:"Listed",one:"directory",many:"directories"}};function hc(e){if(e==="read")return"read";if(e==="grep"||e==="find"||e==="glob")return"search";if(e==="ls")return"list"}function qs(e,t=!1){let n=[],i,o=()=>{if(!i||i.indices.length<2){i=void 0;return}n.push({start:i.indices[0],indices:i.indices,counts:i.counts,summary:bc(i.counts,t)}),i=void 0};for(let[u,a]of e.entries()){let g=hc(a.toolName);if(g===void 0){o();continue}i||(i={indices:[],counts:{}}),i.indices.push(u),i.counts[g]=(i.counts[g]??0)+1}return o(),n}function bc(e,t){let n=[];for(let i of["search","read","list"]){let o=e[i];if(o===void 0)continue;let u=gc[i],a=t?u.active:u.done,g=o===1?u.one:u.many;n.push(`${n.length===0?a:a.toLowerCase()} ${o} ${g}`)}return n.join(", ")}function Ys(e,t){let n=e[e.length-1];return n&&n.kind==="note"&&n.title===t.title?[...e.slice(0,-1),t]:[...e,t]}var kc=/^(?:\x1b_G|\x1b\]1337;File=)/;function or(e){return typeof e=="string"?Tn(e):Tn(e.map(t=>t.type==="text"?t.text:t.type==="thinking"?"":t.type==="image"?"[image]":(t.type==="toolCall","")).filter(Boolean).join(""))}function Js(e){return e.role==="user"?or(e.content).trim():""}function Xs(e,t,n){let i=t.trim();if(!i)return e;let o=e.findIndex(a=>a.kind==="user"&&a.body.trim()===i);if(o===-1)return[...e,{id:n,kind:"user",title:"you",body:i}];let u=[...e];return u[o]={id:n,kind:"user",title:"you",body:i},u}function $c(e){return e.content.filter(t=>t.type==="toolCall").map(t=>({name:t.name,arguments:t.arguments}))}function vc(e){return e.content.filter(t=>t.type==="toolCall").map(t=>t.id)}function xc(e){let t=e.map(a=>({toolName:a.kind==="result"||a.kind==="tool"?a.title:"",line:a.call??a.body})),n=qs(t);if(n.length===0)return e;let i=new Map(n.map(a=>[a.start,a])),o=new Set(n.flatMap(a=>a.indices)),u=[];for(let[a,g]of e.entries()){let b=i.get(a);if(b){let k=e[b.start];u.push({id:k?.id??`g-${b.start}`,kind:"collapsed",title:"collapsed",body:b.summary,full:b.indices.map(C=>e[C]?.call??e[C]?.body??"").filter(Boolean)});continue}o.has(a)||u.push(g)}return u}function Dt(e){let t=[];for(let n of e)if(n.role==="user"){let i=or(n.content).trim();if(!i)continue;t.push({id:`u-${n.timestamp}`,kind:"user",title:"you",body:i})}else if(n.role==="assistant"){let i=or(n.content).trim(),o=$c(n),u=vc(n);i?t.push({id:`a-${n.timestamp}`,kind:n.stopReason==="error"?"error":"assistant",title:n.errorMessage?"failed":"fix",body:n.errorMessage?`${n.errorMessage}
23
+
24
+ ${i}`:i}):n.errorMessage&&t.push({id:`e-${n.timestamp}`,kind:"error",title:"failed",body:n.errorMessage}),o.forEach((a,g)=>{let b=u[g];t.push({id:b?`tool-${b}`:`c-${n.timestamp}-${g}`,kind:"tool",title:a.name,body:Pe(a.name,a.arguments),...b?{call:Pe(a.name,a.arguments)}:{}})})}else if(n.role==="toolResult"){let i=Ft(n.toolName,{content:n.content},n.isError),o=n.isError===!0||i.startsWith("exit ")&&i!=="exit 0",u=t.find(a=>a.id===`tool-${n.toolCallId}`);u?(u.kind="result",u.body=i,u.title=n.toolName,o&&(u.failed=!0)):t.push({id:`r-${n.toolCallId}`,kind:"result",title:n.toolName,body:i,...o?{failed:!0}:{}})}return xc(t)}function zs(e,t,n){return yc(e,Math.max(8,t)).map(i=>A(i,n))}var ot=new Map;function Sc(e){let t=e.body||" ",n=ot.get(e.id);if(n)return n.text!==t&&(n.component.setText(t),n.text=t),n.component;let i=new wc(t,0,0,Xo);return ot.set(e.id,{text:t,component:i}),i}var sr=class{constructor(t){this.item=t}item;invalidate(){}shade(t){let n=Date.now()-(this.item.born??0);return ke(E.dim,t,Cs(n,As))}render(t){let n=this.item.body;if(this.item.kind==="user"){let o=this.item.pending?[A(" queued \u2014 the run reads this at its next step",E.dim)]:[];return["",...zs(`> ${n}`,t,this.shade(E.user)),...o]}if(this.item.kind==="tool")return[A(`${rt()} ${n}`,this.shade(E.tool))];if(this.item.kind==="collapsed"){let o=[A(`${Nt} ${n}`,this.shade(E.mute))],u=this.item.full??[];if(u.length>0)if(this.item.expanded===!0)for(let a of u)o.push(A(` ${a}`,this.shade(E.dim)));else o.push(A(` ${u.length} call(s) \xB7 ctrl+e to expand`,E.dim));return o}if(this.item.kind==="result"){let o=this.item.failed===!0||n.startsWith("exit ")&&n!=="exit 0";if(this.item.panel)return["",...this.item.panel(t),...n?[A(` ${nr} ${n}`,o?E.bad:E.mute)]:[]];let u=[];this.item.call&&u.push(A(this.item.call,this.shade(E.tool)));let a=` ${nr} ${n}`;if(u.push(A(a,o?E.bad:this.shade(E.mute))),this.item.expanded===!0&&(this.item.full?.length??0)>0){let C=A(` ${this.item.full.length} line(s) \xB7 ctrl+e to collapse`,E.dim);u.push(A(` ${Nt}`,E.dim));for(let _ of this.item.full){let O=_.startsWith("+")?E.tool:_.startsWith("-")?E.bad:E.dim;u.push(A(` ${_}`,O))}return u.push(C),u}let b=this.item.detail??[],k=Ts(Date.now()-(this.item.born??0),b.length);for(let C of b.slice(0,k)){if(kc.test(C)){u.push(C);continue}let _=C.startsWith("+")?E.tool:C.startsWith("-")?E.bad:E.dim;u.push(A(` ${C}`,this.shade(_)))}return(this.item.full?.length??0)>0&&u.push(A(` ${Nt} ${this.item.full.length} line(s) \xB7 ctrl+e to expand`,E.dim)),u}if(this.item.kind==="error"||this.item.kind==="note"){let o=this.item.kind==="error"?E.bad:E.mute;return["",...zs(n,t,this.shade(o))]}return["",...Sc(this.item).render(Math.max(8,t-2))]}},jt=class{items=[];status="";scrollOffset=0;scrollAnchor;settledOffset=0;viewportHeight=0;enteringUntil=0;lastPruneKey="";invalidate(){}entering(){return Date.now()<this.enteringUntil}render(t){let n=`${this.items.length}:${this.items[this.items.length-1]?.id??""}`;if(n!==this.lastPruneKey&&(this.lastPruneKey=n,ot.size>0)){let a=new Set(this.items.map(g=>g.id));for(let g of ot.keys())a.has(g)||ot.delete(g)}let i=[],o=Date.now();for(let a of this.items)a.born===void 0&&(a.born=o,this.enteringUntil=Math.max(this.enteringUntil,o+400)),i.push(...new sr(a).render(t));this.status&&i.push(A(this.status,E.mute));let u=this.viewportHeight;if(u>0&&i.length>u){let a=i.length-u;this.scrollOffset!==this.settledOffset&&(this.scrollAnchor=void 0);let g=this.scrollAnchor,b;if(g!==void 0){let k=i.length-g;k>=0&&k<=a?b=k:b=Math.max(0,Math.min(this.scrollOffset,a))}else b=Math.max(0,Math.min(this.scrollOffset,a));return g===void 0&&(this.scrollOffset=b),this.settledOffset=this.scrollOffset,b===0?this.scrollAnchor=void 0:this.scrollAnchor===void 0&&(this.scrollAnchor=i.length-b),i.slice(a-b,a-b+u)}return i}};function Zs(){let e=null;return{get armed(){return e!==null},arm(t){return e=t,!0},disarm(){let t=e;return t===null?!1:(e=null,t(),!0)}}}function Qs(e,t){let n=e.trim();return n?!n.startsWith("sk-")&&t(n)?{kind:"credential",credential:n}:{kind:"token",token:n}:{kind:"browser"}}var ea="approve the sign-in in your browser, waiting\u2026 (or paste an sk- key)";import{parseColor as re}from"@netrodev/hxf-tui";var $e={off:re("okhsl(230 12% 46%)"),minimal:re("okhsl(240 55% 49%)"),low:re("okhsl(252 60% 55%)"),medium:re("okhsl(270 64% 60%)"),high:re("okhsl(298 70% 64%)"),xhigh:re("okhsl(332 80% 66%)"),max:re("okhsl(42 95% 64%)")},ta={off:re("okhsl(230 14% 64%)"),minimal:re("okhsl(240 60% 64%)"),low:re("okhsl(252 64% 68%)"),medium:re("okhsl(270 68% 72%)"),high:re("okhsl(298 74% 76%)"),xhigh:re("okhsl(332 82% 78%)"),max:re("okhsl(42 96% 76%)")};function Wt(e){return $e[e]??$e.medium}var ar=[$e.minimal,$e.low,$e.medium,$e.high,$e.xhigh,$e.max];function ra(e){return ta[e]??ta.medium}var na=460;function Ut(e){return!Number.isFinite(e)||e<0||e>=na?0:1-e/na}var z=["off","minimal","low","medium","high","xhigh","max"];function ia(e){let t=e?.thinkingLevelMap;if(t===void 0)return z[z.length-1];for(let n=z.length-1;n>=0;n-=1)if(typeof t[z[n]]=="string")return z[n]}function oa(e){let t=z.indexOf(e);return z[(t+1+z.length)%z.length]}function sa(e){let t=z.indexOf(e);return z[(t-1+z.length)%z.length]}import{mkdirSync as Ec,readFileSync as Pc}from"node:fs";import{dirname as Mc}from"node:path";var cr="\x1B[0m",Y="\x1B[2m",Cc="\x1B[1m",Ac="\x1B[31m",dr="\x1B[32m",la="\x1B[33m",aa="\x1B[35m",lr="\x1B[36m";function K(e,t){return`${t}${e}${cr}`}function ca(e,t){return A(e,Wt(t))}function da(e){return e>=85?Ac:e>=70?la:dr}var Tc="\u2726";function ua(e,t,n,i,o){let u=o?o(`[${e}]`):K(`[${e}]`,lr),a=`${K(Tc,Y)} ${t}`,g=K(n,la),b=i?` ${K("git:(",aa)}${K(i.replace(/^git:\(/,"").replace(/\)$/,""),lr)}${K(")",aa)}`:"";return`${u}${K(" \u2502 ",Y)}${a}${K(" \u2502 ",Y)}${g}${b}`}function fa(e,t,n){if(!t)return e;let i=n===void 0?t:`${t} ${K(es(n),Y)}`;return`${K(i,lr)} ${K("\u2502",Y)} ${e}`}function ma(e,...t){let n=Number.isFinite(e)?Math.min(100,Math.max(0,e)):0,i=Math.round(n/10),o=da(n),u=`${o}${"\u2588".repeat(i)}${Y}${"\u2591".repeat(10-i)}${cr}`,a=K(`${Math.round(n)}%`,o),g=t.filter(Boolean).join(K(" \u2502 ",Y));return`${K("Context",Y)} ${u} ${a}${g?`${K(" \u2502 ",Y)}${g}`:""}`}function pa(e){return!Number.isFinite(e)||e<=0?"":`${K("Spent",Y)} ${K(`$${e.toFixed(3)}`,dr)}`}function ur(e,t,n,i){let o=Number.isFinite(t)&&t>0?t:0,u=Number.isFinite(n)?Math.max(0,n):0,a=Math.max(0,o-u),g=o>0?Math.min(100,u/o*100):0,b=Math.round(g/10),k=da(g),C=`${k}${"\u2588".repeat(b)}${Y}${"\u2591".repeat(10-b)}${cr}`,_=O=>O!==0&&Math.abs(O)<.01?`${O.toFixed(6).replace(/0+$/,"").replace(/\.$/,"")} ${i}`:`${O.toFixed(2)} ${i}`;return[`${K(e,Cc)}${K(" account",Y)}`,` ${K("used",Y)} ${C} ${K(`${g.toFixed(1)}%`,k)}`,` ${K("granted",Y)} ${_(o)}`,` ${K("spent",Y)} ${_(u)}`,` ${K("remaining",Y)} ${K(_(a),k)}`]}function Oe(e,t,n){let i=n===null?"":K(` ${n}ms`,Y),o=t&&t!=="USD"?`${t} `:"";return`${K("Balance",Y)} ${K(`${o}${e}`,dr)}${i}`}var fr=Xe,Rc=18e4;async function Ic(e){let t=new Set((await e.modelRuntime.getAvailable()).map(o=>o.provider).filter(o=>oe(o))),n=ye.find(o=>t.has(o));return n?(await e.modelRuntime.getAuth(n))?.auth?.apiKey:void 0}function _c(){try{let e=JSON.parse(Pc(fr,"utf8"));return!e.data||typeof e.cachedAt!="number"?void 0:{data:e.data,cachedAt:e.cachedAt}}catch{return}}function Bt(e){if(e.unlimited)return Oe("unlimited","",e.latencyMs);let n=e.unit==="USD"||e.unit==="CNY"?`$${e.remaining.toFixed(2)}`:`${e.remaining.toLocaleString()}`,i=e.limit>0?Math.min(100,(1-e.remaining/e.limit)*100):0,o=e.limit>0?`${n} ${i.toFixed(0)}%`:n;return Oe(o,e.unit,e.latencyMs)}async function ga(e){let t=_c();if(t&&Date.now()-t.cachedAt<Rc)return Bt(t.data);let n=await Ic(e);if(!n)return t?Bt(t.data):void 0;let i=Date.now(),o=await Ie(n,{timeoutMs:3e3});if(!o.ok)return t?Bt(t.data):void 0;let u={remaining:o.remaining??0,limit:o.limit??0,unit:o.unit,unlimited:o.unlimited,latencyMs:Date.now()-i};return Ec(Mc(fr),{recursive:!0}),ie(fr,JSON.stringify({data:u,cachedAt:Date.now()})),Bt(u)}import{chmodSync as Lc}from"node:fs";import{join as Oc}from"node:path";function Nc(e){return Oc(e,"account-credential.json")}function ha(e,t){return Buffer.from(`${e}:${t}`,"utf8").toString("base64")}function mr(e){let t=e.trim();if(!t)return null;let n=o=>{let u=o.indexOf(":");return u<=0||u===o.length-1?null:{username:o.slice(0,u),password:o.slice(u+1)}},i=n(t);if(i)return i;try{let o=Buffer.from(t,"base64").toString("utf8");return o.includes(":")?n(o):null}catch{return null}}function ba(e,t,n){try{let i={credential:ha(t,n),username:t,savedAt:Math.floor(Date.now()/1e3)},o=Nc(e);return ie(o,JSON.stringify(i,null,2)),Lc(o,384),!0}catch{return!1}}async function Fc(e,t){let n=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t),signal:AbortSignal.timeout(2e4)}),i=await n.text(),o;try{o=JSON.parse(i)}catch{throw new Error(`the panel answered ${n.status} with something that is not JSON`)}let u=o;if(!n.ok||u.success===!1)throw new Error(u.message||`the panel answered ${n.status}`);return u.data}async function wa(e,t,n,i){let o=await Fc(`${e}/api/auth/cli/credential`,{credential:ha(t,n),client_info:i});if(!o?.token)throw new Error("the panel accepted the credential but returned no key");return{token:o.token}}var jc="/cli/checkin",Dc=["Bearer",""].join(" ").trim(),Wc=5e5;function ya(e){return`$${(e/Wc).toFixed(2)}`}async function ka(e,t,n,i,o){let u=new AbortController,a=setTimeout(()=>u.abort(),o);try{let g=await i(`${n}${jc}`,{method:t,headers:{[Vi]:qi(),"X-HowToCode-Device":so().id,Authorization:`${Dc} ${e}`},signal:u.signal}),b={};try{b=await g.json()}catch{}return{status:g.status,body:b}}finally{clearTimeout(a)}}async function pr(e,t){let n=(t?.baseUrl??"https://api.howtofix.id/v1").replace(/\/+$/,""),i=t?.fetchImpl??fetch,o=t?.timeoutMs??1e4,u=e.trim();if(!u)return{ok:!1,enabled:!1,checkedInToday:!1,quotaToday:0,message:"no token given"};try{let{status:a,body:g}=await ka(u,"GET",n,i,o);if(a===401||a===403)return{ok:!1,enabled:!1,checkedInToday:!1,quotaToday:0,message:"the gateway rejected that token for the check-in status"};if(a>=400||g.success!==!0)return{ok:!1,enabled:!1,checkedInToday:!1,quotaToday:0,message:typeof g.message=="string"?g.message:`the gateway answered ${a}`};let b=g.data??{};return{ok:!0,enabled:b.enabled===!0,checkedInToday:b.checked_in_today===!0,quotaToday:Number(b.quota_today??0)||0,message:""}}catch(a){return{ok:!1,enabled:!1,checkedInToday:!1,quotaToday:0,message:a instanceof Error&&a.name==="AbortError"?"the gateway did not answer the check-in in time":"could not reach the gateway"}}}async function $a(e,t){let n=(t?.baseUrl??"https://api.howtofix.id/v1").replace(/\/+$/,""),i=t?.fetchImpl??fetch,o=t?.timeoutMs??15e3,u=e.trim();if(!u)return{ok:!1,alreadyClaimed:!1,blocked:!1,quotaAwarded:0,message:"no token given"};try{let{status:a,body:g}=await ka(u,"POST",n,i,o);if(g.success===!0){let _=g.data??{};return{ok:!0,alreadyClaimed:!1,blocked:!1,quotaAwarded:Number(_.quota_awarded??0)||0,message:""}}let b=typeof g.message=="string"?g.message:`the gateway answered ${a}`,k=/device already claimed|account blocked|appeal/i.test(b);return{ok:!1,alreadyClaimed:!k&&/签到|check-?in|already|今日/.test(b)&&!/not enabled/i.test(b),blocked:k,quotaAwarded:0,message:b}}catch(a){return{ok:!1,alreadyClaimed:!1,blocked:!1,quotaAwarded:0,message:a instanceof Error&&a.name==="AbortError"?"the gateway did not answer the check-in in time":"could not reach the gateway"}}}import{parseColor as Ne}from"@netrodev/hxf-tui";var V={green:Ne("#4ade80"),yellow:Ne("#facc15"),red:Ne("#f87171"),cyan:Ne("#38bdf8"),purple:Ne("#a78bfa"),dimLine:Ne("#404040")};function Kt(e){return Number.isFinite(e)?e.toLocaleString("en-US"):"0"}function le(e,t="USD"){return Number.isFinite(e)?e!==0&&Math.abs(e)<.01?`${e.toFixed(5).replace(/0+$/,"").replace(/\.$/,"")} ${t}`:`${e.toFixed(2)} ${t}`:`0.00 ${t}`}function va(e,t=15){let n=Math.max(0,Math.min(100,Number.isFinite(e)?e:0)),i=Math.round(n/100*t),o=t-i,u=V.green;n>=90?u=V.red:n>=75&&(u=V.yellow);let a=`${A("\u2588".repeat(i),u)}${A("\u2591".repeat(o),E.dim)}`,g=`${A(`${n.toFixed(1)}%`,u,{bold:!0})}`;return`${a} ${g}`}function xa(e,t,n=54){let i=e.trim(),u=`\u256D\u2500${i?` ${J(i,{bold:!0})} `:""}`,a=F=>F.replace(/\x1B\[[0-9;]*m/g,""),g=Math.max(n-4,a(i).length+4);for(let F of t)g=Math.max(g,a(F).length);let b=g+2,k=Math.max(0,b-a(u).length+1),C=A(`\u256D\u2500${i?" ":""}`,V.dimLine)+(i?J(i,{bold:!0})+A(" ",V.dimLine):"")+A("\u2500".repeat(k)+"\u256E",V.dimLine),_=A("\u2570"+"\u2500".repeat(b)+"\u256F",V.dimLine),O=t.map(F=>{let W=a(F).length,G=" ".repeat(Math.max(0,b-W-2));return`${A("\u2502",V.dimLine)} ${F}${G}${A("\u2502",V.dimLine)}`});return[C,...O,_]}function Sa(e){let{provider:t,usage:n,pools:i,checkin:o,sessionStats:u}=e,a=[];if(u){let k=Kt(u.tokens.input),C=Kt(u.tokens.output),_=Kt(u.tokens.cacheRead),O=`$${Number.isFinite(u.cost)?u.cost.toFixed(4):"0.0000"}`,F=[`${J("Cost:",{bold:!0})} ${A(O,V.green,{bold:!0})}`,`${J("Tokens:",{bold:!0})} ${k} ${A("in",E.dim)} \xB7 ${C} ${A("out",E.dim)} \xB7 ${_} ${A("cache",E.dim)}`,`${J("Messages:",{bold:!0})} ${Kt(u.totalMessages)} ${A(`(${u.toolCalls} tool calls)`,E.dim)}`];a.push(...xa("Current Session",F)),a.push("")}let g=i?.unit??n.unit??"USD",b=[];if(!n.ok)b.push(`${J("Status:",{bold:!0})} ${A("Offline / Error",V.red)}`),b.push(`${A("Message:",E.dim)} ${n.message}`);else if(n.unlimited)if(b.push(`${J("Plan / Quota:",{bold:!0})} ${A("Unlimited tier",V.cyan)}`),n.limit!==void 0&&n.used!==void 0){let k=Math.max(0,n.limit-n.used),C=n.limit>0?n.used/n.limit*100:0;b.push(`${J("Wallet Spend:",{bold:!0})} ${va(C)}`),b.push(`${A("Remaining:",E.dim)} ${le(k,g)} of ${le(n.limit,g)}`)}else b.push(`${A("Allowance:",E.dim)} No token limits enforced on this token`);else if(n.limit!==void 0&&n.used!==void 0){let k=Math.max(0,n.limit-n.used),C=n.limit>0?n.used/n.limit*100:0;b.push(`${J("Quota Usage:",{bold:!0})} ${va(C)}`),b.push(`${J("Balance:",{bold:!0})} ${A(le(k,g),V.green,{bold:!0})} remaining`),b.push(`${A("Usage Stats:",E.dim)} ${le(n.used,g)} spent / ${le(n.limit,g)} granted`)}else n.remaining!==void 0&&b.push(`${J("Balance:",{bold:!0})} ${A(le(n.remaining,g),V.green,{bold:!0})}`),n.used!==void 0&&b.push(`${A("Spent:",E.dim)} ${le(n.used,g)}`),n.limit!==void 0&&b.push(`${A("Granted:",E.dim)} ${le(n.limit,g)}`);if(i&&(b.push(A("\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500",V.dimLine)),i.credit!==void 0&&b.push(`${J("Credit Pool:",{bold:!0})} ${le(i.credit,g)} ${A("(spendable on all models)",E.dim)}`),i.pro!==void 0&&(i.pro>0?b.push(`${J("Pro Credit:",{bold:!0})} ${A(le(i.pro,g),V.purple,{bold:!0})} ${A("(VIP priority lane active)",V.cyan)}`):b.push(`${J("Pro Credit:",{bold:!0})} ${A("0.00 "+g,E.dim)} ${A("(VIP lane locked: top up with /wallet)",E.dim)}`))),o&&o.enabled&&o.ok)if(b.push(A("\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500",V.dimLine)),o.checkedInToday){let k=o.quotaToday?` (+${le(o.quotaToday,g)})`:"";b.push(`${J("Daily Check-in:",{bold:!0})} ${A("\u2713 Claimed today"+k,V.green)}`)}else b.push(`${J("Daily Check-in:",{bold:!0})} ${A("\u25CB Ready to claim on next restart",V.yellow)}`);return a.push(...xa(`${t} Account Limits`,b)),a.join(`
25
+ `)}function Uc(e){return!e||!Number.isFinite(e)||e<=0?"":e>=1e6?`${Number((e/1e6).toFixed(1))}M`:e>=1e3?`${Math.round(e/1e3)}K`:String(e)}function Bc(e){if(!e)return"";if(e.input<=0&&e.output<=0)return"free";let t=n=>n===0?"0":String(Number(n>=1?n.toFixed(2):n.toFixed(3)));return`$${t(e.input)}/$${t(e.output)} per M`}function Ca(e){let t=Uc(e.contextWindow),n=Bc(e.cost);return[t?`${t} ctx`:"",n].filter(Boolean).join(" \xB7 ")}function Aa(){return{}}function Ta(e,t,n,i=Date.now()){let o={...e};return t==="run"?(n===void 0||n===""?delete o.run:o.run={label:n,since:e.run?.since??i},o):(n===void 0||n===""?delete o[t]:o[t]=n,o)}function Ea(e,t){let n={...e};return t===void 0?delete n.retry:n.retry=t,n}function Kc(e){let t=Math.max(0,Math.round(e/1e3)),n=Math.floor(t/60);return n>0?`${n}m ${String(t%60).padStart(2,"0")}s`:`${t}s`}function gr(e,t=72){let n=e.split(`
26
+ `).map(i=>i.trim()).find(i=>i!=="")??"";return n.length>t?`${n.slice(0,t-1)}\u2026`:n}function Gc(e,t){let n=Math.max(0,Math.ceil((e.until-t)/1e3)),i=n>0?`in ${n}s`:"now",o=`retry ${e.attempt}/${e.maxAttempts} ${i}`,u=gr(e.error);return u===""?o:`${o} \xB7 ${u}`}function Pa(e,t,n=Date.now()){return e.prompt?`? ${e.prompt}`:e.retry?`* ${Gc(e.retry,n)}`:e.note?`* ${e.note}`:e.run?`${t} ${e.run.label} \xB7 ${Kc(n-e.run.since)}`:e.tally?e.tally:""}import{spawn as Hc}from"node:child_process";function Vc(e){switch(e){case"darwin":return{command:"open",args:[]};case"win32":return{command:"cmd",args:["/c","start",""]};case"linux":return{command:"xdg-open",args:[]};default:return}}async function Fe(e,t=process.platform){let n=Vc(t);return n?new Promise(i=>{try{let o=Hc(n.command,[...n.args,e],{detached:!0,stdio:"ignore"});o.once("error",()=>i(!1)),o.once("spawn",()=>{o.unref(),i(!0)})}catch{i(!1)}}):!1}function Ma(e){return e instanceof Error?e.message:String(e)}var st=class{active;apply;report;pending;running;constructor(t){this.active=new Set(t.initial??[]),this.apply=t.apply,this.report=t.report??(n=>console.error(n))}activeServers(){return[...this.active]}reconcile(t){return this.pending=new Set(t),this.running?this.running:(this.running=this.drain().finally(()=>{this.running=void 0}),this.running)}async drain(){let t={added:[],removed:[],unchanged:[],problems:[]};for(;this.pending!==void 0;){let i=this.pending;this.pending=void 0;let o=await this.applyOnce(i);t.added.push(...o.added),t.removed.push(...o.removed),t.unchanged.push(...o.unchanged),t.problems.push(...o.problems)}let n=this.active;return t.added=t.added.filter(i=>n.has(i)),t.removed=[...new Set(t.removed.filter(i=>!n.has(i)))],t.added=[...new Set(t.added)],t.unchanged=[...new Set(t.unchanged.filter(i=>n.has(i)))],t}async applyOnce(t){let n=[...t].filter(u=>!this.active.has(u)),i=[...this.active].filter(u=>!t.has(u)),o=[...t].filter(u=>this.active.has(u));if(n.length===0&&i.length===0)return{added:[],removed:[],unchanged:o,problems:[]};try{await this.apply(n,i)}catch(u){let a=`mcp reconciliation failed: ${Ma(u)}`;return this.report(a),{added:[],removed:[],unchanged:[],problems:[a]}}for(let u of n)this.active.add(u);for(let u of i)this.active.delete(u);return{added:n,removed:i,unchanged:o,problems:[]}}async dispose(){this.running&&await this.running.catch(()=>{});let t=[...this.active];if(t.length===0)return{added:[],removed:[],unchanged:[],problems:[]};try{return await this.apply([],t),this.active.clear(),{added:[],removed:t,unchanged:[],problems:[]}}catch(n){let i=`mcp teardown failed: ${Ma(n)}`;return this.report(i),{added:[],removed:[],unchanged:[],problems:[i]}}}};import{mkdirSync as qc}from"node:fs";import{join as zc}from"node:path";import{matchesKey as Gt}from"@netrodev/hxf-tui";var hr=["all","running","failed","done"];function Ia(){return{selectedPhase:0,filter:"all",paused:!1,expanded:!1,follow:!0}}function _a(e){if(Gt(e,"up"))return"up";if(Gt(e,"down"))return"down";if(Gt(e,"enter"))return"enter";if(Gt(e,"escape"))return"escape";if(e==="f")return"filter";if(e==="p")return"pause";if(e==="x")return"stop";if(e==="s")return"save"}function Ra(e,t,n){if(t.length===0)return e;let i=Math.max(0,Math.min(t.length-1,e.selectedPhase+n));return{...e,selectedPhase:i,follow:!1}}function Yc(e){let t=hr.indexOf(e);return hr[(t+1)%hr.length]}function La(e,t,n){switch(t){case"up":return Ra(e,n,-1);case"down":return Ra(e,n,1);case"enter":return{...e,expanded:!e.expanded};case"filter":return{...e,filter:Yc(e.filter)};case"pause":return{...e,paused:!e.paused};default:return e}}function Oa(e,t){switch(t){case"running":return e.filter(n=>n.status==="running");case"failed":return e.filter(n=>n.status==="failed");case"done":return e.filter(n=>n.status!=="running");default:return[...e]}}function Na(e){return e==="all"?"":` \xB7 ${e}`}var Fa="ctrl+f";function ja(e,t,n=!0){if(!n)return"Ctrl+F panel keys \xB7 Esc unpin";let i=["\u2191/\u2193 phase",e.expanded?"Enter collapse":"Enter drill in"];return i.push(e.expanded?"Esc back out":"Esc unpin"),i.push(`f filter${e.filter==="all"?"":` (${e.filter})`}`),t?(i.push(e.paused?"p resume":"p pause"),i.push("x stop")):e.paused&&i.push("p resume"),i.push("s save script"),e.paused&&i.unshift("paused"),i.join(" \xB7 ")}function Jc(e){let t=e.trim();if(!(!t||t.length>64)&&!(t==="."||t==="..")&&/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(t)&&!t.includes(".."))return t}function Da(e,t){if(!e)return{ok:!1,reason:"this run was started from a file, so it is already saved where you pointed the tool"};let n=Jc(e.name);if(!n)return{ok:!1,reason:`"${e.name}" is not a usable filename, so the script was not written`};let i=zc(t,`${n}.js`);try{qc(t,{recursive:!0}),ie(i,e.code)}catch(o){return{ok:!1,reason:o instanceof Error?o.message:String(o)}}return{ok:!0,path:i}}function Wa(e){let t=()=>{};return{select:(n,i)=>e.select(n,i),confirm:(n,i)=>e.confirm(n,i),input:n=>e.input(n),notify:(n,i)=>e.notify(n,i),onTerminalInput:()=>t,setStatus:(n,i)=>e.setStatus(n,i),setWorkingMessage:t,setWorkingVisible:t,setWorkingIndicator:t,setHiddenThinkingLabel:t,setWidget:(n,i,o)=>{i!==void 0&&!Array.isArray(i)||e.setWidget?.(n,i,o?.placement)},setFooter:t,setHeader:t,setTitle:t,custom:async()=>{throw new Error("this screen has no custom component host; use the text commands instead")},pasteToEditor:t,setEditorText:t,getEditorText:()=>"",editor:async()=>{},addAutocompleteProvider:t,setEditorComponent:t,getEditorComponent:()=>{},theme:void 0,getAllThemes:()=>[],getTheme:()=>{},setTheme:()=>({success:!1,error:"themes are not available in the workbench"}),getToolsExpanded:()=>!1,setToolsExpanded:t}}import{createCipheriv as Xc,createDecipheriv as Zc,randomBytes as wr,scryptSync as Qc}from"node:crypto";import{existsSync as Ht,readFileSync as ed,rmSync as td}from"node:fs";import{join as nd}from"node:path";function je(e){return nd(e,"vault.json")}var Ua=32768,Ba=8,Ka=1,rd=64*1024*1024,id=32,Ga=16,od=12,te=class extends Error{constructor(t){super(t),this.name="VaultError"}};function br(e,t,n){return Qc(e,t,id,{N:n.N,r:n.r,p:n.p,maxmem:rd})}function sd(e,t){let n=wr(od),i=Xc("aes-256-gcm",e,n),o=Buffer.concat([i.update(t,"utf8"),i.final()]);return{name:"aes-256-gcm",iv:n.toString("base64"),tag:i.getAuthTag().toString("base64"),data:o.toString("base64")}}function ad(e,t){let n=Zc("aes-256-gcm",e,Buffer.from(t.iv,"base64"));return n.setAuthTag(Buffer.from(t.tag,"base64")),Buffer.concat([n.update(Buffer.from(t.data,"base64")),n.final()]).toString("utf8")}function ld(e){return e.length<=4?"****":`\u2026${e.slice(-4)}`}var fe=class e{constructor(t,n,i,o){this.path=t;this.kdf=i;this.entries=o;this.key=n}path;kdf;entries;key;static exists(t){return Ht(je(t))}static create(t,n){let i=je(t);if(Ht(i))throw new te("a vault already exists; unlock it instead of creating one");if(n.length<8)throw new te("the master password must be at least 8 characters");let o=wr(Ga),u={name:"scrypt",N:Ua,r:Ba,p:Ka,salt:o.toString("base64")},a=br(n,o,u),g=new e(i,a,u,[]);return g.save(),g}static unlock(t,n){let i=je(t);if(!Ht(i))throw new te("no vault found; create one first");let o;try{o=JSON.parse(ed(i,"utf8"))}catch{throw new te("the vault file is not readable JSON")}if(o.version!==1||o.kdf?.name!=="scrypt"||o.cipher?.name!=="aes-256-gcm")throw new te("the vault file was written by a version this CLI does not understand");let u=br(n,Buffer.from(o.kdf.salt,"base64"),o.kdf),a;try{a=JSON.parse(ad(u,o.cipher))}catch{throw new te("could not open the vault: wrong master password, or the file is damaged")}if(!Array.isArray(a))throw new te("could not open the vault: the contents are not a credential list");return new e(i,u,o.kdf,a)}lock(){this.key.fill(0)}list(){return this.entries.map(t=>({name:t.name,platform:t.platform,...t.account===void 0?{}:{account:t.account},...t.fields===void 0?{}:{fields:t.fields},updatedAt:t.updatedAt,hint:ld(t.value)})).sort((t,n)=>t.name.localeCompare(n.name))}get(t){return this.entries.find(n=>n.name===t)}put(t){if(!t.name.trim())throw new te("a credential needs a name");if(!t.platform.trim())throw new te("a credential needs a platform");if(!t.value)throw new te("a credential needs a value");let n={...t,updatedAt:Math.floor(Date.now()/1e3)},i=this.entries.findIndex(o=>o.name===t.name);i>=0?this.entries[i]=n:this.entries.push(n),this.save()}remove(t){let n=this.entries.length;return this.entries=this.entries.filter(i=>i.name!==t),this.entries.length===n?!1:(this.save(),!0)}changePassword(t){if(t.length<8)throw new te("the master password must be at least 8 characters");this.lock();let n=wr(Ga),i={name:"scrypt",N:Ua,r:Ba,p:Ka,salt:n.toString("base64")};this.key=br(t,n,i),this.kdf=i,this.save()}save(){let t=JSON.stringify(this.entries),n={version:1,kdf:this.kdf,cipher:sd(this.key,t)};ie(this.path,`${JSON.stringify(n,null,2)}
27
+ `,{mode:384})}};function Ha(e){let t=je(e);return Ht(t)?(td(t,{force:!0}),!0):!1}var Ya={borderColor:()=>"",selectList:{selectedPrefix:e=>A(e,E.accent),selectedText:e=>A(e,E.text,{bold:!0}),description:e=>A(e,E.mute),scrollInfo:e=>A(e,E.dim),noMatch:e=>A(e,E.mute)}},tl=Symbol.for("@netrodev/hxf-tui/layout-node");function Pd(e){if(typeof e!="object"||e===null)return;let t=e[tl];return typeof t=="function"?t.call(e):void 0}var Cr=dd(cd);async function Ja(e){try{let{stdout:t}=await Cr("git",["-C",e,"rev-parse","--abbrev-ref","HEAD"],{encoding:"utf8"}),n=t.trim();if(!n||n==="HEAD")return"";let{stdout:i}=await Cr("git",["-C",e,"status","--porcelain"],{encoding:"utf8"});return`git:(${n}${i.trim()?"*":""})`}catch{return null}}var $r=550,vr=650,Md=Yt("#22d3ee"),Rd=Yt("#eaffff"),Id=Yt("#22d3ee"),_d=Yt("#dafa9b"),Ar=class{folder;model;git;percent=0;meter=new _t(0);sentAt=0;settledAt=0;activity=Aa();live=!1;activitySince=Date.now();thinking="medium";ceiling=void 0;usage="";cost=0;skipPermissions=!1;constructor(t,n){this.folder=md(t),this.model=n.split("/").at(-1)||"no-model",this.git=""}invalidate(){}settling(){return this.meter.moving}atCeiling(){return this.ceiling!==void 0&&this.thinking===this.ceiling}levelChangedAt=0;upgradeAt=0;setThinking(t){if(t===this.thinking)return;let n=u=>u==="high"||u==="xhigh"||u==="max",i=u=>({off:0,minimal:1,low:2,medium:3,high:4,xhigh:5,max:6})[u]??0,o=i(t)>i(this.thinking);o&&n(t)?this.upgradeAt=Date.now():!o&&this.upgradeAt!==0&&(this.upgradeAt=0),this.thinking=t,this.levelChangedAt=Date.now()}upgradeAmount(t=Date.now()){if(this.upgradeAt===0)return 0;let n=t-this.upgradeAt;return n<0||n>=3e3?0:1-n/3e3}upgrading(){return this.upgradeAmount()>0}levelFlashAmount(){return this.levelChangedAt===0?0:Ut(Date.now()-this.levelChangedAt)}flashing(){return this.levelFlashAmount()>0}levelText(t){if(this.upgrading())return Jn(this.thinking,ar,t,45);if(this.atCeiling())return Jn(this.thinking,ar,t);let n=this.levelChangedAt===0?Number.POSITIVE_INFINITY:t-this.levelChangedAt;return Ut(n)<=0?ca(this.thinking,this.thinking):Lt(this.thinking,{rest:Wt(this.thinking),lit:ra(this.thinking)},1-Ut(n))}meterValue(){return this.meter.value!==this.percent&&this.meter.set(this.percent),this.meter.step()}beginRun(){this.live=!0,this.activitySince=Date.now(),this.sentAt=Date.now()}endRun(){this.live=!1,this.settledAt=Date.now()}feedbackPlaying(){let t=Date.now();return this.sentAt>0&&t-this.sentAt<$r||this.settledAt>0&&t-this.settledAt<vr}badgeFeedback(t){if(!ue)return;let n=t-this.settledAt;if(this.settledAt>0&&n>=0&&n<vr)return o=>Lt(o,{rest:Id,lit:_d},n/vr);let i=t-this.sentAt;if(this.sentAt>0&&i>=0&&i<$r)return o=>Lt(o,{rest:Md,lit:Rd},i/$r)}waitedMs(){return Date.now()-this.activitySince}abandonAnimations(){this.meter.snap(this.percent)}render(t){let n=Date.now(),i=rt(),o=this.waitedMs(),u=this.percent===0&&this.meter.value===0?0:this.meterValue(),a=this.levelText(n),g=ua(this.model,a,this.folder,this.git,this.badgeFeedback(n)),b=[We(`${fa(g,this.live?i:"",this.live?o:void 0)} ${ma(u,this.usage,pa(this.cost))}`,t)];this.skipPermissions&&b.push(We(A("Permissions OFF \u2014 critical commands and the repeat guard are not enforced",E.bad),t));let k=jo();k&&b.push(We(A(k,E.warn),t));let C=Ro(Mt());return C&&b.push(We(A(C,E.accent),t)),b}renderActivity(t){let n=Date.now(),i=rt(),o=this.waitedMs(),u=Pa(this.activity,i,n),a=this.live?Ps(u,{base:Yn(o,E.mute,E.warn,E.bad),bright:E.text,charMs:45},n):A(u,Yn(o,E.mute,E.warn,E.bad));return[We(a,t)]}},Tr=class{constructor(t){this.draw=t}draw;render(t){return this.draw(t)}invalidate(){}},Er=class{constructor(t,n){this.editor=t;this.hud=n}editor;hud;focused=!1;invalidate(){this.editor.invalidate()}render(t){let n=Math.max(10,t-4),i=this.editor.render(n),o=C=>/^[─↑↓\d]*$/.test(C.replace(/\x1b\[[0-9;]*[A-Za-z]/g,"").trim()),u=i.length>=2&&o(i[0])&&o(i[i.length-1])?i.slice(1,-1):i,a=u.length>0?u:[""],g="\u2500".repeat(Math.max(0,t-2)),b=a.map(C=>{let _=Math.max(0,n-Sr(C));return`\u2502 ${C}${" ".repeat(_)} \u2502`}),k=`\u2514${g}\u2518`;return[...this.hud.renderActivity(t),`\u250C${g}\u2510`,...b,k,...this.hud.render(t)]}handleInput(t){this.editor.handleInput(t)}};function Ld(e,t,n,i=!1,o=[]){let{inner:u,line:a,bar:g,box:b}=nl(n),k=[a(` ${t}`),...e.render(u).map(O=>a(O))];k.push(a(" type to filter \xB7 \u2191\u2193 move \xB7 enter select \xB7 esc cancel"));let _=o.flatMap(O=>O===""?[""]:el(O,u)).map(O=>a(O,F=>A(F,E.mute)));return rl(b,g,[...k,..._],i)}function Od(e,t,n,i="esc close"){let{inner:o,line:u,bar:a,box:g}=nl(n),b=t.flatMap(C=>C===""?[""]:el(C,o)),k=[u(` ${e} \xB7 ${i}`),...b.map(C=>u(C))];return rl(g,a,k,!1)}function nl(e){let t=Math.max(24,e),n=t-4,i=(o,u)=>{let a=Sr(o)>n?We(o,n,"\u2026"):o,g=`${a}${" ".repeat(Math.max(0,n-Sr(a)))}`;return`\u2502 ${u?u(g):g} \u2502`};return{box:t,inner:n,bar:"\u2500".repeat(t-2),line:i}}function rl(e,t,n,i){if(!i)return["",`\u250C${t}\u2510`,...n,`\u2514${t}\u2518`];let o=Es(E.line,E.warn,Date.now(),1400),u=A("\u2502",o),a=(b,k)=>A(`${b}${t}${k}`,o),g=n.map(b=>`${u}${b.slice(1,-1)}${u}`);return["",a("\u250C","\u2510"),...g,a("\u2514","\u2518")]}function Nd(e,t){let n=t.split(`
28
+ `).filter(Boolean),i=n.filter(a=>a.startsWith("Reason:")),o=n.filter(a=>!a.startsWith("Reason:")&&!a.startsWith("Allow tool:"));return[...e.endsWith(" wants to run")?[]:[e],...i,...o.length>0?["",...o]:[]]}function De(e){let t=e.getContextUsage();if(t?.percent!==null&&t?.percent!==void 0)return Math.min(100,Math.round(t.percent));let n=e.model,o=[...e.state.messages].reverse().find(u=>u.role==="assistant")?.usage?.totalTokens;return!n||typeof o!="number"||!Number.isFinite(o)||n.contextWindow<=0?0:Math.min(100,Math.round(o/n.contextWindow*100))}function xr(e){let n=[["init","write project notes to AGENTS.md"],["model","choose a model"],["providers","list providers"],["thinking","set thinking level"],["approval","set what needs approval"],["settings","turn permission checks on or off"],["trust","trust this folder's .hxf settings, prompts and skills (status | on | off)"],["connect","sign in: approve in your browser (or /connect <sk-key | email:password>)"],["vault","encrypted credentials: init | unlock | list | add | rm | passwd | lock | destroy"],["sync","re-sync models from howtofix.id"],["usage","show the account's quota and what it has spent"],["wallet","open the Wallet to top up Pro Credit (the VIP lane)"],["update","install the newest release"],["login","save a provider API key"],["logout","remove a provider"],["new","start a new session"],["resume","resume another session"],["compact","compact the session"],["name","name this session"],["stats","session tokens and cost, cache hit rate and misses"],["rtk","compress long tool output before the model reads it"],["diff","show the working tree diff"],["commit","stage everything and commit"],["undo","undo the last commit"],["rewind","go back to an earlier message (Esc Esc)"],["review","ask the agent to review the diff"],["tools","list active tools"],["skills","list loaded skills"],["preset","browse, install and remove preset skill bundles"],["roblox","RoToolbox status: whether Studio's MCP server is connected"],["proxy","route requests through a proxy, or show the current one"],["browser-relay","drive your Chrome tabs: install | status"],["export","write the transcript to a markdown file"],["copy","copy the last answer to the clipboard"],["agents","show spawned agents"],["goal","set or view this session's goal"],["plan","toggle plan mode (design before editing)"],["workflow","show or clear the pinned workflow panel"],["dcp","dynamic context pruning: on | off | status | blocks | stats | context | decompress <bN> | sweep"],["context","what the next request carries, and what pruning saved"],["decompress","reopen one compressed block, e.g. /decompress b2"],["sweep","close compressed blocks no ref resolves"],["session","show the current model"],["help","list commands"],["quit","quit"],["exit","quit (alias)"]].map(([i,o])=>({name:i,description:o}));for(let i of e.promptTemplates)n.push({name:i.name,description:i.description});for(let i of e.extensionRunner.getRegisteredCommands())n.push({name:i.invocationName,description:i.description});return n}function Pr(e,t){if(e!=="workflow")return;let n=it(t);if(!(typeof n.name!="string"||!Array.isArray(n.steps)))return n}function Fd(e,t){let n=Pr(e,t);return n?zt(n):void 0}function zt(e,t,n=!1){return i=>ts(e,[],i,t?.selectedPhase,t?jd(e,t,n):void 0)}function jd(e,t,n){return{filter:i=>Oa(i,t.filter),footerText:ja(t,e.endedAt===void 0,n),filterLabel:Na(t.filter),drill:t.expanded}}function Dd(){let e=new Xa(Qa,{"tui.altScreen.pageUp":[],"tui.altScreen.pageDown":[],"tui.altScreen.halfPageUp":[],"tui.altScreen.halfPageDown":[],"tui.altScreen.top":[],"tui.altScreen.bottom":[]});Za(e)}async function vm(e){let t=new $d,n,i=new Cd(t,!0,void 0,{mouse:!0,onRightClickPaste:()=>n?.()}),o=new jt,u=[],a=new Ar(e.cwd,e.modelLabel);a.skipPermissions=Fn();let g=r=>{(async()=>{try{let s=lt(),c=$.getSessionStats().sessionId;if(!Fr){Fr=!0;try{await ds(s,{keep:c})}catch{}}await as(s,c,r)}catch{}})()},b=(r=!1)=>{!r&&!a.live||Ja(e.cwd).then(s=>{s!==null&&(a.git=s,S())})},k=new kd(i,Ya,{paddingX:1}),C=new Map,_=(r,s)=>{s===void 0?C.delete(r):typeof s=="function"?C.set(r,s):C.set(r,()=>s)},O,F=0,W=Ia(),G,Q=null,ve=!1,at,pe=!1,il,Jt=()=>{!G||!ve||_("workflow",r=>zt(G,W,pe)(r))},Mr=()=>{G&&(at=G.name),ve=!1,pe=!1,_("workflow",void 0)};ns({onStop:r=>{Q=r},isPaused:()=>W.paused});let Rr=r=>{if(at===r.name)return;O=r;let s=r.endedAt??Date.now();F=Math.max(F,s+Zo),G=r,ve=!0,_("workflow",c=>zt(r,W,pe)(c))},Ir=new Er(k,a),$=e.session,Xt=e.dispose,_r=e.setCompressToolOutput,Lr=!1,Or=e.session.getSessionStats().sessionId,Zt=()=>{let r=$.getSessionStats().cost;return a.cost=r,r},Qt=Di(e.maxBudgetUsd),Nr=!1,ol=()=>{let r=Qt.check(Zt());r===void 0||Nr||(Nr=!0,$.isStreaming&&$.abort(),m("budget",Wi(r.spent,r.limit)))},xe=()=>{a.ceiling=ia($.model)},be=mo(R),ne,en,sl=async()=>!be||!fo(be)||uo(be)?!1:(en??=(async()=>{try{let r=await go(R,be);return r.renewed?(be=r.credential,r.message&&m("connect",r.message),await $.modelRuntime.setRuntimeApiKey("howtocode",r.credential.accessToken),!0):(r.terminal&&(be=void 0),r.message&&m("connect",r.message),!1)}catch{return!1}finally{en=void 0}})(),await en),tn,lt=()=>tn??=os(e.cwd),nn="",Fr=!1,Se,al=()=>{let r=new Set(["session_info","usage","label","context_edit","custom","model_change","thinking_level_change"]),s=[],c=l=>{for(let f of l)r.has(f.entry.type)||s.push(f.entry.id),c(f.children)};return c($.sessionManager.getTree()),s},jr=!1,ll=()=>{if(jr)return;jr=!0;let r=za().getResolvedBindings();Za(new Xa(Qa,{...r,"app.tree.foldOrUp":["alt+left","ctrl+left"],"app.tree.unfoldOrDown":["alt+right","ctrl+right"],"app.tree.editLabel":["shift+l"],"app.tree.toggleLabelTimestamp":["shift+t"],"app.message.copy":["ctrl+x"],"app.tree.filter.default":["alt+0"],"app.tree.filter.noTools":["alt+1"],"app.tree.filter.userOnly":["alt+2"],"app.tree.filter.labeledOnly":["alt+3"],"app.tree.filter.all":["alt+4"],"app.tree.filter.cycleForward":["alt+f"],"app.tree.filter.cycleBackward":["alt+shift+f"]}))},Dr=!1,cl=()=>{Dr||(Dr=!0,Ed())},Wr=()=>{let r=$.sessionManager.getTree();if(r.length===0){m("rewind","nothing to rewind to yet");return}lt().disabled&&m("rewind","conversation rewind only; this directory is not a git repository"),cl(),ll();let s=Math.max(8,Math.floor(t.rows*.6)),c=new Td(r,$.sessionManager.getLeafId(),s*2,l=>{rn(),dl(l)},()=>rn());if(!c.getTreeList().getSelectedNode()){m("rewind","nothing to rewind to yet");return}Se=c,Se.focused=!0,_("rewind",l=>Se?.render(l)??[]),S()},rn=()=>{Se=void 0,_("rewind",void 0),S()},dl=async r=>{let s=lt(),l=$.getUserMessagesForForking().findIndex(d=>d.entryId===r),f=l>=0?ss(s,$.getSessionStats().sessionId)[l]:void 0,y=f?(await cs(s,f)).length:0;if(y===0){await Ur(r,void 0,"conversation");return}j(`Rewind to this point? ${y} file(s) differ`,[{value:"both",label:"conversation and code",description:`drop the messages after this point and restore ${y} file(s)`},{value:"conversation",label:"conversation only",description:"drop the messages after this point, leave the files alone"},{value:"code",label:"code only",description:`restore ${y} file(s), keep the conversation`}],d=>{Ur(r,f,d)})},Ur=async(r,s,c)=>{let l=[];if((c==="both"||c==="conversation")&&!$.isStreaming)try{let f=await $.navigateTree(r);if(f.cancelled){m("rewind","conversation rewind cancelled");return}l.push("conversation rewound"),o.items=Dt($.state.messages),f.editorText&&(k.setText(f.editorText),l.push("prompt restored to the editor"))}catch(f){H(`conversation rewind failed: ${f instanceof Error?f.message:String(f)}`);return}if((c==="both"||c==="code")&&s){let f=await ls(lt(),s);if(!f.ok){H(`code rewind failed: ${f.output}`);return}l.push(f.output),f.removed.length>0&&l.push(`removed ${f.removed.length} file(s)`),b()}m("rewind",l.join(`
29
+ `)||"nothing to do"),S()};b(!0),g("session start"),e.note&&o.items.push({id:"note",kind:"note",title:"note",body:e.note}),o.items.push(...Dt($.state.messages)),a.percent=De($),Zt(),a.abandonAnimations(),a.setThinking($.thinkingLevel),xe(),k.setAutocompleteProvider(new qa(xr($),e.cwd)),ga($).then(r=>{r&&(a.usage=r,i.requestRender())});let Br=async r=>{let{checkForUpdate:s,checkFailedNote:c,installUpdate:l}=await import("./chunk-LYLJZVZ7.js"),f=await s(r.current);if(!f.available){let d=c(f);d?m("update",d):r.install&&m("update",f.message);return}if(!r.install){m("update",`${f.message}. run /update to install it.`);return}P("note",`installing HowToCode ${f.latest}\u2026`);let y=await l({version:f.latest});P("note",void 0),m("update",y.message),S()};e.update&&Br(e.update);let ce=null,Kr="",on=!1,Gr=[],Ce=null,Hr=0,Ue,sn=()=>{},S=()=>{sn(),i.requestRender()},P=(r,s)=>{a.activity=Ta(a.activity,r,s)},an=r=>{a.activity=Ea(a.activity,r)},ct=new Map,ln=new Set,ul=()=>[...ct].map(([r,s])=>`${ln.has(r)?"!":"\u2713"} ${r} \xD7${s}`).join(" | "),fl=()=>{let r=ul();P("tally",r||void 0)},j=(r,s,c,l,f=!1,y=[])=>{let d=new Sd(s,8,Ya.selectList);d.onSelect=p=>{ce=null,Ue=void 0,c(p.value)},d.onCancel=()=>{ce=null,Ue=void 0,l?.(),S()},Ue=()=>d.onCancel?.(),Kr=r,on=f,Gr=y,ce=d,Jr+=1,S()},m=(r,s)=>{o.items=Ys(o.items,{id:`cmd-${Date.now()}-${o.items.length}`,kind:"note",title:r,body:s}),P("tally",void 0),S()},ml=(r,s)=>{Ce={title:r,body:s},Hr+=1,S()},Vr=()=>{Ce&&(Ce=null,S())};Ho(r=>{r.background&&m("agent",`${Wo(r)}
30
+ read it with /agents ${r.id}`)});let cn=!1,qr=r=>{cn||(cn=!0,(async()=>{try{let s=(await $.modelRuntime.getAvailable()).filter(h=>oe(h.provider)),c=new Set(s.map(h=>h.provider)),l=ye.find(h=>c.has(h)),f=l?(await $.modelRuntime.getAuth(l))?.auth?.apiKey:void 0;if(!f)return;let y=It(s.map(h=>h.id)),{live:d,probed:p}=await io(y,f,{exclude:r,limit:4});if(d.length===0)return;let w=ce===null;m("gateway",`${d.length} of ${p.length} probed models answer right now (${d.join(", ")}); ${w?"the model picker is open below":"switch with /model"}.`),w&&Je("/model")}catch{}finally{cn=!1}})())},H=r=>{o.items.push({id:`err-${Date.now()}-${o.items.length}`,kind:"error",title:"failed",body:r});let s=Mn(r);s!==void 0&&m("gateway",s);let c=Pn(r);c!==void 0&&qr(c),P("tally",void 0),S()},Be=r=>{$.setThinkingLevel(r,{persist:!0}),a.setThinking(r),xe(),P("note",`thinking ${r}`),S()};$o((r,s)=>{let{promise:c,resolve:l}=Promise.withResolvers();return j(r,[{value:"allow",label:"allow"},{value:"deny",label:"deny"}],f=>l(f==="allow"),()=>l(!1),!0,Nd(r,s)),c});let dt=new Map,zr=r=>{let s=Wa({select:(c,l)=>{let{promise:f,resolve:y}=Promise.withResolvers();return j(c,l.map(d=>({value:d,label:d})),y,()=>y(void 0)),f},confirm:(c,l)=>{let{promise:f,resolve:y}=Promise.withResolvers();return j(`${c} \u2014 ${l}`,[{value:"yes",label:"yes"},{value:"no",label:"no"}],d=>y(d==="yes"),()=>y(!1)),f},input:c=>{let{promise:l,resolve:f}=Promise.withResolvers();return P("prompt",c),S(),X=y=>{X=void 0,P("prompt",void 0),f(y),S()},l},notify:(c,l)=>{l==="error"?H(c):m("mcp",c)},setStatus:(c,l)=>{l===void 0?dt.delete(c):dt.set(c,l),P("note",[...dt.values()].join(" | ")||void 0),S()},setWidget:(c,l)=>{_(c,l),S()}});r.bindExtensions({uiContext:s,mode:"print",onError:c=>H(`${c.event}: ${c.error}`)}).catch(c=>H(c instanceof Error?c.message:String(c)))};zr($);let Ae=new yd,pl={invalidate:()=>o.invalidate(),render:r=>{let s=Ae.render(Math.max(20,r)).length;return o.viewportHeight=Math.max(1,Math.max(8,t.rows)-s),o.render(r)},handleMouse:r=>{if(li(r))return Ve(),{handled:!0};ci(r)&&ai();let s=r.type==="wheel"?r.wheelDelta??0:0;if(s!==0)return o.scrollOffset=Math.max(0,o.scrollOffset-s*3),S(),{handled:!0}}},gl=new vd(pl,{follow:"none",overscroll:"contain"}),ut=new Ad([{component:gl,grow:1,shrink:1},{component:Ae,grow:0,shrink:0,basis:"auto"}]),Yr="",Jr=0,hl=()=>`${ce?`picker:${Jr}`:Ce?`info:${Hr}`:"dock"}|${[...C.keys()].join(",")}`;sn=()=>{let r=hl();if(r===Yr)return;Yr=r,Ae.clear();for(let l of C.values())Ae.addChild(new Tr(l));let s=ce,c=Ce;if(s){let l=Kr,f=on,y=Gr;Ae.addChild({render:d=>Ld(s,l,d,f,y),invalidate:()=>{}})}else c?Ae.addChild({render:l=>Od(c.title,c.body,l),invalidate:()=>{}}):Ae.addChild(Ir);ut.invalidate()},sn();let Xr={focused:!1,invalidate(){o.invalidate(),Ir.invalidate(),ce?.invalidate(),ut.invalidate()},[tl]:()=>Pd(ut),render:r=>ut.render(r),handleMouse(r){if(ci(r)){ai();return}if(li(r))return Ve(),{handled:!0}},handleInput(r){k.handleInput(r)}};i.setLayoutRoot(Xr),i.setFocus(Xr);let Z=0,ge="",dn=!1,Te=!1,un,Me="",Zr=0,Ke=!1,ft=Date.now(),mt=!1,Ge=new Map,Qr=()=>{let r=new Set($.getSteeringMessages().map(s=>s.trim()).filter(Boolean));for(let s of o.items)s.kind!=="user"||!s.pending||r.has(s.body.trim())||(s.pending=void 0)},ei=r=>{if(r.type==="agent_start"&&Qr(),r.type==="agent_start"||r.type==="turn_start")r.type==="agent_start"&&yo(),a.live||a.beginRun(),ge="",Te=!1,Ke=!1,ft=Date.now(),Me="";else if(r.type==="message_update"&&r.assistantMessageEvent.type==="thinking_delta"){Te=!0,Me===""&&(Zr=Date.now()),Me+=r.assistantMessageEvent.delta;let s=`think-${Z}`,c=En(Me).split(`
31
+ `).slice(-6).join(`
32
+ `),l=o.items.find(f=>f.id===s);l?l.body=c:o.items.push({id:s,kind:"note",title:"thinking",body:c})}else if(r.type==="message_update"&&r.assistantMessageEvent.type==="thinking_end"){let s=`think-${Z}`,c=o.items.find(l=>l.id===s);if(c){let l=Math.max(1,Math.round((Date.now()-Zr)/1e3));c.title="thought",c.body=`${l}s \xB7 ${Me.length} chars of reasoning`}Me=""}else if(r.type==="message_update"&&r.assistantMessageEvent.type==="text_delta"){Te=!0,ge+=r.assistantMessageEvent.delta;let s=En(ge),c=`live-${Z}`,l=o.items.find(f=>f.id===c);l?l.body=s:o.items.push({id:c,kind:"assistant",title:"HowToCode",body:s})}else if(r.type==="tool_execution_start"){Ge.set(r.toolCallId,r.args),Te=!1,Ke=!1,ft=Date.now();let s=`tool-${r.toolCallId}`,c=Pe(r.toolName,r.args),l=o.items.find(f=>f.id===s);if(l?(l.kind="tool",l.title=r.toolName,l.body=c,l.live=!0):o.items.push({id:s,kind:"tool",title:r.toolName,body:c,live:!0}),un=r.toolName,r.toolName==="task"){let f=Uo.filter(y=>y.status==="queued"||y.status==="running");P("note",f.map(y=>`${y.agent} ${y.status}`).join(" | ")||"agent running")}}else if(r.type==="tool_execution_update"){let s=Fd(r.toolName,r.partialResult);if(s){let c=`tool-${r.toolCallId}`,l=o.items.find(y=>y.id===c);l?l.panel=s:o.items.push({id:c,kind:"tool",title:r.toolName,body:Pe(r.toolName,Ge.get(r.toolCallId)),panel:s,live:!0});let f=Pr(r.toolName,r.partialResult);f&&at!==f.name&&Rr(f),S()}}else if(r.type==="tool_execution_end"){a.percent=De($);let s=o.items.find(x=>x.id===`tool-${r.toolCallId}`);s&&(s.live=!1,s.body=Pe(r.toolName,Ge.get(r.toolCallId))),Ge.delete(r.toolCallId),un=void 0,Te=!0,Ke=!1,ct.set(r.toolName,(ct.get(r.toolName)??0)+1),r.isError&&ln.add(r.toolName),fl();let l=[...Gs(r.result),...Hs(r.toolName,r.result)],f=Vs(r.toolName,r.result),y=Pr(r.toolName,r.result),d=y?zt(y):void 0;y&&at!==y.name&&Rr(y);let p=o.items.find(x=>x.id===`tool-${r.toolCallId}`),w=Ft(r.toolName,r.result,r.isError),h=r.isError===!0||w.startsWith("exit ")&&w!=="exit 0";p?(p.kind="result",p.call=p.body,p.body=w,p.live=!1,h&&(p.failed=!0),l.length>0&&(p.detail=l),f.length>0&&(p.full=f),d&&(p.panel=d)):o.items.push({id:`tool-${r.toolCallId}`,kind:"result",title:r.toolName,body:w,...h?{failed:!0}:{},...l.length>0?{detail:l}:{},...f.length>0?{full:f}:{},...d?{panel:d}:{}}),(r.toolName==="bash"||r.toolName==="powershell"||r.toolName==="edit"||r.toolName==="write")&&b()}else if(r.type==="compaction_start"){Te=!0,Z+=1;let s=r.reason==="manual"?"on request":"context is nearly full",c=o.items.find(y=>y.id===`compact-${Z}`),l="compacting context",f=`${s} \xB7 summarizing the older turns`;c?(c.title=l,c.body=f):o.items.push({id:`compact-${Z}`,kind:"note",title:l,body:f,live:!0}),P("note","compacting context")}else if(r.type==="compaction_end"){let s=o.items.find(y=>y.id===`compact-${Z}`),c=r.result,l="compacted",f;if(r.aborted)f="cancelled";else if(r.errorMessage)f=`failed: ${r.errorMessage}`;else if(c){let y=Math.round(c.tokensBefore/1e3),d=c.estimatedTokensAfter!==void 0?Math.round(c.estimatedTokensAfter/1e3):void 0,p=c.estimatedTokensAfter!==void 0?c.tokensBefore-c.estimatedTokensAfter:void 0,w=p!==void 0&&p<2e3;f=d!==void 0?`${y}k \u2192 ${d}k tokens \xB7 older turns summarized${w?`
33
+ this freed almost nothing; the window may be too small for this work`:""}`:`${y}k tokens \xB7 older turns summarized`}else f="nothing to compact";s?(s.title=l,s.body=f,s.live=!1):o.items.push({id:`compact-${Z}`,kind:"note",title:l,body:f}),a.percent=De($),P("note",void 0)}else if(r.type==="message_start"&&r.message.role==="user"){let s=Js(r.message);s&&(o.items=Xs(o.items,s,`u-${r.message.timestamp}`)),Qr()}else if(r.type==="message_end"&&r.message.role==="assistant"){let s=o.items.find(l=>l.id===`live-${Z}`);s&&(s.id=`done-${Z}`);let c=r.message.errorMessage;if(c&&s){s.title="failed",s.kind="error",s.body=ge.trim()?`${c}
34
+
35
+ ${ge.trim()}`:c;let l=Mn(c);l!==void 0&&m("gateway",l);let f=Pn(c);f!==void 0&&qr(f)}else c&&H(c);Z+=1,ge="",a.percent=De($)}else if(r.type==="agent_settled"){a.endRun();let s=[...$.getSteeringMessages()].map(c=>c.trim()).filter(Boolean);if(s.length>0){let c=k.getText().trim();k.setText(c?`${s.join(`
36
+ `)}
37
+ ${c}`:s.join(`
38
+ `));let l=new Set(s);for(let f of o.items)f.kind==="user"&&f.pending&&l.has(f.body.trim())&&(f.pending=void 0);m("queued",`${s.length} unread message${s.length===1?"":"s"} were never read and are back in the editor`)}for(let c of o.items)c.kind==="user"&&c.pending&&(c.pending=void 0);if(g(nn),nn="",P("run",void 0),dn){let c=o.items.find(l=>l.id===`live-${Z}`);c?(c.id=`stopped-${Z}`,c.title="stopped",c.body=ge.trim()||"(no output)",c.live=!1):o.items.push({id:`stopped-${Z}`,kind:"note",title:"stopped",body:"run cancelled"}),Z+=1,ge="",m("stopped","run cancelled by Esc"),dn=!1}a.percent=De($),P("note",void 0),an(void 0),Ja(e.cwd).then(c=>{c!==null&&(a.git=c,S())}),k.disableSubmit=!1}else r.type==="thinking_level_changed"?a.setThinking(r.level):r.type==="auto_retry_start"?(P("note",void 0),r.attempt%3===0&&r.attempt<r.maxAttempts&&an({attempt:r.attempt,maxAttempts:r.maxAttempts,error:r.errorMessage,until:Date.now()+r.delayMs})):r.type==="auto_retry_end"&&(an(void 0),r.success?m("retry",`answered on attempt ${r.attempt} after a retry`):P("note",`retry ${r.attempt} gave up${r.finalError?` \xB7 ${gr(r.finalError)}`:""}`));ol(),S()},fn=$.subscribe(ei),ti=setInterval(()=>{let r=O!==void 0&&Date.now()<F,s=a.activity.retry!==void 0&&Date.now()<a.activity.retry.until;if((mt||a.live||$.isStreaming||a.settling()||o.entering()||ce!==null&&on||r||a.flashing()||a.feedbackPlaying()||a.upgrading()||s)&&S(),(mt||$.isStreaming)&&!Te&&!Ke&&Date.now()-ft>Ud){Ke=!0;let c=un,l=Math.round((Date.now()-ft)/1e3);P("note",c?`${c} has been running for ${l}s \u2014 it may be blocked; esc cancels`:`no answer yet after ${l}s \u2014 the provider may be stalled; ctrl+c cancels`),S()}},Wd);ti.unref?.();let ni=async r=>{Ue?.(),Ue=void 0,Ce=null,fn(),tn&&us(tn,$.getSessionStats().sessionId);let s=$.getSessionStats().sessionId;Wn(s),Un(s),Po(),dt.clear(),C.clear(),Ge.clear(),await gt.dispose(),await Xt(),$=r.session,Xt=r.dispose,Or=r.session.getSessionStats().sessionId,_r=r.setCompressToolOutput,gt=new st({initial:Object.keys(ze().mcpServers),apply:async(c,l)=>{if(await pt(),c.length>0||l.length>0){let f=[];c.length>0&&f.push(`connected ${c.join(", ")}`),l.length>0&&f.push(`stopped ${l.join(", ")}`),m(c.length>0?"mcp connected":"mcp stopped",f.join("; "))}},report:c=>H(c)}),Z=0,ge="",o.items=[],o.scrollOffset=0,r.note&&o.items.push({id:"note",kind:"note",title:"note",body:r.note}),o.items.push(...Dt($.state.messages)),a.model=r.modelLabel.split("/").at(-1)||"no-model",a.setThinking($.thinkingLevel),xe(),a.percent=De($),Zt(),a.abandonAnimations(),P("tally",void 0),P("run",void 0),k.setAutocompleteProvider(new qa(xr($),e.cwd)),k.disableSubmit=!1,zr($),fn=$.subscribe(ei),S()},ri=!1,mn=r=>{if(!(ri||!r)){ri=!0;try{process.stdout.write(`
39
+ To continue this session: howtocode -c (in ${process.cwd()}) or howtocode resume ${r}
40
+ `)}catch{}}};process.on("exit",()=>mn(Or));let He=async()=>{if(Lr)return;Lr=!0,clearInterval(ti),fn(),process.on("SIGINT",()=>{});let r=(()=>{try{return $.getSessionStats().sessionId}catch{return""}})();mn(r);try{let c=xo(vo);if(c.config.hooks.SessionEnd){let{outcome:l}=await So(c.config,"SessionEnd",{hook_event_name:"SessionEnd",cwd:process.cwd(),reason:"quit"},{cwd:process.cwd()});l.error&&m("hooks",`SessionEnd hook: ${l.error}`)}}catch{}await gt.dispose();let s=$.getSessionStats().sessionId;Qt.close($.getSessionStats().cost),Wn(s),Un(s),await Xt(),i.stop(),process.stdout.write("\x1B[0m"),mn(s),process.exit(0)},ii=0,pn=async(r=!1)=>{let s=Date.now();if(!r&&s-ii<600*1e3)return;ii=s;let c=f=>{if(process.env.HOWTOCODE_CHECKIN_DEBUG==="1")try{ud(`${R}/checkin-debug.log`,`${new Date().toISOString()} ${f}
41
+ `)}catch{}},l=async()=>{try{let f=new Set((await $.modelRuntime.getAvailable()).map(T=>T.provider).filter(T=>oe(T))),y=ye.find(T=>f.has(T));if(c(`providers=${[...f].join(",")||"(none)"} target=${y??"(none)"}`),!y)return!1;let d=(await $.modelRuntime.getAuth(y))?.auth?.apiKey,p=d?.trim().match(/^\$\{?([A-Za-z_][A-Za-z0-9_]*)\}?$|^\{env:([A-Za-z_][A-Za-z0-9_]*)\}$/),w=T=>T?(process.env[T]??"").trim():"",h=p?w(p[1]??p[2])||void 0:d?.trim()||void 0;if(!h)for(let T of["HOWTOCODE_API_KEY","HOWTOCODE_VIP_API_KEY","HOWTOCODE_FREE_API_KEY"]){let I=w(T);if(I){h=I,c(`key dari fallback ${T}`);break}}if(c(`key=${h?`ada(${h.length})`:"(kosong)"}${p?" dari env":""}`),!h)return!1;let x=await pr(h);if(c(`status ok=${x.ok} enabled=${x.enabled} claimed=${x.checkedInToday} msg=${x.message}`),!x.ok||!x.enabled||x.checkedInToday)return!0;let v=await $a(h);return c(`claim ok=${v.ok} awarded=${v.quotaAwarded} msg=${v.message}`),v.ok?(m("check-in",`daily check-in claimed: +${ya(v.quotaAwarded)} credited to your howtofix.id account`),S()):v.blocked&&m("check-in",v.message),!0}catch(f){return c(`error ${f.message}`),!1}};await l()||(await new Promise(f=>setTimeout(f,4e3)),await l())},oi=async r=>{let s=Qt.check($.getSessionStats().cost);if(s!==void 0){H(`budget reached: $${s.spent.toFixed(4)} of $${s.limit.toFixed(2)} \u2014 raise it with --max-budget-usd, or start without the flag`);return}let c=$.isStreaming,l=`you-${Date.now()}`;o.items.push({id:l,kind:"user",title:"you",body:r,pending:c?!0:void 0}),c||(P("tally",void 0),ct.clear(),ln.clear(),P("run","thinking"),a.beginRun()),S(),k.disableSubmit=!1;let f=Ns(wo(r,e.cwd),Fs);nn=r,await sl(),mt=!0;let y=u.length>0?[...u]:void 0;u.length=0;let d=c?$.prompt(f,{streamingBehavior:"steer",...y?{images:y}:{}}):$.prompt(f,y?{images:y}:void 0);mt=!1,d.then(()=>pn()).catch(p=>H(p instanceof Error?p.message:String(p)))},gn=r=>{let s=r.trim();if(s){if(Vr(),X){let c=X;X=void 0,k.setText(""),c(s);return}if(k.setText(""),k.addToHistory(s),s.startsWith("!")){let c=s.slice(1).trim();if(!c)return;o.items.push({id:`sh-${Date.now()}`,kind:"tool",title:"$",body:c}),P("run","shell"),S(),$.executeBash(c,l=>{P("run",`shell \xB7 ${l.length} bytes`),S()}).then(l=>{let f=l.output.trim();o.items.push({id:`sh-out-${Date.now()}`,kind:l.exitCode===0?"result":"error",title:`exit ${l.exitCode??"?"}`,body:f||"(no output)"}),P("tally",void 0),S()}).catch(l=>H(l instanceof Error?l.message:String(l)));return}if(s.startsWith("/")){Je(s);return}oi(s)}};k.onSubmit=gn;let hn=0,we=Zs(),si=0,Ve=()=>{Vn().then(async r=>{if(r.ok){u.push({type:"image",data:r.image.data,mimeType:r.image.mimeType}),k.insertTextAtCursor(`[image ${r.image.path}]`),m("paste",`image stored at ${r.image.path}`),S();return}let s=await ws();s.ok?k.insertTextAtCursor(s.text):m("paste",s.reason),S()}).catch(r=>{m("paste",`could not read the clipboard: ${r instanceof Error?r.message:String(r)}`),S()})};n=Ve;let ai=()=>{Vn().then(r=>{r.ok&&(u.push({type:"image",data:r.image.data,mimeType:r.image.mimeType}),k.insertTextAtCursor(Qn(r.image.path)),m("paste",`image stored at ${r.image.path}`),S())}).catch(()=>{})},bl=r=>{let s=[];for(let c of r){let l=Ls(c);if(!l){s.push(Os(c));continue}try{Va(c).size<=Ms&&u.push({type:"image",data:qt(c).toString("base64"),mimeType:l})}catch{}s.push(Qn(c))}k.insertTextAtCursor(`${s.join(" ")} `),m("paste",r.length===1?`attached ${r[0]}`:`attached ${r.length} files`),S()},li=r=>Et(Ee(R).rightClickPaste)&&r.type==="press"&&r.button==="right",ci=r=>!Et(Ee(R).rightClickPaste)&&process.platform==="win32"&&r.type==="press"&&r.button==="right";i.addInputListener(r=>{if(xd(r))return{consume:!0};if(Se){if(q(r,"escape"))return rn(),{consume:!0};let l=za(),f=l.matches(r,"tui.select.up"),y=l.matches(r,"tui.select.down");if(f||y){let p=Se.getTreeList().getSelectedNode()?.entry.id,w=al(),h=p===void 0?-1:w.indexOf(p);if(f?h===0:h===w.length-1)return S(),{consume:!0}}return Se.handleInput(r),S(),{consume:!0}}if(Ce)return Vr(),q(r,"escape")||q(r,"enter")?{consume:!0}:void 0;if(ve&&G&&q(r,"escape"))return pe?(pe=!1,m("workflow","panel keys off; the editor has the keyboard")):W.expanded?(W.expanded=!1,m("workflow","collapsed the drill-in")):(Mr(),m("workflow","panel unpinned; the run is still in the transcript")),Jt(),S(),{consume:!0};if(ce)return ce.handleInput(r),S(),{consume:!0};if(q(r,"escape")){if(we.disarm())return m("connect","sign-in cancelled \u2014 run /connect again when you have a token"),S(),{consume:!0};if($.isStreaming){dn=!0;let f=[...$.getSteeringMessages()].map(y=>y.trim()).filter(Boolean);if(f.length>0){let y=k.getText().trim();k.setText(y?`${f.join(`
42
+ `)}
43
+ ${y}`:f.join(`
44
+ `));let d=new Set(f);for(let p of o.items)p.kind==="user"&&p.pending&&d.has(p.body.trim())&&(p.pending=void 0);m("queued",`${f.length} unread message${f.length===1?"":"s"} returned to the editor`)}return $.abort(),P("note","stopping"),S(),{consume:!0}}let l=Date.now();if(k.getText().length===0&&l-hn<600)return hn=0,Wr(),{consume:!0};hn=l;return}if(q(r,"ctrl+c")||ps(r)){if($.isStreaming)$.abort(),P("note","stopping"),S();else if(k.getText().length>0)k.setText(""),P("note","draft cleared; ctrl+c again quits"),S();else{let l=Date.now();l-si<2e3?He():(si=l,P("note","press ctrl+c again to quit"),S())}return{consume:!0}}if(q(r,"ctrl+d")&&k.getText().length===0)return He(),{consume:!0};let s=Math.max(1,o.viewportHeight-1);if(q(r,"pageUp"))return o.scrollOffset+=s,S(),{consume:!0};if(q(r,"pageDown"))return o.scrollOffset=Math.max(0,o.scrollOffset-s),S(),{consume:!0};if(q(r,"home"))return o.scrollOffset=Number.MAX_SAFE_INTEGER,S(),{consume:!0};if(q(r,"end"))return o.scrollOffset=0,S(),{consume:!0};let c=Rs(r);if(c!==void 0){if(Is(c))return Ve(),{consume:!0};let l=_s(c,f=>{try{return Va(f).isFile()}catch{return!1}});if(l)return bl(l),{consume:!0}}if(q(r,"ctrl+v")||q(r,"alt+v"))return Ve(),{consume:!0};if(q(r,"ctrl+l"))return o.scrollOffset=0,i.scrollToBottom(),S(),{consume:!0};if(q(r,"ctrl+e")){let l=[...o.items].reverse().find(f=>(f.full?.length??0)>0);return l?(l.expanded=l.expanded!==!0,S(),{consume:!0}):(m("expand","nothing to expand in this transcript yet"),{consume:!0})}if(q(r,"ctrl+o")&&!$.isStreaming)return o.items=[{id:"cleared",kind:"note",title:"bench",body:"screen cleared. session history is still stored."}],S(),{consume:!0};if(q(r,"ctrl+t"))return Be(oa(a.thinking)),{consume:!0};if(q(r,"ctrl+shift+t"))return Be(sa(a.thinking)),{consume:!0};if(q(r,Fa)&&ve&&G)return pe=!pe,m("workflow",pe?"panel keys active; Esc gives the keyboard back":"panel keys off; the editor has the keyboard"),Jt(),S(),{consume:!0};if(pe&&ve&&G){let l=_a(r);if(l){let f=Kn(G,Date.now());if(l==="stop")return Q?(Q(),Q=null,m("workflow","stopping the run; in-flight agents resolve as null")):m("workflow","the run has already finished"),{consume:!0};if(l==="save"){let y=Da(il,Fi);return m("workflow",y.ok?`saved ${y.path}`:y.reason),S(),{consume:!0}}return Object.assign(W,La(W,l,f)),Jt(),S(),{consume:!0}}}});let bn=r=>{let s=c=>{P("prompt",`API key for ${c}. Paste it, then press enter.`),S();let l=X;X=f=>{X=l;let y=f.trim();if(!y){P("prompt",void 0),S();return}$.modelRuntime.setRuntimeApiKey(c,y).then(()=>$.modelRuntime.login(c,"api_key",{prompt:async()=>y,notify:()=>{}}).then(()=>m("login",`saved API key for ${c}`),d=>m("login",`key set for this session, but it could not be saved (${d instanceof Error?d.message:String(d)}); run /login again after restarting`)),d=>m("login",d instanceof Error?d.message:String(d)))}};if(r){s(r);return}$.modelRuntime.getAvailable().then(c=>{let l=[...new Set(c.map(f=>f.provider))].sort();if(l.length===0){m("login","no providers are configured; pass one explicitly, e.g. /login nrimo");return}j("Login",l.map(f=>({value:f,label:f})),s)},c=>m("login",c instanceof Error?c.message:String(c)))},di=async(r,s)=>{let c=me(R,"models.json"),l,f=!1;try{l=JSON.parse(qt(c,"utf8"))}catch(ee){if(!(ee instanceof Error&&"code"in ee&&ee.code==="ENOENT"))return`could not read ${c}; the models were not added`;l={providers:{}},f=!0}(!l.providers||typeof l.providers!="object")&&(l.providers={});let y=l.providers[r];y||(y=Yi(),l.providers[r]=y,f=!0);let d=Array.isArray(y.models)?y.models:[],p=no(d,s),w=await Ji(R).catch(()=>({index:new Map})),h=new Map,x=await oo((await $.modelRuntime.getAuth(r))?.auth?.apiKey??"",{groups:h}),v=Bi(h),T=Qi(d,s,w.index,x),I=v.size>0?eo(T,w.index,x,v).models:T,N=to(I);y.models=N.models;try{yr(R,{recursive:!0}),ie(c,`${JSON.stringify(l,null,2)}
45
+ `)}catch{return`could not write ${c}; the models were not added`}let B=!1;try{await $.modelRuntime.refresh(),B=!0}catch{B=!1}let L=N.changed>0?`, repaired ${N.changed}`:"",M=B?"":"; restart the CLI to see them all",D=f?` (created ${c})`:"";return p===0?`all ${s.length} models were already configured${L}${D}${M}`:`added ${p} model(s) to "${r}"${L}${D}${M}`},qe=(r,s)=>{(async()=>{if(!r){let h=await lo({onProgress:v=>{let T="";try{let N=me(R,".howtocode");yr(N,{recursive:!0,mode:448});let B=me(N,"connect-url.txt"),L=v.kind==="browser"?[v.url]:[v.url,`code: ${v.code}`];kr(B,L.join(`
46
+ `)+`
47
+ `,{mode:384}),T=B}catch{T=""}let I=T?[` saved to ${T}`]:[];v.kind==="browser"?(Fe(v.url),m("connect",["finish signing in to howtofix.id:"," a browser window is opening \u2014 approve the sign-in there",` if it did not open, visit ${v.url}`,...I].join(`
48
+ `))):(Fe(v.url),m("connect",["finish signing in to howtofix.id:",` 1. go to ${v.url}`,` 2. enter the code: ${v.code}`," waiting\u2026",...I].join(`
49
+ `))),S()}});if(h.ok){we.disarm(),P("prompt",void 0),qe(h.token,h.credential);return}let x=await Fe(Rn);m("connect",[`browser sign-in: ${h.message}`,"","connect with a token instead:",` 1. ${x?"the keys page is opening in your browser":`open ${Rn}`}`," 2. sign in if asked, then create a key (starts with sk-)"," 3. run /connect <token>"," or /connect again, and paste the key when asked"].join(`
50
+ `)),S();return}if(!Xi(r)){m("connect","that does not look like a howtocode token; the Console issues tokens that start with sk-");return}P("note",`connecting to howtofix.id (${In(r)})`),S();let c=await St(r);if(!c.ok){P("note",void 0),m("connect",c.message),S();return}let l=await di("howtocode",c.models);await $.modelRuntime.setRuntimeApiKey("howtocode",r);let f;try{await $.modelRuntime.login("howtocode","api_key",{prompt:async()=>r,notify:()=>{}})}catch(h){f=`this sign-in could not be saved (${h instanceof Error?h.message:String(h)}); run /connect again after restarting`}s&&(po(R,s)?be=s:f=`this sign-in renews itself, but the pair could not be saved to ${co(R)}; it will expire in hours and need /connect again`);let y=!!$.model&&$.model?.provider!==void 0&&a.model!=="unknown",d,p;if(!y)try{let h=(await $.modelRuntime.getAvailable()).filter(T=>oe(T.provider)),v=It(h.map(T=>T.id)).slice(0,4);for(let T of v){if(!(await ro(T,r)).ok)continue;let N=h.find(B=>B.id===T);if(N){await $.setModel(N),a.model=N.id,xe(),d=`${N.provider}/${N.id}`;break}}d||(p=v.length>0?`none of the first ${v.length} models answered (${v[0]} did not)`:"the account lists no chat model")}catch(h){p=h instanceof Error?h.message:String(h)}P("note",void 0),pn(!0);let w=await Ie(r);if(w.ok&&!w.unlimited){let h=w.unit,x=w.remaining??0,v=h==="USD"||h==="CNY"?`$${x.toFixed(2)}`:`${x.toLocaleString()} ${h}`;a.usage=Oe(v,h,null);try{yr(pd(Xe),{recursive:!0}),ie(Xe,JSON.stringify({data:{remaining:x,limit:w.limit??0,unit:h,unlimited:!1,latencyMs:null},cachedAt:Date.now()}))}catch{}}else w.ok&&w.unlimited&&(a.usage=Oe("unlimited","",null));m("connect",[`connected ${In(r)} \u2014 ${c.message}`,l,ui("howtocode",w),d?`using ${d} (change it with /model)`:`pick a model with /model, then send a prompt${p?` (auto-select failed: ${p})`:""}`,f].filter(h=>!!h).join(`
51
+ `)),S()})().catch(c=>{P("note",void 0),m("connect",c instanceof Error?c.message:String(c)),S()})},wl=r=>{(async()=>{let s=mr(r);if(!s){m("connect",["that is not an account credential."," /connect <email>:<password>"," /connect <base64 of email:password>"].join(`
52
+ `)),S();return}P("note",`signing in as ${s.username}`),S();let{token:c}=await wa(ao,s.username,s.password,bt),l=ba(R,s.username,s.password);P("note",void 0),m("connect",[`signed in as ${s.username}`,"using the CLI key this account owns \u2014 no new key was made",l?"credential stored \u2014 /connect will not ask again":"could not store the credential, so the next connect will ask again"].join(`
53
+ `)),S(),qe(c)})().catch(s=>{P("note",void 0),m("connect",s instanceof Error?s.message:String(s)),S()})},ui=(r,s)=>{if(!s.ok)return[`${r} account`,` ${s.message}`].join(`
54
+ `);if(s.unlimited)return s.limit!==void 0&&s.used!==void 0?ur(r,s.limit,s.used,s.unit).join(`
55
+ `):[`${r} account`," quota no limit on this token"].join(`
56
+ `);if(s.limit===void 0||s.used===void 0){let c=[`${r} account`],l=f=>`${f.toFixed(2)} ${s.unit}`;return s.limit!==void 0&&c.push(` granted ${l(s.limit)}`),s.used!==void 0&&c.push(` spent ${l(s.used)}`),s.remaining!==void 0&&c.push(` remaining ${l(s.remaining)}`),c.join(`
57
+ `)}return ur(r,s.limit,s.used,s.unit).join(`
58
+ `)},ze=()=>({mcpServers:Co()}),yl=r=>{let s=Object.keys(r??{});return s.length===0?[]:s.map(c=>` mcp ${c} ${yt(r[c])}`)},kl=r=>{let s=Ri(r.dir,r.manifest),c=r.manifest.skills.join(", ");return[r.manifest.description,` category ${r.manifest.category}`,` version ${r.manifest.version}`,` skills ${c}`,r.manifest.prompt?` prompt ${r.manifest.prompt}`:" prompt (none)",` size ${s} bytes of skill text`,` source ${r.source}`,...yl(r.manifest.mcp)].join(`
59
+ `)},fi=r=>{let s=[kl(r),""];if(r.manifest.prompt){let c=me(r.dir,r.manifest.prompt);Vt(c)&&s.push(`--- ${r.manifest.prompt} ---`,qt(c,"utf8").trim(),"")}for(let c of r.manifest.skills){let l=me(r.dir,"skills",c,"SKILL.md");Vt(l)&&s.push(`--- skills/${c}/SKILL.md ---`,qt(l,"utf8").trim(),"")}return s.join(`
60
+ `)},pt=async()=>{await $.reload()},wn=!1,mi=async r=>{if(wn){m("preset","an install is already running; wait for it to finish");return}wn=!0;try{let s;try{s=await r()}catch(d){H(`preset not installed: ${d instanceof Error?d.message:String(d)}`);return}if(!s.ok||!s.name){H(`preset not installed:
61
+ ${s.problems.join(`
62
+ `)}`);return}await pt();let c=se(e.cwd).entries.find(d=>d.manifest.name===s.name),l=c?.manifest.integrates||c?.manifest.mcp,f=l?`
63
+ integration disabled by default; run /preset enable ${s.name} when you want to use it`:await pi(s.name);l&&c&&kr(me(c.dir,".disabled"),`installed
64
+ `);let y=s.modelInvocable===!1?`its skill ${s.skill} is invoke-only (disable-model-invocation): the model cannot choose it, run /skill:${s.skill} yourself`:"its skill is in the model's catalogue from the next message";m("preset",`installed ${s.name} into ${s.target}
65
+ ${y}${f}`)}catch(s){H(`preset installed but the session could not be refreshed: ${s instanceof Error?s.message:String(s)}`)}finally{wn=!1}},gt=new st({initial:Object.keys(ze().mcpServers),apply:async(r,s)=>{if(await pt(),r.length>0||s.length>0){let c=[];r.length>0&&c.push(`connected ${r.join(", ")}`),s.length>0&&c.push(`stopped ${s.join(", ")}`),m(r.length>0?"mcp connected":"mcp stopped",c.join("; "))}},report:r=>H(r)}),Ye=async()=>{let r=Object.keys(ze().mcpServers);return await gt.reconcile(r)},pi=async r=>{let{entries:s}=se(e.cwd),l=s.find(d=>d.manifest.name===r)?.manifest.mcp;if(!l||Object.keys(l).length===0)return"";let f=vn(l);if(f.problems.length>0)return`
66
+ MCP: ${f.problems.join("; ")}`;let y=[];if(f.added.length>0){let d=await Ye(),p=f.added.filter(w=>d.added.includes(w));y.push(p.length>0?`MCP servers connected: ${p.join(", ")}`:`MCP servers added to mcp.json: ${f.added.join(", ")}`)}return f.skipped.length>0&&y.push(`MCP servers kept as they were (already configured): ${f.skipped.join(", ")}`),y.length>0?`
67
+ ${y.join(`
68
+ `)}`:""},gi=r=>mi(async()=>_i(r,$t(e.cwd))),hi=r=>{let s=r.sizeKb>=1024?`${(r.sizeKb/1024).toFixed(1)} MB`:`${r.sizeKb} KB`;return m("preset",[`downloading ${r.title}`,` from ${r.repo} @ ${r.sha.slice(0,7)}`,` skill ${r.skill}${r.modelInvocable===!1?" (invoke-only: the model cannot choose it)":""}`,` size ~${s} \xB7 ${r.license}`," checking the pinned commit and the contents the registry recorded\u2026"].join(`
69
+ `)),mi(()=>Ni(r,$t(e.cwd)))},yn=(r,s)=>{j(s,r.map(c=>({value:c.name,label:c.title,description:c.description})),c=>{let l=r.find(y=>y.name===c);if(!l)return;let f=l.sizeKb>=1024?`${(l.sizeKb/1024).toFixed(1)} MB`:`${l.sizeKb} KB`;j(l.title,[{value:"install",label:"Install",description:`download ~${f} and add its skill to this project`},{value:"view",label:"View contents",description:"read what it contains before downloading"},{value:"back",label:"Back",description:"return to the menu"}],y=>{if(y==="install"){hi(l);return}if(y==="view"){m(`preset ${l.name}`,[`${l.description}`,"",`skill ${l.skill}`,`source ${l.repo} @ ${l.sha.slice(0,7)}`,`licence ${l.license}`,`size ~${f}`,`category ${l.category}`,`model ${l.modelInvocable===!1?"invoke-only \u2014 the model cannot choose it, only /skill:"+l.skill:"the model can choose it from its catalogue"}`,"","Install downloads the skill and adds it to this project."].join(`
70
+ `));return}wi()})},()=>S())},Re=(r,s)=>{j(s,r.map(c=>({value:c.manifest.name,label:c.manifest.title,description:c.manifest.skills.length>0?`${c.manifest.skills.join(", ")} \u2014 ${c.manifest.description}`:c.manifest.description})),c=>{let l=r.find(f=>f.manifest.name===c);l&&j(l.manifest.title,[{value:"install",label:"Install",description:"add its skills and rules to this project"},{value:"view",label:"View contents",description:"read the skills and prompt first"},{value:"back",label:"Back",description:"return to the menu"}],f=>{if(f==="install"){gi(l.dir);return}if(f==="view"){m(`preset ${l.manifest.name}`,fi(l));return}$i("")})},()=>S())},bi=r=>r.filter(s=>s.manifest.integrates!==void 0),$l=()=>{let{entries:r}=se(e.cwd),s=bi(r);if(s.length===0){m("integrations","nothing installed that drives another application. /preset lists the rest.");return}Re(s,"Integrations")},wi=()=>{let{entries:r}=se(e.cwd),s=[{value:"skills",label:"Skills",description:"bundles of skills and prompt text, installed into the project"},{value:"mcp",label:"MCP",description:"Model Context Protocol servers, added to mcp.json"}],c=bi(r).length;c>0&&s.push({value:"integrations",label:"Integrations",description:`${c} that drive another application, and need setup there first`}),j("Presets",s,l=>l==="mcp"?kn():l==="integrations"?$l():vl())},kn=()=>{let{entries:r,problems:s}=xi();if(s.length>0&&m("mcp problems",s.join(`
71
+ `)),r.length===0){m("mcp catalogue","no servers in the catalogue. run /mcp to inspect the ones already configured.");return}let c=new Set(Object.keys(ze().mcpServers)),l=new Map,f=[];for(let y of Si(r)){let d=Ci(r,y);l.set(y,()=>yi(d,y));let p=d.filter(w=>c.has(w.name)).length;f.push({value:y,label:y,description:`${d.map(w=>w.title).join(", ")}${p>0?` \xB7 ${p} configured`:""}`})}l.set("all-mcp",()=>yi(r,"All MCP servers")),f.push({value:"all-mcp",label:"All servers",description:`${r.length} available${c.size>0?`, ${c.size} already configured`:""}`}),j("MCP servers",f,y=>l.get(y)?.())},yi=(r,s)=>{let c=ze().mcpServers;j(s,r.map(l=>{let f=c[l.name]!==void 0?"configured \xB7 ":"";return{value:l.name,label:l.title,description:`${f}${l.description}`}}),l=>{let f=Ai(r,l);if(!f)return;let y=c[f.name]!==void 0,d=Ti(f),p=[f.description,"",`server ${f.name}`,`runs ${yt(kt(f))}`,...f.needs&&f.needs.length>0?[`needs ${f.needs.join(", ")}`,d.length>0?` ${d.join(", ")} ${d.length===1?"is":"are"} not set in this shell \u2014 the value is read at connect time, so export it before the next session`:" all set in this shell"]:[],...f.docs?[`docs ${f.docs}`]:[],"",y?"already in mcp.json \u2014 removing it takes the entry out; nothing else changes":"install writes this server into mcp.json. nothing is downloaded, and it connects on the next session"].join(`
72
+ `),w=y?[{value:"remove",label:"Remove",description:"take the server out of mcp.json"},{value:"view",label:"Details",description:"what it runs and what it needs"},{value:"back",label:"Back",description:"return to the list"}]:[{value:"install",label:"Install",description:"add the server to mcp.json"},{value:"view",label:"Details",description:"what it runs and what it needs"},{value:"back",label:"Back",description:"return to the list"}];j(f.title,w,h=>{if(h==="view"){m(`mcp ${f.name}`,p);return}if(h==="install"){let x=[];if(f.preset){let I=me(Ei(),"mcp",f.preset.replace(/^mcp-/,""));if(Vt(me(I,"preset.json"))){let N=Ii(I,$t(e.cwd));N.ok||x.push(...N.problems)}}let v=vn({[f.name]:kt(f)});if(x.push(...v.problems),x.length>0){H(`mcp not installed:
73
+ ${x.join(`
74
+ `)}`);return}if(v.skipped.length>0){m("mcp install",`${f.name} is already in mcp.json; it was left as it is.`);return}let T=d.length>0?`
75
+ ${d.join(", ")} ${d.length===1?"is":"are"} not set in this shell \u2014 the value is read when the server connects, so export ${d.length===1?"it":"them"} and reload, or it will fail every call`:"";m("mcp installed",[`added ${f.name} to mcp.json${f.preset?" and installed its skill preset":""}`,` runs ${yt(kt(f))}`,` connecting now; /mcp shows its state and its tools${T}`].join(`
76
+ `)),Ye().catch(I=>{H(`mcp installed but the session was not updated: ${I instanceof Error?I.message:String(I)}`)});return}if(h==="remove"){let x=wt([f.name]);if(x.problems.length>0){H(`mcp not removed:
77
+ ${x.problems.join(`
78
+ `)}`);return}Ye().then(v=>{m("mcp remove",v.removed.length>0?`removed ${v.removed.join(", ")} from mcp.json and stopped ${v.removed.length===1?"it":"them"}`:x.removed.length>0?`removed ${f.name} from mcp.json`:`${f.name} was not in mcp.json`)}).catch(v=>{H(`mcp removed from config but the session was not updated: ${v instanceof Error?v.message:String(v)}`)});return}kn()})},()=>kn())},vl=()=>{let{entries:r,problems:s}=se(e.cwd),{entries:c,problems:l}=vt();s.length>0&&m("preset problems",s.join(`
79
+ `)),l.length>0&&m("preset problems",l.join(`
80
+ `));let f=r.filter(p=>p.source==="installed"),y=new Map,d=[];f.length>0&&(y.set("installed",()=>Re(f,"Installed presets")),d.push({value:"installed",label:"Installed",description:`${f.length} active`}));for(let p of Pi(r)){let w=Mi(r,p),h=Sn(c,p);y.set(p,()=>h.length>0?ki(w,p,h):Re(w,p));let x=w.map(v=>`${v.manifest.title} (${v.manifest.skills.join(", ")})`).join(", ");d.push({value:p,label:p,description:`${x}${h.length>0?` \xB7 ${h.length} more to download`:""}`})}for(let p of Oi(c)){if(r.some(h=>h.manifest.category===p))continue;let w=Sn(c,p);y.set(p,()=>yn(w,p)),d.push({value:p,label:p,description:`${w.length} to download`})}if(y.set("all",()=>Re(r,"All presets")),d.push({value:"all",label:"All presets",description:`${r.length} ready to install`}),c.length>0){y.set("hub",()=>ki([],"Community presets",c));let p=new Set(c.map(w=>w.repo)).size;d.push({value:"hub",label:"Community",description:`${c.length} to download, from ${p} projects`})}j("Skill presets",d,p=>y.get(p)?.())},ki=(r,s,c)=>{if(c.length===0){Re(r,s);return}if(r.length===0){yn(c,`${s} (download)`);return}j(s,[{value:"local",label:`Included (${r.length})`,description:"already on disk, no download"},{value:"hub",label:`Downloadable (${c.length})`,description:"fetched when installed"}],l=>l==="local"?Re(r,s):yn(c,s))},$i=r=>{let[s,...c]=r.trim().split(/\s+/),l=c.join(" ").trim();if(!s){wi();return}if(s==="list"){let{entries:f}=se(e.cwd),y=f.filter(d=>d.source==="installed");if(y.length===0){m("preset list","nothing installed. run /preset to browse the catalogue.");return}m("preset list",y.map(d=>`${d.manifest.name} ${d.manifest.version} [${xn(d.dir)?"disabled":"active"}]
81
+ ${d.manifest.description}
82
+ ${d.dir}`).join(`
83
+ `));return}if(s==="show"){if(!l){m("preset show","usage: /preset show <name>");return}let{entries:f}=se(e.cwd),y=f.find(h=>h.manifest.name===l);if(y){m(`preset ${l}`,fi(y));return}let{entries:d}=vt(),p=Cn(d,l);if(!p){m("preset show",`no preset named "${l}". run /preset to list them.`);return}let w=p.sizeKb>=1024?`${(p.sizeKb/1024).toFixed(1)} MB`:`${p.sizeKb} KB`;m(`preset ${l}`,[p.description,"",`skill ${p.skill}`,`source ${p.repo} @ ${p.sha.slice(0,7)}`,`licence ${p.license}`,`size ~${w}`,`category ${p.category}`,"","not installed. install it from /preset, or: /preset add-hub "+p.name].join(`
84
+ `));return}if(s==="add"){if(!l){m("preset add","usage: /preset add <git-url | directory>");return}gi(l);return}if(s==="add-hub"){if(!l){m("preset add-hub","usage: /preset add-hub <name> (see /preset for names)");return}let{entries:f}=vt(),y=Cn(f,l);if(!y){m("preset add-hub",`"${l}" is not in the community registry. run /preset to browse it.`);return}hi(y);return}if(s==="enable"||s==="disable"){if(!l){m(`preset ${s}`,`usage: /preset ${s} <name>`);return}let f=se(e.cwd).entries.find(d=>d.manifest.name===l&&d.source==="installed");if(!f){m(`preset ${s}`,`no installed preset named "${l}"`);return}let y=me(f.dir,".disabled");if(s==="disable"){kr(y,`disabled
85
+ `);let d=f.manifest.mcp?wt(Object.keys(f.manifest.mcp)):{removed:[],kept:[],problems:[]};Ye().then(()=>m("preset",`disabled ${l}${d.removed.length?`; stopped ${d.removed.join(", ")}`:""}`)).catch(p=>H(`preset disable failed: ${p instanceof Error?p.message:String(p)}`));return}fd(y,{force:!0}),pi(l).then(d=>pt().then(()=>m("preset",`enabled ${l}${d}`))).catch(d=>H(`preset enable failed: ${d instanceof Error?d.message:String(d)}`));return}if(s==="remove"){if(!l){m("preset remove","usage: /preset remove <name>");return}let f=Li(l,e.cwd);if(f.problems.length>0){m("preset remove",f.problems.join(`
86
+ `));return}let d=se(e.cwd).entries.find(v=>v.manifest.name===l),p=new Set;for(let v of se(e.cwd).entries)if(v.manifest.name!==l)for(let T of Object.keys(v.manifest.mcp??{}))p.add(T);let w=d?.manifest.mcp?wt(Object.keys(d.manifest.mcp),p):{removed:[],kept:[],problems:[]},h=w.removed.length>0?`
87
+ MCP servers removed from mcp.json: ${w.removed.join(", ")}`:w.kept.length>0?`
88
+ MCP servers kept (still used by another preset): ${w.kept.join(", ")}`:"",x=w.problems.length>0?`
89
+ MCP: ${w.problems.join("; ")}`:"";Ye().then(()=>{m("preset",`removed ${l}
90
+ ${f.removed.join(`
91
+ `)}${h}${x}`)}).catch(v=>H(`preset remove failed: ${v instanceof Error?v.message:String(v)}`));return}m("preset",`unknown subcommand "${s}". try: list, show, add, add-hub, remove.`)},Je=async r=>{let[s,...c]=r.slice(1).split(/\s+/),l=c.join(" ");if(s==="quit"||s==="exit"){He();return}if(s==="help"){m("help",xr($).map(d=>`/${d.name} ${d.description??""}`).join(`
92
+ `));return}if(s==="trust"){let d=new bd(R),p=d.get(e.cwd);if(l==="on"||l==="off"){let h=l==="on";d.set(e.cwd,h),m("trust",h?`trusted ${e.cwd}
93
+ its .hxf settings, SYSTEM.md and skills apply to the next session`:`no longer trusting ${e.cwd}
94
+ its .hxf settings, SYSTEM.md and skills are ignored`);return}let w=p===!0?"trusted":p===!1?"not trusted":"not decided (treated as not trusted)";m("trust",`${e.cwd}
95
+ ${w}
96
+
97
+ /trust on trust this folder
98
+ /trust off stop trusting it`);return}if(s==="init"){let d=me(e.cwd,"AGENTS.md");if(Vt(d)&&l!=="force"){m("init",`AGENTS.md already exists at ${d}. run /init force to overwrite.`);return}ie(d,vi),m("init",`wrote ${d}; asking the agent to fill it in`),await $.prompt("Read AGENTS.md, then fill it in with the real build, test, and layout facts of this repo. Keep it short.");return}if(s==="login"){bn(l);return}if(s==="vault"){let[d="list",...p]=l.trim().split(/\s+/).filter(Boolean),w=x=>x instanceof te||x instanceof Error?x.message:String(x),h=(x,v)=>{P("prompt",`${x} (not echoed, then press enter)`),S();let T=X,I=()=>{X=T,P("prompt",void 0)};we.arm(I),X=N=>{we.disarm(),I(),v(N.trim())}};if(d==="init"||d==="create"){if(fe.exists(R)){m("vault","a vault already exists \u2014 /vault unlock, or /vault destroy first");return}h("choose a master password (at least 8 characters)",x=>{if(x.length<8){m("vault","the master password must be at least 8 characters");return}h("type it again to confirm",v=>{if(x!==v){m("vault","the two passwords did not match; nothing was created");return}try{ne=fe.create(R,x),m("vault",`vault created at ${je(R)}
99
+ there is no recovery: lose the password and the vault is gone`)}catch(T){m("vault",w(T))}})});return}if(d==="unlock"){if(!fe.exists(R)){m("vault","no vault yet \u2014 /vault init");return}h("master password",x=>{try{ne=fe.unlock(R,x),m("vault",`unlocked \u2014 ${ne.list().length} credential(s)`)}catch(v){m("vault",w(v))}});return}if(d==="lock"){if(!ne){m("vault","the vault is already locked");return}ne.lock(),ne=void 0,m("vault","locked; the key is no longer in memory");return}if(d==="destroy"){if(!fe.exists(R)){m("vault","no vault to destroy");return}if(p.join(" ")!=="--yes"){m("vault","this deletes every stored credential. run /vault destroy --yes to confirm");return}ne?.lock(),ne=void 0,Ha(R),m("vault","vault destroyed");return}if(!ne){m("vault",fe.exists(R)?"the vault is locked \u2014 /vault unlock":"no vault yet \u2014 /vault init");return}if(d==="list"||d==="ls"){let x=ne.list();if(x.length===0){m("vault","the vault holds nothing yet \u2014 /vault add <name> <platform>");return}m("vault",x.map(v=>{let T=v.account?` as ${v.account}`:"";return`${v.name} ${v.platform}${T} ${v.hint}`}).join(`
100
+ `));return}if(d==="add"){let[x,v,T]=p;if(!x||!v){m("vault","usage: /vault add <name> <platform> [account] \u2014 then paste the value");return}P("prompt",`paste the value for ${x} (not echoed), then press enter`),S();let I=X,N=()=>{X=I,P("prompt",void 0)};we.arm(N),X=B=>{we.disarm(),N();let L=B.trim();if(!L){m("vault","no value given; nothing was stored");return}try{ne.put({name:x,platform:v,...T?{account:T}:{},value:L}),m("vault",`stored ${x} (${v})${T?` as ${T}`:""}`)}catch(M){m("vault",w(M))}};return}if(d==="rm"||d==="remove"){let x=p[0];if(!x){m("vault","usage: /vault rm <name>");return}m("vault",ne.remove(x)?`removed ${x}`:`no credential named ${x}`);return}if(d==="passwd"||d==="password"){h("current master password",x=>{let v;try{v=fe.unlock(R,x)}catch(T){m("vault",w(T));return}h("new master password (at least 8 characters)",T=>{if(T.length<8){m("vault","the master password must be at least 8 characters");return}try{v.changePassword(T),ne?.lock(),ne=v,m("vault","master password changed")}catch(I){m("vault",w(I))}})});return}m("vault",`unknown subcommand "${d}". try: init, unlock, list, add, rm, passwd, lock, destroy`);return}if(s==="connect"){let d=Qs(l,w=>!!mr(w));if(d.kind==="credential"){wl(d.credential);return}if(d.kind==="token"){qe(d.token);return}qe(""),P("prompt",ea),S();let p=X;we.arm(()=>{X=p,P("prompt",void 0)}),X=w=>{we.disarm(),qe(w.trim())};return}if(s==="sync"){let d=new Set((await $.modelRuntime.getAvailable()).map(I=>I.provider).filter(I=>oe(I))),p=ye.find(I=>d.has(I));if(!p){m("sync","no howtofix.id account is connected; run /connect first");return}P("note",`re-syncing ${p} from howtofix.id`),S();let h=(await $.modelRuntime.getAuth(p))?.auth?.apiKey;if(!h){P("note",void 0),m("sync",`${p} has no usable key; run /connect to sign in again`),S();return}let x=await St(h);if(!x.ok){P("note",void 0),m("sync",x.message),S();return}let v=await di(p,x.models),T=await Ie(h);P("note",void 0),m("sync",`${v}
101
+ ${ui(p,T)}`),await $.modelRuntime.refresh(),S();return}if(s==="usage"){let d=new Set((await $.modelRuntime.getAvailable()).map(B=>B.provider).filter(B=>oe(B))),p=ye.find(B=>d.has(B));if(!p){m("usage","no howtofix.id account is connected; run /connect first");return}P("note","asking howtofix.id for the account usage"),S();let h=(await $.modelRuntime.getAuth(p))?.auth?.apiKey;if(!h){P("note",void 0),m("usage",`${p} has no usable key; run /connect to sign in again`),S();return}let[x,v,T]=await Promise.all([Ie(h),pr(h),Zi(h)]);P("note",void 0);let I=$.getSessionStats?.(),N=Sa({provider:p,usage:x,pools:T,checkin:v,sessionStats:I});ml("usage",N.split(`
102
+ `));return}if(s==="wallet"){let d=await Fe(xt);m("wallet",d?`the Wallet is opening in your browser \u2014 top up Pro Credit there to use the VIP lane. ${xt}`:`open ${xt} to top up Pro Credit, which the VIP lane is billed from.`),S();return}if(s==="logout"){let d=await $.modelRuntime.getAvailable(),p=[...new Set(d.map(w=>w.provider))].sort();if(p.length===0){m("logout","no providers are configured");return}j("Logout",p.map(w=>({value:w,label:w})),w=>{$.modelRuntime.logout(w).then(()=>m("logout",`logged out ${w}`),h=>m("logout",h instanceof Error?h.message:String(h)))});return}if(s==="providers"){let d=await $.modelRuntime.getAvailable(),p=[...new Set(d.map(w=>w.provider))].sort();p.sort((w,h)=>Number(oe(h))-Number(oe(w))),j("Providers",p.map(w=>({value:w,label:w})),w=>{let h=$.modelRuntime.getModels(w);if(h.length===0){bn(w);return}j(w,h.map(x=>({value:x.id,label:x.id})),x=>{let v=h.find(T=>T.id===x);v&&$.setModel(v,{persist:!0}).then(()=>{a.model=v.id,xe(),m("providers",`${w}/${v.id}`)},()=>bn(w))})});return}if(s==="name"){if(!l){m("name","usage: /name <session name>");return}$.setSessionName(l),m("name",`session name: ${l}`);return}if(s==="update"){P("note","checking for a newer release");try{await Br({current:bt,install:!0})}finally{P("note",void 0)}return}if(s==="stats"){let d=$.getSessionStats(),p=$.getContextUsage(),w=v=>Number.isFinite(v)?String(v):";",h=hs($.sessionManager.getEntries()),x=h.hitRate===null?"cache hit rate unknown (no prompt billed yet)":`cache hit ${h.hitRate.toFixed(1)}% of ${h.cachedTokens+h.billedTokens} prompt tokens`;m("stats",[`session ${d.sessionId}`,d.sessionFile?`file ${d.sessionFile}`:"not persisted",`messages ${w(d.totalMessages)} (user ${w(d.userMessages)}, assistant ${w(d.assistantMessages)}, tools ${w(d.toolCalls)})`,`tokens in ${w(d.tokens.input)} out ${w(d.tokens.output)} cache ${w(d.tokens.cacheRead)}/${w(d.tokens.cacheWrite)}`,x,h.misses.length>0?`cache misses ${h.misses.length} (${w(h.missedTokens)} tokens re-billed) \u2014 last: ${bs(h.misses[h.misses.length-1])}`:"cache misses none counted",`cost $${Number.isFinite(d.cost)?d.cost.toFixed(4):";"}`,p?`context ${p.percent===null||!Number.isFinite(p.percent)?"?":`${Math.round(p.percent)}%`} of ${p.contextWindow}`:"context unknown"].join(`
103
+ `));return}if(s==="diff"){let d=async v=>{try{let{stdout:T}=await Cr("git",v,{cwd:e.cwd,encoding:"utf8"});return T.trim()}catch{return""}},p=await d(["diff","--stat"])+`
104
+
105
+ `+await d(["diff","--","."]),[w="",h=""]=p.split(`
106
+
107
+ `,2),x=Jo(h);m("diff",[w.trim(),x].filter(Boolean).join(`
108
+
109
+ `)||"working tree clean");return}if(s==="copy"){let d=[...$.state.messages].reverse().find(h=>h.role==="assistant"),w=(Array.isArray(d?.content)?d.content:[]).filter(h=>h.type==="text").map(h=>h.text).join("");if(!w){m("copy","nothing to copy");return}try{await hd(w),m("copy",`copied ${w.length} characters`)}catch(h){m("copy",h instanceof Error?h.message:String(h))}return}if(s==="export"){let d=o.items.filter(h=>h.body.trim().length>0);if(d.length===0){m("export","nothing to export yet; the transcript is empty");return}let p=gd(e.cwd,l||`howtocode-session-${Date.now()}.md`),w=[`# ${$n} session`,"",`model ${a.model}`,""];for(let h of d)w.push(`## ${h.title||h.kind}`,"",h.body,"");try{ie(p,w.join(`
110
+ `))}catch(h){m("export",`could not write ${p}: ${h instanceof Error?h.message:String(h)}`);return}m("export",`wrote ${p}`);return}if(s==="agents"){let[d="",...p]=l.split(/\s+/).filter(Boolean),w=p.join(" ").trim();if(d&&w){m("agents",await Go(d,w));return}m("agents",d?Ko(d):Bo());return}if(s==="new"){let d=await e.reopen({noSession:!1});await ni(d),m("new","started a new session");return}if(s==="resume"){let d=await wd.list(e.cwd);if(d.length===0){m("resume","no saved sessions for this folder");return}j("Resume session",d.slice(0,30).map(p=>({value:p.path,label:p.name||`${p.id.slice(0,8)} ${p.firstMessage.slice(0,40)}`,description:`${p.modified.toISOString().slice(0,16)} ${p.messageCount} messages`})),p=>{e.reopen({sessionPath:p}).then(ni).catch(w=>H(w instanceof Error?w.message:String(w)))});return}if(s==="model"){let d=await $.modelRuntime.getAvailable(),p=d.filter(v=>oe(v.provider)),w=zi(R),h=p.length>0?p:w.size>0?d.filter(v=>w.has(v.provider)):[];if(h.length===0){m("model","no model configured yet \u2014 run /connect to sign in first");return}let x=l?h.find(v=>`${v.provider}/${v.id}`===l||v.id===l):void 0;if(!l){let v=h.find(L=>oe(L.provider))?.provider??ye[0],T=Hi(An),I=T?new Set(T.ids):void 0;if(!I){let L=(await $.modelRuntime.getAuth(v))?.auth?.apiKey;if(L){let M=await St(L);M.ok&&(I=new Set(M.models),Gi(An,M.models))}}let N=Ki(R),B=L=>oe(L.provider)?I&&!I.has(L.id)?"not on your account's plan":Ui(N.get(L.id)??[]):"";j("Select model",h.map(L=>({value:`${L.provider}/${L.id}`,label:L.id,description:[Ca(L),L.provider,B(L)].filter(Boolean).join(" \xB7 ")})),L=>{let M=h.find(D=>`${D.provider}/${D.id}`===L);M&&$.setModel(M,{persist:!0}).then(()=>{a.model=M.id,xe();let D=B(M);m("model",D?`model ${L} \u2014 ${D}; the gateway will refuse it, and /model picks one it accepts`:`model ${L}`)})});return}if(!x){m("model",`unknown model ${l}`);return}await $.setModel(x,{persist:!0}),a.model=x.id,xe(),m("model",`model ${x.provider}/${x.id}`);return}if(s==="thinking"){if(!l){j("Thinking level",z.map(d=>({value:d,label:d})),d=>Be(d));return}if(!z.includes(l)){m("thinking",`thinking: ${z.join(", ")}`);return}Be(l);return}if(s==="rtk"){let d=Ee(R).compressToolOutput;if(!l){m("rtk",`compress tool output: ${d?"on":"off"}
111
+ /rtk on | /rtk off`);return}let p=l.toLowerCase();if(p!=="on"&&p!=="off"){m("rtk","rtk: on | off");return}let w=p==="on";if(w===d){m("rtk",`already ${p}`);return}if(!Ze(R,"compressToolOutput",w)){m("rtk","could not write the setting");return}_r(w),m("rtk",`compress tool output ${p}
112
+ long results are ${w?"summarised before the model reads them":"sent in full"}`);return}if(s==="compact"){try{await $.compact(l||void 0),m("compact","session compacted")}catch(d){m("compact",d instanceof Error?d.message:String(d))}return}if(s==="approval"){let d=p=>{ko(p),m("approval",On[p])};if(!l){j("Approval mode",Tt.map(p=>({value:p,label:p,description:On[p]})),p=>d(p));return}if(!Tt.includes(l)){m("approval",`modes: ${Tt.join(", ")}`);return}d(l);return}if(s==="settings"){let d=()=>Fn()?"off \u2014 everything runs":"on \u2014 critical commands are refused",p=()=>{j("Permission checks",[{value:"on",label:"on",description:"refuse critical commands and repeated calls (the default)"},{value:"off",label:"off",description:"run everything without asking \u2014 for unattended runs"}],M=>{let D=M==="off",ee=Ze(R,"skipPermissions",D);if(Nn(D),a.skipPermissions=D,S(),!ee){m("settings","changed for this session, but settings.json could not be written (is it valid JSON?)");return}m("settings",D?"permission checks are OFF \u2014 critical commands and the repeat guard will not stop anything. Stored for future sessions.":"permission checks are ON \u2014 critical commands and repeated calls are refused again.")},void 0,!1,[`Currently ${d()}.`])},w=()=>{j("Thinking level",z.map(M=>({value:M,label:M,description:M===a.thinking?"current":void 0})),M=>Be(M),void 0,!1,[`Currently ${a.thinking}.`])},h=()=>{j("Auto-update",[{value:"on",label:"on",description:"install a newer release on start (the default)"},{value:"off",label:"off",description:"stay on this version until you update by hand"}],M=>{let D=M!=="off",ee=Ze(R,"autoUpdate",D);m("settings",ee?`auto-update ${D?"on":"off"} \u2014 takes effect on the next start.`:"auto-update changed for this session, but settings.json could not be written (is it valid JSON?)")},void 0,!1,[`Currently ${bo(`${R}/settings.json`)?"on":"off"}.`])},x=()=>{let M=Qe("status",e.cwd,$.getSessionStats().sessionId);j("Dynamic context pruning",[{value:"on",label:"on",description:"fold stale ranges so long sessions stay affordable"},{value:"off",label:"off",description:"send the full transcript, unpruned"},{value:"status",label:"status",description:"what it has pruned so far"}],D=>m("dcp",Qe(D,e.cwd,$.getSessionStats().sessionId)),void 0,!1,M.split(`
113
+ `).slice(0,2))},v=()=>{Je("/model")},T=()=>{Je("/proxy")},I=()=>{let M=Ee(R).rightClickPaste,D=process.platform==="win32"?"off":"on";j("Right click",[{value:"auto",label:"auto",description:`follow the terminal (${D} on ${process.platform})`},{value:"on",label:"on",description:"the CLI pastes the clipboard itself"},{value:"off",label:"off",description:"the terminal handles it, or the click does nothing"}],ee=>{let ht=Ao(R,ee);m("settings",ht?ee==="auto"?`right click follows the terminal \u2014 ${Et("auto")?"the CLI pastes":"the terminal pastes"} here.`:`right click ${ee==="on"?"pastes from the CLI":"is left to the terminal"}.`:"right click changed for this session, but settings.json could not be written (is it valid JSON?)")},void 0,!1,[`Currently ${M}.`])},N=()=>{let M=[1,2,3,4].map(D=>({value:String(D),label:String(D),description:D===1?"one child at a time":D===et()?"current \u2014 sized to this machine":`${D} children at once`}));j("Agent concurrency",[{value:"auto",label:"auto",description:`size it to the machine (now ${et()}, max ${Do})`},...M],D=>{let ee=D==="auto"?void 0:Number(D),ht=To(R,ee);m("settings",ht?ee===void 0?`agent concurrency follows the machine \u2014 ${et()} at a time.`:`agent concurrency set to ${ee} \u2014 shared by task and workflow.`:"agent concurrency changed for this session, but settings.json could not be written (is it valid JSON?)"),S()},void 0,!1)},B=[{value:"permissions",label:"permissions",description:d()},{value:"thinking",label:"thinking",description:`${a.thinking} \u2014 how hard the model reasons`},{value:"model",label:"model",description:a.model},{value:"dcp",label:"context pruning",description:"fold stale ranges to save tokens"},{value:"proxy",label:"proxy",description:_n(R)??Ln()??"none \u2014 direct to the API"},{value:"rightclick",label:"right click",description:`paste: ${Ee(R).rightClickPaste}`},{value:"agents",label:"agents",description:`${Ee(R).agents??`auto (${et()})`} at once, shared by task and workflow`},{value:"autoupdate",label:"auto-update",description:"install a newer release on start"}];if(!l){j("Settings",B,M=>{M==="permissions"?p():M==="thinking"?w():M==="dcp"?x():M==="autoupdate"?h():M==="model"?v():M==="proxy"?T():M==="rightclick"?I():M==="agents"&&N()});return}let L=B.find(M=>M.value===l||M.label===l);if(L){L.value==="permissions"?p():L.value==="thinking"?w():L.value==="dcp"?x():L.value==="autoupdate"?h():L.value==="model"?v():L.value==="proxy"?T():L.value==="rightclick"?I():L.value==="agents"&&N();return}if(l==="on"||l==="off"){let M=l==="off",D=Ze(R,"skipPermissions",M);Nn(M),a.skipPermissions=M,S(),m("settings",D?M?"permission checks are OFF \u2014 critical commands and the repeat guard will not stop anything.":"permission checks are ON.":"changed for this session, but settings.json could not be written (is it valid JSON?)");return}m("settings",`settings: ${B.map(M=>M.value).join(", ")} | on, off (permission checks)
114
+ usage: /settings <name>, or /settings to choose`);return}if(s==="browser-relay"){if((l.trim()||"status")==="install"){try{let h=rs();m("browser-relay",`extension written to ${h.extensionDir}
115
+ files: ${h.wrote.length?h.wrote.join(", "):"already up to date"}
116
+
117
+ 1. Open chrome://extensions, enable Developer mode
118
+ 2. Load unpacked, then choose the folder above
119
+ 3. Open the extension options and set port ${Gn}
120
+ 4. Paste the relay token from ${h.tokenPath}
121
+
122
+ Then use the browser tool. /browser-relay status confirms the connection.`)}catch(h){m("browser-relay",`install failed: ${h instanceof Error?h.message:String(h)}`)}return}let p=await is(),w=p.state;m("browser-relay",`installed: ${p.tokenConfigured?"yes":"no \u2014 run /browser-relay install"}
123
+ extension dir: ${p.extensionDir}
124
+ relay running: ${p.running?`yes (127.0.0.1:${w?.port??Gn})`:"no (starts on the first browser tool call)"}
125
+ extension: ${w?.extensionConnected?"connected":"not connected"}
126
+ tabs: ${w?.tabs.length??0}
127
+
128
+ usage: /browser-relay install write the Chrome extension + token
129
+ /browser-relay status show this state`);return}if(s==="proxy"){let d=_n(R),p=Ln(),w=()=>d?`proxy: ${d} (set here, in settings.json)`:p?`proxy: ${p} (from the environment, not this file)`:"proxy: none \u2014 requests go straight to the API";if(!l){m("proxy",`${w()}
130
+ usage: /proxy <url> route requests through a proxy
131
+ /proxy off stop using one
132
+ /proxy env use HTTPS_PROXY / HTTP_PROXY / ALL_PROXY
133
+ Only traffic to the HowToCode API goes through it; a change applies on the next start.`);return}let h=l.trim();if(h==="off"||h==="none"){let I=Pt(R,Ct,""),N=At(R),B=N.source==="env"?`the environment still sets one (${N.url})`:"requests go straight to the API";m("proxy",I?`proxy off \u2014 ${B} from the next message.`:"proxy changed for this session, but settings.json could not be written (is it valid JSON?)");return}if(h==="env"){let I=Pt(R,Ct,""),N=At(R),B=N.source==="env"?N.url:void 0;m("proxy",I?B?`using the environment from the next message: ${B}`:"settings cleared, but no HTTPS_PROXY / HTTP_PROXY / ALL_PROXY is set \u2014 requests go straight to the API.":"settings.json could not be written (is it valid JSON?)");return}let x=ho(h);if(!x.ok){m("proxy",`not set: ${x.problem}`);return}if(!Pt(R,Ct,x.url)){m("proxy","settings.json could not be written (is it valid JSON?)");return}let T=At(R);m("proxy",T.url?`proxy set to ${x.url} \u2014 requests go through it from the next message.`:`proxy saved as ${x.url}, but it could not be applied this session; it will be tried on the next start.`);return}if(s==="tools"){let d=$.getActiveToolNames().sort();m("tools",d.length?d.join(`
134
+ `):"no tools enabled");return}if(s==="dcp"){m("dcp",Qe(l,e.cwd,$.getSessionStats().sessionId));return}if(s==="context"||s==="decompress"||s==="sweep"){m(s,Qe(`${s} ${l}`.trim(),e.cwd,$.getSessionStats().sessionId));return}if(s==="rewind"){Wr();return}if(s==="undo"){if(!await Bn(e.cwd)){m("undo","not a git repository");return}let d=await zo(e.cwd);m("undo",d.ok?`undone: ${d.output}`:`undo failed: ${d.output}`),b(!0);return}if(s==="commit"){if(!Bn(e.cwd)){m("commit","not a git repository");return}if(!await Vo(e.cwd)){m("commit","nothing to commit");return}let d=l||`howtocode: session update ${new Date().toISOString().slice(0,16)}`,p=await qo(e.cwd,d);m("commit",p.ok?p.output:`commit failed: ${p.output}`),b(!0);return}if(s==="review"){if(!(await Yo(e.cwd)).trim()){m("review","no changes to review");return}gn("Review the uncommitted changes. Report concrete issues with file evidence. Do not edit files.");return}if(s==="workflow"){if(l.trim()==="clear"){Mr(),m("workflow","cleared the pinned workflow panel");return}if(!G){m("workflow","no workflow run in this session yet");return}let d=Kn(G,Date.now()),p=d[W.selectedPhase];m("workflow",[`panel ${ve?"pinned above the editor":"unpinned"}`,`phase ${W.selectedPhase+1}/${d.length}: ${p?.title??"(none)"}`,`filter: ${W.filter}${W.paused?" \xB7 paused":""}`,"keys: \u2191/\u2193 phase \xB7 Enter drill in \xB7 Esc unpin \xB7 f filter \xB7 p pause \xB7 x stop \xB7 s save","clear it with /workflow clear"].join(`
135
+ `));return}if(s==="plan"){if(Fo()||Rt().state==="pending"){Dn(Oo(Rt())),m("plan","plan mode off; edits are allowed again");return}Dn(Lo(Rt())),m("plan",`plan mode armed \u2014 send your next prompt to start planning
136
+ plan file: ${No()??"(unknown)"}`);return}if(s==="goal"){let d=l.trim();if(!d){m("goal",jn(Mt()));return}let{goal:p,error:w}=_o(Mt(),"set",d,void 0,void 0);if(w){H(w);return}Io(p),await $.sendCustomMessage({customType:Mo,content:d,display:!1,details:p}),m("goal",`goal set
137
+ ${jn(p)}`);return}if(s==="session"){let d=$.model;m("session",d?`${d.provider}/${d.id}`:"no model");return}if(s==="skills"){m("skills",ms($.resourceLoader.getSkills().skills));return}if(s==="preset"){$i(l);return}if(s==="roblox"){let d=se(e.cwd).entries.find(x=>x.manifest.name==="rotoolbox");if(!d||d.source!=="installed"){m("roblox","RoToolbox is not installed. Run /preset and install RoToolbox first.");return}let p=xn(d.dir),w=$.getActiveToolNames().filter(x=>/roblox[-_]studio/i.test(x)),h=w.length>0;m("roblox",p?`RoToolbox: disabled
138
+ Enable with /preset enable rotoolbox
139
+ The MCP server and manager stay stopped while disabled.`:["RoToolbox: active",`MCP server: ${h?`connected \u2014 ${w.length} tool${w.length===1?"":"s"} registered`:"not connected yet"}`,"Open Roblox Studio with a place, then use a prompt to inspect it.","Disable with /preset disable rotoolbox"].join(`
140
+ `));return}let f=fs(r,$.resourceLoader.getSkills().skills.map(d=>d.name));if(f){oi(f);return}let y=$.extensionRunner.getCommand(s??"");if(y){try{await y.handler(l,$.extensionRunner.createCommandContext())}catch(d){H(d instanceof Error?d.message:String(d))}return}m("command",`/${s??""} is not available in this screen yet`)};Eo((r,s)=>{let{promise:c,resolve:l}=Promise.withResolvers();return j(r,s.map(f=>({value:f,label:f})),l,()=>l("cancelled")),c}),process.on("SIGTERM",He),gs(()=>{He()}),t.setTitle(`${$n} ${bt}`),Dd(),i.start(),i.requestRender(!0),pn(!0);{let{maybeShowWelcome:r}=await import("./chunk-KTS2F755.js");await r({cwd:e.cwd,note:e.note,signedIn:be!==void 0,runSlash:s=>{Je(s)},openExternal:s=>{Fe(s)}},j,m)}e.initialPrompt&&gn(e.initialPrompt),await new Promise(()=>{})}var X,Wd=1e3/30,Ud=45e3;export{Er as Dock,Ar as Hud,Tr as PinnedBlock,Nd as approvalDetail,Od as infoPanel,It as orderModelsForDefault,Ld as pickerPanel,vm as runWorkbench,xr as slashCommands,Fd as workflowPanel,zt as workflowPanelFromRun,Pr as workflowRunOf};
@@ -0,0 +1,4 @@
1
+ import{execFile as x}from"node:child_process";import{closeSync as C,existsSync as f,mkdirSync as v,openSync as N,readFileSync as E,realpathSync as k,statSync as T,unlinkSync as w,writeFileSync as _}from"node:fs";import{homedir as p}from"node:os";import{delimiter as $,dirname as I,join as u,sep as m}from"node:path";var l="howtocode",g=["npm","npm.cmd","npm.exe"],A=2e4,O=2,P=12e4,R=600*1e3,U=5*1e3;function L(e,t){let r=s=>{let i=s.trim().split("-")[0]?.split("+")[0]??"";if(/^\d+(\.\d+)*$/.test(i))return i.split(".").map(c=>Number(c))},n=r(e),o=r(t);if(!n||!o)return 0;let a=Math.max(n.length,o.length);for(let s=0;s<a;s+=1){let i=n[s]??0,c=o[s]??0;if(i>c)return 1;if(i<c)return-1}return 0}function H(e,t){return e.includes("-")?!1:L(e,t)>0}var h=(e,t,r)=>new Promise(n=>{x(e,t,{cwd:r.cwd,timeout:r.timeoutMs,windowsHide:!0},(o,a,s)=>{let i=o?o.code:void 0,c=typeof i=="number"?i:o?1:0,d=typeof i=="string"?i:void 0;n({code:c,stdout:String(a??""),stderr:String(s??""),...d?{errorCode:d}:{}})})}),D=new Set(["ENOENT","EACCES","EINVAL","EPERM"]);function b(){let e=I(process.execPath);for(let r of[["..","lib","node_modules","npm","bin","npm-cli.js"],["node_modules","npm","bin","npm-cli.js"]]){let n=u(e,...r);if(f(n))return{command:process.execPath,args:[n]}}let t=process.env.PATH?.split($).filter(Boolean)??[];for(let r of t)for(let n of g){let o=u(r,n);if(!(n.endsWith(".cmd")||n.endsWith(".bat"))&&f(o))return{command:o,args:[]}}if(process.platform==="win32")for(let r of t)for(let n of g){if(!n.endsWith(".cmd")&&!n.endsWith(".bat"))continue;let o=u(r,n);if(f(o))return{command:process.env.ComSpec||"cmd.exe",args:["/d","/s","/c",`"${o}"`]}}}var F="could not check for a newer version: npm was not found, so run `npm install -g howtocode@latest` yourself",G="could not check for a newer version: the registry did not answer";function Q(e){if(e.latest===void 0)return`${e.message} (this is why no update was offered; /update retries it)`}function K(e){if(e.code===-2)return!0;let t=e.errorCode??(e.stderr??"").trim();return D.has(t)}function S(){let t=process.env.HOWTOCODE_CODING_AGENT_DIR?.trim()||u(p(),".howtocode","agent");try{v(t,{recursive:!0})}catch{}return u(t,"update.lock")}function B(e){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(t){return t?.code==="EPERM"}}function y(e,t){try{let r=t-T(e).mtimeMs,n=E(e,"utf8").trim();return{pid:/^\d+$/.test(n)?Number.parseInt(n,10):void 0,ageMs:r}}catch{return}}function W(e){return e?e.pid===void 0?e.ageMs<U:B(e.pid)?e.ageMs<R:!1:!1}function j(e=Date.now()){let t=S();for(let r=0;r<2;r+=1)try{let n=N(t,"wx",384);try{_(n,String(process.pid))}finally{C(n)}return!0}catch(n){if(n.code!=="EEXIST")return!0;if(W(y(t,e)))return!1;try{w(t)}catch{return!1}}return!1}function J(){let e=S();try{let t=y(e,Date.now());if(t&&t.pid!==void 0&&t.pid!==process.pid)return;w(e)}catch{}}async function M(e){let t=e?.runner??h,r=b();if(!r)return{reason:"no-npm"};let n="no-answer";for(let o=0;o<O;o+=1){let a;try{a=await t(r.command,[...r.args,"view",`${l}@latest`,"version","--prefer-online"],{cwd:p(),timeoutMs:e?.timeoutMs??A})}catch{n="no-answer";continue}if(a.code!==0){if(K(a))return{reason:"no-npm"};n="no-answer";continue}let s=a.stdout.trim().split(`
2
+ `).pop()?.trim()??"";if(/^\d+\.\d+/.test(s))return{version:s};n="no-answer"}return{reason:n}}async function Z(e){return(await M(e)).version}async function ee(e,t){let r=await M(t);if(!r.version)return{current:e,available:!1,message:r.reason==="no-npm"?F:G};let n=r.version;return H(n,e)?{current:e,latest:n,available:!0,message:`HowToCode ${n} is available (you have ${e})`}:{current:e,latest:n,available:!1,message:`HowToCode ${e} is up to date`}}function V(e,t,r){let n=`${t}
3
+ ${e}`.split(`
4
+ `).map(d=>d.trim()).filter(Boolean).filter(d=>!/^npm warn\b/i.test(d)),o=n.filter(d=>/^npm error\b/i.test(d)||/\bERR!/i.test(d)),s=(o.find(d=>/^npm error code\b/i.test(d))??o.at(-1)??n.at(-1)??r??"").replace(/^npm error\s*/i,"").trim(),i=`${n.join(" ")} ${r??""}`,c="";return/EACCES|EPERM|permission denied/i.test(i)?c=" \u2014 npm could not write its files (permission denied); close other HowToCode windows and run the terminal as Administrator":/EBUSY|EEXIST|ENOTEMPTY|resource busy|being used by another process/i.test(i)?c=" \u2014 a file is in use; close other HowToCode windows and try again":/ENOSPC/i.test(i)?c=" \u2014 the disk is full":/ETIMEDOUT|ENOTFOUND|EAI_AGAIN|ECONNREFUSED/i.test(i)&&(c=" \u2014 npm could not reach the registry"),{detail:s,hint:c}}async function ne(e){let t=e?.runner??h;if(!j())return{ok:!1,message:"another HowToCode is already installing an update"};try{let r=b();if(!r)return{ok:!1,message:"npm was not found, so run `npm install -g howtocode@latest` yourself"};let n=e?.version?`${l}@${e.version}`:`${l}@latest`,o=await t(r.command,[...r.args,"install","-g",n],{cwd:p(),timeoutMs:e?.timeoutMs??P});if(o.code!==0){let{detail:a,hint:s}=V(o.stdout,o.stderr,o.errorCode);return{ok:!1,message:`the update did not install${s}${a?`: ${a}`:""}`}}return{ok:!0,version:e?.version,message:"updated; it takes effect the next time HowToCode starts"}}catch(r){return{ok:!1,message:`the update failed: ${r instanceof Error?r.message:String(r)}`}}finally{J()}}function te(e=process.argv[1]){if(!e)return!1;let t=e;try{t=k(e)}catch{}return t.includes(`${m}node_modules${m}${l}${m}`)}function re(e){try{return JSON.parse(E(e,"utf8")).autoUpdate!==!1}catch{return!0}}export{l as a,A as b,O as c,P as d,R as e,U as f,L as g,H as h,b as i,F as j,G as k,Q as l,B as m,j as n,J as o,Z as p,ee as q,V as r,ne as s,te as t,re as u};