@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
@@ -0,0 +1,103 @@
1
+ // The one place that decides whether a tool call runs without asking.
2
+ //
3
+ // WHY THIS IS A MODULE AND NOT A CLOSURE
4
+ // --------------------------------------
5
+ // The terminal answered this question inline, inside its approval callback, and the headless run
6
+ // answered it with a single `if (cfg.auto) return true` — a key nothing ever set. So every window
7
+ // that passed `--auto` still received an approval request for each tool call, and the mode the user
8
+ // had chosen in the UI had no effect on the run at all.
9
+ //
10
+ // Two front ends asking the same question need the same answer, and the terminal's version is the
11
+ // complete one: standing rules, session grants, plugin-declared auto-approval, the safe-tool list,
12
+ // read-only shell commands, and the three modes. This module holds it once.
13
+ //
14
+ // WHAT IT DOES NOT DO: it never draws anything and never asks. It returns a verdict, and each front
15
+ // end decides how to put the question to the person. That split is what lets the window show a card
16
+ // in the composer where the terminal shows a prompt on its status row.
17
+ import { decideFromRules } from './permissions.js';
18
+ import { isApprovedForSession } from './session-approvals.js';
19
+ import { isDestructiveCommand, isReadOnlyCommand } from './shell-safety.js';
20
+ import { getTool } from './tools/index.js';
21
+
22
+ // Tools whose only effects are reads or the session's own bookkeeping. A permission prompt for one
23
+ // of these is a prompt the user has no decision to make about.
24
+ //
25
+ // AskUserQuestion is on the list because ASKING is not a side effect; gating it would mean answering
26
+ // two prompts to ask one question. (In auto mode the tool refuses itself before any UI.)
27
+ const SAFE_TOOLS = [
28
+ 'Read', 'Grep', 'Glob', 'FetchURL', 'WebSearch', 'TaskOutput', 'TaskList', 'TaskStop', 'TaskWait',
29
+ 'TodoList', 'Goal', 'ActivateSkill', 'PTC', 'FileLines', 'AgentList', 'AgentMessage',
30
+ 'AgentInterrupt', 'AgentClose', 'TaskInput', 'SendMessage', 'TeamTaskCreate', 'TeamTaskUpdate',
31
+ 'TeamTaskList', 'ListTeammates', 'Memory', 'AskUserQuestion',
32
+ ];
33
+
34
+ /**
35
+ * The verdict for one tool call: `'allow'`, `'deny'` or `'ask'`.
36
+ *
37
+ * @param {object} o
38
+ * @param {string} o.mode - `ask`, `yolo` or `auto`.
39
+ * @param {string} o.toolName - the tool the model asked for.
40
+ * @param {object} o.args - that call's arguments.
41
+ * @param {object} [o.rules] - `cfg.permissions`, the standing rules.
42
+ * @param {string[]} [o.sessionApprovals] - grants given with Ctrl+A for this session.
43
+ * @returns {'allow'|'deny'|'ask'}
44
+ */
45
+ export function decideApproval({ mode, toolName, args, rules, sessionApprovals }) {
46
+ const cur = mode === 'auto' || mode === 'yolo' ? mode : 'ask';
47
+ const cmd = String((args && (args.command || args.cmd)) || '');
48
+
49
+ // STANDING RULES COME FIRST, before every mode rule, so a `deny` cannot be escaped by switching to
50
+ // Auto, an explicit `ask` still prompts in a mode that auto-approves, and an `allow` spares the
51
+ // user the same prompt on every turn.
52
+ const rule = decideFromRules(rules, toolName, args);
53
+ if (rule === 'deny') return 'deny';
54
+
55
+ // A destructive shell command is never auto-approved, not even by an `allow` rule: a rule is
56
+ // written for the command the user had in mind, and one line can carry a second command the rule
57
+ // never described.
58
+ const destructive = toolName === 'Bash' && isDestructiveCommand(cmd);
59
+ if (rule === 'allow' && !destructive) return 'allow';
60
+
61
+ // AUTO ANSWERS HERE, and it answers everything. The mode means "nothing asks": the user has
62
+ // already said they do not want to be interrupted for this session, so nothing below may send
63
+ // them a prompt — not a destructive-looking command, not a heuristic that misfired. A mode that
64
+ // claims to ask nothing and then asks anyway teaches the user to hold down Enter, which destroys
65
+ // the value of every prompt that follows.
66
+ //
67
+ // `deny` above still wins, and an explicit `ask` rule skips this: both are decisions the user
68
+ // wrote down deliberately, and they outrank a mode chosen in a menu.
69
+ if (rule !== 'ask' && cur === 'auto') return 'allow';
70
+
71
+ // Session grants come AFTER the configured rules and BEFORE the mode shortcuts: after, so a `deny`
72
+ // or an explicit `ask` rule still wins; before, so a grant covers the modes that would ask again.
73
+ if (rule !== 'ask' && isApprovedForSession(sessionApprovals, toolName, args, destructive)) return 'allow';
74
+
75
+ // A PLUGIN'S TOOL ANSWERS FOR ITSELF. A plugin's tools cannot be added to the list below from
76
+ // outside, so without this every one of them asked whatever it did. A spec declaring
77
+ // `autoApprove: true` says so itself, which is the only place that knows whether it touches
78
+ // anything.
79
+ if (rule !== 'ask') {
80
+ const own = getTool(toolName);
81
+ if (own && own.autoApprove === true) return 'allow';
82
+ }
83
+ if (rule !== 'ask' && SAFE_TOOLS.includes(toolName)) return 'allow';
84
+
85
+ // A read-only SHELL COMMAND is as safe as a read-only tool, so it runs without a prompt in Ask
86
+ // mode too — there is no decision to make about `git log`.
87
+ if (cur === 'ask' && rule !== 'ask' && toolName === 'Bash') {
88
+ if (isReadOnlyCommand(cmd) && !destructive) return 'allow';
89
+ }
90
+
91
+ // YOLO: routine work runs, and files are not a reason to ask. A user in yolo has said they do not
92
+ // want to confirm edits, and a path is still just a path. What still asks is DESTRUCTION — a
93
+ // command that deletes, rewrites history or kills a process — because that is the one class of
94
+ // action nobody means to authorise wholesale.
95
+ if (cur === 'yolo' && rule !== 'ask') {
96
+ if (toolName === 'Bash') { if (!destructive) return 'allow'; }
97
+ else return 'allow';
98
+ }
99
+
100
+ return 'ask';
101
+ }
102
+
103
+ export default { decideApproval };
package/src/plugin.js CHANGED
@@ -53,6 +53,10 @@ import { addPatch, listPatchTargets, clearPatches, LEGACY_SEAMS, installPatchLoa
53
53
  // THEME_NAMES only. colors.js has no imports of its own, so this cannot create a cycle —
54
54
  // which matters because this module is loaded very early, by bootstrap.
55
55
  import { THEME_NAMES } from './colors.js';
56
+ // The shared message table. i18n.js has no imports of its own, so this cannot close a cycle
57
+ // either — and both front ends read this same table, which is what makes a plugin's own copy
58
+ // appear translated in the terminal and the window without two registrations.
59
+ import { registerPluginMessages } from './i18n.js';
56
60
 
57
61
  // ---------------------------------------------------------------------------
58
62
  // Internal registries — these are the "live" state that plugins mutate.
@@ -229,8 +233,13 @@ const API = {
229
233
  },
230
234
 
231
235
  // Register a slash-command.
232
- // { name: 'echo', description: '...', argumentHint: '[text]', run: (arg, ctx) => {} }
233
- // `run` receives the command argument string and a context object.
236
+ //
237
+ // { name: 'echo', description: '...', argumentHint: '[text]', surfaces: ['tui'], run: (arg, ctx) => {} }
238
+ //
239
+ // `surfaces` says which front end the command belongs to: 'tui', 'gui', or both. A command
240
+ // that opens a terminal editor has no meaning in a window, and offering it there is a dead
241
+ // end the user has to discover by trying it. Omitted means both, which is what almost every
242
+ // command wants.
234
243
  registerCommand(cmd) {
235
244
  if (!cmd || typeof cmd !== 'object' || !cmd.name) {
236
245
  throw new Error('registerCommand: cmd must have a `name`');
@@ -238,6 +247,13 @@ const API = {
238
247
  if (registeredCommands.some((c) => c.name === cmd.name)) {
239
248
  throw new Error(`registerCommand: command "/${cmd.name}" is already registered`);
240
249
  }
250
+ if (cmd.surfaces !== undefined) {
251
+ const list = Array.isArray(cmd.surfaces) ? cmd.surfaces : [cmd.surfaces];
252
+ const bad = list.filter((x) => x !== 'tui' && x !== 'gui');
253
+ if (bad.length || !list.length) {
254
+ throw new Error(`registerCommand: surfaces must be 'tui', 'gui', or both (got ${JSON.stringify(cmd.surfaces)})`);
255
+ }
256
+ }
241
257
  registeredCommands.push(cmd);
242
258
  return track(() => {
243
259
  const i = registeredCommands.findIndex((c) => c.name === cmd.name);
@@ -345,6 +361,26 @@ const API = {
345
361
  return addSkillFromText(content, name);
346
362
  },
347
363
 
364
+ // ----- The plugin's own translations -----
365
+ /**
366
+ * Hand over the copy this plugin's UI shows.
367
+ *
368
+ * `table` is `{ 'my.key': { zh: '…', en: '…' } }` — the shape hncode's own strings use. The
369
+ * entries go into the same table both front ends read, so `t('zh', 'my.key')` and a window's
370
+ * `data-i18n="my.key"` both resolve without the plugin knowing which surface is running.
371
+ *
372
+ * The translation of a plugin's own words has to travel WITH the plugin: hncode has never seen
373
+ * those strings, so it cannot translate them. Returns an unregister function, and the loader
374
+ * calls it on unload — a disabled plugin's text must not stay in the table.
375
+ */
376
+ registerMessages(table) {
377
+ const owner = (currentUnit && currentUnit.name) || 'plugin';
378
+ // Through `track`, so unloadPlugins() removes the entries the same way it removes everything
379
+ // else this plugin registered. A plugin's install() may call this more than once; each call
380
+ // owns its own keys and its own teardown.
381
+ return track(registerPluginMessages(owner, table));
382
+ },
383
+
348
384
  // ----- Runtime control -----
349
385
  sendPrompt(text, opts) { return _host.sendPrompt ? _host.sendPrompt(text, opts || {}) : null; },
350
386
  addMessage(role, text) { return _host.addChat ? _host.addChat(role, text) : null; },
@@ -487,6 +523,167 @@ const API = {
487
523
  get plugins() { return [...loadedPlugins]; },
488
524
  };
489
525
 
526
+ // ---------------------------------------------------------------------------
527
+ // The three namespaces
528
+ // ---------------------------------------------------------------------------
529
+ //
530
+ // WHAT THIS IS FOR
531
+ // ----------------
532
+ // `api` above grew one method at a time, so a plugin author had no way to tell which half of it
533
+ // applied to the surface they were running on. `openEditor` opens a terminal editor and means
534
+ // nothing in a window; `registerTuiWidget` paints a string into a status row that a window does
535
+ // not have. Offering both in one flat object meant every plugin had to know, from memory, which
536
+ // methods were dead where.
537
+ //
538
+ // So the surface is split three ways, and the split is the DOCUMENTATION:
539
+ //
540
+ // api.both works on either surface. Tools, hooks, services, config, skills, files, notices.
541
+ // A plugin that only ever touches `both` runs unchanged in the terminal and the window.
542
+ // api.tui only meaningful with a terminal attached. Returns a no-op or a clear refusal on the
543
+ // window rather than pretending, so a plugin can also test `api.surface` first.
544
+ // api.gui only meaningful with a window attached.
545
+ //
546
+ // `api.surface` is `'tui'` or `'gui'`, set by the host before plugins load. A headless run with no
547
+ // front end is `'tui'` for compatibility: that is the surface every existing plugin was written
548
+ // against, and the methods it uses either work or degrade the way they always did.
549
+ //
550
+ // NOTHING IS REMOVED FROM `api`. Every method above keeps its place, because plugins in the wild
551
+ // call it directly and a move would break them without saying so. The namespaces are views onto
552
+ // the same functions — one implementation, two ways to reach it.
553
+
554
+ /** Which surface plugins are running on: 'tui' or 'gui'. Host sets it; defaults to 'tui'. */
555
+ let _surface = 'tui';
556
+
557
+ /** Point the namespaces at the surface that is actually running. */
558
+ export function setPluginSurface(surface) {
559
+ _surface = surface === 'gui' ? 'gui' : 'tui';
560
+ }
561
+
562
+ /** Refuse a call that has no meaning here, saying so instead of doing nothing silently. */
563
+ function refuseHere(what) {
564
+ return () => { throw new Error(`${what} is not available on the ${_surface} surface; check api.surface first`); };
565
+ }
566
+
567
+ const BOTH = {
568
+ // Registration that works wherever hncode runs.
569
+ registerTool: (spec) => API.registerTool(spec),
570
+ registerCommand: (cmd) => API.registerCommand(cmd),
571
+ registerHook: (name, fn) => API.registerHook(name, fn),
572
+ registerConfig: (defaults) => API.registerConfig(defaults),
573
+ provide: (name, value) => API.provide(name, value),
574
+ get: (name) => API.get(name),
575
+ has: (name) => API.has(name),
576
+ require: (name) => API.require(name),
577
+ onDispose: (fn) => API.onDispose(fn),
578
+ // Runtime control that has a meaning on both surfaces.
579
+ sendPrompt: (text, opts) => API.sendPrompt(text, opts),
580
+ addMessage: (role, text) => API.addMessage(role, text),
581
+ getMessages: () => API.getMessages(),
582
+ clearSession: () => API.clearSession(),
583
+ saveSession: (s) => API.saveSession(s),
584
+ quit: () => API.quit(),
585
+ // A notice is a line the user reads, wherever they are reading.
586
+ notice: (text, kind) => API.notice(text, kind),
587
+ // Config, files, skills.
588
+ getConfig: (key) => API.getConfig(key),
589
+ setConfig: (key, val) => API.setConfig(key, val),
590
+ persistConfig: (key, val) => API.persistConfig(key, val),
591
+ readFile: (f, enc) => API.readFile(f, enc),
592
+ writeFile: (f, d, enc) => API.writeFile(f, d, enc),
593
+ readJSON: (f, fb) => API.readJSON(f, fb),
594
+ writeJSON: (f, o) => API.writeJSON(f, o),
595
+ addSkill: (content, name) => API.addSkill(content, name),
596
+ get skills() { return API.skills; },
597
+ removeSkill: (name) => API.removeSkill(name),
598
+ // A plugin's own copy, into the table both front ends read.
599
+ registerMessages: (table) => API.registerMessages(table),
600
+ // Patching, for the seams each surface publishes.
601
+ patch: (target, handler) => API.patch(target, handler),
602
+ get patchSeams() { return API.patchSeams; },
603
+ log: pluginLogger,
604
+ // Introspection.
605
+ get tools() { return API.tools; },
606
+ get commands() { return API.commands; },
607
+ get hooks() { return API.hooks; },
608
+ get config() { return API.config; },
609
+ get plugins() { return API.plugins; },
610
+ get ctx() { return API.ctx; },
611
+ get serviceNames() { return API.serviceNames; },
612
+ };
613
+
614
+ const TUI_ONLY = {
615
+ openEditor: (opts) => API.openEditor(opts),
616
+ openPicker: (opts) => API.openPicker(opts),
617
+ openForm: (opts) => API.openForm(opts),
618
+ openPanel: (content) => API.openPanel(content),
619
+ openFileTree: (filter) => API.openFileTree(filter),
620
+ closeFileTree: () => API.closeFileTree(),
621
+ openTasksPanel: () => API.openTasksPanel(),
622
+ openRegistryBrowser: (kind) => API.openRegistryBrowser(kind),
623
+ get themeNames() { return API.themeNames; },
624
+ getTheme: () => API.getTheme(),
625
+ setTheme: (n) => API.setTheme(n),
626
+ subagents: () => API.subagents(),
627
+ messageSubagent: (ref, text) => API.messageSubagent(ref, text),
628
+ interruptSubagent: (ref) => API.interruptSubagent(ref),
629
+ closeSubagent: (ref) => API.closeSubagent(ref),
630
+ isKeyBound: (key) => API.isKeyBound(key),
631
+ get boundKeys() { return API.boundKeys; },
632
+ registerKeybind: (key, fn) => API.registerKeybind(key, fn),
633
+ registerTuiWidget: (fn) => API.registerTuiWidget(fn),
634
+ };
635
+
636
+ // The window's own surface. Every entry is a REGISTRATION the window answers to, not a paint
637
+ // call: a plugin's install() runs in the main process while the drawing happens in the renderer,
638
+ // so these record what the window should add and the renderer asks for the list.
639
+ // A host that cannot take the registration (an older window, a headless run) throws with the
640
+ // reason, so a plugin author learns it at install time rather than from a rail row that never
641
+ // appeared.
642
+ const GUI_ONLY = {
643
+ /** Add a row to the rail, above the session list: `{ id, label, icon?, onClick }`. */
644
+ registerRailAction(spec) { return needHost('registerRailAction')(spec); },
645
+ /** Remove a rail row by id. */
646
+ removeRailAction(id) { if (_host.removeRailAction) _host.removeRailAction(id); },
647
+ /** Add a button to a message's action row: `{ id, label, when?, onClick(message) }`. */
648
+ registerMessageAction(spec) { return needHost('registerMessageAction')(spec); },
649
+ /** Add an entry to the command palette: `{ name, description, run(arg, ctx) }`. */
650
+ registerPaletteCommand(spec) { return needHost('registerPaletteCommand')(spec); },
651
+ /** Add a pane to the settings sheet: `{ id, title, render(container) }`. */
652
+ registerSettingsPanel(spec) { return needHost('registerSettingsPanel')(spec); },
653
+ /** Show a line in the window's own notice area. */
654
+ notify(text, level) { if (_host.notify) _host.notify(text, level); },
655
+ /** Ask the window to repaint, after a plugin changed something it draws. */
656
+ repaint() { if (_host.repaint) _host.repaint(); },
657
+ };
658
+
659
+ /** The host's collector, or a function that says why it is missing when it is CALLED. */
660
+ function needHost(name) {
661
+ const fn = _host[name];
662
+ if (typeof fn === 'function') return fn;
663
+ return () => { throw new Error(`api.gui.${name} is not available: this host does not take GUI registrations`); };
664
+ }
665
+
666
+ // A plugin can reach ANY of the three from one object, and `surface` tells it which applies.
667
+ // `tui` and `gui` are always present so `if (api.surface === 'gui') api.gui.notify(...)` reads as
668
+ // one thought; the methods on the wrong one refuse rather than vanish, so a mistake says so.
669
+ Object.defineProperties(API, {
670
+ surface: { get: () => _surface, enumerable: true },
671
+ both: { get: () => BOTH, enumerable: true },
672
+ tui: { get: () => (_surface === 'tui' ? TUI_ONLY : refuseNamespace('tui', TUI_ONLY)), enumerable: true },
673
+ gui: { get: () => (_surface === 'gui' ? GUI_ONLY : refuseNamespace('gui', GUI_ONLY)), enumerable: true },
674
+ });
675
+
676
+ /** The wrong surface's namespace: every method refuses with the reason, rather than being absent. */
677
+ function refuseNamespace(name, real) {
678
+ const out = {};
679
+ for (const key of Object.keys(real)) {
680
+ const desc = Object.getOwnPropertyDescriptor(real, key);
681
+ if (desc && desc.get) { out[key] = undefined; continue; }
682
+ out[key] = refuseHere(`${name}.${key}`);
683
+ }
684
+ return out;
685
+ }
686
+
490
687
  // The agent context is injected lazily; plugins that need it read api.ctx
491
688
  // during their hook callbacks.
492
689
  let _ctx = null;
@@ -840,6 +1037,15 @@ if (typeof installFn !== 'function') {
840
1037
  return [...loadedPlugins];
841
1038
  }
842
1039
 
1040
+ /**
1041
+ * The plugins running right now: `{ id, name, version }` each.
1042
+ *
1043
+ * `loadPlugins` returns the same list, but only to whoever just called it. A page that draws the
1044
+ * plugin list needs it at any moment, and "a folder on disk" and "a plugin running in this
1045
+ * process" are different states — the first needs a reload to take effect.
1046
+ */
1047
+ export function loadedPluginList() { return [...loadedPlugins]; }
1048
+
843
1049
  // ---------------------------------------------------------------------------
844
1050
  // Hook runner — called by the core from the TUI / agent loop.
845
1051
  // ---------------------------------------------------------------------------
@@ -900,6 +1106,19 @@ export async function runHooks(name, ...args) {
900
1106
  // Exports for the core to consume
901
1107
  // ---------------------------------------------------------------------------
902
1108
 
1109
+ /**
1110
+ * The plugin commands a given front end should offer.
1111
+ *
1112
+ * A command registered with `surfaces: ['tui']` opens a terminal affordance and must not
1113
+ * appear in a window. Omitted means both.
1114
+ */
1115
+ export function pluginCommandsForSurface(surface) {
1116
+ return registeredCommands.filter((c) => {
1117
+ if (!c.surfaces) return true;
1118
+ const list = Array.isArray(c.surfaces) ? c.surfaces : [c.surfaces];
1119
+ return list.includes(surface);
1120
+ });
1121
+ }
903
1122
  export { API, registeredTools as pluginTools, registeredCommands as pluginCommands };
904
1123
  export const pluginPatches = registeredPatches;
905
1124
  // The plugins that loaded THIS run, as { id, name, version }. Exported for the
@@ -374,6 +374,42 @@ Do NOT report:
374
374
  Each finding: one short paragraph, why it is a bug, and the conditions under which it bites.
375
375
  Never overstate severity. If you found nothing, say so plainly and name the residual risks and
376
376
  gaps in what you checked — an empty review is a valid result.
377
+ `,
378
+ },
379
+ {
380
+ id: 'security',
381
+ label: 'Security',
382
+ full: 'Security review',
383
+ sub: 'hunt for exploitable paths, not for style',
384
+ // The failure mode of a security pass is a list of vague warnings. What makes it useful is
385
+ // the same thing that makes a code review useful: a filter for what counts, and a demand
386
+ // that every claim name the input that reaches the dangerous line.
387
+ append: `## This task: security
388
+ Do not edit files unless explicitly asked. This is an investigation.
389
+ Every finding needs an ATTACK PATH: the input, where it enters, and the line it reaches.
390
+ A category of bug is not a finding — "this could be vulnerable to X" without the path that
391
+ proves it is noise, and it teaches the reader to ignore the rest of the report.
392
+
393
+ Where to look, in this order:
394
+ - Trust boundaries: anything the user, the network, a file, or a model wrote, and the first
395
+ place it is used without being checked.
396
+ - Command and path construction: shell strings, path joins, anything that concatenates a
397
+ variable a caller controls. Name whether it can escape the workspace.
398
+ - Secrets: a token or key in a log line, an error message, a URL, a session file, a diff shown
399
+ to the user or sent to a model.
400
+ - Deserialization and parsing: JSON, TOML, YAML, archives, and what happens on a malformed or
401
+ hostile document.
402
+ - Permission checks: whether the same guard is applied on every path that reaches the action,
403
+ including the second entry point that was added later.
404
+ - Dependency and supply chain: an unpinned version, a postinstall script, a URL that is fetched
405
+ and executed.
406
+
407
+ For each finding: severity (critical / high / medium / low), the attack path in one paragraph,
408
+ the impact if it succeeds, and the smallest change that closes it. Rank by what an attacker
409
+ gains, not by how interesting the bug is.
410
+
411
+ Say plainly when a suspected issue is NOT exploitable and why — a ruled-out path saves the next
412
+ person the same work. If you found nothing, say so and name what you did not examine.
377
413
  `,
378
414
  },
379
415
  {
@@ -0,0 +1,184 @@
1
+ // The wire protocol between a front end and a running hncode session.
2
+ //
3
+ // WHY A PROTOCOL FILE
4
+ // -------------------
5
+ // The events used to be an informal set of shapes: the CLI wrote `{"type":"data","text":…}`
6
+ // to stdout and the window read them with a switch. Nothing said which fields each type
7
+ // carries, what a front end may send, or what the answer to a request looks like — so a new
8
+ // event meant guessing, and a wrong guess was a field that was silently `undefined` on the
9
+ // other side.
10
+ //
11
+ // This file is the ONE place that says it. Every event has a name and a fixed field list; every
12
+ // request has a name and an answer shape. Both ends read this, so a field cannot be added on
13
+ // one side and forgotten on the other.
14
+ //
15
+ // THE ENVELOPE
16
+ // ------------
17
+ // Everything on the wire is one JSON object per line (NDJSON). A line is a complete message, so
18
+ // a reader never has to guess where a message ends, and a writer never has to frame one.
19
+ //
20
+ // SERVER -> CLIENT
21
+ // { "type": "event", "event": { … } } a thing happened
22
+ // { "type": "reply", "id": "…", "ok": true, "result": … }
23
+ // { "type": "hello", "session": { … } } the first line, once
24
+ //
25
+ // CLIENT -> SERVER
26
+ // { "id": "…", "op": "submit", "text": "…" }
27
+ // { "id": "…", "op": "interrupt" }
28
+ //
29
+ // Every request carries an `id`, and the reply carries the same one: a front end that sends
30
+ // three things at once can tell which answer belongs to which.
31
+ //
32
+ // WHY ONE DIRECTION OF TRUTH
33
+ // --------------------------
34
+ // The session is the only authority. The front end holds a COPY of what it has seen, and the
35
+ // server pushes the authoritative state whenever it changes. The front end never merges its own
36
+ // idea of the conversation with the server's: that is how two views of one conversation drift
37
+ // apart and start disagreeing about what was said.
38
+
39
+ // The events the session publishes. Each entry says what the event means and which fields it
40
+ // carries; a field that is not listed does not exist.
41
+ export const EVENTS = {
42
+ // A chunk of the reply's text.
43
+ data: { fields: ['text'] },
44
+ // A chunk of the model's reasoning.
45
+ think: { fields: ['text'] },
46
+ // The reasoning finished for this step.
47
+ thinking_done: { fields: [] },
48
+ // A tool call started; `id` identifies it for everything that follows.
49
+ tool_start: { fields: ['id', 'name'] },
50
+ // The tool's arguments, arriving in pieces.
51
+ tool_args: { fields: ['id', 'chunk'] },
52
+ // The tool's arguments, complete.
53
+ tool_use: { fields: ['id', 'name', 'args'] },
54
+ // A piece of the tool's output.
55
+ tool_output: { fields: ['id', 'chunk'] },
56
+ // The tool finished. `failed` is true when it did not succeed.
57
+ tool_result: { fields: ['id', 'name', 'output', 'failed', 'diff', 'editDiff', 'content', 'text'] },
58
+ // The tool wants the person to type something.
59
+ tool_stdin_waiting: { fields: ['id', 'waiting'] },
60
+ // A round of the agent's loop began.
61
+ step_start: { fields: ['step', 'round'] },
62
+ // The context window's current state.
63
+ context: { fields: ['tokens', 'max', 'breakdown'] },
64
+ // Token and cost accounting.
65
+ usage: { fields: ['usage', 'total'] },
66
+ // The plan the agent is working through.
67
+ todos: { fields: ['todos'] },
68
+ // The turn's prose is complete.
69
+ done: { fields: [] },
70
+ // The turn was stopped by the person.
71
+ stopped: { fields: [] },
72
+ // The turn ended because the provider aborted it.
73
+ aborted: { fields: [] },
74
+ // Something went wrong. `error` says what.
75
+ error: { fields: ['error'] },
76
+ // A line was steered into the running turn.
77
+ steer: { fields: ['text'] },
78
+ // The history was compacted.
79
+ compacting: { fields: ['before', 'keep', 'dropped'] },
80
+ // The compaction was called off.
81
+ compaction_cancelled: { fields: ['reason'] },
82
+ // Old tool results were dropped to make room.
83
+ results_trimmed: { fields: ['elided', 'elidedBytes'] },
84
+ // The provider's response was truncated and the turn was retried.
85
+ truncation_recovery: { fields: ['attempt'] },
86
+ // The session's objective changed.
87
+ goal: { fields: ['goal', 'owner', 'round'] },
88
+ // The tool wants permission to run.
89
+ // HYPHENATED, matching the window's own switch. The underscore spelling never matched, so a
90
+ // tool waiting for permission was invisible and its turn hung.
91
+ 'approval-request': { fields: ['id', 'name', 'args'] },
92
+ // The tool wants the person to answer a question.
93
+ 'question-request': { fields: ['id', 'questions'] },
94
+ // The status sentence for the session's footer.
95
+ status: { fields: ['status'] },
96
+ };
97
+
98
+ // The requests a front end may make.
99
+ //
100
+ // submit — run a turn with this text
101
+ // dispatch — run a slash command
102
+ // interrupt — stop the running turn
103
+ // enqueue — queue a line for after the current turn
104
+ // set_mode — change the permission mode
105
+ // approve — answer a permission request
106
+ // answer — answer a question request
107
+ // ping — keep the connection alive
108
+ export const REQUESTS = {
109
+ // Which conversation this connection is watching. Answered with its current state, so a front
110
+ // end that just connected does not start from an empty window.
111
+ // `workspace` is the folder the caller wants a NEW conversation to work in. The catalogue strips
112
+ // any field it does not name, so leaving it out here dropped the window's chosen folder before
113
+ // the server ever saw it.
114
+ open: { fields: ['sessionId', 'workspace'], result: 'object' },
115
+ submit: { fields: ['text'], result: 'null' },
116
+ dispatch: { fields: ['cmd', 'arg'], result: 'any' },
117
+ interrupt: { fields: [], result: 'null' },
118
+ enqueue: { fields: ['text'], result: 'boolean' },
119
+ set_mode: { fields: ['mode'], result: 'string' },
120
+ // The folder a conversation works in. The chip can change it mid-session, and every tool
121
+ // resolves a path against it.
122
+ set_workspace: { fields: ['workspace'], result: 'boolean' },
123
+ // Re-read config.toml. The window owns the model picker, and every choice writes that file;
124
+ // without this the server keeps the model it resolved at startup.
125
+ reload_config: { fields: [], result: 'object' },
126
+ approve: { fields: ['target', 'approved'], result: 'null' },
127
+ answer: { fields: ['target', 'answers'], result: 'null' },
128
+ ping: { fields: [], result: 'string' },
129
+ };
130
+
131
+ /**
132
+ * Build a server-to-client message.
133
+ *
134
+ * `event` is checked against the catalogue: an event nobody declared is a mistake, and it is
135
+ * worth saying so where it happened rather than letting the other end read a missing field.
136
+ */
137
+ export function eventMessage(name, payload = {}) {
138
+ const spec = EVENTS[name];
139
+ if (!spec) throw new Error(`unknown event: ${name}`);
140
+ const event = { type: name };
141
+ for (const f of spec.fields) {
142
+ if (payload[f] !== undefined) event[f] = payload[f];
143
+ }
144
+ return { type: 'event', event };
145
+ }
146
+
147
+ /**
148
+ * Build a client-to-server message.
149
+ *
150
+ * The same check as the events: an unknown operation is rejected at the boundary, with a reason
151
+ * the caller can show, rather than being ignored and leaving the caller waiting for an answer
152
+ * that will never come.
153
+ */
154
+ export function requestMessage(id, op, payload = {}) {
155
+ const spec = REQUESTS[op];
156
+ if (!spec) throw new Error(`unknown operation: ${op}`);
157
+ const msg = { id: String(id || ''), op };
158
+ for (const f of spec.fields) {
159
+ if (payload[f] !== undefined) msg[f] = payload[f];
160
+ }
161
+ return msg;
162
+ }
163
+
164
+ /** Is this a well-formed request? Returns an error string, or '' when it is fine. */
165
+ export function validateRequest(msg) {
166
+ if (!msg || typeof msg !== 'object') return 'not an object';
167
+ if (typeof msg.op !== 'string') return 'no op';
168
+ const spec = REQUESTS[msg.op];
169
+ if (!spec) return `unknown operation: ${msg.op}`;
170
+ if (msg.id === undefined || msg.id === null || msg.id === '') return 'no id';
171
+ if (msg.op === 'submit' && !(typeof msg.text === 'string' && msg.text.trim())) {
172
+ return 'submit needs a text';
173
+ }
174
+ if (msg.op === 'dispatch' && !(typeof msg.cmd === 'string' && msg.cmd.trim())) {
175
+ return 'dispatch needs a command';
176
+ }
177
+ if (msg.op === 'enqueue' && !(typeof msg.text === 'string' && msg.text.trim())) {
178
+ return 'enqueue needs a text';
179
+ }
180
+ if (msg.op === 'set_mode' && !['ask', 'yolo', 'auto'].includes(msg.mode)) {
181
+ return `unknown mode: ${msg.mode}`;
182
+ }
183
+ return '';
184
+ }
@@ -120,7 +120,11 @@ export function rowsForTab(state, tabId) {
120
120
  return (d.loaded || []).map((p) => ({
121
121
  name: p.name,
122
122
  label: p.name,
123
- description: `v${p.version || '0.0.0'} · ${p.id}`,
123
+ // WHAT IT IS FIRST, then the version: a reader looking at a list of loaded plugins wants to
124
+ // recognise them, not to read three version strings.
125
+ description: p.description
126
+ ? `${p.description} · v${p.version || '0.0.0'}`
127
+ : `v${p.version || '0.0.0'} · ${p.id}`,
124
128
  status: 'loaded',
125
129
  statusTone: 'ok',
126
130
  action: 'none',
@@ -148,7 +152,10 @@ export function rowsForTab(state, tabId) {
148
152
  return (d.onDisk || []).map((p) => ({
149
153
  name: p.name,
150
154
  label: p.name + (p.kind === 'dir' ? '/' : ''),
151
- description: isLoaded(p) ? 'loaded in this session' : 'not loaded — Need Restart',
155
+ // THE DESCRIPTION, WITH THE LOAD STATE AFTER IT. The state alone told the reader which rows
156
+ // needed a restart and nothing about what any of them did.
157
+ description: [p.description, isLoaded(p) ? 'loaded in this session' : 'not loaded — Need Restart']
158
+ .filter(Boolean).join(' · '),
152
159
  status: isLoaded(p) ? 'loaded' : 'Need Restart',
153
160
  statusTone: isLoaded(p) ? 'ok' : 'warn',
154
161
  action: 'remove-plugin',
@@ -158,7 +165,11 @@ export function rowsForTab(state, tabId) {
158
165
  return (d.remote || []).map((r) => ({
159
166
  name: r.name,
160
167
  label: r.name,
161
- description: local.has(r.name) ? 'already installed locally' : 'available in the repository',
168
+ // WHAT THE PLUGIN IS, in its author's words. This line used to be a fixed "available in the
169
+ // repository", which is true of every row and therefore tells the reader nothing — a remote catalogue
170
+ // of names is the same as no catalogue.
171
+ description: r.description
172
+ || (local.has(r.name) ? 'already installed locally' : '(no description in the plugin header)'),
162
173
  status: local.has(r.name) ? 'Installed' : 'Not Install',
163
174
  statusTone: local.has(r.name) ? 'ok' : 'warn',
164
175
  action: local.has(r.name) ? 'reinstall-plugin' : 'install-plugin',