codesign-mcp-next 0.0.0-stage → 0.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/CHANGELOG.md +121 -0
  2. package/LICENSE +21 -0
  3. package/README.md +458 -3
  4. package/dist/browser/manager.js +204 -0
  5. package/dist/browser/session.js +62 -0
  6. package/dist/codesign/cache.js +85 -0
  7. package/dist/codesign/errors.js +47 -0
  8. package/dist/codesign/integrity.js +197 -0
  9. package/dist/codesign/meta.js +57 -0
  10. package/dist/codesign/parser.js +56 -0
  11. package/dist/codesign/platform.js +232 -0
  12. package/dist/codesign/selection.js +205 -0
  13. package/dist/codesign/sharing.js +153 -0
  14. package/dist/codesign/slices.js +34 -0
  15. package/dist/codesign/types.js +1 -0
  16. package/dist/config.js +94 -0
  17. package/dist/index.js +16 -0
  18. package/dist/logger.js +68 -0
  19. package/dist/mcp/result.js +151 -0
  20. package/dist/mcp/schema.js +122 -0
  21. package/dist/mcp/server.js +313 -0
  22. package/dist/prompts/design-to-code.js +128 -0
  23. package/dist/resources/workflow.js +33 -0
  24. package/dist/server.js +61 -0
  25. package/dist/tools/artboards.js +96 -0
  26. package/dist/tools/diagnostics.js +192 -0
  27. package/dist/tools/image.js +134 -0
  28. package/dist/tools/login.js +136 -0
  29. package/dist/tools/slices.js +228 -0
  30. package/dist/tools/spec.js +236 -0
  31. package/dist/tools/status.js +62 -0
  32. package/dist/utils/download.js +290 -0
  33. package/dist/utils/filename.js +16 -0
  34. package/dist/utils/http.js +54 -0
  35. package/dist/utils/rate-limit.js +120 -0
  36. package/dist/utils/redact.js +110 -0
  37. package/dist/utils/retry.js +97 -0
  38. package/dist/utils/url.js +98 -0
  39. package/package.json +58 -6
  40. package/userscripts/codesign-ai-selection.user.js +445 -0
package/dist/config.js ADDED
@@ -0,0 +1,94 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { resolve } from 'node:path';
3
+ import { fileURLToPath } from 'node:url';
4
+ import { dirname } from 'node:path';
5
+ const here = dirname(fileURLToPath(import.meta.url));
6
+ const PACKAGE_ROOT = resolve(here, '..');
7
+ const PACKAGE_JSON_PATH = resolve(PACKAGE_ROOT, 'package.json');
8
+ const LOG_LEVELS = new Set(['trace', 'debug', 'info', 'warn', 'error']);
9
+ function resolveWorkspaceRoot() {
10
+ if (process.env.CODESIGN_WORKSPACE_DIR) {
11
+ return { path: resolve(process.env.CODESIGN_WORKSPACE_DIR), source: 'CODESIGN_WORKSPACE_DIR' };
12
+ }
13
+ if (process.env.INIT_CWD) {
14
+ return { path: resolve(process.env.INIT_CWD), source: 'INIT_CWD' };
15
+ }
16
+ return { path: process.cwd(), source: 'process.cwd' };
17
+ }
18
+ function readPackageVersion() {
19
+ const parsed = JSON.parse(readFileSync(PACKAGE_JSON_PATH, 'utf8'));
20
+ if (typeof parsed.version !== 'string' || parsed.version.length === 0) {
21
+ throw new Error(`Invalid package version in ${PACKAGE_JSON_PATH}`);
22
+ }
23
+ return parsed.version;
24
+ }
25
+ const workspace = resolveWorkspaceRoot();
26
+ const WORKSPACE_ROOT = workspace.path;
27
+ const PACKAGE_VERSION = readPackageVersion();
28
+ const DATA_DIR = process.env.CODESIGN_DATA_DIR
29
+ ? resolve(process.env.CODESIGN_DATA_DIR)
30
+ : resolve(WORKSPACE_ROOT, '.codesign-mcp');
31
+ function envInt(name, fallback) {
32
+ const raw = process.env[name];
33
+ if (raw == null || raw === '')
34
+ return fallback;
35
+ const n = Number(raw);
36
+ if (!Number.isSafeInteger(n) || n < 0) {
37
+ throw new Error(`${name} must be a non-negative integer, got ${JSON.stringify(raw)}`);
38
+ }
39
+ return n;
40
+ }
41
+ function envBool(name, fallback) {
42
+ const raw = process.env[name];
43
+ if (raw == null || raw === '')
44
+ return fallback;
45
+ const normalized = raw.toLowerCase();
46
+ if (['1', 'true', 'yes', 'on'].includes(normalized))
47
+ return true;
48
+ if (['0', 'false', 'no', 'off'].includes(normalized))
49
+ return false;
50
+ throw new Error(`${name} must be one of 1, true, yes, on, 0, false, no, off; got ${JSON.stringify(raw)}`);
51
+ }
52
+ function envLogLevel(name, fallback) {
53
+ const raw = process.env[name];
54
+ if (raw == null || raw === '')
55
+ return fallback;
56
+ if (LOG_LEVELS.has(raw))
57
+ return raw;
58
+ throw new Error(`${name} must be one of ${Array.from(LOG_LEVELS).join(', ')}; got ${JSON.stringify(raw)}`);
59
+ }
60
+ export const config = {
61
+ packageRoot: PACKAGE_ROOT,
62
+ packageVersion: PACKAGE_VERSION,
63
+ workspaceRoot: WORKSPACE_ROOT,
64
+ workspaceRootSource: workspace.source,
65
+ projectRoot: WORKSPACE_ROOT,
66
+ dataDir: DATA_DIR,
67
+ dataDirSource: process.env.CODESIGN_DATA_DIR ? 'CODESIGN_DATA_DIR' : 'workspace-default',
68
+ profileDir: process.env.CODESIGN_PROFILE_DIR
69
+ ? resolve(process.env.CODESIGN_PROFILE_DIR)
70
+ : resolve(DATA_DIR, 'profile'),
71
+ artifactsDir: process.env.CODESIGN_ARTIFACTS_DIR
72
+ ? resolve(process.env.CODESIGN_ARTIFACTS_DIR)
73
+ : resolve(DATA_DIR, 'artifacts'),
74
+ logFile: process.env.CODESIGN_LOG_FILE
75
+ ? resolve(process.env.CODESIGN_LOG_FILE)
76
+ : resolve(DATA_DIR, 'codesign-mcp.log'),
77
+ logFileSource: process.env.CODESIGN_LOG_FILE ? 'CODESIGN_LOG_FILE' : 'data-dir-default',
78
+ logLevel: envLogLevel('CODESIGN_LOG_LEVEL', 'info'),
79
+ idleMs: envInt('CODESIGN_IDLE_MS', 10 * 60 * 1000),
80
+ keepBrowser: envBool('CODESIGN_KEEP_BROWSER', false),
81
+ cacheTtlMs: envInt('CODESIGN_CACHE_TTL_MS', 60_000),
82
+ integrityStrict: envBool('CODESIGN_INTEGRITY_STRICT', false),
83
+ origin: 'https://codesign.qq.com',
84
+ homePath: '/app/design',
85
+ navTimeoutMs: envInt('CODESIGN_NAV_TIMEOUT_MS', 30_000),
86
+ apiTimeoutMs: envInt('CODESIGN_API_TIMEOUT_MS', 20_000),
87
+ metaTimeoutMs: envInt('CODESIGN_META_TIMEOUT_MS', 30_000),
88
+ retryMaxAttempts: envInt('CODESIGN_RETRY_MAX_ATTEMPTS', 3),
89
+ retryBaseDelayMs: envInt('CODESIGN_RETRY_BASE_MS', 300),
90
+ retryMaxDelayMs: envInt('CODESIGN_RETRY_MAX_DELAY_MS', 8_000),
91
+ retryAfterMaxMs: envInt('CODESIGN_RETRY_AFTER_MAX_MS', 30_000),
92
+ apiRps: envInt('CODESIGN_API_RPS', 5),
93
+ cdnRps: envInt('CODESIGN_CDN_RPS', 10),
94
+ };
package/dist/index.js ADDED
@@ -0,0 +1,16 @@
1
+ #!/usr/bin/env node
2
+ import { startStdio } from './server.js';
3
+ import { getLogger } from './logger.js';
4
+ const log = getLogger();
5
+ process.on('uncaughtException', (err) => {
6
+ log.error({ err: err.message, stack: err.stack }, 'uncaughtException');
7
+ });
8
+ process.on('unhandledRejection', (reason) => {
9
+ log.error({ reason: reason instanceof Error ? reason.message : String(reason) }, 'unhandledRejection');
10
+ });
11
+ startStdio().catch((err) => {
12
+ log.error({ err: err.message, stack: err.stack }, 'failed to start');
13
+ // stdio MCP 协议要求 stderr 用于诊断,stdout 给协议
14
+ process.stderr.write(`codesign-mcp failed to start: ${err.message}\n`);
15
+ process.exit(1);
16
+ });
package/dist/logger.js ADDED
@@ -0,0 +1,68 @@
1
+ import { appendFileSync, existsSync, mkdirSync } from 'node:fs';
2
+ import { dirname } from 'node:path';
3
+ import { config } from './config.js';
4
+ const LEVEL_SEVERITY = {
5
+ trace: 10,
6
+ debug: 20,
7
+ info: 30,
8
+ warn: 40,
9
+ error: 50,
10
+ };
11
+ let _logger;
12
+ export function getLogger() {
13
+ if (_logger)
14
+ return _logger;
15
+ _logger = createFileLogger();
16
+ return _logger;
17
+ }
18
+ function createFileLogger() {
19
+ return {
20
+ trace: (...args) => writeLog('trace', args),
21
+ debug: (...args) => writeLog('debug', args),
22
+ info: (...args) => writeLog('info', args),
23
+ warn: (...args) => writeLog('warn', args),
24
+ error: (...args) => writeLog('error', args),
25
+ };
26
+ }
27
+ function writeLog(level, args) {
28
+ if (LEVEL_SEVERITY[level] < LEVEL_SEVERITY[config.logLevel])
29
+ return;
30
+ const entry = normalizeLogEntry(level, args);
31
+ const logDir = dirname(config.logFile);
32
+ if (config.logFileSource === 'CODESIGN_LOG_FILE' || existsSync(logDir)) {
33
+ mkdirSync(logDir, { recursive: true });
34
+ appendFileSync(config.logFile, `${JSON.stringify(entry)}\n`, 'utf8');
35
+ return;
36
+ }
37
+ process.stderr.write(`${JSON.stringify(entry)}\n`);
38
+ }
39
+ function normalizeLogEntry(level, args) {
40
+ const entry = {
41
+ level,
42
+ time: new Date().toISOString(),
43
+ name: 'codesign-mcp',
44
+ };
45
+ if (args.length === 0)
46
+ return entry;
47
+ const [first, second, ...rest] = args;
48
+ if (isPlainRecord(first)) {
49
+ Object.assign(entry, first);
50
+ if (typeof second === 'string')
51
+ entry.msg = second;
52
+ if (rest.length > 0)
53
+ entry.args = rest.map(stringifyArg);
54
+ return entry;
55
+ }
56
+ entry.msg = args.map(stringifyArg).join(' ');
57
+ return entry;
58
+ }
59
+ function isPlainRecord(value) {
60
+ return value != null && typeof value === 'object' && !Array.isArray(value);
61
+ }
62
+ function stringifyArg(value) {
63
+ if (typeof value === 'string')
64
+ return value;
65
+ if (value instanceof Error)
66
+ return value.message;
67
+ return JSON.stringify(value);
68
+ }
@@ -0,0 +1,151 @@
1
+ // 统一的工具返回构造。
2
+ // 默认只在 content[0].text 放一行摘要,完整数据放在 structuredContent,
3
+ // 避免同一份 JSON 在 LLM 上下文里出现两遍。老客户端如果不读
4
+ // structuredContent,可以传 includeFullText=true 拿完整文本(无缩进)。
5
+ import { isCodesignError } from '../codesign/errors.js';
6
+ function errMsg(err) {
7
+ if (err instanceof Error)
8
+ return err.message;
9
+ return String(err);
10
+ }
11
+ function summarizeValue(value) {
12
+ if (Array.isArray(value))
13
+ return `${value.length} item${value.length === 1 ? '' : 's'}`;
14
+ if (value && typeof value === 'object') {
15
+ const entries = Object.entries(value);
16
+ const arrays = entries
17
+ .filter(([, item]) => Array.isArray(item))
18
+ .map(([key, item]) => `${key}: ${item.length}`);
19
+ return arrays.length > 0
20
+ ? `{${entries.length} fields; ${arrays.join(', ')}}`
21
+ : `{${entries.length} fields}`;
22
+ }
23
+ if (typeof value === 'string' && value.length > 120)
24
+ return `"${value.slice(0, 117)}..."`;
25
+ return String(value);
26
+ }
27
+ export function summarizePayload(payload) {
28
+ const lines = [payload.ok === false ? 'failed' : 'ok'];
29
+ for (const [key, value] of Object.entries(payload)) {
30
+ if (value == null || key === 'ok')
31
+ continue;
32
+ lines.push(`${key}: ${summarizeValue(value)}`);
33
+ }
34
+ lines.push('Full data is available in structuredContent.');
35
+ return lines.join('\n');
36
+ }
37
+ export function toolSuccess(payload, includeFullText = false, summarizer = summarizePayload) {
38
+ const structuredContent = { ok: true, ...payload };
39
+ return {
40
+ structuredContent,
41
+ content: [{
42
+ type: 'text',
43
+ text: includeFullText ? JSON.stringify(structuredContent) : summarizer(structuredContent),
44
+ }],
45
+ };
46
+ }
47
+ // get_artboard_spec 的文本摘要:保留两层层级骨架与完整性告警,
48
+ // 让不读 structuredContent 的客户端也能看到还原必需的结构信息。
49
+ export function summarizeSpecPayload(payload) {
50
+ const lines = [payload.ok === false ? 'failed' : 'ok'];
51
+ for (const [key, value] of Object.entries(payload)) {
52
+ if (value == null || key === 'ok')
53
+ continue;
54
+ if (key === 'spec') {
55
+ lines.push(...summarizeSpec(value));
56
+ }
57
+ else if (key === 'selection') {
58
+ lines.push(...summarizeSelection(value));
59
+ }
60
+ else if (key === 'integrity') {
61
+ lines.push(summarizeIntegrity(value));
62
+ }
63
+ else {
64
+ lines.push(`${key}: ${summarizeValue(value)}`);
65
+ }
66
+ }
67
+ lines.push('Full data is available in structuredContent.');
68
+ return lines.join('\n');
69
+ }
70
+ function summarizeSpec(value) {
71
+ if (!value || typeof value !== 'object')
72
+ return [`spec: ${summarizeValue(value)}`];
73
+ const spec = value;
74
+ const lines = [];
75
+ const artboard = spec.artboard;
76
+ if (artboard) {
77
+ lines.push(`artboard: ${artboard.name ?? '?'} (${artboard.width ?? '?'}x${artboard.height ?? '?'})`);
78
+ }
79
+ lines.push(...summarizeHierarchy(spec.hierarchy));
80
+ lines.push(`spec: layers: ${spec.layers?.length ?? 0}, groups: ${spec.groups?.length ?? 0}, slices: ${spec.slices?.length ?? 0}`);
81
+ return lines;
82
+ }
83
+ function summarizeSelection(value) {
84
+ if (!value || typeof value !== 'object')
85
+ return [`selection: ${summarizeValue(value)}`];
86
+ const selection = value;
87
+ return [
88
+ `selection: ${selection.scope ?? '?'} root=${selection.rootName ?? '?'} nodes=${selection.nodeCount ?? 0} (layers ${selection.layerCount ?? 0}, groups ${selection.groupCount ?? 0})`,
89
+ ...summarizeHierarchy(selection.hierarchy),
90
+ ];
91
+ }
92
+ function summarizeHierarchy(hierarchy) {
93
+ if (!Array.isArray(hierarchy) || hierarchy.length === 0)
94
+ return [];
95
+ const lines = [`hierarchy (top levels):`];
96
+ let visited = 0;
97
+ const walk = (nodes, depth) => {
98
+ for (const node of nodes) {
99
+ if (visited >= 40)
100
+ return;
101
+ if (depth < 2) {
102
+ const size = node.rect ? `${node.rect.width}x${node.rect.height}` : '?';
103
+ lines.push(`${' '.repeat(depth)}- ${node.name} [${node.type}] ${size}`);
104
+ }
105
+ visited += 1;
106
+ if (Array.isArray(node.children))
107
+ walk(node.children, depth + 1);
108
+ }
109
+ };
110
+ walk(hierarchy, 0);
111
+ if (visited > 40)
112
+ lines.push(' ... (truncated)');
113
+ return lines;
114
+ }
115
+ function summarizeIntegrity(value) {
116
+ if (!value || typeof value !== 'object')
117
+ return `integrity: ${summarizeValue(value)}`;
118
+ const integrity = value;
119
+ if (Array.isArray(integrity.warnings) && integrity.warnings.length > 0) {
120
+ const preview = integrity.warnings.slice(0, 3).map((item) => String(item)).join('; ');
121
+ return `integrity: warnings=${integrity.warnings.length} (${preview})`;
122
+ }
123
+ return `integrity: ${integrity.ok === false ? 'failed' : 'ok'}`;
124
+ }
125
+ // 诊断记录本身就是给 LLM 阅读的内容,默认保留完整文本但不加缩进。
126
+ export function toolSuccessFull(payload) {
127
+ const structuredContent = { ok: true, ...payload };
128
+ return {
129
+ structuredContent,
130
+ content: [{ type: 'text', text: JSON.stringify(structuredContent) }],
131
+ };
132
+ }
133
+ export function toolFailure(payload) {
134
+ const structuredContent = { ok: false, ...payload };
135
+ return {
136
+ isError: true,
137
+ structuredContent,
138
+ content: [{ type: 'text', text: summarizePayload(structuredContent) }],
139
+ };
140
+ }
141
+ export function toolError(err) {
142
+ const error = isCodesignError(err)
143
+ ? err.toJSON()
144
+ : { code: 'INTERNAL', message: errMsg(err) };
145
+ const structuredContent = { ok: false, error };
146
+ return {
147
+ isError: true,
148
+ structuredContent,
149
+ content: [{ type: 'text', text: `[${error.code}] ${error.message}` }],
150
+ };
151
+ }
@@ -0,0 +1,122 @@
1
+ export function objectSchema(properties, required = []) {
2
+ const schema = {
3
+ type: 'object',
4
+ properties,
5
+ additionalProperties: false,
6
+ };
7
+ if (required.length > 0)
8
+ schema.required = required;
9
+ return schema;
10
+ }
11
+ export function validateArgs(schema, args, label) {
12
+ return validateValue(schema, args ?? {}, label);
13
+ }
14
+ function validateValue(schema, value, path) {
15
+ if (schema.anyOf) {
16
+ const errors = [];
17
+ for (const option of schema.anyOf) {
18
+ try {
19
+ return validateValue(option, value, path);
20
+ }
21
+ catch (err) {
22
+ errors.push(err instanceof Error ? err.message : String(err));
23
+ }
24
+ }
25
+ throw new Error(`${path} does not match any allowed type: ${errors.join('; ')}`);
26
+ }
27
+ if ('const' in schema && value !== schema.const) {
28
+ throw new Error(`${path} must be ${JSON.stringify(schema.const)}`);
29
+ }
30
+ if (schema.enum && !schema.enum.includes(value)) {
31
+ throw new Error(`${path} must be one of ${schema.enum.map((v) => JSON.stringify(v)).join(', ')}`);
32
+ }
33
+ switch (schema.type) {
34
+ case 'object':
35
+ return validateObject(schema, value, path);
36
+ case 'string':
37
+ return validateString(schema, value, path);
38
+ case 'number':
39
+ return validateNumber(schema, value, path, false);
40
+ case 'integer':
41
+ return validateNumber(schema, value, path, true);
42
+ case 'boolean':
43
+ if (typeof value !== 'boolean')
44
+ throw new Error(`${path} must be a boolean`);
45
+ return value;
46
+ case 'array':
47
+ return validateArray(schema, value, path);
48
+ default:
49
+ return value;
50
+ }
51
+ }
52
+ function validateObject(schema, value, path) {
53
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
54
+ throw new Error(`${path} must be an object`);
55
+ }
56
+ const input = value;
57
+ const properties = schema.properties ?? {};
58
+ const required = new Set(schema.required ?? []);
59
+ const output = {};
60
+ for (const name of required) {
61
+ if (!(name in input) || input[name] === undefined) {
62
+ throw new Error(`${path}.${name} is required`);
63
+ }
64
+ }
65
+ if (schema.additionalProperties === false) {
66
+ for (const name of Object.keys(input)) {
67
+ if (!(name in properties)) {
68
+ throw new Error(`${path}.${name} is not a supported argument`);
69
+ }
70
+ }
71
+ }
72
+ for (const [name, propertySchema] of Object.entries(properties)) {
73
+ const childPath = `${path}.${name}`;
74
+ const raw = input[name];
75
+ if (raw === undefined) {
76
+ if ('default' in propertySchema) {
77
+ output[name] = cloneDefault(propertySchema.default);
78
+ }
79
+ continue;
80
+ }
81
+ output[name] = validateValue(propertySchema, raw, childPath);
82
+ }
83
+ return output;
84
+ }
85
+ function validateString(schema, value, path) {
86
+ if (typeof value !== 'string')
87
+ throw new Error(`${path} must be a string`);
88
+ if (schema.minLength != null && value.length < schema.minLength) {
89
+ throw new Error(`${path} must contain at least ${schema.minLength} character(s)`);
90
+ }
91
+ return value;
92
+ }
93
+ function validateNumber(schema, value, path, integer) {
94
+ if (typeof value !== 'number' || !Number.isFinite(value)) {
95
+ throw new Error(`${path} must be a ${integer ? 'integer' : 'number'}`);
96
+ }
97
+ if (integer && !Number.isInteger(value)) {
98
+ throw new Error(`${path} must be an integer`);
99
+ }
100
+ if (schema.minimum != null && value < schema.minimum) {
101
+ throw new Error(`${path} must be >= ${schema.minimum}`);
102
+ }
103
+ if (schema.maximum != null && value > schema.maximum) {
104
+ throw new Error(`${path} must be <= ${schema.maximum}`);
105
+ }
106
+ return value;
107
+ }
108
+ function validateArray(schema, value, path) {
109
+ if (!Array.isArray(value))
110
+ throw new Error(`${path} must be an array`);
111
+ const itemSchema = schema.items;
112
+ if (!itemSchema)
113
+ return value;
114
+ return value.map((item, index) => validateValue(itemSchema, item, `${path}[${index}]`));
115
+ }
116
+ function cloneDefault(value) {
117
+ if (Array.isArray(value))
118
+ return [...value];
119
+ if (value && typeof value === 'object')
120
+ return { ...value };
121
+ return value;
122
+ }