@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/mcp.js CHANGED
@@ -28,9 +28,26 @@ import os from 'node:os';
28
28
  import path from 'node:path';
29
29
  import cp from 'node:child_process';
30
30
 
31
- // The protocol revision this client speaks. Servers negotiate down if needed.
32
- export const PROTOCOL_VERSION = '2024-11-05';
33
- export const CLIENT_INFO = { name: 'hncode', version: '0.3.1' };
31
+ // The protocol revisions this client speaks, newest first.
32
+ //
33
+ // The version used to be pinned to '2024-11-05'. That is still understood by most
34
+ // servers, but a server that only speaks a newer revision rejects the handshake outright,
35
+ // and the client had no way to try the next one. The handshake now OFFERS this list and
36
+ // the server picks — or names the one it wants, which is then used for the rest of the
37
+ // session.
38
+ export const SUPPORTED_PROTOCOL_VERSIONS = [
39
+ '2025-06-18',
40
+ '2025-03-26',
41
+ '2024-11-05',
42
+ ];
43
+
44
+ // The revision sent in `initialize` when the server has not told us otherwise. The
45
+ // newest is tried first, because a server that supports only the old one will say so in
46
+ // its reply and the client then falls back.
47
+ export const PROTOCOL_VERSION = SUPPORTED_PROTOCOL_VERSIONS[0];
48
+
49
+ export const CLIENT_INFO = { name: 'hncode', version: '0.8.2' };
50
+
34
51
 
35
52
  // How long a server gets to complete the initialize + tools/list handshake. This
36
53
  // runs BEFORE the TUI opens, so it is deliberately short: a wedged server should
@@ -58,6 +75,15 @@ export function projectMcpFile(workspace) {
58
75
  // REPO's .hncode/mcp.json names, so a cloned repository would otherwise get
59
76
  // arbitrary code execution the moment hncode opens the workspace; connectAll
60
77
  // refuses them without an explicit approval (see the gate there).
78
+ //
79
+ // THE KEY NAMES DIFFER BETWEEN CLIENTS, so all of them are read:
80
+ // mcpServers Claude Desktop, Cursor, Claude Code, most of the ecosystem
81
+ // servers VS Code and a few others
82
+ // mcp_servers the snake_case spelling some tools write
83
+ // A file may hold more than one of them; they are merged, first spelling wins on a
84
+ // name clash.
85
+ const SERVER_KEYS = ['mcpServers', 'servers', 'mcp_servers'];
86
+
61
87
  export function loadMcpConfig(workspace) {
62
88
  const out = { servers: {}, errors: [] };
63
89
  const projectFile = workspace ? path.resolve(projectMcpFile(workspace)) : null;
@@ -72,16 +98,64 @@ export function loadMcpConfig(workspace) {
72
98
  try { text = fs.readFileSync(abs, 'utf8'); } catch { continue; }
73
99
  let doc;
74
100
  try { doc = JSON.parse(text); } catch (e) { out.errors.push(`${abs}: invalid JSON (${e.message})`); continue; }
75
- const servers = (doc && doc.mcpServers) || {};
101
+ const servers = {};
102
+ for (const key of SERVER_KEYS) {
103
+ const group = doc && doc[key];
104
+ if (!group || typeof group !== 'object') continue;
105
+ for (const [name, def] of Object.entries(group)) {
106
+ if (!servers[name]) servers[name] = def;
107
+ }
108
+ }
76
109
  for (const [name, def] of Object.entries(servers)) {
77
110
  if (!def || typeof def !== 'object') { out.errors.push(`${abs}: server "${name}" must be an object`); continue; }
78
- if (!def.command && !def.url) { out.errors.push(`${abs}: server "${name}" needs "command" or "url"`); continue; }
79
- out.servers[name] = { ...def, _source: abs, ...(isProject ? { _project: true } : {}) };
111
+ // The transport may be named explicitly: `type: "http"`, `"sse"`,
112
+ // `"streamable-http"` or `"stdio"`. A `url` with no type is a streamable-HTTP
113
+ // server unless it says otherwise.
114
+ const normalised = normaliseServerDef(def);
115
+ if (!normalised.command && !normalised.url) {
116
+ out.errors.push(`${abs}: server "${name}" needs "command" or "url"`);
117
+ continue;
118
+ }
119
+ out.servers[name] = { ...normalised, _source: abs, ...(isProject ? { _project: true } : {}) };
80
120
  }
81
121
  }
82
122
  return out;
83
123
  }
84
124
 
125
+ // The transport a server definition names, normalised to one of three words.
126
+ //
127
+ // "http" and "streamable-http" are the same thing (the newer transport). "sse" is the
128
+ // older one: the client opens a GET stream and POSTs its messages to a separate
129
+ // endpoint the server hands back. A definition with a `url` and no `type` is
130
+ // streamable-HTTP, which is what every current client writes.
131
+ export function transportOf(def) {
132
+ const t = String((def && (def.type || def.transport)) || '').toLowerCase();
133
+ if (t === 'sse' || t === 'sse-server') return 'sse';
134
+ if (t === 'stdio' || t === 'command') return 'stdio';
135
+ if (t === 'http' || t === 'streamable-http' || t === 'streamablehttp') return 'http';
136
+ return def && def.url ? 'http' : 'stdio';
137
+ }
138
+
139
+ // A server definition with its transport and its arguments in the shape the code uses.
140
+ export function normaliseServerDef(def) {
141
+ const out = { ...def };
142
+ out._transport = transportOf(def);
143
+ // An `args` that is a STRING is what some clients write for a single argument;
144
+ // the spawn needs an array.
145
+ if (typeof out.args === 'string') out.args = [out.args];
146
+ if (!Array.isArray(out.args)) out.args = out.args ? [out.args] : [];
147
+ // `env` may be a list of "KEY=value" strings in some tools' configs.
148
+ if (Array.isArray(out.env)) {
149
+ const env = {};
150
+ for (const entry of out.env) {
151
+ const i = String(entry).indexOf('=');
152
+ if (i > 0) env[String(entry).slice(0, i)] = String(entry).slice(i + 1);
153
+ }
154
+ out.env = env;
155
+ }
156
+ return out;
157
+ }
158
+
85
159
  // ---- JSON-RPC framing -------------------------------------------------------
86
160
 
87
161
  // A stdio connection: newline-delimited JSON-RPC over the child's stdin/stdout.
@@ -197,6 +271,130 @@ export function createHttpTransport(url, headers) {
197
271
  };
198
272
  }
199
273
 
274
+ // The OLD SSE transport, still in use by tools that predate streamable-HTTP.
275
+ //
276
+ // The shape is different and the difference is the whole point of supporting it:
277
+ // the client opens a GET and the server keeps THAT connection open, streaming
278
+ // server-initiated messages down it. The first event carries the endpoint the client
279
+ // must POST its own messages to — a separate URL, usually ending in /messages/.
280
+ //
281
+ // So a request here is: POST to the endpoint, and WAIT for the reply to come back
282
+ // down the open stream. The reply is matched by its JSON-RPC id, which is why the
283
+ // stream keeps a map of pending requests instead of answering the POST directly.
284
+ export function createSseTransport(url, headers) {
285
+ return {
286
+ kind: 'sse',
287
+ url,
288
+ headers: { accept: 'text/event-stream', ...(headers || {}) },
289
+ endpoint: null,
290
+ pending: new Map(),
291
+ nextId: 1,
292
+ controller: null,
293
+ };
294
+ }
295
+
296
+ // Open the event stream and learn the endpoint the messages go to.
297
+ //
298
+ // The endpoint event is the first thing on the wire, and everything else waits for
299
+ // it. A server that never sends one leaves the transport unable to send anything,
300
+ // which is why the open has a timeout: without it a broken server hangs the
301
+ // handshake for the whole connect budget.
302
+ export async function openSseStream(state, timeoutMs = 10_000) {
303
+ const ctrl = new AbortController();
304
+ state.controller = ctrl;
305
+ const timer = setTimeout(() => ctrl.abort(), timeoutMs);
306
+ let settled = false;
307
+ const endpointReady = new Promise((resolve, reject) => {
308
+ state._resolveEndpoint = resolve;
309
+ state._rejectEndpoint = reject;
310
+ });
311
+ try {
312
+ const res = await fetch(state.url, {
313
+ method: 'GET',
314
+ headers: state.headers,
315
+ signal: ctrl.signal,
316
+ });
317
+ if (!res.ok) throw new Error(`HTTP ${res.status} ${res.statusText}`);
318
+ const reader = res.body.getReader();
319
+ const decoder = new TextDecoder();
320
+ let buf = '';
321
+ (async () => {
322
+ try {
323
+ for (;;) {
324
+ const { done, value } = await reader.read();
325
+ if (done) break;
326
+ buf += decoder.decode(value, { stream: true });
327
+ let i;
328
+ while ((i = buf.indexOf('\n\n')) >= 0) {
329
+ const frame = buf.slice(0, i);
330
+ buf = buf.slice(i + 2);
331
+ handleSseFrame(state, frame);
332
+ }
333
+ }
334
+ } catch { /* the stream ended */ }
335
+ })();
336
+ await endpointReady;
337
+ settled = true;
338
+ return state.endpoint;
339
+ } finally {
340
+ clearTimeout(timer);
341
+ if (!settled) {
342
+ try { ctrl.abort(); } catch { /* already gone */ }
343
+ throw new Error('the SSE server did not announce an endpoint');
344
+ }
345
+ }
346
+ }
347
+
348
+ // One SSE frame: either the endpoint announcement or a JSON-RPC reply.
349
+ function handleSseFrame(state, frame) {
350
+ let event = 'message';
351
+ let data = '';
352
+ for (const line of String(frame).split('\n')) {
353
+ if (line.startsWith('event:')) event = line.slice(6).trim();
354
+ else if (line.startsWith('data:')) data += line.slice(5).trim();
355
+ }
356
+ if (event === 'endpoint') {
357
+ // The endpoint is often a RELATIVE path; the server's own URL is the base.
358
+ const ep = String(data || '');
359
+ state.endpoint = /^https?:\/\//i.test(ep) ? ep : new URL(ep, state.url).toString();
360
+ if (state._resolveEndpoint) { state._resolveEndpoint(state.endpoint); state._resolveEndpoint = null; }
361
+ return;
362
+ }
363
+ if (!data) return;
364
+ let msg;
365
+ try { msg = JSON.parse(data); } catch { return; }
366
+ if (msg && msg.id != null && state.pending.has(msg.id)) {
367
+ const p = state.pending.get(msg.id);
368
+ state.pending.delete(msg.id);
369
+ clearTimeout(p.timer);
370
+ if (msg.error) p.reject(new Error(msg.error.message || JSON.stringify(msg.error)));
371
+ else p.resolve(msg.result);
372
+ }
373
+ }
374
+
375
+ // Send one message on the SSE transport and wait for its reply on the open stream.
376
+ export async function sseRequest(state, method, params, timeoutMs = 30_000) {
377
+ if (!state.endpoint) await openSseStream(state);
378
+ const id = state.nextId++;
379
+ const body = JSON.stringify({ jsonrpc: '2.0', id, method, params: params || {} });
380
+ const post = fetch(state.endpoint, {
381
+ method: 'POST',
382
+ headers: { 'content-type': 'application/json', ...state.headers },
383
+ body,
384
+ }).then((res) => {
385
+ if (!res.ok) throw new Error(`HTTP ${res.status} ${res.statusText}`);
386
+ });
387
+ const reply = new Promise((resolve, reject) => {
388
+ const timer = setTimeout(() => {
389
+ state.pending.delete(id);
390
+ reject(new Error(`the SSE server did not answer "${method}" within ${timeoutMs}ms`));
391
+ }, timeoutMs);
392
+ state.pending.set(id, { resolve, reject, timer });
393
+ });
394
+ await post;
395
+ return reply;
396
+ }
397
+
200
398
  export async function httpRequest(state, method, params, timeoutMs = 30_000) {
201
399
  const id = state.nextId++;
202
400
  const ctrl = new AbortController();
@@ -251,28 +449,76 @@ export async function connectServer(name, def, opts = {}) {
251
449
  // handshake while keeping a dead server's cost to single-digit seconds.
252
450
  const timeoutMs = opts.timeoutMs || CONNECT_TIMEOUT_MS;
253
451
  let transport;
254
- const isHttp = !!def.url;
452
+ // The transport comes from the definition, not from "does it have a url".
453
+ //
454
+ // A definition may say `type: "sse"`, and an SSE server is reached by a URL just
455
+ // like a streamable-HTTP one — so the presence of a url says nothing about which
456
+ // protocol is spoken. `transportOf` reads the type, defaulting to streamable-HTTP
457
+ // for a url and stdio for a command, which is what every current client writes.
458
+ const kind = transportOf(def);
459
+ const isHttp = kind === 'http';
460
+ const isSse = kind === 'sse';
255
461
  try {
256
- transport = isHttp
257
- ? createHttpTransport(def.url, def.headers)
258
- : createStdioTransport(def.command, def.args, { env: def.env, cwd: def.cwd });
462
+ transport = isSse
463
+ ? createSseTransport(def.url, def.headers)
464
+ : isHttp
465
+ ? createHttpTransport(def.url, def.headers)
466
+ : createStdioTransport(def.command, def.args, { env: def.env, cwd: def.cwd });
259
467
  } catch (e) {
260
468
  return { ok: false, tools: [], error: `could not start "${name}": ${e.message}` };
261
469
  }
262
470
 
263
- const send = (method, params) => (isHttp
264
- ? httpRequest(transport, method, params, timeoutMs)
265
- : request(transport, method, params, timeoutMs));
471
+ const send = (method, params) => (isSse
472
+ ? sseRequest(transport, method, params, timeoutMs)
473
+ : isHttp
474
+ ? httpRequest(transport, method, params, timeoutMs)
475
+ : request(transport, method, params, timeoutMs));
266
476
 
267
477
  try {
268
- const init = await send('initialize', {
269
- protocolVersion: PROTOCOL_VERSION,
270
- capabilities: { tools: {} },
271
- clientInfo: CLIENT_INFO,
272
- });
478
+ // THE VERSION IS NEGOTIATED, NOT ASSUMED.
479
+ //
480
+ // A server that speaks only a revision this client did not offer rejects the
481
+ // handshake, and the client used to have no way to try the next one — one version
482
+ // was hard-coded. Each attempt is a fresh handshake, because a server that has
483
+ // already answered `initialize` will not answer it again on the same connection.
484
+ let init = null;
485
+ let lastError = null;
486
+ for (const version of SUPPORTED_PROTOCOL_VERSIONS) {
487
+ try {
488
+ init = await send('initialize', {
489
+ protocolVersion: version,
490
+ capabilities: { tools: {} },
491
+ clientInfo: CLIENT_INFO,
492
+ });
493
+ break;
494
+ } catch (e) {
495
+ lastError = e;
496
+ // A transport that has died cannot be retried on; only a REJECTED VERSION
497
+ // is worth another attempt, and that needs a fresh connection.
498
+ if (!/protocol|version|unsupported/i.test(String((e && e.message) || e))) break;
499
+ }
500
+ }
501
+ if (!init) throw lastError || new Error('the server did not answer initialize');
273
502
  if (!isHttp) notify(transport, 'notifications/initialized', {});
274
- const list = await send('tools/list', {});
275
- const tools = Array.isArray(list && list.tools) ? list.tools : [];
503
+ // THE TOOL LIST IS PAGINATED, AND THE CURSOR IS FOLLOWED.
504
+ //
505
+ // A server with more tools than it wants to send at once returns a page and a
506
+ // `nextCursor`; the client is expected to ask for the rest. Not following it meant
507
+ // that only the first page was ever registered — the bug Claude Code and Cursor both
508
+ // have. The loop stops on a missing cursor, an empty page, or a cursor that
509
+ // repeats, so a server that always returns one cannot spin forever.
510
+ const tools = [];
511
+ const seenCursors = new Set();
512
+ let cursor = undefined;
513
+ for (let page = 0; page < 50; page++) {
514
+ const list = await send('tools/list', cursor ? { cursor } : {});
515
+ const batch = Array.isArray(list && list.tools) ? list.tools : [];
516
+ tools.push(...batch);
517
+ const next = list && list.nextCursor;
518
+ if (!next || seenCursors.has(next)) break;
519
+ seenCursors.add(next);
520
+ cursor = next;
521
+ }
276
522
  return { ok: true, tools, error: null, serverInfo: (init && init.serverInfo) || {}, transport, isHttp };
277
523
  } catch (e) {
278
524
  try { if (!isHttp) transport.child.kill(); } catch { /* already gone */ }
@@ -281,11 +527,15 @@ export async function connectServer(name, def, opts = {}) {
281
527
  }
282
528
 
283
529
  // Call one tool on a connected server. Returns { ok, text, error, raw }.
284
- export async function callTool(transport, isHttp, toolName, args, timeoutMs = 60_000) {
530
+ export async function callTool(transport, toolName, args, timeoutMs = 60_000) {
531
+ const kind = (transport && transport.kind) || 'stdio';
285
532
  try {
286
- const result = isHttp
287
- ? await httpRequest(transport, 'tools/call', { name: toolName, arguments: args || {} }, timeoutMs)
288
- : await request(transport, 'tools/call', { name: toolName, arguments: args || {} }, timeoutMs);
533
+ const params = { name: toolName, arguments: args || {} };
534
+ const result = kind === 'sse'
535
+ ? await sseRequest(transport, 'tools/call', params, timeoutMs)
536
+ : kind === 'http'
537
+ ? await httpRequest(transport, 'tools/call', params, timeoutMs)
538
+ : await request(transport, 'tools/call', params, timeoutMs);
289
539
  return { ok: true, text: flattenContent(result), error: null, raw: result };
290
540
  } catch (e) {
291
541
  return { ok: false, text: '', error: e.message, raw: null };
@@ -320,7 +570,7 @@ export function mcpToolName(server, tool) {
320
570
 
321
571
  // Convert an MCP tool definition into an hncode tool spec whose execute() calls
322
572
  // back into the server.
323
- export function toHncodeSpec(server, tool, transport, isHttp) {
573
+ export function toHncodeSpec(server, tool, transport) {
324
574
  return {
325
575
  name: mcpToolName(server, tool.name),
326
576
  description: (tool.description || `MCP tool ${tool.name} from ${server}.`).slice(0, 4000),
@@ -329,7 +579,7 @@ export function toHncodeSpec(server, tool, transport, isHttp) {
329
579
  : { type: 'object', properties: {} },
330
580
  _mcp: { server, tool: tool.name },
331
581
  async execute(args) {
332
- const r = await callTool(transport, isHttp, tool.name, args);
582
+ const r = await callTool(transport, tool.name, args);
333
583
  if (!r.ok) return `Error calling ${server}/${tool.name}: ${r.error}`;
334
584
  // MCP signals tool-level failure with isError, not a JSON-RPC error.
335
585
  if (r.raw && r.raw.isError) return `Error from ${server}/${tool.name}: ${r.text}`;
@@ -362,8 +612,8 @@ export async function connectAll(config, registerTool, opts = {}) {
362
612
  if (!approved) {
363
613
  return { name, ok: false, toolCount: 0, skipped: true,
364
614
  error: 'not approved — the project-scope server was not started' };
365
- }
366
615
  }
616
+ }
367
617
  const conn = await connectServer(name, def, opts);
368
618
  if (!conn.ok) return { name, ok: false, toolCount: 0, error: conn.error, serverInfo: {} };
369
619
  let registered = 0;
@@ -371,13 +621,13 @@ export async function connectAll(config, registerTool, opts = {}) {
371
621
  for (const tool of conn.tools) {
372
622
  if (!tool || !tool.name) continue;
373
623
  try {
374
- registerTool(toHncodeSpec(name, tool, conn.transport, conn.isHttp));
624
+ registerTool(toHncodeSpec(name, tool, conn.transport));
375
625
  registered++;
376
626
  } catch (e) {
377
627
  // A name clash with a built-in is reported, not fatal: keep the rest.
378
628
  err = err || `tool "${tool.name}": ${e.message}`;
379
- }
380
629
  }
630
+ }
381
631
  return { name, ok: true, toolCount: registered, error: err, serverInfo: conn.serverInfo, transport: conn.transport, isHttp: conn.isHttp };
382
632
  }));
383
633
  const toolCount = results.reduce((n, r) => n + (r.toolCount || 0), 0);
@@ -24,6 +24,8 @@
24
24
  //
25
25
  // Pure and read-only: it measures, it never trims, loads or rewrites anything.
26
26
 
27
+ import { uiText } from './i18n.js';
28
+
27
29
  /** Content larger than this is counted separately — a single 16 KB block is the shape of
28
30
  * a runaway, while 16 KB spread evenly is nothing. */
29
31
  const LARGE_BLOB_BYTES = 16 * 1024;
@@ -184,25 +186,26 @@ export function renderMemoryProfile(p, opts = {}) {
184
186
  return ` ${v.toFixed(1)}%`.padStart(7);
185
187
  };
186
188
  const row = (label, b, n, share = true) => {
187
- lines.push(` ${label.padEnd(18)} ${mb(b).padStart(9)} MB${n != null ? ` x${n}` : ''}${share ? pct(b) : ''}`);
189
+ const text = uiText(label);
190
+ lines.push(` ${text.padEnd(18)} ${mb(b).padStart(9)} MB${n != null ? ` x${n}` : ''}${share ? pct(b) : ''}`);
188
191
  };
189
192
 
190
- lines.push(`Memory profile — ${mb(total)} MB across the forms a session holds`);
193
+ lines.push(uiText(`Memory profile — ${mb(total)} MB across the forms a session holds`));
191
194
  lines.push('');
192
- lines.push(' content (session.messages)');
195
+ lines.push(uiText(' content (session.messages)'));
193
196
  row('text', p.messages.text.bytes, p.messages.text.count);
194
- row('tool results', p.messages.toolResults.bytes, p.messages.toolResults.count);
195
- row('tool arguments', p.messages.toolArgs.bytes, p.messages.toolArgs.count);
197
+ row(uiText('tool results'), p.messages.toolResults.bytes, p.messages.toolResults.count);
198
+ row(uiText('tool arguments'), p.messages.toolArgs.bytes, p.messages.toolArgs.count);
196
199
  if (p.messages.images.bytes) row('images', p.messages.images.bytes, p.messages.images.count);
197
200
 
198
201
  if (p.transcript.count) {
199
202
  lines.push('');
200
- lines.push(' transcript (display-only, on disk)');
201
- row('all rows', p.transcript.bytes, p.transcript.count);
203
+ lines.push(uiText(' transcript (display-only, on disk)'));
204
+ row(uiText('all rows'), p.transcript.bytes, p.transcript.count);
202
205
  if (p.transcript.largeBytes) {
203
- lines.push(` of which >=16 KB: ${mb(p.transcript.largeBytes).padStart(9)} MB`);
206
+ lines.push(` ${uiText('of which >=16 KB:')} ${mb(p.transcript.largeBytes).padStart(9)} MB`);
204
207
  }
205
- lines.push(` largest row: ${mb(p.transcript.maxRowBytes).padStart(9)} MB`);
208
+ lines.push(` ${uiText('largest row:').padEnd(17)}${mb(p.transcript.maxRowBytes).padStart(9)} MB`);
206
209
  if (opts.verbose) {
207
210
  for (const [role, b] of [...p.transcript.byRole].sort((a, c) => c[1].bytes - a[1].bytes)) {
208
211
  row(` ${role}`, b.bytes, b.count);
@@ -211,22 +214,22 @@ export function renderMemoryProfile(p, opts = {}) {
211
214
  }
212
215
 
213
216
  lines.push('');
214
- lines.push(' other copies held at the same time');
215
- row('state.chat (render)', p.chat.bytes, p.chat.count);
217
+ lines.push(uiText(' other copies held at the same time'));
218
+ row(uiText('state.chat (render)'), p.chat.bytes, p.chat.count);
216
219
 
217
220
  lines.push('');
218
- lines.push(' as one JSON document (a different measure of the same data)');
221
+ lines.push(uiText(' as one JSON document (a different measure of the same data)'));
219
222
  // Measured against the CONTENT, not the content-plus-content the base holds, so these
220
223
  // two rows carry no share: they re-measure what the rows above already report.
221
- row('serialised size', p.messages.jsonBytes, null, false);
222
- row('structure + escapes', p.messages.structuralBytes, null, false);
224
+ row(uiText('serialised size'), p.messages.jsonBytes, null, false);
225
+ row(uiText('structure + escapes'), p.messages.structuralBytes, null, false);
223
226
  if (p.messages.structuralBytes > p.messages.contentBytes) {
224
- lines.push(' (structure is larger than the content — that is normal for many short messages)');
227
+ lines.push(uiText(' (structure is larger than the content — that is normal for many short messages)'));
225
228
  }
226
229
 
227
230
  if (opts.verbose && p.messages.argsByTool.size) {
228
231
  lines.push('');
229
- lines.push(' tool arguments by tool');
232
+ lines.push(uiText(' tool arguments by tool'));
230
233
  const rows = [...p.messages.argsByTool].sort((a, b) => b[1].bytes - a[1].bytes);
231
234
  for (const [name, b] of (opts.top ? rows.slice(0, opts.top) : rows)) {
232
235
  row(name, b.bytes, b.count);
package/src/plan.js CHANGED
@@ -17,6 +17,7 @@
17
17
  // tolerant: a plan is free-form Markdown, so a missed file reference degrades to
18
18
  // "fewer files listed", never to an error.
19
19
 
20
+ import { uiText, t, getUiLang } from './i18n.js';
20
21
  import fs from 'node:fs';
21
22
  import path from 'node:path';
22
23
 
@@ -113,16 +114,17 @@ export function reviewLines(plan, workspace) {
113
114
  const stats = planStats(plan);
114
115
  const files = filesReferenced(plan);
115
116
  const lines = [];
116
- lines.push(`Steps: ${stats.steps} Lines: ${stats.lines} Files mentioned: ${files.length}`);
117
+ lines.push(t(getUiLang(), 'plan.summary',
118
+ { steps: stats.steps, lines: stats.lines, files: files.length }));
117
119
  lines.push('');
118
120
  if (files.length) {
119
- lines.push('Files this plan will touch:');
121
+ lines.push(uiText('Files this plan will touch:'));
120
122
  for (const f of files.slice(0, 40)) lines.push(` ${f}`);
121
- if (files.length > 40) lines.push(` … and ${files.length - 40} more`);
123
+ if (files.length > 40) lines.push(' ' + t(getUiLang(), 'plan.andMore', { n: files.length - 40 }));
122
124
  } else {
123
- lines.push('No specific files named in the plan.');
125
+ lines.push(uiText('No specific files named in the plan.'));
124
126
  }
125
127
  lines.push('');
126
- lines.push('Enter = approve & execute e = edit the plan Esc = keep planning');
128
+ lines.push(uiText('Enter = approve & execute e = edit the plan Esc = keep planning'));
127
129
  return lines;
128
130
  }
package/src/plugin.js CHANGED
@@ -684,29 +684,45 @@ export async function loadPlugins(dir, opts = {}) {
684
684
  // Phase 1: import every file and read its metadata. Imports come first because the
685
685
  // dependency order is declared in that metadata — the graph cannot be built before
686
686
  // the modules are read.
687
+ //
688
+ // THE IMPORTS RUN IN PARALLEL, THEN THE LOOP BELOW CONSUMES THEM IN ORDER.
689
+ //
690
+ // Each file is independent, so importing them one at a time made startup pay the SUM of
691
+ // every plugin's module evaluation — measured at 165ms for eleven plugins, dominated by
692
+ // the largest one. The order that MATTERS is `inject`, applied in phase 2; the filesystem
693
+ // order only ever decided which warning was printed first.
694
+ //
695
+ // The console is redirected across the WHOLE batch rather than per import: the swap is
696
+ // global, so overlapping captures would restore each other's handlers and let plugin
697
+ // output land on the screen, which is the thing the capture exists to prevent.
698
+ const mods = new Map();
699
+ {
700
+ const restoreConsole = capturePluginConsole();
701
+ try {
702
+ await Promise.all(files.map(async ({ id: fid, full }) => {
703
+ // A query string is a DIFFERENT module instance to Node, which is exactly what
704
+ // a hot reload wants. Only on a fresh load: the startup path keeps the plain
705
+ // URL so nothing else can see two instances of a plugin.
706
+ const url = pathToFileURL(full).href + (opts.fresh ? `?v=${++loadSeq}` : '');
707
+ try {
708
+ mods.set(fid, await import(url));
709
+ } catch (e) {
710
+ // Recorded rather than thrown: one broken plugin must not stop the others, and
711
+ // the loop below reports the failure against the file it came from.
712
+ mods.set(fid, { __error: (e && e.message) || String(e) });
713
+ }
714
+ }));
715
+ } finally {
716
+ restoreConsole();
717
+ }
718
+ }
687
719
  const candidates = [];
688
- for (const { id: f, full } of files) {
720
+ for (const { id: f } of files) {
689
721
  try {
690
- // A query string is a DIFFERENT module instance to Node, which is exactly what
691
- // a hot reload wants. Only on a fresh load: the startup path keeps the plain
692
- // URL so nothing else can see two instances of a plugin.
693
- const url = pathToFileURL(full).href + (opts.fresh ? `?v=${++loadSeq}` : '');
694
- // A PLUGIN'S OWN console.log MUST NOT REACH THE SCREEN.
695
- //
696
- // The import below runs the plugin's top-level code, and `install(api)` runs more of it. Both are
697
- // plugin author territory, where `console.log` is the first thing anyone reaches for — and while the
698
- // TUI owns stdout, that write lands wherever the cursor happens to be, on top of the frame. It was
699
- // most visible after `/reload`, which re-runs every plugin's load-time logging in one burst.
700
- //
701
- // Redirected to `pluginLogger`, which queues a notice the TUI already renders in its own transcript.
702
- // The real console is restored immediately afterwards, so this covers exactly the window where
703
- // plugin code runs and nothing else.
704
- const restoreConsole = capturePluginConsole();
705
- let mod;
706
- try {
707
- mod = await import(url);
708
- } finally {
709
- restoreConsole();
722
+ const mod = mods.get(f);
723
+ if (mod && mod.__error) {
724
+ notice('error', `${f} failed to load: ${mod.__error}`);
725
+ continue;
710
726
  }
711
727
  // `install(api)` may be the named export or live on the default export.
712
728
  let installFn;