huaweicloud-devkit 2.0.0-next.4 → 2.0.0-next.6

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 (72) hide show
  1. package/README.md +1 -1
  2. package/integrations/opencode/commands/huaweicloud-doctor.md +1 -1
  3. package/integrations/opencode/hooks/safety-gate.js +235 -0
  4. package/package.json +1 -1
  5. package/plugins/huaweicloud-core/.claude-plugin/plugin.json +3 -16
  6. package/plugins/huaweicloud-core/.codex-plugin/plugin.json +3 -16
  7. package/plugins/huaweicloud-core/.cursor-plugin/plugin.json +3 -16
  8. package/plugins/huaweicloud-core/.hermes-plugin/plugin.json +3 -16
  9. package/plugins/huaweicloud-core/.workbuddy-plugin/plugin.json +3 -16
  10. package/plugins/huaweicloud-core/dist/agents/opencode-config.js +29 -4
  11. package/plugins/huaweicloud-core/dist/agents/opencode.js +55 -14
  12. package/plugins/huaweicloud-core/dist/approval-gate.js +23 -5
  13. package/plugins/huaweicloud-core/dist/doctor-payload.js +29 -0
  14. package/plugins/huaweicloud-core/dist/explain-error.js +9 -1
  15. package/plugins/huaweicloud-core/dist/hcloud-plan.js +6 -1
  16. package/plugins/huaweicloud-core/dist/lib/hdkit/hdkitservice-api.js +18 -9
  17. package/plugins/huaweicloud-core/dist/lib/opencode-permission-seam.js +51 -20
  18. package/plugins/huaweicloud-core/dist/mcp-server.js +520 -290
  19. package/plugins/huaweicloud-core/dist/mcp-server.js.map +4 -4
  20. package/plugins/huaweicloud-core/dist/packs/auth/tools.js +5 -1
  21. package/plugins/huaweicloud-core/dist/packs/registry.js +1 -0
  22. package/plugins/huaweicloud-core/dist/packs/sandbox/expose-task.js +71 -0
  23. package/plugins/huaweicloud-core/dist/packs/sandbox/handlers-account.js +25 -1
  24. package/plugins/huaweicloud-core/dist/packs/sandbox/handlers-tunnel.js +28 -3
  25. package/plugins/huaweicloud-core/dist/packs/sandbox/schemas.js +14 -0
  26. package/plugins/huaweicloud-core/dist/packs/sandbox/tools.js +11 -3
  27. package/plugins/huaweicloud-core/dist/payload-placement.js +8 -0
  28. package/plugins/huaweicloud-core/dist/risk-rule-engine.js +20 -4
  29. package/plugins/huaweicloud-core/dist/safety/classify-hcloud.js +6 -6
  30. package/plugins/huaweicloud-core/dist/safety/classify-text.js +10 -0
  31. package/plugins/huaweicloud-core/dist/safety/policy.js +12 -0
  32. package/plugins/huaweicloud-core/dist/safety/protected-payload.js +93 -0
  33. package/plugins/huaweicloud-core/dist/safety/redact.js +21 -3
  34. package/plugins/huaweicloud-core/dist/safety/risk-merge.js +24 -4
  35. package/plugins/huaweicloud-core/dist/safety-integrity.js +122 -0
  36. package/plugins/huaweicloud-core/dist/sandbox/devbridge-cleanup.js +1 -1
  37. package/plugins/huaweicloud-core/dist/setup-cli.js +8 -1
  38. package/plugins/huaweicloud-core/dist/tool-definitions.js +4 -0
  39. package/plugins/huaweicloud-core/hooks/huaweicloud-safety.mjs +44 -1
  40. package/plugins/huaweicloud-core/hooks/huaweicloud-safety.py +75 -2
  41. package/plugins/huaweicloud-core/openclaw.plugin.json +2 -2
  42. package/plugins/huaweicloud-core/safety/policy.json +5 -0
  43. package/plugins/huaweicloud-core/safety/rules/cloud-risk-rules.json +1 -1
  44. package/plugins/huaweicloud-core/skills/huawei-sandbox/SKILL.md +42 -39
  45. package/plugins/huaweicloud-core/skills/huaweicloud-safety/references/approvals.md +1 -1
  46. package/plugins/huaweicloud-core/src/agents/opencode-config.ts +33 -3
  47. package/plugins/huaweicloud-core/src/agents/opencode.ts +66 -15
  48. package/plugins/huaweicloud-core/src/approval-gate.ts +29 -4
  49. package/plugins/huaweicloud-core/src/doctor-payload.ts +40 -2
  50. package/plugins/huaweicloud-core/src/explain-error.ts +9 -1
  51. package/plugins/huaweicloud-core/src/hcloud-plan.ts +6 -1
  52. package/plugins/huaweicloud-core/src/lib/hdkit/hdkitservice-api.ts +32 -1
  53. package/plugins/huaweicloud-core/src/lib/opencode-permission-seam.ts +60 -19
  54. package/plugins/huaweicloud-core/src/packs/auth/tools.ts +7 -1
  55. package/plugins/huaweicloud-core/src/packs/registry.ts +1 -0
  56. package/plugins/huaweicloud-core/src/packs/sandbox/expose-task.ts +105 -0
  57. package/plugins/huaweicloud-core/src/packs/sandbox/handlers-account.ts +28 -1
  58. package/plugins/huaweicloud-core/src/packs/sandbox/handlers-tunnel.ts +41 -15
  59. package/plugins/huaweicloud-core/src/packs/sandbox/schemas.ts +20 -0
  60. package/plugins/huaweicloud-core/src/packs/sandbox/tools.ts +12 -2
  61. package/plugins/huaweicloud-core/src/payload-placement.ts +8 -0
  62. package/plugins/huaweicloud-core/src/risk-rule-engine.ts +20 -7
  63. package/plugins/huaweicloud-core/src/safety/classify-hcloud.ts +28 -16
  64. package/plugins/huaweicloud-core/src/safety/classify-text.ts +10 -0
  65. package/plugins/huaweicloud-core/src/safety/policy.ts +13 -0
  66. package/plugins/huaweicloud-core/src/safety/protected-payload.ts +97 -0
  67. package/plugins/huaweicloud-core/src/safety/redact.ts +24 -6
  68. package/plugins/huaweicloud-core/src/safety/risk-merge.ts +26 -5
  69. package/plugins/huaweicloud-core/src/safety-integrity.ts +132 -0
  70. package/plugins/huaweicloud-core/src/sandbox/devbridge-cleanup.ts +7 -5
  71. package/plugins/huaweicloud-core/src/setup-cli.ts +8 -0
  72. package/plugins/huaweicloud-core/src/tool-definitions.ts +4 -0
@@ -9,9 +9,10 @@ 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, openCodeAskGate, } from "./opencode-config.js";
12
+ import { removeOpenCodeConfig, updateOpenCodeConfig, openCodeSeamGate, openCodeSeamGlobs, openCodeAskGate, openCodeSafetyGate, } from "./opencode-config.js";
13
13
  import { readPermissionRules, readPermissionRulesV1 } from "../lib/opencode-ask-rule.js";
14
14
  import { scanSavedAllowRows } from "../lib/opencode-saved-perms.js";
15
+ import { payloadEditDenyGlobs } from "../lib/opencode-permission-seam.js";
15
16
  import { asRecord } from "../lib/as-record.js";
16
17
  // Doctor: the OpenCode MCP-configured candidate — the opencode config's
17
18
  // mcp.huaweicloud-devkit entry.
@@ -157,23 +158,27 @@ function savedAllowStoreCheck(ctx) {
157
158
  }
158
159
  // Doctor: the skills-tree permission seam check — OpenCode installs only
159
160
  // (the seam is the installer's zero-prompt path for direct skill reads on
160
- // that harness). Verifies the two keys and their values, honoring the
161
- // ownership contract: a user-owned value on a devkit glob is reported as
162
- // kept, not broken; a below-floor or absent opencode is a SKIP, never a
163
- // FAIL.
161
+ // that harness). Verifies the keys and their values over BOTH glob classes,
162
+ // honoring the ownership contract: a user-owned value on a devkit glob is
163
+ // reported as kept, not broken; a below-floor or absent opencode is a SKIP,
164
+ // never a FAIL.
164
165
  export function opencodeDoctorSeam(ctx) {
165
166
  if (openCodeSeamGate() === 'off') {
166
167
  ctx.skip('Skills-tree permission seam (opencode not verifiably at or above the measured permission floor)');
167
168
  return;
168
169
  }
169
- // Per-glob evaluation, matching the installer's per-section/per-glob
170
+ // Per-glob, two-class evaluation, matching the installer's per-section
170
171
  // contract exactly: user-owned globs (any non-devkit value) are reported
171
172
  // as kept, missing globs as healable — one user-owned glob must never
172
- // mask a missing edit deny. Configs the installer itself refuses to
173
+ // mask a healable gap. The edit-only class (the payload root — the
174
+ // classifier the in-process gate imports) requires just the edit deny:
175
+ // the external allow is deliberately absent there, so requiring it would
176
+ // fail every healthy install. Configs the installer itself refuses to
173
177
  // touch (scalar-shaped permission, unparseable file — the parse-fail
174
178
  // skip is the install path's ONLY skip) get a SKIP with the manual
175
179
  // pointer, never a FAIL whose re-run-install remediation cannot succeed.
176
180
  const globs = openCodeSeamGlobs(opencodePluginsDir());
181
+ const editOnlyGlobs = payloadEditDenyGlobs(opencodePluginsDir());
177
182
  let cfg;
178
183
  try {
179
184
  cfg = asRecord(JSON.parse(readFileSync(opencodeConfigFile(), 'utf8')));
@@ -190,21 +195,38 @@ export function opencodeDoctorSeam(ctx) {
190
195
  const permRecord = asRecord(permission);
191
196
  const ext = asRecord(permRecord.external_directory);
192
197
  const editRules = asRecord(permRecord.edit);
193
- const kept = globs.filter((g) => (g in ext && ext[g] !== 'allow') || (g in editRules && editRules[g] !== 'deny'));
194
- const missing = globs.filter((g) => ext[g] !== 'allow' || editRules[g] !== 'deny');
195
- if (missing.length === 0) {
196
- ctx.check('Skills-tree permission seam (allow + edit deny)', true, '');
198
+ const kept = globs.filter((g) => (g in ext && ext[g] !== 'allow') || (g in editRules && editRules[g] !== 'deny')).length +
199
+ editOnlyGlobs.filter((g) => g in editRules && editRules[g] !== 'deny').length;
200
+ const missing = globs.filter((g) => ext[g] !== 'allow' || editRules[g] !== 'deny').length +
201
+ editOnlyGlobs.filter((g) => editRules[g] !== 'deny').length;
202
+ const LABEL = 'Skills-tree permission seam (allow + edit deny; payload edit deny)';
203
+ if (missing === 0) {
204
+ ctx.check(LABEL, true, '');
197
205
  }
198
- else if (kept.length === 0) {
199
- ctx.check('Skills-tree permission seam (allow + edit deny)', false, 'Run: npx huaweicloud-devkit install (writes the missing skills-tree rules; see README, Harness permission notes)');
206
+ else if (kept === 0) {
207
+ ctx.check(LABEL, false, 'Run: npx huaweicloud-devkit install (writes the missing seam rules; see README, Harness permission notes)');
200
208
  }
201
209
  else {
202
- ctx.check('Skills-tree permission seam (allow + edit deny)', false, `${missing.length} rule(s) missing (re-run: npx huaweicloud-devkit install); ${kept.length} user-owned glob(s) kept as-is (see README, Harness permission notes)`);
210
+ ctx.check(LABEL, false, `${missing} rule(s) missing (re-run: npx huaweicloud-devkit install); ${kept} user-owned glob(s) kept as-is (see README, Harness permission notes)`);
203
211
  }
204
212
  }
213
+ // Doctor: the shell safety gate — OpenCode installs only (the evaluate-hook
214
+ // adapter is the opencode ≥ 2.0 in-process deny face for shell commands).
215
+ // A below-floor, absent, or unparsable opencode is a SKIP, never a FAIL
216
+ // (the adapter has no surface to register on there); a verifiably ≥ 2.0
217
+ // opencode with a missing adapter file is the FAIL install heals.
218
+ export function opencodeDoctorSafetyGate(ctx) {
219
+ if (openCodeSafetyGate() === 'off') {
220
+ ctx.skip('Shell safety gate (opencode not verifiably at or above 2.0.0)');
221
+ return;
222
+ }
223
+ const gateFile = join(configRoot('opencode'), 'plugins', 'safety-gate.js');
224
+ ctx.check('Shell safety gate (evaluate-hook adapter)', existsSync(gateFile), 'Run: npx huaweicloud-devkit install --target opencode');
225
+ }
205
226
  export async function deployOpenCode(mode) {
206
227
  const commandsSrc = join(PACKAGE_ROOT, 'integrations', 'opencode', 'commands');
207
228
  const pluginSrc = join(PACKAGE_ROOT, 'integrations', 'opencode', 'hooks', 'skill-tracker.js');
229
+ const gateSrc = join(PACKAGE_ROOT, 'integrations', 'opencode', 'hooks', 'safety-gate.js');
208
230
  const pluginDest = opencodePluginsDir();
209
231
  copyDir(commandsSrc, opencodeCommandsDir());
210
232
  const staleCommands = mode === 'update' ? pruneStale(opencodeCommandsDir(), commandsSrc) : 0;
@@ -214,6 +236,18 @@ export async function deployOpenCode(mode) {
214
236
  mkdirSync(opcPlugins, { recursive: true });
215
237
  copyFileSync(pluginSrc, join(opcPlugins, 'skill-tracker.js'));
216
238
  console.log(` Plugin${deployWord(mode)} -> ${opcPlugins}`);
239
+ const gateFile = join(opcPlugins, 'safety-gate.js');
240
+ if (openCodeSafetyGate() === 'on') {
241
+ copyFileSync(gateSrc, gateFile);
242
+ console.log(` Safety gate${deployWord(mode)} -> ${opcPlugins}`);
243
+ }
244
+ else {
245
+ // Drift heal, same doctrine as the ask-rule migration: an opencode that
246
+ // downgraded or vanished since the last install must not keep the file
247
+ // (a below-floor host has no evaluate hook to run it on).
248
+ removeIfExists(gateFile);
249
+ console.log(' \x1b[33m[INFO]\x1b[0m opencode not verifiably at or above 2.0.0 — skipping the shell safety-gate plugin; a below-floor host has no evaluate hook to gate the Bash face on.');
250
+ }
217
251
  updateOpenCodeConfig(pluginDest);
218
252
  installRuntimeDeps(pluginDest);
219
253
  }
@@ -229,6 +263,11 @@ export function uninstallOpenCode(removeOwnedSkills) {
229
263
  removeIfExists(pluginFile);
230
264
  console.log(' Removed plugin');
231
265
  }
266
+ const gateFile = join(configRoot('opencode'), 'plugins', 'safety-gate.js');
267
+ if (existsSync(gateFile)) {
268
+ removeIfExists(gateFile);
269
+ console.log(' Removed safety-gate plugin');
270
+ }
232
271
  if (removeIfExists(opencodePluginsDir())) {
233
272
  console.log(' Removed MCP server and safety policy');
234
273
  }
@@ -236,5 +275,7 @@ export function uninstallOpenCode(removeOwnedSkills) {
236
275
  }
237
276
  export function opencodeStatus() {
238
277
  payloadStatusLines(opencodePluginsDir());
278
+ const gateInstalled = existsSync(join(configRoot('opencode'), 'plugins', 'safety-gate.js'));
279
+ console.log(` Shell safety gate: ${gateInstalled ? '\x1b[32mInstalled\x1b[0m' : '\x1b[31mNot installed\x1b[0m'}`);
239
280
  printMcpConfigStatus(opencodeConfigFile(), 'mcp');
240
281
  }
@@ -30,6 +30,15 @@ import { annotateDispatchOutcome, recordAskModeConsent } from "./approval-ledger
30
30
  import { resolveConfirmLanguage } from "./lib/confirm-language.js";
31
31
  export const NO_SESSION_SEAM_ERROR = 'Runtime pack configuration is available in stdio agent sessions only; this surface carries no session state.';
32
32
  const GRANT_REQUIRED_NEXT_STEP = 'Ask the user to run "npx huaweicloud-devkit approve <this approvalToken>" in their own terminal, then retry this exact call.';
33
+ // F-APV-1: every CONFIRM_TOKEN_* rejection spells its way out — the ask
34
+ // envelope and the mint envelope already carry nextStep, and these close the
35
+ // gap so the model never has to reverse-engineer the approval flow from
36
+ // tool descriptions. Splitting NOT_FOUND into MISSING vs INVALID is a
37
+ // contract change held for its own pass; this keeps the pinned codes and
38
+ // only adds the guidance. Exported for the tests that pin the envelopes.
39
+ export const PLAN_FACE_TOKEN_MISSING_NEXT_STEP = 'This run call requires an approvalToken minted by the plan face. Call huaweicloud_plan_cli_command with the same args first — its USER_CONFIRMATION_REQUIRED envelope carries the fresh approvalToken; retry this call with it.';
40
+ export const CONFIRM_TOKEN_UNKNOWN_NEXT_STEP = 'This approvalToken was never minted in this process — malformed, or dropped by a server restart (tokens are process-scoped and never persisted). Re-run the plan call to mint a fresh approvalToken, then retry this call with it.';
41
+ export const CONFIRM_TOKEN_EXPIRED_NEXT_STEP = 'This approvalToken passed its 5-minute TTL. Re-run the plan call to mint a fresh approvalToken and have the user approve it promptly, then retry this call with it.';
33
42
  // The command-forward anchor (the operator-approved display field): a call
34
43
  // that carries the tool's `command` string must spell the exact line its args
35
44
  // execute, so the harness popup's first line is the command the user is
@@ -849,7 +858,9 @@ export async function runApprovalGate(name, spec, args, opts) {
849
858
  // classified nothing on a tokenless call, and the plan face's own hook
850
859
  // deny already covers the credential class at plan time.
851
860
  if (spec.tokenSource === 'plan-face') {
852
- return { envelope: { status: 'rejected', code: 'CONFIRM_TOKEN_NOT_FOUND' } };
861
+ return {
862
+ envelope: { status: 'rejected', code: 'CONFIRM_TOKEN_NOT_FOUND', nextStep: PLAN_FACE_TOKEN_MISSING_NEXT_STEP },
863
+ };
853
864
  }
854
865
  // Gate-source mint face (PR-3 registrations; ApprovalCoreMint's
855
866
  // classify-before-mint). BOTH floors sit before the mint for the same
@@ -889,13 +900,17 @@ export async function runApprovalGate(name, spec, args, opts) {
889
900
  return { envelope: { status: 'ok', outcome: 'already_processed' } };
890
901
  }
891
902
  if (inspection.state === 'expired') {
892
- return { envelope: { status: 'rejected', code: 'CONFIRM_TOKEN_EXPIRED' } };
903
+ return {
904
+ envelope: { status: 'rejected', code: 'CONFIRM_TOKEN_EXPIRED', nextStep: CONFIRM_TOKEN_EXPIRED_NEXT_STEP },
905
+ };
893
906
  }
894
907
  if (inspection.state === 'not_found') {
895
908
  // A token that was never created (typo / unknown / pruned beyond the
896
909
  // tombstone window) is still a rejection, but carries no expired or
897
910
  // already semantics — a distinct code so clients can tell them apart.
898
- return { envelope: { status: 'rejected', code: 'CONFIRM_TOKEN_NOT_FOUND' } };
911
+ return {
912
+ envelope: { status: 'rejected', code: 'CONFIRM_TOKEN_NOT_FOUND', nextStep: CONFIRM_TOKEN_UNKNOWN_NEXT_STEP },
913
+ };
899
914
  }
900
915
  // Credential floor before the consume, so the refusal burns nothing and
901
916
  // the guidance stays followable on the same token; the execution floor
@@ -915,8 +930,11 @@ export async function runApprovalGate(name, spec, args, opts) {
915
930
  // two reads. Classify via re-inspect, never a misleading success and
916
931
  // never a false not_found.
917
932
  const recheck = inspectApprovalToken(token);
918
- if (recheck.state === 'expired')
919
- return { envelope: { status: 'rejected', code: 'CONFIRM_TOKEN_EXPIRED' } };
933
+ if (recheck.state === 'expired') {
934
+ return {
935
+ envelope: { status: 'rejected', code: 'CONFIRM_TOKEN_EXPIRED', nextStep: CONFIRM_TOKEN_EXPIRED_NEXT_STEP },
936
+ };
937
+ }
920
938
  return { envelope: { status: 'ok', outcome: 'already_processed' } };
921
939
  }
922
940
  const stored = consumed.entry;
@@ -9,6 +9,7 @@ import { existsSync } from 'node:fs';
9
9
  import { join } from 'node:path';
10
10
  import { nativeFreshnessChecks } from "./doctor-native.js";
11
11
  import { mcpServerInstalled, serverSkillDirNames } from "./install-payload.js";
12
+ import { verifyIntegrity } from "./safety-integrity.js";
12
13
  // Set equality against the shipped manifest, not a count floor and not a
13
14
  // one-direction subset: verifySkillTree (boot) rejects missing, hollow (name
14
15
  // present, SKILL.md absent), and unclaimed entries, so doctor must fail any
@@ -20,6 +21,12 @@ export function skillsTreeMatches(dir, expectedSkills) {
20
21
  }
21
22
  // The generic per-row section: the triple over the row's plugin dir plus the
22
23
  // receipt-gated native-freshness checks over the row's native dirs.
24
+ // The generic per-row section: the triple over the row's plugin dir plus
25
+ // the receipt-gated native-freshness checks over the row's native dirs,
26
+ // plus the deployed-classifier integrity comparison (layer 3). Rows
27
+ // without a deployed safety payload stay silent; a payload without a
28
+ // receipt (a pre-integrity install) WARNs — backward compatibility, never
29
+ // a false red; drift FAILs with the reinstall remediation.
23
30
  export function payloadDoctorSection(row, shared) {
24
31
  const dir = row.dir();
25
32
  return {
@@ -30,5 +37,27 @@ export function payloadDoctorSection(row, shared) {
30
37
  skillsTree: skillsTreeMatches(dir, shared.expectedSkills),
31
38
  },
32
39
  nativeFreshness: (ctx) => nativeFreshnessChecks(ctx, row, shared.corePack),
40
+ integrity: (ctx) => payloadIntegrityCheck(ctx, row.label, dir),
33
41
  };
34
42
  }
43
+ export function payloadIntegrityCheck(ctx, label, dir) {
44
+ const status = verifyIntegrity(dir);
45
+ if (status.status === 'no-payload')
46
+ return;
47
+ if (status.status === 'match') {
48
+ ctx.pass(`Safety policy integrity (${label})`);
49
+ return;
50
+ }
51
+ if (status.status === 'no-receipt') {
52
+ ctx.warn(`Safety policy integrity (${label}) — integrity receipt missing (payload predates integrity tracking); re-run: npx huaweicloud-devkit install`);
53
+ return;
54
+ }
55
+ const all = [...status.drifted, ...status.missing, ...status.unrecorded];
56
+ const parts = [
57
+ status.drifted.length > 0 ? `${status.drifted.length} changed` : '',
58
+ status.missing.length > 0 ? `${status.missing.length} missing` : '',
59
+ status.unrecorded.length > 0 ? `${status.unrecorded.length} unrecorded` : '',
60
+ ].filter(Boolean);
61
+ const names = `${all.slice(0, 3).join(', ')}${all.length > 3 ? ', …' : ''}`;
62
+ ctx.check(`Safety policy integrity (${label})`, false, `${parts.join(', ')} classifier file(s) (${names}) — Run: npx huaweicloud-devkit install`);
63
+ }
@@ -200,8 +200,16 @@ export function explainError({ service = 'unknown', errorCode = '', code = '', m
200
200
  const uniqueSuggestions = suggestions.filter((s, i, arr) => {
201
201
  return !arr.slice(0, i).some((prev) => prev.substring(0, 50).toLowerCase() === s.substring(0, 50).toLowerCase());
202
202
  });
203
+ // The response names the service the error was RESOLVED to, not a raw
204
+ // `unknown`/wrong pasted name: `code`-only calls and a pasted service whose
205
+ // own pattern table is empty derive their key from the code prefix (the
206
+ // suggestions already walked that table). A valid explicit service keeps
207
+ // its exact spelling — the pre-existing contract and its #935 regression
208
+ // pin (AX report D-05).
209
+ const providedKnown = Boolean(service) && svc !== 'unknown';
210
+ const responseService = !providedKnown || !hwErrorPatterns[patternKey] ? effectiveKey : service;
203
211
  return {
204
- service,
212
+ service: responseService,
205
213
  errorCode: resolvedCode,
206
214
  requestId,
207
215
  suggestions: uniqueSuggestions,
@@ -336,6 +336,11 @@ export function planHcloudCommand(args, options = {}) {
336
336
  ...(approvalToken !== undefined ? { command: `npx huaweicloud-devkit approve ${approvalToken}` } : {}),
337
337
  }
338
338
  : { needed: false },
339
- safeToRun: effectiveClassification.decision === 'allow',
339
+ // "Safe to run NOW": a caller-supplied allowWrites:true only unlocks the
340
+ // classification — the strict view still demands the user's confirmation
341
+ // (the approval token/form), so a plan showing decision:"allow" must not
342
+ // also read as runnable while userConfirmation.needed is true (AX D-02
343
+ // display-layer alignment).
344
+ safeToRun: effectiveClassification.decision === 'allow' && !needsConfirmation,
340
345
  };
341
346
  }
@@ -377,16 +377,10 @@ export async function hdkitConnect(options = {}) {
377
377
  }
378
378
  return asRecord(await hdkitRequest('POST', 'connect', body));
379
379
  }
380
- /**
381
- * connect 专用网关 502/504 重试(dev e0c8700b):编排期响应超时不是创建失败,
382
- * 服务端可能已创建/启动实例,重试通常复用。有界重试、逐档退避,其余状态一律
383
- * 不重试(含 409 版本门禁与配额/容量/凭证类客户端裁决码——不可重试裁决由
384
- * hdkit-gate 的瞬时判定与裁决码集合独占)。
385
- * 重试表经 HW_SANDBOX_CONNECT_RETRY_DELAYS_MS 针脚可覆写(v2 扩展)。
386
- * 成功路径回显 connect_retries(v2 扩展;dev 仅在错误路径带尝试次数)。
387
- */
388
- export async function hdkitConnectWithRetry(options = {}) {
380
+ export async function hdkitConnectWithRetry(options = {}, retryOptions = {}) {
389
381
  const delays = connectRetryDelaysMs();
382
+ const inlineRetry = retryOptions.inlineRetry !== false;
383
+ const maxInlineDelayMs = retryOptions.maxInlineDelayMs ?? Number.POSITIVE_INFINITY;
390
384
  let retries = 0;
391
385
  for (;;) {
392
386
  try {
@@ -411,6 +405,21 @@ export async function hdkitConnectWithRetry(options = {}) {
411
405
  throw decorateExhaustedConnect(error, retries);
412
406
  throw error;
413
407
  }
408
+ if (!inlineRetry || (delays[retries] ?? Number.POSITIVE_INFINITY) > maxInlineDelayMs) {
409
+ // AX N-SB.2: never hold the tool call through a backoff longer than
410
+ // the host's request budget — a host request timeout would abandon
411
+ // the call while the server completed the create. The retry moves to
412
+ // the next tool call (same params). Short test/operator backoffs keep
413
+ // the inline ladder.
414
+ const pendingCode = asString(safeReadField(error, 'code'));
415
+ return {
416
+ pending: true,
417
+ connectRetries: retries,
418
+ retryAfterMs: delays[retries] ?? delays[0] ?? 0,
419
+ ...(pendingCode ? { code: pendingCode } : {}),
420
+ message: safeMessageText(error),
421
+ };
422
+ }
414
423
  await new Promise((resolve) => setTimeout(resolve, delays[retries]));
415
424
  retries += 1;
416
425
  }
@@ -13,6 +13,17 @@
13
13
  // Mitigations: the tree is regenerated by every install/update
14
14
  // (copyServerPayload), and the PreToolUse hook still denies hcloud writes.
15
15
  //
16
+ // The payload root is the seam's EDIT-ONLY class (the interrogate round's
17
+ // classifier-rewrite finding): the deployed dist/safety-policy.js is what
18
+ // the in-process evaluate gate imports at runtime, so an edit-tool rewrite
19
+ // disarms the gate mid-session. The edit deny closes that tool vector; the
20
+ // external_directory allow is deliberately NOT extended to the payload —
21
+ // an allowed external directory inherits workspace defaults where bash is
22
+ // allowed, and the payload must not become a no-prompt bash write target.
23
+ // The bash-face residual is disclosed in the approvals reference and the
24
+ // changelog (the architectural fix direction is install-time integrity
25
+ // verification, out of scope here).
26
+ //
16
27
  // Ownership rules (no receipt, by judgment recorded in the changelog): two
17
28
  // keys over devkit-only globs — any rule on these globs is devkit-domain by
18
29
  // construction, so add-only-if-absent (a pre-existing rule with ANY value is
@@ -46,12 +57,39 @@ export function skillTreePermissionGlobs(pluginSkillsDir, nativeSkillsDir, coreS
46
57
  }
47
58
  return globs;
48
59
  }
60
+ // The edit-only class: the payload root (dist/, safety/, node_modules —
61
+ // everything the deployed gate imports or executes). Edit/write/patch tools
62
+ // deny there, but the external_directory allow is deliberately NOT
63
+ // extended: the payload must not become a no-prompt bash write target.
64
+ export function payloadEditDenyGlobs(pluginDir) {
65
+ return [`${pluginDir.replace(/\\/g, '/')}/**`];
66
+ }
67
+ // The per-section resolver shared by apply and remove: the section record
68
+ // (fresh when absent, so the caller's writes land and are assigned back),
69
+ // or null when the user owns a scalar shape there — one ownership check in
70
+ // one place for both directions of the seam.
71
+ function sectionFor(permission, key) {
72
+ if (permission[key] !== undefined && !isRecord(permission[key]))
73
+ return null;
74
+ return asRecord(permission[key]);
75
+ }
76
+ // The two-class section table shared by apply and remove: the external
77
+ // allow covers the skills globs only, the edit deny covers them plus the
78
+ // edit-only payload class.
79
+ function seamSections(globs, editOnlyGlobs) {
80
+ return [
81
+ ['external_directory', 'allow', globs],
82
+ ['edit', 'deny', [...globs, ...editOnlyGlobs]],
83
+ ];
84
+ }
49
85
  // Mutates config in place. Add-only-if-absent per section: a glob already
50
86
  // present with ANY value keeps the user's rule; only missing globs get the
51
87
  // devkit value. Appended keys win under OpenCode's last-matching-rule-wins
52
88
  // evaluation — deliberate, so the devkit's specific allow beats an earlier
53
- // broader user pattern (e.g. "~/.config/opencode/**": "ask").
54
- export function applySkillTreePermissionSeam(config, globs) {
89
+ // broader user pattern (e.g. "~/.config/opencode/**": "ask"). The edit-only
90
+ // class writes the edit section alone; the external allow deliberately
91
+ // never covers it (see the module header).
92
+ export function applySkillTreePermissionSeam(config, globs, editOnlyGlobs = []) {
55
93
  if (config.permission !== undefined && !isRecord(config.permission)) {
56
94
  // The whole-config string form ("permission": "allow") is the user's
57
95
  // global posture; converting it to an object would silently revert
@@ -61,17 +99,13 @@ export function applySkillTreePermissionSeam(config, globs) {
61
99
  const permission = asRecord(config.permission);
62
100
  const skipped = [];
63
101
  let changed = false;
64
- const sections = [
65
- ['external_directory', 'allow'],
66
- ['edit', 'deny'],
67
- ];
68
- for (const [key, value] of sections) {
69
- if (permission[key] !== undefined && !isRecord(permission[key])) {
102
+ for (const [key, value, list] of seamSections(globs, editOnlyGlobs)) {
103
+ const section = sectionFor(permission, key);
104
+ if (section === null) {
70
105
  skipped.push(key);
71
106
  continue;
72
107
  }
73
- const section = asRecord(permission[key]);
74
- const missing = globs.filter((glob) => !Object.hasOwn(section, glob));
108
+ const missing = list.filter((glob) => !Object.hasOwn(section, glob));
75
109
  if (missing.length === 0)
76
110
  continue;
77
111
  for (const glob of missing)
@@ -86,22 +120,19 @@ export function applySkillTreePermissionSeam(config, globs) {
86
120
  // Mutates config in place. Value-exact deletion only — a user-modified value
87
121
  // on a devkit glob survives. Sections emptied by OUR deletions are pruned
88
122
  // (a pre-existing empty section is left untouched), and the permission
89
- // object itself is pruned only when the seam emptied it.
90
- export function removeSkillTreePermissionSeam(config, globs) {
123
+ // object itself is pruned only when the seam emptied it. The edit-only
124
+ // class is removed from the edit section under the same value-exact rule.
125
+ export function removeSkillTreePermissionSeam(config, globs, editOnlyGlobs = []) {
91
126
  if (!isRecord(config.permission))
92
127
  return false;
93
128
  const permission = asRecord(config.permission);
94
129
  let changed = false;
95
- const sections = [
96
- ['external_directory', 'allow'],
97
- ['edit', 'deny'],
98
- ];
99
- for (const [key, value] of sections) {
100
- if (!isRecord(permission[key]))
130
+ for (const [key, value, list] of seamSections(globs, editOnlyGlobs)) {
131
+ const section = sectionFor(permission, key);
132
+ if (section === null)
101
133
  continue;
102
- const section = asRecord(permission[key]);
103
134
  let removedHere = false;
104
- for (const glob of globs) {
135
+ for (const glob of list) {
105
136
  if (section[glob] === value) {
106
137
  delete section[glob];
107
138
  removedHere = true;