@hncode/hncode 0.8.1 → 0.8.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/README.md +18 -0
  2. package/README_CN.md +14 -0
  3. package/bin/hncode +54 -8
  4. package/package.json +1 -1
  5. package/src/agent-task.js +356 -337
  6. package/src/agent.js +1465 -1405
  7. package/src/animate.js +56 -0
  8. package/src/colors.js +615 -593
  9. package/src/config.js +50 -7
  10. package/src/context-bar.js +280 -278
  11. package/src/doctor.js +4 -3
  12. package/src/file-tree.js +4 -3
  13. package/src/highlight.js +20 -6
  14. package/src/i18n.js +1432 -389
  15. package/src/image-row.js +11 -2
  16. package/src/index.js +218 -6
  17. package/src/keybindings.js +2 -1
  18. package/src/llm.js +146 -21
  19. package/src/log-file.js +112 -0
  20. package/src/markdown.js +646 -567
  21. package/src/mcp-server.js +409 -0
  22. package/src/mcp.js +279 -29
  23. package/src/memory-profile.js +19 -16
  24. package/src/migrate-index.js +175 -0
  25. package/src/migrate.js +392 -0
  26. package/src/panels.js +9 -7
  27. package/src/plan.js +7 -5
  28. package/src/plugin.js +37 -21
  29. package/src/registry-browser.js +17 -15
  30. package/src/rows-plan-bg.js +3 -2
  31. package/src/rows-status.js +20 -6
  32. package/src/rows-tool-result.js +242 -208
  33. package/src/screen-paint.js +153 -128
  34. package/src/session-recover.js +317 -0
  35. package/src/session.js +203 -13
  36. package/src/settings-schema.js +9 -0
  37. package/src/swarm-progress.js +6 -2
  38. package/src/tasks-browser.js +37 -36
  39. package/src/team-panel.js +12 -11
  40. package/src/term.js +57 -21
  41. package/src/text.js +254 -149
  42. package/src/tool-line.js +7 -2
  43. package/src/tool-result.js +400 -327
  44. package/src/tools/agent.js +7 -2
  45. package/src/tools/ask-user-question.js +1 -2
  46. package/src/tools/bash.js +446 -434
  47. package/src/tools/edit.js +653 -665
  48. package/src/tools/goal.js +130 -93
  49. package/src/tools/read.js +141 -133
  50. package/src/tools/tasks.js +214 -214
  51. package/src/tools/utils.js +143 -104
  52. package/src/tui.js +20887 -19942
package/src/image-row.js CHANGED
@@ -56,8 +56,17 @@ export function encodeImageRow(sequence, rows, cols, source) {
56
56
  */
57
57
  export function isImageRow(line) {
58
58
  if (typeof line !== 'string') return false;
59
- const at = line.indexOf(IMAGE_MARK);
60
- return at >= 0 && at < 8 && /^\s*$/.test(line.slice(0, at));
59
+ // SEARCH THE ONE CHARACTER, THEN CONFIRM THE REST.
60
+ //
61
+ // `indexOf(IMAGE_MARK)` scans the whole row for a five-character string. Almost every row is text, so almost every
62
+ // call runs that scan to the end and finds nothing — 14% of a scroll frame's samples on a long transcript.
63
+ //
64
+ // The marker begins with U+0001, which does not occur in rendered text at all. Searching for that single character
65
+ // first lets the common case fail after one vectorised pass over a one-character needle instead of a five-character
66
+ // one, and only a row that actually contains it pays for the rest of the check.
67
+ const at = line.indexOf('\u0001');
68
+ if (at < 0 || at >= 8) return false;
69
+ return line.startsWith(IMAGE_MARK, at) && /^\s*$/.test(line.slice(0, at));
61
70
  }
62
71
 
63
72
  /**
package/src/index.js CHANGED
@@ -5,7 +5,7 @@ import path from 'node:path';
5
5
  import fs from 'node:fs';
6
6
  import { resolveConfig, effectiveSnapshot, saveConfig, resolveModelArg, readPersonalPrompt } from './config.js';
7
7
  import * as sess from './session.js';
8
- import { Agent, SYSTEM_PROMPT, canSplitAfter } from './agent.js';
8
+ import { Agent, SYSTEM_PROMPT, THINKING_TAGS_INSTRUCTION, needsThinkingTags, canSplitAfter } from './agent.js';
9
9
  import { llmTools } from './tools/index.js';
10
10
  import { localVersion } from './version.js';
11
11
  import { EXIT, FORMATS, isValidFormat, buildResult, exitCodeFor, resultLine, createRunTracker, trackEvent, finalReply } from './ci.js';
@@ -49,6 +49,10 @@ Commands:
49
49
  doctor [config] [path] Environment self-check (default), or validate a config.toml.
50
50
  init Create ~/.hncode/config.toml with defaults.
51
51
  export [id] Export a session to ~/.hncode/export/<id>.json.
52
+ backup [path] Archive ALL state (sessions, settings, skills, plugins, memory) for another machine.
53
+ restore <path> Read a backup. Sessions are placed by the index.yml inside it.
54
+ --index <file> use an edited copy; --no-index keep recorded paths;
55
+ --workspace <dir> repoint every session; --overwrite; --dry-run.
52
56
  control status Ask a running session (started with --control) for its status.
53
57
  control prompt <text> Queue a prompt on a running session.
54
58
  control interrupt Interrupt the running turn.
@@ -71,7 +75,10 @@ export function parseArgs(argv) {
71
75
  else { key = a.slice(2); val = null; }
72
76
  if (key === 'resume') key = 'session'; // `--resume <id>` is an alias for `--session <id>`
73
77
  if (['session', 'control', 'web'].includes(key) && val === null) { const nx = argv[i + 1]; out[key] = nx !== undefined && !nx.startsWith('-') ? (i++, nx) : true; }
74
- else if (key === 'model' || key === 'prompt' || key === 'output-format' || key === 'add-dir' || key === 'timeout' || key === 'retries') {
78
+ // FLAGS THAT TAKE A VALUE. `--workspace` and `--index` are here for `hncode restore`: without them the path was
79
+ // left in `positional` and the flag itself became `true`, so the restore would have repointed every session at the
80
+ // string "true".
81
+ else if (key === 'model' || key === 'prompt' || key === 'output-format' || key === 'add-dir' || key === 'timeout' || key === 'retries' || key === 'workspace' || key === 'index') {
75
82
  if (val === null) {
76
83
  const nx = argv[i + 1];
77
84
  // Only consume the next token if it is a real value, not another flag
@@ -255,13 +262,189 @@ function cmdExport(id) {
255
262
  return 0;
256
263
  }
257
264
 
265
+ // ---- migration: every piece of state, to another machine -------------------
266
+ //
267
+ // `hncode backup [path]` writes one archive of everything a person made: sessions, settings, skills, plugins, memory.
268
+ // `hncode restore <path>` reads it back, with `--workspace <dir>` to repoint the imported sessions, `--overwrite` to
269
+ // replace what is already here, and `--dry-run` to see what would happen first.
270
+ //
271
+ // Debug logs and the plugin browser's Chromium profile are deliberately excluded — see EXCLUDED in src/migrate.js.
272
+ async function cmdBackup(dest) {
273
+ const mig = await import('./migrate.js');
274
+ const home = mig.hncodeHome();
275
+ const items = mig.planExport(home);
276
+ if (!items.length) {
277
+ console.error(`nothing to migrate: ${home} holds none of the portable entries`);
278
+ return 1;
279
+ }
280
+ const total = items.reduce((n, i) => n + i.size, 0);
281
+ const out = dest ? path.resolve(String(dest))
282
+ : path.join(process.cwd(), `hncode-backup-${new Date().toISOString().slice(0, 10)}.hnb`);
283
+ console.log(`exporting ${items.length} item(s), ${mig.fmtBytes(total)}, from ${home}`);
284
+ for (const i of items) console.log(` ${mig.fmtBytes(i.size).padStart(9)} ${i.name}${i.kind === 'dir' ? '/' : ''} — ${i.what}`);
285
+ console.log(` (left behind: ${mig.EXCLUDED.map((e) => e.name).join(', ')})`);
286
+ let last = 0;
287
+ const res = mig.writeArchive(out, {
288
+ home,
289
+ items,
290
+ onProgress: (done, all) => {
291
+ // A line every 10% keeps a 190 MB export from looking frozen without flooding the terminal.
292
+ const pct = Math.floor((done / all) * 10) * 10;
293
+ if (pct > last) { last = pct; process.stderr.write(` ${pct}%\r`); }
294
+ },
295
+ });
296
+ console.log(``);
297
+ console.log(`wrote ${res.path}`);
298
+ console.log(` ${res.files} files, ${mig.fmtBytes(res.bytes)}`);
299
+ console.log(`On the other machine: hncode restore ${path.basename(res.path)}`);
300
+ return 0;
301
+ }
302
+
303
+ async function cmdRestore(from, args = {}) {
304
+ const mig = await import('./migrate.js');
305
+ if (!from) { console.error('restore needs an archive: hncode restore <file.hnb> [--workspace <dir>] [--overwrite] [--dry-run]'); return 1; }
306
+ const src = path.resolve(String(from));
307
+ let head;
308
+ try { head = mig.readArchiveManifest(src); } catch (e) { console.error(`cannot read ${src}: ${e.message}`); return 1; }
309
+ const { manifest } = head;
310
+ const home = mig.hncodeHome();
311
+ const bytes = manifest.files.reduce((n, f) => n + f.size, 0);
312
+ console.log(`archive: ${src}`);
313
+ console.log(` created ${new Date(manifest.createdAt).toISOString()}, ${manifest.files.length} files, ${mig.fmtBytes(bytes)}`);
314
+ console.log(` from ${manifest.home || '(unknown)'}`);
315
+ console.log(` into ${home}`);
316
+ // THE INDEX IS THE POINT OF THIS FLAG. Without it the archive's own `index.yml` is used when present, which is what
317
+ // makes an exported-then-edited file worth having. `--index <file>` points at a copy edited OUTSIDE the archive, and
318
+ // `--no-index` ignores it so the recorded paths are kept verbatim.
319
+ const opts = {
320
+ home,
321
+ overwrite: !!args.overwrite,
322
+ workspace: args.workspace,
323
+ dryRun: !!args['dry-run'],
324
+ // DEFAULT IS ON: an archive's own index.yml is used unless `--no-index` says otherwise. `--index <file>` replaces it
325
+ // with an edited copy.
326
+ index: args['no-index'] ? false : true,
327
+ indexFile: typeof args.index === 'string' ? args.index : undefined,
328
+ };
329
+ if (opts.workspace) console.log(` sessions repointed at ${path.resolve(String(opts.workspace))} (--workspace overrides the index)`);
330
+ else if (!opts.index) console.log(' --no-index: paths stay exactly as recorded');
331
+ else if (opts.indexFile) console.log(` mapping read from ${path.resolve(String(opts.indexFile))}`);
332
+ else console.log(' sessions are placed by the index.yml inside the archive, if it has one');
333
+ if (opts.dryRun) console.log(' (dry run — nothing is written)');
334
+ let res;
335
+ try { res = mig.readArchive(src, opts); } catch (e) { console.error(`restore failed: ${e.message}`); return 1; }
336
+ console.log(` ${opts.dryRun ? 'would write' : 'wrote'} ${res.written} file(s), ${mig.fmtBytes(res.bytes)}`);
337
+ if (res.skipped) console.log(` kept ${res.skipped} existing file(s) — pass --overwrite to replace them`);
338
+ if (res.mapped) console.log(` ${res.mapped} session(s) moved by the mapping`);
339
+ else if (res.sessionsRewritten) console.log(` ${res.sessionsRewritten} session(s) repointed`);
340
+ if (opts.index !== false && !res.indexFound) console.log(' no index.yml in the archive (an older backup) — paths left as recorded');
341
+ for (const e of res.errors.slice(0, 5)) console.error(` ! ${e}`);
342
+ if (res.errors.length > 5) console.error(` ! … and ${res.errors.length - 5} more`);
343
+ return res.errors.length ? 1 : 0;
344
+ }
345
+
346
+ // ---- MCP server mode ---------------------------------------------------------
347
+
348
+ // The workspace the exposed tools operate on. A client starts this process from
349
+ // wherever the user happens to be, so the project has to be named explicitly or the
350
+ // tools would work in the wrong directory.
351
+ function mcpWorkspace(args) {
352
+ const fromEnv = process.env.HNCODE_WORKSPACE;
353
+ const fromFlag = args && args.workspace;
354
+ const dir = fromFlag || fromEnv || process.cwd();
355
+ return path.resolve(dir);
356
+ }
357
+
358
+ /**
359
+ * The tool context the exposed tools receive.
360
+ *
361
+ * It is the same shape the agent hands its own tools, so a tool behaves the same
362
+ * whoever called it. `cwd` is what the path helpers resolve against.
363
+ */
364
+ async function mcpToolContext(workspace, args) {
365
+ const cfg = resolveConfig();
366
+ return {
367
+ ...cfg,
368
+ cwd: workspace,
369
+ workspace,
370
+ tasks: {},
371
+ todoState: [],
372
+ allowExternal: cfg.allowExternal !== false,
373
+ signal: undefined,
374
+ };
375
+ }
376
+
377
+ /**
378
+ * `hncode mcp serve` — run hncode as an MCP server.
379
+ *
380
+ * `--stdio` (the default) speaks the protocol over stdin/stdout, which is what every
381
+ * `mcp add` uses. `--http` serves streamable-HTTP on a port instead, for a client that
382
+ * connects to a running server.
383
+ *
384
+ * The toolbelt is the READ-ONE set unless `--full` is given: handing another program
385
+ * the ability to run commands or rewrite files is not something to do by default.
386
+ */
387
+ async function cmdMcpServe(rest, args) {
388
+ const server = await import('./mcp-server.js');
389
+ const mode = args && args.full ? 'full' : 'read';
390
+ const prefix = args && args['no-prefix'] ? '' : 'hncode_';
391
+ const workspace = mcpWorkspace(args);
392
+ const ctx = await mcpToolContext(workspace, args);
393
+
394
+ if (args && args.http) {
395
+ const port = Number(args.port) || 0;
396
+ const host = String(args.host || '127.0.0.1');
397
+ const http = server.createHttpServer({ mode, prefix, ctx });
398
+ const addr = await server.listen(http, port, host);
399
+ // stderr, not stdout: on the HTTP transport stdout is free, but a client reading the
400
+ // process's output expects diagnostics there and the TUI prints its own on stdout.
401
+ console.error(`hncode MCP server on http://${addr.host}:${addr.port}/ workspace=${workspace} tools=${mode}`);
402
+ return new Promise(() => {}); // serve until the process is killed
403
+ }
404
+
405
+ // stdio: stdout carries the protocol and NOTHING else.
406
+ console.error(`hncode MCP server ready workspace=${workspace} tools=${mode}`);
407
+ server.serveStdio({ mode, prefix, ctx });
408
+ return new Promise(() => {});
409
+ }
410
+
411
+ /**
412
+ * `hncode mcp config` — print the JSON another agent's config file needs.
413
+ *
414
+ * The shape is the one every client reads (`mcpServers` with `command`/`args`/`env`),
415
+ * so the output can be pasted into Claude Code's, Cursor's or anyone else's config.
416
+ */
417
+ async function cmdMcpConfig(rest, args) {
418
+ const server = await import('./mcp-server.js');
419
+ const workspace = mcpWorkspace(args);
420
+ const config = server.clientConfig({
421
+ command: process.execPath,
422
+ args: [path.join(path.dirname(new URL(import.meta.url).pathname.replace(/^\//, '')), 'index.js')],
423
+ workspace,
424
+ });
425
+ console.log(JSON.stringify(config, null, 2));
426
+ return 0;
427
+ }
258
428
  const SUBCOMMANDS = {
259
429
  'session': { 'list': cmdSessionList },
260
- 'provider': { 'list': cmdProviderList },
261
430
  'doctor': { 'config': cmdDoctorConfig },
431
+ // MCP server mode: hncode exposes its own tools to another agent. `serve` runs the
432
+ // server; `config` prints the JSON that other clients' config files need.
433
+ 'mcp': {
434
+ 'serve': (rest, args) => cmdMcpServe(rest, args),
435
+ 'config': (rest, args) => cmdMcpConfig(rest, args),
436
+ },
262
437
  'init': cmdInit,
263
438
  'export': cmdExport,
264
- 'control': {
439
+ // MIGRATION. `export` above writes ONE session as Markdown; these move the whole hncode state — every session,
440
+ // the settings, skills, plugins, memory — to another machine. Different jobs, so different names.
441
+ //
442
+ // BOTH ARE `{ run }` ENTRIES, NOT BARE FUNCTIONS. The dispatcher treats a second positional word as the SUBCOMMAND of
443
+ // the first (`session list`), and for these it is just the path — `backup /tmp/x.hnb` was being read as the subcommand
444
+ // `/tmp/x.hnb` of `backup`, which does not exist, so it printed the help and did nothing.
445
+ 'backup': { run: cmdBackup },
446
+ 'restore': { run: cmdRestore },
447
+ control: {
265
448
  // Subcommands pass only positional[2] to their handler, so bind the op.
266
449
  'status': (rest) => cmdControl('status', rest),
267
450
  'prompt': (rest) => cmdControl('prompt', rest),
@@ -303,6 +486,9 @@ async function runPrompt({ cfg, prompt, format, session, modelArg, timeoutSecond
303
486
  // Same layering as the TUI: built-in prompt first, then the user's own
304
487
  // system_prompt override if any, then the /personal notes, then calm mode.
305
488
  let sysText = (cfg.systemPrompt && String(cfg.systemPrompt).trim()) || SYSTEM_PROMPT;
489
+ // The inline-reasoning instruction, only for a model with no reasoning channel of its
490
+ // own — the same rule the TUI applies (see needsThinkingTags).
491
+ if (needsThinkingTags(cfg)) sysText += '\n\n' + THINKING_TAGS_INSTRUCTION;
306
492
  const personal = readPersonalPrompt(cfg.workspace);
307
493
  if (personal) sysText += '\n\n' + personal;
308
494
  messages.push({ role: 'system', content: sysText });
@@ -325,6 +511,13 @@ async function runPrompt({ cfg, prompt, format, session, modelArg, timeoutSecond
325
511
  // history and the system message, so a fresh session answered nothing the
326
512
  // user asked and a resumed one answered nothing new.
327
513
  messages.push({ role: 'user', content: prompt });
514
+ if (session && session._unrecoverable) {
515
+ process.stderr.write(
516
+ `hncode: session ${session.id} has no readable history (its file is damaged). `
517
+ + 'Starting a new session; the old file is untouched.\n',
518
+ );
519
+ session = null;
520
+ }
328
521
  const saved = session || { id: sess.newId(), title: prompt.slice(0, 60), workspace: path.resolve(process.cwd()), model: cfg.model, createdAt: Date.now(), messages: [] };
329
522
  const tracker = createRunTracker();
330
523
  const startedAt = Date.now();
@@ -431,6 +624,18 @@ function loadOrCreateSession(opts, cfg) {
431
624
  // Empty shells are created on every launch, so we skip them to find real conversations.
432
625
  session = sess.latestSession(process.cwd(), undefined, { skipEmpty: true });
433
626
  }
627
+ // A session whose file could not be parsed OR recovered comes back marked, with no
628
+ // messages. Resuming it would present an empty conversation that still looks like the
629
+ // old one, and the first save would write that emptiness over the file. Start fresh and
630
+ // say why, rather than letting the user type into a session that has already lost its
631
+ // history. The damaged file stays on disk, so nothing is destroyed by refusing.
632
+ if (session && session._unrecoverable) {
633
+ process.stderr.write(
634
+ `hncode: session ${session.id} has no readable history (its file is damaged). `
635
+ + 'Starting a new session; the old file is untouched.\n',
636
+ );
637
+ session = null;
638
+ }
434
639
  if (!session) {
435
640
  session = { id: sess.newId(), title: '', workspace: path.resolve(process.cwd()), model: cfg.model, createdAt: Date.now(), messages: [] };
436
641
  } else {
@@ -478,7 +683,6 @@ export function parseWebArg(v) {
478
683
  export async function main(argv) {
479
684
  const args = parseArgs(argv);
480
685
  if (args.help) { printHelp(); return 0; }
481
- if (args.help) { printHelp(); return 0; }
482
686
  if (args.version) { console.log(VERSION); return 0; }
483
687
 
484
688
  // subcommands
@@ -487,9 +691,17 @@ export async function main(argv) {
487
691
  if (cmd === 'doctor' && !sub) { return await cmdDoctorEnv(); }
488
692
  const handler = SUBCOMMANDS[cmd];
489
693
  if (handler) {
694
+ // A `{ needsArgs, run }` entry wants the parsed flags as well as the positional path — the one thing a
695
+ // module-level table cannot close over, because `args` lives in this function.
696
+ if (typeof handler === 'object' && typeof handler.run === 'function') {
697
+ return await handler.run(args.positional[1], args);
698
+ }
699
+ // A NESTED table (`mcp serve`) needs the flags too, for `--stdio`, `--http` and the
700
+ // workspace: the sub-handler is called with the rest of the positional path AND the
701
+ // parsed flags.
490
702
  if (sub !== undefined) {
491
703
  const h2 = handler[sub];
492
- if (h2) return await h2(args.positional[2]);
704
+ if (h2) return await h2(args.positional[2], args);
493
705
  printHelp(); return 1;
494
706
  }
495
707
  if (typeof handler === 'function') return await handler(args.positional[1]);
@@ -25,6 +25,7 @@
25
25
  // instead of after a restart. A malformed file is reported ONCE and then ignored — a typo
26
26
  // must not silently swallow every key the user presses.
27
27
 
28
+ import { uiText, t, getUiLang } from './i18n.js';
28
29
  import fs from 'node:fs';
29
30
  import os from 'node:os';
30
31
  import path from 'node:path';
@@ -239,7 +240,7 @@ export function describeKeybindings(loaded) {
239
240
  if (!loaded.bindings.size) {
240
241
  out.push('No keybindings set.', '', `File: ${loaded.file}`, 'Add one with /keybindings add <key> <key|/command>');
241
242
  } else {
242
- out.push(`Keybindings (${loaded.bindings.size}) — ${loaded.file}`, '');
243
+ out.push(t(getUiLang(), 'keybindings.header', { n: loaded.bindings.size, file: loaded.file }), '');
243
244
  for (const [from, to] of [...loaded.bindings.entries()].sort()) {
244
245
  out.push(` ${from.padEnd(12)} -> ${to.command ? to.command : to.key}`);
245
246
  }
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 });