@hncode/hncode 0.8.1 → 0.8.2

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/llm.js CHANGED
@@ -115,10 +115,28 @@ export function toOpenAi(messages) {
115
115
  }
116
116
 
117
117
  // Internal canonical messages -> Anthropic request shape. Returns {system, messages}.
118
- export function toAnthropic(messages) {
118
+ //
119
+ // TWO SHAPES HERE ARE NOT OPTIONAL, and both were wrong:
120
+ //
121
+ // * PARALLEL TOOL RESULTS GO IN ONE USER MESSAGE. The protocol pairs an assistant's
122
+ // `tool_use` blocks with the `tool_result` blocks that answer them, and puts every
123
+ // result for one assistant turn in the SAME user message. Emitting one user message
124
+ // per result produced a run of consecutive user messages, which the API does not
125
+ // describe and several gateways reject.
126
+ //
127
+ // * THINKING BLOCKS MUST BE SENT BACK. With thinking enabled, the last assistant
128
+ // message before a tool result must BEGIN with a `thinking` block, and the block
129
+ // carries the `signature` the provider issued. Dropping it turned every second step
130
+ // of a thinking session into a 400: `Expected `thinking` or `redacted_thinking`, but
131
+ // found `tool_use``. The signature is opaque, so it is stored on the message and
132
+ // replayed verbatim; it is only sent when thinking is on for this request, because
133
+ // blocks from a disabled-thinking turn are not accepted.
134
+ export function toAnthropic(messages, opts = {}) {
119
135
  const sys = [];
120
136
  const out = [];
121
- for (const m of messages) {
137
+ const includeThinking = opts.includeThinking === true;
138
+ for (let i = 0; i < messages.length; i++) {
139
+ const m = messages[i];
122
140
  if (m.role === 'system') { sys.push(m.content); continue; }
123
141
  if (m.role === 'user') {
124
142
  const c = isMediaContent(m.content) ? toAnthropicContent(m.content) : [{ type: 'text', text: m.content }];
@@ -126,26 +144,40 @@ export function toAnthropic(messages) {
126
144
  continue;
127
145
  }
128
146
  if (m.role === 'tool') {
129
- out.push({
130
- role: 'user',
131
- content: [{
147
+ // Gather this assistant turn's results into ONE user message, in call order.
148
+ const blocks = [];
149
+ let j = i;
150
+ for (; j < messages.length && messages[j].role === 'tool'; j++) {
151
+ const r = messages[j];
152
+ blocks.push({
132
153
  type: 'tool_result',
133
- tool_use_id: m.toolCallId,
134
- content: isMediaContent(m.content) ? toAnthropicContent(m.content) : m.content,
135
- }],
136
- });
154
+ tool_use_id: r.toolCallId,
155
+ content: isMediaContent(r.content) ? toAnthropicContent(r.content) : String(r.content == null ? '' : r.content),
156
+ });
157
+ }
158
+ out.push({ role: 'user', content: blocks });
159
+ i = j - 1;
137
160
  continue;
138
161
  }
139
162
  if (m.role === 'assistant') {
140
163
  const blocks = [];
164
+ if (includeThinking && Array.isArray(m.thoughtBlocks)) {
165
+ for (const b of m.thoughtBlocks) {
166
+ if (!b || typeof b !== 'object') continue;
167
+ if (b.type === 'redacted_thinking' && b.data) blocks.push({ type: 'redacted_thinking', data: b.data });
168
+ else if (b.type === 'thinking' && b.signature) {
169
+ blocks.push({ type: 'thinking', thinking: b.thinking == null ? '' : String(b.thinking), signature: b.signature });
170
+ }
171
+ }
172
+ }
141
173
  if (m.content) blocks.push({ type: 'text', text: m.content });
142
174
  for (const tc of (m.toolCalls || [])) {
143
175
  blocks.push({ type: 'tool_use', id: tc.id, name: tc.name, input: tc.args });
144
176
  }
145
- out.push({ role: 'assistant', content: blocks });
177
+ if (blocks.length) out.push({ role: 'assistant', content: blocks });
146
178
  }
147
179
  }
148
- return { system: sys.join('\n\n').trim(), messages: out };
180
+ return { system: sys.join('\n\n').trim(), messages: out };
149
181
  }
150
182
 
151
183
  /** Responses: content parts use `input_text` / `input_image`. */
@@ -230,17 +262,62 @@ function authHeaders(cfg) {
230
262
  return h;
231
263
  }
232
264
 
265
+ // Anthropic thinking, in the one form this model will actually accept.
266
+ //
267
+ // THREE RULES, and the old code broke all three:
268
+ //
269
+ // * `thinking: {type:'enabled'}` IS NOT A VALID BODY. `budget_tokens` is REQUIRED with
270
+ // `enabled`. The previous mapping omitted it for the plain "on" toggle, so a user who
271
+ // turned thinking on got a 400 rather than a thinking turn.
272
+ // * `budget_tokens` MUST BE AT LEAST 1024 AND STRICTLY LESS THAN `max_tokens`. The old
273
+ // grades are 2000/8000/16000/32000 while the default output cap is 10000, so `high`
274
+ // and `max` asked for more thinking than the whole reply budget — a guaranteed 400.
275
+ // The budget is therefore fitted to the cap here, leaving room for the answer itself.
276
+ // * NEWER MODELS TAKE `thinking: {type:'adaptive'}` PLUS `output_config: {effort}`, and
277
+ // REJECT the legacy `enabled`/`budget_tokens` form. Which class a model belongs to is
278
+ // not something this side can guess from its id, so a model entry opts in with
279
+ // `adaptive_thinking = true`; everything else keeps the legacy shape.
280
+ //
281
+ // Returns `{ thinking, output_config? }`, or null when thinking cannot be requested at
282
+ // all with this cap — in which case the turn runs without it rather than failing.
283
+ const MIN_THINKING_BUDGET = 1024;
284
+ // The answer needs room of its own; a request whose budget equals the cap leaves nothing
285
+ // for the reply and the model answers with an empty, `max_tokens`-truncated message.
286
+ const ANSWER_RESERVE = 1024;
287
+ const DEFAULT_ON_BUDGET = 8000;
288
+
289
+ function anthropicThinking(cfg, opts, wire) {
290
+ if (!wire || !wire.thinking) return null;
291
+ const maxTokens = Number(cfg.maxOutputTokens) || 0;
292
+ const models = (cfg.raw && cfg.raw.models) || {};
293
+ const entry = models[cfg.model] || {};
294
+ const adaptive = entry.adaptive_thinking === true || entry.adaptiveThinking === true;
295
+ if (adaptive) {
296
+ const grade = cfg.effort && cfg.effort !== 'on' ? String(cfg.effort) : '';
297
+ return { thinking: { type: 'adaptive' }, output_config: grade ? { effort: grade } : undefined };
298
+ }
299
+ const requested = Number(wire.thinking.budget_tokens) || DEFAULT_ON_BUDGET;
300
+ if (maxTokens > 0) {
301
+ const room = maxTokens - ANSWER_RESERVE;
302
+ if (room < MIN_THINKING_BUDGET) return null; // too small a cap to think AND answer
303
+ const budget = Math.min(requested, room);
304
+ return { thinking: { type: 'enabled', budget_tokens: budget } };
305
+ }
306
+ return { thinking: { type: 'enabled', budget_tokens: Math.max(MIN_THINKING_BUDGET, requested) } };
307
+ }
308
+
233
309
  function buildBody(cfg, messages, streaming = true, opts = {}) {
234
310
  const common = { stream: streaming, max_tokens: cfg.maxOutputTokens };
235
311
  if (cfg.temperature != null) common.temperature = cfg.temperature;
236
312
  if (cfg.topP != null) common.top_p = cfg.topP;
237
313
  if (cfg.presencePenalty != null) common.presence_penalty = cfg.presencePenalty;
238
314
  // Ask for the token accounting on the FINAL stream frame. Without this the
239
- // OpenAI-compatible stream carries no `usage` at all, so the only token numbers
240
- // available were our own estimates (see /usage, which divided the transcript's
241
- // JSON length by 3.5). `includeUsage` is cleared after a 400 (see request):
242
- // servers that predate the field reject the whole request.
243
- if (streaming && opts.includeUsage !== false) common.stream_options = { include_usage: true };
315
+ // OpenAI-compatible stream carries no `usage` at all. Anthropic reports usage on
316
+ // message_start/message_delta natively, and rejects this OpenAI-only field; Responses
317
+ // has its own accounting and does not use it either. `includeUsage` is cleared after a
318
+ // 400 (see request) for older OpenAI-compatible servers.
319
+ if (streaming && cfg.protocol !== 'anthropic' && cfg.protocol !== 'responses'
320
+ && opts.includeUsage !== false) common.stream_options = { include_usage: true };
244
321
  // effort (see config.effortWire): OpenAI-compatible sends `reasoning_effort`,
245
322
  // Anthropic sends a `thinking` budget. Models that think by default need no
246
323
  // flag, so nothing is sent when the effort is off/unset.
@@ -255,7 +332,10 @@ function buildBody(cfg, messages, streaming = true, opts = {}) {
255
332
  // block: it is pure input cost on top of a request that only wants one line.
256
333
  const defs = Object.prototype.hasOwnProperty.call(opts, 'tools') ? openAiToolDefs(opts.tools) : openAiToolDefs(llmToolsList);
257
334
  if (cfg.protocol === 'anthropic') {
258
- const { system, messages: am } = toAnthropic(messages);
335
+ // The thinking mode is decided ONCE here, so the body, the budget and the replayed
336
+ // blocks cannot disagree with each other. See anthropicThinking.
337
+ const think = opts.noReasoning ? null : anthropicThinking(cfg, opts, wire);
338
+ const { system, messages: am } = toAnthropic(messages, { includeThinking: !!think });
259
339
  const body = {
260
340
  model: cfg.innerModel, system, messages: am,
261
341
  // `tool_choice: none` is the protocol-level refusal. Omitting the tool definitions entirely, which
@@ -264,8 +344,18 @@ function buildBody(cfg, messages, streaming = true, opts = {}) {
264
344
  // use is the only form both providers accept.
265
345
  tools: opts.toolChoice === 'none' ? anthropicToolDefs(opts.tools || llmToolsList) : (opts.noTools ? undefined : anthropicToolDefs(opts.tools || llmToolsList)),
266
346
  tool_choice: opts.toolChoice === 'none' ? { type: 'none' } : undefined,
267
- ...common, ...wire,
347
+ ...common,
268
348
  };
349
+ // `wire` describes thinking too, but its shape depends on the model class and on the
350
+ // output cap, so the decision above supersedes it.
351
+ for (const [k, v] of Object.entries(wire)) {
352
+ if (k === 'thinking' || k === 'output_config') continue;
353
+ body[k] = v;
354
+ }
355
+ if (think) {
356
+ body.thinking = think.thinking;
357
+ if (think.output_config) body.output_config = think.output_config;
358
+ }
269
359
  if (!body.tools || !body.tools.length) delete body.tools;
270
360
  // NO PRESENCE PENALTY ON THIS PROTOCOL: it has no equivalent, and an unknown field is an error
271
361
  // here rather than something quietly ignored.
@@ -560,6 +650,10 @@ export class LLM {
560
650
  const state = {
561
651
  tools: new Map(), indexToId: {}, doneEmitted: false,
562
652
  inThink: !!this._inThink, tagPending: this._tagPending || '',
653
+ // Anthropic thinking blocks, keyed by content-block index. Collected while the
654
+ // block streams and handed to `thought_block` on its stop event, because the
655
+ // signature only arrives at the end and the block is useless without it.
656
+ think: new Map(),
563
657
  };
564
658
  try {
565
659
  while (true) {
@@ -858,6 +952,18 @@ function processAnthropic(d, onEvent, state) {
858
952
  const id = cb.id; const name = cb.name;
859
953
  state.tools.set(d.index, { id, name, argsJson: '', done: false });
860
954
  onEvent({ type: 'tool_start', id, name });
955
+ return 'continue';
956
+ }
957
+ // A thinking block opens here, and its `signature` arrives on the closing delta. Both
958
+ // halves have to be kept: the next request must replay this block or the API rejects
959
+ // the turn's tool result (see toAnthropic).
960
+ if (cb && cb.type === 'thinking') {
961
+ state.think.set(d.index, { type: 'thinking', thinking: '', signature: '' });
962
+ return 'continue';
963
+ }
964
+ if (cb && cb.type === 'redacted_thinking' && cb.data) {
965
+ onEvent({ type: 'thought_block', block: { type: 'redacted_thinking', data: cb.data } });
966
+ return 'continue';
861
967
  }
862
968
  return 'continue';
863
969
  }
@@ -868,8 +974,16 @@ function processAnthropic(d, onEvent, state) {
868
974
  // block, which renders as a bare `●` row. The renderer drops those as well — this
869
975
  // is the cheaper place to stop it, and it keeps `state.chat` free of them.
870
976
  if (delta.type === 'text_delta') feedContent(delta.text || '', onEvent, state);
871
- else if (delta.type === 'thinking_delta' && delta.thinking) onEvent({ type: 'think', text: delta.thinking });
872
- else if (delta.type === 'input_json') {
977
+ else if (delta.type === 'thinking_delta') {
978
+ const blk = state.think.get(d.index);
979
+ if (blk) blk.thinking += delta.thinking || '';
980
+ if (delta.thinking) onEvent({ type: 'think', text: delta.thinking });
981
+ }
982
+ // The signature lands on a `signature_delta` just before the block closes.
983
+ else if (delta.type === 'signature_delta') {
984
+ const blk = state.think.get(d.index);
985
+ if (blk && delta.signature) blk.signature = delta.signature;
986
+ } else if (delta.type === 'input_json') {
873
987
  const blk = state.tools.get(d.index);
874
988
  if (blk) { blk.argsJson += delta.partial_json || ''; onEvent({ type: 'tool_args', id: blk.id, chunk: delta.partial_json || '' }); }
875
989
  }
@@ -878,6 +992,13 @@ function processAnthropic(d, onEvent, state) {
878
992
  if (t === 'content_block_stop') {
879
993
  const blk = state.tools.get(d.index);
880
994
  if (blk && !blk.done) { blk.done = true; onEvent({ type: 'tool_end', id: blk.id }); }
995
+ // A completed thinking block is handed over WITH its signature. Without one the block
996
+ // cannot be replayed, and the provider would reject the next request in the turn.
997
+ const tb = state.think.get(d.index);
998
+ if (tb) {
999
+ state.think.delete(d.index);
1000
+ if (tb.signature) onEvent({ type: 'thought_block', block: tb });
1001
+ }
881
1002
  return 'continue';
882
1003
  }
883
1004
  return 'continue';
@@ -973,7 +1094,11 @@ export function consumeNonStreaming(protocol, json, onEvent) {
973
1094
  if (json.stop_reason === 'max_tokens') onEvent({ type: 'truncated' });
974
1095
  for (const cb of content) {
975
1096
  if (cb.type === 'text' && cb.text) feedContent(cb.text, onEvent, state);
976
- else if (cb.type === 'tool_use') {
1097
+ else if (cb.type === 'thinking' && cb.signature) {
1098
+ onEvent({ type: 'thought_block', block: { type: 'thinking', thinking: String(cb.thinking || ''), signature: cb.signature } });
1099
+ } else if (cb.type === 'redacted_thinking' && cb.data) {
1100
+ onEvent({ type: 'thought_block', block: { type: 'redacted_thinking', data: cb.data } });
1101
+ } else if (cb.type === 'tool_use') {
977
1102
  onEvent({ type: 'tool_start', id: cb.id, name: cb.name });
978
1103
  onEvent({ type: 'tool_args', id: cb.id, chunk: JSON.stringify(cb.input || {}) });
979
1104
  onEvent({ type: 'tool_end', id: cb.id });
@@ -0,0 +1,112 @@
1
+ // A diagnostic log that cannot grow without limit.
2
+ //
3
+ // WHY THIS EXISTS
4
+ // ---------------
5
+ // Every log in this program appended forever: `paint.log` reached 174 MB, `keys.log`
6
+ // 7 MB, and `session-errors.log` grows by a line per failed save. On a machine with a
7
+ // small disk that is the difference between working and not, and none of it is ever
8
+ // read — a diagnostic log is consulted after a problem, not during one.
9
+ //
10
+ // ROTATION IS BY SIZE, CHECKED ON THE FILE'S OWN LENGTH.
11
+ //
12
+ // The check has to be cheap enough to sit on a paint path: `statSync` measured 33 µs
13
+ // here. That is paid per traced frame only when tracing is on, which it is not by
14
+ // default; on the exit and save paths it is paid once per event.
15
+ //
16
+ // The rotated file keeps ONE generation, `<name>.1`. A debug log is read immediately
17
+ // after the event that wrote it, so a second generation would only preserve the moment
18
+ // before the one being investigated, at twice the disk.
19
+ //
20
+ // A CONCURRENT WRITER LOSES NOTHING. The append is a single `appendFileSync`, which is
21
+ // O_APPEND and therefore atomic per record, so two hncode instances sharing one log
22
+ // interleave records rather than overwrite each other. Only the ROTATION can race, and
23
+ // the loser's rename fails harmlessly — that record is still appended, one rotation late.
24
+
25
+ import fs from 'node:fs';
26
+ import path from 'node:path';
27
+
28
+ /** Default ceiling for a diagnostic log. */
29
+ export const DEFAULT_MAX_BYTES = 5 * 1024 * 1024;
30
+
31
+ // The size is remembered between writes so a burst costs one `statSync` instead of one
32
+ // per record. Another process growing the same file makes the value stale, which delays
33
+ // a rotation by that growth — for a shared file the ceiling is best-effort, never a
34
+ // correctness rule.
35
+ const sizeCache = new Map(); // file -> bytes
36
+
37
+ /** Current size of `file`, from the cache when this process wrote it last. */
38
+ function currentSize(file) {
39
+ const known = sizeCache.get(file);
40
+ if (known !== undefined) return known;
41
+ try { return fs.statSync(file).size; } catch { return 0; }
42
+ }
43
+
44
+ /**
45
+ * Rotate `file` to `file.1` when it is at or past `maxBytes`, keeping one generation.
46
+ *
47
+ * Exported for a caller that wants the check on its own, for content it did not build as
48
+ * a single string.
49
+ */
50
+ export function rotateIfLarge(file, maxBytes = DEFAULT_MAX_BYTES) {
51
+ if (currentSize(file) < maxBytes) return false;
52
+ try {
53
+ fs.renameSync(file, `${file}.1`);
54
+ sizeCache.set(file, 0);
55
+ return true;
56
+ } catch {
57
+ return false;
58
+ }
59
+ }
60
+
61
+ /**
62
+ * Append `text` to `file`, rotating first when the record would pass `maxBytes`.
63
+ *
64
+ * A record larger than the whole ceiling becomes the ONLY content of the rotated file.
65
+ * Truncating it instead would cut the stack trace that made it worth recording, and that
66
+ * one record is the reason the log is worth having.
67
+ *
68
+ * Rotation happens BEFORE the append, so the live file never grows past the ceiling and
69
+ * always exists. Rotating afterwards left no live file at all until the next write.
70
+ *
71
+ * Returns true when the bytes landed. NEVER THROWS: a diagnostic log is not worth the
72
+ * failure it would add to the path that was doing the logging.
73
+ */
74
+ export function appendLog(file, text, { maxBytes = DEFAULT_MAX_BYTES } = {}) {
75
+ if (text == null) return false;
76
+ const data = String(text);
77
+ const grow = Buffer.byteLength(data);
78
+ try {
79
+ fs.mkdirSync(path.dirname(file), { recursive: true });
80
+ if (grow >= maxBytes) {
81
+ // The oversized record becomes the rotated file in one step, and the live log is
82
+ // left present but empty: a reader must never find it MISSING, which would look
83
+ // like logging was broken rather than rotated.
84
+ fs.writeFileSync(`${file}.1`, data, 'utf8');
85
+ fs.writeFileSync(file, '', 'utf8');
86
+ sizeCache.set(file, 0);
87
+ return true;
88
+ }
89
+ let size = currentSize(file);
90
+ if (size > 0 && size + grow > maxBytes) {
91
+ try {
92
+ fs.renameSync(file, `${file}.1`);
93
+ size = 0;
94
+ sizeCache.set(file, 0);
95
+ } catch {
96
+ // Another reader holds the file open. Keep the record and let a later attempt
97
+ // rotate; losing the write to win the rotation would be the wrong trade.
98
+ }
99
+ }
100
+ fs.appendFileSync(file, data, 'utf8');
101
+ sizeCache.set(file, size + grow);
102
+ return true;
103
+ } catch {
104
+ return false;
105
+ }
106
+ }
107
+
108
+ /** Forget the cached size for one file, or for all of them when no file is given. */
109
+ export function forgetLogSize(file) {
110
+ if (file === undefined) { sizeCache.clear(); return; }
111
+ sizeCache.delete(file);
112
+ }