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