@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.
- package/README.md +30 -0
- package/README_CN.md +27 -0
- package/package.json +1 -1
- package/src/agent.js +172 -43
- package/src/bootstrap.js +63 -56
- package/src/ci.js +247 -247
- package/src/colors.js +5 -1
- package/src/commands.js +121 -0
- package/src/composer.js +31 -1
- package/src/config.js +177 -45
- package/src/context.js +29 -0
- package/src/files.js +32 -0
- package/src/fx.js +19 -2
- package/src/i18n.js +180 -131
- package/src/index.js +558 -77
- package/src/permission-gate.js +103 -0
- package/src/plugin.js +221 -2
- package/src/prompt-presets.js +36 -0
- package/src/protocol.js +184 -0
- package/src/registry-browser.js +14 -3
- package/src/remote.js +117 -5
- package/src/schedule.js +148 -11
- package/src/serve.js +613 -0
- package/src/session-client.js +148 -0
- package/src/session-host.js +52 -0
- package/src/session.js +26 -3
- package/src/settings-schema.js +2 -2
- package/src/status-line.js +48 -0
- package/src/term.js +20 -1
- package/src/toml.js +18 -4
- package/src/tool-line.js +13 -6
- package/src/tool-status.js +45 -0
- package/src/tools/bash.js +43 -24
- package/src/tools/edit.js +10 -5
- package/src/tools/web-search.js +8 -5
- package/src/tools/write.js +28 -3
- package/src/tui.js +498 -1397
- package/src/ws.js +248 -0
- package/src/session-hub.js +0 -445
- package/src/web-auth.js +0 -98
- package/src/web-daemon-cli.js +0 -63
- package/src/web-daemon-client.js +0 -203
- package/src/web-daemon.js +0 -894
- package/src/web-live.js +0 -250
- package/src/web-public/app.css +0 -1524
- package/src/web-public/app.js +0 -2969
- package/src/web-public/complete.js +0 -154
- package/src/web-public/fonts/JetBrainsMono-Bold.woff2 +0 -0
- package/src/web-public/fonts/JetBrainsMono-Regular.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-100-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-101-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-102-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-103-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-104-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-105-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-106-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-107-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-108-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-109-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-110-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-111-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-112-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-113-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-114-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-115-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-116-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-117-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-118-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-119-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-21-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-22-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-23-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-24-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-25-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-26-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-27-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-28-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-29-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-30-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-31-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-32-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-33-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-34-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-35-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-36-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-37-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-38-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-39-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-4-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-40-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-41-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-42-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-43-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-44-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-45-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-46-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-47-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-48-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-49-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-5-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-50-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-51-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-52-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-53-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-54-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-55-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-56-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-57-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-58-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-59-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-6-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-60-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-61-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-62-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-63-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-64-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-65-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-66-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-67-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-68-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-69-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-70-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-71-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-72-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-73-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-74-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-75-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-76-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-77-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-78-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-79-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-80-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-81-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-82-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-83-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-84-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-85-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-86-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-87-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-88-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-89-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-90-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-91-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-97-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-98-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-99-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc.css +0 -775
- package/src/web-public/fonts.css +0 -31
- package/src/web-public/home.css +0 -222
- package/src/web-public/home.html +0 -33
- package/src/web-public/home.js +0 -160
- package/src/web-public/i18n.js +0 -983
- package/src/web-public/index.html +0 -196
- package/src/web-public/login.css +0 -123
- package/src/web-public/login.html +0 -25
- package/src/web-public/login.js +0 -46
- package/src/web-public/settings.js +0 -290
- package/src/web-ws.js +0 -226
- 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
|
+
}
|
package/src/session-host.js
CHANGED
|
@@ -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
|
-
|
|
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
|
|
package/src/settings-schema.js
CHANGED
|
@@ -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
|
-
|
|
171
|
-
|
|
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/term.js
CHANGED
|
@@ -62,6 +62,15 @@ export function strWidth(s) {
|
|
|
62
62
|
// * everything else is memoised (see WIDTH_CACHE_MAX). Rows are re-measured
|
|
63
63
|
// every frame while a reply streams, and the same substrings come back
|
|
64
64
|
// again and again.
|
|
65
|
+
/** Matches any escape sequence, for the width walk to skip. */
|
|
66
|
+
const ESC_RE = /\x1b/;
|
|
67
|
+
function stripEscapes(s) {
|
|
68
|
+
return String(s)
|
|
69
|
+
.replace(/\x1b\[[0-9;?]*[a-zA-Z]/g, '')
|
|
70
|
+
.replace(/\x1b\[[0-9;?]* [a-zA-Z]/g, '')
|
|
71
|
+
.replace(/\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)/g, '');
|
|
72
|
+
}
|
|
73
|
+
|
|
65
74
|
export function visualWidth(s) {
|
|
66
75
|
if (!s) return 0;
|
|
67
76
|
const str = typeof s === 'string' ? s : String(s);
|
|
@@ -69,7 +78,17 @@ export function visualWidth(s) {
|
|
|
69
78
|
if (isPrintableAscii(str)) return str.length;
|
|
70
79
|
const hit = widthCache.get(str);
|
|
71
80
|
if (hit !== undefined) return hit;
|
|
72
|
-
|
|
81
|
+
|
|
82
|
+
// ANSI ESCAPES ARE NOT GLYPHS.
|
|
83
|
+
//
|
|
84
|
+
// This measured the raw string, so every colour sequence counted as its own characters:
|
|
85
|
+
// `col('● ', orange)` — `ESC[38;2;240;160;80m` + `● ` + `ESC[0m` — came out TWENTY-TWO
|
|
86
|
+
// columns wide instead of two. Every styled row in the frame was therefore measured far
|
|
87
|
+
// wider than it draws, which put `fitAnsi` short, pushed the scrollbar off the edge, and
|
|
88
|
+
// made the row/column arithmetic in the mouse mapping disagree with the screen by however
|
|
89
|
+
// much styling that row happened to carry — an offset that changes from place to place.
|
|
90
|
+
const plain = ESC_RE.test(str) ? stripEscapes(str) : str;
|
|
91
|
+
const w = clusterWidth(plain);
|
|
73
92
|
if (widthCache.size >= WIDTH_CACHE_MAX) {
|
|
74
93
|
// Cheap eviction: drop the oldest insertion (Map preserves order).
|
|
75
94
|
const oldest = widthCache.keys().next().value;
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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;
|
package/src/tool-line.js
CHANGED
|
@@ -55,7 +55,7 @@ const MAX_ARG = 60;
|
|
|
55
55
|
* of characters, and printing it whole wrapped the row across the screen for every call. Ctrl+O is the escape hatch —
|
|
56
56
|
* whoever expands tool output to read it wants to see the command they are reading the output OF.
|
|
57
57
|
*/
|
|
58
|
-
export function keyArgument(name, args, workspace, expanded = false) {
|
|
58
|
+
export function keyArgument(name, args, workspace, expanded = false, budget = MAX_ARG) {
|
|
59
59
|
if (!args || typeof args !== 'object') return '';
|
|
60
60
|
const keys = KEY_ARG[name] || Object.keys(args);
|
|
61
61
|
// Expanded: the whole value, with newlines kept, so a multi-line script shows as the lines it was written as rather
|
|
@@ -81,15 +81,15 @@ export function keyArgument(name, args, workspace, expanded = false) {
|
|
|
81
81
|
while (valueLines.length > 1 && valueLines[valueLines.length - 1].trim() === '') valueLines.pop();
|
|
82
82
|
let text = valueLines[0];
|
|
83
83
|
const rest = valueLines.length > 1 ? valueLines.length - 1 : 0;
|
|
84
|
-
if (text.length >
|
|
84
|
+
if (text.length > budget) {
|
|
85
85
|
text = (k === 'path' || k === 'file_path')
|
|
86
|
-
? '…' + text.slice(text.length - (
|
|
87
|
-
: text.slice(0,
|
|
86
|
+
? '…' + text.slice(text.length - (budget - 1))
|
|
87
|
+
: text.slice(0, budget - 1) + '…';
|
|
88
88
|
} else if (rest) {
|
|
89
89
|
// Make room for the marker before adding it, so the row never overflows: the count is dropped first because the
|
|
90
90
|
// ellipsis already carries the important half of the message.
|
|
91
91
|
const withCount = `… (+${rest} line${rest === 1 ? '' : 's'})`;
|
|
92
|
-
text += text.length + withCount.length <=
|
|
92
|
+
text += text.length + withCount.length <= budget
|
|
93
93
|
? withCount
|
|
94
94
|
: '…';
|
|
95
95
|
}
|
|
@@ -109,7 +109,14 @@ export function keyArgument(name, args, workspace, expanded = false) {
|
|
|
109
109
|
*/
|
|
110
110
|
export function formatToolLine(msg, workspace, spin, pulseStart, shimmerEdge, expanded = false, reducedMotion = false, width = 0) {
|
|
111
111
|
const name = msg.toolName || '';
|
|
112
|
-
|
|
112
|
+
// THE ARGUMENT IS CUT TO WHAT IS LEFT OF THE ROW.
|
|
113
|
+
//
|
|
114
|
+
// It was cut to a hardcoded 60 characters, so `● Using Bash (…)` measured 13 + 60 = 73
|
|
115
|
+
// columns on every terminal. Anything narrower than that was wrapped BY THE TERMINAL,
|
|
116
|
+
// taking two display rows where the frame counted one, and every row below moved down.
|
|
117
|
+
// `width` is the row the caller has; the verb and the name come out of it first.
|
|
118
|
+
const argBudget = Math.max(8, (width || 0) - (msg.pending ? 'Using' : 'Used').length - 1 - name.length - 3);
|
|
119
|
+
const arg = keyArgument(name, msg.toolArgs, workspace, expanded, argBudget);
|
|
113
120
|
const verb = msg.pending ? 'Using' : 'Used';
|
|
114
121
|
let nameDisplay;
|
|
115
122
|
if (msg.pending) {
|
|
@@ -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.
|
|
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: '
|
|
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
|
|
159
|
-
//
|
|
160
|
-
|
|
161
|
-
|
|
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
|
-
|
|
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
|
-
//
|
|
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
|
-
//
|
|
424
|
-
//
|
|
425
|
-
// a
|
|
426
|
-
|
|
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).`;
|