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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
"""
Simple generation services (title, daily tip, related questions, agent selection).
"""

from __future__ import annotations

from datetime import datetime
import re
from typing import Any
from zoneinfo import ZoneInfo

from ..models.generation import (
    DailyTipResponse,
    TitleSpaceResponse,
)
from ..models.stream_chat import StreamChatRequest
from .llm_utils import run_agent_completion, safe_json_parse


def _get_output_value(output_obj: Any, *keys: str) -> Any:
    if not output_obj:
        return None
    if isinstance(output_obj, dict):
        for key in keys:
            if key in output_obj:
                return output_obj.get(key)
        return None
    for key in keys:
        if hasattr(output_obj, key):
            return getattr(output_obj, key)
    return None


def _build_time_context(user_timezone: str | None, user_locale: str | None) -> str:
    timezone = user_timezone or "UTC"
    locale = user_locale or "en-US"
    try:
        tzinfo = ZoneInfo(timezone)
        now = datetime.now(tzinfo)
    except Exception:
        timezone = "UTC"
        now = datetime.utcnow()
    formatted = now.strftime("%Y-%m-%d %H:%M:%S")
    return (
        "\n\nLocal time context:\n"
        f"##today local time: {formatted} ({timezone})\n"
        f"locale: {locale}\n"
        f"iso: {now.isoformat()}\n"
    )


def _append_time_context(
    messages: list[dict[str, Any]],
    user_timezone: str | None,
    user_locale: str | None,
    reference_text: str | None = None,
) -> list[dict[str, Any]]:
    time_context = _build_time_context(user_timezone, user_locale)
    if not messages:
        return [{"role": "system", "content": time_context.strip()}]
    updated = list(messages)
    system_index = next((i for i, m in enumerate(updated) if m.get("role") == "system"), -1)
    if system_index != -1:
        updated[system_index] = {
            **updated[system_index],
            "content": f"{updated[system_index].get('content', '')}{time_context}",
        }
    else:
        updated.insert(0, {"role": "system", "content": time_context.strip()})
    return updated


def _normalize_title_text_output(raw: str) -> str:
    text = str(raw or "").strip()
    if not text:
        return ""
    # Common wrappers from models
    text = text.replace("\r", "\n").strip()
    first_line = next((line.strip() for line in text.split("\n") if line.strip()), "")
    text = first_line or text
    for prefix in ("title:", "标题:", "标题:", "- ", "* ", "# "):
        if text.lower().startswith(prefix.lower()):
            text = text[len(prefix):].strip()
    for prefix in (
        "suggested title:",
        "suggested title:",
        "generated title:",
        "generated title:",
        "conversation title:",
        "conversation title:",
    ):
        if text.lower().startswith(prefix.lower()):
            text = text[len(prefix):].strip()
    text = text.replace("**", "").replace("__", "").strip()
    text = text.strip().strip("\"'“”‘’")
    text = re.sub(r"^(?:user|assistant|system)\s*:\s*", "", text, flags=re.IGNORECASE)
    text = re.sub(
        r"^(?:the user(?:'s)? (?:is asking|asks|wants|needs) (?:about|for)\s+|"
        r"this conversation is about\s+|the conversation is about\s+|"
        r"topic\s*:\s*|summary\s*:\s*)",
        "",
        text,
        flags=re.IGNORECASE,
    )
    text = re.split(r"[.?!。!?]\s*", text, maxsplit=1)[0].strip()
    text = re.sub(r"\s+", " ", text).strip(" ,;:[](){}")
    text = text.strip().strip("\"'“”‘’")
    return text[:120].strip()


def _truncate_title_phrase(text: str, max_words: int = 5, max_chars: int = 36) -> str:
    normalized = re.sub(r"\s+", " ", str(text or "")).strip()
    if not normalized:
        return ""
    if " " not in normalized:
        return normalized[:max_chars].strip(" ,;:-")
    words = normalized.split(" ")
    return " ".join(words[:max_words]).strip(" ,;:-")


def _finalize_title(raw: Any, fallback: str = "New Conversation") -> str:
    title = _normalize_title_text_output(str(raw or ""))
    if not title:
        return fallback

    disallowed_starts = (
        "here is",
        "here's",
        "i can",
        "i would",
        "sure",
        "certainly",
        "let me",
        "user:",
        "assistant:",
        "system:",
    )
    lowered = title.lower()
    if lowered.startswith(disallowed_starts):
        return fallback

    title = _truncate_title_phrase(title)
    return title or fallback


def _title_prompt(task_suffix: str = "") -> str:
    suffix = f"\n{task_suffix.strip()}" if task_suffix and task_suffix.strip() else ""
    return (
        "Generate a short conversation title from the provided text.\n"
        "The text may be a user message or a short transcript.\n\n"
        "Rules:\n"
        "- Return only the title.\n"
        "- Maximum 5 words.\n"
        "- Do not answer the user.\n"
        "- Do not explain.\n"
        "- Do not use quotes or markdown."
        f"{suffix}\n\n"
        "Return only the title text."
    )


def _extract_single_emoji_text(raw: str) -> str:
    import re

    text = str(raw or "").strip()
    if not text:
        return ""

    # JSON / key-value fallback parsing still allowed, but not required.
    parsed = safe_json_parse(text)
    if isinstance(parsed, dict):
        emojis = parsed.get("emojis")
        if isinstance(emojis, list) and emojis:
            return str(emojis[0]).strip()
        if isinstance(emojis, str) and emojis.strip():
            return emojis.strip()

    m = re.search(r"emojis=\[[\"']?(.*?)[\"']?\]", text)
    if m:
        return m.group(1).strip()

    # Extract first likely emoji grapheme-ish token
    # Covers most symbols/pictographs and optional variation selector / ZWJ tails.
    m = re.search(
        r"([\u2600-\u27BF\U0001F300-\U0001FAFF](?:\uFE0F)?(?:\u200D[\u2600-\u27BF\U0001F300-\U0001FAFF](?:\uFE0F)?)*)",
        text,
    )
    if m:
        return m.group(1).strip()

    # Last resort: first non-empty token
    token = next((part for part in re.split(r"\s+", text) if part), "")
    return token[:8].strip()


async def generate_daily_tip(
    *,
    provider: str,
    language: str | None,
    category: str | None,
    api_key: str,
    base_url: str | None = None,
    model: str | None = None,
    tools: list[dict[str, Any]] | None = None,
    tool_ids: list[str] | None = None,
    user_tools: list[dict[str, Any]] | None = None,
    tool_choice: Any = None,
    response_format: dict[str, Any] | None = None,
    thinking: dict[str, Any] | bool | None = None,
    temperature: float | None = None,
    top_k: int | None = None,
    top_p: float | None = None,
    frequency_penalty: float | None = None,
    presence_penalty: float | None = None,
    context_message_limit: int | None = None,
    search_provider: str | None = None,
    tavily_api_key: str | None = None,
    user_timezone: str | None = None,
    user_locale: str | None = None,
) -> str:
    language_block = f"\n\n## Language\nReply in {language}." if language else ""
    category_block = f"\n\n## Category\n{category}" if category else ""
    messages = [
        {
            "role": "system",
            "content": (
                "## Task\n"
                "Generate a short, practical tip for today. Keep it to 1-2 sentences and avoid emojis."
                f"{category_block}{language_block}\n\n"
                "## Output\n"
                "Return only the tip text."
            ),
        },
        {"role": "user", "content": "Daily tip."},
    ]
    messages = _append_time_context(messages, user_timezone, user_locale, "daily tip")

    request = StreamChatRequest(
        provider=provider,
        apiKey=api_key,
        baseUrl=base_url,
        model=model,
        messages=messages,
        tools=tools or [],
        toolChoice=tool_choice,
        toolIds=tool_ids or [],
        userTools=user_tools or [],
        responseFormat=response_format,
        output_schema=DailyTipResponse,
        thinking=thinking,
        temperature=temperature,
        top_k=top_k,
        top_p=top_p,
        frequency_penalty=frequency_penalty,
        presence_penalty=presence_penalty,
        contextMessageLimit=context_message_limit,
        searchProvider=search_provider,
        tavilyApiKey=tavily_api_key,
        skipDefaultTools=True,
        stream=True,
    )
    result = await run_agent_completion(request)
    content = result.get("content", "").strip()
    thought = result.get("thought", "").strip()
    output_obj = result.get("output")

    tip = None
    if output_obj:
        tip = _get_output_value(output_obj, "tip")

    if not tip:
        parsed = safe_json_parse(content)
        if isinstance(parsed, dict):
            tip = parsed.get("tip")
    if not tip and thought:
        parsed = safe_json_parse(thought)
        if isinstance(parsed, dict):
            tip = parsed.get("tip")
    if not tip:
        tip = content # Fallback for plain text

    # Cleanup if model included "tip='...'"
    if tip and isinstance(tip, str) and tip.startswith("tip="):
        import re
        match = re.search(r"tip=['\"](.*?)['\"]", tip)
        if match:
            tip = match.group(1)

    return (tip or content or "").strip()


async def generate_title(
    *,
    provider: str,
    first_message: str,
    api_key: str,
    base_url: str | None = None,
    model: str | None = None,
    tools: list[dict[str, Any]] | None = None,
    tool_ids: list[str] | None = None,
    user_tools: list[dict[str, Any]] | None = None,
    tool_choice: Any = None,
    response_format: dict[str, Any] | None = None,
    thinking: dict[str, Any] | bool | None = None,
    temperature: float | None = None,
    top_k: int | None = None,
    top_p: float | None = None,
    frequency_penalty: float | None = None,
    presence_penalty: float | None = None,
    context_message_limit: int | None = None,
    search_provider: str | None = None,
    tavily_api_key: str | None = None,
    user_timezone: str | None = None,
    user_locale: str | None = None,
) -> dict[str, Any]:
    messages = [
        {
            "role": "system",
            "content": _title_prompt(),
        },
        {"role": "user", "content": first_message},
    ]
    messages = _append_time_context(messages, user_timezone, user_locale, first_message)
    request = StreamChatRequest(
        provider=provider,
        apiKey=api_key,
        baseUrl=base_url,
        model=model,
        messages=messages,
        tools=tools or [],
        toolChoice=tool_choice,
        toolIds=tool_ids or [],
        userTools=user_tools or [],
        responseFormat=None,
        output_schema=None,
        thinking=thinking,
        temperature=temperature,
        top_k=top_k,
        top_p=top_p,
        frequency_penalty=frequency_penalty,
        presence_penalty=presence_penalty,
        contextMessageLimit=context_message_limit,
        searchProvider=search_provider,
        tavilyApiKey=tavily_api_key,
        skipDefaultTools=True,
        stream=True,
    )
    result = await run_agent_completion(request)
    content = result.get("content", "").strip()
    thought = result.get("thought", "").strip()

    title = ""
    parsed = safe_json_parse(content) or {}
    if isinstance(parsed, dict):
        title = str(parsed.get("title") or "").strip()
    if not title and thought:
        parsed_thought = safe_json_parse(thought) or {}
        if isinstance(parsed_thought, dict):
            title = str(parsed_thought.get("title") or "").strip()

    # Robust cleanup for models like GLM
    if (not title or str(title).strip().startswith("title=")) and content:
        import re
        m_title = re.search(r"title=['\"](.*?)['\"]", content, flags=re.DOTALL)
        if m_title:
            title = m_title.group(1)

    # Final normalization
    title = _finalize_title(title or content)
    return {"title": title}


async def generate_emoji(
    *,
    provider: str,
    first_message: str,
    api_key: str,
    base_url: str | None = None,
    model: str | None = None,
    tools: list[dict[str, Any]] | None = None,
    tool_ids: list[str] | None = None,
    user_tools: list[dict[str, Any]] | None = None,
    tool_choice: Any = None,
    response_format: dict[str, Any] | None = None,
    thinking: dict[str, Any] | bool | None = None,
    temperature: float | None = None,
    top_k: int | None = None,
    top_p: float | None = None,
    frequency_penalty: float | None = None,
    presence_penalty: float | None = None,
    context_message_limit: int | None = None,
    search_provider: str | None = None,
    tavily_api_key: str | None = None,
    user_timezone: str | None = None,
    user_locale: str | None = None,
) -> dict[str, Any]:
    messages = [
        {
            "role": "system",
            "content": (
                "## Task\n"
                "Select exactly 1 emoji that best matches the user's message topic.\n"
                "Do NOT answer the message.\n\n"
                "## Output\n"
                "Return only 1 emoji character. No JSON. No words."
            ),
        },
        {"role": "user", "content": first_message},
    ]
    messages = _append_time_context(messages, user_timezone, user_locale, first_message)
    request = StreamChatRequest(
        provider=provider,
        apiKey=api_key,
        baseUrl=base_url,
        model=model,
        messages=messages,
        tools=tools or [],
        toolChoice=tool_choice,
        toolIds=tool_ids or [],
        userTools=user_tools or [],
        responseFormat=None,
        thinking=thinking,
        temperature=temperature,
        top_k=top_k,
        top_p=top_p,
        frequency_penalty=frequency_penalty,
        presence_penalty=presence_penalty,
        contextMessageLimit=context_message_limit,
        searchProvider=search_provider,
        tavilyApiKey=tavily_api_key,
        skipDefaultTools=True,
        stream=True,
    )
    result = await run_agent_completion(request)
    content = result.get("content", "").strip()
    thought = result.get("thought", "").strip()

    emoji = _extract_single_emoji_text(content)
    if not emoji:
        emoji = _extract_single_emoji_text(thought)
    return {"emojis": [emoji] if emoji else []}


async def generate_title_and_space(
    *,
    provider: str,
    first_message: str,
    spaces: list[dict[str, Any]],
    api_key: str,
    base_url: str | None = None,
    model: str | None = None,
    tools: list[dict[str, Any]] | None = None,
    tool_ids: list[str] | None = None,
    user_tools: list[dict[str, Any]] | None = None,
    tool_choice: Any = None,
    response_format: dict[str, Any] | None = None,
    thinking: dict[str, Any] | bool | None = None,
    temperature: float | None = None,
    top_k: int | None = None,
    top_p: float | None = None,
    frequency_penalty: float | None = None,
    presence_penalty: float | None = None,
    context_message_limit: int | None = None,
    search_provider: str | None = None,
    tavily_api_key: str | None = None,
    user_timezone: str | None = None,
    user_locale: str | None = None,
) -> dict[str, Any]:
    space_labels = ", ".join([str(s.get("label", "")).strip() for s in spaces or []]).strip()
    messages = [
        {
            "role": "system",
            "content": (
                f"{_title_prompt()}\n\n"
                "## Additional Tasks\n"
                f'1. Select the most appropriate space from the following list: [{space_labels}]. '
                "If none fit well, return null.\n"
                "2. Select 1 emoji that best matches the conversation.\n\n"
                "## Output\n"
                'Return the result as a JSON object with keys "title", "spaceLabel", and "emojis".'
            ),
        },
        {"role": "user", "content": first_message},
    ]
    messages = _append_time_context(messages, user_timezone, user_locale, first_message)
    response_format = {"type": "json_object"} if provider != "gemini" else None
    request = StreamChatRequest(
        provider=provider,
        apiKey=api_key,
        baseUrl=base_url,
        model=model,
        messages=messages,
        tools=tools or [],
        toolChoice=tool_choice,
        toolIds=tool_ids or [],
        userTools=user_tools or [],
        responseFormat=response_format,
        output_schema=TitleSpaceResponse,
        thinking=thinking,
        temperature=temperature,
        top_k=top_k,
        top_p=top_p,
        frequency_penalty=frequency_penalty,
        presence_penalty=presence_penalty,
        contextMessageLimit=context_message_limit,
        searchProvider=search_provider,
        tavilyApiKey=tavily_api_key,
        skipDefaultTools=True,
        stream=True,
    )
    result = await run_agent_completion(request)
    content = result.get("content", "").strip()
    thought = result.get("thought", "").strip()

    # Try structured output first
    output_obj = result.get("output")

    title = None
    space_label = None
    emojis = []

    # If it's a dict or model, extract directly
    if output_obj:
        title = _get_output_value(output_obj, "title")
        space_label = _get_output_value(output_obj, "space_label", "spaceLabel")
        emojis = _get_output_value(output_obj, "emojis") or []

    # If above failed, fallback to manual parsing of content
    if not title:
        parsed = safe_json_parse(content) or {}
        if isinstance(parsed, dict):
            title = parsed.get("title")
            space_label = space_label or parsed.get("spaceLabel") or parsed.get("space_label")
            emojis = emojis or parsed.get("emojis")
    if not title and thought:
        parsed = safe_json_parse(thought) or {}
        if isinstance(parsed, dict):
            title = parsed.get("title")
            space_label = space_label or parsed.get("spaceLabel") or parsed.get("space_label")
            emojis = emojis or parsed.get("emojis")

    # Robust cleanup for models like GLM (even if parsing failed partially)
    if (not title or (isinstance(title, str) and title.strip().startswith("title="))) and content:
        import re
        m_title = re.search(r"title=['\"](.*?)['\"]", content, flags=re.DOTALL)
        if m_title:
            title = m_title.group(1)

        if not emojis:
            m_emojis = re.search(r"emojis=\[[\"']?(.*?)[\"']?\]", content)
            if m_emojis:
                emojis = [m_emojis.group(1)]

        if not space_label:
            m_space = re.search(r"space_?label=['\"](.*?)['\"]", content, re.IGNORECASE) or re.search(r"space=['\"](.*?)['\"]", content, re.IGNORECASE)
            if m_space:
                space_label = m_space.group(1)

    # Normalize values
    title = _finalize_title(title or content)

    # IMPROVED matching: Case-insensitive and trimmed
    search_label = str(space_label or "").strip().lower()
    selected_space = next(
        (s for s in spaces if s.get("label", "").strip().lower() == search_label),
        None
    )

    if not isinstance(emojis, list):
        emojis = []
    emojis = [str(item).strip().strip("'").strip('"') for item in emojis if str(item).strip()][:1]

    return {"title": title, "space": selected_space, "emojis": emojis}


def _sanitize_option_text(text: Any) -> str:
    return (
        str(text or "")
        .replace("\r", " ")
        .replace("\n", " ")
        .replace("{", "")
        .replace("}", "")
        .split()
    )


async def generate_title_space_and_agent(
    *,
    provider: str,
    first_message: str,
    spaces_with_agents: list[dict[str, Any]],
    api_key: str,
    base_url: str | None = None,
    model: str | None = None,
    tools: list[dict[str, Any]] | None = None,
    tool_ids: list[str] | None = None,
    user_tools: list[dict[str, Any]] | None = None,
    tool_choice: Any = None,
    response_format: dict[str, Any] | None = None,
    thinking: dict[str, Any] | bool | None = None,
    temperature: float | None = None,
    top_k: int | None = None,
    top_p: float | None = None,
    frequency_penalty: float | None = None,
    presence_penalty: float | None = None,
    context_message_limit: int | None = None,
    search_provider: str | None = None,
    tavily_api_key: str | None = None,
    user_timezone: str | None = None,
    user_locale: str | None = None,
) -> dict[str, Any]:
    space_lines = []
    for space in spaces_with_agents or []:
        agent_entries = []
        for agent in space.get("agents") or []:
            if isinstance(agent, str):
                agent_entries.append({"name": agent})
            else:
                agent_entries.append(
                    {"name": agent.get("name", ""), "description": agent.get("description", "")}
                )
        agent_tokens = []
        for agent in agent_entries:
            name = " ".join(_sanitize_option_text(agent.get("name")))
            description = " ".join(_sanitize_option_text(agent.get("description")))
            if name and description:
                agent_tokens.append(f"{name} - {description}")
            elif name:
                agent_tokens.append(name)
        space_label = " ".join(_sanitize_option_text(space.get("label")))
        space_description = " ".join(_sanitize_option_text(space.get("description")))
        space_token = f"{space_label} - {space_description}" if space_description else space_label
        space_lines.append(f"{space_token}:{{{','.join(agent_tokens)}}}")

    messages = [
        {
            "role": "system",
            "content": (
                f"{_title_prompt()}\n\n"
                "## Additional Tasks\n"
                "1. Select the most appropriate space from the list below and return its spaceLabel.\n"
                "2. If the chosen space has agents, select the best matching agent by agentName. Otherwise return null.\n"
                "3. Select 1 emoji that best matches the conversation.\n\n"
                "## Output\n"
                'Return the result as JSON with keys "title", "spaceLabel", "agentName", and "emojis". '
                '"emojis" must be an array with 1 emoji character.'
            ),
        },
        {
            "role": "user",
            "content": f"{first_message}\n\nSpaces and agents:\n" + "\n".join(space_lines),
        },
    ]
    messages = _append_time_context(messages, user_timezone, user_locale, first_message)
    response_format = {"type": "json_object"} if provider != "gemini" else None
    request = StreamChatRequest(
        provider=provider,
        apiKey=api_key,
        baseUrl=base_url,
        model=model,
        messages=messages,
        tools=tools or [],
        toolChoice=tool_choice,
        toolIds=tool_ids or [],
        userTools=user_tools or [],
        responseFormat=response_format,
        # Avoid provider-side grammar cache collisions for lightweight JSON routes.
        # We parse JSON content locally instead of forcing native structured output.
        output_schema=None,
        thinking=thinking,
        temperature=temperature,
        top_k=top_k,
        top_p=top_p,
        frequency_penalty=frequency_penalty,
        presence_penalty=presence_penalty,
        contextMessageLimit=context_message_limit,
        searchProvider=search_provider,
        tavilyApiKey=tavily_api_key,
        skipDefaultTools=True,
        stream=True,
    )
    result = await run_agent_completion(request)
    content = result.get("content", "").strip()
    thought = result.get("thought", "").strip()

    # Try structured output first
    output_obj = result.get("output")
    title = None
    space_label = None
    agent_name = None
    emojis = []

    # If it's a dict or model, extract directly
    if output_obj:
        title = _get_output_value(output_obj, "title")
        space_label = _get_output_value(output_obj, "space_label", "spaceLabel")
        agent_name = _get_output_value(output_obj, "agent_name", "agentName")
        emojis = _get_output_value(output_obj, "emojis") or []

    # Fallback to manual parsing of content
    if not title:
        parsed = safe_json_parse(content) or {}
        if isinstance(parsed, dict):
            title = parsed.get("title")
            space_label = space_label or parsed.get("spaceLabel") or parsed.get("space_label")
            agent_name = agent_name or parsed.get("agentName") or parsed.get("agent_name")
            emojis = emojis or parsed.get("emojis")
    if not title and thought:
        parsed = safe_json_parse(thought) or {}
        if isinstance(parsed, dict):
            title = parsed.get("title")
            space_label = space_label or parsed.get("spaceLabel") or parsed.get("space_label")
            agent_name = agent_name or parsed.get("agentName") or parsed.get("agent_name")
            emojis = emojis or parsed.get("emojis")

    # Robust cleanup for models like GLM
    if (not title or (isinstance(title, str) and title.strip().startswith("title="))) and content:
        import re
        m_title = re.search(r"title=['\"](.*?)['\"]", content, flags=re.DOTALL)
        if m_title:
            title = m_title.group(1)

        if not emojis:
            m_emojis = re.search(r"emojis=\[[\"']?(.*?)[\"']?\]", content)
            if m_emojis:
                emojis = [m_emojis.group(1)]

        if not space_label:
            m_space = re.search(r"space_?label=['\"](.*?)['\"]", content, re.IGNORECASE) or re.search(r"space=['\"](.*?)['\"]", content, re.IGNORECASE)
            if m_space:
                space_label = m_space.group(1)

        if not agent_name:
            m_agent = re.search(r"agent_?name=['\"](.*?)['\"]", content, re.IGNORECASE) or re.search(r"agent=['\"](.*?)['\"]", content, re.IGNORECASE)
            if m_agent:
                agent_name = m_agent.group(1)

    # Normalize values
    title = _finalize_title(title or content)

    # Strip descriptions if model included them (e.g. "Coding - Help" -> "Coding")
    if space_label and " - " in space_label:
        space_label = space_label.split(" - ")[0].strip()
    if agent_name and " - " in agent_name:
        agent_name = agent_name.split(" - ")[0].strip()

    if not isinstance(emojis, list):
        emojis = []
    emojis = [str(item).strip().strip("'").strip('"') for item in emojis if str(item).strip()][:1]

    return {
        "title": title,
        "spaceLabel": space_label,
        "agentName": agent_name,
        "emojis": emojis,
    }


async def generate_space_and_agent(
    *,
    provider: str,
    first_message: str,
    spaces_with_agents: list[dict[str, Any]],
    api_key: str,
    base_url: str | None = None,
    model: str | None = None,
    tools: list[dict[str, Any]] | None = None,
    tool_ids: list[str] | None = None,
    user_tools: list[dict[str, Any]] | None = None,
    tool_choice: Any = None,
    response_format: dict[str, Any] | None = None,
    thinking: dict[str, Any] | bool | None = None,
    temperature: float | None = None,
    top_k: int | None = None,
    top_p: float | None = None,
    frequency_penalty: float | None = None,
    presence_penalty: float | None = None,
    context_message_limit: int | None = None,
    search_provider: str | None = None,
    tavily_api_key: str | None = None,
    user_timezone: str | None = None,
    user_locale: str | None = None,
) -> dict[str, Any]:
    space_lines: list[str] = []
    for space in spaces_with_agents or []:
        agent_entries = []
        for agent in space.get("agents") or []:
            if isinstance(agent, str):
                agent_entries.append({"name": agent})
            else:
                agent_entries.append(
                    {"name": agent.get("name", ""), "description": agent.get("description", "")}
                )
        agent_tokens = []
        for agent in agent_entries:
            name = " ".join(_sanitize_option_text(agent.get("name")))
            description = " ".join(_sanitize_option_text(agent.get("description")))
            if name and description:
                agent_tokens.append(f"{name} - {description}")
            elif name:
                agent_tokens.append(name)
        space_label = " ".join(_sanitize_option_text(space.get("label")))
        space_description = " ".join(_sanitize_option_text(space.get("description")))
        space_token = f"{space_label} - {space_description}" if space_description else space_label
        space_lines.append(f"{space_token}:{{{','.join(agent_tokens)}}}")

    messages = [
        {
            "role": "system",
            "content": (
                "You are a helpful assistant.\n"
                "## Task\n"
                "1. Select the most appropriate space from the list below and return its spaceLabel.\n"
                "2. If the chosen space has agents, select the best matching agent by agentName. Otherwise return null.\n\n"
                "## Output\n"
                'Return the result as JSON with keys "spaceLabel" and "agentName".'
            ),
        },
        {
            "role": "user",
            "content": f"{first_message}\n\nSpaces and agents:\n" + "\n".join(space_lines),
        },
    ]
    messages = _append_time_context(messages, user_timezone, user_locale, first_message)
    response_format = {"type": "json_object"} if provider != "gemini" else None
    request = StreamChatRequest(
        provider=provider,
        apiKey=api_key,
        baseUrl=base_url,
        model=model,
        messages=messages,
        tools=tools or [],
        toolChoice=tool_choice,
        toolIds=tool_ids or [],
        userTools=user_tools or [],
        responseFormat=response_format,
        thinking=thinking,
        temperature=temperature,
        top_k=top_k,
        top_p=top_p,
        frequency_penalty=frequency_penalty,
        presence_penalty=presence_penalty,
        contextMessageLimit=context_message_limit,
        searchProvider=search_provider,
        tavilyApiKey=tavily_api_key,
        skipDefaultTools=True,
        stream=True,
        # Avoid provider-side grammar cache collisions for lightweight JSON routes.
        # We parse JSON content locally instead of forcing native structured output.
        output_schema=None,
    )
    result = await run_agent_completion(request)
    content = result.get("content", "").strip()
    thought = result.get("thought", "").strip()
    thought = result.get("thought", "").strip()

    output_obj = result.get("output")
    space_label = None
    agent_name = None
    if output_obj:
        space_label = _get_output_value(output_obj, "space_label", "spaceLabel")
        agent_name = _get_output_value(output_obj, "agent_name", "agentName")

    if not space_label:
        parsed = safe_json_parse(content) or {}
        if isinstance(parsed, dict):
            space_label = parsed.get("spaceLabel") or parsed.get("space_label")
            agent_name = agent_name or parsed.get("agentName") or parsed.get("agent_name")
    if not space_label and thought:
        parsed = safe_json_parse(thought) or {}
        if isinstance(parsed, dict):
            space_label = parsed.get("spaceLabel") or parsed.get("space_label")
            agent_name = agent_name or parsed.get("agentName") or parsed.get("agent_name")

    if space_label and " - " in str(space_label):
        space_label = str(space_label).split(" - ")[0].strip()
    if agent_name and " - " in str(agent_name):
        agent_name = str(agent_name).split(" - ")[0].strip()

    return {
        "spaceLabel": space_label,
        "agentName": agent_name,
    }


async def generate_agent_for_auto(
    *,
    provider: str,
    user_message: str,
    current_space: dict[str, Any] | None,
    api_key: str,
    base_url: str | None = None,
    model: str | None = None,
    tools: list[dict[str, Any]] | None = None,
    tool_ids: list[str] | None = None,
    user_tools: list[dict[str, Any]] | None = None,
    tool_choice: Any = None,
    response_format: dict[str, Any] | None = None,
    thinking: dict[str, Any] | bool | None = None,
    temperature: float | None = None,
    top_k: int | None = None,
    top_p: float | None = None,
    frequency_penalty: float | None = None,
    presence_penalty: float | None = None,
    context_message_limit: int | None = None,
    search_provider: str | None = None,
    tavily_api_key: str | None = None,
    user_timezone: str | None = None,
    user_locale: str | None = None,
) -> str | None:
    agent_entries = []
    for agent in (current_space or {}).get("agents") or []:
        if isinstance(agent, str):
            agent_entries.append({"name": agent})
        else:
            agent_entries.append(
                {"name": agent.get("name", ""), "description": agent.get("description", "")}
            )
    agent_tokens = []
    for agent in agent_entries:
        name = " ".join(_sanitize_option_text(agent.get("name")))
        description = " ".join(_sanitize_option_text(agent.get("description")))
        if name and description:
            agent_tokens.append(f"{name} - {description}")
        elif name:
            agent_tokens.append(name)

    space_label = (current_space or {}).get("label") or "Default"
    messages = [
        {
            "role": "system",
            "content": (
                "You are a helpful assistant.\n"
                f"## Task\nSelect the best matching agent for the user's message from the \"{space_label}\" space. "
                "Consider the agent's name and description to determine which one is most appropriate. "
                "If no agent is a good match, return null.\n\n"
                "## Output\nReturn the result as JSON with key \"agentName\" (agent name only, or null)."
            ),
        },
        {
            "role": "user",
            "content": f"{user_message}\n\nAvailable agents in {space_label}:\n" + "\n".join(agent_tokens),
        },
    ]
    messages = _append_time_context(messages, user_timezone, user_locale, user_message)
    response_format = {"type": "json_object"} if provider != "gemini" else None
    request = StreamChatRequest(
        provider=provider,
        apiKey=api_key,
        baseUrl=base_url,
        model=model,
        messages=messages,
        tools=tools or [],
        toolChoice=tool_choice,
        toolIds=tool_ids or [],
        userTools=user_tools or [],
        responseFormat=response_format,
        thinking=thinking,
        temperature=temperature,
        top_k=top_k,
        top_p=top_p,
        frequency_penalty=frequency_penalty,
        presence_penalty=presence_penalty,
        contextMessageLimit=context_message_limit,
        searchProvider=search_provider,
        tavilyApiKey=tavily_api_key,
        skipDefaultTools=True,
        stream=True,
        # Avoid provider-side grammar cache collisions for this lightweight route.
        # We parse JSON content locally instead of forcing native structured output.
        output_schema=None,
    )
    result = await run_agent_completion(request)
    output_obj = result.get("output")
    if output_obj:
        selected_agent = _get_output_value(output_obj, "agentName", "agent_name")
        if selected_agent:
            return selected_agent

    parsed = safe_json_parse(result.get("content", "")) or {}
    if isinstance(parsed, dict):
        return parsed.get("agentName") or parsed.get("agent_name") or None

    thought_parsed = safe_json_parse(result.get("thought", "")) or {}
    if isinstance(thought_parsed, dict):
        return thought_parsed.get("agentName") or thought_parsed.get("agent_name") or None
    return None


def _normalize_related_questions(parsed: Any) -> list[str]:
    def _sanitize_related_question_text(value: Any) -> str:
        if not isinstance(value, str):
            return ""
        cleaned = " ".join(value.split()).strip()
        if not cleaned:
            return ""
        lowered = cleaned.lower()
        if (
            "<|tool_" in lowered
            or "tool_calls_section" in lowered
            or "tool_call_begin" in lowered
            or "tool_call_end" in lowered
            or "endgroup" in lowered
        ):
            return ""
        if cleaned in {"{", "}", "[", "]"}:
            return ""
        if len(cleaned) > 240:
            return ""
        return cleaned

    def _normalize_list(items: list[Any]) -> list[str]:
        out: list[str] = []
        seen: set[str] = set()
        for item in items or []:
            normalized = _sanitize_related_question_text(item)
            if not normalized or normalized in seen:
                continue
            seen.add(normalized)
            out.append(normalized)
            if len(out) >= 3:
                break
        return out

    if isinstance(parsed, list):
        return _normalize_list(parsed)
    if isinstance(parsed, dict):
        if isinstance(parsed.get("questions"), list):
            return _normalize_list(parsed["questions"])
        if isinstance(parsed.get("related_questions"), list):
            return _normalize_list(parsed["related_questions"])
    return []


async def generate_related_questions(
    *,
    provider: str,
    messages: list[dict[str, Any]],
    api_key: str,
    base_url: str | None = None,
    model: str | None = None,
    tools: list[dict[str, Any]] | None = None,
    tool_ids: list[str] | None = None,
    user_tools: list[dict[str, Any]] | None = None,
    tool_choice: Any = None,
    response_format: dict[str, Any] | None = None,
    thinking: dict[str, Any] | bool | None = None,
    temperature: float | None = None,
    top_k: int | None = None,
    top_p: float | None = None,
    frequency_penalty: float | None = None,
    presence_penalty: float | None = None,
    context_message_limit: int | None = None,
    search_provider: str | None = None,
    tavily_api_key: str | None = None,
    user_timezone: str | None = None,
    user_locale: str | None = None,
) -> list[str]:
    prompt_messages = [
        *(messages or []),
        {
            "role": "user",
            "content": (
                "Based on our conversation, suggest 3 short, relevant follow-up questions I (the user) might ask you next. "
                "The questions MUST be from the user's perspective (e.g., 'How does X work?', 'Tell me more about Y'). "
                "Do NOT generate questions from the assistant's perspective (e.g., 'Do you want to know about...?'). "
                "Return the result as JSON with a 'questions' key containing the array of strings."
            ),
        },
    ]
    prompt_messages = _append_time_context(prompt_messages, user_timezone, user_locale, "related questions")
    response_format = {"type": "json_object"} if provider != "gemini" else None
    request = StreamChatRequest(
        provider=provider,
        apiKey=api_key,
        baseUrl=base_url,
        model=model,
        messages=prompt_messages,
        tools=tools or [],
        toolChoice=tool_choice,
        toolIds=tool_ids or [],
        userTools=user_tools or [],
        responseFormat=response_format,
        # Avoid provider-side grammar cache collisions for this lightweight route.
        # We parse JSON content locally instead of forcing native structured output.
        output_schema=None,
        thinking=thinking,
        temperature=temperature,
        top_k=top_k,
        top_p=top_p,
        frequency_penalty=frequency_penalty,
        presence_penalty=presence_penalty,
        contextMessageLimit=context_message_limit,
        searchProvider=search_provider,
        tavilyApiKey=tavily_api_key,
        skipDefaultTools=True,
        stream=True,
    )
    result = await run_agent_completion(request)
    content = result.get("content", "").strip()
    thought = result.get("thought", "").strip()
    output_obj = result.get("output")

    questions = []
    if output_obj:
        questions = _get_output_value(output_obj, "questions") or []

    if not questions:
        parsed = safe_json_parse(content)
        # If model returned a list directly, use it
        if isinstance(parsed, list):
            questions = parsed
        else:
            questions = _normalize_related_questions(parsed)
    if not questions and thought:
        thought_parsed = safe_json_parse(thought)
        if isinstance(thought_parsed, list):
            questions = thought_parsed
        else:
            questions = _normalize_related_questions(thought_parsed)

    # Robust cleanup for weird formats
    if not questions and content:
        import re
        # Try to find questions=["..." or questions=['...']
        match = re.search(r"questions=\[([\s\S]*?)\]", content)
        if match:
            raw_list = match.group(1)
            questions = [q.strip().strip("'").strip('"') for q in re.findall(r"['\"](.*?)['\"]", raw_list)]

        # New Fallback: Try to find numbered lists like 1. "Question" or 1. **Question**
        if not questions:
            # Matches strings starting with number, dot, maybe whitespace, maybe quotes/stars, then text, then closing quotes/stars
            numbered_matches = re.findall(r"^\d+\.\s+[*\"']+(.*?)[*\"']+", content, re.MULTILINE)
            if numbered_matches:
                questions = [q.strip() for q in numbered_matches]
            else:
                # Last ditch: simplified numbered list without quotes
                numbered_matches_simple = re.findall(r"^\d+\.\s+(.*?)$", content, re.MULTILINE)
                if numbered_matches_simple:
                    questions = [q.strip().strip('*').strip('"').strip("'") for q in numbered_matches_simple]

    return _normalize_related_questions(questions)