fix: improve AI response JSON parsing robustness
This commit is contained in:
@@ -118,7 +118,9 @@ function apiSavePlugin() {
|
|||||||
let resolvedSessionId = sessionId
|
let resolvedSessionId = sessionId
|
||||||
let aiText = ''
|
let aiText = ''
|
||||||
|
|
||||||
for (const line of stdout.trim().split('\n')) {
|
for (const rawLine of stdout.split(/\r?\n/)) {
|
||||||
|
const line = rawLine.trim()
|
||||||
|
if (!line) continue
|
||||||
try {
|
try {
|
||||||
const event = JSON.parse(line)
|
const event = JSON.parse(line)
|
||||||
if (!resolvedSessionId && event.sessionID) resolvedSessionId = event.sessionID
|
if (!resolvedSessionId && event.sessionID) resolvedSessionId = event.sessionID
|
||||||
@@ -129,16 +131,16 @@ function apiSavePlugin() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (mode === 'json') {
|
if (mode === 'json') {
|
||||||
const jsonMatch = aiText.match(/```json\n?([\s\S]*?)\n?```/)
|
const codeBlock = aiText.match(/```(?:json)?\s*\n?([\s\S]*?)\n?\s*```/)
|
||||||
const jsonStr = jsonMatch ? jsonMatch[1] : aiText
|
let jsonStr = codeBlock ? codeBlock[1] : aiText
|
||||||
try {
|
try {
|
||||||
JSON.parse(jsonStr)
|
JSON.parse(jsonStr)
|
||||||
|
} catch {
|
||||||
|
const bareMatch = aiText.match(/(\{[\s\S]*\}|\[[\s\S]*\])/)
|
||||||
|
jsonStr = bareMatch ? bareMatch[0] : aiText
|
||||||
|
}
|
||||||
res.writeHead(200, { 'Content-Type': 'application/json' })
|
res.writeHead(200, { 'Content-Type': 'application/json' })
|
||||||
res.end(JSON.stringify({ result: jsonStr, sessionId: resolvedSessionId || '' }))
|
res.end(JSON.stringify({ result: jsonStr, sessionId: resolvedSessionId || '' }))
|
||||||
} catch {
|
|
||||||
res.writeHead(500)
|
|
||||||
res.end(JSON.stringify({ error: 'invalid JSON returned', raw: stdout }))
|
|
||||||
}
|
|
||||||
} else {
|
} else {
|
||||||
res.writeHead(200, { 'Content-Type': 'application/json' })
|
res.writeHead(200, { 'Content-Type': 'application/json' })
|
||||||
res.end(JSON.stringify({ result: aiText || 'done', sessionId: resolvedSessionId || '' }))
|
res.end(JSON.stringify({ result: aiText || 'done', sessionId: resolvedSessionId || '' }))
|
||||||
|
|||||||
Reference in New Issue
Block a user