File size: 33,664 Bytes
7cfdc4c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Runtime caching layer for latency optimization.

This module provides Redis-based caching for frequently accessed data:
- Agent configs (Suna static + user MCPs, custom agent configs)
- Project metadata (sandbox info)
- Running runs count (concurrent limit checks)
- Thread count (thread limit checks)

All caches use explicit invalidation on data changes, with TTL as safety net.
"""
import json
import time
from typing import Dict, Any, Optional, Union
from core.utils.logger import logger

# Use orjson for cache operations (3-5x faster than stdlib json)
try:
    import orjson
    _HAS_ORJSON = True
except ImportError:
    _HAS_ORJSON = False

def _json_dumps(value: Any) -> str:
    """Fast JSON serialization using orjson when available."""
    if _HAS_ORJSON:
        return orjson.dumps(value).decode('utf-8')
    return json.dumps(value)

def _json_loads(value: Union[str, bytes]) -> Any:
    """Fast JSON deserialization using orjson when available."""
    if _HAS_ORJSON:
        if isinstance(value, str):
            return orjson.loads(value.encode('utf-8'))
        return orjson.loads(value)
    if isinstance(value, bytes):
        return json.loads(value.decode('utf-8'))
    return json.loads(value)

# ============================================================================
# STATIC SUNA CONFIG - Loaded once at startup, never expires
# This is Python code that's identical across all workers - safe to keep in memory
# ============================================================================
_SUNA_STATIC_CONFIG: Optional[Dict[str, Any]] = None
_SUNA_STATIC_LOADED = False

def get_static_suna_config() -> Optional[Dict[str, Any]]:
    """Get the static Suna config (loaded once at startup)."""
    return _SUNA_STATIC_CONFIG

def load_static_suna_config() -> Dict[str, Any]:
    """
    Load Suna's static config into memory ONCE.
    This includes: system_prompt, model, agentpress_tools, restrictions.
    
    This is safe to cache in memory because it's Python code - identical across all workers.
    """
    global _SUNA_STATIC_CONFIG, _SUNA_STATIC_LOADED
    
    if _SUNA_STATIC_LOADED:
        return _SUNA_STATIC_CONFIG
    
    from core.config.suna_config import SUNA_CONFIG
    from core.config.config_helper import _extract_agentpress_tools_for_run
    
    _SUNA_STATIC_CONFIG = {
        'system_prompt': SUNA_CONFIG['system_prompt'],
        'model': SUNA_CONFIG['model'],
        'agentpress_tools': _extract_agentpress_tools_for_run(SUNA_CONFIG['agentpress_tools']),
        'centrally_managed': True,
        'is_suna_default': True,
        'restrictions': {
            'system_prompt_editable': False,
            'tools_editable': False,
            'name_editable': False,
            'description_editable': False,
            'mcps_editable': True
        }
    }
    
    _SUNA_STATIC_LOADED = True
    logger.info(f"βœ… Loaded static Suna config into memory (prompt: {len(_SUNA_STATIC_CONFIG['system_prompt'])} chars)")
    return _SUNA_STATIC_CONFIG

# ============================================================================
# AGENT CONFIG CACHE - Redis, invalidated on version changes
# ============================================================================
AGENT_CONFIG_TTL = 3600  # 1 hour (was 24h - reduced to save Redis memory)

def _get_cache_key(agent_id: str, version_id: Optional[str] = None) -> str:
    """Generate Redis cache key for agent config."""
    if version_id:
        return f"agent_config:{agent_id}:{version_id}"
    return f"agent_config:{agent_id}:current"

def _get_user_mcps_key(agent_id: str) -> str:
    """Generate cache key for user-specific MCPs."""
    return f"agent_mcps:{agent_id}"


async def get_cached_user_mcps(agent_id: str) -> Optional[Dict[str, Any]]:
    """
    Get user-specific MCPs from Redis cache.
    
    Returns dict with configured_mcps, custom_mcps, triggers.
    """
    cache_key = _get_user_mcps_key(agent_id)
    
    try:
        from core.services import redis as redis_service
        
        cached = await redis_service.get(cache_key)
        if cached:
            data = _json_loads(cached) if isinstance(cached, (str, bytes)) else cached
            logger.debug(f"⚑ Redis cache hit for user MCPs: {agent_id}")
            return data
    except Exception as e:
        logger.warning(f"Failed to get user MCPs from cache: {e}")
    
    return None


async def set_cached_user_mcps(
    agent_id: str,
    configured_mcps: list,
    custom_mcps: list,
    triggers: list = None
) -> None:
    """Cache user-specific MCPs in Redis."""
    cache_key = _get_user_mcps_key(agent_id)
    data = {
        'configured_mcps': configured_mcps,
        'custom_mcps': custom_mcps,
        'triggers': triggers or []
    }
    
    try:
        from core.services import redis as redis_service
        await redis_service.set(cache_key, _json_dumps(data), ex=AGENT_CONFIG_TTL)
        logger.debug(f"βœ… Cached user MCPs in Redis: {agent_id}")
    except Exception as e:
        logger.warning(f"Failed to cache user MCPs: {e}")


MCP_VERSION_CONFIG_TTL = 300

def _get_mcp_version_config_key(agent_id: str) -> str:
    return f"mcp_version_config:{agent_id}"


async def get_cached_mcp_version_config(agent_id: str) -> Optional[Dict[str, Any]]:
    cache_key = _get_mcp_version_config_key(agent_id)
    
    try:
        from core.services import redis as redis_service
        
        cached = await redis_service.get(cache_key)
        if cached:
            data = _json_loads(cached) if isinstance(cached, (str, bytes)) else cached
            logger.debug(f"⚑ Redis cache hit for MCP version config: {agent_id}")
            return data
    except Exception as e:
        logger.warning(f"Failed to get MCP version config from cache: {e}")
    
    return None


async def set_cached_mcp_version_config(agent_id: str, config: Dict[str, Any]) -> None:
    cache_key = _get_mcp_version_config_key(agent_id)
    
    try:
        from core.services import redis as redis_service
        await redis_service.set(cache_key, _json_dumps(config), ex=MCP_VERSION_CONFIG_TTL)
        logger.debug(f"βœ… Cached MCP version config in Redis: {agent_id}")
    except Exception as e:
        logger.warning(f"Failed to cache MCP version config: {e}")


async def invalidate_mcp_version_config(agent_id: str) -> None:
    cache_key = _get_mcp_version_config_key(agent_id)
    
    try:
        from core.services import redis as redis_service
        await redis_service.delete(cache_key)
        logger.debug(f"πŸ—‘οΈ Invalidated MCP version config cache: {agent_id}")
    except Exception as e:
        logger.warning(f"Failed to invalidate MCP version config: {e}")


async def get_cached_agent_config(
    agent_id: str,
    version_id: Optional[str] = None
) -> Optional[Dict[str, Any]]:
    """
    Get agent config from Redis cache.
    
    For custom agents only - Suna uses get_static_suna_config() + get_cached_user_mcps().
    """
    cache_key = _get_cache_key(agent_id, version_id)
    
    try:
        from core.services import redis as redis_service
        
        cached = await redis_service.get(cache_key)
        if cached:
            data = _json_loads(cached) if isinstance(cached, (str, bytes)) else cached
            logger.debug(f"⚑ Redis cache hit for agent config: {agent_id}")
            return data
    except Exception as e:
        logger.warning(f"Failed to get agent config from cache: {e}")
    
    return None


async def set_cached_agent_config(
    agent_id: str,
    config: Dict[str, Any],
    version_id: Optional[str] = None,
    is_suna_default: bool = False
) -> None:
    await set_cached_agent_type(agent_id, is_suna_default)
    
    if is_suna_default:
        await set_cached_user_mcps(
            agent_id,
            config.get('configured_mcps', []),
            config.get('custom_mcps', []),
            config.get('triggers', [])
        )
        return
    
    cache_key = _get_cache_key(agent_id, version_id)
    
    try:
        from core.services import redis as redis_service
        await redis_service.set(cache_key, _json_dumps(config), ex=AGENT_CONFIG_TTL)
        logger.debug(f"βœ… Cached custom agent config in Redis: {agent_id}")
    except Exception as e:
        logger.warning(f"Failed to cache agent config: {e}")


def _get_agent_type_key(agent_id: str) -> str:
    return f"agent_type:{agent_id}"


async def get_cached_agent_type(agent_id: str) -> Optional[str]:
    cache_key = _get_agent_type_key(agent_id)
    try:
        from core.services import redis as redis_service
        return await redis_service.get(cache_key)
    except Exception as e:
        logger.warning(f"Failed to get agent type from cache: {e}")
    return None


async def set_cached_agent_type(agent_id: str, is_suna: bool) -> None:
    cache_key = _get_agent_type_key(agent_id)
    try:
        from core.services import redis as redis_service
        await redis_service.set(cache_key, "suna" if is_suna else "custom", ex=AGENT_CONFIG_TTL)
    except Exception as e:
        logger.warning(f"Failed to cache agent type: {e}")


async def invalidate_agent_config_cache(agent_id: str) -> None:
    """Invalidate cached configs for an agent in Redis using batch delete."""
    try:
        from core.services.redis import delete_multiple
        keys = [
            f"agent_config:{agent_id}:current",
            f"agent_mcps:{agent_id}",
            f"agent_type:{agent_id}"
        ]
        deleted = await delete_multiple(keys, timeout=5.0)
        logger.info(f"πŸ—‘οΈ Invalidated Redis cache for agent: {agent_id} ({deleted} keys)")
    except Exception as e:
        logger.warning(f"Failed to invalidate cache: {e}")


async def warm_up_suna_config_cache() -> None:
    """
    Load static Suna config into memory at worker startup.
    
    This is instant since it just reads from SUNA_CONFIG (Python code).
    No DB calls needed for the static parts.
    """
    t_start = time.time()
    
    # Load static Suna config (system prompt, model, tools) - instant
    load_static_suna_config()
    
    elapsed = (time.time() - t_start) * 1000
    logger.info(f"βœ… Suna static config loaded in {elapsed:.1f}ms (zero DB calls)")


async def prewarm_user_agents(user_id: str) -> dict:
    import asyncio
    t_start = time.time()
    
    try:
        from core.agents import repo as agents_repo
        from core.agents.agent_loader import get_agent_loader
        
        agent_ids = await agents_repo.get_user_agent_ids(user_id)
        
        if not agent_ids:
            try:
                from core.utils.ensure_suna import ensure_suna_installed
                await ensure_suna_installed(user_id)
                agent_ids = await agents_repo.get_user_agent_ids(user_id)
                if agent_ids:
                    logger.info(f"[PREWARM] Installed Suna for new user {user_id[:8]}...")
            except Exception as e:
                logger.debug(f"[PREWARM] Could not ensure Suna for {user_id[:8]}...: {e}")
        
        if not agent_ids:
            logger.debug(f"[PREWARM] No agents for user {user_id[:8]}...")
            return {"prewarmed": 0, "errors": 0, "skipped": 0}
        
        loader = await get_agent_loader()
        prewarmed = 0
        errors = 0
        skipped = 0
        
        async def prewarm_single(agent_id: str) -> bool:
            try:
                agent_type = await get_cached_agent_type(agent_id)
                if agent_type == "suna":
                    mcps = await get_cached_user_mcps(agent_id)
                    if mcps is not None:
                        return None 
                elif agent_type == "custom":
                    cached = await get_cached_agent_config(agent_id)
                    if cached:
                        return None 
                
                agent_data = await loader.load_agent(agent_id, user_id, load_config=True)
                if agent_data:
                    return True
                return False
            except Exception as e:
                logger.warning(f"[PREWARM] Failed for agent {agent_id}: {e}")
                return False
        
        batch_size = 5
        for i in range(0, len(agent_ids), batch_size):
            batch = agent_ids[i:i + batch_size]
            results = await asyncio.gather(*[prewarm_single(aid) for aid in batch], return_exceptions=True)
            
            for result in results:
                if result is None:
                    skipped += 1
                elif result is True:
                    prewarmed += 1
                else:
                    errors += 1
        
        elapsed = (time.time() - t_start) * 1000
        logger.info(f"βœ… [PREWARM] User {user_id[:8]}...: {prewarmed} loaded, {skipped} cached, {errors} errors ({elapsed:.0f}ms)")
        
        return {"prewarmed": prewarmed, "errors": errors, "skipped": skipped}
        
    except Exception as e:
        elapsed = (time.time() - t_start) * 1000
        logger.error(f"[PREWARM] User {user_id[:8]}... failed after {elapsed:.0f}ms: {e}")
        return {"prewarmed": 0, "errors": 1, "skipped": 0, "error": str(e)}


# ============================================================================
# PROJECT METADATA CACHE - Invalidated on sandbox changes
# ============================================================================
PROJECT_CACHE_TTL = 300  # 5 minutes (invalidated on sandbox change)

def _get_project_cache_key(project_id: str) -> str:
    """Generate Redis cache key for project metadata."""
    return f"project_meta:{project_id}"


async def get_cached_project_metadata(project_id: str) -> Optional[Dict[str, Any]]:
    """
    Get project metadata (sandbox info) from Redis cache.
    Eliminates ~300ms DB query on repeated agent runs.
    """
    cache_key = _get_project_cache_key(project_id)
    
    try:
        from core.services import redis as redis_service
        
        cached = await redis_service.get(cache_key)
        if cached:
            data = _json_loads(cached) if isinstance(cached, (str, bytes)) else cached
            logger.debug(f"⚑ Redis cache hit for project metadata: {project_id}")
            return data
    except Exception as e:
        logger.warning(f"Failed to get project metadata from cache: {e}")
    
    return None


async def set_cached_project_metadata(project_id: str, sandbox: Dict[str, Any]) -> None:
    """Cache project metadata in Redis."""
    cache_key = _get_project_cache_key(project_id)
    data = {'project_id': project_id, 'sandbox': sandbox}
    
    try:
        from core.services import redis as redis_service
        await redis_service.set(cache_key, _json_dumps(data), ex=PROJECT_CACHE_TTL)
        logger.debug(f"βœ… Cached project metadata in Redis: {project_id}")
    except Exception as e:
        logger.warning(f"Failed to cache project metadata: {e}")


async def invalidate_project_cache(project_id: str) -> None:
    """Invalidate cached project metadata."""
    try:
        from core.services import redis as redis_service
        await redis_service.delete(_get_project_cache_key(project_id))
        logger.debug(f"πŸ—‘οΈ Invalidated project cache: {project_id}")
    except Exception as e:
        logger.warning(f"Failed to invalidate project cache: {e}")


# Alias for backwards compatibility
invalidate_project_metadata = invalidate_project_cache


# ============================================================================
# RUNNING RUNS CACHE - Short TTL for concurrent runs limit checks
# ============================================================================
RUNNING_RUNS_TTL = 5  # 5 seconds - needs fresh data for limit accuracy

def _get_running_runs_key(account_id: str) -> str:
    """Generate Redis cache key for running runs count."""
    return f"running_runs:{account_id}"


async def get_cached_running_runs(account_id: str) -> Optional[Dict[str, Any]]:
    """
    Get running runs data from Redis cache.
    Short TTL to balance freshness and latency.
    """
    cache_key = _get_running_runs_key(account_id)
    
    try:
        from core.services import redis as redis_service
        
        cached = await redis_service.get(cache_key)
        if cached:
            data = _json_loads(cached) if isinstance(cached, (str, bytes)) else cached
            logger.debug(f"⚑ Redis cache hit for running runs: {account_id}")
            return data
    except Exception as e:
        logger.warning(f"Failed to get running runs from cache: {e}")
    
    return None


async def set_cached_running_runs(
    account_id: str, 
    running_count: int, 
    running_thread_ids: list
) -> None:
    """Cache running runs data in Redis."""
    cache_key = _get_running_runs_key(account_id)
    # Convert UUIDs to strings for JSON serialization
    thread_ids_str = [str(tid) for tid in running_thread_ids] if running_thread_ids else []
    data = {
        'running_count': running_count,
        'running_thread_ids': thread_ids_str,
        'cached_at': time.time()
    }
    
    try:
        from core.services import redis as redis_service
        await redis_service.set(cache_key, _json_dumps(data), ex=RUNNING_RUNS_TTL)
        logger.debug(f"βœ… Cached running runs in Redis: {account_id} ({running_count} runs)")
    except Exception as e:
        logger.warning(f"Failed to cache running runs: {e}")


async def invalidate_running_runs_cache(account_id: str) -> None:
    """Invalidate cached running runs when agent starts/stops."""
    try:
        from core.services import redis as redis_service
        await redis_service.delete(_get_running_runs_key(account_id))
        logger.debug(f"πŸ—‘οΈ Invalidated running runs cache: {account_id}")
    except Exception as e:
        logger.warning(f"Failed to invalidate running runs cache: {e}")


# ============================================================================
# THREAD COUNT CACHE - Invalidated on thread create/delete
# ============================================================================
THREAD_COUNT_TTL = 300  # 5 minutes (invalidated on create/delete)

def _get_thread_count_key(account_id: str) -> str:
    """Generate Redis cache key for thread count."""
    return f"thread_count:{account_id}"


async def get_cached_thread_count(account_id: str) -> Optional[int]:
    """Get thread count from Redis cache."""
    cache_key = _get_thread_count_key(account_id)
    
    try:
        from core.services import redis as redis_service
        
        cached = await redis_service.get(cache_key)
        if cached is not None:
            count = int(cached) if isinstance(cached, (str, bytes)) else cached
            logger.debug(f"⚑ Redis cache hit for thread count: {account_id} ({count} threads)")
            return count
    except Exception as e:
        logger.warning(f"Failed to get thread count from cache: {e}")
    
    return None


async def set_cached_thread_count(account_id: str, count: int) -> None:
    """Cache thread count in Redis."""
    cache_key = _get_thread_count_key(account_id)
    
    try:
        from core.services import redis as redis_service
        await redis_service.set(cache_key, str(count), ex=THREAD_COUNT_TTL)
        logger.debug(f"βœ… Cached thread count in Redis: {account_id} ({count} threads)")
    except Exception as e:
        logger.warning(f"Failed to cache thread count: {e}")


async def increment_thread_count_cache(account_id: str) -> None:
    """Increment cached thread count when a new thread is created."""
    cache_key = _get_thread_count_key(account_id)
    
    try:
        from core.services import redis as redis_service
        # Use INCR for atomic increment, but only if key exists
        current = await redis_service.get(cache_key)
        if current is not None:
            await redis_service.incr(cache_key)
            logger.debug(f"βœ… Incremented thread count cache: {account_id}")
    except Exception as e:
        logger.warning(f"Failed to increment thread count cache: {e}")


async def invalidate_thread_count_cache(account_id: str) -> None:
    """Invalidate cached thread count when thread is deleted."""
    try:
        from core.services import redis as redis_service
        await redis_service.delete(_get_thread_count_key(account_id))
        logger.debug(f"πŸ—‘οΈ Invalidated thread count cache: {account_id}")
    except Exception as e:
        logger.warning(f"Failed to invalidate thread count cache: {e}")


# ============================================================================
# KNOWLEDGE BASE CONTEXT CACHE - Short TTL, invalidated on KB mutations
# ============================================================================
KB_CONTEXT_TTL = 300  # 5 minutes

def _get_kb_context_key(agent_id: str) -> str:
    """Generate Redis cache key for knowledge base context."""
    return f"kb_context:{agent_id}"


async def get_cached_kb_context(agent_id: str) -> Optional[str]:
    """
    Get knowledge base context from Redis cache.
    Returns None on cache miss, empty string if cached as "no entries".
    """
    cache_key = _get_kb_context_key(agent_id)
    
    try:
        from core.services import redis as redis_service
        
        cached = await redis_service.get(cache_key)
        if cached is not None:
            # Empty string means "no entries", None means cache miss
            data = cached.decode() if isinstance(cached, bytes) else cached
            logger.debug(f"⚑ Redis cache hit for KB context: {agent_id}")
            return data if data else None  # Return None for empty string (no entries)
    except Exception as e:
        logger.warning(f"Failed to get KB context from cache: {e}")
    
    return None  # Cache miss


async def set_cached_kb_context(agent_id: str, context: str) -> None:
    """
    Cache knowledge base context in Redis.
    Use empty string to cache "no entries" result.
    """
    cache_key = _get_kb_context_key(agent_id)
    
    try:
        from core.services import redis as redis_service
        # Store empty string as empty string (to distinguish from cache miss)
        await redis_service.set(cache_key, context, ex=KB_CONTEXT_TTL)
        logger.debug(f"βœ… Cached KB context in Redis: {agent_id} ({len(context)} chars)")
    except Exception as e:
        logger.warning(f"Failed to cache KB context: {e}")


async def invalidate_kb_context_cache(agent_id: str) -> None:
    """Invalidate cached knowledge base context when KB entries change."""
    try:
        from core.services import redis as redis_service
        await redis_service.delete(_get_kb_context_key(agent_id))
        logger.debug(f"πŸ—‘οΈ Invalidated KB context cache: {agent_id}")
    except Exception as e:
        logger.warning(f"Failed to invalidate KB context cache: {e}")


# ============================================================================
# USER CONTEXT CACHE - Locale + username, invalidated on profile updates
# ============================================================================
USER_CONTEXT_TTL = 900  # 15 minutes

def _get_user_context_key(user_id: str) -> str:
    """Generate Redis cache key for user context."""
    return f"user_context:{user_id}"


async def get_cached_user_context(user_id: str) -> Optional[str]:
    """
    Get user context (locale + username) from Redis cache.
    Returns None on cache miss, empty string if cached as "no context".
    """
    cache_key = _get_user_context_key(user_id)
    
    try:
        from core.services import redis as redis_service
        
        cached = await redis_service.get(cache_key)
        if cached is not None:
            data = cached.decode() if isinstance(cached, bytes) else cached
            logger.debug(f"⚑ Redis cache hit for user context: {user_id}")
            return data if data else None  # Return None for empty string (no context)
    except Exception as e:
        logger.warning(f"Failed to get user context from cache: {e}")
    
    return None  # Cache miss


async def set_cached_user_context(user_id: str, context: str) -> None:
    """
    Cache user context in Redis.
    Use empty string to cache "no context" result.
    """
    cache_key = _get_user_context_key(user_id)
    
    try:
        from core.services import redis as redis_service
        await redis_service.set(cache_key, context, ex=USER_CONTEXT_TTL)
        logger.debug(f"βœ… Cached user context in Redis: {user_id} ({len(context)} chars)")
    except Exception as e:
        logger.warning(f"Failed to cache user context: {e}")


async def invalidate_user_context_cache(user_id: str) -> None:
    """Invalidate cached user context when profile is updated."""
    try:
        from core.services import redis as redis_service
        await redis_service.delete(_get_user_context_key(user_id))
        logger.debug(f"πŸ—‘οΈ Invalidated user context cache: {user_id}")
    except Exception as e:
        logger.warning(f"Failed to invalidate user context cache: {e}")


# ============================================================================
# MESSAGE HISTORY CACHE - Short TTL for repeated turns in same thread
# ============================================================================
MESSAGE_HISTORY_TTL = 60  # 1 minute - very short since messages change frequently

def _get_message_history_key(thread_id: str) -> str:
    """Generate Redis cache key for message history."""
    return f"message_history:{thread_id}"


async def get_cached_message_history(thread_id: str) -> Optional[list]:
    """Get message history from Redis cache."""
    cache_key = _get_message_history_key(thread_id)
    
    try:
        from core.services import redis as redis_service
        
        cached = await redis_service.get(cache_key)
        if cached:
            data = _json_loads(cached) if isinstance(cached, (str, bytes)) else cached
            logger.debug(f"⚑ Redis cache hit for message history: {thread_id} ({len(data)} messages)")
            return data
    except Exception as e:
        logger.warning(f"Failed to get message history from cache: {e}")
    
    return None


async def set_cached_message_history(thread_id: str, messages: list) -> None:
    """Cache message history in Redis."""
    cache_key = _get_message_history_key(thread_id)
    
    try:
        from core.services import redis as redis_service
        await redis_service.set(cache_key, _json_dumps(messages), ex=MESSAGE_HISTORY_TTL)
        logger.debug(f"βœ… Cached message history in Redis: {thread_id} ({len(messages)} messages)")
    except Exception as e:
        logger.warning(f"Failed to cache message history: {e}")


async def invalidate_message_history_cache(thread_id: str) -> None:
    """Invalidate cached message history when new message is added."""
    try:
        from core.services import redis as redis_service
        await redis_service.delete(_get_message_history_key(thread_id))
        logger.debug(f"πŸ—‘οΈ Invalidated message history cache: {thread_id}")
    except Exception as e:
        logger.warning(f"Failed to invalidate message history cache: {e}")


async def append_to_cached_message_history(thread_id: str, message: dict) -> bool:
    cache_key = _get_message_history_key(thread_id)
    
    try:
        from core.services import redis as redis_service
        
        cached = await redis_service.get(cache_key)
        if cached:
            messages = _json_loads(cached) if isinstance(cached, (str, bytes)) else cached
            messages.append(message)
            await redis_service.set(cache_key, _json_dumps(messages), ex=MESSAGE_HISTORY_TTL)
            logger.debug(f"βœ… Appended message to cached history: {thread_id} ({len(messages)} messages)")
            return True
    except Exception as e:
        logger.warning(f"Failed to append to message history cache: {e}")
    
    return False


TIER_INFO_TTL = 600

def _get_tier_info_key(account_id: str) -> str:
    return f"tier_info:{account_id}"


async def get_cached_tier_info(account_id: str) -> Optional[Dict[str, Any]]:
    cache_key = _get_tier_info_key(account_id)
    
    try:
        from core.services import redis as redis_service
        
        cached = await redis_service.get(cache_key)
        if cached:
            data = _json_loads(cached) if isinstance(cached, (str, bytes)) else cached
            logger.debug(f"⚑ Redis cache hit for tier info: {account_id}")
            return data
    except Exception as e:
        logger.warning(f"Failed to get tier info from cache: {e}")
    
    return None


async def set_cached_tier_info(account_id: str, tier_info: Dict[str, Any]) -> None:
    cache_key = _get_tier_info_key(account_id)
    
    try:
        from core.services import redis as redis_service
        await redis_service.set(cache_key, _json_dumps(tier_info), ex=TIER_INFO_TTL)
        logger.debug(f"βœ… Cached tier info in Redis: {account_id} (tier: {tier_info.get('name', 'unknown')})")
    except Exception as e:
        logger.warning(f"Failed to cache tier info: {e}")


async def invalidate_tier_info_cache(account_id: str) -> None:
    try:
        from core.services import redis as redis_service
        await redis_service.delete(_get_tier_info_key(account_id))
        logger.debug(f"πŸ—‘οΈ Invalidated tier info cache: {account_id}")
    except Exception as e:
        logger.warning(f"Failed to invalidate tier info cache: {e}")
    
    try:
        from core.agents.pipeline.slot_manager import invalidate_tier_cache
        await invalidate_tier_cache(account_id)
    except Exception as e:
        logger.warning(f"Failed to invalidate slot_manager tier cache: {e}")


AGENT_RUN_STREAM_TTL = 3600

def _get_agent_run_stream_key(agent_run_id: str) -> str:
    return f"agent_run_stream:{agent_run_id}"


async def set_agent_run_stream_data(
    agent_run_id: str,
    thread_id: str,
    account_id: str,
    status: str = "running",
    metadata: Optional[Dict[str, Any]] = None
) -> None:
    cache_key = _get_agent_run_stream_key(agent_run_id)
    
    try:
        from core.services import redis as redis_service
        
        stream_data = {
            "id": agent_run_id,
            "thread_id": thread_id,
            "thread_account_id": account_id,
            "status": status,
            "metadata": metadata or {},
        }
        await redis_service.set(cache_key, _json_dumps(stream_data), ex=AGENT_RUN_STREAM_TTL)
        logger.debug(f"βœ… Cached agent run stream data: {agent_run_id}")
    except Exception as e:
        logger.warning(f"Failed to cache agent run stream data: {e}")


async def get_agent_run_stream_data(agent_run_id: str) -> Optional[Dict[str, Any]]:
    cache_key = _get_agent_run_stream_key(agent_run_id)
    
    try:
        from core.services import redis as redis_service
        
        cached = await redis_service.get(cache_key)
        if cached:
            data = _json_loads(cached) if isinstance(cached, (str, bytes)) else cached
            logger.debug(f"⚑ Redis cache hit for agent run stream: {agent_run_id}")
            return data
    except Exception as e:
        logger.warning(f"Failed to get agent run stream data from cache: {e}")
    
    return None


async def delete_agent_run_stream_data(agent_run_id: str) -> None:
    try:
        from core.services import redis as redis_service
        await redis_service.delete(_get_agent_run_stream_key(agent_run_id))
        logger.debug(f"πŸ—‘οΈ Deleted agent run stream cache: {agent_run_id}")
    except Exception as e:
        logger.warning(f"Failed to delete agent run stream cache: {e}")


PENDING_THREAD_TTL = 60

def _get_pending_thread_key(thread_id: str) -> str:
    return f"pending_thread:{thread_id}"


async def set_pending_thread(
    thread_id: str, 
    project_id: str, 
    account_id: str,
    agent_run_id: str,
    prompt: str
) -> None:
    cache_key = _get_pending_thread_key(thread_id)
    
    try:
        from core.services import redis as redis_service
        from datetime import datetime, timezone
        
        pending_data = {
            "thread_id": thread_id,
            "project_id": project_id,
            "account_id": account_id,
            "agent_run_id": agent_run_id,
            "name": prompt[:50] + "..." if len(prompt) > 50 else prompt,
            "status": "pending",
            "created_at": datetime.now(timezone.utc).isoformat(),
        }
        await redis_service.set(cache_key, _json_dumps(pending_data), ex=PENDING_THREAD_TTL)
        logger.debug(f"βœ… Cached pending thread: {thread_id}")
    except Exception as e:
        logger.warning(f"Failed to cache pending thread: {e}")


async def get_pending_thread(thread_id: str) -> Optional[Dict[str, Any]]:
    cache_key = _get_pending_thread_key(thread_id)
    
    try:
        from core.services import redis as redis_service
        
        cached = await redis_service.get(cache_key)
        if cached:
            data = _json_loads(cached) if isinstance(cached, (str, bytes)) else cached
            logger.debug(f"⚑ Redis cache hit for pending thread: {thread_id}")
            return data
    except Exception as e:
        logger.warning(f"Failed to get pending thread from cache: {e}")
    
    return None


async def delete_pending_thread(thread_id: str) -> None:
    try:
        from core.services import redis as redis_service
        await redis_service.delete(_get_pending_thread_key(thread_id))
        logger.debug(f"πŸ—‘οΈ Deleted pending thread cache: {thread_id}")
    except Exception as e:
        logger.warning(f"Failed to delete pending thread cache: {e}")