kimi-code icon indicating copy to clipboard operation
kimi-code copied to clipboard

Session restore re-quotes malformed tool-call arguments (JSON.stringify of raw-string journal fallback) → tool_use.input 400 on Anthropic-compatible providers

Open wintrover opened this issue 2 weeks ago • 3 comments

Title: Session restore re-quotes malformed tool-call arguments (JSON.stringify of raw-string journal fallback) → tool_use.input 400 on Anthropic-compatible providers

Summary

On 2.6.1, the session-restore path re-encodes journaled tool-call arguments without preserving their type. When a provider streams function.arguments = "" (the empty string), the journal stores the raw string (its JSON.parse fallback), and the restore fold re-serializes it unconditionally with JSON.stringify — turning the empty string into the two-character string '""'. That value is valid JSON which parses to the empty string, so any Anthropic-converting provider builds a tool_use.input of non-object type and the backend rejects the entire conversation with HTTP 400 messages.N.content.M.tool_use.input: Input should be an object.

The execution path handles the same call correctly, so nothing fails at the moment the tool call happens. Only a later journal restore flips the representation — and from then on every request in the session 400s, including full compaction (the self-heal path replays the same folded history). The session becomes unrecoverable on Anthropic-family models until the user switches to a model whose rail tolerates non-object tool_use.input, compacts there, and switches back.

The chain (tag 2.6.1)

(a) Stream decoder — decode.ts:276-287: ToolCall.arguments is left as "" when the provider sends function.arguments: "". The ?? null fallback only fires on null/undefined, so an empty string survives as the empty string (not null, not undefined).

(b) Journal — journal.ts:302-310 (toolArguments): arguments are JSON.parsed with a raw-string catch fallback. Object-shaped arguments journal as objects; "" fails to parse and journals as the raw string "".

(c) Restore fold — contextMemory/loopEventFold.ts:184-197 (plus the replayBuilder/fold.ts copy — this fold ships twice in the bundle) re-serializes unconditionally:

arguments: event.args === undefined ? null : JSON.stringify(event.args)

A journaled raw string "" becomes the two-character string '""' — valid JSON, parses back to the empty string. The original wire form is lost for every restore consumer.

(d) OpenAI lower — openai/lower.ts:152-158: arguments are sent verbatim (?? ''), so the restored value reaches the wire as arguments: "\"\"".

(e) Anthropic-converting providers: the provider JSON-parses arguments and places the result into tool_use.input; a parsed non-object produces tool_use.input of non-object type → HTTP 400 messages.N.content.M.tool_use.input: Input should be an object.

Note that kimi's own native Anthropic lower has the same hole (anthropic/lower.ts:127-136): parseToolArguments returns {} for null/empty/malformed input, but passes valid-JSON non-objects through as-is — so the restored '""' (valid JSON, parses to a string) would reach a native Anthropic request's tool_use.input as well. This is not purely a third-party interop quirk.

Why this is a silent wedge: the execution/restore asymmetry

kimi's execution contract is already correct: parseToolCallArguments (tool-args-parse.ts:1-21) coerces ""/null to {} and runs the tool, while malformed and valid-JSON-non-object inputs take the ToolStop path — they never execute. So the live path works.

Only journal restore flips the representation: agent-scope re-creation (getOrRestoreAgent → dispatcher.restore()) re-reads wire.jsonl from disk — triggered, for example, by killing background subagent tasks, with no process restart. From that moment:

  • every subsequent request re-quotes the empty-string arguments and 400s;
  • full compaction cannot self-heal — the compactor replays the same folded history, so the manual /compact fails identically;
  • the session is unrecoverable on Anthropic-family models until the user switches models and compacts on a tolerant one.

Repro evidence (2026-11-16, kimi 2.6.1, Linux, third-party Anthropic-compatible rail)

Trigger sequence: a session contains a tool call whose streamed function.arguments was ""; an agent-scope restore is triggered (e.g. killing a background subagent task); the next request — and every request after it, plus /compact — 400s.

  • An ExitPlanMode call was journaled with "args": "" and executed fine (coerced to {} — the plan approval completed).

  • After a subagent-kill-triggered restore, every request and the manual /compact failed with (exact text):

    messages.61.content.1.tool_use.input: Input should be an object. Unusual bug? Email [email protected] with request id 01M7GYH85G4732S0AYE1FRXVM5
    

    with the compaction twin 01M7GYHYZMNG74VDGW25ZX8XYC.

  • Direct rail probes reproduce it deterministically: replaying an assistant tool_call with arguments: "\"\"", "null", or "\"Seoul\"" in the messages array returns the same 400 (request ids 01M7H0NTCGYZKE6Z49G7PYVZFV, 01M7H0NVGXGARJFMXEHA9HPKYT, 01M7NWSRPY3FYXCJ5S4MF6N0), while arguments: "" (unparseable) is accepted — i.e. only parseable non-object arguments 400.

Proposed fix

A type dispatch in the fold:

arguments: typeof event.args === 'string' ? event.args : event.args === undefined ? null : JSON.stringify(event.args)

This restores the original wire form: "" stays "", truncated fragments stay verbatim, and objects stringify correctly. One line covers every restore consumer — TUI resume, /sessions, web/ACP replay, compaction replay.

A more durable form would pair it with a journal-side type tag, so the fold never has to guess the representation.

Related

No duplicate found — searched "Input should be an object", tool_use input, empty tool arguments, malformed arguments, resume tool arguments, restore re-encode:

  • #4863 — same topology, image_url field
  • #3087 — media twin
  • #1053 — compaction split + resume determinism
  • #3220 — dropped streamed arguments
  • PR #4269 / PR #4300 — tool_result content — explicitly excludes tool_use.input
  • PR #4274 — outgoing-request sanitizer — poison list doesn't cover argument re-quoting
  • PR #1209 — origin of the execution-side {} coercion
  • #2506 — empty-string think parts journaled raw — nearest neighbor in spirit

Environment

  • @moonshot-ai/kimi-code 2.6.1
  • Linux x64

wintrover avatar Nov 16 '26 02:11 wintrover

Cause: the restore fold turns a journaled raw string back into a JSON string literal (JSON.stringify("") is '""'), and anthropic/lower.ts parseToolArguments forwards any parseable value, object or not, into tool_use.input. Both are unchanged on main (loopEventFold.ts:190, replayBuilder/fold.ts:336, now packages/core/src/llm/builtin/protocol/anthropic/lower.ts).

I confirmed the chain by running the 2.6.1 functions themselves. A small script copies toolArguments (journal.ts), the fold expression, parseToolArguments and createDecoder (anthropic/decode.ts) verbatim from the tag and feeds them wire values. Two things came out that the issue doesn't cover yet.

1. First-party Anthropic sessions hit this too, not only function.arguments: "" rails. The native decoder starts every tool_use block with arguments: '' (decode.ts:189) and skips an empty input_json_delta (decode.ts:218, && delta.partial_json). So a tool called with no arguments, streamed with only an empty delta, is stored as ''. ExitPlanMode is a typical case, since its only parameter (options) is optional. The live request is fine, but after a restore it fails:

$ node decoder-repro.mts
decoded ToolCall.arguments  = ""
live    tool_use.input      = {}
journal args                = ""
restored arguments          = "\"\""
restore tool_use.input      = "" string

2. The proposed fold one-liner fixes "" and truncated fragments, but not parseable non-objects. For null, [] and 42, tool_use.input is still a non-object after restore, and on the live path as well, because the history keeps the streamed string and the lower passes the parsed value through:

$ node repro.mts
wire arguments  "{\"city\":\"Se"
  live    tool_use.input  {}
  restore (2.6.1)         arguments="\"{\\\"city\\\":\\\"Se\""  tool_use.input="{\"city\":\"Se"  <-- non-object
  restore (proposed fold) arguments="{\"city\":\"Se"  tool_use.input={}
wire arguments  "null"
  live    tool_use.input  null  <-- non-object
  restore (2.6.1)         arguments="null"  tool_use.input=null  <-- non-object
  restore (proposed fold) arguments="null"  tool_use.input=null  <-- non-object
  restore (proposed fold + guarded lower) tool_use.input={}
wire arguments  "[]"
  live    tool_use.input  []  <-- non-object
  restore (proposed fold) arguments="[]"  tool_use.input=[]  <-- non-object
  restore (proposed fold + guarded lower) tool_use.input={}

(Minor: the one-liner doesn't strictly give back the wire form either. A wire "\"Seoul\"" is journaled already parsed as Seoul and restored as Seoul. That's harmless, since it then fails to parse and becomes {}.)

Fix. Keep the type dispatch in both fold copies, and also make the lower refuse non-objects, so that neither restore nor a model emitting null/[] can wedge a session:

function parseToolArguments(args: string | null): Record<string, unknown> {
  if (args === null || args.trim() === '') {
    return {};
  }
  try {
    const parsed: unknown = JSON.parse(args);
    return parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed)
      ? (parsed as Record<string, unknown>)
      : {};
  } catch {
    return {};
  }
}

{} is already what this function returns for null, empty and malformed arguments, so the change only extends that existing fallback to valid JSON that isn't an object. For third-party rails behind openai/lower.ts, kimi doesn't control the conversion. The equivalent guard there is to send '{}' when arguments parses to a non-object. Regression cases worth pinning: a fold test with journaled args: "" expecting restored arguments: "", and an anthropic-lower.test.ts case where arguments: 'null' lowers to input: {}.

aron-intframe avatar Nov 16 '26 03:11 aron-intframe

Also reproducible on CLI 2.7.3 (Linux x86_64) with no-argument TaskList and CronList calls, not only ExitPlanMode.

There is an important interaction with #5268. That change preserves the raw argument bytes for newly written records through argsRaw, but the legacy path remains on current main:

event.argsRaw ?? (event.args === undefined ? null : JSON.stringify(event.args))

In both restore folds, a legacy record such as:

{"type":"tool.call","name":"TaskList","args":""}

still restores arguments as "\"\"". The native Anthropic lower then JSON.parses that to an empty string, which Bedrock/LiteLLM rejects as tool_use.input.

I verified the failure and the workaround on 2.7.3: rewriting the affected legacy args: "" records to args: {} unblocks the session, while a fresh process still encounters the same issue when restoring other legacy records. #5288 is reporting the same failure mode.

Could a maintainer /approve a scoped bug-fix PR for the legacy fallback in both restore folds, with regression tests for args: "", malformed raw strings, and parsed non-objects? I can also include the guarded non-object return in anthropic/lower.ts if preferred, or keep that as a separate change.

lucifer1004 avatar Nov 25 '26 01:11 lucifer1004

Closing this as fixed on main by #5268 and #5234 (both merged on Nov 23, shipping in the next release after 2.7.3):

  • #5268 preserves raw tool-call argument bytes (argsRaw) across journal restore, so an empty string "" is no longer re-encoded into '""' by JSON.stringify(event.args) during the restore fold.
  • #5234 validates newly streamed tool-call arguments in settle.ts before execution or persistence, retrying with a temporary correction message when a provider returns malformed or non-object arguments.

(For legacy sessions already persisted with non-object JSON primitives in history, see also open PR #5356 for an additional object fallback at the Anthropic lowering boundary.)

sailist avatar Nov 25 '26 14:11 sailist