howtocode 0.7.75 → 0.7.76
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/assets/background.js.txt +92 -6
- package/dist/assets/manifest.json.txt +2 -1
- package/dist/assets/options.html.txt +2 -2
- package/dist/{chunk-QAXXSULF.js → chunk-42J3SVVD.js} +1 -1
- package/dist/{chunk-YB5UNXVA.js → chunk-6MW4XQH2.js} +1 -1
- package/dist/{chunk-L73LU5W5.js → chunk-AMYTGLTF.js} +1 -1
- package/dist/chunk-DBPJZUIT.js +17 -0
- package/dist/{chunk-QNBA2A2M.js → chunk-DQZCH2E4.js} +1 -1
- package/dist/{chunk-GLOEJWUF.js → chunk-EMFKTIYL.js} +1 -1
- package/dist/chunk-G3RLGCT7.js +187 -0
- package/dist/chunk-KBZERZVM.js +2 -0
- package/dist/{chunk-E2JC7MLI.js → chunk-MSEVYMAA.js} +1 -1
- package/dist/{chunk-VWHAFIOV.js → chunk-NARUJ2JE.js} +1 -1
- package/dist/{chunk-NLV4AD4X.js → chunk-SBWZZCV5.js} +1 -1
- package/dist/{chunk-YW4RNAH5.js → chunk-WXNRNAQ6.js} +32 -30
- package/dist/{chunk-Q57F6VH7.js → chunk-XORAIQWU.js} +1 -1
- package/dist/{chunk-IM52NDS4.js → chunk-XZBFNLPM.js} +1 -1
- package/dist/cli-auth.js +1 -1
- package/dist/main-app.js +6 -6
- package/package.json +1 -1
- package/dist/chunk-AMHJO4G3.js +0 -201
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{b as c,d as l}from"./chunk-XODGJSB3.js";import{a as i,b as r}from"./chunk-
|
|
1
|
+
import{b as c,d as l}from"./chunk-XODGJSB3.js";import{a as i,b as r}from"./chunk-SBWZZCV5.js";import{H as s}from"./chunk-5FIFNXLT.js";import"./chunk-UTYFLLSM.js";import"./chunk-WOT6VMZA.js";var d=[["/connect","sign in to howtofix.id: approve it in your browser"],["/model","choose which model answers"],["/help","list every command"],["/quit","leave"]],u=[" \u2588\u2588\u2557 \u2588\u2588\u2557\u2588\u2588\u2557 \u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557"," \u2588\u2588\u2551 \u2588\u2588\u2551\u255A\u2588\u2588\u2557\u2588\u2588\u2554\u255D\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D"," \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551 \u255A\u2588\u2588\u2588\u2554\u255D \u2588\u2588\u2588\u2588\u2588\u2557 "," \u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2551 \u2588\u2588\u2554\u2588\u2588\u2557 \u2588\u2588\u2554\u2550\u2550\u255D "," \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2554\u255D \u2588\u2588\u2557\u2588\u2588\u2551 "," \u255A\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u255D "],g=[" _ _ _____ ","| | | | __ __ | ___|","| |_| | \\ \\/ / | |_ ","| _ | > < | _| ","|_| |_| /_/\\_\\ |_| "];function m(){if(process.platform==="win32")return!1;let e=(process.env.LC_ALL||process.env.LC_CTYPE||process.env.LANG||"").toLowerCase();return e===""||e==="c"||e==="posix"||!e.includes("utf-8")&&!e.includes("utf8")?!1:!/ja|ko|zh|_kr|_jp|_cn|_tw|_hk/.test(e)}function h(){return m()?u:g}var _="https://howtofix.id/cli";function p(e){let n=process.env.HOME??"",t=n!==""&&e.startsWith(n)?`~${e.slice(n.length)}`:e,o=t.split("/").filter(Boolean);return o.length>3?`\u2026/${o.slice(-2).join("/")}`:t}function f(e){let n=e.signedIn?d.filter(([t])=>t!=="/connect"):d;return[...h(),"",`${i} ${r} \u2014 a terminal coding agent. Describe the change you want and it reads, edits and runs the code in front of you.`,"",` working in ${p(e.cwd)}`,...e.note?[` session ${e.note}`]:[],"",...e.signedIn?[" already signed in to howtofix.id",""]:[],...n.map(([t,o])=>` ${t.padEnd(11)}${o}`),"",' Or just start typing. Every message goes to the model; anything beginning with "/" stays local.'].join(`
|
|
2
2
|
`)}function v(){return[{value:"connect",label:"Sign in to howtofix.id",description:"approve the sign-in in your browser"},{value:"ready",label:"I have a key \u2014 just give me the prompt",description:"drops you at the prompt; run /connect whenever you like"},{value:"release",label:"What's in this release",description:`opens the ${r} notes in your browser`}]}async function E(e,n,t){c(s).welcomeSeen||(l(s),t(`welcome to ${i}`,f(e)),!e.signedIn&&await new Promise(o=>{n("First run \u2014 how do you want to begin?",v(),a=>{a==="connect"&&e.runSlash("/connect"),a==="release"&&e.openExternal(_),o()},()=>o())}))}export{E as maybeShowWelcome};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as v}from"./chunk-7LA2AMZB.js";import{h as M,i as T}from"./chunk-
|
|
1
|
+
import{a as v}from"./chunk-7LA2AMZB.js";import{h as M,i as T}from"./chunk-DQZCH2E4.js";import{a as w}from"./chunk-UTYFLLSM.js";import{existsSync as H,mkdirSync as I,readFileSync as b}from"node:fs";import{join as k}from"node:path";var J="https://models.dev/api.json";var N=["anthropic","openai","google","deepseek","zai","xai","moonshotai","minimax","alibaba","xiaomi","meta","tencent","nvidia","venice","openrouter"];function _(n){return n.toLowerCase().replace(/[^a-z0-9]+/g,"")}function S(n){let e=n.split("/");return _(e[e.length-1]??n)}function q(n){let e=new Map,s=new Map;if(!n||typeof n!="object")return e;let t=n,r=c=>{let o=N.indexOf(c);return o===-1?N.length:o};for(let c of Object.keys(t).sort()){let o=t[c]?.models;if(!(!o||typeof o!="object"))for(let a of Object.keys(o)){let i=o[a],u=Number(i?.limit?.context);if(!Number.isFinite(u)||u<=0)continue;let l=_(a),f=r(c),d=s.get(l);if(d!==void 0&&d<=f)continue;let m=Number(i?.limit?.output);e.set(l,{contextWindow:Math.floor(u),maxTokens:Number.isFinite(m)&&m>0?Math.floor(m):void 0,reasoning:i?.reasoning===!0,vision:Array.isArray(i?.modalities?.input)&&i.modalities.input.includes("image")}),s.set(l,f)}}return e}function A(n,e){let s=_(e);if(!s)return;let t=n.get(s);if(t)return t;let r=S(e);for(let[c,o]of n)if(S(c)===r)return o;for(let[c,o]of n)if(c.endsWith(s)||s.endsWith(c))return o}function R(n){return`${n}/models-dev-cache.json`}function $(n){let e={};for(let[s,t]of n)e[s]=[t.contextWindow,t.maxTokens??0,t.reasoning?1:0,t.vision?1:0];return JSON.stringify(e)}function P(n){let e=new Map,s;try{s=JSON.parse(n)}catch{return e}if(!s||typeof s!="object")return e;for(let[t,r]of Object.entries(s)){if(!Array.isArray(r)||r.length<3)continue;let c=Number(r[0]),o=Number(r[1]);!Number.isFinite(c)||c<=0||e.set(t,{contextWindow:Math.floor(c),maxTokens:Number.isFinite(o)&&o>0?Math.floor(o):void 0,reasoning:r[2]===1||r[2]===!0,vision:r[3]===1||r[3]===!0})}return e}async function U(n){let e=n?.url??J,s=n?.fetchImpl??fetch,t=n?.timeoutMs??2e4,r=new AbortController,c=setTimeout(()=>r.abort(),t);try{let o=await s(e,{signal:r.signal,headers:{Accept:"application/json"}});if(!o.ok)return{ok:!1,message:`the model catalogue answered ${o.status}`};let a=q(await o.json());return a.size===0?{ok:!1,message:"the model catalogue was empty or in an unexpected shape"}:{ok:!0,index:a}}catch(o){return{ok:!1,message:o instanceof Error&&o.name==="AbortError"?`the model catalogue did not answer within ${Math.round(t/1e3)}s`:"could not reach the model catalogue"}}finally{clearTimeout(c)}}var x="https://api.howtofix.id/v1",ce=v,C=["howtocode","howtocode-free"];function ue(n){try{let s=JSON.parse(b(k(n,"models.json"),"utf8")).providers;return!s||typeof s!="object"?new Set:new Set(Object.keys(s))}catch{return new Set}}function le(){return{baseUrl:x,api:"openai-completions",headers:{[M]:T()}}}function de(n){let e=k(n,"models.json"),s;try{s=JSON.parse(b(e,"utf8"))}catch{return 0}let t=s.providers;if(!t||typeof t!="object")return 0;let r=0;for(let c of C){let o=t[c];if(!o||!Array.isArray(o.models))continue;let a=Y(o.models),i={...o.headers??{},[M]:T()},u=o.headers?.[M]!==i[M];a.changed===0&&!u||(o.models=a.models,o.headers=i,r+=a.changed===0?1:a.changed)}if(r===0)return 0;try{w(e,`${JSON.stringify(s,null,2)}
|
|
2
2
|
`)}catch{return 0}return r}var G=10080*60*1e3;async function F(n,e){let s=R(n),t=e?.now??Date.now(),r,c=0;try{let i=JSON.parse(b(s,"utf8"));typeof i?.entries=="string"&&(r=P(i.entries),c=Number(i.at)||0)}catch{r=void 0}if(r&&r.size>0&&t-c<G&&!e?.force)return{index:r};let a=await U({fetchImpl:e?.fetchImpl});if(!a.ok)return r&&r.size>0?{index:r,message:a.message}:{index:new Map,message:a.message};try{I(n,{recursive:!0}),w(s,`${JSON.stringify({at:t,entries:$(a.index)})}
|
|
3
3
|
`)}catch{}return{index:a.index}}async function fe(n,e){let s=k(n,"models.json"),t;try{t=JSON.parse(b(s,"utf8"))}catch{return{changed:0}}let r=t.providers;if(!r||typeof r!="object")return{changed:0};let{index:c,message:o}=await F(n,e);if(c.size===0&&!e?.prices&&!e?.tiers)return{changed:0,message:o};let a=0;for(let i of C){let u=r[i];if(!u||!Array.isArray(u.models))continue;let l=Z(u.models,c,e?.prices,e?.tiers);l.changed!==0&&(u.models=l.models,a+=l.changed)}if(a>0)try{w(s,`${JSON.stringify(t,null,2)}
|
|
4
4
|
`)}catch{return{changed:0,message:"the models file could not be written"}}return{changed:a,message:o}}var B=3e5;function me(n){let e=k(n,"settings.json"),s={};try{let t=b(e,"utf8"),r=JSON.parse(t);r&&typeof r=="object"&&!Array.isArray(r)&&(s=r)}catch{if(H(e))return!1}if("httpIdleTimeoutMs"in s)return!1;s.httpIdleTimeoutMs=B;try{I(n,{recursive:!0}),w(e,`${JSON.stringify(s,null,2)}
|
package/dist/cli-auth.js
CHANGED
|
@@ -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-DQZCH2E4.js";import"./chunk-SBWZZCV5.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};
|
package/dist/main-app.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{b as q,d as Q,e as Z}from"./chunk-EZNNALD3.js";import"./chunk-7LA2AMZB.js";import{e as J,f as K}from"./chunk-
|
|
2
|
+
import{b as q,d as Q,e as Z}from"./chunk-EZNNALD3.js";import"./chunk-7LA2AMZB.js";import{e as J,f as K}from"./chunk-DQZCH2E4.js";import{c as z}from"./chunk-PH72JBBL.js";import{a as V,b as F}from"./chunk-MCAAX33K.js";import{a as d,b as y}from"./chunk-SBWZZCV5.js";import{H as _,P as Y}from"./chunk-5FIFNXLT.js";import"./chunk-UTYFLLSM.js";import{j as X}from"./chunk-MVVEYKN6.js";import"./chunk-WOT6VMZA.js";import{existsSync as qe,mkdirSync as Qe,readdirSync as pe,statSync as Ze,writeFileSync as et}from"node:fs";import{join as N}from"node:path";var ee={rpc:!0,acp:!0},te={off:!0,minimal:!0,low:!0,medium:!0,high:!0,xhigh:!0,max:!0},se={suggest:!0,"auto-edit":!0,"full-auto":!0},oe={text:!0,json:!0,"stream-json":!0};function Be(i){let e=Number(i);if(!Number.isFinite(e)||e<=0)throw new Error(`--max-budget-usd needs a positive number of dollars, got '${i}'`);return e}function E(i,e,t){let s=i[e];if(s?.includes("="))return s.slice(s.indexOf("=")+1);let a=i[e+1];if(!a||a.startsWith("-"))throw new Error(`${t} needs a value`);return i.splice(e+1,1),a}function ne(i){let e={print:!1,continueSession:!1,noSession:!1,help:!1,version:!1,update:!1,checkUpdate:!1,outputFormat:"text",dangerouslySkipPermissions:!1,sandbox:!1,prompt:""},t=[],s=[...i];s[0]==="resume"&&s[1]&&!s[1].startsWith("-")&&(e.resumeId=s[1],s.splice(0,2));for(let a=0;a<s.length;a++){let o=s[a]??"";if(o==="--"){t.push(...s.slice(a+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=E(s,a,"--session");else if(o==="-m"||o==="--model"||o.startsWith("--model="))e.model=E(s,a,"--model");else if(o==="--thinking"||o.startsWith("--thinking="))e.thinking=E(s,a,"--thinking");else if(o==="--approval"||o.startsWith("--approval="))e.approval=E(s,a,"--approval");else if(o==="--output-format"||o.startsWith("--output-format="))e.outputFormat=E(s,a,"--output-format");else if(o==="--max-budget-usd"||o.startsWith("--max-budget-usd="))e.maxBudgetUsd=Be(E(s,a,"--max-budget-usd"));else if(o==="--mode"||o.startsWith("--mode=")){let u=E(s,a,"--mode");if(!ee[u])throw new Error(`--mode must be one of: ${Object.keys(ee).join(", ")}`);e.mode=u}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}`);t.push(o)}}if(e.thinking&&!te[e.thinking])throw new Error(`thinking must be one of: ${Object.keys(te).join(", ")}`);if(e.approval&&!se[e.approval])throw new Error(`approval must be one of: ${Object.keys(se).join(", ")}`);if(!oe[e.outputFormat])throw new Error(`output-format must be one of: ${Object.keys(oe).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=t.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 R(){return`${d} ${y}
|
|
3
3
|
coding agent. layout is a workbench, not a chat log.
|
|
4
4
|
|
|
5
5
|
usage:
|
|
@@ -93,10 +93,10 @@ token; /login takes another provider's key.
|
|
|
93
93
|
`}function He(i,e=!1){let{message:t,hint:s}=V(i),a=s?`${t}
|
|
94
94
|
${s}`:t;if(!e)return a;let o=i instanceof Error?i.stack:void 0;return o&&o.includes(`
|
|
95
95
|
`)?`${a}
|
|
96
|
-
${o}`:a}function re(i,e){let t=e?.debug??process.env.HOWTOCODE_DEBUG==="1",s=e?.exit??(o=>process.exit(o)),a=o=>{console.error(`${i}: ${He(o,t)}`),s(1)};process.on("uncaughtException",a),process.on("unhandledRejection",a)}import{connect as We}from"node:net";var x={HANDSHAKE:0,FRAME:1,CLOSE:2,PING:3,PONG:4},de="1560641616753066135",Ge="https://discord.howtofix.id",ie=10,Je=1e4,ae=1e3,Ke=3e4,Ve=3e4,Ye=15e3;function le(i){let e=i.cwd.split(/[\\/]/).filter(Boolean).pop()??i.cwd,t=i.largeImage?.trim();return{details:"HowToCode",state:`${i.modelLabel} \u2022 ${e}`.slice(0,128),timestamps:{start:i.startedAt??Date.now()},buttons:[{label:"Join Discord",url:i.inviteUrl?.trim()||Ge}],...t?{assets:{large_image:t,large_text:"HowToCode"}}:{}}}function Xe(i=process.platform){if(i==="win32")return Array.from({length:ie},(s,a)=>`\\\\?\\pipe\\discord-ipc-${a}`);let e=process.env.XDG_RUNTIME_DIR??process.env.TMPDIR??process.env.TMP??"/tmp";return[e,`${e}/app/com.discordapp.Discord`,`${e}/snap.discord`,`${e}/.flatpak/dev.vencord.Vesktop`,`${e}/.flatpak/com.discordapp.Discord`].flatMap(s=>Array.from({length:ie},(a,o)=>`${s.replace(/\/+$/,"")}/discord-ipc-${o}`))}function ce(i,e){let t=Buffer.from(JSON.stringify(e??{}),"utf8"),s=Buffer.allocUnsafe(8+t.length);return s.writeUInt32LE(i,0),s.writeUInt32LE(t.length,4),t.copy(s,8),s}function ze(i){let e=[],t=i;for(;t.length>=8;){let s=t.readUInt32LE(0),a=t.readUInt32LE(4);if(t.length<8+a)break;let o=t.subarray(8,8+a).toString("utf8");t=t.subarray(8+a);let
|
|
97
|
-
${R()}`),process.exitCode=2;return}if(I.print&&!I.prompt){console.error(`${d}: --print needs a prompt`),process.exitCode=2;return}let{repairGatewayModels:he,ensureGatewaySettings:fe,repairModelFacts:ge,syncGatewayModelsOnStart:we,checkAccount:
|
|
98
|
-
`)}let w,S,je=()=>{if(
|
|
99
|
-
`)}process.exitCode=1;return}let b=l.session.state.messages.at(-1),g=
|
|
96
|
+
${o}`:a}function re(i,e){let t=e?.debug??process.env.HOWTOCODE_DEBUG==="1",s=e?.exit??(o=>process.exit(o)),a=o=>{console.error(`${i}: ${He(o,t)}`),s(1)};process.on("uncaughtException",a),process.on("unhandledRejection",a)}import{connect as We}from"node:net";var x={HANDSHAKE:0,FRAME:1,CLOSE:2,PING:3,PONG:4},de="1560641616753066135",Ge="https://discord.howtofix.id",ie=10,Je=1e4,ae=1e3,Ke=3e4,Ve=3e4,Ye=15e3;function le(i){let e=i.cwd.split(/[\\/]/).filter(Boolean).pop()??i.cwd,t=i.largeImage?.trim();return{details:"HowToCode",state:`${i.modelLabel} \u2022 ${e}`.slice(0,128),timestamps:{start:i.startedAt??Date.now()},buttons:[{label:"Join Discord",url:i.inviteUrl?.trim()||Ge}],...t?{assets:{large_image:t,large_text:"HowToCode"}}:{}}}function Xe(i=process.platform){if(i==="win32")return Array.from({length:ie},(s,a)=>`\\\\?\\pipe\\discord-ipc-${a}`);let e=process.env.XDG_RUNTIME_DIR??process.env.TMPDIR??process.env.TMP??"/tmp";return[e,`${e}/app/com.discordapp.Discord`,`${e}/snap.discord`,`${e}/.flatpak/dev.vencord.Vesktop`,`${e}/.flatpak/com.discordapp.Discord`].flatMap(s=>Array.from({length:ie},(a,o)=>`${s.replace(/\/+$/,"")}/discord-ipc-${o}`))}function ce(i,e){let t=Buffer.from(JSON.stringify(e??{}),"utf8"),s=Buffer.allocUnsafe(8+t.length);return s.writeUInt32LE(i,0),s.writeUInt32LE(t.length,4),t.copy(s,8),s}function ze(i){let e=[],t=i;for(;t.length>=8;){let s=t.readUInt32LE(0),a=t.readUInt32LE(4);if(t.length<8+a)break;let o=t.subarray(8,8+a).toString("utf8");t=t.subarray(8+a);let u;try{u=JSON.parse(o)}catch{u={raw:o}}e.push({op:s,payload:u})}return{frames:e,rest:t}}var M=class{clientId;activity;candidates;log;socket;buffer=Buffer.alloc(0);ready=!1;stopped=!1;reconnectTimer;pingTimer;handshakeTimer;reconnectDelay=ae;lastSent=0;applied="";constructor(e){this.clientId=e.clientId,this.activity=e.activity,this.candidates=e.candidates??Xe(),this.log=e.log??(()=>{})}start(){this.stopped||this.socket!==void 0||this.reconnectTimer!==void 0||this.clientId.trim().length!==0&&this.connectToAny(0)}update(e){this.activity=e,this.flush(!1)}stop(){if(this.stopped=!0,this.ready=!1,clearTimeout(this.reconnectTimer),clearTimeout(this.handshakeTimer),clearInterval(this.pingTimer),this.reconnectTimer=void 0,this.handshakeTimer=void 0,this.pingTimer=void 0,this.socket){try{this.socket.write(ce(x.CLOSE,{code:1e3,message:"HowToCode stopped"})),this.socket.end()}catch{}this.socket.destroy(),this.socket=void 0}}connectToAny(e){if(this.stopped)return;if(e>=this.candidates.length){this.log("Discord IPC socket not found; presence disabled"),this.scheduleReconnect();return}let t=this.candidates[e],s=We(t);s.once("connect",()=>{s.removeAllListeners("error"),this.attach(s)}),s.once("error",()=>{s.destroy(),this.connectToAny(e+1)})}attach(e){this.socket=e,this.buffer=Buffer.alloc(0),this.ready=!1,e.on("data",t=>this.onData(t)),e.on("close",()=>this.onDrop("Discord closed the socket")),e.on("error",t=>this.onDrop(t.message)),this.handshakeTimer=setTimeout(()=>this.onDrop("Discord handshake timed out"),Je),this.write(x.HANDSHAKE,{v:1,client_id:this.clientId})}onData(e){this.buffer=Buffer.concat([this.buffer,e]);let t=ze(this.buffer);this.buffer=t.rest;for(let s of t.frames)this.onFrame(s.op,s.payload)}onFrame(e,t){if(e===x.PING){this.write(x.PONG,t);return}if(e===x.CLOSE){let o=typeof t=="object"&&t!==null&&"code"in t?t.code:void 0;this.onDrop(`Discord closed the session${o===4e3?" (unknown application id)":""}`);return}if(e!==x.FRAME||typeof t!="object"||t===null)return;let s="evt"in t?t.evt:void 0,a="cmd"in t?t.cmd:void 0;if(s==="READY"){clearTimeout(this.handshakeTimer),this.handshakeTimer=void 0,this.ready=!0,this.reconnectDelay=ae,this.applied="",this.startPing(),this.flush(!0);return}a==="SET_ACTIVITY"&&this.log("presence updated")}write(e,t){let s=this.socket;if(!s||s.destroyed)return!1;try{return s.write(ce(e,t)),!0}catch(a){return this.onDrop(a instanceof Error?a.message:String(a)),!1}}startPing(){clearInterval(this.pingTimer),this.pingTimer=setInterval(()=>this.write(x.PING,{t:Date.now()}),Ve),this.pingTimer.unref?.()}flush(e){if(!this.ready||this.stopped)return;let t=Date.now();if(!e&&t-this.lastSent<Ye)return;let s=JSON.stringify(this.activity);s!==this.applied&&(this.applied=s,this.lastSent=t,this.write(x.FRAME,{cmd:"SET_ACTIVITY",args:{pid:process.pid,activity:this.activity},nonce:`howtocode-${t}`}))}onDrop(e){this.ready=!1,clearTimeout(this.handshakeTimer),clearInterval(this.pingTimer),this.handshakeTimer=void 0,this.pingTimer=void 0;let t=this.socket;this.socket=void 0,t&&(t.removeAllListeners(),t.destroy()),!this.stopped&&(this.log(`Discord presence disconnected: ${e}`),this.scheduleReconnect())}scheduleReconnect(){if(this.stopped||this.reconnectTimer!==void 0)return;let e=this.reconnectDelay;this.reconnectDelay=Math.min(this.reconnectDelay*2,Ke),this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.connectToAny(0)},e),this.reconnectTimer.unref?.()}};function tt(){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 st(){process.stdout.on("error",i=>{throw i.code==="EPIPE"&&process.exit(0),i})}function ot(){let i=N(_,".welcomed");if(!qe(i)){try{Qe(_,{recursive:!0}),et(i,y)}catch{return}console.error(`${d} ${y} installed. Docs: https://howtofix.id/code`),console.error("Continue the last session here with: howtocode -c")}}async function ue(){J()||(console.error(`${d}: this build's CLI signing key (${K()}) does not match the key the panel verifies against, so sign-in will be refused.`),process.exitCode=1)}async function nt(){st(),Y();let i=performance.now(),e=tt();if("error"in e){console.error(`${d}: ${e.error}`),process.exitCode=1;return}let t=e.cwd,s=process.env.HXF_FAKE_NODE??process.versions.node,[a,o]=s.split(".").map(n=>Number.parseInt(n,10));if(!Number.isFinite(a)||a<22||a===22&&Number.isFinite(o)&&o<19){console.error(`${d}: Node ${s} 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 n=process.argv.slice(2);if(n.some(c=>c==="-h"||c==="--help")){console.log(R());return}if(n.some(c=>c==="-v"||c==="--version")){console.log(`${d} ${y}`);return}return}let u=process.argv.slice(2);if(u[0]==="doctor"||u[0]==="models"||u[0]==="sessions"){let n=u[0];try{let c=await import("./chunk-MSEVYMAA.js");n==="doctor"?process.exitCode=await c.runDoctor():n==="models"?process.exitCode=c.runModels():process.exitCode=c.runSessions(u.slice(1))}catch(c){F(d,n,c),process.exitCode=1}return}if(u.some(n=>n==="-v"||n==="--version")){await ue(),console.log(`${d} ${y}`);return}if(u[0]==="browser-relay"&&u[1]==="native-host"){let{runNativeHost:n}=await import("./chunk-KBZERZVM.js");await n();return}let me=u[0]==="acp"?["--acp",...u.slice(1)]:u,I;try{I=ne(me)}catch(n){let c=n instanceof Error?n.message:String(n);console.error(`${d}: ${c}
|
|
97
|
+
${R()}`),process.exitCode=2;return}if(I.print&&!I.prompt){console.error(`${d}: --print needs a prompt`),process.exitCode=2;return}let{repairGatewayModels:he,ensureGatewaySettings:fe,repairModelFacts:ge,syncGatewayModelsOnStart:we,checkAccount:ve,fetchGatewayPrices:ye,readProviderKey:be}=await import("./chunk-6MW4XQH2.js"),{tiersFrom:ke,writeReachable:xe}=await import("./chunk-XBVWQC7P.js"),{readCliCredential:Se,renewCliCredentialIfNeeded:Te}=await import("./chunk-42J3SVVD.js"),{AGENT_DIR:f,REACHABLE_CACHE_PATH:_e}=await import("./chunk-336TZTEK.js"),{readCachedPrices:Ee,writeCachedPrices:Ce}=await import("./chunk-A3LZMZ3C.js"),L=he(f);L>0&&console.error(`${d}: repaired ${L} howtocode model(s) that the gateway would have rejected`);let C,P,D=new Map,$=Ee(f);if($){C=$.prices;for(let[n,c]of $.groups)D.set(n,c)}try{let n=Se(f),c=n?(await Te(f,n)).credential.accessToken:be(f,"howtocode");if(c){let[h,m]=await Promise.all([$?Promise.resolve(C??new Map):ye(c,{groups:D}),ve(c)]);!$&&h.size>0&&(C=h,Ce(f,h,D)),m.ok&&(P=m.models)}}catch{}let U=ke(D),A=await ge(f,{...C?{prices:C}:{},...U.size>0?{tiers:U}:{}});if(A.changed>0?console.error(`${d}: filled in the context window, reasoning flag and price for ${A.changed} model(s)`):A.message&&console.error(`${d}: model catalogue unavailable (${A.message}); context windows stay at their conservative defaults`),fe(f)&&console.error(`${d}: set httpIdleTimeoutMs in settings.json so a stalled provider recovers instead of hanging`),P){xe(_e,P);try{let n=await we(f,P,C);n.added>0&&console.error(`${d}: added ${n.added} model(s) this account can now reach`)}catch{}}let r=I;if(r.help){console.log(R());return}if(r.version){await ue(),console.log(`${d} ${y}`);return}if(r.sandbox&&!process.env.HOWTOCODE_SANDBOXED){let{detectSandbox:n,enterSandbox:c,describeSandbox:h}=await import("./chunk-GQYIIDKK.js"),m=n();if(!m){console.error(`${d}: --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(h(m)),process.exitCode=c(m,{cwd:t,agentDir:_,argv:[process.execPath,...process.argv.slice(1)]});return}let{installProxy:$e}=await import("./chunk-WKUJ7CFO.js");$e(_);let{retireRobloxBridge:Ie}=await import("./chunk-ULXYWUXZ.js");if(Ie(_),r.update||r.checkUpdate){let{PACKAGE_NAME:n,checkForUpdate:c,installUpdate:h,isInstalledCopy:m}=await import("./chunk-LYLJZVZ7.js"),w=await c(y);if(!w.latest){console.error(`${d}: ${w.message}`),process.exitCode=r.update?1:0;return}if(console.log(w.message),r.checkUpdate||!w.available)return;if(!m()){console.error(`${d}: this copy was not installed by npm, so npm cannot replace it. install it with: npm install -g ${n}`),process.exitCode=1;return}let S=await h({version:w.latest});console.log(S.message),S.ok||(process.exitCode=1);return}let j=process.argv.slice(2);if(j[0]==="preset"){let{runPresetCommand:n}=await import("./chunk-RJYOUCLJ.js");process.exitCode=n(j.slice(1));return}let{expandFileReferences:Pe}=await import("./chunk-TSEKPGK4.js"),{isApprovalMode:De,setApprovalMode:Ae,setDangerousBypass:Oe,isDangerousBypass:Re}=await import("./chunk-4SK7TRJW.js"),{openSession:Me}=await import("./chunk-EMFKTIYL.js");Ae(r.approval&&De(r.approval)?r.approval:"full-auto");let{readWorkbenchSettings:B}=await import("./chunk-UDX555SX.js");if((r.dangerouslySkipPermissions||B(f).skipPermissions)&&Oe(!0),Re()&&console.error(`${d}: 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.`),r.mode){let{serveProtocol:n}=await import("./chunk-NARUJ2JE.js");await n(r.mode,{cwd:t,model:r.model,thinking:r.thinking});return}let H=n=>Me({cwd:t,model:r.model,thinking:r.thinking,continueSession:n.continueSession??!1,noSession:n.noSession??!1,sessionPath:n.sessionPath,interactive:!r.print});if(r.resumeId&&!r.sessionPath){let n=N(_,"sessions"),c=[];try{for(let h of pe(n))for(let m of pe(N(n,h))){if(!m.endsWith(".jsonl")||!m.includes(r.resumeId))continue;let w=N(n,h,m);try{c.push({path:w,mtime:Ze(w).mtimeMs})}catch{}}}catch{}if(c=c.sort((h,m)=>m.mtime-h.mtime),c.length===0){console.error(`${d}: no stored session matches '${r.resumeId}'. Run 'howtocode -c' to continue the latest one in this folder.`),process.exitCode=1;return}c.length>1&&console.error(`${d}: '${r.resumeId}' matches ${c.length} sessions; using the newest (${c[0].path}).`),r.sessionPath=c[0].path}let l=await H({continueSession:r.continueSession,sessionPath:r.sessionPath,noSession:r.noSession||r.print});if(r.print&&l.note&&console.error(l.note),r.maxBudgetUsd!==void 0&&!l.priced){console.error(`${d}: ${Z(l.modelLabel,f)}`),await l.dispose(),process.exitCode=2;return}if(r.print){let n=r.prompt.trimStart();if(n.startsWith("/")){let v=n.slice(1).split(/\s+/)[0]??"",{skillInvocation:O}=await import("./chunk-E2UZLMQH.js"),T=l.session.resourceLoader.getSkills().skills.map(g=>g.name);if(!(O(n,T)!==void 0)){let{slashCommands:g}=await import("./chunk-WXNRNAQ6.js");if(g(l.session).some(p=>p.name===v)){console.error(`${d}: /${v} runs in the TUI only \u2014 --print sends prompts straight to the model. Run \`howtocode\` without --print for interactive commands.`),await l.dispose(),process.exitCode=2;return}}}let c=r.outputFormat==="stream-json",h=r.outputFormat==="json",m=c||h;if(c){let v={type:"system",subtype:"init",cwd:t,session_id:l.session.sessionId,model:l.modelLabel,output_format:r.outputFormat,max_budget_usd:r.maxBudgetUsd??null,dangerously_skip_permissions:r.dangerouslySkipPermissions,cli_version:y};process.stdout.write(`${JSON.stringify(v)}
|
|
98
|
+
`)}let w,S,je=()=>{if(r.maxBudgetUsd===void 0||S!==void 0)return;let v=l.session.getSessionStats().cost;v>r.maxBudgetUsd&&(S={spent:v},l.session.abort())};try{let v,O=z();if(w=l.session.subscribe(p=>{if(c){let k=O.line(p);k!==void 0&&process.stdout.write(k)}if(p.type==="turn_end"&&p.message?.role==="assistant"){let k=p.message;k.stopReason==="error"||k.stopReason==="aborted"||k.errorMessage?v={stopReason:k.stopReason??"error",errorMessage:k.errorMessage}:v=void 0}je()}),await l.session.prompt(Pe(r.prompt,t)),c){let p=O.finish();p!==void 0&&process.stdout.write(p)}let T=X(l.session.getLastAssistantText()??"");if(S){if(console.error(`${d}: ${Q(S.spent,r.maxBudgetUsd)}`),m){let p=l.session.getSessionStats();process.stdout.write(`${JSON.stringify({type:"result",subtype:"error_max_budget_usd",is_error:!0,result:T,session_id:l.session.sessionId,duration_ms:Math.round(performance.now()-i),num_turns:p.assistantMessages,total_cost_usd:p.cost,usage:{input_tokens:p.tokens.input,output_tokens:p.tokens.output,cache_read_input_tokens:p.tokens.cacheRead,cache_creation_input_tokens:p.tokens.cacheWrite}})}
|
|
99
|
+
`)}process.exitCode=1;return}let b=l.session.state.messages.at(-1),g=v??(b?.role==="assistant"&&(b.stopReason==="error"||b.stopReason==="aborted"||b.errorMessage)?{stopReason:b.stopReason??"error",errorMessage:b.errorMessage}:void 0);if(m){let p=l.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:T,session_id:l.session.sessionId,duration_ms:Math.round(performance.now()-i),num_turns:p.assistantMessages,total_cost_usd:p.cost,usage:{input_tokens:p.tokens.input,output_tokens:p.tokens.output,cache_read_input_tokens:p.tokens.cacheRead,cache_creation_input_tokens:p.tokens.cacheWrite},stop_reason:g?.stopReason??(b?.role==="assistant"?b.stopReason:void 0)})}
|
|
100
100
|
`)}else process.stdout.write(T.endsWith(`
|
|
101
101
|
`)?T:`${T}
|
|
102
|
-
`);if(g&&(process.exitCode=1,g.errorMessage)){console.error(`${d}: ${g.errorMessage}`);let p=q(g.errorMessage);p!==void 0&&console.error(`${d}: ${p}`)}}finally{w?.(),await l.dispose()}return}if(!process.stdin.isTTY||!process.stdout.isTTY){console.error(`${d}: interactive mode needs a terminal. use --print for pipes.`),await l.dispose(),process.exitCode=2;return}ot();let{runWorkbench:Ne}=await import("./chunk-
|
|
102
|
+
`);if(g&&(process.exitCode=1,g.errorMessage)){console.error(`${d}: ${g.errorMessage}`);let p=q(g.errorMessage);p!==void 0&&console.error(`${d}: ${p}`)}}finally{w?.(),await l.dispose()}return}if(!process.stdin.isTTY||!process.stdout.isTTY){console.error(`${d}: interactive mode needs a terminal. use --print for pipes.`),await l.dispose(),process.exitCode=2;return}ot();let{runWorkbench:Ne}=await import("./chunk-WXNRNAQ6.js"),{autoUpdateEnabled:Fe,isInstalledCopy:Le}=await import("./chunk-LYLJZVZ7.js"),Ue=Le()&&Fe(`${f}/settings.json`),W=process.env.HOWTOCODE_DISCORD_DISABLE==="1"?"":process.env.HOWTOCODE_DISCORD_CLIENT_ID?.trim()||B(f).discordClientId||de,G=W?new M({clientId:W,activity:le({modelLabel:l.modelLabel,cwd:t,largeImage:process.env.HOWTOCODE_DISCORD_LARGE_IMAGE})}):void 0;G?.start();try{await Ne({cwd:t,modelLabel:l.modelLabel,session:l.session,dispose:()=>l.dispose(),setCompressToolOutput:l.setCompressToolOutput,initialPrompt:r.prompt||void 0,note:l.note,approval:r.approval,maxBudgetUsd:r.maxBudgetUsd,update:Ue?{current:y,install:!0}:void 0,reopen:H})}finally{G?.stop()}}re(d);nt().catch(i=>{F(d,void 0,i),process.exitCode=1});
|