@hncode/hncode 0.7.4 → 0.7.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -6,9 +6,31 @@
6
6
 
7
7
  English | [简体中文](https://github.com/NiceHello666/HNCode/blob/main/README_CN.md) | [Wiki](https://github.com/NiceHello666/HNCode/blob/main/README_WIKI.md)
8
8
 
9
- > **This is a product of my vibe coding session. I'm trying my best to make it perfect, so if you have any suggestions, feel free to open an issue.**
9
+ A coding agent that lives in your terminal. Point it at a repo, describe the change, and it reads the files, edits them and runs the tests — inside a raw-TTY renderer that stays correct on Windows Terminal, where most terminal UIs garble.
10
10
 
11
- A cyan-blue terminal user interface (TUI) coding agent inspired by [Kimi Code](https://github.com/MoonshotAI/kimi-code), with OpenAI + Anthropic support, an MCP-style toolbelt, and intelligent context management.
11
+ ## Why this one
12
+
13
+ **Raw terminal, done properly.** No UI library sits between the agent and the terminal. The renderer writes the escape sequences itself and keeps its own cell buffer, so Windows Terminal — where blessed-style libraries garble on a non-TTY stream — gets the same layout as everything else. Capabilities are probed live: synchronized output, the Kitty keyboard protocol, image protocols, and a theme that follows the detected background.
14
+
15
+ **Fast enough to type against.** Markdown is rendered block-by-block with a cache, so a streaming reply does not re-parse the whole transcript on every frame. Only changed cells are repainted. Message token counts are memoized per message and kept as a rolling total; the context gauge no longer re-walks a long history several times per turn. It makes a visible difference once a session has read a few hundred files.
16
+
17
+ **Built to be looked at.** Syntax-highlighted diffs and file reads, line-level red/green washes that survive a mouse selection, block comments that stay grey, wide CJK glyphs, a scrollbar with sub-cell resolution, LaTeX typeset as a bitmap with Unicode and source fallbacks, Mermaid fences drawn as diagrams. `/raw` shows the model's reply verbatim when you need to tell a bad answer from a bad render.
18
+
19
+ **Everything is in this repository.** No runtime dependencies. The token estimator, the RFC6455 WebSocket behind `/web`, the image encoder, the syntax highlighter and the plugin/skill managers are all here, readable and patchable. `npm install -g @hncode/hncode` installs exactly this code.
20
+
21
+ ---
22
+
23
+ ## A session
24
+
25
+ ```bash
26
+ $ npm install -g @hncode/hncode
27
+ $ cd my-project
28
+ $ hncode
29
+
30
+ > the tests fail after the config change — find out why and fix it
31
+ ```
32
+
33
+ The agent reads the config and the failing test, runs the suite, edits the file, and runs it again. Every tool call appears with its own syntax-highlighted diff, so the change is on screen before it happens.
12
34
 
13
35
  ---
14
36
 
package/README_CN.md CHANGED
@@ -6,9 +6,31 @@
6
6
 
7
7
  [English](https://github.com/NiceHello666/HNCode/blob/main/README.md) | 简体中文 | [Wiki](https://github.com/NiceHello666/HNCode/blob/main/README_WIKI_CN.md)
8
8
 
9
- > **这是我vibe coding的产物. 我在尽全力让它变的完美, 所以如果你有何建议, 欢迎开一个issue.**
9
+ 一个住在终端里的编程 agent。指到某个仓库、说清楚要改什么,它会读文件、改文件、跑测试,全过程都在一个原始终端渲染器里完成,包括 Windows Terminal 上那些会让多数终端界面花屏的场景。
10
10
 
11
- 一个基于终端用户界面(TUI)的 AI 编程助手,灵感源自 [Kimi Code](https://github.com/MoonshotAI/kimi-code)。它提供青色蓝调 (Cyan-blue) 的 TUI 界面,支持 OpenAI 和 Anthropic 双协议,配备 MCP 风格的工具集和智能上下文管理。
11
+ ## 为什么用它
12
+
13
+ **原始终端,做对了。** agent 和终端之间没有 UI 库。渲染器自己写终端序列、自己维护单元格缓冲,所以 blessed 一类库会在非 TTY 流上花屏的 Windows Terminal,也能拿到和别处一致的排版。能力是实时探测的:同步输出、Kitty 键盘协议、图片协议,以及跟着背景色走的主题。
14
+
15
+ **打字时跟得上。** Markdown 按块渲染并带缓存,流式回复不用每一帧都重新解析整份记录;重绘只写变化的单元格。消息的 token 数按对象记忆化,并维护滚动总量,context 计量不再在每一轮里反复遍历长历史。读过几百个文件之后,这个差别肉眼可见。
16
+
17
+ **为「看代码」而做。** diff 和文件读取带语法高亮,行级红绿底色在鼠标选区下仍然保留,块注释整段灰色,CJK 宽字符对齐,滚动条有亚单元格精度,LaTeX 排版成位图并带 Unicode 与源码回退,Mermaid 画成图。`/raw` 可以逐字看模型的原始回复,用来分辨是回答本身不对还是渲染不对。
18
+
19
+ **全部就在这个仓库里。** 零运行时依赖:token 估算器、`/web` 背后的 RFC6455 WebSocket、图片编码器、语法高亮器、插件与 skill 管理器都在这里,能读也能改。`npm install -g @hncode/hncode` 装的就是这份代码。
20
+
21
+ ---
22
+
23
+ ## 一次会话
24
+
25
+ ```bash
26
+ $ npm install -g @hncode/hncode
27
+ $ cd my-project
28
+ $ hncode
29
+
30
+ > 改完配置之后测试挂了,查清楚原因并修好
31
+ ```
32
+
33
+ 它会读配置和失败的测试,跑一遍测试,改文件,再跑一遍。每次工具调用都带着自己的语法高亮 diff,改动发生之前就已经在屏幕上。
12
34
 
13
35
  ---
14
36
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hncode/hncode",
3
- "version": "0.7.4",
3
+ "version": "0.7.5",
4
4
  "description": "hncode — A cyan-blue TUI AI coding agent with zero runtime dependencies.",
5
5
  "type": "module",
6
6
  "main": "src/index.js",
package/src/hooks.js CHANGED
@@ -47,15 +47,41 @@ export const HOOK_EVENTS = [
47
47
  'SessionEnd',
48
48
  'UserPromptSubmit',
49
49
  'PreToolUse',
50
+ 'PermissionRequest',
50
51
  'PostToolUse',
51
52
  'PostToolUseFailure',
53
+ 'FileChanged',
52
54
  'Stop',
55
+ 'SubagentStart',
53
56
  'SubagentStop',
54
57
  'PreCompact',
55
58
  'PostCompact',
56
59
  'Notification',
60
+ 'ConfigChange',
61
+ 'CwdChanged',
57
62
  ];
58
63
 
64
+ /** What each event means, shown by /hooks so the panel is a reference rather than a bare list of names. */
65
+ export const HOOK_EVENT_HINTS = {
66
+ SessionStart: 'a session opens or resumes',
67
+ SessionEnd: 'a session is closing',
68
+ UserPromptSubmit: 'before your prompt is sent',
69
+ PreToolUse: 'before a tool runs; can block it',
70
+ PermissionRequest: 'a tool needs your approval',
71
+ PostToolUse: 'after a tool succeeds',
72
+ PostToolUseFailure: 'after a tool fails',
73
+ FileChanged: 'after a file is written or edited',
74
+ Stop: 'the model finishes a turn',
75
+ SubagentStart: 'a subagent is spawned',
76
+ SubagentStop: 'a subagent finishes',
77
+ PreCompact: 'before history is summarized',
78
+ PostCompact: 'after history is summarized',
79
+ Notification: 'the app needs your attention',
80
+ ConfigChange: 'a setting or config file changes',
81
+ CwdChanged: 'the working directory changes',
82
+ };
83
+
84
+
59
85
  // A hook that hangs must not hang the agent. 60s is generous for a formatter or
60
86
  // a lint pass and still bounded.
61
87
  export const HOOK_TIMEOUT_MS = 60 * 1000;
@@ -221,7 +247,12 @@ export async function runShellHooks(config, event, payload, cwd) {
221
247
  // ran after reads and searches too.
222
248
  const isToolEvent = event === 'PreToolUse' || event === 'PostToolUse' || event === 'PostToolUseFailure';
223
249
  const results = [];
224
- for (const entry of list) {
250
+ for (const raw of list) {
251
+ // A hook entry can arrive from a CONFIG FILE (which fills in the defaults) or from a caller that built it by
252
+ // hand — a test, a plugin, or one of the TUI-side notifications. The timeout must exist in both cases: an
253
+ // undefined one made setTimeout fire at once and reported "timed out after NaNs" without ever running the
254
+ // command.
255
+ const entry = { ...raw, timeoutMs: Number.isFinite(raw.timeoutMs) ? raw.timeoutMs : HOOK_TIMEOUT_MS };
225
256
  if (isToolEvent && !matcherApplies(entry.matcher, payload && payload.toolName)) continue;
226
257
  const r = await runHookCommand(entry, event, payload, cwd);
227
258
  results.push({ entry, ...r });
@@ -239,19 +270,25 @@ export async function runShellHooks(config, event, payload, cwd) {
239
270
  }
240
271
 
241
272
  // Human-readable summary for /hooks.
242
- export function describeHooks(config) {
273
+ //
274
+ // EVERY EVENT IS LISTED, including the ones with nothing configured. The old version printed a single
275
+ // "No hooks configured." line when the config was empty, which told the user nothing about what COULD be hooked
276
+ // and left the panel almost blank. Listing the full set is what makes the screen a reference: a reader sees the
277
+ // eleven events, which of them are active, and where the files live, without having to read the docs first.
278
+ export function describeHooks(config, workspace) {
243
279
  const hooks = (config && config.hooks) || {};
244
280
  const lines = [];
245
- const total = Object.values(hooks).reduce((a, l) => a + l.length, 0);
246
- if (!total) return ['No hooks configured.', '', `Global file: ${globalHooksFile()}`, `Project file: ${projectHooksFile(process.cwd())}`];
281
+ const total = HOOK_EVENTS.reduce((a, ev) => a + ((hooks[ev] || []).length), 0);
282
+ lines.push(`${total} hook${total === 1 ? '' : 's'} configured across ${HOOK_EVENTS.length} events.`, '');
247
283
  for (const ev of HOOK_EVENTS) {
248
- const list = hooks[ev];
249
- if (!list || !list.length) continue;
250
- lines.push(`${ev}:`);
284
+ const list = hooks[ev] || [];
285
+ const hint = HOOK_EVENT_HINTS[ev] || '';
286
+ lines.push(`${ev}${hint ? ` — ${hint}` : ''}: ${list.length ? `${list.length} configured` : '(none)'}`);
251
287
  for (const e of list) {
252
288
  lines.push(` ${e.matcher ? `[${e.matcher}] ` : ''}${e.command}`);
253
289
  lines.push(` (${e.source})`);
254
290
  }
255
291
  }
292
+ lines.push('', `Global file: ${globalHooksFile()}`, `Project file: ${projectHooksFile(workspace || process.cwd())}`);
256
293
  return lines;
257
294
  }
package/src/tui.js CHANGED
@@ -1543,7 +1543,9 @@ function paintCode(text, lang, bg, inComment = false) {
1543
1543
  // whole body inside one token, so it drew with no wash at all while the code below it was washed, and the block
1544
1544
  // looked striped. Seeding the background at the front covers that first run; the replacement covers every run
1545
1545
  // after it, because each token closes with a reset that would otherwise drop back to the page background.
1546
- return { text: bg + raw.replace(/\x1b\[0m/g, `\x1b[0m${bg}`) + C.reset, inComment: result.inComment };
1546
+ // ESC[39m, NOT ESC[0m: a bare reset clears the background too, and the row's wash must survive past the last
1547
+ // token. The final glyph is still inside the coloured run, so nothing is left over to clear.
1548
+ return { text: bg + raw.replace(/\x1b\[0m/g, `\x1b[0m${bg}`) + '\x1b[39m', inComment: result.inComment };
1547
1549
  }
1548
1550
 
1549
1551
  /**
@@ -3007,7 +3009,9 @@ function messageLines(msg, width, workspace, expanded, spin, pulseStart, rawMode
3007
3009
  inComment = painted.inComment;
3008
3010
  const used = visualCol(`${no} ${mark} `) + visualCol(painted.text);
3009
3011
  const pad = ' '.repeat(Math.max(0, bodyW - used));
3010
- diffRows.push({ text: lead + painted.text + col(pad, lineBg), ind: cont, raw: true });
3012
+ // The padding is INSIDE the wash, so it must not end with a bare reset: `col()` closes with ESC[0m, which
3013
+ // would drop the background on the last column and leave a strip of page colour at the right edge.
3014
+ diffRows.push({ text: lead + painted.text + lineBg + pad + '\x1b[39m', ind: cont, raw: true });
3011
3015
  emitted++;
3012
3016
  }
3013
3017
  if (total > emitted) {
@@ -5308,25 +5312,45 @@ function applySelectionToRow(lines, idx, sel, w) {
5308
5312
  */
5309
5313
  function highlightAnsiRange(row, c0, c1, w) {
5310
5314
  const s = String(row);
5315
+ const cells = parseCells(s);
5316
+ // The SGR for the background each column was drawn with, or '' when the row has none there.
5317
+ const ownBg = cells.map((_, c) => {
5318
+ const rgb = cellBg(cells, c);
5319
+ return rgb ? `\x1b[48;2;${rgb[0]};${rgb[1]};${rgb[2]}m` : '';
5320
+ });
5321
+ // The theme's selection colour, read from the SGR rather than hardcoded: a light theme has a pale one.
5322
+ const m = /48;2;(\d+);(\d+);(\d+)/.exec(C.selBg);
5323
+ const selRgb = m ? [Number(m[1]), Number(m[2]), Number(m[3])] : null;
5324
+ // The SELECTION WINS. A hint of the row's own wash stays in the mix so a selected deletion still reads as a
5325
+ // deletion, but nine parts selection to one part row — an earlier three-parts-row blend left the diff colour
5326
+ // dominating and the selected range looked like an unselected diff with a tint.
5327
+ const selectedBg = (col) => {
5328
+ const rgb = cellBg(cells, col);
5329
+ if (!rgb || !selRgb) return C.selBg;
5330
+ const mix = (a, b) => Math.round(a * 0.9 + b * 0.1);
5331
+ return `\x1b[48;2;${mix(selRgb[0], rgb[0])};${mix(selRgb[1], rgb[1])};${mix(selRgb[2], rgb[2])}m`;
5332
+ };
5333
+ const lo = Math.max(c0, 1);
5311
5334
  let out = '';
5312
5335
  let col = 0;
5313
5336
  let i = 0;
5314
5337
  let inSel = false;
5315
- // A range that begins at the margin starts one column later.
5316
- const lo = Math.max(c0, 1);
5317
5338
 
5318
5339
  while (i < s.length) {
5319
5340
  if (s[i] === '\x1b') {
5320
- // Emit the escape, then RE-ASSERT the selection background if we are
5321
- // inside the range. The row embeds its own resets (a markdown bold or
5322
- // inline-code span ends in ESC[0m), and a bare ESC[0m cancels the
5323
- // background too — so without re-asserting, everything after the first
5324
- // coloured run inside the selection lost its highlight.
5325
- const m = /^\x1b\[[0-9;?]*[a-zA-Z]/.exec(s.slice(i)) || /^\x1b\[[0-9;?]* [a-zA-Z]/.exec(s.slice(i));
5326
- if (m) {
5327
- out += m[0];
5328
- if (inSel) out += C.selBg;
5329
- i += m[0].length;
5341
+ // Emit the escape, then RE-ASSERT the background for the column it was emitted at: the row embeds its own
5342
+ // resets (a markdown span ends in ESC[0m), and a bare reset clears the background too.
5343
+ const esc = /^\x1b\[[0-9;?]*[a-zA-Z]/.exec(s.slice(i)) || /^\x1b\[[0-9;?]* [a-zA-Z]/.exec(s.slice(i));
5344
+ if (esc) {
5345
+ out += esc[0];
5346
+ // The row writes its OWN background back after every syntax token — `paintCode` re-asserts the diff wash
5347
+ // after each `ESC[0m`. Those SGRs arrive here as ordinary escapes, not resets, so leaving them untouched
5348
+ // let the diff colour overwrite the selection mid-run. Inside the selection, ANY background escape that
5349
+ // follows is replaced by the selected one; outside it, only a reset needs the row's own wash restored.
5350
+ const isBg = /^\x1b\[48;/.test(esc[0]);
5351
+ if (inSel && (isBg || esc[0] === '\x1b[0m' || esc[0] === '\x1b[m')) out += selectedBg(col);
5352
+ else if (!inSel && (esc[0] === '\x1b[0m' || esc[0] === '\x1b[m')) out += ownBg[col] || '';
5353
+ i += esc[0].length;
5330
5354
  continue;
5331
5355
  }
5332
5356
  }
@@ -5336,28 +5360,21 @@ function highlightAnsiRange(row, c0, c1, w) {
5336
5360
  const cw = visualWidth(ch);
5337
5361
  const want = col >= lo && col < c1;
5338
5362
 
5339
- if (want && !inSel) {
5340
- // Selection changes only the BACKGROUND; the foreground (documented colour)
5341
- // is left intact so a cyan/teal markdown span stays its colour inside the
5342
- // highlight.
5343
- out += C.selBg;
5344
- inSel = true;
5345
- } else if (!want && inSel) {
5346
- // Leave the selection: reset just the background (ESC[49m), keeping the
5347
- // row's foreground. A bare reset would also clear the foreground.
5348
- out += C.bgReset;
5363
+ if (want && !inSel) { out += selectedBg(col); inSel = true; }
5364
+ else if (!want && inSel) {
5365
+ // RESTORE the row's own background, not ESC[49m: a diff row is red or green all the way to the right edge,
5366
+ // and clearing the background there left a strip of page colour in the middle of the wash.
5367
+ out += ownBg[col] || C.bgReset;
5349
5368
  inSel = false;
5350
5369
  }
5351
5370
 
5352
5371
  out += ch;
5353
5372
  col += cw;
5354
5373
  i += cp > 0xffff ? 2 : 1;
5355
-
5356
5374
  if (col >= w) break;
5357
5375
  }
5358
5376
 
5359
5377
  if (inSel) out += C.reset;
5360
-
5361
5378
  return out;
5362
5379
  }
5363
5380
 
@@ -9009,6 +9026,19 @@ export async function dispatch(cmdRaw, arg, state, cfg, session, h, submit, stdo
9009
9026
  * Every surface lands here — `/set`, the /settings browser, and the web's setConfig — so
9010
9027
  * they cannot disagree about what a value means or which keys exist.
9011
9028
  */
9029
+ /**
9030
+ * Fire a TUI-side hook and FORGET it. These are notifications, not decisions: a slow or failing hook must not
9031
+ * hold up a permission prompt, a directory move or a settings save. The config is loaded fresh so an edit made
9032
+ * while the session was running is picked up without a restart.
9033
+ */
9034
+ function fireHook(event, payload, ws) {
9035
+ try {
9036
+ const { hooks } = loadHooks(ws);
9037
+ if (!(hooks[event] || []).length) return;
9038
+ void runShellHooks({ hooks }, event, payload, ws).catch(() => {});
9039
+ } catch { /* a broken hook config is a reason to carry on, not to fail the command */ }
9040
+ }
9041
+
9012
9042
  function applySetting(key, value) {
9013
9043
  const def = SETTING_BY_KEY.get(key);
9014
9044
  if (!def) { appErr(`Unknown setting: ${key}. Try /settings.`); return false; }
@@ -9087,6 +9117,7 @@ export async function dispatch(cmdRaw, arg, state, cfg, session, h, submit, stdo
9087
9117
  if (key === 'plan_instructions') cfg.planInstructions = raw;
9088
9118
  if (key === 'focus_instructions') cfg.focusInstructions = raw;
9089
9119
  if (key === 'swarm_instructions') cfg.swarmInstructions = raw;
9120
+ fireHook('ConfigChange', { key, value: coerced.value, source: 'settings' }, state.workspace || cfg.workspace);
9090
9121
  if (typeof renderFrameArg === 'function') renderFrameArg();
9091
9122
  return true;
9092
9123
  }
@@ -12853,6 +12884,7 @@ export async function dispatch(cmdRaw, arg, state, cfg, session, h, submit, stdo
12853
12884
  // paths against `ctx.cwd || ctx.workspace`, which the agent copies from `cfg`
12854
12885
  // each turn. Moving only the status line left Edit/Read/Bash pointed at the
12855
12886
  // directory being left behind.
12887
+ const prevCwd = state.cwd || cfg.workspace;
12856
12888
  state.cwd = target;
12857
12889
  state.workspace = target;
12858
12890
  cfg.workspace = target;
@@ -12869,6 +12901,7 @@ export async function dispatch(cmdRaw, arg, state, cfg, session, h, submit, stdo
12869
12901
  state.steps = session.steps || 0;
12870
12902
  saveSession(session);
12871
12903
  app(`Session moved to: ${target} (${newSession.id})`);
12904
+ fireHook('CwdChanged', { cwd: target, previous: prevCwd }, target);
12872
12905
  return;
12873
12906
  }
12874
12907
 
@@ -13076,7 +13109,7 @@ export async function dispatch(cmdRaw, arg, state, cfg, session, h, submit, stdo
13076
13109
  return;
13077
13110
  }
13078
13111
  const { hooks, errors } = loadHooks(workspace);
13079
- const lines = describeHooks({ hooks });
13112
+ const lines = describeHooks({ hooks }, workspace);
13080
13113
  if (errors.length) lines.push('', 'Config problems:', ...errors.map((e) => ` ! ${e}`));
13081
13114
  h.openPanel('hncode — hooks', lines);
13082
13115
  return;
@@ -14774,6 +14807,8 @@ const agents = readAgentsMd(state.cwd || state.workspace || cfg.workspace, state
14774
14807
  // The prompt must NOT touch the composer: the user may already be typing,
14775
14808
  // and only Enter/Esc belong to the prompt.
14776
14809
  state.approvalPending = { toolName, args, desc, resolve, detail };
14810
+ fireHook('PermissionRequest', { toolName, toolArgs: args, prompt: desc }, state.workspace || cfg.workspace);
14811
+ fireHook('Notification', { type: 'permission_prompt', toolName, prompt: desc }, state.workspace || cfg.workspace);
14777
14812
  viewCur.render();
14778
14813
  });
14779
14814
  };
@@ -15235,6 +15270,7 @@ const agents = readAgentsMd(state.cwd || state.workspace || cfg.workspace, state
15235
15270
  // block renders from the moment the swarm is announced. Every item
15236
15271
  // starts "queued" and flips as the tool reports progress.
15237
15272
  if (e.name === 'AgentSwarm') {
15273
+ fireHook('SubagentStart', { description: (e.args && e.args.description) || '', items: (e.args && e.args.items) || [] }, state.workspace || cfg.workspace);
15238
15274
  const a = entry.toolArgs || {};
15239
15275
  entry.swarmDescription = a.description || '';
15240
15276
  entry.swarmModel = a.subagent_type || '';
@@ -15283,6 +15319,7 @@ const agents = readAgentsMd(state.cwd || state.workspace || cfg.workspace, state
15283
15319
  // straight from that payload — no LCS inference, which mis-paired the context rows
15284
15320
  // into `-`/`+` pairs because the two sides had different shapes.
15285
15321
  entry.diff = editDiffRows(e.editDiff);
15322
+ fireHook('FileChanged', { path: e.editDiff.path || (entry.toolArgs && entry.toolArgs.path), change: 'edit' }, state.workspace || cfg.workspace);
15286
15323
  }
15287
15324
  // Hand the counts to the TOOL row (which keeps `+N -N` next to its
15288
15325
  // name) and the diff to the RESULT row (rendered beneath the `↳`).