import 'package:cutdex/errors/app_failure.dart'; import 'dart:async'; import 'dart:convert'; import 'package:cutdex_agent/cutdex_agent.dart'; import 'package:freezed_annotation/freezed_annotation.dart'; import 'package:riverpod_annotation/riverpod_annotation.dart'; import 'package:cutdex_sdk/runtime.dart'; import 'package:uuid/uuid.dart'; import '../../diagnostics/agent_request_diagnostics.dart'; import '../../diagnostics/app_diagnostics.dart'; import '../../integrations/agent/agent_prompt_policy.dart'; import '../../integrations/agent/agent_provider.dart'; import '../../integrations/agent/agent_runtime_factory.dart'; import '../../integrations/agent/conversation_repository.dart'; import '../../integrations/editor_tools.dart'; import 'agent_message_codec.dart'; import 'chat_state.dart'; import 'composer_document.dart'; part 'agent_conversation_service.g.dart'; part 'agent_conversation_service.freezed.dart'; enum AgentConversationFailure { configurationRead, notConfigured, contextBudget, authentication, connection, protocol, request, } class AgentConversationException implements Exception { const AgentConversationException(this.failure); final AgentConversationFailure failure; } @freezed abstract class AgentConversationMessage with _$AgentConversationMessage { const AgentConversationMessage._(); const factory AgentConversationMessage({ required String text, required bool isUser, int? elapsedMs, }) = _AgentConversationMessage; } @freezed abstract class AgentConversationHistory with _$AgentConversationHistory { const factory AgentConversationHistory( List messages, { @Default(false) bool exportReplyFailed, @Default(false) bool recoveryRequired, @Default(false) bool resumeAvailable, }) = _AgentConversationHistory; } @freezed abstract class AgentConversationPreparation with _$AgentConversationPreparation { const factory AgentConversationPreparation( List messages, { required bool sessionChanged, }) = _AgentConversationPreparation; } @freezed abstract class AgentConversationOutcome with _$AgentConversationOutcome { const AgentConversationOutcome._(); const factory AgentConversationOutcome({ required String response, required bool completed, required bool failed, ConversationMetadata? conversation, RunFailure? failure, @Default(false) bool paused, @Default(false) bool recoveryRequired, @Default(false) bool exportReplyFailed, int? elapsedMs, }) = _AgentConversationOutcome; } @Riverpod(keepAlive: true) AgentConversationRegistry agentConversationRegistry(Ref ref) { final registry = AgentConversationRegistry(); ref.onDispose(registry.dispose); return registry; } @Riverpod(keepAlive: true) Future Function(ConversationMetadata?) agentConversationRuntimeResolver(Ref ref) { return (item) async { if (item == null) return ref.read(agentRuntimeProvider.future); final settings = await ref.read(agentSettingsProvider.future); return ref .read(agentRuntimeFactoryProvider) .createFor( settings, providerId: item.providerId, modelId: item.modelId, ); }; } @Riverpod(keepAlive: true) Future Function(String, String) agentConversationToolsResolver(Ref ref) { return (projectId, timelineId) => createEditorAgentBinding(ref, projectId, timelineId); } class AgentConversationRegistry { final _services = {}; bool _paused = false; bool get hasRunning => _services.values.any((service) => service.busy); bool get canStart => !_paused; Future whilePaused(Future Function() action) async { if (_paused || hasRunning) { throw AppException(AppErrorCode.agentLocationBusy); } _paused = true; try { return await action(); } finally { _paused = false; } } String _key(String projectId, String id) => '$projectId\u0000$id'; AgentConversationService obtain( String projectId, String key, String? conversationId, AgentConversationService Function(void Function(String) published) create, ) { final lookup = _key(projectId, conversationId ?? 'draft:$key'); return _services.putIfAbsent(lookup, () { late final AgentConversationService service; service = create((id) => _services[_key(projectId, id)] = service); return service; }); } Future cancel(String projectId, String id) async => _services[_key(projectId, id)]?.cancelAndWait(); Future cancelAll() async { await Future.wait([ for (final service in _services.values.toSet()) service.cancelAndWait(), ]); } void dispose() { for (final service in _services.values.toSet()) { service.dispose(); } _services.clear(); } } /// Not auto-disposed: switching the visible conversation must not stop a run. @Riverpod(keepAlive: true) AgentConversationService agentConversationService( Ref ref, String projectId, String key, String? conversationId, ) { return ref .read(agentConversationRegistryProvider) .obtain( projectId, key, conversationId, (published) => AgentConversationService( projectId: projectId, conversationId: conversationId, canStart: () => ref.read(agentConversationRegistryProvider).canStart, onPublished: published, loadRepository: () => ref.read(conversationRepositoryProvider.future), loadRuntime: ref.read(agentConversationRuntimeResolverProvider), loadTools: (timelineId) => ref.read( agentConversationToolsResolverProvider, )(projectId, timelineId), ), ); } /// Owns one explicit conversation identity, checkpoint recovery and Agent run. class AgentConversationService { AgentConversationService({ required this.projectId, required this.conversationId, required this.loadRepository, required this.loadRuntime, required this.loadTools, this.onPublished, this.canStart, }); final String projectId; final String? conversationId; final Future Function() loadRepository; final Future Function(ConversationMetadata?) loadRuntime; final Future Function(String timelineId) loadTools; final void Function(String id)? onPublished; final bool Function()? canStart; final _changes = StreamController.broadcast(); Stream get changes => _changes.stream; AgentChatActivity _activity = AgentChatActivity.replying; AgentChatActivity get activity => _activity; String _partialResponse = ''; String get partialResponse => _partialResponse; bool get busy => _busy; void _notify() { if (!_changes.isClosed) _changes.add(null); } AgentRun? _run; Completer? _settled; bool _cancelRequested = false; bool _disposed = false; bool _busy = false; ConversationMetadata? _created; bool _startingNewConversation = false; int _identityRevision = 0; ConversationMetadata? get metadata => _created; void startNewConversation() { if (_busy) throw AppException(AppErrorCode.agentLocationBusy); _identityRevision++; _created = null; _startingNewConversation = true; _partialResponse = ''; } void _checkActive() { if (_disposed || _cancelRequested) throw const _PreparationCancelled(); } List _messages( SessionSnapshot snapshot, { List responseDurationsMs = const [], }) { final history = snapshot.history; final result = snapshot.completionEvidence?['result']; final rejectedFinal = result is Map && result['isError'] == true; final visible = []; var responseIndex = 0; for (var i = 0; i < history.length; i++) { final message = history[i]; if (message.role == MessageRole.tool || message.runtimeNotice || message.text.isEmpty || (message.role == MessageRole.assistant && ((i + 1 < history.length && history[i + 1].runtimeNotice && history[i + 1].text.startsWith( '[Runtime artifact verification,', )) || (i == history.length - 1 && rejectedFinal)))) { continue; } final isUser = message.role == MessageRole.user; visible.add( AgentConversationMessage( text: message.text, isUser: isUser, elapsedMs: isUser || responseIndex >= responseDurationsMs.length ? null : responseDurationsMs[responseIndex], ), ); if (!isUser) responseIndex++; } return visible; } Future restore() async { final identityRevision = _identityRevision; final id = _created?.id ?? (_startingNewConversation ? null : conversationId); if (id == null) return null; try { final repository = await loadRepository(); final item = await repository.read(projectId, id); if (item == null) return null; final snapshot = await repository.store(item).read(item.id); if (identityRevision != _identityRevision) return null; _created = item; return snapshot == null ? null : AgentConversationHistory( _messages( snapshot, responseDurationsMs: item.responseDurationsMs, ), exportReplyFailed: _exportReplyFailed(snapshot), resumeAvailable: !_busy && (snapshot.pending.isNotEmpty || snapshot.status == RunStatus.running || snapshot.status == RunStatus.paused), recoveryRequired: !_busy && (snapshot.status == RunStatus.waiting || snapshot.pending.any( (call) => call.status == CallStatus.started, )), ); } catch (_) { throw const AgentConversationException(AgentConversationFailure.request); } } Future send( String text, { required String timelineId, bool summaryOnly = false, bool resumeOnly = false, required void Function(AgentConversationPreparation value) onPrepared, required void Function(String text) onTextDelta, void Function(ConversationMetadata value)? onCreated, }) { final requestId = const Uuid().v4(); return withDiagnosticContext( { 'requestId': requestId, 'projectId': projectId, 'timelineId': timelineId, }, () => _send( text, requestId: requestId, timelineId: timelineId, summaryOnly: summaryOnly, resumeOnly: resumeOnly, onPrepared: onPrepared, onTextDelta: onTextDelta, onCreated: onCreated, ), ); } Future _send( String text, { required String requestId, required String timelineId, bool summaryOnly = false, bool resumeOnly = false, required void Function(AgentConversationPreparation value) onPrepared, required void Function(String text) onTextDelta, void Function(ConversationMetadata value)? onCreated, }) async { if (canStart?.call() == false) { throw const AgentConversationException(AgentConversationFailure.request); } if (_busy) throw AppException(AppErrorCode.agentLocationBusy); _busy = true; _activity = AgentChatActivity.replying; _settled = Completer(); _cancelRequested = false; _partialResponse = ''; _notify(); final elapsed = Stopwatch()..start(); final diagnostics = AgentRequestDiagnostics(requestId: requestId); AgentRun? measuredRun; StreamSubscription? subscription; EditorAgentBinding? binding; ConversationRepository? repository; ConversationMetadata? item; try { binding = summaryOnly // Each run needs a distinct ownership token. // ignore: prefer_const_constructors ? EditorAgentBinding(owner: Object(), tools: const []) : await loadTools(timelineId); _checkActive(); if (!summaryOnly) { final references = AgentComposerMessage.decode(text).references; for (final reference in references) { if (reference.kind == ComposerReferenceKind.timeline && reference.projectId == projectId) { await binding.ensureTimeline?.call(reference.id); _checkActive(); } } } repository = await loadRepository(); _checkActive(); final savedId = _created?.id ?? (_startingNewConversation ? null : conversationId); item = savedId == null ? null : await repository.read(projectId, savedId); if ((savedId != null || summaryOnly || resumeOnly) && item == null) { throw const AgentConversationException( AgentConversationFailure.request, ); } final AgentRuntime? runtime; try { runtime = await loadRuntime(item); } catch (_) { throw const AgentConversationException( AgentConversationFailure.configurationRead, ); } _checkActive(); if (runtime == null) { throw const AgentConversationException( AgentConversationFailure.notConfigured, ); } final system = summaryOnly ? _summaryOnlyInstruction : AgentPromptPolicy.forTimeline(projectId, timelineId); final runTools = summaryOnly ? [] : binding.tools; // Check the mandatory payload before committing a new user turn. try { await runtime.contextBuilder.build( system: system, history: [AgentMessage(role: MessageRole.user, text: text)], tools: [ ...runTools, ...runtime.contextBuilder.runtimeTools( () => SessionSnapshot(id: 'preflight'), runTools, ), ], cancellation: CancellationToken(), ); } on ContextOverflow { throw const AgentConversationException( AgentConversationFailure.contextBudget, ); } _checkActive(); item ??= await repository.begin( projectId: projectId, timelineId: timelineId, providerId: runtime.providerId ?? runtime.sessionIdentity, modelId: runtime.modelId ?? runtime.sessionIdentity, title: () { final prompt = AgentComposerMessage.decode(text); final visible = prompt.text.isNotEmpty ? prompt.text : prompt.attachments.firstOrNull?.name ?? text; return visible.length <= 64 ? visible : '${visible.substring(0, 64)}…'; }(), ); _created = item; final store = repository.store(item); final manager = SessionManager( model: runtime.model, store: store, tools: runTools, contextBuilder: runtime.contextBuilder, completionCheck: summaryOnly ? null : binding.completionCheck, ); var snapshot = await store.read(item.id); _checkActive(); snapshot ??= await manager.create(id: item.id, system: system); _checkActive(); if (summaryOnly && (!_exportReplyFailed(snapshot) || snapshot.pending.isNotEmpty || snapshot.queued.isNotEmpty)) { throw const AgentConversationException( AgentConversationFailure.request, ); } final unfinished = snapshot.pending.isNotEmpty || snapshot.queued.isNotEmpty || snapshot.status == RunStatus.running || snapshot.status == RunStatus.waiting || snapshot.status == RunStatus.paused; if (resumeOnly && !unfinished) { throw const AgentConversationException( AgentConversationFailure.request, ); } onPrepared( AgentConversationPreparation( _messages(snapshot, responseDurationsMs: item.responseDurationsMs), sessionChanged: conversationId == null || _startingNewConversation, ), ); if (!resumeOnly && unfinished) { return AgentConversationOutcome( response: '', completed: false, failed: true, recoveryRequired: true, conversation: item, ); } final run = resumeOnly ? await manager.resume(item.id, maxTurns: snapshot.turns + 80) : await manager.prompt(item.id, text, system: system, maxTurns: 80); _run = run; measuredRun = run; diagnostics.prepared(); _activity = run.phase == AgentRunPhase.compacting ? AgentChatActivity.compacting : AgentChatActivity.replying; _notify(); subscription = run.events.listen((event) { if (_disposed) return; if (event.kind == AgentEventKind.phase) { _activity = event.text == AgentRunPhase.compacting.name ? AgentChatActivity.compacting : AgentChatActivity.replying; _notify(); } else if (event.kind == AgentEventKind.toolStarted) { _activity = event.text.endsWith('_query') || event.text.endsWith('_list') || event.text == 'cutdex_workspaces' || event.text == 'completion_check' ? AgentChatActivity.verifying : AgentChatActivity.editing; _notify(); } if (!_disposed && event.kind == AgentEventKind.textDelta) { _activity = AgentChatActivity.replying; _partialResponse += event.text; _notify(); onTextDelta(event.text); } }); if (item.pending) { item = await repository.publish(item); _created = item; onPublished?.call(item.id); onCreated?.call(item); } if (_cancelRequested || _disposed) unawaited(run.cancel()); final result = await run.done; diagnostics.outcome = result.status.name; if (result.status == RunStatus.failed || result.status == RunStatus.waiting) { reportDiagnostic( AppDiagnostics.report, DiagnosticEvent( component: 'agent', operation: 'run', error: StateError( 'Agent run ${result.status.name}: ${result.failure?.name ?? 'request'}', ), context: {'failure': result.failure?.name}, ), ); } final completed = result.status == RunStatus.completed && !_cancelRequested; final response = completed && result.history.last.role == MessageRole.assistant ? result.history.last.text : ''; final responseIndex = _messages(result).where((message) => !message.isUser).length - 1; final elapsedMs = completed && response.isNotEmpty ? elapsed.elapsedMilliseconds : null; final responseDurationsMs = [...item.responseDurationsMs]; if (elapsedMs != null && responseIndex >= 0) { while (responseDurationsMs.length <= responseIndex) { responseDurationsMs.add(null); } responseDurationsMs[responseIndex] = elapsedMs; } item = await repository.update( item.copyWith( timelineId: timelineId, responseDurationsMs: responseDurationsMs, ), ); _created = item; _partialResponse = ''; _notify(); return AgentConversationOutcome( response: response, completed: completed, failed: result.status == RunStatus.failed || result.status == RunStatus.waiting, conversation: item, paused: result.status == RunStatus.paused && !_cancelRequested, recoveryRequired: result.status == RunStatus.waiting, failure: result.failure, exportReplyFailed: _exportReplyFailed(result), elapsedMs: elapsedMs, ); } on _PreparationCancelled { diagnostics.outcome = 'cancelled'; return AgentConversationOutcome( response: '', completed: false, failed: false, conversation: item, ); } on AgentConversationException catch (error, stack) { AppDiagnostics.failure('agent', 'send', error, stack); rethrow; } catch (error, stack) { AppDiagnostics.failure('agent', 'send', error, stack); if (repository != null && item != null && item.pending) { try { final published = await repository.publish(item); _created = published; onPublished?.call(published.id); onCreated?.call(published); } catch (_) { // No user message committed; startup recovery ignores this draft. } } throw const AgentConversationException(AgentConversationFailure.request); } finally { if (measuredRun != null) { diagnostics.runs.add(measuredRun.diagnostics.toJson()); } final report = diagnostics.stop(); reportDiagnostic( AppDiagnostics.report, DiagnosticEvent( component: 'agent', operation: 'requestFinished', level: DiagnosticSeverity.info, context: {'outcome': report.outcome, 'elapsedUs': report.elapsedUs}, ), ); unawaited( AppDiagnostics.instance?.request(report, requestId) ?? Future.value(), ); if (repository != null) { await AgentRequestDiagnostics.persist(repository.root, report); } _run = null; _busy = false; _notify(); try { await subscription?.cancel(); await binding?.release?.call(); } finally { _settled?.complete(); _settled = null; } } } Future cancel() async { _cancelRequested = true; final run = _run; if (run != null) { await run.cancel(); await _settled?.future; } } Future cancelAndWait() async { await cancel(); await _settled?.future; } void dispose() { _disposed = true; unawaited(cancel()); unawaited(_changes.close()); } } class _PreparationCancelled implements Exception { const _PreparationCancelled(); } const _summaryOnlyInstruction = 'Summarize the already completed export and edits from successful tool results. No tools are available. Never claim a new edit or export occurred. State the saved destination and confirmed results in the user language.'; bool _exportReplyFailed(SessionSnapshot snapshot) { if (snapshot.status != RunStatus.failed || snapshot.pending.isNotEmpty || snapshot.queued.isNotEmpty) { return false; } final start = snapshot.system == _summaryOnlyInstruction ? 0 : snapshot.runStart; final history = snapshot.history.skip(start).toList(); final tool = history.where((m) => m.role == MessageRole.tool).lastOrNull; if (tool == null || tool.isError) return false; final calls = history.expand((m) => m.calls); if (!calls.any((c) => c.id == tool.callId && c.name == 'project_export')) { return false; } try { final result = jsonDecode(tool.text) as Map; final data = result['data'] as Map; return result['isError'] != true && data['status'] == 'succeeded' && (data['data'] as Map)['destination'] is String; } on FormatException { return false; } on TypeError { return false; } }