"""Compatibility for Gemini translators that retain only the last system turn. Only instruction-bearing text messages are folded; user/tool content is never promoted. Caller must scope this to the affected Gemini route. No network or IO. """ def coalesce_context(request): items = request.get('input') base = request.get('instructions', '') if not isinstance(items, list) or not isinstance(base, str): return 0 chunks = ['[BASE SYSTEM INSTRUCTIONS]\n' + base] if base else [] remaining = [] count = 0 for item in items: if not isinstance(item, dict) or item.get('type', 'message') != 'message' or item.get('role') not in ('system', 'developer'): remaining.append(item) continue content = item.get('content', '') if isinstance(content, str): text = content elif isinstance(content, list) and all(isinstance(p, dict) and p.get('type') in ('input_text','text') and isinstance(p.get('text'), str) for p in content): text = '\n'.join(p['text'] for p in content) else: # Unknown multimodal instruction block: do not discard or rewrite. return 0 chunks.append('[' + item['role'].upper() + ' CONTEXT ' + str(count+1) + ']\n' + text) count += 1 if count: request['instructions'] = '\n\n'.join(chunks) request['input'] = remaining return count