huaweicloud-devkit 2.0.0-next.0 → 2.0.0-next.2

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 (62) hide show
  1. package/README.md +2 -0
  2. package/package.json +1 -1
  3. package/plugins/huaweicloud-core/.claude-plugin/plugin.json +1 -1
  4. package/plugins/huaweicloud-core/.codex-plugin/plugin.json +1 -1
  5. package/plugins/huaweicloud-core/.cursor-plugin/plugin.json +1 -1
  6. package/plugins/huaweicloud-core/.hermes-plugin/plugin.json +1 -1
  7. package/plugins/huaweicloud-core/.workbuddy-plugin/plugin.json +1 -1
  8. package/plugins/huaweicloud-core/dist/agents/codearts-work.js +4 -0
  9. package/plugins/huaweicloud-core/dist/agents/codearts.js +4 -0
  10. package/plugins/huaweicloud-core/dist/agents/officeace-sqlite.js +14 -4
  11. package/plugins/huaweicloud-core/dist/agents/opencode-config.js +5 -1
  12. package/plugins/huaweicloud-core/dist/approvals-cli.js +159 -0
  13. package/plugins/huaweicloud-core/dist/auth/s1-store.js +43 -22
  14. package/plugins/huaweicloud-core/dist/hcloud-plan.js +26 -4
  15. package/plugins/huaweicloud-core/dist/hcloud-run.js +4 -1
  16. package/plugins/huaweicloud-core/dist/lib/approval-tokens.js +135 -16
  17. package/plugins/huaweicloud-core/dist/lib/approvals-pin.js +128 -0
  18. package/plugins/huaweicloud-core/dist/lib/pack-state.js +23 -19
  19. package/plugins/huaweicloud-core/dist/lib/param-warnings.js +70 -0
  20. package/plugins/huaweicloud-core/dist/lib/state-dir.js +125 -0
  21. package/plugins/huaweicloud-core/dist/mcp-server.js +877 -595
  22. package/plugins/huaweicloud-core/dist/mcp-server.js.map +4 -4
  23. package/plugins/huaweicloud-core/dist/packs/huaweicloud-cli/tools.js +27 -9
  24. package/plugins/huaweicloud-core/dist/payload-runtime-deps.js +11 -3
  25. package/plugins/huaweicloud-core/dist/safety/classify-text.js +13 -0
  26. package/plugins/huaweicloud-core/dist/safety/policy.js +1 -0
  27. package/plugins/huaweicloud-core/dist/setup-cli.js +23 -0
  28. package/plugins/huaweicloud-core/dist/tool-schemas.js +15 -0
  29. package/plugins/huaweicloud-core/dist/tools.js +36 -4
  30. package/plugins/huaweicloud-core/dist/update-registry.js +8 -2
  31. package/plugins/huaweicloud-core/dist/update-skip.js +5 -6
  32. package/plugins/huaweicloud-core/dist/update-upgrade.js +8 -1
  33. package/plugins/huaweicloud-core/hooks/huaweicloud-safety.py +20 -1
  34. package/plugins/huaweicloud-core/openclaw.plugin.json +1 -1
  35. package/plugins/huaweicloud-core/safety/policy.json +8 -0
  36. package/plugins/huaweicloud-core/safety/rules/cloud-risk-rules.json +78 -2
  37. package/plugins/huaweicloud-core/skills/huaweicloud-cli-and-auth/SKILL.md +4 -1
  38. package/plugins/huaweicloud-core/skills/huaweicloud-safety/SKILL.md +13 -6
  39. package/plugins/huaweicloud-core/skills/huaweicloud-safety/references/approvals.md +47 -0
  40. package/plugins/huaweicloud-core/src/agents/codearts-work.ts +3 -0
  41. package/plugins/huaweicloud-core/src/agents/codearts.ts +4 -0
  42. package/plugins/huaweicloud-core/src/agents/officeace-sqlite.ts +14 -4
  43. package/plugins/huaweicloud-core/src/agents/opencode-config.ts +5 -1
  44. package/plugins/huaweicloud-core/src/approvals-cli.ts +187 -0
  45. package/plugins/huaweicloud-core/src/auth/s1-store.ts +41 -20
  46. package/plugins/huaweicloud-core/src/hcloud-plan.ts +44 -5
  47. package/plugins/huaweicloud-core/src/hcloud-run.ts +4 -1
  48. package/plugins/huaweicloud-core/src/lib/approval-tokens.ts +197 -16
  49. package/plugins/huaweicloud-core/src/lib/approvals-pin.ts +153 -0
  50. package/plugins/huaweicloud-core/src/lib/pack-state.ts +23 -20
  51. package/plugins/huaweicloud-core/src/lib/param-warnings.ts +69 -0
  52. package/plugins/huaweicloud-core/src/lib/state-dir.ts +128 -0
  53. package/plugins/huaweicloud-core/src/packs/huaweicloud-cli/tools.ts +29 -9
  54. package/plugins/huaweicloud-core/src/payload-runtime-deps.ts +11 -3
  55. package/plugins/huaweicloud-core/src/safety/classify-text.ts +15 -0
  56. package/plugins/huaweicloud-core/src/safety/policy.ts +2 -0
  57. package/plugins/huaweicloud-core/src/setup-cli.ts +28 -0
  58. package/plugins/huaweicloud-core/src/tool-schemas.ts +16 -0
  59. package/plugins/huaweicloud-core/src/tools.ts +39 -4
  60. package/plugins/huaweicloud-core/src/update-registry.ts +8 -2
  61. package/plugins/huaweicloud-core/src/update-skip.ts +5 -6
  62. package/plugins/huaweicloud-core/src/update-upgrade.ts +8 -1
@@ -1,11 +1,12 @@
1
- import { createHash, randomUUID } from 'node:crypto';
1
+ import { createHash, createHmac, randomUUID, timingSafeEqual } from 'node:crypto';
2
2
  import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, statSync, unlinkSync, writeFileSync, } from 'node:fs';
3
3
  import { dirname, join } from 'node:path';
4
4
  import { redactSecrets } from "../safety-policy.js";
5
- import { huaweiConfigBase } from "./pack-state.js";
5
+ import { ensureMasterKey, resolveMasterKey } from "./secret-vault/custody.js";
6
+ import { devkitStateBase } from "./pack-state.js";
6
7
  const APPROVAL_TTL_MS = 5 * 60_000;
7
8
  function approvalFilePath() {
8
- return join(huaweiConfigBase(), 'approvals.json');
9
+ return join(devkitStateBase(), 'approvals.json');
9
10
  }
10
11
  function sha256Hex(data) {
11
12
  return createHash('sha256').update(data).digest('hex');
@@ -93,6 +94,10 @@ function readApprovals() {
93
94
  createdAt: entry.createdAt,
94
95
  ...(entry.secretsSubstitutable === true ? { secretsSubstitutable: true } : {}),
95
96
  ...(entry.argsPinView !== undefined ? { argsPinView: entry.argsPinView } : {}),
97
+ ...(isApprovalEntryState(entry.state) ? { state: entry.state } : {}),
98
+ ...(isConfirmGrant(entry.confirmGrant)
99
+ ? { confirmGrant: { confirmedAt: entry.confirmGrant.confirmedAt, mac: entry.confirmGrant.mac } }
100
+ : {}),
96
101
  };
97
102
  }
98
103
  return result;
@@ -101,6 +106,18 @@ function readApprovals() {
101
106
  return {};
102
107
  }
103
108
  }
109
+ // The store is untrusted input: a malformed field reads as absent, never as
110
+ // a value. A wrong-typed state or grant therefore degrades to the legacy
111
+ // entry shape (awaiting_user, no grant), which every consumer fails closed on.
112
+ function isApprovalEntryState(value) {
113
+ return value === 'awaiting_user' || value === 'user_confirmed';
114
+ }
115
+ function isConfirmGrant(value) {
116
+ if (!value || typeof value !== 'object' || Array.isArray(value))
117
+ return false;
118
+ const grant = value;
119
+ return typeof grant.confirmedAt === 'number' && typeof grant.mac === 'string';
120
+ }
104
121
  function writeApprovals(map) {
105
122
  try {
106
123
  const path = approvalFilePath();
@@ -125,7 +142,7 @@ function pruneStale(map, now = Date.now()) {
125
142
  return changed;
126
143
  }
127
144
  function consumedMarkerDir() {
128
- return join(huaweiConfigBase(), 'approvals-consumed');
145
+ return join(devkitStateBase(), 'approvals-consumed');
129
146
  }
130
147
  // Exclusive-create claim on a token: 'wx' maps to O_EXCL|O_CREAT, so the
131
148
  // first consumer wins atomically and every replay sees EEXIST. Claimed
@@ -172,6 +189,7 @@ export function createApprovalToken(rawArgs, opts = {}) {
172
189
  createdAt: Date.now(),
173
190
  ...(opts.secretsSubstitutable === true ? { secretsSubstitutable: true } : {}),
174
191
  ...(opts.argsPinView !== undefined ? { argsPinView: opts.argsPinView } : {}),
192
+ state: 'awaiting_user',
175
193
  };
176
194
  pruneStale(map);
177
195
  pruneConsumedMarkers();
@@ -205,30 +223,131 @@ export function inspectApprovalToken(token) {
205
223
  return { state: 'expired' };
206
224
  return { state: 'valid', entry };
207
225
  }
208
- // Mint→approve→run across processes: consume claims the entry and replaces it
209
- // with a tombstone. Returns the claimed entry on success, null otherwise
210
- // (unknown, already-consumed, or expired — classify via inspectApprovalToken).
211
- export function consumeApprovalToken(token) {
226
+ export function consumeApprovalToken(token, opts = {}) {
212
227
  if (!TOKEN_SHAPE.test(token))
213
- return null;
228
+ return { status: 'gone' };
214
229
  const map = readApprovals();
215
230
  const entry = map[token];
216
231
  if (!entry || isTombstone(entry))
217
- return null;
232
+ return { status: 'gone' };
218
233
  if (Date.now() - entry.createdAt > APPROVAL_TTL_MS) {
219
234
  delete map[token];
220
235
  writeApprovals(map);
221
- return null;
236
+ return { status: 'gone' };
237
+ }
238
+ // The confirmation gate rides INSIDE the consume cycle, on THIS freshly
239
+ // read snapshot: state and grant are verified on the same entry the
240
+ // execution will consume, before any marker claim and before any
241
+ // tombstone write — the ApprovalSafety Run step is one atomic read over
242
+ // the entry, by construction. A gate that read a different snapshot than
243
+ // the one execution consumed was the TOCTOU the adversarial review
244
+ // reproduced.
245
+ if (opts.requireGrant) {
246
+ const grant = verifyConfirmationGrant(entry, token);
247
+ if (!grant.ok)
248
+ return { status: 'grant_required', reason: grant.reason };
222
249
  }
223
250
  // Claim after validation: the marker exists only for tokens that were
224
- // real and unexpired at read time. A crash between claim and the
225
- // tombstone-write below can burn a valid token without spending it —
226
- // fail-closed, rare, accepted.
251
+ // real, unexpired, and (when required) grant-verified at read time. A
252
+ // crash between claim and the tombstone-write below can burn a valid
253
+ // token without spending it — fail-closed, rare, accepted.
227
254
  if (!claimSingleUse(token))
228
- return null;
255
+ return { status: 'gone' };
229
256
  // Tombstone instead of deleting outright (D4-24): a repeat call is
230
257
  // already_processed, not not_found.
231
258
  map[token] = { consumedAt: Date.now(), createdAt: entry.createdAt };
232
259
  writeApprovals(map);
233
- return entry;
260
+ return { status: 'consumed', entry };
261
+ }
262
+ // The grant mac's domain separator: custody-keyed material from one HMAC use
263
+ // never verifies in another (the approval PIN has its own domain), and the
264
+ // mac binds the token, the confirmation time, and the FULL execution-gating
265
+ // shape of the entry — a same-user edit of any field the run gate trusts
266
+ // (argsHash, argsPinView, argsRedacted, secretsSubstitutable, createdAt)
267
+ // breaks verification, not just an argsHash swap.
268
+ const GRANT_MAC_DOMAIN = 'huaweicloud-approval-grant';
269
+ // The shape digests through hashArgs (the module's canonical-JSON machinery),
270
+ // so the confirm side and the verify side agree no matter how the store was
271
+ // re-serialized between them. undefined-valued keys drop on both sides.
272
+ // createdAt is covered so an attacker extending it cannot lengthen the
273
+ // 5-minute window on an old confirmation.
274
+ function grantMac(masterKey, token, entry, confirmedAt) {
275
+ const shapeDigest = hashArgs({
276
+ argsHash: entry.argsHash,
277
+ argsPinView: entry.argsPinView,
278
+ argsRedacted: entry.argsRedacted,
279
+ secretsSubstitutable: entry.secretsSubstitutable,
280
+ createdAt: entry.createdAt,
281
+ });
282
+ return createHmac('sha256', masterKey)
283
+ .update(`${GRANT_MAC_DOMAIN}\x00${token}\x00${shapeDigest}\x00${String(confirmedAt)}`)
284
+ .digest('hex');
285
+ }
286
+ export function confirmApprovalToken(token) {
287
+ if (!TOKEN_SHAPE.test(token))
288
+ return { status: 'not_found' };
289
+ const map = readApprovals();
290
+ const entry = map[token];
291
+ if (!entry)
292
+ return { status: 'not_found' };
293
+ if (isTombstone(entry)) {
294
+ return Date.now() - entry.createdAt > APPROVAL_TTL_MS ? { status: 'not_found' } : { status: 'already_consumed' };
295
+ }
296
+ if (Date.now() - entry.createdAt > APPROVAL_TTL_MS)
297
+ return { status: 'expired' };
298
+ // No rewrite on an already-confirmed entry, even one whose grant a hand
299
+ // edit mangled: re-minting would upgrade a forged state string to a real
300
+ // grant the forger cannot make. verifyConfirmationGrant keeps rejecting it.
301
+ if (entry.state === 'user_confirmed')
302
+ return { status: 'already_confirmed' };
303
+ let master;
304
+ try {
305
+ // Mutating path, so bootstrap semantics match `secret set`: the first
306
+ // confirm on a keyless machine creates the custody key.
307
+ master = ensureMasterKey();
308
+ }
309
+ catch (error) {
310
+ const message = error instanceof Error ? error.message : String(error);
311
+ return { status: 'custody_unavailable', reason: `vault master key unavailable: ${message}` };
312
+ }
313
+ const confirmedAt = Date.now();
314
+ const grant = {
315
+ confirmedAt,
316
+ mac: grantMac(master.key, token, entry, confirmedAt),
317
+ };
318
+ // The spread is safe because readApprovals rebuilds entries through the
319
+ // whitelist: unknown fields planted in the file never reach this object.
320
+ map[token] = { ...entry, state: 'user_confirmed', confirmGrant: grant };
321
+ writeApprovals(map);
322
+ return { status: 'confirmed' };
323
+ }
324
+ export function resolveVerificationMasterKey() {
325
+ try {
326
+ const master = resolveMasterKey();
327
+ if (!master)
328
+ return { failure: 'vault master key unavailable' };
329
+ return { key: master.key };
330
+ }
331
+ catch (error) {
332
+ const message = error instanceof Error ? error.message : String(error);
333
+ return { failure: `vault master key unreadable: ${message}` };
334
+ }
335
+ }
336
+ export function verifyConfirmationGrant(entry, token) {
337
+ if (entry.state !== 'user_confirmed') {
338
+ return { ok: false, reason: 'token is awaiting user confirmation' };
339
+ }
340
+ const grant = entry.confirmGrant;
341
+ if (!isConfirmGrant(grant)) {
342
+ return { ok: false, reason: 'confirmation grant is missing or malformed' };
343
+ }
344
+ const master = resolveVerificationMasterKey();
345
+ if ('failure' in master)
346
+ return { ok: false, reason: master.failure };
347
+ if (!/^[0-9a-f]{64}$/.test(grant.mac)) {
348
+ return { ok: false, reason: 'confirmation grant mac is malformed' };
349
+ }
350
+ const expected = grantMac(master.key, token, entry, grant.confirmedAt);
351
+ const matches = timingSafeEqual(Buffer.from(expected, 'hex'), Buffer.from(grant.mac, 'hex'));
352
+ return matches ? { ok: true } : { ok: false, reason: 'confirmation grant does not verify' };
234
353
  }
@@ -0,0 +1,128 @@
1
+ import { createHmac, timingSafeEqual } from 'node:crypto';
2
+ import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
3
+ import { dirname, join } from 'node:path';
4
+ import { resolveVerificationMasterKey } from "./approval-tokens.js";
5
+ import { ensureMasterKey } from "./secret-vault/custody.js";
6
+ import { huaweiConfigBase } from "./pack-state.js";
7
+ // The pin mac's domain separator: distinct from the approval grant's, so
8
+ // custody-keyed material from one HMAC use never verifies in another.
9
+ const PIN_MAC_DOMAIN = 'huaweicloud-pin';
10
+ // The lockout ladder: every 6th cumulative failure locks verification for
11
+ // 5 minutes doubled per lockout episode, capped at 24 hours.
12
+ const LOCKOUT_BASE_MS = 5 * 60_000;
13
+ const LOCKOUT_CAP_MS = 24 * 60 * 60_000;
14
+ function lockoutDurationMs(fails) {
15
+ const episode = Math.floor(fails / 6);
16
+ return Math.min(LOCKOUT_BASE_MS * 2 ** (episode - 1), LOCKOUT_CAP_MS);
17
+ }
18
+ export function approvalsPinPath() {
19
+ return join(huaweiConfigBase(), 'approvals-pin.json');
20
+ }
21
+ // The record is untrusted input: anything malformed reads as absent, and
22
+ // absent reads as not enrolled — the fail-closed direction for every caller.
23
+ // A valid pinMac with malformed counters keeps the mac authority and reads
24
+ // the counters as zero: the counters are guidance, not a boundary.
25
+ function readPinRecord() {
26
+ try {
27
+ const path = approvalsPinPath();
28
+ if (!existsSync(path))
29
+ return null;
30
+ const parsed = JSON.parse(readFileSync(path, 'utf8'));
31
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed))
32
+ return null;
33
+ const record = parsed;
34
+ const pinMac = record.pinMac;
35
+ if (typeof pinMac !== 'string' || !/^[0-9a-f]{64}$/.test(pinMac))
36
+ return null;
37
+ const fails = typeof record.fails === 'number' && Number.isFinite(record.fails) && record.fails >= 0 ? record.fails : 0;
38
+ const lockedUntil = typeof record.lockedUntil === 'number' && Number.isFinite(record.lockedUntil) && record.lockedUntil >= 0
39
+ ? record.lockedUntil
40
+ : 0;
41
+ return { pinMac, fails, lockedUntil };
42
+ }
43
+ catch {
44
+ return null;
45
+ }
46
+ }
47
+ // Atomic temp+rename write, the same discipline as the approvals store: a
48
+ // crash never leaves a torn record behind.
49
+ function writePinRecord(record) {
50
+ const path = approvalsPinPath();
51
+ mkdirSync(dirname(path), { recursive: true });
52
+ const tmp = `${path}.${process.pid}.tmp`;
53
+ writeFileSync(tmp, JSON.stringify(record), { encoding: 'utf8', mode: 0o600 });
54
+ renameSync(tmp, path);
55
+ }
56
+ export function isApprovalsPinEnrolled() {
57
+ return readPinRecord() !== null;
58
+ }
59
+ export function enrollApprovalsPin(pin) {
60
+ if (typeof pin !== 'string' || pin.length < 6) {
61
+ return { ok: false, reason: 'the approvals PIN must be at least 6 characters' };
62
+ }
63
+ let master;
64
+ try {
65
+ // Mutating path, so bootstrap semantics match `secret set`: the first
66
+ // enroll on a keyless machine creates the custody key.
67
+ master = ensureMasterKey();
68
+ }
69
+ catch (error) {
70
+ const message = error instanceof Error ? error.message : String(error);
71
+ return { ok: false, reason: `vault master key unavailable: ${message}` };
72
+ }
73
+ const pinMac = createHmac('sha256', master.key).update(`${PIN_MAC_DOMAIN}\x00${pin}`).digest('hex');
74
+ try {
75
+ // Enrollment resets the failure state: a fresh credential starts with a
76
+ // clean counter (and re-enrollment is the recovery path for a forgotten
77
+ // pin, which a stale lockout must not outlive).
78
+ writePinRecord({ pinMac, fails: 0, lockedUntil: 0 });
79
+ }
80
+ catch (error) {
81
+ const message = error instanceof Error ? error.message : String(error);
82
+ return { ok: false, reason: `failed to persist the approvals PIN: ${message}` };
83
+ }
84
+ return { ok: true };
85
+ }
86
+ export function verifyApprovalsPin(pin) {
87
+ const record = readPinRecord();
88
+ if (!record)
89
+ return { ok: false, reason: 'no approvals PIN is enrolled' };
90
+ const now = Date.now();
91
+ if (record.lockedUntil > now) {
92
+ const minutes = Math.max(1, Math.ceil((record.lockedUntil - now) / 60_000));
93
+ return {
94
+ ok: false,
95
+ reason: `too many incorrect attempts: the approvals PIN is locked, retry in ${minutes} minute(s)`,
96
+ };
97
+ }
98
+ const master = resolveVerificationMasterKey();
99
+ if ('failure' in master)
100
+ return { ok: false, reason: master.failure };
101
+ const expected = createHmac('sha256', master.key).update(`${PIN_MAC_DOMAIN}\x00${pin}`).digest('hex');
102
+ const matches = timingSafeEqual(Buffer.from(expected, 'hex'), Buffer.from(record.pinMac, 'hex'));
103
+ if (matches) {
104
+ if (record.fails !== 0 || record.lockedUntil !== 0) {
105
+ try {
106
+ writePinRecord({ pinMac: record.pinMac, fails: 0, lockedUntil: 0 });
107
+ }
108
+ catch {
109
+ // The counter reset is guidance bookkeeping; its write failure must
110
+ // not turn a correct PIN into a refusal.
111
+ }
112
+ }
113
+ return { ok: true };
114
+ }
115
+ // The counter is guidance, not a boundary: a same-user process can edit
116
+ // this record the same way it can edit approvals.json. It slows online
117
+ // guessing across invocations; it cannot stop a writer that owns the file.
118
+ const fails = record.fails + 1;
119
+ const lockedUntil = fails % 6 === 0 ? now + lockoutDurationMs(fails) : record.lockedUntil;
120
+ try {
121
+ writePinRecord({ pinMac: record.pinMac, fails, lockedUntil });
122
+ }
123
+ catch {
124
+ // Same guidance doctrine: the verdict is the mac comparison, not the
125
+ // counter's persistence.
126
+ }
127
+ return { ok: false, reason: 'the approvals PIN does not match' };
128
+ }
@@ -1,23 +1,29 @@
1
1
  import { chmodSync, lstatSync, mkdirSync, realpathSync, writeFileSync } from 'node:fs';
2
- import { homedir, tmpdir } from 'node:os';
2
+ import { tmpdir } from 'node:os';
3
3
  import { basename, dirname, join, resolve, sep } from 'node:path';
4
+ import { devkitStateBase, huaweiConfigBase } from "./state-dir.js";
5
+ export { devkitStateBase, huaweiConfigBase };
4
6
  // The pack-scoped state space and the single resolver for the devkit's
5
7
  // config tree (~/.config/huaweicloud, relocatable whole-tree via
6
- // HUAWEICLOUD_HOME).
8
+ // HUAWEICLOUD_HOME) and its writable state tree (state-dir.ts: the same tree
9
+ // by default, the agent-owned devkit-state directory on a read-only home).
7
10
  //
8
11
  // Ownership criterion, stated here so the next state file does not have to
9
12
  // guess: the writer/reader set decides where state lives. approvals.json
10
13
  // is the CLI approval face's store (plan_cli_command /
11
14
  // run_approved_command mint and consume), credentials.json is the
12
15
  // devkit-wide S1 store, and deps/ belongs to the dependency domain — all
13
- // three stay at the config root. State with exactly one pack as writer
16
+ // three live in the state tree. State with exactly one pack as writer
14
17
  // and reader (the open-mcp gateway's policy file) lives under packs/<id>/,
15
18
  // so ownership is derivable from the directory name and an uninstall can
16
19
  // preserve user state without a manifest. Modules that still hand-roll
17
- // the base (auth/credentials, dep/receipts, update-check, proxy-config,
18
- // officeace-paths) migrate here when next touched; the guard below
19
- // already resolves through this module, so guard and store cannot
20
- // disagree about where the tree is.
20
+ // the base (dep/receipts, update-check, proxy-config, officeace-paths)
21
+ // migrate when next touched; the guard below already resolves through this
22
+ // module, so guard and store cannot disagree about where the trees are.
23
+ //
24
+ // S1 is the one exception: credentials are WRITTEN to the state tree but
25
+ // READ from the state tree first and the config tree second, so a
26
+ // pre-provisioned credentials.json in a read-only home keeps resolving.
21
27
  //
22
28
  // The same resolver backs the protected-tree guard the gateway face uses:
23
29
  // anything the devkit or its operator considers consent infrastructure (the
@@ -30,15 +36,8 @@ import { basename, dirname, join, resolve, sep } from 'node:path';
30
36
  // Runtime import graph stays at node builtins plus a type-only edge (PackId)
31
37
  // — the installer chain (dist/setup-cli.js, plain tsc output) must never
32
38
  // pull zod, same contract as dependency-model.ts and dep-resolve.ts.
33
- export function huaweiConfigBase(env = process.env) {
34
- // resolve() absolutizes once, here, so every consumer — store writes and
35
- // the guard below — shares one anchor even for a relative
36
- // HUAWEICLOUD_HOME (a relative base previously made the store land at
37
- // the process cwd while the guard protected a tmpdir-anchored tree).
38
- return resolve(env.HUAWEICLOUD_HOME || homedir(), '.config', 'huaweicloud');
39
- }
40
39
  export function packStateDir(packId, env = process.env) {
41
- return join(huaweiConfigBase(env), 'packs', packId);
40
+ return join(devkitStateBase(env), 'packs', packId);
42
41
  }
43
42
  // Idempotent provisioning, called at lazy-spawn time (a trimmed pack never
44
43
  // calls it, so trimming keeps its zero-files-on-disk guarantee). Permissions
@@ -136,22 +135,27 @@ function resolveForWrite(target) {
136
135
  return null;
137
136
  }
138
137
  }
139
- // The roots a gateway file write must never touch: the devkit config tree
140
- // plus whatever policy/audit paths the operator configured (the LIVE paths,
141
- // not what the devkit would have provisioned). Returns null when a root is
138
+ // The roots a gateway file write must never touch: the devkit config tree,
139
+ // the writable state tree (they differ on a read-only-home fallback), plus
140
+ // whatever policy/audit paths the operator configured (the LIVE paths, not
141
+ // what the devkit would have provisioned). Returns null when a root is
142
142
  // present-but-unresolvable — callers deny everything in that case.
143
143
  export function protectedTreeRoots(env = process.env) {
144
- const candidates = [huaweiConfigBase(env)];
144
+ const candidates = [huaweiConfigBase(env), devkitStateBase(env)];
145
145
  for (const key of ['HUAWEICLOUD_MCP_POLICY_FILE', 'HUAWEICLOUD_MCP_AUDIT_FILE']) {
146
146
  const value = (env[key] ?? '').trim();
147
147
  if (value !== '')
148
148
  candidates.push(value);
149
149
  }
150
150
  const roots = [];
151
+ const seen = new Set();
151
152
  for (const candidate of candidates) {
152
153
  const resolved = resolveForWrite(candidate);
153
154
  if (resolved === null)
154
155
  return null;
156
+ if (seen.has(resolved))
157
+ continue;
158
+ seen.add(resolved);
155
159
  roots.push(resolved);
156
160
  }
157
161
  return roots;
@@ -0,0 +1,70 @@
1
+ // Unknown-parameter warnings for the MCP boundary. The #530 leniency keeps
2
+ // accepting keys a tool does not declare (model wire shapes are noisy and a
3
+ // rejection used to cost the whole call), but silently dropping a typo makes
4
+ // `pack` vs `pak` invisible — this module turns that into an additive
5
+ // `warnings` entry without changing the acceptance decision.
6
+ const MAX_WARNINGS = 5;
7
+ const SUGGESTION_DISTANCE = 2;
8
+ function levenshtein(a, b) {
9
+ const rows = a.length + 1;
10
+ const cols = b.length + 1;
11
+ const previous = new Array(cols);
12
+ const current = new Array(cols);
13
+ for (let j = 0; j < cols; j++)
14
+ previous[j] = j;
15
+ for (let i = 1; i < rows; i++) {
16
+ current[0] = i;
17
+ for (let j = 1; j < cols; j++) {
18
+ const cost = a[i - 1] === b[j - 1] ? 0 : 1;
19
+ current[j] = Math.min(previous[j] + 1, current[j - 1] + 1, previous[j - 1] + cost);
20
+ }
21
+ for (let j = 0; j < cols; j++)
22
+ previous[j] = current[j];
23
+ }
24
+ return previous[cols - 1];
25
+ }
26
+ export function suggestParam(key, knownKeys) {
27
+ let best = null;
28
+ let bestDistance = SUGGESTION_DISTANCE + 1;
29
+ const lowerKey = key.toLowerCase();
30
+ for (const candidate of knownKeys) {
31
+ if (candidate === key)
32
+ continue;
33
+ const distance = levenshtein(lowerKey, candidate.toLowerCase());
34
+ if (distance > SUGGESTION_DISTANCE)
35
+ continue;
36
+ if (distance < bestDistance || (distance === bestDistance && best !== null && candidate < best)) {
37
+ best = candidate;
38
+ bestDistance = distance;
39
+ }
40
+ }
41
+ return best;
42
+ }
43
+ export function unknownParamWarnings(args, knownKeys) {
44
+ const unknown = Object.keys(args)
45
+ .filter((key) => !knownKeys.has(key))
46
+ .sort((a, b) => a.localeCompare(b));
47
+ return unknown.slice(0, MAX_WARNINGS).map((key) => {
48
+ const suggestion = suggestParam(key, knownKeys);
49
+ return suggestion
50
+ ? `Unknown parameter "${key}" was ignored. Did you mean "${suggestion}"?`
51
+ : `Unknown parameter "${key}" was ignored (no matching parameter).`;
52
+ });
53
+ }
54
+ // Additive by construction: a warnings array is merged, an absent field is
55
+ // created, and any other existing shape is left untouched under paramWarnings.
56
+ // Non-object results (there are none on the shipped surface) pass through.
57
+ export function attachParamWarnings(result, warnings) {
58
+ if (warnings.length === 0)
59
+ return result;
60
+ if (result === null || typeof result !== 'object' || Array.isArray(result))
61
+ return result;
62
+ const record = result;
63
+ if (Array.isArray(record.warnings)) {
64
+ return { ...record, warnings: [...record.warnings, ...warnings] };
65
+ }
66
+ if (record.warnings === undefined) {
67
+ return { ...record, warnings };
68
+ }
69
+ return { ...record, paramWarnings: warnings };
70
+ }
@@ -0,0 +1,125 @@
1
+ import { existsSync, lstatSync, mkdirSync, rmSync } from 'node:fs';
2
+ import { homedir } from 'node:os';
3
+ import { dirname, isAbsolute, join, resolve } from 'node:path';
4
+ // The devkit's two directory roots. `configBase` is the historical
5
+ // ~/.config/huaweicloud tree (credentials, approvals, pack state, proxy and
6
+ // update state); `stateBase` is the same tree by default and moves to a
7
+ // writable agent-owned directory only when the config tree cannot be written.
8
+ //
9
+ // The split exists because some agent sandboxes ship a read-only home: the
10
+ // gateway's pack state, approval tokens, S1 writes and update state all need
11
+ // a writable directory, while the pre-provisioned credentials.json must stay
12
+ // readable at its original location. The installer/CLI and the MCP server
13
+ // resolve the same paths from the same filesystem, so no env plumbing is
14
+ // required for them to agree.
15
+ //
16
+ // Runtime import graph stays at node builtins — pack-state.ts (the stable
17
+ // resolver face) and the installer graph import this module.
18
+ const STATE_DIR_ENV = 'HUAWEICLOUD_STATE_DIR';
19
+ const AGENT_STATE_MARKERS = ['.codearts', '.codeartswork', '.codeartsdoer'];
20
+ const stateBaseCache = new Map();
21
+ export function huaweiConfigBase(env = process.env) {
22
+ // resolve() absolutizes once, here, so every consumer — store writes and
23
+ // the protected-tree guard — shares one anchor even for a relative
24
+ // HUAWEICLOUD_HOME (a relative base previously made the store land at
25
+ // the process cwd while the guard protected a tmpdir-anchored tree).
26
+ return resolve(env.HUAWEICLOUD_HOME || homedir(), '.config', 'huaweicloud');
27
+ }
28
+ function agentHomeBase(env) {
29
+ return resolve(env.HUAWEICLOUD_HOME || homedir());
30
+ }
31
+ function nearestExisting(path) {
32
+ let current = resolve(path);
33
+ for (;;) {
34
+ try {
35
+ lstatSync(current);
36
+ return current;
37
+ }
38
+ catch {
39
+ const parent = dirname(current);
40
+ if (parent === current)
41
+ return null;
42
+ current = parent;
43
+ }
44
+ }
45
+ }
46
+ // A real create/remove probe, not access(W_OK): Windows ACLs and WSL drvfs
47
+ // can report a writable mode while mkdir still fails, and the gateway's first
48
+ // pack-state provisioning is exactly a mkdir under the config tree.
49
+ export function probeWritableDir(path) {
50
+ const anchor = nearestExisting(path);
51
+ if (!anchor)
52
+ return false;
53
+ const probe = join(anchor, `.devkit-write-probe-${process.pid}-${Math.random().toString(36).slice(2)}`);
54
+ try {
55
+ mkdirSync(probe, { mode: 0o700 });
56
+ return true;
57
+ }
58
+ catch {
59
+ return false;
60
+ }
61
+ finally {
62
+ try {
63
+ rmSync(probe, { recursive: true, force: true });
64
+ }
65
+ catch {
66
+ // best-effort cleanup; the probe directory is empty and 0700
67
+ }
68
+ }
69
+ }
70
+ // Agent-owned writable roots, checked in the same order the installer targets
71
+ // them: CodeArts Work's new layout, its legacy home, then CodeArts.
72
+ function codeArtsStateBase(env) {
73
+ const home = agentHomeBase(env);
74
+ for (const marker of AGENT_STATE_MARKERS) {
75
+ const root = join(home, marker);
76
+ if (!existsSync(root) || !probeWritableDir(root))
77
+ continue;
78
+ return join(root, 'devkit-state');
79
+ }
80
+ return null;
81
+ }
82
+ function explicitStateBase(env) {
83
+ const value = (env[STATE_DIR_ENV] ?? '').trim();
84
+ if (value === '')
85
+ return null;
86
+ if (!isAbsolute(value)) {
87
+ throw new Error(`${STATE_DIR_ENV} must be an absolute path (got "${value}"): the CLI and the MCP server resolve relative paths against different working directories.`);
88
+ }
89
+ return resolve(value);
90
+ }
91
+ export function devkitStateBase(env = process.env) {
92
+ const explicit = explicitStateBase(env);
93
+ if (explicit)
94
+ return explicit;
95
+ const configBase = huaweiConfigBase(env);
96
+ const cached = stateBaseCache.get(configBase);
97
+ if (cached)
98
+ return cached;
99
+ const stateBase = probeWritableDir(configBase) ? configBase : (codeArtsStateBase(env) ?? configBase);
100
+ stateBaseCache.set(configBase, stateBase);
101
+ return stateBase;
102
+ }
103
+ // Doctor/installer display form: home-relative paths stay stable in the
104
+ // golden fixtures and read better to a human. Forward slashes keep the
105
+ // rendered form identical on Windows and POSIX (the goldens are committed
106
+ // once, not per platform).
107
+ export function displayStatePath(path, env = process.env) {
108
+ const home = agentHomeBase(env).replace(/\\/g, '/');
109
+ const normalized = path.replace(/\\/g, '/');
110
+ if (normalized === home)
111
+ return '~';
112
+ return normalized.startsWith(home + '/') ? `~${normalized.slice(home.length)}` : normalized;
113
+ }
114
+ export function stateDirNotice(env = process.env) {
115
+ const configBase = huaweiConfigBase(env);
116
+ const stateBase = devkitStateBase(env);
117
+ if (stateBase === configBase)
118
+ return null;
119
+ return `state directory ${displayStatePath(stateBase, env)} (${displayStatePath(configBase, env)} is not writable; set ${STATE_DIR_ENV} to pin it)`;
120
+ }
121
+ // Tests swap HUAWEICLOUD_HOME between cases; the cache is keyed by configBase,
122
+ // so this is only for a case that changes permissions under one home.
123
+ export function _resetStateDirCache() {
124
+ stateBaseCache.clear();
125
+ }