Repository navigation
refactor(agent-core): align malformed tool args with schema validation - #1209
Conversation
Attempt jsonrepair when tool call arguments fail JSON.parse, then continue schema validation. Return malformed JSON errors with a concise expected schema hint so the model can retry with corrected arguments.
🦋 Changeset detectedLatest commit: 3037783 The changes in this PR will be included in the next version bump. This PR includes changesets to release 2 packages
Not sure what this means? Click here to learn what changesets are. Click here if you're a maintainer who wants to add another changeset to this PR |
|
❌ Nix build failed Hash mismatch in
Please update |
commit: |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: fd273db5f1
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| toolCall, | ||
| toolName, | ||
| args, | ||
| args: {}, |
There was a problem hiding this comment.
Preserve arguments for unknown tools
When the model calls an unavailable tool with valid JSON arguments, this branch now returns {} before parsing the provider arguments, so dispatchToolCall records {} and AgentContext.appendLoopEvent serializes {} back into the assistant tool_call transcript. Before this change, the parsed arguments were preserved even on the not-found path, which matters for transcript fidelity, auditing, and duplicate-call telemetry because distinct unknown-tool calls are now indistinguishable.
Useful? React with 👍 / 👎.
Update the fixed-output pnpmDeps hash after adding jsonrepair so the Nix build can fetch dependencies.
# Conflicts: # flake.nix
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 80930ae0f7
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| "chokidar": "^4.0.3", | ||
| "ignore": "^5.3.2", | ||
| "js-yaml": "^4.1.1", | ||
| "jsonrepair": "^3.14.1", |
There was a problem hiding this comment.
This change adds a runtime dependency and changes agent-core behavior by repairing malformed tool-call arguments before validation/execution, but the commit does not add any .changeset/ entry. The root AGENTS.md workflow requires generating a changeset before submitting a PR, and without one the release tooling/changelog will not record the user-visible CLI behavior change.
Useful? React with 👍 / 👎.
Stop repairing malformed tool call arguments. Fall back to an empty object on JSON parse failure and let schema validation produce the retry error, while preserving valid arguments for unknown tools in the transcript.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: c6ab18fb24
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| } catch (error) { | ||
| return { | ||
| success: true, | ||
| data: {}, |
There was a problem hiding this comment.
Reject malformed args before executing zero-arg tools
When a non-empty malformed arguments string is caught, this now returns success with {}. Because preflightToolCall validates and executes parsedArgs.data, any tool whose schema accepts an empty object can run even though the model supplied invalid or extra arguments; for example EnterPlanMode has a zero-arg strict schema and immediately calls planMode.enter() (packages/agent-core/src/tools/builtin/planning/enter-plan-mode.ts:19,42-43). A malformed call such as {"unexpected":true,} is therefore treated as an approved empty call instead of producing the malformed-JSON tool error that previously stopped execution.
Useful? React with 👍 / 👎.
These were the only changes in this branch that touched agent-core. They persisted two previously live-only signals (step retries, tool progress) to the wire purely so the visualizer could display them — marginal features that did not justify modifying the core loop or extending the wire surface. Reverts the agent-core loop/type/export changes (restored to main, keeping #1209) and its changeset, and removes the vis-side rendering and types that consumed step.end.retries / tool.result.progress. The rest of vis is unchanged and reads only data agent-core already persists.
…etries & tool progress (#1210) * feat(vis): surface background tasks and cron jobs The visualizer read every wire/state/blob artifact a session persists but ignored the two on-demand families agent-core also writes under the session directory: background tasks (tasks/<id>.json + output.log) and cron jobs (cron/<id>.json). Neither is reconstructable from the wire, so there was no way to inspect what a session spawned in the background or scheduled. Server: - task-store / cron-store read-only readers mirroring agent-core's on-disk layout, id-validation guard, and legacy snake_case task normalization - GET /:id/tasks, /:id/tasks/:taskId/output (byte-window paged via an exact nextOffset cursor), and /:id/cron routes - re-export the public background-task types from agent-core; mirror the non-exported CronTask shape with a fixture-backed drift test Web: - Tasks tab: process/agent/question kinds with status, timing, kind-specific fields, raw JSON, and a progressively paged output.log viewer - Cron tab: expression, prompt, recurring/one-shot, created/last-fired - count badges on both tabs Tests: +20 (lib + route), all 113 vis-server tests green; web typecheck and build clean. * feat(agent-core): persist step retries and tool progress summary Two transient signals were only ever emitted as live-only loop events, so nothing survived in the agent record for post-hoc analysis: - step retries: chatWithRetry gains an onRetry callback; turn-step collects the recovered attempts and attaches them to step.end as an optional `retries` array (previously only the live `step.retrying` event). - tool progress: tool-call distills a tool's sparse status/percent updates into a bounded `progress` summary (updateCount / lastStatus / maxPercent) on tool.result. Streamed stdout/stderr is excluded — it would bloat the wire and is already reflected in the result output. Both are additive optional fields, so the wire protocol version is unchanged and existing records keep loading. New public types: LoopStepRetryRecord, LoopToolProgressSummary. * feat(vis): add execution-analysis timeline and surface retries/progress Turn the debugger from a flat record viewer into an analysis tool. New Timeline tab: folds the wire into turns → steps → tool calls (client-side, no extra round-trip) and derives the metrics the raw list hides — per-turn / per-step / per-tool duration, per-turn token cost, a context-window fill sparkline with cache-hit rate, a tool usage table, idle-gap detection, and a config-change timeline. Inline elsewhere: - Wire rows show tool.call → tool.result elapsed time; tool.result detail shows truncation, output size, retries, and the progress summary. - Issues drawer gains tool-error, truncation, filtered, max_tokens, and retried categories. - Tasks tab links agent-kind tasks to the subagent's wire. Wires up vitest for the web package and adds analysis/issues unit tests. * feat(vis): import debug zips with a logs view and imported-session filtering A `/export-debug-zip` bundle is just `manifest.json` plus a flattened session directory, which vis already knows how to read. Importing one therefore lights up every existing tab for a session that lives on someone else's machine. Server: - zip-import: yauzl extraction with zip-slip path guards and entry-count / uncompressed-size caps for untrusted uploads. - import-store: extract a bundle into <home>/imported/<imp_…>/, validate it has a main wire, and record an import-meta.json sidecar. - session-store resolves imp_-prefixed ids against imported/, so wire / context / tasks / cron / blobs / logs all work on imported sessions; agent homedirs are re-derived locally (the bundle holds foreign absolute paths). - POST /api/imports (raw zip body) and GET /api/sessions/:id/logs (structured log lines — also available for local sessions). Web: - session rail: import button + all/local/imported filter + imported badge. - new Logs tab: virtualized, level filter, search, session/global toggle. - manifest card atop the State tab for imported sessions. SessionSummary/SessionDetail gain `imported` + `importMeta`. Tests cover extraction, the zip-slip guard, list merge, reading an imported wire through the existing route, and log parsing. * fix(vis): read tasks/cron from agent homedirs and stop persisting tool status text Addresses review feedback on the debug-tooling changes: - Background tasks and cron jobs are persisted under each agent's homedir (<session>/agents/<id>/tasks and /cron), not the session root. The Tasks and Cron tabs read the session root, so they showed nothing for normal sessions. Both routes now aggregate across detail.agents homedirs; task entries carry the owning agentId. The route-test fixtures were writing to the wrong (session-root) location too — corrected to the real agents/main layout so they actually exercise the path. - tool.result progress no longer keeps free-form status text, only updateCount and maxPercent. A tool's status string can contain sensitive data (e.g. an MCP OAuth authorization URL) that must not leak into persisted wire files or exported debug bundles. * fix(vis): stop the main content area from overflowing horizontally The <main> flex child lacked min-w-0, so it defaulted to min-width:auto and refused to shrink below its content's intrinsic width. Tabs that lay out in normal flow with flex-wrap rows (the Timeline tab) then got unbounded width, never wrapped, and blew the layout out to thousands of pixels wide. Adding min-w-0 lets the column shrink to the available width so its content wraps, truncates, or scrolls within its own container. * fix(vis): resolve local global log path and imported-state agent fallback - Logs tab: for non-imported sessions the shared global log lives at <KIMI_CODE_HOME>/logs/kimi-code.log, not under the session dir (that path is only used inside exported bundles). The route now reads the home path for local sessions, so the global-log toggle works for them. - Imported detail: a bundle's state.json is best-effort and may omit the agents map. When the inventory is empty, fall back to discovering agents from disk so routes that require an agent (wire/context) still resolve main. * fix(vis): harden imported manifest and task parsing against corrupt input An imported debug zip is untrusted, so a syntactically valid but type-corrupt file could crash whole views: - manifest.json: a non-string field (e.g. workspaceDir: 123) flowed into SessionSummary.workDir, where the session rail calls .split('/') and crashed the entire list. readManifest/readImportMeta now sanitize declared string fields, keeping only strings. - task JSON: a record that passed the shape guard but held a non-string legacy field (e.g. stop_reason: 5) threw in normalization, failing GET /tasks with a 500 and hiding all of a session's tasks. optionalNonEmptyString now tolerates non-strings, and listBackgroundTasks skips any record that still fails to normalize — honouring the reader's documented silently-skips contract. * fix(vis): discover rotated logs; keep tool progress on thrown failures - Logs tab: the diagnostic log can rotate (kimi-code.log.1, .2, …) and an exported bundle may contain only the archives. The route now discovers the active file plus its rotated siblings and concatenates them oldest-first, so a rotated-away log still surfaces (covered by node-sdk's rotated-export case). - agent-core: a tool that reported sparse progress and then threw lost its progress summary, because the catch path built the error tool.result without it. Thread progressSummary through that path too, matching the success and malformed-return paths. * fix(vis): skip type-corrupt agent entries in imported state readImportedDetail's empty-inventory fallback never ran when a bundle's state.json had a non-empty but type-corrupt agents map (e.g. `{ "agents": { "main": null } }`): inventoryAgents dereferenced the null entry and threw, so readSessionDetail returned 500 instead of recovering main from the on-disk agents/main/wire.jsonl. inventoryAgents now skips non-object entries, letting the disk-discovery fallback take over. * fix(vis): reset timeline agent on session change; preserve context on zero-usage steps - Timeline tab kept the previously-selected agent id across session navigation, so a subagent selection would 404 against the next session. Reset it to main on sessionId change, mirroring WireTab/ContextTab. - A zero-usage step.end (e.g. a content-filtered response) reset the context-window fill to 0, pushing a false drop into the Timeline chart and the Context tab. agent-core's ContextMemory keeps the prior count in that case; the analysis lib and the context projector now do the same. * revert: drop agent-core retries/tool-progress persistence These were the only changes in this branch that touched agent-core. They persisted two previously live-only signals (step retries, tool progress) to the wire purely so the visualizer could display them — marginal features that did not justify modifying the core loop or extending the wire surface. Reverts the agent-core loop/type/export changes (restored to main, keeping #1209) and its changeset, and removes the vis-side rendering and types that consumed step.end.retries / tool.result.progress. The rest of vis is unchanged and reads only data agent-core already persists.
MoonshotAI#1209) * feat(agent-core): repair malformed tool args JSON Attempt jsonrepair when tool call arguments fail JSON.parse, then continue schema validation. Return malformed JSON errors with a concise expected schema hint so the model can retry with corrected arguments. * chore(nix): update pnpm deps hash Update the fixed-output pnpmDeps hash after adding jsonrepair so the Nix build can fetch dependencies. * refactor(agent-core): drop tool args JSON repair Stop repairing malformed tool call arguments. Fall back to an empty object on JSON parse failure and let schema validation produce the retry error, while preserving valid arguments for unknown tools in the transcript. * chore: add changeset for tool args validation
…etries & tool progress (MoonshotAI#1210) * feat(vis): surface background tasks and cron jobs The visualizer read every wire/state/blob artifact a session persists but ignored the two on-demand families agent-core also writes under the session directory: background tasks (tasks/<id>.json + output.log) and cron jobs (cron/<id>.json). Neither is reconstructable from the wire, so there was no way to inspect what a session spawned in the background or scheduled. Server: - task-store / cron-store read-only readers mirroring agent-core's on-disk layout, id-validation guard, and legacy snake_case task normalization - GET /:id/tasks, /:id/tasks/:taskId/output (byte-window paged via an exact nextOffset cursor), and /:id/cron routes - re-export the public background-task types from agent-core; mirror the non-exported CronTask shape with a fixture-backed drift test Web: - Tasks tab: process/agent/question kinds with status, timing, kind-specific fields, raw JSON, and a progressively paged output.log viewer - Cron tab: expression, prompt, recurring/one-shot, created/last-fired - count badges on both tabs Tests: +20 (lib + route), all 113 vis-server tests green; web typecheck and build clean. * feat(agent-core): persist step retries and tool progress summary Two transient signals were only ever emitted as live-only loop events, so nothing survived in the agent record for post-hoc analysis: - step retries: chatWithRetry gains an onRetry callback; turn-step collects the recovered attempts and attaches them to step.end as an optional `retries` array (previously only the live `step.retrying` event). - tool progress: tool-call distills a tool's sparse status/percent updates into a bounded `progress` summary (updateCount / lastStatus / maxPercent) on tool.result. Streamed stdout/stderr is excluded — it would bloat the wire and is already reflected in the result output. Both are additive optional fields, so the wire protocol version is unchanged and existing records keep loading. New public types: LoopStepRetryRecord, LoopToolProgressSummary. * feat(vis): add execution-analysis timeline and surface retries/progress Turn the debugger from a flat record viewer into an analysis tool. New Timeline tab: folds the wire into turns → steps → tool calls (client-side, no extra round-trip) and derives the metrics the raw list hides — per-turn / per-step / per-tool duration, per-turn token cost, a context-window fill sparkline with cache-hit rate, a tool usage table, idle-gap detection, and a config-change timeline. Inline elsewhere: - Wire rows show tool.call → tool.result elapsed time; tool.result detail shows truncation, output size, retries, and the progress summary. - Issues drawer gains tool-error, truncation, filtered, max_tokens, and retried categories. - Tasks tab links agent-kind tasks to the subagent's wire. Wires up vitest for the web package and adds analysis/issues unit tests. * feat(vis): import debug zips with a logs view and imported-session filtering A `/export-debug-zip` bundle is just `manifest.json` plus a flattened session directory, which vis already knows how to read. Importing one therefore lights up every existing tab for a session that lives on someone else's machine. Server: - zip-import: yauzl extraction with zip-slip path guards and entry-count / uncompressed-size caps for untrusted uploads. - import-store: extract a bundle into <home>/imported/<imp_…>/, validate it has a main wire, and record an import-meta.json sidecar. - session-store resolves imp_-prefixed ids against imported/, so wire / context / tasks / cron / blobs / logs all work on imported sessions; agent homedirs are re-derived locally (the bundle holds foreign absolute paths). - POST /api/imports (raw zip body) and GET /api/sessions/:id/logs (structured log lines — also available for local sessions). Web: - session rail: import button + all/local/imported filter + imported badge. - new Logs tab: virtualized, level filter, search, session/global toggle. - manifest card atop the State tab for imported sessions. SessionSummary/SessionDetail gain `imported` + `importMeta`. Tests cover extraction, the zip-slip guard, list merge, reading an imported wire through the existing route, and log parsing. * fix(vis): read tasks/cron from agent homedirs and stop persisting tool status text Addresses review feedback on the debug-tooling changes: - Background tasks and cron jobs are persisted under each agent's homedir (<session>/agents/<id>/tasks and /cron), not the session root. The Tasks and Cron tabs read the session root, so they showed nothing for normal sessions. Both routes now aggregate across detail.agents homedirs; task entries carry the owning agentId. The route-test fixtures were writing to the wrong (session-root) location too — corrected to the real agents/main layout so they actually exercise the path. - tool.result progress no longer keeps free-form status text, only updateCount and maxPercent. A tool's status string can contain sensitive data (e.g. an MCP OAuth authorization URL) that must not leak into persisted wire files or exported debug bundles. * fix(vis): stop the main content area from overflowing horizontally The <main> flex child lacked min-w-0, so it defaulted to min-width:auto and refused to shrink below its content's intrinsic width. Tabs that lay out in normal flow with flex-wrap rows (the Timeline tab) then got unbounded width, never wrapped, and blew the layout out to thousands of pixels wide. Adding min-w-0 lets the column shrink to the available width so its content wraps, truncates, or scrolls within its own container. * fix(vis): resolve local global log path and imported-state agent fallback - Logs tab: for non-imported sessions the shared global log lives at <KIMI_CODE_HOME>/logs/kimi-code.log, not under the session dir (that path is only used inside exported bundles). The route now reads the home path for local sessions, so the global-log toggle works for them. - Imported detail: a bundle's state.json is best-effort and may omit the agents map. When the inventory is empty, fall back to discovering agents from disk so routes that require an agent (wire/context) still resolve main. * fix(vis): harden imported manifest and task parsing against corrupt input An imported debug zip is untrusted, so a syntactically valid but type-corrupt file could crash whole views: - manifest.json: a non-string field (e.g. workspaceDir: 123) flowed into SessionSummary.workDir, where the session rail calls .split('/') and crashed the entire list. readManifest/readImportMeta now sanitize declared string fields, keeping only strings. - task JSON: a record that passed the shape guard but held a non-string legacy field (e.g. stop_reason: 5) threw in normalization, failing GET /tasks with a 500 and hiding all of a session's tasks. optionalNonEmptyString now tolerates non-strings, and listBackgroundTasks skips any record that still fails to normalize — honouring the reader's documented silently-skips contract. * fix(vis): discover rotated logs; keep tool progress on thrown failures - Logs tab: the diagnostic log can rotate (kimi-code.log.1, .2, …) and an exported bundle may contain only the archives. The route now discovers the active file plus its rotated siblings and concatenates them oldest-first, so a rotated-away log still surfaces (covered by node-sdk's rotated-export case). - agent-core: a tool that reported sparse progress and then threw lost its progress summary, because the catch path built the error tool.result without it. Thread progressSummary through that path too, matching the success and malformed-return paths. * fix(vis): skip type-corrupt agent entries in imported state readImportedDetail's empty-inventory fallback never ran when a bundle's state.json had a non-empty but type-corrupt agents map (e.g. `{ "agents": { "main": null } }`): inventoryAgents dereferenced the null entry and threw, so readSessionDetail returned 500 instead of recovering main from the on-disk agents/main/wire.jsonl. inventoryAgents now skips non-object entries, letting the disk-discovery fallback take over. * fix(vis): reset timeline agent on session change; preserve context on zero-usage steps - Timeline tab kept the previously-selected agent id across session navigation, so a subagent selection would 404 against the next session. Reset it to main on sessionId change, mirroring WireTab/ContextTab. - A zero-usage step.end (e.g. a content-filtered response) reset the context-window fill to 0, pushing a false drop into the Timeline chart and the Context tab. agent-core's ContextMemory keeps the prior count in that case; the analysis lib and the context projector now do the same. * revert: drop agent-core retries/tool-progress persistence These were the only changes in this branch that touched agent-core. They persisted two previously live-only signals (step retries, tool progress) to the wire purely so the visualizer could display them — marginal features that did not justify modifying the core loop or extending the wire surface. Reverts the agent-core loop/type/export changes (restored to main, keeping MoonshotAI#1209) and its changeset, and removes the vis-side rendering and types that consumed step.end.retries / tool.result.progress. The rest of vis is unchanged and reads only data agent-core already persists.
Summary
parseToolCallArgumentshelper that falls back to{}when tool call arguments are not valid JSON, then continues through normal AJV validation.Notes
@moonshot-ai/agent-coreand@moonshot-ai/kimi-code.Tests
pnpm exec vitest run packages/agent-core/test/loop/tool-args-parse.test.ts packages/agent-core/test/loop/tool-call.e2e.test.tspnpm --filter @moonshot-ai/agent-core run typecheckpnpm exec oxlint --type-aware packages/agent-core/src/loop/tool-args-parse.ts packages/agent-core/src/loop/tool-call.ts packages/agent-core/test/loop/tool-args-parse.test.ts packages/agent-core/test/loop/tool-call.e2e.test.ts