/// 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-'; /// The operation id prefix of the prompt the server queues after it switched /// a refused chat to another Claude account (`auto-switch-`); /// while one waits, the chat is already being continued. const String chatAutoSwitchPrefix = 'auto-switch-'; /// Whether the server's queue for the chat holds its automatic-switch /// continue prompt. bool chatAutoSwitchPending(Iterable queued) => queued.any( (prompt) => '${prompt['operation_id'] ?? ''}'.startsWith(chatAutoSwitchPrefix), ); 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"); /// Whether [message] is a turn of the conversation: the operator's message /// or the agent's reply. Not one: a message scheduled to send later, content /// the harness injected after the turn (an agent's report, a notice such as /// a background task ending), and a row with no text or tool of its own (an /// activity record). bool chatIsTurnMessage(JsonMap message) { if (message['send_at'] != null) return false; if ('${message['kind'] ?? ''}'.isNotEmpty) return false; final role = message['role']; if (role == 'user') return true; if (role != 'assistant') return false; final parts = message['parts']; if (parts is! List) return '${message['text'] ?? ''}'.isNotEmpty; return parts.any( (part) => part is Map && (part['type'] == 'text' || part['type'] == 'tool' || part['type'] == 'reasoning'), ); } /// The conversation's turn messages, in order. List _turns(List messages) => [ for (final m in messages) if (chatIsTurnMessage(m)) m, ]; /// The last turn message (see [chatIsTurnMessage]), or an empty map. JsonMap _lastTurn(List messages) => messages.lastWhere(chatIsTurnMessage, orElse: () => const {}); /// The limit for the open chat: the reported quota first, then the /// transcript's last turn when it is the harness's limit refusal (notices /// and reports that arrived after it, and a message scheduled since, are /// not turns). ChatUsageLimit? chatThreadUsageLimit( ChatAccountUsage? usage, List messages, DateTime now, ) { final quota = chatUsageLimit(usage, now); if (quota != null) return quota; final last = _lastTurn(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's latest turn is the harness's /// limit refusal (whatever notices, agent reports or background-task rows /// followed it), until a later turn starts. 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 their last turn (see /// [chatIsTurnMessage]) is not a limit refusal (or came before an account /// switch in [usage]). ChatRefusedTurn? chatRefusedTurn( List messages, ChatAccountUsage? usage, ) { final sent = _turns(messages); 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; }