@morshoto/framekit 0.1.10 → 0.1.12
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -0
- package/dist-package/adapters/final-cut/typescript/src/analyzers.js +68 -5
- package/dist-package/adapters/final-cut/typescript/src/background-materialization.js +175 -0
- package/dist-package/adapters/final-cut/typescript/src/canonical-recovery.js +31 -0
- package/dist-package/adapters/final-cut/typescript/src/canonical-verification.js +16 -0
- package/dist-package/adapters/final-cut/typescript/src/canonical.js +600 -56
- package/dist-package/adapters/final-cut/typescript/src/connection.js +52 -14
- package/dist-package/adapters/final-cut/typescript/src/fcpxml-console-experiment.js +74 -0
- package/dist-package/adapters/final-cut/typescript/src/index.js +9 -0
- package/dist-package/adapters/final-cut/typescript/src/live.js +11 -4
- package/dist-package/adapters/final-cut/typescript/src/native.js +321 -19
- package/dist-package/adapters/final-cut/typescript/src/session.js +19 -1
- package/dist-package/adapters/final-cut/typescript/src/shadow-mutation.js +174 -0
- package/dist-package/adapters/final-cut/typescript/src/sqlite-experiment.js +472 -0
- package/dist-package/adapters/final-cut/typescript/src/sqlite-inspection.js +433 -0
- package/dist-package/adapters/final-cut/typescript/src/sqlite-materialization.js +230 -0
- package/dist-package/adapters/final-cut/typescript/src/timeline-ir-fcpxml.js +372 -0
- package/dist-package/adapters/final-cut/typescript/src/unattended-editing.js +66 -0
- package/dist-package/apps/mcp-server/src/headless-sessions.js +112 -0
- package/dist-package/apps/mcp-server/src/main.js +36 -2
- package/dist-package/apps/mcp-server/src/materialization-jobs.js +326 -0
- package/dist-package/apps/mcp-server/src/routing.js +17 -0
- package/dist-package/apps/mcp-server/src/server.js +146 -12
- package/dist-package/packages/runtime/src/application/media-analysis-service.js +52 -6
- package/dist-package/packages/runtime/src/context/project-catalog.js +46 -1
- package/dist-package/packages/runtime/src/index.js +2 -0
- package/dist-package/packages/runtime/src/skills/builtin.js +99 -8
- package/dist-package/packages/runtime/src/skills/runtime.js +1 -0
- package/dist-package/packages/runtime/src/timeline/drift-reconciliation.js +295 -0
- package/dist-package/packages/runtime/src/timeline/editing-session.js +490 -0
- package/package.json +10 -6
|
@@ -0,0 +1,372 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { isAbsolute } from "node:path";
|
|
3
|
+
import { pathToFileURL } from "node:url";
|
|
4
|
+
import { timelineIrDigest, validateTimelineIr } from "../../../../packages/runtime/src/index.js";
|
|
5
|
+
export const FRAMEKIT_FCPXML_VERSION = "1.11";
|
|
6
|
+
/**
|
|
7
|
+
* Compiles a complete provider-neutral Timeline IR into a new FCPXML
|
|
8
|
+
* document. The target binding is mandatory because names are not stable
|
|
9
|
+
* enough to identify a Final Cut destination.
|
|
10
|
+
*/
|
|
11
|
+
export function compileTimelineIrToFcpxml(timeline, options) {
|
|
12
|
+
validateTimelineIr(timeline);
|
|
13
|
+
const version = options.version ?? FRAMEKIT_FCPXML_VERSION;
|
|
14
|
+
if (version !== FRAMEKIT_FCPXML_VERSION) {
|
|
15
|
+
throw new Error(`FCPXML_VERSION_UNSUPPORTED: ${String(version)}`);
|
|
16
|
+
}
|
|
17
|
+
validateTarget(options.target);
|
|
18
|
+
const destination = resolveDestination(timeline, options.target);
|
|
19
|
+
const resourceIds = createResourceIds(timeline);
|
|
20
|
+
const resourceNames = uniqueResourceNames(timeline);
|
|
21
|
+
const resources = [...timeline.resources].sort((left, right) => left.id.localeCompare(right.id));
|
|
22
|
+
const elements = renderableElements(timeline, resourceIds);
|
|
23
|
+
const elementIds = new Set();
|
|
24
|
+
for (const element of elements) {
|
|
25
|
+
if (elementIds.has(element.id))
|
|
26
|
+
throw new Error(`FCPXML_DUPLICATE_ELEMENT_ID: ${element.id}`);
|
|
27
|
+
elementIds.add(element.id);
|
|
28
|
+
}
|
|
29
|
+
for (const item of [...timeline.sequence.markers, ...timeline.sequence.captions]) {
|
|
30
|
+
if (elementIds.has(item.id))
|
|
31
|
+
throw new Error(`FCPXML_DUPLICATE_ELEMENT_ID: ${item.id}`);
|
|
32
|
+
elementIds.add(item.id);
|
|
33
|
+
}
|
|
34
|
+
const formatId = "format-framekit";
|
|
35
|
+
const lines = [
|
|
36
|
+
'<?xml version="1.0" encoding="UTF-8"?>',
|
|
37
|
+
`<fcpxml version="${FRAMEKIT_FCPXML_VERSION}">`,
|
|
38
|
+
" <resources>",
|
|
39
|
+
` <format id="${formatId}" frameDuration="${formatRational(timeline.sequence.frameDuration, "sequence.frameDuration")}" />`,
|
|
40
|
+
...resources.map((resource) => renderResource(resource, resourceIds.get(resource.id), resourceNames.get(resource.id))),
|
|
41
|
+
" </resources>",
|
|
42
|
+
" <library>",
|
|
43
|
+
` <event uid="${xmlEscape(options.target.eventUid)}" name="${xmlEscape(options.target.eventName ?? "Framekit Event")}">`,
|
|
44
|
+
` <project uid="${xmlEscape(destination.projectUid)}" name="${xmlEscape(destination.projectName)}">`,
|
|
45
|
+
` <sequence uid="${xmlEscape(destination.sequenceUid)}" name="${xmlEscape(destination.sequenceName)}" format="${formatId}" duration="${formatRational(timeline.sequence.durationTime, "sequence.durationTime")}">`,
|
|
46
|
+
" <spine>",
|
|
47
|
+
...renderElements(elements),
|
|
48
|
+
...timeline.sequence.markers
|
|
49
|
+
.slice()
|
|
50
|
+
.sort(compareTimedItems)
|
|
51
|
+
.map((marker) => ` <marker id="${xmlEscape(marker.id)}" start="${formatRational(marker.startTime, `marker ${marker.id}.startTime`)}" duration="${formatRational(marker.durationTime, `marker ${marker.id}.durationTime`)}" value="${xmlEscape(marker.name)}" />`),
|
|
52
|
+
...timeline.sequence.captions
|
|
53
|
+
.slice()
|
|
54
|
+
.sort(compareTimedItems)
|
|
55
|
+
.map((caption) => ` <caption id="${xmlEscape(caption.id)}" start="${formatRational(caption.startTime, `caption ${caption.id}.startTime`)}" duration="${formatRational(caption.durationTime, `caption ${caption.id}.durationTime`)}" text="${xmlEscape(caption.text)}" />`),
|
|
56
|
+
" </spine>",
|
|
57
|
+
" </sequence>",
|
|
58
|
+
" </project>",
|
|
59
|
+
" </event>",
|
|
60
|
+
" </library>",
|
|
61
|
+
"</fcpxml>",
|
|
62
|
+
"",
|
|
63
|
+
];
|
|
64
|
+
const xml = lines.join("\n");
|
|
65
|
+
return {
|
|
66
|
+
format: "fcpxml",
|
|
67
|
+
version: FRAMEKIT_FCPXML_VERSION,
|
|
68
|
+
xml,
|
|
69
|
+
digest: createHash("sha256").update(xml).digest("hex"),
|
|
70
|
+
target: structuredClone(options.target),
|
|
71
|
+
destination,
|
|
72
|
+
resourceIds: Object.fromEntries([...resourceIds.entries()].sort(([left], [right]) => left.localeCompare(right))),
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
function validateTarget(target) {
|
|
76
|
+
if (!target || target.provider !== "final-cut")
|
|
77
|
+
throw new Error("FCPXML_TARGET_BINDING_INVALID: provider must be final-cut");
|
|
78
|
+
requireText(target.libraryUid, "libraryUid");
|
|
79
|
+
requireText(target.eventUid, "eventUid");
|
|
80
|
+
requireText(target.projectUid, "projectUid");
|
|
81
|
+
requireText(target.sequenceUid, "sequenceUid");
|
|
82
|
+
if (target.eventName !== undefined)
|
|
83
|
+
requireText(target.eventName, "eventName");
|
|
84
|
+
if (target.materialization !== undefined && !["versioned", "reuse-existing"].includes(target.materialization)) {
|
|
85
|
+
throw new Error(`FCPXML_TARGET_BINDING_INVALID: unsupported materialization ${target.materialization}`);
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
function resolveDestination(timeline, target) {
|
|
89
|
+
if (target.materialization === "reuse-existing") {
|
|
90
|
+
return {
|
|
91
|
+
mode: "reuse-existing",
|
|
92
|
+
projectUid: target.projectUid,
|
|
93
|
+
sequenceUid: target.sequenceUid,
|
|
94
|
+
projectName: timeline.project.name,
|
|
95
|
+
sequenceName: timeline.sequence.name,
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
const revisionKey = shortHash(`${timeline.project.id}:${timeline.sequence.id}:${timelineIrDigest(timeline)}`);
|
|
99
|
+
return {
|
|
100
|
+
mode: "versioned",
|
|
101
|
+
projectUid: `${safeId(target.projectUid)}-framekit-${revisionKey}`,
|
|
102
|
+
sequenceUid: `${safeId(target.sequenceUid)}-framekit-${revisionKey}`,
|
|
103
|
+
projectName: `${timeline.project.name} (Framekit ${revisionKey})`,
|
|
104
|
+
sequenceName: `${timeline.sequence.name} (Framekit ${revisionKey})`,
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
function createResourceIds(timeline) {
|
|
108
|
+
const ids = new Map();
|
|
109
|
+
const used = new Set();
|
|
110
|
+
for (const resource of [...timeline.resources].sort((left, right) => left.id.localeCompare(right.id))) {
|
|
111
|
+
if (resource.mediaKind !== "video" && resource.mediaKind !== "audio") {
|
|
112
|
+
throw new Error(`FCPXML_UNSUPPORTED_RESOURCE_KIND: ${resource.mediaKind}`);
|
|
113
|
+
}
|
|
114
|
+
requireText(resource.source, `resource ${resource.id}.source`);
|
|
115
|
+
const source = resource.source;
|
|
116
|
+
if (!source.startsWith("file://") && !isAbsolute(source)) {
|
|
117
|
+
throw new Error(`FCPXML_RESOURCE_SOURCE_UNSUPPORTED: resource ${resource.id} requires an absolute path or file URL`);
|
|
118
|
+
}
|
|
119
|
+
const base = `resource-${safeId(resource.id)}`;
|
|
120
|
+
let candidate = base;
|
|
121
|
+
if (used.has(candidate))
|
|
122
|
+
candidate = `${base}-${shortHash(resource.id)}`;
|
|
123
|
+
let suffix = 2;
|
|
124
|
+
while (used.has(candidate))
|
|
125
|
+
candidate = `${base}-${shortHash(resource.id)}-${suffix++}`;
|
|
126
|
+
ids.set(resource.id, candidate);
|
|
127
|
+
used.add(candidate);
|
|
128
|
+
}
|
|
129
|
+
return ids;
|
|
130
|
+
}
|
|
131
|
+
function uniqueResourceNames(timeline) {
|
|
132
|
+
const counts = new Map();
|
|
133
|
+
const names = new Map();
|
|
134
|
+
for (const resource of [...timeline.resources].sort((left, right) => left.id.localeCompare(right.id))) {
|
|
135
|
+
const count = (counts.get(resource.name) ?? 0) + 1;
|
|
136
|
+
counts.set(resource.name, count);
|
|
137
|
+
names.set(resource.id, count === 1 ? resource.name : `${resource.name} (${count})`);
|
|
138
|
+
}
|
|
139
|
+
return names;
|
|
140
|
+
}
|
|
141
|
+
function renderResource(resource, id, name) {
|
|
142
|
+
const source = resource.source;
|
|
143
|
+
let src;
|
|
144
|
+
try {
|
|
145
|
+
src = source.startsWith("file://") ? new URL(source).toString() : pathToFileURL(source).toString();
|
|
146
|
+
}
|
|
147
|
+
catch (error) {
|
|
148
|
+
throw new Error(`FCPXML_RESOURCE_SOURCE_UNSUPPORTED: resource ${resource.id} has an invalid file URL: ${error instanceof Error ? error.message : String(error)}`);
|
|
149
|
+
}
|
|
150
|
+
const mediaAttributes = resource.mediaKind === "video"
|
|
151
|
+
? ' hasVideo="1" hasAudio="0"'
|
|
152
|
+
: ' hasVideo="0" hasAudio="1"';
|
|
153
|
+
return ` <asset id="${xmlEscape(id)}" name="${xmlEscape(name)}" src="${xmlEscape(src)}"${mediaAttributes} />`;
|
|
154
|
+
}
|
|
155
|
+
function renderableElements(timeline, resourceIds) {
|
|
156
|
+
const occurrenceIds = new Set(timeline.sequence.occurrences.map(({ id }) => id));
|
|
157
|
+
const elements = timeline.sequence.occurrences.map((occurrence) => renderOccurrence(occurrence, timeline, resourceIds, occurrenceIds));
|
|
158
|
+
for (const element of timeline.sequence.storyElements) {
|
|
159
|
+
if (occurrenceIds.has(element.id) || element.occurrenceId !== undefined && occurrenceIds.has(element.occurrenceId))
|
|
160
|
+
continue;
|
|
161
|
+
if (element.kind !== "gap")
|
|
162
|
+
throw new Error(`FCPXML_UNSUPPORTED_STORY_ELEMENT: ${element.kind}`);
|
|
163
|
+
if (element.attachedTo !== undefined && !occurrenceIds.has(element.attachedTo)) {
|
|
164
|
+
throw new Error(`FCPXML_ATTACHMENT_TARGET_NOT_FOUND: ${element.id} -> ${element.attachedTo}`);
|
|
165
|
+
}
|
|
166
|
+
elements.push({
|
|
167
|
+
id: element.id,
|
|
168
|
+
kind: "gap",
|
|
169
|
+
startTime: element.startTime,
|
|
170
|
+
durationTime: element.durationTime,
|
|
171
|
+
...(element.lane !== undefined ? { lane: element.lane } : {}),
|
|
172
|
+
...(element.attachedTo !== undefined ? { parentId: element.attachedTo } : {}),
|
|
173
|
+
});
|
|
174
|
+
}
|
|
175
|
+
return elements;
|
|
176
|
+
}
|
|
177
|
+
function renderOccurrence(occurrence, timeline, resourceIds, occurrenceIds) {
|
|
178
|
+
if (occurrence.role === "title")
|
|
179
|
+
throw new Error("FCPXML_UNSUPPORTED_OCCURRENCE_ROLE: title");
|
|
180
|
+
if (occurrence.fadeIn !== undefined || occurrence.fadeOut !== undefined) {
|
|
181
|
+
throw new Error(`FCPXML_UNSUPPORTED_OCCURRENCE_FIELD: ${occurrence.id} fades require an FCPXML audio-fade contract`);
|
|
182
|
+
}
|
|
183
|
+
const resource = occurrence.mediaId === undefined ? undefined : resourceIds.get(occurrence.mediaId);
|
|
184
|
+
if (!resource)
|
|
185
|
+
throw new Error(`FCPXML_MEDIA_BINDING_NOT_FOUND: occurrence ${occurrence.id} has no compiled resource`);
|
|
186
|
+
const resourceDefinition = occurrence.mediaId === undefined
|
|
187
|
+
? undefined
|
|
188
|
+
: timeline.resources.find(({ id }) => id === occurrence.mediaId);
|
|
189
|
+
if (resourceDefinition && (occurrence.role === "video" && resourceDefinition.mediaKind !== "video"
|
|
190
|
+
|| (occurrence.role === "audio" || occurrence.role === "music") && resourceDefinition.mediaKind !== "audio")) {
|
|
191
|
+
throw new Error(`FCPXML_MEDIA_ROLE_MISMATCH: occurrence ${occurrence.id} cannot use ${resourceDefinition.mediaKind} resource as ${occurrence.role}`);
|
|
192
|
+
}
|
|
193
|
+
if (occurrence.attachedTo !== undefined && !occurrenceIds.has(occurrence.attachedTo)) {
|
|
194
|
+
throw new Error(`FCPXML_ATTACHMENT_TARGET_NOT_FOUND: ${occurrence.id} -> ${occurrence.attachedTo}`);
|
|
195
|
+
}
|
|
196
|
+
return {
|
|
197
|
+
id: occurrence.id,
|
|
198
|
+
kind: "asset-clip",
|
|
199
|
+
startTime: occurrence.startTime,
|
|
200
|
+
durationTime: occurrence.durationTime,
|
|
201
|
+
...(occurrence.track > 0 ? { lane: occurrence.track } : {}),
|
|
202
|
+
...(occurrence.attachedTo !== undefined ? { parentId: occurrence.attachedTo } : {}),
|
|
203
|
+
name: occurrence.name,
|
|
204
|
+
resourceId: resource,
|
|
205
|
+
...(occurrence.sourceStartTime ? { sourceStartTime: occurrence.sourceStartTime } : {}),
|
|
206
|
+
...(occurrence.role === "audio" || occurrence.role === "music" ? { role: occurrence.role } : {}),
|
|
207
|
+
...(occurrence.gainDb !== undefined ? { gainDb: occurrence.gainDb } : {}),
|
|
208
|
+
...(occurrence.enabled !== undefined ? { enabled: occurrence.enabled } : {}),
|
|
209
|
+
};
|
|
210
|
+
}
|
|
211
|
+
function renderElements(elements) {
|
|
212
|
+
const byParent = new Map();
|
|
213
|
+
const byId = new Map();
|
|
214
|
+
for (const element of elements) {
|
|
215
|
+
byId.set(element.id, element);
|
|
216
|
+
const siblings = byParent.get(element.parentId) ?? [];
|
|
217
|
+
siblings.push(element);
|
|
218
|
+
byParent.set(element.parentId, siblings);
|
|
219
|
+
}
|
|
220
|
+
for (const siblings of byParent.values())
|
|
221
|
+
siblings.sort(compareTimedItems);
|
|
222
|
+
const rendered = new Set();
|
|
223
|
+
const lines = [];
|
|
224
|
+
const render = (parentId, indent) => {
|
|
225
|
+
for (const element of byParent.get(parentId) ?? []) {
|
|
226
|
+
if (rendered.has(element.id))
|
|
227
|
+
throw new Error(`FCPXML_CYCLIC_ATTACHMENT: ${element.id}`);
|
|
228
|
+
rendered.add(element.id);
|
|
229
|
+
const children = byParent.get(element.id) ?? [];
|
|
230
|
+
const parentStartTime = element.parentId === undefined
|
|
231
|
+
? { value: "0", timescale: "1" }
|
|
232
|
+
: byId.get(element.parentId)?.startTime;
|
|
233
|
+
if (!parentStartTime)
|
|
234
|
+
throw new Error(`FCPXML_ATTACHMENT_TARGET_NOT_FOUND: ${element.id} -> ${element.parentId}`);
|
|
235
|
+
const localStartTime = subtractRational(element.startTime, parentStartTime, `${element.id}.startTime`);
|
|
236
|
+
const attributes = element.kind === "asset-clip"
|
|
237
|
+
? [
|
|
238
|
+
`id="${xmlEscape(element.id)}"`,
|
|
239
|
+
`ref="${xmlEscape(element.resourceId)}"`,
|
|
240
|
+
`name="${xmlEscape(element.name)}"`,
|
|
241
|
+
`offset="${formatRational(localStartTime, `${element.id}.startTime`)}"`,
|
|
242
|
+
...(element.sourceStartTime ? [`start="${formatRational(element.sourceStartTime, `${element.id}.sourceStartTime`)}"`] : []),
|
|
243
|
+
`duration="${formatRational(element.durationTime, `${element.id}.durationTime`)}"`,
|
|
244
|
+
...(element.lane !== undefined ? [`lane="${String(element.lane)}"`] : []),
|
|
245
|
+
...(element.role ? [`role="${element.role}"`] : []),
|
|
246
|
+
...(element.enabled !== undefined ? [`enabled="${element.enabled ? "1" : "0"}"`] : []),
|
|
247
|
+
]
|
|
248
|
+
: [
|
|
249
|
+
`id="${xmlEscape(element.id)}"`,
|
|
250
|
+
`offset="${formatRational(localStartTime, `${element.id}.startTime`)}"`,
|
|
251
|
+
`duration="${formatRational(element.durationTime, `${element.id}.durationTime`)}"`,
|
|
252
|
+
...(element.lane !== undefined ? [`lane="${String(element.lane)}"`] : []),
|
|
253
|
+
];
|
|
254
|
+
const opening = `<${element.kind} ${attributes.join(" ")}>`;
|
|
255
|
+
const childLines = element.gainDb !== undefined
|
|
256
|
+
? [`${indent} <adjust-volume amount="${formatDb(element.gainDb, element.id)}" />`]
|
|
257
|
+
: [];
|
|
258
|
+
const childStart = childLines.length > 0 ? childLines : [];
|
|
259
|
+
if (children.length === 0 && childStart.length === 0) {
|
|
260
|
+
lines.push(`${indent}<${element.kind} ${attributes.join(" ")} />`);
|
|
261
|
+
continue;
|
|
262
|
+
}
|
|
263
|
+
lines.push(`${indent}${opening}`);
|
|
264
|
+
lines.push(...childStart);
|
|
265
|
+
render(element.id, `${indent} `);
|
|
266
|
+
lines.push(`${indent}</${element.kind}>`);
|
|
267
|
+
}
|
|
268
|
+
};
|
|
269
|
+
render(undefined, " ");
|
|
270
|
+
if (rendered.size !== elements.length) {
|
|
271
|
+
const missing = elements.find(({ id }) => !rendered.has(id));
|
|
272
|
+
throw new Error(`FCPXML_CYCLIC_ATTACHMENT: ${missing?.id ?? "unknown"}`);
|
|
273
|
+
}
|
|
274
|
+
return lines;
|
|
275
|
+
}
|
|
276
|
+
function compareTimedItems(left, right) {
|
|
277
|
+
const leftTime = parseExactRational(left.startTime);
|
|
278
|
+
const rightTime = parseExactRational(right.startTime);
|
|
279
|
+
const difference = leftTime.value * rightTime.timescale - rightTime.value * leftTime.timescale;
|
|
280
|
+
if (difference !== 0n)
|
|
281
|
+
return difference < 0n ? -1 : 1;
|
|
282
|
+
if ((left.lane ?? 0) !== (right.lane ?? 0))
|
|
283
|
+
return (left.lane ?? 0) - (right.lane ?? 0);
|
|
284
|
+
return left.id.localeCompare(right.id);
|
|
285
|
+
}
|
|
286
|
+
function formatRational(value, field) {
|
|
287
|
+
const parsed = parseExactRational(value);
|
|
288
|
+
if (parsed.value < 0n)
|
|
289
|
+
throw new Error(`FCPXML_INVALID_TIME: ${field} cannot be negative`);
|
|
290
|
+
const divisor = greatestCommonDivisor(parsed.value, parsed.timescale);
|
|
291
|
+
const numerator = parsed.value / divisor;
|
|
292
|
+
const denominator = parsed.timescale / divisor;
|
|
293
|
+
return denominator === 1n ? `${numerator}s` : `${numerator}/${denominator}s`;
|
|
294
|
+
}
|
|
295
|
+
function subtractRational(left, right, field) {
|
|
296
|
+
const leftParts = parseExactRational(left);
|
|
297
|
+
const rightParts = parseExactRational(right);
|
|
298
|
+
const numerator = leftParts.value * rightParts.timescale - rightParts.value * leftParts.timescale;
|
|
299
|
+
if (numerator < 0n)
|
|
300
|
+
throw new Error(`FCPXML_INVALID_TIME: ${field} precedes its attachment target`);
|
|
301
|
+
const denominator = leftParts.timescale * rightParts.timescale;
|
|
302
|
+
const divisor = greatestCommonDivisor(numerator, denominator);
|
|
303
|
+
return { value: String(numerator / divisor), timescale: String(denominator / divisor) };
|
|
304
|
+
}
|
|
305
|
+
function formatDb(value, id) {
|
|
306
|
+
if (!Number.isFinite(value))
|
|
307
|
+
throw new Error(`FCPXML_INVALID_GAIN: ${id}`);
|
|
308
|
+
return `${Object.is(value, -0) ? 0 : value}dB`;
|
|
309
|
+
}
|
|
310
|
+
function safeId(value) {
|
|
311
|
+
let result = "";
|
|
312
|
+
let pendingSeparator = false;
|
|
313
|
+
for (const character of value) {
|
|
314
|
+
const code = character.charCodeAt(0);
|
|
315
|
+
const isAllowed = code >= 0x30 && code <= 0x39
|
|
316
|
+
|| code >= 0x41 && code <= 0x5a
|
|
317
|
+
|| code >= 0x61 && code <= 0x7a
|
|
318
|
+
|| character === "_"
|
|
319
|
+
|| character === "-";
|
|
320
|
+
if (!isAllowed) {
|
|
321
|
+
if (result.length > 0)
|
|
322
|
+
pendingSeparator = true;
|
|
323
|
+
continue;
|
|
324
|
+
}
|
|
325
|
+
if (pendingSeparator)
|
|
326
|
+
result += "-";
|
|
327
|
+
result += character;
|
|
328
|
+
pendingSeparator = false;
|
|
329
|
+
}
|
|
330
|
+
let start = 0;
|
|
331
|
+
let end = result.length;
|
|
332
|
+
while (start < end && result[start] === "-")
|
|
333
|
+
start += 1;
|
|
334
|
+
while (end > start && result[end - 1] === "-")
|
|
335
|
+
end -= 1;
|
|
336
|
+
const trimmed = result.slice(start, end);
|
|
337
|
+
return trimmed.length > 0 ? trimmed : `id-${shortHash(value)}`;
|
|
338
|
+
}
|
|
339
|
+
function shortHash(value) {
|
|
340
|
+
return createHash("sha256").update(value).digest("hex").slice(0, 10);
|
|
341
|
+
}
|
|
342
|
+
function greatestCommonDivisor(left, right) {
|
|
343
|
+
let a = left < 0n ? -left : left;
|
|
344
|
+
let b = right < 0n ? -right : right;
|
|
345
|
+
while (b !== 0n) {
|
|
346
|
+
const remainder = a % b;
|
|
347
|
+
a = b;
|
|
348
|
+
b = remainder;
|
|
349
|
+
}
|
|
350
|
+
return a || 1n;
|
|
351
|
+
}
|
|
352
|
+
function parseExactRational(value) {
|
|
353
|
+
if (!/^-?\d+$/.test(value.value) || !/^\d+$/.test(value.timescale)) {
|
|
354
|
+
throw new Error("FCPXML_INVALID_TIME: rational time requires integer value and timescale");
|
|
355
|
+
}
|
|
356
|
+
const timescale = BigInt(value.timescale);
|
|
357
|
+
if (timescale <= 0n)
|
|
358
|
+
throw new Error("FCPXML_INVALID_TIME: rational timescale must be positive");
|
|
359
|
+
return { value: BigInt(value.value), timescale };
|
|
360
|
+
}
|
|
361
|
+
function xmlEscape(value) {
|
|
362
|
+
return value
|
|
363
|
+
.replaceAll("&", "&")
|
|
364
|
+
.replaceAll("<", "<")
|
|
365
|
+
.replaceAll(">", ">")
|
|
366
|
+
.replaceAll('"', """)
|
|
367
|
+
.replaceAll("'", "'");
|
|
368
|
+
}
|
|
369
|
+
function requireText(value, field) {
|
|
370
|
+
if (typeof value !== "string" || !value.trim())
|
|
371
|
+
throw new Error(`FCPXML_TARGET_BINDING_INVALID: ${field} must be non-empty`);
|
|
372
|
+
}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { EditingSession } from "../../../../packages/runtime/src/index.js";
|
|
2
|
+
import { compareFinalCutSqliteObservations, } from "./sqlite-inspection.js";
|
|
3
|
+
import { compileTimelineIrToFcpxml, } from "./timeline-ir-fcpxml.js";
|
|
4
|
+
import { classifyFinalCutFcpxmlExperiment, } from "./fcpxml-console-experiment.js";
|
|
5
|
+
/**
|
|
6
|
+
* Runs the safe, unattended portion of an edit. It can read a storage
|
|
7
|
+
* observation, rebase a session against provider state, and produce a new
|
|
8
|
+
* FCPXML artifact. It never calls Final Cut, imports an artifact, or writes a
|
|
9
|
+
* destination file.
|
|
10
|
+
*/
|
|
11
|
+
export function runUnattendedEditingWorkflow(options) {
|
|
12
|
+
const session = EditingSession.create({ base: options.base, provider: { id: "final-cut" } });
|
|
13
|
+
session.apply(options.operations);
|
|
14
|
+
const sqlite = sqliteEvidence(options.sqlite);
|
|
15
|
+
if (sqlite.status === "changed" && sameRevision(options.base.revision, options.providerState.revision)) {
|
|
16
|
+
session.markPossiblyStale();
|
|
17
|
+
return result(session, "stale", sqlite);
|
|
18
|
+
}
|
|
19
|
+
let reconciliation;
|
|
20
|
+
if (!sameRevision(options.base.revision, options.providerState.revision)) {
|
|
21
|
+
reconciliation = session.reconcile(options.providerState);
|
|
22
|
+
if (reconciliation.status === "conflicted")
|
|
23
|
+
return result(session, "conflicted", sqlite, reconciliation);
|
|
24
|
+
}
|
|
25
|
+
session.assertMaterializationReady(options.providerState.revision);
|
|
26
|
+
const artifact = compileTimelineIrToFcpxml(session.desired(), { target: options.target });
|
|
27
|
+
const experiment = classifyFinalCutFcpxmlExperiment({
|
|
28
|
+
...options.environment,
|
|
29
|
+
artifact: { format: "fcpxml", version: artifact.version, digest: artifact.digest, valid: true },
|
|
30
|
+
});
|
|
31
|
+
return {
|
|
32
|
+
...result(session, experiment.status === "headed-preflight-ready" ? "artifact-verified" : "artifact-verified-native-blocked", sqlite, reconciliation),
|
|
33
|
+
artifact,
|
|
34
|
+
experiment,
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
function result(session, status, sqlite, reconciliation) {
|
|
38
|
+
return {
|
|
39
|
+
status,
|
|
40
|
+
session: {
|
|
41
|
+
state: session.state(),
|
|
42
|
+
base: session.base(),
|
|
43
|
+
desired: session.desired(),
|
|
44
|
+
serialized: session.serialize(),
|
|
45
|
+
},
|
|
46
|
+
...(reconciliation ? { reconciliation } : {}),
|
|
47
|
+
sqlite,
|
|
48
|
+
mutationAttempted: false,
|
|
49
|
+
overwritten: false,
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
function sqliteEvidence(input) {
|
|
53
|
+
if (!input?.before && !input?.after)
|
|
54
|
+
return { status: "not-provided", canonical: false };
|
|
55
|
+
if (!input?.before) {
|
|
56
|
+
return { status: "observed", canonical: false, digest: input.after.digest, coverageComplete: input.after.coverage.complete };
|
|
57
|
+
}
|
|
58
|
+
if (!input.after) {
|
|
59
|
+
return { status: "observed", canonical: false, digest: input.before.digest, coverageComplete: input.before.coverage.complete };
|
|
60
|
+
}
|
|
61
|
+
const comparison = compareFinalCutSqliteObservations(input.before, input.after);
|
|
62
|
+
return { ...comparison, canonical: false };
|
|
63
|
+
}
|
|
64
|
+
function sameRevision(left, right) {
|
|
65
|
+
return left.id === right.id && left.sequence === right.sequence;
|
|
66
|
+
}
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
|
|
2
|
+
import { dirname, join, resolve } from "node:path";
|
|
3
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
4
|
+
import { EditingSession, } from "../../../packages/runtime/src/index.js";
|
|
5
|
+
export class EditingSessionRepository {
|
|
6
|
+
directory;
|
|
7
|
+
constructor(directory) {
|
|
8
|
+
this.directory = directory;
|
|
9
|
+
}
|
|
10
|
+
async create(input) {
|
|
11
|
+
const sessionId = input.sessionId ?? `session-${randomUUID()}`;
|
|
12
|
+
await this.assertMissing(sessionId);
|
|
13
|
+
const session = EditingSession.create({ base: input.base, provider: input.provider });
|
|
14
|
+
return this.save(sessionId, session);
|
|
15
|
+
}
|
|
16
|
+
async inspect(sessionId) {
|
|
17
|
+
const session = await this.load(sessionId);
|
|
18
|
+
return { sessionId, document: session.document() };
|
|
19
|
+
}
|
|
20
|
+
async preview(sessionId, operations, expectedRevision) {
|
|
21
|
+
const session = await this.load(sessionId);
|
|
22
|
+
return session.preview(operations, expectedRevision);
|
|
23
|
+
}
|
|
24
|
+
async execute(sessionId, operations, expectedRevision) {
|
|
25
|
+
const session = await this.load(sessionId);
|
|
26
|
+
session.apply(operations, expectedRevision);
|
|
27
|
+
return this.save(sessionId, session);
|
|
28
|
+
}
|
|
29
|
+
async status(sessionId) {
|
|
30
|
+
const { document } = await this.inspect(sessionId);
|
|
31
|
+
return {
|
|
32
|
+
sessionId,
|
|
33
|
+
state: document.state,
|
|
34
|
+
...(document.provider ? { provider: document.provider } : {}),
|
|
35
|
+
baseRevision: document.base.revision,
|
|
36
|
+
desiredRevision: document.desired.revision,
|
|
37
|
+
...(document.observation ? { observation: document.observation } : {}),
|
|
38
|
+
readyToMaterialize: document.state === "clean" || document.state === "dirty" || document.state === "rebased",
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
async reconcile(sessionId, provider, providerState) {
|
|
42
|
+
const session = await this.load(sessionId);
|
|
43
|
+
const boundProvider = session.document().provider;
|
|
44
|
+
if (boundProvider && boundProvider.id !== provider.id) {
|
|
45
|
+
throw new Error(`SESSION_PROVIDER_MISMATCH: expected ${boundProvider.id}, received ${provider.id}`);
|
|
46
|
+
}
|
|
47
|
+
const reconciliation = session.reconcile(providerState);
|
|
48
|
+
const stored = await this.save(sessionId, session);
|
|
49
|
+
return { ...stored, reconciliation };
|
|
50
|
+
}
|
|
51
|
+
async observe(sessionId, sourcePath, provider) {
|
|
52
|
+
const result = await provider.inspect(sourcePath);
|
|
53
|
+
if (result.status !== "partial") {
|
|
54
|
+
throw new Error(`${result.error.code}: ${result.error.message.replaceAll(sourcePath, "[redacted]")}`);
|
|
55
|
+
}
|
|
56
|
+
const session = await this.load(sessionId);
|
|
57
|
+
const observation = {
|
|
58
|
+
backend: result.observation.backend,
|
|
59
|
+
sourceId: createHash("sha256").update(resolve(sourcePath)).digest("hex"),
|
|
60
|
+
databaseKind: result.observation.databaseKind,
|
|
61
|
+
digest: result.observation.digest,
|
|
62
|
+
schemaVersion: result.observation.schemaVersion,
|
|
63
|
+
observedAt: result.observation.revision.timestamp,
|
|
64
|
+
canonical: false,
|
|
65
|
+
coverageComplete: false,
|
|
66
|
+
};
|
|
67
|
+
const change = session.bindObservation(observation);
|
|
68
|
+
const stored = await this.save(sessionId, session);
|
|
69
|
+
return { ...stored, observation, change };
|
|
70
|
+
}
|
|
71
|
+
loadForMaterialization(sessionId) {
|
|
72
|
+
return this.load(sessionId);
|
|
73
|
+
}
|
|
74
|
+
checkpoint(sessionId, session) {
|
|
75
|
+
return this.save(sessionId, session);
|
|
76
|
+
}
|
|
77
|
+
async load(sessionId) {
|
|
78
|
+
try {
|
|
79
|
+
return EditingSession.fromJSON(await readFile(this.path(sessionId), "utf8"));
|
|
80
|
+
}
|
|
81
|
+
catch (error) {
|
|
82
|
+
if (error.code === "ENOENT") {
|
|
83
|
+
throw new Error(`SESSION_NOT_FOUND: unknown editing session ${sessionId}`);
|
|
84
|
+
}
|
|
85
|
+
throw error;
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
async save(sessionId, session) {
|
|
89
|
+
const path = this.path(sessionId);
|
|
90
|
+
await mkdir(dirname(path), { recursive: true });
|
|
91
|
+
const temporary = `${path}.${randomUUID()}.tmp`;
|
|
92
|
+
await writeFile(temporary, `${session.serialize()}\n`, { encoding: "utf8", flag: "wx" });
|
|
93
|
+
await rename(temporary, path);
|
|
94
|
+
return { sessionId, document: session.document() };
|
|
95
|
+
}
|
|
96
|
+
async assertMissing(sessionId) {
|
|
97
|
+
try {
|
|
98
|
+
await readFile(this.path(sessionId));
|
|
99
|
+
throw new Error(`SESSION_ALREADY_EXISTS: editing session ${sessionId} already exists`);
|
|
100
|
+
}
|
|
101
|
+
catch (error) {
|
|
102
|
+
if (error.code !== "ENOENT")
|
|
103
|
+
throw error;
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
path(sessionId) {
|
|
107
|
+
if (!/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(sessionId)) {
|
|
108
|
+
throw new Error("SESSION_ID_INVALID: sessionId must be a portable identifier");
|
|
109
|
+
}
|
|
110
|
+
return join(this.directory, `${sessionId}.json`);
|
|
111
|
+
}
|
|
112
|
+
}
|
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
2
|
+
import { homedir } from "node:os";
|
|
3
|
+
import { join } from "node:path";
|
|
2
4
|
import { InMemoryEditorAdapter } from "../../../packages/testkit/src/index.js";
|
|
3
|
-
import { createCommandAnalyzers, createFinalCutLiveAdapter, FcpxmlDocumentAdapter, FinalCutAssetRegistry, FinalCutMediaRegistry, FinalCutConnectionManager, assertCanonicalProviderConfiguration, FinalCutCanonicalNativeProvider, FinalCutCanonicalSnapshotSource, FinalCutLibraryInspectionProvider, FinalCutNativeAutomationAdapter, createFinalCutNativeTargetResolver, DisposableNativeEditWorkflow, FinalCutProjectPublisher, FinalCutVideoExporter, FinalCutSessionAdapter, createNativeOperationLease, createDisposableNativeOperationSession, isFinalCutVideoProbeAvailable, } from "../../../adapters/final-cut/typescript/src/index.js";
|
|
5
|
+
import { createCommandAnalyzers, createFinalCutLiveAdapter, FcpxmlDocumentAdapter, FinalCutAssetRegistry, FinalCutMediaRegistry, FinalCutConnectionManager, assertCanonicalProviderConfiguration, FinalCutCanonicalNativeProvider, FinalCutCanonicalSnapshotSource, FinalCutLibraryInspectionProvider, FinalCutNativeAutomationAdapter, createFinalCutNativeTargetResolver, DisposableNativeEditWorkflow, FinalCutBackgroundMaterializationPublisher, FinalCutProjectPublisher, FinalCutSqliteInspectionProvider, FinalCutVideoExporter, FinalCutSessionAdapter, createNativeOperationLease, createDisposableNativeOperationSession, isFinalCutVideoProbeAvailable, } from "../../../adapters/final-cut/typescript/src/index.js";
|
|
4
6
|
import { FixtureAudioAnalyzer, FixtureMetadataAnalyzer, FixtureSpeechAnalyzer, FixtureVisualAnalyzer } from "../../../packages/testkit/src/index.js";
|
|
5
7
|
import { AgentVideoRuntime } from "../../../packages/runtime/src/index.js";
|
|
6
8
|
import { createMcpServer } from "./server.js";
|
|
@@ -83,6 +85,7 @@ const nativeEditor = liveMode
|
|
|
83
85
|
const canonicalNativeMutationEditor = canonicalNativeProviderEnabled
|
|
84
86
|
? new FinalCutNativeAutomationAdapter({
|
|
85
87
|
enabled: true,
|
|
88
|
+
liveState: () => liveAdapter.readLiveState(),
|
|
86
89
|
nativeOperationLease,
|
|
87
90
|
})
|
|
88
91
|
: nativeEditor;
|
|
@@ -94,6 +97,23 @@ const canonicalNativeProvider = canonicalNativeProviderEnabled
|
|
|
94
97
|
const result = await canonicalNativeMutationEditor.edit({ type: "rename-selected-clip", name });
|
|
95
98
|
return { operationId: result.operationId, undoAvailable: result.undoAvailable };
|
|
96
99
|
},
|
|
100
|
+
trimSelectedClipToRange: async (range) => {
|
|
101
|
+
const result = await canonicalNativeMutationEditor.trimSelectedClipToRange(range);
|
|
102
|
+
return { operationId: result.operationId, undoAvailable: result.undoAvailable };
|
|
103
|
+
},
|
|
104
|
+
addMarkerAtTime: async (marker) => {
|
|
105
|
+
const result = await canonicalNativeMutationEditor.addMarkerAtTime(marker);
|
|
106
|
+
return { operationId: result.operationId, undoAvailable: result.undoAvailable };
|
|
107
|
+
},
|
|
108
|
+
rippleDeleteRange: async (range) => {
|
|
109
|
+
const preview = await canonicalNativeMutationEditor.previewDeleteRange(range);
|
|
110
|
+
const result = await canonicalNativeMutationEditor.executeDeleteRange(preview.previewToken);
|
|
111
|
+
return { operationId: result.operationId, undoAvailable: result.undoAvailable };
|
|
112
|
+
},
|
|
113
|
+
setSelectedClipGain: async (gainDb) => {
|
|
114
|
+
const result = await canonicalNativeMutationEditor.edit({ type: "set-selected-clip-gain", gainDb });
|
|
115
|
+
return { operationId: result.operationId, undoAvailable: result.undoAvailable };
|
|
116
|
+
},
|
|
97
117
|
undo: async (operationId) => {
|
|
98
118
|
const result = await canonicalNativeMutationEditor.undo(operationId);
|
|
99
119
|
return { undone: result.undone, verification: result.verification };
|
|
@@ -131,6 +151,8 @@ const editor = liveMode
|
|
|
131
151
|
const analyzers = liveMode
|
|
132
152
|
? createCommandAnalyzers({
|
|
133
153
|
speechCommand: process.env.FRAMEKIT_SPEECH_ANALYZER,
|
|
154
|
+
speechProviderVersion: process.env.FRAMEKIT_SPEECH_ANALYZER_VERSION,
|
|
155
|
+
speechRequireVad: process.env.FRAMEKIT_SPEECH_REQUIRE_VAD === "1",
|
|
134
156
|
audioCommand: process.env.FRAMEKIT_AUDIO_ANALYZER,
|
|
135
157
|
visualCommand: process.env.FRAMEKIT_VISUAL_ANALYZER,
|
|
136
158
|
metadataCommand: process.env.FRAMEKIT_METADATA_ANALYZER,
|
|
@@ -143,6 +165,8 @@ const analyzers = liveMode
|
|
|
143
165
|
metadataAnalyzer: new FixtureMetadataAnalyzer(),
|
|
144
166
|
};
|
|
145
167
|
const runtime = new AgentVideoRuntime(editor, analyzers);
|
|
168
|
+
const framekitStateDirectory = process.env.FRAMEKIT_STATE_DIR ?? join(homedir(), ".framekit");
|
|
169
|
+
const sqliteObservationProvider = new FinalCutSqliteInspectionProvider();
|
|
146
170
|
const disposableNative = liveMode && !headlessFinalCut && !fcpxmlPath && nativeEditor
|
|
147
171
|
? new DisposableNativeEditWorkflow({
|
|
148
172
|
native: nativeEditor,
|
|
@@ -160,6 +184,12 @@ const projectPublisher = liveMode && fcpxmlPath
|
|
|
160
184
|
liveState: () => liveAdapter.readLiveState(),
|
|
161
185
|
})
|
|
162
186
|
: undefined;
|
|
187
|
+
const backgroundMaterializationCommand = liveMode
|
|
188
|
+
? process.env.FRAMEKIT_FINAL_CUT_BACKGROUND_MATERIALIZATION_COMMAND
|
|
189
|
+
: undefined;
|
|
190
|
+
const sessionMaterializationPublisher = backgroundMaterializationCommand?.trim()
|
|
191
|
+
? new FinalCutBackgroundMaterializationPublisher({ command: backgroundMaterializationCommand })
|
|
192
|
+
: undefined;
|
|
163
193
|
const videoExportProbeAvailable = liveMode && !headlessFinalCut && process.env.FRAMEKIT_FINAL_CUT_NATIVE_WRITES === "1"
|
|
164
194
|
? await isFinalCutVideoProbeAvailable()
|
|
165
195
|
: false;
|
|
@@ -173,12 +203,16 @@ const videoExporter = liveMode && !headlessFinalCut && process.env.FRAMEKIT_FINA
|
|
|
173
203
|
: undefined;
|
|
174
204
|
const server = createMcpServer(runtime, {
|
|
175
205
|
processMode: liveMode && !headlessFinalCut ? "headed" : "headless",
|
|
176
|
-
connectionStatus: () => connection?.
|
|
206
|
+
connectionStatus: () => connection?.ensureConnected(),
|
|
177
207
|
nativeEditor,
|
|
178
208
|
disposableNative,
|
|
179
209
|
nativeOperationSession,
|
|
180
210
|
projectPublisher,
|
|
211
|
+
...(sessionMaterializationPublisher?.isAvailable() ? { sessionMaterializationPublisher } : {}),
|
|
181
212
|
videoExporter,
|
|
213
|
+
sessionDirectory: join(framekitStateDirectory, "sessions"),
|
|
214
|
+
materializationDirectory: join(framekitStateDirectory, "materializations"),
|
|
215
|
+
sqliteObservationProvider,
|
|
182
216
|
});
|
|
183
217
|
const transport = new StdioServerTransport();
|
|
184
218
|
let shuttingDown = false;
|