huaweicloud-devkit 2.0.0-next.1 → 2.0.0-next.3

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 (51) hide show
  1. package/README.md +3 -1
  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/opencode-config.js +73 -2
  11. package/plugins/huaweicloud-core/dist/agents/opencode.js +62 -1
  12. package/plugins/huaweicloud-core/dist/auth/s1-store.js +43 -22
  13. package/plugins/huaweicloud-core/dist/hcloud-plan.js +25 -5
  14. package/plugins/huaweicloud-core/dist/lib/approval-mode.js +30 -0
  15. package/plugins/huaweicloud-core/dist/lib/approval-tokens.js +3 -3
  16. package/plugins/huaweicloud-core/dist/lib/opencode-ask-rule.js +116 -0
  17. package/plugins/huaweicloud-core/dist/lib/pack-state.js +23 -19
  18. package/plugins/huaweicloud-core/dist/lib/param-warnings.js +70 -0
  19. package/plugins/huaweicloud-core/dist/lib/state-dir.js +125 -0
  20. package/plugins/huaweicloud-core/dist/mcp-protocol.js +20 -1
  21. package/plugins/huaweicloud-core/dist/mcp-server.js +849 -585
  22. package/plugins/huaweicloud-core/dist/mcp-server.js.map +4 -4
  23. package/plugins/huaweicloud-core/dist/packs/huaweicloud-cli/tools.js +74 -22
  24. package/plugins/huaweicloud-core/dist/setup-cli.js +22 -3
  25. package/plugins/huaweicloud-core/dist/tool-schemas.js +15 -0
  26. package/plugins/huaweicloud-core/dist/tools.js +36 -4
  27. package/plugins/huaweicloud-core/dist/update-skip.js +5 -6
  28. package/plugins/huaweicloud-core/openclaw.plugin.json +1 -1
  29. package/plugins/huaweicloud-core/safety/rules/cloud-risk-rules.json +78 -2
  30. package/plugins/huaweicloud-core/skills/huaweicloud-cli-and-auth/SKILL.md +4 -4
  31. package/plugins/huaweicloud-core/skills/huaweicloud-safety/SKILL.md +8 -7
  32. package/plugins/huaweicloud-core/skills/huaweicloud-safety/references/approvals.md +10 -0
  33. package/plugins/huaweicloud-core/src/agents/codearts-work.ts +3 -0
  34. package/plugins/huaweicloud-core/src/agents/codearts.ts +4 -0
  35. package/plugins/huaweicloud-core/src/agents/opencode-config.ts +82 -2
  36. package/plugins/huaweicloud-core/src/agents/opencode.ts +86 -1
  37. package/plugins/huaweicloud-core/src/auth/s1-store.ts +41 -20
  38. package/plugins/huaweicloud-core/src/hcloud-plan.ts +38 -6
  39. package/plugins/huaweicloud-core/src/lib/approval-mode.ts +32 -0
  40. package/plugins/huaweicloud-core/src/lib/approval-tokens.ts +3 -3
  41. package/plugins/huaweicloud-core/src/lib/opencode-ask-rule.ts +131 -0
  42. package/plugins/huaweicloud-core/src/lib/pack-state.ts +23 -20
  43. package/plugins/huaweicloud-core/src/lib/param-warnings.ts +69 -0
  44. package/plugins/huaweicloud-core/src/lib/state-dir.ts +128 -0
  45. package/plugins/huaweicloud-core/src/mcp-protocol.ts +20 -1
  46. package/plugins/huaweicloud-core/src/mcp-server.ts +13 -0
  47. package/plugins/huaweicloud-core/src/packs/huaweicloud-cli/tools.ts +81 -24
  48. package/plugins/huaweicloud-core/src/setup-cli.ts +27 -2
  49. package/plugins/huaweicloud-core/src/tool-schemas.ts +16 -0
  50. package/plugins/huaweicloud-core/src/tools.ts +39 -4
  51. package/plugins/huaweicloud-core/src/update-skip.ts +5 -6
@@ -22,6 +22,12 @@ import {
22
22
  removeSkillTreePermissionSeam,
23
23
  skillTreePermissionGlobs,
24
24
  } from '../lib/opencode-permission-seam.ts';
25
+ import {
26
+ ASK_RULE_ACTION,
27
+ applyAskPermissionRule,
28
+ opencodeAskRuleVersionSupported,
29
+ removeAskPermissionRule,
30
+ } from '../lib/opencode-ask-rule.ts';
25
31
  import { asRecord } from '../lib/as-record.ts';
26
32
  import { devkitOwnedSkillNames, tryCoreSkillNames } from '../install-payload.ts';
27
33
 
@@ -92,6 +98,43 @@ export function openCodeSeamGate(): 'on' | 'off' {
92
98
  return opencodeSeamVersionSupported(probeOpencodeVersion()) ? 'on' : 'off';
93
99
  }
94
100
 
101
+ // The ask rule's version gate, same doctrine as the seam's:
102
+ // HUAWEICLOUD_OPENCODE_ASK_RULE=on|off is the deterministic override for
103
+ // the installer test suite (e2e strips it — the runner's install relies on
104
+ // the natural probe); unset runs the probe. Unknown polarity is off: the
105
+ // `permissions` array is the V2 shape measured on 2.2.7 only, so a
106
+ // below-2.0, absent, or unparsable opencode writes NEITHER half of the
107
+ // posture — the client rule without the server env double-gates, the env
108
+ // without the rule fail-opens, and the pair must move together.
109
+ export function openCodeAskGate(): 'on' | 'off' {
110
+ const forced = process.env.HUAWEICLOUD_OPENCODE_ASK_RULE;
111
+ if (forced === 'on' || forced === 'off') return forced;
112
+ return opencodeAskRuleVersionSupported(probeOpencodeVersion()) ? 'on' : 'off';
113
+ }
114
+
115
+ // The server half of the ask posture: DEVKIT_APPROVAL_MODE=ask in the mcp
116
+ // entry's environment (the field OpenCode reads — the applyPacksToEntry
117
+ // 'environment' precedent). Add-only-if-absent with the packs-write
118
+ // doctrine: a user-set value other than 'ask' is theirs and wins with a
119
+ // one-line WARN; 'ask' already present needs no write. An absent or empty
120
+ // environment object is created. No delete path: uninstall removes the
121
+ // whole mcp entry wholesale. Runs ONLY under the ask gate — see
122
+ // openCodeAskGate for why the halves must move together.
123
+ function applyApprovalModeToEntry(entry: Record<string, unknown>): boolean {
124
+ const env = asRecord(entry.environment);
125
+ const current = env.DEVKIT_APPROVAL_MODE;
126
+ if (current === 'ask') return false;
127
+ if (current !== undefined) {
128
+ const shown = typeof current === 'string' ? current : JSON.stringify(current);
129
+ console.log(
130
+ ` \x1b[33m[WARN]\x1b[0m OpenCode mcp entry already sets DEVKIT_APPROVAL_MODE=${shown} — keeping the user's value; it may not match the permissions ask rule (see README, Harness permission notes).`,
131
+ );
132
+ return false;
133
+ }
134
+ entry.environment = { ...env, DEVKIT_APPROVAL_MODE: 'ask' };
135
+ return true;
136
+ }
137
+
95
138
  // The glob set the seam covers: the plugin-dir tree actually deployed by
96
139
  // this run plus per-skill globs for the native core meta-skill copies
97
140
  // (under the XDG opencode skills dir). An unusable manifest degrades to the
@@ -140,11 +183,33 @@ export function updateOpenCodeConfig(pluginDir: string): void {
140
183
  ' \x1b[33m[INFO]\x1b[0m opencode not verifiably at or above the measured permission floor — skipping the skills-tree permission write; see README (Harness permission notes) if direct skill reads prompt for approval.',
141
184
  );
142
185
  }
186
+ const askOn = openCodeAskGate() === 'on';
187
+ // The ask rule is a FOURTH change source, computed before the unchanged
188
+ // short-circuit for the same reason as the seam: an unchanged mcp entry
189
+ // is the dominant update shape, and every install made before the ask
190
+ // posture existed is exactly the population this must heal. The rule
191
+ // mutates config in place (ownership rules in lib/opencode-ask-rule.ts),
192
+ // so the single write below carries it.
193
+ let askRuleChanged = false;
194
+ if (askOn) {
195
+ const applied = applyAskPermissionRule(config);
196
+ askRuleChanged = applied.changed;
197
+ if (applied.skipped) {
198
+ console.log(
199
+ ` \x1b[33m[WARN]\x1b[0m opencode permissions already has an entry for ${ASK_RULE_ACTION} — keeping it as the user's (the posture follows its effect; see README, Harness permission notes).`,
200
+ );
201
+ }
202
+ } else {
203
+ console.log(
204
+ ' \x1b[33m[INFO]\x1b[0m opencode not verifiably at or above 2.0 — keeping the terminal token approval gate; no permissions ask rule or DEVKIT_APPROVAL_MODE is written.',
205
+ );
206
+ }
143
207
  const existing: unknown = asRecord(config.mcp)['huaweicloud-devkit'];
144
208
  if (existing) {
145
209
  const { entry, changed } = mergeCommandStyle(existing, { mcpPath });
146
210
  const packsChanged = applyPacksToEntry(entry, 'environment', 'OpenCode');
147
- if (!changed && !packsChanged && !permChanged) {
211
+ const askEnvChanged = askOn && applyApprovalModeToEntry(entry);
212
+ if (!changed && !packsChanged && !permChanged && !askRuleChanged && !askEnvChanged) {
148
213
  console.log(` OpenCode MCP config unchanged: ${configPath}`);
149
214
  return;
150
215
  }
@@ -153,6 +218,9 @@ export function updateOpenCodeConfig(pluginDir: string): void {
153
218
  config.mcp = mcpMap;
154
219
  writeMcpSettingsFile(configPath, config);
155
220
  console.log(` OpenCode MCP config merged (user fields preserved): ${configPath}`);
221
+ if (askRuleChanged || askEnvChanged) {
222
+ console.log(` ASK approval (permissions ask rule + DEVKIT_APPROVAL_MODE) -> ${configPath}`);
223
+ }
156
224
  return;
157
225
  }
158
226
  const mcpMap: Record<string, unknown> = asRecord(config.mcp);
@@ -162,10 +230,14 @@ export function updateOpenCodeConfig(pluginDir: string): void {
162
230
  const delta = takeAgentDelta('opencode');
163
231
  if (delta) entry = asRecord(applyUserDelta(entry, delta, 'command'));
164
232
  applyPacksToEntry(entry, 'environment', 'OpenCode');
233
+ const askEnvChanged = askOn && applyApprovalModeToEntry(entry);
165
234
  mcpMap['huaweicloud-devkit'] = entry;
166
235
  config.mcp = mcpMap;
167
236
  writeMcpSettingsFile(configPath, config);
168
237
  console.log(` OpenCode config updated: ${configPath}`);
238
+ if (askRuleChanged || askEnvChanged) {
239
+ console.log(` ASK approval (permissions ask rule + DEVKIT_APPROVAL_MODE) -> ${configPath}`);
240
+ }
169
241
  }
170
242
 
171
243
  export function removeOpenCodeConfig(): void {
@@ -190,8 +262,16 @@ export function removeOpenCodeConfig(): void {
190
262
  // value-exact deletion keeps user-modified rules (the ownership contract
191
263
  // lives in lib/opencode-permission-seam.ts).
192
264
  const permCleaned = removeSkillTreePermissionSeam(config, openCodeSeamGlobs(opencodePluginsDir()));
193
- if (!hadEntry && !permCleaned) return;
265
+ // The ask-rule cleanup also runs unconditionally of the version gate: an
266
+ // uninstall must remove what any past install wrote — the opencode that
267
+ // gated the write may since have been upgraded, downgraded, or removed
268
+ // from PATH. Value-exact deletion keeps user-modified entries (the
269
+ // ownership contract lives in lib/opencode-ask-rule.ts); the mcp entry
270
+ // (and its DEVKIT_APPROVAL_MODE env) is already gone wholesale above.
271
+ const askCleaned = removeAskPermissionRule(config);
272
+ if (!hadEntry && !permCleaned && !askCleaned) return;
194
273
  writeMcpSettingsFile(configPath, config);
195
274
  if (hadEntry) console.log(` OpenCode MCP config cleaned: ${configPath}`);
196
275
  if (permCleaned) console.log(` Skills-tree permission rules removed: ${configPath}`);
276
+ if (askCleaned) console.log(` ASK permission rule removed: ${configPath}`);
197
277
  }
@@ -28,7 +28,14 @@ import {
28
28
  removeIfExists,
29
29
  type DeployMode,
30
30
  } from '../install-payload.ts';
31
- import { removeOpenCodeConfig, updateOpenCodeConfig, openCodeSeamGate, openCodeSeamGlobs } from './opencode-config.ts';
31
+ import {
32
+ removeOpenCodeConfig,
33
+ updateOpenCodeConfig,
34
+ openCodeSeamGate,
35
+ openCodeSeamGlobs,
36
+ openCodeAskGate,
37
+ } from './opencode-config.ts';
38
+ import { inspectAskPermissionRule } from '../lib/opencode-ask-rule.ts';
32
39
  import type { DoctorReporter } from '../doctor-report.ts';
33
40
  import { asRecord } from '../lib/as-record.ts';
34
41
 
@@ -46,6 +53,84 @@ export function opencodeDoctorMcpConfigured(): string | null {
46
53
  return null;
47
54
  }
48
55
 
56
+ // Doctor: the ASK approval posture check — OpenCode installs only. The
57
+ // posture is a PAIR: the client half (the permissions ask rule that makes
58
+ // opencode itself prompt on huaweicloud_run_approved_command) and the
59
+ // server half (DEVKIT_APPROVAL_MODE=ask in the mcp entry's env). A
60
+ // gate-off opencode is a SKIP — token mode is that install's legitimate
61
+ // posture — and so are configs the installer itself refuses to touch.
62
+ // Every mixed state is a FAIL because each lies in a known direction:
63
+ // the rule without the env double-gates (the client prompts AND the
64
+ // server still demands a token), the env without the rule fail-opens
65
+ // (the server trusts a prompt nobody shows), and an allow/deny rule
66
+ // destroys the ask contract outright ("always allow" stops prompting;
67
+ // deny bricks the write tool entirely).
68
+ export function opencodeDoctorAskRule(ctx: DoctorReporter): void {
69
+ if (openCodeAskGate() === 'off') {
70
+ ctx.skip('ASK approval posture (opencode not verifiably at or above 2.0)');
71
+ return;
72
+ }
73
+ let cfg: Record<string, unknown> | null;
74
+ try {
75
+ cfg = asRecord(JSON.parse(readFileSync(opencodeConfigFile(), 'utf8')));
76
+ } catch {
77
+ cfg = null;
78
+ }
79
+ const posture = cfg !== null ? inspectAskPermissionRule(cfg) : null;
80
+ if (cfg === null || posture === 'foreign') {
81
+ ctx.skip(
82
+ 'ASK approval posture: opencode config unreadable or permissions not array-shaped — the installer keeps it untouched; add the ask rule and DEVKIT_APPROVAL_MODE manually (see README, Harness permission notes)',
83
+ );
84
+ return;
85
+ }
86
+ // The mcp entry carries the server half; a missing entry counts as no
87
+ // env, so the halves are judged independently of entry presence.
88
+ const env = asRecord(asRecord(asRecord(cfg.mcp)['huaweicloud-devkit']).environment);
89
+ const envAsk = env.DEVKIT_APPROVAL_MODE === 'ask';
90
+ const label = 'ASK approval posture (client prompt + server env)';
91
+ if (posture === 'ask') {
92
+ ctx.check(
93
+ label,
94
+ envAsk,
95
+ envAsk
96
+ ? ''
97
+ : 'DEVKIT_APPROVAL_MODE=ask missing from the mcp entry — the client prompts AND the server still demands a token (re-run: npx huaweicloud-devkit install --target opencode)',
98
+ );
99
+ return;
100
+ }
101
+ if (posture === 'allow') {
102
+ // FAIL, never a warn: with the env also ask this is fail-open (the
103
+ // always-allow rule suppresses the prompt the server trusts); without
104
+ // it the run degrades to the token gate. Either way the ask contract
105
+ // is silently gone.
106
+ ctx.check(
107
+ label,
108
+ false,
109
+ 'the permissions rule for the run tool is "allow" (always allow) — writes no longer prompt: fail-open when DEVKIT_APPROVAL_MODE=ask, a plain token gate otherwise. Delete that rule or set its effect to "ask" (see README, Harness permission notes)',
110
+ );
111
+ return;
112
+ }
113
+ if (posture === 'deny') {
114
+ ctx.check(
115
+ label,
116
+ false,
117
+ 'the permissions rule for the run tool is "deny" — the write tool is blocked entirely. Delete that rule or set its effect to "ask" (see README, Harness permission notes)',
118
+ );
119
+ return;
120
+ }
121
+ if (envAsk) {
122
+ // posture === 'absent': the fail-open direction.
123
+ ctx.check(
124
+ label,
125
+ false,
126
+ 'DEVKIT_APPROVAL_MODE=ask is set but the permissions ask rule is missing — the server trusts a client prompt nobody shows (re-run: npx huaweicloud-devkit install --target opencode, or unset DEVKIT_APPROVAL_MODE in the mcp entry)',
127
+ );
128
+ return;
129
+ }
130
+ // Token mode is the legitimate default posture, not an error.
131
+ ctx.check('ASK approval posture (token mode)', true, '');
132
+ }
133
+
49
134
  // Doctor: the skills-tree permission seam check — OpenCode installs only
50
135
  // (the seam is the installer's zero-prompt path for direct skill reads on
51
136
  // that harness). Verifies the two keys and their values, honoring the
@@ -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 {
@@ -4,10 +4,18 @@
4
4
  // classification, OBS/SG/parameter warnings, required-parameter
5
5
  // validation, and the approval token. The consent layer itself lives in
6
6
  // src/lib/approval-tokens.ts.
7
+ //
8
+ // The plan's approval posture is mode-dependent (HcloudPlanOptions.
9
+ // approvalMode): 'ask' (DEVKIT_APPROVAL_MODE=ask) plans for the harness
10
+ // client's own permission prompt as the user's confirmation, so no token
11
+ // is minted and userConfirmation carries the ask note instead of a
12
+ // terminal approve line; 'token' (the default) keeps the mint + approve
13
+ // line contract above.
7
14
 
8
15
  import { classifyHcloudArgs, redactSecrets, stripExecutable, type ClassifyOptions } from './safety-policy.ts';
9
16
  import { isHcloudToken } from './safety/tokens.ts';
10
17
  import { createApprovalToken } from './lib/approval-tokens.ts';
18
+ import type { ApprovalMode } from './lib/approval-mode.ts';
11
19
  import type { RiskDecision } from './risk-rule-engine.ts';
12
20
  import { obsWriteHint } from './hcloud-obs-redact.ts';
13
21
  import { applyPreflightFindings, preflightSecurityGroupCheck, type SgFinding } from './hcloud-sg-preflight.ts';
@@ -21,10 +29,15 @@ import { triageUnknownService } from './hcloud-triage.ts';
21
29
 
22
30
  // The plan's terminal-confirmation block: `needed` says the command waits
23
31
  // 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).
32
+ // exact line they run (present only on plans that minted a token). Ask
33
+ // mode shifts the confirmation onto the harness client's permission
34
+ // prompt: `mode` names that posture and `note` teaches the run call that
35
+ // satisfies it — no `command` exists to name.
25
36
  export interface HcloudPlanUserConfirmation {
26
37
  needed: boolean;
27
38
  command?: string;
39
+ mode?: 'ask';
40
+ note?: string;
28
41
  }
29
42
 
30
43
  export interface HcloudPlan {
@@ -56,6 +69,12 @@ export interface HcloudPlanOptions extends ClassifyOptions {
56
69
  // False on run paths: only the plan face mints approval tokens. Defaults
57
70
  // true, so the plan tool face keeps its consent contract unchanged.
58
71
  mintApprovalToken?: boolean;
72
+ // The approval posture this plan reports: 'ask' suppresses token minting
73
+ // and describes the client-prompt confirmation in userConfirmation;
74
+ // 'token' (the default) keeps the terminal gate. The tool faces resolve
75
+ // it from DEVKIT_APPROVAL_MODE (lib/approval-mode.ts) — never a tool
76
+ // argument an agent could set.
77
+ approvalMode?: ApprovalMode;
59
78
  }
60
79
 
61
80
  // Does this command wait on the user's terminal confirmation? The verdict
@@ -349,8 +368,13 @@ export function planHcloudCommand(args: unknown, options: HcloudPlanOptions = {}
349
368
  warnings.push(`${triage.message} ${triage.nextStep}`);
350
369
  }
351
370
  }
371
+ const approvalMode = options.approvalMode ?? 'token';
372
+ // Ask mode never mints: the confirmation is the harness client's prompt
373
+ // on the run call, so there is no token to hand the model and nothing
374
+ // lands in the approvals store. Run paths keep mintApprovalToken:false
375
+ // in both modes.
352
376
  const approvalToken =
353
- options.mintApprovalToken === false
377
+ approvalMode === 'ask' || options.mintApprovalToken === false
354
378
  ? undefined
355
379
  : createApprovalToken(normalizedArgs, {
356
380
  secretsSubstitutable: secretsSubstitutable(normalizedArgs),
@@ -372,11 +396,19 @@ export function planHcloudCommand(args: unknown, options: HcloudPlanOptions = {}
372
396
  ...(approvalToken !== undefined ? { approvalToken } : {}),
373
397
  // `command` exists only where a token was minted: a run-path plan stays
374
398
  // silent rather than name a line for a token the run cannot offer.
399
+ // Ask mode names the posture instead — the confirmation happens at the
400
+ // run call, and the note teaches exactly that.
375
401
  userConfirmation: needsConfirmation
376
- ? {
377
- needed: true,
378
- ...(approvalToken !== undefined ? { command: `npx huaweicloud-devkit approve ${approvalToken}` } : {}),
379
- }
402
+ ? approvalMode === 'ask'
403
+ ? {
404
+ needed: true,
405
+ mode: 'ask',
406
+ note: 'The harness client confirms this command with the user when huaweicloud_run_approved_command is called. Call it with the same args and approvedByUser: true. No terminal approval line or token is needed.',
407
+ }
408
+ : {
409
+ needed: true,
410
+ ...(approvalToken !== undefined ? { command: `npx huaweicloud-devkit approve ${approvalToken}` } : {}),
411
+ }
380
412
  : { needed: false },
381
413
  safeToRun: effectiveClassification.decision === 'allow',
382
414
  };
@@ -0,0 +1,32 @@
1
+ // The hcloud write-approval posture, resolved from DEVKIT_APPROVAL_MODE.
2
+ //
3
+ // 'token' (the default) is the out-of-band terminal gate: the plan mints
4
+ // an approval token, the user confirms it in their own terminal
5
+ // (`npx huaweicloud-devkit approve <uuid>`), and run_approved_command
6
+ // consumes the token before executing. 'ask' moves the confirmation onto
7
+ // the harness client's own permission prompt: the operator opts in via
8
+ // the env var (normally written by the installer together with the
9
+ // client's ask rule), and accepting that client prompt IS the user's
10
+ // confirmation — no terminal trip, no UUID in the model's context; the
11
+ // plan mints nothing and the run needs only approvedByUser.
12
+ //
13
+ // Resolution is exact-match and fail-loud, mirroring the DEVKIT_PACKS
14
+ // unknown-id doctrine: a typo'd mode must not silently fall back to the
15
+ // weaker gate, so anything but 'ask' or 'token' throws with the env name
16
+ // and the bad value (case included — 'ASK' throws). Unset or empty keeps
17
+ // 'token'. The resolver is pure and takes the env as a parameter; every
18
+ // reader re-resolves from process.env (the mode is process-stable for the
19
+ // life of the process), so there is deliberately no cached module state
20
+ // to disagree with a fresh read. The module imports nothing: it feeds
21
+ // both the bundled mcp-server graph and the unbundled setup-cli graph.
22
+
23
+ export type ApprovalMode = 'token' | 'ask';
24
+
25
+ export const APPROVAL_MODE_ENV = 'DEVKIT_APPROVAL_MODE';
26
+
27
+ export function approvalModeFromEnv(env: Record<string, string | undefined>): ApprovalMode {
28
+ const raw = env[APPROVAL_MODE_ENV];
29
+ if (raw === undefined || raw === '') return 'token';
30
+ if (raw === 'ask' || raw === 'token') return raw;
31
+ throw new Error(`DEVKIT_APPROVAL_MODE must be "ask" or "token" (got "${raw}")`);
32
+ }
@@ -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
@@ -0,0 +1,131 @@
1
+ // The OpenCode ask-mode permission rule — pure merge/cleanup logic.
2
+ //
3
+ // Purpose: in the ASK approval posture (DEVKIT_APPROVAL_MODE=ask), the
4
+ // user's confirmation for an hcloud write is the harness client's own
5
+ // permission prompt on the huaweicloud_run_approved_command call — which
6
+ // only happens when the client is made to ASK for that tool. Measured on
7
+ // opencode 2.2.7: the V2 config key is a top-level `permissions` ARRAY of
8
+ // { action, resource, effect } objects; the MCP tool action is
9
+ // `<server>_<tool>`, and our server key is `huaweicloud-devkit`, so the
10
+ // action is `huaweicloud-devkit_huaweicloud_run_approved_command`; the
11
+ // config hot-reloads without restarting opencode; and a `deny` on that
12
+ // exact action prunes the tool from the live catalog (restored when the
13
+ // deny is removed) — which is also why an allow on it silently removes
14
+ // the gate. 2.2.7 still parses the V1 `permission` object the skills-tree
15
+ // seam writes (the bundle migrates it), but the array is the documented
16
+ // V2 shape — this rule rides ONLY the array form and is gated on opencode
17
+ // major >= 2; the V1 seam is untouched.
18
+ //
19
+ // Ownership rules: an entry on the ask action is user-owned by
20
+ // construction — add-only-if-absent (a pre-existing entry with ANY effect
21
+ // is the user's and survives the write; `skipped` reports it) and
22
+ // value-exact deletion (only the exact action + resource '*' + effect
23
+ // 'ask' triple is removed at uninstall) are the whole contract. The
24
+ // accepted edge is the same one the seam records: a user-authored
25
+ // same-shape rule that predates the write is removed together with it.
26
+ //
27
+ // This module is pure: no fs, no spawn, no console — opencode-config.ts
28
+ // owns I/O, the version probe, and logging; tests import these functions
29
+ // directly.
30
+
31
+ import { asRecord } from './as-record.ts';
32
+
33
+ export const ASK_RULE_ACTION = 'huaweicloud-devkit_huaweicloud_run_approved_command';
34
+ export const ASK_RULE_RESOURCE = '*';
35
+
36
+ export interface AskRuleApplyResult {
37
+ changed: boolean;
38
+ // True when nothing was written because the user owns the territory: an
39
+ // entry on the ask action already exists (any effect — including one
40
+ // identical to ours, indistinguishable from a pre-existing user rule),
41
+ // or `permissions` is present but not an array.
42
+ skipped: boolean;
43
+ }
44
+
45
+ function isRuleRecord(value: unknown): value is Record<string, unknown> {
46
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
47
+ }
48
+
49
+ // Mutates config in place. Fresh configs get the single-entry array;
50
+ // arrays without an entry on the ask action get ours APPENDED — OpenCode
51
+ // evaluates last-matching-rule-wins, so the appended entry is the
52
+ // effective one. Arrays that already carry an entry on the action, and
53
+ // non-array `permissions` shapes, are the user's: nothing is written.
54
+ export function applyAskPermissionRule(config: Record<string, unknown>): AskRuleApplyResult {
55
+ if (config.permissions === undefined) {
56
+ config.permissions = [{ action: ASK_RULE_ACTION, resource: ASK_RULE_RESOURCE, effect: 'ask' }];
57
+ return { changed: true, skipped: false };
58
+ }
59
+ if (!Array.isArray(config.permissions)) {
60
+ return { changed: false, skipped: true };
61
+ }
62
+ const rules: unknown[] = config.permissions;
63
+ if (rules.some((rule) => isRuleRecord(rule) && rule.action === ASK_RULE_ACTION)) {
64
+ return { changed: false, skipped: true };
65
+ }
66
+ rules.push({ action: ASK_RULE_ACTION, resource: ASK_RULE_RESOURCE, effect: 'ask' });
67
+ return { changed: true, skipped: false };
68
+ }
69
+
70
+ // Mutates config in place. Value-exact deletion only — an entry matching
71
+ // action + resource '*' + effect 'ask' exactly is ours; a user-modified
72
+ // entry (any other effect or resource) survives. The array key is pruned
73
+ // only when OUR removals emptied it; a pre-existing empty array is left
74
+ // untouched. Returns whether anything changed.
75
+ export function removeAskPermissionRule(config: Record<string, unknown>): boolean {
76
+ if (!Array.isArray(config.permissions)) return false;
77
+ const rules: unknown[] = config.permissions;
78
+ const kept = rules.filter(
79
+ (rule) =>
80
+ !(
81
+ isRuleRecord(rule) &&
82
+ rule.action === ASK_RULE_ACTION &&
83
+ rule.resource === ASK_RULE_RESOURCE &&
84
+ rule.effect === 'ask'
85
+ ),
86
+ );
87
+ if (kept.length === rules.length) return false;
88
+ if (kept.length === 0) {
89
+ delete config.permissions;
90
+ } else {
91
+ config.permissions = kept;
92
+ }
93
+ return true;
94
+ }
95
+
96
+ // The effective posture of the ask action. OpenCode evaluates
97
+ // last-matching-rule-wins, so the LAST entry on the action is the
98
+ // effective one — read that, never the first. Returns its effect
99
+ // ('ask' / 'allow' / 'deny'), 'absent' when no entry matches (or the
100
+ // array is empty / the key is missing), and 'foreign' for an unreadable
101
+ // posture: `permissions` present but not an array, or the last matching
102
+ // entry carrying an effect outside the allow/ask/deny vocabulary.
103
+ export function inspectAskPermissionRule(
104
+ config: Record<string, unknown>,
105
+ ): 'ask' | 'allow' | 'deny' | 'absent' | 'foreign' {
106
+ if (config.permissions === undefined) return 'absent';
107
+ if (!Array.isArray(config.permissions)) return 'foreign';
108
+ const rules: unknown[] = config.permissions;
109
+ for (let i = rules.length - 1; i >= 0; i--) {
110
+ const rule = asRecord(rules[i]);
111
+ if (rule.action !== ASK_RULE_ACTION) continue;
112
+ if (rule.effect === 'ask' || rule.effect === 'allow' || rule.effect === 'deny') {
113
+ return rule.effect;
114
+ }
115
+ return 'foreign';
116
+ }
117
+ return 'absent';
118
+ }
119
+
120
+ // Floor check for the probe result: the `permissions` array is the
121
+ // documented V2 shape, measured on 2.2.7 only. Opencode major >= 2 (the
122
+ // anchored `v<major>.` form, mirroring opencodeSeamVersionSupported's
123
+ // extract-not-pass-raw polarity); null and unparsable output are
124
+ // unsupported — the caller's polarity is skip, keeping BOTH the terminal
125
+ // token gate and its mcp env untouched rather than guessing.
126
+ export function opencodeAskRuleVersionSupported(version: string | null): boolean {
127
+ if (version === null) return false;
128
+ const match = /^v?(\d+)\./.exec(version.trim());
129
+ if (!match) return false;
130
+ return Number(match[1]) >= 2;
131
+ }