feat: initial Cutdex application
Add the Flutter video editing application with project management, media import, timeline editing, preview, AI assistance, diagnostics and settings. Include shared UI and native host packages, platform runners, application tests and release tooling. Provide usage and contribution guides, the MIT license and third-party notices. Exclude local credentials, build outputs and validation data.
This commit is contained in:
commit
27e77fff39
718 files changed
+183958
No files matched your search
@@ -0,0 +1,51 @@
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
|
||||
import 'package:riverpod_annotation/riverpod_annotation.dart';
|
||||
|
||||
part 'agent_credentials.g.dart';
|
||||
|
||||
abstract interface class AgentCredentialStore {
|
||||
Future<String?> read(String id);
|
||||
Future<void> write(String id, String value);
|
||||
Future<void> delete(String id);
|
||||
}
|
||||
|
||||
@Riverpod(keepAlive: true)
|
||||
AgentCredentialStore agentCredentialStore(Ref ref) {
|
||||
final storage = Platform.isMacOS
|
||||
? const FlutterSecureStorage(
|
||||
mOptions: MacOsOptions(usesDataProtectionKeychain: false),
|
||||
)
|
||||
: const FlutterSecureStorage();
|
||||
return FlutterSecureAgentCredentialStore(storage);
|
||||
}
|
||||
|
||||
class FlutterSecureAgentCredentialStore implements AgentCredentialStore {
|
||||
FlutterSecureAgentCredentialStore(this._storage);
|
||||
|
||||
final FlutterSecureStorage _storage;
|
||||
|
||||
@override
|
||||
Future<String?> read(String id) => _storage.read(key: id);
|
||||
|
||||
@override
|
||||
Future<void> write(String id, String value) =>
|
||||
_storage.write(key: id, value: value);
|
||||
|
||||
@override
|
||||
Future<void> delete(String id) => _storage.delete(key: id);
|
||||
}
|
||||
|
||||
class MemoryAgentCredentialStore implements AgentCredentialStore {
|
||||
final Map<String, String> _values = {};
|
||||
|
||||
@override
|
||||
Future<String?> read(String id) async => _values[id];
|
||||
|
||||
@override
|
||||
Future<void> write(String id, String value) async => _values[id] = value;
|
||||
|
||||
@override
|
||||
Future<void> delete(String id) async => _values.remove(id);
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'agent_credentials.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// RiverpodGenerator
|
||||
// **************************************************************************
|
||||
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
// ignore_for_file: type=lint, type=warning
|
||||
|
||||
@ProviderFor(agentCredentialStore)
|
||||
final agentCredentialStoreProvider = AgentCredentialStoreProvider._();
|
||||
|
||||
final class AgentCredentialStoreProvider
|
||||
extends
|
||||
$FunctionalProvider<
|
||||
AgentCredentialStore,
|
||||
AgentCredentialStore,
|
||||
AgentCredentialStore
|
||||
>
|
||||
with $Provider<AgentCredentialStore> {
|
||||
AgentCredentialStoreProvider._()
|
||||
: super(
|
||||
from: null,
|
||||
argument: null,
|
||||
retry: null,
|
||||
name: r'agentCredentialStoreProvider',
|
||||
isAutoDispose: false,
|
||||
dependencies: null,
|
||||
$allTransitiveDependencies: null,
|
||||
);
|
||||
|
||||
@override
|
||||
String debugGetCreateSourceHash() => _$agentCredentialStoreHash();
|
||||
|
||||
@$internal
|
||||
@override
|
||||
$ProviderElement<AgentCredentialStore> $createElement(
|
||||
$ProviderPointer pointer,
|
||||
) => $ProviderElement(pointer);
|
||||
|
||||
@override
|
||||
AgentCredentialStore create(Ref ref) {
|
||||
return agentCredentialStore(ref);
|
||||
}
|
||||
|
||||
/// {@macro riverpod.override_with_value}
|
||||
Override overrideWithValue(AgentCredentialStore value) {
|
||||
return $ProviderOverride(
|
||||
origin: this,
|
||||
providerOverride: $SyncValueProvider<AgentCredentialStore>(value),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
String _$agentCredentialStoreHash() =>
|
||||
r'5905f9d4740138df60d6f32dd3fde66489be97c3';
|
||||
@@ -0,0 +1,69 @@
|
||||
import 'package:cutdex_agent/cutdex_agent.dart';
|
||||
import 'package:freezed_annotation/freezed_annotation.dart';
|
||||
|
||||
import 'agent_prompt_policy.dart';
|
||||
|
||||
part 'agent_models.freezed.dart';
|
||||
|
||||
enum AgentApiType { openAiChatCompletions, openAiResponses, anthropicMessages }
|
||||
|
||||
@freezed
|
||||
abstract class AgentModelSettings with _$AgentModelSettings {
|
||||
const AgentModelSettings._();
|
||||
|
||||
const factory AgentModelSettings({
|
||||
required String id,
|
||||
int? contextWindow,
|
||||
int? maxOutputTokens,
|
||||
}) = _AgentModelSettings;
|
||||
|
||||
/// Reserve at most half of a small window when output is unspecified.
|
||||
int get effectiveMaxOutputTokens =>
|
||||
maxOutputTokens ??
|
||||
(contextWindow == null || contextWindow! >= 8192
|
||||
? 4096
|
||||
: contextWindow! ~/ 2);
|
||||
|
||||
int get effectiveMaxInputTokens =>
|
||||
contextWindow == null ? 32000 : contextWindow! - effectiveMaxOutputTokens;
|
||||
|
||||
bool get hasInstructionBudget =>
|
||||
effectiveMaxInputTokens >=
|
||||
ContextBuilder().measureInput(system: AgentPromptPolicy.editorAssistant);
|
||||
|
||||
bool get hasValidTokenBudget =>
|
||||
effectiveMaxInputTokens > 0 && effectiveMaxOutputTokens > 0;
|
||||
}
|
||||
|
||||
@freezed
|
||||
abstract class AgentProviderSettings with _$AgentProviderSettings {
|
||||
const AgentProviderSettings._();
|
||||
|
||||
const factory AgentProviderSettings({
|
||||
required String id,
|
||||
required String name,
|
||||
required String apiType,
|
||||
required String baseUrl,
|
||||
required List<AgentModelSettings> models,
|
||||
String? credentialId,
|
||||
@Default(true) bool enabled,
|
||||
}) = _AgentProviderSettings;
|
||||
}
|
||||
|
||||
@freezed
|
||||
abstract class AgentSettingsState with _$AgentSettingsState {
|
||||
const AgentSettingsState._();
|
||||
|
||||
const factory AgentSettingsState({
|
||||
@Default(false) bool enabled,
|
||||
@Default([]) List<AgentProviderSettings> providers,
|
||||
String? selectedProviderId,
|
||||
String? selectedModelId,
|
||||
@Default(0) int revision,
|
||||
}) = _AgentSettingsState;
|
||||
}
|
||||
|
||||
abstract interface class AgentSettingsRepository {
|
||||
Future<AgentSettingsState> load();
|
||||
Future<void> save(AgentSettingsState settings);
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,28 @@
|
||||
import 'dart:convert';
|
||||
|
||||
abstract final class AgentPromptPolicy {
|
||||
static String forTimeline(String projectId, String timelineId) =>
|
||||
'$editorAssistant\n'
|
||||
'当前界面编辑目标(用户明确指定其他目标时,以用户要求为准):${jsonEncode({'projectId': projectId, 'timelineId': timelineId})}。'
|
||||
'已有适用于当前目标的成功工具结果时复用其 workspaceId。仅首次没有目标 ID、切换目标或工作区失效时调用 cutdex_workspaces;toolSetId 引用同一返回中的 toolSets。当前任务内复用已确认的 ID,不要在每次模型回复、工具调用或上下文压缩后重复发现工作区;仅在目标切换或工作区失效时重新查询。'
|
||||
'application 工作区只处理项目管理;时间线查询和片段编辑必须使用对应的时间线工作区。';
|
||||
static const editorAssistant =
|
||||
'你是 Cutdex 视频剪辑助手,请使用用户的语言回答。'
|
||||
'音频分析使用 audio_analyze,先从 timeline_query 确定音频 clipId 和 sourceRange;startSeconds/durationSeconds 是素材时间,单次最多120秒,长素材按区间读取。波形峰值、RMS和高能量片段只是高潮候选,不等于语义高潮;重音候选不等于已识别小节强拍。置信度或分辨率不足时明确说明,不要编造节拍。'
|
||||
'用户要求实际卡点剪辑时,调用 timeline_planBeatCuts 并设置 requireCuts:true;仅查看方案时为false。指定音频参考片段和要剪切的主时间线片段,每拍every:1、两拍every:2,phase小于every。工具负责裁剪/变速时间映射和帧对齐,严格按返回actions顺序逐一调用timeline_split,使用每次成功操作返回的最新expectedVersion。不要对剪辑后的项目重算或替换原计划,不要擅自切割音频参考。完成后project_save,结束前程序会按原计划核验切点和素材范围。mode:split保留内容只做分割;用户要求多个镜头卡点切换且允许裁剪时,用mode:fitClips,把全部主时间线素材按现有顺序缩短到连续节拍,严格执行返回的timeline_trim操作。工具不会自动选素材或重排;需要选材时先安排素材再制定卡点计划,不能把单纯分割称为已经换镜头。'
|
||||
'修改片段名称或静态参数前,调用 editor_expect_clips 登记用户要求的全部目标、最终名称和参数默认值;未要求调整结构时保留 preserveLayout:true。音量参数 ID 为 cutdex.audio.gainDb。新建翻译轨道后、写入译文前调用 editor_expect_translation,登记源和目标 roleId。结束时程序会重新读取工程核验数量、身份、时间和已声明参数;有差异时按具体问题修正,不要重新登记来降低原标准。先完成 project_save,再报告保存完成。声明范围之外的要求不能声称已由程序核验。'
|
||||
'语义检查只提供带原文、译文和疑点的复核建议;不能仅凭一次语义评分自动改写正确译文。结构通过不等于翻译准确、自然或适合交付。遇到原文不清楚要明确列出待复核项,不能猜测事实,也不能把占位或省略号当作已完成翻译。'
|
||||
'字幕翻译可使用内置 subtitle_translate(需要支持的字幕文件和可用模型),也可读取 caption_query 的原文由你直接翻译。用户要求新增字幕轨道时,保留原字幕,用 captionTrack_create 创建目标语言轨道,再用 caption_addTranslations 按返回的 roleId 逐条或分批添加译文。翻译时每条只提供 text 和 sourceCaptionId(原字幕 captionId),由工具复制精确时间,避免抄写或计算时间数字。翻译风格未指定时使用自然准确的译文,不必为可选风格偏好暂停执行。'
|
||||
'批量字幕任务优先 caption_list:不传 roleId 先列轨道,再指定源 roleId 每页读取 20 条,翻译并用 caption_addTranslations 写入后才读取下一页。通过 update_plan checkpoint 记录源 roleId、目标 roleId、nextOffset 和最新版本;上下文压缩后从 nextOffset 继续,不能重新全量查询或重复写入。caption_list 已完成字幕编辑前的状态查询,字幕任务不需要全量 timeline_query;结束时用 caption_list 核对轨道数量和保存状态。'
|
||||
'同一时间线的写操作必须逐次调用并等待返回,再使用更新后的版本;不要在同一条模型回复中批量发出共享同一个 expectedVersion 的独立写操作。只有专用批量工具才能原子批量编辑。'
|
||||
'上下文压缩本身不会改变工程状态,也不会使已确认的工作区和版本失效。即使摘要泛称版本可能过时,也应复用本轮最近一次成功查询或提交的版本;不要陷入压缩后重新查询、查询后再次压缩的循环。'
|
||||
'编辑前查询时间线;只核对少量片段时使用 clipIds 和 parameterIds,结构查询用 includeParameters:false;连续编辑可使用上一次成功提交返回的最新 expectedVersion。无状态变化时不要重复查询同一时间线;发生版本冲突或结果未知时重新查询。'
|
||||
'clip_setTransform 的画面位置使用相对画布中心的像素坐标;'
|
||||
'keyframe_edit/keyframe_editMany 的 canvas.position.x/y 则使用归一化值,x 向右为正、y 向上为正,必须将像素除以画布宽高,不能直接传像素。'
|
||||
'编辑时间使用时间线时间;查询关键帧的 sourceTime 是素材时间,需结合片段起点和 sourceRange 换算。'
|
||||
'仅报告工具确认的结果;预览异步同步,提交成功不等于预览或导出完成。'
|
||||
'结果未知时先核对状态,不要重复执行编辑。'
|
||||
'完成编辑后按修改过的片段和参数查询时间线,核对实际结果与 saveState,再报告最新的保存状态。'
|
||||
'总时长以时间线查询的 duration 为准,不能沿用编辑前的时长或把重叠 lane 时长相加。'
|
||||
'查询结果中的 preview:notRequested 仅指该次查询未请求预览,不表示实际预览未同步;需要报告预览时调用 preview_query。';
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
export 'agent_models.dart';
|
||||
export 'agent_runtime.dart';
|
||||
export 'agent_settings.dart';
|
||||
export 'agent_session_store.dart';
|
||||
@@ -0,0 +1,20 @@
|
||||
import 'package:cutdex_agent/cutdex_agent.dart';
|
||||
|
||||
/// Runtime-only dependencies for one selected provider/model.
|
||||
class AgentRuntime {
|
||||
const AgentRuntime({
|
||||
required this.model,
|
||||
required this.contextBuilder,
|
||||
required this.revision,
|
||||
required this.sessionIdentity,
|
||||
this.providerId,
|
||||
this.modelId,
|
||||
});
|
||||
|
||||
final ModelAdapter model;
|
||||
final ContextBuilder contextBuilder;
|
||||
final int revision;
|
||||
final String sessionIdentity;
|
||||
final String? providerId;
|
||||
final String? modelId;
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
import 'package:cutdex_agent/cutdex_agent.dart';
|
||||
import 'package:cutdex_agent/io.dart';
|
||||
import 'package:riverpod_annotation/riverpod_annotation.dart';
|
||||
|
||||
import 'agent_credentials.dart';
|
||||
import 'agent_models.dart';
|
||||
import 'agent_runtime.dart';
|
||||
|
||||
part 'agent_runtime_factory.g.dart';
|
||||
|
||||
@Riverpod(keepAlive: true)
|
||||
AgentRuntimeFactory agentRuntimeFactory(Ref ref) {
|
||||
return AgentRuntimeFactory(ref.watch(agentCredentialStoreProvider));
|
||||
}
|
||||
|
||||
/// Converts persisted provider metadata into runtime-only Agent dependencies.
|
||||
class AgentRuntimeFactory {
|
||||
const AgentRuntimeFactory(this._credentials);
|
||||
|
||||
final AgentCredentialStore _credentials;
|
||||
|
||||
Future<AgentRuntime?> create(AgentSettingsState settings) async {
|
||||
if (!settings.enabled) return null;
|
||||
return createFor(
|
||||
settings,
|
||||
providerId: settings.selectedProviderId,
|
||||
modelId: settings.selectedModelId,
|
||||
);
|
||||
}
|
||||
|
||||
Future<AgentRuntime?> createFor(
|
||||
AgentSettingsState settings, {
|
||||
required String? providerId,
|
||||
required String? modelId,
|
||||
}) async {
|
||||
if (!settings.enabled) return null;
|
||||
final provider = settings.providers
|
||||
.where((candidate) => candidate.id == providerId)
|
||||
.firstOrNull;
|
||||
final model = provider?.models
|
||||
.where((candidate) => candidate.id == modelId)
|
||||
.firstOrNull;
|
||||
if (provider == null || !provider.enabled || model == null) return null;
|
||||
final apiType = AgentApiType.values
|
||||
.where((candidate) => candidate.name == provider.apiType)
|
||||
.firstOrNull;
|
||||
if (apiType == null) return null;
|
||||
|
||||
final credentialId = provider.credentialId;
|
||||
final apiKey = credentialId == null
|
||||
? ''
|
||||
: await _credentials.read(credentialId) ?? '';
|
||||
final adapter = switch (apiType) {
|
||||
AgentApiType.openAiChatCompletions => OpenAiChatAdapter(
|
||||
baseUrl: Uri.parse(provider.baseUrl),
|
||||
model: model.id,
|
||||
apiKey: apiKey,
|
||||
),
|
||||
AgentApiType.openAiResponses => OpenAiResponsesAdapter(
|
||||
baseUrl: Uri.parse(provider.baseUrl),
|
||||
model: model.id,
|
||||
apiKey: apiKey,
|
||||
),
|
||||
AgentApiType.anthropicMessages => AnthropicMessagesAdapter(
|
||||
baseUrl: Uri.parse(provider.baseUrl),
|
||||
model: model.id,
|
||||
apiKey: apiKey,
|
||||
),
|
||||
};
|
||||
return AgentRuntime(
|
||||
model: adapter,
|
||||
contextBuilder: HarnessContextBuilder(
|
||||
directTools: const {'cutdex_workspaces'},
|
||||
summarizer: ModelContextSummarizer(
|
||||
model: adapter,
|
||||
budget: ContextBuilder(
|
||||
maxInputTokens: model.effectiveMaxInputTokens,
|
||||
maxOutputTokens: model.effectiveMaxOutputTokens,
|
||||
),
|
||||
instructions:
|
||||
'For video editing preserve project, timeline, sequence '
|
||||
'and clip IDs, lane relationships, source versus timeline time, '
|
||||
'keyframe units, mask identifiers, committed edits and unsaved '
|
||||
'or uncertain results. Preserve user constraints and pending edits. '
|
||||
'Preserve the latest confirmed workspace and version IDs and '
|
||||
'whether any later edit or error invalidated them. Compaction '
|
||||
'alone does not invalidate a successful query or commit. Reuse '
|
||||
'its version for the next sequential write; do not add a pending '
|
||||
'query merely because a summary was created. Requery only when '
|
||||
'the target changes or a stale/uncertain '
|
||||
'result requires reconciliation. Preserve durable resultId references and cursors needed for pending reads. Do not copy full curves or unrelated tool call IDs. Keep the summary concise: group completed edits by target, retain only latest valid version, exact pending actions and user constraints. Do not repeat the same IDs under multiple headings.',
|
||||
),
|
||||
maxInputTokens: model.effectiveMaxInputTokens,
|
||||
maxOutputTokens: model.effectiveMaxOutputTokens,
|
||||
),
|
||||
revision: settings.revision,
|
||||
sessionIdentity: '${provider.id}\u0000${model.id}',
|
||||
providerId: provider.id,
|
||||
modelId: model.id,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'agent_runtime_factory.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// RiverpodGenerator
|
||||
// **************************************************************************
|
||||
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
// ignore_for_file: type=lint, type=warning
|
||||
|
||||
@ProviderFor(agentRuntimeFactory)
|
||||
final agentRuntimeFactoryProvider = AgentRuntimeFactoryProvider._();
|
||||
|
||||
final class AgentRuntimeFactoryProvider
|
||||
extends
|
||||
$FunctionalProvider<
|
||||
AgentRuntimeFactory,
|
||||
AgentRuntimeFactory,
|
||||
AgentRuntimeFactory
|
||||
>
|
||||
with $Provider<AgentRuntimeFactory> {
|
||||
AgentRuntimeFactoryProvider._()
|
||||
: super(
|
||||
from: null,
|
||||
argument: null,
|
||||
retry: null,
|
||||
name: r'agentRuntimeFactoryProvider',
|
||||
isAutoDispose: false,
|
||||
dependencies: null,
|
||||
$allTransitiveDependencies: null,
|
||||
);
|
||||
|
||||
@override
|
||||
String debugGetCreateSourceHash() => _$agentRuntimeFactoryHash();
|
||||
|
||||
@$internal
|
||||
@override
|
||||
$ProviderElement<AgentRuntimeFactory> $createElement(
|
||||
$ProviderPointer pointer,
|
||||
) => $ProviderElement(pointer);
|
||||
|
||||
@override
|
||||
AgentRuntimeFactory create(Ref ref) {
|
||||
return agentRuntimeFactory(ref);
|
||||
}
|
||||
|
||||
/// {@macro riverpod.override_with_value}
|
||||
Override overrideWithValue(AgentRuntimeFactory value) {
|
||||
return $ProviderOverride(
|
||||
origin: this,
|
||||
providerOverride: $SyncValueProvider<AgentRuntimeFactory>(value),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
String _$agentRuntimeFactoryHash() =>
|
||||
r'e937512aa2ab3c32b8270bedac59ae179639377a';
|
||||
@@ -0,0 +1,18 @@
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:cutdex_agent/cutdex_agent.dart';
|
||||
import 'package:cutdex_agent/io.dart';
|
||||
import 'package:path/path.dart' as p;
|
||||
import 'package:path_provider/path_provider.dart';
|
||||
import 'package:riverpod_annotation/riverpod_annotation.dart';
|
||||
|
||||
part 'agent_session_store.g.dart';
|
||||
|
||||
/// Owns the durable Agent checkpoint journal for the lifetime of the app.
|
||||
@Riverpod(keepAlive: true)
|
||||
FutureOr<SessionStore> agentSessionStore(Ref ref) async {
|
||||
final support = await getApplicationSupportDirectory();
|
||||
return FileSessionStore(
|
||||
Directory(p.join(support.path, 'Cutdex', 'Agent', 'Sessions')),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'agent_session_store.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// RiverpodGenerator
|
||||
// **************************************************************************
|
||||
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
// ignore_for_file: type=lint, type=warning
|
||||
/// Owns the durable Agent checkpoint journal for the lifetime of the app.
|
||||
|
||||
@ProviderFor(agentSessionStore)
|
||||
final agentSessionStoreProvider = AgentSessionStoreProvider._();
|
||||
|
||||
/// Owns the durable Agent checkpoint journal for the lifetime of the app.
|
||||
|
||||
final class AgentSessionStoreProvider
|
||||
extends
|
||||
$FunctionalProvider<
|
||||
AsyncValue<SessionStore>,
|
||||
SessionStore,
|
||||
FutureOr<SessionStore>
|
||||
>
|
||||
with $FutureModifier<SessionStore>, $FutureProvider<SessionStore> {
|
||||
/// Owns the durable Agent checkpoint journal for the lifetime of the app.
|
||||
AgentSessionStoreProvider._()
|
||||
: super(
|
||||
from: null,
|
||||
argument: null,
|
||||
retry: null,
|
||||
name: r'agentSessionStoreProvider',
|
||||
isAutoDispose: false,
|
||||
dependencies: null,
|
||||
$allTransitiveDependencies: null,
|
||||
);
|
||||
|
||||
@override
|
||||
String debugGetCreateSourceHash() => _$agentSessionStoreHash();
|
||||
|
||||
@$internal
|
||||
@override
|
||||
$FutureProviderElement<SessionStore> $createElement(
|
||||
$ProviderPointer pointer,
|
||||
) => $FutureProviderElement(pointer);
|
||||
|
||||
@override
|
||||
FutureOr<SessionStore> create(Ref ref) {
|
||||
return agentSessionStore(ref);
|
||||
}
|
||||
}
|
||||
|
||||
String _$agentSessionStoreHash() => r'9a27b793eb8891e72040a71e9900d074ae069da4';
|
||||
@@ -0,0 +1,80 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:riverpod_annotation/riverpod_annotation.dart';
|
||||
|
||||
import '../../settings/settings_write_queue.dart';
|
||||
import 'agent_models.dart';
|
||||
import 'agent_runtime.dart';
|
||||
import 'agent_runtime_factory.dart';
|
||||
import 'agent_settings_service.dart';
|
||||
|
||||
part 'agent_settings.g.dart';
|
||||
|
||||
/// Presentation-facing state holder. Persistence and credentials are delegated
|
||||
/// to [AgentSettingsService].
|
||||
@Riverpod(keepAlive: true)
|
||||
class AgentSettings extends _$AgentSettings {
|
||||
late AgentSettingsService _service;
|
||||
final _writes = SettingsWriteQueue();
|
||||
|
||||
@override
|
||||
Future<AgentSettingsState> build() async {
|
||||
_service = ref.watch(agentSettingsServiceProvider);
|
||||
return _service.load();
|
||||
}
|
||||
|
||||
Future<void> setEnabled(bool enabled) =>
|
||||
_replace((current) => _service.setEnabled(current, enabled));
|
||||
|
||||
Future<void> setProviderEnabled(String providerId, bool enabled) => _replace(
|
||||
(current) => _service.setProviderEnabled(current, providerId, enabled),
|
||||
);
|
||||
|
||||
Future<void> selectModel(String providerId, String modelId) =>
|
||||
_replace((current) => _service.selectModel(current, providerId, modelId));
|
||||
|
||||
Future<void> upsertProvider({
|
||||
String? id,
|
||||
required String name,
|
||||
required AgentApiType apiType,
|
||||
required String baseUrl,
|
||||
required List<AgentModelSettings> models,
|
||||
String? apiKey,
|
||||
bool clearApiKey = false,
|
||||
}) => _replace(
|
||||
(current) => _service.upsertProvider(
|
||||
current,
|
||||
id: id,
|
||||
name: name,
|
||||
apiType: apiType,
|
||||
baseUrl: baseUrl,
|
||||
models: models,
|
||||
apiKey: apiKey,
|
||||
clearApiKey: clearApiKey,
|
||||
),
|
||||
);
|
||||
|
||||
Future<void> deleteProvider(String providerId) =>
|
||||
_replace((current) => _service.deleteProvider(current, providerId));
|
||||
|
||||
Future<void> _replace(
|
||||
Future<AgentSettingsState> Function(AgentSettingsState) update,
|
||||
) {
|
||||
return _writes.run(() async {
|
||||
if (!ref.mounted) return;
|
||||
final current = await future;
|
||||
if (!ref.mounted) return;
|
||||
final next = await update(current);
|
||||
if (ref.mounted) state = AsyncData(next);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@Riverpod(keepAlive: true)
|
||||
FutureOr<AgentRuntime?> agentRuntime(Ref ref) async {
|
||||
final factory = ref.watch(agentRuntimeFactoryProvider);
|
||||
final settings = ref.watch(agentSettingsProvider);
|
||||
final value = settings.asData?.value;
|
||||
if (value != null) return factory.create(value);
|
||||
return factory.create(await ref.watch(agentSettingsProvider.future));
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'agent_settings.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// RiverpodGenerator
|
||||
// **************************************************************************
|
||||
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
// ignore_for_file: type=lint, type=warning
|
||||
/// Presentation-facing state holder. Persistence and credentials are delegated
|
||||
/// to [AgentSettingsService].
|
||||
|
||||
@ProviderFor(AgentSettings)
|
||||
final agentSettingsProvider = AgentSettingsProvider._();
|
||||
|
||||
/// Presentation-facing state holder. Persistence and credentials are delegated
|
||||
/// to [AgentSettingsService].
|
||||
final class AgentSettingsProvider
|
||||
extends $AsyncNotifierProvider<AgentSettings, AgentSettingsState> {
|
||||
/// Presentation-facing state holder. Persistence and credentials are delegated
|
||||
/// to [AgentSettingsService].
|
||||
AgentSettingsProvider._()
|
||||
: super(
|
||||
from: null,
|
||||
argument: null,
|
||||
retry: null,
|
||||
name: r'agentSettingsProvider',
|
||||
isAutoDispose: false,
|
||||
dependencies: null,
|
||||
$allTransitiveDependencies: null,
|
||||
);
|
||||
|
||||
@override
|
||||
String debugGetCreateSourceHash() => _$agentSettingsHash();
|
||||
|
||||
@$internal
|
||||
@override
|
||||
AgentSettings create() => AgentSettings();
|
||||
}
|
||||
|
||||
String _$agentSettingsHash() => r'484af184c2ccf373b8d0955d737ce64b5a085c54';
|
||||
|
||||
/// Presentation-facing state holder. Persistence and credentials are delegated
|
||||
/// to [AgentSettingsService].
|
||||
|
||||
abstract class _$AgentSettings extends $AsyncNotifier<AgentSettingsState> {
|
||||
FutureOr<AgentSettingsState> build();
|
||||
@$mustCallSuper
|
||||
@override
|
||||
WhenComplete runBuild() {
|
||||
final ref =
|
||||
this.ref as $Ref<AsyncValue<AgentSettingsState>, AgentSettingsState>;
|
||||
final element =
|
||||
ref.element
|
||||
as $ClassProviderElement<
|
||||
AnyNotifier<AsyncValue<AgentSettingsState>, AgentSettingsState>,
|
||||
AsyncValue<AgentSettingsState>,
|
||||
Object?,
|
||||
Object?
|
||||
>;
|
||||
return element.handleCreate(ref, build);
|
||||
}
|
||||
}
|
||||
|
||||
@ProviderFor(agentRuntime)
|
||||
final agentRuntimeProvider = AgentRuntimeProvider._();
|
||||
|
||||
final class AgentRuntimeProvider
|
||||
extends
|
||||
$FunctionalProvider<
|
||||
AsyncValue<AgentRuntime?>,
|
||||
AgentRuntime?,
|
||||
FutureOr<AgentRuntime?>
|
||||
>
|
||||
with $FutureModifier<AgentRuntime?>, $FutureProvider<AgentRuntime?> {
|
||||
AgentRuntimeProvider._()
|
||||
: super(
|
||||
from: null,
|
||||
argument: null,
|
||||
retry: null,
|
||||
name: r'agentRuntimeProvider',
|
||||
isAutoDispose: false,
|
||||
dependencies: null,
|
||||
$allTransitiveDependencies: null,
|
||||
);
|
||||
|
||||
@override
|
||||
String debugGetCreateSourceHash() => _$agentRuntimeHash();
|
||||
|
||||
@$internal
|
||||
@override
|
||||
$FutureProviderElement<AgentRuntime?> $createElement(
|
||||
$ProviderPointer pointer,
|
||||
) => $FutureProviderElement(pointer);
|
||||
|
||||
@override
|
||||
FutureOr<AgentRuntime?> create(Ref ref) {
|
||||
return agentRuntime(ref);
|
||||
}
|
||||
}
|
||||
|
||||
String _$agentRuntimeHash() => r'fa5447ca986924e6f1fe82ee20f6b7c3b41a96c4';
|
||||
@@ -0,0 +1,259 @@
|
||||
import 'package:riverpod_annotation/riverpod_annotation.dart';
|
||||
import 'package:uuid/uuid.dart';
|
||||
|
||||
import '../../persistence/app_settings_repositories.dart';
|
||||
import 'agent_credentials.dart';
|
||||
import 'agent_models.dart';
|
||||
|
||||
part 'agent_settings_service.g.dart';
|
||||
|
||||
@Riverpod(keepAlive: true)
|
||||
AgentSettingsService agentSettingsService(Ref ref) {
|
||||
return AgentSettingsService(
|
||||
repository: ref.watch(agentSettingsRepositoryProvider),
|
||||
credentials: ref.watch(agentCredentialStoreProvider),
|
||||
);
|
||||
}
|
||||
|
||||
/// Owns validation and consistency across settings storage and secure storage.
|
||||
class AgentSettingsService {
|
||||
const AgentSettingsService({
|
||||
required this._repository,
|
||||
required this._credentials,
|
||||
});
|
||||
|
||||
final AgentSettingsRepository _repository;
|
||||
final AgentCredentialStore _credentials;
|
||||
|
||||
Future<AgentSettingsState> load() => _repository.load();
|
||||
|
||||
Future<AgentSettingsState> setEnabled(
|
||||
AgentSettingsState current,
|
||||
bool enabled,
|
||||
) => _save(current, current.copyWith(enabled: enabled));
|
||||
|
||||
Future<AgentSettingsState> setProviderEnabled(
|
||||
AgentSettingsState current,
|
||||
String providerId,
|
||||
bool enabled,
|
||||
) {
|
||||
if (!current.providers.any((provider) => provider.id == providerId)) {
|
||||
throw ArgumentError('Unknown Agent provider');
|
||||
}
|
||||
final providers = [
|
||||
for (final provider in current.providers)
|
||||
if (provider.id == providerId)
|
||||
provider.copyWith(enabled: enabled)
|
||||
else
|
||||
provider,
|
||||
];
|
||||
return _save(
|
||||
current,
|
||||
_normalizeSelection(
|
||||
current.copyWith(
|
||||
providers: providers,
|
||||
enabled: enabled ? true : current.enabled,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Future<AgentSettingsState> selectModel(
|
||||
AgentSettingsState current,
|
||||
String providerId,
|
||||
String modelId,
|
||||
) async {
|
||||
final provider = current.providers
|
||||
.where((candidate) => candidate.id == providerId)
|
||||
.firstOrNull;
|
||||
if (provider == null ||
|
||||
!provider.enabled ||
|
||||
!provider.models.any((candidate) => candidate.id == modelId)) {
|
||||
throw ArgumentError('Unknown Agent model selection');
|
||||
}
|
||||
return _save(
|
||||
current,
|
||||
current.copyWith(
|
||||
enabled: true,
|
||||
selectedProviderId: providerId,
|
||||
selectedModelId: modelId,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Future<AgentSettingsState> upsertProvider(
|
||||
AgentSettingsState current, {
|
||||
String? id,
|
||||
required String name,
|
||||
required AgentApiType apiType,
|
||||
required String baseUrl,
|
||||
required List<AgentModelSettings> models,
|
||||
String? apiKey,
|
||||
bool clearApiKey = false,
|
||||
}) async {
|
||||
final providerId = id ?? const Uuid().v4();
|
||||
final existing = current.providers
|
||||
.where((provider) => provider.id == providerId)
|
||||
.firstOrNull;
|
||||
_validateProvider(name, baseUrl, models, apiKey);
|
||||
|
||||
var credentialId = existing?.credentialId;
|
||||
var credentialWriteAttempted = false;
|
||||
String? previousSecret;
|
||||
String? credentialToDelete;
|
||||
if (clearApiKey && credentialId != null) {
|
||||
credentialToDelete = credentialId;
|
||||
credentialId = null;
|
||||
} else if (apiKey != null && apiKey.isNotEmpty) {
|
||||
credentialId ??= 'cutdex-agent-provider-$providerId';
|
||||
if (existing?.credentialId != null) {
|
||||
previousSecret = await _credentials.read(credentialId);
|
||||
}
|
||||
credentialWriteAttempted = true;
|
||||
try {
|
||||
await _credentials.write(credentialId, apiKey);
|
||||
} catch (error, stackTrace) {
|
||||
await _restoreCredential(credentialId, previousSecret);
|
||||
Error.throwWithStackTrace(error, stackTrace);
|
||||
}
|
||||
}
|
||||
|
||||
final normalizedModels = [
|
||||
for (final model in models) model.copyWith(id: model.id.trim()),
|
||||
];
|
||||
final provider = AgentProviderSettings(
|
||||
id: providerId,
|
||||
name: name.trim(),
|
||||
apiType: apiType.name,
|
||||
baseUrl: baseUrl.trim(),
|
||||
credentialId: credentialId,
|
||||
enabled: existing?.enabled ?? true,
|
||||
models: List.unmodifiable(normalizedModels),
|
||||
);
|
||||
final providers = [
|
||||
for (final candidate in current.providers)
|
||||
if (candidate.id != providerId) candidate,
|
||||
provider,
|
||||
];
|
||||
|
||||
try {
|
||||
final saved = await _save(
|
||||
current,
|
||||
_normalizeSelection(
|
||||
current.copyWith(
|
||||
providers: providers,
|
||||
enabled: (existing?.enabled ?? true) ? true : current.enabled,
|
||||
),
|
||||
),
|
||||
);
|
||||
if (credentialToDelete != null) {
|
||||
await _deleteOrphan(credentialToDelete);
|
||||
}
|
||||
return saved;
|
||||
} catch (error, stackTrace) {
|
||||
if (credentialWriteAttempted && credentialId != null) {
|
||||
await _restoreCredential(credentialId, previousSecret);
|
||||
}
|
||||
Error.throwWithStackTrace(error, stackTrace);
|
||||
}
|
||||
}
|
||||
|
||||
Future<AgentSettingsState> deleteProvider(
|
||||
AgentSettingsState current,
|
||||
String providerId,
|
||||
) async {
|
||||
final removed = current.providers
|
||||
.where((provider) => provider.id == providerId)
|
||||
.firstOrNull;
|
||||
if (removed == null) return current;
|
||||
final providers = current.providers
|
||||
.where((provider) => provider.id != providerId)
|
||||
.toList();
|
||||
final saved = await _save(
|
||||
current,
|
||||
_normalizeSelection(current.copyWith(providers: providers)),
|
||||
);
|
||||
if (removed.credentialId case final credentialId?) {
|
||||
await _deleteOrphan(credentialId);
|
||||
}
|
||||
return saved;
|
||||
}
|
||||
|
||||
Future<AgentSettingsState> _save(
|
||||
AgentSettingsState current,
|
||||
AgentSettingsState next,
|
||||
) async {
|
||||
final revised = next.copyWith(revision: current.revision + 1);
|
||||
await _repository.save(revised);
|
||||
return revised;
|
||||
}
|
||||
|
||||
Future<void> _deleteOrphan(String credentialId) async {
|
||||
try {
|
||||
await _credentials.delete(credentialId);
|
||||
} catch (_) {
|
||||
// Metadata is authoritative. An inaccessible orphan can be cleaned later.
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _restoreCredential(
|
||||
String credentialId,
|
||||
String? previousSecret,
|
||||
) async {
|
||||
try {
|
||||
if (previousSecret == null) {
|
||||
await _credentials.delete(credentialId);
|
||||
} else {
|
||||
await _credentials.write(credentialId, previousSecret);
|
||||
}
|
||||
} catch (_) {
|
||||
// Preserve the original storage or repository failure for the caller.
|
||||
}
|
||||
}
|
||||
|
||||
static AgentSettingsState _normalizeSelection(AgentSettingsState settings) {
|
||||
final available = settings.providers.where(
|
||||
(provider) => provider.enabled && provider.models.isNotEmpty,
|
||||
);
|
||||
final selected = available
|
||||
.where((provider) => provider.id == settings.selectedProviderId)
|
||||
.firstOrNull;
|
||||
final provider = selected ?? available.firstOrNull;
|
||||
final model =
|
||||
provider?.models
|
||||
.where((model) => model.id == settings.selectedModelId)
|
||||
.firstOrNull ??
|
||||
provider?.models.firstOrNull;
|
||||
return settings.copyWith(
|
||||
selectedProviderId: provider?.id,
|
||||
selectedModelId: model?.id,
|
||||
);
|
||||
}
|
||||
|
||||
static void _validateProvider(
|
||||
String name,
|
||||
String baseUrl,
|
||||
List<AgentModelSettings> models,
|
||||
String? apiKey,
|
||||
) {
|
||||
final uri = Uri.tryParse(baseUrl.trim());
|
||||
if (name.trim().isEmpty ||
|
||||
uri == null ||
|
||||
!uri.hasAuthority ||
|
||||
!['http', 'https'].contains(uri.scheme) ||
|
||||
uri.userInfo.isNotEmpty ||
|
||||
uri.hasQuery ||
|
||||
uri.hasFragment ||
|
||||
models.isEmpty ||
|
||||
models.any((model) => model.id.trim().isEmpty) ||
|
||||
models.map((model) => model.id.trim()).toSet().length !=
|
||||
models.length ||
|
||||
models.any(
|
||||
(model) => !model.hasValidTokenBudget || !model.hasInstructionBudget,
|
||||
) ||
|
||||
(apiKey?.contains('\n') ?? false) ||
|
||||
(apiKey?.contains('\r') ?? false)) {
|
||||
throw ArgumentError('Invalid Agent provider configuration');
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'agent_settings_service.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// RiverpodGenerator
|
||||
// **************************************************************************
|
||||
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
// ignore_for_file: type=lint, type=warning
|
||||
|
||||
@ProviderFor(agentSettingsService)
|
||||
final agentSettingsServiceProvider = AgentSettingsServiceProvider._();
|
||||
|
||||
final class AgentSettingsServiceProvider
|
||||
extends
|
||||
$FunctionalProvider<
|
||||
AgentSettingsService,
|
||||
AgentSettingsService,
|
||||
AgentSettingsService
|
||||
>
|
||||
with $Provider<AgentSettingsService> {
|
||||
AgentSettingsServiceProvider._()
|
||||
: super(
|
||||
from: null,
|
||||
argument: null,
|
||||
retry: null,
|
||||
name: r'agentSettingsServiceProvider',
|
||||
isAutoDispose: false,
|
||||
dependencies: null,
|
||||
$allTransitiveDependencies: null,
|
||||
);
|
||||
|
||||
@override
|
||||
String debugGetCreateSourceHash() => _$agentSettingsServiceHash();
|
||||
|
||||
@$internal
|
||||
@override
|
||||
$ProviderElement<AgentSettingsService> $createElement(
|
||||
$ProviderPointer pointer,
|
||||
) => $ProviderElement(pointer);
|
||||
|
||||
@override
|
||||
AgentSettingsService create(Ref ref) {
|
||||
return agentSettingsService(ref);
|
||||
}
|
||||
|
||||
/// {@macro riverpod.override_with_value}
|
||||
Override overrideWithValue(AgentSettingsService value) {
|
||||
return $ProviderOverride(
|
||||
origin: this,
|
||||
providerOverride: $SyncValueProvider<AgentSettingsService>(value),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
String _$agentSettingsServiceHash() =>
|
||||
r'76935437a9221e7add0706e92634ae8a21496fa2';
|
||||
@@ -0,0 +1,389 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:cutdex_agent/cutdex_agent.dart';
|
||||
import 'package:cutdex_agent/io.dart';
|
||||
import 'package:freezed_annotation/freezed_annotation.dart';
|
||||
import 'package:path/path.dart' as p;
|
||||
import 'package:path_provider/path_provider.dart';
|
||||
import 'package:riverpod_annotation/riverpod_annotation.dart';
|
||||
import 'package:uuid/uuid.dart';
|
||||
|
||||
import '../../persistence/app_settings_repositories.dart';
|
||||
import '../../errors/app_failure.dart';
|
||||
|
||||
part 'conversation_repository.g.dart';
|
||||
part 'conversation_repository.freezed.dart';
|
||||
|
||||
@Riverpod(keepAlive: true)
|
||||
ConversationLocation conversationLocation(Ref ref) => ConversationLocation(
|
||||
ref.watch(conversationLocationSettingsRepositoryProvider),
|
||||
);
|
||||
|
||||
@Riverpod(keepAlive: true)
|
||||
FutureOr<ConversationRepository> conversationRepository(Ref ref) async =>
|
||||
ConversationRepository(
|
||||
await ref.watch(conversationLocationProvider).load(),
|
||||
);
|
||||
|
||||
/// The location pointer is replaceable; the conversation files are not app data.
|
||||
class ConversationLocation {
|
||||
ConversationLocation(
|
||||
this._settings, {
|
||||
Future<Directory> Function()? documentsDirectory,
|
||||
}) : _documentsDirectory =
|
||||
documentsDirectory ?? getApplicationDocumentsDirectory;
|
||||
|
||||
final ConversationLocationSettingsRepository _settings;
|
||||
final Future<Directory> Function() _documentsDirectory;
|
||||
|
||||
Future<Directory> load() async {
|
||||
final configured = await _settings.load();
|
||||
if (configured != null) {
|
||||
final root = Directory(configured);
|
||||
if (!root.isAbsolute || !await root.exists()) {
|
||||
throw AppException(
|
||||
AppErrorCode.agentLocationUnavailable,
|
||||
diagnostic: root.path,
|
||||
);
|
||||
}
|
||||
return root;
|
||||
}
|
||||
final documents = await _documentsDirectory();
|
||||
return Directory(p.join(documents.path, 'Cutdex', 'Conversations'));
|
||||
}
|
||||
|
||||
Future<void> useExisting(Directory root) async {
|
||||
if (!root.isAbsolute || !await root.exists()) {
|
||||
throw AppException(
|
||||
AppErrorCode.agentLocationUnavailable,
|
||||
diagnostic: root.path,
|
||||
);
|
||||
}
|
||||
if (!await ConversationRepository(root).verify()) {
|
||||
throw const FormatException('Invalid conversation directory');
|
||||
}
|
||||
await _settings.save(root.path);
|
||||
}
|
||||
|
||||
Future<void> relocate(Directory source, Directory target) async {
|
||||
if (!target.isAbsolute || await target.exists()) {
|
||||
throw const FileSystemException(
|
||||
'Destination must be an unused directory',
|
||||
);
|
||||
}
|
||||
final sourcePath = p.normalize(source.absolute.path);
|
||||
final targetPath = p.normalize(target.absolute.path);
|
||||
if (targetPath == sourcePath || p.isWithin(sourcePath, targetPath)) {
|
||||
throw const FileSystemException(
|
||||
'Destination cannot be inside the current conversations directory',
|
||||
);
|
||||
}
|
||||
final staging = await target.parent.createTemp('.cutdex-conversations-');
|
||||
try {
|
||||
await _copyDirectory(source, staging);
|
||||
if (!(await ConversationRepository(staging).verify())) {
|
||||
throw const FormatException('Copied conversations failed validation');
|
||||
}
|
||||
await staging.rename(target.path);
|
||||
await _settings.save(target.path);
|
||||
} finally {
|
||||
if (await staging.exists()) await staging.delete(recursive: true);
|
||||
}
|
||||
}
|
||||
|
||||
static Future<void> _copyDirectory(Directory source, Directory target) async {
|
||||
if (!await source.exists()) return;
|
||||
await for (final entry in source.list(followLinks: false)) {
|
||||
final destination = p.join(target.path, p.basename(entry.path));
|
||||
if (entry is Directory) {
|
||||
final child = await Directory(destination).create();
|
||||
await _copyDirectory(entry, child);
|
||||
} else if (entry is File) {
|
||||
await entry.copy(destination);
|
||||
} else {
|
||||
throw const FileSystemException('Unsupported conversation entry');
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@freezed
|
||||
abstract class ConversationMetadata with _$ConversationMetadata {
|
||||
const factory ConversationMetadata({
|
||||
required String id,
|
||||
required String projectId,
|
||||
required String title,
|
||||
required DateTime createdAt,
|
||||
required DateTime updatedAt,
|
||||
required String providerId,
|
||||
required String modelId,
|
||||
required String timelineId,
|
||||
@JsonKey(required: true, disallowNullValue: true) required bool pending,
|
||||
@JsonKey(required: true, disallowNullValue: true)
|
||||
required List<int?> responseDurationsMs,
|
||||
}) = _ConversationMetadata;
|
||||
|
||||
factory ConversationMetadata.fromJson(Map<String, Object?> json) =>
|
||||
_$ConversationMetadataFromJson(json);
|
||||
}
|
||||
|
||||
/// Owns project-to-conversation membership; the Agent owns journal contents.
|
||||
class ConversationRepository {
|
||||
ConversationRepository(this.root);
|
||||
|
||||
final Directory root;
|
||||
static const _uuid = Uuid();
|
||||
final Set<String> _pendingInProcess = {};
|
||||
|
||||
String _projectName(String id) =>
|
||||
base64Url.encode(utf8.encode(id)).replaceAll('=', '');
|
||||
|
||||
Directory _project(String id, {bool trash = false}) =>
|
||||
Directory(p.joinAll([root.path, if (trash) 'Trash', _projectName(id)]));
|
||||
|
||||
Directory directory(
|
||||
String projectId,
|
||||
String conversationId, {
|
||||
bool trash = false,
|
||||
}) {
|
||||
if (!Uuid.isValidUUID(fromString: conversationId)) {
|
||||
throw ArgumentError.value(conversationId, 'conversationId');
|
||||
}
|
||||
return Directory(
|
||||
p.join(_project(projectId, trash: trash).path, conversationId),
|
||||
);
|
||||
}
|
||||
|
||||
FileSessionStore store(ConversationMetadata conversation) =>
|
||||
FileSessionStore(directory(conversation.projectId, conversation.id));
|
||||
|
||||
Future<ConversationMetadata> begin({
|
||||
required String projectId,
|
||||
required String timelineId,
|
||||
required String providerId,
|
||||
required String modelId,
|
||||
required String title,
|
||||
}) async {
|
||||
final now = DateTime.now().toUtc();
|
||||
final item = ConversationMetadata(
|
||||
id: _uuid.v4(),
|
||||
projectId: projectId,
|
||||
title: title.trim(),
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
providerId: providerId,
|
||||
modelId: modelId,
|
||||
timelineId: timelineId,
|
||||
pending: true,
|
||||
responseDurationsMs: const [],
|
||||
);
|
||||
await directory(projectId, item.id).create(recursive: true);
|
||||
await _write(item);
|
||||
_pendingInProcess.add(item.id);
|
||||
return item;
|
||||
}
|
||||
|
||||
Future<ConversationMetadata> publish(ConversationMetadata item) async {
|
||||
final snapshot = await store(item).read(item.id);
|
||||
if (snapshot == null ||
|
||||
!snapshot.history.any((message) => message.role == MessageRole.user)) {
|
||||
throw StateError('Conversation has no saved user message');
|
||||
}
|
||||
final published = item.copyWith(
|
||||
pending: false,
|
||||
updatedAt: DateTime.now().toUtc(),
|
||||
);
|
||||
await _write(published);
|
||||
_pendingInProcess.remove(item.id);
|
||||
return published;
|
||||
}
|
||||
|
||||
Future<ConversationMetadata?> read(
|
||||
String projectId,
|
||||
String id, {
|
||||
bool trash = false,
|
||||
}) async {
|
||||
final file = File(
|
||||
p.join(directory(projectId, id, trash: trash).path, 'metadata.json'),
|
||||
);
|
||||
if (!await file.exists()) return null;
|
||||
final json = (jsonDecode(await file.readAsString()) as Map)
|
||||
.cast<String, Object?>();
|
||||
final item = ConversationMetadata.fromJson(json);
|
||||
if (item.id != id || item.projectId != projectId) {
|
||||
throw const FormatException('Conversation identity mismatch');
|
||||
}
|
||||
return item;
|
||||
}
|
||||
|
||||
Future<List<ConversationMetadata>> list(
|
||||
String projectId, {
|
||||
bool trash = false,
|
||||
}) async {
|
||||
final parent = _project(projectId, trash: trash);
|
||||
if (!await parent.exists()) return [];
|
||||
final result = <ConversationMetadata>[];
|
||||
await for (final entry in parent.list(followLinks: false)) {
|
||||
if (entry is! Directory) continue;
|
||||
try {
|
||||
final item = await read(
|
||||
projectId,
|
||||
p.basename(entry.path),
|
||||
trash: trash,
|
||||
);
|
||||
if (item == null) {
|
||||
continue;
|
||||
}
|
||||
if (item.pending && !trash) {
|
||||
if (_pendingInProcess.contains(item.id)) continue;
|
||||
final snapshot = await store(item).read(item.id);
|
||||
if (snapshot?.history.any(
|
||||
(message) => message.role == MessageRole.user,
|
||||
) ==
|
||||
true) {
|
||||
result.add(await publish(item));
|
||||
} else {
|
||||
await entry.delete(recursive: true);
|
||||
}
|
||||
} else {
|
||||
result.add(item);
|
||||
}
|
||||
} on FormatException {
|
||||
// One corrupt metadata file must not hide the remaining conversations.
|
||||
} on BadKeyException {
|
||||
// Entries outside the current metadata contract stay untouched.
|
||||
} on TypeError {
|
||||
// Malformed field types are isolated to the affected conversation.
|
||||
} on FileSystemException {
|
||||
// A damaged or inaccessible entry does not hide its siblings.
|
||||
} on ArgumentError {
|
||||
// Ignore unrelated folders without treating them as conversations.
|
||||
}
|
||||
}
|
||||
result.sort((a, b) => b.updatedAt.compareTo(a.updatedAt));
|
||||
return result;
|
||||
}
|
||||
|
||||
Future<String?> selected(String projectId) async {
|
||||
final state = File(p.join(_project(projectId).path, 'state.json'));
|
||||
try {
|
||||
final json = (jsonDecode(await state.readAsString()) as Map)
|
||||
.cast<String, Object?>();
|
||||
if (json['version'] != 1) {
|
||||
throw const FormatException('Unsupported conversation state');
|
||||
}
|
||||
final id = json['conversationId'] as String?;
|
||||
if (id != null && await read(projectId, id) != null) return id;
|
||||
} on FileSystemException {
|
||||
// Missing selection is recovered from the conversation list.
|
||||
} on FormatException {
|
||||
// The selection is disposable view state.
|
||||
} on BadKeyException {
|
||||
// Select only conversations that satisfy the current metadata contract.
|
||||
} on TypeError {
|
||||
// A malformed selection is disposable view state.
|
||||
} on ArgumentError {
|
||||
// An invalid UUID is disposable view state.
|
||||
}
|
||||
return (await list(projectId)).firstOrNull?.id;
|
||||
}
|
||||
|
||||
Future<void> select(String projectId, String? id) async {
|
||||
if (id != null && await read(projectId, id) == null) {
|
||||
throw ArgumentError.value(id, 'conversationId');
|
||||
}
|
||||
final parent = _project(projectId);
|
||||
await parent.create(recursive: true);
|
||||
await _writeJson(File(p.join(parent.path, 'state.json')), {
|
||||
'version': 1,
|
||||
'conversationId': id,
|
||||
});
|
||||
}
|
||||
|
||||
Future<ConversationMetadata> update(ConversationMetadata item) async {
|
||||
if (await read(item.projectId, item.id) == null) {
|
||||
throw StateError('Conversation no longer exists');
|
||||
}
|
||||
final updated = item.copyWith(updatedAt: DateTime.now().toUtc());
|
||||
await _write(updated);
|
||||
return updated;
|
||||
}
|
||||
|
||||
Future<void> trash(String projectId, String id) async {
|
||||
final source = directory(projectId, id);
|
||||
if (!await source.exists()) return;
|
||||
final wasSelected = await selected(projectId) == id;
|
||||
final destination = directory(projectId, id, trash: true);
|
||||
await destination.parent.create(recursive: true);
|
||||
await source.rename(destination.path);
|
||||
if (wasSelected) await select(projectId, null);
|
||||
}
|
||||
|
||||
Future<void> restore(String projectId, String id) async {
|
||||
final source = directory(projectId, id, trash: true);
|
||||
if (!await source.exists()) throw ArgumentError.value(id, 'conversationId');
|
||||
final target = directory(projectId, id);
|
||||
if (await target.exists()) throw StateError('Conversation already exists');
|
||||
await target.parent.create(recursive: true);
|
||||
await source.rename(target.path);
|
||||
}
|
||||
|
||||
Future<void> deletePermanently(String projectId, String id) async {
|
||||
if (await selected(projectId) == id) await select(projectId, null);
|
||||
for (final trash in [false, true]) {
|
||||
final target = directory(projectId, id, trash: trash);
|
||||
if (await target.exists()) await target.delete(recursive: true);
|
||||
}
|
||||
}
|
||||
|
||||
Future<bool> verify() async {
|
||||
if (!await root.exists()) return true;
|
||||
if (!await _verifyProjects(root)) return false;
|
||||
final trash = Directory(p.join(root.path, 'Trash'));
|
||||
if (await trash.exists() && !await _verifyProjects(trash)) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
Future<bool> _verifyProjects(Directory parent) async {
|
||||
await for (final project in parent.list(followLinks: false)) {
|
||||
if (project is! Directory || p.basename(project.path) == 'Trash') {
|
||||
continue;
|
||||
}
|
||||
await for (final entry in project.list(followLinks: false)) {
|
||||
if (entry is! Directory) continue;
|
||||
try {
|
||||
final file = File(p.join(entry.path, 'metadata.json'));
|
||||
final json = (jsonDecode(await file.readAsString()) as Map)
|
||||
.cast<String, Object?>();
|
||||
final item = ConversationMetadata.fromJson(json);
|
||||
if (item.id != p.basename(entry.path) ||
|
||||
_projectName(item.projectId) != p.basename(project.path)) {
|
||||
return false;
|
||||
}
|
||||
await FileSessionStore(entry).verify(item.id);
|
||||
} catch (_) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
Future<void> _write(ConversationMetadata item) => _writeJson(
|
||||
File(p.join(directory(item.projectId, item.id).path, 'metadata.json')),
|
||||
item.toJson(),
|
||||
);
|
||||
|
||||
Future<void> _writeJson(File target, Map<String, Object?> json) async {
|
||||
await target.parent.create(recursive: true);
|
||||
final temp = File('${target.path}.${_uuid.v4()}.tmp');
|
||||
try {
|
||||
await temp.writeAsString(jsonEncode(json), flush: true);
|
||||
await temp.rename(target.path);
|
||||
} finally {
|
||||
if (await temp.exists()) await temp.delete();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,626 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
// coverage:ignore-file
|
||||
// ignore_for_file: type=lint, type=warning, deprecated_member_use, deprecated_member_use_from_same_package
|
||||
// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark
|
||||
|
||||
part of 'conversation_repository.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// FreezedGenerator
|
||||
// **************************************************************************
|
||||
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
T _$identity<T>(T value) => value;
|
||||
|
||||
/// @nodoc
|
||||
mixin _$ConversationMetadata {
|
||||
String get id;
|
||||
String get projectId;
|
||||
String get title;
|
||||
DateTime get createdAt;
|
||||
DateTime get updatedAt;
|
||||
String get providerId;
|
||||
String get modelId;
|
||||
String get timelineId;
|
||||
@JsonKey(required: true, disallowNullValue: true)
|
||||
bool get pending;
|
||||
@JsonKey(required: true, disallowNullValue: true)
|
||||
List<int?> get responseDurationsMs;
|
||||
|
||||
/// Create a copy of ConversationMetadata
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@JsonKey(includeFromJson: false, includeToJson: false)
|
||||
@pragma('vm:prefer-inline')
|
||||
$ConversationMetadataCopyWith<ConversationMetadata> get copyWith =>
|
||||
_$ConversationMetadataCopyWithImpl<ConversationMetadata>(
|
||||
this as ConversationMetadata,
|
||||
_$identity,
|
||||
);
|
||||
|
||||
/// Serializes this ConversationMetadata to a JSON map.
|
||||
Map<String, dynamic> toJson();
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) {
|
||||
final _this = this as ConversationMetadata;
|
||||
return identical(this, other) ||
|
||||
(other.runtimeType == runtimeType &&
|
||||
other is ConversationMetadata &&
|
||||
(identical(other.id, _this.id) || other.id == _this.id) &&
|
||||
(identical(other.projectId, _this.projectId) ||
|
||||
other.projectId == _this.projectId) &&
|
||||
(identical(other.title, _this.title) ||
|
||||
other.title == _this.title) &&
|
||||
(identical(other.createdAt, _this.createdAt) ||
|
||||
other.createdAt == _this.createdAt) &&
|
||||
(identical(other.updatedAt, _this.updatedAt) ||
|
||||
other.updatedAt == _this.updatedAt) &&
|
||||
(identical(other.providerId, _this.providerId) ||
|
||||
other.providerId == _this.providerId) &&
|
||||
(identical(other.modelId, _this.modelId) ||
|
||||
other.modelId == _this.modelId) &&
|
||||
(identical(other.timelineId, _this.timelineId) ||
|
||||
other.timelineId == _this.timelineId) &&
|
||||
(identical(other.pending, _this.pending) ||
|
||||
other.pending == _this.pending) &&
|
||||
const DeepCollectionEquality().equals(
|
||||
other.responseDurationsMs,
|
||||
_this.responseDurationsMs,
|
||||
));
|
||||
}
|
||||
|
||||
@JsonKey(includeFromJson: false, includeToJson: false)
|
||||
@override
|
||||
int get hashCode {
|
||||
final _this = this as ConversationMetadata;
|
||||
return Object.hash(
|
||||
runtimeType,
|
||||
_this.id,
|
||||
_this.projectId,
|
||||
_this.title,
|
||||
_this.createdAt,
|
||||
_this.updatedAt,
|
||||
_this.providerId,
|
||||
_this.modelId,
|
||||
_this.timelineId,
|
||||
_this.pending,
|
||||
const DeepCollectionEquality().hash(_this.responseDurationsMs),
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
final _this = this as ConversationMetadata;
|
||||
return 'ConversationMetadata(id: ${_this.id}, projectId: ${_this.projectId}, title: ${_this.title}, createdAt: ${_this.createdAt}, updatedAt: ${_this.updatedAt}, providerId: ${_this.providerId}, modelId: ${_this.modelId}, timelineId: ${_this.timelineId}, pending: ${_this.pending}, responseDurationsMs: ${_this.responseDurationsMs})';
|
||||
}
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
abstract mixin class $ConversationMetadataCopyWith<$Res> {
|
||||
factory $ConversationMetadataCopyWith(
|
||||
ConversationMetadata value,
|
||||
$Res Function(ConversationMetadata) _then,
|
||||
) = _$ConversationMetadataCopyWithImpl;
|
||||
@useResult
|
||||
$Res call({
|
||||
String id,
|
||||
String projectId,
|
||||
String title,
|
||||
DateTime createdAt,
|
||||
DateTime updatedAt,
|
||||
String providerId,
|
||||
String modelId,
|
||||
String timelineId,
|
||||
@JsonKey(required: true, disallowNullValue: true) bool pending,
|
||||
@JsonKey(required: true, disallowNullValue: true)
|
||||
List<int?> responseDurationsMs,
|
||||
});
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
class _$ConversationMetadataCopyWithImpl<$Res>
|
||||
implements $ConversationMetadataCopyWith<$Res> {
|
||||
_$ConversationMetadataCopyWithImpl(this._self, this._then);
|
||||
|
||||
final ConversationMetadata _self;
|
||||
final $Res Function(ConversationMetadata) _then;
|
||||
|
||||
/// Create a copy of ConversationMetadata
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@pragma('vm:prefer-inline')
|
||||
@override
|
||||
$Res call({
|
||||
Object? id = null,
|
||||
Object? projectId = null,
|
||||
Object? title = null,
|
||||
Object? createdAt = null,
|
||||
Object? updatedAt = null,
|
||||
Object? providerId = null,
|
||||
Object? modelId = null,
|
||||
Object? timelineId = null,
|
||||
Object? pending = null,
|
||||
Object? responseDurationsMs = null,
|
||||
}) {
|
||||
return _then(
|
||||
ConversationMetadata(
|
||||
id: null == id
|
||||
? _self.id
|
||||
: id // ignore: cast_nullable_to_non_nullable
|
||||
as String,
|
||||
projectId: null == projectId
|
||||
? _self.projectId
|
||||
: projectId // ignore: cast_nullable_to_non_nullable
|
||||
as String,
|
||||
title: null == title
|
||||
? _self.title
|
||||
: title // ignore: cast_nullable_to_non_nullable
|
||||
as String,
|
||||
createdAt: null == createdAt
|
||||
? _self.createdAt
|
||||
: createdAt // ignore: cast_nullable_to_non_nullable
|
||||
as DateTime,
|
||||
updatedAt: null == updatedAt
|
||||
? _self.updatedAt
|
||||
: updatedAt // ignore: cast_nullable_to_non_nullable
|
||||
as DateTime,
|
||||
providerId: null == providerId
|
||||
? _self.providerId
|
||||
: providerId // ignore: cast_nullable_to_non_nullable
|
||||
as String,
|
||||
modelId: null == modelId
|
||||
? _self.modelId
|
||||
: modelId // ignore: cast_nullable_to_non_nullable
|
||||
as String,
|
||||
timelineId: null == timelineId
|
||||
? _self.timelineId
|
||||
: timelineId // ignore: cast_nullable_to_non_nullable
|
||||
as String,
|
||||
pending: null == pending
|
||||
? _self.pending
|
||||
: pending // ignore: cast_nullable_to_non_nullable
|
||||
as bool,
|
||||
responseDurationsMs: null == responseDurationsMs
|
||||
? _self.responseDurationsMs
|
||||
: responseDurationsMs // ignore: cast_nullable_to_non_nullable
|
||||
as List<int?>,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds pattern-matching-related methods to [ConversationMetadata].
|
||||
extension ConversationMetadataPatterns on ConversationMetadata {
|
||||
/// A variant of `map` that fallback to returning `orElse`.
|
||||
///
|
||||
/// It is equivalent to doing:
|
||||
/// ```dart
|
||||
/// switch (sealedClass) {
|
||||
/// case final Subclass value:
|
||||
/// return ...;
|
||||
/// case _:
|
||||
/// return orElse();
|
||||
/// }
|
||||
/// ```
|
||||
|
||||
@optionalTypeArgs
|
||||
TResult maybeMap<TResult extends Object?>(
|
||||
TResult Function(_ConversationMetadata value)? $default, {
|
||||
required TResult orElse(),
|
||||
}) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _ConversationMetadata() when $default != null:
|
||||
return $default(_that);
|
||||
case _:
|
||||
return orElse();
|
||||
}
|
||||
}
|
||||
|
||||
/// A `switch`-like method, using callbacks.
|
||||
///
|
||||
/// Callbacks receives the raw object, upcasted.
|
||||
/// It is equivalent to doing:
|
||||
/// ```dart
|
||||
/// switch (sealedClass) {
|
||||
/// case final Subclass value:
|
||||
/// return ...;
|
||||
/// case final Subclass2 value:
|
||||
/// return ...;
|
||||
/// }
|
||||
/// ```
|
||||
|
||||
@optionalTypeArgs
|
||||
TResult map<TResult extends Object?>(
|
||||
TResult Function(_ConversationMetadata value) $default,
|
||||
) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _ConversationMetadata():
|
||||
return $default(_that);
|
||||
case _:
|
||||
throw StateError('Unexpected subclass');
|
||||
}
|
||||
}
|
||||
|
||||
/// A variant of `map` that fallback to returning `null`.
|
||||
///
|
||||
/// It is equivalent to doing:
|
||||
/// ```dart
|
||||
/// switch (sealedClass) {
|
||||
/// case final Subclass value:
|
||||
/// return ...;
|
||||
/// case _:
|
||||
/// return null;
|
||||
/// }
|
||||
/// ```
|
||||
|
||||
@optionalTypeArgs
|
||||
TResult? mapOrNull<TResult extends Object?>(
|
||||
TResult? Function(_ConversationMetadata value)? $default,
|
||||
) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _ConversationMetadata() when $default != null:
|
||||
return $default(_that);
|
||||
case _:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// A variant of `when` that fallback to an `orElse` callback.
|
||||
///
|
||||
/// It is equivalent to doing:
|
||||
/// ```dart
|
||||
/// switch (sealedClass) {
|
||||
/// case Subclass(:final field):
|
||||
/// return ...;
|
||||
/// case _:
|
||||
/// return orElse();
|
||||
/// }
|
||||
/// ```
|
||||
|
||||
@optionalTypeArgs
|
||||
TResult maybeWhen<TResult extends Object?>(
|
||||
TResult Function(
|
||||
String id,
|
||||
String projectId,
|
||||
String title,
|
||||
DateTime createdAt,
|
||||
DateTime updatedAt,
|
||||
String providerId,
|
||||
String modelId,
|
||||
String timelineId,
|
||||
@JsonKey(required: true, disallowNullValue: true) bool pending,
|
||||
@JsonKey(required: true, disallowNullValue: true)
|
||||
List<int?> responseDurationsMs,
|
||||
)?
|
||||
$default, {
|
||||
required TResult orElse(),
|
||||
}) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _ConversationMetadata() when $default != null:
|
||||
return $default(
|
||||
_that.id,
|
||||
_that.projectId,
|
||||
_that.title,
|
||||
_that.createdAt,
|
||||
_that.updatedAt,
|
||||
_that.providerId,
|
||||
_that.modelId,
|
||||
_that.timelineId,
|
||||
_that.pending,
|
||||
_that.responseDurationsMs,
|
||||
);
|
||||
case _:
|
||||
return orElse();
|
||||
}
|
||||
}
|
||||
|
||||
/// A `switch`-like method, using callbacks.
|
||||
///
|
||||
/// As opposed to `map`, this offers destructuring.
|
||||
/// It is equivalent to doing:
|
||||
/// ```dart
|
||||
/// switch (sealedClass) {
|
||||
/// case Subclass(:final field):
|
||||
/// return ...;
|
||||
/// case Subclass2(:final field2):
|
||||
/// return ...;
|
||||
/// }
|
||||
/// ```
|
||||
|
||||
@optionalTypeArgs
|
||||
TResult when<TResult extends Object?>(
|
||||
TResult Function(
|
||||
String id,
|
||||
String projectId,
|
||||
String title,
|
||||
DateTime createdAt,
|
||||
DateTime updatedAt,
|
||||
String providerId,
|
||||
String modelId,
|
||||
String timelineId,
|
||||
@JsonKey(required: true, disallowNullValue: true) bool pending,
|
||||
@JsonKey(required: true, disallowNullValue: true)
|
||||
List<int?> responseDurationsMs,
|
||||
)
|
||||
$default,
|
||||
) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _ConversationMetadata():
|
||||
return $default(
|
||||
_that.id,
|
||||
_that.projectId,
|
||||
_that.title,
|
||||
_that.createdAt,
|
||||
_that.updatedAt,
|
||||
_that.providerId,
|
||||
_that.modelId,
|
||||
_that.timelineId,
|
||||
_that.pending,
|
||||
_that.responseDurationsMs,
|
||||
);
|
||||
case _:
|
||||
throw StateError('Unexpected subclass');
|
||||
}
|
||||
}
|
||||
|
||||
/// A variant of `when` that fallback to returning `null`
|
||||
///
|
||||
/// It is equivalent to doing:
|
||||
/// ```dart
|
||||
/// switch (sealedClass) {
|
||||
/// case Subclass(:final field):
|
||||
/// return ...;
|
||||
/// case _:
|
||||
/// return null;
|
||||
/// }
|
||||
/// ```
|
||||
|
||||
@optionalTypeArgs
|
||||
TResult? whenOrNull<TResult extends Object?>(
|
||||
TResult? Function(
|
||||
String id,
|
||||
String projectId,
|
||||
String title,
|
||||
DateTime createdAt,
|
||||
DateTime updatedAt,
|
||||
String providerId,
|
||||
String modelId,
|
||||
String timelineId,
|
||||
@JsonKey(required: true, disallowNullValue: true) bool pending,
|
||||
@JsonKey(required: true, disallowNullValue: true)
|
||||
List<int?> responseDurationsMs,
|
||||
)?
|
||||
$default,
|
||||
) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _ConversationMetadata() when $default != null:
|
||||
return $default(
|
||||
_that.id,
|
||||
_that.projectId,
|
||||
_that.title,
|
||||
_that.createdAt,
|
||||
_that.updatedAt,
|
||||
_that.providerId,
|
||||
_that.modelId,
|
||||
_that.timelineId,
|
||||
_that.pending,
|
||||
_that.responseDurationsMs,
|
||||
);
|
||||
case _:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
@JsonSerializable()
|
||||
class _ConversationMetadata implements ConversationMetadata {
|
||||
const _ConversationMetadata({
|
||||
required this.id,
|
||||
required this.projectId,
|
||||
required this.title,
|
||||
required this.createdAt,
|
||||
required this.updatedAt,
|
||||
required this.providerId,
|
||||
required this.modelId,
|
||||
required this.timelineId,
|
||||
@JsonKey(required: true, disallowNullValue: true) required this.pending,
|
||||
@JsonKey(required: true, disallowNullValue: true)
|
||||
required List<int?> responseDurationsMs,
|
||||
}) : _responseDurationsMs = responseDurationsMs;
|
||||
factory _ConversationMetadata.fromJson(Map<String, dynamic> json) =>
|
||||
_$ConversationMetadataFromJson(json);
|
||||
|
||||
@override
|
||||
final String id;
|
||||
@override
|
||||
final String projectId;
|
||||
@override
|
||||
final String title;
|
||||
@override
|
||||
final DateTime createdAt;
|
||||
@override
|
||||
final DateTime updatedAt;
|
||||
@override
|
||||
final String providerId;
|
||||
@override
|
||||
final String modelId;
|
||||
@override
|
||||
final String timelineId;
|
||||
@override
|
||||
@JsonKey(required: true, disallowNullValue: true)
|
||||
final bool pending;
|
||||
final List<int?> _responseDurationsMs;
|
||||
@override
|
||||
@JsonKey(required: true, disallowNullValue: true)
|
||||
List<int?> get responseDurationsMs {
|
||||
if (_responseDurationsMs is EqualUnmodifiableListView)
|
||||
return _responseDurationsMs;
|
||||
// ignore: implicit_dynamic_type
|
||||
return EqualUnmodifiableListView(_responseDurationsMs);
|
||||
}
|
||||
|
||||
/// Create a copy of ConversationMetadata
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@override
|
||||
@JsonKey(includeFromJson: false, includeToJson: false)
|
||||
@pragma('vm:prefer-inline')
|
||||
_$ConversationMetadataCopyWith<_ConversationMetadata> get copyWith =>
|
||||
__$ConversationMetadataCopyWithImpl<_ConversationMetadata>(
|
||||
this,
|
||||
_$identity,
|
||||
);
|
||||
|
||||
@override
|
||||
Map<String, dynamic> toJson() {
|
||||
return _$ConversationMetadataToJson(this);
|
||||
}
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) {
|
||||
return identical(this, other) ||
|
||||
(other.runtimeType == runtimeType &&
|
||||
other is _ConversationMetadata &&
|
||||
(identical(other.id, id) || other.id == id) &&
|
||||
(identical(other.projectId, projectId) ||
|
||||
other.projectId == projectId) &&
|
||||
(identical(other.title, title) || other.title == title) &&
|
||||
(identical(other.createdAt, createdAt) ||
|
||||
other.createdAt == createdAt) &&
|
||||
(identical(other.updatedAt, updatedAt) ||
|
||||
other.updatedAt == updatedAt) &&
|
||||
(identical(other.providerId, providerId) ||
|
||||
other.providerId == providerId) &&
|
||||
(identical(other.modelId, modelId) || other.modelId == modelId) &&
|
||||
(identical(other.timelineId, timelineId) ||
|
||||
other.timelineId == timelineId) &&
|
||||
(identical(other.pending, pending) || other.pending == pending) &&
|
||||
const DeepCollectionEquality().equals(
|
||||
other.responseDurationsMs,
|
||||
_responseDurationsMs,
|
||||
));
|
||||
}
|
||||
|
||||
@JsonKey(includeFromJson: false, includeToJson: false)
|
||||
@override
|
||||
int get hashCode {
|
||||
return Object.hash(
|
||||
runtimeType,
|
||||
id,
|
||||
projectId,
|
||||
title,
|
||||
createdAt,
|
||||
updatedAt,
|
||||
providerId,
|
||||
modelId,
|
||||
timelineId,
|
||||
pending,
|
||||
const DeepCollectionEquality().hash(_responseDurationsMs),
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
return 'ConversationMetadata(id: $id, projectId: $projectId, title: $title, createdAt: $createdAt, updatedAt: $updatedAt, providerId: $providerId, modelId: $modelId, timelineId: $timelineId, pending: $pending, responseDurationsMs: $responseDurationsMs)';
|
||||
}
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
abstract mixin class _$ConversationMetadataCopyWith<$Res>
|
||||
implements $ConversationMetadataCopyWith<$Res> {
|
||||
factory _$ConversationMetadataCopyWith(
|
||||
_ConversationMetadata value,
|
||||
$Res Function(_ConversationMetadata) _then,
|
||||
) = __$ConversationMetadataCopyWithImpl;
|
||||
@override
|
||||
@useResult
|
||||
$Res call({
|
||||
String id,
|
||||
String projectId,
|
||||
String title,
|
||||
DateTime createdAt,
|
||||
DateTime updatedAt,
|
||||
String providerId,
|
||||
String modelId,
|
||||
String timelineId,
|
||||
@JsonKey(required: true, disallowNullValue: true) bool pending,
|
||||
@JsonKey(required: true, disallowNullValue: true)
|
||||
List<int?> responseDurationsMs,
|
||||
});
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
class __$ConversationMetadataCopyWithImpl<$Res>
|
||||
implements _$ConversationMetadataCopyWith<$Res> {
|
||||
__$ConversationMetadataCopyWithImpl(this._self, this._then);
|
||||
|
||||
final _ConversationMetadata _self;
|
||||
final $Res Function(_ConversationMetadata) _then;
|
||||
|
||||
/// Create a copy of ConversationMetadata
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@override
|
||||
@pragma('vm:prefer-inline')
|
||||
$Res call({
|
||||
Object? id = null,
|
||||
Object? projectId = null,
|
||||
Object? title = null,
|
||||
Object? createdAt = null,
|
||||
Object? updatedAt = null,
|
||||
Object? providerId = null,
|
||||
Object? modelId = null,
|
||||
Object? timelineId = null,
|
||||
Object? pending = null,
|
||||
Object? responseDurationsMs = null,
|
||||
}) {
|
||||
return _then(
|
||||
_ConversationMetadata(
|
||||
id: null == id
|
||||
? _self.id
|
||||
: id // ignore: cast_nullable_to_non_nullable
|
||||
as String,
|
||||
projectId: null == projectId
|
||||
? _self.projectId
|
||||
: projectId // ignore: cast_nullable_to_non_nullable
|
||||
as String,
|
||||
title: null == title
|
||||
? _self.title
|
||||
: title // ignore: cast_nullable_to_non_nullable
|
||||
as String,
|
||||
createdAt: null == createdAt
|
||||
? _self.createdAt
|
||||
: createdAt // ignore: cast_nullable_to_non_nullable
|
||||
as DateTime,
|
||||
updatedAt: null == updatedAt
|
||||
? _self.updatedAt
|
||||
: updatedAt // ignore: cast_nullable_to_non_nullable
|
||||
as DateTime,
|
||||
providerId: null == providerId
|
||||
? _self.providerId
|
||||
: providerId // ignore: cast_nullable_to_non_nullable
|
||||
as String,
|
||||
modelId: null == modelId
|
||||
? _self.modelId
|
||||
: modelId // ignore: cast_nullable_to_non_nullable
|
||||
as String,
|
||||
timelineId: null == timelineId
|
||||
? _self.timelineId
|
||||
: timelineId // ignore: cast_nullable_to_non_nullable
|
||||
as String,
|
||||
pending: null == pending
|
||||
? _self.pending
|
||||
: pending // ignore: cast_nullable_to_non_nullable
|
||||
as bool,
|
||||
responseDurationsMs: null == responseDurationsMs
|
||||
? _self._responseDurationsMs
|
||||
: responseDurationsMs // ignore: cast_nullable_to_non_nullable
|
||||
as List<int?>,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'conversation_repository.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// JsonSerializableGenerator
|
||||
// **************************************************************************
|
||||
|
||||
_ConversationMetadata _$ConversationMetadataFromJson(
|
||||
Map<String, dynamic> json,
|
||||
) {
|
||||
$checkKeys(
|
||||
json,
|
||||
requiredKeys: const ['pending', 'responseDurationsMs'],
|
||||
disallowNullValues: const ['pending', 'responseDurationsMs'],
|
||||
);
|
||||
return _ConversationMetadata(
|
||||
id: json['id'] as String,
|
||||
projectId: json['projectId'] as String,
|
||||
title: json['title'] as String,
|
||||
createdAt: DateTime.parse(json['createdAt'] as String),
|
||||
updatedAt: DateTime.parse(json['updatedAt'] as String),
|
||||
providerId: json['providerId'] as String,
|
||||
modelId: json['modelId'] as String,
|
||||
timelineId: json['timelineId'] as String,
|
||||
pending: json['pending'] as bool,
|
||||
responseDurationsMs: (json['responseDurationsMs'] as List<dynamic>)
|
||||
.map((e) => (e as num?)?.toInt())
|
||||
.toList(),
|
||||
);
|
||||
}
|
||||
|
||||
Map<String, dynamic> _$ConversationMetadataToJson(
|
||||
_ConversationMetadata instance,
|
||||
) => <String, dynamic>{
|
||||
'id': instance.id,
|
||||
'projectId': instance.projectId,
|
||||
'title': instance.title,
|
||||
'createdAt': instance.createdAt.toIso8601String(),
|
||||
'updatedAt': instance.updatedAt.toIso8601String(),
|
||||
'providerId': instance.providerId,
|
||||
'modelId': instance.modelId,
|
||||
'timelineId': instance.timelineId,
|
||||
'pending': instance.pending,
|
||||
'responseDurationsMs': instance.responseDurationsMs,
|
||||
};
|
||||
|
||||
// **************************************************************************
|
||||
// RiverpodGenerator
|
||||
// **************************************************************************
|
||||
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
// ignore_for_file: type=lint, type=warning
|
||||
|
||||
@ProviderFor(conversationLocation)
|
||||
final conversationLocationProvider = ConversationLocationProvider._();
|
||||
|
||||
final class ConversationLocationProvider
|
||||
extends
|
||||
$FunctionalProvider<
|
||||
ConversationLocation,
|
||||
ConversationLocation,
|
||||
ConversationLocation
|
||||
>
|
||||
with $Provider<ConversationLocation> {
|
||||
ConversationLocationProvider._()
|
||||
: super(
|
||||
from: null,
|
||||
argument: null,
|
||||
retry: null,
|
||||
name: r'conversationLocationProvider',
|
||||
isAutoDispose: false,
|
||||
dependencies: null,
|
||||
$allTransitiveDependencies: null,
|
||||
);
|
||||
|
||||
@override
|
||||
String debugGetCreateSourceHash() => _$conversationLocationHash();
|
||||
|
||||
@$internal
|
||||
@override
|
||||
$ProviderElement<ConversationLocation> $createElement(
|
||||
$ProviderPointer pointer,
|
||||
) => $ProviderElement(pointer);
|
||||
|
||||
@override
|
||||
ConversationLocation create(Ref ref) {
|
||||
return conversationLocation(ref);
|
||||
}
|
||||
|
||||
/// {@macro riverpod.override_with_value}
|
||||
Override overrideWithValue(ConversationLocation value) {
|
||||
return $ProviderOverride(
|
||||
origin: this,
|
||||
providerOverride: $SyncValueProvider<ConversationLocation>(value),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
String _$conversationLocationHash() =>
|
||||
r'f087694520af1c0f37a5311284768415a95b3811';
|
||||
|
||||
@ProviderFor(conversationRepository)
|
||||
final conversationRepositoryProvider = ConversationRepositoryProvider._();
|
||||
|
||||
final class ConversationRepositoryProvider
|
||||
extends
|
||||
$FunctionalProvider<
|
||||
AsyncValue<ConversationRepository>,
|
||||
ConversationRepository,
|
||||
FutureOr<ConversationRepository>
|
||||
>
|
||||
with
|
||||
$FutureModifier<ConversationRepository>,
|
||||
$FutureProvider<ConversationRepository> {
|
||||
ConversationRepositoryProvider._()
|
||||
: super(
|
||||
from: null,
|
||||
argument: null,
|
||||
retry: null,
|
||||
name: r'conversationRepositoryProvider',
|
||||
isAutoDispose: false,
|
||||
dependencies: null,
|
||||
$allTransitiveDependencies: null,
|
||||
);
|
||||
|
||||
@override
|
||||
String debugGetCreateSourceHash() => _$conversationRepositoryHash();
|
||||
|
||||
@$internal
|
||||
@override
|
||||
$FutureProviderElement<ConversationRepository> $createElement(
|
||||
$ProviderPointer pointer,
|
||||
) => $FutureProviderElement(pointer);
|
||||
|
||||
@override
|
||||
FutureOr<ConversationRepository> create(Ref ref) {
|
||||
return conversationRepository(ref);
|
||||
}
|
||||
}
|
||||
|
||||
String _$conversationRepositoryHash() =>
|
||||
r'674fa602f63c49495d4c9c6773dd98ebd0bf30b2';
|
||||
@@ -0,0 +1,448 @@
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:cutdex_sdk/editor.dart';
|
||||
import 'package:cutdex_agent/cutdex_agent.dart';
|
||||
|
||||
/// Deterministic, read-only acceptance for explicitly declared editor outcomes.
|
||||
/// Contracts live in successful tool results, so compaction and restart cannot
|
||||
/// erase or silently weaken them. Semantic quality is deliberately out of scope.
|
||||
class EditorAcceptance {
|
||||
EditorAcceptance(Iterable<AgentTool> tools)
|
||||
: _tools = {for (final tool in tools) tool.name: tool};
|
||||
|
||||
final Map<String, AgentTool> _tools;
|
||||
static const _registration = {
|
||||
'editor_expect_clips',
|
||||
'editor_expect_translation',
|
||||
'timeline_planBeatCuts',
|
||||
};
|
||||
static const _coveredWrites = {'clip_setAudio', 'caption_addTranslations'};
|
||||
|
||||
List<AgentTool> get tools => [
|
||||
AgentTool(
|
||||
name: 'editor_expect_clips',
|
||||
description: 'Before changing clips, declare expected final names and static parameter default values. Captures exact clip count, ordering, timing and connections to preserve. Every declared clip is checked from CURRENT project state before completion. Register all requested targets, not only those already edited. Re-registering cannot weaken an earlier contract in the same user task. Animated keyframe values are not checked by this tool.',
|
||||
parameters: {
|
||||
'type': 'object',
|
||||
'properties': {
|
||||
'workspaceId': {'type': 'string'},
|
||||
'preserveLayout': {
|
||||
'type': 'boolean',
|
||||
'description': 'Default true; false only when the user also requests layout or timing changes.',
|
||||
},
|
||||
'clips': {
|
||||
'type': 'array',
|
||||
'minItems': 1,
|
||||
'maxItems': 200,
|
||||
'items': {
|
||||
'type': 'object',
|
||||
'additionalProperties': false,
|
||||
'properties': {
|
||||
'clipId': {'type': 'string'},
|
||||
'name': {'type': 'string'},
|
||||
'parameters': {
|
||||
'type': 'array',
|
||||
'maxItems': 32,
|
||||
'items': {
|
||||
'type': 'object',
|
||||
'additionalProperties': false,
|
||||
'properties': {
|
||||
'parameterId': {'type': 'string'},
|
||||
'value': {'type': 'number'},
|
||||
},
|
||||
'required': ['parameterId', 'value'],
|
||||
},
|
||||
},
|
||||
},
|
||||
'required': ['clipId'],
|
||||
},
|
||||
},
|
||||
},
|
||||
'required': ['workspaceId', 'clips'],
|
||||
'additionalProperties': false,
|
||||
},
|
||||
validate: _validateClips,
|
||||
execute: (call, context) async {
|
||||
final args = call.arguments;
|
||||
final view = await _read('timeline_query', {
|
||||
'workspaceId': args['workspaceId'],
|
||||
'includeParameters': false,
|
||||
}, context);
|
||||
final ids = (view.data['clips'] as List)
|
||||
.map((c) => (c as Map)['clipId'])
|
||||
.toSet();
|
||||
final contracts = <Object?>[];
|
||||
for (final row in args['clips'] as List) {
|
||||
if (!ids.contains(row['clipId'])) {
|
||||
return ToolResult('Unknown clipId ${row['clipId']}', isError: true);
|
||||
}
|
||||
contracts.add({
|
||||
'kind': 'clip',
|
||||
'workspaceId': args['workspaceId'],
|
||||
'expected': row,
|
||||
if (args['preserveLayout'] != false)
|
||||
'layoutHash': editorEvidenceHash(editorLayout(view.data)),
|
||||
});
|
||||
}
|
||||
return ToolResult(
|
||||
'Registered deterministic clip outcomes; semantic quality is not certified',
|
||||
data: {'contracts': contracts, 'version': view.version},
|
||||
);
|
||||
},
|
||||
// A started registration with no durable result must not recapture a new
|
||||
// baseline after concurrent edits. The normal unknown-outcome path applies.
|
||||
),
|
||||
AgentTool(
|
||||
name: 'editor_expect_translation',
|
||||
description: 'After creating the new target track and BEFORE writing translations, register sourceRoleId and targetRoleId. Reads all source pages at one version. Completion checks source unchanged, track identities/count unchanged, target cue count and timing multiset equal source, unique target IDs and nonempty text. This does NOT certify translation meaning or fluency; semantic concerns are review suggestions, never automatic rewrite instructions.',
|
||||
parameters: {
|
||||
'type': 'object',
|
||||
'additionalProperties': false,
|
||||
'properties': {
|
||||
for (final key in ['workspaceId', 'sourceRoleId', 'targetRoleId'])
|
||||
key: {'type': 'string'},
|
||||
},
|
||||
'required': ['workspaceId', 'sourceRoleId', 'targetRoleId'],
|
||||
},
|
||||
validate: (a) =>
|
||||
[
|
||||
'workspaceId',
|
||||
'sourceRoleId',
|
||||
'targetRoleId',
|
||||
].any((k) => a[k] is! String || (a[k] as String).isEmpty) ||
|
||||
a['sourceRoleId'] == a['targetRoleId']
|
||||
? 'Supply distinct source and target tracks and a workspace'
|
||||
: null,
|
||||
execute: (call, context) async {
|
||||
final a = call.arguments;
|
||||
final tracks = await _read('caption_list', {
|
||||
'workspaceId': a['workspaceId'],
|
||||
}, context);
|
||||
final ids = editorTrackIds(tracks.data);
|
||||
if (!ids.contains(a['sourceRoleId']) ||
|
||||
!ids.contains(a['targetRoleId'])) {
|
||||
return ToolResult(
|
||||
'Source or target track does not exist',
|
||||
isError: true,
|
||||
);
|
||||
}
|
||||
final source = await _cues(
|
||||
a['workspaceId'] as String,
|
||||
a['sourceRoleId'] as String,
|
||||
context,
|
||||
tracks.version,
|
||||
);
|
||||
return ToolResult(
|
||||
'Registered translation structure; semantic quality remains unverified',
|
||||
data: {
|
||||
'contracts': [
|
||||
{
|
||||
'kind': 'translation',
|
||||
...a,
|
||||
'trackIds': ids,
|
||||
'sourceHash': editorEvidenceHash(source),
|
||||
'sourceCount': source.length,
|
||||
},
|
||||
],
|
||||
'version': tracks.version,
|
||||
},
|
||||
);
|
||||
},
|
||||
),
|
||||
];
|
||||
|
||||
String? _validateClips(Map<String, Object?> a) {
|
||||
if (a['workspaceId'] is! String ||
|
||||
(a['workspaceId'] as String).isEmpty ||
|
||||
a['clips'] is! List ||
|
||||
(a['clips'] as List).isEmpty ||
|
||||
(a['clips'] as List).length > 200 ||
|
||||
(a['preserveLayout'] != null && a['preserveLayout'] is! bool)) {
|
||||
return 'Invalid clip expectations';
|
||||
}
|
||||
final ids = <String>{};
|
||||
for (final row in a['clips'] as List) {
|
||||
if (row is! Map ||
|
||||
row['clipId'] is! String ||
|
||||
!ids.add(row['clipId'] as String) ||
|
||||
(row['name'] != null && row['name'] is! String)) {
|
||||
return 'Supply unique clip IDs and valid names';
|
||||
}
|
||||
final parameters = row['parameters'];
|
||||
if (parameters != null && parameters is! List) {
|
||||
return 'parameters must be an array';
|
||||
}
|
||||
if (row['name'] == null &&
|
||||
(parameters == null || (parameters as List).isEmpty)) {
|
||||
return 'Declare a name or parameter value';
|
||||
}
|
||||
final params = <String>{};
|
||||
for (final p in parameters as List? ?? const []) {
|
||||
if (p is! Map ||
|
||||
p['parameterId'] is! String ||
|
||||
!params.add(p['parameterId'] as String) ||
|
||||
p['value'] is! num ||
|
||||
!(p['value'] as num).isFinite) {
|
||||
return 'Supply unique parameter IDs and finite values';
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
Future<ToolResult> check(
|
||||
SessionSnapshot snapshot,
|
||||
CancellationToken token,
|
||||
) async {
|
||||
final calls = <String, ToolCall>{};
|
||||
final contracts = <String, Map<String, Object?>>{};
|
||||
final issues = <Map<String, Object?>>[];
|
||||
final writes = <ToolCall>[];
|
||||
for (final message in snapshot.history.skip(snapshot.runStart)) {
|
||||
for (final call in message.calls) {
|
||||
calls[call.id] = call;
|
||||
}
|
||||
if (message.role != MessageRole.tool || message.isError) continue;
|
||||
final call = calls[message.callId];
|
||||
if (call == null) continue;
|
||||
if (_coveredWrites.contains(call.name)) writes.add(call);
|
||||
if (!_registration.contains(call.name)) continue;
|
||||
final result = jsonDecode(message.text) as Map;
|
||||
final payload = result['data'] as Map;
|
||||
final List<dynamic> registrations;
|
||||
if (call.name == 'timeline_planBeatCuts') {
|
||||
final plan = payload['data'] as Map;
|
||||
if (plan['requireCuts'] != true) continue;
|
||||
registrations = [
|
||||
{
|
||||
...(plan['contract'] as Map),
|
||||
'workspaceId': call.arguments['workspaceId'],
|
||||
},
|
||||
];
|
||||
} else {
|
||||
registrations = payload['contracts'] as List;
|
||||
}
|
||||
for (final raw in registrations) {
|
||||
final c = (raw as Map).cast<String, Object?>();
|
||||
final key =
|
||||
'${c['workspaceId']}:${c['kind']}:${c['kind'] == 'clip' ? (c['expected'] as Map)['clipId'] : c['targetRoleId']}';
|
||||
if (contracts.containsKey(key) &&
|
||||
editorEvidenceHash(contracts[key]) != editorEvidenceHash(c)) {
|
||||
issues.add({
|
||||
'kind': 'contractChanged',
|
||||
'target': key,
|
||||
'reason': 'Earlier acceptance criteria cannot be replaced within this task.',
|
||||
});
|
||||
} else {
|
||||
contracts[key] = c;
|
||||
}
|
||||
}
|
||||
}
|
||||
// Never infer a complete user goal from writes alone. Require explicit
|
||||
// expectations for supported editing operations and disclose coverage.
|
||||
for (final call in writes) {
|
||||
final workspace = call.arguments['workspaceId'];
|
||||
final covered = contracts.values.any((c) {
|
||||
if (c['workspaceId'] != workspace) return false;
|
||||
if (call.name == 'clip_setAudio') {
|
||||
if (c['kind'] != 'clip') return false;
|
||||
final expected = c['expected'] as Map;
|
||||
if (expected['clipId'] != call.arguments['clipId']) return false;
|
||||
final parameters = (expected['parameters'] as List? ?? const [])
|
||||
.map((p) => (p as Map)['parameterId'])
|
||||
.toSet();
|
||||
return (!call.arguments.containsKey('db') ||
|
||||
parameters.contains('cutdex.audio.gainDb')) &&
|
||||
(!call.arguments.containsKey('muted') ||
|
||||
parameters.contains('cutdex.audio.mute'));
|
||||
}
|
||||
return c['kind'] == 'translation' &&
|
||||
c['targetRoleId'] == call.arguments['roleId'];
|
||||
});
|
||||
if (!covered) {
|
||||
issues.add({
|
||||
'kind': 'missingExpectation',
|
||||
'tool': call.name,
|
||||
'arguments': call.arguments,
|
||||
'reason': 'Declare the original requested outcomes with editor_expect_clips or editor_expect_translation. Include every requested target, not just successful writes.',
|
||||
});
|
||||
}
|
||||
}
|
||||
if (issues.isNotEmpty) {
|
||||
return ToolResult(
|
||||
'Acceptance requirements are unresolved',
|
||||
isError: true,
|
||||
data: {'issues': issues},
|
||||
);
|
||||
}
|
||||
final context = ToolContext(
|
||||
sessionId: snapshot.id,
|
||||
runId: snapshot.runId!,
|
||||
operationId:
|
||||
'verification:${snapshot.id}:${snapshot.runId}:${snapshot.turns}',
|
||||
cancellation: token,
|
||||
onProgress: (_) {},
|
||||
);
|
||||
final versions = <String, String>{};
|
||||
final views = <String, _View>{};
|
||||
try {
|
||||
for (final c in contracts.values) {
|
||||
token.throwIfCancelled();
|
||||
final workspace = c['workspaceId'] as String;
|
||||
final view = views[workspace] ??= await _read('timeline_query', {
|
||||
'workspaceId': workspace,
|
||||
}, context);
|
||||
versions[workspace] = view.version;
|
||||
if (view.data['saveState'] != 'saved') {
|
||||
issues.add({
|
||||
'kind': 'saveState',
|
||||
'workspaceId': workspace,
|
||||
'actual': view.data['saveState'],
|
||||
'expected': 'saved',
|
||||
'action': 'Use project_save, then recheck.',
|
||||
});
|
||||
}
|
||||
Map<String, Object?>? tracks;
|
||||
List<Map<String, Object?>> source = const [], target = const [];
|
||||
final expectation = EditorExpectation.fromJson(c);
|
||||
if (expectation.needsCaptions) {
|
||||
final page = await _read('caption_list', {
|
||||
'workspaceId': workspace,
|
||||
}, context);
|
||||
_sameVersion(page.version, view.version);
|
||||
tracks = page.data;
|
||||
source = await _cues(
|
||||
workspace,
|
||||
c['sourceRoleId'] as String,
|
||||
context,
|
||||
view.version,
|
||||
);
|
||||
target = await _cues(
|
||||
workspace,
|
||||
c['targetRoleId'] as String,
|
||||
context,
|
||||
view.version,
|
||||
);
|
||||
}
|
||||
issues.addAll(
|
||||
verifyEditorOutcome(
|
||||
expectation,
|
||||
EditorOutcomeEvidence(
|
||||
timeline: view.data,
|
||||
tracks: tracks,
|
||||
sourceCues: source,
|
||||
targetCues: target,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
// No receipt is reused as current evidence. Catch edits during multi-page
|
||||
// reads as well as changes between workspaces while verification runs.
|
||||
for (final entry in versions.entries) {
|
||||
final current = await _read('timeline_query', {
|
||||
'workspaceId': entry.key,
|
||||
'includeParameters': false,
|
||||
}, context);
|
||||
_sameVersion(current.version, entry.value);
|
||||
}
|
||||
} on AgentCancelled {
|
||||
rethrow;
|
||||
} catch (_) {
|
||||
return ToolResult(
|
||||
'Current project evidence unavailable or changed during verification; query current state and retry. No acceptance granted.',
|
||||
isError: true,
|
||||
data: {
|
||||
'issues': [
|
||||
...issues,
|
||||
{'kind': 'unavailableEvidence'},
|
||||
],
|
||||
},
|
||||
);
|
||||
}
|
||||
return ToolResult(
|
||||
issues.isEmpty
|
||||
? 'Declared deterministic outcomes verified from current project state; semantic quality is not certified.'
|
||||
: 'Current project differs from the requested outcomes. Repair these specific differences and recheck.',
|
||||
isError: issues.isNotEmpty,
|
||||
data: {
|
||||
'scope': 'declaredDeterministicOutcomes',
|
||||
'semanticQuality': 'unverified',
|
||||
'contracts': contracts.length,
|
||||
'versions': versions,
|
||||
'issues': issues,
|
||||
'artifactHashes': {
|
||||
for (final e in views.entries)
|
||||
e.key: editorEvidenceHash(e.value.data),
|
||||
},
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
Future<_View> _read(
|
||||
String name,
|
||||
Map<String, Object?> arguments,
|
||||
ToolContext context,
|
||||
) async {
|
||||
context.cancellation.throwIfCancelled();
|
||||
final tool = _tools[name];
|
||||
if (tool == null || tool.validate(arguments) != null) {
|
||||
throw StateError('Query unavailable');
|
||||
}
|
||||
final result = await tool.execute(
|
||||
ToolCall(id: context.operationId, name: name, arguments: arguments),
|
||||
context,
|
||||
);
|
||||
context.cancellation.throwIfCancelled();
|
||||
final version = result.data['version'];
|
||||
final data = result.data['data'];
|
||||
if (result.isError || version is! String || data is! Map) {
|
||||
throw StateError('Invalid current state');
|
||||
}
|
||||
return _View(data.cast<String, Object?>(), version);
|
||||
}
|
||||
|
||||
Future<List<Map<String, Object?>>> _cues(
|
||||
String workspace,
|
||||
String role,
|
||||
ToolContext context,
|
||||
String version,
|
||||
) async {
|
||||
final cues = <Map<String, Object?>>[];
|
||||
var offset = 0;
|
||||
while (true) {
|
||||
final page = await _read('caption_list', {
|
||||
'workspaceId': workspace,
|
||||
'roleId': role,
|
||||
'offset': offset,
|
||||
'limit': 100,
|
||||
}, context);
|
||||
_sameVersion(page.version, version);
|
||||
final rows = (page.data['cues'] as List)
|
||||
.map((e) => (e as Map).cast<String, Object?>())
|
||||
.toList();
|
||||
cues.addAll(rows);
|
||||
if (cues.length > 20000) throw StateError('Caption verification limit');
|
||||
final next = page.data['nextOffset'];
|
||||
if (next == null) {
|
||||
if (cues.length != page.data['total']) {
|
||||
throw StateError('Incomplete caption read');
|
||||
}
|
||||
return cues;
|
||||
}
|
||||
if (next is! int || next <= offset || rows.isEmpty) {
|
||||
throw StateError('Invalid cursor');
|
||||
}
|
||||
offset = next;
|
||||
}
|
||||
}
|
||||
|
||||
static void _sameVersion(String a, String b) {
|
||||
if (a != b) throw StateError('State changed during verification');
|
||||
}
|
||||
}
|
||||
|
||||
class _View {
|
||||
const _View(this.data, this.version);
|
||||
final Map<String, Object?> data;
|
||||
final String version;
|
||||
}
|
||||
@@ -0,0 +1,216 @@
|
||||
import 'package:cutdex_sdk/editor.dart';
|
||||
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:cutdex_agent/cutdex_agent.dart';
|
||||
import 'package:cutdex_sdk/tools.dart';
|
||||
|
||||
/// Protocol adaptation only. The dispatchers belong to the open project.
|
||||
List<AgentTool> editorAgentTools(
|
||||
Map<String, EditorToolDispatcher> workspaces, {
|
||||
bool dynamicWorkspaces = false,
|
||||
Future<void> Function(ToolContext)? beforeInvoke,
|
||||
Future<void> Function(ToolCall, ToolContext, CommandResult)? afterInvoke,
|
||||
}) {
|
||||
ToolResult result(CommandResult value) {
|
||||
final data = value.toJson();
|
||||
final payload = data['data'];
|
||||
if (payload is Map<String, Object?>) {
|
||||
data['data'] = {
|
||||
...payload,
|
||||
if (payload['clips'] is List)
|
||||
'clips': (payload['clips']! as List).map(_compactClip).toList(),
|
||||
// Full schemas are loaded on demand through runtime tool discovery.
|
||||
if (payload['tools'] is List)
|
||||
'tools': [
|
||||
for (final tool in payload['tools']! as List)
|
||||
if (tool is Map<String, Object?>)
|
||||
{'name': tool['name'], 'readOnly': tool['readOnly']}
|
||||
else
|
||||
tool,
|
||||
],
|
||||
};
|
||||
}
|
||||
return ToolResult(value.message, isError: value.isError, data: data);
|
||||
}
|
||||
|
||||
(EditorToolDispatcher, Map<String, Object?>) resolve(
|
||||
Map<String, Object?> args,
|
||||
) {
|
||||
final dispatcher = workspaces[args['workspaceId']];
|
||||
if (dispatcher == null) {
|
||||
throw CommandRejected(
|
||||
'missingWorkspace',
|
||||
'Unknown workspaceId. Copy an exact ID from ${jsonEncode(workspaces.keys.toList())}. '
|
||||
'Call cutdex_workspaces for supported tools.',
|
||||
);
|
||||
}
|
||||
return (dispatcher, {...args}..remove('workspaceId'));
|
||||
}
|
||||
|
||||
String operation(ToolContext context) =>
|
||||
jsonEncode(['agent', context.operationId]);
|
||||
final definitions = {
|
||||
if (dynamicWorkspaces)
|
||||
for (final definition in editorToolDefinitions)
|
||||
definition.name: definition,
|
||||
for (final tools in workspaces.values)
|
||||
for (final definition in tools.definitions) definition.name: definition,
|
||||
};
|
||||
Future<ToolResult> listWorkspaces(ToolContext context) async {
|
||||
await beforeInvoke?.call(context);
|
||||
final toolSets = <String, List<String>>{};
|
||||
final ids = <String, String>{};
|
||||
final targets = <Map<String, Object?>>[];
|
||||
for (final entry in workspaces.entries) {
|
||||
final names = [
|
||||
for (final tool in entry.value.definitions)
|
||||
tool.name.replaceAll('.', '_'),
|
||||
]..sort();
|
||||
final key = jsonEncode(names);
|
||||
final id = ids.putIfAbsent(key, () => 'tools${ids.length}');
|
||||
toolSets[id] = names;
|
||||
targets.add({'workspaceId': entry.key, 'toolSetId': id});
|
||||
}
|
||||
return ToolResult(jsonEncode({'targets': targets, 'toolSets': toolSets}));
|
||||
}
|
||||
|
||||
return [
|
||||
AgentTool(
|
||||
name: 'cutdex_workspaces',
|
||||
description: 'List workspace IDs and their supported tools. application manages projects; use a timeline workspace for timeline queries and clip edits. Every call requires an explicit workspaceId from this list.',
|
||||
parameters: const {
|
||||
'type': 'object',
|
||||
'properties': <String, Object?>{},
|
||||
'additionalProperties': false,
|
||||
},
|
||||
validate: (args) => args.isEmpty ? null : 'No arguments expected',
|
||||
execute: (_, context) => listWorkspaces(context),
|
||||
// Discovery is read-only: obtain fresh data after an interrupted call.
|
||||
recover: (_, context) async =>
|
||||
ToolRecovery.completed(await listWorkspaces(context)),
|
||||
),
|
||||
for (final definition in definitions.values)
|
||||
AgentTool(
|
||||
name: definition.name.replaceAll('.', '_'),
|
||||
description: definition.description,
|
||||
parameters: {
|
||||
...definition.inputSchema,
|
||||
'properties': {
|
||||
...definition.inputSchema['properties']! as Map<String, Object?>,
|
||||
'workspaceId': {'type': 'string'},
|
||||
},
|
||||
'required': [
|
||||
...definition.inputSchema['required']! as List,
|
||||
'workspaceId',
|
||||
],
|
||||
},
|
||||
validate: (args) {
|
||||
try {
|
||||
final (dispatcher, arguments) = resolve(args);
|
||||
if (!dispatcher.definitions.any(
|
||||
(tool) => tool.name == definition.name,
|
||||
)) {
|
||||
final available = [
|
||||
for (final entry in workspaces.entries)
|
||||
if (entry.value.definitions.any(
|
||||
(tool) => tool.name == definition.name,
|
||||
))
|
||||
entry.key,
|
||||
];
|
||||
return 'This workspace does not support ${definition.name}. '
|
||||
'Use a workspaceId from ${jsonEncode(available)}. '
|
||||
'Call cutdex_workspaces to inspect workspace tools.';
|
||||
}
|
||||
decodeEditorCommand(definition.name, arguments);
|
||||
return null;
|
||||
} on CommandRejected catch (error) {
|
||||
return error.message;
|
||||
} catch (_) {
|
||||
return 'Invalid arguments';
|
||||
}
|
||||
},
|
||||
execute: (call, context) async {
|
||||
await beforeInvoke?.call(context);
|
||||
final (dispatcher, arguments) = resolve(call.arguments);
|
||||
final value = await dispatcher.invoke(
|
||||
name: definition.name,
|
||||
arguments: arguments,
|
||||
context: CommandContext(
|
||||
operationId: operation(context),
|
||||
isCancelled: () => context.cancellation.isCancelled,
|
||||
),
|
||||
);
|
||||
if (value.status == CommandStatus.unknown) {
|
||||
throw StateError(
|
||||
'Reconcile the original operation before retrying',
|
||||
);
|
||||
}
|
||||
if (!value.isError) await afterInvoke?.call(call, context, value);
|
||||
return result(value);
|
||||
},
|
||||
recover: (call, context) async {
|
||||
await beforeInvoke?.call(context);
|
||||
final (dispatcher, arguments) = resolve(call.arguments);
|
||||
if (definition.readOnly) {
|
||||
// Read-only dispatches deliberately have no operation receipt.
|
||||
// Re-query current state; never apply this rule to edits.
|
||||
final value = await dispatcher.invoke(
|
||||
name: definition.name,
|
||||
arguments: arguments,
|
||||
context: CommandContext(
|
||||
operationId: operation(context),
|
||||
isCancelled: () => context.cancellation.isCancelled,
|
||||
),
|
||||
);
|
||||
return value.status == CommandStatus.unknown
|
||||
? const ToolRecovery.unknown()
|
||||
: ToolRecovery.completed(result(value));
|
||||
}
|
||||
final OperationReceipt receipt;
|
||||
try {
|
||||
receipt = await dispatcher.recoverInvocation(
|
||||
operationId: operation(context),
|
||||
name: definition.name,
|
||||
arguments: arguments,
|
||||
);
|
||||
} on CommandRejected {
|
||||
return const ToolRecovery.unknown();
|
||||
}
|
||||
return switch (receipt.state) {
|
||||
OperationState.notStarted => const ToolRecovery.notStarted(),
|
||||
OperationState.running => const ToolRecovery.running(),
|
||||
OperationState.completed
|
||||
when receipt.result!.status != CommandStatus.unknown =>
|
||||
ToolRecovery.completed(result(receipt.result!)),
|
||||
_ => const ToolRecovery.unknown(),
|
||||
};
|
||||
},
|
||||
),
|
||||
];
|
||||
}
|
||||
|
||||
// Keep authored values and keys intact; omit repetitive empty/default metadata
|
||||
// only in the Agent projection. MCP and the authoritative command result retain
|
||||
// the full parameter definitions.
|
||||
Object? _compactClip(Object? value) {
|
||||
if (value is! Map<String, Object?> || value['parameters'] is! List) {
|
||||
return value;
|
||||
}
|
||||
return {
|
||||
...value,
|
||||
'parameters': [
|
||||
for (final parameter in value['parameters']! as List)
|
||||
if (parameter is Map<String, Object?>)
|
||||
Map<String, Object?>.from(parameter)..removeWhere(
|
||||
(key, value) =>
|
||||
(key == 'unit' && value == '') ||
|
||||
(key == 'keyframes' && value is List && value.isEmpty) ||
|
||||
(key == 'minimum' && value == -1000000) ||
|
||||
(key == 'maximum' && value == 1000000),
|
||||
)
|
||||
else
|
||||
parameter,
|
||||
],
|
||||
};
|
||||
}
|
||||
Reference in new issue
Block a user