File size: 3,446 Bytes
a9e27c0
 
 
 
 
844b7df
 
a9e27c0
 
 
 
 
 
 
 
844b7df
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a9e27c0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
from __future__ import annotations
"""Explain system turns inside Messages ``messages`` to the people who send them."""

import re
from collections.abc import Mapping
from copy import deepcopy
from typing import Any

from free_claude_code.application.errors import InvalidRequestError

_CLAUDE_CODE_VERSION = re.compile(r"\bclaude-cli/(\d+(?:\.\d+)+)")
# Claude Code retries without system turns only when the refusal carries this code.
MID_CONVERSATION_SYSTEM_NOT_SUPPORTED = "mid_conversation_system_not_supported"


def normalize_supported_inline_system_turns(
    body: Mapping[str, object], headers: Mapping[str, str] | None
) -> dict[str, Any] | None:
    """Move inline system turns to ``system`` for newer Claude Code clients."""
    messages = body.get("messages")
    if not isinstance(messages, list):
        return None
    user_agent = headers.get("user-agent", "") if headers is not None else ""
    match = _CLAUDE_CODE_VERSION.search(user_agent)
    if match is None or _version_tuple(match.group(1)) < (2, 1, 317):
        return None
    inline = [
        message
        for message in messages
        if isinstance(message, Mapping) and message.get("role") == "system"
    ]
    if not inline:
        return None
    normalized = deepcopy(dict(body))
    normalized["messages"] = [
        message
        for message in messages
        if not (isinstance(message, Mapping) and message.get("role") == "system")
    ]
    system_parts: list[dict[str, Any]] = []
    existing = normalized.get("system")
    if isinstance(existing, str):
        system_parts.append({"type": "text", "text": existing})
    elif isinstance(existing, list):
        system_parts.extend(deepcopy(existing))
    for message in inline:
        content = message.get("content")
        if isinstance(content, str):
            system_parts.append({"type": "text", "text": content})
        elif isinstance(content, list):
            system_parts.extend(deepcopy(content))
    if system_parts:
        normalized["system"] = system_parts
    return normalized


def _version_tuple(version: str) -> tuple[int, ...]:
    return tuple(int(part) for part in version.split("."))


def reject_inline_system_turns(
    body: Mapping[str, object], headers: Mapping[str, str] | None
) -> None:
    """Raise an actionable error when ``messages`` holds a ``system`` turn.

    Current Claude Code recognizes the error code and resends without these
    turns. Older builds cannot recover, so the message says how to fix it.
    """

    messages = body.get("messages")
    if not isinstance(messages, list) or not any(
        isinstance(message, Mapping) and message.get("role") == "system"
        for message in messages
    ):
        return
    user_agent = headers.get("user-agent", "") if headers is not None else ""
    if match := _CLAUDE_CODE_VERSION.search(user_agent):
        raise InvalidRequestError(
            f"Claude Code {match.group(1)} sent a system message inside `messages`, "
            "which Free Claude Code can't accept. Run `claude update`, then "
            "restart Claude Code.",
            error_code=MID_CONVERSATION_SYSTEM_NOT_SUPPORTED,
        )
    raise InvalidRequestError(
        "System messages belong in the top-level `system` field, not in "
        "`messages`. If you're using Claude Code, run `claude update`, then "
        "restart it.",
        error_code=MID_CONVERSATION_SYSTEM_NOT_SUPPORTED,
    )