@hcmai/sdk 0.7.0 → 0.7.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
@@ -155,8 +155,8 @@ var DEFAULT_DEFAULTS = {
155
155
  timeout: "60s",
156
156
  credentialStore: "auto"
157
157
  };
158
- function resolveCredentialStoreMode(cfg, env = process.env) {
159
- const fromEnv = normalizeCredentialStoreMode(env.HCM_CREDENTIAL_STORE, "HCM_CREDENTIAL_STORE");
158
+ function resolveCredentialStoreMode(cfg, env2 = process.env) {
159
+ const fromEnv = normalizeCredentialStoreMode(env2.HCM_CREDENTIAL_STORE, "HCM_CREDENTIAL_STORE");
160
160
  if (fromEnv) return fromEnv;
161
161
  const fromCfg = normalizeCredentialStoreMode(
162
162
  cfg?.defaults?.credentialStore,
@@ -207,11 +207,11 @@ async function saveGlobalConfig(cfg) {
207
207
  };
208
208
  await fs.writeFile(globalConfigFile(), yaml.dump(out), "utf-8");
209
209
  }
210
- function resolveActiveEnv(args, env, global) {
211
- return args.envFlag ?? env.HCM_ENV ?? env.HCM_PROFILE ?? global.activeEnv;
210
+ function resolveActiveEnv(args, env2, global) {
211
+ return args.envFlag ?? env2.HCM_ENV ?? env2.HCM_PROFILE ?? global.activeEnv;
212
212
  }
213
- function resolveActiveProfile(args, env, global) {
214
- return resolveActiveEnv({ envFlag: args.flag }, env, global);
213
+ function resolveActiveProfile(args, env2, global) {
214
+ return resolveActiveEnv({ envFlag: args.flag }, env2, global);
215
215
  }
216
216
 
217
217
  // src/auth/token-store.ts
@@ -813,13 +813,13 @@ async function deleteEnv(name) {
813
813
 
814
814
  // src/config/identity.ts
815
815
  import * as fs5 from "fs/promises";
816
- async function assertEnvExists(env) {
816
+ async function assertEnvExists(env2) {
817
817
  try {
818
- await fs5.access(envFile(env));
818
+ await fs5.access(envFile(env2));
819
819
  } catch {
820
820
  throw new CliError({
821
821
  code: "IDENTITY_NOT_IN_ENV" /* IDENTITY_NOT_IN_ENV */,
822
- message: `env '${env}' does not exist. Run: hcm env add ${env} --endpoint <url>`
822
+ message: `env '${env2}' does not exist. Run: hcm env add ${env2} --endpoint <url>`
823
823
  });
824
824
  }
825
825
  }
@@ -842,7 +842,7 @@ async function loadIdentity(name) {
842
842
  throw e;
843
843
  }
844
844
  }
845
- async function listIdentities(env) {
845
+ async function listIdentities(env2) {
846
846
  try {
847
847
  const entries = await fs5.readdir(identitiesDir(), { withFileTypes: true });
848
848
  const result = [];
@@ -850,7 +850,7 @@ async function listIdentities(env) {
850
850
  if (!e.isDirectory()) continue;
851
851
  try {
852
852
  const meta = await loadIdentity(e.name);
853
- if (!env || meta.env === env) result.push(e.name);
853
+ if (!env2 || meta.env === env2) result.push(e.name);
854
854
  } catch {
855
855
  }
856
856
  }
@@ -1025,9 +1025,9 @@ async function migrateOne(name) {
1025
1025
  }
1026
1026
 
1027
1027
  // src/config/resolve.ts
1028
- async function resolveActiveIdentity(args, env, activeEnv) {
1028
+ async function resolveActiveIdentity(args, env2, activeEnv) {
1029
1029
  if (args.asFlag) return args.asFlag;
1030
- if (env.HCM_IDENTITY) return env.HCM_IDENTITY;
1030
+ if (env2.HCM_IDENTITY) return env2.HCM_IDENTITY;
1031
1031
  const cfg = await loadEnv(activeEnv);
1032
1032
  if (cfg.defaultIdentity) return cfg.defaultIdentity;
1033
1033
  const [first] = await listIdentities(activeEnv);
@@ -1188,18 +1188,18 @@ async function action(http, model, actionName, input) {
1188
1188
  if (scope === "object" && !input.id) {
1189
1189
  throw new Error(`object action ${model}.${actionName} requires id`);
1190
1190
  }
1191
- const path22 = scope === "object" ? `/api/models/${model}/${input.id}/action/${actionName}` : `/api/models/${model}/action/${actionName}`;
1191
+ const path23 = scope === "object" ? `/api/models/${model}/${input.id}/action/${actionName}` : `/api/models/${model}/action/${actionName}`;
1192
1192
  const resp = await (async () => {
1193
1193
  if (method === "GET") {
1194
- return http.get(path22, { params: queryParams(input) });
1194
+ return http.get(path23, { params: queryParams(input) });
1195
1195
  }
1196
1196
  if (method === "DELETE") {
1197
- return http.delete(path22, { params: queryParams(input) });
1197
+ return http.delete(path23, { params: queryParams(input) });
1198
1198
  }
1199
1199
  if (method === "PUT") {
1200
- return http.put(path22, scope === "object" ? objectBody(input) : classBody(input));
1200
+ return http.put(path23, scope === "object" ? objectBody(input) : classBody(input));
1201
1201
  }
1202
- return http.post(path22, scope === "object" ? objectBody(input) : classBody(input));
1202
+ return http.post(path23, scope === "object" ? objectBody(input) : classBody(input));
1203
1203
  })();
1204
1204
  return resp.data;
1205
1205
  }
@@ -2500,22 +2500,22 @@ function isDelegationToolName(name) {
2500
2500
  function detectDelegationPause(resultData) {
2501
2501
  if (!resultData || typeof resultData !== "object") return false;
2502
2502
  const rd = resultData;
2503
- let env = null;
2503
+ let env2 = null;
2504
2504
  const raw = rd.result;
2505
2505
  if (typeof raw === "string") {
2506
2506
  try {
2507
2507
  const o = JSON.parse(raw);
2508
- env = o && typeof o === "object" ? o : null;
2508
+ env2 = o && typeof o === "object" ? o : null;
2509
2509
  } catch {
2510
- env = null;
2510
+ env2 = null;
2511
2511
  }
2512
2512
  } else if (raw && typeof raw === "object") {
2513
- env = raw;
2513
+ env2 = raw;
2514
2514
  } else {
2515
- env = rd;
2515
+ env2 = rd;
2516
2516
  }
2517
- if (!env || env.ok !== true) return false;
2518
- const text2 = [env.summary, env.data].filter((x) => typeof x === "string").join(" ");
2517
+ if (!env2 || env2.ok !== true) return false;
2518
+ const text2 = [env2.summary, env2.data].filter((x) => typeof x === "string").join(" ");
2519
2519
  return text2.includes("INTERACTION_REQUIRED") || text2.includes("CONFIRMATION_REQUIRED");
2520
2520
  }
2521
2521
  function resultText(resultData) {
@@ -2545,21 +2545,21 @@ function parseConfirmToolName(resultData) {
2545
2545
  function extractNextSteps(resultData) {
2546
2546
  if (!resultData || typeof resultData !== "object") return void 0;
2547
2547
  const rd = resultData;
2548
- let env = null;
2548
+ let env2 = null;
2549
2549
  const raw = rd.result;
2550
2550
  if (typeof raw === "string") {
2551
2551
  try {
2552
2552
  const o = JSON.parse(raw);
2553
- env = o && typeof o === "object" ? o : null;
2553
+ env2 = o && typeof o === "object" ? o : null;
2554
2554
  } catch {
2555
- env = null;
2555
+ env2 = null;
2556
2556
  }
2557
2557
  } else if (raw && typeof raw === "object") {
2558
- env = raw;
2558
+ env2 = raw;
2559
2559
  } else {
2560
- env = rd;
2560
+ env2 = rd;
2561
2561
  }
2562
- if (!env) return void 0;
2562
+ if (!env2) return void 0;
2563
2563
  const collect = (v) => {
2564
2564
  if (Array.isArray(v)) return v.map((x) => String(x)).filter((s) => s.length > 0);
2565
2565
  if (typeof v === "string" && v.length > 0) return [v];
@@ -2569,11 +2569,11 @@ function extractNextSteps(resultData) {
2569
2569
  }
2570
2570
  return [];
2571
2571
  };
2572
- const error = env.error;
2572
+ const error = env2.error;
2573
2573
  const fromError = error && typeof error === "object" ? collect(error.nextSteps).concat(
2574
2574
  collect(error.next_step)
2575
2575
  ) : [];
2576
- const fromTop = collect(env.nextSteps).concat(collect(env.next_step));
2576
+ const fromTop = collect(env2.nextSteps).concat(collect(env2.next_step));
2577
2577
  const all = [...fromError, ...fromTop];
2578
2578
  return all.length > 0 ? all : void 0;
2579
2579
  }
@@ -5592,18 +5592,18 @@ async function listTenantMeta(http, opts = {}) {
5592
5592
  const total = typeof body?.total === "number" ? body.total : payload?.total;
5593
5593
  return { items, total, raw: payload };
5594
5594
  }
5595
- async function getTenantMeta(http, path22) {
5596
- const resp = await http.get("/api/tenant-meta/meta", { params: { path: path22 } });
5595
+ async function getTenantMeta(http, path23) {
5596
+ const resp = await http.get("/api/tenant-meta/meta", { params: { path: path23 } });
5597
5597
  const payload = resp.data?.data ?? resp.data;
5598
5598
  if (typeof payload === "string") return payload;
5599
5599
  return String(payload?.content ?? "");
5600
5600
  }
5601
- async function saveTenantMeta(http, path22, content) {
5602
- const resp = await http.put("/api/tenant-meta/meta", { content }, { params: { path: path22 } });
5601
+ async function saveTenantMeta(http, path23, content) {
5602
+ const resp = await http.put("/api/tenant-meta/meta", { content }, { params: { path: path23 } });
5603
5603
  return resp.data?.data ?? resp.data;
5604
5604
  }
5605
- async function deleteTenantMeta(http, path22) {
5606
- const resp = await http.delete("/api/tenant-meta/meta", { params: { path: path22 } });
5605
+ async function deleteTenantMeta(http, path23) {
5606
+ const resp = await http.delete("/api/tenant-meta/meta", { params: { path: path23 } });
5607
5607
  return resp.data?.data ?? resp.data;
5608
5608
  }
5609
5609
 
@@ -9391,14 +9391,14 @@ function resolveSkillInstallOrder(manifest2, targetId) {
9391
9391
  throw invalid(`\u6280\u80FD\u76EE\u5F55\u4E2D\u4E0D\u5B58\u5728 ${targetId}`);
9392
9392
  }
9393
9393
  const state = /* @__PURE__ */ new Map();
9394
- const path22 = [];
9394
+ const path23 = [];
9395
9395
  const order = [];
9396
9396
  const visit = (id, requiredBy) => {
9397
9397
  const current = state.get(id);
9398
9398
  if (current === "done") return;
9399
9399
  if (current === "visiting") {
9400
- const cycleStart = path22.indexOf(id);
9401
- const cycle = [...path22.slice(Math.max(0, cycleStart)), id];
9400
+ const cycleStart = path23.indexOf(id);
9401
+ const cycle = [...path23.slice(Math.max(0, cycleStart)), id];
9402
9402
  throw invalid(`\u6280\u80FD\u4F9D\u8D56\u5B58\u5728\u73AF: ${cycle.join(" -> ")}`);
9403
9403
  }
9404
9404
  const skill = byId.get(id);
@@ -9407,11 +9407,11 @@ function resolveSkillInstallOrder(manifest2, targetId) {
9407
9407
  }
9408
9408
  assertSafeSkillId(skill.id);
9409
9409
  state.set(id, "visiting");
9410
- path22.push(id);
9410
+ path23.push(id);
9411
9411
  for (const required2 of normalizeRequirements(skill.requires, skill.id)) {
9412
9412
  visit(required2, skill.id);
9413
9413
  }
9414
- path22.pop();
9414
+ path23.pop();
9415
9415
  state.set(id, "done");
9416
9416
  order.push(skill);
9417
9417
  };
@@ -9502,11 +9502,11 @@ async function resetSettingItem(http, domain, namespace, settingKey, revision) {
9502
9502
  function parseSettingAssignment(raw) {
9503
9503
  const eq = raw.indexOf("=");
9504
9504
  if (eq <= 0) throw new Error(`--set \u9700\u8981 namespace.key=value \u5F62\u6001\uFF0C\u6536\u5230 "${raw}"`);
9505
- const path22 = raw.slice(0, eq).trim();
9505
+ const path23 = raw.slice(0, eq).trim();
9506
9506
  const value = raw.slice(eq + 1);
9507
- const dot = path22.lastIndexOf(".");
9508
- if (dot <= 0) throw new Error(`--set \u7684\u952E\u9700\u542B namespace\uFF0C\u5982 security.password.passwordPolicy=complex\uFF0C\u6536\u5230 "${path22}"`);
9509
- return { namespace: path22.slice(0, dot), settingKey: path22.slice(dot + 1), value };
9507
+ const dot = path23.lastIndexOf(".");
9508
+ if (dot <= 0) throw new Error(`--set \u7684\u952E\u9700\u542B namespace\uFF0C\u5982 security.password.passwordPolicy=complex\uFF0C\u6536\u5230 "${path23}"`);
9509
+ return { namespace: path23.slice(0, dot), settingKey: path23.slice(dot + 1), value };
9510
9510
  }
9511
9511
 
9512
9512
  // src/fde/layout.ts
@@ -9895,11 +9895,11 @@ function classifyStatus(status) {
9895
9895
  return "bad-response";
9896
9896
  }
9897
9897
  var CAPABILITIES_HEADER = "x-hcm-capabilities";
9898
- function buildUrl(path22, params) {
9898
+ function buildUrl(path23, params) {
9899
9899
  const entries = Object.entries(params ?? {}).filter(([, v]) => v !== void 0 && v !== null);
9900
- if (entries.length === 0) return path22;
9900
+ if (entries.length === 0) return path23;
9901
9901
  const qs = entries.map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(String(v))}`).join("&");
9902
- return `${path22}${path22.includes("?") ? "&" : "?"}${qs}`;
9902
+ return `${path23}${path23.includes("?") ? "&" : "?"}${qs}`;
9903
9903
  }
9904
9904
  function lowerHeaders(raw) {
9905
9905
  const out = {};
@@ -9941,14 +9941,14 @@ function httpProbe(http, capabilities) {
9941
9941
  const headers = { [CAPABILITIES_HEADER]: capabilities };
9942
9942
  const probe = {
9943
9943
  capabilities,
9944
- get(path22, params) {
9944
+ get(path23, params) {
9945
9945
  return once(
9946
- () => http.get(buildUrl(path22, params), { headers, validateStatus: () => true })
9946
+ () => http.get(buildUrl(path23, params), { headers, validateStatus: () => true })
9947
9947
  );
9948
9948
  },
9949
- post(path22, body) {
9949
+ post(path23, body) {
9950
9950
  return once(
9951
- () => http.post(path22, body, {
9951
+ () => http.post(path23, body, {
9952
9952
  headers: { ...headers, "content-type": "application/json" },
9953
9953
  validateStatus: () => true
9954
9954
  })
@@ -10060,8 +10060,8 @@ async function crawlMeta(probe, modelKeys2, metaType = DEFAULT_META_TYPE) {
10060
10060
  const results = probe.getMany ? await probe.getMany([...paths.keys()]) : await sequentialGet(probe, [...paths.keys()]);
10061
10061
  const metas = {};
10062
10062
  const unavailable = [];
10063
- for (const [path22, key] of paths) {
10064
- const out = results[path22];
10063
+ for (const [path23, key] of paths) {
10064
+ const out = results[path23];
10065
10065
  if (out === void 0) {
10066
10066
  unavailable.push({
10067
10067
  modelKey: key,
@@ -10291,8 +10291,8 @@ async function collectActionGates(probe, modelKeys2, state = "") {
10291
10291
  const statesEchoed = /* @__PURE__ */ new Set();
10292
10292
  let noStateEcho = 0;
10293
10293
  let answered = 0;
10294
- for (const [path22, model] of paths) {
10295
- const out = results[path22];
10294
+ for (const [path23, model] of paths) {
10295
+ const out = results[path23];
10296
10296
  if (out === void 0) {
10297
10297
  unavailable.push({
10298
10298
  modelKey: model,
@@ -10701,8 +10701,8 @@ async function collectMutation(probe, modelKeys2) {
10701
10701
  const results = probe.getMany ? await probe.getMany([...paths.keys()]) : await sequentialGet(probe, [...paths.keys()]);
10702
10702
  const mutation = {};
10703
10703
  const problems = [];
10704
- for (const [path22, key] of paths) {
10705
- const out = results[path22];
10704
+ for (const [path23, key] of paths) {
10705
+ const out = results[path23];
10706
10706
  if (out === void 0) {
10707
10707
  problems.push(`${key}: mutation-capability ${BATCH_LOST}`);
10708
10708
  mutation[key] = Object.fromEntries(
@@ -11147,11 +11147,11 @@ async function collectCodeTables(probe, modelEntries2, opts = {}) {
11147
11147
  keys.push(key);
11148
11148
  }
11149
11149
  for (const key of [...new Set(keys)].sort()) {
11150
- const path22 = listPath(key);
11150
+ const path23 = listPath(key);
11151
11151
  const started = tick();
11152
11152
  let requests = 0;
11153
11153
  let truncatedBy = null;
11154
- const probeOut = await post.call(probe, path22, { page: 0, size: 0 });
11154
+ const probeOut = await post.call(probe, path23, { page: 0, size: 0 });
11155
11155
  requests += 1;
11156
11156
  let total = null;
11157
11157
  let reason = null;
@@ -11200,7 +11200,7 @@ async function collectCodeTables(probe, modelEntries2, opts = {}) {
11200
11200
  failed = `\u89E6\u53D1\u5DE5\u5177\u7684\u6BCF\u8868${which === "requests" ? "\u8BF7\u6C42" : "\u5899\u949F"}\u4E0A\u9650\uFF08${which === "requests" ? `\u5DF2\u53D1 ${requests} \u6B21\u8BF7\u6C42` : `\u5DF2\u82B1 ${elapsed.toFixed(3)}s`}\uFF09\uFF0C\u505C\u5728\u7B2C ${page} \u9875\uFF0C\u5DF2\u6536 ${rows.length} \u884C / \u8BA1\u6570 ${total} \u884C\uFF0C\u672C\u8868\u6807 partial\u3002**\u8FD9\u662F\u5DE5\u5177\u7684\u622A\u65AD\uFF0C\u4E0D\u662F\u670D\u52A1\u7AEF\u7684\u6BDB\u75C5** \u2014\u2014 \u8C03\u5927 valuedomain.${which === "requests" ? "MAX_REQUESTS_PER_TABLE" : "MAX_SECONDS_PER_TABLE"} \u6216\u7ED9 collectCodeTables \u4F20 ${which === "requests" ? "maxRequests" : "maxSeconds"} \u540E\u91CD\u8DD1\u5C31\u80FD\u53D6\u5168`;
11201
11201
  break;
11202
11202
  }
11203
- const out = await post.call(probe, path22, { page, size: PAGE_SIZE });
11203
+ const out = await post.call(probe, path23, { page, size: PAGE_SIZE });
11204
11204
  requests += 1;
11205
11205
  if (out.error !== "ok") {
11206
11206
  failed = `\u7B2C ${page} \u9875\u5931\u8D25\uFF08HTTP ${out.status} / ${out.error}\uFF09`;
@@ -11964,7 +11964,7 @@ async function loadKeyIndex(client, model, keyFields, pageSize = PAGE_SIZE_DEFAU
11964
11964
  for (const name of ["id", ...fields]) {
11965
11965
  if (!projected.includes(name)) projected.push(name);
11966
11966
  }
11967
- const path22 = listPath2(model);
11967
+ const path23 = listPath2(model);
11968
11968
  const idx = /* @__PURE__ */ new Map();
11969
11969
  let total = null;
11970
11970
  let pages = 0;
@@ -11981,7 +11981,7 @@ async function loadKeyIndex(client, model, keyFields, pageSize = PAGE_SIZE_DEFAU
11981
11981
  let repeatedIds = 0;
11982
11982
  while (total === null || received < total) {
11983
11983
  const pageNo = pages;
11984
- const out = await client.post(path22, {
11984
+ const out = await client.post(path23, {
11985
11985
  page: pageNo,
11986
11986
  size: pageSize,
11987
11987
  fields: projected,
@@ -12173,8 +12173,8 @@ var CFB_MAGIC = Buffer.from([208, 207, 17, 224, 161, 177, 26, 225]);
12173
12173
  var ENCRYPTED_PACKAGE = Buffer.from("EncryptedPackage", "utf16le");
12174
12174
  var MAX_ENTRY_BYTES = 128 * 1024 * 1024;
12175
12175
  var SCAN_CHUNK_BYTES = 1024 * 1024;
12176
- function scanFor(path22, needle = ENCRYPTED_PACKAGE, budget = MAX_ENTRY_BYTES) {
12177
- const fd = openSync2(path22, "r");
12176
+ function scanFor(path23, needle = ENCRYPTED_PACKAGE, budget = MAX_ENTRY_BYTES) {
12177
+ const fd = openSync2(path23, "r");
12178
12178
  try {
12179
12179
  let tail = Buffer.alloc(0);
12180
12180
  let seen = 0;
@@ -12195,9 +12195,9 @@ function scanFor(path22, needle = ENCRYPTED_PACKAGE, budget = MAX_ENTRY_BYTES) {
12195
12195
  closeSync2(fd);
12196
12196
  }
12197
12197
  }
12198
- function isCfb(path22) {
12199
- if (statSync3(path22).size < CFB_MAGIC.length) return false;
12200
- const fd = openSync2(path22, "r");
12198
+ function isCfb(path23) {
12199
+ if (statSync3(path23).size < CFB_MAGIC.length) return false;
12200
+ const fd = openSync2(path23, "r");
12201
12201
  try {
12202
12202
  const head = Buffer.alloc(CFB_MAGIC.length);
12203
12203
  const n = readSync(fd, head, 0, CFB_MAGIC.length, 0);
@@ -12206,9 +12206,9 @@ function isCfb(path22) {
12206
12206
  closeSync2(fd);
12207
12207
  }
12208
12208
  }
12209
- function classifyCfb(path22, budget = MAX_ENTRY_BYTES) {
12210
- if (!isCfb(path22)) return "not-cfb";
12211
- switch (scanFor(path22, ENCRYPTED_PACKAGE, budget)) {
12209
+ function classifyCfb(path23, budget = MAX_ENTRY_BYTES) {
12210
+ if (!isCfb(path23)) return "not-cfb";
12211
+ switch (scanFor(path23, ENCRYPTED_PACKAGE, budget)) {
12212
12212
  case "found":
12213
12213
  return "encrypted";
12214
12214
  case "absent":
@@ -14748,16 +14748,16 @@ function rowCycles(parents) {
14748
14748
  const cycles = [];
14749
14749
  for (const start of [...parents.keys()].sort((a, b) => a - b)) {
14750
14750
  if (done.has(start)) continue;
14751
- const path22 = [];
14751
+ const path23 = [];
14752
14752
  const seen = /* @__PURE__ */ new Map();
14753
14753
  let node = start;
14754
14754
  while (node !== void 0 && !seen.has(node) && !done.has(node)) {
14755
- seen.set(node, path22.length);
14756
- path22.push(node);
14755
+ seen.set(node, path23.length);
14756
+ path23.push(node);
14757
14757
  node = parents.get(node);
14758
14758
  }
14759
- if (node !== void 0 && seen.has(node)) cycles.push(path22.slice(seen.get(node)));
14760
- for (const n of path22) done.add(n);
14759
+ if (node !== void 0 && seen.has(node)) cycles.push(path23.slice(seen.get(node)));
14760
+ for (const n of path23) done.add(n);
14761
14761
  }
14762
14762
  return cycles;
14763
14763
  }
@@ -20869,6 +20869,213 @@ function baselineRoundPremise(round) {
20869
20869
  }
20870
20870
  ];
20871
20871
  }
20872
+
20873
+ // src/internal-endpoints.ts
20874
+ var env = (key, fallback) => {
20875
+ const v = process.env[key];
20876
+ return v && v.trim() ? v.trim() : fallback;
20877
+ };
20878
+ var trimSlash = (u) => u.replace(/\/+$/, "");
20879
+ var JIRA_BASE = trimSlash(env("JIRA_BASE", "https://jira.hcmcloud.cn"));
20880
+ var JIRA_PROJECT = env("JIRA_PROJECT", "HCMNX");
20881
+ var JIRA_KEYCHAIN = env("JIRA_KEYCHAIN_SERVICE", "jira-hcmcloud");
20882
+ var CNB_ORIGIN = trimSlash(env("HCM_CNB_ORIGIN", "https://cnb.cool"));
20883
+ var CASES_REPO_SLUG = env("HCM_CASES_REPO", "hcm/chiron-cases");
20884
+ var CASES_REPO_URL = `${CNB_ORIGIN}/${CASES_REPO_SLUG}.git`;
20885
+ var repoIssueUrl = (repo, number) => `${CNB_ORIGIN}/${repo}/-/issues/${number}`;
20886
+ var CNB_FAVICON_URL = `${CNB_ORIGIN}/favicon.ico`;
20887
+
20888
+ // src/jira/client.ts
20889
+ import { execFileSync } from "child_process";
20890
+ import { promises as fs11 } from "fs";
20891
+ import os4 from "os";
20892
+ import path22 from "path";
20893
+ var JIRA_TOKEN_FILE = () => process.env.JIRA_TOKEN_FILE || path22.join(os4.homedir(), ".config", "hcm", "jira-token");
20894
+ async function jiraTokenSource() {
20895
+ if (process.env.JIRA_TOKEN?.trim()) return { token: process.env.JIRA_TOKEN.trim(), from: "\u73AF\u5883\u53D8\u91CF JIRA_TOKEN" };
20896
+ const file = JIRA_TOKEN_FILE();
20897
+ try {
20898
+ const stat = await fs11.stat(file);
20899
+ const value = (await fs11.readFile(file, "utf8")).trim();
20900
+ if (value) {
20901
+ if (stat.mode & 63) process.stderr.write(`[jira] \u8B66\u544A\uFF1A${file} \u5BF9\u5176\u4ED6\u7528\u6237\u53EF\u8BFB\uFF08chmod 600 \u6536\u7D27\uFF09
20902
+ `);
20903
+ return { token: value, from: file };
20904
+ }
20905
+ } catch {
20906
+ }
20907
+ try {
20908
+ const out = execFileSync("security", ["find-generic-password", "-s", JIRA_KEYCHAIN, "-w"], {
20909
+ encoding: "utf8",
20910
+ stdio: ["ignore", "pipe", "ignore"]
20911
+ }).trim();
20912
+ if (out) return { token: out, from: `\u94A5\u5319\u4E32 ${JIRA_KEYCHAIN}` };
20913
+ } catch {
20914
+ }
20915
+ return null;
20916
+ }
20917
+ function jiraTokenHelp() {
20918
+ return `\u62FF\u4E0D\u5230 Jira \u4EE4\u724C\u3002next_step=\u5148\u5728 ${JIRA_BASE} \u53F3\u4E0A\u89D2\u5934\u50CF \u2192 \u4E2A\u4EBA\u8BBE\u7F6E \u2192 Personal Access Tokens \u5EFA\u4E00\u4E2A\uFF0C\u518D\u9009\u4E00\u79CD\u5B58\u6CD5\uFF08\u90FD\u4E0D\u4F1A\u8FDB\u4ED3\u5E93\uFF09\uFF1A
20919
+ \u2460 \u6587\u4EF6\uFF08\u63A8\u8350\uFF0C\u4E0D\u5F39\u7A97\uFF09\uFF1Amkdir -p ~/.config/hcm && (umask 177; cat > ${JIRA_TOKEN_FILE()}) \u7136\u540E\u7C98\u4EE4\u724C\u3001Ctrl-D
20920
+ \u2461 \u94A5\u5319\u4E32\uFF08\u514D\u5F39\u7A97\u8981\u5E26 -A\uFF09\uFF1Asecurity add-generic-password -a "$USER" -s ${JIRA_KEYCHAIN} -A -w
20921
+ \u2462 \u53EA\u7528\u4E00\u6B21\uFF1AJIRA_TOKEN=<\u4EE4\u724C> \u8DD1\u672C\u6B21\u547D\u4EE4`;
20922
+ }
20923
+ var JiraClient = class {
20924
+ base;
20925
+ project;
20926
+ token;
20927
+ fetchImpl;
20928
+ timeoutMs;
20929
+ constructor(o) {
20930
+ this.base = (o.base ?? JIRA_BASE).replace(/\/+$/, "");
20931
+ this.project = o.project ?? JIRA_PROJECT;
20932
+ this.token = o.token;
20933
+ this.fetchImpl = o.fetchImpl ?? fetch;
20934
+ this.timeoutMs = o.timeoutMs ?? 3e4;
20935
+ }
20936
+ browseUrl(key) {
20937
+ return `${this.base}/browse/${key}`;
20938
+ }
20939
+ /** 一次 REST 调用。失败时把 Jira 的 errorMessages 原样带出来,不吞。 */
20940
+ async api(p, init = {}) {
20941
+ const method = init.method ?? "GET";
20942
+ const url = p.startsWith("http") ? p : `${this.base}${p}`;
20943
+ const res = await this.fetchImpl(url, {
20944
+ method,
20945
+ headers: {
20946
+ Authorization: `Bearer ${this.token}`,
20947
+ Accept: "application/json",
20948
+ ...init.body !== void 0 ? { "Content-Type": "application/json" } : {}
20949
+ },
20950
+ body: init.body !== void 0 ? JSON.stringify(init.body) : void 0,
20951
+ signal: AbortSignal.timeout(this.timeoutMs)
20952
+ });
20953
+ const text2 = await res.text();
20954
+ if (!res.ok) {
20955
+ let detail = text2.slice(0, 600);
20956
+ try {
20957
+ const j = JSON.parse(text2);
20958
+ const msgs = [...j.errorMessages ?? [], ...Object.entries(j.errors ?? {}).map(([k, v]) => `${k}: ${v}`)];
20959
+ if (msgs.length) detail = msgs.join("\uFF1B");
20960
+ } catch {
20961
+ }
20962
+ const hint = res.status === 401 ? " next_step=\u4EE4\u724C\u65E0\u6548\u6216\u8FC7\u671F\uFF0C\u91CD\u5EFA PAT \u540E\u91CD\u65B0\u5B58\u4E00\u6B21" : res.status === 403 ? " next_step=\u4EE4\u724C\u6709\u6548\u4F46\u6CA1\u6709\u8FD9\u4E2A\u9879\u76EE\u7684\u6743\u9650\uFF0C\u627E Jira \u7BA1\u7406\u5458\u5F00\u6743\u9650" : "";
20963
+ throw new Error(`Jira ${method} ${p} \u2192 ${res.status}\uFF1A${detail}${hint}`);
20964
+ }
20965
+ return text2 ? JSON.parse(text2) : null;
20966
+ }
20967
+ serverInfo() {
20968
+ return this.api("/rest/api/2/serverInfo");
20969
+ }
20970
+ myself() {
20971
+ return this.api("/rest/api/2/myself");
20972
+ }
20973
+ async search(jql, {
20974
+ fields = ["summary", "status", "priority", "created", "updated", "labels", "issuetype", "reporter", "resolution"],
20975
+ max = 30
20976
+ } = {}) {
20977
+ const q = new URLSearchParams({ jql, maxResults: String(max), fields: fields.join(",") });
20978
+ const r = await this.api(`/rest/api/2/search?${q}`);
20979
+ return r.issues ?? [];
20980
+ }
20981
+ issue(key, fields) {
20982
+ return this.api(`/rest/api/2/issue/${encodeURIComponent(key)}${fields ? `?fields=${fields.join(",")}` : ""}`);
20983
+ }
20984
+ async comments(key) {
20985
+ const r = await this.api(
20986
+ `/rest/api/2/issue/${encodeURIComponent(key)}/comment?maxResults=50`
20987
+ );
20988
+ return r.comments ?? [];
20989
+ }
20990
+ addComment(key, body) {
20991
+ return this.api(`/rest/api/2/issue/${encodeURIComponent(key)}/comment`, { method: "POST", body: { body } });
20992
+ }
20993
+ createIssue(fields) {
20994
+ return this.api("/rest/api/2/issue", { method: "POST", body: { fields } });
20995
+ }
20996
+ async transitions(key) {
20997
+ const r = await this.api(
20998
+ `/rest/api/2/issue/${encodeURIComponent(key)}/transitions?expand=transitions.fields`
20999
+ );
21000
+ return r.transitions ?? [];
21001
+ }
21002
+ /** 按流转 id / 流转名 / 目标状态名三种写法找;找不到把可用流转列出来,不猜。 */
21003
+ async transition(key, nameOrId, comment) {
21004
+ const list = await this.transitions(key);
21005
+ const hit = list.find((t) => t.id === String(nameOrId)) || list.find((t) => t.name === nameOrId) || list.find((t) => t.to?.name === nameOrId);
21006
+ if (!hit) {
21007
+ throw new Error(
21008
+ `${key} \u4E0A\u6CA1\u6709\u5230\u300C${nameOrId}\u300D\u7684\u6D41\u8F6C\u3002\u53EF\u7528\uFF1A${list.map((t) => `${t.name}\u2192${t.to?.name}`).join(" / ") || "\uFF08\u65E0\uFF09"}`
21009
+ );
21010
+ }
21011
+ await this.api(`/rest/api/2/issue/${encodeURIComponent(key)}/transitions`, {
21012
+ method: "POST",
21013
+ body: {
21014
+ transition: { id: hit.id },
21015
+ ...comment ? { update: { comment: [{ add: { body: comment } }] } } : {}
21016
+ }
21017
+ });
21018
+ return hit;
21019
+ }
21020
+ /**
21021
+ * 建单前先问 Jira:这个项目有哪些 issuetype、每种哪些字段必填、可选值是什么。
21022
+ *
21023
+ * 🔴 不写死 customfield 编号:同名字段在别的项目里编号不同,写死就是换个项目静默填错格。
21024
+ * Jira 9 起旧的 `createmeta?projectKeys=&expand=` 已移除(11.3.2 实测 404),用按 issuetype 分页的新接口。
21025
+ */
21026
+ async createMeta(project = this.project) {
21027
+ const list = await this.api(
21028
+ `/rest/api/2/issue/createmeta/${project}/issuetypes`
21029
+ );
21030
+ const types = list.values ?? list.issueTypes ?? [];
21031
+ const out = [];
21032
+ for (const t of types) {
21033
+ if (t.subtask) continue;
21034
+ const f = await this.api(`/rest/api/2/issue/createmeta/${project}/issuetypes/${t.id}`);
21035
+ out.push({ id: t.id, name: t.name, fields: f.values ?? [] });
21036
+ }
21037
+ return out;
21038
+ }
21039
+ projectInfo(project = this.project) {
21040
+ return this.api(`/rest/api/2/project/${project}`);
21041
+ }
21042
+ projectStatuses(project = this.project) {
21043
+ return this.api(`/rest/api/2/project/${project}/statuses`);
21044
+ }
21045
+ /**
21046
+ * 远程链接:把代码库的 issue 挂到 Jira 单的「链接」栏里,而不是埋在评论中。
21047
+ * 公司现有惯例就是这样(HF 的开发任务用链接挂到 HCR 的需求上),照它来。
21048
+ * globalId 用 URL 本身,重复调用是覆盖不是新增。
21049
+ */
21050
+ addRemoteLink(key, url, title, relationship = "\u4EE3\u7801\u5E93\u6761\u76EE") {
21051
+ return this.api(`/rest/api/2/issue/${encodeURIComponent(key)}/remotelink`, {
21052
+ method: "POST",
21053
+ body: {
21054
+ globalId: url,
21055
+ relationship,
21056
+ object: { url, title, icon: { url16x16: CNB_FAVICON_URL, title: "cnb" } }
21057
+ }
21058
+ });
21059
+ }
21060
+ async remoteLinks(key) {
21061
+ try {
21062
+ return await this.api(`/rest/api/2/issue/${encodeURIComponent(key)}/remotelink`) ?? [];
21063
+ } catch {
21064
+ return [];
21065
+ }
21066
+ }
21067
+ assign(key, name) {
21068
+ return this.api(`/rest/api/2/issue/${encodeURIComponent(key)}/assignee`, { method: "PUT", body: { name } });
21069
+ }
21070
+ };
21071
+ function fieldByName(typeMeta, name) {
21072
+ return (typeMeta.fields ?? []).find((f) => f.name === name) ?? null;
21073
+ }
21074
+ async function createJiraClient(opts = {}) {
21075
+ const src = opts.token ? { token: opts.token, from: "\u53C2\u6570" } : await jiraTokenSource();
21076
+ if (!src) throw new Error(jiraTokenHelp());
21077
+ return new JiraClient({ ...opts, token: src.token });
21078
+ }
20872
21079
  export {
20873
21080
  ADVISORY_CODES,
20874
21081
  AGREEING_VERDICTS,
@@ -20894,12 +21101,16 @@ export {
20894
21101
  CARRIER_MISS,
20895
21102
  CARRIER_UNAVAILABLE,
20896
21103
  CARRIER_VERDICTS,
21104
+ CASES_REPO_SLUG,
21105
+ CASES_REPO_URL,
20897
21106
  CAUSE_INCOMPLETE_CURRENT,
20898
21107
  CHANGE_NOT_WRITTEN,
20899
21108
  CHANGE_STATES,
20900
21109
  CHANGE_UNKNOWN,
20901
21110
  CHANGE_WRITTEN,
20902
21111
  CHECK_GROUPS2 as CHECK_GROUPS,
21112
+ CNB_FAVICON_URL,
21113
+ CNB_ORIGIN,
20903
21114
  CODE_BINDING_ELSEWHERE,
20904
21115
  CODE_BINDING_OFF,
20905
21116
  CODE_BINDING_UNREADABLE,
@@ -20952,9 +21163,14 @@ export {
20952
21163
  HcmClient,
20953
21164
  IMPORT_PLAN_FILE,
20954
21165
  INIT_EXIT_CODES,
21166
+ JIRA_BASE,
21167
+ JIRA_KEYCHAIN,
21168
+ JIRA_PROJECT,
21169
+ JIRA_TOKEN_FILE,
20955
21170
  JOURNAL_FILE,
20956
21171
  JOURNAL_STOP_KINDS,
20957
21172
  JOURNAL_STOP_UNKNOWN,
21173
+ JiraClient,
20958
21174
  Journal,
20959
21175
  JournalError,
20960
21176
  KIT_CARRY_OVER_KEY,
@@ -21114,6 +21330,7 @@ export {
21114
21330
  create,
21115
21331
  createConversation,
21116
21332
  createHttpClient,
21333
+ createJiraClient,
21117
21334
  createV4Reducer,
21118
21335
  createWorkspaceFile,
21119
21336
  credentialsFile,
@@ -21151,6 +21368,7 @@ export {
21151
21368
  fetchSkillFile,
21152
21369
  fetchSkillMarkdown,
21153
21370
  fetchSkillReference,
21371
+ fieldByName,
21154
21372
  filterByStage,
21155
21373
  find,
21156
21374
  findLastAssistantSeq,
@@ -21186,6 +21404,8 @@ export {
21186
21404
  isTempEnv,
21187
21405
  isTerminalRunStatus,
21188
21406
  isZeroNetwork,
21407
+ jiraTokenHelp,
21408
+ jiraTokenSource,
21189
21409
  journalNote,
21190
21410
  judgeDrift,
21191
21411
  ledgerOnlySignpost,
@@ -21257,6 +21477,7 @@ export {
21257
21477
  renderTriage,
21258
21478
  renderValues,
21259
21479
  replHistoryFile,
21480
+ repoIssueUrl,
21260
21481
  resetSettingItem,
21261
21482
  resolveActiveEnv,
21262
21483
  resolveActiveIdentity,