diff --git a/README.md b/README.md index f763ebf..9522db9 100644 --- a/README.md +++ b/README.md @@ -48,18 +48,15 @@ darknode-cli/ ## Installation -```bash -# from npm (Node 18+) — installs the `darknode` and `nexus` commands -npm install -g darknode-cli - -# or run it without installing -npx darknode-cli nexus +Requires Node 18 or newer. -# from source +```bash git clone https://github.com/Darknode-Official/darknode-cli -cd darknode-cli && npm install && node darknode.js +cd darknode-cli && npm install +node darknode.js -# or grab a standalone binary from Releases and put it on PATH +# optional: put the `darknode` and `nexus` commands on your PATH +npm install -g . ``` Free to download and use (see [LICENSE](LICENSE)). diff --git a/darknode-legacy.js b/darknode-legacy.js index 2313fcc..f97a8fe 100644 --- a/darknode-legacy.js +++ b/darknode-legacy.js @@ -846,9 +846,9 @@ async function cli(args) { const portArg = rest.indexOf("--port"); const apiPort = portArg >= 0 ? parseInt(rest[portArg + 1], 10) || 8080 : 8080; const apiToken = process.env.SENTINEL_API_TOKEN || null; const { srv, port: p, token: t } = createAPIServer({ port: apiPort, token: apiToken }); - srv.listen(apiPort, "0.0.0.0", () => { - h1("Darknode API Server"); console.log(" " + green("listening ") + cyan("http://0.0.0.0:" + apiPort)); - if (t) console.log(" token " + bold(t)); else console.log(" " + yellow("no API key required (set DARKNODE_API_TOKEN to require one)")); + srv.listen(apiPort, "127.0.0.1", () => { + h1("Darknode API Server"); console.log(" " + green("listening ") + cyan("http://127.0.0.1:" + apiPort)); + console.log(" token " + bold(t) + gray(" (send as: X-API-Key: )")); console.log("\n " + gray("health ") + "curl http://localhost:" + apiPort + "/health"); console.log(" " + gray("scan ") + "curl -s http://localhost:" + apiPort + "/api/v1/scan/url -H 'Content-Type: application/json' -d '{\"url\":\"https://target.com\"}'"); console.log("\n " + gray("Ctrl-C to stop")); diff --git a/darknode.js b/darknode.js index 1cb7758..e6a0bb3 100755 --- a/darknode.js +++ b/darknode.js @@ -2987,7 +2987,7 @@ function nexusTui(engine, cwd, nexusMd, autoResume, launch) { ["/help", "commands, input prefixes & keys · /help searches them"], ["/clear", "start a fresh chat"], ["/chat-clear", "clear the screen, keep the conversation memory"], ["/compact", "summarize & shrink the context"], ["/trust", "trust this workspace's .nexus MCP servers, hooks + allow rules"], ["/connect", "connect an AI: local model · Claude (API) · any provider"], - ["/context", "show token / context usage"], ["/cost", "session cost at exact list prices"], ["/turns", "per-turn cost ledger for this session"], ["/cheaper", "lossless ways to spend fewer tokens"], ["/warm", "prompt-cache countdown + warm-vs-cold follow-up cost"], ["/tokens", "estimate what @-attaching a file/dir costs"], ["/alias", "make a shortcut: /alias name = text|/cmd"], ["/retry", "re-run your last prompt (fresh, no cache)"], ["/pricing", "exact per-model prices (USD per million tokens)"], ["/budget", "set a spend cap in USD"], + ["/context", "show token / context usage"], ["/cost", "session cost at exact list prices"], ["/turns", "per-turn cost ledger for this session"], ["/cheaper", "tips only: how this session could cost less, changes nothing"], ["/warm", "prompt-cache countdown + warm-vs-cold follow-up cost"], ["/tokens", "estimate what @-attaching a file/dir costs"], ["/alias", "make a shortcut: /alias name = text|/cmd"], ["/retry", "re-run your last prompt (fresh, no cache)"], ["/pricing", "exact per-model prices (USD per million tokens)"], ["/budget", "set a spend cap in USD"], ["/report", "cost & usage report for chargeback (/report json|save|since )"], ["/compliance", "write a signed audit+usage compliance bundle (SOC2/review)"], ["/undo", "revert the last turn's file changes"], ["/rewind", "restore a specific checkpoint (/rewind N)"], ["/checkpoints", "list undo checkpoints"], @@ -3004,7 +3004,7 @@ function nexusTui(engine, cwd, nexusMd, autoResume, launch) { ["/ensemble", "all engines answer, then synthesize the best"], ["/settings", "all options, neatly arranged (alias /options /config)"], ["/jobs", "background commands the agent started (run_background)"], ["/loop", "autonomous goal loop: /loop [-n rounds] until GOAL-DONE"], ["/team", "multi-model workspace: architect + builder + reviewer, loops to PASS"], ["/policy", "show the enterprise security policy (org + local)"], ["/audit", "audited tool actions · /audit verify (tamper check)"], ["/bench", "speed / tokens / cost table per engine"], ["/explain", "explain the diff or a file in plain English"], ["/test", "generate & run unit tests for a file"], ["/refactor", "restructure code for clarity without changing behavior"], ["/migrate", "migrate code: /migrate to "], ["/pr", "AI-write a PR title+body from the diff and open it (gh)"], ["/index", "index the repo for code search; /index finds the code it is about"], ["/map", "show the repo map; /map ranks it for a task; /map on|off"], ["/verify", "detect + run this project's tests/build"], ["/radar", "codebase complexity + hotspot map"], ["/review-fast", "fast rule-based review of changed code (no AI)"], ["/diffexplain", "explain the current git diff"], ["/testgen", "scaffold tests for a function/file"], ["/snippet", "save / use a prompt macro"], ["/snippets", "list saved prompt macros"], ["/plan", "make & run an editable task checklist"], ["/git", "branch, status & recent commits"], ["/blame", "who last changed a file's lines"], - ["/cowork", "strong model codes, weak model does cheap work"], ["/cheap", "max token savings with ZERO quality loss (status · off)"], ["/tight", "surgical edits — change only what differs (lossless)"], ["/lean", "ask for minimal output (saves output tokens) · /lean on|off"], ["/style", "output style: concise·explanatory·review·tdd·secure·teacher"], ["/effort", "claude thinking level — interactive slider (or low|medium|high|xhigh|max|ultracode)"], ["/estimate", "rough token/cost of a prompt before sending"], ["/fallback", "auto-switch model on rate-limit"], + ["/cowork", "strong model codes, weak model does cheap work"], ["/cheap", "turn on every lossless token saver · /cheap status · /cheap off"], ["/tight", "surgical edits — change only what differs (lossless)"], ["/lean", "ask for minimal output (saves output tokens) · /lean on|off"], ["/style", "output style: concise·explanatory·review·tdd·secure·teacher"], ["/effort", "claude thinking level — interactive slider (or low|medium|high|xhigh|max|ultracode)"], ["/estimate", "rough token/cost of a prompt before sending"], ["/fallback", "auto-switch model on rate-limit"], ["/guard", "preflight destructive commands (enforce|warn|off)"], ["/permissions", "allow/deny tool rules — /allow /deny "], ["/impact", "same as /savings — cost-savings analysis"], ["/savings", "cross-session cost-savings analysis + 30d projection"], ["/cache", "serve exact-repeat read-only answers free (on/off/clear)"], ["/models", "list cloud & local models"], ["/api", "drive ANY model via an OpenAI-compatible API (OpenRouter, Groq, …)"], ["/recent", "recently changed files"], ["/keys", "keyboard shortcuts"], ["/docs", "Nexus docs: /docs or /docs to search every command & key"], ["/gaps", "list TODO/FIXME markers · /gaps plan"], ["/dream", "consolidate the session into NEXUS.md memory"], ["/tree", "show the project file tree"], ["/theme", "change the color theme"], ["/color", "set the accent color · /color · /color reset"], ["/colors", "list accent colors"], ["/gradient", "set the logo gradient · /gradient "], ["/mouse", "toggle mouse capture · /mouse off to select & copy text"], diff --git a/docs/NEXUS-COMMANDS.md b/docs/NEXUS-COMMANDS.md index d96de6e..9e39cb9 100644 --- a/docs/NEXUS-COMMANDS.md +++ b/docs/NEXUS-COMMANDS.md @@ -77,7 +77,7 @@ File tools are confined to the project folder; secrets are blocked from being wr - `/context` — show token / context usage (opens in the side panel) - `/cost` — session cost at exact list prices (opens in the side panel) - `/turns` — per-turn cost ledger for this session (opens in the side panel) -- `/cheaper` — lossless ways to spend fewer tokens (opens in the side panel) +- `/cheaper` — tips only: how this session could cost less, changes nothing (opens in the side panel) - `/warm` — prompt-cache countdown + warm-vs-cold follow-up cost (opens in the side panel) - `/tokens` — estimate what @-attaching a file/dir costs (opens in the side panel) - `/alias` — make a shortcut: /alias name = text|/cmd @@ -151,7 +151,7 @@ File tools are confined to the project folder; secrets are blocked from being wr - `/git` — branch, status & recent commits - `/blame` — who last changed a file's lines - `/cowork` — strong model codes, weak model does cheap work -- `/cheap` — max token savings with ZERO quality loss (status · off) +- `/cheap` — turn on every lossless token saver · /cheap status · /cheap off - `/tight` — surgical edits — change only what differs (lossless) - `/lean` — ask for minimal output (saves output tokens) · /lean on|off - `/style` — output style: concise·explanatory·review·tdd·secure·teacher diff --git a/lib/cli/composer.js b/lib/cli/composer.js index 76434f5..33f5918 100644 --- a/lib/cli/composer.js +++ b/lib/cli/composer.js @@ -17,6 +17,15 @@ function nextGrapheme(t, i) { for (const g of _seg.segment(t.slice(i, i + 64))) return i + g.segment.length; return t.length; } +// Placeholder tags the composer inserts ([Pasted text #1 +40 lines], [Image#2]) and the +// expanded form a sent or recalled message carries ([attached image: shots/a.png]). The caret +// moves over each one in a single step and Backspace/Delete remove it whole, so a tag can never +// be half-edited into something that no longer expands. +const TAG = "\\[(?:Pasted text #\\d+ \\+\\d+ lines|Image#\\d+|attached image: [^\\]\\n]+)\\]"; +const TAG_BEFORE = new RegExp(TAG + "$"), TAG_AFTER = new RegExp("^" + TAG); +// Length of the tag that ends exactly at i / starts exactly at i (0 when there is none). +const tagBefore = (t, i) => { const m = t.slice(Math.max(0, i - 4096), i).match(TAG_BEFORE); return m ? m[0].length : 0; }; +const tagAfter = (t, i) => { const m = t.slice(i, i + 4096).match(TAG_AFTER); return m ? m[0].length : 0; }; // Start of the grapheme that contains index i (i itself when it is already a boundary). function snapGrapheme(t, i) { const p = prevGrapheme(t, i); return nextGrapheme(t, p) > i ? p : i; } // ============================================================================ @@ -220,10 +229,7 @@ class ComposerModel { backspace() { if (this.cursor <= 0) return; // a collapsed-paste / image placeholder deletes as one unit - const before = this.text.slice(0, this.cursor); - const ph = before.match(/\[(?:Pasted text #\d+ \+\d+ lines|Image#\d+)\]$/); - let del = ph ? ph[0].length : 1; - if (!ph) del = this.cursor - prevGrapheme(this.text, this.cursor); // a whole emoji / accented letter, not half of it + const del = tagBefore(this.text, this.cursor) || this.cursor - prevGrapheme(this.text, this.cursor); // a whole emoji / accented letter, not half of it this.snapshot(); this.text = this.text.slice(0, this.cursor - del) + this.text.slice(this.cursor); this.cursor -= del; @@ -231,21 +237,18 @@ class ComposerModel { deleteForward() { if (this.cursor >= this.text.length) return; // a collapsed-paste / image placeholder deletes as one unit (mirror of backspace) - const after = this.text.slice(this.cursor); - const ph = after.match(/^\[(?:Pasted text #\d+ \+\d+ lines|Image#\d+)\]/); - let del = ph ? ph[0].length : 1; - if (!ph) del = nextGrapheme(this.text, this.cursor) - this.cursor; + const del = tagAfter(this.text, this.cursor) || nextGrapheme(this.text, this.cursor) - this.cursor; this.snapshot(); this.text = this.text.slice(0, this.cursor) + this.text.slice(this.cursor + del); } // ---- cursor movement (char, word, line) ---- - left() { this.cursor = prevGrapheme(this.text, this.cursor); } // one user-visible character (👍🏽, é, 🇫🇷 …) - right() { this.cursor = nextGrapheme(this.text, this.cursor); } + left() { const n = tagBefore(this.text, this.cursor); this.cursor = n ? this.cursor - n : prevGrapheme(this.text, this.cursor); } // one user-visible character (👍🏽, é, 🇫🇷 …) or one whole tag + right() { const n = tagAfter(this.text, this.cursor); this.cursor = n ? this.cursor + n : nextGrapheme(this.text, this.cursor); } home() { const nl = this.text.lastIndexOf("\n", this.cursor - 1); this.cursor = nl + 1; } // start of current line end() { const nl = this.text.indexOf("\n", this.cursor); this.cursor = nl === -1 ? this.text.length : nl; } // end of current line - wordLeft() { let i = this.cursor; while (i > 0 && /\s/.test(this.text[i - 1])) i--; while (i > 0 && !/\s/.test(this.text[i - 1])) i--; this.cursor = i; } - wordRight() { let i = this.cursor; while (i < this.text.length && /\s/.test(this.text[i])) i++; while (i < this.text.length && !/\s/.test(this.text[i])) i++; this.cursor = i; } + wordLeft() { let i = this.cursor; while (i > 0 && /\s/.test(this.text[i - 1])) i--; const tg = tagBefore(this.text, i); if (tg) { this.cursor = i - tg; return; } while (i > 0 && !/\s/.test(this.text[i - 1])) i--; this.cursor = i; } + wordRight() { let i = this.cursor; while (i < this.text.length && /\s/.test(this.text[i])) i++; const tg = tagAfter(this.text, i); if (tg) { this.cursor = i + tg; return; } while (i < this.text.length && !/\s/.test(this.text[i])) i++; this.cursor = i; } endWord() { let i = this.cursor; if (i < this.text.length) i++; while (i < this.text.length && /\s/.test(this.text[i])) i++; while (i < this.text.length && !/\s/.test(this.text[i])) i++; this.cursor = i; } // just past the end of the current/next word (vim `e`, operator-friendly) // ---- kill-ring ---- diff --git a/lib/cli/tui-format.js b/lib/cli/tui-format.js index 306079e..9e064b5 100644 --- a/lib/cli/tui-format.js +++ b/lib/cli/tui-format.js @@ -23,12 +23,17 @@ function charWidth(ch) { } // visible width in terminal cells (ANSI-aware, wide/zero-width aware) const _graphemes = (typeof Intl !== "undefined" && Intl.Segmenter) ? new Intl.Segmenter(undefined, { granularity: "grapheme" }) : null; +const _wMemo = new Map(); function strWidth(s) { s = stripAnsi(s); if (!/[^\x00-\u02ff]/.test(s)) return s.length; // fast path: nothing wide or zero-width if (!/[\u200D\uFE0F]|\uD83C[\uDDE6-\uDDFF]/.test(s) || !_graphemes) { let w = 0; for (const ch of s) w += charWidth(ch); return w; } - // ZWJ sequences (👨‍👩‍👧), emoji-presentation (❤️) and flags (🇫🇷) render as ONE 2-cell glyph - let w = 0; for (const { segment: g } of _graphemes.segment(s)) { const c = charWidth(g); w += /\u200D|\uFE0F/.test(g) || /^\uD83C[\uDDE6-\uDDFF]\uD83C[\uDDE6-\uDDFF]$/.test(g) ? 2 : [...g].reduce((a, ch, k) => a + (k ? charWidth(ch) : c), 0); } return w; + // ZWJ sequences (👨‍👩‍👧), emoji-presentation (❤️) and flags (🇫🇷) render as ONE 2-cell glyph. + // Segmenting is slow per call and the wrapper re-measures short clusters, so memoize those. + const memo = s.length <= 64 ? _wMemo.get(s) : undefined; if (memo !== undefined) return memo; + let w = 0; for (const { segment: g } of _graphemes.segment(s)) { const c = charWidth(g); w += /\u200D|\uFE0F/.test(g) || /^\uD83C[\uDDE6-\uDDFF]\uD83C[\uDDE6-\uDDFF]$/.test(g) ? 2 : [...g].reduce((a, ch, k) => a + (k ? charWidth(ch) : c), 0); } + if (s.length <= 64) { if (_wMemo.size >= 1024) _wMemo.clear(); _wMemo.set(s, w); } + return w; } const visLen = strWidth; // Longest prefix of plain `s` (in UTF-16 units) that fits `w` cells; always >=1 glyph so wrappers progress. diff --git a/test/composer.test.js b/test/composer.test.js index 30e2ed5..6f62dd8 100644 --- a/test/composer.test.js +++ b/test/composer.test.js @@ -610,5 +610,28 @@ group("graphemes — backspace/arrows treat emoji clusters as one character"); eq("strWidth: CJK = 2 cells each", TF.strWidth("\u4e2d\u6587"), 4); } +{ + // Arrow keys cross a whole tag in one press (never step into it letter by letter), and + // word jumps / word-delete treat a tag with spaces inside as one unit. + const txt = "see [attached image: shots/a b.png] and [Image#2] [Pasted text #1 +40 lines]!"; + const m = new C.ComposerModel({ text: txt }); + const t1 = txt.indexOf("["), t1e = txt.indexOf("]") + 1, t2 = txt.indexOf("[Image"), t2e = t2 + "[Image#2]".length; + m.cursor = t1; m.right(); eq("Right crosses [attached image: ...] in one press", m.cursor, t1e); + m.left(); eq("Left crosses it back in one press", m.cursor, t1); + m.cursor = t2; C.feed(m, "\x1b[C", {}); eq("Right arrow key crosses [Image#2]", m.cursor, t2e); + C.feed(m, "\x1b[D", {}); eq("Left arrow key crosses [Image#2] back", m.cursor, t2); + const p = txt.indexOf("[Pasted"); m.cursor = p; m.right(); eq("Right crosses [Pasted text ...]", m.cursor, txt.length - 1); + m.cursor = 0; m.wordRight(); m.wordRight(); eq("word-right skips a tag containing spaces", m.cursor, t1e); + m.wordLeft(); eq("word-left lands at the start of the tag", m.cursor, t1); + m.cursor = 2; m.right(); eq("ordinary text still moves one character", m.cursor, 3); + const d = new C.ComposerModel({ text: "a [attached image: x.png]b" }); d.cursor = d.text.length - 1; d.backspace(); + eq("Backspace removes [attached image: ...] whole", d.text, "a b"); + const f = new C.ComposerModel({ text: "a [attached image: x.png]b" }); f.cursor = 2; f.deleteForward(); + eq("Delete removes [attached image: ...] whole", f.text, "a b"); + const w = new C.ComposerModel({ text: "x [attached image: a b.png]" }); w.cursor = w.text.length; w.deleteWordLeft(); + eq("Ctrl+W removes the whole tag", w.text, "x "); + const n = new C.ComposerModel({ text: "[not a tag] ok" }); n.cursor = 0; n.right(); eq("plain brackets are not tags", n.cursor, 1); +} + console.log("\n" + (fail ? "\x1b[31m" : "\x1b[32m") + pass + " passed, " + fail + " failed\x1b[0m (composer + settings)"); process.exit(fail ? 1 : 0);