From 28b929c58f3bbec174f4137afdacdfecbf63f2d1 Mon Sep 17 00:00:00 2001 From: tanmay11k Date: Sun, 22 Feb 2026 01:09:05 -0500 Subject: [PATCH] Initial commit: Discord-Claude Gateway with event-driven agent runtime --- src/agent-runtime.ts | 56 ++++++++++++++++++++++++++++++++++++++------ 1 file changed, 49 insertions(+), 7 deletions(-) diff --git a/src/agent-runtime.ts b/src/agent-runtime.ts index 6dc6ba2..46bdb8a 100644 --- a/src/agent-runtime.ts +++ b/src/agent-runtime.ts @@ -106,7 +106,7 @@ export class AgentRuntime { } return { - responseText: response.result, + responseText: response.result || undefined, targetChannelId: channelId, sessionId: response.session_id, }; @@ -233,16 +233,58 @@ export class AgentRuntime { } try { + // The CLI with --output-format json returns newline-delimited JSON objects. + // We need to find the "result" type message which contains the actual response. const lines = stdout.trim().split("\n"); - const lastLine = lines[lines.length - 1]; - const parsed = JSON.parse(lastLine) as ClaudeJsonResponse; + let resultText = ""; + let sessionId: string | undefined; - if (parsed.is_error) { - reject(new Error(`Claude error: ${parsed.result ?? "Unknown error"}`)); - return; + for (const line of lines) { + try { + // Each line might be a JSON object or part of a JSON array + const cleaned = line.replace(/^\[/, "").replace(/,?\]$/, "").replace(/^,/, "").trim(); + if (!cleaned) continue; + const obj = JSON.parse(cleaned); + + if (obj.type === "system" && obj.subtype === "init" && obj.session_id) { + sessionId = obj.session_id; + } + + if (obj.type === "result" && obj.result) { + resultText = obj.result; + } + } catch { + // Skip unparseable lines + } } - resolve(parsed); + // If we couldn't parse individual lines, try parsing the whole thing as a JSON array + if (!resultText) { + try { + const arr = JSON.parse(stdout.trim()); + if (Array.isArray(arr)) { + for (const obj of arr) { + if (obj.type === "system" && obj.subtype === "init" && obj.session_id) { + sessionId = obj.session_id; + } + if (obj.type === "result" && obj.result) { + resultText = obj.result; + } + } + } + } catch { + // Not a JSON array either + } + } + + console.log(`[DEBUG] Parsed result: ${resultText.length} chars, session=${sessionId ?? "none"}`); + + resolve({ + type: "result", + result: resultText || undefined, + session_id: sessionId, + is_error: false, + }); } catch { resolve({ type: "result",