Files
cutdex/lib/integrations/agent/editor_agent_tools.dart
T
lingjhf 38ca180cf7
Gitea CI / Check code and tests (pull_request) Failing after 8s
Gitea CI / Build Android APK (pull_request) Skipped
Gitea CI / Build Windows x64 app (pull_request) Skipped
Gitea CI / Audit and package Windows x64 (pull_request) Skipped
Gitea CI / Assemble and validate CI artifacts (pull_request) Skipped
Gitea CI / Gitea CI passed (pull_request) Failing after 1s
refactor(core): own editor UI and pin verified native releases
2026-10-12 03:20:29 +08:00

217 lines
8.0 KiB
Dart

import 'package:cutdex_core/editor.dart';
import 'dart:convert';
import 'package:cutdex_agent/cutdex_agent.dart';
import 'package:cutdex_core/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,
],
};
}