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
@@ -0,0 +1,354 @@
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
+
47
+ import { APPROVAL_TOOLS, approvalToolAction } from '../approval-roster.ts';
48
+
49
+ /** One saved permission row, already matched as an allow for the action. */
50
+ export interface SavedAllowRow {
51
+ id: string;
52
+ projectId: string;
53
+ /** The project's canonical worktree, or null when the project row is gone. */
54
+ projectWorktree: string | null;
55
+ action: string;
56
+ resource: string;
57
+ }
58
+
59
+ /**
60
+ * The scan outcome. `absent` is the healthy fresh state (no store, nothing to
61
+ * refuse); `unreadable` is the warn-only degradation (a store we could not
62
+ * read must never fail the call); `ok` carries the rows the caller asked for
63
+ * under one of three scopes:
64
+ * - `project` the current project resolved, so only its rows are here;
65
+ * - `any-project` the project join failed, so EVERY matching row is here
66
+ * (the conservative fallback: a saved allow that cannot be
67
+ * attributed to another project is still a saved allow);
68
+ * - `all` the inventory scope (doctor), every matching row.
69
+ */
70
+ export type SavedAllowScan =
71
+ | { status: 'absent'; dbPath: string }
72
+ | { status: 'unreadable'; dbPath: string; detail: string }
73
+ | { status: 'ok'; dbPath: string; scope: 'project' | 'any-project' | 'all'; rows: SavedAllowRow[] };
74
+
75
+ export interface SavedAllowScanOptions {
76
+ /** 'project' is the gate's question; 'all' is the doctor's inventory. */
77
+ scope: 'project' | 'all';
78
+ /** The permission actions to match; defaults to every roster tool's action. */
79
+ actions?: readonly string[];
80
+ env?: NodeJS.ProcessEnv;
81
+ /** The directory the MCP server was spawned in (the opencode instance's project directory). */
82
+ cwd?: string;
83
+ }
84
+
85
+ /** The permission action opencode namespaces for one roster tool. */
86
+ export function savedAllowAction(tool: string = APPROVAL_TOOLS[0]): string {
87
+ return approvalToolAction(tool);
88
+ }
89
+
90
+ /** Every roster tool's permission action (the doctor's inventory set). */
91
+ export function savedAllowActions(): string[] {
92
+ return APPROVAL_TOOLS.map((tool) => approvalToolAction(tool));
93
+ }
94
+
95
+ // The data root opencode keys its store off: `$XDG_DATA_HOME` when absolute,
96
+ // else `~/.local/share` (opencode's own Global data dir).
97
+ export function opencodeDataDir(env: NodeJS.ProcessEnv = process.env): string {
98
+ const xdg = env.XDG_DATA_HOME;
99
+ const base = xdg !== undefined && xdg !== '' && isAbsolute(xdg) ? xdg : join(homedir(), '.local', 'share');
100
+ return join(base, 'opencode');
101
+ }
102
+
103
+ // The exact path opencode resolves, in its own order: OPENCODE_DB wins
104
+ // outright (resolved against the data dir, exactly as the client does), then
105
+ // the channel-named store. The channel name is a build-time constant of the
106
+ // installed binary, so the reader cannot ask for it; it looks the store up
107
+ // instead: the stable `opencode.db` first, then the newest `opencode-<channel>.db`.
108
+ // `opencode-next.db` is excluded on purpose: it is the V1 legacy migration
109
+ // source with a different schema, not this store.
110
+ export function opencodeDbCandidates(env: NodeJS.ProcessEnv = process.env): string[] {
111
+ const dir = opencodeDataDir(env);
112
+ const override = env.OPENCODE_DB;
113
+ if (override !== undefined && override !== '') {
114
+ if (override === ':memory:') return []; // an in-memory store persists nothing
115
+ return [isAbsolute(override) ? override : resolve(dir, override)];
116
+ }
117
+ const stable = join(dir, 'opencode.db');
118
+ const candidates = [stable];
119
+ const channels = readdirOrEmpty(dir)
120
+ .filter((name) => /^opencode-.+\.db$/.test(name) && name !== 'opencode-next.db')
121
+ .map((name) => join(dir, name))
122
+ .sort((a, b) => mtimeMs(b) - mtimeMs(a));
123
+ candidates.push(...channels);
124
+ return candidates;
125
+ }
126
+
127
+ function readdirOrEmpty(dir: string): string[] {
128
+ try {
129
+ return readdirSync(dir);
130
+ } catch {
131
+ return []; // no data dir yet
132
+ }
133
+ }
134
+
135
+ function mtimeMs(path: string): number {
136
+ try {
137
+ return statSync(path).mtimeMs;
138
+ } catch {
139
+ return 0;
140
+ }
141
+ }
142
+
143
+ // opencode's `util/wildcard.ts`, mirrored: backslashes normalize to '/', the
144
+ // pattern's regex metacharacters are escaped, `*` becomes `.*` and `?` a
145
+ // single char, and the result is anchored. The trailing-' *' fold (a pattern
146
+ // ending in a space-star also matches the bare prefix) is part of the same
147
+ // matcher, so it is kept.
148
+ export function wildcardMatch(input: string, pattern: string): boolean {
149
+ const normalized = input.replaceAll('\\', '/');
150
+ let escaped = pattern
151
+ .replaceAll('\\', '/')
152
+ .replace(/[.+^${}()|[\]\\]/g, '\\$&')
153
+ .replace(/\*/g, '.*')
154
+ .replace(/\?/g, '.');
155
+ if (escaped.endsWith(' .*')) escaped = escaped.slice(0, -3) + '( .*)?';
156
+ return new RegExp(`^${escaped}$`, process.platform === 'win32' ? 'si' : 's').test(normalized);
157
+ }
158
+
159
+ interface ProjectRow {
160
+ id: string;
161
+ worktree: string | null;
162
+ }
163
+
164
+ interface PermissionRow {
165
+ id: string;
166
+ projectId: string;
167
+ action: string;
168
+ resource: string;
169
+ }
170
+
171
+ interface DirectoryRow {
172
+ projectId: string;
173
+ directory: string;
174
+ }
175
+
176
+ function readRows(db: SqliteDatabase): {
177
+ projects: ProjectRow[];
178
+ directories: DirectoryRow[];
179
+ permissions: PermissionRow[];
180
+ } {
181
+ const projects = db
182
+ .prepare('SELECT id, worktree FROM project')
183
+ .all()
184
+ .map((row) => ({
185
+ id: typeof row['id'] === 'string' ? row['id'] : '',
186
+ worktree: typeof row['worktree'] === 'string' ? row['worktree'] : null,
187
+ }))
188
+ .filter((row) => row.id !== '');
189
+ const permissions = db
190
+ .prepare('SELECT id, project_id, action, resource FROM permission')
191
+ .all()
192
+ .map((row) => ({
193
+ id: typeof row['id'] === 'string' ? row['id'] : '',
194
+ projectId: typeof row['project_id'] === 'string' ? row['project_id'] : '',
195
+ action: typeof row['action'] === 'string' ? row['action'] : '',
196
+ resource: typeof row['resource'] === 'string' ? row['resource'] : '',
197
+ }))
198
+ .filter((row) => row.id !== '');
199
+ return { projects, directories: readDirectories(db), permissions };
200
+ }
201
+
202
+ // The directory -> project map opencode itself resolves a location through
203
+ // (the `worktree` table, which carries a row per directory it has attributed,
204
+ // linked worktrees included). Tolerated, never required: the table is newer
205
+ // than the store, so an older schema answers with the project join alone.
206
+ function readDirectories(db: SqliteDatabase): DirectoryRow[] {
207
+ try {
208
+ return db
209
+ .prepare('SELECT project_id, directory FROM worktree')
210
+ .all()
211
+ .map((row) => ({
212
+ projectId: typeof row['project_id'] === 'string' ? row['project_id'] : '',
213
+ directory: typeof row['directory'] === 'string' ? row['directory'] : '',
214
+ }))
215
+ .filter((row) => row.projectId !== '' && row.directory !== '');
216
+ } catch {
217
+ return [];
218
+ }
219
+ }
220
+
221
+ function canonical(path: string): string | null {
222
+ try {
223
+ return realpathSync(path);
224
+ } catch {
225
+ return null;
226
+ }
227
+ }
228
+
229
+ // The rows whose directory is the one this process runs in. Cheap first pass
230
+ // on resolved spellings (a cwd carrying `..` or a trailing slash); the
231
+ // canonical pass runs only when nothing matched — a symlinked checkout
232
+ // spelling — so the steady-state scan stays string comparisons rather than a
233
+ // realpath sweep over every project row.
234
+ function rowsForDirectory<T>(rows: T[], pathOf: (row: T) => string, cwd: string): T[] {
235
+ const target = resolve(cwd);
236
+ const direct = rows.filter((row) => resolve(pathOf(row)) === target);
237
+ if (direct.length > 0) return direct;
238
+ const canonicalTarget = canonical(cwd);
239
+ if (canonicalTarget === null) return [];
240
+ return rows.filter((row) => canonical(pathOf(row)) === canonicalTarget);
241
+ }
242
+
243
+ function sha1(value: string): string {
244
+ return createHash('sha1').update(value).digest('hex');
245
+ }
246
+
247
+ // The project ids the current directory belongs to, or null when the join
248
+ // fails (the conservative caller then treats every matching row as the
249
+ // current project's). Three readings, in the order opencode itself attributes
250
+ // a directory: the `project.worktree` join (canonical directory match — this
251
+ // is the one that resolves a plain directory, a git checkout opened at its
252
+ // root, and a clone that shares a project), the `worktree` directory map (the
253
+ // row opencode writes per attributed directory, which is what resolves a
254
+ // linked worktree), then the plain-directory hash `sha1('directory:' + dir)`
255
+ // for a project row neither directory reading can see.
256
+ function resolveProjectIds(projects: ProjectRow[], directories: DirectoryRow[], cwd: string): string[] | null {
257
+ const joined = [
258
+ ...rowsForDirectory(projects, (project) => project.worktree ?? '', cwd).map((project) => project.id),
259
+ ...rowsForDirectory(directories, (row) => row.directory, cwd).map((row) => row.projectId),
260
+ ];
261
+ if (joined.length > 0) return [...new Set(joined)];
262
+ const spellings = new Set([cwd, resolve(cwd)]);
263
+ const canonicalCwd = canonical(cwd);
264
+ if (canonicalCwd !== null) spellings.add(canonicalCwd);
265
+ const hashed = new Set([...spellings].map((spelling) => sha1(`directory:${spelling}`)));
266
+ const matched = projects.filter((project) => hashed.has(project.id)).map((project) => project.id);
267
+ return matched.length > 0 ? matched : null;
268
+ }
269
+
270
+ function toRows(matched: PermissionRow[], projects: ProjectRow[]): SavedAllowRow[] {
271
+ const worktrees = new Map(projects.map((project) => [project.id, project.worktree]));
272
+ return matched.map((row) => ({
273
+ id: row.id,
274
+ projectId: row.projectId,
275
+ projectWorktree: worktrees.get(row.projectId) ?? null,
276
+ action: row.action,
277
+ resource: row.resource,
278
+ }));
279
+ }
280
+
281
+ // The builtin, loaded on demand (see the header): the doctor is the only
282
+ // consumer, and the CLI's boot graph must not import the experimental module.
283
+ interface SqliteDatabase {
284
+ exec(sql: string): void;
285
+ prepare(sql: string): { all(): Array<Record<string, unknown>> };
286
+ close(): void;
287
+ }
288
+
289
+ type SqliteCtor = new (path: string, options: { readOnly?: boolean }) => SqliteDatabase;
290
+
291
+ function loadDatabaseSync(): SqliteCtor {
292
+ const sqlite = createRequire(import.meta.url)('node:sqlite') as { DatabaseSync?: SqliteCtor };
293
+ const ctor = sqlite.DatabaseSync;
294
+ if (ctor === undefined) {
295
+ throw new Error('node:sqlite is unavailable; the saved-permission scan requires Node.js >= 22.19');
296
+ }
297
+ return ctor;
298
+ }
299
+
300
+ function scanFile(dbPath: string, options: SavedAllowScanOptions): SavedAllowScan {
301
+ const actions = options.actions ?? savedAllowActions();
302
+ let db: SqliteDatabase;
303
+ try {
304
+ db = new (loadDatabaseSync())(dbPath, { readOnly: true });
305
+ } catch (error) {
306
+ return { status: 'unreadable', dbPath, detail: errorMessage(error) };
307
+ }
308
+ try {
309
+ // A writer holding the store must not turn a read into an instant
310
+ // SQLITE_BUSY (or a stall): the read is bounded, and a busy store still
311
+ // reads as warn-only below, never as a refusal.
312
+ db.exec('PRAGMA busy_timeout = 500');
313
+ const { projects, directories, permissions } = readRows(db);
314
+ const matching = permissions.filter((row) => actions.some((action) => wildcardMatch(action, row.action)));
315
+ if (options.scope === 'all') {
316
+ return { status: 'ok', dbPath, scope: 'all', rows: toRows(matching, projects) };
317
+ }
318
+ const projectIds = resolveProjectIds(projects, directories, options.cwd ?? process.cwd());
319
+ if (projectIds === null) {
320
+ return { status: 'ok', dbPath, scope: 'any-project', rows: toRows(matching, projects) };
321
+ }
322
+ const scoped = matching.filter((row) => projectIds.includes(row.projectId));
323
+ return { status: 'ok', dbPath, scope: 'project', rows: toRows(scoped, projects) };
324
+ } catch (error) {
325
+ // A schema shift, a corrupt file, a locked table: warn-only by contract.
326
+ return { status: 'unreadable', dbPath, detail: errorMessage(error) };
327
+ } finally {
328
+ db.close();
329
+ }
330
+ }
331
+
332
+ function errorMessage(error: unknown): string {
333
+ return error instanceof Error ? error.message : String(error);
334
+ }
335
+
336
+ /**
337
+ * Read the saved-permission store for allow rows covering one of `actions`
338
+ * (default: every roster tool's action), under the scope the caller asks for.
339
+ * Missing db reads as `absent` (pass); every read failure reads as
340
+ * `unreadable` (warn-only). Never writes.
341
+ */
342
+ export function scanSavedAllowRows(options: SavedAllowScanOptions): SavedAllowScan {
343
+ const env = options.env ?? process.env;
344
+ const candidates = opencodeDbCandidates(env);
345
+ if (candidates.length === 0) return { status: 'absent', dbPath: '' };
346
+ const existing = candidates.find((candidate) => existsSync(candidate));
347
+ if (existing === undefined) return { status: 'absent', dbPath: candidates[0]! };
348
+ return scanFile(existing, options);
349
+ }
350
+
351
+ /** The db path a scan resolved without touching the file (for messages). */
352
+ export function opencodeDbPath(env: NodeJS.ProcessEnv = process.env): string {
353
+ return opencodeDbCandidates(env)[0] ?? '';
354
+ }
@@ -0,0 +1,129 @@
1
+ // The shared display-redaction leaf. Two passes live here, one canonical home
2
+ // each:
3
+ // 1. the secret-TOKEN FOLD — the argv/string fold that hides secret VALUES
4
+ // from every display and store surface (the run face's pin view, the
5
+ // sandbox exec views, the approval token store's argsRedacted, the
6
+ // trace). The fold's primitives were born in hcloud-plan.ts for the
7
+ // run face's pin view; PR-3a round 3 moved them HERE because the exec
8
+ // face and the token store need the same fold and cannot import the
9
+ // face (approval-tokens ← hcloud-cli would be a value cycle). One
10
+ // fold, every consumer; the classification engines see the RAW
11
+ // command always — this leaf is for display and persistence only.
12
+ // 2. the supplemental-key denylist (api_key/apiKey/value) — object-shaped
13
+ // secrets redactSecrets alone never covered.
14
+ const SUPPLEMENTAL_SECRET_KEYS = new Set(['api_key', 'apikey', 'value']);
15
+
16
+ // The secret key families (the run face's exact vocabulary, kept verbatim):
17
+ // unanchored inside a token (redactSecrets folds `password=` inside
18
+ // `--dbpassword=` the same way), with AK/SK boundary-anchored.
19
+ const SECRET_KEY_ALT =
20
+ 'access[_-]?key(?:[_-]?(?:id|secret))?|secret[_-]?key|secret[_-]?string|secret[_-]?binary|security[_-]?token|x[_-]?auth[_-]?token|token|password|passwd|admin[_-]?pass|credential|input[_-]?value|user[_-]?data|metadata|private[_-]?key|authorization';
21
+ // A bare key token (`--password`, `--server.adminPass`, `--dbpassword`): the
22
+ // value rides the NEXT argv element. The optional prefix must end on a
23
+ // separator char, or `--task` would parse as the SK key token.
24
+ export const SECRET_KEY_TOKEN_RE = new RegExp('^(?:--?[A-Za-z0-9_.-]*[._-])?(?:' + SECRET_KEY_ALT + '|AK|SK)$', 'i');
25
+ // Shared key+separator scanner: ONE global split drives every consumer. The
26
+ // value segment of a key runs to the NEXT key occurrence — a multi-key body
27
+ // yields one segment per key.
28
+ const SECRET_KEY_SEP_RE = new RegExp(
29
+ '((?:(?:' + SECRET_KEY_ALT + ')|\\b(?:AK|SK))["\'\\\\]*\\s*(?:[=:]|\\s|(?=["\']))\\s*)',
30
+ 'gi',
31
+ );
32
+
33
+ export function secretSegments(arg: string): Array<{ sep: string; value: string }> {
34
+ const parts = String(arg).split(SECRET_KEY_SEP_RE);
35
+ const segments: Array<{ sep: string; value: string }> = [];
36
+ for (let i = 1; i < parts.length; i += 2) {
37
+ segments.push({ sep: parts[i] ?? '', value: parts[i + 1] ?? '' });
38
+ }
39
+ return segments;
40
+ }
41
+
42
+ // The canonical argv fold (the run face's pin view, verbatim): a string
43
+ // token the scanner sees a secret key in has every value segment folded to
44
+ // `<redacted>` while the STRUCTURE (flag names, key names, non-secret
45
+ // prefix) survives, and a bare key token folds the value riding the next
46
+ // element. A chained bare key (`--password --token x`) is left for its own
47
+ // iteration so no real value hides behind the skip. Mixed arrays are safe:
48
+ // non-string elements pass through untouched at their position, so object
49
+ // payloads (the tunnel faces' arrays) never coerce.
50
+ export function foldSecretTokens(args: readonly unknown[]): unknown[] {
51
+ const out: unknown[] = [];
52
+ for (let i = 0; i < args.length; i += 1) {
53
+ const raw = args[i];
54
+ if (typeof raw !== 'string' && typeof raw !== 'number') {
55
+ out.push(raw);
56
+ continue;
57
+ }
58
+ const arg = String(raw);
59
+ const segments = secretSegments(arg);
60
+ if (segments.length > 0) {
61
+ const parts = String(arg).split(SECRET_KEY_SEP_RE);
62
+ let folded = parts[0] ?? '';
63
+ for (let j = 1; j < parts.length; j += 2) {
64
+ folded += parts[j] + '<redacted>';
65
+ }
66
+ out.push(folded);
67
+ continue;
68
+ }
69
+ const nextRaw = i + 1 < args.length ? args[i + 1] : undefined;
70
+ // Narrow before String(): only string- and number-shaped elements can
71
+ // be a bare key's value token — anything else (objects, arrays) is not
72
+ // a shell word and passes through untouched, and Object's default
73
+ // stringification never enters the fold.
74
+ const next: string | undefined =
75
+ typeof nextRaw === 'string' || typeof nextRaw === 'number' ? String(nextRaw) : undefined;
76
+ if (SECRET_KEY_TOKEN_RE.test(arg) && next !== undefined && !SECRET_KEY_TOKEN_RE.test(next)) {
77
+ out.push(arg, '<redacted>');
78
+ i += 1;
79
+ continue;
80
+ }
81
+ out.push(raw);
82
+ }
83
+ return out;
84
+ }
85
+
86
+ // The string twin of the argv fold: whitespace-split a command string into
87
+ // its words, fold the same way, rejoin. The word approximation is the
88
+ // documented residual: a quoted value containing spaces folds only its
89
+ // first word (the same space-bearing-value partial-redaction class the
90
+ // run face records).
91
+ export function foldSecretTokensInString(text: string): string {
92
+ return (foldSecretTokens(text.split(/\s+/)) as string[]).join(' ');
93
+ }
94
+
95
+ // THE COMPOSITION RULE (one statement, every consumer): a display or store
96
+ // surface redacts by composing `redactSecrets(value)` FIRST (the engine's
97
+ // glued key=value/key:value folds) and `redactWithSupplementalKeys(...)`
98
+ // SECOND (the supplemental key denylist plus the two-token fold). There is
99
+ // deliberately no helper wrapping the pair: the consumers run it on whole
100
+ // argv arrays and object bindings (values redactSecrets alone mishandles),
101
+ // so a string-only helper was a zero-call-site lie the round-4 seat caught.
102
+ // redactSecrets's import stays — it is the first half of the composition
103
+ // the callers name at their sites.
104
+
105
+ export function redactWithSupplementalKeys(value: unknown): unknown {
106
+ if (typeof value === 'string') {
107
+ // The two-token secret form (`--password hunter2`) folds on the string
108
+ // leaf every display/store consumer routes through: the glued forms
109
+ // fold earlier via redactSecrets (the callers compose this leaf after
110
+ // it), the cross-word forms here (interrogate round 3, F1 — reproduced
111
+ // on every surface by both seats and the root).
112
+ return foldSecretTokensInString(value);
113
+ }
114
+ if (Array.isArray(value)) {
115
+ // The array fold is pairwise: adjacent elements carry the bare key
116
+ // token and its value (the run face's argv shape), so recursion alone
117
+ // could never catch the pair.
118
+ return foldSecretTokens(value.map((item) => redactWithSupplementalKeys(item)));
119
+ }
120
+ if (value && typeof value === 'object') {
121
+ return Object.fromEntries(
122
+ Object.entries(value as Record<string, unknown>).map(([key, val]) => [
123
+ key,
124
+ SUPPLEMENTAL_SECRET_KEYS.has(key.toLowerCase()) ? '<redacted>' : redactWithSupplementalKeys(val),
125
+ ]),
126
+ );
127
+ }
128
+ return value;
129
+ }
@@ -70,6 +70,46 @@ export const gitConfig = z.looseObject({
70
70
  open_type: z.string().optional(),
71
71
  });
72
72
 
73
+ // The shared approval-gate parameters, declared once for every roster tool
74
+ // the gate covers (the hcloud run face today; the PR-3 pack registrations
75
+ // join by spreading the same parts into their schemas). Both are optional
76
+ // in the schema ON PURPOSE, same doctrine as vendorConfirmed: a missing
77
+ // value must reach callTool's gate, which owns the refusal teaching —
78
+ // SDK-level required-field rejects would silence the consent instruction.
79
+ // The gate, not zod, is the enforcement.
80
+ export const approvalTokenArg = z
81
+ .string()
82
+ .optional()
83
+ .describe(
84
+ "Required in token-approval mode (from the minting face — the plan tool, or the approval gate's USER_CONFIRMATION_REQUIRED envelope); omit in ask mode, where the server-run gate confirms at run time.",
85
+ );
86
+
87
+ // Optional in the schema for the same reason: in token mode the gate throws
88
+ // the teaching rejection when it is absent, and in ask mode the server-run
89
+ // confirmation owns the gate — the first arrival has no attestation yet (the
90
+ // chat round-trip envelope asks for it), so a required field here would kill
91
+ // the T3 flow in SDK validation before the gate ever saw it.
92
+ export const approvedByUserArg = booleanArg
93
+ .optional()
94
+ .describe(
95
+ 'Must be true only after the user explicitly approves this exact call. In token mode the gate requires it; in ask mode the server-run confirmation asks the user itself, and this flag is the chat round-trip retry marker (posture trust) when the client cannot render a form.',
96
+ );
97
+
98
+ // The confirm-language hint, injected on every roster tool by
99
+ // src/tool-schemas.ts (the approval domain's parameter, not any pack's).
100
+ // The model relays the user's conversation language so the human-facing
101
+ // confirmation form renders its display text in it — the MCP server never
102
+ // sees the chat, so the model is the only context observer. Optional and
103
+ // soft-failing by design (lib/confirm-language.ts): an unrecognized value
104
+ // falls through to the operator's DEVKIT_CONFIRM_LANG pin, then the machine
105
+ // locale; the enum VALUES and every refusal stay English in both languages.
106
+ export const confirmLanguageArg = z
107
+ .string()
108
+ .optional()
109
+ .describe(
110
+ "Optional: the user's conversation language, 'zh' (Chinese) or 'en' — the approval confirmation form renders its display text in that language.",
111
+ );
112
+
73
113
  export const workspaceId = z
74
114
  .string()
75
115
  .optional()