File size: 5,102 Bytes
4131875
 
5fd78ff
 
 
 
4131875
5ea523e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4131875
89b1f9c
ef5a0f7
4131875
 
 
 
 
8a87a60
 
 
 
5fd78ff
 
 
 
 
8a87a60
 
 
 
 
 
 
 
 
 
 
 
4131875
 
 
 
 
 
 
 
 
 
 
 
 
 
3f0378a
4131875
 
3f0378a
 
 
 
5ea523e
 
 
89b1f9c
 
5ea523e
89b1f9c
 
 
5ea523e
 
 
 
 
 
 
 
3f0378a
5ea523e
4131875
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
"""Event & bubble contracts (Python side). Mirrors aria-worker/src/events.js."""
import json
import re

# Internal event/bubble ids must never leak into visible text.
_ID_LEAK = re.compile(r'["\'โ€žโ€œโ€]?\b(?:evt|sys|bub|ac)_[A-Za-z0-9]+\b["\'โ€žโ€œโ€]?')

# Split a multi-sentence reply into separate messenger bubbles (chat style).
# Don't split right after a few common Polish abbreviations.
_ABBR = ("np", "itd", "itp", "tzn", "tj", "m.in", "dr", "mgr", "godz", "ok")
_SENT_SPLIT = re.compile(r'(?<=[.!?โ€ฆ])\s+')

def _split_sentences(text):
    text = (text or "").strip()
    if not text:
        return []
    out, buf = [], ""
    for part in _SENT_SPLIT.split(text):
        cand = (buf + " " + part).strip() if buf else part
        low = buf.rstrip(".").split()[-1].lower() if buf else ""
        if buf and low in _ABBR:        # don't break after "np." etc.
            buf = cand
            continue
        if buf:
            out.append(buf)
        buf = part
    if buf:
        out.append(buf)
    return [s for s in (x.strip() for x in out) if s]

EVENT_TYPES = ("message", "image", "file", "system_idle")
BUBBLE_TYPES = ("response", "follow_up", "proactive", "reaction")
ALLOWED_REACTIONS = ("โค๏ธ", "๐Ÿ˜†", "๐Ÿ˜ฎ", "๐Ÿฅน", "๐Ÿ˜ข", "๐Ÿ˜ก")

BUBBLES_MAX = 6
BUBBLE_CHARS = 1200


def _messenger_style(text):
    """Mimic how people text: lowercase start, no trailing full stop.
    Keeps '...', '?', '!', and all-caps tokens like 'XD'/'OK' intact."""
    text = text.strip()
    if not text:
        return text
    # strip any leaked internal id (e.g. evt_xxx), then tidy spacing
    text = _ID_LEAK.sub("", text)
    text = re.sub(r"\s{2,}", " ", text).strip()
    if not text:
        return text
    # drop a single trailing period (but keep an ellipsis)
    if text.endswith(".") and not text.endswith(".."):
        text = text[:-1].rstrip()
    # lowercase the first letter unless the first word is an all-caps token
    first = text.split(" ", 1)[0]
    if not (len(first) >= 2 and first.isupper()):
        text = text[:1].lower() + text[1:]
    return text


def sanitize_bubbles(raw, valid_event_ids):
    """Coerce whatever the model produced into a safe list of bubble dicts."""
    arr = raw
    if isinstance(raw, str):
        arr = _extract_json_array(raw)
    if not isinstance(arr, list):
        arr = []
    out = []
    for b in arr:
        if len(out) >= BUBBLES_MAX:
            break
        if not isinstance(b, dict):
            continue
        btype = b.get("type") if b.get("type") in BUBBLE_TYPES else "response"
        target = b.get("target_event_id") or b.get("target")
        if target not in valid_event_ids:
            target = None
        # quote / reply-to: which earlier message this bubble answers (shown as a quote)
        reply_to = b.get("reply_to") or b.get("quote")
        if reply_to not in valid_event_ids:
            reply_to = None
        # Models vary on the field name โ€” accept bubble/content/text/message/emoji.
        raw_text = (b.get("bubble") or b.get("content") or b.get("text")
                    or b.get("message") or b.get("emoji") or "")
        # Reaction: keep the raw emoji (no messenger styling); must be allowed + targeted.
        if btype == "reaction":
            emoji = str(raw_text).strip()
            if emoji in ALLOWED_REACTIONS and target:
                out.append({"bubble": emoji, "target_event_id": target, "type": "reaction"})
            continue
        # split a multi-sentence reply into separate short bubbles (chat style)
        for i, piece in enumerate(_split_sentences(str(raw_text)[:BUBBLE_CHARS])):
            if len(out) >= BUBBLES_MAX:
                break
            t = _messenger_style(piece)
            if not t:
                continue
            out.append({"bubble": t, "target_event_id": target,
                        "reply_to": reply_to if i == 0 else None,   # quote only on the first bubble
                        "type": btype if i == 0 else "follow_up"})
    return out


def _extract_json_array(s: str):
    """Best-effort: pull the first JSON array out of a model response."""
    s = s.strip()
    if s.startswith("```"):
        s = s.strip("`")
        if s.lower().startswith("json"):
            s = s[4:]
    try:
        return json.loads(s)
    except Exception:
        pass
    start, depth, in_str, esc = -1, 0, False, False
    for i, ch in enumerate(s):
        if start == -1:
            if ch == "[":
                start, depth = i, 1
            continue
        if in_str:
            if esc:
                esc = False
            elif ch == "\\":
                esc = True
            elif ch == '"':
                in_str = False
        else:
            if ch == '"':
                in_str = True
            elif ch == "[":
                depth += 1
            elif ch == "]":
                depth -= 1
                if depth == 0:
                    try:
                        return json.loads(s[start:i + 1])
                    except Exception:
                        return []
    return []