chore: freeze v1.1.3 filing submission build (60 levels, full-screen safe layout)
This commit is contained in:
commit
96c19dca82
174 files changed
+37935
No files matched your search
@@ -0,0 +1,67 @@
|
||||
'use strict';
|
||||
|
||||
const PRIVATE_FIELD = /password|passwd|secret|token|authorization|credential|cookie|apikey/i;
|
||||
const BODY_FIELDS = new Set(['content', 'contents', 'text', 'code', 'script', 'source', 'stdout', 'stderr', 'html', 'raw', 'diff', 'datauri', 'imagedata', 'base64', 'buffer']);
|
||||
const PREVIEW_LIMITS = { nodes: 200, depth: 6, keys: 24, items: 12, string: 800, characters: 16000 };
|
||||
|
||||
function sanitizeActivityText(value, limit = PREVIEW_LIMITS.string) {
|
||||
const text = String(value)
|
||||
.replace(/data:[^\s"']+/gi, '[omitted]')
|
||||
.replace(/\bBearer\s+[^\s"',;]+/gi, 'Bearer [redacted]')
|
||||
.replace(/(["']?(?:password|passwd|secret|access[_-]?token|api[_-]?key|token|credential|cookie|authorization)["']?\s*[:=]\s*)(?:"[^"]*"|'[^']*'|[^,\s;}]+)/gi, '$1[redacted]');
|
||||
return text.length > limit ? text.slice(0, limit) + '…' : text;
|
||||
}
|
||||
|
||||
// Snapshot the actual result in its original order and shape. Bound retained data,
|
||||
// not a hand-picked set of fields, and never execute getters for the dashboard.
|
||||
function createActivityPreview(value) {
|
||||
const seen = new WeakSet();
|
||||
let remaining = PREVIEW_LIMITS.nodes;
|
||||
let characters = PREVIEW_LIMITS.characters;
|
||||
function visit(input, depth) {
|
||||
if (remaining-- <= 0 || characters <= 0) return '[truncated]';
|
||||
if (typeof input === 'string') {
|
||||
const text = sanitizeActivityText(input, Math.min(PREVIEW_LIMITS.string, characters));
|
||||
characters -= text.length;
|
||||
return text;
|
||||
}
|
||||
if (input === null || typeof input === 'boolean' || typeof input === 'number') return input;
|
||||
if (typeof input === 'bigint') return String(input);
|
||||
if (!input || typeof input !== 'object') return undefined;
|
||||
if (seen.has(input)) return '[circular]';
|
||||
if (depth > PREVIEW_LIMITS.depth) return '[truncated]';
|
||||
seen.add(input);
|
||||
try {
|
||||
if (Array.isArray(input)) {
|
||||
const preview = [];
|
||||
let i = 0;
|
||||
for (; i < Math.min(PREVIEW_LIMITS.items, input.length) && remaining > 0 && characters > 0; i++) {
|
||||
const property = Object.getOwnPropertyDescriptor(input, String(i));
|
||||
preview.push(property && 'value' in property ? visit(property.value, depth + 1) ?? null : null);
|
||||
}
|
||||
if (i < input.length) preview.push({ $remaining: input.length - i });
|
||||
return preview;
|
||||
}
|
||||
const preview = Object.create(null);
|
||||
const keys = Object.keys(input);
|
||||
let i = 0;
|
||||
for (; i < Math.min(PREVIEW_LIMITS.keys, keys.length) && remaining > 0 && characters > 0; i++) {
|
||||
const key = keys[i];
|
||||
const label = sanitizeActivityText(key, 160);
|
||||
characters -= label.length;
|
||||
const normalized = key.replace(/[^a-z0-9]/gi, '');
|
||||
if (PRIVATE_FIELD.test(normalized)) { preview[label] = '[redacted]'; remaining--; continue; }
|
||||
if (BODY_FIELDS.has(normalized.toLowerCase())) { preview[label] = '[omitted]'; remaining--; continue; }
|
||||
const property = Object.getOwnPropertyDescriptor(input, key);
|
||||
if (!property || !('value' in property)) continue;
|
||||
const result = visit(property.value, depth + 1);
|
||||
if (result !== undefined) preview[label] = result;
|
||||
}
|
||||
if (i < keys.length) preview.$remaining = keys.length - i;
|
||||
return preview;
|
||||
} finally { seen.delete(input); }
|
||||
}
|
||||
try { return visit(value, 0); } catch (error) { return undefined; }
|
||||
}
|
||||
|
||||
module.exports = { createActivityPreview, sanitizeActivityText, PREVIEW_LIMITS };
|
||||
+160
@@ -0,0 +1,160 @@
|
||||
'use strict';
|
||||
|
||||
// Readiness is deliberately narrower than importer/compilation/runtime completion.
|
||||
// Only exact AssetDB identities are queried; this module never refreshes or retries writes.
|
||||
function normalizeAssetTarget(value) {
|
||||
if (value === undefined) return null;
|
||||
if (typeof value !== 'string') throw new Error('target must be an asset UUID or exact db:// URL.');
|
||||
const target = value.trim().replace(/\\/g, '/');
|
||||
if (!target || target.length > 512 || /[\0*?#]/.test(target)) {
|
||||
throw new Error('target must be an asset UUID or exact db:// URL.');
|
||||
}
|
||||
const url = target.startsWith('assets/') || target.startsWith('internal/') ? `db://${target}` : target;
|
||||
if (url.startsWith('db://')) {
|
||||
const segments = url.slice(5).split('/');
|
||||
if (!['assets', 'internal'].includes(segments[0]) || segments.length < 2 ||
|
||||
segments.some((segment) => !segment || segment === '.' || segment === '..')) {
|
||||
throw new Error('target must be an exact db://assets/ or db://internal/ asset URL.');
|
||||
}
|
||||
return url;
|
||||
}
|
||||
// Compressed Cocos UUIDs may contain + or /; ordinary filesystem paths are not accepted.
|
||||
if (!/^[A-Za-z0-9_-]+(?:@[A-Za-z0-9_-]+)?$/.test(target) &&
|
||||
!/^[A-Za-z0-9+/]{22}(?:@[A-Za-z0-9_-]+)?$/.test(target)) {
|
||||
throw new Error('target must be an asset UUID, not a filesystem path.');
|
||||
}
|
||||
return target;
|
||||
}
|
||||
|
||||
function integerOption(value, fallback, name, minimum, maximum) {
|
||||
const number = value === undefined ? fallback : value;
|
||||
if (!Number.isInteger(number) || number < minimum || number > maximum) {
|
||||
throw new Error(`${name} must be an integer between ${minimum} and ${maximum}.`);
|
||||
}
|
||||
return number;
|
||||
}
|
||||
|
||||
function importedIdentity(info) {
|
||||
if (!info || typeof info !== 'object' || typeof info.uuid !== 'string' || !info.uuid ||
|
||||
typeof info.url !== 'string' || !info.url || typeof info.type !== 'string' || !info.type ||
|
||||
info.imported !== true || info.invalid === true) return null;
|
||||
return { uuid: info.uuid, url: info.url, type: info.type, importer: info.importer || null };
|
||||
}
|
||||
|
||||
function editorRequest(method, ...args) {
|
||||
if (!global.Editor || !Editor.Message || typeof Editor.Message.request !== 'function') {
|
||||
throw new Error('AssetDB queries require the Cocos Creator extension host.');
|
||||
}
|
||||
return Editor.Message.request('asset-db', method, ...args);
|
||||
}
|
||||
|
||||
async function observeAsset(request, target) {
|
||||
const databaseState = await request('query-ready');
|
||||
if (databaseState !== true) {
|
||||
return { status: databaseState === false ? 'database_busy' : 'unknown', databaseReady: databaseState === false ? false : null, asset: null };
|
||||
}
|
||||
if (!target) return { status: 'observed', databaseReady: true, asset: null };
|
||||
|
||||
const info = await request('query-asset-info', target);
|
||||
if (!info) return { status: 'missing', databaseReady: true, asset: null };
|
||||
const asset = importedIdentity(info);
|
||||
if (!asset) {
|
||||
return { status: info.invalid === true ? 'invalid_asset' : 'importing', databaseReady: true, asset: {
|
||||
uuid: info.uuid || null, url: info.url || null, imported: info.imported === true,
|
||||
} };
|
||||
}
|
||||
if ((target.startsWith('db://') ? asset.url : asset.uuid) !== target) {
|
||||
return { status: 'identity_mismatch', databaseReady: true, asset };
|
||||
}
|
||||
const uuid = await request('query-uuid', asset.url);
|
||||
const url = await request('query-url', asset.uuid);
|
||||
const readback = importedIdentity(await request('query-asset-info', asset.uuid));
|
||||
if (uuid !== asset.uuid || url !== asset.url || JSON.stringify(readback) !== JSON.stringify(asset)) {
|
||||
return { status: 'identity_mismatch', databaseReady: true, asset };
|
||||
}
|
||||
const readyAfterRead = await request('query-ready');
|
||||
if (readyAfterRead !== true) {
|
||||
return { status: readyAfterRead === false ? 'database_busy' : 'unknown', databaseReady: readyAfterRead === false ? false : null, asset };
|
||||
}
|
||||
return { status: 'observed', databaseReady: true, asset };
|
||||
}
|
||||
|
||||
async function checkAssetReady(options = {}, dependencies = {}) {
|
||||
const target = normalizeAssetTarget(options.target);
|
||||
const waitMs = integerOption(options.waitMs, 1500, 'waitMs', 0, 10000);
|
||||
const pollIntervalMs = integerOption(options.pollIntervalMs, 100, 'pollIntervalMs', 20, 2000);
|
||||
const now = dependencies.now || Date.now;
|
||||
const sleep = dependencies.sleep || ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
|
||||
const nativeRequest = dependencies.request || editorRequest;
|
||||
const started = now();
|
||||
// A zero-wait request still bounds its single IPC observation, but cannot establish stability.
|
||||
const deadline = started + (waitMs || 1000);
|
||||
const request = (method, ...args) => new Promise((resolve, reject) => {
|
||||
const budget = Math.min(1000, deadline - now());
|
||||
if (budget <= 0) {
|
||||
const error = new Error('AssetDB readiness deadline reached.');
|
||||
error.code = 'READINESS_QUERY_TIMEOUT';
|
||||
reject(error);
|
||||
return;
|
||||
}
|
||||
const timer = setTimeout(() => {
|
||||
const error = new Error(`AssetDB ${method} did not respond within the readiness deadline.`);
|
||||
error.code = 'READINESS_QUERY_TIMEOUT';
|
||||
reject(error);
|
||||
}, budget);
|
||||
Promise.resolve().then(() => nativeRequest(method, ...args)).then(
|
||||
(value) => { clearTimeout(timer); resolve(value); },
|
||||
(error) => { clearTimeout(timer); reject(error); }
|
||||
);
|
||||
});
|
||||
|
||||
let attempts = 0;
|
||||
let stableObservations = 0;
|
||||
let previous = null;
|
||||
let sample = { status: 'unknown', databaseReady: null, asset: null };
|
||||
let queryError = '';
|
||||
while (attempts < 102) {
|
||||
attempts += 1;
|
||||
try {
|
||||
sample = await observeAsset(request, target);
|
||||
} catch (error) {
|
||||
sample = { status: error.code === 'READINESS_QUERY_TIMEOUT' ? 'query_timeout' : 'unavailable', databaseReady: null, asset: null };
|
||||
queryError = String(error.message || error).slice(0, 500);
|
||||
stableObservations = 0;
|
||||
break;
|
||||
}
|
||||
const identity = sample.status === 'observed' ? JSON.stringify(sample.asset || { databaseReady: true }) : null;
|
||||
stableObservations = identity ? (identity === previous ? stableObservations + 1 : 1) : 0;
|
||||
previous = identity;
|
||||
if (stableObservations >= 2 || waitMs === 0 || now() >= deadline) break;
|
||||
await sleep(Math.min(pollIntervalMs, deadline - now()));
|
||||
if (now() >= deadline) break;
|
||||
}
|
||||
|
||||
const ready = stableObservations >= 2;
|
||||
return {
|
||||
ready,
|
||||
status: ready ? 'ready' : sample.status === 'observed' ? 'unconfirmed' : sample.status,
|
||||
scope: target ? 'asset_db_record' : 'asset_db_query',
|
||||
target,
|
||||
databaseReady: sample.databaseReady,
|
||||
asset: sample.asset,
|
||||
stableObservations,
|
||||
attempts,
|
||||
elapsedMs: Math.max(0, now() - started),
|
||||
timedOut: !ready && (sample.status === 'query_timeout' || waitMs > 0 && now() >= deadline),
|
||||
error: queryError,
|
||||
boundaries: {
|
||||
importQueueVerified: false,
|
||||
sourceBytesVerified: false,
|
||||
scriptCompilationVerified: false,
|
||||
runtimeLoadedVerified: false,
|
||||
},
|
||||
summary: ready
|
||||
? target ? 'Stable imported AssetDB identity verified; compilation and runtime loading are not verified.'
|
||||
: 'Stable AssetDB query readiness verified; individual assets and the importer queue are not verified.'
|
||||
: `AssetDB readiness was not established (${sample.status === 'observed' ? 'unconfirmed' : sample.status}).`,
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = { checkAssetReady, normalizeAssetTarget };
|
||||
+210
@@ -0,0 +1,210 @@
|
||||
'use strict';
|
||||
|
||||
async function safeRequest(channel, method, ...args) {
|
||||
if (!global.Editor || !Editor.Message || typeof Editor.Message.request !== 'function') {
|
||||
throw new Error('Editor.Message.request is unavailable in the Cocos extension host.');
|
||||
}
|
||||
return await Editor.Message.request(channel, method, ...args);
|
||||
}
|
||||
|
||||
function buildAssetTargetCandidates(uuidOrPath) {
|
||||
const raw = String(uuidOrPath || '').trim().replace(/\\/g, '/');
|
||||
const candidates = [];
|
||||
const add = (value) => {
|
||||
if (value && !candidates.includes(value)) {
|
||||
candidates.push(value);
|
||||
}
|
||||
};
|
||||
|
||||
add(raw);
|
||||
|
||||
if (raw.startsWith('assets/')) {
|
||||
add(`db://${raw}`);
|
||||
} else if (raw.startsWith('/assets/')) {
|
||||
add(`db://${raw.slice(1)}`);
|
||||
}
|
||||
|
||||
if (raw.includes('/assets/')) {
|
||||
add(`db://assets/${raw.split('/assets/').pop()}`);
|
||||
}
|
||||
|
||||
if (raw.startsWith('db://assets/') && !raw.match(/\.[a-z0-9]+$/i)) {
|
||||
add(`${raw}.scene`);
|
||||
add(`${raw}.prefab`);
|
||||
add(`${raw}.ts`);
|
||||
}
|
||||
|
||||
return candidates;
|
||||
}
|
||||
|
||||
async function requestFirst(method, uuidOrPath) {
|
||||
const candidates = buildAssetTargetCandidates(uuidOrPath);
|
||||
let lastError = null;
|
||||
|
||||
for (const candidate of candidates) {
|
||||
try {
|
||||
const result = await safeRequest('asset-db', method, candidate);
|
||||
if (result != null) {
|
||||
return result;
|
||||
}
|
||||
} catch (error) {
|
||||
lastError = error;
|
||||
}
|
||||
}
|
||||
|
||||
if (lastError) {
|
||||
throw lastError;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
async function listAssets(options = {}) {
|
||||
const payload = {};
|
||||
if (options.pattern) {
|
||||
payload.pattern = options.pattern;
|
||||
}
|
||||
if (options.ccType) {
|
||||
payload.ccType = options.ccType;
|
||||
}
|
||||
const result = await safeRequest('asset-db', 'query-assets', payload);
|
||||
return Array.isArray(result) ? result : [];
|
||||
}
|
||||
|
||||
async function queryAssetInfo(uuidOrPath) {
|
||||
if (!uuidOrPath) {
|
||||
throw new Error('Asset uuid or path is required.');
|
||||
}
|
||||
|
||||
const direct = await requestFirst('query-asset-info', uuidOrPath);
|
||||
if (direct) {
|
||||
return direct;
|
||||
}
|
||||
|
||||
const url = await queryAssetUrl(uuidOrPath).catch(() => null);
|
||||
if (url) {
|
||||
const fromUrl = await safeRequest('asset-db', 'query-asset-info', url);
|
||||
if (fromUrl) {
|
||||
return fromUrl;
|
||||
}
|
||||
}
|
||||
|
||||
throw new Error(`Asset not found: ${uuidOrPath}`);
|
||||
}
|
||||
|
||||
async function queryAssetMeta(uuidOrPath) {
|
||||
if (!uuidOrPath) {
|
||||
throw new Error('Asset uuid or path is required.');
|
||||
}
|
||||
|
||||
const direct = await requestFirst('query-asset-meta', uuidOrPath);
|
||||
if (direct) {
|
||||
return direct;
|
||||
}
|
||||
|
||||
const info = await queryAssetInfo(uuidOrPath);
|
||||
return await safeRequest('asset-db', 'query-asset-meta', info.uuid || info.url || uuidOrPath);
|
||||
}
|
||||
|
||||
async function queryAssetData(uuidOrPath) {
|
||||
if (!uuidOrPath) {
|
||||
throw new Error('Asset uuid or path is required.');
|
||||
}
|
||||
|
||||
const direct = await requestFirst('query-asset-data', uuidOrPath);
|
||||
if (direct) {
|
||||
return direct;
|
||||
}
|
||||
|
||||
const info = await queryAssetInfo(uuidOrPath);
|
||||
return await safeRequest('asset-db', 'query-asset-data', info.uuid || info.url || uuidOrPath);
|
||||
}
|
||||
|
||||
async function queryAssetUrl(uuidOrPath) {
|
||||
if (!uuidOrPath) {
|
||||
throw new Error('Asset uuid or path is required.');
|
||||
}
|
||||
const result = await requestFirst('query-url', uuidOrPath);
|
||||
if (result) {
|
||||
return result;
|
||||
}
|
||||
throw new Error(`Asset URL not found: ${uuidOrPath}`);
|
||||
}
|
||||
|
||||
async function openAsset(uuidOrPath) {
|
||||
const info = await queryAssetInfo(uuidOrPath);
|
||||
await safeRequest('asset-db', 'open-asset', info.uuid || uuidOrPath);
|
||||
return info;
|
||||
}
|
||||
|
||||
async function deleteAsset(uuidOrPath) {
|
||||
let url = String(uuidOrPath || '');
|
||||
if (!url.startsWith('db://')) {
|
||||
const info = await queryAssetInfo(uuidOrPath);
|
||||
url = info.url || (await queryAssetUrl(info.uuid || uuidOrPath));
|
||||
}
|
||||
|
||||
await safeRequest('asset-db', 'delete-asset', url);
|
||||
return { deleted: true, url };
|
||||
}
|
||||
|
||||
function selectAsset(uuid) {
|
||||
if (!global.Editor || !Editor.Selection || typeof Editor.Selection.select !== 'function') {
|
||||
throw new Error('Editor.Selection.select is unavailable in this Cocos environment.');
|
||||
}
|
||||
|
||||
Editor.Selection.clear('asset');
|
||||
Editor.Selection.select('asset', uuid);
|
||||
return { selected: true, uuid };
|
||||
}
|
||||
|
||||
function selectNode(uuid) {
|
||||
if (!global.Editor || !Editor.Selection || typeof Editor.Selection.select !== 'function') {
|
||||
throw new Error('Editor.Selection.select is unavailable in this Cocos environment.');
|
||||
}
|
||||
|
||||
Editor.Selection.clear('node');
|
||||
Editor.Selection.select('node', uuid);
|
||||
return { selected: true, uuid };
|
||||
}
|
||||
|
||||
function clearSelection(type) {
|
||||
if (!global.Editor || !Editor.Selection || typeof Editor.Selection.clear !== 'function') {
|
||||
throw new Error('Editor.Selection.clear is unavailable in this Cocos environment.');
|
||||
}
|
||||
|
||||
const normalized = String(type || 'all').trim().toLowerCase();
|
||||
if (normalized === 'asset' || normalized === 'node') {
|
||||
Editor.Selection.clear(normalized);
|
||||
return { cleared: true, type: normalized };
|
||||
}
|
||||
|
||||
Editor.Selection.clear('asset');
|
||||
Editor.Selection.clear('node');
|
||||
return { cleared: true, type: 'all' };
|
||||
}
|
||||
|
||||
function getCurrentSelection() {
|
||||
if (!global.Editor || !Editor.Selection || typeof Editor.Selection.getSelected !== 'function') {
|
||||
throw new Error('Editor.Selection API is unavailable in this Cocos environment.');
|
||||
}
|
||||
|
||||
return {
|
||||
asset: Editor.Selection.getSelected('asset') || '',
|
||||
node: Editor.Selection.getSelected('node') || '',
|
||||
type: typeof Editor.Selection.getLastSelectedType === 'function' ? Editor.Selection.getLastSelectedType() : '',
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
clearSelection,
|
||||
deleteAsset,
|
||||
getCurrentSelection,
|
||||
listAssets,
|
||||
openAsset,
|
||||
queryAssetData,
|
||||
queryAssetInfo,
|
||||
queryAssetMeta,
|
||||
queryAssetUrl,
|
||||
selectAsset,
|
||||
selectNode,
|
||||
};
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
'use strict';
|
||||
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const crypto = require('crypto');
|
||||
|
||||
function readOptionalText(filePath) {
|
||||
try { return fs.readFileSync(filePath, 'utf8'); } catch (error) {
|
||||
if (error.code === 'ENOENT') return null;
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
function writeTextIfUnchanged(filePath, content, original) {
|
||||
// Preserve symlinked config locations while replacing the real file atomically.
|
||||
const destination = fs.existsSync(filePath) ? fs.realpathSync(filePath) : filePath;
|
||||
fs.mkdirSync(path.dirname(destination), { recursive: true });
|
||||
const temporary = `${destination}.funplay-${crypto.randomBytes(8).toString('hex')}.tmp`;
|
||||
try {
|
||||
const mode = fs.existsSync(destination) ? fs.statSync(destination).mode & 0o777 : 0o600;
|
||||
fs.writeFileSync(temporary, content, { encoding: 'utf8', flag: 'wx', mode });
|
||||
if (readOptionalText(filePath) !== original) throw new Error(`Configuration changed while editing: ${filePath}. Retry after reviewing it.`);
|
||||
fs.renameSync(temporary, destination);
|
||||
} finally {
|
||||
if (fs.existsSync(temporary)) fs.unlinkSync(temporary);
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = { readOptionalText, writeTextIfUnchanged };
|
||||
+609
@@ -0,0 +1,609 @@
|
||||
'use strict';
|
||||
|
||||
const fs = require('fs');
|
||||
const os = require('os');
|
||||
const path = require('path');
|
||||
const { getProjectIdentity } = require('./config');
|
||||
const { serverUrl } = require('./project-context');
|
||||
const { readOptionalText, writeTextIfUnchanged } = require('./atomic-file');
|
||||
const { findGitRootOrSelf } = require('./skill-platforms');
|
||||
const { parseJsonc, updateJsonc } = require('./jsonc');
|
||||
const { resolveProjectFilePath } = require('./path-safety');
|
||||
|
||||
const SERVER_NAME = 'funplay_cocos';
|
||||
|
||||
function getServerName(config) {
|
||||
if (!config.projectPath) return SERVER_NAME; // Compatibility for callers without project context.
|
||||
const identity = getProjectIdentity(config.projectPath);
|
||||
const slug = path.basename(config.projectPath).toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '').slice(0, 12).replace(/-$/, '') || 'project';
|
||||
return `cocos-${slug}-${identity.slice(0, 6)}`;
|
||||
}
|
||||
|
||||
function getPreviousEntry(config, targetId) {
|
||||
const record = config.clientConfigEntries && config.clientConfigEntries[targetId];
|
||||
// A copied project config is not proof of ownership of the source project's client entry.
|
||||
if (!record || record.projectIdentity !== getProjectIdentity(config.projectPath)) return undefined;
|
||||
const name = targetId === 'pi' ? String(record.serverName).replace(/_/g, '-') : record.serverName;
|
||||
return record.serverName === SERVER_NAME || /^cocos-[a-z0-9-]+$/.test(name) ? record : undefined;
|
||||
}
|
||||
|
||||
function isObject(value) { return Boolean(value && typeof value === 'object' && !Array.isArray(value)); }
|
||||
|
||||
// Claude Code keys `projects` by a forward-slash path even on Windows, where path.resolve
|
||||
// yields backslashes. A backslash key is a distinct entry that Claude Code never reads.
|
||||
function getClaudeScopePath(projectPath, platform = process.platform, resolveGitRoot = findGitRootOrSelf) {
|
||||
const resolved = resolveGitRoot(projectPath);
|
||||
return platform === 'win32' ? resolved.replace(/\\/g, '/') : resolved;
|
||||
}
|
||||
|
||||
// Claude Code preserves whatever drive-letter case its cwd had, so the same directory can
|
||||
// already be keyed as `D:/repo` or `d:/repo`. Reuse that key instead of adding a duplicate.
|
||||
function resolveProjectKey(projects, scopePath, platform = process.platform) {
|
||||
if (!isObject(projects) || projects[scopePath] !== undefined || platform !== 'win32') return scopePath;
|
||||
const lowered = scopePath.toLowerCase();
|
||||
return Object.keys(projects).find((key) => key.toLowerCase() === lowered) || scopePath;
|
||||
}
|
||||
|
||||
function getServerKeys(root, target) {
|
||||
if (target.scopePath) return ['projects', resolveProjectKey(root.projects, target.scopePath, target.platform), target.rootKey || 'mcpServers'];
|
||||
if (target.id === 'opencode' && isObject(root) && isObject(root.mcp)) {
|
||||
// V2 nests servers and timeouts under mcp; V1 puts server names directly
|
||||
// under mcp. Keep the existing layout, including a V1 server named "servers".
|
||||
const legacyEntry = (entry) => isObject(entry) && (typeof entry.type === 'string'
|
||||
|| typeof entry.url === 'string' || Array.isArray(entry.command) || typeof entry.enabled === 'boolean');
|
||||
const nested = (root.mcp.servers !== undefined && !legacyEntry(root.mcp.servers))
|
||||
|| (root.mcp.timeout !== undefined && !legacyEntry(root.mcp.timeout));
|
||||
if (nested) {
|
||||
if (root.mcp.servers !== undefined && (!isObject(root.mcp.servers) || legacyEntry(root.mcp.servers))) {
|
||||
throw new Error('OpenCode mcp.servers must be a server map; the file was left unchanged.');
|
||||
}
|
||||
const name = target.serverName || SERVER_NAME;
|
||||
if (root.mcp[name] !== undefined) {
|
||||
if (root.mcp.servers && root.mcp.servers[name] !== undefined) throw new Error('Duplicate OpenCode MCP entry in flat and nested maps; the file was left unchanged.');
|
||||
return ['mcp']; // An existing flat registration remains authoritative.
|
||||
}
|
||||
return ['mcp', 'servers'];
|
||||
}
|
||||
}
|
||||
// Flat OpenCode entries remain schema-supported in V2 and work with V1.
|
||||
return [target.rootKey || 'mcpServers'];
|
||||
}
|
||||
|
||||
function getServerContainer(root, target, create = false, keys) {
|
||||
if (!isObject(root)) throw new Error('MCP configuration must be a JSON object.');
|
||||
keys = keys || getServerKeys(root, target);
|
||||
let current = root;
|
||||
for (const key of keys) {
|
||||
if (current[key] === undefined) {
|
||||
if (!create) return null;
|
||||
current[key] = {};
|
||||
}
|
||||
if (!isObject(current[key])) throw new Error(`MCP configuration field '${key}' must be an object; the file was left unchanged.`);
|
||||
current = current[key];
|
||||
}
|
||||
return current;
|
||||
}
|
||||
|
||||
function resolveJsonServerName(servers, target) {
|
||||
const name = target.serverName || SERVER_NAME;
|
||||
if (target.id !== 'pi' || !servers) return name;
|
||||
// Pi treats hyphens and underscores as the same character in server namespaces.
|
||||
const namespace = name.replace(/-/g, '_');
|
||||
const matches = Object.keys(servers).filter((key) => key.replace(/-/g, '_') === namespace);
|
||||
if (matches.length > 1) throw new Error(`Multiple Pi MCP entries share the namespace for '${name}'. Resolve the conflict in .pi/mcp.json first.`);
|
||||
return matches[0] || name;
|
||||
}
|
||||
|
||||
function formatTargetPreview(target) {
|
||||
let name = target.serverName || SERVER_NAME;
|
||||
if (target.isToml) return `[mcp_servers.${name}]\nurl = "${target.url}"\n`;
|
||||
if (target.isDsh) return JSON.stringify(getDshPatch(target), null, 2) + '\n';
|
||||
const root = {};
|
||||
let keys = getServerKeys(root, target);
|
||||
// Match the existing OpenCode layout or Pi server name without exposing unrelated settings.
|
||||
// A malformed file is reported by inspectTarget and blocks setup.
|
||||
if (target.id === 'opencode' || target.id === 'pi') {
|
||||
try {
|
||||
if (target.projectPath) resolveProjectFilePath(target.projectPath, target.configPath);
|
||||
const existing = readJson(target.configPath, target.isJsonc);
|
||||
keys = getServerKeys(existing, target);
|
||||
name = resolveJsonServerName(getServerContainer(existing, target, false, keys), target);
|
||||
} catch (error) { /* status reports the read error */ }
|
||||
}
|
||||
getServerContainer(root, target, true, keys)[name] = target.entry;
|
||||
return JSON.stringify(root, null, 2);
|
||||
}
|
||||
|
||||
function getTargetUrl(target) {
|
||||
return target.url || target.entry[target.urlField || 'url'];
|
||||
}
|
||||
|
||||
function getJsonEntryUrl(entry, urlField) {
|
||||
return isObject(entry) ? entry[urlField] ?? entry.url : undefined;
|
||||
}
|
||||
|
||||
function isGeneratedEntry(entry, url, urlField) {
|
||||
return isObject(entry) && entry[urlField] === url && Object.keys(entry).every((key) => (
|
||||
key === urlField || (key === 'type' && (entry.type === 'http' || entry.type === 'remote'))
|
||||
));
|
||||
}
|
||||
|
||||
function canReplaceEntry(target, name, url) {
|
||||
const previous = target.previousEntry;
|
||||
return url === getTargetUrl(target)
|
||||
|| Boolean(target.migrateLegacy && name === target.serverName && url === target.legacyUrl)
|
||||
|| Boolean(previous && previous.serverName === name && previous.url === url && previous.configPath === target.configPath);
|
||||
}
|
||||
|
||||
function getUserHomePath() {
|
||||
const home = os.homedir();
|
||||
if (home) {
|
||||
return home;
|
||||
}
|
||||
|
||||
const homeDrive = process.env.HOMEDRIVE;
|
||||
const homePath = process.env.HOMEPATH;
|
||||
if (homeDrive && homePath) {
|
||||
return `${homeDrive}${homePath}`;
|
||||
}
|
||||
|
||||
return process.env.HOME || '';
|
||||
}
|
||||
|
||||
function getVSCodeConfigPath(homePath, options = {}) {
|
||||
const platform = options.platform || process.platform;
|
||||
const env = options.env || process.env;
|
||||
if (env.VSCODE_PORTABLE) return path.join(env.VSCODE_PORTABLE, 'user-data', 'User', 'mcp.json');
|
||||
if (env.VSCODE_APPDATA) return path.join(env.VSCODE_APPDATA, 'Code', 'User', 'mcp.json');
|
||||
|
||||
switch (platform) {
|
||||
case 'win32': {
|
||||
const appData = env.APPDATA || path.join(homePath, 'AppData', 'Roaming');
|
||||
return path.join(appData, 'Code', 'User', 'mcp.json');
|
||||
}
|
||||
|
||||
case 'darwin':
|
||||
return path.join(homePath, 'Library', 'Application Support', 'Code', 'User', 'mcp.json');
|
||||
|
||||
case 'linux':
|
||||
return path.join(env.XDG_CONFIG_HOME || path.join(homePath, '.config'), 'Code', 'User', 'mcp.json');
|
||||
|
||||
default:
|
||||
return path.join(homePath, '.vscode', 'mcp.json');
|
||||
}
|
||||
}
|
||||
|
||||
function getOpenCodeConfigPath(homePath, options = {}) {
|
||||
const env = options.env || process.env;
|
||||
const existsSync = options.existsSync || fs.existsSync;
|
||||
|
||||
// OpenCode resolves its global config dir cross-platform via xdg-basedir
|
||||
// (packages/core/src/global.ts): XDG_CONFIG_HOME wins, else ~/.config.
|
||||
// There is no APPDATA or macOS Application Support branch.
|
||||
const xdgHome = String(env && env.XDG_CONFIG_HOME || '').trim();
|
||||
const configDir = xdgHome || path.join(homePath, '.config');
|
||||
const dir = path.join(configDir, 'opencode');
|
||||
// globalConfigFile() prefers opencode.jsonc over opencode.json; write
|
||||
// where the user already keeps the file, else the canonical .json.
|
||||
const jsonc = path.join(dir, 'opencode.jsonc');
|
||||
return existsSync(jsonc) ? jsonc : path.join(dir, 'opencode.json');
|
||||
}
|
||||
|
||||
function getConfiguredDirectory(env, key, fallback) {
|
||||
const configured = String(env && env[key] || '').trim();
|
||||
return configured || fallback;
|
||||
}
|
||||
|
||||
function ensureParent(filePath) {
|
||||
const dir = path.dirname(filePath);
|
||||
if (dir && !fs.existsSync(dir)) {
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
}
|
||||
}
|
||||
|
||||
function readJson(filePath, isJsonc = false) {
|
||||
if (!fs.existsSync(filePath)) {
|
||||
return {};
|
||||
}
|
||||
|
||||
const text = fs.readFileSync(filePath, 'utf8');
|
||||
if (!text) {
|
||||
return {};
|
||||
}
|
||||
|
||||
return parseConfigJson(text, isJsonc);
|
||||
}
|
||||
|
||||
function parseConfigJson(text, isJsonc) {
|
||||
if (!text || !text.trim()) return {};
|
||||
if (!isJsonc) JSON.parse(text.replace(/^\uFEFF/, '')); // Reject comments/trailing commas for strict clients.
|
||||
return parseJsonc(text); // Reject duplicate keys for both JSON and JSONC.
|
||||
}
|
||||
|
||||
function assertRemoteEntry(entry, urlField) {
|
||||
if (!isObject(entry)) return;
|
||||
if (entry.command !== undefined) throw new Error('This MCP entry declares a local command. Review it manually before replacing it with HTTP; the file was left unchanged.');
|
||||
if (entry.disabled === true || entry.enabled === false) throw new Error('This MCP entry is disabled in the client configuration. Enable it there before configuring; the file was left unchanged.');
|
||||
if (urlField !== 'url' && entry[urlField] !== undefined && entry.url !== undefined && entry[urlField] !== entry.url) {
|
||||
throw new Error(`This MCP entry has conflicting ${urlField} and url values. The file was left unchanged.`);
|
||||
}
|
||||
}
|
||||
|
||||
function matchesJsonTransport(entry, target) {
|
||||
if (target.entry.type) return entry.type === target.entry.type;
|
||||
return entry.type === undefined || entry.type === 'http' || (target.id === 'pi' && entry.type === 'streamable-http');
|
||||
}
|
||||
|
||||
function configureJsonTarget(target) {
|
||||
if (target.projectPath) resolveProjectFilePath(target.projectPath, target.configPath);
|
||||
const original = readOptionalText(target.configPath);
|
||||
const root = parseConfigJson(original, target.isJsonc);
|
||||
const servers = getServerContainer(root, target, true);
|
||||
const name = resolveJsonServerName(servers, target);
|
||||
const urlField = target.urlField || 'url';
|
||||
const existing = servers[name];
|
||||
if (existing !== undefined && (!isObject(existing) || !canReplaceEntry(target, name, getJsonEntryUrl(existing, urlField)))) {
|
||||
throw new Error(`MCP entry '${name}' already belongs to another endpoint. Existing configuration was left unchanged.`);
|
||||
}
|
||||
assertRemoteEntry(existing, urlField);
|
||||
const previous = target.previousEntry;
|
||||
if (previous && previous.configPath === target.configPath && previous.serverName !== name
|
||||
&& isGeneratedEntry(servers[previous.serverName], previous.url, urlField)) {
|
||||
delete servers[previous.serverName];
|
||||
}
|
||||
if (target.migrateLegacy && urlField === 'url' && target.id !== 'pi') {
|
||||
if (name !== SERVER_NAME && isGeneratedEntry(servers[SERVER_NAME], target.entry.url, urlField)) delete servers[SERVER_NAME];
|
||||
if (target.scopePath && isObject(root.mcpServers) && isGeneratedEntry(root.mcpServers[SERVER_NAME], target.entry.url, urlField)) {
|
||||
delete root.mcpServers[SERVER_NAME];
|
||||
}
|
||||
}
|
||||
servers[name] = { ...(existing || {}), ...target.entry };
|
||||
if (urlField !== 'url') delete servers[name].url;
|
||||
// URL-only clients auto-select HTTP. Pi also accepts an explicit HTTP transport.
|
||||
if (!target.entry.type && (target.id !== 'pi' || !matchesJsonTransport(servers[name], target))) delete servers[name].type;
|
||||
const content = target.isJsonc ? updateJsonc(original || '', root) : JSON.stringify(root, null, 2) + '\n';
|
||||
if (content !== original) writeTextIfUnchanged(target.configPath, content, original);
|
||||
return name;
|
||||
}
|
||||
|
||||
// DSH accepts JSON as YAML for --patch. Keep a dedicated project overlay instead
|
||||
// of parsing/replacing a user's Cordis YAML (which can contain executable !!js).
|
||||
function getDshPatch(target, existing = {}) {
|
||||
return [{ insert: [{
|
||||
...existing,
|
||||
id: target.serverName,
|
||||
name: '@deepseek-ai/dsh-mcp-client',
|
||||
config: { ...existing.config, ...target.entry },
|
||||
}] }];
|
||||
}
|
||||
|
||||
function readDshEntry(target, text) {
|
||||
JSON.parse(text); // Reject JSONC, which is not valid YAML/JSON for DSH.
|
||||
const patches = parseJsonc(text); // Also reject duplicate/ambiguous JSON keys.
|
||||
const patch = Array.isArray(patches) && patches.length === 1 && patches[0];
|
||||
const entry = isObject(patch) && Object.keys(patch).length === 1
|
||||
&& Array.isArray(patch.insert) && patch.insert.length === 1 && patch.insert[0];
|
||||
if (!isObject(entry) || Object.keys(entry).some((key) => !['id', 'name', 'config', 'disabled'].includes(key))
|
||||
|| entry.id !== target.serverName || entry.name !== '@deepseek-ai/dsh-mcp-client'
|
||||
|| !isObject(entry.config) || entry.config.serverName !== target.serverName
|
||||
|| entry.config.transport !== 'streamable-http') {
|
||||
throw new Error('The dedicated DSH overlay contains unrelated or ambiguous entries; the file was left unchanged.');
|
||||
}
|
||||
if (entry.disabled !== undefined && entry.disabled !== false) {
|
||||
throw new Error('The DSH MCP entry is disabled; review it manually. The file was left unchanged.');
|
||||
}
|
||||
return entry;
|
||||
}
|
||||
|
||||
function configureDshTarget(target) {
|
||||
const original = readOptionalText(target.configPath);
|
||||
const existing = original === null ? {} : readDshEntry(target, original);
|
||||
if (existing.config && !canReplaceEntry(target, target.serverName, existing.config.url)) {
|
||||
throw new Error(`MCP entry '${target.serverName}' already belongs to another endpoint. Existing configuration was left unchanged.`);
|
||||
}
|
||||
const content = JSON.stringify(getDshPatch(target, existing), null, 2) + '\n';
|
||||
if (content !== original) writeTextIfUnchanged(target.configPath, content, original);
|
||||
}
|
||||
|
||||
function getDshLaunchCommand(configPath, platform) {
|
||||
// Single-quote paths for the host's POSIX shell or Windows PowerShell. Do not
|
||||
// interpolate project names as executable shell syntax in the displayed hint.
|
||||
const quoted = platform === 'win32' ? configPath.replace(/'/g, "''") : configPath.replace(/'/g, "'\\''");
|
||||
return `dsh web --patch '${quoted}'`;
|
||||
}
|
||||
|
||||
function configureTomlTarget(target) {
|
||||
ensureParent(target.configPath);
|
||||
const name = target.serverName || SERVER_NAME;
|
||||
const sectionHeader = `[mcp_servers.${name}]`;
|
||||
const section = `${sectionHeader}\nurl = "${target.url}"\n`;
|
||||
const original = readOptionalText(target.configPath);
|
||||
let content = original || '';
|
||||
const blocks = getTomlBlocks(content);
|
||||
const existing = blocks.find((block) => block.name === name);
|
||||
if (existing) {
|
||||
assertTomlRemoteBlock(existing);
|
||||
if (!canReplaceEntry(target, name, existing.url)) throw new Error(`MCP entry '${name}' already belongs to another endpoint. Existing configuration was left unchanged.`);
|
||||
const updated = existing.text.replace(/^[ \t]*url[ \t]*=[^\n]*/m, `url = "${target.url}"`);
|
||||
content = content.slice(0, existing.start) + updated + content.slice(existing.end);
|
||||
} else {
|
||||
if (content.length > 0 && !content.endsWith('\n')) {
|
||||
content += '\n';
|
||||
}
|
||||
if (content.length > 0) {
|
||||
content += '\n';
|
||||
}
|
||||
content += section;
|
||||
}
|
||||
// Retire only exact generated URL-only blocks that this project can identify.
|
||||
const previous = target.previousEntry;
|
||||
const retired = getTomlBlocks(content).filter((block) => block.name !== name && (
|
||||
(target.migrateLegacy && block.name === SERVER_NAME && block.url === target.url) ||
|
||||
(previous && previous.configPath === target.configPath && block.name === previous.serverName && block.url === previous.url)
|
||||
) && !block.hasChildren && block.text.trim().split('\n').length === 2);
|
||||
for (const block of retired.reverse()) content = content.slice(0, block.start) + content.slice(block.end);
|
||||
writeTextIfUnchanged(target.configPath, content, original);
|
||||
}
|
||||
|
||||
function getTomlBlocks(content) {
|
||||
// Do not guess at TOML forms that could hide table-looking text inside strings.
|
||||
const first = content.replace(/^\uFEFF/, '').split(/\r?\n/).find((line) => line.trim() && !line.trim().startsWith('#'));
|
||||
if (first && /^[ \t]*[{}=]/.test(first)) throw new Error('This is not a supported TOML configuration; review it manually. The file was left unchanged.');
|
||||
if (/"""|'''|^[ \t]*mcp_servers[ \t]*=/m.test(content)) throw new Error('This TOML uses multiline strings or inline MCP tables. Configure it manually; the file was left unchanged.');
|
||||
const headers = [...content.matchAll(/^[ \t]*\[(\[[^\]\r\n]+\]|[^\]\r\n]+)\][ \t]*(?:#[^\n]*)?\r?$/gm)];
|
||||
const blocks = [];
|
||||
let hasParent = false;
|
||||
for (let index = 0; index < headers.length; index += 1) {
|
||||
const header = headers[index];
|
||||
if (header[1].trim() === 'mcp_servers') {
|
||||
const end = index + 1 < headers.length ? headers[index + 1].index : content.length;
|
||||
const body = content.slice(header.index + header[0].length, end);
|
||||
if (hasParent || body.split(/\r?\n/).some((line) => line.trim() && !line.trim().startsWith('#'))) {
|
||||
throw new Error('Duplicate or inline MCP parent table. Use explicit [mcp_servers.name] tables; the file was left unchanged.');
|
||||
}
|
||||
hasParent = true;
|
||||
continue;
|
||||
}
|
||||
const match = header[1].trim().match(/^mcp_servers\s*\.\s*(?:([A-Za-z0-9_-]+)|"([A-Za-z0-9_-]+)"|'([A-Za-z0-9_-]+)')$/);
|
||||
if (!match) continue;
|
||||
const start = header.index;
|
||||
const end = index + 1 < headers.length ? headers[index + 1].index : content.length;
|
||||
const text = content.slice(start, end);
|
||||
const urls = [...text.matchAll(/^[ \t]*url[ \t]*=[ \t]*["']([^"']+)["'][ \t]*(?:#[^\n]*)?\r?$/gm)];
|
||||
const name = match[1] || match[2] || match[3];
|
||||
if (blocks.some((block) => block.name === name) || urls.length > 1) throw new Error('Duplicate MCP table or URL; configuration was left unchanged.');
|
||||
const hasChildren = headers.some((item) => [name, `"${name}"`, `'${name}'`].some((key) => item[1].trim().replace(/\s*\.\s*/g, '.').startsWith(`mcp_servers.${key}.`)));
|
||||
blocks.push({ name, start, end, text, hasChildren, url: urls.length ? urls[0][1] : '' });
|
||||
}
|
||||
return blocks;
|
||||
}
|
||||
|
||||
function assertTomlRemoteBlock(block) {
|
||||
if (/^[ \t]*command[ \t]*=/m.test(block.text)) throw new Error('This MCP table declares a local command; the file was left unchanged.');
|
||||
if (/^[ \t]*enabled[ \t]*=[ \t]*false[ \t]*(?:#[^\n]*)?\r?$/m.test(block.text)) throw new Error('This MCP table is disabled. Enable it in Codex before configuring; the file was left unchanged.');
|
||||
}
|
||||
|
||||
function buildTargets(config, options = {}) {
|
||||
const home = options.homePath || getUserHomePath();
|
||||
const env = options.env || process.env;
|
||||
const platform = options.platform || process.platform;
|
||||
const resolveGitRoot = options.resolveGitRoot || findGitRootOrSelf;
|
||||
const url = serverUrl(config);
|
||||
|
||||
return [
|
||||
{
|
||||
id: 'claude_code',
|
||||
name: 'Claude Code',
|
||||
configPath: path.join(home, '.claude.json'),
|
||||
rootKey: 'mcpServers',
|
||||
entry: { type: 'http', url },
|
||||
},
|
||||
{
|
||||
id: 'cursor',
|
||||
name: 'Cursor',
|
||||
configPath: path.join(home, '.cursor', 'mcp.json'),
|
||||
rootKey: 'mcpServers',
|
||||
entry: { url },
|
||||
},
|
||||
{
|
||||
id: 'vscode',
|
||||
name: 'VS Code',
|
||||
configPath: getVSCodeConfigPath(home, options),
|
||||
rootKey: 'servers',
|
||||
entry: { type: 'http', url },
|
||||
isJsonc: true,
|
||||
},
|
||||
{
|
||||
id: 'kiro',
|
||||
name: 'Kiro',
|
||||
configPath: path.join(home, '.kiro', 'settings', 'mcp.json'),
|
||||
rootKey: 'mcpServers',
|
||||
entry: { type: 'http', url },
|
||||
},
|
||||
{
|
||||
id: 'qoder',
|
||||
name: 'Qoder',
|
||||
configPath: path.join(
|
||||
getConfiguredDirectory(env, 'QODER_CONFIG_DIR', path.join(home, '.qoder')),
|
||||
'settings.json'
|
||||
),
|
||||
rootKey: 'mcpServers',
|
||||
entry: { type: 'http', url },
|
||||
},
|
||||
{
|
||||
id: 'kimi',
|
||||
name: 'Kimi Code',
|
||||
configPath: path.join(
|
||||
getConfiguredDirectory(env, 'KIMI_CODE_HOME', path.join(home, '.kimi-code')),
|
||||
'mcp.json'
|
||||
),
|
||||
rootKey: 'mcpServers',
|
||||
entry: { url },
|
||||
},
|
||||
{
|
||||
id: 'codex',
|
||||
name: 'Codex',
|
||||
configPath: path.join(getConfiguredDirectory(env, 'CODEX_HOME', path.join(home, '.codex')), 'config.toml'),
|
||||
isToml: true,
|
||||
url,
|
||||
},
|
||||
{
|
||||
id: 'opencode',
|
||||
name: 'OpenCode',
|
||||
configPath: getOpenCodeConfigPath(home, options),
|
||||
rootKey: 'mcp',
|
||||
entry: { type: 'remote', url },
|
||||
isJsonc: true,
|
||||
},
|
||||
// These clients load their configuration from the current Cocos project.
|
||||
...(config.projectPath ? [{
|
||||
id: 'trae',
|
||||
name: 'Trae',
|
||||
configPath: path.resolve(config.projectPath, '.trae', 'mcp.json'),
|
||||
rootKey: 'mcpServers',
|
||||
entry: { url },
|
||||
setupHintKey: 'client.trae_project_hint',
|
||||
}, {
|
||||
id: 'antigravity',
|
||||
name: 'Antigravity',
|
||||
configPath: path.resolve(config.projectPath, '.agents', 'mcp_config.json'),
|
||||
projectPath: config.projectPath,
|
||||
rootKey: 'mcpServers',
|
||||
urlField: 'serverUrl',
|
||||
entry: { serverUrl: url },
|
||||
setupHintKey: 'client.antigravity_project_hint',
|
||||
}, {
|
||||
id: 'pi',
|
||||
name: 'Pi',
|
||||
configPath: path.resolve(config.projectPath, '.pi', 'mcp.json'),
|
||||
projectPath: config.projectPath,
|
||||
rootKey: 'mcpServers',
|
||||
entry: { url },
|
||||
setupHintKey: 'client.pi_project_hint',
|
||||
}, {
|
||||
// CodeBuddy IDE 4.0+ reads the workspace .mcp.json.
|
||||
id: 'codebuddy',
|
||||
name: 'CodeBuddy IDE',
|
||||
configPath: path.resolve(config.projectPath, '.mcp.json'),
|
||||
rootKey: 'mcpServers',
|
||||
entry: { type: 'http', url },
|
||||
isJsonc: true,
|
||||
}, {
|
||||
id: 'deepseek_harness',
|
||||
name: 'DeepSeek Harness (DSH)',
|
||||
configPath: path.resolve(config.projectPath, '.dsh', 'funplay-cocos-mcp.patch.json'),
|
||||
isDsh: true,
|
||||
entry: { serverName: getServerName(config), transport: 'streamable-http', url },
|
||||
launchCommand: getDshLaunchCommand(path.resolve(config.projectPath, '.dsh', 'funplay-cocos-mcp.patch.json'), platform),
|
||||
}] : []),
|
||||
].map((target) => config.projectPath ? ({
|
||||
...target,
|
||||
serverName: getServerName(config),
|
||||
...(target.id === 'claude_code'
|
||||
? { scopePath: getClaudeScopePath(config.projectPath, platform, resolveGitRoot), platform }
|
||||
: {}),
|
||||
previousEntry: getPreviousEntry(config, target.id),
|
||||
legacyUrl: serverUrl(config, config.port, ''),
|
||||
migrateLegacy: config.migrateLegacy === true,
|
||||
}) : target);
|
||||
}
|
||||
|
||||
function getTomlServerUrl(target) {
|
||||
if (!fs.existsSync(target.configPath)) {
|
||||
return '';
|
||||
}
|
||||
const content = fs.readFileSync(target.configPath, 'utf8');
|
||||
const block = getTomlBlocks(content).find((item) => item.name === (target.serverName || SERVER_NAME));
|
||||
if (block) assertTomlRemoteBlock(block);
|
||||
return block ? block.url : '';
|
||||
}
|
||||
|
||||
function inspectTarget(target) {
|
||||
try {
|
||||
if (target.projectPath) resolveProjectFilePath(target.projectPath, target.configPath);
|
||||
if (!fs.existsSync(target.configPath)) return { configured: false };
|
||||
let url;
|
||||
let configured;
|
||||
let serverName = target.serverName || SERVER_NAME;
|
||||
if (target.isToml) {
|
||||
url = getTomlServerUrl(target);
|
||||
configured = url === target.url;
|
||||
} else if (target.isDsh) {
|
||||
const entry = readDshEntry(target, fs.readFileSync(target.configPath, 'utf8'));
|
||||
url = entry.config.url;
|
||||
configured = Object.entries(target.entry).every(([key, value]) => entry.config[key] === value);
|
||||
} else {
|
||||
const root = readJson(target.configPath, target.isJsonc);
|
||||
const servers = getServerContainer(root, target);
|
||||
serverName = resolveJsonServerName(servers, target);
|
||||
const entry = servers && servers[serverName];
|
||||
const urlField = target.urlField || 'url';
|
||||
assertRemoteEntry(entry, urlField);
|
||||
url = getJsonEntryUrl(entry, urlField);
|
||||
configured = isObject(entry) && url === getTargetUrl(target) && matchesJsonTransport(entry, target);
|
||||
// Do not remove an old shared entry. Offer a separate project-bound entry.
|
||||
if (!entry && target.legacyUrl && servers && getJsonEntryUrl(servers[SERVER_NAME], urlField) === target.legacyUrl) {
|
||||
return { configured: false, needsReconfigure: true, canReconfigure: true };
|
||||
}
|
||||
}
|
||||
const legacy = Boolean(target.legacyUrl && url === target.legacyUrl && url !== getTargetUrl(target));
|
||||
return { configured, serverName, ...(legacy ? { needsReconfigure: true, canReconfigure: canReplaceEntry(target, serverName, url) } : {}) };
|
||||
} catch (error) {
|
||||
return { configured: false, readError: error.message.slice(0, 500) };
|
||||
}
|
||||
}
|
||||
|
||||
function getTargetStatuses(config, options = {}) {
|
||||
return buildTargets(config, options).map((target) => ({
|
||||
id: target.id,
|
||||
name: target.name,
|
||||
configPath: target.configPath,
|
||||
serverName: target.serverName || SERVER_NAME,
|
||||
...inspectTarget(target),
|
||||
isToml: Boolean(target.isToml),
|
||||
...(target.setupHintKey ? { setupHintKey: target.setupHintKey } : {}),
|
||||
...(target.launchCommand ? { launchCommand: target.launchCommand } : {}),
|
||||
}));
|
||||
}
|
||||
|
||||
function configureTarget(config, targetId, options = {}) {
|
||||
if (config.stablePort !== undefined && config.port !== config.stablePort) throw new Error('Server is using a temporary fallback port. Pin the current port or use the per-project port before configuring a client.');
|
||||
const targets = buildTargets(config, options);
|
||||
const target = targets.find((item) => item.id === targetId);
|
||||
if (!target) {
|
||||
throw new Error(`Unknown MCP client target: ${targetId}`);
|
||||
}
|
||||
|
||||
let serverName = target.serverName || SERVER_NAME;
|
||||
if (target.isToml) {
|
||||
configureTomlTarget(target);
|
||||
} else if (target.isDsh) {
|
||||
configureDshTarget(target);
|
||||
} else {
|
||||
serverName = configureJsonTarget(target);
|
||||
}
|
||||
|
||||
return {
|
||||
id: target.id,
|
||||
name: target.name,
|
||||
configPath: target.configPath,
|
||||
configured: true,
|
||||
serverName,
|
||||
url: getTargetUrl(target),
|
||||
projectIdentity: config.projectPath ? getProjectIdentity(config.projectPath) : '',
|
||||
...(target.launchCommand ? { launchCommand: target.launchCommand } : {}),
|
||||
...(target.setupHintKey ? { setupHintKey: target.setupHintKey } : {}),
|
||||
restartHint: target.launchCommand
|
||||
? `From the Cocos project directory, start DSH with: ${target.launchCommand}. The overlay is not loaded automatically.`
|
||||
: `Please restart ${target.name} for the MCP configuration to take effect.`,
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
SERVER_NAME,
|
||||
getServerName,
|
||||
formatTargetPreview,
|
||||
buildTargets,
|
||||
configureTarget,
|
||||
getTargetStatuses,
|
||||
};
|
||||
+208
@@ -0,0 +1,208 @@
|
||||
'use strict';
|
||||
|
||||
const crypto = require('crypto');
|
||||
const fs = require('fs');
|
||||
const net = require('net');
|
||||
const path = require('path');
|
||||
const { normalizeLanguagePreference } = require('./i18n');
|
||||
const { normalizeSavedToolProfiles } = require('./tool-profiles');
|
||||
|
||||
const DEFAULTS = {
|
||||
host: '127.0.0.1',
|
||||
port: 8765,
|
||||
portMode: 'project',
|
||||
toolProfile: 'core',
|
||||
enabledTools: [],
|
||||
disabledTools: [],
|
||||
enabledToolCategories: [],
|
||||
disabledToolCategories: [],
|
||||
enableSessions: false,
|
||||
enableConsoleLogging: true,
|
||||
executeJavascriptSafetyChecks: true,
|
||||
autostart: true,
|
||||
maxInteractionLogEntries: 50,
|
||||
lastClientTargetId: 'claude_code',
|
||||
activeToolProfileName: '',
|
||||
savedToolProfiles: [],
|
||||
language: 'auto',
|
||||
};
|
||||
|
||||
const RUNTIME_CONFIG_KEYS = [
|
||||
'host',
|
||||
'port',
|
||||
'toolProfile',
|
||||
'enabledTools',
|
||||
'disabledTools',
|
||||
'enabledToolCategories',
|
||||
'disabledToolCategories',
|
||||
'enableSessions',
|
||||
'executeJavascriptSafetyChecks',
|
||||
'maxInteractionLogEntries',
|
||||
];
|
||||
|
||||
function getProjectPath() {
|
||||
if (global.Editor && Editor.Project && typeof Editor.Project.path === 'string' && Editor.Project.path) {
|
||||
return Editor.Project.path;
|
||||
}
|
||||
return process.cwd();
|
||||
}
|
||||
|
||||
function getProjectName() {
|
||||
return path.basename(getProjectPath());
|
||||
}
|
||||
|
||||
function normalizeProjectIdentityPath(projectPath) {
|
||||
const normalized = path.resolve(String(projectPath || process.cwd())).replace(/\\/g, '/');
|
||||
return process.platform === 'win32' ? normalized.toLowerCase() : normalized;
|
||||
}
|
||||
|
||||
function getProjectIdentity(projectPath = getProjectPath()) {
|
||||
return crypto
|
||||
.createHash('sha256')
|
||||
.update(`funplay-cocos-mcp:${normalizeProjectIdentityPath(projectPath)}`)
|
||||
.digest('hex')
|
||||
.slice(0, 24);
|
||||
}
|
||||
|
||||
function getProjectPort(projectPath = getProjectPath()) {
|
||||
return 20000 + (parseInt(getProjectIdentity(projectPath).slice(0, 8), 16) % 10000);
|
||||
}
|
||||
|
||||
function getCocosVersion() {
|
||||
if (global.Editor && Editor.App) {
|
||||
if (typeof Editor.App.version === 'string' && Editor.App.version) {
|
||||
return Editor.App.version;
|
||||
}
|
||||
if (typeof Editor.App.ver === 'string' && Editor.App.ver) {
|
||||
return Editor.App.ver;
|
||||
}
|
||||
}
|
||||
return 'unknown';
|
||||
}
|
||||
|
||||
function loadJson(filePath) {
|
||||
if (!fs.existsSync(filePath)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
return JSON.parse(fs.readFileSync(filePath, 'utf8'));
|
||||
} catch (error) {
|
||||
return {
|
||||
__error: `Failed to parse config file '${filePath}': ${error.message}`,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
function clampPort(value) {
|
||||
const port = Number(value);
|
||||
if (!Number.isInteger(port) || port <= 0 || port > 65535) {
|
||||
return DEFAULTS.port;
|
||||
}
|
||||
return port;
|
||||
}
|
||||
|
||||
function normalizeProfile(value) {
|
||||
const normalized = String(value || DEFAULTS.toolProfile).toLowerCase();
|
||||
if (normalized === 'full' || normalized === 'custom') {
|
||||
return normalized;
|
||||
}
|
||||
return 'core';
|
||||
}
|
||||
|
||||
function normalizeStringList(value) {
|
||||
if (Array.isArray(value)) {
|
||||
return value
|
||||
.map((item) => String(item || '').trim())
|
||||
.filter(Boolean);
|
||||
}
|
||||
if (typeof value === 'string') {
|
||||
return value
|
||||
.split(/[\n,]/)
|
||||
.map((item) => item.trim())
|
||||
.filter(Boolean);
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
function normalizeClientTargetId(value) {
|
||||
const normalized = String(value || '').trim();
|
||||
return normalized || DEFAULTS.lastClientTargetId;
|
||||
}
|
||||
|
||||
function normalizeHost(value) {
|
||||
const host = typeof value === 'string' ? value.trim() : '';
|
||||
const hostname = host.length <= 253 && host.split('.').every((label) => (
|
||||
/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/i.test(label)
|
||||
));
|
||||
if (!host || (!net.isIP(host) && !hostname)) {
|
||||
throw new Error('Host must be an IP address or hostname, without a URL scheme, path, or port.');
|
||||
}
|
||||
return host;
|
||||
}
|
||||
|
||||
function hasRuntimeConfigChanges(currentConfig = {}, nextConfig = {}) {
|
||||
return RUNTIME_CONFIG_KEYS.some((key) => (
|
||||
JSON.stringify(currentConfig[key]) !== JSON.stringify(nextConfig[key])
|
||||
));
|
||||
}
|
||||
|
||||
function loadConfig(options = {}) {
|
||||
const projectPath = options.projectPath || getProjectPath();
|
||||
const env = options.env || process.env;
|
||||
const configPath = path.join(projectPath, 'funplay-cocos-mcp.config.json');
|
||||
const fileConfig = loadJson(configPath) || {};
|
||||
// Existing config files without a mode retain their old fixed endpoint.
|
||||
const portMode = fileConfig.portMode === 'project' || (!fs.existsSync(configPath) && !env.COCOS_MCP_PORT)
|
||||
? 'project' : 'fixed';
|
||||
const port = clampPort(env.COCOS_MCP_PORT || (portMode === 'project' ? getProjectPort(projectPath) : fileConfig.port || DEFAULTS.port));
|
||||
|
||||
return {
|
||||
...DEFAULTS,
|
||||
...fileConfig,
|
||||
host: env.COCOS_MCP_HOST || fileConfig.host || DEFAULTS.host,
|
||||
hostSource: env.COCOS_MCP_HOST ? 'environment' : 'project',
|
||||
port,
|
||||
portMode: env.COCOS_MCP_PORT ? 'fixed' : portMode,
|
||||
projectPath,
|
||||
clientConfigEntries: fileConfig.clientConfigEntries && typeof fileConfig.clientConfigEntries === 'object' && !Array.isArray(fileConfig.clientConfigEntries)
|
||||
? fileConfig.clientConfigEntries : {},
|
||||
toolProfile: normalizeProfile(process.env.COCOS_MCP_PROFILE || fileConfig.toolProfile || DEFAULTS.toolProfile),
|
||||
enabledTools: normalizeStringList(fileConfig.enabledTools),
|
||||
disabledTools: normalizeStringList(fileConfig.disabledTools),
|
||||
enabledToolCategories: normalizeStringList(fileConfig.enabledToolCategories).map((item) => item.toLowerCase()),
|
||||
disabledToolCategories: normalizeStringList(fileConfig.disabledToolCategories).map((item) => item.toLowerCase()),
|
||||
enableSessions: typeof fileConfig.enableSessions === 'boolean' ? fileConfig.enableSessions : DEFAULTS.enableSessions,
|
||||
enableConsoleLogging: typeof fileConfig.enableConsoleLogging === 'boolean'
|
||||
? fileConfig.enableConsoleLogging
|
||||
: DEFAULTS.enableConsoleLogging,
|
||||
executeJavascriptSafetyChecks: typeof fileConfig.executeJavascriptSafetyChecks === 'boolean'
|
||||
? fileConfig.executeJavascriptSafetyChecks
|
||||
: DEFAULTS.executeJavascriptSafetyChecks,
|
||||
autostart: typeof fileConfig.autostart === 'boolean' ? fileConfig.autostart : DEFAULTS.autostart,
|
||||
maxInteractionLogEntries: Number.isInteger(fileConfig.maxInteractionLogEntries)
|
||||
? Math.max(10, Math.min(500, fileConfig.maxInteractionLogEntries))
|
||||
: DEFAULTS.maxInteractionLogEntries,
|
||||
lastClientTargetId: normalizeClientTargetId(fileConfig.lastClientTargetId),
|
||||
activeToolProfileName: typeof fileConfig.activeToolProfileName === 'string' ? fileConfig.activeToolProfileName : '',
|
||||
savedToolProfiles: normalizeSavedToolProfiles(fileConfig.savedToolProfiles),
|
||||
language: normalizeLanguagePreference(fileConfig.language),
|
||||
configPath,
|
||||
configError: fileConfig.__error || '',
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
DEFAULTS,
|
||||
getProjectPath,
|
||||
getProjectName,
|
||||
getProjectIdentity,
|
||||
getProjectPort,
|
||||
getCocosVersion,
|
||||
loadConfig,
|
||||
hasRuntimeConfigChanges,
|
||||
normalizeProfile,
|
||||
normalizeHost,
|
||||
normalizeStringList,
|
||||
normalizeLanguagePreference,
|
||||
};
|
||||
+179
@@ -0,0 +1,179 @@
|
||||
'use strict';
|
||||
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const { execFile } = require('child_process');
|
||||
|
||||
function exists(filePath) {
|
||||
try {
|
||||
return fs.existsSync(filePath);
|
||||
} catch (error) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function findTypescriptCommand(projectPath, runtime = {}) {
|
||||
const platform = runtime.platform || process.platform;
|
||||
const nodeBinary = runtime.execPath || process.execPath;
|
||||
const possibleRoots = [
|
||||
runtime.editorPath || (global.Editor && Editor.App && Editor.App.path),
|
||||
runtime.resourcesPath || process.resourcesPath,
|
||||
global.Editor && Editor.App && Editor.App.path ? path.dirname(Editor.App.path) : '',
|
||||
global.Editor && Editor.App && Editor.App.path ? path.resolve(Editor.App.path, '..') : '',
|
||||
].filter(Boolean);
|
||||
|
||||
const editorBundledScripts = [];
|
||||
for (const root of possibleRoots) {
|
||||
editorBundledScripts.push(
|
||||
path.join(root, 'resources', '3d', 'engine', 'node_modules', 'typescript', 'bin', 'tsc'),
|
||||
path.join(root, 'resources', '3d', 'engine', 'node_modules', '@cocos', 'typescript', 'bin', 'tsc'),
|
||||
path.join(root, 'app.asar.unpacked', 'node_modules', 'typescript', 'bin', 'tsc'),
|
||||
path.join(root, 'Contents', 'Resources', 'resources', '3d', 'engine', 'node_modules', 'typescript', 'bin', 'tsc'),
|
||||
path.join(root, 'Contents', 'Resources', 'resources', '3d', 'engine', 'node_modules', '@cocos', 'typescript', 'bin', 'tsc')
|
||||
);
|
||||
}
|
||||
|
||||
const scriptCandidates = [
|
||||
path.join(projectPath, 'node_modules', 'typescript', 'bin', 'tsc'),
|
||||
...editorBundledScripts,
|
||||
];
|
||||
|
||||
for (const scriptPath of scriptCandidates) {
|
||||
if (exists(scriptPath)) {
|
||||
return {
|
||||
binary: nodeBinary,
|
||||
argsPrefix: [scriptPath],
|
||||
compiler: scriptPath,
|
||||
env: { ELECTRON_RUN_AS_NODE: '1' },
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
if (platform === 'win32') {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
binary: 'npx',
|
||||
argsPrefix: ['tsc'],
|
||||
compiler: 'npx tsc',
|
||||
};
|
||||
}
|
||||
|
||||
function findTsConfig(projectPath, explicitPath) {
|
||||
if (explicitPath) {
|
||||
return path.isAbsolute(explicitPath) ? explicitPath : path.join(projectPath, explicitPath);
|
||||
}
|
||||
|
||||
const candidates = [
|
||||
path.join(projectPath, 'tsconfig.json'),
|
||||
path.join(projectPath, 'temp', 'tsconfig.cocos.json'),
|
||||
];
|
||||
|
||||
return candidates.find((candidate) => exists(candidate)) || '';
|
||||
}
|
||||
|
||||
function runExec(file, args, cwd, env = {}) {
|
||||
return new Promise((resolve) => {
|
||||
execFile(file, args, {
|
||||
cwd,
|
||||
env: { ...process.env, ...env },
|
||||
maxBuffer: 8 * 1024 * 1024,
|
||||
}, (error, stdout, stderr) => {
|
||||
resolve({
|
||||
code: error && typeof error.code === 'number' ? error.code : 0,
|
||||
stdout: stdout || '',
|
||||
stderr: stderr || '',
|
||||
error: error ? error.message : '',
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function parseTscOutput(output) {
|
||||
const lines = String(output || '')
|
||||
.split(/\r?\n/)
|
||||
.map((line) => line.trim())
|
||||
.filter(Boolean);
|
||||
|
||||
const diagnostics = [];
|
||||
const regex = /^(.*)\((\d+),(\d+)\):\s+error\s+(TS\d+):\s+(.*)$/i;
|
||||
for (const line of lines) {
|
||||
const match = regex.exec(line);
|
||||
if (!match) {
|
||||
continue;
|
||||
}
|
||||
|
||||
diagnostics.push({
|
||||
file: match[1],
|
||||
line: Number(match[2]),
|
||||
column: Number(match[3]),
|
||||
code: match[4],
|
||||
message: match[5],
|
||||
});
|
||||
}
|
||||
|
||||
return diagnostics;
|
||||
}
|
||||
|
||||
async function runScriptDiagnostics(projectPath, options = {}) {
|
||||
const tsconfigPath = findTsConfig(projectPath, options.tsconfigPath);
|
||||
if (!tsconfigPath || !exists(tsconfigPath)) {
|
||||
return {
|
||||
ok: false,
|
||||
tool: 'typescript',
|
||||
summary: 'No tsconfig.json was found in the Cocos project.',
|
||||
diagnostics: [],
|
||||
stdout: '',
|
||||
stderr: '',
|
||||
};
|
||||
}
|
||||
|
||||
const command = findTypescriptCommand(projectPath);
|
||||
if (!command) {
|
||||
return {
|
||||
ok: false,
|
||||
tool: 'typescript',
|
||||
summary: 'TypeScript compiler was not found in the Cocos project or editor installation.',
|
||||
diagnostics: [],
|
||||
stdout: '',
|
||||
stderr: '',
|
||||
};
|
||||
}
|
||||
|
||||
const args = [
|
||||
...command.argsPrefix,
|
||||
'--noEmit',
|
||||
'-p',
|
||||
tsconfigPath,
|
||||
'--pretty',
|
||||
'false',
|
||||
];
|
||||
|
||||
const result = await runExec(command.binary, args, projectPath, command.env);
|
||||
const mergedOutput = [result.stdout, result.stderr, result.error].filter(Boolean).join('\n').trim();
|
||||
const diagnostics = parseTscOutput(mergedOutput);
|
||||
const ok = result.code === 0 && diagnostics.length === 0;
|
||||
|
||||
return {
|
||||
ok,
|
||||
tool: 'typescript',
|
||||
binary: command.binary,
|
||||
compiler: command.compiler,
|
||||
tsconfigPath,
|
||||
exitCode: result.code,
|
||||
summary: ok
|
||||
? 'TypeScript diagnostics completed successfully with no errors.'
|
||||
: diagnostics.length
|
||||
? `Found ${diagnostics.length} TypeScript error(s).`
|
||||
: mergedOutput || 'TypeScript diagnostics reported a non-zero exit code.',
|
||||
diagnostics,
|
||||
stdout: result.stdout,
|
||||
stderr: result.stderr,
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
findTypescriptCommand,
|
||||
runScriptDiagnostics,
|
||||
};
|
||||
+336
@@ -0,0 +1,336 @@
|
||||
'use strict';
|
||||
|
||||
function getElectron() {
|
||||
try {
|
||||
return require('electron');
|
||||
} catch (error) {
|
||||
throw new Error(`Electron APIs are unavailable: ${error.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeText(value) {
|
||||
return String(value || '').trim().toLowerCase();
|
||||
}
|
||||
|
||||
function getAllWindows() {
|
||||
const electron = getElectron();
|
||||
const BrowserWindow = electron.BrowserWindow;
|
||||
if (!BrowserWindow || typeof BrowserWindow.getAllWindows !== 'function') {
|
||||
throw new Error('Electron BrowserWindow API is unavailable.');
|
||||
}
|
||||
|
||||
return BrowserWindow.getAllWindows().filter((window) => window && !window.isDestroyed());
|
||||
}
|
||||
|
||||
function inferWindowKind(title) {
|
||||
const normalized = normalizeText(title);
|
||||
if (normalized.includes('simulator')) {
|
||||
return 'simulator';
|
||||
}
|
||||
if (normalized.includes('preview')) {
|
||||
return 'preview';
|
||||
}
|
||||
if (normalized.includes('cocos creator') || normalized.includes('cocos')) {
|
||||
return 'editor';
|
||||
}
|
||||
return 'unknown';
|
||||
}
|
||||
|
||||
function listWindows() {
|
||||
return getAllWindows().map((window, index) => ({
|
||||
index,
|
||||
id: typeof window.id === 'number' ? window.id : index,
|
||||
title: typeof window.getTitle === 'function' ? window.getTitle() : '',
|
||||
bounds: typeof window.getBounds === 'function' ? window.getBounds() : null,
|
||||
visible: typeof window.isVisible === 'function' ? window.isVisible() : true,
|
||||
focused: typeof window.isFocused === 'function' ? window.isFocused() : false,
|
||||
kind: inferWindowKind(typeof window.getTitle === 'function' ? window.getTitle() : ''),
|
||||
}));
|
||||
}
|
||||
|
||||
function pickWindow(options = {}) {
|
||||
const electron = getElectron();
|
||||
const BrowserWindow = electron.BrowserWindow;
|
||||
const windows = getAllWindows();
|
||||
if (!windows.length) {
|
||||
throw new Error('No Electron windows are available.');
|
||||
}
|
||||
if (options.windowId !== undefined) {
|
||||
if (!Number.isInteger(options.windowId)) throw new Error('windowId must be an integer returned by list_editor_windows or a screenshot.');
|
||||
const target = windows.find((window) => window.id === options.windowId);
|
||||
if (!target) throw new Error(`Electron window ${options.windowId} is unavailable.`);
|
||||
return target;
|
||||
}
|
||||
|
||||
const titleContains = normalizeText(options.titleContains);
|
||||
const windowKind = normalizeText(options.windowKind || 'focused');
|
||||
const focusedWindow = BrowserWindow.getFocusedWindow && BrowserWindow.getFocusedWindow();
|
||||
|
||||
const titleMatches = (window) => {
|
||||
if (!titleContains) {
|
||||
return true;
|
||||
}
|
||||
return normalizeText(window.getTitle && window.getTitle()).includes(titleContains);
|
||||
};
|
||||
|
||||
const kindMatches = (window) => {
|
||||
const kind = inferWindowKind(window.getTitle && window.getTitle());
|
||||
switch (windowKind) {
|
||||
case 'focused':
|
||||
return true;
|
||||
case 'editor':
|
||||
case 'simulator':
|
||||
case 'preview':
|
||||
return kind === windowKind;
|
||||
default:
|
||||
return true;
|
||||
}
|
||||
};
|
||||
|
||||
const candidates = windows.filter((window) => kindMatches(window) && titleMatches(window));
|
||||
const target = (focusedWindow && candidates.includes(focusedWindow) && focusedWindow)
|
||||
|| candidates.find((window) => typeof window.isVisible === 'function' ? window.isVisible() : true)
|
||||
|| candidates[0];
|
||||
|
||||
if (!target) {
|
||||
throw new Error(`No BrowserWindow matched windowKind='${windowKind}' titleContains='${titleContains}'.`);
|
||||
}
|
||||
|
||||
return target;
|
||||
}
|
||||
|
||||
async function executeJavaScript(window, script) {
|
||||
if (!window || !window.webContents || typeof window.webContents.executeJavaScript !== 'function') {
|
||||
throw new Error('Target window does not support webContents.executeJavaScript.');
|
||||
}
|
||||
return await window.webContents.executeJavaScript(script, true);
|
||||
}
|
||||
|
||||
function buildPanelBoundsScript(panelName) {
|
||||
const panel = JSON.stringify(String(panelName || 'scene'));
|
||||
return `
|
||||
(() => {
|
||||
try {
|
||||
const panelName = ${panel}.toLowerCase();
|
||||
|
||||
const isVisible = (element) => {
|
||||
if (!element || typeof element.getBoundingClientRect !== 'function') return false;
|
||||
const style = window.getComputedStyle(element);
|
||||
const rect = element.getBoundingClientRect();
|
||||
return style && style.display !== 'none' && style.visibility !== 'hidden' && rect.width > 4 && rect.height > 4;
|
||||
};
|
||||
|
||||
const textOf = (element) => {
|
||||
const parts = [
|
||||
element.getAttribute && element.getAttribute('name'),
|
||||
element.getAttribute && element.getAttribute('title'),
|
||||
element.id,
|
||||
element.className,
|
||||
element.textContent,
|
||||
];
|
||||
return parts.filter(Boolean).join(' ').toLowerCase();
|
||||
};
|
||||
|
||||
const collectAll = (root, bucket) => {
|
||||
if (!root) return;
|
||||
const nodes = root.querySelectorAll ? root.querySelectorAll('*') : [];
|
||||
for (const node of nodes) {
|
||||
if (bucket.length >= 15000) throw new Error('Panel discovery exceeded its DOM budget.');
|
||||
bucket.push(node);
|
||||
if (node.shadowRoot) {
|
||||
collectAll(node.shadowRoot, bucket);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const all = [];
|
||||
collectAll(document, all);
|
||||
|
||||
const viewportBounds = (element, label) => {
|
||||
const rect = element.getBoundingClientRect();
|
||||
return {
|
||||
x: rect.left, y: rect.top, width: rect.width, height: rect.height,
|
||||
elementTag: element.tagName, innerTag: element.tagName,
|
||||
text: label, innerText: label,
|
||||
};
|
||||
};
|
||||
|
||||
// Creator 3.8 Game View lives inside the Scene panel's shadow DOM. Its
|
||||
// toolbar contains "game" but is not the render surface; text scoring
|
||||
// alone can crop just that 29px bar. Prefer the native engine WebView.
|
||||
if (panelName === 'game' || panelName === 'scene') {
|
||||
const gamePreload = '/preload/web/preview.js';
|
||||
const scenePreload = '/preload/web/preload.js';
|
||||
const engineViews = all.flatMap((element) => {
|
||||
if (String(element.tagName).toLowerCase() !== 'webview') return [];
|
||||
try {
|
||||
const source = new URL(element.getAttribute('src') || '');
|
||||
if (source.protocol !== 'packages:' || source.hostname !== 'scene') return [];
|
||||
const scriptPath = (source.searchParams.get('url') || source.pathname).replace(/\\\\/g, '/');
|
||||
if (scriptPath.endsWith(gamePreload)) return [{ element, panel: 'game' }];
|
||||
if (scriptPath.endsWith(scenePreload)) return [{ element, panel: 'scene' }];
|
||||
} catch (error) {
|
||||
// A WebView without a parseable source cannot identify a native viewport.
|
||||
}
|
||||
return [];
|
||||
});
|
||||
const nativeViews = engineViews.filter((view) => view.panel === panelName && isVisible(view.element));
|
||||
if (nativeViews.length > 1) throw new Error('Multiple visible native ' + panelName + ' viewports matched; choose an exact window.');
|
||||
if (nativeViews.length === 1) return viewportBounds(nativeViews[0].element, 'native-' + panelName + '-viewport');
|
||||
if (engineViews.length) throw new Error('The native ' + panelName + ' viewport is not visible or ready; activate it and capture again.');
|
||||
}
|
||||
|
||||
if (panelName === 'game') {
|
||||
const gameCanvases = all.filter((element) => (
|
||||
String(element.tagName).toLowerCase() === 'canvas' && element.id === 'GameCanvas' && isVisible(element)
|
||||
));
|
||||
if (gameCanvases.length === 1) return viewportBounds(gameCanvases[0], 'game-canvas');
|
||||
if (gameCanvases.length > 1) throw new Error('Multiple visible GameCanvas elements matched; choose an exact preview window.');
|
||||
throw new Error('Could not locate a visible Cocos Game View or GameCanvas. Open Editor Preview or select the window containing the game preview.');
|
||||
}
|
||||
|
||||
const scoreElement = (element) => {
|
||||
const text = textOf(element);
|
||||
let score = 0;
|
||||
if (text.includes(panelName)) score += 100;
|
||||
if (text.includes('panel-frame')) score += 5;
|
||||
if (panelName === 'scene' && text.includes('game')) score -= 10;
|
||||
return score;
|
||||
};
|
||||
|
||||
const largestChildRect = (element) => {
|
||||
const bucket = [element];
|
||||
if (element.shadowRoot) collectAll(element.shadowRoot, bucket);
|
||||
const children = bucket
|
||||
.filter((node) => isVisible(node))
|
||||
.map((node) => {
|
||||
const rect = node.getBoundingClientRect();
|
||||
const text = textOf(node);
|
||||
let score = rect.width * rect.height;
|
||||
if (node.tagName && node.tagName.toLowerCase() === 'canvas') score += 50000;
|
||||
if (text.includes(panelName)) score += 20000;
|
||||
if (text.includes('canvas') || text.includes('preview') || text.includes('viewport')) score += 10000;
|
||||
return { rect, score, tag: node.tagName || '', text };
|
||||
})
|
||||
.sort((a, b) => b.score - a.score);
|
||||
return children[0] || null;
|
||||
};
|
||||
|
||||
const candidates = all
|
||||
.filter((element) => isVisible(element))
|
||||
.map((element) => {
|
||||
const panelScore = scoreElement(element);
|
||||
if (panelScore <= 0) return null;
|
||||
const rectInfo = largestChildRect(element) || { rect: element.getBoundingClientRect(), score: 0, tag: element.tagName || '', text: textOf(element) };
|
||||
return {
|
||||
score: panelScore + rectInfo.score,
|
||||
elementTag: element.tagName || '',
|
||||
rect: rectInfo.rect,
|
||||
text: textOf(element),
|
||||
innerTag: rectInfo.tag,
|
||||
innerText: rectInfo.text,
|
||||
};
|
||||
})
|
||||
.filter(Boolean)
|
||||
.sort((a, b) => b.score - a.score);
|
||||
|
||||
const fallbackCanvases = all
|
||||
.filter((element) => isVisible(element) && element.tagName && element.tagName.toLowerCase() === 'canvas')
|
||||
.map((element) => {
|
||||
const rect = element.getBoundingClientRect();
|
||||
const text = textOf(element);
|
||||
let score = rect.width * rect.height;
|
||||
if (text.includes(panelName)) score += 50000;
|
||||
return { score, rect, elementTag: 'CANVAS', text, innerTag: 'CANVAS', innerText: text };
|
||||
})
|
||||
.sort((a, b) => b.score - a.score);
|
||||
|
||||
const target = candidates[0] || fallbackCanvases[0];
|
||||
if (!target) return null;
|
||||
|
||||
return {
|
||||
x: Math.max(0, Math.floor(target.rect.left)),
|
||||
y: Math.max(0, Math.floor(target.rect.top)),
|
||||
width: Math.max(1, Math.floor(target.rect.width)),
|
||||
height: Math.max(1, Math.floor(target.rect.height)),
|
||||
elementTag: target.elementTag,
|
||||
innerTag: target.innerTag,
|
||||
text: target.text,
|
||||
innerText: target.innerText,
|
||||
};
|
||||
} catch (error) {
|
||||
// Electron discards thrown renderer error messages. Return a bounded
|
||||
// diagnostic so the host can report why this viewport was rejected.
|
||||
return { panelDiscoveryError: String(error && error.message || error).slice(0, 500) };
|
||||
}
|
||||
})();
|
||||
`;
|
||||
}
|
||||
|
||||
async function getPanelBounds(window, panelName) {
|
||||
const result = await executeJavaScript(window, buildPanelBoundsScript(panelName));
|
||||
if (result && result.panelDiscoveryError) throw new Error(result.panelDiscoveryError);
|
||||
if (!result || !result.width || !result.height) {
|
||||
throw new Error(`Could not locate a visible '${panelName}' panel in the target window.`);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
function buildPanelFocusScript(panelName, offsetX, offsetY) {
|
||||
return `
|
||||
(() => {
|
||||
const panelName = ${JSON.stringify(String(panelName || 'scene').toLowerCase())};
|
||||
const offsetX = ${Number(offsetX || 0)};
|
||||
const offsetY = ${Number(offsetY || 0)};
|
||||
const isVisible = (element) => {
|
||||
if (!element || typeof element.getBoundingClientRect !== 'function') return false;
|
||||
const style = window.getComputedStyle(element);
|
||||
const rect = element.getBoundingClientRect();
|
||||
return style && style.display !== 'none' && style.visibility !== 'hidden' && rect.width > 4 && rect.height > 4;
|
||||
};
|
||||
const textOf = (element) => [
|
||||
element.getAttribute && element.getAttribute('name'),
|
||||
element.getAttribute && element.getAttribute('title'),
|
||||
element.id,
|
||||
element.className,
|
||||
element.textContent,
|
||||
].filter(Boolean).join(' ').toLowerCase();
|
||||
const collectAll = (root, bucket) => {
|
||||
if (!root) return;
|
||||
const nodes = root.querySelectorAll ? root.querySelectorAll('*') : [];
|
||||
for (const node of nodes) {
|
||||
bucket.push(node);
|
||||
if (node.shadowRoot) collectAll(node.shadowRoot, bucket);
|
||||
}
|
||||
};
|
||||
const all = [];
|
||||
collectAll(document, all);
|
||||
const target = all.find((element) => isVisible(element) && textOf(element).includes(panelName));
|
||||
const rect = target ? target.getBoundingClientRect() : { left: 0, top: 0, width: window.innerWidth, height: window.innerHeight };
|
||||
const x = Math.floor(rect.left + rect.width / 2 + offsetX);
|
||||
const y = Math.floor(rect.top + rect.height / 2 + offsetY);
|
||||
const focusable = document.elementFromPoint(x, y) || target || document.body;
|
||||
if (focusable && typeof focusable.focus === 'function') focusable.focus();
|
||||
return { x, y };
|
||||
})();
|
||||
`;
|
||||
}
|
||||
|
||||
async function getPanelPoint(window, panelName, offsetX, offsetY) {
|
||||
return await executeJavaScript(window, buildPanelFocusScript(panelName, offsetX, offsetY));
|
||||
}
|
||||
|
||||
function sleep(milliseconds) {
|
||||
return new Promise((resolve) => setTimeout(resolve, milliseconds));
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
executeJavaScript,
|
||||
getAllWindows,
|
||||
getPanelBounds,
|
||||
getPanelPoint,
|
||||
inferWindowKind,
|
||||
listWindows,
|
||||
pickWindow,
|
||||
sleep,
|
||||
};
|
||||
+351
@@ -0,0 +1,351 @@
|
||||
'use strict';
|
||||
|
||||
const fs = require('fs');
|
||||
const os = require('os');
|
||||
const path = require('path');
|
||||
const { compareVersions, normalizeVersion } = require('./update-checker');
|
||||
const { installLatestUpdate } = require('./updater');
|
||||
|
||||
const PACKAGE_NAME = 'funplay-cocos-mcp';
|
||||
|
||||
function normalizePathForComparison(value) {
|
||||
const resolved = path.resolve(String(value || ''));
|
||||
return process.platform === 'win32' ? resolved.toLowerCase() : resolved;
|
||||
}
|
||||
|
||||
function realPathOrResolved(value) {
|
||||
const resolved = path.resolve(String(value || ''));
|
||||
try {
|
||||
const realPath = fs.realpathSync.native
|
||||
? fs.realpathSync.native(resolved)
|
||||
: fs.realpathSync(resolved);
|
||||
return normalizePathForComparison(realPath);
|
||||
} catch (error) {
|
||||
return normalizePathForComparison(resolved);
|
||||
}
|
||||
}
|
||||
|
||||
function isSameLocation(left, right) {
|
||||
if (!left || !right) {
|
||||
return false;
|
||||
}
|
||||
return realPathOrResolved(left) === realPathOrResolved(right);
|
||||
}
|
||||
|
||||
function getGlobalExtensionsDirectory(options = {}) {
|
||||
const editorHomePath = String(options.editorHomePath || '').trim();
|
||||
const editorVersion = String(options.editorVersion || '').trim().replace(/^v/i, '');
|
||||
if (editorHomePath && editorVersion) {
|
||||
return path.resolve(editorHomePath, 'builtin-extensions', editorVersion);
|
||||
}
|
||||
|
||||
const homePath = String(options.homePath || os.homedir() || '').trim();
|
||||
if (!homePath) {
|
||||
throw new Error('Unable to resolve the current user home directory for the Cocos global extension install.');
|
||||
}
|
||||
return path.resolve(homePath, '.CocosCreator', 'extensions');
|
||||
}
|
||||
|
||||
function readPackageInstallation(packagePath) {
|
||||
const resolvedPath = path.resolve(String(packagePath || ''));
|
||||
let stat;
|
||||
try {
|
||||
stat = fs.lstatSync(resolvedPath);
|
||||
} catch (error) {
|
||||
if (error && error.code === 'ENOENT') {
|
||||
return {
|
||||
path: resolvedPath,
|
||||
realPath: realPathOrResolved(resolvedPath),
|
||||
exists: false,
|
||||
valid: false,
|
||||
name: '',
|
||||
version: '',
|
||||
isSymlink: false,
|
||||
error: '',
|
||||
};
|
||||
}
|
||||
return {
|
||||
path: resolvedPath,
|
||||
realPath: realPathOrResolved(resolvedPath),
|
||||
exists: true,
|
||||
valid: false,
|
||||
name: '',
|
||||
version: '',
|
||||
isSymlink: false,
|
||||
error: error.message,
|
||||
};
|
||||
}
|
||||
|
||||
const installation = {
|
||||
path: resolvedPath,
|
||||
realPath: realPathOrResolved(resolvedPath),
|
||||
exists: true,
|
||||
valid: false,
|
||||
name: '',
|
||||
version: '',
|
||||
isSymlink: stat.isSymbolicLink(),
|
||||
error: '',
|
||||
};
|
||||
|
||||
if (!stat.isDirectory() && !stat.isSymbolicLink()) {
|
||||
installation.error = 'The extension path exists but is not a directory.';
|
||||
return installation;
|
||||
}
|
||||
|
||||
const manifestPath = path.join(resolvedPath, 'package.json');
|
||||
if (!fs.existsSync(manifestPath)) {
|
||||
installation.error = 'package.json is missing.';
|
||||
return installation;
|
||||
}
|
||||
|
||||
try {
|
||||
const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8'));
|
||||
installation.name = String(manifest.name || '');
|
||||
installation.version = normalizeVersion(manifest.version || '');
|
||||
installation.valid = installation.name === PACKAGE_NAME && Boolean(installation.version);
|
||||
if (!installation.valid) {
|
||||
installation.error = installation.name !== PACKAGE_NAME
|
||||
? `Unexpected extension package name: ${installation.name || 'unknown'}.`
|
||||
: 'The extension package version is missing.';
|
||||
}
|
||||
} catch (error) {
|
||||
installation.error = `Failed to read package.json: ${error.message}`;
|
||||
}
|
||||
|
||||
return installation;
|
||||
}
|
||||
|
||||
function getGlobalInstallationState(options = {}) {
|
||||
const currentPackagePath = path.resolve(options.packagePath || path.join(__dirname, '..'));
|
||||
const projectPath = path.resolve(options.projectPath || process.cwd());
|
||||
const globalExtensionsPath = path.resolve(
|
||||
options.globalExtensionsPath || getGlobalExtensionsDirectory(options)
|
||||
);
|
||||
const globalPackagePath = path.join(globalExtensionsPath, PACKAGE_NAME);
|
||||
const projectPackagePath = path.join(projectPath, 'extensions', PACKAGE_NAME);
|
||||
const current = readPackageInstallation(currentPackagePath);
|
||||
const global = readPackageInstallation(globalPackagePath);
|
||||
const project = readPackageInstallation(projectPackagePath);
|
||||
const currentVersion = normalizeVersion(options.currentVersion || current.version || '');
|
||||
const targetVersion = normalizeVersion(options.availableVersion || currentVersion);
|
||||
|
||||
let scope = 'external';
|
||||
if (isSameLocation(currentPackagePath, globalPackagePath)) {
|
||||
scope = 'global';
|
||||
} else if (isSameLocation(currentPackagePath, projectPackagePath)) {
|
||||
scope = 'project';
|
||||
}
|
||||
|
||||
const globalInvalid = global.exists && !global.valid;
|
||||
const duplicateInstall = Boolean(
|
||||
global.valid &&
|
||||
project.valid &&
|
||||
!isSameLocation(globalPackagePath, projectPackagePath)
|
||||
);
|
||||
|
||||
let action = 'installed';
|
||||
if (globalInvalid) {
|
||||
action = 'blocked';
|
||||
} else if (!global.valid) {
|
||||
action = 'install';
|
||||
} else if (targetVersion && compareVersions(targetVersion, global.version) > 0) {
|
||||
action = 'update';
|
||||
} else if (scope === 'global') {
|
||||
action = 'active';
|
||||
}
|
||||
|
||||
return {
|
||||
packageName: PACKAGE_NAME,
|
||||
editorVersion: String(options.editorVersion || '').trim().replace(/^v/i, ''),
|
||||
scope,
|
||||
currentPackagePath,
|
||||
currentVersion,
|
||||
targetVersion,
|
||||
globalExtensionsPath,
|
||||
globalPackagePath,
|
||||
globalPathExists: global.exists,
|
||||
globalInstalled: global.valid,
|
||||
globalVersion: global.version,
|
||||
globalInstallError: globalInvalid ? global.error : '',
|
||||
projectPackagePath,
|
||||
projectInstalled: project.valid,
|
||||
projectVersion: project.version,
|
||||
duplicateInstall,
|
||||
action,
|
||||
canInstallGlobally: action === 'install' || action === 'update',
|
||||
automaticForNewProjects: global.valid,
|
||||
};
|
||||
}
|
||||
|
||||
function getMatchingEditorPackages(editor, filter = {}) {
|
||||
if (!editor || !editor.Package || typeof editor.Package.getPackages !== 'function') {
|
||||
return [];
|
||||
}
|
||||
|
||||
try {
|
||||
const packages = editor.Package.getPackages(filter);
|
||||
return Array.isArray(packages) ? packages : [];
|
||||
} catch (error) {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
function findEditorPackageByPath(editor, packagePath) {
|
||||
const resolvedPath = path.resolve(String(packagePath || ''));
|
||||
return getMatchingEditorPackages(editor, { path: resolvedPath })
|
||||
.find((item) => item && isSameLocation(item.path, resolvedPath)) || null;
|
||||
}
|
||||
|
||||
async function activateGlobalExtension(options = {}) {
|
||||
const editor = options.editor;
|
||||
const globalPackagePath = path.resolve(String(options.globalPackagePath || ''));
|
||||
const result = {
|
||||
available: Boolean(editor && editor.Package),
|
||||
scanned: false,
|
||||
registered: false,
|
||||
enabled: false,
|
||||
activePath: '',
|
||||
shadowedBy: '',
|
||||
errors: [],
|
||||
};
|
||||
|
||||
if (!result.available) {
|
||||
result.errors.push('Cocos package APIs are unavailable; reopen the project to activate the global extension.');
|
||||
return result;
|
||||
}
|
||||
|
||||
if (editor.Message && typeof editor.Message.request === 'function') {
|
||||
try {
|
||||
await editor.Message.request('extension', 'scanning', 'global');
|
||||
result.scanned = true;
|
||||
} catch (error) {
|
||||
result.errors.push(`Cocos global extension scan failed: ${error.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
let packageInfo = findEditorPackageByPath(editor, globalPackagePath);
|
||||
if (!packageInfo && typeof editor.Package.register === 'function') {
|
||||
try {
|
||||
await editor.Package.register(globalPackagePath);
|
||||
packageInfo = findEditorPackageByPath(editor, globalPackagePath);
|
||||
} catch (error) {
|
||||
result.errors.push(`Cocos extension registration failed: ${error.message}`);
|
||||
}
|
||||
}
|
||||
result.registered = Boolean(packageInfo);
|
||||
|
||||
const activePackageBeforeEnable = getMatchingEditorPackages(editor, { name: PACKAGE_NAME })
|
||||
.find((item) => item && item.enable);
|
||||
if (
|
||||
activePackageBeforeEnable &&
|
||||
activePackageBeforeEnable.path &&
|
||||
!isSameLocation(activePackageBeforeEnable.path, globalPackagePath)
|
||||
) {
|
||||
result.activePath = path.resolve(activePackageBeforeEnable.path);
|
||||
result.shadowedBy = result.activePath;
|
||||
return result;
|
||||
}
|
||||
|
||||
if (result.registered) {
|
||||
try {
|
||||
if (editor.Message && typeof editor.Message.request === 'function') {
|
||||
await editor.Message.request(
|
||||
'extension',
|
||||
'enable',
|
||||
globalPackagePath,
|
||||
true,
|
||||
{ addNotification: false, showInExtensionManager: false }
|
||||
);
|
||||
} else if (typeof editor.Package.enable === 'function') {
|
||||
await editor.Package.enable(globalPackagePath);
|
||||
}
|
||||
} catch (error) {
|
||||
result.errors.push(`Cocos extension enable failed: ${error.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
packageInfo = findEditorPackageByPath(editor, globalPackagePath);
|
||||
result.registered = Boolean(packageInfo);
|
||||
result.enabled = Boolean(packageInfo && packageInfo.enable);
|
||||
|
||||
const activePackage = getMatchingEditorPackages(editor, { name: PACKAGE_NAME })
|
||||
.find((item) => item && item.enable);
|
||||
if (activePackage && activePackage.path) {
|
||||
result.activePath = path.resolve(activePackage.path);
|
||||
if (!isSameLocation(activePackage.path, globalPackagePath)) {
|
||||
result.shadowedBy = result.activePath;
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
async function installGlobalExtension(options = {}) {
|
||||
const state = getGlobalInstallationState(options);
|
||||
if (state.globalPathExists && !state.globalInstalled) {
|
||||
throw new Error(
|
||||
`Global extension path is occupied by an invalid package: ${state.globalPackagePath}. ` +
|
||||
`${state.globalInstallError || 'Remove or rename it before installing.'}`
|
||||
);
|
||||
}
|
||||
|
||||
const releaseInfo = options.releaseInfo || {};
|
||||
const latestVersion = normalizeVersion(releaseInfo.latestVersion || releaseInfo.tagName || '');
|
||||
if (!latestVersion) {
|
||||
throw new Error('Latest release version is unknown.');
|
||||
}
|
||||
|
||||
if (state.globalInstalled) {
|
||||
const comparison = compareVersions(latestVersion, state.globalVersion);
|
||||
if (comparison < 0 && !options.allowDowngrade) {
|
||||
throw new Error(
|
||||
`Refusing to replace newer global version ${state.globalVersion} with ${latestVersion}.`
|
||||
);
|
||||
}
|
||||
if (comparison === 0 && !options.force) {
|
||||
return {
|
||||
ok: true,
|
||||
installed: false,
|
||||
alreadyInstalled: true,
|
||||
installedVersion: state.globalVersion,
|
||||
packagePath: state.globalPackagePath,
|
||||
globalPackagePath: state.globalPackagePath,
|
||||
restartRequired: false,
|
||||
duplicateInstall: state.duplicateInstall,
|
||||
projectPackagePath: state.projectPackagePath,
|
||||
automaticForNewProjects: true,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
const installer = options.installer || installLatestUpdate;
|
||||
const result = await installer({
|
||||
releaseInfo,
|
||||
currentVersion: state.globalVersion || '0.0.0',
|
||||
packagePath: state.globalPackagePath,
|
||||
timeoutMs: options.timeoutMs,
|
||||
maxDownloadBytes: options.maxDownloadBytes,
|
||||
log: options.log,
|
||||
force: Boolean(options.force || options.allowDowngrade),
|
||||
});
|
||||
const after = getGlobalInstallationState(options);
|
||||
|
||||
return {
|
||||
...result,
|
||||
globalPackagePath: after.globalPackagePath,
|
||||
restartRequired: true,
|
||||
duplicateInstall: after.duplicateInstall,
|
||||
projectPackagePath: after.projectPackagePath,
|
||||
automaticForNewProjects: after.automaticForNewProjects,
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
PACKAGE_NAME,
|
||||
activateGlobalExtension,
|
||||
getGlobalExtensionsDirectory,
|
||||
getGlobalInstallationState,
|
||||
installGlobalExtension,
|
||||
isSameLocation,
|
||||
readPackageInstallation,
|
||||
};
|
||||
+71
@@ -0,0 +1,71 @@
|
||||
'use strict';
|
||||
|
||||
const DEFAULT_LANGUAGE = 'en';
|
||||
const LANGUAGE_PREFERENCES = new Set(['auto', 'en', 'zh']);
|
||||
const TRANSLATION_KEY = 'funplay-cocos-mcp.language_code';
|
||||
|
||||
function normalizeLanguagePreference(value) {
|
||||
const normalized = String(value || '').trim().toLowerCase();
|
||||
return LANGUAGE_PREFERENCES.has(normalized) ? normalized : 'auto';
|
||||
}
|
||||
|
||||
function normalizeLocale(value) {
|
||||
const normalized = String(value || '').trim().toLowerCase().replace(/_/g, '-');
|
||||
return normalized === 'zh' || normalized.startsWith('zh-') ? 'zh' : DEFAULT_LANGUAGE;
|
||||
}
|
||||
|
||||
function detectEditorLanguage(editor = global.Editor) {
|
||||
if (editor && editor.I18n && typeof editor.I18n.t === 'function') {
|
||||
try {
|
||||
const translated = String(editor.I18n.t(TRANSLATION_KEY) || '').trim().toLowerCase();
|
||||
if (translated === 'en' || translated === 'zh') {
|
||||
return translated;
|
||||
}
|
||||
} catch (error) {
|
||||
// Fall back to exposed locale properties and the host locale.
|
||||
}
|
||||
}
|
||||
|
||||
const candidates = [
|
||||
editor && editor.I18n && editor.I18n.locale,
|
||||
editor && editor.I18n && editor.I18n.language,
|
||||
editor && editor.App && editor.App.language,
|
||||
process.env.LC_ALL,
|
||||
process.env.LC_MESSAGES,
|
||||
process.env.LANG,
|
||||
];
|
||||
const explicit = candidates.find((value) => typeof value === 'string' && value.trim());
|
||||
if (explicit) {
|
||||
return normalizeLocale(explicit);
|
||||
}
|
||||
|
||||
try {
|
||||
return normalizeLocale(Intl.DateTimeFormat().resolvedOptions().locale);
|
||||
} catch (error) {
|
||||
return DEFAULT_LANGUAGE;
|
||||
}
|
||||
}
|
||||
|
||||
function resolveLanguage(preference, detectedLanguage) {
|
||||
const normalized = normalizeLanguagePreference(preference);
|
||||
return normalized === 'auto' ? normalizeLocale(detectedLanguage) : normalized;
|
||||
}
|
||||
|
||||
function translate(dictionaries, language, key, replacements = {}) {
|
||||
const dictionary = dictionaries[normalizeLocale(language)] || dictionaries[DEFAULT_LANGUAGE] || {};
|
||||
const fallback = dictionaries[DEFAULT_LANGUAGE] || {};
|
||||
const template = dictionary[key] !== undefined ? dictionary[key] : fallback[key];
|
||||
const text = template === undefined ? key : String(template);
|
||||
return text.replace(/\{([A-Za-z0-9_]+)\}/g, (match, name) => (
|
||||
replacements[name] === undefined ? match : String(replacements[name])
|
||||
));
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
DEFAULT_LANGUAGE,
|
||||
detectEditorLanguage,
|
||||
normalizeLanguagePreference,
|
||||
normalizeLocale,
|
||||
resolveLanguage,
|
||||
translate,
|
||||
};
|
||||
+289
@@ -0,0 +1,289 @@
|
||||
'use strict';
|
||||
|
||||
const crypto = require('crypto');
|
||||
const { performance } = require('perf_hooks');
|
||||
const electronTools = require('./electron-tools');
|
||||
const { getCaptureWindow, resolveImagePoints, acquireInputWindow } = require('./visual-coordinates');
|
||||
const { controlPreviewToolbar } = require('./preview-runtime');
|
||||
|
||||
const MAX_RECEIPTS = 32;
|
||||
const MAX_SAMPLES = 64;
|
||||
const jobs = new Map();
|
||||
|
||||
// Serialized into the exact captured BrowserWindow. A renderer animation frame
|
||||
// is NOT evidence of the native Game View's engine Update or game acceptance.
|
||||
function nextRendererFrame() {
|
||||
return new Promise((resolve, reject) => {
|
||||
if (typeof requestAnimationFrame !== 'function' || typeof cancelAnimationFrame !== 'function') {
|
||||
reject(new Error('Renderer animation frames are unavailable.'));
|
||||
return;
|
||||
}
|
||||
let id;
|
||||
const timer = setTimeout(() => { cancelAnimationFrame(id); reject(new Error('Target renderer frame stalled.')); }, 1000);
|
||||
id = requestAnimationFrame((timestamp) => {
|
||||
clearTimeout(timer);
|
||||
try {
|
||||
resolve({ timestamp, epoch: performance.timeOrigin, focused: document.hasFocus(),
|
||||
source: 'target-renderer-animation-frame' });
|
||||
} catch (error) { reject(error); }
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function fail(code, message) {
|
||||
const error = new Error(`${code}: ${message}`);
|
||||
error.code = code;
|
||||
return error;
|
||||
}
|
||||
|
||||
function numberOption(options, name, fallback, min, max) {
|
||||
const value = options[name] === undefined ? fallback : options[name];
|
||||
if (!Number.isFinite(value) || value < min || value > max) throw fail('INVALID_INPUT_TIMING', `${name} must be ${min}..${max}.`);
|
||||
return value;
|
||||
}
|
||||
|
||||
function ownerKey(options) {
|
||||
if (!options.inputOwner || !options.projectPath || !options.originatingTool) throw fail('INPUT_CONTEXT_REQUIRED', 'Input owner, project and originating tool are required.');
|
||||
return JSON.stringify([options.inputOwner, options.projectPath, options.originatingTool]);
|
||||
}
|
||||
|
||||
function snapshot(job) {
|
||||
return { jobId: job.id, requestKey: job.requestKey, status: job.status, phase: job.phase,
|
||||
sent: job.status === 'completed', inputSent: job.status === 'completed' ? true : job.attempted ? null : false,
|
||||
eventsSubmitted: job.events, releaseSubmitted: job.releaseSubmitted, cleanup: job.cleanup,
|
||||
error: job.error ? { ...job.error } : null, windowId: job.window && job.window.id,
|
||||
captureId: job.options.captureId, coordinateSpace: 'image-pixels',
|
||||
durationMs: job.options.durationMs, pressHoldMs: job.options.pressHoldMs, endHoldMs: job.options.endHoldMs,
|
||||
elapsedMs: Math.round((job.finishedAt || performance.now()) - job.createdAt),
|
||||
observedRendererFrames: job.frameCount, samples: job.samples.map((item) => ({ ...item })),
|
||||
samplesOmitted: Math.max(0, job.frameCount - job.samples.length),
|
||||
frameEvidenceScope: 'target-renderer-animation-frame', nativeGameUpdateVerified: false, businessOutcomeVerified: false,
|
||||
projectContext: job.options.projectContext ? { ...job.options.projectContext } : null, originatingTool: job.options.originatingTool,
|
||||
};
|
||||
}
|
||||
|
||||
async function bounded(job, operation) {
|
||||
if (job.abort.signal.aborted) throw fail('INPUT_CANCELLED', 'Gesture cancelled.');
|
||||
let timer;
|
||||
let abort;
|
||||
try {
|
||||
return await Promise.race([
|
||||
Promise.resolve().then(operation),
|
||||
new Promise((resolve, reject) => {
|
||||
abort = () => reject(fail('INPUT_CANCELLED', 'Gesture cancelled.'));
|
||||
job.abort.signal.addEventListener('abort', abort, { once: true });
|
||||
timer = setTimeout(() => reject(fail('INPUT_FRAME_TIMEOUT', 'Renderer or geometry observation timed out.')), Math.max(1, Math.min(1500, job.deadline - performance.now())));
|
||||
}),
|
||||
]);
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
if (abort) job.abort.signal.removeEventListener('abort', abort);
|
||||
}
|
||||
}
|
||||
|
||||
async function cleanup(job) {
|
||||
if (job.pressed) {
|
||||
try {
|
||||
if (!job.window.isDestroyed || !job.window.isDestroyed()) {
|
||||
job.emit({ type: 'mouseUp', ...job.lastPoint, button: job.options.button, clickCount: 1, modifiers: job.options.modifiers }, true);
|
||||
job.events++;
|
||||
job.releaseSubmitted = true;
|
||||
}
|
||||
job.pressed = false;
|
||||
} catch (error) {
|
||||
job.cleanup = 'failed';
|
||||
return;
|
||||
}
|
||||
}
|
||||
job.cleanup = 'complete';
|
||||
if (job.releaseLock) { job.releaseLock(); job.releaseLock = null; }
|
||||
}
|
||||
|
||||
async function run(job, nativeMouseEvent) {
|
||||
const options = job.options;
|
||||
const pixels = [{ x: options.startX, y: options.startY }, { x: options.endX, y: options.endY }];
|
||||
job.emit = (event, held) => {
|
||||
job.attempted = true;
|
||||
job.window.webContents.sendInputEvent(nativeMouseEvent(job.window, event, held));
|
||||
};
|
||||
const submit = (type, point) => {
|
||||
if (job.abort.signal.aborted) throw fail('INPUT_CANCELLED', 'Gesture cancelled.');
|
||||
if (type === 'mouseDown') job.pressed = true; // May have arrived even if dispatch throws.
|
||||
job.lastPoint = point;
|
||||
job.emit({ type, ...point, button: options.button, clickCount: 1, modifiers: options.modifiers }, type !== 'mouseMove' || job.pressed);
|
||||
job.events++;
|
||||
if (type === 'mouseUp') { job.pressed = false; job.releaseSubmitted = true; }
|
||||
};
|
||||
const sample = async () => {
|
||||
if (performance.now() > job.deadline) throw fail('INPUT_DEADLINE_EXCEEDED', 'Gesture deadline exceeded.');
|
||||
const frame = await bounded(job, () => electronTools.executeJavaScript(job.window, `(${nextRendererFrame.toString()})()`));
|
||||
// Creator's native Game View can own focus inside the captured window
|
||||
// while its host document reports false. Require the OS window's focus
|
||||
// for native input; web targets still require their document's focus too.
|
||||
// After Up no further input is sent, so a focus handoff can be observed
|
||||
// without turning an otherwise finished gesture into failed delivery.
|
||||
const windowFocused = typeof job.window.isFocused === 'function'
|
||||
? job.window.isFocused() === true : Boolean(frame && frame.focused === true);
|
||||
const inputFocused = windowFocused && Boolean(frame && (frame.focused === true || job.gameView));
|
||||
if (!frame || !Number.isFinite(frame.timestamp) || !Number.isFinite(frame.epoch)
|
||||
|| (job.phase !== 'released' && !inputFocused)) {
|
||||
throw fail('INPUT_FRAME_UNAVAILABLE', 'A focused target window with advancing renderer frames is required. No background/focus policy was changed.');
|
||||
}
|
||||
if (job.lastFrame && (frame.epoch !== job.lastFrame.epoch || frame.timestamp <= job.lastFrame.timestamp)) {
|
||||
throw fail('INPUT_RENDERER_CHANGED', 'Renderer reloaded or its frame clock stopped advancing.');
|
||||
}
|
||||
await bounded(job, () => resolveImagePoints(options, pixels));
|
||||
if (job.gameView) {
|
||||
const preview = await bounded(job, () => controlPreviewToolbar({ action: 'state' }));
|
||||
if (!preview.running || preview.paused || !preview.toolbarSynchronized) throw fail('INPUT_PREVIEW_INTERRUPTED', 'Game View stopped, paused or changed state.');
|
||||
}
|
||||
job.lastFrame = frame;
|
||||
job.frameCount++;
|
||||
const evidence = { phase: job.phase, rendererTime: frame.timestamp, focused: frame.focused === true, windowFocused,
|
||||
elapsedMs: Math.round(performance.now() - job.createdAt), ...job.lastPoint };
|
||||
if (job.samples.length >= MAX_SAMPLES) {
|
||||
// Keep each phase's first/last witness even during long movements.
|
||||
const index = job.samples.findIndex((item, i, all) => i > 0 && i < all.length - 1
|
||||
&& item.phase === all[i - 1].phase && item.phase === all[i + 1].phase);
|
||||
job.samples.splice(index < 0 ? 1 : index, 1);
|
||||
}
|
||||
job.samples.push(evidence);
|
||||
return frame;
|
||||
};
|
||||
const hold = async (ms, frames = 2) => {
|
||||
const began = performance.now();
|
||||
let count = 0;
|
||||
do { await sample(); count++; } while (count < frames || performance.now() - began < ms);
|
||||
};
|
||||
try {
|
||||
job.window = getCaptureWindow(options);
|
||||
job.releaseLock = acquireInputWindow(job.window);
|
||||
await bounded(job, () => resolveImagePoints(options, pixels));
|
||||
if (typeof job.window.focus === 'function') job.window.focus();
|
||||
// A native Game View can own keyboard focus inside the same window.
|
||||
// Focus the exact captured host once before input, never on later frames.
|
||||
if (typeof job.window.webContents.focus === 'function') job.window.webContents.focus();
|
||||
const resolved = await bounded(job, () => resolveImagePoints(options, pixels));
|
||||
const [start, end] = resolved.points;
|
||||
job.lastPoint = start;
|
||||
const url = typeof job.window.webContents.getURL === 'function' ? job.window.webContents.getURL() : '';
|
||||
job.gameView = resolved.panel === 'game' && /\/windows\/main\.html(?:[?#]|$)/i.test(url);
|
||||
job.phase = 'preflight';
|
||||
await sample(); // No input before frame, focus, geometry and preview checks pass.
|
||||
submit('mouseMove', start);
|
||||
submit('mouseDown', start);
|
||||
job.phase = 'pressed';
|
||||
await hold(options.pressHoldMs);
|
||||
job.phase = 'moving';
|
||||
const began = performance.now();
|
||||
let fraction;
|
||||
do {
|
||||
await sample();
|
||||
fraction = Math.min(1, (performance.now() - began) / options.durationMs);
|
||||
submit('mouseMove', { x: Math.round(start.x + (end.x - start.x) * fraction), y: Math.round(start.y + (end.y - start.y) * fraction) });
|
||||
} while (fraction < 1);
|
||||
job.phase = 'target-hold';
|
||||
await hold(options.endHoldMs);
|
||||
submit('mouseUp', end);
|
||||
job.phase = 'released';
|
||||
await hold(0);
|
||||
job.status = 'completed';
|
||||
} catch (error) {
|
||||
job.status = job.abort.signal.aborted ? 'cancelled' : 'failed';
|
||||
job.error = { code: error.code || 'INPUT_OUTCOME_UNKNOWN', message: error.message };
|
||||
} finally {
|
||||
await cleanup(job);
|
||||
if (job.cleanup === 'failed') {
|
||||
job.status = 'failed';
|
||||
job.error = { code: 'INPUT_CLEANUP_FAILED', message: 'Release could not be submitted. Cancel this job to retry cleanup; its window stays locked.' };
|
||||
}
|
||||
job.finishedAt = performance.now();
|
||||
}
|
||||
}
|
||||
|
||||
async function waitReceipt(job, waitMs) {
|
||||
let timer;
|
||||
try {
|
||||
if (job.status === 'running' && waitMs > 0) await Promise.race([job.done, new Promise((resolve) => { timer = setTimeout(resolve, waitMs); })]);
|
||||
return snapshot(job);
|
||||
} finally { clearTimeout(timer); }
|
||||
}
|
||||
|
||||
async function frameDrag(options, nativeMouseEvent) {
|
||||
const owner = ownerKey(options);
|
||||
const action = options.action || 'start';
|
||||
if (!['start', 'status', 'cancel'].includes(action)) throw fail('INVALID_INPUT_ACTION', 'Use start, status or cancel.');
|
||||
let job;
|
||||
if (options.jobId !== undefined) job = jobs.get(options.jobId);
|
||||
else if (options.requestKey) job = [...jobs.values()].find((item) => item.owner === owner && item.requestKey === options.requestKey);
|
||||
if (job && job.owner !== owner) throw fail('INPUT_OWNER_MISMATCH', 'This receipt belongs to another project, Editor session or originating tool.');
|
||||
if (action !== 'start') {
|
||||
if (!job) throw fail('INPUT_RECEIPT_NOT_FOUND', 'Receipt expired or belongs to another input tool/project. Do not replay a lost gesture.');
|
||||
if (action === 'cancel') {
|
||||
job.abort.abort();
|
||||
await job.done;
|
||||
if (job.cleanup === 'failed') await cleanup(job);
|
||||
if (job.cleanup === 'failed') {
|
||||
const error = fail('INPUT_CLEANUP_FAILED', 'Release still could not be submitted. The owned window remains locked.');
|
||||
error.inputOutcome = { ...snapshot(job), retrySafe: false };
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
return snapshot(job);
|
||||
}
|
||||
if (options.jobId !== undefined) throw fail('INVALID_INPUT_ACTION', 'Use status or cancel with a jobId.');
|
||||
if (options.coordinateSpace !== 'image-pixels' || typeof options.captureId !== 'string' || !options.captureId || options.captureId.length > 128) throw fail('INPUT_CAPTURE_REQUIRED', 'Frame-paced dragging requires a fresh calibrated screenshot and image-pixels coordinates. Legacy coordinates remain available with legacy timing.');
|
||||
if (typeof options.requestKey !== 'string' || !/^[A-Za-z0-9_.:-]{1,128}$/.test(options.requestKey)) throw fail('INPUT_REQUEST_KEY_REQUIRED', 'Provide a unique requestKey (1..128 ASCII letters, digits, dot, colon, underscore or hyphen).');
|
||||
if (options.steps !== undefined || options.stepDelayMs !== undefined) throw fail('INVALID_INPUT_TIMING', 'Frame-paced timing uses durationMs/pressHoldMs/endHoldMs, not legacy steps or stepDelayMs.');
|
||||
const normalized = { projectPath: options.projectPath, inputOwner: options.inputOwner, originatingTool: options.originatingTool,
|
||||
projectContext: options.projectContext || null,
|
||||
captureId: options.captureId, coordinateSpace: 'image-pixels', windowId: options.windowId,
|
||||
windowKind: options.windowKind, titleContains: options.titleContains, panel: options.panel,
|
||||
startX: options.startX, startY: options.startY, endX: options.endX, endY: options.endY,
|
||||
durationMs: numberOption(options, 'durationMs', 600, 50, 10000),
|
||||
pressHoldMs: numberOption(options, 'pressHoldMs', 100, 0, 2000), endHoldMs: numberOption(options, 'endHoldMs', 100, 0, 2000),
|
||||
button: options.button || 'left', modifiers: options.modifiers || [] };
|
||||
if (!['left', 'right', 'middle'].includes(normalized.button) || !Array.isArray(normalized.modifiers)
|
||||
|| normalized.modifiers.length > 16 || normalized.modifiers.some((item) => typeof item !== 'string' || item.length > 64)
|
||||
|| ['panel', 'titleContains', 'windowKind'].some((key) => options[key] !== undefined && (typeof options[key] !== 'string' || options[key].length > 200))) throw fail('INVALID_INPUT_ARGUMENTS', 'Invalid mouse button, modifiers or target description.');
|
||||
normalized.modifiers = normalized.modifiers.slice();
|
||||
normalized.projectContext = normalized.projectContext ? { ...normalized.projectContext } : null;
|
||||
if (![options.startX, options.startY, options.endX, options.endY].every(Number.isFinite)) throw fail('INVALID_INPUT_ARGUMENTS', 'Finite start/end image coordinates are required.');
|
||||
const waitMs = numberOption(options, 'waitMs', 1200, 0, 15000);
|
||||
const fingerprint = JSON.stringify([options.captureId, options.windowId, options.windowKind, options.titleContains, options.panel,
|
||||
options.startX, options.startY, options.endX, options.endY, normalized.button, normalized.modifiers, normalized.durationMs, normalized.pressHoldMs, normalized.endHoldMs]);
|
||||
if (job) {
|
||||
if (job.fingerprint !== fingerprint) throw fail('INPUT_REQUEST_KEY_CONFLICT', 'The same requestKey cannot name different gesture arguments.');
|
||||
} else {
|
||||
if (jobs.size >= MAX_RECEIPTS) {
|
||||
const retired = [...jobs.values()].find((item) => item.status !== 'running' && item.cleanup !== 'failed');
|
||||
if (!retired) throw fail('INPUT_RECEIPTS_BUSY', 'All retained receipts are active or need cleanup.');
|
||||
jobs.delete(retired.id);
|
||||
}
|
||||
const createdAt = performance.now();
|
||||
job = { id: `input_${crypto.randomBytes(12).toString('hex')}`, owner, requestKey: options.requestKey, fingerprint,
|
||||
options: normalized, status: 'running', phase: 'queued', createdAt,
|
||||
deadline: createdAt + normalized.durationMs + normalized.pressHoldMs + normalized.endHoldMs + 5000,
|
||||
events: 0, attempted: false, pressed: false, releaseSubmitted: false, cleanup: 'pending', samples: [], frameCount: 0,
|
||||
abort: new AbortController() };
|
||||
jobs.set(job.id, job);
|
||||
job.done = run(job, nativeMouseEvent);
|
||||
}
|
||||
const receipt = await waitReceipt(job, waitMs);
|
||||
if (receipt.status === 'failed' || receipt.status === 'cancelled') {
|
||||
const error = new Error(receipt.error && receipt.error.message || 'Gesture cancelled.');
|
||||
error.code = receipt.error && receipt.error.code || 'INPUT_CANCELLED';
|
||||
error.inputOutcome = { ...receipt, retrySafe: !job.attempted };
|
||||
throw error;
|
||||
}
|
||||
return receipt;
|
||||
}
|
||||
|
||||
async function cancelFrameDrags(owner) {
|
||||
const owned = [...jobs.values()].filter((job) => job.options.inputOwner === owner);
|
||||
for (const job of owned) job.abort.abort();
|
||||
await Promise.all(owned.map((job) => job.done));
|
||||
if (owned.some((job) => job.cleanup === 'failed')) throw fail('INPUT_CLEANUP_FAILED', 'An owned input job still needs release cleanup.');
|
||||
}
|
||||
|
||||
module.exports = { frameDrag, cancelFrameDrags, nextRendererFrame, MAX_RECEIPTS };
|
||||
+287
@@ -0,0 +1,287 @@
|
||||
'use strict';
|
||||
|
||||
const electronTools = require('./electron-tools');
|
||||
const { acquireInputWindow, getCaptureWindow, resolveImagePoints } = require('./visual-coordinates');
|
||||
const { frameDrag, cancelFrameDrags: cancelFrameJobs } = require('./input-frames');
|
||||
|
||||
// Keep ownership while a release is uncertain. Stop/restart retries only the
|
||||
// owned release; it must never replay the original press or gesture.
|
||||
const mouseGestures = new Set();
|
||||
|
||||
function normalizeButton(button) {
|
||||
const value = String(button || 'left').toLowerCase();
|
||||
return ['left', 'right', 'middle'].includes(value) ? value : 'left';
|
||||
}
|
||||
|
||||
function normalizeModifiers(modifiers) {
|
||||
return Array.isArray(modifiers) ? modifiers.map((item) => String(item)) : [];
|
||||
}
|
||||
|
||||
function nativeMouseEvent(window, event, held) {
|
||||
// Blink does not infer the pressed-button flags from `button`. Keep keyboard
|
||||
// modifiers, but derive mouse state from this gesture (including mouseUp's
|
||||
// changed button so Creator receives the correct `which` value).
|
||||
const modifiers = event.modifiers.filter((value) => !/^(left|middle|right)buttondown$/i.test(value));
|
||||
if (held) modifiers.push(`${event.button}buttondown`);
|
||||
const result = { ...event, modifiers };
|
||||
// Creator's Game View filters/forwards movement using screen coordinates.
|
||||
// Electron otherwise defaults these to (0, 0), dropping drag movement even
|
||||
// when the local client coordinates and button flags are correct.
|
||||
if (typeof window.getContentBounds === 'function') {
|
||||
const bounds = window.getContentBounds();
|
||||
if (!bounds || !Number.isFinite(bounds.x) || !Number.isFinite(bounds.y)) {
|
||||
throw new Error('The target window has unavailable screen bounds.');
|
||||
}
|
||||
result.globalX = Math.round(bounds.x + event.x);
|
||||
result.globalY = Math.round(bounds.y + event.y);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
async function focusTarget(window, panel, x, y) {
|
||||
if (typeof window.focus === 'function') {
|
||||
window.focus();
|
||||
}
|
||||
if (panel) {
|
||||
return await electronTools.getPanelPoint(window, panel, x, y);
|
||||
}
|
||||
return { x: Math.floor(x || 0), y: Math.floor(y || 0) };
|
||||
}
|
||||
|
||||
async function resolvePoint(window, panel, x, y) {
|
||||
if (panel) {
|
||||
return await electronTools.getPanelPoint(window, panel, x, y);
|
||||
}
|
||||
return { x: Math.floor(x || 0), y: Math.floor(y || 0) };
|
||||
}
|
||||
|
||||
function mouseGesture(window, options) {
|
||||
const gesture = {
|
||||
window, inputOwner: options.inputOwner || '', releaseLock: acquireInputWindow(window),
|
||||
button: normalizeButton(options.button), modifiers: normalizeModifiers(options.modifiers),
|
||||
attempted: false, pressed: false, eventsSubmitted: 0, releaseSubmitted: false, cancelled: false,
|
||||
};
|
||||
mouseGestures.add(gesture);
|
||||
return gesture;
|
||||
}
|
||||
|
||||
function submitMouse(gesture, event) {
|
||||
if (gesture.cancelled) throw new Error('INPUT_CANCELLED: Gesture cancelled during MCP shutdown.');
|
||||
const nativeEvent = nativeMouseEvent(gesture.window, event, event.type !== 'mouseMove' || gesture.pressed);
|
||||
gesture.attempted = true;
|
||||
gesture.lastPoint = { x: event.x, y: event.y };
|
||||
// Dispatch can throw after delivery; ownership starts before the attempt.
|
||||
if (event.type === 'mouseDown') gesture.pressed = true;
|
||||
gesture.window.webContents.sendInputEvent(nativeEvent);
|
||||
gesture.eventsSubmitted++;
|
||||
if (event.type === 'mouseUp') {
|
||||
gesture.pressed = false;
|
||||
gesture.releaseSubmitted = true;
|
||||
}
|
||||
}
|
||||
|
||||
function unlockMouse(gesture) {
|
||||
if (!gesture || gesture.pressed) return;
|
||||
if (gesture.releaseLock) { gesture.releaseLock(); gesture.releaseLock = null; }
|
||||
mouseGestures.delete(gesture);
|
||||
}
|
||||
|
||||
function releaseMouse(gesture) {
|
||||
if (gesture.pressed) {
|
||||
const window = gesture.window;
|
||||
if (!window.isDestroyed || !window.isDestroyed()) {
|
||||
window.webContents.sendInputEvent(nativeMouseEvent(window, {
|
||||
type: 'mouseUp', ...gesture.lastPoint, button: gesture.button, clickCount: 1, modifiers: gesture.modifiers,
|
||||
}, true));
|
||||
gesture.releaseSubmitted = true;
|
||||
}
|
||||
gesture.pressed = false;
|
||||
}
|
||||
unlockMouse(gesture);
|
||||
}
|
||||
|
||||
function mouseFailure(error, gesture) {
|
||||
if (gesture) {
|
||||
try { releaseMouse(gesture); } catch (cleanupError) { /* Retain the window lock until owned cleanup succeeds. */ }
|
||||
}
|
||||
const attempted = Boolean(gesture && gesture.attempted);
|
||||
const locked = Boolean(gesture && gesture.pressed);
|
||||
error.inputOutcome = {
|
||||
code: attempted ? 'INPUT_OUTCOME_UNKNOWN' : 'INPUT_NOT_SENT',
|
||||
inputSent: attempted ? null : false,
|
||||
eventsSubmitted: gesture ? gesture.eventsSubmitted : 0,
|
||||
releaseSubmitted: Boolean(gesture && gesture.releaseSubmitted),
|
||||
cleanup: locked ? 'failed' : 'complete', windowLocked: locked,
|
||||
retrySafe: !attempted, businessOutcomeVerified: false,
|
||||
};
|
||||
if (locked) error.message += ' Release could not be submitted; the window stays locked. Stop/restart MCP to retry owned cleanup.';
|
||||
return error;
|
||||
}
|
||||
|
||||
async function sendMouseClick(options = {}) {
|
||||
if (calibratedInput(options)) return await sendCalibratedMouse(options, false);
|
||||
return await sendLegacyMouse(options, false);
|
||||
}
|
||||
|
||||
async function sendMouseDrag(options = {}) {
|
||||
if (options.timing === 'frame-paced' || options.action !== undefined) return await frameDrag(options, nativeMouseEvent);
|
||||
if (options.timing !== undefined && options.timing !== 'legacy') throw new Error('timing must be legacy or frame-paced.');
|
||||
if (calibratedInput(options)) return await sendCalibratedMouse(options, true);
|
||||
return await sendLegacyMouse(options, true);
|
||||
}
|
||||
|
||||
async function sendLegacyMouse(options, drag) {
|
||||
let gesture;
|
||||
try {
|
||||
const window = electronTools.pickWindow(options);
|
||||
gesture = mouseGesture(window, options);
|
||||
const start = await focusTarget(window, options.panel, drag ? options.startX : options.x, drag ? options.startY : options.y);
|
||||
const end = drag ? await resolvePoint(window, options.panel, options.endX ?? 0, options.endY ?? 0) : start;
|
||||
const steps = Number.isFinite(options.steps) ? Math.max(1, Math.min(60, options.steps)) : 10;
|
||||
const clickCount = drag ? 1 : Number.isFinite(options.clickCount) ? Math.max(1, options.clickCount) : 1;
|
||||
const { button, modifiers } = gesture;
|
||||
submitMouse(gesture, { type: 'mouseMove', ...start, button, modifiers });
|
||||
submitMouse(gesture, { type: 'mouseDown', ...start, button, clickCount, modifiers });
|
||||
if (drag) {
|
||||
for (let step = 1; step <= steps; step += 1) {
|
||||
const x = Math.round(start.x + ((end.x - start.x) * step) / steps);
|
||||
const y = Math.round(start.y + ((end.y - start.y) * step) / steps);
|
||||
submitMouse(gesture, { type: 'mouseMove', x, y, button, modifiers });
|
||||
if (options.stepDelayMs) await electronTools.sleep(options.stepDelayMs);
|
||||
}
|
||||
}
|
||||
submitMouse(gesture, { type: 'mouseUp', ...end, button, clickCount, modifiers });
|
||||
return {
|
||||
sent: true, type: drag ? 'mouse_drag' : 'mouse_click',
|
||||
...(drag ? { from: start, to: end, steps } : { point: start, button, clickCount }),
|
||||
windowTitle: typeof window.getTitle === 'function' ? window.getTitle() : '',
|
||||
};
|
||||
} catch (error) {
|
||||
throw mouseFailure(error, gesture);
|
||||
} finally { unlockMouse(gesture); }
|
||||
}
|
||||
|
||||
async function sendKeyPress(options = {}) {
|
||||
if (options.coordinateSpace === 'image-pixels' || options.captureId) throw new Error('Screenshot calibration applies to mouse input, not key input.');
|
||||
const window = electronTools.pickWindow(options);
|
||||
if (typeof window.focus === 'function') {
|
||||
window.focus();
|
||||
}
|
||||
if (options.panel) {
|
||||
await electronTools.getPanelPoint(window, options.panel, 0, 0);
|
||||
}
|
||||
|
||||
const keyCode = String(options.keyCode || '').trim();
|
||||
if (!keyCode) {
|
||||
throw new Error('keyCode is required.');
|
||||
}
|
||||
|
||||
const modifiers = normalizeModifiers(options.modifiers);
|
||||
window.webContents.sendInputEvent({ type: 'keyDown', keyCode, modifiers });
|
||||
if (options.text) {
|
||||
window.webContents.sendInputEvent({ type: 'char', keyCode: String(options.text), modifiers });
|
||||
}
|
||||
window.webContents.sendInputEvent({ type: 'keyUp', keyCode, modifiers });
|
||||
|
||||
return {
|
||||
sent: true,
|
||||
type: 'key_press',
|
||||
keyCode,
|
||||
modifiers,
|
||||
windowTitle: typeof window.getTitle === 'function' ? window.getTitle() : '',
|
||||
};
|
||||
}
|
||||
|
||||
async function sendKeyCombo(options = {}) {
|
||||
const modifiers = normalizeModifiers(options.modifiers);
|
||||
const keyCode = String(options.keyCode || '').trim();
|
||||
if (!keyCode) {
|
||||
throw new Error('keyCode is required.');
|
||||
}
|
||||
return await sendKeyPress({
|
||||
...options,
|
||||
keyCode,
|
||||
modifiers,
|
||||
});
|
||||
}
|
||||
|
||||
function calibratedInput(options) {
|
||||
const space = options.coordinateSpace || 'legacy';
|
||||
if (!['legacy', 'image-pixels'].includes(space)) throw new Error('coordinateSpace must be legacy or image-pixels.');
|
||||
if (space === 'legacy' && options.captureId) throw new Error('captureId requires coordinateSpace="image-pixels"; legacy offsets are not screenshot pixels.');
|
||||
return space === 'image-pixels';
|
||||
}
|
||||
|
||||
async function sendCalibratedMouse(options, drag) {
|
||||
let window;
|
||||
let gesture;
|
||||
const button = normalizeButton(options.button);
|
||||
const modifiers = normalizeModifiers(options.modifiers);
|
||||
const submit = (event) => submitMouse(gesture, event);
|
||||
try {
|
||||
const steps = options.steps === undefined ? 10 : options.steps;
|
||||
const delay = options.stepDelayMs === undefined ? 0 : options.stepDelayMs;
|
||||
const clickCount = options.clickCount === undefined ? 1 : options.clickCount;
|
||||
if (!Number.isInteger(steps) || steps < 1 || steps > 60 || !Number.isInteger(delay) || delay < 0 || delay > 100 ||
|
||||
!Number.isInteger(clickCount) || clickCount < 1 || clickCount > 3) {
|
||||
throw new Error('Calibrated input requires steps 1..60, stepDelayMs 0..100, and clickCount 1..3.');
|
||||
}
|
||||
const pixels = drag ? [{ x: options.startX, y: options.startY }, { x: options.endX, y: options.endY }]
|
||||
: [{ x: options.x, y: options.y }];
|
||||
window = getCaptureWindow(options);
|
||||
gesture = mouseGesture(window, options);
|
||||
await resolveImagePoints(options, pixels); // Validate before moving focus.
|
||||
if (typeof window.focus === 'function') window.focus();
|
||||
const resolved = await resolveImagePoints(options, pixels); // Focus can resize/change the viewport.
|
||||
const start = resolved.points[0];
|
||||
const end = drag ? resolved.points[1] : start;
|
||||
submit({ type: 'mouseMove', ...start, button, modifiers });
|
||||
submit({ type: 'mouseDown', ...start, button, clickCount, modifiers });
|
||||
if (drag) {
|
||||
for (let step = 1; step <= steps; step += 1) {
|
||||
if (delay) {
|
||||
await electronTools.sleep(delay);
|
||||
await resolveImagePoints(options, pixels);
|
||||
}
|
||||
submit({ type: 'mouseMove', x: Math.round(start.x + (end.x - start.x) * step / steps),
|
||||
y: Math.round(start.y + (end.y - start.y) * step / steps), button, modifiers });
|
||||
}
|
||||
}
|
||||
submit({ type: 'mouseUp', ...end, button, clickCount, modifiers });
|
||||
return {
|
||||
sent: true, inputSent: true, outcome: 'events_submitted',
|
||||
type: drag ? 'mouse_drag' : 'mouse_click', captureId: resolved.captureId, coordinateSpace: 'image-pixels',
|
||||
...(drag ? { from: start, to: end, steps } : { point: start, clickCount }),
|
||||
button, eventsSubmitted: gesture.eventsSubmitted,
|
||||
windowId: window.id, windowTitle: typeof window.getTitle === 'function' ? window.getTitle() : '',
|
||||
businessOutcomeVerified: false,
|
||||
};
|
||||
} catch (error) {
|
||||
throw mouseFailure(error, gesture);
|
||||
} finally {
|
||||
unlockMouse(gesture);
|
||||
}
|
||||
}
|
||||
|
||||
async function cancelFrameDrags(owner) {
|
||||
let failure;
|
||||
try { await cancelFrameJobs(owner); } catch (error) { failure = error; }
|
||||
for (const gesture of [...mouseGestures]) {
|
||||
if (gesture.inputOwner !== owner) continue;
|
||||
gesture.cancelled = true;
|
||||
try { releaseMouse(gesture); } catch (error) {
|
||||
failure = new Error('INPUT_CLEANUP_FAILED: Release could not be submitted. The owned window stays locked; retry MCP stop/restart to clean up.');
|
||||
failure.code = 'INPUT_CLEANUP_FAILED';
|
||||
}
|
||||
}
|
||||
if (failure) throw failure;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
listWindows: electronTools.listWindows,
|
||||
sendKeyCombo,
|
||||
sendKeyPress,
|
||||
sendMouseClick,
|
||||
sendMouseDrag,
|
||||
cancelFrameDrags,
|
||||
};
|
||||
@@ -0,0 +1,59 @@
|
||||
'use strict';
|
||||
|
||||
const { createActivityPreview, sanitizeActivityText } = require('./activity-preview');
|
||||
|
||||
class InteractionLog {
|
||||
constructor(limit = 200) {
|
||||
this.limit = limit;
|
||||
this.entries = [];
|
||||
}
|
||||
|
||||
add(toolName, status, summary, result, execution) {
|
||||
const preview = createActivityPreview(result);
|
||||
// Execution logs have their own bounded capture budget; do not run them
|
||||
// through the result array preview limit or silently turn them into a count.
|
||||
const script = execution && {
|
||||
context: execution.context,
|
||||
durationMs: execution.durationMs,
|
||||
logs: execution.logs.map((entry) => ({ level: entry.level, message: entry.message })),
|
||||
logsOmitted: execution.logsOmitted,
|
||||
};
|
||||
this.entries.unshift({
|
||||
toolName,
|
||||
status,
|
||||
summary: sanitizeActivityText(summary || '', 500),
|
||||
timestamp: new Date().toISOString(),
|
||||
...(preview === undefined ? {} : { preview }),
|
||||
...(script ? { execution: script } : {}),
|
||||
});
|
||||
|
||||
if (this.entries.length > this.limit) {
|
||||
this.entries.length = this.limit;
|
||||
}
|
||||
}
|
||||
|
||||
list(limit = 20) {
|
||||
return this.entries.slice(0, Math.max(1, limit));
|
||||
}
|
||||
|
||||
clear() {
|
||||
const count = this.entries.length;
|
||||
this.entries.length = 0;
|
||||
return count;
|
||||
}
|
||||
|
||||
summary(limit = 20) {
|
||||
const items = this.list(limit);
|
||||
if (!items.length) {
|
||||
return 'No MCP interactions recorded yet.';
|
||||
}
|
||||
|
||||
return items
|
||||
.map((entry) => `[${entry.timestamp}] ${entry.status.toUpperCase()} ${entry.toolName}: ${entry.summary}`)
|
||||
.join('\n');
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
InteractionLog,
|
||||
};
|
||||
@@ -0,0 +1,114 @@
|
||||
'use strict';
|
||||
|
||||
const path = require('path');
|
||||
const { isPathInside } = require('./path-safety');
|
||||
|
||||
const DELETE_METHOD_PATTERN = /\bfs(?:\s*\.\s*promises)?\s*\.\s*(rm|rmdir|unlink|truncate|rmSync|rmdirSync|unlinkSync|truncateSync)\s*\(/;
|
||||
const WRITE_STREAM_PATTERN = /\bfs\s*\.\s*(createWriteStream|openSync)\s*\(/;
|
||||
const SHELL_PATTERN = /require\s*\(\s*['"]child_process['"]\s*\)|\bchild_process\s*\.|\b(exec|execFile|spawn|fork|execSync|execFileSync|spawnSync)\s*\(/;
|
||||
const WRITE_METHOD_PATTERN = /\bfs(?:\s*\.\s*promises)?\s*\.\s*(writeFile|appendFile|copyFile|cp|rename|mkdir|writeFileSync|appendFileSync|copyFileSync|cpSync|renameSync|mkdirSync)\s*\(/;
|
||||
const HOME_PATH_PATTERN = /(?:^~(?:\/|\\|$)|\$HOME|%USERPROFILE%|%HOMEPATH%)/i;
|
||||
const TRAVERSAL_PATTERN = /(^|[\\/])\.\.([\\/]|$)/;
|
||||
|
||||
function extractStringLiterals(code) {
|
||||
const literals = [];
|
||||
const pattern = /(['"`])((?:\\[\s\S]|(?!\1)[\s\S])*?)\1/g;
|
||||
let match;
|
||||
while ((match = pattern.exec(String(code || '')))) {
|
||||
literals.push(match[2]);
|
||||
}
|
||||
return literals;
|
||||
}
|
||||
|
||||
function isAbsoluteLiteral(value) {
|
||||
return path.isAbsolute(value)
|
||||
|| path.win32.isAbsolute(value)
|
||||
|| /^\\\\/.test(value);
|
||||
}
|
||||
|
||||
function isAbsoluteLiteralInsideProject(projectPath, value) {
|
||||
if (!projectPath) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (path.win32.isAbsolute(value)) {
|
||||
const root = projectPath.replace(/\//g, '\\');
|
||||
const relative = path.win32.relative(root, value);
|
||||
return relative === '' || (relative && !relative.startsWith('..') && !path.win32.isAbsolute(relative));
|
||||
}
|
||||
|
||||
if (path.isAbsolute(value)) {
|
||||
return isPathInside(projectPath, path.resolve(value));
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
function inspectJavascriptSafety(code, options = {}) {
|
||||
const source = String(code || '');
|
||||
const projectPath = options.projectPath ? path.resolve(String(options.projectPath)) : '';
|
||||
const violations = [];
|
||||
|
||||
if (DELETE_METHOD_PATTERN.test(source)) {
|
||||
violations.push('direct fs delete/truncate calls are blocked by default');
|
||||
}
|
||||
|
||||
if (WRITE_STREAM_PATTERN.test(source)) {
|
||||
violations.push('raw writable file streams are blocked by default');
|
||||
}
|
||||
|
||||
if (SHELL_PATTERN.test(source)) {
|
||||
violations.push('child_process execution is blocked by default');
|
||||
}
|
||||
|
||||
const hasFileMutation = DELETE_METHOD_PATTERN.test(source)
|
||||
|| WRITE_METHOD_PATTERN.test(source)
|
||||
|| WRITE_STREAM_PATTERN.test(source);
|
||||
if (hasFileMutation && /\bos\s*\.\s*homedir\s*\(/.test(source)) {
|
||||
violations.push('file mutations derived from os.homedir() are blocked by default');
|
||||
}
|
||||
if (hasFileMutation && /\bprocess\s*\.\s*env\s*\.\s*(HOME|USERPROFILE|HOMEPATH|APPDATA|LOCALAPPDATA|TMP|TEMP)\b/.test(source)) {
|
||||
violations.push('file mutations derived from user/system environment paths are blocked by default');
|
||||
}
|
||||
|
||||
for (const literal of extractStringLiterals(source)) {
|
||||
if (HOME_PATH_PATTERN.test(literal)) {
|
||||
violations.push(`user-home path literal is blocked: ${literal}`);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (TRAVERSAL_PATTERN.test(literal)) {
|
||||
violations.push(`path traversal literal is blocked: ${literal}`);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (isAbsoluteLiteral(literal)) {
|
||||
if (!isAbsoluteLiteralInsideProject(projectPath, literal)) {
|
||||
violations.push(`absolute path outside the Cocos project is blocked: ${literal}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
ok: violations.length === 0,
|
||||
violations: Array.from(new Set(violations)),
|
||||
};
|
||||
}
|
||||
|
||||
function assertJavascriptSafety(code, options = {}) {
|
||||
const result = inspectJavascriptSafety(code, options);
|
||||
if (result.ok) {
|
||||
return result;
|
||||
}
|
||||
|
||||
throw new Error(
|
||||
'JavaScript safety checks blocked this code: ' +
|
||||
`${result.violations.join('; ')}. ` +
|
||||
'Use project-relative helper/file tools, or pass safety_checks=false only after reviewing the risk.'
|
||||
);
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
assertJavascriptSafety,
|
||||
inspectJavascriptSafety,
|
||||
};
|
||||
+148
@@ -0,0 +1,148 @@
|
||||
'use strict';
|
||||
|
||||
const { isDeepStrictEqual } = require('util');
|
||||
|
||||
// Keep source ranges so config edits do not discard comments or reformat
|
||||
// unrelated settings. No runtime dependency is needed in the Cocos ZIP.
|
||||
function parseDocument(source) {
|
||||
let offset = source.charCodeAt(0) === 0xFEFF ? 1 : 0;
|
||||
const fail = (message) => { throw new SyntaxError(`Invalid JSONC at offset ${offset}: ${message}. File was left unchanged.`); };
|
||||
function trivia() {
|
||||
while (offset < source.length) {
|
||||
if (/[ \t\r\n]/.test(source[offset])) { offset += 1; continue; }
|
||||
if (source.startsWith('//', offset)) {
|
||||
offset += 2;
|
||||
while (offset < source.length && !/[\r\n]/.test(source[offset])) offset += 1;
|
||||
} else if (source.startsWith('/*', offset)) {
|
||||
const end = source.indexOf('*/', offset + 2);
|
||||
if (end < 0) fail('unterminated comment');
|
||||
offset = end + 2;
|
||||
} else break;
|
||||
}
|
||||
}
|
||||
function string() {
|
||||
const start = offset++;
|
||||
while (offset < source.length) {
|
||||
const character = source[offset++];
|
||||
if (character === '"') {
|
||||
try { return { start, end: offset, value: JSON.parse(source.slice(start, offset)) }; }
|
||||
catch (error) { fail('invalid string'); }
|
||||
}
|
||||
if (character === '\\') offset += 1;
|
||||
}
|
||||
fail('unterminated string');
|
||||
}
|
||||
function value(depth = 0) {
|
||||
if (depth > 128) fail('configuration nesting is too deep');
|
||||
trivia();
|
||||
const start = offset;
|
||||
const character = source[offset];
|
||||
if (character === '"') return string();
|
||||
if (character !== '{' && character !== '[') {
|
||||
const literal = /^(?:true|false|null|-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?)/.exec(source.slice(offset));
|
||||
if (!literal) fail('expected a JSON value');
|
||||
offset += literal[0].length;
|
||||
return { start, end: offset, value: JSON.parse(literal[0]) };
|
||||
}
|
||||
const object = character === '{';
|
||||
const closing = object ? '}' : ']';
|
||||
const result = object ? {} : [];
|
||||
const properties = [];
|
||||
offset += 1;
|
||||
trivia();
|
||||
while (source[offset] !== closing) {
|
||||
let key;
|
||||
if (object) {
|
||||
if (source[offset] !== '"') fail('expected an object key');
|
||||
key = string();
|
||||
if (Object.prototype.hasOwnProperty.call(result, key.value)) fail('duplicate object key');
|
||||
trivia();
|
||||
if (source[offset++] !== ':') fail('expected a colon');
|
||||
}
|
||||
const child = value(depth + 1);
|
||||
const property = object ? { key: key.value, start: key.start, node: child, comma: null } : null;
|
||||
if (object) {
|
||||
// Treat __proto__ like a normal JSON key, never as a prototype setter.
|
||||
Object.defineProperty(result, key.value, { value: child.value, enumerable: true, writable: true, configurable: true });
|
||||
properties.push(property);
|
||||
} else result.push(child.value);
|
||||
trivia();
|
||||
if (source[offset] === closing) break;
|
||||
if (source[offset] !== ',') fail('expected a comma or closing delimiter');
|
||||
if (property) property.comma = offset;
|
||||
offset += 1;
|
||||
trivia(); // A single trailing comma is allowed, but not holes or doubled commas.
|
||||
}
|
||||
offset += 1;
|
||||
return { start, end: offset, value: result, properties: object ? properties : undefined };
|
||||
}
|
||||
trivia();
|
||||
if (offset === source.length) return null;
|
||||
const root = value();
|
||||
trivia();
|
||||
if (offset !== source.length) fail('unexpected content after the root value');
|
||||
return root;
|
||||
}
|
||||
|
||||
function parseJsonc(source) {
|
||||
const document = parseDocument(source);
|
||||
return document ? document.value : {};
|
||||
}
|
||||
|
||||
function updateJsonc(source, desired) {
|
||||
const root = parseDocument(source);
|
||||
const newline = source.includes('\r\n') ? '\r\n' : '\n';
|
||||
const indent = (/\r?\n([ \t]+)"/.exec(source) || [null, ' '])[1];
|
||||
const lineIndent = (position) => /^[ \t]*/.exec(source.slice(source.lastIndexOf('\n', position - 1) + 1))[0];
|
||||
const serialize = (value, prefix) => JSON.stringify(value, null, indent).replace(/\n/g, newline + prefix);
|
||||
if (!root) {
|
||||
const separator = source && !/[\r\n]$/.test(source) ? newline : '';
|
||||
return source + separator + serialize(desired, '') + newline;
|
||||
}
|
||||
const edits = [];
|
||||
const edit = (start, end, text) => edits.push({ start, end, text, order: edits.length });
|
||||
function visit(node, next) {
|
||||
if (isDeepStrictEqual(node.value, next)) return;
|
||||
if (!node.properties || !next || typeof next !== 'object' || Array.isArray(next)) {
|
||||
edit(node.start, node.end, serialize(next, lineIndent(node.start)));
|
||||
return;
|
||||
}
|
||||
const retained = [];
|
||||
const existing = new Set();
|
||||
for (const property of node.properties) {
|
||||
existing.add(property.key);
|
||||
if (Object.prototype.hasOwnProperty.call(next, property.key)) {
|
||||
retained.push(property);
|
||||
visit(property.node, next[property.key]);
|
||||
} else {
|
||||
edit(property.start, property.node.end, '');
|
||||
// Leave surrounding comments intact. A previous separator may become
|
||||
// a valid trailing comma when removing the final property.
|
||||
if (property.comma !== null) edit(property.comma, property.comma + 1, '');
|
||||
}
|
||||
}
|
||||
const added = Object.keys(next).filter((key) => !existing.has(key));
|
||||
if (!added.length) return;
|
||||
const last = retained[retained.length - 1];
|
||||
if (last && last.comma === null) edit(last.node.end, last.node.end, ',');
|
||||
const base = lineIndent(node.start);
|
||||
const prefix = base + indent;
|
||||
const closing = node.end - 1;
|
||||
const closingLine = source.lastIndexOf('\n', closing - 1) + 1;
|
||||
const onOwnLine = /^[ \t]*$/.test(source.slice(closingLine, closing));
|
||||
const trailingComma = node.properties.length && node.properties[node.properties.length - 1].comma !== null;
|
||||
const fields = added.map((key) => `${prefix}${JSON.stringify(key)}: ${serialize(next[key], prefix)}`).join(',' + newline);
|
||||
const text = (onOwnLine ? '' : newline) + fields + (trailingComma ? ',' : '') + newline + (onOwnLine ? '' : base);
|
||||
edit(onOwnLine ? closingLine : closing, onOwnLine ? closingLine : closing, text);
|
||||
}
|
||||
visit(root, desired);
|
||||
let result = source;
|
||||
for (const change of edits.sort((a, b) => b.start - a.start || b.end - a.end || b.order - a.order)) {
|
||||
result = result.slice(0, change.start) + change.text + result.slice(change.end);
|
||||
}
|
||||
// Fail closed before the caller performs its atomic write.
|
||||
if (!isDeepStrictEqual(parseJsonc(result), desired)) throw new Error('JSONC edit could not be verified; the file was left unchanged.');
|
||||
return result;
|
||||
}
|
||||
|
||||
module.exports = { parseJsonc, updateJsonc };
|
||||
+206
@@ -0,0 +1,206 @@
|
||||
'use strict';
|
||||
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const { resolveProjectPath } = require('./path-safety');
|
||||
|
||||
const DEFAULT_LOG_DIRS = [
|
||||
'temp/logs',
|
||||
'temp',
|
||||
'logs',
|
||||
'local/logs',
|
||||
'local',
|
||||
];
|
||||
const LOG_EXTENSIONS = new Set(['.log', '.txt']);
|
||||
const MAX_READ_BYTES = 2 * 1024 * 1024;
|
||||
|
||||
function normalizeLimit(value, fallback, min, max) {
|
||||
const number = Number(value);
|
||||
if (!Number.isFinite(number)) {
|
||||
return fallback;
|
||||
}
|
||||
return Math.max(min, Math.min(max, Math.floor(number)));
|
||||
}
|
||||
|
||||
function shouldSkipDirectory(name) {
|
||||
return name === '.git' || name === 'node_modules' || name === 'library';
|
||||
}
|
||||
|
||||
function isLogFile(fileName) {
|
||||
return LOG_EXTENSIONS.has(path.extname(fileName).toLowerCase());
|
||||
}
|
||||
|
||||
function safeStat(filePath) {
|
||||
try {
|
||||
return fs.statSync(filePath);
|
||||
} catch (error) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function collectLogFiles(rootDir, maxDepth, limit) {
|
||||
const files = [];
|
||||
const stack = [{ dir: rootDir, depth: 0 }];
|
||||
|
||||
while (stack.length && files.length < limit) {
|
||||
const current = stack.pop();
|
||||
let entries;
|
||||
try {
|
||||
entries = fs.readdirSync(current.dir, { withFileTypes: true });
|
||||
} catch (error) {
|
||||
continue;
|
||||
}
|
||||
|
||||
for (const entry of entries) {
|
||||
const fullPath = path.join(current.dir, entry.name);
|
||||
if (entry.isDirectory()) {
|
||||
if (current.depth < maxDepth && !shouldSkipDirectory(entry.name)) {
|
||||
stack.push({ dir: fullPath, depth: current.depth + 1 });
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!entry.isFile() || !isLogFile(entry.name)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const stat = safeStat(fullPath);
|
||||
if (stat) {
|
||||
files.push({ fullPath, size: stat.size, mtimeMs: stat.mtimeMs });
|
||||
}
|
||||
if (files.length >= limit) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return files;
|
||||
}
|
||||
|
||||
function findProjectLogFiles(projectPath, options = {}) {
|
||||
const limit = normalizeLimit(options.limit, 20, 1, 200);
|
||||
const maxDepth = normalizeLimit(options.maxDepth, 2, 0, 5);
|
||||
const directories = options.directory
|
||||
? [options.directory]
|
||||
: DEFAULT_LOG_DIRS;
|
||||
const seen = new Set();
|
||||
const files = [];
|
||||
|
||||
for (const directory of directories) {
|
||||
let rootDir;
|
||||
try {
|
||||
rootDir = resolveProjectPath(projectPath, directory);
|
||||
} catch (error) {
|
||||
continue;
|
||||
}
|
||||
if (!fs.existsSync(rootDir) || !fs.statSync(rootDir).isDirectory()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
for (const file of collectLogFiles(rootDir, maxDepth, limit)) {
|
||||
if (seen.has(file.fullPath)) {
|
||||
continue;
|
||||
}
|
||||
seen.add(file.fullPath);
|
||||
files.push(file);
|
||||
if (files.length >= limit) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (files.length >= limit) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return files
|
||||
.sort((left, right) => right.mtimeMs - left.mtimeMs)
|
||||
.slice(0, limit);
|
||||
}
|
||||
|
||||
function readTail(filePath, maxLines = 80) {
|
||||
const stat = safeStat(filePath);
|
||||
if (!stat) {
|
||||
return '';
|
||||
}
|
||||
|
||||
const size = Math.min(stat.size, MAX_READ_BYTES);
|
||||
const buffer = Buffer.alloc(size);
|
||||
const fd = fs.openSync(filePath, 'r');
|
||||
try {
|
||||
fs.readSync(fd, buffer, 0, size, stat.size - size);
|
||||
} finally {
|
||||
fs.closeSync(fd);
|
||||
}
|
||||
|
||||
return buffer
|
||||
.toString('utf8')
|
||||
.replace(/\s+$/g, '')
|
||||
.split(/\r?\n/)
|
||||
.slice(-normalizeLimit(maxLines, 80, 1, 1000))
|
||||
.join('\n')
|
||||
.trim();
|
||||
}
|
||||
|
||||
function getRecentProjectLogs(projectPath, options = {}) {
|
||||
const maxLines = normalizeLimit(options.lines, 80, 1, 1000);
|
||||
return findProjectLogFiles(projectPath, options).map((file) => ({
|
||||
path: path.relative(projectPath, file.fullPath).replace(/\\/g, '/'),
|
||||
size: file.size,
|
||||
mtime: new Date(file.mtimeMs).toISOString(),
|
||||
text: readTail(file.fullPath, maxLines),
|
||||
}));
|
||||
}
|
||||
|
||||
function searchProjectLogs(projectPath, options = {}) {
|
||||
const query = String(options.query || '').trim();
|
||||
if (!query) {
|
||||
throw new Error('query is required.');
|
||||
}
|
||||
|
||||
const limit = normalizeLimit(options.limit, 50, 1, 500);
|
||||
const flags = options.caseSensitive ? '' : 'i';
|
||||
const pattern = options.regex ? new RegExp(query, flags) : null;
|
||||
const lowerQuery = query.toLowerCase();
|
||||
const results = [];
|
||||
|
||||
for (const file of findProjectLogFiles(projectPath, { ...options, limit: normalizeLimit(options.fileLimit, 40, 1, 200) })) {
|
||||
const text = readTail(file.fullPath, normalizeLimit(options.linesPerFile, 2000, 1, 10000));
|
||||
const lines = text.split(/\r?\n/);
|
||||
for (let index = 0; index < lines.length; index += 1) {
|
||||
const line = lines[index];
|
||||
const matched = pattern
|
||||
? pattern.test(line)
|
||||
: (options.caseSensitive ? line.includes(query) : line.toLowerCase().includes(lowerQuery));
|
||||
if (!matched) {
|
||||
continue;
|
||||
}
|
||||
|
||||
results.push({
|
||||
path: path.relative(projectPath, file.fullPath).replace(/\\/g, '/'),
|
||||
line: index + 1,
|
||||
text: line,
|
||||
});
|
||||
if (results.length >= limit) {
|
||||
return { query, count: results.length, matches: results };
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return { query, count: results.length, matches: results };
|
||||
}
|
||||
|
||||
function clearProjectLogFiles(projectPath, options = {}) {
|
||||
const cleared = [];
|
||||
for (const file of findProjectLogFiles(projectPath, options)) {
|
||||
fs.truncateSync(file.fullPath, 0);
|
||||
cleared.push(path.relative(projectPath, file.fullPath).replace(/\\/g, '/'));
|
||||
}
|
||||
return cleared;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
findProjectLogFiles,
|
||||
getRecentProjectLogs,
|
||||
searchProjectLogs,
|
||||
clearProjectLogFiles,
|
||||
};
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
'use strict';
|
||||
|
||||
const path = require('path');
|
||||
const fs = require('fs');
|
||||
|
||||
function normalizeRoot(projectPath) {
|
||||
return path.resolve(String(projectPath || process.cwd()));
|
||||
}
|
||||
|
||||
function isPathInside(rootPath, targetPath) {
|
||||
const root = normalizeRoot(rootPath);
|
||||
const target = path.resolve(String(targetPath || ''));
|
||||
const relative = path.relative(root, target);
|
||||
return relative === '' || (relative && !relative.startsWith('..') && !path.isAbsolute(relative));
|
||||
}
|
||||
|
||||
function resolveProjectPath(projectPath, rawPath) {
|
||||
if (!rawPath || typeof rawPath !== 'string') {
|
||||
throw new Error('path is required.');
|
||||
}
|
||||
|
||||
const root = normalizeRoot(projectPath);
|
||||
const targetPath = path.isAbsolute(rawPath)
|
||||
? path.resolve(rawPath)
|
||||
: path.resolve(root, rawPath);
|
||||
|
||||
if (!isPathInside(root, targetPath)) {
|
||||
throw new Error(`Path is outside the Cocos project: ${rawPath}`);
|
||||
}
|
||||
|
||||
return targetPath;
|
||||
}
|
||||
|
||||
// For managed configuration/instruction files, lexical containment alone is not enough:
|
||||
// a project-local directory may be a symlink to another project's or the user's files.
|
||||
function resolveProjectFilePath(projectPath, rawPath) {
|
||||
const resolved = resolveProjectPath(projectPath, rawPath);
|
||||
const root = normalizeRoot(projectPath);
|
||||
const realRoot = fs.existsSync(root) ? fs.realpathSync(root) : root;
|
||||
let existing = resolved;
|
||||
while (!fs.existsSync(existing)) {
|
||||
try {
|
||||
if (fs.lstatSync(existing).isSymbolicLink()) throw new Error(`Dangling symbolic link in project path: ${rawPath}`);
|
||||
} catch (error) { if (error.code !== 'ENOENT') throw error; }
|
||||
const parent = path.dirname(existing);
|
||||
if (parent === existing) break;
|
||||
existing = parent;
|
||||
}
|
||||
if (fs.existsSync(root) && !isPathInside(realRoot, fs.realpathSync(existing))) throw new Error(`Path resolves outside the Cocos project: ${rawPath}`);
|
||||
return resolved;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
isPathInside,
|
||||
resolveProjectPath,
|
||||
resolveProjectFilePath,
|
||||
};
|
||||
+228
@@ -0,0 +1,228 @@
|
||||
'use strict';
|
||||
|
||||
const crypto = require('crypto');
|
||||
|
||||
const UI_2D_LAYER = 33554432;
|
||||
|
||||
function createPrefabFileId() {
|
||||
return crypto.randomBytes(16).toString('base64').replace(/=+$/, '');
|
||||
}
|
||||
|
||||
function normalizePrefabNodeLayers(root, layer = UI_2D_LAYER) {
|
||||
if (!root || typeof root !== 'object') {
|
||||
throw new Error('Prefab root node is required.');
|
||||
}
|
||||
if (!Number.isSafeInteger(layer) || layer < 0) {
|
||||
throw new Error('Prefab node layer must be a non-negative integer.');
|
||||
}
|
||||
|
||||
const visitedNodes = new Set();
|
||||
let nodeCount = 0;
|
||||
|
||||
function visit(node) {
|
||||
if (!node || typeof node !== 'object' || visitedNodes.has(node)) {
|
||||
return;
|
||||
}
|
||||
visitedNodes.add(node);
|
||||
node.layer = layer;
|
||||
nodeCount += 1;
|
||||
|
||||
const children = Array.isArray(node.children) ? node.children : [];
|
||||
for (const child of children) {
|
||||
visit(child);
|
||||
}
|
||||
}
|
||||
|
||||
visit(root);
|
||||
return { nodeCount, layer };
|
||||
}
|
||||
|
||||
function attachPrefabMetadata(root, prefab, options = {}) {
|
||||
if (!root || typeof root !== 'object') {
|
||||
throw new Error('Prefab root node is required.');
|
||||
}
|
||||
if (!prefab || typeof prefab !== 'object') {
|
||||
throw new Error('Prefab asset is required.');
|
||||
}
|
||||
|
||||
const prefabUtils = options.prefabUtils;
|
||||
const PrefabInfo = prefabUtils && prefabUtils.PrefabInfo;
|
||||
const CompPrefabInfo = prefabUtils && prefabUtils.CompPrefabInfo;
|
||||
if (typeof PrefabInfo !== 'function' || typeof CompPrefabInfo !== 'function') {
|
||||
throw new Error('Cocos PrefabInfo constructors are unavailable.');
|
||||
}
|
||||
|
||||
const generateFileId = typeof options.createFileId === 'function'
|
||||
? options.createFileId
|
||||
: createPrefabFileId;
|
||||
const usedFileIds = new Set();
|
||||
const visitedNodes = new Set();
|
||||
let nodeCount = 0;
|
||||
let componentCount = 0;
|
||||
|
||||
function nextFileId() {
|
||||
for (let attempt = 0; attempt < 32; attempt += 1) {
|
||||
const fileId = String(generateFileId() || '').trim();
|
||||
if (fileId && !usedFileIds.has(fileId)) {
|
||||
usedFileIds.add(fileId);
|
||||
return fileId;
|
||||
}
|
||||
}
|
||||
throw new Error('Unable to generate a unique prefab fileId.');
|
||||
}
|
||||
|
||||
function visit(node) {
|
||||
if (!node || typeof node !== 'object' || visitedNodes.has(node)) {
|
||||
return;
|
||||
}
|
||||
visitedNodes.add(node);
|
||||
|
||||
const nodeInfo = new PrefabInfo();
|
||||
nodeInfo.root = root;
|
||||
nodeInfo.asset = prefab;
|
||||
nodeInfo.fileId = nextFileId();
|
||||
node._prefab = nodeInfo;
|
||||
nodeCount += 1;
|
||||
|
||||
const components = Array.isArray(node.components) ? node.components : [];
|
||||
for (const component of components) {
|
||||
if (!component || typeof component !== 'object') {
|
||||
continue;
|
||||
}
|
||||
const componentInfo = new CompPrefabInfo();
|
||||
componentInfo.fileId = nextFileId();
|
||||
component.__prefab = componentInfo;
|
||||
componentCount += 1;
|
||||
}
|
||||
|
||||
const children = Array.isArray(node.children) ? node.children : [];
|
||||
for (const child of children) {
|
||||
visit(child);
|
||||
}
|
||||
}
|
||||
|
||||
visit(root);
|
||||
return {
|
||||
nodeCount,
|
||||
componentCount,
|
||||
fileIdCount: usedFileIds.size,
|
||||
};
|
||||
}
|
||||
|
||||
function invalidMetadata(message) {
|
||||
throw new Error(`Invalid serialized prefab metadata: ${message}`);
|
||||
}
|
||||
|
||||
function referenceId(value, label) {
|
||||
if (!value || typeof value !== 'object' || !Number.isInteger(value.__id__)) {
|
||||
invalidMetadata(`${label} is not an object reference.`);
|
||||
}
|
||||
return value.__id__;
|
||||
}
|
||||
|
||||
function referencedObject(objects, reference, label) {
|
||||
const id = referenceId(reference, label);
|
||||
if (id < 0 || id >= objects.length || !objects[id] || typeof objects[id] !== 'object') {
|
||||
invalidMetadata(`${label} points to missing object ${id}.`);
|
||||
}
|
||||
return { id, value: objects[id] };
|
||||
}
|
||||
|
||||
function assertFileId(info, label, fileIds) {
|
||||
const fileId = String(info.fileId || '').trim();
|
||||
if (!fileId) {
|
||||
invalidMetadata(`${label} has an empty fileId.`);
|
||||
}
|
||||
if (fileIds.has(fileId)) {
|
||||
invalidMetadata(`${label} reuses fileId '${fileId}'.`);
|
||||
}
|
||||
fileIds.add(fileId);
|
||||
}
|
||||
|
||||
function assertSerializedPrefabMetadata(serialized, options = {}) {
|
||||
let objects;
|
||||
try {
|
||||
objects = typeof serialized === 'string' ? JSON.parse(serialized) : serialized;
|
||||
} catch (error) {
|
||||
invalidMetadata(`content is not valid JSON: ${error.message}`);
|
||||
}
|
||||
if (!Array.isArray(objects)) {
|
||||
invalidMetadata('root value must be an object array.');
|
||||
}
|
||||
|
||||
const prefabIndex = objects.findIndex((value) => value && value.__type__ === 'cc.Prefab');
|
||||
if (prefabIndex < 0) {
|
||||
invalidMetadata('cc.Prefab object is missing.');
|
||||
}
|
||||
const prefab = objects[prefabIndex];
|
||||
const rootRef = referencedObject(objects, prefab.data, 'cc.Prefab.data');
|
||||
if (rootRef.value.__type__ !== 'cc.Node') {
|
||||
invalidMetadata(`cc.Prefab.data points to ${rootRef.value.__type__ || 'an unknown type'}, not cc.Node.`);
|
||||
}
|
||||
|
||||
const nodes = objects
|
||||
.map((value, index) => ({ value, index }))
|
||||
.filter(({ value }) => value && value.__type__ === 'cc.Node');
|
||||
if (!nodes.length) {
|
||||
invalidMetadata('cc.Node objects are missing.');
|
||||
}
|
||||
|
||||
const fileIds = new Set();
|
||||
let componentCount = 0;
|
||||
for (const { value: node, index: nodeIndex } of nodes) {
|
||||
if (options.expectedLayer !== undefined && node._layer !== options.expectedLayer) {
|
||||
invalidMetadata(
|
||||
`cc.Node at index ${nodeIndex}._layer is ${String(node._layer)}, expected ${String(options.expectedLayer)}.`
|
||||
);
|
||||
}
|
||||
const nodeInfoRef = referencedObject(objects, node._prefab, `cc.Node at index ${nodeIndex}._prefab`);
|
||||
const nodeInfo = nodeInfoRef.value;
|
||||
if (nodeInfo.__type__ !== 'cc.PrefabInfo') {
|
||||
invalidMetadata(`cc.Node at index ${nodeIndex}._prefab does not reference cc.PrefabInfo.`);
|
||||
}
|
||||
if (referenceId(nodeInfo.root, `cc.PrefabInfo at index ${nodeInfoRef.id}.root`) !== rootRef.id) {
|
||||
invalidMetadata(`cc.PrefabInfo at index ${nodeInfoRef.id}.root does not reference the prefab root.`);
|
||||
}
|
||||
if (referenceId(nodeInfo.asset, `cc.PrefabInfo at index ${nodeInfoRef.id}.asset`) !== prefabIndex) {
|
||||
invalidMetadata(`cc.PrefabInfo at index ${nodeInfoRef.id}.asset does not reference the prefab asset.`);
|
||||
}
|
||||
assertFileId(nodeInfo, `cc.PrefabInfo at index ${nodeInfoRef.id}`, fileIds);
|
||||
|
||||
const componentRefs = Array.isArray(node._components) ? node._components : [];
|
||||
for (let componentOffset = 0; componentOffset < componentRefs.length; componentOffset += 1) {
|
||||
const componentRef = referencedObject(
|
||||
objects,
|
||||
componentRefs[componentOffset],
|
||||
`cc.Node at index ${nodeIndex}._components[${componentOffset}]`
|
||||
);
|
||||
const componentInfoRef = referencedObject(
|
||||
objects,
|
||||
componentRef.value.__prefab,
|
||||
`component at index ${componentRef.id}.__prefab`
|
||||
);
|
||||
const componentInfo = componentInfoRef.value;
|
||||
if (componentInfo.__type__ !== 'cc.CompPrefabInfo') {
|
||||
invalidMetadata(`component at index ${componentRef.id}.__prefab does not reference cc.CompPrefabInfo.`);
|
||||
}
|
||||
assertFileId(componentInfo, `cc.CompPrefabInfo at index ${componentInfoRef.id}`, fileIds);
|
||||
componentCount += 1;
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
valid: true,
|
||||
prefabIndex,
|
||||
rootIndex: rootRef.id,
|
||||
nodeCount: nodes.length,
|
||||
componentCount,
|
||||
fileIdCount: fileIds.size,
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
UI_2D_LAYER,
|
||||
assertSerializedPrefabMetadata,
|
||||
attachPrefabMetadata,
|
||||
createPrefabFileId,
|
||||
normalizePrefabNodeLayers,
|
||||
};
|
||||
+376
@@ -0,0 +1,376 @@
|
||||
'use strict';
|
||||
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const { listAssets, queryAssetData, queryAssetInfo, queryAssetMeta } = require('./assets');
|
||||
const { resolveProjectPath } = require('./path-safety');
|
||||
|
||||
function requestEditorMessage(channel, method, ...args) {
|
||||
if (!global.Editor || !Editor.Message || typeof Editor.Message.request !== 'function') {
|
||||
throw new Error('Editor.Message.request is unavailable in the Cocos extension host.');
|
||||
}
|
||||
return Editor.Message.request(channel, method, ...args);
|
||||
}
|
||||
|
||||
function assetUrlToPath(projectPath, url) {
|
||||
if (!url || !String(url).startsWith('db://assets/')) {
|
||||
return '';
|
||||
}
|
||||
return path.join(projectPath, String(url).slice('db://'.length));
|
||||
}
|
||||
|
||||
function assetFilePath(projectPath, info) {
|
||||
const candidates = [
|
||||
info && info.file,
|
||||
info && info.path,
|
||||
info && info.source,
|
||||
info && info.url ? assetUrlToPath(projectPath, info.url) : '',
|
||||
].filter(Boolean);
|
||||
|
||||
for (const candidate of candidates) {
|
||||
const fullPath = path.isAbsolute(candidate)
|
||||
? resolveProjectPath(projectPath, candidate)
|
||||
: resolveProjectPath(projectPath, candidate);
|
||||
if (fs.existsSync(fullPath) && fs.statSync(fullPath).isFile()) {
|
||||
return fullPath;
|
||||
}
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
function normalizePrefabTarget(projectPath, target) {
|
||||
const raw = String(target || '').trim().replace(/\\/g, '/');
|
||||
if (!raw) {
|
||||
throw new Error('target is required.');
|
||||
}
|
||||
|
||||
let relative = raw;
|
||||
if (relative.startsWith('db://assets/')) {
|
||||
relative = relative.slice('db://'.length);
|
||||
} else if (relative.startsWith('/assets/')) {
|
||||
relative = relative.slice(1);
|
||||
} else if (!relative.startsWith('assets/')) {
|
||||
relative = `assets/${relative}`;
|
||||
}
|
||||
|
||||
if (!relative.endsWith('.prefab')) {
|
||||
relative = `${relative}.prefab`;
|
||||
}
|
||||
|
||||
const filePath = resolveProjectPath(projectPath, relative);
|
||||
const assetsRoot = path.join(projectPath, 'assets');
|
||||
const relativeToAssets = path.relative(assetsRoot, filePath);
|
||||
if (relativeToAssets.startsWith('..') || path.isAbsolute(relativeToAssets)) {
|
||||
throw new Error('target must be inside the Cocos assets directory.');
|
||||
}
|
||||
|
||||
const projectRelative = path.relative(projectPath, filePath).replace(/\\/g, '/');
|
||||
return {
|
||||
filePath,
|
||||
projectRelative,
|
||||
dbUrl: `db://${projectRelative}`,
|
||||
};
|
||||
}
|
||||
|
||||
async function queryAssetInfoOptional(target) {
|
||||
try {
|
||||
return await queryAssetInfo(target);
|
||||
} catch (error) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async function savePrefabContent(projectPath, options = {}) {
|
||||
const target = normalizePrefabTarget(projectPath, options.target);
|
||||
const content = String(options.content || '');
|
||||
if (!content) {
|
||||
throw new Error('content is required.');
|
||||
}
|
||||
JSON.parse(content);
|
||||
|
||||
const exists = fs.existsSync(target.filePath);
|
||||
if (exists && options.overwrite !== true) {
|
||||
throw new Error(`Target prefab already exists: ${target.projectRelative}`);
|
||||
}
|
||||
|
||||
fs.mkdirSync(path.dirname(target.filePath), { recursive: true });
|
||||
|
||||
let method = 'fs-write';
|
||||
let result;
|
||||
if (global.Editor && Editor.Message && typeof Editor.Message.request === 'function') {
|
||||
if (exists && options.overwrite === true) {
|
||||
try {
|
||||
result = await requestEditorMessage('asset-db', 'save-asset', target.dbUrl, content);
|
||||
method = 'asset-db:save-asset';
|
||||
if (!fs.existsSync(target.filePath) || fs.readFileSync(target.filePath, 'utf8') !== content) {
|
||||
fs.writeFileSync(target.filePath, content.endsWith('\n') ? content : `${content}\n`, 'utf8');
|
||||
}
|
||||
} catch (error) {
|
||||
fs.writeFileSync(target.filePath, content.endsWith('\n') ? content : `${content}\n`, 'utf8');
|
||||
result = { fallbackReason: error.message };
|
||||
}
|
||||
} else {
|
||||
try {
|
||||
result = await requestEditorMessage('asset-db', 'create-asset', target.dbUrl, content);
|
||||
method = 'asset-db:create-asset';
|
||||
} catch (error) {
|
||||
if (fs.existsSync(target.filePath)) {
|
||||
result = { fallbackReason: error.message, fileCreated: true };
|
||||
} else {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
fs.writeFileSync(target.filePath, content.endsWith('\n') ? content : `${content}\n`, 'utf8');
|
||||
}
|
||||
|
||||
const fileExists = fs.existsSync(target.filePath);
|
||||
const info = await queryAssetInfoOptional(target.dbUrl);
|
||||
if (!fileExists && !info) {
|
||||
throw new Error(`Prefab was not created: ${target.projectRelative}`);
|
||||
}
|
||||
|
||||
return {
|
||||
created: !exists,
|
||||
overwritten: exists && options.overwrite === true,
|
||||
method,
|
||||
result,
|
||||
dbUrl: target.dbUrl,
|
||||
path: target.projectRelative,
|
||||
fileExists,
|
||||
info,
|
||||
};
|
||||
}
|
||||
|
||||
function collectUuidReferences(value, refs = [], pointer = '') {
|
||||
if (!value || typeof value !== 'object') {
|
||||
return refs;
|
||||
}
|
||||
|
||||
if (Array.isArray(value)) {
|
||||
value.forEach((item, index) => collectUuidReferences(item, refs, `${pointer}/${index}`));
|
||||
return refs;
|
||||
}
|
||||
|
||||
for (const [key, child] of Object.entries(value)) {
|
||||
const childPointer = `${pointer}/${key}`;
|
||||
if (
|
||||
typeof child === 'string' &&
|
||||
(key.toLowerCase().includes('uuid') || key === '__uuid__' || key === 'assetUuid' || key === 'prefabUuid')
|
||||
) {
|
||||
refs.push({ uuid: child, path: childPointer, key });
|
||||
} else {
|
||||
collectUuidReferences(child, refs, childPointer);
|
||||
}
|
||||
}
|
||||
return refs;
|
||||
}
|
||||
|
||||
function getByJsonPath(target, jsonPath) {
|
||||
const segments = String(jsonPath || '')
|
||||
.replace(/^\//, '')
|
||||
.split(/[/.]/)
|
||||
.map((segment) => segment.trim())
|
||||
.filter(Boolean);
|
||||
let current = target;
|
||||
for (const segment of segments) {
|
||||
if (current == null) {
|
||||
return undefined;
|
||||
}
|
||||
current = current[segment];
|
||||
}
|
||||
return current;
|
||||
}
|
||||
|
||||
function setByJsonPath(target, jsonPath, value) {
|
||||
const segments = String(jsonPath || '')
|
||||
.replace(/^\//, '')
|
||||
.split(/[/.]/)
|
||||
.map((segment) => segment.trim())
|
||||
.filter(Boolean);
|
||||
if (!segments.length) {
|
||||
throw new Error('jsonPath is required.');
|
||||
}
|
||||
let current = target;
|
||||
for (let index = 0; index < segments.length - 1; index += 1) {
|
||||
const segment = segments[index];
|
||||
if (current[segment] == null || typeof current[segment] !== 'object') {
|
||||
current[segment] = {};
|
||||
}
|
||||
current = current[segment];
|
||||
}
|
||||
current[segments[segments.length - 1]] = value;
|
||||
}
|
||||
|
||||
async function inspectPrefab(projectPath, target) {
|
||||
const info = await queryAssetInfo(target);
|
||||
const meta = await queryAssetMeta(target).catch(() => null);
|
||||
const data = await queryAssetData(target).catch(() => null);
|
||||
const filePath = assetFilePath(projectPath, info);
|
||||
const content = filePath ? fs.readFileSync(filePath, 'utf8') : '';
|
||||
const parsed = content ? JSON.parse(content) : data;
|
||||
const references = collectUuidReferences(parsed).slice(0, 500);
|
||||
|
||||
return {
|
||||
info,
|
||||
meta,
|
||||
filePath: filePath ? path.relative(projectPath, filePath).replace(/\\/g, '/') : '',
|
||||
referenceCount: references.length,
|
||||
references,
|
||||
};
|
||||
}
|
||||
|
||||
async function validatePrefabReferences(projectPath, options = {}) {
|
||||
const targets = options.target
|
||||
? [options.target]
|
||||
: (await listAssets({ pattern: options.pattern || 'db://assets/**', ccType: 'cc.Prefab' }))
|
||||
.slice(0, Number.isFinite(options.limit) ? Math.max(1, Math.min(200, options.limit)) : 50)
|
||||
.map((asset) => asset.uuid || asset.url)
|
||||
.filter(Boolean);
|
||||
const prefabs = [];
|
||||
|
||||
for (const target of targets) {
|
||||
const prefab = await inspectPrefab(projectPath, target);
|
||||
const checked = [];
|
||||
const missing = [];
|
||||
for (const ref of prefab.references) {
|
||||
try {
|
||||
const info = await queryAssetInfo(ref.uuid);
|
||||
checked.push({ ...ref, exists: true, asset: { uuid: info.uuid, url: info.url, type: info.type } });
|
||||
} catch (error) {
|
||||
missing.push({ ...ref, exists: false, error: error.message });
|
||||
}
|
||||
}
|
||||
prefabs.push({
|
||||
target,
|
||||
filePath: prefab.filePath,
|
||||
referenceCount: prefab.referenceCount,
|
||||
checkedCount: checked.length + missing.length,
|
||||
missingCount: missing.length,
|
||||
missing,
|
||||
});
|
||||
}
|
||||
|
||||
const missingCount = prefabs.reduce((sum, prefab) => sum + prefab.missingCount, 0);
|
||||
return {
|
||||
ok: missingCount === 0,
|
||||
prefabCount: prefabs.length,
|
||||
missingCount,
|
||||
prefabs,
|
||||
};
|
||||
}
|
||||
|
||||
async function duplicatePrefab(projectPath, options = {}) {
|
||||
const source = String(options.source || '').trim();
|
||||
const target = String(options.target || '').trim();
|
||||
if (!source || !target) {
|
||||
throw new Error('source and target are required.');
|
||||
}
|
||||
|
||||
const info = await queryAssetInfo(source);
|
||||
const sourcePath = assetFilePath(projectPath, info);
|
||||
if (!sourcePath) {
|
||||
throw new Error(`Prefab source file was not found: ${source}`);
|
||||
}
|
||||
|
||||
const targetPath = resolveProjectPath(projectPath, target.endsWith('.prefab') ? target : `${target}.prefab`);
|
||||
const assetsRoot = path.join(projectPath, 'assets');
|
||||
const relativeToAssets = path.relative(assetsRoot, targetPath);
|
||||
if (relativeToAssets.startsWith('..') || path.isAbsolute(relativeToAssets)) {
|
||||
throw new Error('target must be inside the Cocos assets directory.');
|
||||
}
|
||||
if (fs.existsSync(targetPath) && options.overwrite !== true) {
|
||||
throw new Error(`Target prefab already exists: ${target}`);
|
||||
}
|
||||
|
||||
fs.mkdirSync(path.dirname(targetPath), { recursive: true });
|
||||
fs.copyFileSync(sourcePath, targetPath);
|
||||
return {
|
||||
duplicated: true,
|
||||
source: path.relative(projectPath, sourcePath).replace(/\\/g, '/'),
|
||||
target: path.relative(projectPath, targetPath).replace(/\\/g, '/'),
|
||||
};
|
||||
}
|
||||
|
||||
async function editPrefabJson(projectPath, options = {}) {
|
||||
const target = String(options.target || '').trim();
|
||||
if (!target) {
|
||||
throw new Error('target is required.');
|
||||
}
|
||||
const info = await queryAssetInfo(target);
|
||||
const filePath = assetFilePath(projectPath, info);
|
||||
if (!filePath) {
|
||||
throw new Error(`Prefab file was not found: ${target}`);
|
||||
}
|
||||
|
||||
const original = fs.readFileSync(filePath, 'utf8');
|
||||
let updated = original;
|
||||
if (options.search !== undefined) {
|
||||
const search = String(options.search);
|
||||
if (!search) {
|
||||
throw new Error('search must not be empty.');
|
||||
}
|
||||
if (!original.includes(search)) {
|
||||
throw new Error('search text was not found in prefab file.');
|
||||
}
|
||||
updated = options.replaceAll
|
||||
? original.split(search).join(String(options.replace || ''))
|
||||
: original.replace(search, String(options.replace || ''));
|
||||
} else {
|
||||
const json = JSON.parse(original);
|
||||
const value = JSON.parse(String(options.valueJson || 'null'));
|
||||
setByJsonPath(json, options.jsonPath, value);
|
||||
updated = JSON.stringify(json, null, 2) + '\n';
|
||||
}
|
||||
|
||||
JSON.parse(updated);
|
||||
if (options.createBackup) {
|
||||
fs.writeFileSync(`${filePath}.bak`, original, 'utf8');
|
||||
}
|
||||
fs.writeFileSync(filePath, updated, 'utf8');
|
||||
return {
|
||||
edited: true,
|
||||
path: path.relative(projectPath, filePath).replace(/\\/g, '/'),
|
||||
oldValue: options.jsonPath ? getByJsonPath(JSON.parse(original), options.jsonPath) : undefined,
|
||||
validation: await validatePrefabReferences(projectPath, { target }),
|
||||
};
|
||||
}
|
||||
|
||||
async function applyPrefabInstance(nodeUuid) {
|
||||
const uuid = String(nodeUuid || '').trim();
|
||||
if (!uuid) {
|
||||
throw new Error('node uuid is required.');
|
||||
}
|
||||
const result = await requestEditorMessage('scene', 'apply-prefab', uuid);
|
||||
return { applied: true, uuid, result };
|
||||
}
|
||||
|
||||
async function revertPrefabInstance(nodeUuid) {
|
||||
const uuid = String(nodeUuid || '').trim();
|
||||
if (!uuid) {
|
||||
throw new Error('node uuid is required.');
|
||||
}
|
||||
const candidates = ['revert-prefab', 'restore-prefab'];
|
||||
let lastError = null;
|
||||
for (const method of candidates) {
|
||||
try {
|
||||
const result = await requestEditorMessage('scene', method, uuid);
|
||||
return { reverted: true, uuid, method, result };
|
||||
} catch (error) {
|
||||
lastError = error;
|
||||
}
|
||||
}
|
||||
throw lastError || new Error('No prefab revert editor message was available.');
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
applyPrefabInstance,
|
||||
duplicatePrefab,
|
||||
editPrefabJson,
|
||||
inspectPrefab,
|
||||
normalizePrefabTarget,
|
||||
revertPrefabInstance,
|
||||
savePrefabContent,
|
||||
validatePrefabReferences,
|
||||
};
|
||||
+133
@@ -0,0 +1,133 @@
|
||||
'use strict';
|
||||
|
||||
const electronTools = require('./electron-tools');
|
||||
|
||||
// This function is serialized into Creator's main renderer. Keep it self-contained.
|
||||
async function previewToolbarCommand(command) {
|
||||
const toolbar = document.querySelector('#toolbar');
|
||||
const panels = toolbar ? Array.from(toolbar.querySelectorAll('ui-panel')) : [];
|
||||
const candidates = panels.filter((panel) => /\/builtin\/preview\/static\/toolbar\/middle\.js$/.test(
|
||||
String(panel.getAttribute('src') || '').replace(/\\/g, '/')
|
||||
));
|
||||
const panel = candidates.length === 1 ? candidates[0] : null;
|
||||
const root = panel && (panel.shadowRoot || panel);
|
||||
const element = root && root.querySelector('.preview-info-wrap');
|
||||
const vm = element && element.__vue__;
|
||||
if (!vm || !vm.gameView || typeof vm.gameView.isPlay !== 'boolean'
|
||||
|| typeof vm.gameView.isPaused !== 'boolean'
|
||||
|| !['play', 'changePlatform', 'gameViewPause'].every((key) => typeof vm[key] === 'function')) {
|
||||
throw new Error('Compatible Cocos Creator preview toolbar is unavailable. Open the main editor window and retry; Game View cannot be controlled safely without its toolbar.');
|
||||
}
|
||||
if (!['state', 'start', 'set-mode', 'pause', 'resume'].includes(command.action)
|
||||
|| (command.action === 'set-mode' && !['browser', 'gameView', 'simulator'].includes(command.mode))) {
|
||||
throw new Error('Unsupported preview toolbar command.');
|
||||
}
|
||||
|
||||
const lock = Symbol.for('funplay-cocos-mcp.preview-operation');
|
||||
const busy = () => Boolean(vm[lock] || vm.isPlaying || vm.isLoading || vm.gameView.isStep);
|
||||
const readPreview = async () => {
|
||||
// Creator 3.8 returns undefined/null (depending on IPC context) when there
|
||||
// is no preview, otherwise the PreviewPlay manager's boolean pause state
|
||||
// (not the edit-scene director).
|
||||
const paused = await Editor.Message.request('scene', 'editor-preview-call-method', 'isPause');
|
||||
if (paused != null && typeof paused !== 'boolean') {
|
||||
throw new Error('Cocos Creator returned an unsupported Game View preview state.');
|
||||
}
|
||||
return { running: typeof paused === 'boolean', paused: paused === true };
|
||||
};
|
||||
const snapshot = (state) => ({
|
||||
scope: 'gameView',
|
||||
source: 'scene.editor-preview-call-method',
|
||||
mode: vm.currPlatform,
|
||||
...state,
|
||||
busy: busy(),
|
||||
toolbarSynchronized: vm.gameView.isPlay === state.running
|
||||
&& vm.gameView.isPaused === state.paused
|
||||
&& (!state.running || vm.currPlatform === 'gameView'),
|
||||
});
|
||||
if (command.action === 'state') return snapshot(await readPreview());
|
||||
if (busy()) throw new Error('Cocos Creator preview toolbar is busy. Wait for the current preview operation to finish and retry.');
|
||||
|
||||
vm[lock] = true;
|
||||
try {
|
||||
const previousMode = vm.currPlatform;
|
||||
const before = await readPreview();
|
||||
if (['pause', 'resume'].includes(command.action) && !before.running) {
|
||||
throw new Error('Game View preview is not running. Start run_project_preview with mode="gameView" first; browser and simulator previews are not controlled by this tool.');
|
||||
}
|
||||
|
||||
const changeMode = async (mode) => {
|
||||
await vm.changePlatform(mode);
|
||||
// Creator's changePlatform starts this write without awaiting it. Wait
|
||||
// for persistence as well so subsequent MCP calls see the same mode.
|
||||
await Editor.Profile.setConfig('preview', 'preview.current.platform', mode, 'local');
|
||||
if (vm.currPlatform !== mode) throw new Error(`Cocos Creator did not select preview mode '${mode}'.`);
|
||||
};
|
||||
|
||||
// Repair previews started by older MCP versions/direct scene messages.
|
||||
// Normal starts and pause changes below always use the native toolbar.
|
||||
if (before.running && vm.currPlatform !== 'gameView') await changeMode('gameView');
|
||||
vm.gameView.isPlay = before.running;
|
||||
vm.gameView.isPaused = before.paused;
|
||||
|
||||
if (command.action === 'set-mode') {
|
||||
if (before.running && command.mode !== 'gameView') {
|
||||
await vm.play();
|
||||
if ((await readPreview()).running) {
|
||||
throw new Error('Cocos Creator rejected the Game View stop request; preview mode was not changed.');
|
||||
}
|
||||
vm.gameView.isPlay = false;
|
||||
vm.gameView.isPaused = false;
|
||||
}
|
||||
await changeMode(command.mode);
|
||||
} else if (command.action === 'start') {
|
||||
if (vm.currPlatform !== 'gameView') await changeMode('gameView');
|
||||
// play() is a toggle; never invoke it for an already running preview.
|
||||
if (!before.running) await vm.play();
|
||||
} else {
|
||||
const paused = command.action === 'pause';
|
||||
// gameViewPause() toggles the preview manager and its toolbar together.
|
||||
if (before.paused !== paused) await vm.gameViewPause();
|
||||
}
|
||||
|
||||
const after = await readPreview();
|
||||
if (command.action === 'start' && !after.running) {
|
||||
throw new Error('Cocos Creator rejected the Game View start request.');
|
||||
}
|
||||
if (['pause', 'resume'].includes(command.action)
|
||||
&& (!after.running || after.paused !== (command.action === 'pause'))) {
|
||||
throw new Error(`Cocos Creator did not ${command.action} the Game View preview.`);
|
||||
}
|
||||
const result = snapshot(after);
|
||||
if (!result.toolbarSynchronized) {
|
||||
throw new Error('Game View preview and toolbar state changed during the operation. Query get_runtime_state and retry.');
|
||||
}
|
||||
return {
|
||||
...result,
|
||||
busy: Boolean(vm.isPlaying || vm.isLoading || vm.gameView.isStep),
|
||||
changed: previousMode !== vm.currPlatform || before.running !== after.running || before.paused !== after.paused,
|
||||
};
|
||||
} finally {
|
||||
delete vm[lock];
|
||||
}
|
||||
}
|
||||
|
||||
function buildPreviewToolbarScript(command) {
|
||||
return `(${previewToolbarCommand.toString()})(${JSON.stringify(command)})`;
|
||||
}
|
||||
|
||||
async function controlPreviewToolbar(command) {
|
||||
// Never fall back to the focused window: it may be a preview, inspector,
|
||||
// another panel, or DevTools rather than the project's main toolbar.
|
||||
const windows = electronTools.getAllWindows().filter((window) => {
|
||||
const url = window.webContents && typeof window.webContents.getURL === 'function'
|
||||
? window.webContents.getURL() : '';
|
||||
return /^file:\/\/.*\/windows\/main\.html(?:[?#]|$)/i.test(url);
|
||||
});
|
||||
if (windows.length !== 1) {
|
||||
throw new Error('A unique Cocos Creator main editor window is required to control Game View preview.');
|
||||
}
|
||||
return await electronTools.executeJavaScript(windows[0], buildPreviewToolbarScript(command));
|
||||
}
|
||||
|
||||
module.exports = { buildPreviewToolbarScript, controlPreviewToolbar };
|
||||
@@ -0,0 +1,66 @@
|
||||
'use strict';
|
||||
|
||||
const path = require('path');
|
||||
const { getProjectIdentity } = require('./config');
|
||||
|
||||
const CONTEXT_META_KEY = 'io.funplay.cocos/context';
|
||||
|
||||
function projectEndpoint(projectIdentity) {
|
||||
return projectIdentity ? `/mcp/project/${encodeURIComponent(projectIdentity)}/` : '/';
|
||||
}
|
||||
|
||||
function serverUrl(config, port = config.port, identity) {
|
||||
const host = String(config.host || '127.0.0.1');
|
||||
const authority = host.includes(':') && !host.startsWith('[') ? `[${host}]` : host;
|
||||
const project = identity === undefined ? (config.projectPath ? getProjectIdentity(config.projectPath) : '') : identity;
|
||||
return `http://${authority}:${port}${projectEndpoint(project)}`;
|
||||
}
|
||||
|
||||
function projectContext({ projectIdentity, projectPath, instanceId }) {
|
||||
return {
|
||||
project_id: projectIdentity || '',
|
||||
project_path: projectPath ? path.resolve(projectPath) : '',
|
||||
instance_id: instanceId,
|
||||
expected_context: `${projectIdentity || ''}:${instanceId}`,
|
||||
};
|
||||
}
|
||||
|
||||
function requestRoute(pathname, identity) {
|
||||
const legacy = { '/': 'rpc', '/mcp': 'rpc', '/mcp/': 'rpc', '/health': 'health', '/tools': 'tools' };
|
||||
if (Object.prototype.hasOwnProperty.call(legacy, pathname)) return { kind: legacy[pathname], scoped: false };
|
||||
const match = /^\/mcp\/project\/([^/]+)(?:\/(health|tools))?\/?$/.exec(pathname);
|
||||
if (!match) return { error: 'ENDPOINT_NOT_FOUND', status: 404 };
|
||||
let project;
|
||||
try { project = decodeURIComponent(match[1]); } catch (error) { return { error: 'ENDPOINT_NOT_FOUND', status: 404 }; }
|
||||
if (!identity || project !== identity) return { error: 'PROJECT_CONTEXT_MISMATCH', status: 409 };
|
||||
return { kind: match[2] || 'rpc', scoped: true, project };
|
||||
}
|
||||
|
||||
function expectedContext(params = {}) {
|
||||
const fromMeta = params._meta && params._meta.expected_context;
|
||||
const fromArgs = params.arguments && params.arguments.expected_context;
|
||||
if (fromMeta !== undefined && fromArgs !== undefined && fromMeta !== fromArgs) {
|
||||
return { error: 'PROJECT_CONTEXT_MISMATCH' };
|
||||
}
|
||||
const token = fromMeta === undefined ? fromArgs : fromMeta;
|
||||
if (token !== undefined && (typeof token !== 'string' || !token)) return { error: 'PROJECT_CONTEXT_MISMATCH' };
|
||||
return { token };
|
||||
}
|
||||
|
||||
function contextError(context, params, { scoped = false, readOnly = false } = {}) {
|
||||
const expected = expectedContext(params);
|
||||
if (expected.error) return expected.error;
|
||||
if (expected.token !== undefined && expected.token !== context.expected_context) {
|
||||
return expected.token.split(':')[0] === context.project_id ? 'EDITOR_INSTANCE_CHANGED' : 'PROJECT_CONTEXT_MISMATCH';
|
||||
}
|
||||
return !scoped && !readOnly && !expected.token ? 'PROJECT_CONTEXT_REQUIRED' : null;
|
||||
}
|
||||
|
||||
function withContextSchema(tool) {
|
||||
return { ...tool, inputSchema: { ...tool.inputSchema, properties: {
|
||||
...tool.inputSchema && tool.inputSchema.properties,
|
||||
expected_context: { type: 'string', description: 'Optional Editor-session pin from initialize.funplay.context after independently verifying the intended project. Required for mutating calls through legacy unscoped URLs.' },
|
||||
} } };
|
||||
}
|
||||
|
||||
module.exports = { CONTEXT_META_KEY, projectEndpoint, serverUrl, projectContext, requestRoute, contextError, withContextSchema };
|
||||
@@ -0,0 +1,419 @@
|
||||
'use strict';
|
||||
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const { resolveProjectFilePath: resolveProjectPath } = require('./path-safety');
|
||||
const { readOptionalText, writeTextIfUnchanged } = require('./atomic-file');
|
||||
const { getSkillsDirectory, getSkillProjectPath } = require('./skill-platforms');
|
||||
|
||||
const KNOWN_INSTRUCTION_PATHS = [
|
||||
'AGENTS.md',
|
||||
'CLAUDE.md',
|
||||
'GEMINI.md',
|
||||
'.cursorrules',
|
||||
'.windsurfrules',
|
||||
'.github/copilot-instructions.md',
|
||||
];
|
||||
|
||||
const COCOS_MCP_SKILL_NAME = 'funplay-cocos-mcp-workflow';
|
||||
const COCOS_MCP_SKILL_TITLE = 'Funplay Cocos MCP Workflow';
|
||||
const LEGACY_COCOS_MCP_SKILL_DESCRIPTION =
|
||||
'Use this skill when editing, validating, or debugging this Cocos Creator project through Funplay Cocos MCP.';
|
||||
const COCOS_MCP_SKILL_DESCRIPTION =
|
||||
'Edit, inspect, validate, preview, and debug Cocos Creator projects through Funplay Cocos MCP. Use when working with scenes, nodes, prefabs, assets, TypeScript, logs, screenshots, preview behavior, runtime state, or MCP connectivity.';
|
||||
const COCOS_MCP_SKILL_INSTRUCTIONS = [
|
||||
'## Operating Loop',
|
||||
'',
|
||||
'1. Establish context.',
|
||||
' - Before writes, independently match the intended project to initialize.funplay.context; do not adopt whichever server answered. For old endpoints, reconnects, or frame-paced gestures, read [project identity and input](references/project-identity-and-input.md).',
|
||||
' - Read `cocos://project/context` or call `get_editor_state` before assuming the project, active scene, MCP URL, selection, visible windows, or tool profile.',
|
||||
' - Inspect the active scene with `get_scene_info` and `get_hierarchy`; use `get_selection`, `list_scenes`, `list_assets`, or `list_prefabs` when identity or ownership is unclear.',
|
||||
' - Treat user-provided node and asset names as hints. Resolve the real hierarchy path, node UUID, asset UUID, or `db://assets/...` URL before editing.',
|
||||
' - Call `get_tool_catalog` when a required tool may be hidden by the `core`, `full`, or custom exposure profile.',
|
||||
'2. Choose the edit surface.',
|
||||
' - Edit TypeScript and ordinary project files with repository tools or the MCP file tools, then refresh the affected asset and run diagnostics.',
|
||||
' - Edit live scene nodes with focused scene/component tools or `execute_javascript` using `context="scene"`; save the scene when the change must persist.',
|
||||
' - Use `execute_javascript` with `context="editor"` for asset-db, Editor messages, project orchestration, and filesystem work that belongs in the editor process.',
|
||||
' - Inspect prefab ownership and references before mutation. Prefer focused prefab tools, or edit a verified linked instance and apply it back through the editor workflow.',
|
||||
' - Preserve an existing UI or gameplay prefab hierarchy and change only the necessary nodes, components, and serialized fields; do not rebuild the entire prefab unless explicitly requested.',
|
||||
'3. Execute the smallest coherent change.',
|
||||
' - Prefer one guarded `execute_javascript` operation for tightly related editor work, but use focused tools when they provide clearer validation or safer arguments.',
|
||||
' - Keep JavaScript safety checks enabled unless the code and its paths were reviewed explicitly.',
|
||||
' - Null-check every scene, node, component, asset, and filesystem lookup. Return concise structured before/after values, including stable UUIDs or asset URLs where useful.',
|
||||
' - Save or refresh only the assets and scenes intentionally changed.',
|
||||
' - Do not guess alternate paths, silently create replacement objects, or run self-healing fallback loops after a missing reference or unsupported editor message.',
|
||||
'4. Read back and validate.',
|
||||
' - Re-inspect the exact node, component, prefab instance, or asset after mutation; a successful command response alone is not proof of the final editor state.',
|
||||
' - Run `run_script_diagnostics` or `get_script_diagnostic_context` after TypeScript changes, then use `validate_scene` and project logs before claiming success.',
|
||||
' - For visual or runtime work, run the appropriate browser, Game View, or simulator preview and verify with runtime state, input, logs, and screenshots.',
|
||||
' - State exactly what was verified and what still requires a native build, device, network, store, or manual check.',
|
||||
'',
|
||||
'## Scene, Prefab, and Asset Safety',
|
||||
'',
|
||||
'- Do not treat Cocos `.scene`, `.prefab`, or `.meta` files as ordinary text. Prefer scene-process, prefab, and asset-db operations that preserve UUID references and editor import state.',
|
||||
'- If `edit_prefab_json` is used, target a verified prefab path and the smallest exact JSON path or literal replacement, then run `validate_prefab_references` and inspect the result.',
|
||||
'- Before structural prefab work, call `inspect_prefab`; for scene instances, call `inspect_prefab_instance` and choose deliberately between apply and revert.',
|
||||
'- Replacing a prefab at the same path can keep the asset UUID while changing internal object IDs and breaking serialized references, animation tracks, nested prefab links, and scene overrides.',
|
||||
'- Inspect dependencies with `inspect_asset_dependencies` and validate them with `validate_asset_dependencies` before and after sensitive asset changes.',
|
||||
'- Never copy a `.meta` file when duplicating an asset. Use `duplicate_prefab` or asset-db operations so the new asset receives its own UUID.',
|
||||
'',
|
||||
'## Tool Exposure and Execution Contexts',
|
||||
'',
|
||||
'- The default `core` profile exposes the main inspection, diagnostics, logs, screenshots, scene, asset, and unified JavaScript workflow.',
|
||||
'- The `full` profile adds focused mutation tools for nodes, components, prefabs, UI, runtime control, input simulation, files, and project preview.',
|
||||
'- If a named tool is unavailable under a custom profile, adapt to the exposed catalog and report the missing capability instead of pretending it ran.',
|
||||
'- In scene context, use the Cocos runtime and scene APIs for live hierarchy and component work. In editor context, use `Editor` APIs and messages for asset-db and extension orchestration.',
|
||||
'- Use `execute_scene_script` and `execute_editor_script` only as compatibility entrypoints; prefer `execute_javascript` with an explicit context for new workflows.',
|
||||
'',
|
||||
'## Readiness and Preview Evidence',
|
||||
'',
|
||||
'- For imports, scripts, preview startup, calibrated input, or persistence checks, read [project readiness](references/project-readiness.md). Do not load this conditional reference for an unrelated inspection.',
|
||||
'- `check_asset_ready` checks stable AssetDB identity, not script compilation or runtime loading. Discover its exposure before use.',
|
||||
'- `get_runtime_state` describes the editor Game View and toolbar, not browser/simulator runtime or edit-scene counters.',
|
||||
'- Read `get_recent_logs` or `search_project_logs` for relevant errors. Do not clear persistent logs without explicit confirmation.',
|
||||
'',
|
||||
'## Failure Handling',
|
||||
'',
|
||||
'- If MCP is unreachable, limit claims to safe filesystem inspection or code edits; do not claim scene, prefab, editor, preview, or runtime verification.',
|
||||
'- If a node lookup is ambiguous, return the matching paths and UUIDs and choose only after identifying the user-visible or prefab-owned target.',
|
||||
'- If editor readback and serialized text disagree, trust editor and asset-db readback first and investigate whether the wrong asset, scene instance, or stale import was inspected.',
|
||||
'- Fix diagnostics or new error logs caused by the change before visual or runtime validation.',
|
||||
].join('\n');
|
||||
|
||||
const COCOS_UI_SKILL_NAME = 'funplay-cocos-ui-composition';
|
||||
const COCOS_UI_SKILL_TITLE = 'Funplay Cocos UI Composition';
|
||||
const COCOS_UI_SKILL_DESCRIPTION =
|
||||
'Build and revise responsive Cocos Creator UI, and turn full-page design images into editable prefabs with reusable sprites, layout adaptation, and visual fidelity checks. Use for Canvas layout, prefabs, scrolling, text, input, and UI validation.';
|
||||
const COCOS_UI_SKILL_INSTRUCTIONS = [
|
||||
'For MCP writes, reconnects, or interactive drag tests, read [project identity and input](references/project-identity-and-input.md). Renderer frames are not native Game View engine updates or gameplay acceptance.',
|
||||
'',
|
||||
"## UI Workflow",
|
||||
"",
|
||||
"1. Inspect the active scene, Canvas, design resolution, target viewports, `UITransform`, `Widget`, `Layout`, existing `SafeArea` policy, prefab ownership and serialized references.",
|
||||
"2. Preserve the user's design requirements and established project baseline. A full-page reference may define a new screen's baseline; clarify cropped or conflicting references instead of imposing a fixed resolution.",
|
||||
"3. Preserve existing roots, node/component identities, event bindings, animation targets and nested prefabs. Change only what the request requires; do not rebuild the entire prefab unless explicitly requested.",
|
||||
"4. Choose one owner for each position/size property. Avoid conflicting Widget, Layout, animation and manual writes. Use supported Cocos scene/prefab/AssetDB workflows for authored assets.",
|
||||
"5. Read back exact dimensions, anchors, constraints, SpriteFrame/font references and event bindings. Save/reopen when persistence matters; use preview input and screenshots for visual or interaction claims.",
|
||||
"",
|
||||
"## Design Fidelity",
|
||||
"",
|
||||
"- Preserve authored spacing and the project's adaptation. Do not proactively add SafeArea containers, adaptation scripts or extra insets. New adaptation requires an explicit request or a demonstrated overlap confirmed with the user.",
|
||||
"- Keep complete UI pages in saved prefabs when that fits the project; runtime hierarchy creation is not a substitute for requested authored UI.",
|
||||
"- A tool response, hierarchy, edit-scene performance counter and screenshot prove different things. Report unverified runtime, device, glyph or business behavior explicitly.",
|
||||
"",
|
||||
"## Read Only the Relevant References",
|
||||
"",
|
||||
"- For a complete design image or screenshot to editable UI, including asset splitting, shared controls, and fidelity acceptance, start with [image to prefab](references/image-to-prefab.md).",
|
||||
"- For resolution, orientation, SafeArea, Widget/Layout, scrolling or masks: [layout and adaptation](references/layout-and-adaptation.md).",
|
||||
"- For SpriteFrames, nine-slice, atlas or importer edits: [sprites and importers](references/sprites-and-importers.md).",
|
||||
"- For fonts, text overflow, glyph coverage or requested localization: [text and localization](references/text-and-localization.md).",
|
||||
"- For event bindings, real input, animation, screenshots or performance evidence: [input and validation](references/input-and-validation.md).",
|
||||
"",
|
||||
"These references are conditional; do not load every file for a focused edit.",
|
||||
].join('\n');
|
||||
|
||||
function normalizeSkillName(value) {
|
||||
const normalized = String(value || '')
|
||||
.trim()
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9]+/g, '-')
|
||||
.replace(/^-+|-+$/g, '')
|
||||
.slice(0, 63)
|
||||
.replace(/-+$/g, '');
|
||||
if (!normalized) {
|
||||
throw new Error('skillName is required.');
|
||||
}
|
||||
return normalized;
|
||||
}
|
||||
|
||||
function statFile(filePath) {
|
||||
try {
|
||||
return fs.statSync(filePath);
|
||||
} catch (error) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function decodeYamlScalar(value) {
|
||||
const text = String(value || '').trim();
|
||||
if (!text) {
|
||||
return '';
|
||||
}
|
||||
if (text.startsWith('"')) {
|
||||
try {
|
||||
return JSON.parse(text);
|
||||
} catch (error) {
|
||||
return text.slice(1, text.endsWith('"') ? -1 : undefined);
|
||||
}
|
||||
}
|
||||
if (text.startsWith("'") && text.endsWith("'")) {
|
||||
return text.slice(1, -1).replace(/''/g, "'");
|
||||
}
|
||||
return text;
|
||||
}
|
||||
|
||||
function parseSkillMetadata(content) {
|
||||
const text = String(content || '');
|
||||
const frontmatter = /^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/.exec(text);
|
||||
if (frontmatter) {
|
||||
const values = {};
|
||||
for (const line of frontmatter[1].split(/\r?\n/)) {
|
||||
const match = /^([A-Za-z0-9_-]+):\s*(.*)$/.exec(line);
|
||||
if (match) {
|
||||
values[match[1]] = decodeYamlScalar(match[2]);
|
||||
}
|
||||
}
|
||||
const name = String(values.name || '').trim();
|
||||
const description = String(values.description || '').trim();
|
||||
const validName = /^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(name) && name.length <= 63;
|
||||
const validDescription = Boolean(
|
||||
description && description.length <= 1024 && !/[<>]/.test(description)
|
||||
);
|
||||
return {
|
||||
name,
|
||||
description,
|
||||
format: 'frontmatter',
|
||||
valid: validName && validDescription,
|
||||
};
|
||||
}
|
||||
|
||||
const title = /^#\s+(.+)$/m.exec(text);
|
||||
const description = /^Description:\s*(.+)$/m.exec(text);
|
||||
return {
|
||||
name: '',
|
||||
description: description ? description[1].trim() : '',
|
||||
title: title ? title[1].trim() : '',
|
||||
format: title || description ? 'legacy' : 'unknown',
|
||||
valid: false,
|
||||
};
|
||||
}
|
||||
|
||||
function buildProjectSkillContent(options = {}) {
|
||||
const skillName = normalizeSkillName(options.skillName);
|
||||
const title = String(options.title || '').trim() || skillName;
|
||||
const description = String(options.description || '').trim() || `Project-specific workflow for ${title}.`;
|
||||
if (description.length > 1024) {
|
||||
throw new Error('Skill description must be 1024 characters or fewer.');
|
||||
}
|
||||
if (/[<>]/.test(description)) {
|
||||
throw new Error('Skill description cannot contain angle brackets.');
|
||||
}
|
||||
const body = String(options.instructions || '').trim() || [
|
||||
`Use this skill for ${title} work in this Cocos project.`,
|
||||
'',
|
||||
'- Inspect the active scene and project context before editing.',
|
||||
'- Prefer focused MCP tools before broad manual file edits.',
|
||||
'- Run relevant validation tools after changes.',
|
||||
].join('\n');
|
||||
|
||||
return [
|
||||
'---',
|
||||
`name: ${skillName}`,
|
||||
`description: ${JSON.stringify(description)}`,
|
||||
'---',
|
||||
'',
|
||||
`# ${title}`,
|
||||
'',
|
||||
'## Instructions',
|
||||
'',
|
||||
body,
|
||||
'',
|
||||
].join('\n');
|
||||
}
|
||||
|
||||
function buildCocosMcpProjectSkillContent(options = {}) {
|
||||
return buildProjectSkillContent({
|
||||
skillName: options.skillName || COCOS_MCP_SKILL_NAME,
|
||||
title: options.title || COCOS_MCP_SKILL_TITLE,
|
||||
description: options.description || COCOS_MCP_SKILL_DESCRIPTION,
|
||||
instructions: String(options.instructions || '').trim() || COCOS_MCP_SKILL_INSTRUCTIONS,
|
||||
});
|
||||
}
|
||||
|
||||
function buildCocosUiProjectSkillContent(options = {}) {
|
||||
return buildProjectSkillContent({
|
||||
skillName: options.skillName || COCOS_UI_SKILL_NAME,
|
||||
title: options.title || COCOS_UI_SKILL_TITLE,
|
||||
description: options.description || COCOS_UI_SKILL_DESCRIPTION,
|
||||
instructions: String(options.instructions || '').trim() || COCOS_UI_SKILL_INSTRUCTIONS,
|
||||
});
|
||||
}
|
||||
|
||||
function buildLegacyCocosMcpProjectSkillContent(options = {}) {
|
||||
const instructions = [
|
||||
'- Start by reading `cocos://project/context` or calling `get_editor_state` to confirm the active project, scene, server URL, and tool profile.',
|
||||
'- Prefer `execute_javascript` for high-level scene/editor orchestration, but keep safety checks enabled unless the code was reviewed.',
|
||||
'- Use focused tools when they are better primitives: `list_assets`, `inspect_asset_dependencies`, `validate_asset_dependencies`, `run_script_diagnostics`, `get_script_diagnostic_context`, and screenshot tools.',
|
||||
'- For UI work, inspect the active Canvas/hierarchy first, mutate the smallest necessary node/component set, then verify with `validate_scene` and a screenshot.',
|
||||
...(options.includePrefabPreservationRule ? [
|
||||
'- When modifying a UI or gameplay-object prefab, preserve the existing prefab and edit only the necessary nodes/components; do not rebuild the entire prefab unless explicitly requested.',
|
||||
] : []),
|
||||
'- For prefab or asset edits, inspect dependencies/references before mutation and refresh assets afterward.',
|
||||
'- When changing tool exposure, save a named tool profile so the same client setup can be restored later.',
|
||||
].join('\n');
|
||||
return [
|
||||
`# ${COCOS_MCP_SKILL_TITLE}`,
|
||||
'',
|
||||
`Description: ${LEGACY_COCOS_MCP_SKILL_DESCRIPTION}`,
|
||||
'',
|
||||
'## Instructions',
|
||||
instructions,
|
||||
'',
|
||||
].join('\n');
|
||||
}
|
||||
|
||||
function listSkillFiles(projectPath, options = {}) {
|
||||
projectPath = getSkillProjectPath(projectPath, options);
|
||||
const skillRoot = resolveProjectPath(projectPath, getSkillsDirectory(options));
|
||||
if (!fs.existsSync(skillRoot)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const skills = [];
|
||||
const stack = [skillRoot];
|
||||
while (stack.length) {
|
||||
const current = stack.pop();
|
||||
for (const entry of fs.readdirSync(current, { withFileTypes: true })) {
|
||||
const fullPath = resolveProjectPath(projectPath, path.join(current, entry.name));
|
||||
if (entry.isDirectory()) {
|
||||
stack.push(fullPath);
|
||||
continue;
|
||||
}
|
||||
if (entry.name === 'SKILL.md') {
|
||||
const stat = statFile(fullPath);
|
||||
const metadata = parseSkillMetadata(fs.readFileSync(fullPath, 'utf8'));
|
||||
skills.push({
|
||||
path: path.relative(projectPath, fullPath).replace(/\\/g, '/'),
|
||||
size: stat ? stat.size : 0,
|
||||
mtime: stat ? stat.mtime.toISOString() : '',
|
||||
name: metadata.name || path.basename(path.dirname(fullPath)),
|
||||
title: metadata.title || '',
|
||||
description: metadata.description,
|
||||
format: metadata.format,
|
||||
valid: metadata.valid,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
return skills.sort((left, right) => left.path.localeCompare(right.path));
|
||||
}
|
||||
|
||||
function listProjectInstructions(projectPath, options = {}) {
|
||||
projectPath = getSkillProjectPath(projectPath, options);
|
||||
const files = [];
|
||||
for (const relativePath of KNOWN_INSTRUCTION_PATHS) {
|
||||
const fullPath = resolveProjectPath(projectPath, relativePath);
|
||||
const stat = statFile(fullPath);
|
||||
if (stat && stat.isFile()) {
|
||||
files.push({
|
||||
path: relativePath,
|
||||
size: stat.size,
|
||||
mtime: stat.mtime.toISOString(),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
files,
|
||||
skills: listSkillFiles(projectPath, options),
|
||||
};
|
||||
}
|
||||
|
||||
function readProjectInstruction(projectPath, target) {
|
||||
const relativePath = String(target || '').trim();
|
||||
if (!relativePath) {
|
||||
throw new Error('target is required.');
|
||||
}
|
||||
const fullPath = resolveProjectPath(projectPath, relativePath);
|
||||
if (!fs.existsSync(fullPath) || !fs.statSync(fullPath).isFile()) {
|
||||
throw new Error(`Instruction file not found: ${relativePath}`);
|
||||
}
|
||||
return {
|
||||
path: relativePath,
|
||||
content: fs.readFileSync(fullPath, 'utf8'),
|
||||
};
|
||||
}
|
||||
|
||||
function writeProjectInstruction(projectPath, options = {}) {
|
||||
const relativePath = String(options.target || '').trim();
|
||||
if (!relativePath) {
|
||||
throw new Error('target is required.');
|
||||
}
|
||||
const content = String(options.content || '');
|
||||
const fullPath = resolveProjectPath(projectPath, relativePath);
|
||||
const original = Object.prototype.hasOwnProperty.call(options, 'expectedContent') ? options.expectedContent : readOptionalText(fullPath);
|
||||
if (original !== null && options.overwrite === false) {
|
||||
throw new Error(`Instruction file already exists: ${relativePath}`);
|
||||
}
|
||||
writeTextIfUnchanged(fullPath, content, original);
|
||||
const stat = fs.statSync(fullPath);
|
||||
return {
|
||||
written: true,
|
||||
path: relativePath,
|
||||
size: stat.size,
|
||||
mtime: stat.mtime.toISOString(),
|
||||
};
|
||||
}
|
||||
|
||||
function createProjectSkill(projectPath, options = {}) {
|
||||
projectPath = getSkillProjectPath(projectPath, options);
|
||||
const skillName = normalizeSkillName(options.skillName);
|
||||
const relativePath = `${getSkillsDirectory(options)}/${skillName}/SKILL.md`;
|
||||
const content = buildProjectSkillContent({ ...options, skillName });
|
||||
return writeProjectInstruction(projectPath, {
|
||||
target: relativePath,
|
||||
content,
|
||||
overwrite: options.overwrite !== false,
|
||||
});
|
||||
}
|
||||
|
||||
function createCocosMcpProjectSkill(projectPath, options = {}) {
|
||||
return createManagedProjectSkill(projectPath, COCOS_MCP_SKILL_NAME, options);
|
||||
}
|
||||
|
||||
function createCocosUiProjectSkill(projectPath, options = {}) {
|
||||
return createManagedProjectSkill(projectPath, COCOS_UI_SKILL_NAME, options);
|
||||
}
|
||||
|
||||
function createManagedProjectSkill(projectPath, templateSkillName, options) {
|
||||
projectPath = getSkillProjectPath(projectPath, options);
|
||||
const skillName = normalizeSkillName(options.skillName || templateSkillName);
|
||||
const target = `${getSkillsDirectory(options)}/${skillName}/SKILL.md`;
|
||||
if (options.overwrite === false && fs.existsSync(resolveProjectPath(projectPath, target))) {
|
||||
throw new Error(`Instruction file already exists: ${target}`);
|
||||
}
|
||||
// Lazy import avoids a cycle: the manager uses the pure content builders above.
|
||||
const result = require('./project-skills').updateBuiltInProjectSkill(projectPath, {
|
||||
...options, skillName, templateSkillName, allowModified: options.overwrite !== false,
|
||||
});
|
||||
return {
|
||||
...(result.write || { written: false, path: result.state.path }),
|
||||
manifest: result.manifest || result.state.manifest.path,
|
||||
references: result.references || result.state.references.map((file) => file.path),
|
||||
backup: result.backup || null,
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
COCOS_MCP_SKILL_DESCRIPTION,
|
||||
COCOS_MCP_SKILL_INSTRUCTIONS,
|
||||
COCOS_MCP_SKILL_NAME,
|
||||
COCOS_MCP_SKILL_TITLE,
|
||||
COCOS_UI_SKILL_DESCRIPTION,
|
||||
COCOS_UI_SKILL_INSTRUCTIONS,
|
||||
COCOS_UI_SKILL_NAME,
|
||||
COCOS_UI_SKILL_TITLE,
|
||||
KNOWN_INSTRUCTION_PATHS,
|
||||
buildCocosMcpProjectSkillContent,
|
||||
buildCocosUiProjectSkillContent,
|
||||
buildLegacyCocosMcpProjectSkillContent,
|
||||
buildProjectSkillContent,
|
||||
createCocosMcpProjectSkill,
|
||||
createCocosUiProjectSkill,
|
||||
createProjectSkill,
|
||||
listProjectInstructions,
|
||||
normalizeSkillName,
|
||||
parseSkillMetadata,
|
||||
readProjectInstruction,
|
||||
writeProjectInstruction,
|
||||
};
|
||||
@@ -0,0 +1,77 @@
|
||||
'use strict';
|
||||
|
||||
const fs = require('fs');
|
||||
const { resolveProjectFilePath: resolveProjectPath } = require('./path-safety');
|
||||
|
||||
const PROMPT_DIRECTORY = 'mcp-prompts';
|
||||
const MAX_PROMPT_FILES = 100;
|
||||
const MAX_PROMPT_BYTES = 256 * 1024;
|
||||
const IDENTIFIER = /^[a-z][a-z0-9_-]{0,63}$/;
|
||||
|
||||
function parseProjectPrompt(content) {
|
||||
const match = String(content).replace(/^\uFEFF/, '').replace(/\r\n?/g, '\n')
|
||||
.match(/^---[ \t]*\n([\s\S]*?)\n---[ \t]*\n([\s\S]*)$/);
|
||||
if (!match) throw new Error('Expected a --- frontmatter block followed by a prompt body.');
|
||||
const fields = Object.create(null);
|
||||
for (const line of match[1].split('\n')) {
|
||||
if (!line.trim() || line.trim().startsWith('#')) continue;
|
||||
const field = line.match(/^([a-z]+):[ \t]*(.*)$/);
|
||||
if (!field || !['name', 'description', 'arguments'].includes(field[1])) throw new Error(`Unsupported frontmatter line: ${line}`);
|
||||
if (Object.prototype.hasOwnProperty.call(fields, field[1])) throw new Error(`Duplicate field: ${field[1]}`);
|
||||
fields[field[1]] = field[2].trim();
|
||||
}
|
||||
if (!IDENTIFIER.test(fields.name || '')) throw new Error('Invalid prompt name. Use lowercase letters, digits, hyphens or underscores (1–64 characters).');
|
||||
if ((fields.description || '').length > 512) throw new Error('Description exceeds 512 characters.');
|
||||
const body = match[2].trim();
|
||||
if (!body) throw new Error('Prompt body is empty.');
|
||||
const names = new Set();
|
||||
const args = fields.arguments ? fields.arguments.split(',').map((value) => {
|
||||
const arg = value.trim().match(/^([a-z][a-z0-9_-]{0,63})(\(required\))?$/);
|
||||
if (!arg) throw new Error(`Invalid argument declaration: ${value}`);
|
||||
if (names.has(arg[1])) throw new Error(`Duplicate argument: ${arg[1]}`);
|
||||
names.add(arg[1]);
|
||||
return { name: arg[1], description: arg[1], required: Boolean(arg[2]) };
|
||||
}) : [];
|
||||
return { name: fields.name, description: fields.description || fields.name, arguments: args, body };
|
||||
}
|
||||
|
||||
function loadProjectPrompts(projectPath, reservedNames = []) {
|
||||
const prompts = [];
|
||||
const warnings = [];
|
||||
if (!projectPath) return { prompts, warnings };
|
||||
try {
|
||||
const directory = resolveProjectPath(projectPath, PROMPT_DIRECTORY);
|
||||
if (!fs.existsSync(directory)) return { prompts, warnings };
|
||||
if (fs.lstatSync(directory).isSymbolicLink()) throw new Error('The mcp-prompts directory must not be a symbolic link.');
|
||||
const files = fs.readdirSync(directory, { withFileTypes: true })
|
||||
.filter((entry) => entry.name.endsWith('.md')).sort((a, b) => a.name.localeCompare(b.name));
|
||||
if (files.length > MAX_PROMPT_FILES) warnings.push(`Only the first ${MAX_PROMPT_FILES} Markdown files are loaded.`);
|
||||
const seen = new Set(reservedNames.map((name) => name.toLowerCase()));
|
||||
for (const entry of files.slice(0, MAX_PROMPT_FILES)) {
|
||||
try {
|
||||
if (!entry.isFile()) throw new Error('Only regular files are supported; symbolic links are skipped.');
|
||||
const filePath = resolveProjectPath(projectPath, `${PROMPT_DIRECTORY}/${entry.name}`);
|
||||
if (fs.statSync(filePath).size > MAX_PROMPT_BYTES) throw new Error(`File exceeds ${MAX_PROMPT_BYTES} bytes.`);
|
||||
const prompt = parseProjectPrompt(fs.readFileSync(filePath, 'utf8'));
|
||||
if (seen.has(prompt.name.toLowerCase())) throw new Error(`Duplicate or reserved prompt name: ${prompt.name}`);
|
||||
seen.add(prompt.name.toLowerCase());
|
||||
prompts.push(prompt);
|
||||
} catch (error) {
|
||||
warnings.push(`${entry.name}: ${error.message}`);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
warnings.push(error.message);
|
||||
}
|
||||
return { prompts, warnings };
|
||||
}
|
||||
|
||||
function interpolatePrompt(body, args, declarations) {
|
||||
const allowed = new Set(declarations.map((arg) => arg.name));
|
||||
// One pass: placeholders inside argument values are data, not more template syntax.
|
||||
return body.replace(/\{([a-z][a-z0-9_-]{0,63})\}/g, (original, name) => (
|
||||
allowed.has(name) ? (Object.prototype.hasOwnProperty.call(args, name) ? args[name] : '') : original
|
||||
));
|
||||
}
|
||||
|
||||
module.exports = { PROMPT_DIRECTORY, MAX_PROMPT_FILES, MAX_PROMPT_BYTES, parseProjectPrompt, loadProjectPrompts, interpolatePrompt };
|
||||
@@ -0,0 +1,161 @@
|
||||
'use strict';
|
||||
|
||||
// Original Cocos-specific guidance, exported beside each client's SKILL.md.
|
||||
// Entrypoints route here only when the corresponding kind of work is requested.
|
||||
const WORKFLOW_REFERENCES = Object.freeze({
|
||||
'references/project-readiness.md': `# Project, import, and preview readiness
|
||||
|
||||
## Asset and script changes
|
||||
|
||||
- Resolve the exact AssetDB UUID or db:// URL. Refresh only the changed source assets; do not guess an extension or silently substitute another asset.
|
||||
- Import is asynchronous. If exposed, use \`check_asset_ready\` with the exact target after refresh/import and before assigning the asset or attaching its script. A stable imported UUID/URL identity is not proof that the importer queue is empty, TypeScript compiled, or the preview loaded those bytes.
|
||||
- \`check_asset_ready\` is a Full-profile read-only tool. Discover exposure with \`get_tool_catalog\`; do not change a custom allowlist without authorization. If unavailable, query exact asset info and report the narrower evidence instead of claiming full readiness.
|
||||
- After TypeScript edits, run \`run_script_diagnostics\` and inspect import/preview errors. Its no-emit compiler result is separate from Creator's compilation and preview loading.
|
||||
- A zero-wait readiness query is one observation, not stable readiness. Busy, missing, importing, timeout, unavailable, and unknown results are not success. Wait within a bounded budget or report the unresolved state; never repeat a mutation to obtain a cleaner response.
|
||||
- Check APIs against the actual Creator version and loaded project components, not only a package.json declaration. Preserve existing dependencies and project conventions.
|
||||
|
||||
## Preview evidence
|
||||
|
||||
- Query \`get_preview_mode\` before choosing browser, editor Game View, or simulator. Browser \`localUrl\` is same-host; \`networkUrl\` is Creator's LAN address.
|
||||
- \`get_runtime_state\`, pause, and resume address the editor Game View and its native toolbar. They do not inspect external browser/simulator runtime state. Edit-scene director counters and time scale are not Game View state.
|
||||
- A listening MCP server, opened window, non-empty screenshot, current scene drawing, and correct business behavior are different claims. Verify only the layers relevant to the user's request and identify missing evidence.
|
||||
- Use \`capture_scene_screenshot\` for editor Scene composition and Game/preview capture for game output. For real pointer testing, bind \`simulate_mouse_click\` or drag to the returned \`captureId\` with \`coordinateSpace="image-pixels"\`; use coordinates from that exact image.
|
||||
- Recapture after a resize, zoom, reload, scene change, or stale-capture rejection. Do not scale coordinates from an unrelated/resized reference image yourself. Button event emission tests handlers but does not prove hit testing, clipping, focus, or occlusion.
|
||||
- If an input reports an unknown outcome, inspect the resulting state before deciding on another action. Do not automatically resend it. Restore only temporary state owned by this task; preserve user changes.
|
||||
|
||||
## Persistence
|
||||
|
||||
- Prefer scene-process, prefab, and AssetDB tools for .scene/.prefab/.meta changes. A successful native message alone does not prove saved content or preserved UUID links.
|
||||
- Reinspect the exact object and relevant serialized references, save only the requested changes, and reopen when persistence matters. Keep incomplete checks explicit.
|
||||
|
||||
Sources: [Creator messages](https://docs.cocos.com/creator/3.8/manual/en/editor/extension/messages.html) and [asset workflow](https://docs.cocos.com/creator/3.8/manual/en/asset/asset-workflow.html).\n`,
|
||||
});
|
||||
|
||||
const UI_REFERENCES = Object.freeze({
|
||||
'references/layout-and-adaptation.md': `# Layout and design fidelity
|
||||
|
||||
## Resolution and safe area
|
||||
|
||||
- User requirements and explicit design specifications take priority. Preserve an established project's design resolution and Fit Width/Fit Height policy unless a change is requested. For a new screen without a baseline, a full-page design image may define the baseline; a crop, conflicting images, or unclear intended dimensions need clarification. Do not impose a fixed phone resolution.
|
||||
- Keep authored spacing and full-bleed composition. Inspect existing SafeArea components and runtime adaptation before changing them. Do not proactively add SafeArea containers, adaptation scripts, extra margins, or a second inset; new adaptation needs an explicit request or a demonstrated overlap confirmed with the user.
|
||||
- If safe-area adaptation is requested, distinguish full-bleed art from critical controls and apply it once. Cocos SafeArea uses sys.getSafeAreaRect and Widget; preserve the project's existing ownership of position/size.
|
||||
- Separate Canvas adaptation from gameplay camera composition. Correct Widget constraints do not prove that the world camera shows the desired area.
|
||||
|
||||
## Property ownership
|
||||
|
||||
- UITransform owns contentSize and anchor point. Keep ordinary layout scale at one; change dimensions or constraints rather than stretching transforms to approximate a design.
|
||||
- Widget owns selected edges/centers and may overwrite position or size. Choose ONCE, ON_WINDOW_RESIZE, or ALWAYS from actual behavior; do not animate a property continuously rewritten by Widget.
|
||||
- Layout drives children or container according to ResizeMode. Putting Layout and Widget on the same node can create competing ownership. Read back driven sizes after layout settles; call updateLayout only when same-frame measurement is required.
|
||||
- Verify grid cell/constraint policy, padding, spacing, axis and growth direction. Keep nested layout chains shallow and batch repeated content changes.
|
||||
- Responsive region patterns are options, not permission to reorganize existing prefabs. Reposition only the regions needed by the requested aspect-ratio change; retain roots, identities, references and animation tracks.
|
||||
|
||||
## Scrolling and clipping
|
||||
|
||||
- Use a ScrollView root, masked view and content node. Verify the actual content reference, enabled axes, inertia/brake/bounce, child-button cancellation and nested scrolling.
|
||||
- Respect Mask renderer constraints and clipping boundaries. Do not add Sprite/Label renderers to a Mask node where its renderer is owned by the mask implementation.
|
||||
- Pool large repeated lists. Test first/last items, resize, overflow and dynamic content in preview; dimensions alone do not prove visibility or input.
|
||||
|
||||
Sources: [Widget](https://docs.cocos.com/creator/3.8/manual/en/ui-system/components/editor/widget.html), [Layout](https://docs.cocos.com/creator/3.8/manual/en/ui-system/components/editor/layout.html), [SafeArea](https://docs.cocos.com/creator/3.8/manual/en/ui-system/components/editor/safearea.html), [multi-resolution adaptation](https://docs.cocos.com/creator/3.8/manual/en/ui-system/components/engine/multi-resolution.html).\n`,
|
||||
'references/sprites-and-importers.md': `# SpriteFrames, nine-slice, and importer edits
|
||||
|
||||
- Resolve the source image, its .meta ownership and exact SpriteFrame subasset UUID before assignment or importer edits. Texture, ImageAsset and SpriteFrame are different asset types; never fabricate a subasset UUID.
|
||||
- Inspect source dimensions, rect/trim/rotation, cap insets, Sprite type, sizeMode and UITransform dimensions. Set CUSTOM sizeMode before assigning a SpriteFrame when authored dimensions must remain fixed, then read back the final size after assignment.
|
||||
- For sliced borders, retain source-coordinate insets and surviving SpriteFrame identities. Check that left+right and top+bottom fit the source rect and that corners/borders remain intact at the intended sizes. Do not derive importer coordinates from a downscaled screenshot.
|
||||
- Use focused importer/AssetDB operations when available. If a narrowly scoped .meta edit is necessary, preserve unrelated importer settings, UUIDs, submeta mappings and atlas references, refresh the exact source, and verify imported state. Do not recreate metadata or copy a .meta file to duplicate an asset.
|
||||
- Changing atlas membership, trimming or slicing can affect animation tracks, nested prefabs and material/batching behavior. Inspect incoming references before a structural change and report unsupported identity preservation rather than rebuilding references by name.
|
||||
- After import, \`check_asset_ready\` verifies only the imported AssetDB identity; inspect the actual SpriteFrame and saved component binding separately. Save/reopen when persistence is required and visually inspect corners at the target size.
|
||||
- Group compatible materials/textures only while preserving intended render order. Editor node/component counts are not a runtime draw-call or GPU measurement.
|
||||
|
||||
Sources: [Sprite](https://docs.cocos.com/creator/3.8/manual/en/ui-system/components/editor/sprite.html) and [image assets](https://docs.cocos.com/creator/3.8/manual/en/asset/image.html).\n`,
|
||||
'references/text-and-localization.md': `# Fonts, text sizing, and requested localization
|
||||
|
||||
- Preserve the project's font system: system font, imported TTF/OTF, bitmap font, RichText, or a project-specific localization component. Resolve font assets and their actual component bindings; do not replace the font strategy merely to silence a warning.
|
||||
- Verify fontSize, lineHeight, alignment, wrapping, contentSize, cacheMode and overflow at the intended viewport. CLAMP clips, SHRINK changes readable size and can cost CPU on dynamic text, and RESIZE_HEIGHT transfers height ownership to the label. Choose from project policy rather than applying SHRINK everywhere.
|
||||
- Check CJK, punctuation, digits, icons and other required glyphs in representative strings. Include line breaks, long translations and dynamic/code-composed strings when localization is requested. A successful string assignment does not establish glyph coverage or readability.
|
||||
- Bitmap-font atlas glyphs, character-cache capacity, fallback behavior and persisted font assets need separate checks. If coverage cannot be measured, report unknown rather than assuming all characters render.
|
||||
- For requested localization, identify the existing locale IDs and mapping, text keys, authored labels, runtime formatting and fallback policy. Change only requested languages/scope and preserve existing services; do not install an unrelated localization package by default.
|
||||
- Read back persisted font/text/localization references and representative outputs. Report covered, missing and unverified strings separately; inspecting authored labels does not prove coverage of runtime-generated text.
|
||||
- Capture representative languages and aspect ratios and inspect missing glyphs, clipping, wrapping and layout growth. Native/device performance and input-method behavior require corresponding platform evidence.
|
||||
|
||||
Sources: [Label](https://docs.cocos.com/creator/3.8/manual/en/ui-system/components/editor/label.html) and [font assets](https://docs.cocos.com/creator/3.8/manual/en/asset/font.html).\n`,
|
||||
'references/input-and-validation.md': `# Input, animation, and visual verification
|
||||
|
||||
- Verify Button/Toggle/Slider/EditBox target nodes, serialized component/handler/custom data, disabled state, hit area and focus behavior. Bind once; don't make duplicate listeners to compensate for an unresolved reference.
|
||||
- Emitting Button click events checks callbacks, not real pointer dispatch. For hit testing use the actual Game View/preview and calibrated screenshot coordinates; verify the resulting state or screenshot rather than treating event delivery as the business outcome.
|
||||
- Screenshot \`captureId\` identifies one image and its observed geometry. Use \`coordinateSpace="image-pixels"\` with coordinates in that exact PNG. Calibration maps to Electron content coordinates and rejects stale or changed targets. It does not identify a Button or prove absence of occlusion.
|
||||
- Keep UIOpacity, active state, Button interactability and BlockInputEvents consistent. A transparent modal may still block input; a visible scrim may not block anything. Check sibling order, masks and hidden states in preview.
|
||||
- Animate a Visual/Container child when Widget or Layout owns the root. Cancel/reconcile prior tweens, and verify deterministic position, scale, opacity, active state and close/reopen behavior. Use an explicit UI clock only if menus must animate during gameplay pause.
|
||||
- Test only requested interactions. An input with unknown delivery/outcome must be followed by readback, not automatic replay. Restore temporary preview state only if still owned by this task.
|
||||
- Use \`validate_scene\`, exact component/reference readback and screenshots as complementary evidence. A complete hierarchy or non-empty image does not prove correct layout, visible text, hit testing or business behavior.
|
||||
- \`get_performance_snapshot\` reports edit-scene node/component/UI/depth/memory counters, not browser/Game View draw calls or GPU performance. Use actual runtime/platform measurements before making performance claims.
|
||||
- Choose representative aspect ratios and locales for the target project. Record which checks passed, failed, were incomplete or require a device; avoid claiming universal validation from one screenshot.
|
||||
|
||||
Sources: [UI system](https://docs.cocos.com/creator/3.8/manual/en/2d-object/ui-system/) and [node hierarchy](https://docs.cocos.com/creator/3.8/manual/en/concepts/scene/node-tree.html).\n`,
|
||||
'references/image-to-prefab.md': `# From a full UI image to an editable Cocos prefab
|
||||
|
||||
Use this workflow for a new page or a set of switchable pages drawn in a user design. Work with the project's reusable artwork and the user's own designs and assets. For a third-party inspiration reference, create original visuals for the new UI.
|
||||
|
||||
## When image generation helps
|
||||
|
||||
Image generation is optional. Cocos MCP handles asset import, prefab composition, and preview verification. Any image generation or editing comes from a tool available in the AI client or the project's art pipeline.
|
||||
|
||||
- For a layered design, reuse its exported assets. For a flattened image, reuse clean cuts from visible regions and build text, dividers, and simple surfaces with native UI components. The reference can be analyzed by an image-capable client or described in a supplied component map.
|
||||
- If a complex background or icon is missing, or a UI element hides part of the background, use an available image generation or editing tool to produce just the missing asset. Specify its intended dimensions, silhouette, style, and transparency or bleed. Inspect the output at its intended size and mark generated artwork as an approximation until it passes the visual comparison.
|
||||
- With no generation tool, proceed with reusable assets and the layout that can be verified. If missing artwork blocks fidelity acceptance, request the corresponding clean background, transparent sprite, or layered design. Record any placeholder and the affected regions in the review.
|
||||
|
||||
## Lock the design and map the parts
|
||||
|
||||
- Keep each reference at its original pixel dimensions. Identify the game viewport, the selected page/tab, the locale, visible counter values, list scroll position, and relevant control states. Keep the reference and state record for comparison after implementation. If supplied pages disagree on a shared control, resolve the intended variant and record each deliberate departure from the references.
|
||||
- Use the existing Canvas policy in an established project. On a new page without a baseline, use the intended full viewport as the design basis. Map part bounds in top-left reference pixels, node paths, stacking order, anchors, and fixed or flexible edges. Distinguish visible artwork bounds from the control's layout box and hit area.
|
||||
- Record the chosen source for each part. Inspect cutouts, including their alpha edges and original padding, against the background they will actually use.
|
||||
|
||||
## Build the saved UI
|
||||
|
||||
- Keep the full reference image outside the rendered hierarchy. Import only the separately reusable art and use real SpriteFrames. Separate the background, title, button surfaces, icons, labels, badges, progress track/fill, and state overlays so each can move or change independently. Give text, dynamic values, and localization native text components. Reserve graphical lettering for artwork meant to stay fixed.
|
||||
- Share a navigation prefab or shell across related pages. Keep each tab's icon and caption separate from the normal and selected backgrounds and divider lines. Derive the highlight, tab widths, divider positions, label placement, and hit areas from the selected state and available width. Use nine-slice for stretchable surfaces with fixed corners. Keep icon proportions and intentional blank margins.
|
||||
- Author repeated lists as reusable rows in a ScrollView with a clipped viewport and Layout-managed content. Give each row separate art, text, and button bindings. Bind callbacks inside standalone prefab boundaries and use the project's normal events or controller bindings to connect them to a shell.
|
||||
- Save the UI under the existing Canvas with UI_2D layers. Use native prefab serialization, verify exact imported references, and confirm that assets survive reload or fresh instantiation. Consult [sprites and importers](sprites-and-importers.md) for trim/insets and [text and localization](text-and-localization.md) for font behavior. If an icon appears too large, check the imported trim and padding first. If a label clips, apply the font and overflow policy before setting the final box, then inspect the glyph baseline in preview.
|
||||
- Adapt regions independently. Use anchors for pinned controls, let the list viewport consume the remaining space, and crop flexible background art while preserving its aspect ratio. Keep a single owner for each driven dimension. Use [layout and adaptation](layout-and-adaptation.md) for the project's resize and safe-area policy.
|
||||
|
||||
## Verify fidelity in the actual preview
|
||||
|
||||
1. Capture the saved scene or prefab instance in the target Cocos preview. For fidelity, use a raw PNG of the same game viewport size and state as the reference. Check visible landmarks, the crop and the canvas size. Equal PNG dimensions alone can still conceal a cropped or zoomed capture.
|
||||
2. Compare at the same pixel coordinates. Review the whole page, then zoom into the mapped regions for icon silhouettes, alignment, text baselines, borders, shadow/alpha edges, and clipping. Use a side-by-side view and, when available, a same-scale overlay, wipe, or difference heatmap. Avoid shifting or stretching individual regions during comparison.
|
||||
3. Check node geometry and rendered appearance separately. Use runtime bounds projected into capture pixels for geometry. Use the visible pixels for glyphs, strokes, and artwork. Region color error, structural similarity, and tolerant edge overlap can help locate differences. Choose tolerances for the project before accepting results, and review each required region so a large matching background cannot hide a small control defect.
|
||||
4. Fix the source of each difference and recapture under the same conditions. A flat 1 px stroke may require a filled border or different pixel alignment. A matching node box can still contain the wrong sprite or state. Preserve the original design, captures, per-region results, and any approved variations for review.
|
||||
5. Check adaptation at the requested narrow and wide viewports with real pointer input. Exercise the in-scope page changes, button states, value updates, list scrolling and clipping using [input and validation](input-and-validation.md). Report the fidelity result for the baseline size and the adaptation/input results for the tested sizes. State any remaining mismatches or untested conditions.
|
||||
|
||||
For example, a shared bottom bar can have separate mapped regions for five icon silhouettes, the selected surface, a thin divider, and the full bar. At the reference size, check these independently. On a wider viewport, check that the highlight and lines follow the slots and that the same tabs respond to clicks. This catches trim and resize problems even when the page looks close in a thumbnail.
|
||||
\n`,
|
||||
});
|
||||
|
||||
function getProjectSkillReferences(skillName) {
|
||||
const templates = skillName === 'funplay-cocos-mcp-workflow' ? WORKFLOW_REFERENCES
|
||||
: skillName === 'funplay-cocos-ui-composition' ? UI_REFERENCES : {};
|
||||
const execution = `# Project identity and frame-paced input
|
||||
|
||||
## Before editing through MCP
|
||||
|
||||
Generated connections use /mcp/project/<project-id>/ on the existing project port. Independently compare initialize.funplay.context.project_path and project_id to the user's intended project. Context metadata identifies an extension/Editor lifetime, not authentication or permission to edit another project.
|
||||
|
||||
Legacy / and /mcp addresses still support initialization and exposed read-only tools. Mutating tools require expected_context from that verified initialization, either as a tool argument or params._meta.expected_context. A project-scoped URL binds the project; an explicit expected_context also pins the extension/Editor instance. Missing, wrong-project, conflicting or stale pins execute nothing. Never automatically fetch a token from an arbitrary responding server just to bypass a rejection.
|
||||
|
||||
Prefer reconfiguration from MCP Server's existing connection/Skills notice, then reconnect or restart the client. Existing user edits remain protected. Unreadable client files need review; unrelated entries and historical shared entries are not silently deleted. A reload can invalidate the instance pin and calibrated screenshots even while the port remains the same. Read fresh identity and capture again; never replay a mutation solely to get a cleaner reply.
|
||||
|
||||
## Frame-paced mouse drag (Full profile)
|
||||
|
||||
Use this only when a drag test is requested and the originating input tool is exposed. Keep legacy timing for existing steps/stepDelayMs callers. For a new frame-paced gesture, capture the exact target, use coordinateSpace=image-pixels with its captureId, and choose a unique requestKey. Set timing=frame-paced and supply startX/startY/endX/endY from that PNG. durationMs is 50..10000 (default 600); pressHoldMs and endHoldMs are 0..2000 (default 100). Each edge still gets separate renderer frames at zero hold. Do not mix legacy step timing with these fields.
|
||||
|
||||
The tool waits up to waitMs (default 1200), then may return a running receipt. Read it through the SAME tool with action=status and jobId or requestKey; cancel through action=cancel without coordinates. A retained identical start recovers its original receipt and never dispatches the gesture again. Changed arguments conflict. Only the latest 32 receipts are retained; these are not durable transactions across eviction/reload. A missing receipt requires inspection of the resulting state, not an automatic retry with a new key. The preview wrapper and direct mouse-drag tool have separate ownership; do not change custom exposure lists to access another tool's receipts.
|
||||
|
||||
Frame-paced input observes the captured Electron renderer's requestAnimationFrame callbacks. Native Game View pause/stop state is checked separately; renderer progression does not prove that native game Update advanced or a game accepted the gesture. Receipts deliberately report nativeGameUpdateVerified=false and businessOutcomeVerified=false. Compare authored state, actual preview/game state and fresh screenshots independently. This is mouse input, not touch injection or proof of physical-device provenance.
|
||||
|
||||
Focus loss, stale geometry, stalled frames, cancellation, preview pause/stop and extension shutdown interrupt the job. Only its own mouse release is attempted, without business callbacks or a legacy fallback. Cleanup failure leaves the target window locked; explicitly cancel that job to retry cleanup. Status reads never send input. No background/focus policy, preview pause state, project input setting or dependency is automatically changed.
|
||||
|
||||
Sources: [MCP transport](https://modelcontextprotocol.io/specification/2025-11-25/basic/transports), [Electron input](https://www.electronjs.org/docs/latest/api/web-contents#contentssendinputeventinputevent) and [Creator Director](https://docs.cocos.com/creator/3.8/api/en/class/Director).
|
||||
`;
|
||||
return Object.entries(Object.keys(templates).length ? { ...templates, 'references/project-identity-and-input.md': execution } : {})
|
||||
.map(([filePath, content]) => ({ path: filePath, content }));
|
||||
}
|
||||
|
||||
module.exports = { getProjectSkillReferences };
|
||||
+766
@@ -0,0 +1,766 @@
|
||||
'use strict';
|
||||
|
||||
const crypto = require('crypto');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const {
|
||||
COCOS_MCP_SKILL_DESCRIPTION,
|
||||
COCOS_MCP_SKILL_NAME,
|
||||
COCOS_MCP_SKILL_TITLE,
|
||||
COCOS_UI_SKILL_DESCRIPTION,
|
||||
COCOS_UI_SKILL_NAME,
|
||||
COCOS_UI_SKILL_TITLE,
|
||||
buildCocosMcpProjectSkillContent,
|
||||
buildCocosUiProjectSkillContent,
|
||||
buildLegacyCocosMcpProjectSkillContent,
|
||||
listProjectInstructions,
|
||||
normalizeSkillName,
|
||||
parseSkillMetadata,
|
||||
writeProjectInstruction,
|
||||
} = require('./project-instructions');
|
||||
const { resolveProjectFilePath: resolveProjectPath } = require('./path-safety');
|
||||
const { SKILL_PLATFORMS, getSkillPlatform, getSkillsDirectory, getSkillProjectPath } = require('./skill-platforms');
|
||||
const { readOptionalText } = require('./atomic-file');
|
||||
const { getProjectSkillReferences } = require('./project-skill-references');
|
||||
|
||||
const COCOS_MCP_SKILL_TEMPLATE_VERSION = 4;
|
||||
const COCOS_UI_SKILL_TEMPLATE_VERSION = 5;
|
||||
const MANIFEST_FILE_NAME = '.funplay-cocos-mcp.json';
|
||||
const BACKUP_ROOT = '.agents/skill-backups';
|
||||
|
||||
const BUILT_IN_PROJECT_SKILLS = Object.freeze([
|
||||
Object.freeze({
|
||||
id: 'cocos-mcp-workflow',
|
||||
skillName: COCOS_MCP_SKILL_NAME,
|
||||
title: COCOS_MCP_SKILL_TITLE,
|
||||
description: COCOS_MCP_SKILL_DESCRIPTION,
|
||||
templateVersion: COCOS_MCP_SKILL_TEMPLATE_VERSION,
|
||||
buildContent: buildCocosMcpProjectSkillContent,
|
||||
legacyTemplates: Object.freeze([
|
||||
Object.freeze({ version: 3, hash: 'a1ab6bd3201e4e16513b0c6307d90db737326c3de4df51d85028b68a3495832c' }),
|
||||
Object.freeze({ version: 2, hash: 'b0371afe3dd7084052927af8130a0929c0877cd48ade67ca9bd9605e1d8cee35' }),
|
||||
Object.freeze({ version: 1, content: buildLegacyCocosMcpProjectSkillContent() }),
|
||||
Object.freeze({
|
||||
version: 1,
|
||||
content: buildLegacyCocosMcpProjectSkillContent({ includePrefabPreservationRule: true }),
|
||||
}),
|
||||
]),
|
||||
}),
|
||||
Object.freeze({
|
||||
id: 'cocos-ui-composition',
|
||||
skillName: COCOS_UI_SKILL_NAME,
|
||||
title: COCOS_UI_SKILL_TITLE,
|
||||
description: COCOS_UI_SKILL_DESCRIPTION,
|
||||
templateVersion: COCOS_UI_SKILL_TEMPLATE_VERSION,
|
||||
buildContent: buildCocosUiProjectSkillContent,
|
||||
legacyTemplates: Object.freeze([
|
||||
Object.freeze({ version: 4, hash: '66a3c8d8df159ea796b838710b895992142851092c9d235d4b0f556b8e8aecb2' }),
|
||||
Object.freeze({ version: 3, hash: 'aa57456be315901395adc8ba83e6fe55b5a4c996659365bcea9a76fa1e55d6f8' }),
|
||||
Object.freeze({ version: 2, hash: 'f3ea391fd31b703e29919d92e95294b075494d0368b156524017fa7fcd58db9a' }),
|
||||
Object.freeze({
|
||||
version: 1,
|
||||
// Original v1 content from v0.5.2, including installs without a manifest.
|
||||
hash: '835f4c4b6e6dc79cabf4e5048ac056b6f2441b2b77c0c555ca502740cc175e72',
|
||||
}),
|
||||
]),
|
||||
}),
|
||||
]);
|
||||
|
||||
function sha256Text(value) {
|
||||
return crypto.createHash('sha256').update(String(value || ''), 'utf8').digest('hex');
|
||||
}
|
||||
|
||||
function getBuiltInProjectSkillDefinitions() {
|
||||
return BUILT_IN_PROJECT_SKILLS.map((definition) => ({
|
||||
id: definition.id,
|
||||
skillName: definition.skillName,
|
||||
title: definition.title,
|
||||
description: definition.description,
|
||||
templateVersion: definition.templateVersion,
|
||||
}));
|
||||
}
|
||||
|
||||
function resolveBuiltInProjectSkillDefinition(value = COCOS_MCP_SKILL_NAME) {
|
||||
const key = String(value || COCOS_MCP_SKILL_NAME).trim();
|
||||
const definition = BUILT_IN_PROJECT_SKILLS.find((item) => (
|
||||
item.skillName === key || item.id === key
|
||||
));
|
||||
if (!definition) {
|
||||
throw new Error(`Unknown built-in project skill: ${key}`);
|
||||
}
|
||||
return definition;
|
||||
}
|
||||
|
||||
function definitionFromOptions(options = {}) {
|
||||
return resolveBuiltInProjectSkillDefinition(
|
||||
options.templateSkillName || options.skillName || options.skillId || COCOS_MCP_SKILL_NAME
|
||||
);
|
||||
}
|
||||
|
||||
function resolveReferencePath(projectPath, relativePath) {
|
||||
const filePath = resolveProjectPath(projectPath, relativePath);
|
||||
// A managed reference must not adopt a symlink to another authored project file.
|
||||
const parts = path.relative(projectPath, filePath).split(path.sep);
|
||||
let current = projectPath;
|
||||
for (const part of parts) {
|
||||
current = path.join(current, part);
|
||||
try {
|
||||
if (fs.lstatSync(current).isSymbolicLink()) throw new Error(`Skill reference path is a symbolic link: ${relativePath}`);
|
||||
} catch (error) {
|
||||
if (error.code !== 'ENOENT') throw error;
|
||||
}
|
||||
}
|
||||
return filePath;
|
||||
}
|
||||
|
||||
function referenceSnapshots(projectPath, skillName, definition, options, manifestData = {}) {
|
||||
const root = path.dirname(getSkillRelativePath(skillName, options));
|
||||
return getProjectSkillReferences(definition.skillName).map((template) => {
|
||||
const relativePath = `${root}/${template.path}`;
|
||||
const filePath = resolveReferencePath(projectPath, relativePath);
|
||||
const content = readOptionalText(filePath);
|
||||
const currentHash = content === null ? '' : sha256Text(content);
|
||||
const templateHash = sha256Text(template.content);
|
||||
const record = manifestData.skillName === skillName && manifestData.files &&
|
||||
Object.prototype.hasOwnProperty.call(manifestData.files, template.path) ? manifestData.files[template.path] : null;
|
||||
const tracked = Boolean(record && typeof record.installedHash === 'string' && /^[a-f0-9]{64}$/.test(record.installedHash));
|
||||
const current = content !== null && currentHash === templateHash;
|
||||
const modified = content !== null && !current && tracked && currentHash !== record.installedHash;
|
||||
const conflict = content !== null && !current && !tracked;
|
||||
return {
|
||||
path: relativePath, relativePath: template.path, filePath, content, templateContent: template.content,
|
||||
exists: content !== null, current, modified, conflict, managed: current || tracked,
|
||||
currentHash, templateHash,
|
||||
status: content === null ? 'missing' : conflict ? 'conflict' : modified ? 'modified' : current ? 'current' : 'update-available',
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function publicReferenceState(reference) {
|
||||
const { content, templateContent, filePath, ...state } = reference;
|
||||
return state;
|
||||
}
|
||||
|
||||
function getSkillRelativePath(skillName = COCOS_MCP_SKILL_NAME, options = {}) {
|
||||
return `${getSkillsDirectory(options)}/${skillName}/SKILL.md`;
|
||||
}
|
||||
|
||||
function getManifestRelativePath(skillName = COCOS_MCP_SKILL_NAME, options = {}) {
|
||||
return `${getSkillsDirectory(options)}/${skillName}/${MANIFEST_FILE_NAME}`;
|
||||
}
|
||||
|
||||
function readJsonFile(filePath) {
|
||||
try {
|
||||
return {
|
||||
valid: true,
|
||||
value: JSON.parse(fs.readFileSync(filePath, 'utf8')),
|
||||
error: '',
|
||||
};
|
||||
} catch (error) {
|
||||
return {
|
||||
valid: false,
|
||||
value: null,
|
||||
error: error.message,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
function readManagedSkillManifest(projectPath, skillName = COCOS_MCP_SKILL_NAME, options = {}) {
|
||||
projectPath = getSkillProjectPath(projectPath, options);
|
||||
const relativePath = getManifestRelativePath(skillName, options);
|
||||
const filePath = resolveProjectPath(projectPath, relativePath);
|
||||
if (!fs.existsSync(filePath)) {
|
||||
return {
|
||||
exists: false,
|
||||
valid: false,
|
||||
path: relativePath,
|
||||
data: null,
|
||||
error: '',
|
||||
};
|
||||
}
|
||||
const parsed = readJsonFile(filePath);
|
||||
return {
|
||||
exists: true,
|
||||
valid: parsed.valid,
|
||||
path: relativePath,
|
||||
data: parsed.value,
|
||||
error: parsed.error,
|
||||
};
|
||||
}
|
||||
|
||||
function writeManagedSkillManifest(projectPath, content, options = {}) {
|
||||
projectPath = getSkillProjectPath(projectPath, options);
|
||||
const skillName = options.skillName || COCOS_MCP_SKILL_NAME;
|
||||
let definition = null;
|
||||
try {
|
||||
definition = resolveBuiltInProjectSkillDefinition(skillName);
|
||||
} catch (error) {
|
||||
// A custom folder name may still contain the recommended workflow template.
|
||||
}
|
||||
const contentHash = sha256Text(content);
|
||||
const data = {
|
||||
schemaVersion: 2,
|
||||
skillId: String(options.skillId || definition && definition.id || skillName),
|
||||
skillName,
|
||||
templateVersion: Number(
|
||||
options.templateVersion || definition && definition.templateVersion || COCOS_MCP_SKILL_TEMPLATE_VERSION
|
||||
),
|
||||
templateHash: contentHash,
|
||||
installedHash: contentHash,
|
||||
files: Object.fromEntries([
|
||||
['SKILL.md', { templateHash: contentHash, installedHash: contentHash }],
|
||||
...(options.referenceFiles || []).map((file) => [file.path, {
|
||||
templateHash: sha256Text(file.content), installedHash: sha256Text(file.content),
|
||||
}]),
|
||||
]),
|
||||
extensionVersion: String(options.extensionVersion || ''),
|
||||
updatedAt: new Date().toISOString(),
|
||||
};
|
||||
const result = writeProjectInstruction(projectPath, {
|
||||
target: getManifestRelativePath(skillName, options),
|
||||
content: `${JSON.stringify(data, null, 2)}\n`,
|
||||
...(Object.prototype.hasOwnProperty.call(options, 'expectedManifestContent') ? { expectedContent: options.expectedManifestContent } : {}),
|
||||
overwrite: true,
|
||||
});
|
||||
return { ...result, data };
|
||||
}
|
||||
|
||||
function timestampForPath(date = new Date()) {
|
||||
return date.toISOString().replace(/[:.]/g, '-');
|
||||
}
|
||||
|
||||
function listProjectSkillBackups(projectPath, skillName = COCOS_MCP_SKILL_NAME, options = {}) {
|
||||
projectPath = getSkillProjectPath(projectPath, options);
|
||||
const relativeRoot = `${getSkillsDirectory(options).replace(/\/skills$/, '/skill-backups')}/${skillName}`;
|
||||
const platform = getSkillPlatform(options);
|
||||
const roots = [relativeRoot];
|
||||
if (platform.legacyDirectory && !options.legacy) roots.push(`${platform.legacyDirectory.replace(/\/skills$/, '/skill-backups')}/${skillName}`);
|
||||
return roots.flatMap((relativeRoot) => {
|
||||
const root = resolveProjectPath(projectPath, relativeRoot);
|
||||
if (!fs.existsSync(root)) return [];
|
||||
return fs.readdirSync(root, { withFileTypes: true })
|
||||
.filter((entry) => entry.isFile() && entry.name.endsWith('.md'))
|
||||
.map((entry) => {
|
||||
const filePath = path.join(root, entry.name);
|
||||
const stat = fs.statSync(filePath);
|
||||
return {
|
||||
path: `${relativeRoot}/${entry.name}`,
|
||||
size: stat.size,
|
||||
mtime: stat.mtime.toISOString(),
|
||||
};
|
||||
});
|
||||
})
|
||||
.sort((left, right) => right.mtime.localeCompare(left.mtime) || right.path.localeCompare(left.path));
|
||||
}
|
||||
|
||||
function createProjectSkillBackup(projectPath, content, options = {}) {
|
||||
projectPath = getSkillProjectPath(projectPath, options);
|
||||
const skillName = options.skillName || COCOS_MCP_SKILL_NAME;
|
||||
const label = String(options.label || 'before-update').replace(/[^a-z0-9_-]+/gi, '-');
|
||||
const root = `${getSkillsDirectory(options).replace(/\/skills$/, '/skill-backups')}/${skillName}`;
|
||||
const baseName = `${timestampForPath(options.date || new Date())}-${label}-SKILL`;
|
||||
let relativePath = `${root}/${baseName}.md`;
|
||||
let suffix = 2;
|
||||
while (fs.existsSync(resolveProjectPath(projectPath, relativePath))) {
|
||||
relativePath = `${root}/${baseName}-${suffix}.md`;
|
||||
suffix += 1;
|
||||
}
|
||||
const backup = writeProjectInstruction(projectPath, {
|
||||
target: relativePath,
|
||||
content: String(content || ''),
|
||||
overwrite: false,
|
||||
});
|
||||
if (options.bundle) {
|
||||
writeProjectInstruction(projectPath, {
|
||||
target: `${relativePath}.files.json`,
|
||||
content: `${JSON.stringify({ schemaVersion: 1, ...options.bundle }, null, 2)}\n`,
|
||||
overwrite: false,
|
||||
});
|
||||
}
|
||||
return backup;
|
||||
}
|
||||
|
||||
function findRecognizedLegacyTemplate(definition, currentHash) {
|
||||
return definition.legacyTemplates.find((legacy) => (
|
||||
(legacy.hash || sha256Text(legacy.content)) === currentHash
|
||||
)) || null;
|
||||
}
|
||||
|
||||
function getBuiltInProjectSkillState(projectPath, options = {}) {
|
||||
projectPath = getSkillProjectPath(projectPath, options);
|
||||
const definition = definitionFromOptions(options);
|
||||
const skillName = options.templateSkillName ? normalizeSkillName(options.skillName || definition.skillName) : definition.skillName;
|
||||
const relativePath = getSkillRelativePath(skillName, options);
|
||||
let filePath = resolveProjectPath(projectPath, relativePath);
|
||||
const platform = getSkillPlatform(options);
|
||||
const oldPath = platform.legacyDirectory ? `${platform.legacyDirectory}/${skillName}/SKILL.md` : '';
|
||||
const legacyPath = !fs.existsSync(filePath) && oldPath && fs.existsSync(resolveProjectPath(projectPath, oldPath)) ? oldPath : '';
|
||||
if (legacyPath) filePath = resolveProjectPath(projectPath, legacyPath);
|
||||
const installed = fs.existsSync(filePath) && fs.statSync(filePath).isFile();
|
||||
const templateContent = definition.buildContent({ skillName });
|
||||
const templateHash = sha256Text(templateContent);
|
||||
const content = installed ? fs.readFileSync(filePath, 'utf8') : '';
|
||||
const currentHash = installed ? sha256Text(content) : '';
|
||||
const metadata = installed ? parseSkillMetadata(content) : {
|
||||
name: skillName,
|
||||
description: '',
|
||||
format: 'missing',
|
||||
valid: false,
|
||||
};
|
||||
const manifest = readManagedSkillManifest(projectPath, skillName, { ...options, legacy: Boolean(legacyPath) });
|
||||
const manifestData = manifest.valid && manifest.data ? manifest.data : {};
|
||||
const recognizedLegacy = installed
|
||||
? findRecognizedLegacyTemplate(definition, currentHash)
|
||||
: null;
|
||||
const contentCurrent = installed && currentHash === templateHash;
|
||||
const references = referenceSnapshots(projectPath, skillName, definition, options, manifestData);
|
||||
const current = contentCurrent && !legacyPath && references.every((file) => file.current);
|
||||
const matchesManagedInstall = Boolean(
|
||||
installed &&
|
||||
manifest.valid &&
|
||||
manifestData.skillName === skillName &&
|
||||
manifestData.installedHash === currentHash
|
||||
);
|
||||
const modified = Boolean(
|
||||
installed && !contentCurrent && !recognizedLegacy && !matchesManagedInstall ||
|
||||
references.some((file) => file.modified || file.conflict)
|
||||
);
|
||||
const updateAvailable = Boolean(installed && !current);
|
||||
const backups = listProjectSkillBackups(projectPath, skillName, options);
|
||||
|
||||
let status = 'missing';
|
||||
if (current) {
|
||||
status = 'current';
|
||||
} else if (modified) {
|
||||
status = 'modified';
|
||||
} else if (installed) {
|
||||
status = 'update-available';
|
||||
}
|
||||
|
||||
const installedTemplateVersion = contentCurrent
|
||||
? definition.templateVersion
|
||||
: recognizedLegacy
|
||||
? recognizedLegacy.version
|
||||
: Number(manifestData.templateVersion || 0);
|
||||
|
||||
return {
|
||||
skillId: definition.id,
|
||||
skillName,
|
||||
title: definition.title,
|
||||
description: definition.description,
|
||||
path: relativePath,
|
||||
clientId: platform.id,
|
||||
legacyPath,
|
||||
absolutePath: filePath,
|
||||
installed,
|
||||
status,
|
||||
current,
|
||||
modified,
|
||||
managed: Boolean(contentCurrent || recognizedLegacy || matchesManagedInstall),
|
||||
updateAvailable,
|
||||
templateVersion: definition.templateVersion,
|
||||
installedTemplateVersion,
|
||||
templateHash,
|
||||
currentHash,
|
||||
references: references.map(publicReferenceState),
|
||||
missingReferenceCount: references.filter((file) => !file.exists).length,
|
||||
modifiedReferenceCount: references.filter((file) => file.modified).length,
|
||||
referenceConflictCount: references.filter((file) => file.conflict).length,
|
||||
metadata,
|
||||
manifest: {
|
||||
exists: manifest.exists,
|
||||
valid: manifest.valid,
|
||||
path: manifest.path,
|
||||
error: manifest.error,
|
||||
},
|
||||
backupCount: backups.length,
|
||||
latestBackup: backups[0] || null,
|
||||
canInstall: !installed && !references.some((file) => file.conflict),
|
||||
canUpdate: updateAvailable && !references.some((file) => file.conflict),
|
||||
};
|
||||
}
|
||||
|
||||
function getCocosMcpProjectSkillState(projectPath, options = {}) {
|
||||
return getBuiltInProjectSkillState(projectPath, { ...options, skillName: COCOS_MCP_SKILL_NAME });
|
||||
}
|
||||
|
||||
function getCocosUiProjectSkillState(projectPath, options = {}) {
|
||||
return getBuiltInProjectSkillState(projectPath, { ...options, skillName: COCOS_UI_SKILL_NAME });
|
||||
}
|
||||
|
||||
function getProjectSkillsState(projectPath, options = {}) {
|
||||
const platform = getSkillPlatform(options);
|
||||
const platforms = SKILL_PLATFORMS.map((item) => ({ ...item }));
|
||||
if (!platform) return { projectPath: path.resolve(projectPath), clientId: options.clientId, supported: false, platforms, builtIns: [], skills: [], backups: [] };
|
||||
projectPath = getSkillProjectPath(projectPath, options);
|
||||
try {
|
||||
return readProjectSkillsState(projectPath, options, platform, platforms);
|
||||
} catch (error) {
|
||||
// A broken or unsafe directory for one client must not break every panel.
|
||||
// Mutations still use the strict path checks and cannot install through it.
|
||||
return {
|
||||
projectPath: path.resolve(projectPath),
|
||||
clientId: platform.id,
|
||||
clientName: platform.name,
|
||||
supported: true,
|
||||
platforms,
|
||||
error: error.message,
|
||||
builtIns: [],
|
||||
skills: [],
|
||||
backups: [],
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
function readProjectSkillsState(projectPath, options, platform, platforms) {
|
||||
const instructions = listProjectInstructions(projectPath, options);
|
||||
const builtIns = BUILT_IN_PROJECT_SKILLS.map((definition) => (
|
||||
getBuiltInProjectSkillState(projectPath, { ...options, skillName: definition.skillName })
|
||||
));
|
||||
const builtInByPath = new Map(builtIns.map((skill) => [skill.path, skill]));
|
||||
return {
|
||||
projectPath: path.resolve(projectPath),
|
||||
clientId: platform.id,
|
||||
clientName: platform.name,
|
||||
supported: true,
|
||||
platforms,
|
||||
skillRoot: resolveProjectPath(projectPath, platform.directory),
|
||||
builtIns,
|
||||
official: builtIns[0],
|
||||
skills: instructions.skills.map((skill) => {
|
||||
const builtIn = builtInByPath.get(skill.path);
|
||||
return {
|
||||
...skill,
|
||||
title: builtIn ? builtIn.title : skill.title,
|
||||
description: builtIn ? builtIn.description : skill.description,
|
||||
builtIn: Boolean(builtIn),
|
||||
builtInId: builtIn ? builtIn.skillId : '',
|
||||
official: Boolean(builtIn),
|
||||
};
|
||||
}),
|
||||
backups: builtIns.flatMap((skill) => (
|
||||
listProjectSkillBackups(projectPath, skill.skillName, options).map((backup) => ({
|
||||
...backup,
|
||||
skillName: skill.skillName,
|
||||
}))
|
||||
)),
|
||||
};
|
||||
}
|
||||
|
||||
function buildLineDiff(before, after, options = {}) {
|
||||
const beforeLines = String(before || '').replace(/\r\n/g, '\n').split('\n');
|
||||
const afterLines = String(after || '').replace(/\r\n/g, '\n').split('\n');
|
||||
const maxLines = options.maxLines || 1000;
|
||||
if (beforeLines.length > maxLines || afterLines.length > maxLines) {
|
||||
return {
|
||||
text: 'Diff preview is unavailable because the skill exceeds the safe line limit.',
|
||||
added: afterLines.length,
|
||||
removed: beforeLines.length,
|
||||
};
|
||||
}
|
||||
|
||||
const rows = beforeLines.length + 1;
|
||||
const columns = afterLines.length + 1;
|
||||
const table = Array.from({ length: rows }, () => new Uint16Array(columns));
|
||||
for (let left = beforeLines.length - 1; left >= 0; left -= 1) {
|
||||
for (let right = afterLines.length - 1; right >= 0; right -= 1) {
|
||||
table[left][right] = beforeLines[left] === afterLines[right]
|
||||
? table[left + 1][right + 1] + 1
|
||||
: Math.max(table[left + 1][right], table[left][right + 1]);
|
||||
}
|
||||
}
|
||||
|
||||
const templateVersion = Number(options.templateVersion || COCOS_MCP_SKILL_TEMPLATE_VERSION);
|
||||
const relativePath = options.relativePath || 'SKILL.md';
|
||||
const output = [`--- installed/${relativePath}`, `+++ template-v${templateVersion}/${relativePath}`, '@@'];
|
||||
let left = 0;
|
||||
let right = 0;
|
||||
let added = 0;
|
||||
let removed = 0;
|
||||
while (left < beforeLines.length && right < afterLines.length) {
|
||||
if (beforeLines[left] === afterLines[right]) {
|
||||
output.push(` ${beforeLines[left]}`);
|
||||
left += 1;
|
||||
right += 1;
|
||||
} else if (table[left + 1][right] >= table[left][right + 1]) {
|
||||
output.push(`- ${beforeLines[left]}`);
|
||||
removed += 1;
|
||||
left += 1;
|
||||
} else {
|
||||
output.push(`+ ${afterLines[right]}`);
|
||||
added += 1;
|
||||
right += 1;
|
||||
}
|
||||
}
|
||||
while (left < beforeLines.length) {
|
||||
output.push(`- ${beforeLines[left]}`);
|
||||
removed += 1;
|
||||
left += 1;
|
||||
}
|
||||
while (right < afterLines.length) {
|
||||
output.push(`+ ${afterLines[right]}`);
|
||||
added += 1;
|
||||
right += 1;
|
||||
}
|
||||
|
||||
return { text: output.join('\n'), added, removed };
|
||||
}
|
||||
|
||||
function previewBuiltInProjectSkillUpdate(projectPath, options = {}) {
|
||||
projectPath = getSkillProjectPath(projectPath, options);
|
||||
const definition = definitionFromOptions(options);
|
||||
const state = getBuiltInProjectSkillState(projectPath, options);
|
||||
const currentContent = state.installed
|
||||
? fs.readFileSync(state.absolutePath, 'utf8')
|
||||
: '';
|
||||
const templateContent = definition.buildContent({ skillName: state.skillName });
|
||||
const diff = buildLineDiff(currentContent, templateContent, {
|
||||
...options,
|
||||
templateVersion: state.templateVersion,
|
||||
});
|
||||
const manifest = readManagedSkillManifest(projectPath, state.skillName, options);
|
||||
const referenceDiffs = referenceSnapshots(projectPath, state.skillName, definition, options, manifest.valid ? manifest.data : {})
|
||||
.filter((file) => !file.current)
|
||||
.map((file) => ({
|
||||
path: file.path,
|
||||
status: file.status,
|
||||
...buildLineDiff(file.content || '', file.templateContent, { ...options, relativePath: file.relativePath, templateVersion: state.templateVersion }),
|
||||
}));
|
||||
return {
|
||||
skillId: state.skillId,
|
||||
skillName: state.skillName,
|
||||
title: state.title,
|
||||
path: state.path,
|
||||
legacyPath: state.legacyPath,
|
||||
status: state.status,
|
||||
modified: state.modified,
|
||||
templateVersion: state.templateVersion,
|
||||
installedTemplateVersion: state.installedTemplateVersion,
|
||||
references: state.references,
|
||||
addedLines: diff.added + referenceDiffs.reduce((sum, file) => sum + file.added, 0),
|
||||
removedLines: diff.removed + referenceDiffs.reduce((sum, file) => sum + file.removed, 0),
|
||||
diff: [diff.text, ...referenceDiffs.map((file) => file.text)].join('\n\n'),
|
||||
};
|
||||
}
|
||||
|
||||
function previewCocosMcpProjectSkillUpdate(projectPath, options = {}) {
|
||||
return previewBuiltInProjectSkillUpdate(projectPath, {
|
||||
...options,
|
||||
skillName: options.skillName || COCOS_MCP_SKILL_NAME,
|
||||
});
|
||||
}
|
||||
|
||||
function updateBuiltInProjectSkill(projectPath, options = {}) {
|
||||
projectPath = getSkillProjectPath(projectPath, options);
|
||||
const definition = definitionFromOptions(options);
|
||||
const state = getBuiltInProjectSkillState(projectPath, options);
|
||||
const content = definition.buildContent({ ...options, skillName: state.skillName });
|
||||
if (state.current && sha256Text(content) === state.currentHash) {
|
||||
return {
|
||||
installed: false,
|
||||
updated: false,
|
||||
alreadyCurrent: true,
|
||||
backup: null,
|
||||
state,
|
||||
};
|
||||
}
|
||||
if (state.installed && options.onlyIfMissing === true) {
|
||||
return { installed: false, updated: false, skipped: true, backup: null, state };
|
||||
}
|
||||
if (state.referenceConflictCount) {
|
||||
throw new Error(`A reference destination for '${state.skillName}' is user-owned. Move or rename the conflicting file before installation; it will not be overwritten.`);
|
||||
}
|
||||
if (state.modified && options.allowModified !== true) {
|
||||
throw new Error(`The built-in project skill '${state.skillName}' has local modifications. Confirm a backup update before replacing it.`);
|
||||
}
|
||||
|
||||
const currentContent = state.installed ? fs.readFileSync(state.absolutePath, 'utf8') : null;
|
||||
if (state.installed && sha256Text(currentContent) !== state.currentHash) throw new Error('Skill changed while preparing the update. Refresh and review it again.');
|
||||
const manifestState = readManagedSkillManifest(projectPath, state.skillName, { ...options, legacy: Boolean(state.legacyPath) });
|
||||
const references = referenceSnapshots(projectPath, state.skillName, definition, options, manifestState.valid ? manifestState.data : {});
|
||||
if (references.some((file, index) => file.currentHash !== state.references[index].currentHash || file.conflict)) {
|
||||
throw new Error('Skill references changed while preparing the update. Refresh and review them again.');
|
||||
}
|
||||
const manifestPath = resolveProjectPath(projectPath, getManifestRelativePath(state.skillName, options));
|
||||
const manifestContent = readOptionalText(manifestPath);
|
||||
// Resolve every destination before any write; a late conflict/symlink must not partially install SKILL.md.
|
||||
resolveProjectPath(projectPath, state.path);
|
||||
for (const file of references) resolveReferencePath(projectPath, file.path);
|
||||
|
||||
let backup = null;
|
||||
if (state.installed) {
|
||||
backup = createProjectSkillBackup(
|
||||
projectPath,
|
||||
currentContent,
|
||||
{ ...options, skillName: state.skillName, label: 'before-update', bundle: {
|
||||
files: Object.fromEntries(references.map((file) => [file.relativePath, file.content])),
|
||||
manifest: manifestContent,
|
||||
} }
|
||||
);
|
||||
}
|
||||
|
||||
const write = writeProjectInstruction(projectPath, {
|
||||
target: state.path,
|
||||
content,
|
||||
expectedContent: state.legacyPath ? null : currentContent,
|
||||
overwrite: true,
|
||||
});
|
||||
for (const file of references) {
|
||||
if (file.current) continue;
|
||||
resolveReferencePath(projectPath, file.path);
|
||||
writeProjectInstruction(projectPath, {
|
||||
target: file.path, content: file.templateContent, expectedContent: file.content, overwrite: true,
|
||||
});
|
||||
}
|
||||
const manifest = writeManagedSkillManifest(projectPath, content, {
|
||||
...options,
|
||||
skillId: state.skillId,
|
||||
skillName: state.skillName,
|
||||
templateVersion: state.templateVersion,
|
||||
extensionVersion: options.extensionVersion,
|
||||
referenceFiles: references.map((file) => ({ path: file.relativePath, content: file.templateContent })),
|
||||
expectedManifestContent: manifestContent,
|
||||
});
|
||||
return {
|
||||
installed: !state.installed,
|
||||
updated: state.installed,
|
||||
alreadyCurrent: false,
|
||||
backup,
|
||||
write,
|
||||
manifest: manifest.path,
|
||||
references: references.map((file) => file.path),
|
||||
state: getBuiltInProjectSkillState(projectPath, options),
|
||||
};
|
||||
}
|
||||
|
||||
function updateCocosMcpProjectSkill(projectPath, options = {}) {
|
||||
return updateBuiltInProjectSkill(projectPath, {
|
||||
...options,
|
||||
skillName: options.skillName || COCOS_MCP_SKILL_NAME,
|
||||
});
|
||||
}
|
||||
|
||||
function restoreLatestBuiltInProjectSkillBackup(projectPath, options = {}) {
|
||||
projectPath = getSkillProjectPath(projectPath, options);
|
||||
const state = getBuiltInProjectSkillState(projectPath, options);
|
||||
const backups = listProjectSkillBackups(projectPath, state.skillName, options);
|
||||
const selected = options.backupPath
|
||||
? backups.find((backup) => backup.path === options.backupPath)
|
||||
: backups[0];
|
||||
if (!selected) {
|
||||
throw new Error(`No project skill backup is available to restore for '${state.skillName}'.`);
|
||||
}
|
||||
|
||||
const sourcePath = resolveProjectPath(projectPath, selected.path);
|
||||
const sourceContent = fs.readFileSync(sourcePath, 'utf8');
|
||||
const currentContent = state.installed ? fs.readFileSync(state.absolutePath, 'utf8') : null;
|
||||
if (state.installed && sha256Text(currentContent) !== state.currentHash) throw new Error('Skill changed while preparing the restore. Review the backup again.');
|
||||
const definition = definitionFromOptions(options);
|
||||
const manifestState = readManagedSkillManifest(projectPath, state.skillName, options);
|
||||
const references = referenceSnapshots(projectPath, state.skillName, definition, options, manifestState.valid ? manifestState.data : {});
|
||||
const manifestPath = getManifestRelativePath(state.skillName, options);
|
||||
const currentManifest = readOptionalText(resolveProjectPath(projectPath, manifestPath));
|
||||
const sidecarPath = resolveProjectPath(projectPath, `${selected.path}.files.json`);
|
||||
let bundle = null;
|
||||
if (fs.existsSync(sidecarPath)) {
|
||||
const parsed = readJsonFile(sidecarPath);
|
||||
bundle = parsed.valid && parsed.value;
|
||||
if (!bundle || bundle.schemaVersion !== 1 || !bundle.files || typeof bundle.files !== 'object' || Array.isArray(bundle.files) ||
|
||||
!(bundle.manifest === null || typeof bundle.manifest === 'string')) {
|
||||
throw new Error('The skill reference backup is invalid; no files were restored.');
|
||||
}
|
||||
for (const [relativePath, content] of Object.entries(bundle.files)) {
|
||||
const reference = references.find((file) => file.relativePath === relativePath);
|
||||
if (!reference || !(content === null || typeof content === 'string') || content && content.length > 256 * 1024) {
|
||||
throw new Error('The skill reference backup contains an unsupported path or content.');
|
||||
}
|
||||
if (reference.conflict) throw new Error(`Cannot restore over a user-owned reference: ${reference.path}`);
|
||||
}
|
||||
if (bundle.manifest === null && currentManifest !== null &&
|
||||
(!manifestState.valid || manifestState.data.skillName !== state.skillName)) {
|
||||
throw new Error('Cannot remove an unrecognized skill manifest while restoring a backup.');
|
||||
}
|
||||
}
|
||||
let currentBackup = null;
|
||||
if (state.installed) {
|
||||
currentBackup = createProjectSkillBackup(
|
||||
projectPath,
|
||||
currentContent,
|
||||
{ ...options, skillName: state.skillName, label: 'before-restore', bundle: {
|
||||
files: Object.fromEntries(references.map((file) => [file.relativePath, file.content])),
|
||||
manifest: currentManifest,
|
||||
} }
|
||||
);
|
||||
}
|
||||
const write = writeProjectInstruction(projectPath, {
|
||||
target: state.path,
|
||||
content: sourceContent,
|
||||
expectedContent: state.legacyPath ? null : currentContent,
|
||||
overwrite: true,
|
||||
});
|
||||
if (bundle) {
|
||||
for (const [relativePath, content] of Object.entries(bundle.files)) {
|
||||
const file = references.find((item) => item.relativePath === relativePath);
|
||||
const destination = resolveReferencePath(projectPath, file.path);
|
||||
if (content === null) {
|
||||
if (file.content === null) continue;
|
||||
if (readOptionalText(destination) !== file.content) throw new Error('Skill reference changed while restoring; review the backup again.');
|
||||
// Remove only this recorded, managed file; unrelated references remain untouched.
|
||||
fs.unlinkSync(destination);
|
||||
} else {
|
||||
writeProjectInstruction(projectPath, { target: file.path, content, expectedContent: file.content, overwrite: true });
|
||||
}
|
||||
}
|
||||
if (bundle.manifest === null) {
|
||||
if (currentManifest !== null) {
|
||||
const destination = resolveProjectPath(projectPath, manifestPath);
|
||||
if (readOptionalText(destination) !== currentManifest) throw new Error('Skill manifest changed while restoring.');
|
||||
fs.unlinkSync(destination);
|
||||
}
|
||||
} else {
|
||||
writeProjectInstruction(projectPath, { target: manifestPath, content: bundle.manifest, expectedContent: currentManifest, overwrite: true });
|
||||
}
|
||||
}
|
||||
return {
|
||||
restored: true,
|
||||
source: selected,
|
||||
currentBackup,
|
||||
write,
|
||||
state: getBuiltInProjectSkillState(projectPath, options),
|
||||
};
|
||||
}
|
||||
|
||||
function restoreLatestCocosMcpProjectSkillBackup(projectPath, options = {}) {
|
||||
return restoreLatestBuiltInProjectSkillBackup(projectPath, {
|
||||
...options,
|
||||
skillName: options.skillName || COCOS_MCP_SKILL_NAME,
|
||||
});
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
BACKUP_ROOT,
|
||||
BUILT_IN_PROJECT_SKILLS,
|
||||
COCOS_MCP_SKILL_TEMPLATE_VERSION,
|
||||
COCOS_UI_SKILL_TEMPLATE_VERSION,
|
||||
MANIFEST_FILE_NAME,
|
||||
buildLineDiff,
|
||||
createProjectSkillBackup,
|
||||
getBuiltInProjectSkillDefinitions,
|
||||
getBuiltInProjectSkillState,
|
||||
getCocosMcpProjectSkillState,
|
||||
getCocosUiProjectSkillState,
|
||||
getManifestRelativePath,
|
||||
getProjectSkillsState,
|
||||
getSkillRelativePath,
|
||||
listProjectSkillBackups,
|
||||
previewBuiltInProjectSkillUpdate,
|
||||
previewCocosMcpProjectSkillUpdate,
|
||||
readManagedSkillManifest,
|
||||
resolveBuiltInProjectSkillDefinition,
|
||||
restoreLatestBuiltInProjectSkillBackup,
|
||||
restoreLatestCocosMcpProjectSkillBackup,
|
||||
sha256Text,
|
||||
updateBuiltInProjectSkill,
|
||||
updateCocosMcpProjectSkill,
|
||||
writeManagedSkillManifest,
|
||||
};
|
||||
+105
@@ -0,0 +1,105 @@
|
||||
'use strict';
|
||||
|
||||
const { loadProjectPrompts, interpolatePrompt } = require('./project-prompts');
|
||||
|
||||
const BUILT_IN_ARGUMENTS = {
|
||||
fix_script_errors: ['touched_paths'],
|
||||
create_playable_prototype: ['idea'],
|
||||
scene_validation: ['focus'],
|
||||
auto_wire_scene: ['target', 'component_type'],
|
||||
};
|
||||
|
||||
class PromptProvider {
|
||||
constructor(getRuntimeContext, options = {}) {
|
||||
this.getRuntimeContext = getRuntimeContext;
|
||||
this.onWarning = options.onWarning || (() => {});
|
||||
this.reportedWarnings = new Set();
|
||||
}
|
||||
|
||||
projectPrompts() {
|
||||
const loaded = loadProjectPrompts(this.getRuntimeContext().projectPath, Object.keys(BUILT_IN_ARGUMENTS));
|
||||
const warnings = new Set(loaded.warnings);
|
||||
for (const warning of warnings) {
|
||||
if (!this.reportedWarnings.has(warning)) this.onWarning(`mcp-prompts: ${warning}`);
|
||||
}
|
||||
this.reportedWarnings = warnings;
|
||||
return loaded.prompts;
|
||||
}
|
||||
|
||||
listPrompts() {
|
||||
const { projectName } = this.getRuntimeContext();
|
||||
return [
|
||||
this.createPrompt('fix_script_errors', `In core mode, default to execute_javascript first and only switch to specialist tools when they are clearly better for diagnostics, screenshots, or resource reads in '${projectName}'.`),
|
||||
this.createPrompt('create_playable_prototype', `In core mode, default to execute_javascript first and only switch to specialist tools when they are clearly better for screenshots, asset lookup, or scene opening in '${projectName}'.`),
|
||||
this.createPrompt('scene_validation', `In core mode, default to execute_javascript first and only switch to specialist tools when they are clearly better for screenshots, diagnostics, or structured resource reads in '${projectName}'.`),
|
||||
this.createPrompt('auto_wire_scene', `In core mode, default to execute_javascript first and only switch to specialist tools when they are clearly better for asset lookup, scene opening, diagnostics, or screenshots in '${projectName}'.`),
|
||||
...this.projectPrompts().map(({ name, description, arguments: args }) => ({ name, description, arguments: args })),
|
||||
];
|
||||
}
|
||||
|
||||
getPrompt(name, args = {}) {
|
||||
const invalid = (message) => { const error = new Error(message); error.code = -32602; throw error; };
|
||||
const builtin = Object.prototype.hasOwnProperty.call(BUILT_IN_ARGUMENTS, name);
|
||||
const projectPrompt = builtin ? null : this.projectPrompts().find((prompt) => prompt.name === name);
|
||||
if (!builtin && !projectPrompt) invalid(`Prompt not found: ${name}`);
|
||||
const declarations = builtin ? this.createPrompt(name, '').arguments : projectPrompt.arguments;
|
||||
if (!args || typeof args !== 'object' || Array.isArray(args)) invalid('Prompt arguments must be an object of strings.');
|
||||
const declared = new Set(declarations.map((arg) => arg.name));
|
||||
for (const [key, value] of Object.entries(args)) {
|
||||
if (!declared.has(key)) invalid(`Unknown argument for '${name}': ${key}`);
|
||||
if (typeof value !== 'string') invalid(`Prompt argument '${key}' must be a string.`);
|
||||
if (value.length > 65536) invalid(`Prompt argument '${key}' exceeds 65536 characters.`);
|
||||
}
|
||||
for (const arg of declarations) {
|
||||
if (arg.required && (!Object.prototype.hasOwnProperty.call(args, arg.name) || !args[arg.name].trim())) invalid(`Missing required argument: ${arg.name}`);
|
||||
}
|
||||
const { projectName, projectPath } = this.getRuntimeContext();
|
||||
let text = '';
|
||||
|
||||
switch (name) {
|
||||
case 'fix_script_errors':
|
||||
text = 'In `core` mode, assume `execute_javascript` is the default first tool. Start with `context="editor"` for diagnosis, local file edits, asset-db workflows, and orchestration; switch to `context="scene"` only when runtime or scene state must be inspected directly. Only use specialist tools when they are strictly better primitives: `run_script_diagnostics` and `get_script_diagnostic_context` for TypeScript errors, `resources/read` for structured project context, and screenshot tools for visual verification. Avoid hopping across many narrow tools when one `execute_javascript` call can inspect, decide, and act. Patch the smallest safe regions, refresh assets if needed, and verify the project returns to a healthy state.';
|
||||
break;
|
||||
case 'create_playable_prototype':
|
||||
text = 'In `core` mode, treat `execute_javascript` as the primary tool for almost the entire workflow. Use `context="scene"` for node, component, UI, and runtime orchestration, and use `context="editor"` only when editor-side automation, file work, or asset-db access is required. Reach for specialist tools only when they provide a clearly better primitive: `open_scene` to load a scene, asset tools when you need exact asset identification, and screenshot tools when you need visual proof. Build the prototype in a few high-leverage `execute_javascript` steps instead of many tiny tool calls, then verify with runtime state and screenshots.';
|
||||
break;
|
||||
case 'scene_validation':
|
||||
text = 'In `core` mode, start with `execute_javascript`, usually with `context="scene"`, and keep it as the main tool unless a specialist tool is clearly superior. Use it to inspect hierarchy, nodes, components, prefab instances, cameras, animations, and runtime state in one place. Only switch to specialist tools when you specifically need a screenshot, a structured resource read, or TypeScript diagnostics. Prefer a small number of high-signal validation steps over broad tool hopping.';
|
||||
break;
|
||||
case 'auto_wire_scene':
|
||||
text = 'In `core` mode, begin with `execute_javascript` and assume it will handle nearly all inspection and repair. Use `context="scene"` for hierarchy, node, component, and UI wiring repair, and use `context="editor"` only when file edits, asset-db access, or editor-side orchestration is required. Switch to specialist tools only for exact asset lookup, scene opening, diagnostics, or screenshots. Inspect the target structure, identify missing references or expected children, and repair them with the smallest safe change rather than scattering work across many narrow tools.';
|
||||
break;
|
||||
default:
|
||||
text = interpolatePrompt(projectPrompt.body, args, declarations);
|
||||
break;
|
||||
}
|
||||
|
||||
const context = builtin ? Object.entries(args).map(([key, value]) => `${key}: ${value}`).join('\n') : '';
|
||||
if (name === 'scene_validation') text += '\nThis workflow is read-only unless the user also requests repairs.';
|
||||
const fullText = `Target Cocos project: ${projectName}\nProject path: ${projectPath}\n${context}\n${text}`;
|
||||
return {
|
||||
description: fullText,
|
||||
messages: [
|
||||
{
|
||||
role: 'user',
|
||||
content: {
|
||||
type: 'text',
|
||||
text: fullText,
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
createPrompt(name, description) {
|
||||
return {
|
||||
name,
|
||||
description,
|
||||
arguments: (BUILT_IN_ARGUMENTS[name] || []).map((key) => ({ name: key, description: key, required: false })),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
PromptProvider,
|
||||
};
|
||||
+293
@@ -0,0 +1,293 @@
|
||||
'use strict';
|
||||
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const { getCurrentSelection, queryAssetInfo, queryAssetMeta } = require('./assets');
|
||||
const { runScriptDiagnostics } = require('./diagnostics');
|
||||
const { getRecentProjectLogs } = require('./logs');
|
||||
const { resolveProjectPath } = require('./path-safety');
|
||||
|
||||
function createResource(uri, name, description) {
|
||||
return { uri, name, description, mimeType: 'text/plain' };
|
||||
}
|
||||
|
||||
function createTemplate(uriTemplate, name, description) {
|
||||
return { uriTemplate, name, description, mimeType: 'text/plain' };
|
||||
}
|
||||
|
||||
function truncate(text, limit = 12000) {
|
||||
if (typeof text !== 'string') {
|
||||
return text;
|
||||
}
|
||||
if (text.length <= limit) {
|
||||
return text;
|
||||
}
|
||||
return `${text.slice(0, limit)}\n... (truncated)`;
|
||||
}
|
||||
|
||||
function toText(value) {
|
||||
if (typeof value === 'string') {
|
||||
return value;
|
||||
}
|
||||
return JSON.stringify(value, null, 2);
|
||||
}
|
||||
|
||||
function summarizeSelection() {
|
||||
if (!global.Editor || !Editor.Selection || typeof Editor.Selection.getSelected !== 'function') {
|
||||
return 'Selection API is unavailable in this Cocos environment.';
|
||||
}
|
||||
|
||||
try {
|
||||
const selectedNode = Editor.Selection.getSelected('node');
|
||||
const selectedAsset = Editor.Selection.getSelected('asset');
|
||||
return [
|
||||
`Selected node: ${selectedNode || '(none)'}`,
|
||||
`Selected asset: ${selectedAsset || '(none)'}`,
|
||||
].join('\n');
|
||||
} catch (error) {
|
||||
return `Failed to inspect current selection: ${error.message}`;
|
||||
}
|
||||
}
|
||||
|
||||
class ResourceProvider {
|
||||
constructor(getRuntimeContext, sceneBridge, interactionLog, runtimeLog) {
|
||||
this.getRuntimeContext = getRuntimeContext;
|
||||
this.sceneBridge = sceneBridge;
|
||||
this.interactionLog = interactionLog;
|
||||
this.runtimeLog = runtimeLog;
|
||||
}
|
||||
|
||||
listResources() {
|
||||
const { projectName } = this.getRuntimeContext();
|
||||
return [
|
||||
createResource('cocos://project/context', `${projectName} Project Context`, 'Live Cocos project context summary.'),
|
||||
createResource('cocos://project/summary', `${projectName} Project Summary`, 'Project path, folder summary, and asset overview.'),
|
||||
createResource('cocos://scene/active', `${projectName} Active Scene`, 'Summary of the active Cocos scene.'),
|
||||
createResource('cocos://scene/current', `${projectName} Current Scene`, 'Alias of the active Cocos scene summary.'),
|
||||
createResource('cocos://selection/current', `${projectName} Current Selection`, 'Summary of the current editor selection.'),
|
||||
createResource('cocos://selection/asset', `${projectName} Selected Asset`, 'Details for the currently selected asset.'),
|
||||
createResource('cocos://errors/scripts', `${projectName} Script Diagnostics`, 'Latest TypeScript diagnostic summary for the project.'),
|
||||
createResource('cocos://logs/editor', `${projectName} Editor Logs`, 'Recent MCP runtime logs and tool interaction history.'),
|
||||
createResource('cocos://logs/project', `${projectName} Project Logs`, 'Recent tails from common project log files.'),
|
||||
createResource('cocos://mcp/interactions', `${projectName} MCP Interactions`, 'Recent MCP tool interaction summaries.'),
|
||||
];
|
||||
}
|
||||
|
||||
listResourceTemplates() {
|
||||
return [
|
||||
createTemplate('cocos://scene/node/{path}', 'Scene Node', 'Inspect a scene node by hierarchy path.'),
|
||||
createTemplate('cocos://asset/path/{relative_path}', 'Asset By Path', 'Read a script or text asset by project-relative path.'),
|
||||
createTemplate('cocos://asset/info/{uuid_or_path}', 'Asset Info', 'Inspect an asset by uuid, db url, or path.'),
|
||||
];
|
||||
}
|
||||
|
||||
async readResource(uri) {
|
||||
const text = await this.resolveResourceText(uri);
|
||||
return {
|
||||
contents: [
|
||||
{
|
||||
uri,
|
||||
mimeType: 'text/plain',
|
||||
text,
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
async resolveResourceText(uri) {
|
||||
const { projectName, projectPath, cocosVersion, version, config } = this.getRuntimeContext();
|
||||
|
||||
switch (uri) {
|
||||
case 'cocos://project/context':
|
||||
return [
|
||||
'Funplay Cocos MCP Project Context',
|
||||
`Project: ${projectName}`,
|
||||
`Project Path: ${projectPath}`,
|
||||
`Cocos Creator: ${cocosVersion}`,
|
||||
`Extension Version: ${version}`,
|
||||
`Tool Profile: ${config.toolProfile}`,
|
||||
`Server: http://${config.host}:${config.port}/`,
|
||||
'',
|
||||
'Selection',
|
||||
summarizeSelection(),
|
||||
'',
|
||||
'Active Scene',
|
||||
await this.safeSceneCall('getSceneInfo', { maxDepth: 2 }),
|
||||
].join('\n');
|
||||
case 'cocos://project/summary':
|
||||
return this.buildProjectSummary(projectPath, cocosVersion, version);
|
||||
case 'cocos://scene/active':
|
||||
case 'cocos://scene/current':
|
||||
return await this.safeSceneCall('getSceneInfo', { maxDepth: 3 });
|
||||
case 'cocos://selection/current':
|
||||
return summarizeSelection();
|
||||
case 'cocos://selection/asset':
|
||||
return await this.getSelectedAssetText();
|
||||
case 'cocos://errors/scripts':
|
||||
return await this.getScriptDiagnosticsText(projectPath);
|
||||
case 'cocos://logs/editor':
|
||||
return this.getEditorLogsText();
|
||||
case 'cocos://logs/project':
|
||||
return this.getProjectLogsText(projectPath);
|
||||
case 'cocos://mcp/interactions':
|
||||
return this.interactionLog.summary();
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
if (uri.startsWith('cocos://scene/node/')) {
|
||||
const nodePath = decodeURIComponent(uri.slice('cocos://scene/node/'.length));
|
||||
return await this.safeSceneCall('inspectNode', { path: nodePath });
|
||||
}
|
||||
|
||||
if (uri.startsWith('cocos://asset/path/')) {
|
||||
const relativePath = decodeURIComponent(uri.slice('cocos://asset/path/'.length));
|
||||
return this.readAssetByPath(relativePath);
|
||||
}
|
||||
|
||||
if (uri.startsWith('cocos://asset/info/')) {
|
||||
const uuidOrPath = decodeURIComponent(uri.slice('cocos://asset/info/'.length));
|
||||
return await this.getAssetInfoText(uuidOrPath);
|
||||
}
|
||||
|
||||
return `Resource not found: ${uri}`;
|
||||
}
|
||||
|
||||
buildProjectSummary(projectPath, cocosVersion, version) {
|
||||
const topLevel = fs.existsSync(projectPath)
|
||||
? fs
|
||||
.readdirSync(projectPath, { withFileTypes: true })
|
||||
.filter((entry) => entry.isDirectory())
|
||||
.map((entry) => entry.name)
|
||||
.sort((left, right) => left.localeCompare(right))
|
||||
: [];
|
||||
|
||||
const assetsDir = path.join(projectPath, 'assets');
|
||||
const scriptCount = this.countFiles(assetsDir, ['.ts', '.js']);
|
||||
const prefabCount = this.countFiles(assetsDir, ['.prefab']);
|
||||
const sceneCount = this.countFiles(assetsDir, ['.scene']);
|
||||
|
||||
return [
|
||||
'Project Summary',
|
||||
`Project Root: ${projectPath}`,
|
||||
`Assets Path: ${assetsDir}`,
|
||||
`Cocos Creator: ${cocosVersion}`,
|
||||
`Extension Version: ${version}`,
|
||||
`Scripts: ${scriptCount}`,
|
||||
`Prefabs: ${prefabCount}`,
|
||||
`Scenes: ${sceneCount}`,
|
||||
'',
|
||||
`Top-Level Directories (${topLevel.length})`,
|
||||
...topLevel.map((name) => `- ${name}`),
|
||||
].join('\n');
|
||||
}
|
||||
|
||||
countFiles(rootDir, extensions) {
|
||||
if (!fs.existsSync(rootDir)) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
let count = 0;
|
||||
const stack = [rootDir];
|
||||
while (stack.length) {
|
||||
const current = stack.pop();
|
||||
const entries = fs.readdirSync(current, { withFileTypes: true });
|
||||
for (const entry of entries) {
|
||||
const fullPath = path.join(current, entry.name);
|
||||
if (entry.isDirectory()) {
|
||||
stack.push(fullPath);
|
||||
continue;
|
||||
}
|
||||
if (extensions.includes(path.extname(entry.name).toLowerCase())) {
|
||||
count += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
readAssetByPath(relativePath) {
|
||||
const { projectPath } = this.getRuntimeContext();
|
||||
const fullPath = resolveProjectPath(projectPath, relativePath);
|
||||
if (!fs.existsSync(fullPath)) {
|
||||
return `Asset not found: ${relativePath}`;
|
||||
}
|
||||
return truncate(`[${relativePath}]\n${fs.readFileSync(fullPath, 'utf8')}`);
|
||||
}
|
||||
|
||||
async safeSceneCall(method, payload) {
|
||||
try {
|
||||
const result = await this.sceneBridge.call(method, payload);
|
||||
return toText(result);
|
||||
} catch (error) {
|
||||
return `Scene bridge error (${method}): ${error.message}`;
|
||||
}
|
||||
}
|
||||
|
||||
async getSelectedAssetText() {
|
||||
try {
|
||||
const selection = getCurrentSelection();
|
||||
if (!selection.asset) {
|
||||
return 'No asset is currently selected.';
|
||||
}
|
||||
|
||||
return await this.getAssetInfoText(selection.asset);
|
||||
} catch (error) {
|
||||
return `Selected asset lookup failed: ${error.message}`;
|
||||
}
|
||||
}
|
||||
|
||||
async getAssetInfoText(uuidOrPath) {
|
||||
try {
|
||||
const info = await queryAssetInfo(uuidOrPath);
|
||||
const meta = await queryAssetMeta(uuidOrPath).catch(() => null);
|
||||
return JSON.stringify({ info, meta }, null, 2);
|
||||
} catch (error) {
|
||||
return `Asset lookup failed: ${error.message}`;
|
||||
}
|
||||
}
|
||||
|
||||
async getScriptDiagnosticsText(projectPath) {
|
||||
try {
|
||||
const result = await runScriptDiagnostics(projectPath);
|
||||
return JSON.stringify(result, null, 2);
|
||||
} catch (error) {
|
||||
return `Script diagnostics failed: ${error.message}`;
|
||||
}
|
||||
}
|
||||
|
||||
getEditorLogsText() {
|
||||
return [
|
||||
'MCP Runtime Logs',
|
||||
this.runtimeLog && typeof this.runtimeLog.summary === 'function'
|
||||
? this.runtimeLog.summary(80)
|
||||
: 'Runtime log is unavailable.',
|
||||
'',
|
||||
'MCP Tool Interactions',
|
||||
this.interactionLog && typeof this.interactionLog.summary === 'function'
|
||||
? this.interactionLog.summary(80)
|
||||
: 'Interaction log is unavailable.',
|
||||
].join('\n');
|
||||
}
|
||||
|
||||
getProjectLogsText(projectPath) {
|
||||
const logs = getRecentProjectLogs(projectPath, { limit: 10, lines: 100 });
|
||||
if (!logs.length) {
|
||||
return 'No project log files found in common project log directories.';
|
||||
}
|
||||
|
||||
return logs
|
||||
.map((log) => [
|
||||
`# ${log.path}`,
|
||||
`mtime: ${log.mtime}`,
|
||||
`size: ${log.size}`,
|
||||
'',
|
||||
log.text,
|
||||
].join('\n'))
|
||||
.join('\n\n---\n\n');
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
ResourceProvider,
|
||||
};
|
||||
+46
@@ -0,0 +1,46 @@
|
||||
'use strict';
|
||||
|
||||
class RuntimeLog {
|
||||
constructor(limit = 200) {
|
||||
this.limit = Math.max(10, Number(limit) || 200);
|
||||
this.entries = [];
|
||||
}
|
||||
|
||||
add(level, message, details) {
|
||||
this.entries.unshift({
|
||||
level: String(level || 'info'),
|
||||
message: String(message || ''),
|
||||
details: details === undefined ? null : details,
|
||||
timestamp: new Date().toISOString(),
|
||||
});
|
||||
|
||||
if (this.entries.length > this.limit) {
|
||||
this.entries.length = this.limit;
|
||||
}
|
||||
}
|
||||
|
||||
list(limit = 50) {
|
||||
return this.entries.slice(0, Math.max(1, Number(limit) || 50));
|
||||
}
|
||||
|
||||
clear() {
|
||||
const count = this.entries.length;
|
||||
this.entries.length = 0;
|
||||
return count;
|
||||
}
|
||||
|
||||
summary(limit = 50) {
|
||||
const items = this.list(limit);
|
||||
if (!items.length) {
|
||||
return 'No MCP runtime logs recorded yet.';
|
||||
}
|
||||
|
||||
return items
|
||||
.map((entry) => `[${entry.timestamp}] ${entry.level.toUpperCase()} ${entry.message}`)
|
||||
.join('\n');
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
RuntimeLog,
|
||||
};
|
||||
+129
@@ -0,0 +1,129 @@
|
||||
'use strict';
|
||||
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const { queryAssetInfo } = require('./assets');
|
||||
const { resolveProjectPath } = require('./path-safety');
|
||||
|
||||
function requestEditorMessage(channel, method, ...args) {
|
||||
if (!global.Editor || !Editor.Message || typeof Editor.Message.request !== 'function') {
|
||||
throw new Error('Editor.Message.request is unavailable in the Cocos extension host.');
|
||||
}
|
||||
return Editor.Message.request(channel, method, ...args);
|
||||
}
|
||||
|
||||
function normalizeSceneTarget(projectPath, target) {
|
||||
const raw = String(target || '').trim().replace(/\\/g, '/');
|
||||
if (!raw) {
|
||||
throw new Error('target is required.');
|
||||
}
|
||||
|
||||
let relative = raw;
|
||||
if (relative.startsWith('db://assets/')) {
|
||||
relative = relative.slice('db://'.length);
|
||||
} else if (relative.startsWith('/assets/')) {
|
||||
relative = relative.slice(1);
|
||||
} else if (!relative.startsWith('assets/')) {
|
||||
relative = `assets/${relative}`;
|
||||
}
|
||||
|
||||
if (!relative.endsWith('.scene')) {
|
||||
relative = `${relative}.scene`;
|
||||
}
|
||||
|
||||
const filePath = resolveProjectPath(projectPath, relative);
|
||||
const assetsRoot = path.join(projectPath, 'assets');
|
||||
const relativeToAssets = path.relative(assetsRoot, filePath);
|
||||
if (relativeToAssets.startsWith('..') || path.isAbsolute(relativeToAssets)) {
|
||||
throw new Error('target must be inside the Cocos assets directory.');
|
||||
}
|
||||
|
||||
const projectRelative = path.relative(projectPath, filePath).replace(/\\/g, '/');
|
||||
return {
|
||||
filePath,
|
||||
projectRelative,
|
||||
dbUrl: `db://${projectRelative}`,
|
||||
sceneName: path.basename(filePath, '.scene'),
|
||||
};
|
||||
}
|
||||
|
||||
async function queryAssetInfoOptional(target) {
|
||||
try {
|
||||
return await queryAssetInfo(target);
|
||||
} catch (error) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async function saveSceneContent(projectPath, options = {}) {
|
||||
const target = normalizeSceneTarget(projectPath, options.target);
|
||||
const content = String(options.content || '');
|
||||
if (!content) {
|
||||
throw new Error('content is required.');
|
||||
}
|
||||
|
||||
const parsed = JSON.parse(content);
|
||||
if (!Array.isArray(parsed) || !parsed.some((entry) => entry && entry.__type__ === 'cc.SceneAsset')) {
|
||||
throw new Error('content must contain a serialized cc.SceneAsset.');
|
||||
}
|
||||
|
||||
const existed = fs.existsSync(target.filePath);
|
||||
if (existed && options.overwrite !== true) {
|
||||
throw new Error(`Target scene already exists: ${target.projectRelative}`);
|
||||
}
|
||||
|
||||
fs.mkdirSync(path.dirname(target.filePath), { recursive: true });
|
||||
|
||||
let method = 'fs-write';
|
||||
let result;
|
||||
if (global.Editor && Editor.Message && typeof Editor.Message.request === 'function') {
|
||||
if (existed) {
|
||||
try {
|
||||
result = await requestEditorMessage('asset-db', 'save-asset', target.dbUrl, content);
|
||||
method = 'asset-db:save-asset';
|
||||
if (!fs.existsSync(target.filePath) || fs.readFileSync(target.filePath, 'utf8').trimEnd() !== content.trimEnd()) {
|
||||
fs.writeFileSync(target.filePath, content.endsWith('\n') ? content : `${content}\n`, 'utf8');
|
||||
}
|
||||
} catch (error) {
|
||||
fs.writeFileSync(target.filePath, content.endsWith('\n') ? content : `${content}\n`, 'utf8');
|
||||
result = { fallbackReason: error.message };
|
||||
}
|
||||
} else {
|
||||
try {
|
||||
result = await requestEditorMessage('asset-db', 'create-asset', target.dbUrl, content);
|
||||
method = 'asset-db:create-asset';
|
||||
} catch (error) {
|
||||
if (fs.existsSync(target.filePath)) {
|
||||
result = { fallbackReason: error.message, fileCreated: true };
|
||||
} else {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
fs.writeFileSync(target.filePath, content.endsWith('\n') ? content : `${content}\n`, 'utf8');
|
||||
}
|
||||
|
||||
const fileExists = fs.existsSync(target.filePath);
|
||||
const info = await queryAssetInfoOptional(target.dbUrl);
|
||||
if (!fileExists && !info) {
|
||||
throw new Error(`Scene was not created: ${target.projectRelative}`);
|
||||
}
|
||||
|
||||
return {
|
||||
created: !existed,
|
||||
overwritten: existed && options.overwrite === true,
|
||||
method,
|
||||
result,
|
||||
dbUrl: target.dbUrl,
|
||||
path: target.projectRelative,
|
||||
sceneName: target.sceneName,
|
||||
fileExists,
|
||||
info,
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
normalizeSceneTarget,
|
||||
saveSceneContent,
|
||||
};
|
||||
+130
@@ -0,0 +1,130 @@
|
||||
'use strict';
|
||||
|
||||
const fs = require('fs');
|
||||
const os = require('os');
|
||||
const path = require('path');
|
||||
const { execFile } = require('child_process');
|
||||
const crypto = require('crypto');
|
||||
const { resolveProjectFilePath } = require('./path-safety');
|
||||
const electronTools = require('./electron-tools');
|
||||
const { pngDimensions, readVisualState, registerCapture } = require('./visual-coordinates');
|
||||
|
||||
function ensureDir(dirPath) {
|
||||
fs.mkdirSync(dirPath, { recursive: true });
|
||||
}
|
||||
|
||||
function screenshotPath(projectPath, options, kind) {
|
||||
const outputDir = resolveProjectFilePath(projectPath, 'temp/mcp-captures');
|
||||
const fileName = options.fileName || `${kind}-${Date.now()}-${crypto.randomBytes(4).toString('hex')}.png`;
|
||||
if (typeof fileName !== 'string' || fileName.length > 180 || /[\\/\0<>:"|?*\r\n]/.test(fileName) || !fileName.toLowerCase().endsWith('.png') || fileName === '.png') {
|
||||
throw new Error('fileName must be a plain PNG filename under temp/mcp-captures.');
|
||||
}
|
||||
ensureDir(outputDir);
|
||||
return checkedScreenshotPath(projectPath, path.join(outputDir, fileName));
|
||||
}
|
||||
|
||||
function checkedScreenshotPath(projectPath, destination) {
|
||||
const filePath = resolveProjectFilePath(projectPath, destination);
|
||||
try {
|
||||
if (fs.lstatSync(filePath).isSymbolicLink()) throw new Error('Screenshot destination cannot be a symbolic link.');
|
||||
} catch (error) { if (error.code !== 'ENOENT') throw error; }
|
||||
return filePath;
|
||||
}
|
||||
|
||||
function exec(file, args) {
|
||||
return new Promise((resolve, reject) => {
|
||||
execFile(file, args, { maxBuffer: 8 * 1024 * 1024 }, (error, stdout, stderr) => {
|
||||
if (error) {
|
||||
reject(new Error(stderr || stdout || error.message));
|
||||
return;
|
||||
}
|
||||
resolve({ stdout, stderr });
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
async function captureDesktopScreenshot(projectPath, options = {}) {
|
||||
const filePath = screenshotPath(projectPath, options, 'desktop');
|
||||
|
||||
if (process.platform === 'darwin') {
|
||||
await exec('screencapture', ['-x', filePath]);
|
||||
} else if (process.platform === 'win32') {
|
||||
const script = `
|
||||
Add-Type -AssemblyName System.Windows.Forms
|
||||
Add-Type -AssemblyName System.Drawing
|
||||
$bounds = [System.Windows.Forms.SystemInformation]::VirtualScreen
|
||||
$bitmap = New-Object System.Drawing.Bitmap $bounds.Width, $bounds.Height
|
||||
$graphics = [System.Drawing.Graphics]::FromImage($bitmap)
|
||||
$graphics.CopyFromScreen($bounds.Location, [System.Drawing.Point]::Empty, $bounds.Size)
|
||||
$bitmap.Save('${filePath.replace(/'/g, "''")}', [System.Drawing.Imaging.ImageFormat]::Png)
|
||||
$graphics.Dispose()
|
||||
$bitmap.Dispose()
|
||||
`;
|
||||
await exec('powershell', ['-NoProfile', '-Command', script]);
|
||||
} else {
|
||||
try {
|
||||
await exec('gnome-screenshot', ['-f', filePath]);
|
||||
} catch (error) {
|
||||
await exec('import', ['-window', 'root', filePath]);
|
||||
}
|
||||
}
|
||||
|
||||
const data = fs.readFileSync(filePath).toString('base64');
|
||||
return {
|
||||
filePath,
|
||||
dataUri: `data:image/png;base64,${data}`,
|
||||
size: fs.statSync(filePath).size,
|
||||
platform: os.platform(),
|
||||
imageSize: pngDimensions(fs.readFileSync(filePath)),
|
||||
interactive: false,
|
||||
reason: 'Desktop capture has no Electron window calibration.',
|
||||
};
|
||||
}
|
||||
|
||||
async function captureEditorWindowScreenshot(projectPath, options = {}) {
|
||||
const filePath = screenshotPath(projectPath, options, 'editor');
|
||||
const target = electronTools.pickWindow(options);
|
||||
const before = await readVisualState(target, null, options.getContext);
|
||||
const image = await target.capturePage();
|
||||
const png = image.toPNG();
|
||||
const after = await readVisualState(target, null, options.getContext);
|
||||
const geometry = registerCapture(target, png, before, after, { ...options, panel: null, projectPath });
|
||||
fs.writeFileSync(checkedScreenshotPath(projectPath, filePath), png);
|
||||
|
||||
return {
|
||||
filePath,
|
||||
dataUri: `data:image/png;base64,${png.toString('base64')}`,
|
||||
size: png.length,
|
||||
title: typeof target.getTitle === 'function' ? target.getTitle() : '',
|
||||
captureId: geometry.captureId,
|
||||
geometry,
|
||||
};
|
||||
}
|
||||
|
||||
async function capturePanelScreenshot(projectPath, options = {}) {
|
||||
const panel = options.panel || 'scene';
|
||||
const filePath = screenshotPath(projectPath, options, panel);
|
||||
const target = electronTools.pickWindow(options);
|
||||
const before = await readVisualState(target, panel, options.getContext);
|
||||
const image = await target.capturePage(before.inputBounds);
|
||||
const png = image.toPNG();
|
||||
const after = await readVisualState(target, panel, options.getContext);
|
||||
const geometry = registerCapture(target, png, before, after, { ...options, panel, projectPath });
|
||||
fs.writeFileSync(checkedScreenshotPath(projectPath, filePath), png);
|
||||
|
||||
return {
|
||||
filePath,
|
||||
dataUri: `data:image/png;base64,${png.toString('base64')}`,
|
||||
size: png.length,
|
||||
title: typeof target.getTitle === 'function' ? target.getTitle() : '',
|
||||
bounds: before.panelBounds,
|
||||
captureId: geometry.captureId,
|
||||
geometry,
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
captureDesktopScreenshot,
|
||||
captureEditorWindowScreenshot,
|
||||
capturePanelScreenshot,
|
||||
};
|
||||
@@ -0,0 +1,63 @@
|
||||
'use strict';
|
||||
|
||||
const { formatWithOptions, types } = require('util');
|
||||
const { createActivityPreview, sanitizeActivityText } = require('./activity-preview');
|
||||
|
||||
const SCRIPT_EXECUTION_PACKET = 'funplay.script-execution.v1';
|
||||
const LOG_LIMITS = { entries: 50, message: 1000, characters: 20000 };
|
||||
|
||||
// Inject a console into this invocation only. Never patch the process console:
|
||||
// concurrent/nested scripts and ordinary project logging must stay independent.
|
||||
async function captureScriptExecution(run, { context, targetConsole = console }) {
|
||||
const logs = [];
|
||||
let logsOmitted = 0;
|
||||
let characters = 0;
|
||||
let active = true;
|
||||
const started = Date.now();
|
||||
const methods = Object.create(null);
|
||||
for (const method of ['log', 'info', 'warn', 'error', 'debug']) {
|
||||
methods[method] = (...values) => {
|
||||
if (active) {
|
||||
if (logs.length >= LOG_LIMITS.entries || characters >= LOG_LIMITS.characters) {
|
||||
logsOmitted++;
|
||||
} else {
|
||||
// No custom inspection or getter evaluation while retaining a log.
|
||||
let message;
|
||||
try {
|
||||
const safe = values.slice(0, 20).map((value) => types.isNativeError(value)
|
||||
? sanitizeActivityText(Object.getOwnPropertyDescriptor(value, 'message')?.value || 'Error')
|
||||
: createActivityPreview(value));
|
||||
message = sanitizeActivityText(formatWithOptions({
|
||||
depth: 6, getters: false, customInspect: false, maxArrayLength: 12,
|
||||
}, ...safe), Math.min(LOG_LIMITS.message, LOG_LIMITS.characters - characters));
|
||||
} catch (error) { message = '[unavailable]'; }
|
||||
logs.push({ level: method === 'log' ? 'info' : method, message });
|
||||
characters += message.length;
|
||||
}
|
||||
}
|
||||
// The MCP print preference only controls MCP's own logger, not user scripts.
|
||||
if (typeof targetConsole[method] === 'function') targetConsole[method](...values);
|
||||
};
|
||||
}
|
||||
const scriptConsole = new Proxy(methods, {
|
||||
get(target, key) {
|
||||
if (Object.prototype.hasOwnProperty.call(target, key)) return target[key];
|
||||
const value = targetConsole[key];
|
||||
return typeof value === 'function' ? value.bind(targetConsole) : value;
|
||||
},
|
||||
});
|
||||
const packet = { kind: SCRIPT_EXECUTION_PACKET };
|
||||
try {
|
||||
packet.value = await run(scriptConsole);
|
||||
} catch (error) {
|
||||
let message = 'Script execution failed.';
|
||||
try { message = String(error && error.message || error); } catch (_) { /* Keep the fallback. */ }
|
||||
packet.error = { message };
|
||||
} finally {
|
||||
active = false;
|
||||
packet.execution = { context, durationMs: Math.max(0, Date.now() - started), logs, logsOmitted };
|
||||
}
|
||||
return packet;
|
||||
}
|
||||
|
||||
module.exports = { captureScriptExecution, SCRIPT_EXECUTION_PACKET, LOG_LIMITS };
|
||||
+852
@@ -0,0 +1,852 @@
|
||||
'use strict';
|
||||
|
||||
const crypto = require('crypto');
|
||||
const http = require('http');
|
||||
const { safeStringify } = require('./utils');
|
||||
const { CONTEXT_META_KEY, projectContext, projectEndpoint, serverUrl, requestRoute, contextError, withContextSchema } = require('./project-context');
|
||||
const IMAGE_DATA_URI_PREFIX = 'data:image/png;base64,';
|
||||
const LOG_PREFIX = '[Funplay Cocos MCP Server]';
|
||||
const MAX_PORT_FALLBACK_ATTEMPTS = 20;
|
||||
const MAX_REQUEST_BODY_BYTES = 4 * 1024 * 1024;
|
||||
const MCP_PROTOCOL_VERSION = '2025-11-25';
|
||||
const SUPPORTED_PROTOCOL_VERSIONS = [
|
||||
MCP_PROTOCOL_VERSION,
|
||||
'2025-06-18',
|
||||
'2025-03-26',
|
||||
'2024-11-05',
|
||||
];
|
||||
|
||||
function responseHeaders(protocolVersion = MCP_PROTOCOL_VERSION, extraHeaders = {}) {
|
||||
return {
|
||||
'MCP-Protocol-Version': protocolVersion,
|
||||
...extraHeaders,
|
||||
};
|
||||
}
|
||||
|
||||
function json(response, statusCode, payload, protocolVersion = MCP_PROTOCOL_VERSION, extraHeaders = {}) {
|
||||
response.writeHead(statusCode, {
|
||||
'Content-Type': 'application/json; charset=utf-8',
|
||||
...responseHeaders(protocolVersion, extraHeaders),
|
||||
});
|
||||
response.end(JSON.stringify(payload));
|
||||
}
|
||||
|
||||
function empty(response, statusCode, protocolVersion = MCP_PROTOCOL_VERSION, extraHeaders = {}) {
|
||||
response.writeHead(statusCode, responseHeaders(protocolVersion, extraHeaders));
|
||||
response.end();
|
||||
}
|
||||
|
||||
function textContent(value, metadataText) {
|
||||
if (typeof value === 'string' && value.startsWith(IMAGE_DATA_URI_PREFIX)) {
|
||||
return [
|
||||
{
|
||||
type: 'image',
|
||||
data: value.slice(IMAGE_DATA_URI_PREFIX.length),
|
||||
mimeType: 'image/png',
|
||||
},
|
||||
{
|
||||
type: 'text',
|
||||
text: metadataText || 'Screenshot captured successfully.',
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
return [
|
||||
{
|
||||
type: 'text',
|
||||
text: typeof value === 'string' ? value : JSON.stringify(value, null, 2),
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
function isStructuredValue(value) {
|
||||
return value !== null && typeof value === 'object' && !Buffer.isBuffer(value);
|
||||
}
|
||||
|
||||
function structuredContent(value) {
|
||||
if (!isStructuredValue(value)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
return JSON.parse(safeStringify(value));
|
||||
} catch (error) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
class McpServer {
|
||||
constructor(options) {
|
||||
this.config = options.config;
|
||||
this.toolRegistry = options.toolRegistry;
|
||||
this.resourceProvider = options.resourceProvider;
|
||||
this.promptProvider = options.promptProvider;
|
||||
this.interactionLog = options.interactionLog;
|
||||
this.runtimeLog = options.runtimeLog;
|
||||
this.serverName = options.serverName;
|
||||
this.serverVersion = options.serverVersion;
|
||||
this.projectName = options.projectName || '';
|
||||
this.projectIdentity = options.projectIdentity || '';
|
||||
this.context = projectContext({ projectIdentity: this.projectIdentity, projectPath: options.projectPath || this.config.projectPath,
|
||||
instanceId: options.instanceId || crypto.randomBytes(16).toString('hex') });
|
||||
this.getActiveContext = options.getActiveContext;
|
||||
this.server = null;
|
||||
this.attached = false;
|
||||
this.attachedInfo = null;
|
||||
this.actualPort = null;
|
||||
this.portFallbackInfo = null;
|
||||
this.negotiatedProtocolVersion = MCP_PROTOCOL_VERSION;
|
||||
this.enableSessions = Boolean(this.config && this.config.enableSessions);
|
||||
this.sessions = new Set();
|
||||
}
|
||||
|
||||
isRunning() {
|
||||
return Boolean(this.attached || (this.server && this.server.listening));
|
||||
}
|
||||
|
||||
getPort() {
|
||||
if (this.attached && this.actualPort) {
|
||||
return this.actualPort;
|
||||
}
|
||||
if (this.server && typeof this.server.address === 'function') {
|
||||
const address = this.server.address();
|
||||
if (address && typeof address.port === 'number') {
|
||||
return address.port;
|
||||
}
|
||||
}
|
||||
return this.actualPort || this.config.port;
|
||||
}
|
||||
|
||||
getRequestedPort() {
|
||||
return this.config.port;
|
||||
}
|
||||
|
||||
getPortFallbackInfo() {
|
||||
return this.portFallbackInfo;
|
||||
}
|
||||
|
||||
getAttachInfo() {
|
||||
return this.attachedInfo;
|
||||
}
|
||||
|
||||
getProjectContext() {
|
||||
return this.attachedInfo && this.attachedInfo.context || this.context;
|
||||
}
|
||||
|
||||
rejectContext(id, code) {
|
||||
const response = this.createError(id, -32001, code);
|
||||
response.error.data = { code,
|
||||
recovery: 'Reconnect using this project\'s generated scoped URL, or independently verify initialize.funplay.context against the intended project and pass its expected_context. Do not automatically trust a token from an arbitrary responding server.' };
|
||||
return response;
|
||||
}
|
||||
|
||||
log(level, message) {
|
||||
if (this.runtimeLog && typeof this.runtimeLog.add === 'function') {
|
||||
this.runtimeLog.add(level, message);
|
||||
}
|
||||
if (this.config && this.config.enableConsoleLogging === false) return;
|
||||
|
||||
const output = `${LOG_PREFIX} ${message}`;
|
||||
if (level === 'error') {
|
||||
console.error(output);
|
||||
} else if (level === 'warn') {
|
||||
console.warn(output);
|
||||
} else {
|
||||
console.log(output);
|
||||
}
|
||||
}
|
||||
|
||||
async start() {
|
||||
if (this.isRunning()) {
|
||||
this.log('info', 'Start skipped: already running.');
|
||||
return;
|
||||
}
|
||||
|
||||
this.actualPort = null;
|
||||
this.portFallbackInfo = null;
|
||||
this.attached = false;
|
||||
this.attachedInfo = null;
|
||||
|
||||
const requestHandler = async (request, response) => {
|
||||
try {
|
||||
const requestUrl = new URL(request.url || '/', 'http://localhost');
|
||||
if (!this.isAllowedOrigin(request)) {
|
||||
this.log('warn', `Rejected ${request.method} ${request.url}: invalid Origin header.`);
|
||||
return json(response, 403, { error: 'Forbidden: invalid Origin header' }, this.negotiatedProtocolVersion);
|
||||
}
|
||||
const route = requestRoute(requestUrl.pathname, this.projectIdentity);
|
||||
if (route.error) return json(response, route.status, { error: route.error }, this.negotiatedProtocolVersion);
|
||||
if (request.method === 'GET' && route.kind === 'health') {
|
||||
this.log('info', 'GET /health');
|
||||
return json(response, 200, {
|
||||
ok: true,
|
||||
name: this.serverName,
|
||||
version: this.serverVersion,
|
||||
projectName: this.projectName,
|
||||
projectIdentity: this.projectIdentity,
|
||||
context: this.getProjectContext(),
|
||||
}, this.negotiatedProtocolVersion);
|
||||
}
|
||||
|
||||
if (request.method === 'GET' && route.kind === 'tools') {
|
||||
this.log('info', 'GET /tools');
|
||||
const includeCatalog = requestUrl.searchParams.get('catalog') === '1';
|
||||
const tools = includeCatalog && typeof this.toolRegistry.listToolCatalog === 'function'
|
||||
? this.toolRegistry.listToolCatalog()
|
||||
: this.toolRegistry.listTools().map(withContextSchema);
|
||||
const baseUrl = `http://${request.headers.host || `${this.config.host}:${this.getPort()}`}${route.scoped ? projectEndpoint(this.projectIdentity).replace(/\/$/, '') : ''}`;
|
||||
return json(response, 200, {
|
||||
ok: true,
|
||||
name: this.serverName,
|
||||
version: this.serverVersion,
|
||||
count: tools.length,
|
||||
context: this.getProjectContext(),
|
||||
tools,
|
||||
examples: {
|
||||
health: `curl ${baseUrl}/health`,
|
||||
tools: `curl ${baseUrl}/tools`,
|
||||
catalog: `curl ${baseUrl}/tools?catalog=1`,
|
||||
},
|
||||
}, this.negotiatedProtocolVersion);
|
||||
}
|
||||
|
||||
if (route.kind !== 'rpc') return json(response, 405, { error: 'Method Not Allowed' }, this.negotiatedProtocolVersion);
|
||||
|
||||
if (request.method === 'DELETE') {
|
||||
return this.handleDelete(request, response);
|
||||
}
|
||||
|
||||
if (request.method === 'GET') {
|
||||
// An SSE GET probe is normal MCP negotiation; 405 is the supported
|
||||
// response when no SSE stream is offered, not a warning to log.
|
||||
return json(response, 405, { error: 'Method Not Allowed: SSE streams are not supported' }, this.negotiatedProtocolVersion);
|
||||
}
|
||||
|
||||
if (request.method !== 'POST') {
|
||||
this.log('warn', `Rejected ${request.method} ${request.url}: method not allowed.`);
|
||||
return json(response, 405, { error: 'Method Not Allowed' }, this.negotiatedProtocolVersion);
|
||||
}
|
||||
|
||||
const acceptHeaderError = this.validateAcceptHeader(request);
|
||||
if (acceptHeaderError) {
|
||||
return json(response, 406, acceptHeaderError, this.negotiatedProtocolVersion);
|
||||
}
|
||||
|
||||
const body = await this.readBody(request);
|
||||
if (!body) {
|
||||
return json(response, 400, this.createError(null, -32700, 'Parse error: empty body'), this.negotiatedProtocolVersion);
|
||||
}
|
||||
|
||||
let rpc;
|
||||
try {
|
||||
rpc = JSON.parse(body);
|
||||
} catch (error) {
|
||||
return json(response, 400, this.createError(null, -32700, `Parse error: ${error.message}`), this.negotiatedProtocolVersion);
|
||||
}
|
||||
|
||||
if (rpc && rpc.method) {
|
||||
this.log('info', `RPC ${rpc.method}`);
|
||||
}
|
||||
|
||||
const protocolHeaderError = this.validateProtocolVersionHeader(request, rpc);
|
||||
if (protocolHeaderError) {
|
||||
return json(response, 400, protocolHeaderError, this.negotiatedProtocolVersion);
|
||||
}
|
||||
const responseProtocolVersion = this.getProtocolVersionForResponse(request, rpc);
|
||||
|
||||
const sessionError = this.validateSession(request, rpc);
|
||||
if (sessionError) {
|
||||
return json(response, sessionError.statusCode, sessionError.error, responseProtocolVersion);
|
||||
}
|
||||
|
||||
const messageType = this.classifyJsonRpcMessage(rpc);
|
||||
if (messageType === 'response') {
|
||||
return empty(response, 202, responseProtocolVersion);
|
||||
}
|
||||
|
||||
if (messageType === 'notification') {
|
||||
const notificationError = this.handleRpcNotification(rpc);
|
||||
if (notificationError) {
|
||||
return json(response, 400, notificationError, responseProtocolVersion);
|
||||
}
|
||||
return empty(response, 202, responseProtocolVersion);
|
||||
}
|
||||
|
||||
if (messageType !== 'request') {
|
||||
return json(response, 400, this.createError(rpc && rpc.id, -32600, 'Invalid Request'), responseProtocolVersion);
|
||||
}
|
||||
|
||||
const result = await this.handleRpcRequest(rpc, route);
|
||||
if (result == null) {
|
||||
return empty(response, 202, responseProtocolVersion);
|
||||
}
|
||||
|
||||
const extraHeaders = {};
|
||||
if (this.enableSessions && rpc.method === 'initialize' && result && !result.error) {
|
||||
const sessionId = this.createSessionId();
|
||||
this.sessions.add(sessionId);
|
||||
extraHeaders['Mcp-Session-Id'] = sessionId;
|
||||
}
|
||||
|
||||
return json(response, 200, result, this.getProtocolVersionForResponse(request, rpc), extraHeaders);
|
||||
} catch (error) {
|
||||
this.log('error', `Request handling failed: ${error.message}`);
|
||||
const statusCode = error.statusCode || 500;
|
||||
const rpcCode = error.rpcCode || -32603;
|
||||
const message = statusCode === 500 ? `Internal error: ${error.message}` : error.message;
|
||||
return json(response, statusCode, this.createError(null, rpcCode, message), this.negotiatedProtocolVersion);
|
||||
}
|
||||
};
|
||||
|
||||
let attempt = 0;
|
||||
let port = this.config.port;
|
||||
let lastError = null;
|
||||
|
||||
while (attempt <= MAX_PORT_FALLBACK_ATTEMPTS) {
|
||||
this.log('info', `Creating HTTP server on ${this.config.host}:${port}...`);
|
||||
const candidate = http.createServer(requestHandler);
|
||||
|
||||
try {
|
||||
await this.listen(candidate, port, this.config.host);
|
||||
this.server = candidate;
|
||||
this.actualPort = candidate.address() && typeof candidate.address().port === 'number'
|
||||
? candidate.address().port
|
||||
: port;
|
||||
|
||||
if (this.config.port !== 0 && this.actualPort !== this.config.port) {
|
||||
this.portFallbackInfo = {
|
||||
requestedPort: this.config.port,
|
||||
actualPort: this.actualPort,
|
||||
attempts: attempt,
|
||||
};
|
||||
this.log(
|
||||
'warn',
|
||||
`Port ${this.config.port} was unavailable. Fell back to ${this.actualPort}.`
|
||||
);
|
||||
}
|
||||
|
||||
this.log('info', `Listening on ${serverUrl(this.config, this.actualPort, this.projectIdentity)}`);
|
||||
return;
|
||||
} catch (error) {
|
||||
lastError = error;
|
||||
candidate.removeAllListeners();
|
||||
if (error && error.code === 'EADDRINUSE' && port < 65535 && attempt < MAX_PORT_FALLBACK_ATTEMPTS) {
|
||||
if (await this.tryAttachToExisting(port)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const nextPort = port + 1;
|
||||
this.log(
|
||||
'warn',
|
||||
`Port ${port} is already in use. Trying fallback port ${nextPort}...`
|
||||
);
|
||||
port = nextPort;
|
||||
attempt += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
this.server = null;
|
||||
this.actualPort = null;
|
||||
this.portFallbackInfo = null;
|
||||
throw lastError || new Error('Failed to start MCP server.');
|
||||
}
|
||||
|
||||
async stop() {
|
||||
if (this.attached) {
|
||||
this.log('info', `Detached from existing MCP listener on ${this.config.host}:${this.actualPort}.`);
|
||||
this.attached = false;
|
||||
this.attachedInfo = null;
|
||||
this.actualPort = null;
|
||||
this.portFallbackInfo = null;
|
||||
return;
|
||||
}
|
||||
|
||||
if (!this.server) {
|
||||
this.log('info', 'Stop skipped: server object is empty.');
|
||||
return;
|
||||
}
|
||||
|
||||
this.log('info', 'Closing HTTP server...');
|
||||
const active = this.server;
|
||||
this.server = null;
|
||||
this.actualPort = null;
|
||||
this.portFallbackInfo = null;
|
||||
this.attachedInfo = null;
|
||||
await new Promise((resolve, reject) => {
|
||||
active.close((error) => {
|
||||
if (error) {
|
||||
this.log('error', `Close failed: ${error.message}`);
|
||||
reject(error);
|
||||
return;
|
||||
}
|
||||
this.log('info', 'HTTP server closed.');
|
||||
resolve();
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
async tryAttachToExisting(port) {
|
||||
if (!this.projectIdentity || this.config.attachToExisting === false || port === 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const probe = await this.probeExistingServer(port);
|
||||
if (!probe || !probe.result) {
|
||||
this.log('warn', `Port ${port} is occupied, but no compatible Funplay MCP initialize response was received.`);
|
||||
return false;
|
||||
}
|
||||
|
||||
const result = probe.result || {};
|
||||
const serverInfo = result.serverInfo || {};
|
||||
const funplay = result.funplay || {};
|
||||
const remoteProjectIdentity = funplay.projectIdentity || serverInfo.projectIdentity || '';
|
||||
const remoteName = serverInfo.name || '';
|
||||
|
||||
if (remoteName === this.serverName && remoteProjectIdentity === this.projectIdentity
|
||||
&& funplay.routingVersion === 1 && funplay.context && funplay.context.project_id === this.projectIdentity
|
||||
&& typeof funplay.context.instance_id === 'string' && funplay.context.instance_id
|
||||
&& funplay.context.expected_context === `${this.projectIdentity}:${funplay.context.instance_id}`) {
|
||||
this.attached = true;
|
||||
this.attachedInfo = {
|
||||
host: this.config.host,
|
||||
port,
|
||||
serverName: remoteName,
|
||||
projectName: funplay.projectName || this.projectName,
|
||||
projectIdentity: remoteProjectIdentity,
|
||||
version: serverInfo.version || '',
|
||||
context: funplay.context,
|
||||
};
|
||||
this.actualPort = port;
|
||||
this.portFallbackInfo = null;
|
||||
this.log('info', `Attached to existing MCP listener for this project at http://${this.config.host}:${port}/.`);
|
||||
return true;
|
||||
}
|
||||
|
||||
this.log(
|
||||
'warn',
|
||||
`Port ${port} belongs to another listener; expected name=${this.serverName}, project=${this.projectIdentity}, ` +
|
||||
`got name=${remoteName || 'unknown'}, project=${remoteProjectIdentity || 'unknown'}.`
|
||||
);
|
||||
return false;
|
||||
}
|
||||
|
||||
probeExistingServer(port) {
|
||||
const body = JSON.stringify({
|
||||
jsonrpc: '2.0',
|
||||
id: 'funplay-probe',
|
||||
method: 'initialize',
|
||||
params: {
|
||||
protocolVersion: MCP_PROTOCOL_VERSION,
|
||||
clientInfo: {
|
||||
name: 'funplay-cocos-mcp-probe',
|
||||
version: this.serverVersion,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
return new Promise((resolve) => {
|
||||
const request = http.request(
|
||||
{
|
||||
host: this.config.host,
|
||||
port,
|
||||
method: 'POST',
|
||||
path: '/',
|
||||
timeout: 600,
|
||||
headers: {
|
||||
Accept: 'application/json, text/event-stream',
|
||||
'Content-Type': 'application/json',
|
||||
'Content-Length': Buffer.byteLength(body),
|
||||
},
|
||||
},
|
||||
(response) => {
|
||||
const chunks = [];
|
||||
response.on('data', (chunk) => chunks.push(chunk));
|
||||
response.on('end', () => {
|
||||
if (response.statusCode !== 200) {
|
||||
resolve(null);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
resolve(JSON.parse(Buffer.concat(chunks).toString('utf8')));
|
||||
} catch (error) {
|
||||
resolve(null);
|
||||
}
|
||||
});
|
||||
}
|
||||
);
|
||||
request.on('timeout', () => {
|
||||
request.destroy();
|
||||
resolve(null);
|
||||
});
|
||||
request.on('error', () => resolve(null));
|
||||
request.end(body);
|
||||
});
|
||||
}
|
||||
|
||||
listen(server, port, host) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const onError = (error) => {
|
||||
server.off('listening', onListening);
|
||||
reject(error);
|
||||
};
|
||||
const onListening = () => {
|
||||
server.off('error', onError);
|
||||
resolve();
|
||||
};
|
||||
server.once('error', onError);
|
||||
server.once('listening', onListening);
|
||||
server.listen(port, host);
|
||||
});
|
||||
}
|
||||
|
||||
readBody(request) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const chunks = [];
|
||||
let size = 0;
|
||||
request.on('data', (chunk) => {
|
||||
size += chunk.length;
|
||||
if (size > MAX_REQUEST_BODY_BYTES) {
|
||||
const error = new Error(`Request body exceeds ${MAX_REQUEST_BODY_BYTES} bytes.`);
|
||||
error.statusCode = 413;
|
||||
error.rpcCode = -32600;
|
||||
reject(error);
|
||||
request.destroy();
|
||||
return;
|
||||
}
|
||||
chunks.push(chunk);
|
||||
});
|
||||
request.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')));
|
||||
request.on('error', reject);
|
||||
});
|
||||
}
|
||||
|
||||
isAllowedOrigin(request) {
|
||||
const origin = request.headers && request.headers.origin;
|
||||
if (!origin) {
|
||||
return true;
|
||||
}
|
||||
|
||||
try {
|
||||
const parsed = new URL(String(origin));
|
||||
const hostname = parsed.hostname.toLowerCase();
|
||||
const configuredHost = String(this.config.host || '').toLowerCase();
|
||||
return hostname === 'localhost'
|
||||
|| hostname === '127.0.0.1'
|
||||
|| hostname === '::1'
|
||||
|| (configuredHost && hostname === configuredHost);
|
||||
} catch (error) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
validateAcceptHeader(request) {
|
||||
const header = request.headers && request.headers.accept;
|
||||
if (!header) {
|
||||
return this.createError(
|
||||
null,
|
||||
-32600,
|
||||
'Missing Accept header. Streamable HTTP clients must accept application/json and text/event-stream.'
|
||||
);
|
||||
}
|
||||
|
||||
const tokens = String(Array.isArray(header) ? header.join(',') : header)
|
||||
.split(',')
|
||||
.map((item) => item.split(';')[0].trim().toLowerCase())
|
||||
.filter(Boolean);
|
||||
const hasWildcard = tokens.includes('*/*');
|
||||
const hasJson = hasWildcard || tokens.includes('application/json') || tokens.includes('application/*');
|
||||
const hasSse = hasWildcard || tokens.includes('text/event-stream') || tokens.includes('text/*');
|
||||
|
||||
if (!hasJson || !hasSse) {
|
||||
return this.createError(
|
||||
null,
|
||||
-32600,
|
||||
'Invalid Accept header. Streamable HTTP clients must accept both application/json and text/event-stream.'
|
||||
);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
validateProtocolVersionHeader(request, rpc) {
|
||||
const header = request.headers && request.headers['mcp-protocol-version'];
|
||||
if (!header || (rpc && rpc.method === 'initialize')) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const version = Array.isArray(header) ? header[0] : String(header);
|
||||
if (!SUPPORTED_PROTOCOL_VERSIONS.includes(version)) {
|
||||
return this.createError(
|
||||
rpc && rpc.id,
|
||||
-32600,
|
||||
`Unsupported MCP protocol version header: ${version}`
|
||||
);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
getProtocolVersionForResponse(request, rpc) {
|
||||
if (rpc && rpc.method === 'initialize') {
|
||||
return this.negotiatedProtocolVersion;
|
||||
}
|
||||
|
||||
const header = request.headers && request.headers['mcp-protocol-version'];
|
||||
const version = Array.isArray(header) ? header[0] : header ? String(header) : '';
|
||||
if (SUPPORTED_PROTOCOL_VERSIONS.includes(version)) {
|
||||
return version;
|
||||
}
|
||||
return this.negotiatedProtocolVersion;
|
||||
}
|
||||
|
||||
validateSession(request, rpc) {
|
||||
if (!this.enableSessions || (rpc && rpc.method === 'initialize')) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const sessionId = this.getSessionId(request);
|
||||
if (!sessionId) {
|
||||
return {
|
||||
statusCode: 400,
|
||||
error: this.createError(rpc && rpc.id, -32600, 'Missing Mcp-Session-Id header.'),
|
||||
};
|
||||
}
|
||||
if (!this.sessions.has(sessionId)) {
|
||||
return {
|
||||
statusCode: 404,
|
||||
error: this.createError(rpc && rpc.id, -32001, 'Unknown or expired MCP session.'),
|
||||
};
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
getSessionId(request) {
|
||||
const value = request.headers && (request.headers['mcp-session-id'] || request.headers['Mcp-Session-Id']);
|
||||
if (Array.isArray(value)) {
|
||||
return value[0] || '';
|
||||
}
|
||||
return value ? String(value) : '';
|
||||
}
|
||||
|
||||
createSessionId() {
|
||||
if (typeof crypto.randomUUID === 'function') {
|
||||
return crypto.randomUUID();
|
||||
}
|
||||
return crypto.randomBytes(16).toString('hex');
|
||||
}
|
||||
|
||||
handleDelete(request, response) {
|
||||
if (!this.enableSessions) {
|
||||
return json(response, 405, { error: 'Method Not Allowed: MCP sessions are disabled' }, this.negotiatedProtocolVersion);
|
||||
}
|
||||
|
||||
const sessionId = this.getSessionId(request);
|
||||
if (!sessionId) {
|
||||
return json(
|
||||
response,
|
||||
400,
|
||||
this.createError(null, -32600, 'Missing Mcp-Session-Id header.'),
|
||||
this.negotiatedProtocolVersion
|
||||
);
|
||||
}
|
||||
if (!this.sessions.has(sessionId)) {
|
||||
return json(
|
||||
response,
|
||||
404,
|
||||
this.createError(null, -32001, 'Unknown or expired MCP session.'),
|
||||
this.negotiatedProtocolVersion
|
||||
);
|
||||
}
|
||||
|
||||
this.sessions.delete(sessionId);
|
||||
return empty(response, 202, this.negotiatedProtocolVersion);
|
||||
}
|
||||
|
||||
classifyJsonRpcMessage(message) {
|
||||
if (!message || message.jsonrpc !== '2.0') {
|
||||
return 'invalid';
|
||||
}
|
||||
if (typeof message.method === 'string') {
|
||||
return Object.prototype.hasOwnProperty.call(message, 'id') ? 'request' : 'notification';
|
||||
}
|
||||
if (
|
||||
Object.prototype.hasOwnProperty.call(message, 'id') &&
|
||||
(Object.prototype.hasOwnProperty.call(message, 'result') || Object.prototype.hasOwnProperty.call(message, 'error'))
|
||||
) {
|
||||
return 'response';
|
||||
}
|
||||
return 'invalid';
|
||||
}
|
||||
|
||||
handleRpcNotification(notification) {
|
||||
if (!notification || notification.jsonrpc !== '2.0' || typeof notification.method !== 'string') {
|
||||
return this.createError(null, -32600, 'Invalid Request');
|
||||
}
|
||||
|
||||
if (notification.method.startsWith('notifications/')) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return this.createError(null, -32601, `Notification method not found: ${notification.method}`);
|
||||
}
|
||||
|
||||
async handleRpcRequest(request, route = {}) {
|
||||
if (!request || request.jsonrpc !== '2.0') {
|
||||
return this.createError(request && request.id, -32600, 'Invalid Request');
|
||||
}
|
||||
|
||||
const method = request.method;
|
||||
if (typeof method !== 'string' || !method) {
|
||||
return this.createError(request.id, -32600, 'Invalid Request: method is required');
|
||||
}
|
||||
if (this.getActiveContext) {
|
||||
let active;
|
||||
try { active = this.getActiveContext(); } catch (error) { return this.rejectContext(request.id, 'PROJECT_CONTEXT_UNAVAILABLE'); }
|
||||
if (!active || active.project_id !== this.context.project_id
|
||||
|| active.instance_id !== this.context.instance_id) return this.rejectContext(request.id, 'PROJECT_CONTEXT_MISMATCH');
|
||||
}
|
||||
|
||||
if (method === 'initialize') {
|
||||
this.negotiatedProtocolVersion = this.negotiateProtocolVersion(request.params && request.params.protocolVersion);
|
||||
return this.createResult(request.id, {
|
||||
protocolVersion: this.negotiatedProtocolVersion,
|
||||
serverInfo: {
|
||||
name: this.serverName,
|
||||
version: this.serverVersion,
|
||||
},
|
||||
funplay: {
|
||||
server: 'funplay-cocos-mcp',
|
||||
projectName: this.projectName,
|
||||
projectIdentity: this.projectIdentity,
|
||||
routingVersion: 1,
|
||||
context: this.getProjectContext(),
|
||||
},
|
||||
capabilities: {
|
||||
tools: {},
|
||||
resources: {},
|
||||
prompts: {},
|
||||
},
|
||||
instructions: 'Independently compare initialize.funplay.context.project_path and project_id with the intended project before writes. Generated /mcp/project/<project_id>/ URLs guard project routing. Legacy URLs remain readable but mutations require expected_context in arguments or params._meta; explicit pins also detect an Editor restart. Identity guards are not authentication. Input event delivery is not proof of gameplay acceptance.',
|
||||
});
|
||||
}
|
||||
|
||||
if (method === 'notifications/initialized' || method === 'notifications/cancelled' || method.startsWith('notifications/')) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (method === 'tools/list') {
|
||||
return this.createResult(request.id, { tools: this.toolRegistry.listTools().map(withContextSchema) });
|
||||
}
|
||||
|
||||
if (method === 'tools/call') {
|
||||
const params = request.params || {};
|
||||
if (typeof params.name !== 'string' || !params.name) {
|
||||
return this.createError(request.id, -32602, "Invalid params: 'name' is required");
|
||||
}
|
||||
|
||||
const tool = this.toolRegistry.listTools().find((item) => item.name === params.name);
|
||||
const guard = contextError(this.getProjectContext(), params, {
|
||||
scoped: route.scoped === true,
|
||||
readOnly: Boolean(tool && tool.annotations && tool.annotations.readOnlyHint === true),
|
||||
});
|
||||
if (guard) return this.rejectContext(request.id, guard);
|
||||
const args = { ...(params.arguments || {}) };
|
||||
delete args.expected_context;
|
||||
|
||||
try {
|
||||
const output = typeof this.toolRegistry.callToolDetailed === 'function'
|
||||
? await this.toolRegistry.callToolDetailed(params.name, args)
|
||||
: { value: null, text: await this.toolRegistry.callTool(params.name, args) };
|
||||
const result = { content: textContent(output.text, output.metadataText), _meta: { [CONTEXT_META_KEY]: this.getProjectContext() } };
|
||||
const structured = structuredContent(output.value);
|
||||
if (structured) {
|
||||
result.structuredContent = structured;
|
||||
}
|
||||
return this.createResult(request.id, result);
|
||||
} catch (error) {
|
||||
const result = {
|
||||
content: textContent(error.inputOutcome && error.toolEnvelope ? safeStringify(error.toolEnvelope) : error.message),
|
||||
isError: true,
|
||||
_meta: { [CONTEXT_META_KEY]: this.getProjectContext() },
|
||||
};
|
||||
const structured = structuredContent(error.toolEnvelope);
|
||||
if (structured) {
|
||||
result.structuredContent = structured;
|
||||
}
|
||||
return this.createResult(request.id, result);
|
||||
}
|
||||
}
|
||||
|
||||
if (method === 'resources/list') {
|
||||
return this.createResult(request.id, { resources: this.resourceProvider.listResources() });
|
||||
}
|
||||
|
||||
if (method === 'resources/read') {
|
||||
const params = request.params || {};
|
||||
if (typeof params.uri !== 'string' || !params.uri) {
|
||||
return this.createError(request.id, -32602, "Invalid params: 'uri' is required");
|
||||
}
|
||||
return this.createResult(request.id, await this.resourceProvider.readResource(params.uri));
|
||||
}
|
||||
|
||||
if (method === 'resources/templates/list') {
|
||||
return this.createResult(request.id, { resourceTemplates: this.resourceProvider.listResourceTemplates() });
|
||||
}
|
||||
|
||||
if (method === 'prompts/list') {
|
||||
return this.createResult(request.id, { prompts: this.promptProvider.listPrompts() });
|
||||
}
|
||||
|
||||
if (method === 'prompts/get') {
|
||||
const params = request.params || {};
|
||||
if (typeof params.name !== 'string' || !params.name) {
|
||||
return this.createError(request.id, -32602, "Invalid params: 'name' is required");
|
||||
}
|
||||
try {
|
||||
return this.createResult(request.id, this.promptProvider.getPrompt(
|
||||
params.name, params.arguments === undefined ? {} : params.arguments
|
||||
));
|
||||
} catch (error) {
|
||||
return this.createError(request.id, error.code === -32602 ? -32602 : -32603, error.message);
|
||||
}
|
||||
}
|
||||
|
||||
return this.createError(request.id, -32601, `Method not found: ${method}`);
|
||||
}
|
||||
|
||||
negotiateProtocolVersion(clientVersion) {
|
||||
if (SUPPORTED_PROTOCOL_VERSIONS.includes(clientVersion)) {
|
||||
return clientVersion;
|
||||
}
|
||||
return MCP_PROTOCOL_VERSION;
|
||||
}
|
||||
|
||||
createResult(id, result) {
|
||||
return {
|
||||
jsonrpc: '2.0',
|
||||
id,
|
||||
result,
|
||||
};
|
||||
}
|
||||
|
||||
createError(id, code, message) {
|
||||
return {
|
||||
jsonrpc: '2.0',
|
||||
id,
|
||||
error: {
|
||||
code,
|
||||
message,
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
McpServer,
|
||||
MCP_PROTOCOL_VERSION,
|
||||
SUPPORTED_PROTOCOL_VERSIONS,
|
||||
};
|
||||
@@ -0,0 +1,50 @@
|
||||
'use strict';
|
||||
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
const SKILL_PLATFORMS = Object.freeze([
|
||||
{ id: 'codex', name: 'Codex', directory: '.agents/skills', legacyDirectory: '.codex/skills' },
|
||||
{ id: 'claude_code', name: 'Claude Code', directory: '.claude/skills' },
|
||||
{ id: 'cursor', name: 'Cursor', directory: '.cursor/skills' },
|
||||
{ id: 'vscode', name: 'VS Code / Copilot', directory: '.github/skills' },
|
||||
{ id: 'trae', name: 'Trae', directory: '.trae/skills' },
|
||||
{ id: 'antigravity', name: 'Antigravity', directory: '.agents/skills', legacyDirectory: '.agent/skills' },
|
||||
{ id: 'pi', name: 'Pi', directory: '.agents/skills' },
|
||||
{ id: 'kiro', name: 'Kiro', directory: '.kiro/skills' },
|
||||
{ id: 'qoder', name: 'Qoder', directory: '.qoder/skills' },
|
||||
{ id: 'kimi', name: 'Kimi Code', directory: '.kimi-code/skills', gitRoot: true },
|
||||
{ id: 'opencode', name: 'OpenCode', directory: '.opencode/skills' },
|
||||
{ id: 'codebuddy', name: 'CodeBuddy', directory: '.codebuddy/skills' },
|
||||
{ id: 'deepseek_harness', name: 'DeepSeek Harness (DSH)', directory: '.dsh/skills', gitRoot: true },
|
||||
]);
|
||||
|
||||
function findGitRootOrSelf(projectPath) {
|
||||
const original = path.resolve(projectPath);
|
||||
for (let current = original; ; current = path.dirname(current)) {
|
||||
if (fs.existsSync(path.join(current, '.git'))) return current;
|
||||
if (path.dirname(current) === current) return original;
|
||||
}
|
||||
}
|
||||
|
||||
function getSkillPlatform(options = {}) {
|
||||
const id = options.clientId || 'codex';
|
||||
return SKILL_PLATFORMS.find((platform) => platform.id === id) || null;
|
||||
}
|
||||
|
||||
function requireSkillPlatform(options = {}) {
|
||||
const platform = getSkillPlatform(options);
|
||||
if (!platform) throw new Error(`Project Skills installation is not supported for client: ${options.clientId}`);
|
||||
return platform;
|
||||
}
|
||||
|
||||
function getSkillsDirectory(options = {}) {
|
||||
const platform = requireSkillPlatform(options);
|
||||
return options.legacy && platform.legacyDirectory ? platform.legacyDirectory : platform.directory;
|
||||
}
|
||||
|
||||
function getSkillProjectPath(projectPath, options = {}) {
|
||||
return requireSkillPlatform(options).gitRoot ? findGitRootOrSelf(projectPath) : path.resolve(projectPath);
|
||||
}
|
||||
|
||||
module.exports = { SKILL_PLATFORMS, findGitRootOrSelf, getSkillPlatform, getSkillsDirectory, getSkillProjectPath };
|
||||
+155
@@ -0,0 +1,155 @@
|
||||
'use strict';
|
||||
|
||||
const PROFILE_FIELDS = [
|
||||
'toolProfile',
|
||||
'enabledToolCategories',
|
||||
'disabledToolCategories',
|
||||
'enabledTools',
|
||||
'disabledTools',
|
||||
];
|
||||
|
||||
function normalizeProfileName(value) {
|
||||
const normalized = String(value || '').trim();
|
||||
if (!normalized) {
|
||||
throw new Error('profile name is required.');
|
||||
}
|
||||
return normalized.slice(0, 80);
|
||||
}
|
||||
|
||||
function normalizeStringList(value) {
|
||||
if (Array.isArray(value)) {
|
||||
return value.map((item) => String(item || '').trim()).filter(Boolean);
|
||||
}
|
||||
if (typeof value === 'string') {
|
||||
return value.split(/[\n,]/).map((item) => item.trim()).filter(Boolean);
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
function normalizeProfileMode(value) {
|
||||
const normalized = String(value || 'core').trim().toLowerCase();
|
||||
return normalized === 'full' || normalized === 'custom' ? normalized : 'core';
|
||||
}
|
||||
|
||||
function normalizeToolProfile(value) {
|
||||
const profile = value || {};
|
||||
return {
|
||||
name: normalizeProfileName(profile.name),
|
||||
toolProfile: normalizeProfileMode(profile.toolProfile),
|
||||
enabledToolCategories: normalizeStringList(profile.enabledToolCategories).map((item) => item.toLowerCase()),
|
||||
disabledToolCategories: normalizeStringList(profile.disabledToolCategories).map((item) => item.toLowerCase()),
|
||||
enabledTools: normalizeStringList(profile.enabledTools),
|
||||
disabledTools: normalizeStringList(profile.disabledTools),
|
||||
updatedAt: profile.updatedAt ? String(profile.updatedAt) : new Date().toISOString(),
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeSavedToolProfiles(value) {
|
||||
const profiles = [];
|
||||
const seen = new Set();
|
||||
for (const item of Array.isArray(value) ? value : []) {
|
||||
try {
|
||||
const profile = normalizeToolProfile(item);
|
||||
const key = profile.name.toLowerCase();
|
||||
if (seen.has(key)) {
|
||||
const index = profiles.findIndex((existing) => existing.name.toLowerCase() === key);
|
||||
profiles[index] = profile;
|
||||
} else {
|
||||
seen.add(key);
|
||||
profiles.push(profile);
|
||||
}
|
||||
} catch (error) {
|
||||
// Ignore malformed saved profile entries rather than breaking extension startup.
|
||||
}
|
||||
}
|
||||
return profiles.sort((left, right) => left.name.localeCompare(right.name));
|
||||
}
|
||||
|
||||
function createToolProfileSnapshot(config = {}, name) {
|
||||
return normalizeToolProfile({
|
||||
name,
|
||||
toolProfile: config.toolProfile,
|
||||
enabledToolCategories: config.enabledToolCategories,
|
||||
disabledToolCategories: config.disabledToolCategories,
|
||||
enabledTools: config.enabledTools,
|
||||
disabledTools: config.disabledTools,
|
||||
});
|
||||
}
|
||||
|
||||
function upsertToolProfile(savedProfiles, profile) {
|
||||
const normalized = normalizeToolProfile(profile);
|
||||
const profiles = normalizeSavedToolProfiles(savedProfiles);
|
||||
const key = normalized.name.toLowerCase();
|
||||
const index = profiles.findIndex((item) => item.name.toLowerCase() === key);
|
||||
if (index >= 0) {
|
||||
profiles[index] = normalized;
|
||||
} else {
|
||||
profiles.push(normalized);
|
||||
}
|
||||
return normalizeSavedToolProfiles(profiles);
|
||||
}
|
||||
|
||||
function deleteToolProfile(savedProfiles, name) {
|
||||
const key = normalizeProfileName(name).toLowerCase();
|
||||
return normalizeSavedToolProfiles(savedProfiles)
|
||||
.filter((profile) => profile.name.toLowerCase() !== key);
|
||||
}
|
||||
|
||||
function findToolProfile(savedProfiles, name) {
|
||||
const key = normalizeProfileName(name).toLowerCase();
|
||||
return normalizeSavedToolProfiles(savedProfiles)
|
||||
.find((profile) => profile.name.toLowerCase() === key) || null;
|
||||
}
|
||||
|
||||
function applyToolProfile(config = {}, profile) {
|
||||
const normalized = normalizeToolProfile(profile);
|
||||
const next = { ...config };
|
||||
for (const field of PROFILE_FIELDS) {
|
||||
next[field] = Array.isArray(normalized[field])
|
||||
? normalized[field].slice()
|
||||
: normalized[field];
|
||||
}
|
||||
next.activeToolProfileName = normalized.name;
|
||||
return next;
|
||||
}
|
||||
|
||||
function exportToolProfiles(savedProfiles) {
|
||||
return {
|
||||
version: 1,
|
||||
profiles: normalizeSavedToolProfiles(savedProfiles),
|
||||
};
|
||||
}
|
||||
|
||||
function parseProfileImportPayload(payload) {
|
||||
if (typeof payload === 'string') {
|
||||
return JSON.parse(payload);
|
||||
}
|
||||
return payload || {};
|
||||
}
|
||||
|
||||
function importToolProfiles(savedProfiles, payload, options = {}) {
|
||||
const parsed = parseProfileImportPayload(payload);
|
||||
const incoming = Array.isArray(parsed)
|
||||
? parsed
|
||||
: Array.isArray(parsed.profiles)
|
||||
? parsed.profiles
|
||||
: [];
|
||||
if (!incoming.length) {
|
||||
throw new Error('No tool profiles found in import payload.');
|
||||
}
|
||||
|
||||
const base = options.replace ? [] : normalizeSavedToolProfiles(savedProfiles);
|
||||
return incoming.reduce((profiles, profile) => upsertToolProfile(profiles, profile), base);
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
applyToolProfile,
|
||||
createToolProfileSnapshot,
|
||||
deleteToolProfile,
|
||||
exportToolProfiles,
|
||||
findToolProfile,
|
||||
importToolProfiles,
|
||||
normalizeSavedToolProfiles,
|
||||
normalizeToolProfile,
|
||||
upsertToolProfile,
|
||||
};
|
||||
+2136
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,236 @@
|
||||
'use strict';
|
||||
|
||||
const { checkAssetReady } = require('../asset-readiness');
|
||||
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const { listAssets, queryAssetInfo } = require('../assets');
|
||||
const { resolveProjectPath } = require('../path-safety');
|
||||
|
||||
const UUID_KEY_PATTERN = /uuid|assetUuid|prefabUuid|sceneUuid|__uuid__/i;
|
||||
const UUID_LITERAL_PATTERN = /[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}|[A-Za-z0-9+/=-]{20,32}/g;
|
||||
|
||||
function assetUrlToPath(projectPath, url) {
|
||||
if (!url || !String(url).startsWith('db://assets/')) {
|
||||
return '';
|
||||
}
|
||||
return path.join(projectPath, String(url).slice('db://'.length));
|
||||
}
|
||||
|
||||
function assetFilePath(projectPath, info) {
|
||||
const candidates = [
|
||||
info && info.file,
|
||||
info && info.path,
|
||||
info && info.source,
|
||||
info && info.url ? assetUrlToPath(projectPath, info.url) : '',
|
||||
].filter(Boolean);
|
||||
|
||||
for (const candidate of candidates) {
|
||||
const fullPath = resolveProjectPath(projectPath, candidate);
|
||||
if (fs.existsSync(fullPath) && fs.statSync(fullPath).isFile()) {
|
||||
return fullPath;
|
||||
}
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
function collectStructuredUuidReferences(value, refs = [], pointer = '') {
|
||||
if (value == null) {
|
||||
return refs;
|
||||
}
|
||||
if (Array.isArray(value)) {
|
||||
value.forEach((item, index) => collectStructuredUuidReferences(item, refs, `${pointer}/${index}`));
|
||||
return refs;
|
||||
}
|
||||
if (typeof value !== 'object') {
|
||||
return refs;
|
||||
}
|
||||
|
||||
for (const [key, child] of Object.entries(value)) {
|
||||
const childPointer = `${pointer}/${key}`;
|
||||
if (typeof child === 'string' && UUID_KEY_PATTERN.test(key)) {
|
||||
refs.push({ uuid: child, path: childPointer, key, source: 'structured' });
|
||||
continue;
|
||||
}
|
||||
collectStructuredUuidReferences(child, refs, childPointer);
|
||||
}
|
||||
return refs;
|
||||
}
|
||||
|
||||
function collectTextUuidReferences(text) {
|
||||
const refs = [];
|
||||
const seen = new Set();
|
||||
let match;
|
||||
while ((match = UUID_LITERAL_PATTERN.exec(String(text || '')))) {
|
||||
const uuid = match[0];
|
||||
if (seen.has(uuid)) {
|
||||
continue;
|
||||
}
|
||||
seen.add(uuid);
|
||||
refs.push({ uuid, path: `@${match.index}`, key: '', source: 'text' });
|
||||
}
|
||||
return refs;
|
||||
}
|
||||
|
||||
function dedupeReferences(refs) {
|
||||
const seen = new Set();
|
||||
const result = [];
|
||||
for (const ref of refs) {
|
||||
const key = `${ref.uuid}:${ref.path}`;
|
||||
if (seen.has(key)) {
|
||||
continue;
|
||||
}
|
||||
seen.add(key);
|
||||
result.push(ref);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
function collectUuidReferences(content) {
|
||||
const refs = [];
|
||||
try {
|
||||
refs.push(...collectStructuredUuidReferences(JSON.parse(content)));
|
||||
} catch (error) {
|
||||
// Non-JSON assets still get a literal reference scan below.
|
||||
}
|
||||
refs.push(...collectTextUuidReferences(content));
|
||||
return dedupeReferences(refs);
|
||||
}
|
||||
|
||||
async function inspectAssetDependencies(projectPath, target, options = {}) {
|
||||
const info = await queryAssetInfo(target);
|
||||
const filePath = assetFilePath(projectPath, info);
|
||||
if (!filePath) {
|
||||
throw new Error(`Asset file was not found: ${target}`);
|
||||
}
|
||||
|
||||
const content = fs.readFileSync(filePath, 'utf8');
|
||||
const limit = Number.isFinite(options.limit) ? Math.max(1, Math.min(500, options.limit)) : 200;
|
||||
const references = collectUuidReferences(content).slice(0, limit);
|
||||
const dependencies = [];
|
||||
const missing = [];
|
||||
|
||||
for (const ref of references) {
|
||||
try {
|
||||
const asset = await queryAssetInfo(ref.uuid);
|
||||
dependencies.push({
|
||||
...ref,
|
||||
exists: true,
|
||||
asset: {
|
||||
uuid: asset.uuid,
|
||||
url: asset.url,
|
||||
type: asset.type,
|
||||
importer: asset.importer,
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
missing.push({ ...ref, exists: false, error: error.message });
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
ok: missing.length === 0,
|
||||
target,
|
||||
asset: {
|
||||
uuid: info.uuid,
|
||||
url: info.url,
|
||||
type: info.type,
|
||||
},
|
||||
filePath: path.relative(projectPath, filePath).replace(/\\/g, '/'),
|
||||
referenceCount: references.length,
|
||||
dependencyCount: dependencies.length,
|
||||
missingCount: missing.length,
|
||||
dependencies,
|
||||
missing,
|
||||
};
|
||||
}
|
||||
|
||||
async function validateAssetDependencies(projectPath, options = {}) {
|
||||
const targets = options.target
|
||||
? [options.target]
|
||||
: (await listAssets({ pattern: options.pattern || 'db://assets/**', ccType: options.ccType }))
|
||||
.slice(0, Number.isFinite(options.limit) ? Math.max(1, Math.min(200, options.limit)) : 50)
|
||||
.map((asset) => asset.uuid || asset.url)
|
||||
.filter(Boolean);
|
||||
|
||||
const assets = [];
|
||||
for (const target of targets) {
|
||||
try {
|
||||
assets.push(await inspectAssetDependencies(projectPath, target, options));
|
||||
} catch (error) {
|
||||
assets.push({
|
||||
ok: false,
|
||||
target,
|
||||
error: error.message,
|
||||
missingCount: 1,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const missingCount = assets.reduce((sum, asset) => sum + (Number(asset.missingCount) || 0), 0);
|
||||
return {
|
||||
ok: missingCount === 0,
|
||||
assetCount: assets.length,
|
||||
missingCount,
|
||||
assets,
|
||||
};
|
||||
}
|
||||
|
||||
function createAssetsAdvancedTools({ createSchema, getRuntimeContext }) {
|
||||
return [
|
||||
{
|
||||
name: 'check_asset_ready',
|
||||
profile: 'full',
|
||||
category: 'assets',
|
||||
description: '[specialist] Check bounded AssetDB readiness and optionally a stable imported UUID/URL identity. Does not prove importer queue, script compilation, source bytes, or runtime loading completion.',
|
||||
annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true },
|
||||
inputSchema: createSchema({
|
||||
target: { type: 'string', description: 'Optional exact asset UUID, db:// URL, or assets/... path. No extension guessing.' },
|
||||
waitMs: { type: 'integer', minimum: 0, maximum: 10000, description: 'Total polling budget; defaults to 1500 ms. Zero returns one unconfirmed observation.' },
|
||||
pollIntervalMs: { type: 'integer', minimum: 20, maximum: 2000, description: 'Polling interval; defaults to 100 ms.' },
|
||||
}, []),
|
||||
handler: async (args) => await checkAssetReady(args),
|
||||
},
|
||||
{
|
||||
name: 'inspect_asset_dependencies',
|
||||
profile: 'core',
|
||||
description: '[specialist] Inspect UUID-style dependencies referenced by a serialized Cocos asset.',
|
||||
inputSchema: createSchema(
|
||||
{
|
||||
target: { type: 'string', description: 'Asset uuid, db url, or project path.' },
|
||||
limit: { type: 'number', description: 'Maximum dependency references to inspect.' },
|
||||
},
|
||||
['target']
|
||||
),
|
||||
handler: async (args) => {
|
||||
const { projectPath } = getRuntimeContext();
|
||||
return await inspectAssetDependencies(projectPath, args.target, args);
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'validate_asset_dependencies',
|
||||
profile: 'core',
|
||||
description: '[specialist] Validate UUID-style dependencies for one asset or a project asset query.',
|
||||
inputSchema: createSchema(
|
||||
{
|
||||
target: { type: 'string', description: 'Optional asset uuid, db url, or project path.' },
|
||||
pattern: { type: 'string', description: 'Asset-db pattern used when target is omitted.' },
|
||||
ccType: { type: 'string', description: 'Optional Cocos asset type filter.' },
|
||||
limit: { type: 'number', description: 'Maximum assets to scan when target is omitted.' },
|
||||
},
|
||||
[]
|
||||
),
|
||||
handler: async (args) => {
|
||||
const { projectPath } = getRuntimeContext();
|
||||
return await validateAssetDependencies(projectPath, args);
|
||||
},
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
collectUuidReferences,
|
||||
createAssetsAdvancedTools,
|
||||
inspectAssetDependencies,
|
||||
validateAssetDependencies,
|
||||
};
|
||||
@@ -0,0 +1,547 @@
|
||||
'use strict';
|
||||
|
||||
const previewRuntime = require('../preview-runtime');
|
||||
|
||||
const PREVIEW_PROFILE_PACKAGE = 'preview';
|
||||
const PREVIEW_PROFILE_KEY = 'preview.current.platform';
|
||||
const PREVIEW_PROFILE_SCOPE = 'local';
|
||||
const PREVIEW_MODES = Object.freeze(['browser', 'gameView', 'simulator']);
|
||||
const PREVIEW_MODE_DETAILS = Object.freeze({
|
||||
browser: Object.freeze({
|
||||
mode: 'browser',
|
||||
label: 'Browser Preview',
|
||||
description: 'Run the scene in the system browser and expose the preview URL.',
|
||||
hasUrl: true,
|
||||
}),
|
||||
gameView: Object.freeze({
|
||||
mode: 'gameView',
|
||||
label: 'Editor Preview',
|
||||
description: 'Run the scene inside the Cocos Creator Game View.',
|
||||
hasUrl: false,
|
||||
}),
|
||||
simulator: Object.freeze({
|
||||
mode: 'simulator',
|
||||
label: 'Simulator Preview',
|
||||
description: 'Run the scene in the Cocos native simulator.',
|
||||
hasUrl: false,
|
||||
}),
|
||||
});
|
||||
|
||||
const PREVIEW_MODE_ALIASES = Object.freeze({
|
||||
browser: 'browser',
|
||||
web: 'browser',
|
||||
'browser-preview': 'browser',
|
||||
gameview: 'gameView',
|
||||
'game-view': 'gameView',
|
||||
editor: 'gameView',
|
||||
'editor-preview': 'gameView',
|
||||
simulator: 'simulator',
|
||||
native: 'simulator',
|
||||
'simulator-preview': 'simulator',
|
||||
});
|
||||
|
||||
function hasEditorMessage() {
|
||||
return Boolean(global.Editor && Editor.Message);
|
||||
}
|
||||
|
||||
function ensureEditorMessage() {
|
||||
if (!hasEditorMessage()) {
|
||||
throw new Error('Editor.Message is unavailable in this Cocos extension host.');
|
||||
}
|
||||
}
|
||||
|
||||
async function requestEditorMessage(channel, method, ...args) {
|
||||
ensureEditorMessage();
|
||||
if (typeof Editor.Message.request !== 'function') {
|
||||
throw new Error('Editor.Message.request is unavailable in this Cocos extension host.');
|
||||
}
|
||||
return await Editor.Message.request(channel, method, ...args);
|
||||
}
|
||||
|
||||
async function tryEditorRequests(candidates) {
|
||||
const attempts = [];
|
||||
for (const candidate of candidates) {
|
||||
const channel = candidate.channel;
|
||||
const method = candidate.method;
|
||||
const args = Array.isArray(candidate.args) ? candidate.args : [];
|
||||
try {
|
||||
const result = await requestEditorMessage(channel, method, ...args);
|
||||
return {
|
||||
ok: true,
|
||||
channel,
|
||||
method,
|
||||
result,
|
||||
attempts,
|
||||
};
|
||||
} catch (error) {
|
||||
attempts.push({ channel, method, error: error.message });
|
||||
}
|
||||
}
|
||||
|
||||
const message = attempts.length
|
||||
? attempts.map((attempt) => `${attempt.channel}.${attempt.method}: ${attempt.error}`).join('; ')
|
||||
: 'no editor message candidates were provided';
|
||||
const error = new Error(`No compatible Cocos editor message succeeded: ${message}`);
|
||||
error.attempts = attempts;
|
||||
throw error;
|
||||
}
|
||||
|
||||
async function tryEditorRequestsStatus(candidates) {
|
||||
try {
|
||||
return await tryEditorRequests(candidates);
|
||||
} catch (error) {
|
||||
return {
|
||||
ok: false,
|
||||
available: false,
|
||||
attempts: error.attempts || [],
|
||||
error: error.message,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
function normalizePreviewMode(value, options = {}) {
|
||||
const raw = String(value == null ? '' : value).trim();
|
||||
if (!raw && options.allowEmpty === true) {
|
||||
return '';
|
||||
}
|
||||
|
||||
const mode = PREVIEW_MODE_ALIASES[raw.toLowerCase()];
|
||||
if (!mode) {
|
||||
throw new Error(`Unsupported preview mode '${raw}'. Expected one of: ${PREVIEW_MODES.join(', ')}.`);
|
||||
}
|
||||
return mode;
|
||||
}
|
||||
|
||||
function previewModeCatalog() {
|
||||
return PREVIEW_MODES.map((mode) => ({ ...PREVIEW_MODE_DETAILS[mode] }));
|
||||
}
|
||||
|
||||
function ensurePreviewProfile() {
|
||||
if (
|
||||
!global.Editor ||
|
||||
!Editor.Profile ||
|
||||
typeof Editor.Profile.getConfig !== 'function' ||
|
||||
typeof Editor.Profile.setConfig !== 'function'
|
||||
) {
|
||||
throw new Error('Editor.Profile.getConfig/setConfig is unavailable in this Cocos extension host.');
|
||||
}
|
||||
}
|
||||
|
||||
async function queryPreviewUrl() {
|
||||
const result = await requestEditorMessage('preview', 'query-preview-url');
|
||||
return typeof result === 'string' ? result : '';
|
||||
}
|
||||
|
||||
function normalizePreviewHostname(value) {
|
||||
return String(value || '').trim().toLowerCase().replace(/^\[|\]$/g, '');
|
||||
}
|
||||
|
||||
function isLoopbackPreviewHostname(value) {
|
||||
const hostname = normalizePreviewHostname(value);
|
||||
if (hostname === 'localhost' || hostname.endsWith('.localhost') || hostname === '::1') {
|
||||
return true;
|
||||
}
|
||||
|
||||
const ipv4 = hostname.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/);
|
||||
return Boolean(ipv4 && ipv4.slice(1).every((part) => Number(part) <= 255) && Number(ipv4[1]) === 127);
|
||||
}
|
||||
|
||||
function resolvePreviewUrls(value) {
|
||||
const reportedUrl = typeof value === 'string' ? value.trim() : '';
|
||||
const empty = {
|
||||
url: '',
|
||||
localUrl: '',
|
||||
networkUrl: '',
|
||||
reportedUrl: '',
|
||||
urlAvailable: false,
|
||||
urlWarning: '',
|
||||
};
|
||||
if (!reportedUrl) {
|
||||
return empty;
|
||||
}
|
||||
|
||||
let parsed;
|
||||
try {
|
||||
parsed = new URL(reportedUrl);
|
||||
} catch (_error) {
|
||||
return {
|
||||
...empty,
|
||||
url: reportedUrl,
|
||||
reportedUrl,
|
||||
urlAvailable: true,
|
||||
urlWarning: 'Cocos Creator returned a preview URL that is not an absolute HTTP(S) URL; the value was left unchanged.',
|
||||
};
|
||||
}
|
||||
|
||||
if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
|
||||
return {
|
||||
...empty,
|
||||
url: reportedUrl,
|
||||
reportedUrl,
|
||||
urlAvailable: true,
|
||||
urlWarning: `Cocos Creator returned an unsupported preview URL protocol '${parsed.protocol}'; the value was left unchanged.`,
|
||||
};
|
||||
}
|
||||
|
||||
const loopback = isLoopbackPreviewHostname(parsed.hostname);
|
||||
const wildcard = ['0.0.0.0', '::'].includes(normalizePreviewHostname(parsed.hostname));
|
||||
let localUrl = reportedUrl;
|
||||
if (!loopback) {
|
||||
const local = new URL(parsed.href);
|
||||
local.hostname = 'localhost';
|
||||
localUrl = local.href;
|
||||
}
|
||||
|
||||
return {
|
||||
url: localUrl,
|
||||
localUrl,
|
||||
networkUrl: loopback || wildcard ? '' : reportedUrl,
|
||||
reportedUrl,
|
||||
urlAvailable: true,
|
||||
urlWarning: '',
|
||||
};
|
||||
}
|
||||
|
||||
async function getPreviewMode(options = {}) {
|
||||
ensurePreviewProfile();
|
||||
const storedValue = await Editor.Profile.getConfig(
|
||||
PREVIEW_PROFILE_PACKAGE,
|
||||
PREVIEW_PROFILE_KEY,
|
||||
PREVIEW_PROFILE_SCOPE
|
||||
);
|
||||
|
||||
let mode = 'browser';
|
||||
let warning = '';
|
||||
try {
|
||||
mode = normalizePreviewMode(storedValue || 'browser');
|
||||
} catch (error) {
|
||||
warning = `${error.message} Falling back to browser.`;
|
||||
}
|
||||
|
||||
let previewUrls = resolvePreviewUrls('');
|
||||
let urlError = '';
|
||||
if (mode === 'browser' && options.includeUrl !== false) {
|
||||
try {
|
||||
previewUrls = resolvePreviewUrls(await queryPreviewUrl());
|
||||
} catch (error) {
|
||||
urlError = error.message;
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
mode,
|
||||
label: PREVIEW_MODE_DETAILS[mode].label,
|
||||
storedValue: storedValue == null ? '' : String(storedValue),
|
||||
supportedModes: previewModeCatalog(),
|
||||
...previewUrls,
|
||||
warning,
|
||||
urlError,
|
||||
};
|
||||
}
|
||||
|
||||
async function setPreviewMode(value) {
|
||||
ensurePreviewProfile();
|
||||
ensureEditorMessage();
|
||||
if (typeof Editor.Message.send !== 'function') {
|
||||
throw new Error('Editor.Message.send is unavailable in this Cocos extension host.');
|
||||
}
|
||||
|
||||
const mode = normalizePreviewMode(value);
|
||||
const previous = await getPreviewMode({ includeUrl: false });
|
||||
const runtime = await previewRuntime.controlPreviewToolbar({ action: 'set-mode', mode });
|
||||
|
||||
const current = await getPreviewMode({ includeUrl: false });
|
||||
if (current.mode !== mode) {
|
||||
throw new Error(`Cocos Creator did not persist preview mode '${mode}'. Current mode is '${current.mode}'.`);
|
||||
}
|
||||
|
||||
return {
|
||||
changed: previous.mode !== mode,
|
||||
previousMode: previous.mode,
|
||||
mode,
|
||||
label: PREVIEW_MODE_DETAILS[mode].label,
|
||||
editorPreviewStop: previous.mode === 'gameView' && mode !== 'gameView' ? !runtime.running : null,
|
||||
editorPreviewStopError: '',
|
||||
runtime,
|
||||
supportedModes: previewModeCatalog(),
|
||||
};
|
||||
}
|
||||
|
||||
async function runProjectPreview(options = {}) {
|
||||
const modeInput = options.mode == null ? options.platform : options.mode;
|
||||
if (options.mode != null && options.platform != null) {
|
||||
const mode = normalizePreviewMode(options.mode);
|
||||
const platform = normalizePreviewMode(options.platform);
|
||||
if (mode !== platform) {
|
||||
throw new Error(`Conflicting preview mode values: mode='${options.mode}', platform='${options.platform}'.`);
|
||||
}
|
||||
}
|
||||
|
||||
let modeChange = null;
|
||||
let mode;
|
||||
if (modeInput == null || String(modeInput).trim() === '') {
|
||||
mode = (await getPreviewMode({ includeUrl: false })).mode;
|
||||
} else {
|
||||
mode = normalizePreviewMode(modeInput);
|
||||
modeChange = await setPreviewMode(mode);
|
||||
}
|
||||
|
||||
const usedDeprecatedPlatform = options.mode == null && options.platform != null;
|
||||
if (mode === 'gameView') {
|
||||
const runtime = await previewRuntime.controlPreviewToolbar({ action: 'start' });
|
||||
return {
|
||||
started: true,
|
||||
mode,
|
||||
label: PREVIEW_MODE_DETAILS[mode].label,
|
||||
method: 'preview.toolbar.play',
|
||||
result: true,
|
||||
runtime,
|
||||
...resolvePreviewUrls(''),
|
||||
urlError: '',
|
||||
modeChange,
|
||||
usedDeprecatedPlatform,
|
||||
};
|
||||
}
|
||||
|
||||
const result = await requestEditorMessage('preview', 'open-terminal', undefined);
|
||||
let previewUrls = resolvePreviewUrls('');
|
||||
let urlError = '';
|
||||
if (mode === 'browser') {
|
||||
try {
|
||||
previewUrls = resolvePreviewUrls(await queryPreviewUrl());
|
||||
} catch (error) {
|
||||
urlError = error.message;
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
started: true,
|
||||
mode,
|
||||
label: PREVIEW_MODE_DETAILS[mode].label,
|
||||
method: 'preview.open-terminal',
|
||||
result,
|
||||
...previewUrls,
|
||||
urlError,
|
||||
modeChange,
|
||||
usedDeprecatedPlatform,
|
||||
};
|
||||
}
|
||||
|
||||
async function openPanel(panelName) {
|
||||
const id = String(panelName || 'builder').trim();
|
||||
if (!id) {
|
||||
throw new Error('panelName is required.');
|
||||
}
|
||||
if (!global.Editor || !Editor.Panel || typeof Editor.Panel.open !== 'function') {
|
||||
throw new Error('Editor.Panel.open is unavailable in this Cocos extension host.');
|
||||
}
|
||||
const result = await Editor.Panel.open(id);
|
||||
return { opened: true, panelName: id, result };
|
||||
}
|
||||
|
||||
function getEditorPreference(scope, key) {
|
||||
if (!global.Editor || !Editor.Profile) {
|
||||
throw new Error('Editor.Profile is unavailable in this Cocos extension host.');
|
||||
}
|
||||
const normalizedScope = String(scope || 'project').toLowerCase();
|
||||
const target = normalizedScope === 'global' ? Editor.Profile : Editor.Profile;
|
||||
const getters = normalizedScope === 'global'
|
||||
? ['getConfig', 'getGlobal']
|
||||
: ['getProject', 'getConfig'];
|
||||
for (const getter of getters) {
|
||||
if (typeof target[getter] === 'function') {
|
||||
return target[getter](key);
|
||||
}
|
||||
}
|
||||
throw new Error('No compatible Editor.Profile getter is available.');
|
||||
}
|
||||
|
||||
function setEditorPreference(scope, key, value) {
|
||||
if (!global.Editor || !Editor.Profile) {
|
||||
throw new Error('Editor.Profile is unavailable in this Cocos extension host.');
|
||||
}
|
||||
const normalizedScope = String(scope || 'project').toLowerCase();
|
||||
const target = Editor.Profile;
|
||||
const setters = normalizedScope === 'global'
|
||||
? ['setConfig', 'setGlobal']
|
||||
: ['setProject', 'setConfig'];
|
||||
for (const setter of setters) {
|
||||
if (typeof target[setter] === 'function') {
|
||||
const result = target[setter](key, value);
|
||||
return { set: true, scope: normalizedScope, key, value, method: setter, result };
|
||||
}
|
||||
}
|
||||
throw new Error('No compatible Editor.Profile setter is available.');
|
||||
}
|
||||
|
||||
function broadcastEditorMessage(options = {}) {
|
||||
ensureEditorMessage();
|
||||
const channel = String(options.channel || '').trim();
|
||||
const message = String(options.message || '').trim();
|
||||
if (!message) {
|
||||
throw new Error('message is required.');
|
||||
}
|
||||
const payload = options.payload === undefined ? {} : options.payload;
|
||||
if (channel && typeof Editor.Message.send === 'function') {
|
||||
const result = Editor.Message.send(channel, message, payload);
|
||||
return { sent: true, mode: 'send', channel, message, payload, result };
|
||||
}
|
||||
if (typeof Editor.Message.broadcast === 'function') {
|
||||
const result = Editor.Message.broadcast(message, payload);
|
||||
return { sent: true, mode: 'broadcast', message, payload, result };
|
||||
}
|
||||
throw new Error('Neither Editor.Message.send nor Editor.Message.broadcast is available.');
|
||||
}
|
||||
|
||||
function createCocosProjectTools({ createSchema }) {
|
||||
return [
|
||||
{
|
||||
name: 'save_current_scene',
|
||||
profile: 'full',
|
||||
description: '[core] Save the currently open Cocos scene using available editor scene messages.',
|
||||
inputSchema: createSchema({}, []),
|
||||
handler: async () => {
|
||||
const result = await tryEditorRequests([
|
||||
{ channel: 'scene', method: 'save-scene' },
|
||||
{ channel: 'scene', method: 'save' },
|
||||
]);
|
||||
return { saved: true, ...result };
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'open_build_panel',
|
||||
profile: 'full',
|
||||
description: '[core] Open the Cocos build panel, defaulting to the builder panel id.',
|
||||
inputSchema: createSchema(
|
||||
{
|
||||
panelName: { type: 'string', description: 'Panel id to open. Defaults to builder.' },
|
||||
},
|
||||
[]
|
||||
),
|
||||
handler: async (args) => openPanel(args.panelName || 'builder'),
|
||||
},
|
||||
{
|
||||
name: 'get_build_status',
|
||||
profile: 'core',
|
||||
description: '[specialist] Query Cocos build/preview status using known builder message variants.',
|
||||
inputSchema: createSchema({}, []),
|
||||
handler: async () => await tryEditorRequestsStatus([
|
||||
{ channel: 'builder', method: 'query-build-status' },
|
||||
{ channel: 'builder', method: 'get-build-status' },
|
||||
{ channel: 'builder', method: 'query-build-tasks' },
|
||||
]),
|
||||
},
|
||||
{
|
||||
name: 'get_preview_mode',
|
||||
profile: 'core',
|
||||
description: '[specialist] Query the active Cocos Creator preview mode. Browser results use a same-host loopback url/localUrl and preserve Creator\'s reported LAN address as networkUrl.',
|
||||
inputSchema: createSchema({}, []),
|
||||
handler: async () => await getPreviewMode(),
|
||||
},
|
||||
{
|
||||
name: 'set_preview_mode',
|
||||
profile: 'full',
|
||||
description: '[core] Switch Cocos Creator 3.8.x preview mode through the native toolbar, synchronizing its state and stopping Game View before switching away.',
|
||||
inputSchema: createSchema(
|
||||
{
|
||||
mode: {
|
||||
type: 'string',
|
||||
enum: PREVIEW_MODES,
|
||||
description: 'Preview mode: browser, gameView (editor preview), or simulator.',
|
||||
},
|
||||
},
|
||||
['mode']
|
||||
),
|
||||
handler: async (args) => await setPreviewMode(args.mode),
|
||||
},
|
||||
{
|
||||
name: 'run_project_preview',
|
||||
profile: 'full',
|
||||
description: '[core] Start Cocos Creator 3.8.x preview in browser, editor Game View, or simulator mode. Game View uses the native toolbar and does not toggle off an already running preview. Browser results use a same-host loopback url/localUrl and preserve Creator\'s reported LAN address as networkUrl.',
|
||||
inputSchema: createSchema(
|
||||
{
|
||||
mode: {
|
||||
type: 'string',
|
||||
enum: PREVIEW_MODES,
|
||||
description: 'Preview mode: browser, gameView (editor preview), or simulator. Defaults to the current mode.',
|
||||
},
|
||||
platform: {
|
||||
type: 'string',
|
||||
enum: PREVIEW_MODES,
|
||||
description: 'Deprecated alias for mode. This selects preview mode, not a build target.',
|
||||
},
|
||||
},
|
||||
[]
|
||||
),
|
||||
handler: async (args) => await runProjectPreview(args),
|
||||
},
|
||||
{
|
||||
name: 'get_editor_preference',
|
||||
profile: 'full',
|
||||
description: '[core] Read a Cocos editor preference through Editor.Profile when available.',
|
||||
inputSchema: createSchema(
|
||||
{
|
||||
scope: { type: 'string', description: 'Preference scope: project or global. Defaults to project.' },
|
||||
key: { type: 'string', description: 'Preference key.' },
|
||||
},
|
||||
['key']
|
||||
),
|
||||
handler: async (args) => ({
|
||||
scope: args.scope || 'project',
|
||||
key: args.key,
|
||||
value: getEditorPreference(args.scope, args.key),
|
||||
}),
|
||||
},
|
||||
{
|
||||
name: 'set_editor_preference',
|
||||
profile: 'full',
|
||||
description: '[core] Write a Cocos editor preference through Editor.Profile when available.',
|
||||
inputSchema: createSchema(
|
||||
{
|
||||
scope: { type: 'string', description: 'Preference scope: project or global. Defaults to project.' },
|
||||
key: { type: 'string', description: 'Preference key.' },
|
||||
valueJson: { type: 'string', description: 'JSON encoded preference value.' },
|
||||
},
|
||||
['key', 'valueJson']
|
||||
),
|
||||
handler: async (args) => {
|
||||
let value;
|
||||
try {
|
||||
value = JSON.parse(args.valueJson);
|
||||
} catch (error) {
|
||||
throw new Error(`valueJson must be valid JSON: ${error.message}`);
|
||||
}
|
||||
return setEditorPreference(args.scope, args.key, value);
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'broadcast_editor_message',
|
||||
profile: 'full',
|
||||
description: '[core] Send or broadcast a Cocos editor message for advanced editor automation.',
|
||||
inputSchema: createSchema(
|
||||
{
|
||||
channel: { type: 'string', description: 'Optional Editor.Message channel for send().' },
|
||||
message: { type: 'string', description: 'Message name to send or broadcast.' },
|
||||
payload: { type: 'object', description: 'Optional JSON payload.' },
|
||||
},
|
||||
['message']
|
||||
),
|
||||
handler: async (args) => broadcastEditorMessage(args),
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
PREVIEW_MODES,
|
||||
broadcastEditorMessage,
|
||||
createCocosProjectTools,
|
||||
getEditorPreference,
|
||||
getPreviewMode,
|
||||
normalizePreviewMode,
|
||||
resolvePreviewUrls,
|
||||
runProjectPreview,
|
||||
setEditorPreference,
|
||||
setPreviewMode,
|
||||
tryEditorRequests,
|
||||
tryEditorRequestsStatus,
|
||||
};
|
||||
+303
@@ -0,0 +1,303 @@
|
||||
'use strict';
|
||||
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const { resolveProjectPath } = require('../path-safety');
|
||||
|
||||
/**
|
||||
* Build a focused, line-numbered snippet around one file line.
|
||||
* @param {string} filePath Absolute file path.
|
||||
* @param {number} lineNumber One-based target line number.
|
||||
* @param {number} contextLines Surrounding lines to include.
|
||||
* @returns {string}
|
||||
*/
|
||||
function buildSnippet(filePath, lineNumber, contextLines = 3) {
|
||||
const lines = fs.readFileSync(filePath, 'utf8').split(/\r?\n/);
|
||||
const start = Math.max(1, Number(lineNumber || 1) - Math.max(0, contextLines));
|
||||
const end = Math.min(lines.length, Number(lineNumber || 1) + Math.max(0, contextLines));
|
||||
const snippet = [];
|
||||
for (let line = start; line <= end; line += 1) {
|
||||
const marker = line === Number(lineNumber || 1) ? '>' : ' ';
|
||||
snippet.push(`${marker} ${String(line).padStart(4, ' ')} | ${lines[line - 1]}`);
|
||||
}
|
||||
return snippet.join('\n');
|
||||
}
|
||||
|
||||
function matchesPattern(fileName, pattern) {
|
||||
const escaped = pattern.replace(/[.+^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '.*');
|
||||
return new RegExp(`^${escaped}$`, 'i').test(fileName);
|
||||
}
|
||||
|
||||
function searchFiles(rootDir, pattern, limit) {
|
||||
const results = [];
|
||||
if (!fs.existsSync(rootDir)) {
|
||||
return results;
|
||||
}
|
||||
|
||||
const stack = [rootDir];
|
||||
while (stack.length && results.length < limit) {
|
||||
const current = stack.pop();
|
||||
const entries = fs.readdirSync(current, { withFileTypes: true });
|
||||
for (const entry of entries) {
|
||||
if (entry.name === '.git' || entry.name === 'node_modules' || entry.name === 'temp' || entry.name === 'library') {
|
||||
continue;
|
||||
}
|
||||
|
||||
const fullPath = path.join(current, entry.name);
|
||||
if (entry.isDirectory()) {
|
||||
stack.push(fullPath);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (matchesPattern(entry.name, pattern)) {
|
||||
results.push(fullPath);
|
||||
if (results.length >= limit) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return results;
|
||||
}
|
||||
|
||||
function replaceAllLiteral(content, search, replacement) {
|
||||
if (!search) {
|
||||
throw new Error('search text is required.');
|
||||
}
|
||||
return content.split(search).join(replacement);
|
||||
}
|
||||
|
||||
/**
|
||||
* Best-effort refresh for Cocos asset database after external file edits.
|
||||
* @param {string} projectPath Active Cocos project root.
|
||||
* @param {string} targetPath Absolute file or directory path.
|
||||
* @returns {Promise<string>}
|
||||
*/
|
||||
async function refreshAssets(projectPath, targetPath) {
|
||||
if (!global.Editor || !Editor.Message || typeof Editor.Message.request !== 'function') {
|
||||
return 'Asset refresh API is unavailable; Cocos Creator should pick up file changes automatically.';
|
||||
}
|
||||
|
||||
const relative = path.relative(path.join(projectPath, 'assets'), targetPath).replace(/\\/g, '/');
|
||||
if (!relative.startsWith('..')) {
|
||||
const dbUrl = relative ? `db://assets/${relative}` : 'db://assets';
|
||||
try {
|
||||
await Editor.Message.request('asset-db', 'refresh-asset', dbUrl);
|
||||
return `Refreshed asset database for ${dbUrl}`;
|
||||
} catch (error) {
|
||||
try {
|
||||
await Editor.Message.request('asset-db', 'refresh-asset', 'db://assets');
|
||||
return `Refreshed asset database after writing ${dbUrl}`;
|
||||
} catch (innerError) {
|
||||
return `File written, but asset refresh failed: ${innerError.message}`;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return 'File written outside assets directory; no asset-db refresh was needed.';
|
||||
}
|
||||
|
||||
/**
|
||||
* File-system tools. Kept separate from the registry so path safety and asset
|
||||
* refresh behavior can be tested and evolved independently.
|
||||
*/
|
||||
function createFileTools({ createSchema, getRuntimeContext }) {
|
||||
return [
|
||||
{
|
||||
name: 'read_file',
|
||||
profile: 'full',
|
||||
description: '[core] Read a file from the Cocos project.',
|
||||
inputSchema: createSchema(
|
||||
{
|
||||
path: { type: 'string', description: 'Project-relative or absolute file path.' },
|
||||
},
|
||||
['path']
|
||||
),
|
||||
handler: async (args) => {
|
||||
const { projectPath } = getRuntimeContext();
|
||||
const fullPath = resolveProjectPath(projectPath, args.path);
|
||||
if (!fs.existsSync(fullPath)) {
|
||||
throw new Error(`File not found: ${args.path}`);
|
||||
}
|
||||
const content = fs.readFileSync(fullPath, 'utf8');
|
||||
return content.length > 12000 ? `${content.slice(0, 12000)}\n... (truncated)` : content;
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'get_file_snippet',
|
||||
profile: 'full',
|
||||
description: '[core] Read a focused snippet around a file line number.',
|
||||
inputSchema: createSchema(
|
||||
{
|
||||
path: { type: 'string', description: 'Project-relative or absolute file path.' },
|
||||
line: { type: 'number', description: 'Target line number, starting at 1.' },
|
||||
contextLines: { type: 'number', description: 'Number of surrounding context lines.' },
|
||||
},
|
||||
['path', 'line']
|
||||
),
|
||||
handler: async (args) => {
|
||||
const { projectPath } = getRuntimeContext();
|
||||
const fullPath = resolveProjectPath(projectPath, args.path);
|
||||
if (!fs.existsSync(fullPath)) {
|
||||
throw new Error(`File not found: ${args.path}`);
|
||||
}
|
||||
return buildSnippet(fullPath, args.line, Number.isFinite(args.contextLines) ? args.contextLines : 3);
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'write_file',
|
||||
profile: 'full',
|
||||
description: '[core] Write or overwrite a file in the Cocos project.',
|
||||
inputSchema: createSchema(
|
||||
{
|
||||
path: { type: 'string', description: 'Project-relative or absolute file path.' },
|
||||
content: { type: 'string', description: 'File content to write.' },
|
||||
},
|
||||
['path', 'content']
|
||||
),
|
||||
handler: async (args) => {
|
||||
const { projectPath } = getRuntimeContext();
|
||||
const fullPath = resolveProjectPath(projectPath, args.path);
|
||||
fs.mkdirSync(path.dirname(fullPath), { recursive: true });
|
||||
fs.writeFileSync(fullPath, args.content, 'utf8');
|
||||
return `Wrote ${args.content.length} chars to ${args.path}\n${await refreshAssets(projectPath, fullPath)}`;
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'replace_in_file',
|
||||
profile: 'full',
|
||||
description: '[core] Replace text in a file, useful for script auto-fix loops.',
|
||||
inputSchema: createSchema(
|
||||
{
|
||||
path: { type: 'string', description: 'Project-relative or absolute file path.' },
|
||||
search: { type: 'string', description: 'Literal text to search for.' },
|
||||
replace: { type: 'string', description: 'Replacement text.' },
|
||||
replaceAll: { type: 'boolean', description: 'Replace every occurrence instead of only the first.' },
|
||||
},
|
||||
['path', 'search', 'replace']
|
||||
),
|
||||
handler: async (args) => {
|
||||
const { projectPath } = getRuntimeContext();
|
||||
const fullPath = resolveProjectPath(projectPath, args.path);
|
||||
if (!fs.existsSync(fullPath)) {
|
||||
throw new Error(`File not found: ${args.path}`);
|
||||
}
|
||||
|
||||
const original = fs.readFileSync(fullPath, 'utf8');
|
||||
if (!original.includes(args.search)) {
|
||||
throw new Error(`Search text was not found in ${args.path}`);
|
||||
}
|
||||
|
||||
const updated = args.replaceAll
|
||||
? replaceAllLiteral(original, args.search, args.replace)
|
||||
: original.replace(args.search, args.replace);
|
||||
|
||||
fs.writeFileSync(fullPath, updated, 'utf8');
|
||||
return `Updated ${args.path} (${args.replaceAll ? 'all matches' : 'first match'})\n${await refreshAssets(projectPath, fullPath)}`;
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'search_files',
|
||||
profile: 'full',
|
||||
description: '[core] Search project files by simple wildcard pattern.',
|
||||
inputSchema: createSchema(
|
||||
{
|
||||
pattern: { type: 'string', description: "Wildcard file pattern such as '*.ts' or 'Player*'." },
|
||||
directory: { type: 'string', description: 'Project-relative search root. Defaults to assets.' },
|
||||
limit: { type: 'number', description: 'Maximum number of results to return.' },
|
||||
},
|
||||
['pattern']
|
||||
),
|
||||
handler: async (args) => {
|
||||
const { projectPath } = getRuntimeContext();
|
||||
const searchRoot = resolveProjectPath(projectPath, args.directory || 'assets');
|
||||
if (!fs.existsSync(searchRoot)) {
|
||||
throw new Error(`Directory not found: ${args.directory || 'assets'}`);
|
||||
}
|
||||
|
||||
const limit = Number.isFinite(args.limit) ? Math.max(1, Math.min(500, args.limit)) : 100;
|
||||
const results = searchFiles(searchRoot, args.pattern, limit).map((fullPath) =>
|
||||
path.relative(projectPath, fullPath).replace(/\\/g, '/')
|
||||
);
|
||||
return {
|
||||
count: results.length,
|
||||
files: results,
|
||||
};
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'list_directory',
|
||||
profile: 'full',
|
||||
description: '[core] List files and directories inside a project directory.',
|
||||
inputSchema: createSchema(
|
||||
{
|
||||
path: { type: 'string', description: 'Project-relative or absolute directory path.' },
|
||||
},
|
||||
['path']
|
||||
),
|
||||
handler: async (args) => {
|
||||
const { projectPath } = getRuntimeContext();
|
||||
const targetPath = resolveProjectPath(projectPath, args.path);
|
||||
if (!fs.existsSync(targetPath) || !fs.statSync(targetPath).isDirectory()) {
|
||||
throw new Error(`Directory not found: ${args.path}`);
|
||||
}
|
||||
|
||||
const entries = fs
|
||||
.readdirSync(targetPath, { withFileTypes: true })
|
||||
.filter((entry) => !entry.name.startsWith('.'))
|
||||
.map((entry) => ({
|
||||
name: entry.name,
|
||||
type: entry.isDirectory() ? 'directory' : 'file',
|
||||
}));
|
||||
return {
|
||||
path: args.path,
|
||||
entries,
|
||||
};
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'exists',
|
||||
profile: 'full',
|
||||
description: '[core] Check whether a project file or directory exists.',
|
||||
inputSchema: createSchema(
|
||||
{
|
||||
path: { type: 'string', description: 'Project-relative or absolute path.' },
|
||||
},
|
||||
['path']
|
||||
),
|
||||
handler: async (args) => {
|
||||
const { projectPath } = getRuntimeContext();
|
||||
const targetPath = resolveProjectPath(projectPath, args.path);
|
||||
return {
|
||||
path: args.path,
|
||||
exists: fs.existsSync(targetPath),
|
||||
isFile: fs.existsSync(targetPath) ? fs.statSync(targetPath).isFile() : false,
|
||||
isDirectory: fs.existsSync(targetPath) ? fs.statSync(targetPath).isDirectory() : false,
|
||||
};
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'refresh_assets',
|
||||
profile: 'full',
|
||||
description: '[core] Best-effort asset database refresh for a file or the assets root.',
|
||||
inputSchema: createSchema(
|
||||
{
|
||||
path: { type: 'string', description: 'Optional project-relative file path to refresh.' },
|
||||
},
|
||||
[]
|
||||
),
|
||||
handler: async (args) => {
|
||||
const { projectPath } = getRuntimeContext();
|
||||
const targetPath = resolveProjectPath(projectPath, args.path || 'assets');
|
||||
return await refreshAssets(projectPath, targetPath);
|
||||
},
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
buildSnippet,
|
||||
createFileTools,
|
||||
refreshAssets,
|
||||
};
|
||||
@@ -0,0 +1,45 @@
|
||||
'use strict';
|
||||
|
||||
function createSceneEventTools({ createSchema, sceneBridge }) {
|
||||
return [
|
||||
{
|
||||
name: 'list_button_click_events',
|
||||
profile: 'full',
|
||||
description: '[core] List click event bindings on a Cocos Button component.',
|
||||
inputSchema: createSchema(
|
||||
{
|
||||
path: { type: 'string', description: 'Button node hierarchy path.' },
|
||||
uuid: { type: 'string', description: 'Button node uuid.' },
|
||||
name: { type: 'string', description: 'Fallback exact button node name.' },
|
||||
},
|
||||
[]
|
||||
),
|
||||
handler: async (args) => sceneBridge.call('listButtonClickEvents', args),
|
||||
},
|
||||
{
|
||||
name: 'bind_button_click_event',
|
||||
profile: 'full',
|
||||
description: '[core] Bind a Cocos Button click event to a target node component method.',
|
||||
inputSchema: createSchema(
|
||||
{
|
||||
path: { type: 'string', description: 'Button node hierarchy path.' },
|
||||
uuid: { type: 'string', description: 'Button node uuid.' },
|
||||
name: { type: 'string', description: 'Fallback exact button node name.' },
|
||||
targetPath: { type: 'string', description: 'Target node path containing the handler component.' },
|
||||
targetUuid: { type: 'string', description: 'Target node uuid containing the handler component.' },
|
||||
targetName: { type: 'string', description: 'Fallback exact target node name.' },
|
||||
componentName: { type: 'string', description: 'Target component class name.' },
|
||||
handler: { type: 'string', description: 'Method name to invoke on the target component.' },
|
||||
customEventData: { type: 'string', description: 'Optional custom event data string.' },
|
||||
replace: { type: 'boolean', description: 'Replace an identical existing binding.' },
|
||||
},
|
||||
['componentName', 'handler']
|
||||
),
|
||||
handler: async (args) => sceneBridge.call('bindButtonClickEvent', args),
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
createSceneEventTools,
|
||||
};
|
||||
+155
@@ -0,0 +1,155 @@
|
||||
'use strict';
|
||||
|
||||
const https = require('https');
|
||||
|
||||
const LATEST_RELEASE_URL = 'https://api.github.com/repos/FunplayAI/funplay-cocos-mcp/releases/latest';
|
||||
const EXTENSION_ZIP_PATTERN = /^Funplay\.CocosMcp\.v.+\.zip$/i;
|
||||
|
||||
function normalizeVersion(value) {
|
||||
return String(value || '')
|
||||
.trim()
|
||||
.replace(/^v/i, '')
|
||||
.split(/[+-]/)[0];
|
||||
}
|
||||
|
||||
function parseVersion(value) {
|
||||
return normalizeVersion(value)
|
||||
.split('.')
|
||||
.map((part) => Number.parseInt(part, 10))
|
||||
.map((part) => (Number.isFinite(part) ? part : 0));
|
||||
}
|
||||
|
||||
function compareVersions(left, right) {
|
||||
const leftParts = parseVersion(left);
|
||||
const rightParts = parseVersion(right);
|
||||
const length = Math.max(leftParts.length, rightParts.length, 3);
|
||||
for (let index = 0; index < length; index += 1) {
|
||||
const leftPart = leftParts[index] || 0;
|
||||
const rightPart = rightParts[index] || 0;
|
||||
if (leftPart > rightPart) return 1;
|
||||
if (leftPart < rightPart) return -1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
function fetchJson(url, timeoutMs = 5000) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const request = https.get(
|
||||
url,
|
||||
{
|
||||
headers: {
|
||||
Accept: 'application/vnd.github+json',
|
||||
'User-Agent': 'funplay-cocos-mcp-update-checker',
|
||||
},
|
||||
timeout: timeoutMs,
|
||||
},
|
||||
(response) => {
|
||||
const chunks = [];
|
||||
response.on('data', (chunk) => chunks.push(chunk));
|
||||
response.on('end', () => {
|
||||
const body = Buffer.concat(chunks).toString('utf8');
|
||||
if (response.statusCode < 200 || response.statusCode >= 300) {
|
||||
reject(new Error(`GitHub returned HTTP ${response.statusCode}: ${body.slice(0, 160)}`));
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
resolve(JSON.parse(body));
|
||||
} catch (error) {
|
||||
reject(new Error(`Failed to parse GitHub response: ${error.message}`));
|
||||
}
|
||||
});
|
||||
}
|
||||
);
|
||||
|
||||
request.on('timeout', () => {
|
||||
request.destroy(new Error(`Update check timed out after ${timeoutMs}ms.`));
|
||||
});
|
||||
request.on('error', reject);
|
||||
});
|
||||
}
|
||||
|
||||
function mapReleaseAsset(asset) {
|
||||
return {
|
||||
name: String(asset && asset.name || ''),
|
||||
browserDownloadUrl: String(asset && asset.browser_download_url || asset && asset.browserDownloadUrl || ''),
|
||||
size: Number(asset && asset.size || 0),
|
||||
contentType: String(asset && asset.content_type || asset && asset.contentType || ''),
|
||||
};
|
||||
}
|
||||
|
||||
function selectReleaseAssets(version, assets = []) {
|
||||
const mapped = (Array.isArray(assets) ? assets : [])
|
||||
.map(mapReleaseAsset)
|
||||
.filter((asset) => asset.name && asset.browserDownloadUrl);
|
||||
const exactZipName = `Funplay.CocosMcp.v${normalizeVersion(version)}.zip`;
|
||||
const extensionAsset = mapped.find((asset) => asset.name === exactZipName)
|
||||
|| mapped.find((asset) => EXTENSION_ZIP_PATTERN.test(asset.name))
|
||||
|| mapped.find((asset) => /\.zip$/i.test(asset.name));
|
||||
const checksumAsset = mapped.find((asset) => asset.name === 'SHA256SUMS.txt')
|
||||
|| mapped.find((asset) => /sha256sums/i.test(asset.name));
|
||||
const manifestAsset = mapped.find((asset) => asset.name === 'release-manifest.json');
|
||||
|
||||
return {
|
||||
assets: mapped,
|
||||
extensionAsset: extensionAsset || null,
|
||||
checksumAsset: checksumAsset || null,
|
||||
manifestAsset: manifestAsset || null,
|
||||
};
|
||||
}
|
||||
|
||||
async function checkForUpdate(options = {}) {
|
||||
const currentVersion = normalizeVersion(options.currentVersion || '0.0.0');
|
||||
const checkedAt = new Date().toISOString();
|
||||
|
||||
try {
|
||||
const release = await fetchJson(options.url || LATEST_RELEASE_URL, options.timeoutMs || 5000);
|
||||
const latestVersion = normalizeVersion(release.tag_name || release.name || '');
|
||||
const comparison = latestVersion ? compareVersions(latestVersion, currentVersion) : 0;
|
||||
const releaseAssets = selectReleaseAssets(latestVersion, release.assets);
|
||||
return {
|
||||
ok: true,
|
||||
checkedAt,
|
||||
currentVersion,
|
||||
latestVersion,
|
||||
updateAvailable: comparison > 0,
|
||||
releaseUrl: release.html_url || '',
|
||||
publishedAt: release.published_at || '',
|
||||
source: options.url || LATEST_RELEASE_URL,
|
||||
tagName: release.tag_name || '',
|
||||
releaseName: release.name || '',
|
||||
assets: releaseAssets.assets,
|
||||
extensionAsset: releaseAssets.extensionAsset,
|
||||
checksumAsset: releaseAssets.checksumAsset,
|
||||
manifestAsset: releaseAssets.manifestAsset,
|
||||
downloadAvailable: Boolean(releaseAssets.extensionAsset && releaseAssets.checksumAsset),
|
||||
};
|
||||
} catch (error) {
|
||||
return {
|
||||
ok: false,
|
||||
checkedAt,
|
||||
currentVersion,
|
||||
latestVersion: '',
|
||||
updateAvailable: false,
|
||||
releaseUrl: '',
|
||||
publishedAt: '',
|
||||
source: options.url || LATEST_RELEASE_URL,
|
||||
tagName: '',
|
||||
releaseName: '',
|
||||
assets: [],
|
||||
extensionAsset: null,
|
||||
checksumAsset: null,
|
||||
manifestAsset: null,
|
||||
downloadAvailable: false,
|
||||
error: error.message,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
LATEST_RELEASE_URL,
|
||||
checkForUpdate,
|
||||
compareVersions,
|
||||
normalizeVersion,
|
||||
selectReleaseAssets,
|
||||
};
|
||||
+502
@@ -0,0 +1,502 @@
|
||||
'use strict';
|
||||
|
||||
const crypto = require('crypto');
|
||||
const fs = require('fs');
|
||||
const http = require('http');
|
||||
const https = require('https');
|
||||
const os = require('os');
|
||||
const path = require('path');
|
||||
const zlib = require('zlib');
|
||||
const { compareVersions, normalizeVersion, selectReleaseAssets } = require('./update-checker');
|
||||
|
||||
const PACKAGE_NAME = 'funplay-cocos-mcp';
|
||||
const MAX_REDIRECTS = 5;
|
||||
const DEFAULT_TIMEOUT_MS = 30000;
|
||||
const DEFAULT_MAX_DOWNLOAD_BYTES = 64 * 1024 * 1024;
|
||||
const DEFAULT_MAX_UNCOMPRESSED_BYTES = 128 * 1024 * 1024;
|
||||
const DEFAULT_MAX_FILE_BYTES = 32 * 1024 * 1024;
|
||||
const DEFAULT_MAX_ZIP_ENTRIES = 5000;
|
||||
|
||||
function logMessage(log, level, message, details) {
|
||||
if (typeof log === 'function') {
|
||||
log(level, message, details);
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeAsset(asset) {
|
||||
if (!asset) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
name: String(asset.name || ''),
|
||||
browserDownloadUrl: String(asset.browserDownloadUrl || asset.browser_download_url || ''),
|
||||
size: Number(asset.size || 0),
|
||||
contentType: String(asset.contentType || asset.content_type || ''),
|
||||
};
|
||||
}
|
||||
|
||||
function parseChecksum(text, fileName) {
|
||||
const target = path.basename(String(fileName || ''));
|
||||
for (const line of String(text || '').split(/\r?\n/)) {
|
||||
const match = /^([a-fA-F0-9]{64})\s+[* ]?(.+?)\s*$/.exec(line.trim());
|
||||
if (!match) {
|
||||
continue;
|
||||
}
|
||||
const candidate = path.basename(match[2].trim());
|
||||
if (candidate === target) {
|
||||
return match[1].toLowerCase();
|
||||
}
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
function sha256File(filePath) {
|
||||
return crypto.createHash('sha256').update(fs.readFileSync(filePath)).digest('hex');
|
||||
}
|
||||
|
||||
function assertInside(parent, target) {
|
||||
const resolvedParent = path.resolve(parent);
|
||||
const resolvedTarget = path.resolve(target);
|
||||
const prefix = resolvedParent.endsWith(path.sep) ? resolvedParent : `${resolvedParent}${path.sep}`;
|
||||
if (resolvedTarget !== resolvedParent && !resolvedTarget.startsWith(prefix)) {
|
||||
throw new Error(`Unsafe archive path escaped destination: ${target}`);
|
||||
}
|
||||
return resolvedTarget;
|
||||
}
|
||||
|
||||
function normalizeArchivePath(value) {
|
||||
const raw = String(value || '').replace(/\\/g, '/');
|
||||
if (!raw || raw.includes('\0') || raw.startsWith('/') || /^[A-Za-z]:/.test(raw)) {
|
||||
throw new Error(`Unsafe archive path: ${raw}`);
|
||||
}
|
||||
const normalized = path.posix.normalize(raw);
|
||||
if (!normalized || normalized === '.' || normalized === '..' || normalized.startsWith('../')) {
|
||||
throw new Error(`Unsafe archive path: ${raw}`);
|
||||
}
|
||||
return normalized;
|
||||
}
|
||||
|
||||
function findEndOfCentralDirectory(buffer) {
|
||||
const minOffset = Math.max(0, buffer.length - 22 - 0xffff);
|
||||
for (let offset = buffer.length - 22; offset >= minOffset; offset -= 1) {
|
||||
if (buffer.readUInt32LE(offset) === 0x06054b50) {
|
||||
return offset;
|
||||
}
|
||||
}
|
||||
throw new Error('Invalid zip file: end of central directory was not found.');
|
||||
}
|
||||
|
||||
function extractZip(zipPath, destination, options = {}) {
|
||||
const buffer = fs.readFileSync(zipPath);
|
||||
const eocd = findEndOfCentralDirectory(buffer);
|
||||
const entryCount = buffer.readUInt16LE(eocd + 10);
|
||||
const centralDirectoryOffset = buffer.readUInt32LE(eocd + 16);
|
||||
const maxEntries = options.maxEntries || DEFAULT_MAX_ZIP_ENTRIES;
|
||||
const maxFileBytes = options.maxFileBytes || DEFAULT_MAX_FILE_BYTES;
|
||||
const maxUncompressedBytes = options.maxUncompressedBytes || DEFAULT_MAX_UNCOMPRESSED_BYTES;
|
||||
|
||||
if (entryCount > maxEntries) {
|
||||
throw new Error(`Zip has too many entries: ${entryCount}`);
|
||||
}
|
||||
|
||||
fs.mkdirSync(destination, { recursive: true });
|
||||
let offset = centralDirectoryOffset;
|
||||
let totalUncompressed = 0;
|
||||
const extracted = [];
|
||||
|
||||
for (let index = 0; index < entryCount; index += 1) {
|
||||
if (buffer.readUInt32LE(offset) !== 0x02014b50) {
|
||||
throw new Error(`Invalid zip central directory entry at offset ${offset}.`);
|
||||
}
|
||||
|
||||
const method = buffer.readUInt16LE(offset + 10);
|
||||
const compressedSize = buffer.readUInt32LE(offset + 20);
|
||||
const uncompressedSize = buffer.readUInt32LE(offset + 24);
|
||||
const nameLength = buffer.readUInt16LE(offset + 28);
|
||||
const extraLength = buffer.readUInt16LE(offset + 30);
|
||||
const commentLength = buffer.readUInt16LE(offset + 32);
|
||||
const localHeaderOffset = buffer.readUInt32LE(offset + 42);
|
||||
const rawName = buffer.slice(offset + 46, offset + 46 + nameLength).toString('utf8');
|
||||
offset += 46 + nameLength + extraLength + commentLength;
|
||||
|
||||
if (compressedSize === 0xffffffff || uncompressedSize === 0xffffffff || localHeaderOffset === 0xffffffff) {
|
||||
throw new Error('Zip64 archives are not supported by the built-in updater.');
|
||||
}
|
||||
|
||||
const archivePath = normalizeArchivePath(rawName);
|
||||
if (archivePath.endsWith('/')) {
|
||||
fs.mkdirSync(assertInside(destination, path.join(destination, archivePath)), { recursive: true });
|
||||
continue;
|
||||
}
|
||||
|
||||
if (uncompressedSize > maxFileBytes) {
|
||||
throw new Error(`Zip entry is too large: ${archivePath}`);
|
||||
}
|
||||
totalUncompressed += uncompressedSize;
|
||||
if (totalUncompressed > maxUncompressedBytes) {
|
||||
throw new Error('Zip archive expands beyond the safe size limit.');
|
||||
}
|
||||
|
||||
if (buffer.readUInt32LE(localHeaderOffset) !== 0x04034b50) {
|
||||
throw new Error(`Invalid zip local header for ${archivePath}.`);
|
||||
}
|
||||
|
||||
const localNameLength = buffer.readUInt16LE(localHeaderOffset + 26);
|
||||
const localExtraLength = buffer.readUInt16LE(localHeaderOffset + 28);
|
||||
const dataOffset = localHeaderOffset + 30 + localNameLength + localExtraLength;
|
||||
const compressed = buffer.slice(dataOffset, dataOffset + compressedSize);
|
||||
let content;
|
||||
|
||||
if (method === 0) {
|
||||
content = compressed;
|
||||
} else if (method === 8) {
|
||||
content = zlib.inflateRawSync(compressed);
|
||||
} else {
|
||||
throw new Error(`Unsupported zip compression method ${method} for ${archivePath}.`);
|
||||
}
|
||||
|
||||
if (content.length !== uncompressedSize) {
|
||||
throw new Error(`Zip entry size mismatch for ${archivePath}.`);
|
||||
}
|
||||
|
||||
const targetPath = assertInside(destination, path.join(destination, archivePath));
|
||||
fs.mkdirSync(path.dirname(targetPath), { recursive: true });
|
||||
fs.writeFileSync(targetPath, content);
|
||||
extracted.push(targetPath);
|
||||
}
|
||||
|
||||
return {
|
||||
entries: entryCount,
|
||||
files: extracted.length,
|
||||
totalUncompressedBytes: totalUncompressed,
|
||||
};
|
||||
}
|
||||
|
||||
function requestUrl(url, options = {}, redirectCount = 0) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const parsed = new URL(url);
|
||||
const client = parsed.protocol === 'http:' ? http : https;
|
||||
const request = client.get(
|
||||
parsed,
|
||||
{
|
||||
headers: {
|
||||
'User-Agent': 'funplay-cocos-mcp-updater',
|
||||
Accept: '*/*',
|
||||
},
|
||||
timeout: options.timeoutMs || DEFAULT_TIMEOUT_MS,
|
||||
},
|
||||
(response) => {
|
||||
const status = response.statusCode || 0;
|
||||
const location = response.headers.location;
|
||||
if ([301, 302, 303, 307, 308].includes(status) && location) {
|
||||
response.resume();
|
||||
if (redirectCount >= MAX_REDIRECTS) {
|
||||
reject(new Error(`Too many redirects while downloading ${url}`));
|
||||
return;
|
||||
}
|
||||
const redirected = new URL(location, parsed).toString();
|
||||
requestUrl(redirected, options, redirectCount + 1).then(resolve, reject);
|
||||
return;
|
||||
}
|
||||
|
||||
if (status < 200 || status >= 300) {
|
||||
const chunks = [];
|
||||
response.on('data', (chunk) => chunks.push(chunk));
|
||||
response.on('end', () => {
|
||||
const body = Buffer.concat(chunks).toString('utf8').slice(0, 200);
|
||||
reject(new Error(`Download failed with HTTP ${status}: ${body}`));
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
resolve(response);
|
||||
}
|
||||
);
|
||||
|
||||
request.on('timeout', () => {
|
||||
request.destroy(new Error(`Download timed out after ${options.timeoutMs || DEFAULT_TIMEOUT_MS}ms.`));
|
||||
});
|
||||
request.on('error', reject);
|
||||
});
|
||||
}
|
||||
|
||||
async function downloadFile(url, destination, options = {}) {
|
||||
const response = await requestUrl(url, options);
|
||||
const maxBytes = options.maxBytes || DEFAULT_MAX_DOWNLOAD_BYTES;
|
||||
|
||||
await new Promise((resolve, reject) => {
|
||||
const output = fs.createWriteStream(destination);
|
||||
let total = 0;
|
||||
response.on('data', (chunk) => {
|
||||
total += chunk.length;
|
||||
if (total > maxBytes) {
|
||||
response.destroy(new Error(`Download exceeded ${maxBytes} bytes.`));
|
||||
}
|
||||
});
|
||||
response.on('error', reject);
|
||||
output.on('error', reject);
|
||||
output.on('finish', resolve);
|
||||
response.pipe(output);
|
||||
});
|
||||
|
||||
return {
|
||||
path: destination,
|
||||
sizeBytes: fs.statSync(destination).size,
|
||||
};
|
||||
}
|
||||
|
||||
async function downloadText(url, options = {}) {
|
||||
const response = await requestUrl(url, options);
|
||||
const maxBytes = options.maxBytes || 1024 * 1024;
|
||||
|
||||
return await new Promise((resolve, reject) => {
|
||||
const chunks = [];
|
||||
let total = 0;
|
||||
response.on('data', (chunk) => {
|
||||
total += chunk.length;
|
||||
if (total > maxBytes) {
|
||||
response.destroy(new Error(`Download exceeded ${maxBytes} bytes.`));
|
||||
return;
|
||||
}
|
||||
chunks.push(chunk);
|
||||
});
|
||||
response.on('error', reject);
|
||||
response.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')));
|
||||
});
|
||||
}
|
||||
|
||||
function findPackageDirectory(root) {
|
||||
const direct = path.join(root, PACKAGE_NAME);
|
||||
if (isExpectedPackageDirectory(direct)) {
|
||||
return direct;
|
||||
}
|
||||
|
||||
const entries = fs.readdirSync(root, { withFileTypes: true });
|
||||
for (const entry of entries) {
|
||||
if (!entry.isDirectory()) {
|
||||
continue;
|
||||
}
|
||||
const candidate = path.join(root, entry.name);
|
||||
if (isExpectedPackageDirectory(candidate)) {
|
||||
return candidate;
|
||||
}
|
||||
}
|
||||
|
||||
throw new Error(`Release archive does not contain a ${PACKAGE_NAME} package directory.`);
|
||||
}
|
||||
|
||||
function isExpectedPackageDirectory(directory) {
|
||||
const packagePath = path.join(directory, 'package.json');
|
||||
if (!fs.existsSync(packagePath)) {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
const pkg = JSON.parse(fs.readFileSync(packagePath, 'utf8'));
|
||||
return pkg.name === PACKAGE_NAME;
|
||||
} catch (error) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function validatePackageDirectory(directory, expectedVersion) {
|
||||
const packagePath = path.join(directory, 'package.json');
|
||||
const pkg = JSON.parse(fs.readFileSync(packagePath, 'utf8'));
|
||||
const version = normalizeVersion(pkg.version);
|
||||
if (pkg.name !== PACKAGE_NAME) {
|
||||
throw new Error(`Update package name mismatch: ${pkg.name}`);
|
||||
}
|
||||
if (expectedVersion && version !== normalizeVersion(expectedVersion)) {
|
||||
throw new Error(`Update package version ${version} does not match release ${expectedVersion}.`);
|
||||
}
|
||||
if (!pkg.main || !fs.existsSync(path.join(directory, pkg.main))) {
|
||||
throw new Error('Update package main file is missing.');
|
||||
}
|
||||
return {
|
||||
name: pkg.name,
|
||||
version,
|
||||
packageVersion: pkg.package_version || pkg.packageVersion || 0,
|
||||
};
|
||||
}
|
||||
|
||||
function hasGitMetadata(directory) {
|
||||
return fs.existsSync(path.join(directory, '.git'));
|
||||
}
|
||||
|
||||
function pathEntryExists(targetPath) {
|
||||
try {
|
||||
fs.lstatSync(targetPath);
|
||||
return true;
|
||||
} catch (error) {
|
||||
if (error && error.code === 'ENOENT') {
|
||||
return false;
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
function assertInstallablePackagePath(packagePath, options = {}) {
|
||||
if (!pathEntryExists(packagePath)) {
|
||||
return;
|
||||
}
|
||||
const stat = fs.lstatSync(packagePath);
|
||||
if (stat.isSymbolicLink() && !options.allowSymlinkInstall) {
|
||||
throw new Error('One-click update is disabled for symlink installs. Use git pull, Cocos Store, or replace the extension manually.');
|
||||
}
|
||||
if (hasGitMetadata(packagePath) && !options.allowGitWorktreeInstall) {
|
||||
throw new Error('One-click update is disabled inside a git worktree. Use git pull or install the release package manually.');
|
||||
}
|
||||
}
|
||||
|
||||
function timestampForPath(date = new Date()) {
|
||||
return date.toISOString().replace(/[:.]/g, '-');
|
||||
}
|
||||
|
||||
function copyDirectoryContents(source, destination) {
|
||||
fs.mkdirSync(destination, { recursive: true });
|
||||
for (const entry of fs.readdirSync(source)) {
|
||||
fs.cpSync(path.join(source, entry), path.join(destination, entry), {
|
||||
recursive: true,
|
||||
force: true,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function cleanDirectory(directory) {
|
||||
fs.mkdirSync(directory, { recursive: true });
|
||||
for (const entry of fs.readdirSync(directory)) {
|
||||
fs.rmSync(path.join(directory, entry), { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
function restoreBackup(backupDir, packagePath) {
|
||||
cleanDirectory(packagePath);
|
||||
copyDirectoryContents(backupDir, packagePath);
|
||||
}
|
||||
|
||||
async function installLatestUpdate(options = {}) {
|
||||
const releaseInfo = options.releaseInfo || {};
|
||||
const currentVersion = normalizeVersion(options.currentVersion || releaseInfo.currentVersion || '0.0.0');
|
||||
const latestVersion = normalizeVersion(releaseInfo.latestVersion || releaseInfo.tagName || '');
|
||||
const packagePath = path.resolve(options.packagePath || path.join(__dirname, '..'));
|
||||
const packagePathExisted = pathEntryExists(packagePath);
|
||||
const timeoutMs = options.timeoutMs || DEFAULT_TIMEOUT_MS;
|
||||
const log = options.log;
|
||||
|
||||
if (!latestVersion) {
|
||||
throw new Error('Latest release version is unknown.');
|
||||
}
|
||||
if (!options.force && compareVersions(latestVersion, currentVersion) <= 0) {
|
||||
throw new Error(`Already up to date: ${currentVersion}.`);
|
||||
}
|
||||
|
||||
assertInstallablePackagePath(packagePath, options);
|
||||
|
||||
const selected = selectReleaseAssets(latestVersion, releaseInfo.assets || []);
|
||||
const extensionAsset = normalizeAsset(releaseInfo.extensionAsset) || selected.extensionAsset;
|
||||
const checksumAsset = normalizeAsset(releaseInfo.checksumAsset) || selected.checksumAsset;
|
||||
if (!extensionAsset || !extensionAsset.browserDownloadUrl) {
|
||||
throw new Error('Latest release does not include a downloadable extension zip.');
|
||||
}
|
||||
if (!checksumAsset || !checksumAsset.browserDownloadUrl) {
|
||||
throw new Error('Latest release does not include SHA256SUMS.txt, so one-click update was refused.');
|
||||
}
|
||||
|
||||
const tempRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'funplay-cocos-mcp-update-'));
|
||||
const downloadDir = path.join(tempRoot, 'downloads');
|
||||
const extractDir = path.join(tempRoot, 'extract');
|
||||
fs.mkdirSync(downloadDir, { recursive: true });
|
||||
fs.mkdirSync(extractDir, { recursive: true });
|
||||
const zipPath = path.join(downloadDir, path.basename(extensionAsset.name));
|
||||
const checksumPath = path.join(downloadDir, 'SHA256SUMS.txt');
|
||||
let backupDir = '';
|
||||
|
||||
try {
|
||||
logMessage(log, 'info', `Downloading update package ${extensionAsset.name}...`);
|
||||
await downloadFile(extensionAsset.browserDownloadUrl, zipPath, {
|
||||
timeoutMs,
|
||||
maxBytes: options.maxDownloadBytes || DEFAULT_MAX_DOWNLOAD_BYTES,
|
||||
});
|
||||
await downloadFile(checksumAsset.browserDownloadUrl, checksumPath, {
|
||||
timeoutMs,
|
||||
maxBytes: 1024 * 1024,
|
||||
});
|
||||
|
||||
const expectedSha256 = parseChecksum(fs.readFileSync(checksumPath, 'utf8'), extensionAsset.name);
|
||||
if (!expectedSha256) {
|
||||
throw new Error(`SHA256SUMS.txt does not contain a checksum for ${extensionAsset.name}.`);
|
||||
}
|
||||
const actualSha256 = sha256File(zipPath);
|
||||
if (actualSha256 !== expectedSha256) {
|
||||
throw new Error(`Checksum mismatch for ${extensionAsset.name}.`);
|
||||
}
|
||||
|
||||
logMessage(log, 'info', `Checksum verified for ${extensionAsset.name}.`);
|
||||
const extraction = extractZip(zipPath, extractDir, options);
|
||||
const extractedPackage = findPackageDirectory(extractDir);
|
||||
const packageInfo = validatePackageDirectory(extractedPackage, latestVersion);
|
||||
|
||||
if (pathEntryExists(packagePath) !== packagePathExisted) {
|
||||
throw new Error('The extension install path changed while the release was downloading. Try again.');
|
||||
}
|
||||
assertInstallablePackagePath(packagePath, options);
|
||||
|
||||
if (packagePathExisted) {
|
||||
const backupRoot = path.join(path.dirname(packagePath), '.funplay-cocos-mcp-backups');
|
||||
backupDir = path.join(backupRoot, `${path.basename(packagePath)}-${timestampForPath()}`);
|
||||
fs.mkdirSync(backupRoot, { recursive: true });
|
||||
copyDirectoryContents(packagePath, backupDir);
|
||||
} else {
|
||||
fs.mkdirSync(path.dirname(packagePath), { recursive: true });
|
||||
}
|
||||
|
||||
logMessage(
|
||||
log,
|
||||
'info',
|
||||
packagePathExisted
|
||||
? `Replacing extension package. Backup: ${backupDir}`
|
||||
: `Installing extension package at ${packagePath}`
|
||||
);
|
||||
try {
|
||||
if (packagePathExisted) {
|
||||
cleanDirectory(packagePath);
|
||||
} else {
|
||||
fs.mkdirSync(packagePath, { recursive: true });
|
||||
}
|
||||
copyDirectoryContents(extractedPackage, packagePath);
|
||||
} catch (error) {
|
||||
if (backupDir) {
|
||||
restoreBackup(backupDir, packagePath);
|
||||
} else {
|
||||
fs.rmSync(packagePath, { recursive: true, force: true });
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
|
||||
return {
|
||||
ok: true,
|
||||
installed: true,
|
||||
currentVersion,
|
||||
installedVersion: packageInfo.version,
|
||||
backupDir,
|
||||
packagePath,
|
||||
zipName: extensionAsset.name,
|
||||
zipSha256: actualSha256,
|
||||
checksumVerified: true,
|
||||
extraction,
|
||||
};
|
||||
} finally {
|
||||
if (!options.keepTemp) {
|
||||
fs.rmSync(tempRoot, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
downloadFile,
|
||||
downloadText,
|
||||
extractZip,
|
||||
installLatestUpdate,
|
||||
parseChecksum,
|
||||
sha256File,
|
||||
validatePackageDirectory,
|
||||
};
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
'use strict';
|
||||
|
||||
function safeJsonParse(text, fallback = null) {
|
||||
try {
|
||||
return JSON.parse(text);
|
||||
} catch (error) {
|
||||
return fallback;
|
||||
}
|
||||
}
|
||||
|
||||
function safeStringify(value) {
|
||||
const seen = new WeakSet();
|
||||
return JSON.stringify(
|
||||
value,
|
||||
(key, current) => {
|
||||
if (typeof current === 'object' && current !== null) {
|
||||
if (seen.has(current)) {
|
||||
return '[Circular]';
|
||||
}
|
||||
seen.add(current);
|
||||
}
|
||||
return current;
|
||||
},
|
||||
2
|
||||
);
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
safeJsonParse,
|
||||
safeStringify,
|
||||
};
|
||||
@@ -0,0 +1,204 @@
|
||||
'use strict';
|
||||
|
||||
const crypto = require('crypto');
|
||||
const path = require('path');
|
||||
const electronTools = require('./electron-tools');
|
||||
|
||||
const CAPTURE_TTL_MS = 60000;
|
||||
const MAX_CAPTURES = 32;
|
||||
const captures = new Map();
|
||||
const inputWindows = new WeakSet();
|
||||
|
||||
// Serialized into the target renderer. Read display geometry, not business data.
|
||||
function windowGeometry() {
|
||||
const key = Symbol.for('funplay-cocos-mcp.visual-geometry');
|
||||
const state = window[key] || (window[key] = { ids: new WeakMap(), nextId: 1 });
|
||||
const identity = (node) => {
|
||||
if (!state.ids.has(node)) state.ids.set(node, state.nextId++);
|
||||
return state.ids.get(node);
|
||||
};
|
||||
const canvases = [];
|
||||
const frames = [];
|
||||
let visited = 0;
|
||||
let complete = true;
|
||||
const rectOf = (node) => {
|
||||
const rect = node.getBoundingClientRect();
|
||||
const style = window.getComputedStyle(node);
|
||||
if (style.display === 'none' || style.visibility === 'hidden' || rect.width <= 0 || rect.height <= 0) return null;
|
||||
return { x: rect.left, y: rect.top, width: rect.width, height: rect.height };
|
||||
};
|
||||
const collect = (root) => {
|
||||
for (const node of root.querySelectorAll('*')) {
|
||||
if (++visited > 15000) { complete = false; return; }
|
||||
const tag = node.tagName && node.tagName.toLowerCase();
|
||||
if (tag === 'canvas') {
|
||||
const rect = rectOf(node);
|
||||
if (rect) {
|
||||
if (canvases.length >= 64) { complete = false; return; }
|
||||
canvases.push({ id: identity(node), rect, width: node.width, height: node.height });
|
||||
}
|
||||
} else if (tag === 'iframe' || tag === 'webview') {
|
||||
const rect = rectOf(node);
|
||||
if (rect) {
|
||||
if (frames.length >= 64) { complete = false; return; }
|
||||
let epoch = null;
|
||||
try { epoch = node.contentWindow.performance.timeOrigin; } catch (error) { /* Cross-origin frames are identified by element/src only. */ }
|
||||
frames.push({ id: identity(node), rect, src: node.getAttribute('src') || '', epoch });
|
||||
}
|
||||
}
|
||||
if (node.shadowRoot) collect(node.shadowRoot);
|
||||
if (!complete) return;
|
||||
}
|
||||
};
|
||||
collect(document);
|
||||
return {
|
||||
width: window.innerWidth, height: window.innerHeight,
|
||||
devicePixelRatio: window.devicePixelRatio, documentEpoch: performance.timeOrigin,
|
||||
scrollX: window.scrollX, scrollY: window.scrollY,
|
||||
url: window.location.href, canvases, frames, complete,
|
||||
};
|
||||
}
|
||||
|
||||
function boundedRead(read) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const timer = setTimeout(() => reject(new Error('Visual geometry query timed out. Recapture after the editor becomes responsive.')), 1500);
|
||||
Promise.resolve().then(read).then(
|
||||
(value) => { clearTimeout(timer); resolve(value); },
|
||||
(error) => { clearTimeout(timer); reject(error); }
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
function usableWindow(window) {
|
||||
if (!window || typeof window.isDestroyed === 'function' && window.isDestroyed()) throw new Error('The captured window is no longer available.');
|
||||
if (typeof window.isVisible === 'function' && !window.isVisible() ||
|
||||
typeof window.isMinimized === 'function' && window.isMinimized()) {
|
||||
throw new Error('A visible, non-minimized window is required for calibrated screenshots/input.');
|
||||
}
|
||||
if (!window.webContents || typeof window.webContents.isDestroyed === 'function' && window.webContents.isDestroyed()) {
|
||||
throw new Error('The captured renderer is no longer available.');
|
||||
}
|
||||
}
|
||||
|
||||
async function readVisualState(window, panel, getContext) {
|
||||
usableWindow(window);
|
||||
const renderer = await boundedRead(() => electronTools.executeJavaScript(window, `(${windowGeometry.toString()})()`));
|
||||
if (!renderer || !Number.isFinite(renderer.width) || renderer.width <= 0 || !Number.isFinite(renderer.height) || renderer.height <= 0 || renderer.complete !== true) {
|
||||
throw new Error('Complete visible-window geometry is unavailable; calibrated input is not safe.');
|
||||
}
|
||||
const zoomFactor = typeof window.webContents.getZoomFactor === 'function' ? window.webContents.getZoomFactor() : 1;
|
||||
if (!Number.isFinite(zoomFactor) || zoomFactor <= 0) throw new Error('The renderer zoom factor is unavailable.');
|
||||
const panelBounds = panel ? await boundedRead(() => electronTools.getPanelBounds(window, panel)) : null;
|
||||
const windowWidth = Math.round(renderer.width * zoomFactor);
|
||||
const windowHeight = Math.round(renderer.height * zoomFactor);
|
||||
const css = panelBounds || { x: 0, y: 0, width: renderer.width, height: renderer.height };
|
||||
if (![css.x, css.y, css.width, css.height].every(Number.isFinite) || css.width <= 0 || css.height <= 0) {
|
||||
throw new Error('The capture region has invalid geometry.');
|
||||
}
|
||||
// Electron capturePage/sendInputEvent use content coordinates; DOM bounds are zoomed CSS coordinates.
|
||||
const x = Math.max(0, Math.floor(css.x * zoomFactor));
|
||||
const y = Math.max(0, Math.floor(css.y * zoomFactor));
|
||||
const right = Math.min(windowWidth, Math.ceil((css.x + css.width) * zoomFactor));
|
||||
const bottom = Math.min(windowHeight, Math.ceil((css.y + css.height) * zoomFactor));
|
||||
if (right <= x || bottom <= y) throw new Error('The requested capture region is outside the visible window.');
|
||||
const inputBounds = { x, y, width: right - x, height: bottom - y };
|
||||
const context = getContext ? await boundedRead(getContext) : null;
|
||||
const signature = crypto.createHash('sha256').update(JSON.stringify({ renderer, zoomFactor, inputBounds, context })).digest('hex');
|
||||
return {
|
||||
signature, inputBounds, panelBounds,
|
||||
viewport: { width: windowWidth, height: windowHeight, cssWidth: renderer.width, cssHeight: renderer.height, devicePixelRatio: renderer.devicePixelRatio, zoomFactor },
|
||||
context,
|
||||
};
|
||||
}
|
||||
|
||||
function pngDimensions(png) {
|
||||
if (!Buffer.isBuffer(png) || png.length < 24 || !png.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10])) || png.toString('ascii', 12, 16) !== 'IHDR') {
|
||||
throw new Error('Screenshot did not contain a PNG with measurable dimensions.');
|
||||
}
|
||||
const width = png.readUInt32BE(16);
|
||||
const height = png.readUInt32BE(20);
|
||||
if (!width || !height) throw new Error('Screenshot PNG has empty dimensions.');
|
||||
return { width, height };
|
||||
}
|
||||
|
||||
function registerCapture(window, png, before, after, options = {}) {
|
||||
const image = pngDimensions(png);
|
||||
const capturedAt = Date.now();
|
||||
for (const [id, entry] of captures) if (capturedAt - entry.createdAt > CAPTURE_TTL_MS) captures.delete(id);
|
||||
while (captures.size >= MAX_CAPTURES) captures.delete(captures.keys().next().value);
|
||||
const captureId = `capture_${crypto.randomBytes(12).toString('hex')}`;
|
||||
const interactive = before.signature === after.signature;
|
||||
const geometry = {
|
||||
schemaVersion: 1, captureId, capturedAt: new Date(capturedAt).toISOString(),
|
||||
coordinateSpace: 'image-pixels', origin: 'top-left',
|
||||
windowId: window.id, webContentsId: window.webContents.id,
|
||||
panel: options.panel || null, image, viewport: before.viewport,
|
||||
inputBounds: before.inputBounds,
|
||||
imageToWindowScale: { x: before.inputBounds.width / image.width, y: before.inputBounds.height / image.height },
|
||||
interactive, expiresAfterMs: CAPTURE_TTL_MS,
|
||||
reason: interactive ? null : 'geometry_changed_during_capture',
|
||||
editorScene: before.context,
|
||||
projectContext: options.projectContext || null,
|
||||
runtimeContentVerified: false,
|
||||
};
|
||||
captures.set(captureId, {
|
||||
window, webContents: window.webContents, geometry, createdAt: capturedAt,
|
||||
signature: before.signature, getContext: options.getContext,
|
||||
projectPath: options.projectPath ? path.resolve(options.projectPath) : '',
|
||||
inputOwner: options.inputOwner || '',
|
||||
});
|
||||
return geometry;
|
||||
}
|
||||
|
||||
function captureRecord(options) {
|
||||
if (typeof options.captureId !== 'string' || !options.captureId) throw new Error('captureId is required for image-pixels input.');
|
||||
const record = captures.get(options.captureId);
|
||||
if (!record) throw new Error('Unknown or expired captureId. Capture a new screenshot; do not guess a target window.');
|
||||
if (Date.now() - record.createdAt > CAPTURE_TTL_MS) {
|
||||
captures.delete(options.captureId);
|
||||
throw new Error('The screenshot is stale. Capture a new screenshot before sending input.');
|
||||
}
|
||||
if (!record.geometry.interactive) throw new Error('Geometry changed during screenshot capture. Capture a new stable image.');
|
||||
if (record.projectPath && (!options.projectPath || path.resolve(options.projectPath) !== record.projectPath)) throw new Error('The screenshot belongs to a different project.');
|
||||
if (record.inputOwner && options.inputOwner !== record.inputOwner) throw new Error('The screenshot belongs to a different Editor session. Recapture before input.');
|
||||
usableWindow(record.window);
|
||||
if (record.window.webContents !== record.webContents) throw new Error('The captured renderer was replaced. Recapture.');
|
||||
if (options.windowId !== undefined && options.windowId !== record.geometry.windowId) throw new Error('windowId does not match the screenshot.');
|
||||
if (options.panel && options.panel !== record.geometry.panel) throw new Error('panel does not match the screenshot.');
|
||||
if (options.titleContains && !String(record.window.getTitle()).toLowerCase().includes(String(options.titleContains).toLowerCase())) throw new Error('The target title does not match the screenshot window.');
|
||||
if (options.windowKind && options.windowKind !== 'focused' && options.windowKind !== electronTools.inferWindowKind(record.window.getTitle())) throw new Error('windowKind does not match the screenshot window. Use its windowId.');
|
||||
return record;
|
||||
}
|
||||
|
||||
function getCaptureWindow(options) {
|
||||
return captureRecord(options).window;
|
||||
}
|
||||
|
||||
async function resolveImagePoints(options, points) {
|
||||
const record = captureRecord(options);
|
||||
const geometry = record.geometry;
|
||||
const mapped = points.map((point) => {
|
||||
if (!Number.isFinite(point.x) || !Number.isFinite(point.y) || point.x < 0 || point.y < 0 || point.x >= geometry.image.width || point.y >= geometry.image.height) {
|
||||
throw new Error('Image coordinates must be finite and inside the exact captured PNG.');
|
||||
}
|
||||
return {
|
||||
x: Math.min(geometry.inputBounds.x + geometry.inputBounds.width - 1, Math.floor(geometry.inputBounds.x + point.x * geometry.imageToWindowScale.x)),
|
||||
y: Math.min(geometry.inputBounds.y + geometry.inputBounds.height - 1, Math.floor(geometry.inputBounds.y + point.y * geometry.imageToWindowScale.y)),
|
||||
};
|
||||
});
|
||||
const state = await readVisualState(record.window, geometry.panel, record.getContext);
|
||||
captureRecord(options); // A long read or concurrent capture may have expired/evicted this receipt.
|
||||
if (state.signature !== record.signature) throw new Error('Window, viewport, renderer, panel, or editor scene changed since capture. Recapture before input.');
|
||||
return { window: record.window, points: mapped, captureId: geometry.captureId, panel: geometry.panel, coordinateSpace: 'image-pixels' };
|
||||
}
|
||||
|
||||
function acquireInputWindow(window) {
|
||||
if (inputWindows.has(window)) throw new Error('A calibrated input operation is already active in this window.');
|
||||
inputWindows.add(window);
|
||||
return () => inputWindows.delete(window);
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
CAPTURE_TTL_MS, MAX_CAPTURES, acquireInputWindow, getCaptureWindow, pngDimensions,
|
||||
readVisualState, registerCapture, resolveImagePoints,
|
||||
};
|
||||
Reference in new issue
Block a user