@hncode/hncode 0.8.6 → 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 (157) 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/toml.js +18 -4
  30. package/src/tool-status.js +45 -0
  31. package/src/tools/bash.js +43 -24
  32. package/src/tools/edit.js +10 -5
  33. package/src/tools/web-search.js +8 -5
  34. package/src/tools/write.js +28 -3
  35. package/src/tui.js +448 -1380
  36. package/src/ws.js +248 -0
  37. package/src/session-hub.js +0 -445
  38. package/src/web-auth.js +0 -98
  39. package/src/web-daemon-cli.js +0 -63
  40. package/src/web-daemon-client.js +0 -203
  41. package/src/web-daemon.js +0 -894
  42. package/src/web-live.js +0 -250
  43. package/src/web-public/app.css +0 -1524
  44. package/src/web-public/app.js +0 -2969
  45. package/src/web-public/complete.js +0 -154
  46. package/src/web-public/fonts/JetBrainsMono-Bold.woff2 +0 -0
  47. package/src/web-public/fonts/JetBrainsMono-Regular.woff2 +0 -0
  48. package/src/web-public/fonts/noto-sans-sc-100-400-normal.woff2 +0 -0
  49. package/src/web-public/fonts/noto-sans-sc-101-400-normal.woff2 +0 -0
  50. package/src/web-public/fonts/noto-sans-sc-102-400-normal.woff2 +0 -0
  51. package/src/web-public/fonts/noto-sans-sc-103-400-normal.woff2 +0 -0
  52. package/src/web-public/fonts/noto-sans-sc-104-400-normal.woff2 +0 -0
  53. package/src/web-public/fonts/noto-sans-sc-105-400-normal.woff2 +0 -0
  54. package/src/web-public/fonts/noto-sans-sc-106-400-normal.woff2 +0 -0
  55. package/src/web-public/fonts/noto-sans-sc-107-400-normal.woff2 +0 -0
  56. package/src/web-public/fonts/noto-sans-sc-108-400-normal.woff2 +0 -0
  57. package/src/web-public/fonts/noto-sans-sc-109-400-normal.woff2 +0 -0
  58. package/src/web-public/fonts/noto-sans-sc-110-400-normal.woff2 +0 -0
  59. package/src/web-public/fonts/noto-sans-sc-111-400-normal.woff2 +0 -0
  60. package/src/web-public/fonts/noto-sans-sc-112-400-normal.woff2 +0 -0
  61. package/src/web-public/fonts/noto-sans-sc-113-400-normal.woff2 +0 -0
  62. package/src/web-public/fonts/noto-sans-sc-114-400-normal.woff2 +0 -0
  63. package/src/web-public/fonts/noto-sans-sc-115-400-normal.woff2 +0 -0
  64. package/src/web-public/fonts/noto-sans-sc-116-400-normal.woff2 +0 -0
  65. package/src/web-public/fonts/noto-sans-sc-117-400-normal.woff2 +0 -0
  66. package/src/web-public/fonts/noto-sans-sc-118-400-normal.woff2 +0 -0
  67. package/src/web-public/fonts/noto-sans-sc-119-400-normal.woff2 +0 -0
  68. package/src/web-public/fonts/noto-sans-sc-21-400-normal.woff2 +0 -0
  69. package/src/web-public/fonts/noto-sans-sc-22-400-normal.woff2 +0 -0
  70. package/src/web-public/fonts/noto-sans-sc-23-400-normal.woff2 +0 -0
  71. package/src/web-public/fonts/noto-sans-sc-24-400-normal.woff2 +0 -0
  72. package/src/web-public/fonts/noto-sans-sc-25-400-normal.woff2 +0 -0
  73. package/src/web-public/fonts/noto-sans-sc-26-400-normal.woff2 +0 -0
  74. package/src/web-public/fonts/noto-sans-sc-27-400-normal.woff2 +0 -0
  75. package/src/web-public/fonts/noto-sans-sc-28-400-normal.woff2 +0 -0
  76. package/src/web-public/fonts/noto-sans-sc-29-400-normal.woff2 +0 -0
  77. package/src/web-public/fonts/noto-sans-sc-30-400-normal.woff2 +0 -0
  78. package/src/web-public/fonts/noto-sans-sc-31-400-normal.woff2 +0 -0
  79. package/src/web-public/fonts/noto-sans-sc-32-400-normal.woff2 +0 -0
  80. package/src/web-public/fonts/noto-sans-sc-33-400-normal.woff2 +0 -0
  81. package/src/web-public/fonts/noto-sans-sc-34-400-normal.woff2 +0 -0
  82. package/src/web-public/fonts/noto-sans-sc-35-400-normal.woff2 +0 -0
  83. package/src/web-public/fonts/noto-sans-sc-36-400-normal.woff2 +0 -0
  84. package/src/web-public/fonts/noto-sans-sc-37-400-normal.woff2 +0 -0
  85. package/src/web-public/fonts/noto-sans-sc-38-400-normal.woff2 +0 -0
  86. package/src/web-public/fonts/noto-sans-sc-39-400-normal.woff2 +0 -0
  87. package/src/web-public/fonts/noto-sans-sc-4-400-normal.woff2 +0 -0
  88. package/src/web-public/fonts/noto-sans-sc-40-400-normal.woff2 +0 -0
  89. package/src/web-public/fonts/noto-sans-sc-41-400-normal.woff2 +0 -0
  90. package/src/web-public/fonts/noto-sans-sc-42-400-normal.woff2 +0 -0
  91. package/src/web-public/fonts/noto-sans-sc-43-400-normal.woff2 +0 -0
  92. package/src/web-public/fonts/noto-sans-sc-44-400-normal.woff2 +0 -0
  93. package/src/web-public/fonts/noto-sans-sc-45-400-normal.woff2 +0 -0
  94. package/src/web-public/fonts/noto-sans-sc-46-400-normal.woff2 +0 -0
  95. package/src/web-public/fonts/noto-sans-sc-47-400-normal.woff2 +0 -0
  96. package/src/web-public/fonts/noto-sans-sc-48-400-normal.woff2 +0 -0
  97. package/src/web-public/fonts/noto-sans-sc-49-400-normal.woff2 +0 -0
  98. package/src/web-public/fonts/noto-sans-sc-5-400-normal.woff2 +0 -0
  99. package/src/web-public/fonts/noto-sans-sc-50-400-normal.woff2 +0 -0
  100. package/src/web-public/fonts/noto-sans-sc-51-400-normal.woff2 +0 -0
  101. package/src/web-public/fonts/noto-sans-sc-52-400-normal.woff2 +0 -0
  102. package/src/web-public/fonts/noto-sans-sc-53-400-normal.woff2 +0 -0
  103. package/src/web-public/fonts/noto-sans-sc-54-400-normal.woff2 +0 -0
  104. package/src/web-public/fonts/noto-sans-sc-55-400-normal.woff2 +0 -0
  105. package/src/web-public/fonts/noto-sans-sc-56-400-normal.woff2 +0 -0
  106. package/src/web-public/fonts/noto-sans-sc-57-400-normal.woff2 +0 -0
  107. package/src/web-public/fonts/noto-sans-sc-58-400-normal.woff2 +0 -0
  108. package/src/web-public/fonts/noto-sans-sc-59-400-normal.woff2 +0 -0
  109. package/src/web-public/fonts/noto-sans-sc-6-400-normal.woff2 +0 -0
  110. package/src/web-public/fonts/noto-sans-sc-60-400-normal.woff2 +0 -0
  111. package/src/web-public/fonts/noto-sans-sc-61-400-normal.woff2 +0 -0
  112. package/src/web-public/fonts/noto-sans-sc-62-400-normal.woff2 +0 -0
  113. package/src/web-public/fonts/noto-sans-sc-63-400-normal.woff2 +0 -0
  114. package/src/web-public/fonts/noto-sans-sc-64-400-normal.woff2 +0 -0
  115. package/src/web-public/fonts/noto-sans-sc-65-400-normal.woff2 +0 -0
  116. package/src/web-public/fonts/noto-sans-sc-66-400-normal.woff2 +0 -0
  117. package/src/web-public/fonts/noto-sans-sc-67-400-normal.woff2 +0 -0
  118. package/src/web-public/fonts/noto-sans-sc-68-400-normal.woff2 +0 -0
  119. package/src/web-public/fonts/noto-sans-sc-69-400-normal.woff2 +0 -0
  120. package/src/web-public/fonts/noto-sans-sc-70-400-normal.woff2 +0 -0
  121. package/src/web-public/fonts/noto-sans-sc-71-400-normal.woff2 +0 -0
  122. package/src/web-public/fonts/noto-sans-sc-72-400-normal.woff2 +0 -0
  123. package/src/web-public/fonts/noto-sans-sc-73-400-normal.woff2 +0 -0
  124. package/src/web-public/fonts/noto-sans-sc-74-400-normal.woff2 +0 -0
  125. package/src/web-public/fonts/noto-sans-sc-75-400-normal.woff2 +0 -0
  126. package/src/web-public/fonts/noto-sans-sc-76-400-normal.woff2 +0 -0
  127. package/src/web-public/fonts/noto-sans-sc-77-400-normal.woff2 +0 -0
  128. package/src/web-public/fonts/noto-sans-sc-78-400-normal.woff2 +0 -0
  129. package/src/web-public/fonts/noto-sans-sc-79-400-normal.woff2 +0 -0
  130. package/src/web-public/fonts/noto-sans-sc-80-400-normal.woff2 +0 -0
  131. package/src/web-public/fonts/noto-sans-sc-81-400-normal.woff2 +0 -0
  132. package/src/web-public/fonts/noto-sans-sc-82-400-normal.woff2 +0 -0
  133. package/src/web-public/fonts/noto-sans-sc-83-400-normal.woff2 +0 -0
  134. package/src/web-public/fonts/noto-sans-sc-84-400-normal.woff2 +0 -0
  135. package/src/web-public/fonts/noto-sans-sc-85-400-normal.woff2 +0 -0
  136. package/src/web-public/fonts/noto-sans-sc-86-400-normal.woff2 +0 -0
  137. package/src/web-public/fonts/noto-sans-sc-87-400-normal.woff2 +0 -0
  138. package/src/web-public/fonts/noto-sans-sc-88-400-normal.woff2 +0 -0
  139. package/src/web-public/fonts/noto-sans-sc-89-400-normal.woff2 +0 -0
  140. package/src/web-public/fonts/noto-sans-sc-90-400-normal.woff2 +0 -0
  141. package/src/web-public/fonts/noto-sans-sc-91-400-normal.woff2 +0 -0
  142. package/src/web-public/fonts/noto-sans-sc-97-400-normal.woff2 +0 -0
  143. package/src/web-public/fonts/noto-sans-sc-98-400-normal.woff2 +0 -0
  144. package/src/web-public/fonts/noto-sans-sc-99-400-normal.woff2 +0 -0
  145. package/src/web-public/fonts/noto-sans-sc.css +0 -775
  146. package/src/web-public/fonts.css +0 -31
  147. package/src/web-public/home.css +0 -222
  148. package/src/web-public/home.html +0 -33
  149. package/src/web-public/home.js +0 -160
  150. package/src/web-public/i18n.js +0 -983
  151. package/src/web-public/index.html +0 -196
  152. package/src/web-public/login.css +0 -123
  153. package/src/web-public/login.html +0 -25
  154. package/src/web-public/login.js +0 -46
  155. package/src/web-public/settings.js +0 -290
  156. package/src/web-ws.js +0 -226
  157. package/src/web.js +0 -430
@@ -1,445 +0,0 @@
1
- // Session hub — the single source of truth shared by the TUI and the web UI.
2
- //
3
- // WHY THIS EXISTS: the TUI is the original owner of the transcript, the agent
4
- // events and the input. The web UI must see exactly what the TUI sees AND be able
5
- // to drive the same session (send prompts, run slash commands, interrupt, answer
6
- // approvals). Without one shared object the two would drift: a web-sent prompt
7
- // would never appear in the terminal, and a TUI-sent one would never reach the
8
- // browser.
9
- //
10
- // Shape: the hub keeps the durable view (transcript rows, status, tasks, todos)
11
- // and an append-only event log. Both front-ends are SUBSCRIBERS:
12
- // * `emit(event)` — anything happening in the session. Broadcast to every
13
- // subscriber; the hub also folds it into its own view so a late subscriber
14
- // (a browser opened mid-turn) can render the whole state on connect.
15
- // * `pushRow(row)` — a transcript row was appended by the TUI. Goes out as a
16
- // `row` event AND into the durable view.
17
- // Actions (the user's intent) travel the OTHER way through injected handlers, so
18
- // the web never touches the agent directly — it calls the same functions the
19
- // keyboard does. That is what keeps behaviour identical in both front-ends.
20
-
21
- // How many transcript rows / events to keep for a reconnecting client. The
22
- // transcript is bounded because a long session with big tool results would
23
- // otherwise grow without limit in a process that may run for days; the browser
24
- // gets the tail and can scroll back no further than that on a fresh connect.
25
- //
26
- // NOTE: this is a MEMORY bound for a long-running process, not a rendering one.
27
- // The browser is sent everything up to here and the windowed list (vlist.js)
28
- // keeps only the visible slice in the DOM, so the two limits are independent.
29
- const MAX_ROWS = 4000;
30
- const MAX_EVENTS = 2000;
31
- const SNAPSHOT_ROWS = 0; // 0 = no cap; see snapshot()
32
-
33
- /**
34
- * Status fields that animate the Working row and change on EVERY frame a turn is
35
- * running. They must not count as a "status change" — otherwise a long turn
36
- * broadcasts the whole status (and the browser rebuilds every card pane) once per
37
- * frame. The pulse is drawn client-side; these ride along when a real change
38
- * broadcasts.
39
- */
40
- const ANIMATION_FIELDS = new Set(['spin', 'workMsg', 'pulseStart']);
41
- // Which fields of a transcript row the browser actually renders. The fingerprint
42
- // covers exactly these, so streaming text (a growing `text`) invalidates it while
43
- // an unrelated mutation does not. Keeping the list here — rather than hashing the
44
- // whole object — also keeps a large tool result from being stringified on every
45
- // frame.
46
- const ROW_FIELDS = [
47
- 'role', 'text', 'toolName', 'pending', 'failed',
48
- 'streamContent', 'liveOutput', 'phase', 'tokensBefore', 'tokensAfter',
49
- 'instruction', 'card',
50
- ];
51
-
52
- function rowFingerprint(msg) {
53
- let s = '';
54
- for (const f of ROW_FIELDS) {
55
- const v = msg[f];
56
- if (v === undefined || v === null) { s += '|'; continue; }
57
- if (typeof v === 'string') s += v.length + ':' + (v.length <= 64 ? v : '');
58
- else if (typeof v === 'object') s += v === msg.card ? 'card:' + String(v.headline || '') : 'obj';
59
- else s += String(v);
60
- s += '|';
61
- }
62
- // Tool arguments drive the one-line summary, so a change there must be seen.
63
- s += msg.toolArgs ? Object.keys(msg.toolArgs).join(',') + ':' + String(msg.toolArgs.command || msg.toolArgs.path || msg.toolArgs.pattern || '').length : '';
64
- // The diff drives an expanded row's body.
65
- s += '/' + (Array.isArray(msg.diff) ? msg.diff.length : 0);
66
- return s;
67
- }
68
-
69
- /**
70
- * Content equality for status fields. Scalars by value; arrays element-wise with a
71
- * one-level object compare (the shape of a todo / task / file entry); other
72
- * objects field-wise with a JSON fallback for anything nested deeper — exactly the
73
- * shapes webStatus builds (`options` carries arrays of objects, `pending` carries
74
- * option lists).
75
- */
76
- function sameValue(a, b) {
77
- if (a === b) return true;
78
- if (a == null || b == null || typeof a !== 'object' || typeof b !== 'object') return false;
79
- if (Array.isArray(a) !== Array.isArray(b)) return false;
80
- if (Array.isArray(a)) {
81
- if (a.length !== b.length) return false;
82
- for (let i = 0; i < a.length; i++) {
83
- if (a[i] === b[i]) continue;
84
- if (!sameValue(a[i], b[i])) return false;
85
- }
86
- return true;
87
- }
88
- const ka = Object.keys(a);
89
- const kb = Object.keys(b);
90
- if (ka.length !== kb.length) return false;
91
- for (const k of ka) {
92
- const va = a[k];
93
- const vb = b[k];
94
- if (va === vb) continue;
95
- if (va && vb && typeof va === 'object' && typeof vb === 'object') {
96
- if (JSON.stringify(va) !== JSON.stringify(vb)) return false;
97
- continue;
98
- }
99
- return false;
100
- }
101
- return true;
102
- }
103
- // The subset of a TUI message the browser needs. Built explicitly rather than
104
- // spreading, so TUI-only bookkeeping (render caches, the arg-stream parser state,
105
- // the hub id itself) never travels over the wire.
106
- function snapshotRow(msg) {
107
- const out = { role: msg.role || 'system', text: msg.text == null ? '' : String(msg.text) };
108
- for (const k of ['toolName', 'pending', 'failed', 'streamContent', 'liveOutput',
109
- 'phase', 'tokensBefore', 'tokensAfter', 'instruction']) {
110
- if (msg[k] !== undefined) out[k] = msg[k];
111
- }
112
- // The two fields that can be unbounded. `text` is a finished tool result and
113
- // `liveOutput` is a running command's stream; both are capped BEFORE the wire,
114
- // because this snapshot travels as one SSE frame and the browser copies it into
115
- // a fresh row object on every patch. 128 KiB matches the tool-result cap
116
- // (`MAX_OUTPUT_BYTES`), so the browser sees the same content the terminal kept.
117
- out.text = capText(out.text, MAX_ROW_TEXT_CHARS);
118
- if (typeof out.liveOutput === 'string') {
119
- out.liveOutput = capText(out.liveOutput, MAX_ROW_TEXT_CHARS);
120
- }
121
- // A tool's one-line summary needs its identifying argument, not the whole
122
- // payload — a Write's `content` can be megabytes.
123
- if (msg.toolArgs && typeof msg.toolArgs === 'object') {
124
- const a = {};
125
- for (const k of ['command', 'cmd', 'path', 'file_path', 'pattern', 'query', 'url', 'description', 'task_id']) {
126
- if (typeof msg.toolArgs[k] === 'string') a[k] = String(msg.toolArgs[k]).slice(0, 400);
127
- }
128
- if (Object.keys(a).length) out.toolArgs = a;
129
- }
130
- if (Array.isArray(msg.diff)) out.diff = msg.diff.slice(0, 400);
131
- // The same pieces `formatToolLine` composes, as data rather than as ANSI.
132
- if (out.role === 'tool') {
133
- const verb = msg.pending ? 'Using' : 'Used';
134
- const name = out.toolName || 'tool';
135
- // The identifying argument, by the same key order the line uses. `toolArgs` above already holds
136
- // only the short, displayable ones.
137
- const arg = out.toolArgs
138
- ? (out.toolArgs.command || out.toolArgs.cmd || out.toolArgs.path || out.toolArgs.file_path
139
- || out.toolArgs.pattern || out.toolArgs.query || out.toolArgs.url || out.toolArgs.description || '')
140
- : '';
141
- const summary = arg ? `${verb} ${name} (${arg})` : `${verb} ${name}`;
142
- let added = 0;
143
- let removed = 0;
144
- if (Array.isArray(msg.diff)) for (const d of msg.diff) {
145
- if (d && (d.type === 'add' || d.type === '+')) added++;
146
- else if (d && (d.type === 'del' || d.type === '-')) removed++;
147
- }
148
- out.display = {
149
- verb,
150
- tool: name,
151
- arg: arg ? String(arg).slice(0, 400) : '',
152
- summary,
153
- status: msg.pending ? 'running' : (msg.failed ? 'failed' : 'done'),
154
- diff: (added || removed) ? { added, removed } : null,
155
- };
156
- }
157
- if (msg.card && typeof msg.card === 'object') {
158
- out.card = { phase: msg.card.phase, headline: msg.card.headline, detail: msg.card.detail };
159
- }
160
- return out;
161
- }
162
-
163
- /** Per-row character budget for the two fields that can grow without bound. */
164
- const MAX_ROW_TEXT_CHARS = 128 * 1024;
165
-
166
- /** Keep the TAIL of an over-long field — the part both front-ends show — and mark
167
- what was dropped, so a truncated row is not mistaken for a short one. */
168
- function capText(s, max) {
169
- const str = String(s == null ? '' : s);
170
- if (str.length <= max) return str;
171
- return `...[${str.length - max} chars truncated]\n` + str.slice(str.length - max);
172
- }
173
-
174
-
175
-
176
- export class SessionHub {
177
- constructor() {
178
- this.rows = []; // durable transcript: { id, role, text, ... }
179
- this.events = []; // ring of recent events, replayed on connect
180
- this.subscribers = new Set();
181
- this.seq = 0;
182
- this.rowSeq = 0;
183
- // hub row id -> last fingerprint, for syncChat's incremental diff.
184
- this._rowFp = new Map();
185
- // hub row id -> the row object in `this.rows`. syncChat runs on every paint
186
- // frame, and looking a row up with Array.find() inside the per-message loop
187
- // made it O(n^2): every token of a long reply walked the whole transcript. The
188
- // index turns that lookup into a Map hit.
189
- this._rowById = new Map();
190
- // Filled in by the TUI once it owns these. A web action that has no handler
191
- // reports a clear error instead of silently doing nothing.
192
- this.actions = {
193
- submit: null, // async (text) => void — same path as typing
194
- dispatch: null, // async (cmd, arg) => void — slash commands
195
- interrupt: null, // async () => void
196
- approve: null, // async (id, ok) => void — answer an approval
197
- answerPlan: null, // async (id, outcome) => void — answer a Plan-mode review
198
- answerQuestion: null,// async (id, answers) => void — AskUserQuestion
199
- stopTask: null, // async (taskId) => void
200
- setMode: null, // async (mode) => void
201
- status: null, // () => object
202
- shell: null, // async (cmd) => void — `!` passthrough
203
- steer: null, // async (text) => void — inject into the running turn
204
- editQueued: null, // async (text) => {text} — recall a queued msg for editing
205
- dropQueued: null, // async (text) => void — remove a queued message
206
- };
207
- }
208
-
209
- // ---- broadcasting ----------------------------------------------------------
210
-
211
- subscribe(fn) {
212
- this.subscribers.add(fn);
213
- return () => this.subscribers.delete(fn);
214
- }
215
-
216
- /** Broadcast one event. Subscriber failures must never break the session. */
217
- emit(event) {
218
- const e = { ...event, seq: ++this.seq, at: Date.now() };
219
- this.events.push(e);
220
- if (this.events.length > MAX_EVENTS) this.events.splice(0, this.events.length - MAX_EVENTS);
221
- for (const fn of this.subscribers) {
222
- try { fn(e); } catch { /* one bad client must not kill the others */ }
223
- }
224
- return e;
225
- }
226
-
227
- /**
228
- * Append a transcript row. `row` is the TUI's own message object (role/text/
229
- * toolName/toolArgs/pending/failed/diff/…), so the two front-ends render the
230
- * SAME data rather than two parallel models.
231
- */
232
- pushRow(row) {
233
- const r = { ...row, id: row.id != null ? row.id : ++this.rowSeq };
234
- if (row.id == null) r.id = this.rowSeq;
235
- this.rows.push(r);
236
- if (this.rows.length > MAX_ROWS) this.rows.splice(0, this.rows.length - MAX_ROWS);
237
- this.emit({ type: 'row', row: r });
238
- return r;
239
- }
240
-
241
- /** Mutate an existing row in place (streaming text, a tool finishing, …). */
242
- patchRow(id, patch) {
243
- const r = this.rows.find((x) => x.id === id);
244
- if (!r) return null;
245
- Object.assign(r, patch);
246
- this.emit({ type: 'row_patch', id, patch });
247
- return r;
248
- }
249
-
250
- /**
251
- * Sync the hub's view of the transcript against the TUI's own `state.chat`.
252
- *
253
- * This is the bridge between the two front-ends, and it exists so the TUI does
254
- * NOT have to announce every change. `state.chat` is mutated from half a dozen
255
- * places (addChat plus direct pushes for streamed prose, tool rows, thinking
256
- * blocks, the plan bubble, aborts) and one of them is a streaming hot path where
257
- * an extra call per token would be felt. Instead the caller runs this once per
258
- * paint: rows are matched by IDENTITY, so a pushed row is picked up on the next
259
- * frame, and a mutated row is diffed by a cheap field fingerprint.
260
- *
261
- * Returns nothing; failures here must never affect rendering.
262
- */
263
- syncChat(chat) {
264
- // NOBODY IS WATCHING, SO NOTHING IS BUILT.
265
- //
266
- // `/web` starts a server, but a browser may never connect — and this ran on every frame regardless,
267
- // walking the whole transcript to build rows no one would read. Measured on a 300-message transcript:
268
- // 8.8ms per frame with zero subscribers, which is most of a 60fps budget spent on nothing.
269
- //
270
- // The rows are rebuilt from scratch on the next sync after a client connects (it starts with no rows
271
- // and `_rowFp` empty), so skipping here costs one frame of latency at connect time and nothing else.
272
- if (this.subscribers.size === 0) return;
273
- const list = Array.isArray(chat) ? chat : [];
274
- const seen = new Set();
275
- for (let i = 0; i < list.length; i++) {
276
- const msg = list[i];
277
- if (!msg || typeof msg !== 'object') continue;
278
- // Bind the TUI's message object to a stable hub row id the first time we see
279
- // it. A WeakMap would be cleaner but the TUI copies rows (spread) in a few
280
- // paths, so the id lives on the message itself.
281
- let id = msg._hubId;
282
- if (id == null) {
283
- id = ++this.rowSeq;
284
- Object.defineProperty(msg, '_hubId', { value: id, enumerable: false, configurable: true, writable: true });
285
- }
286
- seen.add(id);
287
- const fp = rowFingerprint(msg);
288
- const known = this._rowFp.get(id);
289
- if (known === undefined) {
290
- const row = { ...snapshotRow(msg), id };
291
- this.rows.push(row);
292
- this._rowById.set(id, row);
293
- this.emit({ type: 'row', row });
294
- this._rowFp.set(id, fp);
295
- } else if (known !== fp) {
296
- const target = this._rowById.get(id);
297
- // The WHOLE row's renderable fields, not a text delta.
298
- //
299
- // A delta looked like an easy win — a streamed reply grows one token at a
300
- // time, so shipping only the appended slice is O(n) instead of O(n^2) over a
301
- // message. But it puts the sender and the receiver into a shared state
302
- // machine: the receiver must hold exactly the text the sender assumed, and
303
- // any divergence (a dropped frame, a reconnect mid-stream, an out-of-order
304
- // batch) silently TRUNCATES the message instead of visibly failing. That is
305
- // exactly what happened: replies rendered at a fraction of their real length
306
- // in the browser while the terminal showed them whole.
307
- //
308
- // The full patch costs bandwidth, and this is a LOOPBACK server: the cost
309
- // that matters is the browser's re-render, and `text` is assigned to one
310
- // text node either way. Correctness over a micro-optimisation.
311
- const patch = snapshotRow(msg);
312
- if (target) Object.assign(target, patch);
313
- this.emit({ type: 'row_patch', id, patch });
314
- this._rowFp.set(id, fp);
315
- }
316
- }
317
- // The TUI rebuilds `state.chat` wholesale on /compact and on session resume.
318
- // Anything it no longer holds is gone from the hub too, or the browser would
319
- // keep showing rows the terminal has already dropped.
320
- //
321
- // The COUNT is compared first: it is almost always equal, so the common frame
322
- // never walks the list. The previous version built two filtered copies of
323
- // `rows` on every frame whether anything had been dropped or not.
324
- if (this.rows.length !== seen.size) {
325
- const kept = this.rows.filter((r) => seen.has(r.id));
326
- if (kept.length !== this.rows.length) {
327
- this.rows = kept;
328
- this._rowById = new Map(kept.map((r) => [r.id, r]));
329
- this.emit({ type: 'rows_reset', rows: this.rows });
330
- }
331
- }
332
- if (this.rows.length > MAX_ROWS) {
333
- const dropped = this.rows.splice(0, this.rows.length - MAX_ROWS);
334
- for (const r of dropped) {
335
- this._rowById.delete(r.id);
336
- this._rowFp.delete(r.id);
337
- }
338
- }
339
- }
340
-
341
-
342
- /**
343
- * Update non-transcript session state (context gauge, tasks, todos, model).
344
- *
345
- * Broadcasts ONLY when something actually changed. `setStatus` runs on EVERY TUI
346
- * frame (~12/s), and `webStatus` rebuilds every array and the nested
347
- * `options`/`pending` objects each time — so identical content always arrives
348
- * behind FRESH references. A reference compare (`next[k] !== prev[k]`) therefore
349
- * reported a change every frame, every frame was broadcast, and the browser
350
- * re-rendered its whole status DOM — the card panes included — 12 times a second
351
- * while nothing had changed. That idle churn is what showed up as a tab sitting
352
- * at 800+ MB with typing that stuttered even when the model was not streaming.
353
- *
354
- * ANIMATION FIELDS are excluded from the change test. `spin`, `workMsg` and
355
- * `pulseStart` drive the Working row's pulse and change on every frame while a
356
- * turn runs, but the ONLY thing that needs them is the pulse — which the browser
357
- * draws itself with requestAnimationFrame. Broadcasting on each of those changes
358
- * meant a long turn rebuilt the whole status DOM (and every card pane) once per
359
- * frame. They ride along in a broadcast a REAL change triggers, never by
360
- * themselves.
361
- *
362
- * Scalars compare by value; objects compare one level deep (arrays element-wise,
363
- * nested objects by field) with a JSON fallback for anything deeper — exactly
364
- * the shapes webStatus builds.
365
- */
366
- statusChanged(next) {
367
- const prev = this.status || {};
368
- for (const k of Object.keys(next)) {
369
- if (ANIMATION_FIELDS.has(k)) continue;
370
- if (!sameValue(next[k], prev[k])) return true;
371
- }
372
- // A field present before but dropped from next is also a change.
373
- for (const k of Object.keys(prev)) {
374
- if (ANIMATION_FIELDS.has(k)) continue;
375
- if (!(k in next)) return true;
376
- }
377
- return false;
378
- }
379
-
380
- setStatus(patch) {
381
- const next = { ...(this.status || {}), ...patch };
382
- if (!this.statusChanged(next)) return this.status;
383
- this.status = next;
384
- this.emit({ type: 'status', status: this.status });
385
- return this.status;
386
- }
387
-
388
- /**
389
- * Publish ONE status field as its own event, so a low-frequency change
390
- * (e.g. a queued message) reaches the browser immediately instead of riding
391
- * the next whole-status snapshot. Keeps the field in `this.status` too, so a
392
- * freshly-connected client still gets it via snapshot().
393
- */
394
- pubStatusField(field, value) {
395
- if (field == null) return this.status;
396
- const next = { ...(this.status || {}), [field]: value };
397
- if (!this.statusChanged(next)) return this.status;
398
- this.status = next;
399
- const e = { type: field, [field]: value };
400
- this.emit(e);
401
- return this.status;
402
- }
403
-
404
- /**
405
- * Everything a freshly connected client needs to render the current view.
406
- *
407
- * The whole transcript is sent by default. `limit` exists for callers that want
408
- * a bounded slice (it is a tail), but nothing forces a cap: the browser's
409
- * windowed list renders only the visible rows, so a long transcript costs one
410
- * payload rather than one DOM node per row. When a caller DOES cap it, `hidden`
411
- * reports how much was left out.
412
- */
413
- snapshot(limit) {
414
- const cap = Number.isFinite(limit) && limit > 0 ? Math.floor(limit) : SNAPSHOT_ROWS;
415
- const start = cap > 0 ? Math.max(0, this.rows.length - cap) : 0;
416
- return {
417
- rows: start > 0 ? this.rows.slice(start) : this.rows,
418
- hidden: start,
419
- totalRows: this.rows.length,
420
- status: this.status || {},
421
- events: this.events.slice(-200),
422
- };
423
- }
424
-
425
- // ---- actions (web -> session) ---------------------------------------------
426
- // Each returns { ok, error } so the HTTP layer can answer honestly instead of
427
- // pretending an action ran.
428
-
429
- async call(name, ...args) {
430
- const fn = this.actions[name];
431
- if (typeof fn !== 'function') {
432
- return { ok: false, error: `action "${name}" is not available in this session` };
433
- }
434
- try {
435
- // The handler's return value travels back to the caller. Most actions are
436
- // fire-and-forget (submit, interrupt) and return undefined, but the ones
437
- // that READ something — listProviders, getConfig — have nothing else to
438
- // report with, and dropping it made them look like they did nothing.
439
- const result = await fn(...args);
440
- return { ok: true, result };
441
- } catch (e) {
442
- return { ok: false, error: (e && e.message) || String(e) };
443
- }
444
- }
445
- }
package/src/web-auth.js DELETED
@@ -1,98 +0,0 @@
1
- // Authentication for the local web UI.
2
- //
3
- // THREAT MODEL, stated plainly because it decides every choice here: the server
4
- // binds to a local address by default and serves one user's coding session — the
5
- // transcript, the file contents it read, and the ability to RUN COMMANDS as that
6
- // user. So the bar is not "keep out a determined attacker"; it is:
7
- // * a page the user visits in another tab must not be able to talk to it
8
- // (same-origin rules do not apply to `fetch` from a random site without CORS,
9
- // but a form POST or a `<img>`/websocket still reaches it),
10
- // * another user on the same machine must not read the transcript,
11
- // * a leaked URL pasted into a chat must not be enough on its own.
12
- //
13
- // What that buys:
14
- // * a 256-bit TOKEN, generated per process, required on every request;
15
- // * constant-time comparison, so a token cannot be guessed byte by byte;
16
- // * a same-origin check on state-changing requests (Origin/Referer must match
17
- // the bound host), which is the standard defence against a cross-site POST;
18
- // * HttpOnly + SameSite=Strict session cookie after a one-time token exchange,
19
- // so the token does not have to sit in the page's JS or in a URL.
20
- //
21
- // What it deliberately does NOT do: TLS (the transport is loopback), user
22
- // accounts, or rate limiting beyond a small login delay. Binding to a non-loopback
23
- // address is allowed (/web 0.0.0.0) but is opt-in and warned about, because then
24
- // the token is the ONLY thing between the network and a shell.
25
-
26
- import crypto from 'node:crypto';
27
-
28
- // 32 bytes of entropy, base64url. Long enough that guessing is hopeless, short
29
- // enough to paste from a terminal.
30
- export function newToken() {
31
- return crypto.randomBytes(32).toString('base64url');
32
- }
33
-
34
- /**
35
- * Constant-time string compare. `crypto.timingSafeEqual` throws on a length
36
- * mismatch, which would itself leak the length — so both sides are hashed first,
37
- * making every comparison the same length.
38
- */
39
- export function safeEqual(a, b) {
40
- if (typeof a !== 'string' || typeof b !== 'string') return false;
41
- const ha = crypto.createHash('sha256').update(a).digest();
42
- const hb = crypto.createHash('sha256').update(b).digest();
43
- return crypto.timingSafeEqual(ha, hb);
44
- }
45
-
46
- /** Loopback check — decides whether binding needs a warning. */
47
- export function isLoopback(addr) {
48
- const a = String(addr || '').trim().toLowerCase();
49
- if (a === 'localhost' || a === '::1' || a === '[::1]') return true;
50
- if (/^127(\.\d{1,3}){3}$/.test(a)) return true;
51
- return false;
52
- }
53
-
54
- /**
55
- * Is this request allowed to CHANGE something? A browser sends `Origin` on every
56
- * state-changing cross-origin request (and on same-origin POSTs too), so a
57
- * mismatch means the request came from a page we do not control. Requests with no
58
- * Origin at all are allowed only when they carry the bearer token — that is a
59
- * script (curl), not a browser being abused by another site.
60
- */
61
- export function sameOriginOk(req, expectedHosts) {
62
- const origin = req.headers.origin || req.headers.referer;
63
- if (!origin) return null; // caller decides (token-only scripts)
64
- let host;
65
- try { host = new URL(origin).host; } catch { return false; }
66
- return expectedHosts.includes(host);
67
- }
68
-
69
- /** Parse `Cookie: a=1; b=2`. Returns {} for anything malformed. */
70
- export function parseCookies(header) {
71
- const out = {};
72
- const s = String(header || '');
73
- if (!s) return out;
74
- for (const part of s.split(';')) {
75
- const i = part.indexOf('=');
76
- if (i < 0) continue;
77
- const k = part.slice(0, i).trim();
78
- if (!k) continue;
79
- out[k] = decodeURIComponent(part.slice(i + 1).trim());
80
- }
81
- return out;
82
- }
83
-
84
- /**
85
- * The request's credential, from either place:
86
- * * `Authorization: Bearer <token>` — scripts, curl, the CLI;
87
- * * the `hncode_web` cookie — the browser, set by POST /api/login.
88
- */
89
- export function requestSecret(req, cookieName = 'hncode_web') {
90
- const auth = String(req.headers.authorization || '');
91
- if (auth.toLowerCase().startsWith('bearer ')) return auth.slice(7).trim();
92
- const cookies = parseCookies(req.headers.cookie);
93
- return cookies[cookieName] || '';
94
- }
95
-
96
- export function isAuthed(req, token, cookieName) {
97
- return safeEqual(requestSecret(req, cookieName), token);
98
- }
@@ -1,63 +0,0 @@
1
- #!/usr/bin/env node
2
- // Entry point for the global web UI daemon.
3
- //
4
- // Normally spawned by web-daemon-client.js from a TUI session; it can also be
5
- // run by hand (`node src/web-daemon-cli.js`) to keep the UI up without a TUI.
6
- //
7
- // Everything it would have printed to a terminal goes to the log file instead,
8
- // because a daemon started detached has no terminal to report to — that log is
9
- // the only place a bind failure can be read afterwards.
10
-
11
- import { startWebDaemon, defaultDaemonPipe } from './web-daemon.js';
12
- import { resolveConfig } from './config.js';
13
-
14
- const cfg = resolveConfig();
15
-
16
- async function main() {
17
- const host = process.env.HNCODE_WEB_HOST || cfg.webHost || '127.0.0.1';
18
- const port = Number(process.env.HNCODE_WEB_PORT ?? (cfg.webPort == null ? 8765 : cfg.webPort));
19
- const pipePath = defaultDaemonPipe();
20
-
21
- let daemon;
22
- try {
23
- daemon = await startWebDaemon({ host, port, pipePath });
24
- } catch (e) {
25
- // The port is the usual failure: something else already holds it. Say WHICH
26
- // address and how to change it, because a detached daemon cannot ask.
27
- if (e && (e.code === 'EADDRINUSE' || /EADDRINUSE/.test(String(e.message)))) {
28
- process.stderr.write(
29
- `[web-daemon] port ${port} on ${host} is already in use.\n`
30
- + '[web-daemon] Choose another in config.toml: web_port = 8766\n'
31
- + '[web-daemon] or for this run: HNCODE_WEB_PORT=8766\n',
32
- );
33
- process.exit(1);
34
- }
35
- throw e;
36
- }
37
-
38
- if (daemon.pipeError) {
39
- // Another daemon already owns the pipe. Not an error for the caller — this
40
- // one simply has nothing to add, so it exits and the TUI keeps using the
41
- // existing daemon.
42
- process.stderr.write(`[web-daemon] another daemon already owns ${pipePath}; exiting\n`);
43
- daemon.close();
44
- process.exit(0);
45
- }
46
-
47
- process.stdout.write(
48
- `[web-daemon] listening on ${daemon.url} (pid ${process.pid})\n`
49
- + `[web-daemon] pipe: ${daemon.pipePath}\n`,
50
- );
51
-
52
- const shutdown = () => {
53
- try { daemon.close(); } catch { /* already closed */ }
54
- process.exit(0);
55
- };
56
- process.on('SIGINT', shutdown);
57
- process.on('SIGTERM', shutdown);
58
- }
59
-
60
- main().catch((e) => {
61
- process.stderr.write(`[web-daemon] fatal: ${(e && e.stack) || e}\n`);
62
- process.exit(1);
63
- });