huaweicloud-devkit 1.1.13 → 1.1.14-next.1

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 (28) hide show
  1. package/integrations/opencode/package-lock.json +24 -0
  2. package/integrations/opencode/package.json +10 -0
  3. package/integrations/opencode/plugins/huaweicloud-devkit.js +194 -0
  4. package/package.json +1 -1
  5. package/plugins/huaweicloud-core/.claude-plugin/plugin.json +16 -3
  6. package/plugins/huaweicloud-core/.codex-plugin/plugin.json +16 -3
  7. package/plugins/huaweicloud-core/.cursor-plugin/plugin.json +16 -3
  8. package/plugins/huaweicloud-core/.hermes-plugin/plugin.json +16 -3
  9. package/plugins/huaweicloud-core/.workbuddy-plugin/plugin.json +16 -3
  10. package/plugins/huaweicloud-core/openclaw.plugin.json +1 -1
  11. package/plugins/huaweicloud-core/safety/rules/cloud-risk-rules.json +6 -0
  12. package/plugins/huaweicloud-core/src/account-type.mjs +10 -1
  13. package/plugins/huaweicloud-core/src/auth/agent-registration.mjs +1 -1
  14. package/plugins/huaweicloud-core/src/auth/credentials.mjs +118 -4
  15. package/plugins/huaweicloud-core/src/auth/service.mjs +25 -2
  16. package/plugins/huaweicloud-core/src/auth/token-exchange.mjs +100 -0
  17. package/plugins/huaweicloud-core/src/hcloud-cli.mjs +49 -4
  18. package/plugins/huaweicloud-core/src/hcloud-probe.mjs +12 -0
  19. package/plugins/huaweicloud-core/src/koocli-install.mjs +57 -0
  20. package/plugins/huaweicloud-core/src/mcp-config-merge.mjs +1 -1
  21. package/plugins/huaweicloud-core/src/risk-rule-engine.mjs +1 -1
  22. package/plugins/huaweicloud-core/src/safety-policy.mjs +1 -1
  23. package/plugins/huaweicloud-core/src/sandbox/devbridge-key.mjs +6 -0
  24. package/plugins/huaweicloud-core/src/sandbox/hdkitservice-api.mjs +29 -7
  25. package/plugins/huaweicloud-core/src/sandbox/hwlink-api.mjs +36 -1
  26. package/plugins/huaweicloud-core/src/sandbox/session-manager.mjs +4 -4
  27. package/plugins/huaweicloud-core/src/setup-cli.mjs +91 -9
  28. package/plugins/huaweicloud-core/src/tools.mjs +57 -3
@@ -25,6 +25,9 @@ import { redactSecrets } from './safety-policy.mjs';
25
25
  import {
26
26
  globalCredentialsPath,
27
27
  readGlobalCredentials,
28
+ readJsonFile,
29
+ resolveCredentialsWithRuntime,
30
+ resolveXAuthToken,
28
31
  writeGlobalCredentials,
29
32
  writeLastSync,
30
33
  writeObsConfig,
@@ -44,6 +47,7 @@ import {
44
47
  applyUserDelta,
45
48
  inheritPeerUserEnv,
46
49
  detectOpenCodeEra,
50
+ isPlainObject,
47
51
  mergeOpenCodeEntry,
48
52
  } from './mcp-config-merge.mjs';
49
53
  import { readAgentDelta, saveAgentDelta, takeAgentDelta, purgeBackup } from './mcp-config-backup.mjs';
@@ -52,8 +56,6 @@ import { queryDistTagsFetch, determineTarget, semverCompare } from './update-che
52
56
  import { getKooCliVersion, compareVersion, kooCliDownloadBase, KOO_CLI_BASE } from './koocli-version.mjs';
53
57
  import { findHcloudBin, hcloudProbeNextStep, probeHcloud } from './hcloud-probe.mjs';
54
58
 
55
- const { DatabaseSync } = createRequire(import.meta.url)('node:sqlite');
56
-
57
59
  const __dirname = dirname(fileURLToPath(import.meta.url));
58
60
  const PLUGIN_ROOT = resolve(__dirname, '..');
59
61
  const PACKAGE_ROOT = resolve(PLUGIN_ROOT, '..', '..');
@@ -250,6 +252,9 @@ function officeaceSqlitePath() {
250
252
  }
251
253
 
252
254
  function openOfficeaceDb() {
255
+ // Lazy-require node:sqlite (experimental on Node 22.x) so CLI commands that
256
+ // don't touch OfficeAce (version/doctor/install) run without the flag.
257
+ const { DatabaseSync } = createRequire(import.meta.url)('node:sqlite');
253
258
  return new DatabaseSync(officeaceSqlitePath());
254
259
  }
255
260
 
@@ -710,7 +715,7 @@ function resolveOpenCodeEra() {
710
715
  return (resolvedOpenCodeEra = 'v2');
711
716
  }
712
717
 
713
- function updateOpenCodeConfig(pluginDir) {
718
+ function updateOpenCodeConfig(pluginDir, { nativePluginInstalled = false } = {}) {
714
719
  const configPath = opencodeConfigFile();
715
720
  const mcpPath = join(pluginDir, 'src', 'mcp-server.mjs').replace(/\\/g, '/');
716
721
  const era = resolveOpenCodeEra();
@@ -729,6 +734,25 @@ function updateOpenCodeConfig(pluginDir) {
729
734
 
730
735
  const { config: next, existing, changed } = mergeOpenCodeEntry(config, { mcpPath, era });
731
736
 
737
+ // Native-plugin mode: the in-process plugin already bridges all 42 tools with
738
+ // the shared callTool layer (names, approval gate, telemetry unchanged). Keep
739
+ // the MCP entry for manual fallback but leave it disabled so OpenCode does
740
+ // not register 42 duplicate `huaweicloud-devkit_*` copies (#940 follow-up).
741
+ let mcpDisabled = false;
742
+ if (nativePluginInstalled) {
743
+ const key = 'huaweicloud-devkit';
744
+ if (era === 'v2') {
745
+ const servers = isPlainObject(next.mcp?.servers) ? next.mcp.servers : null;
746
+ if (servers && servers[key] && servers[key].disabled !== true) {
747
+ servers[key] = { ...servers[key], disabled: true };
748
+ mcpDisabled = true;
749
+ }
750
+ } else if (next.mcp?.[key] && next.mcp[key].enabled !== false) {
751
+ next.mcp[key] = { ...next.mcp[key], enabled: false };
752
+ mcpDisabled = true;
753
+ }
754
+ }
755
+
732
756
  // Restore user fields saved by a previous uninstall (issue #615), on fresh install only.
733
757
  if (!existing) {
734
758
  const delta = takeAgentDelta('opencode');
@@ -741,12 +765,15 @@ function updateOpenCodeConfig(pluginDir) {
741
765
  }
742
766
  }
743
767
 
744
- if (existing && !changed) {
768
+ if (existing && !changed && !mcpDisabled) {
745
769
  console.log(` OpenCode MCP config unchanged: ${configPath}`);
746
770
  return;
747
771
  }
748
772
 
749
773
  writeMcpSettingsFile(configPath, next);
774
+ if (mcpDisabled) {
775
+ console.log(` OpenCode MCP entry disabled (native plugin active — no duplicate tools) -> ${configPath}`);
776
+ }
750
777
  console.log(
751
778
  existing
752
779
  ? ` OpenCode MCP config merged (user fields preserved, ${era}): ${configPath}`
@@ -968,7 +995,24 @@ async function installOpenCode() {
968
995
  mkdirSync(opcPlugins, { recursive: true });
969
996
  copyFileSync(pluginSrc, join(opcPlugins, 'skill-tracker.js'));
970
997
  console.log(` Plugin -> ${opcPlugins}`);
971
- updateOpenCodeConfig(pluginDest);
998
+ // OpenCode native plugin (#905 OpenCode performance): bridges all 42 MCP tools
999
+ // into OpenCode in-process custom tools (zod schemas + callTool), plus safety
1000
+ // gate and telemetry. Local plugins are auto-loaded from this directory.
1001
+ const nativePluginSrc = join(PACKAGE_ROOT, 'integrations', 'opencode', 'plugins', 'huaweicloud-devkit.js');
1002
+ let nativePluginInstalled = false;
1003
+ if (existsSync(nativePluginSrc)) {
1004
+ copyFileSync(nativePluginSrc, join(opcPlugins, 'huaweicloud-devkit.js'));
1005
+ // Deps for the native plugin (zod) live next to the OpenCode config so the
1006
+ // plugin can require them at load time.
1007
+ const nativePkgSrc = join(PACKAGE_ROOT, 'integrations', 'opencode', 'package.json');
1008
+ const nativePkgDst = join(configRoot('opencode'), 'package.json');
1009
+ if (existsSync(nativePkgSrc) && !existsSync(nativePkgDst)) {
1010
+ copyFileSync(nativePkgSrc, nativePkgDst);
1011
+ }
1012
+ nativePluginInstalled = true;
1013
+ console.log(` Native plugin -> ${join(opcPlugins, 'huaweicloud-devkit.js')}`);
1014
+ }
1015
+ updateOpenCodeConfig(pluginDest, { nativePluginInstalled });
972
1016
  installRuntimeDeps(pluginDest);
973
1017
  }
974
1018
 
@@ -1001,6 +1045,11 @@ function uninstallOpenCode() {
1001
1045
  removeIfExists(pluginFile);
1002
1046
  console.log(' Removed plugin');
1003
1047
  }
1048
+ const nativePluginFile = join(configRoot('opencode'), 'plugins', 'huaweicloud-devkit.js');
1049
+ if (existsSync(nativePluginFile)) {
1050
+ removeIfExists(nativePluginFile);
1051
+ console.log(' Removed native plugin');
1052
+ }
1004
1053
 
1005
1054
  if (removeIfExists(opencodePluginsDir())) {
1006
1055
  console.log(' Removed MCP server and safety policy');
@@ -1048,7 +1097,20 @@ async function updateOpenCode() {
1048
1097
  mkdirSync(opcPlugins, { recursive: true });
1049
1098
  copyFileSync(pluginSrc, join(opcPlugins, 'skill-tracker.js'));
1050
1099
  console.log(` Plugin updated -> ${opcPlugins}`);
1051
- updateOpenCodeConfig(pluginDest);
1100
+ // Native plugin refresh (#905 OpenCode performance) — overwrite in place.
1101
+ const nativePluginSrc = join(PACKAGE_ROOT, 'integrations', 'opencode', 'plugins', 'huaweicloud-devkit.js');
1102
+ let nativePluginInstalled = false;
1103
+ if (existsSync(nativePluginSrc)) {
1104
+ copyFileSync(nativePluginSrc, join(opcPlugins, 'huaweicloud-devkit.js'));
1105
+ const nativePkgSrc = join(PACKAGE_ROOT, 'integrations', 'opencode', 'package.json');
1106
+ const nativePkgDst = join(configRoot('opencode'), 'package.json');
1107
+ if (existsSync(nativePkgSrc) && !existsSync(nativePkgDst)) {
1108
+ copyFileSync(nativePkgSrc, nativePkgDst);
1109
+ }
1110
+ nativePluginInstalled = true;
1111
+ console.log(` Native plugin updated -> ${join(opcPlugins, 'huaweicloud-devkit.js')}`);
1112
+ }
1113
+ updateOpenCodeConfig(pluginDest, { nativePluginInstalled });
1052
1114
  mkdirSync(pluginDest, { recursive: true });
1053
1115
  writeFileSync(join(pluginDest, '.installed'), new Date().toISOString());
1054
1116
  installRuntimeDeps(pluginDest);
@@ -1533,7 +1595,7 @@ function codeartsStatus() {
1533
1595
  );
1534
1596
  if (existsSync(codeartsMcpSettingsFile())) {
1535
1597
  try {
1536
- const config = JSON.parse(readFileSync(codeartsMcpSettingsFile(), 'utf8'));
1598
+ const config = readJsonFile(codeartsMcpSettingsFile());
1537
1599
  console.log(
1538
1600
  ` MCP config: ${config.mcpServers?.['huaweicloud-devkit'] ? '\x1b[32mConfigured\x1b[0m' : '\x1b[31mNot configured\x1b[0m'}`,
1539
1601
  );
@@ -1694,7 +1756,7 @@ function codeartsWorkStatus() {
1694
1756
  );
1695
1757
  if (existsSync(codeartsWorkMcpSettingsFile())) {
1696
1758
  try {
1697
- const config = JSON.parse(readFileSync(codeartsWorkMcpSettingsFile(), 'utf8'));
1759
+ const config = readJsonFile(codeartsWorkMcpSettingsFile());
1698
1760
  console.log(
1699
1761
  ` MCP config: ${config.mcp?.['huaweicloud-devkit'] ? '\x1b[32mConfigured\x1b[0m' : '\x1b[31mNot configured\x1b[0m'}`,
1700
1762
  );
@@ -4259,7 +4321,27 @@ async function cmdDoctor() {
4259
4321
  timeout: 5000,
4260
4322
  });
4261
4323
  const hasAuth = authCheck.status === 0 && /access.?key/i.test(authCheck.stdout.toString());
4262
- check('hcloud credentials configured', hasAuth, 'Run: npx huaweicloud-devkit auth init');
4324
+ if (hasAuth) {
4325
+ check('hcloud credentials configured', true, '');
4326
+ } else {
4327
+ // In CodeArts, platform-injected STS / X-Auth-Token reach only the MCP
4328
+ // server process, not this bash tool process — so `hcloud configure list`
4329
+ // shows no profile even though the backend API path is usable. Degrade to
4330
+ // a warning instead of a hard fail in that case (#P3 of CodeArts test).
4331
+ let platformCredsActive = false;
4332
+ try {
4333
+ const c = resolveCredentialsWithRuntime({ allowMissing: true });
4334
+ platformCredsActive = Boolean((c && c.ak && c.sk && c.securityToken) || resolveXAuthToken());
4335
+ } catch {}
4336
+ if (platformCredsActive) {
4337
+ console.log(
4338
+ ` \x1b[33m[WARN]\x1b[0m hcloud credentials configured — KooCLI 无 profile,但检测到平台凭证(MCP 通道可用);仅 KooCLI 直接调用需 auth init`,
4339
+ );
4340
+ warn++;
4341
+ } else {
4342
+ check('hcloud credentials configured', false, 'Run: npx huaweicloud-devkit auth init');
4343
+ }
4344
+ }
4263
4345
  }
4264
4346
 
4265
4347
  // Skills
@@ -13,6 +13,7 @@ import { checkAccountType } from './account-type.mjs';
13
13
  import { searchMarketplace } from './search-market.mjs';
14
14
  import { getServiceIcon } from './icon-library.mjs';
15
15
  import { detectFramework } from './detect-framework.mjs';
16
+ import { installKooCli } from './koocli-install.mjs';
16
17
  import {
17
18
  execWithSession,
18
19
  execOneShot,
@@ -47,7 +48,7 @@ import {
47
48
  hdkitCompetitionVoucherClaim,
48
49
  hdkitGenerateUserHash,
49
50
  } from './sandbox/hdkitservice-api.mjs';
50
- import { getCredentials } from './sandbox/hwlink-api.mjs';
51
+ import { resolveBackendCredentials } from './sandbox/hwlink-api.mjs';
51
52
  import { getAuthStatus, syncAuth } from './auth/service.mjs';
52
53
  import { validateIamCredentials } from './auth/credential-validator.mjs';
53
54
  import {
@@ -63,6 +64,7 @@ import {
63
64
  globalCredentialsPath,
64
65
  parseStsExpiry,
65
66
  resolveCredentialsWithRuntime,
67
+ warmTokenCredentials,
66
68
  } from './auth/credentials.mjs';
67
69
  import { trackToolInvoke, trackSkillRetrieve, clearUserHash, cacheUserHash } from './telemetry/telemetry.mjs';
68
70
  import { fetchWithProxy } from './proxy/proxy-agent.mjs';
@@ -211,6 +213,15 @@ export const TOOL_DEFINITIONS = [
211
213
  properties: {},
212
214
  },
213
215
  },
216
+ {
217
+ name: 'huaweicloud_install_hcloud',
218
+ description:
219
+ 'Install KooCLI (hcloud) from inside the MCP server process via Node (no agent bash tool required). Downloads and extracts the pinned hcloud binary to ~/.local/bin/hcloud. Use when huaweicloud_check_cli reports HCLOUD_NOT_FOUND and the agent bash tool is unavailable (e.g. CodeArts with OPENCODE_CONFIG unset).',
220
+ inputSchema: {
221
+ type: 'object',
222
+ properties: {},
223
+ },
224
+ },
214
225
  {
215
226
  name: 'huaweicloud_plan_cli_command',
216
227
  description: 'Classify and plan a Huawei Cloud hcloud command without executing it.',
@@ -1198,7 +1209,9 @@ function readImportFile() {
1198
1209
  const path = join(dirname(globalCredentialsPath()), 'creds-import.json');
1199
1210
  try {
1200
1211
  if (!existsSync(path)) return null;
1201
- const data = JSON.parse(readFileSync(path, 'utf8'));
1212
+ // Strip a leading UTF-8 BOM: PowerShell `Set-Content -Encoding UTF8` writes
1213
+ // one, which plain JSON.parse rejects (#devkit-体验报告 P1-4).
1214
+ const data = JSON.parse(readFileSync(path, 'utf8').replace(/^\uFEFF/, ''));
1202
1215
  return {
1203
1216
  ak: String(data.ak || ''),
1204
1217
  sk: String(data.sk || ''),
@@ -1307,14 +1320,30 @@ function normalizeNumericArgs(args) {
1307
1320
  return out;
1308
1321
  }
1309
1322
 
1323
+ // Auth-state tools report user intent; warming would mask the real credential
1324
+ // state (runtime would show the exchanged STS instead of token-auth).
1325
+ const NO_WARM_TOOLS = new Set([
1326
+ 'huaweicloud_auth_status',
1327
+ 'huaweicloud_auth_init',
1328
+ 'huaweicloud_auth_switch',
1329
+ 'huaweicloud_auth_sync',
1330
+ 'huaweicloud_show_profile_redacted',
1331
+ 'huaweicloud_explain_error',
1332
+ ]);
1333
+
1310
1334
  export async function callTool(name, rawArgs = {}, opts = {}) {
1311
1335
  const args = normalizeNumericArgs(rawArgs);
1312
1336
  const toolValue = toolInvokeValue(name, args);
1313
1337
  trackToolInvoke(name, toolValue);
1338
+ if (!NO_WARM_TOOLS.has(name)) {
1339
+ await warmTokenCredentials(); // no-op with AK/SK; token→STS for token-only users
1340
+ }
1314
1341
 
1315
1342
  switch (name) {
1316
1343
  case 'huaweicloud_check_cli':
1317
1344
  return runVersionCheck();
1345
+ case 'huaweicloud_install_hcloud':
1346
+ return installKooCli();
1318
1347
  case 'huaweicloud_plan_cli_command':
1319
1348
  return planHcloudCommand(args.args || [], { allowWrites: args.allowWrites === true });
1320
1349
  case 'huaweicloud_run_readonly_command':
@@ -1418,6 +1447,11 @@ export async function callTool(name, rawArgs = {}, opts = {}) {
1418
1447
  }
1419
1448
 
1420
1449
  if (!ak || !sk) {
1450
+ if (sourceChannel === 'import') {
1451
+ throw new Error(
1452
+ 'ak and sk are required. creds-import.json 缺失或无法解析(可能带 UTF-8 BOM 或非法 JSON),解析失败时文件已被清除。请用无 BOM 的 UTF-8 JSON 重新写入后重试 mode=import(PowerShell 推荐 [IO.File]::WriteAllText 配 UTF8Encoding($false))。',
1453
+ );
1454
+ }
1421
1455
  throw new Error('ak and sk are required (or provide creds-import.json for mode=import).');
1422
1456
  }
1423
1457
 
@@ -1838,7 +1872,7 @@ export async function callTool(name, rawArgs = {}, opts = {}) {
1838
1872
  const apiKeyFile = '/tmp/hw_api_key';
1839
1873
  if (sandboxWsIdCred) {
1840
1874
  try {
1841
- const { ak, sk, securitytoken } = getCredentials();
1875
+ const { ak, sk, securitytoken } = await resolveBackendCredentials();
1842
1876
  const credsScript = [
1843
1877
  `export HW_ACCESS_KEY='${ak}'`,
1844
1878
  `export HW_SECRET_KEY='${sk}'`,
@@ -2593,6 +2627,26 @@ function explainError({ service = 'unknown', errorCode = '', message = '', reque
2593
2627
  }
2594
2628
  const patternKey = SERVICE_ALIASES[svc] || resolvedService;
2595
2629
 
2630
+ // devkit internal credential/environment error codes (experience-report #3.9)
2631
+ // — these come from devkit's own guidance/credential layer, not Huawei Cloud API.
2632
+ const devkitErrorPatterns = {
2633
+ HDKIT_CRED_MISSING:
2634
+ '未配置华为云凭证。运行 npx huaweicloud-devkit auth init 配置 AK/SK,或注入 HW_X_AUTH_TOKEN(devkit 会自动用 token 换取临时 AK/SK)。',
2635
+ HDKIT_CRED_INVALID: '凭证已被华为云拒绝(AK/SK 无效或已过期)。重新生成 AK/SK 后 auth init。',
2636
+ HDKIT_CRED_FORBIDDEN: '凭证有效但无权限列出项目。检查 IAM 授权(可用 huaweicloud_check_account_type 判断账号类型)。',
2637
+ HDKIT_CRED_REGION_MISSING: '缺少 region 配置。运行 hcloud configure set --cli-region=<region>。',
2638
+ HDKIT_KOOCLI_NOT_READY: 'KooCLI(hcloud)未安装或未就绪。运行 npx huaweicloud-devkit install-hcloud。',
2639
+ HDKIT_PROJECT_ID_MISSING: '缺少 project_id。运行 npx huaweicloud-devkit auth init 自动配置。',
2640
+ TOKEN_INVALID: 'X-Auth-Token 无效或已过期。重新注入有效的 HW_X_AUTH_TOKEN。',
2641
+ TOKEN_EXPIRED: 'X-Auth-Token 已过期。重启进程重新注入凭证。',
2642
+ TOKEN_EXCHANGE_FAILED:
2643
+ 'X-Auth-Token 换取临时 AK/SK 失败,通常是网络无法访问 IAM 端点。检查网络连通性与 token 有效性。',
2644
+ HDKIT_SUB_ACCOUNT_RESTRICTED: '沙箱使用限制:当前子账号无法使用沙箱。切换主账号认证(auth_init)后重试。',
2645
+ };
2646
+ if (devkitErrorPatterns[errorCode]) {
2647
+ suggestions.push(`${errorCode}: ${devkitErrorPatterns[errorCode]}`);
2648
+ }
2649
+
2596
2650
  const hwErrorPatterns = {
2597
2651
  OBS: {
2598
2652
  InvalidAccessKeyId: