@hncode/hncode 0.8.2 → 0.8.3

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/src/index.js CHANGED
@@ -1,731 +1,823 @@
1
- // hncode entry: CLI arg parsing, subcommands, headless -p mode, and TUI dispatch.
2
-
3
- import os from 'node:os';
4
- import path from 'node:path';
5
- import fs from 'node:fs';
6
- import { resolveConfig, effectiveSnapshot, saveConfig, resolveModelArg, readPersonalPrompt } from './config.js';
7
- import * as sess from './session.js';
8
- import { Agent, SYSTEM_PROMPT, canSplitAfter } from './agent.js';
9
- import { llmTools } from './tools/index.js';
10
- import { localVersion } from './version.js';
11
- import { EXIT, FORMATS, isValidFormat, buildResult, exitCodeFor, resultLine, createRunTracker, trackEvent, finalReply } from './ci.js';
12
-
13
- // The version shown by `hncode -V` and the help banner. Read from package.json
14
- // (via version.js) so it can never drift from the published version again.
15
- export const VERSION = localVersion();
16
-
17
- const HELP = `hncode ${VERSION} — a Kimi Code-style coding agent.
18
-
19
- Usage: hncode [options] [command]
20
-
21
- Cyan-blue TUI for long agent sessions. OpenAI + Anthropic streaming,
22
- MCP-style toolbelt (Edit, Read, Write, Bash, Glob, Grep, TodoList, ...).
23
-
24
- Options:
25
- -V, --version output the version number
26
- -S, --session [id] Resume a session (with id) or pick interactively.
27
- -c, --continue Continue the previous session for this directory.
28
- -y, --yolo Yolo mode: routine edits/commands run; risky actions still ask.
29
- --auto Auto mode: never ask; everything runs automatically.
30
- -m, --model <model> Model alias to use for this invocation.
31
- -p, --prompt <prompt> Run one prompt non-interactively and print the reply.
32
- --output-format <format> Prompt mode output: text (default), json, or stream-json.
33
- json prints one result object; stream-json streams events then a result.
34
- Exit code reflects the outcome: 0 ok, 1 failure, 2 config, 3 no answer, 4 interrupted.
35
- --control Expose a local control socket (prompt/status/interrupt) while the TUI runs.
36
- --timeout <seconds> Prompt mode: abort the run after this many seconds (default: no limit).
37
- --retries <n> Prompt mode: HTTP retries per request before failing (default: 3).
38
- --control <path> Same, at an explicit socket path.
39
- --web Serve this session to a browser on 127.0.0.1 (random port).
40
- --web [ip][:port] Same, on a chosen address/port (e.g. --web 0.0.0.0:8080).
41
- --plan Start in plan mode (research only, no writes).
42
- --plan Start in plan mode (research only, no writes).
43
- --add-dir <dir> Add an additional workspace directory. Repeatable.
44
- -h, --help Show help.
45
-
46
- Commands:
47
- session list List sessions, most recent first.
48
- provider list Show configured providers.
49
- doctor [config] [path] Environment self-check (default), or validate a config.toml.
50
- init Create ~/.hncode/config.toml with defaults.
51
- export [id] Export a session to ~/.hncode/export/<id>.json.
52
- backup [path] Archive ALL state (sessions, settings, skills, plugins, memory) for another machine.
53
- restore <path> Read a backup. Sessions are placed by the index.yml inside it.
54
- --index <file> use an edited copy; --no-index keep recorded paths;
55
- --workspace <dir> repoint every session; --overwrite; --dry-run.
56
- control status Ask a running session (started with --control) for its status.
57
- control prompt <text> Queue a prompt on a running session.
58
- control interrupt Interrupt the running turn.
59
- hooks list Show configured shell hooks.
60
- skills list List installed skills.
61
- mcp list Show configured MCP servers.
62
- `;
63
-
64
- function printHelp() { process.stdout.write(HELP); }
65
-
66
- // ---- minimal argv parsing ----
67
- export function parseArgs(argv) {
68
- const out = { positional: [], flags: {} };
69
- for (let i = 0; i < argv.length; i++) {
70
- const a = argv[i];
71
- if (a.startsWith('--')) {
72
- const eq = a.indexOf('=');
73
- let key, val;
74
- if (eq >= 0) { key = a.slice(2, eq); val = a.slice(eq + 1); }
75
- else { key = a.slice(2); val = null; }
76
- if (key === 'resume') key = 'session'; // `--resume <id>` is an alias for `--session <id>`
77
- if (['session', 'control', 'web'].includes(key) && val === null) { const nx = argv[i + 1]; out[key] = nx !== undefined && !nx.startsWith('-') ? (i++, nx) : true; }
78
- // FLAGS THAT TAKE A VALUE. `--workspace` and `--index` are here for `hncode restore`: without them the path was
79
- // left in `positional` and the flag itself became `true`, so the restore would have repointed every session at the
80
- // string "true".
81
- else if (key === 'model' || key === 'prompt' || key === 'output-format' || key === 'add-dir' || key === 'timeout' || key === 'retries' || key === 'workspace' || key === 'index') {
82
- if (val === null) {
83
- const nx = argv[i + 1];
84
- // Only consume the next token if it is a real value, not another flag
85
- // or the end of argv. Previously `--model -y` and a trailing `--model`
86
- // swallowed or mangled the value, breaking the real flag.
87
- val = (nx !== undefined && !nx.startsWith('-')) ? argv[++i] : undefined;
88
- }
89
- out[key] = (key === 'add-dir' && val !== undefined)
90
- ? (out[key] || []).concat([val])
91
- : val;
92
- } else if (val !== null) { out[key] = val === 'true' ? true : val === 'false' ? false : val; }
93
- else out[key] = true;
94
- } else if (a.startsWith('-') && a.length > 1) {
95
- const key = a.slice(1);
96
- const short = { V: 'version', S: 'session', c: 'continue', y: 'yolo', auto: 'auto', m: 'model', p: 'prompt', h: 'help' };
97
- if (key === 'S' || key === 'm' || key === 'p') {
98
- const nx = argv[i + 1];
99
- // Take the next token as the value only if it exists and is not another
100
- // flag. Previously `-S -y` swallowed `-y` as the session id and a bare
101
- // trailing `-m` became undefined; both silently broke the real flag.
102
- const hasVal = nx !== undefined && !nx.startsWith('-');
103
- if (hasVal) { out[short[key]] = argv[i + 1]; i++; }
104
- else if (key === 'S') { out.session = true; } // "-S" with no id => pick interactively
105
- // '-m' / '-p' with no usable value: leave unset (same as a missing arg).
106
- } else out[short[key]] = true;
107
- } else {
108
- out.positional.push(a);
109
- }
110
- }
111
- return out;
112
- }
113
-
114
- // ---- subcommands ----
115
- function cmdSessionList(args) {
116
- const items = sess.listSessions();
117
- if (items.length === 0) { console.log('No sessions yet.'); return 0; }
118
- for (const s of items.slice(0, 30)) {
119
- const when = new Date(s.updatedAt || 0).toISOString().slice(0, 19).replace('T', ' ');
120
- const title = (s.title || '(untitled)').replace(/\n/g, ' ');
121
- console.log(`${s.id.padEnd(20)} ${when} ${title}`);
122
- }
123
- return 0;
124
- }
125
- function cmdProviderList() {
126
- const cfg = resolveConfig();
127
- const provs = (cfg.raw.providers) || {};
128
- const models = (cfg.raw.models) || {};
129
- const counts = {};
130
- for (const m of Object.values(models)) if (m.provider) counts[m.provider] = (counts[m.provider] || 0) + 1;
131
- const names = Object.keys(provs).length ? Object.keys(provs) : [cfg.provider];
132
- for (const name of names) {
133
- const p = provs[name];
134
- const url = p ? (p.base_url || p.baseUrl || '') : cfg.baseUrl;
135
- console.log(`${name} (${counts[name] || 0} models) ${url}`);
136
- }
137
- console.log(`active: ${cfg.provider} / ${cfg.model}`);
138
- return 0;
139
- }
140
- async function cmdDoctorConfig(p) {
141
- let file = p;
142
- if (!file) {
143
- const home = os.homedir();
144
- for (const f of [process.env.HNCODE_CONFIG, path.join(home, '.hncode', 'config.toml')]) {
145
- if (f && fs.existsSync(f)) { file = f; break; }
146
- }
147
- file = file || path.join(home, '.hncode', 'config.toml');
148
- console.log(`No path given; validated: ${file}`);
149
- }
150
- try {
151
- const txt = fs.readFileSync(file, 'utf8');
152
- const { parse } = await import('./toml.js');
153
- parse(txt);
154
- console.log(`OK: ${file} is valid TOML.`);
155
- return 0;
156
- } catch (e) {
157
- console.error(`INVALID: ${file}: ${e.message}`);
158
- return 1;
159
- }
160
- }
161
-
162
- // `hncode doctor` — environment self-check. Answers "will hncode actually work in
163
- // THIS terminal?" for the things that silently break it: too-old Node, a non-TTY
164
- // or odd terminal, Windows consoles that do not forward mouse sequences, a missing
165
- // git, an unreadable config. Every line is OK / WARN / FAIL so one paste answers a
166
- // support question.
167
- async function cmdDoctorEnv() {
168
- const rows = [];
169
- const add = (level, label, detail) => rows.push({ level, label, detail });
170
-
171
- const major = Number(process.versions.node.split('.')[0]);
172
- if (major >= 22) add('OK', 'node', process.version);
173
- else if (major >= 20) add('WARN', 'node', process.version + ' — 20/21 work, but 22+ has TTY fixes');
174
- else add('FAIL', 'node', process.version + ' — hncode needs Node >= 20');
175
-
176
- add('OK', 'platform', process.platform + ' ' + os.release());
177
- const isWin = process.platform === 'win32';
178
- const term = process.env.TERM || '';
179
- const wt = process.env.WT_SESSION ? 'windows-terminal' : (process.env.TERM_PROGRAM || (isWin ? 'conhost/other' : 'unknown'));
180
- add(process.stdout.isTTY ? 'OK' : 'WARN', 'stdout isatty', process.stdout.isTTY ? 'yes' : 'no — colors/mouse assume a real terminal');
181
- add('OK', 'terminal', wt + (term ? ' (TERM=' + term + ')' : ''));
182
- if (isWin && !process.env.WT_SESSION) {
183
- add('WARN', 'mouse', 'not inside Windows Terminal (WT_SESSION unset); some consoles do not forward mouse input');
184
- }
185
- add('OK', 'truecolor', (process.env.COLORTERM === 'truecolor' || /256color|truecolor/.test(term)) ? 'yes' : 'no — 256-color fallback in use');
186
-
187
- try {
188
- const { spawnSync } = await import('node:child_process');
189
- const r = spawnSync('git', ['--version'], { encoding: 'utf8' });
190
- add(r.status === 0 ? 'OK' : 'WARN', 'git', r.status === 0 ? String(r.stdout).trim() : 'not found — git tools limited');
191
- } catch { add('WARN', 'git', 'not found on PATH'); }
192
-
193
- const cfgFile = process.env.HNCODE_CONFIG || path.join(os.homedir(), '.hncode', 'config.toml');
194
- if (!fs.existsSync(cfgFile)) {
195
- add('WARN', 'config', 'no file at ' + cfgFile + ' (run hncode init)');
196
- } else {
197
- try {
198
- const { parse } = await import('./toml.js');
199
- parse(fs.readFileSync(cfgFile, 'utf8'));
200
- add('OK', 'config', cfgFile);
201
- } catch (e) {
202
- add('FAIL', 'config', cfgFile + ': ' + e.message);
203
- }
204
- }
205
-
206
- try {
207
- const cfg = resolveConfig();
208
- const model = cfg.innerModel || cfg.model;
209
- add(model ? 'OK' : 'WARN', 'model', model || 'none configured (run /model or set default_model)');
210
- add(cfg.apiKey ? 'OK' : 'WARN', 'api key', cfg.apiKey ? 'set' : 'missing — requests will 401');
211
- } catch (e) {
212
- add('WARN', 'config resolve', e.message);
213
- }
214
-
215
- try {
216
- const dir = path.join(os.homedir(), '.hncode', 'plugins');
217
- const n = fs.existsSync(dir) ? fs.readdirSync(dir).filter((x) => fs.statSync(path.join(dir, x)).isDirectory()).length : 0;
218
- add('OK', 'plugins', n + ' installed (' + dir + ')');
219
- } catch { /* ignore */ }
220
-
221
- const order = { FAIL: 0, WARN: 1, OK: 2 };
222
- rows.sort((a, b) => order[a.level] - order[b.level]);
223
- console.log('hncode doctor — environment check\n');
224
- for (const r of rows) console.log(' [' + r.level.padEnd(4) + '] ' + r.label.padEnd(16) + ' ' + r.detail);
225
- const fails = rows.filter((r) => r.level === 'FAIL').length;
226
- console.log('\n' + (fails ? fails + ' problem(s) found' : 'No blocking problems found.'));
227
- return fails ? 1 : 0;
228
- }
229
-
230
-
231
- function cmdInit() {
232
- const cfg = resolveConfig();
233
- const target = path.join(os.homedir(), '.hncode', 'config.toml');
234
- fs.mkdirSync(path.dirname(target), { recursive: true });
235
- const lines = [
236
- `# hncode configuration`,
237
- `default_model = "${cfg.raw.default_model || 'gpt-4o-mini'}"`,
238
- ``,
239
- `# Or set these directly:`,
240
- `# base_url = "${cfg.baseUrl}"`,
241
- `# protocol = "openai" # or "anthropic"`,
242
- `# max_context_size = 128000`,
243
- `# max_output_size = 4096`,
244
- ];
245
- if (!fs.existsSync(target)) {
246
- fs.writeFileSync(target, lines.join('\n') + '\n', 'utf8');
247
- console.log(`Created ${target}`);
248
- } else {
249
- console.log(`Already exists: ${target}`);
250
- }
251
- return 0;
252
- }
253
-
254
- function cmdExport(id) {
255
- const s = id ? sess.loadSession(id) : sess.latestSession(process.cwd());
256
- if (!s) { console.error('No session found.'); return 1; }
257
- const exportDir = path.join(os.homedir(), '.hncode', 'export');
258
- fs.mkdirSync(exportDir, { recursive: true });
259
- const out = path.join(exportDir, `${s.id}.json`);
260
- fs.writeFileSync(out, JSON.stringify(s, null, 2), 'utf8');
261
- console.log(`Exported ${s.id} -> ${out}`);
262
- return 0;
263
- }
264
-
265
- // ---- migration: every piece of state, to another machine -------------------
266
- //
267
- // `hncode backup [path]` writes one archive of everything a person made: sessions, settings, skills, plugins, memory.
268
- // `hncode restore <path>` reads it back, with `--workspace <dir>` to repoint the imported sessions, `--overwrite` to
269
- // replace what is already here, and `--dry-run` to see what would happen first.
270
- //
271
- // Debug logs and the plugin browser's Chromium profile are deliberately excluded — see EXCLUDED in src/migrate.js.
272
- async function cmdBackup(dest) {
273
- const mig = await import('./migrate.js');
274
- const home = mig.hncodeHome();
275
- const items = mig.planExport(home);
276
- if (!items.length) {
277
- console.error(`nothing to migrate: ${home} holds none of the portable entries`);
278
- return 1;
279
- }
280
- const total = items.reduce((n, i) => n + i.size, 0);
281
- const out = dest ? path.resolve(String(dest))
282
- : path.join(process.cwd(), `hncode-backup-${new Date().toISOString().slice(0, 10)}.hnb`);
283
- console.log(`exporting ${items.length} item(s), ${mig.fmtBytes(total)}, from ${home}`);
284
- for (const i of items) console.log(` ${mig.fmtBytes(i.size).padStart(9)} ${i.name}${i.kind === 'dir' ? '/' : ''} — ${i.what}`);
285
- console.log(` (left behind: ${mig.EXCLUDED.map((e) => e.name).join(', ')})`);
286
- let last = 0;
287
- const res = mig.writeArchive(out, {
288
- home,
289
- items,
290
- onProgress: (done, all) => {
291
- // A line every 10% keeps a 190 MB export from looking frozen without flooding the terminal.
292
- const pct = Math.floor((done / all) * 10) * 10;
293
- if (pct > last) { last = pct; process.stderr.write(` ${pct}%\r`); }
294
- },
295
- });
296
- console.log(``);
297
- console.log(`wrote ${res.path}`);
298
- console.log(` ${res.files} files, ${mig.fmtBytes(res.bytes)}`);
299
- console.log(`On the other machine: hncode restore ${path.basename(res.path)}`);
300
- return 0;
301
- }
302
-
303
- async function cmdRestore(from, args = {}) {
304
- const mig = await import('./migrate.js');
305
- if (!from) { console.error('restore needs an archive: hncode restore <file.hnb> [--workspace <dir>] [--overwrite] [--dry-run]'); return 1; }
306
- const src = path.resolve(String(from));
307
- let head;
308
- try { head = mig.readArchiveManifest(src); } catch (e) { console.error(`cannot read ${src}: ${e.message}`); return 1; }
309
- const { manifest } = head;
310
- const home = mig.hncodeHome();
311
- const bytes = manifest.files.reduce((n, f) => n + f.size, 0);
312
- console.log(`archive: ${src}`);
313
- console.log(` created ${new Date(manifest.createdAt).toISOString()}, ${manifest.files.length} files, ${mig.fmtBytes(bytes)}`);
314
- console.log(` from ${manifest.home || '(unknown)'}`);
315
- console.log(` into ${home}`);
316
- // THE INDEX IS THE POINT OF THIS FLAG. Without it the archive's own `index.yml` is used when present, which is what
317
- // makes an exported-then-edited file worth having. `--index <file>` points at a copy edited OUTSIDE the archive, and
318
- // `--no-index` ignores it so the recorded paths are kept verbatim.
319
- const opts = {
320
- home,
321
- overwrite: !!args.overwrite,
322
- workspace: args.workspace,
323
- dryRun: !!args['dry-run'],
324
- // DEFAULT IS ON: an archive's own index.yml is used unless `--no-index` says otherwise. `--index <file>` replaces it
325
- // with an edited copy.
326
- index: args['no-index'] ? false : true,
327
- indexFile: typeof args.index === 'string' ? args.index : undefined,
328
- };
329
- if (opts.workspace) console.log(` sessions repointed at ${path.resolve(String(opts.workspace))} (--workspace overrides the index)`);
330
- else if (!opts.index) console.log(' --no-index: paths stay exactly as recorded');
331
- else if (opts.indexFile) console.log(` mapping read from ${path.resolve(String(opts.indexFile))}`);
332
- else console.log(' sessions are placed by the index.yml inside the archive, if it has one');
333
- if (opts.dryRun) console.log(' (dry run — nothing is written)');
334
- let res;
335
- try { res = mig.readArchive(src, opts); } catch (e) { console.error(`restore failed: ${e.message}`); return 1; }
336
- console.log(` ${opts.dryRun ? 'would write' : 'wrote'} ${res.written} file(s), ${mig.fmtBytes(res.bytes)}`);
337
- if (res.skipped) console.log(` kept ${res.skipped} existing file(s) — pass --overwrite to replace them`);
338
- if (res.mapped) console.log(` ${res.mapped} session(s) moved by the mapping`);
339
- else if (res.sessionsRewritten) console.log(` ${res.sessionsRewritten} session(s) repointed`);
340
- if (opts.index !== false && !res.indexFound) console.log(' no index.yml in the archive (an older backup) — paths left as recorded');
341
- for (const e of res.errors.slice(0, 5)) console.error(` ! ${e}`);
342
- if (res.errors.length > 5) console.error(` ! … and ${res.errors.length - 5} more`);
343
- return res.errors.length ? 1 : 0;
344
- }
345
-
346
- const SUBCOMMANDS = {
347
- 'session': { 'list': cmdSessionList },
348
- 'provider': { 'list': cmdProviderList },
349
- 'doctor': { 'config': cmdDoctorConfig },
350
- 'init': cmdInit,
351
- 'export': cmdExport,
352
- // MIGRATION. `export` above writes ONE session as Markdown; these move the whole hncode state — every session,
353
- // the settings, skills, plugins, memory — to another machine. Different jobs, so different names.
354
- //
355
- // BOTH ARE `{ run }` ENTRIES, NOT BARE FUNCTIONS. The dispatcher treats a second positional word as the SUBCOMMAND of
356
- // the first (`session list`), and for these it is just the path — `backup /tmp/x.hnb` was being read as the subcommand
357
- // `/tmp/x.hnb` of `backup`, which does not exist, so it printed the help and did nothing.
358
- 'backup': { run: cmdBackup },
359
- 'restore': { run: cmdRestore },
360
- control: {
361
- // Subcommands pass only positional[2] to their handler, so bind the op.
362
- 'status': (rest) => cmdControl('status', rest),
363
- 'prompt': (rest) => cmdControl('prompt', rest),
364
- 'interrupt': (rest) => cmdControl('interrupt', rest),
365
- },
366
- };
367
-
368
- // ---- control (talk to a running --control session) --------------------------
369
- // `hncode control status|prompt|interrupt` — the client half of the control
370
- // socket the TUI opens with --control. Prints the JSON reply so a script can
371
- // parse it; exits non-zero when the running session could not be reached.
372
- async function cmdControl(sub, arg) {
373
- const { sendControl } = await import('./ci.js');
374
- const op = sub || 'status';
375
- if (!['status', 'prompt', 'interrupt'].includes(op)) {
376
- console.error(`unknown control op: ${op}. Use status | prompt <text> | interrupt.`);
377
- return 1;
378
- }
379
- const req = { op };
380
- if (op === 'prompt') {
381
- const text = String(arg || '').trim();
382
- if (!text) { console.error('control prompt requires text.'); return 1; }
383
- req.text = text;
384
- }
385
- const res = await sendControl(req, { path: process.env.HNCODE_CONTROL_SOCKET || undefined });
386
- console.log(JSON.stringify(res));
387
- return res && res.ok ? 0 : 1;
388
- }
389
-
390
- // ---- headless prompt mode ----
391
- async function runPrompt({ cfg, prompt, format, session, modelArg, timeoutSeconds, maxRetries }) {
392
- cfg = resolveModelArg(cfg, modelArg);
393
- if (maxRetries !== undefined) cfg.maxRetries = maxRetries;
394
- if (!cfg.apiKey) {
395
- console.error('hncode: no api_key configured. Set HNCODE_API_KEY or configure a provider first. Run `hncode doctor config` to check.');
396
- return EXIT.CONFIG;
397
- }
398
- const messages = [];
399
- // Same layering as the TUI: built-in prompt first, then the user's own
400
- // system_prompt override if any, then the /personal notes, then calm mode.
401
- let sysText = (cfg.systemPrompt && String(cfg.systemPrompt).trim()) || SYSTEM_PROMPT;
402
- const personal = readPersonalPrompt(cfg.workspace);
403
- if (personal) sysText += '\n\n' + personal;
404
- messages.push({ role: 'system', content: sysText });
405
- if (session && session.messages) {
406
- // Resume on a TOOL-EXCHANGE BOUNDARY: a cut that separates an assistant
407
- // message from its tool results (or leaves orphaned tool results) is a 400
408
- // from the provider, not just a shorter history. `canSplitAfter` is the same
409
- // rule the compaction logic uses. System messages are dropped — the fresh
410
- // one above is authoritative.
411
- const hist = session.messages.filter((m) => m && m.role !== 'system');
412
- // A session persisted mid-step can end with an assistant message whose tool
413
- // results were never appended; sending it before the user message is a 400.
414
- while (hist.length && hist[hist.length - 1].role === 'assistant'
415
- && Array.isArray(hist[hist.length - 1].toolCalls) && hist[hist.length - 1].toolCalls.length) hist.pop();
416
- let start = Math.max(0, hist.length - 30);
417
- while (start > 0 && !canSplitAfter(hist, start - 1)) start++;
418
- for (let i = start; i < hist.length; i++) messages.push(hist[i]);
419
- }
420
- // THE PROMPT ITSELF. This used to never be pushed: -p sent only the resumed
421
- // history and the system message, so a fresh session answered nothing the
422
- // user asked and a resumed one answered nothing new.
423
- messages.push({ role: 'user', content: prompt });
424
- if (session && session._unrecoverable) {
425
- process.stderr.write(
426
- `hncode: session ${session.id} has no readable history (its file is damaged). `
427
- + 'Starting a new session; the old file is untouched.\n',
428
- );
429
- session = null;
430
- }
431
- const saved = session || { id: sess.newId(), title: prompt.slice(0, 60), workspace: path.resolve(process.cwd()), model: cfg.model, createdAt: Date.now(), messages: [] };
432
- const tracker = createRunTracker();
433
- const startedAt = Date.now();
434
- let fatal = null;
435
- const agent = new Agent({
436
- cfg,
437
- messages,
438
- // Uncapped: run until the model finishes (see agent.js).
439
- onEvent: (e) => {
440
- trackEvent(tracker, e);
441
- if (e.type === 'error') fatal = (e.error && e.error.message) || String(e.error);
442
- if (format === 'stream-json' || format === 'json') {
443
- // `json` mode keeps stdout clean for the final envelope, so events go to
444
- // stderr there. `stream-json` is the streaming contract: one event/line.
445
- if (format === 'stream-json') {
446
- if (e.type === 'context') return; // TUI-only gauge; not part of the stream
447
- const line = { type: e.type };
448
- if (e.text) line.text = e.text;
449
- if (e.name) line.name = e.name;
450
- if (e.id) line.id = e.id;
451
- if (e.content != null) line.content = e.content;
452
- process.stdout.write(JSON.stringify(line) + '\n');
453
- }
454
- } else if (e.type === 'data') {
455
- process.stdout.write(e.text);
456
- }
457
- },
458
- });
459
- saved.messages = messages;
460
- // `--timeout <seconds>`: hard wall-clock cap on the whole run, so an unattended
461
- // scripted prompt cannot hang forever on a stuck model or a wedged tool. The
462
- // timer calls the SAME interrupt() the TUI's Esc uses — it aborts the in-flight
463
- // request and kills the tool's AbortSignal — rather than process.exit, so the
464
- // session is still saved and any final output is emitted.
465
- let timedOut = false;
466
- let timer = null;
467
- if (timeoutSeconds > 0) {
468
- timer = setTimeout(() => {
469
- timedOut = true;
470
- try { agent.interrupt(); } catch { /* best-effort */ }
471
- }, timeoutSeconds * 1000);
472
- if (timer.unref) timer.unref();
473
- }
474
- try {
475
- await agent.run();
476
- } finally {
477
- if (timer) clearTimeout(timer);
478
- // MCP stdio children were spawned for this run; most die on stdin EOF at
479
- // process exit, but one that ignores EOF would linger. Kill them outright —
480
- // best-effort, the result has already been produced.
481
- try {
482
- const mcp = await import('./mcp.js');
483
- mcp.disconnectAll(mcp.getLiveConnections());
484
- } catch { /* best-effort */ }
485
- }
486
- sess.saveSession(saved);
487
-
488
- const reply = finalReply(messages, tracker.text);
489
- const result = buildResult({
490
- reply,
491
- toolCalls: tracker.toolCalls,
492
- files: tracker.files,
493
- error: fatal || (tracker.errors.length ? tracker.errors[tracker.errors.length - 1] : null),
494
- stopped: !!agent.stopRequested,
495
- durationMs: Date.now() - startedAt,
496
- model: cfg.model,
497
- sessionId: saved.id,
498
- timedOut,
499
- });
500
-
501
- if (format === 'json') {
502
- // Exactly one JSON object on stdout, so `| jq` / `tail -1` works.
503
- process.stdout.write(resultLine(result) + '\n');
504
- } else if (format === 'stream-json') {
505
- // A terminating event tells a streaming reader the run is over and carries
506
- // the same envelope, so both formats end with a `result` record.
507
- process.stdout.write(resultLine(result) + '\n');
508
- } else {
509
- process.stdout.write('\n');
510
- }
511
- return exitCodeFor(result, false);
512
- }
513
-
514
- // ---- TUI dispatch ----
515
- async function startTui(opts) {
516
- const { startTUI } = await import('./tui.js');
517
- await startTUI(opts);
518
- }
519
-
520
- function loadOrCreateSession(opts, cfg) {
521
- let session = null;
522
- // NOTE: these keys must match what parseArgs actually produces — `--continue`
523
- // yields `args.continue` (not `args.cont`), and `--resume <id>` is normalised
524
- // to `args.session`. Reading the wrong key silently fell through to "create a
525
- // new session", which is why --continue looked like it started a fresh one.
526
- const sessionArg = opts.session;
527
- const wantsSession = typeof sessionArg === 'string' || sessionArg === true || !!opts.sessionId;
528
- const wantsContinue = !!(opts.continue || opts.cont);
529
- if (wantsSession) {
530
- const id = typeof sessionArg === 'string' ? sessionArg : opts.sessionId;
531
- if (id) session = sess.loadSession(id) || null;
532
- } else if (wantsContinue) {
533
- // --continue: get the most recent session for THIS directory that has messages.
534
- // Empty shells are created on every launch, so we skip them to find real conversations.
535
- session = sess.latestSession(process.cwd(), undefined, { skipEmpty: true });
536
- }
537
- // A session whose file could not be parsed OR recovered comes back marked, with no
538
- // messages. Resuming it would present an empty conversation that still looks like the
539
- // old one, and the first save would write that emptiness over the file. Start fresh and
540
- // say why, rather than letting the user type into a session that has already lost its
541
- // history. The damaged file stays on disk, so nothing is destroyed by refusing.
542
- if (session && session._unrecoverable) {
543
- process.stderr.write(
544
- `hncode: session ${session.id} has no readable history (its file is damaged). `
545
- + 'Starting a new session; the old file is untouched.\n',
546
- );
547
- session = null;
548
- }
549
- if (!session) {
550
- session = { id: sess.newId(), title: '', workspace: path.resolve(process.cwd()), model: cfg.model, createdAt: Date.now(), messages: [] };
551
- } else {
552
- // CRITICAL: Update session model to match current config!
553
- // This prevents using stale model ID from old sessions.
554
- session.model = cfg.model;
555
- }
556
- return session;
557
- }
558
-
559
-
560
- /**
561
- * Parse the --web flag into { bindIp, port } or null.
562
- * --web -> loopback, OS-assigned port
563
- * --web 8080 -> loopback, that port
564
- * --web 0.0.0.0:8080 -> explicit address and port
565
- * --web 192.168.1.5 -> that address, OS-assigned port
566
- * Anything unparseable returns null, so the flag is ignored rather than failing
567
- * the launch — /web from inside the session still works either way.
568
- */
569
- export function parseWebArg(v) {
570
- if (v == null || v === false) return null;
571
- if (v === true) return { bindIp: '127.0.0.1', port: 0 };
572
- const s = String(v).trim();
573
- if (!s) return { bindIp: '127.0.0.1', port: 0 };
574
- let bindIp = '127.0.0.1';
575
- let port = 0;
576
- if (/^\d+$/.test(s)) {
577
- port = Number(s);
578
- } else if (s.includes(':')) {
579
- // IPv6 in brackets is deliberately not handled: /web covers it, and a
580
- // half-parsed address is worse than ignoring the flag.
581
- const at = s.lastIndexOf(':');
582
- bindIp = s.slice(0, at) || '127.0.0.1';
583
- const p = s.slice(at + 1);
584
- if (!/^\d+$/.test(p)) return null;
585
- port = Number(p);
586
- } else {
587
- bindIp = s;
588
- }
589
- if (port < 0 || port > 65535) return null;
590
- return { bindIp, port };
591
- }
592
-
593
- export async function main(argv) {
594
- const args = parseArgs(argv);
595
- if (args.help) { printHelp(); return 0; }
596
- if (args.help) { printHelp(); return 0; }
597
- if (args.version) { console.log(VERSION); return 0; }
598
-
599
- // subcommands
600
- const [cmd, sub] = args.positional;
601
- if (cmd) {
602
- if (cmd === 'doctor' && !sub) { return await cmdDoctorEnv(); }
603
- const handler = SUBCOMMANDS[cmd];
604
- if (handler) {
605
- // A `{ needsArgs, run }` entry wants the parsed flags as well as the positional path — the one thing a
606
- // module-level table cannot close over, because `args` lives in this function.
607
- if (typeof handler === 'object' && typeof handler.run === 'function') {
608
- return await handler.run(args.positional[1], args);
609
- }
610
- if (sub !== undefined) {
611
- const h2 = handler[sub];
612
- if (h2) return await h2(args.positional[2]);
613
- printHelp(); return 1;
614
- }
615
- if (typeof handler === 'function') return await handler(args.positional[1]);
616
- printHelp(); return 0;
617
- }
618
- console.error(`unknown command: ${cmd}`);
619
- return 1;
620
- }
621
-
622
- const baseCfg = resolveConfig();
623
- const cfg = resolveModelArg(baseCfg, args.model);
624
-
625
- // Plugins are normally loaded by bootstrap (bin/hncode) BEFORE this module is
626
- // imported, because symbol patching has to register targets before the patched
627
- // modules load. Only load them here when bootstrap did NOT already do it (e.g.
628
- // index.js imported directly, or a test), so tools/commands still appear in
629
- // both modes without a second load tripping "tool already registered".
630
- try {
631
- const { pluginsAlreadyLoaded } = await import('./bootstrap.js');
632
- if (cfg.pluginDir && !pluginsAlreadyLoaded() && !globalThis.__hncodePluginsLoaded) {
633
- const { loadPlugins } = await import('./plugin.js');
634
- await loadPlugins(cfg.pluginDir);
635
- globalThis.__hncodePluginsLoaded = true;
636
- }
637
- } catch (e) {
638
- console.error('[hncode] plugin load step failed, continuing without plugins:', e && e.message);
639
- }
640
-
641
- // Connect configured MCP servers and register their tools.
642
- //
643
- // This is a FUNCTION rather than an inline block because the two modes want
644
- // different timing:
645
- // * headless (`-p`) MUST wait — the prompt runs immediately and its model
646
- // request has to see the MCP tools in the tool list.
647
- // * the TUI must NOT wait — connecting can take seconds (8s per wedged
648
- // server), and blocking the first paint for that is unacceptable. The TUI
649
- // starts this in the background and reports the result as a notice.
650
- // Failures are reported but never fatal: an unreachable server must not stop
651
- // the session from starting.
652
- const connectMcp = async (mcpOpts = {}) => {
653
- if (cfg.mcp === false) return { servers: [], toolCount: 0 };
654
- try {
655
- const mcp = await import('./mcp.js');
656
- const { API } = await import('./plugin.js');
657
- const mcpCfg = mcp.loadMcpConfig(cfg.workspace);
658
- if (!Object.keys(mcpCfg.servers).length) return { servers: [], toolCount: 0 };
659
- const res = await mcp.connectAll(mcpCfg, (spec) => API.registerTool(spec), mcpOpts);
660
- mcp.setLiveConnections(res.servers);
661
- if (process.env.HNCODE_MCP_VERBOSE === '1') {
662
- for (const s of res.servers) {
663
- console.error(s.ok ? `[hncode-mcp] ${s.name}: ${s.toolCount} tool(s)` : `[hncode-mcp] ${s.name}: ${s.error}`);
664
- }
665
- }
666
- return res;
667
- } catch (e) {
668
- console.error(`hncode: MCP setup failed: ${e.message}`);
669
- return { servers: [], toolCount: 0 };
670
- }
671
- };
672
-
673
- // headless prompt: MCP must be live BEFORE the request goes out.
674
- if (args.prompt) {
675
- const format = args['output-format'];
676
- if (!isValidFormat(format)) {
677
- console.error(`hncode: unknown --output-format "${format}". Use one of: ${FORMATS.join(', ')}.`);
678
- return EXIT.CONFIG;
679
- }
680
- await connectMcp();
681
- let session = null;
682
- if (args.session) session = typeof args.session === 'string' ? sess.loadSession(args.session) : sess.latestSession(undefined, undefined, { skipEmpty: true });
683
- else if (args.continue) session = sess.latestSession(undefined, undefined, { skipEmpty: true });
684
- // --timeout / --retries are validated here so a typo fails loudly instead of
685
- // being parsed as NaN and silently ignored.
686
- const timeoutSeconds = args.timeout !== undefined ? Number.parseInt(String(args.timeout), 10) : 0;
687
- if (args.timeout !== undefined && (!Number.isInteger(timeoutSeconds) || timeoutSeconds < 1)) {
688
- console.error(`hncode: --timeout needs a positive integer (seconds), got "${args.timeout}".`);
689
- return EXIT.CONFIG;
690
- }
691
- const maxRetries = args.retries !== undefined ? Number.parseInt(String(args.retries), 10) : undefined;
692
- if (args.retries !== undefined && (!Number.isInteger(maxRetries) || maxRetries < 0)) {
693
- console.error(`hncode: --retries needs a non-negative integer, got "${args.retries}".`);
694
- return EXIT.CONFIG;
695
- }
696
- return runPrompt({ cfg, prompt: args.prompt, format, session, modelArg: args.model, timeoutSeconds, maxRetries });
697
- }
698
-
699
- if (!process.stdout.isTTY) {
700
- console.error('hncode: interactive mode requires a TTY. Use `hncode -p "prompt"` for non-interactive use.');
701
- return EXIT.FAILURE;
702
- }
703
-
704
- const opts = {
705
- cfg,
706
- sessionFlag: args.session,
707
- sessionId: typeof args.session === 'string' ? args.session : null,
708
- cont: !!args.continue,
709
- yolo: !!args.yolo,
710
- auto: !!args.auto,
711
- plan: !!args.plan,
712
- addDirs: args['add-dir'] || [],
713
- // Remote control: expose a local socket so a script can queue a prompt or
714
- // query status on the running session (see ci.js).
715
- control: args.control === true ? '' : (typeof args.control === 'string' ? args.control : null),
716
- // Web UI: start the server as soon as the TUI is up. `--web` alone binds
717
- // loopback on an OS-assigned port; `--web 0.0.0.0:8080` chooses both. Parsed
718
- // here so it behaves like every other flag, and the TUI still has /web to
719
- // start or stop it mid-session.
720
- web: parseWebArg(args.web),
721
- // MCP runs in the BACKGROUND once the TUI is up (see startTUI): connecting
722
- // can take seconds and must not delay the first paint.
723
- mcpConnect: connectMcp,
724
- session: loadOrCreateSession(args, cfg),
725
- };
726
- await startTui(opts);
727
- return EXIT.OK;
728
- }
729
-
730
- // main() is invoked by bin/hncode (the CLI entry point), which imports this module
1
+ // hncode entry: CLI arg parsing, subcommands, headless -p mode, and TUI dispatch.
2
+
3
+ import os from 'node:os';
4
+ import path from 'node:path';
5
+ import fs from 'node:fs';
6
+ import { resolveConfig, effectiveSnapshot, saveConfig, resolveModelArg, readPersonalPrompt } from './config.js';
7
+ import * as sess from './session.js';
8
+ import { Agent, SYSTEM_PROMPT, THINKING_TAGS_INSTRUCTION, needsThinkingTags, canSplitAfter } from './agent.js';
9
+ import { llmTools } from './tools/index.js';
10
+ import { localVersion } from './version.js';
11
+ import { EXIT, FORMATS, isValidFormat, buildResult, exitCodeFor, resultLine, createRunTracker, trackEvent, finalReply } from './ci.js';
12
+
13
+ // The version shown by `hncode -V` and the help banner. Read from package.json
14
+ // (via version.js) so it can never drift from the published version again.
15
+ export const VERSION = localVersion();
16
+
17
+ const HELP = `hncode ${VERSION} — a Kimi Code-style coding agent.
18
+
19
+ Usage: hncode [options] [command]
20
+
21
+ Cyan-blue TUI for long agent sessions. OpenAI + Anthropic streaming,
22
+ MCP-style toolbelt (Edit, Read, Write, Bash, Glob, Grep, TodoList, ...).
23
+
24
+ Options:
25
+ -V, --version output the version number
26
+ -S, --session [id] Resume a session (with id) or pick interactively.
27
+ -c, --continue Continue the previous session for this directory.
28
+ -y, --yolo Yolo mode: routine edits/commands run; risky actions still ask.
29
+ --auto Auto mode: never ask; everything runs automatically.
30
+ -m, --model <model> Model alias to use for this invocation.
31
+ -p, --prompt <prompt> Run one prompt non-interactively and print the reply.
32
+ --output-format <format> Prompt mode output: text (default), json, or stream-json.
33
+ json prints one result object; stream-json streams events then a result.
34
+ Exit code reflects the outcome: 0 ok, 1 failure, 2 config, 3 no answer, 4 interrupted.
35
+ --control Expose a local control socket (prompt/status/interrupt) while the TUI runs.
36
+ --timeout <seconds> Prompt mode: abort the run after this many seconds (default: no limit).
37
+ --retries <n> Prompt mode: HTTP retries per request before failing (default: 3).
38
+ --control <path> Same, at an explicit socket path.
39
+ --web Serve this session to a browser on 127.0.0.1 (random port).
40
+ --web [ip][:port] Same, on a chosen address/port (e.g. --web 0.0.0.0:8080).
41
+ --plan Start in plan mode (research only, no writes).
42
+ --plan Start in plan mode (research only, no writes).
43
+ --add-dir <dir> Add an additional workspace directory. Repeatable.
44
+ -h, --help Show help.
45
+
46
+ Commands:
47
+ session list List sessions, most recent first.
48
+ provider list Show configured providers.
49
+ doctor [config] [path] Environment self-check (default), or validate a config.toml.
50
+ init Create ~/.hncode/config.toml with defaults.
51
+ export [id] Export a session to ~/.hncode/export/<id>.json.
52
+ backup [path] Archive ALL state (sessions, settings, skills, plugins, memory) for another machine.
53
+ restore <path> Read a backup. Sessions are placed by the index.yml inside it.
54
+ --index <file> use an edited copy; --no-index keep recorded paths;
55
+ --workspace <dir> repoint every session; --overwrite; --dry-run.
56
+ control status Ask a running session (started with --control) for its status.
57
+ control prompt <text> Queue a prompt on a running session.
58
+ control interrupt Interrupt the running turn.
59
+ hooks list Show configured shell hooks.
60
+ skills list List installed skills.
61
+ mcp list Show configured MCP servers.
62
+ `;
63
+
64
+ function printHelp() { process.stdout.write(HELP); }
65
+
66
+ // ---- minimal argv parsing ----
67
+ export function parseArgs(argv) {
68
+ const out = { positional: [], flags: {} };
69
+ for (let i = 0; i < argv.length; i++) {
70
+ const a = argv[i];
71
+ if (a.startsWith('--')) {
72
+ const eq = a.indexOf('=');
73
+ let key, val;
74
+ if (eq >= 0) { key = a.slice(2, eq); val = a.slice(eq + 1); }
75
+ else { key = a.slice(2); val = null; }
76
+ if (key === 'resume') key = 'session'; // `--resume <id>` is an alias for `--session <id>`
77
+ if (['session', 'control', 'web'].includes(key) && val === null) { const nx = argv[i + 1]; out[key] = nx !== undefined && !nx.startsWith('-') ? (i++, nx) : true; }
78
+ // FLAGS THAT TAKE A VALUE. `--workspace` and `--index` are here for `hncode restore`: without them the path was
79
+ // left in `positional` and the flag itself became `true`, so the restore would have repointed every session at the
80
+ // string "true".
81
+ else if (key === 'model' || key === 'prompt' || key === 'output-format' || key === 'add-dir' || key === 'timeout' || key === 'retries' || key === 'workspace' || key === 'index') {
82
+ if (val === null) {
83
+ const nx = argv[i + 1];
84
+ // Only consume the next token if it is a real value, not another flag
85
+ // or the end of argv. Previously `--model -y` and a trailing `--model`
86
+ // swallowed or mangled the value, breaking the real flag.
87
+ val = (nx !== undefined && !nx.startsWith('-')) ? argv[++i] : undefined;
88
+ }
89
+ out[key] = (key === 'add-dir' && val !== undefined)
90
+ ? (out[key] || []).concat([val])
91
+ : val;
92
+ } else if (val !== null) { out[key] = val === 'true' ? true : val === 'false' ? false : val; }
93
+ else out[key] = true;
94
+ } else if (a.startsWith('-') && a.length > 1) {
95
+ const key = a.slice(1);
96
+ const short = { V: 'version', S: 'session', c: 'continue', y: 'yolo', auto: 'auto', m: 'model', p: 'prompt', h: 'help' };
97
+ if (key === 'S' || key === 'm' || key === 'p') {
98
+ const nx = argv[i + 1];
99
+ // Take the next token as the value only if it exists and is not another
100
+ // flag. Previously `-S -y` swallowed `-y` as the session id and a bare
101
+ // trailing `-m` became undefined; both silently broke the real flag.
102
+ const hasVal = nx !== undefined && !nx.startsWith('-');
103
+ if (hasVal) { out[short[key]] = argv[i + 1]; i++; }
104
+ else if (key === 'S') { out.session = true; } // "-S" with no id => pick interactively
105
+ // '-m' / '-p' with no usable value: leave unset (same as a missing arg).
106
+ } else out[short[key]] = true;
107
+ } else {
108
+ out.positional.push(a);
109
+ }
110
+ }
111
+ return out;
112
+ }
113
+
114
+ // ---- subcommands ----
115
+ function cmdSessionList(args) {
116
+ const items = sess.listSessions();
117
+ if (items.length === 0) { console.log('No sessions yet.'); return 0; }
118
+ for (const s of items.slice(0, 30)) {
119
+ const when = new Date(s.updatedAt || 0).toISOString().slice(0, 19).replace('T', ' ');
120
+ const title = (s.title || '(untitled)').replace(/\n/g, ' ');
121
+ console.log(`${s.id.padEnd(20)} ${when} ${title}`);
122
+ }
123
+ return 0;
124
+ }
125
+ function cmdProviderList() {
126
+ const cfg = resolveConfig();
127
+ const provs = (cfg.raw.providers) || {};
128
+ const models = (cfg.raw.models) || {};
129
+ const counts = {};
130
+ for (const m of Object.values(models)) if (m.provider) counts[m.provider] = (counts[m.provider] || 0) + 1;
131
+ const names = Object.keys(provs).length ? Object.keys(provs) : [cfg.provider];
132
+ for (const name of names) {
133
+ const p = provs[name];
134
+ const url = p ? (p.base_url || p.baseUrl || '') : cfg.baseUrl;
135
+ console.log(`${name} (${counts[name] || 0} models) ${url}`);
136
+ }
137
+ console.log(`active: ${cfg.provider} / ${cfg.model}`);
138
+ return 0;
139
+ }
140
+ async function cmdDoctorConfig(p) {
141
+ let file = p;
142
+ if (!file) {
143
+ const home = os.homedir();
144
+ for (const f of [process.env.HNCODE_CONFIG, path.join(home, '.hncode', 'config.toml')]) {
145
+ if (f && fs.existsSync(f)) { file = f; break; }
146
+ }
147
+ file = file || path.join(home, '.hncode', 'config.toml');
148
+ console.log(`No path given; validated: ${file}`);
149
+ }
150
+ try {
151
+ const txt = fs.readFileSync(file, 'utf8');
152
+ const { parse } = await import('./toml.js');
153
+ parse(txt);
154
+ console.log(`OK: ${file} is valid TOML.`);
155
+ return 0;
156
+ } catch (e) {
157
+ console.error(`INVALID: ${file}: ${e.message}`);
158
+ return 1;
159
+ }
160
+ }
161
+
162
+ // `hncode doctor` — environment self-check. Answers "will hncode actually work in
163
+ // THIS terminal?" for the things that silently break it: too-old Node, a non-TTY
164
+ // or odd terminal, Windows consoles that do not forward mouse sequences, a missing
165
+ // git, an unreadable config. Every line is OK / WARN / FAIL so one paste answers a
166
+ // support question.
167
+ async function cmdDoctorEnv() {
168
+ const rows = [];
169
+ const add = (level, label, detail) => rows.push({ level, label, detail });
170
+
171
+ const major = Number(process.versions.node.split('.')[0]);
172
+ if (major >= 22) add('OK', 'node', process.version);
173
+ else if (major >= 20) add('WARN', 'node', process.version + ' — 20/21 work, but 22+ has TTY fixes');
174
+ else add('FAIL', 'node', process.version + ' — hncode needs Node >= 20');
175
+
176
+ add('OK', 'platform', process.platform + ' ' + os.release());
177
+ const isWin = process.platform === 'win32';
178
+ const term = process.env.TERM || '';
179
+ const wt = process.env.WT_SESSION ? 'windows-terminal' : (process.env.TERM_PROGRAM || (isWin ? 'conhost/other' : 'unknown'));
180
+ add(process.stdout.isTTY ? 'OK' : 'WARN', 'stdout isatty', process.stdout.isTTY ? 'yes' : 'no — colors/mouse assume a real terminal');
181
+ add('OK', 'terminal', wt + (term ? ' (TERM=' + term + ')' : ''));
182
+ if (isWin && !process.env.WT_SESSION) {
183
+ add('WARN', 'mouse', 'not inside Windows Terminal (WT_SESSION unset); some consoles do not forward mouse input');
184
+ }
185
+ add('OK', 'truecolor', (process.env.COLORTERM === 'truecolor' || /256color|truecolor/.test(term)) ? 'yes' : 'no — 256-color fallback in use');
186
+
187
+ try {
188
+ const { spawnSync } = await import('node:child_process');
189
+ const r = spawnSync('git', ['--version'], { encoding: 'utf8' });
190
+ add(r.status === 0 ? 'OK' : 'WARN', 'git', r.status === 0 ? String(r.stdout).trim() : 'not found — git tools limited');
191
+ } catch { add('WARN', 'git', 'not found on PATH'); }
192
+
193
+ const cfgFile = process.env.HNCODE_CONFIG || path.join(os.homedir(), '.hncode', 'config.toml');
194
+ if (!fs.existsSync(cfgFile)) {
195
+ add('WARN', 'config', 'no file at ' + cfgFile + ' (run hncode init)');
196
+ } else {
197
+ try {
198
+ const { parse } = await import('./toml.js');
199
+ parse(fs.readFileSync(cfgFile, 'utf8'));
200
+ add('OK', 'config', cfgFile);
201
+ } catch (e) {
202
+ add('FAIL', 'config', cfgFile + ': ' + e.message);
203
+ }
204
+ }
205
+
206
+ try {
207
+ const cfg = resolveConfig();
208
+ const model = cfg.innerModel || cfg.model;
209
+ add(model ? 'OK' : 'WARN', 'model', model || 'none configured (run /model or set default_model)');
210
+ add(cfg.apiKey ? 'OK' : 'WARN', 'api key', cfg.apiKey ? 'set' : 'missing — requests will 401');
211
+ } catch (e) {
212
+ add('WARN', 'config resolve', e.message);
213
+ }
214
+
215
+ try {
216
+ const dir = path.join(os.homedir(), '.hncode', 'plugins');
217
+ const n = fs.existsSync(dir) ? fs.readdirSync(dir).filter((x) => fs.statSync(path.join(dir, x)).isDirectory()).length : 0;
218
+ add('OK', 'plugins', n + ' installed (' + dir + ')');
219
+ } catch { /* ignore */ }
220
+
221
+ const order = { FAIL: 0, WARN: 1, OK: 2 };
222
+ rows.sort((a, b) => order[a.level] - order[b.level]);
223
+ console.log('hncode doctor — environment check\n');
224
+ for (const r of rows) console.log(' [' + r.level.padEnd(4) + '] ' + r.label.padEnd(16) + ' ' + r.detail);
225
+ const fails = rows.filter((r) => r.level === 'FAIL').length;
226
+ console.log('\n' + (fails ? fails + ' problem(s) found' : 'No blocking problems found.'));
227
+ return fails ? 1 : 0;
228
+ }
229
+
230
+
231
+ function cmdInit() {
232
+ const cfg = resolveConfig();
233
+ const target = path.join(os.homedir(), '.hncode', 'config.toml');
234
+ fs.mkdirSync(path.dirname(target), { recursive: true });
235
+ const lines = [
236
+ `# hncode configuration`,
237
+ `default_model = "${cfg.raw.default_model || 'gpt-4o-mini'}"`,
238
+ ``,
239
+ `# Or set these directly:`,
240
+ `# base_url = "${cfg.baseUrl}"`,
241
+ `# protocol = "openai" # or "anthropic"`,
242
+ `# max_context_size = 128000`,
243
+ `# max_output_size = 4096`,
244
+ ];
245
+ if (!fs.existsSync(target)) {
246
+ fs.writeFileSync(target, lines.join('\n') + '\n', 'utf8');
247
+ console.log(`Created ${target}`);
248
+ } else {
249
+ console.log(`Already exists: ${target}`);
250
+ }
251
+ return 0;
252
+ }
253
+
254
+ function cmdExport(id) {
255
+ const s = id ? sess.loadSession(id) : sess.latestSession(process.cwd());
256
+ if (!s) { console.error('No session found.'); return 1; }
257
+ const exportDir = path.join(os.homedir(), '.hncode', 'export');
258
+ fs.mkdirSync(exportDir, { recursive: true });
259
+ const out = path.join(exportDir, `${s.id}.json`);
260
+ fs.writeFileSync(out, JSON.stringify(s, null, 2), 'utf8');
261
+ console.log(`Exported ${s.id} -> ${out}`);
262
+ return 0;
263
+ }
264
+
265
+ // ---- migration: every piece of state, to another machine -------------------
266
+ //
267
+ // `hncode backup [path]` writes one archive of everything a person made: sessions, settings, skills, plugins, memory.
268
+ // `hncode restore <path>` reads it back, with `--workspace <dir>` to repoint the imported sessions, `--overwrite` to
269
+ // replace what is already here, and `--dry-run` to see what would happen first.
270
+ //
271
+ // Debug logs and the plugin browser's Chromium profile are deliberately excluded — see EXCLUDED in src/migrate.js.
272
+ async function cmdBackup(dest) {
273
+ const mig = await import('./migrate.js');
274
+ const home = mig.hncodeHome();
275
+ const items = mig.planExport(home);
276
+ if (!items.length) {
277
+ console.error(`nothing to migrate: ${home} holds none of the portable entries`);
278
+ return 1;
279
+ }
280
+ const total = items.reduce((n, i) => n + i.size, 0);
281
+ const out = dest ? path.resolve(String(dest))
282
+ : path.join(process.cwd(), `hncode-backup-${new Date().toISOString().slice(0, 10)}.hnb`);
283
+ console.log(`exporting ${items.length} item(s), ${mig.fmtBytes(total)}, from ${home}`);
284
+ for (const i of items) console.log(` ${mig.fmtBytes(i.size).padStart(9)} ${i.name}${i.kind === 'dir' ? '/' : ''} — ${i.what}`);
285
+ console.log(` (left behind: ${mig.EXCLUDED.map((e) => e.name).join(', ')})`);
286
+ let last = 0;
287
+ const res = mig.writeArchive(out, {
288
+ home,
289
+ items,
290
+ onProgress: (done, all) => {
291
+ // A line every 10% keeps a 190 MB export from looking frozen without flooding the terminal.
292
+ const pct = Math.floor((done / all) * 10) * 10;
293
+ if (pct > last) { last = pct; process.stderr.write(` ${pct}%\r`); }
294
+ },
295
+ });
296
+ console.log(``);
297
+ console.log(`wrote ${res.path}`);
298
+ console.log(` ${res.files} files, ${mig.fmtBytes(res.bytes)}`);
299
+ console.log(`On the other machine: hncode restore ${path.basename(res.path)}`);
300
+ return 0;
301
+ }
302
+
303
+ async function cmdRestore(from, args = {}) {
304
+ const mig = await import('./migrate.js');
305
+ if (!from) { console.error('restore needs an archive: hncode restore <file.hnb> [--workspace <dir>] [--overwrite] [--dry-run]'); return 1; }
306
+ const src = path.resolve(String(from));
307
+ let head;
308
+ try { head = mig.readArchiveManifest(src); } catch (e) { console.error(`cannot read ${src}: ${e.message}`); return 1; }
309
+ const { manifest } = head;
310
+ const home = mig.hncodeHome();
311
+ const bytes = manifest.files.reduce((n, f) => n + f.size, 0);
312
+ console.log(`archive: ${src}`);
313
+ console.log(` created ${new Date(manifest.createdAt).toISOString()}, ${manifest.files.length} files, ${mig.fmtBytes(bytes)}`);
314
+ console.log(` from ${manifest.home || '(unknown)'}`);
315
+ console.log(` into ${home}`);
316
+ // THE INDEX IS THE POINT OF THIS FLAG. Without it the archive's own `index.yml` is used when present, which is what
317
+ // makes an exported-then-edited file worth having. `--index <file>` points at a copy edited OUTSIDE the archive, and
318
+ // `--no-index` ignores it so the recorded paths are kept verbatim.
319
+ const opts = {
320
+ home,
321
+ overwrite: !!args.overwrite,
322
+ workspace: args.workspace,
323
+ dryRun: !!args['dry-run'],
324
+ // DEFAULT IS ON: an archive's own index.yml is used unless `--no-index` says otherwise. `--index <file>` replaces it
325
+ // with an edited copy.
326
+ index: args['no-index'] ? false : true,
327
+ indexFile: typeof args.index === 'string' ? args.index : undefined,
328
+ };
329
+ if (opts.workspace) console.log(` sessions repointed at ${path.resolve(String(opts.workspace))} (--workspace overrides the index)`);
330
+ else if (!opts.index) console.log(' --no-index: paths stay exactly as recorded');
331
+ else if (opts.indexFile) console.log(` mapping read from ${path.resolve(String(opts.indexFile))}`);
332
+ else console.log(' sessions are placed by the index.yml inside the archive, if it has one');
333
+ if (opts.dryRun) console.log(' (dry run — nothing is written)');
334
+ let res;
335
+ try { res = mig.readArchive(src, opts); } catch (e) { console.error(`restore failed: ${e.message}`); return 1; }
336
+ console.log(` ${opts.dryRun ? 'would write' : 'wrote'} ${res.written} file(s), ${mig.fmtBytes(res.bytes)}`);
337
+ if (res.skipped) console.log(` kept ${res.skipped} existing file(s) — pass --overwrite to replace them`);
338
+ if (res.mapped) console.log(` ${res.mapped} session(s) moved by the mapping`);
339
+ else if (res.sessionsRewritten) console.log(` ${res.sessionsRewritten} session(s) repointed`);
340
+ if (opts.index !== false && !res.indexFound) console.log(' no index.yml in the archive (an older backup) — paths left as recorded');
341
+ for (const e of res.errors.slice(0, 5)) console.error(` ! ${e}`);
342
+ if (res.errors.length > 5) console.error(` ! … and ${res.errors.length - 5} more`);
343
+ return res.errors.length ? 1 : 0;
344
+ }
345
+
346
+ // ---- MCP server mode ---------------------------------------------------------
347
+
348
+ // The workspace the exposed tools operate on. A client starts this process from
349
+ // wherever the user happens to be, so the project has to be named explicitly or the
350
+ // tools would work in the wrong directory.
351
+ function mcpWorkspace(args) {
352
+ const fromEnv = process.env.HNCODE_WORKSPACE;
353
+ const fromFlag = args && args.workspace;
354
+ const dir = fromFlag || fromEnv || process.cwd();
355
+ return path.resolve(dir);
356
+ }
357
+
358
+ /**
359
+ * The tool context the exposed tools receive.
360
+ *
361
+ * It is the same shape the agent hands its own tools, so a tool behaves the same
362
+ * whoever called it. `cwd` is what the path helpers resolve against.
363
+ */
364
+ async function mcpToolContext(workspace, args) {
365
+ const cfg = resolveConfig();
366
+ return {
367
+ ...cfg,
368
+ cwd: workspace,
369
+ workspace,
370
+ tasks: {},
371
+ todoState: [],
372
+ allowExternal: cfg.allowExternal !== false,
373
+ signal: undefined,
374
+ };
375
+ }
376
+
377
+ /**
378
+ * `hncode mcp serve` — run hncode as an MCP server.
379
+ *
380
+ * `--stdio` (the default) speaks the protocol over stdin/stdout, which is what every
381
+ * `mcp add` uses. `--http` serves streamable-HTTP on a port instead, for a client that
382
+ * connects to a running server.
383
+ *
384
+ * The toolbelt is the READ-ONE set unless `--full` is given: handing another program
385
+ * the ability to run commands or rewrite files is not something to do by default.
386
+ */
387
+ async function cmdMcpServe(rest, args) {
388
+ const server = await import('./mcp-server.js');
389
+ const mode = args && args.full ? 'full' : 'read';
390
+ const prefix = args && args['no-prefix'] ? '' : 'hncode_';
391
+ const workspace = mcpWorkspace(args);
392
+ const ctx = await mcpToolContext(workspace, args);
393
+
394
+ if (args && args.http) {
395
+ const port = Number(args.port) || 0;
396
+ const host = String(args.host || '127.0.0.1');
397
+ const http = server.createHttpServer({ mode, prefix, ctx });
398
+ const addr = await server.listen(http, port, host);
399
+ // stderr, not stdout: on the HTTP transport stdout is free, but a client reading the
400
+ // process's output expects diagnostics there and the TUI prints its own on stdout.
401
+ console.error(`hncode MCP server on http://${addr.host}:${addr.port}/ workspace=${workspace} tools=${mode}`);
402
+ return new Promise(() => {}); // serve until the process is killed
403
+ }
404
+
405
+ // stdio: stdout carries the protocol and NOTHING else.
406
+ console.error(`hncode MCP server ready workspace=${workspace} tools=${mode}`);
407
+ server.serveStdio({ mode, prefix, ctx });
408
+ return new Promise(() => {});
409
+ }
410
+
411
+ /**
412
+ * `hncode mcp config` — print the JSON another agent's config file needs.
413
+ *
414
+ * The shape is the one every client reads (`mcpServers` with `command`/`args`/`env`),
415
+ * so the output can be pasted into Claude Code's, Cursor's or anyone else's config.
416
+ */
417
+ async function cmdMcpConfig(rest, args) {
418
+ const server = await import('./mcp-server.js');
419
+ const workspace = mcpWorkspace(args);
420
+ const config = server.clientConfig({
421
+ command: process.execPath,
422
+ args: [path.join(path.dirname(new URL(import.meta.url).pathname.replace(/^\//, '')), 'index.js')],
423
+ workspace,
424
+ });
425
+ console.log(JSON.stringify(config, null, 2));
426
+ return 0;
427
+ }
428
+ const SUBCOMMANDS = {
429
+ 'session': { 'list': cmdSessionList },
430
+ 'doctor': { 'config': cmdDoctorConfig },
431
+ // MCP server mode: hncode exposes its own tools to another agent. `serve` runs the
432
+ // server; `config` prints the JSON that other clients' config files need.
433
+ 'mcp': {
434
+ 'serve': (rest, args) => cmdMcpServe(rest, args),
435
+ 'config': (rest, args) => cmdMcpConfig(rest, args),
436
+ },
437
+ 'init': cmdInit,
438
+ 'export': cmdExport,
439
+ // MIGRATION. `export` above writes ONE session as Markdown; these move the whole hncode state — every session,
440
+ // the settings, skills, plugins, memory — to another machine. Different jobs, so different names.
441
+ //
442
+ // BOTH ARE `{ run }` ENTRIES, NOT BARE FUNCTIONS. The dispatcher treats a second positional word as the SUBCOMMAND of
443
+ // the first (`session list`), and for these it is just the path — `backup /tmp/x.hnb` was being read as the subcommand
444
+ // `/tmp/x.hnb` of `backup`, which does not exist, so it printed the help and did nothing.
445
+ 'backup': { run: cmdBackup },
446
+ 'restore': { run: cmdRestore },
447
+ control: {
448
+ // Subcommands pass only positional[2] to their handler, so bind the op.
449
+ 'status': (rest) => cmdControl('status', rest),
450
+ 'prompt': (rest) => cmdControl('prompt', rest),
451
+ 'interrupt': (rest) => cmdControl('interrupt', rest),
452
+ },
453
+ };
454
+
455
+ // ---- control (talk to a running --control session) --------------------------
456
+ // `hncode control status|prompt|interrupt` — the client half of the control
457
+ // socket the TUI opens with --control. Prints the JSON reply so a script can
458
+ // parse it; exits non-zero when the running session could not be reached.
459
+ async function cmdControl(sub, arg) {
460
+ const { sendControl } = await import('./ci.js');
461
+ const op = sub || 'status';
462
+ if (!['status', 'prompt', 'interrupt'].includes(op)) {
463
+ console.error(`unknown control op: ${op}. Use status | prompt <text> | interrupt.`);
464
+ return 1;
465
+ }
466
+ const req = { op };
467
+ if (op === 'prompt') {
468
+ const text = String(arg || '').trim();
469
+ if (!text) { console.error('control prompt requires text.'); return 1; }
470
+ req.text = text;
471
+ }
472
+ const res = await sendControl(req, { path: process.env.HNCODE_CONTROL_SOCKET || undefined });
473
+ console.log(JSON.stringify(res));
474
+ return res && res.ok ? 0 : 1;
475
+ }
476
+
477
+ // ---- headless prompt mode ----
478
+ async function runPrompt({ cfg, prompt, format, session, modelArg, timeoutSeconds, maxRetries }) {
479
+ cfg = resolveModelArg(cfg, modelArg);
480
+ if (maxRetries !== undefined) cfg.maxRetries = maxRetries;
481
+ if (!cfg.apiKey) {
482
+ console.error('hncode: no api_key configured. Set HNCODE_API_KEY or configure a provider first. Run `hncode doctor config` to check.');
483
+ return EXIT.CONFIG;
484
+ }
485
+ const messages = [];
486
+ // Same layering as the TUI: built-in prompt first, then the user's own
487
+ // system_prompt override if any, then the /personal notes, then calm mode.
488
+ let sysText = (cfg.systemPrompt && String(cfg.systemPrompt).trim()) || SYSTEM_PROMPT;
489
+ // The inline-reasoning instruction, only for a model with no reasoning channel of its
490
+ // own — the same rule the TUI applies (see needsThinkingTags).
491
+ if (needsThinkingTags(cfg)) sysText += '\n\n' + THINKING_TAGS_INSTRUCTION;
492
+ const personal = readPersonalPrompt(cfg.workspace);
493
+ if (personal) sysText += '\n\n' + personal;
494
+ messages.push({ role: 'system', content: sysText });
495
+ if (session && session.messages) {
496
+ // Resume on a TOOL-EXCHANGE BOUNDARY: a cut that separates an assistant
497
+ // message from its tool results (or leaves orphaned tool results) is a 400
498
+ // from the provider, not just a shorter history. `canSplitAfter` is the same
499
+ // rule the compaction logic uses. System messages are dropped — the fresh
500
+ // one above is authoritative.
501
+ const hist = session.messages.filter((m) => m && m.role !== 'system');
502
+ // A session persisted mid-step can end with an assistant message whose tool
503
+ // results were never appended; sending it before the user message is a 400.
504
+ while (hist.length && hist[hist.length - 1].role === 'assistant'
505
+ && Array.isArray(hist[hist.length - 1].toolCalls) && hist[hist.length - 1].toolCalls.length) hist.pop();
506
+ let start = Math.max(0, hist.length - 30);
507
+ while (start > 0 && !canSplitAfter(hist, start - 1)) start++;
508
+ for (let i = start; i < hist.length; i++) messages.push(hist[i]);
509
+ }
510
+ // THE PROMPT ITSELF. This used to never be pushed: -p sent only the resumed
511
+ // history and the system message, so a fresh session answered nothing the
512
+ // user asked and a resumed one answered nothing new.
513
+ messages.push({ role: 'user', content: prompt });
514
+ if (session && session._unrecoverable) {
515
+ process.stderr.write(
516
+ `hncode: session ${session.id} has no readable history (its file is damaged). `
517
+ + 'Starting a new session; the old file is untouched.\n',
518
+ );
519
+ session = null;
520
+ }
521
+ const saved = session || { id: sess.newId(), title: prompt.slice(0, 60), workspace: path.resolve(process.cwd()), model: cfg.model, createdAt: Date.now(), messages: [] };
522
+ const tracker = createRunTracker();
523
+ const startedAt = Date.now();
524
+ let fatal = null;
525
+ const agent = new Agent({
526
+ cfg,
527
+ messages,
528
+ // Uncapped: run until the model finishes (see agent.js).
529
+ onEvent: (e) => {
530
+ trackEvent(tracker, e);
531
+ if (e.type === 'error') fatal = (e.error && e.error.message) || String(e.error);
532
+ if (format === 'stream-json' || format === 'json') {
533
+ // `json` mode keeps stdout clean for the final envelope, so events go to
534
+ // stderr there. `stream-json` is the streaming contract: one event/line.
535
+ if (format === 'stream-json') {
536
+ if (e.type === 'context') return; // TUI-only gauge; not part of the stream
537
+ const line = { type: e.type };
538
+ if (e.text) line.text = e.text;
539
+ if (e.name) line.name = e.name;
540
+ if (e.id) line.id = e.id;
541
+ if (e.content != null) line.content = e.content;
542
+ process.stdout.write(JSON.stringify(line) + '\n');
543
+ }
544
+ } else if (e.type === 'data') {
545
+ process.stdout.write(e.text);
546
+ }
547
+ },
548
+ });
549
+ saved.messages = messages;
550
+ // `--timeout <seconds>`: hard wall-clock cap on the whole run, so an unattended
551
+ // scripted prompt cannot hang forever on a stuck model or a wedged tool. The
552
+ // timer calls the SAME interrupt() the TUI's Esc uses — it aborts the in-flight
553
+ // request and kills the tool's AbortSignal — rather than process.exit, so the
554
+ // session is still saved and any final output is emitted.
555
+ let timedOut = false;
556
+ let timer = null;
557
+ if (timeoutSeconds > 0) {
558
+ timer = setTimeout(() => {
559
+ timedOut = true;
560
+ try { agent.interrupt(); } catch { /* best-effort */ }
561
+ }, timeoutSeconds * 1000);
562
+ if (timer.unref) timer.unref();
563
+ }
564
+ try {
565
+ await agent.run();
566
+ } finally {
567
+ if (timer) clearTimeout(timer);
568
+ // MCP stdio children were spawned for this run; most die on stdin EOF at
569
+ // process exit, but one that ignores EOF would linger. Kill them outright —
570
+ // best-effort, the result has already been produced.
571
+ try {
572
+ const mcp = await import('./mcp.js');
573
+ mcp.disconnectAll(mcp.getLiveConnections());
574
+ } catch { /* best-effort */ }
575
+ }
576
+ sess.saveSession(saved);
577
+
578
+ const reply = finalReply(messages, tracker.text);
579
+ const result = buildResult({
580
+ reply,
581
+ toolCalls: tracker.toolCalls,
582
+ files: tracker.files,
583
+ error: fatal || (tracker.errors.length ? tracker.errors[tracker.errors.length - 1] : null),
584
+ stopped: !!agent.stopRequested,
585
+ durationMs: Date.now() - startedAt,
586
+ model: cfg.model,
587
+ sessionId: saved.id,
588
+ timedOut,
589
+ });
590
+
591
+ if (format === 'json') {
592
+ // Exactly one JSON object on stdout, so `| jq` / `tail -1` works.
593
+ process.stdout.write(resultLine(result) + '\n');
594
+ } else if (format === 'stream-json') {
595
+ // A terminating event tells a streaming reader the run is over and carries
596
+ // the same envelope, so both formats end with a `result` record.
597
+ process.stdout.write(resultLine(result) + '\n');
598
+ } else {
599
+ process.stdout.write('\n');
600
+ }
601
+ return exitCodeFor(result, false);
602
+ }
603
+
604
+ // ---- TUI dispatch ----
605
+ async function startTui(opts) {
606
+ const { startTUI } = await import('./tui.js');
607
+ await startTUI(opts);
608
+ }
609
+
610
+ function loadOrCreateSession(opts, cfg) {
611
+ let session = null;
612
+ // NOTE: these keys must match what parseArgs actually produces — `--continue`
613
+ // yields `args.continue` (not `args.cont`), and `--resume <id>` is normalised
614
+ // to `args.session`. Reading the wrong key silently fell through to "create a
615
+ // new session", which is why --continue looked like it started a fresh one.
616
+ const sessionArg = opts.session;
617
+ const wantsSession = typeof sessionArg === 'string' || sessionArg === true || !!opts.sessionId;
618
+ const wantsContinue = !!(opts.continue || opts.cont);
619
+ if (wantsSession) {
620
+ const id = typeof sessionArg === 'string' ? sessionArg : opts.sessionId;
621
+ if (id) session = sess.loadSession(id) || null;
622
+ } else if (wantsContinue) {
623
+ // --continue: get the most recent session for THIS directory that has messages.
624
+ // Empty shells are created on every launch, so we skip them to find real conversations.
625
+ session = sess.latestSession(process.cwd(), undefined, { skipEmpty: true });
626
+ }
627
+ // A session whose file could not be parsed OR recovered comes back marked, with no
628
+ // messages. Resuming it would present an empty conversation that still looks like the
629
+ // old one, and the first save would write that emptiness over the file. Start fresh and
630
+ // say why, rather than letting the user type into a session that has already lost its
631
+ // history. The damaged file stays on disk, so nothing is destroyed by refusing.
632
+ if (session && session._unrecoverable) {
633
+ process.stderr.write(
634
+ `hncode: session ${session.id} has no readable history (its file is damaged). `
635
+ + 'Starting a new session; the old file is untouched.\n',
636
+ );
637
+ session = null;
638
+ }
639
+ if (!session) {
640
+ session = { id: sess.newId(), title: '', workspace: path.resolve(process.cwd()), model: cfg.model, createdAt: Date.now(), messages: [] };
641
+ } else {
642
+ // CRITICAL: Update session model to match current config!
643
+ // This prevents using stale model ID from old sessions.
644
+ session.model = cfg.model;
645
+ }
646
+ return session;
647
+ }
648
+
649
+
650
+ /**
651
+ * Parse the --web flag into { bindIp, port } or null.
652
+ * --web -> loopback, OS-assigned port
653
+ * --web 8080 -> loopback, that port
654
+ * --web 0.0.0.0:8080 -> explicit address and port
655
+ * --web 192.168.1.5 -> that address, OS-assigned port
656
+ * Anything unparseable returns null, so the flag is ignored rather than failing
657
+ * the launch — /web from inside the session still works either way.
658
+ */
659
+ export function parseWebArg(v) {
660
+ if (v == null || v === false) return null;
661
+ if (v === true) return { bindIp: '127.0.0.1', port: 0 };
662
+ const s = String(v).trim();
663
+ if (!s) return { bindIp: '127.0.0.1', port: 0 };
664
+ let bindIp = '127.0.0.1';
665
+ let port = 0;
666
+ if (/^\d+$/.test(s)) {
667
+ port = Number(s);
668
+ } else if (s.includes(':')) {
669
+ // IPv6 in brackets is deliberately not handled: /web covers it, and a
670
+ // half-parsed address is worse than ignoring the flag.
671
+ const at = s.lastIndexOf(':');
672
+ bindIp = s.slice(0, at) || '127.0.0.1';
673
+ const p = s.slice(at + 1);
674
+ if (!/^\d+$/.test(p)) return null;
675
+ port = Number(p);
676
+ } else {
677
+ bindIp = s;
678
+ }
679
+ if (port < 0 || port > 65535) return null;
680
+ return { bindIp, port };
681
+ }
682
+
683
+ export async function main(argv) {
684
+ const args = parseArgs(argv);
685
+ if (args.help) { printHelp(); return 0; }
686
+ if (args.version) { console.log(VERSION); return 0; }
687
+
688
+ // subcommands
689
+ const [cmd, sub] = args.positional;
690
+ if (cmd) {
691
+ if (cmd === 'doctor' && !sub) { return await cmdDoctorEnv(); }
692
+ const handler = SUBCOMMANDS[cmd];
693
+ if (handler) {
694
+ // A `{ needsArgs, run }` entry wants the parsed flags as well as the positional path — the one thing a
695
+ // module-level table cannot close over, because `args` lives in this function.
696
+ if (typeof handler === 'object' && typeof handler.run === 'function') {
697
+ return await handler.run(args.positional[1], args);
698
+ }
699
+ // A NESTED table (`mcp serve`) needs the flags too, for `--stdio`, `--http` and the
700
+ // workspace: the sub-handler is called with the rest of the positional path AND the
701
+ // parsed flags.
702
+ if (sub !== undefined) {
703
+ const h2 = handler[sub];
704
+ if (h2) return await h2(args.positional[2], args);
705
+ printHelp(); return 1;
706
+ }
707
+ if (typeof handler === 'function') return await handler(args.positional[1]);
708
+ printHelp(); return 0;
709
+ }
710
+ console.error(`unknown command: ${cmd}`);
711
+ return 1;
712
+ }
713
+
714
+ const baseCfg = resolveConfig();
715
+ const cfg = resolveModelArg(baseCfg, args.model);
716
+
717
+ // Plugins are normally loaded by bootstrap (bin/hncode) BEFORE this module is
718
+ // imported, because symbol patching has to register targets before the patched
719
+ // modules load. Only load them here when bootstrap did NOT already do it (e.g.
720
+ // index.js imported directly, or a test), so tools/commands still appear in
721
+ // both modes without a second load tripping "tool already registered".
722
+ try {
723
+ const { pluginsAlreadyLoaded } = await import('./bootstrap.js');
724
+ if (cfg.pluginDir && !pluginsAlreadyLoaded() && !globalThis.__hncodePluginsLoaded) {
725
+ const { loadPlugins } = await import('./plugin.js');
726
+ await loadPlugins(cfg.pluginDir);
727
+ globalThis.__hncodePluginsLoaded = true;
728
+ }
729
+ } catch (e) {
730
+ console.error('[hncode] plugin load step failed, continuing without plugins:', e && e.message);
731
+ }
732
+
733
+ // Connect configured MCP servers and register their tools.
734
+ //
735
+ // This is a FUNCTION rather than an inline block because the two modes want
736
+ // different timing:
737
+ // * headless (`-p`) MUST wait — the prompt runs immediately and its model
738
+ // request has to see the MCP tools in the tool list.
739
+ // * the TUI must NOT wait — connecting can take seconds (8s per wedged
740
+ // server), and blocking the first paint for that is unacceptable. The TUI
741
+ // starts this in the background and reports the result as a notice.
742
+ // Failures are reported but never fatal: an unreachable server must not stop
743
+ // the session from starting.
744
+ const connectMcp = async (mcpOpts = {}) => {
745
+ if (cfg.mcp === false) return { servers: [], toolCount: 0 };
746
+ try {
747
+ const mcp = await import('./mcp.js');
748
+ const { API } = await import('./plugin.js');
749
+ const mcpCfg = mcp.loadMcpConfig(cfg.workspace);
750
+ if (!Object.keys(mcpCfg.servers).length) return { servers: [], toolCount: 0 };
751
+ const res = await mcp.connectAll(mcpCfg, (spec) => API.registerTool(spec), mcpOpts);
752
+ mcp.setLiveConnections(res.servers);
753
+ if (process.env.HNCODE_MCP_VERBOSE === '1') {
754
+ for (const s of res.servers) {
755
+ console.error(s.ok ? `[hncode-mcp] ${s.name}: ${s.toolCount} tool(s)` : `[hncode-mcp] ${s.name}: ${s.error}`);
756
+ }
757
+ }
758
+ return res;
759
+ } catch (e) {
760
+ console.error(`hncode: MCP setup failed: ${e.message}`);
761
+ return { servers: [], toolCount: 0 };
762
+ }
763
+ };
764
+
765
+ // headless prompt: MCP must be live BEFORE the request goes out.
766
+ if (args.prompt) {
767
+ const format = args['output-format'];
768
+ if (!isValidFormat(format)) {
769
+ console.error(`hncode: unknown --output-format "${format}". Use one of: ${FORMATS.join(', ')}.`);
770
+ return EXIT.CONFIG;
771
+ }
772
+ await connectMcp();
773
+ let session = null;
774
+ if (args.session) session = typeof args.session === 'string' ? sess.loadSession(args.session) : sess.latestSession(undefined, undefined, { skipEmpty: true });
775
+ else if (args.continue) session = sess.latestSession(undefined, undefined, { skipEmpty: true });
776
+ // --timeout / --retries are validated here so a typo fails loudly instead of
777
+ // being parsed as NaN and silently ignored.
778
+ const timeoutSeconds = args.timeout !== undefined ? Number.parseInt(String(args.timeout), 10) : 0;
779
+ if (args.timeout !== undefined && (!Number.isInteger(timeoutSeconds) || timeoutSeconds < 1)) {
780
+ console.error(`hncode: --timeout needs a positive integer (seconds), got "${args.timeout}".`);
781
+ return EXIT.CONFIG;
782
+ }
783
+ const maxRetries = args.retries !== undefined ? Number.parseInt(String(args.retries), 10) : undefined;
784
+ if (args.retries !== undefined && (!Number.isInteger(maxRetries) || maxRetries < 0)) {
785
+ console.error(`hncode: --retries needs a non-negative integer, got "${args.retries}".`);
786
+ return EXIT.CONFIG;
787
+ }
788
+ return runPrompt({ cfg, prompt: args.prompt, format, session, modelArg: args.model, timeoutSeconds, maxRetries });
789
+ }
790
+
791
+ if (!process.stdout.isTTY) {
792
+ console.error('hncode: interactive mode requires a TTY. Use `hncode -p "prompt"` for non-interactive use.');
793
+ return EXIT.FAILURE;
794
+ }
795
+
796
+ const opts = {
797
+ cfg,
798
+ sessionFlag: args.session,
799
+ sessionId: typeof args.session === 'string' ? args.session : null,
800
+ cont: !!args.continue,
801
+ yolo: !!args.yolo,
802
+ auto: !!args.auto,
803
+ plan: !!args.plan,
804
+ addDirs: args['add-dir'] || [],
805
+ // Remote control: expose a local socket so a script can queue a prompt or
806
+ // query status on the running session (see ci.js).
807
+ control: args.control === true ? '' : (typeof args.control === 'string' ? args.control : null),
808
+ // Web UI: start the server as soon as the TUI is up. `--web` alone binds
809
+ // loopback on an OS-assigned port; `--web 0.0.0.0:8080` chooses both. Parsed
810
+ // here so it behaves like every other flag, and the TUI still has /web to
811
+ // start or stop it mid-session.
812
+ web: parseWebArg(args.web),
813
+ // MCP runs in the BACKGROUND once the TUI is up (see startTUI): connecting
814
+ // can take seconds and must not delay the first paint.
815
+ mcpConnect: connectMcp,
816
+ session: loadOrCreateSession(args, cfg),
817
+ };
818
+ await startTui(opts);
819
+ return EXIT.OK;
820
+ }
821
+
822
+ // main() is invoked by bin/hncode (the CLI entry point), which imports this module
731
823
  // and calls main(process.argv.slice(2)) explicitly.