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

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 (161) hide show
  1. package/README.md +3 -1
  2. package/package.json +3 -1
  3. package/plugins/huaweicloud-core/.claude-plugin/plugin.json +16 -3
  4. package/plugins/huaweicloud-core/.codex-plugin/plugin.json +16 -3
  5. package/plugins/huaweicloud-core/.cursor-plugin/plugin.json +16 -3
  6. package/plugins/huaweicloud-core/.hermes-plugin/plugin.json +16 -3
  7. package/plugins/huaweicloud-core/.mcp.json +55 -1
  8. package/plugins/huaweicloud-core/.workbuddy-plugin/plugin.json +16 -3
  9. package/plugins/huaweicloud-core/dist/agents/codex-config.js +374 -0
  10. package/plugins/huaweicloud-core/dist/agents/codex-desktop.js +8 -1
  11. package/plugins/huaweicloud-core/dist/agents/codex.js +9 -0
  12. package/plugins/huaweicloud-core/dist/agents/opencode-config.js +141 -86
  13. package/plugins/huaweicloud-core/dist/agents/opencode.js +106 -39
  14. package/plugins/huaweicloud-core/dist/approval-gate.js +1185 -0
  15. package/plugins/huaweicloud-core/dist/approval-ledger.js +2331 -0
  16. package/plugins/huaweicloud-core/dist/approval-roster.js +89 -0
  17. package/plugins/huaweicloud-core/dist/approval-types.js +1 -0
  18. package/plugins/huaweicloud-core/dist/approvals-cli.js +4 -4
  19. package/plugins/huaweicloud-core/dist/data/icons-manifest.v1.json +23 -5
  20. package/plugins/huaweicloud-core/dist/dep/receipts.js +65 -5
  21. package/plugins/huaweicloud-core/dist/hcloud-cli.js +1 -1
  22. package/plugins/huaweicloud-core/dist/hcloud-plan.js +62 -61
  23. package/plugins/huaweicloud-core/dist/lib/approval-mode.js +7 -5
  24. package/plugins/huaweicloud-core/dist/lib/approval-tokens.js +18 -4
  25. package/plugins/huaweicloud-core/dist/lib/call-trace.js +7 -14
  26. package/plugins/huaweicloud-core/dist/lib/confirm-language.js +50 -0
  27. package/plugins/huaweicloud-core/dist/lib/credentials.js +9 -9
  28. package/plugins/huaweicloud-core/dist/lib/hdkit/hdkit-gate.js +1398 -0
  29. package/plugins/huaweicloud-core/dist/lib/hdkit/hdkitservice-api.js +362 -32
  30. package/plugins/huaweicloud-core/dist/lib/hdkit/sandbox-pool.js +6 -16
  31. package/plugins/huaweicloud-core/dist/lib/opencode-ask-rule.js +224 -78
  32. package/plugins/huaweicloud-core/dist/lib/opencode-saved-perms.js +282 -0
  33. package/plugins/huaweicloud-core/dist/lib/supplemental-redaction.js +116 -0
  34. package/plugins/huaweicloud-core/dist/lib/tool-schema-parts.js +31 -0
  35. package/plugins/huaweicloud-core/dist/lib/workspace-glob.js +442 -0
  36. package/plugins/huaweicloud-core/dist/mcp-config-io.js +28 -1
  37. package/plugins/huaweicloud-core/dist/mcp-protocol.js +68 -16
  38. package/plugins/huaweicloud-core/dist/mcp-server.js +6506 -912
  39. package/plugins/huaweicloud-core/dist/mcp-server.js.map +4 -4
  40. package/plugins/huaweicloud-core/dist/mcp-stdio-transport.js +14 -4
  41. package/plugins/huaweicloud-core/dist/packs/auth/approval.js +249 -0
  42. package/plugins/huaweicloud-core/dist/packs/auth/tools.js +44 -44
  43. package/plugins/huaweicloud-core/dist/packs/huaweicloud-cli/tools.js +85 -130
  44. package/plugins/huaweicloud-core/dist/packs/obs/approval.js +110 -0
  45. package/plugins/huaweicloud-core/dist/packs/obs/tools.js +7 -2
  46. package/plugins/huaweicloud-core/dist/packs/registry.js +19 -1
  47. package/plugins/huaweicloud-core/dist/packs/sandbox/approval.js +245 -0
  48. package/plugins/huaweicloud-core/dist/packs/sandbox/handlers-account.js +156 -23
  49. package/plugins/huaweicloud-core/dist/packs/sandbox/handlers-credentials.js +13 -1
  50. package/plugins/huaweicloud-core/dist/packs/sandbox/handlers-hwexec.js +136 -0
  51. package/plugins/huaweicloud-core/dist/packs/sandbox/handlers-session.js +11 -1
  52. package/plugins/huaweicloud-core/dist/packs/sandbox/handlers-tunnel.js +1 -0
  53. package/plugins/huaweicloud-core/dist/packs/sandbox/schemas.js +79 -9
  54. package/plugins/huaweicloud-core/dist/packs/sandbox/tools.js +28 -9
  55. package/plugins/huaweicloud-core/dist/packs/secrets/approval.js +46 -0
  56. package/plugins/huaweicloud-core/dist/packs/secrets/tools.js +4 -1
  57. package/plugins/huaweicloud-core/dist/packs/update/approval.js +79 -0
  58. package/plugins/huaweicloud-core/dist/packs/update/tools.js +8 -1
  59. package/plugins/huaweicloud-core/dist/packs/voucher/tools.js +1 -1
  60. package/plugins/huaweicloud-core/dist/packs-configure.js +74 -0
  61. package/plugins/huaweicloud-core/dist/safety/classify-text.js +36 -0
  62. package/plugins/huaweicloud-core/dist/safety/policy.js +2 -0
  63. package/plugins/huaweicloud-core/dist/sandbox/deploy-check.js +1 -1
  64. package/plugins/huaweicloud-core/dist/sandbox/devbridge-auth.js +65 -14
  65. package/plugins/huaweicloud-core/dist/sandbox/devbridge-cleanup.js +422 -0
  66. package/plugins/huaweicloud-core/dist/sandbox/devbridge-expose-flow.js +66 -16
  67. package/plugins/huaweicloud-core/dist/sandbox/devbridge-expose.js +13 -10
  68. package/plugins/huaweicloud-core/dist/sandbox/devbridge-keepalive.js +42 -2
  69. package/plugins/huaweicloud-core/dist/sandbox/devbridge-key.js +11 -3
  70. package/plugins/huaweicloud-core/dist/sandbox/devbridge-tunnel.js +6 -0
  71. package/plugins/huaweicloud-core/dist/sandbox/devbridge-validation.js +10 -1
  72. package/plugins/huaweicloud-core/dist/sandbox/hwexec-task.js +244 -0
  73. package/plugins/huaweicloud-core/dist/setup-cli.js +36 -1
  74. package/plugins/huaweicloud-core/dist/tool-definitions.js +9 -1
  75. package/plugins/huaweicloud-core/dist/tool-schemas.js +32 -6
  76. package/plugins/huaweicloud-core/dist/tools.js +76 -9
  77. package/plugins/huaweicloud-core/dist/update-registry.js +358 -5
  78. package/plugins/huaweicloud-core/dist/update-upgrade.js +1083 -14
  79. package/plugins/huaweicloud-core/dist/vendor-gate.js +2 -2
  80. package/plugins/huaweicloud-core/hooks/huaweicloud-safety.mjs +150 -1
  81. package/plugins/huaweicloud-core/hooks/huaweicloud-safety.py +53 -3
  82. package/plugins/huaweicloud-core/openclaw.plugin.json +1 -1
  83. package/plugins/huaweicloud-core/safety/policy.json +18 -11
  84. package/plugins/huaweicloud-core/safety/rules/cloud-risk-rules.json +114 -10
  85. package/plugins/huaweicloud-core/skills/huawei-sandbox/SKILL.md +190 -138
  86. package/plugins/huaweicloud-core/skills/huawei-sandbox/references/resource-pool.md +36 -12
  87. package/plugins/huaweicloud-core/skills/huawei-voucher/SKILL.md +2 -0
  88. package/plugins/huaweicloud-core/skills/huaweicloud-cli-and-auth/SKILL.md +2 -2
  89. package/plugins/huaweicloud-core/skills/huaweicloud-safety/SKILL.md +11 -7
  90. package/plugins/huaweicloud-core/skills/huaweicloud-safety/references/approvals.md +74 -29
  91. package/plugins/huaweicloud-core/skills/huaweicloud-troubleshooting/SKILL.md +21 -19
  92. package/plugins/huaweicloud-core/src/agents/codex-config.ts +432 -0
  93. package/plugins/huaweicloud-core/src/agents/codex-desktop.ts +8 -1
  94. package/plugins/huaweicloud-core/src/agents/codex.ts +10 -0
  95. package/plugins/huaweicloud-core/src/agents/opencode-config.ts +176 -88
  96. package/plugins/huaweicloud-core/src/agents/opencode.ts +125 -54
  97. package/plugins/huaweicloud-core/src/approval-gate.ts +1306 -0
  98. package/plugins/huaweicloud-core/src/approval-ledger.ts +2446 -0
  99. package/plugins/huaweicloud-core/src/approval-roster.ts +127 -0
  100. package/plugins/huaweicloud-core/src/approval-types.ts +237 -0
  101. package/plugins/huaweicloud-core/src/approvals-cli.ts +4 -4
  102. package/plugins/huaweicloud-core/src/data/icons-manifest.v1.json +23 -5
  103. package/plugins/huaweicloud-core/src/dep/receipts.ts +84 -5
  104. package/plugins/huaweicloud-core/src/hcloud-cli.ts +3 -0
  105. package/plugins/huaweicloud-core/src/hcloud-plan.ts +68 -70
  106. package/plugins/huaweicloud-core/src/lib/approval-mode.ts +7 -5
  107. package/plugins/huaweicloud-core/src/lib/approval-tokens.ts +19 -4
  108. package/plugins/huaweicloud-core/src/lib/call-trace.ts +7 -17
  109. package/plugins/huaweicloud-core/src/lib/confirm-language.ts +51 -0
  110. package/plugins/huaweicloud-core/src/lib/credentials.ts +9 -8
  111. package/plugins/huaweicloud-core/src/lib/hdkit/hdkit-gate.ts +1428 -0
  112. package/plugins/huaweicloud-core/src/lib/hdkit/hdkitservice-api.ts +377 -30
  113. package/plugins/huaweicloud-core/src/lib/hdkit/sandbox-pool.ts +8 -15
  114. package/plugins/huaweicloud-core/src/lib/opencode-ask-rule.ts +302 -83
  115. package/plugins/huaweicloud-core/src/lib/opencode-saved-perms.ts +354 -0
  116. package/plugins/huaweicloud-core/src/lib/supplemental-redaction.ts +129 -0
  117. package/plugins/huaweicloud-core/src/lib/tool-schema-parts.ts +40 -0
  118. package/plugins/huaweicloud-core/src/lib/workspace-glob.ts +414 -0
  119. package/plugins/huaweicloud-core/src/mcp-config-io.ts +27 -1
  120. package/plugins/huaweicloud-core/src/mcp-protocol.ts +81 -17
  121. package/plugins/huaweicloud-core/src/mcp-server.ts +7 -7
  122. package/plugins/huaweicloud-core/src/mcp-stdio-transport.ts +14 -4
  123. package/plugins/huaweicloud-core/src/packs/auth/approval.ts +302 -0
  124. package/plugins/huaweicloud-core/src/packs/auth/tools.ts +54 -45
  125. package/plugins/huaweicloud-core/src/packs/huaweicloud-cli/tools.ts +99 -137
  126. package/plugins/huaweicloud-core/src/packs/obs/approval.ts +122 -0
  127. package/plugins/huaweicloud-core/src/packs/obs/tools.ts +7 -2
  128. package/plugins/huaweicloud-core/src/packs/registry.ts +42 -1
  129. package/plugins/huaweicloud-core/src/packs/sandbox/approval.ts +296 -0
  130. package/plugins/huaweicloud-core/src/packs/sandbox/handlers-account.ts +168 -23
  131. package/plugins/huaweicloud-core/src/packs/sandbox/handlers-credentials.ts +11 -1
  132. package/plugins/huaweicloud-core/src/packs/sandbox/handlers-hwexec.ts +228 -0
  133. package/plugins/huaweicloud-core/src/packs/sandbox/handlers-session.ts +11 -1
  134. package/plugins/huaweicloud-core/src/packs/sandbox/handlers-tunnel.ts +1 -0
  135. package/plugins/huaweicloud-core/src/packs/sandbox/schemas.ts +100 -8
  136. package/plugins/huaweicloud-core/src/packs/sandbox/tools.ts +31 -8
  137. package/plugins/huaweicloud-core/src/packs/secrets/approval.ts +50 -0
  138. package/plugins/huaweicloud-core/src/packs/secrets/tools.ts +4 -1
  139. package/plugins/huaweicloud-core/src/packs/update/approval.ts +87 -0
  140. package/plugins/huaweicloud-core/src/packs/update/tools.ts +8 -1
  141. package/plugins/huaweicloud-core/src/packs/voucher/tools.ts +1 -1
  142. package/plugins/huaweicloud-core/src/packs-configure.ts +75 -0
  143. package/plugins/huaweicloud-core/src/safety/classify-text.ts +40 -0
  144. package/plugins/huaweicloud-core/src/safety/policy.ts +7 -0
  145. package/plugins/huaweicloud-core/src/sandbox/deploy-check.ts +1 -1
  146. package/plugins/huaweicloud-core/src/sandbox/devbridge-auth.ts +74 -14
  147. package/plugins/huaweicloud-core/src/sandbox/devbridge-cleanup.ts +509 -0
  148. package/plugins/huaweicloud-core/src/sandbox/devbridge-expose-flow.ts +70 -18
  149. package/plugins/huaweicloud-core/src/sandbox/devbridge-expose.ts +26 -10
  150. package/plugins/huaweicloud-core/src/sandbox/devbridge-keepalive.ts +41 -2
  151. package/plugins/huaweicloud-core/src/sandbox/devbridge-key.ts +9 -3
  152. package/plugins/huaweicloud-core/src/sandbox/devbridge-tunnel.ts +24 -0
  153. package/plugins/huaweicloud-core/src/sandbox/devbridge-validation.ts +11 -1
  154. package/plugins/huaweicloud-core/src/sandbox/hwexec-task.ts +304 -0
  155. package/plugins/huaweicloud-core/src/setup-cli.ts +39 -1
  156. package/plugins/huaweicloud-core/src/tool-definitions.ts +9 -1
  157. package/plugins/huaweicloud-core/src/tool-schemas.ts +39 -6
  158. package/plugins/huaweicloud-core/src/tools.ts +124 -10
  159. package/plugins/huaweicloud-core/src/update-registry.ts +340 -5
  160. package/plugins/huaweicloud-core/src/update-upgrade.ts +1130 -14
  161. package/plugins/huaweicloud-core/src/vendor-gate.ts +2 -2
@@ -1,71 +1,112 @@
1
- // The OpenCode ask-mode permission rule — pure merge/cleanup logic.
1
+ // The OpenCode client permission rules for the approval roster — pure
2
+ // merge/cleanup logic.
2
3
  //
3
4
  // Purpose: in the ASK approval posture (DEVKIT_APPROVAL_MODE=ask), the
4
- // user's confirmation for an hcloud write is the harness client's own
5
- // permission prompt on the huaweicloud_run_approved_command call — which
6
- // only happens when the client is made to ASK for that tool. Measured on
7
- // opencode 2.2.7: the V2 config key is a top-level `permissions` ARRAY of
8
- // { action, resource, effect } objects; the MCP tool action is
9
- // `<server>_<tool>`, and our server key is `huaweicloud-devkit`, so the
10
- // action is `huaweicloud-devkit_huaweicloud_run_approved_command`; the
11
- // config hot-reloads without restarting opencode; and a `deny` on that
12
- // exact action prunes the tool from the live catalog (restored when the
13
- // deny is removed) — which is also why an allow on it silently removes
14
- // the gate. 2.2.7 still parses the V1 `permission` object the skills-tree
15
- // seam writes (the bundle migrates it), but the array is the documented
16
- // V2 shape — this rule rides ONLY the array form and is gated on opencode
17
- // major >= 2; the V1 seam is untouched.
5
+ // confirmation runs on the SERVER inside the tool call — an elicitation form
6
+ // on opencode 2.x, the T3 chat round-trip on 1.19–1.x (where forms do not
7
+ // exist, so the yield hands the only mechanical client prompt to the
8
+ // round-trip, recorded as posture trust). The client rules are yield-only:
9
+ // one exact `allow` rule per roster tool suppresses the redundant client
10
+ // popup so the server's confirmation is the only prompt. A client rule can
11
+ // therefore no longer fail anything open — the gate confirms every roster
12
+ // call regardless — but a `deny` rule still bricks the call in the client,
13
+ // which is why the doctor keeps deny a FAIL direction.
18
14
  //
19
- // Ownership rules: an entry on the ask action is user-owned by
20
- // construction — add-only-if-absent (a pre-existing entry with ANY effect
21
- // is the user's and survives the write; `skipped` reports it) and
22
- // value-exact deletion (only the exact action + resource '*' + effect
23
- // 'ask' triple is removed at uninstall) are the whole contract. The
24
- // accepted edge is the same one the seam records: a user-authored
25
- // same-shape rule that predates the write is removed together with it.
15
+ // Shape, measured on opencode 2.2.7: the V2 config key is a top-level
16
+ // `permissions` ARRAY of { action, resource, effect } objects; the MCP tool
17
+ // action is `<server>_<tool>` (approval-roster.ts owns the derivation), and
18
+ // the config hot-reloads without restarting opencode. Exact per-tool rules
19
+ // stay the choice over a server-wide wildcard: value-exact uninstall and
20
+ // per-rule doctor verification both need per-tool rows, and a wildcard row is
21
+ // indistinguishable from a user's own. 2.2.7 still parses the V1 `permission`
22
+ // object the skills-tree seam writes (the bundle migrates it), but the V2
23
+ // rule rides ONLY the array form.
26
24
  //
27
- // This module is pure: no fs, no spawn, no console — opencode-config.ts
28
- // owns I/O, the version probe, and logging; tests import these functions
29
- // directly.
25
+ // opencode 1.19.0–1.x alignment (the V1 `permission` object form):
26
+ // source-verified on the v1.19.0 tag — the same version the skills-tree seam
27
+ // measures. mcp/catalog.ts toolName() builds the permission key as
28
+ // sanitize(server) + "_" + sanitize(tool), byte-identical across shapes, so
29
+ // the roster action is shared; permission/index.ts fromConfig() turns a bare
30
+ // string value under a key into { permission, pattern: "*", action: value },
31
+ // and evaluate() is findLast — appending our key last beats any earlier user
32
+ // wildcard, mirroring V2's last-matching-rule-wins. A V1 "Always allow" is
33
+ // session memory, not a persisted grant, so it dies with the process.
34
+ //
35
+ // Ownership rules: an entry on a roster action is user-owned by construction —
36
+ // add-only-if-absent per rule (a pre-existing entry that is anything but our
37
+ // exact allow survives the write; `skipped` reports it by action, so partial
38
+ // coverage is always surfaced) and value-exact deletion (only the
39
+ // devkit-written `allow`/legacy `ask` shapes are removed) are the whole
40
+ // contract. The accepted edge is the same one the seam records: a
41
+ // user-authored same-shape rule that predates the write is removed together
42
+ // with it.
43
+ //
44
+ // Legacy migration: the pre-yield posture wrote effect `ask` on the same
45
+ // action. Every install/update removes those value-exact ask rules in both
46
+ // generations before applying the allow set, so the abandoned posture never
47
+ // survives a path that touches the config.
48
+ //
49
+ // This module is pure: no fs, no spawn, no console — opencode-config.ts owns
50
+ // I/O, the version probe, and logging; tests import these functions directly.
51
+ import { APPROVAL_TOOLS, approvalToolAction } from "../approval-roster.js";
30
52
  import { asRecord } from "./as-record.js";
31
- export const ASK_RULE_ACTION = 'huaweicloud-devkit_huaweicloud_run_approved_command';
32
- export const ASK_RULE_RESOURCE = '*';
53
+ export const PERMISSION_RULE_RESOURCE = '*';
54
+ // Every roster tool's client permission action, derived from the roster leaf
55
+ // so the writer, the uninstaller, and the doctor can never drift.
56
+ export function allowRuleActions() {
57
+ return APPROVAL_TOOLS.map((tool) => approvalToolAction(tool));
58
+ }
33
59
  function isRuleRecord(value) {
34
60
  return value !== null && typeof value === 'object' && !Array.isArray(value);
35
61
  }
36
- // Mutates config in place. Fresh configs get the single-entry array;
37
- // arrays without an entry on the ask action get ours APPENDED — OpenCode
38
- // evaluates last-matching-rule-wins, so the appended entry is the
39
- // effective one. Arrays that already carry an entry on the action, and
40
- // non-array `permissions` shapes, are the user's: nothing is written.
41
- export function applyAskPermissionRule(config) {
62
+ function allowRule(action) {
63
+ return { action, resource: PERMISSION_RULE_RESOURCE, effect: 'allow' };
64
+ }
65
+ // ── V2: the `permissions` array form (opencode 2.0+) ──
66
+ // Mutates config in place. Fresh configs get the N-entry allow set; arrays
67
+ // without an entry on a roster action get that entry APPENDED — OpenCode
68
+ // evaluates last-matching-rule-wins, so the appended entry is the effective
69
+ // one. An action already carrying exactly our rule is the target state (a
70
+ // reinstall is a no-op, never a false "user-owned" warning); an action
71
+ // carrying anything else is the user's and is skipped by name, so the writer
72
+ // never overrides a user's deny/ask or different resource.
73
+ export function applyAllowPermissionRules(config, actions = allowRuleActions()) {
42
74
  if (config.permissions === undefined) {
43
- config.permissions = [{ action: ASK_RULE_ACTION, resource: ASK_RULE_RESOURCE, effect: 'ask' }];
44
- return { changed: true, skipped: false };
75
+ config.permissions = actions.map((action) => allowRule(action));
76
+ return { changed: actions.length > 0, skipped: [], shapeUnreadable: false };
45
77
  }
46
78
  if (!Array.isArray(config.permissions)) {
47
- return { changed: false, skipped: true };
79
+ return { changed: false, skipped: [], shapeUnreadable: true };
48
80
  }
49
81
  const rules = config.permissions;
50
- if (rules.some((rule) => isRuleRecord(rule) && rule.action === ASK_RULE_ACTION)) {
51
- return { changed: false, skipped: true };
82
+ const skipped = [];
83
+ let changed = false;
84
+ for (const action of actions) {
85
+ const matching = rules.filter(isRuleRecord).filter((rule) => rule.action === action);
86
+ if (matching.length > 0) {
87
+ const ours = matching.every((rule) => rule.resource === PERMISSION_RULE_RESOURCE && rule.effect === 'allow');
88
+ if (!ours)
89
+ skipped.push(action);
90
+ continue;
91
+ }
92
+ rules.push(allowRule(action));
93
+ changed = true;
52
94
  }
53
- rules.push({ action: ASK_RULE_ACTION, resource: ASK_RULE_RESOURCE, effect: 'ask' });
54
- return { changed: true, skipped: false };
95
+ return { changed, skipped, shapeUnreadable: false };
55
96
  }
56
97
  // Mutates config in place. Value-exact deletion only — an entry matching
57
- // action + resource '*' + effect 'ask' exactly is ours; a user-modified
58
- // entry (any other effect or resource) survives. The array key is pruned
59
- // only when OUR removals emptied it; a pre-existing empty array is left
60
- // untouched. Returns whether anything changed.
61
- export function removeAskPermissionRule(config) {
98
+ // action + resource '*' + the given effect exactly is ours; a user-modified
99
+ // entry (any other effect or resource) survives. The array key is pruned only
100
+ // when OUR removals emptied it; a pre-existing empty array is left untouched.
101
+ function removeExactRules(config, actions, effect) {
62
102
  if (!Array.isArray(config.permissions))
63
103
  return false;
64
104
  const rules = config.permissions;
65
105
  const kept = rules.filter((rule) => !(isRuleRecord(rule) &&
66
- rule.action === ASK_RULE_ACTION &&
67
- rule.resource === ASK_RULE_RESOURCE &&
68
- rule.effect === 'ask'));
106
+ typeof rule.action === 'string' &&
107
+ actions.includes(rule.action) &&
108
+ rule.resource === PERMISSION_RULE_RESOURCE &&
109
+ rule.effect === effect));
69
110
  if (kept.length === rules.length)
70
111
  return false;
71
112
  if (kept.length === 0) {
@@ -76,41 +117,146 @@ export function removeAskPermissionRule(config) {
76
117
  }
77
118
  return true;
78
119
  }
79
- // The effective posture of the ask action. OpenCode evaluates
80
- // last-matching-rule-wins, so the LAST entry on the action is the
81
- // effective one — read that, never the first. Returns its effect
82
- // ('ask' / 'allow' / 'deny'), 'absent' when no entry matches (or the
83
- // array is empty / the key is missing), and 'foreign' for an unreadable
84
- // posture: `permissions` present but not an array, or the last matching
85
- // entry carrying an effect outside the allow/ask/deny vocabulary.
86
- export function inspectAskPermissionRule(config) {
87
- if (config.permissions === undefined)
88
- return 'absent';
89
- if (!Array.isArray(config.permissions))
90
- return 'foreign';
91
- const rules = config.permissions;
92
- for (let i = rules.length - 1; i >= 0; i--) {
93
- const rule = asRecord(rules[i]);
94
- if (rule.action !== ASK_RULE_ACTION)
120
+ // The client half at uninstall: every devkit-written allow rule, value-exact.
121
+ export function removeAllowPermissionRules(config, actions = allowRuleActions()) {
122
+ return removeExactRules(config, actions, 'allow');
123
+ }
124
+ // The abandoned ask posture, value-exact: migration (install/update) and
125
+ // uninstall both remove it.
126
+ export function removeAskPermissionRules(config, actions = allowRuleActions()) {
127
+ return removeExactRules(config, actions, 'ask');
128
+ }
129
+ // ── V1: the `permission` object form (opencode 1.19.0 – 1.x) ──
130
+ // Mutates config in place. Fresh configs get the N-key allow object; object
131
+ // configs without a roster key get it APPENDED — V1's evaluate() is findLast
132
+ // over the fromConfig() ruleset, and Object.entries preserves insertion
133
+ // order, so the appended key is the effective one. A key already set to
134
+ // 'allow' is the target state (reinstall no-op); any other value is the
135
+ // user's and is skipped by name. A scalar-shaped `permission` (the user's
136
+ // global posture) is never converted.
137
+ export function applyAllowPermissionRulesV1(config, actions = allowRuleActions()) {
138
+ if (config.permission === undefined) {
139
+ config.permission = Object.fromEntries(actions.map((action) => [action, 'allow']));
140
+ return { changed: actions.length > 0, skipped: [], shapeUnreadable: false };
141
+ }
142
+ if (!isRuleRecord(config.permission)) {
143
+ return { changed: false, skipped: [], shapeUnreadable: true };
144
+ }
145
+ const permission = config.permission;
146
+ const skipped = [];
147
+ let changed = false;
148
+ for (const action of actions) {
149
+ const value = permission[action];
150
+ if (value === 'allow')
151
+ continue;
152
+ if (value !== undefined) {
153
+ skipped.push(action);
95
154
  continue;
96
- if (rule.effect === 'ask' || rule.effect === 'allow' || rule.effect === 'deny') {
97
- return rule.effect;
98
155
  }
99
- return 'foreign';
156
+ permission[action] = 'allow';
157
+ changed = true;
100
158
  }
101
- return 'absent';
159
+ return { changed, skipped, shapeUnreadable: false };
102
160
  }
103
- // Floor check for the probe result: the `permissions` array is the
104
- // documented V2 shape, measured on 2.2.7 only. Opencode major >= 2 (the
105
- // anchored `v<major>.` form, mirroring opencodeSeamVersionSupported's
106
- // extract-not-pass-raw polarity); null and unparsable output are
107
- // unsupported — the caller's polarity is skip, keeping BOTH the terminal
108
- // token gate and its mcp env untouched rather than guessing.
161
+ function removeExactKeys(config, actions, effect) {
162
+ if (!isRuleRecord(config.permission))
163
+ return false;
164
+ const permission = config.permission;
165
+ let removed = false;
166
+ for (const action of actions) {
167
+ if (permission[action] === effect) {
168
+ delete permission[action];
169
+ removed = true;
170
+ }
171
+ }
172
+ if (!removed)
173
+ return false;
174
+ if (Object.keys(permission).length === 0)
175
+ delete config.permission;
176
+ return true;
177
+ }
178
+ export function removeAllowPermissionRulesV1(config, actions = allowRuleActions()) {
179
+ return removeExactKeys(config, actions, 'allow');
180
+ }
181
+ export function removeAskPermissionRulesV1(config, actions = allowRuleActions()) {
182
+ return removeExactKeys(config, actions, 'ask');
183
+ }
184
+ export function readPermissionRules(config, actions = allowRuleActions()) {
185
+ if (config.permissions !== undefined && !Array.isArray(config.permissions)) {
186
+ return {
187
+ sectionUnreadable: true,
188
+ rules: actions.map((action) => ({ action, state: 'foreign', askResidue: false })),
189
+ };
190
+ }
191
+ const rules = Array.isArray(config.permissions) ? config.permissions : [];
192
+ return {
193
+ sectionUnreadable: false,
194
+ rules: actions.map((action) => {
195
+ const matching = rules.filter(isRuleRecord).filter((rule) => rule.action === action);
196
+ const askResidue = matching.some((rule) => rule.resource === PERMISSION_RULE_RESOURCE && rule.effect === 'ask');
197
+ // A deny anywhere on the action is a bricked call, whether or not a
198
+ // later allow row currently shadows it for some resources.
199
+ if (matching.some((rule) => rule.effect === 'deny'))
200
+ return { action, state: 'deny', askResidue };
201
+ const exact = matching.filter((rule) => rule.resource === PERMISSION_RULE_RESOURCE);
202
+ const last = exact.at(-1);
203
+ if (last === undefined) {
204
+ return { action, state: matching.length > 0 ? 'user-other' : 'absent', askResidue };
205
+ }
206
+ if (last.effect === 'allow')
207
+ return { action, state: 'allow', askResidue };
208
+ if (last.effect === 'ask')
209
+ return { action, state: 'ask', askResidue };
210
+ return { action, state: 'foreign', askResidue };
211
+ }),
212
+ };
213
+ }
214
+ export function readPermissionRulesV1(config, actions = allowRuleActions()) {
215
+ if (config.permission !== undefined && !isRuleRecord(config.permission)) {
216
+ return {
217
+ sectionUnreadable: true,
218
+ rules: actions.map((action) => ({ action, state: 'foreign', askResidue: false })),
219
+ };
220
+ }
221
+ const permission = asRecord(config.permission);
222
+ return {
223
+ sectionUnreadable: false,
224
+ rules: actions.map((action) => {
225
+ const value = permission[action];
226
+ if (value === undefined)
227
+ return { action, state: 'absent', askResidue: false };
228
+ if (value === 'allow')
229
+ return { action, state: 'allow', askResidue: false };
230
+ if (value === 'ask')
231
+ return { action, state: 'ask', askResidue: true };
232
+ if (value === 'deny')
233
+ return { action, state: 'deny', askResidue: false };
234
+ // A pattern map (or any other value) is not a single-effect posture;
235
+ // the installer never writes one, so it is unverifiable, never ours.
236
+ return { action, state: 'foreign', askResidue: false };
237
+ }),
238
+ };
239
+ }
240
+ // Floor check for the probe result: the `permissions` array is the documented
241
+ // V2 shape, measured on 2.2.7 only. Opencode major >= 2 (the anchored
242
+ // `v<major>.` form, mirroring opencodeSeamVersionSupported's
243
+ // extract-not-pass-raw polarity); null and unparsable output are unsupported
244
+ // — the caller's polarity is skip, keeping BOTH the terminal token gate and
245
+ // its mcp env untouched rather than guessing.
109
246
  export function opencodeAskRuleVersionSupported(version) {
247
+ return askRuleShapeFor(version) === 'v2-array';
248
+ }
249
+ export function askRuleShapeFor(version) {
110
250
  if (version === null)
111
- return false;
112
- const match = /^v?(\d+)\./.exec(version.trim());
251
+ return 'unsupported';
252
+ const match = /^v?(\d+)\.(\d+)\.(\d+)/.exec(version.trim());
113
253
  if (!match)
114
- return false;
115
- return Number(match[1]) >= 2;
254
+ return 'unsupported';
255
+ const major = Number(match[1]);
256
+ const minor = Number(match[2]);
257
+ if (major >= 2)
258
+ return 'v2-array';
259
+ if (major === 1 && minor >= 19)
260
+ return 'v1-object';
261
+ return 'unsupported';
116
262
  }
@@ -0,0 +1,282 @@
1
+ // The opencode saved-permission store reader — DOCTOR HYGIENE ONLY (PR-1.5).
2
+ //
3
+ // Why it exists: opencode persists an ALLOW row for the roster action when a
4
+ // user clicks "Always allow" on the client's prompt (measured on 2.2.7: the
5
+ // MCP tool wrapper asserts `resources: ['*'], save: ['*']`, the reply handler
6
+ // writes those save patterns through the saved-permission store, and
7
+ // `evaluate()` appends the saved rows AFTER the configured rules with
8
+ // findLast). That row used to suppress the client popup the old ask posture
9
+ // trusted. It cannot suppress anything now: the confirmation runs on the
10
+ // server (the approval gate raises an elicitation form, or the T3 chat
11
+ // round-trip), inside the tool call and outside opencode's permission
12
+ // evaluation. The gate NEVER reads this store; the doctor does, and reports a
13
+ // saved row as a stale grant the operator may clean up.
14
+ //
15
+ // What is trusted here: nothing in the store. The database is opened
16
+ // readOnly, only `project`, `permission`, and the optional `worktree`
17
+ // directory map are read (never a blob table), and every failure shape
18
+ // degrades to "no rows" — a missing db is the healthy fresh state, an
19
+ // unreadable or schema-shifted db is warn-only — so an opencode internals
20
+ // change can never brick a diagnostic. Read-under-service is safe: the live
21
+ // store runs WAL, and a readOnly reader takes no write lock (probe-measured
22
+ // against an 805 MB store with the service running).
23
+ //
24
+ // `node:sqlite` is REQUIRED INSIDE the scan, never imported at module scope:
25
+ // this module compiles into the setup-cli boot graph (agents/opencode.ts'
26
+ // doctor), and the builtin is experimental through Node 22.x — the declared
27
+ // floor — so a module-scope load printed its ExperimentalWarning on every CLI
28
+ // run (the officeace-sqlite.ts precedent; test/structure.test.ts pins the
29
+ // shape for every src module, and test/cli-boot-warnings.test.ts pins the
30
+ // behavior on the floor).
31
+ //
32
+ // A row's `action` is a PATTERN, not a literal: opencode matches it with its
33
+ // own wildcard matcher against the requested action, so a hand-edited or
34
+ // older row can be `huaweicloud-devkit_*`. wildcardMatch below mirrors
35
+ // opencode's `util/wildcard.ts`, so the scan asks the question the client
36
+ // asks.
37
+ //
38
+ // The action itself comes from the roster leaf (approval-roster.ts), never a
39
+ // local literal: the roster tuple is the single home of the tool name, and
40
+ // this module must not drift from it.
41
+ import { createHash } from 'node:crypto';
42
+ import { existsSync, readdirSync, realpathSync, statSync } from 'node:fs';
43
+ import { createRequire } from 'node:module';
44
+ import { homedir } from 'node:os';
45
+ import { isAbsolute, join, resolve } from 'node:path';
46
+ import { APPROVAL_TOOLS, approvalToolAction } from "../approval-roster.js";
47
+ /** The permission action opencode namespaces for one roster tool. */
48
+ export function savedAllowAction(tool = APPROVAL_TOOLS[0]) {
49
+ return approvalToolAction(tool);
50
+ }
51
+ /** Every roster tool's permission action (the doctor's inventory set). */
52
+ export function savedAllowActions() {
53
+ return APPROVAL_TOOLS.map((tool) => approvalToolAction(tool));
54
+ }
55
+ // The data root opencode keys its store off: `$XDG_DATA_HOME` when absolute,
56
+ // else `~/.local/share` (opencode's own Global data dir).
57
+ export function opencodeDataDir(env = process.env) {
58
+ const xdg = env.XDG_DATA_HOME;
59
+ const base = xdg !== undefined && xdg !== '' && isAbsolute(xdg) ? xdg : join(homedir(), '.local', 'share');
60
+ return join(base, 'opencode');
61
+ }
62
+ // The exact path opencode resolves, in its own order: OPENCODE_DB wins
63
+ // outright (resolved against the data dir, exactly as the client does), then
64
+ // the channel-named store. The channel name is a build-time constant of the
65
+ // installed binary, so the reader cannot ask for it; it looks the store up
66
+ // instead: the stable `opencode.db` first, then the newest `opencode-<channel>.db`.
67
+ // `opencode-next.db` is excluded on purpose: it is the V1 legacy migration
68
+ // source with a different schema, not this store.
69
+ export function opencodeDbCandidates(env = process.env) {
70
+ const dir = opencodeDataDir(env);
71
+ const override = env.OPENCODE_DB;
72
+ if (override !== undefined && override !== '') {
73
+ if (override === ':memory:')
74
+ return []; // an in-memory store persists nothing
75
+ return [isAbsolute(override) ? override : resolve(dir, override)];
76
+ }
77
+ const stable = join(dir, 'opencode.db');
78
+ const candidates = [stable];
79
+ const channels = readdirOrEmpty(dir)
80
+ .filter((name) => /^opencode-.+\.db$/.test(name) && name !== 'opencode-next.db')
81
+ .map((name) => join(dir, name))
82
+ .sort((a, b) => mtimeMs(b) - mtimeMs(a));
83
+ candidates.push(...channels);
84
+ return candidates;
85
+ }
86
+ function readdirOrEmpty(dir) {
87
+ try {
88
+ return readdirSync(dir);
89
+ }
90
+ catch {
91
+ return []; // no data dir yet
92
+ }
93
+ }
94
+ function mtimeMs(path) {
95
+ try {
96
+ return statSync(path).mtimeMs;
97
+ }
98
+ catch {
99
+ return 0;
100
+ }
101
+ }
102
+ // opencode's `util/wildcard.ts`, mirrored: backslashes normalize to '/', the
103
+ // pattern's regex metacharacters are escaped, `*` becomes `.*` and `?` a
104
+ // single char, and the result is anchored. The trailing-' *' fold (a pattern
105
+ // ending in a space-star also matches the bare prefix) is part of the same
106
+ // matcher, so it is kept.
107
+ export function wildcardMatch(input, pattern) {
108
+ const normalized = input.replaceAll('\\', '/');
109
+ let escaped = pattern
110
+ .replaceAll('\\', '/')
111
+ .replace(/[.+^${}()|[\]\\]/g, '\\$&')
112
+ .replace(/\*/g, '.*')
113
+ .replace(/\?/g, '.');
114
+ if (escaped.endsWith(' .*'))
115
+ escaped = escaped.slice(0, -3) + '( .*)?';
116
+ return new RegExp(`^${escaped}$`, process.platform === 'win32' ? 'si' : 's').test(normalized);
117
+ }
118
+ function readRows(db) {
119
+ const projects = db
120
+ .prepare('SELECT id, worktree FROM project')
121
+ .all()
122
+ .map((row) => ({
123
+ id: typeof row['id'] === 'string' ? row['id'] : '',
124
+ worktree: typeof row['worktree'] === 'string' ? row['worktree'] : null,
125
+ }))
126
+ .filter((row) => row.id !== '');
127
+ const permissions = db
128
+ .prepare('SELECT id, project_id, action, resource FROM permission')
129
+ .all()
130
+ .map((row) => ({
131
+ id: typeof row['id'] === 'string' ? row['id'] : '',
132
+ projectId: typeof row['project_id'] === 'string' ? row['project_id'] : '',
133
+ action: typeof row['action'] === 'string' ? row['action'] : '',
134
+ resource: typeof row['resource'] === 'string' ? row['resource'] : '',
135
+ }))
136
+ .filter((row) => row.id !== '');
137
+ return { projects, directories: readDirectories(db), permissions };
138
+ }
139
+ // The directory -> project map opencode itself resolves a location through
140
+ // (the `worktree` table, which carries a row per directory it has attributed,
141
+ // linked worktrees included). Tolerated, never required: the table is newer
142
+ // than the store, so an older schema answers with the project join alone.
143
+ function readDirectories(db) {
144
+ try {
145
+ return db
146
+ .prepare('SELECT project_id, directory FROM worktree')
147
+ .all()
148
+ .map((row) => ({
149
+ projectId: typeof row['project_id'] === 'string' ? row['project_id'] : '',
150
+ directory: typeof row['directory'] === 'string' ? row['directory'] : '',
151
+ }))
152
+ .filter((row) => row.projectId !== '' && row.directory !== '');
153
+ }
154
+ catch {
155
+ return [];
156
+ }
157
+ }
158
+ function canonical(path) {
159
+ try {
160
+ return realpathSync(path);
161
+ }
162
+ catch {
163
+ return null;
164
+ }
165
+ }
166
+ // The rows whose directory is the one this process runs in. Cheap first pass
167
+ // on resolved spellings (a cwd carrying `..` or a trailing slash); the
168
+ // canonical pass runs only when nothing matched — a symlinked checkout
169
+ // spelling — so the steady-state scan stays string comparisons rather than a
170
+ // realpath sweep over every project row.
171
+ function rowsForDirectory(rows, pathOf, cwd) {
172
+ const target = resolve(cwd);
173
+ const direct = rows.filter((row) => resolve(pathOf(row)) === target);
174
+ if (direct.length > 0)
175
+ return direct;
176
+ const canonicalTarget = canonical(cwd);
177
+ if (canonicalTarget === null)
178
+ return [];
179
+ return rows.filter((row) => canonical(pathOf(row)) === canonicalTarget);
180
+ }
181
+ function sha1(value) {
182
+ return createHash('sha1').update(value).digest('hex');
183
+ }
184
+ // The project ids the current directory belongs to, or null when the join
185
+ // fails (the conservative caller then treats every matching row as the
186
+ // current project's). Three readings, in the order opencode itself attributes
187
+ // a directory: the `project.worktree` join (canonical directory match — this
188
+ // is the one that resolves a plain directory, a git checkout opened at its
189
+ // root, and a clone that shares a project), the `worktree` directory map (the
190
+ // row opencode writes per attributed directory, which is what resolves a
191
+ // linked worktree), then the plain-directory hash `sha1('directory:' + dir)`
192
+ // for a project row neither directory reading can see.
193
+ function resolveProjectIds(projects, directories, cwd) {
194
+ const joined = [
195
+ ...rowsForDirectory(projects, (project) => project.worktree ?? '', cwd).map((project) => project.id),
196
+ ...rowsForDirectory(directories, (row) => row.directory, cwd).map((row) => row.projectId),
197
+ ];
198
+ if (joined.length > 0)
199
+ return [...new Set(joined)];
200
+ const spellings = new Set([cwd, resolve(cwd)]);
201
+ const canonicalCwd = canonical(cwd);
202
+ if (canonicalCwd !== null)
203
+ spellings.add(canonicalCwd);
204
+ const hashed = new Set([...spellings].map((spelling) => sha1(`directory:${spelling}`)));
205
+ const matched = projects.filter((project) => hashed.has(project.id)).map((project) => project.id);
206
+ return matched.length > 0 ? matched : null;
207
+ }
208
+ function toRows(matched, projects) {
209
+ const worktrees = new Map(projects.map((project) => [project.id, project.worktree]));
210
+ return matched.map((row) => ({
211
+ id: row.id,
212
+ projectId: row.projectId,
213
+ projectWorktree: worktrees.get(row.projectId) ?? null,
214
+ action: row.action,
215
+ resource: row.resource,
216
+ }));
217
+ }
218
+ function loadDatabaseSync() {
219
+ const sqlite = createRequire(import.meta.url)('node:sqlite');
220
+ const ctor = sqlite.DatabaseSync;
221
+ if (ctor === undefined) {
222
+ throw new Error('node:sqlite is unavailable; the saved-permission scan requires Node.js >= 22.19');
223
+ }
224
+ return ctor;
225
+ }
226
+ function scanFile(dbPath, options) {
227
+ const actions = options.actions ?? savedAllowActions();
228
+ let db;
229
+ try {
230
+ db = new (loadDatabaseSync())(dbPath, { readOnly: true });
231
+ }
232
+ catch (error) {
233
+ return { status: 'unreadable', dbPath, detail: errorMessage(error) };
234
+ }
235
+ try {
236
+ // A writer holding the store must not turn a read into an instant
237
+ // SQLITE_BUSY (or a stall): the read is bounded, and a busy store still
238
+ // reads as warn-only below, never as a refusal.
239
+ db.exec('PRAGMA busy_timeout = 500');
240
+ const { projects, directories, permissions } = readRows(db);
241
+ const matching = permissions.filter((row) => actions.some((action) => wildcardMatch(action, row.action)));
242
+ if (options.scope === 'all') {
243
+ return { status: 'ok', dbPath, scope: 'all', rows: toRows(matching, projects) };
244
+ }
245
+ const projectIds = resolveProjectIds(projects, directories, options.cwd ?? process.cwd());
246
+ if (projectIds === null) {
247
+ return { status: 'ok', dbPath, scope: 'any-project', rows: toRows(matching, projects) };
248
+ }
249
+ const scoped = matching.filter((row) => projectIds.includes(row.projectId));
250
+ return { status: 'ok', dbPath, scope: 'project', rows: toRows(scoped, projects) };
251
+ }
252
+ catch (error) {
253
+ // A schema shift, a corrupt file, a locked table: warn-only by contract.
254
+ return { status: 'unreadable', dbPath, detail: errorMessage(error) };
255
+ }
256
+ finally {
257
+ db.close();
258
+ }
259
+ }
260
+ function errorMessage(error) {
261
+ return error instanceof Error ? error.message : String(error);
262
+ }
263
+ /**
264
+ * Read the saved-permission store for allow rows covering one of `actions`
265
+ * (default: every roster tool's action), under the scope the caller asks for.
266
+ * Missing db reads as `absent` (pass); every read failure reads as
267
+ * `unreadable` (warn-only). Never writes.
268
+ */
269
+ export function scanSavedAllowRows(options) {
270
+ const env = options.env ?? process.env;
271
+ const candidates = opencodeDbCandidates(env);
272
+ if (candidates.length === 0)
273
+ return { status: 'absent', dbPath: '' };
274
+ const existing = candidates.find((candidate) => existsSync(candidate));
275
+ if (existing === undefined)
276
+ return { status: 'absent', dbPath: candidates[0] };
277
+ return scanFile(existing, options);
278
+ }
279
+ /** The db path a scan resolved without touching the file (for messages). */
280
+ export function opencodeDbPath(env = process.env) {
281
+ return opencodeDbCandidates(env)[0] ?? '';
282
+ }