/// 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; and what auto-continue sends /// once it is back. library; import '../../../core/api_gateway.dart'; import 'chat_account_usage.dart'; /// How long after the reported reset an auto-continue message is sent, so /// it does not race the quota coming back. const Duration chatScheduleMargin = Duration(minutes: 1); /// What auto-continue sends when the refused turn had no operator message /// of its own to send again. const String chatAutoContinueText = 'continue'; /// The operation id prefix of auto-continue prompts, so unchecking /// auto-continue can find them in the server's queue. const String chatAutoContinuePrefix = 'auto-continue-'; class ChatUsageLimit { const ChatUsageLimit({required this.resetsAt}); /// When the last exhausted window resets, local time. final DateTime resetsAt; /// When an auto-continue message 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)); } /// Older 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'); /// Current Claude Code refuses with "You've hit your 5-hour limit · resets /// 5:20pm (Europe/London) · out of usage credits" (or "your limit", "your /// session limit"); the first clause is the limit's own wording. final RegExp _hitText = RegExp(r"^\s*You['’]ve hit your [^·\n]*limit"); /// The last transcript message that is part of the conversation (a message /// scheduled since is not yet), or an empty map. JsonMap _lastSent(List messages) => messages.lastWhere((m) => m['send_at'] == null, orElse: () => const {}); /// 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 = _lastSent(messages); if (last.isEmpty || last['role'] == 'user') return null; if (_beforeSwitch(usage, last)) return null; return chatUsageLimitFromText(_text(last), now); } /// A refusal received before the operator switched accounts was the old /// account's. bool _beforeSwitch(ChatAccountUsage? usage, JsonMap message) { final switchedAt = usage?.switchedAt ?? 0; if (switchedAt <= 0) return false; final created = message['created_at']; return created is! num || created <= switchedAt; } /// The turn the limit refused: the transcript ends on the harness's limit /// refusal. Auto-continue and Try again send [text]: the operator's message /// the refusal answered, or "continue" when the refusal ended a turn that /// had already worked on it. class ChatRefusedTurn { const ChatRefusedTurn({ required this.refusalId, required this.wording, required this.text, required this.resends, required this.hadAttachments, }); /// The refusal message's id. final String refusalId; /// The refusal's own first clause, "You've hit your 5-hour limit"; null /// for the older `usage limit reached|` text. final String? wording; /// What auto-continue and Try again send. final String text; /// [text] is the operator's refused message (rather than "continue"). final bool resends; /// The refused message carried files, which a re-send does not repeat. final bool hadAttachments; /// The auto-continue prompt's operation id: one per refusal, so every /// device that schedules it asks for the same prompt and the server keeps /// one. String get autoContinueId => '$chatAutoContinuePrefix$refusalId'; } /// The refused turn [messages] end on, or null when the last message is not /// a limit refusal (or came before an account switch in [usage]). ChatRefusedTurn? chatRefusedTurn( List messages, ChatAccountUsage? usage, ) { final sent = [ for (final m in messages) if (m['send_at'] == null) m, ]; if (sent.isEmpty) return null; final last = sent.last; if (last['role'] == 'user' || _beforeSwitch(usage, last)) return null; final text = _text(last); final hit = _hitText.firstMatch(text); if (hit == null && !_limitText.hasMatch(text)) return null; final before = sent.length > 1 ? sent[sent.length - 2] : const {}; final prompt = before['role'] == 'user' ? _text(before).trim() : ''; return ChatRefusedTurn( refusalId: '${last['id'] ?? ''}', wording: hit?.group(0)?.trim(), text: prompt.isEmpty ? chatAutoContinueText : prompt, resends: prompt.isNotEmpty, hadAttachments: prompt.isNotEmpty && _hasFiles(before), ); } bool _hasFiles(JsonMap message) { final parts = message['parts']; return parts is List && parts.any((part) => part is Map && part['type'] != 'text'); } 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; }