@yivan-lab/pretty-please 1.1.0 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/README.md +390 -1
  2. package/bin/pls.tsx +1255 -123
  3. package/dist/bin/pls.js +1098 -103
  4. package/dist/package.json +4 -4
  5. package/dist/src/alias.d.ts +41 -0
  6. package/dist/src/alias.js +240 -0
  7. package/dist/src/chat-history.js +10 -1
  8. package/dist/src/components/Chat.js +54 -26
  9. package/dist/src/components/CodeColorizer.js +26 -20
  10. package/dist/src/components/CommandBox.js +19 -8
  11. package/dist/src/components/ConfirmationPrompt.js +2 -1
  12. package/dist/src/components/Duration.js +2 -1
  13. package/dist/src/components/InlineRenderer.js +2 -1
  14. package/dist/src/components/MarkdownDisplay.js +2 -1
  15. package/dist/src/components/MultiStepCommandGenerator.d.ts +3 -1
  16. package/dist/src/components/MultiStepCommandGenerator.js +20 -10
  17. package/dist/src/components/TableRenderer.js +2 -1
  18. package/dist/src/config.d.ts +33 -3
  19. package/dist/src/config.js +83 -34
  20. package/dist/src/mastra-agent.d.ts +1 -0
  21. package/dist/src/mastra-agent.js +3 -11
  22. package/dist/src/mastra-chat.d.ts +13 -6
  23. package/dist/src/mastra-chat.js +31 -31
  24. package/dist/src/multi-step.d.ts +23 -7
  25. package/dist/src/multi-step.js +45 -26
  26. package/dist/src/prompts.d.ts +30 -4
  27. package/dist/src/prompts.js +218 -70
  28. package/dist/src/remote-history.d.ts +63 -0
  29. package/dist/src/remote-history.js +315 -0
  30. package/dist/src/remote.d.ts +113 -0
  31. package/dist/src/remote.js +634 -0
  32. package/dist/src/shell-hook.d.ts +58 -0
  33. package/dist/src/shell-hook.js +295 -26
  34. package/dist/src/ui/theme.d.ts +60 -23
  35. package/dist/src/ui/theme.js +544 -22
  36. package/dist/src/upgrade.d.ts +41 -0
  37. package/dist/src/upgrade.js +348 -0
  38. package/dist/src/utils/console.d.ts +4 -0
  39. package/dist/src/utils/console.js +89 -17
  40. package/package.json +4 -4
  41. package/src/alias.ts +301 -0
  42. package/src/chat-history.ts +11 -1
  43. package/src/components/Chat.tsx +71 -26
  44. package/src/components/CodeColorizer.tsx +27 -19
  45. package/src/components/CommandBox.tsx +26 -8
  46. package/src/components/ConfirmationPrompt.tsx +2 -1
  47. package/src/components/Duration.tsx +2 -1
  48. package/src/components/InlineRenderer.tsx +2 -1
  49. package/src/components/MarkdownDisplay.tsx +2 -1
  50. package/src/components/MultiStepCommandGenerator.tsx +25 -11
  51. package/src/components/TableRenderer.tsx +2 -1
  52. package/src/config.ts +126 -35
  53. package/src/mastra-agent.ts +3 -12
  54. package/src/mastra-chat.ts +40 -34
  55. package/src/multi-step.ts +62 -30
  56. package/src/prompts.ts +236 -78
  57. package/src/remote-history.ts +390 -0
  58. package/src/remote.ts +800 -0
  59. package/src/shell-hook.ts +339 -26
  60. package/src/ui/theme.ts +632 -23
  61. package/src/upgrade.ts +397 -0
  62. package/src/utils/console.ts +99 -17
package/dist/bin/pls.js CHANGED
@@ -1,46 +1,99 @@
1
1
  #!/usr/bin/env node
2
- import React from 'react';
3
- import { render } from 'ink';
4
2
  import { Command } from 'commander';
5
3
  import { fileURLToPath } from 'url';
6
4
  import { dirname, join } from 'path';
5
+ import path from 'path';
7
6
  import { exec } from 'child_process';
7
+ import fs from 'fs';
8
8
  import os from 'os';
9
9
  import chalk from 'chalk';
10
- import { MultiStepCommandGenerator } from '../src/components/MultiStepCommandGenerator.js';
11
- import { Chat } from '../src/components/Chat.js';
10
+ // React Ink 懒加载(只在需要 UI 时加载)
11
+ // import React from 'react'
12
+ // import { render } from 'ink'
13
+ // import { MultiStepCommandGenerator } from '../src/components/MultiStepCommandGenerator.js'
14
+ // import { Chat } from '../src/components/Chat.js'
12
15
  import { isConfigValid, setConfigValue, getConfig, maskApiKey } from '../src/config.js';
13
16
  import { clearHistory, addHistory, getHistory, getHistoryFilePath } from '../src/history.js';
14
17
  import { clearChatHistory, getChatRoundCount, getChatHistoryFilePath, displayChatHistory } from '../src/chat-history.js';
15
18
  import { installShellHook, uninstallShellHook, getHookStatus, detectShell, getShellConfigPath, displayShellHistory, clearShellHistory, } from '../src/shell-hook.js';
19
+ import { checkForUpdates, showUpdateNotice, performUpgrade, } from '../src/upgrade.js';
20
+ import { getCurrentTheme } from '../src/ui/theme.js';
21
+ import { addAlias, removeAlias, displayAliases, resolveAlias, } from '../src/alias.js';
22
+ import { addRemote, removeRemote, displayRemotes, getRemote, testRemoteConnection, sshExec, collectRemoteSysInfo, setRemoteWorkDir, getRemoteWorkDir, generateBatchRemoteCommands, executeBatchRemoteCommands, } from '../src/remote.js';
23
+ import { addRemoteHistory, displayRemoteHistory, clearRemoteHistory, fetchRemoteShellHistory, displayRemoteShellHistory, clearRemoteShellHistory, } from '../src/remote-history.js';
24
+ import { detectRemoteShell, getRemoteShellConfigPath, installRemoteShellHook, uninstallRemoteShellHook, getRemoteHookStatus, } from '../src/shell-hook.js';
25
+ // 获取主题颜色的辅助函数
26
+ function getThemeColors() {
27
+ const theme = getCurrentTheme();
28
+ return {
29
+ primary: theme.primary,
30
+ success: theme.success,
31
+ error: theme.error,
32
+ warning: theme.warning,
33
+ info: theme.info,
34
+ muted: theme.text.muted,
35
+ secondary: theme.text.secondary,
36
+ };
37
+ }
16
38
  import * as console2 from '../src/utils/console.js';
17
39
  // 导入 package.json(Bun 会自动打包进二进制)
18
- import packageJson from '../package.json';
40
+ import packageJson from '../package.json' with { type: 'json' };
19
41
  // 保留这些用于其他可能的用途
20
42
  const __filename = fileURLToPath(import.meta.url);
21
43
  const __dirname = dirname(__filename);
22
44
  const program = new Command();
45
+ // 启动时异步检查更新(不阻塞主流程)
46
+ let updateCheckResult = null;
47
+ const isUpgradeCommand = process.argv.includes('upgrade');
48
+ // 延迟更新检查到命令解析后(减少启动时间)
49
+ // 非 upgrade 命令时才检查更新
50
+ if (!isUpgradeCommand) {
51
+ // 延迟 100ms 开始检查,避免影响简单命令的响应速度
52
+ setTimeout(() => {
53
+ checkForUpdates(packageJson.version)
54
+ .then((result) => {
55
+ updateCheckResult = result;
56
+ })
57
+ .catch(() => {
58
+ // 静默失败
59
+ });
60
+ }, 100);
61
+ }
62
+ // 程序退出时显示更新提示
63
+ process.on('beforeExit', () => {
64
+ if (updateCheckResult?.hasUpdate && updateCheckResult.latestVersion && !isUpgradeCommand) {
65
+ showUpdateNotice(packageJson.version, updateCheckResult.latestVersion);
66
+ }
67
+ });
23
68
  /**
24
69
  * 执行命令(原生版本)
25
70
  */
26
71
  function executeCommand(command) {
27
72
  return new Promise((resolve) => {
28
- let output = '';
73
+ let stdout = '';
74
+ let stderr = '';
29
75
  let hasOutput = false;
30
76
  console.log(''); // 空行
31
- // 计算命令框宽度,让分隔线长度一致
77
+ // 计算命令框宽度,让分隔线长度一致(限制终端宽度)
78
+ const termWidth = process.stdout.columns || 80;
79
+ const maxContentWidth = termWidth - 6;
32
80
  const lines = command.split('\n');
33
- const maxContentWidth = Math.max(...lines.map(l => console2.getDisplayWidth(l)));
34
- const boxWidth = Math.max(maxContentWidth + 4, console2.getDisplayWidth('生成命令') + 6, 20);
81
+ const wrappedLines = [];
82
+ for (const line of lines) {
83
+ wrappedLines.push(...console2.wrapText(line, maxContentWidth));
84
+ }
85
+ const actualMaxWidth = Math.max(...wrappedLines.map((l) => console2.getDisplayWidth(l)), console2.getDisplayWidth('生成命令'));
86
+ const boxWidth = Math.min(actualMaxWidth + 4, termWidth - 2);
35
87
  console2.printSeparator('输出', boxWidth);
36
- const child = exec(command);
88
+ // 使用 bash 并启用 pipefail,确保管道中任何命令失败都能正确返回非零退出码
89
+ const child = exec(`set -o pipefail; ${command}`, { shell: '/bin/bash' });
37
90
  child.stdout?.on('data', (data) => {
38
- output += data;
91
+ stdout += data;
39
92
  hasOutput = true;
40
93
  process.stdout.write(data);
41
94
  });
42
95
  child.stderr?.on('data', (data) => {
43
- output += data;
96
+ stderr += data;
44
97
  hasOutput = true;
45
98
  process.stderr.write(data);
46
99
  });
@@ -48,7 +101,7 @@ function executeCommand(command) {
48
101
  if (hasOutput) {
49
102
  console2.printSeparator('', boxWidth);
50
103
  }
51
- resolve({ exitCode: code || 0, output });
104
+ resolve({ exitCode: code || 0, output: stdout + stderr, stdout, stderr });
52
105
  });
53
106
  child.on('error', (err) => {
54
107
  if (!hasOutput) {
@@ -56,7 +109,7 @@ function executeCommand(command) {
56
109
  }
57
110
  console2.error(err.message);
58
111
  console2.printSeparator('', boxWidth);
59
- resolve({ exitCode: 1, output: err.message });
112
+ resolve({ exitCode: 1, output: err.message, stdout: '', stderr: err.message });
60
113
  });
61
114
  });
62
115
  }
@@ -65,7 +118,8 @@ program
65
118
  .name('pls')
66
119
  .description('AI 驱动的命令行工具,将自然语言转换为可执行的 Shell 命令')
67
120
  .version(packageJson.version, '-v, --version', '显示版本号')
68
- .helpOption('-h, --help', '显示帮助信息');
121
+ .helpOption('-h, --help', '显示帮助信息')
122
+ .allowUnknownOption(true); // 允许未知选项(用于别名参数传递)
69
123
  // config 子命令
70
124
  const configCmd = program.command('config').description('管理配置');
71
125
  configCmd
@@ -78,15 +132,16 @@ configCmd
78
132
  console.log('');
79
133
  console2.title('当前配置:');
80
134
  console2.muted('━'.repeat(50));
81
- console.log(` ${chalk.hex('#00D9FF')('apiKey')}: ${maskApiKey(config.apiKey)}`);
82
- console.log(` ${chalk.hex('#00D9FF')('baseUrl')}: ${config.baseUrl}`);
83
- console.log(` ${chalk.hex('#00D9FF')('provider')}: ${config.provider}`);
84
- console.log(` ${chalk.hex('#00D9FF')('model')}: ${config.model}`);
85
- console.log(` ${chalk.hex('#00D9FF')('shellHook')}: ${config.shellHook ? chalk.hex('#10B981')('已启用') : chalk.gray('未启用')}`);
86
- console.log(` ${chalk.hex('#00D9FF')('editMode')}: ${config.editMode === 'auto' ? chalk.hex('#00D9FF')('auto (自动编辑)') : chalk.gray('manual (按E编辑)')}`);
87
- console.log(` ${chalk.hex('#00D9FF')('chatHistoryLimit')}: ${config.chatHistoryLimit} 轮`);
88
- console.log(` ${chalk.hex('#00D9FF')('commandHistoryLimit')}: ${config.commandHistoryLimit} 条`);
89
- console.log(` ${chalk.hex('#00D9FF')('shellHistoryLimit')}: ${config.shellHistoryLimit} 条`);
135
+ console.log(` ${chalk.hex(getThemeColors().primary)('apiKey')}: ${maskApiKey(config.apiKey)}`);
136
+ console.log(` ${chalk.hex(getThemeColors().primary)('baseUrl')}: ${config.baseUrl}`);
137
+ console.log(` ${chalk.hex(getThemeColors().primary)('provider')}: ${config.provider}`);
138
+ console.log(` ${chalk.hex(getThemeColors().primary)('model')}: ${config.model}`);
139
+ console.log(` ${chalk.hex(getThemeColors().primary)('shellHook')}: ${config.shellHook ? chalk.hex(getThemeColors().success)('已启用') : chalk.gray('未启用')}`);
140
+ console.log(` ${chalk.hex(getThemeColors().primary)('editMode')}: ${config.editMode === 'auto' ? chalk.hex(getThemeColors().primary)('auto (自动编辑)') : chalk.gray('manual (按E编辑)')}`);
141
+ console.log(` ${chalk.hex(getThemeColors().primary)('chatHistoryLimit')}: ${config.chatHistoryLimit} 轮`);
142
+ console.log(` ${chalk.hex(getThemeColors().primary)('commandHistoryLimit')}: ${config.commandHistoryLimit} 条`);
143
+ console.log(` ${chalk.hex(getThemeColors().primary)('shellHistoryLimit')}: ${config.shellHistoryLimit} 条`);
144
+ console.log(` ${chalk.hex(getThemeColors().primary)('theme')}: ${config.theme === 'dark' ? chalk.hex(getThemeColors().primary)('dark (深色)') : chalk.hex(getThemeColors().primary)('light (浅色)')}`);
90
145
  console2.muted('━'.repeat(50));
91
146
  console2.muted(`配置文件: ${CONFIG_FILE}`);
92
147
  console.log('');
@@ -94,11 +149,18 @@ configCmd
94
149
  configCmd
95
150
  .command('set <key> <value>')
96
151
  .description('设置配置项 (apiKey, baseUrl, provider, model, shellHook, chatHistoryLimit)')
97
- .action((key, value) => {
152
+ .action(async (key, value) => {
98
153
  try {
154
+ const oldConfig = getConfig();
155
+ const oldShellHistoryLimit = oldConfig.shellHistoryLimit;
99
156
  setConfigValue(key, value);
100
157
  console.log('');
101
158
  console2.success(`已设置 ${key}`);
159
+ // 如果修改了 shellHistoryLimit,自动重装 hook
160
+ if (key === 'shellHistoryLimit') {
161
+ const { reinstallHookForLimitChange } = await import('../src/shell-hook.js');
162
+ await reinstallHookForLimitChange(oldShellHistoryLimit, Number(value));
163
+ }
102
164
  console.log('');
103
165
  }
104
166
  catch (error) {
@@ -113,6 +175,240 @@ configCmd.action(async () => {
113
175
  const { runConfigWizard } = await import('../src/config.js');
114
176
  await runConfigWizard();
115
177
  });
178
+ // theme 子命令
179
+ const themeCmd = program.command('theme').description('管理主题');
180
+ themeCmd
181
+ .command('list')
182
+ .description('查看所有可用主题')
183
+ .option('--custom', '只显示自定义主题')
184
+ .option('--builtin', '只显示内置主题')
185
+ .action(async (options) => {
186
+ const { getAllThemeMetadata, isBuiltinTheme } = await import('../src/ui/theme.js');
187
+ const config = getConfig();
188
+ const currentTheme = config.theme || 'dark';
189
+ console.log('');
190
+ console2.title('🎨 可用主题:');
191
+ console2.muted('━'.repeat(50));
192
+ // 动态获取所有主题元数据
193
+ const allThemes = getAllThemeMetadata();
194
+ // 根据选项过滤主题
195
+ const builtinThemes = allThemes.filter((meta) => isBuiltinTheme(meta.name));
196
+ const customThemes = allThemes.filter((meta) => !isBuiltinTheme(meta.name));
197
+ // 显示内置主题
198
+ if (!options.custom) {
199
+ if (builtinThemes.length > 0) {
200
+ console.log('');
201
+ console2.info('内置主题:');
202
+ builtinThemes.forEach((meta) => {
203
+ const isCurrent = meta.name === currentTheme;
204
+ const prefix = isCurrent ? '●' : '○';
205
+ const label = `${meta.name} (${meta.displayName})`;
206
+ if (isCurrent) {
207
+ console.log(` ${chalk.hex(meta.previewColor)(prefix)} ${chalk.hex(meta.previewColor).bold(label)} ${chalk.gray('(当前)')}`);
208
+ }
209
+ else {
210
+ console.log(` ${chalk.gray(prefix)} ${label}`);
211
+ }
212
+ });
213
+ }
214
+ }
215
+ // 显示自定义主题
216
+ if (!options.builtin) {
217
+ if (customThemes.length > 0) {
218
+ console.log('');
219
+ console2.info('自定义主题:');
220
+ customThemes.forEach((meta) => {
221
+ const isCurrent = meta.name === currentTheme;
222
+ const prefix = isCurrent ? '●' : '○';
223
+ const label = `${meta.name} (${meta.displayName})`;
224
+ const emoji = ' ✨';
225
+ if (isCurrent) {
226
+ console.log(` ${chalk.hex(meta.previewColor)(prefix)} ${chalk.hex(meta.previewColor).bold(label)}${emoji} ${chalk.gray('(当前)')}`);
227
+ }
228
+ else {
229
+ console.log(` ${chalk.gray(prefix)} ${label}${emoji}`);
230
+ }
231
+ });
232
+ }
233
+ else if (options.custom) {
234
+ console.log('');
235
+ console2.muted(' 还没有自定义主题');
236
+ console2.muted(' 使用 pls theme create <name> 创建');
237
+ }
238
+ }
239
+ console.log('');
240
+ console2.muted('━'.repeat(50));
241
+ console.log('');
242
+ });
243
+ themeCmd
244
+ .argument('[name]', '主题名称')
245
+ .description('切换主题')
246
+ .action(async (name) => {
247
+ const { getThemeMetadata, getAllThemeMetadata, isValidTheme } = await import('../src/ui/theme.js');
248
+ if (!name) {
249
+ // 显示当前主题
250
+ const config = getConfig();
251
+ const currentTheme = config.theme || 'dark';
252
+ const meta = getThemeMetadata(currentTheme);
253
+ if (meta) {
254
+ console.log('');
255
+ console.log(`当前主题: ${chalk.hex(meta.previewColor).bold(`${meta.name} (${meta.displayName})`)}`);
256
+ if (meta.description) {
257
+ console2.muted(` ${meta.description}`);
258
+ }
259
+ console.log('');
260
+ }
261
+ console2.muted('使用 pls theme list 查看所有主题');
262
+ console2.muted('使用 pls theme <name> 切换主题');
263
+ console.log('');
264
+ return;
265
+ }
266
+ // 切换主题
267
+ try {
268
+ // 验证主题是否存在
269
+ if (!isValidTheme(name)) {
270
+ const allThemes = getAllThemeMetadata();
271
+ const themeNames = allThemes.map((m) => m.name).join(', ');
272
+ throw new Error(`未知主题 "${name}",可用主题: ${themeNames}`);
273
+ }
274
+ setConfigValue('theme', name);
275
+ const meta = getThemeMetadata(name);
276
+ if (meta) {
277
+ console.log('');
278
+ console2.success(`已切换到 ${chalk.hex(meta.previewColor).bold(`${meta.name} (${meta.displayName})`)} 主题`);
279
+ if (meta.description) {
280
+ console2.muted(` ${meta.description}`);
281
+ }
282
+ console.log('');
283
+ }
284
+ }
285
+ catch (error) {
286
+ console.log('');
287
+ console2.error(error.message);
288
+ console.log('');
289
+ process.exit(1);
290
+ }
291
+ });
292
+ // theme create - 创建主题模板
293
+ themeCmd
294
+ .command('create <name>')
295
+ .description('创建自定义主题模板')
296
+ .option('-d, --display-name <name>', '显示名称')
297
+ .option('-c, --category <type>', '主题类别 (dark 或 light)', 'dark')
298
+ .action(async (name, options) => {
299
+ const { createThemeTemplate } = await import('../src/ui/theme.js');
300
+ try {
301
+ // 验证主题名称格式
302
+ if (!/^[a-z0-9-]+$/.test(name)) {
303
+ throw new Error('主题名称只能包含小写字母、数字和连字符');
304
+ }
305
+ // 验证类别
306
+ const category = options.category;
307
+ if (category !== 'dark' && category !== 'light') {
308
+ throw new Error('主题类别必须是 dark 或 light');
309
+ }
310
+ // 创建主题目录
311
+ const themesDir = path.join(os.homedir(), '.please', 'themes');
312
+ if (!fs.existsSync(themesDir)) {
313
+ fs.mkdirSync(themesDir, { recursive: true });
314
+ }
315
+ // 检查主题文件是否已存在
316
+ const themePath = path.join(themesDir, `${name}.json`);
317
+ if (fs.existsSync(themePath)) {
318
+ throw new Error(`主题 "${name}" 已存在`);
319
+ }
320
+ // 创建主题模板
321
+ const displayName = options.displayName || name;
322
+ const template = createThemeTemplate(name, displayName, category);
323
+ // 保存到文件
324
+ fs.writeFileSync(themePath, JSON.stringify(template, null, 2), 'utf-8');
325
+ // 显示成功信息
326
+ console.log('');
327
+ console2.success(`已创建主题模板: ${themePath}`);
328
+ console.log('');
329
+ console2.info('📝 下一步:');
330
+ console.log(` 1. 编辑主题文件修改颜色配置`);
331
+ console2.muted(` vim ${themePath}`);
332
+ console.log('');
333
+ console.log(` 2. 验证主题格式`);
334
+ console2.muted(` pls theme validate ${themePath}`);
335
+ console.log('');
336
+ console.log(` 3. 应用主题查看效果`);
337
+ console2.muted(` pls theme ${name}`);
338
+ console.log('');
339
+ console2.info('💡 提示:');
340
+ console2.muted(' - 使用在线工具选择颜色: https://colorhunt.co');
341
+ console2.muted(' - 参考内置主题: pls theme list');
342
+ console.log('');
343
+ }
344
+ catch (error) {
345
+ console.log('');
346
+ console2.error(error.message);
347
+ console.log('');
348
+ process.exit(1);
349
+ }
350
+ });
351
+ // theme validate - 验证主题文件
352
+ themeCmd
353
+ .command('validate <file>')
354
+ .description('验证主题文件格式')
355
+ .action(async (file) => {
356
+ const { validateThemeWithDetails } = await import('../src/ui/theme.js');
357
+ try {
358
+ // 读取主题文件
359
+ const themePath = path.isAbsolute(file) ? file : path.join(process.cwd(), file);
360
+ if (!fs.existsSync(themePath)) {
361
+ throw new Error(`文件不存在: ${themePath}`);
362
+ }
363
+ const content = fs.readFileSync(themePath, 'utf-8');
364
+ const theme = JSON.parse(content);
365
+ // 验证主题
366
+ const result = validateThemeWithDetails(theme);
367
+ console.log('');
368
+ if (result.valid) {
369
+ console2.success('✓ 主题验证通过');
370
+ console.log('');
371
+ if (theme.metadata) {
372
+ console2.info('主题信息:');
373
+ console.log(` 名称: ${theme.metadata.name} (${theme.metadata.displayName})`);
374
+ console.log(` 类别: ${theme.metadata.category}`);
375
+ if (theme.metadata.description) {
376
+ console.log(` 描述: ${theme.metadata.description}`);
377
+ }
378
+ if (theme.metadata.author) {
379
+ console.log(` 作者: ${theme.metadata.author}`);
380
+ }
381
+ }
382
+ console.log('');
383
+ }
384
+ else {
385
+ console2.error('✗ 主题验证失败');
386
+ console.log('');
387
+ console2.info('错误列表:');
388
+ result.errors.forEach((err, idx) => {
389
+ console.log(` ${idx + 1}. ${err}`);
390
+ });
391
+ console.log('');
392
+ console2.info('修复建议:');
393
+ console2.muted(` 1. 编辑主题文件: vim ${themePath}`);
394
+ console2.muted(' 2. 参考内置主题格式');
395
+ console2.muted(' 3. 确保所有颜色使用 #RRGGBB 格式');
396
+ console.log('');
397
+ process.exit(1);
398
+ }
399
+ }
400
+ catch (error) {
401
+ console.log('');
402
+ if (error.message.includes('Unexpected token')) {
403
+ console2.error('JSON 格式错误,请检查文件语法');
404
+ }
405
+ else {
406
+ console2.error(error.message);
407
+ }
408
+ console.log('');
409
+ process.exit(1);
410
+ }
411
+ });
116
412
  // history 子命令
117
413
  const historyCmd = program.command('history').description('查看或管理命令历史');
118
414
  historyCmd
@@ -132,14 +428,14 @@ historyCmd
132
428
  history.forEach((item, index) => {
133
429
  const status = item.executed
134
430
  ? item.exitCode === 0
135
- ? chalk.hex('#10B981')('✓')
136
- : chalk.hex('#EF4444')(`✗ 退出码:${item.exitCode}`)
431
+ ? chalk.hex(getThemeColors().success)('✓')
432
+ : chalk.hex(getThemeColors().error)(`✗ 退出码:${item.exitCode}`)
137
433
  : chalk.gray('(未执行)');
138
- console.log(`\n${chalk.gray(`${index + 1}.`)} ${chalk.hex('#00D9FF')(item.userPrompt)}`);
434
+ console.log(`\n${chalk.gray(`${index + 1}.`)} ${chalk.hex(getThemeColors().primary)(item.userPrompt)}`);
139
435
  // 显示用户修改信息
140
436
  if (item.userModified && item.aiGeneratedCommand) {
141
437
  console.log(` ${chalk.dim('AI 生成:')} ${chalk.gray(item.aiGeneratedCommand)}`);
142
- console.log(` ${chalk.dim('用户修改为:')} ${item.command} ${status} ${chalk.yellow('(已修改)')}`);
438
+ console.log(` ${chalk.dim('用户修改为:')} ${item.command} ${status} ${chalk.hex(getThemeColors().warning)('(已修改)')}`);
143
439
  }
144
440
  else {
145
441
  console.log(` ${chalk.dim('→')} ${item.command} ${status}`);
@@ -199,14 +495,14 @@ historyCmd.action(() => {
199
495
  history.forEach((item, index) => {
200
496
  const status = item.executed
201
497
  ? item.exitCode === 0
202
- ? chalk.hex('#10B981')('✓')
203
- : chalk.hex('#EF4444')(`✗ 退出码:${item.exitCode}`)
498
+ ? chalk.hex(getThemeColors().success)('✓')
499
+ : chalk.hex(getThemeColors().error)(`✗ 退出码:${item.exitCode}`)
204
500
  : chalk.gray('(未执行)');
205
- console.log(`\n${chalk.gray(`${index + 1}.`)} ${chalk.hex('#00D9FF')(item.userPrompt)}`);
501
+ console.log(`\n${chalk.gray(`${index + 1}.`)} ${chalk.hex(getThemeColors().primary)(item.userPrompt)}`);
206
502
  // 显示用户修改信息
207
503
  if (item.userModified && item.aiGeneratedCommand) {
208
504
  console.log(` ${chalk.dim('AI 生成:')} ${chalk.gray(item.aiGeneratedCommand)}`);
209
- console.log(` ${chalk.dim('用户修改为:')} ${item.command} ${status} ${chalk.yellow('(已修改)')}`);
505
+ console.log(` ${chalk.dim('用户修改为:')} ${item.command} ${status} ${chalk.hex(getThemeColors().warning)('(已修改)')}`);
210
506
  }
211
507
  else {
212
508
  console.log(` ${chalk.dim('→')} ${item.command} ${status}`);
@@ -265,11 +561,11 @@ hookCmd
265
561
  console.log('');
266
562
  console2.title('📊 Shell Hook 状态');
267
563
  console2.muted('━'.repeat(40));
268
- console.log(` ${chalk.hex('#00D9FF')('Shell 类型')}: ${status.shellType}`);
269
- console.log(` ${chalk.hex('#00D9FF')('配置文件')}: ${status.configPath || '未知'}`);
270
- console.log(` ${chalk.hex('#00D9FF')('已安装')}: ${status.installed ? chalk.hex('#10B981')('是') : chalk.gray('否')}`);
271
- console.log(` ${chalk.hex('#00D9FF')('已启用')}: ${status.enabled ? chalk.hex('#10B981')('是') : chalk.gray('否')}`);
272
- console.log(` ${chalk.hex('#00D9FF')('历史文件')}: ${status.historyFile}`);
564
+ console.log(` ${chalk.hex(getThemeColors().primary)('Shell 类型')}: ${status.shellType}`);
565
+ console.log(` ${chalk.hex(getThemeColors().primary)('配置文件')}: ${status.configPath || '未知'}`);
566
+ console.log(` ${chalk.hex(getThemeColors().primary)('已安装')}: ${status.installed ? chalk.hex(getThemeColors().success)('是') : chalk.gray('否')}`);
567
+ console.log(` ${chalk.hex(getThemeColors().primary)('已启用')}: ${status.enabled ? chalk.hex(getThemeColors().success)('是') : chalk.gray('否')}`);
568
+ console.log(` ${chalk.hex(getThemeColors().primary)('历史文件')}: ${status.historyFile}`);
273
569
  console2.muted('━'.repeat(40));
274
570
  if (!status.installed) {
275
571
  console.log('');
@@ -283,11 +579,11 @@ hookCmd.action(() => {
283
579
  console.log('');
284
580
  console2.title('📊 Shell Hook 状态');
285
581
  console2.muted('━'.repeat(40));
286
- console.log(` ${chalk.hex('#00D9FF')('Shell 类型')}: ${status.shellType}`);
287
- console.log(` ${chalk.hex('#00D9FF')('配置文件')}: ${status.configPath || '未知'}`);
288
- console.log(` ${chalk.hex('#00D9FF')('已安装')}: ${status.installed ? chalk.hex('#10B981')('是') : chalk.gray('否')}`);
289
- console.log(` ${chalk.hex('#00D9FF')('已启用')}: ${status.enabled ? chalk.hex('#10B981')('是') : chalk.gray('否')}`);
290
- console.log(` ${chalk.hex('#00D9FF')('历史文件')}: ${status.historyFile}`);
582
+ console.log(` ${chalk.hex(getThemeColors().primary)('Shell 类型')}: ${status.shellType}`);
583
+ console.log(` ${chalk.hex(getThemeColors().primary)('配置文件')}: ${status.configPath || '未知'}`);
584
+ console.log(` ${chalk.hex(getThemeColors().primary)('已安装')}: ${status.installed ? chalk.hex(getThemeColors().success)('是') : chalk.gray('否')}`);
585
+ console.log(` ${chalk.hex(getThemeColors().primary)('已启用')}: ${status.enabled ? chalk.hex(getThemeColors().success)('是') : chalk.gray('否')}`);
586
+ console.log(` ${chalk.hex(getThemeColors().primary)('历史文件')}: ${status.historyFile}`);
291
587
  console2.muted('━'.repeat(40));
292
588
  if (!status.installed) {
293
589
  console.log('');
@@ -295,22 +591,400 @@ hookCmd.action(() => {
295
591
  }
296
592
  console.log('');
297
593
  });
298
- // chat 子命令
299
- const chatCmd = program.command('chat').description('AI 对话模式,问答、讲解命令');
300
- chatCmd
301
- .command('clear')
302
- .description('清空对话历史')
594
+ // upgrade 子命令
595
+ program
596
+ .command('upgrade')
597
+ .description('升级到最新版本')
598
+ .action(async () => {
599
+ const success = await performUpgrade(packageJson.version);
600
+ process.exit(success ? 0 : 1);
601
+ });
602
+ // alias 子命令
603
+ const aliasCmd = program.command('alias').description('管理命令别名');
604
+ // 获取所有子命令名称(用于检测冲突)
605
+ function getReservedCommands() {
606
+ return program.commands.map((cmd) => cmd.name());
607
+ }
608
+ aliasCmd
609
+ .command('list')
610
+ .description('列出所有别名')
303
611
  .action(() => {
304
- clearChatHistory();
612
+ displayAliases();
613
+ });
614
+ aliasCmd
615
+ .command('add <name> <prompt>')
616
+ .description('添加别名(prompt 支持 {{param}} 或 {{param:default}} 参数模板)')
617
+ .option('-d, --description <desc>', '别名描述')
618
+ .action((name, prompt, options) => {
619
+ try {
620
+ addAlias(name, prompt, options.description, getReservedCommands());
621
+ console.log('');
622
+ console2.success(`已添加别名: ${name}`);
623
+ console.log(` ${chalk.gray('→')} ${prompt}`);
624
+ console.log('');
625
+ }
626
+ catch (error) {
627
+ console.log('');
628
+ console2.error(error.message);
629
+ console.log('');
630
+ process.exit(1);
631
+ }
632
+ });
633
+ aliasCmd
634
+ .command('remove <name>')
635
+ .description('删除别名')
636
+ .action((name) => {
637
+ const removed = removeAlias(name);
305
638
  console.log('');
306
- console2.success('对话历史已清空');
639
+ if (removed) {
640
+ console2.success(`已删除别名: ${name}`);
641
+ }
642
+ else {
643
+ console2.error(`别名不存在: ${name}`);
644
+ }
307
645
  console.log('');
308
646
  });
309
- // 默认 chat 命令(进行对话)
310
- chatCmd
311
- .argument('[prompt...]', '你的问题')
647
+ // 默认 alias 命令(显示列表)
648
+ aliasCmd.action(() => {
649
+ displayAliases();
650
+ });
651
+ // remote 子命令
652
+ const remoteCmd = program.command('remote').description('管理远程服务器');
653
+ remoteCmd
654
+ .command('list')
655
+ .description('列出所有远程服务器')
656
+ .action(() => {
657
+ displayRemotes();
658
+ });
659
+ remoteCmd
660
+ .command('add <name> <host>')
661
+ .description('添加远程服务器(格式: user@host 或 user@host:port)')
662
+ .option('-k, --key <path>', 'SSH 私钥路径')
663
+ .option('-p, --password', '使用密码认证(每次执行时输入)')
664
+ .action((name, host, options) => {
665
+ try {
666
+ addRemote(name, host, { key: options.key, password: options.password });
667
+ console.log('');
668
+ console2.success(`已添加远程服务器: ${name}`);
669
+ console.log(` ${chalk.gray('→')} ${host}`);
670
+ if (options.key) {
671
+ console.log(` ${chalk.gray('密钥:')} ${options.key}`);
672
+ }
673
+ if (options.password) {
674
+ console.log(` ${chalk.gray('认证:')} 密码(每次执行时输入)`);
675
+ }
676
+ console.log('');
677
+ }
678
+ catch (error) {
679
+ console.log('');
680
+ console2.error(error.message);
681
+ console.log('');
682
+ process.exit(1);
683
+ }
684
+ });
685
+ remoteCmd
686
+ .command('remove <name>')
687
+ .description('删除远程服务器')
688
+ .action((name) => {
689
+ const removed = removeRemote(name);
690
+ console.log('');
691
+ if (removed) {
692
+ console2.success(`已删除远程服务器: ${name}`);
693
+ }
694
+ else {
695
+ console2.error(`远程服务器不存在: ${name}`);
696
+ }
697
+ console.log('');
698
+ });
699
+ remoteCmd
700
+ .command('test <name>')
701
+ .description('测试远程服务器连接')
702
+ .action(async (name) => {
703
+ const remote = getRemote(name);
704
+ if (!remote) {
705
+ console.log('');
706
+ console2.error(`远程服务器不存在: ${name}`);
707
+ console.log('');
708
+ process.exit(1);
709
+ }
710
+ console.log('');
711
+ console2.info(`正在测试连接 ${name} (${remote.user}@${remote.host}:${remote.port})...`);
712
+ const result = await testRemoteConnection(name);
713
+ console.log(` ${result.message}`);
714
+ if (result.success) {
715
+ // 采集系统信息
716
+ console2.info('正在采集系统信息...');
717
+ try {
718
+ const sysInfo = await collectRemoteSysInfo(name, true);
719
+ console.log(` ${chalk.gray('系统:')} ${sysInfo.os} ${sysInfo.osVersion}`);
720
+ console.log(` ${chalk.gray('Shell:')} ${sysInfo.shell}`);
721
+ console.log(` ${chalk.gray('主机名:')} ${sysInfo.hostname}`);
722
+ }
723
+ catch (error) {
724
+ console2.warning(`无法采集系统信息: ${error.message}`);
725
+ }
726
+ }
727
+ console.log('');
728
+ });
729
+ // remote hook 子命令
730
+ const remoteHookCmd = remoteCmd.command('hook').description('管理远程服务器 Shell Hook');
731
+ remoteHookCmd
732
+ .command('install <name>')
733
+ .description('在远程服务器安装 Shell Hook')
734
+ .action(async (name) => {
735
+ const remote = getRemote(name);
736
+ if (!remote) {
737
+ console.log('');
738
+ console2.error(`远程服务器不存在: ${name}`);
739
+ console.log('');
740
+ process.exit(1);
741
+ }
742
+ console.log('');
743
+ console2.title('🔧 远程 Shell Hook 安装');
744
+ console2.muted('━'.repeat(40));
745
+ console2.info(`目标服务器: ${name} (${remote.user}@${remote.host})`);
746
+ try {
747
+ // 检测远程 shell 类型
748
+ const sshExecFn = async (cmd) => {
749
+ const result = await sshExec(name, cmd, { timeout: 30000 });
750
+ return { stdout: result.stdout, exitCode: result.exitCode };
751
+ };
752
+ const shellType = await detectRemoteShell(sshExecFn);
753
+ const configPath = getRemoteShellConfigPath(shellType);
754
+ console2.muted(`检测到 Shell: ${shellType}`);
755
+ console2.muted(`配置文件: ${configPath}`);
756
+ console.log('');
757
+ const result = await installRemoteShellHook(sshExecFn, shellType);
758
+ console.log(` ${result.message}`);
759
+ if (result.success) {
760
+ console.log('');
761
+ console2.warning('⚠️ 请在远程服务器重启终端或执行:');
762
+ console2.info(` source ${configPath}`);
763
+ }
764
+ }
765
+ catch (error) {
766
+ console2.error(`安装失败: ${error.message}`);
767
+ }
768
+ console.log('');
769
+ });
770
+ remoteHookCmd
771
+ .command('uninstall <name>')
772
+ .description('从远程服务器卸载 Shell Hook')
773
+ .action(async (name) => {
774
+ const remote = getRemote(name);
775
+ if (!remote) {
776
+ console.log('');
777
+ console2.error(`远程服务器不存在: ${name}`);
778
+ console.log('');
779
+ process.exit(1);
780
+ }
781
+ console.log('');
782
+ console2.info(`正在从 ${name} 卸载 Shell Hook...`);
783
+ try {
784
+ const sshExecFn = async (cmd) => {
785
+ const result = await sshExec(name, cmd, { timeout: 30000 });
786
+ return { stdout: result.stdout, exitCode: result.exitCode };
787
+ };
788
+ const shellType = await detectRemoteShell(sshExecFn);
789
+ const result = await uninstallRemoteShellHook(sshExecFn, shellType);
790
+ console.log(` ${result.message}`);
791
+ if (result.success) {
792
+ console.log('');
793
+ console2.warning('⚠️ 请在远程服务器重启终端使其生效');
794
+ }
795
+ }
796
+ catch (error) {
797
+ console2.error(`卸载失败: ${error.message}`);
798
+ }
799
+ console.log('');
800
+ });
801
+ remoteHookCmd
802
+ .command('status <name>')
803
+ .description('查看远程服务器 Shell Hook 状态')
804
+ .action(async (name) => {
805
+ const remote = getRemote(name);
806
+ if (!remote) {
807
+ console.log('');
808
+ console2.error(`远程服务器不存在: ${name}`);
809
+ console.log('');
810
+ process.exit(1);
811
+ }
812
+ console.log('');
813
+ console2.info(`正在检查 ${name} 的 Hook 状态...`);
814
+ try {
815
+ const sshExecFn = async (cmd) => {
816
+ const result = await sshExec(name, cmd, { timeout: 30000 });
817
+ return { stdout: result.stdout, exitCode: result.exitCode };
818
+ };
819
+ const status = await getRemoteHookStatus(sshExecFn);
820
+ console.log('');
821
+ console2.title(`📊 远程 Shell Hook 状态 - ${name}`);
822
+ console2.muted('━'.repeat(40));
823
+ console.log(` ${chalk.hex(getThemeColors().primary)('Shell 类型')}: ${status.shellType}`);
824
+ console.log(` ${chalk.hex(getThemeColors().primary)('配置文件')}: ${status.configPath}`);
825
+ console.log(` ${chalk.hex(getThemeColors().primary)('已安装')}: ${status.installed ? chalk.hex(getThemeColors().success)('是') : chalk.gray('否')}`);
826
+ console2.muted('━'.repeat(40));
827
+ if (!status.installed) {
828
+ console.log('');
829
+ console2.muted(`提示: 运行 pls remote hook install ${name} 安装 Shell Hook`);
830
+ }
831
+ }
832
+ catch (error) {
833
+ console2.error(`检查失败: ${error.message}`);
834
+ }
835
+ console.log('');
836
+ });
837
+ // remote history 子命令
838
+ const remoteHistoryCmd = remoteCmd.command('history').description('管理远程服务器历史记录');
839
+ remoteHistoryCmd
840
+ .command('show <name>')
841
+ .description('显示远程服务器命令历史')
842
+ .action((name) => {
843
+ displayRemoteHistory(name);
844
+ });
845
+ remoteHistoryCmd
846
+ .command('clear <name>')
847
+ .description('清空远程服务器命令历史')
848
+ .action((name) => {
849
+ clearRemoteHistory(name);
850
+ console.log('');
851
+ console2.success(`已清空服务器 "${name}" 的命令历史`);
852
+ console.log('');
853
+ });
854
+ remoteHistoryCmd
855
+ .command('shell <name>')
856
+ .description('显示远程服务器 Shell 历史')
857
+ .action(async (name) => {
858
+ await displayRemoteShellHistory(name);
859
+ });
860
+ remoteHistoryCmd
861
+ .command('shell-clear <name>')
862
+ .description('清空远程服务器 Shell 历史')
863
+ .action(async (name) => {
864
+ await clearRemoteShellHistory(name);
865
+ });
866
+ // remote default 子命令
867
+ remoteCmd
868
+ .command('default [name]')
869
+ .description('设置或查看默认远程服务器')
870
+ .option('-c, --clear', '清除默认服务器设置')
871
+ .action((name, options) => {
872
+ const config = getConfig();
873
+ // 清除默认
874
+ if (options?.clear) {
875
+ if (config.defaultRemote) {
876
+ setConfigValue('defaultRemote', '');
877
+ console.log('');
878
+ console2.success('已清除默认远程服务器');
879
+ console.log('');
880
+ }
881
+ else {
882
+ console.log('');
883
+ console2.muted('当前没有设置默认远程服务器');
884
+ console.log('');
885
+ }
886
+ return;
887
+ }
888
+ // 查看默认
889
+ if (!name) {
890
+ console.log('');
891
+ if (config.defaultRemote) {
892
+ const remote = getRemote(config.defaultRemote);
893
+ if (remote) {
894
+ console.log(`默认远程服务器: ${chalk.hex(getThemeColors().primary)(config.defaultRemote)}`);
895
+ console.log(` ${chalk.gray('→')} ${remote.user}@${remote.host}:${remote.port}`);
896
+ }
897
+ else {
898
+ console2.warning(`默认服务器 "${config.defaultRemote}" 不存在,建议清除设置`);
899
+ console2.muted('运行 pls remote default --clear 清除');
900
+ }
901
+ }
902
+ else {
903
+ console2.muted('当前没有设置默认远程服务器');
904
+ console2.muted('使用 pls remote default <name> 设置默认服务器');
905
+ }
906
+ console.log('');
907
+ return;
908
+ }
909
+ // 设置默认
910
+ const remote = getRemote(name);
911
+ if (!remote) {
912
+ console.log('');
913
+ console2.error(`远程服务器不存在: ${name}`);
914
+ console2.muted('使用 pls remote list 查看所有服务器');
915
+ console.log('');
916
+ process.exit(1);
917
+ }
918
+ setConfigValue('defaultRemote', name);
919
+ console.log('');
920
+ console2.success(`已设置默认远程服务器: ${name}`);
921
+ console.log(` ${chalk.gray('→')} ${remote.user}@${remote.host}:${remote.port}`);
922
+ console2.muted('现在可以使用 pls -r <prompt> 直接在该服务器执行');
923
+ console.log('');
924
+ });
925
+ // remote workdir 子命令
926
+ remoteCmd
927
+ .command('workdir <name> [path]')
928
+ .description('设置或查看远程服务器的工作目录')
929
+ .option('-c, --clear', '清除工作目录设置')
930
+ .action((name, workdirPath, options) => {
931
+ const remote = getRemote(name);
932
+ if (!remote) {
933
+ console.log('');
934
+ console2.error(`远程服务器不存在: ${name}`);
935
+ console.log('');
936
+ process.exit(1);
937
+ }
938
+ // 清除工作目录
939
+ if (options?.clear) {
940
+ if (remote.workDir) {
941
+ setRemoteWorkDir(name, '-');
942
+ console.log('');
943
+ console2.success(`已清除 ${name} 的工作目录设置`);
944
+ console.log('');
945
+ }
946
+ else {
947
+ console.log('');
948
+ console2.muted(`${name} 没有设置工作目录`);
949
+ console.log('');
950
+ }
951
+ return;
952
+ }
953
+ // 查看工作目录
954
+ if (!workdirPath) {
955
+ console.log('');
956
+ if (remote.workDir) {
957
+ console.log(`${chalk.hex(getThemeColors().primary)(name)} 的工作目录:`);
958
+ console.log(` ${chalk.gray('→')} ${remote.workDir}`);
959
+ }
960
+ else {
961
+ console2.muted(`${name} 没有设置工作目录`);
962
+ console2.muted(`使用 pls remote workdir ${name} <path> 设置工作目录`);
963
+ }
964
+ console.log('');
965
+ return;
966
+ }
967
+ // 设置工作目录
968
+ setRemoteWorkDir(name, workdirPath);
969
+ console.log('');
970
+ console2.success(`已设置 ${name} 的工作目录: ${workdirPath}`);
971
+ console2.muted('现在在该服务器执行的命令会自动切换到此目录');
972
+ console.log('');
973
+ });
974
+ // 默认 remote 命令(显示列表)
975
+ remoteCmd.action(() => {
976
+ displayRemotes();
977
+ });
978
+ // chat 命令(AI 对话)
979
+ program
980
+ .command('chat')
981
+ .description('AI 对话模式,问答、讲解命令')
982
+ .argument('[prompt...]', '你的问题(不提供则显示状态)')
312
983
  .option('-d, --debug', '显示调试信息')
313
984
  .action((promptArgs, options) => {
985
+ // Workaround: Commander.js 14.x 的子命令 option 解析有 bug
986
+ // 直接从 process.argv 检查 --debug
987
+ const debug = process.argv.includes('--debug') || process.argv.includes('-d');
314
988
  const prompt = promptArgs.join(' ');
315
989
  if (!prompt.trim()) {
316
990
  // 没有输入,显示对话状态
@@ -319,13 +993,13 @@ chatCmd
319
993
  console.log('');
320
994
  console2.title('💬 AI 对话模式');
321
995
  console2.muted('━'.repeat(40));
322
- console.log(` ${chalk.hex('#00D9FF')('当前对话轮数')}: ${roundCount}`);
323
- console.log(` ${chalk.hex('#00D9FF')('历史文件')}: ${historyFile}`);
996
+ console.log(` ${chalk.hex(getThemeColors().primary)('当前对话轮数')}: ${roundCount}`);
997
+ console.log(` ${chalk.hex(getThemeColors().primary)('历史文件')}: ${historyFile}`);
324
998
  console2.muted('━'.repeat(40));
325
999
  console.log('');
326
1000
  console2.muted('用法:');
327
- console2.info(' pls chat <问题> 与 AI 对话');
328
- console2.info(' pls chat clear 清空对话历史');
1001
+ console2.info(' pls chat <问题> 与 AI 对话');
1002
+ console2.info(' pls history chat clear 清空对话历史');
329
1003
  console.log('');
330
1004
  return;
331
1005
  }
@@ -337,19 +1011,37 @@ chatCmd
337
1011
  console.log('');
338
1012
  process.exit(1);
339
1013
  }
340
- // 使用 Ink 渲染对话(Chat 适合用 Ink 流式输出)
341
- render(React.createElement(Chat, { prompt: prompt, debug: options.debug, showRoundCount: true, onComplete: () => process.exit(0) }));
1014
+ // 懒加载 Chat 组件(避免启动时加载 React/Ink
1015
+ ;
1016
+ (async () => {
1017
+ const React = await import('react');
1018
+ const { render } = await import('ink');
1019
+ const { Chat } = await import('../src/components/Chat.js');
1020
+ render(React.createElement(Chat, {
1021
+ prompt,
1022
+ debug: debug, // 使用 debug 变量
1023
+ showRoundCount: true,
1024
+ onComplete: () => process.exit(0),
1025
+ }));
1026
+ })();
342
1027
  });
343
1028
  // 默认命令(执行 prompt)
344
1029
  program
345
1030
  .argument('[prompt...]', '自然语言描述你想执行的操作')
346
1031
  .option('-d, --debug', '显示调试信息(系统信息、完整 prompt 等)')
1032
+ .option('-r, --remote [name]', '在远程服务器上执行(不指定则使用默认服务器)')
347
1033
  .action((promptArgs, options) => {
1034
+ // 智能处理 -r 参数:如果 -r 后面的值不是已注册的服务器名,把它当作 prompt 的一部分
1035
+ if (typeof options.remote === 'string' && !getRemote(options.remote)) {
1036
+ // "查看当前目录" 不是服务器名,放回 prompt
1037
+ promptArgs.unshift(options.remote);
1038
+ options.remote = true; // 改为使用默认服务器
1039
+ }
348
1040
  if (promptArgs.length === 0) {
349
1041
  program.help();
350
1042
  return;
351
1043
  }
352
- const prompt = promptArgs.join(' ');
1044
+ let prompt = promptArgs.join(' ');
353
1045
  if (!prompt.trim()) {
354
1046
  console.log('');
355
1047
  console2.error('请提供你想执行的操作描述');
@@ -357,6 +1049,23 @@ program
357
1049
  console.log('');
358
1050
  process.exit(1);
359
1051
  }
1052
+ // 尝试解析别名(支持 pls disk 和 pls @disk 两种格式)
1053
+ try {
1054
+ const aliasResult = resolveAlias(prompt);
1055
+ if (aliasResult.resolved) {
1056
+ prompt = aliasResult.prompt;
1057
+ if (options.debug) {
1058
+ console.log('');
1059
+ console2.muted(`别名解析: ${aliasResult.aliasName} → ${prompt}`);
1060
+ }
1061
+ }
1062
+ }
1063
+ catch (error) {
1064
+ console.log('');
1065
+ console2.error(error.message);
1066
+ console.log('');
1067
+ process.exit(1);
1068
+ }
360
1069
  // 检查配置
361
1070
  if (!isConfigValid()) {
362
1071
  console.log('');
@@ -365,39 +1074,226 @@ program
365
1074
  console.log('');
366
1075
  process.exit(1);
367
1076
  }
368
- // 使用多步骤命令生成器(统一处理单步和多步)
1077
+ // 解析远程服务器名称
1078
+ // options.remote 可能是:
1079
+ // - undefined: 没有使用 -r
1080
+ // - true: 使用了 -r 但没有指定名称(使用默认)
1081
+ // - string: 使用了 -r 并指定了名称(支持逗号分隔的多个服务器)
1082
+ let remoteName;
1083
+ let remoteNames; // 批量执行时的服务器列表
1084
+ if (options.remote !== undefined) {
1085
+ if (options.remote === true) {
1086
+ // 使用默认服务器
1087
+ const config = getConfig();
1088
+ if (!config.defaultRemote) {
1089
+ console.log('');
1090
+ console2.error('未设置默认远程服务器');
1091
+ console2.muted('使用 pls remote default <name> 设置默认服务器');
1092
+ console2.muted('或使用 pls -r <name> <prompt> 指定服务器');
1093
+ console.log('');
1094
+ process.exit(1);
1095
+ }
1096
+ remoteName = config.defaultRemote;
1097
+ }
1098
+ else {
1099
+ // 检查是否为批量执行(逗号分隔的服务器名)
1100
+ if (options.remote.includes(',')) {
1101
+ remoteNames = options.remote.split(',').map(s => s.trim()).filter(s => s.length > 0);
1102
+ // 验证所有服务器是否存在
1103
+ const invalidServers = remoteNames.filter(name => !getRemote(name));
1104
+ if (invalidServers.length > 0) {
1105
+ console.log('');
1106
+ console2.error(`以下服务器不存在: ${invalidServers.join(', ')}`);
1107
+ console2.muted('使用 pls remote list 查看所有服务器');
1108
+ console2.muted('使用 pls remote add <name> <user@host> 添加服务器');
1109
+ console.log('');
1110
+ process.exit(1);
1111
+ }
1112
+ }
1113
+ else {
1114
+ remoteName = options.remote;
1115
+ // 检查服务器是否存在
1116
+ const remote = getRemote(remoteName);
1117
+ if (!remote) {
1118
+ console.log('');
1119
+ console2.error(`远程服务器不存在: ${remoteName}`);
1120
+ console2.muted('使用 pls remote add <name> <user@host> 添加服务器');
1121
+ console.log('');
1122
+ process.exit(1);
1123
+ }
1124
+ }
1125
+ }
1126
+ }
1127
+ // 懒加载 MultiStepCommandGenerator 组件(避免启动时加载 React/Ink)
369
1128
  ;
370
1129
  (async () => {
1130
+ // 批量远程执行模式
1131
+ if (remoteNames && remoteNames.length > 0) {
1132
+ console.log('');
1133
+ console2.info(`正在为 ${remoteNames.length} 台服务器生成命令...`);
1134
+ console.log('');
1135
+ try {
1136
+ // 1. 并发生成命令
1137
+ const commands = await generateBatchRemoteCommands(remoteNames, prompt, { debug: options.debug });
1138
+ // 2. 显示生成的命令
1139
+ console2.success('✓ 命令生成完成\n');
1140
+ const theme = getCurrentTheme();
1141
+ commands.forEach(({ server, command, sysInfo }) => {
1142
+ console.log(chalk.hex(theme.primary)(`${server}`) + chalk.gray(` (${sysInfo.os}):`));
1143
+ console.log(chalk.hex(theme.secondary)(` ${command}`));
1144
+ });
1145
+ console.log('');
1146
+ // 3. 询问用户确认
1147
+ const readline = await import('readline');
1148
+ const rl = readline.createInterface({
1149
+ input: process.stdin,
1150
+ output: process.stdout,
1151
+ });
1152
+ const confirmed = await new Promise((resolve) => {
1153
+ console.log(chalk.gray(`将在 ${remoteNames.length} 台服务器执行以上命令`));
1154
+ rl.question(chalk.gray('执行? [回车执行 / Ctrl+C 取消] '), (answer) => {
1155
+ rl.close();
1156
+ resolve(true);
1157
+ });
1158
+ });
1159
+ if (!confirmed) {
1160
+ console.log('');
1161
+ console2.muted('已取消执行');
1162
+ console.log('');
1163
+ process.exit(0);
1164
+ }
1165
+ // 4. 并发执行
1166
+ console.log('');
1167
+ console2.info('正在执行...');
1168
+ const results = await executeBatchRemoteCommands(commands);
1169
+ // 5. 显示执行结果摘要
1170
+ console.log('');
1171
+ console2.info('执行完成:\n');
1172
+ results.forEach(({ server, exitCode }) => {
1173
+ const icon = exitCode === 0 ? '✓' : '✗';
1174
+ const color = exitCode === 0 ? theme.success : theme.error;
1175
+ console.log(` ${chalk.hex(color)(icon)} ${server} ${chalk.gray(`(退出码: ${exitCode})`)}`);
1176
+ });
1177
+ // 6. 显示每个服务器的详细输出
1178
+ console.log('');
1179
+ results.forEach(({ server, output }) => {
1180
+ console.log(chalk.hex(theme.primary)(`─── ${server} ───`));
1181
+ console.log(output || chalk.gray('(无输出)'));
1182
+ });
1183
+ // 7. 记录到历史
1184
+ results.forEach(({ server, command, exitCode, output }) => {
1185
+ addRemoteHistory(server, {
1186
+ userPrompt: prompt,
1187
+ command,
1188
+ aiGeneratedCommand: command, // 批量执行无编辑功能
1189
+ userModified: false,
1190
+ executed: true,
1191
+ exitCode,
1192
+ output,
1193
+ });
1194
+ });
1195
+ // 8. 根据结果决定退出码
1196
+ const allSuccess = results.every(r => r.exitCode === 0);
1197
+ const allFailed = results.every(r => r.exitCode !== 0);
1198
+ if (allFailed) {
1199
+ process.exit(2); // 全部失败
1200
+ }
1201
+ else if (!allSuccess) {
1202
+ process.exit(1); // 部分失败
1203
+ }
1204
+ process.exit(0); // 全部成功
1205
+ }
1206
+ catch (error) {
1207
+ console.log('');
1208
+ console2.error(`批量执行失败: ${error.message}`);
1209
+ console.log('');
1210
+ process.exit(1);
1211
+ }
1212
+ return;
1213
+ }
1214
+ // 单服务器执行模式
1215
+ const React = await import('react');
1216
+ const { render } = await import('ink');
1217
+ const { MultiStepCommandGenerator } = await import('../src/components/MultiStepCommandGenerator.js');
1218
+ // 如果是远程模式,先获取远程上下文
1219
+ let remoteContext = null;
1220
+ if (remoteName) {
1221
+ console.log('');
1222
+ console2.info(`正在连接远程服务器 ${remoteName}...`);
1223
+ try {
1224
+ // 采集系统信息(使用缓存)
1225
+ const sysInfo = await collectRemoteSysInfo(remoteName);
1226
+ if (options.debug) {
1227
+ console2.muted(`系统: ${sysInfo.os} ${sysInfo.osVersion} (${sysInfo.shell})`);
1228
+ }
1229
+ // 获取远程 shell 历史
1230
+ const shellHistory = await fetchRemoteShellHistory(remoteName);
1231
+ if (options.debug && shellHistory.length > 0) {
1232
+ console2.muted(`Shell 历史: ${shellHistory.length} 条`);
1233
+ }
1234
+ remoteContext = { name: remoteName, sysInfo, shellHistory };
1235
+ console2.success(`已连接到 ${remoteName}`);
1236
+ }
1237
+ catch (error) {
1238
+ console2.error(`无法连接到 ${remoteName}: ${error.message}`);
1239
+ console.log('');
1240
+ process.exit(1);
1241
+ }
1242
+ }
371
1243
  const executedSteps = [];
372
1244
  let currentStepNumber = 1;
373
1245
  let lastStepFailed = false; // 跟踪上一步是否失败
374
1246
  while (true) {
375
1247
  let stepResult = null;
376
1248
  // 使用 Ink 渲染命令生成
377
- const { waitUntilExit, unmount } = render(React.createElement(MultiStepCommandGenerator, { prompt: prompt, debug: options.debug, previousSteps: executedSteps, currentStepNumber: currentStepNumber, onStepComplete: (res) => {
1249
+ const { waitUntilExit, unmount } = render(React.createElement(MultiStepCommandGenerator, {
1250
+ prompt,
1251
+ debug: options.debug,
1252
+ previousSteps: executedSteps,
1253
+ currentStepNumber,
1254
+ remoteContext: remoteContext ? {
1255
+ name: remoteContext.name,
1256
+ sysInfo: remoteContext.sysInfo,
1257
+ shellHistory: remoteContext.shellHistory,
1258
+ } : undefined,
1259
+ isRemote: !!remoteName, // 远程执行时不检测 builtin
1260
+ onStepComplete: (res) => {
378
1261
  stepResult = res;
379
1262
  unmount();
380
- } }));
1263
+ },
1264
+ }));
381
1265
  await waitUntilExit();
382
1266
  await new Promise((resolve) => setTimeout(resolve, 10));
383
1267
  // 处理步骤结果
384
1268
  if (!stepResult || stepResult.cancelled) {
385
- console.log('');
386
- console2.muted('已取消执行');
387
- console.log('');
388
1269
  process.exit(0);
389
1270
  }
390
1271
  if (stepResult.hasBuiltin) {
391
- addHistory({
392
- userPrompt: currentStepNumber === 1 ? prompt : `[步骤${currentStepNumber}] ${prompt}`,
393
- command: stepResult.command,
394
- aiGeneratedCommand: stepResult.aiGeneratedCommand, // AI 原始命令
395
- userModified: stepResult.userModified || false,
396
- executed: false,
397
- exitCode: null,
398
- output: '',
399
- reason: 'builtin',
400
- });
1272
+ // 远程模式记录到远程历史
1273
+ if (remoteName) {
1274
+ addRemoteHistory(remoteName, {
1275
+ userPrompt: currentStepNumber === 1 ? prompt : `[步骤${currentStepNumber}] ${prompt}`,
1276
+ command: stepResult.command,
1277
+ aiGeneratedCommand: stepResult.aiGeneratedCommand,
1278
+ userModified: stepResult.userModified || false,
1279
+ executed: false,
1280
+ exitCode: null,
1281
+ output: '',
1282
+ reason: 'builtin',
1283
+ });
1284
+ }
1285
+ else {
1286
+ addHistory({
1287
+ userPrompt: currentStepNumber === 1 ? prompt : `[步骤${currentStepNumber}] ${prompt}`,
1288
+ command: stepResult.command,
1289
+ aiGeneratedCommand: stepResult.aiGeneratedCommand, // AI 原始命令
1290
+ userModified: stepResult.userModified || false,
1291
+ executed: false,
1292
+ exitCode: null,
1293
+ output: '',
1294
+ reason: 'builtin',
1295
+ });
1296
+ }
401
1297
  process.exit(0);
402
1298
  }
403
1299
  if (stepResult.confirmed) {
@@ -423,10 +1319,32 @@ program
423
1319
  console.log('');
424
1320
  process.exit(1);
425
1321
  }
426
- // 执行命令
1322
+ // 执行命令(本地或远程)
427
1323
  const execStart = Date.now();
428
- const { exitCode, output } = await executeCommand(stepResult.command);
1324
+ let exitCode;
1325
+ let output;
1326
+ let stdout;
1327
+ if (remoteName) {
1328
+ // 远程执行
1329
+ const result = await executeRemoteCommand(remoteName, stepResult.command);
1330
+ exitCode = result.exitCode;
1331
+ output = result.output;
1332
+ stdout = result.stdout;
1333
+ }
1334
+ else {
1335
+ // 本地执行
1336
+ const result = await executeCommand(stepResult.command);
1337
+ exitCode = result.exitCode;
1338
+ output = result.output;
1339
+ stdout = result.stdout;
1340
+ }
429
1341
  const execDuration = Date.now() - execStart;
1342
+ // 判断命令是否成功
1343
+ // 退出码 141 = 128 + 13 (SIGPIPE),是管道正常关闭时的信号
1344
+ // 例如:ps aux | head -3,head 读完 3 行就关闭管道,ps 收到 SIGPIPE
1345
+ // 但如果退出码是 141 且没有 stdout 输出,说明可能是真正的错误
1346
+ const isSigpipeWithOutput = exitCode === 141 && stdout.trim().length > 0;
1347
+ const isSuccess = exitCode === 0 || isSigpipeWithOutput;
430
1348
  // 保存到执行历史
431
1349
  const executedStep = {
432
1350
  command: stepResult.command,
@@ -437,19 +1355,32 @@ program
437
1355
  output,
438
1356
  };
439
1357
  executedSteps.push(executedStep);
440
- // 记录到 pls 历史
441
- addHistory({
442
- userPrompt: currentStepNumber === 1 ? prompt : `[步骤${currentStepNumber}] ${stepResult.reasoning || prompt}`,
443
- command: stepResult.command,
444
- aiGeneratedCommand: stepResult.aiGeneratedCommand, // AI 原始命令
445
- userModified: stepResult.userModified || false,
446
- executed: true,
447
- exitCode,
448
- output,
449
- });
1358
+ // 记录到 pls 历史(远程模式记录到远程历史)
1359
+ if (remoteName) {
1360
+ addRemoteHistory(remoteName, {
1361
+ userPrompt: currentStepNumber === 1 ? prompt : `[步骤${currentStepNumber}] ${stepResult.reasoning || prompt}`,
1362
+ command: stepResult.command,
1363
+ aiGeneratedCommand: stepResult.aiGeneratedCommand,
1364
+ userModified: stepResult.userModified || false,
1365
+ executed: true,
1366
+ exitCode,
1367
+ output,
1368
+ });
1369
+ }
1370
+ else {
1371
+ addHistory({
1372
+ userPrompt: currentStepNumber === 1 ? prompt : `[步骤${currentStepNumber}] ${stepResult.reasoning || prompt}`,
1373
+ command: stepResult.command,
1374
+ aiGeneratedCommand: stepResult.aiGeneratedCommand, // AI 原始命令
1375
+ userModified: stepResult.userModified || false,
1376
+ executed: true,
1377
+ exitCode,
1378
+ output,
1379
+ });
1380
+ }
450
1381
  // 显示结果
451
1382
  console.log('');
452
- if (exitCode === 0) {
1383
+ if (isSuccess) {
453
1384
  if (currentStepNumber === 1 && stepResult.needsContinue !== true) {
454
1385
  // 单步命令
455
1386
  console2.success(`执行完成 ${console2.formatDuration(execDuration)}`);
@@ -501,22 +1432,86 @@ program
501
1432
  }
502
1433
  })();
503
1434
  });
1435
+ /**
1436
+ * 执行远程命令
1437
+ * 如果设置了工作目录,自动添加 cd 前缀
1438
+ */
1439
+ async function executeRemoteCommand(remoteName, command) {
1440
+ let stdout = '';
1441
+ let stderr = '';
1442
+ // 如果有工作目录,自动添加 cd 前缀
1443
+ const workDir = getRemoteWorkDir(remoteName);
1444
+ const actualCommand = workDir ? `cd ${workDir} && ${command}` : command;
1445
+ console.log(''); // 空行
1446
+ // 计算命令框宽度,让分隔线长度一致(限制终端宽度)
1447
+ const termWidth = process.stdout.columns || 80;
1448
+ const maxContentWidth = termWidth - 6;
1449
+ const lines = command.split('\n');
1450
+ const wrappedLines = [];
1451
+ for (const line of lines) {
1452
+ wrappedLines.push(...console2.wrapText(line, maxContentWidth));
1453
+ }
1454
+ const actualMaxWidth = Math.max(...wrappedLines.map((l) => console2.getDisplayWidth(l)), console2.getDisplayWidth('生成命令'));
1455
+ const boxWidth = Math.min(actualMaxWidth + 4, termWidth - 2);
1456
+ console2.printSeparator(`远程输出 (${remoteName})`, boxWidth);
1457
+ try {
1458
+ const result = await sshExec(remoteName, actualCommand, {
1459
+ onStdout: (data) => {
1460
+ stdout += data;
1461
+ process.stdout.write(data);
1462
+ },
1463
+ onStderr: (data) => {
1464
+ stderr += data;
1465
+ process.stderr.write(data);
1466
+ },
1467
+ });
1468
+ if (stdout || stderr) {
1469
+ console2.printSeparator('', boxWidth);
1470
+ }
1471
+ return {
1472
+ exitCode: result.exitCode,
1473
+ output: stdout + stderr,
1474
+ stdout,
1475
+ stderr,
1476
+ };
1477
+ }
1478
+ catch (error) {
1479
+ console2.printSeparator('', boxWidth);
1480
+ console2.error(error.message);
1481
+ return {
1482
+ exitCode: 1,
1483
+ output: error.message,
1484
+ stdout: '',
1485
+ stderr: error.message,
1486
+ };
1487
+ }
1488
+ }
504
1489
  // 自定义帮助信息
505
1490
  program.addHelpText('after', `
506
1491
  ${chalk.bold('示例:')}
507
- ${chalk.hex('#00D9FF')('pls 安装 git')} 让 AI 生成安装 git 的命令
508
- ${chalk.hex('#00D9FF')('pls 查找大于 100MB 的文件')} 查找大文件
509
- ${chalk.hex('#00D9FF')('pls 删除刚才创建的文件')} AI 会参考历史记录
510
- ${chalk.hex('#00D9FF')('pls --debug 压缩 logs 目录')} 显示调试信息
511
- ${chalk.hex('#00D9FF')('pls -m 删除当前目录的空文件夹')} 多步骤模式(AI 自动规划)
512
- ${chalk.hex('#00D9FF')('pls chat tar 命令怎么用')} AI 对话模式
513
- ${chalk.hex('#00D9FF')('pls chat clear')} 清空对话历史
514
- ${chalk.hex('#00D9FF')('pls history')} 查看 pls 命令历史
515
- ${chalk.hex('#00D9FF')('pls history clear')} 清空历史记录
516
- ${chalk.hex('#00D9FF')('pls hook')} 查看 shell hook 状态
517
- ${chalk.hex('#00D9FF')('pls hook install')} 安装 shell hook(增强功能)
518
- ${chalk.hex('#00D9FF')('pls hook uninstall')} 卸载 shell hook
519
- ${chalk.hex('#00D9FF')('pls config')} 交互式配置
520
- ${chalk.hex('#00D9FF')('pls config list')} 查看当前配置
1492
+ ${chalk.hex(getThemeColors().primary)('pls 安装 git')} 让 AI 生成安装 git 的命令
1493
+ ${chalk.hex(getThemeColors().primary)('pls 查找大于 100MB 的文件')} 查找大文件
1494
+ ${chalk.hex(getThemeColors().primary)('pls 删除刚才创建的文件')} AI 会参考历史记录
1495
+ ${chalk.hex(getThemeColors().primary)('pls --debug 压缩 logs 目录')} 显示调试信息
1496
+ ${chalk.hex(getThemeColors().primary)('pls chat tar 命令怎么用')} AI 对话模式
1497
+ ${chalk.hex(getThemeColors().primary)('pls chat clear')} 清空对话历史
1498
+ ${chalk.hex(getThemeColors().primary)('pls history')} 查看 pls 命令历史
1499
+ ${chalk.hex(getThemeColors().primary)('pls history clear')} 清空历史记录
1500
+ ${chalk.hex(getThemeColors().primary)('pls alias')} 查看命令别名
1501
+ ${chalk.hex(getThemeColors().primary)('pls alias add disk "查看磁盘"')} 添加别名
1502
+ ${chalk.hex(getThemeColors().primary)('pls disk')} 使用别名(等同于 pls @disk)
1503
+ ${chalk.hex(getThemeColors().primary)('pls hook')} 查看 shell hook 状态
1504
+ ${chalk.hex(getThemeColors().primary)('pls hook install')} 安装 shell hook(增强功能)
1505
+ ${chalk.hex(getThemeColors().primary)('pls hook uninstall')} 卸载 shell hook
1506
+ ${chalk.hex(getThemeColors().primary)('pls upgrade')} 升级到最新版本
1507
+ ${chalk.hex(getThemeColors().primary)('pls config')} 交互式配置
1508
+ ${chalk.hex(getThemeColors().primary)('pls config list')} 查看当前配置
1509
+
1510
+ ${chalk.bold('远程执行:')}
1511
+ ${chalk.hex(getThemeColors().primary)('pls remote')} 查看远程服务器列表
1512
+ ${chalk.hex(getThemeColors().primary)('pls remote add myserver root@1.2.3.4')} 添加服务器
1513
+ ${chalk.hex(getThemeColors().primary)('pls remote test myserver')} 测试连接
1514
+ ${chalk.hex(getThemeColors().primary)('pls -r myserver 查看磁盘')} 在远程服务器执行
1515
+ ${chalk.hex(getThemeColors().primary)('pls remote hook install myserver')} 安装远程 Shell Hook
521
1516
  `);
522
1517
  program.parse();