huaweicloud-devkit 2.0.0-next.0 → 2.0.0-next.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/README.md +2 -0
  2. package/package.json +1 -1
  3. package/plugins/huaweicloud-core/.claude-plugin/plugin.json +1 -1
  4. package/plugins/huaweicloud-core/.codex-plugin/plugin.json +1 -1
  5. package/plugins/huaweicloud-core/.cursor-plugin/plugin.json +1 -1
  6. package/plugins/huaweicloud-core/.hermes-plugin/plugin.json +1 -1
  7. package/plugins/huaweicloud-core/.workbuddy-plugin/plugin.json +1 -1
  8. package/plugins/huaweicloud-core/dist/agents/codearts-work.js +4 -0
  9. package/plugins/huaweicloud-core/dist/agents/codearts.js +4 -0
  10. package/plugins/huaweicloud-core/dist/agents/officeace-sqlite.js +14 -4
  11. package/plugins/huaweicloud-core/dist/agents/opencode-config.js +5 -1
  12. package/plugins/huaweicloud-core/dist/approvals-cli.js +159 -0
  13. package/plugins/huaweicloud-core/dist/auth/s1-store.js +43 -22
  14. package/plugins/huaweicloud-core/dist/hcloud-plan.js +26 -4
  15. package/plugins/huaweicloud-core/dist/hcloud-run.js +4 -1
  16. package/plugins/huaweicloud-core/dist/lib/approval-tokens.js +135 -16
  17. package/plugins/huaweicloud-core/dist/lib/approvals-pin.js +128 -0
  18. package/plugins/huaweicloud-core/dist/lib/pack-state.js +23 -19
  19. package/plugins/huaweicloud-core/dist/lib/param-warnings.js +70 -0
  20. package/plugins/huaweicloud-core/dist/lib/state-dir.js +125 -0
  21. package/plugins/huaweicloud-core/dist/mcp-server.js +877 -595
  22. package/plugins/huaweicloud-core/dist/mcp-server.js.map +4 -4
  23. package/plugins/huaweicloud-core/dist/packs/huaweicloud-cli/tools.js +27 -9
  24. package/plugins/huaweicloud-core/dist/payload-runtime-deps.js +11 -3
  25. package/plugins/huaweicloud-core/dist/safety/classify-text.js +13 -0
  26. package/plugins/huaweicloud-core/dist/safety/policy.js +1 -0
  27. package/plugins/huaweicloud-core/dist/setup-cli.js +23 -0
  28. package/plugins/huaweicloud-core/dist/tool-schemas.js +15 -0
  29. package/plugins/huaweicloud-core/dist/tools.js +36 -4
  30. package/plugins/huaweicloud-core/dist/update-registry.js +8 -2
  31. package/plugins/huaweicloud-core/dist/update-skip.js +5 -6
  32. package/plugins/huaweicloud-core/dist/update-upgrade.js +8 -1
  33. package/plugins/huaweicloud-core/hooks/huaweicloud-safety.py +20 -1
  34. package/plugins/huaweicloud-core/openclaw.plugin.json +1 -1
  35. package/plugins/huaweicloud-core/safety/policy.json +8 -0
  36. package/plugins/huaweicloud-core/safety/rules/cloud-risk-rules.json +78 -2
  37. package/plugins/huaweicloud-core/skills/huaweicloud-cli-and-auth/SKILL.md +4 -1
  38. package/plugins/huaweicloud-core/skills/huaweicloud-safety/SKILL.md +13 -6
  39. package/plugins/huaweicloud-core/skills/huaweicloud-safety/references/approvals.md +47 -0
  40. package/plugins/huaweicloud-core/src/agents/codearts-work.ts +3 -0
  41. package/plugins/huaweicloud-core/src/agents/codearts.ts +4 -0
  42. package/plugins/huaweicloud-core/src/agents/officeace-sqlite.ts +14 -4
  43. package/plugins/huaweicloud-core/src/agents/opencode-config.ts +5 -1
  44. package/plugins/huaweicloud-core/src/approvals-cli.ts +187 -0
  45. package/plugins/huaweicloud-core/src/auth/s1-store.ts +41 -20
  46. package/plugins/huaweicloud-core/src/hcloud-plan.ts +44 -5
  47. package/plugins/huaweicloud-core/src/hcloud-run.ts +4 -1
  48. package/plugins/huaweicloud-core/src/lib/approval-tokens.ts +197 -16
  49. package/plugins/huaweicloud-core/src/lib/approvals-pin.ts +153 -0
  50. package/plugins/huaweicloud-core/src/lib/pack-state.ts +23 -20
  51. package/plugins/huaweicloud-core/src/lib/param-warnings.ts +69 -0
  52. package/plugins/huaweicloud-core/src/lib/state-dir.ts +128 -0
  53. package/plugins/huaweicloud-core/src/packs/huaweicloud-cli/tools.ts +29 -9
  54. package/plugins/huaweicloud-core/src/payload-runtime-deps.ts +11 -3
  55. package/plugins/huaweicloud-core/src/safety/classify-text.ts +15 -0
  56. package/plugins/huaweicloud-core/src/safety/policy.ts +2 -0
  57. package/plugins/huaweicloud-core/src/setup-cli.ts +28 -0
  58. package/plugins/huaweicloud-core/src/tool-schemas.ts +16 -0
  59. package/plugins/huaweicloud-core/src/tools.ts +39 -4
  60. package/plugins/huaweicloud-core/src/update-registry.ts +8 -2
  61. package/plugins/huaweicloud-core/src/update-skip.ts +5 -6
  62. package/plugins/huaweicloud-core/src/update-upgrade.ts +8 -1
@@ -0,0 +1,128 @@
1
+ import { existsSync, lstatSync, mkdirSync, rmSync } from 'node:fs';
2
+ import { homedir } from 'node:os';
3
+ import { dirname, isAbsolute, join, resolve } from 'node:path';
4
+
5
+ // The devkit's two directory roots. `configBase` is the historical
6
+ // ~/.config/huaweicloud tree (credentials, approvals, pack state, proxy and
7
+ // update state); `stateBase` is the same tree by default and moves to a
8
+ // writable agent-owned directory only when the config tree cannot be written.
9
+ //
10
+ // The split exists because some agent sandboxes ship a read-only home: the
11
+ // gateway's pack state, approval tokens, S1 writes and update state all need
12
+ // a writable directory, while the pre-provisioned credentials.json must stay
13
+ // readable at its original location. The installer/CLI and the MCP server
14
+ // resolve the same paths from the same filesystem, so no env plumbing is
15
+ // required for them to agree.
16
+ //
17
+ // Runtime import graph stays at node builtins — pack-state.ts (the stable
18
+ // resolver face) and the installer graph import this module.
19
+
20
+ const STATE_DIR_ENV = 'HUAWEICLOUD_STATE_DIR';
21
+ const AGENT_STATE_MARKERS = ['.codearts', '.codeartswork', '.codeartsdoer'] as const;
22
+
23
+ const stateBaseCache = new Map<string, string>();
24
+
25
+ export function huaweiConfigBase(env: NodeJS.ProcessEnv = process.env): string {
26
+ // resolve() absolutizes once, here, so every consumer — store writes and
27
+ // the protected-tree guard — shares one anchor even for a relative
28
+ // HUAWEICLOUD_HOME (a relative base previously made the store land at
29
+ // the process cwd while the guard protected a tmpdir-anchored tree).
30
+ return resolve(env.HUAWEICLOUD_HOME || homedir(), '.config', 'huaweicloud');
31
+ }
32
+
33
+ function agentHomeBase(env: NodeJS.ProcessEnv): string {
34
+ return resolve(env.HUAWEICLOUD_HOME || homedir());
35
+ }
36
+
37
+ function nearestExisting(path: string): string | null {
38
+ let current = resolve(path);
39
+ for (;;) {
40
+ try {
41
+ lstatSync(current);
42
+ return current;
43
+ } catch {
44
+ const parent = dirname(current);
45
+ if (parent === current) return null;
46
+ current = parent;
47
+ }
48
+ }
49
+ }
50
+
51
+ // A real create/remove probe, not access(W_OK): Windows ACLs and WSL drvfs
52
+ // can report a writable mode while mkdir still fails, and the gateway's first
53
+ // pack-state provisioning is exactly a mkdir under the config tree.
54
+ export function probeWritableDir(path: string): boolean {
55
+ const anchor = nearestExisting(path);
56
+ if (!anchor) return false;
57
+ const probe = join(anchor, `.devkit-write-probe-${process.pid}-${Math.random().toString(36).slice(2)}`);
58
+ try {
59
+ mkdirSync(probe, { mode: 0o700 });
60
+ return true;
61
+ } catch {
62
+ return false;
63
+ } finally {
64
+ try {
65
+ rmSync(probe, { recursive: true, force: true });
66
+ } catch {
67
+ // best-effort cleanup; the probe directory is empty and 0700
68
+ }
69
+ }
70
+ }
71
+
72
+ // Agent-owned writable roots, checked in the same order the installer targets
73
+ // them: CodeArts Work's new layout, its legacy home, then CodeArts.
74
+ function codeArtsStateBase(env: NodeJS.ProcessEnv): string | null {
75
+ const home = agentHomeBase(env);
76
+ for (const marker of AGENT_STATE_MARKERS) {
77
+ const root = join(home, marker);
78
+ if (!existsSync(root) || !probeWritableDir(root)) continue;
79
+ return join(root, 'devkit-state');
80
+ }
81
+ return null;
82
+ }
83
+
84
+ function explicitStateBase(env: NodeJS.ProcessEnv): string | null {
85
+ const value = (env[STATE_DIR_ENV] ?? '').trim();
86
+ if (value === '') return null;
87
+ if (!isAbsolute(value)) {
88
+ throw new Error(
89
+ `${STATE_DIR_ENV} must be an absolute path (got "${value}"): the CLI and the MCP server resolve relative paths against different working directories.`,
90
+ );
91
+ }
92
+ return resolve(value);
93
+ }
94
+
95
+ export function devkitStateBase(env: NodeJS.ProcessEnv = process.env): string {
96
+ const explicit = explicitStateBase(env);
97
+ if (explicit) return explicit;
98
+ const configBase = huaweiConfigBase(env);
99
+ const cached = stateBaseCache.get(configBase);
100
+ if (cached) return cached;
101
+ const stateBase = probeWritableDir(configBase) ? configBase : (codeArtsStateBase(env) ?? configBase);
102
+ stateBaseCache.set(configBase, stateBase);
103
+ return stateBase;
104
+ }
105
+
106
+ // Doctor/installer display form: home-relative paths stay stable in the
107
+ // golden fixtures and read better to a human. Forward slashes keep the
108
+ // rendered form identical on Windows and POSIX (the goldens are committed
109
+ // once, not per platform).
110
+ export function displayStatePath(path: string, env: NodeJS.ProcessEnv = process.env): string {
111
+ const home = agentHomeBase(env).replace(/\\/g, '/');
112
+ const normalized = path.replace(/\\/g, '/');
113
+ if (normalized === home) return '~';
114
+ return normalized.startsWith(home + '/') ? `~${normalized.slice(home.length)}` : normalized;
115
+ }
116
+
117
+ export function stateDirNotice(env: NodeJS.ProcessEnv = process.env): string | null {
118
+ const configBase = huaweiConfigBase(env);
119
+ const stateBase = devkitStateBase(env);
120
+ if (stateBase === configBase) return null;
121
+ return `state directory ${displayStatePath(stateBase, env)} (${displayStatePath(configBase, env)} is not writable; set ${STATE_DIR_ENV} to pin it)`;
122
+ }
123
+
124
+ // Tests swap HUAWEICLOUD_HOME between cases; the cache is keyed by configBase,
125
+ // so this is only for a case that changes permissions under one home.
126
+ export function _resetStateDirCache(): void {
127
+ stateBaseCache.clear();
128
+ }
@@ -246,16 +246,37 @@ async function runApprovedCommand(args: ToolArgs = {}) {
246
246
  );
247
247
  }
248
248
 
249
- const stored = consumeApprovalToken(token);
250
- if (!stored) {
251
- // Defensive: inspectApprovalToken said 'valid' but consume returned null.
252
- // The only path is the O_EXCL claim losing a race — another consumer is
253
- // spending this exact token right now — so classify as already_consumed
254
- // (never a misleading success, never a false not_found).
249
+ // The strict plan is pure, so it is computed before the token is consumed:
250
+ // its userConfirmation.needed decides whether the consume requires a grant,
251
+ // and the result still embeds it.
252
+ const strictPlan = planHcloudCommand(effectiveArgs, { allowWrites: false, mintApprovalToken: false });
253
+
254
+ // One snapshot: the confirmation gate, the args-hash binding, the pinView
255
+ // fallback, and the single-use claim all read the SAME entry — the one
256
+ // consumeApprovalToken returns. The pre-consume inspect-gate this replaces
257
+ // verified the grant on one read while execution consumed another, which
258
+ // a same-user store swap between the two reads laundered (the review's
259
+ // TOCTOU repro).
260
+ const consumed = consumeApprovalToken(token, { requireGrant: strictPlan.userConfirmation.needed });
261
+ if (consumed.status === 'grant_required') {
262
+ return {
263
+ status: 'rejected',
264
+ code: 'USER_CONFIRMATION_REQUIRED',
265
+ nextStep:
266
+ 'Ask the user to run "npx huaweicloud-devkit approve <this approvalToken>" in their own terminal, then retry this exact call.',
267
+ };
268
+ }
269
+ if (consumed.status === 'gone') {
270
+ // Defensive: inspectApprovalToken said 'valid' but consume returned gone.
271
+ // The paths are the O_EXCL claim losing a race (another consumer is
272
+ // spending this exact token right now) or a store swap removing the
273
+ // entry between the two reads — classify via re-inspect, never a
274
+ // misleading success and never a false not_found.
255
275
  const recheck = inspectApprovalToken(token);
256
276
  if (recheck.state === 'expired') return { status: 'rejected', code: 'CONFIRM_TOKEN_EXPIRED' };
257
277
  return { status: 'ok', outcome: 'already_processed' };
258
278
  }
279
+ const stored = consumed.entry;
259
280
  if (hashArgs(effectiveArgs) !== stored.argsHash) {
260
281
  // The pin view is the canonical fold for the substitution comparison
261
282
  // (loop round 4, seat-1 B2): it folds the two-token/glued secret forms
@@ -285,7 +306,6 @@ async function runApprovedCommand(args: ToolArgs = {}) {
285
306
  );
286
307
  }
287
308
  }
288
- const strictPlan = planHcloudCommand(effectiveArgs, { allowWrites: false });
289
309
  const result = await runHcloud(effectiveArgs, {
290
310
  allowWrites: true,
291
311
  timeoutMs: args.timeoutMs,
@@ -422,7 +442,7 @@ export const HUAWEICLOUD_CLI_TOOLS = [
422
442
  {
423
443
  name: 'huaweicloud_plan_cli_command',
424
444
  description:
425
- 'Classify and plan a Huawei Cloud hcloud command without executing it. Vendor-gated (vendorConfirmed): call only when the vendor is established — see the vendorConfirmed parameter description; when unknown, ask which cloud the user means first.',
445
+ "Classify and plan a Huawei Cloud hcloud command without executing it. When the result's userConfirmation.needed is true, the USER must confirm in their own terminal by running the userConfirmation.command line (npx huaweicloud-devkit approve <approvalToken>) before huaweicloud_run_approved_command will accept the command. Vendor-gated (vendorConfirmed): call only when the vendor is established — see the vendorConfirmed parameter description; when unknown, ask which cloud the user means first.",
426
446
  schema: planCliCommandSchema,
427
447
  handler: handlePlanCliCommand,
428
448
  },
@@ -443,7 +463,7 @@ export const HUAWEICLOUD_CLI_TOOLS = [
443
463
  {
444
464
  name: 'huaweicloud_run_approved_command',
445
465
  description:
446
- 'Run a write-capable hcloud command only after the exact command has been shown and explicitly approved by the user. Vendor-gated (vendorConfirmed): call only when the vendor is established — see the vendorConfirmed parameter description; when unknown, ask which cloud the user means first.',
466
+ 'Run a write-capable hcloud command only after the exact command has been shown and explicitly approved by the user, and after the user confirmed the plan token in their own terminal (npx huaweicloud-devkit approve <token>). A non-read command without that terminal confirmation is rejected with USER_CONFIRMATION_REQUIRED and the token stays usable. Vendor-gated (vendorConfirmed): call only when the vendor is established — see the vendorConfirmed parameter description; when unknown, ask which cloud the user means first.',
447
467
  schema: runApprovedCommandSchema,
448
468
  handler: handleRunApprovedCommand,
449
469
  },
@@ -33,7 +33,15 @@ export function installRuntimeDeps(pluginsDir: string): void {
33
33
  stdio: 'pipe',
34
34
  timeout: 120000,
35
35
  };
36
- let r = spawnSync('npm', ['install', '--omit=dev', '--no-audit', '--no-fund'], spawnOpts);
36
+ // A string command, never an args array: args + shell:true is DEP0190 on
37
+ // Node 24 (the shell concatenates args unescaped), and the warning lands
38
+ // on the CLI's own stderr mid-install — deferred by emitWarning, it even
39
+ // surfaced glued to the provisioning prompt (2026-11-10 report #2). The
40
+ // words are static, so the shell concatenation is injection-safe by
41
+ // construction, and shell:true stays load-bearing: it routes npm.cmd on
42
+ // Windows (the #643 EINVAL doctrine).
43
+ const installCommand = 'npm install --omit=dev --no-audit --no-fund';
44
+ let r = spawnSync(installCommand, spawnOpts);
37
45
  const isRetryable = (res: SpawnSyncReturns<unknown>): boolean => {
38
46
  if (res.status === 0) return false;
39
47
  const stderr = asText(res.stderr || '');
@@ -42,12 +50,12 @@ export function installRuntimeDeps(pluginsDir: string): void {
42
50
  if (r.status !== 0 && isRetryable(r)) {
43
51
  console.log(` \x1b[33m[WARN]\x1b[0m npm install hit file-lock error, retrying in 2s...`);
44
52
  sleepSync(2000);
45
- r = spawnSync('npm', ['install', '--omit=dev', '--no-audit', '--no-fund'], spawnOpts);
53
+ r = spawnSync(installCommand, spawnOpts);
46
54
  }
47
55
  if (r.status !== 0 && !isRetryable(r)) {
48
56
  console.log(` \x1b[33m[RETRY]\x1b[0m npm install failed (exit ${r.status}), retrying in 3s...`);
49
57
  sleepSync(3000);
50
- r = spawnSync('npm', ['install', '--omit=dev', '--no-audit', '--no-fund'], spawnOpts);
58
+ r = spawnSync(installCommand, spawnOpts);
51
59
  }
52
60
  const undiciDir = join(pluginsDir, 'node_modules', 'undici');
53
61
  if (r.status === 0 && existsSync(undiciDir)) {
@@ -843,6 +843,21 @@ export function classifyTextCommand(command: unknown, options: ClassifyOptions =
843
843
  };
844
844
  }
845
845
 
846
+ // The approval CLI's terminal-only verbs: `approve` consumes the plan token
847
+ // the user is meant to confirm in their own TTY (PIN-checked), and `pin`
848
+ // enrolls the credential that confirm checks. An agent that runs either
849
+ // from Bash drives the human's channel itself — an enrolled-by-agent PIN
850
+ // owns every later confirmation — so both verbs deny. Matched against the
851
+ // same two shadows as the reveal gate.
852
+ if (shadowCandidates.some((candidate) => matchesAny(candidate, policy.blockedApprovalCliPatterns))) {
853
+ return {
854
+ decision: 'deny',
855
+ risk: 'approval',
856
+ reason:
857
+ "Running the approval CLI from the agent Bash face is blocked: the confirmation must come from the user's own interactive terminal, where the PIN is checked. Ask the user to run the printed npx huaweicloud-devkit approve <token> line themselves (first use: npx huaweicloud-devkit pin, once), then retry the same call.",
858
+ };
859
+ }
860
+
846
861
  // Order-independent reveal pair: `echo secret get <ref> --stdout | xargs
847
862
  // npx huaweicloud-devkit` reorders the argv through xargs while every word
848
863
  // is literal in the text — the patterns above assume bin-before-
@@ -10,6 +10,7 @@ export interface Policy {
10
10
  blockedConfigureSubcommands: string[];
11
11
  blockedSecretOperations: string[];
12
12
  blockedSecretCliPatterns: string[];
13
+ blockedApprovalCliPatterns: string[];
13
14
  writeOperationPrefixes: string[];
14
15
  readOperationPrefixes: string[];
15
16
  readOperationExceptions: string[];
@@ -62,6 +63,7 @@ export function loadPolicy(path: string): Policy {
62
63
  blockedConfigureSubcommands: toStringArray(raw.blockedConfigureSubcommands, 'blockedConfigureSubcommands'),
63
64
  blockedSecretOperations: toStringArray(raw.blockedSecretOperations, 'blockedSecretOperations'),
64
65
  blockedSecretCliPatterns: toStringArray(raw.blockedSecretCliPatterns, 'blockedSecretCliPatterns'),
66
+ blockedApprovalCliPatterns: toStringArray(raw.blockedApprovalCliPatterns, 'blockedApprovalCliPatterns'),
65
67
  writeOperationPrefixes,
66
68
  readOperationPrefixes: toStringArray(raw.readOperationPrefixes, 'readOperationPrefixes'),
67
69
  readOperationExceptions: toStringArray(raw.readOperationExceptions, 'readOperationExceptions'),
@@ -35,6 +35,7 @@ import { cmdProxy } from './proxy/cli.ts';
35
35
  import { removeKooCli, removeObsConfig } from './sandbox/uninstall-cleanup.ts';
36
36
  import { readReceipt, removeReceipt } from './dep/receipts.ts';
37
37
  import { runSecretCommand } from './lib/secret-vault/cli.ts';
38
+ import { createProcessApproveIo, runApproveCommand, runPinCommand } from './approvals-cli.ts';
38
39
  import { custodyReport } from './lib/secret-vault/custody.ts';
39
40
  import { vaultList } from './lib/secret-vault/store.ts';
40
41
  import { detectCodeartsSandbox } from './codearts-sandbox.ts';
@@ -45,6 +46,7 @@ import { queryDistTagsFetch, determineTarget, semverCompare } from './update-che
45
46
  import { getKooCliVersion, compareVersion, kooCliDownloadBase } from './koocli-version.ts';
46
47
  import { hcloudProbeNextStep, hcloudProbeRaw, probeHcloud } from './hcloud-probe.ts';
47
48
  import { asRecord } from './lib/as-record.ts';
49
+ import { devkitStateBase, displayStatePath, huaweiConfigBase, probeWritableDir } from './lib/state-dir.ts';
48
50
  import { DEPENDENCIES, DEPENDENCY_IDS, requiredDependencies, type DependencyId } from './lib/dependency-model.ts';
49
51
  import { resolveDependencyCommand } from './lib/dep-resolve.ts';
50
52
  // The installer's payload machinery: file ops, server payload placement,
@@ -923,6 +925,26 @@ async function cmdDoctor(): Promise<void> {
923
925
  const nodeOk = nodeParts[0]! > 22 || (nodeParts[0]! === 22 && nodeParts[1]! >= 19);
924
926
  check('Node.js >= 22.19', nodeOk, 'Run: nvm install 22.19 && nvm use 22.19');
925
927
 
928
+ // State directory — gateway pack state, approval tokens, S1 writes and
929
+ // update state all write here. A read-only home falls back to an
930
+ // agent-owned dir (state-dir.ts); the fallback is a warning, not a failure.
931
+ const configBase = huaweiConfigBase();
932
+ const stateBase = devkitStateBase();
933
+ const stateDisplay = displayStatePath(stateBase);
934
+ if (stateBase === configBase) {
935
+ check(
936
+ `State directory writable (${stateDisplay})`,
937
+ probeWritableDir(stateBase),
938
+ 'Fix permissions, or set HUAWEICLOUD_STATE_DIR to a writable path',
939
+ );
940
+ } else if (probeWritableDir(stateBase)) {
941
+ ctx.warn(
942
+ `State directory fallback: ${stateDisplay} (${displayStatePath(configBase)} is not writable; set HUAWEICLOUD_STATE_DIR to pin it)`,
943
+ );
944
+ } else {
945
+ check(`State directory writable (${stateDisplay})`, false, 'Set HUAWEICLOUD_STATE_DIR to a writable path');
946
+ }
947
+
926
948
  // MCP server — derived from the per-row doctor bindings (one membership
927
949
  // table for every payload check in this doctor run). The bindings run the
928
950
  // pure triple probes here; their native-freshness halves run late, after
@@ -1482,6 +1504,12 @@ async function main(): Promise<void> {
1482
1504
  case 'secret':
1483
1505
  process.exitCode = runSecretCommand(process.argv.slice(3));
1484
1506
  break;
1507
+ case 'approve':
1508
+ process.exitCode = await runApproveCommand(process.argv.slice(3), createProcessApproveIo());
1509
+ break;
1510
+ case 'pin':
1511
+ process.exitCode = await runPinCommand(process.argv.slice(3), createProcessApproveIo());
1512
+ break;
1485
1513
  case 'proxy':
1486
1514
  await cmdProxy();
1487
1515
  break;
@@ -165,6 +165,22 @@ export function toolSchemaEntries(): Array<[ToolName, LooseToolSchema]> {
165
165
  return Object.entries(TOOL_SCHEMAS) as Array<[ToolName, LooseToolSchema]>;
166
166
  }
167
167
 
168
+ const argKeyCache = new Map<ToolName, ReadonlySet<string>>();
169
+
170
+ // The keys a tool's input schema declares, plus the central vendorConfirmed
171
+ // part (rendered only on cloud-facing tools but accepted by the dispatch gate
172
+ // everywhere). callTool's unknown-parameter warning reads this; the #530
173
+ // pass-through leniency itself is unchanged.
174
+ export function toolArgKeys(name: ToolName): ReadonlySet<string> {
175
+ const cached = argKeyCache.get(name);
176
+ if (cached) return cached;
177
+ const def = (TOOL_SCHEMAS[name] as unknown as { _zod?: { def?: { shape?: Record<string, unknown> } } })._zod?.def;
178
+ const keys = new Set<string>(Object.keys(def?.shape ?? {}));
179
+ keys.add('vendorConfirmed');
180
+ argKeyCache.set(name, keys);
181
+ return keys;
182
+ }
183
+
168
184
  // Runtime guard: every entry must be a constructed zod loose-object. A bare
169
185
  // raw shape would be wrapped by the SDK into STRIP semantics, silently
170
186
  // dropping client keys instead of passing them through.
@@ -36,12 +36,14 @@ import { PACK_TOOL_HANDLERS, isPackToolName, type PackToolName } from './packs/r
36
36
  // the build-time --check stray scan, and validate-package's skill gate all
37
37
  // hold one membership predicate (dir-or-symlink with a SKILL.md).
38
38
  import { listSkillDirs } from './lib/skill-tree.ts';
39
+ import { attachParamWarnings, unknownParamWarnings } from './lib/param-warnings.ts';
39
40
  import { recordToolCall, traceEnabled } from './lib/call-trace.ts';
40
41
  // The tool name/description registry (TOOL_DEFINITIONS_LITERALS and its
41
42
  // derived types) lives in tool-definitions.ts; this module keeps the
42
43
  // re-export face every importer (mcp-protocol, tests, scripts) already
43
44
  // targets — same exported names, same import path, same behavior.
44
45
  import { TOOL_DEFINITIONS, type ToolName } from './tool-definitions.ts';
46
+ import { toolArgKeys } from './tool-schemas.ts';
45
47
  // The vendorConfirmed gate (VENDOR_GATED_TOOLS, the gate/challenge
46
48
  // messages, and the once-per-session challenge state) lives in
47
49
  // vendor-gate.ts; this module re-exports the roster for its existing
@@ -237,15 +239,19 @@ export async function callTool(name: ToolName, rawArgs: ToolArgs = {}, opts: Cal
237
239
  const args = normalizeNumericArgs(rawArgs);
238
240
  const toolValue = toolInvokeValue(name, args);
239
241
  trackToolInvoke(name, toolValue);
242
+ // Unknown keys stay accepted (#530 leniency) but are no longer silent: a
243
+ // typo'd optional parameter would otherwise return a default-shaped result
244
+ // the model reads as a successful filter.
245
+ const paramWarnings = unknownParamWarnings(args, toolArgKeys(name));
240
246
 
241
247
  // Trace sits between normalization and dispatch: it records the shape
242
248
  // the handler will actually see, and only calls that reached dispatch —
243
249
  // SDK-level zod rejects never get here (see lib/call-trace.ts contract).
244
- if (!traceEnabled()) return dispatchTool(name, args, opts);
250
+ if (!traceEnabled()) return attachParamWarnings(await dispatchTool(name, args, opts), paramWarnings);
245
251
  try {
246
252
  const result = await dispatchTool(name, args, opts);
247
253
  recordToolCall(name, args, true);
248
- return result;
254
+ return attachParamWarnings(result, paramWarnings);
249
255
  } catch (error) {
250
256
  recordToolCall(name, args, false, error);
251
257
  throw error;
@@ -318,12 +324,15 @@ function hookResult(result: RiskEvaluation) {
318
324
  ok: result.decision !== 'deny',
319
325
  decision: result.decision,
320
326
  findings: result.findings,
327
+ // allow means "no rule matched", never "approved": make that explicit so
328
+ // an agent cannot read a green advisory check as a safety verdict.
329
+ ...(result.decision === 'allow' ? { unmatched: true } : {}),
321
330
  nextStep:
322
331
  result.decision === 'deny'
323
332
  ? 'Revise the command, artifact, or deployment plan before execution.'
324
333
  : result.decision === 'warn'
325
334
  ? 'Review the warnings with the user before proceeding.'
326
- : 'No Huawei Cloud hook risk rule matched.',
335
+ : 'No Huawei Cloud hook risk rule matched. This is not a safety verdict or an approval.',
327
336
  };
328
337
  }
329
338
 
@@ -339,7 +348,10 @@ function hookResult(result: RiskEvaluation) {
339
348
  // cn hint, and a real service or a missing catalog keeps the original wording.
340
349
  // The run faces stay allow for everything but the triage's negative-evidence
341
350
  // deny (refined at planHcloudCommand, which the run engine asserts), and the
342
- // PreToolUse hook is untouched (it acts on deny alone).
351
+ // PreToolUse hook is untouched (it acts on deny alone). The same face upgrades
352
+ // classified write/execution operations to hwc-write-operation: the advisory
353
+ // signal that a write needs the plan + approval path, never an execution
354
+ // block (run_readonly_command and the approval chain own that decision).
343
355
  // `classify` is injectable so the OBS-14-shape closure is honestly pinnable:
344
356
  // a classifier crash used to fall through to the bare allow (silent fail-open,
345
357
  // the #564 shape one layer up); it now degrades to an hwc-unverified-command
@@ -372,6 +384,21 @@ const unverifiedFinding = (command: string): RiskFinding => ({
372
384
  evidence: command.slice(0, 240),
373
385
  });
374
386
 
387
+ const writeOperationFinding = (command: string): RiskFinding => ({
388
+ ruleId: 'hwc-write-operation',
389
+ title: 'Write or execution operation',
390
+ category: 'approval',
391
+ severity: 'warn',
392
+ message:
393
+ 'This command is classified as a write or execution operation. Raw shell execution is blocked; ' +
394
+ 'writes require a plan and explicit user approval.',
395
+ remediation:
396
+ 'Plan the exact command with huaweicloud_plan_cli_command, show it to the user, obtain explicit approval, ' +
397
+ 'then run it with huaweicloud_run_approved_command and the approval token.',
398
+ source: 'command',
399
+ evidence: command.slice(0, 240),
400
+ });
401
+
375
402
  export function withUnknownOperationWarn(
376
403
  command: string,
377
404
  result: RiskEvaluation,
@@ -384,6 +411,14 @@ export function withUnknownOperationWarn(
384
411
  } catch {
385
412
  return { ...result, decision: 'warn', findings: [unverifiedFinding(command)] };
386
413
  }
414
+ // The advisory face never turns a write into "safe": classified writes and
415
+ // execution operations get a warn even when the pattern catalog has no
416
+ // specific finding. The enforcement faces (run_readonly_command, the
417
+ // PreToolUse hook, the plan/run approval chain) are unchanged — this is
418
+ // the pre-flight signal, not the gate.
419
+ if (classification?.risk === 'write' || classification?.risk === 'execution') {
420
+ return { ...result, decision: 'warn', findings: [writeOperationFinding(command)] };
421
+ }
387
422
  if (classification?.risk !== 'unknown_read') return result;
388
423
  const triage = triageUnknownService(classification.service);
389
424
  if (triage.cause === 'service-not-found' || triage.cause === 'lang-missing') {
@@ -70,7 +70,11 @@ export function queryDistTagsSync({
70
70
  cwd,
71
71
  }: { timeoutMs?: number; cwd?: string } = {}): DistTags | null {
72
72
  try {
73
- const result = spawnSync(NPM_BIN, ['view', 'huaweicloud-devkit', 'dist-tags', '--json'], {
73
+ // String command, never an args array: args + shell:true is DEP0190 on
74
+ // Node 24, and the words are static so the shell concatenation is
75
+ // injection-safe. shell:true stays load-bearing: it routes npm.cmd on
76
+ // Windows (the #643 EINVAL doctrine below).
77
+ const result = spawnSync(`${NPM_BIN} view huaweicloud-devkit dist-tags --json`, {
74
78
  encoding: 'utf8',
75
79
  timeout: timeoutMs,
76
80
  windowsHide: true,
@@ -105,7 +109,9 @@ export function queryDistTags({
105
109
  return new Promise<DistTags | null>((resolve) => {
106
110
  let child: ChildProcessWithoutNullStreams;
107
111
  try {
108
- child = spawn(NPM_BIN, ['view', 'huaweicloud-devkit', 'dist-tags', '--json'], {
112
+ // Same string-command doctrine as queryDistTagsSync: no args array
113
+ // under shell (DEP0190 on Node 24), static words only.
114
+ child = spawn(`${NPM_BIN} view huaweicloud-devkit dist-tags --json`, {
109
115
  windowsHide: true,
110
116
  cwd,
111
117
  shell: true,
@@ -1,12 +1,12 @@
1
1
  // Skip-state (dismiss) persistence for the update machinery: the plugin-local
2
- // skip file with per-session suffixing (#607), the HUAWEICLOUD_HOME fallback,
3
- // and the atomic read/write pair. Part of the src/update-* family behind the
4
- // src/update-check.ts re-export face.
2
+ // skip file with per-session suffixing (#607), the writable-state-tree
3
+ // fallback, and the atomic read/write pair. Part of the src/update-* family
4
+ // behind the src/update-check.ts re-export face.
5
5
  import { existsSync, readFileSync, writeFileSync, renameSync, mkdirSync, rmSync } from 'node:fs';
6
6
  import { join, dirname, resolve } from 'node:path';
7
- import { homedir } from 'node:os';
8
7
 
9
8
  import { asText } from './lib/as-text.ts';
9
+ import { devkitStateBase } from './lib/pack-state.ts';
10
10
  import { selfDir } from './update-installed.ts';
11
11
 
12
12
  const COOLDOWN_DAYS = 3;
@@ -22,8 +22,7 @@ export function skipFilePath(): string {
22
22
  }
23
23
 
24
24
  export function fallbackSkipFilePath(): string {
25
- const base = process.env.HUAWEICLOUD_HOME || homedir();
26
- return join(base, '.config', 'huaweicloud', 'devkit-skip.json');
25
+ return join(devkitStateBase(), 'devkit-skip.json');
27
26
  }
28
27
 
29
28
  // 会话化 skip 文件:remote 多会话按 sessionId 拆分,stdio/默认保持原文件(向后兼容)。
@@ -30,7 +30,14 @@ function defaultSpawn(
30
30
  args: readonly string[],
31
31
  options: SpawnSyncOptionsWithStringEncoding,
32
32
  ): SpawnResultLike {
33
- return spawnSync(command, args, options);
33
+ // The args join into the command string before the spawn: options carries
34
+ // shell:true (the #643 npm.cmd routing; the target interpolation stays
35
+ // guarded by the SUPPORTED_AGENT_TARGETS allowlist, review #717), and an
36
+ // args array under shell is DEP0190 on Node 24. shell:true already
37
+ // concatenates args unescaped, so the join is behavior-identical minus
38
+ // the warning; the seam's (command, args) contract is unchanged for the
39
+ // injected test doubles.
40
+ return spawnSync([command, ...args].join(' '), options);
34
41
  }
35
42
 
36
43
  function restartMessage(target: string): string {