@hcmai/cli 0.13.2 → 0.14.1

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
@@ -752,8 +752,8 @@ var init_TerminalRenderer = __esm({
752
752
  }
753
753
  }
754
754
  /** 来源行(仅子代理触发,agentPath ≥2 段时显示 `↑ 来自 a › b`,对齐 Web)。 */
755
- originLine(path17) {
756
- const segs = path17.split(".").filter(Boolean);
755
+ originLine(path18) {
756
+ const segs = path18.split(".").filter(Boolean);
757
757
  if (segs.length < 2) return "";
758
758
  const names = segs.map((k) => agentDisplayName(k));
759
759
  return chalk.gray(` \u2191 \u6765\u81EA ${names.join(" \u203A ")}`) + "\n";
@@ -1935,8 +1935,8 @@ function agentLabel(agentId) {
1935
1935
  if (/^[0-9a-f]{8}-[0-9a-f-]{27}$/i.test(agentId)) return `agent \u2026${agentId.slice(-4)}`;
1936
1936
  return agentDisplayName(agentId);
1937
1937
  }
1938
- function originLine(path17) {
1939
- const segs = (path17 ?? "").split(".").filter(Boolean);
1938
+ function originLine(path18) {
1939
+ const segs = (path18 ?? "").split(".").filter(Boolean);
1940
1940
  if (segs.length < 2) return null;
1941
1941
  return `\u6765\u81EA ${segs.map((k) => agentDisplayName(k)).join(" \u203A ")}`;
1942
1942
  }
@@ -2359,7 +2359,7 @@ function launchBrowser(url, platform = process.platform, onFailure) {
2359
2359
  child.unref();
2360
2360
  }
2361
2361
  async function runOpen(target, args, deps) {
2362
- const path17 = normalizeTarget(target);
2362
+ const path18 = normalizeTarget(target);
2363
2363
  if (!deps.frontend?.trim()) {
2364
2364
  throw new CliError3({
2365
2365
  code: CliErrorCode2.INVALID_ARGUMENT,
@@ -2367,13 +2367,13 @@ async function runOpen(target, args, deps) {
2367
2367
  });
2368
2368
  }
2369
2369
  const { ticket, expiresIn } = await deps.mintTicket();
2370
- const url = buildBrowserLoginUrl(deps.frontend, ticket, path17);
2370
+ const url = buildBrowserLoginUrl(deps.frontend, ticket, path18);
2371
2371
  if (args.printUrl) {
2372
2372
  deps.write(`${url}
2373
2373
  `);
2374
2374
  } else {
2375
2375
  deps.launch(url);
2376
- deps.write(`\u5DF2\u7528\u5F53\u524D\u8EAB\u4EFD\u6253\u5F00 ${path17}\uFF08\u7968\u636E ${expiresIn ?? 60}s \u5185\u6709\u6548\uFF0C\u53EA\u80FD\u7528\u4E00\u6B21\uFF09
2376
+ deps.write(`\u5DF2\u7528\u5F53\u524D\u8EAB\u4EFD\u6253\u5F00 ${path18}\uFF08\u7968\u636E ${expiresIn ?? 60}s \u5185\u6709\u6548\uFF0C\u53EA\u80FD\u7528\u4E00\u6B21\uFF09
2377
2377
  `);
2378
2378
  }
2379
2379
  return { url, expiresIn };
@@ -4451,8 +4451,8 @@ import {
4451
4451
  formatObject as formatObject7,
4452
4452
  fromAxiosError as fromAxiosError9
4453
4453
  } from "@hcmai/sdk";
4454
- function collectYmlFiles(path17) {
4455
- if (statSync(path17).isFile()) return [path17];
4454
+ function collectYmlFiles(path18) {
4455
+ if (statSync(path18).isFile()) return [path18];
4456
4456
  const out = [];
4457
4457
  const walk = (dir) => {
4458
4458
  for (const name of readdirSync(dir).sort()) {
@@ -4461,7 +4461,7 @@ function collectYmlFiles(path17) {
4461
4461
  else if (full.endsWith(".yml") || full.endsWith(".yaml")) out.push(full);
4462
4462
  }
4463
4463
  };
4464
- walk(path17);
4464
+ walk(path18);
4465
4465
  return out.sort();
4466
4466
  }
4467
4467
  var DRY_RUN_CLIENT = {
@@ -4469,9 +4469,9 @@ var DRY_RUN_CLIENT = {
4469
4469
  create: async () => ({ id: "" }),
4470
4470
  update: async () => ({})
4471
4471
  };
4472
- async function importCommand(path17, args) {
4472
+ async function importCommand(path18, args) {
4473
4473
  try {
4474
- const files = collectYmlFiles(path17);
4474
+ const files = collectYmlFiles(path18);
4475
4475
  const fixtures = files.map(
4476
4476
  (f) => parseFixture(readFileSync2(f, "utf8"), relative(process.cwd(), f))
4477
4477
  );
@@ -5980,8 +5980,8 @@ function emit3(payload, fmt) {
5980
5980
  // src/commands/skills.ts
5981
5981
  init_exit();
5982
5982
  import { promises as fsp2 } from "fs";
5983
- import os2 from "os";
5984
- import path6 from "path";
5983
+ import os3 from "os";
5984
+ import path8 from "path";
5985
5985
  import { createHash as createHash4 } from "crypto";
5986
5986
  import {
5987
5987
  createHttpClient as createHttpClient2,
@@ -5998,13 +5998,13 @@ import {
5998
5998
  resolveAllSkillsInstallOrder,
5999
5999
  matchSkills,
6000
6000
  filterByStage,
6001
- formatObject as formatObject16,
6001
+ formatObject as formatObject17,
6002
6002
  fromAxiosError as fromAxiosError16,
6003
6003
  loadGlobalConfig as loadGlobalConfig6,
6004
6004
  resolveEnvContext as resolveEnvContext5,
6005
6005
  printResolvedEnvironment as printResolvedEnvironment4,
6006
- CliError as CliError19,
6007
- CliErrorCode as CliErrorCode18
6006
+ CliError as CliError20,
6007
+ CliErrorCode as CliErrorCode19
6008
6008
  } from "@hcmai/sdk";
6009
6009
 
6010
6010
  // src/commands/skills-catalog.ts
@@ -6173,7 +6173,8 @@ function upsertBlock(existing, begin, end, block) {
6173
6173
  var BUILTIN_BOUNDARY = [
6174
6174
  "# HCM \u987E\u95EE\u9879\u76EE\u8FB9\u754C",
6175
6175
  "",
6176
- "- \u53EA\u4F7F\u7528\u672C\u9879\u76EE `hcm-skills/` \u91CC\u7684\u777F\u620E\u6280\u80FD\u4E0E\u5DF2\u53D1\u5E03\u7684 `hcm` CLI\uFF1B\u4E0D\u8BFB\u53D6\u4EA7\u54C1\u6E90\u7801\uFF0C\u4E0D\u76F4\u8FDE\u6570\u636E\u5E93\uFF0C\u4E0D\u7528 `curl` \u7ED5\u8FC7 CLI\u3002",
6176
+ "- \u53EA\u4F7F\u7528\u672C\u9879\u76EE `hcm-skills/` \u91CC\u7684\u6280\u80FD\u4E0E\u5DF2\u53D1\u5E03\u7684 `hcm` CLI\uFF1B\u4E0D\u8BFB\u53D6\u4EA7\u54C1\u6E90\u7801\uFF0C\u4E0D\u76F4\u8FDE\u6570\u636E\u5E93\uFF0C\u4E0D\u7528 `curl` \u7ED5\u8FC7 CLI\u3002",
6177
+ "- \u6280\u80FD\u76EE\u5F55\u5206\u4E24\u534A\uFF1A`hcm-skills/sync/` \u662F\u4EA7\u54C1\u7684\uFF08\u540C\u6B65\u7EF4\u62A4\uFF0C\u522B\u624B\u6539\uFF09\uFF0C`hcm-skills/local/` \u662F\u8FD9\u4E2A\u9879\u76EE\u81EA\u5DF1\u7684\uFF08\u540C\u6B65\u4E0D\u78B0\uFF09\u3002\u8981\u6539\u4E00\u4EFD\u4EA7\u54C1\u6280\u80FD\uFF0C\u590D\u5236\u5230 `local/` \u6539\u2014\u2014\u540C\u540D\u65F6\u5B83\u906E\u853D\u4EA7\u54C1\u90A3\u4EFD\uFF0C\u800C\u4EA7\u54C1\u90A3\u4EFD\u7EE7\u7EED\u8DDF\u7740\u66F4\u65B0\u3002",
6177
6178
  "- **\u63A5\u5230\u9700\u6C42\u5148\u505A\u4E00\u8F6E\u53EA\u8BFB\u6838\u5BF9**\uFF08\u8FB9\u754C\u3001\u6280\u80FD\u6E05\u5355\u3001CLI \u7248\u672C\u3001\u73AF\u5883\u4E0E\u8EAB\u4EFD\uFF09\uFF0C\u7ED9\u51FA READY / READY WITH RISKS / BLOCKED \u518D\u52A8\u624B\u3002\u987E\u95EE\u4E0D\u9700\u8981\u7C98\u4EFB\u4F55\u5F00\u573A\u767D\uFF0C\u8FD9\u6761\u5C31\u662F\u5F00\u573A\u767D\u3002",
6178
6179
  "- \u9700\u6C42\u8BF4\u5F97\u542B\u7CCA\u5C31\u8FFD\u95EE\uFF0C\u4E0D\u8981\u66FF\u5BA2\u6237\u731C\u53E3\u5F84\uFF1B\u53E3\u5F84\u4E0E\u8303\u56F4\u5199\u8FDB `requirements/`\uFF0C\u5BA2\u6237\u62CD\u677F\u7684\u5199\u8FDB `decisions/`\u3002",
6179
6180
  "- \u9879\u76EE\u5BF9\u7740\u7684\u73AF\u5883\u5728 `env.yaml`\uFF08default / environments\uFF0C\u5404\u73AF\u5883\u542B endpoint / frontend / tenant / roles\uFF09\uFF0C\u8EAB\u4EFD\u5728\u672C\u673A `hcm login`\u3002\u6BCF\u6B21\u5F00\u5DE5\u5148\u8DD1 `hcm chiron doctor`\uFF1B\u73AF\u5883\u4E8B\u5B9E\u5FC5\u987B\u73B0\u67E5\uFF0C\u4E0D\u51ED\u8BB0\u5FC6\u586B\u5199\u3002",
@@ -6195,137 +6196,487 @@ function mergeBoundaryBlock(existing, fromProduct) {
6195
6196
  return { text: upsertBlock(existing, AGENT_BEGIN, AGENT_END, block.trimEnd()), source };
6196
6197
  }
6197
6198
 
6198
- // src/commands/skills-bundled.ts
6199
- import { promises as fsp } from "fs";
6200
- import * as path5 from "path";
6201
- import { CliError as CliError18, CliErrorCode as CliErrorCode17, assertSafeReferencePath, parseSkillRequirements } from "@hcmai/sdk";
6199
+ // src/commands/chiron-project.ts
6200
+ import { promises as fs7 } from "fs";
6201
+ import path5 from "path";
6202
6202
 
6203
- // src/commands/skills-manifest.ts
6204
- import { readFileSync as readFileSync4, readdirSync as readdirSync2, statSync as statSync3, existsSync } from "fs";
6205
- import { createHash as createHash3 } from "crypto";
6206
- import * as path4 from "path";
6207
- import { fileURLToPath } from "url";
6208
- import { formatObject as formatObject15, parseSkillFrontmatter } from "@hcmai/sdk";
6209
- function collectCommandSurface(root) {
6210
- const out = [];
6211
- const walk = (cmd, prefix) => {
6212
- for (const sub of cmd.commands) {
6213
- const segs = [...prefix, sub.name()];
6214
- const options = sub.options.map((o) => /(--[a-zA-Z0-9][\w-]*)/.exec(o.flags)?.[1] ?? "").filter((s) => s.length > 0);
6215
- out.push({ path: segs.join(" "), options: [...new Set(options)].sort() });
6216
- walk(sub, segs);
6203
+ // src/commands/chiron-case.ts
6204
+ init_exit();
6205
+ import { execFileSync } from "child_process";
6206
+ import { cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync as readFileSync4, rmSync, statSync as statSync3, writeFileSync as writeFileSync2 } from "fs";
6207
+ import os2 from "os";
6208
+ import path4 from "path";
6209
+ import { CASES_REPO_SLUG, CASES_REPO_URL, CNB_ORIGIN, CliError as CliError18, CliErrorCode as CliErrorCode17, formatObject as formatObject15 } from "@hcmai/sdk";
6210
+ var casesCacheDir = () => process.env.HCM_CASES_CACHE?.trim() || path4.join(os2.homedir(), ".cache", "hcm", "chiron-cases");
6211
+ var INDEX_CACHE = () => path4.join(casesCacheDir(), "index.json");
6212
+ var INDEX_TTL_MS = 60 * 60 * 1e3;
6213
+ var fail5 = (message, nextStep) => new CliError18({ code: CliErrorCode17.INVALID_ARGUMENT, message, context: { nextStep } });
6214
+ var run = (cmd, args, opts = {}) => execFileSync(cmd, args, { encoding: "utf8", maxBuffer: 1 << 26, ...opts });
6215
+ function fetchRepoFile(relPath) {
6216
+ let raw;
6217
+ try {
6218
+ raw = run("cnb", ["git", "get-raw", "--repo", CASES_REPO_SLUG, "--ref-with-path", `main/${relPath}`]);
6219
+ } catch (e) {
6220
+ throw fail5(
6221
+ `\u53D6\u4E0D\u5230\u6848\u4F8B\u5E93\u6587\u4EF6 ${relPath}\uFF1A${String(e.message).split("\n")[0]}`,
6222
+ "\u6848\u4F8B\u5E93\u8BFB\u53D6\u8D70 cnb\uFF08\u9700\u8981\u5DF2 `cnb login` \u4E14\u6709\u8BE5\u4ED3\u8BFB\u6743\u9650\uFF09\u3002\u6CA1\u6709\u6743\u9650\u5C31\u5148\u8DF3\u8FC7\u6848\u4F8B\u5E93\uFF0C\u76F4\u63A5\u6309\u6280\u80FD\u505A\uFF1B\u522B\u628A\u300C\u53D6\u4E0D\u5230\u300D\u5F53\u6210\u300C\u6CA1\u6709\u5148\u4F8B\u300D\u3002"
6223
+ );
6224
+ }
6225
+ const i = raw.indexOf("data: ");
6226
+ if (i < 0) throw fail5(`cnb \u7684\u56DE\u6267\u91CC\u6CA1\u6709 data \u90A3\u4E00\u683C\uFF1A${relPath}`, "\u5347\u7EA7 cnb CLI\uFF0C\u6216\u628A\u8FD9\u6BB5\u539F\u6837\u8D34\u7ED9\u6211\u3002");
6227
+ const body = raw.slice(i + "data: ".length).trim();
6228
+ if (body.startsWith('"')) {
6229
+ try {
6230
+ return JSON.parse(body);
6231
+ } catch {
6232
+ return body;
6217
6233
  }
6218
- };
6219
- walk(root, []);
6220
- return out.sort((a, b) => a.path.localeCompare(b.path));
6221
- }
6222
- function bundledSkillsDir() {
6223
- const here = path4.dirname(fileURLToPath(import.meta.url));
6224
- return path4.join(here, "skills");
6225
- }
6226
- function sha256(buf) {
6227
- return createHash3("sha256").update(buf).digest("hex");
6234
+ }
6235
+ return body;
6228
6236
  }
6229
- function listFiles(dir, rel = "") {
6230
- const out = [];
6231
- for (const name of readdirSync2(dir)) {
6232
- const p = path4.join(dir, name);
6233
- const r = rel ? `${rel}/${name}` : name;
6234
- if (statSync3(p).isDirectory()) out.push(...listFiles(p, r));
6235
- else out.push(r);
6237
+ function loadIndex(opts = {}) {
6238
+ const file = INDEX_CACHE();
6239
+ const fresh = !opts.refresh && existsSync(file) && Date.now() - statSync3(file).mtimeMs < INDEX_TTL_MS;
6240
+ if (fresh) return JSON.parse(readFileSync4(file, "utf8"));
6241
+ let text;
6242
+ try {
6243
+ text = fetchRepoFile("index/index.json");
6244
+ } catch (e) {
6245
+ if (!existsSync(file)) throw e;
6246
+ process.stderr.write(
6247
+ `[hcm] \u7D22\u5F15\u6CA1\u62C9\u52A8\uFF08${e.message.split("\n")[0]}\uFF09\uFF0C\u7528\u672C\u673A\u7F13\u5B58\u7684\u90A3\u4EFD\uFF1A${file}
6248
+ `
6249
+ );
6250
+ return JSON.parse(readFileSync4(file, "utf8"));
6236
6251
  }
6237
- return out;
6252
+ mkdirSync(path4.dirname(file), { recursive: true });
6253
+ writeFileSync2(file, text);
6254
+ return JSON.parse(text);
6238
6255
  }
6239
- function collectBundledSkills(dir = bundledSkillsDir()) {
6240
- if (!existsSync(dir)) return [];
6241
- const out = [];
6242
- for (const id of readdirSync2(dir).sort()) {
6243
- const skillDir = path4.join(dir, id);
6244
- if (!statSync3(skillDir).isDirectory()) continue;
6245
- const files = listFiles(skillDir).sort();
6246
- if (!files.includes("SKILL.md")) continue;
6247
- let bytes = 0;
6248
- const fileRows = files.map((rel) => {
6249
- const buf = readFileSync4(path4.join(skillDir, rel));
6250
- bytes += buf.byteLength;
6251
- return { path: rel, bytes: buf.byteLength, sha256: sha256(buf) };
6252
- });
6253
- const body = readFileSync4(path4.join(skillDir, "SKILL.md"), "utf8");
6254
- const fm = parseSkillFrontmatter(body, id);
6255
- out.push({
6256
- id,
6257
- title: str(fm.title),
6258
- description: str(fm.description),
6259
- category: str(fm.category),
6260
- stages: strArray(fm.stages),
6261
- actionSurface: str(fm.actionSurface),
6262
- requires: strArray(fm.requires),
6263
- bytes,
6264
- files: fileRows
6265
- });
6256
+ function backendFingerprint(env2) {
6257
+ if (!env2) return { reason: "\u6CA1\u7ED9 --env\uFF0C\u6CA1\u6CD5\u73B0\u67E5\u6307\u7EB9" };
6258
+ try {
6259
+ const raw = run(process.execPath, [process.argv[1], "version", "--env", env2, "--output", "json"]);
6260
+ const j = JSON.parse(raw.slice(raw.indexOf("{")));
6261
+ const backend = j.backend?.commit ?? j.commit ?? j.server?.commit;
6262
+ if (!backend) return { reason: "\u540E\u7AEF\u56DE\u6267\u91CC\u6CA1\u6709 commit \u5B57\u6BB5" };
6263
+ return { backend: String(backend), cli: String(j.cli?.version ?? j.cliVersion ?? "") };
6264
+ } catch (e) {
6265
+ return { reason: String(e.message).split("\n")[0]?.slice(0, 120) };
6266
6266
  }
6267
- return out;
6268
6267
  }
6269
- function buildManifest(root, skillsDir = bundledSkillsDir()) {
6270
- return {
6271
- schemaVersion: 1,
6272
- cliVersion: CLI_VERSION,
6273
- commands: collectCommandSurface(root),
6274
- skills: collectBundledSkills(skillsDir)
6275
- };
6268
+ function matchTag(c, fp) {
6269
+ if (!fp.backend) return `\u672A\u6BD4\u5BF9\uFF08${fp.reason ?? "\u6CA1\u6709\u6307\u7EB9"}\uFF09`;
6270
+ const be = String(c.fingerprint?.backend_commit ?? "");
6271
+ if (!be) return "\u6848\u4F8B\u6CA1\u8BB0\u540E\u7AEF\u6307\u7EB9";
6272
+ const a = be.slice(0, 12);
6273
+ const b = fp.backend.slice(0, 12);
6274
+ return a === b ? "\u5339\u914D" : `\u4E0D\u5339\u914D\uFF08\u6848\u4F8B ${a} / \u5F53\u524D ${b}\uFF09`;
6276
6275
  }
6277
- function skillsManifestCommand(root, args) {
6278
- const manifest2 = buildManifest(root);
6279
- process.stdout.write(formatObject15(manifest2, { format: args.output ?? "json" }) + "\n");
6276
+ function emit4(args, data, text) {
6277
+ if (args.output === "json" || args.output === "yaml") {
6278
+ process.stdout.write(formatObject15(data, { format: args.output }) + "\n");
6279
+ } else {
6280
+ process.stdout.write(text() + "\n");
6281
+ }
6280
6282
  }
6281
- function str(v) {
6282
- return typeof v === "string" && v ? v : void 0;
6283
+ async function guard(fn) {
6284
+ try {
6285
+ await fn();
6286
+ } catch (e) {
6287
+ exitWithError(e);
6288
+ }
6283
6289
  }
6284
- function strArray(v) {
6285
- return Array.isArray(v) ? v.map(String) : void 0;
6290
+ async function caseSearchCommand(query, args) {
6291
+ await guard(async () => {
6292
+ const idx = loadIndex({ refresh: args.refresh });
6293
+ const fp = backendFingerprint(args.env);
6294
+ let raw;
6295
+ try {
6296
+ raw = run("cnb", [
6297
+ "knowledge-base",
6298
+ "query-knowledge-base-get",
6299
+ "--repo",
6300
+ CASES_REPO_SLUG,
6301
+ "--query",
6302
+ query,
6303
+ "--top-k",
6304
+ String(args.topK ?? 5),
6305
+ "--verbose"
6306
+ ]);
6307
+ } catch (e) {
6308
+ throw fail5(
6309
+ `\u6848\u4F8B\u5E93\u68C0\u7D22\u6CA1\u8DD1\u6210\uFF1A${String(e.message).split("\n")[0]}`,
6310
+ "\u68C0\u7D22\u8D70 cnb \u7684\u77E5\u8BC6\u5E93\u63A5\u53E3\uFF0C\u9700\u8981 cnb \u5DF2\u767B\u5F55\u4E14\u6709\u6848\u4F8B\u5E93\u6743\u9650\u3002\u6CA1\u6709\u5C31\u5148\u8DF3\u8FC7\u6848\u4F8B\u5E93\uFF0C\u76F4\u63A5\u6309\u6280\u80FD\u505A\uFF1B\u522B\u628A\u300C\u67E5\u4E0D\u5230\u300D\u5F53\u6210\u300C\u6CA1\u6709\u5148\u4F8B\u300D\u3002"
6311
+ );
6312
+ }
6313
+ const json = JSON.parse(raw.slice(raw.indexOf("{")));
6314
+ const seen = /* @__PURE__ */ new Map();
6315
+ for (const h of json.data ?? []) {
6316
+ const p = h.metadata?.path ?? "";
6317
+ const m = /^cases\/[^/]+\/([^/]+)\//.exec(p);
6318
+ if (!m) continue;
6319
+ const id = m[1];
6320
+ if (seen.has(id)) continue;
6321
+ const c = idx.cases.find((x) => x.id === id);
6322
+ seen.set(id, {
6323
+ id,
6324
+ score: h.score,
6325
+ file: p.split("/").pop(),
6326
+ status: c?.status,
6327
+ tier: c?.tier,
6328
+ skills: c?.skills,
6329
+ customer_ask: c?.customer_ask,
6330
+ match: c ? matchTag(c, fp) : "\u7D22\u5F15\u91CC\u6CA1\u6709\uFF08\u672C\u673A clone \u53EF\u80FD\u65E7\u4E86\uFF0Cgit pull \u4E00\u6B21\uFF09"
6331
+ });
6332
+ }
6333
+ const rows2 = [...seen.values()];
6334
+ emit4(
6335
+ args,
6336
+ { query, rows: rows2 },
6337
+ () => rows2.length ? rows2.map((r) => `${r.id} [${r.status ?? "?"}\xB7${r.match}] ${r.customer_ask ?? ""}
6338
+ \u6280\u80FD\uFF1A${(r.skills ?? []).join(" / ") || "\uFF08\u672A\u767B\u8BB0\uFF09"}`).join("\n") : `\u6CA1\u6709\u547D\u4E2D\u300C${query}\u300D\u7684\u6848\u4F8B\u3002\u5148\u6309\u6280\u80FD\u505A\uFF0C\u8DD1\u901A\u4E86\u7528 \`hcm chiron case submit\` \u4E0A\u884C\u4E00\u6761\u3002`
6339
+ );
6340
+ });
6286
6341
  }
6342
+ async function caseShowCommand(id, args) {
6343
+ await guard(async () => {
6344
+ const idx = loadIndex({ refresh: args.refresh });
6345
+ const c = idx.cases.find((x) => x.id === id);
6346
+ if (!c?.path) {
6347
+ throw fail5(
6348
+ `\u7D22\u5F15\u91CC\u6CA1\u6709\u6848\u4F8B ${id}`,
6349
+ `\u5148 \`hcm chiron case search <\u5173\u952E\u8BCD>\` \u62FF\u51C6\u786E\u7684 id\uFF1B\u7D22\u5F15\u53EF\u80FD\u65E7\u4E86\uFF0C\u52A0 --refresh \u518D\u8BD5\u4E00\u6B21\u3002`
6350
+ );
6351
+ }
6352
+ const files = args.file ? [args.file] : ["\u95EE\u9898.md", "\u65B9\u6848.md"];
6353
+ const parts = [];
6354
+ for (const f of files) {
6355
+ try {
6356
+ parts.push(`# ${f}
6287
6357
 
6288
- // src/commands/skills-bundled.ts
6289
- function listBundledSkills(dir = bundledSkillsDir()) {
6290
- return collectBundledSkills(dir);
6358
+ ${fetchRepoFile(`${c.path}/${f}`)}`);
6359
+ } catch {
6360
+ parts.push(`# ${f}
6361
+
6362
+ \uFF08\u8FD9\u4E2A\u6848\u4F8B\u6CA1\u6709\u8FD9\u4EFD\u6587\u4EF6\uFF09`);
6363
+ }
6364
+ }
6365
+ const meta2 = fetchRepoFile(`${c.path}/case.yml`);
6366
+ emit4(
6367
+ args,
6368
+ { id, caseYml: meta2, files: parts },
6369
+ () => `case.yml:
6370
+ ${meta2}
6371
+
6372
+ ${parts.join("\n\n---\n\n")}
6373
+
6374
+ \uFF08\u8BC1\u636E\u6587\u4EF6\u6CA1\u6709\u4E0B\u8F7D \u2014\u2014 \u53BB ${CNB_ORIGIN}/${CASES_REPO_SLUG}/-/tree/main/${c.path} \u770B\uFF09`
6375
+ );
6376
+ });
6291
6377
  }
6292
- function unreachable(id, detail) {
6293
- return new CliError18({
6294
- code: CliErrorCode17.SKILL_SOURCE_UNREACHABLE,
6295
- message: `\u88C5\u5728\u8FD9\u4EFD CLI \u91CC\u7684\u6280\u80FD\u8D44\u6E90\u8BFB\u4E0D\u5230\uFF08${detail}\uFF09\uFF0C\u91CD\u88C5 @hcmai/cli\u3002
6296
- \u6280\u80FD id\uFF1A${id}\uFF1B\u627E\u7684\u4F4D\u7F6E\uFF1A${bundledSkillsDir()}`
6378
+ async function caseMatchCommand(args) {
6379
+ await guard(async () => {
6380
+ const idx = loadIndex({ refresh: args.refresh });
6381
+ const fp = backendFingerprint(args.env);
6382
+ const rows2 = idx.cases.filter((c) => c.status === "approved").map((c) => ({ id: c.id, match: matchTag(c, fp), skills: c.skills, customer_ask: c.customer_ask }));
6383
+ emit4(args, { fingerprint: fp, rows: rows2 }, () => {
6384
+ const head = fp.backend ? `\u5F53\u524D\u540E\u7AEF ${fp.backend.slice(0, 12)}\uFF08env ${args.env}\uFF09` : `\u26A0\uFE0F \u6CA1\u53D6\u5230\u5F53\u524D\u6307\u7EB9\uFF08${fp.reason}\uFF09\u2014\u2014\u4E0B\u9762\u6BCF\u4E00\u6761\u90FD\u6807\u7740\u300C\u672A\u6BD4\u5BF9\u300D\uFF0C\u522B\u628A\u5B83\u8BFB\u6210\u300C\u90FD\u80FD\u7167\u505A\u300D`;
6385
+ return [head, ...rows2.map((r) => `${r.match === "\u5339\u914D" ? "\u2705" : "\xB7 "} ${r.id} [${r.match}] ${r.customer_ask ?? ""}`)].join("\n");
6386
+ });
6297
6387
  });
6298
6388
  }
6299
- async function readBundledReferences(skillDir) {
6300
- const root = path5.join(skillDir, "references");
6301
- const out = [];
6302
- const walk = async (dir, prefix) => {
6303
- let items;
6304
- try {
6305
- items = await fsp.readdir(dir, { withFileTypes: true });
6306
- } catch (cause) {
6307
- if (cause?.code === "ENOENT") return;
6308
- throw cause;
6389
+ async function caseSubmitCommand(dir, args) {
6390
+ await guard(async () => {
6391
+ const src = path4.resolve(dir);
6392
+ if (!existsSync(path4.join(src, "case.yml"))) {
6393
+ throw fail5(`${src} \u91CC\u6CA1\u6709 case.yml`, "\u6307\u5230\u9879\u76EE\u4ED3\u7684\u6848\u4F8B\u76EE\u5F55\uFF08\u5982 cases/CASE-20260902-xxx\uFF09\uFF0C\u90A3\u91CC\u5E94\u5F53\u6709 case.yml\u3002");
6309
6394
  }
6310
- for (const item of items.sort((a, b) => a.name.localeCompare(b.name))) {
6311
- const relative2 = prefix ? `${prefix}/${item.name}` : item.name;
6312
- if (item.isDirectory()) {
6313
- await walk(path5.join(dir, item.name), relative2);
6314
- continue;
6395
+ const yamlText = readFileSync4(path4.join(src, "case.yml"), "utf8");
6396
+ const id = /^\s*(?:id|case_id):\s*(\S+)/m.exec(yamlText)?.[1];
6397
+ if (!id) throw fail5("case.yml \u91CC\u6CA1\u6709 id", "case.yml \u9876\u5C42\u8981\u6709 `id: CASE-YYYYMMDD-xxx`\u3002");
6398
+ const work = mkdtempSync(path4.join(os2.tmpdir(), "hcm-case-submit-"));
6399
+ try {
6400
+ const repo = path4.join(work, "chiron-cases");
6401
+ try {
6402
+ run("git", ["clone", "--depth", "1", "--filter=blob:none", "--quiet", CASES_REPO_URL, repo]);
6403
+ } catch (e) {
6404
+ throw fail5(
6405
+ `clone \u6848\u4F8B\u5E93\u5931\u8D25\uFF1A${String(e.message).split("\n")[0]}`,
6406
+ `\u4E0A\u884C\u8981\u5F80 ${CASES_REPO_SLUG} \u63D0 PR\uFF0C\u9700\u8981\u8BE5\u4ED3\u5199\u6743\u9650\uFF08\`cnb login\` \u4E14\u88AB\u52A0\u8FDB\u4ED3\uFF09\u3002\u6848\u4F8B\u8FD8\u5728\u4F60\u7684\u9879\u76EE\u4ED3\u91CC\uFF0C\u6CA1\u4E22\u3002`
6407
+ );
6315
6408
  }
6316
- if (!item.isFile()) continue;
6409
+ const branch = `case/${id}-submit`;
6410
+ run("git", ["-C", repo, "checkout", "-q", "-B", branch]);
6411
+ const dst = path4.join(repo, "cases", args.category, id);
6412
+ cpSync(src, dst, { recursive: true, filter: (p) => !p.includes("node_modules") });
6413
+ mkdirSync(path4.join(dst, "evidence"), { recursive: true });
6414
+ let doc = readFileSync4(path4.join(dst, "case.yml"), "utf8");
6415
+ doc = /^\s*tier:/m.test(doc) ? doc.replace(/^\s*tier:.*$/m, "tier: public") : `tier: public
6416
+ ${doc}`;
6417
+ doc = /^\s*category:/m.test(doc) ? doc.replace(/^\s*category:.*$/m, `category: ${args.category}`) : `category: ${args.category}
6418
+ ${doc}`;
6419
+ doc = /^\s*origin:/m.test(doc) ? doc.replace(/^\s*origin:.*$/m, `origin: ${args.origin}`) : `origin: ${args.origin}
6420
+ ${doc}`;
6421
+ if (!/^\s*status:/m.test(doc)) doc = `status: approved
6422
+ ${doc}`;
6423
+ writeFileSync2(path4.join(dst, "case.yml"), doc);
6424
+ run("python3", ["scripts/render-readme.py", dst], { cwd: repo });
6425
+ let lint;
6426
+ try {
6427
+ lint = run("python3", ["scripts/lint-case.py"], { cwd: repo });
6428
+ } catch (e) {
6429
+ throw fail5(
6430
+ `\u6848\u4F8B lint \u6CA1\u8FC7\uFF0CPR \u6CA1\u5F00\uFF1A
6431
+ ${e.stdout ?? e.message}`,
6432
+ "\u7167 lint \u7684\u63D0\u793A\u8865\u9F50 case.yml \u4E0E\u6B63\u6587\uFF0C\u518D\u8DD1\u4E00\u6B21\u3002\u6848\u4F8B\u8FD8\u5728\u9879\u76EE\u4ED3\u91CC\uFF0C\u6CA1\u4E22\u3002"
6433
+ );
6434
+ }
6435
+ run("python3", ["scripts/build-index.py"], { cwd: repo });
6436
+ run("git", ["-C", repo, "add", "-A"]);
6437
+ run("git", ["-C", repo, "-c", "user.name=hcm-cli", "-c", "user.email=chiron@local", "commit", "-q", "-m", `case: ${id}\uFF08\u9879\u76EE\u6848\u4F8B\u4E0A\u884C\uFF09`]);
6438
+ run("git", ["-C", repo, "push", "-q", "-f", "-u", "origin", branch]);
6439
+ const pr = run("cnb", [
6440
+ "pulls",
6441
+ "post-pull",
6442
+ "--repo",
6443
+ CASES_REPO_SLUG,
6444
+ "--base",
6445
+ "main",
6446
+ "--head",
6447
+ branch,
6448
+ "--title",
6449
+ `case: ${id}\uFF08\u9879\u76EE\u6848\u4F8B\u4E0A\u884C\uFF09`,
6450
+ "--body",
6451
+ `\u6765\u6E90\uFF1A${args.origin}
6452
+
6453
+ \u7531 \`hcm chiron case submit\` \u63D0\u4EA4\uFF0Clint \u5DF2\u8FC7\u3002`
6454
+ ]);
6455
+ const num = /number: "?(\d+)/.exec(pr)?.[1];
6456
+ rmSync(INDEX_CACHE(), { force: true });
6457
+ emit4(
6458
+ args,
6459
+ { id, pr: num, lint: lint.trim() },
6460
+ () => `\u5DF2\u5F00 PR #${num ?? "?"}\uFF1A${CNB_ORIGIN}/${CASES_REPO_SLUG}/-/pulls/${num ?? ""}
6461
+ ${lint.trim()}`
6462
+ );
6463
+ } finally {
6464
+ rmSync(work, { recursive: true, force: true });
6465
+ }
6466
+ });
6467
+ }
6468
+
6469
+ // src/commands/chiron-project.ts
6470
+ import { normalizeOrigin as normalizeOrigin2 } from "@hcmai/sdk";
6471
+ import { JIRA_BASE, JIRA_PROJECT, jiraTokenSource } from "@hcmai/sdk";
6472
+ import { ENV_FILE, parseEnvYaml, renderEnvYaml, findEnvByEndpoint as findEnvByEndpoint3, normalizeOrigin as normalizeOrigin3 } from "@hcmai/sdk";
6473
+ import { CASES_REPO_URL as CASES_REPO_URL2 } from "@hcmai/sdk";
6474
+ import { JIRA_BASE as JIRA_BASE2, JIRA_PROJECT as JIRA_PROJECT2, JIRA_TOKEN_FILE, jiraTokenSource as jiraTokenSource2 } from "@hcmai/sdk";
6475
+ var SKILLS_DIR = "hcm-skills";
6476
+ var SKILLS_SYNC_SUBDIR = "sync";
6477
+ var SKILLS_LOCAL_SUBDIR = "local";
6478
+ function skillsSyncDir(root) {
6479
+ return path5.join(root, SKILLS_DIR, SKILLS_SYNC_SUBDIR);
6480
+ }
6481
+ function skillsLocalDir(root) {
6482
+ return path5.join(root, SKILLS_DIR, SKILLS_LOCAL_SUBDIR);
6483
+ }
6484
+ var CHIRON_PROJECT_DIRECTORIES = [
6485
+ "work",
6486
+ "decisions",
6487
+ "evidence",
6488
+ "requirements",
6489
+ "deliverables",
6490
+ "cases",
6491
+ "gaps",
6492
+ "customer-docs"
6493
+ ];
6494
+ function projectEnvFromConfig(cfg) {
6495
+ const endpoint = normalizeOrigin2(cfg.endpoint);
6496
+ return {
6497
+ endpoint,
6498
+ // 冗余一份 frontend:前后端地址不一致的部署里,页面验收要开的是它。
6499
+ frontend: normalizeOrigin2(cfg.frontend ?? endpoint),
6500
+ tenant: cfg.tenantId ?? "1"
6501
+ };
6502
+ }
6503
+ async function inspectCaseLibrary() {
6504
+ try {
6505
+ const idx = loadIndex();
6506
+ return { ok: true, count: idx.cases.length };
6507
+ } catch (e) {
6508
+ return { ok: false, reason: firstLine("", e) };
6509
+ }
6510
+ }
6511
+ function firstLine(stderr, error) {
6512
+ if (error) return error.message;
6513
+ const line = stderr.split(/\r?\n/).map((l) => l.trim()).find(Boolean);
6514
+ return line ?? "\uFF08\u65E0\u8F93\u51FA\uFF09";
6515
+ }
6516
+ async function inspectJira() {
6517
+ const src = await jiraTokenSource();
6518
+ if (!src) {
6519
+ return {
6520
+ ok: false,
6521
+ reason: `\u6CA1\u6709\u4EE4\u724C\u3002\u5728 ${JIRA_BASE} \u53F3\u4E0A\u89D2\u5934\u50CF \u2192 \u4E2A\u4EBA\u8BBE\u7F6E \u2192 Personal Access Tokens \u5EFA\u4E00\u4E2A\uFF0C\u7136\u540E\uFF1Amkdir -p ~/.config/hcm && read -rs pat && printf "%s" "$pat" > ~/.config/hcm/jira-token && chmod 600 ~/.config/hcm/jira-token && unset pat`
6522
+ };
6523
+ }
6524
+ const call = async (path_) => {
6525
+ const res = await fetch(`${JIRA_BASE}${path_}`, {
6526
+ headers: { Authorization: `Bearer ${src.token}`, Accept: "application/json" },
6527
+ signal: AbortSignal.timeout(15e3)
6528
+ });
6529
+ return res;
6530
+ };
6531
+ try {
6532
+ const me = await call("/rest/api/2/myself");
6533
+ if (me.status === 401) return { ok: false, from: src.from, reason: "\u4EE4\u724C\u65E0\u6548\u6216\u5DF2\u8FC7\u671F\uFF0C\u91CD\u5EFA PAT \u540E\u91CD\u65B0\u5B58\u4E00\u6B21" };
6534
+ if (!me.ok) return { ok: false, from: src.from, reason: `\u8FDE\u5F97\u4E0A\u4F46 /myself \u8FD4\u56DE ${me.status}` };
6535
+ const who = (await me.json()).displayName ?? "";
6536
+ const project = await call(`/rest/api/2/project/${JIRA_PROJECT}`);
6537
+ return {
6538
+ ok: project.ok,
6539
+ from: src.from,
6540
+ who,
6541
+ projectVisible: project.ok,
6542
+ reason: project.ok ? void 0 : `\u770B\u4E0D\u5230\u9879\u76EE ${JIRA_PROJECT}\uFF08${project.status}\uFF09\uFF0C\u627E Jira \u7BA1\u7406\u5458\u5F00\u6743\u9650`
6543
+ };
6544
+ } catch (e) {
6545
+ return { ok: false, from: src.from, reason: `\u8FDE\u4E0D\u4E0A ${JIRA_BASE}\uFF1A${e.message}` };
6546
+ }
6547
+ }
6548
+
6549
+ // src/commands/skills-bundled.ts
6550
+ import { promises as fsp } from "fs";
6551
+ import * as path7 from "path";
6552
+ import { CliError as CliError19, CliErrorCode as CliErrorCode18, assertSafeReferencePath, parseSkillRequirements } from "@hcmai/sdk";
6553
+
6554
+ // src/commands/skills-manifest.ts
6555
+ import { readFileSync as readFileSync5, readdirSync as readdirSync2, statSync as statSync4, existsSync as existsSync2 } from "fs";
6556
+ import { createHash as createHash3 } from "crypto";
6557
+ import * as path6 from "path";
6558
+ import { fileURLToPath } from "url";
6559
+ import { formatObject as formatObject16, parseSkillFrontmatter } from "@hcmai/sdk";
6560
+ function collectCommandSurface(root) {
6561
+ const out = [];
6562
+ const walk = (cmd, prefix) => {
6563
+ for (const sub of cmd.commands) {
6564
+ const segs = [...prefix, sub.name()];
6565
+ const options = sub.options.map((o) => /(--[a-zA-Z0-9][\w-]*)/.exec(o.flags)?.[1] ?? "").filter((s) => s.length > 0);
6566
+ out.push({ path: segs.join(" "), options: [...new Set(options)].sort() });
6567
+ walk(sub, segs);
6568
+ }
6569
+ };
6570
+ walk(root, []);
6571
+ return out.sort((a, b) => a.path.localeCompare(b.path));
6572
+ }
6573
+ function bundledSkillsDir() {
6574
+ const here = path6.dirname(fileURLToPath(import.meta.url));
6575
+ return path6.join(here, "skills");
6576
+ }
6577
+ function sha256(buf) {
6578
+ return createHash3("sha256").update(buf).digest("hex");
6579
+ }
6580
+ function listFiles(dir, rel = "") {
6581
+ const out = [];
6582
+ for (const name of readdirSync2(dir)) {
6583
+ const p = path6.join(dir, name);
6584
+ const r = rel ? `${rel}/${name}` : name;
6585
+ if (statSync4(p).isDirectory()) out.push(...listFiles(p, r));
6586
+ else out.push(r);
6587
+ }
6588
+ return out;
6589
+ }
6590
+ function collectBundledSkills(dir = bundledSkillsDir()) {
6591
+ if (!existsSync2(dir)) return [];
6592
+ const out = [];
6593
+ for (const id of readdirSync2(dir).sort()) {
6594
+ const skillDir = path6.join(dir, id);
6595
+ if (!statSync4(skillDir).isDirectory()) continue;
6596
+ const files = listFiles(skillDir).sort();
6597
+ if (!files.includes("SKILL.md")) continue;
6598
+ let bytes = 0;
6599
+ const fileRows = files.map((rel) => {
6600
+ const buf = readFileSync5(path6.join(skillDir, rel));
6601
+ bytes += buf.byteLength;
6602
+ return { path: rel, bytes: buf.byteLength, sha256: sha256(buf) };
6603
+ });
6604
+ const body = readFileSync5(path6.join(skillDir, "SKILL.md"), "utf8");
6605
+ const fm = parseSkillFrontmatter(body, id);
6606
+ out.push({
6607
+ id,
6608
+ title: str(fm.title),
6609
+ description: str(fm.description),
6610
+ category: str(fm.category),
6611
+ stages: strArray(fm.stages),
6612
+ actionSurface: str(fm.actionSurface),
6613
+ requires: strArray(fm.requires),
6614
+ bytes,
6615
+ files: fileRows
6616
+ });
6617
+ }
6618
+ return out;
6619
+ }
6620
+ function buildManifest(root, skillsDir = bundledSkillsDir()) {
6621
+ return {
6622
+ schemaVersion: 1,
6623
+ cliVersion: CLI_VERSION,
6624
+ commands: collectCommandSurface(root),
6625
+ skills: collectBundledSkills(skillsDir)
6626
+ };
6627
+ }
6628
+ function skillsManifestCommand(root, args) {
6629
+ const manifest2 = buildManifest(root);
6630
+ process.stdout.write(formatObject16(manifest2, { format: args.output ?? "json" }) + "\n");
6631
+ }
6632
+ function str(v) {
6633
+ return typeof v === "string" && v ? v : void 0;
6634
+ }
6635
+ function strArray(v) {
6636
+ return Array.isArray(v) ? v.map(String) : void 0;
6637
+ }
6638
+
6639
+ // src/commands/skills-bundled.ts
6640
+ function listBundledSkills(dir = bundledSkillsDir()) {
6641
+ return collectBundledSkills(dir);
6642
+ }
6643
+ function unreachable(id, detail) {
6644
+ return new CliError19({
6645
+ code: CliErrorCode18.SKILL_SOURCE_UNREACHABLE,
6646
+ message: `\u88C5\u5728\u8FD9\u4EFD CLI \u91CC\u7684\u6280\u80FD\u8D44\u6E90\u8BFB\u4E0D\u5230\uFF08${detail}\uFF09\uFF0C\u91CD\u88C5 @hcmai/cli\u3002
6647
+ \u6280\u80FD id\uFF1A${id}\uFF1B\u627E\u7684\u4F4D\u7F6E\uFF1A${bundledSkillsDir()}`
6648
+ });
6649
+ }
6650
+ async function readBundledReferences(skillDir) {
6651
+ const root = path7.join(skillDir, "references");
6652
+ const out = [];
6653
+ const walk = async (dir, prefix) => {
6654
+ let items;
6655
+ try {
6656
+ items = await fsp.readdir(dir, { withFileTypes: true });
6657
+ } catch (cause) {
6658
+ if (cause?.code === "ENOENT") return;
6659
+ throw cause;
6660
+ }
6661
+ for (const item of items.sort((a, b) => a.name.localeCompare(b.name))) {
6662
+ const relative2 = prefix ? `${prefix}/${item.name}` : item.name;
6663
+ if (item.isDirectory()) {
6664
+ await walk(path7.join(dir, item.name), relative2);
6665
+ continue;
6666
+ }
6667
+ if (!item.isFile()) continue;
6317
6668
  assertSafeReferencePath(relative2);
6318
- out.push({ path: relative2, content: await fsp.readFile(path5.join(dir, item.name), "utf8") });
6669
+ out.push({ path: relative2, content: await fsp.readFile(path7.join(dir, item.name), "utf8") });
6319
6670
  }
6320
6671
  };
6321
6672
  await walk(root, "");
6322
6673
  return out;
6323
6674
  }
6324
6675
  async function readBundledSkillDocument(id, dir = bundledSkillsDir()) {
6325
- const skillDir = path5.join(dir, id);
6676
+ const skillDir = path7.join(dir, id);
6326
6677
  let markdown;
6327
6678
  try {
6328
- markdown = await fsp.readFile(path5.join(skillDir, "SKILL.md"), "utf8");
6679
+ markdown = await fsp.readFile(path7.join(skillDir, "SKILL.md"), "utf8");
6329
6680
  } catch (cause) {
6330
6681
  if (cause?.code === "ENOENT") throw unreachable(id, "SKILL.md \u4E0D\u5B58\u5728");
6331
6682
  throw cause;
@@ -6348,8 +6699,8 @@ async function resolveBundledClosure(targetId, dir = bundledSkillsDir()) {
6348
6699
  const visit = async (id) => {
6349
6700
  if (state.get(id) === "done") return;
6350
6701
  if (state.get(id) === "visiting") {
6351
- throw new CliError18({
6352
- code: CliErrorCode17.INVALID_ARGUMENT,
6702
+ throw new CliError19({
6703
+ code: CliErrorCode18.INVALID_ARGUMENT,
6353
6704
  message: `\u81EA\u5E26\u6280\u80FD\u4F9D\u8D56\u6210\u73AF\uFF1A${[...stack, id].join(" \u2192 ")}`
6354
6705
  });
6355
6706
  }
@@ -6404,8 +6755,8 @@ async function resolveEndpoint(args) {
6404
6755
  printResolvedEnvironment4(resolved);
6405
6756
  const env2 = resolved.config;
6406
6757
  if (!env2?.endpoint) {
6407
- throw new CliError19({
6408
- code: CliErrorCode18.MISSING_FLAG,
6758
+ throw new CliError20({
6759
+ code: CliErrorCode19.MISSING_FLAG,
6409
6760
  message: "\u672A\u89E3\u6790\u5230 endpoint \u2014\u2014 \u4F20 --endpoint <url>\uFF0C\u6216\u5148 `hcm env add <name> --endpoint <url>`\u3002\uFF08\u6280\u80FD\u5E93\u514D\u8BA4\u8BC1\uFF0C\u4E0D\u9700\u8981\u5148 login\uFF09"
6410
6761
  });
6411
6762
  }
@@ -6424,8 +6775,8 @@ function decideTrackedEndpoint(options) {
6424
6775
  }
6425
6776
  if (!recorded) {
6426
6777
  if (!current) {
6427
- throw new CliError19({
6428
- code: CliErrorCode18.MISSING_FLAG,
6778
+ throw new CliError20({
6779
+ code: CliErrorCode19.MISSING_FLAG,
6429
6780
  message: "\u672A\u89E3\u6790\u5230 endpoint \u2014\u2014 \u4F20 --endpoint <url>\uFF0C\u6216\u5148 `hcm env add <name> --endpoint <url>`\u3002\uFF08\u6280\u80FD\u5E93\u514D\u8BA4\u8BC1\uFF0C\u4E0D\u9700\u8981\u5148 login\uFF09"
6430
6781
  });
6431
6782
  }
@@ -6449,27 +6800,28 @@ async function exists(target) {
6449
6800
  }
6450
6801
  }
6451
6802
  async function detectTarget(cwd) {
6452
- if (await exists(path6.join(cwd, ".claude"))) return "claude";
6453
- if (await exists(path6.join(cwd, "AGENTS.md"))) return "codex";
6454
- if (await exists(path6.join(cwd, ".codex"))) return "codex";
6803
+ if (await exists(path8.join(cwd, ".claude"))) return "claude";
6804
+ if (await exists(path8.join(cwd, "AGENTS.md"))) return "codex";
6805
+ if (await exists(path8.join(cwd, ".codex"))) return "codex";
6455
6806
  return void 0;
6456
6807
  }
6457
6808
  async function resolveInstallLayout(args, cwd = process.cwd()) {
6458
6809
  const requested = args.target && args.target !== "auto" ? args.target : void 0;
6459
6810
  const target = requested ?? await detectTarget(cwd) ?? "claude";
6460
6811
  if (target === "codex") {
6461
- const root = args.global ? path6.join(os2.homedir(), ".codex") : cwd;
6462
- const claudeFile = path6.join(root, "CLAUDE.md");
6812
+ const root = args.global ? path8.join(os3.homedir(), ".codex") : cwd;
6813
+ const claudeFile = path8.join(root, "CLAUDE.md");
6463
6814
  return {
6464
6815
  target,
6465
- baseDir: args.dir ? path6.resolve(args.dir) : path6.join(root, "hcm-skills"),
6466
- agentsFile: path6.join(root, "AGENTS.md"),
6816
+ baseDir: args.dir ? path8.resolve(args.dir) : skillsSyncDir(root),
6817
+ localDir: args.dir ? void 0 : skillsLocalDir(root),
6818
+ agentsFile: path8.join(root, "AGENTS.md"),
6467
6819
  companionAgentFiles: !args.global && await exists(claudeFile) ? [claudeFile] : []
6468
6820
  };
6469
6821
  }
6470
6822
  return {
6471
6823
  target,
6472
- baseDir: args.dir ? path6.resolve(args.dir) : args.global ? path6.join(os2.homedir(), ".claude", "skills") : path6.join(cwd, ".claude", "skills")
6824
+ baseDir: args.dir ? path8.resolve(args.dir) : args.global ? path8.join(os3.homedir(), ".claude", "skills") : path8.join(cwd, ".claude", "skills")
6473
6825
  };
6474
6826
  }
6475
6827
  async function chironClient(args) {
@@ -6482,7 +6834,7 @@ async function chironClient(args) {
6482
6834
  });
6483
6835
  return { http, endpoint, base: await resolveChironBase(http) };
6484
6836
  }
6485
- function fail5(e, args) {
6837
+ function fail6(e, args) {
6486
6838
  const err = e;
6487
6839
  if (err?.response?.status === 404) {
6488
6840
  exitWithError(new Error("\u8BE5\u73AF\u5883\u6CA1\u6709\u8FD9\u4E2A\u6280\u80FD \u2014\u2014 \u8DD1 `hcm skills list` \u770B\u76EE\u5F55\uFF08\u6280\u80FD\u968F\u4EA7\u54C1\u7248\u672C\u8D70\uFF09"));
@@ -6491,9 +6843,9 @@ function fail5(e, args) {
6491
6843
  exitWithError(e);
6492
6844
  process.exit(1);
6493
6845
  }
6494
- async function skillsListCommand(keyword, args) {
6846
+ async function skillsListCommand(keyword, args, cwd = process.cwd()) {
6495
6847
  try {
6496
- if (args.installed) return await listInstalledSkills(keyword, args);
6848
+ if (args.installed) return await listInstalledSkills(keyword, args, cwd);
6497
6849
  const source = parseSourceFilter(args.source);
6498
6850
  let manifest2;
6499
6851
  let endpoint;
@@ -6506,8 +6858,8 @@ async function skillsListCommand(keyword, args) {
6506
6858
  const catalog = buildUnifiedCatalog({ source, chironManifest: manifest2, bundled, cliVersion: CLI_VERSION });
6507
6859
  const conflicts = detectIdConflicts(catalog);
6508
6860
  if (conflicts.ids.length > 0) {
6509
- throw new CliError19({
6510
- code: CliErrorCode18.SKILL_ID_CONFLICT,
6861
+ throw new CliError20({
6862
+ code: CliErrorCode19.SKILL_ID_CONFLICT,
6511
6863
  message: conflictMessage(conflicts.ids, endpoint ?? "(\u672A\u77E5\u73AF\u5883)")
6512
6864
  });
6513
6865
  }
@@ -6538,7 +6890,7 @@ async function skillsListCommand(keyword, args) {
6538
6890
  }
6539
6891
  if (fmt === "json" || fmt === "yaml") {
6540
6892
  process.stdout.write(
6541
- formatObject16(
6893
+ formatObject17(
6542
6894
  {
6543
6895
  ...manifest2 ?? {},
6544
6896
  categories: cats,
@@ -6615,27 +6967,28 @@ async function skillsListCommand(keyword, args) {
6615
6967
  process.exitCode = 0;
6616
6968
  return;
6617
6969
  } catch (e) {
6618
- fail5(e, args);
6970
+ fail6(e, args);
6619
6971
  }
6620
6972
  }
6621
- async function listInstalledSkills(keyword, args) {
6622
- const layout = await resolveInstallLayout(args);
6973
+ async function listInstalledSkills(keyword, args, cwd = process.cwd()) {
6974
+ const layout = await resolveInstallLayout(args, cwd);
6623
6975
  const state = await readSkillsState(layout.baseDir);
6624
6976
  const fmt = args.output ?? "table";
6625
- if (!state || Object.keys(state.skills).length === 0) {
6977
+ const localSkills = await readLocalSkills(layout.localDir);
6978
+ if ((!state || Object.keys(state.skills).length === 0) && localSkills.length === 0) {
6626
6979
  if (fmt === "json" || fmt === "yaml") {
6627
- process.stdout.write(formatObject16({ baseDir: layout.baseDir, target: layout.target, all: false, skills: [] }, { format: fmt }) + "\n");
6980
+ process.stdout.write(formatObject17({ baseDir: layout.baseDir, target: layout.target, all: false, skills: [] }, { format: fmt }) + "\n");
6628
6981
  process.exitCode = 0;
6629
6982
  return;
6630
6983
  }
6631
- process.stdout.write(`${path6.join(layout.baseDir, SKILLS_STATE_FILE)} \u4E0D\u5B58\u5728\u6216\u4E3A\u7A7A \u2014\u2014 \u8FD9\u4E2A\u76EE\u5F55\u4E0B\u8FD8\u6CA1\u7528\u672C CLI \u88C5\u8FC7\u6280\u80FD\u3002
6984
+ process.stdout.write(`${path8.join(layout.baseDir, SKILLS_STATE_FILE)} \u4E0D\u5B58\u5728\u6216\u4E3A\u7A7A \u2014\u2014 \u8FD9\u4E2A\u76EE\u5F55\u4E0B\u8FD8\u6CA1\u7528\u672C CLI \u88C5\u8FC7\u6280\u80FD\u3002
6632
6985
  `);
6633
6986
  process.stdout.write(" \u5168\u90E8\u88C5\u9F50\uFF1Ahcm chiron skills sync\n");
6634
6987
  process.exitCode = 0;
6635
6988
  return;
6636
6989
  }
6637
6990
  const rows2 = [];
6638
- for (const [id, record] of Object.entries(state.skills).sort(([a], [b]) => a.localeCompare(b))) {
6991
+ for (const [id, record] of Object.entries(state?.skills ?? {}).sort(([a], [b]) => a.localeCompare(b))) {
6639
6992
  const markdown = await readInstalled(layout.baseDir, id);
6640
6993
  let title = id;
6641
6994
  if (markdown !== void 0) {
@@ -6654,17 +7007,28 @@ async function listInstalledSkills(keyword, args) {
6654
7007
  status: markdown === void 0 ? "missing" : sha2562(markdown) !== record.sha256 ? "locally-modified" : "installed"
6655
7008
  });
6656
7009
  }
6657
- const byKeyword = keyword ? rows2.filter((row) => row.id.includes(keyword) || row.title.includes(keyword)) : rows2;
7010
+ const shadowed = new Set(localSkills.map((x) => x.id));
7011
+ const localRows = localSkills.map((x) => ({
7012
+ id: x.id,
7013
+ title: x.title,
7014
+ sourceKind: "local",
7015
+ sourceLocator: path8.relative(path8.dirname(layout.baseDir), x.absolute).split(path8.sep).join("/"),
7016
+ direct: true,
7017
+ installedAt: void 0,
7018
+ status: "installed"
7019
+ }));
7020
+ const allRows = [...rows2.filter((r) => !shadowed.has(r.id)), ...localRows].sort((a, b) => a.id.localeCompare(b.id));
7021
+ const byKeyword = keyword ? allRows.filter((row) => row.id.includes(keyword) || row.title.includes(keyword)) : allRows;
6658
7022
  const sourceFilter = parseSourceFilter(args.source);
6659
7023
  const shown = sourceFilter === "all" ? byKeyword : byKeyword.filter((row) => row.sourceKind === sourceFilter);
6660
- const groupOf = (kind) => kind === "cli" ? "CLI \u81EA\u5E26" : kind === "local" ? "\u672C\u5730\u76EE\u5F55\u88C5\u7684" : "\u777F\u620E\u6280\u80FD\u5E93";
7024
+ const groupOf = (kind) => kind === "cli" ? "CLI \u81EA\u5E26" : kind === "local" ? "\u672C\u9879\u76EE\u81EA\u5DF1\u7684\uFF08hcm-skills/local/\uFF09" : "\u777F\u620E\u6280\u80FD\u5E93";
6661
7025
  if (fmt === "json" || fmt === "yaml") {
6662
- process.stdout.write(formatObject16({
7026
+ process.stdout.write(formatObject17({
6663
7027
  baseDir: layout.baseDir,
6664
7028
  target: layout.target,
6665
- endpoint: state.endpoint,
6666
- all: Boolean(state.all),
6667
- updatedAt: state.updatedAt,
7029
+ endpoint: state?.endpoint,
7030
+ all: Boolean(state?.all),
7031
+ updatedAt: state?.updatedAt,
6668
7032
  // 按来源分组的小计:顾问要能一眼看出「这份是跟着 CLI 走的还是跟着后端走的」
6669
7033
  bySource: {
6670
7034
  cli: shown.filter((r) => r.sourceKind === "cli").length,
@@ -6678,7 +7042,7 @@ async function listInstalledSkills(keyword, args) {
6678
7042
  }
6679
7043
  process.stdout.write(`\u5DF2\u5B89\u88C5\u7684\u6280\u80FD \u2014 ${layout.baseDir}\uFF08${layout.target}\uFF09
6680
7044
  `);
6681
- process.stdout.write(`\u6765\u6E90 ${state.endpoint ?? "\uFF08\u672A\u8BB0\u5F55\uFF09"}` + (state.all ? " \u8DDF\u968F\u5168\u96C6\uFF1A\u662F\n\n" : "\n\n"));
7045
+ process.stdout.write(`\u6765\u6E90 ${state?.endpoint ?? "\uFF08\u672A\u8BB0\u5F55\uFF09"}` + (state?.all ? " \u8DDF\u968F\u5168\u96C6\uFF1A\u662F\n\n" : "\n\n"));
6682
7046
  if (shown.length === 0) {
6683
7047
  process.stdout.write(` \u6CA1\u6709\u5339\u914D\u300C${keyword}\u300D\u7684\u6280\u80FD\uFF08\u5171\u88C5\u4E86 ${rows2.length} \u4E2A\uFF09
6684
7048
  `);
@@ -6709,7 +7073,7 @@ async function listInstalledSkills(keyword, args) {
6709
7073
  modified > 0 ? `${modified} \u4E2A\u672C\u5730\u6539\u8FC7` : "",
6710
7074
  missing > 0 ? `${missing} \u4E2A\u6587\u4EF6\u7F3A\u5931` : ""
6711
7075
  ].filter(Boolean).map((t) => `\uFF0C${t}`).join("") + "\n");
6712
- process.stdout.write(` \u5BF9\u9F50\uFF1Ahcm chiron skills sync${state.all ? "" : "\uFF08\u8FD9\u4E2A\u76EE\u5F55\u5F53\u521D\u53EA\u88C5\u4E86\u6307\u5B9A\u7684\u51E0\u4E2A\uFF1Bsync \u4F1A\u8865\u9F50\u5168\u96C6\uFF09"}
7076
+ process.stdout.write(` \u5BF9\u9F50\uFF1Ahcm chiron skills sync${state?.all ? "" : "\uFF08\u8FD9\u4E2A\u76EE\u5F55\u5F53\u521D\u53EA\u88C5\u4E86\u6307\u5B9A\u7684\u51E0\u4E2A\uFF1Bsync \u4F1A\u8865\u9F50\u5168\u96C6\uFF09"}
6713
7077
  `);
6714
7078
  process.exitCode = 0;
6715
7079
  return;
@@ -6733,7 +7097,7 @@ async function skillsShowCommand(id, args) {
6733
7097
  process.exitCode = 0;
6734
7098
  return;
6735
7099
  } catch (e) {
6736
- fail5(e, args);
7100
+ fail6(e, args);
6737
7101
  }
6738
7102
  }
6739
7103
  async function skillsInstallCommand(id, args) {
@@ -6743,6 +7107,7 @@ async function skillsInstallCommand(id, args) {
6743
7107
  if (!all && !id) throw invalid("\u8981\u88C5\u54EA\u4E2A\u6280\u80FD\uFF1F\u7ED9\u4E2A id\uFF08`hcm skills list` \u770B\u76EE\u5F55\uFF09\uFF0C\u6216\u7528 `--all` \u88C5\u5168\u90E8");
6744
7108
  if (id) assertSafeSkillId(id);
6745
7109
  const layout = await resolveInstallLayout(args);
7110
+ const installDir = args.from && layout.localDir ? layout.localDir : layout.baseDir;
6746
7111
  let documents;
6747
7112
  let requestedIds;
6748
7113
  let endpoint;
@@ -6750,7 +7115,7 @@ async function skillsInstallCommand(id, args) {
6750
7115
  let manifest2;
6751
7116
  let conflictNote;
6752
7117
  if (args.from) {
6753
- const root = path6.resolve(args.from);
7118
+ const root = path8.resolve(args.from);
6754
7119
  requestedIds = all ? await listLocalSkillIds(root) : [id];
6755
7120
  const seen = /* @__PURE__ */ new Set();
6756
7121
  documents = [];
@@ -6769,7 +7134,7 @@ async function skillsInstallCommand(id, args) {
6769
7134
  const tracked = decideTrackedEndpoint({
6770
7135
  explicit: Boolean(args.endpoint || args.env),
6771
7136
  current: await resolveEndpoint(args).catch((error) => {
6772
- if (error instanceof CliError19 && error.code === CliErrorCode18.NO_ACTIVE_ENV) return void 0;
7137
+ if (error instanceof CliError20 && error.code === CliErrorCode19.NO_ACTIVE_ENV) return void 0;
6773
7138
  throw error;
6774
7139
  }),
6775
7140
  recorded: (await readSkillsState(layout.baseDir))?.endpoint
@@ -6783,8 +7148,8 @@ async function skillsInstallCommand(id, args) {
6783
7148
  const catalog = buildUnifiedCatalog({ source, chironManifest: manifest2, bundled, cliVersion: CLI_VERSION });
6784
7149
  const conflicts = detectIdConflicts(catalog);
6785
7150
  if (conflicts.ids.length > 0) {
6786
- throw new CliError19({
6787
- code: CliErrorCode18.SKILL_ID_CONFLICT,
7151
+ throw new CliError20({
7152
+ code: CliErrorCode19.SKILL_ID_CONFLICT,
6788
7153
  message: conflictMessage(conflicts.ids, endpoint ?? "(\u672A\u77E5\u73AF\u5883)")
6789
7154
  });
6790
7155
  }
@@ -6862,7 +7227,7 @@ async function skillsInstallCommand(id, args) {
6862
7227
  const fmtCheck = args.output ?? "table";
6863
7228
  const would = documents.map((d) => d.id).sort();
6864
7229
  if (fmtCheck === "json" || fmtCheck === "yaml") {
6865
- process.stdout.write(formatObject16({
7230
+ process.stdout.write(formatObject17({
6866
7231
  dryRun: true,
6867
7232
  baseDir: layout.baseDir,
6868
7233
  target: layout.target,
@@ -6873,7 +7238,7 @@ async function skillsInstallCommand(id, args) {
6873
7238
  base
6874
7239
  }, { format: fmtCheck }) + "\n");
6875
7240
  } else {
6876
- process.stdout.write(`\u8FD9\u4E2A\u76EE\u5F55\u8FD8\u6CA1\u88C5\u8FC7\u6280\u80FD\uFF08${path6.join(layout.baseDir, SKILLS_STATE_FILE)} \u4E0D\u5B58\u5728\uFF09\u3002
7241
+ process.stdout.write(`\u8FD9\u4E2A\u76EE\u5F55\u8FD8\u6CA1\u88C5\u8FC7\u6280\u80FD\uFF08${path8.join(layout.baseDir, SKILLS_STATE_FILE)} \u4E0D\u5B58\u5728\uFF09\u3002
6877
7242
  `);
6878
7243
  process.stdout.write(`--check\uFF1A\u4F1A\u88C5 ${would.length} \u4E2A\u6280\u80FD\u5230 ${layout.baseDir}\uFF0C\u5E76\u628A\u7D22\u5F15\u4E0E\u9879\u76EE\u8FB9\u754C\u5757\u5199\u8FDB ${layout.agentsFile ?? "AGENTS.md"}\u3002**\u672C\u6B21\u4E00\u4E2A\u5B57\u8282\u90FD\u6CA1\u5199\u3002**
6879
7244
  `);
@@ -6886,19 +7251,20 @@ async function skillsInstallCommand(id, args) {
6886
7251
  process.exitCode = 0;
6887
7252
  return;
6888
7253
  }
6889
- const result = await installSkillDocuments(documents, requestedIds, layout.baseDir, Boolean(args.force), {
7254
+ const result = await installSkillDocuments(documents, requestedIds, installDir, Boolean(args.force), {
6890
7255
  endpoint,
6891
7256
  base,
6892
7257
  target: layout.target,
6893
- all
7258
+ all,
7259
+ recordState: installDir === layout.baseDir
6894
7260
  });
6895
7261
  const agentIndexes = layout.agentsFile ? await syncAgentIndexes(layout, manifest2) : [];
6896
7262
  const agents = agentIndexes[0]?.status;
6897
7263
  const fmt = args.output ?? "table";
6898
7264
  if (fmt === "json" || fmt === "yaml") {
6899
- process.stdout.write(formatObject16({ ...result, all, target_agent: layout.target, agentsFile: layout.agentsFile, agents, agentIndexes, conflictCheck: conflictNote ? { checked: false, note: conflictNote } : { checked: true } }, { format: fmt }) + "\n");
7265
+ process.stdout.write(formatObject17({ ...result, all, target_agent: layout.target, agentsFile: layout.agentsFile, agents, agentIndexes, conflictCheck: conflictNote ? { checked: false, note: conflictNote } : { checked: true } }, { format: fmt }) + "\n");
6900
7266
  } else {
6901
- const headline = all ? `\u2705 \u5168\u90E8 ${requestedIds.length} \u4E2A\u6280\u80FD \u2192 ${result.baseDir}` : `\u2705 ${id} \u2192 ${path6.join(result.baseDir, id, "SKILL.md")}`;
7267
+ const headline = all ? `\u2705 \u5168\u90E8 ${requestedIds.length} \u4E2A\u6280\u80FD \u2192 ${result.baseDir}` : `\u2705 ${id} \u2192 ${path8.join(result.baseDir, id, "SKILL.md")}`;
6902
7268
  process.stdout.write(`${headline}
6903
7269
  `);
6904
7270
  if (result.installed.length > 0) {
@@ -6917,14 +7283,14 @@ async function skillsInstallCommand(id, args) {
6917
7283
  `);
6918
7284
  }
6919
7285
  for (const index of agentIndexes) {
6920
- const reader = path6.basename(index.file) === "CLAUDE.md" ? "Claude Code" : "Codex";
7286
+ const reader = path8.basename(index.file) === "CLAUDE.md" ? "Claude Code" : "Codex";
6921
7287
  process.stdout.write(` \u5DF2${index.status === "created" ? "\u521B\u5EFA" : "\u66F4\u65B0"} ${index.file} \u91CC\u7684\u6280\u80FD\u7D22\u5F15\u4E0E\u9879\u76EE\u8FB9\u754C\u5757\uFF08${reader} \u8BFB\u8FD9\u91CC\uFF09
6922
7288
  `);
6923
7289
  }
6924
7290
  if (agentIndexes.some((i) => i.boundary === "cli-fallback")) {
6925
7291
  process.stdout.write(" \u26A0\uFE0F \u9879\u76EE\u8FB9\u754C\u5757\u7528\u7684\u662F CLI \u5185\u7F6E\u526F\u672C\uFF08\u8FD9\u4E2A\u73AF\u5883\u7684 /chiron.json \u6CA1\u5E26 agentBoundary\uFF09\uFF0C\u672A\u4E0E\u4EA7\u54C1\u7248\u672C\u6838\u5BF9\n");
6926
7292
  }
6927
- process.stdout.write(` \u6765\u6E90 ${endpoint ?? (args.from ? path6.resolve(args.from) : `@hcmai/cli@${CLI_VERSION}`)}
7293
+ process.stdout.write(` \u6765\u6E90 ${endpoint ?? (args.from ? path8.resolve(args.from) : `@hcmai/cli@${CLI_VERSION}`)}
6928
7294
  `);
6929
7295
  if (conflictNote) process.stdout.write(` \u26A0\uFE0F ${conflictNote}
6930
7296
  `);
@@ -6933,7 +7299,7 @@ async function skillsInstallCommand(id, args) {
6933
7299
  process.exitCode = 0;
6934
7300
  return;
6935
7301
  } catch (e) {
6936
- fail5(e, args);
7302
+ fail6(e, args);
6937
7303
  }
6938
7304
  }
6939
7305
  var FETCH_CONCURRENCY = 6;
@@ -6960,7 +7326,7 @@ async function listLocalSkillIds(root) {
6960
7326
  const ids = [];
6961
7327
  for (const entry of entries) {
6962
7328
  if (!entry.isDirectory()) continue;
6963
- if (await exists(path6.join(root, entry.name, "SKILL.md"))) ids.push(entry.name);
7329
+ if (await exists(path8.join(root, entry.name, "SKILL.md"))) ids.push(entry.name);
6964
7330
  }
6965
7331
  if (ids.length === 0) throw invalid(`\u672C\u5730\u76EE\u5F55\u91CC\u6CA1\u6709\u4EFB\u4F55 <id>/SKILL.md\uFF1A${root}`);
6966
7332
  return ids.sort();
@@ -6979,23 +7345,63 @@ async function fetchSkillDocument(http, skill, endpoint, base) {
6979
7345
  references
6980
7346
  };
6981
7347
  }
6982
- async function syncAgentIndexes(layout, manifest2) {
6983
- if (!layout.agentsFile) return [];
6984
- const state = await readSkillsState(layout.baseDir);
6985
- if (!state) return [];
6986
- const catalog = /* @__PURE__ */ new Map();
6987
- for (const category of manifest2?.categories ?? []) {
6988
- for (const skill of category.skills ?? []) catalog.set(skill.id, skill);
7348
+ async function ensureLocalSlot(localDir) {
7349
+ if (!localDir) return;
7350
+ const keep = path8.join(localDir, ".gitkeep");
7351
+ if (await fsp2.stat(localDir).then(() => true).catch(() => false)) return;
7352
+ await fsp2.mkdir(localDir, { recursive: true });
7353
+ await fsp2.writeFile(keep, "# \u4F60\u81EA\u5DF1\u5199\u7684\u6280\u80FD\u653E\u8FD9\u513F\u3002hcm chiron skills sync \u53EA\u7BA1\u9694\u58C1 sync/\uFF0C\u4E00\u4E2A\u5B57\u8282\u90FD\u4E0D\u78B0\u8FD9\u91CC\u3002\n", "utf8");
7354
+ }
7355
+ async function readLocalSkills(localDir) {
7356
+ if (!localDir) return [];
7357
+ let names;
7358
+ try {
7359
+ names = (await fsp2.readdir(localDir, { withFileTypes: true })).filter((e) => e.isDirectory() && !e.name.startsWith(".")).map((e) => e.name);
7360
+ } catch {
7361
+ return [];
6989
7362
  }
6990
- const files = [layout.agentsFile, ...layout.companionAgentFiles ?? []];
6991
- const results = [];
6992
- for (const file of files) {
6993
- const agentsDir = path6.dirname(file);
6994
- const entries = await Promise.all(Object.keys(state.skills).sort().map(async (id) => {
6995
- const known = catalog.get(id);
6996
- const absolute = path6.join(layout.baseDir, id, "SKILL.md");
6997
- let relative2 = path6.relative(agentsDir, absolute);
6998
- if (!relative2.startsWith(".")) relative2 = `./${relative2}`;
7363
+ const out = [];
7364
+ for (const id of names.sort()) {
7365
+ const absolute = path8.join(localDir, id, "SKILL.md");
7366
+ let markdown;
7367
+ try {
7368
+ markdown = await fsp2.readFile(absolute, "utf8");
7369
+ } catch {
7370
+ continue;
7371
+ }
7372
+ let title = id;
7373
+ let description = "";
7374
+ try {
7375
+ const frontmatter = parseSkillFrontmatter2(markdown, id);
7376
+ if (typeof frontmatter.title === "string" && frontmatter.title.trim()) title = frontmatter.title.trim();
7377
+ if (typeof frontmatter.description === "string" && frontmatter.description.trim()) {
7378
+ description = frontmatter.description.trim();
7379
+ }
7380
+ } catch {
7381
+ }
7382
+ out.push({ id, title, description, absolute });
7383
+ }
7384
+ return out;
7385
+ }
7386
+ async function syncAgentIndexes(layout, manifest2) {
7387
+ if (!layout.agentsFile) return [];
7388
+ const state = await readSkillsState(layout.baseDir);
7389
+ const local = await readLocalSkills(layout.localDir);
7390
+ if (!state && local.length === 0) return [];
7391
+ const catalog = /* @__PURE__ */ new Map();
7392
+ for (const category of manifest2?.categories ?? []) {
7393
+ for (const skill of category.skills ?? []) catalog.set(skill.id, skill);
7394
+ }
7395
+ await ensureLocalSlot(layout.localDir);
7396
+ const files = [layout.agentsFile, ...layout.companionAgentFiles ?? []];
7397
+ const results = [];
7398
+ for (const file of files) {
7399
+ const agentsDir = path8.dirname(file);
7400
+ const managed = await Promise.all(Object.keys(state?.skills ?? {}).sort().map(async (id) => {
7401
+ const known = catalog.get(id);
7402
+ const absolute = path8.join(layout.baseDir, id, "SKILL.md");
7403
+ let relative2 = path8.relative(agentsDir, absolute);
7404
+ if (!relative2.startsWith(".")) relative2 = `./${relative2}`;
6999
7405
  let title = known?.title;
7000
7406
  let description = known?.description;
7001
7407
  if (title === void 0 || description === void 0) {
@@ -7017,9 +7423,22 @@ async function syncAgentIndexes(layout, manifest2) {
7017
7423
  id,
7018
7424
  title: title ?? id,
7019
7425
  description: description ?? "",
7020
- relativePath: relative2.split(path6.sep).join("/")
7426
+ relativePath: relative2.split(path8.sep).join("/")
7021
7427
  };
7022
7428
  }));
7429
+ const shadowed = new Set(local.map((x) => x.id));
7430
+ const localEntries = local.map((x) => {
7431
+ let relative2 = path8.relative(agentsDir, x.absolute);
7432
+ if (!relative2.startsWith(".")) relative2 = `./${relative2}`;
7433
+ const covers = managed.some((m) => m.id === x.id) ? `\uFF08\u4F60\u6539\u8FC7\u7684\u7248\u672C\uFF0C\u4EA7\u54C1\u90A3\u4E00\u4EFD\u5728 ${SKILLS_DIR}/${SKILLS_SYNC_SUBDIR}/${x.id}/\uFF0C\u540C\u6B65\u53EA\u66F4\u65B0\u90A3\u4E00\u4EFD\uFF09` : "";
7434
+ return {
7435
+ id: x.id,
7436
+ title: x.title,
7437
+ description: x.description ? `${x.description}${covers}` : covers,
7438
+ relativePath: relative2.split(path8.sep).join("/")
7439
+ };
7440
+ });
7441
+ const entries = [...managed.filter((m) => !shadowed.has(m.id)), ...localEntries].sort((a, b) => a.id.localeCompare(b.id));
7023
7442
  const status = await upsertAgentsBlock(file, renderAgentsBlock(entries));
7024
7443
  const before = await fsp2.readFile(file, "utf8").catch(() => "");
7025
7444
  const merged = mergeBoundaryBlock(before, manifest2?.agentBoundary);
@@ -7042,13 +7461,13 @@ async function resolveLocalSkillDocuments(sourceRoot, targetId) {
7042
7461
  throw invalid(`\u6280\u80FD\u4F9D\u8D56\u5B58\u5728\u73AF: ${[...pathStack.slice(Math.max(0, start)), id].join(" -> ")}`);
7043
7462
  }
7044
7463
  assertSafeSkillId(id);
7045
- const local = path6.join(sourceRoot, id, "SKILL.md");
7464
+ const local = path8.join(sourceRoot, id, "SKILL.md");
7046
7465
  let markdown;
7047
7466
  try {
7048
7467
  markdown = await fsp2.readFile(local, "utf8");
7049
7468
  } catch (cause) {
7050
7469
  if (cause?.code === "ENOENT") {
7051
- throw invalid(requiredBy ? `\u672C\u5730\u6280\u80FD ${requiredBy} \u4F9D\u8D56\u4E0D\u5B58\u5728: ${id}\uFF08${local}\uFF09` : `\u672C\u5730\u76EE\u5F55\u91CC\u6CA1\u6709 ${id}/SKILL.md\uFF1A${path6.join(sourceRoot, id)}`);
7470
+ throw invalid(requiredBy ? `\u672C\u5730\u6280\u80FD ${requiredBy} \u4F9D\u8D56\u4E0D\u5B58\u5728: ${id}\uFF08${local}\uFF09` : `\u672C\u5730\u76EE\u5F55\u91CC\u6CA1\u6709 ${id}/SKILL.md\uFF1A${path8.join(sourceRoot, id)}`);
7052
7471
  }
7053
7472
  throw cause;
7054
7473
  }
@@ -7060,7 +7479,7 @@ async function resolveLocalSkillDocuments(sourceRoot, targetId) {
7060
7479
  markdown,
7061
7480
  source: local,
7062
7481
  sourceKind: "local",
7063
- references: await readLocalReferences(path6.join(sourceRoot, id))
7482
+ references: await readLocalReferences(path8.join(sourceRoot, id))
7064
7483
  };
7065
7484
  for (const required2 of parseSkillRequirements2(markdown, id)) {
7066
7485
  await visit(required2, id);
@@ -7074,7 +7493,7 @@ async function resolveLocalSkillDocuments(sourceRoot, targetId) {
7074
7493
  }
7075
7494
  async function readSkillsState(baseDir) {
7076
7495
  try {
7077
- const raw = await fsp2.readFile(path6.join(baseDir, SKILLS_STATE_FILE), "utf8");
7496
+ const raw = await fsp2.readFile(path8.join(baseDir, SKILLS_STATE_FILE), "utf8");
7078
7497
  const parsed = JSON.parse(raw);
7079
7498
  if (!parsed || typeof parsed !== "object" || !parsed.skills) return void 0;
7080
7499
  return migrateSkillsState(parsed);
@@ -7084,7 +7503,7 @@ async function readSkillsState(baseDir) {
7084
7503
  }
7085
7504
  async function writeSkillsState(baseDir, state) {
7086
7505
  await fsp2.mkdir(baseDir, { recursive: true });
7087
- const file = path6.join(baseDir, SKILLS_STATE_FILE);
7506
+ const file = path8.join(baseDir, SKILLS_STATE_FILE);
7088
7507
  const temp = `${file}.${process.pid}.tmp`;
7089
7508
  await fsp2.writeFile(temp, JSON.stringify(state, null, 2) + "\n", "utf8");
7090
7509
  await fsp2.rename(temp, file);
@@ -7117,7 +7536,7 @@ async function upsertAgentsBlock(agentsFile, block) {
7117
7536
  existing = await fsp2.readFile(agentsFile, "utf8");
7118
7537
  } catch (cause) {
7119
7538
  if (cause?.code !== "ENOENT") throw cause;
7120
- await fsp2.mkdir(path6.dirname(agentsFile), { recursive: true });
7539
+ await fsp2.mkdir(path8.dirname(agentsFile), { recursive: true });
7121
7540
  await fsp2.writeFile(agentsFile, block + "\n", "utf8");
7122
7541
  return "created";
7123
7542
  }
@@ -7143,7 +7562,7 @@ async function installSkillDocuments(documents, requestedIds, baseDir, force, me
7143
7562
  if (!document.markdown.trim()) throw invalid(`\u6280\u80FD ${document.id} \u5185\u5BB9\u4E3A\u7A7A`);
7144
7563
  return {
7145
7564
  ...document,
7146
- target: path6.join(baseDir, document.id, "SKILL.md"),
7565
+ target: path8.join(baseDir, document.id, "SKILL.md"),
7147
7566
  bytes: Buffer.byteLength(document.markdown)
7148
7567
  };
7149
7568
  });
@@ -7165,11 +7584,13 @@ async function installSkillDocuments(documents, requestedIds, baseDir, force, me
7165
7584
  }
7166
7585
  const pending = candidates.filter((candidate) => !unchanged.has(candidate.id));
7167
7586
  await writeSkillDocuments(pending, baseDir);
7168
- await recordInstalled(baseDir, candidates, {
7169
- ...meta2,
7170
- directIds: new Set(requestedIds),
7171
- keepInstalledAt: unchanged
7172
- });
7587
+ if (meta2?.recordState !== false) {
7588
+ await recordInstalled(baseDir, candidates, {
7589
+ ...meta2,
7590
+ directIds: new Set(requestedIds),
7591
+ keepInstalledAt: unchanged
7592
+ });
7593
+ }
7173
7594
  return {
7174
7595
  ids: [...requestedIds],
7175
7596
  baseDir,
@@ -7194,7 +7615,7 @@ async function sameOnDisk(baseDir, candidate) {
7194
7615
  return true;
7195
7616
  }
7196
7617
  async function readLocalReferences(skillDir) {
7197
- const root = path6.join(skillDir, "references");
7618
+ const root = path8.join(skillDir, "references");
7198
7619
  const out = [];
7199
7620
  const walk = async (dir, prefix) => {
7200
7621
  let items;
@@ -7207,12 +7628,12 @@ async function readLocalReferences(skillDir) {
7207
7628
  for (const item of items.sort((a, b) => a.name.localeCompare(b.name))) {
7208
7629
  const relative2 = prefix ? `${prefix}/${item.name}` : item.name;
7209
7630
  if (item.isDirectory()) {
7210
- await walk(path6.join(dir, item.name), relative2);
7631
+ await walk(path8.join(dir, item.name), relative2);
7211
7632
  continue;
7212
7633
  }
7213
7634
  if (!item.isFile()) continue;
7214
7635
  assertSafeReferencePath2(relative2);
7215
- out.push({ path: relative2, content: await fsp2.readFile(path6.join(dir, item.name), "utf8") });
7636
+ out.push({ path: relative2, content: await fsp2.readFile(path8.join(dir, item.name), "utf8") });
7216
7637
  }
7217
7638
  };
7218
7639
  await walk(root, "");
@@ -7244,10 +7665,10 @@ async function removeRenamedSkills(baseDir, renamed) {
7244
7665
  const state = await readSkillsState(baseDir);
7245
7666
  for (const { from } of renamed) {
7246
7667
  assertSafeSkillId(from);
7247
- const dir = path6.join(baseDir, from);
7248
- const resolved = path6.resolve(dir);
7249
- if (resolved !== path6.join(path6.resolve(baseDir), from)) continue;
7250
- const hasSkillFile = await fsp2.stat(path6.join(dir, "SKILL.md")).then(() => true).catch(() => false);
7668
+ const dir = path8.join(baseDir, from);
7669
+ const resolved = path8.resolve(dir);
7670
+ if (resolved !== path8.join(path8.resolve(baseDir), from)) continue;
7671
+ const hasSkillFile = await fsp2.stat(path8.join(dir, "SKILL.md")).then(() => true).catch(() => false);
7251
7672
  const exists2 = await fsp2.stat(dir).then(() => true).catch(() => false);
7252
7673
  if (exists2 && !hasSkillFile) {
7253
7674
  kept.push({ from, kept: "\u76EE\u5F55\u91CC\u6CA1\u6709 SKILL.md\uFF0C\u50CF\u662F\u4F60\u81EA\u5DF1\u653E\u7684\u4E1C\u897F\uFF0C\u6CA1\u6709\u5220" });
@@ -7264,15 +7685,15 @@ async function writeSkillDocuments(documents, baseDir, removals = []) {
7264
7685
  const removed = [];
7265
7686
  try {
7266
7687
  for (const document of documents) {
7267
- const target = path6.join(baseDir, document.id, "SKILL.md");
7268
- await fsp2.mkdir(path6.dirname(target), { recursive: true });
7269
- const temp = path6.join(path6.dirname(target), `.SKILL.md.${process.pid}.${Date.now()}.tmp`);
7688
+ const target = path8.join(baseDir, document.id, "SKILL.md");
7689
+ await fsp2.mkdir(path8.dirname(target), { recursive: true });
7690
+ const temp = path8.join(path8.dirname(target), `.SKILL.md.${process.pid}.${Date.now()}.tmp`);
7270
7691
  await fsp2.writeFile(temp, document.markdown, "utf8");
7271
7692
  staged.push({ temp, target });
7272
7693
  for (const reference of document.references ?? []) {
7273
7694
  assertSafeReferencePath2(reference.path);
7274
- const referenceTarget = path6.join(baseDir, document.id, "references", reference.path);
7275
- await fsp2.mkdir(path6.dirname(referenceTarget), { recursive: true });
7695
+ const referenceTarget = path8.join(baseDir, document.id, "references", reference.path);
7696
+ await fsp2.mkdir(path8.dirname(referenceTarget), { recursive: true });
7276
7697
  const referenceTemp = `${referenceTarget}.${process.pid}.${Date.now()}.tmp`;
7277
7698
  await fsp2.writeFile(referenceTemp, reference.content, "utf8");
7278
7699
  staged.push({ temp: referenceTemp, target: referenceTarget });
@@ -7280,7 +7701,7 @@ async function writeSkillDocuments(documents, baseDir, removals = []) {
7280
7701
  }
7281
7702
  for (const stale of removals) {
7282
7703
  assertSafeReferencePath2(stale.path);
7283
- const original = path6.join(baseDir, stale.id, "references", stale.path);
7704
+ const original = path8.join(baseDir, stale.id, "references", stale.path);
7284
7705
  const parked = `${original}.${process.pid}.${Date.now()}.removed`;
7285
7706
  await fsp2.rename(original, parked);
7286
7707
  removed.push({ parked, original });
@@ -7326,11 +7747,11 @@ async function recordInstalled(baseDir, documents, meta2) {
7326
7747
  return state;
7327
7748
  }
7328
7749
  function invalid(message) {
7329
- return new CliError19({ code: CliErrorCode18.INVALID_ARGUMENT, message });
7750
+ return new CliError20({ code: CliErrorCode19.INVALID_ARGUMENT, message });
7330
7751
  }
7331
7752
  async function readInstalled(baseDir, id) {
7332
7753
  try {
7333
- return await fsp2.readFile(path6.join(baseDir, id, "SKILL.md"), "utf8");
7754
+ return await fsp2.readFile(path8.join(baseDir, id, "SKILL.md"), "utf8");
7334
7755
  } catch (cause) {
7335
7756
  if (cause?.code === "ENOENT") return void 0;
7336
7757
  throw cause;
@@ -7338,7 +7759,7 @@ async function readInstalled(baseDir, id) {
7338
7759
  }
7339
7760
  async function readInstalledReference(baseDir, id, relative2) {
7340
7761
  try {
7341
- return await fsp2.readFile(path6.join(baseDir, id, "references", relative2), "utf8");
7762
+ return await fsp2.readFile(path8.join(baseDir, id, "references", relative2), "utf8");
7342
7763
  } catch (cause) {
7343
7764
  if (cause?.code === "ENOENT") return void 0;
7344
7765
  throw cause;
@@ -7460,7 +7881,7 @@ async function planSkillUpdate(options) {
7460
7881
  entries.push({
7461
7882
  id,
7462
7883
  status: "locally-modified",
7463
- note: "\u672C\u5730\u6539\u8FC7\uFF0C\u6CA1\u6709\u8986\u76D6\uFF1B\u786E\u5B9A\u8981\u7528\u4EA7\u54C1\u8FD9\u4E00\u7248\u5C31\u52A0 --force"
7884
+ note: `\u672C\u5730\u6539\u8FC7\uFF0C\u6CA1\u6709\u8986\u76D6\u3002${SKILLS_SYNC_SUBDIR}/ \u5F52\u4EA7\u54C1\uFF1A\u628A\u8FD9\u4EFD\u6539\u52A8\u632A\u5230 ${SKILLS_LOCAL_SUBDIR}/${id}/ \u5C31\u80FD\u957F\u671F\u7559\u4F4F\uFF08\u540C\u540D\u65F6\u5B83\u906E\u853D\u4EA7\u54C1\u90A3\u4EFD\uFF0C\u4EA7\u54C1\u90A3\u4EFD\u7EE7\u7EED\u8DDF\u7740\u66F4\u65B0\uFF09\uFF1B\u786E\u5B9A\u8981\u4E22\u5F03\u6539\u52A8\u624D\u7528 --force`
7464
7885
  });
7465
7886
  continue;
7466
7887
  }
@@ -7492,16 +7913,16 @@ async function skillsUpdateCommand(args) {
7492
7913
  const layout = await resolveInstallLayout(args);
7493
7914
  const state = await readSkillsState(layout.baseDir);
7494
7915
  if (!state || Object.keys(state.skills).length === 0) {
7495
- throw new CliError19({
7496
- code: CliErrorCode18.INVALID_ARGUMENT,
7497
- message: `${path6.join(layout.baseDir, SKILLS_STATE_FILE)} \u4E0D\u5B58\u5728\u6216\u4E3A\u7A7A \u2014\u2014 \u8FD9\u4E2A\u76EE\u5F55\u4E0B\u8FD8\u6CA1\u6709\u7528\u672C CLI \u88C5\u8FC7\u6280\u80FD\u3002\u5148\u8DD1 \`hcm chiron skills sync\`\uFF1B\u5982\u679C\u6280\u80FD\u662F\u624B\u5DE5\u62F7\u8FDB\u6765\u7684\uFF0C\u540C\u6B65\u4E00\u6B21\u5373\u53EF\u63A5\u7BA1\u5347\u7EA7\u3002`
7916
+ throw new CliError20({
7917
+ code: CliErrorCode19.INVALID_ARGUMENT,
7918
+ message: `${path8.join(layout.baseDir, SKILLS_STATE_FILE)} \u4E0D\u5B58\u5728\u6216\u4E3A\u7A7A \u2014\u2014 \u8FD9\u4E2A\u76EE\u5F55\u4E0B\u8FD8\u6CA1\u6709\u7528\u672C CLI \u88C5\u8FC7\u6280\u80FD\u3002\u5148\u8DD1 \`hcm chiron skills sync\`\uFF1B\u5982\u679C\u6280\u80FD\u662F\u624B\u5DE5\u62F7\u8FDB\u6765\u7684\uFF0C\u540C\u6B65\u4E00\u6B21\u5373\u53EF\u63A5\u7BA1\u5347\u7EA7\u3002`
7498
7919
  });
7499
7920
  }
7500
7921
  const source = parseSourceFilter(args.source);
7501
7922
  const endpoint = decideTrackedEndpoint({
7502
7923
  explicit: Boolean(args.endpoint || args.env),
7503
7924
  current: await resolveEndpoint(args).catch((error) => {
7504
- if (error instanceof CliError19 && error.code === CliErrorCode18.NO_ACTIVE_ENV) return void 0;
7925
+ if (error instanceof CliError20 && error.code === CliErrorCode19.NO_ACTIVE_ENV) return void 0;
7505
7926
  throw error;
7506
7927
  }),
7507
7928
  recorded: state.endpoint
@@ -7547,7 +7968,7 @@ async function skillsUpdateCommand(args) {
7547
7968
  const changed = plan.entries.filter((e) => e.status === "updated" || e.status === "added");
7548
7969
  const fmt = args.output ?? "table";
7549
7970
  if (fmt === "json" || fmt === "yaml") {
7550
- process.stdout.write(formatObject16({
7971
+ process.stdout.write(formatObject17({
7551
7972
  endpoint,
7552
7973
  baseDir: layout.baseDir,
7553
7974
  target: layout.target,
@@ -7623,9 +8044,37 @@ async function skillsUpdateCommand(args) {
7623
8044
  process.exitCode = 0;
7624
8045
  return;
7625
8046
  } catch (e) {
7626
- fail5(e, args);
8047
+ fail6(e, args);
7627
8048
  }
7628
8049
  }
8050
+ async function migrateFlatSkillsLayout(skillsRoot) {
8051
+ const legacyState = path8.join(skillsRoot, SKILLS_STATE_FILE);
8052
+ const syncDir = path8.join(skillsRoot, SKILLS_SYNC_SUBDIR);
8053
+ const localDir = path8.join(skillsRoot, SKILLS_LOCAL_SUBDIR);
8054
+ const hasLegacy = await fsp2.stat(legacyState).then(() => true).catch(() => false);
8055
+ if (!hasLegacy) return { moved: [], migrated: false };
8056
+ const state = await readSkillsState(skillsRoot);
8057
+ const owned = new Set(Object.keys(state?.skills ?? {}));
8058
+ let names;
8059
+ try {
8060
+ names = (await fsp2.readdir(skillsRoot, { withFileTypes: true })).filter((e) => e.isDirectory() && !e.name.startsWith(".")).map((e) => e.name).filter((n) => n !== SKILLS_SYNC_SUBDIR && n !== SKILLS_LOCAL_SUBDIR).sort();
8061
+ } catch {
8062
+ return { moved: [], migrated: false };
8063
+ }
8064
+ const moved = [];
8065
+ for (const id of names) {
8066
+ const hasSkill = await fsp2.stat(path8.join(skillsRoot, id, "SKILL.md")).then(() => true).catch(() => false);
8067
+ if (!hasSkill) continue;
8068
+ const to = owned.has(id) ? "sync" : "local";
8069
+ const target = path8.join(to === "sync" ? syncDir : localDir, id);
8070
+ await fsp2.mkdir(path8.dirname(target), { recursive: true });
8071
+ await fsp2.rename(path8.join(skillsRoot, id), target);
8072
+ moved.push({ id, to });
8073
+ }
8074
+ await fsp2.mkdir(syncDir, { recursive: true });
8075
+ await fsp2.rename(legacyState, path8.join(syncDir, SKILLS_STATE_FILE));
8076
+ return { moved, migrated: true };
8077
+ }
7629
8078
  function assertSyncArgs(args) {
7630
8079
  const only = (args.only ?? []).filter((id) => id.trim().length > 0);
7631
8080
  if (only.length > 0 && args.check) {
@@ -7641,6 +8090,11 @@ var defaultSkillsSyncDeps = {
7641
8090
  if (!layout) return false;
7642
8091
  const state = await readSkillsState(layout.baseDir).catch(() => void 0);
7643
8092
  return Boolean(state && Object.keys(state.skills).length > 0);
8093
+ },
8094
+ migrate: async (args) => {
8095
+ const layout = await resolveInstallLayout(args).catch(() => null);
8096
+ if (!layout || !layout.localDir) return { moved: [], migrated: false };
8097
+ return migrateFlatSkillsLayout(path8.dirname(layout.baseDir)).catch(() => ({ moved: [], migrated: false }));
7644
8098
  }
7645
8099
  };
7646
8100
  async function skillsSyncCommand(args, deps = defaultSkillsSyncDeps) {
@@ -7650,6 +8104,19 @@ async function skillsSyncCommand(args, deps = defaultSkillsSyncDeps) {
7650
8104
  } catch (e) {
7651
8105
  return exitWithError(e);
7652
8106
  }
8107
+ if (!args.check) {
8108
+ const result = await deps.migrate(args);
8109
+ if (result.migrated) {
8110
+ const toSync = result.moved.filter((m) => m.to === "sync");
8111
+ const toLocal = result.moved.filter((m) => m.to === "local");
8112
+ process.stderr.write(`\u2192 \u6280\u80FD\u76EE\u5F55\u5DF2\u5206\u6210\u4E24\u534A\uFF1A${SKILLS_DIR}/${SKILLS_SYNC_SUBDIR}/\uFF08\u4EA7\u54C1\u7684\uFF0C\u540C\u6B65\u5168\u6743\uFF09 \u4E0E ${SKILLS_DIR}/${SKILLS_LOCAL_SUBDIR}/\uFF08\u4F60\u81EA\u5DF1\u7684\uFF0C\u540C\u6B65\u4E0D\u78B0\uFF09
8113
+ `);
8114
+ process.stderr.write(` \u642C\u8FDB ${SKILLS_SYNC_SUBDIR}/\uFF1A${toSync.length} \u4EFD${toLocal.length > 0 ? `\uFF1B\u642C\u8FDB ${SKILLS_LOCAL_SUBDIR}/\uFF1A${toLocal.length} \u4EFD\uFF08${toLocal.map((m) => m.id).join("\u3001")}\uFF09` : ""}
8115
+ `);
8116
+ process.stderr.write(` \u26A0\uFE0F ${SKILLS_SYNC_SUBDIR}/ \u91CC\u7684\u6539\u52A8\u4EE5\u540E\u4F1A\u88AB\u540C\u6B65\u8986\u76D6\uFF1B\u8981\u4FDD\u4F4F\u54EA\u4E00\u4EFD\uFF0C\u628A\u5B83\u632A\u5230 ${SKILLS_LOCAL_SUBDIR}/\uFF08\u540C\u540D\u65F6 ${SKILLS_LOCAL_SUBDIR}/ \u4F18\u5148\uFF0C\u4EA7\u54C1\u90A3\u4EFD\u7EE7\u7EED\u66F4\u65B0\uFF09\u3002
8117
+ `);
8118
+ }
8119
+ }
7653
8120
  if (only.length > 0) {
7654
8121
  for (const id of only) {
7655
8122
  await deps.install(id, { ...args, all: false });
@@ -7666,15 +8133,15 @@ import {
7666
8133
  bootstrapTenant,
7667
8134
  discoverProjectEnv as discoverProjectEnv3,
7668
8135
  assertDangerWrite as assertDangerWrite3,
7669
- normalizeOrigin as normalizeOrigin2,
8136
+ normalizeOrigin as normalizeOrigin4,
7670
8137
  createHttpClient as createHttpClient3,
7671
- formatObject as formatObject17,
8138
+ formatObject as formatObject18,
7672
8139
  fromAxiosError as fromAxiosError17,
7673
8140
  loadGlobalConfig as loadGlobalConfig7,
7674
8141
  resolveEnvContext as resolveEnvContext6,
7675
8142
  printResolvedEnvironment as printResolvedEnvironment5,
7676
- CliError as CliError20,
7677
- CliErrorCode as CliErrorCode19
8143
+ CliError as CliError21,
8144
+ CliErrorCode as CliErrorCode20
7678
8145
  } from "@hcmai/sdk";
7679
8146
  init_exit();
7680
8147
  async function resolveBootstrapKey(args, stdinTaken) {
@@ -7682,8 +8149,8 @@ async function resolveBootstrapKey(args, stdinTaken) {
7682
8149
  if (fromEnv) return fromEnv;
7683
8150
  if (args.bootstrapKeyStdin) {
7684
8151
  if (stdinTaken) {
7685
- throw new CliError20({
7686
- code: CliErrorCode19.INVALID_ARGUMENT,
8152
+ throw new CliError21({
8153
+ code: CliErrorCode20.INVALID_ARGUMENT,
7687
8154
  message: "--bootstrap-key-stdin \u4E0E --admin-password-stdin \u4E0D\u80FD\u540C\u65F6\u7528\uFF08stdin \u53EA\u6709\u4E00\u8DEF\uFF09\uFF1B\u628A\u5176\u4E2D\u4E00\u4E2A\u6539\u8D70 HCM_BOOTSTRAP_KEY \u73AF\u5883\u53D8\u91CF\u6216\u4EA4\u4E92\u8F93\u5165"
7688
8155
  });
7689
8156
  }
@@ -7714,8 +8181,8 @@ async function resolveEndpoint2(args) {
7714
8181
  printResolvedEnvironment5(resolved);
7715
8182
  const env2 = resolved.config;
7716
8183
  if (!env2?.endpoint) {
7717
- throw new CliError20({
7718
- code: CliErrorCode19.MISSING_FLAG,
8184
+ throw new CliError21({
8185
+ code: CliErrorCode20.MISSING_FLAG,
7719
8186
  message: "\u672A\u89E3\u6790\u5230 endpoint \u2014\u2014 \u4F20 --endpoint <url>\uFF0C\u6216\u5148 `hcm env add <name> --endpoint <url>`"
7720
8187
  });
7721
8188
  }
@@ -7724,14 +8191,14 @@ async function resolveEndpoint2(args) {
7724
8191
  async function tenantBootstrapCommand(args) {
7725
8192
  try {
7726
8193
  if (!args.tenantId || !args.adminUsername) {
7727
- throw new CliError20({
7728
- code: CliErrorCode19.MISSING_FLAG,
8194
+ throw new CliError21({
8195
+ code: CliErrorCode20.MISSING_FLAG,
7729
8196
  message: "--tenant-id \u4E0E --admin-username \u5FC5\u586B"
7730
8197
  });
7731
8198
  }
7732
8199
  const endpoint = await resolveEndpoint2(args);
7733
8200
  const project = await discoverProjectEnv3();
7734
- const protectedNames = project ? Object.entries(project.config.environments).filter(([, candidate]) => candidate.danger && candidate.endpoint === normalizeOrigin2(endpoint)).map(([name]) => name) : [];
8201
+ const protectedNames = project ? Object.entries(project.config.environments).filter(([, candidate]) => candidate.danger && candidate.endpoint === normalizeOrigin4(endpoint)).map(([name]) => name) : [];
7735
8202
  assertDangerWrite3({ name: protectedNames.join(", "), danger: protectedNames.length > 0, allowDanger: args.allowDanger }, "\u5F00\u901A\u79DF\u6237");
7736
8203
  if (args.endpoint) process.stderr.write(`\u2192 ${endpoint} \xB7 \u79DF\u6237 ${args.tenantId} \xB7 \u8EAB\u4EFD bootstrap key\uFF08\u6765\u81EA --endpoint\uFF09
7737
8204
  `);
@@ -7766,7 +8233,7 @@ async function tenantBootstrapCommand(args) {
7766
8233
  `
7767
8234
  );
7768
8235
  }
7769
- process.stdout.write(formatObject17(result, { format: fmt }) + "\n");
8236
+ process.stdout.write(formatObject18(result, { format: fmt }) + "\n");
7770
8237
  process.exitCode = 0;
7771
8238
  return;
7772
8239
  } catch (e) {
@@ -7783,11 +8250,11 @@ async function tenantBootstrapCommand(args) {
7783
8250
 
7784
8251
  // src/commands/meta.ts
7785
8252
  import { promises as fsp3 } from "fs";
7786
- import os3 from "os";
8253
+ import os4 from "os";
7787
8254
  import nodePath from "path";
7788
8255
  import {
7789
8256
  HcmClient as HcmClient18,
7790
- formatObject as formatObject18,
8257
+ formatObject as formatObject19,
7791
8258
  fromAxiosError as fromAxiosError18,
7792
8259
  listTenantMeta,
7793
8260
  getTenantMeta,
@@ -7798,8 +8265,8 @@ import {
7798
8265
  formatMetaIssues,
7799
8266
  explainJacksonError,
7800
8267
  META_SCHEMA_SOURCE_COMMIT,
7801
- CliError as CliError21,
7802
- CliErrorCode as CliErrorCode20
8268
+ CliError as CliError22,
8269
+ CliErrorCode as CliErrorCode21
7803
8270
  } from "@hcmai/sdk";
7804
8271
  init_exit();
7805
8272
  init_impersonation_lifecycle();
@@ -7807,7 +8274,7 @@ init_auth_guard();
7807
8274
  async function client2(args) {
7808
8275
  return HcmClient18.fromAuthContext(await getActiveAuthContextFromCli(args));
7809
8276
  }
7810
- function fail6(e, args) {
8277
+ function fail7(e, args) {
7811
8278
  const err = e;
7812
8279
  if (err?.response?.status === 403) {
7813
8280
  exitWithError(
@@ -7830,27 +8297,27 @@ async function metaListCommand(args) {
7830
8297
  const fmt = args.output ?? "json";
7831
8298
  if (fmt !== "json") process.stdout.write(`\u{1F4C4} ${items.length} \u4EFD${total ? ` / \u5171 ${total}` : ""}
7832
8299
  `);
7833
- process.stdout.write(formatObject18(items, { format: fmt }) + "\n");
8300
+ process.stdout.write(formatObject19(items, { format: fmt }) + "\n");
7834
8301
  process.exitCode = 0;
7835
8302
  return;
7836
8303
  } catch (e) {
7837
- fail6(e, args);
8304
+ fail7(e, args);
7838
8305
  }
7839
8306
  }
7840
- async function metaGetCommand(path17, args) {
8307
+ async function metaGetCommand(path18, args) {
7841
8308
  try {
7842
8309
  const c = await client2(args);
7843
- const content = await getTenantMeta(c.raw(), path17);
8310
+ const content = await getTenantMeta(c.raw(), path18);
7844
8311
  process.stdout.write(content.endsWith("\n") ? content : content + "\n");
7845
8312
  process.exitCode = 0;
7846
8313
  return;
7847
8314
  } catch (e) {
7848
- fail6(e, args);
8315
+ fail7(e, args);
7849
8316
  }
7850
8317
  }
7851
8318
  var PROBEABLE_META_TYPES = /* @__PURE__ */ new Set(["model", "list", "info", "view", "filter", "page", "wiz", "impexp"]);
7852
- function parseMetaPath(path17) {
7853
- const base = path17.split(/[\\/]/).pop() ?? path17;
8319
+ function parseMetaPath(path18) {
8320
+ const base = path18.split(/[\\/]/).pop() ?? path18;
7854
8321
  if (!/\.(yml|yaml)$/i.test(base)) return {};
7855
8322
  const parts = base.replace(/\.(yml|yaml)$/i, "").split(".");
7856
8323
  return { model: parts[0] || void 0, kind: parts[1] ?? "model", state: parts[2] };
@@ -7867,10 +8334,10 @@ function unverifiableReason(e) {
7867
8334
  if (st == null) return `\u8BF7\u6C42\u6CA1\u53D1\u51FA\u53BB\u6216\u6CA1\u56DE\u6765\uFF08${err.code ?? err.message ?? "\u672A\u77E5"}\uFF09`;
7868
8335
  return void 0;
7869
8336
  }
7870
- async function verifyAfterWrite(c, path17) {
7871
- const { model, kind, state } = parseMetaPath(path17);
8337
+ async function verifyAfterWrite(c, path18) {
8338
+ const { model, kind, state } = parseMetaPath(path18);
7872
8339
  if (!model || !kind) {
7873
- return { status: "unverified", where: "(\u672A\u63A2)", why: `\u4ECE\u8DEF\u5F84 ${path17} \u8BA4\u4E0D\u51FA\u6A21\u578B\u540D/\u5C42\u540D` };
8340
+ return { status: "unverified", where: "(\u672A\u63A2)", why: `\u4ECE\u8DEF\u5F84 ${path18} \u8BA4\u4E0D\u51FA\u6A21\u578B\u540D/\u5C42\u540D` };
7874
8341
  }
7875
8342
  try {
7876
8343
  await clearMetaCache2(c.raw(), model, {});
@@ -7915,11 +8382,11 @@ async function verifyAfterWrite(c, path17) {
7915
8382
  }
7916
8383
  return { status: "ok" };
7917
8384
  }
7918
- async function metaSetCommand(path17, args) {
8385
+ async function metaSetCommand(path18, args) {
7919
8386
  try {
7920
8387
  if (!args.file) {
7921
- throw new CliError21({
7922
- code: CliErrorCode20.MISSING_FLAG,
8388
+ throw new CliError22({
8389
+ code: CliErrorCode21.MISSING_FLAG,
7923
8390
  message: "--file <path> \u5FC5\u586B\uFF08\u4ECE\u6587\u4EF6\u8BFB\u53D6 meta \u539F\u6587\uFF1B\u7528 - \u8868\u793A stdin\uFF09"
7924
8391
  });
7925
8392
  }
@@ -7931,9 +8398,9 @@ async function metaSetCommand(path17, args) {
7931
8398
  process.stdin.on("error", reject);
7932
8399
  }) : await fsp3.readFile(args.file, "utf8");
7933
8400
  if (!args.skipValidate) {
7934
- const result2 = validateMetaContent(path17, content);
8401
+ const result2 = validateMetaContent(path18, content);
7935
8402
  if (result2.issues.length > 0) {
7936
- process.stderr.write(`\u{1F50E} \u5199\u524D\u6821\u9A8C ${path17}\uFF08schema \u7C7B\u578B\uFF1A${result2.kind ?? "\u672A\u8BC6\u522B"}\uFF09
8403
+ process.stderr.write(`\u{1F50E} \u5199\u524D\u6821\u9A8C ${path18}\uFF08schema \u7C7B\u578B\uFF1A${result2.kind ?? "\u672A\u8BC6\u522B"}\uFF09
7937
8404
  `);
7938
8405
  process.stderr.write(formatMetaIssues(result2, " ") + "\n");
7939
8406
  }
@@ -7951,14 +8418,14 @@ async function metaSetCommand(path17, args) {
7951
8418
  const dryFmt = args.output;
7952
8419
  if (dryFmt === "json" || dryFmt === "yaml") {
7953
8420
  process.stdout.write(
7954
- formatObject18(
7955
- { dryRun: true, path: path17, bytes: Buffer.byteLength(content), content },
8421
+ formatObject19(
8422
+ { dryRun: true, path: path18, bytes: Buffer.byteLength(content), content },
7956
8423
  { format: dryFmt }
7957
8424
  ) + "\n"
7958
8425
  );
7959
8426
  } else {
7960
8427
  process.stdout.write(
7961
- `[dry-run] \u5C06\u5199\u5165 ${path17}\uFF08${Buffer.byteLength(content)} B\uFF09\u2014\u2014\u672A\u5B9E\u9645\u5199\u5165
8428
+ `[dry-run] \u5C06\u5199\u5165 ${path18}\uFF08${Buffer.byteLength(content)} B\uFF09\u2014\u2014\u672A\u5B9E\u9645\u5199\u5165
7962
8429
  ---
7963
8430
  ${content}
7964
8431
  `
@@ -7972,13 +8439,13 @@ ${content}
7972
8439
  let backupState = "unknown";
7973
8440
  let backupWhy;
7974
8441
  try {
7975
- const prev = await getTenantMeta(c.raw(), path17);
8442
+ const prev = await getTenantMeta(c.raw(), path18);
7976
8443
  if (!prev || prev.trim() === "") {
7977
8444
  backupState = "absent";
7978
8445
  } else {
7979
8446
  backupFile = nodePath.join(
7980
- os3.tmpdir(),
7981
- `hcm-meta-backup-${Date.now()}-${path17.replace(/[\\/]/g, "_")}`
8447
+ os4.tmpdir(),
8448
+ `hcm-meta-backup-${Date.now()}-${path18.replace(/[\\/]/g, "_")}`
7982
8449
  );
7983
8450
  await fsp3.writeFile(backupFile, prev, "utf8");
7984
8451
  backupState = "saved";
@@ -7993,22 +8460,22 @@ ${content}
7993
8460
  backupWhy = `HTTP ${st ?? "-"}${err.code ? ` ${err.code}` : ""}${err.message ? `\uFF1A${err.message}` : ""}`;
7994
8461
  }
7995
8462
  }
7996
- const result = await saveTenantMeta(c.raw(), path17, content);
8463
+ const result = await saveTenantMeta(c.raw(), path18, content);
7997
8464
  const fmt = args.output ?? "json";
7998
- if (fmt !== "json") process.stdout.write(`\u2705 \u5DF2\u5199\u5165 ${path17}
8465
+ if (fmt !== "json") process.stdout.write(`\u2705 \u5DF2\u5199\u5165 ${path18}
7999
8466
  `);
8000
8467
  const restoreHint = backupState === "saved" && backupFile ? ` \u65E7\u5185\u5BB9\u5DF2\u5B58\uFF1A${backupFile}
8001
- \u653E\u56DE\u53BB\uFF1Ahcm meta set ${path17} --file ${backupFile}${connFlags(args)}
8002
- ` : backupState === "absent" ? ` \u8FD9\u4E00\u5C42\u6B64\u524D\u6CA1\u6709\u8986\u76D6\uFF08\u5DF2\u8BC1\u5B9E\uFF09\uFF0C\u6062\u590D\u5373\u5220\u9664\uFF1Ahcm meta delete ${path17}${connFlags(args)}
8468
+ \u653E\u56DE\u53BB\uFF1Ahcm meta set ${path18} --file ${backupFile}${connFlags(args)}
8469
+ ` : backupState === "absent" ? ` \u8FD9\u4E00\u5C42\u6B64\u524D\u6CA1\u6709\u8986\u76D6\uFF08\u5DF2\u8BC1\u5B9E\uFF09\uFF0C\u6062\u590D\u5373\u5220\u9664\uFF1Ahcm meta delete ${path18}${connFlags(args)}
8003
8470
  ` : ` \u26A0\uFE0F \u65E7\u5185\u5BB9**\u6CA1\u5907\u4EFD\u6210**\uFF08${backupWhy ?? "\u539F\u56E0\u672A\u77E5"}\uFF09\u2014\u2014\u65E2\u4E0D\u77E5\u9053\u6B64\u524D\u6709\u6CA1\u6709\u8986\u76D6\uFF0C\u4E5F\u5C31\u7ED9\u4E0D\u51FA\u6062\u590D\u547D\u4EE4\u3002
8004
- \u5148\u81EA\u5DF1\u8BFB\u4E00\u904D\u786E\u8BA4\uFF1Ahcm meta get ${path17}${connFlags(args)}
8471
+ \u5148\u81EA\u5DF1\u8BFB\u4E00\u904D\u786E\u8BA4\uFF1Ahcm meta get ${path18}${connFlags(args)}
8005
8472
  `;
8006
8473
  if (args.verify === false) {
8007
8474
  process.stderr.write(
8008
8475
  "\u26A0\uFE0F --no-verify\uFF1A**\u6CA1\u6709**\u9A8C\u8FC7\u670D\u52A1\u7AEF\u8BFB\u4E0D\u8BFB\u5F97\u52A8\u8FD9\u4EFD meta\u3002\u300C\u5199\u5165\u6210\u529F\u300D\u53EA\u8BF4\u660E\u5B57\u8282\u6536\u4E0B\u4E86\u3002\n \u81EA\u5DF1\u8865\uFF1Ahcm cache clear-meta <Model> \u540E\u6253\u5F00\u9875\u9762\u770B\u4E00\u773C\u3002\n" + restoreHint
8009
8476
  );
8010
8477
  } else {
8011
- const outcome = await verifyAfterWrite(c, path17);
8478
+ const outcome = await verifyAfterWrite(c, path18);
8012
8479
  if (outcome.status === "broken") {
8013
8480
  const human = explainJacksonError(outcome.raw);
8014
8481
  process.stderr.write(
@@ -8034,40 +8501,40 @@ ${content}
8034
8501
  process.stdout.write(" \u5DF2\u6E05\u5143\u6570\u636E\u7F13\u5B58\uFF0C\u5E76\u771F\u8BFB\u4E86\u4E00\u904D\uFF1A\u670D\u52A1\u7AEF\u8BFB\u5F97\u52A8 \u2714\n");
8035
8502
  }
8036
8503
  }
8037
- process.stdout.write(formatObject18(result, { format: fmt }) + "\n");
8504
+ process.stdout.write(formatObject19(result, { format: fmt }) + "\n");
8038
8505
  process.exitCode = 0;
8039
8506
  return;
8040
8507
  } catch (e) {
8041
8508
  if (e.code === "ENOENT") exitWithError(new Error(`\u6587\u4EF6\u4E0D\u5B58\u5728\uFF1A${args.file}`));
8042
- fail6(e, args);
8509
+ fail7(e, args);
8043
8510
  }
8044
8511
  }
8045
- async function metaDeleteCommand(path17, args) {
8512
+ async function metaDeleteCommand(path18, args) {
8046
8513
  try {
8047
8514
  if (!args.yes) {
8048
- const ok = await promptConfirm(`\u5C06\u5220\u9664\u5143\u6570\u636E ${path17}\uFF0C\u6B64\u64CD\u4F5C\u4E0D\u53EF\u9006\u3002\u7EE7\u7EED\uFF1F`);
8515
+ const ok = await promptConfirm(`\u5C06\u5220\u9664\u5143\u6570\u636E ${path18}\uFF0C\u6B64\u64CD\u4F5C\u4E0D\u53EF\u9006\u3002\u7EE7\u7EED\uFF1F`);
8049
8516
  if (!ok) {
8050
8517
  process.stderr.write("\u5DF2\u53D6\u6D88\n");
8051
8518
  process.exit(1);
8052
8519
  }
8053
8520
  }
8054
8521
  const c = await client2(args);
8055
- const result = await deleteTenantMeta(c.raw(), path17);
8522
+ const result = await deleteTenantMeta(c.raw(), path18);
8056
8523
  const fmt = args.output ?? "json";
8057
- if (fmt !== "json") process.stdout.write(`\u{1F5D1}\uFE0F \u5DF2\u5220\u9664 ${path17}
8524
+ if (fmt !== "json") process.stdout.write(`\u{1F5D1}\uFE0F \u5DF2\u5220\u9664 ${path18}
8058
8525
  `);
8059
- process.stdout.write(formatObject18(result, { format: fmt }) + "\n");
8526
+ process.stdout.write(formatObject19(result, { format: fmt }) + "\n");
8060
8527
  process.exitCode = 0;
8061
8528
  return;
8062
8529
  } catch (e) {
8063
- fail6(e, args);
8530
+ fail7(e, args);
8064
8531
  }
8065
8532
  }
8066
- async function metaValidateCommand(path17, args) {
8533
+ async function metaValidateCommand(path18, args) {
8067
8534
  try {
8068
8535
  if (!args.file) {
8069
- throw new CliError21({
8070
- code: CliErrorCode20.MISSING_FLAG,
8536
+ throw new CliError22({
8537
+ code: CliErrorCode21.MISSING_FLAG,
8071
8538
  message: "--file <path> \u5FC5\u586B\uFF08\u8981\u9A8C\u7684\u90A3\u4EFD\u539F\u6587\uFF1B\u7528 - \u8868\u793A stdin\uFF09"
8072
8539
  });
8073
8540
  }
@@ -8078,13 +8545,13 @@ async function metaValidateCommand(path17, args) {
8078
8545
  process.stdin.on("end", () => resolve3(buf));
8079
8546
  process.stdin.on("error", reject);
8080
8547
  }) : await fsp3.readFile(args.file, "utf8");
8081
- const result = validateMetaContent(path17, content);
8548
+ const result = validateMetaContent(path18, content);
8082
8549
  const fmt = args.output ?? "table";
8083
8550
  if (fmt === "json" || fmt === "yaml") {
8084
8551
  process.stdout.write(
8085
- formatObject18(
8552
+ formatObject19(
8086
8553
  {
8087
- path: path17,
8554
+ path: path18,
8088
8555
  kind: result.kind,
8089
8556
  schemaKnown: result.schemaKnown,
8090
8557
  schemaSourceCommit: META_SCHEMA_SOURCE_COMMIT,
@@ -8096,7 +8563,7 @@ async function metaValidateCommand(path17, args) {
8096
8563
  );
8097
8564
  } else {
8098
8565
  process.stdout.write(
8099
- `\u{1F50E} ${path17}\uFF08schema \u7C7B\u578B\uFF1A${result.kind ?? "\u672A\u8BC6\u522B"}\uFF0C\u6765\u6E90 ${META_SCHEMA_SOURCE_COMMIT.slice(0, 8)}\uFF09
8566
+ `\u{1F50E} ${path18}\uFF08schema \u7C7B\u578B\uFF1A${result.kind ?? "\u672A\u8BC6\u522B"}\uFF0C\u6765\u6E90 ${META_SCHEMA_SOURCE_COMMIT.slice(0, 8)}\uFF09
8100
8567
  `
8101
8568
  );
8102
8569
  process.stdout.write(
@@ -8107,7 +8574,7 @@ async function metaValidateCommand(path17, args) {
8107
8574
  return;
8108
8575
  } catch (e) {
8109
8576
  if (e.code === "ENOENT") exitWithError(new Error(`\u6587\u4EF6\u4E0D\u5B58\u5728\uFF1A${args.file}`));
8110
- fail6(e, args);
8577
+ fail7(e, args);
8111
8578
  }
8112
8579
  }
8113
8580
 
@@ -8115,15 +8582,15 @@ async function metaValidateCommand(path17, args) {
8115
8582
  init_exit();
8116
8583
  init_auth_guard();
8117
8584
  import * as crypto from "crypto";
8118
- import * as fs7 from "fs/promises";
8119
- import * as path7 from "path";
8585
+ import * as fs8 from "fs/promises";
8586
+ import * as path9 from "path";
8120
8587
  import {
8121
8588
  buildMiniPreviewTargets,
8122
8589
  buildMiniVerifyAgentReport,
8123
8590
  createWorkspaceFile,
8124
8591
  deleteWorkspaceFile,
8125
8592
  formatMiniVerifyReport,
8126
- formatObject as formatObject19,
8593
+ formatObject as formatObject20,
8127
8594
  formatRows as formatRows5,
8128
8595
  getMiniStatus,
8129
8596
  HcmClient as HcmClient19,
@@ -8256,7 +8723,7 @@ async function workspaceBindCommand(workspaceKey, args) {
8256
8723
  tenantId: args.tenant ?? client3?.tenantId,
8257
8724
  endpoint: args.endpoint ?? client3?.endpoint
8258
8725
  });
8259
- await fs7.mkdir(rootDir, { recursive: true });
8726
+ await fs8.mkdir(rootDir, { recursive: true });
8260
8727
  await writeWorkspaceContext(rootDir, context);
8261
8728
  writeWorkspaceBindResult(context, rootDir, args.output ?? "table");
8262
8729
  process.exitCode = 0;
@@ -8293,7 +8760,7 @@ async function workspaceCreateCommand(workspaceKey, args) {
8293
8760
  tenantId: client3.tenantId,
8294
8761
  endpoint: client3.endpoint
8295
8762
  });
8296
- await fs7.mkdir(rootDir, { recursive: true });
8763
+ await fs8.mkdir(rootDir, { recursive: true });
8297
8764
  await writeWorkspaceContext(rootDir, context);
8298
8765
  writeWorkspaceCreateResult(
8299
8766
  {
@@ -8331,7 +8798,7 @@ async function workspacePullCommand(args) {
8331
8798
  tenantId: client3.tenantId ?? existing?.tenantId,
8332
8799
  endpoint: client3.endpoint ?? existing?.endpoint
8333
8800
  });
8334
- await fs7.mkdir(rootDir, { recursive: true });
8801
+ await fs8.mkdir(rootDir, { recursive: true });
8335
8802
  await writeWorkspaceContext(rootDir, context);
8336
8803
  const files = await listWorkspaceFiles(client3.raw(), workspaceKey, { pageSize: 5e3 });
8337
8804
  const miniApps = detectRemoteMiniApps(files.data);
@@ -8341,7 +8808,7 @@ async function workspacePullCommand(args) {
8341
8808
  http: client3.raw(),
8342
8809
  appCode,
8343
8810
  workspaceKey,
8344
- targetDir: path7.join(rootDir, MINI_APPS_DIR, appCode),
8811
+ targetDir: path9.join(rootDir, MINI_APPS_DIR, appCode),
8345
8812
  tenantId: client3.tenantId,
8346
8813
  endpoint: client3.endpoint,
8347
8814
  profile: args.profile ?? client3.profile,
@@ -8356,7 +8823,7 @@ async function workspacePullCommand(args) {
8356
8823
  const rawRemoteByLocalPath = /* @__PURE__ */ new Map();
8357
8824
  for (const file of rawFiles) {
8358
8825
  const content = await loadWorkspaceFileContent(client3.raw(), file.id);
8359
- const target = path7.join(rootDir, content.relativePath);
8826
+ const target = path9.join(rootDir, content.relativePath);
8360
8827
  await writeTextFile(target, content.content, !!args.force);
8361
8828
  pulledRawFiles.push(content.relativePath);
8362
8829
  rawRemoteByLocalPath.set(content.relativePath, file);
@@ -8407,7 +8874,7 @@ async function workspaceAddMiniCommand(appCode, args) {
8407
8874
  const result = await initMiniAppProject({
8408
8875
  appCode,
8409
8876
  workspaceKey: context.workspaceKey,
8410
- targetDir: path7.join(rootDir, MINI_APPS_DIR, appCode),
8877
+ targetDir: path9.join(rootDir, MINI_APPS_DIR, appCode),
8411
8878
  name: args.name,
8412
8879
  defaultSurface: parseSurface(args.surface),
8413
8880
  templateKind,
@@ -8433,10 +8900,10 @@ async function workspaceRmCommand(relativePath, args) {
8433
8900
  const rootDir = resolveRootDir(args.dir);
8434
8901
  const context = await requireWorkspaceContext(rootDir);
8435
8902
  const normalized = normalizeWorkspaceRmPath(relativePath);
8436
- const absolutePath = path7.join(rootDir, ...normalized.split("/"));
8903
+ const absolutePath = path9.join(rootDir, ...normalized.split("/"));
8437
8904
  let stat;
8438
8905
  try {
8439
- stat = await fs7.lstat(absolutePath);
8906
+ stat = await fs8.lstat(absolutePath);
8440
8907
  } catch (e) {
8441
8908
  if (e.code !== "ENOENT") throw e;
8442
8909
  stat = null;
@@ -8476,7 +8943,7 @@ async function workspaceRmCommand(relativePath, args) {
8476
8943
  if (!stat) {
8477
8944
  if (manifestEntry) {
8478
8945
  process.stdout.write(
8479
- formatObject19(
8946
+ formatObject20(
8480
8947
  {
8481
8948
  workspaceKey: context.workspaceKey,
8482
8949
  file: normalized,
@@ -8492,7 +8959,7 @@ async function workspaceRmCommand(relativePath, args) {
8492
8959
  }
8493
8960
  throw new Error(`workspace file not found locally or in the workspace: ${normalized}`);
8494
8961
  }
8495
- await fs7.unlink(absolutePath);
8962
+ await fs8.unlink(absolutePath);
8496
8963
  const result = {
8497
8964
  workspaceKey: context.workspaceKey,
8498
8965
  file: normalized,
@@ -8501,7 +8968,7 @@ async function workspaceRmCommand(relativePath, args) {
8501
8968
  next: `hcm workspace push --dir ${args.dir ?? "."}`
8502
8969
  };
8503
8970
  if (args.output === "json" || args.output === "yaml") {
8504
- process.stdout.write(formatObject19(result, { format: args.output }) + "\n");
8971
+ process.stdout.write(formatObject20(result, { format: args.output }) + "\n");
8505
8972
  } else {
8506
8973
  process.stdout.write(`workspace file staged for deletion: ${normalized}
8507
8974
  `);
@@ -8548,7 +9015,7 @@ async function workspaceStatusCommand(args) {
8548
9015
  }
8549
9016
  if (args.output === "json" || args.output === "yaml") {
8550
9017
  process.stdout.write(
8551
- formatObject19({ rootDir, miniApps: rows2 }, { format: args.output }) + "\n"
9018
+ formatObject20({ rootDir, miniApps: rows2 }, { format: args.output }) + "\n"
8552
9019
  );
8553
9020
  } else {
8554
9021
  process.stdout.write(formatRows5(rows2, { format: "table" }) + "\n");
@@ -8653,7 +9120,7 @@ async function workspacePreviewCommand(args) {
8653
9120
  );
8654
9121
  }
8655
9122
  if (args.output === "json" || args.output === "yaml") {
8656
- process.stdout.write(formatObject19(rows2, { format: args.output }) + "\n");
9123
+ process.stdout.write(formatObject20(rows2, { format: args.output }) + "\n");
8657
9124
  } else {
8658
9125
  process.stdout.write(formatRows5(rows2, { format: "table" }) + "\n");
8659
9126
  }
@@ -8766,7 +9233,7 @@ function removedMiniCommand() {
8766
9233
  );
8767
9234
  }
8768
9235
  function resolveRootDir(dir) {
8769
- return path7.resolve(dir ?? ".");
9236
+ return path9.resolve(dir ?? ".");
8770
9237
  }
8771
9238
  function buildWorkspaceContext(args) {
8772
9239
  return {
@@ -8782,7 +9249,7 @@ function buildWorkspaceContext(args) {
8782
9249
  async function readWorkspaceContext(rootDir) {
8783
9250
  try {
8784
9251
  const parsed = JSON.parse(
8785
- await fs7.readFile(path7.join(rootDir, WORKSPACE_CONTEXT_FILE), "utf-8")
9252
+ await fs8.readFile(path9.join(rootDir, WORKSPACE_CONTEXT_FILE), "utf-8")
8786
9253
  );
8787
9254
  if (parsed.kind !== WORKSPACE_CONTEXT_KIND || parsed.version !== WORKSPACE_CONTEXT_VERSION) {
8788
9255
  throw new Error(`${WORKSPACE_CONTEXT_FILE} is not an HCM workspace context`);
@@ -8811,26 +9278,26 @@ async function requireWorkspaceContext(rootDir) {
8811
9278
  return context;
8812
9279
  }
8813
9280
  async function writeWorkspaceContext(rootDir, context) {
8814
- await fs7.writeFile(
8815
- path7.join(rootDir, WORKSPACE_CONTEXT_FILE),
9281
+ await fs8.writeFile(
9282
+ path9.join(rootDir, WORKSPACE_CONTEXT_FILE),
8816
9283
  JSON.stringify(context, null, 2) + "\n"
8817
9284
  );
8818
9285
  }
8819
9286
  async function writeTextFile(file, content, force) {
8820
9287
  try {
8821
- await fs7.access(file);
9288
+ await fs8.access(file);
8822
9289
  if (!force) throw new Error(`${file} already exists; use --force to overwrite`);
8823
9290
  } catch (e) {
8824
9291
  if (e.code !== "ENOENT") throw e;
8825
9292
  }
8826
- await fs7.mkdir(path7.dirname(file), { recursive: true });
8827
- await fs7.writeFile(file, content);
9293
+ await fs8.mkdir(path9.dirname(file), { recursive: true });
9294
+ await fs8.writeFile(file, content);
8828
9295
  }
8829
9296
  async function readWorkspaceRawManifest(rootDir, context) {
8830
9297
  try {
8831
9298
  const parsed = JSON.parse(
8832
- await fs7.readFile(
8833
- path7.join(rootDir, WORKSPACE_STATE_DIR, WORKSPACE_PULL_MANIFEST_FILE),
9299
+ await fs8.readFile(
9300
+ path9.join(rootDir, WORKSPACE_STATE_DIR, WORKSPACE_PULL_MANIFEST_FILE),
8834
9301
  "utf-8"
8835
9302
  )
8836
9303
  );
@@ -8852,8 +9319,8 @@ async function readWorkspaceRawManifest(rootDir, context) {
8852
9319
  }
8853
9320
  }
8854
9321
  async function writeWorkspaceRawState(rootDir, context, files, remoteByLocalPath) {
8855
- const stateDir = path7.join(rootDir, WORKSPACE_STATE_DIR);
8856
- await fs7.mkdir(stateDir, { recursive: true });
9322
+ const stateDir = path9.join(rootDir, WORKSPACE_STATE_DIR);
9323
+ await fs8.mkdir(stateDir, { recursive: true });
8857
9324
  const snapshots = files.map(
8858
9325
  (file) => ({
8859
9326
  localPath: file.localPath,
@@ -8864,8 +9331,8 @@ async function writeWorkspaceRawState(rootDir, context, files, remoteByLocalPath
8864
9331
  lastModified: remoteByLocalPath.get(file.localPath)?.lastModified
8865
9332
  })
8866
9333
  );
8867
- await fs7.writeFile(
8868
- path7.join(stateDir, WORKSPACE_PULL_MANIFEST_FILE),
9334
+ await fs8.writeFile(
9335
+ path9.join(stateDir, WORKSPACE_PULL_MANIFEST_FILE),
8869
9336
  JSON.stringify(
8870
9337
  {
8871
9338
  version: WORKSPACE_CONTEXT_VERSION,
@@ -8881,10 +9348,10 @@ async function writeWorkspaceRawState(rootDir, context, files, remoteByLocalPath
8881
9348
  );
8882
9349
  }
8883
9350
  async function writeWorkspaceRawManifest(rootDir, manifest2) {
8884
- const stateDir = path7.join(rootDir, WORKSPACE_STATE_DIR);
8885
- await fs7.mkdir(stateDir, { recursive: true });
8886
- await fs7.writeFile(
8887
- path7.join(stateDir, WORKSPACE_PULL_MANIFEST_FILE),
9351
+ const stateDir = path9.join(rootDir, WORKSPACE_STATE_DIR);
9352
+ await fs8.mkdir(stateDir, { recursive: true });
9353
+ await fs8.writeFile(
9354
+ path9.join(stateDir, WORKSPACE_PULL_MANIFEST_FILE),
8888
9355
  JSON.stringify(manifest2, null, 2) + "\n",
8889
9356
  "utf8"
8890
9357
  );
@@ -8896,10 +9363,10 @@ async function readWorkspaceRawLocalFiles(rootDir) {
8896
9363
  return files;
8897
9364
  }
8898
9365
  async function walkWorkspaceRawFiles(rootDir, relativeDir, files) {
8899
- const absoluteDir = path7.join(rootDir, relativeDir);
9366
+ const absoluteDir = path9.join(rootDir, relativeDir);
8900
9367
  let entries;
8901
9368
  try {
8902
- entries = await fs7.readdir(absoluteDir, { withFileTypes: true });
9369
+ entries = await fs8.readdir(absoluteDir, { withFileTypes: true });
8903
9370
  } catch (e) {
8904
9371
  if (e.code === "ENOENT") return;
8905
9372
  throw e;
@@ -8907,14 +9374,14 @@ async function walkWorkspaceRawFiles(rootDir, relativeDir, files) {
8907
9374
  for (const entry of entries) {
8908
9375
  if (entry.isDirectory() && RAW_WORKSPACE_EXCLUDED_DIRS.has(entry.name)) continue;
8909
9376
  if (entry.isFile() && RAW_WORKSPACE_EXCLUDED_FILES.has(entry.name)) continue;
8910
- const localPath = normalizeRelativePath(path7.posix.join(toPosix(relativeDir), entry.name));
8911
- const absolutePath = path7.join(rootDir, localPath);
9377
+ const localPath = normalizeRelativePath(path9.posix.join(toPosix(relativeDir), entry.name));
9378
+ const absolutePath = path9.join(rootDir, localPath);
8912
9379
  if (entry.isDirectory()) {
8913
9380
  await walkWorkspaceRawFiles(rootDir, localPath, files);
8914
9381
  continue;
8915
9382
  }
8916
9383
  if (!entry.isFile()) continue;
8917
- const content = await fs7.readFile(absolutePath, "utf-8");
9384
+ const content = await fs8.readFile(absolutePath, "utf-8");
8918
9385
  files.push({
8919
9386
  localPath,
8920
9387
  absolutePath,
@@ -9096,15 +9563,15 @@ function workspaceRawConflict(entry, reason) {
9096
9563
  };
9097
9564
  }
9098
9565
  async function discoverMiniApps(rootDir) {
9099
- const appsRoot = path7.join(rootDir, MINI_APPS_DIR);
9566
+ const appsRoot = path9.join(rootDir, MINI_APPS_DIR);
9100
9567
  let entries;
9101
9568
  try {
9102
- entries = await fs7.readdir(appsRoot, { withFileTypes: true });
9569
+ entries = await fs8.readdir(appsRoot, { withFileTypes: true });
9103
9570
  } catch (e) {
9104
9571
  if (e.code === "ENOENT") return [];
9105
9572
  throw e;
9106
9573
  }
9107
- return entries.filter((entry) => entry.isDirectory()).map((entry) => ({ appCode: entry.name, dir: path7.join(appsRoot, entry.name) })).sort((a, b) => a.appCode.localeCompare(b.appCode));
9574
+ return entries.filter((entry) => entry.isDirectory()).map((entry) => ({ appCode: entry.name, dir: path9.join(appsRoot, entry.name) })).sort((a, b) => a.appCode.localeCompare(b.appCode));
9108
9575
  }
9109
9576
  function detectRemoteMiniApps(files) {
9110
9577
  const appCodes = /* @__PURE__ */ new Set();
@@ -9247,7 +9714,7 @@ function normalizeWorkspaceKey(value) {
9247
9714
  return key2;
9248
9715
  }
9249
9716
  function normalizeWorkspaceRmPath(value) {
9250
- if (path7.isAbsolute(value) || /^[A-Za-z]:[\\/]/.test(value)) {
9717
+ if (path9.isAbsolute(value) || /^[A-Za-z]:[\\/]/.test(value)) {
9251
9718
  throw new Error("workspace rm path must be relative to the bound workspace");
9252
9719
  }
9253
9720
  const normalized = normalizeRelativePath(value);
@@ -9269,7 +9736,7 @@ function normalizeRelativePath(value) {
9269
9736
  return normalized;
9270
9737
  }
9271
9738
  function toPosix(value) {
9272
- return value.split(path7.sep).join("/");
9739
+ return value.split(path9.sep).join("/");
9273
9740
  }
9274
9741
  function sha2563(content) {
9275
9742
  return crypto.createHash("sha256").update(content, "utf-8").digest("hex");
@@ -9297,7 +9764,7 @@ function optionalText(value) {
9297
9764
  }
9298
9765
  function writeWorkspaceListResult(rows2, format, total) {
9299
9766
  if (format !== "table") {
9300
- process.stdout.write(formatObject19({ rows: rows2, total }, { format }) + "\n");
9767
+ process.stdout.write(formatObject20({ rows: rows2, total }, { format }) + "\n");
9301
9768
  return;
9302
9769
  }
9303
9770
  process.stdout.write(formatRows5(toWorkspaceListRows(rows2), { format: "table" }) + "\n");
@@ -9308,7 +9775,7 @@ function writeWorkspaceListResult(rows2, format, total) {
9308
9775
  }
9309
9776
  function writeWorkspaceActiveResult(view, format) {
9310
9777
  if (format !== "table") {
9311
- process.stdout.write(formatObject19(view, { format }) + "\n");
9778
+ process.stdout.write(formatObject20(view, { format }) + "\n");
9312
9779
  return;
9313
9780
  }
9314
9781
  const rows2 = [
@@ -9330,7 +9797,7 @@ function writeWorkspaceActiveResult(view, format) {
9330
9797
  }
9331
9798
  function writeWorkspaceBindResult(context, rootDir, format) {
9332
9799
  if (format !== "table") {
9333
- process.stdout.write(formatObject19({ ...context, rootDir }, { format }) + "\n");
9800
+ process.stdout.write(formatObject20({ ...context, rootDir }, { format }) + "\n");
9334
9801
  return;
9335
9802
  }
9336
9803
  process.stdout.write(
@@ -9344,7 +9811,7 @@ function writeWorkspaceBindResult(context, rootDir, format) {
9344
9811
  }
9345
9812
  function writeWorkspaceCreateResult(result, format) {
9346
9813
  if (format !== "table") {
9347
- process.stdout.write(formatObject19(result, { format }) + "\n");
9814
+ process.stdout.write(formatObject20(result, { format }) + "\n");
9348
9815
  return;
9349
9816
  }
9350
9817
  process.stdout.write(
@@ -9360,7 +9827,7 @@ function writeWorkspaceCreateResult(result, format) {
9360
9827
  }
9361
9828
  function writeWorkspacePullResult(result, format) {
9362
9829
  if (format !== "table") {
9363
- process.stdout.write(formatObject19(result, { format }) + "\n");
9830
+ process.stdout.write(formatObject20(result, { format }) + "\n");
9364
9831
  return;
9365
9832
  }
9366
9833
  const lines = [
@@ -9378,7 +9845,7 @@ function writeWorkspacePullResult(result, format) {
9378
9845
  }
9379
9846
  function writeWorkspaceAddMiniResult(result, rootDir, format) {
9380
9847
  if (format !== "table") {
9381
- process.stdout.write(formatObject19({ ...result, workspaceRoot: rootDir }, { format }) + "\n");
9848
+ process.stdout.write(formatObject20({ ...result, workspaceRoot: rootDir }, { format }) + "\n");
9382
9849
  return;
9383
9850
  }
9384
9851
  process.stdout.write(
@@ -9394,7 +9861,7 @@ function writeWorkspaceAddMiniResult(result, rootDir, format) {
9394
9861
  function writeWorkspaceValidateResult(results, format) {
9395
9862
  if (format !== "table") {
9396
9863
  process.stdout.write(
9397
- formatObject19(
9864
+ formatObject20(
9398
9865
  results.map((item) => ({ artifact: `mini:${item.app.appCode}`, ...item.result })),
9399
9866
  { format }
9400
9867
  ) + "\n"
@@ -9422,7 +9889,7 @@ mini:${item.app.appCode}
9422
9889
  function writeWorkspacePushResult(rawResult, results, format) {
9423
9890
  if (format !== "table") {
9424
9891
  process.stdout.write(
9425
- formatObject19(
9892
+ formatObject20(
9426
9893
  {
9427
9894
  workspaceFiles: { artifact: "workspace", ...rawResult },
9428
9895
  miniApps: results.map((item) => ({
@@ -9481,7 +9948,7 @@ function writeWorkspaceVerifyResult(context, rootDir, raw, reports, format) {
9481
9948
  const ok = rawOk && reports.every((item) => item.report.ok);
9482
9949
  if (format === "json") {
9483
9950
  process.stdout.write(
9484
- formatObject19(
9951
+ formatObject20(
9485
9952
  {
9486
9953
  ok,
9487
9954
  workspaceKey: context.workspaceKey,
@@ -9508,7 +9975,7 @@ function writeWorkspaceVerifyResult(context, rootDir, raw, reports, format) {
9508
9975
  }
9509
9976
  if (format !== "table") {
9510
9977
  process.stdout.write(
9511
- formatObject19(
9978
+ formatObject20(
9512
9979
  {
9513
9980
  ok,
9514
9981
  workspaceKey: context.workspaceKey,
@@ -9593,557 +10060,214 @@ async function setDevModeBinding(client3, workspaceKey) {
9593
10060
  workspaceKey
9594
10061
  });
9595
10062
  }
9596
- function workspaceActiveNextCommand(activeWorkspaceKey) {
9597
- return activeWorkspaceKey ? "hcm workspace deactivate" : null;
9598
- }
9599
- function unwrapWorkspaceActionPayload(response) {
9600
- if (!response || typeof response !== "object") return response;
9601
- const envelope = response;
9602
- if (envelope.data && typeof envelope.data === "object") return envelope.data;
9603
- if (envelope.result && typeof envelope.result === "object") return envelope.result;
9604
- return response;
9605
- }
9606
- async function requestWorkspaceDeactivation(client3) {
9607
- const response = await client3.action(
9608
- "TenantExtensionWorkspace",
9609
- "unbind-current-user",
9610
- { method: "POST", scope: "class" }
9611
- );
9612
- const binding = unwrapWorkspaceActionPayload(response);
9613
- if (!binding || typeof binding !== "object" || binding.enabled !== false) {
9614
- throw new Error("workspace deactivate \u672A\u6536\u5230 enabled=false \u7684\u670D\u52A1\u7AEF\u56DE\u6267\uFF0C\u4E0D\u80FD\u786E\u8BA4\u5DF2\u9000\u51FA\u5F00\u53D1\u6A21\u5F0F");
9615
- }
9616
- return binding;
9617
- }
9618
- async function workspaceActivateCommand(workspaceKey, args) {
9619
- try {
9620
- const client3 = HcmClient19.fromAuthContext(await getActiveAuthContextFromCli(args));
9621
- const key2 = normalizeWorkspaceKey(workspaceKey);
9622
- await setDevModeBinding(client3, key2);
9623
- const fmt = args.output ?? "table";
9624
- if (fmt === "table") {
9625
- process.stdout.write(`workspace activated: ${key2}
9626
- `);
9627
- process.stdout.write("\u8BE5\u7A7A\u95F4\u7684 metas / scripts / menus / mini_apps \u73B0\u5DF2\u5728\u5F53\u524D\u79DF\u6237\u751F\u6548\u3002\n");
9628
- } else {
9629
- process.stdout.write(
9630
- formatObject19({ workspaceKey: key2, activated: true }, { format: fmt }) + "\n"
9631
- );
9632
- }
9633
- process.exitCode = 0;
9634
- return;
9635
- } catch (e) {
9636
- exitWorkspaceError(e, args.env ?? args.profile);
9637
- }
9638
- }
9639
- async function workspaceDeactivateCommand(args) {
9640
- try {
9641
- const client3 = HcmClient19.fromAuthContext(await getActiveAuthContextFromCli(args));
9642
- const binding = await requestWorkspaceDeactivation(client3);
9643
- const result = { ...binding, deactivated: true };
9644
- const fmt = args.output ?? "table";
9645
- if (fmt === "table") {
9646
- process.stdout.write("workspace deactivated\n");
9647
- process.stdout.write("\u5F53\u524D\u8EAB\u4EFD\u5DF2\u9000\u51FA\u5F00\u53D1\u8005\u6A21\u5F0F\uFF1B\u5F00\u53D1\u7A7A\u95F4\u3001\u672C\u5730\u6587\u4EF6\u4E0E\u5DF2\u53D1\u5E03\u8D44\u4EA7\u5747\u672A\u5220\u9664\u3002\n");
9648
- } else {
9649
- process.stdout.write(formatObject19(result, { format: fmt }) + "\n");
9650
- }
9651
- process.exitCode = 0;
9652
- return;
9653
- } catch (e) {
9654
- exitWorkspaceError(e, args.env ?? args.profile);
9655
- }
9656
- }
9657
-
9658
- // src/commands/identity.ts
9659
- init_exit();
9660
- import axios4 from "axios";
9661
- import {
9662
- AUTH_INFO_PATH,
9663
- CliError as CliError22,
9664
- CliErrorCode as CliErrorCode21,
9665
- formatObject as formatObject20,
9666
- fromAxiosError as fromAxiosError20,
9667
- loadEnv as loadEnv4,
9668
- saveEnv as saveEnv3,
9669
- loadIdentity as loadIdentity4,
9670
- listIdentities as listIdentities4,
9671
- deleteIdentity as deleteIdentity3,
9672
- loadGlobalConfig as loadGlobalConfig8,
9673
- resolveActiveEnv,
9674
- printResolvedEnvironment as printResolvedEnvironment6,
9675
- TokenStore as TokenStore4,
9676
- toPrincipal
9677
- } from "@hcmai/sdk";
9678
- var fetchAuthInfo = async (endpoint, accessToken) => {
9679
- const response = await axios4.get(`${endpoint.replace(/\/$/, "")}${AUTH_INFO_PATH}`, {
9680
- headers: { Authorization: `Bearer ${accessToken}` },
9681
- timeout: 3e4
9682
- });
9683
- return response.data;
9684
- };
9685
- async function inspectIdentity(name, fetcher = fetchAuthInfo) {
9686
- const meta2 = await loadIdentity4(name);
9687
- const env2 = await loadEnv4(meta2.env);
9688
- const accessToken = await TokenStore4.forIdentity(name).getStoredAccessToken();
9689
- if (!accessToken) {
9690
- throw new CliError22({
9691
- code: CliErrorCode21.AUTH_FAILED,
9692
- message: `identity '${name}' \u6CA1\u6709\u53EF\u8BFB\u53D6\u7684\u6301\u4E45\u5316 token`,
9693
- context: { nextStep: `\u91CD\u65B0\u767B\u5F55\u8BE5\u8EAB\u4EFD\uFF1Ahcm login --env ${meta2.env} --name ${name}` }
9694
- });
9695
- }
9696
- printResolvedEnvironment6({ name: meta2.env, config: env2, source: "identity" }, name, meta2.tenantId);
9697
- const raw = await fetcher(env2.endpoint, accessToken);
9698
- const principal = toPrincipal(raw);
9699
- const body = raw && typeof raw === "object" && !Array.isArray(raw) ? raw : {};
9700
- const serverScopes = Array.isArray(body.scopes) ? body.scopes.map(String) : void 0;
9701
- return {
9702
- identity: name,
9703
- env: meta2.env,
9704
- endpoint: env2.endpoint,
9705
- scheme: meta2.scheme,
9706
- userId: principal?.userId ?? null,
9707
- username: principal?.username ?? null,
9708
- tenantId: principal?.tenantId ?? null,
9709
- // null 明确表示服务端没回该字段;[] 才表示服务端确认角色为空。
9710
- roles: principal?.roles ?? null,
9711
- scopes: serverScopes ?? meta2.scopes,
9712
- expiresAt: meta2.expiresAt ?? null,
9713
- source: AUTH_INFO_PATH
9714
- };
9715
- }
9716
- async function identityShow(name, args) {
9717
- try {
9718
- const details = await inspectIdentity(name);
9719
- return exitOk(formatObject20(details, { format: args.output ?? "json" }));
9720
- } catch (e) {
9721
- exitWithError(axios4.isAxiosError(e) ? fromAxiosError20(e, name) : e);
9722
- }
9723
- }
9724
- async function identityList(args) {
9725
- try {
9726
- const g = await loadGlobalConfig8();
9727
- const filter = args.env === "all" ? void 0 : await resolveActiveEnv({ envFlag: args.env }, process.env, g);
9728
- const names = await listIdentities4(filter);
9729
- if (names.length === 0) {
9730
- return exitOk("(no identities)");
9731
- }
9732
- const lines = [];
9733
- for (const n of names) {
9734
- const meta2 = await loadIdentity4(n);
9735
- const env2 = await loadEnv4(meta2.env).catch(() => null);
9736
- const isDefault = env2?.defaultIdentity === n ? "*" : " ";
9737
- const expired = meta2.expiresAt && new Date(meta2.expiresAt) < /* @__PURE__ */ new Date() ? " (expired)" : "";
9738
- lines.push(`${isDefault} ${n} scheme=${meta2.scheme} env=${meta2.env}${expired}`);
9739
- }
9740
- return exitOk(lines.join("\n"));
9741
- } catch (e) {
9742
- exitWithError(e);
9743
- }
9744
- }
9745
- async function identityUse(name) {
9746
- try {
9747
- const meta2 = await loadIdentity4(name);
9748
- const env2 = await loadEnv4(meta2.env).catch(() => {
9749
- throw new CliError22({
9750
- code: CliErrorCode21.IDENTITY_NOT_IN_ENV,
9751
- message: `identity '${name}' references env '${meta2.env}' which no longer exists. Re-create the env, or remove this orphan: hcm identity remove ${name}`
9752
- });
9753
- });
9754
- env2.defaultIdentity = name;
9755
- await saveEnv3(meta2.env, env2);
9756
- return exitOk(`\u2705 default identity for env '${meta2.env}': ${name}`);
9757
- } catch (e) {
9758
- exitWithError(e);
9759
- }
9760
- }
9761
- async function identityRemove(name) {
9762
- try {
9763
- const meta2 = await loadIdentity4(name);
9764
- try {
9765
- await TokenStore4.forIdentity(name).clear();
9766
- } catch (err) {
9767
- process.stderr.write(
9768
- `[hcm] event=identity_cleanup_failed identity=${name} reason=${JSON.stringify(String(err.message))}
9769
- `
9770
- );
9771
- }
9772
- await deleteIdentity3(name);
9773
- const env2 = await loadEnv4(meta2.env).catch(() => null);
9774
- if (env2?.defaultIdentity === name) {
9775
- env2.defaultIdentity = void 0;
9776
- await saveEnv3(meta2.env, env2);
9777
- }
9778
- return exitOk(`\u2705 identity '${name}' removed`);
9779
- } catch (e) {
9780
- exitWithError(e);
9781
- }
9782
- }
9783
-
9784
- // src/commands/chiron-init.ts
9785
- init_auth_guard();
9786
- init_exit();
9787
- import { promises as fs9 } from "fs";
9788
- import path9 from "path";
9789
- import {
9790
- CliError as CliError24,
9791
- CliErrorCode as CliErrorCode23,
9792
- HcmClient as HcmClient20,
9793
- fetchReconIdentity,
9794
- formatObject as formatObject22,
9795
- httpProbe,
9796
- isTempEnv as isTempEnv3,
9797
- listIdentities as listIdentities5,
9798
- loadEnv as loadEnv5,
9799
- discoverProjectEnv as discoverProjectEnv4,
9800
- findEnvByEndpoint as findEnvByEndpoint4,
9801
- normalizeOrigin as normalizeOrigin5,
9802
- loadGlobalConfig as loadGlobalConfig9
9803
- } from "@hcmai/sdk";
9804
-
9805
- // src/commands/chiron-project.ts
9806
- import { promises as fs8 } from "fs";
9807
-
9808
- // src/commands/chiron-case.ts
9809
- init_exit();
9810
- import { execFileSync } from "child_process";
9811
- import { cpSync, existsSync as existsSync2, mkdirSync, mkdtempSync, readFileSync as readFileSync5, rmSync, statSync as statSync4, writeFileSync as writeFileSync2 } from "fs";
9812
- import os4 from "os";
9813
- import path8 from "path";
9814
- import { CASES_REPO_SLUG, CASES_REPO_URL, CNB_ORIGIN, CliError as CliError23, CliErrorCode as CliErrorCode22, formatObject as formatObject21 } from "@hcmai/sdk";
9815
- var casesCacheDir = () => process.env.HCM_CASES_CACHE?.trim() || path8.join(os4.homedir(), ".cache", "hcm", "chiron-cases");
9816
- var INDEX_CACHE = () => path8.join(casesCacheDir(), "index.json");
9817
- var INDEX_TTL_MS = 60 * 60 * 1e3;
9818
- var fail7 = (message, nextStep) => new CliError23({ code: CliErrorCode22.INVALID_ARGUMENT, message, context: { nextStep } });
9819
- var run = (cmd, args, opts = {}) => execFileSync(cmd, args, { encoding: "utf8", maxBuffer: 1 << 26, ...opts });
9820
- function fetchRepoFile(relPath) {
9821
- let raw;
9822
- try {
9823
- raw = run("cnb", ["git", "get-raw", "--repo", CASES_REPO_SLUG, "--ref-with-path", `main/${relPath}`]);
9824
- } catch (e) {
9825
- throw fail7(
9826
- `\u53D6\u4E0D\u5230\u6848\u4F8B\u5E93\u6587\u4EF6 ${relPath}\uFF1A${String(e.message).split("\n")[0]}`,
9827
- "\u6848\u4F8B\u5E93\u8BFB\u53D6\u8D70 cnb\uFF08\u9700\u8981\u5DF2 `cnb login` \u4E14\u6709\u8BE5\u4ED3\u8BFB\u6743\u9650\uFF09\u3002\u6CA1\u6709\u6743\u9650\u5C31\u5148\u8DF3\u8FC7\u6848\u4F8B\u5E93\uFF0C\u76F4\u63A5\u6309\u6280\u80FD\u505A\uFF1B\u522B\u628A\u300C\u53D6\u4E0D\u5230\u300D\u5F53\u6210\u300C\u6CA1\u6709\u5148\u4F8B\u300D\u3002"
9828
- );
9829
- }
9830
- const i = raw.indexOf("data: ");
9831
- if (i < 0) throw fail7(`cnb \u7684\u56DE\u6267\u91CC\u6CA1\u6709 data \u90A3\u4E00\u683C\uFF1A${relPath}`, "\u5347\u7EA7 cnb CLI\uFF0C\u6216\u628A\u8FD9\u6BB5\u539F\u6837\u8D34\u7ED9\u6211\u3002");
9832
- const body = raw.slice(i + "data: ".length).trim();
9833
- if (body.startsWith('"')) {
9834
- try {
9835
- return JSON.parse(body);
9836
- } catch {
9837
- return body;
9838
- }
9839
- }
9840
- return body;
9841
- }
9842
- function loadIndex(opts = {}) {
9843
- const file = INDEX_CACHE();
9844
- const fresh = !opts.refresh && existsSync2(file) && Date.now() - statSync4(file).mtimeMs < INDEX_TTL_MS;
9845
- if (fresh) return JSON.parse(readFileSync5(file, "utf8"));
9846
- let text;
9847
- try {
9848
- text = fetchRepoFile("index/index.json");
9849
- } catch (e) {
9850
- if (!existsSync2(file)) throw e;
9851
- process.stderr.write(
9852
- `[hcm] \u7D22\u5F15\u6CA1\u62C9\u52A8\uFF08${e.message.split("\n")[0]}\uFF09\uFF0C\u7528\u672C\u673A\u7F13\u5B58\u7684\u90A3\u4EFD\uFF1A${file}
9853
- `
9854
- );
9855
- return JSON.parse(readFileSync5(file, "utf8"));
9856
- }
9857
- mkdirSync(path8.dirname(file), { recursive: true });
9858
- writeFileSync2(file, text);
9859
- return JSON.parse(text);
9860
- }
9861
- function backendFingerprint(env2) {
9862
- if (!env2) return { reason: "\u6CA1\u7ED9 --env\uFF0C\u6CA1\u6CD5\u73B0\u67E5\u6307\u7EB9" };
9863
- try {
9864
- const raw = run(process.execPath, [process.argv[1], "version", "--env", env2, "--output", "json"]);
9865
- const j = JSON.parse(raw.slice(raw.indexOf("{")));
9866
- const backend = j.backend?.commit ?? j.commit ?? j.server?.commit;
9867
- if (!backend) return { reason: "\u540E\u7AEF\u56DE\u6267\u91CC\u6CA1\u6709 commit \u5B57\u6BB5" };
9868
- return { backend: String(backend), cli: String(j.cli?.version ?? j.cliVersion ?? "") };
9869
- } catch (e) {
9870
- return { reason: String(e.message).split("\n")[0]?.slice(0, 120) };
9871
- }
9872
- }
9873
- function matchTag(c, fp) {
9874
- if (!fp.backend) return `\u672A\u6BD4\u5BF9\uFF08${fp.reason ?? "\u6CA1\u6709\u6307\u7EB9"}\uFF09`;
9875
- const be = String(c.fingerprint?.backend_commit ?? "");
9876
- if (!be) return "\u6848\u4F8B\u6CA1\u8BB0\u540E\u7AEF\u6307\u7EB9";
9877
- const a = be.slice(0, 12);
9878
- const b = fp.backend.slice(0, 12);
9879
- return a === b ? "\u5339\u914D" : `\u4E0D\u5339\u914D\uFF08\u6848\u4F8B ${a} / \u5F53\u524D ${b}\uFF09`;
9880
- }
9881
- function emit4(args, data, text) {
9882
- if (args.output === "json" || args.output === "yaml") {
9883
- process.stdout.write(formatObject21(data, { format: args.output }) + "\n");
9884
- } else {
9885
- process.stdout.write(text() + "\n");
9886
- }
9887
- }
9888
- async function guard(fn) {
9889
- try {
9890
- await fn();
9891
- } catch (e) {
9892
- exitWithError(e);
9893
- }
9894
- }
9895
- async function caseSearchCommand(query, args) {
9896
- await guard(async () => {
9897
- const idx = loadIndex({ refresh: args.refresh });
9898
- const fp = backendFingerprint(args.env);
9899
- let raw;
9900
- try {
9901
- raw = run("cnb", [
9902
- "knowledge-base",
9903
- "query-knowledge-base-get",
9904
- "--repo",
9905
- CASES_REPO_SLUG,
9906
- "--query",
9907
- query,
9908
- "--top-k",
9909
- String(args.topK ?? 5),
9910
- "--verbose"
9911
- ]);
9912
- } catch (e) {
9913
- throw fail7(
9914
- `\u6848\u4F8B\u5E93\u68C0\u7D22\u6CA1\u8DD1\u6210\uFF1A${String(e.message).split("\n")[0]}`,
9915
- "\u68C0\u7D22\u8D70 cnb \u7684\u77E5\u8BC6\u5E93\u63A5\u53E3\uFF0C\u9700\u8981 cnb \u5DF2\u767B\u5F55\u4E14\u6709\u6848\u4F8B\u5E93\u6743\u9650\u3002\u6CA1\u6709\u5C31\u5148\u8DF3\u8FC7\u6848\u4F8B\u5E93\uFF0C\u76F4\u63A5\u6309\u6280\u80FD\u505A\uFF1B\u522B\u628A\u300C\u67E5\u4E0D\u5230\u300D\u5F53\u6210\u300C\u6CA1\u6709\u5148\u4F8B\u300D\u3002"
9916
- );
9917
- }
9918
- const json = JSON.parse(raw.slice(raw.indexOf("{")));
9919
- const seen = /* @__PURE__ */ new Map();
9920
- for (const h of json.data ?? []) {
9921
- const p = h.metadata?.path ?? "";
9922
- const m = /^cases\/[^/]+\/([^/]+)\//.exec(p);
9923
- if (!m) continue;
9924
- const id = m[1];
9925
- if (seen.has(id)) continue;
9926
- const c = idx.cases.find((x) => x.id === id);
9927
- seen.set(id, {
9928
- id,
9929
- score: h.score,
9930
- file: p.split("/").pop(),
9931
- status: c?.status,
9932
- tier: c?.tier,
9933
- skills: c?.skills,
9934
- customer_ask: c?.customer_ask,
9935
- match: c ? matchTag(c, fp) : "\u7D22\u5F15\u91CC\u6CA1\u6709\uFF08\u672C\u673A clone \u53EF\u80FD\u65E7\u4E86\uFF0Cgit pull \u4E00\u6B21\uFF09"
9936
- });
9937
- }
9938
- const rows2 = [...seen.values()];
9939
- emit4(
9940
- args,
9941
- { query, rows: rows2 },
9942
- () => rows2.length ? rows2.map((r) => `${r.id} [${r.status ?? "?"}\xB7${r.match}] ${r.customer_ask ?? ""}
9943
- \u6280\u80FD\uFF1A${(r.skills ?? []).join(" / ") || "\uFF08\u672A\u767B\u8BB0\uFF09"}`).join("\n") : `\u6CA1\u6709\u547D\u4E2D\u300C${query}\u300D\u7684\u6848\u4F8B\u3002\u5148\u6309\u6280\u80FD\u505A\uFF0C\u8DD1\u901A\u4E86\u7528 \`hcm chiron case submit\` \u4E0A\u884C\u4E00\u6761\u3002`
9944
- );
9945
- });
9946
- }
9947
- async function caseShowCommand(id, args) {
9948
- await guard(async () => {
9949
- const idx = loadIndex({ refresh: args.refresh });
9950
- const c = idx.cases.find((x) => x.id === id);
9951
- if (!c?.path) {
9952
- throw fail7(
9953
- `\u7D22\u5F15\u91CC\u6CA1\u6709\u6848\u4F8B ${id}`,
9954
- `\u5148 \`hcm chiron case search <\u5173\u952E\u8BCD>\` \u62FF\u51C6\u786E\u7684 id\uFF1B\u7D22\u5F15\u53EF\u80FD\u65E7\u4E86\uFF0C\u52A0 --refresh \u518D\u8BD5\u4E00\u6B21\u3002`
9955
- );
9956
- }
9957
- const files = args.file ? [args.file] : ["\u95EE\u9898.md", "\u65B9\u6848.md"];
9958
- const parts = [];
9959
- for (const f of files) {
9960
- try {
9961
- parts.push(`# ${f}
9962
-
9963
- ${fetchRepoFile(`${c.path}/${f}`)}`);
9964
- } catch {
9965
- parts.push(`# ${f}
9966
-
9967
- \uFF08\u8FD9\u4E2A\u6848\u4F8B\u6CA1\u6709\u8FD9\u4EFD\u6587\u4EF6\uFF09`);
9968
- }
9969
- }
9970
- const meta2 = fetchRepoFile(`${c.path}/case.yml`);
9971
- emit4(
9972
- args,
9973
- { id, caseYml: meta2, files: parts },
9974
- () => `case.yml:
9975
- ${meta2}
9976
-
9977
- ${parts.join("\n\n---\n\n")}
9978
-
9979
- \uFF08\u8BC1\u636E\u6587\u4EF6\u6CA1\u6709\u4E0B\u8F7D \u2014\u2014 \u53BB ${CNB_ORIGIN}/${CASES_REPO_SLUG}/-/tree/main/${c.path} \u770B\uFF09`
9980
- );
9981
- });
9982
- }
9983
- async function caseMatchCommand(args) {
9984
- await guard(async () => {
9985
- const idx = loadIndex({ refresh: args.refresh });
9986
- const fp = backendFingerprint(args.env);
9987
- const rows2 = idx.cases.filter((c) => c.status === "approved").map((c) => ({ id: c.id, match: matchTag(c, fp), skills: c.skills, customer_ask: c.customer_ask }));
9988
- emit4(args, { fingerprint: fp, rows: rows2 }, () => {
9989
- const head = fp.backend ? `\u5F53\u524D\u540E\u7AEF ${fp.backend.slice(0, 12)}\uFF08env ${args.env}\uFF09` : `\u26A0\uFE0F \u6CA1\u53D6\u5230\u5F53\u524D\u6307\u7EB9\uFF08${fp.reason}\uFF09\u2014\u2014\u4E0B\u9762\u6BCF\u4E00\u6761\u90FD\u6807\u7740\u300C\u672A\u6BD4\u5BF9\u300D\uFF0C\u522B\u628A\u5B83\u8BFB\u6210\u300C\u90FD\u80FD\u7167\u505A\u300D`;
9990
- return [head, ...rows2.map((r) => `${r.match === "\u5339\u914D" ? "\u2705" : "\xB7 "} ${r.id} [${r.match}] ${r.customer_ask ?? ""}`)].join("\n");
9991
- });
9992
- });
9993
- }
9994
- async function caseSubmitCommand(dir, args) {
9995
- await guard(async () => {
9996
- const src = path8.resolve(dir);
9997
- if (!existsSync2(path8.join(src, "case.yml"))) {
9998
- throw fail7(`${src} \u91CC\u6CA1\u6709 case.yml`, "\u6307\u5230\u9879\u76EE\u4ED3\u7684\u6848\u4F8B\u76EE\u5F55\uFF08\u5982 cases/CASE-20260902-xxx\uFF09\uFF0C\u90A3\u91CC\u5E94\u5F53\u6709 case.yml\u3002");
9999
- }
10000
- const yamlText = readFileSync5(path8.join(src, "case.yml"), "utf8");
10001
- const id = /^\s*(?:id|case_id):\s*(\S+)/m.exec(yamlText)?.[1];
10002
- if (!id) throw fail7("case.yml \u91CC\u6CA1\u6709 id", "case.yml \u9876\u5C42\u8981\u6709 `id: CASE-YYYYMMDD-xxx`\u3002");
10003
- const work = mkdtempSync(path8.join(os4.tmpdir(), "hcm-case-submit-"));
10004
- try {
10005
- const repo = path8.join(work, "chiron-cases");
10006
- try {
10007
- run("git", ["clone", "--depth", "1", "--filter=blob:none", "--quiet", CASES_REPO_URL, repo]);
10008
- } catch (e) {
10009
- throw fail7(
10010
- `clone \u6848\u4F8B\u5E93\u5931\u8D25\uFF1A${String(e.message).split("\n")[0]}`,
10011
- `\u4E0A\u884C\u8981\u5F80 ${CASES_REPO_SLUG} \u63D0 PR\uFF0C\u9700\u8981\u8BE5\u4ED3\u5199\u6743\u9650\uFF08\`cnb login\` \u4E14\u88AB\u52A0\u8FDB\u4ED3\uFF09\u3002\u6848\u4F8B\u8FD8\u5728\u4F60\u7684\u9879\u76EE\u4ED3\u91CC\uFF0C\u6CA1\u4E22\u3002`
10012
- );
10013
- }
10014
- const branch = `case/${id}-submit`;
10015
- run("git", ["-C", repo, "checkout", "-q", "-B", branch]);
10016
- const dst = path8.join(repo, "cases", args.category, id);
10017
- cpSync(src, dst, { recursive: true, filter: (p) => !p.includes("node_modules") });
10018
- mkdirSync(path8.join(dst, "evidence"), { recursive: true });
10019
- let doc = readFileSync5(path8.join(dst, "case.yml"), "utf8");
10020
- doc = /^\s*tier:/m.test(doc) ? doc.replace(/^\s*tier:.*$/m, "tier: public") : `tier: public
10021
- ${doc}`;
10022
- doc = /^\s*category:/m.test(doc) ? doc.replace(/^\s*category:.*$/m, `category: ${args.category}`) : `category: ${args.category}
10023
- ${doc}`;
10024
- doc = /^\s*origin:/m.test(doc) ? doc.replace(/^\s*origin:.*$/m, `origin: ${args.origin}`) : `origin: ${args.origin}
10025
- ${doc}`;
10026
- if (!/^\s*status:/m.test(doc)) doc = `status: approved
10027
- ${doc}`;
10028
- writeFileSync2(path8.join(dst, "case.yml"), doc);
10029
- run("python3", ["scripts/render-readme.py", dst], { cwd: repo });
10030
- let lint;
10031
- try {
10032
- lint = run("python3", ["scripts/lint-case.py"], { cwd: repo });
10033
- } catch (e) {
10034
- throw fail7(
10035
- `\u6848\u4F8B lint \u6CA1\u8FC7\uFF0CPR \u6CA1\u5F00\uFF1A
10036
- ${e.stdout ?? e.message}`,
10037
- "\u7167 lint \u7684\u63D0\u793A\u8865\u9F50 case.yml \u4E0E\u6B63\u6587\uFF0C\u518D\u8DD1\u4E00\u6B21\u3002\u6848\u4F8B\u8FD8\u5728\u9879\u76EE\u4ED3\u91CC\uFF0C\u6CA1\u4E22\u3002"
10038
- );
10039
- }
10040
- run("python3", ["scripts/build-index.py"], { cwd: repo });
10041
- run("git", ["-C", repo, "add", "-A"]);
10042
- run("git", ["-C", repo, "-c", "user.name=hcm-cli", "-c", "user.email=chiron@local", "commit", "-q", "-m", `case: ${id}\uFF08\u9879\u76EE\u6848\u4F8B\u4E0A\u884C\uFF09`]);
10043
- run("git", ["-C", repo, "push", "-q", "-f", "-u", "origin", branch]);
10044
- const pr = run("cnb", [
10045
- "pulls",
10046
- "post-pull",
10047
- "--repo",
10048
- CASES_REPO_SLUG,
10049
- "--base",
10050
- "main",
10051
- "--head",
10052
- branch,
10053
- "--title",
10054
- `case: ${id}\uFF08\u9879\u76EE\u6848\u4F8B\u4E0A\u884C\uFF09`,
10055
- "--body",
10056
- `\u6765\u6E90\uFF1A${args.origin}
10057
-
10058
- \u7531 \`hcm chiron case submit\` \u63D0\u4EA4\uFF0Clint \u5DF2\u8FC7\u3002`
10059
- ]);
10060
- const num = /number: "?(\d+)/.exec(pr)?.[1];
10061
- rmSync(INDEX_CACHE(), { force: true });
10062
- emit4(
10063
- args,
10064
- { id, pr: num, lint: lint.trim() },
10065
- () => `\u5DF2\u5F00 PR #${num ?? "?"}\uFF1A${CNB_ORIGIN}/${CASES_REPO_SLUG}/-/pulls/${num ?? ""}
10066
- ${lint.trim()}`
10063
+ function workspaceActiveNextCommand(activeWorkspaceKey) {
10064
+ return activeWorkspaceKey ? "hcm workspace deactivate" : null;
10065
+ }
10066
+ function unwrapWorkspaceActionPayload(response) {
10067
+ if (!response || typeof response !== "object") return response;
10068
+ const envelope = response;
10069
+ if (envelope.data && typeof envelope.data === "object") return envelope.data;
10070
+ if (envelope.result && typeof envelope.result === "object") return envelope.result;
10071
+ return response;
10072
+ }
10073
+ async function requestWorkspaceDeactivation(client3) {
10074
+ const response = await client3.action(
10075
+ "TenantExtensionWorkspace",
10076
+ "unbind-current-user",
10077
+ { method: "POST", scope: "class" }
10078
+ );
10079
+ const binding = unwrapWorkspaceActionPayload(response);
10080
+ if (!binding || typeof binding !== "object" || binding.enabled !== false) {
10081
+ throw new Error("workspace deactivate \u672A\u6536\u5230 enabled=false \u7684\u670D\u52A1\u7AEF\u56DE\u6267\uFF0C\u4E0D\u80FD\u786E\u8BA4\u5DF2\u9000\u51FA\u5F00\u53D1\u6A21\u5F0F");
10082
+ }
10083
+ return binding;
10084
+ }
10085
+ async function workspaceActivateCommand(workspaceKey, args) {
10086
+ try {
10087
+ const client3 = HcmClient19.fromAuthContext(await getActiveAuthContextFromCli(args));
10088
+ const key2 = normalizeWorkspaceKey(workspaceKey);
10089
+ await setDevModeBinding(client3, key2);
10090
+ const fmt = args.output ?? "table";
10091
+ if (fmt === "table") {
10092
+ process.stdout.write(`workspace activated: ${key2}
10093
+ `);
10094
+ process.stdout.write("\u8BE5\u7A7A\u95F4\u7684 metas / scripts / menus / mini_apps \u73B0\u5DF2\u5728\u5F53\u524D\u79DF\u6237\u751F\u6548\u3002\n");
10095
+ } else {
10096
+ process.stdout.write(
10097
+ formatObject20({ workspaceKey: key2, activated: true }, { format: fmt }) + "\n"
10067
10098
  );
10068
- } finally {
10069
- rmSync(work, { recursive: true, force: true });
10070
10099
  }
10071
- });
10100
+ process.exitCode = 0;
10101
+ return;
10102
+ } catch (e) {
10103
+ exitWorkspaceError(e, args.env ?? args.profile);
10104
+ }
10105
+ }
10106
+ async function workspaceDeactivateCommand(args) {
10107
+ try {
10108
+ const client3 = HcmClient19.fromAuthContext(await getActiveAuthContextFromCli(args));
10109
+ const binding = await requestWorkspaceDeactivation(client3);
10110
+ const result = { ...binding, deactivated: true };
10111
+ const fmt = args.output ?? "table";
10112
+ if (fmt === "table") {
10113
+ process.stdout.write("workspace deactivated\n");
10114
+ process.stdout.write("\u5F53\u524D\u8EAB\u4EFD\u5DF2\u9000\u51FA\u5F00\u53D1\u8005\u6A21\u5F0F\uFF1B\u5F00\u53D1\u7A7A\u95F4\u3001\u672C\u5730\u6587\u4EF6\u4E0E\u5DF2\u53D1\u5E03\u8D44\u4EA7\u5747\u672A\u5220\u9664\u3002\n");
10115
+ } else {
10116
+ process.stdout.write(formatObject20(result, { format: fmt }) + "\n");
10117
+ }
10118
+ process.exitCode = 0;
10119
+ return;
10120
+ } catch (e) {
10121
+ exitWorkspaceError(e, args.env ?? args.profile);
10122
+ }
10072
10123
  }
10073
10124
 
10074
- // src/commands/chiron-project.ts
10075
- import { normalizeOrigin as normalizeOrigin3 } from "@hcmai/sdk";
10076
- import { JIRA_BASE, JIRA_PROJECT, jiraTokenSource } from "@hcmai/sdk";
10077
- import { ENV_FILE, parseEnvYaml, renderEnvYaml, findEnvByEndpoint as findEnvByEndpoint3, normalizeOrigin as normalizeOrigin4 } from "@hcmai/sdk";
10078
- import { CASES_REPO_URL as CASES_REPO_URL2 } from "@hcmai/sdk";
10079
- import { JIRA_BASE as JIRA_BASE2, JIRA_PROJECT as JIRA_PROJECT2, JIRA_TOKEN_FILE, jiraTokenSource as jiraTokenSource2 } from "@hcmai/sdk";
10080
- var SKILLS_DIR = "hcm-skills";
10081
- var CHIRON_PROJECT_DIRECTORIES = [
10082
- "work",
10083
- "decisions",
10084
- "evidence",
10085
- "requirements",
10086
- "deliverables",
10087
- "cases",
10088
- "gaps",
10089
- "customer-docs"
10090
- ];
10091
- function projectEnvFromConfig(cfg) {
10092
- const endpoint = normalizeOrigin3(cfg.endpoint);
10125
+ // src/commands/identity.ts
10126
+ init_exit();
10127
+ import axios4 from "axios";
10128
+ import {
10129
+ AUTH_INFO_PATH,
10130
+ CliError as CliError23,
10131
+ CliErrorCode as CliErrorCode22,
10132
+ formatObject as formatObject21,
10133
+ fromAxiosError as fromAxiosError20,
10134
+ loadEnv as loadEnv4,
10135
+ saveEnv as saveEnv3,
10136
+ loadIdentity as loadIdentity4,
10137
+ listIdentities as listIdentities4,
10138
+ deleteIdentity as deleteIdentity3,
10139
+ loadGlobalConfig as loadGlobalConfig8,
10140
+ resolveActiveEnv,
10141
+ printResolvedEnvironment as printResolvedEnvironment6,
10142
+ TokenStore as TokenStore4,
10143
+ toPrincipal
10144
+ } from "@hcmai/sdk";
10145
+ var fetchAuthInfo = async (endpoint, accessToken) => {
10146
+ const response = await axios4.get(`${endpoint.replace(/\/$/, "")}${AUTH_INFO_PATH}`, {
10147
+ headers: { Authorization: `Bearer ${accessToken}` },
10148
+ timeout: 3e4
10149
+ });
10150
+ return response.data;
10151
+ };
10152
+ async function inspectIdentity(name, fetcher = fetchAuthInfo) {
10153
+ const meta2 = await loadIdentity4(name);
10154
+ const env2 = await loadEnv4(meta2.env);
10155
+ const accessToken = await TokenStore4.forIdentity(name).getStoredAccessToken();
10156
+ if (!accessToken) {
10157
+ throw new CliError23({
10158
+ code: CliErrorCode22.AUTH_FAILED,
10159
+ message: `identity '${name}' \u6CA1\u6709\u53EF\u8BFB\u53D6\u7684\u6301\u4E45\u5316 token`,
10160
+ context: { nextStep: `\u91CD\u65B0\u767B\u5F55\u8BE5\u8EAB\u4EFD\uFF1Ahcm login --env ${meta2.env} --name ${name}` }
10161
+ });
10162
+ }
10163
+ printResolvedEnvironment6({ name: meta2.env, config: env2, source: "identity" }, name, meta2.tenantId);
10164
+ const raw = await fetcher(env2.endpoint, accessToken);
10165
+ const principal = toPrincipal(raw);
10166
+ const body = raw && typeof raw === "object" && !Array.isArray(raw) ? raw : {};
10167
+ const serverScopes = Array.isArray(body.scopes) ? body.scopes.map(String) : void 0;
10093
10168
  return {
10094
- endpoint,
10095
- // 冗余一份 frontend:前后端地址不一致的部署里,页面验收要开的是它。
10096
- frontend: normalizeOrigin3(cfg.frontend ?? endpoint),
10097
- tenant: cfg.tenantId ?? "1"
10169
+ identity: name,
10170
+ env: meta2.env,
10171
+ endpoint: env2.endpoint,
10172
+ scheme: meta2.scheme,
10173
+ userId: principal?.userId ?? null,
10174
+ username: principal?.username ?? null,
10175
+ tenantId: principal?.tenantId ?? null,
10176
+ // null 明确表示服务端没回该字段;[] 才表示服务端确认角色为空。
10177
+ roles: principal?.roles ?? null,
10178
+ scopes: serverScopes ?? meta2.scopes,
10179
+ expiresAt: meta2.expiresAt ?? null,
10180
+ source: AUTH_INFO_PATH
10098
10181
  };
10099
10182
  }
10100
- async function inspectCaseLibrary() {
10183
+ async function identityShow(name, args) {
10101
10184
  try {
10102
- const idx = loadIndex();
10103
- return { ok: true, count: idx.cases.length };
10185
+ const details = await inspectIdentity(name);
10186
+ return exitOk(formatObject21(details, { format: args.output ?? "json" }));
10104
10187
  } catch (e) {
10105
- return { ok: false, reason: firstLine("", e) };
10188
+ exitWithError(axios4.isAxiosError(e) ? fromAxiosError20(e, name) : e);
10106
10189
  }
10107
10190
  }
10108
- function firstLine(stderr, error) {
10109
- if (error) return error.message;
10110
- const line = stderr.split(/\r?\n/).map((l) => l.trim()).find(Boolean);
10111
- return line ?? "\uFF08\u65E0\u8F93\u51FA\uFF09";
10112
- }
10113
- async function inspectJira() {
10114
- const src = await jiraTokenSource();
10115
- if (!src) {
10116
- return {
10117
- ok: false,
10118
- reason: `\u6CA1\u6709\u4EE4\u724C\u3002\u5728 ${JIRA_BASE} \u53F3\u4E0A\u89D2\u5934\u50CF \u2192 \u4E2A\u4EBA\u8BBE\u7F6E \u2192 Personal Access Tokens \u5EFA\u4E00\u4E2A\uFF0C\u7136\u540E\uFF1Amkdir -p ~/.config/hcm && read -rs pat && printf "%s" "$pat" > ~/.config/hcm/jira-token && chmod 600 ~/.config/hcm/jira-token && unset pat`
10119
- };
10191
+ async function identityList(args) {
10192
+ try {
10193
+ const g = await loadGlobalConfig8();
10194
+ const filter = args.env === "all" ? void 0 : await resolveActiveEnv({ envFlag: args.env }, process.env, g);
10195
+ const names = await listIdentities4(filter);
10196
+ if (names.length === 0) {
10197
+ return exitOk("(no identities)");
10198
+ }
10199
+ const lines = [];
10200
+ for (const n of names) {
10201
+ const meta2 = await loadIdentity4(n);
10202
+ const env2 = await loadEnv4(meta2.env).catch(() => null);
10203
+ const isDefault = env2?.defaultIdentity === n ? "*" : " ";
10204
+ const expired = meta2.expiresAt && new Date(meta2.expiresAt) < /* @__PURE__ */ new Date() ? " (expired)" : "";
10205
+ lines.push(`${isDefault} ${n} scheme=${meta2.scheme} env=${meta2.env}${expired}`);
10206
+ }
10207
+ return exitOk(lines.join("\n"));
10208
+ } catch (e) {
10209
+ exitWithError(e);
10120
10210
  }
10121
- const call = async (path_) => {
10122
- const res = await fetch(`${JIRA_BASE}${path_}`, {
10123
- headers: { Authorization: `Bearer ${src.token}`, Accept: "application/json" },
10124
- signal: AbortSignal.timeout(15e3)
10211
+ }
10212
+ async function identityUse(name) {
10213
+ try {
10214
+ const meta2 = await loadIdentity4(name);
10215
+ const env2 = await loadEnv4(meta2.env).catch(() => {
10216
+ throw new CliError23({
10217
+ code: CliErrorCode22.IDENTITY_NOT_IN_ENV,
10218
+ message: `identity '${name}' references env '${meta2.env}' which no longer exists. Re-create the env, or remove this orphan: hcm identity remove ${name}`
10219
+ });
10125
10220
  });
10126
- return res;
10127
- };
10221
+ env2.defaultIdentity = name;
10222
+ await saveEnv3(meta2.env, env2);
10223
+ return exitOk(`\u2705 default identity for env '${meta2.env}': ${name}`);
10224
+ } catch (e) {
10225
+ exitWithError(e);
10226
+ }
10227
+ }
10228
+ async function identityRemove(name) {
10128
10229
  try {
10129
- const me = await call("/rest/api/2/myself");
10130
- if (me.status === 401) return { ok: false, from: src.from, reason: "\u4EE4\u724C\u65E0\u6548\u6216\u5DF2\u8FC7\u671F\uFF0C\u91CD\u5EFA PAT \u540E\u91CD\u65B0\u5B58\u4E00\u6B21" };
10131
- if (!me.ok) return { ok: false, from: src.from, reason: `\u8FDE\u5F97\u4E0A\u4F46 /myself \u8FD4\u56DE ${me.status}` };
10132
- const who = (await me.json()).displayName ?? "";
10133
- const project = await call(`/rest/api/2/project/${JIRA_PROJECT}`);
10134
- return {
10135
- ok: project.ok,
10136
- from: src.from,
10137
- who,
10138
- projectVisible: project.ok,
10139
- reason: project.ok ? void 0 : `\u770B\u4E0D\u5230\u9879\u76EE ${JIRA_PROJECT}\uFF08${project.status}\uFF09\uFF0C\u627E Jira \u7BA1\u7406\u5458\u5F00\u6743\u9650`
10140
- };
10230
+ const meta2 = await loadIdentity4(name);
10231
+ try {
10232
+ await TokenStore4.forIdentity(name).clear();
10233
+ } catch (err) {
10234
+ process.stderr.write(
10235
+ `[hcm] event=identity_cleanup_failed identity=${name} reason=${JSON.stringify(String(err.message))}
10236
+ `
10237
+ );
10238
+ }
10239
+ await deleteIdentity3(name);
10240
+ const env2 = await loadEnv4(meta2.env).catch(() => null);
10241
+ if (env2?.defaultIdentity === name) {
10242
+ env2.defaultIdentity = void 0;
10243
+ await saveEnv3(meta2.env, env2);
10244
+ }
10245
+ return exitOk(`\u2705 identity '${name}' removed`);
10141
10246
  } catch (e) {
10142
- return { ok: false, from: src.from, reason: `\u8FDE\u4E0D\u4E0A ${JIRA_BASE}\uFF1A${e.message}` };
10247
+ exitWithError(e);
10143
10248
  }
10144
10249
  }
10145
10250
 
10146
10251
  // src/commands/chiron-init.ts
10252
+ init_auth_guard();
10253
+ init_exit();
10254
+ import { promises as fs9 } from "fs";
10255
+ import path10 from "path";
10256
+ import {
10257
+ CliError as CliError24,
10258
+ CliErrorCode as CliErrorCode23,
10259
+ HcmClient as HcmClient20,
10260
+ fetchReconIdentity,
10261
+ formatObject as formatObject22,
10262
+ httpProbe,
10263
+ isTempEnv as isTempEnv3,
10264
+ listIdentities as listIdentities5,
10265
+ loadEnv as loadEnv5,
10266
+ discoverProjectEnv as discoverProjectEnv4,
10267
+ findEnvByEndpoint as findEnvByEndpoint4,
10268
+ normalizeOrigin as normalizeOrigin5,
10269
+ loadGlobalConfig as loadGlobalConfig9
10270
+ } from "@hcmai/sdk";
10147
10271
  async function probeTokenTenant(envName, requested) {
10148
10272
  const ctx = await getActiveAuthContextFromCli({ env: envName });
10149
10273
  const client3 = HcmClient20.fromAuthContext(ctx);
@@ -10161,7 +10285,6 @@ var defaultChironInitDeps = {
10161
10285
  await skillsSyncCommand({
10162
10286
  target: "codex",
10163
10287
  env: envName,
10164
- dir: path9.join(root, SKILLS_DIR),
10165
10288
  output: "table"
10166
10289
  });
10167
10290
  } finally {
@@ -10192,7 +10315,7 @@ async function resolveInitEnv(root, args, deps) {
10192
10315
  };
10193
10316
  }
10194
10317
  const existing = await discoverProjectEnv4(root);
10195
- if (existing && path9.dirname(existing.path) === path9.resolve(root)) {
10318
+ if (existing && path10.dirname(existing.path) === path10.resolve(root)) {
10196
10319
  const name2 = args.env ?? existing.config.default;
10197
10320
  const env2 = existing.config.environments[name2];
10198
10321
  if (!env2) throw new CliError24({
@@ -10242,7 +10365,7 @@ ${explicitPaths}` }
10242
10365
  }
10243
10366
  async function scaffoldChironProject(root, env2, envName) {
10244
10367
  const result = { created: [], updated: [], preserved: [] };
10245
- const envFile = path9.join(root, ENV_FILE);
10368
+ const envFile = path10.join(root, ENV_FILE);
10246
10369
  const existing = await fs9.readFile(envFile, "utf8").catch(() => null);
10247
10370
  if (existing !== null) {
10248
10371
  const document = parseEnvYaml(existing);
@@ -10268,14 +10391,14 @@ async function scaffoldChironProject(root, env2, envName) {
10268
10391
  result.created.push(ENV_FILE);
10269
10392
  }
10270
10393
  for (const directory of CHIRON_PROJECT_DIRECTORIES) {
10271
- const absolute = path9.join(root, directory);
10394
+ const absolute = path10.join(root, directory);
10272
10395
  await ensureDirectory(absolute);
10273
- await writeIfAbsent(path9.join(absolute, ".gitkeep"), "", result, `${directory}/.gitkeep`);
10396
+ await writeIfAbsent(path10.join(absolute, ".gitkeep"), "", result, `${directory}/.gitkeep`);
10274
10397
  }
10275
10398
  return result;
10276
10399
  }
10277
10400
  async function runChironInit(args, deps = defaultChironInitDeps) {
10278
- const root = path9.resolve(args.project ?? ".");
10401
+ const root = path10.resolve(args.project ?? ".");
10279
10402
  const say = (line) => process.stderr.write(`[chiron init] ${line}
10280
10403
  `);
10281
10404
  const choice = await resolveInitEnv(root, args, deps);
@@ -10707,7 +10830,7 @@ ${r.url}
10707
10830
  init_auth_guard();
10708
10831
  init_exit();
10709
10832
  import { promises as fs10 } from "fs";
10710
- import path10 from "path";
10833
+ import path11 from "path";
10711
10834
  import {
10712
10835
  HcmClient as HcmClient21,
10713
10836
  CliError as CliError25,
@@ -10728,9 +10851,9 @@ var defaultDeps2 = {
10728
10851
  inspectJira: () => inspectJira()
10729
10852
  };
10730
10853
  async function runChironDoctor(args, deps = defaultDeps2) {
10731
- const root = path10.resolve(args.project ?? ".");
10854
+ const root = path11.resolve(args.project ?? ".");
10732
10855
  const report = { ok: false, project: root, env: null, envName: null, lines: [] };
10733
- const envText = await fs10.readFile(path10.join(root, ENV_FILE), "utf8").catch(() => null);
10856
+ const envText = await fs10.readFile(path11.join(root, ENV_FILE), "utf8").catch(() => null);
10734
10857
  if (envText === null) {
10735
10858
  report.lines.push({
10736
10859
  item: "\u767B\u5F55",
@@ -10800,10 +10923,17 @@ async function runChironDoctor(args, deps = defaultDeps2) {
10800
10923
  }
10801
10924
  }
10802
10925
  const skillsLine = async () => {
10803
- const state = await readSkillsState(path10.join(root, SKILLS_DIR));
10804
- if (!state) return { item: "\u6280\u80FD", verdict: "fail", detail: `${SKILLS_DIR}/ \u91CC\u6CA1\u6709\u5B89\u88C5\u6E05\u5355`, nextStep: "hcm chiron skills sync" };
10926
+ const state = await readSkillsState(skillsSyncDir(root));
10927
+ if (!state) {
10928
+ return {
10929
+ item: "\u6280\u80FD",
10930
+ verdict: "fail",
10931
+ detail: `${SKILLS_DIR}/${SKILLS_SYNC_SUBDIR}/ \u91CC\u6CA1\u6709\u5B89\u88C5\u6E05\u5355`,
10932
+ nextStep: "hcm chiron skills sync"
10933
+ };
10934
+ }
10805
10935
  const count = Object.keys(state.skills).length;
10806
- if (state.endpoint && normalizeOrigin4(state.endpoint) !== env2.endpoint) {
10936
+ if (state.endpoint && normalizeOrigin3(state.endpoint) !== env2.endpoint) {
10807
10937
  return { item: "\u6280\u80FD", verdict: "fail", detail: `${count} \u4E2A\uFF0C\u4F46\u88C5\u81EA ${state.endpoint}\uFF0C\u4E0D\u662F\u9879\u76EE\u73AF\u5883 ${env2.endpoint}`, nextStep: "hcm chiron skills sync \u91CD\u88C5\uFF08\u5B83\u4F1A\u6309\u9879\u76EE\u73AF\u5883\u91CD\u65B0\u5BF9\u8D26\uFF09" };
10808
10938
  }
10809
10939
  if (state.target !== "codex") {
@@ -10857,7 +10987,7 @@ async function chironDoctorCommand(args, deps) {
10857
10987
  // src/commands/chiron-env.ts
10858
10988
  init_exit();
10859
10989
  import { promises as fs11 } from "fs";
10860
- import path11 from "path";
10990
+ import path12 from "path";
10861
10991
  import yaml from "js-yaml";
10862
10992
  import {
10863
10993
  AUTH_INFO_PATH as AUTH_INFO_PATH2,
@@ -11003,9 +11133,9 @@ async function runChironEnv(action, args = {}) {
11003
11133
  if (args.output && !["table", "json", "yaml"].includes(args.output)) {
11004
11134
  invalid2(`\u672A\u77E5\u8F93\u51FA\u683C\u5F0F '${args.output}'\uFF0C\u914D\u7F6E\u672A\u5199\u5165\u3002`, "\u4F7F\u7528 --output table\u3001json \u6216 yaml");
11005
11135
  }
11006
- const root = path11.resolve(args.project ?? ".");
11136
+ const root = path12.resolve(args.project ?? ".");
11007
11137
  const discovered = await discoverProjectEnv5(root);
11008
- const file = discovered?.path ?? path11.join(root, ENV_FILE2);
11138
+ const file = discovered?.path ?? path12.join(root, ENV_FILE2);
11009
11139
  if (!discovered && action !== "add") invalid2(`\u6CA1\u6709\u627E\u5230 ${file}\u3002`, "\u8FDB\u5165\u987E\u95EE\u9879\u76EE\uFF0C\u6216\u8FD0\u884C hcm chiron env add <\u540D\u5B57> --endpoint <URL> --frontend <URL> --tenant <\u79DF\u6237>");
11010
11140
  const original = discovered ? await fs11.readFile(file, "utf8") : null;
11011
11141
  const config2 = original ? parseEnvYaml2(original) : { default: "", environments: {} };
@@ -11101,7 +11231,7 @@ init_exit();
11101
11231
  import { spawnSync } from "child_process";
11102
11232
  import { accessSync, constants } from "fs";
11103
11233
  import fs12 from "fs/promises";
11104
- import path12 from "path";
11234
+ import path13 from "path";
11105
11235
  import { CliError as CliError27, CliErrorCode as CliErrorCode25, formatObject as formatObject26, HcmClient as HcmClient22, loadEnv as loadEnv6 } from "@hcmai/sdk";
11106
11236
  var EVIDENCE_DIR = "evidence";
11107
11237
  var WAIT_MS_MAX = 6e4;
@@ -11142,10 +11272,10 @@ function resolveEvidenceTarget(projectRoot, out) {
11142
11272
  if (!out.endsWith(".png")) {
11143
11273
  throw new CliError27({ code: CliErrorCode25.INVALID_ARGUMENT, message: `--out \u8981\u4EE5 .png \u7ED3\u5C3E\uFF0C\u6536\u5230\u7684\u662F ${out}` });
11144
11274
  }
11145
- const root = path12.resolve(projectRoot);
11146
- const evidenceRoot = path12.join(root, EVIDENCE_DIR);
11147
- const absolute = path12.resolve(root, out);
11148
- if (absolute !== evidenceRoot && !absolute.startsWith(evidenceRoot + path12.sep)) {
11275
+ const root = path13.resolve(projectRoot);
11276
+ const evidenceRoot = path13.join(root, EVIDENCE_DIR);
11277
+ const absolute = path13.resolve(root, out);
11278
+ if (absolute !== evidenceRoot && !absolute.startsWith(evidenceRoot + path13.sep)) {
11149
11279
  throw new CliError27({
11150
11280
  code: CliErrorCode25.INVALID_ARGUMENT,
11151
11281
  message: `--out \u8981\u843D\u5728\u9879\u76EE\u7684 ${EVIDENCE_DIR}/ \u4E0B\uFF08${evidenceRoot}\uFF09\uFF0C\u6536\u5230\u7684\u662F ${absolute}`
@@ -11192,9 +11322,9 @@ function findChrome(probe, override) {
11192
11322
  }
11193
11323
  async function assertInsideEvidence(deps, evidenceRoot, absolute) {
11194
11324
  const canonicalRoot = await deps.realpath(evidenceRoot);
11195
- const canonicalParent = await deps.realpath(path12.dirname(absolute));
11325
+ const canonicalParent = await deps.realpath(path13.dirname(absolute));
11196
11326
  if (canonicalRoot === null || canonicalParent === null) return;
11197
- if (canonicalParent !== canonicalRoot && !canonicalParent.startsWith(canonicalRoot + path12.sep)) {
11327
+ if (canonicalParent !== canonicalRoot && !canonicalParent.startsWith(canonicalRoot + path13.sep)) {
11198
11328
  throw new CliError27({
11199
11329
  code: CliErrorCode25.INVALID_ARGUMENT,
11200
11330
  message: `--out \u7684\u7236\u76EE\u5F55\u7ECF\u7B26\u53F7\u94FE\u63A5\u8DD1\u51FA\u4E86 ${EVIDENCE_DIR}/\uFF1A${canonicalParent}`
@@ -11213,7 +11343,7 @@ async function runChironPage(target, args, deps) {
11213
11343
  const reject = (args.rejectText ?? []).filter((t) => t.trim().length > 0);
11214
11344
  const viewport = parseViewport(args.size ?? "1440x900");
11215
11345
  const waitMs = parseWaitMs(args.waitMs);
11216
- const root = path12.resolve(args.project ?? ".");
11346
+ const root = path13.resolve(args.project ?? ".");
11217
11347
  const { evidenceRoot, absolute } = resolveEvidenceTarget(root, args.out);
11218
11348
  if (await deps.present(absolute)) {
11219
11349
  throw new CliError27({
@@ -11221,7 +11351,7 @@ async function runChironPage(target, args, deps) {
11221
11351
  message: `\u622A\u56FE\u5DF2\u5B58\u5728\uFF0C\u4E0D\u8986\u76D6\uFF1A${absolute}\u3002\u6362\u4E2A --out\uFF0C\u6216\u5148\u628A\u65E7\u8BC1\u636E\u632A\u8D70\u3002`
11222
11352
  });
11223
11353
  }
11224
- await deps.ensureDir(path12.dirname(absolute));
11354
+ await deps.ensureDir(path13.dirname(absolute));
11225
11355
  await assertInsideEvidence(deps, evidenceRoot, absolute);
11226
11356
  const browser = deps.findBrowser();
11227
11357
  if (!browser) {
@@ -11334,7 +11464,7 @@ async function chironPageCommand(target, args, deps = defaultChironPageDeps) {
11334
11464
  init_exit();
11335
11465
  import { spawnSync as spawnSync2 } from "child_process";
11336
11466
  import { promises as fs13 } from "fs";
11337
- import path13 from "path";
11467
+ import path14 from "path";
11338
11468
  import yaml2 from "js-yaml";
11339
11469
  import { formatObject as formatObject27 } from "@hcmai/sdk";
11340
11470
 
@@ -12203,7 +12333,7 @@ async function runCase(spec, root, opts = {}, deps = defaultDeps3) {
12203
12333
  continue;
12204
12334
  }
12205
12335
  if (c.file) {
12206
- const file = path13.resolve(root, fill(c.file));
12336
+ const file = path14.resolve(root, fill(c.file));
12207
12337
  const want = c.expect ?? {};
12208
12338
  const bad = [];
12209
12339
  if (want.xlsx_header || want.xlsx_min_rows !== void 0) {
@@ -12219,7 +12349,7 @@ async function runCase(spec, root, opts = {}, deps = defaultDeps3) {
12219
12349
  results.push(bad.length ? { name: c.name, verdict: "fail", detail: bad.join("\uFF1B") } : { name: c.name, verdict: "pass", detail: "" });
12220
12350
  continue;
12221
12351
  }
12222
- const out = path13.join("evidence", "test", `${spec.name}-${c.name}`.replace(/[^\w一-龥-]+/g, "_") + ".png");
12352
+ const out = path14.join("evidence", "test", `${spec.name}-${c.name}`.replace(/[^\w一-龥-]+/g, "_") + ".png");
12223
12353
  const argv = [fill(c.page), "--out", out, "--project", root];
12224
12354
  if (opts.env) argv.push("--env", opts.env);
12225
12355
  const as = c.as ?? opts.as;
@@ -12236,11 +12366,11 @@ async function runCase(spec, root, opts = {}, deps = defaultDeps3) {
12236
12366
  }
12237
12367
  async function loadCases(target) {
12238
12368
  const stat = await fs13.stat(target);
12239
- const files = stat.isDirectory() ? (await fs13.readdir(target)).filter((f) => /\.ya?ml$/.test(f)).sort().map((f) => path13.join(target, f)) : [target];
12369
+ const files = stat.isDirectory() ? (await fs13.readdir(target)).filter((f) => /\.ya?ml$/.test(f)).sort().map((f) => path14.join(target, f)) : [target];
12240
12370
  const out = [];
12241
12371
  for (const f of files) {
12242
12372
  const spec = yaml2.load(await fs13.readFile(f, "utf8"));
12243
- assertUsableSpec(spec, path13.basename(f));
12373
+ assertUsableSpec(spec, path14.basename(f));
12244
12374
  out.push({ file: f, spec });
12245
12375
  }
12246
12376
  if (out.length === 0) throw new Error(`${target} \u4E0B\u6CA1\u6709\u7528\u4F8B\uFF08*.yml\uFF09`);
@@ -12248,15 +12378,15 @@ async function loadCases(target) {
12248
12378
  }
12249
12379
  async function chironTestCommand(target, args, deps) {
12250
12380
  try {
12251
- const root = path13.resolve(args.project ?? ".");
12252
- const where = path13.resolve(root, target ?? "tests");
12381
+ const root = path14.resolve(args.project ?? ".");
12382
+ const where = path14.resolve(root, target ?? "tests");
12253
12383
  const cases = await loadCases(where);
12254
12384
  const report = [];
12255
12385
  let failed2 = 0;
12256
12386
  for (const { file, spec } of cases) {
12257
12387
  const results = await runCase(spec, root, { env: args.env, as: args.as }, deps);
12258
12388
  failed2 += results.filter((r) => r.verdict === "fail").length;
12259
- report.push({ case: spec.name, file: path13.relative(root, file), results });
12389
+ report.push({ case: spec.name, file: path14.relative(root, file), results });
12260
12390
  }
12261
12391
  const fmt = args.output ?? "table";
12262
12392
  if (fmt === "json" || fmt === "yaml") {
@@ -12397,7 +12527,7 @@ import {
12397
12527
  writeRisk
12398
12528
  } from "@hcmai/sdk";
12399
12529
  import { existsSync as existsSync3 } from "fs";
12400
- import * as path14 from "path";
12530
+ import * as path15 from "path";
12401
12531
  function premise(message, hint = "") {
12402
12532
  process.stderr.write(message + (hint ? `
12403
12533
  \u2192 ${hint}` : "") + "\n");
@@ -12424,13 +12554,13 @@ async function runSeedPlan(args, client3) {
12424
12554
  const reconDir = candidates[0].reconDir;
12425
12555
  if (candidates.length > 1) {
12426
12556
  process.stderr.write(
12427
- `\u26A0\uFE0F \u540C\u79DF\u6237\u4E0B\u6709 ${candidates.length} \u4EFD\u57FA\u7EBF\uFF0C\u672C\u8F6E\u8BFB\u7684\u662F \`${path14.basename(reconDir)}\`\uFF1A` + candidates.slice(1).map((c) => `\`${path14.basename(c.reconDir)}\``).join("\u3001") + " \u672A\u88AB\u8BFB\u53D6 \u2014\u2014 \u4E0D\u540C sourceKey \u7684\u4EA7\u7269**\u4E0D\u53EF\u4E92\u6362**\u3002\n"
12557
+ `\u26A0\uFE0F \u540C\u79DF\u6237\u4E0B\u6709 ${candidates.length} \u4EFD\u57FA\u7EBF\uFF0C\u672C\u8F6E\u8BFB\u7684\u662F \`${path15.basename(reconDir)}\`\uFF1A` + candidates.slice(1).map((c) => `\`${path15.basename(c.reconDir)}\``).join("\u3001") + " \u672A\u88AB\u8BFB\u53D6 \u2014\u2014 \u4E0D\u540C sourceKey \u7684\u4EA7\u7269**\u4E0D\u53EF\u4E92\u6362**\u3002\n"
12428
12558
  );
12429
12559
  }
12430
12560
  const round = inspectRound2(reconDir);
12431
12561
  process.stderr.write(roundWarning(round));
12432
12562
  const baseline = {
12433
- path: `${path14.basename(path14.dirname(reconDir))}/${path14.basename(reconDir)}`,
12563
+ path: `${path15.basename(path15.dirname(reconDir))}/${path15.basename(reconDir)}`,
12434
12564
  roundId: round.roundId ?? null
12435
12565
  };
12436
12566
  let exemptions = null;
@@ -12692,7 +12822,7 @@ async function deliverySeedVerifyCommand(args) {
12692
12822
  // src/commands/delivery-seed-find.ts
12693
12823
  import { existsSync as existsSync4 } from "fs";
12694
12824
  import { readFileSync as readFileSync8 } from "fs";
12695
- import * as path15 from "path";
12825
+ import * as path16 from "path";
12696
12826
  import {
12697
12827
  INIT_EXIT_CODES as INIT_EXIT_CODES2,
12698
12828
  ValueHints,
@@ -12706,10 +12836,10 @@ import {
12706
12836
  valuesRoundCaveat
12707
12837
  } from "@hcmai/sdk";
12708
12838
  function provenance(chosenReconDir, others) {
12709
- let line = `> \u57FA\u7EBF\uFF1A\`${path15.basename(chosenReconDir)}\`
12839
+ let line = `> \u57FA\u7EBF\uFF1A\`${path16.basename(chosenReconDir)}\`
12710
12840
  `;
12711
12841
  if (others.length > 0) {
12712
- line += `> \u26A0\uFE0F \u540C\u79DF\u6237\u4E0B\u53E6\u6709 ${others.length} \u4EFD\u57FA\u7EBF\u672A\u88AB\u8BFB\u53D6\uFF1A` + others.map((o) => `\`${path15.basename(o)}\``).join("\u3001") + " \u2014\u2014 \u4E0D\u540C sourceKey \u7684\u4EA7\u7269**\u4E0D\u53EF\u4E92\u6362**\u3002\n";
12842
+ line += `> \u26A0\uFE0F \u540C\u79DF\u6237\u4E0B\u53E6\u6709 ${others.length} \u4EFD\u57FA\u7EBF\u672A\u88AB\u8BFB\u53D6\uFF1A` + others.map((o) => `\`${path16.basename(o)}\``).join("\u3001") + " \u2014\u2014 \u4E0D\u540C sourceKey \u7684\u4EA7\u7269**\u4E0D\u53EF\u4E92\u6362**\u3002\n";
12713
12843
  }
12714
12844
  return `${line}
12715
12845
  `;
@@ -13046,7 +13176,7 @@ import {
13046
13176
  runTriageRound
13047
13177
  } from "@hcmai/sdk";
13048
13178
  import { mkdirSync as mkdirSync2, readFileSync as readFileSync10, writeFileSync as writeFileSync3 } from "fs";
13049
- import * as path16 from "path";
13179
+ import * as path17 from "path";
13050
13180
  var DEFAULT_CAPABILITIES3 = "default";
13051
13181
  function premise4(message, hint) {
13052
13182
  process.stderr.write(`\u{1F534} \u524D\u63D0\u4E0D\u6210\u7ACB\uFF1A${message}
@@ -13082,8 +13212,8 @@ function renderProblems(rows2) {
13082
13212
  `;
13083
13213
  }
13084
13214
  function writeTriageArtifact(outDir, body) {
13085
- const out = path16.join(outDir, "work", "triage.md");
13086
- mkdirSync2(path16.dirname(out), { recursive: true });
13215
+ const out = path17.join(outDir, "work", "triage.md");
13216
+ mkdirSync2(path17.dirname(out), { recursive: true });
13087
13217
  writeFileSync3(out, body, "utf8");
13088
13218
  return out;
13089
13219
  }
@@ -13502,7 +13632,7 @@ program.command("update <Model>").description("\u66F4\u65B0\u4E00\u6761 Model \u
13502
13632
  ).action((model, opts) => updateCommand(model, opts));
13503
13633
  program.command("version").description("\u67E5 CLI \u4E0E\u540E\u7AEF\u4E24\u4E2A\u7248\u672C\uFF08commit / tag / \u6784\u5EFA\u65F6\u95F4\uFF09\u2014\u2014\u514D\u8BA4\u8BC1\uFF0C\u65E0\u9700\u5148 login").option("--endpoint <url>", "\u540E\u7AEF\u5730\u5740\uFF08\u9ED8\u8BA4\u53D6\u9879\u76EE\u73AF\u5883\u6216 activeEnv \u7684 endpoint\uFF09").option("--env <name>", "\u4ECE\u8BE5 env \u89E3\u6790 endpoint").option("--output <fmt>", "\u8F93\u51FA\u683C\u5F0F\uFF1Atable | json | yaml", "json").action((opts) => versionCommand(opts));
13504
13634
  program.command("upgrade").alias("self-update").description("\u5347\u7EA7 CLI \u81EA\u5DF1\uFF08\u6CE8\u610F\uFF1A`hcm update` \u662F\u66F4\u65B0\u4E1A\u52A1\u8BB0\u5F55\uFF0C\u4E0D\u662F\u5347\u7EA7\uFF09").option("--check", "\u53EA\u68C0\u67E5\uFF1B\u6709\u65B0\u7248\u672C\u65F6\u4EE5\u9000\u51FA\u7801 1 \u7ED3\u675F\uFF0C\u4FBF\u4E8E\u811A\u672C\u5224\u65AD").action((opts) => upgradeCommand(opts));
13505
- program.command("open [path]").description("\u7528\u5F53\u524D CLI \u8EAB\u4EFD\u6253\u5F00\u524D\u7AEF\u9875\u9762\uFF1A\u94F8\u4E00\u5F20 60s \u4E00\u6B21\u6027\u7968\u636E\u4EA4\u7ED9\u6D4F\u89C8\u5668\uFF0C\u4F1A\u8BDD token \u4E0D\u8FDB URL").option("--print-url", "\u53EA\u6253\u5370\u767B\u5F55 URL\uFF0C\u4E0D\u5F00\u6D4F\u89C8\u5668\uFF08\u7ED9 agent \u6D4F\u89C8\u5668 navigate \u7528\uFF09").option("--env <name>", "\u672C\u6B21\u4F7F\u7528\u7684\u9879\u76EE\u73AF\u5883\u540D\u6216\u672C\u673A\u69FD\u540D").option("--as <identity>", "\u4E34\u65F6\u6362\u8EAB\u4EFD\uFF08\u8986\u76D6 env defaultIdentity\uFF0C\u672C\u6B21\u547D\u4EE4\uFF09").option("--profile <name>", "[deprecated] \u7528 --env \u66FF\u4EE3").action((path17, opts) => openCommand(path17, opts));
13635
+ program.command("open [path]").description("\u7528\u5F53\u524D CLI \u8EAB\u4EFD\u6253\u5F00\u524D\u7AEF\u9875\u9762\uFF1A\u94F8\u4E00\u5F20 60s \u4E00\u6B21\u6027\u7968\u636E\u4EA4\u7ED9\u6D4F\u89C8\u5668\uFF0C\u4F1A\u8BDD token \u4E0D\u8FDB URL").option("--print-url", "\u53EA\u6253\u5370\u767B\u5F55 URL\uFF0C\u4E0D\u5F00\u6D4F\u89C8\u5668\uFF08\u7ED9 agent \u6D4F\u89C8\u5668 navigate \u7528\uFF09").option("--env <name>", "\u672C\u6B21\u4F7F\u7528\u7684\u9879\u76EE\u73AF\u5883\u540D\u6216\u672C\u673A\u69FD\u540D").option("--as <identity>", "\u4E34\u65F6\u6362\u8EAB\u4EFD\uFF08\u8986\u76D6 env defaultIdentity\uFF0C\u672C\u6B21\u547D\u4EE4\uFF09").option("--profile <name>", "[deprecated] \u7528 --env \u66FF\u4EE3").action((path18, opts) => openCommand(path18, opts));
13506
13636
  var setting = program.command("setting").description("\u79DF\u6237\u7CFB\u7EDF\u53C2\u6570\uFF08\u767B\u5F55\u7B56\u7565 / \u5BC6\u7801\u7B56\u7565 / \u529F\u80FD\u5F00\u5173 / \u96C6\u6210\u53C2\u6570\uFF09");
13507
13637
  setting.command("get <domain>").description("\u8BFB\u67D0\u57DF\u53C2\u6570\uFF08\u5B9A\u4E49 + \u79DF\u6237\u8986\u76D6\u503C\u5408\u5E76\uFF0C\u7F3A\u5931\u56DE\u843D\u9ED8\u8BA4\u503C\uFF09").option("--env <name>", "\u672C\u6B21\u4F7F\u7528\u7684\u9879\u76EE\u73AF\u5883\u540D\u6216\u672C\u673A\u69FD\u540D").option("--as <identity>", "\u4E34\u65F6\u6362\u8EAB\u4EFD").option("--output <fmt>", "\u8F93\u51FA\u683C\u5F0F\uFF1Atable | json | yaml", "table").action((d, opts) => settingGetCommand(d, opts));
13508
13638
  setting.command("set <domain>").description("\u6539\u53C2\u6570\uFF0C\u53EF\u91CD\u590D --set\uFF1B\u8D70\u53D7\u63A7\u6821\u9A8C\u8DEF\u5F84\u800C\u975E\u6807\u51C6 CRUD").option(