@ajsmonty/adobe-mcp 1.1.1 → 1.3.0

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.
@@ -0,0 +1,148 @@
1
+ # adobe-mcp Blender helpers for library textures (prepended to tool code; not an add-on).
2
+ # build_pbr_material(): Principled BSDF from canonical maps (BaseColor, Roughness, Metallic,
3
+ # Normal [OpenGL], Height, ARM, Opacity; AO is deliberately unused — a path tracer computes
4
+ # its own occlusion, and multiplying baked AO in double-darkens contact areas).
5
+ # set_world_hdri(): image-based lighting from an equirectangular HDRI.
6
+ import math
7
+ import os
8
+
9
+ import bpy
10
+
11
+
12
+ def _img_node(nt, path, non_color, loc):
13
+ node = nt.nodes.new("ShaderNodeTexImage")
14
+ node.location = loc
15
+ node.image = bpy.data.images.load(path, check_existing=True)
16
+ if non_color:
17
+ node.image.colorspace_settings.name = "Non-Color"
18
+ return node
19
+
20
+
21
+ def _has_uvs(ob):
22
+ return ob.type == "MESH" and len(getattr(ob.data, "uv_layers", [])) > 0
23
+
24
+
25
+ def build_pbr_material(name, maps, objects=(), tile_m=2.0, projection="auto",
26
+ displacement_m=0.02, replace=True):
27
+ """Create (or rebuild) material `name` from `maps` and assign it to `objects`.
28
+
29
+ tile_m: real-world size of one texture tile in meters (box projection and UV scaling).
30
+ projection: "uv", "box" (tri-planar in object space, for meshes without UVs) or "auto".
31
+ """
32
+ obs = [bpy.data.objects.get(o) if isinstance(o, str) else o for o in objects]
33
+ missing = [o for o, ob in zip(objects, obs) if ob is None]
34
+ if missing:
35
+ raise RuntimeError("Objects not found: %s" % missing)
36
+ if projection == "auto":
37
+ projection = "uv" if obs and all(_has_uvs(ob) for ob in obs) else "box"
38
+
39
+ mat = bpy.data.materials.get(name) or bpy.data.materials.new(name)
40
+ mat.use_nodes = True
41
+ nt = mat.node_tree
42
+ for n in list(nt.nodes):
43
+ nt.nodes.remove(n)
44
+ out = nt.nodes.new("ShaderNodeOutputMaterial")
45
+ out.location = (600, 0)
46
+ bsdf = nt.nodes.new("ShaderNodeBsdfPrincipled")
47
+ bsdf.location = (250, 0)
48
+ nt.links.new(bsdf.outputs["BSDF"], out.inputs["Surface"])
49
+
50
+ coord = nt.nodes.new("ShaderNodeTexCoord")
51
+ coord.location = (-1100, 0)
52
+ mapping = nt.nodes.new("ShaderNodeMapping")
53
+ mapping.location = (-900, 0)
54
+ s = 1.0 / max(1e-4, float(tile_m))
55
+ mapping.inputs["Scale"].default_value = (s, s, s)
56
+ nt.links.new(coord.outputs["UV" if projection == "uv" else "Object"], mapping.inputs["Vector"])
57
+
58
+ used, y = {}, 400
59
+
60
+ def tex(key, non_color):
61
+ nonlocal y
62
+ node = _img_node(nt, maps[key], non_color, (-600, y))
63
+ y -= 280
64
+ if projection == "box":
65
+ node.projection = "BOX"
66
+ node.projection_blend = 0.25 # soften tri-planar seams
67
+ nt.links.new(mapping.outputs["Vector"], node.inputs["Vector"])
68
+ used[key] = os.path.basename(maps[key])
69
+ return node
70
+
71
+ if "BaseColor" in maps:
72
+ nt.links.new(tex("BaseColor", False).outputs["Color"], bsdf.inputs["Base Color"])
73
+ arm = None
74
+ if "ARM" in maps and ("Roughness" not in maps or "Metallic" not in maps):
75
+ arm_img = tex("ARM", True)
76
+ arm = nt.nodes.new("ShaderNodeSeparateColor")
77
+ arm.location = (-250, y + 280)
78
+ nt.links.new(arm_img.outputs["Color"], arm.inputs["Color"])
79
+ if "Roughness" in maps:
80
+ nt.links.new(tex("Roughness", True).outputs["Color"], bsdf.inputs["Roughness"])
81
+ elif arm:
82
+ nt.links.new(arm.outputs["Green"], bsdf.inputs["Roughness"])
83
+ if "Metallic" in maps:
84
+ nt.links.new(tex("Metallic", True).outputs["Color"], bsdf.inputs["Metallic"])
85
+ elif arm:
86
+ nt.links.new(arm.outputs["Blue"], bsdf.inputs["Metallic"])
87
+ else:
88
+ bsdf.inputs["Metallic"].default_value = 0.0
89
+ if "Normal" in maps:
90
+ nm = nt.nodes.new("ShaderNodeNormalMap")
91
+ nm.location = (-150, -500)
92
+ nt.links.new(tex("Normal", True).outputs["Color"], nm.inputs["Color"])
93
+ nt.links.new(nm.outputs["Normal"], bsdf.inputs["Normal"])
94
+ if "Opacity" in maps:
95
+ nt.links.new(tex("Opacity", True).outputs["Color"], bsdf.inputs["Alpha"])
96
+ if "Height" in maps and displacement_m:
97
+ disp = nt.nodes.new("ShaderNodeDisplacement")
98
+ disp.location = (250, -500)
99
+ disp.inputs["Midlevel"].default_value = 0.5
100
+ disp.inputs["Scale"].default_value = float(displacement_m)
101
+ nt.links.new(tex("Height", True).outputs["Color"], disp.inputs["Height"])
102
+ nt.links.new(disp.outputs["Displacement"], out.inputs["Displacement"])
103
+ try:
104
+ mat.displacement_method = "BOTH" # real displacement where subdivided, bump elsewhere
105
+ except (AttributeError, TypeError):
106
+ pass
107
+
108
+ assigned = []
109
+ for ob in obs:
110
+ if not hasattr(ob.data, "materials"):
111
+ continue
112
+ if replace:
113
+ ob.data.materials.clear()
114
+ ob.data.materials.append(mat)
115
+ assigned.append(ob.name)
116
+ return {"material": mat.name, "projection": projection, "tile_m": tile_m,
117
+ "maps": used, "assigned": assigned,
118
+ "skipped": [k for k in maps if k not in used and k != "AO"] + (["AO (path tracer computes occlusion)"] if "AO" in maps else [])}
119
+
120
+
121
+ def set_world_hdri(path, strength=1.0, rotation_deg=0.0, world_name="MCP_HDRI_World"):
122
+ """Light the scene with an equirectangular HDRI; rotation_deg turns the sun direction."""
123
+ scene = bpy.context.scene
124
+ world = scene.world or bpy.data.worlds.new(world_name)
125
+ scene.world = world
126
+ world.use_nodes = True
127
+ nt = world.node_tree
128
+ for n in list(nt.nodes):
129
+ nt.nodes.remove(n)
130
+ coord = nt.nodes.new("ShaderNodeTexCoord")
131
+ coord.location = (-900, 0)
132
+ mapping = nt.nodes.new("ShaderNodeMapping")
133
+ mapping.location = (-700, 0)
134
+ mapping.inputs["Rotation"].default_value = (0.0, 0.0, math.radians(rotation_deg))
135
+ env = nt.nodes.new("ShaderNodeTexEnvironment")
136
+ env.location = (-450, 0)
137
+ env.image = bpy.data.images.load(path, check_existing=True)
138
+ bg = nt.nodes.new("ShaderNodeBackground")
139
+ bg.location = (-150, 0)
140
+ bg.inputs["Strength"].default_value = float(strength)
141
+ out = nt.nodes.new("ShaderNodeOutputWorld")
142
+ out.location = (100, 0)
143
+ nt.links.new(coord.outputs["Generated"], mapping.inputs["Vector"])
144
+ nt.links.new(mapping.outputs["Vector"], env.inputs["Vector"])
145
+ nt.links.new(env.outputs["Color"], bg.inputs["Color"])
146
+ nt.links.new(bg.outputs["Background"], out.inputs["Surface"])
147
+ return {"world": world.name, "hdri": os.path.basename(path), "strength": strength,
148
+ "rotation_deg": rotation_deg}
package/core/bridge.mjs CHANGED
@@ -1,63 +1,58 @@
1
1
  // adobe-mcp core bridge: routes ExtendScript to each app.
2
- // AE/PS/AI: osascript (AppleScript DoScript / do javascript).
3
- // Premiere: command-file handoff to the mcp-bridge CEP panel.
2
+ // macOS AE/PS/AI: osascript (AppleScript DoScript / do javascript).
3
+ // Windows AE: AfterFX.exe -r <file.jsx> (no COM server); PS/AI: COM DoJavaScriptFile via cscript.
4
+ // Both Premiere: command-file handoff to the mcp-bridge CEP panel.
4
5
  import { execFile } from "node:child_process";
5
6
  import fs from "node:fs";
6
7
  import os from "node:os";
7
8
  import path from "node:path";
8
9
  import { fileURLToPath } from "node:url";
9
10
  import { logError, matchError, hintBlock } from "../knowledge/knowledge.mjs";
11
+ import { WORKSPACE } from "./workspace.mjs";
12
+ import {
13
+ IS_WIN,
14
+ IS_MAC,
15
+ PLATFORM_LABEL,
16
+ macAppName,
17
+ aeExecutable,
18
+ runningAeExecutable,
19
+ COM_PROGIDS,
20
+ isAppRunning,
21
+ downscalePng as platformDownscale,
22
+ } from "./platform.mjs";
10
23
 
11
24
  const __dirname = path.dirname(fileURLToPath(import.meta.url));
12
25
  const HARNESS = fs.readFileSync(path.join(__dirname, "harness.jsx"), "utf8");
26
+ const COM_RUNNER = path.join(__dirname, "win", "run_com.js");
13
27
 
14
- export const WORKSPACE =
15
- process.env.ADOBE_MCP_WORKSPACE || path.join(os.homedir(), "AdobeMCP");
16
- export const PPRO_BRIDGE_DIR = path.join(WORKSPACE, "ppro-bridge");
17
- fs.mkdirSync(WORKSPACE, { recursive: true });
28
+ export { WORKSPACE };
29
+ // The CEP panel cannot see ADOBE_MCP_WORKSPACE (it runs inside Premiere), so the command
30
+ // folder is always ~/AdobeMCP/ppro-bridge, wherever the asset workspace lives.
31
+ export const PPRO_BRIDGE_DIR = path.join(os.homedir(), "AdobeMCP", "ppro-bridge");
18
32
  fs.mkdirSync(PPRO_BRIDGE_DIR, { recursive: true });
19
33
 
20
34
  // ---------------------------------------------------------------------------
21
35
  // App registry
22
36
  // ---------------------------------------------------------------------------
23
37
 
24
- function findApp(dirPattern, fallback, envVar) {
25
- if (process.env[envVar]) return process.env[envVar];
26
- try {
27
- const dirs = fs
28
- .readdirSync("/Applications")
29
- .filter((e) => dirPattern.test(e))
30
- .sort();
31
- if (dirs.length) {
32
- const dir = dirs[dirs.length - 1];
33
- if (dir.endsWith(".app")) return dir.replace(/\.app$/, "");
34
- const inner = fs
35
- .readdirSync(path.join("/Applications", dir))
36
- .find((f) => f.endsWith(".app"));
37
- if (inner) return inner.replace(/\.app$/, "");
38
- return dir;
39
- }
40
- } catch {
41
- /* fall through */
42
- }
43
- return fallback;
44
- }
38
+ const AE_PREF_HINT =
39
+ ' Enable AE Preferences → Scripting & Expressions → "Allow Scripts to Write Files and Access Network".';
45
40
 
46
41
  export const APPS = {
47
42
  ae: {
48
43
  label: "After Effects",
49
- bridge: "osascript",
50
- appName: () => findApp(/^Adobe After Effects/i, "Adobe After Effects", "AE_APP_NAME"),
44
+ bridge: IS_WIN ? "afterfx" : "osascript",
45
+ appName: () => macAppName(/^Adobe After Effects/i, "Adobe After Effects", "AE_APP_NAME"),
51
46
  osa: (app, jsxPath) =>
52
47
  `tell application "${app}" to DoScript "$.evalFile('${jsxPath}')"`,
53
48
  undoGroup: true,
54
- writePrefHint:
55
- ' Enable AE Preferences → Scripting & Expressions → "Allow Scripts to Write Files and Access Network".',
49
+ writePrefHint: AE_PREF_HINT,
56
50
  },
57
51
  ps: {
58
52
  label: "Photoshop",
59
- bridge: "osascript",
60
- appName: () => findApp(/^Adobe Photoshop/i, "Adobe Photoshop 2026", "PS_APP_NAME"),
53
+ bridge: IS_WIN ? "com" : "osascript",
54
+ appName: () => macAppName(/^Adobe Photoshop/i, "Adobe Photoshop 2026", "PS_APP_NAME"),
55
+ progId: COM_PROGIDS.ps,
61
56
  osa: (app, jsxPath) =>
62
57
  `tell application "${app}" to do javascript "$.evalFile(new File('${jsxPath}'))"`,
63
58
  undoGroup: false,
@@ -65,8 +60,9 @@ export const APPS = {
65
60
  },
66
61
  ai: {
67
62
  label: "Illustrator",
68
- bridge: "osascript",
69
- appName: () => findApp(/^Adobe Illustrator/i, "Adobe Illustrator", "AI_APP_NAME"),
63
+ bridge: IS_WIN ? "com" : "osascript",
64
+ appName: () => macAppName(/^Adobe Illustrator/i, "Adobe Illustrator", "AI_APP_NAME"),
65
+ progId: COM_PROGIDS.ai,
70
66
  osa: (app, jsxPath) =>
71
67
  `tell application "${app}" to do javascript "$.evalFile(new File('${jsxPath}'))"`,
72
68
  undoGroup: false,
@@ -75,7 +71,7 @@ export const APPS = {
75
71
  ppro: {
76
72
  label: "Premiere Pro",
77
73
  bridge: "panel",
78
- appName: () => findApp(/^Adobe Premiere Pro/i, "Adobe Premiere Pro 2026", "PPRO_APP_NAME"),
74
+ appName: () => macAppName(/^Adobe Premiere Pro/i, "Adobe Premiere Pro 2026", "PPRO_APP_NAME"),
79
75
  undoGroup: false,
80
76
  writePrefHint: "",
81
77
  },
@@ -85,12 +81,12 @@ export const APPS = {
85
81
  // Execution
86
82
  // ---------------------------------------------------------------------------
87
83
 
88
- function osascript(script, timeoutMs) {
84
+ function exec(cmd, args, timeoutMs) {
89
85
  return new Promise((resolve, reject) => {
90
86
  execFile(
91
- "osascript",
92
- ["-e", script],
93
- { timeout: timeoutMs, killSignal: "SIGKILL" },
87
+ cmd,
88
+ args,
89
+ { timeout: timeoutMs, killSignal: "SIGKILL", windowsHide: true },
94
90
  (err, stdout, stderr) => {
95
91
  if (err) {
96
92
  err.stderr = stderr;
@@ -101,17 +97,47 @@ function osascript(script, timeoutMs) {
101
97
  });
102
98
  }
103
99
 
100
+ const osascript = (script, timeoutMs) => exec("osascript", ["-e", script], timeoutMs);
101
+
102
+ /** Map a launcher failure to an actionable hint. Pure, so it is unit-tested on every OS. */
103
+ export function launchFailureHint(app, err, timeoutMs, scriptPath) {
104
+ const msg = String(err.stderr || err.message || err);
105
+ if (err.killed || /timed?.?out/i.test(msg))
106
+ return ` Timed out after ${timeoutMs / 1000}s — ${app.label} may be showing a modal dialog, or raise timeout_seconds. Script kept: ${scriptPath}`;
107
+ // macOS AppleScript errors
108
+ if (/-600|isn.t running|can.t be found|-1728|-10810/i.test(msg))
109
+ return ` Is ${app.label} open? (Looked for app "${app.appName()}"; override with env var.)`;
110
+ if (/-1743|not authori[sz]ed/i.test(msg))
111
+ return ` macOS blocked Automation permission for ${app.label} — approve in System Settings → Privacy & Security → Automation.`;
112
+ // Windows COM errors (run_com.js prints COM_CREATE_FAILED / COM_CALL_FAILED 0x<hresult>)
113
+ if (/COM_CREATE_FAILED/.test(msg) && /800401f3|800a01ad|80040154/i.test(msg))
114
+ return ` ${app.label} is not registered for COM automation — is it installed? Run it once as a normal user, or set ${app.label === "Photoshop" ? "PS" : "AI"}_COM_PROGID (e.g. "Photoshop.Application.200").`;
115
+ if (/COM_CREATE_FAILED/.test(msg) && /80080005|800706ba|80010001/i.test(msg))
116
+ return ` ${app.label} did not answer COM — it may be starting up or showing a modal dialog. Try again once it is idle.`;
117
+ if (/COM_CREATE_FAILED/.test(msg) && /80070005/i.test(msg))
118
+ return ` Access denied: ${app.label} and this MCP client must run at the same privilege level (both normal, or both "Run as administrator").`;
119
+ if (/ENOENT/.test(msg) && /cscript/i.test(msg))
120
+ return " Windows Script Host (cscript.exe) is missing or disabled by policy; it is needed to reach Photoshop/Illustrator over COM.";
121
+ return "";
122
+ }
123
+
104
124
  const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
105
125
 
106
126
  function writeHarnessed(appKey, userCode, resultPath, scriptPath) {
107
127
  const app = APPS[appKey];
108
128
  const undoOpen = app.undoGroup ? "app.beginUndoGroup('adobe-mcp');" : "";
109
129
  const undoClose = app.undoGroup ? "app.endUndoGroup();" : "";
110
- const wrapped = HARNESS.replace(/__RESULT_PATH__/g, () => JSON.stringify(resultPath))
130
+ const wrapped = HARNESS.replace(/__RESULT_PATH__/g, () => jsxString(resultPath))
111
131
  .replace(/__USER_CODE__/g, () => userCode)
112
132
  .replace(/__UNDO_OPEN__/g, () => undoOpen)
113
133
  .replace(/__UNDO_CLOSE__/g, () => undoClose);
114
- fs.writeFileSync(scriptPath, wrapped, "utf8");
134
+ // Windows ExtendScript reads BOM-less files in the ANSI code page; the BOM keeps non-ASCII user code intact.
135
+ fs.writeFileSync(scriptPath, (IS_WIN ? "\uFEFF" : "") + wrapped, "utf8");
136
+ }
137
+
138
+ /** JS string literal with non-ASCII escaped, so paths like C:\Users\José survive any file encoding. */
139
+ export function jsxString(str) {
140
+ return JSON.stringify(String(str)).replace(/[\u007f-\uffff]/g, (c) => "\\u" + c.charCodeAt(0).toString(16).padStart(4, "0"));
115
141
  }
116
142
 
117
143
  async function awaitResultFile(resultPath, timeoutMs, failMsg) {
@@ -164,27 +190,21 @@ export async function runJSX(appKey, userCode, timeoutMs = 120000) {
164
190
  async function runJSXInner(appKey, userCode, timeoutMs = 120000) {
165
191
  const app = APPS[appKey];
166
192
  if (!app) throw new Error(`Unknown app "${appKey}". Use: ${Object.keys(APPS).join(", ")}`);
193
+ if (!IS_MAC && !IS_WIN)
194
+ throw new Error(`Adobe apps need macOS or Windows; this server is running on ${PLATFORM_LABEL}. Blender and texture tools still work here.`);
167
195
  const stamp = `${Date.now()}_${Math.floor(Math.random() * 1e6)}`;
168
196
  const resultPath = path.join(os.tmpdir(), `adobe_mcp_result_${appKey}_${stamp}.json`);
169
197
  const scriptPath = path.join(os.tmpdir(), `adobe_mcp_script_${appKey}_${stamp}.jsx`);
170
198
  writeHarnessed(appKey, userCode, resultPath, scriptPath);
171
199
 
172
- if (app.bridge === "osascript") {
173
- const appName = app.appName();
200
+ if (app.bridge === "osascript" || app.bridge === "com") {
174
201
  try {
175
- await osascript(app.osa(appName, scriptPath), timeoutMs);
202
+ if (app.bridge === "osascript") await osascript(app.osa(app.appName(), scriptPath), timeoutMs);
203
+ else await exec("cscript.exe", ["//nologo", "//E:JScript", COM_RUNNER, app.progId(), scriptPath], timeoutMs);
176
204
  } catch (err) {
177
205
  fs.rmSync(resultPath, { force: true });
178
- const msg = String(err.stderr || err.message || err);
179
- let hint = "";
180
- if (err.killed || /timed?.?out/i.test(msg)) {
181
- hint = ` Timed out after ${timeoutMs / 1000}s — ${app.label} may be showing a modal dialog, or raise timeout_seconds. Script kept: ${scriptPath}`;
182
- } else if (/-600|isn.t running|can.t be found|-1728|-10810/i.test(msg)) {
183
- hint = ` Is ${app.label} open? (Looked for app "${appName}"; override with env var.)`;
184
- } else if (/-1743|not authori[sz]ed/i.test(msg)) {
185
- hint = ` macOS blocked Automation permission for ${app.label} — approve in System Settings → Privacy & Security → Automation.`;
186
- }
187
- throw new Error(`osascript failed: ${msg.trim()}.${hint}`);
206
+ const msg = String(err.stderr || err.message || err).trim();
207
+ throw new Error(`${app.bridge === "com" ? "COM" : "osascript"} call failed: ${msg}.${launchFailureHint(app, err, timeoutMs, scriptPath)}`);
188
208
  }
189
209
  const result = await awaitResultFile(
190
210
  resultPath,
@@ -195,12 +215,45 @@ async function runJSXInner(appKey, userCode, timeoutMs = 120000) {
195
215
  return result;
196
216
  }
197
217
 
218
+ if (app.bridge === "afterfx") {
219
+ // AfterFX.exe -r hands the file to the running instance. Whether it returns at once or waits
220
+ // for the script, the caller's timeout is measured on the result file, not the launcher.
221
+ // Prefer the running instance's own AfterFX.exe: -r on a different installed version would
222
+ // start a second After Effects.
223
+ const exe = (await runningAeExecutable()) || aeExecutable();
224
+ if (!exe)
225
+ throw new Error(
226
+ "After Effects not found under Program Files\\Adobe. Set AE_EXE to the full path of AfterFX.exe."
227
+ );
228
+ if ((await isAppRunning("ae")) === false)
229
+ throw new Error(`Is After Effects open? Start it (with a project, even the empty default) and retry. (Would launch: ${exe})`);
230
+ const started = Date.now();
231
+ try {
232
+ await exec(exe, ["-r", scriptPath], Math.min(timeoutMs, 30000));
233
+ } catch (err) {
234
+ // If AfterFX.exe -r waits for the script to finish, a long script outlives the launcher's
235
+ // timeout: keep waiting for the result file instead of failing.
236
+ if (!err.killed) {
237
+ fs.rmSync(resultPath, { force: true });
238
+ const msg = String(err.stderr || err.message || err).trim();
239
+ throw new Error(`AfterFX.exe -r failed: ${msg}.${launchFailureHint(app, err, timeoutMs, scriptPath)}`);
240
+ }
241
+ }
242
+ const result = await awaitResultFile(
243
+ resultPath,
244
+ Math.max(timeoutMs - (Date.now() - started), 15000),
245
+ `After Effects accepted the script but no result file appeared within ${timeoutMs / 1000}s. A modal dialog may be open.${app.writePrefHint} Script kept: ${scriptPath}`
246
+ );
247
+ fs.rmSync(scriptPath, { force: true });
248
+ return result;
249
+ }
250
+
198
251
  // panel bridge (Premiere)
199
252
  if (!pproPanelAlive()) {
200
253
  throw new Error(
201
- "Premiere mcp-bridge panel is not running. In Premiere: Window → Extensions → MCP Bridge " +
202
- "(requires the panel installed under ~/Library/Application Support/Adobe/CEP/extensions and " +
203
- "PlayerDebugMode=1 for com.adobe.CSXS.11)."
254
+ "Premiere mcp-bridge panel is not running. In Premiere: Window → Extensions → MCP Bridge. " +
255
+ "Not in the menu? Run `npx @ajsmonty/adobe-mcp install` (copies the panel and enables PlayerDebugMode), " +
256
+ "restart Premiere, then check with `npx @ajsmonty/adobe-mcp doctor`."
204
257
  );
205
258
  }
206
259
  const cmdPath = path.join(PPRO_BRIDGE_DIR, `cmd_${stamp}.json`);
@@ -214,9 +267,5 @@ async function runJSXInner(appKey, userCode, timeoutMs = 120000) {
214
267
  return result;
215
268
  }
216
269
 
217
- // Small helper shared by preview tools: downscale a PNG with sips.
218
- export async function downscalePng(pngPath, maxWidth) {
219
- await new Promise((resolve) =>
220
- execFile("sips", ["-Z", String(maxWidth), pngPath], () => resolve())
221
- );
222
- }
270
+ // Shared by preview tools: downscale a PNG in place (sips on macOS, System.Drawing on Windows).
271
+ export const downscalePng = platformDownscale;
@@ -0,0 +1,34 @@
1
+ # adobe-mcp Python harness (Blender + Substance 3D Painter).
2
+ # Runs the user's code as a module body in a fresh namespace, captures stdout, and writes
3
+ # {ok, result, stdout} or {ok: false, error, line, traceback} as JSON to __RESULT_PATH__.
4
+ # Set `result = <value>` in user code to return data (non-JSON values are str()-ed).
5
+ def __adobe_mcp_run():
6
+ import base64, contextlib, io, json, traceback
7
+
8
+ code = base64.b64decode("__USER_CODE_B64__").decode("utf-8")
9
+ ns = {"__name__": "__adobe_mcp__"}
10
+ out = io.StringIO()
11
+ try:
12
+ with contextlib.redirect_stdout(out):
13
+ exec(compile(code, "<adobe-mcp>", "exec"), ns)
14
+ res = {"ok": True, "result": ns.get("result"), "stdout": out.getvalue()[-8000:]}
15
+ except BaseException as e: # SystemExit from user code must still report back
16
+ line = None
17
+ if isinstance(e, SyntaxError) and e.filename == "<adobe-mcp>":
18
+ line = e.lineno
19
+ for fr in traceback.extract_tb(e.__traceback__):
20
+ if fr.filename == "<adobe-mcp>":
21
+ line = fr.lineno
22
+ res = {
23
+ "ok": False,
24
+ "error": "%s: %s" % (type(e).__name__, e),
25
+ "line": line,
26
+ "traceback": traceback.format_exc()[-4000:],
27
+ "stdout": out.getvalue()[-4000:],
28
+ }
29
+ with open(__RESULT_PATH__, "w", encoding="utf-8") as f:
30
+ f.write(json.dumps(res, default=str))
31
+ return res
32
+
33
+
34
+ __adobe_mcp_run()
@@ -0,0 +1,205 @@
1
+ // Platform layer: everything that differs between macOS and Windows lives here, so the
2
+ // bridges and the CLI share one answer to "where is the app?", "is it running?" and
3
+ // "where do CEP panels go?".
4
+ import { execFile } from "node:child_process";
5
+ import fs from "node:fs";
6
+ import os from "node:os";
7
+ import path from "node:path";
8
+
9
+ export const IS_WIN = process.platform === "win32";
10
+ export const IS_MAC = process.platform === "darwin";
11
+ export const PLATFORM_LABEL = IS_WIN ? "Windows" : IS_MAC ? "macOS" : process.platform;
12
+
13
+ /** Directories Adobe (and Blender) installers use on this OS. */
14
+ export function programRoots() {
15
+ if (IS_MAC) return ["/Applications"];
16
+ if (IS_WIN) {
17
+ const roots = [process.env.ProgramFiles || "C:\\Program Files", process.env["ProgramFiles(x86)"]];
18
+ return [...new Set(roots.filter(Boolean))];
19
+ }
20
+ return [];
21
+ }
22
+
23
+ export function adobeRoots() {
24
+ if (IS_MAC) return ["/Applications"];
25
+ return programRoots().map((r) => path.join(r, "Adobe"));
26
+ }
27
+
28
+ function listDir(dir) {
29
+ try {
30
+ return fs.readdirSync(dir);
31
+ } catch {
32
+ return [];
33
+ }
34
+ }
35
+
36
+ /** Version-aware sort: "Adobe Photoshop 2026" after "Adobe Photoshop 2025", "Blender 4.10" after "Blender 4.9". */
37
+ export function versionSort(names) {
38
+ return [...names].sort((a, b) => a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }));
39
+ }
40
+
41
+ /** Install directories matching `pattern` under the Adobe roots, newest last. */
42
+ export function findAdobeInstallDirs(pattern) {
43
+ const out = [];
44
+ for (const root of adobeRoots())
45
+ for (const e of listDir(root)) if (pattern.test(e)) out.push(path.join(root, e));
46
+ return versionSort(out);
47
+ }
48
+
49
+ /**
50
+ * macOS application name ("Adobe After Effects 2026") for AppleScript `tell application`.
51
+ * Handles both bare bundles (/Applications/Foo.app) and folders that contain one.
52
+ */
53
+ export function macAppName(dirPattern, fallback, envVar) {
54
+ if (process.env[envVar]) return process.env[envVar];
55
+ const dirs = versionSort(listDir("/Applications").filter((e) => dirPattern.test(e)));
56
+ if (!dirs.length) return fallback;
57
+ const dir = dirs[dirs.length - 1];
58
+ if (dir.endsWith(".app")) return dir.replace(/\.app$/, "");
59
+ const inner = listDir(path.join("/Applications", dir)).find((f) => f.endsWith(".app"));
60
+ return inner ? inner.replace(/\.app$/, "") : dir;
61
+ }
62
+
63
+ /** Windows: newest AfterFX.exe (override with AE_EXE). */
64
+ export function aeExecutable() {
65
+ if (process.env.AE_EXE) return process.env.AE_EXE;
66
+ const dirs = findAdobeInstallDirs(/^Adobe After Effects/i).reverse();
67
+ for (const d of dirs) {
68
+ const exe = path.join(d, "Support Files", "AfterFX.exe");
69
+ if (fs.existsSync(exe)) return exe;
70
+ }
71
+ return null;
72
+ }
73
+
74
+ /** Windows COM ProgIDs. The unversioned ID binds to the newest registered version. */
75
+ export const COM_PROGIDS = {
76
+ ps: () => process.env.PS_COM_PROGID || "Photoshop.Application",
77
+ ai: () => process.env.AI_COM_PROGID || "Illustrator.Application",
78
+ };
79
+
80
+ /** Per-user CEP extensions folder (no admin rights needed). */
81
+ export function cepExtensionsDir() {
82
+ if (IS_WIN) return path.join(process.env.APPDATA || path.join(os.homedir(), "AppData", "Roaming"), "Adobe", "CEP", "extensions");
83
+ return path.join(os.homedir(), "Library", "Application Support", "Adobe", "CEP", "extensions");
84
+ }
85
+
86
+ /** CSXS versions we set PlayerDebugMode for (Premiere 2020 → current). */
87
+ export const CSXS_VERSIONS = [9, 10, 11, 12];
88
+
89
+ /** execFile that never throws: synchronous spawn errors (e.g. EINVAL for .cmd files) resolve as { ok: false }. */
90
+ export function run(cmd, args, opts = {}) {
91
+ return new Promise((resolve) => {
92
+ try {
93
+ execFile(cmd, args, { timeout: 15000, windowsHide: true, ...opts }, (err, stdout, stderr) =>
94
+ resolve({ ok: !err, code: err?.code, stdout: String(stdout || ""), stderr: String(stderr || ""), err })
95
+ );
96
+ } catch (err) {
97
+ resolve({ ok: false, code: err.code, stdout: "", stderr: String(err.message || err), err });
98
+ }
99
+ });
100
+ }
101
+
102
+ /** Names of running processes, lower-cased; null when the process list could not be read. */
103
+ export async function runningProcesses() {
104
+ if (IS_WIN) {
105
+ const r = await run("tasklist", ["/fo", "csv", "/nh"]);
106
+ if (!r.ok) return null;
107
+ return r.stdout
108
+ .split(/\r?\n/)
109
+ .map((l) => (l.match(/^"([^"]+)"/) || [])[1])
110
+ .filter(Boolean)
111
+ .map((s) => s.toLowerCase());
112
+ }
113
+ const r = await run("ps", ["-axo", "comm="]);
114
+ if (!r.ok) return null;
115
+ return r.stdout
116
+ .split("\n")
117
+ .map((l) => path.basename(l.trim()).toLowerCase())
118
+ .filter(Boolean);
119
+ }
120
+
121
+ /** Process-name prefixes per app, used by "is it running?" checks. */
122
+ export const PROCESS_NAMES = {
123
+ ae: IS_WIN ? ["afterfx.exe"] : ["after effects"],
124
+ ps: IS_WIN ? ["photoshop.exe"] : ["adobe photoshop"],
125
+ ai: IS_WIN ? ["illustrator.exe"] : ["adobe illustrator"],
126
+ ppro: IS_WIN ? ["adobe premiere pro.exe"] : ["adobe premiere pro"],
127
+ ch: IS_WIN ? ["character animator.exe"] : ["character animator"],
128
+ blender: IS_WIN ? ["blender.exe"] : ["blender"],
129
+ substance: IS_WIN ? ["adobe substance 3d painter.exe"] : ["adobe substance 3d painter"],
130
+ };
131
+
132
+ /** true / false, or null when the process list is unavailable (callers must not block on null). */
133
+ export async function isAppRunning(appKey, procs) {
134
+ const list = procs === undefined ? await runningProcesses() : procs;
135
+ if (!list) return null;
136
+ return list.some((p) => PROCESS_NAMES[appKey].some((n) => p.includes(n)));
137
+ }
138
+
139
+ /** Windows: full path of the After Effects instance that is running now (so -r reaches it, not a newer install). */
140
+ export async function runningAeExecutable() {
141
+ if (!IS_WIN) return null;
142
+ const r = await run("powershell.exe", [
143
+ "-NoProfile",
144
+ "-NonInteractive",
145
+ "-Command",
146
+ "(Get-Process -Name AfterFX -ErrorAction SilentlyContinue | Select-Object -First 1).Path",
147
+ ]);
148
+ const p = r.ok ? r.stdout.trim() : "";
149
+ return p && fs.existsSync(p) ? p : null;
150
+ }
151
+
152
+ /**
153
+ * Downscale a PNG in place so its width is at most maxWidth.
154
+ * macOS: sips. Windows: System.Drawing via Windows PowerShell (paths passed through
155
+ * env vars, never interpolated into the script). Elsewhere: no-op.
156
+ */
157
+ export async function downscalePng(pngPath, maxWidth) {
158
+ if (IS_MAC) {
159
+ await run("sips", ["-Z", String(maxWidth), pngPath], { timeout: 30000 });
160
+ return;
161
+ }
162
+ if (IS_WIN) {
163
+ const ps = [
164
+ "Add-Type -AssemblyName System.Drawing",
165
+ "$p = $env:ADOBE_MCP_PNG; $max = [int]$env:ADOBE_MCP_MAXW",
166
+ "$src = [System.Drawing.Image]::FromFile($p)",
167
+ "if ($src.Width -le $max) { $src.Dispose(); exit 0 }",
168
+ "$w = $max; $h = [int][Math]::Round($src.Height * $max / $src.Width)",
169
+ "$bmp = New-Object System.Drawing.Bitmap $w, $h",
170
+ "$g = [System.Drawing.Graphics]::FromImage($bmp)",
171
+ "$g.InterpolationMode = [System.Drawing.Drawing2D.InterpolationMode]::HighQualityBicubic",
172
+ "$g.DrawImage($src, 0, 0, $w, $h); $g.Dispose(); $src.Dispose()",
173
+ "$bmp.Save($p, [System.Drawing.Imaging.ImageFormat]::Png); $bmp.Dispose()",
174
+ ].join("; ");
175
+ await run("powershell.exe", ["-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-Command", ps], {
176
+ timeout: 30000,
177
+ env: { ...process.env, ADOBE_MCP_PNG: pngPath, ADOBE_MCP_MAXW: String(maxWidth) },
178
+ });
179
+ }
180
+ }
181
+
182
+ /** How to start Substance 3D Painter with remote scripting on this OS. */
183
+ export function substanceLaunchHint() {
184
+ if (IS_WIN)
185
+ return '"C:\\Program Files\\Adobe\\Adobe Substance 3D Painter\\Adobe Substance 3D Painter.exe" --enable-remote-scripting';
186
+ return 'open -a "Adobe Substance 3D Painter" --args --enable-remote-scripting';
187
+ }
188
+
189
+ /** Blender executable candidates for this OS, newest first. */
190
+ export function blenderCandidates() {
191
+ const out = [];
192
+ if (IS_MAC) {
193
+ out.push("/Applications/Blender.app/Contents/MacOS/Blender");
194
+ for (const e of versionSort(listDir("/Applications").filter((d) => /^Blender.*\.app$/i.test(d))).reverse())
195
+ out.push(path.join("/Applications", e, "Contents/MacOS/Blender"));
196
+ } else if (IS_WIN) {
197
+ for (const root of programRoots()) {
198
+ const foundation = path.join(root, "Blender Foundation");
199
+ for (const e of versionSort(listDir(foundation).filter((d) => /^Blender/i.test(d))).reverse())
200
+ out.push(path.join(foundation, e, "blender.exe"));
201
+ }
202
+ // Steam / Microsoft Store installs land elsewhere: BLENDER_PATH covers those.
203
+ }
204
+ return out;
205
+ }