huaweicloud-devkit 2.0.0-next.1 → 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 (33) 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/auth/s1-store.js +43 -22
  11. package/plugins/huaweicloud-core/dist/lib/approval-tokens.js +3 -3
  12. package/plugins/huaweicloud-core/dist/lib/pack-state.js +23 -19
  13. package/plugins/huaweicloud-core/dist/lib/param-warnings.js +70 -0
  14. package/plugins/huaweicloud-core/dist/lib/state-dir.js +125 -0
  15. package/plugins/huaweicloud-core/dist/mcp-server.js +763 -567
  16. package/plugins/huaweicloud-core/dist/mcp-server.js.map +4 -4
  17. package/plugins/huaweicloud-core/dist/setup-cli.js +16 -0
  18. package/plugins/huaweicloud-core/dist/tool-schemas.js +15 -0
  19. package/plugins/huaweicloud-core/dist/tools.js +36 -4
  20. package/plugins/huaweicloud-core/dist/update-skip.js +5 -6
  21. package/plugins/huaweicloud-core/openclaw.plugin.json +1 -1
  22. package/plugins/huaweicloud-core/safety/rules/cloud-risk-rules.json +78 -2
  23. package/plugins/huaweicloud-core/src/agents/codearts-work.ts +3 -0
  24. package/plugins/huaweicloud-core/src/agents/codearts.ts +4 -0
  25. package/plugins/huaweicloud-core/src/auth/s1-store.ts +41 -20
  26. package/plugins/huaweicloud-core/src/lib/approval-tokens.ts +3 -3
  27. package/plugins/huaweicloud-core/src/lib/pack-state.ts +23 -20
  28. package/plugins/huaweicloud-core/src/lib/param-warnings.ts +69 -0
  29. package/plugins/huaweicloud-core/src/lib/state-dir.ts +128 -0
  30. package/plugins/huaweicloud-core/src/setup-cli.ts +21 -0
  31. package/plugins/huaweicloud-core/src/tool-schemas.ts +16 -0
  32. package/plugins/huaweicloud-core/src/tools.ts +39 -4
  33. package/plugins/huaweicloud-core/src/update-skip.ts +5 -6
package/README.md CHANGED
@@ -139,6 +139,8 @@ npx --yes huaweicloud-devkit uninstall --target codearts-work
139
139
  ```
140
140
 
141
141
  > **CodeArts Work** (CodeArts Space, appId: `com.codearts.work`) uses user-level config at `%USERPROFILE%\.codeartswork\`. No project-level `.codeartswork` directory is created.
142
+ >
143
+ > **Read-only home**: when `~/.config/huaweicloud` is not writable (sandbox home), devkit state — gateway policy, approval tokens, update skip, S1 writes — moves automatically to `~/.codearts*/devkit-state`; a pre-provisioned `credentials.json` in the old tree remains readable. `doctor` reports the resolved state directory; set `HUAWEICLOUD_STATE_DIR` to an absolute path to pin it explicitly.
142
144
 
143
145
  ### WorkBuddy
144
146
 
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "huaweicloud-devkit",
3
3
  "mcpName": "io.github.huaweicloud/huaweicloud-devkit",
4
- "version": "2.0.0-next.1",
4
+ "version": "2.0.0-next.2",
5
5
  "kooCliVersion": "7.3.12",
6
6
  "description": "Agent toolkit that helps coding agents use Huawei Cloud Skills, KooCLI, APIs, SDKs, and future MCP capabilities safely and accurately.",
7
7
  "type": "module",
@@ -16,7 +16,7 @@
16
16
  },
17
17
  "mcpServers": "./.mcp.json",
18
18
  "description": "Guide coding agents to use Huawei Cloud Skills, KooCLI, APIs, SDKs, and future MCP capabilities with safer execution and less context.",
19
- "version": "2.0.0-next.1",
19
+ "version": "2.0.0-next.2",
20
20
  "author": {
21
21
  "name": "HuaweiCloud Mate",
22
22
  "url": "https://github.com/huaweicloud"
@@ -19,7 +19,7 @@
19
19
  },
20
20
  "mcpServers": "./.mcp.json",
21
21
  "description": "Agent toolkit that helps coding agents use Huawei Cloud Skills, KooCLI, APIs, SDKs, and future MCP capabilities safely and accurately.",
22
- "version": "2.0.0-next.1",
22
+ "version": "2.0.0-next.2",
23
23
  "author": {
24
24
  "name": "HuaweiCloud Mate",
25
25
  "url": "https://github.com/huaweicloud"
@@ -16,7 +16,7 @@
16
16
  },
17
17
  "mcpServers": "./.mcp.json",
18
18
  "description": "Guide coding agents to use Huawei Cloud Skills, KooCLI, APIs, SDKs, and future MCP capabilities with safer execution and less context.",
19
- "version": "2.0.0-next.1",
19
+ "version": "2.0.0-next.2",
20
20
  "author": {
21
21
  "name": "HuaweiCloud Mate",
22
22
  "url": "https://github.com/huaweicloud"
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "huaweicloud-devkit",
3
- "version": "2.0.0-next.1",
3
+ "version": "2.0.0-next.2",
4
4
  "description": "Guide coding agents to use Huawei Cloud Skills, KooCLI, APIs, SDKs, and future MCP capabilities with safer execution and less context.",
5
5
  "author": {
6
6
  "name": "HuaweiCloud Mate",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "huaweicloud-devkit",
3
- "version": "2.0.0-next.1",
3
+ "version": "2.0.0-next.2",
4
4
  "description": "Guide coding agents to use Huawei Cloud Skills, KooCLI, APIs, SDKs, and future MCP capabilities with safer execution and less context.",
5
5
  "author": {
6
6
  "name": "HuaweiCloud Mate",
@@ -10,6 +10,7 @@ import { mergeCommandStyle, applyUserDelta, inheritPeerUserEnv } from "../mcp-co
10
10
  import { takeAgentDelta } from "../mcp-config-backup.js";
11
11
  import { printMcpConfigStatus, readJsonRecord, removeMcpServerEntry, writeMcpSettingsFile } from "../mcp-config-io.js";
12
12
  import { asRecord } from "../lib/as-record.js";
13
+ import { stateDirNotice } from "../lib/state-dir.js";
13
14
  import { copyServerPayload, installRuntimeDeps, payloadStatusLines, removeIfExists, } from "../install-payload.js";
14
15
  // Doctor: the CodeArts Work MCP-configured candidate — the mcp settings
15
16
  // file's mcp.huaweicloud-devkit entry.
@@ -102,6 +103,9 @@ function isPlainLocal(value) {
102
103
  export async function deployCodeArtsWork(_mode) {
103
104
  const pluginDest = codeartsWorkPluginsDir();
104
105
  copyServerPayload(pluginDest);
106
+ const stateNotice = stateDirNotice();
107
+ if (stateNotice)
108
+ console.log(` [CodeArts Work] ${stateNotice}`);
105
109
  registerCodeartsWorkMcp();
106
110
  installRuntimeDeps(pluginDest);
107
111
  }
@@ -6,6 +6,7 @@ import { homedir } from 'node:os';
6
6
  import { codeartsMcpSettingsFile, codeartsPluginsDir, codeartsProjectMcpSettingsFile, codeartsProjectSkillsDir, codeartsSkillsDir, } from "../targets.js";
7
7
  import { findHcloudBin } from "../hcloud-probe.js";
8
8
  import { asRecord } from "../lib/as-record.js";
9
+ import { stateDirNotice } from "../lib/state-dir.js";
9
10
  import { ensureMcpServersConfig, printMcpConfigStatus, removeMcpServerEntry } from "../mcp-config-io.js";
10
11
  import { PACKAGE_ROOT, copyServerPayload, deployWord, installRuntimeDeps, payloadStatusLines, removeIfExists, } from "../install-payload.js";
11
12
  // Doctor: the CodeArts MCP-configured candidate — the user-level mcp settings
@@ -37,6 +38,9 @@ export async function deployCodeArts(mode) {
37
38
  const pluginSrc = join(PACKAGE_ROOT, 'integrations', 'opencode', 'hooks', 'skill-tracker.js');
38
39
  const pluginDest = codeartsPluginsDir();
39
40
  copyServerPayload(pluginDest);
41
+ const stateNotice = stateDirNotice();
42
+ if (stateNotice)
43
+ console.log(` [CodeArts] ${stateNotice}`);
40
44
  const codeartsHookDir = join(homedir(), '.codeartsdoer', 'plugins');
41
45
  mkdirSync(codeartsHookDir, { recursive: true });
42
46
  copyFileSync(pluginSrc, join(codeartsHookDir, 'skill-tracker.js'));
@@ -4,8 +4,8 @@
4
4
  // resolution seam, the last-sync sidecar, and the backup/restore pair.
5
5
  import { chmodSync, copyFileSync, existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from 'node:fs';
6
6
  import { dirname, join } from 'node:path';
7
- import { homedir } from 'node:os';
8
7
  import { asText } from "../lib/as-text.js";
8
+ import { devkitStateBase, huaweiConfigBase } from "../lib/pack-state.js";
9
9
  import { resolveSecretValue } from "../lib/secret-vault/store.js";
10
10
  // Verify a credential file ended up with 0600. On Windows-mounted drives inside WSL
11
11
  // (drvfs/9p) chmod is silently ignored, so the file can be world-readable (0777).
@@ -35,24 +35,40 @@ export function ensurePrivateMode(path) {
35
35
  // best-effort: if even stat fails there is no mode left to verify or warn about
36
36
  }
37
37
  }
38
- function baseHome() {
39
- return process.env.HUAWEICLOUD_HOME || homedir();
40
- }
41
38
  export function globalCredentialsPath() {
42
- return join(baseHome(), '.config', 'huaweicloud', 'credentials.json');
39
+ return join(devkitStateBase(), 'credentials.json');
43
40
  }
44
- export function readGlobalCredentials() {
45
- const path = globalCredentialsPath();
41
+ // The historical read location. On a read-only-home fallback the config tree
42
+ // may still carry a pre-provisioned credentials.json; reads prefer the
43
+ // writable state tree but fall back here so those credentials keep working.
44
+ function legacyGlobalCredentialsPath() {
45
+ return join(huaweiConfigBase(), 'credentials.json');
46
+ }
47
+ function readJsonObject(path) {
46
48
  if (!existsSync(path))
47
49
  return null;
48
50
  try {
49
51
  const parsed = JSON.parse(readFileSync(path, 'utf8'));
50
- return parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : null;
52
+ return parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed)
53
+ ? parsed
54
+ : null;
51
55
  }
52
56
  catch {
53
57
  return null;
54
58
  }
55
59
  }
60
+ export function readGlobalCredentials() {
61
+ const primary = globalCredentialsPath();
62
+ const stored = readJsonObject(primary);
63
+ if (stored)
64
+ return stored;
65
+ if (!existsSync(primary)) {
66
+ const legacy = legacyGlobalCredentialsPath();
67
+ if (legacy !== primary)
68
+ return readJsonObject(legacy);
69
+ }
70
+ return null;
71
+ }
56
72
  // S1 may hold secret://<scope>/<name> refs in its secret-bearing fields (the
57
73
  // vault is the at-rest-encrypted alternative to plaintext AK/SK). This is the
58
74
  // one seam every S1 value CONSUMER goes through: refs resolve to plaintext,
@@ -116,19 +132,22 @@ export function setConfiguredBySession(flag) {
116
132
  writeGlobalCredentials(next);
117
133
  }
118
134
  export function lastSyncPath() {
119
- return join(baseHome(), '.config', 'huaweicloud', '.last_sync');
135
+ return join(devkitStateBase(), '.last_sync');
136
+ }
137
+ function readLastSyncFile(path) {
138
+ return readJsonObject(path);
120
139
  }
121
140
  export function readLastSync() {
122
- const path = lastSyncPath();
123
- if (!existsSync(path))
124
- return null;
125
- try {
126
- const parsed = JSON.parse(readFileSync(path, 'utf8'));
127
- return parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : null;
128
- }
129
- catch {
130
- return null;
141
+ const primary = lastSyncPath();
142
+ const stored = readLastSyncFile(primary);
143
+ if (stored)
144
+ return stored;
145
+ if (!existsSync(primary)) {
146
+ const legacy = join(huaweiConfigBase(), '.last_sync');
147
+ if (legacy !== primary)
148
+ return readLastSyncFile(legacy);
131
149
  }
150
+ return null;
132
151
  }
133
152
  export function writeLastSync(metadata = {}) {
134
153
  const path = lastSyncPath();
@@ -142,12 +161,14 @@ export function writeLastSync(metadata = {}) {
142
161
  ensurePrivateMode(path);
143
162
  }
144
163
  export function backupGlobalCredentials() {
145
- const path = globalCredentialsPath();
146
- if (!existsSync(path))
164
+ const target = globalCredentialsPath();
165
+ const source = existsSync(target) ? target : legacyGlobalCredentialsPath();
166
+ if (!existsSync(source))
147
167
  return null;
148
- const bakPath = `${path}.bak`;
168
+ const bakPath = `${target}.bak`;
149
169
  try {
150
- copyFileSync(path, bakPath);
170
+ mkdirSync(dirname(bakPath), { recursive: true });
171
+ copyFileSync(source, bakPath);
151
172
  ensurePrivateMode(bakPath);
152
173
  return bakPath;
153
174
  }
@@ -3,10 +3,10 @@ import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, statSync,
3
3
  import { dirname, join } from 'node:path';
4
4
  import { redactSecrets } from "../safety-policy.js";
5
5
  import { ensureMasterKey, resolveMasterKey } from "./secret-vault/custody.js";
6
- import { huaweiConfigBase } from "./pack-state.js";
6
+ import { devkitStateBase } from "./pack-state.js";
7
7
  const APPROVAL_TTL_MS = 5 * 60_000;
8
8
  function approvalFilePath() {
9
- return join(huaweiConfigBase(), 'approvals.json');
9
+ return join(devkitStateBase(), 'approvals.json');
10
10
  }
11
11
  function sha256Hex(data) {
12
12
  return createHash('sha256').update(data).digest('hex');
@@ -142,7 +142,7 @@ function pruneStale(map, now = Date.now()) {
142
142
  return changed;
143
143
  }
144
144
  function consumedMarkerDir() {
145
- return join(huaweiConfigBase(), 'approvals-consumed');
145
+ return join(devkitStateBase(), 'approvals-consumed');
146
146
  }
147
147
  // Exclusive-create claim on a token: 'wx' maps to O_EXCL|O_CREAT, so the
148
148
  // first consumer wins atomically and every replay sees EEXIST. Claimed
@@ -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
+ }