@hncode/hncode 0.8.2 → 0.8.4

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.
@@ -25,6 +25,7 @@
25
25
  // instead of after a restart. A malformed file is reported ONCE and then ignored — a typo
26
26
  // must not silently swallow every key the user presses.
27
27
 
28
+ import { uiText, t, getUiLang } from './i18n.js';
28
29
  import fs from 'node:fs';
29
30
  import os from 'node:os';
30
31
  import path from 'node:path';
@@ -239,7 +240,7 @@ export function describeKeybindings(loaded) {
239
240
  if (!loaded.bindings.size) {
240
241
  out.push('No keybindings set.', '', `File: ${loaded.file}`, 'Add one with /keybindings add <key> <key|/command>');
241
242
  } else {
242
- out.push(`Keybindings (${loaded.bindings.size}) — ${loaded.file}`, '');
243
+ out.push(t(getUiLang(), 'keybindings.header', { n: loaded.bindings.size, file: loaded.file }), '');
243
244
  for (const [from, to] of [...loaded.bindings.entries()].sort()) {
244
245
  out.push(` ${from.padEnd(12)} -> ${to.command ? to.command : to.key}`);
245
246
  }
package/src/markdown.js CHANGED
@@ -31,7 +31,7 @@ function loadTex() {
31
31
  }
32
32
  import { encodeImageRow } from './image-row.js';
33
33
  import { terminalCaps } from './term-caps.js';
34
- import { col, visualCol, wrapWords } from './text.js';
34
+ import { col, visualCol, wrapWords, wrapStyled } from './text.js';
35
35
 
36
36
  /**
37
37
  * Mermaid is loaded on first use, not at import.
@@ -46,11 +46,32 @@ import { col, visualCol, wrapWords } from './text.js';
46
46
  */
47
47
  let mermaidMod = null;
48
48
  let mermaidLoading = null;
49
+
50
+ // The repaint hook. The renderer is PURE — it draws and returns — so it cannot ask for a
51
+ // frame itself, and without asking the diagram never appears: the first frame draws the
52
+ // source, the module finishes loading a moment later, and nothing repaints, so the source
53
+ // stays on screen for the rest of the session.
54
+ //
55
+ // The TUI registers its own repaint here at startup. A caller that does not care (a test,
56
+ // a headless render) simply never sees the diagram and keeps the source, which is the
57
+ // honest fallback.
58
+ let mermaidReady = null;
59
+
60
+ /** Ask to be repainted when the mermaid module finishes loading. */
61
+ export function onMermaidReady(fn) {
62
+ mermaidReady = typeof fn === 'function' ? fn : null;
63
+ }
64
+
49
65
  function loadMermaid() {
50
66
  if (mermaidMod) return mermaidMod;
51
67
  if (!mermaidLoading) {
52
68
  mermaidLoading = import('./mermaid/index.js')
53
- .then((m) => { mermaidMod = m; return m; })
69
+ .then((m) => {
70
+ mermaidMod = m;
71
+ // The diagram is drawable now. Repaint, or the source stays on screen forever.
72
+ if (mermaidReady) { try { mermaidReady(); } catch { /* a repaint is not worth failing for */ } }
73
+ return m;
74
+ })
54
75
  .catch(() => { mermaidLoading = null; return null; });
55
76
  }
56
77
  return null; // not ready yet; the caller falls back to the source this frame
@@ -343,19 +364,20 @@ export function renderTable(out, header, body, colCount, width, fg) {
343
364
  };
344
365
  // A cell renders its INLINE MARKDOWN (bold, code, links) — a table of `**name**` and `` `value` `` used to show the
345
366
  // asterisks and backticks verbatim, which is not what the author wrote.
367
+ //
368
+ // RENDER FIRST, WRAP SECOND, for the same reason as the prose renderer: a `**bold**` that
369
+ // straddled a line break matched no pattern and the asterisks were printed as they were
370
+ // written. The wrap is on the RENDERED text, so it measures what the terminal shows.
346
371
  const styled = (text, w, bold) => {
347
- const plain = wrapCell(text, w);
348
372
  const paint = bold ? C.white + C.bold : C.gray;
349
- return plain.map((lineText) => {
350
- // Render the markdown FIRST, then pad the RESULT.
351
- //
373
+ const md = inlineMarkdown(String(text == null ? '' : text), C.gray, bold ? C.white : C.gray);
374
+ return wrapStyled(md, Math.max(1, w)).map((lineText) => {
352
375
  // The pad has to be measured on what the cell will actually PRINT, not on the source: `` `--verbose` `` is 11
353
376
  // characters of source but 9 on screen once the backticks become a colour, so padding by the source width left
354
377
  // the column short by two and every border after it moved left.
355
- const md = inlineMarkdown(lineText, C.gray, bold ? C.white : C.gray);
356
- const printed = visualCol(String(md).replace(/\x1b\[[0-9;]*m/g, ''));
378
+ const printed = visualCol(lineText);
357
379
  const pad = Math.max(0, w - printed);
358
- return col(' ', paint) + col(md, paint) + col(' '.repeat(pad) + ' ', paint);
380
+ return col(' ', paint) + col(lineText, paint) + col(' '.repeat(pad) + ' ', paint);
359
381
  });
360
382
  };
361
383
  const rule = (left, mid, right) => col(left + widths.map((w) => '─'.repeat(w + 2)).join(mid) + right, B);
@@ -437,8 +459,13 @@ export function markdownLineToRows(line, width, fg, codeFg, isContinuation) {
437
459
  }
438
460
  }
439
461
  // Inline styles: **bold**, *italic*, `code`, [text](url), $math$
462
+ //
463
+ // RENDER FIRST, WRAP SECOND. Wrapping the source broke every marker that straddled a line
464
+ // break: a `**bold**` split across two lines matched no pattern, so the asterisks were
465
+ // printed verbatim — a literal `**` in the middle of a sentence. Rendering first turns the
466
+ // markers into colour, and the wrap then measures what the terminal will show.
440
467
  if (/[*`\[$]|\\\(/.test(t)) {
441
- for (const w of wrapWords(t, width)) out.push(col(inlineMarkdown(w, codeFg, fg), fg));
468
+ for (const w of wrapStyled(inlineMarkdown(t, codeFg, fg), width)) out.push(col(w, fg));
442
469
  return out;
443
470
  }
444
471
  // Plain - apply default foreground color
@@ -0,0 +1,409 @@
1
+ // MCP SERVER MODE — hncode as an MCP server, so another agent can drive it.
2
+ //
3
+ // WHY THIS EXISTS
4
+ // ---------------
5
+ // The client half (src/mcp.js) connects hncode to OTHER people's MCP servers and uses
6
+ // their tools. This is the other direction: hncode exposes ITS tools — Read, Edit, Bash,
7
+ // Grep, Glob and the rest — to another agent, over the same protocol.
8
+ //
9
+ // The point is not novelty. A user who already has their editor open in Claude Code or
10
+ // Cursor can point it at the project they are working on and let it use hncode's tools
11
+ // without installing a second copy of the code agent, and without the two agents editing
12
+ // the same files through different rules.
13
+ //
14
+ // WHAT IS SERVED
15
+ // -------------
16
+ // initialize -> capabilities and the protocol version we speak
17
+ // notifications/initialized
18
+ // tools/list -> the toolbelt, with hncode's schemas
19
+ // tools/call -> run one tool
20
+ // ping -> liveness, which some clients use as a health check
21
+ //
22
+ // TRANSPORTS
23
+ // ----------
24
+ // stdio the one every `mcp add` uses: the client starts this process
25
+ // and speaks newline-delimited JSON-RPC over its stdin/stdout
26
+ // http streamable-HTTP: one POST per message, JSON or SSE back
27
+ //
28
+ // NAMES ARE PREFIXED
29
+ // ------------------
30
+ // The other agent already has tools of its own, and a bare `Read` would collide with
31
+ // theirs — or with a tool they expose under a name hncode also uses. Every tool is
32
+ // offered as `hncode_<name>`, and the prefix is stripped on the way in. A client that
33
+ // wants the bare names can ask for them (`--no-prefix`).
34
+ //
35
+ // SAFETY
36
+ // ------
37
+ // The exposed toolbelt is filtered. A tool that can run arbitrary commands or write
38
+ // anywhere is not something to hand to another program by default, so the default set is
39
+ // the read-only one, and the full set needs an explicit flag.
40
+
41
+ import fs from 'node:fs';
42
+ import path from 'node:path';
43
+ import os from 'node:os';
44
+ import http from 'node:http';
45
+
46
+ import { combinedTools, getTool } from './tools/index.js';
47
+
48
+ // The protocol revisions this server speaks, newest first. A client asks for one in
49
+ // `initialize`; the server answers with the same version when it knows it, and with its
50
+ // own latest when it does not — which is what the spec allows and what every client
51
+ // handles.
52
+ export const SUPPORTED_PROTOCOL_VERSIONS = [
53
+ '2025-06-18',
54
+ '2025-03-26',
55
+ '2024-11-05',
56
+ ];
57
+
58
+ export const SERVER_INFO = { name: 'hncode', version: '0.8.2' };
59
+
60
+ // The tools that only READ. This is the default set: an outside agent can look at the
61
+ // project without being able to change it.
62
+ const READ_ONLY_TOOLS = new Set([
63
+ 'Read', 'Grep', 'Glob', 'FileLines', 'WebSearch', 'FetchUrl',
64
+ 'ListMcpServers', 'GetAppState', 'ListWindows', 'ListApps', 'GetScreenSize',
65
+ 'ListDisplays', 'GetUITree', 'FindElement', 'GetElementInfo', 'GetFocusedElement',
66
+ 'ReadScreenText', 'ReadPixel', 'GetCursorPos', 'ClipboardRead', 'TaskList',
67
+ 'TaskOutput', 'Memory', 'Goal', 'ListSkills', 'Skills',
68
+ ]);
69
+
70
+ /**
71
+ * The toolbelt this server offers.
72
+ *
73
+ * `mode` is 'read' (the default), 'full' (everything) or 'write' (everything that
74
+ * changes a file, but not the ones that run commands).
75
+ */
76
+ export function selectableTools(mode = 'read') {
77
+ const all = combinedTools();
78
+ if (mode === 'full') return all;
79
+ if (mode === 'write') {
80
+ return all.filter((t) => !/^Bash$|Shell|Execute|Run/i.test(t.name));
81
+ }
82
+ return all.filter((t) => READ_ONLY_TOOLS.has(t.name));
83
+ }
84
+
85
+ /** The MCP name for a tool: `hncode_Read`, or `Read` without the prefix. */
86
+ export function externalName(name, prefix = 'hncode_') {
87
+ return prefix ? prefix + name : name;
88
+ }
89
+
90
+ /** The internal name for an exposed tool: strips the prefix. */
91
+ export function internalName(name, prefix = 'hncode_') {
92
+ return prefix && name.startsWith(prefix) ? name.slice(prefix.length) : name;
93
+ }
94
+
95
+ /**
96
+ * Build the `tools/list` payload.
97
+ *
98
+ * The schema is the tool's own JSON Schema, with the hncode-only extras removed: a
99
+ * client renders the schema as a tool definition and has no idea what `_` fields mean.
100
+ */
101
+ export function toolListPayload(mode = 'read', prefix = 'hncode_') {
102
+ return {
103
+ tools: selectableTools(mode).map((t) => ({
104
+ name: externalName(t.name, prefix),
105
+ description: String(t.description || t.name),
106
+ inputSchema: normaliseSchema(t.parameters),
107
+ })),
108
+ };
109
+ }
110
+
111
+ // Strip the properties the model never sees and the clients cannot type: the internal
112
+ // flags hncode adds to its own schemas.
113
+ function normaliseSchema(parameters) {
114
+ const p = parameters && typeof parameters === 'object' ? parameters : {};
115
+ const schema = JSON.parse(JSON.stringify(p));
116
+ if (schema.properties) {
117
+ for (const key of Object.keys(schema.properties)) {
118
+ if (key.startsWith('_')) delete schema.properties[key];
119
+ }
120
+ }
121
+ if (!schema.type) schema.type = 'object';
122
+ return schema;
123
+ }
124
+
125
+ /**
126
+ * The result of one tool call, in the shape MCP defines.
127
+ *
128
+ * A tool that returns a plain string becomes one text block. A tool that returns a
129
+ * structured result — `{ text, media }`, which is how an image travels — keeps both:
130
+ * the text block and the image blocks, so the calling agent SEES the picture.
131
+ */
132
+ export function contentBlocks(result) {
133
+ if (result == null) return [{ type: 'text', text: '' }];
134
+ if (typeof result === 'string') return [{ type: 'text', text: result }];
135
+ if (Array.isArray(result)) {
136
+ return result.map((r) => (typeof r === 'string' ? { type: 'text', text: r } : r));
137
+ }
138
+ const blocks = [];
139
+ const text = typeof result.text === 'string' ? result.text : JSON.stringify(result);
140
+ if (text) blocks.push({ type: 'text', text });
141
+ if (Array.isArray(result.media)) {
142
+ for (const m of result.media) {
143
+ if (!m || !m.data) continue;
144
+ blocks.push({ type: 'image', data: m.data, mimeType: m.mimeType || 'image/png' });
145
+ }
146
+ }
147
+ return blocks.length ? blocks : [{ type: 'text', text: '' }];
148
+ }
149
+
150
+ /** The JSON-RPC envelope for a successful reply. */
151
+ function ok(id, result) {
152
+ return { jsonrpc: '2.0', id, result };
153
+ }
154
+
155
+ /** The JSON-RPC envelope for a failed call. */
156
+ function fail(id, code, message, data) {
157
+ const error = { code, message };
158
+ if (data !== undefined) error.data = data;
159
+ return { jsonrpc: '2.0', id, error };
160
+ }
161
+
162
+ // JSON-RPC error codes used here.
163
+ const PARSE_ERROR = -32700;
164
+ const INVALID_REQUEST = -32600;
165
+ const METHOD_NOT_FOUND = -32601;
166
+ const INVALID_PARAMS = -32602;
167
+ const INTERNAL_ERROR = -32603;
168
+
169
+ /**
170
+ * Handle one JSON-RPC request. Returns the reply, or null for a notification.
171
+ *
172
+ * `ctx` is what the tools receive: the same shape the agent hands them, so a tool
173
+ * behaves identically whether hncode's own model or an outside agent called it.
174
+ */
175
+ export async function handleRequest(req, opts = {}) {
176
+ const mode = opts.mode || 'read';
177
+ const prefix = opts.prefix === undefined ? 'hncode_' : opts.prefix;
178
+ const ctx = opts.ctx || {};
179
+
180
+ if (!req || typeof req !== 'object') {
181
+ return fail(null, INVALID_REQUEST, 'the request is not a JSON-RPC object');
182
+ }
183
+ const { id, method, params } = req;
184
+ // A notification has no id and expects no answer.
185
+ const isNotification = id === undefined || id === null;
186
+
187
+ switch (method) {
188
+ case 'initialize': {
189
+ const asked = params && params.protocolVersion;
190
+ const version = SUPPORTED_PROTOCOL_VERSIONS.includes(asked)
191
+ ? asked
192
+ : SUPPORTED_PROTOCOL_VERSIONS[0];
193
+ return ok(id, {
194
+ protocolVersion: version,
195
+ capabilities: {
196
+ // The tools capability is all this server has. `resources` and `prompts` are
197
+ // NOT claimed: claiming a capability a server does not implement makes a
198
+ // client call it and wait for an answer that never comes.
199
+ tools: { listChanged: false },
200
+ logging: {},
201
+ },
202
+ serverInfo: SERVER_INFO,
203
+ instructions: 'hncode tools operate on the workspace of the hncode session that started this server. '
204
+ + 'Paths are resolved inside that workspace.',
205
+ });
206
+ }
207
+ case 'notifications/initialized':
208
+ case 'notifications/cancelled':
209
+ return null;
210
+ case 'ping':
211
+ return ok(id, {});
212
+ case 'tools/list': {
213
+ const payload = toolListPayload(mode, prefix);
214
+ // Pagination: the spec allows a server to page, and a client that follows
215
+ // `nextCursor` must be answered with one. hncode's toolbelt is small enough to
216
+ // send in one page, so there is never a cursor — but a client that sends a cursor
217
+ // gets an empty list rather than an error, which is what the spec asks for.
218
+ const cursor = params && params.cursor;
219
+ if (cursor) return ok(id, { tools: [] });
220
+ return ok(id, payload);
221
+ }
222
+ case 'tools/call': {
223
+ const name = internalName((params && params.name) || '', prefix);
224
+ const args = (params && params.arguments) || {};
225
+ const tool = getTool(name);
226
+ if (!tool) {
227
+ return fail(id, INVALID_PARAMS, `unknown tool "${name}"`);
228
+ }
229
+ // A TOOL THAT WAS NOT OFFERED CANNOT BE CALLED.
230
+ //
231
+ // The list is the contract: a client is told what exists and calls that. Without
232
+ // this check a client could name a tool that was never listed — `hncode_Bash` in the
233
+ // read-only set, for instance — and the server would run it. The set that was
234
+ // offered is what decides, not what the tool table happens to contain.
235
+ if (!selectableTools(mode).some((t) => t.name === name)) {
236
+ return fail(id, INVALID_PARAMS,
237
+ `"${name}" is not available in this session's tool set`);
238
+ }
239
+ try {
240
+ const result = await tool.execute(args, ctx);
241
+ return ok(id, { content: contentBlocks(result), isError: false });
242
+ } catch (e) {
243
+ // A tool that throws is a tool that failed, not a broken protocol: the failure
244
+ // is reported IN the result so the calling agent can read it and act.
245
+ return ok(id, {
246
+ content: [{ type: 'text', text: `Error: ${(e && e.message) || e}` }],
247
+ isError: true,
248
+ });
249
+ }
250
+ }
251
+ default:
252
+ if (isNotification) return null;
253
+ return fail(id, METHOD_NOT_FOUND, `unknown method "${method}"`);
254
+ }
255
+ }
256
+
257
+ /**
258
+ * Parse a line of JSON-RPC and answer it.
259
+ *
260
+ * Returns null when the line is not a request (a notification, or noise), and the reply
261
+ * otherwise. Malformed JSON gets an error reply rather than silence, so a client that sent
262
+ * something broken learns about it.
263
+ */
264
+ export async function handleLine(line, opts = {}) {
265
+ const text = String(line || '').trim();
266
+ if (!text) return null;
267
+ let req;
268
+ try {
269
+ req = JSON.parse(text);
270
+ } catch (e) {
271
+ return { jsonrpc: '2.0', id: null, error: { code: PARSE_ERROR, message: `invalid JSON: ${e.message}` } };
272
+ }
273
+ return handleRequest(req, opts);
274
+ }
275
+
276
+ // ---- stdio transport ---------------------------------------------------------
277
+
278
+ /**
279
+ * Serve MCP over stdin/stdout.
280
+ *
281
+ * The framing is newline-delimited JSON — NOT the Content-Length headers of LSP. Mixing
282
+ * the two is the classic way this breaks, and the comment belongs where somebody will
283
+ * look when it does.
284
+ *
285
+ * stdout carries the protocol and NOTHING else: a stray `console.log` in this process
286
+ * would corrupt the stream. Diagnostics go to stderr.
287
+ */
288
+ export function serveStdio(opts = {}) {
289
+ const write = opts.write || ((line) => process.stdout.write(line + '\n'));
290
+ let buffer = '';
291
+ let chain = Promise.resolve();
292
+
293
+ const onData = (chunk) => {
294
+ buffer += chunk.toString('utf8');
295
+ let i;
296
+ while ((i = buffer.indexOf('\n')) >= 0) {
297
+ const line = buffer.slice(0, i);
298
+ buffer = buffer.slice(i + 1);
299
+ chain = chain.then(async () => {
300
+ const reply = await handleLine(line, opts);
301
+ if (reply) write(JSON.stringify(reply));
302
+ }).catch((e) => {
303
+ try { write(JSON.stringify(fail(null, INTERNAL_ERROR, String((e && e.message) || e)))); } catch { /* stdout is gone */ }
304
+ });
305
+ }
306
+ };
307
+
308
+ process.stdin.on('data', onData);
309
+ process.stdin.on('end', () => { /* the client closed the connection */ });
310
+ // RESUME, or the process exits.
311
+ //
312
+ // A `data` listener alone does not keep the event loop alive when stdin is a pipe: Node
313
+ // treats an un-resumed, un-ended stdin as nothing to wait for, finds no other work, and
314
+ // exits — the server printed its banner and died before the client said anything. The
315
+ // resume is what holds the loop open until the client closes the connection.
316
+ try { process.stdin.resume(); } catch { /* already flowing */ }
317
+ return {
318
+ close() { try { process.stdin.off('data', onData); } catch { /* already off */ } },
319
+ };
320
+ }
321
+
322
+ // ---- HTTP transport ----------------------------------------------------------
323
+
324
+ /**
325
+ * Serve MCP over streamable-HTTP.
326
+ *
327
+ * One POST per JSON-RPC message. The reply is JSON, unless the client asked for an SSE
328
+ * stream, in which case it is the same message wrapped in a `data:` frame — which is
329
+ * what the spec's streamable transport allows.
330
+ *
331
+ * A GET opens an SSE stream for server-initiated messages; this server has none, so the
332
+ * stream is opened and left empty, which is a legal no-op.
333
+ */
334
+ export function createHttpServer(opts = {}) {
335
+ const sessions = new Map();
336
+
337
+ const server = http.createServer(async (req, res) => {
338
+ const origin = req.headers.origin;
339
+ // A browser page on another origin must not be able to drive this endpoint.
340
+ if (origin && opts.allowedOrigins && !opts.allowedOrigins.includes(origin)) {
341
+ res.writeHead(403).end();
342
+ return;
343
+ }
344
+ if (req.method === 'GET') {
345
+ res.writeHead(200, {
346
+ 'content-type': 'text/event-stream',
347
+ 'cache-control': 'no-cache',
348
+ connection: 'keep-alive',
349
+ });
350
+ return; // no server-initiated messages: an empty stream
351
+ }
352
+ if (req.method !== 'POST') {
353
+ res.writeHead(405, { allow: 'GET, POST' }).end();
354
+ return;
355
+ }
356
+ let body = '';
357
+ for await (const chunk of req) body += chunk;
358
+ const reply = await handleLine(body, opts);
359
+ if (!reply) {
360
+ // A notification: the client does not expect a body.
361
+ res.writeHead(202).end();
362
+ return;
363
+ }
364
+ const sid = req.headers['mcp-session-id'];
365
+ if (sid) sessions.set(sid, true);
366
+ const headers = { 'content-type': 'application/json' };
367
+ if (sid) headers['mcp-session-id'] = sid;
368
+ const wantsSse = String(req.headers.accept || '').includes('text/event-stream');
369
+ if (wantsSse) {
370
+ res.writeHead(200, { ...headers, 'content-type': 'text/event-stream' });
371
+ res.write(`data: ${JSON.stringify(reply)}\n\n`);
372
+ res.end();
373
+ return;
374
+ }
375
+ res.writeHead(200, headers);
376
+ res.end(JSON.stringify(reply));
377
+ });
378
+
379
+ return server;
380
+ }
381
+
382
+ /** Listen on `port` (0 picks a free one). Resolves with the address. */
383
+ export function listen(server, port, host = '127.0.0.1') {
384
+ return new Promise((resolve, reject) => {
385
+ server.once('error', reject);
386
+ server.listen(port, host, () => {
387
+ const a = server.address();
388
+ resolve({ port: a && typeof a === 'object' ? a.port : port, host });
389
+ });
390
+ });
391
+ }
392
+
393
+ // ---- the config a client needs -----------------------------------------------
394
+
395
+ /**
396
+ * The JSON another agent's config file needs.
397
+ *
398
+ * The shape is the one every client reads: `mcpServers`, then `command`/`args` for a
399
+ * stdio server. `env` carries the workspace, because the server has to know WHICH project
400
+ * to work in and the client starts it from wherever the user happens to be.
401
+ */
402
+ export function clientConfig({ command = process.execPath, args = [], workspace = process.cwd(), name = 'hncode' } = {}) {
403
+ const entry = {
404
+ command,
405
+ args: [...args, 'mcp', 'serve', '--stdio'],
406
+ env: { HNCODE_WORKSPACE: workspace },
407
+ };
408
+ return { mcpServers: { [name]: entry } };
409
+ }