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