huaweicloud-devkit 0.1.24 → 0.1.26-dev.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 (27) hide show
  1. package/README.md +5 -2
  2. package/integrations/opencode/opencode.json +1 -1
  3. package/integrations/opencode/skills/huaweicloud-core/SKILL.md +2 -0
  4. package/package.json +1 -1
  5. package/plugins/huaweicloud-core/.claude-plugin/plugin.json +43 -43
  6. package/plugins/huaweicloud-core/.codex-plugin/plugin.json +42 -42
  7. package/plugins/huaweicloud-core/.cursor-plugin/plugin.json +43 -43
  8. package/plugins/huaweicloud-core/.mcp.json +1 -1
  9. package/plugins/huaweicloud-core/hooks/huaweicloud-safety.py +48 -0
  10. package/plugins/huaweicloud-core/safety/rules/cloud-risk-rules.json +178 -0
  11. package/plugins/huaweicloud-core/skills/huawei-cloud-find-skills/SKILL.md +1 -1
  12. package/plugins/huaweicloud-core/skills/huawei-dds-dcs/SKILL.md +2 -2
  13. package/plugins/huaweicloud-core/skills/huawei-ecs/SKILL.md +4 -0
  14. package/plugins/huaweicloud-core/skills/huawei-ecs/references/create-instance.md +21 -6
  15. package/plugins/huaweicloud-core/skills/huawei-ecs/references/flavors.md +28 -1
  16. package/plugins/huaweicloud-core/skills/huawei-functiongraph/SKILL.md +0 -1
  17. package/plugins/huaweicloud-core/skills/huawei-functiongraph/references/triggers.md +1 -1
  18. package/plugins/huaweicloud-core/skills/huawei-getting-started/SKILL.md +2 -2
  19. package/plugins/huaweicloud-core/skills/huawei-obs/SKILL.md +2 -11
  20. package/plugins/huaweicloud-core/skills/huawei-vpc/SKILL.md +4 -1
  21. package/plugins/huaweicloud-core/skills/huaweicloud-cli-and-auth/SKILL.md +5 -5
  22. package/plugins/huaweicloud-core/skills/huaweicloud-safety/SKILL.md +14 -0
  23. package/plugins/huaweicloud-core/src/mcp-server.mjs +39 -14
  24. package/plugins/huaweicloud-core/src/risk-rule-engine.mjs +137 -0
  25. package/plugins/huaweicloud-core/src/safety-policy.mjs +26 -13
  26. package/plugins/huaweicloud-core/src/setup-cli.mjs +126 -65
  27. package/plugins/huaweicloud-core/src/tools.mjs +156 -1
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
 
3
- import { copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs';
3
+ import { copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from 'node:fs';
4
4
  import { join, dirname, resolve } from 'node:path';
5
5
  import { fileURLToPath } from 'node:url';
6
6
  import { homedir, platform } from 'node:os';
@@ -11,9 +11,14 @@ const __dirname = dirname(fileURLToPath(import.meta.url));
11
11
  const PLUGIN_ROOT = resolve(__dirname, '..');
12
12
  const PACKAGE_ROOT = resolve(PLUGIN_ROOT, '..', '..');
13
13
 
14
+ let pkgVersion = '0.0.0';
15
+ try {
16
+ pkgVersion = JSON.parse(readFileSync(join(PACKAGE_ROOT, 'package.json'), 'utf8')).version;
17
+ } catch {}
18
+
14
19
  const BANNER = `
15
20
  ╔══════════════════════════════════════════════╗
16
- ║ HuaweiCloud DevKit v0.1.0
21
+ ║ HuaweiCloud DevKit v${pkgVersion}${' '.repeat(Math.max(0, 22 - String(pkgVersion).length))}
17
22
  ║ https://github.com/huaweicloud-mate ║
18
23
  ╚══════════════════════════════════════════════╝
19
24
  `;
@@ -80,20 +85,6 @@ function printSandboxWarning(reason) {
80
85
  console.log(`\x1b[31m 关闭沙箱后重新运行: npx huaweicloud-devkit install-hcloud\x1b[0m`);
81
86
  }
82
87
 
83
- // Try to auto-accept the KooCLI privacy agreement by answering 'y' on stdin.
84
- // Returns true when hcloud runs without re-prompting for the agreement.
85
- function acceptKooCliPrivacy(hcloudBin) {
86
- const run = () => spawnSync(hcloudBin, ['version'], {
87
- encoding: 'utf8', timeout: 10000, windowsHide: true, input: 'y\n',
88
- });
89
- const first = run();
90
- const out = (first.stdout || '') + (first.stderr || '');
91
- if (!/同意并继续使用|agree/i.test(out)) return first.status === 0;
92
- const second = run();
93
- const out2 = (second.stdout || '') + (second.stderr || '');
94
- return second.status === 0 && !/同意并继续使用/.test(out2);
95
- }
96
-
97
88
  function checkNode() {
98
89
  const v = process.versions.node.split('.').map(Number);
99
90
  if (v[0] < 20) {
@@ -133,7 +124,7 @@ function updateOpenCodeConfig(pluginDir) {
133
124
  }
134
125
  const mcpPath = join(pluginDir, 'src', 'mcp-server.mjs').replace(/\\/g, '/');
135
126
  config.mcp = config.mcp || {};
136
- config.mcp.huaweicloud = {
127
+ config.mcp['huaweicloud-devkit'] = {
137
128
  type: 'local',
138
129
  command: ['node', mcpPath],
139
130
  enabled: true,
@@ -147,8 +138,8 @@ function removeOpenCodeConfig() {
147
138
  if (!existsSync(configPath)) return;
148
139
  let config = {};
149
140
  try { config = JSON.parse(readFileSync(configPath, 'utf8')); } catch { return; }
150
- if (!config.mcp?.huaweicloud) return;
151
- delete config.mcp.huaweicloud;
141
+ if (!config.mcp?.['huaweicloud-devkit']) return;
142
+ delete config.mcp['huaweicloud-devkit'];
152
143
  if (Object.keys(config.mcp).length === 0) delete config.mcp;
153
144
  writeFileSync(configPath, JSON.stringify(config, null, 2));
154
145
  console.log(` OpenCode MCP config cleaned: ${configPath}`);
@@ -156,14 +147,29 @@ function removeOpenCodeConfig() {
156
147
 
157
148
  function hasCodexCLI() {
158
149
  const r = spawnSync('codex --version', [], { shell: true, windowsHide: true, stdio: 'pipe' });
159
- return r.status === 0 && r.stdout && r.stdout.toString().includes('codex');
150
+ if (r.status === 0 && r.stdout && r.stdout.toString().includes('codex')) return true;
151
+ // WindowsApps codex.exe may fail with "Access is denied"
152
+ // Fallback: check if codex exists on PATH via where.exe
153
+ if (process.platform === 'win32') {
154
+ const w = spawnSync('where.exe', ['codex'], { windowsHide: true, stdio: 'pipe' });
155
+ if (w.status === 0 && w.stdout.toString().trim()) return true;
156
+ }
157
+ return false;
160
158
  }
161
159
 
162
160
  function checkHcloud() {
163
161
  const bin = findHcloudBin() || (process.env.HCLOUD_BIN || 'hcloud');
164
- const r = spawnSync(`"${bin}" version`, [], { shell: true, windowsHide: true, stdio: 'pipe', timeout: 5000, input: 'y\n' });
165
- const out = (r.stdout ? r.stdout.toString() : '') + (r.stderr ? r.stderr.toString() : '');
166
- return r.status === 0 && /KooCLI|Current.*version|当前KooCLI/i.test(out);
162
+ if (!existsSync(bin)) return false;
163
+ try {
164
+ if (statSync(bin).size < 1024) return false;
165
+ } catch { return false; }
166
+ try {
167
+ const r = spawnSync(`"${bin}" version`, [], { shell: true, windowsHide: true, stdio: 'pipe', timeout: 5000 });
168
+ const out = (r.stdout ? r.stdout.toString() : '') + (r.stderr ? r.stderr.toString() : '');
169
+ return r.status === 0 && /KooCLI|Current.*version|当前KooCLI/i.test(out);
170
+ } catch {
171
+ return false;
172
+ }
167
173
  }
168
174
 
169
175
  function getMarketplaceName() {
@@ -186,12 +192,25 @@ function installCodex() {
186
192
  });
187
193
  console.log(` ${r1.stdout ? r1.stdout.toString().trim() : r1.stderr.toString().trim()}`);
188
194
 
195
+ if (r1.status !== 0 && /Access is denied/i.test((r1.stderr || '').toString())) {
196
+ console.log(` \x1b[33mWindowsApps codex.exe permission denied.\x1b[0m`);
197
+ console.log(` \x1b[33mUse: npx huaweicloud-devkit install --target codex-desktop\x1b[0m`);
198
+ return false;
199
+ }
200
+
189
201
  console.log(` Installing plugin: ${pluginName}@${marketplaceName}`);
190
202
  const r2 = spawnSync(`codex plugin add "${pluginName}@${marketplaceName}"`, [], {
191
203
  shell: true, windowsHide: true, stdio: 'pipe',
192
204
  });
193
205
  console.log(` ${r2.stdout ? r2.stdout.toString().trim() : r2.stderr.toString().trim()}`);
194
- return r2.status === 0;
206
+
207
+ if (r2.status !== 0 && /Access is denied/i.test((r2.stderr || '').toString())) {
208
+ console.log(` \x1b[33mWindowsApps codex.exe permission denied.\x1b[0m`);
209
+ console.log(` \x1b[33mUse: npx huaweicloud-devkit install --target codex-desktop\x1b[0m`);
210
+ return false;
211
+ }
212
+
213
+ return true;
195
214
  }
196
215
 
197
216
  function uninstallCodex() {
@@ -276,6 +295,27 @@ async function installCodexDesktop() {
276
295
  copyDir(safetyDir, join(codexDesktopPluginsDir(), 'safety'));
277
296
  console.log(` Safety Policy -> ${join(codexDesktopPluginsDir(), 'safety')}`);
278
297
 
298
+ // Generate .mcp.json with absolute paths for Codex Desktop MCP server discovery
299
+ const mcpServerAbsPath = join(codexDesktopPluginsDir(), 'src', 'mcp-server.mjs').replace(/\\/g, '/');
300
+ const mcpConfig = {
301
+ mcpServers: {
302
+ 'huaweicloud-devkit': {
303
+ command: 'node',
304
+ args: [mcpServerAbsPath],
305
+ env: { HUAWEICLOUD_AGENT_TOOLKIT_MODE: 'local' },
306
+ },
307
+ },
308
+ };
309
+ writeFileSync(join(codexDesktopPluginsDir(), '.mcp.json'), JSON.stringify(mcpConfig, null, 2));
310
+ console.log(` MCP Config -> ${join(codexDesktopPluginsDir(), '.mcp.json')}`);
311
+
312
+ // Copy .codex-plugin manifest for Codex Desktop plugin registration
313
+ const codexPluginSrc = join(PLUGIN_ROOT, '.codex-plugin');
314
+ if (existsSync(codexPluginSrc)) {
315
+ copyDir(codexPluginSrc, join(codexDesktopPluginsDir(), '.codex-plugin'));
316
+ console.log(` Plugin Manifest -> ${join(codexDesktopPluginsDir(), '.codex-plugin')}`);
317
+ }
318
+
279
319
  const mcpPath = join(codexDesktopPluginsDir(), 'src', 'mcp-server.mjs').replace(/\\/g, '/');
280
320
  const configPath = codexDesktopConfigFile();
281
321
  let config = {};
@@ -283,7 +323,7 @@ async function installCodexDesktop() {
283
323
  try { config = JSON.parse(readFileSync(configPath, 'utf8')); } catch {}
284
324
  }
285
325
  config.mcp = config.mcp || {};
286
- config.mcp.huaweicloud = {
326
+ config.mcp['huaweicloud-devkit'] = {
287
327
  type: 'local',
288
328
  command: ['node', mcpPath],
289
329
  enabled: true,
@@ -324,8 +364,8 @@ function uninstallCodexDesktop() {
324
364
  if (existsSync(configPath)) {
325
365
  let config = {};
326
366
  try { config = JSON.parse(readFileSync(configPath, 'utf8')); } catch {}
327
- if (config.mcp?.huaweicloud) {
328
- delete config.mcp.huaweicloud;
367
+ if (config.mcp?.['huaweicloud-devkit']) {
368
+ delete config.mcp['huaweicloud-devkit'];
329
369
  if (Object.keys(config.mcp).length === 0) delete config.mcp;
330
370
  writeFileSync(configPath, JSON.stringify(config, null, 2));
331
371
  console.log(' Config cleaned');
@@ -343,7 +383,7 @@ function registerCodeartsMcp(configPath) {
343
383
  const env = { HUAWEICLOUD_AGENT_TOOLKIT_MODE: 'local' };
344
384
  const hcloudBin = findHcloudBin();
345
385
  if (hcloudBin) env.HCLOUD_BIN = hcloudBin.replace(/\\/g, '/');
346
- config.mcpServers.huaweicloud = {
386
+ config.mcpServers['huaweicloud-devkit'] = {
347
387
  command: 'node',
348
388
  args: [mcpPath],
349
389
  env,
@@ -394,8 +434,8 @@ function uninstallCodeArts() {
394
434
  if (!existsSync(configPath)) continue;
395
435
  let config = {};
396
436
  try { config = JSON.parse(readFileSync(configPath, 'utf8')); } catch {}
397
- if (config.mcpServers?.huaweicloud) {
398
- delete config.mcpServers.huaweicloud;
437
+ if (config.mcpServers?.['huaweicloud-devkit']) {
438
+ delete config.mcpServers['huaweicloud-devkit'];
399
439
  if (Object.keys(config.mcpServers).length === 0) delete config.mcpServers;
400
440
  writeFileSync(configPath, JSON.stringify(config, null, 2));
401
441
  console.log(` Config cleaned: ${configPath}`);
@@ -416,7 +456,7 @@ function codeartsStatus() {
416
456
  if (existsSync(codeartsMcpSettingsFile())) {
417
457
  try {
418
458
  const config = JSON.parse(readFileSync(codeartsMcpSettingsFile(), 'utf8'));
419
- console.log(` MCP config: ${config.mcpServers?.huaweicloud ? '\x1b[32mConfigured\x1b[0m' : '\x1b[31mNot configured\x1b[0m'}`);
459
+ console.log(` MCP config: ${config.mcpServers?.['huaweicloud-devkit'] ? '\x1b[32mConfigured\x1b[0m' : '\x1b[31mNot configured\x1b[0m'}`);
420
460
  } catch {
421
461
  console.log(` MCP config: \x1b[31mInvalid\x1b[0m`);
422
462
  }
@@ -438,7 +478,7 @@ function opencodeStatus() {
438
478
  if (existsSync(configPath)) {
439
479
  try {
440
480
  const config = JSON.parse(readFileSync(configPath, 'utf8'));
441
- console.log(` MCP config: ${config.mcp?.huaweicloud ? '\x1b[32mConfigured\x1b[0m' : '\x1b[31mNot configured\x1b[0m'}`);
481
+ console.log(` MCP config: ${config.mcp?.['huaweicloud-devkit'] ? '\x1b[32mConfigured\x1b[0m' : '\x1b[31mNot configured\x1b[0m'}`);
442
482
  } catch {
443
483
  console.log(` MCP config: \x1b[31mInvalid\x1b[0m`);
444
484
  }
@@ -478,18 +518,25 @@ async function cmdInstall() {
478
518
  console.log('\n[Codex]');
479
519
  if (!hasCodexCLI()) {
480
520
  if (target === 'codex') {
481
- console.log(` \x1b[31mCodex CLI not found. Install Codex first: https://github.com/openai/codex-cli\x1b[0m`);
482
- console.log(` Then re-run: npx huaweicloud-devkit install --target codex`);
521
+ console.log(` \x1b[31mCodex CLI not found.\x1b[0m`);
522
+ if (process.platform === 'win32') {
523
+ console.log(` \x1b[33mTip: Codex Desktop on Windows installs codex.exe under WindowsApps,\x1b[0m`);
524
+ console.log(` \x1b[33m which may fail with "Access is denied". Try instead:\x1b[0m`);
525
+ console.log(` \x1b[33m npx huaweicloud-devkit install --target codex-desktop\x1b[0m`);
526
+ }
527
+ console.log(` \x1b[31mOr install Codex CLI: https://github.com/openai/codex-cli\x1b[0m`);
483
528
  process.exit(1);
484
529
  }
485
530
  console.log(` \x1b[33mCodex CLI not found. Skipping Codex.\x1b[0m`);
486
- console.log(' Install Codex CLI to enable: npx huaweicloud-devkit install --target codex');
531
+ if (process.platform === 'win32') {
532
+ console.log(' \x1b[33mTip: try --target codex-desktop for Codex Desktop on Windows\x1b[0m');
533
+ } else {
534
+ console.log(' Install Codex CLI to enable: npx huaweicloud-devkit install --target codex');
535
+ }
487
536
  } else {
488
537
  installCodex();
489
538
  }
490
- }
491
-
492
- console.log(`\n\x1b[32mInstallation complete!\x1b[0m`);
539
+ } console.log(`\n\x1b[32mInstallation complete!\x1b[0m`);
493
540
  const appName = target === 'codearts' ? 'CodeArts'
494
541
  : target === 'codex-desktop' ? 'Codex Desktop'
495
542
  : target === 'codex' ? 'Codex' : 'OpenCode';
@@ -589,38 +636,45 @@ async function cmdDoctor() {
589
636
  // Node.js
590
637
  check('Node.js >= 20', process.versions.node.split('.')[0] >= 20, 'Run: nvm install 20 && nvm use 20');
591
638
 
592
- // OpenCode installed files
593
- const pluginDir = opencodePluginsDir();
594
- const mcpOk = existsSync(join(pluginDir, 'src', 'mcp-server.mjs'));
595
- check('MCP server installed', mcpOk, 'Run: npx huaweicloud-devkit-test install');
639
+ // MCP server — check OpenCode and Codex Desktop paths
640
+ const opencodePluginDir = opencodePluginsDir();
641
+ const codexPluginDir = codexDesktopPluginsDir();
642
+ const mcpOk = existsSync(join(opencodePluginDir, 'src', 'mcp-server.mjs'))
643
+ || existsSync(join(codexPluginDir, 'src', 'mcp-server.mjs'));
644
+ const mcpTarget = existsSync(join(opencodePluginDir, 'src', 'mcp-server.mjs')) ? 'OpenCode'
645
+ : existsSync(join(codexPluginDir, 'src', 'mcp-server.mjs')) ? 'Codex Desktop' : '';
646
+ check('MCP server installed', mcpOk, 'Run: npx huaweicloud-devkit install');
596
647
 
597
648
  if (mcpOk) {
598
- // Try to start MCP server briefly
599
- const test = spawnSync('node', [join(pluginDir, 'src', 'mcp-server.mjs')], {
600
- env: { ...process.env, HUAWEICLOUD_AGENT_TOOLKIT_MODE: 'local' },
601
- timeout: 3000, stdio: 'pipe', windowsHide: true,
602
- });
603
- // MCP server reads stdin for JSON-RPC, so it will hang briefly then get killed
604
- // We just check that the process spawned OK
605
- check('MCP server can start', true, '');
649
+ check(`MCP server can start (${mcpTarget})`, true, '');
606
650
  }
607
651
 
608
- const safetyOk = existsSync(join(pluginDir, 'safety', 'policy.json'));
609
- check('Safety policy installed', safetyOk, 'Run: npx huaweicloud-devkit-test install');
652
+ const safetyOk = existsSync(join(opencodePluginDir, 'safety', 'policy.json'))
653
+ || existsSync(join(codexPluginDir, 'safety', 'policy.json'));
654
+ check('Safety policy installed', safetyOk, 'Run: npx huaweicloud-devkit install');
610
655
 
611
- const opencodeCfg = opencodeConfigFile();
656
+ // MCP config — check OpenCode and Codex Desktop
612
657
  let mcpConfigured = false;
658
+ let mcpCfgTarget = '';
659
+ const opencodeCfg = opencodeConfigFile();
613
660
  if (existsSync(opencodeCfg)) {
614
661
  try {
615
662
  const cfg = JSON.parse(readFileSync(opencodeCfg, 'utf8'));
616
- mcpConfigured = !!(cfg.mcp && cfg.mcp.huaweicloud);
663
+ if (cfg.mcp && cfg.mcp['huaweicloud-devkit']) { mcpConfigured = true; mcpCfgTarget = 'OpenCode'; }
664
+ } catch {}
665
+ }
666
+ const codexCfg = codexDesktopConfigFile();
667
+ if (!mcpConfigured && existsSync(codexCfg)) {
668
+ try {
669
+ const cfg = JSON.parse(readFileSync(codexCfg, 'utf8'));
670
+ if (cfg.mcp && cfg.mcp['huaweicloud-devkit']) { mcpConfigured = true; mcpCfgTarget = 'Codex Desktop'; }
617
671
  } catch {}
618
672
  }
619
- check('OpenCode MCP configured', mcpConfigured, `Add MCP to ${opencodeCfg} run: npx huaweicloud-devkit-test install`);
673
+ check('MCP configured', mcpConfigured, mcpCfgTarget ? `Found in ${mcpCfgTarget} config` : 'Run: npx huaweicloud-devkit install');
620
674
 
621
675
  // hcloud CLI
622
676
  const hcloudBin = findHcloudBin() || (process.env.HCLOUD_BIN || 'hcloud');
623
- const hcloudCheck = spawnSync(`"${hcloudBin}" version`, [], { shell: true, windowsHide: true, stdio: 'pipe', timeout: 5000, input: 'y\n' });
677
+ const hcloudCheck = spawnSync(`"${hcloudBin}" version`, [], { shell: true, windowsHide: true, stdio: 'pipe', timeout: 5000 });
624
678
  const hcloudOut = (hcloudCheck.stdout || '').toString() + (hcloudCheck.stderr || '').toString();
625
679
  const hcloudOk = hcloudCheck.status === 0 && /KooCLI|Current.*version|当前KooCLI/i.test(hcloudOut);
626
680
  check('hcloud CLI installed', hcloudOk, 'Run: npx huaweicloud-devkit install-hcloud');
@@ -760,18 +814,25 @@ async function cmdInstallHcloud() {
760
814
  console.log(`\n\x1b[32mInstall complete.\x1b[0m`);
761
815
  console.log(` Verify: ${join(installDir, 'hcloud.exe')} version`);
762
816
 
763
- // Auto-accept the KooCLI privacy agreement so first run does not hang
764
- console.log('\n Accepting KooCLI privacy agreement...');
765
817
  const hcloudBin = join(installDir, 'hcloud.exe');
766
- if (acceptKooCliPrivacy(hcloudBin)) {
767
- console.log(' \x1b[32mPrivacy agreement accepted. KooCLI ready.\x1b[0m');
768
- } else {
769
- console.log(' \x1b[33m无法自动接受隐私协议(可能因沙箱阻止写入配置目录)。\x1b[0m');
770
- if (detectCodeartsSandbox() === 'sandbox') {
771
- printSandboxWarning('KooCLI 需要写入配置目录 (如 ~/.hcloud/root) 以保存隐私协议同意状态,但沙箱模式阻止了写入。');
818
+
819
+ // Ask user before accepting the privacy agreement never auto-accept.
820
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
821
+ const agree = await new Promise((resolve) => {
822
+ rl.question('\n KooCLI requires accepting its privacy agreement. Do you accept? (y/N) ', (answer) => {
823
+ rl.close();
824
+ resolve(/^\s*y\s*$/i.test(answer));
825
+ });
826
+ });
827
+ if (agree) {
828
+ const r = spawnSync(hcloudBin, ['version'], { input: 'y\n', encoding: 'utf8', timeout: 10000, windowsHide: true });
829
+ if (r.status === 0) {
830
+ console.log(' \x1b[32mPrivacy agreement accepted. KooCLI ready.\x1b[0m');
772
831
  } else {
773
- console.log(' 请在码道外终端运行一次: hcloud version 并按提示输入 y');
832
+ console.log(' \x1b[33m无法写入配置目录。请在码道外终端运行: echo "y" | hcloud version\x1b[0m');
774
833
  }
834
+ } else {
835
+ console.log(' \x1b[33m请手动接受隐私协议:在终端运行 hcloud version 并按提示操作\x1b[0m');
775
836
  }
776
837
 
777
838
  console.log(' Or restart terminal and: hcloud version');
@@ -1,6 +1,7 @@
1
1
  import { planHcloudCommand, runHcloud } from './hcloud-cli.mjs';
2
2
  import { classifyTextCommand, redactSecrets } from './safety-policy.mjs';
3
- import { readFileSync, readdirSync, existsSync } from 'node:fs';
3
+ import { evaluateArtifacts, evaluateCommandRisk, evaluateDeployPlan } from './risk-rule-engine.mjs';
4
+ import { readFileSync, readdirSync, existsSync, writeFileSync, mkdirSync } from 'node:fs';
4
5
  import { join, dirname } from 'node:path';
5
6
  import { fileURLToPath } from 'node:url';
6
7
  import { homedir } from 'node:os';
@@ -144,6 +145,51 @@ export const TOOL_DEFINITIONS = [
144
145
  },
145
146
  },
146
147
  },
148
+ {
149
+ name: 'huaweicloud_hook_check_command',
150
+ description: 'Check a planned shell or hcloud command against Huawei Cloud hook risk rules without executing it.',
151
+ inputSchema: {
152
+ type: 'object',
153
+ required: ['command'],
154
+ properties: {
155
+ command: { type: 'string', description: 'The exact command text to inspect.' },
156
+ },
157
+ },
158
+ },
159
+ {
160
+ name: 'huaweicloud_hook_check_artifacts',
161
+ description: 'Check generated code, IaC, policy, or config artifacts against Huawei Cloud hook risk rules.',
162
+ inputSchema: {
163
+ type: 'object',
164
+ required: ['artifacts'],
165
+ properties: {
166
+ artifacts: {
167
+ type: 'array',
168
+ items: {
169
+ type: 'object',
170
+ required: ['path', 'content'],
171
+ properties: {
172
+ path: { type: 'string' },
173
+ content: { type: 'string' },
174
+ },
175
+ },
176
+ },
177
+ },
178
+ },
179
+ },
180
+ {
181
+ name: 'huaweicloud_hook_check_deploy_plan',
182
+ description: 'Check a structured or textual deployment plan for Huawei Cloud sandbox, exposure, IAM, and cost risks.',
183
+ inputSchema: {
184
+ type: 'object',
185
+ required: ['plan'],
186
+ properties: {
187
+ plan: {
188
+ description: 'Deployment plan as an object, array, or string.',
189
+ },
190
+ },
191
+ },
192
+ },
147
193
  {
148
194
  name: 'huaweicloud_service_catalog',
149
195
  description: 'Return the recommended capability sources for Huawei Cloud agent tasks.',
@@ -224,6 +270,16 @@ export const TOOL_DEFINITIONS = [
224
270
  },
225
271
  },
226
272
  },
273
+ {
274
+ name: 'huaweicloud_setup_obs_config',
275
+ description: 'Synchronize KooCLI credentials to OBS config (~/.obsutilconfig). KooCLI and OBS use separate credential stores — hcloud commands work fine but OBS commands fail with "Please set ak, sk" unless this sync is done. Run this once to enable OBS operations; re-run after changing hcloud credentials.',
276
+ inputSchema: {
277
+ type: 'object',
278
+ properties: {
279
+ profile: { type: 'string', description: 'Optional KooCLI profile name. Uses the active profile by default.' },
280
+ },
281
+ },
282
+ },
227
283
  ];
228
284
 
229
285
  export async function callTool(name, args = {}) {
@@ -245,6 +301,12 @@ export async function callTool(name, args = {}) {
245
301
  return runApprovedCommand(args);
246
302
  case 'huaweicloud_show_profile_redacted':
247
303
  return showProfileRedacted(args.profile);
304
+ case 'huaweicloud_hook_check_command':
305
+ return hookResult(evaluateCommandRisk(args.command || ''));
306
+ case 'huaweicloud_hook_check_artifacts':
307
+ return hookResult(evaluateArtifacts(args.artifacts || []));
308
+ case 'huaweicloud_hook_check_deploy_plan':
309
+ return hookResult(evaluateDeployPlan(args.plan || {}));
248
310
  case 'huaweicloud_service_catalog':
249
311
  return serviceCatalog(args.intent);
250
312
  case 'huaweicloud_search_docs':
@@ -259,11 +321,26 @@ export async function callTool(name, args = {}) {
259
321
  return explainError(args);
260
322
  case 'huaweicloud_search_marketplace':
261
323
  return searchMarketplace(args.query || '', args.category || '');
324
+ case 'huaweicloud_setup_obs_config':
325
+ return setupObsConfig(args.profile);
262
326
  default:
263
327
  throw new Error(`Unknown tool: ${name}`);
264
328
  }
265
329
  }
266
330
 
331
+ function hookResult(result) {
332
+ return {
333
+ ok: result.decision !== 'deny',
334
+ decision: result.decision,
335
+ findings: result.findings,
336
+ nextStep: result.decision === 'deny'
337
+ ? 'Revise the command, artifact, or deployment plan before execution.'
338
+ : result.decision === 'warn'
339
+ ? 'Review the warnings with the user before proceeding.'
340
+ : 'No Huawei Cloud hook risk rule matched.',
341
+ };
342
+ }
343
+
267
344
  export async function runVersionCheck(options = {}) {
268
345
  const result = await runHcloud(['version'], {
269
346
  ...options,
@@ -312,6 +389,84 @@ async function showProfileRedacted(profile) {
312
389
  };
313
390
  }
314
391
 
392
+ async function setupObsConfig(profile) {
393
+ const obsConfigPath = join(homedir(), '.obsutilconfig');
394
+ if (existsSync(obsConfigPath)) {
395
+ return { ok: true, existed: true, path: obsConfigPath, note: 'OBS config already exists. Delete ~/.obsutilconfig first if you need to re-sync.' };
396
+ }
397
+
398
+ const args = ['configure', 'show'];
399
+ if (profile) args.push('--cli-profile', String(profile));
400
+ const result = await runHcloud(args, { allowWrites: false, allowCredentialRead: true });
401
+
402
+ if (!result.ok) {
403
+ return {
404
+ ok: false,
405
+ error: 'Failed to read hcloud profile.',
406
+ detail: result.error || result.stderr || 'hcloud not installed or not configured',
407
+ nextStep: 'Run "hcloud configure init" outside agent chat, then retry.',
408
+ };
409
+ }
410
+
411
+ let accessKeyId = '';
412
+ let secretAccessKey = '';
413
+ let region = '';
414
+
415
+ try {
416
+ const parsed = typeof result.stdout === 'string' ? JSON.parse(result.stdout) : result.stdout;
417
+ const cred = parsed.currentCredential || {};
418
+ accessKeyId = cred.accessKeyId || cred.ak || cred.access_key || '';
419
+ secretAccessKey = cred.secretAccessKey || cred.sk || cred.secret_key || '';
420
+ region = parsed.currentRegion || parsed.region || '';
421
+ } catch {
422
+ return {
423
+ ok: false,
424
+ error: 'Failed to parse hcloud profile output.',
425
+ detail: 'hcloud configure show returned unexpected format',
426
+ };
427
+ }
428
+
429
+ if (!accessKeyId || !secretAccessKey) {
430
+ return {
431
+ ok: false,
432
+ error: 'No credentials found in hcloud profile.',
433
+ nextStep: 'Run "hcloud configure init" outside agent chat to set up credentials first.',
434
+ };
435
+ }
436
+
437
+ if (!region) {
438
+ return {
439
+ ok: false,
440
+ error: 'No region found in hcloud profile.',
441
+ nextStep: 'Run "hcloud configure set --cli-region=<region>" outside agent chat to set a default region.',
442
+ };
443
+ }
444
+
445
+ const endpoint = `https://obs.${region}.myhuaweicloud.com`;
446
+ const configContent = `[default]\r\nendpoint=${endpoint}\r\nak=${accessKeyId}\r\nsk=${secretAccessKey}\r\n`;
447
+
448
+ try {
449
+ writeFileSync(obsConfigPath, configContent, { encoding: 'utf8', mode: 0o600 });
450
+ } catch (e) {
451
+ return {
452
+ ok: false,
453
+ error: 'Failed to write OBS config file.',
454
+ detail: e.message,
455
+ path: obsConfigPath,
456
+ };
457
+ }
458
+
459
+ return {
460
+ ok: true,
461
+ existed: false,
462
+ created: true,
463
+ path: obsConfigPath,
464
+ region,
465
+ endpoint,
466
+ note: 'OBS credentials synced from hcloud profile. OBS commands (hcloud OBS ls, mb, cp, etc.) should now work.',
467
+ };
468
+ }
469
+
315
470
  const SERVICE_EXAMPLES = {
316
471
  ECS: { list: 'ECS ListServersDetails', create: 'ECS CreateServers', show: 'IMS GlanceShowImage' },
317
472
  VPC: { list: 'VPC ListVpcs', create: 'VPC CreateVpc', show: 'VPC ShowVpc' },