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,47 @@
1
+ <!-- generated from src/packs/core/skills/huaweicloud-safety - do not edit -->
2
+
3
+ # Terminal Confirmation For Write Commands
4
+
5
+ A write or execution command runs only after the user confirms the plan token in their own interactive terminal. The agent plans, the user confirms, the agent runs. One confirmation covers exactly one execution.
6
+
7
+ ## The three-step contract
8
+
9
+ 1. Plan: call `huaweicloud_plan_cli_command` with the final hcloud arguments. The result echoes the exact command and carries `userConfirmation`.
10
+ - `needed: true` means the command is a write or has execution side effects, and `command` is the exact line the user must run: `npx huaweicloud-devkit approve <approvalToken>`.
11
+ - `needed: false` means the command is read-only, so the terminal confirmation does not apply.
12
+ 2. Confirm: show the user the plan echo and the `userConfirmation.command` line, then wait. The user runs that line in their own terminal. The terminal prints the redacted command and states that this authorizes one execution.
13
+ 3. Run: call `huaweicloud_run_approved_command` with the same `approvalToken`, the same `args`, and `approvedByUser: true`.
14
+
15
+ An unconfirmed non-read command is rejected with `status: "rejected"` and `code: "USER_CONFIRMATION_REQUIRED"`, plus a `nextStep` naming the approve line. The refusal does not consume the token, so retry the same call after the user confirms.
16
+
17
+ ## The PIN and the TTY check
18
+
19
+ The approve command refuses to record a confirmation unless stdin and stdout are both terminals. A pipe cannot answer a prompt, so an agent that shells out to Bash cannot drive the confirmation. A human at an interactive terminal can.
20
+
21
+ First use is two steps, both in the user's own terminal: run `npx huaweicloud-devkit pin` once to choose an approvals PIN (at least 6 characters, typed twice), then confirm plans with `npx huaweicloud-devkit approve <approvalToken>`. The approve command refuses outright on a machine with no enrolled PIN instead of enrolling one inline. Every confirmation verifies the PIN with three attempts per invocation.
22
+
23
+ A wrong PIN also counts toward a persistent failure lockout: every sixth cumulative failure locks verification for 5 minutes, doubling per lockout episode and capped at 24 hours, and a correct PIN clears the counter. The failure lockout is guidance, not a boundary — a same-user process can edit the PIN record the same way it can edit any file under `~/.config/huaweicloud/`.
24
+
25
+ The PIN record stores only a mac over the vault custody master key, never the plaintext. The PIN proves presence at the terminal. It does not prove the user read the command.
26
+
27
+ ## One confirmation per execution
28
+
29
+ The confirmation authorizes one execution of one command.
30
+
31
+ - The plan token expires 5 minutes after the plan. An expired token is refused, and the agent must plan the command again.
32
+ - A run consumes the token. A repeat run of the same token reports `outcome: "already_processed"`, never a second execution.
33
+ - A run result's plan is minted without a token, so it never carries a usable approval. Re-running the command needs a fresh `huaweicloud_plan_cli_command` call and a fresh terminal confirmation.
34
+ - Changing the arguments rejects the run, because the token pins the exact command hash and any real secret values in it.
35
+
36
+ ## What the agent must not do
37
+
38
+ - Never run `npx huaweicloud-devkit approve` or `npx huaweicloud-devkit pin` yourself, in any spelling. The confirmation's value is that the user's own terminal records it, and the safety hook denies both verbs on the agent Bash face for exactly that reason.
39
+ - Never treat `approvedByUser: true` as the confirmation. It is the agent's statement that the user approved the exact command, and the run tool still requires the terminal-confirmed grant.
40
+ - Never ask the user for their PIN, and never enter a PIN on the user's behalf.
41
+ - Never retry a run with different arguments under the same token. Plan again and get a fresh confirmation.
42
+
43
+ ## Honest security boundary
44
+
45
+ The terminal confirmation defends: execution needs a user-recorded, PIN-checked grant made at an interactive terminal; the grant is a custody-keyed mac bound to the token, the confirmation time, and every stored field the run gate trusts (command hash, pin view, redacted form, secret-pinning flag, mint time), so a same-user edit of the state string or any trusted field does not verify; and a non-read command without a valid grant never runs.
46
+
47
+ It does NOT defend against: a socially engineered user who approves a command they did not read (the terminal prints the command, but the PIN proves presence, not comprehension); a same-user process that holds BOTH the custody master key and write access to `~/.config/huaweicloud/`, which can forge a grant for any pending token on the keyfile tier; a harness without the safety hook, where the TTY check is the only barrier and an agent driving a pseudo-terminal looks like a terminal; or the hook's text gate missing variable-indirect verbs (`V=approve; npx huaweicloud-devkit $V` — the same indirection residual the shell shadow documents for the secret gate), where the agent reaches the CLI spelling through a shell variable. This is a consent gate, not an isolation boundary.
@@ -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'));
@@ -44,11 +44,20 @@ function toSqliteModule(value: unknown): SqliteModule | null {
44
44
  return typeof ctor === 'function' ? (value as SqliteModule) : null;
45
45
  }
46
46
 
47
- const sqliteModule = toSqliteModule(createRequire(import.meta.url)('node:sqlite'));
48
- if (!sqliteModule) {
49
- throw new Error('node:sqlite is unavailable; the OfficeAce integration requires Node.js >= 22');
47
+ // The builtin is required inside a function, never at module scope: loading
48
+ // the setup-cli graph is the CLI's boot, and node:sqlite is experimental
49
+ // through Node 22.x (the declared floor) — at module scope it printed
50
+ // "(node:xxxx) ExperimentalWarning: SQLite is an experimental feature" on
51
+ // every CLI run, install included, and throws outright below Node 22.5,
52
+ // though only the officeace packs/doctor paths ever open the connector db.
53
+ // agent-registration.ts keeps the same doctrine for the MCP graph's probe.
54
+ function loadDatabaseSync(): new (_path: string) => SqliteDatabase {
55
+ const sqliteModule = toSqliteModule(createRequire(import.meta.url)('node:sqlite'));
56
+ if (!sqliteModule) {
57
+ throw new Error('node:sqlite is unavailable; the OfficeAce integration requires Node.js >= 22');
58
+ }
59
+ return sqliteModule.DatabaseSync;
50
60
  }
51
- const { DatabaseSync } = sqliteModule;
52
61
 
53
62
  export function officeaceSqlitePath(): string {
54
63
  const capDir = officeaceCapabilitiesDirSafe();
@@ -56,6 +65,7 @@ export function officeaceSqlitePath(): string {
56
65
  }
57
66
 
58
67
  export function openOfficeaceDb(): SqliteDatabase {
68
+ const DatabaseSync = loadDatabaseSync();
59
69
  return new DatabaseSync(officeaceSqlitePath());
60
70
  }
61
71
 
@@ -56,7 +56,11 @@ function probeOpencodeVersion(): string | null {
56
56
  const probeEnv = { ...process.env, XDG_CONFIG_HOME: probeRoot };
57
57
  const run = (cmd: string, shell: boolean): string | null => {
58
58
  try {
59
- const r = spawnSync(cmd, ['--version'], {
59
+ // Args ride the command string whenever shell is true: an args array
60
+ // under shell is DEP0190 on Node 24+ (and would double the --version
61
+ // the win32 fallback string already carries). Without a shell the
62
+ // array stays — spawn needs the separated argument there.
63
+ const r = spawnSync(cmd, shell ? undefined : ['--version'], {
60
64
  shell,
61
65
  windowsHide: true,
62
66
  stdio: 'pipe',
@@ -0,0 +1,187 @@
1
+ import { confirmApprovalToken, inspectApprovalToken, type ApprovalEntry } from './lib/approval-tokens.ts';
2
+ import { enrollApprovalsPin, isApprovalsPinEnrolled, verifyApprovalsPin } from './lib/approvals-pin.ts';
3
+ import { readSecret } from './lib/cli-io.ts';
4
+
5
+ // The human half of the approval gate: `npx huaweicloud-devkit approve <token>`
6
+ // is the only channel that writes a user confirmation, so it must be driven
7
+ // by a person at a terminal. The command refuses every non-interactive
8
+ // caller (an agent piping into Bash cannot pass), and it refuses to record
9
+ // the confirmation without the PIN. The door has no flags, because a flag
10
+ // would be an escape hatch for the caller the gate is built to stop.
11
+ //
12
+ // PIN enrollment is its own verb (`pin`): approve refuses outright on a
13
+ // machine with no enrolled PIN instead of enrolling inline — an inline
14
+ // first-use enroll would let any pseudo-terminal caller choose the PIN.
15
+ //
16
+ // The token lifecycle and the PIN record are pure state/crypto modules
17
+ // (lib/approval-tokens.ts, lib/approvals-pin.ts); this file owns prompts and
18
+ // exit codes, and takes its terminal as an injected ApproveIo so tests can
19
+ // drive both the refusal and the interactive paths without a real TTY.
20
+
21
+ const USAGE = 'Usage: npx huaweicloud-devkit approve <token>';
22
+ const PIN_USAGE = 'Usage: npx huaweicloud-devkit pin';
23
+
24
+ const PIN_ATTEMPTS = 3;
25
+ const ENROLL_ATTEMPTS = 2;
26
+
27
+ export interface ApproveIo {
28
+ isTTY: boolean;
29
+ write(text: string): void;
30
+ readLine(): Promise<string>;
31
+ }
32
+
33
+ export function createProcessApproveIo(): ApproveIo {
34
+ return {
35
+ // Both ends must be terminals: stdout-only TTY (agent captures output)
36
+ // and stdin-only TTY (agent feeds input) are both agent-shaped pipes.
37
+ isTTY: Boolean(process.stdin.isTTY && process.stdout.isTTY),
38
+ write: (text) => {
39
+ process.stdout.write(text);
40
+ },
41
+ readLine: () => readSecret(''),
42
+ };
43
+ }
44
+
45
+ function renderCommand(argsRedacted: unknown): string {
46
+ if (Array.isArray(argsRedacted)) {
47
+ const rendered = argsRedacted.map((arg) => (typeof arg === 'string' ? arg : JSON.stringify(arg)));
48
+ return `hcloud ${rendered.join(' ')}`;
49
+ }
50
+ return JSON.stringify(argsRedacted);
51
+ }
52
+
53
+ function printRefusal(io: ApproveIo, inspectionState: string): number {
54
+ if (inspectionState === 'not_found') {
55
+ io.write('No pending approval matches that token.\n');
56
+ } else if (inspectionState === 'expired') {
57
+ io.write(
58
+ 'That approval expired. A confirmation must happen within 5 minutes of the plan; ask the agent to plan the command again.\n',
59
+ );
60
+ } else {
61
+ io.write('This approval was already used.\n');
62
+ }
63
+ return inspectionState === 'already_consumed' ? 0 : 1;
64
+ }
65
+
66
+ async function enrollPin(io: ApproveIo): Promise<boolean> {
67
+ io.write('Choose a PIN of at least 6 characters.\n');
68
+ for (let attempt = 1; attempt <= ENROLL_ATTEMPTS; attempt++) {
69
+ io.write('Choose a PIN: ');
70
+ const first = await io.readLine();
71
+ io.write('Re-type the PIN: ');
72
+ const second = await io.readLine();
73
+ if (first !== second) {
74
+ io.write(attempt < ENROLL_ATTEMPTS ? 'The PINs did not match, try again.\n' : 'The PINs did not match.\n');
75
+ continue;
76
+ }
77
+ const enrolled = enrollApprovalsPin(first);
78
+ if (!enrolled.ok) {
79
+ io.write(`Cannot enroll the approvals PIN: ${enrolled.reason ?? 'unknown error'}.\n`);
80
+ return false;
81
+ }
82
+ io.write('Approvals PIN enrolled.\n');
83
+ return true;
84
+ }
85
+ return false;
86
+ }
87
+
88
+ async function verifyPin(io: ApproveIo): Promise<boolean> {
89
+ for (let attempt = 1; attempt <= PIN_ATTEMPTS; attempt++) {
90
+ io.write('PIN: ');
91
+ const pin = await io.readLine();
92
+ if (verifyApprovalsPin(pin).ok) return true;
93
+ if (attempt < PIN_ATTEMPTS) io.write(`Incorrect PIN (${attempt}/${PIN_ATTEMPTS}), try again.\n`);
94
+ }
95
+ io.write('Too many incorrect PIN attempts.\n');
96
+ return false;
97
+ }
98
+
99
+ function printConfirmResult(
100
+ io: ApproveIo,
101
+ status: ReturnType<typeof confirmApprovalToken>['status'],
102
+ reason: string | undefined,
103
+ ): number {
104
+ switch (status) {
105
+ case 'confirmed':
106
+ io.write('Confirmed. The agent may now run this command once.\n');
107
+ return 0;
108
+ case 'already_confirmed':
109
+ io.write('This approval was already confirmed. The agent may run this command once.\n');
110
+ return 0;
111
+ case 'already_consumed':
112
+ io.write('This approval was already used.\n');
113
+ return 0;
114
+ case 'expired':
115
+ io.write(
116
+ 'That approval expired. A confirmation must happen within 5 minutes of the plan; ask the agent to plan the command again.\n',
117
+ );
118
+ return 1;
119
+ case 'custody_unavailable':
120
+ io.write(`Cannot record the confirmation: ${reason ?? 'the vault master key is unavailable'}.\n`);
121
+ return 1;
122
+ case 'not_found':
123
+ io.write('No pending approval matches that token.\n');
124
+ return 1;
125
+ }
126
+ }
127
+
128
+ export async function runApproveCommand(argv: string[], io: ApproveIo): Promise<number> {
129
+ const token = argv[0];
130
+ // No flags: any extra argv is a caller trying to steer the confirmation.
131
+ if (!token || token.startsWith('-') || argv.length > 1) {
132
+ io.write(`${USAGE}\n`);
133
+ return 1;
134
+ }
135
+
136
+ const inspection = inspectApprovalToken(token);
137
+ if (inspection.state !== 'valid') return printRefusal(io, inspection.state);
138
+
139
+ const entry: ApprovalEntry | undefined = inspection.entry;
140
+ if (!entry) {
141
+ io.write('No pending approval matches that token.\n');
142
+ return 1;
143
+ }
144
+
145
+ io.write(`Confirming: ${renderCommand(entry.argsRedacted)}\n`);
146
+ io.write('This authorizes ONE execution of exactly this command.\n');
147
+
148
+ // The TTY gate sits after the description so a human sees what would have
149
+ // been confirmed, and before any prompt so no pipe can answer one.
150
+ if (!io.isTTY) {
151
+ io.write('Approvals must be confirmed in your own interactive terminal.\n');
152
+ return 1;
153
+ }
154
+
155
+ // Enrollment is a deliberate separate step, never an inline fallback: a
156
+ // first confirm that mints its own PIN would enroll whatever the current
157
+ // caller typed, and a pseudo-terminal makes even an agent "interactive".
158
+ if (!isApprovalsPinEnrolled()) {
159
+ io.write(
160
+ 'No approvals PIN is enrolled yet. Run "npx huaweicloud-devkit pin" in your own terminal once, then confirm plans with "approve".\n',
161
+ );
162
+ return 1;
163
+ }
164
+ if (!(await verifyPin(io))) {
165
+ return 1;
166
+ }
167
+
168
+ const result = confirmApprovalToken(token);
169
+ return printConfirmResult(io, result.status, result.reason);
170
+ }
171
+
172
+ // `npx huaweicloud-devkit pin`: the deliberate enrollment step the approve
173
+ // command refuses to perform inline. Same door shape as approve — no flags,
174
+ // TTY-gated, injected io — because it writes the credential the confirmation
175
+ // gate trusts.
176
+ export async function runPinCommand(argv: string[], io: ApproveIo): Promise<number> {
177
+ // No flags: any extra argv is a caller trying to steer the enrollment.
178
+ if (argv.length > 0) {
179
+ io.write(`${PIN_USAGE}\n`);
180
+ return 1;
181
+ }
182
+ if (!io.isTTY) {
183
+ io.write('The approvals PIN must be enrolled in your own interactive terminal.\n');
184
+ return 1;
185
+ }
186
+ return (await enrollPin(io)) ? 0 : 1;
187
+ }
@@ -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 {
@@ -19,6 +19,14 @@ import { triageUnknownService } from './hcloud-triage.ts';
19
19
  // The machinery lives in src/lib/approval-tokens.ts (the CLI face's
20
20
  // consent layer for plan_cli_command / run_approved_command).
21
21
 
22
+ // The plan's terminal-confirmation block: `needed` says the command waits
23
+ // on a confirmation the user makes in their own terminal, `command` is the
24
+ // exact line they run (present only on plans that minted a token).
25
+ export interface HcloudPlanUserConfirmation {
26
+ needed: boolean;
27
+ command?: string;
28
+ }
29
+
22
30
  export interface HcloudPlan {
23
31
  executable: string;
24
32
  args: string[];
@@ -27,7 +35,11 @@ export interface HcloudPlan {
27
35
  warnings: Array<string | SgFinding>;
28
36
  classification: RiskDecision;
29
37
  sgFindings: SgFinding[];
30
- approvalToken: string;
38
+ // Present only when this call minted one: run paths pass
39
+ // mintApprovalToken:false, so a run result never carries a fresh usable
40
+ // token (the model leaves minting to the plan face).
41
+ approvalToken?: string;
42
+ userConfirmation: HcloudPlanUserConfirmation;
31
43
  safeToRun: boolean;
32
44
  }
33
45
 
@@ -41,6 +53,20 @@ export interface HcloudPlanOptions extends ClassifyOptions {
41
53
  // operator-side only — never a tool argument an agent could aim at a fake
42
54
  // catalog to downgrade its own verdict.
43
55
  metaDir?: string;
56
+ // False on run paths: only the plan face mints approval tokens. Defaults
57
+ // true, so the plan tool face keeps its consent contract unchanged.
58
+ mintApprovalToken?: boolean;
59
+ }
60
+
61
+ // Does this command wait on the user's terminal confirmation? The verdict
62
+ // comes from the STRICT view — allowWrites forced false — never the
63
+ // caller's option, so an agent passing allowWrites:true cannot weaken it.
64
+ // Only write/execution denies answer true: secret, credential, and invalid
65
+ // denies are never unlockable by a terminal confirmation, and reads never
66
+ // need one.
67
+ export function needsUserConfirmation(args: string[], options: ClassifyOptions = {}): boolean {
68
+ const strict = classifyHcloudArgs(args, { ...options, allowWrites: false });
69
+ return strict.decision === 'deny' && (strict.risk === 'write' || strict.risk === 'execution');
44
70
  }
45
71
 
46
72
  function quoteShellArg(value: unknown): string {
@@ -323,6 +349,14 @@ export function planHcloudCommand(args: unknown, options: HcloudPlanOptions = {}
323
349
  warnings.push(`${triage.message} ${triage.nextStep}`);
324
350
  }
325
351
  }
352
+ const approvalToken =
353
+ options.mintApprovalToken === false
354
+ ? undefined
355
+ : createApprovalToken(normalizedArgs, {
356
+ secretsSubstitutable: secretsSubstitutable(normalizedArgs),
357
+ argsPinView: pinViewArgs(normalizedArgs),
358
+ });
359
+ const needsConfirmation = needsUserConfirmation(normalizedArgs, options);
326
360
  return {
327
361
  executable: 'hcloud',
328
362
  args: normalizedArgs.map((arg) => redactSecrets(arg)),
@@ -335,10 +369,15 @@ export function planHcloudCommand(args: unknown, options: HcloudPlanOptions = {}
335
369
  warnings,
336
370
  classification: applyPreflightFindings(effectiveClassification, sgFindings),
337
371
  sgFindings,
338
- approvalToken: createApprovalToken(normalizedArgs, {
339
- secretsSubstitutable: secretsSubstitutable(normalizedArgs),
340
- argsPinView: pinViewArgs(normalizedArgs),
341
- }),
372
+ ...(approvalToken !== undefined ? { approvalToken } : {}),
373
+ // `command` exists only where a token was minted: a run-path plan stays
374
+ // silent rather than name a line for a token the run cannot offer.
375
+ userConfirmation: needsConfirmation
376
+ ? {
377
+ needed: true,
378
+ ...(approvalToken !== undefined ? { command: `npx huaweicloud-devkit approve ${approvalToken}` } : {}),
379
+ }
380
+ : { needed: false },
342
381
  safeToRun: effectiveClassification.decision === 'allow',
343
382
  };
344
383
  }
@@ -54,8 +54,11 @@ export async function runHcloud(args: unknown, options: HcloudRunOptions = {}):
54
54
  // longer reach the spawn as a doubled `hcloud hcloud ...` prefix. The
55
55
  // warning for the stripped token comes from the plan this call builds.
56
56
  const { args: normalizedArgs } = stripLeadingHcloudBinArgs(inputArgs);
57
+ // Run paths never mint approval tokens: only the plan face does, so a run
58
+ // result can never hand the agent a fresh usable token for the next
59
+ // execution.
57
60
  const plan: HcloudPlanWithArgs = {
58
- ...planHcloudCommand(normalizedArgs, options),
61
+ ...planHcloudCommand(normalizedArgs, { ...options, mintApprovalToken: false }),
59
62
  rawArgs: normalizedArgs,
60
63
  };
61
64
  assertAllowed(plan.classification);