howtocode 0.7.65 → 0.7.67
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{chunk-CCISJKGS.js → chunk-3H2ECHBB.js} +1 -1
- package/dist/chunk-465RG5I6.js +10 -0
- package/dist/{chunk-DL7CRCHC.js → chunk-7NGP36QA.js} +1 -1
- package/dist/{chunk-DVI5E6EG.js → chunk-7OR4XA5B.js} +1 -1
- package/dist/{chunk-2OPR6ZSG.js → chunk-ED624AEE.js} +1 -1
- package/dist/{chunk-YLA3E4Q3.js → chunk-EMU362DM.js} +1 -1
- package/dist/{chunk-JC3DY2HZ.js → chunk-GEAWXEQG.js} +1 -1
- package/dist/{chunk-XKD6WADL.js → chunk-IYKHXISM.js} +1 -1
- package/dist/{chunk-NQNMEZEO.js → chunk-K4ONXZQE.js} +1 -1
- package/dist/{chunk-BZJSYOTO.js → chunk-L4XKIPIG.js} +1 -1
- package/dist/{chunk-CYOHDIPQ.js → chunk-NFVGCV56.js} +1 -1
- package/dist/{chunk-ELM3OMOE.js → chunk-NPD6557W.js} +1 -1
- package/dist/{chunk-3NMNRSD2.js → chunk-OFKOOEKB.js} +2 -2
- package/dist/{chunk-IYOBVZ6H.js → chunk-R5LA6DL2.js} +1 -1
- package/dist/{chunk-RU6VPYMJ.js → chunk-VDUY46W2.js} +1 -1
- package/dist/{chunk-AS4FUFAN.js → chunk-W2U7D5UF.js} +1 -1
- package/dist/{chunk-SBVQNV6A.js → chunk-XAIUZHIW.js} +1 -1
- package/dist/{chunk-4AQGNUVQ.js → chunk-XSUEEWKS.js} +1 -1
- package/dist/{chunk-3YSNDQVR.js → chunk-YFJKKWIX.js} +1 -1
- package/dist/main-app.js +102 -0
- package/dist/main.js +8 -101
- package/package.json +1 -1
- package/dist/chunk-ABDZXFNM.js +0 -10
package/dist/main-app.js
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import{b as G,d as J,e as K}from"./chunk-EZNNALD3.js";import"./chunk-7LA2AMZB.js";import{c as H}from"./chunk-PH72JBBL.js";import{a as B,b as F}from"./chunk-MCAAX33K.js";import{H as $,P as D}from"./chunk-465RG5I6.js";import"./chunk-UTYFLLSM.js";import{j as L}from"./chunk-MVVEYKN6.js";import{a as r,b as k}from"./chunk-XSUEEWKS.js";import"./chunk-WOT6VMZA.js";import{existsSync as Oe,mkdirSync as Te,readdirSync as Z,statSync as Ae,writeFileSync as je}from"node:fs";import{join as j}from"node:path";var V={rpc:!0,acp:!0},q={off:!0,minimal:!0,low:!0,medium:!0,high:!0,xhigh:!0,max:!0},z={suggest:!0,"auto-edit":!0,"full-auto":!0},X={text:!0,json:!0,"stream-json":!0};function Re(l){let e=Number(l);if(!Number.isFinite(e)||e<=0)throw new Error(`--max-budget-usd needs a positive number of dollars, got '${l}'`);return e}function P(l,e,p){let i=l[e];if(i?.includes("="))return i.slice(i.indexOf("=")+1);let c=l[e+1];if(!c||c.startsWith("-"))throw new Error(`${p} needs a value`);return l.splice(e+1,1),c}function Y(l){let e={print:!1,continueSession:!1,noSession:!1,help:!1,version:!1,update:!1,checkUpdate:!1,outputFormat:"text",dangerouslySkipPermissions:!1,sandbox:!1,prompt:""},p=[],i=[...l];i[0]==="resume"&&i[1]&&!i[1].startsWith("-")&&(e.resumeId=i[1],i.splice(0,2));for(let c=0;c<i.length;c++){let o=i[c]??"";if(o==="--"){p.push(...i.slice(c+1));break}if(o==="-h"||o==="--help")e.help=!0;else if(o==="-v"||o==="--version")e.version=!0;else if(o==="-p"||o==="--print")e.print=!0;else if(o==="-c"||o==="--continue")e.continueSession=!0;else if(o==="--no-session")e.noSession=!0;else if(o==="--sandbox")e.sandbox=!0;else if(o==="--update")e.update=!0;else if(o==="--check-update")e.checkUpdate=!0;else if(o==="-r"||o==="--resume")e.continueSession=!0;else if(o==="--session"||o.startsWith("--session="))e.sessionPath=P(i,c,"--session");else if(o==="-m"||o==="--model"||o.startsWith("--model="))e.model=P(i,c,"--model");else if(o==="--thinking"||o.startsWith("--thinking="))e.thinking=P(i,c,"--thinking");else if(o==="--approval"||o.startsWith("--approval="))e.approval=P(i,c,"--approval");else if(o==="--output-format"||o.startsWith("--output-format="))e.outputFormat=P(i,c,"--output-format");else if(o==="--max-budget-usd"||o.startsWith("--max-budget-usd="))e.maxBudgetUsd=Re(P(i,c,"--max-budget-usd"));else if(o==="--mode"||o.startsWith("--mode=")){let h=P(i,c,"--mode");if(!V[h])throw new Error(`--mode must be one of: ${Object.keys(V).join(", ")}`);e.mode=h}else if(o==="--acp")e.mode="acp";else if(o==="--dangerously-skip-permissions")e.dangerouslySkipPermissions=!0;else{if(o.startsWith("-"))throw new Error(`unknown option ${o}`);p.push(o)}}if(e.thinking&&!q[e.thinking])throw new Error(`thinking must be one of: ${Object.keys(q).join(", ")}`);if(e.approval&&!z[e.approval])throw new Error(`approval must be one of: ${Object.keys(z).join(", ")}`);if(!X[e.outputFormat])throw new Error(`output-format must be one of: ${Object.keys(X).join(", ")}`);if(e.outputFormat!=="text"&&!e.print)throw new Error(`--output-format ${e.outputFormat} is a machine contract; it needs --print`);if(e.dangerouslySkipPermissions&&!e.print)throw new Error("--dangerously-skip-permissions is for unattended runs; it needs --print. interactively, pick an approval mode instead (/approval, or --approval)");if(e.prompt=p.join(" ").trim(),e.update&&e.checkUpdate)throw new Error("--update installs; --check-update only looks. pick one");if((e.update||e.checkUpdate)&&(e.print||e.continueSession||e.sessionPath||e.prompt))throw new Error("--update and --check-update act on the installation, not a session; they take no prompt");if(e.continueSession&&e.noSession)throw new Error("--continue and --no-session cannot be combined");if(e.sessionPath&&e.noSession)throw new Error("--session and --no-session cannot be combined");if(e.sessionPath&&e.continueSession)throw new Error("--session and --continue cannot be combined");if(e.resumeId&&e.sessionPath)throw new Error("resume <id> and --session cannot be combined");if(e.resumeId&&e.continueSession)throw new Error("resume <id> and --continue cannot be combined");if(e.print&&(e.continueSession||e.sessionPath||e.resumeId))throw new Error("--print runs one prompt in a throwaway session; it cannot be combined with --continue, --session, or resume <id>");if(e.mode&&(e.print||e.prompt))throw new Error(`--mode ${e.mode} is a protocol server: prompts arrive over the protocol, not the command line`);if(e.mode&&(e.continueSession||e.sessionPath))throw new Error(`--mode ${e.mode} opens its own sessions; it cannot be combined with --continue or --session`);if(e.sessionPath&&!e.sessionPath.endsWith(".jsonl"))throw new Error(`--session expects a session file, got '${e.sessionPath}'`);return e}function E(){return`${r} ${k}
|
|
3
|
+
coding agent. layout is a workbench, not a chat log.
|
|
4
|
+
|
|
5
|
+
usage:
|
|
6
|
+
howtocode [options] [prompt]
|
|
7
|
+
howtocode -p "explain this repo"
|
|
8
|
+
howtocode resume <id> reopen one stored conversation by its id (or prefix)
|
|
9
|
+
/browser-relay install|status drive your own Chrome tabs from a session
|
|
10
|
+
howtocode acp serve the Agent Client Protocol on stdio
|
|
11
|
+
howtocode --mode rpc serve JSON-line commands on stdio
|
|
12
|
+
howtocode preset new|check|pack author a preset
|
|
13
|
+
howtocode doctor|models|sessions inspect the installation
|
|
14
|
+
howtocode sessions --search <text> find a session by what was said in it
|
|
15
|
+
howtocode sessions --export <n> print session n from the list as markdown
|
|
16
|
+
|
|
17
|
+
options:
|
|
18
|
+
-p, --print run one prompt and print the answer
|
|
19
|
+
-c, --continue resume the latest session in this folder
|
|
20
|
+
-r, --resume alias for --continue
|
|
21
|
+
--session <file> run inside a specific saved session file
|
|
22
|
+
--no-session do not write a session file
|
|
23
|
+
-m, --model <id> provider/model, or a fuzzy model id
|
|
24
|
+
--thinking <lv> off | minimal | low | medium | high | xhigh | max
|
|
25
|
+
--approval <m> suggest | auto-edit | full-auto
|
|
26
|
+
--output-format <f> text | json | stream-json
|
|
27
|
+
text for a person; json writes the final result only;
|
|
28
|
+
stream-json writes every event as it happens
|
|
29
|
+
--max-budget-usd <n> stop the run once it has spent n dollars
|
|
30
|
+
--mode <m> rpc | acp: serve a protocol on stdin/stdout, no terminal
|
|
31
|
+
--acp same as --mode acp
|
|
32
|
+
--sandbox run the whole session inside a filesystem sandbox:
|
|
33
|
+
the project is writable, the rest is read-only.
|
|
34
|
+
needs bubblewrap (Linux) or sandbox-exec (macOS)
|
|
35
|
+
--dangerously-skip-permissions
|
|
36
|
+
run everything, including commands otherwise refused.
|
|
37
|
+
unattended runs only; pairs with --print
|
|
38
|
+
--update install the newest release and exit
|
|
39
|
+
--check-update say whether a newer release exists
|
|
40
|
+
-h, --help
|
|
41
|
+
-v, --version
|
|
42
|
+
|
|
43
|
+
keys:
|
|
44
|
+
enter send
|
|
45
|
+
shift+enter new line
|
|
46
|
+
ctrl+c stop the run, or quit when idle
|
|
47
|
+
ctrl+d quit
|
|
48
|
+
ctrl+l jump to the latest line
|
|
49
|
+
ctrl+o clear the screen (history is kept)
|
|
50
|
+
ctrl+t raise the thinking level (wraps to off)
|
|
51
|
+
ctrl+shift+t lower the thinking level
|
|
52
|
+
esc clear the draft
|
|
53
|
+
ctrl+v paste from the clipboard
|
|
54
|
+
pgup / pgdn scroll the transcript a page
|
|
55
|
+
home / end jump to the top / back to the latest line
|
|
56
|
+
wheel scroll the transcript
|
|
57
|
+
|
|
58
|
+
commands:
|
|
59
|
+
/init /model /providers /thinking /approval /login /connect /logout /new
|
|
60
|
+
/resume /compact /name /stats /rtk /diff /commit /undo /rewind /review /tools /export
|
|
61
|
+
/copy /agents /goal /plan /workflow /session /help /quit /exit
|
|
62
|
+
/dcp /context /decompress /sweep
|
|
63
|
+
/update /usage /wallet /sync
|
|
64
|
+
/skills /preset /settings /trust /proxy /roblox /vault
|
|
65
|
+
/roblox shows whether RoToolbox is on and Roblox Studio's MCP server is connected.
|
|
66
|
+
RoToolbox uses Studio's own MCP server: open a place in Studio, nothing to install.
|
|
67
|
+
|
|
68
|
+
/stats shows session tokens, cost, and the prompt-cache hit rate; a high read
|
|
69
|
+
total alone hides re-billed context, so the rate is what tells you the truth.
|
|
70
|
+
/rtk compresses long tool output (logs, diffs, greps) before the model reads it.
|
|
71
|
+
Off by default: /rtk on to save tokens when skimming, /rtk off to keep every line.
|
|
72
|
+
Nothing is invented by it \u2014 it drops redundant lines and says how many it dropped,
|
|
73
|
+
and never touches a failed command or one already truncated.
|
|
74
|
+
|
|
75
|
+
/preset lists skills bundled with this build and skills from the registry, by
|
|
76
|
+
category; picking one downloads it into the project and loads it as a skill.
|
|
77
|
+
An integration preset installs disabled: its skills and MCP server stay dormant
|
|
78
|
+
until /preset enable <name>, and /preset disable <name> takes the server back
|
|
79
|
+
out of the live session. /roblox reports that state for RoToolbox in one line.
|
|
80
|
+
/skills lists what is loaded now.
|
|
81
|
+
|
|
82
|
+
/proxy <url> routes requests through a proxy, /proxy off stops, /proxy env uses
|
|
83
|
+
HTTPS_PROXY / HTTP_PROXY / ALL_PROXY; /proxy alone shows what is set.
|
|
84
|
+
|
|
85
|
+
/agents <id> <message> messages a parked agent; /agents <id> shows one.
|
|
86
|
+
|
|
87
|
+
a line starting with ! runs in the project shell.
|
|
88
|
+
|
|
89
|
+
an npm install checks for a newer release at startup and can install it itself;
|
|
90
|
+
/update does it on demand. config and sessions live in ~/.howtocode/agent.
|
|
91
|
+
/connect signs in to howtofix.id in your browser, and falls back to a pasted
|
|
92
|
+
token; /login takes another provider's key.
|
|
93
|
+
`}function Me(l,e=!1){let{message:p,hint:i}=B(l),c=i?`${p}
|
|
94
|
+
${i}`:p;if(!e)return c;let o=l instanceof Error?l.stack:void 0;return o&&o.includes(`
|
|
95
|
+
`)?`${c}
|
|
96
|
+
${o}`:c}function Q(l,e){let p=e?.debug??process.env.HOWTOCODE_DEBUG==="1",i=e?.exit??(o=>process.exit(o)),c=o=>{console.error(`${l}: ${Me(o,p)}`),i(1)};process.on("uncaughtException",c),process.on("unhandledRejection",c)}function Fe(){try{return{cwd:process.cwd()}}catch{return{error:"the current directory no longer exists (it was deleted while the shell stayed in it). cd to a directory that exists, or pass one on the command line."}}}function Ie(){process.stdout.on("error",l=>{throw l.code==="EPIPE"&&process.exit(0),l})}function Ne(){let l=j($,".welcomed");if(!Oe(l)){try{Te($,{recursive:!0}),je(l,k)}catch{return}console.error(`${r} ${k} installed. Docs: https://howtofix.id/code`),console.error("Continue the last session here with: howtocode -c")}}async function Ue(){Ie(),D();let l=performance.now(),e=Fe();if("error"in e){console.error(`${r}: ${e.error}`),process.exitCode=1;return}let p=e.cwd,i=process.env.HXF_FAKE_NODE??process.versions.node,[c,o]=i.split(".").map(s=>Number.parseInt(s,10));if(!Number.isFinite(c)||c<22||c===22&&Number.isFinite(o)&&o<19){console.error(`${r}: Node ${i} is too old. Node 22.19 or newer is required (run "node --version" to check yours), because undici needs zstd, which Node added in 22.19. Upgrade Node and run this again.`),process.exitCode=1;let s=process.argv.slice(2);if(s.some(n=>n==="-h"||n==="--help")){console.log(E());return}if(s.some(n=>n==="-v"||n==="--version")){console.log(`${r} ${k}`);return}return}let h=process.argv.slice(2);if(h[0]==="doctor"||h[0]==="models"||h[0]==="sessions"){let s=h[0];try{let n=await import("./chunk-ED624AEE.js");s==="doctor"?process.exitCode=await n.runDoctor():s==="models"?process.exitCode=n.runModels():process.exitCode=n.runSessions(h.slice(1))}catch(n){F(r,s,n),process.exitCode=1}return}if(h.some(s=>s==="-v"||s==="--version")){console.log(`${r} ${k}`);return}if(h.some(s=>s==="-h"||s==="--help")){console.log(E());return}let ee=h[0]==="acp"?["--acp",...h.slice(1)]:h,R;try{R=Y(ee)}catch(s){let n=s instanceof Error?s.message:String(s);console.error(`${r}: ${n}
|
|
97
|
+
${E()}`),process.exitCode=2;return}if(R.print&&!R.prompt){console.error(`${r}: --print needs a prompt`),process.exitCode=2;return}let{repairGatewayModels:se,ensureGatewaySettings:oe,repairModelFacts:te,syncGatewayModelsOnStart:ne,checkAccount:re,fetchGatewayPrices:ie,readProviderKey:ae}=await import("./chunk-EMU362DM.js"),{tiersFrom:ce,writeReachable:de}=await import("./chunk-XBVWQC7P.js"),{readCliCredential:le,renewCliCredentialIfNeeded:pe}=await import("./chunk-7OR4XA5B.js"),{AGENT_DIR:f,REACHABLE_CACHE_PATH:ue}=await import("./chunk-NPD6557W.js"),{readCachedPrices:me,writeCachedPrices:he}=await import("./chunk-A3LZMZ3C.js"),I=se(f);I>0&&console.error(`${r}: repaired ${I} howtocode model(s) that the gateway would have rejected`);let _,M,O=new Map,C=me(f);if(C){_=C.prices;for(let[s,n]of C.groups)O.set(s,n)}try{let s=le(f),n=s?(await pe(f,s)).credential.accessToken:ae(f,"howtocode");if(n){let[m,u]=await Promise.all([C?Promise.resolve(_??new Map):ie(n,{groups:O}),re(n)]);!C&&m.size>0&&(_=m,he(f,m,O)),u.ok&&(M=u.models)}}catch{}let N=ce(O),T=await te(f,{..._?{prices:_}:{},...N.size>0?{tiers:N}:{}});if(T.changed>0?console.error(`${r}: filled in the context window, reasoning flag and price for ${T.changed} model(s)`):T.message&&console.error(`${r}: model catalogue unavailable (${T.message}); context windows stay at their conservative defaults`),oe(f)&&console.error(`${r}: set httpIdleTimeoutMs in settings.json so a stalled provider recovers instead of hanging`),M){de(ue,M);try{let s=await ne(f,M,_);s.added>0&&console.error(`${r}: added ${s.added} model(s) this account can now reach`)}catch{}}let t=R;if(t.help){console.log(E());return}if(t.version){console.log(`${r} ${k}`);let{cliSigningKeyMatchesPanel:s,cliSigningKeyFingerprint:n}=await import("./chunk-IYKHXISM.js");s()||(console.error(`${r}: this build's CLI signing key (${n()}) does not match the key the panel verifies against, so sign-in will be refused.`),process.exitCode=1);return}if(t.sandbox&&!process.env.HOWTOCODE_SANDBOXED){let{detectSandbox:s,enterSandbox:n,describeSandbox:m}=await import("./chunk-YX2QDCVK.js"),u=s();if(!u){console.error(`${r}: --sandbox needs a working bubblewrap (Linux) or sandbox-exec (macOS). Neither could be used here \u2014 on Linux this usually means unprivileged user namespaces are disabled.`),process.exitCode=1;return}console.error(m(u)),process.exitCode=n(u,{cwd:p,agentDir:$,argv:[process.execPath,...process.argv.slice(1)]});return}let{installProxy:fe}=await import("./chunk-WKUJ7CFO.js");fe($);let{retireRobloxBridge:ge}=await import("./chunk-3H2ECHBB.js");if(ge($),t.update||t.checkUpdate){let{PACKAGE_NAME:s,checkForUpdate:n,installUpdate:m,isInstalledCopy:u}=await import("./chunk-LYLJZVZ7.js"),w=await n(k);if(!w.latest){console.error(`${r}: ${w.message}`),process.exitCode=t.update?1:0;return}if(console.log(w.message),t.checkUpdate||!w.available)return;if(!u()){console.error(`${r}: this copy was not installed by npm, so npm cannot replace it. install it with: npm install -g ${s}`),process.exitCode=1;return}let v=await m({version:w.latest});console.log(v.message),v.ok||(process.exitCode=1);return}let U=process.argv.slice(2);if(U[0]==="preset"){let{runPresetCommand:s}=await import("./chunk-W2U7D5UF.js");process.exitCode=s(U.slice(1));return}let{expandFileReferences:we}=await import("./chunk-TSEKPGK4.js"),{isApprovalMode:be,setApprovalMode:ke,setDangerousBypass:xe,isDangerousBypass:ye}=await import("./chunk-7LAMZWB5.js"),{openSession:ve}=await import("./chunk-7NGP36QA.js");ke(t.approval&&be(t.approval)?t.approval:"full-auto");let{readWorkbenchSettings:Se}=await import("./chunk-V3R4FYTJ.js");if((t.dangerouslySkipPermissions||Se(f).skipPermissions)&&xe(!0),ye()&&console.error(`${r}: permission checks are OFF \u2014 critical commands (filesystem wipes, fork bombs, host shutdown) and the repeated-call guard are NOT enforced for this run. Turn it off with /settings, or by removing skipPermissions from settings.json.`),t.mode){let{serveProtocol:s}=await import("./chunk-R5LA6DL2.js");await s(t.mode,{cwd:p,model:t.model,thinking:t.thinking});return}let W=s=>ve({cwd:p,model:t.model,thinking:t.thinking,continueSession:s.continueSession??!1,noSession:s.noSession??!1,sessionPath:s.sessionPath,interactive:!t.print});if(t.resumeId&&!t.sessionPath){let s=j($,"sessions"),n=[];try{for(let m of Z(s))for(let u of Z(j(s,m))){if(!u.endsWith(".jsonl")||!u.includes(t.resumeId))continue;let w=j(s,m,u);try{n.push({path:w,mtime:Ae(w).mtimeMs})}catch{}}}catch{}if(n=n.sort((m,u)=>u.mtime-m.mtime),n.length===0){console.error(`${r}: no stored session matches '${t.resumeId}'. Run 'howtocode -c' to continue the latest one in this folder.`),process.exitCode=1;return}n.length>1&&console.error(`${r}: '${t.resumeId}' matches ${n.length} sessions; using the newest (${n[0].path}).`),t.sessionPath=n[0].path}let a=await W({continueSession:t.continueSession,sessionPath:t.sessionPath,noSession:t.noSession||t.print});if(t.print&&a.note&&console.error(a.note),t.maxBudgetUsd!==void 0&&!a.priced){console.error(`${r}: ${K(a.modelLabel,f)}`),await a.dispose(),process.exitCode=2;return}if(t.print){let s=t.prompt.trimStart();if(s.startsWith("/")){let b=s.slice(1).split(/\s+/)[0]??"",{skillInvocation:A}=await import("./chunk-L4XKIPIG.js"),S=a.session.resourceLoader.getSkills().skills.map(g=>g.name);if(!(A(s,S)!==void 0)){let{slashCommands:g}=await import("./chunk-OFKOOEKB.js");if(g(a.session).some(d=>d.name===b)){console.error(`${r}: /${b} runs in the TUI only \u2014 --print sends prompts straight to the model. Run \`howtocode\` without --print for interactive commands.`),await a.dispose(),process.exitCode=2;return}}}let n=t.outputFormat==="stream-json",m=t.outputFormat==="json",u=n||m;if(n){let b={type:"system",subtype:"init",cwd:p,session_id:a.session.sessionId,model:a.modelLabel,output_format:t.outputFormat,max_budget_usd:t.maxBudgetUsd??null,dangerously_skip_permissions:t.dangerouslySkipPermissions,cli_version:k};process.stdout.write(`${JSON.stringify(b)}
|
|
98
|
+
`)}let w,v,Ee=()=>{if(t.maxBudgetUsd===void 0||v!==void 0)return;let b=a.session.getSessionStats().cost;b>t.maxBudgetUsd&&(v={spent:b},a.session.abort())};try{let b,A=H();if(w=a.session.subscribe(d=>{if(n){let y=A.line(d);y!==void 0&&process.stdout.write(y)}if(d.type==="turn_end"&&d.message?.role==="assistant"){let y=d.message;y.stopReason==="error"||y.stopReason==="aborted"||y.errorMessage?b={stopReason:y.stopReason??"error",errorMessage:y.errorMessage}:b=void 0}Ee()}),await a.session.prompt(we(t.prompt,p)),n){let d=A.finish();d!==void 0&&process.stdout.write(d)}let S=L(a.session.getLastAssistantText()??"");if(v){if(console.error(`${r}: ${J(v.spent,t.maxBudgetUsd)}`),u){let d=a.session.getSessionStats();process.stdout.write(`${JSON.stringify({type:"result",subtype:"error_max_budget_usd",is_error:!0,result:S,session_id:a.session.sessionId,duration_ms:Math.round(performance.now()-l),num_turns:d.assistantMessages,total_cost_usd:d.cost,usage:{input_tokens:d.tokens.input,output_tokens:d.tokens.output,cache_read_input_tokens:d.tokens.cacheRead,cache_creation_input_tokens:d.tokens.cacheWrite}})}
|
|
99
|
+
`)}process.exitCode=1;return}let x=a.session.state.messages.at(-1),g=b??(x?.role==="assistant"&&(x.stopReason==="error"||x.stopReason==="aborted"||x.errorMessage)?{stopReason:x.stopReason??"error",errorMessage:x.errorMessage}:void 0);if(u){let d=a.session.getSessionStats();process.stdout.write(`${JSON.stringify({type:"result",subtype:g?g.stopReason==="aborted"?"error_aborted":"error_during_execution":"success",is_error:g!==void 0,result:S,session_id:a.session.sessionId,duration_ms:Math.round(performance.now()-l),num_turns:d.assistantMessages,total_cost_usd:d.cost,usage:{input_tokens:d.tokens.input,output_tokens:d.tokens.output,cache_read_input_tokens:d.tokens.cacheRead,cache_creation_input_tokens:d.tokens.cacheWrite},stop_reason:g?.stopReason??(x?.role==="assistant"?x.stopReason:void 0)})}
|
|
100
|
+
`)}else process.stdout.write(S.endsWith(`
|
|
101
|
+
`)?S:`${S}
|
|
102
|
+
`);if(g&&(process.exitCode=1,g.errorMessage)){console.error(`${r}: ${g.errorMessage}`);let d=G(g.errorMessage);d!==void 0&&console.error(`${r}: ${d}`)}}finally{w?.(),await a.dispose()}return}if(!process.stdin.isTTY||!process.stdout.isTTY){console.error(`${r}: interactive mode needs a terminal. use --print for pipes.`),await a.dispose(),process.exitCode=2;return}Ne();let{runWorkbench:$e}=await import("./chunk-OFKOOEKB.js"),{autoUpdateEnabled:Pe,isInstalledCopy:_e}=await import("./chunk-LYLJZVZ7.js"),Ce=_e()&&Pe(`${f}/settings.json`);await $e({cwd:p,modelLabel:a.modelLabel,session:a.session,dispose:()=>a.dispose(),setCompressToolOutput:a.setCompressToolOutput,initialPrompt:t.prompt||void 0,note:a.note,maxBudgetUsd:t.maxBudgetUsd,update:Ce?{current:k,install:!0}:void 0,reopen:W})}Q(r);Ue().catch(l=>{F(r,void 0,l),process.exitCode=1});
|
package/dist/main.js
CHANGED
|
@@ -1,102 +1,9 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
howtocode acp serve the Agent Client Protocol on stdio
|
|
11
|
-
howtocode --mode rpc serve JSON-line commands on stdio
|
|
12
|
-
howtocode preset new|check|pack author a preset
|
|
13
|
-
howtocode doctor|models|sessions inspect the installation
|
|
14
|
-
howtocode sessions --search <text> find a session by what was said in it
|
|
15
|
-
howtocode sessions --export <n> print session n from the list as markdown
|
|
16
|
-
|
|
17
|
-
options:
|
|
18
|
-
-p, --print run one prompt and print the answer
|
|
19
|
-
-c, --continue resume the latest session in this folder
|
|
20
|
-
-r, --resume alias for --continue
|
|
21
|
-
--session <file> run inside a specific saved session file
|
|
22
|
-
--no-session do not write a session file
|
|
23
|
-
-m, --model <id> provider/model, or a fuzzy model id
|
|
24
|
-
--thinking <lv> off | minimal | low | medium | high | xhigh | max
|
|
25
|
-
--approval <m> suggest | auto-edit | full-auto
|
|
26
|
-
--output-format <f> text | json | stream-json
|
|
27
|
-
text for a person; json writes the final result only;
|
|
28
|
-
stream-json writes every event as it happens
|
|
29
|
-
--max-budget-usd <n> stop the run once it has spent n dollars
|
|
30
|
-
--mode <m> rpc | acp: serve a protocol on stdin/stdout, no terminal
|
|
31
|
-
--acp same as --mode acp
|
|
32
|
-
--sandbox run the whole session inside a filesystem sandbox:
|
|
33
|
-
the project is writable, the rest is read-only.
|
|
34
|
-
needs bubblewrap (Linux) or sandbox-exec (macOS)
|
|
35
|
-
--dangerously-skip-permissions
|
|
36
|
-
run everything, including commands otherwise refused.
|
|
37
|
-
unattended runs only; pairs with --print
|
|
38
|
-
--update install the newest release and exit
|
|
39
|
-
--check-update say whether a newer release exists
|
|
40
|
-
-h, --help
|
|
41
|
-
-v, --version
|
|
42
|
-
|
|
43
|
-
keys:
|
|
44
|
-
enter send
|
|
45
|
-
shift+enter new line
|
|
46
|
-
ctrl+c stop the run, or quit when idle
|
|
47
|
-
ctrl+d quit
|
|
48
|
-
ctrl+l jump to the latest line
|
|
49
|
-
ctrl+o clear the screen (history is kept)
|
|
50
|
-
ctrl+t raise the thinking level (wraps to off)
|
|
51
|
-
ctrl+shift+t lower the thinking level
|
|
52
|
-
esc clear the draft
|
|
53
|
-
ctrl+v paste from the clipboard
|
|
54
|
-
pgup / pgdn scroll the transcript a page
|
|
55
|
-
home / end jump to the top / back to the latest line
|
|
56
|
-
wheel scroll the transcript
|
|
57
|
-
|
|
58
|
-
commands:
|
|
59
|
-
/init /model /providers /thinking /approval /login /connect /logout /new
|
|
60
|
-
/resume /compact /name /stats /rtk /diff /commit /undo /rewind /review /tools /export
|
|
61
|
-
/copy /agents /goal /plan /workflow /session /help /quit /exit
|
|
62
|
-
/dcp /context /decompress /sweep
|
|
63
|
-
/update /usage /wallet /sync
|
|
64
|
-
/skills /preset /settings /trust /proxy /roblox /vault
|
|
65
|
-
/roblox shows whether RoToolbox is on and Roblox Studio's MCP server is connected.
|
|
66
|
-
RoToolbox uses Studio's own MCP server: open a place in Studio, nothing to install.
|
|
67
|
-
|
|
68
|
-
/stats shows session tokens, cost, and the prompt-cache hit rate; a high read
|
|
69
|
-
total alone hides re-billed context, so the rate is what tells you the truth.
|
|
70
|
-
/rtk compresses long tool output (logs, diffs, greps) before the model reads it.
|
|
71
|
-
Off by default: /rtk on to save tokens when skimming, /rtk off to keep every line.
|
|
72
|
-
Nothing is invented by it \u2014 it drops redundant lines and says how many it dropped,
|
|
73
|
-
and never touches a failed command or one already truncated.
|
|
74
|
-
|
|
75
|
-
/preset lists skills bundled with this build and skills from the registry, by
|
|
76
|
-
category; picking one downloads it into the project and loads it as a skill.
|
|
77
|
-
An integration preset installs disabled: its skills and MCP server stay dormant
|
|
78
|
-
until /preset enable <name>, and /preset disable <name> takes the server back
|
|
79
|
-
out of the live session. /roblox reports that state for RoToolbox in one line.
|
|
80
|
-
/skills lists what is loaded now.
|
|
81
|
-
|
|
82
|
-
/proxy <url> routes requests through a proxy, /proxy off stops, /proxy env uses
|
|
83
|
-
HTTPS_PROXY / HTTP_PROXY / ALL_PROXY; /proxy alone shows what is set.
|
|
84
|
-
|
|
85
|
-
/agents <id> <message> messages a parked agent; /agents <id> shows one.
|
|
86
|
-
|
|
87
|
-
a line starting with ! runs in the project shell.
|
|
88
|
-
|
|
89
|
-
an npm install checks for a newer release at startup and can install it itself;
|
|
90
|
-
/update does it on demand. config and sessions live in ~/.howtocode/agent.
|
|
91
|
-
/connect signs in to howtofix.id in your browser, and falls back to a pasted
|
|
92
|
-
token; /login takes another provider's key.
|
|
93
|
-
`}function Me(l,e=!1){let{message:p,hint:i}=B(l),c=i?`${p}
|
|
94
|
-
${i}`:p;if(!e)return c;let o=l instanceof Error?l.stack:void 0;return o&&o.includes(`
|
|
95
|
-
`)?`${c}
|
|
96
|
-
${o}`:c}function Q(l,e){let p=e?.debug??process.env.HOWTOCODE_DEBUG==="1",i=e?.exit??(o=>process.exit(o)),c=o=>{console.error(`${l}: ${Me(o,p)}`),i(1)};process.on("uncaughtException",c),process.on("unhandledRejection",c)}function Fe(){try{return{cwd:process.cwd()}}catch{return{error:"the current directory no longer exists (it was deleted while the shell stayed in it). cd to a directory that exists, or pass one on the command line."}}}function Ie(){process.stdout.on("error",l=>{throw l.code==="EPIPE"&&process.exit(0),l})}function Ne(){let l=j($,".welcomed");if(!Oe(l)){try{Te($,{recursive:!0}),je(l,k)}catch{return}console.error(`${r} ${k} installed. Docs: https://howtofix.id/code`),console.error("Continue the last session here with: howtocode -c")}}async function Ue(){Ie(),D();let l=performance.now(),e=Fe();if("error"in e){console.error(`${r}: ${e.error}`),process.exitCode=1;return}let p=e.cwd,i=process.env.HXF_FAKE_NODE??process.versions.node,[c,o]=i.split(".").map(s=>Number.parseInt(s,10));if(!Number.isFinite(c)||c<22||c===22&&Number.isFinite(o)&&o<19){console.error(`${r}: Node ${i} is too old. Node 22.19 or newer is required (run "node --version" to check yours), because undici needs zstd, which Node added in 22.19. Upgrade Node and run this again.`),process.exitCode=1;let s=process.argv.slice(2);if(s.some(n=>n==="-h"||n==="--help")){console.log(E());return}if(s.some(n=>n==="-v"||n==="--version")){console.log(`${r} ${k}`);return}return}let h=process.argv.slice(2);if(h[0]==="doctor"||h[0]==="models"||h[0]==="sessions"){let s=h[0];try{let n=await import("./chunk-2OPR6ZSG.js");s==="doctor"?process.exitCode=await n.runDoctor():s==="models"?process.exitCode=n.runModels():process.exitCode=n.runSessions(h.slice(1))}catch(n){F(r,s,n),process.exitCode=1}return}if(h.some(s=>s==="-v"||s==="--version")){console.log(`${r} ${k}`);return}if(h.some(s=>s==="-h"||s==="--help")){console.log(E());return}let ee=h[0]==="acp"?["--acp",...h.slice(1)]:h,R;try{R=Y(ee)}catch(s){let n=s instanceof Error?s.message:String(s);console.error(`${r}: ${n}
|
|
97
|
-
${E()}`),process.exitCode=2;return}if(R.print&&!R.prompt){console.error(`${r}: --print needs a prompt`),process.exitCode=2;return}let{repairGatewayModels:se,ensureGatewaySettings:oe,repairModelFacts:te,syncGatewayModelsOnStart:ne,checkAccount:re,fetchGatewayPrices:ie,readProviderKey:ae}=await import("./chunk-YLA3E4Q3.js"),{tiersFrom:ce,writeReachable:de}=await import("./chunk-XBVWQC7P.js"),{readCliCredential:le,renewCliCredentialIfNeeded:pe}=await import("./chunk-DVI5E6EG.js"),{AGENT_DIR:f,REACHABLE_CACHE_PATH:ue}=await import("./chunk-ELM3OMOE.js"),{readCachedPrices:me,writeCachedPrices:he}=await import("./chunk-A3LZMZ3C.js"),I=se(f);I>0&&console.error(`${r}: repaired ${I} howtocode model(s) that the gateway would have rejected`);let _,M,O=new Map,C=me(f);if(C){_=C.prices;for(let[s,n]of C.groups)O.set(s,n)}try{let s=le(f),n=s?(await pe(f,s)).credential.accessToken:ae(f,"howtocode");if(n){let[m,u]=await Promise.all([C?Promise.resolve(_??new Map):ie(n,{groups:O}),re(n)]);!C&&m.size>0&&(_=m,he(f,m,O)),u.ok&&(M=u.models)}}catch{}let N=ce(O),T=await te(f,{..._?{prices:_}:{},...N.size>0?{tiers:N}:{}});if(T.changed>0?console.error(`${r}: filled in the context window, reasoning flag and price for ${T.changed} model(s)`):T.message&&console.error(`${r}: model catalogue unavailable (${T.message}); context windows stay at their conservative defaults`),oe(f)&&console.error(`${r}: set httpIdleTimeoutMs in settings.json so a stalled provider recovers instead of hanging`),M){de(ue,M);try{let s=await ne(f,M,_);s.added>0&&console.error(`${r}: added ${s.added} model(s) this account can now reach`)}catch{}}let t=R;if(t.help){console.log(E());return}if(t.version){console.log(`${r} ${k}`);let{cliSigningKeyMatchesPanel:s,cliSigningKeyFingerprint:n}=await import("./chunk-XKD6WADL.js");s()||(console.error(`${r}: this build's CLI signing key (${n()}) does not match the key the panel verifies against, so sign-in will be refused.`),process.exitCode=1);return}if(t.sandbox&&!process.env.HOWTOCODE_SANDBOXED){let{detectSandbox:s,enterSandbox:n,describeSandbox:m}=await import("./chunk-YX2QDCVK.js"),u=s();if(!u){console.error(`${r}: --sandbox needs a working bubblewrap (Linux) or sandbox-exec (macOS). Neither could be used here \u2014 on Linux this usually means unprivileged user namespaces are disabled.`),process.exitCode=1;return}console.error(m(u)),process.exitCode=n(u,{cwd:p,agentDir:$,argv:[process.execPath,...process.argv.slice(1)]});return}let{installProxy:fe}=await import("./chunk-WKUJ7CFO.js");fe($);let{retireRobloxBridge:ge}=await import("./chunk-CCISJKGS.js");if(ge($),t.update||t.checkUpdate){let{PACKAGE_NAME:s,checkForUpdate:n,installUpdate:m,isInstalledCopy:u}=await import("./chunk-LYLJZVZ7.js"),w=await n(k);if(!w.latest){console.error(`${r}: ${w.message}`),process.exitCode=t.update?1:0;return}if(console.log(w.message),t.checkUpdate||!w.available)return;if(!u()){console.error(`${r}: this copy was not installed by npm, so npm cannot replace it. install it with: npm install -g ${s}`),process.exitCode=1;return}let v=await m({version:w.latest});console.log(v.message),v.ok||(process.exitCode=1);return}let U=process.argv.slice(2);if(U[0]==="preset"){let{runPresetCommand:s}=await import("./chunk-AS4FUFAN.js");process.exitCode=s(U.slice(1));return}let{expandFileReferences:we}=await import("./chunk-TSEKPGK4.js"),{isApprovalMode:be,setApprovalMode:ke,setDangerousBypass:xe,isDangerousBypass:ye}=await import("./chunk-7LAMZWB5.js"),{openSession:ve}=await import("./chunk-DL7CRCHC.js");ke(t.approval&&be(t.approval)?t.approval:"full-auto");let{readWorkbenchSettings:Se}=await import("./chunk-V3R4FYTJ.js");if((t.dangerouslySkipPermissions||Se(f).skipPermissions)&&xe(!0),ye()&&console.error(`${r}: permission checks are OFF \u2014 critical commands (filesystem wipes, fork bombs, host shutdown) and the repeated-call guard are NOT enforced for this run. Turn it off with /settings, or by removing skipPermissions from settings.json.`),t.mode){let{serveProtocol:s}=await import("./chunk-IYOBVZ6H.js");await s(t.mode,{cwd:p,model:t.model,thinking:t.thinking});return}let W=s=>ve({cwd:p,model:t.model,thinking:t.thinking,continueSession:s.continueSession??!1,noSession:s.noSession??!1,sessionPath:s.sessionPath,interactive:!t.print});if(t.resumeId&&!t.sessionPath){let s=j($,"sessions"),n=[];try{for(let m of Z(s))for(let u of Z(j(s,m))){if(!u.endsWith(".jsonl")||!u.includes(t.resumeId))continue;let w=j(s,m,u);try{n.push({path:w,mtime:Ae(w).mtimeMs})}catch{}}}catch{}if(n=n.sort((m,u)=>u.mtime-m.mtime),n.length===0){console.error(`${r}: no stored session matches '${t.resumeId}'. Run 'howtocode -c' to continue the latest one in this folder.`),process.exitCode=1;return}n.length>1&&console.error(`${r}: '${t.resumeId}' matches ${n.length} sessions; using the newest (${n[0].path}).`),t.sessionPath=n[0].path}let a=await W({continueSession:t.continueSession,sessionPath:t.sessionPath,noSession:t.noSession||t.print});if(t.print&&a.note&&console.error(a.note),t.maxBudgetUsd!==void 0&&!a.priced){console.error(`${r}: ${K(a.modelLabel,f)}`),await a.dispose(),process.exitCode=2;return}if(t.print){let s=t.prompt.trimStart();if(s.startsWith("/")){let b=s.slice(1).split(/\s+/)[0]??"",{skillInvocation:A}=await import("./chunk-BZJSYOTO.js"),S=a.session.resourceLoader.getSkills().skills.map(g=>g.name);if(!(A(s,S)!==void 0)){let{slashCommands:g}=await import("./chunk-3NMNRSD2.js");if(g(a.session).some(d=>d.name===b)){console.error(`${r}: /${b} runs in the TUI only \u2014 --print sends prompts straight to the model. Run \`howtocode\` without --print for interactive commands.`),await a.dispose(),process.exitCode=2;return}}}let n=t.outputFormat==="stream-json",m=t.outputFormat==="json",u=n||m;if(n){let b={type:"system",subtype:"init",cwd:p,session_id:a.session.sessionId,model:a.modelLabel,output_format:t.outputFormat,max_budget_usd:t.maxBudgetUsd??null,dangerously_skip_permissions:t.dangerouslySkipPermissions,cli_version:k};process.stdout.write(`${JSON.stringify(b)}
|
|
98
|
-
`)}let w,v,Ee=()=>{if(t.maxBudgetUsd===void 0||v!==void 0)return;let b=a.session.getSessionStats().cost;b>t.maxBudgetUsd&&(v={spent:b},a.session.abort())};try{let b,A=H();if(w=a.session.subscribe(d=>{if(n){let y=A.line(d);y!==void 0&&process.stdout.write(y)}if(d.type==="turn_end"&&d.message?.role==="assistant"){let y=d.message;y.stopReason==="error"||y.stopReason==="aborted"||y.errorMessage?b={stopReason:y.stopReason??"error",errorMessage:y.errorMessage}:b=void 0}Ee()}),await a.session.prompt(we(t.prompt,p)),n){let d=A.finish();d!==void 0&&process.stdout.write(d)}let S=L(a.session.getLastAssistantText()??"");if(v){if(console.error(`${r}: ${J(v.spent,t.maxBudgetUsd)}`),u){let d=a.session.getSessionStats();process.stdout.write(`${JSON.stringify({type:"result",subtype:"error_max_budget_usd",is_error:!0,result:S,session_id:a.session.sessionId,duration_ms:Math.round(performance.now()-l),num_turns:d.assistantMessages,total_cost_usd:d.cost,usage:{input_tokens:d.tokens.input,output_tokens:d.tokens.output,cache_read_input_tokens:d.tokens.cacheRead,cache_creation_input_tokens:d.tokens.cacheWrite}})}
|
|
99
|
-
`)}process.exitCode=1;return}let x=a.session.state.messages.at(-1),g=b??(x?.role==="assistant"&&(x.stopReason==="error"||x.stopReason==="aborted"||x.errorMessage)?{stopReason:x.stopReason??"error",errorMessage:x.errorMessage}:void 0);if(u){let d=a.session.getSessionStats();process.stdout.write(`${JSON.stringify({type:"result",subtype:g?g.stopReason==="aborted"?"error_aborted":"error_during_execution":"success",is_error:g!==void 0,result:S,session_id:a.session.sessionId,duration_ms:Math.round(performance.now()-l),num_turns:d.assistantMessages,total_cost_usd:d.cost,usage:{input_tokens:d.tokens.input,output_tokens:d.tokens.output,cache_read_input_tokens:d.tokens.cacheRead,cache_creation_input_tokens:d.tokens.cacheWrite},stop_reason:g?.stopReason??(x?.role==="assistant"?x.stopReason:void 0)})}
|
|
100
|
-
`)}else process.stdout.write(S.endsWith(`
|
|
101
|
-
`)?S:`${S}
|
|
102
|
-
`);if(g&&(process.exitCode=1,g.errorMessage)){console.error(`${r}: ${g.errorMessage}`);let d=G(g.errorMessage);d!==void 0&&console.error(`${r}: ${d}`)}}finally{w?.(),await a.dispose()}return}if(!process.stdin.isTTY||!process.stdout.isTTY){console.error(`${r}: interactive mode needs a terminal. use --print for pipes.`),await a.dispose(),process.exitCode=2;return}Ne();let{runWorkbench:$e}=await import("./chunk-3NMNRSD2.js"),{autoUpdateEnabled:Pe,isInstalledCopy:_e}=await import("./chunk-LYLJZVZ7.js"),Ce=_e()&&Pe(`${f}/settings.json`);await $e({cwd:p,modelLabel:a.modelLabel,session:a.session,dispose:()=>a.dispose(),setCompressToolOutput:a.setCompressToolOutput,initialPrompt:t.prompt||void 0,note:a.note,maxBudgetUsd:t.maxBudgetUsd,update:Ce?{current:k,install:!0}:void 0,reopen:W})}Q(r);Ue().catch(l=>{F(r,void 0,l),process.exitCode=1});
|
|
2
|
+
const argv = process.argv.slice(2);
|
|
3
|
+
if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v") && !process.env.HXF_FAKE_NODE) {
|
|
4
|
+
const { readFileSync } = await import("node:fs");
|
|
5
|
+
const pkg = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8"));
|
|
6
|
+
console.log("HowToCode " + pkg.version);
|
|
7
|
+
} else {
|
|
8
|
+
await import("./main-app.js");
|
|
9
|
+
}
|
package/package.json
CHANGED
package/dist/chunk-ABDZXFNM.js
DELETED
|
@@ -1,10 +0,0 @@
|
|
|
1
|
-
import{a as A}from"./chunk-UTYFLLSM.js";import{existsSync as E,readFileSync as D}from"node:fs";import{dirname as _e,join as fe}from"node:path";import{fileURLToPath as Le}from"node:url";import{cpSync as z,existsSync as T,readdirSync as Ie,readFileSync as Re,renameSync as He,statSync as N,writeFileSync as je}from"node:fs";import{homedir as ce}from"node:os";import{join as g,resolve as Ne}from"node:path";import{cpSync as me,existsSync as S,mkdirSync as O,mkdtempSync as L,readdirSync as I,readFileSync as H,renameSync as ye,rmSync as b,statSync as x,writeFileSync as M}from"node:fs";import{tmpdir as q}from"node:os";import{dirname as V,isAbsolute as he,join as u,relative as be,resolve as C}from"node:path";import{fileURLToPath as Se}from"node:url";import{execFileSync as ke}from"node:child_process";import{createHash as X}from"node:crypto";import{gunzipSync as de}from"node:zlib";var k=512;function P(e,r,t){let s=e.subarray(r,r+t),n=s.indexOf(0);return s.subarray(0,n===-1?s.length:n).toString("utf8").trim()}function G(e,r,t){let s=P(e,r,t);if(!s)return 0;let n=Number.parseInt(s,8);return Number.isFinite(n)?n:0}function ge(e){let r={},t=0;for(;t<e.length;){let s=e.indexOf(32,t);if(s===-1)break;let n=Number.parseInt(e.toString("utf8",t,s),10);if(!Number.isFinite(n)||n<=0)break;let i=e.toString("utf8",s+1,t+n-1),o=i.indexOf("=");o>0&&(r[i.slice(0,o)]=i.slice(o+1)),t+=n}return r}function W(e){let r=de(e),t=[],s=0,n,i={};for(;s+k<=r.length;){let o=r.subarray(s,s+k);if(o.every(pe=>pe===0))break;let a=P(o,0,100),c=P(o,345,155),l=G(o,124,12),f=G(o,100,8),m=String.fromCharCode(o[156]??48),w=P(o,157,100),v=l>0?r.subarray(s+k,s+k+l):Buffer.alloc(0);if(s+=k+Math.ceil(l/k)*k,m==="x"||m==="g"){i=ge(v);continue}if(m==="L"){n=v.toString("utf8").replace(/\0.*$/s,"").trim();continue}let y=i.path??n??(c?`${c}/${a}`:a);n=void 0,i={};let p=y.indexOf("/");if(p===-1||(y=y.slice(p+1),y=y.replace(/\/+$/,""),!y))continue;let h=m==="5"?"directory":m==="2"?"symlink":m==="0"||m==="\0"||m===""?"file":"other";t.push({path:y,kind:h,size:l,mode:f&511,...h==="file"?{data:Buffer.from(v)}:{},...h==="symlink"?{link:w}:{}})}return t}function K(e){if(!e||e.startsWith("/")||e.startsWith("\\")||/^[a-zA-Z]:/.test(e))return!1;let r=e.replace(/\/+$/,"");return r?r.split("/").every(s=>s!==""&&s!=="."&&s!==".."):!1}function U(e,r){let t=`${r.replace(/\/+$/,"")}/`,s=[];for(let n of e){if(!n.path.startsWith(t))continue;let i=n.path.slice(t.length);i&&s.push({...n,path:i})}return s}function ve(){return u(d,"presets")}function Q(e){return u(e,".howtocode","presets")}function Y(e){return S(u(e,".disabled"))}function ee(){return u(V(Se(import.meta.url)),"presets")}function j(e){return[Q(e),ve()]}var re=/^[a-z0-9][a-z0-9-]*$/,xe=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/;function _(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function $(e,r){let t=be(C(e),C(r));return t!==""&&!t.startsWith("..")&&!he(t)}function te(e,r){let t=[];if(!_(r))return["preset.json must be a JSON object"];let s=l=>{let f=r[l];return typeof f!="string"||f.trim()===""?(t.push(`${l} must be a non-empty string`),""):f.trim()},n=s("name");s("title"),s("description"),s("category");let i=s("version");n&&!re.test(n)&&t.push(`name "${n}" must be lowercase letters, digits and dashes`),i&&!xe.test(i)&&t.push(`version "${i}" is not a version like 1.0.0`);let o=r.skills;if(!Array.isArray(o)||o.length===0)t.push("skills must be a non-empty array of directory names");else for(let l of o){if(typeof l!="string"||l.trim()===""){t.push("every skills entry must be a non-empty string");continue}let f=u(e,"skills",l.trim());if(!$(u(e,"skills"),f)){t.push(`skill "${l}" escapes the preset directory`);continue}S(u(f,"SKILL.md"))||t.push(`skill "${l}" has no SKILL.md at ${u("skills",l)}`)}let a=r.prompt;if(a!==void 0)if(typeof a!="string"||a.trim()==="")t.push("prompt must be a non-empty string when present");else{let l=u(e,a.trim());$(e,l)?S(l)||t.push(`prompt file "${a}" does not exist`):t.push(`prompt "${a}" escapes the preset directory`)}let c=r.tags;return c!==void 0&&!Array.isArray(c)&&t.push("tags must be an array when present"),t.push(...Z(r.mcp)),t}function ne(e){let r=u(e,"preset.json");if(!S(r))return{problems:[`no preset.json in ${e}`]};let t;try{t=JSON.parse(H(r,"utf8"))}catch(o){return{problems:[`preset.json is not valid JSON: ${o instanceof Error?o.message:String(o)}`]}}let s=te(e,t);if(s.length>0)return{problems:s};let n=t,i=Array.isArray(n.tags)?n.tags.filter(o=>typeof o=="string"):[];return{problems:[],manifest:{name:String(n.name),title:String(n.title),description:String(n.description),category:String(n.category),tags:i,version:String(n.version),skills:n.skills.map(o=>String(o)),prompt:typeof n.prompt=="string"?n.prompt:void 0,mcp:n.mcp&&typeof n.mcp=="object"&&!Array.isArray(n.mcp)?n.mcp:void 0,integrates:typeof n.integrates=="string"&&n.integrates.trim()!==""?n.integrates.trim():void 0}}}function F(e){return e.filter(r=>{try{return x(r).isDirectory()}catch{return!1}})}function R(e,r){let t=[],s=[],n=(o,a)=>{if(!S(u(o,"preset.json")))return;let{manifest:c,problems:l}=ne(o);c?t.push({manifest:c,dir:o,source:r}):s.push(`${a}: ${l.join("; ")}`)},i;try{i=I(e).sort()}catch{return{entries:t,problems:s}}for(let o of i){if(o.startsWith("."))continue;let a=u(e,o);try{if(!x(a).isDirectory())continue}catch{continue}if(S(u(a,"preset.json"))){n(a,o);continue}let c;try{c=I(a).sort()}catch{continue}for(let l of c){if(l.startsWith("."))continue;let f=u(a,l);try{if(!x(f).isDirectory())continue}catch{continue}n(f,u(o,l))}}return{entries:t,problems:s}}function Qe(e){let r=R(ee(),"bundled"),t=[...r.entries],s=[...r.problems],n=new Map(t.map(i=>[i.manifest.name,i]));for(let i of F(j(e))){let o=R(i,"installed");s.push(...o.problems);for(let a of o.entries){let c=n.get(a.manifest.name);if(c){let l=t.indexOf(c);l>=0&&(t[l]=a),n.set(a.manifest.name,a)}else t.push(a),n.set(a.manifest.name,a)}}return{entries:t,problems:s}}function Ye(e){return[...new Set(e.map(r=>r.manifest.category))].sort()}function er(e,r){return e.filter(t=>t.manifest.category===r).sort((t,s)=>t.manifest.title.localeCompare(s.manifest.title))}function se(e){let r=[];for(let t of F(j(e))){let{entries:s}=R(t,"installed");for(let n of s)Y(n.dir)||r.push(u(n.dir,"skills"))}return r}function rr(e){let r=[];for(let t of F(j(e))){let{entries:s}=R(t,"installed");for(let n of s){if(Y(n.dir))continue;let i=n.manifest.prompt;if(!i)continue;let o=u(n.dir,i);if($(n.dir,o))try{let a=H(o,"utf8").trim();a&&r.push({name:n.manifest.name,title:n.manifest.title,text:a})}catch{}}}return r}function tr(e,r){let t=0;for(let s of r.skills)try{t+=x(u(e,"skills",s,"SKILL.md")).size}catch{}return t}function we(e){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,e)}var $e=".install.lock";function Ee(e,r){O(e,{recursive:!0});let t=u(e,$e),s=Date.now()+6e4;for(;;)try{M(t,`${process.pid}
|
|
2
|
-
`,{flag:"wx"});break}catch(n){if(n.code!=="EEXIST")throw n;let i=!1;try{i=Date.now()-x(t).mtimeMs>12e4}catch{continue}if(i){b(t,{force:!0});continue}if(Date.now()>s)throw new Error(`another install is holding ${t}; remove it if no install is running`);we(100)}try{for(let n of I(e))n.startsWith(".staging-")&&b(u(e,n),{recursive:!0,force:!0});return r()}finally{b(t,{force:!0})}}function ie(e,r,t){let s=u(r,t.name);return Ee(r,()=>{O(r,{recursive:!0});let n=L(u(r,".staging-"));try{me(e,n,{recursive:!0}),b(s,{recursive:!0,force:!0}),ye(n,s)}catch(i){throw b(n,{recursive:!0,force:!0}),i}return s})}function oe(e,r){if(!S(e))return{ok:!1,problems:[`no such directory: ${e}`]};let{manifest:t,problems:s}=ne(e);if(!t)return{ok:!1,problems:s};let n=ie(e,r,t);return{ok:!0,name:t.name,target:n,problems:[]}}function Ae(e,r){let t=L(u(q(),"howtocode-preset-"));try{return ke("git",["clone","--depth","1","--quiet",e,t],{stdio:"pipe"}),oe(t,r)}catch(s){return{ok:!1,problems:[`git clone failed: ${(s instanceof Error?s.message:String(s)).split(`
|
|
3
|
-
`)[0]}`]}}finally{b(t,{recursive:!0,force:!0})}}function nr(e,r){return/^(https?:\/\/|git@|git:\/\/)/.test(e)?Ae(e,r):oe(C(e),r)}function sr(e,r){let t=[],s=[];if(!re.test(e))return{removed:t,problems:[`"${e}" is not a preset name`]};for(let n of j(r)){let i=u(n,e);if(S(i)){if(!$(n,i)){s.push(`refusing to remove ${i}: outside ${n}`);continue}b(i,{recursive:!0,force:!0}),t.push(i)}}return t.length===0&&s.push(`"${e}" is not installed`),{removed:t,problems:s}}function ir(e){return Q(e)}function Pe(e){let r=[],t=(i,o)=>{for(let a of I(i,{withFileTypes:!0}).sort((c,l)=>c.name.localeCompare(l.name))){let c=u(i,a.name),l=o?`${o}/${a.name}`:a.name;a.isSymbolicLink()||(a.isDirectory()?t(c,l):a.isFile()&&r.push([l,X("sha256").update(H(c)).digest("hex")]))}};t(e,"");let s=0;for(let[i]of r)s+=x(u(e,i)).size;let n=r.map(([i,o])=>`${o} ${i}`).join(`
|
|
4
|
-
`);return{digest:X("sha256").update(n).digest("hex").slice(0,16),fileCount:r.length,bytes:s}}function or(){let e=u(ee(),"hub.json");try{let r=H(e,"utf8"),t=JSON.parse(r),s=_(t)&&Array.isArray(t.entries)?t.entries:[],n=[];for(let i of s)_(i)&&(typeof i.name!="string"||typeof i.repo!="string"||typeof i.sha!="string"||typeof i.path!="string"||typeof i.category!="string"||n.push({name:i.name,title:typeof i.title=="string"?i.title:i.name,description:typeof i.description=="string"?i.description:"",category:i.category,skill:typeof i.skill=="string"?i.skill:i.name,path:i.path,repo:i.repo,sha:i.sha,license:typeof i.license=="string"?i.license:"unknown",stars:typeof i.stars=="number"?i.stars:0,sizeKb:typeof i.sizeKb=="number"?i.sizeKb:0,...typeof i.digest=="string"?{digest:i.digest}:{},...typeof i.fileCount=="number"?{fileCount:i.fileCount}:{},...typeof i.modelInvocable=="boolean"?{modelInvocable:i.modelInvocable}:{}}));return{entries:n,problems:[]}}catch(r){return r?.code==="ENOENT"?{entries:[],problems:[]}:{entries:[],problems:[`registry unreadable: ${r instanceof Error?r.message:String(r)}`]}}}function ar(e){return[...new Set(e.map(r=>r.category))].sort()}function cr(e,r){return e.filter(t=>t.category===r).sort((t,s)=>s.stars-t.stars||t.name.localeCompare(s.name))}function lr(e,r){return e.find(t=>t.name===r)}function Oe(e){return`https://codeload.github.com/${e.repo}/tar.gz/${e.sha}`}async function ur(e,r,t=12e4){let s=L(u(q(),"howtocode-hub-"));try{let n=await fetch(Oe(e),{signal:AbortSignal.timeout(t),redirect:"follow"});if(!n.ok)return{ok:!1,problems:[`${e.repo}: HTTP ${n.status} from codeload`]};let i=Buffer.from(await n.arrayBuffer()),o=W(i),a=U(o,e.path).filter(p=>p.kind==="file"||p.kind==="directory");if(!a.some(p=>p.path==="SKILL.md"))return{ok:!1,problems:[`${e.repo}@${e.sha.slice(0,7)} has no ${e.path}/SKILL.md`]};let c=u(s,"preset",e.name),l=u(c,"skills",e.skill),f=0;for(let p of a){if(!K(p.path))return{ok:!1,problems:[`refusing unsafe path in archive: ${p.path}`]};let h=u(l,p.path);if(!$(l,h))return{ok:!1,problems:[`refusing path outside the skill: ${p.path}`]};if(p.kind==="directory"){O(h,{recursive:!0});continue}O(V(h),{recursive:!0}),M(h,p.data??Buffer.alloc(0)),f+=1}let m={name:e.name,title:e.title,description:e.description,category:e.category,version:"1.0.0",skills:[e.skill],source:`${e.repo}@${e.sha}`,license:e.license};if(M(u(c,"preset.json"),`${JSON.stringify(m,null,2)}
|
|
5
|
-
`),!e.digest)return{ok:!1,problems:[`${e.repo}@${e.sha.slice(0,7)}: registry entry has no digest`,"refusing to install; content cannot be verified against what was reviewed"]};let w=Pe(l);if(w.digest!==e.digest)return{ok:!1,problems:[`${e.repo}@${e.sha.slice(0,7)}: content changed under a pinned commit`,`expected ${e.digest} (${e.fileCount??"?"} files), got ${w.digest} (${w.fileCount} files)`,"refusing to install; the registry needs regenerating"]};let v=te(c,m);if(v.length>0)return{ok:!1,problems:v};let y=ie(c,r,m);return{ok:!0,name:e.name,target:y,problems:[],skill:e.skill,modelInvocable:e.modelInvocable}}catch(n){return{ok:!1,problems:[`download failed: ${(n instanceof Error?n.message:String(n)).split(`
|
|
6
|
-
`)[0]}`]}}finally{b(s,{recursive:!0,force:!0})}}function Te(){let e=(process.env.HOWTOCODE_HOME??process.env.HOWTOFIX_HOME??process.env.HOME??"").trim();return Ne(e||ce())}function le(e,r){for(let t of Ie(e)){let s=g(e,t),n=g(r,t);if(!T(n)){try{z(s,n,{recursive:!0,force:!1})}catch{}continue}let i=!1;try{i=N(s).isDirectory()}catch{continue}if(i&&N(n).isDirectory()){le(s,n);continue}try{let o=N(n).size,a=N(s).size;!i&&o<=2&&a>o&&z(s,n,{force:!0})}catch{}}}function De(e){let r=g(ce(),".howtofix");if(T(r)){if(!T(e))try{He(r,e);return}catch{try{z(r,e,{recursive:!0});return}catch{return}}le(r,e),Me(e)}}function Me(e){ae(g(e,"agent","models.json"),"providers"),ae(g(e,"agent","auth.json"),void 0)}function ae(e,r){if(!T(e))return;let t;try{t=JSON.parse(Re(e,"utf8"))}catch{return}let s=r?t[r]:t;if(!s||typeof s!="object")return;let n=!1;for(let[i,o]of Object.entries(s)){let a=i==="howtofix"?"howtocode":i==="howtofix-free"?"howtocode-free":i;a===i||s[a]!==void 0||(s[a]=o,delete s[i],n=!0)}if(n)try{je(e,`${JSON.stringify(t,null,2)}
|
|
7
|
-
`)}catch{}}var d=process.env.HOWTOCODE_CODING_AGENT_DIR?.trim()||process.env.HOWTOFIX_CODING_AGENT_DIR?.trim()||(()=>{let e=g(Te(),".howtocode");return De(e),g(e,"agent")})(),yr=g(d,"skills");function Ce(e){return g(e,".howtocode","skills")}function hr(e){let r=[Ce(e)];return r.push(...se(e)),r}var br=g(d,"agents"),Sr=g(d,"usage-cache.json"),kr=g(d,"reachable-models.json"),vr=g(d,"workflows");function xr(){process.env.HXF_CODING_AGENT_DIR=d}var wr=g(d,"images");function J(e=d){return fe(e,"mcp.json")}function Z(e){let r=[];if(e===void 0)return r;if(typeof e!="object"||e===null||Array.isArray(e))return["mcp must be an object of server names"];for(let[t,s]of Object.entries(e)){if(!/^[A-Za-z0-9_-]+$/.test(t)){r.push(`mcp server "${t}" must use only letters, digits, _ and -`);continue}if(typeof s!="object"||s===null||Array.isArray(s)){r.push(`mcp server "${t}" must be an object`);continue}let n=s,i=typeof n.command=="string"&&n.command.trim()!=="",o=typeof n.url=="string"&&n.url.trim()!=="";!i&&!o&&r.push(`mcp server "${t}" needs either a command or a url`),n.args!==void 0&&!Array.isArray(n.args)&&r.push(`mcp server "${t}": args must be an array`);for(let a of["env","headers"]){let c=n[a];if(c!==void 0){if(typeof c!="object"||c===null||Array.isArray(c)){r.push(`mcp server "${t}": ${a} must be an object of strings`);continue}for(let[l,f]of Object.entries(c))typeof f!="string"&&r.push(`mcp server "${t}": ${a}.${l} must be a string`)}}}return r}function B(e){if(!E(e))return{mcpServers:{}};try{let r=JSON.parse(D(e,"utf8"));if(!r||typeof r!="object"||Array.isArray(r))return{mcpServers:{}};let t=r.mcpServers;return!t||typeof t!="object"||Array.isArray(t)?{mcpServers:{}}:{mcpServers:t}}catch{return{mcpServers:{}}}}function Rr(e,r=d){let t=Object.keys(e);if(t.length===0)return{added:[],skipped:[],problems:[]};let s=J(r),n=[];if(E(s))try{JSON.parse(D(s,"utf8"))}catch{return{added:[],skipped:[],problems:[`${s} is not valid JSON; leaving it alone`]}}let i=B(s),o=[],a=[];for(let c of t){if(i.mcpServers[c]!==void 0){a.push(c);continue}i.mcpServers[c]=e[c],o.push(c)}if(o.length>0)try{A(s,`${JSON.stringify(i,null,2)}
|
|
8
|
-
`)}catch(c){return{added:[],skipped:a,problems:[`could not write ${s}: ${c instanceof Error?c.message:String(c)}`]}}return{added:o,skipped:a,problems:n}}function Hr(e,r=new Set,t=d){let s=J(t),n=[];if(e.length===0||!E(s))return{removed:[],kept:[],problems:n};let i=B(s),o=[],a=[];for(let c of e)if(i.mcpServers[c]!==void 0){if(r.has(c)){a.push(c);continue}delete i.mcpServers[c],o.push(c)}if(o.length>0)try{A(s,`${JSON.stringify(i,null,2)}
|
|
9
|
-
`)}catch(c){return{removed:[],kept:a,problems:[`could not write ${s}: ${c instanceof Error?c.message:String(c)}`]}}return{removed:o,kept:a,problems:n}}var ue="@netrodev/howtocode-roblox-bridge";function jr(e=d){let r=J(e);if(!E(r))return[];try{JSON.parse(D(r,"utf8"))}catch{return[]}let t=B(r),s=Object.keys(t.mcpServers).filter(n=>{let i=t.mcpServers[n];return[i.command,...Array.isArray(i.args)?i.args:[]].map(a=>String(a??"")).some(a=>a===ue||a.startsWith(`${ue}@`))});if(s.length===0)return[];for(let n of s)delete t.mcpServers[n];try{A(r,`${JSON.stringify(t,null,2)}
|
|
10
|
-
`)}catch{return[]}return s}function Nr(e){if(typeof e.url=="string"&&e.url)return`http: ${e.url}`;let r=typeof e.command=="string"?e.command:"",t=Array.isArray(e.args)?e.args.filter(s=>typeof s=="string"):[];return`stdio: ${[r,...t].join(" ")}`.trim()}function Fe(){return fe(_e(Le(import.meta.url)),"presets","mcp-hub.json")}function Tr(e=Fe()){let r=[];if(!E(e))return{entries:[],problems:[`no MCP catalogue at ${e}`]};let t;try{t=JSON.parse(D(e,"utf8"))}catch(i){return{entries:[],problems:[`${e} is not valid JSON: ${i instanceof Error?i.message:String(i)}`]}}let s=t?.entries;if(!Array.isArray(s))return{entries:[],problems:[`${e} has no entries array`]};let n=[];for(let i of s){if(typeof i!="object"||i===null||Array.isArray(i))continue;let o=i,a=typeof o.name=="string"?o.name.trim():"";if(!a){r.push("an entry has no name");continue}if(!/^[A-Za-z0-9_-]+$/.test(a)){r.push(`"${a}" is not a usable server name`);continue}let c=typeof o.command=="string"&&o.command.trim()!=="",l=typeof o.url=="string"&&o.url.trim()!=="";if(!c&&!l){r.push(`"${a}" has neither a command nor a url`);continue}n.push({name:a,title:typeof o.title=="string"?o.title:a,description:typeof o.description=="string"?o.description:"",category:typeof o.category=="string"?o.category:"other",preset:typeof o.preset=="string"?o.preset:void 0,command:typeof o.command=="string"?o.command:void 0,url:typeof o.url=="string"?o.url:void 0,args:Array.isArray(o.args)?o.args.filter(f=>typeof f=="string"):void 0,env:o.env&&typeof o.env=="object"&&!Array.isArray(o.env)?o.env:void 0,needs:Array.isArray(o.needs)?o.needs.filter(f=>typeof f=="string"):void 0,docs:typeof o.docs=="string"?o.docs:void 0})}return{entries:n,problems:r}}function Dr(e){return[...new Set(e.map(r=>r.category))].sort()}function Mr(e,r){return e.filter(t=>t.category===r).sort((t,s)=>t.title.localeCompare(s.title))}function Cr(e,r){return e.find(t=>t.name===r)}function _r(e){let r={};return e.command&&(r.command=e.command),e.url&&(r.url=e.url),e.args&&e.args.length>0&&(r.args=[...e.args]),e.env&&Object.keys(e.env).length>0&&(r.env={...e.env}),e.description&&(r.description=e.description),r}function Lr(e,r=process.env){return(e.needs??[]).filter(t=>!r[t])}export{J as a,Z as b,Rr as c,Hr as d,ue as e,jr as f,Nr as g,Fe as h,Tr as i,Dr as j,Mr as k,Cr as l,_r as m,Lr as n,Y as o,ee as p,te as q,ne as r,Qe as s,Ye as t,er as u,se as v,rr as w,tr as x,oe as y,nr as z,sr as A,ir as B,or as C,ar as D,cr as E,lr as F,ur as G,d as H,yr as I,Ce as J,hr as K,br as L,Sr as M,kr as N,vr as O,xr as P,wr as Q};
|