@morshoto/framekit 0.1.14 → 0.1.16

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 (30) hide show
  1. package/dist-package/adapters/final-cut/typescript/src/background-materialization.js +28 -0
  2. package/dist-package/adapters/final-cut/typescript/src/canonical.js +144 -35
  3. package/dist-package/adapters/final-cut/typescript/src/disposable-native.js +36 -7
  4. package/dist-package/adapters/final-cut/typescript/src/index.js +2 -0
  5. package/dist-package/adapters/final-cut/typescript/src/live.js +56 -1
  6. package/dist-package/adapters/final-cut/typescript/src/native.js +311 -20
  7. package/dist-package/adapters/final-cut/typescript/src/pasteboard-snapshot.js +312 -0
  8. package/dist-package/adapters/final-cut/typescript/src/publisher.js +68 -8
  9. package/dist-package/adapters/final-cut/typescript/src/sqlite-wal-observation.js +263 -0
  10. package/dist-package/adapters/final-cut/typescript/src/timeline-ir-fcpxml.js +75 -3
  11. package/dist-package/adapters/headless/typescript/src/ffmpeg-media-probe.js +62 -0
  12. package/dist-package/adapters/headless/typescript/src/ffmpeg-renderer.js +443 -0
  13. package/dist-package/adapters/headless/typescript/src/ffmpeg-verifier.js +181 -0
  14. package/dist-package/adapters/headless/typescript/src/index.js +3 -0
  15. package/dist-package/apps/mcp-server/src/headless-projects.js +139 -0
  16. package/dist-package/apps/mcp-server/src/headless-sessions.js +3 -0
  17. package/dist-package/apps/mcp-server/src/main.js +22 -1
  18. package/dist-package/apps/mcp-server/src/materialization-jobs.js +233 -4
  19. package/dist-package/apps/mcp-server/src/readback-policy.js +26 -0
  20. package/dist-package/apps/mcp-server/src/routing.js +134 -5
  21. package/dist-package/apps/mcp-server/src/server.js +214 -31
  22. package/dist-package/packages/runtime/src/application/local-media.js +157 -0
  23. package/dist-package/packages/runtime/src/application/project-store.js +234 -0
  24. package/dist-package/packages/runtime/src/application/project-transactions.js +227 -0
  25. package/dist-package/packages/runtime/src/index.js +6 -0
  26. package/dist-package/packages/runtime/src/render/render-and-verify.js +126 -0
  27. package/dist-package/packages/runtime/src/render/render-contract.js +143 -0
  28. package/dist-package/packages/runtime/src/timeline/editing-session.js +277 -9
  29. package/dist-package/packages/runtime/src/timeline/fast-observation.js +141 -0
  30. package/package.json +2 -1
@@ -53,6 +53,8 @@ function validateRequest(request) {
53
53
  }
54
54
  if (!request.desiredDigest.trim())
55
55
  throw new Error("MATERIALIZATION_REQUEST_INVALID: desired digest is required");
56
+ if (!request.baseDigest.trim() || !request.baseRevision?.id?.trim())
57
+ throw new Error("MATERIALIZATION_REQUEST_INVALID: canonical base provenance is required");
56
58
  if (request.collisionPolicy !== "create-only")
57
59
  throw new Error("MATERIALIZATION_REQUEST_INVALID: publication must be create-only");
58
60
  const { target } = request;
@@ -66,6 +68,32 @@ function validateRequest(request) {
66
68
  throw new Error("MATERIALIZATION_DESTINATION_INVALID: versioned project and sequence identities are required");
67
69
  }
68
70
  validateTimelineIr(request.desired);
71
+ validateMaterializationMetadata(request);
72
+ }
73
+ function validateMaterializationMetadata(request) {
74
+ const { coverage, provenance } = request;
75
+ if (!coverage || !Array.isArray(coverage.exact) || !Array.isArray(coverage.degraded) || !Array.isArray(coverage.unsupported)
76
+ || [...coverage.exact, ...coverage.degraded, ...coverage.unsupported].some((value) => typeof value !== "string" || !value.trim())) {
77
+ throw new Error("MATERIALIZATION_COVERAGE_INVALID: exact, degraded, and unsupported feature lists are required");
78
+ }
79
+ if (coverage.unsupported.length > 0) {
80
+ throw new Error("MATERIALIZATION_COVERAGE_UNSUPPORTED: unsupported Timeline IR features cannot be delivered");
81
+ }
82
+ if (!provenance || provenance.source !== "framekit-timeline-ir" || provenance.schemaVersion !== 1
83
+ || provenance.projectId !== request.desired.project.id
84
+ || provenance.sequenceId !== request.desired.sequence.id
85
+ || provenance.timelineDigest !== request.desiredDigest
86
+ || provenance.revision?.id !== request.desired.revision.id
87
+ || provenance.revision?.sequence !== request.desired.revision.sequence
88
+ || provenance.revision?.timestamp !== request.desired.revision.timestamp
89
+ || provenance.target?.libraryUid !== request.target.libraryUid
90
+ || provenance.target?.eventUid !== request.target.eventUid
91
+ || provenance.target?.projectUid !== request.target.projectUid
92
+ || provenance.target?.sequenceUid !== request.target.sequenceUid
93
+ || provenance.destination?.projectUid !== request.destination.projectUid
94
+ || provenance.destination?.sequenceUid !== request.destination.sequenceUid) {
95
+ throw new Error("MATERIALIZATION_PROVENANCE_INVALID: provenance does not bind to the desired Timeline IR and target");
96
+ }
69
97
  }
70
98
  function validateResult(result) {
71
99
  if (!result || (result.state !== "completed" && result.state !== "blocked")) {
@@ -1,13 +1,14 @@
1
1
  import { execFile as execFileCallback } from "node:child_process";
2
2
  import { mkdtemp, rm, stat } from "node:fs/promises";
3
3
  import { basename, dirname, join } from "node:path";
4
- import { tmpdir } from "node:os";
4
+ import { homedir, tmpdir } from "node:os";
5
5
  import { promisify } from "node:util";
6
6
  import { canonicalSnapshotDigest, canonicalTimelineMode, assertTimelineTargetReadAfterWrite, createTimelineTarget, resolveTimelineTarget, reconcileProjectCatalog, validateProjectCatalog, withCapabilityFamilies, CapabilityUnavailableError, } from "../../../../packages/runtime/src/index.js";
7
7
  import { recoverCanonicalNativeMutation } from "./canonical-recovery.js";
8
8
  import { verifyCanonicalReadback } from "./canonical-verification.js";
9
9
  import { FcpxmlDocumentAdapter } from "./fcpxml.js";
10
10
  const execFile = promisify(execFileCallback);
11
+ const CANONICAL_APPLE_EVENT_TIMEOUT_MS = 30_000;
11
12
  /** Structured failure returned when headed Export XML recovery can be retried. */
12
13
  export class FinalCutCanonicalExportError extends Error {
13
14
  code;
@@ -86,15 +87,23 @@ export class FinalCutCanonicalSnapshotSource {
86
87
  exportTimeoutMs;
87
88
  pollIntervalMs;
88
89
  target;
90
+ stageOnDesktop;
89
91
  constructor(options = {}) {
90
92
  this.executor = options.executor ?? executeCanonicalAppleScript;
91
93
  this.exportTimeoutMs = Math.max(1_000, options.exportTimeoutMs ?? 30_000);
92
94
  this.pollIntervalMs = Math.max(10, options.pollIntervalMs ?? 100);
93
95
  this.target = options.target;
96
+ this.stageOnDesktop = !options.executor;
94
97
  }
95
98
  async readSnapshot() {
96
99
  const directory = await mkdtemp(join(tmpdir(), "framekit-finalcut-canonical-"));
97
- const exportPath = join(directory, "active.fcpxml");
100
+ // Final Cut's headed save panel does not reliably honor Go To Folder when
101
+ // driven through System Events. Stage real headed reads on the default
102
+ // Desktop, then remove the exact package after parsing it. Injected
103
+ // executors retain the isolated temporary path used by deterministic tests.
104
+ const exportPath = this.stageOnDesktop
105
+ ? join(homedir(), "Desktop", `${basename(directory)}.fcpxml`)
106
+ : join(directory, "active.fcpxml");
98
107
  try {
99
108
  for (let attempt = 1; attempt <= 2; attempt += 1) {
100
109
  const result = parseFinalCutCanonicalExportResult(await this.executor(buildFinalCutCanonicalExportScript(exportPath)));
@@ -115,6 +124,8 @@ export class FinalCutCanonicalSnapshotSource {
115
124
  throw new Error(`FINAL_CUT_CANONICAL_EXPORT_FAILED: ${detail}`);
116
125
  }
117
126
  finally {
127
+ await rm(exportPath, { force: true });
128
+ await rm(`${exportPath}.fcpxmld`, { recursive: true, force: true });
118
129
  await rm(directory, { recursive: true, force: true });
119
130
  }
120
131
  }
@@ -122,6 +133,22 @@ export class FinalCutCanonicalSnapshotSource {
122
133
  export function buildFinalCutCanonicalExportScript(exportPath) {
123
134
  const exportDirectory = dirname(exportPath);
124
135
  const exportName = basename(exportPath);
136
+ const defaultDesktop = join(homedir(), "Desktop");
137
+ const chooseExportDirectory = exportDirectory === defaultDesktop
138
+ ? ""
139
+ : ` keystroke "g" using {command down, shift down}
140
+ delay 1
141
+ try
142
+ set pathField to text field 1 of sheet 1 of window "Export XML"
143
+ set value of pathField to ${appleScriptString(exportDirectory)}
144
+ on error
145
+ keystroke "a" using {command down}
146
+ keystroke ${appleScriptString(exportDirectory)}
147
+ end try
148
+ delay 0.5
149
+ key code 36
150
+ delay 0.8
151
+ `;
125
152
  return `
126
153
  using terms from application "System Events"
127
154
 
@@ -196,6 +223,23 @@ on findAccessibilityDescendant(container, expectedRoles, depth)
196
223
  return missing value
197
224
  end findAccessibilityDescendant
198
225
 
226
+ on findTimelineArea(container, depth)
227
+ if depth > 12 then return missing value
228
+ try
229
+ if (role of container as text) is "AXLayoutArea" then
230
+ if my accessibilityMatchesExpectedName(container, {"Project Timeline", "Timeline"}) then return container
231
+ end if
232
+ end try
233
+ try
234
+ repeat with childRef in (UI elements of container)
235
+ set candidate to contents of childRef
236
+ set found to my findTimelineArea(candidate, depth + 1)
237
+ if found is not missing value then return found
238
+ end repeat
239
+ end try
240
+ return missing value
241
+ end findTimelineArea
242
+
199
243
  on accessibilityContainsPathMarker(candidate)
200
244
  repeat with attributeName in {"AXDescription", "AXTitle", "AXIdentifier"}
201
245
  try
@@ -214,6 +258,10 @@ on matchesCanonicalPathField(candidate)
214
258
  try
215
259
  if not my roleIsExpected(role of candidate as text, {"AXTextField", "AXTextArea", "AXComboBox"}) then return false
216
260
  end try
261
+ try
262
+ set candidateIdentifier to id of candidate as text
263
+ if candidateIdentifier is "PathTextField" then return true
264
+ end try
217
265
  try
218
266
  set candidateIdentifier to value of attribute "AXIdentifier" of candidate as text
219
267
  if candidateIdentifier is "path" or candidateIdentifier is "location" then return true
@@ -257,9 +305,31 @@ on findCanonicalPathField(container, depth)
257
305
  return missing value
258
306
  end findCanonicalPathField
259
307
 
308
+ on findAccessibilityIdentifier(container, expectedIdentifier, depth)
309
+ if depth > 12 then return missing value
310
+ try
311
+ set candidateIdentifier to id of container as text
312
+ if candidateIdentifier is expectedIdentifier then return container
313
+ end try
314
+ try
315
+ set candidateIdentifier to (value of attribute "AXIdentifier" of container) as text
316
+ if candidateIdentifier is expectedIdentifier then return container
317
+ end try
318
+ try
319
+ repeat with childRef in (UI elements of container)
320
+ set candidate to contents of childRef
321
+ set found to my findAccessibilityIdentifier(candidate, expectedIdentifier, depth + 1)
322
+ if found is not missing value then return found
323
+ end repeat
324
+ end try
325
+ return missing value
326
+ end findAccessibilityIdentifier
327
+
260
328
  on findSavePathField(saveWindow, timeoutSeconds, timeoutMessage)
261
329
  set deadline to (current date) + timeoutSeconds
262
330
  repeat
331
+ set candidate to my findAccessibilityIdentifier(saveWindow, "PathTextField", 0)
332
+ if candidate is not missing value then return candidate
263
333
  set focusedCandidate to missing value
264
334
  try
265
335
  set focusedCandidate to value of attribute "AXFocusedUIElement"
@@ -280,6 +350,10 @@ on matchesCanonicalSaveNameField(candidate)
280
350
  try
281
351
  if not my roleIsExpected(role of candidate as text, {"AXTextField", "AXTextArea", "AXComboBox"}) then return false
282
352
  end try
353
+ try
354
+ set candidateIdentifier to id of candidate as text
355
+ if candidateIdentifier is "saveAsNameTextField" then return true
356
+ end try
283
357
  repeat with attributeName in {"AXIdentifier", "AXDescription", "AXTitle"}
284
358
  try
285
359
  set candidateLabel to value of attribute (attributeName as text) of candidate as text
@@ -307,6 +381,12 @@ end findCanonicalSaveNameFieldDescendant
307
381
  on findCanonicalSaveNameField(saveWindow, timeoutSeconds, timeoutMessage)
308
382
  set deadline to (current date) + timeoutSeconds
309
383
  repeat
384
+ set candidate to my findAccessibilityIdentifier(saveWindow, "saveAsNameTextField", 0)
385
+ if candidate is not missing value then return candidate
386
+ try
387
+ set focusedCandidate to value of attribute "AXFocusedUIElement"
388
+ if my matchesCanonicalSaveNameField(focusedCandidate) then return focusedCandidate
389
+ end try
310
390
  set candidate to my findCanonicalSaveNameFieldDescendant(saveWindow, 0)
311
391
  if candidate is not missing value then return candidate
312
392
  if (current date) > deadline then error timeoutMessage
@@ -408,6 +488,25 @@ tell application "System Events"
408
488
  set frontmost to true
409
489
  delay 0.1
410
490
  if not frontmost then error "FINAL_CUT_CANONICAL_NOT_FRONTMOST: Final Cut Pro must be frontmost"
491
+ try
492
+ if exists window "Final Cut Pro" of finalCut then
493
+ perform action "AXRaise" of window "Final Cut Pro" of finalCut
494
+ delay 0.2
495
+ end if
496
+ end try
497
+ set frontWindow to window "Final Cut Pro" of finalCut
498
+ set timelineArea to my findTimelineArea(frontWindow, 0)
499
+ if timelineArea is missing value then error "FINAL_CUT_CANONICAL_TIMELINE_UNAVAILABLE: Project Timeline was not exposed"
500
+ try
501
+ perform action "AXPress" of timelineArea
502
+ on error
503
+ try
504
+ click timelineArea
505
+ on error
506
+ error "FINAL_CUT_CANONICAL_TIMELINE_UNAVAILABLE: Project Timeline could not be focused"
507
+ end try
508
+ end try
509
+ delay 0.2
411
510
  set fileMenu to menu "File" of menu bar 1
412
511
  set exportCommand to missing value
413
512
  try
@@ -430,35 +529,32 @@ tell application "System Events"
430
529
  end try
431
530
  perform action "AXPress" of exportCommand
432
531
  set exportWindow to my findWindow(finalCut, {"Export XML", "XML"}, 15, "FINAL_CUT_CANONICAL_EXPORT_WINDOW_UNAVAILABLE: Export XML window did not appear")
433
- my pressAccessibilityButtonIfPresent(exportWindow, {"Next…", "Next...", "Export"})
434
- delay 0.2
435
- set saveWindow to my findWindow(finalCut, {"Save", "Export XML"}, 15, "FINAL_CUT_CANONICAL_SAVE_WINDOW_UNAVAILABLE: XML save window did not appear")
436
- keystroke "g" using {command down, shift down}
437
- set pathField to my findSavePathField(saveWindow, 5, "FINAL_CUT_CANONICAL_SAVE_PATH_UNAVAILABLE: save path field did not appear")
438
- set value of pathField to ${appleScriptString(exportDirectory)}
439
- delay 0.2
440
- key code 36
532
+ set saveWindow to exportWindow
533
+ set saveRoot to first UI element of saveWindow
534
+ set nameField to missing value
535
+ try
536
+ set nameField to text field 2 of saveRoot
537
+ end try
538
+ if nameField is missing value then
539
+ if not my pressAccessibilityButtonIfPresent(exportWindow, {"Next…", "Next...", "Export"}) then error "FINAL_CUT_CANONICAL_EXPORT_WINDOW_UNAVAILABLE: Export XML next control was not exposed"
540
+ delay 0.2
541
+ set saveWindow to my findWindow(finalCut, {"Save", "Export XML"}, 15, "FINAL_CUT_CANONICAL_SAVE_WINDOW_UNAVAILABLE: XML save window did not appear")
542
+ ${chooseExportDirectory} set saveRoot to first UI element of saveWindow
543
+ try
544
+ set nameField to text field 2 of saveRoot
545
+ on error
546
+ error "FINAL_CUT_CANONICAL_SAVE_NAME_UNAVAILABLE: save filename field was not exposed as text field 2"
547
+ end try
548
+ else
549
+ ${chooseExportDirectory} end if
550
+ set value of nameField to ${appleScriptString(exportName)}
551
+ set savePressed to false
552
+ try
553
+ perform action "AXPress" of button 3 of saveRoot
554
+ set savePressed to true
555
+ end try
556
+ if not savePressed and not my pressAccessibilityButtonIfPresent(saveWindow, {"Save"}) then error "FINAL_CUT_CANONICAL_SAVE_BUTTON_UNAVAILABLE: Save button was not exposed"
441
557
  delay 0.2
442
- set saveWindow to my findWindow(finalCut, {"Save", "Export XML"}, 15, "FINAL_CUT_CANONICAL_SAVE_WINDOW_UNAVAILABLE: XML save window did not appear")
443
- set nameField to my findCanonicalSaveNameField(saveWindow, 5, "FINAL_CUT_CANONICAL_SAVE_NAME_UNAVAILABLE: save filename field did not appear")
444
- set value of nameField to ${appleScriptString(exportName)}
445
- if not my pressAccessibilityButtonIfPresent(saveWindow, {"Save"}) then error "FINAL_CUT_CANONICAL_SAVE_BUTTON_UNAVAILABLE: Save button was not exposed"
446
- repeat 10 times
447
- set savePanelOpen to false
448
- repeat with saveWindowName in {"Save", "Export XML"}
449
- try
450
- if exists window (saveWindowName as text) of finalCut then
451
- set savePanelOpen to true
452
- set saveWindow to window (saveWindowName as text) of finalCut
453
- exit repeat
454
- end if
455
- end try
456
- end repeat
457
- if not savePanelOpen then exit repeat
458
- if not my pressAccessibilityButtonIfPresent(saveWindow, {"Save"}) then key code 36
459
- delay 0.2
460
- end repeat
461
- my pressAccessibilityButtonIfPresent(saveWindow, {"Replace"})
462
558
  return my canonicalExportResponse("export-requested", "", "", "complete")
463
559
  on error errorMessage number errorNumber
464
560
  set cleanupComplete to my cleanupCanonicalExport(finalCut)
@@ -493,12 +589,19 @@ export function createFinalCutNativeTargetResolver(native) {
493
589
  if (located.status === "none" || located.occurrences.length === 0) {
494
590
  throw new Error(`TARGET_MISMATCH: Final Cut timeline has no occurrence for ${query}`);
495
591
  }
496
- if (located.status !== "unique" || located.occurrences.length !== 1) {
497
- throw new Error(`AMBIGUOUS_PROJECT_TARGET: Final Cut timeline has multiple occurrences for ${query}`);
592
+ const matchingOccurrences = located.occurrences.filter((candidate) => candidate.start && candidate.duration && clip.startTime && clip.durationTime
593
+ && sameRationalText(candidate.start, clip.startTime)
594
+ && sameRationalText(candidate.duration, clip.durationTime));
595
+ if (matchingOccurrences.length === 0) {
596
+ throw new Error(`TARGET_MISMATCH: native occurrence coordinates changed for ${clip.id}`);
498
597
  }
499
- const occurrence = located.occurrences[0];
598
+ if (matchingOccurrences.length !== 1) {
599
+ throw new Error(`AMBIGUOUS_PROJECT_TARGET: Final Cut timeline occurrence coordinates are not unique for ${clip.id}`);
600
+ }
601
+ const occurrence = matchingOccurrences[0];
602
+ await native.selectOccurrence?.(occurrence.handle);
500
603
  const occurrenceIdentity = occurrence.identity ?? occurrence.nativeIdentity;
501
- if (!occurrenceIdentity) {
604
+ if (!occurrenceIdentity && !native.selectOccurrence) {
502
605
  throw new Error(`TARGET_MISMATCH: native occurrence has no stable identity for ${clip.id}`);
503
606
  }
504
607
  if (!occurrence.sequenceId) {
@@ -1400,11 +1503,17 @@ function sameRevision(left, right) {
1400
1503
  }
1401
1504
  async function executeCanonicalAppleScript(script) {
1402
1505
  try {
1403
- const result = await execFile("osascript", ["-e", script], { maxBuffer: 1_000_000 });
1506
+ const result = await execFile("osascript", ["-e", script], {
1507
+ maxBuffer: 1_000_000,
1508
+ timeout: CANONICAL_APPLE_EVENT_TIMEOUT_MS,
1509
+ });
1404
1510
  return result.stdout.trim();
1405
1511
  }
1406
1512
  catch (error) {
1407
1513
  const detail = error instanceof Error ? error.message : String(error);
1514
+ if (detail.includes("ETIMEDOUT") || detail.includes("timed out")) {
1515
+ throw new Error(`FINAL_CUT_CANONICAL_AUTOMATION_TIMEOUT: Export XML AppleEvent exceeded ${CANONICAL_APPLE_EVENT_TIMEOUT_MS}ms`);
1516
+ }
1408
1517
  if (detail.includes("not authorized") || detail.includes("-1743") || detail.includes("-25211")) {
1409
1518
  throw new Error(`FINAL_CUT_CANONICAL_PERMISSION_REQUIRED: ${detail}`);
1410
1519
  }
@@ -32,7 +32,8 @@ export class DisposableNativeEditWorkflow {
32
32
  if (target.name === request.name) {
33
33
  throw new Error("INVALID_OPERATION: disposable native rename must change the target name");
34
34
  }
35
- const nativeTarget = await this.assertNativeTarget(before, target.name);
35
+ await this.options.prepareTarget?.(target, before);
36
+ const nativeTarget = await this.assertNativeTarget(before, target);
36
37
  const previewToken = `disposable-native-preview-${randomToken()}`;
37
38
  const expiresAt = this.now() + this.previewTtlMs;
38
39
  this.prunePreviews();
@@ -40,7 +41,12 @@ export class DisposableNativeEditWorkflow {
40
41
  return {
41
42
  previewToken,
42
43
  operation: { type: "rename-selected-clip", name: request.name },
43
- target: { clipId: target.id, name: target.name, ...(nativeTarget.identity ? { identity: nativeTarget.identity } : {}) },
44
+ target: {
45
+ clipId: target.id,
46
+ name: target.name,
47
+ ...(nativeTarget.identity ? { identity: nativeTarget.identity } : {}),
48
+ ...(nativeTarget.occurrenceIndex ? { occurrenceIndex: nativeTarget.occurrenceIndex } : {}),
49
+ },
44
50
  projectId: before.projectId,
45
51
  sequenceId: before.timeline.id,
46
52
  targetIdentity: nativeTarget.identity ?? target.id,
@@ -62,7 +68,12 @@ export class DisposableNativeEditWorkflow {
62
68
  return {
63
69
  previewToken,
64
70
  operation: { type: "rename-selected-clip", name: preview.request.name },
65
- target: { clipId: target.id, name: target.name, ...(preview.nativeTarget.identity ? { identity: preview.nativeTarget.identity } : {}) },
71
+ target: {
72
+ clipId: target.id,
73
+ name: target.name,
74
+ ...(preview.nativeTarget.identity ? { identity: preview.nativeTarget.identity } : {}),
75
+ ...(preview.nativeTarget.occurrenceIndex ? { occurrenceIndex: preview.nativeTarget.occurrenceIndex } : {}),
76
+ },
66
77
  projectId: preview.before.projectId,
67
78
  sequenceId: preview.before.timeline.id,
68
79
  targetIdentity: preview.nativeTarget.identity ?? target.id,
@@ -85,7 +96,8 @@ export class DisposableNativeEditWorkflow {
85
96
  if (!currentTarget || currentTarget.name !== preview.before.timeline.clips.find((clip) => clip.id === preview.request.clipId)?.name) {
86
97
  throw new Error("TARGET_MISMATCH: canonical target changed after disposable native preview");
87
98
  }
88
- await this.assertNativeTarget(current, currentTarget.name, preview.nativeTarget, options.signal);
99
+ await this.options.prepareTarget?.(currentTarget, current);
100
+ await this.assertNativeTarget(current, currentTarget, preview.nativeTarget, options.signal);
89
101
  options.onMutationStart?.();
90
102
  const native = await this.options.native.edit({ type: "rename-selected-clip", name: preview.request.name }, { signal: options.signal });
91
103
  let after;
@@ -184,11 +196,17 @@ export class DisposableNativeEditWorkflow {
184
196
  throw new Error(`CAPABILITY_UNAVAILABLE: disposable native canonical snapshot (${String(error)})`);
185
197
  });
186
198
  const editor = capabilities.editor;
199
+ const activeCanonicalTarget = editor.canonicalTimelineMode === "canonical-read"
200
+ && editor.projectRead
201
+ && editor.timelineSnapshotRead
202
+ && editor.projectCatalogRead
203
+ && editor.projectSelection === false
204
+ && editor.projectSelectionMode === "unavailable";
187
205
  if (editor.canonicalTimelineMode === "metadata-only"
188
206
  || !editor.projectRead
189
207
  || !editor.timelineSnapshotRead
190
208
  || !editor.projectCatalogRead
191
- || !editor.projectSelection) {
209
+ || (!editor.projectSelection && !activeCanonicalTarget)) {
192
210
  throw new Error(`CAPABILITY_UNAVAILABLE: disposable native canonical snapshot is unavailable during ${stage}`);
193
211
  }
194
212
  try {
@@ -198,7 +216,7 @@ export class DisposableNativeEditWorkflow {
198
216
  throw new Error(`CAPABILITY_UNAVAILABLE: disposable native canonical snapshot (${String(error)})`);
199
217
  }
200
218
  }
201
- async assertNativeTarget(snapshot, expectedName, previousTarget, signal) {
219
+ async assertNativeTarget(snapshot, expectedTarget, previousTarget, signal) {
202
220
  const capabilities = this.options.native.capabilities();
203
221
  assertNativeCapabilities(capabilities);
204
222
  const context = await this.options.native.inspect({ signal });
@@ -211,12 +229,23 @@ export class DisposableNativeEditWorkflow {
211
229
  if (context.sequence && context.sequence !== snapshot.timeline.name) {
212
230
  throw new Error("TARGET_MISMATCH: native sequence does not match canonical timeline");
213
231
  }
214
- if (context.target.kind !== "selected-clip" || context.target.name !== expectedName) {
232
+ if (context.target.kind !== "selected-clip" || context.target.name !== expectedTarget.name) {
215
233
  throw new Error("TARGET_MISMATCH: native selected clip does not match the canonical target");
216
234
  }
235
+ const expectedOccurrenceIndex = snapshot.timeline.clips.findIndex((clip) => clip.id === expectedTarget.id) + 1;
236
+ const sameNameCount = snapshot.timeline.clips.filter((clip) => clip.name === expectedTarget.name).length;
237
+ if (context.target.occurrenceIndex !== undefined && context.target.occurrenceIndex !== expectedOccurrenceIndex) {
238
+ throw new Error("TARGET_MISMATCH: native selected clip occurrence does not match the canonical target");
239
+ }
240
+ if (sameNameCount > 1 && context.target.occurrenceIndex === undefined) {
241
+ throw new Error("TARGET_MISMATCH: native selected clip occurrence is not uniquely bound to the canonical target");
242
+ }
217
243
  if (previousTarget?.identity && previousTarget.identity !== context.target.identity) {
218
244
  throw new Error("TARGET_MISMATCH: native selected clip identity changed after disposable preview");
219
245
  }
246
+ if (previousTarget?.occurrenceIndex !== undefined && previousTarget.occurrenceIndex !== context.target.occurrenceIndex) {
247
+ throw new Error("TARGET_MISMATCH: native selected clip occurrence changed after disposable preview");
248
+ }
220
249
  return context.target;
221
250
  }
222
251
  async compensate(operationId, before, clipId, cause, code) {
@@ -16,6 +16,7 @@ export * from "./background-export.js";
16
16
  export * from "./background-materialization.js";
17
17
  export * from "./library-inspection.js";
18
18
  export * from "./sqlite-inspection.js";
19
+ export * from "./sqlite-wal-observation.js";
19
20
  export * from "./sqlite-experiment.js";
20
21
  export * from "./shadow-mutation.js";
21
22
  export * from "./native-operation.js";
@@ -23,3 +24,4 @@ export * from "./native-session.js";
23
24
  export * from "./timeline-ir-fcpxml.js";
24
25
  export * from "./fcpxml-console-experiment.js";
25
26
  export * from "./unattended-editing.js";
27
+ export * from "./pasteboard-snapshot.js";
@@ -6,6 +6,13 @@ import { createProjectSelectionResult, withCanonicalTimelineMode, withCapability
6
6
  export const FINAL_CUT_LIVE_PROTOCOL_VERSION = 1;
7
7
  /** Shared deterministic endpoint used by both the Node client and Swift host. */
8
8
  export const DEFAULT_FINAL_CUT_LIVE_SOCKET = join(homedir(), "Library/Containers/com.framekit.finalcut.workflow.extension/Data/framekit.sock");
9
+ const READ_ONLY_LIVE_METHODS = new Set([
10
+ "capabilities",
11
+ "state",
12
+ "changes",
13
+ "projects",
14
+ "snapshot",
15
+ ]);
9
16
  /** Newline-delimited JSON transport for the local Workflow Extension socket. */
10
17
  export class UnixSocketFinalCutLiveTransport {
11
18
  socketPath;
@@ -14,7 +21,23 @@ export class UnixSocketFinalCutLiveTransport {
14
21
  this.socketPath = socketPath;
15
22
  this.timeoutMs = timeoutMs;
16
23
  }
17
- request(request) {
24
+ async request(request) {
25
+ const attempts = READ_ONLY_LIVE_METHODS.has(request.method) ? 3 : 1;
26
+ let lastError;
27
+ for (let attempt = 0; attempt < attempts; attempt += 1) {
28
+ try {
29
+ return await this.requestOnce(request);
30
+ }
31
+ catch (error) {
32
+ lastError = error;
33
+ if (attempt === attempts - 1)
34
+ throw error;
35
+ await new Promise((resolve) => setTimeout(resolve, 50 * (attempt + 1)));
36
+ }
37
+ }
38
+ throw lastError instanceof Error ? lastError : new Error(String(lastError));
39
+ }
40
+ requestOnce(request) {
18
41
  return new Promise((resolve, reject) => {
19
42
  let settled = false;
20
43
  let buffer = "";
@@ -144,6 +167,19 @@ export class FinalCutLiveAdapter {
144
167
  changes.forEach((change, index) => validateLiveChange(change, `live change ${index}`));
145
168
  return changes;
146
169
  }
170
+ async deliverFcpxml(request) {
171
+ requireNonEmpty(request.artifactPath, "FCPXML artifact path");
172
+ const response = await this.request({
173
+ method: "deliver-fcpxml",
174
+ artifactPath: request.artifactPath,
175
+ ...(request.targetLibraryUid ? { targetLibraryUid: request.targetLibraryUid } : {}),
176
+ activates: request.activates,
177
+ });
178
+ if (!response.delivery)
179
+ throw new Error("FINAL_CUT_LIVE_PROTOCOL: FCPXML delivery response was empty");
180
+ validateFcpxmlDelivery(response.delivery, request);
181
+ return response.delivery;
182
+ }
147
183
  async listProjects() {
148
184
  const response = await this.request({ method: "projects" });
149
185
  if (!response.catalog)
@@ -188,6 +224,25 @@ export class FinalCutLiveAdapter {
188
224
  export function createFinalCutLiveAdapter(socketPath = process.env.FRAMEKIT_FINAL_CUT_SOCKET ?? DEFAULT_FINAL_CUT_LIVE_SOCKET) {
189
225
  return new FinalCutLiveAdapter(new UnixSocketFinalCutLiveTransport(socketPath), socketPath);
190
226
  }
227
+ function validateFcpxmlDelivery(delivery, request) {
228
+ if (!["dispatched", "user-interaction-required", "failed"].includes(delivery.status)
229
+ || delivery.route !== "background-document-open"
230
+ || typeof delivery.attempted !== "boolean"
231
+ || typeof delivery.imported !== "boolean"
232
+ || delivery.requestedActivates !== request.activates
233
+ || !["preserved", "activated", "unknown"].includes(delivery.activation)
234
+ || !["none", "prompted", "displayed", "unknown"].includes(delivery.ui)
235
+ || !delivery.target
236
+ || !["requested-unverified", "unavailable"].includes(delivery.target.guarantee)) {
237
+ throw new Error("FINAL_CUT_LIVE_PROTOCOL: invalid FCPXML delivery response");
238
+ }
239
+ if (delivery.status !== "dispatched" && (!delivery.error?.code?.trim() || !delivery.error.message.trim())) {
240
+ throw new Error("FINAL_CUT_LIVE_PROTOCOL: blocked FCPXML delivery response is missing an error");
241
+ }
242
+ if (request.targetLibraryUid && delivery.target.requestedLibraryUid !== request.targetLibraryUid) {
243
+ throw new Error("FINAL_CUT_LIVE_PROTOCOL: FCPXML delivery target does not match the request");
244
+ }
245
+ }
191
246
  function validateCanonicalSnapshot(snapshot) {
192
247
  requireNonEmpty(snapshot.projectId, "project id");
193
248
  requireNonEmpty(snapshot.projectName, "project name");