howtocode 0.7.64 → 0.7.66
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-IZEC6RRH.js → chunk-4EQD3OPC.js} +1 -1
- package/dist/{chunk-S3XJFLP4.js → chunk-BAB55K5H.js} +1 -1
- package/dist/{chunk-235M52T5.js → chunk-BZ6PO2P5.js} +1 -1
- package/dist/{chunk-TFAXSHWM.js → chunk-DG7OCYNY.js} +1 -1
- package/dist/{chunk-EERXPN2B.js → chunk-IYR7VCH4.js} +1 -1
- package/dist/{chunk-TPMW4JXS.js → chunk-JREL7M6J.js} +1 -1
- package/dist/{chunk-GYFZKOJV.js → chunk-JY72ELJM.js} +2 -2
- package/dist/{chunk-V262WPO6.js → chunk-OHCWPWJW.js} +1 -1
- package/dist/{chunk-NQ3G4X3F.js → chunk-TN22ZVV4.js} +1 -1
- package/dist/{chunk-4A5FL2OO.js → chunk-VGY6AHOB.js} +1 -1
- package/dist/{chunk-GNDRI3LT.js → chunk-XB6IDZUM.js} +1 -1
- package/dist/{chunk-O5MPUAA5.js → chunk-YVRSL6ZX.js} +1 -1
- package/dist/main-app.js +102 -0
- package/dist/main.js +8 -101
- package/package.json +1 -1
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{a as T}from"./chunk-UTYFLLSM.js";import{g as R,j as P}from"./chunk-O5MPUAA5.js";import{existsSync as z,readFileSync as ye,rmSync as xe}from"node:fs";import{join as ve}from"node:path";import{createHash as q,randomBytes as J}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 F,cpus as M,hostname as N,platform as v,userInfo as O}from"node:os";var te="howtocode-cli-hwid-v1";function x(e){try{let t=ee(e,"utf8").trim();return t.length>0?t:void 0}catch{return}}function $(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=v();if(e==="linux"){let t=x("/etc/machine-id");if(t)return{value:t,source:"machine-id",strong:!0};let r=x("/var/lib/dbus/machine-id");if(r)return{value:r,source:"dbus-machine-id",strong:!0};let o=x("/sys/class/dmi/id/product_uuid");return o?{value:o,source:"dmi-product-uuid",strong:!0}:void 0}if(e==="win32"){let r=$("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=$("ioreg",["-rd1","-c","IOPlatformExpertDevice"])?.match(/"IOPlatformUUID"\s*=\s*"([^"]+)"/);return r?.[1]?{value:r[1],source:"platform-uuid",strong:!0}:void 0}}function H(){let e=re(),t=e?.value??[N(),v(),F(),O().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 U(e){return[e.id,e.source,N(),v(),F(),O().username,String(M().length),M()[0]?.model??""]}var _="https://howtofix.id",se=300*1e3,G=3e3,K="/callback";function I(e){return e.toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function oe(){return I(J(32))}function ie(e){return I(q("sha256").update(e).digest())}function ae(){return I(J(16))}var ce="howtocode-cli-",ue="x-howtocode-client",le="cli";function L(e){let t=e??U(H());return ce+q("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:o}=r.address();e({port:o,close:()=>r.close(),waitForCode:(n,s)=>new Promise((i,a)=>{let c=(l,f)=>{let h=new URL(l.url??"/","http://127.0.0.1");if(h.pathname!==K){f.writeHead(404).end("not found");return}let y=(V,Z)=>f.writeHead(200,{"content-type":"text/html; charset=utf-8"}).end(`<!doctype html><meta charset="utf-8"><h2>${V}</h2><p>${Z}</p>`),S=h.searchParams.get("error")??"",E=h.searchParams.get("code")??"",Y=h.searchParams.get("state")??"";if(S){y("Sign-in was refused","You can close this tab."),u(new Error(`the browser reported: ${S}`));return}if(!E||Y!==n){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 HowToCode."),u(void 0,E)},u=(l,f)=>{r.off("request",c),s?.removeEventListener("abort",g),l?a(l):i(f)},g=()=>u(new Error("cancelled"));s?.addEventListener("abort",g,{once:!0}),r.on("request",c)})})})});function k(e,t){e.onProgress?.(t)}async function p(e,t,r,o){let n=await e(t,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(r),signal:o}),s={};try{s=await n.json()}catch{}let i=Number(n.headers?.get?.("retry-after"));return{status:n.status,body:s,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 j(...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 ge(e,t,r){let o=await e(t,{headers:de(),signal:r}),n={};try{n=await o.json()}catch{}let s=Number(o.headers?.get?.("retry-after"));return{status:o.status,body:n,retryAfterSeconds:Number.isFinite(s)&&s>0?s:void 0}}function A(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 o of r)if(typeof o=="string"&&o.trim().startsWith("sk-"))return o.trim()}function pe(e){let t=e.data,r=d(e.token,t?.token),o=d(e.refresh_token,t?.refresh_token),n=d(e.device_id,t?.device_id);if(!r||!o||!n)return;let s=j(e.access_expires_at,t?.access_expires_at),i=j(e.refresh_expires_at,t?.refresh_expires_at);return{accessToken:r,accessExpiresAt:s,refreshToken:o,deviceId:n,refreshExpiresAt:i}}function m(e,t){let r=e.message??e.error;return typeof r=="string"&&r.trim()?r.trim():t}async function He(e){let t=e.fetchImpl??fetch,r=(e.panelUrl??_).replace(/\/+$/,""),o=e.timeoutMs??se,n={...e,panel:r,fetchImpl:t,timeoutMs:o},s=await ke(n);if(s.ok||s.terminal)return s.result;let i=await he(n);if(i.ok||i.terminal)return i.result;let a=await we(n);return a.ok?a:{ok:!1,message:`${s.result.ok?"":s.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(),o;try{o=await(e.loopback??fe)();let n=`http://127.0.0.1:${o.port}${K}`,s=await p(e.fetchImpl,`${e.panel}/api/oauth/device/start`,{redirect_uri:n,code_challenge:ie(t),code_challenge_method:"S256",state:r},e.signal);if(s.status===404)return{ok:!1,terminal:!1,result:{ok:!1,message:"the panel has no loopback login endpoint"}};if(s.status>=400)return{ok:!1,terminal:!1,result:{ok:!1,message:m(s.body,`the panel refused the login (${s.status})`)}};let i=typeof s.body.authorize_url=="string"?s.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(o.waitForCode(r,e.signal),e.timeoutMs),c=await p(e.fetchImpl,`${e.panel}/api/oauth/device/token`,{flow_token:s.body.flow_token,code:a,code_verifier:t},e.signal);if(c.status>=400)return{ok:!1,terminal:!0,result:{ok:!1,message:m(c.body,`the panel refused the exchange (${c.status})`)}};let u=A(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(n){let s=n instanceof Error?n.message:String(n);return{ok:!1,terminal:s==="cancelled",result:{ok:!1,message:s}}}finally{o?.close()}}async function ke(e){let t=e.fingerprintId??L(),r=e.clientInfo??R(),o=P(t,r);try{let n=await p(e.fetchImpl,`${e.panel}/api/auth/cli/code`,{fingerprintId:t,clientInfo:r,...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 HowToCode CLI \u2014 update it with `npm install -g howtocode@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:m(n.body,`the panel refused the login (${n.status})`)}};let s=n.body.data??{},i=d(n.body.login_url,s.login_url),a=d(n.body.code,s.code)??(i?me(i):void 0),c=d(n.body.secret,s.secret);return!i||!a?{ok:!1,terminal:!1,result:{ok:!1,message:"the panel did not return a login URL"}}:c?(k(e,{kind:"browser",url:i}),await D(e,a,c)):(k(e,{kind:"browser",url:i}),await D(e,a,void 0))}catch(n){let s=n instanceof Error?n.message:String(n);return{ok:!1,terminal:s==="cancelled",result:{ok:!1,message:s}}}}async function D(e,t,r){let o=e.pollIntervalMs??G,n=Date.now()+e.timeoutMs;for(;Date.now()<n;){await w(o,e.signal);let s=new URLSearchParams(r?{code:t,secret:r}:{code:t});s.set("capability","device-refresh");let i=await ge(e.fetchImpl,`${e.panel}/api/auth/cli/status?${s}`,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=A(i.body);if(a)return{ok:!0,result:{ok:!0,token:a,credential:pe(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:m(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??G;try{let r=await p(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:m(r.body,`the panel refused the request (${r.status})`)};let o=typeof r.body.device_code=="string"?r.body.device_code:"",n=typeof r.body.user_code=="string"?r.body.user_code:"",s=typeof r.body.verification_uri=="string"?r.body.verification_uri:`${e.panel}/oauth/device`;if(!o||!n)return{ok:!1,message:"the panel did not return a code to show"};k(e,{kind:"code",code:n,url:s});let i=Date.now()+e.timeoutMs;for(;Date.now()<i;){await w(t,e.signal);let a=await p(e.fetchImpl,`${e.panel}/api/oauth/device/poll`,{device_code:o},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=A(a.body);if(u)return{ok:!0,token:u};if(a.status>=400)return{ok:!1,message:m(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,o)=>{let n=setTimeout(()=>o(new Error("the sign-in was not finished in time")),t);e.then(s=>{clearTimeout(n),r(s)},s=>{clearTimeout(n),o(s)})})}function w(e,t){return new Promise((r,o)=>{let n=setTimeout(r,e);t?.addEventListener("abort",()=>{clearTimeout(n),o(new Error("cancelled"))},{once:!0})})}function b(e){return ve(e,"cli-credentials.json")}var _e=300*1e3;function Ie(e,t=Date.now()){return e.accessToken?!Number.isFinite(e.accessExpiresAt)||e.accessExpiresAt<=0?!0:e.accessExpiresAt*1e3-_e>t:!1}function Le(e,t=Date.now()){return!e.refreshToken||!e.deviceId?!1:!Number.isFinite(e.refreshExpiresAt)||e.refreshExpiresAt<=0?!0:e.refreshExpiresAt*1e3>t}function Ge(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 o=r,n=typeof o.accessToken=="string"?o.accessToken.trim():"",s=typeof o.refreshToken=="string"?o.refreshToken.trim():"",i=typeof o.deviceId=="string"?o.deviceId.trim():"";if(!(!n||!s||!i))return{accessToken:n,accessExpiresAt:W(o.accessExpiresAt),refreshToken:s,deviceId:i,refreshExpiresAt:W(o.refreshExpiresAt)}}function Ae(e,t){try{return T(b(e),`${JSON.stringify(t,null,2)}
|
|
1
|
+
import{a as T}from"./chunk-UTYFLLSM.js";import{g as R,j as P}from"./chunk-YVRSL6ZX.js";import{existsSync as z,readFileSync as ye,rmSync as xe}from"node:fs";import{join as ve}from"node:path";import{createHash as q,randomBytes as J}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 F,cpus as M,hostname as N,platform as v,userInfo as O}from"node:os";var te="howtocode-cli-hwid-v1";function x(e){try{let t=ee(e,"utf8").trim();return t.length>0?t:void 0}catch{return}}function $(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=v();if(e==="linux"){let t=x("/etc/machine-id");if(t)return{value:t,source:"machine-id",strong:!0};let r=x("/var/lib/dbus/machine-id");if(r)return{value:r,source:"dbus-machine-id",strong:!0};let o=x("/sys/class/dmi/id/product_uuid");return o?{value:o,source:"dmi-product-uuid",strong:!0}:void 0}if(e==="win32"){let r=$("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=$("ioreg",["-rd1","-c","IOPlatformExpertDevice"])?.match(/"IOPlatformUUID"\s*=\s*"([^"]+)"/);return r?.[1]?{value:r[1],source:"platform-uuid",strong:!0}:void 0}}function H(){let e=re(),t=e?.value??[N(),v(),F(),O().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 U(e){return[e.id,e.source,N(),v(),F(),O().username,String(M().length),M()[0]?.model??""]}var _="https://howtofix.id",se=300*1e3,G=3e3,K="/callback";function I(e){return e.toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function oe(){return I(J(32))}function ie(e){return I(q("sha256").update(e).digest())}function ae(){return I(J(16))}var ce="howtocode-cli-",ue="x-howtocode-client",le="cli";function L(e){let t=e??U(H());return ce+q("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:o}=r.address();e({port:o,close:()=>r.close(),waitForCode:(n,s)=>new Promise((i,a)=>{let c=(l,f)=>{let h=new URL(l.url??"/","http://127.0.0.1");if(h.pathname!==K){f.writeHead(404).end("not found");return}let y=(V,Z)=>f.writeHead(200,{"content-type":"text/html; charset=utf-8"}).end(`<!doctype html><meta charset="utf-8"><h2>${V}</h2><p>${Z}</p>`),S=h.searchParams.get("error")??"",E=h.searchParams.get("code")??"",Y=h.searchParams.get("state")??"";if(S){y("Sign-in was refused","You can close this tab."),u(new Error(`the browser reported: ${S}`));return}if(!E||Y!==n){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 HowToCode."),u(void 0,E)},u=(l,f)=>{r.off("request",c),s?.removeEventListener("abort",g),l?a(l):i(f)},g=()=>u(new Error("cancelled"));s?.addEventListener("abort",g,{once:!0}),r.on("request",c)})})})});function k(e,t){e.onProgress?.(t)}async function p(e,t,r,o){let n=await e(t,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(r),signal:o}),s={};try{s=await n.json()}catch{}let i=Number(n.headers?.get?.("retry-after"));return{status:n.status,body:s,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 j(...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 ge(e,t,r){let o=await e(t,{headers:de(),signal:r}),n={};try{n=await o.json()}catch{}let s=Number(o.headers?.get?.("retry-after"));return{status:o.status,body:n,retryAfterSeconds:Number.isFinite(s)&&s>0?s:void 0}}function A(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 o of r)if(typeof o=="string"&&o.trim().startsWith("sk-"))return o.trim()}function pe(e){let t=e.data,r=d(e.token,t?.token),o=d(e.refresh_token,t?.refresh_token),n=d(e.device_id,t?.device_id);if(!r||!o||!n)return;let s=j(e.access_expires_at,t?.access_expires_at),i=j(e.refresh_expires_at,t?.refresh_expires_at);return{accessToken:r,accessExpiresAt:s,refreshToken:o,deviceId:n,refreshExpiresAt:i}}function m(e,t){let r=e.message??e.error;return typeof r=="string"&&r.trim()?r.trim():t}async function He(e){let t=e.fetchImpl??fetch,r=(e.panelUrl??_).replace(/\/+$/,""),o=e.timeoutMs??se,n={...e,panel:r,fetchImpl:t,timeoutMs:o},s=await ke(n);if(s.ok||s.terminal)return s.result;let i=await he(n);if(i.ok||i.terminal)return i.result;let a=await we(n);return a.ok?a:{ok:!1,message:`${s.result.ok?"":s.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(),o;try{o=await(e.loopback??fe)();let n=`http://127.0.0.1:${o.port}${K}`,s=await p(e.fetchImpl,`${e.panel}/api/oauth/device/start`,{redirect_uri:n,code_challenge:ie(t),code_challenge_method:"S256",state:r},e.signal);if(s.status===404)return{ok:!1,terminal:!1,result:{ok:!1,message:"the panel has no loopback login endpoint"}};if(s.status>=400)return{ok:!1,terminal:!1,result:{ok:!1,message:m(s.body,`the panel refused the login (${s.status})`)}};let i=typeof s.body.authorize_url=="string"?s.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(o.waitForCode(r,e.signal),e.timeoutMs),c=await p(e.fetchImpl,`${e.panel}/api/oauth/device/token`,{flow_token:s.body.flow_token,code:a,code_verifier:t},e.signal);if(c.status>=400)return{ok:!1,terminal:!0,result:{ok:!1,message:m(c.body,`the panel refused the exchange (${c.status})`)}};let u=A(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(n){let s=n instanceof Error?n.message:String(n);return{ok:!1,terminal:s==="cancelled",result:{ok:!1,message:s}}}finally{o?.close()}}async function ke(e){let t=e.fingerprintId??L(),r=e.clientInfo??R(),o=P(t,r);try{let n=await p(e.fetchImpl,`${e.panel}/api/auth/cli/code`,{fingerprintId:t,clientInfo:r,...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 HowToCode CLI \u2014 update it with `npm install -g howtocode@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:m(n.body,`the panel refused the login (${n.status})`)}};let s=n.body.data??{},i=d(n.body.login_url,s.login_url),a=d(n.body.code,s.code)??(i?me(i):void 0),c=d(n.body.secret,s.secret);return!i||!a?{ok:!1,terminal:!1,result:{ok:!1,message:"the panel did not return a login URL"}}:c?(k(e,{kind:"browser",url:i}),await D(e,a,c)):(k(e,{kind:"browser",url:i}),await D(e,a,void 0))}catch(n){let s=n instanceof Error?n.message:String(n);return{ok:!1,terminal:s==="cancelled",result:{ok:!1,message:s}}}}async function D(e,t,r){let o=e.pollIntervalMs??G,n=Date.now()+e.timeoutMs;for(;Date.now()<n;){await w(o,e.signal);let s=new URLSearchParams(r?{code:t,secret:r}:{code:t});s.set("capability","device-refresh");let i=await ge(e.fetchImpl,`${e.panel}/api/auth/cli/status?${s}`,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=A(i.body);if(a)return{ok:!0,result:{ok:!0,token:a,credential:pe(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:m(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??G;try{let r=await p(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:m(r.body,`the panel refused the request (${r.status})`)};let o=typeof r.body.device_code=="string"?r.body.device_code:"",n=typeof r.body.user_code=="string"?r.body.user_code:"",s=typeof r.body.verification_uri=="string"?r.body.verification_uri:`${e.panel}/oauth/device`;if(!o||!n)return{ok:!1,message:"the panel did not return a code to show"};k(e,{kind:"code",code:n,url:s});let i=Date.now()+e.timeoutMs;for(;Date.now()<i;){await w(t,e.signal);let a=await p(e.fetchImpl,`${e.panel}/api/oauth/device/poll`,{device_code:o},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=A(a.body);if(u)return{ok:!0,token:u};if(a.status>=400)return{ok:!1,message:m(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,o)=>{let n=setTimeout(()=>o(new Error("the sign-in was not finished in time")),t);e.then(s=>{clearTimeout(n),r(s)},s=>{clearTimeout(n),o(s)})})}function w(e,t){return new Promise((r,o)=>{let n=setTimeout(r,e);t?.addEventListener("abort",()=>{clearTimeout(n),o(new Error("cancelled"))},{once:!0})})}function b(e){return ve(e,"cli-credentials.json")}var _e=300*1e3;function Ie(e,t=Date.now()){return e.accessToken?!Number.isFinite(e.accessExpiresAt)||e.accessExpiresAt<=0?!0:e.accessExpiresAt*1e3-_e>t:!1}function Le(e,t=Date.now()){return!e.refreshToken||!e.deviceId?!1:!Number.isFinite(e.refreshExpiresAt)||e.refreshExpiresAt<=0?!0:e.refreshExpiresAt*1e3>t}function Ge(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 o=r,n=typeof o.accessToken=="string"?o.accessToken.trim():"",s=typeof o.refreshToken=="string"?o.refreshToken.trim():"",i=typeof o.deviceId=="string"?o.deviceId.trim():"";if(!(!n||!s||!i))return{accessToken:n,accessExpiresAt:W(o.accessExpiresAt),refreshToken:s,deviceId:i,refreshExpiresAt:W(o.refreshExpiresAt)}}function Ae(e,t){try{return T(b(e),`${JSON.stringify(t,null,2)}
|
|
2
2
|
`,{mode:384}),!0}catch{return!1}}function Ce(e){try{let t=b(e);z(t)&&xe(t,{force:!0})}catch{}}function W(e){return typeof e=="number"&&Number.isFinite(e)?e:0}async function Se(e,t){let r=(t?.panelUrl??_).replace(/\/+$/,""),o=t?.fetchImpl??fetch,n=t?.timeoutMs??15e3,s=new AbortController,i=setTimeout(()=>s.abort(),n);try{let a=await o(`${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:L()}),signal:s.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; 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??{},g=C(c.token,u.token),l=C(c.refresh_token,u.refresh_token),f=C(c.device_id,u.device_id)??e.deviceId;return!g||!l?{ok:!1,terminal:!1,message:"the panel did not return a renewed credential"}:{ok:!0,terminal:!1,credential:{accessToken:g,accessExpiresAt:B(c.access_expires_at,u.access_expires_at),refreshToken:l,deviceId:f,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(n/1e3)}s`:"could not reach the panel"}}finally{clearTimeout(i)}}function C(...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 Ke(e,t,r){let o=r?.now??Date.now();if(Ie(t,o)||!Le(t,o))return{credential:t,renewed:!1,terminal:!1};let n=await Se(t,r);if(!n.ok||!n.credential)return n.terminal&&Ce(e),{credential:t,renewed:!1,terminal:n.terminal,message:n.message};let s=Ae(e,n.credential);return{credential:n.credential,renewed:!0,terminal:!1,message:s?void 0:`the renewed sign-in could not be saved to ${b(e)}`}}export{H as a,_ as b,He as c,b as d,_e as e,Ie as f,Le as g,Ge as h,Ae as i,Ce as j,Se as k,Ke as l};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{b as j}from"./chunk-MCAAX33K.js";import{H as m,N as A}from"./chunk-ABDZXFNM.js";import"./chunk-UTYFLLSM.js";import{j as R}from"./chunk-MVVEYKN6.js";import{b as M,d as T,f as D}from"./chunk-TUXY64DT.js";import{a as I}from"./chunk-U3GZBLTM.js";import{a as b}from"./chunk-
|
|
1
|
+
import{b as j}from"./chunk-MCAAX33K.js";import{H as m,N as A}from"./chunk-ABDZXFNM.js";import"./chunk-UTYFLLSM.js";import{j as R}from"./chunk-MVVEYKN6.js";import{b as M,d as T,f as D}from"./chunk-TUXY64DT.js";import{a as I}from"./chunk-U3GZBLTM.js";import{a as b}from"./chunk-OHCWPWJW.js";import"./chunk-WOT6VMZA.js";import{spawnSync as J}from"node:child_process";import{existsSync as S,readdirSync as E,readFileSync as x,realpathSync as B,statSync as C,writeFileSync as F,unlinkSync as z}from"node:fs";import{dirname as N,join as p}from"node:path";var k=[22,19];async function W(t="https://api.howtofix.id/api/status"){let n=[],[s,e]=process.versions.node.split(".").map(Number),r=s>k[0]||s===k[0]&&e>=k[1];n.push({name:"node",ok:r,detail:`${process.versions.node} (needs >= ${k[0]}.${k[1]})`});let i=J("git",["--version"],{encoding:"utf8"});n.push({name:"git",ok:i.status===0,detail:i.status===0?i.stdout.trim():"not found on PATH"});let o=I();n.push({name:"sandbox",ok:!!o,detail:o??"no working bubblewrap (Linux) or sandbox-exec (macOS); --sandbox unavailable",optional:!0});let l=!1,c=m;try{let d=p(m,`.doctor-${process.pid}`);F(d,"ok"),z(d),l=!0}catch(d){c=`${m} is not writable: ${d instanceof Error?d.message:String(d)}`}n.push({name:"state dir",ok:l,detail:c});let a=p(m,"auth.json"),u="no auth.json \u2014 run `howtocode` and sign in",h=!1;try{let d=JSON.parse(x(a,"utf8")),f=Object.keys(d).length;h=f>0,u=h?`${f} provider credential${f===1?"":"s"}`:u}catch{}n.push({name:"auth",ok:h,detail:u,optional:!0});try{let d=Date.now(),f=await fetch(t,{signal:AbortSignal.timeout(5e3)});n.push({name:"gateway",ok:f.ok,detail:`${t} \u2192 ${f.status} in ${Date.now()-d}ms`,optional:!0})}catch(d){n.push({name:"gateway",ok:!1,detail:`${t} unreachable: ${d instanceof Error?d.message:String(d)}`,optional:!0})}return n.push(G()),n}function G(t=q()){if(t===void 0)return{name:"install",ok:!0,detail:"not an npm install; skipped",optional:!0};if(!S(t))return{name:"install",ok:!0,detail:"no bundled dependencies to check",optional:!0};let n=[],s=0;for(let e of["@netrodev"]){let r=p(t,e);if(S(r))for(let i of E(r)){let o=p(r,i,"dist");if(S(o))for(let l of _(o)){s+=1;let c=x(l,"utf8");for(let a of c.matchAll(/import\("(\.[^"]+)"\)/g)){let u=p(N(l),a[1]);S(u)||n.push(`${e}/${i}: ${u.slice(o.length+1)}`)}}}}return n.length>0?{name:"install",ok:!1,detail:`${n.length} module${n.length===1?"":"s"} missing (${n[0]}); reinstall with \`npm install -g howtocode@latest\``}:{name:"install",ok:!0,detail:`${s} lazy module${s===1?"":"s"} present`}}function q(){try{return p(N(N(B(process.argv[1]??""))),"node_modules")}catch{return}}function _(t,n=[]){let s;try{s=E(t)}catch{return n}for(let e of s){let r=p(t,e);if(e.endsWith(".lazy.js"))n.push(r);else if(!e.includes("."))try{C(r).isDirectory()&&_(r,n)}catch{}}return n}async function ie(){let t=await W(),n=Math.max(...t.map(e=>e.name.length));for(let e of t){let r=e.ok?"ok ":e.optional?"warn":"FAIL";console.log(` ${r} ${e.name.padEnd(n)} ${e.detail}`)}let s=t.filter(e=>!e.ok&&!e.optional);return s.length>0?(console.log(`
|
|
2
2
|
${s.length} problem${s.length===1?"":"s"} must be fixed before a session will work.`),1):0}function ce(t=m){let n=p(t,"models.json"),s;try{s=x(n,"utf8")}catch(a){return a.code==="ENOENT"?console.log(` no models.json at ${n} \u2014 run \`howtocode /connect\` to pull the catalogue`):j(b,"models",a),1}let e;try{e=JSON.parse(s)}catch(a){return console.error(`${b}: models: ${n} is not valid JSON (${a instanceof Error?a.message:String(a)})`),console.error(" fix the file, or delete it and run `howtocode /connect` to write a new one"),1}let r=e.providers??{},i=D(A),o=i?new Set(i.ids):void 0,l=new Set,c=0;for(let[a,u]of Object.entries(r)){let h=u.models??[],d=h.map(f=>f.id).filter(Boolean);for(let f of d)l.add(f);c+=d.length,console.log(` ${a} (${d.length})`);for(let f of h){if(!f.id)continue;let O=T(m).get(f.id),$=M(O??[]),g=$?` ${$}`:"",w=o&&!o.has(f.id)?" \u2014 not on this account":"";console.log(` ${f.id}${g}${w}`)}}if(o){let a=[...l].filter(u=>!o.has(u)).length;console.log(`
|
|
3
3
|
${[...o].filter(u=>l.has(u)).length} of ${c} listed model(s) this account can call${a>0?`; ${a} cannot (kept for other plans)`:""}`)}else console.log("\n which of these this account can call is unknown: run `howtocode` once to record it");return c===0?(console.log(" no models configured"),1):0}function v(t=15,n=m){let s=p(n,"sessions"),e;try{e=E(s)}catch{return[]}let r=[];for(let i of e){let o=p(s,i),l;try{l=E(o)}catch{continue}for(let c of l){if(!c.endsWith(".jsonl"))continue;let a=p(o,c);try{let u=C(a);r.push({file:a,project:i,modified:u.mtimeMs,bytes:u.size})}catch{}}}return r.sort((i,o)=>o.modified-i.modified).slice(0,t)}function le(t){let n=t.indexOf("--search");if(n>=0){let o=t[n+1]?.trim();if(!o)return console.error(`${b}: sessions: --search needs a word or phrase`),2;let l=K(o);if(l.length===0)return console.log(` no session mentions "${o}"`),0;for(let c of l){let a=new Date(c.row.modified).toISOString().replace("T"," ").slice(0,16),u=`${c.matches} hit${c.matches===1?"":"s"}`;console.log(` ${a} ${c.row.project} (${u})`),console.log(` ${c.row.file}`),console.log(` ${c.snippet}`)}return 0}let s=t.indexOf("--limit"),e=s>=0&&Number(t[s+1])||15,r=v(e);if(r.length===0)return console.log(` no saved sessions under ${p(m,"sessions")}`),t.includes("--export")?1:0;let i=t.indexOf("--export");if(i>=0){let o=Number(t[i+1]);if(!Number.isInteger(o)||o<1||o>r.length)return console.error(`${b}: sessions: --export needs a number from the list (1-${r.length})`),2;let l=r[o-1];try{console.log(Q(l.file))}catch(c){return j(b,"sessions",c),1}return 0}return r.forEach((o,l)=>{let c=new Date(o.modified).toISOString().replace("T"," ").slice(0,16),a=Math.round(o.bytes/1024);console.log(` ${String(l+1).padStart(2)} ${c} ${String(a).padStart(6)}k ${o.project}`),console.log(` ${o.file}`)}),0}function H(t){let n=t;try{let s=JSON.parse(t),e=s.message?.content??s.content;if(typeof e=="string"&&e.trim())n=e;else if(Array.isArray(e)){let r=e.map(i=>i&&typeof i=="object"&&"text"in i?String(i.text):"").join(" ");r.trim()&&(n=r)}}catch{}return R(X(n).replace(/\s+/g," ").trim())}function X(t){return t.replace(/\u001b\[[0-9;?]*[ -/]*[@-~]|\u001b\][^\u0007]*\u0007|\u001b[@-Z\\-_]/g,"")}function Z(t,n,s=80){let e=t.toLowerCase().indexOf(n);if(e<0)return t.slice(0,s*2).trim();let r=Math.max(0,e-s),i=Math.min(t.length,e+n.length+s);return`${r>0?"\u2026":""}${t.slice(r,i).trim()}${i<t.length?"\u2026":""}`}function K(t,n=10,s=m){let e=t.toLowerCase(),r=new RegExp(`\\b${e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\b`,"i"),i=[];for(let o of v(Number.MAX_SAFE_INTEGER,s)){let l;try{l=x(o.file,"utf8")}catch{continue}let c=0,a=0,u=0,h=0,d=!1,f="";for(let $ of l.split(`
|
|
4
4
|
`)){let g=$.toLowerCase(),w=g.indexOf(e);if(w<0)continue;let y=0;for(;w>=0;)y++,w=g.indexOf(e,w+e.length);c+=y;let L=g.includes('"role":"user"'),P=g.includes('"role":"toolresult"')||g.includes('"role":"tool"');L?a+=y:P?h+=y:u+=y,r.test($)&&(d=!0),f||(f=Z(H($),e))}if(c===0)continue;let O=(a>0?100:0)+(u>0?10:0)+Math.min(h,5)+(d?5:0)+Math.min(c,10)/100;i.push({row:o,matches:c,score:O,snippet:f})}return i.sort((o,l)=>l.score-o.score||l.row.modified-o.row.modified).slice(0,n)}function Q(t){let n=[`# Session ${t.split(/[\\/]/).pop()??t}`,""];for(let s of x(t,"utf8").split(`
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{$ as We,B as De,C as Ce,E as R,F as H,Fa as ot,H as B,I as Pe,Q as je,R as Ne,Ra as st,S as Me,T as Fe,U as Le,Ua as Q,V as Be,W as Ue,Wa as rt,Y as Ge,_ as Y,a as N,b as M,ba as He,c as ge,ca as qe,d as he,da as ze,e as we,ea as V,f as be,fa as Ze,g as A,ga as Ke,i as ye,j as ke,ja as Xe,k as Se,l as _e,la as Ye,m as X,ma as q,na as Ve,o as Te,oa as Je,p as Ee,q as $e,qa as J,r as ve,s as Ae,t as x,u as Re,ua as Qe,va as et,w as Oe,x as W,xa as tt,y as Ie,ya as nt}from"./chunk-RU6VPYMJ.js";import{b as xe}from"./chunk-27TRKD65.js";import{c as ue}from"./chunk-
|
|
1
|
+
import{$ as We,B as De,C as Ce,E as R,F as H,Fa as ot,H as B,I as Pe,Q as je,R as Ne,Ra as st,S as Me,T as Fe,U as Le,Ua as Q,V as Be,W as Ue,Wa as rt,Y as Ge,_ as Y,a as N,b as M,ba as He,c as ge,ca as qe,d as he,da as ze,e as we,ea as V,f as be,fa as Ze,g as A,ga as Ke,i as ye,j as ke,ja as Xe,k as Se,l as _e,la as Ye,m as X,ma as q,na as Ve,o as Te,oa as Je,p as Ee,q as $e,qa as J,r as ve,s as Ae,t as x,u as Re,ua as Qe,va as et,w as Oe,x as W,xa as tt,y as Ie,ya as nt}from"./chunk-RU6VPYMJ.js";import{b as xe}from"./chunk-27TRKD65.js";import{c as ue}from"./chunk-TN22ZVV4.js";import{h as pe,l as fe}from"./chunk-4EQD3OPC.js";import{t as me}from"./chunk-SVONBXW3.js";import"./chunk-7LA2AMZB.js";import{H as S,K as de,v as ce,w as le}from"./chunk-ABDZXFNM.js";import"./chunk-UTYFLLSM.js";import"./chunk-MVVEYKN6.js";import"./chunk-YVRSL6ZX.js";import{b as G,c as ie,d as ae}from"./chunk-OHCWPWJW.js";import"./chunk-WOT6VMZA.js";import{join as Nt}from"node:path";import{hostname as io}from"node:os";import{createAgentSession as ao,createCodemodeExtension as co,createMcpExtension as lo,createToolSearchExtension as uo,DefaultResourceLoader as po,ProjectTrustStore as fo,SessionManager as Z,SettingsManager as mo}from"@netrodev/hxf-coding-agent";import{existsSync as Ft,readFileSync as Lt}from"node:fs";import{join as Bt}from"node:path";var it=Bt(S,"APPEND_SYSTEM.md"),Ut=["<non-interactive>","This run has no user attached: it was started with --print, and there is nobody to answer a question. Anything that stops and waits for a reply \u2014 `ask`, a confirmation, a skill that resolves a mode by asking which mode to use \u2014 will simply end the run with the task unfinished.","So do not ask. Where an instruction tells you to ask the user and wait, take the default it describes and continue, and say which default you took and why in your final answer. The user reads that answer; they cannot answer mid-run.","Where a skill offers a choice of modes, prefer the one that applies the rules while you work over the one that audits afterwards: this is the mode for building something now, and the audit mode can still be run later by the same person who reads your answer.","</non-interactive>"].join(`
|
|
2
2
|
`),Gt=16*1024;function Wt(e){try{if(!Ft(e))return;let t=Lt(e,"utf8").trim();return!t||Buffer.byteLength(t,"utf8")>Gt?void 0:t}catch{return}}function at(e,t){let s=[t?e:`${e}
|
|
3
3
|
|
|
4
4
|
${Ut}`],n=Wt(it);return n&&s.push(`# Standing instructions from ${it}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{j as a}from"./chunk-MVVEYKN6.js";import{b as r}from"./chunk-
|
|
1
|
+
import{j as a}from"./chunk-MVVEYKN6.js";import{b as r}from"./chunk-OHCWPWJW.js";import"./chunk-WOT6VMZA.js";function c(e){return{prompt:s=>e.session.prompt(s),abort:()=>e.session.abort(),subscribe:s=>e.session.subscribe(n=>s(n)),getLastAssistantText:()=>a(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 g(e,s){let{openSession:n}=await import("./chunk-BZ6PO2P5.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-TOV557ET.js");await t({input:process.stdin,output:process.stdout,version:r,createAgent:async u=>c(await i(u))});return}let{runRpc:p}=await import("./chunk-QOYTPACU.js"),{createJsonEventEncoder:d}=await import("./chunk-MCDEIIEN.js"),o=await i(s.cwd),m=d();await p({input:process.stdin,output:process.stdout,agent:c(o),encodeEvent:t=>m.line(t),state:()=>({sessionId:o.session.sessionId,model:o.modelLabel,cwd:s.cwd})})}export{c as agentFromSession,g as serveProtocol};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{b as c,d as l}from"./chunk-27TRKD65.js";import{H as s}from"./chunk-ABDZXFNM.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{H as s}from"./chunk-ABDZXFNM.js";import"./chunk-UTYFLLSM.js";import{a as i,b as r}from"./chunk-OHCWPWJW.js";import"./chunk-WOT6VMZA.js";var d=[["/connect","sign in to howtofix.id: approve it in your browser"],["/model","choose which model answers"],["/help","list every command"],["/quit","leave"]],u=[" \u2588\u2588\u2557 \u2588\u2588\u2557\u2588\u2588\u2557 \u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557"," \u2588\u2588\u2551 \u2588\u2588\u2551\u255A\u2588\u2588\u2557\u2588\u2588\u2554\u255D\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D"," \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551 \u255A\u2588\u2588\u2588\u2554\u255D \u2588\u2588\u2588\u2588\u2588\u2557 "," \u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2551 \u2588\u2588\u2554\u2588\u2588\u2557 \u2588\u2588\u2554\u2550\u2550\u255D "," \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2554\u255D \u2588\u2588\u2557\u2588\u2588\u2551 "," \u255A\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u255D "],g=[" _ _ _____ ","| | | | __ __ | ___|","| |_| | \\ \\/ / | |_ ","| _ | > < | _| ","|_| |_| /_/\\_\\ |_| "];function m(){if(process.platform==="win32")return!1;let e=(process.env.LC_ALL||process.env.LC_CTYPE||process.env.LANG||"").toLowerCase();return e===""||e==="c"||e==="posix"||!e.includes("utf-8")&&!e.includes("utf8")?!1:!/ja|ko|zh|_kr|_jp|_cn|_tw|_hk/.test(e)}function h(){return m()?u:g}var _="https://howtofix.id/cli";function p(e){let n=process.env.HOME??"",t=n!==""&&e.startsWith(n)?`~${e.slice(n.length)}`:e,o=t.split("/").filter(Boolean);return o.length>3?`\u2026/${o.slice(-2).join("/")}`:t}function f(e){let n=e.signedIn?d.filter(([t])=>t!=="/connect"):d;return[...h(),"",`${i} ${r} \u2014 a terminal coding agent. Describe the change you want and it reads, edits and runs the code in front of you.`,"",` working in ${p(e.cwd)}`,...e.note?[` session ${e.note}`]:[],"",...e.signedIn?[" already signed in to howtofix.id",""]:[],...n.map(([t,o])=>` ${t.padEnd(11)}${o}`),"",' Or just start typing. Every message goes to the model; anything beginning with "/" stays local.'].join(`
|
|
2
2
|
`)}function v(){return[{value:"connect",label:"Sign in to howtofix.id",description:"approve the sign-in in your browser"},{value:"ready",label:"I have a key \u2014 just give me the prompt",description:"drops you at the prompt; run /connect whenever you like"},{value:"release",label:"What's in this release",description:`opens the ${r} notes in your browser`}]}async function E(e,n,t){c(s).welcomeSeen||(l(s),t(`welcome to ${i}`,f(e)),!e.signedIn&&await new Promise(o=>{n("First run \u2014 how do you want to begin?",v(),a=>{a==="connect"&&e.runSlash("/connect"),a==="release"&&e.openExternal(_),o()},()=>o())}))}export{E as maybeShowWelcome};
|
|
@@ -1 +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-YVRSL6ZX.js";import"./chunk-OHCWPWJW.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,4 +1,4 @@
|
|
|
1
|
-
import{$a as us,A as _o,Aa as zo,Ba as Yo,Ca as Jo,D as Mt,Da as Xo,E as Lo,Ea as Zo,G as Oo,Ga as de,Ha as E,Ia as J,J as No,Ja as A,K as Fo,Ka as Qo,L as Rt,La as es,M as jo,Ma as ts,N as Do,Na as ns,O as Wo,Oa as Kn,P as Dn,Pa as rs,Qa as is,Sa as Gn,Ta as os,Va as ss,X as Wn,Xa as as,Ya as ls,Z as Un,Za as cs,_a as ds,aa as Qe,ab as fs,bb as ms,c as So,e as Co,g as Ao,h as To,ha as Uo,ia as et,ka as It,n as Mo,oa as Bo,pa as Ko,ra as Go,sa as Ho,ta as Vo,v as Ro,wa as qo,x as Io,z as jn,za as Bn}from"./chunk-RU6VPYMJ.js";import{b as ps,c as gs}from"./chunk-3YSNDQVR.js";import{b as Ee,c as Ze,e as Eo,f as Et,g as Po,h as Pt}from"./chunk-27TRKD65.js";import{A as io,B as St,C as oo,b as Rn,c as ye,d as zi,e as Yi,h as Ji,n as In,o as Xi,q as oe,s as Zi,t as Ie,v as Qi,w as eo,x as to,y as no,z as ro}from"./chunk-
|
|
1
|
+
import{$a as us,A as _o,Aa as zo,Ba as Yo,Ca as Jo,D as Mt,Da as Xo,E as Lo,Ea as Zo,G as Oo,Ga as de,Ha as E,Ia as J,J as No,Ja as A,K as Fo,Ka as Qo,L as Rt,La as es,M as jo,Ma as ts,N as Do,Na as ns,O as Wo,Oa as Kn,P as Dn,Pa as rs,Qa as is,Sa as Gn,Ta as os,Va as ss,X as Wn,Xa as as,Ya as ls,Z as Un,Za as cs,_a as ds,aa as Qe,ab as fs,bb as ms,c as So,e as Co,g as Ao,h as To,ha as Uo,ia as et,ka as It,n as Mo,oa as Bo,pa as Ko,ra as Go,sa as Ho,ta as Vo,v as Ro,wa as qo,x as Io,z as jn,za as Bn}from"./chunk-RU6VPYMJ.js";import{b as ps,c as gs}from"./chunk-3YSNDQVR.js";import{b as Ee,c as Ze,e as Eo,f as Et,g as Po,h as Pt}from"./chunk-27TRKD65.js";import{A as io,B as St,C as oo,b as Rn,c as ye,d as zi,e as Yi,h as Ji,n as In,o as Xi,q as oe,s as Zi,t as Ie,v as Qi,w as eo,x as to,y as no,z as ro}from"./chunk-TN22ZVV4.js";import{a as so,b as ao,c as lo,d as co,f as uo,g as fo,h as mo,i as po,l as go}from"./chunk-4EQD3OPC.js";import{a as Ct,b as _n,c as Ln,d as ho,e as At}from"./chunk-3FYCFLNK.js";import{u as bo}from"./chunk-SDO33XPR.js";import{a as wo}from"./chunk-ORJ2QZBG.js";import{a as yo,c as Tt,d as On,j as ko,k as $o,l as vo,n as Nn,o as Fn,p as xo}from"./chunk-SVONBXW3.js";import{a as Pn,b as Mn,c as Di,d as Wi}from"./chunk-EZNNALD3.js";import{b as xt}from"./chunk-7LA2AMZB.js";import{A as Li,B as $t,C as vt,D as Oi,E as Sn,F as Cn,G as Ni,H as R,M as Xe,N as An,O as Fi,Q as ji,c as vn,d as wt,g as yt,i as xi,j as Si,k as Ci,l as Ai,m as kt,n as Ti,o as xn,p as Ei,s as se,t as Pi,u as Mi,x as Ri,y as Ii,z as _i}from"./chunk-ABDZXFNM.js";import{a as ie}from"./chunk-UTYFLLSM.js";import{j as Tn,k as En}from"./chunk-MVVEYKN6.js";import{b as Ui,c as Bi,d as Ki,e as Gi,f as Hi}from"./chunk-TUXY64DT.js";import{h as Vi,i as qi}from"./chunk-YVRSL6ZX.js";import{a as $n,b as bt,e as vi}from"./chunk-OHCWPWJW.js";import"./chunk-WOT6VMZA.js";import{execFile as ud}from"node:child_process";import{promisify as fd}from"node:util";import{appendFileSync as md,existsSync as Vt,mkdirSync as yr,readFileSync as qt,rmSync as pd,statSync as za,writeFileSync as kr}from"node:fs";import{basename as gd,dirname as hd,join as me,resolve as bd}from"node:path";function hs(e){if(e==="")return!0;let t=/^\x1b\[(\d+);(\d+)u$/.exec(e);if(t&&Number(t[1])===99&&(Number(t[2])&5)!==0)return!0;let n=/^\x1b\[27;(\d+);(\d+)~$/.exec(e);return!!(n&&Number(n[2])===99&&(Number(n[1])&5)!==0)}function bs(e){let t=!1;process.on("SIGINT",()=>{t||(t=!0,e())})}function Cl(e){if(!e||typeof e!="object")return;let t=e;if(!(typeof t.input!="number"&&typeof t.cacheRead!="number"&&typeof t.cacheWrite!="number"))return t}function Al(e){let t=e?.input??0,n=e?.cacheRead??0,i=e?.cacheWrite??0;return{input:t,cacheRead:n,cacheWrite:i,prompt:t+n+i}}function Tl(e){if(typeof e!="string")return null;let t=Date.parse(e);return Number.isNaN(t)?null:t}function El(e){if(!e||typeof e!="object")return;let t=e,i=(t.message&&typeof t.message=="object"?t.message:void 0)??t,o=Cl(i.usage);if(!o)return;let u=typeof i.provider=="string"?i.provider:"",a=typeof i.model=="string"?i.model:"";return{usage:o,model:[u,a].filter(Boolean).join("/")}}function ws(e){let t=0,n=0,i=[],o=0,u=null;for(let g of e){let b=El(g);if(!b)continue;let{input:k,cacheRead:C,cacheWrite:_,prompt:O}=Al(b.usage);if(O===0)continue;t+=C,n+=k+_;let F=Tl(g.timestamp),W=u,G=W?W.at:null;if(W!==null&&C===0&&k>=1e3){let Q=F!==null&&G!==null?Math.max(0,F-G):0;i.push({missedTokens:k,idleMs:Q,modelChanged:b.model!==""&&W.model!==""&&b.model!==W.model}),o+=k}u={prompt:O,at:F??G??null,model:b.model}}let a=t+n;return{cachedTokens:t,billedTokens:n,hitRate:a>0?t/a*100:null,misses:i,missedTokens:o}}function ys(e){return e.modelChanged?"model changed, so its cache had to be built":e.idleMs>=3e5?`cache expired after ${Math.round(e.idleMs/1e3)}s idle`:e.idleMs>0?"prompt changed too early in the prefix to hit":"reason not recorded"}import{copyToClipboard as wd,ProjectTrustStore as yd,SessionManager as kd}from"@netrodev/hxf-coding-agent";import{CombinedAutocompleteProvider as Ya,Container as $d,Editor as vd,matchesKey as q,ProcessTerminal as xd,ScrollView as Sd,KeybindingsManager as Qa,setKeybindings as el,isKeyRelease as Cd,parseColor as Yt,TUI_KEYBINDINGS as tl,SelectList as Ad,TuiAltScreen as Td,truncateToWidth as We,VStack as Ed,visibleWidth as Sr,wrapTextWithAnsi as nl}from"@netrodev/hxf-tui";import{spawn as Pl}from"node:child_process";function Ml(e,t,n=2e3){return new Promise(i=>{let o=!1,u,a=k=>{o||(o=!0,u!==void 0&&clearTimeout(u),i(k))},g;try{g=Pl(e,[...t],{stdio:["ignore","pipe","ignore"]})}catch{a({ok:!1,stdout:""});return}u=setTimeout(()=>{g.kill("SIGKILL"),a({ok:!1,stdout:""})},n);let b=[];g.stdout?.on("data",k=>b.push(k)),g.on("error",()=>a({ok:!1,stdout:""})),g.on("close",k=>{a({ok:k===0,stdout:Buffer.concat(b).toString("utf8")})})})}function Hn(){return process.env.XDG_SESSION_TYPE==="wayland"||(process.env.WAYLAND_DISPLAY?.length??0)>0}async function Rl(){let e=[];process.platform==="darwin"?e.push({command:"pbpaste",args:[]}):process.platform==="win32"?e.push({command:"powershell.exe",args:["-NoProfile","-Command","Get-Clipboard -Raw"]}):(Hn()&&(e.push({command:"wl-paste",args:["--no-newline","--type","text/plain;charset=utf-8"]}),e.push({command:"wl-paste",args:["--no-newline","--type","text/plain"]}),e.push({command:"wl-paste",args:["--no-newline"]})),((process.env.DISPLAY?.length??0)>0||!Hn())&&(e.push({command:"xclip",args:["-selection","clipboard","-o"]}),e.push({command:"xsel",args:["--clipboard","--output"]})),e.push({command:"termux-clipboard-get",args:[]}));for(let t of e){let n=await Ml(t.command,t.args);if(n.ok&&n.stdout.length>0)return n.stdout}}async function ks(){let e;try{let{getNativeClipboard:i}=await import("@netrodev/hxf-tui");e=i()}catch{e=void 0}if(e)try{let i=await e.getText();if(typeof i=="string"&&i.length>0)return{ok:!0,text:i}}catch{}let t=await Rl();return t!==void 0?{ok:!0,text:t}:{ok:!1,reason:`no clipboard tool could read it \u2014 ${Hn()?"install wl-clipboard (wl-paste)":process.platform==="darwin"?"pbpaste should be present on macOS":process.platform==="win32"?"Get-Clipboard should be present on Windows":"install xclip or xsel, or run under a display"}`}}import{spawn as Il}from"node:child_process";import{mkdirSync as _l,writeFileSync as Ll}from"node:fs";import{join as Ol}from"node:path";import{getNativeClipboard as Nl}from"@netrodev/hxf-tui";async function _e(e,t,n=4e3){let{promise:i,resolve:o}=Promise.withResolvers(),u=!1,a,g=C=>{u||(u=!0,clearTimeout(a),o(C))},b;try{b=Il(e,[...t],{stdio:["ignore","pipe","ignore"]})}catch{return g(void 0),i}a=setTimeout(()=>{b.kill("SIGKILL"),g(void 0)},n);let k=[];return b.stdout?.on("data",C=>k.push(C)),b.on("error",()=>g(void 0)),b.on("close",C=>{let _=Buffer.concat(k);g(C===0&&_.length>0?_:void 0)}),i}function $s(){return process.env.XDG_SESSION_TYPE==="wayland"||(process.env.WAYLAND_DISPLAY?.length??0)>0}function Fl(e){return e.length>8&&e[0]===137&&e[1]===80&&e[2]===78&&e[3]===71}function jl(e){return e.length>3&&e[0]===255&&e[1]===216&&e[2]===255}async function Dl(){try{let e=await Nl()?.getImage();if(e&&e.length>0)return Buffer.from(e)}catch{}if(process.platform==="darwin"){let e=await _e("pngpaste",["-"]);return e||await _e("osascript",["-e",`set d to the clipboard as \xABclass PNGf\xBB
|
|
2
2
|
return d`])}if(process.platform==="win32"){let e=["Add-Type -AssemblyName System.Windows.Forms","$img = [System.Windows.Forms.Clipboard]::GetImage()","if ($img -ne $null) {"," $ms = New-Object System.IO.MemoryStream"," $img.Save($ms, [System.Drawing.Imaging.ImageFormat]::Png)"," [Console]::OpenStandardOutput().Write($ms.ToArray(), 0, $ms.Length)","}"].join("; ");return _e("powershell.exe",["-NoProfile","-Command",e])}if($s()){let e=await _e("wl-paste",["--type","image/png"]);if(e)return e}if((process.env.DISPLAY?.length??0)>0||!$s()){let e=await _e("xclip",["-selection","clipboard","-t","image/png","-o"]);if(e)return e;let t=await _e("xclip",["-selection","clipboard","-t","image/jpeg","-o"]);if(t)return t}}function Wl(e,t){let n=t==="image/jpeg"?"jpg":"png";return`pasted-${new Date(e).toISOString().replace(/[:.]/g,"-")}.${n}`}async function Vn(e=ji,t=Date.now()){let n=await Dl();if(!n)return{ok:!1,reason:"the clipboard holds no image"};let i=Fl(n)?"image/png":jl(n)?"image/jpeg":void 0;if(!i)return{ok:!1,reason:"the clipboard image is not PNG or JPEG"};try{_l(e,{recursive:!0});let o=Ol(e,Wl(t,i));return Ll(o,n,{mode:384}),{ok:!0,image:{path:o,data:n.toString("base64"),mimeType:i}}}catch(o){return{ok:!1,reason:`could not store the image: ${o instanceof Error?o.message:String(o)}`}}}import{TreeSelectorComponent as Pd,initTheme as Md}from"@netrodev/hxf-coding-agent";import{getKeybindings as Ja}from"@netrodev/hxf-tui";import{mixColors as Ul,parseColor as Bl,styleText as he}from"@netrodev/hxf-tui";var ue=process.env.HOWTOCODE_NO_MOTION!=="1",Kl=45,vs=5,xs=8,qn=1e4,Ss=6e4,Cs=3,As=4,zn=e=>e<0?0:e>1?1:e;function ke(e,t,n){let i=zn(n);return i>=1?t:i<=0?e:Ul(e,t,i)}var _t=class{value;velocity=0;last=Date.now();target;constructor(t,n=t){this.value=t,this.target=n}set(t){this.target=t}get moving(){return Math.abs(this.target-this.value)>.15}snap(t){this.value=t,this.target=t,this.velocity=0,this.last=Date.now()}step(t=Date.now()){let n=Math.max(0,t-this.last),i=Math.min(250,n)/1e3;if(this.last=t,!ue)return this.value=this.target,this.velocity=0,this.value;n>250&&(this.velocity=0);let o=150,u=2*Math.sqrt(o),a=Math.max(1,Math.ceil(i/.008)),g=i/a;for(let b=0;b<a;b+=1)this.velocity+=(this.target-this.value)*o*g-this.velocity*u*g,this.value+=this.velocity*g;return this.moving||(this.value=this.target,this.velocity=0),this.value}};function Yn(e,t,n,i){return!ue||e<=qn?t:e>=Ss?i:ke(n,i,(e-qn)/(Ss-qn))}function Ts(e,t){return!ue||t<=0||e<0?1:1-(1-zn(e/t))**3}var Es=260,Gl=45;function Ps(e,t,n=Gl,i=400){return!ue||n<=0||e<0||e>=i?t:Math.min(t,Math.floor(e/n)+1)}function Ms(e,t,n=Date.now(),i=1400){if(!ue||i<=0)return e;let o=n%i/i;return ke(e,t,o<.5?o*2:(1-o)*2)}function Lt(e,t,n){let i=he(e,{fg:t.rest},de);if(!ue||e.length===0)return i;let o=zn(n);if(o>=1)return i;let u=t.band??1,a=e.length+As*2,b=Math.min(a-1,Math.floor(o*a))-As,k=G=>{let Q=Math.abs(G-b);return Q>u?0:1-Q/(u+1)},C="",_=0,O=null,F=0,W=0;for(let G of e){let Q=k(W);O===null?O=Q:Q!==O&&(C+=he(e.slice(_,F),{fg:ke(t.rest,t.lit,O)},de),_=F,O=Q),F+=G.length,W+=1}return C+he(e.slice(_),{fg:ke(t.rest,t.lit,O??0)},de)}function Jn(e,t,n=Date.now(),i=90){let o=t[0]??Bl("#e6e6e6");if(t.length===0||e.length===0)return he(e,{fg:o},de);if(!ue||i<=0)return he(e,{fg:t[t.length-1]??o},de);let u=t.length*i,a=(n%u+u)%u,g="",b=0,k=null,C=0,_=0,O=F=>{let W=(a+F*i)/u%1*t.length,G=Math.floor(W)%t.length,Q=(G+1)%t.length;return ke(t[G]??o,t[Q]??o,W-Math.floor(W))};for(let F of e){let W=O(_);k===null?k=W:W!==k&&(g+=he(e.slice(b,C),{fg:k},de),b=C,k=W),C+=F.length,_+=1}return g+he(e.slice(b),{fg:k??o},de)}function Hl(e,t){let n=Math.abs(e-t);return n>=vs?0:Math.ceil((1-n/vs)*Cs)/Cs}function Rs(e,t,n=Date.now()){let i=t.charMs??Kl;if(!ue||e.length===0||i<=0)return he(e,{fg:t.base},de);let o=e.length+xs*2,u=n/i%o-xs,a=(O,F)=>he(O,{fg:ke(t.base,t.bright,F)},de),g="",b=0,k=null,C=0,_=0;for(let O of e){let F=Hl(_,u);k===null?k=F:F!==k&&(g+=a(e.slice(b,C),k),b=C,k=F),C+=O.length,_+=1}return g+a(e.slice(b),k??0)}import{readFileSync as Vl,statSync as ql}from"node:fs";import{homedir as zl}from"node:os";import{extname as Yl}from"node:path";var Xn="\x1B[200~",Zn="\x1B[201~",Jl={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp"},Is=10*1024*1024,Xl=256*1024,Zl=20;function _s(e){if(!e.startsWith(Xn)||!e.endsWith(Zn))return;let t=e.slice(Xn.length,e.length-Zn.length);if(!(t.includes(Xn)||t.includes(Zn)))return t}function Ls(e){return e.trim()===""}function Ql(e){return/^[a-zA-Z]:[\\/]/.test(e)||e.startsWith("\\\\")||e.startsWith("/")||e==="~"||e.startsWith("~/")}function ec(e,t=zl()){let n=e.trim();return n.startsWith("file://")&&(n=decodeURIComponent(n.slice(7)),/^\/[a-zA-Z]:\//.test(n)&&(n=n.slice(1))),!/^[a-zA-Z]:[\\/]/.test(n)&&!n.startsWith("\\\\")&&(n=n.replace(/\\([ ()'&])/g,"$1")),n==="~"?t:n.startsWith("~/")?t+n.slice(1):n}function Os(e,t){let n=e.trim();if(!n||n.length>8192)return;let i,o=[...n.matchAll(/"([^"]+)"|'([^']+)'/g)].map(a=>a[1]??a[2]??"");if(o.length>0&&n.replace(/"[^"]+"|'[^']+'/g,"").trim()===""?i=o:i=n.split(/\r?\n/).map(a=>a.trim()).filter(a=>a.length>0),i.length===0||i.length>Zl||!i.every(a=>Ql(a)||a.startsWith("file://")))return;let u=i.map(a=>ec(a));return u.every(t)?u:void 0}function Ns(e){return Jl[Yl(e).toLowerCase()]}function Fs(e){return`[file ${e}]`}function Qn(e){return`[image ${e}]`}function js(e,t){return e.replace(/\[file ([^\]\n]+)\]/g,(n,i)=>{let o=t(i);return o===void 0?n:`<file name="${i}">
|
|
3
3
|
${o.trimEnd()}
|
|
4
4
|
</file>`})}function Ds(e){try{let t=ql(e);if(!t.isFile()||t.size===0||t.size>Xl)return;let n=Vl(e);return n.includes(0)?void 0:n.toString("utf8")}catch{return}}import{Markdown as kc,wrapTextWithAnsi as $c}from"@netrodev/hxf-tui";import{homedir as tc}from"node:os";import{isAbsolute as nc,relative as rc,resolve as ic,sep as Ws}from"node:path";import{getImageDimensions as oc,imageFallback as Us,renderImage as sc}from"@netrodev/hxf-tui";var ac="\u25CF",nr="\u2514",Nt="\u22EF",er=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"];function rt(e=1e3/30){let t=Math.floor(Date.now()/e)%er.length;return er[t]??er[0]}var lc="\u25B2";var cc="\u25CB",dc=["create_object","set_properties","delete_object","clone_instance","reparent_instance","set_script_source","edit_script_lines","insert_script_lines","execute_luau","generate_mesh","generate_material","generate_procedural_model"];function rr(e){return e.includes("__")?e.slice(e.lastIndexOf("__")+2):e}function Hs(e){return dc.includes(rr(e))}function tt(e,t=process.cwd()){if(!e||!nc(e))return e;let n=ic(e),i=rc(t,n);if(i==="")return".";if(i&&!i.startsWith(`..${Ws}`)&&i!=="..")return i;let o=tc();return o&&(n===o||n.startsWith(o+Ws))?`~${n.slice(o.length)}`:n}function ae(e,t){let n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,Math.max(1,t-1))}\u2026`:n}function U(e,t){if(e&&typeof e=="object"){let n=e[t];if(typeof n=="string"&&n.length>0)return n;if(typeof n=="number")return String(n)}}function uc(e,t=160){if(!e||typeof e!="object")return"";try{let n=JSON.stringify(e);return n&&n!=="{}"?ae(n,t):""}catch{return""}}function fc(e,t){switch(e){case"read":{let n=tt(U(t,"path")??""),i=[U(t,"offset"),U(t,"limit")].filter(Boolean);return i.length>0?`${n} ${i.length===1?`offset=${i[0]}`:`offset=${i[0]}, limit=${i[1]}`}`:n}case"edit":case"write":return tt(U(t,"path")??"");case"bash":case"powershell":{let n=U(t,"command")??"";return t?.run_in_background===!0?`${n} [background]`:n}case"bash_output":{let n=U(t,"task_id"),i=U(t,"filter");return n?i?`${n} filter=${i}`:n:"all tasks"}case"kill_shell":return U(t,"task_id")??"";case"compress":{let n=U(t,"topic")??"",i=Array.isArray(t.content)?t.content.length:0;return i>1?`${n} (${i} ranges)`:n}case"grep":{let n=U(t,"pattern")??"",i=U(t,"path");return i?`${n} in ${tt(i)}`:n}case"find":case"glob":{let n=U(t,"pattern")??U(t,"glob")??"",i=U(t,"path");return i?`${n} in ${tt(i)}`:n}case"ls":return tt(U(t,"path")??".");case"task":return U(t,"agent")??"task";case"ask":return U(t,"question")??"";case"web_search":return U(t,"query")??"";case"web_fetch":return U(t,"url")??"";case"lsp":{let n=U(t,"action")??"lsp",i=U(t,"file")??"",o=U(t,"line");return o?`${n} ${i}:${o}`:`${n} ${i}`}case"quality":return U(t,"path")??"changed files";case"think":return"private";case"todo":{let n=U(t,"op")??"view",i=U(t,"task"),o=t?.items;return n==="init"&&Array.isArray(o)?`init ${o.length} task${o.length===1?"":"s"}`:i?`${n} ${i}`:n}case"context":{let n=U(t,"op")??"list",i=U(t,"key");return i?`${n} ${i}`:n}case"workflow":{let n=U(t,"path");if(n)return n;let i=U(t,"code")??"",o=/export\s+const\s+meta\s*=\s*\{[\s\S]*?name\s*:\s*["'`]([^"'`]+)/.exec(i)?.[1];if(o)return o;let u=i.trim().split(`
|
|
@@ -137,4 +137,4 @@ plan file: ${jo()??"(unknown)"}`);return}if(s==="goal"){let d=l.trim();if(!d){m(
|
|
|
137
137
|
${jn(p)}`);return}if(s==="session"){let d=$.model;m("session",d?`${d.provider}/${d.id}`:"no model");return}if(s==="skills"){m("skills",gs($.resourceLoader.getSkills().skills));return}if(s==="preset"){$i(l);return}if(s==="roblox"){let d=se(e.cwd).entries.find(x=>x.manifest.name==="rotoolbox");if(!d||d.source!=="installed"){m("roblox","RoToolbox is not installed. Run /preset and install RoToolbox first.");return}let p=xn(d.dir),w=$.getActiveToolNames().filter(x=>/roblox[-_]studio/i.test(x)),h=w.length>0;m("roblox",p?`RoToolbox: disabled
|
|
138
138
|
Enable with /preset enable rotoolbox
|
|
139
139
|
The MCP server and manager stay stopped while disabled.`:["RoToolbox: active",`MCP server: ${h?`connected \u2014 ${w.length} tool${w.length===1?"":"s"} registered`:"not connected yet"}`,"Open Roblox Studio with a place, then use a prompt to inspect it.","Disable with /preset disable rotoolbox"].join(`
|
|
140
|
-
`));return}let f=ps(r,$.resourceLoader.getSkills().skills.map(d=>d.name));if(f){oi(f);return}let y=$.extensionRunner.getCommand(s??"");if(y){try{await y.handler(l,$.extensionRunner.createCommandContext())}catch(d){H(d instanceof Error?d.message:String(d))}return}m("command",`/${s??""} is not available in this screen yet`)};Mo((r,s)=>{let{promise:c,resolve:l}=Promise.withResolvers();return j(r,s.map(f=>({value:f,label:f})),l,()=>l("cancelled")),c}),process.on("SIGTERM",He),bs(()=>{He()}),t.setTitle(`${$n} ${bt}`),Ud(),i.start(),i.requestRender(!0),pn(!0);{let{maybeShowWelcome:r}=await import("./chunk-
|
|
140
|
+
`));return}let f=ps(r,$.resourceLoader.getSkills().skills.map(d=>d.name));if(f){oi(f);return}let y=$.extensionRunner.getCommand(s??"");if(y){try{await y.handler(l,$.extensionRunner.createCommandContext())}catch(d){H(d instanceof Error?d.message:String(d))}return}m("command",`/${s??""} is not available in this screen yet`)};Mo((r,s)=>{let{promise:c,resolve:l}=Promise.withResolvers();return j(r,s.map(f=>({value:f,label:f})),l,()=>l("cancelled")),c}),process.on("SIGTERM",He),bs(()=>{He()}),t.setTitle(`${$n} ${bt}`),Ud(),i.start(),i.requestRender(!0),pn(!0);{let{maybeShowWelcome:r}=await import("./chunk-IYR7VCH4.js");await r({cwd:e.cwd,note:e.note,signedIn:be!==void 0,runSlash:s=>{Je(s)},openExternal:s=>{Fe(s)}},j,m)}e.initialPrompt&&gn(e.initialPrompt),await new Promise(()=>{})}var X,Bd=1e3/30,Kd=45e3;export{Er as Dock,Ar as Hud,Tr as PinnedBlock,jd as approvalDetail,Fd as infoPanel,It as orderModelsForDefault,Nd as pickerPanel,Sm as runWorkbench,xr as slashCommands,Dd as workflowPanel,zt as workflowPanelFromRun,Pr as workflowRunOf};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var a="HowToCode",o="0.7.
|
|
1
|
+
var a="HowToCode",o="0.7.66",n=["You are HowToCode, 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{a as v}from"./chunk-7LA2AMZB.js";import{a as w}from"./chunk-UTYFLLSM.js";import{h as M,i as T}from"./chunk-
|
|
1
|
+
import{a as v}from"./chunk-7LA2AMZB.js";import{a as w}from"./chunk-UTYFLLSM.js";import{h as M,i as T}from"./chunk-YVRSL6ZX.js";import{existsSync as H,mkdirSync as I,readFileSync as b}from"node:fs";import{join as k}from"node:path";var J="https://models.dev/api.json";var N=["anthropic","openai","google","deepseek","zai","xai","moonshotai","minimax","alibaba","xiaomi","meta","tencent","nvidia","venice","openrouter"];function _(n){return n.toLowerCase().replace(/[^a-z0-9]+/g,"")}function S(n){let e=n.split("/");return _(e[e.length-1]??n)}function q(n){let e=new Map,s=new Map;if(!n||typeof n!="object")return e;let t=n,r=c=>{let o=N.indexOf(c);return o===-1?N.length:o};for(let c of Object.keys(t).sort()){let o=t[c]?.models;if(!(!o||typeof o!="object"))for(let a of Object.keys(o)){let i=o[a],u=Number(i?.limit?.context);if(!Number.isFinite(u)||u<=0)continue;let l=_(a),f=r(c),d=s.get(l);if(d!==void 0&&d<=f)continue;let m=Number(i?.limit?.output);e.set(l,{contextWindow:Math.floor(u),maxTokens:Number.isFinite(m)&&m>0?Math.floor(m):void 0,reasoning:i?.reasoning===!0,vision:Array.isArray(i?.modalities?.input)&&i.modalities.input.includes("image")}),s.set(l,f)}}return e}function A(n,e){let s=_(e);if(!s)return;let t=n.get(s);if(t)return t;let r=S(e);for(let[c,o]of n)if(S(c)===r)return o;for(let[c,o]of n)if(c.endsWith(s)||s.endsWith(c))return o}function R(n){return`${n}/models-dev-cache.json`}function $(n){let e={};for(let[s,t]of n)e[s]=[t.contextWindow,t.maxTokens??0,t.reasoning?1:0,t.vision?1:0];return JSON.stringify(e)}function P(n){let e=new Map,s;try{s=JSON.parse(n)}catch{return e}if(!s||typeof s!="object")return e;for(let[t,r]of Object.entries(s)){if(!Array.isArray(r)||r.length<3)continue;let c=Number(r[0]),o=Number(r[1]);!Number.isFinite(c)||c<=0||e.set(t,{contextWindow:Math.floor(c),maxTokens:Number.isFinite(o)&&o>0?Math.floor(o):void 0,reasoning:r[2]===1||r[2]===!0,vision:r[3]===1||r[3]===!0})}return e}async function U(n){let e=n?.url??J,s=n?.fetchImpl??fetch,t=n?.timeoutMs??2e4,r=new AbortController,c=setTimeout(()=>r.abort(),t);try{let o=await s(e,{signal:r.signal,headers:{Accept:"application/json"}});if(!o.ok)return{ok:!1,message:`the model catalogue answered ${o.status}`};let a=q(await o.json());return a.size===0?{ok:!1,message:"the model catalogue was empty or in an unexpected shape"}:{ok:!0,index:a}}catch(o){return{ok:!1,message:o instanceof Error&&o.name==="AbortError"?`the model catalogue did not answer within ${Math.round(t/1e3)}s`:"could not reach the model catalogue"}}finally{clearTimeout(c)}}var x="https://api.howtofix.id/v1",ce=v,C=["howtocode","howtocode-free"];function ue(n){try{let s=JSON.parse(b(k(n,"models.json"),"utf8")).providers;return!s||typeof s!="object"?new Set:new Set(Object.keys(s))}catch{return new Set}}function le(){return{baseUrl:x,api:"openai-completions",headers:{[M]:T()}}}function de(n){let e=k(n,"models.json"),s;try{s=JSON.parse(b(e,"utf8"))}catch{return 0}let t=s.providers;if(!t||typeof t!="object")return 0;let r=0;for(let c of C){let o=t[c];if(!o||!Array.isArray(o.models))continue;let a=Y(o.models),i={...o.headers??{},[M]:T()},u=o.headers?.[M]!==i[M];a.changed===0&&!u||(o.models=a.models,o.headers=i,r+=a.changed===0?1:a.changed)}if(r===0)return 0;try{w(e,`${JSON.stringify(s,null,2)}
|
|
2
2
|
`)}catch{return 0}return r}var G=10080*60*1e3;async function F(n,e){let s=R(n),t=e?.now??Date.now(),r,c=0;try{let i=JSON.parse(b(s,"utf8"));typeof i?.entries=="string"&&(r=P(i.entries),c=Number(i.at)||0)}catch{r=void 0}if(r&&r.size>0&&t-c<G&&!e?.force)return{index:r};let a=await U({fetchImpl:e?.fetchImpl});if(!a.ok)return r&&r.size>0?{index:r,message:a.message}:{index:new Map,message:a.message};try{I(n,{recursive:!0}),w(s,`${JSON.stringify({at:t,entries:$(a.index)})}
|
|
3
3
|
`)}catch{}return{index:a.index}}async function fe(n,e){let s=k(n,"models.json"),t;try{t=JSON.parse(b(s,"utf8"))}catch{return{changed:0}}let r=t.providers;if(!r||typeof r!="object")return{changed:0};let{index:c,message:o}=await F(n,e);if(c.size===0&&!e?.prices&&!e?.tiers)return{changed:0,message:o};let a=0;for(let i of C){let u=r[i];if(!u||!Array.isArray(u.models))continue;let l=Z(u.models,c,e?.prices,e?.tiers);l.changed!==0&&(u.models=l.models,a+=l.changed)}if(a>0)try{w(s,`${JSON.stringify(t,null,2)}
|
|
4
4
|
`)}catch{return{changed:0,message:"the models file could not be written"}}return{changed:a,message:o}}var B=3e5;function me(n){let e=k(n,"settings.json"),s={};try{let t=b(e,"utf8"),r=JSON.parse(t);r&&typeof r=="object"&&!Array.isArray(r)&&(s=r)}catch{if(H(e))return!1}if("httpIdleTimeoutMs"in s)return!1;s.httpIdleTimeoutMs=B;try{I(n,{recursive:!0}),w(e,`${JSON.stringify(s,null,2)}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{d as a,e as b,f as c,g as d,h as e,i as f,j as g,k as h,l as i}from"./chunk-
|
|
1
|
+
import{d as a,e as b,f as c,g as d,h as e,i as f,j as g,k as h,l as i}from"./chunk-4EQD3OPC.js";import"./chunk-UTYFLLSM.js";import"./chunk-YVRSL6ZX.js";import"./chunk-OHCWPWJW.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};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{A,B,C,D,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,C,D,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-TN22ZVV4.js";import"./chunk-7LA2AMZB.js";import"./chunk-UTYFLLSM.js";import"./chunk-YVRSL6ZX.js";import"./chunk-OHCWPWJW.js";import"./chunk-WOT6VMZA.js";export{g as CATALOG_CACHE_TTL_MS,m as DEFAULT_CONTEXT_WINDOW,a as HOWTOCODE_BASE_URL,b as HOWTOCODE_CONSOLE_URL,l as HOWTOCODE_MODEL_COMPAT,c as HOWTOCODE_PROVIDERS,j as HTTP_IDLE_TIMEOUT_MS,r as UNLIMITED_SENTINEL,w as applyCatalog,x as applyCompat,B as checkAccount,s as checkCreditPools,t as checkUsage,d as configuredProviderIds,y as countNewModels,k as ensureGatewaySettings,C as fetchGatewayPrices,A as findLiveModels,q as isHowtoCodeProvider,h as loadCatalog,o as looksLikeToken,n as maskToken,v as mergeModels,e as newProviderEntry,p as parseModelIds,z as probeModel,D as readProviderKey,f as repairGatewayModels,i as repairModelFacts,u as syncGatewayModelsOnStart};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{b as o}from"./chunk-
|
|
1
|
+
import{b as o}from"./chunk-OHCWPWJW.js";import{createPrivateKey as p,createPublicKey as f,createHash as l,randomBytes as d,sign as y}from"node:crypto";import{arch as c,cpus as m,hostname as I,platform as s}from"node:os";var a="hf-cli-1",C="MC4CAQAwBQYDK2VwBCIEIDmKoNgInS7oDpncee1d1+Mnci1R/q4aE5xxHeCKq4Dc",x="howtocode-cli-auth-v1",i;function u(){return i||(i=p({key:Buffer.from(C,"base64"),format:"der",type:"pkcs8"})),i}function g(){return f(u())}function K(t,e,n,r){return Buffer.from([x,t,e,n,r].join(`
|
|
2
2
|
`),"utf8")}function h(){return d(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=(m()[0]?.model??"").replace(/\s+/g," ").trim(),n=I(),r=e?`${n} (${s()}/${c()}, ${e})`:`${n} (${s()}/${c()})`;return`CLI (${o}, ${r})`}var k="X-HowToCode-Client";function A(){return`CLI (${o})`}function B(t,e){let n=h(),r=y(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};
|
package/dist/main-app.js
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import{b as G,d as J,e as K}from"./chunk-EZNNALD3.js";import"./chunk-7LA2AMZB.js";import{c as H}from"./chunk-PH72JBBL.js";import{a as B,b as F}from"./chunk-MCAAX33K.js";import{H as $,P as D}from"./chunk-ABDZXFNM.js";import"./chunk-UTYFLLSM.js";import{j as L}from"./chunk-MVVEYKN6.js";import{a as r,b as k}from"./chunk-OHCWPWJW.js";import"./chunk-WOT6VMZA.js";import{existsSync as Oe,mkdirSync as Te,readdirSync as Z,statSync as Ae,writeFileSync as je}from"node:fs";import{join as j}from"node:path";var V={rpc:!0,acp:!0},q={off:!0,minimal:!0,low:!0,medium:!0,high:!0,xhigh:!0,max:!0},z={suggest:!0,"auto-edit":!0,"full-auto":!0},X={text:!0,json:!0,"stream-json":!0};function Re(l){let e=Number(l);if(!Number.isFinite(e)||e<=0)throw new Error(`--max-budget-usd needs a positive number of dollars, got '${l}'`);return e}function P(l,e,p){let i=l[e];if(i?.includes("="))return i.slice(i.indexOf("=")+1);let c=l[e+1];if(!c||c.startsWith("-"))throw new Error(`${p} needs a value`);return l.splice(e+1,1),c}function Y(l){let e={print:!1,continueSession:!1,noSession:!1,help:!1,version:!1,update:!1,checkUpdate:!1,outputFormat:"text",dangerouslySkipPermissions:!1,sandbox:!1,prompt:""},p=[],i=[...l];i[0]==="resume"&&i[1]&&!i[1].startsWith("-")&&(e.resumeId=i[1],i.splice(0,2));for(let c=0;c<i.length;c++){let o=i[c]??"";if(o==="--"){p.push(...i.slice(c+1));break}if(o==="-h"||o==="--help")e.help=!0;else if(o==="-v"||o==="--version")e.version=!0;else if(o==="-p"||o==="--print")e.print=!0;else if(o==="-c"||o==="--continue")e.continueSession=!0;else if(o==="--no-session")e.noSession=!0;else if(o==="--sandbox")e.sandbox=!0;else if(o==="--update")e.update=!0;else if(o==="--check-update")e.checkUpdate=!0;else if(o==="-r"||o==="--resume")e.continueSession=!0;else if(o==="--session"||o.startsWith("--session="))e.sessionPath=P(i,c,"--session");else if(o==="-m"||o==="--model"||o.startsWith("--model="))e.model=P(i,c,"--model");else if(o==="--thinking"||o.startsWith("--thinking="))e.thinking=P(i,c,"--thinking");else if(o==="--approval"||o.startsWith("--approval="))e.approval=P(i,c,"--approval");else if(o==="--output-format"||o.startsWith("--output-format="))e.outputFormat=P(i,c,"--output-format");else if(o==="--max-budget-usd"||o.startsWith("--max-budget-usd="))e.maxBudgetUsd=Re(P(i,c,"--max-budget-usd"));else if(o==="--mode"||o.startsWith("--mode=")){let h=P(i,c,"--mode");if(!V[h])throw new Error(`--mode must be one of: ${Object.keys(V).join(", ")}`);e.mode=h}else if(o==="--acp")e.mode="acp";else if(o==="--dangerously-skip-permissions")e.dangerouslySkipPermissions=!0;else{if(o.startsWith("-"))throw new Error(`unknown option ${o}`);p.push(o)}}if(e.thinking&&!q[e.thinking])throw new Error(`thinking must be one of: ${Object.keys(q).join(", ")}`);if(e.approval&&!z[e.approval])throw new Error(`approval must be one of: ${Object.keys(z).join(", ")}`);if(!X[e.outputFormat])throw new Error(`output-format must be one of: ${Object.keys(X).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.resumeId&&e.sessionPath)throw new Error("resume <id> and --session cannot be combined");if(e.resumeId&&e.continueSession)throw new Error("resume <id> and --continue cannot be combined");if(e.print&&(e.continueSession||e.sessionPath||e.resumeId))throw new Error("--print runs one prompt in a throwaway session; it cannot be combined with --continue, --session, or resume <id>");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 E(){return`${r} ${k}
|
|
3
|
+
coding agent. layout is a workbench, not a chat log.
|
|
4
|
+
|
|
5
|
+
usage:
|
|
6
|
+
howtocode [options] [prompt]
|
|
7
|
+
howtocode -p "explain this repo"
|
|
8
|
+
howtocode resume <id> reopen one stored conversation by its id (or prefix)
|
|
9
|
+
/browser-relay install|status drive your own Chrome tabs from a session
|
|
10
|
+
howtocode acp serve the Agent Client Protocol on stdio
|
|
11
|
+
howtocode --mode rpc serve JSON-line commands on stdio
|
|
12
|
+
howtocode preset new|check|pack author a preset
|
|
13
|
+
howtocode doctor|models|sessions inspect the installation
|
|
14
|
+
howtocode sessions --search <text> find a session by what was said in it
|
|
15
|
+
howtocode sessions --export <n> print session n from the list as markdown
|
|
16
|
+
|
|
17
|
+
options:
|
|
18
|
+
-p, --print run one prompt and print the answer
|
|
19
|
+
-c, --continue resume the latest session in this folder
|
|
20
|
+
-r, --resume alias for --continue
|
|
21
|
+
--session <file> run inside a specific saved session file
|
|
22
|
+
--no-session do not write a session file
|
|
23
|
+
-m, --model <id> provider/model, or a fuzzy model id
|
|
24
|
+
--thinking <lv> off | minimal | low | medium | high | xhigh | max
|
|
25
|
+
--approval <m> suggest | auto-edit | full-auto
|
|
26
|
+
--output-format <f> text | json | stream-json
|
|
27
|
+
text for a person; json writes the final result only;
|
|
28
|
+
stream-json writes every event as it happens
|
|
29
|
+
--max-budget-usd <n> stop the run once it has spent n dollars
|
|
30
|
+
--mode <m> rpc | acp: serve a protocol on stdin/stdout, no terminal
|
|
31
|
+
--acp same as --mode acp
|
|
32
|
+
--sandbox run the whole session inside a filesystem sandbox:
|
|
33
|
+
the project is writable, the rest is read-only.
|
|
34
|
+
needs bubblewrap (Linux) or sandbox-exec (macOS)
|
|
35
|
+
--dangerously-skip-permissions
|
|
36
|
+
run everything, including commands otherwise refused.
|
|
37
|
+
unattended runs only; pairs with --print
|
|
38
|
+
--update install the newest release and exit
|
|
39
|
+
--check-update say whether a newer release exists
|
|
40
|
+
-h, --help
|
|
41
|
+
-v, --version
|
|
42
|
+
|
|
43
|
+
keys:
|
|
44
|
+
enter send
|
|
45
|
+
shift+enter new line
|
|
46
|
+
ctrl+c stop the run, or quit when idle
|
|
47
|
+
ctrl+d quit
|
|
48
|
+
ctrl+l jump to the latest line
|
|
49
|
+
ctrl+o clear the screen (history is kept)
|
|
50
|
+
ctrl+t raise the thinking level (wraps to off)
|
|
51
|
+
ctrl+shift+t lower the thinking level
|
|
52
|
+
esc clear the draft
|
|
53
|
+
ctrl+v paste from the clipboard
|
|
54
|
+
pgup / pgdn scroll the transcript a page
|
|
55
|
+
home / end jump to the top / back to the latest line
|
|
56
|
+
wheel scroll the transcript
|
|
57
|
+
|
|
58
|
+
commands:
|
|
59
|
+
/init /model /providers /thinking /approval /login /connect /logout /new
|
|
60
|
+
/resume /compact /name /stats /rtk /diff /commit /undo /rewind /review /tools /export
|
|
61
|
+
/copy /agents /goal /plan /workflow /session /help /quit /exit
|
|
62
|
+
/dcp /context /decompress /sweep
|
|
63
|
+
/update /usage /wallet /sync
|
|
64
|
+
/skills /preset /settings /trust /proxy /roblox /vault
|
|
65
|
+
/roblox shows whether RoToolbox is on and Roblox Studio's MCP server is connected.
|
|
66
|
+
RoToolbox uses Studio's own MCP server: open a place in Studio, nothing to install.
|
|
67
|
+
|
|
68
|
+
/stats shows session tokens, cost, and the prompt-cache hit rate; a high read
|
|
69
|
+
total alone hides re-billed context, so the rate is what tells you the truth.
|
|
70
|
+
/rtk compresses long tool output (logs, diffs, greps) before the model reads it.
|
|
71
|
+
Off by default: /rtk on to save tokens when skimming, /rtk off to keep every line.
|
|
72
|
+
Nothing is invented by it \u2014 it drops redundant lines and says how many it dropped,
|
|
73
|
+
and never touches a failed command or one already truncated.
|
|
74
|
+
|
|
75
|
+
/preset lists skills bundled with this build and skills from the registry, by
|
|
76
|
+
category; picking one downloads it into the project and loads it as a skill.
|
|
77
|
+
An integration preset installs disabled: its skills and MCP server stay dormant
|
|
78
|
+
until /preset enable <name>, and /preset disable <name> takes the server back
|
|
79
|
+
out of the live session. /roblox reports that state for RoToolbox in one line.
|
|
80
|
+
/skills lists what is loaded now.
|
|
81
|
+
|
|
82
|
+
/proxy <url> routes requests through a proxy, /proxy off stops, /proxy env uses
|
|
83
|
+
HTTPS_PROXY / HTTP_PROXY / ALL_PROXY; /proxy alone shows what is set.
|
|
84
|
+
|
|
85
|
+
/agents <id> <message> messages a parked agent; /agents <id> shows one.
|
|
86
|
+
|
|
87
|
+
a line starting with ! runs in the project shell.
|
|
88
|
+
|
|
89
|
+
an npm install checks for a newer release at startup and can install it itself;
|
|
90
|
+
/update does it on demand. config and sessions live in ~/.howtocode/agent.
|
|
91
|
+
/connect signs in to howtofix.id in your browser, and falls back to a pasted
|
|
92
|
+
token; /login takes another provider's key.
|
|
93
|
+
`}function Me(l,e=!1){let{message:p,hint:i}=B(l),c=i?`${p}
|
|
94
|
+
${i}`:p;if(!e)return c;let o=l instanceof Error?l.stack:void 0;return o&&o.includes(`
|
|
95
|
+
`)?`${c}
|
|
96
|
+
${o}`:c}function Q(l,e){let p=e?.debug??process.env.HOWTOCODE_DEBUG==="1",i=e?.exit??(o=>process.exit(o)),c=o=>{console.error(`${l}: ${Me(o,p)}`),i(1)};process.on("uncaughtException",c),process.on("unhandledRejection",c)}function Fe(){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 Ie(){process.stdout.on("error",l=>{throw l.code==="EPIPE"&&process.exit(0),l})}function Ne(){let l=j($,".welcomed");if(!Oe(l)){try{Te($,{recursive:!0}),je(l,k)}catch{return}console.error(`${r} ${k} installed. Docs: https://howtofix.id/code`),console.error("Continue the last session here with: howtocode -c")}}async function Ue(){Ie(),D();let l=performance.now(),e=Fe();if("error"in e){console.error(`${r}: ${e.error}`),process.exitCode=1;return}let p=e.cwd,i=process.env.HXF_FAKE_NODE??process.versions.node,[c,o]=i.split(".").map(s=>Number.parseInt(s,10));if(!Number.isFinite(c)||c<22||c===22&&Number.isFinite(o)&&o<19){console.error(`${r}: Node ${i} 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 s=process.argv.slice(2);if(s.some(n=>n==="-h"||n==="--help")){console.log(E());return}if(s.some(n=>n==="-v"||n==="--version")){console.log(`${r} ${k}`);return}return}let h=process.argv.slice(2);if(h[0]==="doctor"||h[0]==="models"||h[0]==="sessions"){let s=h[0];try{let n=await import("./chunk-BAB55K5H.js");s==="doctor"?process.exitCode=await n.runDoctor():s==="models"?process.exitCode=n.runModels():process.exitCode=n.runSessions(h.slice(1))}catch(n){F(r,s,n),process.exitCode=1}return}if(h.some(s=>s==="-v"||s==="--version")){console.log(`${r} ${k}`);return}if(h.some(s=>s==="-h"||s==="--help")){console.log(E());return}let ee=h[0]==="acp"?["--acp",...h.slice(1)]:h,R;try{R=Y(ee)}catch(s){let n=s instanceof Error?s.message:String(s);console.error(`${r}: ${n}
|
|
97
|
+
${E()}`),process.exitCode=2;return}if(R.print&&!R.prompt){console.error(`${r}: --print needs a prompt`),process.exitCode=2;return}let{repairGatewayModels:se,ensureGatewaySettings:oe,repairModelFacts:te,syncGatewayModelsOnStart:ne,checkAccount:re,fetchGatewayPrices:ie,readProviderKey:ae}=await import("./chunk-XB6IDZUM.js"),{tiersFrom:ce,writeReachable:de}=await import("./chunk-XBVWQC7P.js"),{readCliCredential:le,renewCliCredentialIfNeeded:pe}=await import("./chunk-VGY6AHOB.js"),{AGENT_DIR:f,REACHABLE_CACHE_PATH:ue}=await import("./chunk-ELM3OMOE.js"),{readCachedPrices:me,writeCachedPrices:he}=await import("./chunk-A3LZMZ3C.js"),I=se(f);I>0&&console.error(`${r}: repaired ${I} howtocode model(s) that the gateway would have rejected`);let _,M,O=new Map,C=me(f);if(C){_=C.prices;for(let[s,n]of C.groups)O.set(s,n)}try{let s=le(f),n=s?(await pe(f,s)).credential.accessToken:ae(f,"howtocode");if(n){let[m,u]=await Promise.all([C?Promise.resolve(_??new Map):ie(n,{groups:O}),re(n)]);!C&&m.size>0&&(_=m,he(f,m,O)),u.ok&&(M=u.models)}}catch{}let N=ce(O),T=await te(f,{..._?{prices:_}:{},...N.size>0?{tiers:N}:{}});if(T.changed>0?console.error(`${r}: filled in the context window, reasoning flag and price for ${T.changed} model(s)`):T.message&&console.error(`${r}: model catalogue unavailable (${T.message}); context windows stay at their conservative defaults`),oe(f)&&console.error(`${r}: set httpIdleTimeoutMs in settings.json so a stalled provider recovers instead of hanging`),M){de(ue,M);try{let s=await ne(f,M,_);s.added>0&&console.error(`${r}: added ${s.added} model(s) this account can now reach`)}catch{}}let t=R;if(t.help){console.log(E());return}if(t.version){console.log(`${r} ${k}`);let{cliSigningKeyMatchesPanel:s,cliSigningKeyFingerprint:n}=await import("./chunk-JREL7M6J.js");s()||(console.error(`${r}: this build's CLI signing key (${n()}) does not match the key the panel verifies against, so sign-in will be refused.`),process.exitCode=1);return}if(t.sandbox&&!process.env.HOWTOCODE_SANDBOXED){let{detectSandbox:s,enterSandbox:n,describeSandbox:m}=await import("./chunk-YX2QDCVK.js"),u=s();if(!u){console.error(`${r}: --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(m(u)),process.exitCode=n(u,{cwd:p,agentDir:$,argv:[process.execPath,...process.argv.slice(1)]});return}let{installProxy:fe}=await import("./chunk-WKUJ7CFO.js");fe($);let{retireRobloxBridge:ge}=await import("./chunk-CCISJKGS.js");if(ge($),t.update||t.checkUpdate){let{PACKAGE_NAME:s,checkForUpdate:n,installUpdate:m,isInstalledCopy:u}=await import("./chunk-LYLJZVZ7.js"),w=await n(k);if(!w.latest){console.error(`${r}: ${w.message}`),process.exitCode=t.update?1:0;return}if(console.log(w.message),t.checkUpdate||!w.available)return;if(!u()){console.error(`${r}: this copy was not installed by npm, so npm cannot replace it. install it with: npm install -g ${s}`),process.exitCode=1;return}let v=await m({version:w.latest});console.log(v.message),v.ok||(process.exitCode=1);return}let U=process.argv.slice(2);if(U[0]==="preset"){let{runPresetCommand:s}=await import("./chunk-AS4FUFAN.js");process.exitCode=s(U.slice(1));return}let{expandFileReferences:we}=await import("./chunk-TSEKPGK4.js"),{isApprovalMode:be,setApprovalMode:ke,setDangerousBypass:xe,isDangerousBypass:ye}=await import("./chunk-7LAMZWB5.js"),{openSession:ve}=await import("./chunk-BZ6PO2P5.js");ke(t.approval&&be(t.approval)?t.approval:"full-auto");let{readWorkbenchSettings:Se}=await import("./chunk-V3R4FYTJ.js");if((t.dangerouslySkipPermissions||Se(f).skipPermissions)&&xe(!0),ye()&&console.error(`${r}: 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:s}=await import("./chunk-DG7OCYNY.js");await s(t.mode,{cwd:p,model:t.model,thinking:t.thinking});return}let W=s=>ve({cwd:p,model:t.model,thinking:t.thinking,continueSession:s.continueSession??!1,noSession:s.noSession??!1,sessionPath:s.sessionPath,interactive:!t.print});if(t.resumeId&&!t.sessionPath){let s=j($,"sessions"),n=[];try{for(let m of Z(s))for(let u of Z(j(s,m))){if(!u.endsWith(".jsonl")||!u.includes(t.resumeId))continue;let w=j(s,m,u);try{n.push({path:w,mtime:Ae(w).mtimeMs})}catch{}}}catch{}if(n=n.sort((m,u)=>u.mtime-m.mtime),n.length===0){console.error(`${r}: no stored session matches '${t.resumeId}'. Run 'howtocode -c' to continue the latest one in this folder.`),process.exitCode=1;return}n.length>1&&console.error(`${r}: '${t.resumeId}' matches ${n.length} sessions; using the newest (${n[0].path}).`),t.sessionPath=n[0].path}let a=await W({continueSession:t.continueSession,sessionPath:t.sessionPath,noSession:t.noSession||t.print});if(t.print&&a.note&&console.error(a.note),t.maxBudgetUsd!==void 0&&!a.priced){console.error(`${r}: ${K(a.modelLabel,f)}`),await a.dispose(),process.exitCode=2;return}if(t.print){let s=t.prompt.trimStart();if(s.startsWith("/")){let b=s.slice(1).split(/\s+/)[0]??"",{skillInvocation:A}=await import("./chunk-BZJSYOTO.js"),S=a.session.resourceLoader.getSkills().skills.map(g=>g.name);if(!(A(s,S)!==void 0)){let{slashCommands:g}=await import("./chunk-JY72ELJM.js");if(g(a.session).some(d=>d.name===b)){console.error(`${r}: /${b} runs in the TUI only \u2014 --print sends prompts straight to the model. Run \`howtocode\` without --print for interactive commands.`),await a.dispose(),process.exitCode=2;return}}}let n=t.outputFormat==="stream-json",m=t.outputFormat==="json",u=n||m;if(n){let b={type:"system",subtype:"init",cwd:p,session_id:a.session.sessionId,model:a.modelLabel,output_format:t.outputFormat,max_budget_usd:t.maxBudgetUsd??null,dangerously_skip_permissions:t.dangerouslySkipPermissions,cli_version:k};process.stdout.write(`${JSON.stringify(b)}
|
|
98
|
+
`)}let w,v,Ee=()=>{if(t.maxBudgetUsd===void 0||v!==void 0)return;let b=a.session.getSessionStats().cost;b>t.maxBudgetUsd&&(v={spent:b},a.session.abort())};try{let b,A=H();if(w=a.session.subscribe(d=>{if(n){let y=A.line(d);y!==void 0&&process.stdout.write(y)}if(d.type==="turn_end"&&d.message?.role==="assistant"){let y=d.message;y.stopReason==="error"||y.stopReason==="aborted"||y.errorMessage?b={stopReason:y.stopReason??"error",errorMessage:y.errorMessage}:b=void 0}Ee()}),await a.session.prompt(we(t.prompt,p)),n){let d=A.finish();d!==void 0&&process.stdout.write(d)}let S=L(a.session.getLastAssistantText()??"");if(v){if(console.error(`${r}: ${J(v.spent,t.maxBudgetUsd)}`),u){let d=a.session.getSessionStats();process.stdout.write(`${JSON.stringify({type:"result",subtype:"error_max_budget_usd",is_error:!0,result:S,session_id:a.session.sessionId,duration_ms:Math.round(performance.now()-l),num_turns:d.assistantMessages,total_cost_usd:d.cost,usage:{input_tokens:d.tokens.input,output_tokens:d.tokens.output,cache_read_input_tokens:d.tokens.cacheRead,cache_creation_input_tokens:d.tokens.cacheWrite}})}
|
|
99
|
+
`)}process.exitCode=1;return}let x=a.session.state.messages.at(-1),g=b??(x?.role==="assistant"&&(x.stopReason==="error"||x.stopReason==="aborted"||x.errorMessage)?{stopReason:x.stopReason??"error",errorMessage:x.errorMessage}:void 0);if(u){let d=a.session.getSessionStats();process.stdout.write(`${JSON.stringify({type:"result",subtype:g?g.stopReason==="aborted"?"error_aborted":"error_during_execution":"success",is_error:g!==void 0,result:S,session_id:a.session.sessionId,duration_ms:Math.round(performance.now()-l),num_turns:d.assistantMessages,total_cost_usd:d.cost,usage:{input_tokens:d.tokens.input,output_tokens:d.tokens.output,cache_read_input_tokens:d.tokens.cacheRead,cache_creation_input_tokens:d.tokens.cacheWrite},stop_reason:g?.stopReason??(x?.role==="assistant"?x.stopReason:void 0)})}
|
|
100
|
+
`)}else process.stdout.write(S.endsWith(`
|
|
101
|
+
`)?S:`${S}
|
|
102
|
+
`);if(g&&(process.exitCode=1,g.errorMessage)){console.error(`${r}: ${g.errorMessage}`);let d=G(g.errorMessage);d!==void 0&&console.error(`${r}: ${d}`)}}finally{w?.(),await a.dispose()}return}if(!process.stdin.isTTY||!process.stdout.isTTY){console.error(`${r}: interactive mode needs a terminal. use --print for pipes.`),await a.dispose(),process.exitCode=2;return}Ne();let{runWorkbench:$e}=await import("./chunk-JY72ELJM.js"),{autoUpdateEnabled:Pe,isInstalledCopy:_e}=await import("./chunk-LYLJZVZ7.js"),Ce=_e()&&Pe(`${f}/settings.json`);await $e({cwd:p,modelLabel:a.modelLabel,session:a.session,dispose:()=>a.dispose(),setCompressToolOutput:a.setCompressToolOutput,initialPrompt:t.prompt||void 0,note:a.note,maxBudgetUsd:t.maxBudgetUsd,update:Ce?{current:k,install:!0}:void 0,reopen:W})}Q(r);Ue().catch(l=>{F(r,void 0,l),process.exitCode=1});
|
package/dist/main.js
CHANGED
|
@@ -1,102 +1,9 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
howtocode acp serve the Agent Client Protocol on stdio
|
|
11
|
-
howtocode --mode rpc serve JSON-line commands on stdio
|
|
12
|
-
howtocode preset new|check|pack author a preset
|
|
13
|
-
howtocode doctor|models|sessions inspect the installation
|
|
14
|
-
howtocode sessions --search <text> find a session by what was said in it
|
|
15
|
-
howtocode sessions --export <n> print session n from the list as markdown
|
|
16
|
-
|
|
17
|
-
options:
|
|
18
|
-
-p, --print run one prompt and print the answer
|
|
19
|
-
-c, --continue resume the latest session in this folder
|
|
20
|
-
-r, --resume alias for --continue
|
|
21
|
-
--session <file> run inside a specific saved session file
|
|
22
|
-
--no-session do not write a session file
|
|
23
|
-
-m, --model <id> provider/model, or a fuzzy model id
|
|
24
|
-
--thinking <lv> off | minimal | low | medium | high | xhigh | max
|
|
25
|
-
--approval <m> suggest | auto-edit | full-auto
|
|
26
|
-
--output-format <f> text | json | stream-json
|
|
27
|
-
text for a person; json writes the final result only;
|
|
28
|
-
stream-json writes every event as it happens
|
|
29
|
-
--max-budget-usd <n> stop the run once it has spent n dollars
|
|
30
|
-
--mode <m> rpc | acp: serve a protocol on stdin/stdout, no terminal
|
|
31
|
-
--acp same as --mode acp
|
|
32
|
-
--sandbox run the whole session inside a filesystem sandbox:
|
|
33
|
-
the project is writable, the rest is read-only.
|
|
34
|
-
needs bubblewrap (Linux) or sandbox-exec (macOS)
|
|
35
|
-
--dangerously-skip-permissions
|
|
36
|
-
run everything, including commands otherwise refused.
|
|
37
|
-
unattended runs only; pairs with --print
|
|
38
|
-
--update install the newest release and exit
|
|
39
|
-
--check-update say whether a newer release exists
|
|
40
|
-
-h, --help
|
|
41
|
-
-v, --version
|
|
42
|
-
|
|
43
|
-
keys:
|
|
44
|
-
enter send
|
|
45
|
-
shift+enter new line
|
|
46
|
-
ctrl+c stop the run, or quit when idle
|
|
47
|
-
ctrl+d quit
|
|
48
|
-
ctrl+l jump to the latest line
|
|
49
|
-
ctrl+o clear the screen (history is kept)
|
|
50
|
-
ctrl+t raise the thinking level (wraps to off)
|
|
51
|
-
ctrl+shift+t lower the thinking level
|
|
52
|
-
esc clear the draft
|
|
53
|
-
ctrl+v paste from the clipboard
|
|
54
|
-
pgup / pgdn scroll the transcript a page
|
|
55
|
-
home / end jump to the top / back to the latest line
|
|
56
|
-
wheel scroll the transcript
|
|
57
|
-
|
|
58
|
-
commands:
|
|
59
|
-
/init /model /providers /thinking /approval /login /connect /logout /new
|
|
60
|
-
/resume /compact /name /stats /rtk /diff /commit /undo /rewind /review /tools /export
|
|
61
|
-
/copy /agents /goal /plan /workflow /session /help /quit /exit
|
|
62
|
-
/dcp /context /decompress /sweep
|
|
63
|
-
/update /usage /wallet /sync
|
|
64
|
-
/skills /preset /settings /trust /proxy /roblox /vault
|
|
65
|
-
/roblox shows whether RoToolbox is on and Roblox Studio's MCP server is connected.
|
|
66
|
-
RoToolbox uses Studio's own MCP server: open a place in Studio, nothing to install.
|
|
67
|
-
|
|
68
|
-
/stats shows session tokens, cost, and the prompt-cache hit rate; a high read
|
|
69
|
-
total alone hides re-billed context, so the rate is what tells you the truth.
|
|
70
|
-
/rtk compresses long tool output (logs, diffs, greps) before the model reads it.
|
|
71
|
-
Off by default: /rtk on to save tokens when skimming, /rtk off to keep every line.
|
|
72
|
-
Nothing is invented by it \u2014 it drops redundant lines and says how many it dropped,
|
|
73
|
-
and never touches a failed command or one already truncated.
|
|
74
|
-
|
|
75
|
-
/preset lists skills bundled with this build and skills from the registry, by
|
|
76
|
-
category; picking one downloads it into the project and loads it as a skill.
|
|
77
|
-
An integration preset installs disabled: its skills and MCP server stay dormant
|
|
78
|
-
until /preset enable <name>, and /preset disable <name> takes the server back
|
|
79
|
-
out of the live session. /roblox reports that state for RoToolbox in one line.
|
|
80
|
-
/skills lists what is loaded now.
|
|
81
|
-
|
|
82
|
-
/proxy <url> routes requests through a proxy, /proxy off stops, /proxy env uses
|
|
83
|
-
HTTPS_PROXY / HTTP_PROXY / ALL_PROXY; /proxy alone shows what is set.
|
|
84
|
-
|
|
85
|
-
/agents <id> <message> messages a parked agent; /agents <id> shows one.
|
|
86
|
-
|
|
87
|
-
a line starting with ! runs in the project shell.
|
|
88
|
-
|
|
89
|
-
an npm install checks for a newer release at startup and can install it itself;
|
|
90
|
-
/update does it on demand. config and sessions live in ~/.howtocode/agent.
|
|
91
|
-
/connect signs in to howtofix.id in your browser, and falls back to a pasted
|
|
92
|
-
token; /login takes another provider's key.
|
|
93
|
-
`}function Me(l,e=!1){let{message:p,hint:i}=B(l),c=i?`${p}
|
|
94
|
-
${i}`:p;if(!e)return c;let s=l instanceof Error?l.stack:void 0;return s&&s.includes(`
|
|
95
|
-
`)?`${c}
|
|
96
|
-
${s}`:c}function Q(l,e){let p=e?.debug??process.env.HOWTOCODE_DEBUG==="1",i=e?.exit??(s=>process.exit(s)),c=s=>{console.error(`${l}: ${Me(s,p)}`),i(1)};process.on("uncaughtException",c),process.on("unhandledRejection",c)}function Fe(){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 Ie(){process.stdout.on("error",l=>{throw l.code==="EPIPE"&&process.exit(0),l})}function Ne(){let l=j($,".welcomed");if(!Oe(l)){try{Te($,{recursive:!0}),je(l,k)}catch{return}console.error(`${r} ${k} installed. Docs: https://howtofix.id/code`),console.error("Continue the last session here with: howtocode -c")}}async function Ue(){Ie(),D();let l=performance.now(),e=Fe();if("error"in e){console.error(`${r}: ${e.error}`),process.exitCode=1;return}let p=e.cwd,i=process.env.HXF_FAKE_NODE??process.versions.node,[c,s]=i.split(".").map(t=>Number.parseInt(t,10));if(!Number.isFinite(c)||c<22||c===22&&Number.isFinite(s)&&s<19){console.error(`${r}: Node ${i} 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 t=process.argv.slice(2);if(t.some(n=>n==="-h"||n==="--help")){console.log(A());return}if(t.some(n=>n==="-v"||n==="--version")){console.log(`${r} ${k}`);return}return}let g=process.argv.slice(2);if(g[0]==="doctor"||g[0]==="models"||g[0]==="sessions"){let t=g[0];try{let n=await import("./chunk-S3XJFLP4.js");t==="doctor"?process.exitCode=await n.runDoctor():t==="models"?process.exitCode=n.runModels():process.exitCode=n.runSessions(g.slice(1))}catch(n){F(r,t,n),process.exitCode=1}return}let ee=g[0]==="acp"?["--acp",...g.slice(1)]:g,E;try{E=Y(ee)}catch(t){let n=t instanceof Error?t.message:String(t);console.error(`${r}: ${n}
|
|
97
|
-
${A()}`),process.exitCode=2;return}if(E.print&&!E.prompt){console.error(`${r}: --print needs a prompt`),process.exitCode=2;return}let{repairGatewayModels:se,ensureGatewaySettings:oe,repairModelFacts:te,syncGatewayModelsOnStart:ne,checkAccount:re,fetchGatewayPrices:ie,readProviderKey:ae}=await import("./chunk-GNDRI3LT.js"),{tiersFrom:ce,writeReachable:de}=await import("./chunk-XBVWQC7P.js"),{readCliCredential:le,renewCliCredentialIfNeeded:pe}=await import("./chunk-4A5FL2OO.js"),{AGENT_DIR:h,REACHABLE_CACHE_PATH:ue}=await import("./chunk-ELM3OMOE.js"),{readCachedPrices:me,writeCachedPrices:he}=await import("./chunk-A3LZMZ3C.js"),I=se(h);I>0&&console.error(`${r}: repaired ${I} howtocode model(s) that the gateway would have rejected`);let _,R,M=new Map,C=me(h);if(C){_=C.prices;for(let[t,n]of C.groups)M.set(t,n)}try{let t=le(h),n=t?(await pe(h,t)).credential.accessToken:ae(h,"howtocode");if(n){let[m,u]=await Promise.all([C?Promise.resolve(_??new Map):ie(n,{groups:M}),re(n)]);!C&&m.size>0&&(_=m,he(h,m,M)),u.ok&&(R=u.models)}}catch{}let N=ce(M),O=await te(h,{..._?{prices:_}:{},...N.size>0?{tiers:N}:{}});if(O.changed>0?console.error(`${r}: filled in the context window, reasoning flag and price for ${O.changed} model(s)`):O.message&&console.error(`${r}: model catalogue unavailable (${O.message}); context windows stay at their conservative defaults`),oe(h)&&console.error(`${r}: set httpIdleTimeoutMs in settings.json so a stalled provider recovers instead of hanging`),R){de(ue,R);try{let t=await ne(h,R,_);t.added>0&&console.error(`${r}: added ${t.added} model(s) this account can now reach`)}catch{}}let o=E;if(o.help){console.log(A());return}if(o.version){console.log(`${r} ${k}`);let{cliSigningKeyMatchesPanel:t,cliSigningKeyFingerprint:n}=await import("./chunk-TPMW4JXS.js");t()||(console.error(`${r}: this build's CLI signing key (${n()}) does not match the key the panel verifies against, so sign-in will be refused.`),process.exitCode=1);return}if(o.sandbox&&!process.env.HOWTOCODE_SANDBOXED){let{detectSandbox:t,enterSandbox:n,describeSandbox:m}=await import("./chunk-YX2QDCVK.js"),u=t();if(!u){console.error(`${r}: --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(m(u)),process.exitCode=n(u,{cwd:p,agentDir:$,argv:[process.execPath,...process.argv.slice(1)]});return}let{installProxy:fe}=await import("./chunk-WKUJ7CFO.js");fe($);let{retireRobloxBridge:ge}=await import("./chunk-CCISJKGS.js");if(ge($),o.update||o.checkUpdate){let{PACKAGE_NAME:t,checkForUpdate:n,installUpdate:m,isInstalledCopy:u}=await import("./chunk-LYLJZVZ7.js"),w=await n(k);if(!w.latest){console.error(`${r}: ${w.message}`),process.exitCode=o.update?1:0;return}if(console.log(w.message),o.checkUpdate||!w.available)return;if(!u()){console.error(`${r}: this copy was not installed by npm, so npm cannot replace it. install it with: npm install -g ${t}`),process.exitCode=1;return}let v=await m({version:w.latest});console.log(v.message),v.ok||(process.exitCode=1);return}let U=process.argv.slice(2);if(U[0]==="preset"){let{runPresetCommand:t}=await import("./chunk-AS4FUFAN.js");process.exitCode=t(U.slice(1));return}let{expandFileReferences:we}=await import("./chunk-TSEKPGK4.js"),{isApprovalMode:be,setApprovalMode:ke,setDangerousBypass:xe,isDangerousBypass:ye}=await import("./chunk-7LAMZWB5.js"),{openSession:ve}=await import("./chunk-235M52T5.js");ke(o.approval&&be(o.approval)?o.approval:"full-auto");let{readWorkbenchSettings:Se}=await import("./chunk-V3R4FYTJ.js");if((o.dangerouslySkipPermissions||Se(h).skipPermissions)&&xe(!0),ye()&&console.error(`${r}: 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.`),o.mode){let{serveProtocol:t}=await import("./chunk-TFAXSHWM.js");await t(o.mode,{cwd:p,model:o.model,thinking:o.thinking});return}let W=t=>ve({cwd:p,model:o.model,thinking:o.thinking,continueSession:t.continueSession??!1,noSession:t.noSession??!1,sessionPath:t.sessionPath,interactive:!o.print});if(o.resumeId&&!o.sessionPath){let t=j($,"sessions"),n=[];try{for(let m of Z(t))for(let u of Z(j(t,m))){if(!u.endsWith(".jsonl")||!u.includes(o.resumeId))continue;let w=j(t,m,u);try{n.push({path:w,mtime:Ae(w).mtimeMs})}catch{}}}catch{}if(n=n.sort((m,u)=>u.mtime-m.mtime),n.length===0){console.error(`${r}: no stored session matches '${o.resumeId}'. Run 'howtocode -c' to continue the latest one in this folder.`),process.exitCode=1;return}n.length>1&&console.error(`${r}: '${o.resumeId}' matches ${n.length} sessions; using the newest (${n[0].path}).`),o.sessionPath=n[0].path}let a=await W({continueSession:o.continueSession,sessionPath:o.sessionPath,noSession:o.noSession||o.print});if(o.print&&a.note&&console.error(a.note),o.maxBudgetUsd!==void 0&&!a.priced){console.error(`${r}: ${K(a.modelLabel,h)}`),await a.dispose(),process.exitCode=2;return}if(o.print){let t=o.prompt.trimStart();if(t.startsWith("/")){let b=t.slice(1).split(/\s+/)[0]??"",{skillInvocation:T}=await import("./chunk-BZJSYOTO.js"),S=a.session.resourceLoader.getSkills().skills.map(f=>f.name);if(!(T(t,S)!==void 0)){let{slashCommands:f}=await import("./chunk-GYFZKOJV.js");if(f(a.session).some(d=>d.name===b)){console.error(`${r}: /${b} runs in the TUI only \u2014 --print sends prompts straight to the model. Run \`howtocode\` without --print for interactive commands.`),await a.dispose(),process.exitCode=2;return}}}let n=o.outputFormat==="stream-json",m=o.outputFormat==="json",u=n||m;if(n){let b={type:"system",subtype:"init",cwd:p,session_id:a.session.sessionId,model:a.modelLabel,output_format:o.outputFormat,max_budget_usd:o.maxBudgetUsd??null,dangerously_skip_permissions:o.dangerouslySkipPermissions,cli_version:k};process.stdout.write(`${JSON.stringify(b)}
|
|
98
|
-
`)}let w,v,Ee=()=>{if(o.maxBudgetUsd===void 0||v!==void 0)return;let b=a.session.getSessionStats().cost;b>o.maxBudgetUsd&&(v={spent:b},a.session.abort())};try{let b,T=H();if(w=a.session.subscribe(d=>{if(n){let y=T.line(d);y!==void 0&&process.stdout.write(y)}if(d.type==="turn_end"&&d.message?.role==="assistant"){let y=d.message;y.stopReason==="error"||y.stopReason==="aborted"||y.errorMessage?b={stopReason:y.stopReason??"error",errorMessage:y.errorMessage}:b=void 0}Ee()}),await a.session.prompt(we(o.prompt,p)),n){let d=T.finish();d!==void 0&&process.stdout.write(d)}let S=L(a.session.getLastAssistantText()??"");if(v){if(console.error(`${r}: ${J(v.spent,o.maxBudgetUsd)}`),u){let d=a.session.getSessionStats();process.stdout.write(`${JSON.stringify({type:"result",subtype:"error_max_budget_usd",is_error:!0,result:S,session_id:a.session.sessionId,duration_ms:Math.round(performance.now()-l),num_turns:d.assistantMessages,total_cost_usd:d.cost,usage:{input_tokens:d.tokens.input,output_tokens:d.tokens.output,cache_read_input_tokens:d.tokens.cacheRead,cache_creation_input_tokens:d.tokens.cacheWrite}})}
|
|
99
|
-
`)}process.exitCode=1;return}let x=a.session.state.messages.at(-1),f=b??(x?.role==="assistant"&&(x.stopReason==="error"||x.stopReason==="aborted"||x.errorMessage)?{stopReason:x.stopReason??"error",errorMessage:x.errorMessage}:void 0);if(u){let d=a.session.getSessionStats();process.stdout.write(`${JSON.stringify({type:"result",subtype:f?f.stopReason==="aborted"?"error_aborted":"error_during_execution":"success",is_error:f!==void 0,result:S,session_id:a.session.sessionId,duration_ms:Math.round(performance.now()-l),num_turns:d.assistantMessages,total_cost_usd:d.cost,usage:{input_tokens:d.tokens.input,output_tokens:d.tokens.output,cache_read_input_tokens:d.tokens.cacheRead,cache_creation_input_tokens:d.tokens.cacheWrite},stop_reason:f?.stopReason??(x?.role==="assistant"?x.stopReason:void 0)})}
|
|
100
|
-
`)}else process.stdout.write(S.endsWith(`
|
|
101
|
-
`)?S:`${S}
|
|
102
|
-
`);if(f&&(process.exitCode=1,f.errorMessage)){console.error(`${r}: ${f.errorMessage}`);let d=G(f.errorMessage);d!==void 0&&console.error(`${r}: ${d}`)}}finally{w?.(),await a.dispose()}return}if(!process.stdin.isTTY||!process.stdout.isTTY){console.error(`${r}: interactive mode needs a terminal. use --print for pipes.`),await a.dispose(),process.exitCode=2;return}Ne();let{runWorkbench:$e}=await import("./chunk-GYFZKOJV.js"),{autoUpdateEnabled:Pe,isInstalledCopy:_e}=await import("./chunk-LYLJZVZ7.js"),Ce=_e()&&Pe(`${h}/settings.json`);await $e({cwd:p,modelLabel:a.modelLabel,session:a.session,dispose:()=>a.dispose(),setCompressToolOutput:a.setCompressToolOutput,initialPrompt:o.prompt||void 0,note:a.note,maxBudgetUsd:o.maxBudgetUsd,update:Ce?{current:k,install:!0}:void 0,reopen:W})}Q(r);Ue().catch(l=>{F(r,void 0,l),process.exitCode=1});
|
|
2
|
+
const argv = process.argv.slice(2);
|
|
3
|
+
if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v") && !process.env.HXF_FAKE_NODE) {
|
|
4
|
+
const { readFileSync } = await import("node:fs");
|
|
5
|
+
const pkg = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8"));
|
|
6
|
+
console.log("HowToCode " + pkg.version);
|
|
7
|
+
} else {
|
|
8
|
+
await import("./main-app.js");
|
|
9
|
+
}
|