@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
@@ -0,0 +1,148 @@
1
+ // The client half of the session protocol.
2
+ //
3
+ // It connects to `hncode serve`, keeps the connection, and turns the protocol into the two
4
+ // things a front end needs: a request that gets an answer, and a stream of events that arrives
5
+ // on its own.
6
+ //
7
+ // WHY NOT A FRESH PROCESS PER TURN
8
+ // --------------------------------
9
+ // Starting `hncode -p` per message re-reads the config, re-loads every plugin and re-parses the
10
+ // session file for every line typed, and then exits — so nothing survives, a turn cannot be
11
+ // talked to while it runs, and stopping means killing a process that may not have finished
12
+ // writing. This connects once and stays.
13
+
14
+ import net from 'node:net';
15
+ import { requestMessage } from './protocol.js';
16
+
17
+ /**
18
+ * A connection to the resident server.
19
+ *
20
+ * `onEvent(name, payload)` is called for every protocol event; `onClose(reason)` when the
21
+ * connection goes away for any reason, so the caller can reconnect rather than sit on a dead
22
+ * socket believing a turn is still running.
23
+ */
24
+ export class SessionClient {
25
+ constructor({ socketPath, onEvent, onClose } = {}) {
26
+ this.socketPath = socketPath;
27
+ this.onEvent = onEvent || (() => {});
28
+ this.onClose = onClose || (() => {});
29
+ this.socket = null;
30
+ this.buf = '';
31
+ this.pending = new Map(); // id -> { resolve, reject, timer }
32
+ this.seq = 0;
33
+ this.closed = false;
34
+ this.sessionId = '';
35
+ }
36
+
37
+ /** Connect and wait until the socket is up. */
38
+ connect() {
39
+ if (this.socket) return Promise.resolve();
40
+ return new Promise((resolve, reject) => {
41
+ const sock = net.connect(this.socketPath);
42
+ let settled = false;
43
+ sock.once('connect', () => {
44
+ settled = true;
45
+ this.socket = sock;
46
+ this.closed = false;
47
+ resolve();
48
+ });
49
+ sock.once('error', (e) => {
50
+ if (!settled) { settled = true; reject(e); return; }
51
+ this._fail(e && e.message ? e.message : 'socket error');
52
+ });
53
+ sock.on('close', () => this._fail('closed'));
54
+ sock.setNoDelay(true);
55
+ sock.on('data', (chunk) => this._onData(chunk));
56
+ });
57
+ }
58
+
59
+ _onData(chunk) {
60
+ this.buf += chunk.toString('utf8');
61
+ let nl;
62
+ while ((nl = this.buf.indexOf('\n')) !== -1) {
63
+ const line = this.buf.slice(0, nl).trim();
64
+ this.buf = this.buf.slice(nl + 1);
65
+ if (!line) continue;
66
+ let msg;
67
+ try { msg = JSON.parse(line); } catch { continue; }
68
+ if (msg.type === 'reply') {
69
+ const p = this.pending.get(msg.id);
70
+ if (!p) continue;
71
+ this.pending.delete(msg.id);
72
+ clearTimeout(p.timer);
73
+ if (msg.ok) p.resolve(msg.result);
74
+ else p.reject(new Error(msg.error || 'request failed'));
75
+ } else if (msg.type === 'event' && msg.event) {
76
+ try { this.onEvent(msg.event.type, msg.event); } catch { /* a listener must not break the stream */ }
77
+ } else if (msg.type === 'error') {
78
+ try { this.onEvent('error', { type: 'error', error: msg.error }); } catch { /* as above */ }
79
+ }
80
+ }
81
+ }
82
+
83
+ /** Reject every waiting request: their answers are never coming. */
84
+ _fail(reason) {
85
+ if (this.closed) return;
86
+ this.closed = true;
87
+ this.socket = null;
88
+ for (const [, p] of this.pending) {
89
+ clearTimeout(p.timer);
90
+ p.reject(new Error(reason || 'disconnected'));
91
+ }
92
+ this.pending.clear();
93
+ try { this.onClose(reason); } catch { /* the caller's own problem */ }
94
+ }
95
+
96
+ /** Send one request and wait for its answer. */
97
+ request(op, payload = {}, timeoutMs = 30_000) {
98
+ if (!this.socket) return Promise.reject(new Error('not connected'));
99
+ const id = `r${++this.seq}`;
100
+ const msg = requestMessage(id, op, payload);
101
+ return new Promise((resolve, reject) => {
102
+ const timer = setTimeout(() => {
103
+ this.pending.delete(id);
104
+ reject(new Error(`no answer to ${op}`));
105
+ }, timeoutMs);
106
+ this.pending.set(id, { resolve, reject, timer });
107
+ try {
108
+ this.socket.write(JSON.stringify(msg) + '\n');
109
+ } catch (e) {
110
+ clearTimeout(timer);
111
+ this.pending.delete(id);
112
+ reject(e);
113
+ }
114
+ });
115
+ }
116
+
117
+ /**
118
+ * Watch one conversation.
119
+ *
120
+ * The answer is the session's CURRENT state — its messages, its mode, whether a turn is
121
+ * running — so a window that opens an existing conversation draws it instead of waiting for
122
+ * the next event.
123
+ */
124
+ async open(sessionId, workspace) {
125
+ const payload = { sessionId: sessionId || '' };
126
+ // THE FOLDER THE CALLER WANTS THIS CONVERSATION TO WORK IN. Omitted means "whatever the record
127
+ // already says" — a caller reopening a conversation is not asking to move it.
128
+ if (workspace) payload.workspace = String(workspace);
129
+ const state = await this.request('open', payload);
130
+ if (state && state.id) this.sessionId = state.id;
131
+ return state;
132
+ }
133
+
134
+ submit(text) { return this.request('submit', { text }, 15_000); }
135
+ dispatch(cmd, arg) { return this.request('dispatch', { cmd, arg }, 60_000); }
136
+ interrupt() { return this.request('interrupt', {}); }
137
+ enqueue(text) { return this.request('enqueue', { text }); }
138
+ setMode(mode) { return this.request('set_mode', { mode }); }
139
+ /** Ask the server to re-read config.toml, after the window changed the model. */
140
+ reloadConfig() { return this.request('reload_config', {}, 10_000); }
141
+ approve(target, approved) { return this.request('approve', { target, approved }); }
142
+ answerTo(target, answers) { return this.request('answer', { target, answers }); }
143
+
144
+ close() {
145
+ if (this.socket) { try { this.socket.end(); } catch { /* gone */ } }
146
+ this._fail('closed by caller');
147
+ }
148
+ }
@@ -17,6 +17,7 @@
17
17
  //
18
18
  // Those belong to a session, not to a terminal. The host is where they live so both a TUI and a
19
19
  // daemon can have them.
20
+ import { usagePercent } from './format.js';
20
21
  import {
21
22
  StreamBuffer, StreamOp,
22
23
  } from './stream-buffer.js';
@@ -183,6 +184,57 @@ export class SessionHost {
183
184
  return s;
184
185
  }
185
186
 
187
+ /**
188
+ * The one place the context gauge is set.
189
+ *
190
+ * `opts.fromEstimate` marks a figure the local tokenizer produced. Those are only used until the
191
+ * endpoint reports a real size, and after that they are ignored: the estimate runs about 1.8x
192
+ * high, so letting it win would make the gauge jump between two definitions of the same thing.
193
+ *
194
+ * `opts.reported` marks a provider figure. It latches the switch and mirrors onto the session, so
195
+ * a resume starts from the real size rather than the estimate.
196
+ */
197
+ setCtxTokens(tokens, max, opts = {}) {
198
+ const st = this.state;
199
+ if (!st) return;
200
+ if (opts.fromEstimate && st.ctxReportedOnce) return; // a report outranks every estimate
201
+ const n = Math.max(0, Number(tokens) || 0);
202
+ st.ctxTokens = n;
203
+ if (opts.reported) {
204
+ st.ctxReportedOnce = true;
205
+ st.ctxSource = 'provider';
206
+ if (this.session) { this.session.ctxTokens = n; this.session.ctxReportedOnce = true; }
207
+ } else if (opts.fromEstimate) {
208
+ st.ctxSource = 'estimate';
209
+ }
210
+ if (Number.isFinite(max) && max > 0) st.ctxMax = max;
211
+ // THE SHARED FUNCTION, not a second formula: `usagePercent` rounds up, and two spellings of
212
+ // the same ratio disagree by a percent on identical numbers.
213
+ st.ctxPercent = usagePercent(n, st.ctxMax || 1);
214
+ if (!Array.isArray(st.tokenHistory)) st.tokenHistory = [];
215
+ const h = st.tokenHistory;
216
+ if (h[h.length - 1] !== n) {
217
+ h.push(n);
218
+ if (h.length > 240) h.splice(0, h.length - 240);
219
+ }
220
+ }
221
+
222
+ /**
223
+ * The history just got SHORTER, so a provider report describes a request that no longer exists.
224
+ *
225
+ * A report outranks an estimate, which is right for a growing request and wrong here: after a
226
+ * compaction the old figure was kept and the gauge sat on the pre-compaction size for the rest
227
+ * of the session.
228
+ */
229
+ noteCtxAfterShrink(tokens) {
230
+ const st = this.state;
231
+ if (st) {
232
+ st.ctxReportedOnce = false;
233
+ st.ctxSource = 'estimate';
234
+ }
235
+ if (this.session) this.session.ctxReportedOnce = false;
236
+ this.setCtxTokens(Number(tokens) || 0, null, { fromEstimate: true });
237
+ }
186
238
  /**
187
239
  * Name the session from its first exchange.
188
240
  *
package/src/session.js CHANGED
@@ -54,6 +54,21 @@ export function newId() {
54
54
  return Date.now().toString(36) + '-' + crypto.randomBytes(3).toString('hex');
55
55
  }
56
56
 
57
+ /**
58
+ * A session name made from the first thing the user typed.
59
+ *
60
+ * Used when automatic naming is OFF, and always by the headless CLI (which never runs the
61
+ * naming request). One line, twenty characters — one rule for both front ends, so a session
62
+ * named in the terminal and one named from the window carry the same string.
63
+ */
64
+ export function titleFromPrompt(text) {
65
+ const line = String(text || '').replace(/\s+/g, ' ').trim();
66
+ if (!line) return '';
67
+ // Count by CODE POINTS: slice(0, 20) on a string of emoji splits one in half and leaves a
68
+ // lone surrogate, which renders as a replacement glyph in the title.
69
+ const chars = Array.from(line);
70
+ return chars.length <= 20 ? line : chars.slice(0, 20).join('') + '…';
71
+ }
57
72
  export function sessionFile(id, storeDir) {
58
73
  return path.join(dir(storeDir), `${id}.json`);
59
74
  }
@@ -105,7 +120,11 @@ function serializableSession(session) {
105
120
  out.workspace = session.workspace || '';
106
121
  out.model = session.model || '';
107
122
  out.createdAt = session.createdAt || Date.now();
108
- out.updatedAt = Date.now();
123
+ // THE SAVE TIME IS NOT THE EDIT TIME. A session is written after every turn AND after a
124
+ // rename, a mode change or a goal set — each of which would bump a timestamp nobody asked
125
+ // for, and that timestamp then reordered the rail. `updatedAt` moves only when the
126
+ // conversation does; a metadata-only save keeps the value the session already had.
127
+ out.updatedAt = Number(session.updatedAt) || Date.now();
109
128
  // Everything else (rounds, steps, plan, focus, swarm, effort, …) is copied AFTER
110
129
  // updatedAt. `messages` and `transcript` in particular must come after the metadata
111
130
  // block, and they are appended below in that order.
@@ -680,13 +699,17 @@ function skipJsonValue(text, at) {
680
699
  // "not loaded yet".
681
700
  export function listSessions(storeDir) {
682
701
  const out = [];
683
- for (const { meta } of scanCached(storeDir)) {
702
+ for (const { meta, hasMessages } of scanCached(storeDir)) {
684
703
  // FIX: fall back to createdAt so a legacy session written with a
685
704
  // post-messages updatedAt still sorts reasonably instead of as 0.
686
705
  if (!meta.updatedAt && meta.createdAt) meta.updatedAt = meta.createdAt;
706
+ // Whether the record holds any message. It comes from the same head-read the cache already
707
+ // did for `--continue`, so publishing it costs nothing — and it is the only reliable way to
708
+ // tell a real conversation from a file a process opened and abandoned.
709
+ meta.hasMessages = !!hasMessages;
687
710
  out.push(meta);
688
711
  }
689
- out.sort((a, b) => (b.updatedAt || 0) - (a.updatedAt || 0));
712
+ out.sort((a, b) => ((b.updatedAt || 0) - (a.updatedAt || 0)) || String(a.id).localeCompare(String(b.id)));
690
713
  return out;
691
714
  }
692
715
 
@@ -167,8 +167,8 @@ export const SETTINGS_SCHEMA = [
167
167
  // ---- tools --------------------------------------------------------------
168
168
  { key: 'tool_allow_external_paths', ...bool(false),
169
169
  ui: { tab: 'tools', group: 'Files', label: 'Allow external paths', hint: 'Let file tools read and write outside the workspace' } },
170
- { key: 'swarm_mode', ...bool(false),
171
- ui: { tab: 'tools', group: 'Delegation', label: 'Swarm mode', hint: 'Expose AgentSwarm for fanning work across subagents' } },
170
+ // `swarm_mode` is NOT here. Swarm is a per-session switch (`/swarm`), like plan and focus;
171
+ // a saved value turned every later session into one that decomposes its work.
172
172
  { key: 'output_style', ...str(''),
173
173
  ui: { tab: 'tools', group: 'Output', label: 'Output style', hint: 'Named style overriding how replies are written' } },
174
174
  // THE WEB SEARCH KEYS. Keyless search is rate-limited per IP, so on a shared or busy address WebSearch
@@ -0,0 +1,48 @@
1
+ // The session tallies as one line of text: rounds, steps, tokens per second.
2
+ //
3
+ // WHY THIS IS ITS OWN MODULE. The terminal draws this sentence with colour codes and a hitbox
4
+ // column, and a window has no use for either — but the WORDS are worth sharing: they go through
5
+ // the i18n table, so a Chinese terminal and a Chinese window print the same thing instead of two
6
+ // translations that drift apart. Putting it here lets both front ends import it without the
7
+ // headless run pulling in tui.js, which is a large module that exists to drive a terminal.
8
+ import { t as i18nT } from './i18n.js';
9
+
10
+ let lang = 'en';
11
+
12
+ /** Point the shared wording at a language. Same two ids the rest of the UI offers. */
13
+ export function setStatusLang(next) { lang = next === 'zh' ? 'zh' : 'en'; }
14
+
15
+ function tr(key, fallback, vars) {
16
+ const s = i18nT(lang, key) || fallback;
17
+ if (!vars) return s;
18
+ let out = s;
19
+ for (const k of Object.keys(vars)) out = out.split('{' + k + '}').join(String(vars[k]));
20
+ return out;
21
+ }
22
+
23
+ /**
24
+ * One line: `12 轮 | 3 步 | 41 tok/s`, or its English equivalent.
25
+ *
26
+ * @param {object} o
27
+ * @param {number} o.rounds - completed turns.
28
+ * @param {number} o.steps - model rounds counted so far.
29
+ * @param {number} o.tokRate - output tokens per second, already a short-window rate.
30
+ * @param {string} [o.cost] - formatted cost; omitted when no price is known, because a guessed
31
+ * figure reads as "this was free" rather than "this is unknown".
32
+ */
33
+ export function statusTallyText({ rounds = 0, steps = 0, tokRate = 0, cost = '' } = {}) {
34
+ const parts = [];
35
+ if (cost) parts.push(`${cost} ${tr('cost', 'cost')}`);
36
+ parts.push(rounds === 1
37
+ ? tr('status.turnsOne', '{n} turn', { n: rounds })
38
+ : tr('status.turns', '{n} turns', { n: rounds }));
39
+ parts.push(steps === 1
40
+ ? tr('status.stepsOne', '{n} step', { n: steps })
41
+ : tr('status.steps', '{n} steps', { n: steps }));
42
+ // THE RATE IS ALWAYS PRINTED, ZERO INCLUDED. Zero says the model is not producing right
43
+ // now, which is a fact about the turn; dropping the part made the row look broken.
44
+ parts.push(`${Math.round(tokRate)} tok/s`);
45
+ return parts.join(' | ');
46
+ }
47
+
48
+ export default { statusTallyText, setStatusLang };
package/src/toml.js CHANGED
@@ -132,7 +132,15 @@ function parseScalar(raw) {
132
132
 
133
133
  function parseBasicString(t, isKey) {
134
134
  t.next(); // opening "
135
- if (t.peek() === '"' && t.next() === '"' && t.next() === '"') {
135
+ // NON-DESTRUCTIVE LOOKAHEAD.
136
+ //
137
+ // This used to be a `peek/next/next` chain that CONSUMED the quotes while testing them. For
138
+ // an EMPTY string `""` it swallowed the closing quote and the character after it — normally
139
+ // the newline — so the single-line loop below ran on into the next line and threw
140
+ // "unterminated basic string". A config holding `model = ""` and any [table] after it became
141
+ // wholly unparseable: every provider and model entry read as "no config at all".
142
+ if (t.s.startsWith('""', t.pos)) {
143
+ t.pos += 3; // consume the three quotes the check just looked at
136
144
  // multiline basic """
137
145
  // line-ending-trim: skip a newline immediately following the opening """
138
146
  if (t.cur() === '\n') t.next();
@@ -145,7 +153,9 @@ function parseBasicString(t, isKey) {
145
153
  out += unescapeBasic(e, t);
146
154
  continue;
147
155
  }
148
- if (c === '"' && t.peek() === '"' && t.next() === '"' && t.next() === '"') break;
156
+ // NON-DESTRUCTIVE, like the opening check: a two-quote sequence inside a multiline
157
+ // string used to be consumed by the test and then never appended, so the text lost it.
158
+ if (c === '"' && t.s.startsWith('""', t.pos)) { t.pos += 2; break; }
149
159
  if (c === '\r' && t.cur() === '\n') { t.next(); out += '\n'; continue; }
150
160
  out += c;
151
161
  }
@@ -182,14 +192,18 @@ function readHex(t, count) {
182
192
 
183
193
  function parseLiteralString(t, isKey) {
184
194
  t.next(); // opening '
185
- if (t.peek() === "'" && t.next() === "'" && t.next() === "'") {
195
+ // The same non-destructive test as the basic string above: on two quotes the old chain ate
196
+ // its own closing quote and the character after it.
197
+ if (t.s.startsWith("''", t.pos)) {
198
+ t.pos += 3; // consume the three quotes the check just looked at
186
199
  // multiline literal '''
187
200
  if (t.cur() === '\n') t.next();
188
201
  else if (t.cur() === '\r') { t.next(); if (t.cur() === '\n') t.next(); }
189
202
  let out = '';
190
203
  while (!t.eof()) {
191
204
  const c = t.next();
192
- if (c === "'" && t.peek() === "'" && t.next() === "'" && t.next() === "'") break;
205
+ // Same as above for the literal form.
206
+ if (c === "'" && t.s.startsWith("''", t.pos)) { t.pos += 2; break; }
193
207
  out += c;
194
208
  }
195
209
  return out;
@@ -0,0 +1,45 @@
1
+ // Whether a tool result is a FAILURE, and why.
2
+ //
3
+ // Shared by both front ends: the terminal colours the row from it, and the CLI puts the answer on
4
+ // the stream as `failed` so a window does not have to re-guess with its own regex. The desktop
5
+ // used to do exactly that, and its short list missed "Edit rejected:" — a refused edit showed a
6
+ // green dot over text that said it had been refused.
7
+
8
+ // Failure prefixes that the built-in tools actually return (verified against src/tools/*.js).
9
+ // "Error: old_string not found in …" (Edit)
10
+ // "Error reading/writing <path>: …" (Read/Write/Edit)
11
+ // "Cannot read: <path> appears to be …" (Read)
12
+ // "Edit rejected: …" (Edit staleness / read guards)
13
+ // "Command cannot be empty." (Bash)
14
+ // resolvePath throws are surfaced verbatim as `e.message`, e.g.
15
+ // "Path outside workspace: …" / "ENOENT: no such file or directory …".
16
+ const FAIL_PREFIX = /^(Error\b|\[error:|Cannot read:|Edit rejected:|Command cannot be empty\b|Path outside workspace\b|ENOENT\b|EACCES\b|EPERM\b|EISDIR\b|ENOTDIR\b)/i;
17
+
18
+ export function isFailureResult(text, toolName) {
19
+ const s = String(text == null ? '' : text);
20
+ const trimmed = s.trim();
21
+ if (FAIL_PREFIX.test(trimmed)) return true;
22
+ // A non-zero Bash exit code marks the call as failed. The `[exit code: N]` line itself is
23
+ // bookkeeping for the model and is never shown.
24
+ const m = /\[exit code:\s*([^\]]+)\]/.exec(s);
25
+ if (!m) return false;
26
+ const v = m[1].trim();
27
+ return v !== '0';
28
+ }
29
+
30
+ /**
31
+ * The human-readable failure reason, or '' when there is nothing extra to say.
32
+ *
33
+ * Shown under the tool call for non-Bash tools; a Bash failure is already obvious from the
34
+ * command's own output.
35
+ */
36
+ export function failureReason(text, toolName) {
37
+ const name = String(toolName || '').toLowerCase();
38
+ if (name === 'bash') return '';
39
+ const s = String(text == null ? '' : text);
40
+ const trimmed = s.trim();
41
+ if (!FAIL_PREFIX.test(trimmed)) return '';
42
+ let line = trimmed.split('\n')[0].trim();
43
+ line = line.replace(/^\[error:\s*/i, '').replace(/\]$/, '').trim();
44
+ return line;
45
+ }
package/src/tools/bash.js CHANGED
@@ -14,6 +14,18 @@ export const DEFAULT_TIMEOUT_S = 60;
14
14
  export const MAX_TIMEOUT_S = 5 * 60;
15
15
  export const MAX_BACKGROUND_TIMEOUT_S = 24 * 60 * 60;
16
16
 
17
+ // A foreground command that is still running after this long is moved to the background
18
+ // rather than killed. The user is waiting on a turn; a command that takes longer than five
19
+ // minutes is plainly a long job, and destroying its work at that point is worse than letting
20
+ // it continue where TaskList can see it.
21
+ export const AUTO_BACKGROUND_S = 5 * 60;
22
+
23
+ /** Overridable for tests and for anyone who wants a different threshold. */
24
+ export function autoBackgroundSeconds() {
25
+ const raw = Number(process.env.HNCODE_AUTO_BACKGROUND_S);
26
+ return Number.isFinite(raw) && raw > 0 ? raw : AUTO_BACKGROUND_S;
27
+ }
28
+
17
29
 
18
30
 
19
31
  // ---- output sanitizing -------------------------------------------------------
@@ -131,14 +143,14 @@ export const spec = {
131
143
  get description() {
132
144
  const shell = getShell();
133
145
  const which = shell ? (shell.edition === 'posix' ? 'the POSIX shell' : shell.name) : 'the system shell';
134
- return `Run a shell command via ${which}. Returns combined stdout+stderr. timeout default 60s (max 300s); run_in_background detaches and returns a task id.`;
146
+ return `Run a shell command via ${which}. Returns combined stdout+stderr. A foreground command still running after 5 minutes moves to the background automatically; run_in_background detaches immediately and returns a task id with no timeout.`;
135
147
  },
136
148
  parameters: {
137
149
  type: 'object',
138
150
  properties: {
139
151
  command: { type: 'string', description: 'Shell command to execute.' },
140
152
  description: { type: 'string', description: 'Short description (shown in task lists; required for background tasks).' },
141
- timeout: { type: 'integer', minimum: 1, description: 'Seconds before the command is killed. Foreground default 60s/max 300s. A BACKGROUND command has NO default limit — it runs until it finishes or is stopped — so pass this only when the job really must be cut short (max 86400s).' },
153
+ timeout: { type: 'integer', minimum: 1, description: 'NOT USED. A foreground command runs up to 5 minutes and then moves to the background; a background command has no timeout. Kept only so older calls that pass it do not break.' },
142
154
  cwd: { type: 'string', description: 'Working directory (default: workspace/project root).' },
143
155
  run_in_background: { type: 'boolean', default: false, description: 'Run detached and return a task id instead of waiting.' },
144
156
  interactive: { type: 'boolean', default: false, description: 'With run_in_background: keep stdin open so TaskInput can write to it — for a command that prompts.' },
@@ -155,10 +167,15 @@ timeout: { type: 'integer', minimum: 1, description: 'Seconds before the command
155
167
 
156
168
  if (args.run_in_background) return spawnBackground(args, cwd, ctx);
157
169
 
158
- // A FOREGROUND run has a default limit: the user is waiting, and a command that hangs
159
- // would hang the turn with it. A BACKGROUND run has none (see spawnBackground).
160
- const timeoutMs = args.disable_timeout ? undefined : Math.min(args.timeout ?? DEFAULT_TIMEOUT_S, MAX_TIMEOUT_S) * 1000;
161
- const command = args.command;
170
+ // A foreground command is given five minutes before it is moved to the background.
171
+ //
172
+ // It used to be killed at 60 seconds. That is wrong for anything with real work in it: a
173
+ // build, a migration, a long install — the user is waiting, but destroying the job at the
174
+ // one-minute mark throws away everything it did. Five minutes is long enough that a
175
+ // command still running is plainly a long job, and it is then DETACHED, not killed (see
176
+ // the timer below). `disable_timeout` keeps its long-standing meaning: never touch it.
177
+ const autoBgMs = args.disable_timeout ? 0 : autoBackgroundSeconds() * 1000;
178
+ const command = args.command;
162
179
  // STDIN IS A PIPE FOR EVERY RUN. The agent never types into it, but the USER can: a program that prompts
163
180
  // (`npm init`, a REPL, a script reading a line) used to sit on /dev/null until the timeout killed it, with
164
181
  // no way to answer. A background run is fed through TaskInput, a foreground one through the composer's
@@ -254,8 +271,18 @@ const command = args.command;
254
271
  if (child.stdout) child.stdout.on('data', push);
255
272
  if (child.stderr) child.stderr.on('data', push);
256
273
 
274
+ // A holder for the detach hook, which is defined inside the Promise below. When the
275
+ // five-minute mark is reached we MOVE the command to the background, never kill it:
276
+ // the work it has done is kept and it stays inspectable through TaskList.
257
277
  let timer = null;
258
- if (timeoutMs) timer = setTimeout(() => { killTree(child); }, timeoutMs);
278
+ let autoDetach = null;
279
+ if (autoBgMs) {
280
+ timer = setTimeout(() => {
281
+ if (autoDetach) autoDetach();
282
+ else killTree(child); // no hook yet means the child never entered the Promise
283
+ }, autoBgMs);
284
+ if (timer.unref) timer.unref();
285
+ }
259
286
 
260
287
  // Esc / Ctrl-C in the TUI aborts the turn: kill the running command too,
261
288
  // otherwise a long command keeps running after the user interrupted.
@@ -305,6 +332,10 @@ if (child.stdout) child.stdout.on('data', push);
305
332
  return id;
306
333
  },
307
334
  };
335
+ // The five-minute timer reaches the SAME path Ctrl+B uses, so an automatic move and
336
+ // a manual one produce exactly the same task: one entry in TaskList, one live output
337
+ // buffer, no kill.
338
+ autoDetach = () => ctx._foreground && ctx._foreground.detach();
308
339
  }
309
340
  child.on('close', (code) => {
310
341
  cleanup();
@@ -413,24 +444,12 @@ function spawnBackground(args, cwd, ctx) {
413
444
  task.exitCode = code;
414
445
  }
415
446
  });
416
- // THE BACKGROUND TIMEOUT IS OPT-IN.
417
- //
418
- // A background task was started precisely because it takes a while — a build, a test
419
- // suite, a deploy. Killing it after ten minutes because nobody happened to say
420
- // otherwise meant the job the user deliberately put in the background died on a clock
421
- // they never asked for, and the work was simply lost.
447
+ // A BACKGROUND TASK HAS NO TIMEOUT, AT ALL.
422
448
  //
423
- // So there is no default limit: the task runs until it finishes or until someone stops
424
- // it. A limit applies only when the caller asked for one, and even then it is capped so
425
- // a mistyped number cannot leave a process running for a week.
426
- if (!args.disable_timeout && args.timeout != null) {
427
- const bgTimeoutMs = Math.min(args.timeout, MAX_BACKGROUND_TIMEOUT_S) * 1000;
428
- const t = setTimeout(() => {
429
- killTree(child);
430
- settleTask(task, 'timed_out', { stopReason: 'timed out' });
431
- }, bgTimeoutMs);
432
- if (t.unref) t.unref();
433
- }
449
+ // It was put in the background precisely because it takes a while. Even an explicit
450
+ // `timeout` is ignored here: the caller may have copied the argument from a foreground
451
+ // call, and a background job that dies on a clock nobody asked for loses work silently.
452
+ // A background task runs until it finishes or until someone stops it with TaskStop.
434
453
  child.unref();
435
454
  return `Background task ${task.taskId} started (pid ${child.pid}): ${args.description || args.command}
436
455
  Inspect with TaskList (running tasks) and TaskOutput {task_id: "${task.taskId}"} (output).`;
package/src/tools/edit.js CHANGED
@@ -28,7 +28,8 @@ import { hashRegion as hashLines } from './read.js';
28
28
 
29
29
  export const spec = {
30
30
  name: 'Edit',
31
- description: `Edit a file. Three shapes: LINE-RANGE (path + start_line + end_line + new_string),
31
+ description: `READ THE FILE FIRST. Never edit what you have not read this turn — the contents move, and an edit against a remembered version fails or lands in the wrong place. Read a file again after anything else has changed it.
32
+ Edit a file. Three shapes: LINE-RANGE (path + start_line + end_line + new_string),
32
33
  SUBSTRING (path + old_string + new_string, unique unless replace_all), RANGED SUBSTRING (the same plus
33
34
  start_line + end_line, which narrows where old_string is searched).
34
35
 
@@ -173,8 +174,10 @@ duplicate, the fix is to remove the duplicated line — never to restate another
173
174
  let rangeHandled = hasSubKeys;
174
175
  if (hasRangeKeys && hasSubKeys && hasNewString) {
175
176
  if ((start_line != null) !== (end_line != null)) {
176
- // Ignore the unpaired bound; `searchFrom`/`searchTo` stay at the whole file and `rangedToWindow`
177
- // was already set above.
177
+ // Ignore the unpaired bound: `searchFrom`/`searchTo` stay at the whole file, so the
178
+ // snippet is searched everywhere. `rangeHandled` is already true from `hasSubKeys`, which
179
+ // is what keeps the line-range guard below from seeing the same half-given bound and
180
+ // rejecting a call that was already complete.
178
181
  searchFrom = 0;
179
182
  searchTo = 0;
180
183
  } else {
@@ -258,7 +261,8 @@ duplicate, the fix is to remove the duplicated line — never to restate another
258
261
  if (ctx) ctx.lastEditDiff = buildEditDiff({ fileLines: lines, oldText: replacedText, newText: inserted.join('\n'), startLine: start, filePath: p });
259
262
  const written = Math.max(1, inserted.length);
260
263
  const excerpt = readAfterEdit(p, start, written, ctx);
261
- return `Edited ${args.path}: replaced lines ${start}-${end} (${removed} line${removed === 1 ? '' : 's'}) with ${inserted.length} line${inserted.length === 1 ? '' : 's'}.\n\n${excerpt}`.trimEnd();
264
+ // THE CHANGED REGION IS THE ANSWER. See the note in write.js.
265
+ return excerpt.trimEnd();
262
266
  }
263
267
 
264
268
  // ---- SUBSTRING mode (old_string -> new_string) --------------------------
@@ -415,7 +419,8 @@ duplicate, the fix is to remove the duplicated line — never to restate another
415
419
  const writtenLines = normalizeText(new_string).split('\n').length;
416
420
  const excerpt = readAfterEdit(p, editedAt, writtenLines, replace_all ? null : ctx);
417
421
  if (replace_all && ctx && ctx.readPool) ctx.readPool.delete(p);
418
- return `Edited ${args.path}: replaced ${occurrences} occurrence(s).\n\n${excerpt}`.trimEnd();
422
+ // THE CHANGED REGION IS THE ANSWER. See the note in write.js.
423
+ return excerpt.trimEnd();
419
424
  },
420
425
  };
421
426
 
@@ -76,12 +76,15 @@ export function parseSearchResults(json, limit = 8) {
76
76
  export const spec = {
77
77
  name: 'WebSearch',
78
78
  description: [
79
- 'Search the web. Results are title/URL/snippet; snippets are summaries, so fetch a promising URL with',
80
- 'FetchURL. Cite sources.',
79
+ 'Search the web. Use it whenever you do not know something and the answer is not in the repository:',
80
+ 'a library version, an API you have not seen, an error you cannot place, anything after your training',
81
+ 'cutoff. A guess presented as fact is worse than a search.',
81
82
  '',
82
- 'Use FEW words: two or three that name the thing. Adding generic terms ("下载", "热门", "官网",',
83
- '"tutorial") does not narrow the search — it matches more unrelated pages, because those are the words',
84
- 'junk pages stuff into their titles.',
83
+ 'Results are title/URL/snippet; snippets are summaries, so fetch a promising URL with FetchURL.',
84
+ 'Cite the sources you use.',
85
+ '',
86
+ 'Use FEW words: two or three that name the thing. Generic terms ("下载", "热门", "官网", "tutorial")',
87
+ 'match more junk, not more relevant pages.',
85
88
  ].join('\n'),
86
89
  parameters: {
87
90
  type: 'object',