huaweicloud-devkit 2.0.0-next.1 → 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 (33) 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/auth/s1-store.js +43 -22
  11. package/plugins/huaweicloud-core/dist/lib/approval-tokens.js +3 -3
  12. package/plugins/huaweicloud-core/dist/lib/pack-state.js +23 -19
  13. package/plugins/huaweicloud-core/dist/lib/param-warnings.js +70 -0
  14. package/plugins/huaweicloud-core/dist/lib/state-dir.js +125 -0
  15. package/plugins/huaweicloud-core/dist/mcp-server.js +763 -567
  16. package/plugins/huaweicloud-core/dist/mcp-server.js.map +4 -4
  17. package/plugins/huaweicloud-core/dist/setup-cli.js +16 -0
  18. package/plugins/huaweicloud-core/dist/tool-schemas.js +15 -0
  19. package/plugins/huaweicloud-core/dist/tools.js +36 -4
  20. package/plugins/huaweicloud-core/dist/update-skip.js +5 -6
  21. package/plugins/huaweicloud-core/openclaw.plugin.json +1 -1
  22. package/plugins/huaweicloud-core/safety/rules/cloud-risk-rules.json +78 -2
  23. package/plugins/huaweicloud-core/src/agents/codearts-work.ts +3 -0
  24. package/plugins/huaweicloud-core/src/agents/codearts.ts +4 -0
  25. package/plugins/huaweicloud-core/src/auth/s1-store.ts +41 -20
  26. package/plugins/huaweicloud-core/src/lib/approval-tokens.ts +3 -3
  27. package/plugins/huaweicloud-core/src/lib/pack-state.ts +23 -20
  28. package/plugins/huaweicloud-core/src/lib/param-warnings.ts +69 -0
  29. package/plugins/huaweicloud-core/src/lib/state-dir.ts +128 -0
  30. package/plugins/huaweicloud-core/src/setup-cli.ts +21 -0
  31. package/plugins/huaweicloud-core/src/tool-schemas.ts +16 -0
  32. package/plugins/huaweicloud-core/src/tools.ts +39 -4
  33. package/plugins/huaweicloud-core/src/update-skip.ts +5 -6
@@ -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
+ }
@@ -46,6 +46,7 @@ import { queryDistTagsFetch, determineTarget, semverCompare } from './update-che
46
46
  import { getKooCliVersion, compareVersion, kooCliDownloadBase } from './koocli-version.ts';
47
47
  import { hcloudProbeNextStep, hcloudProbeRaw, probeHcloud } from './hcloud-probe.ts';
48
48
  import { asRecord } from './lib/as-record.ts';
49
+ import { devkitStateBase, displayStatePath, huaweiConfigBase, probeWritableDir } from './lib/state-dir.ts';
49
50
  import { DEPENDENCIES, DEPENDENCY_IDS, requiredDependencies, type DependencyId } from './lib/dependency-model.ts';
50
51
  import { resolveDependencyCommand } from './lib/dep-resolve.ts';
51
52
  // The installer's payload machinery: file ops, server payload placement,
@@ -924,6 +925,26 @@ async function cmdDoctor(): Promise<void> {
924
925
  const nodeOk = nodeParts[0]! > 22 || (nodeParts[0]! === 22 && nodeParts[1]! >= 19);
925
926
  check('Node.js >= 22.19', nodeOk, 'Run: nvm install 22.19 && nvm use 22.19');
926
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
+
927
948
  // MCP server — derived from the per-row doctor bindings (one membership
928
949
  // table for every payload check in this doctor run). The bindings run the
929
950
  // pure triple probes here; their native-freshness halves run late, after
@@ -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') {
@@ -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/默认保持原文件(向后兼容)。