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
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
 
@@ -402,7 +404,7 @@ Debug logs are written to the plugin's `telemetry/telemetry-debug.log` file.
402
404
  - **Sandbox (DevStation)** — temporary cloud runtime for web app deployment with instant public URL preview
403
405
  - **Capability packs (56 MCP tools)** — the devkit ships ten packs (core 12 tools; huaweicloud-cli carries the 20 service skills plus the 7 KooCLI execution tools; sandbox, auth, obs, voucher, update, discovery, secrets, huaweicloud-open-mcp for the rest). The huaweicloud-open-mcp pack proxies Huawei Cloud's full OpenAPI catalog through the local huaweicloud-open-mcp gateway with one generic call tool (`huaweicloud_gateway_call`: search_apis → list_apis → get_api discovery, execute_api with gateway-engine-gated consent; install the gateway with pip or uv, or just have `uvx` on PATH — no persistent install needed). Discover packs with `huaweicloud_list_packs` → `huaweicloud_pack_info`, browse the effective skill catalog with `huaweicloud_list_skills` (every enabled pack's skills with name, description, version, and reference filenames in one call, plus `skillRoot` — the tree's absolute location; which skills are ENABLED is pack-gated and can change at runtime, so a `huawei-*` service skill absent from the catalog belongs to a trimmed pack — the six `huaweicloud-*` meta-skills never appear in it and are always available), read the skill files directly under `skillRoot` on a same-machine install (the stdio server instructions state the location at initialize, so no catalog call is needed just to start reading; the taught policy is action-first — attempt the direct read, the attempt itself is the reachability check), and fall back to `huaweicloud_retrieve_skill` only when the attempted read fails or is denied — the taught reaction is falling back (the loader needs no file access), never repeatedly requesting. (the gated, telemetry-bearing, portable fallback, whose stdio payload also carries `skillRoot`; the six core meta-skills are additionally installed as native skill copies on directory-loading agents for system-prompt visibility). Trim the surface with `DEVKIT_PACKS` (comma-separated pack ids, e.g. `DEVKIT_PACKS=core,sandbox`); unset means all packs, unknown ids fail fast at startup, and core (pack meta, safety and discovery surface) is always included — trimming huaweicloud-cli removes the CLI execution face and its approval tools together. In a live stdio agent session, `huaweicloud_packs_configure` enables or disables packs on the spot (session-scoped; the refreshed tool list is pushed to the agent, and restarting the session restores the operator posture; the stateless remote surface does not carry it). Manage the surface persistently after install with `npx huaweicloud-devkit packs status | enable <ids> | disable <ids> | all [--target <agent>]`: the command rewrites `DEVKIT_PACKS` inside every installed agent's MCP config (the install-time `--packs` flag never overwrites an existing value), and the change takes effect on the agent's next session restart.
404
406
 
405
- Harness permission notes (skill-tree reads outside the workspace): the taught reaction above is universal — when a direct read fails or is denied, fall back to `huaweicloud_retrieve_skill`, never repeatedly request. The OpenCode installer writes a persistent permission seam (external_directory allow + edit deny over the tree globs); on other harnesses the operator can pre-allow the tree in the harness's own config if prompts bother them. Honest semantics for the seam: the allow covers every path-taking tool including bash (an allowed external directory inherits workspace defaults), so shell-mediated writes to the tree stop asking too — the edit deny governs only the edit tools; the tree is regenerated on every install/update, and the devkit's PreToolUse hook still denies hcloud writes.
407
+ Harness permission notes (skill-tree reads outside the workspace): the taught reaction above is universal — when a direct read fails or is denied, fall back to `huaweicloud_retrieve_skill`, never repeatedly request. The OpenCode installer writes a persistent permission seam (external_directory allow + edit deny over the tree globs); on other harnesses the operator can pre-allow the tree in the harness's own config if prompts bother them. Honest semantics for the seam: the allow covers every path-taking tool including bash (an allowed external directory inherits workspace defaults), so shell-mediated writes to the tree stop asking too — the edit deny governs only the edit tools; the tree is regenerated on every install/update, and the devkit's PreToolUse hook still denies hcloud writes. On opencode >= 2.0 the installer additionally writes the ASK approval posture — a top-level `permissions` entry with effect `ask` on the `huaweicloud-devkit_huaweicloud_run_approved_command` action plus `DEVKIT_APPROVAL_MODE=ask` in the mcp entry's environment — so every hcloud write makes OpenCode itself prompt (no terminal approve trip, no token UUID; below 2.0 neither half is written). Honest residual for that posture: answering OpenCode's prompt with "Allow always" saves an `allow` rule on the same action that removes the gate — `npx huaweicloud-devkit doctor` fails that state; see the huaweicloud-safety skill's approvals reference.
406
408
 
407
409
  | Harness | Outside-workspace reads | Operator relief |
408
410
  | ------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------- |
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.1",
4
+ "version": "2.0.0-next.3",
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.1",
19
+ "version": "2.0.0-next.3",
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.1",
22
+ "version": "2.0.0-next.3",
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.1",
19
+ "version": "2.0.0-next.3",
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.1",
3
+ "version": "2.0.0-next.3",
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.1",
3
+ "version": "2.0.0-next.3",
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'));
@@ -15,6 +15,7 @@ import { mergeCommandStyle, extractUserDelta, applyUserDelta } from "../mcp-conf
15
15
  import { saveAgentDelta, takeAgentDelta } from "../mcp-config-backup.js";
16
16
  import { readJsonRecord, writeMcpSettingsFile } from "../mcp-config-io.js";
17
17
  import { applySkillTreePermissionSeam, opencodeSeamVersionSupported, removeSkillTreePermissionSeam, skillTreePermissionGlobs, } from "../lib/opencode-permission-seam.js";
18
+ import { ASK_RULE_ACTION, applyAskPermissionRule, opencodeAskRuleVersionSupported, removeAskPermissionRule, } from "../lib/opencode-ask-rule.js";
18
19
  import { asRecord } from "../lib/as-record.js";
19
20
  import { devkitOwnedSkillNames, tryCoreSkillNames } from "../install-payload.js";
20
21
  // The seam's version gate. HUAWEICLOUD_OPENCODE_PERMISSION_SEAM=on|off is
@@ -87,6 +88,41 @@ export function openCodeSeamGate() {
87
88
  return forced;
88
89
  return opencodeSeamVersionSupported(probeOpencodeVersion()) ? 'on' : 'off';
89
90
  }
91
+ // The ask rule's version gate, same doctrine as the seam's:
92
+ // HUAWEICLOUD_OPENCODE_ASK_RULE=on|off is the deterministic override for
93
+ // the installer test suite (e2e strips it — the runner's install relies on
94
+ // the natural probe); unset runs the probe. Unknown polarity is off: the
95
+ // `permissions` array is the V2 shape measured on 2.2.7 only, so a
96
+ // below-2.0, absent, or unparsable opencode writes NEITHER half of the
97
+ // posture — the client rule without the server env double-gates, the env
98
+ // without the rule fail-opens, and the pair must move together.
99
+ export function openCodeAskGate() {
100
+ const forced = process.env.HUAWEICLOUD_OPENCODE_ASK_RULE;
101
+ if (forced === 'on' || forced === 'off')
102
+ return forced;
103
+ return opencodeAskRuleVersionSupported(probeOpencodeVersion()) ? 'on' : 'off';
104
+ }
105
+ // The server half of the ask posture: DEVKIT_APPROVAL_MODE=ask in the mcp
106
+ // entry's environment (the field OpenCode reads — the applyPacksToEntry
107
+ // 'environment' precedent). Add-only-if-absent with the packs-write
108
+ // doctrine: a user-set value other than 'ask' is theirs and wins with a
109
+ // one-line WARN; 'ask' already present needs no write. An absent or empty
110
+ // environment object is created. No delete path: uninstall removes the
111
+ // whole mcp entry wholesale. Runs ONLY under the ask gate — see
112
+ // openCodeAskGate for why the halves must move together.
113
+ function applyApprovalModeToEntry(entry) {
114
+ const env = asRecord(entry.environment);
115
+ const current = env.DEVKIT_APPROVAL_MODE;
116
+ if (current === 'ask')
117
+ return false;
118
+ if (current !== undefined) {
119
+ const shown = typeof current === 'string' ? current : JSON.stringify(current);
120
+ console.log(` \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).`);
121
+ return false;
122
+ }
123
+ entry.environment = { ...env, DEVKIT_APPROVAL_MODE: 'ask' };
124
+ return true;
125
+ }
90
126
  // The glob set the seam covers: the plugin-dir tree actually deployed by
91
127
  // this run plus per-skill globs for the native core meta-skill copies
92
128
  // (under the XDG opencode skills dir). An unusable manifest degrades to the
@@ -129,11 +165,30 @@ export function updateOpenCodeConfig(pluginDir) {
129
165
  else {
130
166
  console.log(' \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.');
131
167
  }
168
+ const askOn = openCodeAskGate() === 'on';
169
+ // The ask rule is a FOURTH change source, computed before the unchanged
170
+ // short-circuit for the same reason as the seam: an unchanged mcp entry
171
+ // is the dominant update shape, and every install made before the ask
172
+ // posture existed is exactly the population this must heal. The rule
173
+ // mutates config in place (ownership rules in lib/opencode-ask-rule.ts),
174
+ // so the single write below carries it.
175
+ let askRuleChanged = false;
176
+ if (askOn) {
177
+ const applied = applyAskPermissionRule(config);
178
+ askRuleChanged = applied.changed;
179
+ if (applied.skipped) {
180
+ console.log(` \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).`);
181
+ }
182
+ }
183
+ else {
184
+ console.log(' \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.');
185
+ }
132
186
  const existing = asRecord(config.mcp)['huaweicloud-devkit'];
133
187
  if (existing) {
134
188
  const { entry, changed } = mergeCommandStyle(existing, { mcpPath });
135
189
  const packsChanged = applyPacksToEntry(entry, 'environment', 'OpenCode');
136
- if (!changed && !packsChanged && !permChanged) {
190
+ const askEnvChanged = askOn && applyApprovalModeToEntry(entry);
191
+ if (!changed && !packsChanged && !permChanged && !askRuleChanged && !askEnvChanged) {
137
192
  console.log(` OpenCode MCP config unchanged: ${configPath}`);
138
193
  return;
139
194
  }
@@ -142,6 +197,9 @@ export function updateOpenCodeConfig(pluginDir) {
142
197
  config.mcp = mcpMap;
143
198
  writeMcpSettingsFile(configPath, config);
144
199
  console.log(` OpenCode MCP config merged (user fields preserved): ${configPath}`);
200
+ if (askRuleChanged || askEnvChanged) {
201
+ console.log(` ASK approval (permissions ask rule + DEVKIT_APPROVAL_MODE) -> ${configPath}`);
202
+ }
145
203
  return;
146
204
  }
147
205
  const mcpMap = asRecord(config.mcp);
@@ -152,10 +210,14 @@ export function updateOpenCodeConfig(pluginDir) {
152
210
  if (delta)
153
211
  entry = asRecord(applyUserDelta(entry, delta, 'command'));
154
212
  applyPacksToEntry(entry, 'environment', 'OpenCode');
213
+ const askEnvChanged = askOn && applyApprovalModeToEntry(entry);
155
214
  mcpMap['huaweicloud-devkit'] = entry;
156
215
  config.mcp = mcpMap;
157
216
  writeMcpSettingsFile(configPath, config);
158
217
  console.log(` OpenCode config updated: ${configPath}`);
218
+ if (askRuleChanged || askEnvChanged) {
219
+ console.log(` ASK approval (permissions ask rule + DEVKIT_APPROVAL_MODE) -> ${configPath}`);
220
+ }
159
221
  }
160
222
  export function removeOpenCodeConfig() {
161
223
  const configPath = opencodeConfigFile();
@@ -182,11 +244,20 @@ export function removeOpenCodeConfig() {
182
244
  // value-exact deletion keeps user-modified rules (the ownership contract
183
245
  // lives in lib/opencode-permission-seam.ts).
184
246
  const permCleaned = removeSkillTreePermissionSeam(config, openCodeSeamGlobs(opencodePluginsDir()));
185
- if (!hadEntry && !permCleaned)
247
+ // The ask-rule cleanup also runs unconditionally of the version gate: an
248
+ // uninstall must remove what any past install wrote — the opencode that
249
+ // gated the write may since have been upgraded, downgraded, or removed
250
+ // from PATH. Value-exact deletion keeps user-modified entries (the
251
+ // ownership contract lives in lib/opencode-ask-rule.ts); the mcp entry
252
+ // (and its DEVKIT_APPROVAL_MODE env) is already gone wholesale above.
253
+ const askCleaned = removeAskPermissionRule(config);
254
+ if (!hadEntry && !permCleaned && !askCleaned)
186
255
  return;
187
256
  writeMcpSettingsFile(configPath, config);
188
257
  if (hadEntry)
189
258
  console.log(` OpenCode MCP config cleaned: ${configPath}`);
190
259
  if (permCleaned)
191
260
  console.log(` Skills-tree permission rules removed: ${configPath}`);
261
+ if (askCleaned)
262
+ console.log(` ASK permission rule removed: ${configPath}`);
192
263
  }
@@ -9,7 +9,8 @@ import { join } from 'node:path';
9
9
  import { configRoot, opencodeCommandsDir, opencodeConfigFile, opencodePluginsDir, opencodeSkillsDir, } from "../targets.js";
10
10
  import { printMcpConfigStatus } from "../mcp-config-io.js";
11
11
  import { PACKAGE_ROOT, copyDir, copyServerPayload, deployWord, installRuntimeDeps, payloadStatusLines, pruneStale, removeHuaweiCommandsFrom, removeIfExists, } from "../install-payload.js";
12
- import { removeOpenCodeConfig, updateOpenCodeConfig, openCodeSeamGate, openCodeSeamGlobs } from "./opencode-config.js";
12
+ import { removeOpenCodeConfig, updateOpenCodeConfig, openCodeSeamGate, openCodeSeamGlobs, openCodeAskGate, } from "./opencode-config.js";
13
+ import { inspectAskPermissionRule } from "../lib/opencode-ask-rule.js";
13
14
  import { asRecord } from "../lib/as-record.js";
14
15
  // Doctor: the OpenCode MCP-configured candidate — the opencode config's
15
16
  // mcp.huaweicloud-devkit entry.
@@ -27,6 +28,66 @@ export function opencodeDoctorMcpConfigured() {
27
28
  }
28
29
  return null;
29
30
  }
31
+ // Doctor: the ASK approval posture check — OpenCode installs only. The
32
+ // posture is a PAIR: the client half (the permissions ask rule that makes
33
+ // opencode itself prompt on huaweicloud_run_approved_command) and the
34
+ // server half (DEVKIT_APPROVAL_MODE=ask in the mcp entry's env). A
35
+ // gate-off opencode is a SKIP — token mode is that install's legitimate
36
+ // posture — and so are configs the installer itself refuses to touch.
37
+ // Every mixed state is a FAIL because each lies in a known direction:
38
+ // the rule without the env double-gates (the client prompts AND the
39
+ // server still demands a token), the env without the rule fail-opens
40
+ // (the server trusts a prompt nobody shows), and an allow/deny rule
41
+ // destroys the ask contract outright ("always allow" stops prompting;
42
+ // deny bricks the write tool entirely).
43
+ export function opencodeDoctorAskRule(ctx) {
44
+ if (openCodeAskGate() === 'off') {
45
+ ctx.skip('ASK approval posture (opencode not verifiably at or above 2.0)');
46
+ return;
47
+ }
48
+ let cfg;
49
+ try {
50
+ cfg = asRecord(JSON.parse(readFileSync(opencodeConfigFile(), 'utf8')));
51
+ }
52
+ catch {
53
+ cfg = null;
54
+ }
55
+ const posture = cfg !== null ? inspectAskPermissionRule(cfg) : null;
56
+ if (cfg === null || posture === 'foreign') {
57
+ ctx.skip('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)');
58
+ return;
59
+ }
60
+ // The mcp entry carries the server half; a missing entry counts as no
61
+ // env, so the halves are judged independently of entry presence.
62
+ const env = asRecord(asRecord(asRecord(cfg.mcp)['huaweicloud-devkit']).environment);
63
+ const envAsk = env.DEVKIT_APPROVAL_MODE === 'ask';
64
+ const label = 'ASK approval posture (client prompt + server env)';
65
+ if (posture === 'ask') {
66
+ ctx.check(label, envAsk, envAsk
67
+ ? ''
68
+ : '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)');
69
+ return;
70
+ }
71
+ if (posture === 'allow') {
72
+ // FAIL, never a warn: with the env also ask this is fail-open (the
73
+ // always-allow rule suppresses the prompt the server trusts); without
74
+ // it the run degrades to the token gate. Either way the ask contract
75
+ // is silently gone.
76
+ ctx.check(label, false, '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)');
77
+ return;
78
+ }
79
+ if (posture === 'deny') {
80
+ ctx.check(label, false, '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)');
81
+ return;
82
+ }
83
+ if (envAsk) {
84
+ // posture === 'absent': the fail-open direction.
85
+ ctx.check(label, false, '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)');
86
+ return;
87
+ }
88
+ // Token mode is the legitimate default posture, not an error.
89
+ ctx.check('ASK approval posture (token mode)', true, '');
90
+ }
30
91
  // Doctor: the skills-tree permission seam check — OpenCode installs only
31
92
  // (the seam is the installer's zero-prompt path for direct skill reads on
32
93
  // that harness). Verifies the two keys and their values, honoring the
@@ -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
  }
@@ -4,6 +4,13 @@
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
  import { classifyHcloudArgs, redactSecrets, stripExecutable } from "./safety-policy.js";
8
15
  import { isHcloudToken } from "./safety/tokens.js";
9
16
  import { createApprovalToken } from "./lib/approval-tokens.js";
@@ -287,7 +294,12 @@ export function planHcloudCommand(args, options = {}) {
287
294
  warnings.push(`${triage.message} ${triage.nextStep}`);
288
295
  }
289
296
  }
290
- const approvalToken = options.mintApprovalToken === false
297
+ const approvalMode = options.approvalMode ?? 'token';
298
+ // Ask mode never mints: the confirmation is the harness client's prompt
299
+ // on the run call, so there is no token to hand the model and nothing
300
+ // lands in the approvals store. Run paths keep mintApprovalToken:false
301
+ // in both modes.
302
+ const approvalToken = approvalMode === 'ask' || options.mintApprovalToken === false
291
303
  ? undefined
292
304
  : createApprovalToken(normalizedArgs, {
293
305
  secretsSubstitutable: secretsSubstitutable(normalizedArgs),
@@ -309,11 +321,19 @@ export function planHcloudCommand(args, options = {}) {
309
321
  ...(approvalToken !== undefined ? { approvalToken } : {}),
310
322
  // `command` exists only where a token was minted: a run-path plan stays
311
323
  // silent rather than name a line for a token the run cannot offer.
324
+ // Ask mode names the posture instead — the confirmation happens at the
325
+ // run call, and the note teaches exactly that.
312
326
  userConfirmation: needsConfirmation
313
- ? {
314
- needed: true,
315
- ...(approvalToken !== undefined ? { command: `npx huaweicloud-devkit approve ${approvalToken}` } : {}),
316
- }
327
+ ? approvalMode === 'ask'
328
+ ? {
329
+ needed: true,
330
+ mode: 'ask',
331
+ 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.',
332
+ }
333
+ : {
334
+ needed: true,
335
+ ...(approvalToken !== undefined ? { command: `npx huaweicloud-devkit approve ${approvalToken}` } : {}),
336
+ }
317
337
  : { needed: false },
318
338
  safeToRun: effectiveClassification.decision === 'allow',
319
339
  };
@@ -0,0 +1,30 @@
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
+ export const APPROVAL_MODE_ENV = 'DEVKIT_APPROVAL_MODE';
23
+ export function approvalModeFromEnv(env) {
24
+ const raw = env[APPROVAL_MODE_ENV];
25
+ if (raw === undefined || raw === '')
26
+ return 'token';
27
+ if (raw === 'ask' || raw === 'token')
28
+ return raw;
29
+ throw new Error(`DEVKIT_APPROVAL_MODE must be "ask" or "token" (got "${raw}")`);
30
+ }
@@ -3,10 +3,10 @@ import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, statSync,
3
3
  import { dirname, join } from 'node:path';
4
4
  import { redactSecrets } from "../safety-policy.js";
5
5
  import { ensureMasterKey, resolveMasterKey } from "./secret-vault/custody.js";
6
- import { huaweiConfigBase } from "./pack-state.js";
6
+ import { devkitStateBase } from "./pack-state.js";
7
7
  const APPROVAL_TTL_MS = 5 * 60_000;
8
8
  function approvalFilePath() {
9
- return join(huaweiConfigBase(), 'approvals.json');
9
+ return join(devkitStateBase(), 'approvals.json');
10
10
  }
11
11
  function sha256Hex(data) {
12
12
  return createHash('sha256').update(data).digest('hex');
@@ -142,7 +142,7 @@ function pruneStale(map, now = Date.now()) {
142
142
  return changed;
143
143
  }
144
144
  function consumedMarkerDir() {
145
- return join(huaweiConfigBase(), 'approvals-consumed');
145
+ return join(devkitStateBase(), 'approvals-consumed');
146
146
  }
147
147
  // Exclusive-create claim on a token: 'wx' maps to O_EXCL|O_CREAT, so the
148
148
  // first consumer wins atomically and every replay sees EEXIST. Claimed