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
package/README.md CHANGED
@@ -139,6 +139,8 @@ npx --yes huaweicloud-devkit uninstall --target codearts-work
139
139
  ```
140
140
 
141
141
  > **CodeArts Work** (CodeArts Space, appId: `com.codearts.work`) uses user-level config at `%USERPROFILE%\.codeartswork\`. No project-level `.codeartswork` directory is created.
142
+ >
143
+ > **Read-only home**: when `~/.config/huaweicloud` is not writable (sandbox home), devkit state — gateway policy, approval tokens, update skip, S1 writes — moves automatically to `~/.codearts*/devkit-state`; a pre-provisioned `credentials.json` in the old tree remains readable. `doctor` reports the resolved state directory; set `HUAWEICLOUD_STATE_DIR` to an absolute path to pin it explicitly.
142
144
 
143
145
  ### WorkBuddy
144
146
 
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "huaweicloud-devkit",
3
3
  "mcpName": "io.github.huaweicloud/huaweicloud-devkit",
4
- "version": "2.0.0-next.0",
4
+ "version": "2.0.0-next.2",
5
5
  "kooCliVersion": "7.3.12",
6
6
  "description": "Agent toolkit that helps coding agents use Huawei Cloud Skills, KooCLI, APIs, SDKs, and future MCP capabilities safely and accurately.",
7
7
  "type": "module",
@@ -16,7 +16,7 @@
16
16
  },
17
17
  "mcpServers": "./.mcp.json",
18
18
  "description": "Guide coding agents to use Huawei Cloud Skills, KooCLI, APIs, SDKs, and future MCP capabilities with safer execution and less context.",
19
- "version": "2.0.0-next.0",
19
+ "version": "2.0.0-next.2",
20
20
  "author": {
21
21
  "name": "HuaweiCloud Mate",
22
22
  "url": "https://github.com/huaweicloud"
@@ -19,7 +19,7 @@
19
19
  },
20
20
  "mcpServers": "./.mcp.json",
21
21
  "description": "Agent toolkit that helps coding agents use Huawei Cloud Skills, KooCLI, APIs, SDKs, and future MCP capabilities safely and accurately.",
22
- "version": "2.0.0-next.0",
22
+ "version": "2.0.0-next.2",
23
23
  "author": {
24
24
  "name": "HuaweiCloud Mate",
25
25
  "url": "https://github.com/huaweicloud"
@@ -16,7 +16,7 @@
16
16
  },
17
17
  "mcpServers": "./.mcp.json",
18
18
  "description": "Guide coding agents to use Huawei Cloud Skills, KooCLI, APIs, SDKs, and future MCP capabilities with safer execution and less context.",
19
- "version": "2.0.0-next.0",
19
+ "version": "2.0.0-next.2",
20
20
  "author": {
21
21
  "name": "HuaweiCloud Mate",
22
22
  "url": "https://github.com/huaweicloud"
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "huaweicloud-devkit",
3
- "version": "2.0.0-next.0",
3
+ "version": "2.0.0-next.2",
4
4
  "description": "Guide coding agents to use Huawei Cloud Skills, KooCLI, APIs, SDKs, and future MCP capabilities with safer execution and less context.",
5
5
  "author": {
6
6
  "name": "HuaweiCloud Mate",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "huaweicloud-devkit",
3
- "version": "2.0.0-next.0",
3
+ "version": "2.0.0-next.2",
4
4
  "description": "Guide coding agents to use Huawei Cloud Skills, KooCLI, APIs, SDKs, and future MCP capabilities with safer execution and less context.",
5
5
  "author": {
6
6
  "name": "HuaweiCloud Mate",
@@ -10,6 +10,7 @@ import { mergeCommandStyle, applyUserDelta, inheritPeerUserEnv } from "../mcp-co
10
10
  import { takeAgentDelta } from "../mcp-config-backup.js";
11
11
  import { printMcpConfigStatus, readJsonRecord, removeMcpServerEntry, writeMcpSettingsFile } from "../mcp-config-io.js";
12
12
  import { asRecord } from "../lib/as-record.js";
13
+ import { stateDirNotice } from "../lib/state-dir.js";
13
14
  import { copyServerPayload, installRuntimeDeps, payloadStatusLines, removeIfExists, } from "../install-payload.js";
14
15
  // Doctor: the CodeArts Work MCP-configured candidate — the mcp settings
15
16
  // file's mcp.huaweicloud-devkit entry.
@@ -102,6 +103,9 @@ function isPlainLocal(value) {
102
103
  export async function deployCodeArtsWork(_mode) {
103
104
  const pluginDest = codeartsWorkPluginsDir();
104
105
  copyServerPayload(pluginDest);
106
+ const stateNotice = stateDirNotice();
107
+ if (stateNotice)
108
+ console.log(` [CodeArts Work] ${stateNotice}`);
105
109
  registerCodeartsWorkMcp();
106
110
  installRuntimeDeps(pluginDest);
107
111
  }
@@ -6,6 +6,7 @@ import { homedir } from 'node:os';
6
6
  import { codeartsMcpSettingsFile, codeartsPluginsDir, codeartsProjectMcpSettingsFile, codeartsProjectSkillsDir, codeartsSkillsDir, } from "../targets.js";
7
7
  import { findHcloudBin } from "../hcloud-probe.js";
8
8
  import { asRecord } from "../lib/as-record.js";
9
+ import { stateDirNotice } from "../lib/state-dir.js";
9
10
  import { ensureMcpServersConfig, printMcpConfigStatus, removeMcpServerEntry } from "../mcp-config-io.js";
10
11
  import { PACKAGE_ROOT, copyServerPayload, deployWord, installRuntimeDeps, payloadStatusLines, removeIfExists, } from "../install-payload.js";
11
12
  // Doctor: the CodeArts MCP-configured candidate — the user-level mcp settings
@@ -37,6 +38,9 @@ export async function deployCodeArts(mode) {
37
38
  const pluginSrc = join(PACKAGE_ROOT, 'integrations', 'opencode', 'hooks', 'skill-tracker.js');
38
39
  const pluginDest = codeartsPluginsDir();
39
40
  copyServerPayload(pluginDest);
41
+ const stateNotice = stateDirNotice();
42
+ if (stateNotice)
43
+ console.log(` [CodeArts] ${stateNotice}`);
40
44
  const codeartsHookDir = join(homedir(), '.codeartsdoer', 'plugins');
41
45
  mkdirSync(codeartsHookDir, { recursive: true });
42
46
  copyFileSync(pluginSrc, join(codeartsHookDir, 'skill-tracker.js'));
@@ -20,16 +20,26 @@ function toSqliteModule(value) {
20
20
  const ctor = value.DatabaseSync;
21
21
  return typeof ctor === 'function' ? value : null;
22
22
  }
23
- const sqliteModule = toSqliteModule(createRequire(import.meta.url)('node:sqlite'));
24
- if (!sqliteModule) {
25
- throw new Error('node:sqlite is unavailable; the OfficeAce integration requires Node.js >= 22');
23
+ // The builtin is required inside a function, never at module scope: loading
24
+ // the setup-cli graph is the CLI's boot, and node:sqlite is experimental
25
+ // through Node 22.x (the declared floor) — at module scope it printed
26
+ // "(node:xxxx) ExperimentalWarning: SQLite is an experimental feature" on
27
+ // every CLI run, install included, and throws outright below Node 22.5,
28
+ // though only the officeace packs/doctor paths ever open the connector db.
29
+ // agent-registration.ts keeps the same doctrine for the MCP graph's probe.
30
+ function loadDatabaseSync() {
31
+ const sqliteModule = toSqliteModule(createRequire(import.meta.url)('node:sqlite'));
32
+ if (!sqliteModule) {
33
+ throw new Error('node:sqlite is unavailable; the OfficeAce integration requires Node.js >= 22');
34
+ }
35
+ return sqliteModule.DatabaseSync;
26
36
  }
27
- const { DatabaseSync } = sqliteModule;
28
37
  export function officeaceSqlitePath() {
29
38
  const capDir = officeaceCapabilitiesDirSafe();
30
39
  return join(resolve(capDir, '..'), 'data', 'mcp-connectors.sqlite');
31
40
  }
32
41
  export function openOfficeaceDb() {
42
+ const DatabaseSync = loadDatabaseSync();
33
43
  return new DatabaseSync(officeaceSqlitePath());
34
44
  }
35
45
  export function officeaceGetOwnerUserId() {
@@ -49,7 +49,11 @@ function probeOpencodeVersion() {
49
49
  const probeEnv = { ...process.env, XDG_CONFIG_HOME: probeRoot };
50
50
  const run = (cmd, shell) => {
51
51
  try {
52
- const r = spawnSync(cmd, ['--version'], {
52
+ // Args ride the command string whenever shell is true: an args array
53
+ // under shell is DEP0190 on Node 24+ (and would double the --version
54
+ // the win32 fallback string already carries). Without a shell the
55
+ // array stays — spawn needs the separated argument there.
56
+ const r = spawnSync(cmd, shell ? undefined : ['--version'], {
53
57
  shell,
54
58
  windowsHide: true,
55
59
  stdio: 'pipe',
@@ -0,0 +1,159 @@
1
+ import { confirmApprovalToken, inspectApprovalToken } from "./lib/approval-tokens.js";
2
+ import { enrollApprovalsPin, isApprovalsPinEnrolled, verifyApprovalsPin } from "./lib/approvals-pin.js";
3
+ import { readSecret } from "./lib/cli-io.js";
4
+ // The human half of the approval gate: `npx huaweicloud-devkit approve <token>`
5
+ // is the only channel that writes a user confirmation, so it must be driven
6
+ // by a person at a terminal. The command refuses every non-interactive
7
+ // caller (an agent piping into Bash cannot pass), and it refuses to record
8
+ // the confirmation without the PIN. The door has no flags, because a flag
9
+ // would be an escape hatch for the caller the gate is built to stop.
10
+ //
11
+ // PIN enrollment is its own verb (`pin`): approve refuses outright on a
12
+ // machine with no enrolled PIN instead of enrolling inline — an inline
13
+ // first-use enroll would let any pseudo-terminal caller choose the PIN.
14
+ //
15
+ // The token lifecycle and the PIN record are pure state/crypto modules
16
+ // (lib/approval-tokens.ts, lib/approvals-pin.ts); this file owns prompts and
17
+ // exit codes, and takes its terminal as an injected ApproveIo so tests can
18
+ // drive both the refusal and the interactive paths without a real TTY.
19
+ const USAGE = 'Usage: npx huaweicloud-devkit approve <token>';
20
+ const PIN_USAGE = 'Usage: npx huaweicloud-devkit pin';
21
+ const PIN_ATTEMPTS = 3;
22
+ const ENROLL_ATTEMPTS = 2;
23
+ export function createProcessApproveIo() {
24
+ return {
25
+ // Both ends must be terminals: stdout-only TTY (agent captures output)
26
+ // and stdin-only TTY (agent feeds input) are both agent-shaped pipes.
27
+ isTTY: Boolean(process.stdin.isTTY && process.stdout.isTTY),
28
+ write: (text) => {
29
+ process.stdout.write(text);
30
+ },
31
+ readLine: () => readSecret(''),
32
+ };
33
+ }
34
+ function renderCommand(argsRedacted) {
35
+ if (Array.isArray(argsRedacted)) {
36
+ const rendered = argsRedacted.map((arg) => (typeof arg === 'string' ? arg : JSON.stringify(arg)));
37
+ return `hcloud ${rendered.join(' ')}`;
38
+ }
39
+ return JSON.stringify(argsRedacted);
40
+ }
41
+ function printRefusal(io, inspectionState) {
42
+ if (inspectionState === 'not_found') {
43
+ io.write('No pending approval matches that token.\n');
44
+ }
45
+ else if (inspectionState === 'expired') {
46
+ io.write('That approval expired. A confirmation must happen within 5 minutes of the plan; ask the agent to plan the command again.\n');
47
+ }
48
+ else {
49
+ io.write('This approval was already used.\n');
50
+ }
51
+ return inspectionState === 'already_consumed' ? 0 : 1;
52
+ }
53
+ async function enrollPin(io) {
54
+ io.write('Choose a PIN of at least 6 characters.\n');
55
+ for (let attempt = 1; attempt <= ENROLL_ATTEMPTS; attempt++) {
56
+ io.write('Choose a PIN: ');
57
+ const first = await io.readLine();
58
+ io.write('Re-type the PIN: ');
59
+ const second = await io.readLine();
60
+ if (first !== second) {
61
+ io.write(attempt < ENROLL_ATTEMPTS ? 'The PINs did not match, try again.\n' : 'The PINs did not match.\n');
62
+ continue;
63
+ }
64
+ const enrolled = enrollApprovalsPin(first);
65
+ if (!enrolled.ok) {
66
+ io.write(`Cannot enroll the approvals PIN: ${enrolled.reason ?? 'unknown error'}.\n`);
67
+ return false;
68
+ }
69
+ io.write('Approvals PIN enrolled.\n');
70
+ return true;
71
+ }
72
+ return false;
73
+ }
74
+ async function verifyPin(io) {
75
+ for (let attempt = 1; attempt <= PIN_ATTEMPTS; attempt++) {
76
+ io.write('PIN: ');
77
+ const pin = await io.readLine();
78
+ if (verifyApprovalsPin(pin).ok)
79
+ return true;
80
+ if (attempt < PIN_ATTEMPTS)
81
+ io.write(`Incorrect PIN (${attempt}/${PIN_ATTEMPTS}), try again.\n`);
82
+ }
83
+ io.write('Too many incorrect PIN attempts.\n');
84
+ return false;
85
+ }
86
+ function printConfirmResult(io, status, reason) {
87
+ switch (status) {
88
+ case 'confirmed':
89
+ io.write('Confirmed. The agent may now run this command once.\n');
90
+ return 0;
91
+ case 'already_confirmed':
92
+ io.write('This approval was already confirmed. The agent may run this command once.\n');
93
+ return 0;
94
+ case 'already_consumed':
95
+ io.write('This approval was already used.\n');
96
+ return 0;
97
+ case 'expired':
98
+ io.write('That approval expired. A confirmation must happen within 5 minutes of the plan; ask the agent to plan the command again.\n');
99
+ return 1;
100
+ case 'custody_unavailable':
101
+ io.write(`Cannot record the confirmation: ${reason ?? 'the vault master key is unavailable'}.\n`);
102
+ return 1;
103
+ case 'not_found':
104
+ io.write('No pending approval matches that token.\n');
105
+ return 1;
106
+ }
107
+ }
108
+ export async function runApproveCommand(argv, io) {
109
+ const token = argv[0];
110
+ // No flags: any extra argv is a caller trying to steer the confirmation.
111
+ if (!token || token.startsWith('-') || argv.length > 1) {
112
+ io.write(`${USAGE}\n`);
113
+ return 1;
114
+ }
115
+ const inspection = inspectApprovalToken(token);
116
+ if (inspection.state !== 'valid')
117
+ return printRefusal(io, inspection.state);
118
+ const entry = inspection.entry;
119
+ if (!entry) {
120
+ io.write('No pending approval matches that token.\n');
121
+ return 1;
122
+ }
123
+ io.write(`Confirming: ${renderCommand(entry.argsRedacted)}\n`);
124
+ io.write('This authorizes ONE execution of exactly this command.\n');
125
+ // The TTY gate sits after the description so a human sees what would have
126
+ // been confirmed, and before any prompt so no pipe can answer one.
127
+ if (!io.isTTY) {
128
+ io.write('Approvals must be confirmed in your own interactive terminal.\n');
129
+ return 1;
130
+ }
131
+ // Enrollment is a deliberate separate step, never an inline fallback: a
132
+ // first confirm that mints its own PIN would enroll whatever the current
133
+ // caller typed, and a pseudo-terminal makes even an agent "interactive".
134
+ if (!isApprovalsPinEnrolled()) {
135
+ io.write('No approvals PIN is enrolled yet. Run "npx huaweicloud-devkit pin" in your own terminal once, then confirm plans with "approve".\n');
136
+ return 1;
137
+ }
138
+ if (!(await verifyPin(io))) {
139
+ return 1;
140
+ }
141
+ const result = confirmApprovalToken(token);
142
+ return printConfirmResult(io, result.status, result.reason);
143
+ }
144
+ // `npx huaweicloud-devkit pin`: the deliberate enrollment step the approve
145
+ // command refuses to perform inline. Same door shape as approve — no flags,
146
+ // TTY-gated, injected io — because it writes the credential the confirmation
147
+ // gate trusts.
148
+ export async function runPinCommand(argv, io) {
149
+ // No flags: any extra argv is a caller trying to steer the enrollment.
150
+ if (argv.length > 0) {
151
+ io.write(`${PIN_USAGE}\n`);
152
+ return 1;
153
+ }
154
+ if (!io.isTTY) {
155
+ io.write('The approvals PIN must be enrolled in your own interactive terminal.\n');
156
+ return 1;
157
+ }
158
+ return (await enrollPin(io)) ? 0 : 1;
159
+ }
@@ -4,8 +4,8 @@
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
  import { asText } from "../lib/as-text.js";
8
+ import { devkitStateBase, huaweiConfigBase } from "../lib/pack-state.js";
9
9
  import { resolveSecretValue } from "../lib/secret-vault/store.js";
10
10
  // Verify a credential file ended up with 0600. On Windows-mounted drives inside WSL
11
11
  // (drvfs/9p) chmod is silently ignored, so the file can be world-readable (0777).
@@ -35,24 +35,40 @@ export function ensurePrivateMode(path) {
35
35
  // best-effort: if even stat fails there is no mode left to verify or warn about
36
36
  }
37
37
  }
38
- function baseHome() {
39
- return process.env.HUAWEICLOUD_HOME || homedir();
40
- }
41
38
  export function globalCredentialsPath() {
42
- return join(baseHome(), '.config', 'huaweicloud', 'credentials.json');
39
+ return join(devkitStateBase(), 'credentials.json');
43
40
  }
44
- export function readGlobalCredentials() {
45
- const path = globalCredentialsPath();
41
+ // The historical read location. On a read-only-home fallback the config tree
42
+ // may still carry a pre-provisioned credentials.json; reads prefer the
43
+ // writable state tree but fall back here so those credentials keep working.
44
+ function legacyGlobalCredentialsPath() {
45
+ return join(huaweiConfigBase(), 'credentials.json');
46
+ }
47
+ function readJsonObject(path) {
46
48
  if (!existsSync(path))
47
49
  return null;
48
50
  try {
49
51
  const parsed = JSON.parse(readFileSync(path, 'utf8'));
50
- return parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : null;
52
+ return parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed)
53
+ ? parsed
54
+ : null;
51
55
  }
52
56
  catch {
53
57
  return null;
54
58
  }
55
59
  }
60
+ export function readGlobalCredentials() {
61
+ const primary = globalCredentialsPath();
62
+ const stored = readJsonObject(primary);
63
+ if (stored)
64
+ return stored;
65
+ if (!existsSync(primary)) {
66
+ const legacy = legacyGlobalCredentialsPath();
67
+ if (legacy !== primary)
68
+ return readJsonObject(legacy);
69
+ }
70
+ return null;
71
+ }
56
72
  // S1 may hold secret://<scope>/<name> refs in its secret-bearing fields (the
57
73
  // vault is the at-rest-encrypted alternative to plaintext AK/SK). This is the
58
74
  // one seam every S1 value CONSUMER goes through: refs resolve to plaintext,
@@ -116,19 +132,22 @@ export function setConfiguredBySession(flag) {
116
132
  writeGlobalCredentials(next);
117
133
  }
118
134
  export function lastSyncPath() {
119
- return join(baseHome(), '.config', 'huaweicloud', '.last_sync');
135
+ return join(devkitStateBase(), '.last_sync');
136
+ }
137
+ function readLastSyncFile(path) {
138
+ return readJsonObject(path);
120
139
  }
121
140
  export function readLastSync() {
122
- const path = lastSyncPath();
123
- if (!existsSync(path))
124
- return null;
125
- try {
126
- const parsed = JSON.parse(readFileSync(path, 'utf8'));
127
- return parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : null;
128
- }
129
- catch {
130
- return null;
141
+ const primary = lastSyncPath();
142
+ const stored = readLastSyncFile(primary);
143
+ if (stored)
144
+ return stored;
145
+ if (!existsSync(primary)) {
146
+ const legacy = join(huaweiConfigBase(), '.last_sync');
147
+ if (legacy !== primary)
148
+ return readLastSyncFile(legacy);
131
149
  }
150
+ return null;
132
151
  }
133
152
  export function writeLastSync(metadata = {}) {
134
153
  const path = lastSyncPath();
@@ -142,12 +161,14 @@ export function writeLastSync(metadata = {}) {
142
161
  ensurePrivateMode(path);
143
162
  }
144
163
  export function backupGlobalCredentials() {
145
- const path = globalCredentialsPath();
146
- if (!existsSync(path))
164
+ const target = globalCredentialsPath();
165
+ const source = existsSync(target) ? target : legacyGlobalCredentialsPath();
166
+ if (!existsSync(source))
147
167
  return null;
148
- const bakPath = `${path}.bak`;
168
+ const bakPath = `${target}.bak`;
149
169
  try {
150
- copyFileSync(path, bakPath);
170
+ mkdirSync(dirname(bakPath), { recursive: true });
171
+ copyFileSync(source, bakPath);
151
172
  ensurePrivateMode(bakPath);
152
173
  return bakPath;
153
174
  }
@@ -10,6 +10,16 @@ import { createApprovalToken } from "./lib/approval-tokens.js";
10
10
  import { obsWriteHint } from "./hcloud-obs-redact.js";
11
11
  import { applyPreflightFindings, preflightSecurityGroupCheck } from "./hcloud-sg-preflight.js";
12
12
  import { triageUnknownService } from "./hcloud-triage.js";
13
+ // Does this command wait on the user's terminal confirmation? The verdict
14
+ // comes from the STRICT view — allowWrites forced false — never the
15
+ // caller's option, so an agent passing allowWrites:true cannot weaken it.
16
+ // Only write/execution denies answer true: secret, credential, and invalid
17
+ // denies are never unlockable by a terminal confirmation, and reads never
18
+ // need one.
19
+ export function needsUserConfirmation(args, options = {}) {
20
+ const strict = classifyHcloudArgs(args, { ...options, allowWrites: false });
21
+ return strict.decision === 'deny' && (strict.risk === 'write' || strict.risk === 'execution');
22
+ }
13
23
  function quoteShellArg(value) {
14
24
  const text = String(value);
15
25
  if (!text)
@@ -277,6 +287,13 @@ export function planHcloudCommand(args, options = {}) {
277
287
  warnings.push(`${triage.message} ${triage.nextStep}`);
278
288
  }
279
289
  }
290
+ const approvalToken = options.mintApprovalToken === false
291
+ ? undefined
292
+ : createApprovalToken(normalizedArgs, {
293
+ secretsSubstitutable: secretsSubstitutable(normalizedArgs),
294
+ argsPinView: pinViewArgs(normalizedArgs),
295
+ });
296
+ const needsConfirmation = needsUserConfirmation(normalizedArgs, options);
280
297
  return {
281
298
  executable: 'hcloud',
282
299
  args: normalizedArgs.map((arg) => redactSecrets(arg)),
@@ -289,10 +306,15 @@ export function planHcloudCommand(args, options = {}) {
289
306
  warnings,
290
307
  classification: applyPreflightFindings(effectiveClassification, sgFindings),
291
308
  sgFindings,
292
- approvalToken: createApprovalToken(normalizedArgs, {
293
- secretsSubstitutable: secretsSubstitutable(normalizedArgs),
294
- argsPinView: pinViewArgs(normalizedArgs),
295
- }),
309
+ ...(approvalToken !== undefined ? { approvalToken } : {}),
310
+ // `command` exists only where a token was minted: a run-path plan stays
311
+ // silent rather than name a line for a token the run cannot offer.
312
+ userConfirmation: needsConfirmation
313
+ ? {
314
+ needed: true,
315
+ ...(approvalToken !== undefined ? { command: `npx huaweicloud-devkit approve ${approvalToken}` } : {}),
316
+ }
317
+ : { needed: false },
296
318
  safeToRun: effectiveClassification.decision === 'allow',
297
319
  };
298
320
  }
@@ -18,8 +18,11 @@ export async function runHcloud(args, options = {}) {
18
18
  // longer reach the spawn as a doubled `hcloud hcloud ...` prefix. The
19
19
  // warning for the stripped token comes from the plan this call builds.
20
20
  const { args: normalizedArgs } = stripLeadingHcloudBinArgs(inputArgs);
21
+ // Run paths never mint approval tokens: only the plan face does, so a run
22
+ // result can never hand the agent a fresh usable token for the next
23
+ // execution.
21
24
  const plan = {
22
- ...planHcloudCommand(normalizedArgs, options),
25
+ ...planHcloudCommand(normalizedArgs, { ...options, mintApprovalToken: false }),
23
26
  rawArgs: normalizedArgs,
24
27
  };
25
28
  assertAllowed(plan.classification);