Commit a15bfeb
committed
fix(openrouter): add defensive JSON parsing and error recovery for streaming responses
- Add attemptJSONParse() function with 4 fallback recovery strategies for truncated JSON
1. Try parsing as-is
2. Try trimming trailing whitespace
3. Try closing incomplete JSON structures ({}, ]}, }]}, [])
4. Return null if all attempts fail
- Integrate defensive parsing into handleLine() function:
- Replace simple JSON.parse() with attemptJSONParse() with null checks
- Add error-like pattern detection to handle error responses with malformed schema
- Enhanced logging showing raw response preview and recovery attempts
- Detailed debug logs for truncated/malformed chunks
- Improve handleStreamChunk() robustness:
- Add defensive check for null/undefined/non-array choices
- Better logging with diagnostic information for empty choices
This fixes issue #367 where kimi-k2 and similar models that send truncated JSON at newline boundaries would cause silent parsing failures and agent crashes.1 parent 0f79991 commit a15bfeb
3 files changed
+124
-125
lines changed
0 commit comments