diff --git a/src/commands/createTicket.ts b/src/commands/createTicket.ts index 9311581..4d5eb5a 100644 --- a/src/commands/createTicket.ts +++ b/src/commands/createTicket.ts @@ -84,9 +84,23 @@ const generateTicket = async( return null; } try { + // Strip markdown code fences the model may wrap the JSON in. + const stripped = result.replaceAll(/```(?:json)?\s*/gu, "").trim(); + // Extract the outermost JSON object in case of surrounding prose. + const jsonMatch = /\{[\s\S]*\}/u.exec(stripped); + if (jsonMatch === null) { + await logger.error( + "generateTicket", + new Error(`Non-JSON AI response: ${result.slice(0, 200)}`), + ); + return null; + } // eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- Parsing known AI JSON output. - return JSON.parse(result) as GeneratedTicket; - } catch { + return JSON.parse(jsonMatch[0]) as GeneratedTicket; + } catch (error) { + if (error instanceof Error) { + await logger.error("generateTicket", error); + } return null; } };