@hmharness/kernel 0.23.31 → 0.23.33

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/dist/context.d.ts CHANGED
@@ -15,6 +15,15 @@
15
15
  import type { ChatMessage } from './types.js';
16
16
  export declare const DEFAULT_CONTEXT_CHARS = 160000;
17
17
  export declare function transcriptChars(messages: ChatMessage[]): number;
18
+ /** A pruned tool result keeps its HEAD - the first line(s) of a command
19
+ * output usually contain the finding ("Inno @ 722596", "z-ai provider
20
+ * found"). A zero-information "[context pruned]" tombstone forces the model
21
+ * to re-derive facts it already had, which is the #1 driver of the
22
+ * re-verification loop observed in long sessions (2026-10-07 export:
23
+ * 108 tool calls, 20+ re-verification turns on facts the model already
24
+ * knew). The headstone carries enough signal to say "I already know this"
25
+ * without carrying the full dump. */
26
+ export declare const HEADSTONE_CHARS = 200;
18
27
  export declare const DIGEST_MARK = "[rolling digest of earlier context]";
19
28
  export declare function compactMessages(messages: ChatMessage[], budget?: number): ChatMessage[];
20
29
  export interface CompactResult {
package/dist/context.js CHANGED
@@ -18,6 +18,19 @@ function protectedRange(messages) {
18
18
  keep.add(i);
19
19
  return keep;
20
20
  }
21
+ /** A pruned tool result keeps its HEAD - the first line(s) of a command
22
+ * output usually contain the finding ("Inno @ 722596", "z-ai provider
23
+ * found"). A zero-information "[context pruned]" tombstone forces the model
24
+ * to re-derive facts it already had, which is the #1 driver of the
25
+ * re-verification loop observed in long sessions (2026-10-07 export:
26
+ * 108 tool calls, 20+ re-verification turns on facts the model already
27
+ * knew). The headstone carries enough signal to say "I already know this"
28
+ * without carrying the full dump. */
29
+ export const HEADSTONE_CHARS = 200;
30
+ function headstone(original) {
31
+ const head = original.slice(0, HEADSTONE_CHARS).replace(/\s+$/, '');
32
+ return `[earlier tool output, pruned to fit budget — head preserved]\n${head}${original.length > HEADSTONE_CHARS ? '\n…' : ''}`;
33
+ }
21
34
  export const DIGEST_MARK = '[rolling digest of earlier context]';
22
35
  function findDigest(messages) {
23
36
  return messages.findIndex((m) => m.role === 'system' && typeof m.content === 'string' && m.content.startsWith(DIGEST_MARK));
@@ -30,7 +43,7 @@ export function compactMessages(messages, budget = DEFAULT_CONTEXT_CHARS) {
30
43
  for (let i = 0; i < out.length && transcriptChars(out) > budget; i++) {
31
44
  if (keep.has(i) || out[i].role !== 'tool')
32
45
  continue;
33
- out[i] = { ...out[i], content: '[context pruned: earlier tool output removed to fit budget]' };
46
+ out[i] = { ...out[i], content: headstone(String(out[i].content ?? '')) };
34
47
  }
35
48
  return out;
36
49
  }
@@ -46,7 +59,7 @@ export function compactWithEvictions(messages, budget = DEFAULT_CONTEXT_CHARS) {
46
59
  if (keep.has(i) || out[i].role !== 'tool')
47
60
  continue;
48
61
  evicted += out[i].content?.length ?? 0;
49
- out[i] = { ...out[i], content: '[context pruned: earlier tool output removed to fit budget]' };
62
+ out[i] = { ...out[i], content: headstone(String(out[i].content ?? '')) };
50
63
  }
51
64
  return { messages: out, evictedChars: evicted };
52
65
  }
@@ -66,7 +79,8 @@ export async function compactWithDigest(messages, budget, summarize) {
66
79
  const evicted = [];
67
80
  // what was evicted = tombstoned positions vs the input (compare by index)
68
81
  for (let i = 0; i < pruned.length; i++) {
69
- if (pruned[i].role === 'tool' && pruned[i].content === '[context pruned: earlier tool output removed to fit budget]'
82
+ if (pruned[i].role === 'tool'
83
+ && String(pruned[i].content ?? '').includes('pruned to fit budget')
70
84
  && messages[i]?.role === 'tool' && messages[i].content !== pruned[i].content) {
71
85
  evicted.push(String(messages[i].content).slice(0, 4000));
72
86
  }
package/dist/loop.d.ts CHANGED
@@ -32,6 +32,22 @@ export interface LoopResult {
32
32
  * user interrupt - trajectory outcomes (M1) and UI labels consume it. */
33
33
  reason: 'final' | 'idle' | 'turn-valve' | 'token-valve' | 'interrupted';
34
34
  }
35
+ /** A model occasionally emits tool-call arguments that are not valid JSON —
36
+ * an empty string, or a long argument list truncated mid-string (weak/flash
37
+ * models do both under long outputs; agnes-3.0-flash hit each once on
38
+ * 2026-10-08). Every OpenAI-compatible provider REJECTS any request whose
39
+ * assistant history carries such a call (HTTP 400 "Assistant tool call
40
+ * arguments must be valid JSON"), so one malformed call used to kill the
41
+ * whole task on the NEXT turn. Sanitizing rewrites only the stored
42
+ * arguments to '{}' — the paired error tool result already tells the model
43
+ * what happened, and valid calls pass through byte-for-byte. Shared by the
44
+ * live loop (before the assistant message enters the transcript) and
45
+ * loadTranscript (before a replayed rollout re-enters one). */
46
+ export declare function sanitizeToolCalls<T extends {
47
+ function: {
48
+ arguments: string;
49
+ };
50
+ }>(calls: T[]): T[];
35
51
  export declare function runLoop(opts: {
36
52
  provider: ProviderConfig;
37
53
  registry: RegistryLike;
package/dist/loop.js CHANGED
@@ -10,6 +10,30 @@
10
10
  import { compactMessages, compactWithDigest, transcriptChars } from "./context.js";
11
11
  import { adaptiveContextChars, adaptiveMaxTurns } from "./window.js";
12
12
  import { chat } from "./provider.js";
13
+ /** A model occasionally emits tool-call arguments that are not valid JSON —
14
+ * an empty string, or a long argument list truncated mid-string (weak/flash
15
+ * models do both under long outputs; agnes-3.0-flash hit each once on
16
+ * 2026-10-08). Every OpenAI-compatible provider REJECTS any request whose
17
+ * assistant history carries such a call (HTTP 400 "Assistant tool call
18
+ * arguments must be valid JSON"), so one malformed call used to kill the
19
+ * whole task on the NEXT turn. Sanitizing rewrites only the stored
20
+ * arguments to '{}' — the paired error tool result already tells the model
21
+ * what happened, and valid calls pass through byte-for-byte. Shared by the
22
+ * live loop (before the assistant message enters the transcript) and
23
+ * loadTranscript (before a replayed rollout re-enters one). */
24
+ export function sanitizeToolCalls(calls) {
25
+ return calls.map((c) => {
26
+ if (!c.function?.arguments)
27
+ return { ...c, function: { ...c.function, arguments: '{}' } };
28
+ try {
29
+ JSON.parse(c.function.arguments);
30
+ return c;
31
+ }
32
+ catch {
33
+ return { ...c, function: { ...c.function, arguments: '{}' } };
34
+ }
35
+ });
36
+ }
13
37
  export async function runLoop(opts) {
14
38
  const { provider, registry, ctx, events } = opts;
15
39
  const modelCall = opts.chatImpl ?? chat;
@@ -29,6 +53,22 @@ export async function runLoop(opts) {
29
53
  let turn = 0;
30
54
  let idleTurns = 0; // consecutive turns with no successful tool calls
31
55
  let reason = 'final';
56
+ // Re-verification loop breaker (2026-10-07 export: 108 tool calls in 5
57
+ // user turns, 20+ turns re-deriving the SAME fact because the earlier tool
58
+ // result got tombstoned by compaction and the model doesn't trust its own
59
+ // text conclusions). Ring of recent (tool+args) → result head; an EXACT
60
+ // repeat returns the cached result with a note, saving a network call and
61
+ // telling the model it already knows this.
62
+ const recentCalls = new Map();
63
+ const callKey = (name, args) => {
64
+ try {
65
+ return name + ':' + JSON.stringify(args);
66
+ }
67
+ catch {
68
+ return name + ':unserializable';
69
+ }
70
+ };
71
+ const RESULT_HEAD_CHARS = 500;
32
72
  // The loop runs until the model gives a final answer (no tool calls), goes
33
73
  // idle (stuck), or hits a safety valve. Soft checkpoints at the adaptive
34
74
  // turn limit nudge the model but don't stop it — days-long tasks run
@@ -109,16 +149,30 @@ export async function runLoop(opts) {
109
149
  events?.onFinal?.(text, turn);
110
150
  return { text, turns: turn, toolUses, messages: working, usage, reason: 'final' };
111
151
  }
112
- working.push({ role: 'assistant', content: message.content ?? null, tool_calls: calls });
152
+ // Poison control: invalid-JSON arguments must never enter the transcript
153
+ // raw — the provider 400s the whole next request otherwise (see
154
+ // sanitizeToolCalls). The rollout recorder keeps the raw call via
155
+ // onAssistant; this is only the wire-boundary copy.
156
+ working.push({ role: 'assistant', content: message.content ?? null, tool_calls: sanitizeToolCalls(calls) });
113
157
  const planned = [];
114
158
  for (const call of calls) {
115
159
  const name = call.function.name;
160
+ const rawArgs = call.function.arguments;
116
161
  let args = {};
117
162
  let badArgs = false;
118
- try {
119
- args = call.function.arguments ? JSON.parse(call.function.arguments) : {};
163
+ if (rawArgs) {
164
+ try {
165
+ args = JSON.parse(rawArgs);
166
+ }
167
+ catch {
168
+ badArgs = true;
169
+ }
120
170
  }
121
- catch {
171
+ else {
172
+ // Empty-string arguments are invalid JSON to every provider too (they
173
+ // 400 on replay). Executing with {} used to produce a confusing shell
174
+ // error ("The argument 'file' cannot be empty") — skip with a clear
175
+ // message so the model repeats the call properly.
122
176
  badArgs = true;
123
177
  }
124
178
  events?.onToolCall?.(name, args);
@@ -130,7 +184,9 @@ export async function runLoop(opts) {
130
184
  p.skip = true;
131
185
  }
132
186
  else if (badArgs) {
133
- p.output = `unparseable tool arguments for ${name}: ${call.function.arguments.slice(0, 200)}`;
187
+ p.output = rawArgs
188
+ ? `unparseable tool arguments for ${name} (arguments must be valid JSON — repeat the call with complete JSON): ${rawArgs.slice(0, 200)}`
189
+ : `empty tool arguments for ${name} (arguments must be valid JSON — repeat the call with complete JSON)`;
134
190
  p.isError = true;
135
191
  p.skip = true;
136
192
  }
@@ -149,10 +205,31 @@ export async function runLoop(opts) {
149
205
  await Promise.all(planned.map(async (p) => {
150
206
  if (p.skip)
151
207
  return;
208
+ // Re-verification breaker: an EXACT repeat (same tool, same args) of a
209
+ // recent successful call returns the cached head instead of re-running.
210
+ // The note tells the model WHY, so it stops trying to re-verify.
211
+ const key = callKey(p.name, p.args);
212
+ const prev = recentCalls.get(key);
213
+ if (prev && !prev.isError && turn - prev.turn <= 20) {
214
+ p.output = `[you already ran ${p.name} with these exact arguments at turn ${prev.turn}; re-running identical calls wastes time — here is what it returned]\n${prev.head}`;
215
+ p.isError = false;
216
+ return;
217
+ }
152
218
  try {
153
219
  const r = await registry.get(p.name).execute(p.args, ctx);
154
220
  p.output = r.output;
155
221
  p.isError = r.isError === true;
222
+ // remember successful results for the dedup ring (errors go through
223
+ // the failed-command short-circuit instead)
224
+ if (!p.isError) {
225
+ recentCalls.set(key, { head: p.output.slice(0, RESULT_HEAD_CHARS), isError: false, turn });
226
+ if (recentCalls.size > 50) {
227
+ // drop the oldest entries when the ring fills
228
+ const firstKey = recentCalls.keys().next().value;
229
+ if (firstKey !== undefined)
230
+ recentCalls.delete(firstKey);
231
+ }
232
+ }
156
233
  }
157
234
  catch (err) {
158
235
  p.output = String(err);
package/dist/session.d.ts CHANGED
@@ -138,7 +138,12 @@ export declare function decodeSessionCursor(token: string): {
138
138
  export declare function listSessions(home: string, opts?: ListSessionsOptions): Promise<SessionsPage>;
139
139
  /** Resolve an id (or unambiguous prefix) to its rollout file across layouts. */
140
140
  export declare function findSessionFile(home: string, prefix: string): Promise<string | null>;
141
- /** Find the newest session file under home/sessions matching an id prefix. */
141
+ /** Find the newest session file under home/sessions matching an id prefix.
142
+ * Empty prefix = THE newest session overall. It used to delegate to
143
+ * findSessionFile, whose first line returns null on an empty prefix — so
144
+ * "export the latest session" could NEVER find anything (TUI /export after
145
+ * a crashed first task said "还没有可导出的会话内容" while the rollout sat
146
+ * complete on disk, 2026-10-08 session 5y1nrs). */
142
147
  export declare function latestSession(home: string, prefix?: string): Promise<string | null>;
143
148
  /**
144
149
  * Rebuild a chat transcript from a session log. Tool events don't record
package/dist/session.js CHANGED
@@ -13,6 +13,7 @@
13
13
  import { appendFile, mkdir, open as fopen, readdir, readFile, stat } from 'node:fs/promises';
14
14
  import { readFileSync, statSync } from 'node:fs';
15
15
  import { join, basename as pathBasename } from 'node:path';
16
+ import { sanitizeToolCalls } from "./loop.js";
16
17
  /** codex-rs/rollout list.rs MAX_SCAN_FILES: hard cap bounding worst-case scan work. */
17
18
  export const MAX_SCAN_FILES = 10_000;
18
19
  /** codex-rs/tui resume_picker PAGE_SIZE: sessions per listSessions page. */
@@ -391,9 +392,17 @@ export async function findSessionFile(home, prefix) {
391
392
  }
392
393
  return null;
393
394
  }
394
- /** Find the newest session file under home/sessions matching an id prefix. */
395
+ /** Find the newest session file under home/sessions matching an id prefix.
396
+ * Empty prefix = THE newest session overall. It used to delegate to
397
+ * findSessionFile, whose first line returns null on an empty prefix — so
398
+ * "export the latest session" could NEVER find anything (TUI /export after
399
+ * a crashed first task said "还没有可导出的会话内容" while the rollout sat
400
+ * complete on disk, 2026-10-08 session 5y1nrs). */
395
401
  export async function latestSession(home, prefix = '') {
396
- return findSessionFile(home, prefix);
402
+ if (prefix)
403
+ return findSessionFile(home, prefix);
404
+ const { list } = await collectCandidates(home, 'updated');
405
+ return list.length > 0 ? list[0].file : null;
397
406
  }
398
407
  /**
399
408
  * Rebuild a chat transcript from a session log. Tool events don't record
@@ -433,7 +442,10 @@ export async function loadTranscript(file) {
433
442
  out.messages.push({
434
443
  role: 'assistant',
435
444
  content: ev.text,
436
- ...(calls.length > 0 ? { tool_calls: calls } : {}),
445
+ // replay protection: a rollout may contain calls with invalid-JSON
446
+ // arguments (recorded raw for audit); replaying them into a live
447
+ // conversation would 400 the first provider call of the resumed run
448
+ ...(calls.length > 0 ? { tool_calls: sanitizeToolCalls(calls) } : {}),
437
449
  });
438
450
  pendingCallIds = calls.map((c) => c.id);
439
451
  }
package/package.json CHANGED
@@ -1,28 +1,28 @@
1
- {
2
- "name": "@hmharness/kernel",
3
- "version": "0.23.31",
4
- "description": "hmharness kernel: tool registry, provider adapters, the agent loop, session log, config. Zero runtime dependencies (Node >=22 native fetch).",
5
- "type": "module",
6
- "main": "dist/index.js",
7
- "exports": {
8
- ".": {
9
- "types": "./dist/index.d.ts",
10
- "default": "./dist/index.js"
11
- }
12
- },
13
- "types": "dist/index.d.ts",
14
- "files": [
15
- "dist"
16
- ],
17
- "engines": {
18
- "node": ">=22"
19
- },
20
- "license": "MIT",
21
- "repository": {
22
- "type": "git",
23
- "url": "git+https://github.com/swsgbl/hmharness.git"
24
- },
25
- "scripts": {
26
- "build": "tsc -p tsconfig.build.json"
27
- }
28
- }
1
+ {
2
+ "name": "@hmharness/kernel",
3
+ "version": "0.23.33",
4
+ "description": "hmharness kernel: tool registry, provider adapters, the agent loop, session log, config. Zero runtime dependencies (Node >=22 native fetch).",
5
+ "type": "module",
6
+ "main": "dist/index.js",
7
+ "exports": {
8
+ ".": {
9
+ "types": "./dist/index.d.ts",
10
+ "default": "./dist/index.js"
11
+ }
12
+ },
13
+ "types": "dist/index.d.ts",
14
+ "files": [
15
+ "dist"
16
+ ],
17
+ "engines": {
18
+ "node": ">=22"
19
+ },
20
+ "license": "MIT",
21
+ "repository": {
22
+ "type": "git",
23
+ "url": "git+https://github.com/swsgbl/hmharness.git"
24
+ },
25
+ "scripts": {
26
+ "build": "tsc -p tsconfig.build.json"
27
+ }
28
+ }