howtofixcli 0.7.18 → 0.7.19
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/dist/chunk-3LZR7OEU.js +1 -0
- package/dist/{chunk-5H5C2E2U.js → chunk-A444ANBX.js} +1 -1
- package/dist/{chunk-5UXXGGP7.js → chunk-AKKVDSRL.js} +1 -1
- package/dist/chunk-GBWEIWLX.js +116 -0
- package/dist/{chunk-YVF3HZNM.js → chunk-GCKLZQH4.js} +1 -1
- package/dist/{chunk-OOJLL5GO.js → chunk-ID7ZE5GD.js} +1 -1
- package/dist/{chunk-2PZYTRC4.js → chunk-MXY5C2ZU.js} +1 -1
- package/dist/{chunk-YY42KW6I.js → chunk-NOB2BWQL.js} +1 -1
- package/dist/{chunk-NIDYKFDX.js → chunk-RGWW5HLM.js} +1 -1
- package/dist/{chunk-KIHCI6W4.js → chunk-TFSJ4NIX.js} +1 -1
- package/dist/{chunk-SVE3XYTR.js → chunk-U3H4GCLE.js} +1 -1
- package/dist/{chunk-SIXFT6QP.js → chunk-UENU6N7M.js} +1 -1
- package/dist/{chunk-GNV656Y4.js → chunk-VB72QUU5.js} +1 -1
- package/dist/main.js +10 -11
- package/package.json +1 -1
- package/dist/chunk-6FUWMLWO.js +0 -1
- package/dist/chunk-BFX5IV5E.js +0 -116
- package/dist/chunk-MOKUBKE7.js +0 -1
- package/dist/chunk-VLMQSD25.js +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var o=/no available channel for model\s+([^\s"',)\]]+)/i;function s(t){let e=t??"";if(e.trim())return o.exec(e)?.[1]}function a(t){let e=t??"";if(!e.trim())return;let n=s(e);if(n)return`the gateway has no live channel for ${n} right now \u2014 /model lists the models that answer; pick another.`;if(/\bmissing api key\b|\bauthenticationerror\b|\bauth\s*error\b/i.test(e))return"no key for this model yet \u2014 /connect signs you in and pulls the model list.";if(/\bunknown model\b/i.test(e))return"/connect pulls the current model list from the gateway.";if(/\bcode 11128\b|\billegal api invocation\b/i.test(e))return"the gateway refused the request shape (code 11128) \u2014 /connect re-syncs each model's compatibility flags.";if(/\binsufficient (?:balance|quota|credit)\b|\bexceeded your current quota\b|http\s*402/i.test(e))return"the account is out of credit \u2014 /usage shows what is left.";if(/\bserver error\b|http\s*5\d\d/i.test(e))return"the gateway's channel is failing, not the CLI \u2014 /model lists what your account can reach; pick another.";if(/\brate.?limit|\b429\b/i.test(e))return"the gateway is rate-limiting this token \u2014 wait a moment, then resend the prompt.";if(/\bprompt (?:is )?too long\b|\bprompt too long\b|\bexceeds? (?:the )?(?:model'?s )?maximum context length\b|\bmaximum context length is \d+ tokens\b|\bexceeds the context window\b|\bcontext[_ ]length[_ ]exceeded\b|\breduce the length of the messages\b/i.test(e))return"the conversation is past this model's context window \u2014 /compact summarises it and continues, or /model picks a model with a bigger window.";if(/\bupstream api error\b/i.test(e))return"the gateway refused the request \u2014 run /connect again to re-sync your models."}function u(t){let e=0,n;return{limit:t,close(r){e+=r},total(r){return e+r},check(r){if(t===void 0||n!==void 0)return n;let i=e+r;return i-t>1e-9&&(n={spent:i,limit:t}),n}}}function c(t,e){return`stopped \u2014 spent $${t.toFixed(4)} of a $${e.toFixed(2)} budget.`}function l(t,e){return`--max-budget-usd needs a model with prices, and ${t} declares none (its rates are zero, so every turn costs $0 and the budget would never fire). Add a cost to that model in ${e}/models.json, or drop the flag.`}export{s as a,a as b,u as c,c as d,l as e};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a,b,c,d,e,f,g,h,i,j}from"./chunk-
|
|
1
|
+
import{a,b,c,d,e,f,g,h,i,j}from"./chunk-UENU6N7M.js";import"./chunk-RGWW5HLM.js";import"./chunk-WOT6VMZA.js";export{h as CLI_CLIENT_HEADER,a as CLI_SIGNING_KEY_ID,i as cliClientHeader,c as cliSignaturePayload,f as cliSigningKeyFingerprint,e as cliSigningKeyMatchesPanel,b as cliSigningPublicKey,d as createNonce,g as describeClient,j as signLoginRequest};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{c as a,d as b,e as c,f as d,g as e,h as f,i as g,j as h,k as i}from"./chunk-
|
|
1
|
+
import{c as a,d as b,e as c,f as d,g as e,h as f,i as g,j as h,k as i}from"./chunk-GCKLZQH4.js";import"./chunk-UTYFLLSM.js";import"./chunk-UENU6N7M.js";import"./chunk-RGWW5HLM.js";import"./chunk-WOT6VMZA.js";export{b as CLI_REFRESH_SKEW_MS,c as accessTokenIsFresh,g as clearCliCredential,a as cliCredentialsPath,e as readCliCredential,h as refreshCliCredential,d as refreshTokenIsUsable,i as renewCliCredentialIfNeeded,f as writeCliCredential};
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
import{b as vs,c as xs}from"./chunk-WX3V5P7U.js";import{a as Ke}from"./chunk-LSJC73DG.js";import{a as ft,b as un,c as fn,d as Rr,e as mt}from"./chunk-3FYCFLNK.js";import{u as Er}from"./chunk-WUPU6LTD.js";import{a as Pr}from"./chunk-ORJ2QZBG.js";import{Aa as ss,Ba as is,C as gt,Ca as as,D as Br,Da as ls,F as Gr,Fa as ae,Ga as T,Ha as O,I as qr,Ia as cs,J as Vr,Ja as ds,K as bt,Ka as us,L as zr,La as fs,M as Yr,Ma as vn,N as Xr,Na as ms,O as wn,Oa as ps,Ra as hs,Sa as gs,Ta as bs,U as De,Ua as ws,Va as ys,Wa as ks,X as yn,Xa as $s,Z as kn,aa as We,c as Lr,e as Nr,g as Fr,ga as Jr,h as jr,ha as Ue,ja as wt,n as Ur,na as Zr,oa as Qr,qa as es,ra as ts,sa as ns,va as os,w as Kr,y as bn,ya as $n,z as Hr,za as rs}from"./chunk-AUDMRGWF.js";import{a as Ir,c as pt,d as mn,j as _r,l as pn,m as hn,n as Or}from"./chunk-JFYVRWJI.js";import{b as ke,c as je,e as Dr,f as gn,g as Wr,h as ht}from"./chunk-27TRKD65.js";import{a as sr,b as ir,c as ar,d as lr}from"./chunk-3LZR7OEU.js";import{A as sn,B as an,C as nr,D as P,I as or,J as rr,b as on,c as at,d as lt,e as Ho,f as Bo,g as Go,h as qo,i as ct,j as Vo,k as rn,l as zo,o as te,p as Yo,q as Xo,t as Jo,u as Zo,v as Qo,w as er,x as dt,y as ut,z as tr}from"./chunk-V656XVXV.js";import{A as dn,B as kr,b as ln,c as ye,d as ur,e as fr,h as mr,n as cn,o as pr,q as oe,s as Ae,u as hr,w as gr,x as br,y as wr,z as yr}from"./chunk-U3H4GCLE.js";import{a as $r,b as vr,c as xr,e as Sr,f as Cr,g as Ar,h as Tr,k as Mr}from"./chunk-GCKLZQH4.js";import{a as ie}from"./chunk-UTYFLLSM.js";import{h as cr,i as dr}from"./chunk-UENU6N7M.js";import{a as nn,b as it,e as Ko}from"./chunk-RGWW5HLM.js";import"./chunk-WOT6VMZA.js";import{execFile as Pl}from"node:child_process";import{promisify as Il}from"node:util";import{appendFileSync as _l,existsSync as Et,mkdirSync as Ki,readFileSync as qn,rmSync as Ol,writeFileSync as Vn}from"node:fs";import{basename as Ll,join as le,resolve as Nl}from"node:path";function Ss(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 Cs(e){let t=!1;process.on("SIGINT",()=>{t||(t=!0,e())})}function ha(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 ga(e){let t=e?.input??0,n=e?.cacheRead??0,r=e?.cacheWrite??0;return{input:t,cacheRead:n,cacheWrite:r,prompt:t+n+r}}function ba(e){if(typeof e!="string")return null;let t=Date.parse(e);return Number.isNaN(t)?null:t}function wa(e){if(!e||typeof e!="object")return;let t=e,r=(t.message&&typeof t.message=="object"?t.message:void 0)??t,i=ha(r.usage);if(!i)return;let u=typeof r.provider=="string"?r.provider:"",f=typeof r.model=="string"?r.model:"";return{usage:i,model:[u,f].filter(Boolean).join("/")}}function As(e){let t=0,n=0,r=[],i=0,u=null;for(let h of e){let w=wa(h);if(!w)continue;let{input:S,cacheRead:M,cacheWrite:D,prompt:F}=ga(w.usage);if(F===0)continue;t+=M,n+=S+D;let K=ba(h.timestamp),I=u,H=I?I.at:null;if(I!==null&&M===0&&S>=1e3){let L=K!==null&&H!==null?Math.max(0,K-H):0;r.push({missedTokens:S,idleMs:L,modelChanged:w.model!==""&&I.model!==""&&w.model!==I.model}),i+=S}u={prompt:F,at:K??H??null,model:w.model}}let f=t+n;return{cachedTokens:t,billedTokens:n,hitRate:f>0?t/f*100:null,misses:r,missedTokens:i}}function Ts(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 Fl,ProjectTrustStore as jl,SessionManager as Dl}from"@netrodev/hxf-coding-agent";import{CombinedAutocompleteProvider as Hi,Container as Wl,Editor as Ul,matchesKey as Y,ProcessTerminal as Kl,ScrollView as Hl,KeybindingsManager as Vi,setKeybindings as zi,TUI_KEYBINDINGS as Yi,SelectList as Bl,TuiAltScreen as Gl,truncateToWidth as Re,VStack as ql,visibleWidth as It,wrapTextWithAnsi as Vl}from"@netrodev/hxf-tui";import{spawn as ya}from"node:child_process";function ka(e,t,n=2e3){return new Promise(r=>{let i=!1,u,f=S=>{i||(i=!0,u!==void 0&&clearTimeout(u),r(S))},h;try{h=ya(e,[...t],{stdio:["ignore","pipe","ignore"]})}catch{f({ok:!1,stdout:""});return}u=setTimeout(()=>{h.kill("SIGKILL"),f({ok:!1,stdout:""})},n);let w=[];h.stdout?.on("data",S=>w.push(S)),h.on("error",()=>f({ok:!1,stdout:""})),h.on("close",S=>{f({ok:S===0,stdout:Buffer.concat(w).toString("utf8")})})})}function xn(){return process.env.XDG_SESSION_TYPE==="wayland"||(process.env.WAYLAND_DISPLAY?.length??0)>0}async function $a(){let e=[];process.platform==="darwin"?e.push({command:"pbpaste",args:[]}):process.platform==="win32"?e.push({command:"powershell.exe",args:["-NoProfile","-Command","Get-Clipboard -Raw"]}):(xn()&&(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||!xn())&&(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 ka(t.command,t.args);if(n.ok&&n.stdout.length>0)return n.stdout}}async function Ms(){let e;try{let{getNativeClipboard:r}=await import("@netrodev/hxf-tui");e=r()}catch{e=void 0}if(e)try{let r=await e.getText();if(typeof r=="string"&&r.length>0)return{ok:!0,text:r}}catch{}let t=await $a();return t!==void 0?{ok:!0,text:t}:{ok:!1,reason:`no clipboard tool could read it \u2014 ${xn()?"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{TreeSelectorComponent as zl,initTheme as Yl}from"@netrodev/hxf-coding-agent";import{getKeybindings as Bi}from"@netrodev/hxf-tui";import{mixColors as va,parseColor as xa,styleText as de}from"@netrodev/hxf-tui";var ue=process.env.HOWTOFIX_NO_MOTION!=="1",Sa=45,Rs=5,Es=8,Sn=1e4,Ps=6e4,Is=3,_s=4,Cn=e=>e<0?0:e>1?1:e;function fe(e,t,n){let r=Cn(n);return r>=1?t:r<=0?e:va(e,t,r)}var yt=class{value;velocity=0;last=Date.now();target;constructor(t,n=t){this.value=t,this.target=n}set(t){this.target=t}get moving(){return Math.abs(this.target-this.value)>.15}snap(t){this.value=t,this.target=t,this.velocity=0,this.last=Date.now()}step(t=Date.now()){let n=Math.max(0,t-this.last),r=Math.min(250,n)/1e3;if(this.last=t,!ue)return this.value=this.target,this.velocity=0,this.value;n>250&&(this.velocity=0);let i=150,u=2*Math.sqrt(i),f=Math.max(1,Math.ceil(r/.008)),h=r/f;for(let w=0;w<f;w+=1)this.velocity+=(this.target-this.value)*i*h-this.velocity*u*h,this.value+=this.velocity*h;return this.moving||(this.value=this.target,this.velocity=0),this.value}};function An(e,t,n,r){return!ue||e<=Sn?t:e>=Ps?r:fe(n,r,(e-Sn)/(Ps-Sn))}function Os(e,t){return!ue||t<=0||e<0?1:1-(1-Cn(e/t))**3}function Ls(e,t){return ue&&e>=0&&e<t}var Tn=260,Ca=45;function Mn(e,t,n=Ca,r=400){return!ue||n<=0||e<0||e>=r?t:Math.min(t,Math.floor(e/n)+1)}function Ns(e,t,n=Date.now(),r=1400){if(!ue||r<=0)return e;let i=n%r/r;return fe(e,t,i<.5?i*2:(1-i)*2)}function Fs(e,t,n){let r=de(e,{fg:t.rest},ae);if(!ue||e.length===0)return r;let i=Cn(n);if(i>=1)return r;let u=t.band??1,f=e.length+_s*2,w=Math.min(f-1,Math.floor(i*f))-_s,S=H=>{let L=Math.abs(H-w);return L>u?0:1-L/(u+1)},M="",D=0,F=null,K=0,I=0;for(let H of e){let L=S(I);F===null?F=L:L!==F&&(M+=de(e.slice(D,K),{fg:fe(t.rest,t.lit,F)},ae),D=K,F=L),K+=H.length,I+=1}return M+de(e.slice(D),{fg:fe(t.rest,t.lit,F??0)},ae)}function js(e,t,n=Date.now(),r=90){let i=t[0]??xa("#e6e6e6");if(t.length===0||e.length===0)return de(e,{fg:i},ae);if(!ue||r<=0)return de(e,{fg:t[t.length-1]??i},ae);let u=t.length*r,f=(n%u+u)%u,h="",w=0,S=null,M=0,D=0,F=K=>{let I=(f+K*r)/u%1*t.length,H=Math.floor(I)%t.length,L=(H+1)%t.length;return fe(t[H]??i,t[L]??i,I-Math.floor(I))};for(let K of e){let I=F(D);S===null?S=I:I!==S&&(h+=de(e.slice(w,M),{fg:S},ae),w=M,S=I),M+=K.length,D+=1}return h+de(e.slice(w),{fg:S??i},ae)}function Aa(e,t){let n=Math.abs(e-t);return n>=Rs?0:Math.ceil((1-n/Rs)*Is)/Is}function Ds(e,t,n=Date.now()){let r=t.charMs??Sa;if(!ue||e.length===0||r<=0)return de(e,{fg:t.base},ae);let i=e.length+Es*2,u=n/r%i-Es,f=(F,K)=>de(F,{fg:fe(t.base,t.bright,K)},ae),h="",w=0,S=null,M=0,D=0;for(let F of e){let K=Aa(D,u);S===null?S=K:K!==S&&(h+=f(e.slice(w,M),S),w=M,S=K),M+=F.length,D+=1}return h+f(e.slice(w),S??0)}import{Markdown as Ba,wrapTextWithAnsi as Ga}from"@netrodev/hxf-tui";import{homedir as Ta}from"node:os";import{isAbsolute as Ma,relative as Ra,resolve as Ea,sep as Ws}from"node:path";var Pa="\u25CF",Pn="\u2514",$t="\u22EF",Rn=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"];function Ge(e=90){let t=Math.floor(Date.now()/e)%Rn.length;return Rn[t]??Rn[0]}var Ia="\u25B2";var _a="\u25CB",Oa=["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 In(e){return e.includes("__")?e.slice(e.lastIndexOf("__")+2):e}function Bs(e){return Oa.includes(In(e))}function He(e,t=process.cwd()){if(!e||!Ma(e))return e;let n=Ea(e),r=Ra(t,n);if(r==="")return".";if(r&&!r.startsWith(`..${Ws}`)&&r!=="..")return r;let i=Ta();return i&&(n===i||n.startsWith(i+Ws))?`~${n.slice(i.length)}`:n}function ne(e,t){let n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,Math.max(1,t-1))}\u2026`:n}function N(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 La(e,t=160){if(!e||typeof e!="object")return"";try{let n=JSON.stringify(e);return n&&n!=="{}"?ne(n,t):""}catch{return""}}function Na(e,t){switch(e){case"read":{let n=He(N(t,"path")??""),r=[N(t,"offset"),N(t,"limit")].filter(Boolean);return r.length>0?`${n} ${r.length===1?`offset=${r[0]}`:`offset=${r[0]}, limit=${r[1]}`}`:n}case"edit":case"write":return He(N(t,"path")??"");case"bash":case"powershell":{let n=N(t,"command")??"";return t?.run_in_background===!0?`${n} [background]`:n}case"bash_output":{let n=N(t,"task_id"),r=N(t,"filter");return n?r?`${n} filter=${r}`:n:"all tasks"}case"kill_shell":return N(t,"task_id")??"";case"compress":{let n=N(t,"topic")??"",r=Array.isArray(t.content)?t.content.length:0;return r>1?`${n} (${r} ranges)`:n}case"grep":{let n=N(t,"pattern")??"",r=N(t,"path");return r?`${n} in ${He(r)}`:n}case"find":case"glob":{let n=N(t,"pattern")??N(t,"glob")??"",r=N(t,"path");return r?`${n} in ${He(r)}`:n}case"ls":return He(N(t,"path")??".");case"task":return N(t,"agent")??"task";case"ask":return N(t,"question")??"";case"web_search":return N(t,"query")??"";case"web_fetch":return N(t,"url")??"";case"lsp":{let n=N(t,"action")??"lsp",r=N(t,"file")??"",i=N(t,"line");return i?`${n} ${r}:${i}`:`${n} ${r}`}case"quality":return N(t,"path")??"changed files";case"think":return"private";case"todo":{let n=N(t,"op")??"view",r=N(t,"task"),i=t?.items;return n==="init"&&Array.isArray(i)?`init ${i.length} task${i.length===1?"":"s"}`:r?`${n} ${r}`:n}case"context":{let n=N(t,"op")??"list",r=N(t,"key");return r?`${n} ${r}`:n}case"workflow":{let n=N(t,"path");if(n)return n;let r=N(t,"code")??"",i=/export\s+const\s+meta\s*=\s*\{[\s\S]*?name\s*:\s*["'`]([^"'`]+)/.exec(r)?.[1];if(i)return i;let u=r.trim().split(`
|
|
2
|
+
`)[0]??"";return u.length>40?`${u.slice(0,40)}\u2026`:u}default:return La(t)}}function $e(e,t,n=100){let r=In(e),u=r!==e?r:r.charAt(0).toUpperCase()+r.slice(1),f=Bs(e)?Ia:Pa,h=ne(Na(r,t),n);return h?`${f} ${u}(${h})`:`${f} ${u}`}function Fa(e){let t=0,n=0;for(let r of e.split(`
|
|
3
|
+
`))r.startsWith("+")&&!r.startsWith("+++")?t+=1:r.startsWith("-")&&!r.startsWith("---")&&(n+=1);return{additions:t,removals:n}}function Te(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 qe(e){let t=e?.details;return t&&typeof t=="object"?t:{}}function _n(e){let t=e?.structuredContent;return t&&typeof t=="object"?t:{}}function Us(e){let t=e.exit_code;return typeof t=="number"&&Number.isFinite(t)?t:void 0}function ja(e){let t=[];if(e&&typeof e=="object"){t.push(e);let r=e.content;if(Array.isArray(r))for(let i of r){let u=i?.text;if(typeof u=="string")try{let f=JSON.parse(u);f&&typeof f=="object"&&t.push(f)}catch{}}}let n=[];for(let r of t){let i=["instances","instanceCount","count","parts","partsCreated"].map(w=>r[w]).find(w=>typeof w=="number"&&Number.isFinite(w));typeof i=="number"&&n.push(`${i} instance${i===1?"":"s"}`);let u=En(r,["files","written","paths"]);u&&n.push(u.join(", "));let f=En(r,["images","renders","screenshots"]);f&&n.push(`renders ${_a} ${f.join(", ")}`);let h=En(r,["findings","warnings","errors"]);if(h&&n.push(`${h.length} finding${h.length===1?"":"s"}`),n.length>0)break}return n.length>0?n.join(" \xB7 "):void 0}function En(e,t){for(let n of t){let r=e[n];if(!Array.isArray(r))continue;let i=r.filter(u=>typeof u=="string"&&u!=="");if(i.length>0)return i}}function Ks(e){return e.trim().split(`
|
|
4
|
+
`).find(t=>t.trim())??""}function Da(e,t){let n=typeof e.output=="string"?e.output:t.replace(/\n*Command exited with code \d+\s*$/,""),r=Be(n);return r>0?` (${r} line${r===1?"":"s"})`:""}function Wa(e,t,n){return e===1?t:n}function Be(e){let t=e.trim();return t?t.split(`
|
|
5
|
+
`).length:0}function Hs(e){return e<1e3?`${e} tokens`:`${(e/1e3).toFixed(1)}k tokens`}function vt(e,t,n){let r=Te(t),i=qe(t),u=_n(t);if(n){let f=Us(u);if(f!==void 0&&(e==="bash"||e==="powershell"))return`exit ${f}`;let h=r.trim().split(`
|
|
6
|
+
`).find(w=>w.trim());return ne(h??"failed",120)}if(Bs(e)){let f=ja(t);if(f)return f;let h=In(e);return h==="execute_luau"?"ran":ne(h.replace(/_/g," "),120)}switch(e){case"task":{let f=r.split(`
|
|
7
|
+
`).filter(h=>h.startsWith("## ")).map(h=>h.replace(/^##\s*/,"").trim());if(f.length===0){let h=r.trim().split(`
|
|
8
|
+
`).find(w=>w.trim());return ne(h??"done",120)}return f.map(h=>ne(h,120)).join(`
|
|
9
|
+
`)}case"read":{let f=i.truncation,h=Be(r.replace(/\n*\[[^\]]*\]\s*$/,"")),w=h===0?"empty":`${h} line${h===1?"":"s"}`;return f?.truncated?`${w} (truncated from ${f.totalLines??"?"})`:w}case"compress":{let f=Array.isArray(i.blockIds)?i.blockIds:[],h=typeof i.compressedTokens=="number"?i.compressedTokens:0,w=typeof i.summaryTokens=="number"?i.summaryTokens:0,S=f.length===1?`b${String(f[0])}`:`${f.length} blocks`;if(h===0)return S;let M=h-w;return M<0?`${S} \xB7 ${Hs(-M)} LARGER than the range`:`${S} \xB7 ${Hs(M)} saved`}case"edit":{let f=typeof i.diff=="string"?i.diff:"";if(!f)return"applied";let{additions:h,removals:w}=Fa(f);return`+${h} / -${w}`}case"write":{let f=Be(r);return f===0?"written":`written (${f} ${Wa(f,"line","lines")})`}case"bash":case"powershell":{let f=Us(u);if(f===void 0)return r.trim()?ne(Ks(r),120):"done";let h=Da(u,r);return f===0?`exit 0${h}`:`exit ${f}`}case"grep":{let f=Be(r);return f===0?"no matches":`${f} match${f===1?"":"es"}`}case"web_search":{let f=typeof i.count=="number"?i.count:Be(r);return f===0?"no results":`${f} result${f===1?"":"s"}`}case"web_fetch":return`${typeof i.chars=="number"?i.chars:r.length} chars`;case"lsp":{let f=typeof i.count=="number"?i.count:void 0;return typeof i.error=="string"?ne(i.error,120):f===void 0?ne(Ks(r),120):`${f} location${f===1?"":"s"}`}case"quality":{if(typeof i.error=="string")return ne(i.error,120);if(i.off===!0)return"off";let f=typeof i.files=="number"?i.files:0,h=typeof i.functions=="number"?i.functions:0,w=typeof i.findings=="number"?i.findings:0,S=typeof i.score=="number"?` \xB7 ${Math.round(i.score)}`:"";return f===0?"no files":`${f} file${f===1?"":"s"} \xB7 ${h} fn \xB7 ${w} finding${w===1?"":"s"}${S}`}case"todo":{let f=i.todos??[];if(!Array.isArray(f)||f.length===0)return"list cleared";let h=f.filter(S=>S.status==="completed").length,w=f.filter(S=>S.status==="pending"||S.status==="in_progress").length;return`${h}/${f.length} done, ${w} open`}case"context":{let f=i.notes,h=f?Object.keys(f).length:0;return h===0?"no notes":`${h} note${h===1?"":"s"} held`}case"workflow":{let f=typeof i.agents=="number"?i.agents:0,h=typeof i.outputTokens=="number"?i.outputTokens:0,w=Array.isArray(i.steps)?i.steps.filter(M=>M.status==="failed").length:0;if(typeof i.error=="string")return`failed after ${f} agent(s)`;let S=typeof i.startedAt=="number"&&typeof i.endedAt=="number"?`, ${us(i.endedAt-i.startedAt)}`:"";return`${f} agent(s), ${h} tokens${S}${w>0?`, ${w} failed`:""}`}case"bash_output":{let f=r.trim().split(`
|
|
10
|
+
`)[0]??"",h=/running/.test(f)?"running":/finished/.test(f)?"finished":"task",w=r.trim().split(`
|
|
11
|
+
`).slice(2).filter(S=>S.trim()).length;return w===0?h:`${h} \xB7 ${w} line${w===1?"":"s"}`}case"kill_shell":{let f=r.trim().split(`
|
|
12
|
+
`)[0]??"";return f.startsWith("Stopped")?"stopped":ne(f,120)}default:{let f=r.trim().split(`
|
|
13
|
+
`).find(h=>h.trim());return f?ne(f,120):"done"}}}function Gs(e,t){let n=qe(t);if(e==="edit"&&typeof n.diff=="string")return n.diff.split(`
|
|
14
|
+
`).filter(r=>r.length>0).slice(0,12);if(e==="bash"||e==="powershell"){if(Te(t).startsWith("Started bash_"))return[];let i=_n(t);return(typeof i.output=="string"?i.output:Te(t).replace(/\n*Command exited with code \d+\s*$/,"")).trimEnd().split(`
|
|
15
|
+
`).filter(h=>h.trim()).slice(-4)}if(e==="bash_output")return Te(t).split(`
|
|
16
|
+
`).slice(2).filter(i=>i.trim()).slice(-6);if(e==="todo"){let r=n.todos??[],i={pending:"[ ]",in_progress:"[>]",completed:"[x]",dropped:"[-]"};return r.slice(0,6).map(u=>`${i[u.status??"pending"]??"[ ]"} ${u.content??""}`)}return e==="task"?Te(t).split(`
|
|
17
|
+
`).filter(r=>r.trim()&&!r.startsWith("## ")).slice(0,6):e==="workflow"?(n.steps??[]).map(u=>{let f=u.status==="running"?"\u25B8":u.status==="failed"?"\xD7":"\u2713",h=u.phase?`${u.phase} \xB7 `:"";return`${f} ${h}${u.label??"agent"}`}).slice(-6):[]}var kt=400;function qs(e,t){let n=qe(t);if(e==="edit"&&typeof n.diff=="string")return n.diff.split(`
|
|
18
|
+
`).filter(h=>h.length>0).slice(0,kt);let r=_n(t),u=(typeof r.output=="string"?r.output:Te(t).replace(/\n*Command exited with code \d+\s*$/,"")).trimEnd().split(`
|
|
19
|
+
`),f=u.slice(0,kt);return u.length>kt&&f.push(`\u2026 ${u.length-kt} more line(s)`),f}var Ua={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 Ka(e){if(e==="read")return"read";if(e==="grep"||e==="find"||e==="glob")return"search";if(e==="ls")return"list"}function Vs(e,t=!1){let n=[],r,i=()=>{if(!r||r.indices.length<2){r=void 0;return}n.push({start:r.indices[0],indices:r.indices,counts:r.counts,summary:Ha(r.counts,t)}),r=void 0};for(let[u,f]of e.entries()){let h=Ka(f.toolName);if(h===void 0){i();continue}r||(r={indices:[],counts:{}}),r.indices.push(u),r.counts[h]=(r.counts[h]??0)+1}return i(),n}function Ha(e,t){let n=[];for(let r of["search","read","list"]){let i=e[r];if(i===void 0)continue;let u=Ua[r],f=t?u.active:u.done,h=i===1?u.one:u.many;n.push(`${n.length===0?f:f.toLowerCase()} ${i} ${h}`)}return n.join(", ")}function Ys(e,t){let n=e[e.length-1];return n&&n.kind==="note"&&n.title===t.title?[...e.slice(0,-1),t]:[...e,t]}function On(e){return typeof e=="string"?De(e):De(e.map(t=>t.type==="text"?t.text:t.type==="thinking"?"":t.type==="image"?"[image]":(t.type==="toolCall","")).filter(Boolean).join(""))}function Xs(e){return e.role==="user"?On(e.content).trim():""}function Js(e,t,n){let r=t.trim();if(!r)return e;let i=e.findIndex(f=>f.kind==="user"&&f.body.trim()===r);if(i===-1)return[...e,{id:n,kind:"user",title:"you",body:r}];let u=[...e];return u[i]={id:n,kind:"user",title:"you",body:r},u}function qa(e){return e.content.filter(t=>t.type==="toolCall").map(t=>({name:t.name,arguments:t.arguments}))}function Va(e){return e.content.filter(t=>t.type==="toolCall").map(t=>t.id)}function za(e){let t=e.map(f=>({toolName:f.kind==="result"||f.kind==="tool"?f.title:"",line:f.call??f.body})),n=Vs(t);if(n.length===0)return e;let r=new Map(n.map(f=>[f.start,f])),i=new Set(n.flatMap(f=>f.indices)),u=[];for(let[f,h]of e.entries()){let w=r.get(f);if(w){let S=e[w.start];u.push({id:S?.id??`g-${w.start}`,kind:"collapsed",title:"collapsed",body:w.summary,full:w.indices.map(M=>e[M]?.call??e[M]?.body??"").filter(Boolean)});continue}i.has(f)||u.push(h)}return u}function St(e){let t=[];for(let n of e)if(n.role==="user"){let r=On(n.content).trim();if(!r)continue;t.push({id:`u-${n.timestamp}`,kind:"user",title:"you",body:r})}else if(n.role==="assistant"){let r=On(n.content).trim(),i=qa(n),u=Va(n);r?t.push({id:`a-${n.timestamp}`,kind:n.stopReason==="error"?"error":"assistant",title:n.errorMessage?"failed":"fix",body:n.errorMessage?`${n.errorMessage}
|
|
20
|
+
|
|
21
|
+
${r}`:r}):n.errorMessage&&t.push({id:`e-${n.timestamp}`,kind:"error",title:"failed",body:n.errorMessage}),i.forEach((f,h)=>{let w=u[h];t.push({id:w?`tool-${w}`:`c-${n.timestamp}-${h}`,kind:"tool",title:f.name,body:$e(f.name,f.arguments),...w?{call:$e(f.name,f.arguments)}:{}})})}else if(n.role==="toolResult"){let r=vt(n.toolName,{content:n.content},n.isError),i=t.find(u=>u.id===`tool-${n.toolCallId}`);i?(i.kind="result",i.body=r,i.title=n.toolName):t.push({id:`r-${n.toolCallId}`,kind:"result",title:n.toolName,body:r})}return za(t)}function zs(e,t,n){return Ga(e,Math.max(8,t)).map(r=>O(r,n))}var Ve=new Map;function Ya(e){let t=e.body||" ",n=Ve.get(e.id);if(n)return n.text!==t&&(n.component.setText(t),n.text=t),n.component;let r=new Ba(t,0,0,cs);return Ve.set(e.id,{text:t,component:r}),r}var Ln=class{constructor(t){this.item=t}item;invalidate(){}shade(t){let n=Date.now()-(this.item.born??0);return fe(T.dim,t,Os(n,Tn))}render(t){let n=this.item.body;if(this.item.kind==="user"){let i=this.item.pending?[O(" queued \u2014 the run reads this at its next step",T.dim)]:[];return["",...zs(`> ${n}`,t,this.shade(T.user)),...i]}if(this.item.kind==="tool")return[O(`${Ge()} ${n}`,this.shade(T.tool))];if(this.item.kind==="collapsed"){let i=[O(`${$t} ${n}`,this.shade(T.mute))],u=this.item.full??[];if(u.length>0)if(this.item.expanded===!0)for(let f of u)i.push(O(` ${f}`,this.shade(T.dim)));else i.push(O(` ${u.length} call(s) \xB7 ctrl+e to expand`,T.dim));return i}if(this.item.kind==="result"){let i=n.startsWith("exit ")&&n!=="exit 0";if(this.item.panel)return["",...this.item.panel(t),...n?[O(` ${Pn} ${n}`,i?T.bad:T.mute)]:[]];let u=[];this.item.call&&u.push(O(this.item.call,this.shade(T.tool)));let f=` ${Pn} ${n}`;if(u.push(O(f,i?T.bad:this.shade(T.mute))),this.item.expanded===!0&&(this.item.full?.length??0)>0){let M=O(` ${this.item.full.length} line(s) \xB7 ctrl+e to collapse`,T.dim);u.push(O(` ${$t}`,T.dim));for(let D of this.item.full){let F=D.startsWith("+")?T.tool:D.startsWith("-")?T.bad:T.dim;u.push(O(` ${D}`,F))}return u.push(M),u}let w=this.item.detail??[],S=Mn(Date.now()-(this.item.born??0),w.length);for(let M of w.slice(0,S)){let D=M.startsWith("+")?T.tool:M.startsWith("-")?T.bad:T.dim;u.push(O(` ${M}`,this.shade(D)))}return(this.item.full?.length??0)>0&&u.push(O(` ${$t} ${this.item.full.length} line(s) \xB7 ctrl+e to expand`,T.dim)),u}if(this.item.kind==="error"||this.item.kind==="note"){let i=this.item.kind==="error"?T.bad:T.mute;return["",...zs(n,t,this.shade(i))]}return["",...Ya(this.item).render(Math.max(8,t-2))]}},xt=class{items=[];status="";scrollOffset=0;scrollAnchor;settledOffset=0;viewportHeight=0;invalidate(){}entering(){let t=Date.now();return this.items.some(n=>{if(n.born===void 0)return!1;let r=t-n.born;return Ls(r,Tn)?!0:(n.detail?.length??0)>Mn(r,n.detail?.length??0)})}render(t){if(Ve.size>this.items.length){let i=new Set(this.items.map(u=>u.id));for(let u of Ve.keys())i.has(u)||Ve.delete(u)}let n=[];for(let i of this.items)i.born??=Date.now(),n.push(...new Ln(i).render(t));this.status&&n.push(O(this.status,T.mute));let r=this.viewportHeight;if(r>0&&n.length>r){let i=n.length-r;this.scrollOffset!==this.settledOffset&&(this.scrollAnchor=void 0);let u=this.scrollAnchor,f;if(u!==void 0){let h=n.length-u;h>=0&&h<=i?f=h:f=Math.max(0,Math.min(this.scrollOffset,i))}else f=Math.max(0,Math.min(this.scrollOffset,i));return u===void 0&&(this.scrollOffset=f),this.settledOffset=this.scrollOffset,f===0?this.scrollAnchor=void 0:this.scrollAnchor===void 0&&(this.scrollAnchor=n.length-f),n.slice(i-f,i-f+r)}return n}};function Zs(){let e=null;return{get armed(){return e!==null},arm(t){return e=t,!0},disarm(){let t=e;return t===null?!1:(e=null,t(),!0)}}}import{parseColor as Q}from"@netrodev/hxf-tui";var me={off:Q("okhsl(230 12% 46%)"),minimal:Q("okhsl(240 55% 49%)"),low:Q("okhsl(252 60% 55%)"),medium:Q("okhsl(270 64% 60%)"),high:Q("okhsl(298 70% 64%)"),xhigh:Q("okhsl(332 80% 66%)"),max:Q("okhsl(42 95% 64%)")},Qs={off:Q("okhsl(230 14% 64%)"),minimal:Q("okhsl(240 60% 64%)"),low:Q("okhsl(252 64% 68%)"),medium:Q("okhsl(270 68% 72%)"),high:Q("okhsl(298 74% 76%)"),xhigh:Q("okhsl(332 82% 78%)"),max:Q("okhsl(42 96% 76%)")};function Ct(e){return me[e]??me.medium}var ti=[me.minimal,me.low,me.medium,me.high,me.xhigh,me.max];function ni(e){return Qs[e]??Qs.medium}var ei=460;function At(e){return!Number.isFinite(e)||e<0||e>=ei?0:1-e/ei}var q=["off","minimal","low","medium","high","xhigh","max"];function oi(e){let t=e?.thinkingLevelMap;if(t===void 0)return q[q.length-1];for(let n=q.length-1;n>=0;n-=1)if(typeof t[q[n]]=="string")return q[n]}function ri(e){let t=q.indexOf(e);return q[(t+1+q.length)%q.length]}function si(e){let t=q.indexOf(e);return q[(t-1+q.length)%q.length]}import{mkdirSync as Qa,readFileSync as el}from"node:fs";import{dirname as tl}from"node:path";var Fn="\x1B[0m",V="\x1B[2m",Xa="\x1B[1m",Ja="\x1B[31m",jn="\x1B[32m",ai="\x1B[33m",ii="\x1B[35m",Nn="\x1B[36m";function j(e,t){return`${t}${e}${Fn}`}function li(e,t){return O(e,Ct(t))}function ci(e){return e>=85?Ja:e>=70?ai:jn}var Za="\u2726";function di(e,t,n,r){let i=j(`[${e}]`,Nn),u=`${j(Za,V)} ${t}`,f=j(n,ai),h=r?` ${j("git:(",ii)}${j(r.replace(/^git:\(/,"").replace(/\)$/,""),Nn)}${j(")",ii)}`:"";return`${i}${j(" \u2502 ",V)}${u}${j(" \u2502 ",V)}${f}${h}`}function ui(e,t,n){if(!t)return e;let r=n===void 0?t:`${t} ${j(fs(n),V)}`;return`${j(r,Nn)} ${j("\u2502",V)} ${e}`}function fi(e,...t){let n=Number.isFinite(e)?Math.min(100,Math.max(0,e)):0,r=Math.round(n/10),i=ci(n),u=`${i}${"\u2588".repeat(r)}${V}${"\u2591".repeat(10-r)}${Fn}`,f=j(`${Math.round(n)}%`,i),h=t.filter(Boolean).join(j(" \u2502 ",V));return`${j("Context",V)} ${u} ${f}${h?`${j(" \u2502 ",V)}${h}`:""}`}function mi(e){return!Number.isFinite(e)||e<=0?"":`${j("Spent",V)} ${j(`$${e.toFixed(3)}`,jn)}`}function pi(e,t,n,r){let i=Number.isFinite(t)&&t>0?t:0,u=Number.isFinite(n)?Math.max(0,n):0,f=Math.max(0,i-u),h=i>0?Math.min(100,u/i*100):0,w=Math.round(h/10),S=ci(h),M=`${S}${"\u2588".repeat(w)}${V}${"\u2591".repeat(10-w)}${Fn}`,D=F=>F!==0&&Math.abs(F)<.01?`${F.toFixed(6).replace(/0+$/,"").replace(/\.$/,"")} ${r}`:`${F.toFixed(2)} ${r}`;return[`${j(e,Xa)}${j(" account",V)}`,` ${j("used",V)} ${M} ${j(`${h.toFixed(1)}%`,S)}`,` ${j("granted",V)} ${D(i)}`,` ${j("spent",V)} ${D(u)}`,` ${j("remaining",V)} ${j(D(f),S)}`]}function Dn(e,t,n){let r=n===null?"":j(` ${n}ms`,V),i=t&&t!=="USD"?`${t} `:"";return`${j("Balance",V)} ${j(`${i}${e}`,jn)}${r}`}var Wn=or,nl=18e4;async function ol(e){let t=new Set((await e.modelRuntime.getAvailable()).map(i=>i.provider).filter(i=>oe(i))),n=ye.find(i=>t.has(i));return n?(await e.modelRuntime.getAuth(n))?.auth?.apiKey:void 0}function rl(){try{let e=JSON.parse(el(Wn,"utf8"));return!e.data||typeof e.cachedAt!="number"?void 0:{data:e.data,cachedAt:e.cachedAt}}catch{return}}function Tt(e){if(e.unlimited)return Dn("unlimited","",e.latencyMs);let n=e.unit==="USD"||e.unit==="CNY"?`$${e.remaining.toFixed(2)}`:`${e.remaining.toLocaleString()}`;return Dn(n,e.unit,e.latencyMs)}async function hi(e){let t=rl();if(t&&Date.now()-t.cachedAt<nl)return Tt(t.data);let n=await ol(e);if(!n)return t?Tt(t.data):void 0;let r=Date.now(),i=await Ae(n,{timeoutMs:3e3});if(!i.ok)return t?Tt(t.data):void 0;let u={remaining:i.remaining??0,limit:i.limit??0,unit:i.unit,unlimited:i.unlimited,latencyMs:Date.now()-r};return Qa(tl(Wn),{recursive:!0}),ie(Wn,JSON.stringify({data:u,cachedAt:Date.now()})),Tt(u)}import{chmodSync as sl,existsSync as il,readFileSync as al}from"node:fs";import{join as ll}from"node:path";function gi(e){return ll(e,"account-credential.json")}function bi(e,t){return Buffer.from(`${e}:${t}`,"utf8").toString("base64")}function Un(e){let t=e.trim();if(!t)return null;let n=i=>{let u=i.indexOf(":");return u<=0||u===i.length-1?null:{username:i.slice(0,u),password:i.slice(u+1)}},r=n(t);if(r)return r;try{let i=Buffer.from(t,"base64").toString("utf8");return i.includes(":")?n(i):null}catch{return null}}function wi(e,t,n){try{let r={credential:bi(t,n),username:t,savedAt:Math.floor(Date.now()/1e3)},i=gi(e);return ie(i,JSON.stringify(r,null,2)),sl(i,384),!0}catch{return!1}}function yi(e){try{let t=gi(e);if(!il(t))return null;let n=JSON.parse(al(t,"utf8"));return!n?.credential||!n?.username?null:n}catch{return null}}async function cl(e,t){let n=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t),signal:AbortSignal.timeout(2e4)}),r=await n.text(),i;try{i=JSON.parse(r)}catch{throw new Error(`the panel answered ${n.status} with something that is not JSON`)}let u=i;if(!n.ok||u.success===!1)throw new Error(u.message||`the panel answered ${n.status}`);return u.data}async function ki(e,t,n,r){let i=await cl(`${e}/api/auth/cli/credential`,{credential:bi(t,n),client_info:r});if(!i?.token)throw new Error("the panel accepted the credential but returned no key");return{token:i.token}}import{execFileSync as dl}from"node:child_process";import{createHash as ul}from"node:crypto";import{readFileSync as fl}from"node:fs";import{arch as ml,hostname as pl,platform as $i}from"node:os";function hl(e){try{return fl(e,"utf8").trim()}catch{return""}}function vi(e,t){try{return dl(e,t,{encoding:"utf8",timeout:3e3})}catch{return""}}function gl(){return vi("reg",["query","HKLM\\SOFTWARE\\Microsoft\\Cryptography","/v","MachineGuid"]).match(/MachineGuid\s+REG_SZ\s+([0-9a-fA-F-]+)/)?.[1]??""}function bl(){return vi("ioreg",["-rd1","-c","IOPlatformExpertDevice"]).match(/"IOPlatformUUID"\s*=\s*"([^"]+)"/)?.[1]??""}function wl(){return["/sys/class/dmi/id/product_uuid","/sys/class/dmi/id/board_serial","/sys/class/dmi/id/product_serial","/etc/machine-id","/var/lib/dbus/machine-id"].map(hl).filter(Boolean)}function yl(){switch($i()){case"win32":{let e=gl();return e?[e]:[]}case"darwin":{let e=bl();return e?[e]:[]}default:return wl()}}var Mt;function xi(){if(Mt)return{id:Mt,weak:!1};let e=yl(),t=e.length===0,n=[$i(),ml(),...e,t?pl():""].join("|");return Mt=ul("sha256").update(n).digest("hex").slice(0,32),{id:Mt,weak:t}}var kl="/cli/checkin",$l=["Bearer",""].join(" ").trim(),vl=5e5;function Kn(e){return`$${(e/vl).toFixed(2)}`}async function Si(e,t,n,r,i){let u=new AbortController,f=setTimeout(()=>u.abort(),i);try{let h=await r(`${n}${kl}`,{method:t,headers:{[cr]:dr(),"X-HowToFix-Device":xi().id,Authorization:`${$l} ${e}`},signal:u.signal}),w={};try{w=await h.json()}catch{}return{status:h.status,body:w}}finally{clearTimeout(f)}}async function Hn(e,t){let n=(t?.baseUrl??"https://api.howtofix.id/v1").replace(/\/+$/,""),r=t?.fetchImpl??fetch,i=t?.timeoutMs??1e4,u=e.trim();if(!u)return{ok:!1,enabled:!1,checkedInToday:!1,quotaToday:0,message:"no token given"};try{let{status:f,body:h}=await Si(u,"GET",n,r,i);if(f===401||f===403)return{ok:!1,enabled:!1,checkedInToday:!1,quotaToday:0,message:"the gateway rejected that token for the check-in status"};if(f>=400||h.success!==!0)return{ok:!1,enabled:!1,checkedInToday:!1,quotaToday:0,message:typeof h.message=="string"?h.message:`the gateway answered ${f}`};let w=h.data??{};return{ok:!0,enabled:w.enabled===!0,checkedInToday:w.checked_in_today===!0,quotaToday:Number(w.quota_today??0)||0,message:""}}catch(f){return{ok:!1,enabled:!1,checkedInToday:!1,quotaToday:0,message:f instanceof Error&&f.name==="AbortError"?"the gateway did not answer the check-in in time":"could not reach the gateway"}}}async function Ci(e,t){let n=(t?.baseUrl??"https://api.howtofix.id/v1").replace(/\/+$/,""),r=t?.fetchImpl??fetch,i=t?.timeoutMs??15e3,u=e.trim();if(!u)return{ok:!1,alreadyClaimed:!1,blocked:!1,quotaAwarded:0,message:"no token given"};try{let{status:f,body:h}=await Si(u,"POST",n,r,i);if(h.success===!0){let D=h.data??{};return{ok:!0,alreadyClaimed:!1,blocked:!1,quotaAwarded:Number(D.quota_awarded??0)||0,message:""}}let w=typeof h.message=="string"?h.message:`the gateway answered ${f}`,S=/device already claimed|account blocked|appeal/i.test(w);return{ok:!1,alreadyClaimed:!S&&/签到|check-?in|already|今日/.test(w)&&!/not enabled/i.test(w),blocked:S,quotaAwarded:0,message:w}}catch(f){return{ok:!1,alreadyClaimed:!1,blocked:!1,quotaAwarded:0,message:f instanceof Error&&f.name==="AbortError"?"the gateway did not answer the check-in in time":"could not reach the gateway"}}}function xl(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 Sl(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 Ai(e){let t=xl(e.contextWindow),n=Sl(e.cost);return[t?`${t} ctx`:"",n].filter(Boolean).join(" \xB7 ")}function Ti(){return{}}function Mi(e,t,n,r=Date.now()){let i={...e};return t==="run"?(n===void 0||n===""?delete i.run:i.run={label:n,since:e.run?.since??r},i):(n===void 0||n===""?delete i[t]:i[t]=n,i)}function Ri(e,t){let n={...e};return t===void 0?delete n.retry:n.retry=t,n}function Cl(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 Bn(e,t=72){let n=e.split(`
|
|
22
|
+
`).map(r=>r.trim()).find(r=>r!=="")??"";return n.length>t?`${n.slice(0,t-1)}\u2026`:n}function Al(e,t){let n=Math.max(0,Math.ceil((e.until-t)/1e3)),r=n>0?`in ${n}s`:"now",i=`retry ${e.attempt}/${e.maxAttempts} ${r}`,u=Bn(e.error);return u===""?i:`${i} \xB7 ${u}`}function Ei(e,t,n=Date.now()){return e.prompt?`? ${e.prompt}`:e.retry?`* ${Al(e.retry,n)}`:e.note?`* ${e.note}`:e.run?`${t} ${e.run.label} \xB7 ${Cl(n-e.run.since)}`:e.tally?e.tally:""}function Pi(e){return e instanceof Error?e.message:String(e)}var ze=class{active;apply;report;pending;running;constructor(t){this.active=new Set(t.initial??[]),this.apply=t.apply,this.report=t.report??(n=>console.error(n))}activeServers(){return[...this.active]}reconcile(t){return this.pending=new Set(t),this.running?this.running:(this.running=this.drain().finally(()=>{this.running=void 0}),this.running)}async drain(){let t={added:[],removed:[],unchanged:[],problems:[]};for(;this.pending!==void 0;){let r=this.pending;this.pending=void 0;let i=await this.applyOnce(r);t.added.push(...i.added),t.removed.push(...i.removed),t.unchanged.push(...i.unchanged),t.problems.push(...i.problems)}let n=this.active;return t.added=t.added.filter(r=>n.has(r)),t.removed=[...new Set(t.removed.filter(r=>!n.has(r)))],t.added=[...new Set(t.added)],t.unchanged=[...new Set(t.unchanged.filter(r=>n.has(r)))],t}async applyOnce(t){let n=[...t].filter(u=>!this.active.has(u)),r=[...this.active].filter(u=>!t.has(u)),i=[...t].filter(u=>this.active.has(u));if(n.length===0&&r.length===0)return{added:[],removed:[],unchanged:i,problems:[]};try{await this.apply(n,r)}catch(u){let f=`mcp reconciliation failed: ${Pi(u)}`;return this.report(f),{added:[],removed:[],unchanged:[],problems:[f]}}for(let u of n)this.active.add(u);for(let u of r)this.active.delete(u);return{added:n,removed:r,unchanged:i,problems:[]}}async dispose(){this.running&&await this.running.catch(()=>{});let t=[...this.active];if(t.length===0)return{added:[],removed:[],unchanged:[],problems:[]};try{return await this.apply([],t),this.active.clear(),{added:[],removed:t,unchanged:[],problems:[]}}catch(n){let r=`mcp teardown failed: ${Pi(n)}`;return this.report(r),{added:[],removed:[],unchanged:[],problems:[r]}}}};import{mkdirSync as Tl}from"node:fs";import{join as Ml}from"node:path";import{matchesKey as Rt}from"@netrodev/hxf-tui";var Gn=["all","running","failed","done"];function _i(){return{selectedPhase:0,filter:"all",paused:!1,expanded:!1,follow:!0}}function Oi(e){if(Rt(e,"up"))return"up";if(Rt(e,"down"))return"down";if(Rt(e,"enter"))return"enter";if(Rt(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 Ii(e,t,n){if(t.length===0)return e;let r=Math.max(0,Math.min(t.length-1,e.selectedPhase+n));return{...e,selectedPhase:r,follow:!1}}function Rl(e){let t=Gn.indexOf(e);return Gn[(t+1)%Gn.length]}function Li(e,t,n){switch(t){case"up":return Ii(e,n,-1);case"down":return Ii(e,n,1);case"enter":return{...e,expanded:!e.expanded};case"filter":return{...e,filter:Rl(e.filter)};case"pause":return{...e,paused:!e.paused};default:return e}}function Ni(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 Fi(e){return e==="all"?"":` \xB7 ${e}`}var ji="ctrl+f";function Di(e,t,n=!0){if(!n)return"Ctrl+F panel keys \xB7 Esc unpin";let r=["\u2191/\u2193 phase",e.expanded?"Enter collapse":"Enter drill in"];return r.push(e.expanded?"Esc back out":"Esc unpin"),r.push(`f filter${e.filter==="all"?"":` (${e.filter})`}`),t?(r.push(e.paused?"p resume":"p pause"),r.push("x stop")):e.paused&&r.push("p resume"),r.push("s save script"),e.paused&&r.unshift("paused"),r.join(" \xB7 ")}function El(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 Wi(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=El(e.name);if(!n)return{ok:!1,reason:`"${e.name}" is not a usable filename, so the script was not written`};let r=Ml(t,`${n}.js`);try{Tl(t,{recursive:!0}),ie(r,e.code)}catch(i){return{ok:!1,reason:i instanceof Error?i.message:String(i)}}return{ok:!0,path:r}}function Ui(e){let t=()=>{};return{select:(n,r)=>e.select(n,r),confirm:(n,r)=>e.confirm(n,r),input:n=>e.input(n),notify:(n,r)=>e.notify(n,r),onTerminalInput:()=>t,setStatus:(n,r)=>e.setStatus(n,r),setWorkingMessage:t,setWorkingVisible:t,setWorkingIndicator:t,setHiddenThinkingLabel:t,setWidget:(n,r,i)=>{r!==void 0&&!Array.isArray(r)||e.setWidget?.(n,r,i?.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}}var Gi={borderColor:()=>"",selectList:{selectedPrefix:e=>O(e,T.accent),selectedText:e=>O(e,T.text,{bold:!0}),description:e=>O(e,T.mute),scrollInfo:e=>O(e,T.dim),noMatch:e=>O(e,T.mute)}},Xi=Symbol.for("@netrodev/hxf-tui/layout-node");function Xl(e){if(typeof e!="object"||e===null)return;let t=e[Xi];return typeof t=="function"?t.call(e):void 0}var Yn=Il(Pl);async function qi(e){try{let{stdout:t}=await Yn("git",["-C",e,"rev-parse","--abbrev-ref","HEAD"],{encoding:"utf8"}),n=t.trim();if(!n||n==="HEAD")return"";let{stdout:r}=await Yn("git",["-C",e,"status","--porcelain"],{encoding:"utf8"});return`git:(${n}${r.trim()?"*":""})`}catch{return null}}var Xn=class{folder;model;git;percent=0;meter=new yt(0);activity=Ti();live=!1;activitySince=Date.now();thinking="medium";ceiling=void 0;usage="";cost=0;skipPermissions=!1;constructor(t,n){this.folder=Ll(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;setThinking(t){t!==this.thinking&&(this.thinking=t,this.levelChangedAt=Date.now())}levelFlashAmount(){return this.levelChangedAt===0?0:At(Date.now()-this.levelChangedAt)}flashing(){return this.levelFlashAmount()>0}levelText(t){if(this.atCeiling())return js(this.thinking,ti,t);let n=this.levelChangedAt===0?Number.POSITIVE_INFINITY:t-this.levelChangedAt;return At(n)<=0?li(this.thinking,this.thinking):Fs(this.thinking,{rest:Ct(this.thinking),lit:ni(this.thinking)},1-At(n))}meterValue(){return this.meter.value!==this.percent&&this.meter.set(this.percent),this.meter.step()}beginRun(){this.live=!0,this.activitySince=Date.now()}waitedMs(){return Date.now()-this.activitySince}abandonAnimations(){this.meter.snap(this.percent)}render(t){let n=Date.now(),r=this.percent===0&&this.meter.value===0?0:this.meterValue(),i=this.levelText(n),u=di(this.model,i,this.folder,this.git),f=[Re(`${ui(u,this.live?Ge():"",this.live?this.waitedMs():void 0)} ${fi(r,this.usage,mi(this.cost))}`,t)];this.skipPermissions&&f.push(Re(O("Permissions OFF \u2014 critical commands and the repeat guard are not enforced",T.bad),t));let h=Xr();h&&f.push(Re(O(h,T.warn),t));let w=Hr(gt());w&&f.push(Re(O(w,T.accent),t));let S=Ei(this.activity,Ge(),n),M=this.live?Ds(S,{base:An(this.waitedMs(),T.mute,T.warn,T.bad),bright:T.text,charMs:45},n):O(S,An(this.waitedMs(),T.mute,T.warn,T.bad));return f.push(Re(M,t)),f}},Jn=class{constructor(t){this.draw=t}draw;render(t){return this.draw(t)}invalidate(){}},Zn=class{constructor(t,n){this.editor=t;this.hud=n}editor;hud;focused=!1;invalidate(){this.editor.invalidate()}render(t){let n=Math.max(10,t-4),r=this.editor.render(n).filter(h=>It(h)>0),i=r.length>0?r:[""],u="\u2500".repeat(Math.max(0,t-2)),f=i.map(h=>{let w=Math.max(0,n-It(h));return`\u2502 ${h}${" ".repeat(w)} \u2502`});return[`\u250C${u}\u2510`,...f,`\u2514${u}\u2518`,...this.hud.render(t)]}handleInput(t){this.editor.handleInput(t)}};function Jl(e,t,n,r=!1,i=[]){let u=Math.max(24,n),f=u-4,h=(L,Z)=>{let pe=It(L)>f?Re(L,f,"\u2026"):L,ee=`${pe}${" ".repeat(Math.max(0,f-It(pe)))}`;return`\u2502 ${Z?Z(ee):ee} \u2502`},w="\u2500".repeat(u-2),S=[h(` ${t}`),...e.render(f).map(L=>h(L))];S.push(h(" type to filter \xB7 \u2191\u2193 move \xB7 enter select \xB7 esc cancel"));let M=i.flatMap(L=>L===""?[""]:Vl(L,f)),D=M.length>0?[h(""),...M.map(L=>h(L,Z=>O(Z,T.mute)))]:[];if(!r)return["",`\u250C${w}\u2510`,...S,...D,`\u2514${w}\u2518`];let F=Ns(T.line,T.warn,Date.now(),1400),K=O("\u2502",F),I=(L,Z)=>O(`${L}${w}${Z}`,F),H=[...S,...D].map(L=>`${K}${L.slice(1,-1)}${K}`);return["",I("\u250C","\u2510"),...H,I("\u2514","\u2518")]}function Zl(e,t){let n=t.split(`
|
|
23
|
+
`).filter(Boolean),r=n.filter(f=>f.startsWith("Reason:")),i=n.filter(f=>!f.startsWith("Reason:")&&!f.startsWith("Allow tool:"));return[...e.endsWith(" wants to run")?[]:[e],...r,...i.length>0?["",...i]:[]]}function Me(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,i=[...e.state.messages].reverse().find(u=>u.role==="assistant")?.usage?.totalTokens;return!n||typeof i!="number"||!Number.isFinite(i)||n.contextWindow<=0?0:Math.min(100,Math.round(i/n.contextWindow*100))}function zn(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 with email:password (or a base64 credential), or paste a key"],["sync","re-sync models from howtofix.id"],["usage","show the account's quota and what it has spent"],["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","login | logout | status | tunnel on/off \u2014 Roblox sign-in and workspace link (alone: RoToolbox status)"],["proxy","route requests through a proxy, or show the current one"],["export","write the transcript to a markdown file"],["copy","copy the last answer to the clipboard"],["agents","show spawned agents"],["goal","set or view this session's goal"],["plan","toggle plan mode (design before editing)"],["workflow","show or clear the pinned workflow panel"],["dcp","dynamic context pruning: on | off | status | blocks | stats | context | decompress <bN> | sweep"],["context","what the next request carries, and what pruning saved"],["decompress","reopen one compressed block, e.g. /decompress b2"],["sweep","close compressed blocks no ref resolves"],["session","show the current model"],["help","list commands"],["quit","quit"],["exit","quit (alias)"]].map(([r,i])=>({name:r,description:i}));for(let r of e.promptTemplates)n.push({name:r.name,description:r.description});for(let r of e.extensionRunner.getRegisteredCommands())n.push({name:r.invocationName,description:r.description});return n}function Qn(e,t){if(e!=="workflow")return;let n=qe(t);if(!(typeof n.name!="string"||!Array.isArray(n.steps)))return n}function Ql(e,t){let n=Qn(e,t);return n?Pt(n):void 0}function Pt(e,t,n=!1){return r=>ms(e,[],r,t?.selectedPhase,t?ec(e,t,n):void 0)}function ec(e,t,n){return{filter:r=>Ni(r,t.filter),footerText:Di(t,e.endedAt===void 0,n),filterLabel:Fi(t.filter),drill:t.expanded}}function tc(){let e=new Vi(Yi,{"tui.altScreen.pageUp":[],"tui.altScreen.pageDown":[],"tui.altScreen.halfPageUp":[],"tui.altScreen.halfPageDown":[],"tui.altScreen.top":[],"tui.altScreen.bottom":[]});zi(e)}async function gu(e){let t=new Kl,n,r=new Gl(t,!0,void 0,{mouse:!0,onRightClickPaste:()=>n?.()}),i=new xt,u=new Xn(e.cwd,e.modelLabel);u.skipPermissions=hn();let f=o=>{let s=Date.now();(async()=>{try{let a=Ye(),l=k.getSessionStats().sessionId;if(!ao){ao=!0;try{await ks(a,{keep:l})}catch{}}let d=await bs(a,l,o);d&&s>=Dt&&(io=d,Dt=s)}catch{}})()},h=(o=!1)=>{!o&&!u.live||qi(e.cwd).then(s=>{s!==null&&(u.git=s,v())})},w=new Ul(r,Gi,{paddingX:1}),S=new Map,M=(o,s)=>{s===void 0?S.delete(o):typeof s=="function"?S.set(o,s):S.set(o,()=>s)},D=()=>Math.max(20,t.columns),F,K=0,I=_i(),H,L=null,Z=!1,pe,ee=!1,Ji,_t=()=>{!H||!Z||M("workflow",o=>Pt(H,I,ee)(o))},eo=()=>{H&&(pe=H.name),Z=!1,ee=!1,M("workflow",void 0)};ps({onStop:o=>{L=o},isPaused:()=>I.paused});let to=o=>{if(pe===o.name)return;F=o;let s=o.endedAt??Date.now();K=Math.max(K,s+ds),H=o,Z=!0,M("workflow",a=>Pt(o,I,ee)(a))},no=new Zn(w,u),k=e.session,oo=e.setCompressToolOutput,ro=!1,Ot=()=>{let o=k.getSessionStats().cost;return u.cost=o,o},Lt=ar(e.maxBudgetUsd),so=!1,Zi=()=>{let o=Lt.check(Ot());o===void 0||so||(so=!0,k.isStreaming&&k.abort(),m("budget",lr(o.spent,o.limit)))},he=()=>{u.ceiling=oi(k.model)},ge=Ar(P),Nt,Qi=async()=>!ge||!Cr(ge)||Sr(ge)?!1:(Nt??=(async()=>{try{let o=await Mr(P,ge);return o.renewed?(ge=o.credential,o.message&&m("connect",o.message),await k.modelRuntime.setRuntimeApiKey("howtofix",o.credential.accessToken),!0):(o.message&&m("connect",o.message),!1)}catch{return!1}finally{Nt=void 0}})(),await Nt),Ft,Ye=()=>Ft??=hs(e.cwd),io,jt="",Dt=0,ao=!1,be,ea=()=>{let o=new Set(["session_info","usage","label","context_edit","custom","model_change","thinking_level_change"]),s=[],a=l=>{for(let d of l)o.has(d.entry.type)||s.push(d.entry.id),a(d.children)};return a(k.sessionManager.getTree()),s},lo=!1,ta=()=>{if(lo)return;lo=!0;let o=Bi().getResolvedBindings();zi(new Vi(Yi,{...o,"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"]}))},co=!1,na=()=>{co||(co=!0,Yl())},uo=()=>{let o=k.sessionManager.getTree();if(o.length===0){m("rewind","nothing to rewind to yet");return}Ye().disabled&&m("rewind","conversation rewind only; this directory is not a git repository"),na(),ta();let s=Math.max(8,Math.floor(t.rows*.6)),a=new zl(o,k.sessionManager.getLeafId(),s*2,l=>{Wt(),oa(l)},()=>Wt());if(!a.getTreeList().getSelectedNode()){m("rewind","nothing to rewind to yet");return}be=a,be.focused=!0,M("rewind",l=>be?.render(l)??[]),v()},Wt=()=>{be=void 0,M("rewind",void 0),v()},oa=async o=>{let s=Ye(),l=k.getUserMessagesForForking().findIndex(c=>c.entryId===o),d=l>=0?gs(s,k.getSessionStats().sessionId)[l]:void 0,y=d?(await ys(s,d)).length:0;if(y===0){await fo(o,void 0,"conversation");return}_(`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`}],c=>{fo(o,d,c)})},fo=async(o,s,a)=>{let l=[];if((a==="both"||a==="conversation")&&!k.isStreaming)try{let d=await k.navigateTree(o);if(d.cancelled){m("rewind","conversation rewind cancelled");return}l.push("conversation rewound"),i.items=St(k.state.messages),d.editorText&&(w.setText(d.editorText),l.push("prompt restored to the editor"))}catch(d){G(`conversation rewind failed: ${d instanceof Error?d.message:String(d)}`);return}if((a==="both"||a==="code")&&s){let d=await ws(Ye(),s);if(!d.ok){G(`code rewind failed: ${d.output}`);return}l.push(d.output),d.removed.length>0&&l.push(`removed ${d.removed.length} file(s)`),h()}m("rewind",l.join(`
|
|
24
|
+
`)||"nothing to do"),v()};h(!0),f("session start"),e.note&&i.items.push({id:"note",kind:"note",title:"note",body:e.note}),i.items.push(...St(k.state.messages)),u.percent=Me(k),Ot(),u.abandonAnimations(),u.setThinking(k.thinkingLevel),he(),w.setAutocompleteProvider(new Hi(zn(k),e.cwd)),hi(k).then(o=>{o&&(u.usage=o,r.requestRender())});let mo=async o=>{let{checkForUpdate:s,checkFailedNote:a,installUpdate:l}=await import("./chunk-7CHDNTH6.js"),d=await s(o.current);if(!d.available){let c=a(d);c?m("update",c):o.install&&m("update",d.message);return}if(!o.install){m("update",`${d.message}. run /update to install it.`);return}A("note",`installing HowToFix ${d.latest}\u2026`);let y=await l({version:d.latest});A("note",void 0),m("update",y.message),v()};e.update&&mo(e.update);let se=null,po="",ho=!1,go=[],Ee,Ut=()=>{},v=()=>{Ut(),r.requestRender()},A=(o,s)=>{u.activity=Mi(u.activity,o,s)},Kt=o=>{u.activity=Ri(u.activity,o)},Xe=new Map,Ht=new Set,ra=()=>[...Xe].map(([o,s])=>`${Ht.has(o)?"!":"\u2713"} ${o} \xD7${s}`).join(" | "),sa=()=>{let o=ra();A("tally",o||void 0)},_=(o,s,a,l,d=!1,y=[])=>{let c=new Bl(s,8,Gi.selectList);c.onSelect=p=>{se=null,Ee=void 0,a(p.value)},c.onCancel=()=>{se=null,Ee=void 0,l?.(),v()},Ee=()=>c.onCancel?.(),po=o,ho=d,go=y,se=c,yo+=1,v()},m=(o,s)=>{i.items=Ys(i.items,{id:`cmd-${Date.now()}-${i.items.length}`,kind:"note",title:o,body:s}),A("tally",void 0),v()};os(o=>{o.background&&m("agent",`${Zr(o)}
|
|
25
|
+
read it with /agents ${o.id}`)});let Bt=!1,ia=o=>{Bt||(Bt=!0,(async()=>{try{let s=(await k.modelRuntime.getAvailable()).filter(g=>oe(g.provider)),a=new Set(s.map(g=>g.provider)),l=ye.find(g=>a.has(g)),d=l?(await k.modelRuntime.getAuth(l))?.auth?.apiKey:void 0;if(!d)return;let y=wt(s.map(g=>g.id)),{live:c,probed:p}=await yr(y,d,{exclude:o,limit:4});if(c.length===0)return;let b=se===null;m("gateway",`${c.length} of ${p.length} probed models answer right now (${c.join(", ")}); ${b?"the model picker is open below":"switch with /model"}.`),b&&Ne("/model")}catch{}finally{Bt=!1}})())},G=o=>{i.items.push({id:`err-${Date.now()}-${i.items.length}`,kind:"error",title:"failed",body:o});let s=ir(o);s!==void 0&&m("gateway",s);let a=sr(o);a!==void 0&&ia(a),A("tally",void 0),v()},Pe=o=>{k.setThinkingLevel(o,{persist:!0}),u.setThinking(o),he(),A("note",`thinking ${o}`),v()};Or((o,s)=>{let{promise:a,resolve:l}=Promise.withResolvers();return _(o,[{value:"allow",label:"allow"},{value:"deny",label:"deny"}],d=>l(d==="allow"),()=>l(!1),!0,Zl(o,s)),a});let Gt=new Map,bo=o=>{let s=Ui({select:(a,l)=>{let{promise:d,resolve:y}=Promise.withResolvers();return _(a,l.map(c=>({value:c,label:c})),y,()=>y(void 0)),d},confirm:(a,l)=>{let{promise:d,resolve:y}=Promise.withResolvers();return _(`${a} \u2014 ${l}`,[{value:"yes",label:"yes"},{value:"no",label:"no"}],c=>y(c==="yes"),()=>y(!1)),d},input:a=>{let{promise:l,resolve:d}=Promise.withResolvers();return A("prompt",a),v(),re=y=>{re=void 0,A("prompt",void 0),d(y),v()},l},notify:(a,l)=>{l==="error"?G(a):m("mcp",a)},setStatus:(a,l)=>{l===void 0?Gt.delete(a):Gt.set(a,l),A("note",[...Gt.values()].join(" | ")||void 0),v()},setWidget:(a,l)=>{M(a,l),v()}});o.bindExtensions({uiContext:s,mode:"print",onError:a=>G(`${a.event}: ${a.error}`)}).catch(a=>G(a instanceof Error?a.message:String(a)))};bo(k);let ve=new Wl,aa={invalidate:()=>i.invalidate(),render:o=>{let s=ve.render(Math.max(20,o)).length;return i.viewportHeight=Math.max(1,Math.max(8,t.rows)-s),i.render(o)},handleMouse:o=>{if(Ro(o))return nt(),{handled:!0};let s=o.type==="wheel"?o.wheelDelta??0:0;if(s!==0)return i.scrollOffset=Math.max(0,i.scrollOffset-s*3),v(),{handled:!0}}},la=new Hl(aa,{follow:"none",overscroll:"contain"}),Je=new ql([{component:la,grow:1,shrink:1},{component:ve,grow:0,shrink:0,basis:"auto"}]),wo="",yo=0,ca=()=>`${se?`picker:${yo}`:"dock"}|${[...S.keys()].join(",")}`;Ut=()=>{let o=ca();if(o===wo)return;wo=o,ve.clear();for(let a of S.values())ve.addChild(new Jn(a));let s=se;if(s){let a=po,l=ho,d=go;ve.addChild({render:y=>Jl(s,a,y,l,d),invalidate:()=>{}})}else ve.addChild(no);Je.invalidate()},Ut();let ko={focused:!1,invalidate(){i.invalidate(),no.invalidate(),se?.invalidate(),Je.invalidate()},[Xi]:()=>Xl(Je),render:o=>Je.render(o),handleMouse(o){if(Ro(o))return nt(),{handled:!0}},handleInput(o){w.handleInput(o)}};r.setLayoutRoot(ko),r.setFocus(ko);let X=0,ce="",qt=!1,we=!1,Vt,xe="",$o=0,Ie=!1,Ze=Date.now(),Qe=!1,et=new Map,vo=()=>{let o=new Set(k.getSteeringMessages().map(s=>s.trim()).filter(Boolean));for(let s of i.items)s.kind!=="user"||!s.pending||o.has(s.body.trim())||(s.pending=void 0)},xo=o=>{if(o.type==="agent_start"&&vo(),o.type==="agent_start"||o.type==="turn_start")o.type==="agent_start"&&Ir(),u.live||u.beginRun(),ce="",we=!1,Ie=!1,Ze=Date.now(),xe="";else if(o.type==="message_update"&&o.assistantMessageEvent.type==="thinking_delta"){we=!0,xe===""&&($o=Date.now()),xe+=o.assistantMessageEvent.delta;let s=`think-${X}`,a=i.items.find(d=>d.id===s),l=xe.split(`
|
|
26
|
+
`).slice(-6).join(`
|
|
27
|
+
`);a?a.body=l:i.items.push({id:s,kind:"note",title:"thinking",body:l})}else if(o.type==="message_update"&&o.assistantMessageEvent.type==="thinking_end"){let s=`think-${X}`,a=i.items.find(l=>l.id===s);if(a){let l=Math.max(1,Math.round((Date.now()-$o)/1e3));a.title="thought",a.body=`${l}s \xB7 ${xe.length} chars of reasoning`}xe=""}else if(o.type==="message_update"&&o.assistantMessageEvent.type==="text_delta"){we=!0,ce+=o.assistantMessageEvent.delta;let s=De(ce),a=`live-${X}`,l=i.items.find(d=>d.id===a);l?l.body=s:i.items.push({id:a,kind:"assistant",title:"HowToFix",body:s})}else if(o.type==="tool_execution_start"){et.set(o.toolCallId,o.args),we=!1,Ie=!1,Ze=Date.now();let s=`tool-${o.toolCallId}`,a=$e(o.toolName,o.args),l=i.items.find(d=>d.id===s);if(l?(l.kind="tool",l.title=o.toolName,l.body=a,l.live=!0):i.items.push({id:s,kind:"tool",title:o.toolName,body:a,live:!0}),Vt=o.toolName,o.toolName==="task"){let d=Qr.filter(y=>y.status==="queued"||y.status==="running");A("note",d.map(y=>`${y.agent} ${y.status}`).join(" | ")||"agent running")}}else if(o.type==="tool_execution_update"){let s=Ql(o.toolName,o.partialResult);if(s){let a=`tool-${o.toolCallId}`,l=i.items.find(y=>y.id===a);l?l.panel=s:i.items.push({id:a,kind:"tool",title:o.toolName,body:$e(o.toolName,et.get(o.toolCallId)),panel:s,live:!0});let d=Qn(o.toolName,o.partialResult);d&&pe!==d.name&&to(d),v()}}else if(o.type==="tool_execution_end"){u.percent=Me(k);let s=i.items.find(b=>b.id===`tool-${o.toolCallId}`);s&&(s.live=!1,s.body=$e(o.toolName,et.get(o.toolCallId))),et.delete(o.toolCallId),Vt=void 0,we=!0,Ie=!1,Xe.set(o.toolName,(Xe.get(o.toolName)??0)+1),o.isError&&Ht.add(o.toolName),sa();let a=Gs(o.toolName,o.result),l=qs(o.toolName,o.result),d=Qn(o.toolName,o.result),y=d?Pt(d):void 0;d&&pe!==d.name&&to(d);let c=i.items.find(b=>b.id===`tool-${o.toolCallId}`),p=vt(o.toolName,o.result,o.isError);c?(c.kind="result",c.call=c.body,c.body=p,c.live=!1,a.length>0&&(c.detail=a),l.length>0&&(c.full=l),y&&(c.panel=y)):i.items.push({id:`tool-${o.toolCallId}`,kind:"result",title:o.toolName,body:p,...a.length>0?{detail:a}:{},...l.length>0?{full:l}:{},...y?{panel:y}:{}}),(o.toolName==="bash"||o.toolName==="powershell"||o.toolName==="edit"||o.toolName==="write")&&h()}else if(o.type==="compaction_start"){we=!0;let s=o.reason==="manual"?"on request":"context is nearly full",a=i.items.find(y=>y.id===`compact-${X}`),l="compacting context",d=`${s} \xB7 summarizing the older turns`;a?(a.title=l,a.body=d):i.items.push({id:`compact-${X}`,kind:"note",title:l,body:d,live:!0}),A("note","compacting context")}else if(o.type==="compaction_end"){let s=i.items.find(y=>y.id===`compact-${X}`),a=o.result,l="compacted",d;if(o.aborted)d="cancelled";else if(o.errorMessage)d=`failed: ${o.errorMessage}`;else if(a){let y=Math.round(a.tokensBefore/1e3),c=a.estimatedTokensAfter!==void 0?Math.round(a.estimatedTokensAfter/1e3):void 0,p=a.estimatedTokensAfter!==void 0?a.tokensBefore-a.estimatedTokensAfter:void 0,b=p!==void 0&&p<2e3;d=c!==void 0?`${y}k \u2192 ${c}k tokens \xB7 older turns summarized${b?`
|
|
28
|
+
this freed almost nothing; the window may be too small for this work`:""}`:`${y}k tokens \xB7 older turns summarized`}else d="nothing to compact";s?(s.title=l,s.body=d,s.live=!1):i.items.push({id:`compact-${X}`,kind:"note",title:l,body:d}),u.percent=Me(k),A("note",void 0)}else if(o.type==="message_start"&&o.message.role==="user"){let s=Xs(o.message);s&&(i.items=Js(i.items,s,`u-${o.message.timestamp}`)),vo()}else if(o.type==="message_end"&&o.message.role==="assistant"){let s=i.items.find(l=>l.id===`live-${X}`);s&&(s.id=`done-${X}`);let a=o.message.errorMessage;a&&s?(s.title="failed",s.kind="error",s.body=ce.trim()?`${a}
|
|
29
|
+
|
|
30
|
+
${ce.trim()}`:a):a&&i.items.push({id:`e-${o.message.timestamp}`,kind:"error",title:"failed",body:a}),X+=1,ce="",u.percent=Me(k)}else if(o.type==="agent_settled"){u.live=!1;let s=[...k.getSteeringMessages()].map(a=>a.trim()).filter(Boolean);if(s.length>0){let a=w.getText().trim();w.setText(a?`${s.join(`
|
|
31
|
+
`)}
|
|
32
|
+
${a}`:s.join(`
|
|
33
|
+
`));let l=new Set(s);for(let d of i.items)d.kind==="user"&&d.pending&&l.has(d.body.trim())&&(d.pending=void 0);m("queued",`${s.length} unread message${s.length===1?"":"s"} were never read and are back in the editor`)}for(let a of i.items)a.kind==="user"&&a.pending&&(a.pending=void 0);if(f(jt),jt="",A("run",void 0),qt){let a=i.items.find(l=>l.id===`live-${X}`);a?(a.id=`stopped-${X}`,a.title="stopped",a.body=ce.trim()||"(no output)",a.live=!1):i.items.push({id:`stopped-${X}`,kind:"note",title:"stopped",body:"run cancelled"}),X+=1,ce="",m("stopped","run cancelled by Esc"),qt=!1}u.percent=Me(k),A("note",void 0),Kt(void 0),qi(e.cwd).then(a=>{a!==null&&(u.git=a,v())}),w.disableSubmit=!1}else o.type==="thinking_level_changed"?u.setThinking(o.level):o.type==="auto_retry_start"?(A("note",void 0),Kt({attempt:o.attempt,maxAttempts:o.maxAttempts,error:o.errorMessage,until:Date.now()+o.delayMs})):o.type==="auto_retry_end"&&(Kt(void 0),o.success?m("retry",`answered on attempt ${o.attempt} after a retry`):A("note",`retry ${o.attempt} gave up${o.finalError?` \xB7 ${Bn(o.finalError)}`:""}`));Zi(),v()},zt=k.subscribe(xo),So=setInterval(()=>{let o=F!==void 0&&Date.now()<K;if((Qe||k.isStreaming||u.settling()||i.entering()||se||o||u.atCeiling()||u.flashing()||u.activity.retry!==void 0)&&v(),(Qe||k.isStreaming)&&!we&&!Ie&&Date.now()-Ze>oc){Ie=!0;let s=Vt,a=Math.round((Date.now()-Ze)/1e3);A("note",s?`${s} has been running for ${a}s \u2014 it may be blocked; esc cancels`:`no answer yet after ${a}s \u2014 the provider may be stalled; ctrl+c cancels`),v()}},nc);So.unref?.();let Co=async o=>{Ee?.(),Ee=void 0,zt(),Ft&&$s(Ft,k.getSessionStats().sessionId),io=void 0,Dt=0;let s=k.getSessionStats().sessionId;yn(s),kn(s),await rt.dispose(),k.dispose(),k=o.session,oo=o.setCompressToolOutput,rt=new ze({initial:Object.keys(Le().mcpServers),apply:async(a,l)=>{if(await Se(),a.length>0||l.length>0){let d=[];a.length>0&&d.push(`connected ${a.join(", ")}`),l.length>0&&d.push(`stopped ${l.join(", ")}`),m(a.length>0?"mcp connected":"mcp stopped",d.join("; "))}},report:a=>G(a)}),X=0,ce="",i.items=[],i.scrollOffset=0,o.note&&i.items.push({id:"note",kind:"note",title:"note",body:o.note}),i.items.push(...St(k.state.messages)),u.model=o.modelLabel.split("/").at(-1)||"no-model",u.setThinking(k.thinkingLevel),he(),u.percent=Me(k),Ot(),u.abandonAnimations(),A("tally",void 0),A("run",void 0),w.setAutocompleteProvider(new Hi(zn(k),e.cwd)),w.disableSubmit=!1,bo(k),zt=k.subscribe(xo),v()},_e=async()=>{if(ro)return;ro=!0,clearInterval(So),zt();try{let s=Nr(Lr);if(s.config.hooks.SessionEnd){let{outcome:a}=await Fr(s.config,"SessionEnd",{hook_event_name:"SessionEnd",cwd:process.cwd(),reason:"quit"},{cwd:process.cwd()});a.error&&m("hooks",`SessionEnd hook: ${a.error}`)}}catch{}await rt.dispose();let o=k.getSessionStats().sessionId;Lt.close(k.getSessionStats().cost),yn(o),kn(o),k.dispose(),r.stop(),process.stdout.write("\x1B[0m"),process.exit(0)},Ao=0,Yt=async(o=!1)=>{let s=Date.now();if(!o&&s-Ao<600*1e3)return;Ao=s;let a=d=>{if(process.env.HOWTOFIX_CHECKIN_DEBUG==="1")try{_l(`${P}/checkin-debug.log`,`${new Date().toISOString()} ${d}
|
|
34
|
+
`)}catch{}},l=async()=>{try{let d=new Set((await k.modelRuntime.getAvailable()).map(C=>C.provider).filter(C=>oe(C))),y=ye.find(C=>d.has(C));if(a(`providers=${[...d].join(",")||"(none)"} target=${y??"(none)"}`),!y)return!1;let c=(await k.modelRuntime.getAuth(y))?.auth?.apiKey,p=c?.trim().match(/^\$\{?([A-Za-z_][A-Za-z0-9_]*)\}?$|^\{env:([A-Za-z_][A-Za-z0-9_]*)\}$/),b=C=>C?(process.env[C]??"").trim():"",g=p?b(p[1]??p[2])||void 0:c?.trim()||void 0;if(!g)for(let C of["HOWTOFIX_API_KEY","HOWTOFIX_VIP_API_KEY","HOWTOFIX_FREE_API_KEY"]){let R=b(C);if(R){g=R,a(`key dari fallback ${C}`);break}}if(a(`key=${g?`ada(${g.length})`:"(kosong)"}${p?" dari env":""}`),!g)return!1;let x=await Hn(g);if(a(`status ok=${x.ok} enabled=${x.enabled} claimed=${x.checkedInToday} msg=${x.message}`),!x.ok||!x.enabled||x.checkedInToday)return!0;let $=await Ci(g);return a(`claim ok=${$.ok} awarded=${$.quotaAwarded} msg=${$.message}`),$.ok?(m("check-in",`daily check-in claimed: +${Kn($.quotaAwarded)} credited to your howtofix.id account`),v()):$.blocked&&m("check-in",$.message),!0}catch(d){return a(`error ${d.message}`),!1}};await l()||(await new Promise(d=>setTimeout(d,4e3)),await l())},To=async o=>{let s=Lt.check(k.getSessionStats().cost);if(s!==void 0){G(`budget reached: $${s.spent.toFixed(4)} of $${s.limit.toFixed(2)} \u2014 raise it with --max-budget-usd, or start without the flag`);return}let a=k.isStreaming,l=`you-${Date.now()}`;i.items.push({id:l,kind:"user",title:"you",body:o,pending:a?!0:void 0}),a||(A("tally",void 0),Xe.clear(),Ht.clear(),A("run","thinking"),u.beginRun()),v(),w.disableSubmit=!1;let d=Pr(o,e.cwd);jt=o,await Qi(),Qe=!0;let y=a?k.prompt(d,{streamingBehavior:"steer"}):k.prompt(d);Qe=!1,y.then(()=>Yt()).catch(c=>G(c instanceof Error?c.message:String(c)))},Xt=o=>{let s=o.trim();if(s){if(re){let a=re;re=void 0,w.setText(""),a(s);return}if(w.setText(""),w.addToHistory(s),s.startsWith("!")){let a=s.slice(1).trim();if(!a)return;i.items.push({id:`sh-${Date.now()}`,kind:"tool",title:"$",body:a}),A("run","shell"),v(),k.executeBash(a,l=>{A("run",`shell \xB7 ${l.length} bytes`),v()}).then(l=>{let d=l.output.trim();i.items.push({id:`sh-out-${Date.now()}`,kind:l.exitCode===0?"result":"error",title:`exit ${l.exitCode??"?"}`,body:d||"(no output)"}),A("tally",void 0),v()}).catch(l=>G(l instanceof Error?l.message:String(l)));return}if(s.startsWith("/")){Ne(s);return}To(s)}};w.onSubmit=Xt;let Jt=0,tt=Zs(),Mo=0,nt=()=>{Ms().then(o=>{o.ok?w.insertTextAtCursor(o.text):m("paste",o.reason),v()}).catch(o=>{m("paste",`could not read the clipboard: ${o instanceof Error?o.message:String(o)}`),v()})};n=nt;let Ro=o=>gn(ke(P).rightClickPaste)&&o.type==="press"&&o.button==="right";r.addInputListener(o=>{if(be){if(Y(o,"escape"))return Wt(),{consume:!0};let a=Bi(),l=a.matches(o,"tui.select.up"),d=a.matches(o,"tui.select.down");if(l||d){let c=be.getTreeList().getSelectedNode()?.entry.id,p=ea(),b=c===void 0?-1:p.indexOf(c);if(l?b===0:b===p.length-1)return v(),{consume:!0}}return be.handleInput(o),v(),{consume:!0}}if(Z&&H&&Y(o,"escape"))return ee?(ee=!1,m("workflow","panel keys off; the editor has the keyboard")):I.expanded?(I.expanded=!1,m("workflow","collapsed the drill-in")):(eo(),m("workflow","panel unpinned; the run is still in the transcript")),_t(),v(),{consume:!0};if(se)return se.handleInput(o),v(),{consume:!0};if(Y(o,"escape")){if(tt.disarm())return m("connect","sign-in cancelled \u2014 run /connect again when you have a token"),v(),{consume:!0};if(k.isStreaming){qt=!0;let l=[...k.getSteeringMessages()].map(d=>d.trim()).filter(Boolean);if(l.length>0){let d=w.getText().trim();w.setText(d?`${l.join(`
|
|
35
|
+
`)}
|
|
36
|
+
${d}`:l.join(`
|
|
37
|
+
`));let y=new Set(l);for(let c of i.items)c.kind==="user"&&c.pending&&y.has(c.body.trim())&&(c.pending=void 0);m("queued",`${l.length} unread message${l.length===1?"":"s"} returned to the editor`)}return k.abort(),A("note","stopping"),v(),{consume:!0}}let a=Date.now();if(w.getText().length===0&&a-Jt<600)return Jt=0,uo(),{consume:!0};Jt=a;return}if(Y(o,"ctrl+c")||Ss(o)){if(k.isStreaming)k.abort(),A("note","stopping"),v();else if(w.getText().length>0)w.setText(""),A("note","draft cleared; ctrl+c again quits"),v();else{let a=Date.now();a-Mo<2e3?_e():(Mo=a,A("note","press ctrl+c again to quit"),v())}return{consume:!0}}if(Y(o,"ctrl+d")&&w.getText().length===0)return _e(),{consume:!0};let s=Math.max(1,i.viewportHeight-1);if(Y(o,"pageUp"))return i.scrollOffset+=s,v(),{consume:!0};if(Y(o,"pageDown"))return i.scrollOffset=Math.max(0,i.scrollOffset-s),v(),{consume:!0};if(Y(o,"home"))return i.scrollOffset=Number.MAX_SAFE_INTEGER,v(),{consume:!0};if(Y(o,"end"))return i.scrollOffset=0,v(),{consume:!0};if(Y(o,"ctrl+v"))return nt(),{consume:!0};if(Y(o,"ctrl+l"))return i.scrollOffset=0,r.scrollToBottom(),v(),{consume:!0};if(Y(o,"ctrl+e")){let a=[...i.items].reverse().find(l=>(l.full?.length??0)>0);return a?(a.expanded=a.expanded!==!0,v(),{consume:!0}):(m("expand","nothing to expand in this transcript yet"),{consume:!0})}if(Y(o,"ctrl+o")&&!k.isStreaming)return i.items=[{id:"cleared",kind:"note",title:"bench",body:"screen cleared. session history is still stored."}],v(),{consume:!0};if(Y(o,"ctrl+t"))return Pe(ri(u.thinking)),{consume:!0};if(Y(o,"ctrl+shift+t"))return Pe(si(u.thinking)),{consume:!0};if(Y(o,ji)&&Z&&H)return ee=!ee,m("workflow",ee?"panel keys active; Esc gives the keyboard back":"panel keys off; the editor has the keyboard"),_t(),v(),{consume:!0};if(ee&&Z&&H){let a=Oi(o);if(a){let l=vn(H,Date.now());if(a==="stop")return L?(L(),L=null,m("workflow","stopping the run; in-flight agents resolve as null")):m("workflow","the run has already finished"),{consume:!0};if(a==="save"){let d=Wi(Ji,rr);return m("workflow",d.ok?`saved ${d.path}`:d.reason),v(),{consume:!0}}return Object.assign(I,Li(I,a,l)),_t(),v(),{consume:!0}}}});let Zt=o=>{let s=a=>{A("prompt",`API key for ${a}. Paste it, then press enter.`),v();let l=re;re=d=>{re=l;let y=d.trim();if(!y){A("prompt",void 0),v();return}k.modelRuntime.setRuntimeApiKey(a,y).then(()=>k.modelRuntime.login(a,"api_key",{prompt:async()=>y,notify:()=>{}}).then(()=>m("login",`saved API key for ${a}`),c=>m("login",`key set for this session, but it could not be saved (${c instanceof Error?c.message:String(c)}); run /login again after restarting`)),c=>m("login",c instanceof Error?c.message:String(c)))}};if(o){s(o);return}k.modelRuntime.getAvailable().then(a=>{let l=[...new Set(a.map(d=>d.provider))].sort();if(l.length===0){m("login","no providers are configured; pass one explicitly, e.g. /login nrimo");return}_("Login",l.map(d=>({value:d,label:d})),s)},a=>m("login",a instanceof Error?a.message:String(a)))},Eo=async(o,s)=>{let a=le(P,"models.json"),l,d=!1;try{l=JSON.parse(qn(a,"utf8"))}catch(W){if(!(W instanceof Error&&"code"in W&&W.code==="ENOENT"))return`could not read ${a}; the models were not added`;l={providers:{}},d=!0}(!l.providers||typeof l.providers!="object")&&(l.providers={});let y=l.providers[o];y||(y=fr(),l.providers[o]=y,d=!0);let c=Array.isArray(y.models)?y.models:[],p=br(c,s),b=await mr(P).catch(()=>({index:new Map})),g=await kr((await k.modelRuntime.getAuth(o))?.auth?.apiKey??""),x=gr(hr(c,s,b.index,g));y.models=x.models;try{Ki(P,{recursive:!0}),ie(a,`${JSON.stringify(l,null,2)}
|
|
38
|
+
`)}catch{return`could not write ${a}; the models were not added`}let $=!1;try{await k.modelRuntime.refresh(),$=!0}catch{$=!1}let C=x.changed>0?`, repaired ${x.changed}`:"",R=$?"":"; restart the CLI to see them all",U=d?` (created ${a})`:"";return p===0?`all ${s.length} models were already configured${C}${U}${R}`:`added ${p} model(s) to "${o}"${C}${U}${R}`},Oe=(o,s)=>{(async()=>{if(!o){let g=await vr({onProgress:$=>{let C="";try{let U=le(P,".howtofix");Ki(U,{recursive:!0,mode:448});let W=le(U,"connect-url.txt"),B=$.kind==="browser"?[$.url]:[$.url,`code: ${$.code}`];Vn(W,B.join(`
|
|
39
|
+
`)+`
|
|
40
|
+
`,{mode:384}),C=W}catch{C=""}let R=C?[` saved to ${C}`]:[];$.kind==="browser"?(Ke($.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 ${$.url}`,...R].join(`
|
|
41
|
+
`))):(Ke($.url),m("connect",["finish signing in to howtofix.id:",` 1. go to ${$.url}`,` 2. enter the code: ${$.code}`," waiting\u2026",...R].join(`
|
|
42
|
+
`))),v()}});if(g.ok){tt.disarm(),A("prompt",void 0),Oe(g.token,g.credential);return}let x=await Ke(ln);m("connect",[`browser sign-in: ${g.message}`,"","connect with a token instead:",` 1. ${x?"the keys page is opening in your browser":`open ${ln}`}`," 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(`
|
|
43
|
+
`)),v();return}if(!pr(o)){m("connect","that does not look like a howtofix token; the Console issues tokens that start with sk-");return}A("note",`connecting to howtofix.id (${cn(o)})`),v();let a=await dn(o);if(!a.ok){A("note",void 0),m("connect",a.message),v();return}let l=await Eo("howtofix",a.models);await k.modelRuntime.setRuntimeApiKey("howtofix",o);let d;try{await k.modelRuntime.login("howtofix","api_key",{prompt:async()=>o,notify:()=>{}})}catch(g){d=`this sign-in could not be saved (${g instanceof Error?g.message:String(g)}); run /connect again after restarting`}s&&(Tr(P,s)?ge=s:d=`this sign-in renews itself, but the pair could not be saved to ${xr(P)}; it will expire in hours and need /connect again`);let y=!!k.model&&k.model?.provider!==void 0&&u.model!=="unknown",c,p;if(!y)try{let g=(await k.modelRuntime.getAvailable()).filter(C=>oe(C.provider)),$=wt(g.map(C=>C.id)).slice(0,4);for(let C of $){if(!(await wr(C,o)).ok)continue;let U=g.find(W=>W.id===C);if(U){await k.setModel(U),u.model=U.id,he(),c=`${U.provider}/${U.id}`;break}}c||(p=$.length>0?`none of the first ${$.length} models answered (${$[0]} did not)`:"the account lists no chat model")}catch(g){p=g instanceof Error?g.message:String(g)}A("note",void 0),Yt(!0);let b=await Ae(o);m("connect",[`connected ${cn(o)} \u2014 ${a.message}`,l,ot("howtofix",b),c?`using ${c} (change it with /model)`:`pick a model with /model, then send a prompt${p?` (auto-select failed: ${p})`:""}`,d].filter(g=>!!g).join(`
|
|
44
|
+
`)),v()})().catch(a=>{A("note",void 0),m("connect",a instanceof Error?a.message:String(a)),v()})},Po=o=>{(async()=>{let s=Un(o);if(!s){m("connect",["that is not an account credential."," /connect <email>:<password>"," /connect <base64 of email:password>"].join(`
|
|
45
|
+
`)),v();return}A("note",`signing in as ${s.username}`),v();let{token:a}=await ki($r,s.username,s.password,it),l=wi(P,s.username,s.password);A("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(`
|
|
46
|
+
`)),v(),Oe(a)})().catch(s=>{A("note",void 0),m("connect",s instanceof Error?s.message:String(s)),v()})},ot=(o,s)=>{if(!s.ok)return[`${o} account`,` ${s.message}`].join(`
|
|
47
|
+
`);if(s.unlimited)return[`${o} account`," quota no limit on this token"].join(`
|
|
48
|
+
`);if(s.limit===void 0||s.used===void 0){let a=[`${o} account`],l=d=>`${d.toFixed(2)} ${s.unit}`;return s.limit!==void 0&&a.push(` granted ${l(s.limit)}`),s.used!==void 0&&a.push(` spent ${l(s.used)}`),s.remaining!==void 0&&a.push(` remaining ${l(s.remaining)}`),a.join(`
|
|
49
|
+
`)}return pi(o,s.limit,s.used,s.unit).join(`
|
|
50
|
+
`)},Le=()=>({mcpServers:jr()}),da=o=>{let s=Object.keys(o??{});return s.length===0?[]:s.map(a=>` mcp ${a} ${lt(o[a])}`)},ua=o=>{let s=Jo(o.dir,o.manifest),a=o.manifest.skills.join(", ");return[o.manifest.description,` category ${o.manifest.category}`,` version ${o.manifest.version}`,` skills ${a}`,o.manifest.prompt?` prompt ${o.manifest.prompt}`:" prompt (none)",` size ${s} bytes of skill text`,` source ${o.source}`,...da(o.manifest.mcp)].join(`
|
|
51
|
+
`)},Io=o=>{let s=[ua(o),""];if(o.manifest.prompt){let a=le(o.dir,o.manifest.prompt);Et(a)&&s.push(`--- ${o.manifest.prompt} ---`,qn(a,"utf8").trim(),"")}for(let a of o.manifest.skills){let l=le(o.dir,"skills",a,"SKILL.md");Et(l)&&s.push(`--- skills/${a}/SKILL.md ---`,qn(l,"utf8").trim(),"")}return s.join(`
|
|
52
|
+
`)},Se=async()=>{await k.reload()},Qt=!1,_o=async o=>{if(Qt){m("preset","an install is already running; wait for it to finish");return}Qt=!0;try{let s;try{s=await o()}catch(c){G(`preset not installed: ${c instanceof Error?c.message:String(c)}`);return}if(!s.ok||!s.name){G(`preset not installed:
|
|
53
|
+
${s.problems.join(`
|
|
54
|
+
`)}`);return}await Se();let a=te(e.cwd).entries.find(c=>c.manifest.name===s.name),l=a?.manifest.integrates||a?.manifest.mcp,d=l?`
|
|
55
|
+
integration disabled by default; run /preset enable ${s.name} when you want to use it`:await Oo(s.name);l&&a&&Vn(le(a.dir,".disabled"),`installed
|
|
56
|
+
`);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}
|
|
57
|
+
${y}${d}`)}finally{Qt=!1}},rt=new ze({initial:Object.keys(Le().mcpServers),apply:async(o,s)=>{if(await Se(),o.length>0||s.length>0){let a=[];o.length>0&&a.push(`connected ${o.join(", ")}`),s.length>0&&a.push(`stopped ${s.join(", ")}`),m(o.length>0?"mcp connected":"mcp stopped",a.join("; "))}},report:o=>G(o)}),st=async()=>{let o=Object.keys(Le().mcpServers);return await rt.reconcile(o)},Oo=async o=>{let{entries:s}=te(e.cwd),l=s.find(c=>c.manifest.name===o)?.manifest.mcp;if(!l||Object.keys(l).length===0)return"";let d=on(l);if(d.problems.length>0)return`
|
|
58
|
+
MCP: ${d.problems.join("; ")}`;let y=[];if(d.added.length>0){let c=await st(),p=d.added.filter(b=>c.added.includes(b));y.push(p.length>0?`MCP servers connected: ${p.join(", ")}`:`MCP servers added to mcp.json: ${d.added.join(", ")}`)}return d.skipped.length>0&&y.push(`MCP servers kept as they were (already configured): ${d.skipped.join(", ")}`),y.length>0?`
|
|
59
|
+
${y.join(`
|
|
60
|
+
`)}`:""},Lo=o=>_o(async()=>Qo(o,dt(e.cwd))),No=o=>{let s=o.sizeKb>=1024?`${(o.sizeKb/1024).toFixed(1)} MB`:`${o.sizeKb} KB`;return m("preset",[`downloading ${o.title}`,` from ${o.repo} @ ${o.sha.slice(0,7)}`,` skill ${o.skill}${o.modelInvocable===!1?" (invoke-only: the model cannot choose it)":""}`,` size ~${s} \xB7 ${o.license}`," checking the pinned commit and the contents the registry recorded\u2026"].join(`
|
|
61
|
+
`)),_o(()=>nr(o,dt(e.cwd)))},en=(o,s)=>{_(s,o.map(a=>({value:a.name,label:a.title,description:a.description})),a=>{let l=o.find(y=>y.name===a);if(!l)return;let d=l.sizeKb>=1024?`${(l.sizeKb/1024).toFixed(1)} MB`:`${l.sizeKb} KB`;_(l.title,[{value:"install",label:"Install",description:`download ~${d} 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"){No(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 ~${d}`,`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(`
|
|
62
|
+
`));return}jo()})},()=>v())},Ce=(o,s)=>{_(s,o.map(a=>({value:a.manifest.name,label:a.manifest.title,description:a.manifest.skills.length>0?`${a.manifest.skills.join(", ")} \u2014 ${a.manifest.description}`:a.manifest.description})),a=>{let l=o.find(d=>d.manifest.name===a);l&&_(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"}],d=>{if(d==="install"){Lo(l.dir);return}if(d==="view"){m(`preset ${l.manifest.name}`,Io(l));return}Uo("")})},()=>v())},Fo=o=>o.filter(s=>s.manifest.integrates!==void 0),fa=()=>{let{entries:o}=te(e.cwd),s=Fo(o);if(s.length===0){m("integrations","nothing installed that drives another application. /preset lists the rest.");return}Ce(s,"Integrations")},jo=()=>{let{entries:o}=te(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"}],a=Fo(o).length;a>0&&s.push({value:"integrations",label:"Integrations",description:`${a} that drive another application, and need setup there first`}),_("Presets",s,l=>l==="mcp"?tn():l==="integrations"?fa():ma())},tn=()=>{let{entries:o,problems:s}=Ho();if(s.length>0&&m("mcp problems",s.join(`
|
|
63
|
+
`)),o.length===0){m("mcp catalogue","no servers in the catalogue. run /mcp to inspect the ones already configured.");return}let a=new Set(Object.keys(Le().mcpServers)),l=new Map,d=[];for(let y of Bo(o)){let c=Go(o,y);l.set(y,()=>Do(c,y));let p=c.filter(b=>a.has(b.name)).length;d.push({value:y,label:y,description:`${c.map(b=>b.title).join(", ")}${p>0?` \xB7 ${p} configured`:""}`})}l.set("all-mcp",()=>Do(o,"All MCP servers")),d.push({value:"all-mcp",label:"All servers",description:`${o.length} available${a.size>0?`, ${a.size} already configured`:""}`}),_("MCP servers",d,y=>l.get(y)?.())},Do=(o,s)=>{let a=Le().mcpServers;_(s,o.map(l=>{let d=a[l.name]!==void 0?"configured \xB7 ":"";return{value:l.name,label:l.title,description:`${d}${l.description}`}}),l=>{let d=qo(o,l);if(!d)return;let y=a[d.name]!==void 0,c=Vo(d),p=[d.description,"",`server ${d.name}`,`runs ${lt(ct(d))}`,...d.needs&&d.needs.length>0?[`needs ${d.needs.join(", ")}`,c.length>0?` ${c.join(", ")} ${c.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"]:[],...d.docs?[`docs ${d.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(`
|
|
64
|
+
`),b=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"}];_(d.title,b,g=>{if(g==="view"){m(`mcp ${d.name}`,p);return}if(g==="install"){let x=[];if(d.preset){let R=le(zo(),"mcp",d.preset.replace(/^mcp-/,""));if(Et(le(R,"preset.json"))){let U=Zo(R,dt(e.cwd));U.ok||x.push(...U.problems)}}let $=on({[d.name]:ct(d)});if(x.push(...$.problems),x.length>0){G(`mcp not installed:
|
|
65
|
+
${x.join(`
|
|
66
|
+
`)}`);return}if($.skipped.length>0){m("mcp install",`${d.name} is already in mcp.json; it was left as it is.`);return}let C=c.length>0?`
|
|
67
|
+
${c.join(", ")} ${c.length===1?"is":"are"} not set in this shell \u2014 the value is read when the server connects, so export ${c.length===1?"it":"them"} and reload, or it will fail every call`:"";m("mcp installed",[`added ${d.name} to mcp.json${d.preset?" and installed its skill preset":""}`,` runs ${lt(ct(d))}`,` connecting now; /mcp shows its state and its tools${C}`].join(`
|
|
68
|
+
`)),st().catch(R=>{G(`mcp installed but the session was not updated: ${R instanceof Error?R.message:String(R)}`)});return}if(g==="remove"){let x=at([d.name]);if(x.problems.length>0){G(`mcp not removed:
|
|
69
|
+
${x.problems.join(`
|
|
70
|
+
`)}`);return}st().then($=>{m("mcp remove",$.removed.length>0?`removed ${$.removed.join(", ")} from mcp.json and stopped ${$.removed.length===1?"it":"them"}`:x.removed.length>0?`removed ${d.name} from mcp.json`:`${d.name} was not in mcp.json`)}).catch($=>{G(`mcp removed from config but the session was not updated: ${$ instanceof Error?$.message:String($)}`)});return}tn()})},()=>tn())},ma=()=>{let{entries:o,problems:s}=te(e.cwd),{entries:a,problems:l}=ut();s.length>0&&m("preset problems",s.join(`
|
|
71
|
+
`)),l.length>0&&m("preset problems",l.join(`
|
|
72
|
+
`));let d=o.filter(p=>p.source==="installed"),y=new Map,c=[];d.length>0&&(y.set("installed",()=>Ce(d,"Installed presets")),c.push({value:"installed",label:"Installed",description:`${d.length} active`}));for(let p of Yo(o)){let b=Xo(o,p),g=sn(a,p);y.set(p,()=>g.length>0?Wo(b,p,g):Ce(b,p));let x=b.map($=>`${$.manifest.title} (${$.manifest.skills.join(", ")})`).join(", ");c.push({value:p,label:p,description:`${x}${g.length>0?` \xB7 ${g.length} more to download`:""}`})}for(let p of tr(a)){if(o.some(g=>g.manifest.category===p))continue;let b=sn(a,p);y.set(p,()=>en(b,p)),c.push({value:p,label:p,description:`${b.length} to download`})}if(y.set("all",()=>Ce(o,"All presets")),c.push({value:"all",label:"All presets",description:`${o.length} ready to install`}),a.length>0){y.set("hub",()=>Wo([],"Community presets",a));let p=new Set(a.map(b=>b.repo)).size;c.push({value:"hub",label:"Community",description:`${a.length} to download, from ${p} projects`})}_("Skill presets",c,p=>y.get(p)?.())},Wo=(o,s,a)=>{if(a.length===0){Ce(o,s);return}if(o.length===0){en(a,`${s} (download)`);return}_(s,[{value:"local",label:`Included (${o.length})`,description:"already on disk, no download"},{value:"hub",label:`Downloadable (${a.length})`,description:"fetched when installed"}],l=>l==="local"?Ce(o,s):en(a,s))},Uo=o=>{let[s,...a]=o.trim().split(/\s+/),l=a.join(" ").trim();if(!s){jo();return}if(s==="list"){let{entries:d}=te(e.cwd),y=d.filter(c=>c.source==="installed");if(y.length===0){m("preset list","nothing installed. run /preset to browse the catalogue.");return}m("preset list",y.map(c=>`${c.manifest.name} ${c.manifest.version} [${rn(c.dir)?"disabled":"active"}]
|
|
73
|
+
${c.manifest.description}
|
|
74
|
+
${c.dir}`).join(`
|
|
75
|
+
`));return}if(s==="show"){if(!l){m("preset show","usage: /preset show <name>");return}let{entries:d}=te(e.cwd),y=d.find(g=>g.manifest.name===l);if(y){m(`preset ${l}`,Io(y));return}let{entries:c}=ut(),p=an(c,l);if(!p){m("preset show",`no preset named "${l}". run /preset to list them.`);return}let b=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 ~${b}`,`category ${p.category}`,"","not installed. install it from /preset, or: /preset add-hub "+p.name].join(`
|
|
76
|
+
`));return}if(s==="add"){if(!l){m("preset add","usage: /preset add <git-url | directory>");return}Lo(l);return}if(s==="add-hub"){if(!l){m("preset add-hub","usage: /preset add-hub <name> (see /preset for names)");return}let{entries:d}=ut(),y=an(d,l);if(!y){m("preset add-hub",`"${l}" is not in the community registry. run /preset to browse it.`);return}No(y);return}if(s==="enable"||s==="disable"){if(!l){m(`preset ${s}`,`usage: /preset ${s} <name>`);return}let d=te(e.cwd).entries.find(c=>c.manifest.name===l&&c.source==="installed");if(!d){m(`preset ${s}`,`no installed preset named "${l}"`);return}let y=le(d.dir,".disabled");if(s==="disable"){Vn(y,`disabled
|
|
77
|
+
`);let c=d.manifest.mcp?at(Object.keys(d.manifest.mcp)):{removed:[],kept:[],problems:[]};st().then(()=>Se()).then(()=>m("preset",`disabled ${l}${c.removed.length?`; stopped ${c.removed.join(", ")}`:""}`)).catch(p=>G(`preset disable failed: ${p instanceof Error?p.message:String(p)}`));return}Ol(y,{force:!0}),Oo(l).then(c=>Se().then(()=>m("preset",`enabled ${l}${c}`))).catch(c=>G(`preset enable failed: ${c instanceof Error?c.message:String(c)}`));return}if(s==="remove"){if(!l){m("preset remove","usage: /preset remove <name>");return}let d=er(l,e.cwd);if(d.problems.length>0){m("preset remove",d.problems.join(`
|
|
78
|
+
`));return}let c=te(e.cwd).entries.find($=>$.manifest.name===l),p=new Set;for(let $ of te(e.cwd).entries)if($.manifest.name!==l)for(let C of Object.keys($.manifest.mcp??{}))p.add(C);let b=c?.manifest.mcp?at(Object.keys(c.manifest.mcp),p):{removed:[],kept:[],problems:[]},g=b.removed.length>0?`
|
|
79
|
+
MCP servers removed from mcp.json: ${b.removed.join(", ")}`:b.kept.length>0?`
|
|
80
|
+
MCP servers kept (still used by another preset): ${b.kept.join(", ")}`:"",x=b.problems.length>0?`
|
|
81
|
+
MCP: ${b.problems.join("; ")}`:"";Se().then(()=>{m("preset",`removed ${l}
|
|
82
|
+
${d.removed.join(`
|
|
83
|
+
`)}${g}${x}`)});return}m("preset",`unknown subcommand "${s}". try: list, show, add, add-hub, remove.`)},Ne=async o=>{let[s,...a]=o.slice(1).split(/\s+/),l=a.join(" ");if(s==="quit"||s==="exit"){_e();return}if(s==="help"){m("help",zn(k).map(c=>`/${c.name} ${c.description??""}`).join(`
|
|
84
|
+
`));return}if(s==="trust"){let c=new jl(P),p=c.get(e.cwd);if(l==="on"||l==="off"){let g=l==="on";c.set(e.cwd,g),m("trust",g?`trusted ${e.cwd}
|
|
85
|
+
its .hxf settings, SYSTEM.md and skills apply to the next session`:`no longer trusting ${e.cwd}
|
|
86
|
+
its .hxf settings, SYSTEM.md and skills are ignored`);return}let b=p===!0?"trusted":p===!1?"not trusted":"not decided (treated as not trusted)";m("trust",`${e.cwd}
|
|
87
|
+
${b}
|
|
88
|
+
|
|
89
|
+
/trust on trust this folder
|
|
90
|
+
/trust off stop trusting it`);return}if(s==="init"){let c=le(e.cwd,"AGENTS.md");if(Et(c)&&l!=="force"){m("init",`AGENTS.md already exists at ${c}. run /init force to overwrite.`);return}ie(c,Ko),m("init",`wrote ${c}; asking the agent to fill it in`),await k.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"){Zt(l);return}if(s==="connect"){let c=l.trim();if(c&&!c.startsWith("sk-")&&Un(c)){Po(c);return}if(c){Oe(c);return}let p=yi(P);if(p){Po(p.credential);return}Oe(""),A("prompt","paste your howtofix.id token, then press enter"),v();let b=re;tt.arm(()=>{re=b,A("prompt",void 0)}),re=g=>{tt.disarm(),Oe(g.trim())};return}if(s==="sync"){let c=new Set((await k.modelRuntime.getAvailable()).map(R=>R.provider).filter(R=>oe(R))),p=ye.find(R=>c.has(R));if(!p){m("sync","no howtofix.id account is connected; run /connect first");return}A("note",`re-syncing ${p} from howtofix.id`),v();let g=(await k.modelRuntime.getAuth(p))?.auth?.apiKey;if(!g){A("note",void 0),m("sync",`${p} has no usable key; run /connect to sign in again`),v();return}let x=await dn(g);if(!x.ok){A("note",void 0),m("sync",x.message),v();return}let $=await Eo(p,x.models),C=await Ae(g);A("note",void 0),m("sync",`${$}
|
|
91
|
+
${ot(p,C)}`),await k.modelRuntime.refresh(),v();return}if(s==="usage"){let c=new Set((await k.modelRuntime.getAvailable()).map(R=>R.provider).filter(R=>oe(R))),p=ye.find(R=>c.has(R));if(!p){m("usage","no howtofix.id account is connected; run /connect first");return}A("note","asking howtofix.id for the account usage"),v();let g=(await k.modelRuntime.getAuth(p))?.auth?.apiKey;if(!g){A("note",void 0),m("usage",`${p} has no usable key; run /connect to sign in again`),v();return}let x=await Ae(g),$=await Hn(g);A("note",void 0);let C=$.ok&&$.enabled?$.checkedInToday?`check-in: claimed today (+${Kn($.quotaToday)})`:"check-in: not claimed yet today (it claims itself on the next start)":"";m("usage",C?`${ot(p,x)}
|
|
92
|
+
${C}`:ot(p,x)),v();return}if(s==="logout"){let c=await k.modelRuntime.getAvailable(),p=[...new Set(c.map(b=>b.provider))].sort();if(p.length===0){m("logout","no providers are configured");return}_("Logout",p.map(b=>({value:b,label:b})),b=>{k.modelRuntime.logout(b).then(()=>m("logout",`logged out ${b}`),g=>m("logout",g instanceof Error?g.message:String(g)))});return}if(s==="providers"){let c=await k.modelRuntime.getAvailable(),p=[...new Set(c.map(b=>b.provider))].sort();p.sort((b,g)=>Number(oe(g))-Number(oe(b))),_("Providers",p.map(b=>({value:b,label:b})),b=>{let g=k.modelRuntime.getModels(b);if(g.length===0){Zt(b);return}_(b,g.map(x=>({value:x.id,label:x.id})),x=>{let $=g.find(C=>C.id===x);$&&k.setModel($,{persist:!0}).then(()=>{u.model=$.id,he(),m("providers",`${b}/${$.id}`)},()=>Zt(b))})});return}if(s==="name"){if(!l){m("name","usage: /name <session name>");return}k.setSessionName(l),m("name",`session name: ${l}`);return}if(s==="update"){A("note","checking for a newer release");try{await mo({current:it,install:!0})}finally{A("note",void 0)}return}if(s==="stats"){let c=k.getSessionStats(),p=k.getContextUsage(),b=$=>Number.isFinite($)?String($):";",g=As(k.sessionManager.getEntries()),x=g.hitRate===null?"cache hit rate unknown (no prompt billed yet)":`cache hit ${g.hitRate.toFixed(1)}% of ${g.cachedTokens+g.billedTokens} prompt tokens`;m("stats",[`session ${c.sessionId}`,c.sessionFile?`file ${c.sessionFile}`:"not persisted",`messages ${b(c.totalMessages)} (user ${b(c.userMessages)}, assistant ${b(c.assistantMessages)}, tools ${b(c.toolCalls)})`,`tokens in ${b(c.tokens.input)} out ${b(c.tokens.output)} cache ${b(c.tokens.cacheRead)}/${b(c.tokens.cacheWrite)}`,x,g.misses.length>0?`cache misses ${g.misses.length} (${b(g.missedTokens)} tokens re-billed) \u2014 last: ${Ts(g.misses[g.misses.length-1])}`:"cache misses none counted",`cost $${Number.isFinite(c.cost)?c.cost.toFixed(4):";"}`,p?`context ${p.percent===null||!Number.isFinite(p.percent)?"?":`${Math.round(p.percent)}%`} of ${p.contextWindow}`:"context unknown"].join(`
|
|
93
|
+
`));return}if(s==="diff"){let c=async $=>{try{let{stdout:C}=await Yn("git",$,{cwd:e.cwd,encoding:"utf8"});return C.trim()}catch{return""}},p=await c(["diff","--stat"])+`
|
|
94
|
+
|
|
95
|
+
`+await c(["diff","--","."]),[b="",g=""]=p.split(`
|
|
96
|
+
|
|
97
|
+
`,2),x=ls(g);m("diff",[b.trim(),x].filter(Boolean).join(`
|
|
98
|
+
|
|
99
|
+
`)||"working tree clean");return}if(s==="copy"){let c=[...k.state.messages].reverse().find(g=>g.role==="assistant"),b=(Array.isArray(c?.content)?c.content:[]).filter(g=>g.type==="text").map(g=>g.text).join("");if(!b){m("copy","nothing to copy");return}try{await Fl(b),m("copy",`copied ${b.length} characters`)}catch(g){m("copy",g instanceof Error?g.message:String(g))}return}if(s==="export"){let c=i.items.filter(g=>g.body.trim().length>0);if(c.length===0){m("export","nothing to export yet; the transcript is empty");return}let p=Nl(e.cwd,l||`howtofix-session-${Date.now()}.md`),b=[`# ${nn} session`,"",`model ${u.model}`,""];for(let g of c)b.push(`## ${g.title||g.kind}`,"",g.body,"");try{ie(p,b.join(`
|
|
100
|
+
`))}catch(g){m("export",`could not write ${p}: ${g instanceof Error?g.message:String(g)}`);return}m("export",`wrote ${p}`);return}if(s==="agents"){let[c="",...p]=l.split(/\s+/).filter(Boolean),b=p.join(" ").trim();if(c&&b){m("agents",await ns(c,b));return}m("agents",c?ts(c):es());return}if(s==="new"){let c=await e.reopen({noSession:!1});await Co(c),m("new","started a new session");return}if(s==="resume"){let c=await Dl.list(e.cwd);if(c.length===0){m("resume","no saved sessions for this folder");return}_("Resume session",c.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(Co,b=>G(b instanceof Error?b.message:String(b)))});return}if(s==="model"){let c=await k.modelRuntime.getAvailable(),p=c.filter($=>oe($.provider)),b=ur(P),g=p.length>0?p:b.size>0?c.filter($=>b.has($.provider)):[];if(g.length===0){m("model","no model configured yet \u2014 run /connect to sign in first");return}let x=l?g.find($=>`${$.provider}/${$.id}`===l||$.id===l):void 0;if(!l){_("Select model",g.map($=>({value:`${$.provider}/${$.id}`,label:$.id,description:[Ai($),$.provider].filter(Boolean).join(" \xB7 ")})),$=>{let C=g.find(R=>`${R.provider}/${R.id}`===$);C&&k.setModel(C,{persist:!0}).then(()=>{u.model=C.id,he(),m("model",`model ${$}`)})});return}if(!x){m("model",`unknown model ${l}`);return}await k.setModel(x,{persist:!0}),u.model=x.id,he(),m("model",`model ${x.provider}/${x.id}`);return}if(s==="thinking"){if(!l){_("Thinking level",q.map(c=>({value:c,label:c})),c=>Pe(c));return}if(!q.includes(l)){m("thinking",`thinking: ${q.join(", ")}`);return}Pe(l);return}if(s==="rtk"){let c=ke(P).compressToolOutput;if(!l){m("rtk",`compress tool output: ${c?"on":"off"}
|
|
101
|
+
/rtk on | /rtk off`);return}let p=l.toLowerCase();if(p!=="on"&&p!=="off"){m("rtk","rtk: on | off");return}let b=p==="on";if(b===c){m("rtk",`already ${p}`);return}if(!je(P,"compressToolOutput",b)){m("rtk","could not write the setting");return}oo(b),m("rtk",`compress tool output ${p}
|
|
102
|
+
long results are ${b?"summarised before the model reads them":"sent in full"}`);return}if(s==="compact"){try{await k.compact(l||void 0),m("compact","session compacted")}catch(c){m("compact",c instanceof Error?c.message:String(c))}return}if(s==="approval"){let c=p=>{_r(p),m("approval",mn[p])};if(!l){_("Approval mode",pt.map(p=>({value:p,label:p,description:mn[p]})),p=>c(p));return}if(!pt.includes(l)){m("approval",`modes: ${pt.join(", ")}`);return}c(l);return}if(s==="settings"){let c=()=>hn()?"off \u2014 everything runs":"on \u2014 critical commands are refused",p=()=>{_("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"}],E=>{let J=E==="off",z=je(P,"skipPermissions",J);if(pn(J),u.skipPermissions=J,v(),!z){m("settings","changed for this session, but settings.json could not be written (is it valid JSON?)");return}m("settings",J?"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 ${c()}.`])},b=()=>{_("Thinking level",q.map(E=>({value:E,label:E,description:E===u.thinking?"current":void 0})),E=>Pe(E),void 0,!1,[`Currently ${u.thinking}.`])},g=()=>{_("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"}],E=>{let J=E!=="off",z=je(P,"autoUpdate",J);m("settings",z?`auto-update ${J?"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 ${Er(`${P}/settings.json`)?"on":"off"}.`])},x=()=>{let E=We("status",e.cwd,k.getSessionStats().sessionId);_("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"}],J=>m("dcp",We(J,e.cwd,k.getSessionStats().sessionId)),void 0,!1,E.split(`
|
|
103
|
+
`).slice(0,2))},$=()=>{Ne("/model")},C=()=>{Ne("/proxy")},R=()=>{let E=ke(P).rightClickPaste,J=process.platform==="win32"?"off":"on";_("Right click",[{value:"auto",label:"auto",description:`follow the terminal (${J} 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"}],z=>{let Fe=Dr(P,z);m("settings",Fe?z==="auto"?`right click follows the terminal \u2014 ${gn("auto")?"the CLI pastes":"the terminal pastes"} here.`:`right click ${z==="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 ${E}.`])},U=()=>{let E=ke(P).agents,J=[1,2,3,4].map(z=>({value:String(z),label:String(z),description:z===1?"one child at a time":z===Ue()?"current \u2014 sized to this machine":`${z} children at once`}));_("Agent concurrency",[{value:"auto",label:"auto",description:`size it to the machine (now ${Ue()}, max ${Jr})`},...J],z=>{let Fe=z==="auto"?void 0:Number(z),pa=Wr(P,Fe);m("settings",pa?Fe===void 0?`agent concurrency follows the machine \u2014 ${Ue()} at a time.`:`agent concurrency set to ${Fe} \u2014 shared by task and workflow.`:"agent concurrency changed for this session, but settings.json could not be written (is it valid JSON?)"),v()},void 0,!1)},W=[{value:"permissions",label:"permissions",description:c()},{value:"thinking",label:"thinking",description:`${u.thinking} \u2014 how hard the model reasons`},{value:"model",label:"model",description:u.model},{value:"dcp",label:"context pruning",description:"fold stale ranges to save tokens"},{value:"proxy",label:"proxy",description:un(P)??fn()??"none \u2014 direct to the API"},{value:"rightclick",label:"right click",description:`paste: ${ke(P).rightClickPaste}`},{value:"agents",label:"agents",description:`${ke(P).agents??`auto (${Ue()})`} at once, shared by task and workflow`},{value:"autoupdate",label:"auto-update",description:"install a newer release on start"}];if(!l){_("Settings",W,E=>{E==="permissions"?p():E==="thinking"?b():E==="dcp"?x():E==="autoupdate"?g():E==="model"?$():E==="proxy"?C():E==="rightclick"?R():E==="agents"&&U()});return}let B=W.find(E=>E.value===l||E.label===l);if(B){B.value==="permissions"?p():B.value==="thinking"?b():B.value==="dcp"?x():B.value==="autoupdate"?g():B.value==="model"?$():B.value==="proxy"?C():B.value==="rightclick"?R():B.value==="agents"&&U();return}if(l==="on"||l==="off"){let E=l==="off",J=je(P,"skipPermissions",E);pn(E),u.skipPermissions=E,v(),m("settings",J?E?"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: ${W.map(E=>E.value).join(", ")} | on, off (permission checks)
|
|
104
|
+
usage: /settings <name>, or /settings to choose`);return}if(s==="proxy"){let c=un(P),p=fn(),b=()=>c?`proxy: ${c} (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",`${b()}
|
|
105
|
+
usage: /proxy <url> route requests through a proxy
|
|
106
|
+
/proxy off stop using one
|
|
107
|
+
/proxy env use HTTPS_PROXY / HTTP_PROXY / ALL_PROXY
|
|
108
|
+
Only traffic to the HowToFix API goes through it; a change applies on the next start.`);return}let g=l.trim();if(g==="off"||g==="none"){let R=ht(P,ft,""),U=mt(P),W=U.source==="env"?`the environment still sets one (${U.url})`:"requests go straight to the API";m("proxy",R?`proxy off \u2014 ${W} from the next message.`:"proxy changed for this session, but settings.json could not be written (is it valid JSON?)");return}if(g==="env"){let R=ht(P,ft,""),U=mt(P),W=U.source==="env"?U.url:void 0;m("proxy",R?W?`using the environment from the next message: ${W}`:"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=Rr(g);if(!x.ok){m("proxy",`not set: ${x.problem}`);return}if(!ht(P,ft,x.url)){m("proxy","settings.json could not be written (is it valid JSON?)");return}let C=mt(P);m("proxy",C.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 c=k.getActiveToolNames().sort();m("tools",c.length?c.join(`
|
|
109
|
+
`):"no tools enabled");return}if(s==="dcp"){m("dcp",We(l,e.cwd,k.getSessionStats().sessionId));return}if(s==="context"||s==="decompress"||s==="sweep"){m(s,We(`${s} ${l}`.trim(),e.cwd,k.getSessionStats().sessionId));return}if(s==="rewind"){uo();return}if(s==="undo"){if(!await $n(e.cwd)){m("undo","not a git repository");return}let c=await is(e.cwd);m("undo",c.ok?`undone: ${c.output}`:`undo failed: ${c.output}`),h(!0);return}if(s==="commit"){if(!$n(e.cwd)){m("commit","not a git repository");return}if(!await rs(e.cwd)){m("commit","nothing to commit");return}let c=l||`howtofix: session update ${new Date().toISOString().slice(0,16)}`,p=await ss(e.cwd,c);m("commit",p.ok?p.output:`commit failed: ${p.output}`),h(!0);return}if(s==="review"){if(!(await as(e.cwd)).trim()){m("review","no changes to review");return}Xt("Review the uncommitted changes. Report concrete issues with file evidence. Do not edit files.");return}if(s==="workflow"){if(l.trim()==="clear"){eo(),m("workflow","cleared the pinned workflow panel");return}if(!H){m("workflow","no workflow run in this session yet");return}let c=vn(H,Date.now()),p=c[I.selectedPhase];m("workflow",[`panel ${Z?"pinned above the editor":"unpinned"}`,`phase ${I.selectedPhase+1}/${c.length}: ${p?.title??"(none)"}`,`filter: ${I.filter}${I.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(`
|
|
110
|
+
`));return}if(s==="plan"){if(Yr()||bt().state==="pending"){wn(Vr(bt())),m("plan","plan mode off; edits are allowed again");return}wn(qr(bt())),m("plan",`plan mode armed \u2014 send your next prompt to start planning
|
|
111
|
+
plan file: ${zr()??"(unknown)"}`);return}if(s==="goal"){let c=l.trim();if(!c){m("goal",bn(gt()));return}let{goal:p,error:b}=Gr(gt(),"set",c,void 0,void 0);if(b){G(b);return}Br(p),await k.sendCustomMessage({customType:Kr,content:c,display:!1,details:p}),m("goal",`goal set
|
|
112
|
+
${bn(p)}`);return}if(s==="session"){let c=k.model;m("session",c?`${c.provider}/${c.id}`:"no model");return}if(s==="skills"){m("skills",xs(k.resourceLoader.getSkills().skills));return}if(s==="preset"){Uo(l);return}if(s==="roblox"){let{RobloxConnect:c,readBridgeEndpoint:p,describeStatus:b,parseRobloxSubcommand:g}=await import("./chunk-LAHVHRCS.js"),x=g(l);if(x){let W=new c(p(P));try{if(x.sub==="status"){let B=await W.tunnel("status").catch(()=>{});m("roblox",b(await W.status(),B))}else if(x.sub==="login"){m("roblox","opening Roblox in your browser to sign in\u2026");let B=await W.login({onUrl:E=>m("roblox",`if the browser did not open, go to:
|
|
113
|
+
${E}`)});m("roblox",B.message)}else if(x.sub==="logout")await W.logout(),m("roblox","signed out of Roblox");else{let B=x.rest==="off"?"stop":x.rest==="on"||x.rest===""?"start":void 0;if(!B)m("roblox","usage: /roblox tunnel on | off");else{let E=await W.tunnel(B);m("roblox",E.message??"done")}}}catch(B){m("roblox",B instanceof Error?B.message:String(B))}return}let $=te(e.cwd).entries.find(W=>W.manifest.name==="rotoolbox");if(!$||$.source!=="installed"){m("roblox","RoToolbox is not installed. Run /preset and install RoToolbox first.");return}let C=rn($.dir),R=k.getActiveToolNames().filter(W=>/roblox[-_]studio/i.test(W)),U=R.length>0;m("roblox",C?`RoToolbox: disabled
|
|
114
|
+
Enable with /preset enable rotoolbox
|
|
115
|
+
The MCP server and manager stay stopped while disabled.`:["RoToolbox: active",`MCP server: ${U?`connected \u2014 ${R.length} tool${R.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(`
|
|
116
|
+
`));return}let d=vs(o,k.resourceLoader.getSkills().skills.map(c=>c.name));if(d){To(d);return}let y=k.extensionRunner.getCommand(s??"");if(y){try{await y.handler(l,k.extensionRunner.createCommandContext())}catch(c){G(c instanceof Error?c.message:String(c))}return}m("command",`/${s??""} is not available in this screen yet`)};Ur((o,s)=>{let{promise:a,resolve:l}=Promise.withResolvers();return _(o,s.map(d=>({value:d,label:d})),l,()=>l("cancelled")),a}),process.on("SIGTERM",_e),Cs(()=>{_e()}),t.setTitle(`${nn} ${it}`),tc(),r.start(),r.requestRender(!0),Yt(!0);{let{maybeShowWelcome:o}=await import("./chunk-ID7ZE5GD.js");await o({cwd:e.cwd,note:e.note,signedIn:ge!==void 0,runSlash:s=>{Ne(s)},openExternal:s=>{Ke(s)}},_,m)}e.initialPrompt&&Xt(e.initialPrompt),await new Promise(()=>{})}var re,nc=1e3/30,oc=45e3;export{Zn as Dock,Xn as Hud,Jn as PinnedBlock,Zl as approvalDetail,wt as orderModelsForDefault,Jl as pickerPanel,gu as runWorkbench,zn as slashCommands,Ql as workflowPanel,Pt as workflowPanelFromRun,Qn as workflowRunOf};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{a as x}from"./chunk-UTYFLLSM.js";import{g as P,j as M}from"./chunk-SIXFT6QP.js";import{existsSync as z,readFileSync as ye}from"node:fs";import{join as xe}from"node:path";import{createHash as J,randomBytes as G}from"node:crypto";import{createServer as ne}from"node:http";import{execFileSync as X}from"node:child_process";import{createHmac as Q}from"node:crypto";import{readFileSync as ee}from"node:fs";import{arch as N,cpus as $,hostname as O,platform as _,userInfo as H}from"node:os";var te="howtofix-cli-hwid-v1";function v(e){try{let t=ee(e,"utf8").trim();return t.length>0?t:void 0}catch{return}}function F(e,t){try{let r=X(e,t,{encoding:"utf8",timeout:3e3,stdio:["ignore","pipe","ignore"]});return r.trim().length>0?r.trim():void 0}catch{return}}function re(){let e=_();if(e==="linux"){let t=v("/etc/machine-id");if(t)return{value:t,source:"machine-id",strong:!0};let r=v("/var/lib/dbus/machine-id");if(r)return{value:r,source:"dbus-machine-id",strong:!0};let s=v("/sys/class/dmi/id/product_uuid");return s?{value:s,source:"dmi-product-uuid",strong:!0}:void 0}if(e==="win32"){let r=F("reg",["query","HKLM\\SOFTWARE\\Microsoft\\Cryptography","/v","MachineGuid"])?.match(/MachineGuid\s+REG_SZ\s+(\S+)/i);return r?.[1]?{value:r[1],source:"windows-machine-guid",strong:!0}:void 0}if(e==="darwin"){let r=F("ioreg",["-rd1","-c","IOPlatformExpertDevice"])?.match(/"IOPlatformUUID"\s*=\s*"([^"]+)"/);return r?.[1]?{value:r[1],source:"platform-uuid",strong:!0}:void 0}}function U(){let e=re(),t=e?.value??[O(),_(),N(),H().username].join("\0"),r=e?.source??"hostname";return{id:Q("sha256",te).update(t).digest("hex").slice(0,32),source:r,strong:e?.strong??!1}}function j(e){return[e.id,e.source,O(),_(),N(),H().username,String($().length),$()[0]?.model??""]}var I="https://howtofix.id",se=300*1e3,L=3e3,K="/callback";function A(e){return e.toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function oe(){return A(G(32))}function ie(e){return A(J("sha256").update(e).digest())}function ae(){return A(G(16))}var ce="howtofix-cli-",ue="x-howtofix-client",le="cli";function C(e){let t=e??j(U());return ce+J("sha256").update(t.join("\0")).digest("hex").slice(0,32)}function de(){return{"content-type":"application/json",[ue]:le}}var fe=()=>new Promise((e,t)=>{let r=ne();r.once("error",t),r.listen(0,"127.0.0.1",()=>{let{port:s}=r.address();e({port:s,close:()=>r.close(),waitForCode:(o,n)=>new Promise((i,a)=>{let c=(l,m)=>{let h=new URL(l.url??"/","http://127.0.0.1");if(h.pathname!==K){m.writeHead(404).end("not found");return}let y=(V,Z)=>m.writeHead(200,{"content-type":"text/html; charset=utf-8"}).end(`<!doctype html><meta charset="utf-8"><h2>${V}</h2><p>${Z}</p>`),T=h.searchParams.get("error")??"",R=h.searchParams.get("code")??"",Y=h.searchParams.get("state")??"";if(T){y("Sign-in was refused","You can close this tab."),u(new Error(`the browser reported: ${T}`));return}if(!R||Y!==o){y("This callback did not belong to the login","You can close this tab."),u(new Error("the callback carried the wrong state"));return}y("Signed in","You can close this tab and go back to HowToFix."),u(void 0,R)},u=(l,m)=>{r.off("request",c),n?.removeEventListener("abort",f),l?a(l):i(m)},f=()=>u(new Error("cancelled"));n?.addEventListener("abort",f,{once:!0}),r.on("request",c)})})})});function k(e,t){e.onProgress?.(t)}async function g(e,t,r,s){let o=await e(t,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(r),signal:s}),n={};try{n=await o.json()}catch{}let i=Number(o.headers?.get?.("retry-after"));return{status:o.status,body:n,retryAfterSeconds:Number.isFinite(i)&&i>0?i:void 0}}function d(...e){for(let t of e)if(typeof t=="string"&&t.trim()!=="")return t.trim()}function D(...e){for(let t of e)if(typeof t=="number"&&Number.isFinite(t))return t;return 0}function me(e){try{let t=new URL(e).searchParams.get("code");return t&&t.trim()!==""?t.trim():void 0}catch{return}}async function pe(e,t,r){let s=await e(t,{headers:de(),signal:r}),o={};try{o=await s.json()}catch{}let n=Number(s.headers?.get?.("retry-after"));return{status:s.status,body:o,retryAfterSeconds:Number.isFinite(n)&&n>0?n:void 0}}function S(e){let t=e.data,r=[e.token,e.api_key,e.apiKey,e.key,t?.token,t?.api_key,t?.apiKey,t?.key];for(let s of r)if(typeof s=="string"&&s.trim().startsWith("sk-"))return s.trim()}function ge(e){let t=e.data,r=d(e.token,t?.token),s=d(e.refresh_token,t?.refresh_token),o=d(e.device_id,t?.device_id);if(!r||!s||!o)return;let n=D(e.access_expires_at,t?.access_expires_at),i=D(e.refresh_expires_at,t?.refresh_expires_at);return{accessToken:r,accessExpiresAt:n,refreshToken:s,deviceId:o,refreshExpiresAt:i}}function p(e,t){let r=e.message??e.error;return typeof r=="string"&&r.trim()?r.trim():t}async function Oe(e){let t=e.fetchImpl??fetch,r=(e.panelUrl??I).replace(/\/+$/,""),s=e.timeoutMs??se,o={...e,panel:r,fetchImpl:t,timeoutMs:s},n=await ke(o);if(n.ok||n.terminal)return n.result;let i=await he(o);if(i.ok||i.terminal)return i.result;let a=await we(o);return a.ok?a:{ok:!1,message:`${n.result.ok?"":n.result.message}; ${i.result.ok?"":i.result.message}; ${a.message}. howtofix.id does not offer a browser login a local client can complete yet \u2014 run /connect and paste a token from ${r}/keys instead.`}}async function he(e){let t=oe(),r=ae(),s;try{s=await(e.loopback??fe)();let o=`http://127.0.0.1:${s.port}${K}`,n=await g(e.fetchImpl,`${e.panel}/api/oauth/device/start`,{redirect_uri:o,code_challenge:ie(t),code_challenge_method:"S256",state:r},e.signal);if(n.status===404)return{ok:!1,terminal:!1,result:{ok:!1,message:"the panel has no loopback login endpoint"}};if(n.status>=400)return{ok:!1,terminal:!1,result:{ok:!1,message:p(n.body,`the panel refused the login (${n.status})`)}};let i=typeof n.body.authorize_url=="string"?n.body.authorize_url:"";if(!i)return{ok:!1,terminal:!1,result:{ok:!1,message:"the panel did not say where to send the browser"}};k(e,{kind:"browser",url:i});let a=await be(s.waitForCode(r,e.signal),e.timeoutMs),c=await g(e.fetchImpl,`${e.panel}/api/oauth/device/token`,{flow_token:n.body.flow_token,code:a,code_verifier:t},e.signal);if(c.status>=400)return{ok:!1,terminal:!0,result:{ok:!1,message:p(c.body,`the panel refused the exchange (${c.status})`)}};let u=S(c.body);return u?{ok:!0,result:{ok:!0,token:u}}:{ok:!1,terminal:!0,result:{ok:!1,message:"the panel did not return an API key"}}}catch(o){let n=o instanceof Error?o.message:String(o);return{ok:!1,terminal:n==="cancelled",result:{ok:!1,message:n}}}finally{s?.close()}}async function ke(e){let t=e.pollIntervalMs??L,r=e.fingerprintId??C(),s=e.clientInfo??P(),o=M(r,s);try{let n=await g(e.fetchImpl,`${e.panel}/api/auth/cli/code`,{fingerprintId:r,clientInfo:s,...o},e.signal);if(n.status===404)return{ok:!1,terminal:!1,result:{ok:!1,message:"the panel has no CLI login endpoint"}};if(n.status===401)return{ok:!1,terminal:!1,result:{ok:!1,message:"the panel did not recognise this build as the HowToFix CLI \u2014 update it with `npm install -g howtofixcli@latest`"}};if(n.status===429)return{ok:!1,terminal:!0,result:{ok:!1,message:`too many sign-in attempts from this machine right now.${n.retryAfterSeconds?` Try again in ${Math.ceil(n.retryAfterSeconds/60)} minute(s).`:""}`}};if(n.status>=400)return{ok:!1,terminal:!1,result:{ok:!1,message:p(n.body,`the panel refused the login (${n.status})`)}};let i=n.body.data??{},a=d(n.body.login_url,i.login_url),c=d(n.body.code,i.code)??(a?me(a):void 0),u=d(n.body.secret,i.secret);return!a||!c?{ok:!1,terminal:!1,result:{ok:!1,message:"the panel did not return a login URL"}}:u?(k(e,{kind:"browser",url:a}),await q(e,c,u)):(k(e,{kind:"browser",url:a}),await q(e,c,void 0))}catch(n){let i=n instanceof Error?n.message:String(n);return{ok:!1,terminal:i==="cancelled",result:{ok:!1,message:i}}}}async function q(e,t,r){let s=e.pollIntervalMs??L,o=Date.now()+e.timeoutMs;for(;Date.now()<o;){await w(s,e.signal);let n=new URLSearchParams(r?{code:t,secret:r}:{code:t});n.set("capability","device-refresh");let i=await pe(e.fetchImpl,`${e.panel}/api/auth/cli/status?${n}`,e.signal);if(i.status===404)return{ok:!1,terminal:!1,result:{ok:!1,message:"the panel has no CLI login status endpoint"}};if(i.status===403)return{ok:!1,terminal:!0,result:{ok:!1,message:"the panel rejected this poll \u2014 run /connect again"}};if(i.status===429){let u=Math.min(Math.max(i.retryAfterSeconds??5,1)*1e3,3e4);await w(u,e.signal);continue}let a=S(i.body);if(a)return{ok:!0,result:{ok:!0,token:a,credential:ge(i.body)}};if(d(i.body.data?.status,i.body.status)==="expired")return{ok:!1,terminal:!0,result:{ok:!1,message:"the sign-in link expired before it was approved"}};if(i.status>=400)return{ok:!1,terminal:!0,result:{ok:!1,message:p(i.body,`the panel refused the poll (${i.status})`)}}}return{ok:!1,terminal:!0,result:{ok:!1,message:"the sign-in was not approved in time"}}}async function we(e){let t=e.pollIntervalMs??L;try{let r=await g(e.fetchImpl,`${e.panel}/api/oauth/device`,{},e.signal);if(r.status===404)return{ok:!1,message:"the panel has no device-code endpoint"};if(r.status>=400)return{ok:!1,message:p(r.body,`the panel refused the request (${r.status})`)};let s=typeof r.body.device_code=="string"?r.body.device_code:"",o=typeof r.body.user_code=="string"?r.body.user_code:"",n=typeof r.body.verification_uri=="string"?r.body.verification_uri:`${e.panel}/oauth/device`;if(!s||!o)return{ok:!1,message:"the panel did not return a code to show"};k(e,{kind:"code",code:o,url:n});let i=Date.now()+e.timeoutMs;for(;Date.now()<i;){await w(t,e.signal);let a=await g(e.fetchImpl,`${e.panel}/api/oauth/device/poll`,{device_code:s},e.signal);if(a.status===404)return{ok:!1,message:"the panel has no device-code poll endpoint"};let c=typeof a.body.status=="string"?a.body.status:"";if(c==="pending")continue;if(c==="slow_down"){await w(t,e.signal);continue}if(c==="denied")return{ok:!1,message:"the sign-in was refused in the browser"};if(c==="expired")return{ok:!1,message:"the code expired; run /connect again"};let u=S(a.body);if(u)return{ok:!0,token:u};if(a.status>=400)return{ok:!1,message:p(a.body,`the panel refused the poll (${a.status})`)}}return{ok:!1,message:"the code was not approved in time"}}catch(r){return{ok:!1,message:r instanceof Error?r.message:String(r)}}}function be(e,t){return new Promise((r,s)=>{let o=setTimeout(()=>s(new Error("the sign-in was not finished in time")),t);e.then(n=>{clearTimeout(o),r(n)},n=>{clearTimeout(o),s(n)})})}function w(e,t){return new Promise((r,s)=>{let o=setTimeout(r,e);t?.addEventListener("abort",()=>{clearTimeout(o),s(new Error("cancelled"))},{once:!0})})}function b(e){return xe(e,"cli-credentials.json")}var ve=300*1e3;function _e(e,t=Date.now()){return e.accessToken?!Number.isFinite(e.accessExpiresAt)||e.accessExpiresAt<=0?!0:e.accessExpiresAt*1e3-ve>t:!1}function Ie(e,t=Date.now()){return!e.refreshToken||!e.deviceId?!1:!Number.isFinite(e.refreshExpiresAt)||e.refreshExpiresAt<=0?!0:e.refreshExpiresAt*1e3>t}function Je(e){let t=b(e);if(!z(t))return;let r;try{r=JSON.parse(ye(t,"utf8"))}catch{return}if(!r||typeof r!="object"||Array.isArray(r))return;let s=r,o=typeof s.accessToken=="string"?s.accessToken.trim():"",n=typeof s.refreshToken=="string"?s.refreshToken.trim():"",i=typeof s.deviceId=="string"?s.deviceId.trim():"";if(!(!o||!n||!i))return{accessToken:o,accessExpiresAt:W(s.accessExpiresAt),refreshToken:n,deviceId:i,refreshExpiresAt:W(s.refreshExpiresAt)}}function Le(e,t){try{return x(b(e),`${JSON.stringify(t,null,2)}
|
|
1
|
+
import{a as x}from"./chunk-UTYFLLSM.js";import{g as P,j as M}from"./chunk-UENU6N7M.js";import{existsSync as z,readFileSync as ye}from"node:fs";import{join as xe}from"node:path";import{createHash as J,randomBytes as G}from"node:crypto";import{createServer as ne}from"node:http";import{execFileSync as X}from"node:child_process";import{createHmac as Q}from"node:crypto";import{readFileSync as ee}from"node:fs";import{arch as N,cpus as $,hostname as O,platform as _,userInfo as H}from"node:os";var te="howtofix-cli-hwid-v1";function v(e){try{let t=ee(e,"utf8").trim();return t.length>0?t:void 0}catch{return}}function F(e,t){try{let r=X(e,t,{encoding:"utf8",timeout:3e3,stdio:["ignore","pipe","ignore"]});return r.trim().length>0?r.trim():void 0}catch{return}}function re(){let e=_();if(e==="linux"){let t=v("/etc/machine-id");if(t)return{value:t,source:"machine-id",strong:!0};let r=v("/var/lib/dbus/machine-id");if(r)return{value:r,source:"dbus-machine-id",strong:!0};let s=v("/sys/class/dmi/id/product_uuid");return s?{value:s,source:"dmi-product-uuid",strong:!0}:void 0}if(e==="win32"){let r=F("reg",["query","HKLM\\SOFTWARE\\Microsoft\\Cryptography","/v","MachineGuid"])?.match(/MachineGuid\s+REG_SZ\s+(\S+)/i);return r?.[1]?{value:r[1],source:"windows-machine-guid",strong:!0}:void 0}if(e==="darwin"){let r=F("ioreg",["-rd1","-c","IOPlatformExpertDevice"])?.match(/"IOPlatformUUID"\s*=\s*"([^"]+)"/);return r?.[1]?{value:r[1],source:"platform-uuid",strong:!0}:void 0}}function U(){let e=re(),t=e?.value??[O(),_(),N(),H().username].join("\0"),r=e?.source??"hostname";return{id:Q("sha256",te).update(t).digest("hex").slice(0,32),source:r,strong:e?.strong??!1}}function j(e){return[e.id,e.source,O(),_(),N(),H().username,String($().length),$()[0]?.model??""]}var I="https://howtofix.id",se=300*1e3,L=3e3,K="/callback";function A(e){return e.toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function oe(){return A(G(32))}function ie(e){return A(J("sha256").update(e).digest())}function ae(){return A(G(16))}var ce="howtofix-cli-",ue="x-howtofix-client",le="cli";function C(e){let t=e??j(U());return ce+J("sha256").update(t.join("\0")).digest("hex").slice(0,32)}function de(){return{"content-type":"application/json",[ue]:le}}var fe=()=>new Promise((e,t)=>{let r=ne();r.once("error",t),r.listen(0,"127.0.0.1",()=>{let{port:s}=r.address();e({port:s,close:()=>r.close(),waitForCode:(o,n)=>new Promise((i,a)=>{let c=(l,m)=>{let h=new URL(l.url??"/","http://127.0.0.1");if(h.pathname!==K){m.writeHead(404).end("not found");return}let y=(V,Z)=>m.writeHead(200,{"content-type":"text/html; charset=utf-8"}).end(`<!doctype html><meta charset="utf-8"><h2>${V}</h2><p>${Z}</p>`),T=h.searchParams.get("error")??"",R=h.searchParams.get("code")??"",Y=h.searchParams.get("state")??"";if(T){y("Sign-in was refused","You can close this tab."),u(new Error(`the browser reported: ${T}`));return}if(!R||Y!==o){y("This callback did not belong to the login","You can close this tab."),u(new Error("the callback carried the wrong state"));return}y("Signed in","You can close this tab and go back to HowToFix."),u(void 0,R)},u=(l,m)=>{r.off("request",c),n?.removeEventListener("abort",f),l?a(l):i(m)},f=()=>u(new Error("cancelled"));n?.addEventListener("abort",f,{once:!0}),r.on("request",c)})})})});function k(e,t){e.onProgress?.(t)}async function g(e,t,r,s){let o=await e(t,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(r),signal:s}),n={};try{n=await o.json()}catch{}let i=Number(o.headers?.get?.("retry-after"));return{status:o.status,body:n,retryAfterSeconds:Number.isFinite(i)&&i>0?i:void 0}}function d(...e){for(let t of e)if(typeof t=="string"&&t.trim()!=="")return t.trim()}function D(...e){for(let t of e)if(typeof t=="number"&&Number.isFinite(t))return t;return 0}function me(e){try{let t=new URL(e).searchParams.get("code");return t&&t.trim()!==""?t.trim():void 0}catch{return}}async function pe(e,t,r){let s=await e(t,{headers:de(),signal:r}),o={};try{o=await s.json()}catch{}let n=Number(s.headers?.get?.("retry-after"));return{status:s.status,body:o,retryAfterSeconds:Number.isFinite(n)&&n>0?n:void 0}}function S(e){let t=e.data,r=[e.token,e.api_key,e.apiKey,e.key,t?.token,t?.api_key,t?.apiKey,t?.key];for(let s of r)if(typeof s=="string"&&s.trim().startsWith("sk-"))return s.trim()}function ge(e){let t=e.data,r=d(e.token,t?.token),s=d(e.refresh_token,t?.refresh_token),o=d(e.device_id,t?.device_id);if(!r||!s||!o)return;let n=D(e.access_expires_at,t?.access_expires_at),i=D(e.refresh_expires_at,t?.refresh_expires_at);return{accessToken:r,accessExpiresAt:n,refreshToken:s,deviceId:o,refreshExpiresAt:i}}function p(e,t){let r=e.message??e.error;return typeof r=="string"&&r.trim()?r.trim():t}async function Oe(e){let t=e.fetchImpl??fetch,r=(e.panelUrl??I).replace(/\/+$/,""),s=e.timeoutMs??se,o={...e,panel:r,fetchImpl:t,timeoutMs:s},n=await ke(o);if(n.ok||n.terminal)return n.result;let i=await he(o);if(i.ok||i.terminal)return i.result;let a=await we(o);return a.ok?a:{ok:!1,message:`${n.result.ok?"":n.result.message}; ${i.result.ok?"":i.result.message}; ${a.message}. howtofix.id does not offer a browser login a local client can complete yet \u2014 run /connect and paste a token from ${r}/keys instead.`}}async function he(e){let t=oe(),r=ae(),s;try{s=await(e.loopback??fe)();let o=`http://127.0.0.1:${s.port}${K}`,n=await g(e.fetchImpl,`${e.panel}/api/oauth/device/start`,{redirect_uri:o,code_challenge:ie(t),code_challenge_method:"S256",state:r},e.signal);if(n.status===404)return{ok:!1,terminal:!1,result:{ok:!1,message:"the panel has no loopback login endpoint"}};if(n.status>=400)return{ok:!1,terminal:!1,result:{ok:!1,message:p(n.body,`the panel refused the login (${n.status})`)}};let i=typeof n.body.authorize_url=="string"?n.body.authorize_url:"";if(!i)return{ok:!1,terminal:!1,result:{ok:!1,message:"the panel did not say where to send the browser"}};k(e,{kind:"browser",url:i});let a=await be(s.waitForCode(r,e.signal),e.timeoutMs),c=await g(e.fetchImpl,`${e.panel}/api/oauth/device/token`,{flow_token:n.body.flow_token,code:a,code_verifier:t},e.signal);if(c.status>=400)return{ok:!1,terminal:!0,result:{ok:!1,message:p(c.body,`the panel refused the exchange (${c.status})`)}};let u=S(c.body);return u?{ok:!0,result:{ok:!0,token:u}}:{ok:!1,terminal:!0,result:{ok:!1,message:"the panel did not return an API key"}}}catch(o){let n=o instanceof Error?o.message:String(o);return{ok:!1,terminal:n==="cancelled",result:{ok:!1,message:n}}}finally{s?.close()}}async function ke(e){let t=e.pollIntervalMs??L,r=e.fingerprintId??C(),s=e.clientInfo??P(),o=M(r,s);try{let n=await g(e.fetchImpl,`${e.panel}/api/auth/cli/code`,{fingerprintId:r,clientInfo:s,...o},e.signal);if(n.status===404)return{ok:!1,terminal:!1,result:{ok:!1,message:"the panel has no CLI login endpoint"}};if(n.status===401)return{ok:!1,terminal:!1,result:{ok:!1,message:"the panel did not recognise this build as the HowToFix CLI \u2014 update it with `npm install -g howtofixcli@latest`"}};if(n.status===429)return{ok:!1,terminal:!0,result:{ok:!1,message:`too many sign-in attempts from this machine right now.${n.retryAfterSeconds?` Try again in ${Math.ceil(n.retryAfterSeconds/60)} minute(s).`:""}`}};if(n.status>=400)return{ok:!1,terminal:!1,result:{ok:!1,message:p(n.body,`the panel refused the login (${n.status})`)}};let i=n.body.data??{},a=d(n.body.login_url,i.login_url),c=d(n.body.code,i.code)??(a?me(a):void 0),u=d(n.body.secret,i.secret);return!a||!c?{ok:!1,terminal:!1,result:{ok:!1,message:"the panel did not return a login URL"}}:u?(k(e,{kind:"browser",url:a}),await q(e,c,u)):(k(e,{kind:"browser",url:a}),await q(e,c,void 0))}catch(n){let i=n instanceof Error?n.message:String(n);return{ok:!1,terminal:i==="cancelled",result:{ok:!1,message:i}}}}async function q(e,t,r){let s=e.pollIntervalMs??L,o=Date.now()+e.timeoutMs;for(;Date.now()<o;){await w(s,e.signal);let n=new URLSearchParams(r?{code:t,secret:r}:{code:t});n.set("capability","device-refresh");let i=await pe(e.fetchImpl,`${e.panel}/api/auth/cli/status?${n}`,e.signal);if(i.status===404)return{ok:!1,terminal:!1,result:{ok:!1,message:"the panel has no CLI login status endpoint"}};if(i.status===403)return{ok:!1,terminal:!0,result:{ok:!1,message:"the panel rejected this poll \u2014 run /connect again"}};if(i.status===429){let u=Math.min(Math.max(i.retryAfterSeconds??5,1)*1e3,3e4);await w(u,e.signal);continue}let a=S(i.body);if(a)return{ok:!0,result:{ok:!0,token:a,credential:ge(i.body)}};if(d(i.body.data?.status,i.body.status)==="expired")return{ok:!1,terminal:!0,result:{ok:!1,message:"the sign-in link expired before it was approved"}};if(i.status>=400)return{ok:!1,terminal:!0,result:{ok:!1,message:p(i.body,`the panel refused the poll (${i.status})`)}}}return{ok:!1,terminal:!0,result:{ok:!1,message:"the sign-in was not approved in time"}}}async function we(e){let t=e.pollIntervalMs??L;try{let r=await g(e.fetchImpl,`${e.panel}/api/oauth/device`,{},e.signal);if(r.status===404)return{ok:!1,message:"the panel has no device-code endpoint"};if(r.status>=400)return{ok:!1,message:p(r.body,`the panel refused the request (${r.status})`)};let s=typeof r.body.device_code=="string"?r.body.device_code:"",o=typeof r.body.user_code=="string"?r.body.user_code:"",n=typeof r.body.verification_uri=="string"?r.body.verification_uri:`${e.panel}/oauth/device`;if(!s||!o)return{ok:!1,message:"the panel did not return a code to show"};k(e,{kind:"code",code:o,url:n});let i=Date.now()+e.timeoutMs;for(;Date.now()<i;){await w(t,e.signal);let a=await g(e.fetchImpl,`${e.panel}/api/oauth/device/poll`,{device_code:s},e.signal);if(a.status===404)return{ok:!1,message:"the panel has no device-code poll endpoint"};let c=typeof a.body.status=="string"?a.body.status:"";if(c==="pending")continue;if(c==="slow_down"){await w(t,e.signal);continue}if(c==="denied")return{ok:!1,message:"the sign-in was refused in the browser"};if(c==="expired")return{ok:!1,message:"the code expired; run /connect again"};let u=S(a.body);if(u)return{ok:!0,token:u};if(a.status>=400)return{ok:!1,message:p(a.body,`the panel refused the poll (${a.status})`)}}return{ok:!1,message:"the code was not approved in time"}}catch(r){return{ok:!1,message:r instanceof Error?r.message:String(r)}}}function be(e,t){return new Promise((r,s)=>{let o=setTimeout(()=>s(new Error("the sign-in was not finished in time")),t);e.then(n=>{clearTimeout(o),r(n)},n=>{clearTimeout(o),s(n)})})}function w(e,t){return new Promise((r,s)=>{let o=setTimeout(r,e);t?.addEventListener("abort",()=>{clearTimeout(o),s(new Error("cancelled"))},{once:!0})})}function b(e){return xe(e,"cli-credentials.json")}var ve=300*1e3;function _e(e,t=Date.now()){return e.accessToken?!Number.isFinite(e.accessExpiresAt)||e.accessExpiresAt<=0?!0:e.accessExpiresAt*1e3-ve>t:!1}function Ie(e,t=Date.now()){return!e.refreshToken||!e.deviceId?!1:!Number.isFinite(e.refreshExpiresAt)||e.refreshExpiresAt<=0?!0:e.refreshExpiresAt*1e3>t}function Je(e){let t=b(e);if(!z(t))return;let r;try{r=JSON.parse(ye(t,"utf8"))}catch{return}if(!r||typeof r!="object"||Array.isArray(r))return;let s=r,o=typeof s.accessToken=="string"?s.accessToken.trim():"",n=typeof s.refreshToken=="string"?s.refreshToken.trim():"",i=typeof s.deviceId=="string"?s.deviceId.trim():"";if(!(!o||!n||!i))return{accessToken:o,accessExpiresAt:W(s.accessExpiresAt),refreshToken:n,deviceId:i,refreshExpiresAt:W(s.refreshExpiresAt)}}function Le(e,t){try{return x(b(e),`${JSON.stringify(t,null,2)}
|
|
2
2
|
`,{mode:384}),!0}catch{return!1}}function Ae(e){try{let t=b(e);z(t)&&x(t,"",{mode:384})}catch{}}function W(e){return typeof e=="number"&&Number.isFinite(e)?e:0}async function Ce(e,t){let r=(t?.panelUrl??I).replace(/\/+$/,""),s=t?.fetchImpl??fetch,o=t?.timeoutMs??15e3,n=new AbortController,i=setTimeout(()=>n.abort(),o);try{let a=await s(`${r}/api/auth/cli/refresh`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({device_id:e.deviceId,refresh_token:e.refreshToken,fingerprint_id:C()}),signal:n.signal}),c=await a.json().catch(()=>({}));if(a.status===401||a.status===403)return{ok:!1,terminal:!0,message:"this sign-in is no longer valid \u2014 run /connect to sign in again"};if(!a.ok)return{ok:!1,terminal:!1,message:`the panel refused the renewal (${a.status})`};let u=c.data??{},f=E(c.token,u.token),l=E(c.refresh_token,u.refresh_token),m=E(c.device_id,u.device_id)??e.deviceId;return!f||!l?{ok:!1,terminal:!1,message:"the panel did not return a renewed credential"}:{ok:!0,terminal:!1,credential:{accessToken:f,accessExpiresAt:B(c.access_expires_at,u.access_expires_at),refreshToken:l,deviceId:m,refreshExpiresAt:B(c.refresh_expires_at,u.refresh_expires_at)}}}catch(a){return{ok:!1,terminal:!1,message:a instanceof Error&&a.name==="AbortError"?`the panel did not answer within ${Math.round(o/1e3)}s`:"could not reach the panel"}}finally{clearTimeout(i)}}function E(...e){for(let t of e)if(typeof t=="string"&&t.trim())return t.trim()}function B(...e){for(let t of e)if(typeof t=="number"&&Number.isFinite(t))return t;return 0}async function Ge(e,t,r){let s=r?.now??Date.now();if(_e(t,s)||!Ie(t,s))return{credential:t,renewed:!1,terminal:!1};let o=await Ce(t,r);if(!o.ok||!o.credential)return o.terminal&&Ae(e),{credential:t,renewed:!1,terminal:o.terminal,message:o.message};let n=Le(e,o.credential);return{credential:o.credential,renewed:!0,terminal:!1,message:n?void 0:`the renewed sign-in could not be saved to ${b(e)}`}}export{I as a,Oe as b,b as c,ve as d,_e as e,Ie as f,Je as g,Le as h,Ae as i,Ce as j,Ge as k};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{b as c,d as l}from"./chunk-27TRKD65.js";import{D as s}from"./chunk-V656XVXV.js";import"./chunk-UTYFLLSM.js";import{a as i,b as r}from"./chunk-
|
|
1
|
+
import{b as c,d as l}from"./chunk-27TRKD65.js";import{D as s}from"./chunk-V656XVXV.js";import"./chunk-UTYFLLSM.js";import{a as i,b as r}from"./chunk-RGWW5HLM.js";import"./chunk-WOT6VMZA.js";var d=[["/connect","sign in with your howtofix.id email:password \u2014 no browser needed"],["/model","choose which model answers"],["/help","list every command"],["/quit","leave"]],u=[" \u2588\u2588\u2557 \u2588\u2588\u2557\u2588\u2588\u2557 \u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557"," \u2588\u2588\u2551 \u2588\u2588\u2551\u255A\u2588\u2588\u2557\u2588\u2588\u2554\u255D\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D"," \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551 \u255A\u2588\u2588\u2588\u2554\u255D \u2588\u2588\u2588\u2588\u2588\u2557 "," \u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2551 \u2588\u2588\u2554\u2588\u2588\u2557 \u2588\u2588\u2554\u2550\u2550\u255D "," \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2554\u255D \u2588\u2588\u2557\u2588\u2588\u2551 "," \u255A\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u255D "],m=[" _ _ _____ ","| | | | __ __ | ___|","| |_| | \\ \\/ / | |_ ","| _ | > < | _| ","|_| |_| /_/\\_\\ |_| "];function g(){if(process.platform==="win32")return!1;let e=(process.env.LC_ALL||process.env.LC_CTYPE||process.env.LANG||"").toLowerCase();return e===""||e==="c"||e==="posix"||!e.includes("utf-8")&&!e.includes("utf8")?!1:!/ja|ko|zh|_kr|_jp|_cn|_tw|_hk/.test(e)}function h(){return g()?u:m}var _="https://howtofix.id/cli";function p(e){let n=process.env.HOME??"",t=n!==""&&e.startsWith(n)?`~${e.slice(n.length)}`:e,o=t.split("/").filter(Boolean);return o.length>3?`\u2026/${o.slice(-2).join("/")}`:t}function f(e){let n=e.signedIn?d.filter(([t])=>t!=="/connect"):d;return[...h(),"",`${i} ${r} \u2014 a terminal coding agent. Describe the change you want and it reads, edits and runs the code in front of you.`,"",` working in ${p(e.cwd)}`,...e.note?[` session ${e.note}`]:[],"",...e.signedIn?[" already signed in to howtofix.id",""]:[],...n.map(([t,o])=>` ${t.padEnd(11)}${o}`),"",' Or just start typing. Every message goes to the model; anything beginning with "/" stays local.'].join(`
|
|
2
2
|
`)}function w(){return[{value:"connect",label:"Sign in to howtofix.id",description:"opens the browser, or paste a key from the panel"},{value:"ready",label:"I have a key \u2014 just give me the prompt",description:"drops you at the prompt; run /connect whenever you like"},{value:"release",label:"What's in this release",description:`opens the ${r} notes in your browser`}]}async function E(e,n,t){c(s).welcomeSeen||(l(s),t(`welcome to ${i}`,f(e)),!e.signedIn&&await new Promise(o=>{n("First run \u2014 how do you want to begin?",w(),a=>{a==="connect"&&e.runSlash("/connect"),a==="release"&&e.openExternal(_),o()},()=>o())}))}export{E as maybeShowWelcome};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{A,B,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z}from"./chunk-
|
|
1
|
+
import{A,B,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z}from"./chunk-U3H4GCLE.js";import"./chunk-UTYFLLSM.js";import"./chunk-UENU6N7M.js";import"./chunk-RGWW5HLM.js";import"./chunk-WOT6VMZA.js";export{g as CATALOG_CACHE_TTL_MS,m as DEFAULT_CONTEXT_WINDOW,a as HOWTOFIX_BASE_URL,b as HOWTOFIX_CONSOLE_URL,l as HOWTOFIX_MODEL_COMPAT,c as HOWTOFIX_PROVIDERS,j as HTTP_IDLE_TIMEOUT_MS,r as UNLIMITED_SENTINEL,v as applyCatalog,w as applyCompat,A as checkAccount,s as checkUsage,d as configuredProviderIds,x as countNewModels,k as ensureGatewaySettings,B as fetchGatewayPrices,z as findLiveModels,q as isHowtofixProvider,h as loadCatalog,o as looksLikeToken,n as maskToken,u as mergeModels,e as newProviderEntry,p as parseModelIds,y as probeModel,f as repairGatewayModels,i as repairModelFacts,t as syncGatewayModelsOnStart};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{b as r}from"./chunk-
|
|
1
|
+
import{b as r}from"./chunk-RGWW5HLM.js";import"./chunk-WOT6VMZA.js";function a(e){return{prompt:s=>e.session.prompt(s),abort:()=>e.session.abort(),subscribe:s=>e.session.subscribe(n=>s(n)),getLastAssistantText:()=>e.session.getLastAssistantText(),lastStopReason:()=>{let s=e.session.state.messages.at(-1);return s?.role==="assistant"?s.stopReason:void 0},dispose:()=>e.dispose()}}async function u(e,s){let{openSession:n}=await import("./chunk-VB72QUU5.js"),i=t=>n({cwd:t,model:s.model,thinking:s.thinking,continueSession:!1,noSession:!1,sessionPath:void 0,interactive:!1});if(e==="acp"){let{runAcp:t}=await import("./chunk-DAPXGSGD.js");await t({input:process.stdin,output:process.stdout,version:r,createAgent:async d=>a(await i(d))});return}let{runRpc:p}=await import("./chunk-ONZLNFQ2.js"),{jsonLine:c}=await import("./chunk-DOD7MUGX.js"),o=await i(s.cwd);await p({input:process.stdin,output:process.stdout,agent:a(o),encodeEvent:t=>c(t),state:()=>({sessionId:o.session.sessionId,model:o.modelLabel,cwd:s.cwd})})}export{a as agentFromSession,u as serveProtocol};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var a="HowToFix",o="0.7.
|
|
1
|
+
var a="HowToFix",o="0.7.19",n=["You are HowToFix, a coding agent. The user wants the fix, not a tour of the problem.",'NEVER report a check you did not run. NEVER state a version, path, result or capability you have not verified \u2014 if you did not check it, say you are unsure. "Not found" is not "impossible": a tool missing from PATH is often installed anyway, and one that is truly absent can usually be installed. Exhaust the real options before calling anything unavailable; when you do report a limit, say plainly what you tried and what you could not do. Unexercised behaviour is not evidence.',"NEVER mention the underlying harness, its vendor or its project name to the user.","Every tool is `read`, `write` or `exec`, and each approval mode auto-approves every tier up to its own: `suggest` runs `read` only, `auto-edit` adds `write`, `full-auto` adds `exec`. A read-only shell command runs in every mode, so inspecting the tree asks nothing.","NEVER aim a command at the filesystem root, a block device or a system account file, and NEVER shut down the host: those are refused in EVERY mode, `full-auto` included, so proposing one wastes the turn. This is not a list of things to avoid \u2014 it is a list of things that will not run.","Lead with the diagnosis in one or two sentences, then change the code. SHOULD prefer the smallest correct change over a rewrite. Name the file and the reason in a short line; do not narrate tool calls.","Fix the problem that was asked for. NEVER add features, refactors, validation, error handling or dependencies nobody requested.","Something reported broken: reproduce it first, confirm the fix after. Cannot reproduce it? Say so \u2014 NEVER edit code and call it fixed.","Tests describe intended behaviour. A failing test means fix the code, not the test: NEVER delete, skip or loosen an assertion to get green, and NEVER re-pin an expected value to whatever the code happens to print.","Anything you cannot settle by reading \u2014 a page, a layout, a screenshot, a CLI, a service, a failure \u2014 run it and look at the result. For a visual task, find a browser the way a real one does: `$PUPPETEER_EXECUTABLE_PATH`, `$CHROME_PATH`, then `which` for google-chrome, chromium and chromium-browser, then /usr/bin, /snap/bin and /var/lib/flatpak, then the puppeteer and playwright caches under the home directory. Still empty? `npx -y puppeteer browsers install chrome`, or `npm i puppeteer-core` against a chrome the image already ships outside PATH. Then drive the real artifact \u2014 open it, read the DOM, click the controls, measure at the widths that matter \u2014 instead of describing what you assume it does.","Done means the requested behaviour works end to end and every stated requirement is met \u2014 not a scaffold, a narrowed test or a plausible subset. Genuinely out of reach? Finish everything else, then say exactly what is missing and what you tried.","SHOULD plan multi-step work with `todo` before starting it, and mark each step done as you finish. A plan the user can see is worth more than a narration of what you are about to do.","Genuinely ambiguous design: enter plan mode, write the plan to the plan file, then present it with `exit_plan_mode`. Use it when several reasonable approaches exist or when a restructuring would be hard to undo. In plan mode `edit` and `write` are refused for every path except the plan file itself \u2014 that limit is enforced, not advisory, so plan the work rather than starting it. Plan mode needs an interactive session in which the user can approve it; when there is no UI it is unavailable, so design the approach yourself instead of calling it.","Work that is independent and would flood this conversation belongs in `task` subagents. Give each a self-contained assignment, then verify the file it wrote rather than trusting its summary. When that work has a shape you can script \u2014 many items through the same stages, or fan-out whose results must be combined \u2014 `workflow` states the orchestration in one place and runs it deterministically; `task` is for the one-off you cannot describe in advance.","MUST give each subagent a self-contained assignment: a child starts with none of this conversation, so a brief that says 'the file we discussed' reaches it as nothing. Choose the agent by what the work is \u2014 scout looks something up, architect returns a plan, reviewer reports issues with file evidence, task changes files \u2014 and NEVER send work that needs an edit to scout or reviewer, because neither can make one.","SHOULD delegate only work that is genuinely parallel: a subagent costs its own session and its own requests on the same quota as this conversation. A single lookup, a file you can read yourself, or a step whose result decides the next step stays here. MUST keep one call to at most six agents and the session to twelve live or parked ones \u2014 a larger fan-out is refused, and the refusal is a limit rather than a failure to work around.","Record a decision, a file's role, or a fact you would otherwise re-derive with `context`: notes survive compaction and are visible to the other agents on the task.","Look it up instead of recalling it: `web_search` and `web_fetch` for anything outside this repo, `lsp` for a definition, reference or diagnostic. Name the source you checked.","Before calling changed code done, run `quality` and `slop` over it and act on what they report. A metric you did not measure is a claim you cannot make.","A command runs under a two-minute default timeout. MUST pass a longer timeout for anything that legitimately takes more than that \u2014 a recursive directory walk, a package install, a build, a network fetch \u2014 and SHOULD prefer a bounded command to an unbounded one: 'du -sh' with an explicit path beats the whole profile, and on Windows/MSYS a recursive 'du' over a profile directory takes minutes rather than seconds.","When a choice blocks the task, use `ask` instead of guessing; when you need to work something out, use `think`, whose text stays out of the transcript.","Above all: NEVER claim a check you did not run, and NEVER call done on a subset."].join(`
|
|
2
2
|
`);function s(e){return e===void 0?void 0:e.replace(/Use \/login to log into a provider[^\n]*/gi,"Connect a provider with /connect or /login:").replace(/^[ \t]*\S*hxf-coding-agent[\\/]docs[\\/][^\n]*$/gim,"").replace(/\bhxf-coding-agent\b/gi,"the harness").replace(/\n{3,}/g,`
|
|
3
3
|
|
|
4
4
|
`).trim()}var i=["# Project notes","","## What this is","","## Commands","- build:","- test:","","## Conventions","-",""].join(`
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{b as k}from"./chunk-AGGIYXN7.js";import{D as p}from"./chunk-V656XVXV.js";import{a as E}from"./chunk-PCALBZOO.js";import"./chunk-UTYFLLSM.js";import{a as g}from"./chunk-
|
|
1
|
+
import{b as k}from"./chunk-AGGIYXN7.js";import{D as p}from"./chunk-V656XVXV.js";import{a as E}from"./chunk-PCALBZOO.js";import"./chunk-UTYFLLSM.js";import{a as g}from"./chunk-RGWW5HLM.js";import"./chunk-WOT6VMZA.js";import{spawnSync as A}from"node:child_process";import{readdirSync as j,readFileSync as S,statSync as D,writeFileSync as C,unlinkSync as v}from"node:fs";import{join as m}from"node:path";var x=[22,19];async function J(e="https://api.howtofix.id/api/status"){let s=[],[n,t]=process.versions.node.split(".").map(Number),r=n>x[0]||n===x[0]&&t>=x[1];s.push({name:"node",ok:r,detail:`${process.versions.node} (needs >= ${x[0]}.${x[1]})`});let a=A("git",["--version"],{encoding:"utf8"});s.push({name:"git",ok:a.status===0,detail:a.status===0?a.stdout.trim():"not found on PATH"});let o=E();s.push({name:"sandbox",ok:!!o,detail:o??"no working bubblewrap (Linux) or sandbox-exec (macOS); --sandbox unavailable",optional:!0});let c=!1,i=p;try{let l=m(p,`.doctor-${process.pid}`);C(l,"ok"),v(l),c=!0}catch(l){i=`${p} is not writable: ${l instanceof Error?l.message:String(l)}`}s.push({name:"state dir",ok:c,detail:i});let u=m(p,"auth.json"),f="no auth.json \u2014 run `howtofix` and sign in",h=!1;try{let l=JSON.parse(S(u,"utf8")),d=Object.keys(l).length;h=d>0,f=h?`${d} provider credential${d===1?"":"s"}`:f}catch{}s.push({name:"auth",ok:h,detail:f,optional:!0});try{let l=Date.now(),d=await fetch(e,{signal:AbortSignal.timeout(5e3)});s.push({name:"gateway",ok:d.ok,detail:`${e} \u2192 ${d.status} in ${Date.now()-l}ms`,optional:!0})}catch(l){s.push({name:"gateway",ok:!1,detail:`${e} unreachable: ${l instanceof Error?l.message:String(l)}`,optional:!0})}return s}async function Z(){let e=await J(),s=Math.max(...e.map(t=>t.name.length));for(let t of e){let r=t.ok?"ok ":t.optional?"warn":"FAIL";console.log(` ${r} ${t.name.padEnd(s)} ${t.detail}`)}let n=e.filter(t=>!t.ok&&!t.optional);return n.length>0?(console.log(`
|
|
2
2
|
${n.length} problem${n.length===1?"":"s"} must be fixed before a session will work.`),1):0}function K(e=p){let s=m(e,"models.json"),n;try{n=S(s,"utf8")}catch(o){return o.code==="ENOENT"?console.log(` no models.json at ${s} \u2014 run \`howtofix /connect\` to pull the catalogue`):k(g,"models",o),1}let t;try{t=JSON.parse(n)}catch(o){return console.error(`${g}: models: ${s} is not valid JSON (${o instanceof Error?o.message:String(o)})`),console.error(" fix the file, or delete it and run `howtofix /connect` to write a new one"),1}let r=t.providers??{},a=0;for(let[o,c]of Object.entries(r)){let i=(c.models??[]).map(u=>u.id).filter(Boolean);a+=i.length,console.log(` ${o} (${i.length})`);for(let u of i)console.log(` ${u}`)}return a===0?(console.log(" no models configured"),1):0}function N(e=15,s=p){let n=m(s,"sessions"),t;try{t=j(n)}catch{return[]}let r=[];for(let a of t){let o=m(n,a),c;try{c=j(o)}catch{continue}for(let i of c){if(!i.endsWith(".jsonl"))continue;let u=m(o,i);try{let f=D(u);r.push({file:u,project:a,modified:f.mtimeMs,bytes:f.size})}catch{}}}return r.sort((a,o)=>o.modified-a.modified).slice(0,e)}function Q(e){let s=e.indexOf("--search");if(s>=0){let o=e[s+1]?.trim();if(!o)return console.error(`${g}: sessions: --search needs a word or phrase`),2;let c=P(o);if(c.length===0)return console.log(` no session mentions "${o}"`),0;for(let i of c){let u=new Date(i.row.modified).toISOString().replace("T"," ").slice(0,16),f=`${i.matches} hit${i.matches===1?"":"s"}`;console.log(` ${u} ${i.row.project} (${f})`),console.log(` ${i.row.file}`),console.log(` ${i.snippet}`)}return 0}let n=e.indexOf("--limit"),t=n>=0&&Number(e[n+1])||15,r=N(t);if(r.length===0)return console.log(` no saved sessions under ${m(p,"sessions")}`),e.includes("--export")?1:0;let a=e.indexOf("--export");if(a>=0){let o=Number(e[a+1]);if(!Number.isInteger(o)||o<1||o>r.length)return console.error(`${g}: sessions: --export needs a number from the list (1-${r.length})`),2;let c=r[o-1];try{console.log(_(c.file))}catch(i){return k(g,"sessions",i),1}return 0}return r.forEach((o,c)=>{let i=new Date(o.modified).toISOString().replace("T"," ").slice(0,16),u=Math.round(o.bytes/1024);console.log(` ${String(c+1).padStart(2)} ${i} ${String(u).padStart(6)}k ${o.project}`),console.log(` ${o.file}`)}),0}function R(e){try{let s=JSON.parse(e),n=s.message?.content??s.content;if(typeof n=="string"&&n.trim())return O(n).replace(/\s+/g," ").trim();if(Array.isArray(n)){let t=O(n.map(r=>r&&typeof r=="object"&&"text"in r?String(r.text):"").join(" ")).replace(/\s+/g," ").trim();if(t)return t}}catch{}return O(e).replace(/\s+/g," ").trim()}function O(e){return e.replace(/\u001b\[[0-9;?]*[ -/]*[@-~]|\u001b\][^\u0007]*\u0007|\u001b[@-Z\\-_]/g,"")}function L(e,s,n=80){let t=e.toLowerCase().indexOf(s);if(t<0)return e.slice(0,n*2).trim();let r=Math.max(0,t-n),a=Math.min(e.length,t+s.length+n);return`${r>0?"\u2026":""}${e.slice(r,a).trim()}${a<e.length?"\u2026":""}`}function P(e,s=10,n=p){let t=e.toLowerCase(),r=new RegExp(`\\b${t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\b`,"i"),a=[];for(let o of N(Number.MAX_SAFE_INTEGER,n)){let c;try{c=S(o.file,"utf8")}catch{continue}let i=0,u=0,f=0,h=0,l=!1,d="";for(let y of c.split(`
|
|
3
3
|
`)){let w=y.toLowerCase(),b=w.indexOf(t);if(b<0)continue;let $=0;for(;b>=0;)$++,b=w.indexOf(t,b+t.length);i+=$;let M=w.includes('"role":"user"'),T=w.includes('"role":"toolresult"')||w.includes('"role":"tool"');M?u+=$:T?h+=$:f+=$,r.test(y)&&(l=!0),d||(d=L(R(y),t))}if(i===0)continue;let I=(u>0?100:0)+(f>0?10:0)+Math.min(h,5)+(l?5:0)+Math.min(i,10)/100;a.push({row:o,matches:i,score:I,snippet:d})}return a.sort((o,c)=>c.score-o.score||c.row.modified-o.row.modified).slice(0,s)}function _(e){let s=[`# Session ${e.split(/[\\/]/).pop()??e}`,""];for(let n of S(e,"utf8").split(`
|
|
4
4
|
`)){if(!n.trim())continue;let t;try{t=JSON.parse(n)}catch{continue}if(t.type!=="message")continue;let r=R(n);r&&s.push(`## ${t.message?.role??"unknown"}`,"",r,"")}return s.join(`
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as y}from"./chunk-UTYFLLSM.js";import{h as k,i as T}from"./chunk-
|
|
1
|
+
import{a as y}from"./chunk-UTYFLLSM.js";import{h as k,i as T}from"./chunk-UENU6N7M.js";import{existsSync as L,mkdirSync as $,readFileSync as b}from"node:fs";import{join as M}from"node:path";var F="https://models.dev/api.json";var O=["anthropic","openai","google","deepseek","zai","xai","moonshotai","minimax","alibaba","xiaomi","meta","tencent","nvidia","venice","openrouter"];function x(n){return n.toLowerCase().replace(/[^a-z0-9]+/g,"")}function S(n){let r=n.split("/");return x(r[r.length-1]??n)}function W(n){let r=new Map,o=new Map;if(!n||typeof n!="object")return r;let t=n,s=i=>{let e=O.indexOf(i);return e===-1?O.length:e};for(let i of Object.keys(t).sort()){let e=t[i]?.models;if(!(!e||typeof e!="object"))for(let a of Object.keys(e)){let c=e[a],u=Number(c?.limit?.context);if(!Number.isFinite(u)||u<=0)continue;let l=x(a),d=s(i),m=o.get(l);if(m!==void 0&&m<=d)continue;let f=Number(c?.limit?.output);r.set(l,{contextWindow:Math.floor(u),maxTokens:Number.isFinite(f)&&f>0?Math.floor(f):void 0,reasoning:c?.reasoning===!0,vision:Array.isArray(c?.modalities?.input)&&c.modalities.input.includes("image")}),o.set(l,d)}}return r}function A(n,r){let o=x(r);if(!o)return;let t=n.get(o);if(t)return t;let s=S(r);for(let[i,e]of n)if(S(i)===s)return e;for(let[i,e]of n)if(i.endsWith(o)||o.endsWith(i))return e}function v(n){return`${n}/models-dev-cache.json`}function N(n){let r={};for(let[o,t]of n)r[o]=[t.contextWindow,t.maxTokens??0,t.reasoning?1:0,t.vision?1:0];return JSON.stringify(r)}function R(n){let r=new Map,o;try{o=JSON.parse(n)}catch{return r}if(!o||typeof o!="object")return r;for(let[t,s]of Object.entries(o)){if(!Array.isArray(s)||s.length<3)continue;let i=Number(s[0]),e=Number(s[1]);!Number.isFinite(i)||i<=0||r.set(t,{contextWindow:Math.floor(i),maxTokens:Number.isFinite(e)&&e>0?Math.floor(e):void 0,reasoning:s[2]===1||s[2]===!0,vision:s[3]===1||s[3]===!0})}return r}async function I(n){let r=n?.url??F,o=n?.fetchImpl??fetch,t=n?.timeoutMs??2e4,s=new AbortController,i=setTimeout(()=>s.abort(),t);try{let e=await o(r,{signal:s.signal,headers:{Accept:"application/json"}});if(!e.ok)return{ok:!1,message:`the model catalogue answered ${e.status}`};let a=W(await e.json());return a.size===0?{ok:!1,message:"the model catalogue was empty or in an unexpected shape"}:{ok:!0,index:a}}catch(e){return{ok:!1,message:e instanceof Error&&e.name==="AbortError"?`the model catalogue did not answer within ${Math.round(t/1e3)}s`:"could not reach the model catalogue"}}finally{clearTimeout(i)}}var _="https://api.howtofix.id/v1",ne="https://howtofix.id/keys",C=["howtofix","howtofix-free"];function re(n){try{let o=JSON.parse(b(M(n,"models.json"),"utf8")).providers;return!o||typeof o!="object"?new Set:new Set(Object.keys(o))}catch{return new Set}}function oe(){return{baseUrl:_,api:"openai-completions",headers:{[k]:T()}}}function se(n){let r=M(n,"models.json"),o;try{o=JSON.parse(b(r,"utf8"))}catch{return 0}let t=o.providers;if(!t||typeof t!="object")return 0;let s=0;for(let i of C){let e=t[i];if(!e||!Array.isArray(e.models))continue;let a=X(e.models),c={...e.headers??{},[k]:T()},u=e.headers?.[k]!==c[k];a.changed===0&&!u||(e.models=a.models,e.headers=c,s+=a.changed===0?1:a.changed)}if(s===0)return 0;try{y(r,`${JSON.stringify(o,null,2)}
|
|
2
2
|
`)}catch{return 0}return s}var D=10080*60*1e3;async function j(n,r){let o=v(n),t=r?.now??Date.now(),s,i=0;try{let c=JSON.parse(b(o,"utf8"));typeof c?.entries=="string"&&(s=R(c.entries),i=Number(c.at)||0)}catch{s=void 0}if(s&&s.size>0&&t-i<D&&!r?.force)return{index:s};let a=await I({fetchImpl:r?.fetchImpl});if(!a.ok)return s&&s.size>0?{index:s,message:a.message}:{index:new Map,message:a.message};try{$(n,{recursive:!0}),y(o,`${JSON.stringify({at:t,entries:N(a.index)})}
|
|
3
3
|
`)}catch{}return{index:a.index}}async function ie(n,r){let o=M(n,"models.json"),t;try{t=JSON.parse(b(o,"utf8"))}catch{return{changed:0}}let s=t.providers;if(!s||typeof s!="object")return{changed:0};let{index:i,message:e}=await j(n,r);if(i.size===0&&!r?.prices)return{changed:0,message:e};let a=0;for(let c of C){let u=s[c];if(!u||!Array.isArray(u.models))continue;let l=B(u.models,i,r?.prices);l.changed!==0&&(u.models=l.models,a+=l.changed)}if(a>0)try{y(o,`${JSON.stringify(t,null,2)}
|
|
4
4
|
`)}catch{return{changed:0,message:"the models file could not be written"}}return{changed:a,message:e}}var z=3e5;function ae(n){let r=M(n,"settings.json"),o={};try{let t=b(r,"utf8"),s=JSON.parse(t);s&&typeof s=="object"&&!Array.isArray(s)&&(o=s)}catch{if(L(r))return!1}if("httpIdleTimeoutMs"in o)return!1;o.httpIdleTimeoutMs=z;try{$(n,{recursive:!0}),y(r,`${JSON.stringify(o,null,2)}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{b as o}from"./chunk-
|
|
1
|
+
import{b as o}from"./chunk-RGWW5HLM.js";import{createPrivateKey as p,createPublicKey as f,createHash as l,randomBytes as y,sign as m}from"node:crypto";import{arch as s,cpus as I,hostname as d,platform as c}from"node:os";var a="hf-cli-1",x="MC4CAQAwBQYDK2VwBCIEIDmKoNgInS7oDpncee1d1+Mnci1R/q4aE5xxHeCKq4Dc",C="howtofix-cli-auth-v1",i;function u(){return i||(i=p({key:Buffer.from(x,"base64"),format:"der",type:"pkcs8"})),i}function g(){return f(u())}function K(t,e,n,r){return Buffer.from([C,t,e,n,r].join(`
|
|
2
2
|
`),"utf8")}function h(){return y(16).toString("hex")}var E="tQ91uspGl0sw5Y8x+soLYnFNX6a9vEzSzCuuvalzdKk=";function P(){let t=g().export({format:"der",type:"spki"});return t.subarray(t.length-32).toString("base64")===E}function N(){let t=g().export({format:"der",type:"spki"});return l("sha256").update(t).digest("hex").slice(0,16)}function $(){let e=(I()[0]?.model??"").replace(/\s+/g," ").trim(),n=d(),r=e?`${n} (${c()}/${s()}, ${e})`:`${n} (${c()}/${s()})`;return`CLI (${o}, ${r})`}var k="X-HowToFix-Client";function A(){return`CLI (${o})`}function B(t,e){let n=h(),r=m(null,K(a,t,e,n),u());return{keyId:a,nonce:n,signature:r.toString("base64")}}export{a,g as b,K as c,h as d,P as e,N as f,$ as g,k as h,A as i,B as j};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{$ as Ne,A as Te,B as $e,D as A,E as G,Ea as Xe,G as M,H as Ee,P as Ae,Pa as Ye,Q as ve,Qa as Ve,R as je,S as Oe,T as Pe,V as Re,W as Ce,Y as De,_ as W,a as C,b as D,ba as Fe,c as ie,ca as Me,d as ae,da as Ie,e as ce,ea as Le,f as le,fa as Ge,g as $,i as de,ia as Ue,j as ue,k as fe,ka as Be,l as me,la as U,m as ge,ma as He,na as We,o as he,p as we,pa as z,q as ye,r as be,s as ke,t as E,ta as ze,u as xe,ua as qe,v as Se,w as L,wa as Ze,x as _e,xa as Ke}from"./chunk-AUDMRGWF.js";import{r as re}from"./chunk-JFYVRWJI.js";import{b as pe}from"./chunk-27TRKD65.js";import{D as k,G as te,r as Q,s as ee}from"./chunk-V656XVXV.js";import{c as ne}from"./chunk-
|
|
1
|
+
import{$ as Ne,A as Te,B as $e,D as A,E as G,Ea as Xe,G as M,H as Ee,P as Ae,Pa as Ye,Q as ve,Qa as Ve,R as je,S as Oe,T as Pe,V as Re,W as Ce,Y as De,_ as W,a as C,b as D,ba as Fe,c as ie,ca as Me,d as ae,da as Ie,e as ce,ea as Le,f as le,fa as Ge,g as $,i as de,ia as Ue,j as ue,k as fe,ka as Be,l as me,la as U,m as ge,ma as He,na as We,o as he,p as we,pa as z,q as ye,r as be,s as ke,t as E,ta as ze,u as xe,ua as qe,v as Se,w as L,wa as Ze,x as _e,xa as Ke}from"./chunk-AUDMRGWF.js";import{r as re}from"./chunk-JFYVRWJI.js";import{b as pe}from"./chunk-27TRKD65.js";import{D as k,G as te,r as Q,s as ee}from"./chunk-V656XVXV.js";import{c as ne}from"./chunk-U3H4GCLE.js";import{g as oe,k as se}from"./chunk-GCKLZQH4.js";import"./chunk-UTYFLLSM.js";import"./chunk-UENU6N7M.js";import{b as I,c as V,d as J}from"./chunk-RGWW5HLM.js";import"./chunk-WOT6VMZA.js";import{join as _t}from"node:path";import{hostname as Fn}from"node:os";import{createAgentSession as Mn,createCodemodeExtension as In,createMcpExtension as Ln,DefaultResourceLoader as Gn,ProjectTrustStore as Un,SessionManager as B,SettingsManager as Bn}from"@netrodev/hxf-coding-agent";import{existsSync as $t,readFileSync as Et}from"node:fs";import{join as At}from"node:path";var Je=At(k,"APPEND_SYSTEM.md"),vt=["<non-interactive>","This run has no user attached: it was started with --print, and there is nobody to answer a question. Anything that stops and waits for a reply \u2014 `ask`, a confirmation, a skill that resolves a mode by asking which mode to use \u2014 will simply end the run with the task unfinished.","So do not ask. Where an instruction tells you to ask the user and wait, take the default it describes and continue, and say which default you took and why in your final answer. The user reads that answer; they cannot answer mid-run.","Where a skill offers a choice of modes, prefer the one that applies the rules while you work over the one that audits afterwards: this is the mode for building something now, and the audit mode can still be run later by the same person who reads your answer.","</non-interactive>"].join(`
|
|
2
2
|
`),jt=16*1024;function Ot(e){try{if(!$t(e))return;let o=Et(e,"utf8").trim();return!o||Buffer.byteLength(o,"utf8")>jt?void 0:o}catch{return}}function Qe(e,o){let s=[o?e:`${e}
|
|
3
3
|
|
|
4
4
|
${vt}`],t=Ot(Je);return t&&s.push(`# Standing instructions from ${Je}
|
package/dist/main.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{b as
|
|
2
|
+
import{b as I,d as W,e as B}from"./chunk-3LZR7OEU.js";import{b as U}from"./chunk-YW7NORH3.js";import{a as F,b as R}from"./chunk-AGGIYXN7.js";import{D as M,K as N}from"./chunk-V656XVXV.js";import"./chunk-UTYFLLSM.js";import{a as n,b as y}from"./chunk-RGWW5HLM.js";import"./chunk-WOT6VMZA.js";var L={rpc:!0,acp:!0},D={off:!0,minimal:!0,low:!0,medium:!0,high:!0,xhigh:!0,max:!0},G={suggest:!0,"auto-edit":!0,"full-auto":!0},H={text:!0,json:!0,"stream-json":!0};function fe(c){let e=Number(c);if(!Number.isFinite(e)||e<=0)throw new Error(`--max-budget-usd needs a positive number of dollars, got '${c}'`);return e}function $(c,e,p){let d=c[e];if(d?.includes("="))return d.slice(d.indexOf("=")+1);let l=c[e+1];if(!l||l.startsWith("-"))throw new Error(`${p} needs a value`);return c.splice(e+1,1),l}function X(c){let e={print:!1,continueSession:!1,noSession:!1,help:!1,version:!1,update:!1,checkUpdate:!1,outputFormat:"text",dangerouslySkipPermissions:!1,sandbox:!1,prompt:""},p=[],d=[...c];for(let l=0;l<d.length;l++){let s=d[l]??"";if(s==="--"){p.push(...d.slice(l+1));break}if(s==="-h"||s==="--help")e.help=!0;else if(s==="-v"||s==="--version")e.version=!0;else if(s==="-p"||s==="--print")e.print=!0;else if(s==="-c"||s==="--continue")e.continueSession=!0;else if(s==="--no-session")e.noSession=!0;else if(s==="--sandbox")e.sandbox=!0;else if(s==="--update")e.update=!0;else if(s==="--check-update")e.checkUpdate=!0;else if(s==="-r"||s==="--resume")e.continueSession=!0;else if(s==="--session"||s.startsWith("--session="))e.sessionPath=$(d,l,"--session");else if(s==="-m"||s==="--model"||s.startsWith("--model="))e.model=$(d,l,"--model");else if(s==="--thinking"||s.startsWith("--thinking="))e.thinking=$(d,l,"--thinking");else if(s==="--approval"||s.startsWith("--approval="))e.approval=$(d,l,"--approval");else if(s==="--output-format"||s.startsWith("--output-format="))e.outputFormat=$(d,l,"--output-format");else if(s==="--max-budget-usd"||s.startsWith("--max-budget-usd="))e.maxBudgetUsd=fe($(d,l,"--max-budget-usd"));else if(s==="--mode"||s.startsWith("--mode=")){let u=$(d,l,"--mode");if(!L[u])throw new Error(`--mode must be one of: ${Object.keys(L).join(", ")}`);e.mode=u}else if(s==="--acp")e.mode="acp";else if(s==="--dangerously-skip-permissions")e.dangerouslySkipPermissions=!0;else{if(s.startsWith("-"))throw new Error(`unknown option ${s}`);p.push(s)}}if(e.thinking&&!D[e.thinking])throw new Error(`thinking must be one of: ${Object.keys(D).join(", ")}`);if(e.approval&&!G[e.approval])throw new Error(`approval must be one of: ${Object.keys(G).join(", ")}`);if(!H[e.outputFormat])throw new Error(`output-format must be one of: ${Object.keys(H).join(", ")}`);if(e.outputFormat!=="text"&&!e.print)throw new Error(`--output-format ${e.outputFormat} is a machine contract; it needs --print`);if(e.dangerouslySkipPermissions&&!e.print)throw new Error("--dangerously-skip-permissions is for unattended runs; it needs --print. interactively, pick an approval mode instead (/approval, or --approval)");if(e.prompt=p.join(" ").trim(),e.update&&e.checkUpdate)throw new Error("--update installs; --check-update only looks. pick one");if((e.update||e.checkUpdate)&&(e.print||e.continueSession||e.sessionPath||e.prompt))throw new Error("--update and --check-update act on the installation, not a session; they take no prompt");if(e.continueSession&&e.noSession)throw new Error("--continue and --no-session cannot be combined");if(e.sessionPath&&e.noSession)throw new Error("--session and --no-session cannot be combined");if(e.sessionPath&&e.continueSession)throw new Error("--session and --continue cannot be combined");if(e.print&&(e.continueSession||e.sessionPath))throw new Error("--print runs one prompt in a throwaway session; it cannot be combined with --continue or --session");if(e.mode&&(e.print||e.prompt))throw new Error(`--mode ${e.mode} is a protocol server: prompts arrive over the protocol, not the command line`);if(e.mode&&(e.continueSession||e.sessionPath))throw new Error(`--mode ${e.mode} opens its own sessions; it cannot be combined with --continue or --session`);if(e.sessionPath&&!e.sessionPath.endsWith(".jsonl"))throw new Error(`--session expects a session file, got '${e.sessionPath}'`);return e}function C(){return`${n} ${y}
|
|
3
3
|
coding agent. layout is a workbench, not a chat log.
|
|
4
4
|
|
|
5
5
|
usage:
|
|
@@ -88,13 +88,12 @@ an npm install checks for a newer release at startup and can install it itself;
|
|
|
88
88
|
/update does it on demand. config and sessions live in ~/.howtofix/agent.
|
|
89
89
|
/connect signs in to howtofix.id in your browser, and falls back to a pasted
|
|
90
90
|
token; /login takes another provider's key.
|
|
91
|
-
`}function
|
|
92
|
-
`)?`${
|
|
93
|
-
${d}`:
|
|
94
|
-
${
|
|
95
|
-
`)}let
|
|
96
|
-
`)}process.exitCode=1;return}
|
|
97
|
-
`)}else process.stdout.write(
|
|
98
|
-
`)?
|
|
99
|
-
`);
|
|
100
|
-
`)}}}finally{f?.(),await n.dispose()}return}if(!process.stdin.isTTY||!process.stdout.isTTY){console.error(`${r}: interactive mode needs a terminal. use --print for pipes.`),await n.dispose(),process.exitCode=2;return}let{runWorkbench:ce}=await import("./chunk-BFX5IV5E.js"),{autoUpdateEnabled:de,isInstalledCopy:pe}=await import("./chunk-7CHDNTH6.js"),le=pe()&&de(`${w}/settings.json`);await ce({cwd:l,modelLabel:n.modelLabel,session:n.session,setCompressToolOutput:n.setCompressToolOutput,initialPrompt:t.prompt||void 0,note:n.note,maxBudgetUsd:t.maxBudgetUsd,update:le?{current:x,install:!0}:void 0,reopen:M})}H(r);ke().catch(c=>{O(r,void 0,c),process.exitCode=1});
|
|
91
|
+
`}function ge(c,e=!1){let{message:p}=F(c);if(!e)return p;let d=c instanceof Error?c.stack:void 0;return d&&d.includes(`
|
|
92
|
+
`)?`${p}
|
|
93
|
+
${d}`:p}function V(c,e){let p=e?.debug??process.env.HOWTOFIX_DEBUG==="1",d=e?.exit??(s=>process.exit(s)),l=s=>{console.error(`${c}: ${ge(s,p)}`),d(1)};process.on("uncaughtException",l),process.on("unhandledRejection",l)}function we(){try{return{cwd:process.cwd()}}catch{return{error:"the current directory no longer exists (it was deleted while the shell stayed in it). cd to a directory that exists, or pass one on the command line."}}}function be(){process.stdout.on("error",c=>{throw c.code==="EPIPE"&&process.exit(0),c})}async function ke(){be(),N();let c=performance.now(),e=we();if("error"in e){console.error(`${n}: ${e.error}`),process.exitCode=1;return}let p=e.cwd,d=process.env.HXF_FAKE_NODE??process.versions.node,[l,s]=d.split(".").map(o=>Number.parseInt(o,10));if(!Number.isFinite(l)||l<22||l===22&&Number.isFinite(s)&&s<19){console.error(`${n}: Node ${d} is too old. Node 22.19 or newer is required (run "node --version" to check yours), because undici needs zstd, which Node added in 22.19. Upgrade Node and run this again.`),process.exitCode=1;let o=process.argv.slice(2);if(o.some(a=>a==="-h"||a==="--help")){console.log(C());return}if(o.some(a=>a==="-v"||a==="--version")){console.log(`${n} ${y}`);return}return}let u=process.argv.slice(2);if(u[0]==="doctor"||u[0]==="models"||u[0]==="sessions"){let o=u[0];try{let a=await import("./chunk-TFSJ4NIX.js");o==="doctor"?process.exitCode=await a.runDoctor():o==="models"?process.exitCode=a.runModels():process.exitCode=a.runSessions(u.slice(1))}catch(a){R(n,o,a),process.exitCode=1}return}let q=u[0]==="acp"?["--acp",...u.slice(1)]:u,_;try{_=X(q)}catch(o){let a=o instanceof Error?o.message:String(o);console.error(`${n}: ${a}
|
|
94
|
+
${C()}`),process.exitCode=2;return}if(_.print&&!_.prompt){console.error(`${n}: --print needs a prompt`),process.exitCode=2;return}let{repairGatewayModels:J,ensureGatewaySettings:K,repairModelFacts:Y,syncGatewayModelsOnStart:z,checkAccount:Q,fetchGatewayPrices:Z}=await import("./chunk-MXY5C2ZU.js"),{readCliCredential:ee,renewCliCredentialIfNeeded:se}=await import("./chunk-AKKVDSRL.js"),{AGENT_DIR:b}=await import("./chunk-GXB7RZHH.js"),j=J(b);j>0&&console.error(`${n}: repaired ${j} howtofix model(s) that the gateway would have rejected`);let P,O;try{let o=ee(b);if(o){let x=(await se(b,o)).credential.accessToken,[m,h]=await Promise.all([Z(x),Q(x)]);m.size>0&&(P=m),h.ok&&(O=h.models)}}catch{}let E=await Y(b,P?{prices:P}:void 0);if(E.changed>0?console.error(`${n}: filled in the context window, reasoning flag and price for ${E.changed} model(s)`):E.message&&console.error(`${n}: model catalogue unavailable (${E.message}); context windows stay at their conservative defaults`),K(b)&&console.error(`${n}: set httpIdleTimeoutMs in settings.json so a stalled provider recovers instead of hanging`),O)try{let o=await z(b,O,P);o.added>0&&console.error(`${n}: added ${o.added} model(s) this account can now reach`)}catch{}let t=_;if(t.help){console.log(C());return}if(t.version){console.log(`${n} ${y}`);let{cliSigningKeyMatchesPanel:o,cliSigningKeyFingerprint:a}=await import("./chunk-A444ANBX.js");o()||(console.error(`${n}: this build's CLI signing key (${a()}) does not match the key the panel verifies against, so sign-in will be refused.`),process.exitCode=1);return}if(t.sandbox&&!process.env.HOWTOFIX_SANDBOXED){let{detectSandbox:o,enterSandbox:a,describeSandbox:x}=await import("./chunk-N345KWWK.js"),m=o();if(!m){console.error(`${n}: --sandbox needs a working bubblewrap (Linux) or sandbox-exec (macOS). Neither could be used here \u2014 on Linux this usually means unprivileged user namespaces are disabled.`),process.exitCode=1;return}console.error(x(m)),process.exitCode=a(m,{cwd:p,agentDir:M,argv:[process.execPath,...process.argv.slice(1)]});return}let{installProxy:te}=await import("./chunk-WKUJ7CFO.js");if(te(M),t.update||t.checkUpdate){let{PACKAGE_NAME:o,checkForUpdate:a,installUpdate:x,isInstalledCopy:m}=await import("./chunk-7CHDNTH6.js"),h=await a(y);if(!h.latest){console.error(`${n}: ${h.message}`),process.exitCode=t.update?1:0;return}if(console.log(h.message),t.checkUpdate||!h.available)return;if(!m()){console.error(`${n}: this copy was not installed by npm, so npm cannot replace it. install it with: npm install -g ${o}`),process.exitCode=1;return}let v=await x({version:h.latest});console.log(v.message),v.ok||(process.exitCode=1);return}let A=process.argv.slice(2);if(A[0]==="preset"){let{runPresetCommand:o}=await import("./chunk-FPXVDP32.js");process.exitCode=o(A.slice(1));return}let{expandFileReferences:oe}=await import("./chunk-TSEKPGK4.js"),{isApprovalMode:ne,setApprovalMode:re,setDangerousBypass:ie,isDangerousBypass:ae}=await import("./chunk-56SEAGAQ.js"),{openSession:de}=await import("./chunk-VB72QUU5.js");re(t.approval&&ne(t.approval)?t.approval:"full-auto");let{readWorkbenchSettings:ce}=await import("./chunk-V3R4FYTJ.js");if((t.dangerouslySkipPermissions||ce(b).skipPermissions)&&ie(!0),ae()&&console.error(`${n}: permission checks are OFF \u2014 critical commands (filesystem wipes, fork bombs, host shutdown) and the repeated-call guard are NOT enforced for this run. Turn it off with /settings, or by removing skipPermissions from settings.json.`),t.mode){let{serveProtocol:o}=await import("./chunk-NOB2BWQL.js");await o(t.mode,{cwd:p,model:t.model,thinking:t.thinking});return}let T=o=>de({cwd:p,model:t.model,thinking:t.thinking,continueSession:o.continueSession??!1,noSession:o.noSession??!1,sessionPath:o.sessionPath,interactive:!t.print}),r=await T({continueSession:t.continueSession,sessionPath:t.sessionPath,noSession:t.noSession||t.print});if(t.print&&r.note&&console.error(r.note),t.maxBudgetUsd!==void 0&&!r.priced){console.error(`${n}: ${B(r.modelLabel,b)}`),await r.dispose(),process.exitCode=2;return}if(t.print){let o=t.prompt.trimStart();if(o.startsWith("/")){let f=o.slice(1).split(/\s+/)[0]??"",{skillInvocation:S}=await import("./chunk-ILDDDLRC.js"),g=r.session.resourceLoader.getSkills().skills.map(i=>i.name);if(!(S(o,g)!==void 0)){let{slashCommands:i}=await import("./chunk-GBWEIWLX.js");if(i(r.session).some(w=>w.name===f)){console.error(`${n}: /${f} runs in the TUI only \u2014 --print sends prompts straight to the model. Run \`howtofix\` without --print for interactive commands.`),await r.dispose(),process.exitCode=2;return}}}let a=t.outputFormat==="stream-json",x=t.outputFormat==="json",m=a||x;if(a){let f={type:"system",subtype:"init",cwd:p,session_id:r.session.sessionId,model:r.modelLabel,output_format:t.outputFormat,max_budget_usd:t.maxBudgetUsd??null,dangerously_skip_permissions:t.dangerouslySkipPermissions,cli_version:y};process.stdout.write(`${JSON.stringify(f)}
|
|
95
|
+
`)}let h,v,he=()=>{if(t.maxBudgetUsd===void 0||v!==void 0)return;let f=r.session.getSessionStats().cost;f>t.maxBudgetUsd&&(v={spent:f},r.session.abort())};try{let f;h=r.session.subscribe(i=>{if(a){let w=U(i);w!==void 0&&process.stdout.write(w)}if(i.type==="turn_end"&&i.message?.role==="assistant"){let w=i.message;w.stopReason==="error"||w.stopReason==="aborted"||w.errorMessage?f={stopReason:w.stopReason??"error",errorMessage:w.errorMessage}:f=void 0}he()}),await r.session.prompt(oe(t.prompt,p));let S=r.session.getLastAssistantText()??"";if(v){if(console.error(`${n}: ${W(v.spent,t.maxBudgetUsd)}`),m){let i=r.session.getSessionStats();process.stdout.write(`${JSON.stringify({type:"result",subtype:"error_max_budget_usd",is_error:!0,result:S,session_id:r.session.sessionId,duration_ms:Math.round(performance.now()-c),num_turns:i.assistantMessages,total_cost_usd:i.cost,usage:{input_tokens:i.tokens.input,output_tokens:i.tokens.output,cache_read_input_tokens:i.tokens.cacheRead,cache_creation_input_tokens:i.tokens.cacheWrite}})}
|
|
96
|
+
`)}process.exitCode=1;return}let g=r.session.state.messages.at(-1),k=f??(g?.role==="assistant"&&(g.stopReason==="error"||g.stopReason==="aborted"||g.errorMessage)?{stopReason:g.stopReason??"error",errorMessage:g.errorMessage}:void 0);if(m){let i=r.session.getSessionStats();process.stdout.write(`${JSON.stringify({type:"result",subtype:k?k.stopReason==="aborted"?"error_aborted":"error_during_execution":"success",is_error:k!==void 0,result:S,session_id:r.session.sessionId,duration_ms:Math.round(performance.now()-c),num_turns:i.assistantMessages,total_cost_usd:i.cost,usage:{input_tokens:i.tokens.input,output_tokens:i.tokens.output,cache_read_input_tokens:i.tokens.cacheRead,cache_creation_input_tokens:i.tokens.cacheWrite},stop_reason:k?.stopReason??(g?.role==="assistant"?g.stopReason:void 0)})}
|
|
97
|
+
`)}else process.stdout.write(S.endsWith(`
|
|
98
|
+
`)?S:`${S}
|
|
99
|
+
`);if(k&&(process.exitCode=1,k.errorMessage)){console.error(`${n}: ${k.errorMessage}`);let i=I(k.errorMessage);i!==void 0&&console.error(`${n}: ${i}`)}}finally{h?.(),await r.dispose()}return}if(!process.stdin.isTTY||!process.stdout.isTTY){console.error(`${n}: interactive mode needs a terminal. use --print for pipes.`),await r.dispose(),process.exitCode=2;return}let{runWorkbench:le}=await import("./chunk-GBWEIWLX.js"),{autoUpdateEnabled:pe,isInstalledCopy:ue}=await import("./chunk-7CHDNTH6.js"),me=ue()&&pe(`${b}/settings.json`);await le({cwd:p,modelLabel:r.modelLabel,session:r.session,setCompressToolOutput:r.setCompressToolOutput,initialPrompt:t.prompt||void 0,note:r.note,maxBudgetUsd:t.maxBudgetUsd,update:me?{current:y,install:!0}:void 0,reopen:T})}V(n);ke().catch(c=>{R(n,void 0,c),process.exitCode=1});
|
package/package.json
CHANGED
package/dist/chunk-6FUWMLWO.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
function o(e){let n=0,r;return{limit:e,close(t){n+=t},total(t){return n+t},check(t){if(e===void 0||r!==void 0)return r;let d=n+t;return d-e>1e-9&&(r={spent:d,limit:e}),r}}}function u(e,n){return`stopped \u2014 spent $${e.toFixed(4)} of a $${n.toFixed(2)} budget.`}function i(e,n){return`--max-budget-usd needs a model with prices, and ${e} declares none (its rates are zero, so every turn costs $0 and the budget would never fire). Add a cost to that model in ${n}/models.json, or drop the flag.`}export{o as a,u as b,i as c};
|
package/dist/chunk-BFX5IV5E.js
DELETED
|
@@ -1,116 +0,0 @@
|
|
|
1
|
-
import{b as kr,c as $r}from"./chunk-WX3V5P7U.js";import{a as vr,b as xr}from"./chunk-MOKUBKE7.js";import{a as He}from"./chunk-LSJC73DG.js";import{a as ft,b as dn,c as un,d as Ts,e as pt}from"./chunk-3FYCFLNK.js";import{u as Ms}from"./chunk-WUPU6LTD.js";import{a as Rs}from"./chunk-ORJ2QZBG.js";import{Aa as or,Ba as sr,C as gt,Ca as rr,D as Ks,Da as ir,F as Hs,Fa as ae,Ga as T,Ha as O,I as Bs,Ia as ar,J as Gs,Ja as lr,K as bt,Ka as cr,L as qs,La as dr,M as Vs,Ma as $n,N as zs,Na as ur,O as bn,Oa as fr,Ra as pr,Sa as mr,Ta as hr,U as We,Ua as gr,Va as br,Wa as wr,X as wn,Xa as yr,Z as yn,aa as Ue,c as _s,e as Os,g as Ls,ga as Ys,h as Ns,ha as Ke,ja as wt,n as Ds,na as Xs,oa as Js,qa as Zs,ra as Qs,sa as er,va as tr,w as Ws,y as gn,ya as kn,z as Us,za as nr}from"./chunk-AUDMRGWF.js";import{a as Es,c as mt,d as fn,j as Ps,l as pn,m as mn,n as Is}from"./chunk-JFYVRWJI.js";import{b as ke,c as De,e as Fs,f as hn,g as js,h as ht}from"./chunk-27TRKD65.js";import{a as rs,b as is}from"./chunk-6FUWMLWO.js";import{A as sn,B as rn,C as ns,D as P,I as os,J as ss,b as nn,c as at,d as lt,e as Ho,f as Bo,g as Go,h as qo,i as ct,j as Vo,k as on,l as zo,o as ne,p as Yo,q as Xo,t as Jo,u as Zo,v as Qo,w as es,x as dt,y as ut,z as ts}from"./chunk-V656XVXV.js";import{A as cn,B as ws,b as an,c as ye,d as cs,e as ds,h as us,n as ln,o as fs,q as se,s as Ae,u as ps,w as ms,x as hs,y as gs,z as bs}from"./chunk-SVE3XYTR.js";import{a as ys,b as ks,c as $s,e as vs,f as xs,g as Ss,h as Cs,k as As}from"./chunk-YVF3HZNM.js";import{a as ie}from"./chunk-UTYFLLSM.js";import{h as as,i as ls}from"./chunk-SIXFT6QP.js";import{a as tn,b as it,e as Ko}from"./chunk-NIDYKFDX.js";import"./chunk-WOT6VMZA.js";import{execFile as El}from"node:child_process";import{promisify as Pl}from"node:util";import{appendFileSync as Il,existsSync as Et,mkdirSync as Ui,readFileSync as Gn,rmSync as _l,writeFileSync as qn}from"node:fs";import{basename as Ol,join as le,resolve as Ll}from"node:path";function Sr(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 Cr(e){let t=!1;process.on("SIGINT",()=>{t||(t=!0,e())})}function ma(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 ha(e){let t=e?.input??0,n=e?.cacheRead??0,s=e?.cacheWrite??0;return{input:t,cacheRead:n,cacheWrite:s,prompt:t+n+s}}function ga(e){if(typeof e!="string")return null;let t=Date.parse(e);return Number.isNaN(t)?null:t}function ba(e){if(!e||typeof e!="object")return;let t=e,s=(t.message&&typeof t.message=="object"?t.message:void 0)??t,i=ma(s.usage);if(!i)return;let u=typeof s.provider=="string"?s.provider:"",f=typeof s.model=="string"?s.model:"";return{usage:i,model:[u,f].filter(Boolean).join("/")}}function Ar(e){let t=0,n=0,s=[],i=0,u=null;for(let h of e){let w=ba(h);if(!w)continue;let{input:S,cacheRead:M,cacheWrite:D,prompt:F}=ha(w.usage);if(F===0)continue;t+=M,n+=S+D;let K=ga(h.timestamp),I=u,H=I?I.at:null;if(I!==null&&M===0&&S>=1e3){let L=K!==null&&H!==null?Math.max(0,K-H):0;s.push({missedTokens:S,idleMs:L,modelChanged:w.model!==""&&I.model!==""&&w.model!==I.model}),i+=S}u={prompt:F,at:K??H??null,model:w.model}}let f=t+n;return{cachedTokens:t,billedTokens:n,hitRate:f>0?t/f*100:null,misses:s,missedTokens:i}}function Tr(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 Nl,ProjectTrustStore as Fl,SessionManager as jl}from"@netrodev/hxf-coding-agent";import{CombinedAutocompleteProvider as Ki,Container as Dl,Editor as Wl,matchesKey as Y,ProcessTerminal as Ul,ScrollView as Kl,KeybindingsManager as qi,setKeybindings as Vi,TUI_KEYBINDINGS as zi,SelectList as Hl,TuiAltScreen as Bl,truncateToWidth as Re,VStack as Gl,visibleWidth as It,wrapTextWithAnsi as ql}from"@netrodev/hxf-tui";import{spawn as wa}from"node:child_process";function ya(e,t,n=2e3){return new Promise(s=>{let i=!1,u,f=S=>{i||(i=!0,u!==void 0&&clearTimeout(u),s(S))},h;try{h=wa(e,[...t],{stdio:["ignore","pipe","ignore"]})}catch{f({ok:!1,stdout:""});return}u=setTimeout(()=>{h.kill("SIGKILL"),f({ok:!1,stdout:""})},n);let w=[];h.stdout?.on("data",S=>w.push(S)),h.on("error",()=>f({ok:!1,stdout:""})),h.on("close",S=>{f({ok:S===0,stdout:Buffer.concat(w).toString("utf8")})})})}function vn(){return process.env.XDG_SESSION_TYPE==="wayland"||(process.env.WAYLAND_DISPLAY?.length??0)>0}async function ka(){let e=[];process.platform==="darwin"?e.push({command:"pbpaste",args:[]}):process.platform==="win32"?e.push({command:"powershell.exe",args:["-NoProfile","-Command","Get-Clipboard -Raw"]}):(vn()&&(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||!vn())&&(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 ya(t.command,t.args);if(n.ok&&n.stdout.length>0)return n.stdout}}async function Mr(){let e;try{let{getNativeClipboard:s}=await import("@netrodev/hxf-tui");e=s()}catch{e=void 0}if(e)try{let s=await e.getText();if(typeof s=="string"&&s.length>0)return{ok:!0,text:s}}catch{}let t=await ka();return t!==void 0?{ok:!0,text:t}:{ok:!1,reason:`no clipboard tool could read it \u2014 ${vn()?"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{TreeSelectorComponent as Vl,initTheme as zl}from"@netrodev/hxf-coding-agent";import{getKeybindings as Hi}from"@netrodev/hxf-tui";import{mixColors as $a,parseColor as va,styleText as de}from"@netrodev/hxf-tui";var ue=process.env.HOWTOFIX_NO_MOTION!=="1",xa=45,Rr=5,Er=8,xn=1e4,Pr=6e4,Ir=3,_r=4,Sn=e=>e<0?0:e>1?1:e;function fe(e,t,n){let s=Sn(n);return s>=1?t:s<=0?e:$a(e,t,s)}var yt=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),s=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 i=150,u=2*Math.sqrt(i),f=Math.max(1,Math.ceil(s/.008)),h=s/f;for(let w=0;w<f;w+=1)this.velocity+=(this.target-this.value)*i*h-this.velocity*u*h,this.value+=this.velocity*h;return this.moving||(this.value=this.target,this.velocity=0),this.value}};function Cn(e,t,n,s){return!ue||e<=xn?t:e>=Pr?s:fe(n,s,(e-xn)/(Pr-xn))}function Or(e,t){return!ue||t<=0||e<0?1:1-(1-Sn(e/t))**3}function Lr(e,t){return ue&&e>=0&&e<t}var An=260,Sa=45;function Tn(e,t,n=Sa,s=400){return!ue||n<=0||e<0||e>=s?t:Math.min(t,Math.floor(e/n)+1)}function Nr(e,t,n=Date.now(),s=1400){if(!ue||s<=0)return e;let i=n%s/s;return fe(e,t,i<.5?i*2:(1-i)*2)}function Fr(e,t,n){let s=de(e,{fg:t.rest},ae);if(!ue||e.length===0)return s;let i=Sn(n);if(i>=1)return s;let u=t.band??1,f=e.length+_r*2,w=Math.min(f-1,Math.floor(i*f))-_r,S=H=>{let L=Math.abs(H-w);return L>u?0:1-L/(u+1)},M="",D=0,F=null,K=0,I=0;for(let H of e){let L=S(I);F===null?F=L:L!==F&&(M+=de(e.slice(D,K),{fg:fe(t.rest,t.lit,F)},ae),D=K,F=L),K+=H.length,I+=1}return M+de(e.slice(D),{fg:fe(t.rest,t.lit,F??0)},ae)}function jr(e,t,n=Date.now(),s=90){let i=t[0]??va("#e6e6e6");if(t.length===0||e.length===0)return de(e,{fg:i},ae);if(!ue||s<=0)return de(e,{fg:t[t.length-1]??i},ae);let u=t.length*s,f=(n%u+u)%u,h="",w=0,S=null,M=0,D=0,F=K=>{let I=(f+K*s)/u%1*t.length,H=Math.floor(I)%t.length,L=(H+1)%t.length;return fe(t[H]??i,t[L]??i,I-Math.floor(I))};for(let K of e){let I=F(D);S===null?S=I:I!==S&&(h+=de(e.slice(w,M),{fg:S},ae),w=M,S=I),M+=K.length,D+=1}return h+de(e.slice(w),{fg:S??i},ae)}function Ca(e,t){let n=Math.abs(e-t);return n>=Rr?0:Math.ceil((1-n/Rr)*Ir)/Ir}function Dr(e,t,n=Date.now()){let s=t.charMs??xa;if(!ue||e.length===0||s<=0)return de(e,{fg:t.base},ae);let i=e.length+Er*2,u=n/s%i-Er,f=(F,K)=>de(F,{fg:fe(t.base,t.bright,K)},ae),h="",w=0,S=null,M=0,D=0;for(let F of e){let K=Ca(D,u);S===null?S=K:K!==S&&(h+=f(e.slice(w,M),S),w=M,S=K),M+=F.length,D+=1}return h+f(e.slice(w),S??0)}import{Markdown as Ha,wrapTextWithAnsi as Ba}from"@netrodev/hxf-tui";import{homedir as Aa}from"node:os";import{isAbsolute as Ta,relative as Ma,resolve as Ra,sep as Wr}from"node:path";var Ea="\u25CF",En="\u2514",$t="\u22EF",Mn=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"];function qe(e=90){let t=Math.floor(Date.now()/e)%Mn.length;return Mn[t]??Mn[0]}var Pa="\u25B2";var Ia="\u25CB",_a=["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 Pn(e){return e.includes("__")?e.slice(e.lastIndexOf("__")+2):e}function Br(e){return _a.includes(Pn(e))}function Be(e,t=process.cwd()){if(!e||!Ta(e))return e;let n=Ra(e),s=Ma(t,n);if(s==="")return".";if(s&&!s.startsWith(`..${Wr}`)&&s!=="..")return s;let i=Aa();return i&&(n===i||n.startsWith(i+Wr))?`~${n.slice(i.length)}`:n}function oe(e,t){let n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,Math.max(1,t-1))}\u2026`:n}function N(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 Oa(e,t=160){if(!e||typeof e!="object")return"";try{let n=JSON.stringify(e);return n&&n!=="{}"?oe(n,t):""}catch{return""}}function La(e,t){switch(e){case"read":{let n=Be(N(t,"path")??""),s=[N(t,"offset"),N(t,"limit")].filter(Boolean);return s.length>0?`${n} ${s.length===1?`offset=${s[0]}`:`offset=${s[0]}, limit=${s[1]}`}`:n}case"edit":case"write":return Be(N(t,"path")??"");case"bash":case"powershell":{let n=N(t,"command")??"";return t?.run_in_background===!0?`${n} [background]`:n}case"bash_output":{let n=N(t,"task_id"),s=N(t,"filter");return n?s?`${n} filter=${s}`:n:"all tasks"}case"kill_shell":return N(t,"task_id")??"";case"compress":{let n=N(t,"topic")??"",s=Array.isArray(t.content)?t.content.length:0;return s>1?`${n} (${s} ranges)`:n}case"grep":{let n=N(t,"pattern")??"",s=N(t,"path");return s?`${n} in ${Be(s)}`:n}case"find":case"glob":{let n=N(t,"pattern")??N(t,"glob")??"",s=N(t,"path");return s?`${n} in ${Be(s)}`:n}case"ls":return Be(N(t,"path")??".");case"task":return N(t,"agent")??"task";case"ask":return N(t,"question")??"";case"web_search":return N(t,"query")??"";case"web_fetch":return N(t,"url")??"";case"lsp":{let n=N(t,"action")??"lsp",s=N(t,"file")??"",i=N(t,"line");return i?`${n} ${s}:${i}`:`${n} ${s}`}case"quality":return N(t,"path")??"changed files";case"think":return"private";case"todo":{let n=N(t,"op")??"view",s=N(t,"task"),i=t?.items;return n==="init"&&Array.isArray(i)?`init ${i.length} task${i.length===1?"":"s"}`:s?`${n} ${s}`:n}case"context":{let n=N(t,"op")??"list",s=N(t,"key");return s?`${n} ${s}`:n}case"workflow":{let n=N(t,"path");if(n)return n;let s=N(t,"code")??"",i=/export\s+const\s+meta\s*=\s*\{[\s\S]*?name\s*:\s*["'`]([^"'`]+)/.exec(s)?.[1];if(i)return i;let u=s.trim().split(`
|
|
2
|
-
`)[0]??"";return u.length>40?`${u.slice(0,40)}\u2026`:u}default:return Oa(t)}}function $e(e,t,n=100){let s=Pn(e),u=s!==e?s:s.charAt(0).toUpperCase()+s.slice(1),f=Br(e)?Pa:Ea,h=oe(La(s,t),n);return h?`${f} ${u}(${h})`:`${f} ${u}`}function Na(e){let t=0,n=0;for(let s of e.split(`
|
|
3
|
-
`))s.startsWith("+")&&!s.startsWith("+++")?t+=1:s.startsWith("-")&&!s.startsWith("---")&&(n+=1);return{additions:t,removals:n}}function Te(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 Ve(e){let t=e?.details;return t&&typeof t=="object"?t:{}}function In(e){let t=e?.structuredContent;return t&&typeof t=="object"?t:{}}function Ur(e){let t=e.exit_code;return typeof t=="number"&&Number.isFinite(t)?t:void 0}function Fa(e){let t=[];if(e&&typeof e=="object"){t.push(e);let s=e.content;if(Array.isArray(s))for(let i of s){let u=i?.text;if(typeof u=="string")try{let f=JSON.parse(u);f&&typeof f=="object"&&t.push(f)}catch{}}}let n=[];for(let s of t){let i=["instances","instanceCount","count","parts","partsCreated"].map(w=>s[w]).find(w=>typeof w=="number"&&Number.isFinite(w));typeof i=="number"&&n.push(`${i} instance${i===1?"":"s"}`);let u=Rn(s,["files","written","paths"]);u&&n.push(u.join(", "));let f=Rn(s,["images","renders","screenshots"]);f&&n.push(`renders ${Ia} ${f.join(", ")}`);let h=Rn(s,["findings","warnings","errors"]);if(h&&n.push(`${h.length} finding${h.length===1?"":"s"}`),n.length>0)break}return n.length>0?n.join(" \xB7 "):void 0}function Rn(e,t){for(let n of t){let s=e[n];if(!Array.isArray(s))continue;let i=s.filter(u=>typeof u=="string"&&u!=="");if(i.length>0)return i}}function Kr(e){return e.trim().split(`
|
|
4
|
-
`).find(t=>t.trim())??""}function ja(e,t){let n=typeof e.output=="string"?e.output:t.replace(/\n*Command exited with code \d+\s*$/,""),s=Ge(n);return s>0?` (${s} line${s===1?"":"s"})`:""}function Da(e,t,n){return e===1?t:n}function Ge(e){let t=e.trim();return t?t.split(`
|
|
5
|
-
`).length:0}function Hr(e){return e<1e3?`${e} tokens`:`${(e/1e3).toFixed(1)}k tokens`}function vt(e,t,n){let s=Te(t),i=Ve(t),u=In(t);if(n){let f=Ur(u);if(f!==void 0&&(e==="bash"||e==="powershell"))return`exit ${f}`;let h=s.trim().split(`
|
|
6
|
-
`).find(w=>w.trim());return oe(h??"failed",120)}if(Br(e)){let f=Fa(t);if(f)return f;let h=Pn(e);return h==="execute_luau"?"ran":oe(h.replace(/_/g," "),120)}switch(e){case"task":{let f=s.split(`
|
|
7
|
-
`).filter(h=>h.startsWith("## ")).map(h=>h.replace(/^##\s*/,"").trim());if(f.length===0){let h=s.trim().split(`
|
|
8
|
-
`).find(w=>w.trim());return oe(h??"done",120)}return f.map(h=>oe(h,120)).join(`
|
|
9
|
-
`)}case"read":{let f=i.truncation,h=Ge(s.replace(/\n*\[[^\]]*\]\s*$/,"")),w=h===0?"empty":`${h} line${h===1?"":"s"}`;return f?.truncated?`${w} (truncated from ${f.totalLines??"?"})`:w}case"compress":{let f=Array.isArray(i.blockIds)?i.blockIds:[],h=typeof i.compressedTokens=="number"?i.compressedTokens:0,w=typeof i.summaryTokens=="number"?i.summaryTokens:0,S=f.length===1?`b${String(f[0])}`:`${f.length} blocks`;if(h===0)return S;let M=h-w;return M<0?`${S} \xB7 ${Hr(-M)} LARGER than the range`:`${S} \xB7 ${Hr(M)} saved`}case"edit":{let f=typeof i.diff=="string"?i.diff:"";if(!f)return"applied";let{additions:h,removals:w}=Na(f);return`+${h} / -${w}`}case"write":{let f=Ge(s);return f===0?"written":`written (${f} ${Da(f,"line","lines")})`}case"bash":case"powershell":{let f=Ur(u);if(f===void 0)return s.trim()?oe(Kr(s),120):"done";let h=ja(u,s);return f===0?`exit 0${h}`:`exit ${f}`}case"grep":{let f=Ge(s);return f===0?"no matches":`${f} match${f===1?"":"es"}`}case"web_search":{let f=typeof i.count=="number"?i.count:Ge(s);return f===0?"no results":`${f} result${f===1?"":"s"}`}case"web_fetch":return`${typeof i.chars=="number"?i.chars:s.length} chars`;case"lsp":{let f=typeof i.count=="number"?i.count:void 0;return typeof i.error=="string"?oe(i.error,120):f===void 0?oe(Kr(s),120):`${f} location${f===1?"":"s"}`}case"quality":{if(typeof i.error=="string")return oe(i.error,120);if(i.off===!0)return"off";let f=typeof i.files=="number"?i.files:0,h=typeof i.functions=="number"?i.functions:0,w=typeof i.findings=="number"?i.findings:0,S=typeof i.score=="number"?` \xB7 ${Math.round(i.score)}`:"";return f===0?"no files":`${f} file${f===1?"":"s"} \xB7 ${h} fn \xB7 ${w} finding${w===1?"":"s"}${S}`}case"todo":{let f=i.todos??[];if(!Array.isArray(f)||f.length===0)return"list cleared";let h=f.filter(S=>S.status==="completed").length,w=f.filter(S=>S.status==="pending"||S.status==="in_progress").length;return`${h}/${f.length} done, ${w} open`}case"context":{let f=i.notes,h=f?Object.keys(f).length:0;return h===0?"no notes":`${h} note${h===1?"":"s"} held`}case"workflow":{let f=typeof i.agents=="number"?i.agents:0,h=typeof i.outputTokens=="number"?i.outputTokens:0,w=Array.isArray(i.steps)?i.steps.filter(M=>M.status==="failed").length:0;if(typeof i.error=="string")return`failed after ${f} agent(s)`;let S=typeof i.startedAt=="number"&&typeof i.endedAt=="number"?`, ${cr(i.endedAt-i.startedAt)}`:"";return`${f} agent(s), ${h} tokens${S}${w>0?`, ${w} failed`:""}`}case"bash_output":{let f=s.trim().split(`
|
|
10
|
-
`)[0]??"",h=/running/.test(f)?"running":/finished/.test(f)?"finished":"task",w=s.trim().split(`
|
|
11
|
-
`).slice(2).filter(S=>S.trim()).length;return w===0?h:`${h} \xB7 ${w} line${w===1?"":"s"}`}case"kill_shell":{let f=s.trim().split(`
|
|
12
|
-
`)[0]??"";return f.startsWith("Stopped")?"stopped":oe(f,120)}default:{let f=s.trim().split(`
|
|
13
|
-
`).find(h=>h.trim());return f?oe(f,120):"done"}}}function Gr(e,t){let n=Ve(t);if(e==="edit"&&typeof n.diff=="string")return n.diff.split(`
|
|
14
|
-
`).filter(s=>s.length>0).slice(0,12);if(e==="bash"||e==="powershell"){if(Te(t).startsWith("Started bash_"))return[];let i=In(t);return(typeof i.output=="string"?i.output:Te(t).replace(/\n*Command exited with code \d+\s*$/,"")).trimEnd().split(`
|
|
15
|
-
`).filter(h=>h.trim()).slice(-4)}if(e==="bash_output")return Te(t).split(`
|
|
16
|
-
`).slice(2).filter(i=>i.trim()).slice(-6);if(e==="todo"){let s=n.todos??[],i={pending:"[ ]",in_progress:"[>]",completed:"[x]",dropped:"[-]"};return s.slice(0,6).map(u=>`${i[u.status??"pending"]??"[ ]"} ${u.content??""}`)}return e==="task"?Te(t).split(`
|
|
17
|
-
`).filter(s=>s.trim()&&!s.startsWith("## ")).slice(0,6):e==="workflow"?(n.steps??[]).map(u=>{let f=u.status==="running"?"\u25B8":u.status==="failed"?"\xD7":"\u2713",h=u.phase?`${u.phase} \xB7 `:"";return`${f} ${h}${u.label??"agent"}`}).slice(-6):[]}var kt=400;function qr(e,t){let n=Ve(t);if(e==="edit"&&typeof n.diff=="string")return n.diff.split(`
|
|
18
|
-
`).filter(h=>h.length>0).slice(0,kt);let s=In(t),u=(typeof s.output=="string"?s.output:Te(t).replace(/\n*Command exited with code \d+\s*$/,"")).trimEnd().split(`
|
|
19
|
-
`),f=u.slice(0,kt);return u.length>kt&&f.push(`\u2026 ${u.length-kt} more line(s)`),f}var Wa={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 Ua(e){if(e==="read")return"read";if(e==="grep"||e==="find"||e==="glob")return"search";if(e==="ls")return"list"}function Vr(e,t=!1){let n=[],s,i=()=>{if(!s||s.indices.length<2){s=void 0;return}n.push({start:s.indices[0],indices:s.indices,counts:s.counts,summary:Ka(s.counts,t)}),s=void 0};for(let[u,f]of e.entries()){let h=Ua(f.toolName);if(h===void 0){i();continue}s||(s={indices:[],counts:{}}),s.indices.push(u),s.counts[h]=(s.counts[h]??0)+1}return i(),n}function Ka(e,t){let n=[];for(let s of["search","read","list"]){let i=e[s];if(i===void 0)continue;let u=Wa[s],f=t?u.active:u.done,h=i===1?u.one:u.many;n.push(`${n.length===0?f:f.toLowerCase()} ${i} ${h}`)}return n.join(", ")}function Yr(e,t){let n=e[e.length-1];return n&&n.kind==="note"&&n.title===t.title?[...e.slice(0,-1),t]:[...e,t]}function _n(e){return typeof e=="string"?We(e):We(e.map(t=>t.type==="text"?t.text:t.type==="thinking"?"":t.type==="image"?"[image]":(t.type==="toolCall","")).filter(Boolean).join(""))}function Xr(e){return e.role==="user"?_n(e.content).trim():""}function Jr(e,t,n){let s=t.trim();if(!s)return e;let i=e.findIndex(f=>f.kind==="user"&&f.body.trim()===s);if(i===-1)return[...e,{id:n,kind:"user",title:"you",body:s}];let u=[...e];return u[i]={id:n,kind:"user",title:"you",body:s},u}function Ga(e){return e.content.filter(t=>t.type==="toolCall").map(t=>({name:t.name,arguments:t.arguments}))}function qa(e){return e.content.filter(t=>t.type==="toolCall").map(t=>t.id)}function Va(e){let t=e.map(f=>({toolName:f.kind==="result"||f.kind==="tool"?f.title:"",line:f.call??f.body})),n=Vr(t);if(n.length===0)return e;let s=new Map(n.map(f=>[f.start,f])),i=new Set(n.flatMap(f=>f.indices)),u=[];for(let[f,h]of e.entries()){let w=s.get(f);if(w){let S=e[w.start];u.push({id:S?.id??`g-${w.start}`,kind:"collapsed",title:"collapsed",body:w.summary,full:w.indices.map(M=>e[M]?.call??e[M]?.body??"").filter(Boolean)});continue}i.has(f)||u.push(h)}return u}function St(e){let t=[];for(let n of e)if(n.role==="user"){let s=_n(n.content).trim();if(!s)continue;t.push({id:`u-${n.timestamp}`,kind:"user",title:"you",body:s})}else if(n.role==="assistant"){let s=_n(n.content).trim(),i=Ga(n),u=qa(n);s?t.push({id:`a-${n.timestamp}`,kind:n.stopReason==="error"?"error":"assistant",title:n.errorMessage?"failed":"fix",body:n.errorMessage?`${n.errorMessage}
|
|
20
|
-
|
|
21
|
-
${s}`:s}):n.errorMessage&&t.push({id:`e-${n.timestamp}`,kind:"error",title:"failed",body:n.errorMessage}),i.forEach((f,h)=>{let w=u[h];t.push({id:w?`tool-${w}`:`c-${n.timestamp}-${h}`,kind:"tool",title:f.name,body:$e(f.name,f.arguments),...w?{call:$e(f.name,f.arguments)}:{}})})}else if(n.role==="toolResult"){let s=vt(n.toolName,{content:n.content},n.isError),i=t.find(u=>u.id===`tool-${n.toolCallId}`);i?(i.kind="result",i.body=s,i.title=n.toolName):t.push({id:`r-${n.toolCallId}`,kind:"result",title:n.toolName,body:s})}return Va(t)}function zr(e,t,n){return Ba(e,Math.max(8,t)).map(s=>O(s,n))}var ze=new Map;function za(e){let t=e.body||" ",n=ze.get(e.id);if(n)return n.text!==t&&(n.component.setText(t),n.text=t),n.component;let s=new Ha(t,0,0,ar);return ze.set(e.id,{text:t,component:s}),s}var On=class{constructor(t){this.item=t}item;invalidate(){}shade(t){let n=Date.now()-(this.item.born??0);return fe(T.dim,t,Or(n,An))}render(t){let n=this.item.body;if(this.item.kind==="user"){let i=this.item.pending?[O(" queued \u2014 the run reads this at its next step",T.dim)]:[];return["",...zr(`> ${n}`,t,this.shade(T.user)),...i]}if(this.item.kind==="tool")return[O(`${qe()} ${n}`,this.shade(T.tool))];if(this.item.kind==="collapsed"){let i=[O(`${$t} ${n}`,this.shade(T.mute))],u=this.item.full??[];if(u.length>0)if(this.item.expanded===!0)for(let f of u)i.push(O(` ${f}`,this.shade(T.dim)));else i.push(O(` ${u.length} call(s) \xB7 ctrl+e to expand`,T.dim));return i}if(this.item.kind==="result"){let i=n.startsWith("exit ")&&n!=="exit 0";if(this.item.panel)return["",...this.item.panel(t),...n?[O(` ${En} ${n}`,i?T.bad:T.mute)]:[]];let u=[];this.item.call&&u.push(O(this.item.call,this.shade(T.tool)));let f=` ${En} ${n}`;if(u.push(O(f,i?T.bad:this.shade(T.mute))),this.item.expanded===!0&&(this.item.full?.length??0)>0){let M=O(` ${this.item.full.length} line(s) \xB7 ctrl+e to collapse`,T.dim);u.push(O(` ${$t}`,T.dim));for(let D of this.item.full){let F=D.startsWith("+")?T.tool:D.startsWith("-")?T.bad:T.dim;u.push(O(` ${D}`,F))}return u.push(M),u}let w=this.item.detail??[],S=Tn(Date.now()-(this.item.born??0),w.length);for(let M of w.slice(0,S)){let D=M.startsWith("+")?T.tool:M.startsWith("-")?T.bad:T.dim;u.push(O(` ${M}`,this.shade(D)))}return(this.item.full?.length??0)>0&&u.push(O(` ${$t} ${this.item.full.length} line(s) \xB7 ctrl+e to expand`,T.dim)),u}if(this.item.kind==="error"||this.item.kind==="note"){let i=this.item.kind==="error"?T.bad:T.mute;return["",...zr(n,t,this.shade(i))]}return["",...za(this.item).render(Math.max(8,t-2))]}},xt=class{items=[];status="";scrollOffset=0;scrollAnchor;settledOffset=0;viewportHeight=0;invalidate(){}entering(){let t=Date.now();return this.items.some(n=>{if(n.born===void 0)return!1;let s=t-n.born;return Lr(s,An)?!0:(n.detail?.length??0)>Tn(s,n.detail?.length??0)})}render(t){if(ze.size>this.items.length){let i=new Set(this.items.map(u=>u.id));for(let u of ze.keys())i.has(u)||ze.delete(u)}let n=[];for(let i of this.items)i.born??=Date.now(),n.push(...new On(i).render(t));this.status&&n.push(O(this.status,T.mute));let s=this.viewportHeight;if(s>0&&n.length>s){let i=n.length-s;this.scrollOffset!==this.settledOffset&&(this.scrollAnchor=void 0);let u=this.scrollAnchor,f;if(u!==void 0){let h=n.length-u;h>=0&&h<=i?f=h:f=Math.max(0,Math.min(this.scrollOffset,i))}else f=Math.max(0,Math.min(this.scrollOffset,i));return u===void 0&&(this.scrollOffset=f),this.settledOffset=this.scrollOffset,f===0?this.scrollAnchor=void 0:this.scrollAnchor===void 0&&(this.scrollAnchor=n.length-f),n.slice(i-f,i-f+s)}return n}};import{parseColor as Q}from"@netrodev/hxf-tui";var pe={off:Q("okhsl(230 12% 46%)"),minimal:Q("okhsl(240 55% 49%)"),low:Q("okhsl(252 60% 55%)"),medium:Q("okhsl(270 64% 60%)"),high:Q("okhsl(298 70% 64%)"),xhigh:Q("okhsl(332 80% 66%)"),max:Q("okhsl(42 95% 64%)")},Zr={off:Q("okhsl(230 14% 64%)"),minimal:Q("okhsl(240 60% 64%)"),low:Q("okhsl(252 64% 68%)"),medium:Q("okhsl(270 68% 72%)"),high:Q("okhsl(298 74% 76%)"),xhigh:Q("okhsl(332 82% 78%)"),max:Q("okhsl(42 96% 76%)")};function Ct(e){return pe[e]??pe.medium}var ei=[pe.minimal,pe.low,pe.medium,pe.high,pe.xhigh,pe.max];function ti(e){return Zr[e]??Zr.medium}var Qr=460;function At(e){return!Number.isFinite(e)||e<0||e>=Qr?0:1-e/Qr}var q=["off","minimal","low","medium","high","xhigh","max"];function ni(e){let t=e?.thinkingLevelMap;if(t===void 0)return q[q.length-1];for(let n=q.length-1;n>=0;n-=1)if(typeof t[q[n]]=="string")return q[n]}function oi(e){let t=q.indexOf(e);return q[(t+1+q.length)%q.length]}function si(e){let t=q.indexOf(e);return q[(t-1+q.length)%q.length]}import{mkdirSync as Za,readFileSync as Qa}from"node:fs";import{dirname as el}from"node:path";var Nn="\x1B[0m",V="\x1B[2m",Ya="\x1B[1m",Xa="\x1B[31m",Fn="\x1B[32m",ii="\x1B[33m",ri="\x1B[35m",Ln="\x1B[36m";function j(e,t){return`${t}${e}${Nn}`}function ai(e,t){return O(e,Ct(t))}function li(e){return e>=85?Xa:e>=70?ii:Fn}var Ja="\u2726";function ci(e,t,n,s){let i=j(`[${e}]`,Ln),u=`${j(Ja,V)} ${t}`,f=j(n,ii),h=s?` ${j("git:(",ri)}${j(s.replace(/^git:\(/,"").replace(/\)$/,""),Ln)}${j(")",ri)}`:"";return`${i}${j(" \u2502 ",V)}${u}${j(" \u2502 ",V)}${f}${h}`}function di(e,t,n){if(!t)return e;let s=n===void 0?t:`${t} ${j(dr(n),V)}`;return`${j(s,Ln)} ${j("\u2502",V)} ${e}`}function ui(e,...t){let n=Number.isFinite(e)?Math.min(100,Math.max(0,e)):0,s=Math.round(n/10),i=li(n),u=`${i}${"\u2588".repeat(s)}${V}${"\u2591".repeat(10-s)}${Nn}`,f=j(`${Math.round(n)}%`,i),h=t.filter(Boolean).join(j(" \u2502 ",V));return`${j("Context",V)} ${u} ${f}${h?`${j(" \u2502 ",V)}${h}`:""}`}function fi(e){return!Number.isFinite(e)||e<=0?"":`${j("Spent",V)} ${j(`$${e.toFixed(3)}`,Fn)}`}function pi(e,t,n,s){let i=Number.isFinite(t)&&t>0?t:0,u=Number.isFinite(n)?Math.max(0,n):0,f=Math.max(0,i-u),h=i>0?Math.min(100,u/i*100):0,w=Math.round(h/10),S=li(h),M=`${S}${"\u2588".repeat(w)}${V}${"\u2591".repeat(10-w)}${Nn}`,D=F=>F!==0&&Math.abs(F)<.01?`${F.toFixed(6).replace(/0+$/,"").replace(/\.$/,"")} ${s}`:`${F.toFixed(2)} ${s}`;return[`${j(e,Ya)}${j(" account",V)}`,` ${j("used",V)} ${M} ${j(`${h.toFixed(1)}%`,S)}`,` ${j("granted",V)} ${D(i)}`,` ${j("spent",V)} ${D(u)}`,` ${j("remaining",V)} ${j(D(f),S)}`]}function jn(e,t,n){let s=n===null?"":j(` ${n}ms`,V),i=t&&t!=="USD"?`${t} `:"";return`${j("Balance",V)} ${j(`${i}${e}`,Fn)}${s}`}var Dn=os,tl=18e4;async function nl(e){let t=new Set((await e.modelRuntime.getAvailable()).map(i=>i.provider).filter(i=>se(i))),n=ye.find(i=>t.has(i));return n?(await e.modelRuntime.getAuth(n))?.auth?.apiKey:void 0}function ol(){try{let e=JSON.parse(Qa(Dn,"utf8"));return!e.data||typeof e.cachedAt!="number"?void 0:{data:e.data,cachedAt:e.cachedAt}}catch{return}}function Tt(e){if(e.unlimited)return jn("unlimited","",e.latencyMs);let n=e.unit==="USD"||e.unit==="CNY"?`$${e.remaining.toFixed(2)}`:`${e.remaining.toLocaleString()}`;return jn(n,e.unit,e.latencyMs)}async function mi(e){let t=ol();if(t&&Date.now()-t.cachedAt<tl)return Tt(t.data);let n=await nl(e);if(!n)return t?Tt(t.data):void 0;let s=Date.now(),i=await Ae(n,{timeoutMs:3e3});if(!i.ok)return t?Tt(t.data):void 0;let u={remaining:i.remaining??0,limit:i.limit??0,unit:i.unit,unlimited:i.unlimited,latencyMs:Date.now()-s};return Za(el(Dn),{recursive:!0}),ie(Dn,JSON.stringify({data:u,cachedAt:Date.now()})),Tt(u)}import{chmodSync as sl,existsSync as rl,readFileSync as il}from"node:fs";import{join as al}from"node:path";function hi(e){return al(e,"account-credential.json")}function gi(e,t){return Buffer.from(`${e}:${t}`,"utf8").toString("base64")}function Wn(e){let t=e.trim();if(!t)return null;let n=i=>{let u=i.indexOf(":");return u<=0||u===i.length-1?null:{username:i.slice(0,u),password:i.slice(u+1)}},s=n(t);if(s)return s;try{let i=Buffer.from(t,"base64").toString("utf8");return i.includes(":")?n(i):null}catch{return null}}function bi(e,t,n){try{let s={credential:gi(t,n),username:t,savedAt:Math.floor(Date.now()/1e3)},i=hi(e);return ie(i,JSON.stringify(s,null,2)),sl(i,384),!0}catch{return!1}}function wi(e){try{let t=hi(e);if(!rl(t))return null;let n=JSON.parse(il(t,"utf8"));return!n?.credential||!n?.username?null:n}catch{return null}}async function ll(e,t){let n=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t),signal:AbortSignal.timeout(2e4)}),s=await n.text(),i;try{i=JSON.parse(s)}catch{throw new Error(`the panel answered ${n.status} with something that is not JSON`)}let u=i;if(!n.ok||u.success===!1)throw new Error(u.message||`the panel answered ${n.status}`);return u.data}async function yi(e,t,n,s){let i=await ll(`${e}/api/auth/cli/credential`,{credential:gi(t,n),client_info:s});if(!i?.token)throw new Error("the panel accepted the credential but returned no key");return{token:i.token}}import{execFileSync as cl}from"node:child_process";import{createHash as dl}from"node:crypto";import{readFileSync as ul}from"node:fs";import{arch as fl,hostname as pl,platform as ki}from"node:os";function ml(e){try{return ul(e,"utf8").trim()}catch{return""}}function $i(e,t){try{return cl(e,t,{encoding:"utf8",timeout:3e3})}catch{return""}}function hl(){return $i("reg",["query","HKLM\\SOFTWARE\\Microsoft\\Cryptography","/v","MachineGuid"]).match(/MachineGuid\s+REG_SZ\s+([0-9a-fA-F-]+)/)?.[1]??""}function gl(){return $i("ioreg",["-rd1","-c","IOPlatformExpertDevice"]).match(/"IOPlatformUUID"\s*=\s*"([^"]+)"/)?.[1]??""}function bl(){return["/sys/class/dmi/id/product_uuid","/sys/class/dmi/id/board_serial","/sys/class/dmi/id/product_serial","/etc/machine-id","/var/lib/dbus/machine-id"].map(ml).filter(Boolean)}function wl(){switch(ki()){case"win32":{let e=hl();return e?[e]:[]}case"darwin":{let e=gl();return e?[e]:[]}default:return bl()}}var Mt;function vi(){if(Mt)return{id:Mt,weak:!1};let e=wl(),t=e.length===0,n=[ki(),fl(),...e,t?pl():""].join("|");return Mt=dl("sha256").update(n).digest("hex").slice(0,32),{id:Mt,weak:t}}var yl="/cli/checkin",kl=["Bearer",""].join(" ").trim(),$l=5e5;function Un(e){return`$${(e/$l).toFixed(2)}`}async function xi(e,t,n,s,i){let u=new AbortController,f=setTimeout(()=>u.abort(),i);try{let h=await s(`${n}${yl}`,{method:t,headers:{[as]:ls(),"X-HowToFix-Device":vi().id,Authorization:`${kl} ${e}`},signal:u.signal}),w={};try{w=await h.json()}catch{}return{status:h.status,body:w}}finally{clearTimeout(f)}}async function Kn(e,t){let n=(t?.baseUrl??"https://api.howtofix.id/v1").replace(/\/+$/,""),s=t?.fetchImpl??fetch,i=t?.timeoutMs??1e4,u=e.trim();if(!u)return{ok:!1,enabled:!1,checkedInToday:!1,quotaToday:0,message:"no token given"};try{let{status:f,body:h}=await xi(u,"GET",n,s,i);if(f===401||f===403)return{ok:!1,enabled:!1,checkedInToday:!1,quotaToday:0,message:"the gateway rejected that token for the check-in status"};if(f>=400||h.success!==!0)return{ok:!1,enabled:!1,checkedInToday:!1,quotaToday:0,message:typeof h.message=="string"?h.message:`the gateway answered ${f}`};let w=h.data??{};return{ok:!0,enabled:w.enabled===!0,checkedInToday:w.checked_in_today===!0,quotaToday:Number(w.quota_today??0)||0,message:""}}catch(f){return{ok:!1,enabled:!1,checkedInToday:!1,quotaToday:0,message:f instanceof Error&&f.name==="AbortError"?"the gateway did not answer the check-in in time":"could not reach the gateway"}}}async function Si(e,t){let n=(t?.baseUrl??"https://api.howtofix.id/v1").replace(/\/+$/,""),s=t?.fetchImpl??fetch,i=t?.timeoutMs??15e3,u=e.trim();if(!u)return{ok:!1,alreadyClaimed:!1,blocked:!1,quotaAwarded:0,message:"no token given"};try{let{status:f,body:h}=await xi(u,"POST",n,s,i);if(h.success===!0){let D=h.data??{};return{ok:!0,alreadyClaimed:!1,blocked:!1,quotaAwarded:Number(D.quota_awarded??0)||0,message:""}}let w=typeof h.message=="string"?h.message:`the gateway answered ${f}`,S=/device already claimed|account blocked|appeal/i.test(w);return{ok:!1,alreadyClaimed:!S&&/签到|check-?in|already|今日/.test(w)&&!/not enabled/i.test(w),blocked:S,quotaAwarded:0,message:w}}catch(f){return{ok:!1,alreadyClaimed:!1,blocked:!1,quotaAwarded:0,message:f instanceof Error&&f.name==="AbortError"?"the gateway did not answer the check-in in time":"could not reach the gateway"}}}function vl(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 xl(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 Ci(e){let t=vl(e.contextWindow),n=xl(e.cost);return[t?`${t} ctx`:"",n].filter(Boolean).join(" \xB7 ")}function Ai(){return{}}function Ti(e,t,n,s=Date.now()){let i={...e};return t==="run"?(n===void 0||n===""?delete i.run:i.run={label:n,since:e.run?.since??s},i):(n===void 0||n===""?delete i[t]:i[t]=n,i)}function Mi(e,t){let n={...e};return t===void 0?delete n.retry:n.retry=t,n}function Sl(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 Hn(e,t=72){let n=e.split(`
|
|
22
|
-
`).map(s=>s.trim()).find(s=>s!=="")??"";return n.length>t?`${n.slice(0,t-1)}\u2026`:n}function Cl(e,t){let n=Math.max(0,Math.ceil((e.until-t)/1e3)),s=n>0?`in ${n}s`:"now",i=`retry ${e.attempt}/${e.maxAttempts} ${s}`,u=Hn(e.error);return u===""?i:`${i} \xB7 ${u}`}function Ri(e,t,n=Date.now()){return e.prompt?`? ${e.prompt}`:e.retry?`* ${Cl(e.retry,n)}`:e.note?`* ${e.note}`:e.run?`${t} ${e.run.label} \xB7 ${Sl(n-e.run.since)}`:e.tally?e.tally:""}function Ei(e){return e instanceof Error?e.message:String(e)}var Ye=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 s=this.pending;this.pending=void 0;let i=await this.applyOnce(s);t.added.push(...i.added),t.removed.push(...i.removed),t.unchanged.push(...i.unchanged),t.problems.push(...i.problems)}let n=this.active;return t.added=t.added.filter(s=>n.has(s)),t.removed=[...new Set(t.removed.filter(s=>!n.has(s)))],t.added=[...new Set(t.added)],t.unchanged=[...new Set(t.unchanged.filter(s=>n.has(s)))],t}async applyOnce(t){let n=[...t].filter(u=>!this.active.has(u)),s=[...this.active].filter(u=>!t.has(u)),i=[...t].filter(u=>this.active.has(u));if(n.length===0&&s.length===0)return{added:[],removed:[],unchanged:i,problems:[]};try{await this.apply(n,s)}catch(u){let f=`mcp reconciliation failed: ${Ei(u)}`;return this.report(f),{added:[],removed:[],unchanged:[],problems:[f]}}for(let u of n)this.active.add(u);for(let u of s)this.active.delete(u);return{added:n,removed:s,unchanged:i,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 s=`mcp teardown failed: ${Ei(n)}`;return this.report(s),{added:[],removed:[],unchanged:[],problems:[s]}}}};import{mkdirSync as Al}from"node:fs";import{join as Tl}from"node:path";import{matchesKey as Rt}from"@netrodev/hxf-tui";var Bn=["all","running","failed","done"];function Ii(){return{selectedPhase:0,filter:"all",paused:!1,expanded:!1,follow:!0}}function _i(e){if(Rt(e,"up"))return"up";if(Rt(e,"down"))return"down";if(Rt(e,"enter"))return"enter";if(Rt(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 Pi(e,t,n){if(t.length===0)return e;let s=Math.max(0,Math.min(t.length-1,e.selectedPhase+n));return{...e,selectedPhase:s,follow:!1}}function Ml(e){let t=Bn.indexOf(e);return Bn[(t+1)%Bn.length]}function Oi(e,t,n){switch(t){case"up":return Pi(e,n,-1);case"down":return Pi(e,n,1);case"enter":return{...e,expanded:!e.expanded};case"filter":return{...e,filter:Ml(e.filter)};case"pause":return{...e,paused:!e.paused};default:return e}}function Li(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 Ni(e){return e==="all"?"":` \xB7 ${e}`}var Fi="ctrl+f";function ji(e,t,n=!0){if(!n)return"Ctrl+F panel keys \xB7 Esc unpin";let s=["\u2191/\u2193 phase",e.expanded?"Enter collapse":"Enter drill in"];return s.push(e.expanded?"Esc back out":"Esc unpin"),s.push(`f filter${e.filter==="all"?"":` (${e.filter})`}`),t?(s.push(e.paused?"p resume":"p pause"),s.push("x stop")):e.paused&&s.push("p resume"),s.push("s save script"),e.paused&&s.unshift("paused"),s.join(" \xB7 ")}function Rl(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 Di(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=Rl(e.name);if(!n)return{ok:!1,reason:`"${e.name}" is not a usable filename, so the script was not written`};let s=Tl(t,`${n}.js`);try{Al(t,{recursive:!0}),ie(s,e.code)}catch(i){return{ok:!1,reason:i instanceof Error?i.message:String(i)}}return{ok:!0,path:s}}function Wi(e){let t=()=>{};return{select:(n,s)=>e.select(n,s),confirm:(n,s)=>e.confirm(n,s),input:n=>e.input(n),notify:(n,s)=>e.notify(n,s),onTerminalInput:()=>t,setStatus:(n,s)=>e.setStatus(n,s),setWorkingMessage:t,setWorkingVisible:t,setWorkingIndicator:t,setHiddenThinkingLabel:t,setWidget:(n,s,i)=>{s!==void 0&&!Array.isArray(s)||e.setWidget?.(n,s,i?.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}}var Bi={borderColor:()=>"",selectList:{selectedPrefix:e=>O(e,T.accent),selectedText:e=>O(e,T.text,{bold:!0}),description:e=>O(e,T.mute),scrollInfo:e=>O(e,T.dim),noMatch:e=>O(e,T.mute)}},Yi=Symbol.for("@netrodev/hxf-tui/layout-node");function Yl(e){if(typeof e!="object"||e===null)return;let t=e[Yi];return typeof t=="function"?t.call(e):void 0}var zn=Pl(El);async function Gi(e){try{let{stdout:t}=await zn("git",["-C",e,"rev-parse","--abbrev-ref","HEAD"],{encoding:"utf8"}),n=t.trim();if(!n||n==="HEAD")return"";let{stdout:s}=await zn("git",["-C",e,"status","--porcelain"],{encoding:"utf8"});return`git:(${n}${s.trim()?"*":""})`}catch{return null}}var Yn=class{folder;model;git;percent=0;meter=new yt(0);activity=Ai();live=!1;activitySince=Date.now();thinking="medium";ceiling=void 0;usage="";cost=0;skipPermissions=!1;constructor(t,n){this.folder=Ol(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;setThinking(t){t!==this.thinking&&(this.thinking=t,this.levelChangedAt=Date.now())}levelFlashAmount(){return this.levelChangedAt===0?0:At(Date.now()-this.levelChangedAt)}flashing(){return this.levelFlashAmount()>0}levelText(t){if(this.atCeiling())return jr(this.thinking,ei,t);let n=this.levelChangedAt===0?Number.POSITIVE_INFINITY:t-this.levelChangedAt;return At(n)<=0?ai(this.thinking,this.thinking):Fr(this.thinking,{rest:Ct(this.thinking),lit:ti(this.thinking)},1-At(n))}meterValue(){return this.meter.value!==this.percent&&this.meter.set(this.percent),this.meter.step()}beginRun(){this.live=!0,this.activitySince=Date.now()}waitedMs(){return Date.now()-this.activitySince}abandonAnimations(){this.meter.snap(this.percent)}render(t){let n=Date.now(),s=this.percent===0&&this.meter.value===0?0:this.meterValue(),i=this.levelText(n),u=ci(this.model,i,this.folder,this.git),f=[Re(`${di(u,this.live?qe():"",this.live?this.waitedMs():void 0)} ${ui(s,this.usage,fi(this.cost))}`,t)];this.skipPermissions&&f.push(Re(O("Permissions OFF \u2014 critical commands and the repeat guard are not enforced",T.bad),t));let h=zs();h&&f.push(Re(O(h,T.warn),t));let w=Us(gt());w&&f.push(Re(O(w,T.accent),t));let S=Ri(this.activity,qe(),n),M=this.live?Dr(S,{base:Cn(this.waitedMs(),T.mute,T.warn,T.bad),bright:T.text,charMs:45},n):O(S,Cn(this.waitedMs(),T.mute,T.warn,T.bad));return f.push(Re(M,t)),f}},Xn=class{constructor(t){this.draw=t}draw;render(t){return this.draw(t)}invalidate(){}},Jn=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),s=this.editor.render(n).filter(h=>It(h)>0),i=s.length>0?s:[""],u="\u2500".repeat(Math.max(0,t-2)),f=i.map(h=>{let w=Math.max(0,n-It(h));return`\u2502 ${h}${" ".repeat(w)} \u2502`});return[`\u250C${u}\u2510`,...f,`\u2514${u}\u2518`,...this.hud.render(t)]}handleInput(t){this.editor.handleInput(t)}};function Xl(e,t,n,s=!1,i=[]){let u=Math.max(24,n),f=u-4,h=(L,Z)=>{let me=It(L)>f?Re(L,f,"\u2026"):L,te=`${me}${" ".repeat(Math.max(0,f-It(me)))}`;return`\u2502 ${Z?Z(te):te} \u2502`},w="\u2500".repeat(u-2),S=[h(` ${t}`),...e.render(f).map(L=>h(L))];S.push(h(" type to filter \xB7 \u2191\u2193 move \xB7 enter select \xB7 esc cancel"));let M=i.flatMap(L=>L===""?[""]:ql(L,f)),D=M.length>0?[h(""),...M.map(L=>h(L,Z=>O(Z,T.mute)))]:[];if(!s)return["",`\u250C${w}\u2510`,...S,...D,`\u2514${w}\u2518`];let F=Nr(T.line,T.warn,Date.now(),1400),K=O("\u2502",F),I=(L,Z)=>O(`${L}${w}${Z}`,F),H=[...S,...D].map(L=>`${K}${L.slice(1,-1)}${K}`);return["",I("\u250C","\u2510"),...H,I("\u2514","\u2518")]}function Jl(e,t){let n=t.split(`
|
|
23
|
-
`).filter(Boolean),s=n.filter(f=>f.startsWith("Reason:")),i=n.filter(f=>!f.startsWith("Reason:")&&!f.startsWith("Allow tool:"));return[...e.endsWith(" wants to run")?[]:[e],...s,...i.length>0?["",...i]:[]]}function Me(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,i=[...e.state.messages].reverse().find(u=>u.role==="assistant")?.usage?.totalTokens;return!n||typeof i!="number"||!Number.isFinite(i)||n.contextWindow<=0?0:Math.min(100,Math.round(i/n.contextWindow*100))}function Vn(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 with email:password (or a base64 credential), or paste a key"],["sync","re-sync models from howtofix.id"],["usage","show the account's quota and what it has spent"],["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","login | logout | status | tunnel on/off \u2014 Roblox sign-in and workspace link (alone: RoToolbox status)"],["proxy","route requests through a proxy, or show the current one"],["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(([s,i])=>({name:s,description:i}));for(let s of e.promptTemplates)n.push({name:s.name,description:s.description});for(let s of e.extensionRunner.getRegisteredCommands())n.push({name:s.invocationName,description:s.description});return n}function Zn(e,t){if(e!=="workflow")return;let n=Ve(t);if(!(typeof n.name!="string"||!Array.isArray(n.steps)))return n}function Zl(e,t){let n=Zn(e,t);return n?Pt(n):void 0}function Pt(e,t,n=!1){return s=>ur(e,[],s,t?.selectedPhase,t?Ql(e,t,n):void 0)}function Ql(e,t,n){return{filter:s=>Li(s,t.filter),footerText:ji(t,e.endedAt===void 0,n),filterLabel:Ni(t.filter),drill:t.expanded}}function ec(){let e=new qi(zi,{"tui.altScreen.pageUp":[],"tui.altScreen.pageDown":[],"tui.altScreen.halfPageUp":[],"tui.altScreen.halfPageDown":[],"tui.altScreen.top":[],"tui.altScreen.bottom":[]});Vi(e)}async function pu(e){let t=new Ul,n,s=new Bl(t,!0,void 0,{mouse:!0,onRightClickPaste:()=>n?.()}),i=new xt,u=new Yn(e.cwd,e.modelLabel);u.skipPermissions=mn();let f=o=>{let r=Date.now();(async()=>{try{let a=Xe(),l=k.getSessionStats().sessionId;if(!io){io=!0;try{await wr(a,{keep:l})}catch{}}let d=await hr(a,l,o);d&&r>=Dt&&(ro=d,Dt=r)}catch{}})()},h=(o=!1)=>{!o&&!u.live||Gi(e.cwd).then(r=>{r!==null&&(u.git=r,v())})},w=new Wl(s,Bi,{paddingX:1}),S=new Map,M=(o,r)=>{r===void 0?S.delete(o):typeof r=="function"?S.set(o,r):S.set(o,()=>r)},D=()=>Math.max(20,t.columns),F,K=0,I=Ii(),H,L=null,Z=!1,me,te=!1,Xi,_t=()=>{!H||!Z||M("workflow",o=>Pt(H,I,te)(o))},Qn=()=>{H&&(me=H.name),Z=!1,te=!1,M("workflow",void 0)};fr({onStop:o=>{L=o},isPaused:()=>I.paused});let eo=o=>{if(me===o.name)return;F=o;let r=o.endedAt??Date.now();K=Math.max(K,r+lr),H=o,Z=!0,M("workflow",a=>Pt(o,I,te)(a))},to=new Jn(w,u),k=e.session,no=e.setCompressToolOutput,oo=!1,Ot=()=>{let o=k.getSessionStats().cost;return u.cost=o,o},Lt=rs(e.maxBudgetUsd),so=!1,Ji=()=>{let o=Lt.check(Ot());o===void 0||so||(so=!0,k.isStreaming&&k.abort(),p("budget",is(o.spent,o.limit)))},he=()=>{u.ceiling=ni(k.model)},ge=Ss(P),Nt,Zi=async()=>!ge||!xs(ge)||vs(ge)?!1:(Nt??=(async()=>{try{let o=await As(P,ge);return o.renewed?(ge=o.credential,o.message&&p("connect",o.message),await k.modelRuntime.setRuntimeApiKey("howtofix",o.credential.accessToken),!0):(o.message&&p("connect",o.message),!1)}catch{return!1}finally{Nt=void 0}})(),await Nt),Ft,Xe=()=>Ft??=pr(e.cwd),ro,jt="",Dt=0,io=!1,be,Qi=()=>{let o=new Set(["session_info","usage","label","context_edit","custom","model_change","thinking_level_change"]),r=[],a=l=>{for(let d of l)o.has(d.entry.type)||r.push(d.entry.id),a(d.children)};return a(k.sessionManager.getTree()),r},ao=!1,ea=()=>{if(ao)return;ao=!0;let o=Hi().getResolvedBindings();Vi(new qi(zi,{...o,"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"]}))},lo=!1,ta=()=>{lo||(lo=!0,zl())},co=()=>{let o=k.sessionManager.getTree();if(o.length===0){p("rewind","nothing to rewind to yet");return}Xe().disabled&&p("rewind","conversation rewind only; this directory is not a git repository"),ta(),ea();let r=Math.max(8,Math.floor(t.rows*.6)),a=new Vl(o,k.sessionManager.getLeafId(),r*2,l=>{Wt(),na(l)},()=>Wt());if(!a.getTreeList().getSelectedNode()){p("rewind","nothing to rewind to yet");return}be=a,be.focused=!0,M("rewind",l=>be?.render(l)??[]),v()},Wt=()=>{be=void 0,M("rewind",void 0),v()},na=async o=>{let r=Xe(),l=k.getUserMessagesForForking().findIndex(c=>c.entryId===o),d=l>=0?mr(r,k.getSessionStats().sessionId)[l]:void 0,y=d?(await br(r,d)).length:0;if(y===0){await uo(o,void 0,"conversation");return}_(`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`}],c=>{uo(o,d,c)})},uo=async(o,r,a)=>{let l=[];if((a==="both"||a==="conversation")&&!k.isStreaming)try{let d=await k.navigateTree(o);if(d.cancelled){p("rewind","conversation rewind cancelled");return}l.push("conversation rewound"),i.items=St(k.state.messages),d.editorText&&(w.setText(d.editorText),l.push("prompt restored to the editor"))}catch(d){G(`conversation rewind failed: ${d instanceof Error?d.message:String(d)}`);return}if((a==="both"||a==="code")&&r){let d=await gr(Xe(),r);if(!d.ok){G(`code rewind failed: ${d.output}`);return}l.push(d.output),d.removed.length>0&&l.push(`removed ${d.removed.length} file(s)`),h()}p("rewind",l.join(`
|
|
24
|
-
`)||"nothing to do"),v()};h(!0),f("session start"),e.note&&i.items.push({id:"note",kind:"note",title:"note",body:e.note}),i.items.push(...St(k.state.messages)),u.percent=Me(k),Ot(),u.abandonAnimations(),u.setThinking(k.thinkingLevel),he(),w.setAutocompleteProvider(new Ki(Vn(k),e.cwd)),mi(k).then(o=>{o&&(u.usage=o,s.requestRender())});let fo=async o=>{let{checkForUpdate:r,checkFailedNote:a,installUpdate:l}=await import("./chunk-7CHDNTH6.js"),d=await r(o.current);if(!d.available){let c=a(d);c?p("update",c):o.install&&p("update",d.message);return}if(!o.install){p("update",`${d.message}. run /update to install it.`);return}C("note",`installing HowToFix ${d.latest}\u2026`);let y=await l({version:d.latest});C("note",void 0),p("update",y.message),v()};e.update&&fo(e.update);let re=null,po="",mo=!1,ho=[],Ee,Ut=()=>{},v=()=>{Ut(),s.requestRender()},C=(o,r)=>{u.activity=Ti(u.activity,o,r)},Kt=o=>{u.activity=Mi(u.activity,o)},Je=new Map,Ht=new Set,oa=()=>[...Je].map(([o,r])=>`${Ht.has(o)?"!":"\u2713"} ${o} \xD7${r}`).join(" | "),sa=()=>{let o=oa();C("tally",o||void 0)},_=(o,r,a,l,d=!1,y=[])=>{let c=new Hl(r,8,Bi.selectList);c.onSelect=m=>{re=null,Ee=void 0,a(m.value)},c.onCancel=()=>{re=null,Ee=void 0,l?.(),v()},Ee=()=>c.onCancel?.(),po=o,mo=d,ho=y,re=c,wo+=1,v()},p=(o,r)=>{i.items=Yr(i.items,{id:`cmd-${Date.now()}-${i.items.length}`,kind:"note",title:o,body:r}),C("tally",void 0),v()};tr(o=>{o.background&&p("agent",`${Xs(o)}
|
|
25
|
-
read it with /agents ${o.id}`)});let Bt=!1,ra=o=>{Bt||(Bt=!0,(async()=>{try{let r=(await k.modelRuntime.getAvailable()).filter(g=>se(g.provider)),a=new Set(r.map(g=>g.provider)),l=ye.find(g=>a.has(g)),d=l?(await k.modelRuntime.getAuth(l))?.auth?.apiKey:void 0;if(!d)return;let y=wt(r.map(g=>g.id)),{live:c,probed:m}=await bs(y,d,{exclude:o,limit:4});if(c.length===0)return;let b=re===null;p("gateway",`${c.length} of ${m.length} probed models answer right now (${c.join(", ")}); ${b?"the model picker is open below":"switch with /model"}.`),b&&Fe("/model")}catch{}finally{Bt=!1}})())},G=o=>{i.items.push({id:`err-${Date.now()}-${i.items.length}`,kind:"error",title:"failed",body:o});let r=xr(o);r!==void 0&&p("gateway",r);let a=vr(o);a!==void 0&&ra(a),C("tally",void 0),v()},Pe=o=>{k.setThinkingLevel(o,{persist:!0}),u.setThinking(o),he(),C("note",`thinking ${o}`),v()};Is((o,r)=>{let{promise:a,resolve:l}=Promise.withResolvers();return _(o,[{value:"allow",label:"allow"},{value:"deny",label:"deny"}],d=>l(d==="allow"),()=>l(!1),!0,Jl(o,r)),a});let Gt=new Map,go=o=>{let r=Wi({select:(a,l)=>{let{promise:d,resolve:y}=Promise.withResolvers();return _(a,l.map(c=>({value:c,label:c})),y,()=>y(void 0)),d},confirm:(a,l)=>{let{promise:d,resolve:y}=Promise.withResolvers();return _(`${a} \u2014 ${l}`,[{value:"yes",label:"yes"},{value:"no",label:"no"}],c=>y(c==="yes"),()=>y(!1)),d},input:a=>{let{promise:l,resolve:d}=Promise.withResolvers();return C("prompt",a),v(),ee=y=>{ee=void 0,C("prompt",void 0),d(y),v()},l},notify:(a,l)=>{l==="error"?G(a):p("mcp",a)},setStatus:(a,l)=>{l===void 0?Gt.delete(a):Gt.set(a,l),C("note",[...Gt.values()].join(" | ")||void 0),v()},setWidget:(a,l)=>{M(a,l),v()}});o.bindExtensions({uiContext:r,mode:"print",onError:a=>G(`${a.event}: ${a.error}`)}).catch(a=>G(a instanceof Error?a.message:String(a)))};go(k);let ve=new Dl,ia={invalidate:()=>i.invalidate(),render:o=>{let r=ve.render(Math.max(20,o)).length;return i.viewportHeight=Math.max(1,Math.max(8,t.rows)-r),i.render(o)},handleMouse:o=>{if(Ro(o))return nt(),{handled:!0};let r=o.type==="wheel"?o.wheelDelta??0:0;if(r!==0)return i.scrollOffset=Math.max(0,i.scrollOffset-r*3),v(),{handled:!0}}},aa=new Kl(ia,{follow:"none",overscroll:"contain"}),Ze=new Gl([{component:aa,grow:1,shrink:1},{component:ve,grow:0,shrink:0,basis:"auto"}]),bo="",wo=0,la=()=>`${re?`picker:${wo}`:"dock"}|${[...S.keys()].join(",")}`;Ut=()=>{let o=la();if(o===bo)return;bo=o,ve.clear();for(let a of S.values())ve.addChild(new Xn(a));let r=re;if(r){let a=po,l=mo,d=ho;ve.addChild({render:y=>Xl(r,a,y,l,d),invalidate:()=>{}})}else ve.addChild(to);Ze.invalidate()},Ut();let yo={focused:!1,invalidate(){i.invalidate(),to.invalidate(),re?.invalidate(),Ze.invalidate()},[Yi]:()=>Yl(Ze),render:o=>Ze.render(o),handleMouse(o){if(Ro(o))return nt(),{handled:!0}},handleInput(o){w.handleInput(o)}};s.setLayoutRoot(yo),s.setFocus(yo);let X=0,ce="",qt=!1,we=!1,Vt,xe="",ko=0,Ie=!1,Qe=Date.now(),et=!1,tt=new Map,$o=()=>{let o=new Set(k.getSteeringMessages().map(r=>r.trim()).filter(Boolean));for(let r of i.items)r.kind!=="user"||!r.pending||o.has(r.body.trim())||(r.pending=void 0)},vo=o=>{if(o.type==="agent_start"&&$o(),o.type==="agent_start"||o.type==="turn_start")o.type==="agent_start"&&Es(),u.live||u.beginRun(),ce="",we=!1,Ie=!1,Qe=Date.now(),xe="";else if(o.type==="message_update"&&o.assistantMessageEvent.type==="thinking_delta"){we=!0,xe===""&&(ko=Date.now()),xe+=o.assistantMessageEvent.delta;let r=`think-${X}`,a=i.items.find(d=>d.id===r),l=xe.split(`
|
|
26
|
-
`).slice(-6).join(`
|
|
27
|
-
`);a?a.body=l:i.items.push({id:r,kind:"note",title:"thinking",body:l})}else if(o.type==="message_update"&&o.assistantMessageEvent.type==="thinking_end"){let r=`think-${X}`,a=i.items.find(l=>l.id===r);if(a){let l=Math.max(1,Math.round((Date.now()-ko)/1e3));a.title="thought",a.body=`${l}s \xB7 ${xe.length} chars of reasoning`}xe=""}else if(o.type==="message_update"&&o.assistantMessageEvent.type==="text_delta"){we=!0,ce+=o.assistantMessageEvent.delta;let r=We(ce),a=`live-${X}`,l=i.items.find(d=>d.id===a);l?l.body=r:i.items.push({id:a,kind:"assistant",title:"HowToFix",body:r})}else if(o.type==="tool_execution_start"){tt.set(o.toolCallId,o.args),we=!1,Ie=!1,Qe=Date.now();let r=`tool-${o.toolCallId}`,a=$e(o.toolName,o.args),l=i.items.find(d=>d.id===r);if(l?(l.kind="tool",l.title=o.toolName,l.body=a,l.live=!0):i.items.push({id:r,kind:"tool",title:o.toolName,body:a,live:!0}),Vt=o.toolName,o.toolName==="task"){let d=Js.filter(y=>y.status==="queued"||y.status==="running");C("note",d.map(y=>`${y.agent} ${y.status}`).join(" | ")||"agent running")}}else if(o.type==="tool_execution_update"){let r=Zl(o.toolName,o.partialResult);if(r){let a=`tool-${o.toolCallId}`,l=i.items.find(y=>y.id===a);l?l.panel=r:i.items.push({id:a,kind:"tool",title:o.toolName,body:$e(o.toolName,tt.get(o.toolCallId)),panel:r,live:!0});let d=Zn(o.toolName,o.partialResult);d&&me!==d.name&&eo(d),v()}}else if(o.type==="tool_execution_end"){u.percent=Me(k);let r=i.items.find(b=>b.id===`tool-${o.toolCallId}`);r&&(r.live=!1,r.body=$e(o.toolName,tt.get(o.toolCallId))),tt.delete(o.toolCallId),Vt=void 0,we=!0,Ie=!1,Je.set(o.toolName,(Je.get(o.toolName)??0)+1),o.isError&&Ht.add(o.toolName),sa();let a=Gr(o.toolName,o.result),l=qr(o.toolName,o.result),d=Zn(o.toolName,o.result),y=d?Pt(d):void 0;d&&me!==d.name&&eo(d);let c=i.items.find(b=>b.id===`tool-${o.toolCallId}`),m=vt(o.toolName,o.result,o.isError);c?(c.kind="result",c.call=c.body,c.body=m,c.live=!1,a.length>0&&(c.detail=a),l.length>0&&(c.full=l),y&&(c.panel=y)):i.items.push({id:`tool-${o.toolCallId}`,kind:"result",title:o.toolName,body:m,...a.length>0?{detail:a}:{},...l.length>0?{full:l}:{},...y?{panel:y}:{}}),(o.toolName==="bash"||o.toolName==="powershell"||o.toolName==="edit"||o.toolName==="write")&&h()}else if(o.type==="compaction_start"){we=!0;let r=o.reason==="manual"?"on request":"context is nearly full",a=i.items.find(y=>y.id===`compact-${X}`),l="compacting context",d=`${r} \xB7 summarizing the older turns`;a?(a.title=l,a.body=d):i.items.push({id:`compact-${X}`,kind:"note",title:l,body:d,live:!0}),C("note","compacting context")}else if(o.type==="compaction_end"){let r=i.items.find(y=>y.id===`compact-${X}`),a=o.result,l="compacted",d;if(o.aborted)d="cancelled";else if(o.errorMessage)d=`failed: ${o.errorMessage}`;else if(a){let y=Math.round(a.tokensBefore/1e3),c=a.estimatedTokensAfter!==void 0?Math.round(a.estimatedTokensAfter/1e3):void 0,m=a.estimatedTokensAfter!==void 0?a.tokensBefore-a.estimatedTokensAfter:void 0,b=m!==void 0&&m<2e3;d=c!==void 0?`${y}k \u2192 ${c}k tokens \xB7 older turns summarized${b?`
|
|
28
|
-
this freed almost nothing; the window may be too small for this work`:""}`:`${y}k tokens \xB7 older turns summarized`}else d="nothing to compact";r?(r.title=l,r.body=d,r.live=!1):i.items.push({id:`compact-${X}`,kind:"note",title:l,body:d}),u.percent=Me(k),C("note",void 0)}else if(o.type==="message_start"&&o.message.role==="user"){let r=Xr(o.message);r&&(i.items=Jr(i.items,r,`u-${o.message.timestamp}`)),$o()}else if(o.type==="message_end"&&o.message.role==="assistant"){let r=i.items.find(l=>l.id===`live-${X}`);r&&(r.id=`done-${X}`);let a=o.message.errorMessage;a&&r?(r.title="failed",r.kind="error",r.body=ce.trim()?`${a}
|
|
29
|
-
|
|
30
|
-
${ce.trim()}`:a):a&&i.items.push({id:`e-${o.message.timestamp}`,kind:"error",title:"failed",body:a}),X+=1,ce="",u.percent=Me(k)}else if(o.type==="agent_settled"){u.live=!1;let r=[...k.getSteeringMessages()].map(a=>a.trim()).filter(Boolean);if(r.length>0){let a=w.getText().trim();w.setText(a?`${r.join(`
|
|
31
|
-
`)}
|
|
32
|
-
${a}`:r.join(`
|
|
33
|
-
`));let l=new Set(r);for(let d of i.items)d.kind==="user"&&d.pending&&l.has(d.body.trim())&&(d.pending=void 0);p("queued",`${r.length} unread message${r.length===1?"":"s"} were never read and are back in the editor`)}for(let a of i.items)a.kind==="user"&&a.pending&&(a.pending=void 0);if(f(jt),jt="",C("run",void 0),qt){let a=i.items.find(l=>l.id===`live-${X}`);a?(a.id=`stopped-${X}`,a.title="stopped",a.body=ce.trim()||"(no output)",a.live=!1):i.items.push({id:`stopped-${X}`,kind:"note",title:"stopped",body:"run cancelled"}),X+=1,ce="",p("stopped","run cancelled by Esc"),qt=!1}u.percent=Me(k),C("note",void 0),Kt(void 0),Gi(e.cwd).then(a=>{a!==null&&(u.git=a,v())}),w.disableSubmit=!1}else o.type==="thinking_level_changed"?u.setThinking(o.level):o.type==="auto_retry_start"?(C("note",void 0),Kt({attempt:o.attempt,maxAttempts:o.maxAttempts,error:o.errorMessage,until:Date.now()+o.delayMs})):o.type==="auto_retry_end"&&(Kt(void 0),o.success?p("retry",`answered on attempt ${o.attempt} after a retry`):C("note",`retry ${o.attempt} gave up${o.finalError?` \xB7 ${Hn(o.finalError)}`:""}`));Ji(),v()},zt=k.subscribe(vo),xo=setInterval(()=>{let o=F!==void 0&&Date.now()<K;if((et||k.isStreaming||u.settling()||i.entering()||re||o||u.atCeiling()||u.flashing()||u.activity.retry!==void 0)&&v(),(et||k.isStreaming)&&!we&&!Ie&&Date.now()-Qe>nc){Ie=!0;let r=Vt,a=Math.round((Date.now()-Qe)/1e3);C("note",r?`${r} has been running for ${a}s \u2014 it may be blocked; esc cancels`:`no answer yet after ${a}s \u2014 the provider may be stalled; ctrl+c cancels`),v()}},tc);xo.unref?.();let So=async o=>{Ee?.(),Ee=void 0,zt(),Ft&&yr(Ft,k.getSessionStats().sessionId),ro=void 0,Dt=0;let r=k.getSessionStats().sessionId;wn(r),yn(r),await st.dispose(),k.dispose(),k=o.session,no=o.setCompressToolOutput,st=new Ye({initial:Object.keys(Ne().mcpServers),apply:async(a,l)=>{if(await Se(),a.length>0||l.length>0){let d=[];a.length>0&&d.push(`connected ${a.join(", ")}`),l.length>0&&d.push(`stopped ${l.join(", ")}`),p(a.length>0?"mcp connected":"mcp stopped",d.join("; "))}},report:a=>G(a)}),X=0,ce="",i.items=[],i.scrollOffset=0,o.note&&i.items.push({id:"note",kind:"note",title:"note",body:o.note}),i.items.push(...St(k.state.messages)),u.model=o.modelLabel.split("/").at(-1)||"no-model",u.setThinking(k.thinkingLevel),he(),u.percent=Me(k),Ot(),u.abandonAnimations(),C("tally",void 0),C("run",void 0),w.setAutocompleteProvider(new Ki(Vn(k),e.cwd)),w.disableSubmit=!1,go(k),zt=k.subscribe(vo),v()},_e=async()=>{if(oo)return;oo=!0,clearInterval(xo),zt();try{let r=Os(_s);if(r.config.hooks.SessionEnd){let{outcome:a}=await Ls(r.config,"SessionEnd",{hook_event_name:"SessionEnd",cwd:process.cwd(),reason:"quit"},{cwd:process.cwd()});a.error&&p("hooks",`SessionEnd hook: ${a.error}`)}}catch{}await st.dispose();let o=k.getSessionStats().sessionId;Lt.close(k.getSessionStats().cost),wn(o),yn(o),k.dispose(),s.stop(),process.stdout.write("\x1B[0m"),process.exit(0)},Co=0,Ao=async(o=!1)=>{let r=Date.now();if(!o&&r-Co<600*1e3)return;Co=r;let a=d=>{if(process.env.HOWTOFIX_CHECKIN_DEBUG==="1")try{Il(`${P}/checkin-debug.log`,`${new Date().toISOString()} ${d}
|
|
34
|
-
`)}catch{}},l=async()=>{try{let d=new Set((await k.modelRuntime.getAvailable()).map(A=>A.provider).filter(A=>se(A))),y=ye.find(A=>d.has(A));if(a(`providers=${[...d].join(",")||"(none)"} target=${y??"(none)"}`),!y)return!1;let c=(await k.modelRuntime.getAuth(y))?.auth?.apiKey,m=c?.trim().match(/^\$\{?([A-Za-z_][A-Za-z0-9_]*)\}?$|^\{env:([A-Za-z_][A-Za-z0-9_]*)\}$/),b=A=>A?(process.env[A]??"").trim():"",g=m?b(m[1]??m[2])||void 0:c?.trim()||void 0;if(!g)for(let A of["HOWTOFIX_API_KEY","HOWTOFIX_VIP_API_KEY","HOWTOFIX_FREE_API_KEY"]){let R=b(A);if(R){g=R,a(`key dari fallback ${A}`);break}}if(a(`key=${g?`ada(${g.length})`:"(kosong)"}${m?" dari env":""}`),!g)return!1;let x=await Kn(g);if(a(`status ok=${x.ok} enabled=${x.enabled} claimed=${x.checkedInToday} msg=${x.message}`),!x.ok||!x.enabled||x.checkedInToday)return!0;let $=await Si(g);return a(`claim ok=${$.ok} awarded=${$.quotaAwarded} msg=${$.message}`),$.ok?(p("check-in",`daily check-in claimed: +${Un($.quotaAwarded)} credited to your howtofix.id account`),v()):$.blocked&&p("check-in",$.message),!0}catch(d){return a(`error ${d.message}`),!1}};await l()||(await new Promise(d=>setTimeout(d,4e3)),await l())},To=async o=>{let r=Lt.check(k.getSessionStats().cost);if(r!==void 0){G(`budget reached: $${r.spent.toFixed(4)} of $${r.limit.toFixed(2)} \u2014 raise it with --max-budget-usd, or start without the flag`);return}let a=k.isStreaming,l=`you-${Date.now()}`;i.items.push({id:l,kind:"user",title:"you",body:o,pending:a?!0:void 0}),a||(C("tally",void 0),Je.clear(),Ht.clear(),C("run","thinking"),u.beginRun()),v(),w.disableSubmit=!1;let d=Rs(o,e.cwd);jt=o,await Zi(),et=!0;let y=a?k.prompt(d,{streamingBehavior:"steer"}):k.prompt(d);et=!1,y.then(()=>Ao()).catch(c=>G(c instanceof Error?c.message:String(c)))},Yt=o=>{let r=o.trim();if(r){if(ee){let a=ee;ee=void 0,w.setText(""),a(r);return}if(w.setText(""),w.addToHistory(r),r.startsWith("!")){let a=r.slice(1).trim();if(!a)return;i.items.push({id:`sh-${Date.now()}`,kind:"tool",title:"$",body:a}),C("run","shell"),v(),k.executeBash(a,l=>{C("run",`shell \xB7 ${l.length} bytes`),v()}).then(l=>{let d=l.output.trim();i.items.push({id:`sh-out-${Date.now()}`,kind:l.exitCode===0?"result":"error",title:`exit ${l.exitCode??"?"}`,body:d||"(no output)"}),C("tally",void 0),v()}).catch(l=>G(l instanceof Error?l.message:String(l)));return}if(r.startsWith("/")){Fe(r);return}To(r)}};w.onSubmit=Yt;let Xt=0,Oe={cancel:null},Mo=0,nt=()=>{Mr().then(o=>{o.ok?w.insertTextAtCursor(o.text):p("paste",o.reason),v()}).catch(o=>{p("paste",`could not read the clipboard: ${o instanceof Error?o.message:String(o)}`),v()})};n=nt;let Ro=o=>hn(ke(P).rightClickPaste)&&o.type==="press"&&o.button==="right";s.addInputListener(o=>{if(be){if(Y(o,"escape"))return Wt(),{consume:!0};let a=Hi(),l=a.matches(o,"tui.select.up"),d=a.matches(o,"tui.select.down");if(l||d){let c=be.getTreeList().getSelectedNode()?.entry.id,m=Qi(),b=c===void 0?-1:m.indexOf(c);if(l?b===0:b===m.length-1)return v(),{consume:!0}}return be.handleInput(o),v(),{consume:!0}}if(Z&&H&&Y(o,"escape"))return te?(te=!1,p("workflow","panel keys off; the editor has the keyboard")):I.expanded?(I.expanded=!1,p("workflow","collapsed the drill-in")):(Qn(),p("workflow","panel unpinned; the run is still in the transcript")),_t(),v(),{consume:!0};if(re)return re.handleInput(o),v(),{consume:!0};if(Y(o,"escape")){if(Oe.cancel)return Oe.cancel(),p("connect","sign-in cancelled \u2014 run /connect again when you have a token"),v(),{consume:!0};if(k.isStreaming){qt=!0;let l=[...k.getSteeringMessages()].map(d=>d.trim()).filter(Boolean);if(l.length>0){let d=w.getText().trim();w.setText(d?`${l.join(`
|
|
35
|
-
`)}
|
|
36
|
-
${d}`:l.join(`
|
|
37
|
-
`));let y=new Set(l);for(let c of i.items)c.kind==="user"&&c.pending&&y.has(c.body.trim())&&(c.pending=void 0);p("queued",`${l.length} unread message${l.length===1?"":"s"} returned to the editor`)}return k.abort(),C("note","stopping"),v(),{consume:!0}}let a=Date.now();if(w.getText().length===0&&a-Xt<600)return Xt=0,co(),{consume:!0};Xt=a;return}if(Y(o,"ctrl+c")||Sr(o)){if(k.isStreaming)k.abort(),C("note","stopping"),v();else if(w.getText().length>0)w.setText(""),C("note","draft cleared; ctrl+c again quits"),v();else{let a=Date.now();a-Mo<2e3?_e():(Mo=a,C("note","press ctrl+c again to quit"),v())}return{consume:!0}}if(Y(o,"ctrl+d")&&w.getText().length===0)return _e(),{consume:!0};let r=Math.max(1,i.viewportHeight-1);if(Y(o,"pageUp"))return i.scrollOffset+=r,v(),{consume:!0};if(Y(o,"pageDown"))return i.scrollOffset=Math.max(0,i.scrollOffset-r),v(),{consume:!0};if(Y(o,"home"))return i.scrollOffset=Number.MAX_SAFE_INTEGER,v(),{consume:!0};if(Y(o,"end"))return i.scrollOffset=0,v(),{consume:!0};if(Y(o,"ctrl+v"))return nt(),{consume:!0};if(Y(o,"ctrl+l"))return i.scrollOffset=0,s.scrollToBottom(),v(),{consume:!0};if(Y(o,"ctrl+e")){let a=[...i.items].reverse().find(l=>(l.full?.length??0)>0);return a?(a.expanded=a.expanded!==!0,v(),{consume:!0}):(p("expand","nothing to expand in this transcript yet"),{consume:!0})}if(Y(o,"ctrl+o")&&!k.isStreaming)return i.items=[{id:"cleared",kind:"note",title:"bench",body:"screen cleared. session history is still stored."}],v(),{consume:!0};if(Y(o,"ctrl+t"))return Pe(oi(u.thinking)),{consume:!0};if(Y(o,"ctrl+shift+t"))return Pe(si(u.thinking)),{consume:!0};if(Y(o,Fi)&&Z&&H)return te=!te,p("workflow",te?"panel keys active; Esc gives the keyboard back":"panel keys off; the editor has the keyboard"),_t(),v(),{consume:!0};if(te&&Z&&H){let a=_i(o);if(a){let l=$n(H,Date.now());if(a==="stop")return L?(L(),L=null,p("workflow","stopping the run; in-flight agents resolve as null")):p("workflow","the run has already finished"),{consume:!0};if(a==="save"){let d=Di(Xi,ss);return p("workflow",d.ok?`saved ${d.path}`:d.reason),v(),{consume:!0}}return Object.assign(I,Oi(I,a,l)),_t(),v(),{consume:!0}}}});let Jt=o=>{let r=a=>{C("prompt",`API key for ${a}. Paste it, then press enter.`),v();let l=ee;ee=d=>{ee=l;let y=d.trim();if(!y){C("prompt",void 0),v();return}k.modelRuntime.setRuntimeApiKey(a,y).then(()=>k.modelRuntime.login(a,"api_key",{prompt:async()=>y,notify:()=>{}}).then(()=>p("login",`saved API key for ${a}`),c=>p("login",`key set for this session, but it could not be saved (${c instanceof Error?c.message:String(c)}); run /login again after restarting`)),c=>p("login",c instanceof Error?c.message:String(c)))}};if(o){r(o);return}k.modelRuntime.getAvailable().then(a=>{let l=[...new Set(a.map(d=>d.provider))].sort();if(l.length===0){p("login","no providers are configured; pass one explicitly, e.g. /login nrimo");return}_("Login",l.map(d=>({value:d,label:d})),r)},a=>p("login",a instanceof Error?a.message:String(a)))},Eo=async(o,r)=>{let a=le(P,"models.json"),l,d=!1;try{l=JSON.parse(Gn(a,"utf8"))}catch(W){if(!(W instanceof Error&&"code"in W&&W.code==="ENOENT"))return`could not read ${a}; the models were not added`;l={providers:{}},d=!0}(!l.providers||typeof l.providers!="object")&&(l.providers={});let y=l.providers[o];y||(y=ds(),l.providers[o]=y,d=!0);let c=Array.isArray(y.models)?y.models:[],m=hs(c,r),b=await us(P).catch(()=>({index:new Map})),g=await ws((await k.modelRuntime.getAuth(o))?.auth?.apiKey??""),x=ms(ps(c,r,b.index,g));y.models=x.models;try{Ui(P,{recursive:!0}),ie(a,`${JSON.stringify(l,null,2)}
|
|
38
|
-
`)}catch{return`could not write ${a}; the models were not added`}let $=!1;try{await k.modelRuntime.refresh(),$=!0}catch{$=!1}let A=x.changed>0?`, repaired ${x.changed}`:"",R=$?"":"; restart the CLI to see them all",U=d?` (created ${a})`:"";return m===0?`all ${r.length} models were already configured${A}${U}${R}`:`added ${m} model(s) to "${o}"${A}${U}${R}`},Le=(o,r)=>{(async()=>{if(!o){let g=await ks({onProgress:$=>{let A="";try{let U=le(P,".howtofix");Ui(U,{recursive:!0,mode:448});let W=le(U,"connect-url.txt"),B=$.kind==="browser"?[$.url]:[$.url,`code: ${$.code}`];qn(W,B.join(`
|
|
39
|
-
`)+`
|
|
40
|
-
`,{mode:384}),A=W}catch{A=""}let R=A?[` saved to ${A}`]:[];$.kind==="browser"?(He($.url),p("connect",["finish signing in to howtofix.id:"," a browser window is opening \u2014 approve the sign-in there",` if it did not open, visit ${$.url}`,...R].join(`
|
|
41
|
-
`))):(He($.url),p("connect",["finish signing in to howtofix.id:",` 1. go to ${$.url}`,` 2. enter the code: ${$.code}`," waiting\u2026",...R].join(`
|
|
42
|
-
`))),v()}});if(g.ok){C("prompt",void 0),ee=void 0,Le(g.token,g.credential);return}let x=await He(an);p("connect",[`browser sign-in: ${g.message}`,"","connect with a token instead:",` 1. ${x?"the keys page is opening in your browser":`open ${an}`}`," 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(`
|
|
43
|
-
`)),v();return}if(!fs(o)){p("connect","that does not look like a howtofix token; the Console issues tokens that start with sk-");return}C("note",`connecting to howtofix.id (${ln(o)})`),v();let a=await cn(o);if(!a.ok){C("note",void 0),p("connect",a.message),v();return}let l=await Eo("howtofix",a.models);await k.modelRuntime.setRuntimeApiKey("howtofix",o);let d;try{await k.modelRuntime.login("howtofix","api_key",{prompt:async()=>o,notify:()=>{}})}catch(g){d=`this sign-in could not be saved (${g instanceof Error?g.message:String(g)}); run /connect again after restarting`}r&&(Cs(P,r)?ge=r:d=`this sign-in renews itself, but the pair could not be saved to ${$s(P)}; it will expire in hours and need /connect again`);let y=!!k.model&&k.model?.provider!==void 0&&u.model!=="unknown",c,m;if(!y)try{let g=(await k.modelRuntime.getAvailable()).filter(A=>se(A.provider)),$=wt(g.map(A=>A.id)).slice(0,4);for(let A of $){if(!(await gs(A,o)).ok)continue;let U=g.find(W=>W.id===A);if(U){await k.setModel(U),u.model=U.id,he(),c=`${U.provider}/${U.id}`;break}}c||(m=$.length>0?`none of the first ${$.length} models answered (${$[0]} did not)`:"the account lists no chat model")}catch(g){m=g instanceof Error?g.message:String(g)}C("note",void 0);let b=await Ae(o);p("connect",[`connected ${ln(o)} \u2014 ${a.message}`,l,ot("howtofix",b),c?`using ${c} (change it with /model)`:`pick a model with /model, then send a prompt${m?` (auto-select failed: ${m})`:""}`,d].filter(g=>!!g).join(`
|
|
44
|
-
`)),v()})().catch(a=>{C("note",void 0),p("connect",a instanceof Error?a.message:String(a)),v()})},Po=o=>{(async()=>{let r=Wn(o);if(!r){p("connect",["that is not an account credential."," /connect <email>:<password>"," /connect <base64 of email:password>"].join(`
|
|
45
|
-
`)),v();return}C("note",`signing in as ${r.username}`),v();let{token:a}=await yi(ys,r.username,r.password,it),l=bi(P,r.username,r.password);C("note",void 0),p("connect",[`signed in as ${r.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(`
|
|
46
|
-
`)),v(),Le(a)})().catch(r=>{C("note",void 0),p("connect",r instanceof Error?r.message:String(r)),v()})},ot=(o,r)=>{if(!r.ok)return[`${o} account`,` ${r.message}`].join(`
|
|
47
|
-
`);if(r.unlimited)return[`${o} account`," quota no limit on this token"].join(`
|
|
48
|
-
`);if(r.limit===void 0||r.used===void 0){let a=[`${o} account`],l=d=>`${d.toFixed(2)} ${r.unit}`;return r.limit!==void 0&&a.push(` granted ${l(r.limit)}`),r.used!==void 0&&a.push(` spent ${l(r.used)}`),r.remaining!==void 0&&a.push(` remaining ${l(r.remaining)}`),a.join(`
|
|
49
|
-
`)}return pi(o,r.limit,r.used,r.unit).join(`
|
|
50
|
-
`)},Ne=()=>({mcpServers:Ns()}),ca=o=>{let r=Object.keys(o??{});return r.length===0?[]:r.map(a=>` mcp ${a} ${lt(o[a])}`)},da=o=>{let r=Jo(o.dir,o.manifest),a=o.manifest.skills.join(", ");return[o.manifest.description,` category ${o.manifest.category}`,` version ${o.manifest.version}`,` skills ${a}`,o.manifest.prompt?` prompt ${o.manifest.prompt}`:" prompt (none)",` size ${r} bytes of skill text`,` source ${o.source}`,...ca(o.manifest.mcp)].join(`
|
|
51
|
-
`)},Io=o=>{let r=[da(o),""];if(o.manifest.prompt){let a=le(o.dir,o.manifest.prompt);Et(a)&&r.push(`--- ${o.manifest.prompt} ---`,Gn(a,"utf8").trim(),"")}for(let a of o.manifest.skills){let l=le(o.dir,"skills",a,"SKILL.md");Et(l)&&r.push(`--- skills/${a}/SKILL.md ---`,Gn(l,"utf8").trim(),"")}return r.join(`
|
|
52
|
-
`)},Se=async()=>{await k.reload()},Zt=!1,_o=async o=>{if(Zt){p("preset","an install is already running; wait for it to finish");return}Zt=!0;try{let r;try{r=await o()}catch(c){G(`preset not installed: ${c instanceof Error?c.message:String(c)}`);return}if(!r.ok||!r.name){G(`preset not installed:
|
|
53
|
-
${r.problems.join(`
|
|
54
|
-
`)}`);return}await Se();let a=ne(e.cwd).entries.find(c=>c.manifest.name===r.name),l=a?.manifest.integrates||a?.manifest.mcp,d=l?`
|
|
55
|
-
integration disabled by default; run /preset enable ${r.name} when you want to use it`:await Oo(r.name);l&&a&&qn(le(a.dir,".disabled"),`installed
|
|
56
|
-
`);let y=r.modelInvocable===!1?`its skill ${r.skill} is invoke-only (disable-model-invocation): the model cannot choose it, run /skill:${r.skill} yourself`:"its skill is in the model's catalogue from the next message";p("preset",`installed ${r.name} into ${r.target}
|
|
57
|
-
${y}${d}`)}finally{Zt=!1}},st=new Ye({initial:Object.keys(Ne().mcpServers),apply:async(o,r)=>{if(await Se(),o.length>0||r.length>0){let a=[];o.length>0&&a.push(`connected ${o.join(", ")}`),r.length>0&&a.push(`stopped ${r.join(", ")}`),p(o.length>0?"mcp connected":"mcp stopped",a.join("; "))}},report:o=>G(o)}),rt=async()=>{let o=Object.keys(Ne().mcpServers);return await st.reconcile(o)},Oo=async o=>{let{entries:r}=ne(e.cwd),l=r.find(c=>c.manifest.name===o)?.manifest.mcp;if(!l||Object.keys(l).length===0)return"";let d=nn(l);if(d.problems.length>0)return`
|
|
58
|
-
MCP: ${d.problems.join("; ")}`;let y=[];if(d.added.length>0){let c=await rt(),m=d.added.filter(b=>c.added.includes(b));y.push(m.length>0?`MCP servers connected: ${m.join(", ")}`:`MCP servers added to mcp.json: ${d.added.join(", ")}`)}return d.skipped.length>0&&y.push(`MCP servers kept as they were (already configured): ${d.skipped.join(", ")}`),y.length>0?`
|
|
59
|
-
${y.join(`
|
|
60
|
-
`)}`:""},Lo=o=>_o(async()=>Qo(o,dt(e.cwd))),No=o=>{let r=o.sizeKb>=1024?`${(o.sizeKb/1024).toFixed(1)} MB`:`${o.sizeKb} KB`;return p("preset",[`downloading ${o.title}`,` from ${o.repo} @ ${o.sha.slice(0,7)}`,` skill ${o.skill}${o.modelInvocable===!1?" (invoke-only: the model cannot choose it)":""}`,` size ~${r} \xB7 ${o.license}`," checking the pinned commit and the contents the registry recorded\u2026"].join(`
|
|
61
|
-
`)),_o(()=>ns(o,dt(e.cwd)))},Qt=(o,r)=>{_(r,o.map(a=>({value:a.name,label:a.title,description:a.description})),a=>{let l=o.find(y=>y.name===a);if(!l)return;let d=l.sizeKb>=1024?`${(l.sizeKb/1024).toFixed(1)} MB`:`${l.sizeKb} KB`;_(l.title,[{value:"install",label:"Install",description:`download ~${d} 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"){No(l);return}if(y==="view"){p(`preset ${l.name}`,[`${l.description}`,"",`skill ${l.skill}`,`source ${l.repo} @ ${l.sha.slice(0,7)}`,`licence ${l.license}`,`size ~${d}`,`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(`
|
|
62
|
-
`));return}jo()})},()=>v())},Ce=(o,r)=>{_(r,o.map(a=>({value:a.manifest.name,label:a.manifest.title,description:a.manifest.skills.length>0?`${a.manifest.skills.join(", ")} \u2014 ${a.manifest.description}`:a.manifest.description})),a=>{let l=o.find(d=>d.manifest.name===a);l&&_(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"}],d=>{if(d==="install"){Lo(l.dir);return}if(d==="view"){p(`preset ${l.manifest.name}`,Io(l));return}Uo("")})},()=>v())},Fo=o=>o.filter(r=>r.manifest.integrates!==void 0),ua=()=>{let{entries:o}=ne(e.cwd),r=Fo(o);if(r.length===0){p("integrations","nothing installed that drives another application. /preset lists the rest.");return}Ce(r,"Integrations")},jo=()=>{let{entries:o}=ne(e.cwd),r=[{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"}],a=Fo(o).length;a>0&&r.push({value:"integrations",label:"Integrations",description:`${a} that drive another application, and need setup there first`}),_("Presets",r,l=>l==="mcp"?en():l==="integrations"?ua():fa())},en=()=>{let{entries:o,problems:r}=Ho();if(r.length>0&&p("mcp problems",r.join(`
|
|
63
|
-
`)),o.length===0){p("mcp catalogue","no servers in the catalogue. run /mcp to inspect the ones already configured.");return}let a=new Set(Object.keys(Ne().mcpServers)),l=new Map,d=[];for(let y of Bo(o)){let c=Go(o,y);l.set(y,()=>Do(c,y));let m=c.filter(b=>a.has(b.name)).length;d.push({value:y,label:y,description:`${c.map(b=>b.title).join(", ")}${m>0?` \xB7 ${m} configured`:""}`})}l.set("all-mcp",()=>Do(o,"All MCP servers")),d.push({value:"all-mcp",label:"All servers",description:`${o.length} available${a.size>0?`, ${a.size} already configured`:""}`}),_("MCP servers",d,y=>l.get(y)?.())},Do=(o,r)=>{let a=Ne().mcpServers;_(r,o.map(l=>{let d=a[l.name]!==void 0?"configured \xB7 ":"";return{value:l.name,label:l.title,description:`${d}${l.description}`}}),l=>{let d=qo(o,l);if(!d)return;let y=a[d.name]!==void 0,c=Vo(d),m=[d.description,"",`server ${d.name}`,`runs ${lt(ct(d))}`,...d.needs&&d.needs.length>0?[`needs ${d.needs.join(", ")}`,c.length>0?` ${c.join(", ")} ${c.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"]:[],...d.docs?[`docs ${d.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(`
|
|
64
|
-
`),b=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"}];_(d.title,b,g=>{if(g==="view"){p(`mcp ${d.name}`,m);return}if(g==="install"){let x=[];if(d.preset){let R=le(zo(),"mcp",d.preset.replace(/^mcp-/,""));if(Et(le(R,"preset.json"))){let U=Zo(R,dt(e.cwd));U.ok||x.push(...U.problems)}}let $=nn({[d.name]:ct(d)});if(x.push(...$.problems),x.length>0){G(`mcp not installed:
|
|
65
|
-
${x.join(`
|
|
66
|
-
`)}`);return}if($.skipped.length>0){p("mcp install",`${d.name} is already in mcp.json; it was left as it is.`);return}let A=c.length>0?`
|
|
67
|
-
${c.join(", ")} ${c.length===1?"is":"are"} not set in this shell \u2014 the value is read when the server connects, so export ${c.length===1?"it":"them"} and reload, or it will fail every call`:"";p("mcp installed",[`added ${d.name} to mcp.json${d.preset?" and installed its skill preset":""}`,` runs ${lt(ct(d))}`,` connecting now; /mcp shows its state and its tools${A}`].join(`
|
|
68
|
-
`)),rt().catch(R=>{G(`mcp installed but the session was not updated: ${R instanceof Error?R.message:String(R)}`)});return}if(g==="remove"){let x=at([d.name]);if(x.problems.length>0){G(`mcp not removed:
|
|
69
|
-
${x.problems.join(`
|
|
70
|
-
`)}`);return}rt().then($=>{p("mcp remove",$.removed.length>0?`removed ${$.removed.join(", ")} from mcp.json and stopped ${$.removed.length===1?"it":"them"}`:x.removed.length>0?`removed ${d.name} from mcp.json`:`${d.name} was not in mcp.json`)}).catch($=>{G(`mcp removed from config but the session was not updated: ${$ instanceof Error?$.message:String($)}`)});return}en()})},()=>en())},fa=()=>{let{entries:o,problems:r}=ne(e.cwd),{entries:a,problems:l}=ut();r.length>0&&p("preset problems",r.join(`
|
|
71
|
-
`)),l.length>0&&p("preset problems",l.join(`
|
|
72
|
-
`));let d=o.filter(m=>m.source==="installed"),y=new Map,c=[];d.length>0&&(y.set("installed",()=>Ce(d,"Installed presets")),c.push({value:"installed",label:"Installed",description:`${d.length} active`}));for(let m of Yo(o)){let b=Xo(o,m),g=sn(a,m);y.set(m,()=>g.length>0?Wo(b,m,g):Ce(b,m));let x=b.map($=>`${$.manifest.title} (${$.manifest.skills.join(", ")})`).join(", ");c.push({value:m,label:m,description:`${x}${g.length>0?` \xB7 ${g.length} more to download`:""}`})}for(let m of ts(a)){if(o.some(g=>g.manifest.category===m))continue;let b=sn(a,m);y.set(m,()=>Qt(b,m)),c.push({value:m,label:m,description:`${b.length} to download`})}if(y.set("all",()=>Ce(o,"All presets")),c.push({value:"all",label:"All presets",description:`${o.length} ready to install`}),a.length>0){y.set("hub",()=>Wo([],"Community presets",a));let m=new Set(a.map(b=>b.repo)).size;c.push({value:"hub",label:"Community",description:`${a.length} to download, from ${m} projects`})}_("Skill presets",c,m=>y.get(m)?.())},Wo=(o,r,a)=>{if(a.length===0){Ce(o,r);return}if(o.length===0){Qt(a,`${r} (download)`);return}_(r,[{value:"local",label:`Included (${o.length})`,description:"already on disk, no download"},{value:"hub",label:`Downloadable (${a.length})`,description:"fetched when installed"}],l=>l==="local"?Ce(o,r):Qt(a,r))},Uo=o=>{let[r,...a]=o.trim().split(/\s+/),l=a.join(" ").trim();if(!r){jo();return}if(r==="list"){let{entries:d}=ne(e.cwd),y=d.filter(c=>c.source==="installed");if(y.length===0){p("preset list","nothing installed. run /preset to browse the catalogue.");return}p("preset list",y.map(c=>`${c.manifest.name} ${c.manifest.version} [${on(c.dir)?"disabled":"active"}]
|
|
73
|
-
${c.manifest.description}
|
|
74
|
-
${c.dir}`).join(`
|
|
75
|
-
`));return}if(r==="show"){if(!l){p("preset show","usage: /preset show <name>");return}let{entries:d}=ne(e.cwd),y=d.find(g=>g.manifest.name===l);if(y){p(`preset ${l}`,Io(y));return}let{entries:c}=ut(),m=rn(c,l);if(!m){p("preset show",`no preset named "${l}". run /preset to list them.`);return}let b=m.sizeKb>=1024?`${(m.sizeKb/1024).toFixed(1)} MB`:`${m.sizeKb} KB`;p(`preset ${l}`,[m.description,"",`skill ${m.skill}`,`source ${m.repo} @ ${m.sha.slice(0,7)}`,`licence ${m.license}`,`size ~${b}`,`category ${m.category}`,"","not installed. install it from /preset, or: /preset add-hub "+m.name].join(`
|
|
76
|
-
`));return}if(r==="add"){if(!l){p("preset add","usage: /preset add <git-url | directory>");return}Lo(l);return}if(r==="add-hub"){if(!l){p("preset add-hub","usage: /preset add-hub <name> (see /preset for names)");return}let{entries:d}=ut(),y=rn(d,l);if(!y){p("preset add-hub",`"${l}" is not in the community registry. run /preset to browse it.`);return}No(y);return}if(r==="enable"||r==="disable"){if(!l){p(`preset ${r}`,`usage: /preset ${r} <name>`);return}let d=ne(e.cwd).entries.find(c=>c.manifest.name===l&&c.source==="installed");if(!d){p(`preset ${r}`,`no installed preset named "${l}"`);return}let y=le(d.dir,".disabled");if(r==="disable"){qn(y,`disabled
|
|
77
|
-
`);let c=d.manifest.mcp?at(Object.keys(d.manifest.mcp)):{removed:[],kept:[],problems:[]};rt().then(()=>Se()).then(()=>p("preset",`disabled ${l}${c.removed.length?`; stopped ${c.removed.join(", ")}`:""}`)).catch(m=>G(`preset disable failed: ${m instanceof Error?m.message:String(m)}`));return}_l(y,{force:!0}),Oo(l).then(c=>Se().then(()=>p("preset",`enabled ${l}${c}`))).catch(c=>G(`preset enable failed: ${c instanceof Error?c.message:String(c)}`));return}if(r==="remove"){if(!l){p("preset remove","usage: /preset remove <name>");return}let d=es(l,e.cwd);if(d.problems.length>0){p("preset remove",d.problems.join(`
|
|
78
|
-
`));return}let c=ne(e.cwd).entries.find($=>$.manifest.name===l),m=new Set;for(let $ of ne(e.cwd).entries)if($.manifest.name!==l)for(let A of Object.keys($.manifest.mcp??{}))m.add(A);let b=c?.manifest.mcp?at(Object.keys(c.manifest.mcp),m):{removed:[],kept:[],problems:[]},g=b.removed.length>0?`
|
|
79
|
-
MCP servers removed from mcp.json: ${b.removed.join(", ")}`:b.kept.length>0?`
|
|
80
|
-
MCP servers kept (still used by another preset): ${b.kept.join(", ")}`:"",x=b.problems.length>0?`
|
|
81
|
-
MCP: ${b.problems.join("; ")}`:"";Se().then(()=>{p("preset",`removed ${l}
|
|
82
|
-
${d.removed.join(`
|
|
83
|
-
`)}${g}${x}`)});return}p("preset",`unknown subcommand "${r}". try: list, show, add, add-hub, remove.`)},Fe=async o=>{let[r,...a]=o.slice(1).split(/\s+/),l=a.join(" ");if(r==="quit"||r==="exit"){_e();return}if(r==="help"){p("help",Vn(k).map(c=>`/${c.name} ${c.description??""}`).join(`
|
|
84
|
-
`));return}if(r==="trust"){let c=new Fl(P),m=c.get(e.cwd);if(l==="on"||l==="off"){let g=l==="on";c.set(e.cwd,g),p("trust",g?`trusted ${e.cwd}
|
|
85
|
-
its .hxf settings, SYSTEM.md and skills apply to the next session`:`no longer trusting ${e.cwd}
|
|
86
|
-
its .hxf settings, SYSTEM.md and skills are ignored`);return}let b=m===!0?"trusted":m===!1?"not trusted":"not decided (treated as not trusted)";p("trust",`${e.cwd}
|
|
87
|
-
${b}
|
|
88
|
-
|
|
89
|
-
/trust on trust this folder
|
|
90
|
-
/trust off stop trusting it`);return}if(r==="init"){let c=le(e.cwd,"AGENTS.md");if(Et(c)&&l!=="force"){p("init",`AGENTS.md already exists at ${c}. run /init force to overwrite.`);return}ie(c,Ko),p("init",`wrote ${c}; asking the agent to fill it in`),await k.prompt("Read AGENTS.md, then fill it in with the real build, test, and layout facts of this repo. Keep it short.");return}if(r==="login"){Jt(l);return}if(r==="connect"){let c=l.trim();if(c&&!c.startsWith("sk-")&&Wn(c)){Po(c);return}if(c){Le(c);return}let m=wi(P);if(m){Po(m.credential);return}Le(""),C("prompt","paste your howtofix.id token, then press enter"),v();let b=ee;Oe.cancel=()=>{Oe.cancel=null,ee=b,C("prompt",void 0)},ee=g=>{Oe.cancel=null,ee=b,C("prompt",void 0),Le(g.trim())};return}if(r==="sync"){let c=new Set((await k.modelRuntime.getAvailable()).map(R=>R.provider).filter(R=>se(R))),m=ye.find(R=>c.has(R));if(!m){p("sync","no howtofix.id account is connected; run /connect first");return}C("note",`re-syncing ${m} from howtofix.id`),v();let g=(await k.modelRuntime.getAuth(m))?.auth?.apiKey;if(!g){C("note",void 0),p("sync",`${m} has no usable key; run /connect to sign in again`),v();return}let x=await cn(g);if(!x.ok){C("note",void 0),p("sync",x.message),v();return}let $=await Eo(m,x.models),A=await Ae(g);C("note",void 0),p("sync",`${$}
|
|
91
|
-
${ot(m,A)}`),await k.modelRuntime.refresh(),v();return}if(r==="usage"){let c=new Set((await k.modelRuntime.getAvailable()).map(R=>R.provider).filter(R=>se(R))),m=ye.find(R=>c.has(R));if(!m){p("usage","no howtofix.id account is connected; run /connect first");return}C("note","asking howtofix.id for the account usage"),v();let g=(await k.modelRuntime.getAuth(m))?.auth?.apiKey;if(!g){C("note",void 0),p("usage",`${m} has no usable key; run /connect to sign in again`),v();return}let x=await Ae(g),$=await Kn(g);C("note",void 0);let A=$.ok&&$.enabled?$.checkedInToday?`check-in: claimed today (+${Un($.quotaToday)})`:"check-in: not claimed yet today (it claims itself on the next start)":"";p("usage",A?`${ot(m,x)}
|
|
92
|
-
${A}`:ot(m,x)),v();return}if(r==="logout"){let c=await k.modelRuntime.getAvailable(),m=[...new Set(c.map(b=>b.provider))].sort();if(m.length===0){p("logout","no providers are configured");return}_("Logout",m.map(b=>({value:b,label:b})),b=>{k.modelRuntime.logout(b).then(()=>p("logout",`logged out ${b}`),g=>p("logout",g instanceof Error?g.message:String(g)))});return}if(r==="providers"){let c=await k.modelRuntime.getAvailable(),m=[...new Set(c.map(b=>b.provider))].sort();m.sort((b,g)=>Number(se(g))-Number(se(b))),_("Providers",m.map(b=>({value:b,label:b})),b=>{let g=k.modelRuntime.getModels(b);if(g.length===0){Jt(b);return}_(b,g.map(x=>({value:x.id,label:x.id})),x=>{let $=g.find(A=>A.id===x);$&&k.setModel($,{persist:!0}).then(()=>{u.model=$.id,he(),p("providers",`${b}/${$.id}`)},()=>Jt(b))})});return}if(r==="name"){if(!l){p("name","usage: /name <session name>");return}k.setSessionName(l),p("name",`session name: ${l}`);return}if(r==="update"){C("note","checking for a newer release");try{await fo({current:it,install:!0})}finally{C("note",void 0)}return}if(r==="stats"){let c=k.getSessionStats(),m=k.getContextUsage(),b=$=>Number.isFinite($)?String($):";",g=Ar(k.sessionManager.getEntries()),x=g.hitRate===null?"cache hit rate unknown (no prompt billed yet)":`cache hit ${g.hitRate.toFixed(1)}% of ${g.cachedTokens+g.billedTokens} prompt tokens`;p("stats",[`session ${c.sessionId}`,c.sessionFile?`file ${c.sessionFile}`:"not persisted",`messages ${b(c.totalMessages)} (user ${b(c.userMessages)}, assistant ${b(c.assistantMessages)}, tools ${b(c.toolCalls)})`,`tokens in ${b(c.tokens.input)} out ${b(c.tokens.output)} cache ${b(c.tokens.cacheRead)}/${b(c.tokens.cacheWrite)}`,x,g.misses.length>0?`cache misses ${g.misses.length} (${b(g.missedTokens)} tokens re-billed) \u2014 last: ${Tr(g.misses[g.misses.length-1])}`:"cache misses none counted",`cost $${Number.isFinite(c.cost)?c.cost.toFixed(4):";"}`,m?`context ${m.percent===null||!Number.isFinite(m.percent)?"?":`${Math.round(m.percent)}%`} of ${m.contextWindow}`:"context unknown"].join(`
|
|
93
|
-
`));return}if(r==="diff"){let c=async $=>{try{let{stdout:A}=await zn("git",$,{cwd:e.cwd,encoding:"utf8"});return A.trim()}catch{return""}},m=await c(["diff","--stat"])+`
|
|
94
|
-
|
|
95
|
-
`+await c(["diff","--","."]),[b="",g=""]=m.split(`
|
|
96
|
-
|
|
97
|
-
`,2),x=ir(g);p("diff",[b.trim(),x].filter(Boolean).join(`
|
|
98
|
-
|
|
99
|
-
`)||"working tree clean");return}if(r==="copy"){let c=[...k.state.messages].reverse().find(g=>g.role==="assistant"),b=(Array.isArray(c?.content)?c.content:[]).filter(g=>g.type==="text").map(g=>g.text).join("");if(!b){p("copy","nothing to copy");return}try{await Nl(b),p("copy",`copied ${b.length} characters`)}catch(g){p("copy",g instanceof Error?g.message:String(g))}return}if(r==="export"){let c=i.items.filter(g=>g.body.trim().length>0);if(c.length===0){p("export","nothing to export yet; the transcript is empty");return}let m=Ll(e.cwd,l||`howtofix-session-${Date.now()}.md`),b=[`# ${tn} session`,"",`model ${u.model}`,""];for(let g of c)b.push(`## ${g.title||g.kind}`,"",g.body,"");try{ie(m,b.join(`
|
|
100
|
-
`))}catch(g){p("export",`could not write ${m}: ${g instanceof Error?g.message:String(g)}`);return}p("export",`wrote ${m}`);return}if(r==="agents"){let[c="",...m]=l.split(/\s+/).filter(Boolean),b=m.join(" ").trim();if(c&&b){p("agents",await er(c,b));return}p("agents",c?Qs(c):Zs());return}if(r==="new"){let c=await e.reopen({noSession:!1});await So(c),p("new","started a new session");return}if(r==="resume"){let c=await jl.list(e.cwd);if(c.length===0){p("resume","no saved sessions for this folder");return}_("Resume session",c.slice(0,30).map(m=>({value:m.path,label:m.name||`${m.id.slice(0,8)} ${m.firstMessage.slice(0,40)}`,description:`${m.modified.toISOString().slice(0,16)} ${m.messageCount} messages`})),m=>{e.reopen({sessionPath:m}).then(So,b=>G(b instanceof Error?b.message:String(b)))});return}if(r==="model"){let c=await k.modelRuntime.getAvailable(),m=c.filter($=>se($.provider)),b=cs(P),g=m.length>0?m:b.size>0?c.filter($=>b.has($.provider)):[];if(g.length===0){p("model","no model configured yet \u2014 run /connect to sign in first");return}let x=l?g.find($=>`${$.provider}/${$.id}`===l||$.id===l):void 0;if(!l){_("Select model",g.map($=>({value:`${$.provider}/${$.id}`,label:$.id,description:[Ci($),$.provider].filter(Boolean).join(" \xB7 ")})),$=>{let A=g.find(R=>`${R.provider}/${R.id}`===$);A&&k.setModel(A,{persist:!0}).then(()=>{u.model=A.id,he(),p("model",`model ${$}`)})});return}if(!x){p("model",`unknown model ${l}`);return}await k.setModel(x,{persist:!0}),u.model=x.id,he(),p("model",`model ${x.provider}/${x.id}`);return}if(r==="thinking"){if(!l){_("Thinking level",q.map(c=>({value:c,label:c})),c=>Pe(c));return}if(!q.includes(l)){p("thinking",`thinking: ${q.join(", ")}`);return}Pe(l);return}if(r==="rtk"){let c=ke(P).compressToolOutput;if(!l){p("rtk",`compress tool output: ${c?"on":"off"}
|
|
101
|
-
/rtk on | /rtk off`);return}let m=l.toLowerCase();if(m!=="on"&&m!=="off"){p("rtk","rtk: on | off");return}let b=m==="on";if(b===c){p("rtk",`already ${m}`);return}if(!De(P,"compressToolOutput",b)){p("rtk","could not write the setting");return}no(b),p("rtk",`compress tool output ${m}
|
|
102
|
-
long results are ${b?"summarised before the model reads them":"sent in full"}`);return}if(r==="compact"){try{await k.compact(l||void 0),p("compact","session compacted")}catch(c){p("compact",c instanceof Error?c.message:String(c))}return}if(r==="approval"){let c=m=>{Ps(m),p("approval",fn[m])};if(!l){_("Approval mode",mt.map(m=>({value:m,label:m,description:fn[m]})),m=>c(m));return}if(!mt.includes(l)){p("approval",`modes: ${mt.join(", ")}`);return}c(l);return}if(r==="settings"){let c=()=>mn()?"off \u2014 everything runs":"on \u2014 critical commands are refused",m=()=>{_("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"}],E=>{let J=E==="off",z=De(P,"skipPermissions",J);if(pn(J),u.skipPermissions=J,v(),!z){p("settings","changed for this session, but settings.json could not be written (is it valid JSON?)");return}p("settings",J?"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 ${c()}.`])},b=()=>{_("Thinking level",q.map(E=>({value:E,label:E,description:E===u.thinking?"current":void 0})),E=>Pe(E),void 0,!1,[`Currently ${u.thinking}.`])},g=()=>{_("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"}],E=>{let J=E!=="off",z=De(P,"autoUpdate",J);p("settings",z?`auto-update ${J?"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 ${Ms(`${P}/settings.json`)?"on":"off"}.`])},x=()=>{let E=Ue("status",e.cwd,k.getSessionStats().sessionId);_("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"}],J=>p("dcp",Ue(J,e.cwd,k.getSessionStats().sessionId)),void 0,!1,E.split(`
|
|
103
|
-
`).slice(0,2))},$=()=>{Fe("/model")},A=()=>{Fe("/proxy")},R=()=>{let E=ke(P).rightClickPaste,J=process.platform==="win32"?"off":"on";_("Right click",[{value:"auto",label:"auto",description:`follow the terminal (${J} 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"}],z=>{let je=Fs(P,z);p("settings",je?z==="auto"?`right click follows the terminal \u2014 ${hn("auto")?"the CLI pastes":"the terminal pastes"} here.`:`right click ${z==="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 ${E}.`])},U=()=>{let E=ke(P).agents,J=[1,2,3,4].map(z=>({value:String(z),label:String(z),description:z===1?"one child at a time":z===Ke()?"current \u2014 sized to this machine":`${z} children at once`}));_("Agent concurrency",[{value:"auto",label:"auto",description:`size it to the machine (now ${Ke()}, max ${Ys})`},...J],z=>{let je=z==="auto"?void 0:Number(z),pa=js(P,je);p("settings",pa?je===void 0?`agent concurrency follows the machine \u2014 ${Ke()} at a time.`:`agent concurrency set to ${je} \u2014 shared by task and workflow.`:"agent concurrency changed for this session, but settings.json could not be written (is it valid JSON?)"),v()},void 0,!1)},W=[{value:"permissions",label:"permissions",description:c()},{value:"thinking",label:"thinking",description:`${u.thinking} \u2014 how hard the model reasons`},{value:"model",label:"model",description:u.model},{value:"dcp",label:"context pruning",description:"fold stale ranges to save tokens"},{value:"proxy",label:"proxy",description:dn(P)??un()??"none \u2014 direct to the API"},{value:"rightclick",label:"right click",description:`paste: ${ke(P).rightClickPaste}`},{value:"agents",label:"agents",description:`${ke(P).agents??`auto (${Ke()})`} at once, shared by task and workflow`},{value:"autoupdate",label:"auto-update",description:"install a newer release on start"}];if(!l){_("Settings",W,E=>{E==="permissions"?m():E==="thinking"?b():E==="dcp"?x():E==="autoupdate"?g():E==="model"?$():E==="proxy"?A():E==="rightclick"?R():E==="agents"&&U()});return}let B=W.find(E=>E.value===l||E.label===l);if(B){B.value==="permissions"?m():B.value==="thinking"?b():B.value==="dcp"?x():B.value==="autoupdate"?g():B.value==="model"?$():B.value==="proxy"?A():B.value==="rightclick"?R():B.value==="agents"&&U();return}if(l==="on"||l==="off"){let E=l==="off",J=De(P,"skipPermissions",E);pn(E),u.skipPermissions=E,v(),p("settings",J?E?"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}p("settings",`settings: ${W.map(E=>E.value).join(", ")} | on, off (permission checks)
|
|
104
|
-
usage: /settings <name>, or /settings to choose`);return}if(r==="proxy"){let c=dn(P),m=un(),b=()=>c?`proxy: ${c} (set here, in settings.json)`:m?`proxy: ${m} (from the environment, not this file)`:"proxy: none \u2014 requests go straight to the API";if(!l){p("proxy",`${b()}
|
|
105
|
-
usage: /proxy <url> route requests through a proxy
|
|
106
|
-
/proxy off stop using one
|
|
107
|
-
/proxy env use HTTPS_PROXY / HTTP_PROXY / ALL_PROXY
|
|
108
|
-
Only traffic to the HowToFix API goes through it; a change applies on the next start.`);return}let g=l.trim();if(g==="off"||g==="none"){let R=ht(P,ft,""),U=pt(P),W=U.source==="env"?`the environment still sets one (${U.url})`:"requests go straight to the API";p("proxy",R?`proxy off \u2014 ${W} from the next message.`:"proxy changed for this session, but settings.json could not be written (is it valid JSON?)");return}if(g==="env"){let R=ht(P,ft,""),U=pt(P),W=U.source==="env"?U.url:void 0;p("proxy",R?W?`using the environment from the next message: ${W}`:"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=Ts(g);if(!x.ok){p("proxy",`not set: ${x.problem}`);return}if(!ht(P,ft,x.url)){p("proxy","settings.json could not be written (is it valid JSON?)");return}let A=pt(P);p("proxy",A.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(r==="tools"){let c=k.getActiveToolNames().sort();p("tools",c.length?c.join(`
|
|
109
|
-
`):"no tools enabled");return}if(r==="dcp"){p("dcp",Ue(l,e.cwd,k.getSessionStats().sessionId));return}if(r==="context"||r==="decompress"||r==="sweep"){p(r,Ue(`${r} ${l}`.trim(),e.cwd,k.getSessionStats().sessionId));return}if(r==="rewind"){co();return}if(r==="undo"){if(!await kn(e.cwd)){p("undo","not a git repository");return}let c=await sr(e.cwd);p("undo",c.ok?`undone: ${c.output}`:`undo failed: ${c.output}`),h(!0);return}if(r==="commit"){if(!kn(e.cwd)){p("commit","not a git repository");return}if(!await nr(e.cwd)){p("commit","nothing to commit");return}let c=l||`howtofix: session update ${new Date().toISOString().slice(0,16)}`,m=await or(e.cwd,c);p("commit",m.ok?m.output:`commit failed: ${m.output}`),h(!0);return}if(r==="review"){if(!(await rr(e.cwd)).trim()){p("review","no changes to review");return}Yt("Review the uncommitted changes. Report concrete issues with file evidence. Do not edit files.");return}if(r==="workflow"){if(l.trim()==="clear"){Qn(),p("workflow","cleared the pinned workflow panel");return}if(!H){p("workflow","no workflow run in this session yet");return}let c=$n(H,Date.now()),m=c[I.selectedPhase];p("workflow",[`panel ${Z?"pinned above the editor":"unpinned"}`,`phase ${I.selectedPhase+1}/${c.length}: ${m?.title??"(none)"}`,`filter: ${I.filter}${I.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(`
|
|
110
|
-
`));return}if(r==="plan"){if(Vs()||bt().state==="pending"){bn(Gs(bt())),p("plan","plan mode off; edits are allowed again");return}bn(Bs(bt())),p("plan",`plan mode armed \u2014 send your next prompt to start planning
|
|
111
|
-
plan file: ${qs()??"(unknown)"}`);return}if(r==="goal"){let c=l.trim();if(!c){p("goal",gn(gt()));return}let{goal:m,error:b}=Hs(gt(),"set",c,void 0,void 0);if(b){G(b);return}Ks(m),await k.sendCustomMessage({customType:Ws,content:c,display:!1,details:m}),p("goal",`goal set
|
|
112
|
-
${gn(m)}`);return}if(r==="session"){let c=k.model;p("session",c?`${c.provider}/${c.id}`:"no model");return}if(r==="skills"){p("skills",$r(k.resourceLoader.getSkills().skills));return}if(r==="preset"){Uo(l);return}if(r==="roblox"){let{RobloxConnect:c,readBridgeEndpoint:m,describeStatus:b,parseRobloxSubcommand:g}=await import("./chunk-LAHVHRCS.js"),x=g(l);if(x){let W=new c(m(P));try{if(x.sub==="status"){let B=await W.tunnel("status").catch(()=>{});p("roblox",b(await W.status(),B))}else if(x.sub==="login"){p("roblox","opening Roblox in your browser to sign in\u2026");let B=await W.login({onUrl:E=>p("roblox",`if the browser did not open, go to:
|
|
113
|
-
${E}`)});p("roblox",B.message)}else if(x.sub==="logout")await W.logout(),p("roblox","signed out of Roblox");else{let B=x.rest==="off"?"stop":x.rest==="on"||x.rest===""?"start":void 0;if(!B)p("roblox","usage: /roblox tunnel on | off");else{let E=await W.tunnel(B);p("roblox",E.message??"done")}}}catch(B){p("roblox",B instanceof Error?B.message:String(B))}return}let $=ne(e.cwd).entries.find(W=>W.manifest.name==="rotoolbox");if(!$||$.source!=="installed"){p("roblox","RoToolbox is not installed. Run /preset and install RoToolbox first.");return}let A=on($.dir),R=k.getActiveToolNames().filter(W=>/roblox[-_]studio/i.test(W)),U=R.length>0;p("roblox",A?`RoToolbox: disabled
|
|
114
|
-
Enable with /preset enable rotoolbox
|
|
115
|
-
The MCP server and manager stay stopped while disabled.`:["RoToolbox: active",`MCP server: ${U?`connected \u2014 ${R.length} tool${R.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(`
|
|
116
|
-
`));return}let d=kr(o,k.resourceLoader.getSkills().skills.map(c=>c.name));if(d){To(d);return}let y=k.extensionRunner.getCommand(r??"");if(y){try{await y.handler(l,k.extensionRunner.createCommandContext())}catch(c){G(c instanceof Error?c.message:String(c))}return}p("command",`/${r??""} is not available in this screen yet`)};Ds((o,r)=>{let{promise:a,resolve:l}=Promise.withResolvers();return _(o,r.map(d=>({value:d,label:d})),l,()=>l("cancelled")),a}),process.on("SIGTERM",_e),Cr(()=>{_e()}),t.setTitle(`${tn} ${it}`),ec(),s.start(),s.requestRender(!0),Ao(!0);{let{maybeShowWelcome:o}=await import("./chunk-OOJLL5GO.js");await o({cwd:e.cwd,note:e.note,signedIn:ge!==void 0,runSlash:r=>{Fe(r)},openExternal:r=>{He(r)}},_,p)}e.initialPrompt&&Yt(e.initialPrompt),await new Promise(()=>{})}var ee,tc=1e3/30,nc=45e3;export{Jn as Dock,Yn as Hud,Xn as PinnedBlock,Jl as approvalDetail,wt as orderModelsForDefault,Xl as pickerPanel,pu as runWorkbench,Vn as slashCommands,Zl as workflowPanel,Pt as workflowPanelFromRun,Zn as workflowRunOf};
|
package/dist/chunk-MOKUBKE7.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
var i=/no available channel for model\s+([^\s"',)\]]+)/i;function r(t){let e=t??"";if(e.trim())return i.exec(e)?.[1]}function a(t){let e=t??"";if(!e.trim())return;let n=r(e);if(n)return`the gateway has no live channel for ${n} right now \u2014 /model lists the models that answer; pick another.`;if(/\bmissing api key\b|\bauthenticationerror\b|\bauth\s*error\b/i.test(e))return"no key for this model yet \u2014 /connect signs you in and pulls the model list.";if(/\bunknown model\b/i.test(e))return"/connect pulls the current model list from the gateway.";if(/\bcode 11128\b|\billegal api invocation\b/i.test(e))return"the gateway refused the request shape (code 11128) \u2014 /connect re-syncs each model's compatibility flags.";if(/\binsufficient (?:balance|quota|credit)\b|\bexceeded your current quota\b|http\s*402/i.test(e))return"the account is out of credit \u2014 /usage shows what is left.";if(/\bserver error\b|http\s*5\d\d/i.test(e))return"the gateway's channel is failing, not the CLI \u2014 /model lists what your account can reach; pick another.";if(/\brate.?limit|\b429\b/i.test(e))return"the gateway is rate-limiting this token \u2014 wait a moment, then resend the prompt.";if(/\bupstream api error\b/i.test(e))return"the gateway refused the request \u2014 run /connect again to re-sync your models."}export{r as a,a as b};
|
package/dist/chunk-VLMQSD25.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{a,b}from"./chunk-MOKUBKE7.js";import"./chunk-WOT6VMZA.js";export{a as deadChannelModel,b as diagnoseGatewayFailure};
|