@hncode/hncode 0.8.2 → 0.8.4

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/src/agent.js CHANGED
@@ -1,1421 +1,1465 @@
1
- // The agent loop: sends the message history to the LLM, consumes the normalized
2
- // event stream, executes any tool calls, appends results, and repeats until the
3
- // model answers without tool calls (or a step/interrupt condition is hit).
4
-
5
- import { LLM, setToolsList } from './llm.js';
6
- import { tools, combinedTools, getTool, llmTools } from './tools/index.js';
7
- import { validateToolArgs } from './tools/validate-args.js';
8
- import { DELEGATION_TOOLS } from './subagent-types.js';
9
- import { estimateMessagesTokens, estimateRequestOverhead, estimateTokens, measureToolDefTokens, messageTokens, TokenLedger, forgetMessageTokens } from './term.js';
10
- import { runHooks, runPatch, runPatchSync } from './plugin.js';
11
- import { loadHooks, runShellHooks } from './hooks.js';
12
- import {
13
- shapeToolResult, trimToolResults, DEFAULT_TRIM_THRESHOLD, DEFAULT_TRIM_KEEP_RATIO,
14
- } from './tool-result.js';
15
- // ---- compaction text (kimi's shapes) ----------------------------------------
16
- // These mirror kimi-code's contextMemory/compactionHandoff.ts so a compacted
17
- // history reads the same way there.
18
-
19
- // Wraps harness-generated text so it reads as a system note rather than something
20
- // the user actually typed.
21
- function wrapSystemReminder(content) {
22
- return `<system-reminder>\n${String(content).trim()}\n</system-reminder>`;
23
- }
24
-
25
- // ---- token accounting -------------------------------------------------------
26
- // The provider reports the numbers; this folds one report into a running total.
27
- // A field the provider did not send is left as it was, because "not reported" and
28
- // "zero" are different facts: summing undefined into 0 would claim a model never
29
- // used a cache it simply does not measure.
30
- export function addUsage(total, u) {
31
- const out = { ...(total || {}) };
32
- if (!u) return out;
33
- for (const key of ['input', 'output', 'cached', 'cacheWrite', 'reasoning']) {
34
- if (typeof u[key] === 'number' && Number.isFinite(u[key])) out[key] = (out[key] || 0) + u[key];
35
- }
36
- // How many REQUESTS contributed, so a reader can tell one big call from many
37
- // small ones with the same token count. Counted on the completion side, which
38
- // every protocol reports exactly once per request — Anthropic splits one
39
- // request into two usage events (input at message_start, output at
40
- // message_delta), so counting events would report double.
41
- if (u.output !== undefined) out.calls = (out.calls || 0) + 1;
42
- return out;
43
- }
44
-
45
-
46
- const COMPACTION_SUMMARY_PREFIX = [
47
- 'The conversation so far has been compacted to free up context. What follows is your own working summary of this task — use it to continue your train of thought rather than starting over.',
48
- 'Treat it as notes, not proof: where it says a step was done, tests passed, or a fix worked, verify that yourself before relying on it.',
49
- 'User messages earlier in this context are preserved verbatim from the compacted conversation. The summary records which earlier requests were already addressed.',
50
- ].join(' ');
51
-
52
- // The instruction given to the model that WRITES the summary. Adapted from
53
- // kimi-code's fullCompaction/compaction-instruction.md: it is a handoff for the
54
- // model that resumes, not a recap for a human. The language rule matters — without
55
- // it a Chinese conversation produced an English summary and the resumed context
56
- // lost the vocabulary the task was being discussed in.
57
- const COMPACTION_INSTRUCTION = [
58
- 'You are about to run out of context. Create a handoff summary for the model that will resume this task after the earlier conversation is cleared.',
59
- '',
60
- 'This message is a direct task, not part of the above conversation.',
61
- '',
62
- 'Write it in the same language the conversation has been using — do not switch to English just because these instructions are in English.',
63
- '',
64
- 'Make the summary self-sufficient: the next turn will see only the preserved messages and this summary. In your own words, preserve what is genuinely needed to continue:',
65
- '',
66
- '- What the latest request actually asks for, and any ambiguity you have already resolved. If the latest request is large (a big paste or file) and may be truncated in the kept messages, preserve the actual ask.',
67
- '- The instructions and constraints currently in force (user preferences, project rules, environment limits), with settled decisions kept separate from open questions, so neither is reopened nor mistaken for decided.',
68
- '- What has actually been done, at high fidelity: exact commands run, exact file paths touched, and their results — the concrete values, key lines and error text — not just the commands. Keep only the final working version of any code; drop intermediate attempts and already-resolved errors.',
69
- '- What you still do not know: files referenced but not read, APIs assumed but unseen, questions the user has not answered. Name these gaps so the next turn checks them instead of assuming.',
70
- '- The forward plan: the exact next step, the sequence to finish, decisions already made for those steps, foreseeable obstacles and how you mean to handle them.',
71
- '',
72
- 'Be honest about uncertainty. If an earlier step claimed something was done but was never verified, say so plainly and treat it as unverified rather than fact.',
73
- '',
74
- 'Be concise and proportional: a long multi-step task warrants detail, a nearly finished exchange needs only a sentence or two.',
75
- '',
76
- 'Respond with text only. Do not call any tools. Any tool-call syntax in your answer is discarded and scores the handoff as failed.',
77
- '',
78
- 'That includes XML-style tool syntax such as `<||DSML||invoke name="...">` or `<function_call>`: no such tag is',
79
- 'recognised here, so it becomes part of the summary and the next turn reads it as a step that happened.',
80
- ].join('\n');
81
- // Trailing note: the model should RESUME, not answer the summary.
82
-
83
- // A summariser can answer with tool-call syntax even when no tools were offered — the format is in its
84
- // training data, and a model interrupted mid-workflow reaches for it. Nothing was called, so the text is
85
- // noise, and left in a handoff summary the next turn reads it as a step that happened.
86
- //
87
- // The shapes covered are the ones these models actually emit: a special-token block (`<|tool_call|>`), a
88
- // fenced ```tool_call block, and a bare JSON object that claims a `name` and `arguments`. Only a block that
89
- // occupies whole lines is removed, so prose that merely mentions calling a tool survives.
90
- function stripToolCallText(text) {
91
- if (typeof text !== 'string' || !text) return text || '';
92
-
93
- // NOTHING WAS CALLED, SO THE BLOCK IS NOISE — but removing it outright can leave nothing at all.
94
- //
95
- // A summariser that answers ONLY with a tool call produced no summary: stripping to '' makes the caller
96
- // treat the compaction as failed, and the fallback there is to drop the history. So the stripped text is
97
- // measured: if it lost its substance, the original is kept VERBATIM with a note saying what it is. A
98
- // confusing summary is recoverable; a discarded one is not.
99
- let out = text;
100
- // A special-token block: closed form, or an unterminated one running to the end of its line.
101
- out = out.replace(/<\|tool_call\|>[^\n]*(?:<\|\/tool_call\|>)?/g, '');
102
- // A fenced block form.
103
- out = out.replace(/```tool_call[\s\S]*?```/g, '');
104
- // A bare JSON object on its own lines that declares a tool invocation.
105
- out = out.replace(/^\s*\{[^\n]*"name"\s*:\s*"[^"]+"[^\n]*"arguments"[^\n]*\}\s*$/gm, '');
106
- // THE DSML DIALECT. Some models write a tool call as an XML-ish block with a doubled delimiter around the
107
- // tag name (`<||DSML||invoke name="…">`), which none of the patterns above match. It arrives as a whole
108
- // block, so it is removed as one — an unterminated block included, since a summariser cut off by the token
109
- // limit leaves exactly that.
110
- out = out.replace(/<\|+\|?DSML\|?\|+[\s\S]*?(?=<\/\|\|+DSML\|\|+>|$)/gi, '');
111
- out = out.replace(/<\/?\|+\|?DSML\|?\|+[^>]*>/gi, '');
112
- // THE `<function_call>` DIALECT and its `<tool_call>` sibling: a JSON payload wrapped in a tag. Removed with
113
- // its body when both tags are present, and on its own when the body follows on the next line.
114
- out = out.replace(/<(function_call|tool_call)>[\s\S]*?<\/\1>/gi, '');
115
- out = out.replace(/<(function_call|tool_call)>[^\n]*/gi, '');
116
- out = out.replace(/\n{3,}/g, '\n\n').trim();
117
-
118
- if (out.length > 0) return out;
119
-
120
- // Every remaining character was a tool call: keep the original, marked for what it is.
121
- return [
122
- '(The summariser answered with a tool call instead of a summary. No tool was actually run — the text is',
123
- 'reproduced below unchanged so nothing is lost. Treat it as a summary that was never written.)',
124
- '',
125
- text.trim(),
126
- ].join('\n');
127
- }
128
-
129
- const COMPACTION_CONTINUATION_TEXT = 'Context compaction is complete — continue the work that was in progress when it began.';
130
-
131
- // Clip to a TOKEN budget, counting non-ASCII as one token per character (the same
132
- // rule estimateTokens uses). Slicing by characters is wrong for CJK text: 4000
133
- // Chinese characters are ~4000 tokens, not ~1000.
134
- function clipToTokens(text, maxTokens) {
135
- if (maxTokens <= 0) return '';
136
- const s = String(text ?? '');
137
- let ascii = 0, nonAscii = 0, end = 0;
138
- for (const ch of s) {
139
- if (ch.codePointAt(0) <= 127) ascii++; else nonAscii++;
140
- if (Math.ceil(ascii / 4) + nonAscii > maxTokens) break;
141
- end += ch.length;
142
- }
143
- return end >= s.length ? s : s.slice(0, end) + '\n…[clipped]';
144
- }
145
-
146
- // May the history be split between `index` and `index + 1`? Mirrors kimi's
147
- // canSplitAfter — a split is illegal when it would orphan a tool exchange:
148
- // * the message before the cut is a user message (would start the kept part
149
- // mid-turn), or
150
- // * it is an assistant message that still has tool calls, or
151
- // * the message after the cut is a tool result, or
152
- // * the prefix ends inside an open tool exchange (more results to come).
153
- // Exported for the headless -p path (index.js), which must trim a resumed
154
- // history on the same legal boundaries the compaction logic uses.
155
- export function canSplitAfter(messages, index) {
156
- if (index < 0 || index >= messages.length) return false;
157
- const m = messages[index];
158
- if (!m) return false;
159
- if (m.role === 'user') return false;
160
- if (m.role === 'assistant' && Array.isArray(m.toolCalls) && m.toolCalls.length > 0) return false;
161
- const next = messages[index + 1];
162
- if (next && next.role === 'tool') return false;
163
- return !prefixEndsWithOpenToolExchange(messages, index);
164
- }
165
-
166
- // True when the prefix [0..index] ends with an assistant that issued MORE tool
167
- // calls than have results so far — cutting there would leave a call unanswered.
168
- function prefixEndsWithOpenToolExchange(messages, index) {
169
- if (!messages[index] || messages[index].role !== 'tool') return false;
170
- let results = 0;
171
- for (let i = index; i >= 0; i--) {
172
- const m = messages[i];
173
- if (!m) return false;
174
- if (m.role === 'tool') { results++; continue; }
175
- return m.role === 'assistant' && Array.isArray(m.toolCalls) && m.toolCalls.length > results;
176
- }
177
- return false;
178
- }
179
-
180
-
181
- // A short, stable key for the prompt cache, derived from the conversation's
182
- // first user message. Stability is the whole point: the same conversation must
183
- // produce the same key on every turn, so a cheap deterministic hash beats a
184
- // random id. (Different conversations may collide — that is harmless, it only
185
- // means the provider's routing key is shared.)
186
- function hashKey(s) {
187
- let h = 0x811c9dc5;
188
- const str = String(s || '');
189
- for (let i = 0; i < str.length; i++) {
190
- h ^= str.charCodeAt(i);
191
- h = (h * 0x01000193) >>> 0;
192
- }
193
- return h.toString(36) + '-' + str.length.toString(36);
194
- }
195
-
196
- // Render what an Edit actually changed, for the MODEL's tool result.
197
-
198
- // Render what an Edit actually changed, for the MODEL's tool result.
199
- //
200
- // The UI has always received the edit through `editDiff` (see the tool_result
201
- // event), but the message pushed into `this.messages` carried only the one-line
202
- // receipt ("Edited a.js: replaced 1 occurrence(s)."). The model was therefore
203
- // asked to verify its own edit from a sentence that describes nothing: it could
204
- // not see WHAT changed, so a wrong-but-successful edit looked identical to a
205
- // correct one. The diff is appended here — after the receipt — so the model
206
- // reads what it did.
207
- //
208
- // The format is the usual unified one (`- old`, `+ new`) with the line number
209
- // from the file, and it is deliberately indented two spaces: a tool result is
210
- // rendered as plain text, and the indent keeps the +/- marks from reading as
211
- // part of the JSON envelope some providers wrap tool output in.
212
- export function formatEditDiffForModel(diff, maxLines = 400) {
213
- if (!diff || typeof diff.old !== 'string' || typeof diff.new !== 'string') return '';
214
- const split = (s) => String(s).replace(/\r\n/g, '\n').split('\n');
215
- const oldLines = split(diff.old);
216
- const newLines = split(diff.new);
217
- const startLine = Number(diff.startLine) > 0 ? Number(diff.startLine) : 1;
218
- const out = [];
219
- out.push('');
220
- out.push('--- diff ---');
221
- // Unchanged lines above and below, unmarked, so the change can be LOCATED. Without them this
222
- // was a quoted block with no indication of where in the file it landed — and identical-looking
223
- // code appears in many places, so neither the model nor the user could confirm the edit hit
224
- // the intended one rather than a same-text block further down.
225
- const before = (diff.context && Array.isArray(diff.context.before)) ? diff.context.before : [];
226
- const after = (diff.context && Array.isArray(diff.context.after)) ? diff.context.after : [];
227
- for (const c of before) out.push(' ' + String(c.n).padStart(4) + ' ' + c.text);
228
- let n = startLine;
229
- for (const l of oldLines) out.push(' ' + String(n++).padStart(4) + ' - ' + l);
230
- n = startLine;
231
- for (const l of newLines) out.push(' ' + String(n++).padStart(4) + ' + ' + l);
232
- for (const c of after) out.push(' ' + String(c.n).padStart(4) + ' ' + c.text);
233
- // A whole-file edit (a Write-sized `new`) must not be echoed back in full.
234
- if (out.length > maxLines + 3) {
235
- const hidden = out.length - (maxLines + 3);
236
- out.length = maxLines + 3;
237
- out.push(' … ' + hidden + ' more diff line(s) omitted');
238
- }
239
- return out.join('\n');
240
- }
241
-
242
- // Final instruction appended to the system prompt (see SYSTEM_PROMPT).
243
- // (The wording lives in SYSTEM_PROMPT itself, under "Finishing a turn".)
244
-
245
-
246
- // Tools whose execution cannot affect what any OTHER tool call in the same step
247
- // observes, and cannot be affected by one. Two read-only tools therefore have no
248
- // reason to run one after the other, and the agent runs a consecutive run of them
249
- // in parallel (see the tool loop in run()). Anything that writes, spawns, shells
250
- // out or mutates the working tree is excluded — that rules out `Git` (it can
251
- // stage/commit/switch), `ReadMediaFile` (read-only, but it decodes megabytes of
252
- // media and is never the bottleneck) and every delegation tool. Claude Code
253
- // expresses the same idea as `isConcurrencySafe()` on each tool; this is the flat
254
- // version of it, matching hncode's tool registry.
255
- const READ_ONLY_TOOLS = new Set([
256
- 'Read', 'Grep', 'Glob', 'FileLines', 'FetchURL', 'WebSearch',
257
- 'TaskList', 'TaskOutput',
258
- ]);
259
-
260
- // Debug switch for the size/age control in tool-result.js, mirroring Claude
261
- // Code's env-gated knobs. Set HNCODE_TOOL_RESULT_LIMITS=off to send every tool
262
- // result verbatim (useful when a spill is suspected of hiding something the
263
- // model needed).
264
- function toolResultLimitsEnabled() {
265
- return !/^(0|off|false|no)$/i.test(String(process.env.HNCODE_TOOL_RESULT_LIMITS || ''));
266
- }
267
-
268
- /**
269
- * A tool's return value, as the STRING the model can be sent.
270
- *
271
- * Every tool in `src/tools/` returns a plain string except the team tools, which return
272
- * `{ content }` / `{ error }`. That object went into the `tool` message verbatim, and a provider
273
- * that expects a string rejects the NEXT request with `missing type field in content item at
274
- * index 0` — so a teammate's first `SendMessage` worked and then the conversation died, one
275
- * message in. The symptom was a team that says hello and then never answers again.
276
- *
277
- * Returns `null` for the one shape that must stay an OBJECT: `ReadMediaFile` returns
278
- * `{ text, media: [...] }`, and the media parts travel as structured blocks the caller builds
279
- * from the object. Stringifying that would attach no image at all, so the caller keeps it.
280
- *
281
- * Normalised here, at the single point every tool result passes through, rather than in the
282
- * team tools: a second tool family making the same choice cannot reintroduce the bug.
283
- */
284
- /**
285
- * Settle `promise`, or reject as soon as `signal` aborts — whichever happens first.
286
- *
287
- * A tool is GIVEN the abort signal but cannot be forced to observe it. Built-ins do (Bash kills its
288
- * process tree); a plugin tool that ignores it kept running, and the caller's `await` kept waiting, so
289
- * pressing Esc during a slow plugin tool changed nothing on screen until the plugin finished on its own.
290
- *
291
- * Racing ends the WAIT regardless. The abandoned promise is left to settle detached — an unobserved
292
- * rejection would otherwise surface as an unhandled rejection — and the turn moves on, which is what
293
- * the key was asking for. It cannot stop the plugin's work, and this comment says so rather than
294
- * implying otherwise.
295
- */
296
- function raceWithAbort(promise, signal) {
297
- if (!signal) return promise;
298
- if (signal.aborted) return Promise.reject(new Error('aborted'));
299
- return new Promise((resolve, reject) => {
300
- const onAbort = () => reject(new Error('aborted'));
301
- signal.addEventListener('abort', onAbort, { once: true });
302
- Promise.resolve(promise).then(
303
- (v) => { signal.removeEventListener('abort', onAbort); resolve(v); },
304
- (e) => { signal.removeEventListener('abort', onAbort); reject(e); },
305
- );
306
- // A tool that resolves AFTER the abort must not become an unhandled rejection.
307
- Promise.resolve(promise).catch(() => {});
308
- });
309
- }
310
-
311
- function toolResultText(value) {
312
- if (typeof value === 'string') return value;
313
- if (value == null) return '';
314
- if (typeof value === 'object') {
315
- // Leave a media result alone — the caller needs the parts, not a sentence about them.
316
- if (Array.isArray(value.media)) return null;
317
- if (typeof value.content === 'string') return value.content;
318
- if (typeof value.error === 'string') return value.error;
319
- if (typeof value.text === 'string') return value.text;
320
- try { return JSON.stringify(value); } catch { return String(value); }
321
- }
322
- return String(value);
323
- }
324
-
325
-
326
-
327
- export const SYSTEM_PROMPT = `You are hncode, a coding agent in the user's terminal on ${process.platform}.
328
- You work inside a workspace directory using the tools provided.
329
-
330
- Tools:
331
- - Read a file before editing it; never guess contents or edit code you haven't read.
332
- - Prefer Edit over Write for existing files.
333
- - If a tool fails, read the error and fix your approach. After 2 failed attempts on the same goal, stop and report the blocker.
334
- - Independent tool calls may run in parallel; never parallelize dependent ones.
335
-
336
- - Put ALL of your internal reasoning inside <|thinking|>...<|/thinking|> tags, and always emit BOTH the
337
- opening and the closing tag. Do not omit the tags, do not abbreviate them, and do not leave the block
338
- unclosed.
339
- - Everything outside <|thinking|>...<|/thinking|> is what the user reads: keep it to the answer itself —
340
- what you did and what you found. Never repeat or summarise your reasoning there.
341
- - Keep the tags exactly as written: <|thinking|> and <|/thinking|>. Do not emit any other variant. The
342
- bars matter: a plain <think> is ordinary text that may appear in code or prose, and a bare
343
- "thinking" is a word this very instruction uses.
344
- Acting:
345
- - Unless the user is explicitly asking for a plan, asking a question about the code, or brainstorming,
346
- assume they want the work DONE. Say less and do more: implement the change rather than describing it.
347
- - Carry the task through implementation and verification in this turn. Do not stop at analysis, at a
348
- partial fix, or at a list of things you would do next.
349
- - New project, no prior context: be ambitious, use your judgement on structure.
350
- Existing codebase: be surgical. Touch only what the task needs — no renames, no reorganising,
351
- no drive-by fixes.
352
- - Read the neighbours before you write: match the naming, error handling and comment density you see.
353
- - Do not re-read a file after editing it, and do not re-run a search you already have results for.
354
- A successful edit tool call already proves it worked.
355
-
356
- Scope:
357
- - Do only what was asked. Do not refactor or "improve" unrelated code.
358
- - Do not fix unrelated bugs or broken tests — mention them instead; they are not yours to change.
359
- - If the request is ambiguous, ask one short clarifying question.
360
- - State any assumption you make.
361
- - Might be a dirty git worktree. Never revert changes you did not make. Never run a destructive command
362
- (git reset --hard, git checkout --) unless the user asked for it. If you notice an unexpected change
363
- you did not make, stop and ask.
364
-
365
- Verifying:
366
- - Run the narrowest check that exercises your change first, then widen.
367
- - In auto/yolo mode, run tests and lint yourself without asking.
368
- - In ask mode, do not burn the user's time on slow test suites mid-task: say what you would run and
369
- let them confirm.
370
- - Do not add tests to a codebase that has none. Do not add a formatter that the project did not configure.
371
- - If you could not verify something, say so plainly. Do not imply a test passed when you did not run it.
372
-
373
- Finishing:
374
- - Never stop silently after a tool call; end every turn with a written answer in the user's language.
375
- - Report briefly: what changed, and how you verified it. If something failed, say what you tried and what you need.
376
- - Never claim success without evidence. Cite file:line for referenced code.
377
- - Be concise. No filler, no restating the request or explaining tool output that already spoke for itself.
378
- - If context is running low, call /compact to shrink history.
379
- `;
380
-
381
- /** Plain text of a structured tool result, for the model and the transcript. */
382
- function mediaResultText(r) {
383
- if (!r || typeof r !== 'object') return String(r == null ? '' : r);
384
- return String(r.text == null ? '' : r.text);
385
- }
386
-
387
- export class Agent {
388
- constructor({ cfg, messages, onEvent, maxSteps = 0, onToolStart, canInterrupt = () => false, onApproval }) {
389
- this.cfg = cfg;
390
- this.messages = messages;
391
- this.onEvent = onEvent;
392
- this.maxSteps = maxSteps;
393
- this.onToolStart = onToolStart; // (name, args) => void (for headless/TTY overlays)
394
- // Ensure the LLM client knows the bare tool specs (the client wraps them per-protocol).
395
- // A toolFilter (array of tool names) limits which tools are exposed — used
396
- // by Plan mode (read-only subset) and Focus mode (minimal subset first).
397
- // `cfg.noDelegation` marks this as a SUBAGENT: delegation tools are removed
398
- // even if the filter would have allowed them. The catalog already excludes
399
- // them from every profile; this is the hard backstop that also covers the
400
- // `null` (= everything) case, so a subagent can never spawn another agent.
401
- const filtered = (Array.isArray(cfg.toolFilter) && cfg.toolFilter.length
402
- ? combinedTools().filter((t) => cfg.toolFilter.includes(t.name))
403
- : combinedTools()
404
- )
405
- .filter((t) => !(cfg.noDelegation && DELEGATION_TOOLS.includes(t.name)))
406
- // AgentSwarm is gated behind swarm mode, like Agent is gated behind the user
407
- // having asked for delegation. It is not enough to describe the mode in the
408
- // system prompt: the tool was offered on EVERY turn, so the model could fan a
409
- // task out to 128 subagents in a session where the user never opted in — and
410
- // the prompt's own rule ("never call this on your own initiative") was not
411
- // backed by anything. Off unless /swarm turned the mode on; the Agent tool
412
- // stays available for a single, deliberate delegation.
413
- .filter((t) => !(t.name === 'AgentSwarm' && !cfg.swarm));
414
- // Kept as the process-wide FALLBACK for LLM instances that never register
415
- // their own list (doctor's connectivity probe). Every real agent registers
416
- // its list on its own LLM below — requests no longer read whichever Agent
417
- // happened to be constructed last.
418
- setToolsList(filtered);
419
- // THE REAL COST OF THE TOOLS, measured once per agent.
420
- //
421
- // The context gauge charged a flat 8 tokens per tool, which is short by an order of magnitude — the
422
- // schemas of these 68 tools come to about 15 900 tokens. That figure was missing from every
423
- // usage estimate, so the app's own count ran tens of thousands below the provider's.
424
- //
425
- // Measured here because this is the only place that knows the FINAL set: `toolFilter`, the
426
- // subagent block and the swarm gate above all change what is sent, and a number derived from
427
- // `cfg.toolFilter` alone would price tools the model never sees.
428
- this.toolDefTokens = measureToolDefTokens(filtered);
429
- // ALSO on `cfg`, because the TUI's gauge writers live outside this object and price a request as
430
- // `estimateMessagesTokens(...) + cfg.toolDefTokens`. Without this line those readers saw `undefined`
431
- // and silently fell back to zero, so every restore and every /trim reported a number short by the
432
- // whole tool block — the same fixed gap, from a different cause.
433
- if (this.cfg && typeof this.cfg === 'object') this.cfg.toolDefTokens = this.toolDefTokens;
434
- // A block for the direct-call path too: the model can still emit a tool call
435
- // for a tool that is not exposed, so refuse it here rather than at execution.
436
- this.noDelegation = !!cfg.noDelegation;
437
- // Mirrors the filter above for the direct-call path — a tool the model was told
438
- // about on an earlier turn can still be emitted after /swarm goes off.
439
- this.swarmMode = !!cfg.swarm;
440
- // AbortSignal handed to every tool so a long-running one (Bash) is killed
441
- // when the user presses Esc / Ctrl-C — otherwise the command keeps running
442
- // after the turn was interrupted.
443
- this.toolAbort = new AbortController();
444
- // Reuse an incoming task store when the caller provides one. Background
445
- // tasks OUTLIVE the turn that started them (their process is detached), so a
446
- // fresh `{}` per Agent made them vanish from the UI on the next turn while
447
- // still running. The TUI passes its persistent `state.tasks` through cfg.
448
- this.ctx = { ...cfg, tasks: cfg.tasks || {}, todoState: Array.isArray(cfg.todoState) ? cfg.todoState.slice() : [], allowExternal: !!cfg.allowExternal, signal: this.toolAbort.signal };
449
- // Live output stream for a RUNNING tool (Bash): the tool calls this with raw
450
- // chunks and the agent tags them with the id of the tool call in flight, so
451
- // the TUI can append them to the matching "Using …" row while it runs.
452
- this._currentToolId = null;
453
- this.ctx.onOutput = (chunk) => {
454
- if (chunk && this._currentToolId) this.onEvent({ type: 'tool_output', id: this._currentToolId, chunk });
455
- };
456
- // A command whose output ended mid-line and then went quiet is most likely sitting at a prompt. The tool
457
- // cannot answer it for the user, so it says so and the UI offers the composer.
458
- this.ctx.onStdinWaiting = (waiting) => {
459
- if (this._currentToolId) this.onEvent({ type: 'tool_stdin_waiting', id: this._currentToolId, waiting: !!waiting });
460
- };
461
- // The Read snapshot pool lives ON THE AGENT, not on a per-turn ctx. It records
462
- // what the model has read (and the hashes at that moment) so a later Edit can
463
- // refuse to act on a stale snippet. /undo rewinds files on disk, i.e. it makes
464
- // those hashes describe content that is no longer there — the TUI clears this
465
- // pool right after a rewind so the next Edit is not rejected as stale.
466
- this.readPool = new Map();
467
- this.ctx.readPool = this.readPool;
468
- // `fork` (the Agent tool) snapshots THIS conversation into the subagent. The
469
- // tool reads `ctx._parentMessages`. This must be a GETTER, not the array
470
- // itself: auto-compaction REPLACES `this.messages` with a trimmed history, so
471
- // a retained reference kept pointing at the pre-compaction array — a fork
472
- // after a compaction would hand the subagent exactly the oversized history
473
- // that was just cut, and could push it straight past its own window.
474
- Object.defineProperty(this.ctx, '_parentMessages', {
475
- get: () => this.messages,
476
- enumerable: true,
477
- configurable: true,
478
- });
479
- // Prompt-cache key: identify the SESSION, not the request, so the cached
480
- // prefix is reused across turns instead of thrashing. The caller may pass one
481
- // (the TUI knows the session id); otherwise derive a stable value from the
482
- // first user message so repeated runs of the same conversation still share a
483
- // prefix. A subagent inherits the parent's key (same conversation family).
484
- if (cfg.sessionId == null) {
485
- const firstUser = (Array.isArray(messages) ? messages : []).find((m) => m.role === 'user' && typeof m.content === 'string');
486
- cfg = { ...cfg, sessionId: firstUser ? hashKey(firstUser.content) : 'default' };
487
- this.cfg = cfg;
488
- }
489
- this.llm = new LLM(cfg);
490
- // THIS agent's tool defs ride on THIS instance. The module-global was overwritten
491
- // by every `new Agent()` in the process — a subagent, swarm member or teammate
492
- // constructed while a parent request was being built swapped the parent's tool
493
- // list mid-turn, silently stripping Edit/Bash from its next request.
494
- this.llm.setTools(filtered);
495
- this.stopRequested = false;
496
- // Auto-compaction is allowed at most once per TURN (not per step). Reset here so
497
- // a caller that reuses one Agent across turns still gets a fresh allowance.
498
- this._compactedThisTurn = false;
499
- // THE PROMPT-CACHE BOUNDARY: how many messages an earlier request of this turn
500
- // has already sent. Everything below that index is stable and can carry a cache
501
- // breakpoint. Reset per turn because a new turn opens with a new user message, so
502
- // the previous turn's boundary would describe a prefix this one never sent.
503
- this._stableEnd = 0;
504
- // Rolling context-token total for `this.messages` (see usedTokens). It holds no
505
- // messages of its own, only the count of what it has already priced, so a
506
- // compaction that replaces the array simply falls out of the fast path.
507
- this._ledger = new TokenLedger();
508
- this.onApproval = onApproval; // async (toolName, args) => boolean
509
- // Shell hooks (Claude Code-style): user-configured commands run at lifecycle
510
- // events. ALWAYS stored as a `{ hooks: {Event: [...]} }` config, which is the
511
- // shape runShellHooks() reads. A caller may inject one (tests / the TUI,
512
- // which reloads per turn); otherwise it is read from disk for this workspace.
513
- this.hookConfig = cfg.hookConfig
514
- ? (cfg.hookConfig.hooks ? cfg.hookConfig : { hooks: cfg.hookConfig })
515
- : { hooks: loadHooks(cfg.workspace).hooks };
516
- // The turn's user prompt, for the UserPromptSubmit hook. Set by run().
517
- this._turnPrompt = '';
518
- // Messages the user types while the agent is streaming. They are injected
519
- // as user messages right AFTER the current round of tool calls, so the
520
- // model sees "tool callback / user steer" together on the next request —
521
- // exactly like kimi-code's steer (no separate turn feel).
522
- this.steerQueue = [];
523
- }
524
-
525
- // Queue a steering message typed while streaming. It takes effect once the
526
- // in-flight tool calls finish and the loop asks the model again.
527
- steer(text) {
528
- if (text && text.trim()) this.steerQueue.push(String(text).trim());
529
- }
530
- // True when a steer is pending injection.
531
- get hasSteer() { return this.steerQueue.length > 0; }
532
-
533
- interrupt() {
534
- this.stopRequested = true;
535
- try { this.toolAbort.abort(); } catch {}
536
- if (this.llm) this.llm.abort();
537
- // The compaction summarizer is a SEPARATE LLM instance; abort it too, or an
538
- // auto-compaction in flight cannot be interrupted (Esc did nothing until the
539
- // summary request finished on its own).
540
- if (this._summaryLlm) { try { this._summaryLlm.abort(); } catch {} }
541
- }
542
-
543
- // What the NEXT request will carry: the messages (which already begin with the
544
- // assembled system prompt — see the TUI's runAgent) plus the tool-definition
545
- // overhead. It must NOT add `cfg.systemPrompt` on top: that value is the RAW
546
- // config string, not the assembled prompt (calm/plan/swarm/AGENTS.md are appended
547
- // later), so counting it both double-counted the system text and measured the
548
- // wrong figure — while being the only input that decides whether to compact.
549
- usedTokens() {
550
- // A rolling total rather than a fresh walk of the whole history. This is called at
551
- // least three times per model round (before the request, after compaction, after a
552
- // trim) and once more per step for the gauge, so on a long session the old full
553
- // rescan priced the entire transcript — Read results included — several times per
554
- // step for a number that changes by one message.
555
- let total = this._ledger.sync(this.messages, null);
556
- // THE TOOL DEFINITIONS ARE PART OF WHAT IS SENT, and they are not messages.
557
- //
558
- // This charged `toolFilter.length * 8` — and only when a filter was set, so an ordinary turn
559
- // added NOTHING at all. Measured, the schemas of the 68 registered tools come to about 15 900
560
- // tokens, which is why the app's own gauge ran tens of thousands below the provider's report.
561
- //
562
- // `toolDefTokens` is measured once in the constructor, from the FINAL filtered set.
563
- total += Number.isFinite(this.toolDefTokens) ? this.toolDefTokens : 0;
564
- return total;
565
- }
566
-
567
-
568
-
569
- // Where to cut the history for compaction. Walks back from the end accumulating a
570
- // token budget, but only accepts indices the boundary rule allows (so the kept
571
- // slice can never begin on an orphan tool result). Returns how many messages to
572
- // DROP. Mirrors kimi's computeCompactCount + canSplitAfter.
573
- computeCompactSplit(maxCtx) {
574
- // Keep a fraction of the CURRENT usage, not of the whole window: a big window
575
- // (1M) should not force a huge tail to be kept when only a little was used.
576
- // Ratio is configurable (/auto-compact keep, config.toml compact_keep_ratio),
577
- // default 0.2.
578
- const keepRatio = (typeof this.cfg.compactKeepRatio === 'number'
579
- && this.cfg.compactKeepRatio > 0 && this.cfg.compactKeepRatio < 1)
580
- ? this.cfg.compactKeepRatio : 0.2;
581
- const used = this.usedTokens();
582
- const maxSize = Math.max(1, Math.floor((used || (maxCtx || 512000) * 0.85) * keepRatio));
583
- const msgs = this.messages || [];
584
- // How far the LEADING system block runs. A cut before `floor` would land inside it,
585
- // splitting the assembled system prompt across the drop boundary. The block itself is
586
- // carried over by the trim (renamed `leadingSystem` there), because a cut can only
587
- // ever land at or after its end.
588
- let floor = 0;
589
- while (floor < msgs.length && msgs[floor] && msgs[floor].role === 'system') floor++;
590
- let recent = 1;
591
- let size = 0;
592
- let bestSplit;
593
- for (; recent < msgs.length; recent++) {
594
- const split = msgs.length - recent;
595
- // `messageTokens(m)`, not `estimateMessagesTokens([m])`: the latter allocated a
596
- // throwaway single-element array for every message in the transcript, on every
597
- // call. It is also the memoised form, so repeating this walk after a large tool
598
- // result is a WeakMap hit rather than a re-measure.
599
- size += messageTokens(msgs[split], null);
600
- // The guard the leading system block needs, and the reverse of the `split > floor`
601
- // this used to test. A cut at `split` drops `[0..split-1]`, so `split >= floor`
602
- // keeps the cut at or after the block's end and never inside it — which is what
603
- // the block's comment above asks for, and what `split > floor` inverted.
604
- if (split >= floor && canSplitAfter(msgs, split - 1)) bestSplit = split;
605
- if (size >= maxSize && bestSplit !== undefined) break;
606
- }
607
- return bestSplit ?? 0;
608
- }
609
-
610
- /**
611
- * Trim the history at a legal cut and append the summary + continuation note.
612
- *
613
- * Extracted from `run()` so it can be tested against the REAL implementation. A test that
614
- * re-implemented these four lines was green against a duplicated system prompt — the copy
615
- * carried its own guard, which is the failure mode of testing a restatement.
616
- *
617
- * Returns `{ split, dropped }`.
618
- *
619
- * Shape: `[ ...lead, ...kept, summary, continuation ]`.
620
- *
621
- * The summary is a USER message wrapped in a `<system-reminder>` (kimi's shape), not a
622
- * `system` one. Two reasons:
623
- * * the TUI rebuilds the system prompt from scratch each turn and SKIPS every `system`
624
- * entry in the stored history, so a system summary was dropped before the model saw it;
625
- * * the turn-end save filters `system` out of the session, so it was not persisted either
626
- * — history trimmed AND summary lost at both ends, which made "compaction" pure data loss.
627
- * The continuation note goes LAST so the model's next move is "keep going" rather than
628
- * "answer the summary".
629
- */
630
- applyCompactionSplit(maxCtx, summary) {
631
- const split = this.computeCompactSplit(maxCtx);
632
- const keep = this.messages.slice(split);
633
- const dropped = this.messages.length - keep.length;
634
- // The LEADING system block is carried over explicitly. It sits at the head of the array
635
- // and the cut drops everything before `split`, so it would otherwise be taken by every
636
- // compaction — leaving the request with no instructions, which is the loss the `floor`
637
- // guard in computeCompactSplit exists to prevent.
638
- let leadingSystem = 0;
639
- while (leadingSystem < this.messages.length
640
- && this.messages[leadingSystem] && this.messages[leadingSystem].role === 'system') leadingSystem++;
641
- // Only what the cut actually REMOVED. `keep` is `slice(split)`, so at `split === 0` it
642
- // still contains the whole array including the block — prepending the block then sends the
643
- // system prompt twice, and `llm.js` concatenates every system message into the request, so
644
- // it would stay doubled in every compacted request from then on.
645
- const lead = split > 0 ? this.messages.slice(0, leadingSystem) : [];
646
- const summaryText = summary
647
- ? `${COMPACTION_SUMMARY_PREFIX}\n${summary}`
648
- : `${COMPACTION_SUMMARY_PREFIX}\n(no summary available)`;
649
- this.messages = [
650
- ...lead,
651
- ...keep,
652
- { role: 'user', _harness: true, content: wrapSystemReminder(summaryText) },
653
- { role: 'user', _harness: true, content: wrapSystemReminder(COMPACTION_CONTINUATION_TEXT) },
654
- ];
655
- // `kept` is returned, not just its length: the caller reports how many messages survived, and it
656
- // has no other way to know. It was `keep.length` at the call site referring to a local that lives
657
- // only in here — a ReferenceError raised inside `run()`, which reached unhandledRejection and exited
658
- // the whole TUI at the moment compaction fired.
659
- return { split, dropped, kept: keep.length };
660
- }
661
-
662
- async run() {
663
- // Clear any interrupt flag left from a previous (interrupted) turn. This runs at
664
- // the start of EVERY turn, so a stalled Esc/Ctrl-C from an earlier compaction can
665
- // never suppress auto-compaction on the next message. (The constructor also
666
- // initializes it, but a caller that reuses one Agent across turns must get a
667
- // fresh allowance here — without this, the live block would blink again with no
668
- // compaction behind it.)
669
- this.stopRequested = false;
670
- this._compactedThisTurn = false;
671
- // Plugin lifecycle: `onTurnStart` fires here and `onTurnEnd` in the finally
672
- // block at the end of this method. Both are awaited and both swallow plugin
673
- // errors (see runHooks), so a broken plugin cannot abort a turn.
674
- await runHooks('onTurnStart', { messages: this.messages });
675
- // SHELL HOOK: SessionStart fires once per agent run (the first turn of a
676
- // session). A hook failure never blocks — it is a convenience signal.
677
- await runShellHooks(this.hookConfig, 'SessionStart', { messages: this.messages }, this.cfg.workspace);
678
- // SHELL HOOK: UserPromptSubmit fires with the latest user message. It cannot
679
- // block (Claude Code's can add context; blocking the user's own prompt is a
680
- // worse failure than a missing hook), so the result is only logged.
681
- {
682
- const lastUser = [...this.messages].reverse().find((m) => m.role === 'user' && typeof m.content === 'string');
683
- if (lastUser) {
684
- this._turnPrompt = lastUser.content;
685
- await runShellHooks(this.hookConfig, 'UserPromptSubmit', { prompt: lastUser.content }, this.cfg.workspace);
686
- }
687
- }
688
- let text = '';
689
- let toolCalls = [];
690
- let emittedEnd = false;
691
- let thought = '';
692
- // Anthropic thinking blocks, WITH their signatures. They belong to the assistant
693
- // message: the next request in the turn must replay them or the provider rejects the
694
- // tool result that follows (see toAnthropic in llm.js). Reset per step because each
695
- // step is a separate reply.
696
- let thoughtBlocks = [];
697
- // decide whether running out of steps actually left the turn unfinished.
698
- let hadToolCallsOnFinalStep = false;
699
- // How many times this turn has continued an answer the output cap cut in half.
700
- // Bounded so a model that cannot fit its answer in the budget cannot loop.
701
- let truncationRecoveries = 0;
702
- const MAX_TRUNCATION_RECOVERIES = 3;
703
-
704
- const handle = async (e) => {
705
- switch (e.type) {
706
- case 'data':
707
- text += e.text;
708
- this.onEvent({ type: 'data', text: e.text });
709
- break;
710
- case 'think':
711
- // Reasoning tokens: forward verbatim so the TUI can render a live
712
- // "thinking…" block. They are NOT part of the assistant message.
713
- thought += e.text;
714
- this.onEvent({ type: 'think', text: e.text });
715
- break;
716
- case 'thought_block':
717
- // A signed thinking block from the provider. Opaque to us; kept whole so it can
718
- // be sent back verbatim, which is the only way it is accepted.
719
- if (e.block) thoughtBlocks.push(e.block);
720
- break;
721
- case 'truncated':
722
- // The reply hit max_tokens and was cut off mid-answer. Remember it: the
723
- // loop below continues the turn instead of ending it (see the `truncated`
724
- // branch), so a half-written answer is never presented as a finished one.
725
- this._truncated = true;
726
- break;
727
- case 'usage':
728
- // Provider accounting, accumulated on the AGENT so it survives across the steps of one turn.
729
- //
730
- // IT DOES NOT FEED THE CONTEXT GAUGE. `usage.input` was wired into both the gauge and a
731
- // calibration here, and removed from both: it counts the request that already went out while the
732
- // estimate counts the one about to, so the number jumped between two definitions depending on
733
- // which ran last.
734
- //
735
- // What it IS used for: cost and `/usage`, where it is the only honest source, and the turn's
736
- // output counter.
737
- this.usage = addUsage(this.usage, e.usage);
738
- // THE REAL SIZE OF THE REQUEST THAT JUST WENT OUT.
739
- //
740
- // `usage.input` is what the endpoint actually billed for this request, which is the honest answer
741
- // to "how full is the context". The compaction threshold reads it (see `usedNow` below) instead of
742
- // the local estimate, which runs low because it cannot model the provider's framing. `input`
743
- // INCLUDES the reply's own prompt but not the reply, which is exactly the figure to compare against
744
- // the limit.
745
- if (e.usage && Number.isFinite(e.usage.input) && e.usage.input > 0) {
746
- this.ctxReportedTokens = e.usage.input;
747
- }
748
- this.onEvent({ type: 'usage', usage: e.usage, total: this.usage });
749
- break;
750
- case 'tool_start':
751
- toolCalls.push({ id: e.id, name: e.name, args: {}, argsJson: '' });
752
- this.onEvent({ type: 'tool_start', id: e.id, name: e.name });
753
- break;
754
- case 'tool_args': {
755
- const tc = toolCalls.find((t) => t.id === e.id);
756
- if (tc) { tc.argsJson += e.chunk; }
757
- // Forward the raw argument chunk so the TUI can stream a Write's
758
- // content (or an Edit's old/new text) while the model is emitting it.
759
- this.onEvent({ type: 'tool_args', id: e.id, chunk: e.chunk });
760
- break;
761
- }
762
- case 'tool_end': {
763
- const tc = toolCalls.find((t) => t.id === e.id);
764
- if (tc) {
765
- try { tc.args = tc.argsJson ? JSON.parse(tc.argsJson) : {}; }
766
- catch {
767
- // The streamed arguments did not form complete JSON. The usual cause
768
- // is truncation (a huge `content`, a long command) or an interrupted
769
- // stream. The `raw` shape is kept so a tool can SEE that its
770
- // arguments failed to parse and say so, instead of reporting a
771
- // missing field; `_rawLen` lets that message state how big the
772
- // partial payload was, which is what tells the model to split it.
773
- tc.args = { raw: tc.argsJson, _rawLen: tc.argsJson ? tc.argsJson.length : 0 };
774
- }
775
- }
776
- break;
777
- }
778
- case 'end':
779
- emittedEnd = true;
780
- break;
781
- case 'aborted':
782
- // The request was aborted (Esc / Ctrl-C): surface it and stop the loop.
783
- this.stopRequested = true;
784
- this.onEvent({ type: 'aborted' });
785
- break;
786
- case 'error':
787
- this.onEvent({ type: 'error', error: e.error });
788
- break;
789
- }
790
- };
791
-
792
- // No step cap: the loop runs until the model produces a final answer, the
793
- // user interrupts (Esc / Ctrl-C), or an error ends the turn. maxSteps is
794
- // kept only for callers that explicitly request a bound (0/undefined = none).
795
- const stepLimit = (this.maxSteps > 0) ? this.maxSteps : Infinity;
796
- for (let step = 0; step < stepLimit; step++) {
797
- // Process any steer messages collected during the previous step
798
- if (this.steerQueue.length > 0) {
799
- const steers = this.steerQueue.splice(0);
800
- for (const text of steers) {
801
- this.messages.push({ role: 'user', content: text });
802
- this.onEvent({ type: 'steer', text });
803
- }
804
- }
805
- if (this.stopRequested) { this.onEvent({ type: 'stopped' }); break; }
806
- text = ''; toolCalls = []; emittedEnd = false; thought = ''; thoughtBlocks = [];
807
- this._truncated = false;
808
- // Report the start of each model round so the TUI can count steps/rounds.
809
- this.onEvent({ type: 'step_start', step, round: step + 1 });
810
- // ---- auto-compaction (kimi's runtime strategy) ----
811
- // Before each model call, if the estimated context usage is at or above
812
- // 85% of the model's max context, summarize the older portion and keep a
813
- // small recent tail. Mirrors kimi's triggerRatio=0.85 /
814
- // maxRecentSizeRatio=0.2 policy, plus its `reservedContextSize` rule: a
815
- // request that leaves less than the reserved headroom is compacted even
816
- // below 85%, so the reply has room to be generated.
817
- const maxCtx = this.cfg.maxContextTokens || 512000;
818
- // THE PROVIDER'S OWN COUNT WINS WHEN THERE IS ONE.
819
- //
820
- // `usedTokens()` is a local estimate from the token ledger. The endpoint reports the real size with
821
- // every reply, and that figure is what the status bar shows — but this decision used the estimate
822
- // regardless, so a session the gauge put at 88% could stay under an 85% trigger indefinitely: the
823
- // estimate runs low because it cannot model the provider's own message framing and tool preamble.
824
- // Two numbers for the same thing is the bug; the reported one is the one that is true.
825
- let usedNow = this.usedTokens();
826
- const reported = Number(this.ctxReportedTokens);
827
- if (Number.isFinite(reported) && reported > 0) usedNow = reported;
828
- // THE MESSAGE THAT TRIGGERED THIS TURN IS NOT YET IN A REQUEST.
829
- //
830
- // The user's message is appended before `run()` is entered, so a fresh turn that pushes the
831
- // history over the threshold would compact FIRST and then send — summarising a conversation that
832
- // now includes the message it is about to answer, and paying a summary round-trip before the model
833
- // has seen the request at all.
834
- //
835
- // Excluding the trailing user message from the TRIGGER means the decision is made on what the
836
- // previous turn left behind, which is the history the message is joining. If adding it would still
837
- // overflow, `needsRoom` catches that on the NEXT pass — after the model has answered something —
838
- // and `clipToTokens` bounds the request itself in the meantime.
839
- //
840
- // Counted as a subtraction rather than by pruning the array: the message must stay in `messages`,
841
- // it just must not decide whether to compact.
842
- let triggerTokens = usedNow;
843
- for (let i = this.messages.length - 1; i >= 0; i--) {
844
- const m = this.messages[i];
845
- if (!m) continue;
846
- // Only skip a TRAILING run of user messages — a steering note queued mid-turn, or the prompt that
847
- // opened this turn. A user message further back is part of the history being measured.
848
- if (m.role !== 'user' || m._harness) break;
849
- triggerTokens -= messageTokens(m, this.cfg);
850
- }
851
- triggerTokens = Math.max(0, triggerTokens);
852
- // `reservedContextSize` (kimi): a request leaving less than this much headroom
853
- // is compacted even below the trigger ratio, so the REPLY has room to be
854
- // generated. A request just under the trigger could otherwise still fail.
855
- //
856
- // Measured on `usedNow`, NOT on `triggerTokens`: the headroom question is about the request that
857
- // will actually be sent, and that one does include the new message. The two thresholds ask
858
- // different things — "is the history full" versus "will this request fit" — so they read different
859
- // numbers on purpose.
860
- const reserved = this.cfg.reservedContextTokens || 50_000;
861
- const needsRoom = reserved > 0 && reserved < maxCtx && usedNow + reserved >= maxCtx;
862
- // Trigger ratio is configurable (/auto-compact threshold, config.toml
863
- // compact_threshold); default 0.85.
864
- const trigger = (typeof this.cfg.compactThreshold === 'number' && this.cfg.compactThreshold > 0
865
- && this.cfg.compactThreshold < 1) ? this.cfg.compactThreshold : 0.85;
866
- // At most ONCE per turn. This used to run inside the step loop with no counter,
867
- // so a trim that failed to get under the threshold triggered again on the very
868
- // next step — paying for another summary round-trip each step while the history
869
- // kept shrinking.
870
- const shouldCompact = this.cfg.autoCompact !== false && maxCtx > 0
871
- && !this._compactedThisTurn
872
- // `triggerTokens`, not `usedNow`: the history WITHOUT the message that opened this turn.
873
- && (triggerTokens >= maxCtx * trigger || needsRoom);
874
- if (shouldCompact) {
875
- const before = usedNow;
876
- this._compactedThisTurn = true;
877
- // SHELL HOOK: PreCompact — a chance to back up the transcript before the
878
- // older half is summarized away. Never blocks (the trim must go ahead).
879
- await runShellHooks(this.hookConfig, 'PreCompact',
880
- { tokens: usedNow, messages: this.messages }, this.cfg.workspace);
881
- // Tell the TUI the trim is under way. Summarizing is a full model
882
- // round-trip, so without this the UI sat silent for seconds mid-turn
883
- // with no sign anything was happening.
884
- this.onEvent({ type: 'compacting', before: usedNow, keep: 0, dropped: 0 });
885
- //
886
- // SUMMARIZE BEFORE TRIMMING. The summary is generated from the FULL history,
887
- // so the summarizing model can see what just happened — the most recent
888
- // exchange is what tells it what the session is doing now. Trimming first
889
- // summarized only the OLD part and lost what the summary needed most.
890
- //
891
- // The transcript fed to the summarizer is bounded by TOKENS, not characters.
892
- // A character cap is not a size cap: 120k Chinese characters is roughly 120k
893
- // tokens, which alone can exceed the window and make the call FAIL — after
894
- // which the history was discarded with no summary at all. That is the normal
895
- // case for a Chinese conversation, not an edge case.
896
- const summaryBudget = Math.max(1, Math.floor(maxCtx * 0.3));
897
- const perMsgTokens = 4_000;
898
- const summaryParts = [];
899
- let summaryTokens = 0;
900
- for (let i = this.messages.length - 1; i >= 0; i--) {
901
- const m = this.messages[i];
902
- let raw = typeof m.content === 'string' ? m.content : JSON.stringify(m.content || '');
903
- if (estimateTokens(raw) > perMsgTokens) raw = clipToTokens(raw, perMsgTokens);
904
- const line = `${m.role}: ${raw}`;
905
- const t = estimateTokens(line);
906
- if (summaryTokens + t > summaryBudget) break;
907
- summaryTokens += t;
908
- summaryParts.unshift(line);
909
- }
910
- let summary = '';
911
- if (this.messages.length > 0) {
912
- const summaryPrompt = [
913
- { role: 'system', content: COMPACTION_INSTRUCTION },
914
- { role: 'user', content: summaryParts.join('\n\n') },
915
- ];
916
- const cfgCopy = { ...this.cfg, maxOutputTokens: Math.min(this.cfg.maxOutputTokens || 4096, 4096) };
917
- const llm = new LLM(cfgCopy);
918
- // Remember this throwaway summarizer so Esc / Ctrl-C can abort IT too.
919
- // It is NOT `this.llm`, so `interrupt()` could not reach it — a running
920
- // auto-compaction was uninterruptible, which felt like a hang.
921
- this._summaryLlm = llm;
922
- // Thinking OFF and no tools, matching Claude Code's summarizer
923
- // (`thinkingConfig: { type: 'disabled' }`). Summarizing is a straight
924
- // transcription task: reasoning tokens buy nothing here, and on a
925
- // reasoning model they can consume the whole output budget — which
926
- // returns an EMPTY summary, and an empty summary is what turns a
927
- // compaction into a silent loss of history.
928
- try {
929
- // A DECLARATION IS NEEDED FOR THE REFUSAL.
930
- //
931
- // `tool_choice: 'none'` is rejected by both providers unless a tool list accompanies it, and the
932
- // summariser is a fresh instance with none. One inert definition is declared so the refusal can be
933
- // expressed: the model then cannot produce a tool call, rather than being asked not to.
934
- llm._tools = [{
935
- name: 'noop',
936
- description: 'Takes no action. Present only so the request can refuse tool use.',
937
- parameters: { type: 'object', properties: {}, additionalProperties: false },
938
- }];
939
- const raw = await llm.requestText(summaryPrompt, { noReasoning: true, toolChoice: 'none' });
940
- summary = stripToolCallText(raw);
941
- } catch { summary = ''; }
942
- this._summaryLlm = null;
943
- }
944
- // Interrupted mid-summary: do NOT trim. Aborting yields an empty summary, and
945
- // proceeding would drop history with nothing to replace it — data loss. Mark
946
- // the compaction block cancelled and bail out of the turn.
947
- if (this.stopRequested) {
948
- this.onEvent({ type: 'compaction_cancelled' });
949
- this.onEvent({ type: 'stopped' });
950
- break;
951
- }
952
- // The summarizer FAILED (requestText swallowed a network/429 error — even
953
- // after its retry — and returned null) or came back capped-empty. Trimming
954
- // now would replace real history with "(no summary available)": the exact
955
- // silent data loss the comment above warns about. Leave the history intact
956
- // and let the turn continue un-compacted; if the fat request genuinely
957
- // cannot fit, the provider's context-length error is an honest, recoverable
958
- // failure instead of a vanished transcript.
959
- if (!summary && this.messages.length > 0) {
960
- this.onEvent({ type: 'compaction_cancelled', reason: 'the summary request failed, so nothing was trimmed' });
961
- } else {
962
- // NOW trim, at a split point the boundary rule allows.
963
- const { split, dropped: droppedCount, kept } = this.applyCompactionSplit(maxCtx, summary);
964
- // The array was REPLACED, so every count the ledger held describes messages
965
- // that no longer exist. `sync` would notice on its own (the first/last
966
- // identities no longer match), but resetting here states the intent at the
967
- // point of mutation instead of relying on that check to fire.
968
- this._ledger.reset();
969
- usedNow = this.usedTokens();
970
- // THE REPORT DESCRIBES THE REQUEST THAT WENT OUT, so after a trim it still describes the OLD one.
971
- // Drop it: the next turn falls back to the local estimate until the provider reports again, instead of
972
- // reading a stale figure and compacting a history that was just compacted.
973
- this.ctxReportedTokens = 0;
974
- this.onEvent({
975
- type: 'compacted', before, after: usedNow, kept,
976
- dropped: droppedCount, summary,
977
- });
978
- // SHELL HOOK: PostCompact. Fires after the trim, so a hook can archive the
979
- // summary or record the shrink. Never blocks.
980
- await runShellHooks(this.hookConfig, 'PostCompact',
981
- { before, after: usedNow, kept, dropped: droppedCount, summary }, this.cfg.workspace);
982
- }
983
- }
984
- // ---- tool-result trimming ----
985
- // The cheap pass, and the one that actually runs in practice: a history is
986
- // usually LARGE because of old tool output nobody is reading, not because the
987
- // conversation is long. Bodies are replaced by a short pointer — the message
988
- // list keeps its exact length and roles, so the assistant/tool pairing and the
989
- // cached prefix shape are untouched — and the removed text is copied to disk
990
- // first, so it stays recoverable.
991
- //
992
- // Trigger: the request reached `trimThreshold` (50% by default) of the window.
993
- // Target: keep `trimKeepRatio` (30% by default) of the tool-result TEXT, newest
994
- // first. A different denominator from the trigger on purpose: the trigger asks
995
- // about the window, this asks about the removable output. Skipped while a
996
- // compaction just ran (that already shrank
997
- // things) and above the compaction trigger (compaction is the right tool by
998
- // then, and the two must not fight over the same history).
999
- const trimThreshold = Number.isFinite(this.cfg.trimThreshold) ? this.cfg.trimThreshold : DEFAULT_TRIM_THRESHOLD;
1000
- if (this.cfg.autoTrim !== false && toolResultLimitsEnabled()
1001
- && !this._compactedThisTurn && maxCtx > 0
1002
- && usedNow >= maxCtx * trimThreshold && usedNow < maxCtx * (this.cfg.compactThreshold || 0.85)) {
1003
- const res = trimToolResults(this.messages, {
1004
- sessionId: this.cfg.sessionId,
1005
- keepRatio: Number.isFinite(this.cfg.trimKeepRatio) ? this.cfg.trimKeepRatio : DEFAULT_TRIM_KEEP_RATIO,
1006
- // The model may still be reading the result it was handed last step.
1007
- mustKeep: this._lastToolResultIndex,
1008
- });
1009
- if (res && res.elided > 0) {
1010
- // `trimToolResults` rewrites message CONTENT IN PLACE, so the array is the
1011
- // same one the ledger already counted and its identity check cannot see the
1012
- // change. Without this reset the gauge would keep reporting the PRE-trim
1013
- // total: the trim would look like it freed nothing, and the very next step
1014
- // would compact a history that had already been trimmed.
1015
- this._ledger.reset();
1016
- const after = this.usedTokens();
1017
- this.onEvent({
1018
- type: 'results_trimmed', elided: res.elided, elidedBytes: res.elidedBytes,
1019
- kept: res.kept, keptBytes: res.keptBytes, before: usedNow, after,
1020
- });
1021
- usedNow = after;
1022
- }
1023
- }
1024
- // Live context gauge: report the estimated size of the request about to be
1025
- // sent, so the TUI's context readout is refreshed at every step rather than
1026
- // only once the whole turn ends.
1027
- this.onEvent({ type: 'context', tokens: usedNow, max: maxCtx });
1028
-
1029
- // Inject any user steering messages typed during the previous step.
1030
- // They are appended right after the last assistant/tool round so the
1031
- // model sees "tool callback / user steer" on this next request.
1032
- if (this.steerQueue.length > 0) {
1033
- for (const steerText of this.steerQueue.splice(0)) {
1034
- this.messages.push({ role: 'user', content: steerText });
1035
- this.onEvent({ type: 'steer', text: steerText });
1036
- }
1037
- }
1038
-
1039
- // THE CACHE BOUNDARY: everything BEFORE this index was already sent in an
1040
- // earlier request of this turn and has not changed since. It is captured
1041
- // here — AFTER the previous step's tool results are committed, BEFORE the
1042
- // steering drain appends anything new — so it marks exactly the prefix the
1043
- // provider can reuse.
1044
- //
1045
- // This used to be derived from the message COUNT ("keep the last two"), which
1046
- // is the wrong question. One agent step appends an assistant message plus one
1047
- // tool result PER call, so a step that read four files left five fresh
1048
- // messages; a breakpoint two back sat in the middle of that and the provider
1049
- // had to re-prefill all of it. Counting the boundary from the previous
1050
- // request instead means a step of any size leaves exactly one stable prefix.
1051
- // A COMPACTION REPLACED THE ARRAY, so the boundary measured against the old
1052
- // one no longer describes anything in this one. Clamping would place the
1053
- // breakpoint at a message that never existed when the value was taken.
1054
- if (this._stableEnd > this.messages.length) this._stableEnd = 0;
1055
- if (this._stableEnd !== this.messages.length) this._stableEnd = this.messages.length;
1056
- const cacheEnd = this._stableEnd - 1;
1057
-
1058
-
1059
- // Plugin hooks around the model round-trip. `onBeforeRequest` sees the exact
1060
- // message array being sent (and may mutate it); `onAfterResponse` fires once
1061
- // the stream has been consumed.
1062
- await runHooks('onBeforeRequest', this.messages, this.cfg);
1063
- await this.llm.request(this.messages, handle, cacheEnd);
1064
- await runHooks('onAfterRequest', this.messages, this.cfg);
1065
-
1066
- // An abort ends the turn: keep whatever text arrived, then stop.
1067
- if (this.stopRequested) {
1068
- if (text) this.messages.push({ role: 'assistant', content: text });
1069
- break;
1070
- }
1071
-
1072
- // Append the assistant message. NEVER push one that carries neither text
1073
- // nor tool_calls: upstream rejects it with "content or tool_calls must be
1074
- // set". A signed thinking block counts as content for this protocol — a reply
1075
- // that only thought and called a tool carries nothing else, and dropping it
1076
- // breaks the pairing its tool result depends on.
1077
- const hasText = !!(text && text.trim());
1078
- const hasCalls = toolCalls.length > 0;
1079
- const hasThoughtBlocks = thoughtBlocks.length > 0;
1080
- if (hasText || hasCalls || hasThoughtBlocks) {
1081
- const assistantMsg = {
1082
- role: 'assistant',
1083
- content: hasText ? text : null,
1084
- toolCalls: hasCalls ? toolCalls : undefined,
1085
- // Not part of the answer, never rendered from here: it is the provider's own
1086
- // accounting of its reasoning, replayed verbatim on the next request.
1087
- thoughtBlocks: hasThoughtBlocks ? thoughtBlocks : undefined,
1088
- };
1089
- // Mixin seam: llmResponse - plugins may rewrite the assistant text before it is saved.
1090
- try { const out = await runPatch('llmResponse', { content: assistantMsg.content, toolCalls: assistantMsg.toolCalls }, (c) => c); if (out) { if (out.content !== undefined) assistantMsg.content = out.content; if (out.toolCalls !== undefined) assistantMsg.toolCalls = out.toolCalls; } } catch (e) { console.error('[hncode-plugin] llmResponse error:', e.message); }
1091
- this.messages.push(assistantMsg);
1092
- // Plugin hook: one per assistant message committed to the history. Fired
1093
- // here (the single point where the model's reply lands) rather than at each
1094
- // of the eleven `messages.push` sites, so a plugin sees a coherent message
1095
- // instead of the intermediate bookkeeping pushes.
1096
- await runHooks('onNewMessage', assistantMsg, this.messages);
1097
- }
1098
-
1099
- // ---- if tool calls exist, execute them ----
1100
- if (toolCalls.length > 0) {
1101
- // Execute tools below
1102
- } else if (this.steerQueue.length > 0) {
1103
- const steers = this.steerQueue.splice(0);
1104
- for (const msg of steers) this.messages.push({ role: 'user', content: msg });
1105
- continue;
1106
- } else if (this._truncated && truncationRecoveries < MAX_TRUNCATION_RECOVERIES) {
1107
- if (!hasText) {
1108
- // Truncated with NO text at all: every output token went into reasoning
1109
- // (a reasoning model on a small budget). There is nothing to continue
1110
- // from, and ending the turn here would look like the model simply had
1111
- // nothing to say. Say what actually happened instead.
1112
- this.onEvent({
1113
- type: 'error',
1114
- error: new Error(
1115
- `The model reached its ${this.cfg.maxOutputTokens || 'configured'} output-token limit `
1116
- + 'before producing any text — raise the output limit (HNCODE_MAX_OUTPUT) or lower the thinking effort.',
1117
- ),
1118
- });
1119
- break;
1120
- }
1121
- // The answer was cut off by max_tokens: it is HALF an answer, and it is
1122
- // already committed above with no tool calls. Ask the model to pick up
1123
- // where it stopped instead of ending the turn — otherwise the user reads
1124
- // a sentence that stops mid-word and assumes that was all of it.
1125
- truncationRecoveries++;
1126
- this.messages.push({
1127
- role: 'user',
1128
- // `_harness`: this is the harness talking, not the user. /undo and its
1129
- // picker skip these, and beginTurn does not run for them, so the two
1130
- // stay aligned on what a "prompt" is.
1131
- _harness: true,
1132
- content: 'Your previous message was cut off because it reached the output token limit. Continue from exactly where it stopped — do not repeat what you already wrote, and do not start over.',
1133
- });
1134
- this.onEvent({ type: 'truncation_recovery', attempt: truncationRecoveries });
1135
- continue;
1136
- } else if (!hasText) {
1137
- // No tool calls and no answer text: the model stopped without saying
1138
- // anything. End the turn.
1139
- break;
1140
- } else {
1141
- // The model produced its answer. A steer typed WHILE that answer was
1142
- // streaming still has to be delivered: drain it and take another step.
1143
- // (Checking only at tool boundaries dropped it, because a final answer
1144
- // has no tool boundary.)
1145
- if (this.steerQueue.length > 0) {
1146
- const steers = this.steerQueue.splice(0);
1147
- for (const msg of steers) this.messages.push({ role: 'user', content: msg });
1148
- continue;
1149
- }
1150
- break;
1151
- }
1152
-
1153
- // execute tools
1154
- let allOk = true;
1155
- // Tool-subset enforcement: in Plan/Focus mode the model may still emit a
1156
- // tool that is not exposed. Block it with a fixed message so the model
1157
- // learns it must stick to the allowed subset.
1158
- const modeName = Array.isArray(this.cfg.toolFilter)
1159
- ? (this.cfg.toolFilter.includes('Bash') ? 'Focus' : 'Plan')
1160
- : undefined;
1161
-
1162
- // Gate + execute + hooks for ONE call, with no message bookkeeping: the
1163
- // caller posts the result separately, in call order. Splitting it this way
1164
- // is what makes a parallel batch possible at all — concurrent calls finish
1165
- // out of order, and tool results MUST be appended in the order the model
1166
- // asked for them or the protocol pairing breaks.
1167
- const prepareToolCall = async (tc) => {
1168
- // Tag output produced by THIS tool call so onOutput can route it to the
1169
- // right "Using …" row (a turn can run several tools in sequence).
1170
- this._currentToolId = tc.id;
1171
-
1172
- // MODE GATING COMES FIRST, BEFORE THE APPROVAL PROMPT.
1173
- //
1174
- // A tool the current mode does not allow must be refused WITHOUT asking the user.
1175
- // Asking first was the bug: in Plan mode the tool list is filtered to
1176
- // ['Read','Grep','Glob'], so Bash is not offered — but the model can still emit a
1177
- // call for a tool it saw on an earlier turn, and the approval prompt ran before
1178
- // this check. The user was asked "run this shell command?" in a mode where the
1179
- // answer is always no, and the prompt's own wording offered a choice that did not
1180
- // exist. It also meant a stray call could be APPROVED, and only then refused, which
1181
- // is the worst of both: a decision recorded for something that never ran.
1182
- //
1183
- // These three checks used to sit after the prompt. They all reject outright, so all
1184
- // three belong here — before anything with a side effect, including the session
1185
- // approval that a Ctrl+A on the prompt would have written.
1186
- if (this.noDelegation && DELEGATION_TOOLS.includes(tc.name)) {
1187
- const result = `You CAN'T use ${tc.name}: subagents cannot delegate. Do the work yourself and report the result to the agent that started you.`;
1188
- this.onEvent({ type: 'tool_use', id: tc.id, name: tc.name, args: tc.args });
1189
- return { ok: false, result, editDiff: null, media: false };
1190
- }
1191
- // The list above does not expose AgentSwarm outside swarm mode, but the system
1192
- // prompt describes only ONE shape for it — so refuse a stray call with the fix in
1193
- // the message rather than letting 128 subagents run in a session where the user
1194
- // never opted in.
1195
- if (this.swarmMode !== true && tc.name === 'AgentSwarm') {
1196
- const result = "You CAN'T use AgentSwarm: swarm mode is OFF. For one or two jobs use the Agent tool; for a real fan-out, ask the user to enable it with /swarm.";
1197
- this.onEvent({ type: 'tool_use', id: tc.id, name: tc.name, args: tc.args });
1198
- return { ok: false, result, editDiff: null, media: false };
1199
- }
1200
- if (modeName && !this.cfg.toolFilter.includes(tc.name)) {
1201
- const result = `You CAN'T use this tool on ${modeName} Mode. Allowed: ${this.cfg.toolFilter.join(', ')}.`;
1202
- this.onEvent({ type: 'tool_use', id: tc.id, name: tc.name, args: tc.args });
1203
- return { ok: false, result, editDiff: null, media: false };
1204
- }
1205
-
1206
- // Permission check before executing each tool.
1207
- //
1208
- // The hook may answer with a BOOLEAN (the original contract) or with `{ approved, error }`. The
1209
- // object form exists for the team mailbox, where a refusal travels with a reason the model can act
1210
- // on: "Blocked by user" tells it nothing about what to try instead, and a member that has been
1211
- // refused for a specific reason can re-plan.
1212
- let result = null;
1213
- let ok = true;
1214
- if (this.onApproval) {
1215
- const verdict = await this.onApproval(tc.name, tc.args);
1216
- const approved = verdict && typeof verdict === 'object' ? verdict.approved : verdict;
1217
- if (!approved) {
1218
- const why = verdict && typeof verdict === 'object' && verdict.error ? `: ${verdict.error}` : '.';
1219
- result = `Blocked by user: tool "${tc.name}" was rejected${why}`;
1220
- this.onEvent({ type: 'tool_use', id: tc.id, name: tc.name, args: tc.args });
1221
- return { ok: false, result, editDiff: null, media: false };
1222
- }
1223
- }
1224
-
1225
-
1226
- const tool = getTool(tc.name);
1227
- if (!tool) {
1228
- result = `Error: unknown tool "${tc.name}".`;
1229
- return { ok: false, result, editDiff: null, media: false };
1230
- }
1231
-
1232
- // THE ARGUMENTS MUST MATCH THE TOOL'S OWN SCHEMA.
1233
- //
1234
- // An unknown parameter used to be accepted in silence, and the model had no way to learn that the
1235
- // argument it took trouble to compute was thrown away: it sends `line_offset` to a tool that takes
1236
- // `start_line`, gets a plausible answer computed from defaults, and concludes the tool is broken.
1237
- // Refusing the call names the key and lists the accepted ones, which is the only thing that stops the
1238
- // same mistake being retried with a different spelling.
1239
- const argError = validateToolArgs(tc.args, tool.parameters);
1240
- if (argError) {
1241
- result = `Error: ${tc.name}: ${argError}`;
1242
- this.onEvent({ type: 'tool_use', id: tc.id, name: tc.name, args: tc.args });
1243
- return { ok: false, result, editDiff: null, media: false };
1244
- }
1245
-
1246
-
1247
- // SHELL HOOK: PreToolUse. A non-zero exit blocks the tool, and its
1248
- // message goes back to the model in place of the tool result — that is
1249
- // the whole point of a pre-hook (e.g. refuse a write that fails a lint
1250
- // gate). Checked BEFORE approving/executing so a blocked call never
1251
- // touches the filesystem.
1252
- const pre = await runShellHooks(this.hookConfig, 'PreToolUse',
1253
- { toolName: tc.name, toolArgs: tc.args }, this.ctx.cwd || this.cfg.workspace);
1254
- if (pre.blocked) {
1255
- result = `Blocked by a PreToolUse hook: ${pre.reason}`;
1256
- this.onEvent({ type: 'tool_use', id: tc.id, name: tc.name, args: tc.args });
1257
- return { ok: false, result, editDiff: null, media: false };
1258
- }
1259
- if (this.onToolStart) this.onToolStart(tc.name, tc.args);
1260
- this.onEvent({ type: 'tool_use', id: tc.id, name: tc.name, args: tc.args });
1261
- // Plugin hook: onToolExecute fires BEFORE the tool runs and receives the
1262
- // mutable args object, so a plugin can inspect or adjust a call. Errors
1263
- // are swallowed by runHooks — a broken plugin must not break a turn.
1264
- await runHooks('onToolExecute', tc.name, tc.args, this.ctx);
1265
- try {
1266
- // Mixin seam: toolDispatch - plugins may intercept/modify tool calls before execution.
1267
- let _args = tc.args; let _skip = false;
1268
- try { const out = await runPatch('toolDispatch', { name: tc.name, args: tc.args, ctx: this.ctx }, (c) => c); if (out) { _args = out.args !== undefined ? out.args : tc.args; if (out.skip) _skip = true; } } catch (e) { console.error('[hncode-plugin] toolDispatch error:', e.message); }
1269
- if (_skip) { result = '[skipped by plugin: ' + tc.name + ']'; ok = true; }
1270
- else {
1271
- // RACE THE ABORT SIGNAL, do not merely pass it.
1272
- //
1273
- // `ctx.signal` is handed to every tool, but nothing enforces that a tool LISTENS. A built-in
1274
- // does — Bash kills its process tree — while a plugin tool that ignores it kept running, and
1275
- // this `await` kept waiting for it: Esc reached `interrupt()`, aborted the controller, and the
1276
- // row still said "Using …" until the plugin happened to finish.
1277
- //
1278
- // Aborting the signal now ends the wait immediately whatever the tool is doing. The abandoned
1279
- // promise keeps running detached — a plugin that ignores the signal cannot be forced to stop —
1280
- // but the TURN is no longer held by it, which is what pressing Esc actually asked for.
1281
- const raw = await raceWithAbort(tool.execute(_args, this.ctx), this.toolAbort.signal);
1282
- // `null` means the tool returned a structured MEDIA result: keep the object so the
1283
- // image blocks can be built from it. Only a plain value is stringified.
1284
- const text = toolResultText(raw);
1285
- result = text === null ? raw : text;
1286
- }
1287
- } catch (err) {
1288
- result = `Error running ${tc.name}: ${err.message}`;
1289
- ok = false;
1290
- }
1291
- this.ctx.lastResult = result;
1292
- // Plugin hook: onToolResult fires with the tool's output. A hook may return a
1293
- // (redacted) replacement string — e.g. secret-guard masking keys in a Read
1294
- // result — which is then what the model and transcript receive.
1295
- const hookOut = await runHooks('onToolResult', tc.name, result, this.ctx);
1296
- if (typeof hookOut === 'string') result = hookOut;
1297
- // SHELL HOOK: PostToolUse. Never blocks (the tool already ran); a
1298
- // failure is logged. This is where "format after every edit" lives.
1299
- await runShellHooks(this.hookConfig, 'PostToolUse',
1300
- { toolName: tc.name, toolArgs: tc.args, toolResult: result }, this.ctx.cwd || this.cfg.workspace);
1301
- // SHELL HOOK: PostToolUseFailure. Fires only when the tool failed (an
1302
- // `Error`/`[error:` result, or a thrown run), so a hook can alert or
1303
- // retry without matching on every successful call.
1304
- if (typeof result === 'string' && /^(Error\b|\[error:)/.test(result.trim())) {
1305
- ok = false;
1306
- await runShellHooks(this.hookConfig, 'PostToolUseFailure',
1307
- { toolName: tc.name, toolArgs: tc.args, toolResult: result }, this.ctx.cwd || this.cfg.workspace);
1308
- }
1309
- // Surface the live TODO list so the TUI can render its panel.
1310
- if (tc.name === 'TodoList') {
1311
- this.onEvent({ type: 'todos', todos: this.ctx.todoState || [] });
1312
- }
1313
- // A tool may return a STRUCTURED result instead of a string: ReadMediaFile
1314
- // returns `{ text, media }` so an image can travel as an image.
1315
- const editDiff = this.ctx.lastEditDiff || null;
1316
- const media = !!result && typeof result === 'object' && Array.isArray(result.media);
1317
- this.ctx.lastEditDiff = null;
1318
- return { ok, result, editDiff, media };
1319
- };
1320
-
1321
- // Post one call's outcome: the model's `tool` message, then the TUI event.
1322
- const postToolResult = (tc, out) => {
1323
- if (!out.ok) allOk = false;
1324
- if (out.media) {
1325
- const forModel = out.editDiff
1326
- ? { ...out.result, text: mediaResultText(out.result) + formatEditDiffForModel(out.editDiff) }
1327
- : out.result;
1328
- this.messages.push({ role: 'tool', toolCallId: tc.id, content: forModel });
1329
- this.onEvent({
1330
- type: 'tool_result', id: tc.id, name: tc.name,
1331
- content: out.result._receipt || out.result.text || '[media]',
1332
- editDiff: out.editDiff,
1333
- });
1334
- return;
1335
- }
1336
- // THE MODEL GETS THE TOOL'S OWN RESULT. It used to have the rendered DIFF appended as well, because an Edit
1337
- // reported only "replaced lines 5-7" and the model could not see what it had written. The Edit now quotes
1338
- // the file around the change itself, so appending the diff would show the same lines twice.
1339
- const rawForModel = out.result;
1340
- const shaped = toolResultLimitsEnabled()
1341
- ? shapeToolResult(rawForModel, { sessionId: this.cfg.sessionId, toolCallId: tc.id })
1342
- : { content: rawForModel, spilled: false };
1343
- let _toolContent = shaped.content;
1344
- // Mixin seam: toolResult (sync) - plugins may rewrite what the model receives for this call.
1345
- try { const out = runPatchSync('toolResult', { name: tc.name, content: shaped.content }, (c) => c); if (out && out.content !== undefined) _toolContent = out.content; } catch (e) { console.error('[hncode-plugin] toolResult error:', e.message); }
1346
- this.messages.push({ role: 'tool', toolCallId: tc.id, content: _toolContent });
1347
- // Remember where the newest tool result landed: a trim must never elide the
1348
- // output the model was handed in the step it is about to reason about.
1349
- this._lastToolResultIndex = this.messages.length - 1;
1350
- this.onEvent({
1351
- type: 'tool_result', id: tc.id, name: tc.name,
1352
- // THE UI GETS THE SUMMARY, NOT THE QUOTED FILE. The context lines after an Edit exist for the MODEL, so
1353
- // it does not have to read the same region twice — the user reads the DIFF (`editDiff`) instead, which
1354
- // already shows what changed in place. Passing the whole result drew the same lines twice, once as a
1355
- // diff and once as a block of text.
1356
- content: out.editDiff ? String(out.result).split('\n\n')[0] : out.result,
1357
- editDiff: out.editDiff, spilled: shaped.spilled,
1358
- });
1359
- };
1360
-
1361
-
1362
- for (let i = 0; i < toolCalls.length; i++) {
1363
- if (this.stopRequested) break;
1364
- const tc = toolCalls[i];
1365
- // A RUN of consecutive read-only calls goes out in parallel. Non-
1366
- // destructive by construction (see READ_ONLY_TOOLS), so none of them can
1367
- // observe another's effects. The system prompt has always promised this
1368
- // ("Run independent tool calls in parallel; never parallelize dependent
1369
- // ones") but the loop executed every call one at a time, so a model that
1370
- // issued four Reads paid for four round-trips in sequence.
1371
- if (!READ_ONLY_TOOLS.has(tc.name)) {
1372
- postToolResult(tc, await prepareToolCall(tc));
1373
- continue;
1374
- }
1375
- const batch = [tc];
1376
- while (i + 1 < toolCalls.length && READ_ONLY_TOOLS.has(toolCalls[i + 1].name)) batch.push(toolCalls[++i]);
1377
- if (batch.length === 1) {
1378
- postToolResult(tc, await prepareToolCall(tc));
1379
- continue;
1380
- }
1381
- // Results are posted in CALL order, never completion order.
1382
- const outs = await Promise.all(batch.map((b) => prepareToolCall(b)));
1383
- for (let k = 0; k < batch.length; k++) postToolResult(batch[k], outs[k]);
1384
- }
1385
-
1386
-
1387
- // Did THIS iteration still have tool calls? If the loop runs out of budget
1388
- // right after running them, the turn really is unfinished.
1389
- hadToolCallsOnFinalStep = toolCalls.length > 0;
1390
-
1391
- // Report the context after this step's tool results were appended: that is
1392
- // exactly what the next request will carry, so the gauge grows with history.
1393
- this.onEvent({ type: 'context', tokens: this.usedTokens(), max: maxCtx });
1394
-
1395
- }
1396
-
1397
- // With the cap removed this can only trigger for a caller that set an
1398
- // explicit finite maxSteps: the final iteration still produced tool calls,
1399
- // so the turn genuinely ran out of rounds. Checking the step index alone (as
1400
- // this used to) reported "budget exhausted" for turns that had finished.
1401
- if (Number.isFinite(stepLimit) && !this.stopRequested && hadToolCallsOnFinalStep) {
1402
- this.onEvent({
1403
- type: 'incomplete',
1404
- reason: 'the step budget was exhausted while tools were still being called',
1405
- });
1406
- }
1407
- if (!emittedEnd && this.onEvent) this.onEvent({ type: 'done' });
1408
- // The turn is over, so the inline-reasoning block it may have left open is
1409
- // abandoned: the NEXT user turn starts a fresh one. Without this, a model that
1410
- // never wrote its closing tag would leave the following turn's answer classified
1411
- // as reasoning.
1412
- if (typeof this.llm.resetThink === 'function') this.llm.resetThink();
1413
- // Plugin lifecycle: the turn is over (normally, interrupted, or out of steps).
1414
- // In a finally-equivalent position — every exit path above reaches here.
1415
- await runHooks('onTurnEnd', { messages: this.messages, stopped: this.stopRequested });
1416
- // SHELL HOOK: Stop fires when the turn ends, whether it finished or was
1417
- // interrupted. Never blocks.
1418
- await runShellHooks(this.hookConfig, 'Stop',
1419
- { messages: this.messages, stopped: this.stopRequested, prompt: this._turnPrompt }, this.cfg.workspace);
1420
- }
1421
- }
1
+ // The agent loop: sends the message history to the LLM, consumes the normalized
2
+ // event stream, executes any tool calls, appends results, and repeats until the
3
+ // model answers without tool calls (or a step/interrupt condition is hit).
4
+
5
+ import { LLM, setToolsList } from './llm.js';
6
+ import { tools, combinedTools, getTool, llmTools } from './tools/index.js';
7
+ import { validateToolArgs } from './tools/validate-args.js';
8
+ import { DELEGATION_TOOLS } from './subagent-types.js';
9
+ import { estimateMessagesTokens, estimateRequestOverhead, estimateTokens, measureToolDefTokens, messageTokens, TokenLedger, forgetMessageTokens } from './term.js';
10
+ import { runHooks, runPatch, runPatchSync } from './plugin.js';
11
+ import { loadHooks, runShellHooks } from './hooks.js';
12
+ import {
13
+ shapeToolResult, trimToolResults, DEFAULT_TRIM_THRESHOLD, DEFAULT_TRIM_KEEP_RATIO,
14
+ } from './tool-result.js';
15
+ // ---- compaction text (kimi's shapes) ----------------------------------------
16
+ // These mirror kimi-code's contextMemory/compactionHandoff.ts so a compacted
17
+ // history reads the same way there.
18
+
19
+ // Wraps harness-generated text so it reads as a system note rather than something
20
+ // the user actually typed.
21
+ function wrapSystemReminder(content) {
22
+ return `<system-reminder>\n${String(content).trim()}\n</system-reminder>`;
23
+ }
24
+
25
+ // ---- token accounting -------------------------------------------------------
26
+ // The provider reports the numbers; this folds one report into a running total.
27
+ // A field the provider did not send is left as it was, because "not reported" and
28
+ // "zero" are different facts: summing undefined into 0 would claim a model never
29
+ // used a cache it simply does not measure.
30
+ export function addUsage(total, u) {
31
+ const out = { ...(total || {}) };
32
+ if (!u) return out;
33
+ for (const key of ['input', 'output', 'cached', 'cacheWrite', 'reasoning']) {
34
+ if (typeof u[key] === 'number' && Number.isFinite(u[key])) out[key] = (out[key] || 0) + u[key];
35
+ }
36
+ // How many REQUESTS contributed, so a reader can tell one big call from many
37
+ // small ones with the same token count. Counted on the completion side, which
38
+ // every protocol reports exactly once per request — Anthropic splits one
39
+ // request into two usage events (input at message_start, output at
40
+ // message_delta), so counting events would report double.
41
+ if (u.output !== undefined) out.calls = (out.calls || 0) + 1;
42
+ return out;
43
+ }
44
+
45
+
46
+ const COMPACTION_SUMMARY_PREFIX = [
47
+ 'The conversation so far has been compacted to free up context. What follows is your own working summary of this task — use it to continue your train of thought rather than starting over.',
48
+ 'Treat it as notes, not proof: where it says a step was done, tests passed, or a fix worked, verify that yourself before relying on it.',
49
+ 'User messages earlier in this context are preserved verbatim from the compacted conversation. The summary records which earlier requests were already addressed.',
50
+ ].join(' ');
51
+
52
+ // The instruction given to the model that WRITES the summary. Adapted from
53
+ // kimi-code's fullCompaction/compaction-instruction.md: it is a handoff for the
54
+ // model that resumes, not a recap for a human. The language rule matters — without
55
+ // it a Chinese conversation produced an English summary and the resumed context
56
+ // lost the vocabulary the task was being discussed in.
57
+ const COMPACTION_INSTRUCTION = [
58
+ 'You are about to run out of context. Create a handoff summary for the model that will resume this task after the earlier conversation is cleared.',
59
+ '',
60
+ 'This message is a direct task, not part of the above conversation.',
61
+ '',
62
+ 'Write it in the same language the conversation has been using — do not switch to English just because these instructions are in English.',
63
+ '',
64
+ 'Make the summary self-sufficient: the next turn will see only the preserved messages and this summary. In your own words, preserve what is genuinely needed to continue:',
65
+ '',
66
+ '- What the latest request actually asks for, and any ambiguity you have already resolved. If the latest request is large (a big paste or file) and may be truncated in the kept messages, preserve the actual ask.',
67
+ '- The instructions and constraints currently in force (user preferences, project rules, environment limits), with settled decisions kept separate from open questions, so neither is reopened nor mistaken for decided.',
68
+ '- What has actually been done, at high fidelity: exact commands run, exact file paths touched, and their results — the concrete values, key lines and error text — not just the commands. Keep only the final working version of any code; drop intermediate attempts and already-resolved errors.',
69
+ '- What you still do not know: files referenced but not read, APIs assumed but unseen, questions the user has not answered. Name these gaps so the next turn checks them instead of assuming.',
70
+ '- The forward plan: the exact next step, the sequence to finish, decisions already made for those steps, foreseeable obstacles and how you mean to handle them.',
71
+ '',
72
+ 'Be honest about uncertainty. If an earlier step claimed something was done but was never verified, say so plainly and treat it as unverified rather than fact.',
73
+ '',
74
+ 'Be concise and proportional: a long multi-step task warrants detail, a nearly finished exchange needs only a sentence or two.',
75
+ '',
76
+ 'Respond with text only. Do not call any tools. Any tool-call syntax in your answer is discarded and scores the handoff as failed.',
77
+ '',
78
+ 'That includes XML-style tool syntax such as `<||DSML||invoke name="...">` or `<function_call>`: no such tag is',
79
+ 'recognised here, so it becomes part of the summary and the next turn reads it as a step that happened.',
80
+ ].join('\n');
81
+ // Trailing note: the model should RESUME, not answer the summary.
82
+
83
+ // A summariser can answer with tool-call syntax even when no tools were offered — the format is in its
84
+ // training data, and a model interrupted mid-workflow reaches for it. Nothing was called, so the text is
85
+ // noise, and left in a handoff summary the next turn reads it as a step that happened.
86
+ //
87
+ // The shapes covered are the ones these models actually emit: a special-token block (`<|tool_call|>`), a
88
+ // fenced ```tool_call block, and a bare JSON object that claims a `name` and `arguments`. Only a block that
89
+ // occupies whole lines is removed, so prose that merely mentions calling a tool survives.
90
+ function stripToolCallText(text) {
91
+ if (typeof text !== 'string' || !text) return text || '';
92
+
93
+ // NOTHING WAS CALLED, SO THE BLOCK IS NOISE — but removing it outright can leave nothing at all.
94
+ //
95
+ // A summariser that answers ONLY with a tool call produced no summary: stripping to '' makes the caller
96
+ // treat the compaction as failed, and the fallback there is to drop the history. So the stripped text is
97
+ // measured: if it lost its substance, the original is kept VERBATIM with a note saying what it is. A
98
+ // confusing summary is recoverable; a discarded one is not.
99
+ let out = text;
100
+ // A special-token block: closed form, or an unterminated one running to the end of its line.
101
+ out = out.replace(/<\|tool_call\|>[^\n]*(?:<\|\/tool_call\|>)?/g, '');
102
+ // A fenced block form.
103
+ out = out.replace(/```tool_call[\s\S]*?```/g, '');
104
+ // A bare JSON object on its own lines that declares a tool invocation.
105
+ out = out.replace(/^\s*\{[^\n]*"name"\s*:\s*"[^"]+"[^\n]*"arguments"[^\n]*\}\s*$/gm, '');
106
+ // THE DSML DIALECT. Some models write a tool call as an XML-ish block with a doubled delimiter around the
107
+ // tag name (`<||DSML||invoke name="…">`), which none of the patterns above match. It arrives as a whole
108
+ // block, so it is removed as one — an unterminated block included, since a summariser cut off by the token
109
+ // limit leaves exactly that.
110
+ out = out.replace(/<\|+\|?DSML\|?\|+[\s\S]*?(?=<\/\|\|+DSML\|\|+>|$)/gi, '');
111
+ out = out.replace(/<\/?\|+\|?DSML\|?\|+[^>]*>/gi, '');
112
+ // THE `<function_call>` DIALECT and its `<tool_call>` sibling: a JSON payload wrapped in a tag. Removed with
113
+ // its body when both tags are present, and on its own when the body follows on the next line.
114
+ out = out.replace(/<(function_call|tool_call)>[\s\S]*?<\/\1>/gi, '');
115
+ out = out.replace(/<(function_call|tool_call)>[^\n]*/gi, '');
116
+ out = out.replace(/\n{3,}/g, '\n\n').trim();
117
+
118
+ if (out.length > 0) return out;
119
+
120
+ // Every remaining character was a tool call: keep the original, marked for what it is.
121
+ return [
122
+ '(The summariser answered with a tool call instead of a summary. No tool was actually run — the text is',
123
+ 'reproduced below unchanged so nothing is lost. Treat it as a summary that was never written.)',
124
+ '',
125
+ text.trim(),
126
+ ].join('\n');
127
+ }
128
+
129
+ const COMPACTION_CONTINUATION_TEXT = 'Context compaction is complete — continue the work that was in progress when it began.';
130
+
131
+ // Clip to a TOKEN budget, counting non-ASCII as one token per character (the same
132
+ // rule estimateTokens uses). Slicing by characters is wrong for CJK text: 4000
133
+ // Chinese characters are ~4000 tokens, not ~1000.
134
+ function clipToTokens(text, maxTokens) {
135
+ if (maxTokens <= 0) return '';
136
+ const s = String(text ?? '');
137
+ let ascii = 0, nonAscii = 0, end = 0;
138
+ for (const ch of s) {
139
+ if (ch.codePointAt(0) <= 127) ascii++; else nonAscii++;
140
+ if (Math.ceil(ascii / 4) + nonAscii > maxTokens) break;
141
+ end += ch.length;
142
+ }
143
+ return end >= s.length ? s : s.slice(0, end) + '\n…[clipped]';
144
+ }
145
+
146
+ // May the history be split between `index` and `index + 1`? Mirrors kimi's
147
+ // canSplitAfter — a split is illegal when it would orphan a tool exchange:
148
+ // * the message before the cut is a user message (would start the kept part
149
+ // mid-turn), or
150
+ // * it is an assistant message that still has tool calls, or
151
+ // * the message after the cut is a tool result, or
152
+ // * the prefix ends inside an open tool exchange (more results to come).
153
+ // Exported for the headless -p path (index.js), which must trim a resumed
154
+ // history on the same legal boundaries the compaction logic uses.
155
+ export function canSplitAfter(messages, index) {
156
+ if (index < 0 || index >= messages.length) return false;
157
+ const m = messages[index];
158
+ if (!m) return false;
159
+ if (m.role === 'user') return false;
160
+ if (m.role === 'assistant' && Array.isArray(m.toolCalls) && m.toolCalls.length > 0) return false;
161
+ const next = messages[index + 1];
162
+ if (next && next.role === 'tool') return false;
163
+ return !prefixEndsWithOpenToolExchange(messages, index);
164
+ }
165
+
166
+ // True when the prefix [0..index] ends with an assistant that issued MORE tool
167
+ // calls than have results so far — cutting there would leave a call unanswered.
168
+ function prefixEndsWithOpenToolExchange(messages, index) {
169
+ if (!messages[index] || messages[index].role !== 'tool') return false;
170
+ let results = 0;
171
+ for (let i = index; i >= 0; i--) {
172
+ const m = messages[i];
173
+ if (!m) return false;
174
+ if (m.role === 'tool') { results++; continue; }
175
+ return m.role === 'assistant' && Array.isArray(m.toolCalls) && m.toolCalls.length > results;
176
+ }
177
+ return false;
178
+ }
179
+
180
+
181
+ // A short, stable key for the prompt cache, derived from the conversation's
182
+ // first user message. Stability is the whole point: the same conversation must
183
+ // produce the same key on every turn, so a cheap deterministic hash beats a
184
+ // random id. (Different conversations may collide — that is harmless, it only
185
+ // means the provider's routing key is shared.)
186
+ function hashKey(s) {
187
+ let h = 0x811c9dc5;
188
+ const str = String(s || '');
189
+ for (let i = 0; i < str.length; i++) {
190
+ h ^= str.charCodeAt(i);
191
+ h = (h * 0x01000193) >>> 0;
192
+ }
193
+ return h.toString(36) + '-' + str.length.toString(36);
194
+ }
195
+
196
+ // Render what an Edit actually changed, for the MODEL's tool result.
197
+
198
+ // Render what an Edit actually changed, for the MODEL's tool result.
199
+ //
200
+ // The UI has always received the edit through `editDiff` (see the tool_result
201
+ // event), but the message pushed into `this.messages` carried only the one-line
202
+ // receipt ("Edited a.js: replaced 1 occurrence(s)."). The model was therefore
203
+ // asked to verify its own edit from a sentence that describes nothing: it could
204
+ // not see WHAT changed, so a wrong-but-successful edit looked identical to a
205
+ // correct one. The diff is appended here — after the receipt — so the model
206
+ // reads what it did.
207
+ //
208
+ // The format is the usual unified one (`- old`, `+ new`) with the line number
209
+ // from the file, and it is deliberately indented two spaces: a tool result is
210
+ // rendered as plain text, and the indent keeps the +/- marks from reading as
211
+ // part of the JSON envelope some providers wrap tool output in.
212
+ export function formatEditDiffForModel(diff, maxLines = 400) {
213
+ if (!diff || typeof diff.old !== 'string' || typeof diff.new !== 'string') return '';
214
+ const split = (s) => String(s).replace(/\r\n/g, '\n').split('\n');
215
+ const oldLines = split(diff.old);
216
+ const newLines = split(diff.new);
217
+ const startLine = Number(diff.startLine) > 0 ? Number(diff.startLine) : 1;
218
+ const out = [];
219
+ out.push('');
220
+ out.push('--- diff ---');
221
+ // Unchanged lines above and below, unmarked, so the change can be LOCATED. Without them this
222
+ // was a quoted block with no indication of where in the file it landed — and identical-looking
223
+ // code appears in many places, so neither the model nor the user could confirm the edit hit
224
+ // the intended one rather than a same-text block further down.
225
+ const before = (diff.context && Array.isArray(diff.context.before)) ? diff.context.before : [];
226
+ const after = (diff.context && Array.isArray(diff.context.after)) ? diff.context.after : [];
227
+ for (const c of before) out.push(' ' + String(c.n).padStart(4) + ' ' + c.text);
228
+ let n = startLine;
229
+ for (const l of oldLines) out.push(' ' + String(n++).padStart(4) + ' - ' + l);
230
+ n = startLine;
231
+ for (const l of newLines) out.push(' ' + String(n++).padStart(4) + ' + ' + l);
232
+ for (const c of after) out.push(' ' + String(c.n).padStart(4) + ' ' + c.text);
233
+ // A whole-file edit (a Write-sized `new`) must not be echoed back in full.
234
+ if (out.length > maxLines + 3) {
235
+ const hidden = out.length - (maxLines + 3);
236
+ out.length = maxLines + 3;
237
+ out.push(' … ' + hidden + ' more diff line(s) omitted');
238
+ }
239
+ return out.join('\n');
240
+ }
241
+
242
+ // Final instruction appended to the system prompt (see SYSTEM_PROMPT).
243
+ // (The wording lives in SYSTEM_PROMPT itself, under "Finishing a turn".)
244
+
245
+
246
+ // Tools whose execution cannot affect what any OTHER tool call in the same step
247
+ // observes, and cannot be affected by one. Two read-only tools therefore have no
248
+ // reason to run one after the other, and the agent runs a consecutive run of them
249
+ // in parallel (see the tool loop in run()). Anything that writes, spawns, shells
250
+ // out or mutates the working tree is excluded — that rules out `Git` (it can
251
+ // stage/commit/switch), `ReadMediaFile` (read-only, but it decodes megabytes of
252
+ // media and is never the bottleneck) and every delegation tool. Claude Code
253
+ // expresses the same idea as `isConcurrencySafe()` on each tool; this is the flat
254
+ // version of it, matching hncode's tool registry.
255
+ const READ_ONLY_TOOLS = new Set([
256
+ 'Read', 'Grep', 'Glob', 'FileLines', 'FetchURL', 'WebSearch',
257
+ 'TaskList', 'TaskOutput',
258
+ ]);
259
+
260
+ // Debug switch for the size/age control in tool-result.js, mirroring Claude
261
+ // Code's env-gated knobs. Set HNCODE_TOOL_RESULT_LIMITS=off to send every tool
262
+ // result verbatim (useful when a spill is suspected of hiding something the
263
+ // model needed).
264
+ function toolResultLimitsEnabled() {
265
+ return !/^(0|off|false|no)$/i.test(String(process.env.HNCODE_TOOL_RESULT_LIMITS || ''));
266
+ }
267
+
268
+ /**
269
+ * A tool's return value, as the STRING the model can be sent.
270
+ *
271
+ * Every tool in `src/tools/` returns a plain string except the team tools, which return
272
+ * `{ content }` / `{ error }`. That object went into the `tool` message verbatim, and a provider
273
+ * that expects a string rejects the NEXT request with `missing type field in content item at
274
+ * index 0` — so a teammate's first `SendMessage` worked and then the conversation died, one
275
+ * message in. The symptom was a team that says hello and then never answers again.
276
+ *
277
+ * Returns `null` for the one shape that must stay an OBJECT: `ReadMediaFile` returns
278
+ * `{ text, media: [...] }`, and the media parts travel as structured blocks the caller builds
279
+ * from the object. Stringifying that would attach no image at all, so the caller keeps it.
280
+ *
281
+ * Normalised here, at the single point every tool result passes through, rather than in the
282
+ * team tools: a second tool family making the same choice cannot reintroduce the bug.
283
+ */
284
+ /**
285
+ * Settle `promise`, or reject as soon as `signal` aborts — whichever happens first.
286
+ *
287
+ * A tool is GIVEN the abort signal but cannot be forced to observe it. Built-ins do (Bash kills its
288
+ * process tree); a plugin tool that ignores it kept running, and the caller's `await` kept waiting, so
289
+ * pressing Esc during a slow plugin tool changed nothing on screen until the plugin finished on its own.
290
+ *
291
+ * Racing ends the WAIT regardless. The abandoned promise is left to settle detached — an unobserved
292
+ * rejection would otherwise surface as an unhandled rejection — and the turn moves on, which is what
293
+ * the key was asking for. It cannot stop the plugin's work, and this comment says so rather than
294
+ * implying otherwise.
295
+ */
296
+ function raceWithAbort(promise, signal) {
297
+ if (!signal) return promise;
298
+ if (signal.aborted) return Promise.reject(new Error('aborted'));
299
+ return new Promise((resolve, reject) => {
300
+ const onAbort = () => reject(new Error('aborted'));
301
+ signal.addEventListener('abort', onAbort, { once: true });
302
+ Promise.resolve(promise).then(
303
+ (v) => { signal.removeEventListener('abort', onAbort); resolve(v); },
304
+ (e) => { signal.removeEventListener('abort', onAbort); reject(e); },
305
+ );
306
+ // A tool that resolves AFTER the abort must not become an unhandled rejection.
307
+ Promise.resolve(promise).catch(() => {});
308
+ });
309
+ }
310
+
311
+ function toolResultText(value) {
312
+ if (typeof value === 'string') return value;
313
+ if (value == null) return '';
314
+ if (typeof value === 'object') {
315
+ // Leave a media result alone — the caller needs the parts, not a sentence about them.
316
+ if (Array.isArray(value.media)) return null;
317
+ if (typeof value.content === 'string') return value.content;
318
+ if (typeof value.error === 'string') return value.error;
319
+ if (typeof value.text === 'string') return value.text;
320
+ try { return JSON.stringify(value); } catch { return String(value); }
321
+ }
322
+ return String(value);
323
+ }
324
+
325
+
326
+
327
+ export const SYSTEM_PROMPT = `You are hncode, a coding agent in the user's terminal on ${process.platform}.
328
+ You work inside a workspace directory using the tools provided.
329
+
330
+ Tools:
331
+ - Read a file before editing it; never guess contents or edit code you haven't read.
332
+ - Prefer Edit over Write for existing files.
333
+ - If a tool fails, read the error and fix your approach. After 2 failed attempts on the same goal, stop and report the blocker.
334
+ - Independent tool calls may run in parallel; never parallelize dependent ones.
335
+ - One edit at a time. Every edit shifts the lines below it, so the line numbers you read a
336
+ moment ago are stale for the next one: read the file again before the next edit, or work
337
+ from the lines the previous edit printed. An edit whose range no longer matches the file
338
+ writes a neighbouring line a second time, and the duplicate looks like damage — so the
339
+ fix is to remove the duplicated line, never to restate another one.
340
+
341
+ Acting:
342
+ - Unless the user is explicitly asking for a plan, asking a question about the code, or brainstorming,
343
+ assume they want the work DONE. Say less and do more: implement the change rather than describing it.
344
+ - Carry the task through implementation and verification in this turn. Do not stop at analysis, at a
345
+ partial fix, or at a list of things you would do next.
346
+ - New project, no prior context: be ambitious, use your judgement on structure.
347
+ Existing codebase: be surgical. Touch only what the task needs — no renames, no reorganising,
348
+ no drive-by fixes.
349
+ - Read the neighbours before you write: match the naming, error handling and comment density you see.
350
+ - Do not re-read a file after editing it, and do not re-run a search you already have results for.
351
+ A successful edit tool call already proves it worked.
352
+
353
+ Scope:
354
+ - Do only what was asked. Do not refactor or "improve" unrelated code.
355
+ - Do not fix unrelated bugs or broken tests — mention them instead; they are not yours to change.
356
+ - If the request is ambiguous, ask one short clarifying question.
357
+ - State any assumption you make.
358
+ - Might be a dirty git worktree. Never revert changes you did not make. Never run a destructive command
359
+ (git reset --hard, git checkout --) unless the user asked for it. If you notice an unexpected change
360
+ you did not make, stop and ask.
361
+
362
+ Verifying:
363
+ - Run the narrowest check that exercises your change first, then widen.
364
+ - In auto/yolo mode, run tests and lint yourself without asking.
365
+ - In ask mode, do not burn the user's time on slow test suites mid-task: say what you would run and
366
+ let them confirm.
367
+ - Do not add tests to a codebase that has none. Do not add a formatter that the project did not configure.
368
+ - If you could not verify something, say so plainly. Do not imply a test passed when you did not run it.
369
+
370
+ Finishing:
371
+ - Never stop silently after a tool call; end every turn with a written answer in the user's language.
372
+ - Report briefly: what changed, and how you verified it. If something failed, say what you tried and what you need.
373
+ - Never claim success without evidence. Cite file:line for referenced code.
374
+ - Be concise. No filler, no restating the request or explaining tool output that already spoke for itself.
375
+ - If context is running low, call /compact to shrink history.
376
+ `;
377
+
378
+ // THE INLINE-REASONING INSTRUCTION, AND WHEN IT IS NEEDED AT ALL.
379
+ //
380
+ // A model that has its OWN reasoning channel does not need to be told to wrap its thoughts
381
+ // in a tag: Anthropic sends `thinking` blocks, OpenAI and DeepSeek send `reasoning_content`,
382
+ // and hncode renders all of them as the thinking block. Asking such a model for
383
+ // `<|thinking|>…<|/thinking|>` on top of that asks for the SAME reasoning twice — once in the
384
+ // channel the API provides and once as literal text in the answer, which is then either
385
+ // duplicated on screen or left in the reply as noise.
386
+ //
387
+ // So the instruction is only attached for a model with NO native channel: there the tag is
388
+ // the only way to separate reasoning from the answer, and the transcript depends on it.
389
+ //
390
+ // It is kept OUT of SYSTEM_PROMPT so that the prompt stays static — a static prefix is what
391
+ // providers cache, and a suffix that changes with the model would break that caching for
392
+ // every request that follows it.
393
+ export const THINKING_TAGS_INSTRUCTION = `Reasoning:
394
+ - Put ALL of your internal reasoning inside <|thinking|>...<|/thinking|> tags, and always emit BOTH the
395
+ opening and the closing tag. Do not omit the tags, do not abbreviate them, and do not leave the block
396
+ unclosed.
397
+ - Everything outside <|thinking|>...<|/thinking|> is what the user reads: keep it to the answer itself —
398
+ what you did and what you found. Never repeat or summarise your reasoning there.
399
+ - Keep the tags exactly as written: <|thinking|> and <|/thinking|>. Do not emit any other variant. The
400
+ bars matter: a plain <think> is ordinary text that may appear in code or prose, and a bare
401
+ "thinking" is a word this very instruction uses.`;
402
+
403
+ /**
404
+ * Does this model need to be told to wrap its reasoning in tags?
405
+ *
406
+ * `cfg.reasoning` is the model's own declaration that it can think — Anthropic's `thinking`,
407
+ * OpenAI's `reasoning_effort`, DeepSeek's `reasoning_content`. A model that can do that
408
+ * reports its reasoning through the channel the API gives it, so the tag instruction is
409
+ * redundant at best and asks for doubled output at worst.
410
+ *
411
+ * A model that cannot think has no channel to use, so the tag is the ONLY way to keep the
412
+ * reasoning out of the answer.
413
+ */
414
+ export function needsThinkingTags(cfg) {
415
+ if (!cfg) return true;
416
+ // An explicit choice wins: someone who wants the tag on a reasoning model (or off for
417
+ // one that has no channel) should not have to argue with the detection. The setting is
418
+ // three-state — `auto`, `on`, `off` — and the old booleans are still honoured.
419
+ const choice = cfg.thinkingTags;
420
+ if (choice === 'on' || choice === true) return true;
421
+ if (choice === 'off' || choice === false) return false;
422
+ return cfg.reasoning !== true;
423
+ }
424
+
425
+ /** Plain text of a structured tool result, for the model and the transcript. */
426
+ function mediaResultText(r) {
427
+ if (!r || typeof r !== 'object') return String(r == null ? '' : r);
428
+ return String(r.text == null ? '' : r.text);
429
+ }
430
+
431
+ export class Agent {
432
+ constructor({ cfg, messages, onEvent, maxSteps = 0, onToolStart, canInterrupt = () => false, onApproval }) {
433
+ this.cfg = cfg;
434
+ this.messages = messages;
435
+ this.onEvent = onEvent;
436
+ this.maxSteps = maxSteps;
437
+ this.onToolStart = onToolStart; // (name, args) => void (for headless/TTY overlays)
438
+ // Ensure the LLM client knows the bare tool specs (the client wraps them per-protocol).
439
+ // A toolFilter (array of tool names) limits which tools are exposed — used
440
+ // by Plan mode (read-only subset) and Focus mode (minimal subset first).
441
+ // `cfg.noDelegation` marks this as a SUBAGENT: delegation tools are removed
442
+ // even if the filter would have allowed them. The catalog already excludes
443
+ // them from every profile; this is the hard backstop that also covers the
444
+ // `null` (= everything) case, so a subagent can never spawn another agent.
445
+ const filtered = (Array.isArray(cfg.toolFilter) && cfg.toolFilter.length
446
+ ? combinedTools().filter((t) => cfg.toolFilter.includes(t.name))
447
+ : combinedTools()
448
+ )
449
+ .filter((t) => !(cfg.noDelegation && DELEGATION_TOOLS.includes(t.name)))
450
+ // AgentSwarm is gated behind swarm mode, like Agent is gated behind the user
451
+ // having asked for delegation. It is not enough to describe the mode in the
452
+ // system prompt: the tool was offered on EVERY turn, so the model could fan a
453
+ // task out to 128 subagents in a session where the user never opted in — and
454
+ // the prompt's own rule ("never call this on your own initiative") was not
455
+ // backed by anything. Off unless /swarm turned the mode on; the Agent tool
456
+ // stays available for a single, deliberate delegation.
457
+ .filter((t) => !(t.name === 'AgentSwarm' && !cfg.swarm));
458
+ // Kept as the process-wide FALLBACK for LLM instances that never register
459
+ // their own list (doctor's connectivity probe). Every real agent registers
460
+ // its list on its own LLM below — requests no longer read whichever Agent
461
+ // happened to be constructed last.
462
+ setToolsList(filtered);
463
+ // THE REAL COST OF THE TOOLS, measured once per agent.
464
+ //
465
+ // The context gauge charged a flat 8 tokens per tool, which is short by an order of magnitude — the
466
+ // schemas of these 68 tools come to about 15 900 tokens. That figure was missing from every
467
+ // usage estimate, so the app's own count ran tens of thousands below the provider's.
468
+ //
469
+ // Measured here because this is the only place that knows the FINAL set: `toolFilter`, the
470
+ // subagent block and the swarm gate above all change what is sent, and a number derived from
471
+ // `cfg.toolFilter` alone would price tools the model never sees.
472
+ this.toolDefTokens = measureToolDefTokens(filtered);
473
+ // ALSO on `cfg`, because the TUI's gauge writers live outside this object and price a request as
474
+ // `estimateMessagesTokens(...) + cfg.toolDefTokens`. Without this line those readers saw `undefined`
475
+ // and silently fell back to zero, so every restore and every /trim reported a number short by the
476
+ // whole tool block — the same fixed gap, from a different cause.
477
+ if (this.cfg && typeof this.cfg === 'object') this.cfg.toolDefTokens = this.toolDefTokens;
478
+ // A block for the direct-call path too: the model can still emit a tool call
479
+ // for a tool that is not exposed, so refuse it here rather than at execution.
480
+ this.noDelegation = !!cfg.noDelegation;
481
+ // Mirrors the filter above for the direct-call path — a tool the model was told
482
+ // about on an earlier turn can still be emitted after /swarm goes off.
483
+ this.swarmMode = !!cfg.swarm;
484
+ // AbortSignal handed to every tool so a long-running one (Bash) is killed
485
+ // when the user presses Esc / Ctrl-C — otherwise the command keeps running
486
+ // after the turn was interrupted.
487
+ this.toolAbort = new AbortController();
488
+ // Reuse an incoming task store when the caller provides one. Background
489
+ // tasks OUTLIVE the turn that started them (their process is detached), so a
490
+ // fresh `{}` per Agent made them vanish from the UI on the next turn while
491
+ // still running. The TUI passes its persistent `state.tasks` through cfg.
492
+ this.ctx = { ...cfg, tasks: cfg.tasks || {}, todoState: Array.isArray(cfg.todoState) ? cfg.todoState.slice() : [], allowExternal: !!cfg.allowExternal, signal: this.toolAbort.signal };
493
+ // Live output stream for a RUNNING tool (Bash): the tool calls this with raw
494
+ // chunks and the agent tags them with the id of the tool call in flight, so
495
+ // the TUI can append them to the matching "Using …" row while it runs.
496
+ this._currentToolId = null;
497
+ this.ctx.onOutput = (chunk) => {
498
+ if (chunk && this._currentToolId) this.onEvent({ type: 'tool_output', id: this._currentToolId, chunk });
499
+ };
500
+ // A command whose output ended mid-line and then went quiet is most likely sitting at a prompt. The tool
501
+ // cannot answer it for the user, so it says so and the UI offers the composer.
502
+ this.ctx.onStdinWaiting = (waiting) => {
503
+ if (this._currentToolId) this.onEvent({ type: 'tool_stdin_waiting', id: this._currentToolId, waiting: !!waiting });
504
+ };
505
+ // The Read snapshot pool lives ON THE AGENT, not on a per-turn ctx. It records
506
+ // what the model has read (and the hashes at that moment) so a later Edit can
507
+ // refuse to act on a stale snippet. /undo rewinds files on disk, i.e. it makes
508
+ // those hashes describe content that is no longer there — the TUI clears this
509
+ // pool right after a rewind so the next Edit is not rejected as stale.
510
+ this.readPool = new Map();
511
+ this.ctx.readPool = this.readPool;
512
+ // `fork` (the Agent tool) snapshots THIS conversation into the subagent. The
513
+ // tool reads `ctx._parentMessages`. This must be a GETTER, not the array
514
+ // itself: auto-compaction REPLACES `this.messages` with a trimmed history, so
515
+ // a retained reference kept pointing at the pre-compaction array — a fork
516
+ // after a compaction would hand the subagent exactly the oversized history
517
+ // that was just cut, and could push it straight past its own window.
518
+ Object.defineProperty(this.ctx, '_parentMessages', {
519
+ get: () => this.messages,
520
+ enumerable: true,
521
+ configurable: true,
522
+ });
523
+ // Prompt-cache key: identify the SESSION, not the request, so the cached
524
+ // prefix is reused across turns instead of thrashing. The caller may pass one
525
+ // (the TUI knows the session id); otherwise derive a stable value from the
526
+ // first user message so repeated runs of the same conversation still share a
527
+ // prefix. A subagent inherits the parent's key (same conversation family).
528
+ if (cfg.sessionId == null) {
529
+ const firstUser = (Array.isArray(messages) ? messages : []).find((m) => m.role === 'user' && typeof m.content === 'string');
530
+ cfg = { ...cfg, sessionId: firstUser ? hashKey(firstUser.content) : 'default' };
531
+ this.cfg = cfg;
532
+ }
533
+ this.llm = new LLM(cfg);
534
+ // THIS agent's tool defs ride on THIS instance. The module-global was overwritten
535
+ // by every `new Agent()` in the process — a subagent, swarm member or teammate
536
+ // constructed while a parent request was being built swapped the parent's tool
537
+ // list mid-turn, silently stripping Edit/Bash from its next request.
538
+ this.llm.setTools(filtered);
539
+ this.stopRequested = false;
540
+ // Auto-compaction is allowed at most once per TURN (not per step). Reset here so
541
+ // a caller that reuses one Agent across turns still gets a fresh allowance.
542
+ this._compactedThisTurn = false;
543
+ // THE PROMPT-CACHE BOUNDARY: how many messages an earlier request of this turn
544
+ // has already sent. Everything below that index is stable and can carry a cache
545
+ // breakpoint. Reset per turn because a new turn opens with a new user message, so
546
+ // the previous turn's boundary would describe a prefix this one never sent.
547
+ this._stableEnd = 0;
548
+ // Rolling context-token total for `this.messages` (see usedTokens). It holds no
549
+ // messages of its own, only the count of what it has already priced, so a
550
+ // compaction that replaces the array simply falls out of the fast path.
551
+ this._ledger = new TokenLedger();
552
+ this.onApproval = onApproval; // async (toolName, args) => boolean
553
+ // Shell hooks (Claude Code-style): user-configured commands run at lifecycle
554
+ // events. ALWAYS stored as a `{ hooks: {Event: [...]} }` config, which is the
555
+ // shape runShellHooks() reads. A caller may inject one (tests / the TUI,
556
+ // which reloads per turn); otherwise it is read from disk for this workspace.
557
+ this.hookConfig = cfg.hookConfig
558
+ ? (cfg.hookConfig.hooks ? cfg.hookConfig : { hooks: cfg.hookConfig })
559
+ : { hooks: loadHooks(cfg.workspace).hooks };
560
+ // The turn's user prompt, for the UserPromptSubmit hook. Set by run().
561
+ this._turnPrompt = '';
562
+ // Messages the user types while the agent is streaming. They are injected
563
+ // as user messages right AFTER the current round of tool calls, so the
564
+ // model sees "tool callback / user steer" together on the next request —
565
+ // exactly like kimi-code's steer (no separate turn feel).
566
+ this.steerQueue = [];
567
+ }
568
+
569
+ // Queue a steering message typed while streaming. It takes effect once the
570
+ // in-flight tool calls finish and the loop asks the model again.
571
+ steer(text) {
572
+ if (text && text.trim()) this.steerQueue.push(String(text).trim());
573
+ }
574
+ // True when a steer is pending injection.
575
+ get hasSteer() { return this.steerQueue.length > 0; }
576
+
577
+ interrupt() {
578
+ this.stopRequested = true;
579
+ try { this.toolAbort.abort(); } catch {}
580
+ if (this.llm) this.llm.abort();
581
+ // The compaction summarizer is a SEPARATE LLM instance; abort it too, or an
582
+ // auto-compaction in flight cannot be interrupted (Esc did nothing until the
583
+ // summary request finished on its own).
584
+ if (this._summaryLlm) { try { this._summaryLlm.abort(); } catch {} }
585
+ }
586
+
587
+ // What the NEXT request will carry: the messages (which already begin with the
588
+ // assembled system prompt — see the TUI's runAgent) plus the tool-definition
589
+ // overhead. It must NOT add `cfg.systemPrompt` on top: that value is the RAW
590
+ // config string, not the assembled prompt (calm/plan/swarm/AGENTS.md are appended
591
+ // later), so counting it both double-counted the system text and measured the
592
+ // wrong figure — while being the only input that decides whether to compact.
593
+ usedTokens() {
594
+ // A rolling total rather than a fresh walk of the whole history. This is called at
595
+ // least three times per model round (before the request, after compaction, after a
596
+ // trim) and once more per step for the gauge, so on a long session the old full
597
+ // rescan priced the entire transcript — Read results included — several times per
598
+ // step for a number that changes by one message.
599
+ let total = this._ledger.sync(this.messages, null);
600
+ // THE TOOL DEFINITIONS ARE PART OF WHAT IS SENT, and they are not messages.
601
+ //
602
+ // This charged `toolFilter.length * 8` — and only when a filter was set, so an ordinary turn
603
+ // added NOTHING at all. Measured, the schemas of the 68 registered tools come to about 15 900
604
+ // tokens, which is why the app's own gauge ran tens of thousands below the provider's report.
605
+ //
606
+ // `toolDefTokens` is measured once in the constructor, from the FINAL filtered set.
607
+ total += Number.isFinite(this.toolDefTokens) ? this.toolDefTokens : 0;
608
+ return total;
609
+ }
610
+
611
+
612
+
613
+ // Where to cut the history for compaction. Walks back from the end accumulating a
614
+ // token budget, but only accepts indices the boundary rule allows (so the kept
615
+ // slice can never begin on an orphan tool result). Returns how many messages to
616
+ // DROP. Mirrors kimi's computeCompactCount + canSplitAfter.
617
+ computeCompactSplit(maxCtx) {
618
+ // Keep a fraction of the CURRENT usage, not of the whole window: a big window
619
+ // (1M) should not force a huge tail to be kept when only a little was used.
620
+ // Ratio is configurable (/auto-compact keep, config.toml compact_keep_ratio),
621
+ // default 0.2.
622
+ const keepRatio = (typeof this.cfg.compactKeepRatio === 'number'
623
+ && this.cfg.compactKeepRatio > 0 && this.cfg.compactKeepRatio < 1)
624
+ ? this.cfg.compactKeepRatio : 0.2;
625
+ const used = this.usedTokens();
626
+ const maxSize = Math.max(1, Math.floor((used || (maxCtx || 512000) * 0.85) * keepRatio));
627
+ const msgs = this.messages || [];
628
+ // How far the LEADING system block runs. A cut before `floor` would land inside it,
629
+ // splitting the assembled system prompt across the drop boundary. The block itself is
630
+ // carried over by the trim (renamed `leadingSystem` there), because a cut can only
631
+ // ever land at or after its end.
632
+ let floor = 0;
633
+ while (floor < msgs.length && msgs[floor] && msgs[floor].role === 'system') floor++;
634
+ let recent = 1;
635
+ let size = 0;
636
+ let bestSplit;
637
+ for (; recent < msgs.length; recent++) {
638
+ const split = msgs.length - recent;
639
+ // `messageTokens(m)`, not `estimateMessagesTokens([m])`: the latter allocated a
640
+ // throwaway single-element array for every message in the transcript, on every
641
+ // call. It is also the memoised form, so repeating this walk after a large tool
642
+ // result is a WeakMap hit rather than a re-measure.
643
+ size += messageTokens(msgs[split], null);
644
+ // The guard the leading system block needs, and the reverse of the `split > floor`
645
+ // this used to test. A cut at `split` drops `[0..split-1]`, so `split >= floor`
646
+ // keeps the cut at or after the block's end and never inside it — which is what
647
+ // the block's comment above asks for, and what `split > floor` inverted.
648
+ if (split >= floor && canSplitAfter(msgs, split - 1)) bestSplit = split;
649
+ if (size >= maxSize && bestSplit !== undefined) break;
650
+ }
651
+ return bestSplit ?? 0;
652
+ }
653
+
654
+ /**
655
+ * Trim the history at a legal cut and append the summary + continuation note.
656
+ *
657
+ * Extracted from `run()` so it can be tested against the REAL implementation. A test that
658
+ * re-implemented these four lines was green against a duplicated system prompt — the copy
659
+ * carried its own guard, which is the failure mode of testing a restatement.
660
+ *
661
+ * Returns `{ split, dropped }`.
662
+ *
663
+ * Shape: `[ ...lead, ...kept, summary, continuation ]`.
664
+ *
665
+ * The summary is a USER message wrapped in a `<system-reminder>` (kimi's shape), not a
666
+ * `system` one. Two reasons:
667
+ * * the TUI rebuilds the system prompt from scratch each turn and SKIPS every `system`
668
+ * entry in the stored history, so a system summary was dropped before the model saw it;
669
+ * * the turn-end save filters `system` out of the session, so it was not persisted either
670
+ * — history trimmed AND summary lost at both ends, which made "compaction" pure data loss.
671
+ * The continuation note goes LAST so the model's next move is "keep going" rather than
672
+ * "answer the summary".
673
+ */
674
+ applyCompactionSplit(maxCtx, summary) {
675
+ const split = this.computeCompactSplit(maxCtx);
676
+ const keep = this.messages.slice(split);
677
+ const dropped = this.messages.length - keep.length;
678
+ // The LEADING system block is carried over explicitly. It sits at the head of the array
679
+ // and the cut drops everything before `split`, so it would otherwise be taken by every
680
+ // compaction — leaving the request with no instructions, which is the loss the `floor`
681
+ // guard in computeCompactSplit exists to prevent.
682
+ let leadingSystem = 0;
683
+ while (leadingSystem < this.messages.length
684
+ && this.messages[leadingSystem] && this.messages[leadingSystem].role === 'system') leadingSystem++;
685
+ // Only what the cut actually REMOVED. `keep` is `slice(split)`, so at `split === 0` it
686
+ // still contains the whole array including the block — prepending the block then sends the
687
+ // system prompt twice, and `llm.js` concatenates every system message into the request, so
688
+ // it would stay doubled in every compacted request from then on.
689
+ const lead = split > 0 ? this.messages.slice(0, leadingSystem) : [];
690
+ const summaryText = summary
691
+ ? `${COMPACTION_SUMMARY_PREFIX}\n${summary}`
692
+ : `${COMPACTION_SUMMARY_PREFIX}\n(no summary available)`;
693
+ this.messages = [
694
+ ...lead,
695
+ ...keep,
696
+ { role: 'user', _harness: true, content: wrapSystemReminder(summaryText) },
697
+ { role: 'user', _harness: true, content: wrapSystemReminder(COMPACTION_CONTINUATION_TEXT) },
698
+ ];
699
+ // `kept` is returned, not just its length: the caller reports how many messages survived, and it
700
+ // has no other way to know. It was `keep.length` at the call site referring to a local that lives
701
+ // only in here — a ReferenceError raised inside `run()`, which reached unhandledRejection and exited
702
+ // the whole TUI at the moment compaction fired.
703
+ return { split, dropped, kept: keep.length };
704
+ }
705
+
706
+ async run() {
707
+ // Clear any interrupt flag left from a previous (interrupted) turn. This runs at
708
+ // the start of EVERY turn, so a stalled Esc/Ctrl-C from an earlier compaction can
709
+ // never suppress auto-compaction on the next message. (The constructor also
710
+ // initializes it, but a caller that reuses one Agent across turns must get a
711
+ // fresh allowance here — without this, the live block would blink again with no
712
+ // compaction behind it.)
713
+ this.stopRequested = false;
714
+ this._compactedThisTurn = false;
715
+ // Plugin lifecycle: `onTurnStart` fires here and `onTurnEnd` in the finally
716
+ // block at the end of this method. Both are awaited and both swallow plugin
717
+ // errors (see runHooks), so a broken plugin cannot abort a turn.
718
+ await runHooks('onTurnStart', { messages: this.messages });
719
+ // SHELL HOOK: SessionStart fires once per agent run (the first turn of a
720
+ // session). A hook failure never blocks — it is a convenience signal.
721
+ await runShellHooks(this.hookConfig, 'SessionStart', { messages: this.messages }, this.cfg.workspace);
722
+ // SHELL HOOK: UserPromptSubmit fires with the latest user message. It cannot
723
+ // block (Claude Code's can add context; blocking the user's own prompt is a
724
+ // worse failure than a missing hook), so the result is only logged.
725
+ {
726
+ const lastUser = [...this.messages].reverse().find((m) => m.role === 'user' && typeof m.content === 'string');
727
+ if (lastUser) {
728
+ this._turnPrompt = lastUser.content;
729
+ await runShellHooks(this.hookConfig, 'UserPromptSubmit', { prompt: lastUser.content }, this.cfg.workspace);
730
+ }
731
+ }
732
+ let text = '';
733
+ let toolCalls = [];
734
+ let emittedEnd = false;
735
+ let thought = '';
736
+ // Anthropic thinking blocks, WITH their signatures. They belong to the assistant
737
+ // message: the next request in the turn must replay them or the provider rejects the
738
+ // tool result that follows (see toAnthropic in llm.js). Reset per step because each
739
+ // step is a separate reply.
740
+ let thoughtBlocks = [];
741
+ // decide whether running out of steps actually left the turn unfinished.
742
+ let hadToolCallsOnFinalStep = false;
743
+ // How many times this turn has continued an answer the output cap cut in half.
744
+ // Bounded so a model that cannot fit its answer in the budget cannot loop.
745
+ let truncationRecoveries = 0;
746
+ const MAX_TRUNCATION_RECOVERIES = 3;
747
+
748
+ const handle = async (e) => {
749
+ switch (e.type) {
750
+ case 'data':
751
+ text += e.text;
752
+ this.onEvent({ type: 'data', text: e.text });
753
+ break;
754
+ case 'think':
755
+ // Reasoning tokens: forward verbatim so the TUI can render a live
756
+ // "thinking…" block. They are NOT part of the assistant message.
757
+ thought += e.text;
758
+ this.onEvent({ type: 'think', text: e.text });
759
+ break;
760
+ case 'thought_block':
761
+ // A signed thinking block from the provider. Opaque to us; kept whole so it can
762
+ // be sent back verbatim, which is the only way it is accepted.
763
+ if (e.block) thoughtBlocks.push(e.block);
764
+ break;
765
+ case 'truncated':
766
+ // The reply hit max_tokens and was cut off mid-answer. Remember it: the
767
+ // loop below continues the turn instead of ending it (see the `truncated`
768
+ // branch), so a half-written answer is never presented as a finished one.
769
+ this._truncated = true;
770
+ break;
771
+ case 'usage':
772
+ // Provider accounting, accumulated on the AGENT so it survives across the steps of one turn.
773
+ //
774
+ // IT DOES NOT FEED THE CONTEXT GAUGE. `usage.input` was wired into both the gauge and a
775
+ // calibration here, and removed from both: it counts the request that already went out while the
776
+ // estimate counts the one about to, so the number jumped between two definitions depending on
777
+ // which ran last.
778
+ //
779
+ // What it IS used for: cost and `/usage`, where it is the only honest source, and the turn's
780
+ // output counter.
781
+ this.usage = addUsage(this.usage, e.usage);
782
+ // THE REAL SIZE OF THE REQUEST THAT JUST WENT OUT.
783
+ //
784
+ // `usage.input` is what the endpoint actually billed for this request, which is the honest answer
785
+ // to "how full is the context". The compaction threshold reads it (see `usedNow` below) instead of
786
+ // the local estimate, which runs low because it cannot model the provider's framing. `input`
787
+ // INCLUDES the reply's own prompt but not the reply, which is exactly the figure to compare against
788
+ // the limit.
789
+ if (e.usage && Number.isFinite(e.usage.input) && e.usage.input > 0) {
790
+ this.ctxReportedTokens = e.usage.input;
791
+ }
792
+ this.onEvent({ type: 'usage', usage: e.usage, total: this.usage });
793
+ break;
794
+ case 'tool_start':
795
+ toolCalls.push({ id: e.id, name: e.name, args: {}, argsJson: '' });
796
+ this.onEvent({ type: 'tool_start', id: e.id, name: e.name });
797
+ break;
798
+ case 'tool_args': {
799
+ const tc = toolCalls.find((t) => t.id === e.id);
800
+ if (tc) { tc.argsJson += e.chunk; }
801
+ // Forward the raw argument chunk so the TUI can stream a Write's
802
+ // content (or an Edit's old/new text) while the model is emitting it.
803
+ this.onEvent({ type: 'tool_args', id: e.id, chunk: e.chunk });
804
+ break;
805
+ }
806
+ case 'tool_end': {
807
+ const tc = toolCalls.find((t) => t.id === e.id);
808
+ if (tc) {
809
+ try { tc.args = tc.argsJson ? JSON.parse(tc.argsJson) : {}; }
810
+ catch {
811
+ // The streamed arguments did not form complete JSON. The usual cause
812
+ // is truncation (a huge `content`, a long command) or an interrupted
813
+ // stream. The `raw` shape is kept so a tool can SEE that its
814
+ // arguments failed to parse and say so, instead of reporting a
815
+ // missing field; `_rawLen` lets that message state how big the
816
+ // partial payload was, which is what tells the model to split it.
817
+ tc.args = { raw: tc.argsJson, _rawLen: tc.argsJson ? tc.argsJson.length : 0 };
818
+ }
819
+ }
820
+ break;
821
+ }
822
+ case 'end':
823
+ emittedEnd = true;
824
+ break;
825
+ case 'aborted':
826
+ // The request was aborted (Esc / Ctrl-C): surface it and stop the loop.
827
+ this.stopRequested = true;
828
+ this.onEvent({ type: 'aborted' });
829
+ break;
830
+ case 'error':
831
+ this.onEvent({ type: 'error', error: e.error });
832
+ break;
833
+ }
834
+ };
835
+
836
+ // No step cap: the loop runs until the model produces a final answer, the
837
+ // user interrupts (Esc / Ctrl-C), or an error ends the turn. maxSteps is
838
+ // kept only for callers that explicitly request a bound (0/undefined = none).
839
+ const stepLimit = (this.maxSteps > 0) ? this.maxSteps : Infinity;
840
+ for (let step = 0; step < stepLimit; step++) {
841
+ // Process any steer messages collected during the previous step
842
+ if (this.steerQueue.length > 0) {
843
+ const steers = this.steerQueue.splice(0);
844
+ for (const text of steers) {
845
+ this.messages.push({ role: 'user', content: text });
846
+ this.onEvent({ type: 'steer', text });
847
+ }
848
+ }
849
+ if (this.stopRequested) { this.onEvent({ type: 'stopped' }); break; }
850
+ text = ''; toolCalls = []; emittedEnd = false; thought = ''; thoughtBlocks = [];
851
+ this._truncated = false;
852
+ // Report the start of each model round so the TUI can count steps/rounds.
853
+ this.onEvent({ type: 'step_start', step, round: step + 1 });
854
+ // ---- auto-compaction (kimi's runtime strategy) ----
855
+ // Before each model call, if the estimated context usage is at or above
856
+ // 85% of the model's max context, summarize the older portion and keep a
857
+ // small recent tail. Mirrors kimi's triggerRatio=0.85 /
858
+ // maxRecentSizeRatio=0.2 policy, plus its `reservedContextSize` rule: a
859
+ // request that leaves less than the reserved headroom is compacted even
860
+ // below 85%, so the reply has room to be generated.
861
+ const maxCtx = this.cfg.maxContextTokens || 512000;
862
+ // THE PROVIDER'S OWN COUNT WINS WHEN THERE IS ONE.
863
+ //
864
+ // `usedTokens()` is a local estimate from the token ledger. The endpoint reports the real size with
865
+ // every reply, and that figure is what the status bar shows — but this decision used the estimate
866
+ // regardless, so a session the gauge put at 88% could stay under an 85% trigger indefinitely: the
867
+ // estimate runs low because it cannot model the provider's own message framing and tool preamble.
868
+ // Two numbers for the same thing is the bug; the reported one is the one that is true.
869
+ let usedNow = this.usedTokens();
870
+ const reported = Number(this.ctxReportedTokens);
871
+ if (Number.isFinite(reported) && reported > 0) usedNow = reported;
872
+ // THE MESSAGE THAT TRIGGERED THIS TURN IS NOT YET IN A REQUEST.
873
+ //
874
+ // The user's message is appended before `run()` is entered, so a fresh turn that pushes the
875
+ // history over the threshold would compact FIRST and then send — summarising a conversation that
876
+ // now includes the message it is about to answer, and paying a summary round-trip before the model
877
+ // has seen the request at all.
878
+ //
879
+ // Excluding the trailing user message from the TRIGGER means the decision is made on what the
880
+ // previous turn left behind, which is the history the message is joining. If adding it would still
881
+ // overflow, `needsRoom` catches that on the NEXT pass — after the model has answered something —
882
+ // and `clipToTokens` bounds the request itself in the meantime.
883
+ //
884
+ // Counted as a subtraction rather than by pruning the array: the message must stay in `messages`,
885
+ // it just must not decide whether to compact.
886
+ let triggerTokens = usedNow;
887
+ for (let i = this.messages.length - 1; i >= 0; i--) {
888
+ const m = this.messages[i];
889
+ if (!m) continue;
890
+ // Only skip a TRAILING run of user messages — a steering note queued mid-turn, or the prompt that
891
+ // opened this turn. A user message further back is part of the history being measured.
892
+ if (m.role !== 'user' || m._harness) break;
893
+ triggerTokens -= messageTokens(m, this.cfg);
894
+ }
895
+ triggerTokens = Math.max(0, triggerTokens);
896
+ // `reservedContextSize` (kimi): a request leaving less than this much headroom
897
+ // is compacted even below the trigger ratio, so the REPLY has room to be
898
+ // generated. A request just under the trigger could otherwise still fail.
899
+ //
900
+ // Measured on `usedNow`, NOT on `triggerTokens`: the headroom question is about the request that
901
+ // will actually be sent, and that one does include the new message. The two thresholds ask
902
+ // different things — "is the history full" versus "will this request fit" — so they read different
903
+ // numbers on purpose.
904
+ const reserved = this.cfg.reservedContextTokens || 50_000;
905
+ const needsRoom = reserved > 0 && reserved < maxCtx && usedNow + reserved >= maxCtx;
906
+ // Trigger ratio is configurable (/auto-compact threshold, config.toml
907
+ // compact_threshold); default 0.85.
908
+ const trigger = (typeof this.cfg.compactThreshold === 'number' && this.cfg.compactThreshold > 0
909
+ && this.cfg.compactThreshold < 1) ? this.cfg.compactThreshold : 0.85;
910
+ // At most ONCE per turn. This used to run inside the step loop with no counter,
911
+ // so a trim that failed to get under the threshold triggered again on the very
912
+ // next step — paying for another summary round-trip each step while the history
913
+ // kept shrinking.
914
+ const shouldCompact = this.cfg.autoCompact !== false && maxCtx > 0
915
+ && !this._compactedThisTurn
916
+ // `triggerTokens`, not `usedNow`: the history WITHOUT the message that opened this turn.
917
+ && (triggerTokens >= maxCtx * trigger || needsRoom);
918
+ if (shouldCompact) {
919
+ const before = usedNow;
920
+ this._compactedThisTurn = true;
921
+ // SHELL HOOK: PreCompact — a chance to back up the transcript before the
922
+ // older half is summarized away. Never blocks (the trim must go ahead).
923
+ await runShellHooks(this.hookConfig, 'PreCompact',
924
+ { tokens: usedNow, messages: this.messages }, this.cfg.workspace);
925
+ // Tell the TUI the trim is under way. Summarizing is a full model
926
+ // round-trip, so without this the UI sat silent for seconds mid-turn
927
+ // with no sign anything was happening.
928
+ this.onEvent({ type: 'compacting', before: usedNow, keep: 0, dropped: 0 });
929
+ //
930
+ // SUMMARIZE BEFORE TRIMMING. The summary is generated from the FULL history,
931
+ // so the summarizing model can see what just happened — the most recent
932
+ // exchange is what tells it what the session is doing now. Trimming first
933
+ // summarized only the OLD part and lost what the summary needed most.
934
+ //
935
+ // The transcript fed to the summarizer is bounded by TOKENS, not characters.
936
+ // A character cap is not a size cap: 120k Chinese characters is roughly 120k
937
+ // tokens, which alone can exceed the window and make the call FAIL — after
938
+ // which the history was discarded with no summary at all. That is the normal
939
+ // case for a Chinese conversation, not an edge case.
940
+ const summaryBudget = Math.max(1, Math.floor(maxCtx * 0.3));
941
+ const perMsgTokens = 4_000;
942
+ const summaryParts = [];
943
+ let summaryTokens = 0;
944
+ for (let i = this.messages.length - 1; i >= 0; i--) {
945
+ const m = this.messages[i];
946
+ let raw = typeof m.content === 'string' ? m.content : JSON.stringify(m.content || '');
947
+ if (estimateTokens(raw) > perMsgTokens) raw = clipToTokens(raw, perMsgTokens);
948
+ const line = `${m.role}: ${raw}`;
949
+ const t = estimateTokens(line);
950
+ if (summaryTokens + t > summaryBudget) break;
951
+ summaryTokens += t;
952
+ summaryParts.unshift(line);
953
+ }
954
+ let summary = '';
955
+ if (this.messages.length > 0) {
956
+ const summaryPrompt = [
957
+ { role: 'system', content: COMPACTION_INSTRUCTION },
958
+ { role: 'user', content: summaryParts.join('\n\n') },
959
+ ];
960
+ const cfgCopy = { ...this.cfg, maxOutputTokens: Math.min(this.cfg.maxOutputTokens || 4096, 4096) };
961
+ const llm = new LLM(cfgCopy);
962
+ // Remember this throwaway summarizer so Esc / Ctrl-C can abort IT too.
963
+ // It is NOT `this.llm`, so `interrupt()` could not reach it — a running
964
+ // auto-compaction was uninterruptible, which felt like a hang.
965
+ this._summaryLlm = llm;
966
+ // Thinking OFF and no tools, matching Claude Code's summarizer
967
+ // (`thinkingConfig: { type: 'disabled' }`). Summarizing is a straight
968
+ // transcription task: reasoning tokens buy nothing here, and on a
969
+ // reasoning model they can consume the whole output budget — which
970
+ // returns an EMPTY summary, and an empty summary is what turns a
971
+ // compaction into a silent loss of history.
972
+ try {
973
+ // A DECLARATION IS NEEDED FOR THE REFUSAL.
974
+ //
975
+ // `tool_choice: 'none'` is rejected by both providers unless a tool list accompanies it, and the
976
+ // summariser is a fresh instance with none. One inert definition is declared so the refusal can be
977
+ // expressed: the model then cannot produce a tool call, rather than being asked not to.
978
+ llm._tools = [{
979
+ name: 'noop',
980
+ description: 'Takes no action. Present only so the request can refuse tool use.',
981
+ parameters: { type: 'object', properties: {}, additionalProperties: false },
982
+ }];
983
+ const raw = await llm.requestText(summaryPrompt, { noReasoning: true, toolChoice: 'none' });
984
+ summary = stripToolCallText(raw);
985
+ } catch { summary = ''; }
986
+ this._summaryLlm = null;
987
+ }
988
+ // Interrupted mid-summary: do NOT trim. Aborting yields an empty summary, and
989
+ // proceeding would drop history with nothing to replace it — data loss. Mark
990
+ // the compaction block cancelled and bail out of the turn.
991
+ if (this.stopRequested) {
992
+ this.onEvent({ type: 'compaction_cancelled' });
993
+ this.onEvent({ type: 'stopped' });
994
+ break;
995
+ }
996
+ // The summarizer FAILED (requestText swallowed a network/429 error — even
997
+ // after its retry — and returned null) or came back capped-empty. Trimming
998
+ // now would replace real history with "(no summary available)": the exact
999
+ // silent data loss the comment above warns about. Leave the history intact
1000
+ // and let the turn continue un-compacted; if the fat request genuinely
1001
+ // cannot fit, the provider's context-length error is an honest, recoverable
1002
+ // failure instead of a vanished transcript.
1003
+ if (!summary && this.messages.length > 0) {
1004
+ this.onEvent({ type: 'compaction_cancelled', reason: 'the summary request failed, so nothing was trimmed' });
1005
+ } else {
1006
+ // NOW trim, at a split point the boundary rule allows.
1007
+ const { split, dropped: droppedCount, kept } = this.applyCompactionSplit(maxCtx, summary);
1008
+ // The array was REPLACED, so every count the ledger held describes messages
1009
+ // that no longer exist. `sync` would notice on its own (the first/last
1010
+ // identities no longer match), but resetting here states the intent at the
1011
+ // point of mutation instead of relying on that check to fire.
1012
+ this._ledger.reset();
1013
+ usedNow = this.usedTokens();
1014
+ // THE REPORT DESCRIBES THE REQUEST THAT WENT OUT, so after a trim it still describes the OLD one.
1015
+ // Drop it: the next turn falls back to the local estimate until the provider reports again, instead of
1016
+ // reading a stale figure and compacting a history that was just compacted.
1017
+ this.ctxReportedTokens = 0;
1018
+ this.onEvent({
1019
+ type: 'compacted', before, after: usedNow, kept,
1020
+ dropped: droppedCount, summary,
1021
+ });
1022
+ // SHELL HOOK: PostCompact. Fires after the trim, so a hook can archive the
1023
+ // summary or record the shrink. Never blocks.
1024
+ await runShellHooks(this.hookConfig, 'PostCompact',
1025
+ { before, after: usedNow, kept, dropped: droppedCount, summary }, this.cfg.workspace);
1026
+ }
1027
+ }
1028
+ // ---- tool-result trimming ----
1029
+ // The cheap pass, and the one that actually runs in practice: a history is
1030
+ // usually LARGE because of old tool output nobody is reading, not because the
1031
+ // conversation is long. Bodies are replaced by a short pointer — the message
1032
+ // list keeps its exact length and roles, so the assistant/tool pairing and the
1033
+ // cached prefix shape are untouched — and the removed text is copied to disk
1034
+ // first, so it stays recoverable.
1035
+ //
1036
+ // Trigger: the request reached `trimThreshold` (50% by default) of the window.
1037
+ // Target: keep `trimKeepRatio` (30% by default) of the tool-result TEXT, newest
1038
+ // first. A different denominator from the trigger on purpose: the trigger asks
1039
+ // about the window, this asks about the removable output. Skipped while a
1040
+ // compaction just ran (that already shrank
1041
+ // things) and above the compaction trigger (compaction is the right tool by
1042
+ // then, and the two must not fight over the same history).
1043
+ const trimThreshold = Number.isFinite(this.cfg.trimThreshold) ? this.cfg.trimThreshold : DEFAULT_TRIM_THRESHOLD;
1044
+ if (this.cfg.autoTrim !== false && toolResultLimitsEnabled()
1045
+ && !this._compactedThisTurn && maxCtx > 0
1046
+ && usedNow >= maxCtx * trimThreshold && usedNow < maxCtx * (this.cfg.compactThreshold || 0.85)) {
1047
+ const res = trimToolResults(this.messages, {
1048
+ sessionId: this.cfg.sessionId,
1049
+ keepRatio: Number.isFinite(this.cfg.trimKeepRatio) ? this.cfg.trimKeepRatio : DEFAULT_TRIM_KEEP_RATIO,
1050
+ // The model may still be reading the result it was handed last step.
1051
+ mustKeep: this._lastToolResultIndex,
1052
+ });
1053
+ if (res && res.elided > 0) {
1054
+ // `trimToolResults` rewrites message CONTENT IN PLACE, so the array is the
1055
+ // same one the ledger already counted and its identity check cannot see the
1056
+ // change. Without this reset the gauge would keep reporting the PRE-trim
1057
+ // total: the trim would look like it freed nothing, and the very next step
1058
+ // would compact a history that had already been trimmed.
1059
+ this._ledger.reset();
1060
+ const after = this.usedTokens();
1061
+ this.onEvent({
1062
+ type: 'results_trimmed', elided: res.elided, elidedBytes: res.elidedBytes,
1063
+ kept: res.kept, keptBytes: res.keptBytes, before: usedNow, after,
1064
+ });
1065
+ usedNow = after;
1066
+ }
1067
+ }
1068
+ // Live context gauge: report the estimated size of the request about to be
1069
+ // sent, so the TUI's context readout is refreshed at every step rather than
1070
+ // only once the whole turn ends.
1071
+ this.onEvent({ type: 'context', tokens: usedNow, max: maxCtx });
1072
+
1073
+ // Inject any user steering messages typed during the previous step.
1074
+ // They are appended right after the last assistant/tool round so the
1075
+ // model sees "tool callback / user steer" on this next request.
1076
+ if (this.steerQueue.length > 0) {
1077
+ for (const steerText of this.steerQueue.splice(0)) {
1078
+ this.messages.push({ role: 'user', content: steerText });
1079
+ this.onEvent({ type: 'steer', text: steerText });
1080
+ }
1081
+ }
1082
+
1083
+ // THE CACHE BOUNDARY: everything BEFORE this index was already sent in an
1084
+ // earlier request of this turn and has not changed since. It is captured
1085
+ // here — AFTER the previous step's tool results are committed, BEFORE the
1086
+ // steering drain appends anything new — so it marks exactly the prefix the
1087
+ // provider can reuse.
1088
+ //
1089
+ // This used to be derived from the message COUNT ("keep the last two"), which
1090
+ // is the wrong question. One agent step appends an assistant message plus one
1091
+ // tool result PER call, so a step that read four files left five fresh
1092
+ // messages; a breakpoint two back sat in the middle of that and the provider
1093
+ // had to re-prefill all of it. Counting the boundary from the previous
1094
+ // request instead means a step of any size leaves exactly one stable prefix.
1095
+ // A COMPACTION REPLACED THE ARRAY, so the boundary measured against the old
1096
+ // one no longer describes anything in this one. Clamping would place the
1097
+ // breakpoint at a message that never existed when the value was taken.
1098
+ if (this._stableEnd > this.messages.length) this._stableEnd = 0;
1099
+ if (this._stableEnd !== this.messages.length) this._stableEnd = this.messages.length;
1100
+ const cacheEnd = this._stableEnd - 1;
1101
+
1102
+
1103
+ // Plugin hooks around the model round-trip. `onBeforeRequest` sees the exact
1104
+ // message array being sent (and may mutate it); `onAfterResponse` fires once
1105
+ // the stream has been consumed.
1106
+ await runHooks('onBeforeRequest', this.messages, this.cfg);
1107
+ await this.llm.request(this.messages, handle, cacheEnd);
1108
+ await runHooks('onAfterRequest', this.messages, this.cfg);
1109
+
1110
+ // An abort ends the turn: keep whatever text arrived, then stop.
1111
+ if (this.stopRequested) {
1112
+ if (text) this.messages.push({ role: 'assistant', content: text });
1113
+ break;
1114
+ }
1115
+
1116
+ // Append the assistant message. NEVER push one that carries neither text
1117
+ // nor tool_calls: upstream rejects it with "content or tool_calls must be
1118
+ // set". A signed thinking block counts as content for this protocol — a reply
1119
+ // that only thought and called a tool carries nothing else, and dropping it
1120
+ // breaks the pairing its tool result depends on.
1121
+ const hasText = !!(text && text.trim());
1122
+ const hasCalls = toolCalls.length > 0;
1123
+ const hasThoughtBlocks = thoughtBlocks.length > 0;
1124
+ if (hasText || hasCalls || hasThoughtBlocks) {
1125
+ const assistantMsg = {
1126
+ role: 'assistant',
1127
+ content: hasText ? text : null,
1128
+ toolCalls: hasCalls ? toolCalls : undefined,
1129
+ // Not part of the answer, never rendered from here: it is the provider's own
1130
+ // accounting of its reasoning, replayed verbatim on the next request.
1131
+ thoughtBlocks: hasThoughtBlocks ? thoughtBlocks : undefined,
1132
+ };
1133
+ // Mixin seam: llmResponse - plugins may rewrite the assistant text before it is saved.
1134
+ try { const out = await runPatch('llmResponse', { content: assistantMsg.content, toolCalls: assistantMsg.toolCalls }, (c) => c); if (out) { if (out.content !== undefined) assistantMsg.content = out.content; if (out.toolCalls !== undefined) assistantMsg.toolCalls = out.toolCalls; } } catch (e) { console.error('[hncode-plugin] llmResponse error:', e.message); }
1135
+ this.messages.push(assistantMsg);
1136
+ // Plugin hook: one per assistant message committed to the history. Fired
1137
+ // here (the single point where the model's reply lands) rather than at each
1138
+ // of the eleven `messages.push` sites, so a plugin sees a coherent message
1139
+ // instead of the intermediate bookkeeping pushes.
1140
+ await runHooks('onNewMessage', assistantMsg, this.messages);
1141
+ }
1142
+
1143
+ // ---- if tool calls exist, execute them ----
1144
+ if (toolCalls.length > 0) {
1145
+ // Execute tools below
1146
+ } else if (this.steerQueue.length > 0) {
1147
+ const steers = this.steerQueue.splice(0);
1148
+ for (const msg of steers) this.messages.push({ role: 'user', content: msg });
1149
+ continue;
1150
+ } else if (this._truncated && truncationRecoveries < MAX_TRUNCATION_RECOVERIES) {
1151
+ if (!hasText) {
1152
+ // Truncated with NO text at all: every output token went into reasoning
1153
+ // (a reasoning model on a small budget). There is nothing to continue
1154
+ // from, and ending the turn here would look like the model simply had
1155
+ // nothing to say. Say what actually happened instead.
1156
+ this.onEvent({
1157
+ type: 'error',
1158
+ error: new Error(
1159
+ `The model reached its ${this.cfg.maxOutputTokens || 'configured'} output-token limit `
1160
+ + 'before producing any text — raise the output limit (HNCODE_MAX_OUTPUT) or lower the thinking effort.',
1161
+ ),
1162
+ });
1163
+ break;
1164
+ }
1165
+ // The answer was cut off by max_tokens: it is HALF an answer, and it is
1166
+ // already committed above with no tool calls. Ask the model to pick up
1167
+ // where it stopped instead of ending the turn — otherwise the user reads
1168
+ // a sentence that stops mid-word and assumes that was all of it.
1169
+ truncationRecoveries++;
1170
+ this.messages.push({
1171
+ role: 'user',
1172
+ // `_harness`: this is the harness talking, not the user. /undo and its
1173
+ // picker skip these, and beginTurn does not run for them, so the two
1174
+ // stay aligned on what a "prompt" is.
1175
+ _harness: true,
1176
+ content: 'Your previous message was cut off because it reached the output token limit. Continue from exactly where it stopped — do not repeat what you already wrote, and do not start over.',
1177
+ });
1178
+ this.onEvent({ type: 'truncation_recovery', attempt: truncationRecoveries });
1179
+ continue;
1180
+ } else if (!hasText) {
1181
+ // No tool calls and no answer text: the model stopped without saying
1182
+ // anything. End the turn.
1183
+ break;
1184
+ } else {
1185
+ // The model produced its answer. A steer typed WHILE that answer was
1186
+ // streaming still has to be delivered: drain it and take another step.
1187
+ // (Checking only at tool boundaries dropped it, because a final answer
1188
+ // has no tool boundary.)
1189
+ if (this.steerQueue.length > 0) {
1190
+ const steers = this.steerQueue.splice(0);
1191
+ for (const msg of steers) this.messages.push({ role: 'user', content: msg });
1192
+ continue;
1193
+ }
1194
+ break;
1195
+ }
1196
+
1197
+ // execute tools
1198
+ let allOk = true;
1199
+ // Tool-subset enforcement: in Plan/Focus mode the model may still emit a
1200
+ // tool that is not exposed. Block it with a fixed message so the model
1201
+ // learns it must stick to the allowed subset.
1202
+ const modeName = Array.isArray(this.cfg.toolFilter)
1203
+ ? (this.cfg.toolFilter.includes('Bash') ? 'Focus' : 'Plan')
1204
+ : undefined;
1205
+
1206
+ // Gate + execute + hooks for ONE call, with no message bookkeeping: the
1207
+ // caller posts the result separately, in call order. Splitting it this way
1208
+ // is what makes a parallel batch possible at all — concurrent calls finish
1209
+ // out of order, and tool results MUST be appended in the order the model
1210
+ // asked for them or the protocol pairing breaks.
1211
+ const prepareToolCall = async (tc) => {
1212
+ // Tag output produced by THIS tool call so onOutput can route it to the
1213
+ // right "Using …" row (a turn can run several tools in sequence).
1214
+ this._currentToolId = tc.id;
1215
+
1216
+ // MODE GATING COMES FIRST, BEFORE THE APPROVAL PROMPT.
1217
+ //
1218
+ // A tool the current mode does not allow must be refused WITHOUT asking the user.
1219
+ // Asking first was the bug: in Plan mode the tool list is filtered to
1220
+ // ['Read','Grep','Glob'], so Bash is not offered — but the model can still emit a
1221
+ // call for a tool it saw on an earlier turn, and the approval prompt ran before
1222
+ // this check. The user was asked "run this shell command?" in a mode where the
1223
+ // answer is always no, and the prompt's own wording offered a choice that did not
1224
+ // exist. It also meant a stray call could be APPROVED, and only then refused, which
1225
+ // is the worst of both: a decision recorded for something that never ran.
1226
+ //
1227
+ // These three checks used to sit after the prompt. They all reject outright, so all
1228
+ // three belong here — before anything with a side effect, including the session
1229
+ // approval that a Ctrl+A on the prompt would have written.
1230
+ if (this.noDelegation && DELEGATION_TOOLS.includes(tc.name)) {
1231
+ const result = `You CAN'T use ${tc.name}: subagents cannot delegate. Do the work yourself and report the result to the agent that started you.`;
1232
+ this.onEvent({ type: 'tool_use', id: tc.id, name: tc.name, args: tc.args });
1233
+ return { ok: false, result, editDiff: null, media: false };
1234
+ }
1235
+ // The list above does not expose AgentSwarm outside swarm mode, but the system
1236
+ // prompt describes only ONE shape for it — so refuse a stray call with the fix in
1237
+ // the message rather than letting 128 subagents run in a session where the user
1238
+ // never opted in.
1239
+ if (this.swarmMode !== true && tc.name === 'AgentSwarm') {
1240
+ const result = "You CAN'T use AgentSwarm: swarm mode is OFF. For one or two jobs use the Agent tool; for a real fan-out, ask the user to enable it with /swarm.";
1241
+ this.onEvent({ type: 'tool_use', id: tc.id, name: tc.name, args: tc.args });
1242
+ return { ok: false, result, editDiff: null, media: false };
1243
+ }
1244
+ if (modeName && !this.cfg.toolFilter.includes(tc.name)) {
1245
+ const result = `You CAN'T use this tool on ${modeName} Mode. Allowed: ${this.cfg.toolFilter.join(', ')}.`;
1246
+ this.onEvent({ type: 'tool_use', id: tc.id, name: tc.name, args: tc.args });
1247
+ return { ok: false, result, editDiff: null, media: false };
1248
+ }
1249
+
1250
+ // Permission check before executing each tool.
1251
+ //
1252
+ // The hook may answer with a BOOLEAN (the original contract) or with `{ approved, error }`. The
1253
+ // object form exists for the team mailbox, where a refusal travels with a reason the model can act
1254
+ // on: "Blocked by user" tells it nothing about what to try instead, and a member that has been
1255
+ // refused for a specific reason can re-plan.
1256
+ let result = null;
1257
+ let ok = true;
1258
+ if (this.onApproval) {
1259
+ const verdict = await this.onApproval(tc.name, tc.args);
1260
+ const approved = verdict && typeof verdict === 'object' ? verdict.approved : verdict;
1261
+ if (!approved) {
1262
+ const why = verdict && typeof verdict === 'object' && verdict.error ? `: ${verdict.error}` : '.';
1263
+ result = `Blocked by user: tool "${tc.name}" was rejected${why}`;
1264
+ this.onEvent({ type: 'tool_use', id: tc.id, name: tc.name, args: tc.args });
1265
+ return { ok: false, result, editDiff: null, media: false };
1266
+ }
1267
+ }
1268
+
1269
+
1270
+ const tool = getTool(tc.name);
1271
+ if (!tool) {
1272
+ result = `Error: unknown tool "${tc.name}".`;
1273
+ return { ok: false, result, editDiff: null, media: false };
1274
+ }
1275
+
1276
+ // THE ARGUMENTS MUST MATCH THE TOOL'S OWN SCHEMA.
1277
+ //
1278
+ // An unknown parameter used to be accepted in silence, and the model had no way to learn that the
1279
+ // argument it took trouble to compute was thrown away: it sends `line_offset` to a tool that takes
1280
+ // `start_line`, gets a plausible answer computed from defaults, and concludes the tool is broken.
1281
+ // Refusing the call names the key and lists the accepted ones, which is the only thing that stops the
1282
+ // same mistake being retried with a different spelling.
1283
+ const argError = validateToolArgs(tc.args, tool.parameters);
1284
+ if (argError) {
1285
+ result = `Error: ${tc.name}: ${argError}`;
1286
+ this.onEvent({ type: 'tool_use', id: tc.id, name: tc.name, args: tc.args });
1287
+ return { ok: false, result, editDiff: null, media: false };
1288
+ }
1289
+
1290
+
1291
+ // SHELL HOOK: PreToolUse. A non-zero exit blocks the tool, and its
1292
+ // message goes back to the model in place of the tool result — that is
1293
+ // the whole point of a pre-hook (e.g. refuse a write that fails a lint
1294
+ // gate). Checked BEFORE approving/executing so a blocked call never
1295
+ // touches the filesystem.
1296
+ const pre = await runShellHooks(this.hookConfig, 'PreToolUse',
1297
+ { toolName: tc.name, toolArgs: tc.args }, this.ctx.cwd || this.cfg.workspace);
1298
+ if (pre.blocked) {
1299
+ result = `Blocked by a PreToolUse hook: ${pre.reason}`;
1300
+ this.onEvent({ type: 'tool_use', id: tc.id, name: tc.name, args: tc.args });
1301
+ return { ok: false, result, editDiff: null, media: false };
1302
+ }
1303
+ if (this.onToolStart) this.onToolStart(tc.name, tc.args);
1304
+ this.onEvent({ type: 'tool_use', id: tc.id, name: tc.name, args: tc.args });
1305
+ // Plugin hook: onToolExecute fires BEFORE the tool runs and receives the
1306
+ // mutable args object, so a plugin can inspect or adjust a call. Errors
1307
+ // are swallowed by runHooks — a broken plugin must not break a turn.
1308
+ await runHooks('onToolExecute', tc.name, tc.args, this.ctx);
1309
+ try {
1310
+ // Mixin seam: toolDispatch - plugins may intercept/modify tool calls before execution.
1311
+ let _args = tc.args; let _skip = false;
1312
+ try { const out = await runPatch('toolDispatch', { name: tc.name, args: tc.args, ctx: this.ctx }, (c) => c); if (out) { _args = out.args !== undefined ? out.args : tc.args; if (out.skip) _skip = true; } } catch (e) { console.error('[hncode-plugin] toolDispatch error:', e.message); }
1313
+ if (_skip) { result = '[skipped by plugin: ' + tc.name + ']'; ok = true; }
1314
+ else {
1315
+ // RACE THE ABORT SIGNAL, do not merely pass it.
1316
+ //
1317
+ // `ctx.signal` is handed to every tool, but nothing enforces that a tool LISTENS. A built-in
1318
+ // does — Bash kills its process tree — while a plugin tool that ignores it kept running, and
1319
+ // this `await` kept waiting for it: Esc reached `interrupt()`, aborted the controller, and the
1320
+ // row still said "Using …" until the plugin happened to finish.
1321
+ //
1322
+ // Aborting the signal now ends the wait immediately whatever the tool is doing. The abandoned
1323
+ // promise keeps running detached — a plugin that ignores the signal cannot be forced to stop —
1324
+ // but the TURN is no longer held by it, which is what pressing Esc actually asked for.
1325
+ const raw = await raceWithAbort(tool.execute(_args, this.ctx), this.toolAbort.signal);
1326
+ // `null` means the tool returned a structured MEDIA result: keep the object so the
1327
+ // image blocks can be built from it. Only a plain value is stringified.
1328
+ const text = toolResultText(raw);
1329
+ result = text === null ? raw : text;
1330
+ }
1331
+ } catch (err) {
1332
+ result = `Error running ${tc.name}: ${err.message}`;
1333
+ ok = false;
1334
+ }
1335
+ this.ctx.lastResult = result;
1336
+ // Plugin hook: onToolResult fires with the tool's output. A hook may return a
1337
+ // (redacted) replacement string — e.g. secret-guard masking keys in a Read
1338
+ // result — which is then what the model and transcript receive.
1339
+ const hookOut = await runHooks('onToolResult', tc.name, result, this.ctx);
1340
+ if (typeof hookOut === 'string') result = hookOut;
1341
+ // SHELL HOOK: PostToolUse. Never blocks (the tool already ran); a
1342
+ // failure is logged. This is where "format after every edit" lives.
1343
+ await runShellHooks(this.hookConfig, 'PostToolUse',
1344
+ { toolName: tc.name, toolArgs: tc.args, toolResult: result }, this.ctx.cwd || this.cfg.workspace);
1345
+ // SHELL HOOK: PostToolUseFailure. Fires only when the tool failed (an
1346
+ // `Error`/`[error:` result, or a thrown run), so a hook can alert or
1347
+ // retry without matching on every successful call.
1348
+ if (typeof result === 'string' && /^(Error\b|\[error:)/.test(result.trim())) {
1349
+ ok = false;
1350
+ await runShellHooks(this.hookConfig, 'PostToolUseFailure',
1351
+ { toolName: tc.name, toolArgs: tc.args, toolResult: result }, this.ctx.cwd || this.cfg.workspace);
1352
+ }
1353
+ // Surface the live TODO list so the TUI can render its panel.
1354
+ if (tc.name === 'TodoList') {
1355
+ this.onEvent({ type: 'todos', todos: this.ctx.todoState || [] });
1356
+ }
1357
+ // A tool may return a STRUCTURED result instead of a string: ReadMediaFile
1358
+ // returns `{ text, media }` so an image can travel as an image.
1359
+ const editDiff = this.ctx.lastEditDiff || null;
1360
+ const media = !!result && typeof result === 'object' && Array.isArray(result.media);
1361
+ this.ctx.lastEditDiff = null;
1362
+ return { ok, result, editDiff, media };
1363
+ };
1364
+
1365
+ // Post one call's outcome: the model's `tool` message, then the TUI event.
1366
+ const postToolResult = (tc, out) => {
1367
+ if (!out.ok) allOk = false;
1368
+ if (out.media) {
1369
+ const forModel = out.editDiff
1370
+ ? { ...out.result, text: mediaResultText(out.result) + formatEditDiffForModel(out.editDiff) }
1371
+ : out.result;
1372
+ this.messages.push({ role: 'tool', toolCallId: tc.id, content: forModel });
1373
+ this.onEvent({
1374
+ type: 'tool_result', id: tc.id, name: tc.name,
1375
+ content: out.result._receipt || out.result.text || '[media]',
1376
+ editDiff: out.editDiff,
1377
+ });
1378
+ return;
1379
+ }
1380
+ // THE MODEL GETS THE TOOL'S OWN RESULT. It used to have the rendered DIFF appended as well, because an Edit
1381
+ // reported only "replaced lines 5-7" and the model could not see what it had written. The Edit now quotes
1382
+ // the file around the change itself, so appending the diff would show the same lines twice.
1383
+ const rawForModel = out.result;
1384
+ const shaped = toolResultLimitsEnabled()
1385
+ ? shapeToolResult(rawForModel, { sessionId: this.cfg.sessionId, toolCallId: tc.id })
1386
+ : { content: rawForModel, spilled: false };
1387
+ let _toolContent = shaped.content;
1388
+ // Mixin seam: toolResult (sync) - plugins may rewrite what the model receives for this call.
1389
+ try { const out = runPatchSync('toolResult', { name: tc.name, content: shaped.content }, (c) => c); if (out && out.content !== undefined) _toolContent = out.content; } catch (e) { console.error('[hncode-plugin] toolResult error:', e.message); }
1390
+ this.messages.push({ role: 'tool', toolCallId: tc.id, content: _toolContent });
1391
+ // Remember where the newest tool result landed: a trim must never elide the
1392
+ // output the model was handed in the step it is about to reason about.
1393
+ this._lastToolResultIndex = this.messages.length - 1;
1394
+ this.onEvent({
1395
+ type: 'tool_result', id: tc.id, name: tc.name,
1396
+ // THE UI GETS THE SUMMARY, NOT THE QUOTED FILE. The context lines after an Edit exist for the MODEL, so
1397
+ // it does not have to read the same region twice — the user reads the DIFF (`editDiff`) instead, which
1398
+ // already shows what changed in place. Passing the whole result drew the same lines twice, once as a
1399
+ // diff and once as a block of text.
1400
+ content: out.editDiff ? String(out.result).split('\n\n')[0] : out.result,
1401
+ editDiff: out.editDiff, spilled: shaped.spilled,
1402
+ });
1403
+ };
1404
+
1405
+
1406
+ for (let i = 0; i < toolCalls.length; i++) {
1407
+ if (this.stopRequested) break;
1408
+ const tc = toolCalls[i];
1409
+ // A RUN of consecutive read-only calls goes out in parallel. Non-
1410
+ // destructive by construction (see READ_ONLY_TOOLS), so none of them can
1411
+ // observe another's effects. The system prompt has always promised this
1412
+ // ("Run independent tool calls in parallel; never parallelize dependent
1413
+ // ones") but the loop executed every call one at a time, so a model that
1414
+ // issued four Reads paid for four round-trips in sequence.
1415
+ if (!READ_ONLY_TOOLS.has(tc.name)) {
1416
+ postToolResult(tc, await prepareToolCall(tc));
1417
+ continue;
1418
+ }
1419
+ const batch = [tc];
1420
+ while (i + 1 < toolCalls.length && READ_ONLY_TOOLS.has(toolCalls[i + 1].name)) batch.push(toolCalls[++i]);
1421
+ if (batch.length === 1) {
1422
+ postToolResult(tc, await prepareToolCall(tc));
1423
+ continue;
1424
+ }
1425
+ // Results are posted in CALL order, never completion order.
1426
+ const outs = await Promise.all(batch.map((b) => prepareToolCall(b)));
1427
+ for (let k = 0; k < batch.length; k++) postToolResult(batch[k], outs[k]);
1428
+ }
1429
+
1430
+
1431
+ // Did THIS iteration still have tool calls? If the loop runs out of budget
1432
+ // right after running them, the turn really is unfinished.
1433
+ hadToolCallsOnFinalStep = toolCalls.length > 0;
1434
+
1435
+ // Report the context after this step's tool results were appended: that is
1436
+ // exactly what the next request will carry, so the gauge grows with history.
1437
+ this.onEvent({ type: 'context', tokens: this.usedTokens(), max: maxCtx });
1438
+
1439
+ }
1440
+
1441
+ // With the cap removed this can only trigger for a caller that set an
1442
+ // explicit finite maxSteps: the final iteration still produced tool calls,
1443
+ // so the turn genuinely ran out of rounds. Checking the step index alone (as
1444
+ // this used to) reported "budget exhausted" for turns that had finished.
1445
+ if (Number.isFinite(stepLimit) && !this.stopRequested && hadToolCallsOnFinalStep) {
1446
+ this.onEvent({
1447
+ type: 'incomplete',
1448
+ reason: 'the step budget was exhausted while tools were still being called',
1449
+ });
1450
+ }
1451
+ if (!emittedEnd && this.onEvent) this.onEvent({ type: 'done' });
1452
+ // The turn is over, so the inline-reasoning block it may have left open is
1453
+ // abandoned: the NEXT user turn starts a fresh one. Without this, a model that
1454
+ // never wrote its closing tag would leave the following turn's answer classified
1455
+ // as reasoning.
1456
+ if (typeof this.llm.resetThink === 'function') this.llm.resetThink();
1457
+ // Plugin lifecycle: the turn is over (normally, interrupted, or out of steps).
1458
+ // In a finally-equivalent position — every exit path above reaches here.
1459
+ await runHooks('onTurnEnd', { messages: this.messages, stopped: this.stopRequested });
1460
+ // SHELL HOOK: Stop fires when the turn ends, whether it finished or was
1461
+ // interrupted. Never blocks.
1462
+ await runShellHooks(this.hookConfig, 'Stop',
1463
+ { messages: this.messages, stopped: this.stopRequested, prompt: this._turnPrompt }, this.cfg.workspace);
1464
+ }
1465
+ }