@causyne/agent 1.20.30 → 1.20.32

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 (41) hide show
  1. package/package.json +1 -1
  2. package/src/agentLoop.js +8 -0
  3. package/src/agentLoop.ts +7 -0
  4. package/src/appChannel.js +52 -74
  5. package/src/appChannel.ts +106 -0
  6. package/src/creative/apps.js +206 -11
  7. package/src/creative/apps.ts +198 -6
  8. package/src/creative/liveBridge.js +1481 -0
  9. package/src/creative/liveBridge.ts +1829 -0
  10. package/src/creative/pipeline.js +31 -3
  11. package/src/creative/pipeline.ts +36 -7
  12. package/src/decideTools.js +3 -1
  13. package/src/decideTools.ts +3 -1
  14. package/src/decisionPolicy.js +5 -2
  15. package/src/decisionPolicy.ts +7 -1
  16. package/src/mcp/mcpRegistry.js +3 -1
  17. package/src/mcp/mcpRegistry.ts +3 -1
  18. package/src/sandbox.js +5 -1
  19. package/src/smartToolsUse.js +2 -1
  20. package/src/smartToolsUse.ts +2 -1
  21. package/src/tool-scripts/resolve_automator.py +167 -34
  22. package/src/toolPacks.js +5 -3
  23. package/src/toolPacks.ts +5 -3
  24. package/src/tools/creativeApps.js +226 -7
  25. package/src/tools/creativeApps.ts +233 -7
  26. package/src/tools/memoryWrite.js +71 -89
  27. package/src/tools/memoryWrite.ts +108 -0
  28. package/src/tools/resolveAutomator.js +356 -89
  29. package/src/tools/resolveAutomator.ts +403 -0
  30. package/src/toolsList.js +1 -1
  31. package/src/toolsList.ts +1 -1
  32. package/src/tui/consoleGuard.js +85 -0
  33. package/src/tui/consoleGuard.ts +102 -0
  34. package/src/tui/messageActionPlacement.js +8 -3
  35. package/src/tui/messageActionPlacement.ts +8 -3
  36. package/src/tui/messageInteraction.js +184 -27
  37. package/src/tui/messageInteraction.ts +221 -45
  38. package/src/tui/mouseHover.js +4 -0
  39. package/src/tui/mouseHover.ts +5 -0
  40. package/src/tui/smartLinkClick.js +353 -0
  41. package/src/tui/smartLinkClick.ts +413 -0
@@ -0,0 +1,1481 @@
1
+ import fs from 'node:fs/promises';
2
+ import fsSync from 'node:fs';
3
+ import path from 'node:path';
4
+ import os from 'node:os';
5
+ import vm from 'node:vm';
6
+ import http from 'node:http';
7
+ import { execFile } from 'node:child_process';
8
+ import { promisify } from 'node:util';
9
+ import { findUnrealEngine, findUnityEditor, findGodotEngine } from './apps.js';
10
+ import { runResolveBridge, buildResolvePlatformConfig } from '../tools/resolveAutomator.js';
11
+ const execFileAsync = promisify(execFile);
12
+ const MAX_CACHED_SELECTION_MASKS = 128;
13
+ const selectionMaskCache = new Map();
14
+ export function rememberSelectionMask(documentName, bounds, hasMask = true) {
15
+ const key = String(documentName || 'active_document').trim();
16
+ const entry = {
17
+ key,
18
+ documentName: key,
19
+ bounds: {
20
+ left: Math.round(bounds.left),
21
+ top: Math.round(bounds.top),
22
+ right: Math.round(bounds.right),
23
+ bottom: Math.round(bounds.bottom),
24
+ width: Math.max(1, Math.round(bounds.right - bounds.left)),
25
+ height: Math.max(1, Math.round(bounds.bottom - bounds.top))
26
+ },
27
+ hasMask,
28
+ capturedAt: Date.now()
29
+ };
30
+ if (selectionMaskCache.has(key))
31
+ selectionMaskCache.delete(key);
32
+ selectionMaskCache.set(key, entry);
33
+ while (selectionMaskCache.size > MAX_CACHED_SELECTION_MASKS) {
34
+ const oldestKey = selectionMaskCache.keys().next().value;
35
+ if (oldestKey === undefined)
36
+ break;
37
+ selectionMaskCache.delete(oldestKey);
38
+ }
39
+ return entry;
40
+ }
41
+ export function getLatestSelectionMask(documentName) {
42
+ if (documentName !== undefined) {
43
+ return selectionMaskCache.get(documentName) ?? null;
44
+ }
45
+ let latest = null;
46
+ for (const entry of selectionMaskCache.values()) {
47
+ if (!latest || entry.capturedAt >= latest.capturedAt)
48
+ latest = entry;
49
+ }
50
+ return latest;
51
+ }
52
+ export function clearSelectionMaskCache() {
53
+ selectionMaskCache.clear();
54
+ }
55
+ const ADOBE_HOST_ALIASES = {
56
+ photoshop: 'photoshop',
57
+ 'photo-studio': 'photoshop',
58
+ photostudio: 'photoshop',
59
+ premiere: 'premiere',
60
+ 'premiere-pro': 'premiere',
61
+ premierepro: 'premiere',
62
+ 'video-studio': 'premiere',
63
+ videostudio: 'premiere',
64
+ 'after-effects': 'after-effects',
65
+ aftereffects: 'after-effects',
66
+ 'motion-studio': 'after-effects',
67
+ motionstudio: 'after-effects',
68
+ illustrator: 'illustrator',
69
+ 'vector-studio': 'illustrator',
70
+ vectorstudio: 'illustrator',
71
+ indesign: 'indesign',
72
+ 'layout-studio': 'indesign',
73
+ layoutstudio: 'indesign',
74
+ 'media-encoder': 'media-encoder',
75
+ mediaencoder: 'media-encoder',
76
+ 'encoder-studio': 'media-encoder',
77
+ resolve: 'resolve',
78
+ 'davinci-resolve': 'resolve',
79
+ davinciresolve: 'resolve',
80
+ davinci: 'resolve',
81
+ 'cinema-studio': 'resolve',
82
+ cinemastudio: 'resolve'
83
+ };
84
+ const GAME_ENGINE_ALIASES = {
85
+ unreal: 'unreal',
86
+ 'unreal-engine': 'unreal',
87
+ unrealengine: 'unreal',
88
+ ue5: 'unreal',
89
+ ue4: 'unreal',
90
+ unity: 'unity',
91
+ 'unity-editor': 'unity',
92
+ unity3d: 'unity',
93
+ godot: 'godot',
94
+ 'godot-engine': 'godot',
95
+ godot4: 'godot'
96
+ };
97
+ export async function resolveWorkspacePath(target, workspace, mustExist) {
98
+ if (!target || typeof target !== 'string') {
99
+ throw new Error('Path must be a non-empty string');
100
+ }
101
+ const root = await fs.realpath(workspace);
102
+ const candidate = path.resolve(root, target);
103
+ if (candidate !== root && !candidate.startsWith(root + path.sep)) {
104
+ throw new Error('Path must stay inside the active workspace');
105
+ }
106
+ const parentDir = await fs.realpath(path.dirname(candidate)).catch(() => null);
107
+ if (parentDir && parentDir !== root && !parentDir.startsWith(root + path.sep)) {
108
+ throw new Error('Path parent escapes the active workspace');
109
+ }
110
+ if (mustExist) {
111
+ const real = await fs.realpath(candidate).catch(() => null);
112
+ if (!real)
113
+ throw new Error(`Workspace file does not exist: ${target}`);
114
+ if (real !== root && !real.startsWith(root + path.sep)) {
115
+ throw new Error('Resolved symlink escapes the active workspace');
116
+ }
117
+ return real;
118
+ }
119
+ return candidate;
120
+ }
121
+ export function validateAdobeLiveJob(value) {
122
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
123
+ throw new Error('Adobe live bridge job must be an object');
124
+ }
125
+ const raw = value;
126
+ const hostInput = String(raw.host ?? 'photoshop').trim().toLowerCase();
127
+ const canonicalHost = ADOBE_HOST_ALIASES[hostInput];
128
+ if (!canonicalHost) {
129
+ throw new Error(`Unsupported Adobe host "${String(raw.host)}". Supported hosts: photoshop, premiere, after-effects, illustrator, indesign, media-encoder.`);
130
+ }
131
+ const opInput = String(raw.liveOperation ?? raw.operation ?? 'inspect_active').trim();
132
+ const validOps = [
133
+ 'inspect_active',
134
+ 'export_canvas_preview',
135
+ 'place_in_active_canvas',
136
+ 'insert_in_active_timeline'
137
+ ];
138
+ if (!validOps.includes(opInput)) {
139
+ throw new Error(`Unsupported liveOperation "${opInput}". Supported: ${validOps.join(', ')}`);
140
+ }
141
+ const maxDimensionRaw = typeof raw.maxDimension === 'number' && Number.isFinite(raw.maxDimension)
142
+ ? Math.round(raw.maxDimension)
143
+ : 1024;
144
+ const maxDimension = Math.min(1024, Math.max(64, maxDimensionRaw));
145
+ let fitMode;
146
+ if (raw.fitMode !== undefined) {
147
+ const fm = String(raw.fitMode).trim();
148
+ if (!['selection', 'bounds', 'document_height', 'original'].includes(fm)) {
149
+ throw new Error('fitMode must be one of: selection, bounds, document_height, original');
150
+ }
151
+ fitMode = fm;
152
+ }
153
+ let bounds;
154
+ if (raw.bounds && typeof raw.bounds === 'object' && !Array.isArray(raw.bounds)) {
155
+ const b = raw.bounds;
156
+ const left = Number(b.left ?? 0);
157
+ const top = Number(b.top ?? 0);
158
+ const width = Number(b.width ?? 0);
159
+ const height = Number(b.height ?? 0);
160
+ if (!Number.isFinite(left) || !Number.isFinite(top) || !Number.isFinite(width) || !Number.isFinite(height) || width <= 0 || height <= 0) {
161
+ throw new Error('bounds must contain finite left, top, and positive width, height');
162
+ }
163
+ bounds = { left, top, width, height };
164
+ }
165
+ if (opInput === 'export_canvas_preview') {
166
+ if (canonicalHost !== 'photoshop' && canonicalHost !== 'illustrator') {
167
+ throw new Error('export_canvas_preview is supported for photoshop and illustrator hosts');
168
+ }
169
+ if (typeof raw.output !== 'string' || !raw.output.trim()) {
170
+ throw new Error('export_canvas_preview requires an output PNG file path inside the workspace');
171
+ }
172
+ }
173
+ if (opInput === 'place_in_active_canvas') {
174
+ if (!['photoshop', 'illustrator', 'indesign'].includes(canonicalHost)) {
175
+ throw new Error('place_in_active_canvas is supported for photoshop, illustrator, and indesign hosts');
176
+ }
177
+ if (typeof raw.input !== 'string' || !raw.input.trim()) {
178
+ throw new Error('place_in_active_canvas requires an input asset file path inside the workspace');
179
+ }
180
+ if (fitMode === 'bounds' && !bounds) {
181
+ throw new Error('place_in_active_canvas with fitMode="bounds" requires bounds { left, top, width, height }');
182
+ }
183
+ }
184
+ if (opInput === 'insert_in_active_timeline') {
185
+ if (canonicalHost !== 'premiere' && canonicalHost !== 'after-effects' && canonicalHost !== 'resolve') {
186
+ throw new Error('insert_in_active_timeline is supported for premiere, after-effects, and resolve hosts');
187
+ }
188
+ if (typeof raw.input !== 'string' || !raw.input.trim()) {
189
+ throw new Error('insert_in_active_timeline requires an input media file path inside the workspace');
190
+ }
191
+ }
192
+ return {
193
+ host: hostInput,
194
+ canonicalHost,
195
+ operation: opInput,
196
+ input: typeof raw.input === 'string' ? raw.input.trim() : undefined,
197
+ output: typeof raw.output === 'string' ? raw.output.trim() : undefined,
198
+ maxDimension,
199
+ layerOnly: Boolean(raw.layerOnly),
200
+ fitMode: fitMode ?? (bounds ? 'bounds' : 'selection'),
201
+ bounds,
202
+ applySelectionMask: raw.applySelectionMask === undefined ? true : Boolean(raw.applySelectionMask),
203
+ layerName: typeof raw.layerName === 'string' && raw.layerName.trim() ? raw.layerName.trim() : 'Causyne Placed Asset',
204
+ atPlayhead: raw.atPlayhead === undefined ? raw.start === undefined : Boolean(raw.atPlayhead),
205
+ start: typeof raw.start === 'number' && Number.isFinite(raw.start) && raw.start >= 0 ? raw.start : 0,
206
+ track: typeof raw.track === 'number' && Number.isInteger(raw.track) && raw.track >= 0 ? raw.track : 0,
207
+ audioTrack: Boolean(raw.audioTrack),
208
+ stageOnly: Boolean(raw.stageOnly),
209
+ simulateHost: Boolean(raw.simulateHost)
210
+ };
211
+ }
212
+ export function buildAdobeLiveExtendScript(job, receiptFile, cachedBounds) {
213
+ const receiptLit = JSON.stringify(receiptFile);
214
+ const lines = [
215
+ '(function() {',
216
+ ' function writeJsonReceipt(obj) {',
217
+ ` var f = new File(${receiptLit});`,
218
+ ' f.encoding = "UTF-8";',
219
+ ' f.open("w");',
220
+ ' f.write(obj);',
221
+ ' f.close();',
222
+ ' }',
223
+ ' try {'
224
+ ];
225
+ if (job.canonicalHost === 'photoshop') {
226
+ lines.push(' if (app.documents.length === 0) { throw new Error("No active document is open in Photoshop"); }', ' var doc = app.activeDocument;', ' var origRuler = app.preferences.rulerUnits;', ' app.preferences.rulerUnits = Units.PIXELS;', ' var selBounds = null;', ' try {', ' var sb = doc.selection.bounds;', ' selBounds = [Number(sb[0].as("px")), Number(sb[1].as("px")), Number(sb[2].as("px")), Number(sb[3].as("px"))];', ' } catch (_noSel) { selBounds = null; }');
227
+ if (job.operation === 'inspect_active') {
228
+ lines.push(' var activeLayerName = doc.activeLayer ? String(doc.activeLayer.name) : "";', ' var w = Number(doc.width.as("px"));', ' var h = Number(doc.height.as("px"));', ' app.preferences.rulerUnits = origRuler;', ' writeJsonReceipt(\'{"status":"CAUSYNE_LIVE_OK","host":"photoshop","operation":"inspect_active","documentName":\' + JSON.stringify(String(doc.name)) + \',"width":\' + w + \',"height":\' + h + \',"activeLayerName":\' + JSON.stringify(activeLayerName) + \',"layerCount":\' + doc.layers.length + \',"hasSelection":\' + (selBounds !== null) + \',"selectionBounds":\' + (selBounds ? "[" + selBounds.join(",") + "]" : "null") + \'}\');');
229
+ }
230
+ else if (job.operation === 'export_canvas_preview') {
231
+ const outLit = JSON.stringify(job.output ?? '');
232
+ const maxDim = job.maxDimension ?? 1024;
233
+ lines.push(' var dup = doc.duplicate("Causyne_Temp_Preview", false);', ...(job.layerOnly
234
+ ? [
235
+ ' try { dup.trim(TrimType.TRANSPARENT, true, true, true, true); } catch (_trimErr) {}'
236
+ ]
237
+ : [' dup.flatten();']), ' var dw = Number(dup.width.as("px"));', ' var dh = Number(dup.height.as("px"));', ` var maxDim = ${maxDim};`, ' if (dw > maxDim || dh > maxDim) {', ' var ratio = maxDim / Math.max(dw, dh);', ' dup.resizeImage(UnitValue(Math.max(1, Math.round(dw * ratio)), "px"), UnitValue(Math.max(1, Math.round(dh * ratio)), "px"), null, ResampleMethod.BICUBIC);', ' }', ' var pngOpts = new PNGSaveOptions();', ` dup.saveAs(new File(${outLit}), pngOpts, true, Extension.LOWERCASE);`, ' dup.close(SaveOptions.DONOTSAVECHANGES);', ' app.preferences.rulerUnits = origRuler;', ` writeJsonReceipt('{"status":"CAUSYNE_LIVE_OK","host":"photoshop","operation":"export_canvas_preview","documentName":' + JSON.stringify(String(doc.name)) + ',"output":' + JSON.stringify(${outLit}) + ',"hasSelection":' + (selBounds !== null) + ',"selectionBounds":' + (selBounds ? "[" + selBounds.join(",") + "]" : "null") + '}');`);
238
+ }
239
+ else if (job.operation === 'place_in_active_canvas') {
240
+ const inLit = JSON.stringify(job.input ?? '');
241
+ const layerNameLit = JSON.stringify(job.layerName ?? 'Causyne Placed Asset');
242
+ const fitMode = job.fitMode ?? 'selection';
243
+ const fallbackBounds = job.bounds
244
+ ? [job.bounds.left, job.bounds.top, job.bounds.left + job.bounds.width, job.bounds.top + job.bounds.height]
245
+ : cachedBounds
246
+ ? [cachedBounds.left, cachedBounds.top, cachedBounds.right, cachedBounds.bottom]
247
+ : null;
248
+ const fallbackLit = fallbackBounds ? `[${fallbackBounds.join(',')}]` : 'null';
249
+ const placeLines = [
250
+ ` var targetBounds = (${JSON.stringify(fitMode)} === "bounds") ? ${fallbackLit} : (selBounds !== null ? selBounds : ${fallbackLit});`,
251
+ ' var idPlc = charIDToTypeID("Plc ");',
252
+ ' var descPlc = new ActionDescriptor();',
253
+ ` descPlc.putPath(charIDToTypeID("null"), new File(${inLit}));`,
254
+ ' descPlc.putEnumerated(charIDToTypeID("FTcs"), charIDToTypeID("QCSt"), charIDToTypeID("Qcsa"));',
255
+ ' executeAction(idPlc, descPlc, DialogModes.NO);',
256
+ ' var placedLayer = doc.activeLayer;',
257
+ ` placedLayer.name = ${layerNameLit};`,
258
+ ' var lb = placedLayer.bounds;',
259
+ ' var lw = Math.max(1, Number(lb[2].as("px")) - Number(lb[0].as("px")));',
260
+ ' var lh = Math.max(1, Number(lb[3].as("px")) - Number(lb[1].as("px")));',
261
+ ` var fitMode = ${JSON.stringify(fitMode)};`,
262
+ ' if ((fitMode === "selection" || fitMode === "bounds") && targetBounds !== null) {',
263
+ ' var tw = Math.max(1, targetBounds[2] - targetBounds[0]);',
264
+ ' var th = Math.max(1, targetBounds[3] - targetBounds[1]);',
265
+ ' placedLayer.resize((tw / lw) * 100.0, (th / lh) * 100.0, AnchorPosition.TOPLEFT);',
266
+ ' var nb = placedLayer.bounds;',
267
+ ' placedLayer.translate(UnitValue(targetBounds[0] - Number(nb[0].as("px")), "px"), UnitValue(targetBounds[1] - Number(nb[1].as("px")), "px"));',
268
+ ` if (${Boolean(job.applySelectionMask)} && selBounds !== null) {`,
269
+ ' try {',
270
+ ' doc.selection.select([[targetBounds[0], targetBounds[1]], [targetBounds[2], targetBounds[1]], [targetBounds[2], targetBounds[3]], [targetBounds[0], targetBounds[3]]]);',
271
+ ' var idMk = charIDToTypeID("Mk ");',
272
+ ' var descMk = new ActionDescriptor();',
273
+ ' descMk.putClass(charIDToTypeID("Nw "), charIDToTypeID("Chnl"));',
274
+ ' var refMk = new ActionReference();',
275
+ ' refMk.putEnumerated(charIDToTypeID("Chnl"), charIDToTypeID("Chnl"), charIDToTypeID("Msk "));',
276
+ ' descMk.putReference(charIDToTypeID("At "), refMk);',
277
+ ' descMk.putEnumerated(charIDToTypeID("Usng"), charIDToTypeID("UsrM"), charIDToTypeID("RvlS"));',
278
+ ' executeAction(idMk, descMk, DialogModes.NO);',
279
+ ' } catch (_maskErr) {}',
280
+ ' }',
281
+ ' } else if (fitMode === "document_height") {',
282
+ ' var docH = Math.max(1, Number(doc.height.as("px")));',
283
+ ' var scalePct = (docH / lh) * 100.0;',
284
+ ' placedLayer.resize(scalePct, scalePct, AnchorPosition.MIDDLECENTER);',
285
+ ' }',
286
+ ' app.preferences.rulerUnits = origRuler;',
287
+ ' writeJsonReceipt(\'{"status":"CAUSYNE_LIVE_OK","host":"photoshop","operation":"place_in_active_canvas","layerName":\' + JSON.stringify(String(placedLayer.name)) + \',"fitMode":\' + JSON.stringify(fitMode) + \'}\');'
288
+ ];
289
+ for (const line of placeLines) {
290
+ lines.push(line);
291
+ }
292
+ }
293
+ }
294
+ else if (job.canonicalHost === 'premiere') {
295
+ lines.push(' if (!app.project) { throw new Error("No active project is open in Premiere Pro"); }', ' var seq = app.project.activeSequence;', ' if (!seq) { throw new Error("No active sequence is open in Premiere Pro"); }');
296
+ if (job.operation === 'inspect_active') {
297
+ lines.push(' var playheadTicks = seq.getPlayerPosition();', ' var playheadSec = playheadTicks ? Number(playheadTicks.seconds) : 0;', ' writeJsonReceipt(\'{"status":"CAUSYNE_LIVE_OK","host":"premiere","operation":"inspect_active","projectName":\' + JSON.stringify(String(app.project.name || "Untitled")) + \',"activeSequenceName":\' + JSON.stringify(String(seq.name)) + \',"playheadSeconds":\' + playheadSec + \',"videoTracks":\' + seq.videoTracks.numTracks + \',"audioTracks":\' + seq.audioTracks.numTracks + \'}\');');
298
+ }
299
+ else if (job.operation === 'insert_in_active_timeline') {
300
+ const inLit = JSON.stringify(job.input ?? '');
301
+ const trackIdx = job.track ?? 0;
302
+ lines.push(` var importOk = app.project.importFiles([${inLit}], true, app.project.rootItem, false);`, ' if (!importOk) { throw new Error("Premiere Pro failed to import media file"); }', ' var item = app.project.rootItem.children[app.project.rootItem.children.numItems - 1];', ` var insertTime = ${job.atPlayhead ? '(seq.getPlayerPosition() ? seq.getPlayerPosition().seconds : 0)' : Number(job.start ?? 0)};`, ` var trackCollection = ${job.audioTrack ? 'seq.audioTracks' : 'seq.videoTracks'};`, ` var targetTrack = trackCollection[Math.min(${trackIdx}, trackCollection.numTracks - 1)];`, ' targetTrack.insertClip(item, insertTime);', ' writeJsonReceipt(\'{"status":"CAUSYNE_LIVE_OK","host":"premiere","operation":"insert_in_active_timeline","activeSequenceName":\' + JSON.stringify(String(seq.name)) + \',"insertedAtSeconds":\' + insertTime + \'}\');');
303
+ }
304
+ }
305
+ else if (job.canonicalHost === 'after-effects') {
306
+ lines.push(' if (!app.project) { throw new Error("No active project is open in After Effects"); }', ' var comp = app.project.activeItem;', ' if (!comp || !(comp instanceof CompItem)) { throw new Error("No active composition is selected in After Effects"); }');
307
+ if (job.operation === 'inspect_active') {
308
+ lines.push(' writeJsonReceipt(\'{"status":"CAUSYNE_LIVE_OK","host":"after-effects","operation":"inspect_active","activeCompName":\' + JSON.stringify(String(comp.name)) + \',"width":\' + comp.width + \',"height":\' + comp.height + \',"duration":\' + comp.duration + \',"frameRate":\' + comp.frameRate + \',"numLayers":\' + comp.numLayers + \'}\');');
309
+ }
310
+ else if (job.operation === 'insert_in_active_timeline') {
311
+ const inLit = JSON.stringify(job.input ?? '');
312
+ lines.push(` var io = new ImportOptions(new File(${inLit}));`, ' var footage = app.project.importFile(io);', ' var layer = comp.layers.add(footage);', ` layer.startTime = ${job.atPlayhead ? 'comp.time' : Number(job.start ?? 0)};`, ' writeJsonReceipt(\'{"status":"CAUSYNE_LIVE_OK","host":"after-effects","operation":"insert_in_active_timeline","activeCompName":\' + JSON.stringify(String(comp.name)) + \',"startTime":\' + layer.startTime + \'}\');');
313
+ }
314
+ }
315
+ else if (job.canonicalHost === 'illustrator') {
316
+ lines.push(' if (app.documents.length === 0) { throw new Error("No active document is open in Illustrator"); }', ' var doc = app.activeDocument;');
317
+ if (job.operation === 'inspect_active') {
318
+ lines.push(' writeJsonReceipt(\'{"status":"CAUSYNE_LIVE_OK","host":"illustrator","operation":"inspect_active","documentName":\' + JSON.stringify(String(doc.name)) + \',"width":\' + Number(doc.width) + \',"height":\' + Number(doc.height) + \',"artboardCount":\' + doc.artboards.length + \',"layerCount":\' + doc.layers.length + \'}\');');
319
+ }
320
+ else if (job.operation === 'export_canvas_preview') {
321
+ const outLit = JSON.stringify(job.output ?? '');
322
+ lines.push(' var exportOpts = new ExportOptionsPNG24();', ' exportOpts.artBoardClipping = true;', ` doc.exportFile(new File(${outLit}), ExportType.PNG24, exportOpts);`, ` writeJsonReceipt('{"status":"CAUSYNE_LIVE_OK","host":"illustrator","operation":"export_canvas_preview","documentName":' + JSON.stringify(String(doc.name)) + ',"output":' + JSON.stringify(${outLit}) + '}');`);
323
+ }
324
+ else if (job.operation === 'place_in_active_canvas') {
325
+ const inLit = JSON.stringify(job.input ?? '');
326
+ lines.push(' var placed = doc.placedItems.add();', ` placed.file = new File(${inLit});`, ...(job.bounds
327
+ ? [
328
+ ` placed.position = [${job.bounds.left}, ${-job.bounds.top}];`,
329
+ ` placed.width = ${job.bounds.width};`,
330
+ ` placed.height = ${job.bounds.height};`
331
+ ]
332
+ : []), ' writeJsonReceipt(\'{"status":"CAUSYNE_LIVE_OK","host":"illustrator","operation":"place_in_active_canvas","documentName":\' + JSON.stringify(String(doc.name)) + \'}\');');
333
+ }
334
+ }
335
+ else if (job.canonicalHost === 'indesign') {
336
+ lines.push(' if (app.documents.length === 0) { throw new Error("No active document is open in InDesign"); }', ' var doc = app.activeDocument;');
337
+ if (job.operation === 'inspect_active') {
338
+ lines.push(' writeJsonReceipt(\'{"status":"CAUSYNE_LIVE_OK","host":"indesign","operation":"inspect_active","documentName":\' + JSON.stringify(String(doc.name)) + \',"pages":\' + doc.pages.length + \',"spreads":\' + doc.spreads.length + \'}\');');
339
+ }
340
+ else if (job.operation === 'place_in_active_canvas') {
341
+ const inLit = JSON.stringify(job.input ?? '');
342
+ lines.push(` doc.pages[0].place(new File(${inLit}));`, ' writeJsonReceipt(\'{"status":"CAUSYNE_LIVE_OK","host":"indesign","operation":"place_in_active_canvas","documentName":\' + JSON.stringify(String(doc.name)) + \'}\');');
343
+ }
344
+ }
345
+ else {
346
+ lines.push(' writeJsonReceipt(\'{"status":"CAUSYNE_LIVE_OK","host":"media-encoder","operation":"inspect_active"}\');');
347
+ }
348
+ lines.push(' } catch (err) {', ' var msg = String(err && err.message ? err.message : err);', ' writeJsonReceipt(\'{"status":"CAUSYNE_LIVE_ERR","error":\' + JSON.stringify(msg) + \'}\');', ' }', '})();');
349
+ return lines.join('\n');
350
+ }
351
+ const MACOS_APP_DISPLAY_NAMES = {
352
+ photoshop: 'Adobe Photoshop',
353
+ premiere: 'Adobe Premiere Pro',
354
+ 'after-effects': 'Adobe After Effects',
355
+ illustrator: 'Adobe Illustrator',
356
+ indesign: 'Adobe InDesign',
357
+ 'media-encoder': 'Adobe Media Encoder'
358
+ };
359
+ export function buildAdobeHostInvocationPlan(platform, host, scriptFile, installedEntries, programFilesRoot = 'C:\\Program Files') {
360
+ if (platform === 'darwin') {
361
+ const appPrefix = MACOS_APP_DISPLAY_NAMES[host];
362
+ const entries = installedEntries ?? [`${appPrefix} 2026.app`];
363
+ const matchedApp = entries.find(a => a.startsWith(appPrefix) && a.endsWith('.app'));
364
+ if (!matchedApp)
365
+ return null;
366
+ const appName = matchedApp.replace(/\.app$/, '');
367
+ const appleScript = host === 'after-effects'
368
+ ? `tell application "${appName}" to DoScriptFile POSIX file ${JSON.stringify(scriptFile)}`
369
+ : `tell application "${appName}" to do javascript file POSIX file ${JSON.stringify(scriptFile)}`;
370
+ return {
371
+ platform,
372
+ host,
373
+ command: 'osascript',
374
+ args: ['-e', appleScript]
375
+ };
376
+ }
377
+ if (platform === 'win32') {
378
+ const exeNameMap = {
379
+ photoshop: { folder: /Photoshop/i, defaultFolder: 'Adobe Photoshop 2026', exe: 'Photoshop.exe' },
380
+ premiere: { folder: /Premiere/i, defaultFolder: 'Adobe Premiere Pro 2026', exe: 'Adobe Premiere Pro.exe' },
381
+ 'after-effects': { folder: /After Effects/i, defaultFolder: 'Adobe After Effects 2026', exe: 'AfterFX.exe' },
382
+ illustrator: { folder: /Illustrator/i, defaultFolder: 'Adobe Illustrator 2026', exe: 'Illustrator.exe' },
383
+ indesign: { folder: /InDesign/i, defaultFolder: 'Adobe InDesign 2026', exe: 'InDesign.exe' },
384
+ 'media-encoder': { folder: /Media Encoder/i, defaultFolder: 'Adobe Media Encoder 2026', exe: 'Adobe Media Encoder.exe' }
385
+ };
386
+ const target = exeNameMap[host];
387
+ const entries = installedEntries ?? [target.defaultFolder];
388
+ const matchedDir = entries.find(d => target.folder.test(d));
389
+ if (!matchedDir)
390
+ return null;
391
+ const exePath = `${programFilesRoot}\\Adobe\\${matchedDir}\\${target.exe}`;
392
+ return {
393
+ platform,
394
+ host,
395
+ command: exePath,
396
+ args: ['-r', scriptFile]
397
+ };
398
+ }
399
+ return null;
400
+ }
401
+ export function runSimulatedAdobeExtendScript(jsxCode) {
402
+ const unitVal = (num) => ({
403
+ value: num,
404
+ as: () => num
405
+ });
406
+ class SimFile {
407
+ filePath;
408
+ encoding = 'UTF-8';
409
+ content = '';
410
+ constructor(p) {
411
+ this.filePath = p;
412
+ }
413
+ open(_mode) {
414
+ return true;
415
+ }
416
+ write(text) {
417
+ this.content += String(text);
418
+ }
419
+ close() {
420
+ fsSync.mkdirSync(path.dirname(this.filePath), { recursive: true });
421
+ fsSync.writeFileSync(this.filePath, this.content, 'utf8');
422
+ }
423
+ }
424
+ class SimCompItem {
425
+ name = 'Causyne_Main_Comp';
426
+ width = 1920;
427
+ height = 1080;
428
+ duration = 15;
429
+ frameRate = 24;
430
+ numLayers = 2;
431
+ time = 2.5;
432
+ layers = {
433
+ add: (_item) => {
434
+ this.numLayers += 1;
435
+ return { startTime: 0 };
436
+ }
437
+ };
438
+ }
439
+ const activeLayerObj = {
440
+ name: 'Background',
441
+ bounds: [unitVal(0), unitVal(0), unitVal(1920), unitVal(1080)],
442
+ resize: (_sx, _sy) => { },
443
+ translate: (_dx, _dy) => { }
444
+ };
445
+ const docObj = {
446
+ name: 'Causyne_Studio_Master.psd',
447
+ width: Object.assign(Number(1920), { as: () => 1920 }),
448
+ height: Object.assign(Number(1080), { as: () => 1080 }),
449
+ activeLayer: activeLayerObj,
450
+ layers: [activeLayerObj],
451
+ artboards: [{ name: 'Artboard 1' }],
452
+ pages: [{ place: (_f) => { } }],
453
+ spreads: [{}],
454
+ placedItems: {
455
+ add: () => ({ file: null, position: [0, 0], width: 100, height: 100 })
456
+ },
457
+ selection: {
458
+ bounds: [unitVal(100), unitVal(120), unitVal(500), unitVal(420)],
459
+ select: (_pts) => { }
460
+ },
461
+ duplicate: (_name) => ({
462
+ width: unitVal(1920),
463
+ height: unitVal(1080),
464
+ trim: () => { },
465
+ flatten: () => { },
466
+ resizeImage: () => { },
467
+ saveAs: (fileObj) => {
468
+ fsSync.mkdirSync(path.dirname(fileObj.filePath), { recursive: true });
469
+ fsSync.writeFileSync(fileObj.filePath, 'SIMULATED_PNG_PREVIEW', 'utf8');
470
+ },
471
+ close: () => { }
472
+ }),
473
+ exportFile: (fileObj) => {
474
+ fsSync.mkdirSync(path.dirname(fileObj.filePath), { recursive: true });
475
+ fsSync.writeFileSync(fileObj.filePath, 'SIMULATED_ILLUSTRATOR_PNG', 'utf8');
476
+ }
477
+ };
478
+ const activeComp = new SimCompItem();
479
+ const trackObj = {
480
+ insertClip: (_item, _time) => { }
481
+ };
482
+ const seqObj = {
483
+ name: 'Causyne_Edit_Sequence_01',
484
+ getPlayerPosition: () => ({ seconds: 12.5 }),
485
+ videoTracks: Object.assign([trackObj, trackObj], { numTracks: 2 }),
486
+ audioTracks: Object.assign([trackObj, trackObj], { numTracks: 2 })
487
+ };
488
+ const sandbox = {
489
+ File: SimFile,
490
+ Units: { PIXELS: 'PIXELS' },
491
+ TrimType: { TRANSPARENT: 'TRANSPARENT' },
492
+ ResampleMethod: { BICUBIC: 'BICUBIC' },
493
+ SaveOptions: { DONOTSAVECHANGES: 'DONOTSAVECHANGES' },
494
+ Extension: { LOWERCASE: 'LOWERCASE' },
495
+ DialogModes: { NO: 'NO' },
496
+ AnchorPosition: { TOPLEFT: 'TOPLEFT', MIDDLECENTER: 'MIDDLECENTER' },
497
+ ExportType: { PNG24: 'PNG24' },
498
+ PNGSaveOptions: function PNGSaveOptions() { },
499
+ ExportOptionsPNG24: function ExportOptionsPNG24() { },
500
+ ImportOptions: function ImportOptions(f) {
501
+ this.file = f;
502
+ },
503
+ CompItem: SimCompItem,
504
+ UnitValue: (n) => unitVal(n),
505
+ charIDToTypeID: (id) => id,
506
+ ActionDescriptor: function ActionDescriptor() {
507
+ this.putPath = () => { };
508
+ this.putEnumerated = () => { };
509
+ this.putClass = () => { };
510
+ this.putReference = () => { };
511
+ },
512
+ ActionReference: function ActionReference() {
513
+ this.putEnumerated = () => { };
514
+ },
515
+ executeAction: () => { },
516
+ app: {
517
+ preferences: { rulerUnits: 'PIXELS' },
518
+ documents: [docObj],
519
+ activeDocument: docObj,
520
+ project: {
521
+ name: 'Causyne_Production.prproj',
522
+ activeSequence: seqObj,
523
+ activeItem: activeComp,
524
+ rootItem: {
525
+ children: Object.assign([{ name: 'ImportedClip' }], { numItems: 1 })
526
+ },
527
+ importFiles: () => true,
528
+ importFile: () => ({ name: 'ImportedFootage' })
529
+ }
530
+ },
531
+ JSON,
532
+ Math,
533
+ Number,
534
+ String,
535
+ Boolean,
536
+ Array,
537
+ Error
538
+ };
539
+ vm.runInNewContext(jsxCode, sandbox, { timeout: 5000 });
540
+ }
541
+ export async function runAdobeLiveBridge(value, workspace = process.cwd(), signal) {
542
+ signal?.throwIfAborted();
543
+ const job = validateAdobeLiveJob(value);
544
+ if (job.input) {
545
+ job.input = await resolveWorkspacePath(job.input, workspace, true);
546
+ }
547
+ if (job.output) {
548
+ job.output = await resolveWorkspacePath(job.output, workspace, false);
549
+ await fs.mkdir(path.dirname(job.output), { recursive: true });
550
+ }
551
+ if (job.canonicalHost === 'resolve') {
552
+ const resolveAction = job.operation === 'inspect_active' ? 'inspectActive' : 'insertClipAtPlayhead';
553
+ return await runResolveBridge({
554
+ action: resolveAction,
555
+ mediaPath: job.input,
556
+ simulate: job.simulateHost
557
+ }, { simulate: job.simulateHost });
558
+ }
559
+ const cachedMask = getLatestSelectionMask();
560
+ const tempDir = await fs.mkdtemp(path.join(os.tmpdir(), 'causyne-adobe-live-'));
561
+ const scriptFile = path.join(tempDir, 'live_bridge.jsx');
562
+ const receiptFile = path.join(tempDir, 'live_receipt.json');
563
+ try {
564
+ const jsx = buildAdobeLiveExtendScript(job, receiptFile, cachedMask?.bounds ?? null);
565
+ await fs.writeFile(scriptFile, jsx, 'utf8');
566
+ if (job.stageOnly) {
567
+ const stagedDir = path.join(workspace, '.causyne_studio_bridge');
568
+ await fs.mkdir(stagedDir, { recursive: true });
569
+ const stagedScriptPath = path.join(stagedDir, `${job.canonicalHost}_${job.operation}.jsx`);
570
+ await fs.writeFile(stagedScriptPath, jsx, 'utf8');
571
+ return {
572
+ success: true,
573
+ mode: 'staged_jsx',
574
+ host: job.canonicalHost,
575
+ operation: job.operation,
576
+ scriptPath: stagedScriptPath
577
+ };
578
+ }
579
+ if (job.simulateHost || process.env.CAUSYNE_SIMULATE_DCC === '1') {
580
+ runSimulatedAdobeExtendScript(jsx);
581
+ }
582
+ else if (process.platform === 'darwin') {
583
+ const apps = await fs.readdir('/Applications').catch(() => []);
584
+ const plan = buildAdobeHostInvocationPlan('darwin', job.canonicalHost, scriptFile, apps);
585
+ if (!plan) {
586
+ const appPrefix = MACOS_APP_DISPLAY_NAMES[job.canonicalHost];
587
+ return {
588
+ success: false,
589
+ host: job.canonicalHost,
590
+ operation: job.operation,
591
+ error: `${appPrefix} is not installed in /Applications. Pass stageOnly=true or simulateHost=true to verify without installation.`
592
+ };
593
+ }
594
+ await execFileAsync(plan.command, plan.args, { timeout: 60000, signal });
595
+ }
596
+ else if (process.platform === 'win32') {
597
+ const programFiles = process.env.ProgramFiles || 'C:\\Program Files';
598
+ const adobeRoot = path.join(programFiles, 'Adobe');
599
+ const dirs = await fs.readdir(adobeRoot).catch(() => []);
600
+ const plan = buildAdobeHostInvocationPlan('win32', job.canonicalHost, scriptFile, dirs, programFiles);
601
+ if (!plan) {
602
+ return {
603
+ success: false,
604
+ host: job.canonicalHost,
605
+ operation: job.operation,
606
+ error: `Adobe ${job.canonicalHost} is not installed in ${adobeRoot}. Pass stageOnly=true or simulateHost=true to verify without installation.`
607
+ };
608
+ }
609
+ await execFileAsync(plan.command, plan.args, { timeout: 60000, signal });
610
+ }
611
+ else {
612
+ return {
613
+ success: false,
614
+ host: job.canonicalHost,
615
+ operation: job.operation,
616
+ error: `Native desktop IPC for ${job.canonicalHost} requires macOS or Windows (or pass simulateHost=true).`
617
+ };
618
+ }
619
+ const rawReceipt = await fs.readFile(receiptFile, 'utf8').catch(() => '');
620
+ if (!rawReceipt.trim()) {
621
+ return {
622
+ success: false,
623
+ host: job.canonicalHost,
624
+ operation: job.operation,
625
+ error: 'Host application did not write a live bridge receipt.'
626
+ };
627
+ }
628
+ const parsed = JSON.parse(rawReceipt);
629
+ if (parsed.status === 'CAUSYNE_LIVE_ERR') {
630
+ return {
631
+ success: false,
632
+ host: job.canonicalHost,
633
+ operation: job.operation,
634
+ error: String(parsed.error ?? 'Unknown Adobe live bridge error')
635
+ };
636
+ }
637
+ if (Array.isArray(parsed.selectionBounds) && parsed.selectionBounds.length === 4) {
638
+ const [left, top, right, bottom] = parsed.selectionBounds.map(Number);
639
+ if (left !== undefined &&
640
+ top !== undefined &&
641
+ right !== undefined &&
642
+ bottom !== undefined &&
643
+ Number.isFinite(left) &&
644
+ Number.isFinite(top) &&
645
+ Number.isFinite(right) &&
646
+ Number.isFinite(bottom)) {
647
+ rememberSelectionMask(String(parsed.documentName ?? 'active_document'), {
648
+ left,
649
+ top,
650
+ right,
651
+ bottom,
652
+ width: Math.max(1, right - left),
653
+ height: Math.max(1, bottom - top)
654
+ });
655
+ }
656
+ }
657
+ return {
658
+ success: true,
659
+ ...parsed
660
+ };
661
+ }
662
+ finally {
663
+ await fs.rm(tempDir, { recursive: true, force: true }).catch(() => { });
664
+ }
665
+ }
666
+ export function validateGameEngineJob(value) {
667
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
668
+ throw new Error('Game engine bridge job must be an object');
669
+ }
670
+ const raw = value;
671
+ const engineInput = String(raw.engine ?? raw.host ?? 'unreal').trim().toLowerCase();
672
+ const canonicalEngine = GAME_ENGINE_ALIASES[engineInput];
673
+ if (!canonicalEngine) {
674
+ throw new Error(`Unsupported game engine "${String(raw.engine ?? raw.host)}". Supported engines: unreal, unity, godot.`);
675
+ }
676
+ const opInput = String(raw.engineOperation ?? raw.operation ?? 'import_assets').trim();
677
+ const validOps = ['remote_control', 'import_assets', 'spawn_actor'];
678
+ if (!validOps.includes(opInput)) {
679
+ throw new Error(`Unsupported engineOperation "${opInput}". Supported: ${validOps.join(', ')}`);
680
+ }
681
+ if (opInput === 'remote_control' && canonicalEngine !== 'unreal') {
682
+ throw new Error('remote_control HTTP bridge on port 30010 is specific to Unreal Engine (unreal)');
683
+ }
684
+ const remotePort = typeof raw.remotePort === 'number' && Number.isInteger(raw.remotePort)
685
+ ? raw.remotePort
686
+ : 30010;
687
+ if (remotePort < 1024 || remotePort > 65535) {
688
+ throw new Error('remotePort must be between 1024 and 65535');
689
+ }
690
+ const assets = Array.isArray(raw.assets)
691
+ ? raw.assets.map(a => String(a).trim()).filter(Boolean)
692
+ : typeof raw.input === 'string' && raw.input.trim()
693
+ ? [raw.input.trim()]
694
+ : undefined;
695
+ if (opInput === 'import_assets' && (!assets || assets.length === 0)) {
696
+ throw new Error('import_assets requires at least one workspace file in assets (or input)');
697
+ }
698
+ const parseVec3 = (v, fallback) => {
699
+ if (!Array.isArray(v) || v.length !== 3)
700
+ return fallback;
701
+ const nums = v.map(Number);
702
+ if (nums.some(n => !Number.isFinite(n))) {
703
+ throw new Error('3D vector coordinates must contain 3 finite numbers');
704
+ }
705
+ return [nums[0], nums[1], nums[2]];
706
+ };
707
+ return {
708
+ engine: engineInput,
709
+ canonicalEngine,
710
+ engineOperation: opInput,
711
+ projectPath: typeof raw.projectPath === 'string' && raw.projectPath.trim() ? raw.projectPath.trim() : '.',
712
+ assets,
713
+ destinationFolder: typeof raw.destinationFolder === 'string' && raw.destinationFolder.trim()
714
+ ? raw.destinationFolder.trim()
715
+ : undefined,
716
+ objectPath: typeof raw.objectPath === 'string' ? raw.objectPath.trim() : undefined,
717
+ functionName: typeof raw.functionName === 'string' ? raw.functionName.trim() : undefined,
718
+ propertyName: typeof raw.propertyName === 'string' ? raw.propertyName.trim() : undefined,
719
+ propertyValue: raw.propertyValue,
720
+ parameters: raw.parameters && typeof raw.parameters === 'object' && !Array.isArray(raw.parameters)
721
+ ? raw.parameters
722
+ : undefined,
723
+ remotePort,
724
+ actorName: typeof raw.actorName === 'string' && raw.actorName.trim() ? raw.actorName.trim() : 'CausyneActor',
725
+ actorClass: typeof raw.actorClass === 'string' && raw.actorClass.trim() ? raw.actorClass.trim() : 'StaticMeshActor',
726
+ assetPath: typeof raw.assetPath === 'string' && raw.assetPath.trim() ? raw.assetPath.trim() : undefined,
727
+ location: parseVec3(raw.location, [0, 0, 0]),
728
+ rotation: parseVec3(raw.rotation, [0, 0, 0]),
729
+ scale: parseVec3(raw.scale, [1, 1, 1]),
730
+ executeHeadless: raw.executeHeadless === undefined ? true : Boolean(raw.executeHeadless)
731
+ };
732
+ }
733
+ export function buildUnrealPythonScript(job, resolvedAssets) {
734
+ const destContentPath = job.destinationFolder?.startsWith('/Game/')
735
+ ? job.destinationFolder
736
+ : `/Game/${(job.destinationFolder || 'CausyneAssets').replace(/^\/+|\/+$/g, '')}`;
737
+ if (job.engineOperation === 'import_assets') {
738
+ return [
739
+ '# Generated by Causyne Agent — Unreal Engine 5 Native Python Bridge',
740
+ 'import unreal',
741
+ '',
742
+ 'def run_causyne_import():',
743
+ ' asset_tools = unreal.AssetToolsHelpers.get_asset_tools()',
744
+ ' tasks = []',
745
+ ` dest_path = ${JSON.stringify(destContentPath)}`,
746
+ ` files = ${JSON.stringify(resolvedAssets)}`,
747
+ ' for file_path in files:',
748
+ ' task = unreal.AssetImportTask()',
749
+ ' task.set_editor_property("filename", file_path)',
750
+ ' task.set_editor_property("destination_path", dest_path)',
751
+ ' task.set_editor_property("automated", True)',
752
+ ' task.set_editor_property("save", True)',
753
+ ' task.set_editor_property("replace_existing", True)',
754
+ ' tasks.append(task)',
755
+ ' asset_tools.import_asset_tasks(tasks)',
756
+ ' unreal.EditorAssetLibrary.save_directory(dest_path, only_if_is_dirty=False, recursive=True)',
757
+ ' unreal.log("CAUSYNE_UNREAL_IMPORT_COMPLETE:" + dest_path)',
758
+ '',
759
+ 'if __name__ == "__main__":',
760
+ ' run_causyne_import()',
761
+ ''
762
+ ].join('\n');
763
+ }
764
+ const [lx, ly, lz] = job.location ?? [0, 0, 0];
765
+ const [rx, ry, rz] = job.rotation ?? [0, 0, 0];
766
+ const [sx, sy, sz] = job.scale ?? [1, 1, 1];
767
+ return [
768
+ '# Generated by Causyne Agent — Unreal Engine 5 Level Actor Spawner',
769
+ 'import unreal',
770
+ '',
771
+ 'def run_causyne_spawn():',
772
+ ` actor_label = ${JSON.stringify(job.actorName ?? 'CausyneActor')}`,
773
+ ` asset_path = ${JSON.stringify(job.assetPath ?? '')}`,
774
+ ` loc = unreal.Vector(${lx}, ${ly}, ${lz})`,
775
+ ` rot = unreal.Rotator(${rx}, ${ry}, ${rz})`,
776
+ ' if asset_path:',
777
+ ' loaded_asset = unreal.EditorAssetLibrary.load_asset(asset_path)',
778
+ ' actor = unreal.EditorLevelLibrary.spawn_actor_from_object(loaded_asset, loc, rot)',
779
+ ' else:',
780
+ ` actor_cls = getattr(unreal, ${JSON.stringify(job.actorClass ?? 'StaticMeshActor')}, unreal.StaticMeshActor)`,
781
+ ' actor = unreal.EditorLevelLibrary.spawn_actor_from_class(actor_cls, loc, rot)',
782
+ ' if actor:',
783
+ ' actor.set_actor_label(actor_label)',
784
+ ` actor.set_actor_scale3d(unreal.Vector(${sx}, ${sy}, ${sz}))`,
785
+ ' unreal.EditorLevelLibrary.save_current_level()',
786
+ ' unreal.log("CAUSYNE_UNREAL_SPAWN_COMPLETE:" + actor_label)',
787
+ '',
788
+ 'if __name__ == "__main__":',
789
+ ' run_causyne_spawn()',
790
+ ''
791
+ ].join('\n');
792
+ }
793
+ export function buildUnityEditorScript(job, relativeAssetPaths) {
794
+ const [lx, ly, lz] = job.location ?? [0, 0, 0];
795
+ const [rx, ry, rz] = job.rotation ?? [0, 0, 0];
796
+ const [sx, sy, sz] = job.scale ?? [1, 1, 1];
797
+ const assetListLiteral = relativeAssetPaths.map(p => ` ${JSON.stringify(p.replace(/\\/g, '/'))}`).join(',\n');
798
+ return [
799
+ '// Generated by Causyne Agent — Unity Editor Direct Automation Bridge',
800
+ 'using System;',
801
+ 'using UnityEditor;',
802
+ 'using UnityEditor.SceneManagement;',
803
+ 'using UnityEngine;',
804
+ '',
805
+ 'public static class CausyneUnityBridge',
806
+ '{',
807
+ ' [MenuItem("Causyne/Execute Staged Bridge Job")]',
808
+ ' public static void ExecuteBatch()',
809
+ ' {',
810
+ ' AssetDatabase.Refresh(ImportAssetOptions.ForceSynchronousImport);',
811
+ ' string[] importedAssets = new string[]',
812
+ ' {',
813
+ assetListLiteral,
814
+ ' };',
815
+ ' foreach (string assetPath in importedAssets)',
816
+ ' {',
817
+ ' if (!string.IsNullOrEmpty(assetPath))',
818
+ ' {',
819
+ ' AssetDatabase.ImportAsset(assetPath, ImportAssetOptions.ForceUpdate);',
820
+ ' }',
821
+ ' }',
822
+ ...(job.engineOperation === 'spawn_actor'
823
+ ? [
824
+ ` GameObject spawned = null;`,
825
+ ` string prefabPath = ${JSON.stringify(job.assetPath ?? '')};`,
826
+ ' if (!string.IsNullOrEmpty(prefabPath))',
827
+ ' {',
828
+ ' GameObject prefab = AssetDatabase.LoadAssetAtPath<GameObject>(prefabPath);',
829
+ ' if (prefab != null) spawned = (GameObject)PrefabUtility.InstantiatePrefab(prefab);',
830
+ ' }',
831
+ ' if (spawned == null)',
832
+ ' {',
833
+ ' spawned = GameObject.CreatePrimitive(PrimitiveType.Cube);',
834
+ ' }',
835
+ ` spawned.name = ${JSON.stringify(job.actorName ?? 'CausyneActor')};`,
836
+ ` spawned.transform.position = new Vector3(${lx}f, ${ly}f, ${lz}f);`,
837
+ ` spawned.transform.eulerAngles = new Vector3(${rx}f, ${ry}f, ${rz}f);`,
838
+ ` spawned.transform.localScale = new Vector3(${sx}f, ${sy}f, ${sz}f);`,
839
+ ' EditorSceneManager.MarkSceneDirty(EditorSceneManager.GetActiveScene());',
840
+ ' EditorSceneManager.SaveOpenScenes();'
841
+ ]
842
+ : []),
843
+ ' AssetDatabase.SaveAssets();',
844
+ ' Debug.Log("CAUSYNE_UNITY_BRIDGE_COMPLETE");',
845
+ ' }',
846
+ '}',
847
+ ''
848
+ ].join('\n');
849
+ }
850
+ export function buildGodotImportScript(job, resPaths) {
851
+ const [lx, ly, lz] = job.location ?? [0, 0, 0];
852
+ const [sx, sy, sz] = job.scale ?? [1, 1, 1];
853
+ return [
854
+ '# Generated by Causyne Agent — Godot 4 Headless SceneTree Bridge',
855
+ 'extends SceneTree',
856
+ '',
857
+ 'func _init() -> void:',
858
+ ` var imported_assets := ${JSON.stringify(resPaths)}`,
859
+ ' print("CAUSYNE_GODOT_ASSETS_STAGED:", imported_assets.size())',
860
+ ...(job.engineOperation === 'spawn_actor'
861
+ ? [
862
+ ' var root := Node3D.new()',
863
+ ' root.name = "CausyneSceneRoot"',
864
+ ' var actor := Node3D.new()',
865
+ ` actor.name = ${JSON.stringify(job.actorName ?? 'CausyneActor')}`,
866
+ ` actor.position = Vector3(${lx}, ${ly}, ${lz})`,
867
+ ` actor.scale = Vector3(${sx}, ${sy}, ${sz})`,
868
+ ' root.add_child(actor)',
869
+ ' actor.owner = root',
870
+ ' var packed := PackedScene.new()',
871
+ ' if packed.pack(root) == OK:',
872
+ ' ResourceSaver.save(packed, "res://causyne_spawned_actor.tscn")',
873
+ ' print("CAUSYNE_GODOT_SPAWN_COMPLETE:res://causyne_spawned_actor.tscn")'
874
+ ]
875
+ : []),
876
+ ' quit(0)',
877
+ ''
878
+ ].join('\n');
879
+ }
880
+ export async function runGameEngineBridge(value, workspace = process.cwd(), signal) {
881
+ signal?.throwIfAborted();
882
+ const job = validateGameEngineJob(value);
883
+ if (job.engineOperation === 'remote_control') {
884
+ const port = job.remotePort ?? 30010;
885
+ const baseUrl = `http://127.0.0.1:${port}`;
886
+ try {
887
+ if (!job.objectPath) {
888
+ const infoRes = await fetch(`${baseUrl}/remote/info`, { method: 'GET', signal: signal ?? null });
889
+ const data = await infoRes.json().catch(() => ({}));
890
+ return {
891
+ success: infoRes.ok,
892
+ engine: 'unreal',
893
+ operation: 'remote_control',
894
+ endpoint: `${baseUrl}/remote/info`,
895
+ status: infoRes.status,
896
+ response: data
897
+ };
898
+ }
899
+ const isCall = Boolean(job.functionName);
900
+ const endpoint = isCall ? `${baseUrl}/remote/object/call` : `${baseUrl}/remote/object/property`;
901
+ const payload = isCall
902
+ ? {
903
+ objectPath: job.objectPath,
904
+ functionName: job.functionName,
905
+ parameters: job.parameters ?? {},
906
+ generateTransaction: true
907
+ }
908
+ : {
909
+ objectPath: job.objectPath,
910
+ propertyName: job.propertyName,
911
+ propertyValue: job.propertyValue,
912
+ access: job.propertyValue === undefined ? 'READ_ACCESS' : 'WRITE_TRANSACTION_ACCESS'
913
+ };
914
+ const res = await fetch(endpoint, {
915
+ method: 'PUT',
916
+ headers: { 'Content-Type': 'application/json' },
917
+ body: JSON.stringify(payload),
918
+ signal: signal ?? null
919
+ });
920
+ const data = await res.json().catch(() => ({}));
921
+ return {
922
+ success: res.ok,
923
+ engine: 'unreal',
924
+ operation: 'remote_control',
925
+ endpoint,
926
+ status: res.status,
927
+ response: data
928
+ };
929
+ }
930
+ catch (err) {
931
+ return {
932
+ success: false,
933
+ engine: 'unreal',
934
+ operation: 'remote_control',
935
+ endpoint: baseUrl,
936
+ error: `Unreal Remote Control HTTP bridge at ${baseUrl} is unreachable (${err instanceof Error ? err.message : String(err)}). Ensure Unreal Editor is running with the Remote Control API plugin enabled, or use engineOperation="import_assets" / "spawn_actor" for Python CLI automation.`
937
+ };
938
+ }
939
+ }
940
+ const projectRoot = await resolveWorkspacePath(job.projectPath ?? '.', workspace, false);
941
+ await fs.mkdir(projectRoot, { recursive: true });
942
+ const resolvedAssets = [];
943
+ for (const asset of job.assets ?? []) {
944
+ resolvedAssets.push(await resolveWorkspacePath(asset, workspace, true));
945
+ }
946
+ if (job.canonicalEngine === 'unreal') {
947
+ const bridgeDir = path.join(projectRoot, 'Saved', 'CausyneBridge');
948
+ await fs.mkdir(bridgeDir, { recursive: true });
949
+ const scriptPath = path.join(bridgeDir, `causyne_unreal_${job.engineOperation}.py`);
950
+ const pythonCode = buildUnrealPythonScript(job, resolvedAssets);
951
+ await fs.writeFile(scriptPath, pythonCode, 'utf8');
952
+ const unrealBin = findUnrealEngine();
953
+ const projectEntries = await fs.readdir(projectRoot).catch(() => []);
954
+ const uprojectFile = projectEntries.find(f => f.endsWith('.uproject'));
955
+ if (unrealBin && uprojectFile && job.executeHeadless !== false) {
956
+ const uprojectPath = path.join(projectRoot, uprojectFile);
957
+ const { stdout, stderr } = await execFileAsync(unrealBin.executable, [uprojectPath, '-run=pythonscript', `-script=${scriptPath}`, '-unattended', '-nopause', '-nosplash'], { timeout: 180000, maxBuffer: 4 * 1024 * 1024, signal });
958
+ return {
959
+ success: true,
960
+ engine: 'unreal',
961
+ mode: 'executed_cli',
962
+ operation: job.engineOperation,
963
+ executable: unrealBin.executable,
964
+ uproject: uprojectPath,
965
+ scriptPath,
966
+ assetsCount: resolvedAssets.length,
967
+ stdoutTail: stdout.slice(-1000),
968
+ stderrTail: stderr.slice(-500)
969
+ };
970
+ }
971
+ return {
972
+ success: true,
973
+ engine: 'unreal',
974
+ mode: 'staged_python_bridge',
975
+ operation: job.engineOperation,
976
+ scriptPath,
977
+ assetsCount: resolvedAssets.length,
978
+ installedBinary: unrealBin?.executable ?? null
979
+ };
980
+ }
981
+ if (job.canonicalEngine === 'unity') {
982
+ const destRel = (job.destinationFolder || 'Assets/CausyneAssets').replace(/^\/+|\/+$/g, '');
983
+ const normalizedDestRel = destRel.startsWith('Assets') ? destRel : path.join('Assets', destRel);
984
+ const destAbs = path.join(projectRoot, normalizedDestRel);
985
+ const editorDir = path.join(projectRoot, 'Assets', 'Editor');
986
+ await fs.mkdir(destAbs, { recursive: true });
987
+ await fs.mkdir(editorDir, { recursive: true });
988
+ const copiedRelativePaths = [];
989
+ for (const srcFile of resolvedAssets) {
990
+ const fileName = path.basename(srcFile);
991
+ const destFile = path.join(destAbs, fileName);
992
+ if (path.resolve(srcFile) !== path.resolve(destFile)) {
993
+ await fs.copyFile(srcFile, destFile);
994
+ }
995
+ copiedRelativePaths.push(path.posix.join(normalizedDestRel.replace(/\\/g, '/'), fileName));
996
+ }
997
+ const csPath = path.join(editorDir, 'CausyneUnityBridge.cs');
998
+ const csCode = buildUnityEditorScript(job, copiedRelativePaths);
999
+ await fs.writeFile(csPath, csCode, 'utf8');
1000
+ const unityBin = findUnityEditor();
1001
+ const hasProjectSettings = fsSync.existsSync(path.join(projectRoot, 'ProjectSettings'));
1002
+ if (unityBin && hasProjectSettings && job.executeHeadless !== false) {
1003
+ const { stdout, stderr } = await execFileAsync(unityBin.executable, [
1004
+ '-batchmode',
1005
+ '-nographics',
1006
+ '-quit',
1007
+ '-projectPath',
1008
+ projectRoot,
1009
+ '-executeMethod',
1010
+ 'CausyneUnityBridge.ExecuteBatch'
1011
+ ], { timeout: 180000, maxBuffer: 4 * 1024 * 1024, signal });
1012
+ return {
1013
+ success: true,
1014
+ engine: 'unity',
1015
+ mode: 'executed_batchmode',
1016
+ operation: job.engineOperation,
1017
+ executable: unityBin.executable,
1018
+ editorScriptPath: csPath,
1019
+ importedAssets: copiedRelativePaths,
1020
+ stdoutTail: stdout.slice(-1000),
1021
+ stderrTail: stderr.slice(-500)
1022
+ };
1023
+ }
1024
+ return {
1025
+ success: true,
1026
+ engine: 'unity',
1027
+ mode: 'staged_editor_bridge',
1028
+ operation: job.engineOperation,
1029
+ editorScriptPath: csPath,
1030
+ importedAssets: copiedRelativePaths,
1031
+ installedBinary: unityBin?.executable ?? null
1032
+ };
1033
+ }
1034
+ // Godot 4 Engine Bridge
1035
+ const destRel = (job.destinationFolder || 'assets/causyne').replace(/^res:\/\/|^\/+|\/+$/g, '');
1036
+ const destAbs = path.join(projectRoot, destRel);
1037
+ await fs.mkdir(destAbs, { recursive: true });
1038
+ const resPaths = [];
1039
+ for (const srcFile of resolvedAssets) {
1040
+ const fileName = path.basename(srcFile);
1041
+ const destFile = path.join(destAbs, fileName);
1042
+ if (path.resolve(srcFile) !== path.resolve(destFile)) {
1043
+ await fs.copyFile(srcFile, destFile);
1044
+ }
1045
+ resPaths.push(`res://${destRel.replace(/\\/g, '/')}/${fileName}`);
1046
+ }
1047
+ const gdScriptPath = path.join(projectRoot, '.causyne_godot_bridge.gd');
1048
+ const gdCode = buildGodotImportScript(job, resPaths);
1049
+ await fs.writeFile(gdScriptPath, gdCode, 'utf8');
1050
+ const godotBin = findGodotEngine();
1051
+ const hasProjectGodot = fsSync.existsSync(path.join(projectRoot, 'project.godot'));
1052
+ if (godotBin && hasProjectGodot && job.executeHeadless !== false) {
1053
+ const { stdout, stderr } = await execFileAsync(godotBin.executable, ['--headless', '--path', projectRoot, '--script', gdScriptPath], { timeout: 60000, maxBuffer: 2 * 1024 * 1024, signal });
1054
+ return {
1055
+ success: true,
1056
+ engine: 'godot',
1057
+ mode: 'executed_headless',
1058
+ operation: job.engineOperation,
1059
+ executable: godotBin.executable,
1060
+ scriptPath: gdScriptPath,
1061
+ importedAssets: resPaths,
1062
+ stdoutTail: stdout.slice(-1000),
1063
+ stderrTail: stderr.slice(-500)
1064
+ };
1065
+ }
1066
+ return {
1067
+ success: true,
1068
+ engine: 'godot',
1069
+ mode: 'staged_gdscript_bridge',
1070
+ operation: job.engineOperation,
1071
+ scriptPath: gdScriptPath,
1072
+ importedAssets: resPaths,
1073
+ installedBinary: godotBin?.executable ?? null
1074
+ };
1075
+ }
1076
+ export async function scaffoldCausyneUxpPlugin(outputDirInput, workspace = process.cwd(), options = {}) {
1077
+ const pluginDir = await resolveWorkspacePath(outputDirInput || 'causyne-uxp-bridge', workspace, false);
1078
+ await fs.mkdir(pluginDir, { recursive: true });
1079
+ const wsPort = options.websocketPort && options.websocketPort >= 1024 && options.websocketPort <= 65535
1080
+ ? options.websocketPort
1081
+ : 8080;
1082
+ const manifest = {
1083
+ id: 'com.causyne.studio.bridge',
1084
+ name: 'Causyne Studio Bridge',
1085
+ version: '1.0.0',
1086
+ main: 'index.html',
1087
+ manifestVersion: 5,
1088
+ host: [
1089
+ { app: 'PS', minVersion: '24.4.0' },
1090
+ { app: 'PPRO', minVersion: '25.2.0' }
1091
+ ],
1092
+ entrypoints: [
1093
+ {
1094
+ type: 'panel',
1095
+ id: 'com.causyne.studio.bridge.panel',
1096
+ label: { default: 'Causyne Bridge' },
1097
+ minimumSize: { width: 280, height: 360 },
1098
+ maximumSize: { width: 2400, height: 2400 },
1099
+ preferredDockedSize: { width: 340, height: 520 },
1100
+ preferredFloatingSize: { width: 380, height: 600 }
1101
+ }
1102
+ ],
1103
+ requiredPermissions: {
1104
+ localFileSystem: 'fullAccess',
1105
+ network: {
1106
+ domains: [`ws://127.0.0.1:${wsPort}`, `ws://localhost:${wsPort}`, `http://127.0.0.1:${wsPort}`]
1107
+ },
1108
+ webview: {
1109
+ allow: 'yes',
1110
+ domains: ['https://*.causyne.com', `http://127.0.0.1:${wsPort}`],
1111
+ enableMessageBridge: 'localAndRemote'
1112
+ },
1113
+ ipc: {
1114
+ enablePluginCommunication: true
1115
+ }
1116
+ }
1117
+ };
1118
+ const bridgeJs = `// Causyne Studio UXP Native Bridge (Photoshop & Premiere Pro)
1119
+ const uxp = require("uxp");
1120
+ const fs = uxp.storage.localFileSystem;
1121
+
1122
+ function getHostModule(name) {
1123
+ try { return require(name); } catch (_) { return null; }
1124
+ }
1125
+
1126
+ const photoshop = getHostModule("photoshop");
1127
+ const premierepro = getHostModule("premierepro");
1128
+
1129
+ const selectionMaskCache = new Map();
1130
+ const MAX_MASKS = 128;
1131
+
1132
+ function rememberSelection(docId, bounds) {
1133
+ if (selectionMaskCache.has(docId)) selectionMaskCache.delete(docId);
1134
+ selectionMaskCache.set(docId, { bounds, capturedAt: Date.now() });
1135
+ while (selectionMaskCache.size > MAX_MASKS) {
1136
+ const oldest = selectionMaskCache.keys().next().value;
1137
+ if (oldest === undefined) break;
1138
+ selectionMaskCache.delete(oldest);
1139
+ }
1140
+ }
1141
+
1142
+ async function exportActivePhotoshopCanvasPreview(options = {}) {
1143
+ if (!photoshop) throw new Error("Photoshop UXP host is not active");
1144
+ const doc = photoshop.app.activeDocument;
1145
+ if (!doc) throw new Error("No active document in Photoshop");
1146
+ const maxDimension = Math.min(1024, Math.max(64, Math.round(Number(options.maxDimension) || 1024)));
1147
+ let selectionBounds = null;
1148
+ try {
1149
+ const sb = doc.selection && doc.selection.bounds;
1150
+ if (sb) {
1151
+ selectionBounds = { left: sb.left, top: sb.top, right: sb.right, bottom: sb.bottom };
1152
+ rememberSelection(doc.id, selectionBounds);
1153
+ }
1154
+ } catch (_) {}
1155
+ return {
1156
+ documentId: doc.id,
1157
+ documentName: doc.name,
1158
+ width: doc.width,
1159
+ height: doc.height,
1160
+ maxDimension,
1161
+ selectionBounds
1162
+ };
1163
+ }
1164
+
1165
+ async function placeImageOnCanvas(payload = {}) {
1166
+ if (!photoshop) throw new Error("Photoshop UXP host is not active");
1167
+ const doc = photoshop.app.activeDocument;
1168
+ if (!doc) throw new Error("No active document in Photoshop");
1169
+ const entry = await fs.getEntryWithUrl("file:" + payload.filePath);
1170
+ const token = fs.createSessionToken(entry);
1171
+
1172
+ await photoshop.core.executeAsModal(async () => {
1173
+ await photoshop.action.batchPlay([
1174
+ {
1175
+ _obj: "placeEvent",
1176
+ null: { _path: token, _kind: "local" },
1177
+ freeTransformCenterState: { _enum: "quadCenterState", _value: "QCSAverage" }
1178
+ }
1179
+ ], { synchronousExecution: true });
1180
+
1181
+ if (payload.applySelectionMask && selectionMaskCache.has(doc.id)) {
1182
+ await photoshop.action.batchPlay([
1183
+ {
1184
+ _obj: "make",
1185
+ new: { _class: "channel" },
1186
+ at: { _ref: "channel", _enum: "channel", _value: "mask" },
1187
+ using: { _enum: "userMaskEnabled", _value: "revealSelection" }
1188
+ }
1189
+ ], { synchronousExecution: true });
1190
+ }
1191
+ }, { commandName: "Causyne Place Asset" });
1192
+
1193
+ return { status: "placed", documentId: doc.id, documentName: doc.name };
1194
+ }
1195
+
1196
+ async function handleBridgeCommand(msg) {
1197
+ if (msg.action === "export_canvas_preview") return await exportActivePhotoshopCanvasPreview(msg);
1198
+ if (msg.action === "place_in_active_canvas") return await placeImageOnCanvas(msg);
1199
+ throw new Error("Unsupported UXP action: " + msg.action);
1200
+ }
1201
+
1202
+ window.causyneUxpBridge = {
1203
+ exportActivePhotoshopCanvasPreview,
1204
+ placeImageOnCanvas,
1205
+ handleBridgeCommand
1206
+ };
1207
+ `;
1208
+ const indexHtml = `<!DOCTYPE html>
1209
+ <html lang="en">
1210
+ <head>
1211
+ <meta charset="UTF-8" />
1212
+ <title>Causyne Studio Bridge</title>
1213
+ <style>
1214
+ body { background: #121316; color: #eceef2; font-family: system-ui, sans-serif; margin: 0; padding: 16px; }
1215
+ .badge { display: inline-block; padding: 4px 8px; border-radius: 4px; background: #1e222a; font-size: 11px; letter-spacing: 0.04em; }
1216
+ h1 { font-size: 15px; margin: 12px 0 6px; font-weight: 600; }
1217
+ p { font-size: 12px; color: #9aa0ac; line-height: 1.45; margin: 0; }
1218
+ </style>
1219
+ </head>
1220
+ <body>
1221
+ <span class="badge">CAUSYNE UXP BRIDGE v1.0</span>
1222
+ <h1>Direct Canvas &amp; Sequence Link</h1>
1223
+ <p>Connected to local Causyne Agent over direct machine IPC (ws://127.0.0.1:${wsPort}).</p>
1224
+ <script src="bridge.js"></script>
1225
+ </body>
1226
+ </html>
1227
+ `;
1228
+ const manifestPath = path.join(pluginDir, 'manifest.json');
1229
+ const bridgePath = path.join(pluginDir, 'bridge.js');
1230
+ const htmlPath = path.join(pluginDir, 'index.html');
1231
+ await fs.writeFile(manifestPath, JSON.stringify(manifest, null, 2), 'utf8');
1232
+ await fs.writeFile(bridgePath, bridgeJs, 'utf8');
1233
+ await fs.writeFile(htmlPath, indexHtml, 'utf8');
1234
+ return {
1235
+ success: true,
1236
+ pluginDir,
1237
+ files: [manifestPath, bridgePath, htmlPath],
1238
+ websocketEndpoint: `ws://127.0.0.1:${wsPort}`
1239
+ };
1240
+ }
1241
+ export const MOCK_UNREAL_PY = `# Simulated unreal Python module for cross-platform verification
1242
+ class Vector:
1243
+ def __init__(self, x=0.0, y=0.0, z=0.0):
1244
+ self.x, self.y, self.z = x, y, z
1245
+
1246
+ class Rotator:
1247
+ def __init__(self, r=0.0, p=0.0, y=0.0):
1248
+ self.r, self.p, self.y = r, p, y
1249
+
1250
+ class AssetImportTask:
1251
+ def __init__(self):
1252
+ self.props = {}
1253
+ def set_editor_property(self, key, val):
1254
+ self.props[key] = val
1255
+
1256
+ class _AssetTools:
1257
+ def import_asset_tasks(self, tasks):
1258
+ return len(tasks)
1259
+
1260
+ class AssetToolsHelpers:
1261
+ @staticmethod
1262
+ def get_asset_tools():
1263
+ return _AssetTools()
1264
+
1265
+ class EditorAssetLibrary:
1266
+ @staticmethod
1267
+ def save_directory(dest_path, only_if_is_dirty=False, recursive=True):
1268
+ return True
1269
+ @staticmethod
1270
+ def load_asset(asset_path):
1271
+ return {"asset_path": asset_path}
1272
+
1273
+ class _SpawnedActor:
1274
+ def __init__(self):
1275
+ self.label = ""
1276
+ self.scale = Vector(1, 1, 1)
1277
+ def set_actor_label(self, label):
1278
+ self.label = label
1279
+ def set_actor_scale3d(self, scale):
1280
+ self.scale = scale
1281
+
1282
+ class StaticMeshActor:
1283
+ pass
1284
+
1285
+ class EditorLevelLibrary:
1286
+ @staticmethod
1287
+ def spawn_actor_from_object(obj, loc, rot):
1288
+ return _SpawnedActor()
1289
+ @staticmethod
1290
+ def spawn_actor_from_class(cls, loc, rot):
1291
+ return _SpawnedActor()
1292
+ @staticmethod
1293
+ def save_current_level():
1294
+ return True
1295
+
1296
+ def log(msg):
1297
+ print(str(msg))
1298
+ `;
1299
+ export async function runSimulatedUnrealPython(scriptPath) {
1300
+ const simDir = await fs.mkdtemp(path.join(os.tmpdir(), 'causyne-unreal-sim-'));
1301
+ try {
1302
+ await fs.writeFile(path.join(simDir, 'unreal.py'), MOCK_UNREAL_PY, 'utf8');
1303
+ const pathSep = os.platform() === 'win32' ? ';' : ':';
1304
+ const pyBin = os.platform() === 'win32' ? 'python' : 'python3';
1305
+ const env = {
1306
+ ...process.env,
1307
+ PYTHONPATH: [simDir, process.env.PYTHONPATH || ''].filter(Boolean).join(pathSep)
1308
+ };
1309
+ const { stdout } = await execFileAsync(pyBin, [scriptPath], { timeout: 15000, env });
1310
+ return {
1311
+ success: stdout.includes('CAUSYNE_UNREAL_IMPORT_COMPLETE') || stdout.includes('CAUSYNE_UNREAL_SPAWN_COMPLETE'),
1312
+ stdout: stdout.trim()
1313
+ };
1314
+ }
1315
+ finally {
1316
+ await fs.rm(simDir, { recursive: true, force: true }).catch(() => { });
1317
+ }
1318
+ }
1319
+ export async function verifyAllCreativeAndGameBridges(workspace = process.cwd()) {
1320
+ const tempWork = await fs.mkdtemp(path.join(workspace, '.tmp_causyne_bridge_verify_'));
1321
+ try {
1322
+ const sampleAsset = path.join(tempWork, 'sample_render.png');
1323
+ await fs.writeFile(sampleAsset, 'SIMULATED_PNG_DATA', 'utf8');
1324
+ // 1. Cross-platform OS command & environment matrix (macOS darwin + Windows win32 + Linux)
1325
+ const macPsPlan = buildAdobeHostInvocationPlan('darwin', 'photoshop', '/tmp/test.jsx');
1326
+ const winPsPlan = buildAdobeHostInvocationPlan('win32', 'photoshop', 'C:\\temp\\test.jsx');
1327
+ const macAePlan = buildAdobeHostInvocationPlan('darwin', 'after-effects', '/tmp/ae.jsx');
1328
+ const winPrPlan = buildAdobeHostInvocationPlan('win32', 'premiere', 'C:\\temp\\pr.jsx');
1329
+ const resolveMacCfg = buildResolvePlatformConfig('darwin', {});
1330
+ const resolveWinCfg = buildResolvePlatformConfig('win32', {});
1331
+ const resolveLinuxCfg = buildResolvePlatformConfig('linux', {});
1332
+ const crossPlatformMatrixOk = Boolean(macPsPlan?.command === 'osascript' &&
1333
+ winPsPlan?.command.endsWith('Photoshop.exe') &&
1334
+ macAePlan?.args[1]?.includes('DoScriptFile') &&
1335
+ winPrPlan?.command.endsWith('Adobe Premiere Pro.exe') &&
1336
+ resolveMacCfg.scriptLib.endsWith('fusionscript.so') &&
1337
+ resolveWinCfg.scriptLib.endsWith('fusionscript.dll') &&
1338
+ resolveLinuxCfg.scriptLib.endsWith('fusionscript.so'));
1339
+ // 2. Simulated Adobe ExtendScript DOM execution (Photoshop, Premiere, After Effects, Illustrator, InDesign)
1340
+ const relAsset = path.relative(workspace, sampleAsset);
1341
+ const relPreview = path.relative(workspace, path.join(tempWork, 'ps_preview.png'));
1342
+ const psPreviewRes = await runAdobeLiveBridge({
1343
+ host: 'photoshop',
1344
+ liveOperation: 'export_canvas_preview',
1345
+ output: relPreview,
1346
+ maxDimension: 512,
1347
+ simulateHost: true
1348
+ }, workspace);
1349
+ const psPlaceRes = await runAdobeLiveBridge({
1350
+ host: 'photoshop',
1351
+ liveOperation: 'place_in_active_canvas',
1352
+ input: relAsset,
1353
+ fitMode: 'selection',
1354
+ applySelectionMask: true,
1355
+ simulateHost: true
1356
+ }, workspace);
1357
+ const prInsertRes = await runAdobeLiveBridge({
1358
+ host: 'premiere',
1359
+ liveOperation: 'insert_in_active_timeline',
1360
+ input: relAsset,
1361
+ atPlayhead: true,
1362
+ simulateHost: true
1363
+ }, workspace);
1364
+ const aeInsertRes = await runAdobeLiveBridge({
1365
+ host: 'after-effects',
1366
+ liveOperation: 'insert_in_active_timeline',
1367
+ input: relAsset,
1368
+ atPlayhead: true,
1369
+ simulateHost: true
1370
+ }, workspace);
1371
+ // 3. DaVinci Resolve Studio Python Bridge execution (real python3 + simulated DaVinciResolveScript)
1372
+ const resolveInspectRes = await runResolveBridge({ action: 'inspectActive' }, { simulate: true });
1373
+ const resolveAssembleRes = await runResolveBridge({
1374
+ action: 'importAndAssemble',
1375
+ mediaPath: sampleAsset,
1376
+ markerName: 'Causyne AI Shot'
1377
+ }, { simulate: true });
1378
+ const resolveGradeRes = await runResolveBridge({
1379
+ action: 'applyLutOrGrade',
1380
+ lutPath: '/luts/Rec709_Film.cube',
1381
+ cdl: { slope: '1.05 1.0 0.98', offset: '0 0 0', power: '1 1 1', saturation: '1.1' }
1382
+ }, { simulate: true });
1383
+ // 4. Unreal Engine 5 Python execution + Live Remote Control HTTP loopback server test
1384
+ const unrealStageRes = await runGameEngineBridge({
1385
+ engine: 'unreal',
1386
+ engineOperation: 'import_assets',
1387
+ projectPath: path.relative(workspace, path.join(tempWork, 'UE5Verify')),
1388
+ assets: [relAsset],
1389
+ executeHeadless: false
1390
+ }, workspace);
1391
+ const unrealPySim = await runSimulatedUnrealPython(String(unrealStageRes.scriptPath));
1392
+ let unrealRemoteControlOk = false;
1393
+ const server = http.createServer((req, res) => {
1394
+ res.setHeader('Content-Type', 'application/json');
1395
+ if (req.url === '/remote/info') {
1396
+ res.end(JSON.stringify({ Routes: [{ Path: '/remote/object/call' }] }));
1397
+ return;
1398
+ }
1399
+ if (req.url === '/remote/object/call' && req.method === 'PUT') {
1400
+ res.end(JSON.stringify({ ReturnValue: true }));
1401
+ return;
1402
+ }
1403
+ res.statusCode = 404;
1404
+ res.end('{}');
1405
+ });
1406
+ await new Promise(resolve => server.listen(0, '127.0.0.1', () => resolve()));
1407
+ try {
1408
+ const addr = server.address();
1409
+ const port = typeof addr === 'object' && addr ? addr.port : 30010;
1410
+ const rcCall = await runGameEngineBridge({
1411
+ engine: 'unreal',
1412
+ engineOperation: 'remote_control',
1413
+ remotePort: port,
1414
+ objectPath: '/Script/UnrealEd.Default__EditorActorSubsystem',
1415
+ functionName: 'SpawnActorFromClass'
1416
+ }, workspace);
1417
+ unrealRemoteControlOk = Boolean(rcCall.success);
1418
+ }
1419
+ finally {
1420
+ await new Promise(resolve => server.close(() => resolve()));
1421
+ }
1422
+ // 5. Unity C# & Godot GDScript staging verification
1423
+ const unityStageRes = await runGameEngineBridge({
1424
+ engine: 'unity',
1425
+ engineOperation: 'spawn_actor',
1426
+ projectPath: path.relative(workspace, path.join(tempWork, 'UnityVerify')),
1427
+ assets: [relAsset],
1428
+ executeHeadless: false
1429
+ }, workspace);
1430
+ const godotStageRes = await runGameEngineBridge({
1431
+ engine: 'godot',
1432
+ engineOperation: 'spawn_actor',
1433
+ projectPath: path.relative(workspace, path.join(tempWork, 'GodotVerify')),
1434
+ assets: [relAsset],
1435
+ executeHeadless: false
1436
+ }, workspace);
1437
+ const allPassed = Boolean(crossPlatformMatrixOk &&
1438
+ psPreviewRes.success &&
1439
+ psPlaceRes.success &&
1440
+ prInsertRes.success &&
1441
+ aeInsertRes.success &&
1442
+ resolveInspectRes.success &&
1443
+ resolveAssembleRes.success &&
1444
+ resolveGradeRes.success &&
1445
+ unrealPySim.success &&
1446
+ unrealRemoteControlOk &&
1447
+ unityStageRes.success &&
1448
+ godotStageRes.success);
1449
+ return {
1450
+ success: allPassed,
1451
+ crossPlatformMatrix: {
1452
+ darwinAndWin32Verified: crossPlatformMatrixOk,
1453
+ macPhotoshopCommand: macPsPlan?.command,
1454
+ winPhotoshopCommand: winPsPlan?.command,
1455
+ resolveMacLib: resolveMacCfg.scriptLib,
1456
+ resolveWinLib: resolveWinCfg.scriptLib,
1457
+ resolveLinuxLib: resolveLinuxCfg.scriptLib
1458
+ },
1459
+ adobeDomSimulation: {
1460
+ photoshopPreview: Boolean(psPreviewRes.success),
1461
+ photoshopSelectionMaskPlace: Boolean(psPlaceRes.success),
1462
+ premiereTimelineInsert: Boolean(prInsertRes.success),
1463
+ afterEffectsCompInsert: Boolean(aeInsertRes.success)
1464
+ },
1465
+ davinciResolvePythonSimulation: {
1466
+ inspectActive: Boolean(resolveInspectRes.success),
1467
+ importAndAssemble: Boolean(resolveAssembleRes.success),
1468
+ applyLutOrGrade: Boolean(resolveGradeRes.success)
1469
+ },
1470
+ gameEnginesVerification: {
1471
+ unrealPythonExecution: unrealPySim.success,
1472
+ unrealRemoteControlHttp: unrealRemoteControlOk,
1473
+ unityCSharpStaged: Boolean(unityStageRes.success),
1474
+ godotGdScriptStaged: Boolean(godotStageRes.success)
1475
+ }
1476
+ };
1477
+ }
1478
+ finally {
1479
+ await fs.rm(tempWork, { recursive: true, force: true }).catch(() => { });
1480
+ }
1481
+ }