howtocode 0.7.68 → 0.7.69
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.
- package/README.md +7 -1
- package/dist/{chunk-NPD6557W.js → chunk-336TZTEK.js} +1 -1
- package/dist/{chunk-7LAMZWB5.js → chunk-4SK7TRJW.js} +1 -1
- package/dist/chunk-5FIFNXLT.js +10 -0
- package/dist/{chunk-6PZTZT6T.js → chunk-ADGPAPXH.js} +1 -1
- package/dist/{chunk-O3XEEDMR.js → chunk-DK3DYJTA.js} +1 -1
- package/dist/{chunk-EPNFKO5O.js → chunk-DXMLXM3S.js} +1 -1
- package/dist/{chunk-L4XKIPIG.js → chunk-E2UZLMQH.js} +1 -1
- package/dist/chunk-FABEBOGV.js +2 -0
- package/dist/chunk-GNV6G3JW.js +201 -0
- package/dist/{chunk-YX2QDCVK.js → chunk-GQYIIDKK.js} +1 -1
- package/dist/{chunk-KS6FRAVP.js → chunk-IQGALTAR.js} +1 -1
- package/dist/chunk-KKQCOMDH.js +141 -0
- package/dist/{chunk-XVHYS2UZ.js → chunk-PMWAHAZV.js} +1 -1
- package/dist/{chunk-W2U7D5UF.js → chunk-RJYOUCLJ.js} +1 -1
- package/dist/{chunk-YFJKKWIX.js → chunk-SDU65XW4.js} +1 -1
- package/dist/{chunk-HKABQFBG.js → chunk-SKLMU4IE.js} +1 -1
- package/dist/{chunk-3H2ECHBB.js → chunk-ULXYWUXZ.js} +1 -1
- package/dist/{chunk-LUBZSBUH.js → chunk-VZZPQZDI.js} +1 -1
- package/dist/{chunk-NIDL55H4.js → chunk-W34I6VMP.js} +1 -1
- package/dist/{chunk-4KNWFMK6.js → chunk-W7C4PWUR.js} +1 -1
- package/dist/{chunk-AVNJV7SN.js → chunk-ZEBSTTKL.js} +1 -1
- package/dist/{chunk-SVONBXW3.js → chunk-ZJL4OEXX.js} +3 -3
- package/dist/{chunk-2GVIOMRN.js → cli-auth.js} +1 -1
- package/dist/main-app.js +7 -7
- package/dist/main.js +10 -0
- package/package.json +1 -1
- package/dist/chunk-465RG5I6.js +0 -10
- package/dist/chunk-HDH5ER4H.js +0 -141
- package/dist/chunk-U3GZBLTM.js +0 -2
- package/dist/chunk-VDUY46W2.js +0 -198
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a,b,c,d}from"./chunk-
|
|
1
|
+
import{a,b,c,d}from"./chunk-FABEBOGV.js";import"./chunk-WOT6VMZA.js";export{c as describeSandbox,a as detectSandbox,d as enterSandbox,b as sandboxArgv};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{$ as We,B as De,C as Ce,E as R,F as H,Fa as ot,H as B,I as Pe,Q as je,R as Ne,Ra as st,S as Me,T as Fe,U as Le,Ua as Q,V as Be,W as Ue,Wa as rt,Y as Ge,_ as Y,a as N,b as M,ba as He,c as ge,ca as qe,d as he,da as ze,e as we,ea as V,f as be,fa as Ze,g as A,ga as Ke,i as ye,j as ke,ja as Xe,k as Se,l as _e,la as Ye,m as X,ma as q,na as Ve,o as Te,oa as Je,p as Ee,q as $e,qa as J,r as ve,s as Ae,t as x,u as Re,ua as Qe,va as et,w as Oe,x as W,xa as tt,y as Ie,ya as nt}from"./chunk-
|
|
1
|
+
import{$ as We,B as De,C as Ce,E as R,F as H,Fa as ot,H as B,I as Pe,Q as je,R as Ne,Ra as st,S as Me,T as Fe,U as Le,Ua as Q,V as Be,W as Ue,Wa as rt,Y as Ge,_ as Y,a as N,b as M,ba as He,c as ge,ca as qe,d as he,da as ze,e as we,ea as V,f as be,fa as Ze,g as A,ga as Ke,i as ye,j as ke,ja as Xe,k as Se,l as _e,la as Ye,m as X,ma as q,na as Ve,o as Te,oa as Je,p as Ee,q as $e,qa as J,r as ve,s as Ae,t as x,u as Re,ua as Qe,va as et,w as Oe,x as W,xa as tt,y as Ie,ya as nt}from"./chunk-GNV6G3JW.js";import{b as xe}from"./chunk-27TRKD65.js";import{c as ue}from"./chunk-SKLMU4IE.js";import{h as pe,l as fe}from"./chunk-VZZPQZDI.js";import{t as me}from"./chunk-ZJL4OEXX.js";import"./chunk-7LA2AMZB.js";import"./chunk-W34I6VMP.js";import{b as G,c as ie,d as ae}from"./chunk-DK3DYJTA.js";import{H as S,K as de,v as ce,w as le}from"./chunk-5FIFNXLT.js";import"./chunk-UTYFLLSM.js";import"./chunk-MVVEYKN6.js";import"./chunk-WOT6VMZA.js";import{join as Nt}from"node:path";import{hostname as io}from"node:os";import{createAgentSession as ao,createCodemodeExtension as co,createMcpExtension as lo,createToolSearchExtension as uo,DefaultResourceLoader as po,ProjectTrustStore as fo,SessionManager as Z,SettingsManager as mo}from"@netrodev/hxf-coding-agent";import{existsSync as Ft,readFileSync as Lt}from"node:fs";import{join as Bt}from"node:path";var it=Bt(S,"APPEND_SYSTEM.md"),Ut=["<non-interactive>","This run has no user attached: it was started with --print, and there is nobody to answer a question. Anything that stops and waits for a reply \u2014 `ask`, a confirmation, a skill that resolves a mode by asking which mode to use \u2014 will simply end the run with the task unfinished.","So do not ask. Where an instruction tells you to ask the user and wait, take the default it describes and continue, and say which default you took and why in your final answer. The user reads that answer; they cannot answer mid-run.","Where a skill offers a choice of modes, prefer the one that applies the rules while you work over the one that audits afterwards: this is the mode for building something now, and the audit mode can still be run later by the same person who reads your answer.","</non-interactive>"].join(`
|
|
2
2
|
`),Gt=16*1024;function Wt(e){try{if(!Ft(e))return;let t=Lt(e,"utf8").trim();return!t||Buffer.byteLength(t,"utf8")>Gt?void 0:t}catch{return}}function at(e,t){let s=[t?e:`${e}
|
|
3
3
|
|
|
4
4
|
${Ut}`],n=Wt(it);return n&&s.push(`# Standing instructions from ${it}
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
import{$a as ps,A as Oo,Aa as Jo,Ba as Xo,Ca as Zo,D as Rt,Da as Qo,E as No,Ea as es,G as Fo,Ga as de,Ha as E,Ia as X,J as jo,Ja as A,K as Do,Ka as ts,L as It,La as ns,M as Wo,Ma as rs,N as Uo,Na as is,O as Bo,Oa as Kn,P as Wn,Pa as os,Qa as ss,Sa as as,Ta as ls,Va as cs,X as Un,Xa as ds,Ya as us,Z as Bn,Za as fs,_a as ms,aa as Qe,ab as gs,bb as hs,c as Ao,e as To,g as Eo,h as Mo,ha as Vo,ia as et,ka as _t,n as Io,oa as Ko,pa as Go,ra as Ho,sa as qo,ta as zo,v as _o,wa as Yo,x as Lo,z as Dn,za as Vn}from"./chunk-GNV6G3JW.js";import{b as bs,c as ws}from"./chunk-SDU65XW4.js";import{b as Ee,c as Ze,e as Po,f as Mt,g as Ro,h as Pt}from"./chunk-27TRKD65.js";import{A as so,B as Ct,C as ao,b as In,c as ye,d as Ji,e as Xi,h as Zi,n as _n,o as Qi,q as oe,s as eo,t as Ie,v as to,w as no,x as ro,y as io,z as oo}from"./chunk-SKLMU4IE.js";import{a as lo,b as co,c as uo,d as fo,f as mo,g as po,h as go,i as ho,l as bo}from"./chunk-VZZPQZDI.js";import{a as At,b as Ln,c as On,d as wo,e as Tt}from"./chunk-3FYCFLNK.js";import{u as yo}from"./chunk-SDO33XPR.js";import{a as ko}from"./chunk-ORJ2QZBG.js";import{a as $o,c as Et,d as Nn,j as vo,k as xo,l as So,n as Fn,o as jn,p as Co}from"./chunk-ZJL4OEXX.js";import{a as Pn,b as Rn,c as Vi,d as Ki}from"./chunk-EZNNALD3.js";import{b as St}from"./chunk-7LA2AMZB.js";import{h as Ci,i as Ai}from"./chunk-W34I6VMP.js";import{a as vn,b as wt,e as Si}from"./chunk-DK3DYJTA.js";import{A as ji,B as vt,C as xt,D as Di,E as Cn,F as An,G as Wi,H as P,M as Xe,N as Tn,O as Ui,Q as Bi,c as xn,d as yt,g as kt,i as Ti,j as Ei,k as Mi,l as Pi,m as $t,n as Ri,o as Sn,p as Ii,s as se,t as _i,u as Li,x as Oi,y as Ni,z as Fi}from"./chunk-5FIFNXLT.js";import{a as ie}from"./chunk-UTYFLLSM.js";import{j as En,k as Mn}from"./chunk-MVVEYKN6.js";import{b as Gi,c as Hi,d as qi,e as zi,f as Yi}from"./chunk-TUXY64DT.js";import"./chunk-WOT6VMZA.js";import{execFile as yd}from"node:child_process";import{promisify as kd}from"node:util";import{appendFileSync as $d,existsSync as qt,mkdirSync as $r,readFileSync as zt,rmSync as vd,statSync as tl,writeFileSync as vr}from"node:fs";import{basename as xd,dirname as Sd,join as me,resolve as Cd}from"node:path";function ys(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 ks(e){let t=!1;process.on("SIGINT",()=>{t||(t=!0,e())})}function Il(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 _l(e){let t=e?.input??0,n=e?.cacheRead??0,r=e?.cacheWrite??0;return{input:t,cacheRead:n,cacheWrite:r,prompt:t+n+r}}function Ll(e){if(typeof e!="string")return null;let t=Date.parse(e);return Number.isNaN(t)?null:t}function Ol(e){if(!e||typeof e!="object")return;let t=e,r=(t.message&&typeof t.message=="object"?t.message:void 0)??t,o=Il(r.usage);if(!o)return;let u=typeof r.provider=="string"?r.provider:"",a=typeof r.model=="string"?r.model:"";return{usage:o,model:[u,a].filter(Boolean).join("/")}}function $s(e){let t=0,n=0,r=[],o=0,u=null;for(let g of e){let b=Ol(g);if(!b)continue;let{input:k,cacheRead:C,cacheWrite:_,prompt:O}=_l(b.usage);if(O===0)continue;t+=C,n+=k+_;let F=Ll(g.timestamp),W=u,K=W?W.at:null;if(W!==null&&C===0&&k>=1e3){let ee=F!==null&&K!==null?Math.max(0,F-K):0;r.push({missedTokens:k,idleMs:ee,modelChanged:b.model!==""&&W.model!==""&&b.model!==W.model}),o+=k}u={prompt:O,at:F??K??null,model:b.model}}let a=t+n;return{cachedTokens:t,billedTokens:n,hitRate:a>0?t/a*100:null,misses:r,missedTokens:o}}function vs(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 Ad,ProjectTrustStore as Td,SessionManager as Ed}from"@netrodev/hxf-coding-agent";import{CombinedAutocompleteProvider as nl,Container as Md,Editor as Pd,matchesKey as q,ProcessTerminal as Rd,ScrollView as Id,KeybindingsManager as sl,setKeybindings as al,isKeyRelease as _d,parseColor as Jt,TUI_KEYBINDINGS as ll,SelectList as Ld,TuiAltScreen as Od,truncateToWidth as We,VStack as Nd,visibleWidth as Ar,wrapTextWithAnsi as cl}from"@netrodev/hxf-tui";import{spawn as Nl}from"node:child_process";function Fl(e,t,n=2e3){return new Promise(r=>{let o=!1,u,a=k=>{o||(o=!0,u!==void 0&&clearTimeout(u),r(k))},g;try{g=Nl(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 Gn(){return process.env.XDG_SESSION_TYPE==="wayland"||(process.env.WAYLAND_DISPLAY?.length??0)>0}async function jl(){let e=[];process.platform==="darwin"?e.push({command:"pbpaste",args:[]}):process.platform==="win32"?e.push({command:"powershell.exe",args:["-NoProfile","-Command","Get-Clipboard -Raw"]}):(Gn()&&(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||!Gn())&&(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 Fl(t.command,t.args);if(n.ok&&n.stdout.length>0)return n.stdout}}async function xs(){let e;try{let{getNativeClipboard:r}=await import("@netrodev/hxf-tui");e=r()}catch{e=void 0}if(e)try{let r=await e.getText();if(typeof r=="string"&&r.length>0)return{ok:!0,text:r}}catch{}let t=await jl();return t!==void 0?{ok:!0,text:t}:{ok:!1,reason:`no clipboard tool could read it \u2014 ${Gn()?"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 Dl}from"node:child_process";import{mkdirSync as Wl,writeFileSync as Ul}from"node:fs";import{join as Bl}from"node:path";import{getNativeClipboard as Vl}from"@netrodev/hxf-tui";async function _e(e,t,n=4e3){let{promise:r,resolve:o}=Promise.withResolvers(),u=!1,a,g=C=>{u||(u=!0,clearTimeout(a),o(C))},b;try{b=Dl(e,[...t],{stdio:["ignore","pipe","ignore"]})}catch{return g(void 0),r}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)}),r}function Ss(){return process.env.XDG_SESSION_TYPE==="wayland"||(process.env.WAYLAND_DISPLAY?.length??0)>0}function Kl(e){return e.length>8&&e[0]===137&&e[1]===80&&e[2]===78&&e[3]===71}function Gl(e){return e.length>3&&e[0]===255&&e[1]===216&&e[2]===255}async function Hl(){try{let e=await Vl()?.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(Ss()){let e=await _e("wl-paste",["--type","image/png"]);if(e)return e}if((process.env.DISPLAY?.length??0)>0||!Ss()){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 ql(e,t){let n=t==="image/jpeg"?"jpg":"png";return`pasted-${new Date(e).toISOString().replace(/[:.]/g,"-")}.${n}`}async function Hn(e=Bi,t=Date.now()){let n=await Hl();if(!n)return{ok:!1,reason:"the clipboard holds no image"};let r=Kl(n)?"image/png":Gl(n)?"image/jpeg":void 0;if(!r)return{ok:!1,reason:"the clipboard image is not PNG or JPEG"};try{Wl(e,{recursive:!0});let o=Bl(e,ql(t,r));return Ul(o,n,{mode:384}),{ok:!0,image:{path:o,data:n.toString("base64"),mimeType:r}}}catch(o){return{ok:!1,reason:`could not store the image: ${o instanceof Error?o.message:String(o)}`}}}import{TreeSelectorComponent as Fd,initTheme as jd}from"@netrodev/hxf-coding-agent";import{getKeybindings as rl}from"@netrodev/hxf-tui";import{mixColors as zl,parseColor as Yl,styleText as he}from"@netrodev/hxf-tui";var ue=process.env.HOWTOCODE_NO_MOTION!=="1",Jl=45,Cs=5,As=8,qn=1e4,Ts=6e4,Es=3,Ms=4,zn=e=>e<0?0:e>1?1:e;function ke(e,t,n){let r=zn(n);return r>=1?t:r<=0?e:zl(e,t,r)}var Lt=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),r=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(r/.008)),g=r/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,r){return!ue||e<=qn?t:e>=Ts?r:ke(n,r,(e-qn)/(Ts-qn))}function Ps(e,t){return!ue||t<=0||e<0?1:1-(1-zn(e/t))**3}var Rs=260,Xl=45;function Is(e,t,n=Xl,r=400){return!ue||n<=0||e<0||e>=r?t:Math.min(t,Math.floor(e/n)+1)}function _s(e,t,n=Date.now(),r=1400){if(!ue||r<=0)return e;let o=n%r/r;return ke(e,t,o<.5?o*2:(1-o)*2)}function Ot(e,t,n){let r=he(e,{fg:t.rest},de);if(!ue||e.length===0)return r;let o=zn(n);if(o>=1)return r;let u=t.band??1,a=e.length+Ms*2,b=Math.min(a-1,Math.floor(o*a))-Ms,k=K=>{let ee=Math.abs(K-b);return ee>u?0:1-ee/(u+1)},C="",_=0,O=null,F=0,W=0;for(let K of e){let ee=k(W);O===null?O=ee:ee!==O&&(C+=he(e.slice(_,F),{fg:ke(t.rest,t.lit,O)},de),_=F,O=ee),F+=K.length,W+=1}return C+he(e.slice(_),{fg:ke(t.rest,t.lit,O??0)},de)}function Jn(e,t,n=Date.now(),r=90){let o=t[0]??Yl("#e6e6e6");if(t.length===0||e.length===0)return he(e,{fg:o},de);if(!ue||r<=0)return he(e,{fg:t[t.length-1]??o},de);let u=t.length*r,a=(n%u+u)%u,g="",b=0,k=null,C=0,_=0,O=F=>{let W=(a+F*r)/u%1*t.length,K=Math.floor(W)%t.length,ee=(K+1)%t.length;return ke(t[K]??o,t[ee]??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 Zl(e,t){let n=Math.abs(e-t);return n>=Cs?0:Math.ceil((1-n/Cs)*Es)/Es}function Ls(e,t,n=Date.now()){let r=t.charMs??Jl;if(!ue||e.length===0||r<=0)return he(e,{fg:t.base},de);let o=e.length+As*2,u=n/r%o-As,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=Zl(_,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 Ql,statSync as ec}from"node:fs";import{homedir as tc}from"node:os";import{extname as nc}from"node:path";var Xn="\x1B[200~",Zn="\x1B[201~",rc={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp"},Os=10*1024*1024,ic=256*1024,oc=20;function Ns(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 Fs(e){return e.trim()===""}function sc(e){return/^[a-zA-Z]:[\\/]/.test(e)||e.startsWith("\\\\")||e.startsWith("/")||e==="~"||e.startsWith("~/")}function ac(e,t=tc()){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 js(e,t){let n=e.trim();if(!n||n.length>8192)return;let r,o=[...n.matchAll(/"([^"]+)"|'([^']+)'/g)].map(a=>a[1]??a[2]??"");if(o.length>0&&n.replace(/"[^"]+"|'[^']+'/g,"").trim()===""?r=o:r=n.split(/\r?\n/).map(a=>a.trim()).filter(a=>a.length>0),r.length===0||r.length>oc||!r.every(a=>sc(a)||a.startsWith("file://")))return;let u=r.map(a=>ac(a));return u.every(t)?u:void 0}function Ds(e){return rc[nc(e).toLowerCase()]}function Ws(e){return`[file ${e}]`}function Qn(e){return`[image ${e}]`}function Us(e,t){return e.replace(/\[file ([^\]\n]+)\]/g,(n,r)=>{let o=t(r);return o===void 0?n:`<file name="${r}">
|
|
3
|
+
${o.trimEnd()}
|
|
4
|
+
</file>`})}function Bs(e){try{let t=ec(e);if(!t.isFile()||t.size===0||t.size>ic)return;let n=Ql(e);return n.includes(0)?void 0:n.toString("utf8")}catch{return}}import{Markdown as Tc,wrapTextWithAnsi as Ec}from"@netrodev/hxf-tui";import{homedir as lc}from"node:os";import{isAbsolute as cc,relative as dc,resolve as uc,sep as Vs}from"node:path";import{getImageDimensions as fc,imageFallback as Ks,renderImage as mc}from"@netrodev/hxf-tui";var pc="\u25CF",nr="\u2514",Ft="\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 gc="\u25B2";var hc="\u25CB",bc=["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 zs(e){return bc.includes(rr(e))}function tt(e,t=process.cwd()){if(!e||!cc(e))return e;let n=uc(e),r=dc(t,n);if(r==="")return".";if(r&&!r.startsWith(`..${Vs}`)&&r!=="..")return r;let o=lc();return o&&(n===o||n.startsWith(o+Vs))?`~${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 wc(e,t=160){if(!e||typeof e!="object")return"";try{let n=JSON.stringify(e);return n&&n!=="{}"?ae(n,t):""}catch{return""}}function yc(e,t){switch(e){case"read":{let n=tt(U(t,"path")??""),r=[U(t,"offset"),U(t,"limit")].filter(Boolean);return r.length>0?`${n} ${r.length===1?`offset=${r[0]}`:`offset=${r[0]}, limit=${r[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"),r=U(t,"filter");return n?r?`${n} filter=${r}`:n:"all tasks"}case"kill_shell":return U(t,"task_id")??"";case"compress":{let n=U(t,"topic")??"",r=Array.isArray(t.content)?t.content.length:0;return r>1?`${n} (${r} ranges)`:n}case"grep":{let n=U(t,"pattern")??"",r=U(t,"path");return r?`${n} in ${tt(r)}`:n}case"find":case"glob":{let n=U(t,"pattern")??U(t,"glob")??"",r=U(t,"path");return r?`${n} in ${tt(r)}`: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",r=U(t,"file")??"",o=U(t,"line");return o?`${n} ${r}:${o}`:`${n} ${r}`}case"quality":return U(t,"path")??"changed files";case"think":return"private";case"todo":{let n=U(t,"op")??"view",r=U(t,"task"),o=t?.items;return n==="init"&&Array.isArray(o)?`init ${o.length} task${o.length===1?"":"s"}`:r?`${n} ${r}`:n}case"context":{let n=U(t,"op")??"list",r=U(t,"key");return r?`${n} ${r}`:n}case"workflow":{let n=U(t,"path");if(n)return n;let r=U(t,"code")??"",o=/export\s+const\s+meta\s*=\s*\{[\s\S]*?name\s*:\s*["'`]([^"'`]+)/.exec(r)?.[1];if(o)return o;let u=r.trim().split(`
|
|
5
|
+
`)[0]??"";return u.length>40?`${u.slice(0,40)}\u2026`:u}default:return wc(t)}}function Me(e,t,n=100){let r=rr(e),u=r!==e?r:r.charAt(0).toUpperCase()+r.slice(1),a=zs(e)?gc:pc,g=ae(yc(r,t),n);return g?`${a} ${u}(${g})`:`${a} ${u}`}function kc(e){let t=0,n=0;for(let r of e.split(`
|
|
6
|
+
`))r.startsWith("+")&&!r.startsWith("+++")?t+=1:r.startsWith("-")&&!r.startsWith("---")&&(n+=1);return{additions:t,removals:n}}function Ys(e){let t=e?.content;if(!Array.isArray(t))return[];let n=[];for(let r of t){if(!r||typeof r!="object")continue;let o=r;if(o.type!=="image"||typeof o.data!="string")continue;let u=typeof o.mimeType=="string"?o.mimeType:"image/png";try{let a=fc(o.data,u),g=a?mc(o.data,a,{maxWidthCells:60,maxHeightCells:24}):null;n.push(g?g.sequence:Ks(u,a??void 0))}catch{n.push(Ks(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 Gs(e){let t=e.exit_code;return typeof t=="number"&&Number.isFinite(t)?t:void 0}function $c(e){let t=[];if(e&&typeof e=="object"){t.push(e);let r=e.content;if(Array.isArray(r))for(let o of r){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 r of t){let o=["instances","instanceCount","count","parts","partsCreated"].map(b=>r[b]).find(b=>typeof b=="number"&&Number.isFinite(b));typeof o=="number"&&n.push(`${o} instance${o===1?"":"s"}`);let u=tr(r,["files","written","paths"]);u&&n.push(u.join(", "));let a=tr(r,["images","renders","screenshots"]);a&&n.push(`renders ${hc} ${a.join(", ")}`);let g=tr(r,["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 r=e[n];if(!Array.isArray(r))continue;let o=r.filter(u=>typeof u=="string"&&u!=="");if(o.length>0)return o}}function Hs(e){return e.trim().split(`
|
|
7
|
+
`).find(t=>t.trim())??""}function vc(e,t){let n=typeof e.output=="string"?e.output:t.replace(/\n*Command exited with code \d+\s*$/,""),r=nt(n);return r>0?` (${r} line${r===1?"":"s"})`:""}function xc(e,t,n){return e===1?t:n}function nt(e){let t=e.trim();return t?t.split(`
|
|
8
|
+
`).length:0}function qs(e){return e<1e3?`${e} tokens`:`${(e/1e3).toFixed(1)}k tokens`}function jt(e,t,n){let r=Le(t),o=it(t),u=ir(t);if(n){let a=Gs(u);if(a!==void 0&&(e==="bash"||e==="powershell"))return`exit ${a}`;let g=r.trim().split(`
|
|
9
|
+
`).find(b=>b.trim());return ae(g??"failed",120)}if(zs(e)){let a=$c(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=r.split(`
|
|
10
|
+
`).filter(g=>g.startsWith("## ")).map(g=>g.replace(/^##\s*/,"").trim());if(a.length===0){let g=r.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(r.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 ${qs(-C)} LARGER than the range`:`${k} \xB7 ${qs(C)} saved`}case"edit":{let a=typeof o.diff=="string"?o.diff:"";if(!a)return"applied";let{additions:g,removals:b}=kc(a);return`+${g} / -${b}`}case"write":{let a=nt(r);return a===0?"written":`written (${a} ${xc(a,"line","lines")})`}case"bash":case"powershell":{let a=Gs(u);if(a===void 0)return r.trim()?ae(Hs(r),120):"done";let g=vc(u,r);return a===0?`exit 0${g}`:`exit ${a}`}case"grep":{let a=nt(r);return a===0?"no matches":`${a} match${a===1?"":"es"}`}case"web_search":{let a=typeof o.count=="number"?o.count:nt(r);return a===0?"no results":`${a} result${a===1?"":"s"}`}case"web_fetch":return`${typeof o.chars=="number"?o.chars:r.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(Hs(r),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"?`, ${rs(o.endedAt-o.startedAt)}`:"";return`${a} agent(s), ${g} tokens${k}${b>0?`, ${b} failed`:""}`}case"bash_output":{let a=r.trim().split(`
|
|
13
|
+
`)[0]??"",g=/running/.test(a)?"running":/finished/.test(a)?"finished":"task",b=r.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=r.trim().split(`
|
|
15
|
+
`)[0]??"";return a.startsWith("Stopped")?"stopped":ae(a,120)}default:{let a=r.trim().split(`
|
|
16
|
+
`).find(g=>g.trim());return a?ae(a,120):"done"}}}function Js(e,t){let n=it(t);if(e==="edit"&&typeof n.diff=="string")return n.diff.split(`
|
|
17
|
+
`).filter(r=>r.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 r=n.todos??[],o={pending:"[ ]",in_progress:"[>]",completed:"[x]",dropped:"[-]"};return r.slice(0,6).map(u=>`${o[u.status??"pending"]??"[ ]"} ${u.content??""}`)}return e==="task"?Le(t).split(`
|
|
20
|
+
`).filter(r=>r.trim()&&!r.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 Nt=400;function Xs(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,Nt);let r=ir(t),u=(typeof r.output=="string"?r.output:Le(t).replace(/\n*Command exited with code \d+\s*$/,"")).trimEnd().split(`
|
|
22
|
+
`),a=u.slice(0,Nt);return u.length>Nt&&a.push(`\u2026 ${u.length-Nt} more line(s)`),a}var Sc={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 Cc(e){if(e==="read")return"read";if(e==="grep"||e==="find"||e==="glob")return"search";if(e==="ls")return"list"}function Zs(e,t=!1){let n=[],r,o=()=>{if(!r||r.indices.length<2){r=void 0;return}n.push({start:r.indices[0],indices:r.indices,counts:r.counts,summary:Ac(r.counts,t)}),r=void 0};for(let[u,a]of e.entries()){let g=Cc(a.toolName);if(g===void 0){o();continue}r||(r={indices:[],counts:{}}),r.indices.push(u),r.counts[g]=(r.counts[g]??0)+1}return o(),n}function Ac(e,t){let n=[];for(let r of["search","read","list"]){let o=e[r];if(o===void 0)continue;let u=Sc[r],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 ea(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 Mc=/^(?:\x1b_G|\x1b\]1337;File=)/;function or(e){return typeof e=="string"?En(e):En(e.map(t=>t.type==="text"?t.text:t.type==="thinking"?"":t.type==="image"?"[image]":(t.type==="toolCall","")).filter(Boolean).join(""))}function ta(e){return e.role==="user"?or(e.content).trim():""}function na(e,t,n){let r=t.trim();if(!r)return e;let o=e.findIndex(a=>a.kind==="user"&&a.body.trim()===r);if(o===-1)return[...e,{id:n,kind:"user",title:"you",body:r}];let u=[...e];return u[o]={id:n,kind:"user",title:"you",body:r},u}function Pc(e){return e.content.filter(t=>t.type==="toolCall").map(t=>({name:t.name,arguments:t.arguments}))}function Rc(e){return e.content.filter(t=>t.type==="toolCall").map(t=>t.id)}function Ic(e){let t=e.map(a=>({toolName:a.kind==="result"||a.kind==="tool"?a.title:"",line:a.call??a.body})),n=Zs(t);if(n.length===0)return e;let r=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=r.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 Wt(e){let t=[];for(let n of e)if(n.role==="user"){let r=or(n.content).trim();if(!r)continue;t.push({id:`u-${n.timestamp}`,kind:"user",title:"you",body:r})}else if(n.role==="assistant"){let r=or(n.content).trim(),o=Pc(n),u=Rc(n);r?t.push({id:`a-${n.timestamp}`,kind:n.stopReason==="error"?"error":"assistant",title:n.errorMessage?"failed":"fix",body:n.errorMessage?`${n.errorMessage}
|
|
23
|
+
|
|
24
|
+
${r}`:r}):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:Me(a.name,a.arguments),...b?{call:Me(a.name,a.arguments)}:{}})})}else if(n.role==="toolResult"){let r=jt(n.toolName,{content:n.content},n.isError),o=n.isError===!0||r.startsWith("exit ")&&r!=="exit 0",u=t.find(a=>a.id===`tool-${n.toolCallId}`);u?(u.kind="result",u.body=r,u.title=n.toolName,o&&(u.failed=!0)):t.push({id:`r-${n.toolCallId}`,kind:"result",title:n.toolName,body:r,...o?{failed:!0}:{}})}return Ic(t)}function Qs(e,t,n){return Ec(e,Math.max(8,t)).map(r=>A(r,n))}var ot=new Map;function _c(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 r=new Tc(t,0,0,ts);return ot.set(e.id,{text:t,component:r}),r}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,Ps(n,Rs))}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["",...Qs(`> ${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(`${Ft} ${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(` ${Ft}`,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=Is(Date.now()-(this.item.born??0),b.length);for(let C of b.slice(0,k)){if(Mc.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(` ${Ft} ${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["",...Qs(n,t,this.shade(o))]}return["",..._c(this.item).render(Math.max(8,t-2))]}},Dt=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 r=[],o=Date.now();for(let a of this.items)a.born===void 0&&(a.born=o,this.enteringUntil=Math.max(this.enteringUntil,o+400)),r.push(...new sr(a).render(t));this.status&&r.push(A(this.status,E.mute));let u=this.viewportHeight;if(u>0&&r.length>u){let a=r.length-u;this.scrollOffset!==this.settledOffset&&(this.scrollAnchor=void 0);let g=this.scrollAnchor,b;if(g!==void 0){let k=r.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=r.length-b),r.slice(a-b,a-b+u)}return r}};function ra(){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 ia(e,t){let n=e.trim();return n?!n.startsWith("sk-")&&t(n)?{kind:"credential",credential:n}:{kind:"token",token:n}:{kind:"browser"}}var oa="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%)")},sa={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 Ut(e){return $e[e]??$e.medium}var ar=[$e.minimal,$e.low,$e.medium,$e.high,$e.xhigh,$e.max];function la(e){return sa[e]??sa.medium}var aa=460;function Bt(e){return!Number.isFinite(e)||e<0||e>=aa?0:1-e/aa}var z=["off","minimal","low","medium","high","xhigh","max"];function ca(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 da(e){let t=z.indexOf(e);return z[(t+1+z.length)%z.length]}function ua(e){let t=z.indexOf(e);return z[(t-1+z.length)%z.length]}import{mkdirSync as Fc,readFileSync as jc}from"node:fs";import{dirname as Dc}from"node:path";var cr="\x1B[0m",Y="\x1B[2m",Lc="\x1B[1m",Oc="\x1B[31m",dr="\x1B[32m",ma="\x1B[33m",fa="\x1B[35m",lr="\x1B[36m";function V(e,t){return`${t}${e}${cr}`}function pa(e,t){return A(e,Ut(t))}function ga(e){return e>=85?Oc:e>=70?ma:dr}var Nc="\u2726";function ha(e,t,n,r,o){let u=o?o(`[${e}]`):V(`[${e}]`,lr),a=`${V(Nc,Y)} ${t}`,g=V(n,ma),b=r?` ${V("git:(",fa)}${V(r.replace(/^git:\(/,"").replace(/\)$/,""),lr)}${V(")",fa)}`:"";return`${u}${V(" \u2502 ",Y)}${a}${V(" \u2502 ",Y)}${g}${b}`}function ba(e,t,n){if(!t)return e;let r=n===void 0?t:`${t} ${V(is(n),Y)}`;return`${V(r,lr)} ${V("\u2502",Y)} ${e}`}function wa(e,...t){let n=Number.isFinite(e)?Math.min(100,Math.max(0,e)):0,r=Math.round(n/10),o=ga(n),u=`${o}${"\u2588".repeat(r)}${Y}${"\u2591".repeat(10-r)}${cr}`,a=V(`${Math.round(n)}%`,o),g=t.filter(Boolean).join(V(" \u2502 ",Y));return`${V("Context",Y)} ${u} ${a}${g?`${V(" \u2502 ",Y)}${g}`:""}`}function ya(e){return!Number.isFinite(e)||e<=0?"":`${V("Spent",Y)} ${V(`$${e.toFixed(3)}`,dr)}`}function ur(e,t,n,r){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=ga(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(/\.$/,"")} ${r}`:`${O.toFixed(2)} ${r}`;return[`${V(e,Lc)}${V(" account",Y)}`,` ${V("used",Y)} ${C} ${V(`${g.toFixed(1)}%`,k)}`,` ${V("granted",Y)} ${_(o)}`,` ${V("spent",Y)} ${_(u)}`,` ${V("remaining",Y)} ${V(_(a),k)}`]}function Oe(e,t,n){let r=n===null?"":V(` ${n}ms`,Y),o=t&&t!=="USD"?`${t} `:"";return`${V("Balance",Y)} ${V(`${o}${e}`,dr)}${r}`}var fr=Xe,Wc=18e4;async function Uc(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 Bc(){try{let e=JSON.parse(jc(fr,"utf8"));return!e.data||typeof e.cachedAt!="number"?void 0:{data:e.data,cachedAt:e.cachedAt}}catch{return}}function Vt(e){if(e.unlimited)return Oe("unlimited","",e.latencyMs);let n=e.unit==="USD"||e.unit==="CNY"?`$${e.remaining.toFixed(2)}`:`${e.remaining.toLocaleString()}`,r=e.limit>0?Math.min(100,(1-e.remaining/e.limit)*100):0,o=e.limit>0?`${n} ${r.toFixed(0)}%`:n;return Oe(o,e.unit,e.latencyMs)}async function ka(e){let t=Bc();if(t&&Date.now()-t.cachedAt<Wc)return Vt(t.data);let n=await Uc(e);if(!n)return t?Vt(t.data):void 0;let r=Date.now(),o=await Ie(n,{timeoutMs:3e3});if(!o.ok)return t?Vt(t.data):void 0;let u={remaining:o.remaining??0,limit:o.limit??0,unit:o.unit,unlimited:o.unlimited,latencyMs:Date.now()-r};return Fc(Dc(fr),{recursive:!0}),ie(fr,JSON.stringify({data:u,cachedAt:Date.now()})),Vt(u)}import{chmodSync as Vc,existsSync as Kc,readFileSync as Gc,rmSync as $a}from"node:fs";import{join as Hc}from"node:path";var va="howtofix-account",xa="howtofix",mr=new Map;function st(e,t){t?mr.set(e,t):mr.delete(e)}function Sa(e,t){let n=pr(e);if(!Kc(n))return!1;try{let r=JSON.parse(Gc(n,"utf8"));return typeof r.credential!="string"||r.credential.length===0?!1:(t.put({name:va,platform:xa,account:typeof r.username=="string"?r.username:void 0,value:r.credential}),$a(n,{force:!0}),!0)}catch{return!1}}function pr(e){return Hc(e,"account-credential.json")}function Ca(e,t){return Buffer.from(`${e}:${t}`,"utf8").toString("base64")}function gr(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)}},r=n(t);if(r)return r;try{let o=Buffer.from(t,"base64").toString("utf8");return o.includes(":")?n(o):null}catch{return null}}function Aa(e,t,n){let r=Ca(t,n),o=mr.get(e);if(o)try{return o.put({name:va,platform:xa,account:t,value:r}),$a(pr(e),{force:!0}),!0}catch{return!1}try{let u={credential:r,username:t,savedAt:Math.floor(Date.now()/1e3)},a=pr(e);return ie(a,JSON.stringify(u,null,2),{mode:384}),Vc(a,384),!0}catch{return!1}}async function qc(e,t){let n=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t),signal:AbortSignal.timeout(2e4)}),r=await n.text(),o;try{o=JSON.parse(r)}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 Ta(e,t,n,r){let o=await qc(`${e}/api/auth/cli/credential`,{credential:Ca(t,n),client_info:r});if(!o?.token)throw new Error("the panel accepted the credential but returned no key");return{token:o.token}}var zc="/cli/checkin",Yc=["Bearer",""].join(" ").trim(),Jc=5e5;function Ea(e){return`$${(e/Jc).toFixed(2)}`}async function Ma(e,t,n,r,o){let u=new AbortController,a=setTimeout(()=>u.abort(),o);try{let g=await r(`${n}${zc}`,{method:t,headers:{[Ci]:Ai(),"X-HowToCode-Device":lo().id,Authorization:`${Yc} ${e}`},signal:u.signal}),b={};try{b=await g.json()}catch{}return{status:g.status,body:b}}finally{clearTimeout(a)}}async function hr(e,t){let n=(t?.baseUrl??"https://api.howtofix.id/v1").replace(/\/+$/,""),r=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 Ma(u,"GET",n,r,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 Pa(e,t){let n=(t?.baseUrl??"https://api.howtofix.id/v1").replace(/\/+$/,""),r=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 Ma(u,"POST",n,r,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 H={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 Ra(e,t=15){let n=Math.max(0,Math.min(100,Number.isFinite(e)?e:0)),r=Math.round(n/100*t),o=t-r,u=H.green;n>=90?u=H.red:n>=75&&(u=H.yellow);let a=`${A("\u2588".repeat(r),u)}${A("\u2591".repeat(o),E.dim)}`,g=`${A(`${n.toFixed(1)}%`,u,{bold:!0})}`;return`${a} ${g}`}function Ia(e,t,n=54){let r=e.trim(),u=`\u256D\u2500${r?` ${X(r,{bold:!0})} `:""}`,a=F=>F.replace(/\x1B\[[0-9;]*m/g,""),g=Math.max(n-4,a(r).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${r?" ":""}`,H.dimLine)+(r?X(r,{bold:!0})+A(" ",H.dimLine):"")+A("\u2500".repeat(k)+"\u256E",H.dimLine),_=A("\u2570"+"\u2500".repeat(b)+"\u256F",H.dimLine),O=t.map(F=>{let W=a(F).length,K=" ".repeat(Math.max(0,b-W-2));return`${A("\u2502",H.dimLine)} ${F}${K}${A("\u2502",H.dimLine)}`});return[C,...O,_]}function _a(e){let{provider:t,usage:n,pools:r,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=[`${X("Cost:",{bold:!0})} ${A(O,H.green,{bold:!0})}`,`${X("Tokens:",{bold:!0})} ${k} ${A("in",E.dim)} \xB7 ${C} ${A("out",E.dim)} \xB7 ${_} ${A("cache",E.dim)}`,`${X("Messages:",{bold:!0})} ${Kt(u.totalMessages)} ${A(`(${u.toolCalls} tool calls)`,E.dim)}`];a.push(...Ia("Current Session",F)),a.push("")}let g=r?.unit??n.unit??"USD",b=[];if(!n.ok)b.push(`${X("Status:",{bold:!0})} ${A("Offline / Error",H.red)}`),b.push(`${A("Message:",E.dim)} ${n.message}`);else if(n.unlimited)if(b.push(`${X("Plan / Quota:",{bold:!0})} ${A("Unlimited tier",H.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(`${X("Wallet Spend:",{bold:!0})} ${Ra(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(`${X("Quota Usage:",{bold:!0})} ${Ra(C)}`),b.push(`${X("Balance:",{bold:!0})} ${A(le(k,g),H.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(`${X("Balance:",{bold:!0})} ${A(le(n.remaining,g),H.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(r&&(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",H.dimLine)),r.credit!==void 0&&b.push(`${X("Credit Pool:",{bold:!0})} ${le(r.credit,g)} ${A("(spendable on all models)",E.dim)}`),r.pro!==void 0&&(r.pro>0?b.push(`${X("Pro Credit:",{bold:!0})} ${A(le(r.pro,g),H.purple,{bold:!0})} ${A("(VIP priority lane active)",H.cyan)}`):b.push(`${X("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",H.dimLine)),o.checkedInToday){let k=o.quotaToday?` (+${le(o.quotaToday,g)})`:"";b.push(`${X("Daily Check-in:",{bold:!0})} ${A("\u2713 Claimed today"+k,H.green)}`)}else b.push(`${X("Daily Check-in:",{bold:!0})} ${A("\u25CB Ready to claim on next restart",H.yellow)}`);return a.push(...Ia(`${t} Account Limits`,b)),a.join(`
|
|
25
|
+
`)}function Xc(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 Zc(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 La(e){let t=Xc(e.contextWindow),n=Zc(e.cost);return[t?`${t} ctx`:"",n].filter(Boolean).join(" \xB7 ")}function Oa(){return{}}function Na(e,t,n,r=Date.now()){let o={...e};return t==="run"?(n===void 0||n===""?delete o.run:o.run={label:n,since:e.run?.since??r},o):(n===void 0||n===""?delete o[t]:o[t]=n,o)}function Fa(e,t){let n={...e};return t===void 0?delete n.retry:n.retry=t,n}function Qc(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 br(e,t=72){let n=e.split(`
|
|
26
|
+
`).map(r=>r.trim()).find(r=>r!=="")??"";return n.length>t?`${n.slice(0,t-1)}\u2026`:n}function ed(e,t){let n=Math.max(0,Math.ceil((e.until-t)/1e3)),r=n>0?`in ${n}s`:"now",o=`retry ${e.attempt}/${e.maxAttempts} ${r}`,u=br(e.error);return u===""?o:`${o} \xB7 ${u}`}function ja(e,t,n=Date.now()){return e.prompt?`? ${e.prompt}`:e.retry?`* ${ed(e.retry,n)}`:e.note?`* ${e.note}`:e.run?`${t} ${e.run.label} \xB7 ${Qc(n-e.run.since)}`:e.tally?e.tally:""}import{spawn as td}from"node:child_process";function nd(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=nd(t);return n?new Promise(r=>{try{let o=td(n.command,[...n.args,e],{detached:!0,stdio:"ignore"});o.once("error",()=>r(!1)),o.once("spawn",()=>{o.unref(),r(!0)})}catch{r(!1)}}):!1}function Da(e){return e instanceof Error?e.message:String(e)}var at=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 r=this.pending;this.pending=void 0;let o=await this.applyOnce(r);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(r=>n.has(r)),t.removed=[...new Set(t.removed.filter(r=>!n.has(r)))],t.added=[...new Set(t.added)],t.unchanged=[...new Set(t.unchanged.filter(r=>n.has(r)))],t}async applyOnce(t){let n=[...t].filter(u=>!this.active.has(u)),r=[...this.active].filter(u=>!t.has(u)),o=[...t].filter(u=>this.active.has(u));if(n.length===0&&r.length===0)return{added:[],removed:[],unchanged:o,problems:[]};try{await this.apply(n,r)}catch(u){let a=`mcp reconciliation failed: ${Da(u)}`;return this.report(a),{added:[],removed:[],unchanged:[],problems:[a]}}for(let u of n)this.active.add(u);for(let u of r)this.active.delete(u);return{added:n,removed:r,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 r=`mcp teardown failed: ${Da(n)}`;return this.report(r),{added:[],removed:[],unchanged:[],problems:[r]}}}};import{mkdirSync as rd}from"node:fs";import{join as id}from"node:path";import{matchesKey as Gt}from"@netrodev/hxf-tui";var wr=["all","running","failed","done"];function Ua(){return{selectedPhase:0,filter:"all",paused:!1,expanded:!1,follow:!0}}function Ba(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 Wa(e,t,n){if(t.length===0)return e;let r=Math.max(0,Math.min(t.length-1,e.selectedPhase+n));return{...e,selectedPhase:r,follow:!1}}function od(e){let t=wr.indexOf(e);return wr[(t+1)%wr.length]}function Va(e,t,n){switch(t){case"up":return Wa(e,n,-1);case"down":return Wa(e,n,1);case"enter":return{...e,expanded:!e.expanded};case"filter":return{...e,filter:od(e.filter)};case"pause":return{...e,paused:!e.paused};default:return e}}function Ka(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 Ga(e){return e==="all"?"":` \xB7 ${e}`}var Ha="ctrl+f";function qa(e,t,n=!0){if(!n)return"Ctrl+F panel keys \xB7 Esc unpin";let r=["\u2191/\u2193 phase",e.expanded?"Enter collapse":"Enter drill in"];return r.push(e.expanded?"Esc back out":"Esc unpin"),r.push(`f filter${e.filter==="all"?"":` (${e.filter})`}`),t?(r.push(e.paused?"p resume":"p pause"),r.push("x stop")):e.paused&&r.push("p resume"),r.push("s save script"),e.paused&&r.unshift("paused"),r.join(" \xB7 ")}function sd(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 za(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=sd(e.name);if(!n)return{ok:!1,reason:`"${e.name}" is not a usable filename, so the script was not written`};let r=id(t,`${n}.js`);try{rd(t,{recursive:!0}),ie(r,e.code)}catch(o){return{ok:!1,reason:o instanceof Error?o.message:String(o)}}return{ok:!0,path:r}}function Ya(e){let t=()=>{};return{select:(n,r)=>e.select(n,r),confirm:(n,r)=>e.confirm(n,r),input:n=>e.input(n),notify:(n,r)=>e.notify(n,r),onTerminalInput:()=>t,setStatus:(n,r)=>e.setStatus(n,r),setWorkingMessage:t,setWorkingVisible:t,setWorkingIndicator:t,setHiddenThinkingLabel:t,setWidget:(n,r,o)=>{r!==void 0&&!Array.isArray(r)||e.setWidget?.(n,r,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 ad,createDecipheriv as ld,randomBytes as kr,scryptSync as cd}from"node:crypto";import{existsSync as Ht,readFileSync as dd,rmSync as ud}from"node:fs";import{join as fd}from"node:path";function je(e){return fd(e,"vault.json")}var Ja=32768,Xa=8,Za=1,md=64*1024*1024,pd=32,Qa=16,gd=12,ne=class extends Error{constructor(t){super(t),this.name="VaultError"}};function yr(e,t,n){return cd(e,t,pd,{N:n.N,r:n.r,p:n.p,maxmem:md})}function hd(e,t){let n=kr(gd),r=ad("aes-256-gcm",e,n),o=Buffer.concat([r.update(t,"utf8"),r.final()]);return{name:"aes-256-gcm",iv:n.toString("base64"),tag:r.getAuthTag().toString("base64"),data:o.toString("base64")}}function bd(e,t){let n=ld("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 wd(e){return e.length<=4?"****":`\u2026${e.slice(-4)}`}var fe=class e{constructor(t,n,r,o){this.path=t;this.kdf=r;this.entries=o;this.key=n}path;kdf;entries;key;static exists(t){return Ht(je(t))}static create(t,n){let r=je(t);if(Ht(r))throw new ne("a vault already exists; unlock it instead of creating one");if(n.length<8)throw new ne("the master password must be at least 8 characters");let o=kr(Qa),u={name:"scrypt",N:Ja,r:Xa,p:Za,salt:o.toString("base64")},a=yr(n,o,u),g=new e(r,a,u,[]);return g.save(),g}static unlock(t,n){let r=je(t);if(!Ht(r))throw new ne("no vault found; create one first");let o;try{o=JSON.parse(dd(r,"utf8"))}catch{throw new ne("the vault file is not readable JSON")}if(o.version!==1||o.kdf?.name!=="scrypt"||o.cipher?.name!=="aes-256-gcm")throw new ne("the vault file was written by a version this CLI does not understand");let u=yr(n,Buffer.from(o.kdf.salt,"base64"),o.kdf),a;try{a=JSON.parse(bd(u,o.cipher))}catch{throw new ne("could not open the vault: wrong master password, or the file is damaged")}if(!Array.isArray(a))throw new ne("could not open the vault: the contents are not a credential list");return new e(r,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:wd(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 ne("a credential needs a name");if(!t.platform.trim())throw new ne("a credential needs a platform");if(!t.value)throw new ne("a credential needs a value");let n={...t,updatedAt:Math.floor(Date.now()/1e3)},r=this.entries.findIndex(o=>o.name===t.name);r>=0?this.entries[r]=n:this.entries.push(n),this.save()}remove(t){let n=this.entries.length;return this.entries=this.entries.filter(r=>r.name!==t),this.entries.length===n?!1:(this.save(),!0)}changePassword(t){if(t.length<8)throw new ne("the master password must be at least 8 characters");this.lock();let n=kr(Qa),r={name:"scrypt",N:Ja,r:Xa,p:Za,salt:n.toString("base64")};this.key=yr(t,n,r),this.kdf=r,this.save()}save(){let t=JSON.stringify(this.entries),n={version:1,kdf:this.kdf,cipher:hd(this.key,t)};ie(this.path,`${JSON.stringify(n,null,2)}
|
|
27
|
+
`,{mode:384})}};function el(e){let t=je(e);return Ht(t)?(ud(t,{force:!0}),!0):!1}var il={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)}},dl=Symbol.for("@netrodev/hxf-tui/layout-node");function Dd(e){if(typeof e!="object"||e===null)return;let t=e[dl];return typeof t=="function"?t.call(e):void 0}var Tr=kd(yd);async function ol(e){try{let{stdout:t}=await Tr("git",["-C",e,"rev-parse","--abbrev-ref","HEAD"],{encoding:"utf8"}),n=t.trim();if(!n||n==="HEAD")return"";let{stdout:r}=await Tr("git",["-C",e,"status","--porcelain"],{encoding:"utf8"});return`git:(${n}${r.trim()?"*":""})`}catch{return null}}var xr=550,Sr=650,Wd=Jt("#22d3ee"),Ud=Jt("#eaffff"),Bd=Jt("#22d3ee"),Vd=Jt("#dafa9b"),Er=class{folder;model;git;percent=0;meter=new Lt(0);sentAt=0;settledAt=0;activity=Oa();live=!1;activitySince=Date.now();thinking="medium";ceiling=void 0;usage="";cost=0;skipPermissions=!1;constructor(t,n){this.folder=xd(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",r=u=>({off:0,minimal:1,low:2,medium:3,high:4,xhigh:5,max:6})[u]??0,o=r(t)>r(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:Bt(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 Bt(n)<=0?pa(this.thinking,this.thinking):Ot(this.thinking,{rest:Ut(this.thinking),lit:la(this.thinking)},1-Bt(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<xr||this.settledAt>0&&t-this.settledAt<Sr}badgeFeedback(t){if(!ue)return;let n=t-this.settledAt;if(this.settledAt>0&&n>=0&&n<Sr)return o=>Ot(o,{rest:Bd,lit:Vd},n/Sr);let r=t-this.sentAt;if(this.sentAt>0&&r>=0&&r<xr)return o=>Ot(o,{rest:Wd,lit:Ud},r/xr)}waitedMs(){return Date.now()-this.activitySince}abandonAnimations(){this.meter.snap(this.percent)}render(t){let n=Date.now(),r=rt(),o=this.waitedMs(),u=this.percent===0&&this.meter.value===0?0:this.meterValue(),a=this.levelText(n),g=ha(this.model,a,this.folder,this.git,this.badgeFeedback(n)),b=[We(`${ba(g,this.live?r:"",this.live?o:void 0)} ${wa(u,this.usage,ya(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=Bo();k&&b.push(We(A(k,E.warn),t));let C=Oo(Rt());return C&&b.push(We(A(C,E.accent),t)),b}renderActivity(t){let n=Date.now(),r=rt(),o=this.waitedMs(),u=ja(this.activity,r,n),a=this.live?Ls(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)]}},Mr=class{constructor(t){this.draw=t}draw;render(t){return this.draw(t)}invalidate(){}},Pr=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),r=this.editor.render(n),o=C=>/^[─↑↓\d]*$/.test(C.replace(/\x1b\[[0-9;]*[A-Za-z]/g,"").trim()),u=r.length>=2&&o(r[0])&&o(r[r.length-1])?r.slice(1,-1):r,a=u.length>0?u:[""],g="\u2500".repeat(Math.max(0,t-2)),b=a.map(C=>{let _=Math.max(0,n-Ar(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 Kd(e,t,n,r=!1,o=[]){let{inner:u,line:a,bar:g,box:b}=ul(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===""?[""]:cl(O,u)).map(O=>a(O,F=>A(F,E.mute)));return fl(b,g,[...k,..._],r)}function Gd(e,t,n,r="esc close"){let{inner:o,line:u,bar:a,box:g}=ul(n),b=t.flatMap(C=>C===""?[""]:cl(C,o)),k=[u(` ${e} \xB7 ${r}`),...b.map(C=>u(C))];return fl(g,a,k,!1)}function ul(e){let t=Math.max(24,e),n=t-4,r=(o,u)=>{let a=Ar(o)>n?We(o,n,"\u2026"):o,g=`${a}${" ".repeat(Math.max(0,n-Ar(a)))}`;return`\u2502 ${u?u(g):g} \u2502`};return{box:t,inner:n,bar:"\u2500".repeat(t-2),line:r}}function fl(e,t,n,r){if(!r)return["",`\u250C${t}\u2510`,...n,`\u2514${t}\u2518`];let o=_s(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 Hd(e,t){let n=t.split(`
|
|
28
|
+
`).filter(Boolean),r=n.filter(a=>a.startsWith("Reason:")),o=n.filter(a=>!a.startsWith("Reason:")&&!a.startsWith("Allow tool:"));return[...e.endsWith(" wants to run")?[]:[e],...r,...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 Cr(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(([r,o])=>({name:r,description:o}));for(let r of e.promptTemplates)n.push({name:r.name,description:r.description});for(let r of e.extensionRunner.getRegisteredCommands())n.push({name:r.invocationName,description:r.description});return n}function Rr(e,t){if(e!=="workflow")return;let n=it(t);if(!(typeof n.name!="string"||!Array.isArray(n.steps)))return n}function qd(e,t){let n=Rr(e,t);return n?Yt(n):void 0}function Yt(e,t,n=!1){return r=>os(e,[],r,t?.selectedPhase,t?zd(e,t,n):void 0)}function zd(e,t,n){return{filter:r=>Ka(r,t.filter),footerText:qa(t,e.endedAt===void 0,n),filterLabel:Ga(t.filter),drill:t.expanded}}function Yd(){let e=new sl(ll,{"tui.altScreen.pageUp":[],"tui.altScreen.pageDown":[],"tui.altScreen.halfPageUp":[],"tui.altScreen.halfPageDown":[],"tui.altScreen.top":[],"tui.altScreen.bottom":[]});al(e)}async function Im(e){e.approval||xo(P);let t=new Rd,n,r=new Od(t,!0,void 0,{mouse:!0,onRightClickPaste:()=>n?.()}),o=new Dt,u=[],a=new Er(e.cwd,e.modelLabel);a.skipPermissions=jn();let g=i=>{(async()=>{try{let s=ct(),c=$.getSessionStats().sessionId;if(!Dr){Dr=!0;try{await gs(s,{keep:c})}catch{}}await fs(s,c,i)}catch{}})()},b=(i=!1)=>{!i&&!a.live||ol(e.cwd).then(s=>{s!==null&&(a.git=s,S())})},k=new Pd(r,il,{paddingX:1}),C=new Map,_=(i,s)=>{s===void 0?C.delete(i):typeof s=="function"?C.set(i,s):C.set(i,()=>s)},O,F=0,W=Ua(),K,ee=null,ve=!1,lt,pe=!1,ml,Xt=()=>{!K||!ve||_("workflow",i=>Yt(K,W,pe)(i))},Ir=()=>{K&&(lt=K.name),ve=!1,pe=!1,_("workflow",void 0)};ss({onStop:i=>{ee=i},isPaused:()=>W.paused});let _r=i=>{if(lt===i.name)return;O=i;let s=i.endedAt??Date.now();F=Math.max(F,s+ns),K=i,ve=!0,_("workflow",c=>Yt(i,W,pe)(c))},Lr=new Pr(k,a),$=e.session,Zt=e.dispose,Or=e.setCompressToolOutput,Nr=!1,Fr=e.session.getSessionStats().sessionId,Qt=()=>{let i=$.getSessionStats().cost;return a.cost=i,i},en=Vi(e.maxBudgetUsd),jr=!1,pl=()=>{let i=en.check(Qt());i===void 0||jr||(jr=!0,$.isStreaming&&$.abort(),m("budget",Ki(i.spent,i.limit)))},xe=()=>{a.ceiling=ca($.model)},be=go(P),J,tn,gl=async()=>!be||!po(be)||mo(be)?!1:(tn??=(async()=>{try{let i=await bo(P,be);return i.renewed?(be=i.credential,i.message&&m("connect",i.message),await $.modelRuntime.setRuntimeApiKey("howtocode",i.credential.accessToken),!0):(i.terminal&&(be=void 0),i.message&&m("connect",i.message),!1)}catch{return!1}finally{tn=void 0}})(),await tn),nn,ct=()=>nn??=ds(e.cwd),rn="",Dr=!1,Se,hl=()=>{let i=new Set(["session_info","usage","label","context_edit","custom","model_change","thinking_level_change"]),s=[],c=l=>{for(let f of l)i.has(f.entry.type)||s.push(f.entry.id),c(f.children)};return c($.sessionManager.getTree()),s},Wr=!1,bl=()=>{if(Wr)return;Wr=!0;let i=rl().getResolvedBindings();al(new sl(ll,{...i,"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"]}))},Ur=!1,wl=()=>{Ur||(Ur=!0,jd())},Br=()=>{let i=$.sessionManager.getTree();if(i.length===0){m("rewind","nothing to rewind to yet");return}ct().disabled&&m("rewind","conversation rewind only; this directory is not a git repository"),wl(),bl();let s=Math.max(8,Math.floor(t.rows*.6)),c=new Fd(i,$.sessionManager.getLeafId(),s*2,l=>{on(),yl(l)},()=>on());if(!c.getTreeList().getSelectedNode()){m("rewind","nothing to rewind to yet");return}Se=c,Se.focused=!0,_("rewind",l=>Se?.render(l)??[]),S()},on=()=>{Se=void 0,_("rewind",void 0),S()},yl=async i=>{let s=ct(),l=$.getUserMessagesForForking().findIndex(d=>d.entryId===i),f=l>=0?us(s,$.getSessionStats().sessionId)[l]:void 0,y=f?(await ps(s,f)).length:0;if(y===0){await Vr(i,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=>{Vr(i,f,d)})},Vr=async(i,s,c)=>{let l=[];if((c==="both"||c==="conversation")&&!$.isStreaming)try{let f=await $.navigateTree(i);if(f.cancelled){m("rewind","conversation rewind cancelled");return}l.push("conversation rewound"),o.items=Wt($.state.messages),f.editorText&&(k.setText(f.editorText),l.push("prompt restored to the editor"))}catch(f){G(`conversation rewind failed: ${f instanceof Error?f.message:String(f)}`);return}if((c==="both"||c==="code")&&s){let f=await ms(ct(),s);if(!f.ok){G(`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(...Wt($.state.messages)),a.percent=De($),Qt(),a.abandonAnimations(),a.setThinking($.thinkingLevel),xe(),k.setAutocompleteProvider(new nl(Cr($),e.cwd)),ka($).then(i=>{i&&(a.usage=i,r.requestRender())});let Kr=async i=>{let{checkForUpdate:s,checkFailedNote:c,installUpdate:l}=await import("./chunk-LYLJZVZ7.js"),f=await s(i.current);if(!f.available){let d=c(f);d?m("update",d):i.install&&m("update",f.message);return}if(!i.install){m("update",`${f.message}. run /update to install it.`);return}M("note",`installing HowToCode ${f.latest}\u2026`);let y=await l({version:f.latest});M("note",void 0),m("update",y.message),S()};e.update&&Kr(e.update);let ce=null,Gr="",sn=!1,Hr=[],Ce=null,qr=0,Ue,an=()=>{},S=()=>{an(),r.requestRender()},M=(i,s)=>{a.activity=Na(a.activity,i,s)},ln=i=>{a.activity=Fa(a.activity,i)},dt=new Map,cn=new Set,kl=()=>[...dt].map(([i,s])=>`${cn.has(i)?"!":"\u2713"} ${i} \xD7${s}`).join(" | "),$l=()=>{let i=kl();M("tally",i||void 0)},j=(i,s,c,l,f=!1,y=[])=>{let d=new Ld(s,8,il.selectList);d.onSelect=p=>{ce=null,Ue=void 0,c(p.value)},d.onCancel=()=>{ce=null,Ue=void 0,l?.(),S()},Ue=()=>d.onCancel?.(),Gr=i,sn=f,Hr=y,ce=d,Zr+=1,S()},m=(i,s)=>{o.items=ea(o.items,{id:`cmd-${Date.now()}-${o.items.length}`,kind:"note",title:i,body:s}),M("tally",void 0),S()},vl=(i,s)=>{Ce={title:i,body:s},qr+=1,S()},zr=()=>{Ce&&(Ce=null,S())};Yo(i=>{i.background&&m("agent",`${Ko(i)}
|
|
30
|
+
read it with /agents ${i.id}`)});let dn=!1,Yr=i=>{dn||(dn=!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=_t(s.map(h=>h.id)),{live:d,probed:p}=await so(y,f,{exclude:i,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{dn=!1}})())},G=i=>{o.items.push({id:`err-${Date.now()}-${o.items.length}`,kind:"error",title:"failed",body:i});let s=Rn(i);s!==void 0&&m("gateway",s);let c=Pn(i);c!==void 0&&Yr(c),M("tally",void 0),S()},Be=i=>{$.setThinkingLevel(i,{persist:!0}),a.setThinking(i),xe(),M("note",`thinking ${i}`),S()};Co((i,s)=>{let{promise:c,resolve:l}=Promise.withResolvers();return j(i,[{value:"allow",label:"allow"},{value:"deny",label:"deny"}],f=>l(f==="allow"),()=>l(!1),!0,Hd(i,s)),c});let ut=new Map,Jr=i=>{let s=Ya({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 M("prompt",c),S(),Z=y=>{Z=void 0,M("prompt",void 0),f(y),S()},l},notify:(c,l)=>{l==="error"?G(c):m("mcp",c)},setStatus:(c,l)=>{l===void 0?ut.delete(c):ut.set(c,l),M("note",[...ut.values()].join(" | ")||void 0),S()},setWidget:(c,l)=>{_(c,l),S()}});i.bindExtensions({uiContext:s,mode:"print",onError:c=>G(`${c.event}: ${c.error}`)}).catch(c=>G(c instanceof Error?c.message:String(c)))};Jr($);let Ae=new Md,xl={invalidate:()=>o.invalidate(),render:i=>{let s=Ae.render(Math.max(20,i)).length;return o.viewportHeight=Math.max(1,Math.max(8,t.rows)-s),o.render(i)},handleMouse:i=>{if(di(i))return He(),{handled:!0};ui(i)&&ci();let s=i.type==="wheel"?i.wheelDelta??0:0;if(s!==0)return o.scrollOffset=Math.max(0,o.scrollOffset-s*3),S(),{handled:!0}}},Sl=new Id(xl,{follow:"none",overscroll:"contain"}),ft=new Nd([{component:Sl,grow:1,shrink:1},{component:Ae,grow:0,shrink:0,basis:"auto"}]),Xr="",Zr=0,Cl=()=>`${ce?`picker:${Zr}`:Ce?`info:${qr}`:"dock"}|${[...C.keys()].join(",")}`;an=()=>{let i=Cl();if(i===Xr)return;Xr=i,Ae.clear();for(let l of C.values())Ae.addChild(new Mr(l));let s=ce,c=Ce;if(s){let l=Gr,f=sn,y=Hr;Ae.addChild({render:d=>Kd(s,l,d,f,y),invalidate:()=>{}})}else c?Ae.addChild({render:l=>Gd(c.title,c.body,l),invalidate:()=>{}}):Ae.addChild(Lr);ft.invalidate()},an();let Qr={focused:!1,invalidate(){o.invalidate(),Lr.invalidate(),ce?.invalidate(),ft.invalidate()},[dl]:()=>Dd(ft),render:i=>ft.render(i),handleMouse(i){if(ui(i)){ci();return}if(di(i))return He(),{handled:!0}},handleInput(i){k.handleInput(i)}};r.setLayoutRoot(Qr),r.setFocus(Qr);let Q=0,ge="",un=!1,Te=!1,fn,Pe="",ei=0,Ve=!1,mt=Date.now(),pt=!1,Ke=new Map,ti=()=>{let i=new Set($.getSteeringMessages().map(s=>s.trim()).filter(Boolean));for(let s of o.items)s.kind!=="user"||!s.pending||i.has(s.body.trim())||(s.pending=void 0)},ni=i=>{if(i.type==="agent_start"&&ti(),i.type==="agent_start"||i.type==="turn_start")i.type==="agent_start"&&$o(),a.live||a.beginRun(),ge="",Te=!1,Ve=!1,mt=Date.now(),Pe="";else if(i.type==="message_update"&&i.assistantMessageEvent.type==="thinking_delta"){Te=!0,Pe===""&&(ei=Date.now()),Pe+=i.assistantMessageEvent.delta;let s=`think-${Q}`,c=Mn(Pe).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(i.type==="message_update"&&i.assistantMessageEvent.type==="thinking_end"){let s=`think-${Q}`,c=o.items.find(l=>l.id===s);if(c){let l=Math.max(1,Math.round((Date.now()-ei)/1e3));c.title="thought",c.body=`${l}s \xB7 ${Pe.length} chars of reasoning`}Pe=""}else if(i.type==="message_update"&&i.assistantMessageEvent.type==="text_delta"){Te=!0,ge+=i.assistantMessageEvent.delta;let s=Mn(ge),c=`live-${Q}`,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(i.type==="tool_execution_start"){Ke.set(i.toolCallId,i.args),Te=!1,Ve=!1,mt=Date.now();let s=`tool-${i.toolCallId}`,c=Me(i.toolName,i.args),l=o.items.find(f=>f.id===s);if(l?(l.kind="tool",l.title=i.toolName,l.body=c,l.live=!0):o.items.push({id:s,kind:"tool",title:i.toolName,body:c,live:!0}),fn=i.toolName,i.toolName==="task"){let f=Go.filter(y=>y.status==="queued"||y.status==="running");M("note",f.map(y=>`${y.agent} ${y.status}`).join(" | ")||"agent running")}}else if(i.type==="tool_execution_update"){let s=qd(i.toolName,i.partialResult);if(s){let c=`tool-${i.toolCallId}`,l=o.items.find(y=>y.id===c);l?l.panel=s:o.items.push({id:c,kind:"tool",title:i.toolName,body:Me(i.toolName,Ke.get(i.toolCallId)),panel:s,live:!0});let f=Rr(i.toolName,i.partialResult);f&<!==f.name&&_r(f),S()}}else if(i.type==="tool_execution_end"){a.percent=De($);let s=o.items.find(x=>x.id===`tool-${i.toolCallId}`);s&&(s.live=!1,s.body=Me(i.toolName,Ke.get(i.toolCallId))),Ke.delete(i.toolCallId),fn=void 0,Te=!0,Ve=!1,dt.set(i.toolName,(dt.get(i.toolName)??0)+1),i.isError&&cn.add(i.toolName),$l();let l=[...Ys(i.result),...Js(i.toolName,i.result)],f=Xs(i.toolName,i.result),y=Rr(i.toolName,i.result),d=y?Yt(y):void 0;y&<!==y.name&&_r(y);let p=o.items.find(x=>x.id===`tool-${i.toolCallId}`),w=jt(i.toolName,i.result,i.isError),h=i.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-${i.toolCallId}`,kind:"result",title:i.toolName,body:w,...h?{failed:!0}:{},...l.length>0?{detail:l}:{},...f.length>0?{full:f}:{},...d?{panel:d}:{}}),(i.toolName==="bash"||i.toolName==="powershell"||i.toolName==="edit"||i.toolName==="write")&&b()}else if(i.type==="compaction_start"){Te=!0,Q+=1;let s=i.reason==="manual"?"on request":"context is nearly full",c=o.items.find(y=>y.id===`compact-${Q}`),l="compacting context",f=`${s} \xB7 summarizing the older turns`;c?(c.title=l,c.body=f):o.items.push({id:`compact-${Q}`,kind:"note",title:l,body:f,live:!0}),M("note","compacting context")}else if(i.type==="compaction_end"){let s=o.items.find(y=>y.id===`compact-${Q}`),c=i.result,l="compacted",f;if(i.aborted)f="cancelled";else if(i.errorMessage)f=`failed: ${i.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-${Q}`,kind:"note",title:l,body:f}),a.percent=De($),M("note",void 0)}else if(i.type==="message_start"&&i.message.role==="user"){let s=ta(i.message);s&&(o.items=na(o.items,s,`u-${i.message.timestamp}`)),ti()}else if(i.type==="message_end"&&i.message.role==="assistant"){let s=o.items.find(l=>l.id===`live-${Q}`);s&&(s.id=`done-${Q}`);let c=i.message.errorMessage;if(c&&s){s.title="failed",s.kind="error",s.body=ge.trim()?`${c}
|
|
34
|
+
|
|
35
|
+
${ge.trim()}`:c;let l=Rn(c);l!==void 0&&m("gateway",l);let f=Pn(c);f!==void 0&&Yr(f)}else c&&G(c);Q+=1,ge="",a.percent=De($)}else if(i.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(rn),rn="",M("run",void 0),un){let c=o.items.find(l=>l.id===`live-${Q}`);c?(c.id=`stopped-${Q}`,c.title="stopped",c.body=ge.trim()||"(no output)",c.live=!1):o.items.push({id:`stopped-${Q}`,kind:"note",title:"stopped",body:"run cancelled"}),Q+=1,ge="",m("stopped","run cancelled by Esc"),un=!1}a.percent=De($),M("note",void 0),ln(void 0),ol(e.cwd).then(c=>{c!==null&&(a.git=c,S())}),k.disableSubmit=!1}else i.type==="thinking_level_changed"?a.setThinking(i.level):i.type==="auto_retry_start"?(M("note",void 0),i.attempt%3===0&&i.attempt<i.maxAttempts&&ln({attempt:i.attempt,maxAttempts:i.maxAttempts,error:i.errorMessage,until:Date.now()+i.delayMs})):i.type==="auto_retry_end"&&(ln(void 0),i.success?m("retry",`answered on attempt ${i.attempt} after a retry`):M("note",`retry ${i.attempt} gave up${i.finalError?` \xB7 ${br(i.finalError)}`:""}`));pl(),S()},mn=$.subscribe(ni),ri=setInterval(()=>{let i=O!==void 0&&Date.now()<F,s=a.activity.retry!==void 0&&Date.now()<a.activity.retry.until;if((pt||a.live||$.isStreaming||a.settling()||o.entering()||ce!==null&&sn||i||a.flashing()||a.feedbackPlaying()||a.upgrading()||s)&&S(),(pt||$.isStreaming)&&!Te&&!Ve&&Date.now()-mt>Xd){Ve=!0;let c=fn,l=Math.round((Date.now()-mt)/1e3);M("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()}},Jd);ri.unref?.();let ii=async i=>{Ue?.(),Ue=void 0,Ce=null,mn(),nn&&hs(nn,$.getSessionStats().sessionId);let s=$.getSessionStats().sessionId;Un(s),Bn(s),_o(),ut.clear(),C.clear(),Ke.clear(),await ht.dispose(),await Zt(),$=i.session,Zt=i.dispose,Fr=i.session.getSessionStats().sessionId,Or=i.setCompressToolOutput,ht=new at({initial:Object.keys(ze().mcpServers),apply:async(c,l)=>{if(await gt(),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=>G(c)}),Q=0,ge="",o.items=[],o.scrollOffset=0,i.note&&o.items.push({id:"note",kind:"note",title:"note",body:i.note}),o.items.push(...Wt($.state.messages)),a.model=i.modelLabel.split("/").at(-1)||"no-model",a.setThinking($.thinkingLevel),xe(),a.percent=De($),Qt(),a.abandonAnimations(),M("tally",void 0),M("run",void 0),k.setAutocompleteProvider(new nl(Cr($),e.cwd)),k.disableSubmit=!1,Jr($),mn=$.subscribe(ni),S()},oi=!1,pn=i=>{if(!(oi||!i)){oi=!0;try{process.stdout.write(`
|
|
39
|
+
To continue this session: howtocode -c (in ${process.cwd()}) or howtocode resume ${i}
|
|
40
|
+
`)}catch{}}};process.on("exit",()=>pn(Fr));let Ge=async()=>{if(Nr)return;Nr=!0,clearInterval(ri),mn(),process.on("SIGINT",()=>{});let i=(()=>{try{return $.getSessionStats().sessionId}catch{return""}})();pn(i);try{let c=To(Ao);if(c.config.hooks.SessionEnd){let{outcome:l}=await Eo(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 ht.dispose();let s=$.getSessionStats().sessionId;en.close($.getSessionStats().cost),Un(s),Bn(s),await Zt(),r.stop(),process.stdout.write("\x1B[0m"),pn(s),process.exit(0)},si=0,gn=async(i=!1)=>{let s=Date.now();if(!i&&s-si<600*1e3)return;si=s;let c=f=>{if(process.env.HOWTOCODE_CHECKIN_DEBUG==="1")try{$d(`${P}/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 hr(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 Pa(h);return c(`claim ok=${v.ok} awarded=${v.quotaAwarded} msg=${v.message}`),v.ok?(m("check-in",`daily check-in claimed: +${Ea(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())},ai=async i=>{let s=en.check($.getSessionStats().cost);if(s!==void 0){G(`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:i,pending:c?!0:void 0}),c||(M("tally",void 0),dt.clear(),cn.clear(),M("run","thinking"),a.beginRun()),S(),k.disableSubmit=!1;let f=Us(ko(i,e.cwd),Bs);rn=i,await gl(),pt=!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);pt=!1,d.then(()=>gn()).catch(p=>G(p instanceof Error?p.message:String(p)))},hn=i=>{let s=i.trim();if(s){if(zr(),Z){let c=Z;Z=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}),M("run","shell"),S(),$.executeBash(c,l=>{M("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)"}),M("tally",void 0),S()}).catch(l=>G(l instanceof Error?l.message:String(l)));return}if(s.startsWith("/")){Je(s);return}ai(s)}};k.onSubmit=hn;let bn=0,we=ra(),li=0,He=()=>{Hn().then(async i=>{if(i.ok){u.push({type:"image",data:i.image.data,mimeType:i.image.mimeType}),k.insertTextAtCursor(`[image ${i.image.path}]`),m("paste",`image stored at ${i.image.path}`),S();return}let s=await xs();s.ok?k.insertTextAtCursor(s.text):m("paste",s.reason),S()}).catch(i=>{m("paste",`could not read the clipboard: ${i instanceof Error?i.message:String(i)}`),S()})};n=He;let ci=()=>{Hn().then(i=>{i.ok&&(u.push({type:"image",data:i.image.data,mimeType:i.image.mimeType}),k.insertTextAtCursor(Qn(i.image.path)),m("paste",`image stored at ${i.image.path}`),S())}).catch(()=>{})},Al=i=>{let s=[];for(let c of i){let l=Ds(c);if(!l){s.push(Ws(c));continue}try{tl(c).size<=Os&&u.push({type:"image",data:zt(c).toString("base64"),mimeType:l})}catch{}s.push(Qn(c))}k.insertTextAtCursor(`${s.join(" ")} `),m("paste",i.length===1?`attached ${i[0]}`:`attached ${i.length} files`),S()},di=i=>Mt(Ee(P).rightClickPaste)&&i.type==="press"&&i.button==="right",ui=i=>!Mt(Ee(P).rightClickPaste)&&process.platform==="win32"&&i.type==="press"&&i.button==="right";r.addInputListener(i=>{if(_d(i))return{consume:!0};if(Se){if(q(i,"escape"))return on(),{consume:!0};let l=rl(),f=l.matches(i,"tui.select.up"),y=l.matches(i,"tui.select.down");if(f||y){let p=Se.getTreeList().getSelectedNode()?.entry.id,w=hl(),h=p===void 0?-1:w.indexOf(p);if(f?h===0:h===w.length-1)return S(),{consume:!0}}return Se.handleInput(i),S(),{consume:!0}}if(Ce)return zr(),q(i,"escape")||q(i,"enter")?{consume:!0}:void 0;if(ve&&K&&q(i,"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")):(Ir(),m("workflow","panel unpinned; the run is still in the transcript")),Xt(),S(),{consume:!0};if(ce)return ce.handleInput(i),S(),{consume:!0};if(q(i,"escape")){if(we.disarm())return m("connect","sign-in cancelled \u2014 run /connect again when you have a token"),S(),{consume:!0};if($.isStreaming){un=!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(),M("note","stopping"),S(),{consume:!0}}let l=Date.now();if(k.getText().length===0&&l-bn<600)return bn=0,Br(),{consume:!0};bn=l;return}if(q(i,"ctrl+c")||ys(i)){if($.isStreaming)$.abort(),M("note","stopping"),S();else if(k.getText().length>0)k.setText(""),M("note","draft cleared; ctrl+c again quits"),S();else{let l=Date.now();l-li<2e3?Ge():(li=l,M("note","press ctrl+c again to quit"),S())}return{consume:!0}}if(q(i,"ctrl+d")&&k.getText().length===0)return Ge(),{consume:!0};let s=Math.max(1,o.viewportHeight-1);if(q(i,"pageUp"))return o.scrollOffset+=s,S(),{consume:!0};if(q(i,"pageDown"))return o.scrollOffset=Math.max(0,o.scrollOffset-s),S(),{consume:!0};if(q(i,"home"))return o.scrollOffset=Number.MAX_SAFE_INTEGER,S(),{consume:!0};if(q(i,"end"))return o.scrollOffset=0,S(),{consume:!0};let c=Ns(i);if(c!==void 0){if(Fs(c))return He(),{consume:!0};let l=js(c,f=>{try{return tl(f).isFile()}catch{return!1}});if(l)return Al(l),{consume:!0}}if(q(i,"ctrl+v")||q(i,"alt+v"))return He(),{consume:!0};if(q(i,"ctrl+l"))return o.scrollOffset=0,r.scrollToBottom(),S(),{consume:!0};if(q(i,"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(i,"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(i,"ctrl+t"))return Be(da(a.thinking)),{consume:!0};if(q(i,"ctrl+shift+t"))return Be(ua(a.thinking)),{consume:!0};if(q(i,Ha)&&ve&&K)return pe=!pe,m("workflow",pe?"panel keys active; Esc gives the keyboard back":"panel keys off; the editor has the keyboard"),Xt(),S(),{consume:!0};if(pe&&ve&&K){let l=Ba(i);if(l){let f=Kn(K,Date.now());if(l==="stop")return ee?(ee(),ee=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=za(ml,Ui);return m("workflow",y.ok?`saved ${y.path}`:y.reason),S(),{consume:!0}}return Object.assign(W,Va(W,l,f)),Xt(),S(),{consume:!0}}}});let wn=i=>{let s=c=>{M("prompt",`API key for ${c}. Paste it, then press enter.`),S();let l=Z;Z=f=>{Z=l;let y=f.trim();if(!y){M("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(i){s(i);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)))},fi=async(i,s)=>{let c=me(P,"models.json"),l,f=!1;try{l=JSON.parse(zt(c,"utf8"))}catch(te){if(!(te instanceof Error&&"code"in te&&te.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[i];y||(y=Xi(),l.providers[i]=y,f=!0);let d=Array.isArray(y.models)?y.models:[],p=io(d,s),w=await Zi(P).catch(()=>({index:new Map})),h=new Map,x=await ao((await $.modelRuntime.getAuth(i))?.auth?.apiKey??"",{groups:h}),v=Hi(h),T=to(d,s,w.index,x),I=v.size>0?no(T,w.index,x,v).models:T,N=ro(I);y.models=N.models;try{$r(P,{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}`:"",R=B?"":"; restart the CLI to see them all",D=f?` (created ${c})`:"";return p===0?`all ${s.length} models were already configured${L}${D}${R}`:`added ${p} model(s) to "${i}"${L}${D}${R}`},qe=(i,s)=>{(async()=>{if(!i){let h=await uo({onProgress:v=>{let T="";try{let N=me(P,".howtocode");$r(N,{recursive:!0,mode:448});let B=me(N,"connect-url.txt"),L=v.kind==="browser"?[v.url]:[v.url,`code: ${v.code}`];vr(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(),M("prompt",void 0),qe(h.token,h.credential);return}let x=await Fe(In);m("connect",[`browser sign-in: ${h.message}`,"","connect with a token instead:",` 1. ${x?"the keys page is opening in your browser":`open ${In}`}`," 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(!Qi(i)){m("connect","that does not look like a howtocode token; the Console issues tokens that start with sk-");return}M("note",`connecting to howtofix.id (${_n(i)})`),S();let c=await Ct(i);if(!c.ok){M("note",void 0),m("connect",c.message),S();return}let l=await fi("howtocode",c.models);await $.modelRuntime.setRuntimeApiKey("howtocode",i);let f;try{await $.modelRuntime.login("howtocode","api_key",{prompt:async()=>i,notify:()=>{}})}catch(h){f=`this sign-in could not be saved (${h instanceof Error?h.message:String(h)}); run /connect again after restarting`}s&&(ho(P,s)?be=s:f=`this sign-in renews itself, but the pair could not be saved to ${fo(P)}; 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=_t(h.map(T=>T.id)).slice(0,4);for(let T of v){if(!(await oo(T,i)).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)}M("note",void 0),gn(!0);let w=await Ie(i);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{$r(Sd(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 ${_n(i)} \u2014 ${c.message}`,l,mi("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=>{M("note",void 0),m("connect",c instanceof Error?c.message:String(c)),S()})},Tl=i=>{(async()=>{let s=gr(i);if(!s){m("connect",["that is not an account credential."," /connect <email>:<password>"," /connect <base64 of email:password>"].join(`
|
|
52
|
+
`)),S();return}M("note",`signing in as ${s.username}`),S();let{token:c}=await Ta(co,s.username,s.password,wt),l=Aa(P,s.username,s.password);M("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=>{M("note",void 0),m("connect",s instanceof Error?s.message:String(s)),S()})},mi=(i,s)=>{if(!s.ok)return[`${i} account`,` ${s.message}`].join(`
|
|
54
|
+
`);if(s.unlimited)return s.limit!==void 0&&s.used!==void 0?ur(i,s.limit,s.used,s.unit).join(`
|
|
55
|
+
`):[`${i} account`," quota no limit on this token"].join(`
|
|
56
|
+
`);if(s.limit===void 0||s.used===void 0){let c=[`${i} 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(i,s.limit,s.used,s.unit).join(`
|
|
58
|
+
`)},ze=()=>({mcpServers:Mo()}),El=i=>{let s=Object.keys(i??{});return s.length===0?[]:s.map(c=>` mcp ${c} ${kt(i[c])}`)},Ml=i=>{let s=Oi(i.dir,i.manifest),c=i.manifest.skills.join(", ");return[i.manifest.description,` category ${i.manifest.category}`,` version ${i.manifest.version}`,` skills ${c}`,i.manifest.prompt?` prompt ${i.manifest.prompt}`:" prompt (none)",` size ${s} bytes of skill text`,` source ${i.source}`,...El(i.manifest.mcp)].join(`
|
|
59
|
+
`)},pi=i=>{let s=[Ml(i),""];if(i.manifest.prompt){let c=me(i.dir,i.manifest.prompt);qt(c)&&s.push(`--- ${i.manifest.prompt} ---`,zt(c,"utf8").trim(),"")}for(let c of i.manifest.skills){let l=me(i.dir,"skills",c,"SKILL.md");qt(l)&&s.push(`--- skills/${c}/SKILL.md ---`,zt(l,"utf8").trim(),"")}return s.join(`
|
|
60
|
+
`)},gt=async()=>{await $.reload()},yn=!1,gi=async i=>{if(yn){m("preset","an install is already running; wait for it to finish");return}yn=!0;try{let s;try{s=await i()}catch(d){G(`preset not installed: ${d instanceof Error?d.message:String(d)}`);return}if(!s.ok||!s.name){G(`preset not installed:
|
|
61
|
+
${s.problems.join(`
|
|
62
|
+
`)}`);return}await gt();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 hi(s.name);l&&c&&vr(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){G(`preset installed but the session could not be refreshed: ${s instanceof Error?s.message:String(s)}`)}finally{yn=!1}},ht=new at({initial:Object.keys(ze().mcpServers),apply:async(i,s)=>{if(await gt(),i.length>0||s.length>0){let c=[];i.length>0&&c.push(`connected ${i.join(", ")}`),s.length>0&&c.push(`stopped ${s.join(", ")}`),m(i.length>0?"mcp connected":"mcp stopped",c.join("; "))}},report:i=>G(i)}),Ye=async()=>{let i=Object.keys(ze().mcpServers);return await ht.reconcile(i)},hi=async i=>{let{entries:s}=se(e.cwd),l=s.find(d=>d.manifest.name===i)?.manifest.mcp;if(!l||Object.keys(l).length===0)return"";let f=xn(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
|
+
`)}`:""},bi=i=>gi(async()=>Fi(i,vt(e.cwd))),wi=i=>{let s=i.sizeKb>=1024?`${(i.sizeKb/1024).toFixed(1)} MB`:`${i.sizeKb} KB`;return m("preset",[`downloading ${i.title}`,` from ${i.repo} @ ${i.sha.slice(0,7)}`,` skill ${i.skill}${i.modelInvocable===!1?" (invoke-only: the model cannot choose it)":""}`,` size ~${s} \xB7 ${i.license}`," checking the pinned commit and the contents the registry recorded\u2026"].join(`
|
|
69
|
+
`)),gi(()=>Wi(i,vt(e.cwd)))},kn=(i,s)=>{j(s,i.map(c=>({value:c.name,label:c.title,description:c.description})),c=>{let l=i.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"){wi(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}ki()})},()=>S())},Re=(i,s)=>{j(s,i.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=i.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"){bi(l.dir);return}if(f==="view"){m(`preset ${l.manifest.name}`,pi(l));return}xi("")})},()=>S())},yi=i=>i.filter(s=>s.manifest.integrates!==void 0),Pl=()=>{let{entries:i}=se(e.cwd),s=yi(i);if(s.length===0){m("integrations","nothing installed that drives another application. /preset lists the rest.");return}Re(s,"Integrations")},ki=()=>{let{entries:i}=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=yi(i).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"?$n():l==="integrations"?Pl():Rl())},$n=()=>{let{entries:i,problems:s}=Ti();if(s.length>0&&m("mcp problems",s.join(`
|
|
71
|
+
`)),i.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 Ei(i)){let d=Mi(i,y);l.set(y,()=>$i(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",()=>$i(i,"All MCP servers")),f.push({value:"all-mcp",label:"All servers",description:`${i.length} available${c.size>0?`, ${c.size} already configured`:""}`}),j("MCP servers",f,y=>l.get(y)?.())},$i=(i,s)=>{let c=ze().mcpServers;j(s,i.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=Pi(i,l);if(!f)return;let y=c[f.name]!==void 0,d=Ri(f),p=[f.description,"",`server ${f.name}`,`runs ${kt($t(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(Ii(),"mcp",f.preset.replace(/^mcp-/,""));if(qt(me(I,"preset.json"))){let N=Ni(I,vt(e.cwd));N.ok||x.push(...N.problems)}}let v=xn({[f.name]:$t(f)});if(x.push(...v.problems),x.length>0){G(`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 ${kt($t(f))}`,` connecting now; /mcp shows its state and its tools${T}`].join(`
|
|
76
|
+
`)),Ye().catch(I=>{G(`mcp installed but the session was not updated: ${I instanceof Error?I.message:String(I)}`)});return}if(h==="remove"){let x=yt([f.name]);if(x.problems.length>0){G(`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=>{G(`mcp removed from config but the session was not updated: ${v instanceof Error?v.message:String(v)}`)});return}$n()})},()=>$n())},Rl=()=>{let{entries:i,problems:s}=se(e.cwd),{entries:c,problems:l}=xt();s.length>0&&m("preset problems",s.join(`
|
|
79
|
+
`)),l.length>0&&m("preset problems",l.join(`
|
|
80
|
+
`));let f=i.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 _i(i)){let w=Li(i,p),h=Cn(c,p);y.set(p,()=>h.length>0?vi(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 Di(c)){if(i.some(h=>h.manifest.category===p))continue;let w=Cn(c,p);y.set(p,()=>kn(w,p)),d.push({value:p,label:p,description:`${w.length} to download`})}if(y.set("all",()=>Re(i,"All presets")),d.push({value:"all",label:"All presets",description:`${i.length} ready to install`}),c.length>0){y.set("hub",()=>vi([],"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)?.())},vi=(i,s,c)=>{if(c.length===0){Re(i,s);return}if(i.length===0){kn(c,`${s} (download)`);return}j(s,[{value:"local",label:`Included (${i.length})`,description:"already on disk, no download"},{value:"hub",label:`Downloadable (${c.length})`,description:"fetched when installed"}],l=>l==="local"?Re(i,s):kn(c,s))},xi=i=>{let[s,...c]=i.trim().split(/\s+/),l=c.join(" ").trim();if(!s){ki();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} [${Sn(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}`,pi(y));return}let{entries:d}=xt(),p=An(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}bi(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}=xt(),y=An(f,l);if(!y){m("preset add-hub",`"${l}" is not in the community registry. run /preset to browse it.`);return}wi(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"){vr(y,`disabled
|
|
85
|
+
`);let d=f.manifest.mcp?yt(Object.keys(f.manifest.mcp)):{removed:[],kept:[],problems:[]};Ye().then(()=>m("preset",`disabled ${l}${d.removed.length?`; stopped ${d.removed.join(", ")}`:""}`)).catch(p=>G(`preset disable failed: ${p instanceof Error?p.message:String(p)}`));return}vd(y,{force:!0}),hi(l).then(d=>gt().then(()=>m("preset",`enabled ${l}${d}`))).catch(d=>G(`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=ji(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?yt(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=>G(`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 i=>{let[s,...c]=i.slice(1).split(/\s+/),l=c.join(" ");if(s==="quit"||s==="exit"){Ge();return}if(s==="help"){m("help",Cr($).map(d=>`/${d.name} ${d.description??""}`).join(`
|
|
92
|
+
`));return}if(s==="trust"){let d=new Td(P),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(qt(d)&&l!=="force"){m("init",`AGENTS.md already exists at ${d}. run /init force to overwrite.`);return}ie(d,Si),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"){wn(l);return}if(s==="vault"){let[d="list",...p]=l.trim().split(/\s+/).filter(Boolean),w=x=>x instanceof ne||x instanceof Error?x.message:String(x),h=(x,v)=>{M("prompt",`${x} (not echoed, then press enter)`),S();let T=Z,I=()=>{Z=T,M("prompt",void 0)};we.arm(I),Z=N=>{we.disarm(),I(),v(N.trim())}};if(d==="init"||d==="create"){if(fe.exists(P)){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{J=fe.create(P,x),st(P,J),m("vault",`vault created at ${je(P)}
|
|
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(P)){m("vault","no vault yet \u2014 /vault init");return}h("master password",x=>{try{J=fe.unlock(P,x),st(P,J);let v=Sa(P,J);m("vault",`unlocked \u2014 ${J.list().length} credential(s)${v?"; plaintext account credential moved into the vault":""}`)}catch(v){m("vault",w(v))}});return}if(d==="lock"){if(!J){m("vault","the vault is already locked");return}J.lock(),J=void 0,st(P,void 0),m("vault","locked; the key is no longer in memory");return}if(d==="destroy"){if(!fe.exists(P)){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}J?.lock(),J=void 0,st(P,void 0),el(P),m("vault","vault destroyed");return}if(!J){m("vault",fe.exists(P)?"the vault is locked \u2014 /vault unlock":"no vault yet \u2014 /vault init");return}if(d==="list"||d==="ls"){let x=J.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}M("prompt",`paste the value for ${x} (not echoed), then press enter`),S();let I=Z,N=()=>{Z=I,M("prompt",void 0)};we.arm(N),Z=B=>{we.disarm(),N();let L=B.trim();if(!L){m("vault","no value given; nothing was stored");return}try{J.put({name:x,platform:v,...T?{account:T}:{},value:L}),m("vault",`stored ${x} (${v})${T?` as ${T}`:""}`)}catch(R){m("vault",w(R))}};return}if(d==="rm"||d==="remove"){let x=p[0];if(!x){m("vault","usage: /vault rm <name>");return}m("vault",J.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(P,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),J?.lock(),J=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=ia(l,w=>!!gr(w));if(d.kind==="credential"){Tl(d.credential);return}if(d.kind==="token"){qe(d.token);return}qe(""),M("prompt",oa),S();let p=Z;we.arm(()=>{Z=p,M("prompt",void 0)}),Z=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}M("note",`re-syncing ${p} from howtofix.id`),S();let h=(await $.modelRuntime.getAuth(p))?.auth?.apiKey;if(!h){M("note",void 0),m("sync",`${p} has no usable key; run /connect to sign in again`),S();return}let x=await Ct(h);if(!x.ok){M("note",void 0),m("sync",x.message),S();return}let v=await fi(p,x.models),T=await Ie(h);M("note",void 0),m("sync",`${v}
|
|
101
|
+
${mi(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}M("note","asking howtofix.id for the account usage"),S();let h=(await $.modelRuntime.getAuth(p))?.auth?.apiKey;if(!h){M("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),hr(h),eo(h)]);M("note",void 0);let I=$.getSessionStats?.(),N=_a({provider:p,usage:x,pools:T,checkin:v,sessionStats:I});vl("usage",N.split(`
|
|
102
|
+
`));return}if(s==="wallet"){let d=await Fe(St);m("wallet",d?`the Wallet is opening in your browser \u2014 top up Pro Credit there to use the VIP lane. ${St}`:`open ${St} 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){wn(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}`)},()=>wn(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"){M("note","checking for a newer release");try{await Kr({current:wt,install:!0})}finally{M("note",void 0)}return}if(s==="stats"){let d=$.getSessionStats(),p=$.getContextUsage(),w=v=>Number.isFinite(v)?String(v):";",h=$s($.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: ${vs(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 Tr("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=es(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 Ad(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=Cd(e.cwd,l||`howtocode-session-${Date.now()}.md`),w=[`# ${vn} 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 zo(d,w));return}m("agents",d?qo(d):Ho());return}if(s==="new"){let d=await e.reopen({noSession:!1});await ii(d),m("new","started a new session");return}if(s==="resume"){let d=await Ed.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(ii).catch(w=>G(w instanceof Error?w.message:String(w)))});return}if(s==="model"){let d=await $.modelRuntime.getAvailable(),p=d.filter(v=>oe(v.provider)),w=Ji(P),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=Yi(Tn),I=T?new Set(T.ids):void 0;if(!I){let L=(await $.modelRuntime.getAuth(v))?.auth?.apiKey;if(L){let R=await Ct(L);R.ok&&(I=new Set(R.models),zi(Tn,R.models))}}let N=qi(P),B=L=>oe(L.provider)?I&&!I.has(L.id)?"not on your account's plan":Gi(N.get(L.id)??[]):"";j("Select model",h.map(L=>({value:`${L.provider}/${L.id}`,label:L.id,description:[La(L),L.provider,B(L)].filter(Boolean).join(" \xB7 ")})),L=>{let R=h.find(D=>`${D.provider}/${D.id}`===L);R&&$.setModel(R,{persist:!0}).then(()=>{a.model=R.id,xe();let D=B(R);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(P).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(P,"compressToolOutput",w)){m("rtk","could not write the setting");return}Or(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=>{vo(p),So(P,p),m("approval",Nn[p])};if(!l){j("Approval mode",Et.map(p=>({value:p,label:p,description:Nn[p]})),p=>d(p));return}if(!Et.includes(l)){m("approval",`modes: ${Et.join(", ")}`);return}d(l);return}if(s==="settings"){let d=()=>jn()?"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"}],R=>{let D=R==="off",te=Ze(P,"skipPermissions",D);if(Fn(D),a.skipPermissions=D,S(),!te){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(R=>({value:R,label:R,description:R===a.thinking?"current":void 0})),R=>Be(R),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"}],R=>{let D=R!=="off",te=Ze(P,"autoUpdate",D);m("settings",te?`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 ${yo(`${P}/settings.json`)?"on":"off"}.`])},x=()=>{let R=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,R.split(`
|
|
113
|
+
`).slice(0,2))},v=()=>{Je("/model")},T=()=>{Je("/proxy")},I=()=>{let R=Ee(P).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"}],te=>{let bt=Po(P,te);m("settings",bt?te==="auto"?`right click follows the terminal \u2014 ${Mt("auto")?"the CLI pastes":"the terminal pastes"} here.`:`right click ${te==="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 ${R}.`])},N=()=>{let R=[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 ${Vo})`},...R],D=>{let te=D==="auto"?void 0:Number(D),bt=Ro(P,te);m("settings",bt?te===void 0?`agent concurrency follows the machine \u2014 ${et()} at a time.`:`agent concurrency set to ${te} \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:Ln(P)??On()??"none \u2014 direct to the API"},{value:"rightclick",label:"right click",description:`paste: ${Ee(P).rightClickPaste}`},{value:"agents",label:"agents",description:`${Ee(P).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,R=>{R==="permissions"?p():R==="thinking"?w():R==="dcp"?x():R==="autoupdate"?h():R==="model"?v():R==="proxy"?T():R==="rightclick"?I():R==="agents"&&N()});return}let L=B.find(R=>R.value===l||R.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 R=l==="off",D=Ze(P,"skipPermissions",R);Fn(R),a.skipPermissions=R,S(),m("settings",D?R?"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(R=>R.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=ls();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. Reload the extension (or restart Chrome) if it was already loaded \u2014
|
|
120
|
+
an old service worker will not pick up the stamped token.
|
|
121
|
+
Port and token are already set by the installer; nothing to paste.
|
|
122
|
+
|
|
123
|
+
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 cs(),w=p.state;m("browser-relay",`installed: ${p.tokenConfigured?"yes":"no \u2014 run /browser-relay install"}
|
|
124
|
+
extension dir: ${p.extensionDir}
|
|
125
|
+
relay running: ${p.running?`yes (127.0.0.1:${w?.port??as})`:"no (starts on the first browser tool call)"}
|
|
126
|
+
extension: ${w?.extensionConnected?"connected":"not connected"}
|
|
127
|
+
tabs: ${w?.tabs.length??0}
|
|
128
|
+
|
|
129
|
+
usage: /browser-relay install write the Chrome extension + token
|
|
130
|
+
/browser-relay status show this state`);return}if(s==="proxy"){let d=Ln(P),p=On(),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()}
|
|
131
|
+
usage: /proxy <url> route requests through a proxy
|
|
132
|
+
/proxy off stop using one
|
|
133
|
+
/proxy env use HTTPS_PROXY / HTTP_PROXY / ALL_PROXY
|
|
134
|
+
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(P,At,""),N=Tt(P),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(P,At,""),N=Tt(P),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=wo(h);if(!x.ok){m("proxy",`not set: ${x.problem}`);return}if(!Pt(P,At,x.url)){m("proxy","settings.json could not be written (is it valid JSON?)");return}let T=Tt(P);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(`
|
|
135
|
+
`):"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"){Br();return}if(s==="undo"){if(!await Vn(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(!Vn(e.cwd)){m("commit","not a git repository");return}if(!await Jo(e.cwd)){m("commit","nothing to commit");return}let d=l||`howtocode: session update ${new Date().toISOString().slice(0,16)}`,p=await Xo(e.cwd,d);m("commit",p.ok?p.output:`commit failed: ${p.output}`),b(!0);return}if(s==="review"){if(!(await Qo(e.cwd)).trim()){m("review","no changes to review");return}hn("Review the uncommitted changes. Report concrete issues with file evidence. Do not edit files.");return}if(s==="workflow"){if(l.trim()==="clear"){Ir(),m("workflow","cleared the pinned workflow panel");return}if(!K){m("workflow","no workflow run in this session yet");return}let d=Kn(K,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(`
|
|
136
|
+
`));return}if(s==="plan"){if(Uo()||It().state==="pending"){Wn(Do(It())),m("plan","plan mode off; edits are allowed again");return}Wn(jo(It())),m("plan",`plan mode armed \u2014 send your next prompt to start planning
|
|
137
|
+
plan file: ${Wo()??"(unknown)"}`);return}if(s==="goal"){let d=l.trim();if(!d){m("goal",Dn(Rt()));return}let{goal:p,error:w}=Fo(Rt(),"set",d,void 0,void 0);if(w){G(w);return}No(p),await $.sendCustomMessage({customType:Lo,content:d,display:!1,details:p}),m("goal",`goal set
|
|
138
|
+
${Dn(p)}`);return}if(s==="session"){let d=$.model;m("session",d?`${d.provider}/${d.id}`:"no model");return}if(s==="skills"){m("skills",ws($.resourceLoader.getSkills().skills));return}if(s==="preset"){xi(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=Sn(d.dir),w=$.getActiveToolNames().filter(x=>/roblox[-_]studio/i.test(x)),h=w.length>0;m("roblox",p?`RoToolbox: disabled
|
|
139
|
+
Enable with /preset enable rotoolbox
|
|
140
|
+
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(`
|
|
141
|
+
`));return}let f=bs(i,$.resourceLoader.getSkills().skills.map(d=>d.name));if(f){ai(f);return}let y=$.extensionRunner.getCommand(s??"");if(y){try{await y.handler(l,$.extensionRunner.createCommandContext())}catch(d){G(d instanceof Error?d.message:String(d))}return}m("command",`/${s??""} is not available in this screen yet`)};Io((i,s)=>{let{promise:c,resolve:l}=Promise.withResolvers();return j(i,s.map(f=>({value:f,label:f})),l,()=>l("cancelled")),c}),process.on("SIGTERM",Ge),ks(()=>{Ge()}),t.setTitle(`${vn} ${wt}`),Yd(),r.start(),r.requestRender(!0),gn(!0);{let{maybeShowWelcome:i}=await import("./chunk-PMWAHAZV.js");await i({cwd:e.cwd,note:e.note,signedIn:be!==void 0,runSlash:s=>{Je(s)},openExternal:s=>{Fe(s)}},j,m)}e.initialPrompt&&hn(e.initialPrompt),await new Promise(()=>{})}var Z,Jd=1e3/30,Xd=45e3;export{Pr as Dock,Er as Hud,Mr as PinnedBlock,Hd as approvalDetail,Gd as infoPanel,_t as orderModelsForDefault,Kd as pickerPanel,Im as runWorkbench,Cr as slashCommands,qd as workflowPanel,Yt as workflowPanelFromRun,Rr as workflowRunOf};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{b as c,d as l}from"./chunk-27TRKD65.js";import{
|
|
1
|
+
import{b as c,d as l}from"./chunk-27TRKD65.js";import{a as i,b as r}from"./chunk-DK3DYJTA.js";import{H as s}from"./chunk-5FIFNXLT.js";import"./chunk-UTYFLLSM.js";import"./chunk-WOT6VMZA.js";var d=[["/connect","sign in to howtofix.id: approve it in your browser"],["/model","choose which model answers"],["/help","list every command"],["/quit","leave"]],u=[" \u2588\u2588\u2557 \u2588\u2588\u2557\u2588\u2588\u2557 \u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557"," \u2588\u2588\u2551 \u2588\u2588\u2551\u255A\u2588\u2588\u2557\u2588\u2588\u2554\u255D\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D"," \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551 \u255A\u2588\u2588\u2588\u2554\u255D \u2588\u2588\u2588\u2588\u2588\u2557 "," \u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2551 \u2588\u2588\u2554\u2588\u2588\u2557 \u2588\u2588\u2554\u2550\u2550\u255D "," \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2554\u255D \u2588\u2588\u2557\u2588\u2588\u2551 "," \u255A\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u255D "],g=[" _ _ _____ ","| | | | __ __ | ___|","| |_| | \\ \\/ / | |_ ","| _ | > < | _| ","|_| |_| /_/\\_\\ |_| "];function m(){if(process.platform==="win32")return!1;let e=(process.env.LC_ALL||process.env.LC_CTYPE||process.env.LANG||"").toLowerCase();return e===""||e==="c"||e==="posix"||!e.includes("utf-8")&&!e.includes("utf8")?!1:!/ja|ko|zh|_kr|_jp|_cn|_tw|_hk/.test(e)}function h(){return m()?u:g}var _="https://howtofix.id/cli";function p(e){let n=process.env.HOME??"",t=n!==""&&e.startsWith(n)?`~${e.slice(n.length)}`:e,o=t.split("/").filter(Boolean);return o.length>3?`\u2026/${o.slice(-2).join("/")}`:t}function f(e){let n=e.signedIn?d.filter(([t])=>t!=="/connect"):d;return[...h(),"",`${i} ${r} \u2014 a terminal coding agent. Describe the change you want and it reads, edits and runs the code in front of you.`,"",` working in ${p(e.cwd)}`,...e.note?[` session ${e.note}`]:[],"",...e.signedIn?[" already signed in to howtofix.id",""]:[],...n.map(([t,o])=>` ${t.padEnd(11)}${o}`),"",' Or just start typing. Every message goes to the model; anything beginning with "/" stays local.'].join(`
|
|
2
2
|
`)}function v(){return[{value:"connect",label:"Sign in to howtofix.id",description:"approve the sign-in in your browser"},{value:"ready",label:"I have a key \u2014 just give me the prompt",description:"drops you at the prompt; run /connect whenever you like"},{value:"release",label:"What's in this release",description:`opens the ${r} notes in your browser`}]}async function E(e,n,t){c(s).welcomeSeen||(l(s),t(`welcome to ${i}`,f(e)),!e.signedIn&&await new Promise(o=>{n("First run \u2014 how do you want to begin?",v(),a=>{a==="connect"&&e.runSlash("/connect"),a==="release"&&e.openExternal(_),o()},()=>o())}))}export{E as maybeShowWelcome};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{q as f,r as p}from"./chunk-
|
|
1
|
+
import{q as f,r as p}from"./chunk-5FIFNXLT.js";import"./chunk-UTYFLLSM.js";import"./chunk-WOT6VMZA.js";import{execFileSync as v}from"node:child_process";import{existsSync as m,mkdirSync as x,readFileSync as S,readdirSync as j,statSync as $,writeFileSync as z}from"node:fs";import{join as i,relative as b,resolve as d}from"node:path";function F(o){let e=o.replace(/-/g," ").replace(/\b\w/g,t=>t.toUpperCase());return[{path:"preset.json",body:`${JSON.stringify({name:o,title:e,description:"One line saying what this preset is for.",category:"engineering",version:"1.0.0",skills:[`${o}-skill`]},null,2)}
|
|
2
2
|
`},{path:"prompt.md",body:["Rules the model should follow while this preset is active.","","This text is appended to the system prompt, never substituted for it, so it","adds to the agent's own rules rather than replacing them. Delete this file if","the preset only needs skills.",""].join(`
|
|
3
3
|
`)},{path:i("skills",`${o}-skill`,"SKILL.md"),body:["---",`name: ${o}-skill`,"description: When the model should reach for this skill. This line is what"," the model reads when deciding, so say when to use it, not what it contains.","---","",`# ${e}`,"","What the model should do, as instructions. A skill is read on demand: only the","frontmatter above is in every request, so the body costs nothing until used.","","Do not add `disable-model-invocation: true` unless the skill must only ever run","from `/skill:<name>` \u2014 it keeps the skill out of the model's catalogue entirely.",""].join(`
|
|
4
4
|
`)}]}function g(){return["usage:"," howtocode preset new <name> [dir] write a preset skeleton"," howtocode preset check [dir] validate a preset with the installer's rules"," howtocode preset pack [dir] build <name>-<version>.tar.gz for publishing","","A preset is a directory holding preset.json, an optional prompt.md, and a","skills/ tree. `check` runs the same validation the installer runs, so a preset","that passes here will not be refused at install."].join(`
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{I as s,J as l}from"./chunk-
|
|
1
|
+
import{I as s,J as l}from"./chunk-5FIFNXLT.js";function c(i){return[s,l(i)]}function d(i,n){let t=i.trim(),r=/^\/skill:([^\s]+)(?:\s+([\s\S]*))?$/.exec(t)??/^\/skill\s+([^\s]+)(?:\s+([\s\S]*))?$/.exec(t);if(!r)return;let e=r[1]??"";if(!n.includes(e))return;let o=(r[2]??"").trim();return o?`/skill:${e} ${o}`:`/skill:${e}`}function u(i){if(i.length===0){let[n,t]=c(process.cwd());return["no skills loaded.",`put a SKILL.md in ${n}`,`or in ${t}`,"invoke with /skill:<name>"].join(`
|
|
2
2
|
`)}return i.map(n=>{let t=n.disableModelInvocation?" (invoke only)":"";return`${n.name}${t}
|
|
3
3
|
${n.description}
|
|
4
4
|
${n.filePath}`}).join(`
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as v}from"./chunk-7LA2AMZB.js";import{
|
|
1
|
+
import{a as v}from"./chunk-7LA2AMZB.js";import{h as M,i as T}from"./chunk-W34I6VMP.js";import{a as w}from"./chunk-UTYFLLSM.js";import{existsSync as H,mkdirSync as I,readFileSync as b}from"node:fs";import{join as k}from"node:path";var J="https://models.dev/api.json";var N=["anthropic","openai","google","deepseek","zai","xai","moonshotai","minimax","alibaba","xiaomi","meta","tencent","nvidia","venice","openrouter"];function _(n){return n.toLowerCase().replace(/[^a-z0-9]+/g,"")}function S(n){let e=n.split("/");return _(e[e.length-1]??n)}function q(n){let e=new Map,s=new Map;if(!n||typeof n!="object")return e;let t=n,r=c=>{let o=N.indexOf(c);return o===-1?N.length:o};for(let c of Object.keys(t).sort()){let o=t[c]?.models;if(!(!o||typeof o!="object"))for(let a of Object.keys(o)){let i=o[a],u=Number(i?.limit?.context);if(!Number.isFinite(u)||u<=0)continue;let l=_(a),f=r(c),d=s.get(l);if(d!==void 0&&d<=f)continue;let m=Number(i?.limit?.output);e.set(l,{contextWindow:Math.floor(u),maxTokens:Number.isFinite(m)&&m>0?Math.floor(m):void 0,reasoning:i?.reasoning===!0,vision:Array.isArray(i?.modalities?.input)&&i.modalities.input.includes("image")}),s.set(l,f)}}return e}function A(n,e){let s=_(e);if(!s)return;let t=n.get(s);if(t)return t;let r=S(e);for(let[c,o]of n)if(S(c)===r)return o;for(let[c,o]of n)if(c.endsWith(s)||s.endsWith(c))return o}function R(n){return`${n}/models-dev-cache.json`}function $(n){let e={};for(let[s,t]of n)e[s]=[t.contextWindow,t.maxTokens??0,t.reasoning?1:0,t.vision?1:0];return JSON.stringify(e)}function P(n){let e=new Map,s;try{s=JSON.parse(n)}catch{return e}if(!s||typeof s!="object")return e;for(let[t,r]of Object.entries(s)){if(!Array.isArray(r)||r.length<3)continue;let c=Number(r[0]),o=Number(r[1]);!Number.isFinite(c)||c<=0||e.set(t,{contextWindow:Math.floor(c),maxTokens:Number.isFinite(o)&&o>0?Math.floor(o):void 0,reasoning:r[2]===1||r[2]===!0,vision:r[3]===1||r[3]===!0})}return e}async function U(n){let e=n?.url??J,s=n?.fetchImpl??fetch,t=n?.timeoutMs??2e4,r=new AbortController,c=setTimeout(()=>r.abort(),t);try{let o=await s(e,{signal:r.signal,headers:{Accept:"application/json"}});if(!o.ok)return{ok:!1,message:`the model catalogue answered ${o.status}`};let a=q(await o.json());return a.size===0?{ok:!1,message:"the model catalogue was empty or in an unexpected shape"}:{ok:!0,index:a}}catch(o){return{ok:!1,message:o instanceof Error&&o.name==="AbortError"?`the model catalogue did not answer within ${Math.round(t/1e3)}s`:"could not reach the model catalogue"}}finally{clearTimeout(c)}}var x="https://api.howtofix.id/v1",ce=v,C=["howtocode","howtocode-free"];function ue(n){try{let s=JSON.parse(b(k(n,"models.json"),"utf8")).providers;return!s||typeof s!="object"?new Set:new Set(Object.keys(s))}catch{return new Set}}function le(){return{baseUrl:x,api:"openai-completions",headers:{[M]:T()}}}function de(n){let e=k(n,"models.json"),s;try{s=JSON.parse(b(e,"utf8"))}catch{return 0}let t=s.providers;if(!t||typeof t!="object")return 0;let r=0;for(let c of C){let o=t[c];if(!o||!Array.isArray(o.models))continue;let a=Y(o.models),i={...o.headers??{},[M]:T()},u=o.headers?.[M]!==i[M];a.changed===0&&!u||(o.models=a.models,o.headers=i,r+=a.changed===0?1:a.changed)}if(r===0)return 0;try{w(e,`${JSON.stringify(s,null,2)}
|
|
2
2
|
`)}catch{return 0}return r}var G=10080*60*1e3;async function F(n,e){let s=R(n),t=e?.now??Date.now(),r,c=0;try{let i=JSON.parse(b(s,"utf8"));typeof i?.entries=="string"&&(r=P(i.entries),c=Number(i.at)||0)}catch{r=void 0}if(r&&r.size>0&&t-c<G&&!e?.force)return{index:r};let a=await U({fetchImpl:e?.fetchImpl});if(!a.ok)return r&&r.size>0?{index:r,message:a.message}:{index:new Map,message:a.message};try{I(n,{recursive:!0}),w(s,`${JSON.stringify({at:t,entries:$(a.index)})}
|
|
3
3
|
`)}catch{}return{index:a.index}}async function fe(n,e){let s=k(n,"models.json"),t;try{t=JSON.parse(b(s,"utf8"))}catch{return{changed:0}}let r=t.providers;if(!r||typeof r!="object")return{changed:0};let{index:c,message:o}=await F(n,e);if(c.size===0&&!e?.prices&&!e?.tiers)return{changed:0,message:o};let a=0;for(let i of C){let u=r[i];if(!u||!Array.isArray(u.models))continue;let l=Z(u.models,c,e?.prices,e?.tiers);l.changed!==0&&(u.models=l.models,a+=l.changed)}if(a>0)try{w(s,`${JSON.stringify(t,null,2)}
|
|
4
4
|
`)}catch{return{changed:0,message:"the models file could not be written"}}return{changed:a,message:o}}var B=3e5;function me(n){let e=k(n,"settings.json"),s={};try{let t=b(e,"utf8"),r=JSON.parse(t);r&&typeof r=="object"&&!Array.isArray(r)&&(s=r)}catch{if(H(e))return!1}if("httpIdleTimeoutMs"in s)return!1;s.httpIdleTimeoutMs=B;try{I(n,{recursive:!0}),w(e,`${JSON.stringify(s,null,2)}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a,b,c,d,e,f,g,h,i,j,k,l,m,n}from"./chunk-
|
|
1
|
+
import{a,b,c,d,e,f,g,h,i,j,k,l,m,n}from"./chunk-5FIFNXLT.js";import"./chunk-UTYFLLSM.js";import"./chunk-WOT6VMZA.js";export{e as RETIRED_ROBLOX_BRIDGE,c as addMcpServers,g as describeMcpServer,a as mcpConfigPath,j as mcpHubCategories,l as mcpHubFind,k as mcpHubIn,h as mcpHubPath,n as missingEnvFor,i as readMcpHub,d as removeMcpServers,f as retireRobloxBridge,m as serverSpecFromEntry,b as validateMcpBlock};
|