@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.
- 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/toml.js +18 -4
- 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 +448 -1380
- 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
package/src/index.js
CHANGED
|
@@ -5,9 +5,112 @@ import path from 'node:path';
|
|
|
5
5
|
import fs from 'node:fs';
|
|
6
6
|
import { resolveConfig, effectiveSnapshot, saveConfig, resolveModelArg, readPersonalPrompt } from './config.js';
|
|
7
7
|
import * as sess from './session.js';
|
|
8
|
-
import { Agent, SYSTEM_PROMPT, THINKING_TAGS_INSTRUCTION,
|
|
8
|
+
import { Agent, SYSTEM_PROMPT, THINKING_TAGS_INSTRUCTION, PLAN_MODE_INSTRUCTION, needsThinkingTags } from './agent.js';
|
|
9
|
+
import { installGoalStore } from './tools/goal.js';
|
|
9
10
|
import { llmTools } from './tools/index.js';
|
|
11
|
+
import { isFailureResult } from './tool-status.js';
|
|
12
|
+
import { editDiffRows } from './diff.js';
|
|
10
13
|
import { localVersion } from './version.js';
|
|
14
|
+
import { decideApproval } from './permission-gate.js';
|
|
15
|
+
// The terminal's own status-line wording, so a window prints the same sentence in the same
|
|
16
|
+
// language instead of a second translation that can drift from it.
|
|
17
|
+
import { statusTallyText, setStatusLang } from './status-line.js';
|
|
18
|
+
|
|
19
|
+
import readline from 'node:readline';
|
|
20
|
+
|
|
21
|
+
// ---- the front-end protocol over stdio --------------------------------------
|
|
22
|
+
//
|
|
23
|
+
// A GUI has no terminal to draw a prompt on, so the three things that need an answer from a
|
|
24
|
+
// person travel as JSON lines: a request on stdout carrying an id, and one line back on stdin
|
|
25
|
+
// with the same id.
|
|
26
|
+
//
|
|
27
|
+
// approval-request {"id":"ap-…","name":"Bash","args":{…}} -> {"id":"ap-…","approved":true}
|
|
28
|
+
// question-request {"id":"q-…","questions":[…]} -> {"id":"q-…","answers":{…}}
|
|
29
|
+
// steer no request — {"type":"steer","text":"…"} injects a line mid-turn, so a
|
|
30
|
+
// person can correct a run heading the wrong way without stopping it.
|
|
31
|
+
//
|
|
32
|
+
// Every waiter is keyed by id, so a reply always reaches the request that asked for it.
|
|
33
|
+
const frontEndWaiters = new Map();
|
|
34
|
+
let frontEndReader = null;
|
|
35
|
+
|
|
36
|
+
/** Text injected by the front end, drained by the agent on its next model call. */
|
|
37
|
+
export const steerInbox = [];
|
|
38
|
+
// Set while a headless turn runs, so stdin can interrupt it gracefully.
|
|
39
|
+
let activeAgent = null;
|
|
40
|
+
|
|
41
|
+
function ensureFrontEndReader() {
|
|
42
|
+
if (frontEndReader) return frontEndReader;
|
|
43
|
+
frontEndReader = readline.createInterface({ input: process.stdin, terminal: false });
|
|
44
|
+
frontEndReader.on('line', (line) => {
|
|
45
|
+
let msg;
|
|
46
|
+
try { msg = JSON.parse(String(line).trim()); } catch { return; }
|
|
47
|
+
|
|
48
|
+
// A steer answers nothing, so it carries no id.
|
|
49
|
+
if (msg && msg.type === 'interrupt') {
|
|
50
|
+
try { if (activeAgent) activeAgent.interrupt(); } catch { /* already gone */ }
|
|
51
|
+
return;
|
|
52
|
+
}
|
|
53
|
+
if (msg && msg.type === 'steer' && typeof msg.text === 'string' && msg.text.trim()) {
|
|
54
|
+
steerInbox.push(msg.text.trim());
|
|
55
|
+
return;
|
|
56
|
+
}
|
|
57
|
+
// STDIN TO A FOREGROUND COMMAND. The terminal points its composer at the running process with Ctrl+G; the window sends
|
|
58
|
+
// this message for the same toggle. The process lives on the agent's ctx, placed there by
|
|
59
|
+
// the Bash tool.
|
|
60
|
+
if (msg && msg.type === 'stdin' && typeof msg.text === 'string') {
|
|
61
|
+
const fg = activeAgent && activeAgent.ctx && activeAgent.ctx._foreground;
|
|
62
|
+
// The Bash tool's own writer: it checks the child is still writable and swallows a
|
|
63
|
+
// write to a dead pipe, which a direct stdin write would throw on.
|
|
64
|
+
try { if (fg && typeof fg.write === 'function') fg.write(msg.text + '\n'); } catch { /* gone */ }
|
|
65
|
+
return;
|
|
66
|
+
}
|
|
67
|
+
// BACKGROUND A FOREGROUND COMMAND — the terminal's Ctrl+B. The Bash tool hangs a `detach`
|
|
68
|
+
// hook on the foreground holder when a detach is possible; invoking it moves the child to
|
|
69
|
+
// the task list and the turn continues without it.
|
|
70
|
+
// THE GOAL OF A RUNNING TURN. The window writes the session record, but the child holds its
|
|
71
|
+
// own copy and would overwrite the file at its next save — so a /goal typed mid-turn would
|
|
72
|
+
// survive the window and vanish from the run. This reaches the live copy instead.
|
|
73
|
+
const isGoalMsg = msg && msg.type === 'goal' && (typeof msg.goal === 'string' || typeof msg.paused === 'boolean');
|
|
74
|
+
if (isGoalMsg) {
|
|
75
|
+
try {
|
|
76
|
+
if (saved) {
|
|
77
|
+
if (typeof msg.goal === 'string') saved.objective = msg.goal;
|
|
78
|
+
if (typeof msg.owner === 'string') saved.goalOwner = msg.owner === 'user' ? 'user' : 'agent';
|
|
79
|
+
if (typeof msg.paused === 'boolean') saved.goalPaused = msg.paused;
|
|
80
|
+
}
|
|
81
|
+
} catch { /* a goal that cannot be stored must not stop the turn */ }
|
|
82
|
+
return;
|
|
83
|
+
}
|
|
84
|
+
if (msg && msg.type === 'background') {
|
|
85
|
+
const fg = activeAgent && activeAgent.ctx && activeAgent.ctx._foreground;
|
|
86
|
+
try { if (fg && typeof fg.detach === 'function') fg.detach(); } catch { /* already gone */ }
|
|
87
|
+
return;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
if (!msg || typeof msg.id !== 'string') return;
|
|
92
|
+
const wait = frontEndWaiters.get(msg.id);
|
|
93
|
+
if (!wait) return;
|
|
94
|
+
frontEndWaiters.delete(msg.id);
|
|
95
|
+
clearTimeout(wait.timer);
|
|
96
|
+
// The payload depends on what was asked: an approval is a boolean, a question a map.
|
|
97
|
+
wait.resolve(wait.kind === 'question' ? (msg.answers || {}) : msg.approved === true);
|
|
98
|
+
});
|
|
99
|
+
return frontEndReader;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function waitForFrontEnd(id, kind, timeoutMs) {
|
|
103
|
+
ensureFrontEndReader();
|
|
104
|
+
return new Promise((resolve) => {
|
|
105
|
+
const timer = setTimeout(() => { frontEndWaiters.delete(id); resolve(null); }, timeoutMs);
|
|
106
|
+
if (timer.unref) timer.unref();
|
|
107
|
+
frontEndWaiters.set(id, { resolve, timer, kind });
|
|
108
|
+
});
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
const readApproval = (id, ms = 5 * 60_000) => waitForFrontEnd(id, "approval", ms);
|
|
112
|
+
const readAnswers = (id, ms = 30 * 60_000) => waitForFrontEnd(id, "question", ms);
|
|
113
|
+
|
|
11
114
|
import { EXIT, FORMATS, isValidFormat, buildResult, exitCodeFor, resultLine, createRunTracker, trackEvent, finalReply } from './ci.js';
|
|
12
115
|
|
|
13
116
|
// The version shown by `hncode -V` and the help banner. Read from package.json
|
|
@@ -29,6 +132,8 @@ Options:
|
|
|
29
132
|
--auto Auto mode: never ask; everything runs automatically.
|
|
30
133
|
-m, --model <model> Model alias to use for this invocation.
|
|
31
134
|
-p, --prompt <prompt> Run one prompt non-interactively and print the reply.
|
|
135
|
+
--prompt-file <path> Read the prompt from a file (no command-line length limit).
|
|
136
|
+
--image <path> Attach an image to the prompt; repeatable.
|
|
32
137
|
--output-format <format> Prompt mode output: text (default), json, or stream-json.
|
|
33
138
|
json prints one result object; stream-json streams events then a result.
|
|
34
139
|
Exit code reflects the outcome: 0 ok, 1 failure, 2 config, 3 no answer, 4 interrupted.
|
|
@@ -36,9 +141,6 @@ Options:
|
|
|
36
141
|
--timeout <seconds> Prompt mode: abort the run after this many seconds (default: no limit).
|
|
37
142
|
--retries <n> Prompt mode: HTTP retries per request before failing (default: 3).
|
|
38
143
|
--control <path> Same, at an explicit socket path.
|
|
39
|
-
--web Serve this session to a browser on 127.0.0.1 (random port).
|
|
40
|
-
--web [ip][:port] Same, on a chosen address/port (e.g. --web 0.0.0.0:8080).
|
|
41
|
-
--plan Start in plan mode (research only, no writes).
|
|
42
144
|
--plan Start in plan mode (research only, no writes).
|
|
43
145
|
--add-dir <dir> Add an additional workspace directory. Repeatable.
|
|
44
146
|
-h, --help Show help.
|
|
@@ -74,11 +176,11 @@ export function parseArgs(argv) {
|
|
|
74
176
|
if (eq >= 0) { key = a.slice(2, eq); val = a.slice(eq + 1); }
|
|
75
177
|
else { key = a.slice(2); val = null; }
|
|
76
178
|
if (key === 'resume') key = 'session'; // `--resume <id>` is an alias for `--session <id>`
|
|
77
|
-
if (['session', 'control'
|
|
179
|
+
if (['session', 'control'].includes(key) && val === null) { const nx = argv[i + 1]; out[key] = nx !== undefined && !nx.startsWith('-') ? (i++, nx) : true; }
|
|
78
180
|
// FLAGS THAT TAKE A VALUE. `--workspace` and `--index` are here for `hncode restore`: without them the path was
|
|
79
181
|
// left in `positional` and the flag itself became `true`, so the restore would have repointed every session at the
|
|
80
182
|
// string "true".
|
|
81
|
-
else if (key === 'model' || key === 'prompt' || key === 'output-format' || key === 'add-dir' || key === 'timeout' || key === 'retries' || key === 'workspace' || key === 'index') {
|
|
183
|
+
else if (key === 'model' || key === 'prompt' || key === 'image' || key === 'prompt-file' || key === 'output-format' || key === 'add-dir' || key === 'timeout' || key === 'retries' || key === 'workspace' || key === 'index') {
|
|
82
184
|
if (val === null) {
|
|
83
185
|
const nx = argv[i + 1];
|
|
84
186
|
// Only consume the next token if it is a real value, not another flag
|
|
@@ -86,7 +188,7 @@ else if (key === 'model' || key === 'prompt' || key === 'output-format' || key =
|
|
|
86
188
|
// swallowed or mangled the value, breaking the real flag.
|
|
87
189
|
val = (nx !== undefined && !nx.startsWith('-')) ? argv[++i] : undefined;
|
|
88
190
|
}
|
|
89
|
-
out[key] = (key === 'add-dir' && val !== undefined)
|
|
191
|
+
out[key] = ((key === 'add-dir' || key === 'image') && val !== undefined)
|
|
90
192
|
? (out[key] || []).concat([val])
|
|
91
193
|
: val;
|
|
92
194
|
} else if (val !== null) { out[key] = val === 'true' ? true : val === 'false' ? false : val; }
|
|
@@ -112,8 +214,15 @@ if (key === 'S' || key === 'm' || key === 'p') {
|
|
|
112
214
|
}
|
|
113
215
|
|
|
114
216
|
// ---- subcommands ----
|
|
115
|
-
function cmdSessionList(args) {
|
|
217
|
+
function cmdSessionList(_rest, args) {
|
|
116
218
|
const items = sess.listSessions();
|
|
219
|
+
// A front end gets the whole list in one structured call, using the same cheap meta
|
|
220
|
+
// scan the text list already uses. Thirty printed rows forced a desktop to either
|
|
221
|
+
// truncate the rail or reimplement the scan over thousands of transcript files.
|
|
222
|
+
if (args && args.json) {
|
|
223
|
+
process.stdout.write(JSON.stringify(items) + '\n');
|
|
224
|
+
return 0;
|
|
225
|
+
}
|
|
117
226
|
if (items.length === 0) { console.log('No sessions yet.'); return 0; }
|
|
118
227
|
for (const s of items.slice(0, 30)) {
|
|
119
228
|
const when = new Date(s.updatedAt || 0).toISOString().slice(0, 19).replace('T', ' ');
|
|
@@ -450,8 +559,27 @@ const SUBCOMMANDS = {
|
|
|
450
559
|
'prompt': (rest) => cmdControl('prompt', rest),
|
|
451
560
|
'interrupt': (rest) => cmdControl('interrupt', rest),
|
|
452
561
|
},
|
|
562
|
+
// THE RESIDENT SERVER A FRONT END TALKS TO.
|
|
563
|
+
//
|
|
564
|
+
// Not a subcommand table: `serve` takes no verb, it either runs or it does not. A front end
|
|
565
|
+
// connects to the socket and stays connected; see src/serve.js and src/protocol.js.
|
|
566
|
+
'serve': { run: cmdServe },
|
|
453
567
|
};
|
|
454
568
|
|
|
569
|
+
/**
|
|
570
|
+
* Run the resident server until the process is stopped.
|
|
571
|
+
*
|
|
572
|
+
* It stays in the foreground on purpose: a server that daemonised would need a pid file, a
|
|
573
|
+
* readiness handshake and an orphan sweeper, and the only thing it would buy is that a terminal
|
|
574
|
+
* could be closed. The desktop starts it as a child and keeps it for the window's lifetime.
|
|
575
|
+
*/
|
|
576
|
+
async function cmdServe() {
|
|
577
|
+
const { serve } = await import('./serve.js');
|
|
578
|
+
await serve();
|
|
579
|
+
// `serve` resolves once listening; the process stays up because the server holds the loop.
|
|
580
|
+
return new Promise(() => {});
|
|
581
|
+
}
|
|
582
|
+
|
|
455
583
|
// ---- control (talk to a running --control session) --------------------------
|
|
456
584
|
// `hncode control status|prompt|interrupt` — the client half of the control
|
|
457
585
|
// socket the TUI opens with --control. Prints the JSON reply so a script can
|
|
@@ -475,8 +603,12 @@ async function cmdControl(sub, arg) {
|
|
|
475
603
|
}
|
|
476
604
|
|
|
477
605
|
// ---- headless prompt mode ----
|
|
478
|
-
async function runPrompt({ cfg, prompt, format, session, modelArg, timeoutSeconds, maxRetries }) {
|
|
606
|
+
async function runPrompt({ cfg, prompt, format, session, modelArg, timeoutSeconds, maxRetries, images, frontEnd = false, permissionMode = 'ask' }) {
|
|
479
607
|
cfg = resolveModelArg(cfg, modelArg);
|
|
608
|
+
// THE STATUS LINE SPEAKS THE SESSION'S LANGUAGE. `statusTallyText` builds the words a window
|
|
609
|
+
// prints, and it reads the same `lang` the terminal does — otherwise an English window beside a
|
|
610
|
+
// Chinese terminal would be showing two languages for one conversation.
|
|
611
|
+
try { setStatusLang(cfg.lang); } catch { /* an unknown language falls back to English */ }
|
|
480
612
|
if (maxRetries !== undefined) cfg.maxRetries = maxRetries;
|
|
481
613
|
if (!cfg.apiKey) {
|
|
482
614
|
console.error('hncode: no api_key configured. Set HNCODE_API_KEY or configure a provider first. Run `hncode doctor config` to check.');
|
|
@@ -489,28 +621,82 @@ async function runPrompt({ cfg, prompt, format, session, modelArg, timeoutSecond
|
|
|
489
621
|
// The inline-reasoning instruction, only for a model with no reasoning channel of its
|
|
490
622
|
// own — the same rule the TUI applies (see needsThinkingTags).
|
|
491
623
|
if (needsThinkingTags(cfg)) sysText += '\n\n' + THINKING_TAGS_INSTRUCTION;
|
|
624
|
+
// PLAN MODE: the SAME two halves the terminal applies — the instruction that asks for a plan
|
|
625
|
+
// block, and the tool filter that removes the ability to make the changes first. The filter
|
|
626
|
+
// alone leaves the model writing prose about a plan nobody can approve; the instruction alone
|
|
627
|
+
// leaves it free to edit.
|
|
628
|
+
if (cfg.plan) {
|
|
629
|
+
sysText += '\n\n' + PLAN_MODE_INSTRUCTION;
|
|
630
|
+
if (cfg.planInstructions && String(cfg.planInstructions).trim()) {
|
|
631
|
+
sysText += '\n\n' + String(cfg.planInstructions).trim();
|
|
632
|
+
}
|
|
633
|
+
// Read-only tools only. `undefined` would mean "every tool", so an empty filter is not
|
|
634
|
+
// an option here.
|
|
635
|
+
cfg.toolFilter = ['Read', 'Grep', 'Glob'];
|
|
636
|
+
}
|
|
492
637
|
const personal = readPersonalPrompt(cfg.workspace);
|
|
493
638
|
if (personal) sysText += '\n\n' + personal;
|
|
494
639
|
messages.push({ role: 'system', content: sysText });
|
|
495
640
|
if (session && session.messages) {
|
|
496
|
-
//
|
|
497
|
-
//
|
|
498
|
-
//
|
|
499
|
-
//
|
|
500
|
-
//
|
|
641
|
+
// THE WHOLE HISTORY, the same one the terminal hands its Agent.
|
|
642
|
+
//
|
|
643
|
+
// This used to take only the last 30 messages. That number came from nowhere and it was
|
|
644
|
+
// WRONG in both directions: it silently dropped 700 messages of context the window was
|
|
645
|
+
// nowhere near full of, and it could not help a session that was actually too big, because
|
|
646
|
+
// the one oversized result that made it too big was still inside the 30. Deciding how much
|
|
647
|
+
// history fits is the agent's job — it measures the window and compacts at a threshold —
|
|
648
|
+
// and a second, smaller cap here only made the two disagree.
|
|
649
|
+
//
|
|
650
|
+
// System messages are dropped: the fresh one above is authoritative.
|
|
501
651
|
const hist = session.messages.filter((m) => m && m.role !== 'system');
|
|
502
|
-
// A session persisted mid-step can end with an assistant message whose tool
|
|
503
|
-
//
|
|
652
|
+
// A session persisted mid-step can end with an assistant message whose tool results were
|
|
653
|
+
// never appended; sending it before the user message is a 400.
|
|
504
654
|
while (hist.length && hist[hist.length - 1].role === 'assistant'
|
|
505
655
|
&& Array.isArray(hist[hist.length - 1].toolCalls) && hist[hist.length - 1].toolCalls.length) hist.pop();
|
|
506
|
-
|
|
507
|
-
while (start > 0 && !canSplitAfter(hist, start - 1)) start++;
|
|
508
|
-
for (let i = start; i < hist.length; i++) messages.push(hist[i]);
|
|
656
|
+
for (const m of hist) messages.push(m);
|
|
509
657
|
}
|
|
510
658
|
// THE PROMPT ITSELF. This used to never be pushed: -p sent only the resumed
|
|
511
659
|
// history and the system message, so a fresh session answered nothing the
|
|
512
660
|
// user asked and a resumed one answered nothing new.
|
|
513
|
-
|
|
661
|
+
// IMAGES TRAVEL AS STRUCTURED PARTS, not as paths in the text. A pasted screenshot has no path
|
|
662
|
+
// the model can open, and a path to a PNG only helps if the model thinks to call ReadMediaFile;
|
|
663
|
+
// an attachment is what the provider expects and what the window means by pasting one.
|
|
664
|
+
const imageParts = Array.isArray(images) ? images : [];
|
|
665
|
+
if (imageParts.length) {
|
|
666
|
+
messages.push({
|
|
667
|
+
role: 'user',
|
|
668
|
+
content: [
|
|
669
|
+
{ type: 'text', text: prompt },
|
|
670
|
+
...imageParts.map((m) => ({ type: 'image', mimeType: m.mimeType || 'image/png', data: m.data })),
|
|
671
|
+
],
|
|
672
|
+
});
|
|
673
|
+
} else {
|
|
674
|
+
messages.push({ role: 'user', content: prompt });
|
|
675
|
+
}
|
|
676
|
+
// THE CLOCK, AS PART OF THE REQUEST AND NOT OF THE CONVERSATION.
|
|
677
|
+
//
|
|
678
|
+
// A model has no clock of its own, so the current local time rides along with the turn:
|
|
679
|
+
// "yesterday", "this morning" and "run it at nine" are unanswerable without it. It is a SYSTEM
|
|
680
|
+
// message, which is the difference between a note about the turn and something the person said —
|
|
681
|
+
// as a user message it was drawn in the transcript as the person's words and the model quoted
|
|
682
|
+
// it back. It can be turned off: the stamp carries the machine's zone, which is a fingerprint
|
|
683
|
+
// as well as a convenience.
|
|
684
|
+
if (cfg.injectTime !== false) {
|
|
685
|
+
const { timeStamp } = await import('./agent.js');
|
|
686
|
+
// APPENDED TO THE USER'S OWN MESSAGE, in the tagged form harnesses use for environment
|
|
687
|
+
// facts. A system message between the user's line and the request reads as a fresh
|
|
688
|
+
// instruction, and the model answers it instead of the question.
|
|
689
|
+
const last = messages.length - 1;
|
|
690
|
+
if (last >= 0 && messages[last] && messages[last].role === 'user') {
|
|
691
|
+
const m = messages[last];
|
|
692
|
+
if (typeof m.content === 'string') {
|
|
693
|
+
messages[last] = { ...m, content: `${m.content}\n\n<env>Current time: ${timeStamp()}</env>` };
|
|
694
|
+
} else if (Array.isArray(m.content)) {
|
|
695
|
+
// An image message carries structured parts; the clock becomes one more text part.
|
|
696
|
+
messages[last] = { ...m, content: [...m.content, { type: 'text', text: `<env>Current time: ${timeStamp()}</env>` }] };
|
|
697
|
+
}
|
|
698
|
+
}
|
|
699
|
+
}
|
|
514
700
|
if (session && session._unrecoverable) {
|
|
515
701
|
process.stderr.write(
|
|
516
702
|
`hncode: session ${session.id} has no readable history (its file is damaged). `
|
|
@@ -518,27 +704,165 @@ async function runPrompt({ cfg, prompt, format, session, modelArg, timeoutSecond
|
|
|
518
704
|
);
|
|
519
705
|
session = null;
|
|
520
706
|
}
|
|
521
|
-
const saved = session || { id: sess.newId(), title:
|
|
707
|
+
const saved = session || { id: sess.newId(), title: sess.titleFromPrompt(prompt), workspace: path.resolve(process.cwd()), model: cfg.model, createdAt: Date.now(), messages: [] };
|
|
708
|
+
// THE ARRAY THE SESSION SAVES IS THE ONE THE AGENT APPENDS TO.
|
|
709
|
+
//
|
|
710
|
+
// `saved.messages` used to keep whatever the session file held, because nothing ever pointed
|
|
711
|
+
// it at the array this run builds. Every headless turn therefore wrote the OLD transcript back
|
|
712
|
+
// over the file at the end: the reply was printed and then lost, and the next `--continue`
|
|
713
|
+
// resumed a conversation that never contained it.
|
|
714
|
+
// THE CLOCK IS NOT PART OF THE CONVERSATION. It was pushed into the request as a system
|
|
715
|
+
// message, and saving the array as it stood kept it: every later turn would replay a time
|
|
716
|
+
// that had already passed, and the transcript would show a clock nobody typed.
|
|
717
|
+
// TWO THINGS TO REMOVE, and they are removed for the same reason: neither is part of the
|
|
718
|
+
// conversation. `_timestamp` was a message of its own; the env block is text appended to the
|
|
719
|
+
// user's line on the way out. Saving either replays a passed moment on every later turn.
|
|
720
|
+
const { stripEnvBlock } = await import('./agent.js');
|
|
721
|
+
saved.messages = messages
|
|
722
|
+
.filter((m) => !m || !m._timestamp)
|
|
723
|
+
.map((m) => (m && m.role === 'user' && typeof m.content === 'string'
|
|
724
|
+
? { ...m, content: stripEnvBlock(m.content) }
|
|
725
|
+
: m));
|
|
522
726
|
const tracker = createRunTracker();
|
|
523
727
|
const startedAt = Date.now();
|
|
524
728
|
let fatal = null;
|
|
729
|
+
|
|
730
|
+
// ASKUSERQUESTION OVER STDIO. The tool calls `cfg.askQuestion(questions, ctx)` and blocks
|
|
731
|
+
// until it resolves; without this callback it fails with a message telling the model to ask in
|
|
732
|
+
// plain text, which a GUI could not render as choices either. Same request/reply shape as an
|
|
733
|
+
// approval, carrying the questions rather than a tool name.
|
|
734
|
+
if (frontEnd) {
|
|
735
|
+
cfg.askQuestion = async (questions) => {
|
|
736
|
+
const id = `q-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 7)}`;
|
|
737
|
+
process.stdout.write(JSON.stringify({ type: 'question-request', id, questions }) + '\n');
|
|
738
|
+
const answers = await readAnswers(id);
|
|
739
|
+
// The tool reads `result.answers`, so the map has to be wrapped — returning the bare map
|
|
740
|
+
// made every answer look like a dismissal. A dismissed question stays an empty map, never
|
|
741
|
+
// a vote for the first option.
|
|
742
|
+
return { answers: answers || {} };
|
|
743
|
+
};
|
|
744
|
+
}
|
|
745
|
+
|
|
746
|
+
// THE TWO NUMBERS THE STATUS LINE NEEDS, counted here because only this event stream sees them.
|
|
747
|
+
// `stepCount` is model rounds in THIS run. `tokTimes` holds one arrival timestamp per output
|
|
748
|
+
// token — the same measure the terminal's meter uses: a rate over the last couple of seconds,
|
|
749
|
+
// not an average since the run began, because an average says what the run did rather than
|
|
750
|
+
// whether it is moving now.
|
|
751
|
+
let stepCount = 0;
|
|
752
|
+
const tokTimes = [];
|
|
753
|
+
// The last rate MEASURED, kept so it survives the turn that produced it.
|
|
754
|
+
let lastTokRate = 0;
|
|
755
|
+
const RECENT_MS = 2000;
|
|
756
|
+
const recentTokRate = (times) => {
|
|
757
|
+
if (!times.length) return 0;
|
|
758
|
+
const now = Date.now();
|
|
759
|
+
while (times.length && now - times[0] > RECENT_MS) times.shift();
|
|
760
|
+
if (times.length < 2) return 0;
|
|
761
|
+
return times.length / (Math.max(1, now - times[0]) / 1000);
|
|
762
|
+
};
|
|
763
|
+
|
|
525
764
|
const agent = new Agent({
|
|
526
765
|
cfg,
|
|
527
766
|
messages,
|
|
767
|
+
// THE THREE THINGS THAT NEED A PERSON. Without a front end asking for them, headless runs
|
|
768
|
+
// keep their old behaviour: tools run approved, and AskUserQuestion fails with a message
|
|
769
|
+
// telling the model to ask in plain text instead of silently getting an empty answer.
|
|
770
|
+
onApproval: frontEnd ? async (toolName, args) => {
|
|
771
|
+
// THE MODE IS A DECISION, NOT A PROMPT. `ask` vs `yolo` vs `auto` is answered by the same
|
|
772
|
+
// module the terminal uses, so the two front ends cannot disagree about what runs unattended.
|
|
773
|
+
const verdict = decideApproval({ mode: permissionMode, toolName, args, rules: cfg.permissions });
|
|
774
|
+
if (verdict === 'allow') return true;
|
|
775
|
+
if (verdict === 'deny') return false;
|
|
776
|
+
const id = `ap-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 7)}`;
|
|
777
|
+
process.stdout.write(JSON.stringify({ type: 'approval-request', id, name: toolName, args }) + '\n');
|
|
778
|
+
const approved = await readApproval(id);
|
|
779
|
+
if (approved === null) return false;
|
|
780
|
+
return approved;
|
|
781
|
+
} : undefined,
|
|
528
782
|
// Uncapped: run until the model finishes (see agent.js).
|
|
529
783
|
onEvent: (e) => {
|
|
530
784
|
trackEvent(tracker, e);
|
|
531
785
|
if (e.type === 'error') fatal = (e.error && e.error.message) || String(e.error);
|
|
786
|
+
// THE METER FOLLOWS WHAT STREAMS. `step_start` opens a round; `data` and `think` chunks are
|
|
787
|
+
// output tokens (reasoning is output too, and counting only prose made a thinking model
|
|
788
|
+
// report zero while it was working). The timestamps are pruned by `recentTokRate`.
|
|
789
|
+
if (e.type === 'step_start') stepCount += 1;
|
|
790
|
+
if ((e.type === 'data' || e.type === 'think') && e.text) {
|
|
791
|
+
const n = Math.max(1, Math.min(64, Math.ceil(String(e.text).length / 4)));
|
|
792
|
+
for (let i = 0; i < n; i++) tokTimes.push(Date.now());
|
|
793
|
+
}
|
|
532
794
|
if (format === 'stream-json' || format === 'json') {
|
|
533
795
|
// `json` mode keeps stdout clean for the final envelope, so events go to
|
|
534
796
|
// stderr there. `stream-json` is the streaming contract: one event/line.
|
|
535
797
|
if (format === 'stream-json') {
|
|
536
|
-
if (e.type === 'context') return; // TUI-only gauge; not part of the stream
|
|
537
798
|
const line = { type: e.type };
|
|
799
|
+
// THE CONTEXT GAUGE IS PART OF THE STREAM NOW.
|
|
800
|
+
//
|
|
801
|
+
// It used to be dropped as a TUI-only display detail, which meant a GUI had no way to
|
|
802
|
+
// show how full the window was — the one number a long session most needs. It carries
|
|
803
|
+
// two integers and goes out at most once per model call.
|
|
804
|
+
if (e.type === 'context') { line.tokens = e.tokens; line.max = e.max; line.breakdown = e.breakdown; }
|
|
538
805
|
if (e.text) line.text = e.text;
|
|
539
806
|
if (e.name) line.name = e.name;
|
|
807
|
+
if (e.args) line.args = e.args;
|
|
540
808
|
if (e.id) line.id = e.id;
|
|
541
809
|
if (e.content != null) line.content = e.content;
|
|
810
|
+
// The edit diff is what a window renders; without it the tool card shows only a summary.
|
|
811
|
+
// The LINE COUNTS come from the same differ that draws them, so the card's +N/-M is the
|
|
812
|
+
// real change rather than a count of every old line against every new one.
|
|
813
|
+
if (e.editDiff) {
|
|
814
|
+
line.editDiff = e.editDiff;
|
|
815
|
+
try {
|
|
816
|
+
const rows = editDiffRows(e.editDiff);
|
|
817
|
+
let add = 0;
|
|
818
|
+
let del = 0;
|
|
819
|
+
for (const row of rows) { if (row.type === 'add') add++; else if (row.type === 'del') del++; }
|
|
820
|
+
line.editDiff.counts = { add, del };
|
|
821
|
+
} catch { /* a malformed diff still renders its raw text */ }
|
|
822
|
+
}
|
|
823
|
+
// Whether this call FAILED, decided once here by the same predicate the terminal uses.
|
|
824
|
+
// A window that re-guesses from the text gets the list subtly wrong (a refused edit
|
|
825
|
+
// rendered as a success), so the answer travels with the event instead.
|
|
826
|
+
if (e.type === 'tool_result') {
|
|
827
|
+
const text = e.content != null ? e.content : e.text;
|
|
828
|
+
line.failed = isFailureResult(text, e.name);
|
|
829
|
+
}
|
|
830
|
+
if (e.spilled) line.spilled = e.spilled;
|
|
831
|
+
if (e.media) line.media = e.media;
|
|
832
|
+
// THE STATUS LINE IS WRITTEN ONCE, IN THE TERMINAL'S OWN WORDS.
|
|
833
|
+
//
|
|
834
|
+
// A window has no tok/s meter and no step counter of its own, and re-deriving them here
|
|
835
|
+
// would mean a second translation of "3 turns | 12 steps | 41 tok/s" that could disagree
|
|
836
|
+
// with the terminal's. `statusTallyText` builds the sentence through the i18n table, so
|
|
837
|
+
// it arrives already in the user's language and both front ends print the same thing.
|
|
838
|
+
// Two events carry it because they are the two moments the numbers change: a new step
|
|
839
|
+
// and a new usage report.
|
|
840
|
+
if (e.type === 'step_start' || e.type === 'usage') {
|
|
841
|
+
// THE LAST MEASUREMENT SURVIVES THE TURN, the same as the terminal. The window is
|
|
842
|
+
// pruned as it goes, so the final events of a turn reported nothing and the figure
|
|
843
|
+
// vanished exactly when the turn finished.
|
|
844
|
+
try {
|
|
845
|
+
const rate = recentTokRate(tokTimes);
|
|
846
|
+
if (rate > 0) lastTokRate = rate;
|
|
847
|
+
line.status = statusTallyText({ rounds: saved.rounds || 0, steps: stepCount, tokRate: lastTokRate });
|
|
848
|
+
}
|
|
849
|
+
catch { /* a missing figure must not drop the event */ }
|
|
850
|
+
}
|
|
851
|
+
// Status events carry their data in event-specific fields. Forwarding only the
|
|
852
|
+
// type made the desktop's todo list, usage panel and compaction notices empty.
|
|
853
|
+
for (const key of [
|
|
854
|
+
'todos', 'usage', 'total', 'before', 'after', 'kept', 'dropped', 'keep', 'elided',
|
|
855
|
+
'elidedBytes', 'keptBytes', 'attempt', 'reason', 'round', 'waiting',
|
|
856
|
+
// THE CONTEXT EVENT CARRIES THREE FIELDS, and all three are needed: `tokens` and
|
|
857
|
+
// `max` drive the desktop's gauge (which HIDES ITSELF when max is unknown, so a
|
|
858
|
+
// stripped `max` meant the ring never appeared at all), and `breakdown` is the
|
|
859
|
+
// per-category split its panel shows. The same omission left the stats panel
|
|
860
|
+
// printing a bare "— / ?" for the context row.
|
|
861
|
+
'tokens', 'max', 'breakdown',
|
|
862
|
+
'sessionId', 'error', 'chunk',
|
|
863
|
+
]) {
|
|
864
|
+
if (e[key] !== undefined) line[key] = e[key];
|
|
865
|
+
}
|
|
542
866
|
process.stdout.write(JSON.stringify(line) + '\n');
|
|
543
867
|
}
|
|
544
868
|
} else if (e.type === 'data') {
|
|
@@ -546,32 +870,181 @@ async function runPrompt({ cfg, prompt, format, session, modelArg, timeoutSecond
|
|
|
546
870
|
}
|
|
547
871
|
},
|
|
548
872
|
});
|
|
549
|
-
|
|
550
|
-
//
|
|
551
|
-
//
|
|
552
|
-
//
|
|
553
|
-
//
|
|
554
|
-
//
|
|
873
|
+
activeAgent = agent;
|
|
874
|
+
// THE GOAL TOOL HAS TO WORK HEADLESS. Its store lives in the TUI, so without an install here
|
|
875
|
+
// the desktop's Goal calls read and wrote an empty default: `status` always answered "No goal
|
|
876
|
+
// is set", `set` looked like it worked and nothing was stored, and the desktop could never see
|
|
877
|
+
// an objective the agent gave itself. The session record owns the field — it is what a resume
|
|
878
|
+
// reads back — and a set or clear is saved immediately so the value outlives this process.
|
|
879
|
+
installGoalStore({
|
|
880
|
+
get: () => String(saved.objective || ''),
|
|
881
|
+
set: (goal, owner) => {
|
|
882
|
+
saved.objective = String(goal || '');
|
|
883
|
+
saved.goalOwner = owner === 'user' ? 'user' : 'agent';
|
|
884
|
+
try { sess.saveSession(saved); } catch { /* best-effort */ }
|
|
885
|
+
// THE DESKTOP CANNOT SEE THE SESSION RECORD DIRECTLY, so the change is announced: the
|
|
886
|
+
// window shows the objective the agent is working towards the same way it shows todos.
|
|
887
|
+
process.stdout.write(JSON.stringify({ type: 'goal', goal: saved.objective, owner: saved.goalOwner }) + '\n');
|
|
888
|
+
},
|
|
889
|
+
owner: () => saved.goalOwner || 'agent',
|
|
890
|
+
});
|
|
891
|
+
// STEERING. A line typed while the turn runs lands here instead of stopping the run, and is
|
|
892
|
+
// handed to the agent before its next model call. The poll is what makes it work at all in a
|
|
893
|
+
// headless run: nothing else is reading stdin once a tool is executing.
|
|
894
|
+
const steerTimer = setInterval(() => {
|
|
895
|
+
while (steerInbox.length) {
|
|
896
|
+
const text = steerInbox.shift();
|
|
897
|
+
try { agent.steer(text); } catch { /* an agent that cannot steer simply ignores it */ }
|
|
898
|
+
}
|
|
899
|
+
}, 120);
|
|
900
|
+
if (steerTimer.unref) steerTimer.unref();
|
|
901
|
+
// `--timeout <seconds>`: a wall-clock cap on each turn, so an unattended scripted prompt
|
|
902
|
+
// cannot hang forever on a stuck model or a wedged tool. The timer calls the SAME
|
|
903
|
+
// interrupt() the TUI's Esc uses — it aborts the in-flight request and kills the tool's
|
|
904
|
+
// AbortSignal — rather than process.exit, so the session is still saved and the output is
|
|
905
|
+
// emitted.
|
|
555
906
|
let timedOut = false;
|
|
556
907
|
let timer = null;
|
|
557
|
-
|
|
908
|
+
// ARMED PER ROUND, not once for the run. The timer was cleared in the per-turn finally, so after
|
|
909
|
+
// the first round nothing could stop the run — and a goal that keeps restarting would then spend
|
|
910
|
+
// quota with no ceiling at all.
|
|
911
|
+
const armTimeout = () => {
|
|
912
|
+
if (!(timeoutSeconds > 0)) return;
|
|
558
913
|
timer = setTimeout(() => {
|
|
559
914
|
timedOut = true;
|
|
560
915
|
try { agent.interrupt(); } catch { /* best-effort */ }
|
|
561
916
|
}, timeoutSeconds * 1000);
|
|
562
917
|
if (timer.unref) timer.unref();
|
|
918
|
+
};
|
|
919
|
+
// THE GOAL LOOP, headless too.
|
|
920
|
+
//
|
|
921
|
+
// The terminal restarts a turn while an objective is set and unmet; this run did not, so a
|
|
922
|
+
// goal set from the desktop never continued past the first reply. The rules match the
|
|
923
|
+
// terminal's, for the same reasons: never after a failure (that re-spends quota on a request
|
|
924
|
+
// the endpoint refused), never after the user stopped it, never when a message is already
|
|
925
|
+
// queued (that IS the next turn).
|
|
926
|
+
// A CAP, because nobody is watching a headless run. The terminal's loop is bounded only by
|
|
927
|
+
// the user clearing the goal; here a model that never clears would spend quota unattended,
|
|
928
|
+
// so the run stops after this many restarts and leaves the objective set for inspection.
|
|
929
|
+
const GOAL_RESTART_CAP = 25;
|
|
930
|
+
let goalTurns = 0;
|
|
931
|
+
for (;;) {
|
|
932
|
+
armTimeout();
|
|
933
|
+
try {
|
|
934
|
+
await agent.run();
|
|
935
|
+
} finally {
|
|
936
|
+
if (timer) clearTimeout(timer);
|
|
937
|
+
}
|
|
938
|
+
const goalNow = String(saved.objective || '').trim();
|
|
939
|
+
const goalApplies = !!goalNow && !saved.goalPaused && !fatal
|
|
940
|
+
&& !agent.stopRequested && !timedOut && !steerInbox.length && goalTurns < GOAL_RESTART_CAP;
|
|
941
|
+
// GOAL PAUSED AFTER A FAILURE, and said out loud — the same rule the terminal applies.
|
|
942
|
+
// A refused request is not a finished one, and retrying it re-spends quota on the endpoint's
|
|
943
|
+
// own no; a silent stop afterwards reads as success when nothing was accomplished.
|
|
944
|
+
if (goalNow && !saved.goalPaused && fatal) {
|
|
945
|
+
saved.goalPaused = true;
|
|
946
|
+
process.stderr.write('hncode: goal not restarted — the turn failed. Fix the cause, then /goal resume.\n');
|
|
947
|
+
}
|
|
948
|
+
if (!goalApplies) break;
|
|
949
|
+
goalTurns++;
|
|
950
|
+
// Said out loud: a turn that restarts looks like one that never ended.
|
|
951
|
+
if (format === 'stream-json') {
|
|
952
|
+
process.stdout.write(JSON.stringify({ type: 'goal', goal: goalNow, owner: saved.goalOwner || 'agent', round: goalTurns }) + '\n');
|
|
953
|
+
}
|
|
954
|
+
// `agent.messages` IS this array, so the next model call sees the new message.
|
|
955
|
+
messages.push({
|
|
956
|
+
role: 'user',
|
|
957
|
+
content: [
|
|
958
|
+
'You have an active goal and the turn ended before it was reached.',
|
|
959
|
+
`Goal: ${goalNow}`,
|
|
960
|
+
'',
|
|
961
|
+
'Continue working on it. When the goal is fully met, call the Goal tool with action "clear" so the loop stops; if it is still not met, keep going.',
|
|
962
|
+
].join('\n'),
|
|
963
|
+
});
|
|
563
964
|
}
|
|
965
|
+
// THE STEER POLL OUTLIVES A TURN, NOT THE RUN. It stopped with the first turn, so every
|
|
966
|
+
// later round of the goal loop accepted a steer into an inbox nothing was reading.
|
|
967
|
+
clearInterval(steerTimer);
|
|
968
|
+
// MCP stdio children were spawned for this run; kill them now it is over.
|
|
564
969
|
try {
|
|
565
|
-
await
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
970
|
+
const mcp = await import('./mcp.js');
|
|
971
|
+
mcp.disconnectAll(mcp.getLiveConnections());
|
|
972
|
+
} catch { /* best-effort */ }
|
|
973
|
+
// THE COST AND USAGE TRAVEL WITH THE SESSION.
|
|
974
|
+
//
|
|
975
|
+
// The agent accumulates them for the run and nothing wrote them down, so the window's stats
|
|
976
|
+
// panel and cost row read zeros for every headless session — the numbers existed and were
|
|
977
|
+
// discarded. This is written once, after the loop, so a goal that continued counts as ONE
|
|
978
|
+
// round of the conversation — which is what the user started.
|
|
979
|
+
//
|
|
980
|
+
// THE TODO LIST IS SESSION STATE TOO. The terminal keeps it on `session.todos` and restores its
|
|
981
|
+
// panel from there; a headless run kept it only in memory, so the window's panel was filled by
|
|
982
|
+
// the live `todos` event during a turn and then read as empty the moment the conversation was
|
|
983
|
+
// reopened — the plan vanished exactly when someone came back to look at it.
|
|
984
|
+
if (Array.isArray(agent.ctx && agent.ctx.todoState)) saved.todos = agent.ctx.todoState.slice();
|
|
985
|
+
if (agent.usage && typeof agent.usage === 'object') saved.usage = agent.usage;
|
|
986
|
+
// THE LIMIT TOO, not just the count. `ctxTokens` alone is a numerator with no denominator: the
|
|
987
|
+
// window's ring hides itself when the cap is 0, so every session opened from the rail had no
|
|
988
|
+
// gauge at all — the one figure that makes the count mean anything was never stored.
|
|
989
|
+
const storedMax = Number(cfg.maxContextTokens) || Number(saved.ctxMax) || 0;
|
|
990
|
+
if (storedMax > 0) saved.ctxMax = storedMax;
|
|
991
|
+
if (Number.isFinite(agent.ctxReportedTokens) && agent.ctxReportedTokens > 0) {
|
|
992
|
+
saved.ctxTokens = agent.ctxReportedTokens;
|
|
993
|
+
saved.ctxReportedOnce = true;
|
|
994
|
+
}
|
|
995
|
+
// THE BREAKDOWN TRAVELS WITH THE SESSION TOO. Without it the window's context panel had nothing
|
|
996
|
+
// to draw for any conversation that was not mid-turn — the numbers were computed at every step
|
|
997
|
+
// and dropped when the process exited.
|
|
998
|
+
if (agent.ctxBreakdown && typeof agent.ctxBreakdown === 'object') saved.ctxBreakdown = agent.ctxBreakdown;
|
|
999
|
+
saved.rounds = (Number(saved.rounds) || 0) + 1;
|
|
1000
|
+
saved.lastTurnMs = Date.now() - startedAt;
|
|
1001
|
+
// THE RATE SURVIVES THE TURN. It was computed only while tokens were arriving, so the status
|
|
1002
|
+
// row lost `N tok/s` the moment a turn ended and the reader could never see how fast it had
|
|
1003
|
+
// gone. Recording it with the session is what lets both front ends print it afterwards.
|
|
1004
|
+
//
|
|
1005
|
+
// THE WHOLE TURN, NOT THE LAST FEW SECONDS. `recentTokRate` prunes its window as it goes, so by
|
|
1006
|
+
// the time a turn ends the window can be empty — it would report nothing for the turn that just
|
|
1007
|
+
// finished. The average over the turn is also the figure a reader means by "how fast did that
|
|
1008
|
+
// go".
|
|
1009
|
+
try {
|
|
1010
|
+
if (tokTimes.length > 1) {
|
|
1011
|
+
const span = Math.max(1, (Date.now() - tokTimes[0]) / 1000);
|
|
1012
|
+
const rate = tokTimes.length / span;
|
|
1013
|
+
if (rate > 0) saved.tokRate = Math.round(rate);
|
|
1014
|
+
}
|
|
1015
|
+
} catch { /* a missing figure is not a failed save */ }
|
|
1016
|
+
// WRITE THE SESSION BEFORE THE TITLE. The title is a decoration and the conversation is the
|
|
1017
|
+
// work: a naming request that hangs, or a process killed while it was in flight, must not cost
|
|
1018
|
+
// the reader the turn they just watched. Saving twice — once now, once after the title — is
|
|
1019
|
+
// cheap, and the second write only adds the name.
|
|
1020
|
+
sess.saveSession(saved);
|
|
1021
|
+
// AUTOMATIC NAMING, headless too. The terminal asks the model for a 3-7 word title after the
|
|
1022
|
+
// first turn; the desktop never did, so every session it drove stayed on the 20-character cut
|
|
1023
|
+
// of the first prompt. Same prompt, same budget escalation, same guard: the user's own rename
|
|
1024
|
+
// always wins, and a naming failure is cosmetic.
|
|
1025
|
+
//
|
|
1026
|
+
// BUT NOT AFTER AN INTERRUPT. A naming request is a real round trip, and a stopped turn was
|
|
1027
|
+
// stopped because the reader did not want to wait: the window kills the process a moment after
|
|
1028
|
+
// the interrupt, so the request never came back. An interrupted turn keeps the name it already
|
|
1029
|
+
// had, and the next turn names it.
|
|
1030
|
+
if (cfg.autoTitle !== false && !saved.title && !agent.stopRequested) {
|
|
571
1031
|
try {
|
|
572
|
-
const
|
|
573
|
-
|
|
574
|
-
|
|
1032
|
+
const asked = String(prompt || '').replace(/\s+/g, ' ').trim().slice(0, 400);
|
|
1033
|
+
if (asked) {
|
|
1034
|
+
const { LLM } = await import('./llm.js');
|
|
1035
|
+
const TITLE_PROMPT = 'You name coding-agent sessions. Reply with ONLY the title: one line, 3 to 7 words, sentence case (capitalize only the first word and proper nouns), at most 50 characters. No quotes, no trailing punctuation, no "Title:" label, no explanation.';
|
|
1036
|
+
for (const budget of [64, 256]) {
|
|
1037
|
+
const llm = new LLM({ ...cfg, temperature: 0.2, maxOutputTokens: budget });
|
|
1038
|
+
const got = await llm.requestText([
|
|
1039
|
+
{ role: 'system', content: TITLE_PROMPT },
|
|
1040
|
+
{ role: 'user', content: 'The entry message is:\n' + asked },
|
|
1041
|
+
], { noReasoning: true, noTools: true });
|
|
1042
|
+
const title = String(got || '').replace(/\s+/g, ' ').trim().replace(/^["']|["']$/g, '').slice(0, 50);
|
|
1043
|
+
if (title) { saved.title = title; break; }
|
|
1044
|
+
if (got === null) break;
|
|
1045
|
+
}
|
|
1046
|
+
}
|
|
1047
|
+
} catch { /* a failed naming request is cosmetic */ }
|
|
575
1048
|
}
|
|
576
1049
|
sess.saveSession(saved);
|
|
577
1050
|
|
|
@@ -647,38 +1120,6 @@ function loadOrCreateSession(opts, cfg) {
|
|
|
647
1120
|
}
|
|
648
1121
|
|
|
649
1122
|
|
|
650
|
-
/**
|
|
651
|
-
* Parse the --web flag into { bindIp, port } or null.
|
|
652
|
-
* --web -> loopback, OS-assigned port
|
|
653
|
-
* --web 8080 -> loopback, that port
|
|
654
|
-
* --web 0.0.0.0:8080 -> explicit address and port
|
|
655
|
-
* --web 192.168.1.5 -> that address, OS-assigned port
|
|
656
|
-
* Anything unparseable returns null, so the flag is ignored rather than failing
|
|
657
|
-
* the launch — /web from inside the session still works either way.
|
|
658
|
-
*/
|
|
659
|
-
export function parseWebArg(v) {
|
|
660
|
-
if (v == null || v === false) return null;
|
|
661
|
-
if (v === true) return { bindIp: '127.0.0.1', port: 0 };
|
|
662
|
-
const s = String(v).trim();
|
|
663
|
-
if (!s) return { bindIp: '127.0.0.1', port: 0 };
|
|
664
|
-
let bindIp = '127.0.0.1';
|
|
665
|
-
let port = 0;
|
|
666
|
-
if (/^\d+$/.test(s)) {
|
|
667
|
-
port = Number(s);
|
|
668
|
-
} else if (s.includes(':')) {
|
|
669
|
-
// IPv6 in brackets is deliberately not handled: /web covers it, and a
|
|
670
|
-
// half-parsed address is worse than ignoring the flag.
|
|
671
|
-
const at = s.lastIndexOf(':');
|
|
672
|
-
bindIp = s.slice(0, at) || '127.0.0.1';
|
|
673
|
-
const p = s.slice(at + 1);
|
|
674
|
-
if (!/^\d+$/.test(p)) return null;
|
|
675
|
-
port = Number(p);
|
|
676
|
-
} else {
|
|
677
|
-
bindIp = s;
|
|
678
|
-
}
|
|
679
|
-
if (port < 0 || port > 65535) return null;
|
|
680
|
-
return { bindIp, port };
|
|
681
|
-
}
|
|
682
1123
|
|
|
683
1124
|
export async function main(argv) {
|
|
684
1125
|
const args = parseArgs(argv);
|
|
@@ -762,8 +1203,38 @@ export async function main(argv) {
|
|
|
762
1203
|
}
|
|
763
1204
|
};
|
|
764
1205
|
|
|
765
|
-
//
|
|
1206
|
+
// A PROMPT FROM A FILE, for a caller that cannot pass one on the command line.
|
|
1207
|
+
//
|
|
1208
|
+
// Windows caps a command line at about 32k characters, and the desktop passes the message as
|
|
1209
|
+
// an argv entry: a long paste was refused by the shell or silently truncated. Reading a file
|
|
1210
|
+
// sidesteps the limit and every quoting rule with it.
|
|
1211
|
+
if (!args.prompt && typeof args['prompt-file'] === 'string' && args['prompt-file']) {
|
|
1212
|
+
try {
|
|
1213
|
+
args.prompt = fs.readFileSync(args['prompt-file'], 'utf8');
|
|
1214
|
+
} catch (e) {
|
|
1215
|
+
process.stderr.write(`hncode: cannot read --prompt-file: ${e.message}\n`);
|
|
1216
|
+
return EXIT.CONFIG;
|
|
1217
|
+
}
|
|
1218
|
+
}
|
|
1219
|
+
// --image <path>, repeatable. Read here so a bad path fails with its name, before a turn is
|
|
1220
|
+
// spent on a request that would have gone out without the picture.
|
|
1221
|
+
const promptImages = [];
|
|
1222
|
+
for (const p of (Array.isArray(args.image) ? args.image : (args.image ? [args.image] : []))) {
|
|
1223
|
+
try {
|
|
1224
|
+
const buf = fs.readFileSync(p);
|
|
1225
|
+
const ext = path.extname(p).toLowerCase();
|
|
1226
|
+
const mime = ext === '.jpg' || ext === '.jpeg' ? 'image/jpeg'
|
|
1227
|
+
: ext === '.gif' ? 'image/gif'
|
|
1228
|
+
: ext === '.webp' ? 'image/webp'
|
|
1229
|
+
: 'image/png';
|
|
1230
|
+
promptImages.push({ mimeType: mime, data: buf.toString('base64') });
|
|
1231
|
+
} catch (e) {
|
|
1232
|
+
process.stderr.write(`hncode: cannot read --image ${p}: ${e.message}\n`);
|
|
1233
|
+
return EXIT.CONFIG;
|
|
1234
|
+
}
|
|
1235
|
+
}
|
|
766
1236
|
if (args.prompt) {
|
|
1237
|
+
// headless prompt: MCP must be live BEFORE the request goes out.
|
|
767
1238
|
const format = args['output-format'];
|
|
768
1239
|
if (!isValidFormat(format)) {
|
|
769
1240
|
console.error(`hncode: unknown --output-format "${format}". Use one of: ${FORMATS.join(', ')}.`);
|
|
@@ -773,6 +1244,10 @@ export async function main(argv) {
|
|
|
773
1244
|
let session = null;
|
|
774
1245
|
if (args.session) session = typeof args.session === 'string' ? sess.loadSession(args.session) : sess.latestSession(undefined, undefined, { skipEmpty: true });
|
|
775
1246
|
else if (args.continue) session = sess.latestSession(undefined, undefined, { skipEmpty: true });
|
|
1247
|
+
// PLAN MODE COMES FROM THE SESSION RECORD, and --plan can turn it on. A window that set it
|
|
1248
|
+
// on the session and then sent a turn must get a read-only run; the record keeps the answer
|
|
1249
|
+
// for the next turn without the flag being repeated.
|
|
1250
|
+
cfg.plan = !!(args.plan || (session && session.plan));
|
|
776
1251
|
// --timeout / --retries are validated here so a typo fails loudly instead of
|
|
777
1252
|
// being parsed as NaN and silently ignored.
|
|
778
1253
|
const timeoutSeconds = args.timeout !== undefined ? Number.parseInt(String(args.timeout), 10) : 0;
|
|
@@ -785,7 +1260,18 @@ export async function main(argv) {
|
|
|
785
1260
|
console.error(`hncode: --retries needs a non-negative integer, got "${args.retries}".`);
|
|
786
1261
|
return EXIT.CONFIG;
|
|
787
1262
|
}
|
|
788
|
-
|
|
1263
|
+
// THE MODE COMES FROM THE FLAGS. `--auto` and `-y` were parsed and then dropped: `runPrompt`
|
|
1264
|
+
// never received them, and the approval callback tested `cfg.auto` — a key `config.js` does not
|
|
1265
|
+
// define, so it was always undefined. A window that passed `--auto` still got an approval request
|
|
1266
|
+
// for every tool call, which is the opposite of what the mode promises.
|
|
1267
|
+
return runPrompt({
|
|
1268
|
+
cfg, prompt: args.prompt, format, session, modelArg: args.model, timeoutSeconds, maxRetries, images: promptImages,
|
|
1269
|
+
permissionMode: args.auto ? 'auto' : args.yolo ? 'yolo' : 'ask',
|
|
1270
|
+
// `--approval` is the switch a front end passes when it can answer: it turns on the
|
|
1271
|
+
// approval dialog, the AskUserQuestion dialog and the steer channel together, because a
|
|
1272
|
+
// program that can answer one of them can answer all three.
|
|
1273
|
+
frontEnd: !!args.approval,
|
|
1274
|
+
});
|
|
789
1275
|
}
|
|
790
1276
|
|
|
791
1277
|
if (!process.stdout.isTTY) {
|
|
@@ -805,11 +1291,6 @@ export async function main(argv) {
|
|
|
805
1291
|
// Remote control: expose a local socket so a script can queue a prompt or
|
|
806
1292
|
// query status on the running session (see ci.js).
|
|
807
1293
|
control: args.control === true ? '' : (typeof args.control === 'string' ? args.control : null),
|
|
808
|
-
// Web UI: start the server as soon as the TUI is up. `--web` alone binds
|
|
809
|
-
// loopback on an OS-assigned port; `--web 0.0.0.0:8080` chooses both. Parsed
|
|
810
|
-
// here so it behaves like every other flag, and the TUI still has /web to
|
|
811
|
-
// start or stop it mid-session.
|
|
812
|
-
web: parseWebArg(args.web),
|
|
813
1294
|
// MCP runs in the BACKGROUND once the TUI is up (see startTUI): connecting
|
|
814
1295
|
// can take seconds and must not delay the first paint.
|
|
815
1296
|
mcpConnect: connectMcp,
|