@morshoto/framekit 0.1.5 → 0.1.10

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.
Files changed (40) hide show
  1. package/bin/framekit.mjs +2 -1
  2. package/dist-package/adapters/final-cut/typescript/src/assets.js +223 -15
  3. package/dist-package/adapters/final-cut/typescript/src/background-export.js +384 -0
  4. package/dist-package/adapters/final-cut/typescript/src/canonical.js +588 -0
  5. package/dist-package/adapters/final-cut/typescript/src/connection.js +20 -5
  6. package/dist-package/adapters/final-cut/typescript/src/disposable-native.js +33 -7
  7. package/dist-package/adapters/final-cut/typescript/src/fcpxml.js +805 -51
  8. package/dist-package/adapters/final-cut/typescript/src/index.js +5 -0
  9. package/dist-package/adapters/final-cut/typescript/src/library-inspection.js +390 -0
  10. package/dist-package/adapters/final-cut/typescript/src/live.js +6 -3
  11. package/dist-package/adapters/final-cut/typescript/src/media.js +151 -0
  12. package/dist-package/adapters/final-cut/typescript/src/native-session.js +412 -0
  13. package/dist-package/adapters/final-cut/typescript/src/native.js +2271 -424
  14. package/dist-package/adapters/final-cut/typescript/src/publisher.js +225 -32
  15. package/dist-package/adapters/final-cut/typescript/src/session.js +145 -17
  16. package/dist-package/apps/mcp-server/src/main.js +73 -17
  17. package/dist-package/apps/mcp-server/src/routing.js +242 -39
  18. package/dist-package/apps/mcp-server/src/server.js +677 -89
  19. package/dist-package/apps/mcp-server/src/version.js +109 -1
  20. package/dist-package/packages/runtime/src/application/media-analysis-service.js +3 -4
  21. package/dist-package/packages/runtime/src/application/project-service.js +46 -7
  22. package/dist-package/packages/runtime/src/audio/dialogue-normalization.js +9 -0
  23. package/dist-package/packages/runtime/src/capabilities.js +62 -9
  24. package/dist-package/packages/runtime/src/context/project-catalog.js +159 -0
  25. package/dist-package/packages/runtime/src/domain/capabilities.js +33 -0
  26. package/dist-package/packages/runtime/src/domain/context.js +14 -1
  27. package/dist-package/packages/runtime/src/domain/editing.js +27 -1
  28. package/dist-package/packages/runtime/src/domain/index.js +1 -0
  29. package/dist-package/packages/runtime/src/domain/skills.js +2 -0
  30. package/dist-package/packages/runtime/src/domain/timeline-target.js +217 -0
  31. package/dist-package/packages/runtime/src/editing/edit-service.js +57 -1
  32. package/dist-package/packages/runtime/src/editing/intent.js +178 -2
  33. package/dist-package/packages/runtime/src/index.js +1 -0
  34. package/dist-package/packages/runtime/src/runtime.js +2 -2
  35. package/dist-package/packages/runtime/src/skills/builtin.js +314 -39
  36. package/dist-package/packages/runtime/src/skills/requirements.js +1 -0
  37. package/dist-package/packages/runtime/src/skills/runtime.js +33 -8
  38. package/dist-package/packages/runtime/src/verification/verification.js +81 -4
  39. package/dist-package/packages/testkit/src/in-memory-editor.js +130 -4
  40. package/package.json +12 -2
@@ -0,0 +1,588 @@
1
+ import { execFile as execFileCallback } from "node:child_process";
2
+ import { mkdtemp, rm, stat } from "node:fs/promises";
3
+ import { basename, join } from "node:path";
4
+ import { tmpdir } from "node:os";
5
+ import { promisify } from "node:util";
6
+ import { canonicalSnapshotDigest, assertTimelineTargetReadAfterWrite, createTimelineTarget, resolveTimelineTarget, reconcileProjectCatalog, validateProjectCatalog, withCapabilityFamilies, CapabilityUnavailableError, } from "../../../../packages/runtime/src/index.js";
7
+ import { FcpxmlDocumentAdapter } from "./fcpxml.js";
8
+ const execFile = promisify(execFileCallback);
9
+ /** Reads the active Final Cut project through its headed Export XML command. */
10
+ export class FinalCutCanonicalSnapshotSource {
11
+ executor;
12
+ exportTimeoutMs;
13
+ pollIntervalMs;
14
+ constructor(options = {}) {
15
+ this.executor = options.executor ?? executeCanonicalAppleScript;
16
+ this.exportTimeoutMs = Math.max(1_000, options.exportTimeoutMs ?? 30_000);
17
+ this.pollIntervalMs = Math.max(10, options.pollIntervalMs ?? 100);
18
+ }
19
+ async readSnapshot() {
20
+ const directory = await mkdtemp(join(tmpdir(), "framekit-finalcut-canonical-"));
21
+ const exportPath = join(directory, "active.fcpxml");
22
+ try {
23
+ await this.executor(buildFinalCutCanonicalExportScript(exportPath));
24
+ return await readCanonicalExport(exportPath, this.exportTimeoutMs, this.pollIntervalMs);
25
+ }
26
+ catch (error) {
27
+ const detail = error instanceof Error ? error.message : String(error);
28
+ if (detail.includes("FINAL_CUT_CANONICAL_"))
29
+ throw error;
30
+ throw new Error(`FINAL_CUT_CANONICAL_EXPORT_FAILED: ${detail}`);
31
+ }
32
+ finally {
33
+ await rm(directory, { recursive: true, force: true });
34
+ }
35
+ }
36
+ }
37
+ export function buildFinalCutCanonicalExportScript(exportPath) {
38
+ return `
39
+ using terms from application "System Events"
40
+
41
+ on findMenuItem(container, expectedNames, timeoutSeconds, timeoutMessage)
42
+ set deadline to (current date) + timeoutSeconds
43
+ repeat
44
+ repeat with candidate in (menu items of container)
45
+ try
46
+ set candidateName to name of candidate as text
47
+ repeat with expectedName in expectedNames
48
+ if candidateName is (expectedName as text) then return candidate
49
+ end repeat
50
+ end try
51
+ end repeat
52
+ if (current date) > deadline then error timeoutMessage
53
+ delay 0.1
54
+ end repeat
55
+ end findMenuItem
56
+
57
+ on findWindow(finalCut, expectedNames, timeoutSeconds, timeoutMessage)
58
+ set deadline to (current date) + timeoutSeconds
59
+ repeat
60
+ repeat with expectedName in expectedNames
61
+ try
62
+ if exists window (expectedName as text) of finalCut then return window (expectedName as text) of finalCut
63
+ end try
64
+ end repeat
65
+ if (current date) > deadline then error timeoutMessage
66
+ delay 0.1
67
+ end repeat
68
+ end findWindow
69
+
70
+ on pressButtonIfPresent(targetWindow, expectedNames)
71
+ repeat with candidate in (buttons of targetWindow)
72
+ try
73
+ set candidateName to name of candidate as text
74
+ repeat with expectedName in expectedNames
75
+ if candidateName is (expectedName as text) and enabled of candidate then
76
+ perform action "AXPress" of candidate
77
+ return true
78
+ end if
79
+ end repeat
80
+ end try
81
+ end repeat
82
+ return false
83
+ end pressButtonIfPresent
84
+
85
+ end using terms from
86
+
87
+ tell application "System Events"
88
+ tell process "Final Cut Pro"
89
+ set frontmost to true
90
+ delay 0.1
91
+ if not frontmost then error "FINAL_CUT_CANONICAL_NOT_FRONTMOST: Final Cut Pro must be frontmost"
92
+ set finalCut to it
93
+ set fileMenu to menu "File" of menu bar 1
94
+ set exportCommand to missing value
95
+ try
96
+ set exportCommand to my findMenuItem(fileMenu, {"Export XML…", "Export XML..."}, 10, "FINAL_CUT_CANONICAL_EXPORT_MENU_UNAVAILABLE: File > Export XML was not exposed")
97
+ on error
98
+ set exportMenuItem to my findMenuItem(fileMenu, {"Export"}, 10, "FINAL_CUT_CANONICAL_EXPORT_MENU_UNAVAILABLE: File > Export was not exposed")
99
+ perform action "AXPress" of exportMenuItem
100
+ set exportMenu to missing value
101
+ repeat 100 times
102
+ try
103
+ if exists menu "Export" of exportMenuItem then
104
+ set exportMenu to menu "Export" of exportMenuItem
105
+ exit repeat
106
+ end if
107
+ end try
108
+ delay 0.1
109
+ end repeat
110
+ if exportMenu is missing value then error "FINAL_CUT_CANONICAL_EXPORT_MENU_UNAVAILABLE: Export submenu was not exposed"
111
+ set exportCommand to my findMenuItem(exportMenu, {"XML…", "XML..."}, 10, "FINAL_CUT_CANONICAL_EXPORT_MENU_UNAVAILABLE: Export XML command was not exposed")
112
+ end try
113
+ perform action "AXPress" of exportCommand
114
+ set exportWindow to my findWindow(finalCut, {"Export XML", "XML"}, 15, "FINAL_CUT_CANONICAL_EXPORT_WINDOW_UNAVAILABLE: Export XML window did not appear")
115
+ my pressButtonIfPresent(exportWindow, {"Next…", "Next...", "Export"})
116
+ delay 0.2
117
+ set saveWindow to my findWindow(finalCut, {"Save", "Export XML"}, 15, "FINAL_CUT_CANONICAL_SAVE_WINDOW_UNAVAILABLE: XML save window did not appear")
118
+ keystroke "g" using {command down, shift down}
119
+ repeat 50 times
120
+ try
121
+ if exists sheet 1 of saveWindow then exit repeat
122
+ end try
123
+ delay 0.1
124
+ end repeat
125
+ if not (exists sheet 1 of saveWindow) then error "FINAL_CUT_CANONICAL_SAVE_WINDOW_UNAVAILABLE: save path sheet did not appear"
126
+ set pathSheet to sheet 1 of saveWindow
127
+ if (count of text fields of pathSheet) is 0 then error "FINAL_CUT_CANONICAL_SAVE_PATH_UNAVAILABLE: save path field did not appear"
128
+ set value of text field 1 of pathSheet to ${appleScriptString(exportPath)}
129
+ key code 36
130
+ delay 0.2
131
+ if exists button "Save" of saveWindow then click button "Save" of saveWindow
132
+ delay 0.2
133
+ if exists button "Replace" of saveWindow then click button "Replace" of saveWindow
134
+ return "canonical-export-requested"
135
+ end tell
136
+ end tell`;
137
+ }
138
+ export function createFinalCutNativeTargetResolver(native) {
139
+ return async (clip, snapshot) => {
140
+ if (!clip.mediaId)
141
+ throw new Error(`TARGET_MISMATCH: occurrence ${clip.id} has no media binding`);
142
+ const media = snapshot.media.find(({ mediaId }) => mediaId === clip.mediaId);
143
+ if (!media?.source)
144
+ throw new Error(`TARGET_MISMATCH: media ${clip.mediaId} has no source binding`);
145
+ const query = sourceBasename(media.source);
146
+ if (!query)
147
+ throw new Error(`TARGET_MISMATCH: media ${clip.mediaId} has no searchable source basename`);
148
+ const matches = (await native.searchMedia(query)).filter((match) => match.name.toLocaleLowerCase() === query.toLocaleLowerCase());
149
+ if (matches.length === 0)
150
+ throw new Error(`TARGET_MISMATCH: Final Cut Browser has no exact media match for ${query}`);
151
+ if (matches.length > 1)
152
+ throw new Error(`AMBIGUOUS_PROJECT_TARGET: Final Cut Browser has multiple exact media matches for ${query}`);
153
+ const match = matches[0];
154
+ if (!match.sourceIdentity)
155
+ throw new Error("TARGET_MISMATCH: exact Browser media has no stable source identity");
156
+ const located = await native.locateOccurrence(match.handle);
157
+ if (located.status === "none" || located.occurrences.length === 0) {
158
+ throw new Error(`TARGET_MISMATCH: Final Cut timeline has no occurrence for ${query}`);
159
+ }
160
+ if (located.status !== "unique" || located.occurrences.length !== 1) {
161
+ throw new Error(`AMBIGUOUS_PROJECT_TARGET: Final Cut timeline has multiple occurrences for ${query}`);
162
+ }
163
+ const occurrence = located.occurrences[0];
164
+ const occurrenceIdentity = occurrence.identity ?? occurrence.nativeIdentity;
165
+ if (!occurrenceIdentity) {
166
+ throw new Error(`TARGET_MISMATCH: native occurrence has no stable identity for ${clip.id}`);
167
+ }
168
+ if (!occurrence.sequenceId) {
169
+ throw new Error(`TARGET_MISMATCH: native occurrence has no stable sequence identity for ${clip.id}`);
170
+ }
171
+ if (occurrence.sequenceId !== snapshot.timeline.id) {
172
+ throw new Error(`TARGET_MISMATCH: native occurrence sequence changed for ${clip.id}`);
173
+ }
174
+ if (occurrence.sourceIdentity && occurrence.sourceIdentity !== match.sourceIdentity) {
175
+ throw new Error(`TARGET_MISMATCH: native occurrence source identity changed for ${clip.id}`);
176
+ }
177
+ if (!occurrence.start || !occurrence.duration || !clip.startTime || !clip.durationTime) {
178
+ throw new Error(`TARGET_MISMATCH: exact timeline coordinates are unavailable for ${clip.id}`);
179
+ }
180
+ if (!sameRationalText(occurrence.start, clip.startTime) || !sameRationalText(occurrence.duration, clip.durationTime)) {
181
+ throw new Error(`TARGET_MISMATCH: native occurrence coordinates changed for ${clip.id}`);
182
+ }
183
+ };
184
+ }
185
+ /**
186
+ * Canonical provider for the headed Final Cut UI path.
187
+ *
188
+ * `readSnapshot` must export the currently active Final Cut project through
189
+ * Final Cut itself. It is deliberately injected so the provider cannot fall
190
+ * back to an arbitrary FCPXML artifact. Native mutation is separately bound
191
+ * to one exported occurrence before Accessibility is allowed to edit it.
192
+ */
193
+ export class FinalCutCanonicalNativeProvider {
194
+ live;
195
+ native;
196
+ readSnapshotSource;
197
+ resolveTarget;
198
+ backgroundCatalog;
199
+ lastDigest;
200
+ lastSnapshot;
201
+ revisionSequence = 0;
202
+ revision;
203
+ pending;
204
+ constructor(options) {
205
+ this.live = options.live;
206
+ this.native = options.native;
207
+ this.readSnapshotSource = options.readSnapshot;
208
+ this.resolveTarget = options.resolveTarget;
209
+ this.backgroundCatalog = options.backgroundCatalog;
210
+ }
211
+ async getIdentity() {
212
+ const identity = await this.live.getIdentity();
213
+ return { ...identity, backend: "final-cut-native-canonical" };
214
+ }
215
+ async getCapabilities(options = {}) {
216
+ const backgroundCatalog = await this.resolveBackgroundCatalog();
217
+ const snapshotProbe = backgroundCatalog && options.probeCanonicalSnapshot !== false
218
+ ? await this.probeCanonicalSnapshot()
219
+ : {
220
+ available: false,
221
+ reason: backgroundCatalog
222
+ ? "canonical snapshot availability was not checked"
223
+ : "canonical timeline snapshot requires a background project catalog",
224
+ };
225
+ const canonicalSnapshotCapability = snapshotProbe.available
226
+ ? true
227
+ : unavailableCanonicalSnapshot(snapshotProbe.reason);
228
+ return withCapabilityFamilies({
229
+ editor: {
230
+ projectRead: snapshotProbe.available,
231
+ timelineSnapshotRead: snapshotProbe.available,
232
+ timelineWrite: snapshotProbe.available,
233
+ timelineArtifactWrite: false,
234
+ readAfterWrite: snapshotProbe.available,
235
+ incrementalChanges: true,
236
+ rollback: snapshotProbe.available,
237
+ assetDiscovery: false,
238
+ liveStateRead: true,
239
+ playheadWrite: false,
240
+ frameCapture: false,
241
+ playbackControl: false,
242
+ projectCatalogRead: Boolean(backgroundCatalog),
243
+ projectSelection: false,
244
+ projectSelectionMode: "unavailable",
245
+ backgroundLibraryInspection: Boolean(backgroundCatalog),
246
+ compositeTransactions: snapshotProbe.available,
247
+ },
248
+ analyzers: {
249
+ speechTranscribe: false,
250
+ speechVad: false,
251
+ audioLoudness: false,
252
+ visualTrack: false,
253
+ },
254
+ }, {
255
+ backend: "final-cut-native-canonical",
256
+ connectionBackend: "workflow-extension-ipc",
257
+ canonicalDocument: {
258
+ read: canonicalSnapshotCapability,
259
+ write: canonicalSnapshotCapability,
260
+ artifactWrite: false,
261
+ },
262
+ observation: {
263
+ library: this.backgroundCatalog
264
+ ? {
265
+ available: true,
266
+ backend: this.backgroundCatalog.backend ?? "final-cut-background-library",
267
+ guarantee: "observed",
268
+ }
269
+ : false,
270
+ },
271
+ });
272
+ }
273
+ async probeCanonicalSnapshot() {
274
+ try {
275
+ await this.readSnapshotSource();
276
+ return { available: true };
277
+ }
278
+ catch (error) {
279
+ const detail = error instanceof Error ? error.message : String(error);
280
+ return {
281
+ available: false,
282
+ reason: `canonical snapshot provider unavailable: ${detail}`,
283
+ };
284
+ }
285
+ }
286
+ async read() {
287
+ return this.readProject();
288
+ }
289
+ async readProject() {
290
+ const snapshot = await this.readSnapshotSource();
291
+ await this.assertActiveTarget(snapshot);
292
+ const digest = canonicalSnapshotDigest(snapshot);
293
+ if (digest !== this.lastDigest || !this.revision) {
294
+ this.revisionSequence = Math.max(this.revisionSequence + 1, snapshot.revision.sequence + 1);
295
+ this.lastDigest = digest;
296
+ this.revision = {
297
+ id: `canonical:${digest}`,
298
+ sequence: this.revisionSequence,
299
+ timestamp: new Date().toISOString(),
300
+ };
301
+ }
302
+ this.lastSnapshot = { ...snapshot, revision: this.revision };
303
+ return structuredClone(this.lastSnapshot);
304
+ }
305
+ async previewTransaction(operations, expectedRevision) {
306
+ const before = await this.readProject();
307
+ assertSameRevision(expectedRevision, before.revision);
308
+ const operation = supportedCanonicalOperation(operations);
309
+ const clip = before.timeline.clips.find(({ id }) => id === operation.clipId);
310
+ if (!clip)
311
+ throw new Error(`CLIP_NOT_FOUND: ${operation.clipId}`);
312
+ const preview = structuredClone(before);
313
+ preview.timeline.clips = preview.timeline.clips.map((candidate) => (candidate.id === operation.clipId ? { ...candidate, name: operation.name } : candidate));
314
+ preview.revision = previewRevision(preview, before.revision);
315
+ return preview;
316
+ }
317
+ async applyTransaction(operations, expectedRevision) {
318
+ const operation = supportedCanonicalOperation(operations);
319
+ await this.apply(operation, expectedRevision);
320
+ }
321
+ async apply(operation, expectedRevision) {
322
+ const before = await this.readProject();
323
+ assertSameRevision(expectedRevision, before.revision);
324
+ if (operation.type !== "rename-clip") {
325
+ throw new Error(`CAPABILITY_UNAVAILABLE: final-cut native canonical provider does not support ${operation.type}`);
326
+ }
327
+ validateCanonicalRename(operation);
328
+ const clip = before.timeline.clips.find(({ id }) => id === operation.clipId);
329
+ if (!clip)
330
+ throw new Error(`CLIP_NOT_FOUND: ${operation.clipId}`);
331
+ const timelineTarget = createTimelineTarget(before, {
332
+ occurrenceId: clip.id,
333
+ mediaId: clip.mediaId,
334
+ });
335
+ resolveTimelineTarget(before, timelineTarget);
336
+ await this.resolveTarget(clip, before);
337
+ const nativeResult = await this.native.renameSelectedClip(operation.name);
338
+ if (!nativeResult.operationId || !nativeResult.undoAvailable) {
339
+ throw new Error("FINAL_CUT_CANONICAL_UNDO_UNAVAILABLE: native rename did not expose Undo");
340
+ }
341
+ this.pending = {
342
+ operationId: nativeResult.operationId,
343
+ beforeDigest: canonicalSnapshotDigest(before),
344
+ beforeRevision: before.revision,
345
+ afterRevision: before.revision,
346
+ };
347
+ try {
348
+ const after = await this.readProject();
349
+ const afterClip = after.timeline.clips.find(({ id }) => id === operation.clipId);
350
+ if (!afterClip || afterClip.name !== operation.name) {
351
+ throw new Error("FINAL_CUT_CANONICAL_READBACK_FAILED: renamed occurrence was not read back from Final Cut");
352
+ }
353
+ if (canonicalSnapshotDigest(after) === this.pending.beforeDigest) {
354
+ throw new Error("FINAL_CUT_CANONICAL_READBACK_FAILED: native edit did not change the canonical digest");
355
+ }
356
+ assertTimelineTargetReadAfterWrite(timelineTarget, before, after);
357
+ this.pending.afterRevision = after.revision;
358
+ return after.revision;
359
+ }
360
+ catch (error) {
361
+ try {
362
+ const undone = await this.native.undo(nativeResult.operationId);
363
+ if (!undone.undone || undone.verification?.verified !== true) {
364
+ throw new Error("native Undo did not verify restoration");
365
+ }
366
+ const restored = await this.readProject();
367
+ if (canonicalSnapshotDigest(restored) !== this.pending.beforeDigest) {
368
+ throw new Error("restored canonical digest does not match the pre-edit state");
369
+ }
370
+ }
371
+ catch (rollbackError) {
372
+ const original = error instanceof Error ? error.message : String(error);
373
+ const rollback = rollbackError instanceof Error ? rollbackError.message : String(rollbackError);
374
+ throw new Error(`FINAL_CUT_CANONICAL_ROLLBACK_FAILED: ${rollback}; original error: ${original}`);
375
+ }
376
+ finally {
377
+ this.pending = undefined;
378
+ }
379
+ throw error;
380
+ }
381
+ }
382
+ async restore(snapshot, expectedRevision) {
383
+ const current = await this.readProject();
384
+ assertSameRevision(expectedRevision, current.revision);
385
+ const pending = this.pending;
386
+ if (!pending || !sameRevision(pending.afterRevision, expectedRevision)) {
387
+ throw new Error("FINAL_CUT_CANONICAL_UNDO_STALE: native operation is not the current canonical edit");
388
+ }
389
+ if (canonicalSnapshotDigest(snapshot) !== pending.beforeDigest) {
390
+ throw new Error("FINAL_CUT_CANONICAL_UNDO_TARGET_MISMATCH: rollback target differs from the applied edit");
391
+ }
392
+ const undone = await this.native.undo(pending.operationId);
393
+ if (!undone.undone || undone.verification?.verified !== true) {
394
+ throw new Error("FINAL_CUT_CANONICAL_UNDO_FAILED: Final Cut did not verify native Undo");
395
+ }
396
+ const restored = await this.readProject();
397
+ if (canonicalSnapshotDigest(restored) !== pending.beforeDigest) {
398
+ throw new Error("FINAL_CUT_CANONICAL_UNDO_FAILED: restored canonical digest does not match the pre-edit state");
399
+ }
400
+ this.pending = undefined;
401
+ }
402
+ async listProjects() {
403
+ const backgroundCatalog = await this.resolveBackgroundCatalog();
404
+ if (!backgroundCatalog) {
405
+ throw new CapabilityUnavailableError("project.list", "editor.projectCatalogRead", {
406
+ available: false,
407
+ backend: "final-cut-native-canonical",
408
+ guarantee: "none",
409
+ unavailableReason: "background project catalog is unavailable; canonical timeline snapshot export (File > Export XML) requires a headed Final Cut UI",
410
+ });
411
+ }
412
+ return this.readBackgroundCatalog(backgroundCatalog);
413
+ }
414
+ async selectProject(selection) {
415
+ throw new Error("CAPABILITY_UNAVAILABLE: Final Cut project selection is not exposed by the background provider");
416
+ }
417
+ async readLiveState() {
418
+ return this.live.readLiveState();
419
+ }
420
+ async liveChangesSince(revision, waitMs = 0) {
421
+ return this.live.liveChangesSince(revision, waitMs);
422
+ }
423
+ async assertActiveTarget(snapshot) {
424
+ const live = await this.live.readLiveState();
425
+ if (!live.project || live.project.id !== snapshot.projectId) {
426
+ throw new Error(`TARGET_MISMATCH: active project identity ${live.project?.id ?? "<unavailable>"} does not match exported project ${snapshot.projectId}`);
427
+ }
428
+ if (live.project.name !== snapshot.projectName) {
429
+ throw new Error(`TARGET_MISMATCH: exported project ${snapshot.projectName} is not active Final Cut project ${live.project.name}`);
430
+ }
431
+ if (!live.sequence || live.sequence.id !== snapshot.timeline.id) {
432
+ throw new Error(`TARGET_MISMATCH: active sequence identity ${live.sequence?.id ?? "<unavailable>"} does not match exported sequence ${snapshot.timeline.id}`);
433
+ }
434
+ if (live.sequence.name !== snapshot.timeline.name) {
435
+ throw new Error(`TARGET_MISMATCH: exported sequence ${snapshot.timeline.name} is not active Final Cut sequence ${live.sequence.name}`);
436
+ }
437
+ }
438
+ async resolveBackgroundCatalog() {
439
+ if (this.backgroundCatalog)
440
+ return this.backgroundCatalog;
441
+ if (!this.live.listProjects || !this.live.getCapabilities)
442
+ return undefined;
443
+ try {
444
+ const capabilities = await this.live.getCapabilities();
445
+ if (!capabilities.editor.projectCatalogRead)
446
+ return undefined;
447
+ const identity = await this.live.getIdentity();
448
+ return {
449
+ backend: identity.backend,
450
+ listProjects: () => this.live.listProjects(),
451
+ };
452
+ }
453
+ catch {
454
+ return undefined;
455
+ }
456
+ }
457
+ async readBackgroundCatalog(provider) {
458
+ const before = await this.readLiveStateSafely();
459
+ const catalog = await provider.listProjects();
460
+ validateProjectCatalog(catalog);
461
+ const after = await this.readLiveStateSafely();
462
+ const liveIdentity = before && after ? await this.live.getIdentity() : undefined;
463
+ return reconcileProjectCatalog(catalog, {
464
+ ...(before && after ? { before, after } : {}),
465
+ provenance: {
466
+ catalog: {
467
+ source: "background-library",
468
+ backend: provider.backend ?? "final-cut-background-library",
469
+ guarantee: "observed",
470
+ },
471
+ ...(liveIdentity ? {
472
+ live: {
473
+ source: "live-socket",
474
+ backend: liveIdentity.backend,
475
+ guarantee: "observed",
476
+ },
477
+ } : {}),
478
+ selection: {
479
+ available: false,
480
+ mode: "unavailable",
481
+ unavailableReason: "project selection is not exposed by the background provider",
482
+ },
483
+ },
484
+ });
485
+ }
486
+ async readLiveStateSafely() {
487
+ try {
488
+ return await this.live.readLiveState();
489
+ }
490
+ catch {
491
+ return undefined;
492
+ }
493
+ }
494
+ }
495
+ function supportedCanonicalOperation(operations) {
496
+ if (operations.length !== 1 || operations[0]?.type !== "rename-clip") {
497
+ throw new Error("CAPABILITY_UNAVAILABLE: final-cut native canonical provider supports one rename-clip transaction");
498
+ }
499
+ return validateCanonicalRename(operations[0]);
500
+ }
501
+ function validateCanonicalRename(operation) {
502
+ if (!operation.name.trim())
503
+ throw new Error("INVALID_OPERATION: clip name cannot be empty");
504
+ return operation;
505
+ }
506
+ function unavailableCanonicalSnapshot(reason) {
507
+ return {
508
+ available: false,
509
+ backend: "final-cut-native-canonical",
510
+ guarantee: "none",
511
+ unavailableReason: reason,
512
+ };
513
+ }
514
+ function previewRevision(snapshot, before) {
515
+ return {
516
+ id: `canonical:${canonicalSnapshotDigest(snapshot)}`,
517
+ sequence: before.sequence + 1,
518
+ timestamp: new Date().toISOString(),
519
+ };
520
+ }
521
+ function assertSameRevision(expected, actual) {
522
+ if (!sameRevision(expected, actual))
523
+ throw new Error("STALE_CONTEXT: canonical Final Cut revision changed before mutation");
524
+ }
525
+ function sameRevision(left, right) {
526
+ return left.id === right.id && left.sequence === right.sequence;
527
+ }
528
+ async function executeCanonicalAppleScript(script) {
529
+ try {
530
+ const result = await execFile("osascript", ["-e", script], { maxBuffer: 1_000_000 });
531
+ return result.stdout.trim();
532
+ }
533
+ catch (error) {
534
+ const detail = error instanceof Error ? error.message : String(error);
535
+ if (detail.includes("not authorized") || detail.includes("-1743") || detail.includes("-25211")) {
536
+ throw new Error(`FINAL_CUT_CANONICAL_PERMISSION_REQUIRED: ${detail}`);
537
+ }
538
+ throw new Error(`FINAL_CUT_CANONICAL_AUTOMATION_FAILED: ${detail}`);
539
+ }
540
+ }
541
+ async function readCanonicalExport(path, timeoutMs, pollIntervalMs) {
542
+ const deadline = Date.now() + timeoutMs;
543
+ let previousSignature;
544
+ let lastReadError;
545
+ while (Date.now() <= deadline) {
546
+ let signature;
547
+ try {
548
+ const details = await stat(path);
549
+ if (details.isFile() && details.size > 0) {
550
+ signature = `${details.size}:${details.mtimeMs}`;
551
+ }
552
+ }
553
+ catch {
554
+ // The Save dialog may still be open.
555
+ }
556
+ if (signature && signature === previousSignature) {
557
+ try {
558
+ return await new FcpxmlDocumentAdapter(path).readProject();
559
+ }
560
+ catch (error) {
561
+ lastReadError = error;
562
+ }
563
+ }
564
+ previousSignature = signature;
565
+ await new Promise((resolve) => setTimeout(resolve, Math.min(pollIntervalMs, Math.max(1, deadline - Date.now()))));
566
+ }
567
+ const detail = lastReadError instanceof Error ? `: ${lastReadError.message}` : "";
568
+ throw new Error(`FINAL_CUT_CANONICAL_EXPORT_TIMEOUT: Final Cut did not provide a complete export at ${path}${detail}`);
569
+ }
570
+ function sourceBasename(source) {
571
+ const withoutQuery = source.split(/[?#]/, 1)[0] ?? source;
572
+ try {
573
+ const url = new URL(withoutQuery);
574
+ return basename(decodeURIComponent(url.pathname));
575
+ }
576
+ catch {
577
+ return basename(withoutQuery.replace(/^file:\/\//, ""));
578
+ }
579
+ }
580
+ function sameRationalText(value, expected) {
581
+ const match = value.trim().match(/^(-?\d+)\/(\d+)$/);
582
+ if (!match || Number(match[2]) <= 0 || Number(expected.timescale) <= 0)
583
+ return false;
584
+ return BigInt(match[1]) * BigInt(expected.timescale) === BigInt(expected.value) * BigInt(match[2]);
585
+ }
586
+ function appleScriptString(value) {
587
+ return `"${value.replaceAll("\\", "\\\\").replaceAll('"', '\\"').replace(/[\r\n]/g, " ")}"`;
588
+ }
@@ -4,9 +4,14 @@ import { existsSync } from "node:fs";
4
4
  import { promisify } from "node:util";
5
5
  import { homedir } from "node:os";
6
6
  import { dirname, join, resolve } from "node:path";
7
- import { withCapabilityFamilies } from "../../../../packages/runtime/src/index.js";
7
+ import { withCanonicalTimelineMode, withCapabilityFamilies } from "../../../../packages/runtime/src/index.js";
8
8
  import { createFinalCutLiveAdapter, DEFAULT_FINAL_CUT_LIVE_SOCKET } from "./live.js";
9
9
  const execFile = promisify(execFileCallback);
10
+ export function assertCanonicalProviderConfiguration(options) {
11
+ if (options.required && options.fcpxmlPath?.trim()) {
12
+ throw new Error("FINAL_CUT_CANONICAL_FALLBACK_CONFLICT: canonical provider mode cannot use FRAMEKIT_FCPXML_PATH");
13
+ }
14
+ }
10
15
  const DEFAULT_EXTENSION_NAME = "FramekitFinalCutWorkflow.app";
11
16
  /**
12
17
  * Owns the user-facing lifecycle around the native Workflow Extension.
@@ -16,6 +21,7 @@ const DEFAULT_EXTENSION_NAME = "FramekitFinalCutWorkflow.app";
16
21
  export class FinalCutConnectionManager {
17
22
  socketPath;
18
23
  headless;
24
+ canonicalProviderRequired;
19
25
  extensionSourcePath;
20
26
  extensionInstallPath;
21
27
  finalCutApp;
@@ -38,6 +44,8 @@ export class FinalCutConnectionManager {
38
44
  constructor(options = {}) {
39
45
  this.socketPath = options.socketPath ?? process.env.FRAMEKIT_FINAL_CUT_SOCKET ?? DEFAULT_FINAL_CUT_LIVE_SOCKET;
40
46
  this.headless = options.headless ?? process.env.FRAMEKIT_FINAL_CUT_HEADLESS === "1";
47
+ this.canonicalProviderRequired = options.canonicalProviderRequired
48
+ ?? process.env.FRAMEKIT_FINAL_CUT_CANONICAL_REQUIRED === "1";
41
49
  this.extensionInstallPath = options.extensionInstallPath
42
50
  ?? process.env.FRAMEKIT_EXTENSION_INSTALL_PATH
43
51
  ?? join(homedir(), "Applications", DEFAULT_EXTENSION_NAME);
@@ -98,6 +106,9 @@ export class FinalCutConnectionManager {
98
106
  const existing = await this.tryProbe();
99
107
  if (existing)
100
108
  return this.ready(existing);
109
+ if (this.canonicalProviderRequired) {
110
+ return this.fail("FINAL_CUT_CANONICAL_PROVIDER_UNAVAILABLE", `Canonical live provider is unavailable at ${this.socketPath}; metadata-only fallback is disabled`, "needs-user-action");
111
+ }
101
112
  if (this.headless) {
102
113
  return this.fail("FINAL_CUT_HEADLESS_SOCKET_UNAVAILABLE", `Headless mode only probes the existing Workflow Extension socket at ${this.socketPath}; it does not launch or activate Final Cut Pro`, "unavailable");
103
114
  }
@@ -182,15 +193,19 @@ export class FinalCutConnectionManager {
182
193
  }
183
194
  }
184
195
  ready(result) {
196
+ const capabilities = withCanonicalTimelineMode(withCapabilityFamilies(result.capabilities, {
197
+ backend: result.identity.backend,
198
+ connectionBackend: result.identity.backend,
199
+ }));
200
+ if (this.canonicalProviderRequired && capabilities.editor.canonicalTimelineMode !== "canonical-write") {
201
+ return this.fail("FINAL_CUT_CANONICAL_PROVIDER_REQUIRED", `Canonical live provider at ${this.socketPath} reports ${capabilities.editor.canonicalTimelineMode}; canonical-write is required`, "needs-user-action");
202
+ }
185
203
  this.update({
186
204
  state: "ready",
187
205
  editorDetected: true,
188
206
  extensionInstalled: true,
189
207
  identity: result.identity,
190
- capabilities: withCapabilityFamilies(result.capabilities, {
191
- backend: result.identity.backend,
192
- connectionBackend: result.identity.backend,
193
- }),
208
+ capabilities,
194
209
  lastError: undefined,
195
210
  });
196
211
  return this.getStatus();