@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.
- package/README.md +308 -119
- package/SECURITY.md +19 -1
- package/adapters/blender.mjs +230 -0
- package/adapters/ppro.mjs +4 -3
- package/adapters/substance.mjs +193 -0
- package/adapters/texlib.mjs +193 -0
- package/bridges/blender/adobe_mcp_bridge.py +132 -0
- package/cep/mcp-bridge/main.js +2 -2
- package/cli/doctor.mjs +203 -0
- package/cli/index.mjs +67 -0
- package/cli/install.mjs +142 -0
- package/core/blender_pbr.py +148 -0
- package/core/bridge.mjs +113 -64
- package/core/harness.py +34 -0
- package/core/platform.mjs +205 -0
- package/core/pybridge.mjs +256 -0
- package/core/telemetry.mjs +80 -0
- package/core/texlib.mjs +279 -0
- package/core/win/run_com.js +25 -0
- package/core/workspace.mjs +35 -0
- package/knowledge/knowledge.mjs +9 -7
- package/knowledge/lessons.jsonl +20 -0
- package/package.json +45 -3
- package/scripts/ae/Cinematic_3D_Composite.jsx +173 -0
- package/scripts/blender/Creature_Walk_Cinematic.py +569 -0
- package/scripts/substance/Creature_Skin_LookDev.py +148 -0
- package/server.mjs +69 -27
- package/workflow/vfx.mjs +136 -0
- package/workflow/workflow.mjs +66 -21
|
@@ -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
|
+
}
|
package/core/texlib.mjs
ADDED
|
@@ -0,0 +1,279 @@
|
|
|
1
|
+
// Free CC0 texture / HDRI libraries: Poly Haven and ambientCG.
|
|
2
|
+
//
|
|
3
|
+
// Search both catalogues, download a resolution/format, and cache it under
|
|
4
|
+
// $WORKSPACE/textures/<source>/<id>_<res>_<fmt>/ with maps renamed to one convention
|
|
5
|
+
// (<id>_BaseColor.jpg, _Roughness, _Normal (OpenGL), _Height, _AO, _Metallic, _ARM, _Opacity),
|
|
6
|
+
// so the Blender material builder, the creature script's texture_dir and Substance can all
|
|
7
|
+
// consume any asset the same way. Everything both libraries publish is CC0 (public domain).
|
|
8
|
+
import fs from "node:fs";
|
|
9
|
+
import path from "node:path";
|
|
10
|
+
import zlib from "node:zlib";
|
|
11
|
+
import { WORKSPACE } from "./workspace.mjs";
|
|
12
|
+
|
|
13
|
+
const POLYHAVEN_API = process.env.POLYHAVEN_API || "https://api.polyhaven.com";
|
|
14
|
+
const AMBIENTCG_API = process.env.AMBIENTCG_API || "https://ambientcg.com/api/v2";
|
|
15
|
+
// Poly Haven asks API users to send an identifying User-Agent.
|
|
16
|
+
const UA = "adobe-mcp (+https://github.com/AJSMonty/adobe-mcp)";
|
|
17
|
+
export const TEXTURE_CACHE = path.join(WORKSPACE, "textures");
|
|
18
|
+
|
|
19
|
+
async function getJSON(url) {
|
|
20
|
+
const res = await fetch(url, { headers: { "User-Agent": UA, Accept: "application/json" } });
|
|
21
|
+
if (!res.ok) throw new Error(`GET ${url} → HTTP ${res.status}`);
|
|
22
|
+
return res.json();
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
async function getBytes(url) {
|
|
26
|
+
const res = await fetch(url, { headers: { "User-Agent": UA } });
|
|
27
|
+
if (!res.ok) throw new Error(`GET ${url} → HTTP ${res.status}`);
|
|
28
|
+
return Buffer.from(await res.arrayBuffer());
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
// ---------------------------------------------------------------------------
|
|
32
|
+
// Map classification (Poly Haven map keys and ambientCG file suffixes)
|
|
33
|
+
// ---------------------------------------------------------------------------
|
|
34
|
+
|
|
35
|
+
/** Canonical map name for a library map key / filename, or null to skip it. */
|
|
36
|
+
export function classifyMap(name) {
|
|
37
|
+
const n = name.toLowerCase().replace(/\.[a-z0-9]+$/, "");
|
|
38
|
+
if (/preview|thumb|\.mtlx|usd|blend|gltf|_bump|bump$|idmap|mask_/.test(n)) return null;
|
|
39
|
+
if (/nor(mal)?_?dx|normaldx/.test(n)) return null; // DirectX green channel; Blender wants OpenGL
|
|
40
|
+
if (/nor(mal)?_?gl|normalgl|normal/.test(n)) return "Normal";
|
|
41
|
+
if (/(^|_)arm($|_)/.test(n)) return "ARM"; // AO / Roughness / Metal packed in R/G/B
|
|
42
|
+
if (/rough/.test(n)) return "Roughness";
|
|
43
|
+
if (/metal/.test(n)) return "Metallic";
|
|
44
|
+
if (/disp|height/.test(n)) return "Height";
|
|
45
|
+
if (/ambientocclusion|(^|_)ao($|_)/.test(n)) return "AO";
|
|
46
|
+
if (/opacity|alpha/.test(n)) return "Opacity";
|
|
47
|
+
if (/diff|albedo|basecolor|base_color|color|col($|_)/.test(n)) return "BaseColor";
|
|
48
|
+
return null;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** ambientCG files are <AssetId>_<RES>-<FMT>_<Map>.<ext>: classify the map suffix only, so an
|
|
52
|
+
* id like "Metal032" does not turn its colour map into a metallic map. */
|
|
53
|
+
export function classifyAmbientFile(fileName) {
|
|
54
|
+
const stem = path.basename(fileName).replace(/\.[a-z0-9]+$/i, "");
|
|
55
|
+
const parts = stem.split("_");
|
|
56
|
+
return parts.length > 1 ? classifyMap(parts[parts.length - 1]) : null;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
// ---------------------------------------------------------------------------
|
|
60
|
+
// Minimal ZIP reader (ambientCG ships materials as zips) — store + deflate, no zip64.
|
|
61
|
+
// ---------------------------------------------------------------------------
|
|
62
|
+
|
|
63
|
+
export function unzip(buf) {
|
|
64
|
+
let eocd = -1;
|
|
65
|
+
for (let i = buf.length - 22; i >= Math.max(0, buf.length - 65557); i--) {
|
|
66
|
+
if (buf.readUInt32LE(i) === 0x06054b50) { eocd = i; break; }
|
|
67
|
+
}
|
|
68
|
+
if (eocd < 0) throw new Error("Not a zip file (no end-of-central-directory record)");
|
|
69
|
+
const count = buf.readUInt16LE(eocd + 10);
|
|
70
|
+
let p = buf.readUInt32LE(eocd + 16);
|
|
71
|
+
const out = [];
|
|
72
|
+
for (let k = 0; k < count; k++) {
|
|
73
|
+
if (buf.readUInt32LE(p) !== 0x02014b50) throw new Error("Corrupt zip central directory");
|
|
74
|
+
const method = buf.readUInt16LE(p + 10);
|
|
75
|
+
const csize = buf.readUInt32LE(p + 20);
|
|
76
|
+
const nlen = buf.readUInt16LE(p + 28);
|
|
77
|
+
const xlen = buf.readUInt16LE(p + 30);
|
|
78
|
+
const clen = buf.readUInt16LE(p + 32);
|
|
79
|
+
const local = buf.readUInt32LE(p + 42);
|
|
80
|
+
const name = buf.toString("utf8", p + 46, p + 46 + nlen);
|
|
81
|
+
p += 46 + nlen + xlen + clen;
|
|
82
|
+
if (name.endsWith("/")) continue;
|
|
83
|
+
const dataStart = local + 30 + buf.readUInt16LE(local + 26) + buf.readUInt16LE(local + 28);
|
|
84
|
+
const raw = buf.subarray(dataStart, dataStart + csize);
|
|
85
|
+
if (method === 0) out.push({ name, data: Buffer.from(raw) });
|
|
86
|
+
else if (method === 8) out.push({ name, data: zlib.inflateRawSync(raw) });
|
|
87
|
+
else throw new Error(`Unsupported zip compression method ${method} for ${name}`);
|
|
88
|
+
}
|
|
89
|
+
return out;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
// ---------------------------------------------------------------------------
|
|
93
|
+
// Search
|
|
94
|
+
// ---------------------------------------------------------------------------
|
|
95
|
+
|
|
96
|
+
function scoreText(query, fields) {
|
|
97
|
+
const terms = String(query || "").toLowerCase().split(/[\s,]+/).filter(Boolean);
|
|
98
|
+
if (!terms.length) return 1;
|
|
99
|
+
const hay = fields.join(" ").toLowerCase();
|
|
100
|
+
return terms.filter((t) => hay.includes(t)).length / terms.length;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
async function searchPolyHaven({ query, type, category, limit }) {
|
|
104
|
+
const t = type === "hdri" ? "hdris" : "textures";
|
|
105
|
+
const url = `${POLYHAVEN_API}/assets?t=${t}${category ? `&c=${encodeURIComponent(category)}` : ""}`;
|
|
106
|
+
const all = await getJSON(url);
|
|
107
|
+
return Object.entries(all)
|
|
108
|
+
.map(([id, a]) => ({
|
|
109
|
+
source: "polyhaven",
|
|
110
|
+
id,
|
|
111
|
+
name: a.name || id,
|
|
112
|
+
type: type === "hdri" ? "hdri" : "texture",
|
|
113
|
+
categories: a.categories || [],
|
|
114
|
+
tags: a.tags || [],
|
|
115
|
+
downloads: a.download_count || 0,
|
|
116
|
+
max_resolution: Array.isArray(a.max_resolution) ? a.max_resolution : undefined,
|
|
117
|
+
preview: `https://cdn.polyhaven.com/asset_img/thumbs/${id}.png?width=256`,
|
|
118
|
+
page: `https://polyhaven.com/a/${id}`,
|
|
119
|
+
license: "CC0",
|
|
120
|
+
_score: scoreText(query, [id, a.name || "", ...(a.tags || []), ...(a.categories || [])]),
|
|
121
|
+
}))
|
|
122
|
+
.filter((a) => a._score > 0)
|
|
123
|
+
.sort((a, b) => b._score - a._score || b.downloads - a.downloads)
|
|
124
|
+
.slice(0, limit);
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
async function searchAmbientCG({ query, type, category, limit }) {
|
|
128
|
+
const q = [query, category].filter(Boolean).join(" ");
|
|
129
|
+
const url =
|
|
130
|
+
`${AMBIENTCG_API}/full_json?type=${type === "hdri" ? "HDRI" : "Material"}` +
|
|
131
|
+
`&limit=${limit}&sort=Popular&include=tagData,imageData` +
|
|
132
|
+
(q ? `&q=${encodeURIComponent(q)}` : "");
|
|
133
|
+
const data = await getJSON(url);
|
|
134
|
+
return (data.foundAssets || []).map((a) => {
|
|
135
|
+
const imgs = a.previewImage || {};
|
|
136
|
+
return {
|
|
137
|
+
source: "ambientcg",
|
|
138
|
+
id: a.assetId,
|
|
139
|
+
name: a.displayName || a.assetId,
|
|
140
|
+
type: type === "hdri" ? "hdri" : "texture",
|
|
141
|
+
categories: a.displayCategory ? [a.displayCategory] : [],
|
|
142
|
+
tags: a.tags || [],
|
|
143
|
+
downloads: a.downloadCount || 0,
|
|
144
|
+
preview: imgs["256-PNG"] || imgs["128-PNG"] || Object.values(imgs)[0],
|
|
145
|
+
page: `https://ambientcg.com/view?id=${a.assetId}`,
|
|
146
|
+
license: "CC0",
|
|
147
|
+
};
|
|
148
|
+
});
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
export async function searchLibraries({ source = "all", query = "", type = "texture", category, limit = 12 }) {
|
|
152
|
+
const jobs = [];
|
|
153
|
+
if (source === "all" || source === "polyhaven") jobs.push(["polyhaven", searchPolyHaven({ query, type, category, limit })]);
|
|
154
|
+
if (source === "all" || source === "ambientcg") jobs.push(["ambientcg", searchAmbientCG({ query, type, category, limit })]);
|
|
155
|
+
const results = [];
|
|
156
|
+
const errors = {};
|
|
157
|
+
for (const [name, job] of jobs) {
|
|
158
|
+
try {
|
|
159
|
+
results.push(...(await job));
|
|
160
|
+
} catch (e) {
|
|
161
|
+
errors[name] = e.message;
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
results.forEach((r) => delete r._score);
|
|
165
|
+
return { results, ...(Object.keys(errors).length ? { errors } : {}) };
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
// ---------------------------------------------------------------------------
|
|
169
|
+
// Download (cached)
|
|
170
|
+
// ---------------------------------------------------------------------------
|
|
171
|
+
|
|
172
|
+
function cacheDir(source, id, res, fmt) {
|
|
173
|
+
return path.join(TEXTURE_CACHE, source, `${id.replace(/[^\w.-]/g, "_")}_${res}_${fmt}`);
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
function readCached(dir) {
|
|
177
|
+
try {
|
|
178
|
+
const m = JSON.parse(fs.readFileSync(path.join(dir, "asset.json"), "utf8"));
|
|
179
|
+
if (Object.values(m.maps).every((p) => fs.existsSync(p))) return { ...m, cached: true };
|
|
180
|
+
} catch {
|
|
181
|
+
/* not cached */
|
|
182
|
+
}
|
|
183
|
+
return null;
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
function saveMap(dir, id, canon, ext, data, maps) {
|
|
187
|
+
if (!canon || maps[canon]) return; // first match wins (e.g. prefer the first normal)
|
|
188
|
+
const p = path.join(dir, `${id}_${canon}.${ext}`);
|
|
189
|
+
fs.writeFileSync(p, data);
|
|
190
|
+
maps[canon] = p;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
async function downloadPolyHaven(id, type, res, fmt, dir) {
|
|
194
|
+
const files = await getJSON(`${POLYHAVEN_API}/files/${encodeURIComponent(id)}`);
|
|
195
|
+
const maps = {};
|
|
196
|
+
if (type === "hdri") {
|
|
197
|
+
const byRes = files.hdri?.[res];
|
|
198
|
+
if (!byRes) throw new Error(`Poly Haven HDRI ${id} has no ${res}; available: ${Object.keys(files.hdri || {}).join(", ")}`);
|
|
199
|
+
const f = byRes[fmt] || byRes.hdr || byRes.exr;
|
|
200
|
+
const ext = byRes[fmt] ? fmt : byRes.hdr ? "hdr" : "exr";
|
|
201
|
+
saveMap(dir, id, "HDRI", ext, await getBytes(f.url), maps);
|
|
202
|
+
return maps;
|
|
203
|
+
}
|
|
204
|
+
for (const [key, byRes] of Object.entries(files)) {
|
|
205
|
+
const canon = classifyMap(key);
|
|
206
|
+
if (!canon || !byRes || typeof byRes !== "object") continue;
|
|
207
|
+
const r = byRes[res] || null;
|
|
208
|
+
if (!r) continue;
|
|
209
|
+
// colour maps in the requested format; data maps prefer png/exr (jpg if that's all there is)
|
|
210
|
+
const pick = r[fmt] || r.png || r.jpg || r.exr || Object.values(r)[0];
|
|
211
|
+
if (!pick?.url) continue;
|
|
212
|
+
const ext = path.extname(new URL(pick.url).pathname).slice(1) || fmt;
|
|
213
|
+
saveMap(dir, id, canon, ext, await getBytes(pick.url), maps);
|
|
214
|
+
}
|
|
215
|
+
if (!Object.keys(maps).length) {
|
|
216
|
+
const avail = Object.values(files).flatMap((v) => (v && typeof v === "object" ? Object.keys(v) : []));
|
|
217
|
+
throw new Error(`Poly Haven ${id}: no maps at ${res}; available resolutions: ${[...new Set(avail)].join(", ")}`);
|
|
218
|
+
}
|
|
219
|
+
return maps;
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
async function downloadAmbientCG(id, type, res, fmt, dir) {
|
|
223
|
+
const data = await getJSON(`${AMBIENTCG_API}/full_json?id=${encodeURIComponent(id)}&include=downloadData`);
|
|
224
|
+
const asset = (data.foundAssets || [])[0];
|
|
225
|
+
if (!asset) throw new Error(`ambientCG has no asset "${id}"`);
|
|
226
|
+
const wanted = `${res.toUpperCase()}-${fmt.toUpperCase()}`;
|
|
227
|
+
const downloads = [];
|
|
228
|
+
for (const folder of Object.values(asset.downloadFolders || {}))
|
|
229
|
+
for (const cat of Object.values(folder.downloadFiletypeCategories || {})) downloads.push(...(cat.downloads || []));
|
|
230
|
+
const dl =
|
|
231
|
+
downloads.find((d) => d.attribute === wanted) ||
|
|
232
|
+
downloads.find((d) => String(d.attribute || "").toUpperCase().startsWith(res.toUpperCase() + "-"));
|
|
233
|
+
if (!dl) throw new Error(`ambientCG ${id}: no ${wanted} download; available: ${downloads.map((d) => d.attribute).join(", ")}`);
|
|
234
|
+
const bytes = await getBytes(dl.downloadLink || dl.rawLink);
|
|
235
|
+
const maps = {};
|
|
236
|
+
const fileName = dl.fileName || path.basename(new URL(dl.downloadLink || dl.rawLink).pathname);
|
|
237
|
+
if (/\.zip$/i.test(fileName) || bytes.readUInt32LE(0) === 0x04034b50) {
|
|
238
|
+
for (const f of unzip(bytes)) {
|
|
239
|
+
const ext = path.extname(f.name).slice(1).toLowerCase();
|
|
240
|
+
if (type === "hdri" && /^(hdr|exr)$/.test(ext)) saveMap(dir, id, "HDRI", ext, f.data, maps);
|
|
241
|
+
else if (/^(jpg|jpeg|png|exr|tif|tiff)$/.test(ext)) saveMap(dir, id, classifyAmbientFile(f.name), ext, f.data, maps);
|
|
242
|
+
}
|
|
243
|
+
} else {
|
|
244
|
+
saveMap(dir, id, type === "hdri" ? "HDRI" : classifyAmbientFile(fileName), path.extname(fileName).slice(1), bytes, maps);
|
|
245
|
+
}
|
|
246
|
+
if (!Object.keys(maps).length) throw new Error(`ambientCG ${id}: download contained no usable maps`);
|
|
247
|
+
return maps;
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
/**
|
|
251
|
+
* Download one asset (cached). Returns {source, id, type, resolution, format, dir, maps, license}.
|
|
252
|
+
* res: 1k/2k/4k/8k. fmt: jpg/png/exr for textures, hdr/exr for HDRIs.
|
|
253
|
+
*/
|
|
254
|
+
export async function downloadAsset({ source, id, type = "texture", resolution = "2k", format }) {
|
|
255
|
+
const res = resolution.toLowerCase();
|
|
256
|
+
const fmt = (format || (type === "hdri" ? "hdr" : "jpg")).toLowerCase();
|
|
257
|
+
const dir = cacheDir(source, id, res, fmt);
|
|
258
|
+
const hit = readCached(dir);
|
|
259
|
+
if (hit) return hit;
|
|
260
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
261
|
+
let maps;
|
|
262
|
+
if (source === "polyhaven") maps = await downloadPolyHaven(id, type, res, fmt, dir);
|
|
263
|
+
else if (source === "ambientcg") maps = await downloadAmbientCG(id, type, res, fmt, dir);
|
|
264
|
+
else throw new Error(`Unknown texture source "${source}" (use polyhaven or ambientcg)`);
|
|
265
|
+
const meta = {
|
|
266
|
+
source,
|
|
267
|
+
id,
|
|
268
|
+
type,
|
|
269
|
+
resolution: res,
|
|
270
|
+
format: fmt,
|
|
271
|
+
dir,
|
|
272
|
+
maps,
|
|
273
|
+
license: "CC0 1.0 (public domain)",
|
|
274
|
+
page: source === "polyhaven" ? `https://polyhaven.com/a/${id}` : `https://ambientcg.com/view?id=${id}`,
|
|
275
|
+
downloaded: new Date().toISOString(),
|
|
276
|
+
};
|
|
277
|
+
fs.writeFileSync(path.join(dir, "asset.json"), JSON.stringify(meta, null, 2));
|
|
278
|
+
return { ...meta, cached: false };
|
|
279
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
// Windows Script Host (JScript) runner: hands a .jsx file to Photoshop or Illustrator
|
|
2
|
+
// through their COM automation servers. Run with: cscript //nologo run_com.js <ProgID> <file.jsx>
|
|
3
|
+
// DoJavaScriptFile is synchronous, so this returns once the script has finished.
|
|
4
|
+
var args = WScript.Arguments;
|
|
5
|
+
if (args.length < 2) {
|
|
6
|
+
WScript.StdErr.WriteLine("usage: run_com.js <ProgID> <script.jsx>");
|
|
7
|
+
WScript.Quit(2);
|
|
8
|
+
}
|
|
9
|
+
var progId = args(0);
|
|
10
|
+
var file = args(1);
|
|
11
|
+
var app;
|
|
12
|
+
try {
|
|
13
|
+
app = new ActiveXObject(progId);
|
|
14
|
+
} catch (e) {
|
|
15
|
+
WScript.StdErr.WriteLine("COM_CREATE_FAILED 0x" + (e.number >>> 0).toString(16) + " " + e.message);
|
|
16
|
+
WScript.Quit(3);
|
|
17
|
+
}
|
|
18
|
+
try {
|
|
19
|
+
// Arguments/ExecutionMode are left at their defaults: a JScript array is not a COM
|
|
20
|
+
// SAFEARRAY, and the harness wraps user code in try/catch so the debugger never opens.
|
|
21
|
+
app.DoJavaScriptFile(file);
|
|
22
|
+
} catch (e) {
|
|
23
|
+
WScript.StdErr.WriteLine("COM_CALL_FAILED 0x" + (e.number >>> 0).toString(16) + " " + e.message);
|
|
24
|
+
WScript.Quit(4);
|
|
25
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
// Workspace resolution — shared by the bridge and the knowledge system.
|
|
2
|
+
//
|
|
3
|
+
// Hardened against host quirks: some MCP hosts pass manifest placeholders through
|
|
4
|
+
// unexpanded (e.g. Claude Desktop delivered ADOBE_MCP_WORKSPACE='${HOME}/AdobeMCP'
|
|
5
|
+
// literally, with cwd=/ — which crashed mkdir at module load). Rules:
|
|
6
|
+
// - expand a leading ${HOME} or ~
|
|
7
|
+
// - reject any value still containing ${...} or that is not absolute
|
|
8
|
+
// - if the directory cannot be created, fall back to ~/AdobeMCP rather than dying
|
|
9
|
+
import fs from "node:fs";
|
|
10
|
+
import os from "node:os";
|
|
11
|
+
import path from "node:path";
|
|
12
|
+
|
|
13
|
+
function resolveWorkspace() {
|
|
14
|
+
const fallback = path.join(os.homedir(), "AdobeMCP");
|
|
15
|
+
let w = process.env.ADOBE_MCP_WORKSPACE;
|
|
16
|
+
if (w && w.trim()) {
|
|
17
|
+
w = w.trim().replace(/^\$\{HOME\}/, os.homedir()).replace(/^~(?=[\\/]|$)/, os.homedir());
|
|
18
|
+
if (!w.includes("${") && path.isAbsolute(w)) {
|
|
19
|
+
try {
|
|
20
|
+
fs.mkdirSync(w, { recursive: true });
|
|
21
|
+
return w;
|
|
22
|
+
} catch {
|
|
23
|
+
console.error(`adobe-mcp: cannot create workspace "${w}", falling back to ${fallback}`);
|
|
24
|
+
}
|
|
25
|
+
} else {
|
|
26
|
+
console.error(
|
|
27
|
+
`adobe-mcp: ignoring invalid ADOBE_MCP_WORKSPACE "${process.env.ADOBE_MCP_WORKSPACE}" (unexpanded placeholder or relative path), using ${fallback}`
|
|
28
|
+
);
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
fs.mkdirSync(fallback, { recursive: true });
|
|
32
|
+
return fallback;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export const WORKSPACE = resolveWorkspace();
|