@hncode/hncode 0.8.5 → 1.0.0

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.
Files changed (159) hide show
  1. package/README.md +30 -0
  2. package/README_CN.md +27 -0
  3. package/package.json +1 -1
  4. package/src/agent.js +172 -43
  5. package/src/bootstrap.js +63 -56
  6. package/src/ci.js +247 -247
  7. package/src/colors.js +5 -1
  8. package/src/commands.js +121 -0
  9. package/src/composer.js +31 -1
  10. package/src/config.js +177 -45
  11. package/src/context.js +29 -0
  12. package/src/files.js +32 -0
  13. package/src/fx.js +19 -2
  14. package/src/i18n.js +180 -131
  15. package/src/index.js +558 -77
  16. package/src/permission-gate.js +103 -0
  17. package/src/plugin.js +221 -2
  18. package/src/prompt-presets.js +36 -0
  19. package/src/protocol.js +184 -0
  20. package/src/registry-browser.js +14 -3
  21. package/src/remote.js +117 -5
  22. package/src/schedule.js +148 -11
  23. package/src/serve.js +613 -0
  24. package/src/session-client.js +148 -0
  25. package/src/session-host.js +52 -0
  26. package/src/session.js +26 -3
  27. package/src/settings-schema.js +2 -2
  28. package/src/status-line.js +48 -0
  29. package/src/term.js +20 -1
  30. package/src/toml.js +18 -4
  31. package/src/tool-line.js +13 -6
  32. package/src/tool-status.js +45 -0
  33. package/src/tools/bash.js +43 -24
  34. package/src/tools/edit.js +10 -5
  35. package/src/tools/web-search.js +8 -5
  36. package/src/tools/write.js +28 -3
  37. package/src/tui.js +498 -1397
  38. package/src/ws.js +248 -0
  39. package/src/session-hub.js +0 -445
  40. package/src/web-auth.js +0 -98
  41. package/src/web-daemon-cli.js +0 -63
  42. package/src/web-daemon-client.js +0 -203
  43. package/src/web-daemon.js +0 -894
  44. package/src/web-live.js +0 -250
  45. package/src/web-public/app.css +0 -1524
  46. package/src/web-public/app.js +0 -2969
  47. package/src/web-public/complete.js +0 -154
  48. package/src/web-public/fonts/JetBrainsMono-Bold.woff2 +0 -0
  49. package/src/web-public/fonts/JetBrainsMono-Regular.woff2 +0 -0
  50. package/src/web-public/fonts/noto-sans-sc-100-400-normal.woff2 +0 -0
  51. package/src/web-public/fonts/noto-sans-sc-101-400-normal.woff2 +0 -0
  52. package/src/web-public/fonts/noto-sans-sc-102-400-normal.woff2 +0 -0
  53. package/src/web-public/fonts/noto-sans-sc-103-400-normal.woff2 +0 -0
  54. package/src/web-public/fonts/noto-sans-sc-104-400-normal.woff2 +0 -0
  55. package/src/web-public/fonts/noto-sans-sc-105-400-normal.woff2 +0 -0
  56. package/src/web-public/fonts/noto-sans-sc-106-400-normal.woff2 +0 -0
  57. package/src/web-public/fonts/noto-sans-sc-107-400-normal.woff2 +0 -0
  58. package/src/web-public/fonts/noto-sans-sc-108-400-normal.woff2 +0 -0
  59. package/src/web-public/fonts/noto-sans-sc-109-400-normal.woff2 +0 -0
  60. package/src/web-public/fonts/noto-sans-sc-110-400-normal.woff2 +0 -0
  61. package/src/web-public/fonts/noto-sans-sc-111-400-normal.woff2 +0 -0
  62. package/src/web-public/fonts/noto-sans-sc-112-400-normal.woff2 +0 -0
  63. package/src/web-public/fonts/noto-sans-sc-113-400-normal.woff2 +0 -0
  64. package/src/web-public/fonts/noto-sans-sc-114-400-normal.woff2 +0 -0
  65. package/src/web-public/fonts/noto-sans-sc-115-400-normal.woff2 +0 -0
  66. package/src/web-public/fonts/noto-sans-sc-116-400-normal.woff2 +0 -0
  67. package/src/web-public/fonts/noto-sans-sc-117-400-normal.woff2 +0 -0
  68. package/src/web-public/fonts/noto-sans-sc-118-400-normal.woff2 +0 -0
  69. package/src/web-public/fonts/noto-sans-sc-119-400-normal.woff2 +0 -0
  70. package/src/web-public/fonts/noto-sans-sc-21-400-normal.woff2 +0 -0
  71. package/src/web-public/fonts/noto-sans-sc-22-400-normal.woff2 +0 -0
  72. package/src/web-public/fonts/noto-sans-sc-23-400-normal.woff2 +0 -0
  73. package/src/web-public/fonts/noto-sans-sc-24-400-normal.woff2 +0 -0
  74. package/src/web-public/fonts/noto-sans-sc-25-400-normal.woff2 +0 -0
  75. package/src/web-public/fonts/noto-sans-sc-26-400-normal.woff2 +0 -0
  76. package/src/web-public/fonts/noto-sans-sc-27-400-normal.woff2 +0 -0
  77. package/src/web-public/fonts/noto-sans-sc-28-400-normal.woff2 +0 -0
  78. package/src/web-public/fonts/noto-sans-sc-29-400-normal.woff2 +0 -0
  79. package/src/web-public/fonts/noto-sans-sc-30-400-normal.woff2 +0 -0
  80. package/src/web-public/fonts/noto-sans-sc-31-400-normal.woff2 +0 -0
  81. package/src/web-public/fonts/noto-sans-sc-32-400-normal.woff2 +0 -0
  82. package/src/web-public/fonts/noto-sans-sc-33-400-normal.woff2 +0 -0
  83. package/src/web-public/fonts/noto-sans-sc-34-400-normal.woff2 +0 -0
  84. package/src/web-public/fonts/noto-sans-sc-35-400-normal.woff2 +0 -0
  85. package/src/web-public/fonts/noto-sans-sc-36-400-normal.woff2 +0 -0
  86. package/src/web-public/fonts/noto-sans-sc-37-400-normal.woff2 +0 -0
  87. package/src/web-public/fonts/noto-sans-sc-38-400-normal.woff2 +0 -0
  88. package/src/web-public/fonts/noto-sans-sc-39-400-normal.woff2 +0 -0
  89. package/src/web-public/fonts/noto-sans-sc-4-400-normal.woff2 +0 -0
  90. package/src/web-public/fonts/noto-sans-sc-40-400-normal.woff2 +0 -0
  91. package/src/web-public/fonts/noto-sans-sc-41-400-normal.woff2 +0 -0
  92. package/src/web-public/fonts/noto-sans-sc-42-400-normal.woff2 +0 -0
  93. package/src/web-public/fonts/noto-sans-sc-43-400-normal.woff2 +0 -0
  94. package/src/web-public/fonts/noto-sans-sc-44-400-normal.woff2 +0 -0
  95. package/src/web-public/fonts/noto-sans-sc-45-400-normal.woff2 +0 -0
  96. package/src/web-public/fonts/noto-sans-sc-46-400-normal.woff2 +0 -0
  97. package/src/web-public/fonts/noto-sans-sc-47-400-normal.woff2 +0 -0
  98. package/src/web-public/fonts/noto-sans-sc-48-400-normal.woff2 +0 -0
  99. package/src/web-public/fonts/noto-sans-sc-49-400-normal.woff2 +0 -0
  100. package/src/web-public/fonts/noto-sans-sc-5-400-normal.woff2 +0 -0
  101. package/src/web-public/fonts/noto-sans-sc-50-400-normal.woff2 +0 -0
  102. package/src/web-public/fonts/noto-sans-sc-51-400-normal.woff2 +0 -0
  103. package/src/web-public/fonts/noto-sans-sc-52-400-normal.woff2 +0 -0
  104. package/src/web-public/fonts/noto-sans-sc-53-400-normal.woff2 +0 -0
  105. package/src/web-public/fonts/noto-sans-sc-54-400-normal.woff2 +0 -0
  106. package/src/web-public/fonts/noto-sans-sc-55-400-normal.woff2 +0 -0
  107. package/src/web-public/fonts/noto-sans-sc-56-400-normal.woff2 +0 -0
  108. package/src/web-public/fonts/noto-sans-sc-57-400-normal.woff2 +0 -0
  109. package/src/web-public/fonts/noto-sans-sc-58-400-normal.woff2 +0 -0
  110. package/src/web-public/fonts/noto-sans-sc-59-400-normal.woff2 +0 -0
  111. package/src/web-public/fonts/noto-sans-sc-6-400-normal.woff2 +0 -0
  112. package/src/web-public/fonts/noto-sans-sc-60-400-normal.woff2 +0 -0
  113. package/src/web-public/fonts/noto-sans-sc-61-400-normal.woff2 +0 -0
  114. package/src/web-public/fonts/noto-sans-sc-62-400-normal.woff2 +0 -0
  115. package/src/web-public/fonts/noto-sans-sc-63-400-normal.woff2 +0 -0
  116. package/src/web-public/fonts/noto-sans-sc-64-400-normal.woff2 +0 -0
  117. package/src/web-public/fonts/noto-sans-sc-65-400-normal.woff2 +0 -0
  118. package/src/web-public/fonts/noto-sans-sc-66-400-normal.woff2 +0 -0
  119. package/src/web-public/fonts/noto-sans-sc-67-400-normal.woff2 +0 -0
  120. package/src/web-public/fonts/noto-sans-sc-68-400-normal.woff2 +0 -0
  121. package/src/web-public/fonts/noto-sans-sc-69-400-normal.woff2 +0 -0
  122. package/src/web-public/fonts/noto-sans-sc-70-400-normal.woff2 +0 -0
  123. package/src/web-public/fonts/noto-sans-sc-71-400-normal.woff2 +0 -0
  124. package/src/web-public/fonts/noto-sans-sc-72-400-normal.woff2 +0 -0
  125. package/src/web-public/fonts/noto-sans-sc-73-400-normal.woff2 +0 -0
  126. package/src/web-public/fonts/noto-sans-sc-74-400-normal.woff2 +0 -0
  127. package/src/web-public/fonts/noto-sans-sc-75-400-normal.woff2 +0 -0
  128. package/src/web-public/fonts/noto-sans-sc-76-400-normal.woff2 +0 -0
  129. package/src/web-public/fonts/noto-sans-sc-77-400-normal.woff2 +0 -0
  130. package/src/web-public/fonts/noto-sans-sc-78-400-normal.woff2 +0 -0
  131. package/src/web-public/fonts/noto-sans-sc-79-400-normal.woff2 +0 -0
  132. package/src/web-public/fonts/noto-sans-sc-80-400-normal.woff2 +0 -0
  133. package/src/web-public/fonts/noto-sans-sc-81-400-normal.woff2 +0 -0
  134. package/src/web-public/fonts/noto-sans-sc-82-400-normal.woff2 +0 -0
  135. package/src/web-public/fonts/noto-sans-sc-83-400-normal.woff2 +0 -0
  136. package/src/web-public/fonts/noto-sans-sc-84-400-normal.woff2 +0 -0
  137. package/src/web-public/fonts/noto-sans-sc-85-400-normal.woff2 +0 -0
  138. package/src/web-public/fonts/noto-sans-sc-86-400-normal.woff2 +0 -0
  139. package/src/web-public/fonts/noto-sans-sc-87-400-normal.woff2 +0 -0
  140. package/src/web-public/fonts/noto-sans-sc-88-400-normal.woff2 +0 -0
  141. package/src/web-public/fonts/noto-sans-sc-89-400-normal.woff2 +0 -0
  142. package/src/web-public/fonts/noto-sans-sc-90-400-normal.woff2 +0 -0
  143. package/src/web-public/fonts/noto-sans-sc-91-400-normal.woff2 +0 -0
  144. package/src/web-public/fonts/noto-sans-sc-97-400-normal.woff2 +0 -0
  145. package/src/web-public/fonts/noto-sans-sc-98-400-normal.woff2 +0 -0
  146. package/src/web-public/fonts/noto-sans-sc-99-400-normal.woff2 +0 -0
  147. package/src/web-public/fonts/noto-sans-sc.css +0 -775
  148. package/src/web-public/fonts.css +0 -31
  149. package/src/web-public/home.css +0 -222
  150. package/src/web-public/home.html +0 -33
  151. package/src/web-public/home.js +0 -160
  152. package/src/web-public/i18n.js +0 -983
  153. package/src/web-public/index.html +0 -196
  154. package/src/web-public/login.css +0 -123
  155. package/src/web-public/login.html +0 -25
  156. package/src/web-public/login.js +0 -46
  157. package/src/web-public/settings.js +0 -290
  158. package/src/web-ws.js +0 -226
  159. package/src/web.js +0 -430
package/src/composer.js CHANGED
@@ -51,10 +51,40 @@ export function expandPastes(text, pastes) {
51
51
  if (!pastes || !text || !text.includes('[paste #')) return text;
52
52
  return text.replace(PASTE_MARKER_RE, (whole, id) => {
53
53
  const entry = pastes.get(Number(id));
54
- return entry ? entry.text : whole;
54
+ if (!entry) return whole;
55
+ // A PASTED FILE IS A QUOTED PATH. The window put it there; the user did not type it. Unquoted, a
56
+ // path with a space splits into two words and a Windows path with a parenthesis breaks a command.
57
+ if (entry.kind === 'image' || looksLikePath(entry.text)) return quotePath(entry.text);
58
+ return entry.text;
55
59
  });
56
60
  }
57
61
 
62
+ /**
63
+ * Is this payload a single path, rather than prose somebody typed?
64
+ *
65
+ * A pasted file is one line, has no sentence in it, and either carries a path separator or ends in an
66
+ * extension. Prose can contain a slash — "and/or" — so a separator alone is not enough; the absence of
67
+ * spaces is what separates a path from a sentence.
68
+ */
69
+ function looksLikePath(text) {
70
+ const s = String(text == null ? '' : text).trim();
71
+ if (!s || s.includes('\n')) return false;
72
+ // A sentence: several words with spaces between them. A path may have spaces, but never three words,
73
+ // so a payload that is only a path is short and has an extension or a separator.
74
+ if (/\.[A-Za-z0-9]{1,5}$/.test(s)) return true;
75
+ // No extension: a directory pasted from Explorer, which still arrives as one line with separators.
76
+ return !/\s/.test(s) && /[\\/]/.test(s);
77
+ }
78
+
79
+ /** Wrap a path in double quotes, unless it is already quoted. */
80
+ function quotePath(p) {
81
+ const s = String(p == null ? '' : p).trim();
82
+ if (!s) return s;
83
+ // ALREADY QUOTED IS NOT QUOTED AGAIN: a path the user pasted with quotes would come out as ""…""
84
+ if (/^"[\s\S]*"$/.test(s) || /^'[\s\S]*'$/.test(s)) return s;
85
+ return `"${s}"`;
86
+ }
87
+
58
88
  /**
59
89
  * Chip each collapsed-paste marker with a selection background, leaving non-marker text untouched.
60
90
  *
package/src/config.js CHANGED
@@ -118,7 +118,7 @@ export function writeMemoryRaw(scope, workspace, text) {
118
118
  return file;
119
119
  }
120
120
  fs.mkdirSync(path.dirname(file), { recursive: true });
121
- fs.writeFileSync(file, value.replace(/\s+$/, '') + '\n', 'utf8');
121
+ writeConfigFile(file, value.replace(/\s+$/, '') + '\n', 'utf8');
122
122
  return file;
123
123
  }
124
124
 
@@ -192,7 +192,7 @@ export function writePersonalPrompt(scope, workspace, text) {
192
192
  return file;
193
193
  }
194
194
  fs.mkdirSync(path.dirname(file), { recursive: true });
195
- fs.writeFileSync(file, value.replace(/\s+$/, '') + '\n', 'utf8');
195
+ writeConfigFile(file, value.replace(/\s+$/, '') + '\n', 'utf8');
196
196
  return file;
197
197
  }
198
198
 
@@ -313,27 +313,27 @@ export function clampRatio(value, fallback) {
313
313
  return (v > 0 && v < 1) ? v : fallback;
314
314
  }
315
315
 
316
- // ---- the runtime's own language -------------------------------------------
317
-
318
- /**
319
- * The language the SYSTEM is set to, as `zh` or `en`.
320
- *
321
- * Region, not timezone: a machine can sit in any timezone and still be an English
322
- * install. `Intl` reports what the user picked in their OS settings, which is the same
323
- * value their other applications follow. Anything outside Chinese falls back to English,
324
- * which is what the UI is authored in.
325
- *
326
- * The locale is a parameter so a test can drive both branches without touching the host.
327
- */
328
- export function systemLanguage(locale) {
329
- let tag = locale;
330
- if (tag === undefined) {
331
- try { tag = new Intl.DateTimeFormat().resolvedOptions().locale; } catch { tag = ''; }
332
- }
333
- const norm = String(tag || '').trim().toLowerCase().replace('_', '-');
334
- return (norm === 'zh' || norm.startsWith('zh-')) ? 'zh' : 'en';
335
- }
336
-
316
+ // ---- the runtime's own language -------------------------------------------
317
+
318
+ /**
319
+ * The language the SYSTEM is set to, as `zh` or `en`.
320
+ *
321
+ * Region, not timezone: a machine can sit in any timezone and still be an English
322
+ * install. `Intl` reports what the user picked in their OS settings, which is the same
323
+ * value their other applications follow. Anything outside Chinese falls back to English,
324
+ * which is what the UI is authored in.
325
+ *
326
+ * The locale is a parameter so a test can drive both branches without touching the host.
327
+ */
328
+ export function systemLanguage(locale) {
329
+ let tag = locale;
330
+ if (tag === undefined) {
331
+ try { tag = new Intl.DateTimeFormat().resolvedOptions().locale; } catch { tag = ''; }
332
+ }
333
+ const norm = String(tag || '').trim().toLowerCase().replace('_', '-');
334
+ return (norm === 'zh' || norm.startsWith('zh-')) ? 'zh' : 'en';
335
+ }
336
+
337
337
  export function resolveConfig() {
338
338
  const root = loadBaseToml() || {};
339
339
  // Merge plugin-provided defaults UNDER the user's config: an explicitly set
@@ -505,12 +505,12 @@ const b = baseUrl.replace(/\/+$/, '');
505
505
  // Backwards-compat: read legacy cool_mode key if calm_mode is not set.
506
506
  : (root.calm_mode === true || root.calm_mode === 'true'
507
507
  || root.cool_mode === true || root.cool_mode === 'true'),
508
- lang: (() => {
509
- const explicit = String(process.env.HNCODE_LANG || root.lang || '').trim().toLowerCase().replace('_', '-');
510
- if (explicit === 'zh' || explicit.startsWith('zh-')) return 'zh';
511
- if (explicit === 'en' || explicit.startsWith('en-')) return 'en';
512
- return systemLanguage();
513
- })(),
508
+ lang: (() => {
509
+ const explicit = String(process.env.HNCODE_LANG || root.lang || '').trim().toLowerCase().replace('_', '-');
510
+ if (explicit === 'zh' || explicit.startsWith('zh-')) return 'zh';
511
+ if (explicit === 'en' || explicit.startsWith('en-')) return 'en';
512
+ return systemLanguage();
513
+ })(),
514
514
  // THINKING TAGS: whether the model is told to wrap its reasoning in
515
515
  // `<|thinking|>…<|/thinking|>`. THREE states: `auto` follows the model (a model with
516
516
  // a native reasoning channel does not need the tag, one without it does), and `on`
@@ -596,6 +596,17 @@ const b = baseUrl.replace(/\/+$/, '');
596
596
  promptCache: process.env.HNCODE_PROMPT_CACHE
597
597
  ? /^(1|true|yes|on)$/i.test(process.env.HNCODE_PROMPT_CACHE)
598
598
  : (root.prompt_cache === false || root.prompt_cache === 'false' ? false : true),
599
+ // THE CLOCK IN THE PROMPT, ON BY DEFAULT.
600
+ //
601
+ // A model has no clock of its own: "yesterday", "this morning" and "run it at nine" are all
602
+ // unanswerable without one, so the current time rides along with the turn. That is also a
603
+ // fingerprint — a request carrying the machine's local zone tells the provider where the
604
+ // person is — so it can be turned off, per machine, and stays off until it is turned back on.
605
+ // `inject_time = false` in config.toml, `/time off` in the terminal, or the switch in the
606
+ // window's settings.
607
+ injectTime: process.env.HNCODE_INJECT_TIME
608
+ ? /^(1|true|yes|on)$/i.test(process.env.HNCODE_INJECT_TIME)
609
+ : (root.inject_time === false || root.inject_time === 'false' ? false : true),
599
610
  // REDUCED MOTION (/reduced-motion, config.toml or the environment). When on,
600
611
  // every animation is replaced by a static or slow-breathing form: the spinner
601
612
  // does not rotate, the sweeps do not run, and the pulse does not cycle. For a
@@ -683,6 +694,27 @@ export function saveConfig(overlay) {
683
694
  // BASIC STRING ("""…"""), which keeps newlines readable and means the editor can
684
695
  // round-trip a prompt that contains them. An empty value REMOVES the key, so the
685
696
  // built-in prompt takes over again.
697
+ /**
698
+ * Write config.toml atomically.
699
+ *
700
+ * Every writer in this file used to call `fs.writeFileSync` directly, and this file holds the
701
+ * user's providers, model table and permission rules. A process that dies between open and
702
+ * close leaves a truncated file — and a truncated file reads as "no config at all", so the next
703
+ * start silently has none of it. A temp file plus a rename is atomic on both platforms this
704
+ * ships on: a reader sees either the old file or the new one.
705
+ */
706
+ function writeConfigFile(file, text) {
707
+ const tmp = file + '.tmp' + process.pid;
708
+ try {
709
+ fs.writeFileSync(tmp, text);
710
+ fs.renameSync(tmp, file);
711
+ return file;
712
+ } catch (e) {
713
+ try { fs.unlinkSync(tmp); } catch { /* never created */ }
714
+ throw e;
715
+ }
716
+ }
717
+
686
718
  export function setConfigString(key, value) {
687
719
  const file = hncodeConfigFile();
688
720
  let text = '';
@@ -730,7 +762,7 @@ export function setConfigString(key, value) {
730
762
  }
731
763
  }
732
764
  fs.mkdirSync(path.dirname(file), { recursive: true });
733
- fs.writeFileSync(file, out.join('\n') + (out.length ? '\n' : ''), 'utf8');
765
+ writeConfigFile(file, out.join('\n') + (out.length ? '\n' : ''), 'utf8');
734
766
  return file;
735
767
  return file;
736
768
  }
@@ -768,7 +800,7 @@ export function setConfigBool(key, value) {
768
800
  const re = new RegExp('^\\s*' + escapeRe(key) + '\\s*=\\s*.*$', 'm');
769
801
  if (re.test(text)) text = text.replace(re, wanted);
770
802
  else text = wanted + '\n' + text;
771
- fs.writeFileSync(file, text, 'utf8');
803
+ writeConfigFile(file, text, 'utf8');
772
804
  return file;
773
805
  }
774
806
 
@@ -837,7 +869,7 @@ export function addProvider(name, { base_url, api_key, protocol, known, catalog
837
869
  // meaningful when `known` is true.
838
870
  if (catalog) out.push(`catalog = ${q(catalog)}`);
839
871
  fs.mkdirSync(path.dirname(file), { recursive: true });
840
- fs.writeFileSync(file, out.join('\n') + '\n', 'utf8');
872
+ writeConfigFile(file, out.join('\n') + '\n', 'utf8');
841
873
  return file;
842
874
  }
843
875
 
@@ -878,7 +910,7 @@ export function removeProvider(name) {
878
910
  if (!skipping) out.push(ln);
879
911
  }
880
912
  while (out.length && out[out.length - 1].trim() === '') out.pop();
881
- fs.writeFileSync(file, out.join('\n') + (out.length ? '\n' : ''), 'utf8');
913
+ writeConfigFile(file, out.join('\n') + (out.length ? '\n' : ''), 'utf8');
882
914
  return file;
883
915
  }
884
916
 
@@ -1069,6 +1101,20 @@ export function upsertModel(provider, modelId, opts = {}) {
1069
1101
  let text = '';
1070
1102
  try { text = fs.readFileSync(file, 'utf8'); } catch { /* new file */ }
1071
1103
  const key = modelKey(provider, modelId);
1104
+
1105
+ // WHAT THE ENTRY ALREADY SAYS, read before it is replaced.
1106
+ //
1107
+ // This function deletes the whole `[models."…"]` block and writes a fresh one, so a field the
1108
+ // caller does not pass is GONE. Editing a model's context window in the settings page quietly
1109
+ // stripped its thinking levels, its reasoning flag and its price — the three things an endpoint
1110
+ // does not report and the catalog is the only source of.
1111
+ let previous = {};
1112
+ try {
1113
+ const doc = parse(text);
1114
+ const e = doc && doc.models && doc.models[key];
1115
+ if (e && typeof e === 'object') previous = e;
1116
+ } catch { /* unreadable file: nothing to preserve */ }
1117
+
1072
1118
  const unq = (s) => String(s).replace(/\\(.)/g, '$1');
1073
1119
  const modelRe = /^\s*\[models\.\s*"((?:[^"\\]|\\.)*)"\s*\]\s*$/;
1074
1120
  const lines = text.split(/\r?\n/);
@@ -1086,16 +1132,37 @@ export function upsertModel(provider, modelId, opts = {}) {
1086
1132
  out.push(`[models.${q(key)}]`);
1087
1133
  out.push(`provider = ${q(provider)}`);
1088
1134
  out.push(`model = ${q(modelId)}`);
1089
- if (opts.display_name) out.push(`display_name = ${q(opts.display_name)}`);
1090
- if (opts.contextLength) out.push(`context_length = ${Number(opts.contextLength)}`);
1091
- if (opts.maxTokens) out.push(`max_tokens = ${Number(opts.maxTokens)}`);
1092
- if (opts.maxOutputTokens) out.push(`max_output_tokens = ${Number(opts.maxOutputTokens)}`);
1093
- // Pricing, when the caller knows it. A blank means "leave the entry without
1094
- // prices", which is what an entry edited by hand in config.toml keeps.
1095
- out.push(...costLines(opts.cost));
1096
- fs.mkdirSync(path.dirname(file), { recursive: true });
1135
+
1136
+ const display = opts.display_name || previous.display_name || previous.displayName || "";
1137
+ if (display) out.push(`display_name = ${q(display)}`);
1138
+ const ctx = opts.contextLength || previous.context_length || previous.contextLength;
1139
+ if (ctx) out.push(`context_length = ${Number(ctx)}`);
1140
+ const maxTok = opts.maxTokens || previous.max_tokens || previous.maxTokens;
1141
+ if (maxTok) out.push(`max_tokens = ${Number(maxTok)}`);
1142
+ const maxOut = opts.maxOutputTokens || previous.max_output_tokens || previous.maxOutputTokens;
1143
+ if (maxOut) out.push(`max_output_tokens = ${Number(maxOut)}`);
1144
+
1145
+ // CARRIED OVER unless the caller says otherwise: these describe the MODEL, not the edit.
1146
+ const reasoning = opts.reasoning !== undefined ? opts.reasoning : previous.reasoning;
1147
+ if (reasoning !== undefined && reasoning !== null) {
1148
+ out.push(`reasoning = ${reasoning ? 'true' : 'false'}`);
1149
+ }
1150
+ const efforts = Array.isArray(opts.efforts) ? opts.efforts
1151
+ : (Array.isArray(previous.efforts) ? previous.efforts : null);
1152
+ if (efforts && efforts.length) {
1153
+ const list = efforts.map((e) => q(e)).join(', ');
1154
+ out.push(`efforts = [ ${list} ]`);
1155
+ }
1156
+
1157
+ // Pricing: the caller's value wins, else what the entry already had.
1158
+ const cost = opts.cost || (previous.cost_input !== undefined ? {
1159
+ input: previous.cost_input, output: previous.cost_output,
1160
+ cacheRead: previous.cost_cache_read, cacheWrite: previous.cost_cache_write,
1161
+ } : undefined);
1162
+ out.push(...costLines(cost));
1163
+
1097
1164
  fs.mkdirSync(path.dirname(file), { recursive: true });
1098
- fs.writeFileSync(file, out.join('\n') + '\n', 'utf8');
1165
+ writeConfigFile(file, out.join('\n') + '\n', 'utf8');
1099
1166
  return file;
1100
1167
  }
1101
1168
 
@@ -1105,6 +1172,68 @@ export function upsertModel(provider, modelId, opts = {}) {
1105
1172
  // Unlike upsertModel (one key) this is the bulk form: entries the provider no longer
1106
1173
  // offers DISAPPEAR from the file, which is what makes Ctrl+R in /provider a real
1107
1174
  // refresh rather than an in-memory-only illusion that the next launch undoes.
1175
+ /**
1176
+ * Fill one provider's model table, using the CATALOG as the source of truth.
1177
+ *
1178
+ * This is the operation /provider performs after a provider is added, and it is the reason an
1179
+ * endpoint alone is not enough: `/v1/models` reports ids and little else, while models.dev
1180
+ * carries each model's context window, output limit, whether it reasons, WHICH thinking levels
1181
+ * it offers, and its price. A model written from the endpoint alone gets a generic context bar,
1182
+ * no thinking levels and no cost — which is what the desktop did before this existed.
1183
+ *
1184
+ * Both sources are merged per model: the endpoint wins on identity, the catalog fills the
1185
+ * metadata (and covers the case where the endpoint reports nothing at all).
1186
+ */
1187
+ export async function importProviderModels(provider, { baseUrl, apiKey, protocol, catalogModels } = {}) {
1188
+ const cat = catalogModels && typeof catalogModels === 'object' ? catalogModels : {};
1189
+ let live = [];
1190
+ try {
1191
+ live = await fetchModels({ baseUrl, apiKey: apiKey || '', protocol: protocol || 'openai' });
1192
+ } catch { live = []; }
1193
+ // One row per model, with the catalog's metadata layered under whatever the endpoint
1194
+ // itself reported.
1195
+ const enrich = (id, base = {}) => {
1196
+ const c = cat[id] || {};
1197
+ const lim = c.limit || {};
1198
+ return {
1199
+ id,
1200
+ display_name: base.display || c.name || id,
1201
+ contextLength: base.contextLength || lim.context || undefined,
1202
+ maxOutputTokens: base.maxOutputTokens || lim.output || undefined,
1203
+ reasoning: base.reasoning !== undefined ? base.reasoning : c.reasoning,
1204
+ reasoningOptions: base.reasoningOptions || c.reasoning_options,
1205
+ cost: base.cost || c.cost,
1206
+ };
1207
+ };
1208
+ const merged = live.length
1209
+ ? live.map((m) => enrich(m.id, m))
1210
+ : Object.entries(cat).map(([id, m]) => enrich(id, { id, display: (m && m.name) || id }));
1211
+ // Thinking levels come ONLY from the catalog's reasoning_options. `effortsFromReasoning`
1212
+ // returns null when there is nothing usable, so a model that does not reason gets no
1213
+ // invented levels.
1214
+ const entries = [];
1215
+ for (const m of merged) {
1216
+ entries.push({
1217
+ id: m.id,
1218
+ display_name: m.display_name,
1219
+ contextLength: m.contextLength,
1220
+ maxOutputTokens: m.maxOutputTokens,
1221
+ reasoning: m.reasoning === true,
1222
+ efforts: m.efforts || effortsFromReasoning(m.reasoningOptions) || [],
1223
+ cost: costFromCatalog(m.cost),
1224
+ });
1225
+ }
1226
+ // REPLACED, not appended. `addModel` skips an id that is already present, which made a
1227
+ // refresh a no-op: the endpoint's new ids landed, but every model that was already in the
1228
+ // file kept the metadata it was first written with, even when the catalog had corrected it.
1229
+ try {
1230
+ replaceProviderModels(provider, entries);
1231
+ return { count: entries.length, fromCatalog: live.length ? 'merged' : 'catalog' };
1232
+ } catch (e) {
1233
+ return { count: 0, error: (e && e.message) || String(e) };
1234
+ }
1235
+ }
1236
+
1108
1237
  export function replaceProviderModels(provider, entries) {
1109
1238
  const file = hncodeConfigFile();
1110
1239
  let text = '';
@@ -1140,7 +1269,7 @@ export function replaceProviderModels(provider, entries) {
1140
1269
  out.push(...costLines(e.cost));
1141
1270
  }
1142
1271
  fs.mkdirSync(path.dirname(file), { recursive: true });
1143
- fs.writeFileSync(file, out.join('\n') + (out.length ? '\n' : ''), 'utf8');
1272
+ writeConfigFile(file, out.join('\n') + (out.length ? '\n' : ''), 'utf8');
1144
1273
  return file;
1145
1274
  }
1146
1275
 
@@ -1374,7 +1503,10 @@ export function rememberModel(model) {
1374
1503
  // Once a table header appears, subsequent `model =` lines are table keys,
1375
1504
  // not the active model.
1376
1505
  if (isModelLine && !seenTableHeader && !replaced) {
1377
- out.push(`model = "${String(model).replace(/"/g, '\\"')}"`);
1506
+ // SAME ESCAPING AS `q()` ELSEWHERE IN THIS FILE. This escaped only quotes, so a model id
1507
+ // holding a backslash produced `model = "a\b"` — an invalid escape, and the whole config
1508
+ // then failed to parse. Backslashes are doubled FIRST, or the quote escape gets doubled too.
1509
+ out.push(`model = "${String(model).replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"`);
1378
1510
  replaced = true;
1379
1511
  continue;
1380
1512
  }
@@ -1389,7 +1521,7 @@ export function rememberModel(model) {
1389
1521
  }
1390
1522
  fs.mkdirSync(path.dirname(file), { recursive: true });
1391
1523
  const joined = out.join('\n').replace(/^\n+/, '');
1392
- fs.writeFileSync(file, joined + (joined.endsWith('\n') ? '' : '\n'), 'utf8');
1524
+ writeConfigFile(file, joined + (joined.endsWith('\n') ? '' : '\n'), 'utf8');
1393
1525
  return file;
1394
1526
  }
1395
1527
 
package/src/context.js ADDED
@@ -0,0 +1,29 @@
1
+ // Context-window breakdown, shared by the TUI's /context and the headless event stream.
2
+ //
3
+ // It used to live inside tui.js, which meant a GUI talking to the CLI over stdout could show
4
+ // only the total token count and had to ask the agent to run /context as a prompt — a command
5
+ // the prompt path does not dispatch, so the request did nothing. Moving the calculation here
6
+ // lets the CLI attach the breakdown to its `context` event and both front ends read the same
7
+ // numbers.
8
+
9
+ import { messageTokens } from './term.js';
10
+ import { toolNames } from './tools/index.js';
11
+
12
+ export function contextBreakdown(session, cfg) {
13
+ // `cfg` is optional: callers building a state directly (tests, headless paths) may have none,
14
+ // and an absent config must only mean the tool-definition count falls back to the full list.
15
+ const conf = cfg || {};
16
+ const byRole = { system: 0, user: 0, assistant: 0, tool: 0, other: 0 };
17
+ const countByRole = { system: 0, user: 0, assistant: 0, tool: 0, other: 0 };
18
+
19
+ for (const m of ((session && session.messages) || [])) {
20
+ const t = messageTokens(m, conf);
21
+ const r = (m.role === 'system' || m.role === 'user' || m.role === 'assistant' || m.role === 'tool')
22
+ ? m.role : 'other';
23
+ byRole[r] += t;
24
+ countByRole[r] += 1;
25
+ }
26
+
27
+ const toolCount = Array.isArray(conf.toolFilter) ? conf.toolFilter.length : toolNames().length;
28
+ return { byRole, countByRole, toolDefTokens: toolCount * 8, toolCount };
29
+ }
package/src/files.js ADDED
@@ -0,0 +1,32 @@
1
+ // Workspace file collection shared by the TUI's @ mention list and the desktop's.
2
+ //
3
+ // It is bounded (depth + entry count) because the TUI calls it on a keystroke, and deterministic
4
+ // because a list that reorders between two keystrokes is unusable. Both front ends must rank the
5
+ // same paths for the same query.
6
+
7
+ import fs from 'node:fs';
8
+ import path from 'node:path';
9
+
10
+ export function collectWorkspaceFiles(root, { limit = 4000, maxDepth = 8 } = {}) {
11
+ const out = [];
12
+ const skip = new Set(['node_modules', '.git', 'dist', 'build', '.next', 'target', '__pycache__', '.hncode-media']);
13
+ const walk = (dir, rel, depth) => {
14
+ if (out.length >= limit || depth > maxDepth) return;
15
+ let entries;
16
+ try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch { return; }
17
+ entries.sort((a, b) => (b.isDirectory() - a.isDirectory()) || a.name.localeCompare(b.name));
18
+ for (const e of entries) {
19
+ if (out.length >= limit) return;
20
+ if (skip.has(e.name)) continue;
21
+ const relPath = rel ? rel + '/' + e.name : e.name;
22
+ if (e.isDirectory()) {
23
+ out.push({ label: relPath + '/', isDir: true, rel: relPath + '/' });
24
+ walk(path.join(dir, e.name), relPath, depth + 1);
25
+ } else {
26
+ out.push({ label: relPath, isDir: false, rel: relPath });
27
+ }
28
+ }
29
+ };
30
+ walk(root, '', 0);
31
+ return out;
32
+ }
package/src/fx.js CHANGED
@@ -102,7 +102,7 @@ export async function usdRate(currency, opts = {}) {
102
102
  const timer = setTimeout(() => ctrl.abort(), opts.timeoutMs || 8000);
103
103
  let json;
104
104
  try {
105
- const res = await fetch(ep.url(cur), { signal: ctrl.signal, headers: { accept: 'application/json' } });
105
+ const res = await fetch(ep.url(cur), { redirect: 'follow', signal: ctrl.signal, headers: { accept: 'application/json' } });
106
106
  if (!res.ok) continue;
107
107
  json = await res.json();
108
108
  } finally {
@@ -143,6 +143,23 @@ export function syncRate(currency, opts = {}) {
143
143
 
144
144
 
145
145
  /** Drop the memoized rates (tests, and a manual refresh). */
146
+ /**
147
+ * The currency the cost readouts use.
148
+ *
149
+ * `HNCODE_COST_CURRENCY` first, then `cost_currency` in config.toml, then USD. It lives here
150
+ * because the terminal, the window and the cost endpoint all ask the same question, and three
151
+ * answers is how one of them ends up showing dollars to someone who set ¥.
152
+ *
153
+ * `cfg` is the resolved config; `cfg.raw` is what lets a value the loader has not mapped yet
154
+ * still be read.
155
+ */
156
+ export function costCurrency(cfg, env = (typeof process !== "undefined" ? process.env : {})) {
157
+ const fromEnv = normalizeCurrency(env && env.HNCODE_COST_CURRENCY);
158
+ if (fromEnv) return fromEnv;
159
+ const raw = cfg && ((cfg.raw && cfg.raw.cost_currency) !== undefined ? cfg.raw.cost_currency : cfg.costCurrency);
160
+ return normalizeCurrency(raw) || 'USD';
161
+ }
162
+
146
163
  export function clearRateCache() { cache.clear(); }
147
164
 
148
- export default { usdRate, syncRate, convert, parseRate, normalizeCurrency, envRate, clearRateCache, SUPPORTED_CURRENCIES };
165
+ export default { usdRate, syncRate, convert, parseRate, normalizeCurrency, costCurrency, envRate, clearRateCache, SUPPORTED_CURRENCIES };