/// Whether the open chat's harness account is out of quota, and when it is /// back, from the account usage the server reports (see /// chat_account_usage.dart) or, failing that, a turn that just ended on the /// harness's own "usage limit reached" text. library; import '../../../core/api_gateway.dart'; import 'chat_account_usage.dart'; /// How long after the reported reset a scheduled message is sent, so it does /// not race the quota coming back. const Duration chatScheduleMargin = Duration(minutes: 1); class ChatUsageLimit { const ChatUsageLimit({required this.resetsAt}); /// When the last exhausted window resets, local time. final DateTime resetsAt; /// When a message scheduled for this limit is sent. DateTime get sendAt => resetsAt.add(chatScheduleMargin); } /// The limit [usage] reports at [now]: any window at or past 100% whose reset /// is still ahead. The reset is the latest among those windows, since every /// one of them must have reset before a prompt can run. Null when nothing is /// exhausted, a reset time is unknown, or every reset has already passed. ChatUsageLimit? chatUsageLimit(ChatAccountUsage? usage, DateTime now) { if (usage == null || usage.unsupported) return null; var latest = 0; for (final window in usage.windows) { if (window.usedPercent < 100) continue; if (window.resetsAt <= now.millisecondsSinceEpoch) continue; if (window.resetsAt > latest) latest = window.resetsAt; } if (latest == 0) return null; return ChatUsageLimit(resetsAt: DateTime.fromMillisecondsSinceEpoch(latest)); } /// Claude Code ends a refused turn with `Claude AI usage limit reached|`; the number is the reset. Null for any other text, or a reset /// that has passed. ChatUsageLimit? chatUsageLimitFromText(String text, DateTime now) { final match = _limitText.firstMatch(text); if (match == null) return null; final seconds = int.tryParse(match.group(1)!); if (seconds == null || seconds <= 0) return null; final reset = DateTime.fromMillisecondsSinceEpoch(seconds * 1000); if (!reset.isAfter(now)) return null; return ChatUsageLimit(resetsAt: reset); } final RegExp _limitText = RegExp(r'usage limit reached\|(\d{9,11})\b'); /// The limit for the open chat: the reported quota first, then the /// transcript's last message when it is the harness's limit refusal (a /// message scheduled since then is not part of the conversation yet). ChatUsageLimit? chatThreadUsageLimit( ChatAccountUsage? usage, List messages, DateTime now, ) { final quota = chatUsageLimit(usage, now); if (quota != null) return quota; final last = messages.lastWhere( (message) => message['send_at'] == null, orElse: () => const {}, ); if (last.isEmpty || last['role'] == 'user') return null; return chatUsageLimitFromText(_text(last), now); } /// The operator's most recent message: its text and whether it carried files /// (which a scheduled re-send does not repeat). class ChatLastPrompt { const ChatLastPrompt({required this.text, required this.hadAttachments}); final String text; final bool hadAttachments; } /// The newest user message in [messages] with text, or null. ChatLastPrompt? chatLastPrompt(List messages) { for (final message in messages.reversed) { if (message['role'] != 'user') continue; final text = _text(message).trim(); if (text.isEmpty) continue; final parts = message['parts']; final files = parts is List && parts.any((part) => part is Map && part['type'] != 'text'); return ChatLastPrompt(text: text, hadAttachments: files); } return null; } String _text(JsonMap message) { final parts = message['parts']; if (parts is! List) return '${message['text'] ?? ''}'; return [ for (final part in parts) if (part is Map && part['type'] == 'text') '${part['text'] ?? ''}', ].join('\n'); } /// A queued prompt's `send_at` as a time, or null when it has none or it has /// already passed. DateTime? chatScheduledSendAt(Object? sendAt, DateTime now) { if (sendAt is! num || !sendAt.isFinite || sendAt <= 0) return null; final at = DateTime.fromMillisecondsSinceEpoch(sendAt.toInt()); return at.isAfter(now) ? at : null; }