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
@@ -25,6 +25,7 @@ import { queryDistTagsFetch, determineTarget, semverCompare } from "./update-che
25
25
  import { getKooCliVersion, compareVersion, kooCliDownloadBase } from "./koocli-version.js";
26
26
  import { hcloudProbeNextStep, hcloudProbeRaw, probeHcloud } from "./hcloud-probe.js";
27
27
  import { asRecord } from "./lib/as-record.js";
28
+ import { devkitStateBase, displayStatePath, huaweiConfigBase, probeWritableDir } from "./lib/state-dir.js";
28
29
  import { DEPENDENCIES, DEPENDENCY_IDS, requiredDependencies } from "./lib/dependency-model.js";
29
30
  import { resolveDependencyCommand } from "./lib/dep-resolve.js";
30
31
  // The installer's payload machinery: file ops, server payload placement,
@@ -765,6 +766,21 @@ async function cmdDoctor() {
765
766
  const nodeParts = process.versions.node.split('.').map(Number);
766
767
  const nodeOk = nodeParts[0] > 22 || (nodeParts[0] === 22 && nodeParts[1] >= 19);
767
768
  check('Node.js >= 22.19', nodeOk, 'Run: nvm install 22.19 && nvm use 22.19');
769
+ // State directory — gateway pack state, approval tokens, S1 writes and
770
+ // update state all write here. A read-only home falls back to an
771
+ // agent-owned dir (state-dir.ts); the fallback is a warning, not a failure.
772
+ const configBase = huaweiConfigBase();
773
+ const stateBase = devkitStateBase();
774
+ const stateDisplay = displayStatePath(stateBase);
775
+ if (stateBase === configBase) {
776
+ check(`State directory writable (${stateDisplay})`, probeWritableDir(stateBase), 'Fix permissions, or set HUAWEICLOUD_STATE_DIR to a writable path');
777
+ }
778
+ else if (probeWritableDir(stateBase)) {
779
+ ctx.warn(`State directory fallback: ${stateDisplay} (${displayStatePath(configBase)} is not writable; set HUAWEICLOUD_STATE_DIR to pin it)`);
780
+ }
781
+ else {
782
+ check(`State directory writable (${stateDisplay})`, false, 'Set HUAWEICLOUD_STATE_DIR to a writable path');
783
+ }
768
784
  // MCP server — derived from the per-row doctor bindings (one membership
769
785
  // table for every payload check in this doctor run). The bindings run the
770
786
  // pure triple probes here; their native-freshness halves run late, after
@@ -142,6 +142,21 @@ export function getToolSchema(name) {
142
142
  export function toolSchemaEntries() {
143
143
  return Object.entries(TOOL_SCHEMAS);
144
144
  }
145
+ const argKeyCache = new Map();
146
+ // The keys a tool's input schema declares, plus the central vendorConfirmed
147
+ // part (rendered only on cloud-facing tools but accepted by the dispatch gate
148
+ // everywhere). callTool's unknown-parameter warning reads this; the #530
149
+ // pass-through leniency itself is unchanged.
150
+ export function toolArgKeys(name) {
151
+ const cached = argKeyCache.get(name);
152
+ if (cached)
153
+ return cached;
154
+ const def = TOOL_SCHEMAS[name]._zod?.def;
155
+ const keys = new Set(Object.keys(def?.shape ?? {}));
156
+ keys.add('vendorConfirmed');
157
+ argKeyCache.set(name, keys);
158
+ return keys;
159
+ }
145
160
  // Runtime guard: every entry must be a constructed zod loose-object. A bare
146
161
  // raw shape would be wrapped by the SDK into STRIP semantics, silently
147
162
  // dropping client keys instead of passing them through.
@@ -25,12 +25,14 @@ import { PACK_TOOL_HANDLERS, isPackToolName } from "./packs/registry.js";
25
25
  // the build-time --check stray scan, and validate-package's skill gate all
26
26
  // hold one membership predicate (dir-or-symlink with a SKILL.md).
27
27
  import { listSkillDirs } from "./lib/skill-tree.js";
28
+ import { attachParamWarnings, unknownParamWarnings } from "./lib/param-warnings.js";
28
29
  import { recordToolCall, traceEnabled } from "./lib/call-trace.js";
29
30
  // The tool name/description registry (TOOL_DEFINITIONS_LITERALS and its
30
31
  // derived types) lives in tool-definitions.ts; this module keeps the
31
32
  // re-export face every importer (mcp-protocol, tests, scripts) already
32
33
  // targets — same exported names, same import path, same behavior.
33
34
  import { TOOL_DEFINITIONS } from "./tool-definitions.js";
35
+ import { toolArgKeys } from "./tool-schemas.js";
34
36
  // The vendorConfirmed gate (VENDOR_GATED_TOOLS, the gate/challenge
35
37
  // messages, and the once-per-session challenge state) lives in
36
38
  // vendor-gate.ts; this module re-exports the roster for its existing
@@ -101,15 +103,19 @@ export async function callTool(name, rawArgs = {}, opts = {}) {
101
103
  const args = normalizeNumericArgs(rawArgs);
102
104
  const toolValue = toolInvokeValue(name, args);
103
105
  trackToolInvoke(name, toolValue);
106
+ // Unknown keys stay accepted (#530 leniency) but are no longer silent: a
107
+ // typo'd optional parameter would otherwise return a default-shaped result
108
+ // the model reads as a successful filter.
109
+ const paramWarnings = unknownParamWarnings(args, toolArgKeys(name));
104
110
  // Trace sits between normalization and dispatch: it records the shape
105
111
  // the handler will actually see, and only calls that reached dispatch —
106
112
  // SDK-level zod rejects never get here (see lib/call-trace.ts contract).
107
113
  if (!traceEnabled())
108
- return dispatchTool(name, args, opts);
114
+ return attachParamWarnings(await dispatchTool(name, args, opts), paramWarnings);
109
115
  try {
110
116
  const result = await dispatchTool(name, args, opts);
111
117
  recordToolCall(name, args, true);
112
- return result;
118
+ return attachParamWarnings(result, paramWarnings);
113
119
  }
114
120
  catch (error) {
115
121
  recordToolCall(name, args, false, error);
@@ -180,11 +186,14 @@ function hookResult(result) {
180
186
  ok: result.decision !== 'deny',
181
187
  decision: result.decision,
182
188
  findings: result.findings,
189
+ // allow means "no rule matched", never "approved": make that explicit so
190
+ // an agent cannot read a green advisory check as a safety verdict.
191
+ ...(result.decision === 'allow' ? { unmatched: true } : {}),
183
192
  nextStep: result.decision === 'deny'
184
193
  ? 'Revise the command, artifact, or deployment plan before execution.'
185
194
  : result.decision === 'warn'
186
195
  ? 'Review the warnings with the user before proceeding.'
187
- : 'No Huawei Cloud hook risk rule matched.',
196
+ : 'No Huawei Cloud hook risk rule matched. This is not a safety verdict or an approval.',
188
197
  };
189
198
  }
190
199
  // The advisory command face used to answer a bare allow for an hcloud command
@@ -199,7 +208,10 @@ function hookResult(result) {
199
208
  // cn hint, and a real service or a missing catalog keeps the original wording.
200
209
  // The run faces stay allow for everything but the triage's negative-evidence
201
210
  // deny (refined at planHcloudCommand, which the run engine asserts), and the
202
- // PreToolUse hook is untouched (it acts on deny alone).
211
+ // PreToolUse hook is untouched (it acts on deny alone). The same face upgrades
212
+ // classified write/execution operations to hwc-write-operation: the advisory
213
+ // signal that a write needs the plan + approval path, never an execution
214
+ // block (run_readonly_command and the approval chain own that decision).
203
215
  // `classify` is injectable so the OBS-14-shape closure is honestly pinnable:
204
216
  // a classifier crash used to fall through to the bare allow (silent fail-open,
205
217
  // the #564 shape one layer up); it now degrades to an hwc-unverified-command
@@ -227,6 +239,18 @@ const unverifiedFinding = (command) => ({
227
239
  source: 'command',
228
240
  evidence: command.slice(0, 240),
229
241
  });
242
+ const writeOperationFinding = (command) => ({
243
+ ruleId: 'hwc-write-operation',
244
+ title: 'Write or execution operation',
245
+ category: 'approval',
246
+ severity: 'warn',
247
+ message: 'This command is classified as a write or execution operation. Raw shell execution is blocked; ' +
248
+ 'writes require a plan and explicit user approval.',
249
+ remediation: 'Plan the exact command with huaweicloud_plan_cli_command, show it to the user, obtain explicit approval, ' +
250
+ 'then run it with huaweicloud_run_approved_command and the approval token.',
251
+ source: 'command',
252
+ evidence: command.slice(0, 240),
253
+ });
230
254
  export function withUnknownOperationWarn(command, result, classify = classifyTextCommand) {
231
255
  if (result.decision !== 'allow' || result.findings.length > 0 || !command.trim())
232
256
  return result;
@@ -237,6 +261,14 @@ export function withUnknownOperationWarn(command, result, classify = classifyTex
237
261
  catch {
238
262
  return { ...result, decision: 'warn', findings: [unverifiedFinding(command)] };
239
263
  }
264
+ // The advisory face never turns a write into "safe": classified writes and
265
+ // execution operations get a warn even when the pattern catalog has no
266
+ // specific finding. The enforcement faces (run_readonly_command, the
267
+ // PreToolUse hook, the plan/run approval chain) are unchanged — this is
268
+ // the pre-flight signal, not the gate.
269
+ if (classification?.risk === 'write' || classification?.risk === 'execution') {
270
+ return { ...result, decision: 'warn', findings: [writeOperationFinding(command)] };
271
+ }
240
272
  if (classification?.risk !== 'unknown_read')
241
273
  return result;
242
274
  const triage = triageUnknownService(classification.service);
@@ -1,19 +1,18 @@
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
  import { asText } from "./lib/as-text.js";
8
+ import { devkitStateBase } from "./lib/pack-state.js";
9
9
  import { selfDir } from "./update-installed.js";
10
10
  const COOLDOWN_DAYS = 3;
11
11
  export function skipFilePath() {
12
12
  return join(resolve(selfDir(), '..'), '.update-skip.json');
13
13
  }
14
14
  export function fallbackSkipFilePath() {
15
- const base = process.env.HUAWEICLOUD_HOME || homedir();
16
- return join(base, '.config', 'huaweicloud', 'devkit-skip.json');
15
+ return join(devkitStateBase(), 'devkit-skip.json');
17
16
  }
18
17
  // 会话化 skip 文件:remote 多会话按 sessionId 拆分,stdio/默认保持原文件(向后兼容)。
19
18
  function sanitizeSessionId(sessionId) {
@@ -2,7 +2,7 @@
2
2
  "name": "huaweicloud-devkit",
3
3
  "id": "huaweicloud-devkit",
4
4
  "displayName": "HuaweiCloud DevKit",
5
- "version": "2.0.0-next.1",
5
+ "version": "2.0.0-next.2",
6
6
  "family": "bundle-plugin",
7
7
  "bundleFormat": "codex",
8
8
  "description": "Guide coding agents to use Huawei Cloud safely — KooCLI, APIs, SDKs, 40 MCP tools, skills, and safety guardrails.",
@@ -182,6 +182,61 @@
182
182
  "message": "The artifact contains a literal access key, secret key, or security token. Credentials committed to IaC, config, or code leak through git history, logs, and state files.",
183
183
  "remediation": "Remove the literal credential: reference it from environment variables, a DEW CSMS secret reference, or the platform credential vault (huaweicloud_secret_set), and rotate the exposed key immediately."
184
184
  },
185
+ {
186
+ "id": "hwc-artifact-plaintext-password",
187
+ "title": "Plaintext password in artifact",
188
+ "category": "secret",
189
+ "severity": "warn",
190
+ "stages": ["artifact", "deploy_plan"],
191
+ "match": {
192
+ "any": [
193
+ {
194
+ "field": "text",
195
+ "regex": "[A-Za-z0-9_.-]*(?:password|passwd|pwd|secret)(?!://)[\"']?\\s*[:=]\\s*[\"']?(?!(?:<|\\$|%|\\{\\{|#\\{|secret://|var\\.|local\\.|module\\.|data\\.|each\\.|path\\.|terraform\\.|env\\.|os\\.environ|process\\.env|\\*{3,}|changeme|change_me|placeholder|example|xxx|none|N/A))[^\\s\"'<>]{3,}"
196
+ },
197
+ {
198
+ "field": "text",
199
+ "regex": "<(?:password|passwd|pwd)[^>]*>\\s*(?!(?:<|\\$|%|\\{\\{|#\\{|secret://|\\*{3,}|changeme|change_me|placeholder|example|xxx|none|N/A))[^<\\s][^<]{2,}\\s*</(?:password|passwd|pwd)>"
200
+ }
201
+ ]
202
+ },
203
+ "message": "The artifact or plan carries what looks like a plaintext password or secret value.",
204
+ "remediation": "Replace the literal with a secret reference (DEW CSMS, huaweicloud_secret_set, ${VAR}, or var.<name>) and rotate any value that was committed."
205
+ },
206
+ {
207
+ "id": "hwc-container-privileged",
208
+ "title": "Privileged container",
209
+ "category": "container",
210
+ "severity": "deny",
211
+ "stages": ["artifact", "deploy_plan"],
212
+ "match": {
213
+ "any": [
214
+ {
215
+ "field": "text",
216
+ "regex": "\\bprivileged[\"']?\\s*[:=]\\s*[\"']?true\\b"
217
+ }
218
+ ]
219
+ },
220
+ "message": "The manifest or plan runs a container with privileged: true (host devices and capabilities).",
221
+ "remediation": "Drop privileged mode. Grant only the specific capabilities the workload needs (capabilities.add) and run as a non-root user."
222
+ },
223
+ {
224
+ "id": "hwc-container-privilege-escalation",
225
+ "title": "Container privilege escalation allowed",
226
+ "category": "container",
227
+ "severity": "warn",
228
+ "stages": ["artifact", "deploy_plan"],
229
+ "match": {
230
+ "any": [
231
+ {
232
+ "field": "text",
233
+ "regex": "\\ballowPrivilegeEscalation[\"']?\\s*[:=]\\s*[\"']?true\\b"
234
+ }
235
+ ]
236
+ },
237
+ "message": "The manifest allows a process to gain more privileges than its parent (allowPrivilegeEscalation: true).",
238
+ "remediation": "Set allowPrivilegeEscalation: false and runAsNonRoot: true unless the workload provably requires escalation."
239
+ },
185
240
  {
186
241
  "id": "hwc-obs-anonymous-write",
187
242
  "title": "OBS anonymous write",
@@ -244,17 +299,38 @@
244
299
  },
245
300
  {
246
301
  "field": "text",
247
- "regex": "(\\\"Action\\\"\\s*:\\s*(\\\"(\\*|\\*:\\*)\\\"|\\[\\s*\\\"(\\*|\\*:\\*)\\\")|Action\\s*[=:]\\s*(\\*|\\*:\\*)|AdministratorAccess|FullAccess)"
302
+ "regex": "(\\\"Action\\\"\\s*:\\s*(\\\"(\\*|\\*:\\*)\\\"|\\[\\s*\\\"(\\*|\\*:\\*)\\\")|Action\\s*[=:]\\s*(\\*|\\*:\\*)|[\"']?actions?[\"']?\\s*[=:]\\s*(?:\\[\\s*)?[\"']?(?:\\*|\\*:\\*)|AdministratorAccess|FullAccess)"
248
303
  },
249
304
  {
250
305
  "field": "text",
251
- "regex": "(\\\"Effect\\\"\\s*:\\s*\\\"Allow\\\"|Effect\\s*[=:]\\s*Allow)"
306
+ "regex": "(\\\"Effect\\\"\\s*:\\s*\\\"Allow\\\"|Effect\\s*[=:]\\s*[\"']?Allow[\"']?)"
252
307
  }
253
308
  ]
254
309
  },
255
310
  "message": "The change appears to grant broad administrator permissions.",
256
311
  "remediation": "Use least-privilege service actions, resource constraints, and short-lived credentials for generated application workflows."
257
312
  },
313
+ {
314
+ "id": "hwc-iam-wildcard-action",
315
+ "title": "Wildcard IAM action",
316
+ "category": "iam",
317
+ "severity": "warn",
318
+ "stages": ["command", "artifact", "deploy_plan"],
319
+ "match": {
320
+ "all": [
321
+ {
322
+ "field": "text",
323
+ "regex": "(IAM|policy|role|agency|Statement|Action|actions)"
324
+ },
325
+ {
326
+ "field": "text",
327
+ "regex": "[\"']?(?:Action|actions?)[\"']?\\s*[:=]\\s*(?:\\[\\s*)?[\"']?(?:\\*|\\*:\\*)[\"']?"
328
+ }
329
+ ]
330
+ },
331
+ "message": "The IAM grant uses a wildcard action (* or *:*), which grants every operation on the matched resources.",
332
+ "remediation": "Replace the wildcard with the least-privilege service actions the workflow actually calls, and constrain the resources."
333
+ },
258
334
  {
259
335
  "id": "hwc-iam-highrisk-write",
260
336
  "title": "High-risk IAM write operation",
@@ -12,6 +12,7 @@ import { mergeCommandStyle, applyUserDelta, inheritPeerUserEnv } from '../mcp-co
12
12
  import { takeAgentDelta } from '../mcp-config-backup.ts';
13
13
  import { printMcpConfigStatus, readJsonRecord, removeMcpServerEntry, writeMcpSettingsFile } from '../mcp-config-io.ts';
14
14
  import { asRecord } from '../lib/as-record.ts';
15
+ import { stateDirNotice } from '../lib/state-dir.ts';
15
16
  import {
16
17
  copyServerPayload,
17
18
  installRuntimeDeps,
@@ -112,6 +113,8 @@ export async function deployCodeArtsWork(_mode: DeployMode): Promise<void> {
112
113
  const pluginDest = codeartsWorkPluginsDir();
113
114
 
114
115
  copyServerPayload(pluginDest);
116
+ const stateNotice = stateDirNotice();
117
+ if (stateNotice) console.log(` [CodeArts Work] ${stateNotice}`);
115
118
  registerCodeartsWorkMcp();
116
119
 
117
120
  installRuntimeDeps(pluginDest);
@@ -14,6 +14,7 @@ import {
14
14
  } from '../targets.ts';
15
15
  import { findHcloudBin } from '../hcloud-probe.ts';
16
16
  import { asRecord } from '../lib/as-record.ts';
17
+ import { stateDirNotice } from '../lib/state-dir.ts';
17
18
  import { ensureMcpServersConfig, printMcpConfigStatus, removeMcpServerEntry } from '../mcp-config-io.ts';
18
19
  import {
19
20
  PACKAGE_ROOT,
@@ -54,6 +55,9 @@ export async function deployCodeArts(mode: DeployMode): Promise<void> {
54
55
 
55
56
  copyServerPayload(pluginDest);
56
57
 
58
+ const stateNotice = stateDirNotice();
59
+ if (stateNotice) console.log(` [CodeArts] ${stateNotice}`);
60
+
57
61
  const codeartsHookDir = join(homedir(), '.codeartsdoer', 'plugins');
58
62
  mkdirSync(codeartsHookDir, { recursive: true });
59
63
  copyFileSync(pluginSrc, join(codeartsHookDir, 'skill-tracker.js'));
@@ -4,9 +4,9 @@
4
4
  // resolution seam, the last-sync sidecar, and the backup/restore pair.
5
5
  import { chmodSync, copyFileSync, existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from 'node:fs';
6
6
  import { dirname, join } from 'node:path';
7
- import { homedir } from 'node:os';
8
7
 
9
8
  import { asText } from '../lib/as-text.ts';
9
+ import { devkitStateBase, huaweiConfigBase } from '../lib/pack-state.ts';
10
10
  import { resolveSecretValue } from '../lib/secret-vault/store.ts';
11
11
 
12
12
  // The credential vault is JSON on disk shaped like this. Fields stay `unknown`
@@ -57,25 +57,40 @@ export function ensurePrivateMode(path: string): void {
57
57
  }
58
58
  }
59
59
 
60
- function baseHome(): string {
61
- return process.env.HUAWEICLOUD_HOME || homedir();
60
+ export function globalCredentialsPath(): string {
61
+ return join(devkitStateBase(), 'credentials.json');
62
62
  }
63
63
 
64
- export function globalCredentialsPath(): string {
65
- return join(baseHome(), '.config', 'huaweicloud', 'credentials.json');
64
+ // The historical read location. On a read-only-home fallback the config tree
65
+ // may still carry a pre-provisioned credentials.json; reads prefer the
66
+ // writable state tree but fall back here so those credentials keep working.
67
+ function legacyGlobalCredentialsPath(): string {
68
+ return join(huaweiConfigBase(), 'credentials.json');
66
69
  }
67
70
 
68
- export function readGlobalCredentials(): StoredCredentials | null {
69
- const path = globalCredentialsPath();
71
+ function readJsonObject(path: string): Record<string, unknown> | null {
70
72
  if (!existsSync(path)) return null;
71
73
  try {
72
74
  const parsed: unknown = JSON.parse(readFileSync(path, 'utf8'));
73
- return parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : null;
75
+ return parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed)
76
+ ? (parsed as Record<string, unknown>)
77
+ : null;
74
78
  } catch {
75
79
  return null;
76
80
  }
77
81
  }
78
82
 
83
+ export function readGlobalCredentials(): StoredCredentials | null {
84
+ const primary = globalCredentialsPath();
85
+ const stored = readJsonObject(primary);
86
+ if (stored) return stored;
87
+ if (!existsSync(primary)) {
88
+ const legacy = legacyGlobalCredentialsPath();
89
+ if (legacy !== primary) return readJsonObject(legacy);
90
+ }
91
+ return null;
92
+ }
93
+
79
94
  // S1 may hold secret://<scope>/<name> refs in its secret-bearing fields (the
80
95
  // vault is the at-rest-encrypted alternative to plaintext AK/SK). This is the
81
96
  // one seam every S1 value CONSUMER goes through: refs resolve to plaintext,
@@ -156,18 +171,22 @@ export function setConfiguredBySession(flag: unknown): void {
156
171
  }
157
172
 
158
173
  export function lastSyncPath(): string {
159
- return join(baseHome(), '.config', 'huaweicloud', '.last_sync');
174
+ return join(devkitStateBase(), '.last_sync');
175
+ }
176
+
177
+ function readLastSyncFile(path: string): LastSyncRecord | null {
178
+ return readJsonObject(path);
160
179
  }
161
180
 
162
181
  export function readLastSync(): LastSyncRecord | null {
163
- const path = lastSyncPath();
164
- if (!existsSync(path)) return null;
165
- try {
166
- const parsed: unknown = JSON.parse(readFileSync(path, 'utf8'));
167
- return parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : null;
168
- } catch {
169
- return null;
182
+ const primary = lastSyncPath();
183
+ const stored = readLastSyncFile(primary);
184
+ if (stored) return stored;
185
+ if (!existsSync(primary)) {
186
+ const legacy = join(huaweiConfigBase(), '.last_sync');
187
+ if (legacy !== primary) return readLastSyncFile(legacy);
170
188
  }
189
+ return null;
171
190
  }
172
191
 
173
192
  export interface LastSyncMetadata {
@@ -188,11 +207,13 @@ export function writeLastSync(metadata: LastSyncMetadata = {}): void {
188
207
  }
189
208
 
190
209
  export function backupGlobalCredentials(): string | null {
191
- const path = globalCredentialsPath();
192
- if (!existsSync(path)) return null;
193
- const bakPath = `${path}.bak`;
210
+ const target = globalCredentialsPath();
211
+ const source = existsSync(target) ? target : legacyGlobalCredentialsPath();
212
+ if (!existsSync(source)) return null;
213
+ const bakPath = `${target}.bak`;
194
214
  try {
195
- copyFileSync(path, bakPath);
215
+ mkdirSync(dirname(bakPath), { recursive: true });
216
+ copyFileSync(source, bakPath);
196
217
  ensurePrivateMode(bakPath);
197
218
  return bakPath;
198
219
  } catch {
@@ -13,7 +13,7 @@ import { dirname, join } from 'node:path';
13
13
 
14
14
  import { redactSecrets } from '../safety-policy.ts';
15
15
  import { ensureMasterKey, resolveMasterKey, type ResolvedMasterKey } from './secret-vault/custody.ts';
16
- import { huaweiConfigBase } from './pack-state.ts';
16
+ import { devkitStateBase } from './pack-state.ts';
17
17
 
18
18
  // The CLI face's approval tokens: the consent layer for
19
19
  // plan_cli_command / run_approved_command in the huaweicloud-cli pack.
@@ -110,7 +110,7 @@ export interface ApprovalInspection {
110
110
  const APPROVAL_TTL_MS = 5 * 60_000;
111
111
 
112
112
  function approvalFilePath(): string {
113
- return join(huaweiConfigBase(), 'approvals.json');
113
+ return join(devkitStateBase(), 'approvals.json');
114
114
  }
115
115
 
116
116
  function sha256Hex(data: string): string {
@@ -244,7 +244,7 @@ function pruneStale(map: ApprovalMap, now = Date.now()): boolean {
244
244
  }
245
245
 
246
246
  function consumedMarkerDir(): string {
247
- return join(huaweiConfigBase(), 'approvals-consumed');
247
+ return join(devkitStateBase(), 'approvals-consumed');
248
248
  }
249
249
 
250
250
  // Exclusive-create claim on a token: 'wx' maps to O_EXCL|O_CREAT, so the
@@ -1,26 +1,33 @@
1
1
  import { chmodSync, lstatSync, mkdirSync, realpathSync, writeFileSync } from 'node:fs';
2
- import { homedir, tmpdir } from 'node:os';
2
+ import { tmpdir } from 'node:os';
3
3
  import { basename, dirname, join, resolve, sep } from 'node:path';
4
4
 
5
5
  import type { PackId } from './pack-types.ts';
6
+ import { devkitStateBase, huaweiConfigBase } from './state-dir.ts';
7
+
8
+ export { devkitStateBase, huaweiConfigBase };
6
9
 
7
10
  // The pack-scoped state space and the single resolver for the devkit's
8
11
  // config tree (~/.config/huaweicloud, relocatable whole-tree via
9
- // HUAWEICLOUD_HOME).
12
+ // HUAWEICLOUD_HOME) and its writable state tree (state-dir.ts: the same tree
13
+ // by default, the agent-owned devkit-state directory on a read-only home).
10
14
  //
11
15
  // Ownership criterion, stated here so the next state file does not have to
12
16
  // guess: the writer/reader set decides where state lives. approvals.json
13
17
  // is the CLI approval face's store (plan_cli_command /
14
18
  // run_approved_command mint and consume), credentials.json is the
15
19
  // devkit-wide S1 store, and deps/ belongs to the dependency domain — all
16
- // three stay at the config root. State with exactly one pack as writer
20
+ // three live in the state tree. State with exactly one pack as writer
17
21
  // and reader (the open-mcp gateway's policy file) lives under packs/<id>/,
18
22
  // so ownership is derivable from the directory name and an uninstall can
19
23
  // preserve user state without a manifest. Modules that still hand-roll
20
- // the base (auth/credentials, dep/receipts, update-check, proxy-config,
21
- // officeace-paths) migrate here when next touched; the guard below
22
- // already resolves through this module, so guard and store cannot
23
- // disagree about where the tree is.
24
+ // the base (dep/receipts, update-check, proxy-config, officeace-paths)
25
+ // migrate when next touched; the guard below already resolves through this
26
+ // module, so guard and store cannot disagree about where the trees are.
27
+ //
28
+ // S1 is the one exception: credentials are WRITTEN to the state tree but
29
+ // READ from the state tree first and the config tree second, so a
30
+ // pre-provisioned credentials.json in a read-only home keeps resolving.
24
31
  //
25
32
  // The same resolver backs the protected-tree guard the gateway face uses:
26
33
  // anything the devkit or its operator considers consent infrastructure (the
@@ -34,16 +41,8 @@ import type { PackId } from './pack-types.ts';
34
41
  // — the installer chain (dist/setup-cli.js, plain tsc output) must never
35
42
  // pull zod, same contract as dependency-model.ts and dep-resolve.ts.
36
43
 
37
- export function huaweiConfigBase(env: NodeJS.ProcessEnv = process.env): string {
38
- // resolve() absolutizes once, here, so every consumer — store writes and
39
- // the guard below — shares one anchor even for a relative
40
- // HUAWEICLOUD_HOME (a relative base previously made the store land at
41
- // the process cwd while the guard protected a tmpdir-anchored tree).
42
- return resolve(env.HUAWEICLOUD_HOME || homedir(), '.config', 'huaweicloud');
43
- }
44
-
45
44
  export function packStateDir(packId: PackId, env: NodeJS.ProcessEnv = process.env): string {
46
- return join(huaweiConfigBase(env), 'packs', packId);
45
+ return join(devkitStateBase(env), 'packs', packId);
47
46
  }
48
47
 
49
48
  export interface PackStateLayout {
@@ -153,20 +152,24 @@ function resolveForWrite(target: string): string | null {
153
152
  }
154
153
  }
155
154
 
156
- // The roots a gateway file write must never touch: the devkit config tree
157
- // plus whatever policy/audit paths the operator configured (the LIVE paths,
158
- // not what the devkit would have provisioned). Returns null when a root is
155
+ // The roots a gateway file write must never touch: the devkit config tree,
156
+ // the writable state tree (they differ on a read-only-home fallback), plus
157
+ // whatever policy/audit paths the operator configured (the LIVE paths, not
158
+ // what the devkit would have provisioned). Returns null when a root is
159
159
  // present-but-unresolvable — callers deny everything in that case.
160
160
  export function protectedTreeRoots(env: NodeJS.ProcessEnv = process.env): string[] | null {
161
- const candidates: string[] = [huaweiConfigBase(env)];
161
+ const candidates: string[] = [huaweiConfigBase(env), devkitStateBase(env)];
162
162
  for (const key of ['HUAWEICLOUD_MCP_POLICY_FILE', 'HUAWEICLOUD_MCP_AUDIT_FILE'] as const) {
163
163
  const value = (env[key] ?? '').trim();
164
164
  if (value !== '') candidates.push(value);
165
165
  }
166
166
  const roots: string[] = [];
167
+ const seen = new Set<string>();
167
168
  for (const candidate of candidates) {
168
169
  const resolved = resolveForWrite(candidate);
169
170
  if (resolved === null) return null;
171
+ if (seen.has(resolved)) continue;
172
+ seen.add(resolved);
170
173
  roots.push(resolved);
171
174
  }
172
175
  return roots;
@@ -0,0 +1,69 @@
1
+ // Unknown-parameter warnings for the MCP boundary. The #530 leniency keeps
2
+ // accepting keys a tool does not declare (model wire shapes are noisy and a
3
+ // rejection used to cost the whole call), but silently dropping a typo makes
4
+ // `pack` vs `pak` invisible — this module turns that into an additive
5
+ // `warnings` entry without changing the acceptance decision.
6
+
7
+ const MAX_WARNINGS = 5;
8
+ const SUGGESTION_DISTANCE = 2;
9
+
10
+ function levenshtein(a: string, b: string): number {
11
+ const rows = a.length + 1;
12
+ const cols = b.length + 1;
13
+ const previous = new Array<number>(cols);
14
+ const current = new Array<number>(cols);
15
+ for (let j = 0; j < cols; j++) previous[j] = j;
16
+ for (let i = 1; i < rows; i++) {
17
+ current[0] = i;
18
+ for (let j = 1; j < cols; j++) {
19
+ const cost = a[i - 1] === b[j - 1] ? 0 : 1;
20
+ current[j] = Math.min(previous[j]! + 1, current[j - 1]! + 1, previous[j - 1]! + cost);
21
+ }
22
+ for (let j = 0; j < cols; j++) previous[j] = current[j]!;
23
+ }
24
+ return previous[cols - 1]!;
25
+ }
26
+
27
+ export function suggestParam(key: string, knownKeys: Iterable<string>): string | null {
28
+ let best: string | null = null;
29
+ let bestDistance = SUGGESTION_DISTANCE + 1;
30
+ const lowerKey = key.toLowerCase();
31
+ for (const candidate of knownKeys) {
32
+ if (candidate === key) continue;
33
+ const distance = levenshtein(lowerKey, candidate.toLowerCase());
34
+ if (distance > SUGGESTION_DISTANCE) continue;
35
+ if (distance < bestDistance || (distance === bestDistance && best !== null && candidate < best)) {
36
+ best = candidate;
37
+ bestDistance = distance;
38
+ }
39
+ }
40
+ return best;
41
+ }
42
+
43
+ export function unknownParamWarnings(args: Record<string, unknown>, knownKeys: ReadonlySet<string>): string[] {
44
+ const unknown = Object.keys(args)
45
+ .filter((key) => !knownKeys.has(key))
46
+ .sort((a, b) => a.localeCompare(b));
47
+ return unknown.slice(0, MAX_WARNINGS).map((key) => {
48
+ const suggestion = suggestParam(key, knownKeys);
49
+ return suggestion
50
+ ? `Unknown parameter "${key}" was ignored. Did you mean "${suggestion}"?`
51
+ : `Unknown parameter "${key}" was ignored (no matching parameter).`;
52
+ });
53
+ }
54
+
55
+ // Additive by construction: a warnings array is merged, an absent field is
56
+ // created, and any other existing shape is left untouched under paramWarnings.
57
+ // Non-object results (there are none on the shipped surface) pass through.
58
+ export function attachParamWarnings(result: unknown, warnings: string[]): unknown {
59
+ if (warnings.length === 0) return result;
60
+ if (result === null || typeof result !== 'object' || Array.isArray(result)) return result;
61
+ const record = result as Record<string, unknown>;
62
+ if (Array.isArray(record.warnings)) {
63
+ return { ...record, warnings: [...(record.warnings as unknown[]), ...warnings] };
64
+ }
65
+ if (record.warnings === undefined) {
66
+ return { ...record, warnings };
67
+ }
68
+ return { ...record, paramWarnings: warnings };
69
+ }