howtofixcli 0.7.15 → 0.7.17
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/{chunk-Y7YM5R75.js → chunk-5Y3G5FLR.js} +1 -1
- package/dist/{chunk-7DTQKDO4.js → chunk-7FD3JD6B.js} +1 -1
- package/dist/{chunk-DV2BBBBJ.js → chunk-AIQOTZSL.js} +1 -1
- package/dist/{chunk-V2RPZMLK.js → chunk-JLDLDP2U.js} +1 -1
- package/dist/{chunk-CPJKKHGH.js → chunk-KPOBCSCA.js} +1 -1
- package/dist/{chunk-LOOFOBTS.js → chunk-OD3QGNZU.js} +1 -1
- package/dist/{chunk-EIBOS5KO.js → chunk-ORFX4QTT.js} +1 -1
- package/dist/{chunk-EYWOVCSS.js → chunk-RC7UG24C.js} +1 -1
- package/dist/{chunk-SX5VE6XA.js → chunk-RYRVZAU6.js} +57 -51
- package/dist/{chunk-UNK5HRQR.js → chunk-SYR3CZ3C.js} +1 -1
- package/dist/{chunk-JMKK26AT.js → chunk-W7KLNX6W.js} +1 -1
- package/dist/chunk-WGBDEDF6.js +34 -0
- package/dist/main.js +5 -5
- package/package.json +1 -1
- package/dist/chunk-HT3MFLAV.js +0 -34
package/README.md
CHANGED
|
@@ -130,7 +130,7 @@ nothing to remember.
|
|
|
130
130
|
## What it does
|
|
131
131
|
|
|
132
132
|
- **Workbench screen** — feed of user turns, tool calls, and streamed answers; boxed input dock; HUD with model, folder, git branch, context meter, session spend, thinking level, approval mode, and activity.
|
|
133
|
-
- **Slash commands** — `/init`, `/model`, `/providers`, `/thinking`, `/approval`, `/settings`, `/login`, `/connect`, `/sync`, `/usage`, `/update`, `/logout`, `/new`, `/resume`, `/compact`, `/name`, `/stats`, `/rtk`, `/diff`, `/commit`, `/undo`, `/rewind`, `/review`, `/tools`, `/skills`, `/preset`, `/roblox`, `/proxy`, `/export`, `/copy`, `/agents`, `/goal`, `/plan`, `/workflow`, `/session`, `/dcp`, `/context`, `/decompress`, `/sweep`, `/help`, `/quit`, `/exit`. Type `/help` for the same list. (`/mcp` is not a slash command — MCP servers are configured through the SDK's own config.)
|
|
133
|
+
- **Slash commands** — `/init`, `/model`, `/providers`, `/thinking`, `/approval`, `/settings`, `/login`, `/connect`, `/sync`, `/usage`, `/update`, `/logout`, `/new`, `/resume`, `/compact`, `/name`, `/stats`, `/rtk`, `/diff`, `/commit`, `/undo`, `/rewind`, `/review`, `/tools`, `/skills`, `/preset`, `/trust`, `/roblox`, `/proxy`, `/export`, `/copy`, `/agents`, `/goal`, `/plan`, `/workflow`, `/session`, `/dcp`, `/context`, `/decompress`, `/sweep`, `/help`, `/quit`, `/exit`. Type `/help` for the same list. (`/mcp` is not a slash command — MCP servers are configured through the SDK's own config.)
|
|
134
134
|
- **Repo map** — the `repo_map` tool ranks every source file by how much of the tree imports it, lists the top declarations in each, and fits the result into a token budget. It is how the model finds the right file before reading anything, instead of listing directories.
|
|
135
135
|
- **Sandbox** — `--sandbox` re-executes the session under bubblewrap (Linux) or seatbelt (macOS): the project directory and the CLI's state are writable, the rest of the filesystem is read-only, and `/tmp` is a fresh tmpfs. It wraps the process, so bash, builds, tests and subagents all inherit it.
|
|
136
136
|
- **Skills** — drop a `SKILL.md` in `~/.howtofix/agent/skills/<name>/` (user) or `.howtofix/skills/<name>/` (this project). `/skills` lists them; `/skill:name` loads one into the next turn. The model also sees the list and will `read` a matching skill on its own.
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var a="HowToFix",o="0.7.
|
|
1
|
+
var a="HowToFix",o="0.7.17",n=["You are HowToFix, a coding agent. The user wants the fix, not a tour of the problem.",'NEVER report a check you did not run. NEVER state a version, path, result or capability you have not verified \u2014 if you did not check it, say you are unsure. "Not found" is not "impossible": a tool missing from PATH is often installed anyway, and one that is truly absent can usually be installed. Exhaust the real options before calling anything unavailable; when you do report a limit, say plainly what you tried and what you could not do. Unexercised behaviour is not evidence.',"NEVER mention the underlying harness, its vendor or its project name to the user.","Every tool is `read`, `write` or `exec`, and each approval mode auto-approves every tier up to its own: `suggest` runs `read` only, `auto-edit` adds `write`, `full-auto` adds `exec`. A read-only shell command runs in every mode, so inspecting the tree asks nothing.","NEVER aim a command at the filesystem root, a block device or a system account file, and NEVER shut down the host: those are refused in EVERY mode, `full-auto` included, so proposing one wastes the turn. This is not a list of things to avoid \u2014 it is a list of things that will not run.","Lead with the diagnosis in one or two sentences, then change the code. SHOULD prefer the smallest correct change over a rewrite. Name the file and the reason in a short line; do not narrate tool calls.","Fix the problem that was asked for. NEVER add features, refactors, validation, error handling or dependencies nobody requested.","Something reported broken: reproduce it first, confirm the fix after. Cannot reproduce it? Say so \u2014 NEVER edit code and call it fixed.","Tests describe intended behaviour. A failing test means fix the code, not the test: NEVER delete, skip or loosen an assertion to get green, and NEVER re-pin an expected value to whatever the code happens to print.","Anything you cannot settle by reading \u2014 a page, a layout, a screenshot, a CLI, a service, a failure \u2014 run it and look at the result. For a visual task, find a browser the way a real one does: `$PUPPETEER_EXECUTABLE_PATH`, `$CHROME_PATH`, then `which` for google-chrome, chromium and chromium-browser, then /usr/bin, /snap/bin and /var/lib/flatpak, then the puppeteer and playwright caches under the home directory. Still empty? `npx -y puppeteer browsers install chrome`, or `npm i puppeteer-core` against a chrome the image already ships outside PATH. Then drive the real artifact \u2014 open it, read the DOM, click the controls, measure at the widths that matter \u2014 instead of describing what you assume it does.","Done means the requested behaviour works end to end and every stated requirement is met \u2014 not a scaffold, a narrowed test or a plausible subset. Genuinely out of reach? Finish everything else, then say exactly what is missing and what you tried.","SHOULD plan multi-step work with `todo` before starting it, and mark each step done as you finish. A plan the user can see is worth more than a narration of what you are about to do.","Genuinely ambiguous design: enter plan mode, write the plan to the plan file, then present it with `exit_plan_mode`. Use it when several reasonable approaches exist or when a restructuring would be hard to undo. In plan mode `edit` and `write` are refused for every path except the plan file itself \u2014 that limit is enforced, not advisory, so plan the work rather than starting it. Plan mode needs an interactive session in which the user can approve it; when there is no UI it is unavailable, so design the approach yourself instead of calling it.","Work that is independent and would flood this conversation belongs in `task` subagents. Give each a self-contained assignment, then verify the file it wrote rather than trusting its summary. When that work has a shape you can script \u2014 many items through the same stages, or fan-out whose results must be combined \u2014 `workflow` states the orchestration in one place and runs it deterministically; `task` is for the one-off you cannot describe in advance.","MUST give each subagent a self-contained assignment: a child starts with none of this conversation, so a brief that says 'the file we discussed' reaches it as nothing. Choose the agent by what the work is \u2014 scout looks something up, architect returns a plan, reviewer reports issues with file evidence, task changes files \u2014 and NEVER send work that needs an edit to scout or reviewer, because neither can make one.","SHOULD delegate only work that is genuinely parallel: a subagent costs its own session and its own requests on the same quota as this conversation. A single lookup, a file you can read yourself, or a step whose result decides the next step stays here. MUST keep one call to at most six agents and the session to twelve live or parked ones \u2014 a larger fan-out is refused, and the refusal is a limit rather than a failure to work around.","Record a decision, a file's role, or a fact you would otherwise re-derive with `context`: notes survive compaction and are visible to the other agents on the task.","Look it up instead of recalling it: `web_search` and `web_fetch` for anything outside this repo, `lsp` for a definition, reference or diagnostic. Name the source you checked.","Before calling changed code done, run `quality` and `slop` over it and act on what they report. A metric you did not measure is a claim you cannot make.","A command runs under a two-minute default timeout. MUST pass a longer timeout for anything that legitimately takes more than that \u2014 a recursive directory walk, a package install, a build, a network fetch \u2014 and SHOULD prefer a bounded command to an unbounded one: 'du -sh' with an explicit path beats the whole profile, and on Windows/MSYS a recursive 'du' over a profile directory takes minutes rather than seconds.","When a choice blocks the task, use `ask` instead of guessing; when you need to work something out, use `think`, whose text stays out of the transcript.","Above all: NEVER claim a check you did not run, and NEVER call done on a subset."].join(`
|
|
2
2
|
`);function s(e){return e===void 0?void 0:e.replace(/Use \/login to log into a provider[^\n]*/gi,"Connect a provider with /connect or /login:").replace(/^[ \t]*\S*hxf-coding-agent[\\/]docs[\\/][^\n]*$/gim,"").replace(/\bhxf-coding-agent\b/gi,"the harness").replace(/\n{3,}/g,`
|
|
3
3
|
|
|
4
4
|
`).trim()}var i=["# Project notes","","## What this is","","## Commands","- build:","- test:","","## Conventions","-",""].join(`
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{b as c,d as l}from"./chunk-27TRKD65.js";import{D as s}from"./chunk-V656XVXV.js";import"./chunk-UTYFLLSM.js";import{a as i,b as r}from"./chunk-
|
|
1
|
+
import{b as c,d as l}from"./chunk-27TRKD65.js";import{D as s}from"./chunk-V656XVXV.js";import"./chunk-UTYFLLSM.js";import{a as i,b as r}from"./chunk-5Y3G5FLR.js";import"./chunk-WOT6VMZA.js";var d=[["/connect","sign in with your howtofix.id email:password \u2014 no browser needed"],["/model","choose which model answers"],["/help","list every command"],["/quit","leave"]],u=[" \u2588\u2588\u2557 \u2588\u2588\u2557\u2588\u2588\u2557 \u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557"," \u2588\u2588\u2551 \u2588\u2588\u2551\u255A\u2588\u2588\u2557\u2588\u2588\u2554\u255D\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D"," \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551 \u255A\u2588\u2588\u2588\u2554\u255D \u2588\u2588\u2588\u2588\u2588\u2557 "," \u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2551 \u2588\u2588\u2554\u2588\u2588\u2557 \u2588\u2588\u2554\u2550\u2550\u255D "," \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2554\u255D \u2588\u2588\u2557\u2588\u2588\u2551 "," \u255A\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u255D "],m=[" _ _ _____ ","| | | | __ __ | ___|","| |_| | \\ \\/ / | |_ ","| _ | > < | _| ","|_| |_| /_/\\_\\ |_| "];function g(){if(process.platform==="win32")return!1;let e=(process.env.LC_ALL||process.env.LC_CTYPE||process.env.LANG||"").toLowerCase();return e===""||e==="c"||e==="posix"||!e.includes("utf-8")&&!e.includes("utf8")?!1:!/ja|ko|zh|_kr|_jp|_cn|_tw|_hk/.test(e)}function h(){return g()?u:m}var _="https://howtofix.id/cli";function p(e){let n=process.env.HOME??"",t=n!==""&&e.startsWith(n)?`~${e.slice(n.length)}`:e,o=t.split("/").filter(Boolean);return o.length>3?`\u2026/${o.slice(-2).join("/")}`:t}function f(e){let n=e.signedIn?d.filter(([t])=>t!=="/connect"):d;return[...h(),"",`${i} ${r} \u2014 a terminal coding agent. Describe the change you want and it reads, edits and runs the code in front of you.`,"",` working in ${p(e.cwd)}`,...e.note?[` session ${e.note}`]:[],"",...e.signedIn?[" already signed in to howtofix.id",""]:[],...n.map(([t,o])=>` ${t.padEnd(11)}${o}`),"",' Or just start typing. Every message goes to the model; anything beginning with "/" stays local.'].join(`
|
|
2
2
|
`)}function w(){return[{value:"connect",label:"Sign in to howtofix.id",description:"opens the browser, or paste a key from the panel"},{value:"ready",label:"I have a key \u2014 just give me the prompt",description:"drops you at the prompt; run /connect whenever you like"},{value:"release",label:"What's in this release",description:`opens the ${r} notes in your browser`}]}async function E(e,n,t){c(s).welcomeSeen||(l(s),t(`welcome to ${i}`,f(e)),!e.signedIn&&await new Promise(o=>{n("First run \u2014 how do you want to begin?",w(),a=>{a==="connect"&&e.runSlash("/connect"),a==="release"&&e.openExternal(_),o()},()=>o())}))}export{E as maybeShowWelcome};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{a as x}from"./chunk-UTYFLLSM.js";import{g as P,j as M}from"./chunk-JMKK26AT.js";import{existsSync as z,readFileSync as ye}from"node:fs";import{join as xe}from"node:path";import{createHash as J,randomBytes as G}from"node:crypto";import{createServer as ne}from"node:http";import{execFileSync as X}from"node:child_process";import{createHmac as Q}from"node:crypto";import{readFileSync as ee}from"node:fs";import{arch as N,cpus as $,hostname as O,platform as _,userInfo as H}from"node:os";var te="howtofix-cli-hwid-v1";function v(e){try{let t=ee(e,"utf8").trim();return t.length>0?t:void 0}catch{return}}function F(e,t){try{let r=X(e,t,{encoding:"utf8",timeout:3e3,stdio:["ignore","pipe","ignore"]});return r.trim().length>0?r.trim():void 0}catch{return}}function re(){let e=_();if(e==="linux"){let t=v("/etc/machine-id");if(t)return{value:t,source:"machine-id",strong:!0};let r=v("/var/lib/dbus/machine-id");if(r)return{value:r,source:"dbus-machine-id",strong:!0};let s=v("/sys/class/dmi/id/product_uuid");return s?{value:s,source:"dmi-product-uuid",strong:!0}:void 0}if(e==="win32"){let r=F("reg",["query","HKLM\\SOFTWARE\\Microsoft\\Cryptography","/v","MachineGuid"])?.match(/MachineGuid\s+REG_SZ\s+(\S+)/i);return r?.[1]?{value:r[1],source:"windows-machine-guid",strong:!0}:void 0}if(e==="darwin"){let r=F("ioreg",["-rd1","-c","IOPlatformExpertDevice"])?.match(/"IOPlatformUUID"\s*=\s*"([^"]+)"/);return r?.[1]?{value:r[1],source:"platform-uuid",strong:!0}:void 0}}function U(){let e=re(),t=e?.value??[O(),_(),N(),H().username].join("\0"),r=e?.source??"hostname";return{id:Q("sha256",te).update(t).digest("hex").slice(0,32),source:r,strong:e?.strong??!1}}function j(e){return[e.id,e.source,O(),_(),N(),H().username,String($().length),$()[0]?.model??""]}var I="https://howtofix.id",se=300*1e3,L=3e3,K="/callback";function A(e){return e.toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function oe(){return A(G(32))}function ie(e){return A(J("sha256").update(e).digest())}function ae(){return A(G(16))}var ce="howtofix-cli-",ue="x-howtofix-client",le="cli";function C(e){let t=e??j(U());return ce+J("sha256").update(t.join("\0")).digest("hex").slice(0,32)}function de(){return{"content-type":"application/json",[ue]:le}}var fe=()=>new Promise((e,t)=>{let r=ne();r.once("error",t),r.listen(0,"127.0.0.1",()=>{let{port:s}=r.address();e({port:s,close:()=>r.close(),waitForCode:(o,n)=>new Promise((i,a)=>{let c=(l,m)=>{let h=new URL(l.url??"/","http://127.0.0.1");if(h.pathname!==K){m.writeHead(404).end("not found");return}let y=(V,Z)=>m.writeHead(200,{"content-type":"text/html; charset=utf-8"}).end(`<!doctype html><meta charset="utf-8"><h2>${V}</h2><p>${Z}</p>`),T=h.searchParams.get("error")??"",R=h.searchParams.get("code")??"",Y=h.searchParams.get("state")??"";if(T){y("Sign-in was refused","You can close this tab."),u(new Error(`the browser reported: ${T}`));return}if(!R||Y!==o){y("This callback did not belong to the login","You can close this tab."),u(new Error("the callback carried the wrong state"));return}y("Signed in","You can close this tab and go back to HowToFix."),u(void 0,R)},u=(l,m)=>{r.off("request",c),n?.removeEventListener("abort",f),l?a(l):i(m)},f=()=>u(new Error("cancelled"));n?.addEventListener("abort",f,{once:!0}),r.on("request",c)})})})});function k(e,t){e.onProgress?.(t)}async function g(e,t,r,s){let o=await e(t,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(r),signal:s}),n={};try{n=await o.json()}catch{}let i=Number(o.headers?.get?.("retry-after"));return{status:o.status,body:n,retryAfterSeconds:Number.isFinite(i)&&i>0?i:void 0}}function d(...e){for(let t of e)if(typeof t=="string"&&t.trim()!=="")return t.trim()}function D(...e){for(let t of e)if(typeof t=="number"&&Number.isFinite(t))return t;return 0}function me(e){try{let t=new URL(e).searchParams.get("code");return t&&t.trim()!==""?t.trim():void 0}catch{return}}async function pe(e,t,r){let s=await e(t,{headers:de(),signal:r}),o={};try{o=await s.json()}catch{}let n=Number(s.headers?.get?.("retry-after"));return{status:s.status,body:o,retryAfterSeconds:Number.isFinite(n)&&n>0?n:void 0}}function S(e){let t=e.data,r=[e.token,e.api_key,e.apiKey,e.key,t?.token,t?.api_key,t?.apiKey,t?.key];for(let s of r)if(typeof s=="string"&&s.trim().startsWith("sk-"))return s.trim()}function ge(e){let t=e.data,r=d(e.token,t?.token),s=d(e.refresh_token,t?.refresh_token),o=d(e.device_id,t?.device_id);if(!r||!s||!o)return;let n=D(e.access_expires_at,t?.access_expires_at),i=D(e.refresh_expires_at,t?.refresh_expires_at);return{accessToken:r,accessExpiresAt:n,refreshToken:s,deviceId:o,refreshExpiresAt:i}}function p(e,t){let r=e.message??e.error;return typeof r=="string"&&r.trim()?r.trim():t}async function Oe(e){let t=e.fetchImpl??fetch,r=(e.panelUrl??I).replace(/\/+$/,""),s=e.timeoutMs??se,o={...e,panel:r,fetchImpl:t,timeoutMs:s},n=await ke(o);if(n.ok||n.terminal)return n.result;let i=await he(o);if(i.ok||i.terminal)return i.result;let a=await we(o);return a.ok?a:{ok:!1,message:`${n.result.ok?"":n.result.message}; ${i.result.ok?"":i.result.message}; ${a.message}. howtofix.id does not offer a browser login a local client can complete yet \u2014 run /connect and paste a token from ${r}/keys instead.`}}async function he(e){let t=oe(),r=ae(),s;try{s=await(e.loopback??fe)();let o=`http://127.0.0.1:${s.port}${K}`,n=await g(e.fetchImpl,`${e.panel}/api/oauth/device/start`,{redirect_uri:o,code_challenge:ie(t),code_challenge_method:"S256",state:r},e.signal);if(n.status===404)return{ok:!1,terminal:!1,result:{ok:!1,message:"the panel has no loopback login endpoint"}};if(n.status>=400)return{ok:!1,terminal:!1,result:{ok:!1,message:p(n.body,`the panel refused the login (${n.status})`)}};let i=typeof n.body.authorize_url=="string"?n.body.authorize_url:"";if(!i)return{ok:!1,terminal:!1,result:{ok:!1,message:"the panel did not say where to send the browser"}};k(e,{kind:"browser",url:i});let a=await be(s.waitForCode(r,e.signal),e.timeoutMs),c=await g(e.fetchImpl,`${e.panel}/api/oauth/device/token`,{flow_token:n.body.flow_token,code:a,code_verifier:t},e.signal);if(c.status>=400)return{ok:!1,terminal:!0,result:{ok:!1,message:p(c.body,`the panel refused the exchange (${c.status})`)}};let u=S(c.body);return u?{ok:!0,result:{ok:!0,token:u}}:{ok:!1,terminal:!0,result:{ok:!1,message:"the panel did not return an API key"}}}catch(o){let n=o instanceof Error?o.message:String(o);return{ok:!1,terminal:n==="cancelled",result:{ok:!1,message:n}}}finally{s?.close()}}async function ke(e){let t=e.pollIntervalMs??L,r=e.fingerprintId??C(),s=e.clientInfo??P(),o=M(r,s);try{let n=await g(e.fetchImpl,`${e.panel}/api/auth/cli/code`,{fingerprintId:r,clientInfo:s,...o},e.signal);if(n.status===404)return{ok:!1,terminal:!1,result:{ok:!1,message:"the panel has no CLI login endpoint"}};if(n.status===401)return{ok:!1,terminal:!1,result:{ok:!1,message:"the panel did not recognise this build as the HowToFix CLI \u2014 update it with `npm install -g howtofixcli@latest`"}};if(n.status===429)return{ok:!1,terminal:!0,result:{ok:!1,message:`too many sign-in attempts from this machine right now.${n.retryAfterSeconds?` Try again in ${Math.ceil(n.retryAfterSeconds/60)} minute(s).`:""}`}};if(n.status>=400)return{ok:!1,terminal:!1,result:{ok:!1,message:p(n.body,`the panel refused the login (${n.status})`)}};let i=n.body.data??{},a=d(n.body.login_url,i.login_url),c=d(n.body.code,i.code)??(a?me(a):void 0),u=d(n.body.secret,i.secret);return!a||!c?{ok:!1,terminal:!1,result:{ok:!1,message:"the panel did not return a login URL"}}:u?(k(e,{kind:"browser",url:a}),await q(e,c,u)):(k(e,{kind:"browser",url:a}),await q(e,c,void 0))}catch(n){let i=n instanceof Error?n.message:String(n);return{ok:!1,terminal:i==="cancelled",result:{ok:!1,message:i}}}}async function q(e,t,r){let s=e.pollIntervalMs??L,o=Date.now()+e.timeoutMs;for(;Date.now()<o;){await w(s,e.signal);let n=new URLSearchParams(r?{code:t,secret:r}:{code:t});n.set("capability","device-refresh");let i=await pe(e.fetchImpl,`${e.panel}/api/auth/cli/status?${n}`,e.signal);if(i.status===404)return{ok:!1,terminal:!1,result:{ok:!1,message:"the panel has no CLI login status endpoint"}};if(i.status===403)return{ok:!1,terminal:!0,result:{ok:!1,message:"the panel rejected this poll \u2014 run /connect again"}};if(i.status===429){let u=Math.min(Math.max(i.retryAfterSeconds??5,1)*1e3,3e4);await w(u,e.signal);continue}let a=S(i.body);if(a)return{ok:!0,result:{ok:!0,token:a,credential:ge(i.body)}};if(d(i.body.data?.status,i.body.status)==="expired")return{ok:!1,terminal:!0,result:{ok:!1,message:"the sign-in link expired before it was approved"}};if(i.status>=400)return{ok:!1,terminal:!0,result:{ok:!1,message:p(i.body,`the panel refused the poll (${i.status})`)}}}return{ok:!1,terminal:!0,result:{ok:!1,message:"the sign-in was not approved in time"}}}async function we(e){let t=e.pollIntervalMs??L;try{let r=await g(e.fetchImpl,`${e.panel}/api/oauth/device`,{},e.signal);if(r.status===404)return{ok:!1,message:"the panel has no device-code endpoint"};if(r.status>=400)return{ok:!1,message:p(r.body,`the panel refused the request (${r.status})`)};let s=typeof r.body.device_code=="string"?r.body.device_code:"",o=typeof r.body.user_code=="string"?r.body.user_code:"",n=typeof r.body.verification_uri=="string"?r.body.verification_uri:`${e.panel}/oauth/device`;if(!s||!o)return{ok:!1,message:"the panel did not return a code to show"};k(e,{kind:"code",code:o,url:n});let i=Date.now()+e.timeoutMs;for(;Date.now()<i;){await w(t,e.signal);let a=await g(e.fetchImpl,`${e.panel}/api/oauth/device/poll`,{device_code:s},e.signal);if(a.status===404)return{ok:!1,message:"the panel has no device-code poll endpoint"};let c=typeof a.body.status=="string"?a.body.status:"";if(c==="pending")continue;if(c==="slow_down"){await w(t,e.signal);continue}if(c==="denied")return{ok:!1,message:"the sign-in was refused in the browser"};if(c==="expired")return{ok:!1,message:"the code expired; run /connect again"};let u=S(a.body);if(u)return{ok:!0,token:u};if(a.status>=400)return{ok:!1,message:p(a.body,`the panel refused the poll (${a.status})`)}}return{ok:!1,message:"the code was not approved in time"}}catch(r){return{ok:!1,message:r instanceof Error?r.message:String(r)}}}function be(e,t){return new Promise((r,s)=>{let o=setTimeout(()=>s(new Error("the sign-in was not finished in time")),t);e.then(n=>{clearTimeout(o),r(n)},n=>{clearTimeout(o),s(n)})})}function w(e,t){return new Promise((r,s)=>{let o=setTimeout(r,e);t?.addEventListener("abort",()=>{clearTimeout(o),s(new Error("cancelled"))},{once:!0})})}function b(e){return xe(e,"cli-credentials.json")}var ve=300*1e3;function _e(e,t=Date.now()){return e.accessToken?!Number.isFinite(e.accessExpiresAt)||e.accessExpiresAt<=0?!0:e.accessExpiresAt*1e3-ve>t:!1}function Ie(e,t=Date.now()){return!e.refreshToken||!e.deviceId?!1:!Number.isFinite(e.refreshExpiresAt)||e.refreshExpiresAt<=0?!0:e.refreshExpiresAt*1e3>t}function Je(e){let t=b(e);if(!z(t))return;let r;try{r=JSON.parse(ye(t,"utf8"))}catch{return}if(!r||typeof r!="object"||Array.isArray(r))return;let s=r,o=typeof s.accessToken=="string"?s.accessToken.trim():"",n=typeof s.refreshToken=="string"?s.refreshToken.trim():"",i=typeof s.deviceId=="string"?s.deviceId.trim():"";if(!(!o||!n||!i))return{accessToken:o,accessExpiresAt:W(s.accessExpiresAt),refreshToken:n,deviceId:i,refreshExpiresAt:W(s.refreshExpiresAt)}}function Le(e,t){try{return x(b(e),`${JSON.stringify(t,null,2)}
|
|
1
|
+
import{a as x}from"./chunk-UTYFLLSM.js";import{g as P,j as M}from"./chunk-W7KLNX6W.js";import{existsSync as z,readFileSync as ye}from"node:fs";import{join as xe}from"node:path";import{createHash as J,randomBytes as G}from"node:crypto";import{createServer as ne}from"node:http";import{execFileSync as X}from"node:child_process";import{createHmac as Q}from"node:crypto";import{readFileSync as ee}from"node:fs";import{arch as N,cpus as $,hostname as O,platform as _,userInfo as H}from"node:os";var te="howtofix-cli-hwid-v1";function v(e){try{let t=ee(e,"utf8").trim();return t.length>0?t:void 0}catch{return}}function F(e,t){try{let r=X(e,t,{encoding:"utf8",timeout:3e3,stdio:["ignore","pipe","ignore"]});return r.trim().length>0?r.trim():void 0}catch{return}}function re(){let e=_();if(e==="linux"){let t=v("/etc/machine-id");if(t)return{value:t,source:"machine-id",strong:!0};let r=v("/var/lib/dbus/machine-id");if(r)return{value:r,source:"dbus-machine-id",strong:!0};let s=v("/sys/class/dmi/id/product_uuid");return s?{value:s,source:"dmi-product-uuid",strong:!0}:void 0}if(e==="win32"){let r=F("reg",["query","HKLM\\SOFTWARE\\Microsoft\\Cryptography","/v","MachineGuid"])?.match(/MachineGuid\s+REG_SZ\s+(\S+)/i);return r?.[1]?{value:r[1],source:"windows-machine-guid",strong:!0}:void 0}if(e==="darwin"){let r=F("ioreg",["-rd1","-c","IOPlatformExpertDevice"])?.match(/"IOPlatformUUID"\s*=\s*"([^"]+)"/);return r?.[1]?{value:r[1],source:"platform-uuid",strong:!0}:void 0}}function U(){let e=re(),t=e?.value??[O(),_(),N(),H().username].join("\0"),r=e?.source??"hostname";return{id:Q("sha256",te).update(t).digest("hex").slice(0,32),source:r,strong:e?.strong??!1}}function j(e){return[e.id,e.source,O(),_(),N(),H().username,String($().length),$()[0]?.model??""]}var I="https://howtofix.id",se=300*1e3,L=3e3,K="/callback";function A(e){return e.toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function oe(){return A(G(32))}function ie(e){return A(J("sha256").update(e).digest())}function ae(){return A(G(16))}var ce="howtofix-cli-",ue="x-howtofix-client",le="cli";function C(e){let t=e??j(U());return ce+J("sha256").update(t.join("\0")).digest("hex").slice(0,32)}function de(){return{"content-type":"application/json",[ue]:le}}var fe=()=>new Promise((e,t)=>{let r=ne();r.once("error",t),r.listen(0,"127.0.0.1",()=>{let{port:s}=r.address();e({port:s,close:()=>r.close(),waitForCode:(o,n)=>new Promise((i,a)=>{let c=(l,m)=>{let h=new URL(l.url??"/","http://127.0.0.1");if(h.pathname!==K){m.writeHead(404).end("not found");return}let y=(V,Z)=>m.writeHead(200,{"content-type":"text/html; charset=utf-8"}).end(`<!doctype html><meta charset="utf-8"><h2>${V}</h2><p>${Z}</p>`),T=h.searchParams.get("error")??"",R=h.searchParams.get("code")??"",Y=h.searchParams.get("state")??"";if(T){y("Sign-in was refused","You can close this tab."),u(new Error(`the browser reported: ${T}`));return}if(!R||Y!==o){y("This callback did not belong to the login","You can close this tab."),u(new Error("the callback carried the wrong state"));return}y("Signed in","You can close this tab and go back to HowToFix."),u(void 0,R)},u=(l,m)=>{r.off("request",c),n?.removeEventListener("abort",f),l?a(l):i(m)},f=()=>u(new Error("cancelled"));n?.addEventListener("abort",f,{once:!0}),r.on("request",c)})})})});function k(e,t){e.onProgress?.(t)}async function g(e,t,r,s){let o=await e(t,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(r),signal:s}),n={};try{n=await o.json()}catch{}let i=Number(o.headers?.get?.("retry-after"));return{status:o.status,body:n,retryAfterSeconds:Number.isFinite(i)&&i>0?i:void 0}}function d(...e){for(let t of e)if(typeof t=="string"&&t.trim()!=="")return t.trim()}function D(...e){for(let t of e)if(typeof t=="number"&&Number.isFinite(t))return t;return 0}function me(e){try{let t=new URL(e).searchParams.get("code");return t&&t.trim()!==""?t.trim():void 0}catch{return}}async function pe(e,t,r){let s=await e(t,{headers:de(),signal:r}),o={};try{o=await s.json()}catch{}let n=Number(s.headers?.get?.("retry-after"));return{status:s.status,body:o,retryAfterSeconds:Number.isFinite(n)&&n>0?n:void 0}}function S(e){let t=e.data,r=[e.token,e.api_key,e.apiKey,e.key,t?.token,t?.api_key,t?.apiKey,t?.key];for(let s of r)if(typeof s=="string"&&s.trim().startsWith("sk-"))return s.trim()}function ge(e){let t=e.data,r=d(e.token,t?.token),s=d(e.refresh_token,t?.refresh_token),o=d(e.device_id,t?.device_id);if(!r||!s||!o)return;let n=D(e.access_expires_at,t?.access_expires_at),i=D(e.refresh_expires_at,t?.refresh_expires_at);return{accessToken:r,accessExpiresAt:n,refreshToken:s,deviceId:o,refreshExpiresAt:i}}function p(e,t){let r=e.message??e.error;return typeof r=="string"&&r.trim()?r.trim():t}async function Oe(e){let t=e.fetchImpl??fetch,r=(e.panelUrl??I).replace(/\/+$/,""),s=e.timeoutMs??se,o={...e,panel:r,fetchImpl:t,timeoutMs:s},n=await ke(o);if(n.ok||n.terminal)return n.result;let i=await he(o);if(i.ok||i.terminal)return i.result;let a=await we(o);return a.ok?a:{ok:!1,message:`${n.result.ok?"":n.result.message}; ${i.result.ok?"":i.result.message}; ${a.message}. howtofix.id does not offer a browser login a local client can complete yet \u2014 run /connect and paste a token from ${r}/keys instead.`}}async function he(e){let t=oe(),r=ae(),s;try{s=await(e.loopback??fe)();let o=`http://127.0.0.1:${s.port}${K}`,n=await g(e.fetchImpl,`${e.panel}/api/oauth/device/start`,{redirect_uri:o,code_challenge:ie(t),code_challenge_method:"S256",state:r},e.signal);if(n.status===404)return{ok:!1,terminal:!1,result:{ok:!1,message:"the panel has no loopback login endpoint"}};if(n.status>=400)return{ok:!1,terminal:!1,result:{ok:!1,message:p(n.body,`the panel refused the login (${n.status})`)}};let i=typeof n.body.authorize_url=="string"?n.body.authorize_url:"";if(!i)return{ok:!1,terminal:!1,result:{ok:!1,message:"the panel did not say where to send the browser"}};k(e,{kind:"browser",url:i});let a=await be(s.waitForCode(r,e.signal),e.timeoutMs),c=await g(e.fetchImpl,`${e.panel}/api/oauth/device/token`,{flow_token:n.body.flow_token,code:a,code_verifier:t},e.signal);if(c.status>=400)return{ok:!1,terminal:!0,result:{ok:!1,message:p(c.body,`the panel refused the exchange (${c.status})`)}};let u=S(c.body);return u?{ok:!0,result:{ok:!0,token:u}}:{ok:!1,terminal:!0,result:{ok:!1,message:"the panel did not return an API key"}}}catch(o){let n=o instanceof Error?o.message:String(o);return{ok:!1,terminal:n==="cancelled",result:{ok:!1,message:n}}}finally{s?.close()}}async function ke(e){let t=e.pollIntervalMs??L,r=e.fingerprintId??C(),s=e.clientInfo??P(),o=M(r,s);try{let n=await g(e.fetchImpl,`${e.panel}/api/auth/cli/code`,{fingerprintId:r,clientInfo:s,...o},e.signal);if(n.status===404)return{ok:!1,terminal:!1,result:{ok:!1,message:"the panel has no CLI login endpoint"}};if(n.status===401)return{ok:!1,terminal:!1,result:{ok:!1,message:"the panel did not recognise this build as the HowToFix CLI \u2014 update it with `npm install -g howtofixcli@latest`"}};if(n.status===429)return{ok:!1,terminal:!0,result:{ok:!1,message:`too many sign-in attempts from this machine right now.${n.retryAfterSeconds?` Try again in ${Math.ceil(n.retryAfterSeconds/60)} minute(s).`:""}`}};if(n.status>=400)return{ok:!1,terminal:!1,result:{ok:!1,message:p(n.body,`the panel refused the login (${n.status})`)}};let i=n.body.data??{},a=d(n.body.login_url,i.login_url),c=d(n.body.code,i.code)??(a?me(a):void 0),u=d(n.body.secret,i.secret);return!a||!c?{ok:!1,terminal:!1,result:{ok:!1,message:"the panel did not return a login URL"}}:u?(k(e,{kind:"browser",url:a}),await q(e,c,u)):(k(e,{kind:"browser",url:a}),await q(e,c,void 0))}catch(n){let i=n instanceof Error?n.message:String(n);return{ok:!1,terminal:i==="cancelled",result:{ok:!1,message:i}}}}async function q(e,t,r){let s=e.pollIntervalMs??L,o=Date.now()+e.timeoutMs;for(;Date.now()<o;){await w(s,e.signal);let n=new URLSearchParams(r?{code:t,secret:r}:{code:t});n.set("capability","device-refresh");let i=await pe(e.fetchImpl,`${e.panel}/api/auth/cli/status?${n}`,e.signal);if(i.status===404)return{ok:!1,terminal:!1,result:{ok:!1,message:"the panel has no CLI login status endpoint"}};if(i.status===403)return{ok:!1,terminal:!0,result:{ok:!1,message:"the panel rejected this poll \u2014 run /connect again"}};if(i.status===429){let u=Math.min(Math.max(i.retryAfterSeconds??5,1)*1e3,3e4);await w(u,e.signal);continue}let a=S(i.body);if(a)return{ok:!0,result:{ok:!0,token:a,credential:ge(i.body)}};if(d(i.body.data?.status,i.body.status)==="expired")return{ok:!1,terminal:!0,result:{ok:!1,message:"the sign-in link expired before it was approved"}};if(i.status>=400)return{ok:!1,terminal:!0,result:{ok:!1,message:p(i.body,`the panel refused the poll (${i.status})`)}}}return{ok:!1,terminal:!0,result:{ok:!1,message:"the sign-in was not approved in time"}}}async function we(e){let t=e.pollIntervalMs??L;try{let r=await g(e.fetchImpl,`${e.panel}/api/oauth/device`,{},e.signal);if(r.status===404)return{ok:!1,message:"the panel has no device-code endpoint"};if(r.status>=400)return{ok:!1,message:p(r.body,`the panel refused the request (${r.status})`)};let s=typeof r.body.device_code=="string"?r.body.device_code:"",o=typeof r.body.user_code=="string"?r.body.user_code:"",n=typeof r.body.verification_uri=="string"?r.body.verification_uri:`${e.panel}/oauth/device`;if(!s||!o)return{ok:!1,message:"the panel did not return a code to show"};k(e,{kind:"code",code:o,url:n});let i=Date.now()+e.timeoutMs;for(;Date.now()<i;){await w(t,e.signal);let a=await g(e.fetchImpl,`${e.panel}/api/oauth/device/poll`,{device_code:s},e.signal);if(a.status===404)return{ok:!1,message:"the panel has no device-code poll endpoint"};let c=typeof a.body.status=="string"?a.body.status:"";if(c==="pending")continue;if(c==="slow_down"){await w(t,e.signal);continue}if(c==="denied")return{ok:!1,message:"the sign-in was refused in the browser"};if(c==="expired")return{ok:!1,message:"the code expired; run /connect again"};let u=S(a.body);if(u)return{ok:!0,token:u};if(a.status>=400)return{ok:!1,message:p(a.body,`the panel refused the poll (${a.status})`)}}return{ok:!1,message:"the code was not approved in time"}}catch(r){return{ok:!1,message:r instanceof Error?r.message:String(r)}}}function be(e,t){return new Promise((r,s)=>{let o=setTimeout(()=>s(new Error("the sign-in was not finished in time")),t);e.then(n=>{clearTimeout(o),r(n)},n=>{clearTimeout(o),s(n)})})}function w(e,t){return new Promise((r,s)=>{let o=setTimeout(r,e);t?.addEventListener("abort",()=>{clearTimeout(o),s(new Error("cancelled"))},{once:!0})})}function b(e){return xe(e,"cli-credentials.json")}var ve=300*1e3;function _e(e,t=Date.now()){return e.accessToken?!Number.isFinite(e.accessExpiresAt)||e.accessExpiresAt<=0?!0:e.accessExpiresAt*1e3-ve>t:!1}function Ie(e,t=Date.now()){return!e.refreshToken||!e.deviceId?!1:!Number.isFinite(e.refreshExpiresAt)||e.refreshExpiresAt<=0?!0:e.refreshExpiresAt*1e3>t}function Je(e){let t=b(e);if(!z(t))return;let r;try{r=JSON.parse(ye(t,"utf8"))}catch{return}if(!r||typeof r!="object"||Array.isArray(r))return;let s=r,o=typeof s.accessToken=="string"?s.accessToken.trim():"",n=typeof s.refreshToken=="string"?s.refreshToken.trim():"",i=typeof s.deviceId=="string"?s.deviceId.trim():"";if(!(!o||!n||!i))return{accessToken:o,accessExpiresAt:W(s.accessExpiresAt),refreshToken:n,deviceId:i,refreshExpiresAt:W(s.refreshExpiresAt)}}function Le(e,t){try{return x(b(e),`${JSON.stringify(t,null,2)}
|
|
2
2
|
`,{mode:384}),!0}catch{return!1}}function Ae(e){try{let t=b(e);z(t)&&x(t,"",{mode:384})}catch{}}function W(e){return typeof e=="number"&&Number.isFinite(e)?e:0}async function Ce(e,t){let r=(t?.panelUrl??I).replace(/\/+$/,""),s=t?.fetchImpl??fetch,o=t?.timeoutMs??15e3,n=new AbortController,i=setTimeout(()=>n.abort(),o);try{let a=await s(`${r}/api/auth/cli/refresh`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({device_id:e.deviceId,refresh_token:e.refreshToken,fingerprint_id:C()}),signal:n.signal}),c=await a.json().catch(()=>({}));if(a.status===401||a.status===403)return{ok:!1,terminal:!0,message:"this sign-in is no longer valid \u2014 run /connect to sign in again"};if(!a.ok)return{ok:!1,terminal:!1,message:`the panel refused the renewal (${a.status})`};let u=c.data??{},f=E(c.token,u.token),l=E(c.refresh_token,u.refresh_token),m=E(c.device_id,u.device_id)??e.deviceId;return!f||!l?{ok:!1,terminal:!1,message:"the panel did not return a renewed credential"}:{ok:!0,terminal:!1,credential:{accessToken:f,accessExpiresAt:B(c.access_expires_at,u.access_expires_at),refreshToken:l,deviceId:m,refreshExpiresAt:B(c.refresh_expires_at,u.refresh_expires_at)}}}catch(a){return{ok:!1,terminal:!1,message:a instanceof Error&&a.name==="AbortError"?`the panel did not answer within ${Math.round(o/1e3)}s`:"could not reach the panel"}}finally{clearTimeout(i)}}function E(...e){for(let t of e)if(typeof t=="string"&&t.trim())return t.trim()}function B(...e){for(let t of e)if(typeof t=="number"&&Number.isFinite(t))return t;return 0}async function Ge(e,t,r){let s=r?.now??Date.now();if(_e(t,s)||!Ie(t,s))return{credential:t,renewed:!1,terminal:!1};let o=await Ce(t,r);if(!o.ok||!o.credential)return o.terminal&&Ae(e),{credential:t,renewed:!1,terminal:o.terminal,message:o.message};let n=Le(e,o.credential);return{credential:o.credential,renewed:!0,terminal:!1,message:n?void 0:`the renewed sign-in could not be saved to ${b(e)}`}}export{I as a,Oe as b,b as c,ve as d,_e as e,Ie as f,Je as g,Le as h,Ae as i,Ce as j,Ge as k};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{b as r}from"./chunk-
|
|
1
|
+
import{b as r}from"./chunk-5Y3G5FLR.js";import"./chunk-WOT6VMZA.js";function a(e){return{prompt:s=>e.session.prompt(s),abort:()=>e.session.abort(),subscribe:s=>e.session.subscribe(n=>s(n)),getLastAssistantText:()=>e.session.getLastAssistantText(),lastStopReason:()=>{let s=e.session.state.messages.at(-1);return s?.role==="assistant"?s.stopReason:void 0},dispose:()=>e.dispose()}}async function u(e,s){let{openSession:n}=await import("./chunk-WGBDEDF6.js"),i=t=>n({cwd:t,model:s.model,thinking:s.thinking,continueSession:!1,noSession:!1,sessionPath:void 0,interactive:!1});if(e==="acp"){let{runAcp:t}=await import("./chunk-DAPXGSGD.js");await t({input:process.stdin,output:process.stdout,version:r,createAgent:async d=>a(await i(d))});return}let{runRpc:p}=await import("./chunk-ONZLNFQ2.js"),{jsonLine:c}=await import("./chunk-DOD7MUGX.js"),o=await i(s.cwd);await p({input:process.stdin,output:process.stdout,agent:a(o),encodeEvent:t=>c(t),state:()=>({sessionId:o.session.sessionId,model:o.modelLabel,cwd:s.cwd})})}export{a as agentFromSession,u as serveProtocol};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{c as a,d as b,e as c,f as d,g as e,h as f,i as g,j as h,k as i}from"./chunk-
|
|
1
|
+
import{c as a,d as b,e as c,f as d,g as e,h as f,i as g,j as h,k as i}from"./chunk-AIQOTZSL.js";import"./chunk-UTYFLLSM.js";import"./chunk-W7KLNX6W.js";import"./chunk-5Y3G5FLR.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,e,f,g,h,i,j}from"./chunk-
|
|
1
|
+
import{a,b,c,d,e,f,g,h,i,j}from"./chunk-W7KLNX6W.js";import"./chunk-5Y3G5FLR.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{b as k}from"./chunk-AGGIYXN7.js";import{D as p}from"./chunk-V656XVXV.js";import{a as E}from"./chunk-PCALBZOO.js";import"./chunk-UTYFLLSM.js";import{a as g}from"./chunk-
|
|
1
|
+
import{b as k}from"./chunk-AGGIYXN7.js";import{D as p}from"./chunk-V656XVXV.js";import{a as E}from"./chunk-PCALBZOO.js";import"./chunk-UTYFLLSM.js";import{a as g}from"./chunk-5Y3G5FLR.js";import"./chunk-WOT6VMZA.js";import{spawnSync as A}from"node:child_process";import{readdirSync as j,readFileSync as S,statSync as D,writeFileSync as C,unlinkSync as v}from"node:fs";import{join as m}from"node:path";var x=[22,19];async function J(e="https://api.howtofix.id/api/status"){let s=[],[n,t]=process.versions.node.split(".").map(Number),r=n>x[0]||n===x[0]&&t>=x[1];s.push({name:"node",ok:r,detail:`${process.versions.node} (needs >= ${x[0]}.${x[1]})`});let a=A("git",["--version"],{encoding:"utf8"});s.push({name:"git",ok:a.status===0,detail:a.status===0?a.stdout.trim():"not found on PATH"});let o=E();s.push({name:"sandbox",ok:!!o,detail:o??"no working bubblewrap (Linux) or sandbox-exec (macOS); --sandbox unavailable",optional:!0});let c=!1,i=p;try{let l=m(p,`.doctor-${process.pid}`);C(l,"ok"),v(l),c=!0}catch(l){i=`${p} is not writable: ${l instanceof Error?l.message:String(l)}`}s.push({name:"state dir",ok:c,detail:i});let u=m(p,"auth.json"),f="no auth.json \u2014 run `howtofix` and sign in",h=!1;try{let l=JSON.parse(S(u,"utf8")),d=Object.keys(l).length;h=d>0,f=h?`${d} provider credential${d===1?"":"s"}`:f}catch{}s.push({name:"auth",ok:h,detail:f,optional:!0});try{let l=Date.now(),d=await fetch(e,{signal:AbortSignal.timeout(5e3)});s.push({name:"gateway",ok:d.ok,detail:`${e} \u2192 ${d.status} in ${Date.now()-l}ms`,optional:!0})}catch(l){s.push({name:"gateway",ok:!1,detail:`${e} unreachable: ${l instanceof Error?l.message:String(l)}`,optional:!0})}return s}async function Z(){let e=await J(),s=Math.max(...e.map(t=>t.name.length));for(let t of e){let r=t.ok?"ok ":t.optional?"warn":"FAIL";console.log(` ${r} ${t.name.padEnd(s)} ${t.detail}`)}let n=e.filter(t=>!t.ok&&!t.optional);return n.length>0?(console.log(`
|
|
2
2
|
${n.length} problem${n.length===1?"":"s"} must be fixed before a session will work.`),1):0}function K(e=p){let s=m(e,"models.json"),n;try{n=S(s,"utf8")}catch(o){return o.code==="ENOENT"?console.log(` no models.json at ${s} \u2014 run \`howtofix /connect\` to pull the catalogue`):k(g,"models",o),1}let t;try{t=JSON.parse(n)}catch(o){return console.error(`${g}: models: ${s} is not valid JSON (${o instanceof Error?o.message:String(o)})`),console.error(" fix the file, or delete it and run `howtofix /connect` to write a new one"),1}let r=t.providers??{},a=0;for(let[o,c]of Object.entries(r)){let i=(c.models??[]).map(u=>u.id).filter(Boolean);a+=i.length,console.log(` ${o} (${i.length})`);for(let u of i)console.log(` ${u}`)}return a===0?(console.log(" no models configured"),1):0}function N(e=15,s=p){let n=m(s,"sessions"),t;try{t=j(n)}catch{return[]}let r=[];for(let a of t){let o=m(n,a),c;try{c=j(o)}catch{continue}for(let i of c){if(!i.endsWith(".jsonl"))continue;let u=m(o,i);try{let f=D(u);r.push({file:u,project:a,modified:f.mtimeMs,bytes:f.size})}catch{}}}return r.sort((a,o)=>o.modified-a.modified).slice(0,e)}function Q(e){let s=e.indexOf("--search");if(s>=0){let o=e[s+1]?.trim();if(!o)return console.error(`${g}: sessions: --search needs a word or phrase`),2;let c=P(o);if(c.length===0)return console.log(` no session mentions "${o}"`),0;for(let i of c){let u=new Date(i.row.modified).toISOString().replace("T"," ").slice(0,16),f=`${i.matches} hit${i.matches===1?"":"s"}`;console.log(` ${u} ${i.row.project} (${f})`),console.log(` ${i.row.file}`),console.log(` ${i.snippet}`)}return 0}let n=e.indexOf("--limit"),t=n>=0&&Number(e[n+1])||15,r=N(t);if(r.length===0)return console.log(` no saved sessions under ${m(p,"sessions")}`),e.includes("--export")?1:0;let a=e.indexOf("--export");if(a>=0){let o=Number(e[a+1]);if(!Number.isInteger(o)||o<1||o>r.length)return console.error(`${g}: sessions: --export needs a number from the list (1-${r.length})`),2;let c=r[o-1];try{console.log(_(c.file))}catch(i){return k(g,"sessions",i),1}return 0}return r.forEach((o,c)=>{let i=new Date(o.modified).toISOString().replace("T"," ").slice(0,16),u=Math.round(o.bytes/1024);console.log(` ${String(c+1).padStart(2)} ${i} ${String(u).padStart(6)}k ${o.project}`),console.log(` ${o.file}`)}),0}function R(e){try{let s=JSON.parse(e),n=s.message?.content??s.content;if(typeof n=="string"&&n.trim())return O(n).replace(/\s+/g," ").trim();if(Array.isArray(n)){let t=O(n.map(r=>r&&typeof r=="object"&&"text"in r?String(r.text):"").join(" ")).replace(/\s+/g," ").trim();if(t)return t}}catch{}return O(e).replace(/\s+/g," ").trim()}function O(e){return e.replace(/\u001b\[[0-9;?]*[ -/]*[@-~]|\u001b\][^\u0007]*\u0007|\u001b[@-Z\\-_]/g,"")}function L(e,s,n=80){let t=e.toLowerCase().indexOf(s);if(t<0)return e.slice(0,n*2).trim();let r=Math.max(0,t-n),a=Math.min(e.length,t+s.length+n);return`${r>0?"\u2026":""}${e.slice(r,a).trim()}${a<e.length?"\u2026":""}`}function P(e,s=10,n=p){let t=e.toLowerCase(),r=new RegExp(`\\b${t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\b`,"i"),a=[];for(let o of N(Number.MAX_SAFE_INTEGER,n)){let c;try{c=S(o.file,"utf8")}catch{continue}let i=0,u=0,f=0,h=0,l=!1,d="";for(let y of c.split(`
|
|
3
3
|
`)){let w=y.toLowerCase(),b=w.indexOf(t);if(b<0)continue;let $=0;for(;b>=0;)$++,b=w.indexOf(t,b+t.length);i+=$;let M=w.includes('"role":"user"'),T=w.includes('"role":"toolresult"')||w.includes('"role":"tool"');M?u+=$:T?h+=$:f+=$,r.test(y)&&(l=!0),d||(d=L(R(y),t))}if(i===0)continue;let I=(u>0?100:0)+(f>0?10:0)+Math.min(h,5)+(l?5:0)+Math.min(i,10)/100;a.push({row:o,matches:i,score:I,snippet:d})}return a.sort((o,c)=>c.score-o.score||c.row.modified-o.row.modified).slice(0,s)}function _(e){let s=[`# Session ${e.split(/[\\/]/).pop()??e}`,""];for(let n of S(e,"utf8").split(`
|
|
4
4
|
`)){if(!n.trim())continue;let t;try{t=JSON.parse(n)}catch{continue}if(t.type!=="message")continue;let r=R(n);r&&s.push(`## ${t.message?.role??"unknown"}`,"",r,"")}return s.join(`
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as y}from"./chunk-UTYFLLSM.js";import{h as k,i as T}from"./chunk-
|
|
1
|
+
import{a as y}from"./chunk-UTYFLLSM.js";import{h as k,i as T}from"./chunk-W7KLNX6W.js";import{existsSync as L,mkdirSync as $,readFileSync as b}from"node:fs";import{join as M}from"node:path";var F="https://models.dev/api.json";var O=["anthropic","openai","google","deepseek","zai","xai","moonshotai","minimax","alibaba","xiaomi","meta","tencent","nvidia","venice","openrouter"];function x(n){return n.toLowerCase().replace(/[^a-z0-9]+/g,"")}function S(n){let r=n.split("/");return x(r[r.length-1]??n)}function W(n){let r=new Map,o=new Map;if(!n||typeof n!="object")return r;let t=n,s=i=>{let e=O.indexOf(i);return e===-1?O.length:e};for(let i of Object.keys(t).sort()){let e=t[i]?.models;if(!(!e||typeof e!="object"))for(let a of Object.keys(e)){let c=e[a],u=Number(c?.limit?.context);if(!Number.isFinite(u)||u<=0)continue;let l=x(a),d=s(i),m=o.get(l);if(m!==void 0&&m<=d)continue;let f=Number(c?.limit?.output);r.set(l,{contextWindow:Math.floor(u),maxTokens:Number.isFinite(f)&&f>0?Math.floor(f):void 0,reasoning:c?.reasoning===!0,vision:Array.isArray(c?.modalities?.input)&&c.modalities.input.includes("image")}),o.set(l,d)}}return r}function A(n,r){let o=x(r);if(!o)return;let t=n.get(o);if(t)return t;let s=S(r);for(let[i,e]of n)if(S(i)===s)return e;for(let[i,e]of n)if(i.endsWith(o)||o.endsWith(i))return e}function v(n){return`${n}/models-dev-cache.json`}function N(n){let r={};for(let[o,t]of n)r[o]=[t.contextWindow,t.maxTokens??0,t.reasoning?1:0,t.vision?1:0];return JSON.stringify(r)}function R(n){let r=new Map,o;try{o=JSON.parse(n)}catch{return r}if(!o||typeof o!="object")return r;for(let[t,s]of Object.entries(o)){if(!Array.isArray(s)||s.length<3)continue;let i=Number(s[0]),e=Number(s[1]);!Number.isFinite(i)||i<=0||r.set(t,{contextWindow:Math.floor(i),maxTokens:Number.isFinite(e)&&e>0?Math.floor(e):void 0,reasoning:s[2]===1||s[2]===!0,vision:s[3]===1||s[3]===!0})}return r}async function I(n){let r=n?.url??F,o=n?.fetchImpl??fetch,t=n?.timeoutMs??2e4,s=new AbortController,i=setTimeout(()=>s.abort(),t);try{let e=await o(r,{signal:s.signal,headers:{Accept:"application/json"}});if(!e.ok)return{ok:!1,message:`the model catalogue answered ${e.status}`};let a=W(await e.json());return a.size===0?{ok:!1,message:"the model catalogue was empty or in an unexpected shape"}:{ok:!0,index:a}}catch(e){return{ok:!1,message:e instanceof Error&&e.name==="AbortError"?`the model catalogue did not answer within ${Math.round(t/1e3)}s`:"could not reach the model catalogue"}}finally{clearTimeout(i)}}var _="https://api.howtofix.id/v1",ne="https://howtofix.id/keys",C=["howtofix","howtofix-free"];function re(n){try{let o=JSON.parse(b(M(n,"models.json"),"utf8")).providers;return!o||typeof o!="object"?new Set:new Set(Object.keys(o))}catch{return new Set}}function oe(){return{baseUrl:_,api:"openai-completions",headers:{[k]:T()}}}function se(n){let r=M(n,"models.json"),o;try{o=JSON.parse(b(r,"utf8"))}catch{return 0}let t=o.providers;if(!t||typeof t!="object")return 0;let s=0;for(let i of C){let e=t[i];if(!e||!Array.isArray(e.models))continue;let a=X(e.models),c={...e.headers??{},[k]:T()},u=e.headers?.[k]!==c[k];a.changed===0&&!u||(e.models=a.models,e.headers=c,s+=a.changed===0?1:a.changed)}if(s===0)return 0;try{y(r,`${JSON.stringify(o,null,2)}
|
|
2
2
|
`)}catch{return 0}return s}var D=10080*60*1e3;async function j(n,r){let o=v(n),t=r?.now??Date.now(),s,i=0;try{let c=JSON.parse(b(o,"utf8"));typeof c?.entries=="string"&&(s=R(c.entries),i=Number(c.at)||0)}catch{s=void 0}if(s&&s.size>0&&t-i<D&&!r?.force)return{index:s};let a=await I({fetchImpl:r?.fetchImpl});if(!a.ok)return s&&s.size>0?{index:s,message:a.message}:{index:new Map,message:a.message};try{$(n,{recursive:!0}),y(o,`${JSON.stringify({at:t,entries:N(a.index)})}
|
|
3
3
|
`)}catch{}return{index:a.index}}async function ie(n,r){let o=M(n,"models.json"),t;try{t=JSON.parse(b(o,"utf8"))}catch{return{changed:0}}let s=t.providers;if(!s||typeof s!="object")return{changed:0};let{index:i,message:e}=await j(n,r);if(i.size===0&&!r?.prices)return{changed:0,message:e};let a=0;for(let c of C){let u=s[c];if(!u||!Array.isArray(u.models))continue;let l=B(u.models,i,r?.prices);l.changed!==0&&(u.models=l.models,a+=l.changed)}if(a>0)try{y(o,`${JSON.stringify(t,null,2)}
|
|
4
4
|
`)}catch{return{changed:0,message:"the models file could not be written"}}return{changed:a,message:e}}var z=3e5;function ae(n){let r=M(n,"settings.json"),o={};try{let t=b(r,"utf8"),s=JSON.parse(t);s&&typeof s=="object"&&!Array.isArray(s)&&(o=s)}catch{if(L(r))return!1}if("httpIdleTimeoutMs"in o)return!1;o.httpIdleTimeoutMs=z;try{$(n,{recursive:!0}),y(r,`${JSON.stringify(o,null,2)}
|