import 'dart:async'; import 'package:freezed_annotation/freezed_annotation.dart'; import 'package:cutdex_agent/cutdex_agent.dart'; import 'package:cutdex_sdk/tools.dart'; import 'package:riverpod_annotation/riverpod_annotation.dart'; import '../workspace/projects.dart'; import '../workspace/timeline_provider.dart'; import 'agent/editor_acceptance.dart'; import 'agent/editor_agent_tools.dart'; import 'application_command_dependencies.dart'; import 'application_command_host.dart'; import 'editor_command_host.dart'; import 'editor_tool_access.dart'; import 'mcp/mcp_endpoint_controller.dart'; import 'mcp/mcp_settings.dart'; export 'mcp/mcp_endpoint_controller.dart' show EditorMcpEndpoint; export 'editor_tool_access.dart' show EditorToolAccess; part 'editor_tools.g.dart'; part 'editor_tools.freezed.dart'; @Riverpod(keepAlive: true) EditorMcpEndpoint _editorMcpEndpoint(Ref ref) { final endpoint = EditorMcpEndpoint(); ref.onDispose(() { unawaited(endpoint.close()); }); return endpoint; } @freezed abstract class EditorMcpConfiguration with _$EditorMcpConfiguration { const factory EditorMcpConfiguration({ required int port, required String token, }) = _EditorMcpConfiguration; } @Riverpod(keepAlive: true) EditorMcpConfiguration editorMcpConfiguration(Ref ref) { final settings = ref.watch(mcpSettingsProvider).asData?.value; return EditorMcpConfiguration( port: settings?.enabled == true ? settings!.port : 0, token: settings?.token ?? '', ); } @Riverpod(keepAlive: true) EditorToolAccess applicationToolAccess(Ref ref) { late final EditorToolAccess access; (String, String)? timelineIds; void Function()? releaseTimeline; Future refresh() async { final current = await ref.read(projectsProvider.future); if (!ref.mounted) return; final projectId = current.activeProject?.id; final timelineId = current.timeline?.id; if (projectId == null || timelineId == null) { releaseTimeline?.call(); releaseTimeline = null; timelineIds = null; access.attach(null); return; } final ids = (projectId, timelineId); final provider = editorTimelineProvider(ids.$1, ids.$2); if (timelineIds != ids) { releaseTimeline?.call(); // Tools own an active timeline even when no editor widget is watching it. final subscription = ref.listen(provider, (_, _) {}); releaseTimeline = subscription.close; timelineIds = ids; } var session = await ref.read(provider.future); if (!ref.mounted) return; if (!session.acceptsEdits) { ref.invalidate(provider); session = await ref.read(provider.future); } if (!ref.mounted) return; final latest = ref.read(projectsProvider).asData?.value; if (ref.mounted && latest?.activeProject?.id == projectId && latest?.timeline?.id == timelineId) { access.attach(session, projectId: projectId); } } access = EditorToolAccess.application( ApplicationCommandHost( RiverpodApplicationCommandDependencies(ref), refresh: refresh, ), ); ref.listen(projectsProvider, (_, next) { if (next.asData?.value.projectBusy == false) { unawaited(refresh().catchError((Object _) {})); } }); ref.onDispose(() { releaseTimeline?.call(); unawaited(access.dispose()); }); unawaited(refresh().catchError((Object _) {})); return access; } @riverpod FutureOr editorToolAccess( Ref ref, String projectId, String timelineId, ) async { final session = await ref.watch( editorTimelineProvider(projectId, timelineId).future, ); final access = ref.watch(applicationToolAccessProvider); final current = ref.read(projectsProvider).asData?.value; if (current?.activeProject?.id == projectId && current?.timeline?.id == timelineId && session.acceptsEdits) { access.attach(session, projectId: projectId); } return access; } @Riverpod(keepAlive: true) FutureOr applicationMcpConnection(Ref ref) async { final configuration = ref.watch(editorMcpConfigurationProvider); final endpoint = ref.watch(_editorMcpEndpointProvider); if (configuration.port == 0) { await endpoint.stop(); return; } final access = ref.watch(applicationToolAccessProvider); var disposed = false; ref.onDispose(() { disposed = true; }); final bridge = await endpoint.open( access.server, port: configuration.port, token: configuration.token, ); if (disposed) { await endpoint.release(bridge); return; } ref.onDispose(() => unawaited(endpoint.release(bridge))); } @riverpod FutureOr editorMcpConnection( Ref ref, String projectId, String timelineId, ) async { await ref.watch(editorToolAccessProvider(projectId, timelineId).future); await ref.watch(applicationMcpConnectionProvider.future); } class EditorAgentBinding { const EditorAgentBinding({ required this.owner, required this.tools, this.release, this.completionCheck, this.ensureTimeline, }); final Object owner; final List tools; final Future Function()? release; final CompletionCheck? completionCheck; final Future Function(String timelineId)? ensureTimeline; } /// Leases explicit run targets; opening another timeline adds that target. Future createEditorAgentBinding( Ref ref, String projectId, String timelineId, ) async { await ref.read(editorTimelineProvider(projectId, timelineId).future); final lease = await ref .read(projectsProvider.notifier) .leaseTimeline(projectId, timelineId); final leases = {timelineId: lease}; try { final session = lease.session; final dispatchers = {}; final application = ref.read(applicationToolAccessProvider); if (application.workspaces['application'] case final dispatcher?) { dispatchers['application'] = dispatcher; } for (final sequence in session.document.sequences) { dispatchers['sequence:${sequence.id.value}'] = editorToolsFor( session, sequence.id, ); } Future ensureTimeline(String target) async { if (leases.containsKey(target)) return; final added = await ref .read(projectsProvider.notifier) .leaseTimeline(projectId, target); leases[target] = added; for (final sequence in added.session.document.sequences) { dispatchers['sequence:${sequence.id.value}'] = editorToolsFor( added.session, sequence.id, ); } } final tools = editorAgentTools( dispatchers, dynamicWorkspaces: true, afterInvoke: (call, context, result) async { if (!{ 'timeline_create', 'timeline_open', 'sequence_select', }.contains(call.name)) { return; } if (call.arguments['projectId'] != projectId) return; final target = call.name == 'timeline_create' ? result.data['timelineId'] : call.arguments['timelineId']; if (target is! String) return; await ensureTimeline(target); }, beforeInvoke: (context) async { try { for (final owned in leases.values) { await owned.validate(); } } catch (_) { context.cancellation.cancel(); rethrow; } }, ); final acceptance = EditorAcceptance(tools); return EditorAgentBinding( owner: session, tools: [...tools, ...acceptance.tools], completionCheck: acceptance.check, ensureTimeline: ensureTimeline, release: () async { try { for (final owned in leases.values) { for (final sequence in owned.session.document.sequences) { final dispatcher = dispatchers['sequence:${sequence.id.value}']; if (dispatcher != null) { await releaseEditorTools(owned.session, dispatcher); } } } } finally { for (final owned in leases.values) { await owned.release(); } } }, ); } catch (_) { await lease.release(); rethrow; } } @Riverpod(name: 'editorAgentToolsProvider') FutureOr editorAgentToolsBinding( Ref ref, String projectId, String timelineId, ) async { final access = await ref.watch( editorToolAccessProvider(projectId, timelineId).future, ); return EditorAgentBinding(owner: access.owner, tools: access.agentTools); }