@ajsmonty/adobe-mcp 1.1.2 → 1.5.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.
Files changed (41) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/README.md +361 -119
  3. package/SECURITY.md +24 -1
  4. package/adapters/ae_more.mjs +208 -0
  5. package/adapters/an.mjs +96 -0
  6. package/adapters/assets.mjs +194 -0
  7. package/adapters/blender.mjs +230 -0
  8. package/adapters/id.mjs +250 -0
  9. package/adapters/ppro.mjs +4 -3
  10. package/adapters/ppro_more.mjs +393 -0
  11. package/adapters/ps_ai_more.mjs +277 -0
  12. package/adapters/substance.mjs +193 -0
  13. package/adapters/texlib.mjs +193 -0
  14. package/bridges/blender/adobe_mcp_bridge.py +132 -0
  15. package/cep/mcp-bridge/CSXS/manifest.xml +36 -2
  16. package/cep/mcp-bridge/main.js +48 -20
  17. package/cli/doctor.mjs +234 -0
  18. package/cli/index.mjs +67 -0
  19. package/cli/install.mjs +149 -0
  20. package/core/barrows.mjs +16 -0
  21. package/core/blender_pbr.py +148 -0
  22. package/core/bridge.mjs +166 -77
  23. package/core/harness.jsx +11 -6
  24. package/core/harness.py +34 -0
  25. package/core/helpers.mjs +196 -0
  26. package/core/platform.mjs +209 -0
  27. package/core/pybridge.mjs +256 -0
  28. package/core/telemetry.mjs +80 -0
  29. package/core/texlib.mjs +279 -0
  30. package/core/win/run_com.js +33 -0
  31. package/core/workspace.mjs +1 -1
  32. package/knowledge/knowledge.mjs +8 -5
  33. package/knowledge/lessons.jsonl +19 -0
  34. package/package.json +56 -3
  35. package/scripts/ae/Cinematic_3D_Composite.jsx +173 -0
  36. package/scripts/blender/Creature_Walk_Cinematic.py +569 -0
  37. package/scripts/substance/Creature_Skin_LookDev.py +148 -0
  38. package/server.mjs +92 -27
  39. package/workflow/setup.mjs +106 -0
  40. package/workflow/vfx.mjs +136 -0
  41. package/workflow/workflow.mjs +66 -21
@@ -0,0 +1,209 @@
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
+ id: () => process.env.ID_COM_PROGID || "InDesign.Application",
79
+ };
80
+
81
+ /** Per-user CEP extensions folder (no admin rights needed). */
82
+ export function cepExtensionsDir() {
83
+ if (IS_WIN) return path.join(process.env.APPDATA || path.join(os.homedir(), "AppData", "Roaming"), "Adobe", "CEP", "extensions");
84
+ return path.join(os.homedir(), "Library", "Application Support", "Adobe", "CEP", "extensions");
85
+ }
86
+
87
+ /** CSXS versions we set PlayerDebugMode for (Premiere 2020 → current). */
88
+ export const CSXS_VERSIONS = [9, 10, 11, 12];
89
+
90
+ /** execFile that never throws: synchronous spawn errors (e.g. EINVAL for .cmd files) resolve as { ok: false }. */
91
+ export function run(cmd, args, opts = {}) {
92
+ return new Promise((resolve) => {
93
+ try {
94
+ execFile(cmd, args, { timeout: 15000, windowsHide: true, ...opts }, (err, stdout, stderr) =>
95
+ resolve({ ok: !err, code: err?.code, stdout: String(stdout || ""), stderr: String(stderr || ""), err })
96
+ );
97
+ } catch (err) {
98
+ resolve({ ok: false, code: err.code, stdout: "", stderr: String(err.message || err), err });
99
+ }
100
+ });
101
+ }
102
+
103
+ /** Names of running processes, lower-cased; null when the process list could not be read. */
104
+ export async function runningProcesses() {
105
+ if (IS_WIN) {
106
+ const r = await run("tasklist", ["/fo", "csv", "/nh"]);
107
+ if (!r.ok) return null;
108
+ return r.stdout
109
+ .split(/\r?\n/)
110
+ .map((l) => (l.match(/^"([^"]+)"/) || [])[1])
111
+ .filter(Boolean)
112
+ .map((s) => s.toLowerCase());
113
+ }
114
+ const r = await run("ps", ["-axo", "comm="]);
115
+ if (!r.ok) return null;
116
+ return r.stdout
117
+ .split("\n")
118
+ .map((l) => path.basename(l.trim()).toLowerCase())
119
+ .filter(Boolean);
120
+ }
121
+
122
+ /** Process-name prefixes per app, used by "is it running?" checks. */
123
+ export const PROCESS_NAMES = {
124
+ ae: IS_WIN ? ["afterfx.exe"] : ["after effects"],
125
+ ps: IS_WIN ? ["photoshop.exe"] : ["adobe photoshop"],
126
+ ai: IS_WIN ? ["illustrator.exe"] : ["adobe illustrator"],
127
+ ppro: IS_WIN ? ["adobe premiere pro.exe"] : ["adobe premiere pro"],
128
+ ch: IS_WIN ? ["character animator.exe"] : ["character animator"],
129
+ blender: IS_WIN ? ["blender.exe"] : ["blender"],
130
+ substance: IS_WIN ? ["adobe substance 3d painter.exe"] : ["adobe substance 3d painter"],
131
+ id: IS_WIN ? ["indesign.exe"] : ["adobe indesign"],
132
+ an: IS_WIN ? ["animate.exe"] : ["adobe animate"],
133
+ ame: IS_WIN ? ["adobe media encoder.exe"] : ["adobe media encoder"],
134
+ };
135
+
136
+ /** true / false, or null when the process list is unavailable (callers must not block on null). */
137
+ export async function isAppRunning(appKey, procs) {
138
+ const list = procs === undefined ? await runningProcesses() : procs;
139
+ if (!list) return null;
140
+ return list.some((p) => PROCESS_NAMES[appKey].some((n) => p.includes(n)));
141
+ }
142
+
143
+ /** Windows: full path of the After Effects instance that is running now (so -r reaches it, not a newer install). */
144
+ export async function runningAeExecutable() {
145
+ if (!IS_WIN) return null;
146
+ const r = await run("powershell.exe", [
147
+ "-NoProfile",
148
+ "-NonInteractive",
149
+ "-Command",
150
+ "(Get-Process -Name AfterFX -ErrorAction SilentlyContinue | Select-Object -First 1).Path",
151
+ ]);
152
+ const p = r.ok ? r.stdout.trim() : "";
153
+ return p && fs.existsSync(p) ? p : null;
154
+ }
155
+
156
+ /**
157
+ * Downscale a PNG in place so its width is at most maxWidth.
158
+ * macOS: sips. Windows: System.Drawing via Windows PowerShell (paths passed through
159
+ * env vars, never interpolated into the script). Elsewhere: no-op.
160
+ */
161
+ export async function downscalePng(pngPath, maxWidth) {
162
+ if (IS_MAC) {
163
+ await run("sips", ["-Z", String(maxWidth), pngPath], { timeout: 30000 });
164
+ return;
165
+ }
166
+ if (IS_WIN) {
167
+ const ps = [
168
+ "Add-Type -AssemblyName System.Drawing",
169
+ "$p = $env:ADOBE_MCP_PNG; $max = [int]$env:ADOBE_MCP_MAXW",
170
+ "$src = [System.Drawing.Image]::FromFile($p)",
171
+ "if ($src.Width -le $max) { $src.Dispose(); exit 0 }",
172
+ "$w = $max; $h = [int][Math]::Round($src.Height * $max / $src.Width)",
173
+ "$bmp = New-Object System.Drawing.Bitmap $w, $h",
174
+ "$g = [System.Drawing.Graphics]::FromImage($bmp)",
175
+ "$g.InterpolationMode = [System.Drawing.Drawing2D.InterpolationMode]::HighQualityBicubic",
176
+ "$g.DrawImage($src, 0, 0, $w, $h); $g.Dispose(); $src.Dispose()",
177
+ "$bmp.Save($p, [System.Drawing.Imaging.ImageFormat]::Png); $bmp.Dispose()",
178
+ ].join("; ");
179
+ await run("powershell.exe", ["-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-Command", ps], {
180
+ timeout: 30000,
181
+ env: { ...process.env, ADOBE_MCP_PNG: pngPath, ADOBE_MCP_MAXW: String(maxWidth) },
182
+ });
183
+ }
184
+ }
185
+
186
+ /** How to start Substance 3D Painter with remote scripting on this OS. */
187
+ export function substanceLaunchHint() {
188
+ if (IS_WIN)
189
+ return '"C:\\Program Files\\Adobe\\Adobe Substance 3D Painter\\Adobe Substance 3D Painter.exe" --enable-remote-scripting';
190
+ return 'open -a "Adobe Substance 3D Painter" --args --enable-remote-scripting';
191
+ }
192
+
193
+ /** Blender executable candidates for this OS, newest first. */
194
+ export function blenderCandidates() {
195
+ const out = [];
196
+ if (IS_MAC) {
197
+ out.push("/Applications/Blender.app/Contents/MacOS/Blender");
198
+ for (const e of versionSort(listDir("/Applications").filter((d) => /^Blender.*\.app$/i.test(d))).reverse())
199
+ out.push(path.join("/Applications", e, "Contents/MacOS/Blender"));
200
+ } else if (IS_WIN) {
201
+ for (const root of programRoots()) {
202
+ const foundation = path.join(root, "Blender Foundation");
203
+ for (const e of versionSort(listDir(foundation).filter((d) => /^Blender/i.test(d))).reverse())
204
+ out.push(path.join(foundation, e, "blender.exe"));
205
+ }
206
+ // Steam / Microsoft Store installs land elsewhere: BLENDER_PATH covers those.
207
+ }
208
+ return out;
209
+ }
@@ -0,0 +1,256 @@
1
+ // adobe-mcp Python bridges — the 3D side of the pipeline.
2
+ //
3
+ // Blender → live: TCP socket to the adobe-mcp Blender add-on (bridges/blender/)
4
+ // background: headless `blender -b [file.blend] --python <harness>`
5
+ // Substance 3D Painter → HTTP remote scripting (`--enable-remote-scripting`, port 60041, /run.json)
6
+ //
7
+ // Both wrap user code in the same Python harness (core/harness.py): the code runs as a module
8
+ // body, `result = <value>` comes back as JSON, stdout is captured, and exceptions report the
9
+ // failing line of the user's code. Failures go through the same knowledge loop as ExtendScript.
10
+ import { execFile } from "node:child_process";
11
+ import { blenderCandidates, substanceLaunchHint } from "./platform.mjs";
12
+ import fs from "node:fs";
13
+ import net from "node:net";
14
+ import os from "node:os";
15
+ import path from "node:path";
16
+ import { fileURLToPath } from "node:url";
17
+ import { logError, matchError, hintBlock } from "../knowledge/knowledge.mjs";
18
+
19
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
20
+ const PY_HARNESS = fs.readFileSync(path.join(__dirname, "harness.py"), "utf8");
21
+
22
+ export const BLENDER_PORT = Number(process.env.BLENDER_MCP_PORT || 9877);
23
+ export const PAINTER_PORT = Number(process.env.SUBSTANCE_PAINTER_PORT || 60041);
24
+
25
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
26
+
27
+ /** Build the harnessed Python source. The result JSON is written to resultPath. */
28
+ export function harnessPython(userCode, resultPath) {
29
+ const b64 = Buffer.from(userCode, "utf8").toString("base64");
30
+ return PY_HARNESS.replace(/__USER_CODE_B64__/g, () => b64).replace(
31
+ /__RESULT_PATH__/g,
32
+ () => JSON.stringify(resultPath)
33
+ );
34
+ }
35
+
36
+ function stampPaths(appKey) {
37
+ const stamp = `${Date.now()}_${Math.floor(Math.random() * 1e6)}`;
38
+ return {
39
+ resultPath: path.join(os.tmpdir(), `adobe_mcp_result_${appKey}_${stamp}.json`),
40
+ scriptPath: path.join(os.tmpdir(), `adobe_mcp_script_${appKey}_${stamp}.py`),
41
+ };
42
+ }
43
+
44
+ function readResult(resultPath) {
45
+ if (!fs.existsSync(resultPath)) return null;
46
+ const raw = fs.readFileSync(resultPath, "utf8");
47
+ if (!raw.length) return null;
48
+ fs.rmSync(resultPath, { force: true });
49
+ try {
50
+ return JSON.parse(raw);
51
+ } catch {
52
+ throw new Error(`Could not parse result: ${raw.slice(0, 2000)}`);
53
+ }
54
+ }
55
+
56
+ function unwrap(parsed, label) {
57
+ if (!parsed.ok) {
58
+ const err = new Error(
59
+ `${label} Python error (line ${parsed.line ?? "?"}): ${parsed.error}` +
60
+ (parsed.stdout ? `\n--- stdout ---\n${parsed.stdout}` : "") +
61
+ (parsed.traceback ? `\n--- traceback ---\n${parsed.traceback}` : "")
62
+ );
63
+ throw err;
64
+ }
65
+ return { result: parsed.result ?? null, stdout: parsed.stdout || "" };
66
+ }
67
+
68
+ async function withKnowledge(appKey, code, fn) {
69
+ try {
70
+ return await fn();
71
+ } catch (e) {
72
+ logError(appKey, code, e.message || e);
73
+ const hints = matchError(appKey, e.message || String(e));
74
+ if (hints.length) e.message = `${e.message}${hintBlock(hints)}`;
75
+ throw e;
76
+ }
77
+ }
78
+
79
+ // ---------------------------------------------------------------------------
80
+ // Blender
81
+ // ---------------------------------------------------------------------------
82
+
83
+ export function blenderExecutable() {
84
+ if (process.env.BLENDER_PATH) return process.env.BLENDER_PATH;
85
+ return blenderCandidates().find((c) => fs.existsSync(c)) || "blender"; // fall back to PATH
86
+ }
87
+
88
+ /** True when the adobe-mcp Blender add-on is listening. */
89
+ export function blenderLiveAlive(timeoutMs = 400) {
90
+ return new Promise((resolve) => {
91
+ const sock = net.createConnection({ host: "127.0.0.1", port: BLENDER_PORT });
92
+ const done = (v) => {
93
+ sock.destroy();
94
+ resolve(v);
95
+ };
96
+ sock.setTimeout(timeoutMs, () => done(false));
97
+ sock.once("connect", () => done(true));
98
+ sock.once("error", () => done(false));
99
+ });
100
+ }
101
+
102
+ function blenderLive(code, timeoutMs) {
103
+ return new Promise((resolve, reject) => {
104
+ const sock = net.createConnection({ host: "127.0.0.1", port: BLENDER_PORT });
105
+ let buf = "";
106
+ const timer = setTimeout(() => {
107
+ sock.destroy();
108
+ reject(
109
+ new Error(
110
+ `Blender live bridge timed out after ${timeoutMs / 1000}s — Blender may be busy (rendering, modal operator) or raise timeout_seconds.`
111
+ )
112
+ );
113
+ }, timeoutMs);
114
+ sock.setEncoding("utf8");
115
+ sock.once("connect", () => sock.write(JSON.stringify({ code }) + "\n"));
116
+ sock.on("data", (d) => {
117
+ buf += d;
118
+ const nl = buf.indexOf("\n");
119
+ if (nl < 0) return;
120
+ clearTimeout(timer);
121
+ sock.destroy();
122
+ try {
123
+ resolve(JSON.parse(buf.slice(0, nl)));
124
+ } catch {
125
+ reject(new Error(`Blender bridge sent unparseable reply: ${buf.slice(0, 500)}`));
126
+ }
127
+ });
128
+ sock.once("error", (e) => {
129
+ clearTimeout(timer);
130
+ reject(
131
+ new Error(
132
+ `Cannot reach the Blender live bridge on 127.0.0.1:${BLENDER_PORT} (${e.code || e.message}). ` +
133
+ "Install/enable bridges/blender/adobe_mcp_bridge.py as an add-on (Edit → Preferences → Add-ons → Install from Disk), " +
134
+ "or use mode 'background' with a blend_file."
135
+ )
136
+ );
137
+ });
138
+ });
139
+ }
140
+
141
+ function blenderBackground(code, { blendFile, timeoutMs }) {
142
+ const { resultPath, scriptPath } = stampPaths("blender");
143
+ fs.writeFileSync(scriptPath, harnessPython(code, resultPath), "utf8");
144
+ const exe = blenderExecutable();
145
+ const args = ["-b"];
146
+ if (blendFile) {
147
+ if (!fs.existsSync(blendFile)) throw new Error(`blend_file not found: ${blendFile}`);
148
+ args.push(blendFile);
149
+ } else args.push("--factory-startup");
150
+ args.push("--python-exit-code", "1", "--python", scriptPath);
151
+ return new Promise((resolve, reject) => {
152
+ execFile(exe, args, { timeout: timeoutMs, killSignal: "SIGKILL", maxBuffer: 32 * 1024 * 1024 }, (err, stdout, stderr) => {
153
+ let parsed = null;
154
+ try {
155
+ parsed = readResult(resultPath);
156
+ } catch (e) {
157
+ return reject(e);
158
+ }
159
+ if (parsed) {
160
+ fs.rmSync(scriptPath, { force: true });
161
+ return resolve(parsed);
162
+ }
163
+ const msg = String(stderr || (err && err.message) || "").trim().slice(-2000);
164
+ let hint = "";
165
+ if (err && err.code === "ENOENT")
166
+ hint = ` Blender executable not found ("${exe}") — set BLENDER_PATH to the Blender binary.`;
167
+ else if (err && err.killed) hint = ` Timed out after ${timeoutMs / 1000}s — raise timeout_seconds for long renders.`;
168
+ reject(new Error(`Blender (background) produced no result.${hint} ${msg} Script kept: ${scriptPath}`));
169
+ });
170
+ });
171
+ }
172
+
173
+ /**
174
+ * Run Python inside Blender. mode: 'live' (running Blender via the add-on), 'background'
175
+ * (headless process, optional blend_file), or 'auto' (live if the add-on answers, else background).
176
+ */
177
+ export async function runBlender(code, { mode = "auto", blendFile, timeoutMs = 120000 } = {}) {
178
+ return withKnowledge("blender", code, async () => {
179
+ let useLive = mode === "live";
180
+ if (mode === "auto") useLive = !blendFile && (await blenderLiveAlive());
181
+ const parsed = useLive ? await blenderLive(code, timeoutMs) : await blenderBackground(code, { blendFile, timeoutMs });
182
+ return { ...unwrap(parsed, "Blender"), mode: useLive ? "live" : "background" };
183
+ });
184
+ }
185
+
186
+ // ---------------------------------------------------------------------------
187
+ // Substance 3D Painter
188
+ // ---------------------------------------------------------------------------
189
+
190
+ async function painterPost(body, timeoutMs) {
191
+ const ctl = new AbortController();
192
+ const t = setTimeout(() => ctl.abort(), timeoutMs);
193
+ try {
194
+ const res = await fetch(`http://127.0.0.1:${PAINTER_PORT}/run.json`, {
195
+ method: "POST",
196
+ headers: { "Content-Type": "application/json", Accept: "application/json" },
197
+ body: JSON.stringify(body),
198
+ signal: ctl.signal,
199
+ });
200
+ const txt = await res.text();
201
+ try {
202
+ return JSON.parse(txt);
203
+ } catch {
204
+ return txt;
205
+ }
206
+ } catch (e) {
207
+ if (e.name === "AbortError")
208
+ throw new Error(`Substance Painter did not answer within ${timeoutMs / 1000}s — a modal dialog may be open.`);
209
+ throw new Error(
210
+ `Cannot reach Substance 3D Painter remote scripting on 127.0.0.1:${PAINTER_PORT} (${e.cause?.code || e.message}). ` +
211
+ `Launch Painter with --enable-remote-scripting: ${substanceLaunchHint()}`
212
+ );
213
+ } finally {
214
+ clearTimeout(t);
215
+ }
216
+ }
217
+
218
+ /**
219
+ * Run Python inside Substance 3D Painter over its remote-scripting endpoint.
220
+ * The payload is a single expression statement (exec of the base64 harness), so it is valid
221
+ * whether the endpoint evals or execs it; the harness writes its JSON result to a temp file.
222
+ */
223
+ export async function runPainter(code, { timeoutMs = 120000 } = {}) {
224
+ return withKnowledge("substance", code, async () => {
225
+ const { resultPath } = stampPaths("substance");
226
+ const harness = harnessPython(code, resultPath);
227
+ const stmt = `exec(__import__('base64').b64decode('${Buffer.from(harness, "utf8").toString("base64")}').decode('utf-8'))`;
228
+ // Painter's lib_remote protocol base64-encodes the script; SUBSTANCE_REMOTE_ENCODING=raw sends it verbatim.
229
+ const encodings = process.env.SUBSTANCE_REMOTE_ENCODING === "raw" ? ["raw"] : ["base64", "raw"];
230
+ let lastReply = null;
231
+ for (const enc of encodings) {
232
+ const payload = enc === "base64" ? Buffer.from(stmt, "utf8").toString("base64") : stmt;
233
+ lastReply = await painterPost({ python: payload }, timeoutMs);
234
+ const deadline = Date.now() + 3000; // result file is written synchronously; allow FS latency
235
+ while (Date.now() < deadline) {
236
+ const parsed = readResult(resultPath);
237
+ if (parsed) return unwrap(parsed, "Substance Painter");
238
+ await sleep(100);
239
+ }
240
+ const errTxt = typeof lastReply === "object" && lastReply ? lastReply.error : String(lastReply);
241
+ if (!/syntax|decode|invalid/i.test(String(errTxt || ""))) break; // not an encoding problem
242
+ }
243
+ throw new Error(
244
+ `Substance Painter accepted the request but the script did not report back. Painter replied: ${JSON.stringify(lastReply).slice(0, 1500)}`
245
+ );
246
+ });
247
+ }
248
+
249
+ /** Python appended to Blender code to save the .blend (creating its folder). */
250
+ export function blenderSaveSnippet(filepath) {
251
+ return (
252
+ `\nimport bpy as __bpy, os as __os\n` +
253
+ `__os.makedirs(__os.path.dirname(${JSON.stringify(filepath)}) or ".", exist_ok=True)\n` +
254
+ `__bpy.ops.wm.save_as_mainfile(filepath=${JSON.stringify(filepath)})\n`
255
+ );
256
+ }
@@ -0,0 +1,80 @@
1
+ // Opt-in, anonymous usage counts. OFF unless ADOBE_MCP_TELEMETRY=1 and an endpoint is configured.
2
+ //
3
+ // What is sent (once a day at most, and on shutdown): a random install id, the package version,
4
+ // OS + Node version, which apps are enabled, and how many times each tool was called and failed.
5
+ // Never sent: scripts, file paths, project names, arguments, results or error text.
6
+ import crypto from "node:crypto";
7
+ import fs from "node:fs";
8
+ import os from "node:os";
9
+ import path from "node:path";
10
+ import { WORKSPACE } from "./workspace.mjs";
11
+
12
+ // The maintainer sets this when a collector exists; users can point at their own with ADOBE_MCP_TELEMETRY_URL.
13
+ const DEFAULT_ENDPOINT = "";
14
+ const DAY = 24 * 60 * 60 * 1000;
15
+
16
+ export function telemetryEnabled(env = process.env) {
17
+ return /^(1|true|yes|on)$/i.test(env.ADOBE_MCP_TELEMETRY || "") && !!(env.ADOBE_MCP_TELEMETRY_URL || DEFAULT_ENDPOINT);
18
+ }
19
+
20
+ function installId() {
21
+ const f = path.join(WORKSPACE, ".install-id");
22
+ try {
23
+ return fs.readFileSync(f, "utf8").trim();
24
+ } catch {
25
+ const id = crypto.randomUUID();
26
+ try {
27
+ fs.writeFileSync(f, id);
28
+ } catch {
29
+ /* read-only workspace: id is per-session then */
30
+ }
31
+ return id;
32
+ }
33
+ }
34
+
35
+ /**
36
+ * Wrap server.registerTool so every tool call is counted. Returns a flush function.
37
+ * When telemetry is off this is a no-op and the server is untouched.
38
+ */
39
+ export function instrument(server, { version, apps }) {
40
+ if (!telemetryEnabled()) return async () => {};
41
+ const endpoint = process.env.ADOBE_MCP_TELEMETRY_URL || DEFAULT_ENDPOINT;
42
+ const counts = {};
43
+ const orig = server.registerTool.bind(server);
44
+ server.registerTool = (name, def, handler) =>
45
+ orig(name, def, async (...args) => {
46
+ const c = (counts[name] ||= { calls: 0, errors: 0 });
47
+ c.calls++;
48
+ const r = await handler(...args);
49
+ if (r?.isError) c.errors++;
50
+ return r;
51
+ });
52
+
53
+ let last = Date.now();
54
+ const flush = async () => {
55
+ if (!Object.keys(counts).length) return;
56
+ const body = {
57
+ id: installId(),
58
+ version,
59
+ os: process.platform,
60
+ os_release: os.release(),
61
+ node: process.versions.node,
62
+ apps,
63
+ tools: { ...counts },
64
+ };
65
+ for (const k of Object.keys(counts)) delete counts[k];
66
+ last = Date.now();
67
+ try {
68
+ await fetch(endpoint, {
69
+ method: "POST",
70
+ headers: { "Content-Type": "application/json" },
71
+ body: JSON.stringify(body),
72
+ signal: AbortSignal.timeout(4000),
73
+ });
74
+ } catch {
75
+ /* best effort, never affects the server */
76
+ }
77
+ };
78
+ setInterval(() => Date.now() - last >= DAY && flush(), 60 * 60 * 1000).unref();
79
+ return flush;
80
+ }