#3647: fix: sanitize tool arguments in session history
agents
Cluster:
Error Handling in Agent Tools
# Pull Request: fix: sanitize tool arguments in session history
## ๐ Summary
This PR implements robust sanitization for tool arguments in session history messages. It specifically targets potential corruption where tool input arguments contain invalid JSON. The fix detects these malformed inputs and replaces them with an empty object `{}` during message loading, preventing the entire session from crashing due to `InternalError.Algo.InvalidParameter`.
## ๐ฏ Related Issues
Closes # (Session Crash Bugs)
## ๐ What's New
### Core Changes
#### 1. Session Transcript Repair
**Purpose**: To make the agent resilient to malformed session data ("dirty memory") caused by previous model errors or hallucinations.
**Implementation**:
- Added `sanitizeToolUseArgs` function in `src/agents/session-transcript-repair.ts`.
- Integrated this sanitization step into the `sanitizeToolUseResultPairing` pipeline.
- It parses every `toolUse` input block; if `JSON.parse` fails, it catches the error and repairs the block.
**Key Code**:
```typescript
// src/agents/session-transcript-repair.ts
if (typeof (block as any).input === "string") {
try {
JSON.parse((block as any).input);
nextContent.push(block);
} catch {
// Invalid JSON found in tool args.
// Replace with empty object to prevent downstream crashes.
nextContent.push({
...block,
input: {}, // Fixed
_sanitized: true,
_originalInput: (block as any).input,
});
msgChanged = true;
}
}
```
## ๐ Type of Change
- [x] ๐ Bug fix (non-breaking change that fixes an issue)
- [ ] โจ New feature (non-breaking change that adds functionality)
- [ ] ๐ฅ Breaking change (fix or feature that would cause existing functionality to change)
- [ ] ๐ Documentation update
- [ ] ๐ง Configuration change
- [ ] โป๏ธ Code refactoring (no functional changes)
- [ ] โก Performance improvement
- [ ] ๐จ UI/UX change
- [ ] ๐งช Test coverage improvement
- [ ] ๐ Security fix
## ๐งช Testing
### Automated Tests
- [ ] Unit tests added/updated
- [x] Integration tests added/updated
- [x] All existing tests pass
**Test Results**:
Verified with a reproduction script (`verify-sanitization.js`) that constructed a message with a malformed input string `"{ bad: json }"`.
- Before fix: Crash.
- After fix: Input replaced with `{}` and script succeeded.
### Manual Testing
**Testing Checklist**:
- [x] Tested in development environment
- [x] Tested with real data/production-like scenarios
- [x] Tested error scenarios
- [x] Verified no console errors/warnings
**Environments Tested**:
- [x] Development
## ๐ Deployment Strategy
### Deployment Steps
1. Merge PR.
2. Rebuild agent (`npm run build`).
3. Restart Moltbot services.
### Configuration Changes
None.
## ๐ Code Quality
- [x] ESLint passed (auto-checked by pre-commit hooks)
- [x] Prettier formatting applied (auto-checked by pre-commit hooks)
- [x] Commit messages follow conventional commits
- [x] Code reviewed by AI agent or peer
- [x] Error handling implemented for edge cases
## ๐ Security Considerations
- [x] Input validation added for user input (Sanitization protects against crashes)
## ๐ฆ Status
- [ ] ๐ด Draft - Work in progress
- [x] ๐ก Ready for Review - Code complete, needs review
- [ ] ๐ข Approved - Ready to merge
- [ ] ๐ต Merged - Deployed to staging
- [ ] โ
Complete - Deployed to production
<!-- greptile_comment -->
<h2>Greptile Overview</h2>
<h3>Greptile Summary</h3>
This PR adds a transcript-repair step (`sanitizeToolUseArgs`) that scans assistant tool-call blocks in session history and normalizes tool arguments: valid JSON strings in `input`/`arguments` are parsed into objects, and malformed JSON strings are replaced with `{}` while tagging the block as sanitized. The sanitization is then run as part of `sanitizeToolUseResultPairing` before repairing toolResult ordering/duplication.
Overall this strengthens resilience against โdirtyโ session files that would otherwise crash or be rejected by strict providers when tool-call arguments are not valid JSON.
<h3>Confidence Score: 4/5</h3>
- This PR is mostly safe to merge; main behavior change is limited to session-history repair logic.
- The change is localized and has added tests, but the current parsing accepts non-object JSON (e.g., null/arrays) which can still violate downstream tool schema expectations, and the new warning log may inadvertently leak sensitive tool inputs.
- src/agents/session-transcript-repair.ts
<!-- greptile_other_comments_section -->
<sub>(4/5) You can add custom instructions or style guidelines for the agent [here](https://app.greptile.com/review/github)!</sub>
<!-- /greptile_comment -->
Most Similar PRs
#12487: fix(agents): strip orphaned tool_result when tool_use is sanitized ...
by skylarkoo7 ยท 2026-02-09
86.5%
#8345: fix: prevent synthetic error repair from creating tool_result for d...
by vishaltandale00 ยท 2026-02-03
86.2%
#9861: fix(agents): re-run tool_use/tool_result repair after limitHistoryT...
by CyberSinister ยท 2026-02-05
86.0%
#19094: Fix empty tool_call_id and function names in provider transcript pa...
by yxshee ยท 2026-02-17
86.0%
#14328: fix: strip incomplete tool_use blocks from errored/aborted messages...
by Kropiunig ยท 2026-02-12
85.9%
#4009: fix(agent): sanitize messages after orphan user repair
by drag88 ยท 2026-01-29
85.7%
#9011: fix(session): auto-recovery for corrupted tool responses [AI-assisted]
by cheenu1092-oss ยท 2026-02-04
85.4%
#4844: fix(agents): skip error/aborted assistant messages in transcript re...
by lailoo ยท 2026-01-30
85.2%
#6687: fix(session-repair): strip malformed tool_use blocks to prevent per...
by NSEvent ยท 2026-02-01
84.8%
#21166: fix(agents): sanitize tool names in session transcript repair (#8595)
by dinakars777 ยท 2026-02-19
84.8%