howtofixcli 0.7.7 → 0.7.9

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.
Files changed (152) hide show
  1. package/dist/chunk-27TRKD65.js +2 -0
  2. package/dist/chunk-3FYCFLNK.js +1 -0
  3. package/dist/chunk-56SEAGAQ.js +1 -0
  4. package/dist/chunk-63ZCQDXH.js +6 -0
  5. package/dist/chunk-6FUWMLWO.js +1 -0
  6. package/dist/chunk-7CHDNTH6.js +1 -0
  7. package/dist/chunk-ACOMNDUL.js +185 -0
  8. package/dist/chunk-AEVPET7X.js +2 -0
  9. package/dist/chunk-AGGIYXN7.js +2 -0
  10. package/dist/chunk-BHVBO4SC.js +1 -0
  11. package/dist/chunk-FPXVDP32.js +8 -0
  12. package/dist/chunk-GIUYIKH3.js +109 -0
  13. package/dist/chunk-GQCAJ56I.js +5 -0
  14. package/dist/chunk-GXB7RZHH.js +1 -0
  15. package/dist/chunk-IGEY3AWF.js +1 -0
  16. package/dist/chunk-ILDDDLRC.js +1 -0
  17. package/dist/chunk-JFYVRWJI.js +2 -0
  18. package/dist/chunk-MVLCGU3G.js +1 -0
  19. package/dist/chunk-N345KWWK.js +1 -0
  20. package/dist/chunk-NBQFPCRT.js +1 -0
  21. package/dist/chunk-OIPSLIZE.js +5 -0
  22. package/dist/chunk-ORJ2QZBG.js +3 -0
  23. package/dist/chunk-PCALBZOO.js +2 -0
  24. package/dist/chunk-PDNBGUYP.js +2 -0
  25. package/dist/chunk-S656RE4A.js +1 -0
  26. package/dist/chunk-TSEKPGK4.js +1 -0
  27. package/dist/chunk-U6CI6KXN.js +34 -0
  28. package/dist/chunk-UTYFLLSM.js +1 -0
  29. package/dist/chunk-V3R4FYTJ.js +1 -0
  30. package/dist/chunk-V656XVXV.js +8 -0
  31. package/dist/chunk-WKUJ7CFO.js +1 -0
  32. package/dist/chunk-WOT6VMZA.js +1 -0
  33. package/dist/chunk-WUPU6LTD.js +4 -0
  34. package/dist/chunk-WX3V5P7U.js +5 -0
  35. package/dist/chunk-ZKZ6WCI3.js +2 -0
  36. package/dist/main.js +94 -536
  37. package/package.json +15 -62
  38. package/dist/account-credential.js +0 -136
  39. package/dist/account-credential.test.js +0 -38
  40. package/dist/activity.js +0 -124
  41. package/dist/agent-defs.js +0 -237
  42. package/dist/agent-limiter.js +0 -68
  43. package/dist/agents.js +0 -554
  44. package/dist/anim.js +0 -361
  45. package/dist/args.js +0 -228
  46. package/dist/at-file.js +0 -28
  47. package/dist/brand-extension.js +0 -87
  48. package/dist/brand.js +0 -76
  49. package/dist/browser.js +0 -58
  50. package/dist/cache-report.js +0 -139
  51. package/dist/checkpoint.js +0 -437
  52. package/dist/claims.js +0 -167
  53. package/dist/cli-auth.js +0 -142
  54. package/dist/cli-checkin.js +0 -116
  55. package/dist/cli-credentials.js +0 -254
  56. package/dist/clipboard.js +0 -149
  57. package/dist/collapse.js +0 -129
  58. package/dist/commands.js +0 -301
  59. package/dist/compaction-guard.js +0 -81
  60. package/dist/context-extension.js +0 -17
  61. package/dist/dcp/commands.js +0 -172
  62. package/dist/dcp/compress-state.js +0 -139
  63. package/dist/dcp/compress.js +0 -329
  64. package/dist/dcp/dcp-extension.js +0 -288
  65. package/dist/dcp/dedup.js +0 -93
  66. package/dist/dcp/ids.js +0 -189
  67. package/dist/dcp/index.js +0 -25
  68. package/dist/dcp/prompts.js +0 -68
  69. package/dist/dcp/protected-content.js +0 -221
  70. package/dist/dcp/protected.js +0 -161
  71. package/dist/dcp/prune.js +0 -418
  72. package/dist/dcp/state.js +0 -176
  73. package/dist/device-id.js +0 -90
  74. package/dist/device-id.test.js +0 -23
  75. package/dist/errors.js +0 -63
  76. package/dist/extensions.js +0 -48
  77. package/dist/fatal.js +0 -35
  78. package/dist/feed.js +0 -498
  79. package/dist/fs-atomic.js +0 -54
  80. package/dist/gateway-errors.js +0 -90
  81. package/dist/git.js +0 -230
  82. package/dist/goal-extension.js +0 -88
  83. package/dist/goal.js +0 -222
  84. package/dist/hooks-extension.js +0 -176
  85. package/dist/hooks.js +0 -443
  86. package/dist/howtofix-account.js +0 -715
  87. package/dist/hud-line.js +0 -153
  88. package/dist/hwid.js +0 -130
  89. package/dist/interrupt.js +0 -60
  90. package/dist/json-events.js +0 -50
  91. package/dist/level-style.js +0 -112
  92. package/dist/loop-guard.js +0 -95
  93. package/dist/lsp-tools.js +0 -32
  94. package/dist/lsp.js +0 -347
  95. package/dist/mcp-config.js +0 -85
  96. package/dist/mcp-lifecycle.js +0 -147
  97. package/dist/model-catalog.js +0 -217
  98. package/dist/model-resolve.js +0 -65
  99. package/dist/notes.js +0 -78
  100. package/dist/oauth-login.js +0 -568
  101. package/dist/paths.js +0 -61
  102. package/dist/permissions.js +0 -298
  103. package/dist/plan-mode.js +0 -363
  104. package/dist/preset-command.js +0 -227
  105. package/dist/preset-extension.js +0 -35
  106. package/dist/preset-mcp.js +0 -292
  107. package/dist/presets.js +0 -727
  108. package/dist/prompt-files.js +0 -103
  109. package/dist/prompt-text.js +0 -41
  110. package/dist/proxy.js +0 -137
  111. package/dist/quality/ast.js +0 -196
  112. package/dist/quality/cognitive.js +0 -83
  113. package/dist/quality/cyclomatic.js +0 -30
  114. package/dist/quality/halstead.js +0 -83
  115. package/dist/quality/index.js +0 -18
  116. package/dist/quality/length.js +0 -3
  117. package/dist/quality/maintainability.js +0 -15
  118. package/dist/quality/nesting.js +0 -57
  119. package/dist/quality/report.js +0 -803
  120. package/dist/quality/smells.js +0 -67
  121. package/dist/quality-tool.js +0 -63
  122. package/dist/read-only-commands.js +0 -597
  123. package/dist/repo-map.js +0 -292
  124. package/dist/rtk.js +0 -193
  125. package/dist/sandbox.js +0 -105
  126. package/dist/schema.js +0 -214
  127. package/dist/session-lifecycle.js +0 -19
  128. package/dist/session-retention.js +0 -111
  129. package/dist/session.js +0 -446
  130. package/dist/sessions.js +0 -100
  131. package/dist/settings.js +0 -148
  132. package/dist/skills.js +0 -35
  133. package/dist/slop-tool.js +0 -96
  134. package/dist/spend-cap.js +0 -43
  135. package/dist/subagent.js +0 -171
  136. package/dist/tar.js +0 -146
  137. package/dist/theme.js +0 -79
  138. package/dist/thinking.js +0 -45
  139. package/dist/todo.js +0 -114
  140. package/dist/tool-loadout.js +0 -97
  141. package/dist/tool-render.js +0 -769
  142. package/dist/tools.js +0 -176
  143. package/dist/ui.js +0 -4751
  144. package/dist/update.js +0 -533
  145. package/dist/usage-segment.js +0 -69
  146. package/dist/web-tools.js +0 -46
  147. package/dist/web.js +0 -265
  148. package/dist/welcome.js +0 -179
  149. package/dist/workflow-engine.js +0 -246
  150. package/dist/workflow-progress.js +0 -446
  151. package/dist/workflow-view.js +0 -195
  152. package/dist/workflow.js +0 -349
@@ -0,0 +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-OIPSLIZE.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
+ `)}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};
@@ -0,0 +1,2 @@
1
+ function d(n,t){let e=`${n??""} ${t}`;if(/EACCES|EPERM/.test(e))return"the file or directory is not writable; check permissions and try again";if(/ENOENT/.test(e))return"a file or directory this command needs is missing";if(/ENOSPC/.test(e))return"the disk is full";if(/ECONNREFUSED|ENOTFOUND|EAI_AGAIN|ETIMEDOUT|UND_ERR|fetch failed/i.test(e))return"the network request failed; check the connection and the gateway address";if(/EADDRINUSE/.test(e))return"another process is already using that port";if(/MODULE_NOT_FOUND|ERR_MODULE_NOT_FOUND/.test(e))return"a required file or package is missing; reinstall HowToFix";if(/JSON/i.test(e)&&/parse|unexpected token|end of input/i.test(e))return"a configuration file is not valid JSON";if(/not a git repository/i.test(e))return"run the command inside a project, or pass --cwd"}function c(n){let e=(n instanceof Error?n.message:String(n)).trim()||"unknown error",i=n?.code;return{message:e,hint:d(i,e)}}function u(n,t,e,i=!1){let{message:r,hint:s}=c(e),o=[t?`${n}: ${t}: ${r}`:`${n}: ${r}`];return s&&o.push(` ${s}`),i&&e instanceof Error&&e.stack&&o.push(e.stack),o.join(`
2
+ `)}function f(n,t,e,i){let r=i?.debug??process.env.HOWTOFIX_DEBUG==="1";(i?.write??(a=>console.error(a)))(u(n,t,e,r))}export{c as a,f as b};
@@ -0,0 +1 @@
1
+ var r=/no available channel for model\s+([^\s"',)\]]+)/i;function i(t){let e=t??"";if(e.trim())return r.exec(e)?.[1]}function a(t){let e=t??"";if(!e.trim())return;let n=i(e);if(n)return`the gateway has no live channel for ${n} right now \u2014 /model lists the models that answer; pick another.`;if(/\bunknown model\b/i.test(e))return"/connect pulls the current model list from the gateway.";if(/\bcode 11128\b|\billegal api invocation\b/i.test(e))return"the gateway refused the request shape (code 11128) \u2014 /connect re-syncs each model's compatibility flags.";if(/\binsufficient (?:balance|quota|credit)\b|\bexceeded your current quota\b|http\s*402/i.test(e))return"the account is out of credit \u2014 /usage shows what is left.";if(/\bserver error\b|http\s*5\d\d/i.test(e))return"the gateway's channel is failing, not the CLI \u2014 /model lists what your account can reach; pick another.";if(/\brate.?limit|\b429\b/i.test(e))return"the gateway is rate-limiting this token \u2014 wait a moment, then resend the prompt.";if(/\bupstream api error\b/i.test(e))return"the gateway refused the request \u2014 run /connect again to re-sync your models."}export{i as a,a as b};
@@ -0,0 +1,8 @@
1
+ import{m as p,n as d}from"./chunk-V656XVXV.js";import"./chunk-UTYFLLSM.js";import"./chunk-WOT6VMZA.js";import{execFileSync as v}from"node:child_process";import{existsSync as m,mkdirSync as x,readFileSync as S,readdirSync as j,statSync as $,writeFileSync as z}from"node:fs";import{join as r,relative as b,resolve as u}from"node:path";function F(o){let e=o.replace(/-/g," ").replace(/\b\w/g,t=>t.toUpperCase());return[{path:"preset.json",body:`${JSON.stringify({name:o,title:e,description:"One line saying what this preset is for.",category:"engineering",version:"1.0.0",skills:[`${o}-skill`]},null,2)}
2
+ `},{path:"prompt.md",body:["Rules the model should follow while this preset is active.","","This text is appended to the system prompt, never substituted for it, so it","adds to the agent's own rules rather than replacing them. Delete this file if","the preset only needs skills.",""].join(`
3
+ `)},{path:r("skills",`${o}-skill`,"SKILL.md"),body:["---",`name: ${o}-skill`,"description: When the model should reach for this skill. This line is what"," the model reads when deciding, so say when to use it, not what it contains.","---","",`# ${e}`,"","What the model should do, as instructions. A skill is read on demand: only the","frontmatter above is in every request, so the body costs nothing until used.","","Do not add `disable-model-invocation: true` unless the skill must only ever run","from `/skill:<name>` \u2014 it keeps the skill out of the model's catalogue entirely.",""].join(`
4
+ `)}]}function g(){return["usage:"," howtofix preset new <name> [dir] write a preset skeleton"," howtofix preset check [dir] validate a preset with the installer's rules"," howtofix preset pack [dir] build <name>-<version>.tar.gz for publishing","","A preset is a directory holding preset.json, an optional prompt.md, and a","skills/ tree. `check` runs the same validation the installer runs, so a preset","that passes here will not be refused at install."].join(`
5
+ `)}function w(o){let e=[],t=s=>{for(let l of j(s,{withFileTypes:!0}).sort((n,i)=>n.name.localeCompare(i.name))){let n=r(s,l.name);l.isDirectory()?t(n):e.push(b(o,n).split("\\").join("/"))}};return t(o),e}function C(o){let{manifest:e,problems:t}=d(o);if(!e){console.log(`not installable: ${o}`);for(let a of t)console.log(` - ${a}`);return!1}let s=p(o,e);if(s.length>0){console.log(`not installable: ${o}`);for(let a of s)console.log(` - ${a}`);return!1}let l=e.skills??[],n=0,i=0;for(let a of l){let f=r(o,"skills",a,"SKILL.md"),k=m(f)?/^---\r?\n([\s\S]*?)\r?\n---/.exec(S(f,"utf8")):null,y=k&&/^disable-model-invocation:\s*(.*)$/m.exec(k[1]);y&&y[1].trim().replace(/^["']|["']$/g,"").toLowerCase()==="true"?i+=1:n+=1}let h=w(o),c=h.reduce((a,f)=>a+$(r(o,f)).size,0);return console.log(`installable: ${e.name} ${e.version??""}`.trim()),console.log(` ${h.length} files, ${(c/1024).toFixed(1)} KB`),console.log(` ${l.length} skill(s): ${n} the model can choose`),i>0&&console.log(` ${i} invoke-only \u2014 reachable only as /skill:<name>`),!0}function L(o){let{manifest:e,problems:t}=d(o);if(!e){console.log(`cannot pack: ${o}`);for(let c of t)console.log(` - ${c}`);return!1}let s=p(o,e);if(s.length>0){console.log("cannot pack: the preset does not validate");for(let c of s)console.log(` - ${c}`);return!1}let l=e.version??"1.0.0",n=u(`${e.name}-${l}.tar.gz`),i=w(o);v("tar",["-czf",n,"-C",o,...i]);let h=$(n).size;return console.log(`packed ${n}`),console.log(` ${i.length} files, ${(h/1024).toFixed(1)} KB`),console.log(""),console.log("to offer it to the community registry, open a pull request adding an entry"),console.log("that names the repo, a pinned commit, and the skill directory inside it."),!0}function A(o){let[e,t]=o;if(!e||e==="--help"||e==="-h")return console.log(g()),e?0:2;if(e==="new"){if(!t)return console.log(`preset new: a name is required
6
+ `),console.log(g()),2;if(!/^[a-z0-9][a-z0-9-]*$/.test(t))return console.log(`preset new: "${t}" is not a usable name.`),console.log(" lower-case letters, digits and hyphens; must start with a letter or digit."),console.log(" The installer refuses anything else, and it refuses at install time."),2;let s=o[2]?u(o[2]):u("."),l=r(s,t);if(m(l))return console.log(`preset new: ${l} already exists.`),1;for(let n of F(t)){let i=r(l,n.path);x(r(i,".."),{recursive:!0}),z(i,n.body),console.log(` wrote ${b(l,i)}`)}return console.log(`
7
+ wrote ${l}`),console.log(` edit preset.json and the skill, then: howtofix preset check ${t}`),0}if(e==="check"||e==="pack"){let s=u(t??".");return m(r(s,"preset.json"))?(e==="check"?C(s):L(s))?0:1:(console.log(`${e}: no preset.json in ${s}`),2)}return console.log(`preset: unknown subcommand "${e}"
8
+ `),console.log(g()),2}export{A as runPresetCommand};
@@ -0,0 +1,109 @@
1
+ import{u as Cs}from"./chunk-WUPU6LTD.js";import{a as As}from"./chunk-ORJ2QZBG.js";import{Aa as er,Ba as tr,C as ht,Ca as nr,D as Ds,Da as or,F as Ws,Fa as ae,Ga as T,Ha as O,I as Us,Ia as sr,J as Ks,Ja as rr,K as gt,Ka as ir,L as Hs,La as ar,M as Gs,Ma as kn,N as Bs,Na as lr,O as gn,Oa as cr,Ra as dr,Sa as ur,Ta as fr,U as De,Ua as mr,Va as pr,Wa as hr,X as wn,Xa as gr,Z as bn,aa as We,c as Es,e as Ps,g as Is,ga as qs,h as _s,ha as Ue,ja as wt,n as Ns,na as Vs,oa as zs,qa as Ys,ra as Xs,sa as Js,va as Zs,w as Fs,y as hn,ya as yn,z as js,za as Qs}from"./chunk-ACOMNDUL.js";import{a as Ts,c as mt,d as un,j as Ms,l as fn,m as mn,n as Rs}from"./chunk-JFYVRWJI.js";import{b as ke,c as je,e as Os,f as pn,g as Ls,h as pt}from"./chunk-27TRKD65.js";import{b as wr,c as br}from"./chunk-WX3V5P7U.js";import{a as yr,b as kr}from"./chunk-BHVBO4SC.js";import{a as ss,b as rs}from"./chunk-6FUWMLWO.js";import{A as on,B as sn,C as ts,D as P,I as ns,J as os,b as tn,c as it,d as at,e as Ko,f as Ho,g as Go,h as Bo,i as lt,j as qo,k as nn,l as Vo,o as ee,p as zo,q as Yo,t as Xo,u as Jo,v as Zo,w as Qo,x as ct,y as dt,z as es}from"./chunk-V656XVXV.js";import{b as rn,c as ye,d as ls,g as cs,m as an,n as ds,p as ie,r as Ae,t as us,v as fs,w as ms,x as ps,y as hs,z as ln}from"./chunk-63ZCQDXH.js";import{a as gs,b as ws,c as bs,e as ys,f as ks,g as $s,h as vs,k as xs}from"./chunk-PDNBGUYP.js";import{a as re}from"./chunk-UTYFLLSM.js";import{h as is,i as as}from"./chunk-ZKZ6WCI3.js";import{a as en,b as rt,e as Uo}from"./chunk-OIPSLIZE.js";import{a as ut,b as cn,c as dn,d as Ss,e as ft}from"./chunk-3FYCFLNK.js";import"./chunk-WOT6VMZA.js";import{execFile as Al}from"node:child_process";import{promisify as Tl}from"node:util";import{appendFileSync as Ml,existsSync as Rt,mkdirSync as Fi,readFileSync as Gn,rmSync as Rl,writeFileSync as Bn}from"node:fs";import{basename as El,join as le,resolve as Pl}from"node:path";function $r(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 vr(e){let t=!1;process.on("SIGINT",()=>{t||(t=!0,e())})}function da(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 ua(e){let t=e?.input??0,n=e?.cacheRead??0,s=e?.cacheWrite??0;return{input:t,cacheRead:n,cacheWrite:s,prompt:t+n+s}}function fa(e){if(typeof e!="string")return null;let t=Date.parse(e);return Number.isNaN(t)?null:t}function ma(e){if(!e||typeof e!="object")return;let t=e,s=(t.message&&typeof t.message=="object"?t.message:void 0)??t,r=da(s.usage);if(!r)return;let u=typeof s.provider=="string"?s.provider:"",f=typeof s.model=="string"?s.model:"";return{usage:r,model:[u,f].filter(Boolean).join("/")}}function xr(e){let t=0,n=0,s=[],r=0,u=null;for(let h of e){let b=ma(h);if(!b)continue;let{input:x,cacheRead:M,cacheWrite:j,prompt:D}=ua(b.usage);if(D===0)continue;t+=M,n+=x+j;let W=fa(h.timestamp),I=u,U=I?I.at:null;if(I!==null&&M===0&&x>=1e3){let L=W!==null&&U!==null?Math.max(0,W-U):0;s.push({missedTokens:x,idleMs:L,modelChanged:b.model!==""&&I.model!==""&&b.model!==I.model}),r+=x}u={prompt:D,at:W??U??null,model:b.model}}let f=t+n;return{cachedTokens:t,billedTokens:n,hitRate:f>0?t/f*100:null,misses:s,missedTokens:r}}function Sr(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 Il,SessionManager as _l}from"@netrodev/hxf-coding-agent";import{CombinedAutocompleteProvider as ji,Container as Ol,Editor as Ll,matchesKey as V,ProcessTerminal as Nl,ScrollView as Fl,KeybindingsManager as Ki,setKeybindings as Hi,TUI_KEYBINDINGS as Gi,SelectList as jl,TuiAltScreen as Dl,truncateToWidth as Re,VStack as Wl,visibleWidth as Pt,wrapTextWithAnsi as Ul}from"@netrodev/hxf-tui";import{spawn as pa}from"node:child_process";function ha(e,t,n=2e3){return new Promise(s=>{let r=!1,u,f=x=>{r||(r=!0,u!==void 0&&clearTimeout(u),s(x))},h;try{h=pa(e,[...t],{stdio:["ignore","pipe","ignore"]})}catch{f({ok:!1,stdout:""});return}u=setTimeout(()=>{h.kill("SIGKILL"),f({ok:!1,stdout:""})},n);let b=[];h.stdout?.on("data",x=>b.push(x)),h.on("error",()=>f({ok:!1,stdout:""})),h.on("close",x=>{f({ok:x===0,stdout:Buffer.concat(b).toString("utf8")})})})}function $n(){return process.env.XDG_SESSION_TYPE==="wayland"||(process.env.WAYLAND_DISPLAY?.length??0)>0}async function ga(){let e=[];process.platform==="darwin"?e.push({command:"pbpaste",args:[]}):process.platform==="win32"?e.push({command:"powershell.exe",args:["-NoProfile","-Command","Get-Clipboard -Raw"]}):($n()&&(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||!$n())&&(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 ha(t.command,t.args);if(n.ok&&n.stdout.length>0)return n.stdout}}async function Cr(){let e;try{let{getNativeClipboard:s}=await import("@netrodev/hxf-tui");e=s()}catch{e=void 0}if(e)try{let s=await e.getText();if(typeof s=="string"&&s.length>0)return{ok:!0,text:s}}catch{}let t=await ga();return t!==void 0?{ok:!0,text:t}:{ok:!1,reason:`no clipboard tool could read it \u2014 ${$n()?"install wl-clipboard (wl-paste)":process.platform==="darwin"?"pbpaste should be present on macOS":process.platform==="win32"?"Get-Clipboard should be present on Windows":"install xclip or xsel, or run under a display"}`}}import{TreeSelectorComponent as Kl,initTheme as Hl}from"@netrodev/hxf-coding-agent";import{getKeybindings as Di}from"@netrodev/hxf-tui";import{mixColors as wa,parseColor as ba,styleText as de}from"@netrodev/hxf-tui";var ue=process.env.HOWTOFIX_NO_MOTION!=="1",ya=45,Ar=5,Tr=8,vn=1e4,Mr=6e4,Rr=3,Er=4,xn=e=>e<0?0:e>1?1:e;function fe(e,t,n){let s=xn(n);return s>=1?t:s<=0?e:wa(e,t,s)}var bt=class{value;velocity=0;last=Date.now();target;constructor(t,n=t){this.value=t,this.target=n}set(t){this.target=t}get moving(){return Math.abs(this.target-this.value)>.15}snap(t){this.value=t,this.target=t,this.velocity=0,this.last=Date.now()}step(t=Date.now()){let n=Math.max(0,t-this.last),s=Math.min(250,n)/1e3;if(this.last=t,!ue)return this.value=this.target,this.velocity=0,this.value;n>250&&(this.velocity=0);let r=150,u=2*Math.sqrt(r),f=Math.max(1,Math.ceil(s/.008)),h=s/f;for(let b=0;b<f;b+=1)this.velocity+=(this.target-this.value)*r*h-this.velocity*u*h,this.value+=this.velocity*h;return this.moving||(this.value=this.target,this.velocity=0),this.value}};function Sn(e,t,n,s){return!ue||e<=vn?t:e>=Mr?s:fe(n,s,(e-vn)/(Mr-vn))}function Pr(e,t){return!ue||t<=0||e<0?1:1-(1-xn(e/t))**3}function Ir(e,t){return ue&&e>=0&&e<t}var Cn=260,ka=45;function An(e,t,n=ka,s=400){return!ue||n<=0||e<0||e>=s?t:Math.min(t,Math.floor(e/n)+1)}function _r(e,t,n=Date.now(),s=1400){if(!ue||s<=0)return e;let r=n%s/s;return fe(e,t,r<.5?r*2:(1-r)*2)}function Or(e,t,n){let s=de(e,{fg:t.rest},ae);if(!ue||e.length===0)return s;let r=xn(n);if(r>=1)return s;let u=t.band??1,f=e.length+Er*2,b=Math.min(f-1,Math.floor(r*f))-Er,x=U=>{let L=Math.abs(U-b);return L>u?0:1-L/(u+1)},M="",j=0,D=null,W=0,I=0;for(let U of e){let L=x(I);D===null?D=L:L!==D&&(M+=de(e.slice(j,W),{fg:fe(t.rest,t.lit,D)},ae),j=W,D=L),W+=U.length,I+=1}return M+de(e.slice(j),{fg:fe(t.rest,t.lit,D??0)},ae)}function Lr(e,t,n=Date.now(),s=90){let r=t[0]??ba("#e6e6e6");if(t.length===0||e.length===0)return de(e,{fg:r},ae);if(!ue||s<=0)return de(e,{fg:t[t.length-1]??r},ae);let u=t.length*s,f=(n%u+u)%u,h="",b=0,x=null,M=0,j=0,D=W=>{let I=(f+W*s)/u%1*t.length,U=Math.floor(I)%t.length,L=(U+1)%t.length;return fe(t[U]??r,t[L]??r,I-Math.floor(I))};for(let W of e){let I=D(j);x===null?x=I:I!==x&&(h+=de(e.slice(b,M),{fg:x},ae),b=M,x=I),M+=W.length,j+=1}return h+de(e.slice(b),{fg:x??r},ae)}function $a(e,t){let n=Math.abs(e-t);return n>=Ar?0:Math.ceil((1-n/Ar)*Rr)/Rr}function Nr(e,t,n=Date.now()){let s=t.charMs??ya;if(!ue||e.length===0||s<=0)return de(e,{fg:t.base},ae);let r=e.length+Tr*2,u=n/s%r-Tr,f=(D,W)=>de(D,{fg:fe(t.base,t.bright,W)},ae),h="",b=0,x=null,M=0,j=0;for(let D of e){let W=$a(j,u);x===null?x=W:W!==x&&(h+=f(e.slice(b,M),x),b=M,x=W),M+=D.length,j+=1}return h+f(e.slice(b),x??0)}import{Markdown as Da,wrapTextWithAnsi as Wa}from"@netrodev/hxf-tui";import{homedir as va}from"node:os";import{isAbsolute as xa,relative as Sa,resolve as Ca,sep as Fr}from"node:path";var Aa="\u25CF",Rn="\u2514",kt="\u22EF",Tn=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"];function Ge(e=90){let t=Math.floor(Date.now()/e)%Tn.length;return Tn[t]??Tn[0]}var Ta="\u25B2";var Ma="\u25CB",Ra=["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 En(e){return e.includes("__")?e.slice(e.lastIndexOf("__")+2):e}function Ur(e){return Ra.includes(En(e))}function Ke(e,t=process.cwd()){if(!e||!xa(e))return e;let n=Ca(e),s=Sa(t,n);if(s==="")return".";if(s&&!s.startsWith(`..${Fr}`)&&s!=="..")return s;let r=va();return r&&(n===r||n.startsWith(r+Fr))?`~${n.slice(r.length)}`:n}function te(e,t){let n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,Math.max(1,t-1))}\u2026`:n}function N(e,t){if(e&&typeof e=="object"){let n=e[t];if(typeof n=="string"&&n.length>0)return n;if(typeof n=="number")return String(n)}}function Ea(e,t=160){if(!e||typeof e!="object")return"";try{let n=JSON.stringify(e);return n&&n!=="{}"?te(n,t):""}catch{return""}}function Pa(e,t){switch(e){case"read":{let n=Ke(N(t,"path")??""),s=[N(t,"offset"),N(t,"limit")].filter(Boolean);return s.length>0?`${n} ${s.length===1?`offset=${s[0]}`:`offset=${s[0]}, limit=${s[1]}`}`:n}case"edit":case"write":return Ke(N(t,"path")??"");case"bash":case"powershell":{let n=N(t,"command")??"";return t?.run_in_background===!0?`${n} [background]`:n}case"bash_output":{let n=N(t,"task_id"),s=N(t,"filter");return n?s?`${n} filter=${s}`:n:"all tasks"}case"kill_shell":return N(t,"task_id")??"";case"compress":{let n=N(t,"topic")??"",s=Array.isArray(t.content)?t.content.length:0;return s>1?`${n} (${s} ranges)`:n}case"grep":{let n=N(t,"pattern")??"",s=N(t,"path");return s?`${n} in ${Ke(s)}`:n}case"find":case"glob":{let n=N(t,"pattern")??N(t,"glob")??"",s=N(t,"path");return s?`${n} in ${Ke(s)}`:n}case"ls":return Ke(N(t,"path")??".");case"task":return N(t,"agent")??"task";case"ask":return N(t,"question")??"";case"web_search":return N(t,"query")??"";case"web_fetch":return N(t,"url")??"";case"lsp":{let n=N(t,"action")??"lsp",s=N(t,"file")??"",r=N(t,"line");return r?`${n} ${s}:${r}`:`${n} ${s}`}case"quality":return N(t,"path")??"changed files";case"think":return"private";case"todo":{let n=N(t,"op")??"view",s=N(t,"task"),r=t?.items;return n==="init"&&Array.isArray(r)?`init ${r.length} task${r.length===1?"":"s"}`:s?`${n} ${s}`:n}case"context":{let n=N(t,"op")??"list",s=N(t,"key");return s?`${n} ${s}`:n}case"workflow":{let n=N(t,"path");if(n)return n;let s=N(t,"code")??"",r=/export\s+const\s+meta\s*=\s*\{[\s\S]*?name\s*:\s*["'`]([^"'`]+)/.exec(s)?.[1];if(r)return r;let u=s.trim().split(`
2
+ `)[0]??"";return u.length>40?`${u.slice(0,40)}\u2026`:u}default:return Ea(t)}}function $e(e,t,n=100){let s=En(e),u=s!==e?s:s.charAt(0).toUpperCase()+s.slice(1),f=Ur(e)?Ta:Aa,h=te(Pa(s,t),n);return h?`${f} ${u}(${h})`:`${f} ${u}`}function Ia(e){let t=0,n=0;for(let s of e.split(`
3
+ `))s.startsWith("+")&&!s.startsWith("+++")?t+=1:s.startsWith("-")&&!s.startsWith("---")&&(n+=1);return{additions:t,removals:n}}function Te(e){let t=e?.content;return typeof t=="string"?t:Array.isArray(t)?t.map(n=>n&&typeof n=="object"&&n.type==="text"?String(n.text??""):"").join(""):""}function Be(e){let t=e?.details;return t&&typeof t=="object"?t:{}}function Pn(e){let t=e?.structuredContent;return t&&typeof t=="object"?t:{}}function jr(e){let t=e.exit_code;return typeof t=="number"&&Number.isFinite(t)?t:void 0}function _a(e){let t=[];if(e&&typeof e=="object"){t.push(e);let s=e.content;if(Array.isArray(s))for(let r of s){let u=r?.text;if(typeof u=="string")try{let f=JSON.parse(u);f&&typeof f=="object"&&t.push(f)}catch{}}}let n=[];for(let s of t){let r=["instances","instanceCount","count","parts","partsCreated"].map(b=>s[b]).find(b=>typeof b=="number"&&Number.isFinite(b));typeof r=="number"&&n.push(`${r} instance${r===1?"":"s"}`);let u=Mn(s,["files","written","paths"]);u&&n.push(u.join(", "));let f=Mn(s,["images","renders","screenshots"]);f&&n.push(`renders ${Ma} ${f.join(", ")}`);let h=Mn(s,["findings","warnings","errors"]);if(h&&n.push(`${h.length} finding${h.length===1?"":"s"}`),n.length>0)break}return n.length>0?n.join(" \xB7 "):void 0}function Mn(e,t){for(let n of t){let s=e[n];if(!Array.isArray(s))continue;let r=s.filter(u=>typeof u=="string"&&u!=="");if(r.length>0)return r}}function Dr(e){return e.trim().split(`
4
+ `).find(t=>t.trim())??""}function Oa(e,t){let n=typeof e.output=="string"?e.output:t.replace(/\n*Command exited with code \d+\s*$/,""),s=He(n);return s>0?` (${s} line${s===1?"":"s"})`:""}function La(e,t,n){return e===1?t:n}function He(e){let t=e.trim();return t?t.split(`
5
+ `).length:0}function Wr(e){return e<1e3?`${e} tokens`:`${(e/1e3).toFixed(1)}k tokens`}function $t(e,t,n){let s=Te(t),r=Be(t),u=Pn(t);if(n){let f=jr(u);if(f!==void 0&&(e==="bash"||e==="powershell"))return`exit ${f}`;let h=s.trim().split(`
6
+ `).find(b=>b.trim());return te(h??"failed",120)}if(Ur(e)){let f=_a(t);if(f)return f;let h=En(e);return h==="execute_luau"?"ran":te(h.replace(/_/g," "),120)}switch(e){case"task":{let f=s.split(`
7
+ `).filter(h=>h.startsWith("## ")).map(h=>h.replace(/^##\s*/,"").trim());if(f.length===0){let h=s.trim().split(`
8
+ `).find(b=>b.trim());return te(h??"done",120)}return f.map(h=>te(h,120)).join(`
9
+ `)}case"read":{let f=r.truncation,h=He(s.replace(/\n*\[[^\]]*\]\s*$/,"")),b=h===0?"empty":`${h} line${h===1?"":"s"}`;return f?.truncated?`${b} (truncated from ${f.totalLines??"?"})`:b}case"compress":{let f=Array.isArray(r.blockIds)?r.blockIds:[],h=typeof r.compressedTokens=="number"?r.compressedTokens:0,b=typeof r.summaryTokens=="number"?r.summaryTokens:0,x=f.length===1?`b${String(f[0])}`:`${f.length} blocks`;if(h===0)return x;let M=h-b;return M<0?`${x} \xB7 ${Wr(-M)} LARGER than the range`:`${x} \xB7 ${Wr(M)} saved`}case"edit":{let f=typeof r.diff=="string"?r.diff:"";if(!f)return"applied";let{additions:h,removals:b}=Ia(f);return`+${h} / -${b}`}case"write":{let f=He(s);return f===0?"written":`written (${f} ${La(f,"line","lines")})`}case"bash":case"powershell":{let f=jr(u);if(f===void 0)return s.trim()?te(Dr(s),120):"done";let h=Oa(u,s);return f===0?`exit 0${h}`:`exit ${f}`}case"grep":{let f=He(s);return f===0?"no matches":`${f} match${f===1?"":"es"}`}case"web_search":{let f=typeof r.count=="number"?r.count:He(s);return f===0?"no results":`${f} result${f===1?"":"s"}`}case"web_fetch":return`${typeof r.chars=="number"?r.chars:s.length} chars`;case"lsp":{let f=typeof r.count=="number"?r.count:void 0;return typeof r.error=="string"?te(r.error,120):f===void 0?te(Dr(s),120):`${f} location${f===1?"":"s"}`}case"quality":{if(typeof r.error=="string")return te(r.error,120);if(r.off===!0)return"off";let f=typeof r.files=="number"?r.files:0,h=typeof r.functions=="number"?r.functions:0,b=typeof r.findings=="number"?r.findings:0,x=typeof r.score=="number"?` \xB7 ${Math.round(r.score)}`:"";return f===0?"no files":`${f} file${f===1?"":"s"} \xB7 ${h} fn \xB7 ${b} finding${b===1?"":"s"}${x}`}case"todo":{let f=r.todos??[];if(!Array.isArray(f)||f.length===0)return"list cleared";let h=f.filter(x=>x.status==="completed").length,b=f.filter(x=>x.status==="pending"||x.status==="in_progress").length;return`${h}/${f.length} done, ${b} open`}case"context":{let f=r.notes,h=f?Object.keys(f).length:0;return h===0?"no notes":`${h} note${h===1?"":"s"} held`}case"workflow":{let f=typeof r.agents=="number"?r.agents:0,h=typeof r.outputTokens=="number"?r.outputTokens:0,b=Array.isArray(r.steps)?r.steps.filter(M=>M.status==="failed").length:0;if(typeof r.error=="string")return`failed after ${f} agent(s)`;let x=typeof r.startedAt=="number"&&typeof r.endedAt=="number"?`, ${ir(r.endedAt-r.startedAt)}`:"";return`${f} agent(s), ${h} tokens${x}${b>0?`, ${b} failed`:""}`}case"bash_output":{let f=s.trim().split(`
10
+ `)[0]??"",h=/running/.test(f)?"running":/finished/.test(f)?"finished":"task",b=s.trim().split(`
11
+ `).slice(2).filter(x=>x.trim()).length;return b===0?h:`${h} \xB7 ${b} line${b===1?"":"s"}`}case"kill_shell":{let f=s.trim().split(`
12
+ `)[0]??"";return f.startsWith("Stopped")?"stopped":te(f,120)}default:{let f=s.trim().split(`
13
+ `).find(h=>h.trim());return f?te(f,120):"done"}}}function Kr(e,t){let n=Be(t);if(e==="edit"&&typeof n.diff=="string")return n.diff.split(`
14
+ `).filter(s=>s.length>0).slice(0,12);if(e==="bash"||e==="powershell"){if(Te(t).startsWith("Started bash_"))return[];let r=Pn(t);return(typeof r.output=="string"?r.output:Te(t).replace(/\n*Command exited with code \d+\s*$/,"")).trimEnd().split(`
15
+ `).filter(h=>h.trim()).slice(-4)}if(e==="bash_output")return Te(t).split(`
16
+ `).slice(2).filter(r=>r.trim()).slice(-6);if(e==="todo"){let s=n.todos??[],r={pending:"[ ]",in_progress:"[>]",completed:"[x]",dropped:"[-]"};return s.slice(0,6).map(u=>`${r[u.status??"pending"]??"[ ]"} ${u.content??""}`)}return e==="task"?Te(t).split(`
17
+ `).filter(s=>s.trim()&&!s.startsWith("## ")).slice(0,6):e==="workflow"?(n.steps??[]).map(u=>{let f=u.status==="running"?"\u25B8":u.status==="failed"?"\xD7":"\u2713",h=u.phase?`${u.phase} \xB7 `:"";return`${f} ${h}${u.label??"agent"}`}).slice(-6):[]}var yt=400;function Hr(e,t){let n=Be(t);if(e==="edit"&&typeof n.diff=="string")return n.diff.split(`
18
+ `).filter(h=>h.length>0).slice(0,yt);let s=Pn(t),u=(typeof s.output=="string"?s.output:Te(t).replace(/\n*Command exited with code \d+\s*$/,"")).trimEnd().split(`
19
+ `),f=u.slice(0,yt);return u.length>yt&&f.push(`\u2026 ${u.length-yt} more line(s)`),f}var Na={read:{active:"Reading",done:"Read",one:"file",many:"files"},search:{active:"Searching for",done:"Searched for",one:"pattern",many:"patterns"},list:{active:"Listing",done:"Listed",one:"directory",many:"directories"}};function Fa(e){if(e==="read")return"read";if(e==="grep"||e==="find"||e==="glob")return"search";if(e==="ls")return"list"}function Gr(e,t=!1){let n=[],s,r=()=>{if(!s||s.indices.length<2){s=void 0;return}n.push({start:s.indices[0],indices:s.indices,counts:s.counts,summary:ja(s.counts,t)}),s=void 0};for(let[u,f]of e.entries()){let h=Fa(f.toolName);if(h===void 0){r();continue}s||(s={indices:[],counts:{}}),s.indices.push(u),s.counts[h]=(s.counts[h]??0)+1}return r(),n}function ja(e,t){let n=[];for(let s of["search","read","list"]){let r=e[s];if(r===void 0)continue;let u=Na[s],f=t?u.active:u.done,h=r===1?u.one:u.many;n.push(`${n.length===0?f:f.toLowerCase()} ${r} ${h}`)}return n.join(", ")}function qr(e,t){let n=e[e.length-1];return n&&n.kind==="note"&&n.title===t.title?[...e.slice(0,-1),t]:[...e,t]}function In(e){return typeof e=="string"?De(e):De(e.map(t=>t.type==="text"?t.text:t.type==="thinking"?"":t.type==="image"?"[image]":(t.type==="toolCall","")).filter(Boolean).join(""))}function Vr(e){return e.role==="user"?In(e.content).trim():""}function zr(e,t,n){let s=t.trim();if(!s)return e;let r=e.findIndex(f=>f.kind==="user"&&f.body.trim()===s);if(r===-1)return[...e,{id:n,kind:"user",title:"you",body:s}];let u=[...e];return u[r]={id:n,kind:"user",title:"you",body:s},u}function Ua(e){return e.content.filter(t=>t.type==="toolCall").map(t=>({name:t.name,arguments:t.arguments}))}function Ka(e){return e.content.filter(t=>t.type==="toolCall").map(t=>t.id)}function Ha(e){let t=e.map(f=>({toolName:f.kind==="result"||f.kind==="tool"?f.title:"",line:f.call??f.body})),n=Gr(t);if(n.length===0)return e;let s=new Map(n.map(f=>[f.start,f])),r=new Set(n.flatMap(f=>f.indices)),u=[];for(let[f,h]of e.entries()){let b=s.get(f);if(b){let x=e[b.start];u.push({id:x?.id??`g-${b.start}`,kind:"collapsed",title:"collapsed",body:b.summary,full:b.indices.map(M=>e[M]?.call??e[M]?.body??"").filter(Boolean)});continue}r.has(f)||u.push(h)}return u}function xt(e){let t=[];for(let n of e)if(n.role==="user"){let s=In(n.content).trim();if(!s)continue;t.push({id:`u-${n.timestamp}`,kind:"user",title:"you",body:s})}else if(n.role==="assistant"){let s=In(n.content).trim(),r=Ua(n),u=Ka(n);s?t.push({id:`a-${n.timestamp}`,kind:n.stopReason==="error"?"error":"assistant",title:n.errorMessage?"failed":"fix",body:n.errorMessage?`${n.errorMessage}
20
+
21
+ ${s}`:s}):n.errorMessage&&t.push({id:`e-${n.timestamp}`,kind:"error",title:"failed",body:n.errorMessage}),r.forEach((f,h)=>{let b=u[h];t.push({id:b?`tool-${b}`:`c-${n.timestamp}-${h}`,kind:"tool",title:f.name,body:$e(f.name,f.arguments),...b?{call:$e(f.name,f.arguments)}:{}})})}else if(n.role==="toolResult"){let s=$t(n.toolName,{content:n.content},n.isError),r=t.find(u=>u.id===`tool-${n.toolCallId}`);r?(r.kind="result",r.body=s,r.title=n.toolName):t.push({id:`r-${n.toolCallId}`,kind:"result",title:n.toolName,body:s})}return Ha(t)}function Br(e,t,n){return Wa(e,Math.max(8,t)).map(s=>O(s,n))}var qe=new Map;function Ga(e){let t=e.body||" ",n=qe.get(e.id);if(n)return n.text!==t&&(n.component.setText(t),n.text=t),n.component;let s=new Da(t,0,0,sr);return qe.set(e.id,{text:t,component:s}),s}var _n=class{constructor(t){this.item=t}item;invalidate(){}shade(t){let n=Date.now()-(this.item.born??0);return fe(T.dim,t,Pr(n,Cn))}render(t){let n=this.item.body;if(this.item.kind==="user"){let r=this.item.pending?[O(" queued \u2014 the run reads this at its next step",T.dim)]:[];return["",...Br(`> ${n}`,t,this.shade(T.user)),...r]}if(this.item.kind==="tool")return[O(`${Ge()} ${n}`,this.shade(T.tool))];if(this.item.kind==="collapsed"){let r=[O(`${kt} ${n}`,this.shade(T.mute))],u=this.item.full??[];if(u.length>0)if(this.item.expanded===!0)for(let f of u)r.push(O(` ${f}`,this.shade(T.dim)));else r.push(O(` ${u.length} call(s) \xB7 ctrl+e to expand`,T.dim));return r}if(this.item.kind==="result"){let r=n.startsWith("exit ")&&n!=="exit 0";if(this.item.panel)return["",...this.item.panel(t),...n?[O(` ${Rn} ${n}`,r?T.bad:T.mute)]:[]];let u=[];this.item.call&&u.push(O(this.item.call,this.shade(T.tool)));let f=` ${Rn} ${n}`;if(u.push(O(f,r?T.bad:this.shade(T.mute))),this.item.expanded===!0&&(this.item.full?.length??0)>0){let M=O(` ${this.item.full.length} line(s) \xB7 ctrl+e to collapse`,T.dim);u.push(O(` ${kt}`,T.dim));for(let j of this.item.full){let D=j.startsWith("+")?T.tool:j.startsWith("-")?T.bad:T.dim;u.push(O(` ${j}`,D))}return u.push(M),u}let b=this.item.detail??[],x=An(Date.now()-(this.item.born??0),b.length);for(let M of b.slice(0,x)){let j=M.startsWith("+")?T.tool:M.startsWith("-")?T.bad:T.dim;u.push(O(` ${M}`,this.shade(j)))}return(this.item.full?.length??0)>0&&u.push(O(` ${kt} ${this.item.full.length} line(s) \xB7 ctrl+e to expand`,T.dim)),u}if(this.item.kind==="error"||this.item.kind==="note"){let r=this.item.kind==="error"?T.bad:T.mute;return["",...Br(n,t,this.shade(r))]}return["",...Ga(this.item).render(Math.max(8,t-2))]}},vt=class{items=[];status="";scrollOffset=0;scrollAnchor;settledOffset=0;viewportHeight=0;invalidate(){}entering(){let t=Date.now();return this.items.some(n=>{if(n.born===void 0)return!1;let s=t-n.born;return Ir(s,Cn)?!0:(n.detail?.length??0)>An(s,n.detail?.length??0)})}render(t){if(qe.size>this.items.length){let r=new Set(this.items.map(u=>u.id));for(let u of qe.keys())r.has(u)||qe.delete(u)}let n=[];for(let r of this.items)r.born??=Date.now(),n.push(...new _n(r).render(t));this.status&&n.push(O(this.status,T.mute));let s=this.viewportHeight;if(s>0&&n.length>s){let r=n.length-s;this.scrollOffset!==this.settledOffset&&(this.scrollAnchor=void 0);let u=this.scrollAnchor,f;if(u!==void 0){let h=n.length-u;h>=0&&h<=r?f=h:f=Math.max(0,Math.min(this.scrollOffset,r))}else f=Math.max(0,Math.min(this.scrollOffset,r));return u===void 0&&(this.scrollOffset=f),this.settledOffset=this.scrollOffset,f===0?this.scrollAnchor=void 0:this.scrollAnchor===void 0&&(this.scrollAnchor=n.length-f),n.slice(r-f,r-f+s)}return n}};import{parseColor as Z}from"@netrodev/hxf-tui";var me={off:Z("okhsl(230 12% 46%)"),minimal:Z("okhsl(240 55% 49%)"),low:Z("okhsl(252 60% 55%)"),medium:Z("okhsl(270 64% 60%)"),high:Z("okhsl(298 70% 64%)"),xhigh:Z("okhsl(332 80% 66%)"),max:Z("okhsl(42 95% 64%)")},Yr={off:Z("okhsl(230 14% 64%)"),minimal:Z("okhsl(240 60% 64%)"),low:Z("okhsl(252 64% 68%)"),medium:Z("okhsl(270 68% 72%)"),high:Z("okhsl(298 74% 76%)"),xhigh:Z("okhsl(332 82% 78%)"),max:Z("okhsl(42 96% 76%)")};function St(e){return me[e]??me.medium}var Jr=[me.minimal,me.low,me.medium,me.high,me.xhigh,me.max];function Zr(e){return Yr[e]??Yr.medium}var Xr=460;function Ct(e){return!Number.isFinite(e)||e<0||e>=Xr?0:1-e/Xr}var G=["off","minimal","low","medium","high","xhigh","max"];function Qr(e){let t=e?.thinkingLevelMap;if(t===void 0)return G[G.length-1];for(let n=G.length-1;n>=0;n-=1)if(typeof t[G[n]]=="string")return G[n]}function ei(e){let t=G.indexOf(e);return G[(t+1+G.length)%G.length]}function ti(e){let t=G.indexOf(e);return G[(t-1+G.length)%G.length]}import{mkdirSync as za,readFileSync as Ya}from"node:fs";import{dirname as Xa}from"node:path";var Ln="\x1B[0m",B="\x1B[2m",Ba="\x1B[1m",qa="\x1B[31m",Nn="\x1B[32m",oi="\x1B[33m",ni="\x1B[35m",On="\x1B[36m";function F(e,t){return`${t}${e}${Ln}`}function si(e,t){return O(e,St(t))}function ri(e){return e>=85?qa:e>=70?oi:Nn}var Va="\u2726";function ii(e,t,n,s){let r=F(`[${e}]`,On),u=`${F(Va,B)} ${t}`,f=F(n,oi),h=s?` ${F("git:(",ni)}${F(s.replace(/^git:\(/,"").replace(/\)$/,""),On)}${F(")",ni)}`:"";return`${r}${F(" \u2502 ",B)}${u}${F(" \u2502 ",B)}${f}${h}`}function ai(e,t,n){if(!t)return e;let s=n===void 0?t:`${t} ${F(ar(n),B)}`;return`${F(s,On)} ${F("\u2502",B)} ${e}`}function li(e,...t){let n=Number.isFinite(e)?Math.min(100,Math.max(0,e)):0,s=Math.round(n/10),r=ri(n),u=`${r}${"\u2588".repeat(s)}${B}${"\u2591".repeat(10-s)}${Ln}`,f=F(`${Math.round(n)}%`,r),h=t.filter(Boolean).join(F(" \u2502 ",B));return`${F("Context",B)} ${u} ${f}${h?`${F(" \u2502 ",B)}${h}`:""}`}function ci(e){return!Number.isFinite(e)||e<=0?"":`${F("Spent",B)} ${F(`$${e.toFixed(3)}`,Nn)}`}function di(e,t,n,s){let r=Number.isFinite(t)&&t>0?t:0,u=Number.isFinite(n)?Math.max(0,n):0,f=Math.max(0,r-u),h=r>0?Math.min(100,u/r*100):0,b=Math.round(h/10),x=ri(h),M=`${x}${"\u2588".repeat(b)}${B}${"\u2591".repeat(10-b)}${Ln}`,j=D=>`${D.toFixed(2)} ${s}`;return[`${F(e,Ba)}${F(" account",B)}`,` ${F("used",B)} ${M} ${F(`${h.toFixed(1)}%`,x)}`,` ${F("granted",B)} ${j(r)}`,` ${F("spent",B)} ${j(u)}`,` ${F("remaining",B)} ${F(j(f),x)}`]}function Fn(e,t,n){let s=n===null?"":F(` ${n}ms`,B),r=t&&t!=="USD"?`${t} `:"";return`${F("Balance",B)} ${F(`${r}${e}`,Nn)}${s}`}var jn=ns,Ja=18e4;async function Za(e){let t=new Set((await e.modelRuntime.getAvailable()).map(r=>r.provider).filter(r=>ie(r))),n=ye.find(r=>t.has(r));return n?(await e.modelRuntime.getAuth(n))?.auth?.apiKey:void 0}function Qa(){try{let e=JSON.parse(Ya(jn,"utf8"));return!e.data||typeof e.cachedAt!="number"?void 0:{data:e.data,cachedAt:e.cachedAt}}catch{return}}function At(e){if(e.unlimited)return Fn("unlimited","",e.latencyMs);let n=e.unit==="USD"||e.unit==="CNY"?`$${e.remaining.toFixed(2)}`:`${e.remaining.toLocaleString()}`;return Fn(n,e.unit,e.latencyMs)}async function ui(e){let t=Qa();if(t&&Date.now()-t.cachedAt<Ja)return At(t.data);let n=await Za(e);if(!n)return t?At(t.data):void 0;let s=Date.now(),r=await Ae(n,{timeoutMs:3e3});if(!r.ok)return t?At(t.data):void 0;let u={remaining:r.remaining??0,limit:r.limit??0,unit:r.unit,unlimited:r.unlimited,latencyMs:Date.now()-s};return za(Xa(jn),{recursive:!0}),re(jn,JSON.stringify({data:u,cachedAt:Date.now()})),At(u)}import{chmodSync as el,existsSync as tl,readFileSync as nl}from"node:fs";import{join as ol}from"node:path";function fi(e){return ol(e,"account-credential.json")}function mi(e,t){return Buffer.from(`${e}:${t}`,"utf8").toString("base64")}function Dn(e){let t=e.trim();if(!t)return null;let n=r=>{let u=r.indexOf(":");return u<=0||u===r.length-1?null:{username:r.slice(0,u),password:r.slice(u+1)}},s=n(t);if(s)return s;try{let r=Buffer.from(t,"base64").toString("utf8");return r.includes(":")?n(r):null}catch{return null}}function pi(e,t,n){try{let s={credential:mi(t,n),username:t,savedAt:Math.floor(Date.now()/1e3)},r=fi(e);return re(r,JSON.stringify(s,null,2)),el(r,384),!0}catch{return!1}}function hi(e){try{let t=fi(e);if(!tl(t))return null;let n=JSON.parse(nl(t,"utf8"));return!n?.credential||!n?.username?null:n}catch{return null}}async function sl(e,t){let n=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t),signal:AbortSignal.timeout(2e4)}),s=await n.text(),r;try{r=JSON.parse(s)}catch{throw new Error(`the panel answered ${n.status} with something that is not JSON`)}let u=r;if(!n.ok||u.success===!1)throw new Error(u.message||`the panel answered ${n.status}`);return u.data}async function gi(e,t,n,s){let r=await sl(`${e}/api/auth/cli/credential`,{credential:mi(t,n),client_info:s});if(!r?.token)throw new Error("the panel accepted the credential but returned no key");return{token:r.token}}import{execFileSync as rl}from"node:child_process";import{createHash as il}from"node:crypto";import{readFileSync as al}from"node:fs";import{arch as ll,hostname as cl,platform as wi}from"node:os";function dl(e){try{return al(e,"utf8").trim()}catch{return""}}function bi(e,t){try{return rl(e,t,{encoding:"utf8",timeout:3e3})}catch{return""}}function ul(){return bi("reg",["query","HKLM\\SOFTWARE\\Microsoft\\Cryptography","/v","MachineGuid"]).match(/MachineGuid\s+REG_SZ\s+([0-9a-fA-F-]+)/)?.[1]??""}function fl(){return bi("ioreg",["-rd1","-c","IOPlatformExpertDevice"]).match(/"IOPlatformUUID"\s*=\s*"([^"]+)"/)?.[1]??""}function ml(){return["/sys/class/dmi/id/product_uuid","/sys/class/dmi/id/board_serial","/sys/class/dmi/id/product_serial","/etc/machine-id","/var/lib/dbus/machine-id"].map(dl).filter(Boolean)}function pl(){switch(wi()){case"win32":{let e=ul();return e?[e]:[]}case"darwin":{let e=fl();return e?[e]:[]}default:return ml()}}var Tt;function yi(){if(Tt)return{id:Tt,weak:!1};let e=pl(),t=e.length===0,n=[wi(),ll(),...e,t?cl():""].join("|");return Tt=il("sha256").update(n).digest("hex").slice(0,32),{id:Tt,weak:t}}var hl="/cli/checkin",gl=["Bearer",""].join(" ").trim(),wl=5e5;function Wn(e){return`$${(e/wl).toFixed(2)}`}async function ki(e,t,n,s,r){let u=new AbortController,f=setTimeout(()=>u.abort(),r);try{let h=await s(`${n}${hl}`,{method:t,headers:{[is]:as(),"X-HowToFix-Device":yi().id,Authorization:`${gl} ${e}`},signal:u.signal}),b={};try{b=await h.json()}catch{}return{status:h.status,body:b}}finally{clearTimeout(f)}}async function Un(e,t){let n=(t?.baseUrl??"https://api.howtofix.id/v1").replace(/\/+$/,""),s=t?.fetchImpl??fetch,r=t?.timeoutMs??1e4,u=e.trim();if(!u)return{ok:!1,enabled:!1,checkedInToday:!1,quotaToday:0,message:"no token given"};try{let{status:f,body:h}=await ki(u,"GET",n,s,r);if(f===401||f===403)return{ok:!1,enabled:!1,checkedInToday:!1,quotaToday:0,message:"the gateway rejected that token for the check-in status"};if(f>=400||h.success!==!0)return{ok:!1,enabled:!1,checkedInToday:!1,quotaToday:0,message:typeof h.message=="string"?h.message:`the gateway answered ${f}`};let b=h.data??{};return{ok:!0,enabled:b.enabled===!0,checkedInToday:b.checked_in_today===!0,quotaToday:Number(b.quota_today??0)||0,message:""}}catch(f){return{ok:!1,enabled:!1,checkedInToday:!1,quotaToday:0,message:f instanceof Error&&f.name==="AbortError"?"the gateway did not answer the check-in in time":"could not reach the gateway"}}}async function $i(e,t){let n=(t?.baseUrl??"https://api.howtofix.id/v1").replace(/\/+$/,""),s=t?.fetchImpl??fetch,r=t?.timeoutMs??15e3,u=e.trim();if(!u)return{ok:!1,alreadyClaimed:!1,blocked:!1,quotaAwarded:0,message:"no token given"};try{let{status:f,body:h}=await ki(u,"POST",n,s,r);if(h.success===!0){let j=h.data??{};return{ok:!0,alreadyClaimed:!1,blocked:!1,quotaAwarded:Number(j.quota_awarded??0)||0,message:""}}let b=typeof h.message=="string"?h.message:`the gateway answered ${f}`,x=/device already claimed|account blocked|appeal/i.test(b);return{ok:!1,alreadyClaimed:!x&&/签到|check-?in|already|今日/.test(b)&&!/not enabled/i.test(b),blocked:x,quotaAwarded:0,message:b}}catch(f){return{ok:!1,alreadyClaimed:!1,blocked:!1,quotaAwarded:0,message:f instanceof Error&&f.name==="AbortError"?"the gateway did not answer the check-in in time":"could not reach the gateway"}}}function vi(){return{}}function xi(e,t,n,s=Date.now()){let r={...e};return t==="run"?(n===void 0||n===""?delete r.run:r.run={label:n,since:e.run?.since??s},r):(n===void 0||n===""?delete r[t]:r[t]=n,r)}function Si(e,t){let n={...e};return t===void 0?delete n.retry:n.retry=t,n}function bl(e){let t=Math.max(0,Math.round(e/1e3)),n=Math.floor(t/60);return n>0?`${n}m ${String(t%60).padStart(2,"0")}s`:`${t}s`}function Kn(e,t=72){let n=e.split(`
22
+ `).map(s=>s.trim()).find(s=>s!=="")??"";return n.length>t?`${n.slice(0,t-1)}\u2026`:n}function yl(e,t){let n=Math.max(0,Math.ceil((e.until-t)/1e3)),s=n>0?`in ${n}s`:"now",r=`retry ${e.attempt}/${e.maxAttempts} ${s}`,u=Kn(e.error);return u===""?r:`${r} \xB7 ${u}`}function Ci(e,t,n=Date.now()){return e.prompt?`? ${e.prompt}`:e.retry?`* ${yl(e.retry,n)}`:e.note?`* ${e.note}`:e.run?`${t} ${e.run.label} \xB7 ${bl(n-e.run.since)}`:e.tally?e.tally:""}import{spawn as kl}from"node:child_process";function $l(e){switch(e){case"darwin":return{command:"open",args:[]};case"win32":return{command:"cmd",args:["/c","start",""]};case"linux":return{command:"xdg-open",args:[]};default:return}}async function Ve(e,t=process.platform){let n=$l(t);return n?new Promise(s=>{try{let r=kl(n.command,[...n.args,e],{detached:!0,stdio:"ignore"});r.once("error",()=>s(!1)),r.once("spawn",()=>{r.unref(),s(!0)})}catch{s(!1)}}):!1}function Ai(e){return e instanceof Error?e.message:String(e)}var ze=class{active;apply;report;pending;running;constructor(t){this.active=new Set(t.initial??[]),this.apply=t.apply,this.report=t.report??(n=>console.error(n))}activeServers(){return[...this.active]}reconcile(t){return this.pending=new Set(t),this.running?this.running:(this.running=this.drain().finally(()=>{this.running=void 0}),this.running)}async drain(){let t={added:[],removed:[],unchanged:[],problems:[]};for(;this.pending!==void 0;){let s=this.pending;this.pending=void 0;let r=await this.applyOnce(s);t.added.push(...r.added),t.removed.push(...r.removed),t.unchanged.push(...r.unchanged),t.problems.push(...r.problems)}let n=this.active;return t.added=t.added.filter(s=>n.has(s)),t.removed=[...new Set(t.removed.filter(s=>!n.has(s)))],t.added=[...new Set(t.added)],t.unchanged=[...new Set(t.unchanged.filter(s=>n.has(s)))],t}async applyOnce(t){let n=[...t].filter(u=>!this.active.has(u)),s=[...this.active].filter(u=>!t.has(u)),r=[...t].filter(u=>this.active.has(u));if(n.length===0&&s.length===0)return{added:[],removed:[],unchanged:r,problems:[]};try{await this.apply(n,s)}catch(u){let f=`mcp reconciliation failed: ${Ai(u)}`;return this.report(f),{added:[],removed:[],unchanged:[],problems:[f]}}for(let u of n)this.active.add(u);for(let u of s)this.active.delete(u);return{added:n,removed:s,unchanged:r,problems:[]}}async dispose(){this.running&&await this.running.catch(()=>{});let t=[...this.active];if(t.length===0)return{added:[],removed:[],unchanged:[],problems:[]};try{return await this.apply([],t),this.active.clear(),{added:[],removed:t,unchanged:[],problems:[]}}catch(n){let s=`mcp teardown failed: ${Ai(n)}`;return this.report(s),{added:[],removed:[],unchanged:[],problems:[s]}}}};import{mkdirSync as vl}from"node:fs";import{join as xl}from"node:path";import{matchesKey as Mt}from"@netrodev/hxf-tui";var Hn=["all","running","failed","done"];function Mi(){return{selectedPhase:0,filter:"all",paused:!1,expanded:!1,follow:!0}}function Ri(e){if(Mt(e,"up"))return"up";if(Mt(e,"down"))return"down";if(Mt(e,"enter"))return"enter";if(Mt(e,"escape"))return"escape";if(e==="f")return"filter";if(e==="p")return"pause";if(e==="x")return"stop";if(e==="s")return"save"}function Ti(e,t,n){if(t.length===0)return e;let s=Math.max(0,Math.min(t.length-1,e.selectedPhase+n));return{...e,selectedPhase:s,follow:!1}}function Sl(e){let t=Hn.indexOf(e);return Hn[(t+1)%Hn.length]}function Ei(e,t,n){switch(t){case"up":return Ti(e,n,-1);case"down":return Ti(e,n,1);case"enter":return{...e,expanded:!e.expanded};case"filter":return{...e,filter:Sl(e.filter)};case"pause":return{...e,paused:!e.paused};default:return e}}function Pi(e,t){switch(t){case"running":return e.filter(n=>n.status==="running");case"failed":return e.filter(n=>n.status==="failed");case"done":return e.filter(n=>n.status!=="running");default:return[...e]}}function Ii(e){return e==="all"?"":` \xB7 ${e}`}var _i="ctrl+f";function Oi(e,t,n=!0){if(!n)return"Ctrl+F panel keys \xB7 Esc unpin";let s=["\u2191/\u2193 phase",e.expanded?"Enter collapse":"Enter drill in"];return s.push(e.expanded?"Esc back out":"Esc unpin"),s.push(`f filter${e.filter==="all"?"":` (${e.filter})`}`),t?(s.push(e.paused?"p resume":"p pause"),s.push("x stop")):e.paused&&s.push("p resume"),s.push("s save script"),e.paused&&s.unshift("paused"),s.join(" \xB7 ")}function Cl(e){let t=e.trim();if(!(!t||t.length>64)&&!(t==="."||t==="..")&&/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(t)&&!t.includes(".."))return t}function Li(e,t){if(!e)return{ok:!1,reason:"this run was started from a file, so it is already saved where you pointed the tool"};let n=Cl(e.name);if(!n)return{ok:!1,reason:`"${e.name}" is not a usable filename, so the script was not written`};let s=xl(t,`${n}.js`);try{vl(t,{recursive:!0}),re(s,e.code)}catch(r){return{ok:!1,reason:r instanceof Error?r.message:String(r)}}return{ok:!0,path:s}}function Ni(e){let t=()=>{};return{select:(n,s)=>e.select(n,s),confirm:(n,s)=>e.confirm(n,s),input:n=>e.input(n),notify:(n,s)=>e.notify(n,s),onTerminalInput:()=>t,setStatus:(n,s)=>e.setStatus(n,s),setWorkingMessage:t,setWorkingVisible:t,setWorkingIndicator:t,setHiddenThinkingLabel:t,setWidget:(n,s,r)=>{s!==void 0&&!Array.isArray(s)||e.setWidget?.(n,s,r?.placement)},setFooter:t,setHeader:t,setTitle:t,custom:async()=>{throw new Error("this screen has no custom component host; use the text commands instead")},pasteToEditor:t,setEditorText:t,getEditorText:()=>"",editor:async()=>{},addAutocompleteProvider:t,setEditorComponent:t,getEditorComponent:()=>{},theme:void 0,getAllThemes:()=>[],getTheme:()=>{},setTheme:()=>({success:!1,error:"themes are not available in the workbench"}),getToolsExpanded:()=>!1,setToolsExpanded:t}}var Wi={borderColor:()=>"",selectList:{selectedPrefix:e=>O(e,T.accent),selectedText:e=>O(e,T.text,{bold:!0}),description:e=>O(e,T.mute),scrollInfo:e=>O(e,T.dim),noMatch:e=>O(e,T.mute)}},Bi=Symbol.for("@netrodev/hxf-tui/layout-node");function Gl(e){if(typeof e!="object"||e===null)return;let t=e[Bi];return typeof t=="function"?t.call(e):void 0}var Vn=Tl(Al);async function Ui(e){try{let{stdout:t}=await Vn("git",["-C",e,"rev-parse","--abbrev-ref","HEAD"],{encoding:"utf8"}),n=t.trim();if(!n||n==="HEAD")return"";let{stdout:s}=await Vn("git",["-C",e,"status","--porcelain"],{encoding:"utf8"});return`git:(${n}${s.trim()?"*":""})`}catch{return null}}var zn=class{folder;model;git;percent=0;meter=new bt(0);activity=vi();live=!1;activitySince=Date.now();thinking="medium";ceiling=void 0;usage="";cost=0;skipPermissions=!1;constructor(t,n){this.folder=El(t),this.model=n.split("/").at(-1)||"no-model",this.git=""}invalidate(){}settling(){return this.meter.moving}atCeiling(){return this.ceiling!==void 0&&this.thinking===this.ceiling}levelChangedAt=0;setThinking(t){t!==this.thinking&&(this.thinking=t,this.levelChangedAt=Date.now())}levelFlashAmount(){return this.levelChangedAt===0?0:Ct(Date.now()-this.levelChangedAt)}flashing(){return this.levelFlashAmount()>0}levelText(t){if(this.atCeiling())return Lr(this.thinking,Jr,t);let n=this.levelChangedAt===0?Number.POSITIVE_INFINITY:t-this.levelChangedAt;return Ct(n)<=0?si(this.thinking,this.thinking):Or(this.thinking,{rest:St(this.thinking),lit:Zr(this.thinking)},1-Ct(n))}meterValue(){return this.meter.value!==this.percent&&this.meter.set(this.percent),this.meter.step()}beginRun(){this.live=!0,this.activitySince=Date.now()}waitedMs(){return Date.now()-this.activitySince}abandonAnimations(){this.meter.snap(this.percent)}render(t){let n=Date.now(),s=this.percent===0&&this.meter.value===0?0:this.meterValue(),r=this.levelText(n),u=ii(this.model,r,this.folder,this.git),f=[Re(`${ai(u,this.live?Ge():"",this.live?this.waitedMs():void 0)} ${li(s,this.usage,ci(this.cost))}`,t)];this.skipPermissions&&f.push(Re(O("Permissions OFF \u2014 critical commands and the repeat guard are not enforced",T.bad),t));let h=Bs();h&&f.push(Re(O(h,T.warn),t));let b=js(ht());b&&f.push(Re(O(b,T.accent),t));let x=Ci(this.activity,Ge(),n),M=this.live?Nr(x,{base:Sn(this.waitedMs(),T.mute,T.warn,T.bad),bright:T.text,charMs:45},n):O(x,Sn(this.waitedMs(),T.mute,T.warn,T.bad));return f.push(Re(M,t)),f}},Yn=class{constructor(t){this.draw=t}draw;render(t){return this.draw(t)}invalidate(){}},Xn=class{constructor(t,n){this.editor=t;this.hud=n}editor;hud;focused=!1;invalidate(){this.editor.invalidate()}render(t){let n=Math.max(10,t-4),s=this.editor.render(n).filter(h=>Pt(h)>0),r=s.length>0?s:[""],u="\u2500".repeat(Math.max(0,t-2)),f=r.map(h=>{let b=Math.max(0,n-Pt(h));return`\u2502 ${h}${" ".repeat(b)} \u2502`});return[`\u250C${u}\u2510`,...f,`\u2514${u}\u2518`,...this.hud.render(t)]}handleInput(t){this.editor.handleInput(t)}};function Bl(e,t,n,s=!1,r=[]){let u=Math.max(24,n),f=u-4,h=(L,X)=>{let pe=Pt(L)>f?Re(L,f,"\u2026"):L,Q=`${pe}${" ".repeat(Math.max(0,f-Pt(pe)))}`;return`\u2502 ${X?X(Q):Q} \u2502`},b="\u2500".repeat(u-2),x=[h(` ${t}`),...e.render(f).map(L=>h(L))];x.push(h(" type to filter \xB7 \u2191\u2193 move \xB7 enter select \xB7 esc cancel"));let M=r.flatMap(L=>L===""?[""]:Ul(L,f)),j=M.length>0?[h(""),...M.map(L=>h(L,X=>O(X,T.mute)))]:[];if(!s)return["",`\u250C${b}\u2510`,...x,...j,`\u2514${b}\u2518`];let D=_r(T.line,T.warn,Date.now(),1400),W=O("\u2502",D),I=(L,X)=>O(`${L}${b}${X}`,D),U=[...x,...j].map(L=>`${W}${L.slice(1,-1)}${W}`);return["",I("\u250C","\u2510"),...U,I("\u2514","\u2518")]}function ql(e,t){let n=t.split(`
23
+ `).filter(Boolean),s=n.filter(f=>f.startsWith("Reason:")),r=n.filter(f=>!f.startsWith("Reason:")&&!f.startsWith("Allow tool:"));return[...e.endsWith(" wants to run")?[]:[e],...s,...r.length>0?["",...r]:[]]}function Me(e){let t=e.getContextUsage();if(t?.percent!==null&&t?.percent!==void 0)return Math.min(100,Math.round(t.percent));let n=e.model,r=[...e.state.messages].reverse().find(u=>u.role==="assistant")?.usage?.totalTokens;return!n||typeof r!="number"||!Number.isFinite(r)||n.contextWindow<=0?0:Math.min(100,Math.round(r/n.contextWindow*100))}function qn(e){let n=[["init","write project notes to AGENTS.md"],["model","choose a model"],["providers","list providers"],["thinking","set thinking level"],["approval","set what needs approval"],["settings","turn permission checks on or off"],["connect","sign in with email:password (or a base64 credential), or paste a key"],["sync","re-sync models from howtofix.id"],["usage","show the account's quota and what it has spent"],["update","install the newest release"],["login","save a provider API key"],["logout","remove a provider"],["new","start a new session"],["resume","resume another session"],["compact","compact the session"],["name","name this session"],["stats","session tokens and cost, cache hit rate and misses"],["rtk","compress long tool output before the model reads it"],["diff","show the working tree diff"],["commit","stage everything and commit"],["undo","undo the last commit"],["rewind","go back to an earlier message (Esc Esc)"],["review","ask the agent to review the diff"],["tools","list active tools"],["skills","list loaded skills"],["preset","browse, install and remove preset skill bundles"],["roblox","show RoToolbox activation, MCP and manager status"],["proxy","route requests through a proxy, or show the current one"],["export","write the transcript to a markdown file"],["copy","copy the last answer to the clipboard"],["agents","show spawned agents"],["goal","set or view this session's goal"],["plan","toggle plan mode (design before editing)"],["workflow","show or clear the pinned workflow panel"],["dcp","dynamic context pruning: on | off | status | blocks | stats | context | decompress <bN> | sweep"],["context","what the next request carries, and what pruning saved"],["decompress","reopen one compressed block, e.g. /decompress b2"],["sweep","close compressed blocks no ref resolves"],["session","show the current model"],["help","list commands"],["quit","quit"],["exit","quit (alias)"]].map(([s,r])=>({name:s,description:r}));for(let s of e.promptTemplates)n.push({name:s.name,description:s.description});for(let s of e.extensionRunner.getRegisteredCommands())n.push({name:s.invocationName,description:s.description});return n}function Jn(e,t){if(e!=="workflow")return;let n=Be(t);if(!(typeof n.name!="string"||!Array.isArray(n.steps)))return n}function Vl(e,t){let n=Jn(e,t);return n?Et(n):void 0}function Et(e,t,n=!1){return s=>lr(e,[],s,t?.selectedPhase,t?zl(e,t,n):void 0)}function zl(e,t,n){return{filter:s=>Pi(s,t.filter),footerText:Oi(t,e.endedAt===void 0,n),filterLabel:Ii(t.filter),drill:t.expanded}}function Yl(){let e=new Ki(Gi,{"tui.altScreen.pageUp":[],"tui.altScreen.pageDown":[],"tui.altScreen.halfPageUp":[],"tui.altScreen.halfPageDown":[],"tui.altScreen.top":[],"tui.altScreen.bottom":[]});Hi(e)}async function lu(e){let t=new Nl,n,s=new Dl(t,!0,void 0,{mouse:!0,onRightClickPaste:()=>n?.()}),r=new vt,u=new zn(e.cwd,e.modelLabel);u.skipPermissions=mn();let f=o=>{let i=Date.now();(async()=>{try{let a=Ye(),l=k.getSessionStats().sessionId;if(!ro){ro=!0;try{await hr(a,{keep:l})}catch{}}let d=await fr(a,l,o);d&&i>=jt&&(so=d,jt=i)}catch{}})()},h=(o=!1)=>{!o&&!u.live||Ui(e.cwd).then(i=>{i!==null&&(u.git=i,$())})},b=new Ll(s,Wi,{paddingX:1}),x=new Map,M=(o,i)=>{i===void 0?x.delete(o):typeof i=="function"?x.set(o,i):x.set(o,()=>i)},j=()=>Math.max(20,t.columns),D,W=0,I=Mi(),U,L=null,X=!1,pe,Q=!1,qi,It=()=>{!U||!X||M("workflow",o=>Et(U,I,Q)(o))},Zn=()=>{U&&(pe=U.name),X=!1,Q=!1,M("workflow",void 0)};cr({onStop:o=>{L=o},isPaused:()=>I.paused});let Qn=o=>{if(pe===o.name)return;D=o;let i=o.endedAt??Date.now();W=Math.max(W,i+rr),U=o,X=!0,M("workflow",a=>Et(o,I,Q)(a))},eo=new Xn(b,u),k=e.session,to=e.setCompressToolOutput,no=!1,_t=()=>{let o=k.getSessionStats().cost;return u.cost=o,o},Ot=ss(e.maxBudgetUsd),oo=!1,Vi=()=>{let o=Ot.check(_t());o===void 0||oo||(oo=!0,k.isStreaming&&k.abort(),m("budget",rs(o.spent,o.limit)))},he=()=>{u.ceiling=Qr(k.model)},ge=$s(P),Lt,zi=async()=>!ge||!ks(ge)||ys(ge)?!1:(Lt??=(async()=>{try{let o=await xs(P,ge);return o.renewed?(ge=o.credential,o.message&&m("connect",o.message),await k.modelRuntime.setRuntimeApiKey("howtofix",o.credential.accessToken),!0):(o.message&&m("connect",o.message),!1)}catch{return!1}finally{Lt=void 0}})(),await Lt),Nt,Ye=()=>Nt??=dr(e.cwd),so,Ft="",jt=0,ro=!1,we,Yi=()=>{let o=new Set(["session_info","usage","label","context_edit","custom","model_change","thinking_level_change"]),i=[],a=l=>{for(let d of l)o.has(d.entry.type)||i.push(d.entry.id),a(d.children)};return a(k.sessionManager.getTree()),i},io=!1,Xi=()=>{if(io)return;io=!0;let o=Di().getResolvedBindings();Hi(new Ki(Gi,{...o,"app.tree.foldOrUp":["alt+left","ctrl+left"],"app.tree.unfoldOrDown":["alt+right","ctrl+right"],"app.tree.editLabel":["shift+l"],"app.tree.toggleLabelTimestamp":["shift+t"],"app.message.copy":["ctrl+x"],"app.tree.filter.default":["alt+0"],"app.tree.filter.noTools":["alt+1"],"app.tree.filter.userOnly":["alt+2"],"app.tree.filter.labeledOnly":["alt+3"],"app.tree.filter.all":["alt+4"],"app.tree.filter.cycleForward":["alt+f"],"app.tree.filter.cycleBackward":["alt+shift+f"]}))},ao=!1,Ji=()=>{ao||(ao=!0,Hl())},lo=()=>{let o=k.sessionManager.getTree();if(o.length===0){m("rewind","nothing to rewind to yet");return}Ye().disabled&&m("rewind","conversation rewind only; this directory is not a git repository"),Ji(),Xi();let i=Math.max(8,Math.floor(t.rows*.6)),a=new Kl(o,k.sessionManager.getLeafId(),i*2,l=>{Dt(),Zi(l)},()=>Dt());if(!a.getTreeList().getSelectedNode()){m("rewind","nothing to rewind to yet");return}we=a,we.focused=!0,M("rewind",l=>we?.render(l)??[]),$()},Dt=()=>{we=void 0,M("rewind",void 0),$()},Zi=async o=>{let i=Ye(),l=k.getUserMessagesForForking().findIndex(c=>c.entryId===o),d=l>=0?ur(i,k.getSessionStats().sessionId)[l]:void 0,y=d?(await pr(i,d)).length:0;if(y===0){await co(o,void 0,"conversation");return}_(`Rewind to this point? ${y} file(s) differ`,[{value:"both",label:"conversation and code",description:`drop the messages after this point and restore ${y} file(s)`},{value:"conversation",label:"conversation only",description:"drop the messages after this point, leave the files alone"},{value:"code",label:"code only",description:`restore ${y} file(s), keep the conversation`}],c=>{co(o,d,c)})},co=async(o,i,a)=>{let l=[];if((a==="both"||a==="conversation")&&!k.isStreaming)try{let d=await k.navigateTree(o);if(d.cancelled){m("rewind","conversation rewind cancelled");return}l.push("conversation rewound"),r.items=xt(k.state.messages),d.editorText&&(b.setText(d.editorText),l.push("prompt restored to the editor"))}catch(d){H(`conversation rewind failed: ${d instanceof Error?d.message:String(d)}`);return}if((a==="both"||a==="code")&&i){let d=await mr(Ye(),i);if(!d.ok){H(`code rewind failed: ${d.output}`);return}l.push(d.output),d.removed.length>0&&l.push(`removed ${d.removed.length} file(s)`),h()}m("rewind",l.join(`
24
+ `)||"nothing to do"),$()};h(!0),f("session start"),e.note&&r.items.push({id:"note",kind:"note",title:"note",body:e.note}),r.items.push(...xt(k.state.messages)),u.percent=Me(k),_t(),u.abandonAnimations(),u.setThinking(k.thinkingLevel),he(),b.setAutocompleteProvider(new ji(qn(k),e.cwd)),ui(k).then(o=>{o&&(u.usage=o,s.requestRender())});let uo=async o=>{let{checkForUpdate:i,checkFailedNote:a,installUpdate:l}=await import("./chunk-7CHDNTH6.js"),d=await i(o.current);if(!d.available){let c=a(d);c?m("update",c):o.install&&m("update",d.message);return}if(!o.install){m("update",`${d.message}. run /update to install it.`);return}C("note",`installing HowToFix ${d.latest}\u2026`);let y=await l({version:d.latest});C("note",void 0),m("update",y.message),$()};e.update&&uo(e.update);let se=null,fo="",mo=!1,po=[],Ee,Wt=()=>{},$=()=>{Wt(),s.requestRender()},C=(o,i)=>{u.activity=xi(u.activity,o,i)},Ut=o=>{u.activity=Si(u.activity,o)},Xe=new Map,Kt=new Set,Qi=()=>[...Xe].map(([o,i])=>`${Kt.has(o)?"!":"\u2713"} ${o} \xD7${i}`).join(" | "),ea=()=>{let o=Qi();C("tally",o||void 0)},_=(o,i,a,l,d=!1,y=[])=>{let c=new jl(i,8,Wi.selectList);c.onSelect=p=>{se=null,Ee=void 0,a(p.value)},c.onCancel=()=>{se=null,Ee=void 0,l?.(),$()},Ee=()=>c.onCancel?.(),fo=o,mo=d,po=y,se=c,wo+=1,$()},m=(o,i)=>{r.items=qr(r.items,{id:`cmd-${Date.now()}-${r.items.length}`,kind:"note",title:o,body:i}),C("tally",void 0),$()};Zs(o=>{o.background&&m("agent",`${Vs(o)}
25
+ read it with /agents ${o.id}`)});let Ht=!1,ta=o=>{Ht||(Ht=!0,(async()=>{try{let i=(await k.modelRuntime.getAvailable()).filter(w=>ie(w.provider)),a=new Set(i.map(w=>w.provider)),l=ye.find(w=>a.has(w)),d=l?(await k.modelRuntime.getAuth(l))?.auth?.apiKey:void 0;if(!d)return;let y=wt(i.map(w=>w.id)),{live:c,probed:p}=await hs(y,d,{exclude:o,limit:4});if(c.length===0)return;let g=se===null;m("gateway",`${c.length} of ${p.length} probed models answer right now (${c.join(", ")}); ${g?"the model picker is open below":"switch with /model"}.`),g&&Ne("/model")}catch{}finally{Ht=!1}})())},H=o=>{r.items.push({id:`err-${Date.now()}-${r.items.length}`,kind:"error",title:"failed",body:o});let i=kr(o);i!==void 0&&m("gateway",i);let a=yr(o);a!==void 0&&ta(a),C("tally",void 0),$()},Pe=o=>{k.setThinkingLevel(o,{persist:!0}),u.setThinking(o),he(),C("note",`thinking ${o}`),$()};Rs((o,i)=>{let{promise:a,resolve:l}=Promise.withResolvers();return _(o,[{value:"allow",label:"allow"},{value:"deny",label:"deny"}],d=>l(d==="allow"),()=>l(!1),!0,ql(o,i)),a});let Gt=new Map,ho=o=>{let i=Ni({select:(a,l)=>{let{promise:d,resolve:y}=Promise.withResolvers();return _(a,l.map(c=>({value:c,label:c})),y,()=>y(void 0)),d},confirm:(a,l)=>{let{promise:d,resolve:y}=Promise.withResolvers();return _(`${a} \u2014 ${l}`,[{value:"yes",label:"yes"},{value:"no",label:"no"}],c=>y(c==="yes"),()=>y(!1)),d},input:a=>{let{promise:l,resolve:d}=Promise.withResolvers();return C("prompt",a),$(),ne=y=>{ne=void 0,C("prompt",void 0),d(y),$()},l},notify:(a,l)=>{l==="error"?H(a):m("mcp",a)},setStatus:(a,l)=>{l===void 0?Gt.delete(a):Gt.set(a,l),C("note",[...Gt.values()].join(" | ")||void 0),$()},setWidget:(a,l)=>{M(a,l),$()}});o.bindExtensions({uiContext:i,mode:"print",onError:a=>H(`${a.event}: ${a.error}`)}).catch(a=>H(a instanceof Error?a.message:String(a)))};ho(k);let ve=new Ol,na={invalidate:()=>r.invalidate(),render:o=>{let i=ve.render(Math.max(20,o)).length;return r.viewportHeight=Math.max(1,Math.max(8,t.rows)-i),r.render(o)},handleMouse:o=>{if(Mo(o))return tt(),{handled:!0};let i=o.type==="wheel"?o.wheelDelta??0:0;if(i!==0)return r.scrollOffset=Math.max(0,r.scrollOffset-i*3),$(),{handled:!0}}},oa=new Fl(na,{follow:"none",overscroll:"contain"}),Je=new Wl([{component:oa,grow:1,shrink:1},{component:ve,grow:0,shrink:0,basis:"auto"}]),go="",wo=0,sa=()=>`${se?`picker:${wo}`:"dock"}|${[...x.keys()].join(",")}`;Wt=()=>{let o=sa();if(o===go)return;go=o,ve.clear();for(let a of x.values())ve.addChild(new Yn(a));let i=se;if(i){let a=fo,l=mo,d=po;ve.addChild({render:y=>Bl(i,a,y,l,d),invalidate:()=>{}})}else ve.addChild(eo);Je.invalidate()},Wt();let bo={focused:!1,invalidate(){r.invalidate(),eo.invalidate(),se?.invalidate(),Je.invalidate()},[Bi]:()=>Gl(Je),render:o=>Je.render(o),handleMouse(o){if(Mo(o))return tt(),{handled:!0}},handleInput(o){b.handleInput(o)}};s.setLayoutRoot(bo),s.setFocus(bo);let z=0,ce="",Bt=!1,be=!1,qt,xe="",yo=0,Ie=!1,Ze=Date.now(),Qe=!1,et=new Map,ko=()=>{let o=new Set(k.getSteeringMessages().map(i=>i.trim()).filter(Boolean));for(let i of r.items)i.kind!=="user"||!i.pending||o.has(i.body.trim())||(i.pending=void 0)},$o=o=>{if(o.type==="agent_start"&&ko(),o.type==="agent_start"||o.type==="turn_start")o.type==="agent_start"&&Ts(),u.live||u.beginRun(),ce="",be=!1,Ie=!1,Ze=Date.now(),xe="";else if(o.type==="message_update"&&o.assistantMessageEvent.type==="thinking_delta"){be=!0,xe===""&&(yo=Date.now()),xe+=o.assistantMessageEvent.delta;let i=`think-${z}`,a=r.items.find(d=>d.id===i),l=xe.split(`
26
+ `).slice(-6).join(`
27
+ `);a?a.body=l:r.items.push({id:i,kind:"note",title:"thinking",body:l})}else if(o.type==="message_update"&&o.assistantMessageEvent.type==="thinking_end"){let i=`think-${z}`,a=r.items.find(l=>l.id===i);if(a){let l=Math.max(1,Math.round((Date.now()-yo)/1e3));a.title="thought",a.body=`${l}s \xB7 ${xe.length} chars of reasoning`}xe=""}else if(o.type==="message_update"&&o.assistantMessageEvent.type==="text_delta"){be=!0,ce+=o.assistantMessageEvent.delta;let i=De(ce),a=`live-${z}`,l=r.items.find(d=>d.id===a);l?l.body=i:r.items.push({id:a,kind:"assistant",title:"HowToFix",body:i})}else if(o.type==="tool_execution_start"){et.set(o.toolCallId,o.args),be=!1,Ie=!1,Ze=Date.now();let i=`tool-${o.toolCallId}`,a=$e(o.toolName,o.args),l=r.items.find(d=>d.id===i);if(l?(l.kind="tool",l.title=o.toolName,l.body=a,l.live=!0):r.items.push({id:i,kind:"tool",title:o.toolName,body:a,live:!0}),qt=o.toolName,o.toolName==="task"){let d=zs.filter(y=>y.status==="queued"||y.status==="running");C("note",d.map(y=>`${y.agent} ${y.status}`).join(" | ")||"agent running")}}else if(o.type==="tool_execution_update"){let i=Vl(o.toolName,o.partialResult);if(i){let a=`tool-${o.toolCallId}`,l=r.items.find(y=>y.id===a);l?l.panel=i:r.items.push({id:a,kind:"tool",title:o.toolName,body:$e(o.toolName,et.get(o.toolCallId)),panel:i,live:!0});let d=Jn(o.toolName,o.partialResult);d&&pe!==d.name&&Qn(d),$()}}else if(o.type==="tool_execution_end"){u.percent=Me(k);let i=r.items.find(g=>g.id===`tool-${o.toolCallId}`);i&&(i.live=!1,i.body=$e(o.toolName,et.get(o.toolCallId))),et.delete(o.toolCallId),qt=void 0,be=!0,Ie=!1,Xe.set(o.toolName,(Xe.get(o.toolName)??0)+1),o.isError&&Kt.add(o.toolName),ea();let a=Kr(o.toolName,o.result),l=Hr(o.toolName,o.result),d=Jn(o.toolName,o.result),y=d?Et(d):void 0;d&&pe!==d.name&&Qn(d);let c=r.items.find(g=>g.id===`tool-${o.toolCallId}`),p=$t(o.toolName,o.result,o.isError);c?(c.kind="result",c.call=c.body,c.body=p,c.live=!1,a.length>0&&(c.detail=a),l.length>0&&(c.full=l),y&&(c.panel=y)):r.items.push({id:`tool-${o.toolCallId}`,kind:"result",title:o.toolName,body:p,...a.length>0?{detail:a}:{},...l.length>0?{full:l}:{},...y?{panel:y}:{}}),(o.toolName==="bash"||o.toolName==="powershell"||o.toolName==="edit"||o.toolName==="write")&&h()}else if(o.type==="compaction_start"){be=!0;let i=o.reason==="manual"?"on request":"context is nearly full",a=r.items.find(y=>y.id===`compact-${z}`),l="compacting context",d=`${i} \xB7 summarizing the older turns`;a?(a.title=l,a.body=d):r.items.push({id:`compact-${z}`,kind:"note",title:l,body:d,live:!0}),C("note","compacting context")}else if(o.type==="compaction_end"){let i=r.items.find(y=>y.id===`compact-${z}`),a=o.result,l="compacted",d;if(o.aborted)d="cancelled";else if(o.errorMessage)d=`failed: ${o.errorMessage}`;else if(a){let y=Math.round(a.tokensBefore/1e3),c=a.estimatedTokensAfter!==void 0?Math.round(a.estimatedTokensAfter/1e3):void 0,p=a.estimatedTokensAfter!==void 0?a.tokensBefore-a.estimatedTokensAfter:void 0,g=p!==void 0&&p<2e3;d=c!==void 0?`${y}k \u2192 ${c}k tokens \xB7 older turns summarized${g?`
28
+ this freed almost nothing; the window may be too small for this work`:""}`:`${y}k tokens \xB7 older turns summarized`}else d="nothing to compact";i?(i.title=l,i.body=d,i.live=!1):r.items.push({id:`compact-${z}`,kind:"note",title:l,body:d}),u.percent=Me(k),C("note",void 0)}else if(o.type==="message_start"&&o.message.role==="user"){let i=Vr(o.message);i&&(r.items=zr(r.items,i,`u-${o.message.timestamp}`)),ko()}else if(o.type==="message_end"&&o.message.role==="assistant"){let i=r.items.find(l=>l.id===`live-${z}`);i&&(i.id=`done-${z}`);let a=o.message.errorMessage;a&&i?(i.title="failed",i.kind="error",i.body=ce.trim()?`${a}
29
+
30
+ ${ce.trim()}`:a):a&&r.items.push({id:`e-${o.message.timestamp}`,kind:"error",title:"failed",body:a}),z+=1,ce="",u.percent=Me(k)}else if(o.type==="agent_settled"){u.live=!1;let i=[...k.getSteeringMessages()].map(a=>a.trim()).filter(Boolean);if(i.length>0){let a=b.getText().trim();b.setText(a?`${i.join(`
31
+ `)}
32
+ ${a}`:i.join(`
33
+ `));let l=new Set(i);for(let d of r.items)d.kind==="user"&&d.pending&&l.has(d.body.trim())&&(d.pending=void 0);m("queued",`${i.length} unread message${i.length===1?"":"s"} were never read and are back in the editor`)}for(let a of r.items)a.kind==="user"&&a.pending&&(a.pending=void 0);if(f(Ft),Ft="",C("run",void 0),Bt){let a=r.items.find(l=>l.id===`live-${z}`);a?(a.id=`stopped-${z}`,a.title="stopped",a.body=ce.trim()||"(no output)",a.live=!1):r.items.push({id:`stopped-${z}`,kind:"note",title:"stopped",body:"run cancelled"}),z+=1,ce="",m("stopped","run cancelled by Esc"),Bt=!1}u.percent=Me(k),C("note",void 0),Ut(void 0),Ui(e.cwd).then(a=>{a!==null&&(u.git=a,$())}),b.disableSubmit=!1}else o.type==="thinking_level_changed"?u.setThinking(o.level):o.type==="auto_retry_start"?(C("note",void 0),Ut({attempt:o.attempt,maxAttempts:o.maxAttempts,error:o.errorMessage,until:Date.now()+o.delayMs})):o.type==="auto_retry_end"&&(Ut(void 0),o.success?m("retry",`answered on attempt ${o.attempt} after a retry`):C("note",`retry ${o.attempt} gave up${o.finalError?` \xB7 ${Kn(o.finalError)}`:""}`));Vi(),$()},Vt=k.subscribe($o),vo=setInterval(()=>{let o=D!==void 0&&Date.now()<W;if((Qe||k.isStreaming||u.settling()||r.entering()||se||o||u.atCeiling()||u.flashing()||u.activity.retry!==void 0)&&$(),(Qe||k.isStreaming)&&!be&&!Ie&&Date.now()-Ze>Jl){Ie=!0;let i=qt,a=Math.round((Date.now()-Ze)/1e3);C("note",i?`${i} has been running for ${a}s \u2014 it may be blocked; esc cancels`:`no answer yet after ${a}s \u2014 the provider may be stalled; ctrl+c cancels`),$()}},Xl);vo.unref?.();let xo=async o=>{Ee?.(),Ee=void 0,Vt(),Nt&&gr(Nt,k.getSessionStats().sessionId),so=void 0,jt=0;let i=k.getSessionStats().sessionId;wn(i),bn(i),await ot.dispose(),k.dispose(),k=o.session,to=o.setCompressToolOutput,ot=new ze({initial:Object.keys(Le().mcpServers),apply:async(a,l)=>{if(await Se(),a.length>0||l.length>0){let d=[];a.length>0&&d.push(`connected ${a.join(", ")}`),l.length>0&&d.push(`stopped ${l.join(", ")}`),m(a.length>0?"mcp connected":"mcp stopped",d.join("; "))}},report:a=>H(a)}),z=0,ce="",r.items=[],r.scrollOffset=0,o.note&&r.items.push({id:"note",kind:"note",title:"note",body:o.note}),r.items.push(...xt(k.state.messages)),u.model=o.modelLabel.split("/").at(-1)||"no-model",u.setThinking(k.thinkingLevel),he(),u.percent=Me(k),_t(),u.abandonAnimations(),C("tally",void 0),C("run",void 0),b.setAutocompleteProvider(new ji(qn(k),e.cwd)),b.disableSubmit=!1,ho(k),Vt=k.subscribe($o),$()},_e=async()=>{if(no)return;no=!0,clearInterval(vo),Vt();try{let i=Ps(Es);if(i.config.hooks.SessionEnd){let{outcome:a}=await Is(i.config,"SessionEnd",{hook_event_name:"SessionEnd",cwd:process.cwd(),reason:"quit"},{cwd:process.cwd()});a.error&&m("hooks",`SessionEnd hook: ${a.error}`)}}catch{}await ot.dispose();let o=k.getSessionStats().sessionId;Ot.close(k.getSessionStats().cost),wn(o),bn(o),k.dispose(),s.stop(),process.stdout.write("\x1B[0m"),process.exit(0)},So=0,Co=async(o=!1)=>{let i=Date.now();if(!o&&i-So<600*1e3)return;So=i;let a=d=>{if(process.env.HOWTOFIX_CHECKIN_DEBUG==="1")try{Ml(`${P}/checkin-debug.log`,`${new Date().toISOString()} ${d}
34
+ `)}catch{}},l=async()=>{try{let d=new Set((await k.modelRuntime.getAvailable()).map(A=>A.provider).filter(A=>ie(A))),y=ye.find(A=>d.has(A));if(a(`providers=${[...d].join(",")||"(none)"} target=${y??"(none)"}`),!y)return!1;let c=(await k.modelRuntime.getAuth(y))?.auth?.apiKey,p=c?.trim().match(/^\$\{?([A-Za-z_][A-Za-z0-9_]*)\}?$|^\{env:([A-Za-z_][A-Za-z0-9_]*)\}$/),g=A=>A?(process.env[A]??"").trim():"",w=p?g(p[1]??p[2])||void 0:c?.trim()||void 0;if(!w)for(let A of["HOWTOFIX_API_KEY","HOWTOFIX_VIP_API_KEY","HOWTOFIX_FREE_API_KEY"]){let R=g(A);if(R){w=R,a(`key dari fallback ${A}`);break}}if(a(`key=${w?`ada(${w.length})`:"(kosong)"}${p?" dari env":""}`),!w)return!1;let S=await Un(w);if(a(`status ok=${S.ok} enabled=${S.enabled} claimed=${S.checkedInToday} msg=${S.message}`),!S.ok||!S.enabled||S.checkedInToday)return!0;let v=await $i(w);return a(`claim ok=${v.ok} awarded=${v.quotaAwarded} msg=${v.message}`),v.ok?(m("check-in",`daily check-in claimed: +${Wn(v.quotaAwarded)} credited to your howtofix.id account`),$()):v.blocked&&m("check-in",v.message),!0}catch(d){return a(`error ${d.message}`),!1}};await l()||(await new Promise(d=>setTimeout(d,4e3)),await l())},Ao=async o=>{let i=Ot.check(k.getSessionStats().cost);if(i!==void 0){H(`budget reached: $${i.spent.toFixed(4)} of $${i.limit.toFixed(2)} \u2014 raise it with --max-budget-usd, or start without the flag`);return}let a=k.isStreaming,l=`you-${Date.now()}`;r.items.push({id:l,kind:"user",title:"you",body:o,pending:a?!0:void 0}),a||(C("tally",void 0),Xe.clear(),Kt.clear(),C("run","thinking"),u.beginRun()),$(),b.disableSubmit=!1;let d=As(o,e.cwd);Ft=o,await zi(),Qe=!0;let y=a?k.prompt(d,{streamingBehavior:"steer"}):k.prompt(d);Qe=!1,y.then(()=>Co()).catch(c=>H(c instanceof Error?c.message:String(c)))},zt=o=>{let i=o.trim();if(i){if(ne){let a=ne;ne=void 0,b.setText(""),a(i);return}if(b.setText(""),b.addToHistory(i),i.startsWith("!")){let a=i.slice(1).trim();if(!a)return;r.items.push({id:`sh-${Date.now()}`,kind:"tool",title:"$",body:a}),C("run","shell"),$(),k.executeBash(a,l=>{C("run",`shell \xB7 ${l.length} bytes`),$()}).then(l=>{let d=l.output.trim();r.items.push({id:`sh-out-${Date.now()}`,kind:l.exitCode===0?"result":"error",title:`exit ${l.exitCode??"?"}`,body:d||"(no output)"}),C("tally",void 0),$()}).catch(l=>H(l instanceof Error?l.message:String(l)));return}if(i.startsWith("/")){Ne(i);return}Ao(i)}};b.onSubmit=zt;let Yt=0,To=0,tt=()=>{Cr().then(o=>{o.ok?b.insertTextAtCursor(o.text):m("paste",o.reason),$()}).catch(o=>{m("paste",`could not read the clipboard: ${o instanceof Error?o.message:String(o)}`),$()})};n=tt;let Mo=o=>pn(ke(P).rightClickPaste)&&o.type==="press"&&o.button==="right";s.addInputListener(o=>{if(we){if(V(o,"escape"))return Dt(),{consume:!0};let a=Di(),l=a.matches(o,"tui.select.up"),d=a.matches(o,"tui.select.down");if(l||d){let c=we.getTreeList().getSelectedNode()?.entry.id,p=Yi(),g=c===void 0?-1:p.indexOf(c);if(l?g===0:g===p.length-1)return $(),{consume:!0}}return we.handleInput(o),$(),{consume:!0}}if(X&&U&&V(o,"escape"))return Q?(Q=!1,m("workflow","panel keys off; the editor has the keyboard")):I.expanded?(I.expanded=!1,m("workflow","collapsed the drill-in")):(Zn(),m("workflow","panel unpinned; the run is still in the transcript")),It(),$(),{consume:!0};if(se)return se.handleInput(o),$(),{consume:!0};if(V(o,"escape")){if(k.isStreaming){Bt=!0;let l=[...k.getSteeringMessages()].map(d=>d.trim()).filter(Boolean);if(l.length>0){let d=b.getText().trim();b.setText(d?`${l.join(`
35
+ `)}
36
+ ${d}`:l.join(`
37
+ `));let y=new Set(l);for(let c of r.items)c.kind==="user"&&c.pending&&y.has(c.body.trim())&&(c.pending=void 0);m("queued",`${l.length} unread message${l.length===1?"":"s"} returned to the editor`)}return k.abort(),C("note","stopping"),$(),{consume:!0}}let a=Date.now();if(b.getText().length===0&&a-Yt<600)return Yt=0,lo(),{consume:!0};Yt=a;return}if(V(o,"ctrl+c")||$r(o)){if(k.isStreaming)k.abort(),C("note","stopping"),$();else if(b.getText().length>0)b.setText(""),C("note","draft cleared; ctrl+c again quits"),$();else{let a=Date.now();a-To<2e3?_e():(To=a,C("note","press ctrl+c again to quit"),$())}return{consume:!0}}if(V(o,"ctrl+d")&&b.getText().length===0)return _e(),{consume:!0};let i=Math.max(1,r.viewportHeight-1);if(V(o,"pageUp"))return r.scrollOffset+=i,$(),{consume:!0};if(V(o,"pageDown"))return r.scrollOffset=Math.max(0,r.scrollOffset-i),$(),{consume:!0};if(V(o,"home"))return r.scrollOffset=Number.MAX_SAFE_INTEGER,$(),{consume:!0};if(V(o,"end"))return r.scrollOffset=0,$(),{consume:!0};if(V(o,"ctrl+v"))return tt(),{consume:!0};if(V(o,"ctrl+l"))return r.scrollOffset=0,s.scrollToBottom(),$(),{consume:!0};if(V(o,"ctrl+e")){let a=[...r.items].reverse().find(l=>(l.full?.length??0)>0);return a?(a.expanded=a.expanded!==!0,$(),{consume:!0}):(m("expand","nothing to expand in this transcript yet"),{consume:!0})}if(V(o,"ctrl+o")&&!k.isStreaming)return r.items=[{id:"cleared",kind:"note",title:"bench",body:"screen cleared. session history is still stored."}],$(),{consume:!0};if(V(o,"ctrl+t"))return Pe(ei(u.thinking)),{consume:!0};if(V(o,"ctrl+shift+t"))return Pe(ti(u.thinking)),{consume:!0};if(V(o,_i)&&X&&U)return Q=!Q,m("workflow",Q?"panel keys active; Esc gives the keyboard back":"panel keys off; the editor has the keyboard"),It(),$(),{consume:!0};if(Q&&X&&U){let a=Ri(o);if(a){let l=kn(U,Date.now());if(a==="stop")return L?(L(),L=null,m("workflow","stopping the run; in-flight agents resolve as null")):m("workflow","the run has already finished"),{consume:!0};if(a==="save"){let d=Li(qi,os);return m("workflow",d.ok?`saved ${d.path}`:d.reason),$(),{consume:!0}}return Object.assign(I,Ei(I,a,l)),It(),$(),{consume:!0}}}});let Xt=o=>{let i=a=>{C("prompt",`API key for ${a}. Paste it, then press enter.`),$();let l=ne;ne=d=>{ne=l;let y=d.trim();if(!y){C("prompt",void 0),$();return}k.modelRuntime.setRuntimeApiKey(a,y).then(()=>k.modelRuntime.login(a,"api_key",{prompt:async()=>y,notify:()=>{}}).then(()=>m("login",`saved API key for ${a}`),c=>m("login",`key set for this session, but it could not be saved (${c instanceof Error?c.message:String(c)}); run /login again after restarting`)),c=>m("login",c instanceof Error?c.message:String(c)))}};if(o){i(o);return}k.modelRuntime.getAvailable().then(a=>{let l=[...new Set(a.map(d=>d.provider))].sort();if(l.length===0){m("login","no providers are configured; pass one explicitly, e.g. /login nrimo");return}_("Login",l.map(d=>({value:d,label:d})),i)},a=>m("login",a instanceof Error?a.message:String(a)))},Ro=async(o,i)=>{let a=le(P,"models.json"),l,d=!1;try{l=JSON.parse(Gn(a,"utf8"))}catch(K){if(!(K instanceof Error&&"code"in K&&K.code==="ENOENT"))return`could not read ${a}; the models were not added`;l={providers:{}},d=!0}(!l.providers||typeof l.providers!="object")&&(l.providers={});let y=l.providers[o];y||(y=ls(),l.providers[o]=y,d=!0);let c=Array.isArray(y.models)?y.models:[],p=ms(c,i),g=await cs(P).catch(()=>({index:new Map})),w=fs(us(c,i,g.index));y.models=w.models;try{Fi(P,{recursive:!0}),re(a,`${JSON.stringify(l,null,2)}
38
+ `)}catch{return`could not write ${a}; the models were not added`}let S=!1;try{await k.modelRuntime.refresh(),S=!0}catch{S=!1}let v=w.changed>0?`, repaired ${w.changed}`:"",A=S?"":"; restart the CLI to see them all",R=d?` (created ${a})`:"";return p===0?`all ${i.length} models were already configured${v}${R}${A}`:`added ${p} model(s) to "${o}"${v}${R}${A}`},Oe=(o,i)=>{(async()=>{if(!o){let w=await ws({onProgress:v=>{let A="";try{let K=le(P,".howtofix");Fi(K,{recursive:!0,mode:448});let J=le(K,"connect-url.txt"),oe=v.kind==="browser"?[v.url]:[v.url,`code: ${v.code}`];Bn(J,oe.join(`
39
+ `)+`
40
+ `,{mode:384}),A=J}catch{A=""}let R=A?[` saved to ${A}`]:[];v.kind==="browser"?(Ve(v.url),m("connect",["finish signing in to howtofix.id:"," a browser window is opening \u2014 approve the sign-in there",` if it did not open, visit ${v.url}`,...R].join(`
41
+ `))):(Ve(v.url),m("connect",["finish signing in to howtofix.id:",` 1. go to ${v.url}`,` 2. enter the code: ${v.code}`," waiting\u2026",...R].join(`
42
+ `))),$()}});if(w.ok){C("prompt",void 0),ne=void 0,Oe(w.token,w.credential);return}let S=await Ve(rn);m("connect",[`browser sign-in: ${w.message}`,"","connect with a token instead:",` 1. ${S?"the keys page is opening in your browser":`open ${rn}`}`," 2. sign in if asked, then create a key (starts with sk-)"," 3. run /connect <token>"," or /connect again, and paste the key when asked"].join(`
43
+ `)),$();return}if(!ds(o)){m("connect","that does not look like a howtofix token; the Console issues tokens that start with sk-");return}C("note",`connecting to howtofix.id (${an(o)})`),$();let a=await ln(o);if(!a.ok){C("note",void 0),m("connect",a.message),$();return}let l=await Ro("howtofix",a.models);await k.modelRuntime.setRuntimeApiKey("howtofix",o);let d;try{await k.modelRuntime.login("howtofix","api_key",{prompt:async()=>o,notify:()=>{}})}catch(w){d=`this sign-in could not be saved (${w instanceof Error?w.message:String(w)}); run /connect again after restarting`}i&&(vs(P,i)?ge=i:d=`this sign-in renews itself, but the pair could not be saved to ${bs(P)}; it will expire in hours and need /connect again`);let y=!!k.model&&k.model?.provider!==void 0&&u.model!=="unknown",c,p;if(!y)try{let w=(await k.modelRuntime.getAvailable()).filter(A=>ie(A.provider)),v=wt(w.map(A=>A.id)).slice(0,4);for(let A of v){if(!(await ps(A,o)).ok)continue;let K=w.find(J=>J.id===A);if(K){await k.setModel(K),u.model=K.id,he(),c=`${K.provider}/${K.id}`;break}}c||(p=v.length>0?`none of the first ${v.length} models answered (${v[0]} did not)`:"the account lists no chat model")}catch(w){p=w instanceof Error?w.message:String(w)}C("note",void 0);let g=await Ae(o);m("connect",[`connected ${an(o)} \u2014 ${a.message}`,l,nt("howtofix",g),c?`using ${c} (change it with /model)`:`pick a model with /model, then send a prompt${p?` (auto-select failed: ${p})`:""}`,d].filter(w=>!!w).join(`
44
+ `)),$()})().catch(a=>{C("note",void 0),m("connect",a instanceof Error?a.message:String(a)),$()})},Eo=o=>{(async()=>{let i=Dn(o);if(!i){m("connect",["that is not an account credential."," /connect <email>:<password>"," /connect <base64 of email:password>"].join(`
45
+ `)),$();return}C("note",`signing in as ${i.username}`),$();let{token:a}=await gi(gs,i.username,i.password,rt),l=pi(P,i.username,i.password);C("note",void 0),m("connect",[`signed in as ${i.username}`,"using the CLI key this account owns \u2014 no new key was made",l?"credential stored \u2014 /connect will not ask again":"could not store the credential, so the next connect will ask again"].join(`
46
+ `)),$(),Oe(a)})().catch(i=>{C("note",void 0),m("connect",i instanceof Error?i.message:String(i)),$()})},nt=(o,i)=>{if(!i.ok)return[`${o} account`,` ${i.message}`].join(`
47
+ `);if(i.unlimited)return[`${o} account`," quota no limit on this token"].join(`
48
+ `);if(i.limit===void 0||i.used===void 0){let a=[`${o} account`],l=d=>`${d.toFixed(2)} ${i.unit}`;return i.limit!==void 0&&a.push(` granted ${l(i.limit)}`),i.used!==void 0&&a.push(` spent ${l(i.used)}`),i.remaining!==void 0&&a.push(` remaining ${l(i.remaining)}`),a.join(`
49
+ `)}return di(o,i.limit,i.used,i.unit).join(`
50
+ `)},Le=()=>({mcpServers:_s()}),ra=o=>{let i=Object.keys(o??{});return i.length===0?[]:i.map(a=>` mcp ${a} ${at(o[a])}`)},ia=o=>{let i=Xo(o.dir,o.manifest),a=o.manifest.skills.join(", ");return[o.manifest.description,` category ${o.manifest.category}`,` version ${o.manifest.version}`,` skills ${a}`,o.manifest.prompt?` prompt ${o.manifest.prompt}`:" prompt (none)",` size ${i} bytes of skill text`,` source ${o.source}`,...ra(o.manifest.mcp)].join(`
51
+ `)},Po=o=>{let i=[ia(o),""];if(o.manifest.prompt){let a=le(o.dir,o.manifest.prompt);Rt(a)&&i.push(`--- ${o.manifest.prompt} ---`,Gn(a,"utf8").trim(),"")}for(let a of o.manifest.skills){let l=le(o.dir,"skills",a,"SKILL.md");Rt(l)&&i.push(`--- skills/${a}/SKILL.md ---`,Gn(l,"utf8").trim(),"")}return i.join(`
52
+ `)},Se=async()=>{await k.reload()},Jt=!1,Io=async o=>{if(Jt){m("preset","an install is already running; wait for it to finish");return}Jt=!0;try{let i;try{i=await o()}catch(c){H(`preset not installed: ${c instanceof Error?c.message:String(c)}`);return}if(!i.ok||!i.name){H(`preset not installed:
53
+ ${i.problems.join(`
54
+ `)}`);return}await Se();let a=ee(e.cwd).entries.find(c=>c.manifest.name===i.name),l=a?.manifest.integrates||a?.manifest.mcp,d=l?`
55
+ integration disabled by default; run /preset enable ${i.name} when you want to use it`:await _o(i.name);l&&a&&Bn(le(a.dir,".disabled"),`installed
56
+ `);let y=i.modelInvocable===!1?`its skill ${i.skill} is invoke-only (disable-model-invocation): the model cannot choose it, run /skill:${i.skill} yourself`:"its skill is in the model's catalogue from the next message";m("preset",`installed ${i.name} into ${i.target}
57
+ ${y}${d}`)}finally{Jt=!1}},ot=new ze({initial:Object.keys(Le().mcpServers),apply:async(o,i)=>{if(await Se(),o.length>0||i.length>0){let a=[];o.length>0&&a.push(`connected ${o.join(", ")}`),i.length>0&&a.push(`stopped ${i.join(", ")}`),m(o.length>0?"mcp connected":"mcp stopped",a.join("; "))}},report:o=>H(o)}),st=async()=>{let o=Object.keys(Le().mcpServers);return await ot.reconcile(o)},_o=async o=>{let{entries:i}=ee(e.cwd),l=i.find(c=>c.manifest.name===o)?.manifest.mcp;if(!l||Object.keys(l).length===0)return"";let d=tn(l);if(d.problems.length>0)return`
58
+ MCP: ${d.problems.join("; ")}`;let y=[];if(d.added.length>0){let c=await st(),p=d.added.filter(g=>c.added.includes(g));y.push(p.length>0?`MCP servers connected: ${p.join(", ")}`:`MCP servers added to mcp.json: ${d.added.join(", ")}`)}return d.skipped.length>0&&y.push(`MCP servers kept as they were (already configured): ${d.skipped.join(", ")}`),y.length>0?`
59
+ ${y.join(`
60
+ `)}`:""},Oo=o=>Io(async()=>Zo(o,ct(e.cwd))),Lo=o=>{let i=o.sizeKb>=1024?`${(o.sizeKb/1024).toFixed(1)} MB`:`${o.sizeKb} KB`;return m("preset",[`downloading ${o.title}`,` from ${o.repo} @ ${o.sha.slice(0,7)}`,` skill ${o.skill}${o.modelInvocable===!1?" (invoke-only: the model cannot choose it)":""}`,` size ~${i} \xB7 ${o.license}`," checking the pinned commit and the contents the registry recorded\u2026"].join(`
61
+ `)),Io(()=>ts(o,ct(e.cwd)))},Zt=(o,i)=>{_(i,o.map(a=>({value:a.name,label:a.title,description:a.description})),a=>{let l=o.find(y=>y.name===a);if(!l)return;let d=l.sizeKb>=1024?`${(l.sizeKb/1024).toFixed(1)} MB`:`${l.sizeKb} KB`;_(l.title,[{value:"install",label:"Install",description:`download ~${d} and add its skill to this project`},{value:"view",label:"View contents",description:"read what it contains before downloading"},{value:"back",label:"Back",description:"return to the menu"}],y=>{if(y==="install"){Lo(l);return}if(y==="view"){m(`preset ${l.name}`,[`${l.description}`,"",`skill ${l.skill}`,`source ${l.repo} @ ${l.sha.slice(0,7)}`,`licence ${l.license}`,`size ~${d}`,`category ${l.category}`,`model ${l.modelInvocable===!1?"invoke-only \u2014 the model cannot choose it, only /skill:"+l.skill:"the model can choose it from its catalogue"}`,"","Install downloads the skill and adds it to this project."].join(`
62
+ `));return}Fo()})},()=>$())},Ce=(o,i)=>{_(i,o.map(a=>({value:a.manifest.name,label:a.manifest.title,description:a.manifest.skills.length>0?`${a.manifest.skills.join(", ")} \u2014 ${a.manifest.description}`:a.manifest.description})),a=>{let l=o.find(d=>d.manifest.name===a);l&&_(l.manifest.title,[{value:"install",label:"Install",description:"add its skills and rules to this project"},{value:"view",label:"View contents",description:"read the skills and prompt first"},{value:"back",label:"Back",description:"return to the menu"}],d=>{if(d==="install"){Oo(l.dir);return}if(d==="view"){m(`preset ${l.manifest.name}`,Po(l));return}Wo("")})},()=>$())},No=o=>o.filter(i=>i.manifest.integrates!==void 0),aa=()=>{let{entries:o}=ee(e.cwd),i=No(o);if(i.length===0){m("integrations","nothing installed that drives another application. /preset lists the rest.");return}Ce(i,"Integrations")},Fo=()=>{let{entries:o}=ee(e.cwd),i=[{value:"skills",label:"Skills",description:"bundles of skills and prompt text, installed into the project"},{value:"mcp",label:"MCP",description:"Model Context Protocol servers, added to mcp.json"}],a=No(o).length;a>0&&i.push({value:"integrations",label:"Integrations",description:`${a} that drive another application, and need setup there first`}),_("Presets",i,l=>l==="mcp"?Qt():l==="integrations"?aa():la())},Qt=()=>{let{entries:o,problems:i}=Ko();if(i.length>0&&m("mcp problems",i.join(`
63
+ `)),o.length===0){m("mcp catalogue","no servers in the catalogue. run /mcp to inspect the ones already configured.");return}let a=new Set(Object.keys(Le().mcpServers)),l=new Map,d=[];for(let y of Ho(o)){let c=Go(o,y);l.set(y,()=>jo(c,y));let p=c.filter(g=>a.has(g.name)).length;d.push({value:y,label:y,description:`${c.map(g=>g.title).join(", ")}${p>0?` \xB7 ${p} configured`:""}`})}l.set("all-mcp",()=>jo(o,"All MCP servers")),d.push({value:"all-mcp",label:"All servers",description:`${o.length} available${a.size>0?`, ${a.size} already configured`:""}`}),_("MCP servers",d,y=>l.get(y)?.())},jo=(o,i)=>{let a=Le().mcpServers;_(i,o.map(l=>{let d=a[l.name]!==void 0?"configured \xB7 ":"";return{value:l.name,label:l.title,description:`${d}${l.description}`}}),l=>{let d=Bo(o,l);if(!d)return;let y=a[d.name]!==void 0,c=qo(d),p=[d.description,"",`server ${d.name}`,`runs ${at(lt(d))}`,...d.needs&&d.needs.length>0?[`needs ${d.needs.join(", ")}`,c.length>0?` ${c.join(", ")} ${c.length===1?"is":"are"} not set in this shell \u2014 the value is read at connect time, so export it before the next session`:" all set in this shell"]:[],...d.docs?[`docs ${d.docs}`]:[],"",y?"already in mcp.json \u2014 removing it takes the entry out; nothing else changes":"install writes this server into mcp.json. nothing is downloaded, and it connects on the next session"].join(`
64
+ `),g=y?[{value:"remove",label:"Remove",description:"take the server out of mcp.json"},{value:"view",label:"Details",description:"what it runs and what it needs"},{value:"back",label:"Back",description:"return to the list"}]:[{value:"install",label:"Install",description:"add the server to mcp.json"},{value:"view",label:"Details",description:"what it runs and what it needs"},{value:"back",label:"Back",description:"return to the list"}];_(d.title,g,w=>{if(w==="view"){m(`mcp ${d.name}`,p);return}if(w==="install"){let S=[];if(d.preset){let R=le(Vo(),"mcp",d.preset.replace(/^mcp-/,""));if(Rt(le(R,"preset.json"))){let K=Jo(R,ct(e.cwd));K.ok||S.push(...K.problems)}}let v=tn({[d.name]:lt(d)});if(S.push(...v.problems),S.length>0){H(`mcp not installed:
65
+ ${S.join(`
66
+ `)}`);return}if(v.skipped.length>0){m("mcp install",`${d.name} is already in mcp.json; it was left as it is.`);return}let A=c.length>0?`
67
+ ${c.join(", ")} ${c.length===1?"is":"are"} not set in this shell \u2014 the value is read when the server connects, so export ${c.length===1?"it":"them"} and reload, or it will fail every call`:"";m("mcp installed",[`added ${d.name} to mcp.json${d.preset?" and installed its skill preset":""}`,` runs ${at(lt(d))}`,` connecting now; /mcp shows its state and its tools${A}`].join(`
68
+ `)),st().catch(R=>{H(`mcp installed but the session was not updated: ${R instanceof Error?R.message:String(R)}`)});return}if(w==="remove"){let S=it([d.name]);if(S.problems.length>0){H(`mcp not removed:
69
+ ${S.problems.join(`
70
+ `)}`);return}st().then(v=>{m("mcp remove",v.removed.length>0?`removed ${v.removed.join(", ")} from mcp.json and stopped ${v.removed.length===1?"it":"them"}`:S.removed.length>0?`removed ${d.name} from mcp.json`:`${d.name} was not in mcp.json`)}).catch(v=>{H(`mcp removed from config but the session was not updated: ${v instanceof Error?v.message:String(v)}`)});return}Qt()})},()=>Qt())},la=()=>{let{entries:o,problems:i}=ee(e.cwd),{entries:a,problems:l}=dt();i.length>0&&m("preset problems",i.join(`
71
+ `)),l.length>0&&m("preset problems",l.join(`
72
+ `));let d=o.filter(p=>p.source==="installed"),y=new Map,c=[];d.length>0&&(y.set("installed",()=>Ce(d,"Installed presets")),c.push({value:"installed",label:"Installed",description:`${d.length} active`}));for(let p of zo(o)){let g=Yo(o,p),w=on(a,p);y.set(p,()=>w.length>0?Do(g,p,w):Ce(g,p));let S=g.map(v=>`${v.manifest.title} (${v.manifest.skills.join(", ")})`).join(", ");c.push({value:p,label:p,description:`${S}${w.length>0?` \xB7 ${w.length} more to download`:""}`})}for(let p of es(a)){if(o.some(w=>w.manifest.category===p))continue;let g=on(a,p);y.set(p,()=>Zt(g,p)),c.push({value:p,label:p,description:`${g.length} to download`})}if(y.set("all",()=>Ce(o,"All presets")),c.push({value:"all",label:"All presets",description:`${o.length} ready to install`}),a.length>0){y.set("hub",()=>Do([],"Community presets",a));let p=new Set(a.map(g=>g.repo)).size;c.push({value:"hub",label:"Community",description:`${a.length} to download, from ${p} projects`})}_("Skill presets",c,p=>y.get(p)?.())},Do=(o,i,a)=>{if(a.length===0){Ce(o,i);return}if(o.length===0){Zt(a,`${i} (download)`);return}_(i,[{value:"local",label:`Included (${o.length})`,description:"already on disk, no download"},{value:"hub",label:`Downloadable (${a.length})`,description:"fetched when installed"}],l=>l==="local"?Ce(o,i):Zt(a,i))},Wo=o=>{let[i,...a]=o.trim().split(/\s+/),l=a.join(" ").trim();if(!i){Fo();return}if(i==="list"){let{entries:d}=ee(e.cwd),y=d.filter(c=>c.source==="installed");if(y.length===0){m("preset list","nothing installed. run /preset to browse the catalogue.");return}m("preset list",y.map(c=>`${c.manifest.name} ${c.manifest.version} [${nn(c.dir)?"disabled":"active"}]
73
+ ${c.manifest.description}
74
+ ${c.dir}`).join(`
75
+ `));return}if(i==="show"){if(!l){m("preset show","usage: /preset show <name>");return}let{entries:d}=ee(e.cwd),y=d.find(w=>w.manifest.name===l);if(y){m(`preset ${l}`,Po(y));return}let{entries:c}=dt(),p=sn(c,l);if(!p){m("preset show",`no preset named "${l}". run /preset to list them.`);return}let g=p.sizeKb>=1024?`${(p.sizeKb/1024).toFixed(1)} MB`:`${p.sizeKb} KB`;m(`preset ${l}`,[p.description,"",`skill ${p.skill}`,`source ${p.repo} @ ${p.sha.slice(0,7)}`,`licence ${p.license}`,`size ~${g}`,`category ${p.category}`,"","not installed. install it from /preset, or: /preset add-hub "+p.name].join(`
76
+ `));return}if(i==="add"){if(!l){m("preset add","usage: /preset add <git-url | directory>");return}Oo(l);return}if(i==="add-hub"){if(!l){m("preset add-hub","usage: /preset add-hub <name> (see /preset for names)");return}let{entries:d}=dt(),y=sn(d,l);if(!y){m("preset add-hub",`"${l}" is not in the community registry. run /preset to browse it.`);return}Lo(y);return}if(i==="enable"||i==="disable"){if(!l){m(`preset ${i}`,`usage: /preset ${i} <name>`);return}let d=ee(e.cwd).entries.find(c=>c.manifest.name===l&&c.source==="installed");if(!d){m(`preset ${i}`,`no installed preset named "${l}"`);return}let y=le(d.dir,".disabled");if(i==="disable"){Bn(y,`disabled
77
+ `);let c=d.manifest.mcp?it(Object.keys(d.manifest.mcp)):{removed:[],kept:[],problems:[]};st().then(()=>Se()).then(()=>m("preset",`disabled ${l}${c.removed.length?`; stopped ${c.removed.join(", ")}`:""}`)).catch(p=>H(`preset disable failed: ${p instanceof Error?p.message:String(p)}`));return}Rl(y,{force:!0}),_o(l).then(c=>Se().then(()=>m("preset",`enabled ${l}${c}`))).catch(c=>H(`preset enable failed: ${c instanceof Error?c.message:String(c)}`));return}if(i==="remove"){if(!l){m("preset remove","usage: /preset remove <name>");return}let d=Qo(l,e.cwd);if(d.problems.length>0){m("preset remove",d.problems.join(`
78
+ `));return}let c=ee(e.cwd).entries.find(v=>v.manifest.name===l),p=new Set;for(let v of ee(e.cwd).entries)if(v.manifest.name!==l)for(let A of Object.keys(v.manifest.mcp??{}))p.add(A);let g=c?.manifest.mcp?it(Object.keys(c.manifest.mcp),p):{removed:[],kept:[],problems:[]},w=g.removed.length>0?`
79
+ MCP servers removed from mcp.json: ${g.removed.join(", ")}`:g.kept.length>0?`
80
+ MCP servers kept (still used by another preset): ${g.kept.join(", ")}`:"",S=g.problems.length>0?`
81
+ MCP: ${g.problems.join("; ")}`:"";Se().then(()=>{m("preset",`removed ${l}
82
+ ${d.removed.join(`
83
+ `)}${w}${S}`)});return}m("preset",`unknown subcommand "${i}". try: list, show, add, add-hub, remove.`)},Ne=async o=>{let[i,...a]=o.slice(1).split(/\s+/),l=a.join(" ");if(i==="quit"||i==="exit"){_e();return}if(i==="help"){m("help",qn(k).map(c=>`/${c.name} ${c.description??""}`).join(`
84
+ `));return}if(i==="init"){let c=le(e.cwd,"AGENTS.md");if(Rt(c)&&l!=="force"){m("init",`AGENTS.md already exists at ${c}. run /init force to overwrite.`);return}re(c,Uo),m("init",`wrote ${c}; asking the agent to fill it in`),await k.prompt("Read AGENTS.md, then fill it in with the real build, test, and layout facts of this repo. Keep it short.");return}if(i==="login"){Xt(l);return}if(i==="connect"){let c=l.trim();if(c&&!c.startsWith("sk-")&&Dn(c)){Eo(c);return}if(c){Oe(c);return}let p=hi(P);if(p){Eo(p.credential);return}Oe(""),C("prompt","paste your howtofix.id token, then press enter"),$();let g=ne;ne=w=>{ne=g,C("prompt",void 0),Oe(w.trim())};return}if(i==="sync"){let c=new Set((await k.modelRuntime.getAvailable()).map(R=>R.provider).filter(R=>ie(R))),p=ye.find(R=>c.has(R));if(!p){m("sync","no howtofix.id account is connected; run /connect first");return}C("note",`re-syncing ${p} from howtofix.id`),$();let w=(await k.modelRuntime.getAuth(p))?.auth?.apiKey;if(!w){C("note",void 0),m("sync",`${p} has no usable key; run /connect to sign in again`),$();return}let S=await ln(w);if(!S.ok){C("note",void 0),m("sync",S.message),$();return}let v=await Ro(p,S.models),A=await Ae(w);C("note",void 0),m("sync",`${v}
85
+ ${nt(p,A)}`),await k.modelRuntime.refresh(),$();return}if(i==="usage"){let c=new Set((await k.modelRuntime.getAvailable()).map(R=>R.provider).filter(R=>ie(R))),p=ye.find(R=>c.has(R));if(!p){m("usage","no howtofix.id account is connected; run /connect first");return}C("note","asking howtofix.id for the account usage"),$();let w=(await k.modelRuntime.getAuth(p))?.auth?.apiKey;if(!w){C("note",void 0),m("usage",`${p} has no usable key; run /connect to sign in again`),$();return}let S=await Ae(w),v=await Un(w);C("note",void 0);let A=v.ok&&v.enabled?v.checkedInToday?`check-in: claimed today (+${Wn(v.quotaToday)})`:"check-in: not claimed yet today (it claims itself on the next start)":"";m("usage",A?`${nt(p,S)}
86
+ ${A}`:nt(p,S)),$();return}if(i==="logout"){let c=await k.modelRuntime.getAvailable(),p=[...new Set(c.map(g=>g.provider))].sort();if(p.length===0){m("logout","no providers are configured");return}_("Logout",p.map(g=>({value:g,label:g})),g=>{k.modelRuntime.logout(g).then(()=>m("logout",`logged out ${g}`),w=>m("logout",w instanceof Error?w.message:String(w)))});return}if(i==="providers"){let c=await k.modelRuntime.getAvailable(),p=[...new Set(c.map(g=>g.provider))].sort();p.sort((g,w)=>Number(ie(w))-Number(ie(g))),_("Providers",p.map(g=>({value:g,label:g})),g=>{let w=k.modelRuntime.getModels(g);if(w.length===0){Xt(g);return}_(g,w.map(S=>({value:S.id,label:S.id})),S=>{let v=w.find(A=>A.id===S);v&&k.setModel(v,{persist:!0}).then(()=>{u.model=v.id,he(),m("providers",`${g}/${v.id}`)},()=>Xt(g))})});return}if(i==="name"){if(!l){m("name","usage: /name <session name>");return}k.setSessionName(l),m("name",`session name: ${l}`);return}if(i==="update"){C("note","checking for a newer release");try{await uo({current:rt,install:!0})}finally{C("note",void 0)}return}if(i==="stats"){let c=k.getSessionStats(),p=k.getContextUsage(),g=v=>Number.isFinite(v)?String(v):";",w=xr(k.sessionManager.getEntries()),S=w.hitRate===null?"cache hit rate unknown (no prompt billed yet)":`cache hit ${w.hitRate.toFixed(1)}% of ${w.cachedTokens+w.billedTokens} prompt tokens`;m("stats",[`session ${c.sessionId}`,c.sessionFile?`file ${c.sessionFile}`:"not persisted",`messages ${g(c.totalMessages)} (user ${g(c.userMessages)}, assistant ${g(c.assistantMessages)}, tools ${g(c.toolCalls)})`,`tokens in ${g(c.tokens.input)} out ${g(c.tokens.output)} cache ${g(c.tokens.cacheRead)}/${g(c.tokens.cacheWrite)}`,S,w.misses.length>0?`cache misses ${w.misses.length} (${g(w.missedTokens)} tokens re-billed) \u2014 last: ${Sr(w.misses[w.misses.length-1])}`:"cache misses none counted",`cost $${Number.isFinite(c.cost)?c.cost.toFixed(4):";"}`,p?`context ${p.percent===null||!Number.isFinite(p.percent)?"?":`${Math.round(p.percent)}%`} of ${p.contextWindow}`:"context unknown"].join(`
87
+ `));return}if(i==="diff"){let c=async v=>{try{let{stdout:A}=await Vn("git",v,{cwd:e.cwd,encoding:"utf8"});return A.trim()}catch{return""}},p=await c(["diff","--stat"])+`
88
+
89
+ `+await c(["diff","--","."]),[g="",w=""]=p.split(`
90
+
91
+ `,2),S=or(w);m("diff",[g.trim(),S].filter(Boolean).join(`
92
+
93
+ `)||"working tree clean");return}if(i==="copy"){let c=[...k.state.messages].reverse().find(w=>w.role==="assistant"),g=(Array.isArray(c?.content)?c.content:[]).filter(w=>w.type==="text").map(w=>w.text).join("");if(!g){m("copy","nothing to copy");return}try{await Il(g),m("copy",`copied ${g.length} characters`)}catch(w){m("copy",w instanceof Error?w.message:String(w))}return}if(i==="export"){let c=r.items.filter(w=>w.body.trim().length>0);if(c.length===0){m("export","nothing to export yet; the transcript is empty");return}let p=Pl(e.cwd,l||`howtofix-session-${Date.now()}.md`),g=[`# ${en} session`,"",`model ${u.model}`,""];for(let w of c)g.push(`## ${w.title||w.kind}`,"",w.body,"");try{re(p,g.join(`
94
+ `))}catch(w){m("export",`could not write ${p}: ${w instanceof Error?w.message:String(w)}`);return}m("export",`wrote ${p}`);return}if(i==="agents"){let[c="",...p]=l.split(/\s+/).filter(Boolean),g=p.join(" ").trim();if(c&&g){m("agents",await Js(c,g));return}m("agents",c?Xs(c):Ys());return}if(i==="new"){let c=await e.reopen({noSession:!1});await xo(c),m("new","started a new session");return}if(i==="resume"){let c=await _l.list(e.cwd);if(c.length===0){m("resume","no saved sessions for this folder");return}_("Resume session",c.slice(0,30).map(p=>({value:p.path,label:p.name||`${p.id.slice(0,8)} ${p.firstMessage.slice(0,40)}`,description:`${p.modified.toISOString().slice(0,16)} ${p.messageCount} messages`})),p=>{e.reopen({sessionPath:p}).then(xo,g=>H(g instanceof Error?g.message:String(g)))});return}if(i==="model"){let c=await k.modelRuntime.getAvailable(),p=l?c.find(g=>`${g.provider}/${g.id}`===l||g.id===l):void 0;if(!l){_("Select model",c.map(g=>({value:`${g.provider}/${g.id}`,label:g.id,description:g.provider})),g=>{let w=c.find(S=>`${S.provider}/${S.id}`===g);w&&k.setModel(w,{persist:!0}).then(()=>{u.model=w.id,he(),m("model",`model ${g}`)})});return}if(!p){m("model",`unknown model ${l}`);return}await k.setModel(p,{persist:!0}),u.model=p.id,he(),m("model",`model ${p.provider}/${p.id}`);return}if(i==="thinking"){if(!l){_("Thinking level",G.map(c=>({value:c,label:c})),c=>Pe(c));return}if(!G.includes(l)){m("thinking",`thinking: ${G.join(", ")}`);return}Pe(l);return}if(i==="rtk"){let c=ke(P).compressToolOutput;if(!l){m("rtk",`compress tool output: ${c?"on":"off"}
95
+ /rtk on | /rtk off`);return}let p=l.toLowerCase();if(p!=="on"&&p!=="off"){m("rtk","rtk: on | off");return}let g=p==="on";if(g===c){m("rtk",`already ${p}`);return}if(!je(P,"compressToolOutput",g)){m("rtk","could not write the setting");return}to(g),m("rtk",`compress tool output ${p}
96
+ long results are ${g?"summarised before the model reads them":"sent in full"}`);return}if(i==="compact"){try{await k.compact(l||void 0),m("compact","session compacted")}catch(c){m("compact",c instanceof Error?c.message:String(c))}return}if(i==="approval"){let c=p=>{Ms(p),m("approval",un[p])};if(!l){_("Approval mode",mt.map(p=>({value:p,label:p,description:un[p]})),p=>c(p));return}if(!mt.includes(l)){m("approval",`modes: ${mt.join(", ")}`);return}c(l);return}if(i==="settings"){let c=()=>mn()?"off \u2014 everything runs":"on \u2014 critical commands are refused",p=()=>{_("Permission checks",[{value:"on",label:"on",description:"refuse critical commands and repeated calls (the default)"},{value:"off",label:"off",description:"run everything without asking \u2014 for unattended runs"}],E=>{let Y=E==="off",q=je(P,"skipPermissions",Y);if(fn(Y),u.skipPermissions=Y,$(),!q){m("settings","changed for this session, but settings.json could not be written (is it valid JSON?)");return}m("settings",Y?"permission checks are OFF \u2014 critical commands and the repeat guard will not stop anything. Stored for future sessions.":"permission checks are ON \u2014 critical commands and repeated calls are refused again.")},void 0,!1,[`Currently ${c()}.`])},g=()=>{_("Thinking level",G.map(E=>({value:E,label:E,description:E===u.thinking?"current":void 0})),E=>Pe(E),void 0,!1,[`Currently ${u.thinking}.`])},w=()=>{_("Auto-update",[{value:"on",label:"on",description:"install a newer release on start (the default)"},{value:"off",label:"off",description:"stay on this version until you update by hand"}],E=>{let Y=E!=="off",q=je(P,"autoUpdate",Y);m("settings",q?`auto-update ${Y?"on":"off"} \u2014 takes effect on the next start.`:"auto-update changed for this session, but settings.json could not be written (is it valid JSON?)")},void 0,!1,[`Currently ${Cs(`${P}/settings.json`)?"on":"off"}.`])},S=()=>{let E=We("status",e.cwd,k.getSessionStats().sessionId);_("Dynamic context pruning",[{value:"on",label:"on",description:"fold stale ranges so long sessions stay affordable"},{value:"off",label:"off",description:"send the full transcript, unpruned"},{value:"status",label:"status",description:"what it has pruned so far"}],Y=>m("dcp",We(Y,e.cwd,k.getSessionStats().sessionId)),void 0,!1,E.split(`
97
+ `).slice(0,2))},v=()=>{Ne("/model")},A=()=>{Ne("/proxy")},R=()=>{let E=ke(P).rightClickPaste,Y=process.platform==="win32"?"off":"on";_("Right click",[{value:"auto",label:"auto",description:`follow the terminal (${Y} on ${process.platform})`},{value:"on",label:"on",description:"the CLI pastes the clipboard itself"},{value:"off",label:"off",description:"the terminal handles it, or the click does nothing"}],q=>{let Fe=Os(P,q);m("settings",Fe?q==="auto"?`right click follows the terminal \u2014 ${pn("auto")?"the CLI pastes":"the terminal pastes"} here.`:`right click ${q==="on"?"pastes from the CLI":"is left to the terminal"}.`:"right click changed for this session, but settings.json could not be written (is it valid JSON?)")},void 0,!1,[`Currently ${E}.`])},K=()=>{let E=ke(P).agents,Y=[1,2,3,4].map(q=>({value:String(q),label:String(q),description:q===1?"one child at a time":q===Ue()?"current \u2014 sized to this machine":`${q} children at once`}));_("Agent concurrency",[{value:"auto",label:"auto",description:`size it to the machine (now ${Ue()}, max ${qs})`},...Y],q=>{let Fe=q==="auto"?void 0:Number(q),ca=Ls(P,Fe);m("settings",ca?Fe===void 0?`agent concurrency follows the machine \u2014 ${Ue()} at a time.`:`agent concurrency set to ${Fe} \u2014 shared by task and workflow.`:"agent concurrency changed for this session, but settings.json could not be written (is it valid JSON?)"),$()},void 0,!1)},J=[{value:"permissions",label:"permissions",description:c()},{value:"thinking",label:"thinking",description:`${u.thinking} \u2014 how hard the model reasons`},{value:"model",label:"model",description:u.model},{value:"dcp",label:"context pruning",description:"fold stale ranges to save tokens"},{value:"proxy",label:"proxy",description:cn(P)??dn()??"none \u2014 direct to the API"},{value:"rightclick",label:"right click",description:`paste: ${ke(P).rightClickPaste}`},{value:"agents",label:"agents",description:`${ke(P).agents??`auto (${Ue()})`} at once, shared by task and workflow`},{value:"autoupdate",label:"auto-update",description:"install a newer release on start"}];if(!l){_("Settings",J,E=>{E==="permissions"?p():E==="thinking"?g():E==="dcp"?S():E==="autoupdate"?w():E==="model"?v():E==="proxy"?A():E==="rightclick"?R():E==="agents"&&K()});return}let oe=J.find(E=>E.value===l||E.label===l);if(oe){oe.value==="permissions"?p():oe.value==="thinking"?g():oe.value==="dcp"?S():oe.value==="autoupdate"?w():oe.value==="model"?v():oe.value==="proxy"?A():oe.value==="rightclick"?R():oe.value==="agents"&&K();return}if(l==="on"||l==="off"){let E=l==="off",Y=je(P,"skipPermissions",E);fn(E),u.skipPermissions=E,$(),m("settings",Y?E?"permission checks are OFF \u2014 critical commands and the repeat guard will not stop anything.":"permission checks are ON.":"changed for this session, but settings.json could not be written (is it valid JSON?)");return}m("settings",`settings: ${J.map(E=>E.value).join(", ")} | on, off (permission checks)
98
+ usage: /settings <name>, or /settings to choose`);return}if(i==="proxy"){let c=cn(P),p=dn(),g=()=>c?`proxy: ${c} (set here, in settings.json)`:p?`proxy: ${p} (from the environment, not this file)`:"proxy: none \u2014 requests go straight to the API";if(!l){m("proxy",`${g()}
99
+ usage: /proxy <url> route requests through a proxy
100
+ /proxy off stop using one
101
+ /proxy env use HTTPS_PROXY / HTTP_PROXY / ALL_PROXY
102
+ Only traffic to the HowToFix API goes through it; a change applies on the next start.`);return}let w=l.trim();if(w==="off"||w==="none"){let R=pt(P,ut,""),K=ft(P),J=K.source==="env"?`the environment still sets one (${K.url})`:"requests go straight to the API";m("proxy",R?`proxy off \u2014 ${J} from the next message.`:"proxy changed for this session, but settings.json could not be written (is it valid JSON?)");return}if(w==="env"){let R=pt(P,ut,""),K=ft(P),J=K.source==="env"?K.url:void 0;m("proxy",R?J?`using the environment from the next message: ${J}`:"settings cleared, but no HTTPS_PROXY / HTTP_PROXY / ALL_PROXY is set \u2014 requests go straight to the API.":"settings.json could not be written (is it valid JSON?)");return}let S=Ss(w);if(!S.ok){m("proxy",`not set: ${S.problem}`);return}if(!pt(P,ut,S.url)){m("proxy","settings.json could not be written (is it valid JSON?)");return}let A=ft(P);m("proxy",A.url?`proxy set to ${S.url} \u2014 requests go through it from the next message.`:`proxy saved as ${S.url}, but it could not be applied this session; it will be tried on the next start.`);return}if(i==="tools"){let c=k.getActiveToolNames().sort();m("tools",c.length?c.join(`
103
+ `):"no tools enabled");return}if(i==="dcp"){m("dcp",We(l,e.cwd,k.getSessionStats().sessionId));return}if(i==="context"||i==="decompress"||i==="sweep"){m(i,We(`${i} ${l}`.trim(),e.cwd,k.getSessionStats().sessionId));return}if(i==="rewind"){lo();return}if(i==="undo"){if(!await yn(e.cwd)){m("undo","not a git repository");return}let c=await tr(e.cwd);m("undo",c.ok?`undone: ${c.output}`:`undo failed: ${c.output}`),h(!0);return}if(i==="commit"){if(!yn(e.cwd)){m("commit","not a git repository");return}if(!await Qs(e.cwd)){m("commit","nothing to commit");return}let c=l||`howtofix: session update ${new Date().toISOString().slice(0,16)}`,p=await er(e.cwd,c);m("commit",p.ok?p.output:`commit failed: ${p.output}`),h(!0);return}if(i==="review"){if(!(await nr(e.cwd)).trim()){m("review","no changes to review");return}zt("Review the uncommitted changes. Report concrete issues with file evidence. Do not edit files.");return}if(i==="workflow"){if(l.trim()==="clear"){Zn(),m("workflow","cleared the pinned workflow panel");return}if(!U){m("workflow","no workflow run in this session yet");return}let c=kn(U,Date.now()),p=c[I.selectedPhase];m("workflow",[`panel ${X?"pinned above the editor":"unpinned"}`,`phase ${I.selectedPhase+1}/${c.length}: ${p?.title??"(none)"}`,`filter: ${I.filter}${I.paused?" \xB7 paused":""}`,"keys: \u2191/\u2193 phase \xB7 Enter drill in \xB7 Esc unpin \xB7 f filter \xB7 p pause \xB7 x stop \xB7 s save","clear it with /workflow clear"].join(`
104
+ `));return}if(i==="plan"){if(Gs()||gt().state==="pending"){gn(Ks(gt())),m("plan","plan mode off; edits are allowed again");return}gn(Us(gt())),m("plan",`plan mode armed \u2014 send your next prompt to start planning
105
+ plan file: ${Hs()??"(unknown)"}`);return}if(i==="goal"){let c=l.trim();if(!c){m("goal",hn(ht()));return}let{goal:p,error:g}=Ws(ht(),"set",c,void 0,void 0);if(g){H(g);return}Ds(p),await k.sendCustomMessage({customType:Fs,content:c,display:!1,details:p}),m("goal",`goal set
106
+ ${hn(p)}`);return}if(i==="session"){let c=k.model;m("session",c?`${c.provider}/${c.id}`:"no model");return}if(i==="skills"){m("skills",br(k.resourceLoader.getSkills().skills));return}if(i==="preset"){Wo(l);return}if(i==="roblox"){let c=ee(e.cwd).entries.find(S=>S.manifest.name==="rotoolbox");if(!c||c.source!=="installed"){m("roblox","RoToolbox is not installed. Run /preset and install RoToolbox first.");return}let p=nn(c.dir),g=k.getActiveToolNames().filter(S=>/roblox[-_]studio/i.test(S)),w=g.length>0;m("roblox",p?`RoToolbox: disabled
107
+ Enable with /preset enable rotoolbox
108
+ The MCP server and manager stay stopped while disabled.`:["RoToolbox: active",`MCP server: ${w?`connected \u2014 ${g.length} tool${g.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(`
109
+ `));return}let d=wr(o,k.resourceLoader.getSkills().skills.map(c=>c.name));if(d){Ao(d);return}let y=k.extensionRunner.getCommand(i??"");if(y){try{await y.handler(l,k.extensionRunner.createCommandContext())}catch(c){H(c instanceof Error?c.message:String(c))}return}m("command",`/${i??""} is not available in this screen yet`)};Ns((o,i)=>{let{promise:a,resolve:l}=Promise.withResolvers();return _(o,i.map(d=>({value:d,label:d})),l,()=>l("cancelled")),a}),process.on("SIGTERM",_e),vr(()=>{_e()}),t.setTitle(`${en} ${rt}`),Yl(),s.start(),s.requestRender(!0),Co(!0);{let{maybeShowWelcome:o}=await import("./chunk-AEVPET7X.js");await o({cwd:e.cwd,note:e.note,signedIn:ge!==void 0,runSlash:i=>{Ne(i)},openExternal:i=>{Ve(i)}},_,m)}e.initialPrompt&&zt(e.initialPrompt),await new Promise(()=>{})}var ne,Xl=1e3/30,Jl=45e3;export{Xn as Dock,zn as Hud,Yn as PinnedBlock,ql as approvalDetail,wt as orderModelsForDefault,Bl as pickerPanel,lu as runWorkbench,qn as slashCommands,Vl as workflowPanel,Et as workflowPanelFromRun,Jn as workflowRunOf};
@@ -0,0 +1,5 @@
1
+ import{b as x}from"./chunk-AGGIYXN7.js";import{D as d}from"./chunk-V656XVXV.js";import{a as S}from"./chunk-PCALBZOO.js";import"./chunk-UTYFLLSM.js";import{a as h}from"./chunk-OIPSLIZE.js";import"./chunk-WOT6VMZA.js";import{spawnSync as O}from"node:child_process";import{readdirSync as b,readFileSync as w,statSync as j,writeFileSync as N,unlinkSync as E}from"node:fs";import{join as p}from"node:path";var g=[22,19];async function I(o="https://api.howtofix.id/api/status"){let s=[],[n,t]=process.versions.node.split(".").map(Number),i=n>g[0]||n===g[0]&&t>=g[1];s.push({name:"node",ok:i,detail:`${process.versions.node} (needs >= ${g[0]}.${g[1]})`});let a=O("git",["--version"],{encoding:"utf8"});s.push({name:"git",ok:a.status===0,detail:a.status===0?a.stdout.trim():"not found on PATH"});let e=S();s.push({name:"sandbox",ok:!!e,detail:e??"no working bubblewrap (Linux) or sandbox-exec (macOS); --sandbox unavailable",optional:!0});let c=!1,r=d;try{let u=p(d,`.doctor-${process.pid}`);N(u,"ok"),E(u),c=!0}catch(u){r=`${d} is not writable: ${u instanceof Error?u.message:String(u)}`}s.push({name:"state dir",ok:c,detail:r});let l=p(d,"auth.json"),f="no auth.json \u2014 run `howtofix` and sign in",$=!1;try{let u=JSON.parse(w(l,"utf8")),m=Object.keys(u).length;$=m>0,f=$?`${m} provider credential${m===1?"":"s"}`:f}catch{}s.push({name:"auth",ok:$,detail:f,optional:!0});try{let u=Date.now(),m=await fetch(o,{signal:AbortSignal.timeout(5e3)});s.push({name:"gateway",ok:m.ok,detail:`${o} \u2192 ${m.status} in ${Date.now()-u}ms`,optional:!0})}catch(u){s.push({name:"gateway",ok:!1,detail:`${o} unreachable: ${u instanceof Error?u.message:String(u)}`,optional:!0})}return s}async function F(){let o=await I(),s=Math.max(...o.map(t=>t.name.length));for(let t of o){let i=t.ok?"ok ":t.optional?"warn":"FAIL";console.log(` ${i} ${t.name.padEnd(s)} ${t.detail}`)}let n=o.filter(t=>!t.ok&&!t.optional);return n.length>0?(console.log(`
2
+ ${n.length} problem${n.length===1?"":"s"} must be fixed before a session will work.`),1):0}function _(o=d){let s=p(o,"models.json"),n;try{n=w(s,"utf8")}catch(e){return e.code==="ENOENT"?console.log(` no models.json at ${s} \u2014 run \`howtofix /connect\` to pull the catalogue`):x(h,"models",e),1}let t;try{t=JSON.parse(n)}catch(e){return console.error(`${h}: models: ${s} is not valid JSON (${e instanceof Error?e.message:String(e)})`),console.error(" fix the file, or delete it and run `howtofix /connect` to write a new one"),1}let i=t.providers??{},a=0;for(let[e,c]of Object.entries(i)){let r=(c.models??[]).map(l=>l.id).filter(Boolean);a+=r.length,console.log(` ${e} (${r.length})`);for(let l of r)console.log(` ${l}`)}return a===0?(console.log(" no models configured"),1):0}function y(o=15,s=d){let n=p(s,"sessions"),t;try{t=b(n)}catch{return[]}let i=[];for(let a of t){let e=p(n,a),c;try{c=b(e)}catch{continue}for(let r of c){if(!r.endsWith(".jsonl"))continue;let l=p(e,r);try{let f=j(l);i.push({file:l,project:a,modified:f.mtimeMs,bytes:f.size})}catch{}}}return i.sort((a,e)=>e.modified-a.modified).slice(0,o)}function B(o){let s=o.indexOf("--search");if(s>=0){let e=o[s+1]?.trim();if(!e)return console.error(`${h}: sessions: --search needs a word or phrase`),2;let c=D(e);if(c.length===0)return console.log(` no session mentions "${e}"`),0;for(let r of c){let l=new Date(r.row.modified).toISOString().replace("T"," ").slice(0,16);console.log(` ${l} ${r.row.project} (${r.matches} hit${r.matches===1?"":"s"})`),console.log(` ${r.row.file}`),console.log(` ${r.snippet}`)}return 0}let n=o.indexOf("--limit"),t=n>=0&&Number(o[n+1])||15,i=y(t);if(i.length===0)return console.log(` no saved sessions under ${p(d,"sessions")}`),o.includes("--export")?1:0;let a=o.indexOf("--export");if(a>=0){let e=Number(o[a+1]);if(!Number.isInteger(e)||e<1||e>i.length)return console.error(`${h}: sessions: --export needs a number from the list (1-${i.length})`),2;let c=i[e-1];try{console.log(R(c.file))}catch(r){return x(h,"sessions",r),1}return 0}return i.forEach((e,c)=>{let r=new Date(e.modified).toISOString().replace("T"," ").slice(0,16),l=Math.round(e.bytes/1024);console.log(` ${String(c+1).padStart(2)} ${r} ${String(l).padStart(6)}k ${e.project}`),console.log(` ${e.file}`)}),0}function k(o){try{let n=JSON.parse(o).message?.content;if(typeof n=="string")return n.replace(/\s+/g," ").trim();if(Array.isArray(n))return n.map(t=>t&&typeof t=="object"&&"text"in t?String(t.text):"").join(" ").replace(/\s+/g," ").trim()}catch{}return o.replace(/\s+/g," ").trim()}function D(o,s=10,n=d){let t=o.toLowerCase(),i=[];for(let a of y(500,n)){let e;try{e=w(a.file,"utf8")}catch{continue}let c=0,r="";for(let l of e.split(`
3
+ `))l.toLowerCase().includes(t)&&(c++,r||(r=k(l).slice(0,160)));if(c>0&&i.push({row:a,matches:c,snippet:r}),i.length>=s)break}return i}function R(o){let s=[`# Session ${o.split(/[\\/]/).pop()??o}`,""];for(let n of w(o,"utf8").split(`
4
+ `)){if(!n.trim())continue;let t;try{t=JSON.parse(n)}catch{continue}if(t.type!=="message")continue;let i=k(n);i&&s.push(`## ${t.message?.role??"unknown"}`,"",i,"")}return s.join(`
5
+ `).trimEnd()}export{I as collectChecks,R as exportSessionMarkdown,y as listSessionFiles,F as runDoctor,_ as runModels,B as runSessions,D as searchSessions};
@@ -0,0 +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}from"./chunk-V656XVXV.js";import"./chunk-UTYFLLSM.js";import"./chunk-WOT6VMZA.js";export{e as AGENTS_STORE_DIR,a as AGENT_DIR,f as USAGE_CACHE_PATH,b as USER_SKILLS_DIR,g as WORKFLOWS_DIR,d as additionalSkillPaths,h as pinAgentDir,c as projectSkillsDir};
@@ -0,0 +1 @@
1
+ import{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-63ZCQDXH.js";import"./chunk-UTYFLLSM.js";import"./chunk-ZKZ6WCI3.js";import"./chunk-OIPSLIZE.js";import"./chunk-WOT6VMZA.js";export{f as CATALOG_CACHE_TTL_MS,l as DEFAULT_CONTEXT_WINDOW,a as HOWTOFIX_BASE_URL,b as HOWTOFIX_CONSOLE_URL,k as HOWTOFIX_MODEL_COMPAT,c as HOWTOFIX_PROVIDERS,i as HTTP_IDLE_TIMEOUT_MS,q as UNLIMITED_SENTINEL,u as applyCatalog,v as applyCompat,z as checkAccount,r as checkUsage,w as countNewModels,j as ensureGatewaySettings,y as findLiveModels,p as isHowtofixProvider,g as loadCatalog,n as looksLikeToken,m as maskToken,t as mergeModels,d as newProviderEntry,o as parseModelIds,x as probeModel,e as repairGatewayModels,h as repairModelFacts,s as syncGatewayModelsOnStart};
@@ -0,0 +1 @@
1
+ import{a,b,c}from"./chunk-WX3V5P7U.js";import"./chunk-V656XVXV.js";import"./chunk-UTYFLLSM.js";import"./chunk-WOT6VMZA.js";export{c as formatSkillList,b as skillInvocation,a as skillSearchPaths};
@@ -0,0 +1,2 @@
1
+ var C=new Set(["think"]),l;function E(n){let t=new WeakSet,o=e=>{if(e===null||typeof e!="object")return e;if(t.has(e))return"[circular]";if(t.add(e),Array.isArray(e))return e.map(o);let r=e,s={};for(let i of Object.keys(r).sort())s[i]=o(r[i]);return s};try{return JSON.stringify(o(n))??""}catch{return""}}function x(n,t){if(C.has(n))return;let o=`${n}\0${E(t)}`,e=l&&l.signature===o?l.count+1:1;return l={signature:o,count:e},e>=3?{repeats:e}:void 0}function Q(){l=void 0}function v(n,t){return`Refused: ${n} has been called ${t} times in a row with identical arguments, so the last attempt cannot have changed anything. Do not repeat it. Either use different arguments, use a different tool, or stop and report what you found and what is blocking you.`}var $=/^-[a-zA-Z0-9_-]/;function h(n,t){switch(t){case"number":return/^\d+$/.test(n);case"string":return!0;default:return!1}}function O(n,t){if(!/^-[^-]/.test(n)||n.includes("="))return!1;for(let o=1;o<n.length;o++){let e=t[`-${n[o]}`];if(!e)return!1;if(e!=="none")return h(n.slice(o+1),e)}return!0}function L(n,t,o){let e=t;for(;e<n.length;){let r=n[e];if(!r){e++;continue}if(r==="--")break;if($.test(r)){if(/^-\d+$/.test(r)&&o.safeFlags["-n"]){e++;continue}let s=r.includes("="),[i="",...c]=r.split("="),a=o.safeFlags[i];if(!a){if(!O(r,o.safeFlags))return!1;e++;continue}if(a==="none"){if(s)return!1;e++;continue}if(a==="optional"){e++;continue}if(s){if(!h(c.join("="),a))return!1;e++;continue}let y=n[e+1];if(y===void 0||!h(y,a))return!1;e+=2;continue}if(o.allowPositional===!1)return!1;e++}return!0}var M={"--all":"none","--branches":"none","--tags":"none","--remotes":"none"},u={"--oneline":"none","--graph":"none","--decorate":"none","--no-decorate":"none","--date":"string","--relative-date":"none"},g={"--max-count":"number","-n":"number"},p={"--stat":"none","--numstat":"none","--shortstat":"none","--name-only":"none","--name-status":"none"},d={"--color":"none","--no-color":"none"},m={"--patch":"none","-p":"none","--no-patch":"none","--no-ext-diff":"none","-s":"none"},A={"--author":"string","--committer":"string","--grep":"string"},I={"-l":"none","--list":"none","-a":"none","-r":"none","-v":"none","-vv":"none","-i":"none"},F={"git status":{safeFlags:{"-s":"none","--short":"none","-b":"none","--branch":"none","-u":"optional","--untracked-files":"optional","--porcelain":"optional","--ignored":"none","--long":"none","--no-renames":"none",...d}},"git diff":{safeFlags:{...p,...d,...m,"--cached":"none","--staged":"none","--word-diff":"none","--check":"none","--quiet":"none","--exit-code":"none","--no-renames":"none","--diff-filter":"string","--relative":"string","--full-index":"none","--binary":"none","--abbrev":"number","--unified":"number","-U":"number","--ignore-all-space":"none","--ignore-space-change":"none","--ignore-blank-lines":"none"}},"git log":{safeFlags:{...u,...g,...p,...d,...m,...A,...M,"--since":"string","--after":"string","--until":"string","--before":"string","--follow":"none","--no-merges":"none","--merges":"none","--first-parent":"none","--reverse":"none","--skip":"number","--all":"none","--format":"string","--pretty":"string","--abbrev-commit":"none","--no-abbrev-commit":"none","--left-right":"none"}},"git show":{safeFlags:{...p,...d,...m,...u,"--format":"string","--pretty":"string","--abbrev-commit":"none","--no-patch":"none","-q":"none"}},"git shortlog":{safeFlags:{...g,"-s":"none","--summary":"none","-n":"none","--numbered":"none","-e":"none","--email":"none","-sn":"none","-ns":"none","--all":"none"}},"git reflog":{safeFlags:{...g,...u,...A,"--all":"none","--date":"string"}},"git blame":{safeFlags:{"-L":"string","-w":"none","-c":"none","-n":"none","-s":"none","-e":"none","-p":"none","--porcelain":"none","--line-porcelain":"none","--date":"string","--since":"string","-C":"none","-M":"none"}},"git ls-files":{safeFlags:{"-m":"none","--modified":"none","-o":"none","--others":"none","-i":"none","--ignored":"none","-s":"none","--stage":"none","-d":"none","--deleted":"none","-c":"none","--cached":"none","-u":"none","--unmerged":"none","--exclude-standard":"none","--error-unmatch":"none","-z":"none"}},"git ls-remote":{safeFlags:{"--heads":"none","--tags":"none","--refs":"none","--symref":"none"}},"git rev-parse":{safeFlags:{"--short":"optional","--abbrev-ref":"none","--verify":"none","--quiet":"none","--git-dir":"none","--show-toplevel":"none","--show-cdup":"none","--is-inside-work-tree":"none","--is-bare-repository":"none","--symbolic-full-name":"none","--abbrev":"optional"}},"git rev-list":{safeFlags:{...g,"--count":"none","--all":"none","--objects":"none","--reverse":"none","--max-parents":"number","--min-parents":"number","--no-merges":"none","--first-parent":"none","--abbrev-commit":"none"}},"git describe":{safeFlags:{"--tags":"none","--all":"none","--long":"none","--always":"none","--dirty":"none","--abbrev":"number","--match":"string","--exclude":"string","--first-parent":"none"}},"git cat-file":{safeFlags:{"-p":"none","-t":"none","-s":"none","-e":"none","--batch-check":"none"}},"git for-each-ref":{safeFlags:{"--format":"string","--count":"number","--sort":"string","--points-at":"string","--merged":"string","--no-merged":"string"}},"git grep":{safeFlags:{"-n":"none","--line-number":"none","-i":"none","--ignore-case":"none","-l":"none","--files-with-matches":"none","-c":"none","--count":"none","-w":"none","--word-regexp":"none","-E":"none","--extended-regexp":"none","-F":"none","--fixed-strings":"none","--cached":"none","--untracked":"none","-e":"string","--and":"none","--or":"none","--not":"none"}},"git merge-base":{safeFlags:{"--all":"none","--is-ancestor":"none","--fork-point":"none","--octopus":"none"}},"git stash list":{safeFlags:{...u}},"git worktree list":{safeFlags:{"--porcelain":"none","-v":"none","--verbose":"none","-z":"none"}},"git branch":{safeFlags:{...I,"--merged":"string","--no-merged":"string","--contains":"string","--no-contains":"string","--sort":"string","--format":"string","--points-at":"string","--column":"none","--show-current":"none"},dangerous:n=>{let t=new Set(["--merged","--no-merged","--contains","--no-contains","--sort","--format","--points-at"]),o=!1;for(let e of n){if(o){o=!1;continue}if(t.has(e)){o=!0;continue}if(!e.startsWith("-"))return!0}return!1}},"git tag":{safeFlags:{"-l":"none","--list":"none","-n":"number","--contains":"string","--no-contains":"string","--merged":"string","--sort":"string","--points-at":"string","--column":"none"},dangerous:n=>{let t=new Set(["--contains","--no-contains","--merged","--sort","--points-at"]),o=!1;for(let e of n){if(o){o=!1;continue}if(t.has(e)){o=!0;continue}if(!e.startsWith("-"))return!0}return!1}},"git remote":{safeFlags:{"-v":"none","--verbose":"none"},dangerous:n=>n.some(t=>!t.startsWith("-"))},"git config --get":{safeFlags:{"--local":"none","--global":"none","--system":"none","--get-all":"none","--get-regexp":"none","--list":"none","-l":"none","--show-origin":"none","--null":"none","-z":"none"}}},S=["ls","pwd","cat","head","tail","wc","which","whoami","date","echo","sleep","true","false","type","test","seq","basename","dirname","realpath","stat","file","du","df","tree","uname","hostname","id","groups","tty","cal","uptime","free","locale","printf","grep","rg","fd","jq","bat","column","paste","nl","expand","fold","fmt","md5sum","sha1sum","sha256sum","sha512sum","b2sum","cksum","diff","cmp"],P={find:{safeFlags:{"-name":"string","-iname":"string","-type":"string","-maxdepth":"number","-mindepth":"number","-newer":"string","-path":"string","-not":"none","-print":"none","-print0":"none","-empty":"none","-size":"string","-mtime":"number","-atime":"number","-perm":"string","-L":"none","-H":"none","-P":"none"},dangerous:n=>n.some(t=>/^-(delete|exec|execdir|ok|okdir|fprint0?|fls|fprintf)$/.test(t))},sort:{safeFlags:{"-n":"none","-r":"none","-u":"none","-k":"string","-t":"string","-f":"none","-h":"none","-V":"none","-s":"none","-c":"none","-m":"none","-b":"none","-z":"none"}},uniq:{safeFlags:{"-c":"none","-d":"none","-u":"none","-i":"none","-f":"number","-s":"number","-w":"number"}},cut:{safeFlags:{"-d":"string","-f":"string","-c":"string","-b":"string","-s":"none","--complement":"none","-z":"none"}},tr:{safeFlags:{"-d":"none","-s":"none","-c":"none"}},node:{safeFlags:{"-v":"none","--version":"none"},allowPositional:!1},python:{safeFlags:{"--version":"none"},allowPositional:!1},python3:{safeFlags:{"--version":"none"},allowPositional:!1},npm:{safeFlags:{"--version":"none","-v":"none"},allowPositional:!1},sed:{safeFlags:{"-n":"none","--quiet":"none","-e":"string","-E":"none","-r":"none","--regexp-extended":"none","-s":"none","-u":"none","-z":"none","--posix":"none"},dangerous:n=>n.some(t=>/^-i|^--in-place/.test(t)||/\b[we]\s/.test(t)||/^[we]$/.test(t))},awk:{safeFlags:{"-F":"string","-v":"string","-f":"string"},dangerous:n=>n.some(t=>/\bsystem\s*\(|\|\s*"|>\s*"/.test(t))},xxd:{safeFlags:{"-l":"number","-s":"string","-c":"number","-g":"number","-p":"none","-i":"none","-u":"none","-b":"none","-e":"none","-o":"number"},dangerous:n=>n.some(t=>t==="-r"||/^-[a-z]*r/.test(t))}},k={"npm ls":{safeFlags:{"--depth":"number","--json":"none","--long":"none","--parseable":"none","--all":"none","--prod":"none","--dev":"none","--omit":"string","--link":"none","--global":"none","-g":"none","--silent":"none"}},"npm view":{safeFlags:{"--json":"none","--registry":"string"}},"docker ps":{safeFlags:{"-a":"none","--all":"none","-q":"none","--quiet":"none","--no-trunc":"none","--format":"string","-n":"number","--last":"number","-s":"none","--size":"none","--filter":"string"}},"docker images":{safeFlags:{"-a":"none","--all":"none","-q":"none","--quiet":"none","--no-trunc":"none","--format":"string","--filter":"string","--digests":"none"}},"docker inspect":{safeFlags:{"--format":"string","-f":"string","-s":"none","--size":"none","--type":"string"}},"kubectl get":{safeFlags:{"-o":"string","--output":"string","-n":"string","--namespace":"string","-A":"none","--all-namespaces":"none","--no-headers":"none","-l":"string","--selector":"string","--show-labels":"none","-w":"none","--watch":"none","--sort-by":"string"}},"kubectl describe":{safeFlags:{"-n":"string","--namespace":"string","-l":"string","--selector":"string"}},"cargo tree":{safeFlags:{"--depth":"number","-e":"string","--edges":"string","--no-dev-dependencies":"none","--prefix":"string","-i":"string","--invert":"string","-p":"string","--package":"string"}},"go version":{safeFlags:{}}},z=["cd","alias","history","arch","ip addr","ifconfig"];function G(n){if(!/\$\(|`|\$\{|>|</.test(n)&&!/(?<!&)&(?!&)/.test(n))return n.split(/\|\||&&|;|\|/).map(t=>t.trim()).filter(t=>t.length>0)}function D(n){let t=n.some(e=>/^cd\b/.test(e)),o=n.some(e=>/^git\b/.test(e));return t&&o}function q(n){let t=[],o=/'[^']*'|"[^"]*"|\S+/g;for(let e of n.match(o)??[])t.push(e.length>=2&&/^['"]/.test(e)?e.slice(1,-1):e);return t}function N(n){if(n.length===0)return;let[t="",o=""]=n,e=`${t} ${o}`;if(t==="git"&&o==="config"){let r=n[2];return r==="--get"||r==="--get-all"||r==="--get-regexp"||r==="-l"||r==="--list"?{name:"git config --get",rest:n.slice(3)}:void 0}return t==="git"&&o==="stash"?n[2]==="list"?{name:"git stash list",rest:n.slice(3)}:void 0:t==="git"&&o==="worktree"?n[2]==="list"?{name:"git worktree list",rest:n.slice(3)}:void 0:t==="git"&&F[`git ${o}`]?{name:`git ${o}`,rest:n.slice(2)}:k[e]?{name:e,rest:n.slice(2)}:{name:t,rest:n.slice(1)}}var j=new Set(["echo","printf"]);function U(n){let t=q(n),o=N(t);if(!o)return!1;let{name:e,rest:r}=o;if(j.has(e)&&r.some(i=>i.includes("$")||i.includes("`")))return!1;let s=F[e]??P[e]??k[e];return s?s.dangerous?.(r)?!1:L(r,0,s):!!(S.includes(e)||z.includes(e))}function b(n){let t=G(n);return!t||t.length===0||D(t)?!1:t.every(U)}var W=["suggest","auto-edit","full-auto"],rn={suggest:"suggest: ask before every edit and command","auto-edit":"auto-edit: edits run, commands ask","full-auto":"full-auto: nothing asks"};function sn(n){return W.includes(n)}var T={read:0,write:1,exec:2},H={suggest:"read","auto-edit":"write","full-auto":"exec"},B={read:"read",grep:"read",find:"read",ls:"read",think:"read",ask:"read",todo:"read",context:"read",web_search:"read",web_fetch:"read",lsp:"read",quality:"read",workflow:"exec",goal:"read",enter_plan_mode:"read",exit_plan_mode:"read",edit:"write",write:"write",bash:"exec",powershell:"exec",task:"exec"};function R(n){let t=B[n];return t||(n.startsWith("mcp__")?"write":"exec")}var V=new Set(["sudo","doas","env","nohup","time","exec","command","nice","setsid","stdbuf"]),Z=new Set(["-u","-g","-p","-C","-S","-U","--user","--group","--prompt","--close-from","--chdir","--setenv","--unset"]);function Y(n){let t=(n.match(/"[^"]*"|'[^']*'|\S+/g)??[]).map(s=>s.replace(/^['"]|['"]$/g,"")),o=0;for(;o<t.length;){let s=t[o]??"";if(/^[A-Za-z_][A-Za-z0-9_]*=/.test(s)||V.has(s)){o++;continue}if(s.startsWith("-")){o+=Z.has(s)?2:1;continue}break}let e=t[o];if(e===void 0)return;let r=e.split("/").pop()??e;if(r==="rm"){let s=t.slice(o+1),i=s.some(a=>/^-[a-zA-Z]*r[a-zA-Z]*$/i.test(a)||a==="--recursive"),c=s.find(a=>!a.startsWith("-"));return i&&(c===void 0||/^(?:\/|\/\*|~|~\/\*|\$HOME|\$HOME\/\*|\*)$/.test(c))?"recursive delete of the filesystem root or home":void 0}if(r==="dd")return t.slice(o+1).some(s=>/^of=\/dev\/(?:sd|nvme|hd|vd)/.test(s))?"raw write to a block device":void 0;if(/^mkfs(?:\.[a-z0-9]+)?$/.test(r))return"filesystem format";if(/:\(\)\s*\{.*\}\s*;:/.test(n))return"fork bomb";if(/^(?:shutdown|reboot|halt|poweroff)$/.test(r))return"host shutdown";if(/>\s*\/etc\/(?:passwd|shadow|sudoers)/.test(n))return"overwrite of a system account file"}var w="full-auto",_=async()=>!1,f=!1;function an(n){w=n}function ln(){return w}function cn(n){f=n}function un(){return f}function gn(n){_=n}function J(n,t,o){if(f)return{action:"run"};let e=typeof o?.command=="string"?o.command:"";if(t==="bash"||t==="powershell"){let s=Y(e);if(s)return{action:"deny",reason:`Refused in every mode: ${s}.`};if(b(e))return{action:"run"}}let r=R(t);return T[r]<=T[H[n]]?{action:"run"}:{action:"prompt",reason:`this is a ${r}-tier tool`}}function K(n,t){if(t&&typeof t=="object"){let o=t;if((n==="bash"||n==="powershell")&&typeof o.command=="string")return o.command;if((n==="edit"||n==="write")&&typeof o.path=="string"){let e=Array.isArray(o.edits)?` (${o.edits.length} edits)`:"";return`${o.path}${e}`}try{let e=JSON.stringify(o);if(e&&e!=="{}")return e.length>300?`${e.slice(0,297)}...`:e}catch{}}return n}function X(n,t,o){let e=[`Allow tool: ${n}`];n.startsWith("mcp__")&&e.push("Origin: MCP server tool"),e.push(`Reason: ${o}`);let r=K(n,t);return r!==n&&e.push(r),e.join(`
2
+ `)}function dn(n={}){return t=>{t.on("tool_call",async o=>{if(f)return;let e=x(o.toolName,o.input);if(e)return{block:!0,reason:v(o.toolName,e.repeats)};let r=w,s=J(r,o.toolName,o.input);if(s.action==="run")return;if(s.action==="deny")return{block:!0,reason:s.reason};if(n.interactive===!1)return{block:!0,reason:`Blocked: this is a ${R(o.toolName)}-tier tool and no UI can approve it here (approval mode: ${r}).`};if(!await _(`${o.toolName} wants to run`,X(o.toolName,o.input,s.reason)))return{block:!0,reason:`Blocked by the user (approval mode: ${r}).`}})}}export{Q as a,b,W as c,rn as d,sn as e,T as f,H as g,R as h,Y as i,an as j,ln as k,cn as l,un as m,gn as n,J as o,K as p,X as q,dn as r};
@@ -0,0 +1 @@
1
+ import{a,b}from"./chunk-BHVBO4SC.js";import"./chunk-WOT6VMZA.js";export{a as deadChannelModel,b as diagnoseGatewayFailure};
@@ -0,0 +1 @@
1
+ import{a,b,c,d}from"./chunk-PCALBZOO.js";import"./chunk-WOT6VMZA.js";export{c as describeSandbox,a as detectSandbox,d as enterSandbox,b as sandboxArgv};
@@ -0,0 +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-PDNBGUYP.js";import"./chunk-UTYFLLSM.js";import"./chunk-ZKZ6WCI3.js";import"./chunk-OIPSLIZE.js";import"./chunk-WOT6VMZA.js";export{b as CLI_REFRESH_SKEW_MS,c as accessTokenIsFresh,g as clearCliCredential,a as cliCredentialsPath,e as readCliCredential,h as refreshCliCredential,d as refreshTokenIsUsable,i as renewCliCredentialIfNeeded,f as writeCliCredential};
@@ -0,0 +1,5 @@
1
+ var a="HowToFix",o="0.7.9",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
+ `);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
+
4
+ `).trim()}var i=["# Project notes","","## What this is","","## Commands","- build:","- test:","","## Conventions","-",""].join(`
5
+ `);export{a,o as b,n as c,s as d,i as e};
@@ -0,0 +1,3 @@
1
+ import{readFileSync as f,statSync as u}from"node:fs";import{isAbsolute as a,resolve as p}from"node:path";var $=64*1024;function S(o,c){return o.replace(/(^|\s)@([^\s]+)/g,(e,l,i)=>{let t=i.replace(/[),.;:]+$/,""),g=i.slice(t.length),n=a(t)?t:p(c,t);try{let r=u(n);if(!r.isFile()||r.size===0||r.size>$)return e;let s=f(n);return s.includes(0)?e:`${l}<file name="${n}">
2
+ ${s.toString("utf8").trimEnd()}
3
+ </file>${g}`}catch{return e}})}export{S as a};
@@ -0,0 +1,2 @@
1
+ import{spawnSync as s}from"node:child_process";import{accessSync as d,constants as b}from"node:fs";import{join as l}from"node:path";function c(r){try{return d(r,b.X_OK),!0}catch{return!1}}function w(r=process.platform,e=process.env.PATH??""){let n=e.split(":").filter(Boolean),o=t=>n.map(i=>l(i,t)).find(c);if(r==="linux"){let t=o("bwrap");return t&&s(t,["--ro-bind","/","/","--","true"],{stdio:"ignore",timeout:3e3}).status===0?"bubblewrap":void 0}if(r==="darwin")return o("sandbox-exec")?"seatbelt":void 0}function a(r,e){return r==="bubblewrap"?["bwrap","--die-with-parent","--new-session","--ro-bind","/","/","--dev","/dev","--proc","/proc","--tmpfs","/tmp","--bind",e.cwd,e.cwd,"--bind",e.agentDir,e.agentDir,"--chdir",e.cwd,"--",...e.argv]:["sandbox-exec","-p",["(version 1)","(deny default)","(allow process*)","(allow signal)","(allow sysctl-read)","(allow mach-lookup)","(allow network*)","(allow file-read*)",`(allow file-write* (subpath "${e.cwd}") (subpath "${e.agentDir}") (subpath "/tmp") (subpath "/private/tmp") (subpath "/private/var/folders"))`,""].join(`
2
+ `),...e.argv]}function x(r){return r==="bubblewrap"?"sandbox: bubblewrap \u2014 project writable, rest of the filesystem read-only":"sandbox: seatbelt \u2014 project writable, rest of the filesystem read-only"}function g(r,e){let n=s(a(r,e)[0],a(r,e).slice(1),{stdio:"inherit",env:{...process.env,HOWTOFIX_SANDBOXED:"1"}});return n.error?(console.error(`sandbox: could not start ${r}: ${n.error.message}`),1):n.status??1}export{w as a,a as b,x as c,g as d};