@zenaigc/zenmcp 0.1.5 → 0.1.7

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 (33) hide show
  1. package/INSTALL.md +41 -25
  2. package/dist/src/doctor.js +8 -2
  3. package/dist/src/engine/direct.js +4 -2
  4. package/dist/src/engine/steps.js +2 -1
  5. package/dist/src/gateway/cloud-gateway.js +1 -1
  6. package/dist/src/inspect/media.js +7 -7
  7. package/dist/src/mcp/guidance.js +3 -3
  8. package/dist/src/mcp/server.js +113 -28
  9. package/dist/src/setup/cli.js +273 -0
  10. package/dist/src/setup/credentials.js +157 -0
  11. package/dist/src/setup/page.js +822 -0
  12. package/dist/src/setup/server.js +251 -0
  13. package/dist/src/setup/targets.js +314 -0
  14. package/dist/src/setup/validate.js +84 -0
  15. package/dist/src/speech/tools.js +34 -19
  16. package/dist/src/timeline/ffmpeg.js +6 -1
  17. package/dist/src/timeline/probe.js +50 -0
  18. package/package.json +4 -2
  19. package/skills/zenmcp/SKILL.md +7 -5
  20. package/skills/zenmcp/widgets/fixtures/zenmcp-account.json +1 -0
  21. package/skills/zenmcp/widgets/fixtures/zenmcp-asset-roles.json +24 -0
  22. package/skills/zenmcp/widgets/fixtures/zenmcp-install-checklist.json +1 -1
  23. package/skills/zenmcp/widgets/fixtures/zenmcp-trim-range.json +19 -0
  24. package/skills/zenmcp/widgets/zenmcp-account/template.json +7 -0
  25. package/skills/zenmcp/widgets/zenmcp-account/widget.html +4 -4
  26. package/skills/zenmcp/widgets/zenmcp-asset-roles/template.json +54 -0
  27. package/skills/zenmcp/widgets/zenmcp-asset-roles/widget.html +73 -0
  28. package/skills/zenmcp/widgets/zenmcp-budget-confirm/widget.html +2 -4
  29. package/skills/zenmcp/widgets/zenmcp-install-checklist/widget.html +3 -5
  30. package/skills/zenmcp/widgets/zenmcp-model-picker/widget.html +6 -6
  31. package/skills/zenmcp/widgets/zenmcp-spend-confirm/widget.html +2 -3
  32. package/skills/zenmcp/widgets/zenmcp-trim-range/template.json +53 -0
  33. package/skills/zenmcp/widgets/zenmcp-trim-range/widget.html +52 -0
@@ -0,0 +1,273 @@
1
+ #!/usr/bin/env node
2
+ import { spawn } from 'node:child_process';
3
+ import { realpath } from 'node:fs/promises';
4
+ import { platform } from 'node:os';
5
+ import { pathToFileURL } from 'node:url';
6
+ import { ACCOUNT_URL } from '../mcp/guidance.js';
7
+ import { clearCredential, saveCredential, } from './credentials.js';
8
+ import { startSetupServer } from './server.js';
9
+ import { DEFAULT_ZENMCP_BASE_URL, validateZenmcpKey } from './validate.js';
10
+ export function isHeadlessOrSsh(env = process.env, os = platform()) {
11
+ if (env.SSH_CONNECTION || env.SSH_TTY || env.SSH_CLIENT)
12
+ return true;
13
+ if (os === 'linux' && !env.DISPLAY && !env.WAYLAND_DISPLAY)
14
+ return true;
15
+ return false;
16
+ }
17
+ export function parseSetupArgs(argv, defaultMode = 'auto-web') {
18
+ const parsed = {
19
+ mode: defaultMode,
20
+ noOpen: false,
21
+ port: 0,
22
+ help: false,
23
+ };
24
+ for (let i = 0; i < argv.length; i += 1) {
25
+ const arg = argv[i];
26
+ if (arg === 'login') {
27
+ parsed.mode = 'terminal';
28
+ continue;
29
+ }
30
+ if (arg === 'logout') {
31
+ parsed.mode = 'logout';
32
+ continue;
33
+ }
34
+ if (arg === '--help' || arg === '-h') {
35
+ parsed.help = true;
36
+ continue;
37
+ }
38
+ if (arg === '--web') {
39
+ parsed.mode = 'web';
40
+ continue;
41
+ }
42
+ if (arg === '--terminal' || arg === '--stdin') {
43
+ parsed.mode = 'terminal';
44
+ continue;
45
+ }
46
+ if (arg === '--no-open') {
47
+ parsed.noOpen = true;
48
+ if (parsed.mode === 'terminal')
49
+ parsed.mode = 'web';
50
+ continue;
51
+ }
52
+ if (arg === '--token' ||
53
+ arg === '--key' ||
54
+ arg.startsWith('--token=') ||
55
+ arg.startsWith('--key=')) {
56
+ throw new Error('出于安全原因,请勿通过命令行参数传入平台 Key(会留在终端历史中)。请直接运行 zenmcp login 按隐藏提示粘贴。');
57
+ }
58
+ if (arg === '--port') {
59
+ const next = argv[i + 1];
60
+ if (!next || !/^\d+$/.test(next)) {
61
+ throw new Error('--port 需要一个有效的端口号(0-65535)。');
62
+ }
63
+ const port = Number(next);
64
+ if (port < 0 || port > 65535) {
65
+ throw new Error('--port 必须在 0 到 65535 之间。');
66
+ }
67
+ parsed.port = port;
68
+ parsed.mode = 'web';
69
+ i += 1;
70
+ continue;
71
+ }
72
+ throw new Error(`未知参数:${arg}(运行 zenmcp login --help 查看用法)`);
73
+ }
74
+ return parsed;
75
+ }
76
+ function openBrowser(url, os = platform()) {
77
+ try {
78
+ if (os === 'darwin') {
79
+ const child = spawn('open', [url], { detached: true, stdio: 'ignore' });
80
+ child.unref();
81
+ return true;
82
+ }
83
+ if (os === 'win32') {
84
+ const child = spawn('cmd', ['/c', 'start', '', url], { detached: true, stdio: 'ignore' });
85
+ child.unref();
86
+ return true;
87
+ }
88
+ const child = spawn('xdg-open', [url], { detached: true, stdio: 'ignore' });
89
+ child.unref();
90
+ return true;
91
+ }
92
+ catch {
93
+ return false;
94
+ }
95
+ }
96
+ function stripBracketedPaste(raw) {
97
+ return raw.replace(/\x1b\[20[01]~/g, '').trim();
98
+ }
99
+ export async function readSecretFromStream(stdin = process.stdin, stdout = process.stdout, promptText = '粘贴平台 Key(输入已隐藏,按回车确认):') {
100
+ if (!stdin.isTTY || typeof stdin.setRawMode !== 'function') {
101
+ const chunks = [];
102
+ for await (const chunk of stdin) {
103
+ chunks.push(typeof chunk === 'string' ? Buffer.from(chunk, 'utf8') : chunk);
104
+ }
105
+ const firstLine = Buffer.concat(chunks).toString('utf8').split(/\r?\n/)[0] ?? '';
106
+ return stripBracketedPaste(firstLine);
107
+ }
108
+ stdout.write(promptText);
109
+ return new Promise((resolve, reject) => {
110
+ let buffer = '';
111
+ const wasRaw = Boolean(stdin.isRaw);
112
+ stdin.setRawMode(true);
113
+ stdin.resume();
114
+ const cleanup = () => {
115
+ stdin.off('data', onData);
116
+ stdin.off('error', onError);
117
+ try {
118
+ stdin.setRawMode(wasRaw);
119
+ }
120
+ catch { }
121
+ stdin.pause();
122
+ };
123
+ const onError = (err) => {
124
+ cleanup();
125
+ stdout.write('\n');
126
+ reject(err);
127
+ };
128
+ const onData = (chunk) => {
129
+ const text = typeof chunk === 'string' ? chunk : chunk.toString('utf8');
130
+ for (let i = 0; i < text.length; i += 1) {
131
+ const ch = text[i];
132
+ const code = ch.charCodeAt(0);
133
+ if (code === 3) {
134
+ cleanup();
135
+ stdout.write('\n');
136
+ reject(new Error('已取消输入。'));
137
+ return;
138
+ }
139
+ if (ch === '\r' || ch === '\n' || code === 4) {
140
+ cleanup();
141
+ stdout.write('\n');
142
+ resolve(stripBracketedPaste(buffer));
143
+ return;
144
+ }
145
+ if (code === 127 || code === 8) {
146
+ buffer = buffer.slice(0, -1);
147
+ continue;
148
+ }
149
+ buffer += ch;
150
+ }
151
+ };
152
+ stdin.on('data', onData);
153
+ stdin.on('error', onError);
154
+ });
155
+ }
156
+ function printHelp(stdout) {
157
+ stdout.write([
158
+ 'ZenMCP 账户连接工具(密钥仅保存在本机安全凭据库,免重启即刻生效)',
159
+ '',
160
+ '用法:',
161
+ ' zenmcp login 在终端隐藏输入平台 Key 并验证保存(支持本机与远程 SSH)',
162
+ ' zenmcp login --web 打开本机 127.0.0.1 网页连接卡片粘贴保存',
163
+ ' zenmcp logout 清除已保存的本机平台 Key',
164
+ ' zenmcp-setup 在桌面环境打开本机连接页(远程 SSH 自动切换为终端隐藏输入)',
165
+ '',
166
+ '选项:',
167
+ ' --web 使用本机回环网页连接页',
168
+ ' --terminal 使用终端隐藏输入(默认用于 zenmcp login)',
169
+ ' --port <port> 指定 127.0.0.1 监听端口(默认 0,随机端口)',
170
+ ' --no-open 网页模式下仅输出本地地址,不自动打开浏览器',
171
+ ' -h, --help 显示此帮助信息',
172
+ '',
173
+ ].join('\n'));
174
+ }
175
+ async function runTerminalLogin(io, storeOptions) {
176
+ const stdout = io.stdout ?? process.stdout;
177
+ const env = io.env ?? process.env;
178
+ const baseUrl = env.ZENMCP_BASE_URL?.trim() || DEFAULT_ZENMCP_BASE_URL;
179
+ stdout.write(`请前往 ${ACCOUNT_URL} 创建并复制平台 Key。\n`);
180
+ if (env.ZENMCP_TOKEN?.trim()) {
181
+ stdout.write('提示:检测到当前环境设置了 ZENMCP_TOKEN 环境变量,它会优先于本机凭据文件生效;如旧 Key 已失效,请移除客户端配置中的 env.ZENMCP_TOKEN 后重新加载客户端。\n');
182
+ }
183
+ const secret = io.readSecret
184
+ ? await io.readSecret()
185
+ : await readSecretFromStream(io.stdin ?? process.stdin, stdout);
186
+ const validation = await validateZenmcpKey(secret, {
187
+ baseUrl,
188
+ ...(io.fetch ? { fetch: io.fetch } : {}),
189
+ });
190
+ if (!validation.ok) {
191
+ throw new Error(validation.message);
192
+ }
193
+ await saveCredential(secret, storeOptions);
194
+ stdout.write(`✓ ${validation.message}\n`);
195
+ stdout.write(`可用积分:${validation.account.credits_available} · 当前单次可支配上限:${validation.account.effective_available_credits}\n`);
196
+ stdout.write('现在可直接回到智能体对话继续使用,无需重启客户端。\n');
197
+ }
198
+ export async function runSetupCli(argv = process.argv.slice(2), io = {}, defaultMode = 'auto-web') {
199
+ const stdout = io.stdout ?? process.stdout;
200
+ const env = io.env ?? process.env;
201
+ const os = io.platform ?? platform();
202
+ const args = parseSetupArgs(argv, defaultMode);
203
+ if (args.help) {
204
+ printHelp(stdout);
205
+ return;
206
+ }
207
+ const storeOptions = {
208
+ env,
209
+ platform: os,
210
+ ...(io.credentialsPath !== undefined ? { credentialsPath: io.credentialsPath } : {}),
211
+ };
212
+ if (args.mode === 'logout') {
213
+ const result = await clearCredential(storeOptions);
214
+ stdout.write(result.removed
215
+ ? '已清除本机保存的平台 Key。\n'
216
+ : '本机当前没有已保存的平台 Key。\n');
217
+ if (env.ZENMCP_TOKEN?.trim()) {
218
+ stdout.write('注意:当前环境仍存在 ZENMCP_TOKEN 环境变量,如需停用请从客户端配置中移除。\n');
219
+ }
220
+ return;
221
+ }
222
+ const headless = isHeadlessOrSsh(env, os);
223
+ if (args.mode === 'terminal' || (args.mode === 'auto-web' && headless && !args.noOpen)) {
224
+ if (args.mode === 'auto-web' && headless) {
225
+ stdout.write('检测到远程 SSH 或无图形桌面环境,已自动切换为终端隐藏输入模式。\n');
226
+ }
227
+ await runTerminalLogin(io, storeOptions);
228
+ return;
229
+ }
230
+ if (headless) {
231
+ stdout.write('提示:当前处于远程或无图形桌面环境,127.0.0.1 仅能在当前机器访问;建议直接运行 `zenmcp login` 在终端隐藏粘贴。\n');
232
+ }
233
+ const handle = await startSetupServer({
234
+ port: args.port,
235
+ ...storeOptions,
236
+ ...(io.fetch ? { fetch: io.fetch } : {}),
237
+ });
238
+ const onSignal = () => {
239
+ void handle.close();
240
+ };
241
+ process.once('SIGINT', onSignal);
242
+ process.once('SIGTERM', onSignal);
243
+ stdout.write('ZenMCP 本机安全连接服务已启动(密钥不经过聊天记录,连接后自动关闭)。\n');
244
+ stdout.write(`本机访问地址:${handle.url}\n`);
245
+ if (!args.noOpen) {
246
+ const opened = openBrowser(handle.url, os);
247
+ if (!opened) {
248
+ stdout.write('未能自动打开浏览器,请复制上方地址到本机浏览器打开,或按 Ctrl+C 改用 `zenmcp login`。\n');
249
+ }
250
+ }
251
+ const summary = await handle.closed;
252
+ process.off('SIGINT', onSignal);
253
+ process.off('SIGTERM', onSignal);
254
+ if (summary.saved && summary.account) {
255
+ stdout.write(`✓ 连接已完成(可用积分:${summary.account.credits_available},当前单次可支配上限:${summary.account.effective_available_credits})。无需重启客户端,直接回到对话继续即可。\n`);
256
+ }
257
+ else if (summary.timedOut) {
258
+ stdout.write('连接等待超时,临时端口已自动关闭。如需继续请重新运行 `zenmcp login`。\n');
259
+ }
260
+ else {
261
+ stdout.write('已关闭本地连接服务(未修改本机凭据)。\n');
262
+ }
263
+ }
264
+ export async function runAuthSubcommand(argv, io = {}) {
265
+ await runSetupCli(argv, io, 'terminal');
266
+ }
267
+ const entry = process.argv[1] ? await realpath(process.argv[1]).catch(() => process.argv[1]) : '';
268
+ if (entry && import.meta.url === pathToFileURL(entry).href) {
269
+ runSetupCli().catch((error) => {
270
+ console.error(error instanceof Error ? error.message : '账户连接未能完成。');
271
+ process.exitCode = 1;
272
+ });
273
+ }
@@ -0,0 +1,157 @@
1
+ import { chmod, mkdir, open, readFile, rename, rm } from 'node:fs/promises';
2
+ import { homedir, platform } from 'node:os';
3
+ import { dirname, join, resolve } from 'node:path';
4
+ import { randomBytes } from 'node:crypto';
5
+ /**
6
+ * Resolves the per-user credential store path across macOS, Linux, and Windows.
7
+ * Setting ZENMCP_CREDENTIALS_PATH="" explicitly disables file lookup (useful for isolated tests).
8
+ */
9
+ export function resolveCredentialsPath(options = {}) {
10
+ if (options.credentialsPath !== undefined) {
11
+ if (options.credentialsPath === null)
12
+ return null;
13
+ const trimmed = options.credentialsPath.trim();
14
+ return trimmed ? resolve(trimmed) : null;
15
+ }
16
+ const env = options.env ?? process.env;
17
+ if (env.ZENMCP_CREDENTIALS_PATH !== undefined) {
18
+ const trimmed = env.ZENMCP_CREDENTIALS_PATH.trim();
19
+ return trimmed ? resolve(trimmed) : null;
20
+ }
21
+ const os = options.platform ?? platform();
22
+ const home = options.homedir ?? homedir();
23
+ if (os === 'win32') {
24
+ const appData = env.APPDATA?.trim() || join(home, 'AppData', 'Roaming');
25
+ return join(appData, 'zenmcp', 'credentials.json');
26
+ }
27
+ const configHome = env.XDG_CONFIG_HOME?.trim() || join(home, '.config');
28
+ return join(configHome, 'zenmcp', 'credentials.json');
29
+ }
30
+ export async function readSavedCredential(options = {}) {
31
+ const filePath = resolveCredentialsPath(options);
32
+ if (!filePath)
33
+ return null;
34
+ let raw;
35
+ try {
36
+ raw = await readFile(filePath, 'utf8');
37
+ }
38
+ catch {
39
+ return null;
40
+ }
41
+ try {
42
+ const parsed = JSON.parse(raw);
43
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed))
44
+ return null;
45
+ const record = parsed;
46
+ const token = typeof record.token === 'string' ? record.token.trim() : '';
47
+ if (!token || /[\r\n\0]/.test(token))
48
+ return null;
49
+ const updatedAt = typeof record.updated_at === 'string' ? record.updated_at : undefined;
50
+ return {
51
+ token,
52
+ ...(updatedAt !== undefined ? { updated_at: updatedAt } : {}),
53
+ path: filePath,
54
+ };
55
+ }
56
+ catch {
57
+ return null;
58
+ }
59
+ }
60
+ export async function hasSavedCredential(options = {}) {
61
+ return (await readSavedCredential(options)) !== null;
62
+ }
63
+ export async function saveCredential(rawToken, options = {}) {
64
+ const token = rawToken.trim();
65
+ if (!token || /[\r\n\0]/.test(token)) {
66
+ throw new Error('empty_or_invalid_token');
67
+ }
68
+ const filePath = resolveCredentialsPath(options);
69
+ if (!filePath) {
70
+ throw new Error('credentials_path_disabled');
71
+ }
72
+ const os = options.platform ?? platform();
73
+ const isWindows = os === 'win32';
74
+ const dir = dirname(filePath);
75
+ await mkdir(dir, { recursive: true, mode: 0o700 });
76
+ if (!isWindows) {
77
+ await chmod(dir, 0o700).catch(() => undefined);
78
+ }
79
+ const updatedAt = new Date().toISOString();
80
+ const payload = {
81
+ version: 1,
82
+ token,
83
+ updated_at: updatedAt,
84
+ };
85
+ const serialized = `${JSON.stringify(payload, null, 2)}\n`;
86
+ const tmpPath = `${filePath}.tmp-${process.pid}-${randomBytes(6).toString('hex')}`;
87
+ const handle = await open(tmpPath, 'wx', 0o600);
88
+ try {
89
+ await handle.writeFile(serialized, 'utf8');
90
+ await handle.sync();
91
+ }
92
+ finally {
93
+ await handle.close();
94
+ }
95
+ if (!isWindows) {
96
+ await chmod(tmpPath, 0o600);
97
+ }
98
+ try {
99
+ await rename(tmpPath, filePath);
100
+ }
101
+ catch (error) {
102
+ await rm(tmpPath, { force: true }).catch(() => undefined);
103
+ throw error;
104
+ }
105
+ if (!isWindows) {
106
+ await chmod(filePath, 0o600).catch(() => undefined);
107
+ }
108
+ return { path: filePath, updated_at: updatedAt };
109
+ }
110
+ export async function clearCredential(options = {}) {
111
+ const filePath = resolveCredentialsPath(options);
112
+ if (!filePath)
113
+ return { removed: false, path: null };
114
+ const existing = await readSavedCredential(options);
115
+ await rm(filePath, { force: true });
116
+ return { removed: existing !== null, path: filePath };
117
+ }
118
+ export function createDefaultTokenProvider(options = {}) {
119
+ const resolveEnvToken = () => {
120
+ const captured = options.capturedEnvToken?.trim();
121
+ if (captured)
122
+ return captured;
123
+ const live = (options.env ?? process.env).ZENMCP_TOKEN?.trim();
124
+ return live || undefined;
125
+ };
126
+ return {
127
+ async token() {
128
+ const envToken = resolveEnvToken();
129
+ if (envToken)
130
+ return envToken;
131
+ const saved = await readSavedCredential(options);
132
+ if (saved)
133
+ return saved.token;
134
+ throw new Error('token_missing');
135
+ },
136
+ async source() {
137
+ if (resolveEnvToken())
138
+ return 'env';
139
+ const saved = await readSavedCredential(options);
140
+ return saved ? 'file' : 'none';
141
+ },
142
+ async inspect() {
143
+ const envToken = resolveEnvToken();
144
+ const saved = await readSavedCredential(options);
145
+ const hasEnv = Boolean(envToken);
146
+ const hasFile = Boolean(saved);
147
+ const source = hasEnv ? 'env' : hasFile ? 'file' : 'none';
148
+ return {
149
+ source,
150
+ hasEnv,
151
+ hasFile,
152
+ envOverridesFile: Boolean(envToken && saved && envToken !== saved.token),
153
+ credentialsPath: resolveCredentialsPath(options),
154
+ };
155
+ },
156
+ };
157
+ }