File size: 1,561 Bytes
837e3ac
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import type { ChatResponse } from "./board-actions";
import type { ParsedCommand } from "./work-package-types";

function extractAssistantMessage(rawText: string) {
  const trimmed = rawText.trim();
  if (!trimmed) return "";

  try {
    const parsed = JSON.parse(trimmed) as
      | {
          assistantMessage?: unknown;
          message?: unknown;
          content?: unknown;
          text?: unknown;
        }
      | string;

    if (typeof parsed === "string") {
      return parsed.trim();
    }

    const candidate =
      parsed?.assistantMessage ??
      parsed?.message ??
      parsed?.content ??
      parsed?.text;

    if (typeof candidate === "string" && candidate.trim()) {
      return candidate.trim();
    }
  } catch {
    // ignore
  }

  return trimmed;
}

export function recoverInvalidLlmResponse(args: {
  rawText: string;
  parsedCommand?: ParsedCommand;
  fallbackResponse?: ChatResponse;
}): ChatResponse {
  const { rawText, parsedCommand, fallbackResponse } = args;

  if (parsedCommand?.mode === "ask") {
    return {
      assistantMessage:
        extractAssistantMessage(rawText) ||
        "The model replied, but not in structured JSON. No board changes were applied.",
      boardAction: { type: "none", workPackageId: null },
    };
  }

  if (fallbackResponse) {
    return fallbackResponse;
  }

  return {
    assistantMessage:
      rawText.trim() ||
      "The model replied, but not in the required JSON contract. No board changes were applied.",
    boardAction: { type: "none", workPackageId: null },
  };
}