@morshoto/framekit 0.1.4 → 0.1.6

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 (37) hide show
  1. package/README.md +2 -2
  2. package/dist-package/adapters/final-cut/typescript/src/analyzers.js +29 -2
  3. package/dist-package/adapters/final-cut/typescript/src/assets.js +89 -3
  4. package/dist-package/adapters/final-cut/typescript/src/canonical.js +431 -0
  5. package/dist-package/adapters/final-cut/typescript/src/connection.js +19 -4
  6. package/dist-package/adapters/final-cut/typescript/src/fcpxml.js +212 -13
  7. package/dist-package/adapters/final-cut/typescript/src/index.js +1 -0
  8. package/dist-package/adapters/final-cut/typescript/src/native.js +1026 -7
  9. package/dist-package/adapters/final-cut/typescript/src/publisher.js +207 -30
  10. package/dist-package/adapters/final-cut/typescript/src/session.js +69 -8
  11. package/dist-package/apps/mcp-server/src/main.js +49 -11
  12. package/dist-package/apps/mcp-server/src/routing.js +15 -0
  13. package/dist-package/apps/mcp-server/src/server.js +289 -68
  14. package/dist-package/apps/mcp-server/src/version.js +34 -0
  15. package/dist-package/packages/runtime/src/application/media-analysis-service.js +119 -15
  16. package/dist-package/packages/runtime/src/application/project-service.js +21 -2
  17. package/dist-package/packages/runtime/src/audio/dialogue-normalization.js +9 -0
  18. package/dist-package/packages/runtime/src/capabilities.js +90 -10
  19. package/dist-package/packages/runtime/src/context/context-engine.js +10 -1
  20. package/dist-package/packages/runtime/src/domain/editing.js +27 -1
  21. package/dist-package/packages/runtime/src/domain/media.js +1 -0
  22. package/dist-package/packages/runtime/src/domain/skills.js +2 -0
  23. package/dist-package/packages/runtime/src/editing/edit-service.js +82 -4
  24. package/dist-package/packages/runtime/src/editing/filler-removal-service.js +31 -7
  25. package/dist-package/packages/runtime/src/index.js +2 -0
  26. package/dist-package/packages/runtime/src/planning/rough-cut.js +9 -3
  27. package/dist-package/packages/runtime/src/runtime.js +2 -2
  28. package/dist-package/packages/runtime/src/skills/builtin.js +314 -39
  29. package/dist-package/packages/runtime/src/skills/requirements.js +1 -0
  30. package/dist-package/packages/runtime/src/skills/runtime.js +33 -8
  31. package/dist-package/packages/runtime/src/speech/analysis.js +301 -0
  32. package/dist-package/packages/runtime/src/speech/mapping.js +227 -0
  33. package/dist-package/packages/runtime/src/timeline/rational-time.js +5 -0
  34. package/dist-package/packages/runtime/src/verification/verification.js +81 -4
  35. package/dist-package/packages/testkit/src/fixture-analyzers.js +1 -0
  36. package/dist-package/packages/testkit/src/in-memory-editor.js +126 -0
  37. package/package.json +8 -2
package/README.md CHANGED
@@ -4,7 +4,7 @@
4
4
 
5
5
  <p align="center">
6
6
  <img src="https://img.shields.io/badge/Node.js-20%2B-339933?logo=node.js&logoColor=white" alt="Node.js 20 or newer" />
7
- <img src="https://img.shields.io/badge/pnpm-11.10.0-F69220?logo=pnpm&logoColor=white" alt="pnpm 11.10.0" />
7
+ <img src="https://img.shields.io/badge/pnpm-12.3.4-F69220?logo=pnpm&logoColor=white" alt="pnpm 12.3.4" />
8
8
  <img src="https://img.shields.io/badge/Final%20Cut%20Pro-macOS-000000?logo=apple&logoColor=white" alt="Final Cut Pro on macOS" />
9
9
  <a href="https://discord.gg/Dmp8FSF4vg"><img src="https://img.shields.io/badge/Discord-Join%20Chat-5865F2?logo=discord&logoColor=white" alt="Join the Framekit Discord" /></a>
10
10
  </p>
@@ -18,7 +18,7 @@ Agentic video editing runtime and MCP server for Final Cut Pro.
18
18
  For repository development, you need:
19
19
 
20
20
  - Node.js 20 or newer;
21
- - pnpm 11.10.0;
21
+ - pnpm 12.3.4;
22
22
  - Xcode 16.4 and the macOS 15.5 SDK for native Final Cut work.
23
23
 
24
24
  The Xcode requirement is only needed for the native Workflow Extension. For the
@@ -1,5 +1,6 @@
1
1
  import { spawn } from "node:child_process";
2
2
  import { access } from "node:fs/promises";
3
+ import { bindSpeechAnalysis } from "../../../../packages/runtime/src/index.js";
3
4
  export function createCommandAnalyzers(options) {
4
5
  return {
5
6
  ...(options.speechCommand ? { speechAnalyzer: new CommandSpeechAnalyzer({ command: options.speechCommand, timeoutMs: options.timeoutMs }) } : {}),
@@ -11,11 +12,18 @@ export function createCommandAnalyzers(options) {
11
12
  export class CommandSpeechAnalyzer {
12
13
  options;
13
14
  descriptor = { id: "command.speech", provider: "command" };
15
+ capabilities = { transcription: true, vad: false };
14
16
  constructor(options) {
15
17
  this.options = options;
16
18
  }
17
19
  async analyze(input, range) {
18
- return runCommand(this.options, { ...input, range }, "speech");
20
+ const result = await runCommand(this.options, { ...input, range }, "speech");
21
+ try {
22
+ return bindSpeechAnalysis(result, { input, range, provider: this.descriptor });
23
+ }
24
+ catch (error) {
25
+ throw new Error(`ANALYZER_INVALID_OUTPUT: speech analyzer returned invalid JSON or schema: ${String(error)}`);
26
+ }
19
27
  }
20
28
  }
21
29
  export class CommandAudioAnalyzer {
@@ -97,9 +105,28 @@ async function runCommand(options, request, kind) {
97
105
  reject(new Error(`ANALYZER_INVALID_OUTPUT: ${kind} analyzer returned invalid JSON or schema: ${String(error)}`));
98
106
  }
99
107
  });
100
- child.stdin.end(JSON.stringify(request));
108
+ child.stdin.end(JSON.stringify(commandRequest(request, kind)));
101
109
  });
102
110
  }
111
+ function commandRequest(request, kind) {
112
+ if (kind !== "speech")
113
+ return request;
114
+ return {
115
+ schemaVersion: 1,
116
+ media: sourceIdentityOf(request.media),
117
+ revision: request.project.revision,
118
+ ...(request.range ? { range: structuredClone(request.range) } : {}),
119
+ };
120
+ }
121
+ function sourceIdentityOf(media) {
122
+ return {
123
+ mediaId: media.mediaId,
124
+ source: media.source,
125
+ ...(media.sourceDigest ? { sourceDigest: media.sourceDigest } : {}),
126
+ ...(media.mediaKind ? { mediaKind: media.mediaKind } : {}),
127
+ ...(media.duration !== undefined ? { duration: media.duration } : {}),
128
+ };
129
+ }
103
130
  function validateResult(value, kind) {
104
131
  if (!value || typeof value !== "object")
105
132
  throw new Error("result must be an object");
@@ -19,14 +19,31 @@ export function defaultFinalCutAssetRoots() {
19
19
  }
20
20
  export class FinalCutAssetRegistry {
21
21
  roots;
22
+ nativeTitleProvider;
22
23
  cached;
23
24
  constructor(options = {}) {
24
25
  this.roots = (options.roots ?? defaultFinalCutAssetRoots()).map((root) => resolve(root));
26
+ this.nativeTitleProvider = options.nativeTitleProvider;
25
27
  }
26
28
  async listAssets(query) {
27
29
  if (!this.cached)
28
30
  this.cached = await this.scan();
29
- return filterAssets(this.cached, query);
31
+ const filesystemAssets = filterAssets(this.cached, query);
32
+ if (!this.nativeTitleProvider || (query?.kind && query.kind !== "title"))
33
+ return filesystemAssets;
34
+ let nativeTitles;
35
+ try {
36
+ nativeTitles = await this.nativeTitleProvider.searchTitles(query?.query ?? "");
37
+ }
38
+ catch (error) {
39
+ // Filesystem assets remain usable when the optional native browser is
40
+ // unavailable, but keep the native diagnostic visible in the response.
41
+ if (filesystemAssets.length > 0)
42
+ return withNativeTitleDiagnostic(filesystemAssets, error);
43
+ throw error;
44
+ }
45
+ const composed = [...filesystemAssets, ...nativeTitles.map(nativeTitleAsset)];
46
+ return filterAssets(dedupeAssets(composed), query);
30
47
  }
31
48
  refresh() {
32
49
  this.cached = undefined;
@@ -73,14 +90,83 @@ async function scanCategory(directory, kind, assets) {
73
90
  const path = join(directory, entry.name);
74
91
  const metadata = await readMetadata(path);
75
92
  assets.push({
76
- id: path,
93
+ id: `filesystem:${kind}:${path}`,
77
94
  kind,
78
95
  name: metadata.name ?? basename(entry.name, extension(entry.name)),
79
96
  vendor: metadata.vendor ?? "Unknown",
80
- metadata: { path, ...metadata },
97
+ metadata: {
98
+ path,
99
+ ...metadata,
100
+ identity: path,
101
+ provider: "filesystem-motion-template",
102
+ source: "filesystem",
103
+ discovery: {
104
+ backend: "filesystem-motion-template",
105
+ guarantee: "observed",
106
+ },
107
+ ...(kind === "title"
108
+ ? {
109
+ placement: {
110
+ backend: "final-cut-accessibility",
111
+ guarantee: "native-verified",
112
+ operation: "editor.native.title.add",
113
+ },
114
+ }
115
+ : {}),
116
+ },
81
117
  });
82
118
  }
83
119
  }
120
+ function nativeTitleAsset(match) {
121
+ if (!match.id.startsWith("final-cut:title:") || !match.identity.trim() || !match.name.trim()) {
122
+ throw new Error("FINAL_CUT_NATIVE_TITLE_ID_UNAVAILABLE: native title provider returned an unstable identity");
123
+ }
124
+ return {
125
+ id: match.id,
126
+ kind: "title",
127
+ name: match.name,
128
+ vendor: match.vendor,
129
+ metadata: {
130
+ identity: match.identity,
131
+ provider: "final-cut-accessibility",
132
+ source: "final-cut-titles-browser",
133
+ discovery: {
134
+ backend: "final-cut-accessibility",
135
+ guarantee: "observed",
136
+ },
137
+ placement: {
138
+ backend: "final-cut-accessibility",
139
+ guarantee: "native-verified",
140
+ operation: "editor.native.title.add",
141
+ },
142
+ },
143
+ };
144
+ }
145
+ function dedupeAssets(assets) {
146
+ return assets
147
+ .sort((left, right) => `${left.kind}:${left.name}:${left.id}`.localeCompare(`${right.kind}:${right.name}:${right.id}`))
148
+ .filter((asset, index, all) => index === all.findIndex((candidate) => candidate.id === asset.id));
149
+ }
150
+ function withNativeTitleDiagnostic(assets, error) {
151
+ const native = {
152
+ backend: "final-cut-accessibility",
153
+ guarantee: "none",
154
+ unavailableReason: error instanceof Error ? error.message : String(error),
155
+ };
156
+ return assets.map((asset) => {
157
+ const discovery = asset.metadata.discovery;
158
+ return {
159
+ ...asset,
160
+ metadata: {
161
+ ...asset.metadata,
162
+ discovery: {
163
+ ...(typeof discovery === "object" && discovery !== null ? discovery : {}),
164
+ native: { ...native },
165
+ },
166
+ },
167
+ };
168
+ });
169
+ }
84
170
  async function readMetadata(bundlePath) {
85
171
  try {
86
172
  const infoPath = join(bundlePath, "Contents", "Info.plist");
@@ -0,0 +1,431 @@
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, withCapabilityFamilies, } 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
+ if not frontmost then error "FINAL_CUT_CANONICAL_NOT_FRONTMOST: Final Cut Pro must be frontmost"
90
+ set finalCut to it
91
+ set fileMenu to menu "File" of menu bar 1
92
+ set exportCommand to missing value
93
+ try
94
+ set exportCommand to my findMenuItem(fileMenu, {"Export XML…", "Export XML..."}, 10, "FINAL_CUT_CANONICAL_EXPORT_MENU_UNAVAILABLE: File > Export XML was not exposed")
95
+ on error
96
+ set exportMenuItem to my findMenuItem(fileMenu, {"Export"}, 10, "FINAL_CUT_CANONICAL_EXPORT_MENU_UNAVAILABLE: File > Export was not exposed")
97
+ perform action "AXPress" of exportMenuItem
98
+ set exportMenu to missing value
99
+ repeat 100 times
100
+ try
101
+ if exists menu "Export" of exportMenuItem then
102
+ set exportMenu to menu "Export" of exportMenuItem
103
+ exit repeat
104
+ end if
105
+ end try
106
+ delay 0.1
107
+ end repeat
108
+ if exportMenu is missing value then error "FINAL_CUT_CANONICAL_EXPORT_MENU_UNAVAILABLE: Export submenu was not exposed"
109
+ set exportCommand to my findMenuItem(exportMenu, {"XML…", "XML..."}, 10, "FINAL_CUT_CANONICAL_EXPORT_MENU_UNAVAILABLE: Export XML command was not exposed")
110
+ end try
111
+ perform action "AXPress" of exportCommand
112
+ set exportWindow to my findWindow(finalCut, {"Export XML", "XML"}, 15, "FINAL_CUT_CANONICAL_EXPORT_WINDOW_UNAVAILABLE: Export XML window did not appear")
113
+ my pressButtonIfPresent(exportWindow, {"Next…", "Next...", "Export"})
114
+ delay 0.2
115
+ set saveWindow to my findWindow(finalCut, {"Save", "Export XML"}, 15, "FINAL_CUT_CANONICAL_SAVE_WINDOW_UNAVAILABLE: XML save window did not appear")
116
+ keystroke "g" using {command down, shift down}
117
+ repeat 50 times
118
+ try
119
+ if exists sheet 1 of saveWindow then exit repeat
120
+ end try
121
+ delay 0.1
122
+ end repeat
123
+ if not (exists sheet 1 of saveWindow) then error "FINAL_CUT_CANONICAL_SAVE_WINDOW_UNAVAILABLE: save path sheet did not appear"
124
+ set pathSheet to sheet 1 of saveWindow
125
+ if (count of text fields of pathSheet) is 0 then error "FINAL_CUT_CANONICAL_SAVE_PATH_UNAVAILABLE: save path field did not appear"
126
+ set value of text field 1 of pathSheet to ${appleScriptString(exportPath)}
127
+ key code 36
128
+ delay 0.2
129
+ if exists button "Save" of saveWindow then click button "Save" of saveWindow
130
+ delay 0.2
131
+ if exists button "Replace" of saveWindow then click button "Replace" of saveWindow
132
+ return "canonical-export-requested"
133
+ end tell
134
+ end tell`;
135
+ }
136
+ export function createFinalCutNativeTargetResolver(native) {
137
+ return async (clip, snapshot) => {
138
+ if (!clip.mediaId)
139
+ throw new Error(`TARGET_MISMATCH: occurrence ${clip.id} has no media binding`);
140
+ const media = snapshot.media.find(({ mediaId }) => mediaId === clip.mediaId);
141
+ if (!media?.source)
142
+ throw new Error(`TARGET_MISMATCH: media ${clip.mediaId} has no source binding`);
143
+ const query = sourceBasename(media.source);
144
+ if (!query)
145
+ throw new Error(`TARGET_MISMATCH: media ${clip.mediaId} has no searchable source basename`);
146
+ const matches = (await native.searchMedia(query)).filter((match) => match.name.toLocaleLowerCase() === query.toLocaleLowerCase());
147
+ if (matches.length === 0)
148
+ throw new Error(`TARGET_MISMATCH: Final Cut Browser has no exact media match for ${query}`);
149
+ if (matches.length > 1)
150
+ throw new Error(`AMBIGUOUS_PROJECT_TARGET: Final Cut Browser has multiple exact media matches for ${query}`);
151
+ const match = matches[0];
152
+ if (!match.sourceIdentity)
153
+ throw new Error("TARGET_MISMATCH: exact Browser media has no stable source identity");
154
+ const located = await native.locateOccurrence(match.handle);
155
+ if (located.status === "none" || located.occurrences.length === 0) {
156
+ throw new Error(`TARGET_MISMATCH: Final Cut timeline has no occurrence for ${query}`);
157
+ }
158
+ if (located.status !== "unique" || located.occurrences.length !== 1) {
159
+ throw new Error(`AMBIGUOUS_PROJECT_TARGET: Final Cut timeline has multiple occurrences for ${query}`);
160
+ }
161
+ const occurrence = located.occurrences[0];
162
+ if (occurrence.sourceIdentity && occurrence.sourceIdentity !== match.sourceIdentity) {
163
+ throw new Error(`TARGET_MISMATCH: native occurrence source identity changed for ${clip.id}`);
164
+ }
165
+ if (!occurrence.start || !occurrence.duration || !clip.startTime || !clip.durationTime) {
166
+ throw new Error(`TARGET_MISMATCH: exact timeline coordinates are unavailable for ${clip.id}`);
167
+ }
168
+ if (!sameRationalText(occurrence.start, clip.startTime) || !sameRationalText(occurrence.duration, clip.durationTime)) {
169
+ throw new Error(`TARGET_MISMATCH: native occurrence coordinates changed for ${clip.id}`);
170
+ }
171
+ };
172
+ }
173
+ /**
174
+ * Canonical provider for the headed Final Cut UI path.
175
+ *
176
+ * `readSnapshot` must export the currently active Final Cut project through
177
+ * Final Cut itself. It is deliberately injected so the provider cannot fall
178
+ * back to an arbitrary FCPXML artifact. Native mutation is separately bound
179
+ * to one exported occurrence before Accessibility is allowed to edit it.
180
+ */
181
+ export class FinalCutCanonicalNativeProvider {
182
+ live;
183
+ native;
184
+ readSnapshotSource;
185
+ resolveTarget;
186
+ lastDigest;
187
+ lastSnapshot;
188
+ revisionSequence = 0;
189
+ revision;
190
+ pending;
191
+ constructor(options) {
192
+ this.live = options.live;
193
+ this.native = options.native;
194
+ this.readSnapshotSource = options.readSnapshot;
195
+ this.resolveTarget = options.resolveTarget;
196
+ }
197
+ async getIdentity() {
198
+ const identity = await this.live.getIdentity();
199
+ return { ...identity, backend: "final-cut-native-canonical" };
200
+ }
201
+ async getCapabilities() {
202
+ return withCapabilityFamilies({
203
+ editor: {
204
+ projectRead: true,
205
+ timelineSnapshotRead: true,
206
+ timelineWrite: true,
207
+ timelineArtifactWrite: false,
208
+ readAfterWrite: true,
209
+ incrementalChanges: true,
210
+ rollback: true,
211
+ assetDiscovery: false,
212
+ liveStateRead: true,
213
+ playheadWrite: false,
214
+ frameCapture: false,
215
+ playbackControl: false,
216
+ projectCatalogRead: true,
217
+ projectSelection: true,
218
+ },
219
+ analyzers: {
220
+ speechTranscribe: false,
221
+ speechVad: false,
222
+ audioLoudness: false,
223
+ visualTrack: false,
224
+ },
225
+ }, {
226
+ backend: "final-cut-native-canonical",
227
+ connectionBackend: "workflow-extension-ipc",
228
+ canonicalDocument: { read: true, write: true, artifactWrite: false },
229
+ });
230
+ }
231
+ async read() {
232
+ return this.readProject();
233
+ }
234
+ async readProject() {
235
+ const snapshot = await this.readSnapshotSource();
236
+ await this.assertActiveTarget(snapshot);
237
+ const digest = canonicalSnapshotDigest(snapshot);
238
+ if (digest !== this.lastDigest || !this.revision) {
239
+ this.revisionSequence = Math.max(this.revisionSequence + 1, snapshot.revision.sequence + 1);
240
+ this.lastDigest = digest;
241
+ this.revision = {
242
+ id: `canonical:${digest}`,
243
+ sequence: this.revisionSequence,
244
+ timestamp: new Date().toISOString(),
245
+ };
246
+ }
247
+ this.lastSnapshot = { ...snapshot, revision: this.revision };
248
+ return structuredClone(this.lastSnapshot);
249
+ }
250
+ async apply(operation, expectedRevision) {
251
+ const before = await this.readProject();
252
+ assertSameRevision(expectedRevision, before.revision);
253
+ if (operation.type !== "rename-clip") {
254
+ throw new Error(`CAPABILITY_UNAVAILABLE: final-cut native canonical provider does not support ${operation.type}`);
255
+ }
256
+ const clip = before.timeline.clips.find(({ id }) => id === operation.clipId);
257
+ if (!clip)
258
+ throw new Error(`CLIP_NOT_FOUND: ${operation.clipId}`);
259
+ await this.resolveTarget(clip, before);
260
+ const nativeResult = await this.native.renameSelectedClip(operation.name);
261
+ if (!nativeResult.operationId || !nativeResult.undoAvailable) {
262
+ throw new Error("FINAL_CUT_CANONICAL_UNDO_UNAVAILABLE: native rename did not expose Undo");
263
+ }
264
+ this.pending = {
265
+ operationId: nativeResult.operationId,
266
+ beforeDigest: canonicalSnapshotDigest(before),
267
+ beforeRevision: before.revision,
268
+ afterRevision: before.revision,
269
+ };
270
+ try {
271
+ const after = await this.readProject();
272
+ const afterClip = after.timeline.clips.find(({ id }) => id === operation.clipId);
273
+ if (!afterClip || afterClip.name !== operation.name) {
274
+ throw new Error("FINAL_CUT_CANONICAL_READBACK_FAILED: renamed occurrence was not read back from Final Cut");
275
+ }
276
+ if (canonicalSnapshotDigest(after) === this.pending.beforeDigest) {
277
+ throw new Error("FINAL_CUT_CANONICAL_READBACK_FAILED: native edit did not change the canonical digest");
278
+ }
279
+ this.pending.afterRevision = after.revision;
280
+ return after.revision;
281
+ }
282
+ catch (error) {
283
+ try {
284
+ const undone = await this.native.undo(nativeResult.operationId);
285
+ if (!undone.undone || undone.verification?.verified !== true) {
286
+ throw new Error("native Undo did not verify restoration");
287
+ }
288
+ const restored = await this.readProject();
289
+ if (canonicalSnapshotDigest(restored) !== this.pending.beforeDigest) {
290
+ throw new Error("restored canonical digest does not match the pre-edit state");
291
+ }
292
+ }
293
+ catch (rollbackError) {
294
+ const original = error instanceof Error ? error.message : String(error);
295
+ const rollback = rollbackError instanceof Error ? rollbackError.message : String(rollbackError);
296
+ throw new Error(`FINAL_CUT_CANONICAL_ROLLBACK_FAILED: ${rollback}; original error: ${original}`);
297
+ }
298
+ finally {
299
+ this.pending = undefined;
300
+ }
301
+ throw error;
302
+ }
303
+ }
304
+ async restore(snapshot, expectedRevision) {
305
+ const current = await this.readProject();
306
+ assertSameRevision(expectedRevision, current.revision);
307
+ const pending = this.pending;
308
+ if (!pending || !sameRevision(pending.afterRevision, expectedRevision)) {
309
+ throw new Error("FINAL_CUT_CANONICAL_UNDO_STALE: native operation is not the current canonical edit");
310
+ }
311
+ if (canonicalSnapshotDigest(snapshot) !== pending.beforeDigest) {
312
+ throw new Error("FINAL_CUT_CANONICAL_UNDO_TARGET_MISMATCH: rollback target differs from the applied edit");
313
+ }
314
+ const undone = await this.native.undo(pending.operationId);
315
+ if (!undone.undone || undone.verification?.verified !== true) {
316
+ throw new Error("FINAL_CUT_CANONICAL_UNDO_FAILED: Final Cut did not verify native Undo");
317
+ }
318
+ const restored = await this.readProject();
319
+ if (canonicalSnapshotDigest(restored) !== pending.beforeDigest) {
320
+ throw new Error("FINAL_CUT_CANONICAL_UNDO_FAILED: restored canonical digest does not match the pre-edit state");
321
+ }
322
+ this.pending = undefined;
323
+ }
324
+ async listProjects() {
325
+ const snapshot = await this.readProject();
326
+ return {
327
+ projects: [{
328
+ id: snapshot.projectId,
329
+ name: snapshot.projectName,
330
+ sequences: [{ id: snapshot.timeline.id, name: snapshot.timeline.name }],
331
+ }],
332
+ activeProjectId: snapshot.projectId,
333
+ activeSequenceId: snapshot.timeline.id,
334
+ };
335
+ }
336
+ async selectProject(selection) {
337
+ const catalog = await this.listProjects();
338
+ const project = catalog.projects.find(({ id }) => id === selection.projectId);
339
+ if (!project)
340
+ throw new Error(`TARGET_MISMATCH: active project is not ${selection.projectId}`);
341
+ const sequenceId = selection.sequenceId ?? (project.sequences.length === 1 ? project.sequences[0]?.id : undefined);
342
+ if (!sequenceId)
343
+ throw new Error(`AMBIGUOUS_PROJECT_TARGET: sequenceId is required for ${selection.projectId}`);
344
+ if (sequenceId !== catalog.activeSequenceId)
345
+ throw new Error(`TARGET_MISMATCH: active sequence is not ${sequenceId}`);
346
+ return catalog;
347
+ }
348
+ async readLiveState() {
349
+ return this.live.readLiveState();
350
+ }
351
+ async liveChangesSince(revision, waitMs = 0) {
352
+ return this.live.liveChangesSince(revision, waitMs);
353
+ }
354
+ async assertActiveTarget(snapshot) {
355
+ const live = await this.live.readLiveState();
356
+ if (live.project && live.project.name !== snapshot.projectName) {
357
+ throw new Error(`TARGET_MISMATCH: exported project ${snapshot.projectName} is not active Final Cut project ${live.project.name}`);
358
+ }
359
+ if (live.sequence && live.sequence.name !== snapshot.timeline.name) {
360
+ throw new Error(`TARGET_MISMATCH: exported sequence ${snapshot.timeline.name} is not active Final Cut sequence ${live.sequence.name}`);
361
+ }
362
+ }
363
+ }
364
+ function assertSameRevision(expected, actual) {
365
+ if (!sameRevision(expected, actual))
366
+ throw new Error("STALE_CONTEXT: canonical Final Cut revision changed before mutation");
367
+ }
368
+ function sameRevision(left, right) {
369
+ return left.id === right.id && left.sequence === right.sequence;
370
+ }
371
+ async function executeCanonicalAppleScript(script) {
372
+ try {
373
+ const result = await execFile("osascript", ["-e", script], { maxBuffer: 1_000_000 });
374
+ return result.stdout.trim();
375
+ }
376
+ catch (error) {
377
+ const detail = error instanceof Error ? error.message : String(error);
378
+ if (detail.includes("not authorized") || detail.includes("-1743") || detail.includes("-25211")) {
379
+ throw new Error(`FINAL_CUT_CANONICAL_PERMISSION_REQUIRED: ${detail}`);
380
+ }
381
+ throw new Error(`FINAL_CUT_CANONICAL_AUTOMATION_FAILED: ${detail}`);
382
+ }
383
+ }
384
+ async function readCanonicalExport(path, timeoutMs, pollIntervalMs) {
385
+ const deadline = Date.now() + timeoutMs;
386
+ let previousSignature;
387
+ let lastReadError;
388
+ while (Date.now() <= deadline) {
389
+ let signature;
390
+ try {
391
+ const details = await stat(path);
392
+ if (details.isFile() && details.size > 0) {
393
+ signature = `${details.size}:${details.mtimeMs}`;
394
+ }
395
+ }
396
+ catch {
397
+ // The Save dialog may still be open.
398
+ }
399
+ if (signature && signature === previousSignature) {
400
+ try {
401
+ return await new FcpxmlDocumentAdapter(path).readProject();
402
+ }
403
+ catch (error) {
404
+ lastReadError = error;
405
+ }
406
+ }
407
+ previousSignature = signature;
408
+ await new Promise((resolve) => setTimeout(resolve, Math.min(pollIntervalMs, Math.max(1, deadline - Date.now()))));
409
+ }
410
+ const detail = lastReadError instanceof Error ? `: ${lastReadError.message}` : "";
411
+ throw new Error(`FINAL_CUT_CANONICAL_EXPORT_TIMEOUT: Final Cut did not provide a complete export at ${path}${detail}`);
412
+ }
413
+ function sourceBasename(source) {
414
+ const withoutQuery = source.split(/[?#]/, 1)[0] ?? source;
415
+ try {
416
+ const url = new URL(withoutQuery);
417
+ return basename(decodeURIComponent(url.pathname));
418
+ }
419
+ catch {
420
+ return basename(withoutQuery.replace(/^file:\/\//, ""));
421
+ }
422
+ }
423
+ function sameRationalText(value, expected) {
424
+ const match = value.trim().match(/^(-?\d+)\/(\d+)$/);
425
+ if (!match || Number(match[2]) <= 0 || Number(expected.timescale) <= 0)
426
+ return false;
427
+ return BigInt(match[1]) * BigInt(expected.timescale) === BigInt(expected.value) * BigInt(match[2]);
428
+ }
429
+ function appleScriptString(value) {
430
+ return `"${value.replaceAll("\\", "\\\\").replaceAll('"', '\\"').replace(/[\r\n]/g, " ")}"`;
431
+ }