import '../../../core/api_gateway.dart'; const webChatClient = 'Web'; String nativeChatMessageId(String operationId) { final compact = operationId.replaceAll(RegExp('[^A-Za-z0-9]'), ''); final capped = compact.length > 120 ? compact.substring(0, 120) : compact; return capped.isEmpty ? '' : 'msg_$capped'; } /// Chat wire adapter. ApiGateway supplies request ids and returns full envelopes. class ChatRepository { ChatRepository(this.gateway); final ApiGateway gateway; Future> sessions() async => _maps((await gateway.call('chat_sessions'))['chat_sessions']); /// The models the session's harness offers, in the server's order. /// /// `chat_models` is a JSON list, the same shape the web client reads. A /// missing or wrong-typed field is an empty catalog, never invented rows. Future> models(String sessionId) async { final session = sessionId.trim(); if (session.isEmpty) { throw ArgumentError('Select a chat session first.'); } final reply = await gateway.call('chat_models', { 'chat_query': {'session_id': session}, }); final value = reply['chat_models']; return value is List ? _maps(value) : const []; } Future selectModel(String sessionId, String provider, String model) { final session = sessionId.trim(); if (session.isEmpty) { throw ArgumentError('Select a chat session first.'); } if (provider.trim().isEmpty || model.trim().isEmpty) { throw ArgumentError('Choose a model first.'); } return gateway.call('chat_model', { 'chat_model': { 'session_id': session, 'provider': provider.trim(), 'model': model.trim(), }, }); } Future> shells(String sessionId) async => _maps( (await gateway.call('chat_shells', { 'chat_query': {'session_id': sessionId}, }))['chat_shells'], ); Future> directories() async { final value = (await gateway.call('chat_directories'))['chat_directories']; if (value is! List) { throw StateError('Server did not return chat directories.'); } return value .whereType() .where((entry) => entry.trim().isNotEmpty) .toList(); } Future> backends() async { final value = (await gateway.call('chat_backends'))['chat_backends']; if (value is! List) { throw StateError('Server did not return chat backends.'); } final result = value .whereType() .where((entry) => entry.trim().isNotEmpty) .toList(); if (result.isEmpty) throw StateError('Server returned no chat backends.'); return result; } Future shellOutput( String sessionId, String shellId, { int cursor = 0, int limit = 65536, }) => gateway.call('chat_shell_output', { 'chat_shell_output_query': { 'session_id': sessionId, 'shell_id': shellId, 'cursor': cursor, 'limit': limit, }, }); Future history( String sessionId, { int limit = 200, String cursor = '', }) async { final reply = await gateway.call('chat_messages', { 'chat_query': {'session_id': sessionId, 'limit': limit, 'cursor': cursor}, }); final page = reply['chat_history']; if (page is Map) { return { 'messages': _maps(page['messages']), 'nextCursor': '${page['next_cursor'] ?? ''}', 'hasMore': page['has_more'] == true, }; } return { 'messages': _maps(reply['chat_messages']), 'nextCursor': '', 'hasMore': false, }; } Future subscribe(String sessionId) => gateway.call('chat_subscribe', { 'chat_subscribe': {'session_id': sessionId}, }); Future create({ required String title, required String directory, required String operationId, String backend = 'opencode', String instructions = '', }) { if (title.trim().isEmpty || directory.trim().isEmpty) { throw ArgumentError('Enter a chat name and choose a directory.'); } return gateway.call('chat_create', { 'chat_create': { 'title': title.trim(), 'directory': directory.trim(), 'operation_id': operationId, if (backend.isNotEmpty && backend != 'opencode') 'backend': backend, if (instructions.trim().isNotEmpty) 'instructions': instructions.trim(), }, }); } Future rename(String sessionId, String title) => gateway.call('chat_rename', { 'chat_rename': {'session_id': sessionId, 'title': title.trim()}, }); Future star(String sessionId, bool starred) => gateway.call('chat_star', { 'chat_query': {'session_id': sessionId, 'starred': starred}, }); Future close(String sessionId) => gateway.call('chat_close', { 'chat_query': {'session_id': sessionId}, }); Future reopen(String sessionId) => gateway.call('chat_reopen', { 'chat_query': {'session_id': sessionId}, }); Future prompt( String sessionId, String text, { required String operationId, List files = const [], List attachments = const [], }) { if (sessionId.trim().isEmpty) { throw ArgumentError('Select a chat session first.'); } if (text.trim().isEmpty) { throw ArgumentError('Enter a message before sending.'); } final body = { 'session_id': sessionId, 'text': text.trim(), 'operation_id': operationId, 'native_message_id': nativeChatMessageId(operationId), }; if (files.isNotEmpty) body['files'] = files; if (attachments.isNotEmpty) body['attachments'] = attachments; return gateway.call('chat_prompt', {'chat_prompt': body}); } Future interrupt(String sessionId) => gateway.call('chat_interrupt', { 'chat_query': {'session_id': sessionId}, }); Future answerForm( String sessionId, String formId, JsonMap answers, { String action = '', }) => gateway.call('chat_answer', { 'chat_answer': { 'session_id': sessionId, 'form_id': formId, 'answers': answers, if (action.isNotEmpty) 'action': action, }, }); Future replyPermission( String sessionId, String requestId, String decision, { String client = webChatClient, String message = '', }) { if (sessionId.trim().isEmpty) { throw ArgumentError('Select a chat session first.'); } if (requestId.trim().isEmpty) { throw ArgumentError('This approval request is no longer available.'); } if (!const ['once', 'always', 'reject'].contains(decision.trim())) { throw ArgumentError('Choose once, always or reject.'); } return gateway.call('chat_reply', { 'chat_reply': { 'session_id': sessionId, 'request_id': requestId, 'decision': decision, 'client': client, if (message.trim().isNotEmpty) 'message': message.trim(), }, }); } static List _maps(Object? value) => (value as List? ?? const []) .whereType() .map((item) => Map.from(item)) .toList(); }