howtocode 0.0.0-stage → 0.7.57
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/LICENSE +21 -0
- package/README.md +248 -2
- package/dist/chunk-27TRKD65.js +2 -0
- package/dist/chunk-3FYCFLNK.js +1 -0
- package/dist/chunk-3YOYZOXG.js +2 -0
- package/dist/chunk-3YSNDQVR.js +5 -0
- package/dist/chunk-43YCQFSH.js +1 -0
- package/dist/chunk-5X3PQ36J.js +2 -0
- package/dist/chunk-7LA2AMZB.js +1 -0
- package/dist/chunk-A3LZMZ3C.js +2 -0
- package/dist/chunk-ABDZXFNM.js +10 -0
- package/dist/chunk-ACBAN4MH.js +197 -0
- package/dist/chunk-AS4FUFAN.js +8 -0
- package/dist/chunk-BV6J5Q4T.js +1 -0
- package/dist/chunk-BZJSYOTO.js +1 -0
- package/dist/chunk-CCISJKGS.js +1 -0
- package/dist/chunk-DCFM67MM.js +140 -0
- package/dist/chunk-ELHK7EH4.js +1 -0
- package/dist/chunk-ELM3OMOE.js +1 -0
- package/dist/chunk-EZNNALD3.js +1 -0
- package/dist/chunk-FLP47RIR.js +5 -0
- package/dist/chunk-LYLJZVZ7.js +1 -0
- package/dist/chunk-MBVAG3VC.js +6 -0
- package/dist/chunk-MCAAX33K.js +2 -0
- package/dist/chunk-MCDEIIEN.js +1 -0
- package/dist/chunk-MVVEYKN6.js +6 -0
- package/dist/chunk-ORJ2QZBG.js +3 -0
- package/dist/chunk-PH72JBBL.js +4 -0
- package/dist/chunk-PVFHAKN6.js +1 -0
- package/dist/chunk-QBHBECIB.js +47 -0
- package/dist/chunk-QEPPIFSI.js +6 -0
- package/dist/chunk-QOYTPACU.js +3 -0
- package/dist/chunk-SDO33XPR.js +4 -0
- package/dist/chunk-TOV557ET.js +12 -0
- package/dist/chunk-TSEKPGK4.js +1 -0
- package/dist/chunk-TUXY64DT.js +2 -0
- package/dist/chunk-U3GZBLTM.js +2 -0
- package/dist/chunk-UTYFLLSM.js +1 -0
- package/dist/chunk-V3R4FYTJ.js +1 -0
- package/dist/chunk-VUQVLOAD.js +1 -0
- package/dist/chunk-WKUJ7CFO.js +1 -0
- package/dist/chunk-WOT6VMZA.js +1 -0
- package/dist/chunk-XBVWQC7P.js +1 -0
- package/dist/chunk-YN3H6RHD.js +2 -0
- package/dist/chunk-YNMLRZJK.js +2 -0
- package/dist/chunk-YX2QDCVK.js +1 -0
- package/dist/main.js +102 -0
- package/dist/presets/backend/api/preset.json +17 -0
- package/dist/presets/backend/api/prompt.md +9 -0
- package/dist/presets/backend/api/skills/api-contract/SKILL.md +35 -0
- package/dist/presets/data/sql/preset.json +17 -0
- package/dist/presets/data/sql/prompt.md +9 -0
- package/dist/presets/data/sql/skills/query-hygiene/SKILL.md +48 -0
- package/dist/presets/devops/containers/preset.json +17 -0
- package/dist/presets/devops/containers/prompt.md +9 -0
- package/dist/presets/devops/containers/skills/image-discipline/SKILL.md +59 -0
- package/dist/presets/frontend/web-ui/preset.json +17 -0
- package/dist/presets/frontend/web-ui/prompt.md +11 -0
- package/dist/presets/frontend/web-ui/skills/responsive-check/SKILL.md +46 -0
- package/dist/presets/gamedev/rotoolbox/preset.json +31 -0
- package/dist/presets/gamedev/rotoolbox/prompt.md +34 -0
- package/dist/presets/gamedev/rotoolbox/skills/rotoolbox/SKILL.md +129 -0
- package/dist/presets/hub.json +14582 -0
- package/dist/presets/lang/typescript/preset.json +16 -0
- package/dist/presets/lang/typescript/prompt.md +5 -0
- package/dist/presets/lang/typescript/skills/ts-strict/SKILL.md +48 -0
- package/dist/presets/mcp/filesystem/preset.json +27 -0
- package/dist/presets/mcp/filesystem/prompt.md +8 -0
- package/dist/presets/mcp/filesystem/skills/mcp-files/SKILL.md +27 -0
- package/dist/presets/mcp/memory/preset.json +25 -0
- package/dist/presets/mcp/memory/skills/mcp-memory/SKILL.md +31 -0
- package/dist/presets/mcp/rea/preset.json +28 -0
- package/dist/presets/mcp/rea/prompt.md +5 -0
- package/dist/presets/mcp/rea/skills/mcp-rea/SKILL.md +6 -0
- package/dist/presets/mcp/remotion/preset.json +27 -0
- package/dist/presets/mcp/remotion/prompt.md +7 -0
- package/dist/presets/mcp/remotion/skills/mcp-remotion/SKILL.md +6 -0
- package/dist/presets/mcp-hub.json +157 -0
- package/dist/presets/mobile/app/preset.json +17 -0
- package/dist/presets/mobile/app/prompt.md +7 -0
- package/dist/presets/mobile/app/skills/touch-targets/SKILL.md +47 -0
- package/dist/presets/quality/antislop/preset.json +25 -0
- package/dist/presets/quality/antislop/prompt.md +16 -0
- package/dist/presets/quality/antislop/skills/antislop/SKILL.md +595 -0
- package/dist/presets/quality/antislop/skills/antislop/references/gate.md +84 -0
- package/dist/presets/quality/antislop/skills/antislop-code/SKILL.md +128 -0
- package/dist/presets/quality/antislop/skills/antislop-copywriting/SKILL.md +413 -0
- package/dist/presets/quality/antislop/skills/antislop-human/SKILL.md +147 -0
- package/dist/presets/quality/antislop/skills/antislop-human/contrast-check.py +165 -0
- package/dist/presets/quality/antislop/skills/antislop-layoutmobile/SKILL.md +170 -0
- package/dist/presets/quality/antislop/skills/antislop-ui/SKILL.md +313 -0
- package/dist/presets/quality/antislop/skills/antislop-ui/references/motion.md +34 -0
- package/dist/presets/quality/antislop/skills/antislop-ui/references/states.md +49 -0
- package/package.json +34 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
Copyright (c) 2026 HowToFix. All rights reserved.
|
|
2
|
+
|
|
3
|
+
PROPRIETARY AND CONFIDENTIAL
|
|
4
|
+
|
|
5
|
+
This software and its source code are the property of HowToFix. No licence,
|
|
6
|
+
express or implied, is granted to use, copy, modify, merge, publish, distribute,
|
|
7
|
+
sublicense, or sell this software, in whole or in part, except as expressly
|
|
8
|
+
permitted in writing by the copyright holder.
|
|
9
|
+
|
|
10
|
+
Installing this package grants you the right to run it for its intended purpose.
|
|
11
|
+
It does not grant any right to its source code, and it does not permit
|
|
12
|
+
redistribution, modification, or use in another product.
|
|
13
|
+
|
|
14
|
+
The software is provided "as is", without warranty of any kind, express or
|
|
15
|
+
implied, including but not limited to the warranties of merchantability, fitness
|
|
16
|
+
for a particular purpose and noninfringement. In no event shall the authors or
|
|
17
|
+
copyright holders be liable for any claim, damages or other liability, whether in
|
|
18
|
+
an action of contract, tort or otherwise, arising from, out of or in connection
|
|
19
|
+
with the software or the use or other dealings in the software.
|
|
20
|
+
|
|
21
|
+
For licensing enquiries: https://howtofix.id
|
package/README.md
CHANGED
|
@@ -1,3 +1,249 @@
|
|
|
1
|
-
#
|
|
1
|
+
# HowToCode-CLI
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
A terminal coding agent. Workbench layout: scrolling feed, input dock, one HUD line.
|
|
4
|
+
|
|
5
|
+
```
|
|
6
|
+
howtocode # open the workbench
|
|
7
|
+
howtocode "fix the failing test in src/auth"
|
|
8
|
+
howtocode -p "explain this repo" | less
|
|
9
|
+
howtocode -c # continue the last session in this folder
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
## Install
|
|
13
|
+
|
|
14
|
+
Node **22.19 or newer** is required (`node --version`).
|
|
15
|
+
|
|
16
|
+
```sh
|
|
17
|
+
npm install -g howtocode
|
|
18
|
+
howtocode --version
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
That is the only install path. The package is the artifact: `npm install -g
|
|
22
|
+
howtocode@<version>` pins an exact release, and `howtocode update` checks the
|
|
23
|
+
same registry for a newer one.
|
|
24
|
+
|
|
25
|
+
If `howtocode` is not on your `PATH` afterwards, your npm prefix is not on it:
|
|
26
|
+
|
|
27
|
+
```sh
|
|
28
|
+
npm config get prefix # e.g. /usr/local
|
|
29
|
+
export PATH="$(npm config get prefix)/bin:$PATH"
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
## Connect your howtofix.id account
|
|
33
|
+
|
|
34
|
+
One account is all you need; every model on the gateway is billed to it. This is
|
|
35
|
+
the whole setup:
|
|
36
|
+
|
|
37
|
+
**1. Create the account** — open <https://howtofix.id> and sign up. Sign in with
|
|
38
|
+
Google works (a `@gmail.com` address).
|
|
39
|
+
|
|
40
|
+
**2. Create a token** — open <https://howtofix.id/console/token> and make one. It
|
|
41
|
+
starts with `sk-`. Treat it like a password: it is the credential this CLI uses,
|
|
42
|
+
and it is the only thing you have to copy.
|
|
43
|
+
|
|
44
|
+
**3. Connect the CLI** — run `howtocode`, then:
|
|
45
|
+
|
|
46
|
+
```
|
|
47
|
+
/connect
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
It opens the token page for you and asks you to paste the token. Or skip the
|
|
51
|
+
prompt by passing it directly:
|
|
52
|
+
|
|
53
|
+
```sh
|
|
54
|
+
howtocode
|
|
55
|
+
/connect sk-your-token-here
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
The token is **verified against the gateway before it is stored**, and the model
|
|
59
|
+
list is pulled in at the same time, so `/model` shows everything your account can
|
|
60
|
+
reach. Nothing is written until the gateway accepts the token.
|
|
61
|
+
|
|
62
|
+
**4. Pick a model and go.**
|
|
63
|
+
|
|
64
|
+
```
|
|
65
|
+
/model
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
Choose one, then just describe what you want:
|
|
69
|
+
|
|
70
|
+
```
|
|
71
|
+
fix the failing test in src/auth
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
### If you have a free-tier token
|
|
75
|
+
|
|
76
|
+
The free tier is a separate provider id. `/connect` verifies against the paid
|
|
77
|
+
account first and the free one second, so the same command works for both — the
|
|
78
|
+
models simply land under `howtocode-free` instead. `/providers` shows which one
|
|
79
|
+
your token is attached to.
|
|
80
|
+
|
|
81
|
+
### Updating the token later
|
|
82
|
+
|
|
83
|
+
Run `/connect` again with the new token. It replaces the stored one and re-syncs
|
|
84
|
+
the models; models you configured by hand are never overwritten.
|
|
85
|
+
|
|
86
|
+
### Removing it
|
|
87
|
+
|
|
88
|
+
`/logout` removes the stored key. The account itself is unaffected.
|
|
89
|
+
|
|
90
|
+
### Signing in without copying a token
|
|
91
|
+
|
|
92
|
+
`/login` starts a sign-in in your browser instead: the CLI shows a link, you open
|
|
93
|
+
it, approve, and the key lands in the CLI on its own. It is the same key you
|
|
94
|
+
would have pasted, created for you.
|
|
95
|
+
|
|
96
|
+
Two things are worth knowing about how that flow is protected, because they are
|
|
97
|
+
what make it safe to approve a link:
|
|
98
|
+
|
|
99
|
+
- **The CLI proves it is the CLI.** Every request that starts a sign-in is signed
|
|
100
|
+
with a key that only the published bundle carries, so the panel can tell a real
|
|
101
|
+
CLI from a script that merely sends its name. A build whose key does not match
|
|
102
|
+
says so on `--version`.
|
|
103
|
+
- **The link is not the credential.** The approval code travels in the URL, so it
|
|
104
|
+
is treated as semi-public. The key is only handed over to a request that also
|
|
105
|
+
presents a second, secret value that never leaves the CLI process. If someone
|
|
106
|
+
else sees your approval link, they cannot collect a key with it.
|
|
107
|
+
|
|
108
|
+
The approval page names the machine that asked, so you can check it is yours
|
|
109
|
+
before you click.
|
|
110
|
+
|
|
111
|
+
While the CLI waits for you to approve, it polls the panel. That poll has its own
|
|
112
|
+
rate-limit budget, sized for a whole sign-in, so taking your time is fine. If the
|
|
113
|
+
panel ever does throttle a poll, the CLI waits as long as it asks and keeps
|
|
114
|
+
polling rather than giving up on a sign-in you are in the middle of.
|
|
115
|
+
|
|
116
|
+
## Daily credit
|
|
117
|
+
|
|
118
|
+
Each account can claim one daily credit, and the CLI claims it for you: start
|
|
119
|
+
`howtocode` and the claim is made before the first turn. Nothing to press, and
|
|
120
|
+
nothing to remember.
|
|
121
|
+
|
|
122
|
+
- **One per account per day**, counted by the server's date, not your machine's.
|
|
123
|
+
A second start the same day says so rather than claiming again.
|
|
124
|
+
- **CLI only.** The web dashboard no longer offers the claim; it reports the
|
|
125
|
+
feature as unavailable. The reward belongs where you use the product, and one
|
|
126
|
+
door means one place to look when it does not arrive.
|
|
127
|
+
- **Check the state** with `/usage`: it shows whether today's credit is claimed,
|
|
128
|
+
how much it was worth, and both balances — **Credit**, spendable on every
|
|
129
|
+
model, and **Pro Credit**, which the VIP lane is billed from. The reading opens
|
|
130
|
+
as a panel over the dock, the way `/model` opens a picker, and stays until
|
|
131
|
+
`esc` or `enter` closes it.
|
|
132
|
+
- **Top up** with `/wallet`, which opens `https://howtofix.id/wallet`. Pro Credit
|
|
133
|
+
is a pay-as-you-go purchase there (Midtrans: card, QRIS, e-wallet); the terminal
|
|
134
|
+
has no equivalent because the payment needs a browser.
|
|
135
|
+
|
|
136
|
+
## What it does
|
|
137
|
+
|
|
138
|
+
- **Workbench screen** — feed of user turns, tool calls, and streamed answers; boxed input dock; HUD with model, folder, git branch, context meter, session spend, thinking level, approval mode, and activity.
|
|
139
|
+
- **Slash commands** — `/init`, `/model`, `/providers`, `/thinking`, `/approval`, `/settings`, `/login`, `/connect`, `/sync`, `/usage`, `/wallet`, `/update`, `/logout`, `/new`, `/resume`, `/compact`, `/name`, `/stats`, `/rtk`, `/diff`, `/commit`, `/undo`, `/rewind`, `/review`, `/tools`, `/skills`, `/preset`, `/trust`, `/roblox`, `/proxy`, `/browser-relay`, `/export`, `/copy`, `/agents`, `/goal`, `/plan`, `/workflow`, `/session`, `/dcp`, `/context`, `/decompress`, `/sweep`, `/vault`, `/help`, `/quit`, `/exit`. Type `/help` for the same list. (`/mcp` also works: it comes from the SDK and prints server status.)
|
|
140
|
+
- **Repo map** — the `repo_map` tool ranks every source file by how much of the tree imports it, lists the top declarations in each, and fits the result into a token budget. It is how the model finds the right file before reading anything, instead of listing directories.
|
|
141
|
+
- **Sandbox** — `--sandbox` re-executes the session under bubblewrap (Linux) or seatbelt (macOS): the project directory and the CLI's state are writable, the rest of the filesystem is read-only, and `/tmp` is a fresh tmpfs. It wraps the process, so bash, builds, tests and subagents all inherit it.
|
|
142
|
+
- **Skills** — drop a `SKILL.md` in `~/.howtocode/agent/skills/<name>/` (user) or `.howtocode/skills/<name>/` (this project). `/skills` lists them; `/skill:name` loads one into the next turn. The model also sees the list and will `read` a matching skill on its own.
|
|
143
|
+
- **Custom agents** — a markdown file in `~/.howtocode/agent/agents/<name>.md` (user) or `.howtocode/agents/<name>.md` (this project). Frontmatter sets `name`, `description`, `tools`, `model` and `effort`; the body is the subagent's standing prompt. `/agents` lists them, and a definition replaces a built-in of the same name.
|
|
144
|
+
- **Presets** — bundles of skills and prompt rules, offered by category. `/preset` opens the menu (Installed → category → preset), and every entry shows what it contains before anything is copied: `Install`, `View contents`, `Back`. Nothing installs on its own — a preset is a catalogue entry, not something that arrives with the install. The menu also lists a **community registry** of ~95 skills from other projects; those are *not* shipped in the package, they are downloaded from the source repository (at a pinned commit) when you install one. `/preset list` shows what is active, `/preset show <name>` describes either kind without installing, `/preset add <git-url|directory>` installs one from elsewhere, `/preset add-hub <name>` installs a registry entry by name, and `/preset remove <name>` takes it back out. Installing copies the files into `.howtocode/presets/<name>/` and reloads the session, so its skills and rules apply from the next message.
|
|
145
|
+
- **Shell escape** — a line starting with `!` runs in the project shell and stays in the session history.
|
|
146
|
+
- **Approval modes** — `suggest` asks before every edit and command, `auto-edit` runs edits and asks for commands, `full-auto` (default) never asks. Read-only commands (`ls`, `git log`, `grep` — including pipes like `ls | head`) never ask. A critical command is denied in every mode. Pick one with `/approval` or `--approval <mode>`. Permission checks can also be turned off entirely — for an unattended run that must never stop, or for a machine where the prompts are in the way. `/settings` opens a hub for permissions, thinking level, model, context pruning and auto-update; `/settings permissions` (or `/settings on|off`) jumps straight to the permission toggle, and `--dangerously-skip-permissions` does the same for one `--print` run. Off lifts the last two refusals — critical commands and the repeated-call guard — and says so: a banner on start, and a warning row in the HUD for as long as it is off.
|
|
147
|
+
- **Dynamic context pruning** — the agent calls a `compress` tool to fold a stale range of the conversation into a stored summary, and long tool output that a later edit superseded is replaced automatically. `/dcp` shows the switch, `/dcp stats` the totals, `/context` what the next request will carry, `/decompress <bN>` reopens a block, and `/sweep` drops the ones no ref resolves. `npm run check` covers it end to end.
|
|
148
|
+
- **Slop gate** — `npm run slop` reports naming, comment, placeholder and swallowed-error findings in the changed files, with a committed baseline so only new ones fail. `npm run slop -- --fix` applies the high-certainty ones. A pre-commit hook runs it on what you are committing; `npm run hooks:install` wires that up in a fresh clone.
|
|
149
|
+
- **Git workflow** — `/diff` shows the working tree, `/commit <message>` stages and commits, `/undo` resets the last commit keeping the changes, `/review` asks the agent to review the diff.
|
|
150
|
+
- **Goal and plan** — `/goal` sets what the session is for and keeps it visible; `/plan` designs before editing and waits for your approval.
|
|
151
|
+
- **Rewind** — `Esc Esc` opens the session tree. Pick an entry to drop the messages after it and, when the files differ, restore them too; the checkpoint is snapped before every prompt in a shadow git repo beside your own history. `↑`/`↓` move, `←`/`→` page, and the selection stops at the ends instead of wrapping. Sessions whose snapshots are older than 30 days are swept from the shadow store on startup, and the whole store of a deleted project (or one untouched for 30 days) is dropped with it, so the shadow stores do not grow for the life of the machine.
|
|
152
|
+
- **Cancel a run** — `Esc` stops the current turn (same as `Ctrl+C`) and says so in the transcript.
|
|
153
|
+
- **Background agents** — the `task` tool spawns `scout`, `architect`, `task` or `reviewer` agents that run in parallel, park when done, and can be messaged again with `/agents`. Pass `background: true` to get their ids back at once instead of waiting for the results. Set `isolation: "worktree"` on any task that writes files: the child gets its own detached checkout, so a sibling's half-finished edit cannot break its build, and it is given the ignored directories it needs (`node_modules`, `target`, `.venv` and friends) rather than a bare checkout that cannot run anything — anything too large to copy is named in the result instead of being left out silently. Write your own agents in `<project>/.hxf/agents/<name>.md` or `~/.howtocode/agent/agents/<name>.md` — frontmatter `name`, `description`, `tools`, optional `model` and `effort`, then the prompt as the body — and a child runs the parent's model unless you name another.
|
|
154
|
+
- **Tools** — `read`, `bash`, `edit`, `write`, `grep`, `find`, `ls`, plus `think` (private scratchpad), `ask` (multiple-choice question to the user), and `task` (background agents).
|
|
155
|
+
- **Web search and fetch** — `web_search` and `web_fetch` read public http(s) URLs; local, loopback, and RFC1918 addresses are refused before any request is made. Search defaults to DuckDuckGo, with an optional `BRAVE_API_KEY` upgrade.
|
|
156
|
+
- **Language server queries** — the read-only `lsp` tool asks a language server for definition, references, hover, symbols, or diagnostics. It needs the matching server on PATH (`typescript-language-server` for this repo); a missing binary comes back as a tool result that says so.
|
|
157
|
+
- **Browser relay** — the `browser` tool drives the Chrome tabs you already have open, so signed-in sessions are reused instead of logging in again in a headless browser. Run `/browser-relay install` once, load the unpacked extension from `~/.howtocode/agent/browser-relay/extension` in `chrome://extensions`, set port `9224`, and paste the token from the file the command names into the extension options. The token is never printed. `/browser-relay status` reports the connection. The relay binds `127.0.0.1` only and requires that token; set `HOWTOCODE_BROWSER_RELAY_PORT` if the default port is taken. Actions: `status`, `tabs`, `open`, `activate`, `navigate`, `evaluate`, `screenshot`, `close`. The tier is `exec` — in `suggest` mode each call asks first. The extension ships under the MIT license; its license text is installed alongside the files.
|
|
158
|
+
- **Hooks** — `hooks.json` in the config root attaches shell commands to seven lifecycle points (`PreToolUse`, `PostToolUse`, `UserPromptSubmit`, `SessionStart`, `Stop`, `PreCompact`, `SessionEnd`). A hook reads a JSON payload on stdin and decides with its exit code: `0` allows, `2` blocks with its stderr as the reason. A `PreToolUse` hook can also **rewrite** a call's arguments with `updatedInput` — validated against the tool's own schema, so a hook cannot make the agent run something it never asked for. A `PreToolUse` hook outranks the approval mode, so it holds under `full-auto` too. `async` and `once` are supported. See `docs/hooks.md`.
|
|
159
|
+
- **Sessions** — stored as JSONL under `~/.howtocode/agent/sessions/<project>/`. `-c` continues the latest; `/resume` picks any of them. On startup, transcripts idle for more than 30 days are swept across every project — the session just opened is kept whatever its age — so the store does not grow for the life of the machine (the same window rewind's snapshots use).
|
|
160
|
+
- **Project notes** — `/init` writes an `AGENTS.md` and asks the agent to fill it in; it is loaded into the system prompt on later runs.
|
|
161
|
+
- **`@file`** — `@src/main.ts` in a prompt inlines the file; paths that do not exist are left alone for the agent to read.
|
|
162
|
+
|
|
163
|
+
## Keys
|
|
164
|
+
|
|
165
|
+
| key | action |
|
|
166
|
+
| --- | --- |
|
|
167
|
+
| enter | send |
|
|
168
|
+
| shift+enter | new line |
|
|
169
|
+
| ctrl+c | stop the run, or quit when idle |
|
|
170
|
+
| ctrl+d | quit |
|
|
171
|
+
| ctrl+l | jump to the latest line |
|
|
172
|
+
| ctrl+o | clear the screen (history is kept) |
|
|
173
|
+
| ctrl+f | take the workflow panel's keys while it is pinned |
|
|
174
|
+
| esc | close picker / clear draft |
|
|
175
|
+
|
|
176
|
+
## Config
|
|
177
|
+
|
|
178
|
+
Everything lives in `~/.howtocode/agent`:
|
|
179
|
+
|
|
180
|
+
- `models.json` — providers and model catalog
|
|
181
|
+
- `auth.json` — stored credentials
|
|
182
|
+
- `settings.json` — defaults
|
|
183
|
+
- `sessions/` — transcripts
|
|
184
|
+
- `agents/` — parked background agent runs (`*.json`) and your subagent definitions (`*.md`)
|
|
185
|
+
- `workflows/` — scripts saved from a workflow run
|
|
186
|
+
|
|
187
|
+
Set `HOWTOCODE_CODING_AGENT_DIR` to use a different root. The underlying SDK is pinned to that directory, so HowToCode never reads or writes the SDK's own `~/.hxf` config dir.
|
|
188
|
+
|
|
189
|
+
If no key is stored, the CLI says so and tells you to run `/connect`.
|
|
190
|
+
|
|
191
|
+
## Flags
|
|
192
|
+
|
|
193
|
+
```
|
|
194
|
+
-p, --print run one prompt and print the answer
|
|
195
|
+
-c, --continue resume the latest session in this folder
|
|
196
|
+
--no-session do not write a session file
|
|
197
|
+
-m, --model <id> provider/model, or a fuzzy model id
|
|
198
|
+
--thinking <lv> off | minimal | low | medium | high | xhigh | max
|
|
199
|
+
--approval <m> suggest | auto-edit | full-auto
|
|
200
|
+
--output-format <f> text | json — `json` streams one event per line for
|
|
201
|
+
scripts and CI (needs --print)
|
|
202
|
+
--max-budget-usd <n> stop once this much has been spent — one run with
|
|
203
|
+
--print, the whole session interactively (needs a
|
|
204
|
+
model with declared prices)
|
|
205
|
+
--dangerously-skip-permissions
|
|
206
|
+
run anything, including critical commands and repeated
|
|
207
|
+
calls that are otherwise refused (needs --print)
|
|
208
|
+
-h, --help
|
|
209
|
+
-v, --version
|
|
210
|
+
```
|
|
211
|
+
|
|
212
|
+
### Machine-readable output
|
|
213
|
+
|
|
214
|
+
`--print --output-format json` writes one JSON object per line. The first is a
|
|
215
|
+
`system`/`init` header (model, session id, budget, bypass); the last is a
|
|
216
|
+
`result` record with `subtype` (`success`, `error_max_budget_usd`,
|
|
217
|
+
`error_aborted`, `error_during_execution`), `is_error`, `total_cost_usd` and
|
|
218
|
+
token `usage`. Everything between is the session event stream. No terminal
|
|
219
|
+
scraping, no ANSI stripping:
|
|
220
|
+
|
|
221
|
+
```sh
|
|
222
|
+
howtocode --print --output-format json -p "summarise src/" \
|
|
223
|
+
| jq -c 'select(.type == "result") | {subtype, total_cost_usd, result}'
|
|
224
|
+
```
|
|
225
|
+
|
|
226
|
+
`--max-budget-usd` aborts a run whose spend passes the cap and reports
|
|
227
|
+
`error_max_budget_usd`; it refuses to start against a model with no declared
|
|
228
|
+
prices, because a budget that can never fire only looks like a guard. The same
|
|
229
|
+
flag caps the interactive session: the workbench samples the cost `/stats`
|
|
230
|
+
shows after every event, notes `budget` once when it fires, cuts the turn that
|
|
231
|
+
crossed it and refuses the next prompt. `/new` and `/resume` do not reset the
|
|
232
|
+
total — only restarting the CLI does.
|
|
233
|
+
|
|
234
|
+
## Troubleshooting
|
|
235
|
+
|
|
236
|
+
**`Upstream API error (HTTP 400)`** — the gateway refused the request. Run
|
|
237
|
+
`/connect` again to re-sync your models; a model entry created before a gateway
|
|
238
|
+
change can carry stale compatibility settings.
|
|
239
|
+
|
|
240
|
+
**`No available channel for model <id>`** — the gateway has no live channel for
|
|
241
|
+
that model right now. Try another with `/model`; the ones under `howtocode/` that
|
|
242
|
+
answer change as channels come and go. The CLI checks this for you: it probes a
|
|
243
|
+
few other candidates and opens `/model` itself if any of them answer.
|
|
244
|
+
|
|
245
|
+
**A model returns `Server error`** — that is the gateway's channel failing, not
|
|
246
|
+
the CLI. `/model` lists what your account can reach; pick another.
|
|
247
|
+
|
|
248
|
+
**`unknown model`** — the id is not in your `models.json`. `/connect` pulls the
|
|
249
|
+
current list from the gateway.
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{a as u}from"./chunk-UTYFLLSM.js";import{existsSync as l,mkdirSync as f,readFileSync as c}from"node:fs";import{dirname as p,join as m}from"node:path";var a={skipPermissions:!1,autoUpdate:!0,rightClickPaste:"auto",welcomeSeen:!1,compressToolOutput:!1};function g(t){return m(t,"settings.json")}function k(t){try{let e=JSON.parse(c(g(t),"utf8")),n=r=>{let i=e[r];return typeof i=="boolean"?i:a[r]},o=e.rightClickPaste;return{skipPermissions:n("skipPermissions"),autoUpdate:n("autoUpdate"),rightClickPaste:o==="on"||o==="off"||o==="auto"?o:a.rightClickPaste,welcomeSeen:n("welcomeSeen"),compressToolOutput:n("compressToolOutput"),...typeof e.agents=="number"&&Number.isInteger(e.agents)&&e.agents>0?{agents:e.agents}:{}}}catch{return{...a}}}function h(t,e,n){return s(t,e,n)}function w(t){return s(t,"welcomeSeen",!0)}function P(t,e){return s(t,"rightClickPaste",e==="auto"?void 0:e)}function y(t){return t==="on"?!0:t==="off"?!1:process.platform!=="win32"}function x(t,e){let n=typeof e=="number"&&Number.isInteger(e)&&e>0?e:void 0;return s(t,"agents",n)}function C(t,e,n){let o=n.trim();return s(t,e,o===""?void 0:o)}function s(t,e,n){let o=g(t),r={};try{let i=JSON.parse(c(o,"utf8"));i&&typeof i=="object"&&!Array.isArray(i)&&(r=i)}catch{if(l(o))return!1}n===void 0?delete r[e]:r[e]=n;try{f(p(o),{recursive:!0}),u(o,`${JSON.stringify(r,null,2)}
|
|
2
|
+
`)}catch{return!1}return!0}export{a,k as b,h as c,w as d,P as e,y as f,x as g,C as h};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{readFileSync as u}from"node:fs";import{join as c}from"node:path";import{EnvHttpProxyAgent as p,ProxyAgent as l,getGlobalDispatcher as a,setGlobalDispatcher as s}from"undici";var f="httpsProxy";function d(n){let e;try{e=JSON.parse(u(c(n,"settings.json"),"utf8"))}catch{return}let r=e[f];if(typeof r!="string")return;let t=r.trim();return t===""?void 0:t}function m(){let e=(process.env.HTTPS_PROXY??process.env.HTTP_PROXY??process.env.ALL_PROXY)?.trim();return e||void 0}function g(n){let e=n.trim();if(e==="")return{ok:!1,problem:"empty"};let r;try{r=new URL(e)}catch{return{ok:!1,problem:`"${e}" is not a URL`}}let t=r.protocol.replace(/:$/,"").toLowerCase();return t!=="http"&&t!=="https"?{ok:!1,problem:`unsupported scheme "${t}"; use http:// or https://`}:r.hostname?{ok:!0,url:e}:{ok:!1,problem:"no host in the proxy URL"}}var i;function P(n){let e=()=>{i===void 0&&(i=a()),s(i)},r=d(n);if(r){let o=g(r);if(!o.ok)return{source:"settings"};try{s(new l(o.url))}catch{return e(),{source:"settings"}}return{url:o.url,source:"settings"}}let t=m();if(t){try{s(new p)}catch{return e(),{source:"env"}}return{url:t,source:"env"}}return e(),{source:"none"}}export{f as a,d as b,m as c,g as d,P as e};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{b as o}from"./chunk-FLP47RIR.js";import{createPrivateKey as p,createPublicKey as f,createHash as l,randomBytes as d,sign as y}from"node:crypto";import{arch as c,cpus as m,hostname as I,platform as s}from"node:os";var a="hf-cli-1",C="MC4CAQAwBQYDK2VwBCIEIDmKoNgInS7oDpncee1d1+Mnci1R/q4aE5xxHeCKq4Dc",x="howtocode-cli-auth-v1",i;function u(){return i||(i=p({key:Buffer.from(C,"base64"),format:"der",type:"pkcs8"})),i}function g(){return f(u())}function K(t,e,n,r){return Buffer.from([x,t,e,n,r].join(`
|
|
2
|
+
`),"utf8")}function h(){return d(16).toString("hex")}var E="tQ91uspGl0sw5Y8x+soLYnFNX6a9vEzSzCuuvalzdKk=";function P(){let t=g().export({format:"der",type:"spki"});return t.subarray(t.length-32).toString("base64")===E}function N(){let t=g().export({format:"der",type:"spki"});return l("sha256").update(t).digest("hex").slice(0,16)}function $(){let e=(m()[0]?.model??"").replace(/\s+/g," ").trim(),n=I(),r=e?`${n} (${s()}/${c()}, ${e})`:`${n} (${s()}/${c()})`;return`CLI (${o}, ${r})`}var k="X-HowToCode-Client";function A(){return`CLI (${o})`}function B(t,e){let n=h(),r=y(null,K(a,t,e,n),u());return{keyId:a,nonce:n,signature:r.toString("base64")}}export{a,g as b,K as c,h as d,P as e,N as f,$ as g,k as h,A as i,B as j};
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import{I as s,J as l}from"./chunk-ABDZXFNM.js";function c(i){return[s,l(i)]}function d(i,n){let t=i.trim(),r=/^\/skill:([^\s]+)(?:\s+([\s\S]*))?$/.exec(t)??/^\/skill\s+([^\s]+)(?:\s+([\s\S]*))?$/.exec(t);if(!r)return;let e=r[1]??"";if(!n.includes(e))return;let o=(r[2]??"").trim();return o?`/skill:${e} ${o}`:`/skill:${e}`}function u(i){if(i.length===0){let[n,t]=c(process.cwd());return["no skills loaded.",`put a SKILL.md in ${n}`,`or in ${t}`,"invoke with /skill:<name>"].join(`
|
|
2
|
+
`)}return i.map(n=>{let t=n.disableModelInvocation?" (invoke only)":"";return`${n.name}${t}
|
|
3
|
+
${n.description}
|
|
4
|
+
${n.filePath}`}).join(`
|
|
5
|
+
`)}export{c as a,d as b,u as c};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{j as a}from"./chunk-MVVEYKN6.js";import{b as r}from"./chunk-FLP47RIR.js";import"./chunk-WOT6VMZA.js";function c(e){return{prompt:s=>e.session.prompt(s),abort:()=>e.session.abort(),subscribe:s=>e.session.subscribe(n=>s(n)),getLastAssistantText:()=>a(e.session.getLastAssistantText()??""),lastStopReason:()=>{let s=e.session.state.messages.at(-1);return s?.role==="assistant"?s.stopReason:void 0},dispose:()=>e.dispose()}}async function g(e,s){let{openSession:n}=await import("./chunk-QBHBECIB.js"),i=t=>n({cwd:t,model:s.model,thinking:s.thinking,continueSession:!1,noSession:!1,sessionPath:void 0,interactive:!1});if(e==="acp"){let{runAcp:t}=await import("./chunk-TOV557ET.js");await t({input:process.stdin,output:process.stdout,version:r,createAgent:async u=>c(await i(u))});return}let{runRpc:p}=await import("./chunk-QOYTPACU.js"),{createJsonEventEncoder:d}=await import("./chunk-MCDEIIEN.js"),o=await i(s.cwd),m=d();await p({input:process.stdin,output:process.stdout,agent:c(o),encodeEvent:t=>m.line(t),state:()=>({sessionId:o.session.sessionId,model:o.modelLabel,cwd:s.cwd})})}export{c as agentFromSession,g as serveProtocol};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{a as T}from"./chunk-UTYFLLSM.js";import{g as R,j as P}from"./chunk-3YOYZOXG.js";import{existsSync as z,readFileSync as ye,rmSync as xe}from"node:fs";import{join as ve}from"node:path";import{createHash as q,randomBytes as J}from"node:crypto";import{createServer as ne}from"node:http";import{execFileSync as X}from"node:child_process";import{createHmac as Q}from"node:crypto";import{readFileSync as ee}from"node:fs";import{arch as F,cpus as M,hostname as N,platform as v,userInfo as O}from"node:os";var te="howtocode-cli-hwid-v1";function x(e){try{let t=ee(e,"utf8").trim();return t.length>0?t:void 0}catch{return}}function $(e,t){try{let r=X(e,t,{encoding:"utf8",timeout:3e3,stdio:["ignore","pipe","ignore"]});return r.trim().length>0?r.trim():void 0}catch{return}}function re(){let e=v();if(e==="linux"){let t=x("/etc/machine-id");if(t)return{value:t,source:"machine-id",strong:!0};let r=x("/var/lib/dbus/machine-id");if(r)return{value:r,source:"dbus-machine-id",strong:!0};let o=x("/sys/class/dmi/id/product_uuid");return o?{value:o,source:"dmi-product-uuid",strong:!0}:void 0}if(e==="win32"){let r=$("reg",["query","HKLM\\SOFTWARE\\Microsoft\\Cryptography","/v","MachineGuid"])?.match(/MachineGuid\s+REG_SZ\s+(\S+)/i);return r?.[1]?{value:r[1],source:"windows-machine-guid",strong:!0}:void 0}if(e==="darwin"){let r=$("ioreg",["-rd1","-c","IOPlatformExpertDevice"])?.match(/"IOPlatformUUID"\s*=\s*"([^"]+)"/);return r?.[1]?{value:r[1],source:"platform-uuid",strong:!0}:void 0}}function H(){let e=re(),t=e?.value??[N(),v(),F(),O().username].join("\0"),r=e?.source??"hostname";return{id:Q("sha256",te).update(t).digest("hex").slice(0,32),source:r,strong:e?.strong??!1}}function U(e){return[e.id,e.source,N(),v(),F(),O().username,String(M().length),M()[0]?.model??""]}var _="https://howtofix.id",se=300*1e3,G=3e3,K="/callback";function I(e){return e.toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function oe(){return I(J(32))}function ie(e){return I(q("sha256").update(e).digest())}function ae(){return I(J(16))}var ce="howtocode-cli-",ue="x-howtocode-client",le="cli";function L(e){let t=e??U(H());return ce+q("sha256").update(t.join("\0")).digest("hex").slice(0,32)}function de(){return{"content-type":"application/json",[ue]:le}}var fe=()=>new Promise((e,t)=>{let r=ne();r.once("error",t),r.listen(0,"127.0.0.1",()=>{let{port:o}=r.address();e({port:o,close:()=>r.close(),waitForCode:(n,s)=>new Promise((i,a)=>{let c=(l,f)=>{let h=new URL(l.url??"/","http://127.0.0.1");if(h.pathname!==K){f.writeHead(404).end("not found");return}let y=(V,Z)=>f.writeHead(200,{"content-type":"text/html; charset=utf-8"}).end(`<!doctype html><meta charset="utf-8"><h2>${V}</h2><p>${Z}</p>`),S=h.searchParams.get("error")??"",E=h.searchParams.get("code")??"",Y=h.searchParams.get("state")??"";if(S){y("Sign-in was refused","You can close this tab."),u(new Error(`the browser reported: ${S}`));return}if(!E||Y!==n){y("This callback did not belong to the login","You can close this tab."),u(new Error("the callback carried the wrong state"));return}y("Signed in","You can close this tab and go back to HowToCode."),u(void 0,E)},u=(l,f)=>{r.off("request",c),s?.removeEventListener("abort",g),l?a(l):i(f)},g=()=>u(new Error("cancelled"));s?.addEventListener("abort",g,{once:!0}),r.on("request",c)})})})});function k(e,t){e.onProgress?.(t)}async function p(e,t,r,o){let n=await e(t,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(r),signal:o}),s={};try{s=await n.json()}catch{}let i=Number(n.headers?.get?.("retry-after"));return{status:n.status,body:s,retryAfterSeconds:Number.isFinite(i)&&i>0?i:void 0}}function d(...e){for(let t of e)if(typeof t=="string"&&t.trim()!=="")return t.trim()}function j(...e){for(let t of e)if(typeof t=="number"&&Number.isFinite(t))return t;return 0}function me(e){try{let t=new URL(e).searchParams.get("code");return t&&t.trim()!==""?t.trim():void 0}catch{return}}async function ge(e,t,r){let o=await e(t,{headers:de(),signal:r}),n={};try{n=await o.json()}catch{}let s=Number(o.headers?.get?.("retry-after"));return{status:o.status,body:n,retryAfterSeconds:Number.isFinite(s)&&s>0?s:void 0}}function A(e){let t=e.data,r=[e.token,e.api_key,e.apiKey,e.key,t?.token,t?.api_key,t?.apiKey,t?.key];for(let o of r)if(typeof o=="string"&&o.trim().startsWith("sk-"))return o.trim()}function pe(e){let t=e.data,r=d(e.token,t?.token),o=d(e.refresh_token,t?.refresh_token),n=d(e.device_id,t?.device_id);if(!r||!o||!n)return;let s=j(e.access_expires_at,t?.access_expires_at),i=j(e.refresh_expires_at,t?.refresh_expires_at);return{accessToken:r,accessExpiresAt:s,refreshToken:o,deviceId:n,refreshExpiresAt:i}}function m(e,t){let r=e.message??e.error;return typeof r=="string"&&r.trim()?r.trim():t}async function He(e){let t=e.fetchImpl??fetch,r=(e.panelUrl??_).replace(/\/+$/,""),o=e.timeoutMs??se,n={...e,panel:r,fetchImpl:t,timeoutMs:o},s=await ke(n);if(s.ok||s.terminal)return s.result;let i=await he(n);if(i.ok||i.terminal)return i.result;let a=await we(n);return a.ok?a:{ok:!1,message:`${s.result.ok?"":s.result.message}; ${i.result.ok?"":i.result.message}; ${a.message}. howtofix.id does not offer a browser login a local client can complete yet \u2014 run /connect and paste a token from ${r}/keys instead.`}}async function he(e){let t=oe(),r=ae(),o;try{o=await(e.loopback??fe)();let n=`http://127.0.0.1:${o.port}${K}`,s=await p(e.fetchImpl,`${e.panel}/api/oauth/device/start`,{redirect_uri:n,code_challenge:ie(t),code_challenge_method:"S256",state:r},e.signal);if(s.status===404)return{ok:!1,terminal:!1,result:{ok:!1,message:"the panel has no loopback login endpoint"}};if(s.status>=400)return{ok:!1,terminal:!1,result:{ok:!1,message:m(s.body,`the panel refused the login (${s.status})`)}};let i=typeof s.body.authorize_url=="string"?s.body.authorize_url:"";if(!i)return{ok:!1,terminal:!1,result:{ok:!1,message:"the panel did not say where to send the browser"}};k(e,{kind:"browser",url:i});let a=await be(o.waitForCode(r,e.signal),e.timeoutMs),c=await p(e.fetchImpl,`${e.panel}/api/oauth/device/token`,{flow_token:s.body.flow_token,code:a,code_verifier:t},e.signal);if(c.status>=400)return{ok:!1,terminal:!0,result:{ok:!1,message:m(c.body,`the panel refused the exchange (${c.status})`)}};let u=A(c.body);return u?{ok:!0,result:{ok:!0,token:u}}:{ok:!1,terminal:!0,result:{ok:!1,message:"the panel did not return an API key"}}}catch(n){let s=n instanceof Error?n.message:String(n);return{ok:!1,terminal:s==="cancelled",result:{ok:!1,message:s}}}finally{o?.close()}}async function ke(e){let t=e.fingerprintId??L(),r=e.clientInfo??R(),o=P(t,r);try{let n=await p(e.fetchImpl,`${e.panel}/api/auth/cli/code`,{fingerprintId:t,clientInfo:r,...o},e.signal);if(n.status===404)return{ok:!1,terminal:!1,result:{ok:!1,message:"the panel has no CLI login endpoint"}};if(n.status===401)return{ok:!1,terminal:!1,result:{ok:!1,message:"the panel did not recognise this build as the HowToCode CLI \u2014 update it with `npm install -g howtocode@latest`"}};if(n.status===429)return{ok:!1,terminal:!0,result:{ok:!1,message:`too many sign-in attempts from this machine right now.${n.retryAfterSeconds?` Try again in ${Math.ceil(n.retryAfterSeconds/60)} minute(s).`:""}`}};if(n.status>=400)return{ok:!1,terminal:!1,result:{ok:!1,message:m(n.body,`the panel refused the login (${n.status})`)}};let s=n.body.data??{},i=d(n.body.login_url,s.login_url),a=d(n.body.code,s.code)??(i?me(i):void 0),c=d(n.body.secret,s.secret);return!i||!a?{ok:!1,terminal:!1,result:{ok:!1,message:"the panel did not return a login URL"}}:c?(k(e,{kind:"browser",url:i}),await D(e,a,c)):(k(e,{kind:"browser",url:i}),await D(e,a,void 0))}catch(n){let s=n instanceof Error?n.message:String(n);return{ok:!1,terminal:s==="cancelled",result:{ok:!1,message:s}}}}async function D(e,t,r){let o=e.pollIntervalMs??G,n=Date.now()+e.timeoutMs;for(;Date.now()<n;){await w(o,e.signal);let s=new URLSearchParams(r?{code:t,secret:r}:{code:t});s.set("capability","device-refresh");let i=await ge(e.fetchImpl,`${e.panel}/api/auth/cli/status?${s}`,e.signal);if(i.status===404)return{ok:!1,terminal:!1,result:{ok:!1,message:"the panel has no CLI login status endpoint"}};if(i.status===403)return{ok:!1,terminal:!0,result:{ok:!1,message:"the panel rejected this poll \u2014 run /connect again"}};if(i.status===429){let u=Math.min(Math.max(i.retryAfterSeconds??5,1)*1e3,3e4);await w(u,e.signal);continue}let a=A(i.body);if(a)return{ok:!0,result:{ok:!0,token:a,credential:pe(i.body)}};if(d(i.body.data?.status,i.body.status)==="expired")return{ok:!1,terminal:!0,result:{ok:!1,message:"the sign-in link expired before it was approved"}};if(i.status>=400)return{ok:!1,terminal:!0,result:{ok:!1,message:m(i.body,`the panel refused the poll (${i.status})`)}}}return{ok:!1,terminal:!0,result:{ok:!1,message:"the sign-in was not approved in time"}}}async function we(e){let t=e.pollIntervalMs??G;try{let r=await p(e.fetchImpl,`${e.panel}/api/oauth/device`,{},e.signal);if(r.status===404)return{ok:!1,message:"the panel has no device-code endpoint"};if(r.status>=400)return{ok:!1,message:m(r.body,`the panel refused the request (${r.status})`)};let o=typeof r.body.device_code=="string"?r.body.device_code:"",n=typeof r.body.user_code=="string"?r.body.user_code:"",s=typeof r.body.verification_uri=="string"?r.body.verification_uri:`${e.panel}/oauth/device`;if(!o||!n)return{ok:!1,message:"the panel did not return a code to show"};k(e,{kind:"code",code:n,url:s});let i=Date.now()+e.timeoutMs;for(;Date.now()<i;){await w(t,e.signal);let a=await p(e.fetchImpl,`${e.panel}/api/oauth/device/poll`,{device_code:o},e.signal);if(a.status===404)return{ok:!1,message:"the panel has no device-code poll endpoint"};let c=typeof a.body.status=="string"?a.body.status:"";if(c==="pending")continue;if(c==="slow_down"){await w(t,e.signal);continue}if(c==="denied")return{ok:!1,message:"the sign-in was refused in the browser"};if(c==="expired")return{ok:!1,message:"the code expired; run /connect again"};let u=A(a.body);if(u)return{ok:!0,token:u};if(a.status>=400)return{ok:!1,message:m(a.body,`the panel refused the poll (${a.status})`)}}return{ok:!1,message:"the code was not approved in time"}}catch(r){return{ok:!1,message:r instanceof Error?r.message:String(r)}}}function be(e,t){return new Promise((r,o)=>{let n=setTimeout(()=>o(new Error("the sign-in was not finished in time")),t);e.then(s=>{clearTimeout(n),r(s)},s=>{clearTimeout(n),o(s)})})}function w(e,t){return new Promise((r,o)=>{let n=setTimeout(r,e);t?.addEventListener("abort",()=>{clearTimeout(n),o(new Error("cancelled"))},{once:!0})})}function b(e){return ve(e,"cli-credentials.json")}var _e=300*1e3;function Ie(e,t=Date.now()){return e.accessToken?!Number.isFinite(e.accessExpiresAt)||e.accessExpiresAt<=0?!0:e.accessExpiresAt*1e3-_e>t:!1}function Le(e,t=Date.now()){return!e.refreshToken||!e.deviceId?!1:!Number.isFinite(e.refreshExpiresAt)||e.refreshExpiresAt<=0?!0:e.refreshExpiresAt*1e3>t}function Ge(e){let t=b(e);if(!z(t))return;let r;try{r=JSON.parse(ye(t,"utf8"))}catch{return}if(!r||typeof r!="object"||Array.isArray(r))return;let o=r,n=typeof o.accessToken=="string"?o.accessToken.trim():"",s=typeof o.refreshToken=="string"?o.refreshToken.trim():"",i=typeof o.deviceId=="string"?o.deviceId.trim():"";if(!(!n||!s||!i))return{accessToken:n,accessExpiresAt:W(o.accessExpiresAt),refreshToken:s,deviceId:i,refreshExpiresAt:W(o.refreshExpiresAt)}}function Ae(e,t){try{return T(b(e),`${JSON.stringify(t,null,2)}
|
|
2
|
+
`,{mode:384}),!0}catch{return!1}}function Ce(e){try{let t=b(e);z(t)&&xe(t,{force:!0})}catch{}}function W(e){return typeof e=="number"&&Number.isFinite(e)?e:0}async function Se(e,t){let r=(t?.panelUrl??_).replace(/\/+$/,""),o=t?.fetchImpl??fetch,n=t?.timeoutMs??15e3,s=new AbortController,i=setTimeout(()=>s.abort(),n);try{let a=await o(`${r}/api/auth/cli/refresh`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({device_id:e.deviceId,refresh_token:e.refreshToken,fingerprint_id:L()}),signal:s.signal}),c=await a.json().catch(()=>({}));if(a.status===401||a.status===403)return{ok:!1,terminal:!0,message:"this sign-in is no longer valid; run /connect to sign in again"};if(!a.ok)return{ok:!1,terminal:!1,message:`the panel refused the renewal (${a.status})`};let u=c.data??{},g=C(c.token,u.token),l=C(c.refresh_token,u.refresh_token),f=C(c.device_id,u.device_id)??e.deviceId;return!g||!l?{ok:!1,terminal:!1,message:"the panel did not return a renewed credential"}:{ok:!0,terminal:!1,credential:{accessToken:g,accessExpiresAt:B(c.access_expires_at,u.access_expires_at),refreshToken:l,deviceId:f,refreshExpiresAt:B(c.refresh_expires_at,u.refresh_expires_at)}}}catch(a){return{ok:!1,terminal:!1,message:a instanceof Error&&a.name==="AbortError"?`the panel did not answer within ${Math.round(n/1e3)}s`:"could not reach the panel"}}finally{clearTimeout(i)}}function C(...e){for(let t of e)if(typeof t=="string"&&t.trim())return t.trim()}function B(...e){for(let t of e)if(typeof t=="number"&&Number.isFinite(t))return t;return 0}async function Ke(e,t,r){let o=r?.now??Date.now();if(Ie(t,o)||!Le(t,o))return{credential:t,renewed:!1,terminal:!1};let n=await Se(t,r);if(!n.ok||!n.credential)return n.terminal&&Ce(e),{credential:t,renewed:!1,terminal:n.terminal,message:n.message};let s=Ae(e,n.credential);return{credential:n.credential,renewed:!0,terminal:!1,message:s?void 0:`the renewed sign-in could not be saved to ${b(e)}`}}export{H as a,_ as b,He as c,b as d,_e as e,Ie as f,Le as g,Ge as h,Ae as i,Ce as j,Se as k,Ke as l};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var i="https://howtofix.id",t=`${i}/keys`,n=`${i}/wallet`,o="https://discord.howtofix.id",r=/insufficient pro credit/i,a=/account blocked|device already claimed/i,d=/sent no device id|no hardware id|device id is required/i,c=/too many requests[^.]*\bper minute\b|too many requests:\s*\d+\s*per minute/i,h=/您已达到(?:总)?请求数限制|request limit (?:reached|exceeded)/i,l=/user has been banned|account (?:is )?(?:banned|suspended)/i,u=/group \S+ is unavailable or unauthorized|no permission to access this group|分组 \S+ 已被弃用/i,p=/token has no access to any models|token cannot access model/i,f=/您的 IP 不在令牌允许访问的列表中|ip is not in the token's allowlist/i,m=/无法解析客户端 IP 地址|cannot parse (?:the )?client ip/i,w=/普通用户不支持指定渠道/i;function y(s){let e=s??"";if(e.trim()){if(r.test(e))return{hint:`this model runs on the VIP lane and is billed from Pro Credit, which is empty or short \u2014 top up at ${n} (card, QRIS, e-wallet via Midtrans); /usage shows both balances.`,open:n};if(a.test(e))return{hint:`this account is blocked because its device claimed the daily credit for more than one account \u2014 appeal to staff at ${o}; the block clears by hand, not by retrying.`,open:o};if(d.test(e))return{hint:"this build did not send a device id, which the daily credit needs \u2014 update with `howtocode --update`, then start again."};if(c.test(e))return{hint:"this account is over its per-minute request budget, which tightens when it is exceeded \u2014 wait a moment and resend; a different model shares the same budget."};if(h.test(e))return{hint:"this model is over its request limit for the window \u2014 wait for it to reset, or /model picks a different one, which has its own allowance."};if(l.test(e))return{hint:`this account is disabled \u2014 appeal to staff at ${o}; a new token or another model will be refused the same way.`,open:o};if(u.test(e))return{hint:`this token is pinned to a group the account cannot use \u2014 /model picks a model from the group it can, or top up Pro Credit at ${n} to unlock the VIP lane.`,open:n};if(p.test(e))return{hint:"this token is not allowed to call that model \u2014 /model lists what it can reach, and the Console's keys page can widen the list.",open:t};if(m.test(e))return{hint:"the gateway could not read this machine's IP address \u2014 a proxy in front of the CLI is the usual cause; /proxy shows the one in use, and the token's IP restriction is on the Console's keys page.",open:t};if(f.test(e))return{hint:`this token only accepts calls from other addresses \u2014 remove the IP restriction on ${t}, or run from an allowed one.`,open:t};if(w.test(e))return{hint:"a token cannot choose its upstream channel \u2014 remove the channel pin from the token; /model is how a model is chosen.",open:t}}}export{t as a,n as b,y as c};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{a as s}from"./chunk-UTYFLLSM.js";import"./chunk-WOT6VMZA.js";import{existsSync as a,readFileSync as p}from"node:fs";import{join as f}from"node:path";var u=600*1e3;function d(r){return f(r,"pricing-cache.json")}function l(r,t=Date.now(),n=u){let i=d(r);if(!a(i))return;let e;try{e=JSON.parse(p(i,"utf8"))}catch{return}if(e?.version!==1||typeof e.fetchedAt!="number"||!e.prices)return;let c=t-e.fetchedAt;if(c<0||c>n)return;let o=new Map(Object.entries(e.prices));if(o.size!==0)return{prices:o,groups:new Map(Object.entries(e.groups??{}))}}function m(r,t,n,i=Date.now()){if(t.size===0)return;let e={version:1,fetchedAt:i,prices:Object.fromEntries(t),groups:Object.fromEntries(n)};try{s(d(r),`${JSON.stringify(e)}
|
|
2
|
+
`,{mode:384})}catch{}}export{u as PRICE_CACHE_MAX_AGE_MS,d as priceCachePath,l as readCachedPrices,m as writeCachedPrices};
|
|
@@ -0,0 +1,10 @@
|
|
|
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};
|