@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/serve.js ADDED
@@ -0,0 +1,613 @@
1
+ // A resident hncode session server.
2
+ //
3
+ // WHY THIS EXISTS
4
+ // ---------------
5
+ // The desktop used to start `hncode -p "<text>" --output-format stream-json` for every message.
6
+ // That is a fresh process per turn: it re-reads the config, re-loads every plugin, re-parses the
7
+ // session file, and then exits — so nothing survives between turns, and a front end can only
8
+ // watch a stream that it cannot talk back to. Interrupting means killing the process, which loses
9
+ // whatever had not been written yet, and a turn that is stopped after the naming request has
10
+ // started can lose the whole conversation.
11
+ //
12
+ // This process stays. A session is opened once, runs in place, and answers requests over a
13
+ // long connection. The turn loop, the tool approvals, the interruption and the save are the same
14
+ // code the terminal runs; what changes is only where the events go.
15
+ //
16
+ // THE PROTOCOL
17
+ // ------------
18
+ // One JSON object per line, both directions. `src/protocol.js` is the authority: it names every
19
+ // event and every request, and both ends read it. See that file for the envelope.
20
+ //
21
+ // WHY A NEW SOCKET AND NOT THE EXISTING PIPES
22
+ // -------------------------------------------
23
+ // The control socket (`hncode control`) is one-shot: connect, send one op, read one answer,
24
+ // close. A front end needs to be told about every token as it arrives, which needs a connection
25
+ // that stays open and pushes.
26
+
27
+ import net from 'node:net';
28
+ import fs from 'node:fs';
29
+ import os from 'node:os';
30
+ import path from 'node:path';
31
+ import crypto from 'node:crypto';
32
+
33
+ import { resolveConfig } from './config.js';
34
+ import * as sess from './session.js';
35
+ // THE TURN IS THE TERMINAL'S. See the note on `LiveSession`: a second implementation drifted, and
36
+ // the thing it lost first was the system prompt.
37
+ import { runTurn, makeState } from './tui.js';
38
+ import { SessionHost } from './session-host.js';
39
+ import { HEADLESS_VIEW } from './session-view.js';
40
+ import { eventMessage, validateRequest } from './protocol.js';
41
+ import { decideApproval } from './permission-gate.js';
42
+
43
+ /** Where the socket lives. An env override is what lets a test use its own. */
44
+ export function serveSocketPath() {
45
+ if (process.env.HNCODE_SERVE_SOCKET) return process.env.HNCODE_SERVE_SOCKET;
46
+ if (process.platform === 'win32') return '\\\\.\\pipe\\hncode-serve';
47
+ return path.join(os.homedir(), '.hncode', 'serve.sock');
48
+ }
49
+
50
+ // A connection is a client that stays. It is dropped when it stops responding to pings, so a
51
+ // window that was closed without saying goodbye does not hold a session open forever.
52
+ const IDLE_DROP_MS = 120_000;
53
+
54
+ /**
55
+ * One running conversation.
56
+ *
57
+ * It owns the message array, the Agent that appends to it, and the socket subscribers that watch
58
+ * it. A turn runs one at a time; a request that arrives mid-turn is queued, which is what the
59
+ * terminal does with a typed line.
60
+ */
61
+ class LiveSession {
62
+ constructor({ cfg, record, onSaved }) {
63
+ this.cfg = cfg;
64
+ this.record = record;
65
+ this.messages = Array.isArray(record.messages) ? record.messages : [];
66
+ // THE RECORD SAVES THE ARRAY THE TURN APPENDS TO. Pointing it anywhere else is the bug that
67
+ // once wrote the old transcript back over the file at the end of every turn.
68
+ record.messages = this.messages;
69
+ this.onSaved = onSaved;
70
+ this.clients = new Set();
71
+ this.running = false;
72
+ this.queue = [];
73
+ this.agent = null;
74
+ this.pendingApprovals = new Map();
75
+ // Questions wait in their own map: an approval resolves to true/false, a question to answers.
76
+ this.pendingQuestions = new Map();
77
+ this.stopped = false;
78
+
79
+ // THE SAME STATE AND HOST THE TERMINAL BUILD. `runTurn` reads the session through them —
80
+ // the todos, the counters, the transcript recorder — so a turn driven from here behaves like
81
+ // one typed at the keyboard rather than like a second, simpler agent.
82
+ this.state = makeState({ cfg, session: record, opts: {} });
83
+ this.state.agent = null;
84
+ this.host = new SessionHost({
85
+ state: this.state,
86
+ cfg,
87
+ session: record,
88
+ view: HEADLESS_VIEW,
89
+ onEvent: (e) => this._onAgentEvent(e),
90
+ });
91
+ }
92
+
93
+ /** Send one protocol event to every subscriber. */
94
+ publish(name, payload) {
95
+ let msg;
96
+ try { msg = eventMessage(name, payload); } catch { return; }
97
+ // ON THE EVENT, not the envelope: `eventMessage` wraps the payload in `{ type, event }`.
98
+ msg.event.sessionId = this.record.id;
99
+ const line = JSON.stringify(msg) + '\n';
100
+ for (const c of this.clients) {
101
+ try { c.socket.write(line); } catch { /* the client is gone; its close handler removes it */ }
102
+ }
103
+ }
104
+
105
+ /**
106
+ * Subscribe a socket, once.
107
+ *
108
+ * A set of records keyed by the socket object would be the type-safe way to say this, but the
109
+ * check costs one scan of a list that holds one or two entries — and re-adding a socket that is
110
+ * already here is what doubled every event.
111
+ */
112
+ attach(socket) {
113
+ for (const c of this.clients) if (c.socket === socket) return;
114
+ this.clients.add({ socket, at: Date.now() });
115
+ }
116
+
117
+ detach(socket) {
118
+ for (const c of this.clients) if (c.socket === socket) this.clients.delete(c);
119
+ }
120
+
121
+ get attached() {
122
+ return this.clients.size > 0;
123
+ }
124
+
125
+ /**
126
+ * Run one turn with `text`, through the terminal's own turn loop.
127
+ *
128
+ * Everything the window sees comes from `_onAgentEvent`, which is the `onEvent` the host was
129
+ * given: the same events, in the same order, as a terminal turn. The transcript this session
130
+ * keeps is `runTurn`'s, not a second copy.
131
+ */
132
+ async runTurn(text) {
133
+ if (this.running) {
134
+ this.queue.push(String(text));
135
+ this.publish('status', { status: `queued (${this.queue.length})` });
136
+ return;
137
+ }
138
+ this.running = true;
139
+ this.stopped = false;
140
+ // NAMED FROM THE FIRST LINE, not from the saved record. Until the turn ends nothing has
141
+ // written a title, and the rail — the thing the reader is looking at while they wait — drew
142
+ // the row they had just started as "untitled".
143
+ if (!this.record.title) {
144
+ const named = sess.titleFromPrompt(String(text || ''));
145
+ if (named) {
146
+ this.record.title = named;
147
+ try { sess.saveSessionNow(this.record); } catch { /* the turn still runs */ }
148
+ }
149
+ }
150
+ try {
151
+ process.stderr.write('[turn] start ' + this.record.id + ' model=' + this.cfg.model + '\n');
152
+ // ONE LINE PER PHASE. A turn that never finishes otherwise looks identical to one that is
153
+ // thinking: both are silent. These say which step was reached.
154
+ const beat = setInterval(() => {
155
+ process.stderr.write('[turn] waiting ' + Math.round(process.uptime()) + 's steps=' + (this.state.steps || 0) + '\n');
156
+ }, 8000);
157
+ beat.unref();
158
+ try {
159
+ await runTurn(
160
+ {
161
+ state: this.state,
162
+ cfg: this.cfg,
163
+ session: this.record,
164
+ host: this.host,
165
+ cmdHost: this.host,
166
+ view: HEADLESS_VIEW,
167
+ // THE WINDOW ANSWERS PERMISSION, not the keyboard. `runTurn` otherwise waits on a
168
+ // keypress that a headless caller can never produce, and the turn stops before the
169
+ // model is ever reached.
170
+ onApproval: async (toolName, args) => {
171
+ // THE LIVE MODE. `record.mode` is what was on disk; `state.mode` is what the window
172
+ // is showing after a change, and the two disagree until the record is saved.
173
+ const mode = (this.state && this.state.mode) || this.record.mode || 'ask';
174
+ const verdict = decideApproval({ mode, toolName, args, rules: this.cfg.permissions });
175
+ if (verdict === 'allow') return true;
176
+ if (verdict === 'deny') return false;
177
+ const id = 'ap-' + Date.now().toString(36);
178
+ this.publish('approval-request', { id, name: toolName, args });
179
+ return await new Promise((resolve) => {
180
+ const timer = setTimeout(() => { this.pendingApprovals.delete(id); resolve(false); }, 5 * 60_000);
181
+ this.pendingApprovals.set(id, (ok) => { clearTimeout(timer); resolve(!!ok); });
182
+ });
183
+ },
184
+ // A QUESTION, put to the window the same way. Left to `runTurn`, it waits on a keypress
185
+ // a headless caller can never send and the turn sits until its timeout.
186
+ askQuestion: async (questions) => {
187
+ const id = 'q-' + Date.now().toString(36);
188
+ this.publish('question-request', { id, questions });
189
+ return await new Promise((resolve) => {
190
+ const timer = setTimeout(() => { this.pendingQuestions.delete(id); resolve({}); }, 30 * 60_000);
191
+ this.pendingQuestions.set(id, (answers) => { clearTimeout(timer); resolve(answers || {}); });
192
+ });
193
+ },
194
+ },
195
+ String(text || ''),
196
+ {},
197
+ HEADLESS_VIEW,
198
+ );
199
+ this.save();
200
+ if (this.stopped) this.publish('stopped', {});
201
+ else this.publish('done', {});
202
+ } finally { clearInterval(beat); }
203
+ } catch (e) {
204
+ process.stderr.write('[turn] FAILED ' + this.record.id + ': ' + ((e && e.stack) || e) + '\n');
205
+ this.publish('error', { error: String((e && e.message) || e) });
206
+ this.save();
207
+ } finally {
208
+ this.agent = null;
209
+ this.state.agent = null;
210
+ this.running = false;
211
+ this.publish('status', { status: '' });
212
+ const next = this.queue.shift();
213
+ if (next) void this.runTurn(next);
214
+ }
215
+ }
216
+
217
+ /** One line per agent event: the window's protocol, translated at the only boundary there is. */
218
+ _onAgentEvent(e) {
219
+ if (!e || typeof e !== 'object') return;
220
+ const FIELDS = ['text', 'id', 'name', 'args', 'chunk', 'tokens', 'max', 'breakdown', 'usage',
221
+ 'total', 'todos', 'error', 'reason', 'before', 'keep', 'dropped', 'elided', 'elidedBytes',
222
+ 'attempt', 'goal', 'owner', 'round', 'waiting', 'editDiff'];
223
+ const payload = {};
224
+ for (const f of FIELDS) if (e[f] !== undefined) payload[f] = e[f];
225
+ // `tool_result` carries its verdict, decided once by the same predicate the terminal uses.
226
+ if (e.type === 'tool_result') {
227
+ // THE WIRE NAME IS `diff`; the agent's field is `editDiff`. Renamed here so neither side has to
228
+ // know the other's spelling, and so the diff is not silently dropped by the field whitelist.
229
+ if (e.editDiff && payload.editDiff) { payload.diff = payload.editDiff; delete payload.editDiff; }
230
+ const text = e.content != null ? e.content : e.text;
231
+ payload.content = text;
232
+ }
233
+ // THE AGENT'S `done` IS NOT THE TURN'S END. It reports one round's stream finishing and is
234
+ // re-armed for the next step, so a multi-step turn emits it after its first step — forwarding
235
+ // it ended the turn in the window a second after it started. `runTurn()` returning publishes
236
+ // the ending this protocol means.
237
+ if (e.type === 'done') return;
238
+ try {
239
+ this.publish(e.type, payload);
240
+ } catch (err) {
241
+ // AN EVENT THE CATALOGUE DOES NOT KNOW IS A BUG, and silence made it invisible: the turn
242
+ // ran, the model answered, and the window saw nothing.
243
+ process.stderr.write('[event] dropped ' + e.type + ': ' + ((err && err.message) || err) + '\n');
244
+ }
245
+ }
246
+
247
+ /**
248
+ * Write the session down.
249
+ *
250
+ * Synchronously, and before anything else: a conversation someone watched happen must survive a
251
+ * process that exits a moment later.
252
+ */
253
+ save() {
254
+ try {
255
+ const st = this.state;
256
+ if (st && st.usage) this.record.usage = st.usage;
257
+ if (st && Number.isFinite(st.ctxTokens) && st.ctxTokens > 0) {
258
+ this.record.ctxTokens = st.ctxTokens;
259
+ this.record.ctxReportedOnce = !!st.ctxReportedOnce;
260
+ }
261
+ if (st && st.ctxBreakdown && typeof st.ctxBreakdown === 'object') this.record.ctxBreakdown = st.ctxBreakdown;
262
+ if (st && Array.isArray(st.todos)) this.record.todos = st.todos.slice();
263
+ const max = Number(this.cfg.maxContextTokens) || 0;
264
+ if (max > 0) this.record.ctxMax = max;
265
+ if (st) this.record.rounds = Number(st.rounds) || this.record.rounds;
266
+ // THE TRANSCRIPT IS THE TURN'S, NOT OURS. `runTurn` writes the settled history onto the
267
+ // record when a turn ends; assigning an array captured at construction time here wrote an
268
+ // empty one over it, so every session file came out with no messages.
269
+ const history = Array.isArray(this.record.messages) ? this.record.messages : [];
270
+ if (!this.record.title) {
271
+ const first = history.find((m) => m.role === 'user' && !m._harness && !m._timestamp);
272
+ if (first) this.record.title = sess.titleFromPrompt(String(first.content || ''));
273
+ }
274
+ sess.saveSessionNow(this.record);
275
+ if (this.onSaved) { try { this.onSaved(this.record); } catch { /* a caller's bookkeeping */ } }
276
+ } catch { /* a save failure must not kill the session */ }
277
+ }
278
+
279
+ /** Stop the running turn. */
280
+ interrupt() {
281
+ const agent = this.state && this.state.agent;
282
+ if (!agent || typeof agent.interrupt !== 'function') return false;
283
+ try { agent.interrupt(); } catch { return false; }
284
+ this.stopped = true;
285
+ this.queue.length = 0;
286
+ return true;
287
+ }
288
+
289
+ /**
290
+ * Settle a waiting approval or question.
291
+ *
292
+ * ONE METHOD FOR BOTH because the wire protocol has one `answer` request: an approval resolves to
293
+ * a boolean and a question to a map of answers, and the caller already knows which it sent.
294
+ */
295
+ answer(id, value) {
296
+ const key = String(id);
297
+ const approval = this.pendingApprovals.get(key);
298
+ if (approval) {
299
+ this.pendingApprovals.delete(key);
300
+ approval(value);
301
+ return true;
302
+ }
303
+ const question = this.pendingQuestions.get(key);
304
+ if (question) {
305
+ this.pendingQuestions.delete(key);
306
+ question(value);
307
+ return true;
308
+ }
309
+ return false;
310
+ }
311
+ }
312
+ /** The server: one process, many sessions, many connections. */
313
+ export class SessionServer {
314
+ constructor(opts = {}) {
315
+ this.opts = opts;
316
+ this.sessions = new Map();
317
+ this.server = null;
318
+ this.cfg = null;
319
+ // Every open connection. A resident server with none is an orphan; see `idleCheck`.
320
+ this.conns = new Set();
321
+ this._idleTimer = null;
322
+ }
323
+
324
+ /** Start listening. Returns the address it bound. */
325
+ listen() {
326
+ const sockPath = this.opts.socketPath || serveSocketPath();
327
+ // A STALE SOCKET FILE IS NOT A LISTENER. On POSIX the path survives a crash and bind fails
328
+ // with EADDRINUSE forever; removing it first is what makes a restart work. On Windows the
329
+ // path is a named pipe, which has no file to remove.
330
+ if (process.platform !== 'win32') {
331
+ try { fs.unlinkSync(sockPath); } catch { /* nothing there, which is the good case */ }
332
+ }
333
+ this.server = net.createServer((socket) => this._onConnection(socket));
334
+ return new Promise((resolve, reject) => {
335
+ this.server.once('error', reject);
336
+ this.server.listen(sockPath, () => resolve(sockPath));
337
+ });
338
+ }
339
+
340
+ close() {
341
+ for (const s of this.sessions.values()) s.interrupt();
342
+ this.sessions.clear();
343
+ if (this.server) { try { this.server.close(); } catch { /* gone */ } }
344
+ }
345
+
346
+ /** The session with this id, opened from the record if it is not in memory yet. */
347
+ /**
348
+ * Open a conversation, creating it when the id is a placeholder or unknown.
349
+ *
350
+ * `workspace` is the folder the caller wants this conversation to work in. It is used when the
351
+ * record is NEW and ignored for an existing one — reopening a conversation is not a request to
352
+ * move it; that is `set_workspace`.
353
+ */
354
+ open(id, workspace) {
355
+ const key = String(id || '');
356
+ if (this.sessions.has(key)) return this.sessions.get(key);
357
+
358
+ this.cfg = this.cfg || resolveConfig();
359
+ // A PLACEHOLDER IS NOT A NAME. `new-…` is the window saying "I have not got one yet"; storing
360
+ // it as the id gives the conversation a file named after a placeholder and leaves the real id
361
+ // unused, so the next turn cannot find it.
362
+ const placeholder = !key || key.startsWith('new-');
363
+ let record = null;
364
+ if (!placeholder) {
365
+ try { record = sess.loadSession(key); } catch { record = null; }
366
+ }
367
+ if (!record) {
368
+ record = {
369
+ id: sess.newId(),
370
+ title: '',
371
+ // THE WINDOW'S FOLDER, SENT WITH `open`. Falling back to the server's own cwd meant
372
+ // every tool ran against the app's directory — the reader picked a project and the
373
+ // model kept reading the folder the desktop binary happened to start in.
374
+ // THE CALLER'S FOLDER. Falling back to `process.cwd()` meant the desktop app's own
375
+ // directory, because that is where the server was started.
376
+ workspace: String(workspace || '') || process.cwd(),
377
+ model: this.cfg.model,
378
+ createdAt: Date.now(),
379
+ messages: [],
380
+ };
381
+ }
382
+ // THE MODE THE WINDOW IS IN. Without it `makeState` falls back to `ask`, and a window set
383
+ // to Auto still opened sessions that asked for every tool.
384
+ if (this.opts.mode && !record.mode) record.mode = this.opts.mode;
385
+ // A COPY PER SESSION: `runTurn` sets `cfg.workspace` from the session, and a shared object
386
+ // meant two conversations on this server overwrote each other's working directory.
387
+ const own = { ...this.cfg, workspace: record.workspace || this.cfg.workspace };
388
+ const live = new LiveSession({ cfg: own, record });
389
+ this.sessions.set(record.id, live);
390
+ if (key && key !== record.id) this.sessions.set(key, live);
391
+ return live;
392
+ }
393
+
394
+ _onConnection(socket) {
395
+ socket.setNoDelay(true);
396
+ let buf = '';
397
+ let bound = null; // the session this connection is watching
398
+
399
+ const send = (obj) => {
400
+ try { socket.write(JSON.stringify(obj) + '\n'); } catch { /* the socket is gone */ }
401
+ };
402
+
403
+ const reply = (id, ok, result, error) => {
404
+ send(ok ? { type: 'reply', id, ok: true, result } : { type: 'reply', id, ok: false, error });
405
+ };
406
+
407
+ socket.on('data', (chunk) => {
408
+ buf += chunk.toString('utf8');
409
+ // A LINE IS A MESSAGE. Anything that is not one is dropped with a reason rather than
410
+ // silently ignored: a front end waiting for an answer it will never get is worse than an
411
+ // error it can show.
412
+ let nl;
413
+ while ((nl = buf.indexOf('\n')) !== -1) {
414
+ const line = buf.slice(0, nl).trim();
415
+ buf = buf.slice(nl + 1);
416
+ if (!line) continue;
417
+ let msg;
418
+ try { msg = JSON.parse(line); } catch { send({ type: 'error', error: 'not JSON' }); continue; }
419
+ const bad = validateRequest(msg);
420
+ if (bad) { reply(msg && msg.id, false, null, bad); continue; }
421
+ this._handle(socket, msg, {
422
+ // BOTH ARGUMENTS. Taking only the id dropped the folder the window chose, one level
423
+ // below every caller that passed it correctly.
424
+ open: (id2, workspace2) => {
425
+ bound = this.open(id2, workspace2);
426
+ bound.attach(socket);
427
+ return bound;
428
+ },
429
+ reply,
430
+ send,
431
+ get bound() { return bound; },
432
+ });
433
+ }
434
+ });
435
+
436
+ const drop = () => {
437
+ if (bound) bound.detach(socket);
438
+ this.conns.delete(socket);
439
+ this.idleCheck();
440
+ };
441
+ this.conns.add(socket);
442
+ socket.on('close', drop);
443
+ socket.on('error', drop);
444
+ }
445
+
446
+ /**
447
+ * Save when the last client leaves; do NOT exit.
448
+ *
449
+ * An idle exit looked tidy and caused the worst bug in this file: the window reconnects after any
450
+ * socket hiccup, and between the disconnect and the reconnect the server had already gone — so
451
+ * the next message went to a pipe with nothing behind it and the window waited for an answer
452
+ * from a process that had exited. A desktop application owns its server: it starts it and stops
453
+ * it, and a gap in the connection is not a reason to shut down. The pid file is what keeps one
454
+ * server per machine.
455
+ *
456
+ * The sessions are still written, so nothing is lost if the process is killed later.
457
+ */
458
+ idleCheck() {
459
+ if (this.conns.size > 0) return;
460
+ for (const s of this.sessions.values()) { try { s.save(); } catch { /* best effort */ } }
461
+ }
462
+
463
+ /** One validated request. */
464
+ _handle(socket, msg, ctx) {
465
+ const session = () => ctx.bound || ctx.open(msg.sessionId || '');
466
+ switch (msg.op) {
467
+ case 'ping':
468
+ ctx.reply(msg.id, true, 'pong');
469
+ return;
470
+ case 'open': {
471
+ const live = ctx.open(msg.sessionId || '', msg.workspace);
472
+ // THE FIRST LINE IS THE STATE. A front end that just connected has no idea what has
473
+ // already been said, and waiting for the next event to tell it means an empty window
474
+ // until the model speaks.
475
+ ctx.reply(msg.id, true, {
476
+ id: live.record.id,
477
+ title: live.record.title || '',
478
+ workspace: live.record.workspace || '',
479
+ model: live.record.model || '',
480
+ mode: live.record.mode || 'ask',
481
+ running: live.running,
482
+ rounds: live.rounds,
483
+ messages: live.messages,
484
+ });
485
+ return;
486
+ }
487
+ case 'submit': {
488
+ const live = session();
489
+ // ANSWERED IMMEDIATELY, NOT WHEN THE TURN ENDS. The reply acknowledges that the turn
490
+ // started; its progress arrives as events. Waiting for the turn would hold the
491
+ // connection's answer for minutes and tell the front end nothing until the end.
492
+ ctx.reply(msg.id, true, null);
493
+ void live.runTurn(msg.text);
494
+ return;
495
+ }
496
+ case 'dispatch': {
497
+ const live = session();
498
+ ctx.reply(msg.id, true, null);
499
+ void (async () => {
500
+ try {
501
+ const { SessionCore } = await import('./session-core.js');
502
+ void SessionCore;
503
+ } catch { /* the core is only needed by the TUI */ }
504
+ live.publish('error', { error: `commands are not available from this server yet: ${msg.cmd}` });
505
+ })();
506
+ return;
507
+ }
508
+ case 'interrupt': {
509
+ const live = session();
510
+ ctx.reply(msg.id, true, live.interrupt());
511
+ return;
512
+ }
513
+ case 'enqueue': {
514
+ const live = session();
515
+ live.queue.push(String(msg.text));
516
+ ctx.reply(msg.id, true, true);
517
+ return;
518
+ }
519
+ case 'reload_config': {
520
+ // RE-READ config.toml. The window owns the model picker, and every choice it makes is a
521
+ // write to that file; without this the server kept the model it resolved at startup and
522
+ // sent every turn to the provider the reader had just switched away from.
523
+ try {
524
+ this.cfg = resolveConfig();
525
+ // A COPY PER SESSION, keeping the folder each one is working in. Assigning the shared
526
+ // object back would undo the per-session workspace the turn relies on.
527
+ for (const live of new Set(this.sessions.values())) {
528
+ const own = { ...this.cfg, workspace: live.record.workspace || this.cfg.workspace };
529
+ live.cfg = own;
530
+ live.state.cfg = own;
531
+ live.host.cfg = own;
532
+ live.record.model = this.cfg.model;
533
+ }
534
+ // AND EVERY OPEN SESSION PICKED IT UP, so a conversation in flight follows the change.
535
+ ctx.reply(msg.id, true, { model: this.cfg.model });
536
+ } catch (e) {
537
+ ctx.reply(msg.id, false, null, String((e && e.message) || e));
538
+ }
539
+ return;
540
+ }
541
+ case 'set_workspace': {
542
+ // THE CHIP CAN CHANGE THE FOLDER for a conversation that already exists. It has to reach
543
+ // the session the turn runs in, or the tools keep resolving against the old one.
544
+ const live = session();
545
+ const dir = String(msg.workspace || '');
546
+ if (dir) {
547
+ live.record.workspace = dir;
548
+ live.cfg = { ...live.cfg, workspace: dir };
549
+ if (live.state) live.state.workspace = dir;
550
+ live.save();
551
+ }
552
+ ctx.reply(msg.id, true, !!dir);
553
+ return;
554
+ }
555
+ case 'set_mode': {
556
+ const live = session();
557
+ live.record.mode = msg.mode;
558
+ // THE LIVE STATE TOO. `runTurn` reads `state.mode`, which `makeState` filled from the
559
+ // record when the session opened — so writing only the record left a session that had
560
+ // been switched to Auto still asking permission for every tool.
561
+ live.state.mode = msg.mode;
562
+ live.save();
563
+ ctx.reply(msg.id, true, msg.mode);
564
+ return;
565
+ }
566
+ case 'approve': {
567
+ const live = session();
568
+ // `target` IS THE APPROVAL'S ID, not the request's. The envelope already uses `id` for
569
+ // the request, so answering by `id` would resolve the wrong thing — or nothing.
570
+ ctx.reply(msg.id, true, live.answer(msg.target, msg.approved));
571
+ return;
572
+ }
573
+ case 'answer': {
574
+ const live = session();
575
+ const ok = live.answer(msg.target, msg.answers);
576
+ ctx.reply(msg.id, true, ok);
577
+ return;
578
+ }
579
+ default:
580
+ ctx.reply(msg.id, false, null, `unhandled: ${msg.op}`);
581
+ }
582
+ }
583
+ }
584
+
585
+ /** Where the server records its own pid, so a second one does not start. */
586
+ export function servePidPath() {
587
+ return path.join(os.homedir(), '.hncode', 'serve.pid');
588
+ }
589
+
590
+ /** Open the server and keep it up until the process is asked to stop. */
591
+ export async function serve(opts = {}) {
592
+ const server = new SessionServer(opts);
593
+ const at = await server.listen();
594
+ // THE PID FILE IS THE SINGLETON. A named pipe accepts several instances, so a connection does not
595
+ // prove a server is already there — but a live pid in this file does. Written after `listen` so it
596
+ // never names a process that is not serving, and removed on the way out.
597
+ try {
598
+ const pidFile = servePidPath();
599
+ fs.mkdirSync(path.dirname(pidFile), { recursive: true });
600
+ fs.writeFileSync(pidFile, String(process.pid), 'utf8');
601
+ } catch { /* a machine without a writable home still runs a server, just not a single one */ }
602
+ process.stderr.write(`hncode serve: listening on ${at}\n`);
603
+ const stop = () => {
604
+ try { fs.unlinkSync(servePidPath()); } catch { /* already gone */ }
605
+ server.close();
606
+ process.exit(0);
607
+ };
608
+ process.on('SIGINT', stop);
609
+ process.on('SIGTERM', stop);
610
+ // The idle exit removes it too, or the next start sees a pid nobody owns.
611
+ process.on('exit', () => { try { fs.unlinkSync(servePidPath()); } catch { /* gone */ } });
612
+ return server;
613
+ }