@hmharness/kernel 0.23.32 → 0.23.34

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/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,37 @@
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
+ // Tool arguments must be a JSON OBJECT: "str" / null / [1,2] / 42 all
30
+ // parse fine but leave tools reading undefined fields (v0.23.34
31
+ // hardening - "空/截断/非对象 arguments"). Rewritten to '{}' like the
32
+ // rest: valid on the wire, harmless to execute.
33
+ const parsed = JSON.parse(c.function.arguments);
34
+ if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
35
+ return { ...c, function: { ...c.function, arguments: '{}' } };
36
+ }
37
+ return c;
38
+ }
39
+ catch {
40
+ return { ...c, function: { ...c.function, arguments: '{}' } };
41
+ }
42
+ });
43
+ }
13
44
  export async function runLoop(opts) {
14
45
  const { provider, registry, ctx, events } = opts;
15
46
  const modelCall = opts.chatImpl ?? chat;
@@ -125,16 +156,36 @@ export async function runLoop(opts) {
125
156
  events?.onFinal?.(text, turn);
126
157
  return { text, turns: turn, toolUses, messages: working, usage, reason: 'final' };
127
158
  }
128
- working.push({ role: 'assistant', content: message.content ?? null, tool_calls: calls });
159
+ // Poison control: invalid-JSON arguments must never enter the transcript
160
+ // raw — the provider 400s the whole next request otherwise (see
161
+ // sanitizeToolCalls). The rollout recorder keeps the raw call via
162
+ // onAssistant; this is only the wire-boundary copy.
163
+ working.push({ role: 'assistant', content: message.content ?? null, tool_calls: sanitizeToolCalls(calls) });
129
164
  const planned = [];
130
165
  for (const call of calls) {
131
166
  const name = call.function.name;
167
+ const rawArgs = call.function.arguments;
132
168
  let args = {};
133
169
  let badArgs = false;
134
- try {
135
- args = call.function.arguments ? JSON.parse(call.function.arguments) : {};
170
+ if (rawArgs) {
171
+ try {
172
+ const parsed = JSON.parse(rawArgs);
173
+ // valid JSON but NOT an object ("str"/null/[1,2]/42): tools would
174
+ // read undefined fields - treat like unparseable (skip + clear msg)
175
+ if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed))
176
+ badArgs = true;
177
+ else
178
+ args = parsed;
179
+ }
180
+ catch {
181
+ badArgs = true;
182
+ }
136
183
  }
137
- catch {
184
+ else {
185
+ // Empty-string arguments are invalid JSON to every provider too (they
186
+ // 400 on replay). Executing with {} used to produce a confusing shell
187
+ // error ("The argument 'file' cannot be empty") — skip with a clear
188
+ // message so the model repeats the call properly.
138
189
  badArgs = true;
139
190
  }
140
191
  events?.onToolCall?.(name, args);
@@ -146,7 +197,9 @@ export async function runLoop(opts) {
146
197
  p.skip = true;
147
198
  }
148
199
  else if (badArgs) {
149
- p.output = `unparseable tool arguments for ${name}: ${call.function.arguments.slice(0, 200)}`;
200
+ p.output = rawArgs
201
+ ? `unparseable tool arguments for ${name} (arguments must be valid JSON — repeat the call with complete JSON): ${rawArgs.slice(0, 200)}`
202
+ : `empty tool arguments for ${name} (arguments must be valid JSON — repeat the call with complete JSON)`;
150
203
  p.isError = true;
151
204
  p.skip = true;
152
205
  }
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,6 +1,6 @@
1
1
  {
2
2
  "name": "@hmharness/kernel",
3
- "version": "0.23.32",
3
+ "version": "0.23.34",
4
4
  "description": "hmharness kernel: tool registry, provider adapters, the agent loop, session log, config. Zero runtime dependencies (Node >=22 native fetch).",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",