ccem 2.69.0 → 2.73.0

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.
package/dist/index.js CHANGED
@@ -7,14 +7,283 @@ import inquirer from "inquirer";
7
7
  import chalk7 from "chalk";
8
8
  import Table3 from "cli-table3";
9
9
  import { spawn as spawn3 } from "child_process";
10
- import * as fs11 from "fs";
11
- import * as path9 from "path";
10
+ import * as fs12 from "fs";
11
+ import * as path10 from "path";
12
12
  import { fileURLToPath as fileURLToPath2 } from "url";
13
13
 
14
- // ../../packages/core/dist/chunk-LVDB6VZW.js
15
- var TIER_MODEL_ALIASES = /* @__PURE__ */ new Set(["opus", "sonnet", "haiku"]);
14
+ // ../../packages/core/dist/chunk-WF72XTKK.js
15
+ var DEFAULT_ROUTER_PORT = 17820;
16
+ var DEFAULT_ONLY_ROUTER_PROFILE_ID = "default-only";
17
+ var MY_DEFAULT_ROUTER_PROFILE_ID = "my-default";
18
+ var RESERVED_ROUTER_PROFILE_IDS = /* @__PURE__ */ new Set([
19
+ DEFAULT_ONLY_ROUTER_PROFILE_ID,
20
+ MY_DEFAULT_ROUTER_PROFILE_ID
21
+ ]);
22
+ var BUILTIN_CLAUDE_AGENT_NAMES = Object.freeze([
23
+ "claude",
24
+ "Explore",
25
+ "general-purpose",
26
+ "Plan",
27
+ "statusline-setup"
28
+ ]);
29
+ var DEFAULT_ONLY_ROUTER_PROFILE = Object.freeze({
30
+ id: DEFAULT_ONLY_ROUTER_PROFILE_ID,
31
+ name: "\u4EC5\u9ED8\u8BA4\u89C4\u5219",
32
+ revision: 1,
33
+ bindings: Object.freeze({}),
34
+ allowedEnvs: Object.freeze([])
35
+ });
36
+ var BUILTIN_ROUTER_PROFILES = Object.freeze([
37
+ DEFAULT_ONLY_ROUTER_PROFILE
38
+ ]);
39
+ var DEFAULT_ROUTER_CONFIG = Object.freeze({
40
+ port: DEFAULT_ROUTER_PORT,
41
+ bindings: Object.freeze({}),
42
+ profiles: Object.freeze([]),
43
+ dynamicRouting: true,
44
+ defaultAllowedEnvs: Object.freeze([])
45
+ });
46
+ var ROUTER_AGENT_NAME = /^[A-Za-z0-9._:-]{1,128}$/u;
47
+ function isRecord(value) {
48
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
49
+ }
50
+ function isNonEmptyEnvironmentReference(value) {
51
+ return typeof value === "string" && value.trim().length > 0;
52
+ }
53
+ function isValidRouterBindingKey(value) {
54
+ if (value === "background" || value === "subagent:*") {
55
+ return true;
56
+ }
57
+ if (typeof value !== "string" || !value.startsWith("subagent:")) {
58
+ return false;
59
+ }
60
+ const agentName = value.slice("subagent:".length);
61
+ return ROUTER_AGENT_NAME.test(agentName);
62
+ }
63
+ function validateRouterBindings(value) {
64
+ if (!isRecord(value)) {
65
+ return ["Router bindings must be an object"];
66
+ }
67
+ const errors = [];
68
+ for (const [key, envName] of Object.entries(value)) {
69
+ if (!isValidRouterBindingKey(key)) {
70
+ errors.push(`Invalid router binding key '${key}'`);
71
+ }
72
+ if (!isNonEmptyEnvironmentReference(envName)) {
73
+ errors.push(`Router binding '${key}' must target a non-empty environment reference`);
74
+ }
75
+ }
76
+ return errors;
77
+ }
78
+ function throwValidationErrors(errors) {
79
+ if (errors.length > 0) {
80
+ throw new TypeError(errors.join("; "));
81
+ }
82
+ }
83
+ function cloneBindings(value, fieldName) {
84
+ const errors = validateRouterBindings(value);
85
+ throwValidationErrors(errors.map((error) => `${fieldName}: ${error}`));
86
+ return { ...value };
87
+ }
88
+ function normalizeEnvironmentNames(value, fieldName) {
89
+ if (!Array.isArray(value)) {
90
+ throw new TypeError(`${fieldName} must be an array of environment names`);
91
+ }
92
+ const result = [];
93
+ const seen = /* @__PURE__ */ new Set();
94
+ for (const envName of value) {
95
+ if (!isNonEmptyEnvironmentReference(envName)) {
96
+ throw new TypeError(`${fieldName} must contain only non-empty environment references`);
97
+ }
98
+ if (!seen.has(envName)) {
99
+ seen.add(envName);
100
+ result.push(envName);
101
+ }
102
+ }
103
+ return result;
104
+ }
105
+ function normalizeProfile(value, index) {
106
+ const fieldName = `Router profile at index ${index}`;
107
+ if (!isRecord(value)) {
108
+ throw new TypeError(`${fieldName} must be an object`);
109
+ }
110
+ if (typeof value.id !== "string" || !value.id.trim() || value.id.trim() !== value.id) {
111
+ throw new TypeError(`${fieldName} must have a non-empty id`);
112
+ }
113
+ if (RESERVED_ROUTER_PROFILE_IDS.has(value.id)) {
114
+ throw new TypeError(`${fieldName} id '${value.id}' is reserved`);
115
+ }
116
+ if (typeof value.name !== "string" || !value.name.trim() || value.name.trim() !== value.name) {
117
+ throw new TypeError(`${fieldName} must have a non-empty name`);
118
+ }
119
+ if (!Number.isSafeInteger(value.revision) || value.revision < 0) {
120
+ throw new TypeError(`${fieldName} must have a non-negative safe integer revision`);
121
+ }
122
+ const bindings = cloneBindings(value.bindings, `${fieldName} bindings`);
123
+ const allowedEnvs = normalizeEnvironmentNames(value.allowedEnvs, `${fieldName} allowedEnvs`);
124
+ for (const [key, target] of Object.entries(bindings)) {
125
+ if (typeof target !== "string" || !allowedEnvs.includes(target)) {
126
+ throw new TypeError(
127
+ `${fieldName} binding '${key}' targets an environment outside allowedEnvs`
128
+ );
129
+ }
130
+ }
131
+ return {
132
+ id: value.id,
133
+ name: value.name,
134
+ revision: value.revision,
135
+ bindings,
136
+ allowedEnvs
137
+ };
138
+ }
139
+ function createDefaultRouterConfig() {
140
+ return {
141
+ port: DEFAULT_ROUTER_CONFIG.port,
142
+ bindings: {},
143
+ profiles: [],
144
+ dynamicRouting: DEFAULT_ROUTER_CONFIG.dynamicRouting,
145
+ defaultAllowedEnvs: []
146
+ };
147
+ }
148
+ function normalizeRouterConfig(value = {}) {
149
+ if (!isRecord(value)) {
150
+ throw new TypeError("Router config must be an object");
151
+ }
152
+ const normalized = createDefaultRouterConfig();
153
+ if (value.port !== void 0) {
154
+ if (!Number.isInteger(value.port) || value.port < 1 || value.port > 65535) {
155
+ throw new TypeError("Router port must be an integer between 1 and 65535");
156
+ }
157
+ normalized.port = value.port;
158
+ }
159
+ if (value.bindings !== void 0) {
160
+ normalized.bindings = cloneBindings(value.bindings, "Router bindings");
161
+ }
162
+ if (value.profiles !== void 0) {
163
+ if (!Array.isArray(value.profiles)) {
164
+ throw new TypeError("Router profiles must be an array");
165
+ }
166
+ normalized.profiles = value.profiles.map(normalizeProfile);
167
+ const profileIds = /* @__PURE__ */ new Set();
168
+ for (const profile of normalized.profiles) {
169
+ if (profileIds.has(profile.id)) {
170
+ throw new TypeError(`Router profile id '${profile.id}' is duplicated`);
171
+ }
172
+ profileIds.add(profile.id);
173
+ }
174
+ }
175
+ if (value.dynamicRouting !== void 0) {
176
+ if (typeof value.dynamicRouting !== "boolean") {
177
+ throw new TypeError("Router dynamicRouting must be a boolean");
178
+ }
179
+ normalized.dynamicRouting = value.dynamicRouting;
180
+ }
181
+ if (value.defaultAllowedEnvs !== void 0) {
182
+ normalized.defaultAllowedEnvs = normalizeEnvironmentNames(
183
+ value.defaultAllowedEnvs,
184
+ "Router defaultAllowedEnvs"
185
+ );
186
+ }
187
+ return normalized;
188
+ }
189
+ function findRouterEnvironmentReferences(router, envName) {
190
+ if (!router) {
191
+ return [];
192
+ }
193
+ const normalized = normalizeRouterConfig(router);
194
+ const references = [];
195
+ for (const [key, target] of Object.entries(normalized.bindings)) {
196
+ if (target === envName) {
197
+ references.push(`router.bindings.${key}`);
198
+ }
199
+ }
200
+ if (normalized.defaultAllowedEnvs.includes(envName)) {
201
+ references.push("router.defaultAllowedEnvs");
202
+ }
203
+ for (const profile of normalized.profiles) {
204
+ for (const [key, target] of Object.entries(profile.bindings)) {
205
+ if (target === envName) {
206
+ references.push(`router.profiles[${profile.id}].bindings.${key}`);
207
+ }
208
+ }
209
+ if (profile.allowedEnvs.includes(envName)) {
210
+ references.push(`router.profiles[${profile.id}].allowedEnvs`);
211
+ }
212
+ }
213
+ return references;
214
+ }
215
+ function replaceEnvironmentNames(values, oldName, newName) {
216
+ return [...new Set(values.map((value) => value === oldName ? newName : value))];
217
+ }
218
+ function bumpProfileRevision(revision) {
219
+ return revision >= Number.MAX_SAFE_INTEGER ? Number.MAX_SAFE_INTEGER : revision + 1;
220
+ }
221
+ function renameRouterEnvironmentReferences(router, oldName, newName) {
222
+ const normalized = normalizeRouterConfig(router);
223
+ const renameBindings = (bindings) => Object.fromEntries(
224
+ Object.entries(bindings).map(([key, target]) => [
225
+ key,
226
+ target === oldName ? newName : target
227
+ ])
228
+ );
229
+ return {
230
+ ...normalized,
231
+ bindings: renameBindings(normalized.bindings),
232
+ defaultAllowedEnvs: replaceEnvironmentNames(
233
+ normalized.defaultAllowedEnvs,
234
+ oldName,
235
+ newName
236
+ ),
237
+ profiles: normalized.profiles.map((profile) => {
238
+ const bindings = renameBindings(profile.bindings);
239
+ const allowedEnvs = replaceEnvironmentNames(profile.allowedEnvs, oldName, newName);
240
+ const changed = Object.entries(profile.bindings).some(([, target]) => target === oldName && target !== newName) || profile.allowedEnvs.some((target) => target === oldName && target !== newName);
241
+ return {
242
+ ...profile,
243
+ revision: changed ? bumpProfileRevision(profile.revision) : profile.revision,
244
+ bindings,
245
+ allowedEnvs
246
+ };
247
+ })
248
+ };
249
+ }
16
250
  var OFFICIAL_ENV_NAME = "official";
17
251
  var OFFICIAL_BASE_URL = "https://api.anthropic.com";
252
+ function isTrustedOfficialBaseUrl(value) {
253
+ return value === OFFICIAL_BASE_URL || value === `${OFFICIAL_BASE_URL}/`;
254
+ }
255
+ function assertOfficialEnvironmentPresent(registries) {
256
+ if (!registries || typeof registries !== "object" || Array.isArray(registries) || !Object.prototype.hasOwnProperty.call(registries, OFFICIAL_ENV_NAME)) {
257
+ throw new TypeError(`Cannot remove or rename the protected '${OFFICIAL_ENV_NAME}' environment`);
258
+ }
259
+ }
260
+ function assertOfficialEnvironmentInvariant(registries) {
261
+ assertOfficialEnvironmentPresent(registries);
262
+ const official = registries[OFFICIAL_ENV_NAME];
263
+ if (!official || typeof official !== "object" || Array.isArray(official) || !isTrustedOfficialBaseUrl(
264
+ official.ANTHROPIC_BASE_URL
265
+ )) {
266
+ throw new TypeError(
267
+ `The protected '${OFFICIAL_ENV_NAME}' environment must use the trusted official root URL`
268
+ );
269
+ }
270
+ }
271
+ function assertClaudeEnvironmentAuthBoundary(envName, baseUrl, decryptedAuthToken) {
272
+ if (envName === OFFICIAL_ENV_NAME) {
273
+ if (!isTrustedOfficialBaseUrl(baseUrl)) {
274
+ throw new TypeError(
275
+ `The protected '${OFFICIAL_ENV_NAME}' environment must use the trusted official root URL`
276
+ );
277
+ }
278
+ return;
279
+ }
280
+ if (!decryptedAuthToken?.trim()) {
281
+ throw new TypeError(
282
+ `Environment '${envName ?? "<unknown>"}' requires an auth token; OAuth is only allowed for '${OFFICIAL_ENV_NAME}'`
283
+ );
284
+ }
285
+ }
286
+ var TIER_MODEL_ALIASES = /* @__PURE__ */ new Set(["opus", "sonnet", "haiku"]);
18
287
  var LEGACY_OFFICIAL_MODEL_PIN = "claude-opus-4-1-20250805";
19
288
  var LEGACY_OFFICIAL_HAIKU_PIN = "claude-3-5-haiku-20241022";
20
289
  var OFFICIAL_RUNTIME_ALIAS = "opus";
@@ -48,6 +317,26 @@ function normalizeEnvConfig(envConfig, defaultRuntimeModel = "opus") {
48
317
  }
49
318
  };
50
319
  }
320
+ function normalizeCcemConfig(config3) {
321
+ const normalized = {
322
+ registries: Object.fromEntries(
323
+ Object.entries(config3.registries ?? {}).map(([name, env]) => [
324
+ name,
325
+ normalizeEnvConfig(env)
326
+ ])
327
+ )
328
+ };
329
+ if (config3.current !== void 0) {
330
+ normalized.current = config3.current;
331
+ }
332
+ if (config3.defaultMode !== void 0) {
333
+ normalized.defaultMode = config3.defaultMode;
334
+ }
335
+ if (config3.router !== void 0) {
336
+ normalized.router = normalizeRouterConfig(config3.router);
337
+ }
338
+ return normalized;
339
+ }
51
340
  function shouldRecoverTierModel(model) {
52
341
  return !model || TIER_MODEL_ALIASES.has(model);
53
342
  }
@@ -75,7 +364,7 @@ function recoverEnvConfigFromLegacy(currentEnvConfig, legacyEnvConfig) {
75
364
  }
76
365
  function resolveEnvConfigForRuntime(envName, envConfig) {
77
366
  const resolved = { ...envConfig };
78
- const hasUntouchedLegacyOfficialPins = envName === OFFICIAL_ENV_NAME && resolved.ANTHROPIC_BASE_URL === OFFICIAL_BASE_URL && resolved.ANTHROPIC_DEFAULT_OPUS_MODEL === LEGACY_OFFICIAL_MODEL_PIN && resolved.ANTHROPIC_DEFAULT_SONNET_MODEL === LEGACY_OFFICIAL_MODEL_PIN && resolved.ANTHROPIC_DEFAULT_HAIKU_MODEL === LEGACY_OFFICIAL_HAIKU_PIN && resolved.ANTHROPIC_MODEL === OFFICIAL_RUNTIME_ALIAS && resolved.CLAUDE_CODE_SUBAGENT_MODEL === void 0;
367
+ const hasUntouchedLegacyOfficialPins = envName === OFFICIAL_ENV_NAME && isTrustedOfficialBaseUrl(resolved.ANTHROPIC_BASE_URL) && resolved.ANTHROPIC_DEFAULT_OPUS_MODEL === LEGACY_OFFICIAL_MODEL_PIN && resolved.ANTHROPIC_DEFAULT_SONNET_MODEL === LEGACY_OFFICIAL_MODEL_PIN && resolved.ANTHROPIC_DEFAULT_HAIKU_MODEL === LEGACY_OFFICIAL_HAIKU_PIN && resolved.ANTHROPIC_MODEL === OFFICIAL_RUNTIME_ALIAS && resolved.CLAUDE_CODE_SUBAGENT_MODEL === void 0;
79
368
  if (hasUntouchedLegacyOfficialPins) {
80
369
  delete resolved.ANTHROPIC_DEFAULT_OPUS_MODEL;
81
370
  delete resolved.ANTHROPIC_DEFAULT_SONNET_MODEL;
@@ -510,7 +799,10 @@ var getCcemConfigPath = () => {
510
799
  var ensureCcemDir = () => {
511
800
  const ccemDir = getCcemConfigDir();
512
801
  if (!fs.existsSync(ccemDir)) {
513
- fs.mkdirSync(ccemDir, { recursive: true });
802
+ fs.mkdirSync(ccemDir, { recursive: true, mode: 448 });
803
+ }
804
+ if (process.platform !== "win32") {
805
+ fs.chmodSync(ccemDir, 448);
514
806
  }
515
807
  return ccemDir;
516
808
  };
@@ -1020,10 +1312,10 @@ var renderLogoWithEnvPanel = (envName, env, defaultMode) => {
1020
1312
  const parsed = new URL(url);
1021
1313
  const protocol = parsed.protocol + "//";
1022
1314
  const host = parsed.host;
1023
- const path10 = parsed.pathname + parsed.search;
1315
+ const path11 = parsed.pathname + parsed.search;
1024
1316
  const hostStart = host.slice(0, 8);
1025
1317
  const hostEnd = host.slice(-4);
1026
- const pathPart = path10.length > 10 ? path10.slice(0, 7) + "..." : path10;
1318
+ const pathPart = path11.length > 10 ? path11.slice(0, 7) + "..." : path11;
1027
1319
  return `${protocol}${hostStart}...${hostEnd}${pathPart}`;
1028
1320
  } catch {
1029
1321
  return truncate(url, max);
@@ -1867,11 +2159,19 @@ var MANAGED_CLAUDE_ENV_KEYS = [
1867
2159
  "ANTHROPIC_API_KEY",
1868
2160
  "ANTHROPIC_SMALL_FAST_MODEL"
1869
2161
  ];
1870
- function buildEnvVars(envName, envConfig) {
2162
+ function buildEnvVars(envName, envConfig, options = {}) {
1871
2163
  const runtimeEnv = resolveEnvConfigForRuntime(envName, envConfig);
2164
+ const authToken = runtimeEnv.ANTHROPIC_AUTH_TOKEN ? decrypt(runtimeEnv.ANTHROPIC_AUTH_TOKEN) : void 0;
2165
+ if (!options.allowDesktopProxyOverride || !isTrustedDesktopProxyBaseUrl(runtimeEnv.ANTHROPIC_BASE_URL)) {
2166
+ assertClaudeEnvironmentAuthBoundary(
2167
+ envName,
2168
+ runtimeEnv.ANTHROPIC_BASE_URL,
2169
+ authToken
2170
+ );
2171
+ }
1872
2172
  const vars = {};
1873
2173
  if (runtimeEnv.ANTHROPIC_BASE_URL) vars.ANTHROPIC_BASE_URL = runtimeEnv.ANTHROPIC_BASE_URL;
1874
- if (runtimeEnv.ANTHROPIC_AUTH_TOKEN) vars.ANTHROPIC_AUTH_TOKEN = decrypt(runtimeEnv.ANTHROPIC_AUTH_TOKEN);
2174
+ if (authToken) vars.ANTHROPIC_AUTH_TOKEN = authToken;
1875
2175
  if (runtimeEnv.ANTHROPIC_DEFAULT_OPUS_MODEL) vars.ANTHROPIC_DEFAULT_OPUS_MODEL = runtimeEnv.ANTHROPIC_DEFAULT_OPUS_MODEL;
1876
2176
  if (runtimeEnv.ANTHROPIC_DEFAULT_SONNET_MODEL) vars.ANTHROPIC_DEFAULT_SONNET_MODEL = runtimeEnv.ANTHROPIC_DEFAULT_SONNET_MODEL;
1877
2177
  if (runtimeEnv.ANTHROPIC_DEFAULT_HAIKU_MODEL) vars.ANTHROPIC_DEFAULT_HAIKU_MODEL = runtimeEnv.ANTHROPIC_DEFAULT_HAIKU_MODEL;
@@ -1879,6 +2179,15 @@ function buildEnvVars(envName, envConfig) {
1879
2179
  if (runtimeEnv.CLAUDE_CODE_SUBAGENT_MODEL) vars.CLAUDE_CODE_SUBAGENT_MODEL = runtimeEnv.CLAUDE_CODE_SUBAGENT_MODEL;
1880
2180
  return vars;
1881
2181
  }
2182
+ function isTrustedDesktopProxyBaseUrl(value) {
2183
+ if (!value) return false;
2184
+ try {
2185
+ const url = new URL(value);
2186
+ return url.protocol === "http:" && url.hostname === "127.0.0.1" && !url.username && !url.password && !url.search && !url.hash && url.pathname.startsWith("/proxy/claude/");
2187
+ } catch {
2188
+ return false;
2189
+ }
2190
+ }
1882
2191
  function buildPermArgs(modeName) {
1883
2192
  const preset = PERMISSION_PRESETS[modeName];
1884
2193
  if (!preset) return [];
@@ -1900,14 +2209,23 @@ function ensureSessionsDir() {
1900
2209
  return dir;
1901
2210
  }
1902
2211
  async function launchClaude(options) {
1903
- const { envName, envConfig, permMode, workingDir, sessionId, resumeSessionId, silent } = options;
2212
+ const {
2213
+ envName,
2214
+ envConfig,
2215
+ permMode,
2216
+ workingDir,
2217
+ sessionId,
2218
+ resumeSessionId,
2219
+ silent,
2220
+ allowDesktopProxyOverride
2221
+ } = options;
1904
2222
  const ccemRuntimeId = sessionId ?? `cli-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
1905
2223
  const env = { ...process.env };
1906
2224
  for (const key of MANAGED_CLAUDE_ENV_KEYS) {
1907
2225
  delete env[key];
1908
2226
  }
1909
2227
  if (envConfig) {
1910
- Object.assign(env, buildEnvVars(envName, envConfig));
2228
+ Object.assign(env, buildEnvVars(envName, envConfig, { allowDesktopProxyOverride }));
1911
2229
  }
1912
2230
  delete env.CLAUDECODE;
1913
2231
  env.CCEM_RUNTIME_ID = ccemRuntimeId;
@@ -2141,130 +2459,617 @@ var runWithTempPermissions = async (modeName, envConfig, envName) => {
2141
2459
  await launchClaude({ envConfig, envName, permMode: modeName });
2142
2460
  };
2143
2461
 
2144
- // src/setup.ts
2462
+ // src/environmentMutations.ts
2463
+ import fs8 from "fs";
2464
+ import path7 from "path";
2465
+
2466
+ // src/desktopControl.ts
2145
2467
  import fs7 from "fs";
2146
- import chalk4 from "chalk";
2147
- import { spawn as spawn2 } from "child_process";
2148
- var readJsonFile = (filePath) => {
2149
- if (fs7.existsSync(filePath)) {
2150
- try {
2151
- const content = fs7.readFileSync(filePath, "utf-8");
2152
- return JSON.parse(content);
2153
- } catch {
2154
- console.warn(chalk4.yellow(`\u8B66\u544A: \u65E0\u6CD5\u89E3\u6790 ${filePath}`));
2155
- return {};
2468
+ import path6 from "path";
2469
+ var DEFAULT_REQUEST_TIMEOUT_MS = 5e3;
2470
+ var LOOPBACK_HOSTS = /* @__PURE__ */ new Set(["127.0.0.1", "localhost", "::1", "[::1]"]);
2471
+ var ENDPOINT_UNREACHABLE_CODES = /* @__PURE__ */ new Set([
2472
+ "ECONNREFUSED",
2473
+ "ECONNRESET",
2474
+ "ENOTCONN",
2475
+ "EHOSTUNREACH",
2476
+ "ECONNABORTED"
2477
+ ]);
2478
+ var ROUTER_BINDING_KEY = /^(?:background|subagent:\*|subagent:[A-Za-z0-9._:-]{1,128})$/;
2479
+ var StaleDesktopControlDescriptorError = class extends Error {
2480
+ name = "StaleDesktopControlDescriptorError";
2481
+ reason;
2482
+ descriptorPath;
2483
+ pid;
2484
+ cleanedUp;
2485
+ cause;
2486
+ constructor(details) {
2487
+ const subject = details.pid !== null ? `process ${details.pid}` : "the publishing process";
2488
+ const symptom = details.reason === "dead-pid" ? `${subject} is no longer running` : details.reason === "endpoint-unreachable" ? "the control endpoint refused the connection" : `the control request timed out after ${details.timeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS}ms`;
2489
+ const remedy = details.cleanedUp ? "The stale descriptor was removed automatically; start CCEM Desktop and rerun the command." : details.pid !== null ? "Restart CCEM Desktop so it republishes a fresh control endpoint." : "Restart CCEM Desktop to refresh the descriptor, or remove the stale file manually if it is no longer managed.";
2490
+ super(
2491
+ `CCEM Desktop control descriptor at ${details.descriptorPath} is stale: ${symptom}. ${remedy}`
2492
+ );
2493
+ this.reason = details.reason;
2494
+ this.descriptorPath = details.descriptorPath;
2495
+ this.pid = details.pid;
2496
+ this.cleanedUp = details.cleanedUp;
2497
+ if (details.cause !== void 0) {
2498
+ this.cause = details.cause;
2156
2499
  }
2157
2500
  }
2158
- return {};
2159
2501
  };
2160
- var writeJsonFile = (filePath, data) => {
2161
- fs7.writeFileSync(filePath, JSON.stringify(data, null, 2) + "\n");
2502
+ var DesktopControlRpcError = class extends Error {
2503
+ code;
2504
+ data;
2505
+ constructor(message, code, data) {
2506
+ super(message);
2507
+ this.name = "DesktopControlRpcError";
2508
+ this.code = code;
2509
+ this.data = data;
2510
+ }
2162
2511
  };
2163
- var setupOnboarding = () => {
2164
- const configPath = getGlobalClaudeConfigPath();
2512
+ function getDesktopControlDescriptorPath() {
2513
+ return process.env.CCEM_CONTROL_FILE?.trim() || getDefaultControlDescriptorPath();
2514
+ }
2515
+ function getDefaultControlDescriptorPath() {
2516
+ return path6.join(getCcemConfigDir(), "control.json");
2517
+ }
2518
+ function isDefaultDescriptorPath(descriptorPath) {
2165
2519
  try {
2166
- const config3 = readJsonFile(configPath);
2167
- if (config3.hasCompletedOnboarding === true) {
2168
- console.log(chalk4.gray(" \u2713 hasCompletedOnboarding \u5DF2\u8BBE\u7F6E"));
2169
- return true;
2170
- }
2171
- config3.hasCompletedOnboarding = true;
2172
- writeJsonFile(configPath, config3);
2173
- console.log(chalk4.green(" \u2713 \u5DF2\u8BBE\u7F6E hasCompletedOnboarding: true"));
2174
- return true;
2175
- } catch (err) {
2176
- console.error(chalk4.red(` \u2717 \u8BBE\u7F6E hasCompletedOnboarding \u5931\u8D25: ${err}`));
2520
+ return path6.resolve(descriptorPath) === path6.resolve(getDefaultControlDescriptorPath());
2521
+ } catch {
2522
+ return false;
2523
+ }
2524
+ }
2525
+ function safeRemoveStaleDescriptor(descriptorPath) {
2526
+ if (!isDefaultDescriptorPath(descriptorPath)) {
2177
2527
  return false;
2178
2528
  }
2179
- };
2180
- var setupEnvSettings = () => {
2181
- const settingsPath = getGlobalClaudeSettingsPath();
2182
2529
  try {
2183
- ensureGlobalClaudeDir();
2184
- const settings = readJsonFile(settingsPath);
2185
- if (!settings.env || typeof settings.env !== "object") {
2186
- settings.env = {};
2187
- }
2188
- const env = settings.env;
2189
- const envVars = {
2190
- "DISABLE_BUG_COMMAND": "1",
2191
- "DISABLE_ERROR_REPORTING": "1",
2192
- "DISABLE_TELEMETRY": "1"
2193
- };
2194
- let changed = false;
2195
- for (const [key, value] of Object.entries(envVars)) {
2196
- if (env[key] !== value) {
2197
- env[key] = value;
2198
- changed = true;
2199
- }
2200
- }
2201
- if (!changed) {
2202
- console.log(chalk4.gray(" \u2713 \u73AF\u5883\u53D8\u91CF\u5DF2\u914D\u7F6E"));
2203
- return true;
2204
- }
2205
- writeJsonFile(settingsPath, settings);
2206
- console.log(chalk4.green(" \u2713 \u5DF2\u914D\u7F6E\u73AF\u5883\u53D8\u91CF:"));
2207
- console.log(chalk4.gray(" DISABLE_BUG_COMMAND=1"));
2208
- console.log(chalk4.gray(" DISABLE_ERROR_REPORTING=1"));
2209
- console.log(chalk4.gray(" DISABLE_TELEMETRY=1"));
2530
+ fs7.rmSync(descriptorPath);
2210
2531
  return true;
2211
- } catch (err) {
2212
- console.error(chalk4.red(` \u2717 \u8BBE\u7F6E\u73AF\u5883\u53D8\u91CF\u5931\u8D25: ${err}`));
2532
+ } catch {
2213
2533
  return false;
2214
2534
  }
2215
- };
2216
- var setupMcpTool = () => {
2217
- return new Promise((resolve4) => {
2218
- console.log(chalk4.cyan(" \u2192 \u6B63\u5728\u6DFB\u52A0 chrome-devtools MCP \u5DE5\u5177..."));
2219
- const child = spawn2("claude", [
2220
- "mcp",
2221
- "add",
2222
- "chrome-devtools",
2223
- "npx",
2224
- "chrome-devtools-mcp@latest",
2225
- "--scope",
2226
- "user"
2227
- ], {
2228
- stdio: "pipe",
2229
- shell: true
2230
- });
2231
- let stdout = "";
2232
- let stderr = "";
2233
- child.stdout?.on("data", (data) => {
2234
- stdout += data.toString();
2235
- });
2236
- child.stderr?.on("data", (data) => {
2237
- stderr += data.toString();
2238
- });
2239
- child.on("exit", (code) => {
2240
- if (code === 0) {
2241
- console.log(chalk4.green(" \u2713 \u5DF2\u6DFB\u52A0 chrome-devtools MCP \u5DE5\u5177"));
2242
- resolve4(true);
2243
- } else {
2244
- if (stderr.includes("already exists") || stdout.includes("already exists")) {
2245
- console.log(chalk4.gray(" \u2713 chrome-devtools MCP \u5DE5\u5177\u5DF2\u5B58\u5728"));
2246
- resolve4(true);
2247
- } else {
2248
- console.error(chalk4.red(` \u2717 \u6DFB\u52A0 MCP \u5DE5\u5177\u5931\u8D25 (code: ${code})`));
2249
- if (stderr) console.error(chalk4.gray(` ${stderr.trim()}`));
2250
- resolve4(false);
2251
- }
2252
- }
2253
- });
2254
- child.on("error", (err) => {
2255
- console.error(chalk4.red(` \u2717 \u6267\u884C claude \u547D\u4EE4\u5931\u8D25: ${err.message}`));
2256
- console.log(chalk4.yellow(" \u8BF7\u786E\u4FDD\u5DF2\u5B89\u88C5 Claude Code CLI"));
2257
- resolve4(false);
2258
- });
2259
- });
2260
- };
2261
- var runSetupInit = async (options = {}) => {
2262
- console.log(chalk4.bold("\n\u{1F527} Claude Code \u521D\u59CB\u5316\u8BBE\u7F6E\n"));
2263
- console.log(chalk4.cyan("1. \u8BBE\u7F6E onboarding \u72B6\u6001"));
2264
- const step1 = setupOnboarding();
2265
- console.log(chalk4.cyan("\n2. \u914D\u7F6E\u9690\u79C1\u8BBE\u7F6E"));
2266
- const step2 = setupEnvSettings();
2267
- let step3 = true;
2535
+ }
2536
+ function readErrnoCode(error) {
2537
+ if (!error || typeof error !== "object") return void 0;
2538
+ const candidate = error;
2539
+ return candidate.code ?? candidate.cause?.code;
2540
+ }
2541
+ function readPid(value) {
2542
+ return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : null;
2543
+ }
2544
+ function isLoopbackHost(host) {
2545
+ const normalized = host.trim().toLowerCase().replace(/^\[|\]$/g, "");
2546
+ if (LOOPBACK_HOSTS.has(normalized)) {
2547
+ return true;
2548
+ }
2549
+ if (/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(normalized)) {
2550
+ return true;
2551
+ }
2552
+ if (normalized === "::1" || normalized === "0:0:0:0:0:0:0:1") {
2553
+ return true;
2554
+ }
2555
+ return false;
2556
+ }
2557
+ function extractHost(endpoint) {
2558
+ const withoutScheme = endpoint.replace(/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//, "");
2559
+ const hostPort = withoutScheme.split(/[\/?#]/)[0] || "";
2560
+ if (hostPort.startsWith("[")) {
2561
+ const end = hostPort.indexOf("]");
2562
+ if (end === -1) return null;
2563
+ return hostPort.slice(1, end);
2564
+ }
2565
+ const colonIndex = hostPort.lastIndexOf(":");
2566
+ if (colonIndex === -1) return hostPort;
2567
+ return hostPort.slice(0, colonIndex);
2568
+ }
2569
+ function validateLoopbackEndpoint(endpoint) {
2570
+ const host = extractHost(endpoint);
2571
+ if (!host) {
2572
+ throw new Error(
2573
+ `CCEM Desktop control endpoint '${redactEndpoint(endpoint)}' is missing a host. Refusing to continue.`
2574
+ );
2575
+ }
2576
+ if (!isLoopbackHost(host)) {
2577
+ throw new Error(
2578
+ `CCEM Desktop control endpoint '${redactEndpoint(endpoint)}' is not bound to loopback. Only 127.0.0.1, localhost, or ::1 are allowed.`
2579
+ );
2580
+ }
2581
+ }
2582
+ function isPidAlive(pid) {
2583
+ if (!Number.isFinite(pid) || pid <= 0) return false;
2584
+ try {
2585
+ process.kill(pid, 0);
2586
+ return true;
2587
+ } catch (error) {
2588
+ const code = error.code;
2589
+ if (code === "ESRCH") return false;
2590
+ if (code === "EPERM") return true;
2591
+ return false;
2592
+ }
2593
+ }
2594
+ function redactEndpoint(endpoint) {
2595
+ try {
2596
+ const url = new URL(endpoint);
2597
+ return `${url.protocol}//${url.host}${url.pathname}`;
2598
+ } catch {
2599
+ return "<invalid endpoint>";
2600
+ }
2601
+ }
2602
+ function isDescriptor(value) {
2603
+ return Boolean(
2604
+ value && typeof value === "object" && typeof value.endpoint === "string" && typeof value.token === "string"
2605
+ );
2606
+ }
2607
+ function resolveDesktopControlDescriptor(descriptorPath = getDesktopControlDescriptorPath()) {
2608
+ if (!fs7.existsSync(descriptorPath)) {
2609
+ throw new Error(`CCEM Desktop control endpoint not found at ${descriptorPath}. Start CCEM Desktop first.`);
2610
+ }
2611
+ const parsed = JSON.parse(fs7.readFileSync(descriptorPath, "utf-8"));
2612
+ const endpoint = parsed.endpoint?.trim();
2613
+ const token = parsed.token?.trim();
2614
+ if (!endpoint || !token) {
2615
+ throw new Error(`Invalid CCEM Desktop control descriptor at ${descriptorPath}`);
2616
+ }
2617
+ validateLoopbackEndpoint(endpoint);
2618
+ const pid = readPid(parsed.pid);
2619
+ if (pid !== null && !isPidAlive(pid)) {
2620
+ const cleanedUp = safeRemoveStaleDescriptor(descriptorPath);
2621
+ throw new StaleDesktopControlDescriptorError({
2622
+ reason: "dead-pid",
2623
+ descriptorPath,
2624
+ pid,
2625
+ cleanedUp
2626
+ });
2627
+ }
2628
+ return { endpoint, token, pid };
2629
+ }
2630
+ async function requestDesktopControl(method, params, descriptorOrOptions, maybeOptions = {}) {
2631
+ const descriptorPath = getDesktopControlDescriptorPath();
2632
+ const hasInjectedDescriptor = isDescriptor(descriptorOrOptions);
2633
+ const descriptor = hasInjectedDescriptor ? descriptorOrOptions : resolveDesktopControlDescriptor(descriptorPath);
2634
+ const options = hasInjectedDescriptor ? maybeOptions : descriptorOrOptions ?? maybeOptions ?? {};
2635
+ const timeoutMs = options.timeoutMs ?? options.fetchTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
2636
+ const pid = readPid(descriptor.pid);
2637
+ validateLoopbackEndpoint(descriptor.endpoint);
2638
+ if (pid !== null && !isPidAlive(pid)) {
2639
+ const cleanedUp = hasInjectedDescriptor ? false : safeRemoveStaleDescriptor(descriptorPath);
2640
+ throw new StaleDesktopControlDescriptorError({
2641
+ reason: "dead-pid",
2642
+ descriptorPath,
2643
+ pid,
2644
+ cleanedUp
2645
+ });
2646
+ }
2647
+ const id = `ccem-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
2648
+ const controller = new AbortController();
2649
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
2650
+ const externalSignal = options.signal;
2651
+ const onExternalAbort = () => controller.abort();
2652
+ if (externalSignal) {
2653
+ if (externalSignal.aborted) {
2654
+ clearTimeout(timer);
2655
+ controller.abort();
2656
+ } else {
2657
+ externalSignal.addEventListener("abort", onExternalAbort, { once: true });
2658
+ }
2659
+ }
2660
+ let response;
2661
+ try {
2662
+ response = await fetch(descriptor.endpoint, {
2663
+ method: "POST",
2664
+ headers: {
2665
+ authorization: `Bearer ${descriptor.token}`,
2666
+ "content-type": "application/json"
2667
+ },
2668
+ body: JSON.stringify({
2669
+ jsonrpc: "2.0",
2670
+ id,
2671
+ method,
2672
+ params: params ?? {}
2673
+ }),
2674
+ signal: controller.signal
2675
+ });
2676
+ } catch (error) {
2677
+ if (controller.signal.aborted) {
2678
+ throw new StaleDesktopControlDescriptorError({
2679
+ reason: "request-timeout",
2680
+ descriptorPath,
2681
+ pid,
2682
+ cleanedUp: false,
2683
+ timeoutMs,
2684
+ cause: error
2685
+ });
2686
+ }
2687
+ const code = readErrnoCode(error);
2688
+ if (code && ENDPOINT_UNREACHABLE_CODES.has(code)) {
2689
+ throw new StaleDesktopControlDescriptorError({
2690
+ reason: "endpoint-unreachable",
2691
+ descriptorPath,
2692
+ pid,
2693
+ cleanedUp: false,
2694
+ cause: error
2695
+ });
2696
+ }
2697
+ throw error;
2698
+ } finally {
2699
+ clearTimeout(timer);
2700
+ if (externalSignal) {
2701
+ externalSignal.removeEventListener("abort", onExternalAbort);
2702
+ }
2703
+ }
2704
+ if (!response.ok) {
2705
+ throw new Error(`CCEM Desktop control request failed: HTTP ${response.status}`);
2706
+ }
2707
+ const payload = await response.json();
2708
+ if (payload.error) {
2709
+ throw new DesktopControlRpcError(
2710
+ payload.error.message || `CCEM Desktop control error ${payload.error.code ?? ""}`.trim(),
2711
+ payload.error.code,
2712
+ payload.error.data
2713
+ );
2714
+ }
2715
+ return payload.result;
2716
+ }
2717
+ function parseSinceOption(raw) {
2718
+ if (raw === void 0 || raw === null || raw === "") return null;
2719
+ const value = Number(raw);
2720
+ if (!Number.isFinite(value) || value < 0 || !Number.isInteger(value)) {
2721
+ throw new Error(
2722
+ `Invalid --since value '${raw}'. Expected a non-negative integer sequence number (e.g. 0, 42).`
2723
+ );
2724
+ }
2725
+ return value;
2726
+ }
2727
+ function parseLimitOption(raw) {
2728
+ if (raw === void 0 || raw === null || raw === "") return null;
2729
+ const value = Number(raw);
2730
+ if (!Number.isFinite(value) || value <= 0 || !Number.isInteger(value)) {
2731
+ throw new Error(
2732
+ `Invalid --limit value '${raw}'. Expected a positive integer (e.g. 1, 100).`
2733
+ );
2734
+ }
2735
+ return value;
2736
+ }
2737
+ function parseRouteBinding(raw, optionName) {
2738
+ const separator = raw.indexOf("=");
2739
+ const key = separator > 0 ? raw.slice(0, separator).trim() : "";
2740
+ const env = separator > 0 ? raw.slice(separator + 1).trim() : "";
2741
+ if (!key || !env) {
2742
+ throw new Error(`Invalid ${optionName} value '${raw}'. Expected key=env.`);
2743
+ }
2744
+ if (!ROUTER_BINDING_KEY.test(key)) {
2745
+ throw new Error(
2746
+ `Invalid route key '${key}' in ${optionName}. Expected background, subagent:*, or subagent:<safe-agent-name>.`
2747
+ );
2748
+ }
2749
+ return { key, env };
2750
+ }
2751
+ function parseRoutesJson(raw) {
2752
+ let parsed;
2753
+ try {
2754
+ parsed = JSON.parse(raw);
2755
+ } catch {
2756
+ throw new Error("Invalid --routes-json. Expected a JSON object of key-to-environment bindings.");
2757
+ }
2758
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
2759
+ throw new Error("Invalid --routes-json. Expected a JSON object of key-to-environment bindings.");
2760
+ }
2761
+ const routes = {};
2762
+ for (const [key, value] of Object.entries(parsed)) {
2763
+ if (typeof value !== "string") {
2764
+ throw new Error("Invalid --routes-json. Expected a JSON object of key-to-environment bindings.");
2765
+ }
2766
+ const binding = parseRouteBinding(`${key}=${value}`, "--route");
2767
+ routes[binding.key] = binding.env;
2768
+ }
2769
+ return routes;
2770
+ }
2771
+ function parseDesktopRoutes(routeValues = [], routesJson) {
2772
+ if (routesJson === void 0 && routeValues.length === 0) {
2773
+ return void 0;
2774
+ }
2775
+ const routes = routesJson === void 0 ? {} : parseRoutesJson(routesJson);
2776
+ for (const raw of routeValues) {
2777
+ const binding = parseRouteBinding(raw, "--route");
2778
+ routes[binding.key] = binding.env;
2779
+ }
2780
+ return routes;
2781
+ }
2782
+ function isDesktopSessionRouterState(value) {
2783
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
2784
+ const state = value;
2785
+ if (!Number.isSafeInteger(state.revision) || state.revision < 0) return false;
2786
+ if (!state.bindings || typeof state.bindings !== "object" || Array.isArray(state.bindings)) return false;
2787
+ if (!Object.entries(state.bindings).every(([key, env]) => key.trim() && typeof env === "string")) {
2788
+ return false;
2789
+ }
2790
+ return Array.isArray(state.allowedEnvs) && state.allowedEnvs.every((env) => typeof env === "string");
2791
+ }
2792
+ function buildDesktopRouterUpdateParams(runtimeId, current, setValue) {
2793
+ if (!isDesktopSessionRouterState(current)) {
2794
+ throw new Error("Invalid router state returned by CCEM Desktop.");
2795
+ }
2796
+ const binding = parseRouteBinding(setValue, "--set");
2797
+ const bindings = { ...current.bindings, [binding.key]: binding.env };
2798
+ const allowedEnvs = current.allowedEnvs.includes(binding.env) ? [...current.allowedEnvs] : [...current.allowedEnvs, binding.env];
2799
+ return {
2800
+ runtimeId,
2801
+ expectedRevision: current.revision,
2802
+ patch: { bindings, allowedEnvs }
2803
+ };
2804
+ }
2805
+ async function getOrUpdateDesktopRoutes(runtimeId, setValue, requester = requestDesktopControl) {
2806
+ const current = await requester("ccem.workspace.getRouter", { runtimeId });
2807
+ if (setValue === void 0) {
2808
+ return current;
2809
+ }
2810
+ const update = buildDesktopRouterUpdateParams(runtimeId, current, setValue);
2811
+ return requester("ccem.workspace.updateRouter", update);
2812
+ }
2813
+ function isNullableString(value) {
2814
+ return value === null || typeof value === "string";
2815
+ }
2816
+ function isDesktopEnvironmentRenameResult(value) {
2817
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
2818
+ const result = value;
2819
+ return result.ok === true && result.operation === "rename" && typeof result.oldName === "string" && typeof result.newName === "string" && Number.isSafeInteger(result.updatedSessions) && result.updatedSessions >= 0 && isNullableString(result.current);
2820
+ }
2821
+ function isDesktopEnvironmentDeleteResult(value) {
2822
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
2823
+ const result = value;
2824
+ return result.ok === true && result.operation === "delete" && typeof result.name === "string" && isNullableString(result.current);
2825
+ }
2826
+ async function renameDesktopEnvironment(oldName, newName, requester = requestDesktopControl) {
2827
+ const result = await requester("ccem.environment.rename", { oldName, newName });
2828
+ if (!isDesktopEnvironmentRenameResult(result)) {
2829
+ throw new Error("Invalid environment mutation response from CCEM Desktop.");
2830
+ }
2831
+ return result;
2832
+ }
2833
+ async function deleteDesktopEnvironment(name, requester = requestDesktopControl) {
2834
+ const result = await requester("ccem.environment.delete", { name });
2835
+ if (!isDesktopEnvironmentDeleteResult(result)) {
2836
+ throw new Error("Invalid environment mutation response from CCEM Desktop.");
2837
+ }
2838
+ return result;
2839
+ }
2840
+ function printJson(value) {
2841
+ console.log(JSON.stringify(value, null, 2));
2842
+ }
2843
+
2844
+ // src/environmentMutations.ts
2845
+ function nativeRuntimeStatePath() {
2846
+ return path7.join(getCcemConfigDir(), "native-runtime-state.json");
2847
+ }
2848
+ function resolveMutationAuthority(options) {
2849
+ const descriptorExists = options.descriptorExists ?? (() => fs8.existsSync(getDesktopControlDescriptorPath()));
2850
+ const stateExists = options.stateExists ?? (() => fs8.existsSync(nativeRuntimeStatePath()));
2851
+ return { descriptorExists, stateExists };
2852
+ }
2853
+ function assertOfflineMutationIsSafe(name, stateExists) {
2854
+ if (stateExists()) {
2855
+ throw new Error(
2856
+ `CCEM Desktop is required to update active or recoverable native sessions before changing environment '${name}'. Start CCEM Desktop and retry.`
2857
+ );
2858
+ }
2859
+ }
2860
+ function resolveLocalConfig(source) {
2861
+ return typeof source === "function" ? source() : source;
2862
+ }
2863
+ async function renameEnvironmentWithAuthority(config3, oldName, newName, options = {}) {
2864
+ const authority = resolveMutationAuthority(options);
2865
+ if (authority.descriptorExists()) {
2866
+ const renameRemote = options.renameRemote ?? renameDesktopEnvironment;
2867
+ return {
2868
+ authority: "desktop",
2869
+ result: await renameRemote(oldName, newName)
2870
+ };
2871
+ }
2872
+ assertOfflineMutationIsSafe(oldName, authority.stateExists);
2873
+ return {
2874
+ authority: "local",
2875
+ config: renameEnvironmentInConfig(resolveLocalConfig(config3), oldName, newName)
2876
+ };
2877
+ }
2878
+ async function deleteEnvironmentWithAuthority(config3, name, options = {}) {
2879
+ const authority = resolveMutationAuthority(options);
2880
+ if (authority.descriptorExists()) {
2881
+ const deleteRemote = options.deleteRemote ?? deleteDesktopEnvironment;
2882
+ return {
2883
+ authority: "desktop",
2884
+ result: await deleteRemote(name)
2885
+ };
2886
+ }
2887
+ assertOfflineMutationIsSafe(name, authority.stateExists);
2888
+ return {
2889
+ authority: "local",
2890
+ config: deleteEnvironmentFromConfig(resolveLocalConfig(config3), name)
2891
+ };
2892
+ }
2893
+ function validateRename(config3, oldName, newName) {
2894
+ if (!Object.prototype.hasOwnProperty.call(config3.registries, oldName)) {
2895
+ throw new Error(`Environment '${oldName}' not found.`);
2896
+ }
2897
+ if (!newName.trim()) {
2898
+ throw new Error("Environment name cannot be empty.");
2899
+ }
2900
+ if (Object.prototype.hasOwnProperty.call(config3.registries, newName)) {
2901
+ throw new Error(`Environment '${newName}' already exists.`);
2902
+ }
2903
+ if (oldName === OFFICIAL_ENV_NAME) {
2904
+ throw new Error(`Cannot rename the protected '${OFFICIAL_ENV_NAME}' environment.`);
2905
+ }
2906
+ }
2907
+ function renameEnvironmentInConfig(config3, oldName, newName) {
2908
+ assertOfficialEnvironmentInvariant(config3.registries);
2909
+ validateRename(config3, oldName, newName);
2910
+ const registries = { ...config3.registries };
2911
+ registries[newName] = registries[oldName];
2912
+ delete registries[oldName];
2913
+ const next = {
2914
+ ...config3,
2915
+ registries,
2916
+ current: config3.current === oldName ? newName : config3.current,
2917
+ ...config3.router && {
2918
+ router: renameRouterEnvironmentReferences(config3.router, oldName, newName)
2919
+ }
2920
+ };
2921
+ assertOfficialEnvironmentInvariant(next.registries);
2922
+ return next;
2923
+ }
2924
+ function deleteEnvironmentFromConfig(config3, name) {
2925
+ assertOfficialEnvironmentInvariant(config3.registries);
2926
+ if (!Object.prototype.hasOwnProperty.call(config3.registries, name)) {
2927
+ throw new Error(`Environment '${name}' not found.`);
2928
+ }
2929
+ if (name === OFFICIAL_ENV_NAME) {
2930
+ throw new Error(`Cannot delete the protected '${OFFICIAL_ENV_NAME}' environment.`);
2931
+ }
2932
+ const references = findRouterEnvironmentReferences(config3.router, name);
2933
+ if (references.length > 0) {
2934
+ throw new Error(
2935
+ `Environment '${name}' is referenced by router config: ${references.join(", ")}`
2936
+ );
2937
+ }
2938
+ const registries = { ...config3.registries };
2939
+ delete registries[name];
2940
+ const next = {
2941
+ ...config3,
2942
+ registries,
2943
+ current: config3.current === name ? OFFICIAL_ENV_NAME : config3.current
2944
+ };
2945
+ assertOfficialEnvironmentInvariant(next.registries);
2946
+ return next;
2947
+ }
2948
+
2949
+ // src/setup.ts
2950
+ import fs9 from "fs";
2951
+ import chalk4 from "chalk";
2952
+ import { spawn as spawn2 } from "child_process";
2953
+ var readJsonFile = (filePath) => {
2954
+ if (fs9.existsSync(filePath)) {
2955
+ try {
2956
+ const content = fs9.readFileSync(filePath, "utf-8");
2957
+ return JSON.parse(content);
2958
+ } catch {
2959
+ console.warn(chalk4.yellow(`\u8B66\u544A: \u65E0\u6CD5\u89E3\u6790 ${filePath}`));
2960
+ return {};
2961
+ }
2962
+ }
2963
+ return {};
2964
+ };
2965
+ var writeJsonFile = (filePath, data) => {
2966
+ fs9.writeFileSync(filePath, JSON.stringify(data, null, 2) + "\n");
2967
+ };
2968
+ var setupOnboarding = () => {
2969
+ const configPath = getGlobalClaudeConfigPath();
2970
+ try {
2971
+ const config3 = readJsonFile(configPath);
2972
+ if (config3.hasCompletedOnboarding === true) {
2973
+ console.log(chalk4.gray(" \u2713 hasCompletedOnboarding \u5DF2\u8BBE\u7F6E"));
2974
+ return true;
2975
+ }
2976
+ config3.hasCompletedOnboarding = true;
2977
+ writeJsonFile(configPath, config3);
2978
+ console.log(chalk4.green(" \u2713 \u5DF2\u8BBE\u7F6E hasCompletedOnboarding: true"));
2979
+ return true;
2980
+ } catch (err) {
2981
+ console.error(chalk4.red(` \u2717 \u8BBE\u7F6E hasCompletedOnboarding \u5931\u8D25: ${err}`));
2982
+ return false;
2983
+ }
2984
+ };
2985
+ var setupEnvSettings = () => {
2986
+ const settingsPath = getGlobalClaudeSettingsPath();
2987
+ try {
2988
+ ensureGlobalClaudeDir();
2989
+ const settings = readJsonFile(settingsPath);
2990
+ if (!settings.env || typeof settings.env !== "object") {
2991
+ settings.env = {};
2992
+ }
2993
+ const env = settings.env;
2994
+ const envVars = {
2995
+ "DISABLE_BUG_COMMAND": "1",
2996
+ "DISABLE_ERROR_REPORTING": "1",
2997
+ "DISABLE_TELEMETRY": "1"
2998
+ };
2999
+ let changed = false;
3000
+ for (const [key, value] of Object.entries(envVars)) {
3001
+ if (env[key] !== value) {
3002
+ env[key] = value;
3003
+ changed = true;
3004
+ }
3005
+ }
3006
+ if (!changed) {
3007
+ console.log(chalk4.gray(" \u2713 \u73AF\u5883\u53D8\u91CF\u5DF2\u914D\u7F6E"));
3008
+ return true;
3009
+ }
3010
+ writeJsonFile(settingsPath, settings);
3011
+ console.log(chalk4.green(" \u2713 \u5DF2\u914D\u7F6E\u73AF\u5883\u53D8\u91CF:"));
3012
+ console.log(chalk4.gray(" DISABLE_BUG_COMMAND=1"));
3013
+ console.log(chalk4.gray(" DISABLE_ERROR_REPORTING=1"));
3014
+ console.log(chalk4.gray(" DISABLE_TELEMETRY=1"));
3015
+ return true;
3016
+ } catch (err) {
3017
+ console.error(chalk4.red(` \u2717 \u8BBE\u7F6E\u73AF\u5883\u53D8\u91CF\u5931\u8D25: ${err}`));
3018
+ return false;
3019
+ }
3020
+ };
3021
+ var setupMcpTool = () => {
3022
+ return new Promise((resolve4) => {
3023
+ console.log(chalk4.cyan(" \u2192 \u6B63\u5728\u6DFB\u52A0 chrome-devtools MCP \u5DE5\u5177..."));
3024
+ const child = spawn2("claude", [
3025
+ "mcp",
3026
+ "add",
3027
+ "chrome-devtools",
3028
+ "npx",
3029
+ "chrome-devtools-mcp@latest",
3030
+ "--scope",
3031
+ "user"
3032
+ ], {
3033
+ stdio: "pipe",
3034
+ shell: true
3035
+ });
3036
+ let stdout = "";
3037
+ let stderr = "";
3038
+ child.stdout?.on("data", (data) => {
3039
+ stdout += data.toString();
3040
+ });
3041
+ child.stderr?.on("data", (data) => {
3042
+ stderr += data.toString();
3043
+ });
3044
+ child.on("exit", (code) => {
3045
+ if (code === 0) {
3046
+ console.log(chalk4.green(" \u2713 \u5DF2\u6DFB\u52A0 chrome-devtools MCP \u5DE5\u5177"));
3047
+ resolve4(true);
3048
+ } else {
3049
+ if (stderr.includes("already exists") || stdout.includes("already exists")) {
3050
+ console.log(chalk4.gray(" \u2713 chrome-devtools MCP \u5DE5\u5177\u5DF2\u5B58\u5728"));
3051
+ resolve4(true);
3052
+ } else {
3053
+ console.error(chalk4.red(` \u2717 \u6DFB\u52A0 MCP \u5DE5\u5177\u5931\u8D25 (code: ${code})`));
3054
+ if (stderr) console.error(chalk4.gray(` ${stderr.trim()}`));
3055
+ resolve4(false);
3056
+ }
3057
+ }
3058
+ });
3059
+ child.on("error", (err) => {
3060
+ console.error(chalk4.red(` \u2717 \u6267\u884C claude \u547D\u4EE4\u5931\u8D25: ${err.message}`));
3061
+ console.log(chalk4.yellow(" \u8BF7\u786E\u4FDD\u5DF2\u5B89\u88C5 Claude Code CLI"));
3062
+ resolve4(false);
3063
+ });
3064
+ });
3065
+ };
3066
+ var runSetupInit = async (options = {}) => {
3067
+ console.log(chalk4.bold("\n\u{1F527} Claude Code \u521D\u59CB\u5316\u8BBE\u7F6E\n"));
3068
+ console.log(chalk4.cyan("1. \u8BBE\u7F6E onboarding \u72B6\u6001"));
3069
+ const step1 = setupOnboarding();
3070
+ console.log(chalk4.cyan("\n2. \u914D\u7F6E\u9690\u79C1\u8BBE\u7F6E"));
3071
+ const step2 = setupEnvSettings();
3072
+ let step3 = true;
2268
3073
  if (options.chrome) {
2269
3074
  console.log(chalk4.cyan("\n3. \u5B89\u88C5 MCP \u5DE5\u5177"));
2270
3075
  step3 = await setupMcpTool();
@@ -2285,8 +3090,8 @@ var runSetupInit = async (options = {}) => {
2285
3090
 
2286
3091
  // src/skills.ts
2287
3092
  import { execFileSync as execFileSync2 } from "child_process";
2288
- import * as fs8 from "fs";
2289
- import * as path6 from "path";
3093
+ import * as fs10 from "fs";
3094
+ import * as path8 from "path";
2290
3095
  import chalk5 from "chalk";
2291
3096
  var SKILL_GROUPS = {
2292
3097
  official: { label: "\u5B98\u65B9", icon: "\u{1F3E2}" },
@@ -2522,7 +3327,7 @@ function parseGitHubUrl(url) {
2522
3327
  repo,
2523
3328
  branch,
2524
3329
  repoPath,
2525
- repoPath ? path6.basename(repoPath) : repo
3330
+ repoPath ? path8.basename(repoPath) : repo
2526
3331
  );
2527
3332
  return { owner, repo, branch, path: repoPath };
2528
3333
  } catch {
@@ -2530,12 +3335,12 @@ function parseGitHubUrl(url) {
2530
3335
  }
2531
3336
  }
2532
3337
  function getSkillsDir() {
2533
- return path6.join(process.cwd(), ".claude", "skills");
3338
+ return path8.join(process.cwd(), ".claude", "skills");
2534
3339
  }
2535
3340
  function ensureSkillsDir() {
2536
3341
  const skillsDir = getSkillsDir();
2537
- if (!fs8.existsSync(skillsDir)) {
2538
- fs8.mkdirSync(skillsDir, { recursive: true });
3342
+ if (!fs10.existsSync(skillsDir)) {
3343
+ fs10.mkdirSync(skillsDir, { recursive: true });
2539
3344
  } else {
2540
3345
  cleanupTempDirs(skillsDir);
2541
3346
  }
@@ -2543,11 +3348,11 @@ function ensureSkillsDir() {
2543
3348
  }
2544
3349
  function cleanupTempDirs(skillsDir) {
2545
3350
  try {
2546
- const entries = fs8.readdirSync(skillsDir, { withFileTypes: true });
3351
+ const entries = fs10.readdirSync(skillsDir, { withFileTypes: true });
2547
3352
  for (const entry of entries) {
2548
3353
  if (entry.isDirectory() && entry.name.startsWith(".tmp-")) {
2549
- const tmpPath = path6.join(skillsDir, entry.name);
2550
- fs8.rmSync(tmpPath, { recursive: true });
3354
+ const tmpPath = path8.join(skillsDir, entry.name);
3355
+ fs10.rmSync(tmpPath, { recursive: true });
2551
3356
  }
2552
3357
  }
2553
3358
  } catch {
@@ -2558,27 +3363,27 @@ function downloadSkillWithGit(owner, repo, branch, repoPath, targetName) {
2558
3363
  try {
2559
3364
  validateGitHubInstallParts(owner, repo, branch, repoPath, targetName);
2560
3365
  const skillsDir = ensureSkillsDir();
2561
- const targetDir = path6.join(skillsDir, targetName);
2562
- if (fs8.existsSync(targetDir)) {
3366
+ const targetDir = path8.join(skillsDir, targetName);
3367
+ if (fs10.existsSync(targetDir)) {
2563
3368
  console.log(chalk5.yellow(`Skill "${targetName}" already exists. Updating...`));
2564
- fs8.rmSync(targetDir, { recursive: true });
3369
+ fs10.rmSync(targetDir, { recursive: true });
2565
3370
  }
2566
3371
  const repoUrl = `https://github.com/${owner}/${repo}.git`;
2567
- tempDir = path6.join(skillsDir, `.tmp-${Date.now()}`);
2568
- fs8.mkdirSync(tempDir, { recursive: true });
3372
+ tempDir = path8.join(skillsDir, `.tmp-${Date.now()}`);
3373
+ fs10.mkdirSync(tempDir, { recursive: true });
2569
3374
  execFileSync2("git", ["init"], { cwd: tempDir, stdio: "pipe" });
2570
3375
  execFileSync2("git", ["remote", "add", "origin", repoUrl], { cwd: tempDir, stdio: "pipe" });
2571
3376
  execFileSync2("git", ["config", "core.sparseCheckout", "true"], { cwd: tempDir, stdio: "pipe" });
2572
- const sparseFile = path6.join(tempDir, ".git", "info", "sparse-checkout");
2573
- fs8.mkdirSync(path6.dirname(sparseFile), { recursive: true });
2574
- fs8.writeFileSync(sparseFile, repoPath ? `${repoPath}/
3377
+ const sparseFile = path8.join(tempDir, ".git", "info", "sparse-checkout");
3378
+ fs10.mkdirSync(path8.dirname(sparseFile), { recursive: true });
3379
+ fs10.writeFileSync(sparseFile, repoPath ? `${repoPath}/
2575
3380
  ` : "*\n");
2576
3381
  execFileSync2("git", ["pull", "--depth=1", "origin", branch], {
2577
3382
  cwd: tempDir,
2578
3383
  stdio: "pipe"
2579
3384
  });
2580
- const sourceDir = repoPath ? path6.join(tempDir, repoPath) : tempDir;
2581
- if (!fs8.existsSync(sourceDir)) {
3385
+ const sourceDir = repoPath ? path8.join(tempDir, repoPath) : tempDir;
3386
+ if (!fs10.existsSync(sourceDir)) {
2582
3387
  throw new Error(`Path "${repoPath}" not found in repository`);
2583
3388
  }
2584
3389
  copyDir(sourceDir, targetDir);
@@ -2589,31 +3394,31 @@ function downloadSkillWithGit(owner, repo, branch, repoPath, targetName) {
2589
3394
  console.error(chalk5.red(`Failed to download skill: ${errMsg}`));
2590
3395
  return false;
2591
3396
  } finally {
2592
- if (tempDir && fs8.existsSync(tempDir)) {
2593
- fs8.rmSync(tempDir, { recursive: true });
3397
+ if (tempDir && fs10.existsSync(tempDir)) {
3398
+ fs10.rmSync(tempDir, { recursive: true });
2594
3399
  }
2595
3400
  }
2596
3401
  }
2597
3402
  function copyDir(src, dest) {
2598
- fs8.mkdirSync(dest, { recursive: true });
2599
- const entries = fs8.readdirSync(src, { withFileTypes: true });
3403
+ fs10.mkdirSync(dest, { recursive: true });
3404
+ const entries = fs10.readdirSync(src, { withFileTypes: true });
2600
3405
  for (const entry of entries) {
2601
3406
  if (entry.name === ".git") continue;
2602
- const srcPath = path6.join(src, entry.name);
2603
- const destPath = path6.join(dest, entry.name);
3407
+ const srcPath = path8.join(src, entry.name);
3408
+ const destPath = path8.join(dest, entry.name);
2604
3409
  if (entry.isDirectory()) {
2605
3410
  copyDir(srcPath, destPath);
2606
3411
  } else {
2607
- fs8.copyFileSync(srcPath, destPath);
3412
+ fs10.copyFileSync(srcPath, destPath);
2608
3413
  }
2609
3414
  }
2610
3415
  }
2611
3416
  function isSafeSkillName(name) {
2612
- return name.trim().length > 0 && name !== "." && name !== ".." && !name.startsWith(".") && !path6.isAbsolute(name) && !name.includes("/") && !name.includes("\\") && !name.includes("\0");
3417
+ return name.trim().length > 0 && name !== "." && name !== ".." && !name.startsWith(".") && !path8.isAbsolute(name) && !name.includes("/") && !name.includes("\\") && !name.includes("\0");
2613
3418
  }
2614
3419
  function isPathInside(childPath, parentPath) {
2615
- const relativePath = path6.relative(parentPath, childPath);
2616
- return relativePath === "" || relativePath.length > 0 && !relativePath.startsWith("..") && !path6.isAbsolute(relativePath);
3420
+ const relativePath = path8.relative(parentPath, childPath);
3421
+ return relativePath === "" || relativePath.length > 0 && !relativePath.startsWith("..") && !path8.isAbsolute(relativePath);
2617
3422
  }
2618
3423
  function addSkillFromGitHub(urlOrPreset) {
2619
3424
  const preset = SKILL_PRESETS.find((p) => p.name === urlOrPreset);
@@ -2657,7 +3462,7 @@ function addSkillFromGitHub(urlOrPreset) {
2657
3462
  }
2658
3463
  let skillName;
2659
3464
  if (parsed.path) {
2660
- skillName = path6.basename(parsed.path);
3465
+ skillName = path8.basename(parsed.path);
2661
3466
  } else {
2662
3467
  skillName = parsed.repo;
2663
3468
  }
@@ -2671,13 +3476,13 @@ function addSkillFromGitHub(urlOrPreset) {
2671
3476
  }
2672
3477
  function listInstalledSkills() {
2673
3478
  const skillsDir = getSkillsDir();
2674
- if (!fs8.existsSync(skillsDir)) {
3479
+ if (!fs10.existsSync(skillsDir)) {
2675
3480
  return [];
2676
3481
  }
2677
- const entries = fs8.readdirSync(skillsDir, { withFileTypes: true });
3482
+ const entries = fs10.readdirSync(skillsDir, { withFileTypes: true });
2678
3483
  return entries.filter((entry) => entry.isDirectory() && !entry.name.startsWith(".")).map((entry) => ({
2679
3484
  name: entry.name,
2680
- path: path6.join(skillsDir, entry.name)
3485
+ path: path8.join(skillsDir, entry.name)
2681
3486
  }));
2682
3487
  }
2683
3488
  function removeSkill(name) {
@@ -2686,18 +3491,18 @@ function removeSkill(name) {
2686
3491
  return false;
2687
3492
  }
2688
3493
  const skillsDir = getSkillsDir();
2689
- const targetDir = path6.resolve(skillsDir, name);
2690
- if (!fs8.existsSync(targetDir)) {
3494
+ const targetDir = path8.resolve(skillsDir, name);
3495
+ if (!fs10.existsSync(targetDir)) {
2691
3496
  console.error(chalk5.red(`Skill "${name}" not found`));
2692
3497
  return false;
2693
3498
  }
2694
- const canonicalSkillsDir = fs8.realpathSync(skillsDir);
2695
- const canonicalTargetDir = fs8.realpathSync(targetDir);
3499
+ const canonicalSkillsDir = fs10.realpathSync(skillsDir);
3500
+ const canonicalTargetDir = fs10.realpathSync(targetDir);
2696
3501
  if (!isPathInside(canonicalTargetDir, canonicalSkillsDir)) {
2697
3502
  console.error(chalk5.red(`Refusing to remove skill outside skills directory: "${name}"`));
2698
3503
  return false;
2699
3504
  }
2700
- fs8.rmSync(targetDir, { recursive: true });
3505
+ fs10.rmSync(targetDir, { recursive: true });
2701
3506
  console.log(chalk5.green(`Removed skill "${name}"`));
2702
3507
  return true;
2703
3508
  }
@@ -2937,7 +3742,7 @@ var decryptWithSecret = (encryptedBase64, secret) => {
2937
3742
  }
2938
3743
  return decryptV1Legacy(encryptedBase64, key);
2939
3744
  };
2940
- var getUniqueName = (baseName, existingNames) => {
3745
+ var getUniqueImportedEnvironmentName = (baseName, existingNames) => {
2941
3746
  if (!existingNames.has(baseName)) {
2942
3747
  return baseName;
2943
3748
  }
@@ -3039,10 +3844,11 @@ var loadFromRemote = async (url, key, secret) => {
3039
3844
  process.exit(1);
3040
3845
  }
3041
3846
  const registries = config.get("registries");
3847
+ assertOfficialEnvironmentInvariant(registries);
3042
3848
  const existingNames = new Set(Object.keys(registries));
3043
3849
  const results = [];
3044
3850
  for (const [name, envConfig] of Object.entries(decrypted.environments)) {
3045
- const uniqueName = getUniqueName(name, existingNames);
3851
+ const uniqueName = getUniqueImportedEnvironmentName(name, existingNames);
3046
3852
  const renamed = uniqueName !== name;
3047
3853
  const normalizedConfig = normalizeEnvConfig(envConfig);
3048
3854
  const configToSave = { ...normalizedConfig };
@@ -3057,6 +3863,7 @@ var loadFromRemote = async (url, key, secret) => {
3057
3863
  renamed
3058
3864
  });
3059
3865
  }
3866
+ assertOfficialEnvironmentInvariant(registries);
3060
3867
  config.set("registries", registries);
3061
3868
  console.log(chalk6.green(`
3062
3869
  Loaded ${results.length} environment(s) from remote:`));
@@ -3226,9 +4033,9 @@ ccem cron delete "TASK_ID_OR_EXACT_NAME"
3226
4033
 
3227
4034
  // src/cron.ts
3228
4035
  import crypto5 from "crypto";
3229
- import * as fs9 from "fs";
4036
+ import * as fs11 from "fs";
3230
4037
  import * as os5 from "os";
3231
- import * as path7 from "path";
4038
+ import * as path9 from "path";
3232
4039
  var CRON_TASKS_FILE_NAME = "cron-tasks.json";
3233
4040
  var EXECUTION_PROFILES = /* @__PURE__ */ new Set([
3234
4041
  "conservative",
@@ -3236,13 +4043,13 @@ var EXECUTION_PROFILES = /* @__PURE__ */ new Set([
3236
4043
  "autonomous"
3237
4044
  ]);
3238
4045
  function getCronTasksPath(baseDir = getCcemConfigDir()) {
3239
- return path7.join(baseDir, CRON_TASKS_FILE_NAME);
4046
+ return path9.join(baseDir, CRON_TASKS_FILE_NAME);
3240
4047
  }
3241
4048
  function readCronTasks(tasksPath = getCronTasksPath()) {
3242
- if (!fs9.existsSync(tasksPath)) {
4049
+ if (!fs11.existsSync(tasksPath)) {
3243
4050
  return [];
3244
4051
  }
3245
- const content = fs9.readFileSync(tasksPath, "utf-8").trim();
4052
+ const content = fs11.readFileSync(tasksPath, "utf-8").trim();
3246
4053
  if (!content) {
3247
4054
  return [];
3248
4055
  }
@@ -3257,14 +4064,14 @@ function writeCronTasks(tasks, tasksPath = getCronTasksPath()) {
3257
4064
  if (tasksPath === getCronTasksPath()) {
3258
4065
  ensureCcemDir();
3259
4066
  } else {
3260
- fs9.mkdirSync(path7.dirname(tasksPath), { recursive: true });
4067
+ fs11.mkdirSync(path9.dirname(tasksPath), { recursive: true });
3261
4068
  }
3262
4069
  const payload = { tasks };
3263
4070
  const content = `${JSON.stringify(payload, null, 2)}
3264
4071
  `;
3265
4072
  const tempPath = `${tasksPath}.${process.pid}.${Date.now()}.tmp`;
3266
- fs9.writeFileSync(tempPath, content, { encoding: "utf-8", mode: 384 });
3267
- fs9.renameSync(tempPath, tasksPath);
4073
+ fs11.writeFileSync(tempPath, content, { encoding: "utf-8", mode: 384 });
4074
+ fs11.renameSync(tempPath, tasksPath);
3268
4075
  }
3269
4076
  function validateCronExpression(cronExpression) {
3270
4077
  const fields = cronExpression.trim().split(/\s+/);
@@ -3305,392 +4112,132 @@ function normalizeWecomNotification(value) {
3305
4112
  if (!value) {
3306
4113
  return null;
3307
4114
  }
3308
- return {
3309
- botId: value.botId?.trim() || null,
3310
- peerId: value.peerId?.trim() || null,
3311
- enabled: value.enabled ?? true
3312
- };
3313
- }
3314
- function parseWecomNotification(value) {
3315
- if (typeof value !== "object" || value === null) {
3316
- return null;
3317
- }
3318
- const record = value;
3319
- return {
3320
- botId: typeof record.botId === "string" ? record.botId : typeof record.bot_id === "string" ? record.bot_id : null,
3321
- peerId: typeof record.peerId === "string" ? record.peerId : typeof record.peer_id === "string" ? record.peer_id : null,
3322
- enabled: typeof record.enabled === "boolean" ? record.enabled : true
3323
- };
3324
- }
3325
- function createCronTask(input, tasksPath = getCronTasksPath()) {
3326
- const name = input.name?.trim();
3327
- if (!name) {
3328
- throw new Error("Task name is required");
3329
- }
3330
- const cronExpression = input.cronExpression?.trim();
3331
- if (!cronExpression) {
3332
- throw new Error("cronExpression is required");
3333
- }
3334
- validateCronExpression(cronExpression);
3335
- const prompt = input.prompt?.trim();
3336
- if (!prompt) {
3337
- throw new Error("Task prompt is required");
3338
- }
3339
- const timeoutSecs = input.timeoutSecs ?? 300;
3340
- if (!Number.isInteger(timeoutSecs) || timeoutSecs <= 0) {
3341
- throw new Error("timeoutSecs must be a positive integer");
3342
- }
3343
- const maxBudgetUsd = input.maxBudgetUsd ?? null;
3344
- if (maxBudgetUsd !== null && (!Number.isFinite(maxBudgetUsd) || maxBudgetUsd < 0)) {
3345
- throw new Error("maxBudgetUsd must be a non-negative number");
3346
- }
3347
- const now = (/* @__PURE__ */ new Date()).toISOString();
3348
- const task = {
3349
- id: `cron-${Date.now()}-${crypto5.randomBytes(2).toString("hex")}`,
3350
- name,
3351
- cronExpression,
3352
- prompt,
3353
- workingDir: input.workingDir?.trim() || process.cwd(),
3354
- envName: input.envName?.trim() || null,
3355
- executionProfile: normalizeExecutionProfile(input.executionProfile),
3356
- maxBudgetUsd,
3357
- allowedTools: input.allowedTools ?? [],
3358
- disallowedTools: input.disallowedTools ?? [],
3359
- enabled: input.enabled ?? true,
3360
- timeoutSecs,
3361
- templateId: input.templateId?.trim() || null,
3362
- wecomNotification: normalizeWecomNotification(input.wecomNotification),
3363
- triggerType: "schedule",
3364
- parentTaskId: null,
3365
- createdAt: now,
3366
- updatedAt: now
3367
- };
3368
- const tasks = readCronTasks(tasksPath);
3369
- tasks.push(task);
3370
- writeCronTasks(tasks, tasksPath);
3371
- return task;
3372
- }
3373
- function deleteCronTask(selector, tasksPath = getCronTasksPath()) {
3374
- const normalizedSelector = selector.trim();
3375
- if (!normalizedSelector) {
3376
- throw new Error("Task id or name is required");
3377
- }
3378
- const tasks = readCronTasks(tasksPath);
3379
- const matches = tasks.filter((task) => task.id === normalizedSelector || task.name === normalizedSelector);
3380
- if (matches.length === 0) {
3381
- throw new Error(`Cron task not found: ${normalizedSelector}`);
3382
- }
3383
- if (matches.length > 1) {
3384
- throw new Error(`Cron task selector is ambiguous: ${normalizedSelector}`);
3385
- }
3386
- const [deleted] = matches;
3387
- writeCronTasks(tasks.filter((task) => task.id !== deleted.id), tasksPath);
3388
- return deleted;
3389
- }
3390
- function resolveJsonInput(raw) {
3391
- if (raw === "-") {
3392
- return fs9.readFileSync(0, "utf-8");
3393
- }
3394
- if (raw.startsWith("@")) {
3395
- return fs9.readFileSync(path7.resolve(raw.slice(1)), "utf-8");
3396
- }
3397
- return raw;
3398
- }
3399
- function parseCronCreateJson(raw) {
3400
- const parsed = JSON.parse(resolveJsonInput(raw));
3401
- const wecomNotification = parsed.wecomNotification ?? parsed.wecom_notification;
3402
- return {
3403
- name: String(parsed.name ?? ""),
3404
- cronExpression: String(parsed.cronExpression ?? parsed.schedule ?? ""),
3405
- prompt: String(parsed.prompt ?? ""),
3406
- workingDir: typeof parsed.workingDir === "string" ? parsed.workingDir : null,
3407
- envName: typeof parsed.envName === "string" ? parsed.envName : null,
3408
- executionProfile: typeof parsed.executionProfile === "string" ? parsed.executionProfile : null,
3409
- maxBudgetUsd: typeof parsed.maxBudgetUsd === "number" ? parsed.maxBudgetUsd : null,
3410
- allowedTools: Array.isArray(parsed.allowedTools) ? parsed.allowedTools.map(String) : null,
3411
- disallowedTools: Array.isArray(parsed.disallowedTools) ? parsed.disallowedTools.map(String) : null,
3412
- enabled: typeof parsed.enabled === "boolean" ? parsed.enabled : null,
3413
- timeoutSecs: typeof parsed.timeoutSecs === "number" ? parsed.timeoutSecs : null,
3414
- templateId: typeof parsed.templateId === "string" ? parsed.templateId : null,
3415
- wecomNotification: parseWecomNotification(wecomNotification)
3416
- };
3417
- }
3418
- function formatCronTaskTableRows(tasks) {
3419
- return tasks.map((task) => [
3420
- task.name,
3421
- task.cronExpression,
3422
- task.enabled ? "yes" : "no",
3423
- task.workingDir.replace(os5.homedir(), "~"),
3424
- task.envName ?? "-",
3425
- String(task.timeoutSecs)
3426
- ]);
3427
- }
3428
-
3429
- // src/desktopControl.ts
3430
- import fs10 from "fs";
3431
- import path8 from "path";
3432
- var DEFAULT_REQUEST_TIMEOUT_MS = 5e3;
3433
- var LOOPBACK_HOSTS = /* @__PURE__ */ new Set(["127.0.0.1", "localhost", "::1", "[::1]"]);
3434
- var ENDPOINT_UNREACHABLE_CODES = /* @__PURE__ */ new Set([
3435
- "ECONNREFUSED",
3436
- "ECONNRESET",
3437
- "ENOTCONN",
3438
- "EHOSTUNREACH",
3439
- "ECONNABORTED"
3440
- ]);
3441
- var StaleDesktopControlDescriptorError = class extends Error {
3442
- name = "StaleDesktopControlDescriptorError";
3443
- reason;
3444
- descriptorPath;
3445
- pid;
3446
- cleanedUp;
3447
- cause;
3448
- constructor(details) {
3449
- const subject = details.pid !== null ? `process ${details.pid}` : "the publishing process";
3450
- const symptom = details.reason === "dead-pid" ? `${subject} is no longer running` : details.reason === "endpoint-unreachable" ? "the control endpoint refused the connection" : `the control request timed out after ${details.timeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS}ms`;
3451
- const remedy = details.cleanedUp ? "The stale descriptor was removed automatically; start CCEM Desktop and rerun the command." : details.pid !== null ? "Restart CCEM Desktop so it republishes a fresh control endpoint." : "Restart CCEM Desktop to refresh the descriptor, or remove the stale file manually if it is no longer managed.";
3452
- super(
3453
- `CCEM Desktop control descriptor at ${details.descriptorPath} is stale: ${symptom}. ${remedy}`
3454
- );
3455
- this.reason = details.reason;
3456
- this.descriptorPath = details.descriptorPath;
3457
- this.pid = details.pid;
3458
- this.cleanedUp = details.cleanedUp;
3459
- if (details.cause !== void 0) {
3460
- this.cause = details.cause;
3461
- }
3462
- }
3463
- };
3464
- function getDesktopControlDescriptorPath() {
3465
- return process.env.CCEM_CONTROL_FILE?.trim() || getDefaultControlDescriptorPath();
3466
- }
3467
- function getDefaultControlDescriptorPath() {
3468
- return path8.join(getCcemConfigDir(), "control.json");
3469
- }
3470
- function isDefaultDescriptorPath(descriptorPath) {
3471
- try {
3472
- return path8.resolve(descriptorPath) === path8.resolve(getDefaultControlDescriptorPath());
3473
- } catch {
3474
- return false;
3475
- }
3476
- }
3477
- function safeRemoveStaleDescriptor(descriptorPath) {
3478
- if (!isDefaultDescriptorPath(descriptorPath)) {
3479
- return false;
3480
- }
3481
- try {
3482
- fs10.rmSync(descriptorPath);
3483
- return true;
3484
- } catch {
3485
- return false;
3486
- }
3487
- }
3488
- function readErrnoCode(error) {
3489
- if (!error || typeof error !== "object") return void 0;
3490
- const candidate = error;
3491
- return candidate.code ?? candidate.cause?.code;
3492
- }
3493
- function readPid(value) {
3494
- return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : null;
3495
- }
3496
- function isLoopbackHost(host) {
3497
- const normalized = host.trim().toLowerCase().replace(/^\[|\]$/g, "");
3498
- if (LOOPBACK_HOSTS.has(normalized)) {
3499
- return true;
3500
- }
3501
- if (/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(normalized)) {
3502
- return true;
3503
- }
3504
- if (normalized === "::1" || normalized === "0:0:0:0:0:0:0:1") {
3505
- return true;
3506
- }
3507
- return false;
3508
- }
3509
- function extractHost(endpoint) {
3510
- const withoutScheme = endpoint.replace(/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//, "");
3511
- const hostPort = withoutScheme.split(/[\/?#]/)[0] || "";
3512
- if (hostPort.startsWith("[")) {
3513
- const end = hostPort.indexOf("]");
3514
- if (end === -1) return null;
3515
- return hostPort.slice(1, end);
3516
- }
3517
- const colonIndex = hostPort.lastIndexOf(":");
3518
- if (colonIndex === -1) return hostPort;
3519
- return hostPort.slice(0, colonIndex);
3520
- }
3521
- function validateLoopbackEndpoint(endpoint) {
3522
- const host = extractHost(endpoint);
3523
- if (!host) {
3524
- throw new Error(
3525
- `CCEM Desktop control endpoint '${redactEndpoint(endpoint)}' is missing a host. Refusing to continue.`
3526
- );
3527
- }
3528
- if (!isLoopbackHost(host)) {
3529
- throw new Error(
3530
- `CCEM Desktop control endpoint '${redactEndpoint(endpoint)}' is not bound to loopback. Only 127.0.0.1, localhost, or ::1 are allowed.`
3531
- );
3532
- }
3533
- }
3534
- function isPidAlive(pid) {
3535
- if (!Number.isFinite(pid) || pid <= 0) return false;
3536
- try {
3537
- process.kill(pid, 0);
3538
- return true;
3539
- } catch (error) {
3540
- const code = error.code;
3541
- if (code === "ESRCH") return false;
3542
- if (code === "EPERM") return true;
3543
- return false;
3544
- }
3545
- }
3546
- function redactEndpoint(endpoint) {
3547
- try {
3548
- const url = new URL(endpoint);
3549
- return `${url.protocol}//${url.host}${url.pathname}`;
3550
- } catch {
3551
- return "<invalid endpoint>";
3552
- }
3553
- }
3554
- function isDescriptor(value) {
3555
- return Boolean(
3556
- value && typeof value === "object" && typeof value.endpoint === "string" && typeof value.token === "string"
3557
- );
3558
- }
3559
- function resolveDesktopControlDescriptor(descriptorPath = getDesktopControlDescriptorPath()) {
3560
- if (!fs10.existsSync(descriptorPath)) {
3561
- throw new Error(`CCEM Desktop control endpoint not found at ${descriptorPath}. Start CCEM Desktop first.`);
3562
- }
3563
- const parsed = JSON.parse(fs10.readFileSync(descriptorPath, "utf-8"));
3564
- const endpoint = parsed.endpoint?.trim();
3565
- const token = parsed.token?.trim();
3566
- if (!endpoint || !token) {
3567
- throw new Error(`Invalid CCEM Desktop control descriptor at ${descriptorPath}`);
3568
- }
3569
- validateLoopbackEndpoint(endpoint);
3570
- const pid = readPid(parsed.pid);
3571
- if (pid !== null && !isPidAlive(pid)) {
3572
- const cleanedUp = safeRemoveStaleDescriptor(descriptorPath);
3573
- throw new StaleDesktopControlDescriptorError({
3574
- reason: "dead-pid",
3575
- descriptorPath,
3576
- pid,
3577
- cleanedUp
3578
- });
4115
+ return {
4116
+ botId: value.botId?.trim() || null,
4117
+ peerId: value.peerId?.trim() || null,
4118
+ enabled: value.enabled ?? true
4119
+ };
4120
+ }
4121
+ function parseWecomNotification(value) {
4122
+ if (typeof value !== "object" || value === null) {
4123
+ return null;
3579
4124
  }
3580
- return { endpoint, token, pid };
4125
+ const record = value;
4126
+ return {
4127
+ botId: typeof record.botId === "string" ? record.botId : typeof record.bot_id === "string" ? record.bot_id : null,
4128
+ peerId: typeof record.peerId === "string" ? record.peerId : typeof record.peer_id === "string" ? record.peer_id : null,
4129
+ enabled: typeof record.enabled === "boolean" ? record.enabled : true
4130
+ };
3581
4131
  }
3582
- async function requestDesktopControl(method, params, descriptorOrOptions, maybeOptions = {}) {
3583
- const descriptorPath = getDesktopControlDescriptorPath();
3584
- const hasInjectedDescriptor = isDescriptor(descriptorOrOptions);
3585
- const descriptor = hasInjectedDescriptor ? descriptorOrOptions : resolveDesktopControlDescriptor(descriptorPath);
3586
- const options = hasInjectedDescriptor ? maybeOptions : descriptorOrOptions ?? maybeOptions ?? {};
3587
- const timeoutMs = options.timeoutMs ?? options.fetchTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
3588
- const pid = readPid(descriptor.pid);
3589
- validateLoopbackEndpoint(descriptor.endpoint);
3590
- if (pid !== null && !isPidAlive(pid)) {
3591
- const cleanedUp = hasInjectedDescriptor ? false : safeRemoveStaleDescriptor(descriptorPath);
3592
- throw new StaleDesktopControlDescriptorError({
3593
- reason: "dead-pid",
3594
- descriptorPath,
3595
- pid,
3596
- cleanedUp
3597
- });
4132
+ function createCronTask(input, tasksPath = getCronTasksPath()) {
4133
+ const name = input.name?.trim();
4134
+ if (!name) {
4135
+ throw new Error("Task name is required");
3598
4136
  }
3599
- const id = `ccem-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
3600
- const controller = new AbortController();
3601
- const timer = setTimeout(() => controller.abort(), timeoutMs);
3602
- const externalSignal = options.signal;
3603
- const onExternalAbort = () => controller.abort();
3604
- if (externalSignal) {
3605
- if (externalSignal.aborted) {
3606
- clearTimeout(timer);
3607
- controller.abort();
3608
- } else {
3609
- externalSignal.addEventListener("abort", onExternalAbort, { once: true });
3610
- }
4137
+ const cronExpression = input.cronExpression?.trim();
4138
+ if (!cronExpression) {
4139
+ throw new Error("cronExpression is required");
3611
4140
  }
3612
- let response;
3613
- try {
3614
- response = await fetch(descriptor.endpoint, {
3615
- method: "POST",
3616
- headers: {
3617
- authorization: `Bearer ${descriptor.token}`,
3618
- "content-type": "application/json"
3619
- },
3620
- body: JSON.stringify({
3621
- jsonrpc: "2.0",
3622
- id,
3623
- method,
3624
- params: params ?? {}
3625
- }),
3626
- signal: controller.signal
3627
- });
3628
- } catch (error) {
3629
- if (controller.signal.aborted) {
3630
- throw new StaleDesktopControlDescriptorError({
3631
- reason: "request-timeout",
3632
- descriptorPath,
3633
- pid,
3634
- cleanedUp: false,
3635
- timeoutMs,
3636
- cause: error
3637
- });
3638
- }
3639
- const code = readErrnoCode(error);
3640
- if (code && ENDPOINT_UNREACHABLE_CODES.has(code)) {
3641
- throw new StaleDesktopControlDescriptorError({
3642
- reason: "endpoint-unreachable",
3643
- descriptorPath,
3644
- pid,
3645
- cleanedUp: false,
3646
- cause: error
3647
- });
3648
- }
3649
- throw error;
3650
- } finally {
3651
- clearTimeout(timer);
3652
- if (externalSignal) {
3653
- externalSignal.removeEventListener("abort", onExternalAbort);
3654
- }
4141
+ validateCronExpression(cronExpression);
4142
+ const prompt = input.prompt?.trim();
4143
+ if (!prompt) {
4144
+ throw new Error("Task prompt is required");
3655
4145
  }
3656
- if (!response.ok) {
3657
- throw new Error(`CCEM Desktop control request failed: HTTP ${response.status}`);
4146
+ const timeoutSecs = input.timeoutSecs ?? 300;
4147
+ if (!Number.isInteger(timeoutSecs) || timeoutSecs <= 0) {
4148
+ throw new Error("timeoutSecs must be a positive integer");
3658
4149
  }
3659
- const payload = await response.json();
3660
- if (payload.error) {
3661
- throw new Error(payload.error.message || `CCEM Desktop control error ${payload.error.code ?? ""}`.trim());
4150
+ const maxBudgetUsd = input.maxBudgetUsd ?? null;
4151
+ if (maxBudgetUsd !== null && (!Number.isFinite(maxBudgetUsd) || maxBudgetUsd < 0)) {
4152
+ throw new Error("maxBudgetUsd must be a non-negative number");
3662
4153
  }
3663
- return payload.result;
4154
+ const now = (/* @__PURE__ */ new Date()).toISOString();
4155
+ const task = {
4156
+ id: `cron-${Date.now()}-${crypto5.randomBytes(2).toString("hex")}`,
4157
+ name,
4158
+ cronExpression,
4159
+ prompt,
4160
+ workingDir: input.workingDir?.trim() || process.cwd(),
4161
+ envName: input.envName?.trim() || null,
4162
+ executionProfile: normalizeExecutionProfile(input.executionProfile),
4163
+ maxBudgetUsd,
4164
+ allowedTools: input.allowedTools ?? [],
4165
+ disallowedTools: input.disallowedTools ?? [],
4166
+ enabled: input.enabled ?? true,
4167
+ timeoutSecs,
4168
+ templateId: input.templateId?.trim() || null,
4169
+ wecomNotification: normalizeWecomNotification(input.wecomNotification),
4170
+ triggerType: "schedule",
4171
+ parentTaskId: null,
4172
+ createdAt: now,
4173
+ updatedAt: now
4174
+ };
4175
+ const tasks = readCronTasks(tasksPath);
4176
+ tasks.push(task);
4177
+ writeCronTasks(tasks, tasksPath);
4178
+ return task;
3664
4179
  }
3665
- function parseSinceOption(raw) {
3666
- if (raw === void 0 || raw === null || raw === "") return null;
3667
- const value = Number(raw);
3668
- if (!Number.isFinite(value) || value < 0 || !Number.isInteger(value)) {
3669
- throw new Error(
3670
- `Invalid --since value '${raw}'. Expected a non-negative integer sequence number (e.g. 0, 42).`
3671
- );
4180
+ function deleteCronTask(selector, tasksPath = getCronTasksPath()) {
4181
+ const normalizedSelector = selector.trim();
4182
+ if (!normalizedSelector) {
4183
+ throw new Error("Task id or name is required");
3672
4184
  }
3673
- return value;
4185
+ const tasks = readCronTasks(tasksPath);
4186
+ const matches = tasks.filter((task) => task.id === normalizedSelector || task.name === normalizedSelector);
4187
+ if (matches.length === 0) {
4188
+ throw new Error(`Cron task not found: ${normalizedSelector}`);
4189
+ }
4190
+ if (matches.length > 1) {
4191
+ throw new Error(`Cron task selector is ambiguous: ${normalizedSelector}`);
4192
+ }
4193
+ const [deleted] = matches;
4194
+ writeCronTasks(tasks.filter((task) => task.id !== deleted.id), tasksPath);
4195
+ return deleted;
3674
4196
  }
3675
- function parseLimitOption(raw) {
3676
- if (raw === void 0 || raw === null || raw === "") return null;
3677
- const value = Number(raw);
3678
- if (!Number.isFinite(value) || value <= 0 || !Number.isInteger(value)) {
3679
- throw new Error(
3680
- `Invalid --limit value '${raw}'. Expected a positive integer (e.g. 1, 100).`
3681
- );
4197
+ function resolveJsonInput(raw) {
4198
+ if (raw === "-") {
4199
+ return fs11.readFileSync(0, "utf-8");
3682
4200
  }
3683
- return value;
4201
+ if (raw.startsWith("@")) {
4202
+ return fs11.readFileSync(path9.resolve(raw.slice(1)), "utf-8");
4203
+ }
4204
+ return raw;
3684
4205
  }
3685
- function printJson(value) {
3686
- console.log(JSON.stringify(value, null, 2));
4206
+ function parseCronCreateJson(raw) {
4207
+ const parsed = JSON.parse(resolveJsonInput(raw));
4208
+ const wecomNotification = parsed.wecomNotification ?? parsed.wecom_notification;
4209
+ return {
4210
+ name: String(parsed.name ?? ""),
4211
+ cronExpression: String(parsed.cronExpression ?? parsed.schedule ?? ""),
4212
+ prompt: String(parsed.prompt ?? ""),
4213
+ workingDir: typeof parsed.workingDir === "string" ? parsed.workingDir : null,
4214
+ envName: typeof parsed.envName === "string" ? parsed.envName : null,
4215
+ executionProfile: typeof parsed.executionProfile === "string" ? parsed.executionProfile : null,
4216
+ maxBudgetUsd: typeof parsed.maxBudgetUsd === "number" ? parsed.maxBudgetUsd : null,
4217
+ allowedTools: Array.isArray(parsed.allowedTools) ? parsed.allowedTools.map(String) : null,
4218
+ disallowedTools: Array.isArray(parsed.disallowedTools) ? parsed.disallowedTools.map(String) : null,
4219
+ enabled: typeof parsed.enabled === "boolean" ? parsed.enabled : null,
4220
+ timeoutSecs: typeof parsed.timeoutSecs === "number" ? parsed.timeoutSecs : null,
4221
+ templateId: typeof parsed.templateId === "string" ? parsed.templateId : null,
4222
+ wecomNotification: parseWecomNotification(wecomNotification)
4223
+ };
4224
+ }
4225
+ function formatCronTaskTableRows(tasks) {
4226
+ return tasks.map((task) => [
4227
+ task.name,
4228
+ task.cronExpression,
4229
+ task.enabled ? "yes" : "no",
4230
+ task.workingDir.replace(os5.homedir(), "~"),
4231
+ task.envName ?? "-",
4232
+ String(task.timeoutSecs)
4233
+ ]);
3687
4234
  }
3688
4235
 
3689
4236
  // src/index.ts
3690
4237
  var __filename2 = fileURLToPath2(import.meta.url);
3691
- var __dirname2 = path9.dirname(__filename2);
3692
- var pkgPath = path9.resolve(__dirname2, "..", "package.json");
3693
- var pkg = JSON.parse(fs11.readFileSync(pkgPath, "utf-8"));
4238
+ var __dirname2 = path10.dirname(__filename2);
4239
+ var pkgPath = path10.resolve(__dirname2, "..", "package.json");
4240
+ var pkg = JSON.parse(fs12.readFileSync(pkgPath, "utf-8"));
3694
4241
  var program = new Command();
3695
4242
  var DEFAULT_OFFICIAL_ENV = {
3696
4243
  ANTHROPIC_BASE_URL: "https://api.anthropic.com",
@@ -3716,9 +4263,15 @@ var clearManagedClaudeEnv = (env) => {
3716
4263
  };
3717
4264
  var buildResolvedEnvVars = (envName, env) => {
3718
4265
  const runtimeEnv = resolveEnvConfigForRuntime(envName, env);
4266
+ const authToken = runtimeEnv.ANTHROPIC_AUTH_TOKEN ? decrypt(runtimeEnv.ANTHROPIC_AUTH_TOKEN) : void 0;
4267
+ assertClaudeEnvironmentAuthBoundary(
4268
+ envName,
4269
+ runtimeEnv.ANTHROPIC_BASE_URL,
4270
+ authToken
4271
+ );
3719
4272
  const resolved = {};
3720
4273
  if (runtimeEnv.ANTHROPIC_BASE_URL) resolved.ANTHROPIC_BASE_URL = runtimeEnv.ANTHROPIC_BASE_URL;
3721
- if (runtimeEnv.ANTHROPIC_AUTH_TOKEN) resolved.ANTHROPIC_AUTH_TOKEN = decrypt(runtimeEnv.ANTHROPIC_AUTH_TOKEN);
4274
+ if (authToken) resolved.ANTHROPIC_AUTH_TOKEN = authToken;
3722
4275
  if (runtimeEnv.ANTHROPIC_DEFAULT_OPUS_MODEL) resolved.ANTHROPIC_DEFAULT_OPUS_MODEL = runtimeEnv.ANTHROPIC_DEFAULT_OPUS_MODEL;
3723
4276
  if (runtimeEnv.ANTHROPIC_DEFAULT_SONNET_MODEL) resolved.ANTHROPIC_DEFAULT_SONNET_MODEL = runtimeEnv.ANTHROPIC_DEFAULT_SONNET_MODEL;
3724
4277
  if (runtimeEnv.ANTHROPIC_DEFAULT_HAIKU_MODEL) resolved.ANTHROPIC_DEFAULT_HAIKU_MODEL = runtimeEnv.ANTHROPIC_DEFAULT_HAIKU_MODEL;
@@ -3739,9 +4292,9 @@ var config2 = new Conf2({
3739
4292
  // 使用新路径
3740
4293
  defaults: {
3741
4294
  registries: {
3742
- official: DEFAULT_OFFICIAL_ENV
4295
+ [OFFICIAL_ENV_NAME]: DEFAULT_OFFICIAL_ENV
3743
4296
  },
3744
- current: "official",
4297
+ current: OFFICIAL_ENV_NAME,
3745
4298
  defaultMode: null
3746
4299
  }
3747
4300
  });
@@ -3768,6 +4321,9 @@ function parseOptionalBoolean(value) {
3768
4321
  }
3769
4322
  return void 0;
3770
4323
  }
4324
+ function collectDesktopRoute(value, previous) {
4325
+ return [...previous, value];
4326
+ }
3771
4327
  var recoverRegistriesFromLegacy = (registries) => {
3772
4328
  const currentAuthCount = Object.values(registries).filter(
3773
4329
  (env) => Boolean(env.ANTHROPIC_AUTH_TOKEN)
@@ -3776,11 +4332,11 @@ var recoverRegistriesFromLegacy = (registries) => {
3776
4332
  return registries;
3777
4333
  }
3778
4334
  const legacyConfigPath = getLegacyConfigPath();
3779
- if (!fs11.existsSync(legacyConfigPath)) {
4335
+ if (!fs12.existsSync(legacyConfigPath)) {
3780
4336
  return registries;
3781
4337
  }
3782
4338
  try {
3783
- const legacyRaw = JSON.parse(fs11.readFileSync(legacyConfigPath, "utf-8"));
4339
+ const legacyRaw = JSON.parse(fs12.readFileSync(legacyConfigPath, "utf-8"));
3784
4340
  const legacyRegistries = legacyRaw.registries ?? {};
3785
4341
  let changed = false;
3786
4342
  const recovered = { ...registries };
@@ -3808,9 +4364,10 @@ var getRegistries = () => {
3808
4364
  ]);
3809
4365
  const normalizedRegistries = Object.fromEntries(normalizedEntries);
3810
4366
  const repairedRegistries = recoverRegistriesFromLegacy(normalizedRegistries);
3811
- if (!repairedRegistries.official) {
3812
- repairedRegistries.official = { ...DEFAULT_OFFICIAL_ENV };
4367
+ if (!repairedRegistries[OFFICIAL_ENV_NAME]) {
4368
+ repairedRegistries[OFFICIAL_ENV_NAME] = { ...DEFAULT_OFFICIAL_ENV };
3813
4369
  }
4370
+ assertOfficialEnvironmentInvariant(repairedRegistries);
3814
4371
  const changed = Object.keys(rawRegistries).length !== Object.keys(repairedRegistries).length || JSON.stringify(rawRegistries) !== JSON.stringify(repairedRegistries);
3815
4372
  if (changed) {
3816
4373
  config2.set("registries", repairedRegistries);
@@ -3818,8 +4375,16 @@ var getRegistries = () => {
3818
4375
  return repairedRegistries;
3819
4376
  };
3820
4377
  var setRegistries = (registries) => {
4378
+ assertOfficialEnvironmentInvariant(registries);
3821
4379
  config2.set("registries", registries);
3822
4380
  };
4381
+ var getEnvironmentMutationConfig = (registries) => ({
4382
+ ...config2.store,
4383
+ registries
4384
+ });
4385
+ var setEnvironmentMutationConfig = (next) => {
4386
+ config2.store = next;
4387
+ };
3823
4388
  var getDecryptedAuthToken = (envConfig) => {
3824
4389
  return envConfig.ANTHROPIC_AUTH_TOKEN ? decrypt(envConfig.ANTHROPIC_AUTH_TOKEN) : void 0;
3825
4390
  };
@@ -3974,15 +4539,15 @@ var switchEnvironment = async (name) => {
3974
4539
  exportCmds.forEach((cmd) => console.log(cmd));
3975
4540
  }
3976
4541
  };
3977
- var getSessionsFilePath = () => path9.join(getCcemConfigDir(), "sessions.json");
3978
- var getRuntimeStateFilePath = () => path9.join(getCcemConfigDir(), "runtime-state.json");
3979
- var getBotBindRequestFilePath = () => path9.join(getCcemConfigDir(), "bot-bind-requests.jsonl");
4542
+ var getSessionsFilePath = () => path10.join(getCcemConfigDir(), "sessions.json");
4543
+ var getRuntimeStateFilePath = () => path10.join(getCcemConfigDir(), "runtime-state.json");
4544
+ var getBotBindRequestFilePath = () => path10.join(getCcemConfigDir(), "bot-bind-requests.jsonl");
3980
4545
  var parseJsonFile = (filePath) => {
3981
- if (!fs11.existsSync(filePath)) {
4546
+ if (!fs12.existsSync(filePath)) {
3982
4547
  return null;
3983
4548
  }
3984
4549
  try {
3985
- return JSON.parse(fs11.readFileSync(filePath, "utf-8"));
4550
+ return JSON.parse(fs12.readFileSync(filePath, "utf-8"));
3986
4551
  } catch {
3987
4552
  return null;
3988
4553
  }
@@ -4074,8 +4639,8 @@ var resolveBotBindRuntimeId = (explicitRuntimeId) => {
4074
4639
  };
4075
4640
  var appendBotBindRequest = (payload) => {
4076
4641
  const requestPath = getBotBindRequestFilePath();
4077
- fs11.mkdirSync(path9.dirname(requestPath), { recursive: true });
4078
- fs11.appendFileSync(requestPath, `${JSON.stringify(payload)}
4642
+ fs12.mkdirSync(path10.dirname(requestPath), { recursive: true });
4643
+ fs12.appendFileSync(requestPath, `${JSON.stringify(payload)}
4079
4644
  `, "utf-8");
4080
4645
  return requestPath;
4081
4646
  };
@@ -4217,46 +4782,39 @@ program.command("add <name>").description("Add a new environment configuration")
4217
4782
  setRegistries(registries);
4218
4783
  console.log(chalk7.green(`Environment '${name}' added successfully.`));
4219
4784
  });
4220
- program.command("del <name>").description("Delete an environment configuration").action((name) => {
4221
- const registries = getRegistries();
4222
- if (!registries[name]) {
4223
- console.log(chalk7.red(`Environment '${name}' not found.`));
4224
- return;
4225
- }
4226
- if (name === "official") {
4227
- console.log(chalk7.red(`Cannot delete default 'official' environment.`));
4785
+ program.command("del <name>").description("Delete an environment configuration").action(async (name) => {
4786
+ const wasCurrent = config2.get("current") === name;
4787
+ try {
4788
+ const outcome = await deleteEnvironmentWithAuthority(
4789
+ () => getEnvironmentMutationConfig(getRegistries()),
4790
+ name
4791
+ );
4792
+ if (outcome.authority === "local") {
4793
+ setEnvironmentMutationConfig(outcome.config);
4794
+ }
4795
+ if (wasCurrent) {
4796
+ console.log(chalk7.yellow(`Deleted current environment. Switched back to 'official'.`));
4797
+ }
4798
+ } catch (error) {
4799
+ console.log(chalk7.red(error instanceof Error ? error.message : String(error)));
4228
4800
  return;
4229
4801
  }
4230
- delete registries[name];
4231
- setRegistries(registries);
4232
- const current = config2.get("current");
4233
- if (current === name) {
4234
- config2.set("current", "official");
4235
- console.log(chalk7.yellow(`Deleted current environment. Switched back to 'official'.`));
4236
- }
4237
4802
  console.log(chalk7.green(`Environment '${name}' deleted.`));
4238
4803
  });
4239
- program.command("rename <old> <new>").description("Rename an environment configuration").action((oldName, newName) => {
4240
- const registries = getRegistries();
4241
- if (!registries[oldName]) {
4242
- console.log(chalk7.red(`Environment '${oldName}' not found.`));
4243
- return;
4244
- }
4245
- if (registries[newName]) {
4246
- console.log(chalk7.red(`Environment '${newName}' already exists.`));
4247
- return;
4248
- }
4249
- if (oldName === "official") {
4250
- console.log(chalk7.red(`Cannot rename default 'official' environment.`));
4804
+ program.command("rename <old> <new>").description("Rename an environment configuration").action(async (oldName, newName) => {
4805
+ try {
4806
+ const outcome = await renameEnvironmentWithAuthority(
4807
+ () => getEnvironmentMutationConfig(getRegistries()),
4808
+ oldName,
4809
+ newName
4810
+ );
4811
+ if (outcome.authority === "local") {
4812
+ setEnvironmentMutationConfig(outcome.config);
4813
+ }
4814
+ } catch (error) {
4815
+ console.log(chalk7.red(error instanceof Error ? error.message : String(error)));
4251
4816
  return;
4252
4817
  }
4253
- registries[newName] = registries[oldName];
4254
- delete registries[oldName];
4255
- setRegistries(registries);
4256
- const current = config2.get("current");
4257
- if (current === oldName) {
4258
- config2.set("current", newName);
4259
- }
4260
4818
  console.log(chalk7.green(`Environment '${oldName}' renamed to '${newName}'.`));
4261
4819
  });
4262
4820
  program.command("cp <source> <target>").description("Copy an environment configuration").action(async (source, target) => {
@@ -4448,12 +5006,12 @@ setupCmd.command("migrate").description("\u8FC1\u79FB\u65E7\u7248\u914D\u7F6E\u5
4448
5006
  const newConfigPath = getCcemConfigPath();
4449
5007
  const legacyConfigPath = getLegacyConfigPath();
4450
5008
  console.log(chalk7.cyan("\n\u{1F504} \u914D\u7F6E\u8FC1\u79FB\n"));
4451
- if (!fs11.existsSync(legacyConfigPath)) {
5009
+ if (!fs12.existsSync(legacyConfigPath)) {
4452
5010
  console.log(chalk7.yellow("\u672A\u627E\u5230\u65E7\u7248\u914D\u7F6E\u6587\u4EF6"));
4453
5011
  console.log(chalk7.gray(` \u65E7\u8DEF\u5F84: ${legacyConfigPath}`));
4454
5012
  return;
4455
5013
  }
4456
- if (fs11.existsSync(newConfigPath) && !options.force) {
5014
+ if (fs12.existsSync(newConfigPath) && !options.force) {
4457
5015
  console.log(chalk7.green("\u2713 \u914D\u7F6E\u5DF2\u5728\u65B0\u8DEF\u5F84"));
4458
5016
  console.log(chalk7.gray(` \u8DEF\u5F84: ${newConfigPath}`));
4459
5017
  console.log(chalk7.gray("\n\u4F7F\u7528 --force \u5F3A\u5236\u91CD\u65B0\u8FC1\u79FB"));
@@ -4461,15 +5019,21 @@ setupCmd.command("migrate").description("\u8FC1\u79FB\u65E7\u7248\u914D\u7F6E\u5
4461
5019
  }
4462
5020
  try {
4463
5021
  ensureCcemDir();
4464
- fs11.copyFileSync(legacyConfigPath, newConfigPath);
5022
+ const legacyRaw = JSON.parse(fs12.readFileSync(legacyConfigPath, "utf-8"));
5023
+ const migrated = normalizeCcemConfig(legacyRaw);
5024
+ if (!migrated.registries[OFFICIAL_ENV_NAME]) {
5025
+ migrated.registries[OFFICIAL_ENV_NAME] = { ...DEFAULT_OFFICIAL_ENV };
5026
+ }
5027
+ assertOfficialEnvironmentInvariant(migrated.registries);
5028
+ setEnvironmentMutationConfig(migrated);
4465
5029
  console.log(chalk7.green("\u2713 \u914D\u7F6E\u5DF2\u8FC1\u79FB"));
4466
5030
  console.log(chalk7.gray(` \u4ECE: ${legacyConfigPath}`));
4467
5031
  console.log(chalk7.gray(` \u5230: ${newConfigPath}`));
4468
5032
  if (options.clean) {
4469
- fs11.unlinkSync(legacyConfigPath);
4470
- const legacyDir = path9.dirname(legacyConfigPath);
5033
+ fs12.unlinkSync(legacyConfigPath);
5034
+ const legacyDir = path10.dirname(legacyConfigPath);
4471
5035
  try {
4472
- fs11.rmdirSync(legacyDir);
5036
+ fs12.rmdirSync(legacyDir);
4473
5037
  } catch {
4474
5038
  }
4475
5039
  console.log(chalk7.green("\u2713 \u5DF2\u5220\u9664\u65E7\u914D\u7F6E\u6587\u4EF6"));
@@ -4480,13 +5044,13 @@ setupCmd.command("migrate").description("\u8FC1\u79FB\u65E7\u7248\u914D\u7F6E\u5
4480
5044
  });
4481
5045
  setupCmd.command("cron").description("\u5B89\u88C5 ccem-cron skill \u5230 Claude Code\uFF08~/.claude/skills/\uFF09").option("--force", "\u5F3A\u5236\u8986\u76D6\u5DF2\u6709\u6587\u4EF6").action(async function() {
4482
5046
  const options = this.opts();
4483
- const skillDir = path9.join(getHomeDir(), ".claude", "skills");
4484
- const targetPath = path9.join(skillDir, "ccem-cron.md");
4485
- if (!fs11.existsSync(skillDir)) {
4486
- fs11.mkdirSync(skillDir, { recursive: true });
5047
+ const skillDir = path10.join(getHomeDir(), ".claude", "skills");
5048
+ const targetPath = path10.join(skillDir, "ccem-cron.md");
5049
+ if (!fs12.existsSync(skillDir)) {
5050
+ fs12.mkdirSync(skillDir, { recursive: true });
4487
5051
  console.log(chalk7.gray(`\u521B\u5EFA\u76EE\u5F55: ${skillDir}`));
4488
5052
  }
4489
- if (fs11.existsSync(targetPath) && !options.force) {
5053
+ if (fs12.existsSync(targetPath) && !options.force) {
4490
5054
  const { overwrite } = await inquirer.prompt([
4491
5055
  {
4492
5056
  type: "confirm",
@@ -4500,7 +5064,7 @@ setupCmd.command("cron").description("\u5B89\u88C5 ccem-cron skill \u5230 Claude
4500
5064
  return;
4501
5065
  }
4502
5066
  }
4503
- fs11.writeFileSync(targetPath, CCEM_CRON_SKILL_CONTENT, "utf-8");
5067
+ fs12.writeFileSync(targetPath, CCEM_CRON_SKILL_CONTENT, "utf-8");
4504
5068
  console.log(chalk7.green(`\u2713 \u5DF2\u5B89\u88C5 ccem-cron skill`));
4505
5069
  console.log(chalk7.gray(` \u8DEF\u5F84: ${targetPath}`));
4506
5070
  console.log(chalk7.cyan(`
@@ -4508,13 +5072,13 @@ setupCmd.command("cron").description("\u5B89\u88C5 ccem-cron skill \u5230 Claude
4508
5072
  });
4509
5073
  setupCmd.command("bot-bind").description("\u5B89\u88C5 ccem-bot-bind skill \u5230 Claude Code\uFF08~/.claude/skills/\uFF09").option("--force", "\u5F3A\u5236\u8986\u76D6\u5DF2\u6709\u6587\u4EF6").action(async function() {
4510
5074
  const options = this.opts();
4511
- const skillDir = path9.join(getHomeDir(), ".claude", "skills");
4512
- const targetPath = path9.join(skillDir, "ccem-bot-bind.md");
4513
- if (!fs11.existsSync(skillDir)) {
4514
- fs11.mkdirSync(skillDir, { recursive: true });
5075
+ const skillDir = path10.join(getHomeDir(), ".claude", "skills");
5076
+ const targetPath = path10.join(skillDir, "ccem-bot-bind.md");
5077
+ if (!fs12.existsSync(skillDir)) {
5078
+ fs12.mkdirSync(skillDir, { recursive: true });
4515
5079
  console.log(chalk7.gray(`\u521B\u5EFA\u76EE\u5F55: ${skillDir}`));
4516
5080
  }
4517
- if (fs11.existsSync(targetPath) && !options.force) {
5081
+ if (fs12.existsSync(targetPath) && !options.force) {
4518
5082
  const { overwrite } = await inquirer.prompt([
4519
5083
  {
4520
5084
  type: "confirm",
@@ -4528,7 +5092,7 @@ setupCmd.command("bot-bind").description("\u5B89\u88C5 ccem-bot-bind skill \u523
4528
5092
  return;
4529
5093
  }
4530
5094
  }
4531
- fs11.writeFileSync(targetPath, CCEM_BOT_BIND_SKILL_CONTENT, "utf-8");
5095
+ fs12.writeFileSync(targetPath, CCEM_BOT_BIND_SKILL_CONTENT, "utf-8");
4532
5096
  console.log(chalk7.green(`\u2713 \u5DF2\u5B89\u88C5 ccem-bot-bind skill`));
4533
5097
  console.log(chalk7.gray(` \u8DEF\u5F84: ${targetPath}`));
4534
5098
  console.log(chalk7.cyan(`
@@ -4616,6 +5180,11 @@ program.command("launch").description(false).option("--env <name>", "\u73AF\u588
4616
5180
  process.exit(1);
4617
5181
  }
4618
5182
  const proxyBaseUrl = opts.proxyBaseUrl || opts.anthropicBaseUrl;
5183
+ if (proxyBaseUrl && !isTrustedDesktopProxyBaseUrl(proxyBaseUrl)) {
5184
+ console.error(chalk7.red("Desktop proxy override must use the local CCEM Claude proxy endpoint."));
5185
+ process.exitCode = 1;
5186
+ return;
5187
+ }
4619
5188
  const launchEnvConfig = proxyBaseUrl ? { ...envConfig, ANTHROPIC_BASE_URL: proxyBaseUrl } : envConfig;
4620
5189
  await launchClaude({
4621
5190
  envName,
@@ -4624,7 +5193,8 @@ program.command("launch").description(false).option("--env <name>", "\u73AF\u588
4624
5193
  workingDir: opts.workingDir,
4625
5194
  sessionId: opts.sessionId,
4626
5195
  resumeSessionId: opts.resumeSession,
4627
- silent: true
5196
+ silent: true,
5197
+ allowDesktopProxyOverride: Boolean(proxyBaseUrl)
4628
5198
  });
4629
5199
  });
4630
5200
  var desktopCmd = program.command("desktop").description("Control the running CCEM Desktop app");
@@ -4633,12 +5203,19 @@ desktopCmd.command("health").description("Check the running CCEM Desktop control
4633
5203
  const result = await requestDesktopControl("ccem.health");
4634
5204
  outputDesktopResult(result, opts);
4635
5205
  });
4636
- desktopCmd.command("create").description("Create a workspace session in the running CCEM Desktop app").requiredOption("--provider <provider>", "Agent provider: claude or codex").requiredOption("--cwd <path>", "Working directory").requiredOption("--prompt <text>", "Initial prompt").option("--env <name>", "Environment name").option("--perm <mode>", "Permission mode").option("--runtime-perm <mode>", "Runtime permission mode").option("--provider-session-id <id>", "Provider session id to continue").option("--effort <level>", "Codex effort level").option("--open <value>", "Open the created session in Desktop (true/false)").option("--json", "Output JSON").action(async function() {
5206
+ desktopCmd.command("create").description("Create a workspace session in the running CCEM Desktop app").requiredOption("--provider <provider>", "Agent provider: claude or codex").requiredOption("--cwd <path>", "Working directory").requiredOption("--prompt <text>", "Initial prompt").option("--env <name>", "Environment name").option("--perm <mode>", "Permission mode").option("--runtime-perm <mode>", "Runtime permission mode").option("--provider-session-id <id>", "Provider session id to continue").option("--effort <level>", "Codex effort level").option("--open <value>", "Open the created session in Desktop (true/false)").option("--route <key=env>", "Add a session route binding (repeatable)", collectDesktopRoute, []).option("--routes-json <json>", "Session route bindings as a JSON object").option("--json", "Output JSON").action(async function() {
4637
5207
  const opts = this.opts();
4638
5208
  const provider = String(opts.provider).trim().toLowerCase();
4639
5209
  if (provider !== "claude" && provider !== "codex") {
4640
5210
  throw new Error("Unsupported provider. Use 'claude' or 'codex'.");
4641
5211
  }
5212
+ const hasRouteOptions = opts.route.length > 0 || opts.routesJson !== void 0;
5213
+ const routes = provider === "claude" ? parseDesktopRoutes(opts.route, opts.routesJson) : void 0;
5214
+ if (provider === "codex" && hasRouteOptions) {
5215
+ console.error(chalk7.yellow(
5216
+ "Warning: Codex sessions do not support routing; --route and --routes-json were ignored."
5217
+ ));
5218
+ }
4642
5219
  const result = await requestDesktopControl("ccem.workspace.createSession", {
4643
5220
  provider,
4644
5221
  cwd: opts.cwd,
@@ -4648,10 +5225,16 @@ desktopCmd.command("create").description("Create a workspace session in the runn
4648
5225
  runtimePermissionMode: opts.runtimePerm ?? null,
4649
5226
  providerSessionId: opts.providerSessionId ?? null,
4650
5227
  effort: opts.effort ?? null,
4651
- open: parseOptionalBoolean(opts.open)
5228
+ open: parseOptionalBoolean(opts.open),
5229
+ ...routes === void 0 ? {} : { routes }
4652
5230
  });
4653
5231
  outputDesktopResult(result, opts);
4654
5232
  });
5233
+ desktopCmd.command("routes <runtimeId>").description("Get or update one workspace session router").option("--set <key=env>", "Set one route binding using revision-safe CAS").option("--json", "Output JSON").action(async function(runtimeId) {
5234
+ const opts = this.opts();
5235
+ const result = await getOrUpdateDesktopRoutes(runtimeId, opts.set);
5236
+ outputDesktopResult(result, opts);
5237
+ });
4655
5238
  desktopCmd.command("sessions").description("List CCEM Desktop workspace sessions").option("--cwd <path>", "Filter by working directory").option("--provider <provider>", "Filter by provider").option("--status <status>", "Filter by status").option("--json", "Output JSON").action(async function() {
4656
5239
  const opts = this.opts();
4657
5240
  const result = await requestDesktopControl("ccem.workspace.listSessions", {
@@ -4776,7 +5359,7 @@ Editing environment '${result.name}'`));
4776
5359
  msg.success(`Environment '${result.name}' updated.`);
4777
5360
  await new Promise((resolve4) => setTimeout(resolve4, 800));
4778
5361
  } else if (result.action === "rename") {
4779
- if (result.name === "official") {
5362
+ if (result.name === OFFICIAL_ENV_NAME) {
4780
5363
  msg.error("Cannot rename default 'official' environment.");
4781
5364
  await new Promise((resolve4) => setTimeout(resolve4, 800));
4782
5365
  } else {
@@ -4792,13 +5375,19 @@ Editing environment '${result.name}'`));
4792
5375
  }
4793
5376
  }
4794
5377
  ]);
4795
- registries[newName] = registries[result.name];
4796
- delete registries[result.name];
4797
- setRegistries(registries);
4798
- if (current === result.name) {
4799
- config2.set("current", newName);
5378
+ try {
5379
+ const outcome = await renameEnvironmentWithAuthority(
5380
+ () => getEnvironmentMutationConfig(registries),
5381
+ result.name,
5382
+ newName
5383
+ );
5384
+ if (outcome.authority === "local") {
5385
+ setEnvironmentMutationConfig(outcome.config);
5386
+ }
5387
+ msg.success(`Environment '${result.name}' renamed to '${newName}'.`);
5388
+ } catch (error) {
5389
+ msg.error(error instanceof Error ? error.message : String(error));
4800
5390
  }
4801
- msg.success(`Environment '${result.name}' renamed to '${newName}'.`);
4802
5391
  await new Promise((resolve4) => setTimeout(resolve4, 800));
4803
5392
  }
4804
5393
  } else if (result.action === "copy") {
@@ -4834,7 +5423,7 @@ Editing environment '${result.name}'`));
4834
5423
  }
4835
5424
  await new Promise((resolve4) => setTimeout(resolve4, 800));
4836
5425
  } else if (result.action === "delete") {
4837
- if (result.name === "official") {
5426
+ if (result.name === OFFICIAL_ENV_NAME) {
4838
5427
  msg.error("Cannot delete default 'official' environment.");
4839
5428
  await new Promise((resolve4) => setTimeout(resolve4, 800));
4840
5429
  } else {
@@ -4847,13 +5436,21 @@ Editing environment '${result.name}'`));
4847
5436
  }
4848
5437
  ]);
4849
5438
  if (confirm) {
4850
- delete registries[result.name];
4851
- setRegistries(registries);
4852
- if (current === result.name) {
4853
- config2.set("current", "official");
4854
- msg.warning(`Deleted current environment. Switched back to 'official'.`);
4855
- } else {
4856
- msg.success(`Environment '${result.name}' deleted.`);
5439
+ try {
5440
+ const outcome = await deleteEnvironmentWithAuthority(
5441
+ () => getEnvironmentMutationConfig(registries),
5442
+ result.name
5443
+ );
5444
+ if (outcome.authority === "local") {
5445
+ setEnvironmentMutationConfig(outcome.config);
5446
+ }
5447
+ if (current === result.name) {
5448
+ msg.warning(`Deleted current environment. Switched back to 'official'.`);
5449
+ } else {
5450
+ msg.success(`Environment '${result.name}' deleted.`);
5451
+ }
5452
+ } catch (error) {
5453
+ msg.error(error instanceof Error ? error.message : String(error));
4857
5454
  }
4858
5455
  }
4859
5456
  await new Promise((resolve4) => setTimeout(resolve4, 800));