huaweicloud-devkit 2.0.0-next.2 → 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 (30) hide show
  1. package/README.md +1 -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/opencode-config.js +73 -2
  9. package/plugins/huaweicloud-core/dist/agents/opencode.js +62 -1
  10. package/plugins/huaweicloud-core/dist/hcloud-plan.js +25 -5
  11. package/plugins/huaweicloud-core/dist/lib/approval-mode.js +30 -0
  12. package/plugins/huaweicloud-core/dist/lib/opencode-ask-rule.js +116 -0
  13. package/plugins/huaweicloud-core/dist/mcp-protocol.js +20 -1
  14. package/plugins/huaweicloud-core/dist/mcp-server.js +86 -18
  15. package/plugins/huaweicloud-core/dist/mcp-server.js.map +3 -3
  16. package/plugins/huaweicloud-core/dist/packs/huaweicloud-cli/tools.js +74 -22
  17. package/plugins/huaweicloud-core/dist/setup-cli.js +6 -3
  18. package/plugins/huaweicloud-core/openclaw.plugin.json +1 -1
  19. package/plugins/huaweicloud-core/skills/huaweicloud-cli-and-auth/SKILL.md +4 -4
  20. package/plugins/huaweicloud-core/skills/huaweicloud-safety/SKILL.md +8 -7
  21. package/plugins/huaweicloud-core/skills/huaweicloud-safety/references/approvals.md +10 -0
  22. package/plugins/huaweicloud-core/src/agents/opencode-config.ts +82 -2
  23. package/plugins/huaweicloud-core/src/agents/opencode.ts +86 -1
  24. package/plugins/huaweicloud-core/src/hcloud-plan.ts +38 -6
  25. package/plugins/huaweicloud-core/src/lib/approval-mode.ts +32 -0
  26. package/plugins/huaweicloud-core/src/lib/opencode-ask-rule.ts +131 -0
  27. package/plugins/huaweicloud-core/src/mcp-protocol.ts +20 -1
  28. package/plugins/huaweicloud-core/src/mcp-server.ts +13 -0
  29. package/plugins/huaweicloud-core/src/packs/huaweicloud-cli/tools.ts +81 -24
  30. package/plugins/huaweicloud-core/src/setup-cli.ts +6 -2
@@ -3,6 +3,7 @@ import { runHcloud, planHcloudCommand, stripLeadingHcloudBinArgs, firstPlacehold
3
3
  import { hcloudProbeNextStep, hcloudProbeRaw, probeHcloud } from "../../hcloud-probe.js";
4
4
  import { redactSecrets } from "../../safety-policy.js";
5
5
  import { asText } from "../../lib/as-text.js";
6
+ import { approvalModeFromEnv } from "../../lib/approval-mode.js";
6
7
  import { consumeApprovalToken, hashArgs, inspectApprovalToken } from "../../lib/approval-tokens.js";
7
8
  import { booleanArg, numericArg, stringArrayArg, vendorConfirmed } from "../../lib/tool-schema-parts.js";
8
9
  import { asRecord } from "../../lib/as-record.js";
@@ -10,7 +11,11 @@ import { asRecord } from "../../lib/as-record.js";
10
11
  // version/profile inspection, plan/read-only/approved command execution,
11
12
  // operation discovery, and region listing. The consent layer is imported
12
13
  // directly from src/lib/approval-tokens.ts (the CLI face's consent module),
13
- // not the hcloud-cli.ts re-export shim. The only allowWrites:true call site
14
+ // not the hcloud-cli.ts re-export shim. The approval posture resolves from
15
+ // DEVKIT_APPROVAL_MODE (src/lib/approval-mode.ts): 'token' (default) keeps
16
+ // the out-of-band terminal gate; 'ask' makes the harness client's own
17
+ // permission prompt the user's confirmation, so the plan mints nothing and
18
+ // the run needs no token. The only allowWrites:true call site
14
19
  // in the codebase (runApprovedCommand) lives here, so trimming this pack
15
20
  // removes the CLI execution face and its approval tools together: a
16
21
  // configuration trimmed of this pack has no devkit-side hcloud CLI write
@@ -173,10 +178,64 @@ async function listOperations(service, options = {}) {
173
178
  result,
174
179
  };
175
180
  }
181
+ // A placeholder-shaped secret VALUE at run time is never a real secret in
182
+ // either approval mode: executing a literal `<redacted>`/`<password>` as
183
+ // the password is always wrong. The guard is shared so the two modes can
184
+ // never drift on detection; only the re-run wording is mode-aware — token
185
+ // mode keeps the guidance followable on the SAME approval (the guard runs
186
+ // before the token is consumed; loop round 3, seat-1 B3: the guidance used
187
+ // to be a dead end because the rejection burned the only token), while
188
+ // ask mode has no token to preserve and must not reference one.
189
+ function assertNoPlaceholderSecret(args, mode) {
190
+ const placeholderArg = firstPlaceholderSecretArg(args);
191
+ if (!placeholderArg)
192
+ return;
193
+ throw new Error(`The argument "${placeholderArg}" still carries a placeholder secret value: replace <redacted> with the actual value the user approved, ` +
194
+ (mode === 'ask' ? 'then re-run.' : 'then re-run with the same approval token.'));
195
+ }
196
+ // The run options both approval modes execute under: allowWrites stays
197
+ // scoped to this file's call sites (the only ones in the codebase), and
198
+ // the pass-through fields keep their names verbatim.
199
+ function approvedRunOptions(args) {
200
+ return {
201
+ allowWrites: true,
202
+ timeoutMs: args.timeoutMs,
203
+ maxRetries: args.maxRetries,
204
+ cwd: args.cwd,
205
+ stdin: args.stdin,
206
+ };
207
+ }
208
+ // Ask mode (DEVKIT_APPROVAL_MODE=ask): the harness client's permission
209
+ // prompt on this very call is the user's confirmation, so there is no
210
+ // token to inspect or consume. The safety floors are unchanged — the
211
+ // placeholder-secret guard above, and runHcloud's assertAllowed
212
+ // re-assertion of the strict classification (secret/credential/invalid
213
+ // denies still throw; allowWrites:true stays scoped to this one call
214
+ // site, the only one in the codebase).
215
+ async function runApprovedCommandAskMode(args) {
216
+ const providedArgs = Array.isArray(args.args) ? args.args.map(String) : [];
217
+ // Same normalization as the token path: the strict plan and the executed
218
+ // argv must agree on the effective args.
219
+ const { args: effectiveArgs } = stripLeadingHcloudBinArgs(providedArgs);
220
+ assertNoPlaceholderSecret(effectiveArgs, 'ask');
221
+ const strictPlan = planHcloudCommand(effectiveArgs, {
222
+ allowWrites: false,
223
+ mintApprovalToken: false,
224
+ approvalMode: 'ask',
225
+ });
226
+ const result = await runHcloud(effectiveArgs, approvedRunOptions(args));
227
+ // Spread instead of in-place mutation, mirroring the token path: the
228
+ // HcloudRunResult shape stays owned by hcloud-cli.ts.
229
+ return { ...result, approved: true, plan: strictPlan };
230
+ }
176
231
  async function runApprovedCommand(args = {}) {
177
232
  if (args.approvedByUser !== true) {
178
233
  throw new Error('approvedByUser must be true after explicit user approval for this exact command.');
179
234
  }
235
+ const approvalMode = approvalModeFromEnv(process.env);
236
+ if (approvalMode === 'ask') {
237
+ return runApprovedCommandAskMode(args);
238
+ }
180
239
  const token = String(args.approvalToken || '');
181
240
  // D4-24 precise JSON contract (#745): expired and already-consumed tokens
182
241
  // return a structured result instead of throwing a generic Error string, so
@@ -203,16 +262,9 @@ async function runApprovedCommand(args = {}) {
203
262
  // burned the single-use token on a mismatch (2026-11-05 UX report #6, the
204
263
  // approval-trap probe).
205
264
  const { args: effectiveArgs } = stripLeadingHcloudBinArgs(providedArgs);
206
- // A placeholder-shaped secret VALUE at run time is never a real secret:
207
- // executing a literal `<redacted>`/`<password>` as the password is always
208
- // wrong. This guard runs BEFORE the token is consumed, so its own guidance
209
- // (replace the value, then re-run) stays followable on the same approval
210
- // (loop round 3, seat-1 B3: the guidance used to be a dead end — the
211
- // rejection burned the only token).
212
- const placeholderArg = firstPlaceholderSecretArg(effectiveArgs);
213
- if (placeholderArg) {
214
- throw new Error(`The argument "${placeholderArg}" still carries a placeholder secret value: replace <redacted> with the actual value the user approved, then re-run with the same approval token.`);
215
- }
265
+ // Placeholder guard before the consume: the shared helper's token-mode
266
+ // wording keeps the guidance followable on the same approval.
267
+ assertNoPlaceholderSecret(effectiveArgs, 'token');
216
268
  // The strict plan is pure, so it is computed before the token is consumed:
217
269
  // its userConfirmation.needed decides whether the consume requires a grant,
218
270
  // and the result still embeds it.
@@ -268,13 +320,7 @@ async function runApprovedCommand(args = {}) {
268
320
  throw new Error('Secret values are pinned to the approved plan: re-run huaweicloud_plan_cli_command with the final values and re-approve.');
269
321
  }
270
322
  }
271
- const result = await runHcloud(effectiveArgs, {
272
- allowWrites: true,
273
- timeoutMs: args.timeoutMs,
274
- maxRetries: args.maxRetries,
275
- cwd: args.cwd,
276
- stdin: args.stdin,
277
- });
323
+ const result = await runHcloud(effectiveArgs, approvedRunOptions(args));
278
324
  // Spread instead of in-place mutation: identical serialized content, minus a
279
325
  // write to the HcloudRunResult shape owned by hcloud-cli.ts.
280
326
  return { ...result, approved: true, plan: strictPlan };
@@ -328,7 +374,10 @@ async function handleCheckCli(_args = {}, _opts = {}) {
328
374
  return runVersionCheck();
329
375
  }
330
376
  async function handlePlanCliCommand(args = {}, _opts = {}) {
331
- return planHcloudCommand(args.args || [], { allowWrites: args.allowWrites === true });
377
+ return planHcloudCommand(args.args || [], {
378
+ allowWrites: args.allowWrites === true,
379
+ approvalMode: approvalModeFromEnv(process.env),
380
+ });
332
381
  }
333
382
  async function handleRunReadonlyCommand(args = {}, _opts = {}) {
334
383
  return runHcloud(args.args || [], {
@@ -371,7 +420,10 @@ const listOperationsSchema = z.looseObject({
371
420
  const runApprovedCommandSchema = z.looseObject({
372
421
  vendorConfirmed,
373
422
  args: stringArrayArg.describe('hcloud arguments, excluding the hcloud executable.'),
374
- approvalToken: z.string().describe('The approvalToken returned by huaweicloud_plan_cli_command.'),
423
+ approvalToken: z
424
+ .string()
425
+ .optional()
426
+ .describe('Required in token-approval mode (from huaweicloud_plan_cli_command); omit in ask mode where the harness client confirms at run time.'),
375
427
  approvedByUser: booleanArg.describe('Must be true only after the user explicitly approves this exact command.'),
376
428
  timeoutMs: numericArg.optional().describe('Optional timeout in milliseconds. Defaults to 60000.'),
377
429
  maxRetries: numericArg.optional().describe('Optional retry count for transient network errors. Defaults to 1.'),
@@ -391,7 +443,7 @@ export const HUAWEICLOUD_CLI_TOOLS = [
391
443
  },
392
444
  {
393
445
  name: 'huaweicloud_plan_cli_command',
394
- description: "Classify and plan a Huawei Cloud hcloud command without executing it. When the result's userConfirmation.needed is true, the USER must confirm in their own terminal by running the userConfirmation.command line (npx huaweicloud-devkit approve <approvalToken>) before huaweicloud_run_approved_command will accept the command. Vendor-gated (vendorConfirmed): call only when the vendor is established — see the vendorConfirmed parameter description; when unknown, ask which cloud the user means first.",
446
+ description: "Classify and plan a Huawei Cloud hcloud command without executing it. When the result's userConfirmation.needed is true, the command waits on user confirmation before huaweicloud_run_approved_command will accept it: in the default token mode the USER runs the userConfirmation.command line (npx huaweicloud-devkit approve <approvalToken>) in their own terminal, and under DEVKIT_APPROVAL_MODE=ask the harness client itself prompts the user on the run call — no token is needed. Vendor-gated (vendorConfirmed): call only when the vendor is established — see the vendorConfirmed parameter description; when unknown, ask which cloud the user means first.",
395
447
  schema: planCliCommandSchema,
396
448
  handler: handlePlanCliCommand,
397
449
  },
@@ -409,7 +461,7 @@ export const HUAWEICLOUD_CLI_TOOLS = [
409
461
  },
410
462
  {
411
463
  name: 'huaweicloud_run_approved_command',
412
- description: 'Run a write-capable hcloud command only after the exact command has been shown and explicitly approved by the user, and after the user confirmed the plan token in their own terminal (npx huaweicloud-devkit approve <token>). A non-read command without that terminal confirmation is rejected with USER_CONFIRMATION_REQUIRED and the token stays usable. Vendor-gated (vendorConfirmed): call only when the vendor is established — see the vendorConfirmed parameter description; when unknown, ask which cloud the user means first.',
464
+ description: "Run a write-capable hcloud command only after the exact command has been shown and explicitly approved by the user. In the default token mode the user must also confirm the plan token in their own terminal (npx huaweicloud-devkit approve <token>) — a non-read command without that terminal confirmation is rejected with USER_CONFIRMATION_REQUIRED and the token stays usable. Under DEVKIT_APPROVAL_MODE=ask the harness client's permission prompt on this call is the confirmation: pass the same args with approvedByUser: true and no approvalToken. Vendor-gated (vendorConfirmed): call only when the vendor is established — see the vendorConfirmed parameter description; when unknown, ask which cloud the user means first.",
413
465
  schema: runApprovedCommandSchema,
414
466
  handler: handleRunApprovedCommand,
415
467
  },
@@ -65,7 +65,7 @@ import { codexDesktopStatus, codexSectionStatus, codexStatus, hasCodexCLI, insta
65
65
  import { codexDesktopDoctorMcpConfigured, deployCodexDesktop, uninstallCodexDesktop } from "./agents/codex-desktop.js";
66
66
  import { deployDsh, dshStatus, uninstallDsh } from "./agents/dsh.js";
67
67
  import { dshDoctorMcpConfigured, dshPayloadDoctorSection } from "./agents/dsh-patch.js";
68
- import { deployOpenCode, opencodeDoctorMcpConfigured, opencodeDoctorSeam, opencodeStatus, uninstallOpenCode, } from "./agents/opencode.js";
68
+ import { deployOpenCode, opencodeDoctorAskRule, opencodeDoctorMcpConfigured, opencodeDoctorSeam, opencodeStatus, uninstallOpenCode, } from "./agents/opencode.js";
69
69
  import { deployOpenClaw, openclawDoctorMcpConfigured, openclawStatus, uninstallOpenClaw } from "./agents/openclaw.js";
70
70
  import { codeartsDoctorMcpConfigured, codeartsStatus, deployCodeArts, uninstallCodeArts } from "./agents/codearts.js";
71
71
  import { codeartsWorkDoctorMcpConfigured, codeartsWorkStatus, deployCodeArtsWork, uninstallCodeArtsWork, } from "./agents/codearts-work.js";
@@ -870,10 +870,13 @@ async function cmdDoctor() {
870
870
  }
871
871
  const mcpConfigured = mcpCfgTarget !== null;
872
872
  check('MCP configured', mcpConfigured, mcpCfgTarget ? `Found in ${mcpCfgTarget} config` : 'Run: npx huaweicloud-devkit install');
873
- // Skills-tree permission seam — OpenCode installs only (the section in
874
- // agents/opencode.ts owns the per-glob kept/missing evaluation).
873
+ // OpenCode-only installer seams — the skills-tree permission check (the
874
+ // section in agents/opencode.ts owns the per-glob kept/missing
875
+ // evaluation) and the ASK approval posture check (the same file owns the
876
+ // client-rule/server-env pair evaluation).
875
877
  if (installedPayload?.id === 'opencode') {
876
878
  opencodeDoctorSeam(ctx);
879
+ opencodeDoctorAskRule(ctx);
877
880
  }
878
881
  // Hermes MCP Python SDK (only checked when Hermes config is found).
879
882
  hermesDoctorSdkCheck(ctx, mcpCfgTarget);
@@ -2,7 +2,7 @@
2
2
  "name": "huaweicloud-devkit",
3
3
  "id": "huaweicloud-devkit",
4
4
  "displayName": "HuaweiCloud DevKit",
5
- "version": "2.0.0-next.2",
5
+ "version": "2.0.0-next.3",
6
6
  "family": "bundle-plugin",
7
7
  "bundleFormat": "codex",
8
8
  "description": "Guide coding agents to use Huawei Cloud safely — KooCLI, APIs, SDKs, 40 MCP tools, skills, and safety guardrails.",
@@ -99,10 +99,10 @@ curl -sSL https://cn-north-4-hdn-koocli.obs.cn-north-4.myhuaweicloud.com/cli/lat
99
99
  - Read-only: `List*`, `Show*`, `Get*`, `Describe*`.
100
100
  - Write: `Create*`, `Delete*`, `Update*`, `Resize*`, `Start*`, `Stop*`, `Authorize*`, and similar.
101
101
  - Secret: any operation returning secret string, binary secret, token, or password.
102
- 9. For write operations, follow the terminal confirmation contract:
103
- - Call `huaweicloud_plan_cli_command` and read `userConfirmation`. When `needed` is true, show the user the command echo and the `userConfirmation.command` line.
104
- - The user runs `npx huaweicloud-devkit approve <approvalToken>` in their own terminal. Never run it yourself. First use: the user runs `npx huaweicloud-devkit pin` once in their own terminal to enroll the approvals PIN.
105
- - Then call `huaweicloud_run_approved_command` with that token. An unconfirmed non-read command is rejected with `USER_CONFIRMATION_REQUIRED`; the token stays usable, so retry the same call after the user confirms.
102
+ 9. For write operations, follow the approval contract:
103
+ - Call `huaweicloud_plan_cli_command` and read `userConfirmation`. When `needed` is true, show the user the command echo.
104
+ - Token mode (the default): show the `userConfirmation.command` line; the user runs `npx huaweicloud-devkit approve <approvalToken>` in their own terminal. Never run it yourself. First use: the user runs `npx huaweicloud-devkit pin` once in their own terminal to enroll the approvals PIN. Then call `huaweicloud_run_approved_command` with that token; an unconfirmed non-read command is rejected with `USER_CONFIRMATION_REQUIRED`, and the token stays usable, so retry the same call after the user confirms.
105
+ - Ask mode (`userConfirmation.mode` is `ask`): no terminal line and no token — call `huaweicloud_run_approved_command` with the same args and `approvedByUser: true`; the harness client prompts the user on that call, and that prompt is the confirmation.
106
106
 
107
107
  ## KooCLI Syntax Notes
108
108
 
@@ -23,7 +23,7 @@ Use this skill before any Huawei Cloud action that may expose secrets, change re
23
23
  - IAM/security
24
24
  - cost/payment
25
25
  - public exposure
26
- 5. For any non-read-only operation, follow the plan, confirm, run contract: plan with `huaweicloud_plan_cli_command`, show the user the command and the terminal confirmation line, wait for the user to confirm in their own terminal, then run with `huaweicloud_run_approved_command`. See `references/approvals.md`.
26
+ 5. For any non-read-only operation, follow the plan, confirm, run contract: plan with `huaweicloud_plan_cli_command`, show the user the command, then run with `huaweicloud_run_approved_command`. The confirm step follows the plan's `userConfirmation`: by default (token mode) show the terminal confirmation line and wait for the user to run it in their own terminal; when `userConfirmation.mode` is `ask`, call the run tool directly — the harness client prompts the user on that call. See `references/approvals.md`.
27
27
  6. Redact secrets from command output, errors, JSON, logs, and generated reports.
28
28
  7. If a command contains `adminPass`, `password`, token, or any secret-like field, warn that plaintext can remain in shell history. Prefer local-only input, runtime injection, or user-side execution.
29
29
 
@@ -35,13 +35,14 @@ Use this skill before any Huawei Cloud action that may expose secrets, change re
35
35
 
36
36
  ## Write Execution Boundary
37
37
 
38
- 1. Plan: call `huaweicloud_plan_cli_command`. The result echoes the exact command and carries `userConfirmation: { needed, command }`.
39
- 2. Confirm: when `needed` is true, show the user the plan echo and the `userConfirmation.command` line (`npx huaweicloud-devkit approve <approvalToken>`), then wait. The USER runs that line in their own terminal, where a TTY check and a PIN gate the confirmation. First use: the user runs `npx huaweicloud-devkit pin` once in their own terminal to enroll the PIN.
40
- 3. Run: call `huaweicloud_run_approved_command` with the same `approvalToken` and `approvedByUser: true`.
38
+ 1. Plan: call `huaweicloud_plan_cli_command`. The result echoes the exact command and carries `userConfirmation: { needed, command }` in the default token mode, or `userConfirmation: { needed, mode: "ask", note }` when the plan ran under `DEVKIT_APPROVAL_MODE=ask`.
39
+ 2. Confirm (token mode, the default): when `needed` is true, show the user the plan echo and the `userConfirmation.command` line (`npx huaweicloud-devkit approve <approvalToken>`), then wait. The USER runs that line in their own terminal, where a TTY check and a PIN gate the confirmation. First use: the user runs `npx huaweicloud-devkit pin` once in their own terminal to enroll the PIN.
40
+ 3. Confirm (ask mode): when `userConfirmation.mode` is `ask`, there is no terminal line and no token. Call `huaweicloud_run_approved_command` with the same args and `approvedByUser: true`; the harness client prompts the user on that call, and that prompt IS the confirmation.
41
+ 4. Run: call `huaweicloud_run_approved_command` with the same `args` and `approvedByUser: true`, plus the plan's `approvalToken` in token mode — no token in ask mode.
41
42
 
42
- A non-read command without that terminal confirmation is rejected with `USER_CONFIRMATION_REQUIRED`. The refusal does not consume the token, so retry the same call after the user confirms. Re-running a write needs a fresh plan and a fresh confirmation.
43
+ In token mode, a non-read command without that terminal confirmation is rejected with `USER_CONFIRMATION_REQUIRED`. The refusal does not consume the token, so retry the same call after the user confirms. Re-running a write needs a fresh plan and a fresh confirmation. In ask mode there is no token to refuse or consume; a retried call prompts the user again.
43
44
 
44
- Never run the approve or pin commands yourself; the hook denies both verbs on the agent's Bash face. The `approvedByUser: true` argument is not the terminal confirmation and never replaces it.
45
+ Never run the approve or pin commands yourself; the hook denies both verbs on the agent's Bash face. The `approvedByUser: true` argument is not the terminal confirmation and never replaces it (in ask mode the harness client's own prompt is the confirmation the server trusts).
45
46
 
46
47
  Without the devkit tools, show the reviewed command and let the user execute it in their own terminal. After a write, verify with `huaweicloud_run_readonly_command` or another read-only check.
47
48
 
@@ -64,6 +65,6 @@ Hook checks inspect the command or plan text that is available before execution.
64
65
  - Use redacted profile inspection instead of raw `hcloud configure show`.
65
66
  - Use runtime secret injection instead of fetching secret values into chat.
66
67
  - Use the encrypted secret vault for durable secrets: store values as `secret://<scope>/<name>` refs and pass refs, never values. See `references/secrets.md`.
67
- - Use the terminal confirmation contract for writes: plan, user confirm, run. See `references/approvals.md`.
68
+ - Use the approval contract for writes: plan, user confirm, run — token mode by default, the harness client's permission prompt when `DEVKIT_APPROVAL_MODE=ask`. See `references/approvals.md`.
68
69
  - Use read-only verification after a write.
69
70
  - Prefer reviewed IaC for durable infrastructure changes.
@@ -33,6 +33,16 @@ The confirmation authorizes one execution of one command.
33
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
34
  - Changing the arguments rejects the run, because the token pins the exact command hash and any real secret values in it.
35
35
 
36
+ ## Ask mode (DEVKIT_APPROVAL_MODE=ask)
37
+
38
+ An alternative posture where the confirmation happens in the harness client's own permission prompt instead of the terminal. The plan mints no token and its `userConfirmation` carries `{ needed: true, mode: "ask", note }` instead of a `command` line; `huaweicloud_run_approved_command` needs only the same `args` plus `approvedByUser: true` — the client's prompt on that call IS the user's confirmation.
39
+
40
+ The operator opts in; it is never the default. On OpenCode the installer (at or above 2.0) writes a top-level `permissions` array entry with effect `ask` for the `huaweicloud-devkit_huaweicloud_run_approved_command` action, plus `DEVKIT_APPROVAL_MODE=ask` in the mcp entry's environment, so the client half and the server half move together — the rule without the env double-gates (the client prompts AND the server still demands a token), the env without the rule fail-opens (the server trusts a prompt nobody shows). On other harnesses the operator sets `DEVKIT_APPROVAL_MODE=ask` in the server environment themselves; Claude Code needs no permission rule because the run tool declares `_meta` `anthropic/requiresUserInteraction` and the client prompts on every call.
41
+
42
+ What changes: no approval token, no UUID in the model's context, no 5-minute TTL, and no single-use replay guard — a retried or repeated call simply prompts the user again. The PIN and TTY checks do not apply; the client's own prompt UI is the gate. `approvedByUser: true` is still required and still means the user approved this exact command.
43
+
44
+ Honest trust boundary: the evidence is the client prompt itself — a harness without a per-tool prompt (or one whose permission system auto-approves) would execute without any user confirmation, which is why the mode is opt-in and the pair must stay whole. OpenCode's "Allow always" answer to the prompt saves an `allow` rule on the same action that removes the gate from then on — `npx huaweicloud-devkit doctor` fails that state; delete the rule or set its effect back to `ask`. The remote transport refuses ask mode outright and forces token mode. Token mode remains the default and the fallback for harnesses without a per-tool prompt.
45
+
36
46
  ## What the agent must not do
37
47
 
38
48
  - 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.
@@ -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,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
+ }