@hcmai/sdk 0.9.4 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -46,8 +46,8 @@ function attachRetry(client, onRefresh) {
46
46
  const attempts = cfg.__attempts ?? 0;
47
47
  if (attempts < 2) {
48
48
  cfg.__attempts = attempts + 1;
49
- const delay = 500 * Math.pow(3, attempts);
50
- await new Promise((r) => setTimeout(r, delay));
49
+ const delay2 = 500 * Math.pow(3, attempts);
50
+ await new Promise((r) => setTimeout(r, delay2));
51
51
  cfg.headers.delete("Authorization");
52
52
  return client.request(cfg);
53
53
  }
@@ -57,6 +57,358 @@ function attachRetry(client, onRefresh) {
57
57
  );
58
58
  }
59
59
 
60
+ // src/errors/codes.ts
61
+ var ExitCode = /* @__PURE__ */ ((ExitCode2) => {
62
+ ExitCode2[ExitCode2["SUCCESS"] = 0] = "SUCCESS";
63
+ ExitCode2[ExitCode2["USAGE_ERROR"] = 1] = "USAGE_ERROR";
64
+ ExitCode2[ExitCode2["AUTH_ERROR"] = 2] = "AUTH_ERROR";
65
+ ExitCode2[ExitCode2["BUSINESS_ERROR"] = 3] = "BUSINESS_ERROR";
66
+ ExitCode2[ExitCode2["NETWORK_ERROR"] = 4] = "NETWORK_ERROR";
67
+ ExitCode2[ExitCode2["CONFIG_ERROR"] = 5] = "CONFIG_ERROR";
68
+ ExitCode2[ExitCode2["SIGINT"] = 130] = "SIGINT";
69
+ return ExitCode2;
70
+ })(ExitCode || {});
71
+ var CliErrorCode = /* @__PURE__ */ ((CliErrorCode2) => {
72
+ CliErrorCode2["INVALID_ARGUMENT"] = "INVALID_ARGUMENT";
73
+ CliErrorCode2["INVALID_JSON"] = "INVALID_JSON";
74
+ CliErrorCode2["MISSING_FLAG"] = "MISSING_FLAG";
75
+ CliErrorCode2["AUTH_FAILED"] = "AUTH_FAILED";
76
+ CliErrorCode2["AUTH_EXPIRED"] = "AUTH_EXPIRED";
77
+ CliErrorCode2["AUTH_REFRESH_FAILED"] = "AUTH_REFRESH_FAILED";
78
+ CliErrorCode2["WS_AUTH_ERROR"] = "WS_AUTH_ERROR";
79
+ CliErrorCode2["SCOPE_FORBIDDEN"] = "SCOPE_FORBIDDEN";
80
+ CliErrorCode2["BUSINESS_RULE_VIOLATION"] = "BUSINESS_RULE_VIOLATION";
81
+ CliErrorCode2["MODEL_NOT_FOUND"] = "MODEL_NOT_FOUND";
82
+ CliErrorCode2["ACTION_NOT_FOUND"] = "ACTION_NOT_FOUND";
83
+ CliErrorCode2["AGENT_NOT_FOUND"] = "AGENT_NOT_FOUND";
84
+ CliErrorCode2["TOOL_TIMEOUT"] = "TOOL_TIMEOUT";
85
+ CliErrorCode2["NETWORK_ERROR"] = "NETWORK_ERROR";
86
+ CliErrorCode2["TIMEOUT"] = "TIMEOUT";
87
+ CliErrorCode2["SERVER_ERROR"] = "SERVER_ERROR";
88
+ CliErrorCode2["PROTOCOL_UNSUPPORTED"] = "PROTOCOL_UNSUPPORTED";
89
+ CliErrorCode2["PROFILE_NOT_FOUND"] = "PROFILE_NOT_FOUND";
90
+ CliErrorCode2["CONFIG_PARSE_ERROR"] = "CONFIG_PARSE_ERROR";
91
+ CliErrorCode2["KEYCHAIN_UNAVAILABLE"] = "KEYCHAIN_UNAVAILABLE";
92
+ CliErrorCode2["ENV_NOT_FOUND"] = "ENV_NOT_FOUND";
93
+ CliErrorCode2["ENV_ALREADY_EXISTS"] = "ENV_ALREADY_EXISTS";
94
+ CliErrorCode2["ENV_ENDPOINT_REQUIRED"] = "ENV_ENDPOINT_REQUIRED";
95
+ CliErrorCode2["IDENTITY_NOT_FOUND"] = "IDENTITY_NOT_FOUND";
96
+ CliErrorCode2["IDENTITY_ALREADY_EXISTS"] = "IDENTITY_ALREADY_EXISTS";
97
+ CliErrorCode2["IDENTITY_NOT_IN_ENV"] = "IDENTITY_NOT_IN_ENV";
98
+ CliErrorCode2["TOKEN_EXPIRED"] = "TOKEN_EXPIRED";
99
+ CliErrorCode2["NO_ACTIVE_ENV"] = "NO_ACTIVE_ENV";
100
+ CliErrorCode2["SKILL_ID_CONFLICT"] = "SKILL_ID_CONFLICT";
101
+ CliErrorCode2["SKILL_SOURCE_UNREACHABLE"] = "SKILL_SOURCE_UNREACHABLE";
102
+ CliErrorCode2["SYNC_SOURCE_UNSUPPORTED"] = "SYNC_SOURCE_UNSUPPORTED";
103
+ return CliErrorCode2;
104
+ })(CliErrorCode || {});
105
+ var CODE_TO_EXIT = {
106
+ ["INVALID_ARGUMENT" /* INVALID_ARGUMENT */]: 1 /* USAGE_ERROR */,
107
+ ["INVALID_JSON" /* INVALID_JSON */]: 1 /* USAGE_ERROR */,
108
+ ["MISSING_FLAG" /* MISSING_FLAG */]: 1 /* USAGE_ERROR */,
109
+ ["AUTH_FAILED" /* AUTH_FAILED */]: 2 /* AUTH_ERROR */,
110
+ ["AUTH_EXPIRED" /* AUTH_EXPIRED */]: 2 /* AUTH_ERROR */,
111
+ ["AUTH_REFRESH_FAILED" /* AUTH_REFRESH_FAILED */]: 2 /* AUTH_ERROR */,
112
+ ["WS_AUTH_ERROR" /* WS_AUTH_ERROR */]: 2 /* AUTH_ERROR */,
113
+ ["SCOPE_FORBIDDEN" /* SCOPE_FORBIDDEN */]: 2 /* AUTH_ERROR */,
114
+ ["BUSINESS_RULE_VIOLATION" /* BUSINESS_RULE_VIOLATION */]: 3 /* BUSINESS_ERROR */,
115
+ ["MODEL_NOT_FOUND" /* MODEL_NOT_FOUND */]: 3 /* BUSINESS_ERROR */,
116
+ ["ACTION_NOT_FOUND" /* ACTION_NOT_FOUND */]: 3 /* BUSINESS_ERROR */,
117
+ ["AGENT_NOT_FOUND" /* AGENT_NOT_FOUND */]: 3 /* BUSINESS_ERROR */,
118
+ ["TOOL_TIMEOUT" /* TOOL_TIMEOUT */]: 3 /* BUSINESS_ERROR */,
119
+ ["NETWORK_ERROR" /* NETWORK_ERROR */]: 4 /* NETWORK_ERROR */,
120
+ ["TIMEOUT" /* TIMEOUT */]: 4 /* NETWORK_ERROR */,
121
+ ["SERVER_ERROR" /* SERVER_ERROR */]: 4 /* NETWORK_ERROR */,
122
+ ["PROTOCOL_UNSUPPORTED" /* PROTOCOL_UNSUPPORTED */]: 4 /* NETWORK_ERROR */,
123
+ ["PROFILE_NOT_FOUND" /* PROFILE_NOT_FOUND */]: 5 /* CONFIG_ERROR */,
124
+ ["CONFIG_PARSE_ERROR" /* CONFIG_PARSE_ERROR */]: 5 /* CONFIG_ERROR */,
125
+ ["KEYCHAIN_UNAVAILABLE" /* KEYCHAIN_UNAVAILABLE */]: 5 /* CONFIG_ERROR */,
126
+ ["ENV_NOT_FOUND" /* ENV_NOT_FOUND */]: 5 /* CONFIG_ERROR */,
127
+ ["ENV_ALREADY_EXISTS" /* ENV_ALREADY_EXISTS */]: 5 /* CONFIG_ERROR */,
128
+ ["ENV_ENDPOINT_REQUIRED" /* ENV_ENDPOINT_REQUIRED */]: 1 /* USAGE_ERROR */,
129
+ ["IDENTITY_NOT_FOUND" /* IDENTITY_NOT_FOUND */]: 5 /* CONFIG_ERROR */,
130
+ ["IDENTITY_ALREADY_EXISTS" /* IDENTITY_ALREADY_EXISTS */]: 5 /* CONFIG_ERROR */,
131
+ ["IDENTITY_NOT_IN_ENV" /* IDENTITY_NOT_IN_ENV */]: 5 /* CONFIG_ERROR */,
132
+ ["TOKEN_EXPIRED" /* TOKEN_EXPIRED */]: 2 /* AUTH_ERROR */,
133
+ ["NO_ACTIVE_ENV" /* NO_ACTIVE_ENV */]: 5 /* CONFIG_ERROR */,
134
+ ["SKILL_ID_CONFLICT" /* SKILL_ID_CONFLICT */]: 3 /* BUSINESS_ERROR */,
135
+ // 🔴 装坏了不是网络问题:报 network 会让顾问先去查 VPN。
136
+ ["SKILL_SOURCE_UNREACHABLE" /* SKILL_SOURCE_UNREACHABLE */]: 5 /* CONFIG_ERROR */,
137
+ ["SYNC_SOURCE_UNSUPPORTED" /* SYNC_SOURCE_UNSUPPORTED */]: 1 /* USAGE_ERROR */
138
+ };
139
+ function exitCodeFor(code) {
140
+ return CODE_TO_EXIT[code] ?? 1 /* USAGE_ERROR */;
141
+ }
142
+
143
+ // src/errors/cli-error.ts
144
+ var CliError = class extends Error {
145
+ code;
146
+ exitCode;
147
+ context;
148
+ traceId;
149
+ profile;
150
+ cause;
151
+ constructor(init) {
152
+ super(init.message);
153
+ this.name = "CliError";
154
+ this.code = init.code;
155
+ this.exitCode = exitCodeFor(init.code);
156
+ this.context = init.context;
157
+ this.traceId = init.traceId;
158
+ this.profile = init.profile;
159
+ this.cause = init.cause;
160
+ }
161
+ toFormattedString() {
162
+ const parts = [`${this.code}: ${this.message}`];
163
+ const serverCode = this.context?.responseCode;
164
+ if (typeof serverCode === "string" && serverCode && serverCode !== this.code) {
165
+ parts.push(`[\u670D\u52A1\u7AEF\u9519\u8BEF\u7801: ${serverCode}]`);
166
+ }
167
+ const field = this.context?.field;
168
+ if (typeof field === "string" && field) parts.push(`[\u5B57\u6BB5: ${field}]`);
169
+ if (this.traceId) parts.push(`[traceId: ${this.traceId}]`);
170
+ if (this.profile) parts.push(`[profile: ${this.profile}]`);
171
+ let out = parts.join(" ");
172
+ const details = this.context?.details;
173
+ const detailText = formatDetails(details);
174
+ if (detailText) out += `
175
+ \u8BE6\u60C5: ${detailText}`;
176
+ if (!detailText) {
177
+ const causeText = formatCause(this.cause);
178
+ if (causeText) out += `
179
+ \u539F\u56E0: ${causeText}`;
180
+ }
181
+ const nextStep = this.context?.nextStep;
182
+ if (typeof nextStep === "string" && nextStep) out += `
183
+ \u4E0B\u4E00\u6B65: ${nextStep}`;
184
+ return out;
185
+ }
186
+ toJSON() {
187
+ return {
188
+ code: this.code,
189
+ message: this.message,
190
+ context: this.context,
191
+ traceId: this.traceId
192
+ };
193
+ }
194
+ };
195
+ function fromAxiosError(err, profile) {
196
+ const status = err.response?.status;
197
+ const traceId = err.response?.headers?.["x-trace-id"];
198
+ const data = err.response?.data;
199
+ const body = data?.error ?? data;
200
+ const respCode = body?.code;
201
+ const respMsg = body?.message;
202
+ const respField = body?.field;
203
+ const respDetails = body?.details;
204
+ const respNextStep = body?.nextStep;
205
+ const respRetryable = body?.retryable;
206
+ let code;
207
+ if (status === 401) code = "AUTH_FAILED" /* AUTH_FAILED */;
208
+ else if (status === 403) code = "SCOPE_FORBIDDEN" /* SCOPE_FORBIDDEN */;
209
+ else if (status === 404 && respCode === "MODEL_NOT_FOUND") code = "MODEL_NOT_FOUND" /* MODEL_NOT_FOUND */;
210
+ else if (status === 404 && respCode === "ACTION_NOT_FOUND") code = "ACTION_NOT_FOUND" /* ACTION_NOT_FOUND */;
211
+ else if (status && status >= 400 && status < 500) code = "BUSINESS_RULE_VIOLATION" /* BUSINESS_RULE_VIOLATION */;
212
+ else if (status && status >= 500) code = "SERVER_ERROR" /* SERVER_ERROR */;
213
+ else if (err.code === "ECONNABORTED") code = "TIMEOUT" /* TIMEOUT */;
214
+ else code = "NETWORK_ERROR" /* NETWORK_ERROR */;
215
+ return new CliError({
216
+ code,
217
+ message: respMsg ?? err.message ?? "request failed",
218
+ context: {
219
+ status,
220
+ responseCode: respCode,
221
+ // 结构化错误的这几件必须原样带出:field 指哪个字段错了、details 机器可读、
222
+ // nextStep 是后端给的路标(ADR-166 终局协议)—— 吞掉它等于让命令行用户自己猜下一步。
223
+ ...respField ? { field: respField } : {},
224
+ ...respDetails !== void 0 ? { details: respDetails } : {},
225
+ ...respNextStep ? { nextStep: respNextStep } : {},
226
+ ...respRetryable !== void 0 ? { retryable: respRetryable } : {}
227
+ },
228
+ traceId,
229
+ profile,
230
+ cause: err
231
+ });
232
+ }
233
+ function formatDetails(details) {
234
+ if (details === void 0 || details === null) return void 0;
235
+ if (typeof details === "string") return details.trim() || void 0;
236
+ if (typeof details === "number" || typeof details === "boolean") return String(details);
237
+ let text3;
238
+ try {
239
+ text3 = JSON.stringify(details);
240
+ } catch {
241
+ return void 0;
242
+ }
243
+ if (!text3 || text3 === "{}" || text3 === "[]") return void 0;
244
+ return text3.length > 800 ? `${text3.slice(0, 800)}\u2026\uFF08\u5DF2\u622A\u65AD\uFF09` : text3;
245
+ }
246
+ function formatCause(cause) {
247
+ if (!cause) return void 0;
248
+ if (typeof cause === "string") return cause.trim().slice(0, 300) || void 0;
249
+ if (cause instanceof Error) {
250
+ const text3 = cause.message?.trim();
251
+ return text3 ? text3.slice(0, 300) : void 0;
252
+ }
253
+ return void 0;
254
+ }
255
+
256
+ // src/meta/describe.ts
257
+ function normalizeActionParams(action3) {
258
+ if (action3.parameters) return action3.parameters;
259
+ if (action3.params) return action3.params;
260
+ if (!action3.paramNames?.length && !action3.paramTypes?.length) return void 0;
261
+ const size = Math.max(action3.paramNames?.length ?? 0, action3.paramTypes?.length ?? 0);
262
+ return Array.from({ length: size }, (_, index) => ({
263
+ name: action3.paramNames?.[index] ?? `arg${index}`,
264
+ type: action3.paramTypes?.[index] ?? "unknown"
265
+ }));
266
+ }
267
+ async function describe(http, model, _opts = {}) {
268
+ const [metaResp, effective] = await Promise.all([
269
+ http.get(`/api/models/${model}/meta`),
270
+ fetchEffectiveActions(http, model)
271
+ ]);
272
+ const meta = metaResp.data;
273
+ const fields = (meta.fields ?? []).map((f) => ({
274
+ name: f.key ?? f.name ?? "",
275
+ label: f.name,
276
+ type: f.type ?? "unknown",
277
+ required: f.isRequired,
278
+ description: f.description,
279
+ enum: f.enum,
280
+ relation: f.relation,
281
+ // 只在为真时出这一位:false 与「这个服务端没有 i18n 这个概念」在下游没有区别,
282
+ // 出一个 `i18n: false` 只会让 --output json 的每个字段都多一行噪声。
283
+ ...f.isI18n ? { i18n: true } : {}
284
+ }));
285
+ const actions = (meta.actions ?? []).map((a) => ({
286
+ name: a.key ?? a.name ?? "",
287
+ label: a.label,
288
+ description: a.description,
289
+ params: normalizeActionParams(a),
290
+ scope: a.scope,
291
+ httpMethod: a.httpMethod,
292
+ effect: a.effect,
293
+ readOnly: a.readOnly,
294
+ paramTypes: a.paramTypes,
295
+ paramNames: a.paramNames,
296
+ returnType: a.returnType,
297
+ source: a.source
298
+ }));
299
+ return {
300
+ model: meta.name ?? model,
301
+ labels: meta.labels ?? {},
302
+ fields,
303
+ actions: mergeEffectiveActions(actions, effective),
304
+ relations: meta.relations ?? [],
305
+ effectiveActionsAvailable: effective.available,
306
+ ...effective.available ? {} : { effectiveActionsNote: effective.note }
307
+ };
308
+ }
309
+ async function fetchEffectiveActions(http, model) {
310
+ try {
311
+ const resp = await http.get(`/api/models/${model}/actions`);
312
+ const rows = resp.data?.actions;
313
+ if (!Array.isArray(rows)) {
314
+ return {
315
+ available: false,
316
+ rows: [],
317
+ note: `GET /api/models/${model}/actions \u6CA1\u6709\u8FD4\u56DE actions \u6570\u7EC4\uFF0C\u811A\u672C Action \u672A\u7EB3\u5165`
318
+ };
319
+ }
320
+ return { available: true, rows };
321
+ } catch (e) {
322
+ const err = e;
323
+ const status = err?.response?.status;
324
+ const detail = status ? `HTTP ${status}` : err?.message ?? String(e);
325
+ return {
326
+ available: false,
327
+ rows: [],
328
+ note: `GET /api/models/${model}/actions \u4E0D\u53EF\u7528\uFF08${detail}\uFF09\uFF0C\u811A\u672C Action \u672A\u7EB3\u5165`
329
+ };
330
+ }
331
+ }
332
+ function mergeEffectiveActions(fromMeta, effective) {
333
+ if (!effective.available) return fromMeta;
334
+ const known = new Set(fromMeta.map((a) => a.name));
335
+ const extra = [];
336
+ for (const row of effective.rows) {
337
+ const name = row.key ?? "";
338
+ if (!name || known.has(name)) continue;
339
+ known.add(name);
340
+ const candidate = row.candidates?.[0];
341
+ extra.push({
342
+ name,
343
+ label: row.label,
344
+ scope: candidate?.scope,
345
+ httpMethod: "POST",
346
+ effect: row.effect,
347
+ readOnly: row.readOnly,
348
+ source: candidate?.source
349
+ });
350
+ }
351
+ return [...fromMeta, ...extra];
352
+ }
353
+
354
+ // src/meta/action-effect.ts
355
+ var EFFECT_READ_ONLY = "READ_ONLY";
356
+ var EFFECT_WRITES = "WRITES";
357
+ var EFFECT_UNKNOWN = "UNKNOWN";
358
+ function classifyEffect(effect) {
359
+ if (effect === void 0) return "absent";
360
+ if (effect === EFFECT_READ_ONLY) return "read-only";
361
+ if (effect === EFFECT_WRITES) return "writes";
362
+ if (effect === EFFECT_UNKNOWN) return "declared-unknown";
363
+ return "unrecognized-effect";
364
+ }
365
+
366
+ // src/http/danger-env.ts
367
+ function assertDangerWrite(safety, operation) {
368
+ if (!safety?.danger || safety.allowDanger) return;
369
+ throw new CliError({
370
+ code: "INVALID_ARGUMENT" /* INVALID_ARGUMENT */,
371
+ message: `\u73AF\u5883 '${safety.name}' \u5728 env.yaml \u58F0\u660E\u4E86 danger: true\uFF1B${operation} \u4F1A\u5199\u5165\u6216\u5C1A\u672A\u8BC1\u660E\u53EA\u8BFB\uFF0C\u672A\u53D1\u9001\u8BE5\u8BF7\u6C42\u3002`,
372
+ context: { nextStep: "\u6838\u5BF9\u76EE\u6807\u73AF\u5883\u4E0E\u5F71\u54CD\u540E\uFF0C\u663E\u5F0F\u52A0 --allow-danger \u91CD\u8DD1\uFF1B\u6B64\u6807\u5FD7\u53EA\u786E\u8BA4\u672C\u6B21 danger \u73AF\u5883\u5199\u5165" }
373
+ });
374
+ }
375
+ function attachEnvironmentSafety(http, safety) {
376
+ if (!safety?.danger || safety.allowDanger) return;
377
+ http.interceptors.request.use(async (request) => {
378
+ const actual = new URL(http.getUri(request));
379
+ const base = new URL(request.baseURL);
380
+ let pathname = decodeURIComponent(actual.pathname).replace(/\/+$/, "");
381
+ const basePath = decodeURIComponent(base.pathname).replace(/\/+$/, "");
382
+ if (actual.origin === base.origin && basePath && pathname.startsWith(`${basePath}/`)) pathname = pathname.slice(basePath.length);
383
+ const method = (request.method ?? "GET").toUpperCase();
384
+ const action3 = pathname.match(/^\/api\/models\/([^/]+)\/(?:([^/]+)\/)?action\/([^/]+)$/);
385
+ if (action3) {
386
+ const model = decodeURIComponent(action3[1]);
387
+ const scope = action3[2] ? "object" : "class";
388
+ const name = decodeURIComponent(action3[3]);
389
+ let reason = `${method} ${pathname}`;
390
+ try {
391
+ const meta = await describe(http, model);
392
+ const candidates = meta.actions.filter((candidate) => candidate.name === name && (candidate.httpMethod ?? "POST").toUpperCase() === method && candidate.scope === scope);
393
+ if (candidates.length === 1) {
394
+ const candidate = candidates[0];
395
+ const effect = classifyEffect(candidate.effect);
396
+ if (effect === "read-only" || effect === "absent" && candidate.readOnly === true) return request;
397
+ reason += `\uFF08effect=${String(candidate.effect ?? "\u672A\u58F0\u660E")}\uFF09`;
398
+ } else reason += `\uFF08\u672A\u53D6\u5F97\u552F\u4E00\u5339\u914D\u7684\u526F\u4F5C\u7528\u58F0\u660E\uFF0C\u5339\u914D ${candidates.length} \u9879\uFF09`;
399
+ } catch (e) {
400
+ reason += `\uFF08\u8BFB\u53D6\u526F\u4F5C\u7528\u58F0\u660E\u5931\u8D25\uFF1A${e.message}\uFF09`;
401
+ }
402
+ assertDangerWrite(safety, reason);
403
+ return request;
404
+ }
405
+ if (["GET", "HEAD", "OPTIONS"].includes(method)) return request;
406
+ if (method === "POST" && (/^\/api\/models\/[^/]+\/list\/dsl$/.test(pathname) || ["/api/script/dry-run", "/api/script/manifest/validate"].includes(pathname) || ["/api/auth/refresh", "/api/auth/logout", "/api/oauth/token"].includes(pathname))) return request;
407
+ assertDangerWrite(safety, `${method} ${pathname}`);
408
+ return request;
409
+ });
410
+ }
411
+
60
412
  // src/package-version.ts
61
413
  import { readFileSync } from "fs";
62
414
  var manifest = JSON.parse(
@@ -68,9 +420,9 @@ var SDK_VERSION = manifest.version;
68
420
  var DEFAULT_HTTP_TIMEOUT_MS = 6e4;
69
421
  var HCM_LANG_ENV = "HCM_LANG";
70
422
  function toAcceptLanguage(language) {
71
- const text2 = (language ?? "").trim();
72
- if (!text2) return void 0;
73
- const [lang, region] = text2.replace("-", "_").split("_");
423
+ const text3 = (language ?? "").trim();
424
+ if (!text3) return void 0;
425
+ const [lang, region] = text3.replace("-", "_").split("_");
74
426
  return region ? `${lang.toLowerCase()}-${region.toUpperCase()}` : lang.toLowerCase();
75
427
  }
76
428
  function createHttpClient(opts) {
@@ -86,11 +438,12 @@ function createHttpClient(opts) {
86
438
  attachTrace(client);
87
439
  attachAuth(client, opts.getAccessToken);
88
440
  attachRetry(client, opts.onRefresh);
441
+ attachEnvironmentSafety(client, opts.environmentSafety);
89
442
  return client;
90
443
  }
91
444
 
92
445
  // src/auth/token-store.ts
93
- import * as fs2 from "fs/promises";
446
+ import * as fs5 from "fs/promises";
94
447
 
95
448
  // src/config/paths.ts
96
449
  import * as path from "path";
@@ -131,727 +484,749 @@ function envFile(name) {
131
484
  function identitiesDir() {
132
485
  return path.join(hcmConfigDir(), "identities");
133
486
  }
134
- function identityDir(name) {
135
- return path.join(identitiesDir(), name);
136
- }
137
- function identityMetaFile(name) {
138
- return path.join(identityDir(name), "credentials.json");
139
- }
140
- function archiveDir() {
141
- return path.join(hcmConfigDir(), "_archive");
142
- }
143
- var TEMP_ENV_NAME = "_current";
144
- function isTempEnv(name) {
145
- return name === TEMP_ENV_NAME;
146
- }
147
-
148
- // src/config/global-config.ts
149
- import * as fs from "fs/promises";
150
- import yaml from "js-yaml";
151
- var CREDENTIAL_STORE_MODES = ["auto", "file"];
152
- var DEFAULT_ENV = "default";
153
- var DEFAULT_DEFAULTS = {
154
- output: "table",
155
- timeout: "60s",
156
- credentialStore: "auto"
157
- };
158
- function resolveCredentialStoreMode(cfg, env2 = process.env) {
159
- const fromEnv = normalizeCredentialStoreMode(env2.HCM_CREDENTIAL_STORE, "HCM_CREDENTIAL_STORE");
160
- if (fromEnv) return fromEnv;
161
- const fromCfg = normalizeCredentialStoreMode(
162
- cfg?.defaults?.credentialStore,
163
- "config.yml defaults.credentialStore"
164
- );
165
- return fromCfg ?? "auto";
166
- }
167
- function normalizeCredentialStoreMode(raw, source) {
168
- if (raw !== void 0 && raw !== null && typeof raw !== "string") {
169
- process.stderr.write(
170
- `[hcm] WARNING: ${source} \u7684\u503C\u662F ${typeof raw}\uFF08${JSON.stringify(raw)}\uFF09\uFF0C\u5E94\u4E3A\u5B57\u7B26\u4E32\uFF08${CREDENTIAL_STORE_MODES.join(" / ")}\uFF09\uFF0C\u6309 auto \u5904\u7406\u3002
171
- `
172
- );
173
- return null;
174
- }
175
- const v = (raw ?? "").trim().toLowerCase();
176
- if (!v) return null;
177
- if (CREDENTIAL_STORE_MODES.includes(v)) return v;
178
- process.stderr.write(
179
- `[hcm] WARNING: ${source}='${raw}' \u4E0D\u662F\u53EF\u8BC6\u522B\u7684\u503C\uFF08${CREDENTIAL_STORE_MODES.join(" / ")}\uFF09\uFF0C\u6309 auto \u5904\u7406\u3002
180
- `
181
- );
182
- return null;
183
- }
184
- async function loadGlobalConfig() {
185
- let raw = {};
186
- try {
187
- const content = await fs.readFile(globalConfigFile(), "utf-8");
188
- raw = yaml.load(content) ?? {};
189
- } catch (e) {
190
- if (e.code !== "ENOENT") throw e;
191
- }
192
- const activeEnv = raw.activeEnv ?? raw.activeProfile ?? DEFAULT_ENV;
193
- return {
194
- activeEnv,
195
- activeProfile: activeEnv,
196
- // dual-write alias
197
- defaults: { ...DEFAULT_DEFAULTS, ...raw.defaults }
198
- };
199
- }
200
- async function saveGlobalConfig(cfg) {
201
- await fs.mkdir(hcmConfigDir(), { recursive: true });
202
- const activeEnv = cfg.activeEnv ?? cfg.activeProfile ?? DEFAULT_ENV;
203
- const out = {
204
- activeEnv,
205
- activeProfile: activeEnv,
206
- defaults: cfg.defaults
207
- };
208
- await fs.writeFile(globalConfigFile(), yaml.dump(out), "utf-8");
209
- }
210
- function resolveActiveEnv(args, env2, global) {
211
- return args.envFlag ?? env2.HCM_ENV ?? env2.HCM_PROFILE ?? global.activeEnv;
212
- }
213
- function resolveActiveProfile(args, env2, global) {
214
- return resolveActiveEnv({ envFlag: args.flag }, env2, global);
215
- }
216
-
217
- // src/auth/token-store.ts
218
- function isServerSlidingSession(scheme) {
219
- return scheme === "password" || scheme === "pairing";
220
- }
221
- var SERVICE_PREFIX = "hcm-cli";
222
- var TokenStore = class _TokenStore {
223
- constructor(profile) {
224
- this.profile = profile;
225
- }
226
- profile;
227
- /**
228
- * Factory: build an identity-scoped TokenStore. Stores meta at
229
- * `identities/<name>/credentials.json` and uses keychain account prefix
230
- * `identity-<name>` to isolate from legacy profile-scoped stores.
231
- *
232
- * Used by T13 login when writing identity meta and by T15 business
233
- * commands when reading the active identity's token.
234
- */
235
- static forIdentity(name) {
236
- const ts = new _TokenStore(name);
237
- Object.defineProperty(ts, "__identity", { value: true, writable: false, configurable: false });
238
- return ts;
239
- }
240
- get isIdentity() {
241
- return this.__identity === true;
242
- }
243
- metaFile() {
244
- return this.isIdentity ? identityMetaFile(this.profile) : credentialsFile(this.profile);
245
- }
246
- dataDir() {
247
- return this.isIdentity ? identityDir(this.profile) : profileDir(this.profile);
248
- }
249
- keychainAccountPrefix() {
250
- return this.isIdentity ? `identity-${this.profile}` : this.profile;
251
- }
252
- async writeMeta(record) {
253
- await fs2.mkdir(this.dataDir(), { recursive: true });
254
- await fs2.writeFile(this.metaFile(), JSON.stringify(record, null, 2), { mode: 384 });
255
- }
256
- async readMeta() {
257
- try {
258
- const raw = await fs2.readFile(this.metaFile(), "utf-8");
259
- return JSON.parse(raw);
260
- } catch (e) {
261
- if (e.code === "ENOENT") return null;
262
- throw e;
263
- }
264
- }
265
- async setAccessToken(token) {
266
- return this.storeToken("access", token);
267
- }
268
- async setRefreshToken(token) {
269
- return this.storeToken("refresh", token);
270
- }
271
- /**
272
- * 把一枚 token 存到能存的地方 —— 优先钥匙串,存不进就落 0600 文件。
273
- *
274
- * 🔴 **承重的那个操作自己就是探针**。原先的写法是「先 `getPassword` 探一下,
275
- * 不抛就当钥匙串可用,然后**不设防**地 `setPassword`」——
276
- * 那是**用读探针证写能力**,而这两件事在真机上会分家:
277
- * `HOME` 不指向本人家目录时(SSH 会话 / 容器 / `sudo` / 换 `HOME` 跑),
278
- * `getPassword` 返回 **`null` 而不抛**(「没找到」与「根本够不着」在这个 API 上同形),
279
- * 探针于是判「可用」,紧接着 `setPassword` 抛一个 keytar 未映射的 OSStatus,
280
- * 整条登录中止 —— 而那时**一次性配对码已经消费掉了**,屏幕上只有一句
281
- * `An unknown error occurred.`(那句话来自 keytar 原生模块,不是本 CLI 的文案,
282
- * 所以连错误码和 traceId 都没有)。issue #79。
283
- *
284
- * ⇒ 不再有单独的探针,也就不再有「探针探 A、承重靠 B」那道缝:
285
- * 直接写,抛了就落回文件。下面那条兜底原本**永远够不到**,现在够得到了。
286
- */
287
- async storeToken(kind, token) {
288
- const mode = resolveCredentialStoreMode(await loadGlobalConfig().catch(() => null));
289
- if (mode === "file") return this.writeTokenFile(kind, token, void 0, mode);
290
- const keytar = await loadKeytar();
291
- if (!keytar) return this.writeTokenFile(kind, token, void 0, mode);
292
- const account = `${this.keychainAccountPrefix()}/${kind}`;
293
- try {
294
- await keytar.setPassword(SERVICE_PREFIX, account, token);
295
- } catch (e) {
296
- return this.writeTokenFile(kind, token, e, mode);
297
- }
298
- return `keychain:${SERVICE_PREFIX}/${account}`;
299
- }
300
- async getAccessToken() {
301
- if (process.env.HCM_PAT) return process.env.HCM_PAT;
302
- if (process.env.HCM_ACCESS_TOKEN) return process.env.HCM_ACCESS_TOKEN;
303
- return this.getStoredAccessToken();
304
- }
305
- /**
306
- * 只读取这一个 store 持久化的 token,不接受 HCM_PAT/HCM_ACCESS_TOKEN 覆盖。
307
- *
308
- * `identity show <alias>` 要回答的是「这个 alias 到底是谁」;若沿用普通命令的环境变量
309
- * 优先级,机器上临时设置的一枚 token 会让所有 alias 都显示成同一个人,正向角色验收
310
- * 反而得到一份可信外观的错误证据。普通业务命令仍走 {@link getAccessToken},行为不变。
311
- */
312
- async getStoredAccessToken() {
313
- const meta = await this.readMeta();
314
- if (!meta?.accessTokenRef) return null;
315
- return this.resolveRef(meta.accessTokenRef);
487
+ function identityDir(name) {
488
+ return path.join(identitiesDir(), name);
489
+ }
490
+ function identityMetaFile(name) {
491
+ return path.join(identityDir(name), "credentials.json");
492
+ }
493
+ function archiveDir() {
494
+ return path.join(hcmConfigDir(), "_archive");
495
+ }
496
+ var TEMP_ENV_NAME = "_current";
497
+ function isTempEnv(name) {
498
+ return name === TEMP_ENV_NAME;
499
+ }
500
+
501
+ // src/config/global-config.ts
502
+ import * as fs4 from "fs/promises";
503
+ import yaml3 from "js-yaml";
504
+
505
+ // src/config/project-env.ts
506
+ import * as fs3 from "fs/promises";
507
+ import path2 from "path";
508
+ import yaml2 from "js-yaml";
509
+
510
+ // src/config/env.ts
511
+ import * as fs from "fs/promises";
512
+ import yaml from "js-yaml";
513
+ function assertNotReservedEnvName(name) {
514
+ if (isTempEnv(name)) {
515
+ throw new CliError({
516
+ code: "INVALID_ARGUMENT" /* INVALID_ARGUMENT */,
517
+ message: `'${TEMP_ENV_NAME}' \u662F\u4E34\u65F6\u73AF\u5883\u7684\u4FDD\u7559\u540D\uFF0C\u4E0D\u80FD\u7528\u4F5C env \u540D\u5B57\u3002`,
518
+ context: {
519
+ nextStep: `\u6362\u4E2A\u540D\u5B57\uFF1B\u5982\u679C\u4F60\u662F\u60F3\u628A\u5F53\u524D\u4E34\u65F6\u73AF\u5883\u5B58\u4E0B\u6765\uFF0C\u7528: hcm env save <name>`
520
+ }
521
+ });
316
522
  }
317
- async getRefreshToken() {
318
- const meta = await this.readMeta();
319
- if (!meta?.refreshTokenRef) return null;
320
- return this.resolveRef(meta.refreshTokenRef);
523
+ }
524
+ async function saveEnv(name, cfg) {
525
+ if (!cfg.endpoint) {
526
+ throw new CliError({
527
+ code: "ENV_ENDPOINT_REQUIRED" /* ENV_ENDPOINT_REQUIRED */,
528
+ message: `env '${name}' requires endpoint`
529
+ });
321
530
  }
322
- async clear() {
323
- const meta = await this.readMeta();
324
- if (!meta) return;
325
- if (meta.accessTokenRef?.startsWith("keychain:")) {
326
- const account = meta.accessTokenRef.slice("keychain:".length).split("/").slice(1).join("/");
327
- const keytar = await loadKeytar();
328
- if (keytar) await keytar.deletePassword(SERVICE_PREFIX, account);
329
- } else if (meta.accessTokenRef?.startsWith("file:")) {
330
- await fs2.rm(meta.accessTokenRef.slice("file:".length), { force: true });
331
- }
332
- if (meta.refreshTokenRef?.startsWith("keychain:")) {
333
- const account = meta.refreshTokenRef.slice("keychain:".length).split("/").slice(1).join("/");
334
- const keytar = await loadKeytar();
335
- if (keytar) await keytar.deletePassword(SERVICE_PREFIX, account);
336
- } else if (meta.refreshTokenRef?.startsWith("file:")) {
337
- await fs2.rm(meta.refreshTokenRef.slice("file:".length), { force: true });
338
- }
339
- if (!this.isIdentity) {
340
- await fs2.rm(this.metaFile(), { force: true });
531
+ await fs.mkdir(envDir(name), { recursive: true });
532
+ await fs.writeFile(envFile(name), yaml.dump(cfg), "utf-8");
533
+ }
534
+ async function loadEnv(name) {
535
+ try {
536
+ const content = await fs.readFile(envFile(name), "utf-8");
537
+ return yaml.load(content);
538
+ } catch (e) {
539
+ if (e.code === "ENOENT") {
540
+ throw new CliError({
541
+ code: "ENV_NOT_FOUND" /* ENV_NOT_FOUND */,
542
+ message: `env '${name}' not found. Run: hcm env list`
543
+ });
341
544
  }
545
+ throw e;
342
546
  }
343
- async resolveRef(ref) {
344
- if (ref.startsWith("keychain:")) {
345
- const account = ref.slice("keychain:".length).split("/").slice(1).join("/");
346
- const keytar = await loadKeytar();
347
- if (!keytar) return null;
348
- return keytar.getPassword(SERVICE_PREFIX, account);
349
- }
350
- if (ref.startsWith("file:")) {
547
+ }
548
+ async function listEnvs() {
549
+ try {
550
+ const entries = await fs.readdir(envsDir(), { withFileTypes: true });
551
+ const result = [];
552
+ for (const e of entries) {
553
+ if (!e.isDirectory()) continue;
351
554
  try {
352
- return await fs2.readFile(ref.slice("file:".length), "utf-8");
353
- } catch (e) {
354
- if (e.code === "ENOENT") return null;
355
- throw e;
555
+ await fs.access(envFile(e.name));
556
+ result.push(e.name);
557
+ } catch {
356
558
  }
357
559
  }
358
- if (ref.startsWith("plain:")) return ref.slice("plain:".length);
359
- return null;
360
- }
361
- /**
362
- * 兜底:0600 文件。
363
- *
364
- * 🔴 `cause` 分开两档措辞,**不许合并**:「这台机器上没有 keytar」是常态
365
- * (Linux 无 libsecret 等),「有 keytar 但写不进去」是异常,顾问的下一步不同 ——
366
- * 后者必须把原始报错**原样转述**出来,否则他看到的还是一句没有出处的话。
367
- */
368
- async writeTokenFile(kind, token, cause, mode = "auto") {
369
- const file = `${this.metaFile()}.${kind}`;
370
- await fs2.mkdir(this.dataDir(), { recursive: true, mode: 448 });
371
- await fs2.writeFile(file, token, { mode: 384 });
372
- await fs2.chmod(file, 384);
373
- if (kind === "access" && mode !== "file") {
374
- const why = cause === void 0 ? "OS keychain unavailable" : `OS keychain refused the write (${cause instanceof Error ? cause.message : String(cause)})`;
375
- console.warn(`[hcm] WARNING: ${why}. Token saved to ${file} (0600).`);
376
- }
377
- return `file:${file}`;
560
+ return result;
561
+ } catch (e) {
562
+ if (e.code === "ENOENT") return [];
563
+ throw e;
378
564
  }
379
- };
380
- async function loadKeytar() {
565
+ }
566
+ async function deleteEnv(name) {
381
567
  try {
382
- const mod = await import("keytar");
383
- return mod.default ?? mod;
568
+ await fs.access(envFile(name));
384
569
  } catch {
385
- return null;
570
+ throw new CliError({
571
+ code: "ENV_NOT_FOUND" /* ENV_NOT_FOUND */,
572
+ message: `env '${name}' not found`
573
+ });
386
574
  }
575
+ await fs.rm(envDir(name), { recursive: true, force: true });
387
576
  }
388
577
 
389
- // src/auth/principal.ts
390
- function toPrincipal(raw) {
391
- if (!raw || typeof raw !== "object") return void 0;
392
- const o = raw;
393
- const principal = {};
394
- const rawUserId = o.userId ?? o.id;
395
- if (rawUserId !== void 0 && rawUserId !== null) principal.userId = String(rawUserId);
396
- if (o.tenantId !== void 0 && o.tenantId !== null) principal.tenantId = String(o.tenantId);
397
- if (typeof o.username === "string" && o.username) principal.username = o.username;
398
- if (Array.isArray(o.roles)) principal.roles = o.roles.map(String);
399
- return Object.keys(principal).length > 0 ? principal : void 0;
578
+ // src/config/identity.ts
579
+ import * as fs2 from "fs/promises";
580
+ async function assertEnvExists(env2) {
581
+ try {
582
+ await fs2.access(envFile(env2));
583
+ } catch {
584
+ throw new CliError({
585
+ code: "IDENTITY_NOT_IN_ENV" /* IDENTITY_NOT_IN_ENV */,
586
+ message: `env '${env2}' does not exist. Run: hcm env add ${env2} --endpoint <url>`
587
+ });
588
+ }
400
589
  }
401
- function describePrincipal(principal) {
402
- if (!principal) return "server-identity=<\u672A\u56DE\u8EAB\u4EFD>";
403
- const parts = [];
404
- parts.push(`tenant=${principal.tenantId ?? "<\u672A\u56DE>"}`);
405
- parts.push(`user=${principal.username ?? "<\u672A\u56DE>"}`);
406
- if (principal.roles?.length) parts.push(`roles=${principal.roles.join(",")}`);
407
- return parts.join(" ");
590
+ async function saveIdentity(name, meta) {
591
+ await assertEnvExists(meta.env);
592
+ await fs2.mkdir(identityDir(name), { recursive: true });
593
+ await fs2.writeFile(identityMetaFile(name), JSON.stringify(meta, null, 2), { mode: 384 });
408
594
  }
409
-
410
- // src/auth/password.ts
411
- var DEFAULT_SESSION_TTL_SECONDS = 24 * 60 * 60;
412
- async function loginPassword(input) {
413
- const resp = await input.httpClient.post(
414
- `${input.endpoint}/api/auth/login`,
415
- {
416
- tenantId: input.tenantId,
417
- username: input.username,
418
- password: input.password
419
- },
420
- { headers: { "Content-Type": "application/json" } }
421
- );
422
- const { token, expiresIn, user } = resp.data;
423
- if (!token) {
424
- throw new Error("Login response missing token");
595
+ async function loadIdentity(name) {
596
+ try {
597
+ const raw = await fs2.readFile(identityMetaFile(name), "utf-8");
598
+ return JSON.parse(raw);
599
+ } catch (e) {
600
+ if (e.code === "ENOENT") {
601
+ throw new CliError({
602
+ code: "IDENTITY_NOT_FOUND" /* IDENTITY_NOT_FOUND */,
603
+ message: `identity '${name}' not found. Run: hcm identity list`
604
+ });
605
+ }
606
+ throw e;
425
607
  }
426
- const ttlSeconds = expiresIn ?? DEFAULT_SESSION_TTL_SECONDS;
427
- const expiresAt = new Date(Date.now() + ttlSeconds * 1e3).toISOString();
428
- const store = new TokenStore(input.profile);
429
- const accessTokenRef = await store.setAccessToken(token);
430
- const record = {
431
- scheme: "password",
432
- accessTokenRef,
433
- // 口令会话**没有** refresh token —— 后端 `/api/auth/login` 只回 token。
434
- // 它的续期语义是「同一个 token 被服务端重设 TTL」,见 refresh.ts。
435
- refreshTokenRef: void 0,
436
- expiresAt,
437
- scopes: ["*"],
438
- ttlSeconds
439
- };
440
- await store.writeMeta(record);
441
- return { record, principal: toPrincipal(user) };
442
608
  }
443
-
444
- // src/auth/refresh.ts
445
- var PROACTIVE_REFRESH_MARGIN_SECONDS = 60 * 60;
446
- async function refreshToken(input) {
447
- if (!input.identity && !input.profile) {
448
- throw new Error("refreshToken: either identity or profile required");
449
- }
450
- const store = input.identity ? TokenStore.forIdentity(input.identity) : new TokenStore(input.profile);
451
- const meta = await store.readMeta();
452
- if (!meta) throw new Error("no credentials to refresh");
453
- switch (meta.scheme) {
454
- case "pat":
455
- throw new Error("PAT cannot be refreshed; re-run `hcm login --pat-stdin`");
456
- case "client_credentials":
457
- throw new Error(
458
- "client_credentials \u4F1A\u8BDD\u65E0\u6CD5\u81EA\u52A8\u7EED\u671F\uFF1A\u5237\u65B0\u9700\u8981 client_secret\uFF0C\u800C CLI \u4E0D\u4FDD\u5B58\u5B83\u3002\u91CD\u65B0\u6267\u884C `hcm login --client-id <id>`"
459
- );
460
- case "password":
461
- case "pairing":
462
- return slidePasswordSession(store, meta, input);
463
- default: {
464
- const unknown = meta.scheme;
465
- throw new Error(`unknown auth scheme in stored credentials: ${String(unknown)}`);
609
+ async function listIdentities(env2) {
610
+ try {
611
+ const entries = await fs2.readdir(identitiesDir(), { withFileTypes: true });
612
+ const result = [];
613
+ for (const e of entries) {
614
+ if (!e.isDirectory()) continue;
615
+ try {
616
+ const meta = await loadIdentity(e.name);
617
+ if (!env2 || meta.env === env2) result.push(e.name);
618
+ } catch {
619
+ }
466
620
  }
621
+ return result;
622
+ } catch (e) {
623
+ if (e.code === "ENOENT") return [];
624
+ throw e;
467
625
  }
468
626
  }
469
- async function slidePasswordSession(store, meta, input) {
470
- const accessToken = await store.getAccessToken();
471
- if (!accessToken) {
472
- throw new Error("no access token to refresh; re-run `hcm login`");
627
+ async function deleteIdentity(name) {
628
+ try {
629
+ await fs2.access(identityMetaFile(name));
630
+ } catch {
631
+ throw new CliError({
632
+ code: "IDENTITY_NOT_FOUND" /* IDENTITY_NOT_FOUND */,
633
+ message: `identity '${name}' not found`
634
+ });
473
635
  }
474
- await input.httpClient.post(`${input.endpoint}/api/auth/refresh`, void 0, {
475
- headers: { Authorization: `Bearer ${accessToken}` },
476
- // 见上:阻断 401 → onRefresh → 本函数 → 401 的递归。
477
- __skipAuthRetry: true
478
- });
479
- const ttlSeconds = meta.ttlSeconds ?? DEFAULT_SESSION_TTL_SECONDS;
480
- const record = {
481
- ...meta,
482
- // token 本身没变,accessTokenRef / scopes 原样保留。
483
- expiresAt: new Date(Date.now() + ttlSeconds * 1e3).toISOString(),
484
- ttlSeconds
485
- };
486
- await store.writeMeta(record);
487
- return record;
636
+ await fs2.rm(identityDir(name), { recursive: true, force: true });
488
637
  }
489
- function needsRefresh(meta, marginSec = 60) {
490
- const expiresAtMs = new Date(meta.expiresAt).getTime();
491
- return Date.now() + marginSec * 1e3 > expiresAtMs;
638
+ async function renameIdentity(oldName, newName) {
639
+ if (oldName === newName) return;
640
+ const meta = await loadIdentity(oldName);
641
+ const clash = await loadIdentity(newName).catch(() => null);
642
+ if (clash) {
643
+ throw new CliError({
644
+ code: "IDENTITY_ALREADY_EXISTS" /* IDENTITY_ALREADY_EXISTS */,
645
+ message: `identity '${newName}' \u5DF2\u5B58\u5728\uFF0C\u4E0D\u80FD\u628A '${oldName}' \u6539\u6210\u8FD9\u4E2A\u540D\u5B57\u3002`
646
+ });
647
+ }
648
+ await fs2.rename(identityDir(oldName), identityDir(newName));
649
+ const rebase = (ref, kind) => {
650
+ if (!ref?.startsWith("file:")) return ref;
651
+ return `file:${identityMetaFile(newName)}.${kind}`;
652
+ };
653
+ await saveIdentity(newName, {
654
+ ...meta,
655
+ accessTokenRef: rebase(meta.accessTokenRef, "access"),
656
+ refreshTokenRef: rebase(meta.refreshTokenRef, "refresh")
657
+ });
492
658
  }
493
- async function ensureSessionFresh(input) {
659
+
660
+ // src/config/project-env.ts
661
+ var ENV_FILE = "env.yaml";
662
+ function normalizeOrigin(url) {
663
+ const raw = url.trim().replace(/\/+$/, "");
494
664
  try {
495
- const store = input.identity ? TokenStore.forIdentity(input.identity) : new TokenStore(input.profile);
496
- const meta = await store.readMeta();
497
- if (!meta || !isServerSlidingSession(meta.scheme)) return false;
498
- if (!needsRefresh(meta, PROACTIVE_REFRESH_MARGIN_SECONDS)) return false;
499
- await refreshToken(input);
500
- return true;
665
+ const parsed = new URL(raw);
666
+ if (parsed.protocol === "http:" || parsed.protocol === "https:") {
667
+ parsed.hash = "";
668
+ return parsed.toString().replace(/\/+$/, "");
669
+ }
501
670
  } catch {
502
- return false;
503
671
  }
672
+ return raw;
504
673
  }
505
-
506
- // src/config/profile.ts
507
- import * as fs3 from "fs/promises";
508
- import * as path2 from "path";
509
- import yaml2 from "js-yaml";
510
- async function loadProfile(profile) {
511
- const file = profileFile(profile);
512
- let content;
674
+ function invalid(message) {
675
+ throw new CliError({ code: "CONFIG_PARSE_ERROR" /* CONFIG_PARSE_ERROR */, message: `${ENV_FILE} ${message}` });
676
+ }
677
+ function object(value, label) {
678
+ if (!value || typeof value !== "object" || Array.isArray(value)) invalid(`${label} \u5FC5\u987B\u662F\u6620\u5C04`);
679
+ return value;
680
+ }
681
+ function string(value, label) {
682
+ if (typeof value !== "string" || !value.trim()) invalid(`\u7F3A\u5C11 ${label}\uFF0C\u6216\u8BE5\u5B57\u6BB5\u4E0D\u662F\u975E\u7A7A\u5B57\u7B26\u4E32`);
683
+ return value.trim();
684
+ }
685
+ function parseEnvironment(raw, label) {
686
+ const value = object(raw, label);
687
+ for (const key of Object.keys(value)) {
688
+ if (!["endpoint", "frontend", "tenant", "danger", "roles"].includes(key)) invalid(`${label} \u4E0D\u652F\u6301\u5B57\u6BB5 ${key}`);
689
+ }
690
+ const endpoint = normalizeOrigin(string(value.endpoint, `${label}endpoint`));
691
+ const frontend = normalizeOrigin(string(value.frontend, `${label}frontend`));
692
+ const tenant = typeof value.tenant === "number" && Number.isSafeInteger(value.tenant) ? String(value.tenant) : string(value.tenant, `${label}tenant`);
693
+ if (value.danger !== void 0 && typeof value.danger !== "boolean") invalid(`${label}danger \u5FC5\u987B\u662F true \u6216 false`);
694
+ let roles;
695
+ if (value.roles !== void 0) {
696
+ roles = Object.fromEntries(Object.entries(object(value.roles, `${label}roles`)).map(([name, username]) => [
697
+ string(name, `${label}roles \u540D\u79F0`),
698
+ string(username, `${label}roles.${name}`)
699
+ ]));
700
+ }
701
+ return { endpoint, frontend, tenant, ...value.danger !== void 0 ? { danger: value.danger } : {}, ...roles ? { roles } : {} };
702
+ }
703
+ function parseEnvYaml(text3) {
704
+ let raw;
513
705
  try {
514
- content = await fs3.readFile(file, "utf-8");
706
+ raw = yaml2.load(text3);
515
707
  } catch (e) {
516
- if (e.code === "ENOENT") {
517
- throw new Error(`profile '${profile}' not found at ${file}`);
708
+ invalid(`\u89E3\u6790\u5931\u8D25\uFF1A${e.message}`);
709
+ }
710
+ const value = object(raw, "\u6839\u8282\u70B9");
711
+ if ("endpoint" in value || "frontend" in value || "tenant" in value) {
712
+ return { default: "default", environments: { default: parseEnvironment(value, "") } };
713
+ }
714
+ for (const key of Object.keys(value)) if (!["default", "environments"].includes(key)) invalid(`\u4E0D\u652F\u6301\u5B57\u6BB5 ${key}`);
715
+ const defaultName = string(value.default, "default");
716
+ const entries = Object.entries(object(value.environments, "environments"));
717
+ const environments = Object.fromEntries(entries.map(([name, env2]) => [
718
+ string(name, "\u73AF\u5883\u540D"),
719
+ parseEnvironment(env2, `environments.${name}.`)
720
+ ]));
721
+ if (!Object.hasOwn(environments, defaultName)) invalid(`default '${defaultName}' \u4E0D\u5728 environments \u4E2D`);
722
+ return { default: defaultName, environments };
723
+ }
724
+ function renderEnvYaml(env2) {
725
+ const document = "environments" in env2 ? env2 : { default: "default", environments: { default: env2 } };
726
+ return "# \u9879\u76EE\u73AF\u5883\uFF08\u968F\u4ED3\u5E93\u63D0\u4EA4\uFF1B\u4E0D\u653E\u51ED\u636E\uFF0Croles \u53EA\u767B\u8BB0\u7528\u6237\u540D\uFF09\n# \u767B\u5F55\uFF1Ahcm login --env <\u9879\u76EE\u73AF\u5883\u540D> \u6838\u5BF9\uFF1Ahcm chiron doctor\n" + yaml2.dump(document, { noRefs: true, lineWidth: -1 });
727
+ }
728
+ async function discoverProjectEnv(cwd = process.cwd()) {
729
+ let directory = path2.resolve(cwd);
730
+ for (; ; ) {
731
+ const file = path2.join(directory, ENV_FILE);
732
+ try {
733
+ const text3 = await fs3.readFile(file, "utf8");
734
+ try {
735
+ return { path: file, config: parseEnvYaml(text3) };
736
+ } catch (e) {
737
+ throw new CliError({ code: "CONFIG_PARSE_ERROR" /* CONFIG_PARSE_ERROR */, message: `${file}\uFF1A${e.message}` });
738
+ }
739
+ } catch (e) {
740
+ if (e.code !== "ENOENT") throw e;
518
741
  }
519
- throw e;
742
+ const parent = path2.dirname(directory);
743
+ if (parent === directory) return null;
744
+ directory = parent;
520
745
  }
521
- return yaml2.load(content);
522
746
  }
523
- async function saveProfile(profile, cfg) {
524
- await fs3.mkdir(profileDir(profile), { recursive: true });
525
- await fs3.writeFile(profileFile(profile), yaml2.dump(cfg), "utf-8");
747
+ function requestedEnv(args, env2) {
748
+ if (args.envFlag !== void 0) return { name: args.envFlag, source: "--env" };
749
+ if (env2.HCM_ENV !== void 0) return { name: env2.HCM_ENV, source: "$HCM_ENV" };
750
+ if (env2.HCM_PROFILE !== void 0) return { name: env2.HCM_PROFILE, source: "$HCM_PROFILE" };
751
+ return null;
526
752
  }
527
- async function listProfiles() {
528
- const root = hcmConfigDir();
753
+ function projectSelection(project, requested) {
754
+ if (!project) return null;
755
+ const name = requested?.name ?? project.config.default;
756
+ if (!Object.hasOwn(project.config.environments, name)) return null;
757
+ return { path: project.path, name, environment: project.config.environments[name], source: requested?.source ?? "env.yaml" };
758
+ }
759
+ async function resolveProjectEnvironment(args = {}, env2 = process.env) {
760
+ return projectSelection(await discoverProjectEnv(args.cwd), requestedEnv(args, env2));
761
+ }
762
+ async function findEnvByEndpoint(endpoint, tenant, opts = {}) {
763
+ const wanted = normalizeOrigin(endpoint);
764
+ const matches = [];
765
+ for (const name of await listEnvs()) {
766
+ const config = await loadEnv(name);
767
+ if (normalizeOrigin(config.endpoint) !== wanted) continue;
768
+ if (opts.strictTenant && tenant !== void 0 && config.tenantId !== tenant) continue;
769
+ matches.push({ name, config, hasIdentity: (await listIdentities(name)).length > 0 });
770
+ }
771
+ if (!matches.length) return null;
772
+ const active = opts.activeEnv ?? (await loadGlobalConfig()).activeEnv;
773
+ const usable = matches.filter((match) => match.hasIdentity);
774
+ const pick = usable.find((match) => match.name === active) ?? (tenant ? usable.find((match) => (match.config.tenantId ?? "1") === tenant) : void 0) ?? usable[0] ?? matches.find((match) => match.name === active) ?? matches[0];
775
+ return { name: pick.name, config: pick.config };
776
+ }
777
+ async function resolveEnvContext(args, env2, global) {
778
+ const project = await discoverProjectEnv(args.cwd);
779
+ const requested = requestedEnv(args, env2);
780
+ const selected = projectSelection(project, requested);
781
+ if (selected) {
782
+ const found = await findEnvByEndpoint(selected.environment.endpoint, selected.environment.tenant, { strictTenant: true, activeEnv: global.activeEnv });
783
+ if (!found) throw new CliError({
784
+ code: "ENV_NOT_FOUND" /* ENV_NOT_FOUND */,
785
+ message: `${selected.path} \u7684\u73AF\u5883 '${selected.name}'\uFF08${selected.environment.endpoint} \xB7 \u79DF\u6237 ${selected.environment.tenant}\uFF09\u6CA1\u6709\u5339\u914D\u7684\u672C\u673A\u69FD\uFF1B\u4E0D\u4F1A\u56DE\u843D\u5230 activeEnv '${global.activeEnv}'\u3002`,
786
+ context: { nextStep: `hcm login --env ${selected.name}\uFF1B\u6216 hcm env add <\u672C\u673A\u69FD\u540D> --endpoint ${selected.environment.endpoint} --tenant ${selected.environment.tenant}` }
787
+ });
788
+ return { ...found, source: selected.source, project: selected, danger: selected.environment.danger === true };
789
+ }
790
+ const name = requested?.name ?? args.fallbackEnv ?? global.activeEnv;
791
+ const source = requested?.source ?? (args.fallbackEnv ? "workspace" : "activeEnv");
792
+ let config;
529
793
  try {
530
- const entries = await fs3.readdir(root, { withFileTypes: true });
531
- const result = [];
532
- for (const e of entries) {
533
- if (e.isDirectory()) {
534
- try {
535
- await fs3.access(path2.join(root, e.name, "profile.yml"));
536
- result.push(e.name);
537
- } catch {
538
- }
539
- }
540
- }
541
- return result;
794
+ config = await loadEnv(name);
542
795
  } catch (e) {
543
- if (e.code === "ENOENT") return [];
544
- throw e;
796
+ if (!(e instanceof CliError) || e.code !== "ENV_NOT_FOUND" /* ENV_NOT_FOUND */) throw e;
797
+ if (!requested && !args.fallbackEnv && !project) throw new CliError({
798
+ code: "NO_ACTIVE_ENV" /* NO_ACTIVE_ENV */,
799
+ message: "no env configured. Run: hcm env add <name> --endpoint <url> && hcm login --env <name>"
800
+ });
801
+ throw new CliError({
802
+ code: "ENV_NOT_FOUND" /* ENV_NOT_FOUND */,
803
+ message: `\u73AF\u5883 '${name}' \u672A\u627E\u5230\uFF1A\u5DF2\u67E5${project ? ` ${project.path} \u7684\u9879\u76EE\u73AF\u5883\uFF08${Object.keys(project.config.environments).join(", ")}\uFF09` : " cwd \u5411\u4E0A\uFF08\u6CA1\u6709 env.yaml\uFF09"}\uFF0C\u4EE5\u53CA\u672C\u673A\u69FD '${name}'\u3002`,
804
+ context: { nextStep: "\u6838\u5BF9 env.yaml \u4E2D\u7684\u73AF\u5883\u540D\uFF0C\u6216\u8FD0\u884C hcm env list \u67E5\u770B\u672C\u673A\u69FD" }
805
+ });
806
+ }
807
+ const matching = project ? Object.entries(project.config.environments).filter(([, candidate]) => candidate.endpoint === normalizeOrigin(config.endpoint) && candidate.tenant === config.tenantId) : [];
808
+ if (matching.length > 1) {
809
+ const signatures = new Set(matching.map(([, candidate]) => JSON.stringify({
810
+ danger: candidate.danger === true,
811
+ roles: Object.entries(candidate.roles ?? {}).sort(([a], [b]) => a.localeCompare(b))
812
+ })));
813
+ if (signatures.size > 1) throw new CliError({
814
+ code: "INVALID_ARGUMENT" /* INVALID_ARGUMENT */,
815
+ message: `\u672C\u673A\u69FD '${name}' \u540C\u65F6\u5339\u914D ${matching.map(([alias]) => alias).join(", ")}\uFF0C\u4F46 roles / danger \u58F0\u660E\u4E0D\u540C\uFF1B\u8BF7\u7528 --env <\u9879\u76EE\u73AF\u5883\u540D> \u660E\u786E\u9009\u62E9\u3002`
816
+ });
545
817
  }
818
+ const [match] = matching;
819
+ const bound = match && project ? { path: project.path, name: match[0], environment: match[1], source } : void 0;
820
+ return { name, config, source, ...bound ? { project: bound, danger: bound.environment.danger === true } : {} };
821
+ }
822
+ function printResolvedEnvironment(context, identity, tenantId) {
823
+ const file = context.project?.path;
824
+ const relative3 = file ? path2.relative(process.cwd(), file) : void 0;
825
+ const source = context.source === "env.yaml" && relative3 ? relative3.startsWith(".") ? relative3 : `./${relative3}` : `${context.source}${relative3 ? ` \u2192 ${relative3.startsWith(".") ? relative3 : `./${relative3}`}` : ""}`;
826
+ process.stderr.write(`\u2192 ${context.project?.name ?? context.name}${context.project ? `\uFF08\u672C\u673A\u69FD ${context.name}\uFF09` : ""} \xB7 ${context.config.endpoint} \xB7 \u79DF\u6237 ${tenantId ?? context.project?.environment.tenant ?? context.config.tenantId ?? "\u672A\u6307\u5B9A"} \xB7 \u8EAB\u4EFD ${identity ?? "\u672A\u8BA4\u8BC1"}${context.danger ? " \xB7 danger" : ""}\uFF08\u6765\u81EA ${source}\uFF09
827
+ `);
546
828
  }
547
829
 
548
- // src/config/env.ts
549
- import * as fs4 from "fs/promises";
550
- import yaml3 from "js-yaml";
551
-
552
- // src/errors/codes.ts
553
- var ExitCode = /* @__PURE__ */ ((ExitCode2) => {
554
- ExitCode2[ExitCode2["SUCCESS"] = 0] = "SUCCESS";
555
- ExitCode2[ExitCode2["USAGE_ERROR"] = 1] = "USAGE_ERROR";
556
- ExitCode2[ExitCode2["AUTH_ERROR"] = 2] = "AUTH_ERROR";
557
- ExitCode2[ExitCode2["BUSINESS_ERROR"] = 3] = "BUSINESS_ERROR";
558
- ExitCode2[ExitCode2["NETWORK_ERROR"] = 4] = "NETWORK_ERROR";
559
- ExitCode2[ExitCode2["CONFIG_ERROR"] = 5] = "CONFIG_ERROR";
560
- ExitCode2[ExitCode2["SIGINT"] = 130] = "SIGINT";
561
- return ExitCode2;
562
- })(ExitCode || {});
563
- var CliErrorCode = /* @__PURE__ */ ((CliErrorCode2) => {
564
- CliErrorCode2["INVALID_ARGUMENT"] = "INVALID_ARGUMENT";
565
- CliErrorCode2["INVALID_JSON"] = "INVALID_JSON";
566
- CliErrorCode2["MISSING_FLAG"] = "MISSING_FLAG";
567
- CliErrorCode2["AUTH_FAILED"] = "AUTH_FAILED";
568
- CliErrorCode2["AUTH_EXPIRED"] = "AUTH_EXPIRED";
569
- CliErrorCode2["AUTH_REFRESH_FAILED"] = "AUTH_REFRESH_FAILED";
570
- CliErrorCode2["WS_AUTH_ERROR"] = "WS_AUTH_ERROR";
571
- CliErrorCode2["SCOPE_FORBIDDEN"] = "SCOPE_FORBIDDEN";
572
- CliErrorCode2["BUSINESS_RULE_VIOLATION"] = "BUSINESS_RULE_VIOLATION";
573
- CliErrorCode2["MODEL_NOT_FOUND"] = "MODEL_NOT_FOUND";
574
- CliErrorCode2["ACTION_NOT_FOUND"] = "ACTION_NOT_FOUND";
575
- CliErrorCode2["AGENT_NOT_FOUND"] = "AGENT_NOT_FOUND";
576
- CliErrorCode2["TOOL_TIMEOUT"] = "TOOL_TIMEOUT";
577
- CliErrorCode2["NETWORK_ERROR"] = "NETWORK_ERROR";
578
- CliErrorCode2["TIMEOUT"] = "TIMEOUT";
579
- CliErrorCode2["SERVER_ERROR"] = "SERVER_ERROR";
580
- CliErrorCode2["PROTOCOL_UNSUPPORTED"] = "PROTOCOL_UNSUPPORTED";
581
- CliErrorCode2["PROFILE_NOT_FOUND"] = "PROFILE_NOT_FOUND";
582
- CliErrorCode2["CONFIG_PARSE_ERROR"] = "CONFIG_PARSE_ERROR";
583
- CliErrorCode2["KEYCHAIN_UNAVAILABLE"] = "KEYCHAIN_UNAVAILABLE";
584
- CliErrorCode2["ENV_NOT_FOUND"] = "ENV_NOT_FOUND";
585
- CliErrorCode2["ENV_ALREADY_EXISTS"] = "ENV_ALREADY_EXISTS";
586
- CliErrorCode2["ENV_ENDPOINT_REQUIRED"] = "ENV_ENDPOINT_REQUIRED";
587
- CliErrorCode2["IDENTITY_NOT_FOUND"] = "IDENTITY_NOT_FOUND";
588
- CliErrorCode2["IDENTITY_ALREADY_EXISTS"] = "IDENTITY_ALREADY_EXISTS";
589
- CliErrorCode2["IDENTITY_NOT_IN_ENV"] = "IDENTITY_NOT_IN_ENV";
590
- CliErrorCode2["TOKEN_EXPIRED"] = "TOKEN_EXPIRED";
591
- CliErrorCode2["NO_ACTIVE_ENV"] = "NO_ACTIVE_ENV";
592
- CliErrorCode2["SKILL_ID_CONFLICT"] = "SKILL_ID_CONFLICT";
593
- CliErrorCode2["SKILL_SOURCE_UNREACHABLE"] = "SKILL_SOURCE_UNREACHABLE";
594
- CliErrorCode2["SYNC_SOURCE_UNSUPPORTED"] = "SYNC_SOURCE_UNSUPPORTED";
595
- return CliErrorCode2;
596
- })(CliErrorCode || {});
597
- var CODE_TO_EXIT = {
598
- ["INVALID_ARGUMENT" /* INVALID_ARGUMENT */]: 1 /* USAGE_ERROR */,
599
- ["INVALID_JSON" /* INVALID_JSON */]: 1 /* USAGE_ERROR */,
600
- ["MISSING_FLAG" /* MISSING_FLAG */]: 1 /* USAGE_ERROR */,
601
- ["AUTH_FAILED" /* AUTH_FAILED */]: 2 /* AUTH_ERROR */,
602
- ["AUTH_EXPIRED" /* AUTH_EXPIRED */]: 2 /* AUTH_ERROR */,
603
- ["AUTH_REFRESH_FAILED" /* AUTH_REFRESH_FAILED */]: 2 /* AUTH_ERROR */,
604
- ["WS_AUTH_ERROR" /* WS_AUTH_ERROR */]: 2 /* AUTH_ERROR */,
605
- ["SCOPE_FORBIDDEN" /* SCOPE_FORBIDDEN */]: 2 /* AUTH_ERROR */,
606
- ["BUSINESS_RULE_VIOLATION" /* BUSINESS_RULE_VIOLATION */]: 3 /* BUSINESS_ERROR */,
607
- ["MODEL_NOT_FOUND" /* MODEL_NOT_FOUND */]: 3 /* BUSINESS_ERROR */,
608
- ["ACTION_NOT_FOUND" /* ACTION_NOT_FOUND */]: 3 /* BUSINESS_ERROR */,
609
- ["AGENT_NOT_FOUND" /* AGENT_NOT_FOUND */]: 3 /* BUSINESS_ERROR */,
610
- ["TOOL_TIMEOUT" /* TOOL_TIMEOUT */]: 3 /* BUSINESS_ERROR */,
611
- ["NETWORK_ERROR" /* NETWORK_ERROR */]: 4 /* NETWORK_ERROR */,
612
- ["TIMEOUT" /* TIMEOUT */]: 4 /* NETWORK_ERROR */,
613
- ["SERVER_ERROR" /* SERVER_ERROR */]: 4 /* NETWORK_ERROR */,
614
- ["PROTOCOL_UNSUPPORTED" /* PROTOCOL_UNSUPPORTED */]: 4 /* NETWORK_ERROR */,
615
- ["PROFILE_NOT_FOUND" /* PROFILE_NOT_FOUND */]: 5 /* CONFIG_ERROR */,
616
- ["CONFIG_PARSE_ERROR" /* CONFIG_PARSE_ERROR */]: 5 /* CONFIG_ERROR */,
617
- ["KEYCHAIN_UNAVAILABLE" /* KEYCHAIN_UNAVAILABLE */]: 5 /* CONFIG_ERROR */,
618
- ["ENV_NOT_FOUND" /* ENV_NOT_FOUND */]: 5 /* CONFIG_ERROR */,
619
- ["ENV_ALREADY_EXISTS" /* ENV_ALREADY_EXISTS */]: 5 /* CONFIG_ERROR */,
620
- ["ENV_ENDPOINT_REQUIRED" /* ENV_ENDPOINT_REQUIRED */]: 1 /* USAGE_ERROR */,
621
- ["IDENTITY_NOT_FOUND" /* IDENTITY_NOT_FOUND */]: 5 /* CONFIG_ERROR */,
622
- ["IDENTITY_ALREADY_EXISTS" /* IDENTITY_ALREADY_EXISTS */]: 5 /* CONFIG_ERROR */,
623
- ["IDENTITY_NOT_IN_ENV" /* IDENTITY_NOT_IN_ENV */]: 5 /* CONFIG_ERROR */,
624
- ["TOKEN_EXPIRED" /* TOKEN_EXPIRED */]: 2 /* AUTH_ERROR */,
625
- ["NO_ACTIVE_ENV" /* NO_ACTIVE_ENV */]: 5 /* CONFIG_ERROR */,
626
- ["SKILL_ID_CONFLICT" /* SKILL_ID_CONFLICT */]: 3 /* BUSINESS_ERROR */,
627
- // 🔴 装坏了不是网络问题:报 network 会让顾问先去查 VPN。
628
- ["SKILL_SOURCE_UNREACHABLE" /* SKILL_SOURCE_UNREACHABLE */]: 5 /* CONFIG_ERROR */,
629
- ["SYNC_SOURCE_UNSUPPORTED" /* SYNC_SOURCE_UNSUPPORTED */]: 1 /* USAGE_ERROR */
830
+ // src/config/global-config.ts
831
+ var CREDENTIAL_STORE_MODES = ["auto", "file"];
832
+ var DEFAULT_ENV = "default";
833
+ var DEFAULT_DEFAULTS = {
834
+ output: "table",
835
+ timeout: "60s",
836
+ credentialStore: "auto"
630
837
  };
631
- function exitCodeFor(code) {
632
- return CODE_TO_EXIT[code] ?? 1 /* USAGE_ERROR */;
838
+ function resolveCredentialStoreMode(cfg, env2 = process.env) {
839
+ const fromEnv = normalizeCredentialStoreMode(env2.HCM_CREDENTIAL_STORE, "HCM_CREDENTIAL_STORE");
840
+ if (fromEnv) return fromEnv;
841
+ const fromCfg = normalizeCredentialStoreMode(
842
+ cfg?.defaults?.credentialStore,
843
+ "config.yml defaults.credentialStore"
844
+ );
845
+ return fromCfg ?? "auto";
846
+ }
847
+ function normalizeCredentialStoreMode(raw, source) {
848
+ if (raw !== void 0 && raw !== null && typeof raw !== "string") {
849
+ process.stderr.write(
850
+ `[hcm] WARNING: ${source} \u7684\u503C\u662F ${typeof raw}\uFF08${JSON.stringify(raw)}\uFF09\uFF0C\u5E94\u4E3A\u5B57\u7B26\u4E32\uFF08${CREDENTIAL_STORE_MODES.join(" / ")}\uFF09\uFF0C\u6309 auto \u5904\u7406\u3002
851
+ `
852
+ );
853
+ return null;
854
+ }
855
+ const v = (raw ?? "").trim().toLowerCase();
856
+ if (!v) return null;
857
+ if (CREDENTIAL_STORE_MODES.includes(v)) return v;
858
+ process.stderr.write(
859
+ `[hcm] WARNING: ${source}='${raw}' \u4E0D\u662F\u53EF\u8BC6\u522B\u7684\u503C\uFF08${CREDENTIAL_STORE_MODES.join(" / ")}\uFF09\uFF0C\u6309 auto \u5904\u7406\u3002
860
+ `
861
+ );
862
+ return null;
863
+ }
864
+ async function loadGlobalConfig() {
865
+ let raw = {};
866
+ try {
867
+ const content = await fs4.readFile(globalConfigFile(), "utf-8");
868
+ raw = yaml3.load(content) ?? {};
869
+ } catch (e) {
870
+ if (e.code !== "ENOENT") throw e;
871
+ }
872
+ const activeEnv = raw.activeEnv ?? raw.activeProfile ?? DEFAULT_ENV;
873
+ return {
874
+ activeEnv,
875
+ activeProfile: activeEnv,
876
+ // dual-write alias
877
+ defaults: { ...DEFAULT_DEFAULTS, ...raw.defaults }
878
+ };
879
+ }
880
+ async function saveGlobalConfig(cfg) {
881
+ await fs4.mkdir(hcmConfigDir(), { recursive: true });
882
+ const activeEnv = cfg.activeEnv ?? cfg.activeProfile ?? DEFAULT_ENV;
883
+ const out = {
884
+ activeEnv,
885
+ activeProfile: activeEnv,
886
+ defaults: cfg.defaults
887
+ };
888
+ await fs4.writeFile(globalConfigFile(), yaml3.dump(out), "utf-8");
889
+ }
890
+ async function resolveActiveEnv(args, env2, global) {
891
+ return (await resolveEnvContext(args, env2, global)).name;
892
+ }
893
+ async function resolveActiveProfile(args, env2, global) {
894
+ return resolveActiveEnv({ envFlag: args.flag, cwd: args.cwd }, env2, global);
633
895
  }
634
896
 
635
- // src/errors/cli-error.ts
636
- var CliError = class extends Error {
637
- code;
638
- exitCode;
639
- context;
640
- traceId;
897
+ // src/auth/token-store.ts
898
+ function isServerSlidingSession(scheme) {
899
+ return scheme === "password" || scheme === "pairing" || scheme === "browser" || scheme === "device";
900
+ }
901
+ var SERVICE_PREFIX = "hcm-cli";
902
+ var TokenStore = class _TokenStore {
903
+ constructor(profile) {
904
+ this.profile = profile;
905
+ }
641
906
  profile;
642
- cause;
643
- constructor(init) {
644
- super(init.message);
645
- this.name = "CliError";
646
- this.code = init.code;
647
- this.exitCode = exitCodeFor(init.code);
648
- this.context = init.context;
649
- this.traceId = init.traceId;
650
- this.profile = init.profile;
651
- this.cause = init.cause;
907
+ /**
908
+ * Factory: build an identity-scoped TokenStore. Stores meta at
909
+ * `identities/<name>/credentials.json` and uses keychain account prefix
910
+ * `identity-<name>` to isolate from legacy profile-scoped stores.
911
+ *
912
+ * Used by T13 login when writing identity meta and by T15 business
913
+ * commands when reading the active identity's token.
914
+ */
915
+ static forIdentity(name) {
916
+ const ts = new _TokenStore(name);
917
+ Object.defineProperty(ts, "__identity", { value: true, writable: false, configurable: false });
918
+ return ts;
652
919
  }
653
- toFormattedString() {
654
- const parts = [`${this.code}: ${this.message}`];
655
- const serverCode = this.context?.responseCode;
656
- if (typeof serverCode === "string" && serverCode && serverCode !== this.code) {
657
- parts.push(`[\u670D\u52A1\u7AEF\u9519\u8BEF\u7801: ${serverCode}]`);
920
+ get isIdentity() {
921
+ return this.__identity === true;
922
+ }
923
+ metaFile() {
924
+ return this.isIdentity ? identityMetaFile(this.profile) : credentialsFile(this.profile);
925
+ }
926
+ dataDir() {
927
+ return this.isIdentity ? identityDir(this.profile) : profileDir(this.profile);
928
+ }
929
+ keychainAccountPrefix() {
930
+ return this.isIdentity ? `identity-${this.profile}` : this.profile;
931
+ }
932
+ async writeMeta(record) {
933
+ await fs5.mkdir(this.dataDir(), { recursive: true });
934
+ await fs5.writeFile(this.metaFile(), JSON.stringify(record, null, 2), { mode: 384 });
935
+ }
936
+ async readMeta() {
937
+ try {
938
+ const raw = await fs5.readFile(this.metaFile(), "utf-8");
939
+ return JSON.parse(raw);
940
+ } catch (e) {
941
+ if (e.code === "ENOENT") return null;
942
+ throw e;
658
943
  }
659
- const field = this.context?.field;
660
- if (typeof field === "string" && field) parts.push(`[\u5B57\u6BB5: ${field}]`);
661
- if (this.traceId) parts.push(`[traceId: ${this.traceId}]`);
662
- if (this.profile) parts.push(`[profile: ${this.profile}]`);
663
- let out = parts.join(" ");
664
- const details = this.context?.details;
665
- const detailText = formatDetails(details);
666
- if (detailText) out += `
667
- \u8BE6\u60C5: ${detailText}`;
668
- if (!detailText) {
669
- const causeText = formatCause(this.cause);
670
- if (causeText) out += `
671
- \u539F\u56E0: ${causeText}`;
944
+ }
945
+ async setAccessToken(token) {
946
+ return this.storeToken("access", token);
947
+ }
948
+ async setRefreshToken(token) {
949
+ return this.storeToken("refresh", token);
950
+ }
951
+ /**
952
+ * 把一枚 token 存到能存的地方 —— 优先钥匙串,存不进就落 0600 文件。
953
+ *
954
+ * 🔴 **承重的那个操作自己就是探针**。原先的写法是「先 `getPassword` 探一下,
955
+ * 不抛就当钥匙串可用,然后**不设防**地 `setPassword`」——
956
+ * 那是**用读探针证写能力**,而这两件事在真机上会分家:
957
+ * `HOME` 不指向本人家目录时(SSH 会话 / 容器 / `sudo` / 换 `HOME` 跑),
958
+ * `getPassword` 返回 **`null` 而不抛**(「没找到」与「根本够不着」在这个 API 上同形),
959
+ * 探针于是判「可用」,紧接着 `setPassword` 抛一个 keytar 未映射的 OSStatus,
960
+ * 整条登录中止 —— 而那时**一次性配对码已经消费掉了**,屏幕上只有一句
961
+ * `An unknown error occurred.`(那句话来自 keytar 原生模块,不是本 CLI 的文案,
962
+ * 所以连错误码和 traceId 都没有)。issue #79。
963
+ *
964
+ * ⇒ 不再有单独的探针,也就不再有「探针探 A、承重靠 B」那道缝:
965
+ * 直接写,抛了就落回文件。下面那条兜底原本**永远够不到**,现在够得到了。
966
+ */
967
+ async storeToken(kind, token) {
968
+ const mode = resolveCredentialStoreMode(await loadGlobalConfig().catch(() => null));
969
+ if (mode === "file") return this.writeTokenFile(kind, token, void 0, mode);
970
+ const keytar = await loadKeytar();
971
+ if (!keytar) return this.writeTokenFile(kind, token, void 0, mode);
972
+ const account = `${this.keychainAccountPrefix()}/${kind}`;
973
+ try {
974
+ await keytar.setPassword(SERVICE_PREFIX, account, token);
975
+ } catch (e) {
976
+ return this.writeTokenFile(kind, token, e, mode);
672
977
  }
673
- const nextStep = this.context?.nextStep;
674
- if (typeof nextStep === "string" && nextStep) out += `
675
- \u4E0B\u4E00\u6B65: ${nextStep}`;
676
- return out;
978
+ return `keychain:${SERVICE_PREFIX}/${account}`;
677
979
  }
678
- toJSON() {
679
- return {
680
- code: this.code,
681
- message: this.message,
682
- context: this.context,
683
- traceId: this.traceId
684
- };
980
+ async getAccessToken() {
981
+ if (process.env.HCM_PAT) return process.env.HCM_PAT;
982
+ if (process.env.HCM_ACCESS_TOKEN) return process.env.HCM_ACCESS_TOKEN;
983
+ return this.getStoredAccessToken();
984
+ }
985
+ /**
986
+ * 只读取这一个 store 持久化的 token,不接受 HCM_PAT/HCM_ACCESS_TOKEN 覆盖。
987
+ *
988
+ * `identity show <alias>` 要回答的是「这个 alias 到底是谁」;若沿用普通命令的环境变量
989
+ * 优先级,机器上临时设置的一枚 token 会让所有 alias 都显示成同一个人,正向角色验收
990
+ * 反而得到一份可信外观的错误证据。普通业务命令仍走 {@link getAccessToken},行为不变。
991
+ */
992
+ async getStoredAccessToken() {
993
+ const meta = await this.readMeta();
994
+ if (!meta?.accessTokenRef) return null;
995
+ return this.resolveRef(meta.accessTokenRef);
996
+ }
997
+ async getRefreshToken() {
998
+ const meta = await this.readMeta();
999
+ if (!meta?.refreshTokenRef) return null;
1000
+ return this.resolveRef(meta.refreshTokenRef);
1001
+ }
1002
+ async clear() {
1003
+ const meta = await this.readMeta();
1004
+ if (!meta) return;
1005
+ if (meta.accessTokenRef?.startsWith("keychain:")) {
1006
+ const account = meta.accessTokenRef.slice("keychain:".length).split("/").slice(1).join("/");
1007
+ const keytar = await loadKeytar();
1008
+ if (keytar) await keytar.deletePassword(SERVICE_PREFIX, account);
1009
+ } else if (meta.accessTokenRef?.startsWith("file:")) {
1010
+ await fs5.rm(meta.accessTokenRef.slice("file:".length), { force: true });
1011
+ }
1012
+ if (meta.refreshTokenRef?.startsWith("keychain:")) {
1013
+ const account = meta.refreshTokenRef.slice("keychain:".length).split("/").slice(1).join("/");
1014
+ const keytar = await loadKeytar();
1015
+ if (keytar) await keytar.deletePassword(SERVICE_PREFIX, account);
1016
+ } else if (meta.refreshTokenRef?.startsWith("file:")) {
1017
+ await fs5.rm(meta.refreshTokenRef.slice("file:".length), { force: true });
1018
+ }
1019
+ if (!this.isIdentity) {
1020
+ await fs5.rm(this.metaFile(), { force: true });
1021
+ }
1022
+ }
1023
+ async resolveRef(ref) {
1024
+ if (ref.startsWith("keychain:")) {
1025
+ const account = ref.slice("keychain:".length).split("/").slice(1).join("/");
1026
+ const keytar = await loadKeytar();
1027
+ if (!keytar) return null;
1028
+ return keytar.getPassword(SERVICE_PREFIX, account);
1029
+ }
1030
+ if (ref.startsWith("file:")) {
1031
+ try {
1032
+ return await fs5.readFile(ref.slice("file:".length), "utf-8");
1033
+ } catch (e) {
1034
+ if (e.code === "ENOENT") return null;
1035
+ throw e;
1036
+ }
1037
+ }
1038
+ if (ref.startsWith("plain:")) return ref.slice("plain:".length);
1039
+ return null;
1040
+ }
1041
+ /**
1042
+ * 兜底:0600 文件。
1043
+ *
1044
+ * 🔴 `cause` 分开两档措辞,**不许合并**:「这台机器上没有 keytar」是常态
1045
+ * (Linux 无 libsecret 等),「有 keytar 但写不进去」是异常,顾问的下一步不同 ——
1046
+ * 后者必须把原始报错**原样转述**出来,否则他看到的还是一句没有出处的话。
1047
+ */
1048
+ async writeTokenFile(kind, token, cause, mode = "auto") {
1049
+ const file = `${this.metaFile()}.${kind}`;
1050
+ await fs5.mkdir(this.dataDir(), { recursive: true, mode: 448 });
1051
+ await fs5.writeFile(file, token, { mode: 384 });
1052
+ await fs5.chmod(file, 384);
1053
+ if (kind === "access" && mode !== "file") {
1054
+ const why = cause === void 0 ? "OS keychain unavailable" : `OS keychain refused the write (${cause instanceof Error ? cause.message : String(cause)})`;
1055
+ console.warn(`[hcm] WARNING: ${why}. Token saved to ${file} (0600).`);
1056
+ }
1057
+ return `file:${file}`;
685
1058
  }
686
1059
  };
687
- function fromAxiosError(err, profile) {
688
- const status = err.response?.status;
689
- const traceId = err.response?.headers?.["x-trace-id"];
690
- const data = err.response?.data;
691
- const body = data?.error ?? data;
692
- const respCode = body?.code;
693
- const respMsg = body?.message;
694
- const respField = body?.field;
695
- const respDetails = body?.details;
696
- const respNextStep = body?.nextStep;
697
- const respRetryable = body?.retryable;
698
- let code;
699
- if (status === 401) code = "AUTH_FAILED" /* AUTH_FAILED */;
700
- else if (status === 403) code = "SCOPE_FORBIDDEN" /* SCOPE_FORBIDDEN */;
701
- else if (status === 404 && respCode === "MODEL_NOT_FOUND") code = "MODEL_NOT_FOUND" /* MODEL_NOT_FOUND */;
702
- else if (status === 404 && respCode === "ACTION_NOT_FOUND") code = "ACTION_NOT_FOUND" /* ACTION_NOT_FOUND */;
703
- else if (status && status >= 400 && status < 500) code = "BUSINESS_RULE_VIOLATION" /* BUSINESS_RULE_VIOLATION */;
704
- else if (status && status >= 500) code = "SERVER_ERROR" /* SERVER_ERROR */;
705
- else if (err.code === "ECONNABORTED") code = "TIMEOUT" /* TIMEOUT */;
706
- else code = "NETWORK_ERROR" /* NETWORK_ERROR */;
707
- return new CliError({
708
- code,
709
- message: respMsg ?? err.message ?? "request failed",
710
- context: {
711
- status,
712
- responseCode: respCode,
713
- // 结构化错误的这几件必须原样带出:field 指哪个字段错了、details 机器可读、
714
- // nextStep 是后端给的路标(ADR-166 终局协议)—— 吞掉它等于让命令行用户自己猜下一步。
715
- ...respField ? { field: respField } : {},
716
- ...respDetails !== void 0 ? { details: respDetails } : {},
717
- ...respNextStep ? { nextStep: respNextStep } : {},
718
- ...respRetryable !== void 0 ? { retryable: respRetryable } : {}
719
- },
720
- traceId,
721
- profile,
722
- cause: err
723
- });
724
- }
725
- function formatDetails(details) {
726
- if (details === void 0 || details === null) return void 0;
727
- if (typeof details === "string") return details.trim() || void 0;
728
- if (typeof details === "number" || typeof details === "boolean") return String(details);
729
- let text2;
1060
+ async function loadKeytar() {
730
1061
  try {
731
- text2 = JSON.stringify(details);
1062
+ const mod = await import("keytar");
1063
+ return mod.default ?? mod;
732
1064
  } catch {
733
- return void 0;
1065
+ return null;
734
1066
  }
735
- if (!text2 || text2 === "{}" || text2 === "[]") return void 0;
736
- return text2.length > 800 ? `${text2.slice(0, 800)}\u2026\uFF08\u5DF2\u622A\u65AD\uFF09` : text2;
737
1067
  }
738
- function formatCause(cause) {
739
- if (!cause) return void 0;
740
- if (typeof cause === "string") return cause.trim().slice(0, 300) || void 0;
741
- if (cause instanceof Error) {
742
- const text2 = cause.message?.trim();
743
- return text2 ? text2.slice(0, 300) : void 0;
744
- }
745
- return void 0;
1068
+
1069
+ // src/auth/principal.ts
1070
+ function toPrincipal(raw) {
1071
+ if (!raw || typeof raw !== "object") return void 0;
1072
+ const o = raw;
1073
+ const principal = {};
1074
+ const rawUserId = o.userId ?? o.id;
1075
+ if (rawUserId !== void 0 && rawUserId !== null) principal.userId = String(rawUserId);
1076
+ if (o.tenantId !== void 0 && o.tenantId !== null) principal.tenantId = String(o.tenantId);
1077
+ if (typeof o.username === "string" && o.username) principal.username = o.username;
1078
+ if (Array.isArray(o.roles)) principal.roles = o.roles.map(String);
1079
+ return Object.keys(principal).length > 0 ? principal : void 0;
1080
+ }
1081
+ function describePrincipal(principal) {
1082
+ if (!principal) return "server-identity=<\u672A\u56DE\u8EAB\u4EFD>";
1083
+ const parts = [];
1084
+ parts.push(`tenant=${principal.tenantId ?? "<\u672A\u56DE>"}`);
1085
+ parts.push(`user=${principal.username ?? "<\u672A\u56DE>"}`);
1086
+ if (principal.roles?.length) parts.push(`roles=${principal.roles.join(",")}`);
1087
+ return parts.join(" ");
1088
+ }
1089
+ function assertExpectedTenant(principal, expected) {
1090
+ if (expected === void 0) return;
1091
+ if (principal?.tenantId !== expected) throw new CliError({
1092
+ code: "AUTH_FAILED" /* AUTH_FAILED */,
1093
+ message: `\u9879\u76EE\u58F0\u660E\u79DF\u6237 ${expected}\uFF0C\u4F46\u767B\u5F55\u51ED\u636E\u7684\u670D\u52A1\u7AEF\u79DF\u6237\u662F ${principal?.tenantId ?? "\u672A\u8FD4\u56DE\uFF08\u65E0\u6CD5\u9A8C\u8BC1\uFF09"}\uFF1B\u672A\u4FDD\u5B58\u51ED\u636E\uFF0C\u4E5F\u672A\u6539\u5199\u539F\u69FD\u3002`,
1094
+ context: { nextStep: "\u4F7F\u7528\u9879\u76EE\u79DF\u6237\u7684\u8D26\u53F7\u91CD\u65B0\u767B\u5F55\uFF1B\u82E5\u7528\u914D\u5BF9\u7801\uFF0C\u672C\u6B21\u7801\u53EF\u80FD\u5DF2\u6D88\u8D39\uFF0C\u8BF7\u4ECE\u6B63\u786E\u79DF\u6237\u91CD\u65B0\u751F\u6210\u914D\u5BF9\u7801" }
1095
+ });
746
1096
  }
747
1097
 
748
- // src/config/env.ts
749
- function assertNotReservedEnvName(name) {
750
- if (isTempEnv(name)) {
751
- throw new CliError({
752
- code: "INVALID_ARGUMENT" /* INVALID_ARGUMENT */,
753
- message: `'${TEMP_ENV_NAME}' \u662F\u4E34\u65F6\u73AF\u5883\u7684\u4FDD\u7559\u540D\uFF0C\u4E0D\u80FD\u7528\u4F5C env \u540D\u5B57\u3002`,
754
- context: {
755
- nextStep: `\u6362\u4E2A\u540D\u5B57\uFF1B\u5982\u679C\u4F60\u662F\u60F3\u628A\u5F53\u524D\u4E34\u65F6\u73AF\u5883\u5B58\u4E0B\u6765\uFF0C\u7528: hcm env save <name>`
756
- }
757
- });
1098
+ // src/auth/password.ts
1099
+ var DEFAULT_SESSION_TTL_SECONDS = 24 * 60 * 60;
1100
+ async function loginPassword(input) {
1101
+ const resp = await input.httpClient.post(
1102
+ `${input.endpoint}/api/auth/login`,
1103
+ {
1104
+ tenantId: input.tenantId,
1105
+ username: input.username,
1106
+ password: input.password
1107
+ },
1108
+ { headers: { "Content-Type": "application/json" } }
1109
+ );
1110
+ const { token, expiresIn, user } = resp.data;
1111
+ if (!token) {
1112
+ throw new Error("Login response missing token");
758
1113
  }
1114
+ const ttlSeconds = expiresIn ?? DEFAULT_SESSION_TTL_SECONDS;
1115
+ const expiresAt = new Date(Date.now() + ttlSeconds * 1e3).toISOString();
1116
+ assertExpectedTenant(toPrincipal(user), input.expectedTenantId);
1117
+ const store = new TokenStore(input.profile);
1118
+ const accessTokenRef = await store.setAccessToken(token);
1119
+ const record = {
1120
+ scheme: "password",
1121
+ accessTokenRef,
1122
+ // 口令会话**没有** refresh token —— 后端 `/api/auth/login` 只回 token。
1123
+ // 它的续期语义是「同一个 token 被服务端重设 TTL」,见 refresh.ts。
1124
+ refreshTokenRef: void 0,
1125
+ expiresAt,
1126
+ scopes: ["*"],
1127
+ ttlSeconds
1128
+ };
1129
+ await store.writeMeta(record);
1130
+ return { record, principal: toPrincipal(user) };
759
1131
  }
760
- async function saveEnv(name, cfg) {
761
- if (!cfg.endpoint) {
762
- throw new CliError({
763
- code: "ENV_ENDPOINT_REQUIRED" /* ENV_ENDPOINT_REQUIRED */,
764
- message: `env '${name}' requires endpoint`
765
- });
1132
+
1133
+ // src/auth/refresh.ts
1134
+ var PROACTIVE_REFRESH_MARGIN_SECONDS = 60 * 60;
1135
+ async function refreshToken(input) {
1136
+ if (!input.identity && !input.profile) {
1137
+ throw new Error("refreshToken: either identity or profile required");
766
1138
  }
767
- await fs4.mkdir(envDir(name), { recursive: true });
768
- await fs4.writeFile(envFile(name), yaml3.dump(cfg), "utf-8");
769
- }
770
- async function loadEnv(name) {
771
- try {
772
- const content = await fs4.readFile(envFile(name), "utf-8");
773
- return yaml3.load(content);
774
- } catch (e) {
775
- if (e.code === "ENOENT") {
776
- throw new CliError({
777
- code: "ENV_NOT_FOUND" /* ENV_NOT_FOUND */,
778
- message: `env '${name}' not found. Run: hcm env list`
779
- });
1139
+ const store = input.identity ? TokenStore.forIdentity(input.identity) : new TokenStore(input.profile);
1140
+ const meta = await store.readMeta();
1141
+ if (!meta) throw new Error("no credentials to refresh");
1142
+ switch (meta.scheme) {
1143
+ case "pat":
1144
+ throw new Error("PAT cannot be refreshed; re-run `hcm login --pat-stdin`");
1145
+ case "client_credentials":
1146
+ throw new Error(
1147
+ "client_credentials \u4F1A\u8BDD\u65E0\u6CD5\u81EA\u52A8\u7EED\u671F\uFF1A\u5237\u65B0\u9700\u8981 client_secret\uFF0C\u800C CLI \u4E0D\u4FDD\u5B58\u5B83\u3002\u91CD\u65B0\u6267\u884C `hcm login --client-id <id>`"
1148
+ );
1149
+ case "password":
1150
+ case "pairing":
1151
+ case "browser":
1152
+ case "device":
1153
+ return slidePasswordSession(store, meta, input);
1154
+ default: {
1155
+ const unknown = meta.scheme;
1156
+ throw new Error(`unknown auth scheme in stored credentials: ${String(unknown)}`);
780
1157
  }
781
- throw e;
782
1158
  }
783
1159
  }
784
- async function listEnvs() {
785
- try {
786
- const entries = await fs4.readdir(envsDir(), { withFileTypes: true });
787
- const result = [];
788
- for (const e of entries) {
789
- if (!e.isDirectory()) continue;
790
- try {
791
- await fs4.access(envFile(e.name));
792
- result.push(e.name);
793
- } catch {
794
- }
795
- }
796
- return result;
797
- } catch (e) {
798
- if (e.code === "ENOENT") return [];
799
- throw e;
1160
+ async function slidePasswordSession(store, meta, input) {
1161
+ const accessToken = await store.getAccessToken();
1162
+ if (!accessToken) {
1163
+ throw new Error("no access token to refresh; re-run `hcm login`");
800
1164
  }
1165
+ await input.httpClient.post(`${input.endpoint}/api/auth/refresh`, void 0, {
1166
+ headers: { Authorization: `Bearer ${accessToken}` },
1167
+ // 见上:阻断 401 → onRefresh → 本函数 → 401 的递归。
1168
+ __skipAuthRetry: true
1169
+ });
1170
+ const ttlSeconds = meta.ttlSeconds ?? DEFAULT_SESSION_TTL_SECONDS;
1171
+ const record = {
1172
+ ...meta,
1173
+ // token 本身没变,accessTokenRef / scopes 原样保留。
1174
+ expiresAt: new Date(Date.now() + ttlSeconds * 1e3).toISOString(),
1175
+ ttlSeconds
1176
+ };
1177
+ await store.writeMeta(record);
1178
+ return record;
801
1179
  }
802
- async function deleteEnv(name) {
803
- try {
804
- await fs4.access(envFile(name));
805
- } catch {
806
- throw new CliError({
807
- code: "ENV_NOT_FOUND" /* ENV_NOT_FOUND */,
808
- message: `env '${name}' not found`
809
- });
810
- }
811
- await fs4.rm(envDir(name), { recursive: true, force: true });
1180
+ function needsRefresh(meta, marginSec = 60) {
1181
+ const expiresAtMs = new Date(meta.expiresAt).getTime();
1182
+ return Date.now() + marginSec * 1e3 > expiresAtMs;
812
1183
  }
813
-
814
- // src/config/identity.ts
815
- import * as fs5 from "fs/promises";
816
- async function assertEnvExists(env2) {
1184
+ async function ensureSessionFresh(input) {
817
1185
  try {
818
- await fs5.access(envFile(env2));
1186
+ const store = input.identity ? TokenStore.forIdentity(input.identity) : new TokenStore(input.profile);
1187
+ const meta = await store.readMeta();
1188
+ if (!meta || !isServerSlidingSession(meta.scheme)) return false;
1189
+ if (!needsRefresh(meta, PROACTIVE_REFRESH_MARGIN_SECONDS)) return false;
1190
+ await refreshToken(input);
1191
+ return true;
819
1192
  } catch {
820
- throw new CliError({
821
- code: "IDENTITY_NOT_IN_ENV" /* IDENTITY_NOT_IN_ENV */,
822
- message: `env '${env2}' does not exist. Run: hcm env add ${env2} --endpoint <url>`
823
- });
1193
+ return false;
824
1194
  }
825
1195
  }
826
- async function saveIdentity(name, meta) {
827
- await assertEnvExists(meta.env);
828
- await fs5.mkdir(identityDir(name), { recursive: true });
829
- await fs5.writeFile(identityMetaFile(name), JSON.stringify(meta, null, 2), { mode: 384 });
830
- }
831
- async function loadIdentity(name) {
1196
+
1197
+ // src/config/profile.ts
1198
+ import * as fs6 from "fs/promises";
1199
+ import * as path3 from "path";
1200
+ import yaml4 from "js-yaml";
1201
+ async function loadProfile(profile) {
1202
+ const file = profileFile(profile);
1203
+ let content;
832
1204
  try {
833
- const raw = await fs5.readFile(identityMetaFile(name), "utf-8");
834
- return JSON.parse(raw);
1205
+ content = await fs6.readFile(file, "utf-8");
835
1206
  } catch (e) {
836
1207
  if (e.code === "ENOENT") {
837
- throw new CliError({
838
- code: "IDENTITY_NOT_FOUND" /* IDENTITY_NOT_FOUND */,
839
- message: `identity '${name}' not found. Run: hcm identity list`
840
- });
1208
+ throw new Error(`profile '${profile}' not found at ${file}`);
841
1209
  }
842
1210
  throw e;
843
1211
  }
1212
+ return yaml4.load(content);
844
1213
  }
845
- async function listIdentities(env2) {
1214
+ async function saveProfile(profile, cfg) {
1215
+ await fs6.mkdir(profileDir(profile), { recursive: true });
1216
+ await fs6.writeFile(profileFile(profile), yaml4.dump(cfg), "utf-8");
1217
+ }
1218
+ async function listProfiles() {
1219
+ const root = hcmConfigDir();
846
1220
  try {
847
- const entries = await fs5.readdir(identitiesDir(), { withFileTypes: true });
1221
+ const entries = await fs6.readdir(root, { withFileTypes: true });
848
1222
  const result = [];
849
1223
  for (const e of entries) {
850
- if (!e.isDirectory()) continue;
851
- try {
852
- const meta = await loadIdentity(e.name);
853
- if (!env2 || meta.env === env2) result.push(e.name);
854
- } catch {
1224
+ if (e.isDirectory()) {
1225
+ try {
1226
+ await fs6.access(path3.join(root, e.name, "profile.yml"));
1227
+ result.push(e.name);
1228
+ } catch {
1229
+ }
855
1230
  }
856
1231
  }
857
1232
  return result;
@@ -860,50 +1235,18 @@ async function listIdentities(env2) {
860
1235
  throw e;
861
1236
  }
862
1237
  }
863
- async function deleteIdentity(name) {
864
- try {
865
- await fs5.access(identityMetaFile(name));
866
- } catch {
867
- throw new CliError({
868
- code: "IDENTITY_NOT_FOUND" /* IDENTITY_NOT_FOUND */,
869
- message: `identity '${name}' not found`
870
- });
871
- }
872
- await fs5.rm(identityDir(name), { recursive: true, force: true });
873
- }
874
- async function renameIdentity(oldName, newName) {
875
- if (oldName === newName) return;
876
- const meta = await loadIdentity(oldName);
877
- const clash = await loadIdentity(newName).catch(() => null);
878
- if (clash) {
879
- throw new CliError({
880
- code: "IDENTITY_ALREADY_EXISTS" /* IDENTITY_ALREADY_EXISTS */,
881
- message: `identity '${newName}' \u5DF2\u5B58\u5728\uFF0C\u4E0D\u80FD\u628A '${oldName}' \u6539\u6210\u8FD9\u4E2A\u540D\u5B57\u3002`
882
- });
883
- }
884
- await fs5.rename(identityDir(oldName), identityDir(newName));
885
- const rebase = (ref, kind) => {
886
- if (!ref?.startsWith("file:")) return ref;
887
- return `file:${identityMetaFile(newName)}.${kind}`;
888
- };
889
- await saveIdentity(newName, {
890
- ...meta,
891
- accessTokenRef: rebase(meta.accessTokenRef, "access"),
892
- refreshTokenRef: rebase(meta.refreshTokenRef, "refresh")
893
- });
894
- }
895
1238
 
896
1239
  // src/config/migration.ts
897
- import * as fs6 from "fs/promises";
898
- import * as path3 from "path";
899
- import yaml4 from "js-yaml";
1240
+ import * as fs7 from "fs/promises";
1241
+ import * as path4 from "path";
1242
+ import yaml5 from "js-yaml";
900
1243
  var RESERVED = /* @__PURE__ */ new Set(["envs", "identities", "_archive"]);
901
1244
  async function migrateLegacyProfiles() {
902
1245
  const summary = { migrated: [], failed: [], skipped: [] };
903
1246
  const root = hcmConfigDir();
904
1247
  let entries;
905
1248
  try {
906
- entries = await fs6.readdir(root, { withFileTypes: true });
1249
+ entries = await fs7.readdir(root, { withFileTypes: true });
907
1250
  } catch (e) {
908
1251
  if (e.code === "ENOENT") return summary;
909
1252
  throw e;
@@ -912,12 +1255,12 @@ async function migrateLegacyProfiles() {
912
1255
  if (!e.isDirectory() || RESERVED.has(e.name)) continue;
913
1256
  const legacyYml = profileFile(e.name);
914
1257
  try {
915
- await fs6.access(legacyYml);
1258
+ await fs7.access(legacyYml);
916
1259
  } catch {
917
1260
  continue;
918
1261
  }
919
1262
  try {
920
- await fs6.access(envFile(e.name));
1263
+ await fs7.access(envFile(e.name));
921
1264
  summary.skipped.push(e.name);
922
1265
  continue;
923
1266
  } catch {
@@ -935,7 +1278,7 @@ async function migrateLegacyProfiles() {
935
1278
  if (result === null) {
936
1279
  try {
937
1280
  const creds = JSON.parse(
938
- await fs6.readFile(credentialsFile(e.name), "utf-8")
1281
+ await fs7.readFile(credentialsFile(e.name), "utf-8")
939
1282
  );
940
1283
  const guessedId = creds?.username ? `${creds.username}@${e.name}` : `default@${e.name}`;
941
1284
  await deleteIdentity(guessedId);
@@ -965,8 +1308,8 @@ async function migrateLegacyProfiles() {
965
1308
  return summary;
966
1309
  }
967
1310
  async function migrateOne(name) {
968
- const legacyProfile = yaml4.load(
969
- await fs6.readFile(profileFile(name), "utf-8")
1311
+ const legacyProfile = yaml5.load(
1312
+ await fs7.readFile(profileFile(name), "utf-8")
970
1313
  );
971
1314
  if (!legacyProfile?.endpoint) {
972
1315
  throw new Error("legacy profile.yml missing endpoint");
@@ -974,7 +1317,7 @@ async function migrateOne(name) {
974
1317
  let creds = null;
975
1318
  try {
976
1319
  creds = JSON.parse(
977
- await fs6.readFile(credentialsFile(name), "utf-8")
1320
+ await fs7.readFile(credentialsFile(name), "utf-8")
978
1321
  );
979
1322
  } catch (e) {
980
1323
  if (e.code !== "ENOENT") {
@@ -1006,19 +1349,19 @@ async function migrateOne(name) {
1006
1349
  expiresAt: "1970-01-01T00:00:00Z"
1007
1350
  });
1008
1351
  }
1009
- const archiveTarget = path3.join(archiveDir(), name);
1010
- await fs6.mkdir(archiveTarget, { recursive: true });
1011
- await fs6.rename(profileFile(name), path3.join(archiveTarget, "profile.yml.bak"));
1352
+ const archiveTarget = path4.join(archiveDir(), name);
1353
+ await fs7.mkdir(archiveTarget, { recursive: true });
1354
+ await fs7.rename(profileFile(name), path4.join(archiveTarget, "profile.yml.bak"));
1012
1355
  try {
1013
- await fs6.rename(
1356
+ await fs7.rename(
1014
1357
  credentialsFile(name),
1015
- path3.join(archiveTarget, "credentials.json.bak")
1358
+ path4.join(archiveTarget, "credentials.json.bak")
1016
1359
  );
1017
1360
  } catch (e) {
1018
1361
  if (e.code !== "ENOENT") throw e;
1019
1362
  }
1020
1363
  try {
1021
- await fs6.rmdir(profileDir(name));
1364
+ await fs7.rmdir(profileDir(name));
1022
1365
  } catch {
1023
1366
  }
1024
1367
  return { identityName };
@@ -1167,139 +1510,41 @@ function normalizeScope(input) {
1167
1510
  }
1168
1511
  function queryParams(input) {
1169
1512
  return {
1170
- ...input.params ?? {},
1171
- ...input.scope === "class" && input.id ? { id: input.id } : {},
1172
- ...input.ids?.length ? { ids: input.ids.join(",") } : {}
1173
- };
1174
- }
1175
- function classBody(input) {
1176
- return {
1177
- ...input.params ?? {},
1178
- ...input.id ? { id: input.id } : {},
1179
- ...input.ids?.length ? { ids: input.ids } : {}
1180
- };
1181
- }
1182
- function objectBody(input) {
1183
- return input.params ?? {};
1184
- }
1185
- async function action(http, model, actionName, input) {
1186
- const method = normalizeMethod(input.method);
1187
- const scope = normalizeScope(input);
1188
- if (scope === "object" && !input.id) {
1189
- throw new Error(`object action ${model}.${actionName} requires id`);
1190
- }
1191
- const path23 = scope === "object" ? `/api/models/${model}/${input.id}/action/${actionName}` : `/api/models/${model}/action/${actionName}`;
1192
- const resp = await (async () => {
1193
- if (method === "GET") {
1194
- return http.get(path23, { params: queryParams(input) });
1195
- }
1196
- if (method === "DELETE") {
1197
- return http.delete(path23, { params: queryParams(input) });
1198
- }
1199
- if (method === "PUT") {
1200
- return http.put(path23, scope === "object" ? objectBody(input) : classBody(input));
1201
- }
1202
- return http.post(path23, scope === "object" ? objectBody(input) : classBody(input));
1203
- })();
1204
- return resp.data;
1205
- }
1206
-
1207
- // src/meta/describe.ts
1208
- function normalizeActionParams(action3) {
1209
- if (action3.parameters) return action3.parameters;
1210
- if (action3.params) return action3.params;
1211
- if (!action3.paramNames?.length && !action3.paramTypes?.length) return void 0;
1212
- const size = Math.max(action3.paramNames?.length ?? 0, action3.paramTypes?.length ?? 0);
1213
- return Array.from({ length: size }, (_, index) => ({
1214
- name: action3.paramNames?.[index] ?? `arg${index}`,
1215
- type: action3.paramTypes?.[index] ?? "unknown"
1216
- }));
1217
- }
1218
- async function describe(http, model, _opts = {}) {
1219
- const [metaResp, effective] = await Promise.all([
1220
- http.get(`/api/models/${model}/meta`),
1221
- fetchEffectiveActions(http, model)
1222
- ]);
1223
- const meta = metaResp.data;
1224
- const fields = (meta.fields ?? []).map((f) => ({
1225
- name: f.key ?? f.name ?? "",
1226
- label: f.name,
1227
- type: f.type ?? "unknown",
1228
- required: f.isRequired,
1229
- description: f.description,
1230
- enum: f.enum,
1231
- relation: f.relation,
1232
- // 只在为真时出这一位:false 与「这个服务端没有 i18n 这个概念」在下游没有区别,
1233
- // 出一个 `i18n: false` 只会让 --output json 的每个字段都多一行噪声。
1234
- ...f.isI18n ? { i18n: true } : {}
1235
- }));
1236
- const actions = (meta.actions ?? []).map((a) => ({
1237
- name: a.key ?? a.name ?? "",
1238
- label: a.label,
1239
- description: a.description,
1240
- params: normalizeActionParams(a),
1241
- scope: a.scope,
1242
- httpMethod: a.httpMethod,
1243
- effect: a.effect,
1244
- readOnly: a.readOnly,
1245
- paramTypes: a.paramTypes,
1246
- paramNames: a.paramNames,
1247
- returnType: a.returnType,
1248
- source: a.source
1249
- }));
1513
+ ...input.params ?? {},
1514
+ ...input.scope === "class" && input.id ? { id: input.id } : {},
1515
+ ...input.ids?.length ? { ids: input.ids.join(",") } : {}
1516
+ };
1517
+ }
1518
+ function classBody(input) {
1250
1519
  return {
1251
- model: meta.name ?? model,
1252
- labels: meta.labels ?? {},
1253
- fields,
1254
- actions: mergeEffectiveActions(actions, effective),
1255
- relations: meta.relations ?? [],
1256
- effectiveActionsAvailable: effective.available,
1257
- ...effective.available ? {} : { effectiveActionsNote: effective.note }
1520
+ ...input.params ?? {},
1521
+ ...input.id ? { id: input.id } : {},
1522
+ ...input.ids?.length ? { ids: input.ids } : {}
1258
1523
  };
1259
1524
  }
1260
- async function fetchEffectiveActions(http, model) {
1261
- try {
1262
- const resp = await http.get(`/api/models/${model}/actions`);
1263
- const rows = resp.data?.actions;
1264
- if (!Array.isArray(rows)) {
1265
- return {
1266
- available: false,
1267
- rows: [],
1268
- note: `GET /api/models/${model}/actions \u6CA1\u6709\u8FD4\u56DE actions \u6570\u7EC4\uFF0C\u811A\u672C Action \u672A\u7EB3\u5165`
1269
- };
1270
- }
1271
- return { available: true, rows };
1272
- } catch (e) {
1273
- const err = e;
1274
- const status = err?.response?.status;
1275
- const detail = status ? `HTTP ${status}` : err?.message ?? String(e);
1276
- return {
1277
- available: false,
1278
- rows: [],
1279
- note: `GET /api/models/${model}/actions \u4E0D\u53EF\u7528\uFF08${detail}\uFF09\uFF0C\u811A\u672C Action \u672A\u7EB3\u5165`
1280
- };
1281
- }
1525
+ function objectBody(input) {
1526
+ return input.params ?? {};
1282
1527
  }
1283
- function mergeEffectiveActions(fromMeta, effective) {
1284
- if (!effective.available) return fromMeta;
1285
- const known = new Set(fromMeta.map((a) => a.name));
1286
- const extra = [];
1287
- for (const row of effective.rows) {
1288
- const name = row.key ?? "";
1289
- if (!name || known.has(name)) continue;
1290
- known.add(name);
1291
- const candidate = row.candidates?.[0];
1292
- extra.push({
1293
- name,
1294
- label: row.label,
1295
- scope: candidate?.scope,
1296
- httpMethod: "POST",
1297
- effect: row.effect,
1298
- readOnly: row.readOnly,
1299
- source: candidate?.source
1300
- });
1528
+ async function action(http, model, actionName, input) {
1529
+ const method = normalizeMethod(input.method);
1530
+ const scope = normalizeScope(input);
1531
+ if (scope === "object" && !input.id) {
1532
+ throw new Error(`object action ${model}.${actionName} requires id`);
1301
1533
  }
1302
- return [...fromMeta, ...extra];
1534
+ const path24 = scope === "object" ? `/api/models/${model}/${input.id}/action/${actionName}` : `/api/models/${model}/action/${actionName}`;
1535
+ const resp = await (async () => {
1536
+ if (method === "GET") {
1537
+ return http.get(path24, { params: queryParams(input) });
1538
+ }
1539
+ if (method === "DELETE") {
1540
+ return http.delete(path24, { params: queryParams(input) });
1541
+ }
1542
+ if (method === "PUT") {
1543
+ return http.put(path24, scope === "object" ? objectBody(input) : classBody(input));
1544
+ }
1545
+ return http.post(path24, scope === "object" ? objectBody(input) : classBody(input));
1546
+ })();
1547
+ return resp.data;
1303
1548
  }
1304
1549
 
1305
1550
  // src/fde/fingerprint.ts
@@ -1545,7 +1790,7 @@ function resolveRefs(record, store) {
1545
1790
  }
1546
1791
 
1547
1792
  // src/import/parse.ts
1548
- import yaml5, { JSON_SCHEMA } from "js-yaml";
1793
+ import yaml6, { JSON_SCHEMA } from "js-yaml";
1549
1794
  var REQUIRED = ["model", "key_field", "count", "items"];
1550
1795
  function parseFixture(yamlText, sourcePath) {
1551
1796
  const where = sourcePath ? ` (${sourcePath})` : "";
@@ -1554,7 +1799,7 @@ function parseFixture(yamlText, sourcePath) {
1554
1799
  };
1555
1800
  let parsed;
1556
1801
  try {
1557
- parsed = yaml5.load(yamlText, { schema: JSON_SCHEMA });
1802
+ parsed = yaml6.load(yamlText, { schema: JSON_SCHEMA });
1558
1803
  } catch (e) {
1559
1804
  return fail2(`YAML \u89E3\u6790\u5931\u8D25: ${e.message}`);
1560
1805
  }
@@ -1646,6 +1891,7 @@ var HcmClient = class _HcmClient {
1646
1891
  http;
1647
1892
  tokenStore;
1648
1893
  explicitToken;
1894
+ closeEphemeralSession;
1649
1895
  constructor(opts) {
1650
1896
  this.profile = opts.profile ?? "default";
1651
1897
  this.endpoint = opts.endpoint;
@@ -1655,6 +1901,7 @@ var HcmClient = class _HcmClient {
1655
1901
  this.http = createHttpClient({
1656
1902
  endpoint: opts.endpoint,
1657
1903
  timeoutMs: opts.timeoutMs,
1904
+ environmentSafety: opts.environmentSafety,
1658
1905
  getAccessToken: () => this.getAccessToken(),
1659
1906
  onRefresh: () => this.handleRefresh()
1660
1907
  });
@@ -1682,14 +1929,22 @@ var HcmClient = class _HcmClient {
1682
1929
  */
1683
1930
  identity;
1684
1931
  static fromAuthContext(ctx) {
1932
+ if ((ctx.impersonation || ctx.identityTokenPinned) && !ctx.ephemeralAccessToken) {
1933
+ throw new Error("\u6307\u5B9A\u8EAB\u4EFD\u4E0A\u4E0B\u6587\u7F3A\u5C11\u672C\u8FDB\u7A0B token\uFF1B\u8BF7\u91CD\u65B0\u8FD0\u884C\u5E26 --as \u7684\u547D\u4EE4");
1934
+ }
1685
1935
  const c = new _HcmClient({
1936
+ accessToken: ctx.ephemeralAccessToken,
1937
+ environmentSafety: ctx.environmentSafety,
1686
1938
  endpoint: ctx.endpoint,
1687
1939
  tenantId: ctx.tenantId,
1688
1940
  profile: ctx.env
1689
1941
  // alias env→profile for downstream readers
1690
1942
  });
1691
- c.tokenStore = TokenStore.forIdentity(ctx.identity);
1692
- c.identity = ctx.identity;
1943
+ if (ctx.impersonation) c.closeEphemeralSession = ctx.closeEphemeralSession;
1944
+ if (!ctx.impersonation) {
1945
+ c.tokenStore = TokenStore.forIdentity(ctx.identity);
1946
+ c.identity = ctx.identity;
1947
+ }
1693
1948
  return c;
1694
1949
  }
1695
1950
  /**
@@ -1744,6 +1999,7 @@ var HcmClient = class _HcmClient {
1744
1999
  return this.http;
1745
2000
  }
1746
2001
  async close() {
2002
+ await this.closeEphemeralSession?.();
1747
2003
  }
1748
2004
  async getAccessToken() {
1749
2005
  if (this.explicitToken) return this.explicitToken;
@@ -1764,10 +2020,10 @@ var HcmClient = class _HcmClient {
1764
2020
  };
1765
2021
 
1766
2022
  // src/documents.ts
1767
- import * as fs7 from "fs";
2023
+ import * as fs8 from "fs";
1768
2024
  import * as fsp from "fs/promises";
1769
2025
  import * as os2 from "os";
1770
- import * as path4 from "path";
2026
+ import * as path5 from "path";
1771
2027
  var MIME_BY_EXT = {
1772
2028
  ".pdf": "application/pdf",
1773
2029
  ".docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
@@ -1783,13 +2039,13 @@ var MIME_BY_EXT = {
1783
2039
  ".webp": "image/webp"
1784
2040
  };
1785
2041
  function guessMimeType(filePath) {
1786
- return MIME_BY_EXT[path4.extname(filePath).toLowerCase()] ?? "application/octet-stream";
2042
+ return MIME_BY_EXT[path5.extname(filePath).toLowerCase()] ?? "application/octet-stream";
1787
2043
  }
1788
2044
  var CHAT_ATTACHMENT_CATEGORY = "ai-conversation";
1789
2045
  async function uploadDocument(http, filePath, storageCategory = CHAT_ATTACHMENT_CATEGORY) {
1790
2046
  const abs = expandHome(filePath);
1791
2047
  const buf = await fsp.readFile(abs);
1792
- const fileName = path4.basename(abs);
2048
+ const fileName = path5.basename(abs);
1793
2049
  const form = new FormData();
1794
2050
  form.append("file", new Blob([buf], { type: guessMimeType(abs) }), fileName);
1795
2051
  form.append("storageCategory", storageCategory);
@@ -1804,7 +2060,7 @@ async function uploadDocument(http, filePath, storageCategory = CHAT_ATTACHMENT_
1804
2060
  };
1805
2061
  }
1806
2062
  function defaultDownloadDir() {
1807
- return path4.join(os2.homedir(), "Downloads", "hcm");
2063
+ return path5.join(os2.homedir(), "Downloads", "hcm");
1808
2064
  }
1809
2065
  function absoluteDownloadUrl(apiBase, url) {
1810
2066
  if (!apiBase || !url.startsWith("/")) return url;
@@ -1818,20 +2074,20 @@ async function downloadDocument(http, ref, destPath) {
1818
2074
  let dir;
1819
2075
  let nameSource;
1820
2076
  const expanded = destPath ? expandHome(destPath) : void 0;
1821
- if (expanded && (expanded.endsWith(path4.sep) || isExistingDir(expanded))) {
2077
+ if (expanded && (expanded.endsWith(path5.sep) || isExistingDir(expanded))) {
1822
2078
  dir = expanded;
1823
2079
  nameSource = rawName;
1824
2080
  } else if (expanded) {
1825
- dir = path4.dirname(expanded);
1826
- nameSource = path4.basename(expanded);
2081
+ dir = path5.dirname(expanded);
2082
+ nameSource = path5.basename(expanded);
1827
2083
  } else {
1828
2084
  dir = defaultDownloadDir();
1829
2085
  nameSource = rawName;
1830
2086
  }
1831
2087
  const finalName = safeBasename(nameSource, ref.documentId);
1832
- let target = path4.join(dir, finalName);
1833
- const resolvedDir = path4.resolve(dir);
1834
- if (path4.resolve(target) !== path4.join(resolvedDir, finalName)) {
2088
+ let target = path5.join(dir, finalName);
2089
+ const resolvedDir = path5.resolve(dir);
2090
+ if (path5.resolve(target) !== path5.join(resolvedDir, finalName)) {
1835
2091
  throw new Error(`\u4E0B\u8F7D\u8DEF\u5F84\u8D8A\u754C\uFF1A${target} \u4E0D\u5728 ${resolvedDir} \u5185`);
1836
2092
  }
1837
2093
  await fsp.mkdir(dir, { recursive: true });
@@ -1840,10 +2096,10 @@ async function downloadDocument(http, ref, destPath) {
1840
2096
  return target;
1841
2097
  }
1842
2098
  function expandHome(p) {
1843
- return p.startsWith("~") ? path4.join(os2.homedir(), p.slice(1)) : path4.resolve(p);
2099
+ return p.startsWith("~") ? path5.join(os2.homedir(), p.slice(1)) : path5.resolve(p);
1844
2100
  }
1845
2101
  function safeBasename(rawName, documentId) {
1846
- const base = path4.basename(rawName.replace(/\\/g, "/"));
2102
+ const base = path5.basename(rawName.replace(/\\/g, "/"));
1847
2103
  if (!base || base === "." || base === ".." || base.includes("/")) {
1848
2104
  return documentId ? `${documentId}.bin` : "download.bin";
1849
2105
  }
@@ -1851,19 +2107,19 @@ function safeBasename(rawName, documentId) {
1851
2107
  }
1852
2108
  function isExistingDir(p) {
1853
2109
  try {
1854
- return fs7.statSync(p).isDirectory();
2110
+ return fs8.statSync(p).isDirectory();
1855
2111
  } catch {
1856
2112
  return false;
1857
2113
  }
1858
2114
  }
1859
2115
  function dedupePath(target) {
1860
- if (!fs7.existsSync(target)) return target;
1861
- const dir = path4.dirname(target);
1862
- const ext = path4.extname(target);
1863
- const base = path4.basename(target, ext);
2116
+ if (!fs8.existsSync(target)) return target;
2117
+ const dir = path5.dirname(target);
2118
+ const ext = path5.extname(target);
2119
+ const base = path5.basename(target, ext);
1864
2120
  for (let i = 1; ; i++) {
1865
- const candidate = path4.join(dir, `${base} (${i})${ext}`);
1866
- if (!fs7.existsSync(candidate)) return candidate;
2121
+ const candidate = path5.join(dir, `${base} (${i})${ext}`);
2122
+ if (!fs8.existsSync(candidate)) return candidate;
1867
2123
  }
1868
2124
  }
1869
2125
  function parseFilenameFromDisposition(disposition) {
@@ -1885,9 +2141,9 @@ function toJson(value) {
1885
2141
  }
1886
2142
 
1887
2143
  // src/output/yaml.ts
1888
- import yaml6 from "js-yaml";
2144
+ import yaml7 from "js-yaml";
1889
2145
  function toYaml(value) {
1890
- return yaml6.dump(value, { indent: 2, lineWidth: -1 });
2146
+ return yaml7.dump(value, { indent: 2, lineWidth: -1 });
1891
2147
  }
1892
2148
 
1893
2149
  // src/output/table.ts
@@ -1990,6 +2246,14 @@ async function loginClientCredentials(input) {
1990
2246
  const ttlSeconds = expires_in ?? 3600;
1991
2247
  const expiresAt = new Date(Date.now() + ttlSeconds * 1e3).toISOString();
1992
2248
  const scopes = (scope ?? "").split(/\s+/).filter(Boolean);
2249
+ let principal;
2250
+ if (input.expectedTenantId !== void 0) {
2251
+ const info = await input.httpClient.get(`${input.endpoint}/api/auth/info`, {
2252
+ headers: { Authorization: `Bearer ${access_token}` }
2253
+ });
2254
+ principal = toPrincipal(info.data);
2255
+ assertExpectedTenant(principal, input.expectedTenantId);
2256
+ }
1993
2257
  const store = new TokenStore(input.profile);
1994
2258
  const accessTokenRef = await store.setAccessToken(access_token);
1995
2259
  const refreshTokenRef = refresh_token ? await store.setRefreshToken(refresh_token) : void 0;
@@ -2002,7 +2266,7 @@ async function loginClientCredentials(input) {
2002
2266
  ttlSeconds
2003
2267
  };
2004
2268
  await store.writeMeta(record);
2005
- return { record };
2269
+ return { record, ...principal ? { principal } : {} };
2006
2270
  }
2007
2271
 
2008
2272
  // src/auth/pat.ts
@@ -2011,6 +2275,7 @@ async function loginPat(input) {
2011
2275
  headers: { Authorization: `Bearer ${input.pat}` }
2012
2276
  });
2013
2277
  const scopes = resp.data?.scopes ?? [];
2278
+ assertExpectedTenant(toPrincipal(resp.data), input.expectedTenantId);
2014
2279
  const store = new TokenStore(input.profile);
2015
2280
  const accessTokenRef = await store.setAccessToken(input.pat);
2016
2281
  const expiresAt = new Date(Date.now() + 365 * 24 * 3600 * 1e3).toISOString();
@@ -2037,6 +2302,7 @@ async function loginPairing(input) {
2037
2302
  }
2038
2303
  const ttlSeconds = expiresIn ?? DEFAULT_SESSION_TTL_SECONDS;
2039
2304
  const expiresAt = new Date(Date.now() + ttlSeconds * 1e3).toISOString();
2305
+ assertExpectedTenant(toPrincipal(user), input.expectedTenantId);
2040
2306
  const store = new TokenStore(input.profile);
2041
2307
  const accessTokenRef = await store.setAccessToken(token);
2042
2308
  const record = {
@@ -2057,6 +2323,255 @@ function toOrigin(raw) {
2057
2323
  return url.origin;
2058
2324
  }
2059
2325
 
2326
+ // src/auth/cli-authorization.ts
2327
+ import axios2 from "axios";
2328
+ import { setTimeout as delay } from "timers/promises";
2329
+ var CLI_AUTHORIZE_PATH = "/api/auth/cli/authorize";
2330
+ var CLI_EXCHANGE_PATH = "/api/auth/cli/exchange";
2331
+ var CLI_VERIFICATION_PATH = "/cli/authorize";
2332
+ function protocol(message) {
2333
+ return new CliError({
2334
+ code: "PROTOCOL_UNSUPPORTED" /* PROTOCOL_UNSUPPORTED */,
2335
+ message,
2336
+ context: { nextStep: "\u68C0\u67E5\u540E\u7AEF CLI \u6388\u6743\u63A5\u53E3\u7248\u672C\uFF1B\u672C\u6B21\u6CA1\u6709\u4FDD\u5B58\u767B\u5F55\u51ED\u636E\u3002" }
2337
+ });
2338
+ }
2339
+ function cliAuthorizationExpired() {
2340
+ return new CliError({
2341
+ code: "AUTH_EXPIRED" /* AUTH_EXPIRED */,
2342
+ message: "\u767B\u5F55\u6388\u6743\u7B49\u5F85\u5DF2\u5230\u671F\uFF0C\u672C\u6B21\u6CA1\u6709\u5B8C\u6210\u767B\u5F55\u3002",
2343
+ context: { nextStep: "\u91CD\u65B0\u8FD0\u884C hcm login \u53D1\u8D77\u65B0\u6388\u6743\u3002" }
2344
+ });
2345
+ }
2346
+ function checkCancelled(signal) {
2347
+ if (signal?.aborted) throw new CliError({ code: "AUTH_FAILED" /* AUTH_FAILED */, message: "\u767B\u5F55\u5DF2\u53D6\u6D88\u3002" });
2348
+ }
2349
+ var errorMessages = {
2350
+ authorization_pending: "\u7B49\u5F85\u6D4F\u89C8\u5668\u786E\u8BA4",
2351
+ slow_down: "\u670D\u52A1\u7AEF\u8981\u6C42\u653E\u6162\u8F6E\u8BE2",
2352
+ access_denied: "\u7528\u6237\u62D2\u7EDD\u4E86\u767B\u5F55\u6388\u6743",
2353
+ authorization_forbidden: "\u5F53\u524D\u8D26\u53F7\u4E0D\u80FD\u6279\u51C6\u6B64\u6388\u6743",
2354
+ account_not_eligible: "\u5F53\u524D\u8D26\u53F7\u4E0D\u5141\u8BB8\u767B\u5F55 CLI",
2355
+ expired_token: "\u6388\u6743\u5DF2\u8FC7\u671F",
2356
+ authorization_already_used: "\u6388\u6743\u5DF2\u88AB\u5151\u6362\uFF0C\u4E0D\u80FD\u91CD\u590D\u4F7F\u7528",
2357
+ invalid_grant: "\u6388\u6743\u51ED\u636E\u6216 PKCE \u6821\u9A8C\u5931\u8D25",
2358
+ invalid_request: "\u6388\u6743\u8BF7\u6C42\u4E0D\u7B26\u5408\u670D\u52A1\u7AEF\u5951\u7EA6",
2359
+ authorization_already_decided: "\u6388\u6743\u5DF2\u7ECF\u5904\u7406",
2360
+ identity_changed: "\u6D4F\u89C8\u5668\u8EAB\u4EFD\u5DF2\u53D8\u5316\uFF0C\u8BF7\u91CD\u65B0\u6388\u6743",
2361
+ rate_limited: "\u6388\u6743\u8BF7\u6C42\u8D85\u8FC7\u670D\u52A1\u7AEF\u9891\u7387\u9650\u5236",
2362
+ temporarily_unavailable: "\u6388\u6743\u670D\u52A1\u6682\u65F6\u4E0D\u53EF\u7528"
2363
+ };
2364
+ function unsupportedBackend(status) {
2365
+ return status === 404 || status === 401;
2366
+ }
2367
+ function safeCliAuthorizationError(error) {
2368
+ if (error instanceof CliError) return error;
2369
+ if (!axios2.isAxiosError(error)) return new CliError({ code: "NETWORK_ERROR" /* NETWORK_ERROR */, message: "\u767B\u5F55\u6388\u6743\u8BF7\u6C42\u5931\u8D25\uFF0C\u672A\u786E\u8BA4\u5B8C\u6210\u3002" });
2370
+ const status = error.response?.status;
2371
+ const rawCode = error.response?.data?.error?.code;
2372
+ const known = typeof rawCode === "string" && Object.hasOwn(errorMessages, rawCode) ? rawCode : void 0;
2373
+ const timedOut = !error.response && ["ECONNABORTED", "ETIMEDOUT"].includes(error.code ?? "");
2374
+ const unsupported = known === void 0 && unsupportedBackend(status);
2375
+ const code = unsupported ? "PROTOCOL_UNSUPPORTED" /* PROTOCOL_UNSUPPORTED */ : timedOut ? "TIMEOUT" /* TIMEOUT */ : status === 401 ? "AUTH_FAILED" /* AUTH_FAILED */ : status === 403 ? "SCOPE_FORBIDDEN" /* SCOPE_FORBIDDEN */ : status && status >= 500 ? "SERVER_ERROR" /* SERVER_ERROR */ : status ? "AUTH_FAILED" /* AUTH_FAILED */ : "NETWORK_ERROR" /* NETWORK_ERROR */;
2376
+ const interval = error.response?.data?.error?.details?.interval;
2377
+ return new CliError({
2378
+ code,
2379
+ message: unsupported ? "\u540E\u7AEF\u5C1A\u4E0D\u652F\u6301\u6D4F\u89C8\u5668/\u8BBE\u5907\u7801\u767B\u5F55\uFF0C\u9700\u8981\u5347\u7EA7\u670D\u52A1\u7AEF\u3002" : timedOut ? "\u767B\u5F55\u6388\u6743\u8BF7\u6C42\u8D85\u65F6\uFF0C\u5B8C\u6210\u72B6\u6001\u672A\u786E\u8BA4\u3002" : known ? errorMessages[known] : status === 401 ? "\u6388\u6743\u670D\u52A1\u8981\u6C42\u91CD\u65B0\u767B\u5F55\u3002" : "\u670D\u52A1\u7AEF\u8FD4\u56DE\u672A\u77E5\u6388\u6743\u9519\u8BEF\uFF0C\u5DF2\u505C\u6B62\u767B\u5F55\u3002",
2380
+ context: {
2381
+ ...status !== void 0 ? { status } : {},
2382
+ responseCode: known ?? "unrecognized_response",
2383
+ ...known === "slow_down" && typeof interval === "number" ? { interval } : {},
2384
+ ...timedOut ? { requestTimeout: true } : {},
2385
+ nextStep: unsupported ? "\u5347\u7EA7\u540E\u7AEF\u4E0E\u524D\u7AEF\uFF1B\u65E7\u7248\u53EF\u5728\u7F51\u9875\u201C\u547D\u4EE4\u884C\u5DE5\u5177\u201D\u751F\u6210\u914D\u5BF9\u7801\uFF0C\u518D\u8FD0\u884C hcm login --code <\u914D\u5BF9\u7801>\u3002" : known === "authorization_pending" || known === "slow_down" ? "\u7B49\u5F85\u540C\u4E00\u6388\u6743\u5B8C\u6210\u3002" : "\u6838\u5BF9\u6388\u6743\u72B6\u6001\u540E\u91CD\u65B0\u8FD0\u884C hcm login\uFF1B\u672C\u6B21\u4E0D\u4F1A\u81EA\u52A8\u91CD\u65B0\u53D1\u8D77\u6388\u6743\u3002"
2386
+ }
2387
+ });
2388
+ }
2389
+ function positive(value) {
2390
+ return typeof value === "number" && Number.isSafeInteger(value) && value > 0;
2391
+ }
2392
+ function text(value) {
2393
+ return typeof value === "string" && value.length > 0;
2394
+ }
2395
+ function validateCliAuthorizationUrl(raw, label) {
2396
+ let url;
2397
+ try {
2398
+ url = new URL(raw);
2399
+ } catch {
2400
+ throw protocol(`${label}\u4E0D\u662F\u6709\u6548\u7684\u5B8C\u6574 URL\u3002`);
2401
+ }
2402
+ const local = url.hostname === "localhost" || url.hostname === "127.0.0.1" || url.hostname === "[::1]";
2403
+ if (url.username || url.password || url.search || url.hash || url.protocol !== "https:" && !(url.protocol === "http:" && local)) {
2404
+ throw protocol(`${label}\u5FC5\u987B\u4F7F\u7528 HTTPS\uFF08\u672C\u673A\u5F00\u53D1\u53EF\u4F7F\u7528 loopback HTTP\uFF09\uFF0C\u4E14\u4E0D\u80FD\u5305\u542B\u51ED\u636E\u3001\u67E5\u8BE2\u4E32\u6216\u7247\u6BB5\u3002`);
2405
+ }
2406
+ return url;
2407
+ }
2408
+ async function post(input, path24, body, timeout = 3e4) {
2409
+ checkCancelled(input.signal);
2410
+ try {
2411
+ const { data } = await input.httpClient.post(`${input.endpoint.replace(/\/+$/, "")}${path24}`, body, {
2412
+ timeout,
2413
+ maxRedirects: 0,
2414
+ signal: input.signal,
2415
+ headers: { "Content-Type": "application/json" }
2416
+ });
2417
+ return data;
2418
+ } catch (error) {
2419
+ checkCancelled(input.signal);
2420
+ throw safeCliAuthorizationError(error);
2421
+ }
2422
+ }
2423
+ async function requestCliAuthorization(input) {
2424
+ validateCliAuthorizationUrl(input.endpoint, "\u540E\u7AEF\u5730\u5740");
2425
+ if (!input.tenantId.trim()) throw protocol("\u672A\u914D\u7F6E\u6388\u6743\u79DF\u6237\uFF0C\u4E0D\u80FD\u731C\u6D4B\u79DF\u6237\u53D1\u8D77\u767B\u5F55\u3002");
2426
+ const body = input.mode === "device" ? { mode: input.mode, tenantId: input.tenantId } : {
2427
+ mode: input.mode,
2428
+ tenantId: input.tenantId,
2429
+ redirectUri: input.redirectUri,
2430
+ state: input.state,
2431
+ codeChallenge: input.codeChallenge,
2432
+ codeChallengeMethod: input.codeChallengeMethod
2433
+ };
2434
+ const startedAt = Date.now();
2435
+ const data = await post(input, CLI_AUTHORIZE_PATH, body);
2436
+ checkCancelled(input.signal);
2437
+ if (!data || data.mode !== input.mode || !text(data.requestId) || !/^[A-Za-z0-9_-]{1,200}$/.test(data.requestId) || data.verificationPath !== CLI_VERIFICATION_PATH || !positive(data.expiresIn) || data.expiresIn > 900 || !text(data.expiresAt) || !data.expiresAt.includes("T") || !Number.isFinite(Date.parse(data.expiresAt))) {
2438
+ throw protocol("\u6388\u6743\u54CD\u5E94\u7F3A\u5C11\u6709\u6548 requestId / verificationPath / expiresIn / expiresAt\uFF0C\u672A\u5F00\u59CB\u7B49\u5F85\u3002");
2439
+ }
2440
+ const deadline = Math.min(startedAt + data.expiresIn * 1e3, Date.parse(data.expiresAt));
2441
+ if (deadline <= Date.now()) throw cliAuthorizationExpired();
2442
+ const common = { requestId: data.requestId, verificationPath: CLI_VERIFICATION_PATH, expiresIn: data.expiresIn, expiresAt: data.expiresAt, deadline };
2443
+ if (input.mode === "browser") return { ...common, mode: "browser" };
2444
+ if (!text(data.deviceCode) || !text(data.userCode) || !/^[A-Za-z0-9-]{1,64}$/.test(data.userCode) || !positive(data.interval) || data.interval > 60) {
2445
+ throw protocol("\u8BBE\u5907\u7801\u54CD\u5E94\u7F3A\u5C11\u6709\u6548 deviceCode / userCode / interval\uFF0C\u672A\u5F00\u59CB\u8F6E\u8BE2\u3002");
2446
+ }
2447
+ const result = { ...common, mode: "device", deviceCode: "", userCode: data.userCode, interval: data.interval };
2448
+ Object.defineProperty(result, "deviceCode", { value: data.deviceCode, enumerable: false });
2449
+ return result;
2450
+ }
2451
+ async function readLoginResponse(input, data, scheme) {
2452
+ const response = data;
2453
+ let token = text(response?.token) ? response.token : void 0;
2454
+ const retained = token !== void 0 && input.isRetainedToken?.(token) === true;
2455
+ let committed = false;
2456
+ let releasing;
2457
+ const close = () => {
2458
+ releasing ??= (async () => {
2459
+ if (committed || !token || retained) return;
2460
+ try {
2461
+ await input.httpClient.post(`${input.endpoint.replace(/\/+$/, "")}/api/auth/logout`, void 0, {
2462
+ headers: { Authorization: `Bearer ${token}` },
2463
+ timeout: 5e3,
2464
+ signal: AbortSignal.timeout(5e3),
2465
+ maxRedirects: 0
2466
+ });
2467
+ } catch {
2468
+ throw new CliError({
2469
+ code: "NETWORK_ERROR" /* NETWORK_ERROR */,
2470
+ message: "\u672C\u6B21\u65B0\u767B\u5F55\u4F1A\u8BDD\u7684\u670D\u52A1\u7AEF\u64A4\u9500\u672A\u786E\u8BA4\uFF0C\u4E0D\u80FD\u58F0\u79F0\u5B83\u5DF2\u5931\u6548\u3002",
2471
+ context: { cleanup: "unconfirmed", nextStep: "\u68C0\u67E5\u6388\u6743\u670D\u52A1\u4E0E\u7F51\u7EDC\uFF1B\u6B8B\u7559\u4F1A\u8BDD\u4ECD\u53EF\u80FD\u6709\u6548\uFF0C\u8054\u7CFB\u7BA1\u7406\u5458\u6838\u5B9E\u5E76\u64A4\u9500\u8BE5\u8D26\u53F7\u7684\u4F1A\u8BDD\u3002" }
2472
+ });
2473
+ } finally {
2474
+ token = void 0;
2475
+ }
2476
+ })();
2477
+ return releasing;
2478
+ };
2479
+ try {
2480
+ if (retained) throw protocol("\u6388\u6743\u670D\u52A1\u8FD4\u56DE\u4E86\u672C\u673A\u5DF2\u6709\u51ED\u636E\uFF0C\u62D2\u7EDD\u672C\u6B21\u767B\u5F55\uFF1B\u672A\u8986\u76D6\u6216\u6CE8\u9500\u65E7\u8EAB\u4EFD\u3002");
2481
+ const principal = toPrincipal(response?.user);
2482
+ const user = response?.user;
2483
+ if (!response || !token || !positive(response.expiresIn) || !Number.isFinite(new Date(Date.now() + response.expiresIn * 1e3).getTime()) || !user || !text(user.id ?? user.userId) || !text(user.username) || !["string", "number"].includes(typeof user.tenantId) || !principal?.userId || !principal.username || !principal.tenantId) {
2484
+ throw protocol("\u5151\u6362\u54CD\u5E94\u7F3A\u5C11\u6709\u6548 token / expiresIn / \u5B9E\u9645\u7528\u6237\u4E0E\u79DF\u6237\uFF0C\u672A\u4FDD\u5B58\u51ED\u636E\u3002");
2485
+ }
2486
+ assertExpectedTenant(principal, input.tenantId);
2487
+ checkCancelled(input.signal);
2488
+ const session = {
2489
+ scheme,
2490
+ principal,
2491
+ expiresIn: response.expiresIn,
2492
+ expiresAt: new Date(Date.now() + response.expiresIn * 1e3).toISOString()
2493
+ };
2494
+ Object.defineProperties(session, {
2495
+ accessToken: { enumerable: false, get: () => {
2496
+ if (!token) throw new Error("\u6388\u6743\u4F1A\u8BDD\u5DF2\u7ECF\u5173\u95ED");
2497
+ return token;
2498
+ } },
2499
+ complete: { enumerable: false, value: () => {
2500
+ committed = true;
2501
+ token = void 0;
2502
+ } },
2503
+ close: { enumerable: false, value: close }
2504
+ });
2505
+ return session;
2506
+ } catch (error) {
2507
+ const hadToken = Boolean(token);
2508
+ let cleanup = retained ? "retained_existing_session" : hadToken ? "confirmed" : "unavailable";
2509
+ try {
2510
+ await close();
2511
+ } catch {
2512
+ cleanup = "unconfirmed";
2513
+ }
2514
+ const failure = error instanceof CliError ? error : protocol("\u5151\u6362\u54CD\u5E94\u4E0D\u7B26\u5408\u6388\u6743\u5951\u7EA6\uFF0C\u672A\u4FDD\u5B58\u51ED\u636E\u3002");
2515
+ throw new CliError({
2516
+ code: failure.code,
2517
+ message: failure.message,
2518
+ context: {
2519
+ ...failure.context,
2520
+ cleanup,
2521
+ ...["unconfirmed", "unavailable"].includes(cleanup) ? { details: "\u670D\u52A1\u7AEF\u662F\u5426\u4ECD\u6709\u65B0\u4F1A\u8BDD\u672A\u786E\u8BA4\uFF1B\u672A\u53D6\u5F97\u53EF\u56DE\u6536\u51ED\u636E\u6216\u64A4\u9500\u8BF7\u6C42\u5931\u8D25\u3002" } : {}
2522
+ }
2523
+ });
2524
+ }
2525
+ }
2526
+ async function exchangeBrowserAuthorization(input) {
2527
+ const remaining = input.deadline - Date.now();
2528
+ if (remaining <= 0) throw cliAuthorizationExpired();
2529
+ const data = await post(input, CLI_EXCHANGE_PATH, {
2530
+ authorizationCode: input.authorizationCode,
2531
+ codeVerifier: input.codeVerifier,
2532
+ redirectUri: input.redirectUri
2533
+ }, Math.min(3e4, remaining));
2534
+ return readLoginResponse(input, data, "browser");
2535
+ }
2536
+ async function pollDeviceAuthorization(input) {
2537
+ let serverInterval = input.authorization.interval * 1e3;
2538
+ let interval = serverInterval;
2539
+ while (Date.now() < input.authorization.deadline) {
2540
+ checkCancelled(input.signal);
2541
+ try {
2542
+ await delay(Math.min(interval, input.authorization.deadline - Date.now()), void 0, { signal: input.signal });
2543
+ } catch {
2544
+ checkCancelled(input.signal);
2545
+ throw cliAuthorizationExpired();
2546
+ }
2547
+ const remaining = input.authorization.deadline - Date.now();
2548
+ if (remaining <= 0) break;
2549
+ try {
2550
+ const data = await post(input, CLI_EXCHANGE_PATH, { deviceCode: input.authorization.deviceCode }, Math.min(3e4, remaining));
2551
+ return await readLoginResponse(input, data, "device");
2552
+ } catch (error) {
2553
+ const failure = safeCliAuthorizationError(error);
2554
+ const status = failure.context?.status;
2555
+ const code = failure.context?.responseCode;
2556
+ if (status === 400 && code === "authorization_pending") continue;
2557
+ if (status === 400 && code === "slow_down") {
2558
+ const seconds = failure.context?.interval;
2559
+ if (!positive(seconds) || seconds > 900 || seconds * 1e3 < serverInterval) throw protocol("slow_down \u672A\u8FD4\u56DE\u6709\u6548\u4E14\u4E0D\u51CF\u901F\u7684 interval\uFF0C\u5DF2\u505C\u6B62\u8F6E\u8BE2\u3002");
2560
+ serverInterval = seconds * 1e3;
2561
+ interval = Math.max(interval, serverInterval);
2562
+ continue;
2563
+ }
2564
+ if (failure.context?.requestTimeout === true) {
2565
+ interval = Math.min(interval * 2, Math.max(1, input.authorization.deadline - Date.now()));
2566
+ input.onTimeout?.();
2567
+ continue;
2568
+ }
2569
+ throw failure;
2570
+ }
2571
+ }
2572
+ throw cliAuthorizationExpired();
2573
+ }
2574
+
2060
2575
  // src/auth/change-password.ts
2061
2576
  var PASSWORD_CHANGE_REQUIRED = "AUTH_PASSWORD_CHANGE_REQUIRED";
2062
2577
  function detectPasswordChangeChallenge(err) {
@@ -2094,16 +2609,203 @@ async function adminResetPassword(http, input) {
2094
2609
  return payload;
2095
2610
  }
2096
2611
 
2097
- // src/meta/action-effect.ts
2098
- var EFFECT_READ_ONLY = "READ_ONLY";
2099
- var EFFECT_WRITES = "WRITES";
2100
- var EFFECT_UNKNOWN = "UNKNOWN";
2101
- function classifyEffect(effect) {
2102
- if (effect === void 0) return "absent";
2103
- if (effect === EFFECT_READ_ONLY) return "read-only";
2104
- if (effect === EFFECT_WRITES) return "writes";
2105
- if (effect === EFFECT_UNKNOWN) return "declared-unknown";
2106
- return "unrecognized-effect";
2612
+ // src/auth/impersonation.ts
2613
+ import axios4 from "axios";
2614
+
2615
+ // src/auth/impersonation-lifecycle.ts
2616
+ import axios3 from "axios";
2617
+ var pending = /* @__PURE__ */ new Set();
2618
+ var IMPERSONATION_CLEANUP_TIMEOUT_MS = 5e3;
2619
+ function registerImpersonationSession(endpoint, accessToken, probeQuotaRelease) {
2620
+ let token = accessToken;
2621
+ const prefix = `${accessToken.slice(0, 8)}***`;
2622
+ let result;
2623
+ const release = () => {
2624
+ result ??= (async () => {
2625
+ try {
2626
+ await axios3.post("/api/auth/logout", void 0, {
2627
+ baseURL: endpoint,
2628
+ headers: { Authorization: `Bearer ${token}` },
2629
+ timeout: IMPERSONATION_CLEANUP_TIMEOUT_MS,
2630
+ signal: AbortSignal.timeout(IMPERSONATION_CLEANUP_TIMEOUT_MS),
2631
+ maxRedirects: 0
2632
+ });
2633
+ pending.delete(release);
2634
+ await warnIfQuotaStillHeld(probeQuotaRelease, prefix);
2635
+ return void 0;
2636
+ } catch (error) {
2637
+ const status = axios3.isAxiosError(error) ? error.response?.status : void 0;
2638
+ return new CliError({
2639
+ code: "NETWORK_ERROR" /* NETWORK_ERROR */,
2640
+ message: `\u4EE3\u7406\u4F1A\u8BDD\u6E05\u7406\u672A\u786E\u8BA4${status === void 0 ? "\uFF08\u7F51\u7EDC\u5931\u8D25\u6216\u8D85\u65F6\uFF09" : `\uFF08HTTP ${status}\uFF09`}\uFF1B\u670D\u52A1\u7AEF\u4EE3\u7406\u914D\u989D\u53EF\u80FD\u4ECD\u88AB\u5360\u7528`,
2641
+ context: {
2642
+ cleanup: "unconfirmed",
2643
+ nextStep: "\u68C0\u67E5\u540E\u7AEF /api/auth/logout \u7684\u5355\u679A\u4EE3\u7406\u91CA\u653E\u80FD\u529B\u4E0E\u7F51\u7EDC\uFF1B\u672C\u6B21\u4E0D\u4F1A\u91CD\u8BD5\u7B7E\u53D1\u6216\u6CE8\u9500\u7BA1\u7406\u5458\uFF0C\u6B8B\u7559\u4F1A\u8BDD\u7B49\u5F85\u670D\u52A1\u7AEF\u8FC7\u671F"
2644
+ }
2645
+ });
2646
+ } finally {
2647
+ token = void 0;
2648
+ }
2649
+ })();
2650
+ return result;
2651
+ };
2652
+ pending.add(release);
2653
+ return async () => {
2654
+ const error = await release();
2655
+ if (error) throw error;
2656
+ };
2657
+ }
2658
+ async function warnIfQuotaStillHeld(probe, tokenPrefix) {
2659
+ if (!probe) return;
2660
+ let stillHeld = false;
2661
+ try {
2662
+ stillHeld = await probe(tokenPrefix);
2663
+ } catch {
2664
+ return;
2665
+ }
2666
+ if (!stillHeld) return;
2667
+ process.stderr.write(
2668
+ `\u26A0\uFE0F \u8FD9\u4E2A\u540E\u7AEF\u6CE8\u9500\u4EE3\u7406\u4F1A\u8BDD\u540E\u6CA1\u6709\u91CA\u653E\u914D\u989D\uFF08${tokenPrefix} \u4ECD\u5728 /api/admin/impersonation/active\uFF09\u3002
2669
+ \u591A\u534A\u672A\u542B core#2475\uFF1A\u672C\u6B21\u8FDE\u63A5\u6700\u591A\u80FD\u4EE3\u7406 3 \u6B21\uFF0C\u4E4B\u540E\u4F1A\u649E\u4E0A\u9650\u3002\u8981\u8FDE\u7EED\u7528\uFF0C\u5148\u5347\u7EA7\u540E\u7AEF\u3002
2670
+ `
2671
+ );
2672
+ }
2673
+ function hasPendingImpersonationSessions() {
2674
+ return pending.size > 0;
2675
+ }
2676
+ async function releasePendingImpersonationSessions() {
2677
+ const sessions = [...pending];
2678
+ const results = await Promise.all(sessions.map((release) => release()));
2679
+ for (const session of sessions) pending.delete(session);
2680
+ return results.filter((error) => error !== void 0);
2681
+ }
2682
+
2683
+ // src/auth/impersonation.ts
2684
+ var AUTH_SESSION_INFO_PATH = "/api/auth/info";
2685
+ var IMPERSONATION_START_PATH = "/api/admin/impersonation/start";
2686
+ var IMPERSONATION_ACTIVE_PATH = "/api/admin/impersonation/active";
2687
+ var UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
2688
+ function protocolError(message) {
2689
+ return new CliError({
2690
+ code: "PROTOCOL_UNSUPPORTED" /* PROTOCOL_UNSUPPORTED */,
2691
+ message,
2692
+ context: { nextStep: "\u68C0\u67E5\u540E\u7AEF\u8BA4\u8BC1\u63A5\u53E3\u54CD\u5E94\uFF1B\u672C\u6B21\u547D\u4EE4\u5DF2\u505C\u6B62\uFF0C\u6CA1\u6709\u4F7F\u7528\u7BA1\u7406\u5458\u8EAB\u4EFD\u6267\u884C\u4E1A\u52A1\u8BF7\u6C42" }
2693
+ });
2694
+ }
2695
+ async function readSessionPrincipal(http) {
2696
+ const { data } = await http.get(AUTH_SESSION_INFO_PATH);
2697
+ if (!data || typeof data.userId !== "string" || !data.userId || typeof data.username !== "string" || !data.username || !["string", "number"].includes(typeof data.tenantId) || String(data.tenantId) === "") {
2698
+ throw protocolError("\u8BA4\u8BC1\u63A5\u53E3\u672A\u8FD4\u56DE\u5B8C\u6574 userId / username / tenantId\uFF0C\u65E0\u6CD5\u786E\u8BA4\u672C\u6B21\u8EAB\u4EFD");
2699
+ }
2700
+ return {
2701
+ userId: data.userId,
2702
+ username: data.username,
2703
+ tenantId: String(data.tenantId),
2704
+ roles: Array.isArray(data.roles) && data.roles.every((role) => typeof role === "string") ? data.roles : void 0,
2705
+ impersonated: data.impersonated === true,
2706
+ actSub: data.actSub
2707
+ };
2708
+ }
2709
+ async function startImpersonation(input) {
2710
+ if (input.actor.impersonation) {
2711
+ throw new CliError({
2712
+ code: "SCOPE_FORBIDDEN" /* SCOPE_FORBIDDEN */,
2713
+ message: "\u4EE3\u7406\u4F1A\u8BDD\u7981\u6B62\u518D\u6B21\u53D1\u8D77\u4EE3\u7406\uFF08\u7981\u6B62\u94FE\u5F0F\u4EE3\u7406\uFF09",
2714
+ context: { nextStep: `\u4F7F\u7528\u539F\u59CB\u7BA1\u7406\u5458\u767B\u5F55\u8EAB\u4EFD\u91CD\u65B0\u6267\u884C --as ${input.target}` }
2715
+ });
2716
+ }
2717
+ const http = axios4.create({
2718
+ baseURL: input.actor.endpoint,
2719
+ timeout: 3e4,
2720
+ headers: { Authorization: `Bearer ${input.accessToken}` }
2721
+ });
2722
+ const principal = await readSessionPrincipal(http);
2723
+ if (input.actorUsername && principal.username !== input.actorUsername) {
2724
+ throw new CliError({
2725
+ code: "IDENTITY_NOT_IN_ENV" /* IDENTITY_NOT_IN_ENV */,
2726
+ message: `\u5F53\u524D token \u7684\u5B9E\u9645\u7528\u6237\u540D '${principal.username}' \u4E0E\u64CD\u4F5C\u8005 '${input.actorUsername}' \u4E0D\u4E00\u81F4\uFF0C\u5DF2\u505C\u6B62\u4EE3\u7406`,
2727
+ context: { nextStep: `hcm login --env ${input.actor.env} \u91CD\u65B0\u767B\u5F55\u7BA1\u7406\u5458\u8EAB\u4EFD` }
2728
+ });
2729
+ }
2730
+ if (principal.tenantId !== input.actor.tenantId) {
2731
+ throw new CliError({
2732
+ code: "IDENTITY_NOT_IN_ENV" /* IDENTITY_NOT_IN_ENV */,
2733
+ message: `\u5F53\u524D token \u5C5E\u4E8E\u79DF\u6237 '${principal.tenantId}'\uFF0C\u9884\u671F '${input.actor.tenantId}'\uFF0C\u5DF2\u505C\u6B62\u4EE3\u7406`,
2734
+ context: { nextStep: `hcm login --env ${input.actor.env} \u91CD\u65B0\u767B\u5F55\u6B63\u786E\u79DF\u6237` }
2735
+ });
2736
+ }
2737
+ if (principal.impersonated || principal.actSub != null) {
2738
+ throw new CliError({
2739
+ code: "SCOPE_FORBIDDEN" /* SCOPE_FORBIDDEN */,
2740
+ message: "\u5F53\u524D token \u662F\u4EE3\u7406\u4F1A\u8BDD\uFF0C\u7981\u6B62\u94FE\u5F0F\u4EE3\u7406",
2741
+ context: { nextStep: `hcm login --env ${input.actor.env} \u4F7F\u7528\u539F\u59CB\u7BA1\u7406\u5458\u8EAB\u4EFD\u767B\u5F55` }
2742
+ });
2743
+ }
2744
+ if (!principal.roles?.includes("admin.system")) {
2745
+ throw new CliError({
2746
+ code: "SCOPE_FORBIDDEN" /* SCOPE_FORBIDDEN */,
2747
+ message: `\u76EE\u6807 '${input.targetLabel ?? input.target}' \u6CA1\u6709\u53EF\u7528\u672C\u673A token\uFF1B\u5F53\u524D\u8EAB\u4EFD '${input.actor.identity}' ${principal.roles ? "\u4E0D\u5177\u5907" : "\u672A\u8FD4\u56DE\u53EF\u6838\u5B9E\u7684"} admin.system\uFF0C\u4E0D\u80FD\u5373\u65F6\u4EE3\u7406`,
2748
+ context: { nextStep: `hcm login --env ${input.actor.env} \u767B\u5F55\u76EE\u6807\u7528\u6237\uFF0C\u6216 hcm identity use <\u8BE5\u73AF\u5883\u7684\u7BA1\u7406\u5458\u8EAB\u4EFD> \u540E\u91CD\u8BD5` }
2749
+ });
2750
+ }
2751
+ let targetUserId = input.target;
2752
+ if (!UUID.test(targetUserId)) {
2753
+ const { data: data2 } = await http.post("/api/models/User/list/dsl", {
2754
+ filter: { field: "name", op: "eq", value: input.target },
2755
+ fields: ["id", "name"],
2756
+ page: 0,
2757
+ size: 2
2758
+ });
2759
+ if (!Array.isArray(data2?.content)) throw protocolError("User \u67E5\u8BE2\u672A\u8FD4\u56DE content \u6570\u7EC4\uFF0C\u65E0\u6CD5\u89E3\u6790\u76EE\u6807\u7528\u6237");
2760
+ if (data2.content.length !== 1 || data2.totalElements !== void 0 && data2.totalElements !== 1) {
2761
+ throw new CliError({
2762
+ code: "IDENTITY_NOT_FOUND" /* IDENTITY_NOT_FOUND */,
2763
+ message: `\u7528\u6237\u540D '${input.target}' \u5FC5\u987B\u552F\u4E00\u547D\u4E2D\uFF1B\u672C\u6B21\u8FD4\u56DE ${data2.content.length} \u884C\uFF0C\u65E0\u6CD5\u4EE3\u7406`,
2764
+ context: { nextStep: "\u6838\u5BF9\u5F53\u524D\u79DF\u6237\u4E0E\u7528\u6237\u540D\uFF0C\u6216\u7528 --as <\u76EE\u6807\u7528\u6237 UUID> \u7CBE\u786E\u6307\u5B9A" }
2765
+ });
2766
+ }
2767
+ const row = data2.content[0];
2768
+ if (!row || typeof row.id !== "string" || !UUID.test(row.id) || row.name !== input.target) {
2769
+ throw protocolError("User \u67E5\u8BE2\u8FD4\u56DE\u7684 id / name \u4E0E\u76EE\u6807\u4E0D\u4E00\u81F4\uFF0C\u5DF2\u505C\u6B62\u4EE3\u7406");
2770
+ }
2771
+ targetUserId = row.id;
2772
+ }
2773
+ const { data } = await http.post(IMPERSONATION_START_PATH, { targetUserId });
2774
+ if (data?.impersonationToken === input.accessToken) {
2775
+ throw protocolError("\u4EE3\u7406\u63A5\u53E3\u8FD4\u56DE\u4E86\u7BA1\u7406\u5458\u539F\u51ED\u636E\uFF0C\u5DF2\u62D2\u7EDD\u4F7F\u7528\u4E0E\u6CE8\u9500\u8BE5\u51ED\u636E");
2776
+ }
2777
+ const closeEphemeralSession = typeof data?.impersonationToken === "string" && data.impersonationToken ? registerImpersonationSession(input.actor.endpoint, data.impersonationToken, async (tokenPrefix) => {
2778
+ const { data: active } = await http.get(IMPERSONATION_ACTIVE_PATH);
2779
+ if (!Array.isArray(active)) return false;
2780
+ return active.some((row) => !!row && typeof row === "object" && row.tokenPrefix === tokenPrefix);
2781
+ }) : void 0;
2782
+ if (!data || typeof data.impersonationToken !== "string" || !data.impersonationToken || data.targetUser?.id !== targetUserId || typeof data.targetUser?.username !== "string" || !data.targetUser.username || typeof data.expiresAt !== "string" || !Number.isFinite(Date.parse(data.expiresAt)) || Date.parse(data.expiresAt) <= Date.now()) {
2783
+ const failure = protocolError("\u4EE3\u7406\u63A5\u53E3\u672A\u8FD4\u56DE\u6709\u6548 token / \u76EE\u6807\u7528\u6237 / expiresAt\uFF0C\u5DF2\u505C\u6B62\u672C\u6B21\u547D\u4EE4");
2784
+ try {
2785
+ await closeEphemeralSession?.();
2786
+ } catch (error) {
2787
+ throw new CliError({
2788
+ code: failure.code,
2789
+ message: failure.message,
2790
+ context: { ...failure.context, cleanup: "unconfirmed", details: error.message }
2791
+ });
2792
+ }
2793
+ throw failure;
2794
+ }
2795
+ const ctx = {
2796
+ env: input.actor.env,
2797
+ endpoint: input.actor.endpoint,
2798
+ tenantId: principal.tenantId,
2799
+ identity: input.targetLabel ?? input.target,
2800
+ impersonation: { actorIdentity: input.actor.identity, targetUserId, expiresAt: data.expiresAt }
2801
+ };
2802
+ Object.defineProperty(ctx, "ephemeralAccessToken", { value: data.impersonationToken, enumerable: false });
2803
+ Object.defineProperty(ctx, "closeEphemeralSession", { value: closeEphemeralSession, enumerable: false });
2804
+ process.stderr.write(
2805
+ `\u2192 \u8EAB\u4EFD ${ctx.identity} \u2192 ${data.targetUser.username}\uFF08\u7ECF\u7BA1\u7406\u5458 ${input.actor.identity} \u4EE3\u7406\uFF0CexpiresAt=${data.expiresAt}\uFF1B\u4EC5\u672C\u6B21\u8FDB\u7A0B\uFF09
2806
+ `
2807
+ );
2808
+ return ctx;
2107
2809
  }
2108
2810
 
2109
2811
  // src/chat/ws-client.ts
@@ -2172,10 +2874,10 @@ var WsClient = class {
2172
2874
  this.ws?.send(JSON.stringify({ type: "auth", token: tok }));
2173
2875
  };
2174
2876
  const onMessage = (data) => {
2175
- const text2 = data.toString();
2877
+ const text3 = data.toString();
2176
2878
  let parsed;
2177
2879
  try {
2178
- parsed = JSON.parse(text2);
2880
+ parsed = JSON.parse(text3);
2179
2881
  } catch {
2180
2882
  return;
2181
2883
  }
@@ -2287,10 +2989,10 @@ var WsClient = class {
2287
2989
  this.notifyDisconnect();
2288
2990
  };
2289
2991
  persistentOnMessage = (data) => {
2290
- const text2 = data.toString();
2992
+ const text3 = data.toString();
2291
2993
  let parsed;
2292
2994
  try {
2293
- parsed = JSON.parse(text2);
2995
+ parsed = JSON.parse(text3);
2294
2996
  } catch {
2295
2997
  return;
2296
2998
  }
@@ -2515,8 +3217,8 @@ function detectDelegationPause(resultData) {
2515
3217
  env2 = rd;
2516
3218
  }
2517
3219
  if (!env2 || env2.ok !== true) return false;
2518
- const text2 = [env2.summary, env2.data].filter((x) => typeof x === "string").join(" ");
2519
- return text2.includes("INTERACTION_REQUIRED") || text2.includes("CONFIRMATION_REQUIRED");
3220
+ const text3 = [env2.summary, env2.data].filter((x) => typeof x === "string").join(" ");
3221
+ return text3.includes("INTERACTION_REQUIRED") || text3.includes("CONFIRMATION_REQUIRED");
2520
3222
  }
2521
3223
  function resultText(resultData) {
2522
3224
  if (typeof resultData === "string") return resultData;
@@ -2527,13 +3229,13 @@ function resultText(resultData) {
2527
3229
  return "";
2528
3230
  }
2529
3231
  function detectDirectInteractionPending(resultData) {
2530
- const text2 = resultText(resultData).trimStart();
2531
- return text2.startsWith("CONFIRMATION_REQUIRED") || text2.startsWith("INTERACTION_REQUIRED");
3232
+ const text3 = resultText(resultData).trimStart();
3233
+ return text3.startsWith("CONFIRMATION_REQUIRED") || text3.startsWith("INTERACTION_REQUIRED");
2532
3234
  }
2533
3235
  function deriveNamelessToolLabel(resultData) {
2534
- const text2 = resultText(resultData);
2535
- if (text2.includes("catalog cache hit")) {
2536
- const m = text2.match(/工具\s+(\w+)/);
3236
+ const text3 = resultText(resultData);
3237
+ if (text3.includes("catalog cache hit")) {
3238
+ const m = text3.match(/工具\s+(\w+)/);
2537
3239
  return m ? `${m[1]} (\u7F13\u5B58\u547D\u4E2D)` : "\u7F13\u5B58\u547D\u4E2D";
2538
3240
  }
2539
3241
  return void 0;
@@ -2746,8 +3448,8 @@ async function oneShot(ws, prompt, opts = {}) {
2746
3448
  const agentKeyByCallId = /* @__PURE__ */ new Map();
2747
3449
  const sink = {
2748
3450
  // ROOT 段文本才是最终回答;specialist 子流文本(parent 非空)是中间产物,不计入 content。
2749
- onText(text2, parentToolUseId) {
2750
- if (parentToolUseId === null) content += text2;
3451
+ onText(text3, parentToolUseId) {
3452
+ if (parentToolUseId === null) content += text3;
2751
3453
  },
2752
3454
  onThinkingDelta() {
2753
3455
  },
@@ -2819,10 +3521,10 @@ async function oneShot(ws, prompt, opts = {}) {
2819
3521
  }
2820
3522
 
2821
3523
  // src/chat/conversation-state.ts
2822
- import * as fs8 from "fs/promises";
3524
+ import * as fs9 from "fs/promises";
2823
3525
  async function loadConversationState(profile) {
2824
3526
  try {
2825
- const raw = await fs8.readFile(conversationStateFile(profile), "utf-8");
3527
+ const raw = await fs9.readFile(conversationStateFile(profile), "utf-8");
2826
3528
  return JSON.parse(raw);
2827
3529
  } catch (e) {
2828
3530
  if (e.code === "ENOENT") return null;
@@ -2830,8 +3532,8 @@ async function loadConversationState(profile) {
2830
3532
  }
2831
3533
  }
2832
3534
  async function saveConversationState(profile, state) {
2833
- await fs8.mkdir(profileDir(profile), { recursive: true });
2834
- await fs8.writeFile(
3535
+ await fs9.mkdir(profileDir(profile), { recursive: true });
3536
+ await fs9.writeFile(
2835
3537
  conversationStateFile(profile),
2836
3538
  JSON.stringify({ ...state, updatedAt: (/* @__PURE__ */ new Date()).toISOString() }, null, 2)
2837
3539
  );
@@ -3018,8 +3720,8 @@ function primitiveOrNull(value) {
3018
3720
 
3019
3721
  // src/mini/project.ts
3020
3722
  import * as crypto from "crypto";
3021
- import * as fs9 from "fs/promises";
3022
- import * as path5 from "path";
3723
+ import * as fs10 from "fs/promises";
3724
+ import * as path6 from "path";
3023
3725
 
3024
3726
  // src/mini/templates.ts
3025
3727
  var DEFAULT_MULTI_PAGE_MODEL = "Employee";
@@ -4355,7 +5057,7 @@ var MINI_SDK_ACTION_CALL_PATTERN = /\bhcm\.action\s*\(\s*\{[\s\S]*?\bmodel\s*:\s
4355
5057
  async function initMiniAppProject(args) {
4356
5058
  const appCode = normalizeAppCode(args.appCode);
4357
5059
  const workspaceKey = normalizeWorkspaceKey(args.workspaceKey);
4358
- const targetDir = path5.resolve(args.targetDir);
5060
+ const targetDir = path6.resolve(args.targetDir);
4359
5061
  const remotePrefix = miniRemotePrefix(appCode);
4360
5062
  const templateKind = args.templateKind ?? "dashboard";
4361
5063
  const files = buildMiniAppTemplateFiles2({
@@ -4375,9 +5077,9 @@ async function initMiniAppProject(args) {
4375
5077
  files.map((file) => file.localPath).concat([MINI_CONTEXT_FILE]),
4376
5078
  !!args.force
4377
5079
  );
4378
- await fs9.mkdir(targetDir, { recursive: true });
5080
+ await fs10.mkdir(targetDir, { recursive: true });
4379
5081
  for (const file of files) {
4380
- await writeText(path5.join(targetDir, file.localPath), file.content);
5082
+ await writeText(path6.join(targetDir, file.localPath), file.content);
4381
5083
  }
4382
5084
  const context = {
4383
5085
  kind: MINI_CONTEXT_KIND,
@@ -4390,7 +5092,7 @@ async function initMiniAppProject(args) {
4390
5092
  profile: args.profile,
4391
5093
  updatedAt: (/* @__PURE__ */ new Date()).toISOString()
4392
5094
  };
4393
- await writeJson(path5.join(targetDir, MINI_CONTEXT_FILE), context);
5095
+ await writeJson(path6.join(targetDir, MINI_CONTEXT_FILE), context);
4394
5096
  const localFiles = await readLocalMiniFiles(targetDir);
4395
5097
  await writeMiniState(targetDir, context, [], /* @__PURE__ */ new Map());
4396
5098
  return {
@@ -4403,7 +5105,7 @@ async function initMiniAppProject(args) {
4403
5105
  async function pullMiniAppProject(args) {
4404
5106
  const appCode = normalizeAppCode(args.appCode);
4405
5107
  const workspaceKey = normalizeWorkspaceKey(args.workspaceKey);
4406
- const targetDir = path5.resolve(args.targetDir);
5108
+ const targetDir = path6.resolve(args.targetDir);
4407
5109
  const remotePrefix = miniRemotePrefix(appCode);
4408
5110
  const remoteFiles = await loadRemoteMiniAppFiles(args.http, workspaceKey, appCode);
4409
5111
  if (!remoteFiles.length) {
@@ -4422,9 +5124,9 @@ async function pullMiniAppProject(args) {
4422
5124
  pullFiles.map((file) => file.localPath).concat([MINI_CONTEXT_FILE]),
4423
5125
  !!args.force
4424
5126
  );
4425
- await fs9.mkdir(targetDir, { recursive: true });
5127
+ await fs10.mkdir(targetDir, { recursive: true });
4426
5128
  for (const file of pullFiles) {
4427
- await writeText(path5.join(targetDir, file.localPath), file.content);
5129
+ await writeText(path6.join(targetDir, file.localPath), file.content);
4428
5130
  }
4429
5131
  const context = {
4430
5132
  kind: MINI_CONTEXT_KIND,
@@ -4437,7 +5139,7 @@ async function pullMiniAppProject(args) {
4437
5139
  profile: args.profile,
4438
5140
  updatedAt: (/* @__PURE__ */ new Date()).toISOString()
4439
5141
  };
4440
- await writeJson(path5.join(targetDir, MINI_CONTEXT_FILE), context);
5142
+ await writeJson(path6.join(targetDir, MINI_CONTEXT_FILE), context);
4441
5143
  const localFiles = await readLocalMiniFiles(targetDir);
4442
5144
  const remoteByLocalPath = new Map(
4443
5145
  pullFiles.map((file) => [file.localPath, file.remote])
@@ -4452,14 +5154,14 @@ async function pullMiniAppProject(args) {
4452
5154
  };
4453
5155
  }
4454
5156
  async function getMiniStatus(rootDir) {
4455
- const root = path5.resolve(rootDir);
5157
+ const root = path6.resolve(rootDir);
4456
5158
  const context = await readMiniContext(root);
4457
5159
  const manifest2 = await readPullManifest(root);
4458
5160
  const localFiles = await readLocalMiniFiles(root);
4459
5161
  return computeStatusEntries(context, manifest2, localFiles);
4460
5162
  }
4461
5163
  async function validateMiniProject(rootDir) {
4462
- const root = path5.resolve(rootDir);
5164
+ const root = path6.resolve(rootDir);
4463
5165
  const errors = [];
4464
5166
  const warnings = [];
4465
5167
  let context = null;
@@ -4468,10 +5170,10 @@ async function validateMiniProject(rootDir) {
4468
5170
  } catch (e) {
4469
5171
  errors.push(e.message);
4470
5172
  }
4471
- const manifestPath = path5.join(root, "manifest.json");
5173
+ const manifestPath = path6.join(root, "manifest.json");
4472
5174
  let manifest2 = null;
4473
5175
  try {
4474
- manifest2 = JSON.parse(await fs9.readFile(manifestPath, "utf-8"));
5176
+ manifest2 = JSON.parse(await fs10.readFile(manifestPath, "utf-8"));
4475
5177
  } catch (e) {
4476
5178
  if (e.code === "ENOENT") {
4477
5179
  errors.push("manifest.json is required");
@@ -4499,7 +5201,7 @@ async function validateMiniProject(rootDir) {
4499
5201
  };
4500
5202
  }
4501
5203
  async function pushMiniAppProject(args) {
4502
- const root = path5.resolve(args.rootDir);
5204
+ const root = path6.resolve(args.rootDir);
4503
5205
  const validation = await validateMiniProject(root);
4504
5206
  if (!validation.valid) {
4505
5207
  throw new CliError({
@@ -4555,7 +5257,7 @@ async function pushMiniAppProject(args) {
4555
5257
  return result;
4556
5258
  }
4557
5259
  async function buildMiniPreviewTargets(rootDir, frontendBaseUrl) {
4558
- const context = await readMiniContext(path5.resolve(rootDir));
5260
+ const context = await readMiniContext(path6.resolve(rootDir));
4559
5261
  const app = encodeURIComponent(context.appCode);
4560
5262
  const workspace = encodeURIComponent(context.workspaceKey);
4561
5263
  const base = frontendBaseUrl.replace(/\/+$/, "");
@@ -4578,7 +5280,7 @@ async function buildMiniPreviewTargets(rootDir, frontendBaseUrl) {
4578
5280
  ];
4579
5281
  }
4580
5282
  async function runMiniSmokeChecks(args) {
4581
- const context = await readMiniContext(path5.resolve(args.rootDir));
5283
+ const context = await readMiniContext(path6.resolve(args.rootDir));
4582
5284
  const targets = buildMiniSmokeTargets(context, args.frontendBaseUrl, args.previewTargets);
4583
5285
  const results = await Promise.all(
4584
5286
  targets.map(
@@ -4849,10 +5551,10 @@ function countOperations(operations) {
4849
5551
  return counts;
4850
5552
  }
4851
5553
  async function readMiniContext(rootDir) {
4852
- const file = path5.join(rootDir, MINI_CONTEXT_FILE);
5554
+ const file = path6.join(rootDir, MINI_CONTEXT_FILE);
4853
5555
  let parsed;
4854
5556
  try {
4855
- parsed = JSON.parse(await fs9.readFile(file, "utf-8"));
5557
+ parsed = JSON.parse(await fs10.readFile(file, "utf-8"));
4856
5558
  } catch (e) {
4857
5559
  if (e.code === "ENOENT") {
4858
5560
  throw new CliError({
@@ -4885,9 +5587,9 @@ async function readMiniContext(rootDir) {
4885
5587
  };
4886
5588
  }
4887
5589
  async function readPullManifest(rootDir) {
4888
- const file = path5.join(rootDir, MINI_STATE_DIR, MINI_PULL_MANIFEST_FILE);
5590
+ const file = path6.join(rootDir, MINI_STATE_DIR, MINI_PULL_MANIFEST_FILE);
4889
5591
  try {
4890
- const parsed = JSON.parse(await fs9.readFile(file, "utf-8"));
5592
+ const parsed = JSON.parse(await fs10.readFile(file, "utf-8"));
4891
5593
  return {
4892
5594
  version: MINI_CONTEXT_VERSION,
4893
5595
  appCode: parsed.appCode ? normalizeAppCode(parsed.appCode) : "",
@@ -4986,18 +5688,18 @@ async function validateEntryPath(root, field, value, suffix, errors) {
4986
5688
  return;
4987
5689
  }
4988
5690
  try {
4989
- await fs9.access(path5.join(root, value));
5691
+ await fs10.access(path6.join(root, value));
4990
5692
  } catch {
4991
5693
  errors.push(`${field} target file does not exist: ${value}`);
4992
5694
  }
4993
5695
  }
4994
5696
  async function validateEntryRequiredScopes(root, jsPath, requiredScopes, warnings) {
4995
5697
  if (!jsPath) return;
4996
- const absolutePath = path5.resolve(root, jsPath);
4997
- if (!absolutePath.startsWith(root + path5.sep)) return;
5698
+ const absolutePath = path6.resolve(root, jsPath);
5699
+ if (!absolutePath.startsWith(root + path6.sep)) return;
4998
5700
  let source = "";
4999
5701
  try {
5000
- source = await fs9.readFile(absolutePath, "utf-8");
5702
+ source = await fs10.readFile(absolutePath, "utf-8");
5001
5703
  } catch {
5002
5704
  return;
5003
5705
  }
@@ -5164,10 +5866,10 @@ async function readLocalMiniFiles(root) {
5164
5866
  return files;
5165
5867
  }
5166
5868
  async function walk(root, relativeDir, files) {
5167
- const absoluteDir = path5.join(root, relativeDir);
5869
+ const absoluteDir = path6.join(root, relativeDir);
5168
5870
  let entries;
5169
5871
  try {
5170
- entries = await fs9.readdir(absoluteDir, { withFileTypes: true });
5872
+ entries = await fs10.readdir(absoluteDir, { withFileTypes: true });
5171
5873
  } catch (e) {
5172
5874
  if (e.code === "ENOENT") return;
5173
5875
  throw e;
@@ -5175,12 +5877,12 @@ async function walk(root, relativeDir, files) {
5175
5877
  for (const entry of entries) {
5176
5878
  if (entry.name === MINI_CONTEXT_FILE) continue;
5177
5879
  if (entry.isDirectory() && EXCLUDED_DIRS.has(entry.name)) continue;
5178
- const localPath = normalizeRelativePath(path5.posix.join(toPosix(relativeDir), entry.name));
5179
- const absolutePath = path5.join(root, localPath);
5880
+ const localPath = normalizeRelativePath(path6.posix.join(toPosix(relativeDir), entry.name));
5881
+ const absolutePath = path6.join(root, localPath);
5180
5882
  if (entry.isDirectory()) {
5181
5883
  await walk(root, localPath, files);
5182
5884
  } else if (entry.isFile()) {
5183
- const content = await fs9.readFile(absolutePath, "utf-8");
5885
+ const content = await fs10.readFile(absolutePath, "utf-8");
5184
5886
  files.push({
5185
5887
  localPath,
5186
5888
  absolutePath,
@@ -5192,16 +5894,16 @@ async function walk(root, relativeDir, files) {
5192
5894
  }
5193
5895
  }
5194
5896
  async function writeMiniState(root, context, files, remoteByLocalPath) {
5195
- const stateDir = path5.join(root, MINI_STATE_DIR);
5196
- const baseDir = path5.join(stateDir, "base");
5197
- await fs9.rm(baseDir, { recursive: true, force: true });
5198
- await fs9.mkdir(baseDir, { recursive: true });
5897
+ const stateDir = path6.join(root, MINI_STATE_DIR);
5898
+ const baseDir = path6.join(stateDir, "base");
5899
+ await fs10.rm(baseDir, { recursive: true, force: true });
5900
+ await fs10.mkdir(baseDir, { recursive: true });
5199
5901
  const snapshots = [];
5200
5902
  for (const file of files) {
5201
- await writeText(path5.join(baseDir, file.localPath), file.content);
5903
+ await writeText(path6.join(baseDir, file.localPath), file.content);
5202
5904
  snapshots.push(toSnapshot(context, file, remoteByLocalPath.get(file.localPath)));
5203
5905
  }
5204
- await writeJson(path5.join(stateDir, MINI_PULL_MANIFEST_FILE), {
5906
+ await writeJson(path6.join(stateDir, MINI_PULL_MANIFEST_FILE), {
5205
5907
  version: MINI_CONTEXT_VERSION,
5206
5908
  appCode: context.appCode,
5207
5909
  workspaceKey: context.workspaceKey,
@@ -5229,7 +5931,7 @@ async function ensureTargetWritable(targetDir, relativePaths, force) {
5229
5931
  const existing = [];
5230
5932
  for (const relativePath of relativePaths) {
5231
5933
  try {
5232
- await fs9.access(path5.join(targetDir, relativePath));
5934
+ await fs10.access(path6.join(targetDir, relativePath));
5233
5935
  existing.push(relativePath);
5234
5936
  } catch {
5235
5937
  }
@@ -5302,8 +6004,8 @@ function sha2562(content) {
5302
6004
  return crypto.createHash("sha256").update(content, "utf-8").digest("hex");
5303
6005
  }
5304
6006
  async function writeText(file, content) {
5305
- await fs9.mkdir(path5.dirname(file), { recursive: true });
5306
- await fs9.writeFile(file, content, "utf-8");
6007
+ await fs10.mkdir(path6.dirname(file), { recursive: true });
6008
+ await fs10.writeFile(file, content, "utf-8");
5307
6009
  }
5308
6010
  async function writeJson(file, value) {
5309
6011
  await writeText(file, JSON.stringify(value, null, 2) + "\n");
@@ -5349,17 +6051,17 @@ function toPosix(value) {
5349
6051
 
5350
6052
  // src/datapackage/pack.ts
5351
6053
  import * as fsp2 from "fs/promises";
5352
- import * as fs10 from "fs";
5353
- import * as path6 from "path";
5354
- import yaml7, { JSON_SCHEMA as JSON_SCHEMA2 } from "js-yaml";
6054
+ import * as fs11 from "fs";
6055
+ import * as path7 from "path";
6056
+ import yaml8, { JSON_SCHEMA as JSON_SCHEMA2 } from "js-yaml";
5355
6057
  import * as yazl from "yazl";
5356
6058
  function fail(message) {
5357
6059
  throw new CliError({ code: "INVALID_ARGUMENT" /* INVALID_ARGUMENT */, message: `datapackage pack: ${message}` });
5358
6060
  }
5359
- function parseManifest(text2, manifestPath) {
6061
+ function parseManifest(text3, manifestPath) {
5360
6062
  let parsed;
5361
6063
  try {
5362
- parsed = yaml7.load(text2, { schema: JSON_SCHEMA2 });
6064
+ parsed = yaml8.load(text3, { schema: JSON_SCHEMA2 });
5363
6065
  } catch (e) {
5364
6066
  return fail(`package.yml \u89E3\u6790\u5931\u8D25: ${e.message} (${manifestPath})`);
5365
6067
  }
@@ -5395,11 +6097,11 @@ async function collectFiles(root, skipAbs) {
5395
6097
  entries.sort((a, b) => a.name.localeCompare(b.name));
5396
6098
  for (const e of entries) {
5397
6099
  if (e.name.startsWith(".")) continue;
5398
- const abs = path6.join(dir, e.name);
6100
+ const abs = path7.join(dir, e.name);
5399
6101
  const relPath = rel ? `${rel}/${e.name}` : e.name;
5400
6102
  if (e.isDirectory()) {
5401
6103
  await walk4(abs, relPath);
5402
- } else if (e.isFile() && !skipAbs.has(path6.resolve(abs))) {
6104
+ } else if (e.isFile() && !skipAbs.has(path7.resolve(abs))) {
5403
6105
  out.push(relPath);
5404
6106
  }
5405
6107
  }
@@ -5408,8 +6110,8 @@ async function collectFiles(root, skipAbs) {
5408
6110
  return out;
5409
6111
  }
5410
6112
  async function packDataPackage(packageDir, outPath, opts = {}) {
5411
- const root = path6.resolve(packageDir);
5412
- const manifestPath = path6.join(root, "package.yml");
6113
+ const root = path7.resolve(packageDir);
6114
+ const manifestPath = path7.join(root, "package.yml");
5413
6115
  let manifestText;
5414
6116
  try {
5415
6117
  manifestText = await fsp2.readFile(manifestPath, "utf8");
@@ -5418,25 +6120,25 @@ async function packDataPackage(packageDir, outPath, opts = {}) {
5418
6120
  }
5419
6121
  const { name, version, referenced } = parseManifest(manifestText, manifestPath);
5420
6122
  for (const relFile of referenced) {
5421
- const abs = path6.resolve(root, relFile);
5422
- if (!abs.startsWith(root + path6.sep)) return fail(`\u5F15\u7528\u8DEF\u5F84\u8D8A\u51FA\u5305\u76EE\u5F55: ${relFile}`);
5423
- if (!fs10.existsSync(abs) || !fs10.statSync(abs).isFile()) {
6123
+ const abs = path7.resolve(root, relFile);
6124
+ if (!abs.startsWith(root + path7.sep)) return fail(`\u5F15\u7528\u8DEF\u5F84\u8D8A\u51FA\u5305\u76EE\u5F55: ${relFile}`);
6125
+ if (!fs11.existsSync(abs) || !fs11.statSync(abs).isFile()) {
5424
6126
  return fail(`manifest \u5F15\u7528\u7684\u6587\u4EF6\u4E0D\u5B58\u5728: ${relFile}`);
5425
6127
  }
5426
6128
  }
5427
6129
  const lastSegment = name.includes("/") ? name.slice(name.lastIndexOf("/") + 1) : name;
5428
- const artifactPath = path6.resolve(outPath ?? `${lastSegment}-${version}.hcmpkg`);
6130
+ const artifactPath = path7.resolve(outPath ?? `${lastSegment}-${version}.hcmpkg`);
5429
6131
  const files = await collectFiles(root, /* @__PURE__ */ new Set([artifactPath]));
5430
6132
  if (!files.includes("package.yml")) return fail("\u6536\u96C6\u4E0D\u5230 package.yml\uFF08\u4E0D\u5E94\u53D1\u751F\uFF09");
5431
- await fsp2.mkdir(path6.dirname(artifactPath), { recursive: true });
6133
+ await fsp2.mkdir(path7.dirname(artifactPath), { recursive: true });
5432
6134
  await new Promise((resolve6, reject2) => {
5433
6135
  const zip = new yazl.ZipFile();
5434
6136
  files.forEach((rel, i) => {
5435
- zip.addFile(path6.join(root, rel), rel);
6137
+ zip.addFile(path7.join(root, rel), rel);
5436
6138
  opts.onFile?.(rel, i + 1, files.length);
5437
6139
  });
5438
6140
  zip.end();
5439
- const ws = fs10.createWriteStream(artifactPath);
6141
+ const ws = fs11.createWriteStream(artifactPath);
5440
6142
  zip.outputStream.pipe(ws);
5441
6143
  ws.on("close", () => resolve6());
5442
6144
  ws.on("error", reject2);
@@ -5592,23 +6294,23 @@ async function listTenantMeta(http, opts = {}) {
5592
6294
  const total = typeof body?.total === "number" ? body.total : payload?.total;
5593
6295
  return { items, total, raw: payload };
5594
6296
  }
5595
- async function getTenantMeta(http, path23) {
5596
- const resp = await http.get("/api/tenant-meta/meta", { params: { path: path23 } });
6297
+ async function getTenantMeta(http, path24) {
6298
+ const resp = await http.get("/api/tenant-meta/meta", { params: { path: path24 } });
5597
6299
  const payload = resp.data?.data ?? resp.data;
5598
6300
  if (typeof payload === "string") return payload;
5599
6301
  return String(payload?.content ?? "");
5600
6302
  }
5601
- async function saveTenantMeta(http, path23, content) {
5602
- const resp = await http.put("/api/tenant-meta/meta", { content }, { params: { path: path23 } });
6303
+ async function saveTenantMeta(http, path24, content) {
6304
+ const resp = await http.put("/api/tenant-meta/meta", { content }, { params: { path: path24 } });
5603
6305
  return resp.data?.data ?? resp.data;
5604
6306
  }
5605
- async function deleteTenantMeta(http, path23) {
5606
- const resp = await http.delete("/api/tenant-meta/meta", { params: { path: path23 } });
6307
+ async function deleteTenantMeta(http, path24) {
6308
+ const resp = await http.delete("/api/tenant-meta/meta", { params: { path: path24 } });
5607
6309
  return resp.data?.data ?? resp.data;
5608
6310
  }
5609
6311
 
5610
6312
  // src/meta/validate-meta.ts
5611
- import yaml8 from "js-yaml";
6313
+ import yaml9 from "js-yaml";
5612
6314
 
5613
6315
  // src/meta/generated/meta-schemas.ts
5614
6316
  var META_SCHEMA_SOURCE_COMMIT = "f4a97dbb4db8f6029681b069a240c334a0bc3c3d";
@@ -9221,7 +9923,7 @@ function validateMetaContent(metaPath2, content) {
9221
9923
  }
9222
9924
  let doc;
9223
9925
  try {
9224
- doc = yaml8.load(content);
9926
+ doc = yaml9.load(content);
9225
9927
  } catch (e) {
9226
9928
  const y = e;
9227
9929
  issues.push({
@@ -9294,7 +9996,7 @@ function explainJacksonError(raw) {
9294
9996
  }
9295
9997
 
9296
9998
  // src/skills.ts
9297
- import yaml9, { JSON_SCHEMA as JSON_SCHEMA3 } from "js-yaml";
9999
+ import yaml10, { JSON_SCHEMA as JSON_SCHEMA3 } from "js-yaml";
9298
10000
  var CHIRON_BASE_CANDIDATES = ["/api/chiron", "/api/skills", "/chiron", "/skills"];
9299
10001
  function looksLikeManifest(data) {
9300
10002
  if (!data || typeof data !== "object") return false;
@@ -9351,7 +10053,7 @@ async function fetchSkillReference(http, id, relativePath, base) {
9351
10053
  function assertSafeReferencePath(relativePath) {
9352
10054
  const ok = /^[A-Za-z0-9_][A-Za-z0-9._-]{0,63}(\/[A-Za-z0-9_][A-Za-z0-9._-]{0,63}){0,2}$/.test(relativePath);
9353
10055
  if (!ok) {
9354
- throw invalid(`\u53C2\u8003\u6587\u4EF6\u8DEF\u5F84\u4E0D\u5408\u6CD5\uFF1A${JSON.stringify(relativePath)}`);
10056
+ throw invalid2(`\u53C2\u8003\u6587\u4EF6\u8DEF\u5F84\u4E0D\u5408\u6CD5\uFF1A${JSON.stringify(relativePath)}`);
9355
10057
  }
9356
10058
  }
9357
10059
  function assertSafeSkillFilePath(relativePath) {
@@ -9359,16 +10061,16 @@ function assertSafeSkillFilePath(relativePath) {
9359
10061
  if (!relativePath || relativePath.length > 512 || relativePath.startsWith("/") || relativePath.includes("\\") || segments.some(
9360
10062
  (segment) => !segment || segment === "." || segment === ".." || !/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(segment)
9361
10063
  )) {
9362
- throw invalid(`\u975E\u6CD5 Skill \u6587\u4EF6\u8DEF\u5F84: "${relativePath}"`);
10064
+ throw invalid2(`\u975E\u6CD5 Skill \u6587\u4EF6\u8DEF\u5F84: "${relativePath}"`);
9363
10065
  }
9364
10066
  }
9365
10067
  function normalizeReferences(raw, skillId) {
9366
10068
  if (raw === void 0 || raw === null) return [];
9367
- if (!Array.isArray(raw)) throw invalid(`\u6280\u80FD ${skillId} \u7684 references \u53EA\u80FD\u662F\u5B57\u7B26\u4E32\u6570\u7EC4`);
10069
+ if (!Array.isArray(raw)) throw invalid2(`\u6280\u80FD ${skillId} \u7684 references \u53EA\u80FD\u662F\u5B57\u7B26\u4E32\u6570\u7EC4`);
9368
10070
  const out = [];
9369
10071
  for (const value of raw) {
9370
10072
  if (typeof value !== "string" || !value.trim()) {
9371
- throw invalid(`\u6280\u80FD ${skillId} \u7684 references \u53EA\u80FD\u662F\u975E\u7A7A\u5B57\u7B26\u4E32\u6570\u7EC4`);
10073
+ throw invalid2(`\u6280\u80FD ${skillId} \u7684 references \u53EA\u80FD\u662F\u975E\u7A7A\u5B57\u7B26\u4E32\u6570\u7EC4`);
9372
10074
  }
9373
10075
  const rel = value.trim();
9374
10076
  assertSafeReferencePath(rel);
@@ -9383,35 +10085,35 @@ function resolveSkillInstallOrder(manifest2, targetId) {
9383
10085
  const byId = /* @__PURE__ */ new Map();
9384
10086
  for (const skill of flattenSkills(manifest2)) {
9385
10087
  if (byId.has(skill.id)) {
9386
- throw invalid(`\u6280\u80FD\u76EE\u5F55\u5B58\u5728\u91CD\u590D id: ${skill.id}`);
10088
+ throw invalid2(`\u6280\u80FD\u76EE\u5F55\u5B58\u5728\u91CD\u590D id: ${skill.id}`);
9387
10089
  }
9388
10090
  byId.set(skill.id, skill);
9389
10091
  }
9390
10092
  if (!byId.has(targetId)) {
9391
- throw invalid(`\u6280\u80FD\u76EE\u5F55\u4E2D\u4E0D\u5B58\u5728 ${targetId}`);
10093
+ throw invalid2(`\u6280\u80FD\u76EE\u5F55\u4E2D\u4E0D\u5B58\u5728 ${targetId}`);
9392
10094
  }
9393
10095
  const state = /* @__PURE__ */ new Map();
9394
- const path23 = [];
10096
+ const path24 = [];
9395
10097
  const order = [];
9396
10098
  const visit = (id, requiredBy) => {
9397
10099
  const current = state.get(id);
9398
10100
  if (current === "done") return;
9399
10101
  if (current === "visiting") {
9400
- const cycleStart = path23.indexOf(id);
9401
- const cycle = [...path23.slice(Math.max(0, cycleStart)), id];
9402
- throw invalid(`\u6280\u80FD\u4F9D\u8D56\u5B58\u5728\u73AF: ${cycle.join(" -> ")}`);
10102
+ const cycleStart = path24.indexOf(id);
10103
+ const cycle = [...path24.slice(Math.max(0, cycleStart)), id];
10104
+ throw invalid2(`\u6280\u80FD\u4F9D\u8D56\u5B58\u5728\u73AF: ${cycle.join(" -> ")}`);
9403
10105
  }
9404
10106
  const skill = byId.get(id);
9405
10107
  if (!skill) {
9406
- throw invalid(`\u6280\u80FD ${requiredBy ?? targetId} \u4F9D\u8D56\u4E0D\u5B58\u5728: ${id}`);
10108
+ throw invalid2(`\u6280\u80FD ${requiredBy ?? targetId} \u4F9D\u8D56\u4E0D\u5B58\u5728: ${id}`);
9407
10109
  }
9408
10110
  assertSafeSkillId(skill.id);
9409
10111
  state.set(id, "visiting");
9410
- path23.push(id);
10112
+ path24.push(id);
9411
10113
  for (const required2 of normalizeRequirements(skill.requires, skill.id)) {
9412
10114
  visit(required2, skill.id);
9413
10115
  }
9414
- path23.pop();
10116
+ path24.pop();
9415
10117
  state.set(id, "done");
9416
10118
  order.push(skill);
9417
10119
  };
@@ -9433,7 +10135,7 @@ function parseSkillFrontmatter(markdown, skillId) {
9433
10135
  if (!match) return {};
9434
10136
  let frontmatter;
9435
10137
  try {
9436
- frontmatter = yaml9.load(match[1] ?? "", { schema: JSON_SCHEMA3 });
10138
+ frontmatter = yaml10.load(match[1] ?? "", { schema: JSON_SCHEMA3 });
9437
10139
  } catch (cause) {
9438
10140
  throw new CliError({
9439
10141
  code: "INVALID_ARGUMENT" /* INVALID_ARGUMENT */,
@@ -9449,7 +10151,7 @@ function parseSkillRequirements(markdown, skillId) {
9449
10151
  }
9450
10152
  function assertSafeSkillId(id) {
9451
10153
  if (!/^[a-z0-9][a-z0-9-]{0,63}$/.test(id)) {
9452
- throw invalid(`\u6280\u80FD id \u53EA\u80FD\u662F\u5C0F\u5199\u5B57\u6BCD/\u6570\u5B57/\u8FDE\u5B57\u7B26\uFF0C\u6536\u5230 "${id}"`);
10154
+ throw invalid2(`\u6280\u80FD id \u53EA\u80FD\u662F\u5C0F\u5199\u5B57\u6BCD/\u6570\u5B57/\u8FDE\u5B57\u7B26\uFF0C\u6536\u5230 "${id}"`);
9453
10155
  }
9454
10156
  }
9455
10157
  function normalizeRequirements(raw, skillId) {
@@ -9458,7 +10160,7 @@ function normalizeRequirements(raw, skillId) {
9458
10160
  const normalized = [];
9459
10161
  for (const value of values) {
9460
10162
  if (typeof value !== "string" || !value.trim()) {
9461
- throw invalid(`\u6280\u80FD ${skillId} \u7684 requires \u53EA\u80FD\u662F\u975E\u7A7A\u6280\u80FD id \u6570\u7EC4`);
10163
+ throw invalid2(`\u6280\u80FD ${skillId} \u7684 requires \u53EA\u80FD\u662F\u975E\u7A7A\u6280\u80FD id \u6570\u7EC4`);
9462
10164
  }
9463
10165
  const id = value.trim();
9464
10166
  assertSafeSkillId(id);
@@ -9466,7 +10168,7 @@ function normalizeRequirements(raw, skillId) {
9466
10168
  }
9467
10169
  return normalized;
9468
10170
  }
9469
- function invalid(message) {
10171
+ function invalid2(message) {
9470
10172
  return new CliError({ code: "INVALID_ARGUMENT" /* INVALID_ARGUMENT */, message });
9471
10173
  }
9472
10174
  function filterByStage(skills, stage) {
@@ -9502,11 +10204,11 @@ async function resetSettingItem(http, domain, namespace, settingKey, revision) {
9502
10204
  function parseSettingAssignment(raw) {
9503
10205
  const eq = raw.indexOf("=");
9504
10206
  if (eq <= 0) throw new Error(`--set \u9700\u8981 namespace.key=value \u5F62\u6001\uFF0C\u6536\u5230 "${raw}"`);
9505
- const path23 = raw.slice(0, eq).trim();
10207
+ const path24 = raw.slice(0, eq).trim();
9506
10208
  const value = raw.slice(eq + 1);
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 };
10209
+ const dot = path24.lastIndexOf(".");
10210
+ if (dot <= 0) throw new Error(`--set \u7684\u952E\u9700\u542B namespace\uFF0C\u5982 security.password.passwordPolicy=complex\uFF0C\u6536\u5230 "${path24}"`);
10211
+ return { namespace: path24.slice(0, dot), settingKey: path24.slice(dot + 1), value };
9510
10212
  }
9511
10213
 
9512
10214
  // src/fde/layout.ts
@@ -9524,7 +10226,7 @@ import {
9524
10226
  writeFileSync,
9525
10227
  writeSync
9526
10228
  } from "fs";
9527
- import * as path7 from "path";
10229
+ import * as path8 from "path";
9528
10230
  var UNSAFE = /[^A-Za-z0-9._-]/g;
9529
10231
  function slug(value) {
9530
10232
  return (value || "unknown").replace(UNSAFE, "_");
@@ -9538,10 +10240,10 @@ function tenantSegment(value) {
9538
10240
  return safeSegment(value);
9539
10241
  }
9540
10242
  function isInside(p, container) {
9541
- const rel = path7.relative(container, p);
10243
+ const rel = path8.relative(container, p);
9542
10244
  if (rel === "") return true;
9543
- if (path7.isAbsolute(rel)) return false;
9544
- return !rel.split(path7.sep).includes("..");
10245
+ if (path8.isAbsolute(rel)) return false;
10246
+ return !rel.split(path8.sep).includes("..");
9545
10247
  }
9546
10248
  function hasDotDotComponent(rel) {
9547
10249
  return rel.split(/[/\\]/).includes("..");
@@ -9555,14 +10257,14 @@ var ReconLayout = class {
9555
10257
  this.root = root;
9556
10258
  this.tenantId = String(tenantId);
9557
10259
  this.sourceKey = sourceKey;
9558
- this.dir = path7.join(
10260
+ this.dir = path8.join(
9559
10261
  this.root,
9560
10262
  "recon",
9561
10263
  tenantSegment(this.tenantId),
9562
10264
  safeSegment(sourceKey)
9563
10265
  );
9564
- const container = path7.resolve(this.root, "recon");
9565
- if (!isInside(path7.resolve(this.dir), container)) {
10266
+ const container = path8.resolve(this.root, "recon");
10267
+ if (!isInside(path8.resolve(this.dir), container)) {
9566
10268
  throw new LayoutContainmentError(
9567
10269
  `\u79DF\u6237\u6BB5\u8D8A\u754C\uFF0C\u62D2\u7EDD\u6784\u9020\u4EA7\u7269\u76EE\u5F55\uFF1AtenantId=${JSON.stringify(tenantId)}\uFF08\u4EA7\u7269\u6839 ${container}\uFF09`
9568
10270
  );
@@ -9585,19 +10287,19 @@ var ReconLayout = class {
9585
10287
  * ⚠️ 拒绝而不是消毒:消毒会让 `meta/<modelKey>.json` 不再能按 modelKey grep 回去。
9586
10288
  */
9587
10289
  resolvePath(rel, createParents = true) {
9588
- const p = path7.join(this.dir, rel);
10290
+ const p = path8.join(this.dir, rel);
9589
10291
  if (hasDotDotComponent(rel)) {
9590
10292
  throw new LayoutContainmentError(
9591
10293
  `\u4EA7\u7269\u76F8\u5BF9\u8DEF\u5F84\u542B \`..\` \u5206\u91CF\uFF0C\u62D2\u7EDD\u5199\u5165\uFF1A${JSON.stringify(rel)}\uFF08\u4F1A\u8D8A\u51FA\u9884\u671F\u5B50\u76EE\u5F55\u3001\u9759\u9ED8\u9876\u6389\u540C\u7EA7\u4EA7\u7269\uFF1B\u4EA7\u7269\u6839 ${this.dir}\uFF09`
9592
10294
  );
9593
10295
  }
9594
- if (!isInside(path7.resolve(p), path7.resolve(this.dir))) {
10296
+ if (!isInside(path8.resolve(p), path8.resolve(this.dir))) {
9595
10297
  throw new LayoutContainmentError(
9596
10298
  `\u4EA7\u7269\u76F8\u5BF9\u8DEF\u5F84\u8D8A\u754C\uFF0C\u62D2\u7EDD\u5199\u5165\uFF1A${JSON.stringify(rel)}\uFF08\u4EA7\u7269\u6839 ${this.dir}\uFF09`
9597
10299
  );
9598
10300
  }
9599
10301
  if (createParents) {
9600
- mkdirSync(path7.dirname(p), { recursive: true });
10302
+ mkdirSync(path8.dirname(p), { recursive: true });
9601
10303
  }
9602
10304
  return p;
9603
10305
  }
@@ -9614,9 +10316,9 @@ var ReconLayout = class {
9614
10316
  writeFileSync(p, body, "utf8");
9615
10317
  return p;
9616
10318
  }
9617
- writeText(rel, text2) {
10319
+ writeText(rel, text3) {
9618
10320
  const p = this.resolvePath(rel);
9619
- writeFileSync(p, text2, "utf8");
10321
+ writeFileSync(p, text3, "utf8");
9620
10322
  return p;
9621
10323
  }
9622
10324
  /**
@@ -9646,18 +10348,18 @@ var WorkLayout = class {
9646
10348
  }
9647
10349
  /** 与 {@link ReconLayout.resolvePath} 同样的两道闸,理由见那里。 */
9648
10350
  resolvePath(rel, createParents = true) {
9649
- const p = path7.join(this.dir, rel);
10351
+ const p = path8.join(this.dir, rel);
9650
10352
  if (hasDotDotComponent(rel)) {
9651
10353
  throw new LayoutContainmentError(
9652
10354
  `work \u76EE\u5F55\u76F8\u5BF9\u8DEF\u5F84\u542B \`..\` \u5206\u91CF\uFF0C\u62D2\u7EDD\u5199\u5165\uFF1A${JSON.stringify(rel)}\uFF08work \u6839 ${this.dir}\uFF09`
9653
10355
  );
9654
10356
  }
9655
- if (!isInside(path7.resolve(p), path7.resolve(this.dir))) {
10357
+ if (!isInside(path8.resolve(p), path8.resolve(this.dir))) {
9656
10358
  throw new LayoutContainmentError(
9657
10359
  `work \u76EE\u5F55\u76F8\u5BF9\u8DEF\u5F84\u8D8A\u754C\uFF0C\u62D2\u7EDD\u5199\u5165\uFF1A${JSON.stringify(rel)}\uFF08work \u6839 ${this.dir}\uFF09`
9658
10360
  );
9659
10361
  }
9660
- if (createParents) mkdirSync(path7.dirname(p), { recursive: true });
10362
+ if (createParents) mkdirSync(path8.dirname(p), { recursive: true });
9661
10363
  return p;
9662
10364
  }
9663
10365
  /** 写一份 JSON 产物。中文逐字落盘(本地 grep 才找得到),末尾带换行。 */
@@ -9711,11 +10413,11 @@ var WorkLayout = class {
9711
10413
  * ⚠️ FAT / exFAT / 部分 SMB **不支持硬链接**,那里会抛 `EPERM` / `ENOTSUP` ——
9712
10414
  * 调用方要把它翻成人话,别让顾问拿到一个裸的 fs 错误。
9713
10415
  */
9714
- createExclusive(rel, text2) {
10416
+ createExclusive(rel, text3) {
9715
10417
  const p = this.resolvePath(rel);
9716
10418
  const tmp = tempPath(p);
9717
10419
  try {
9718
- writeFileSync(tmp, text2, "utf8");
10420
+ writeFileSync(tmp, text3, "utf8");
9719
10421
  linkSync(tmp, p);
9720
10422
  } finally {
9721
10423
  drop(tmp);
@@ -9728,11 +10430,11 @@ var WorkLayout = class {
9728
10430
  * 🔴 这样读者永远读不到**半个**文件(同一文件系统上改名是原子的)。
9729
10431
  * ⚠️ 它保证的只是「不会读到半个」,**不保证**读—判—写这三步之间没有窗口。
9730
10432
  */
9731
- replaceAtomically(rel, text2) {
10433
+ replaceAtomically(rel, text3) {
9732
10434
  const p = this.resolvePath(rel);
9733
10435
  const tmp = tempPath(p);
9734
10436
  try {
9735
- writeFileSync(tmp, text2, "utf8");
10437
+ writeFileSync(tmp, text3, "utf8");
9736
10438
  renameSync(tmp, p);
9737
10439
  } finally {
9738
10440
  drop(tmp);
@@ -9751,8 +10453,8 @@ var WorkLayout = class {
9751
10453
  /** 读出**文本**,按 UTF-8 严格解码(BOM 先剥掉)。解不出时抛 `TypeError`。 */
9752
10454
  readText(rel) {
9753
10455
  const bytes2 = this.readBytes(rel);
9754
- const text2 = new TextDecoder("utf-8", { fatal: true }).decode(bytes2);
9755
- return text2.startsWith("\uFEFF") ? text2.slice(1) : text2;
10456
+ const text3 = new TextDecoder("utf-8", { fatal: true }).decode(bytes2);
10457
+ return text3.startsWith("\uFEFF") ? text3.slice(1) : text3;
9756
10458
  }
9757
10459
  /**
9758
10460
  * 读出**原始字节**,不解码。
@@ -9895,11 +10597,11 @@ function classifyStatus(status) {
9895
10597
  return "bad-response";
9896
10598
  }
9897
10599
  var CAPABILITIES_HEADER = "x-hcm-capabilities";
9898
- function buildUrl(path23, params) {
10600
+ function buildUrl(path24, params) {
9899
10601
  const entries = Object.entries(params ?? {}).filter(([, v]) => v !== void 0 && v !== null);
9900
- if (entries.length === 0) return path23;
10602
+ if (entries.length === 0) return path24;
9901
10603
  const qs = entries.map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(String(v))}`).join("&");
9902
- return `${path23}${path23.includes("?") ? "&" : "?"}${qs}`;
10604
+ return `${path24}${path24.includes("?") ? "&" : "?"}${qs}`;
9903
10605
  }
9904
10606
  function lowerHeaders(raw) {
9905
10607
  const out = {};
@@ -9941,14 +10643,14 @@ function httpProbe(http, capabilities) {
9941
10643
  const headers = { [CAPABILITIES_HEADER]: capabilities };
9942
10644
  const probe = {
9943
10645
  capabilities,
9944
- get(path23, params) {
10646
+ get(path24, params) {
9945
10647
  return once(
9946
- () => http.get(buildUrl(path23, params), { headers, validateStatus: () => true })
10648
+ () => http.get(buildUrl(path24, params), { headers, validateStatus: () => true })
9947
10649
  );
9948
10650
  },
9949
- post(path23, body) {
10651
+ post(path24, body) {
9950
10652
  return once(
9951
- () => http.post(path23, body, {
10653
+ () => http.post(path24, body, {
9952
10654
  headers: { ...headers, "content-type": "application/json" },
9953
10655
  validateStatus: () => true
9954
10656
  })
@@ -9992,7 +10694,7 @@ function networkOutcome() {
9992
10694
  // src/fde/recon/runner.ts
9993
10695
  import { randomBytes as randomBytes3 } from "crypto";
9994
10696
  import { existsSync as existsSync5, readFileSync as readFileSync3, readdirSync } from "fs";
9995
- import * as path9 from "path";
10697
+ import * as path10 from "path";
9996
10698
 
9997
10699
  // src/fde/recon/carry-over.ts
9998
10700
  var KIT_CARRY_OVER_KEY = "_kitCarryOver";
@@ -10060,8 +10762,8 @@ async function crawlMeta(probe, modelKeys2, metaType = DEFAULT_META_TYPE) {
10060
10762
  const results = probe.getMany ? await probe.getMany([...paths.keys()]) : await sequentialGet(probe, [...paths.keys()]);
10061
10763
  const metas = {};
10062
10764
  const unavailable = [];
10063
- for (const [path23, key] of paths) {
10064
- const out = results[path23];
10765
+ for (const [path24, key] of paths) {
10766
+ const out = results[path24];
10065
10767
  if (out === void 0) {
10066
10768
  unavailable.push({
10067
10769
  modelKey: key,
@@ -10291,8 +10993,8 @@ async function collectActionGates(probe, modelKeys2, state = "") {
10291
10993
  const statesEchoed = /* @__PURE__ */ new Set();
10292
10994
  let noStateEcho = 0;
10293
10995
  let answered = 0;
10294
- for (const [path23, model] of paths) {
10295
- const out = results[path23];
10996
+ for (const [path24, model] of paths) {
10997
+ const out = results[path24];
10296
10998
  if (out === void 0) {
10297
10999
  unavailable.push({
10298
11000
  modelKey: model,
@@ -10701,8 +11403,8 @@ async function collectMutation(probe, modelKeys2) {
10701
11403
  const results = probe.getMany ? await probe.getMany([...paths.keys()]) : await sequentialGet(probe, [...paths.keys()]);
10702
11404
  const mutation = {};
10703
11405
  const problems = [];
10704
- for (const [path23, key] of paths) {
10705
- const out = results[path23];
11406
+ for (const [path24, key] of paths) {
11407
+ const out = results[path24];
10706
11408
  if (out === void 0) {
10707
11409
  problems.push(`${key}: mutation-capability ${BATCH_LOST}`);
10708
11410
  mutation[key] = Object.fromEntries(
@@ -11007,13 +11709,13 @@ function renderModelsMd(modelsBody, metas, gates, dropped = []) {
11007
11709
  }
11008
11710
  return parts.join("\n");
11009
11711
  }
11010
- function writeModelsMd(layout, text2) {
11011
- return layout.writeText("index/models.md", text2);
11712
+ function writeModelsMd(layout, text3) {
11713
+ return layout.writeText("index/models.md", text3);
11012
11714
  }
11013
11715
 
11014
11716
  // src/fde/recon/pointer-audit.ts
11015
11717
  import { existsSync as existsSync4 } from "fs";
11016
- import * as path8 from "path";
11718
+ import * as path9 from "path";
11017
11719
  function isRecord3(v) {
11018
11720
  return Boolean(v) && typeof v === "object" && !Array.isArray(v);
11019
11721
  }
@@ -11026,7 +11728,7 @@ function auditValueDomainPointers(layout, sheets) {
11026
11728
  const pointer = isRecord3(ref) ? ref.valueDomain : null;
11027
11729
  if (typeof pointer !== "string" || pointer === "") continue;
11028
11730
  if (!seen.has(pointer)) {
11029
- seen.set(pointer, existsSync4(path8.join(layout.dir, pointer)));
11731
+ seen.set(pointer, existsSync4(path9.join(layout.dir, pointer)));
11030
11732
  }
11031
11733
  if (!seen.get(pointer)) {
11032
11734
  problems.push(
@@ -11132,8 +11834,8 @@ async function collectCodeTables(probe, modelEntries2, opts = {}) {
11132
11834
  const maxRequests = opts.maxRequests ?? MAX_REQUESTS_PER_TABLE;
11133
11835
  const maxSeconds = opts.maxSeconds ?? MAX_SECONDS_PER_TABLE;
11134
11836
  const tick = opts.clock ?? (() => performance.now() / 1e3);
11135
- const post = probe.post;
11136
- if (!post) throw new Error("\u63A2\u9488\u6CA1\u6709 post \u80FD\u529B\uFF0C\u53D6\u4E0D\u4E86 list/dsl \u2014\u2014 \u8FD9\u662F\u7F16\u6392\u7684\u914D\u7F6E\u9519\uFF0C\u4E0D\u662F\u6570\u636E\u95EE\u9898");
11837
+ const post2 = probe.post;
11838
+ if (!post2) throw new Error("\u63A2\u9488\u6CA1\u6709 post \u80FD\u529B\uFF0C\u53D6\u4E0D\u4E86 list/dsl \u2014\u2014 \u8FD9\u662F\u7F16\u6392\u7684\u914D\u7F6E\u9519\uFF0C\u4E0D\u662F\u6570\u636E\u95EE\u9898");
11137
11839
  const tables = {};
11138
11840
  const problems = [];
11139
11841
  const keys = [];
@@ -11147,11 +11849,11 @@ async function collectCodeTables(probe, modelEntries2, opts = {}) {
11147
11849
  keys.push(key);
11148
11850
  }
11149
11851
  for (const key of [...new Set(keys)].sort()) {
11150
- const path23 = listPath(key);
11852
+ const path24 = listPath(key);
11151
11853
  const started = tick();
11152
11854
  let requests = 0;
11153
11855
  let truncatedBy = null;
11154
- const probeOut = await post.call(probe, path23, { page: 0, size: 0 });
11856
+ const probeOut = await post2.call(probe, path24, { page: 0, size: 0 });
11155
11857
  requests += 1;
11156
11858
  let total = null;
11157
11859
  let reason = null;
@@ -11200,7 +11902,7 @@ async function collectCodeTables(probe, modelEntries2, opts = {}) {
11200
11902
  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
11903
  break;
11202
11904
  }
11203
- const out = await post.call(probe, path23, { page, size: PAGE_SIZE });
11905
+ const out = await post2.call(probe, path24, { page, size: PAGE_SIZE });
11204
11906
  requests += 1;
11205
11907
  if (out.error !== "ok") {
11206
11908
  failed = `\u7B2C ${page} \u9875\u5931\u8D25\uFF08HTTP ${out.status} / ${out.error}\uFF09`;
@@ -11407,21 +12109,21 @@ function isRecord5(v) {
11407
12109
  return Boolean(v) && typeof v === "object" && !Array.isArray(v);
11408
12110
  }
11409
12111
  function readJsonSoft(file) {
11410
- let text2;
12112
+ let text3;
11411
12113
  try {
11412
- text2 = readFileSync3(file, "utf8");
12114
+ text3 = readFileSync3(file, "utf8");
11413
12115
  } catch (err) {
11414
12116
  if (err?.code === "ENOENT") return void 0;
11415
12117
  throw err;
11416
12118
  }
11417
12119
  try {
11418
- return JSON.parse(text2);
12120
+ return JSON.parse(text3);
11419
12121
  } catch {
11420
12122
  return void 0;
11421
12123
  }
11422
12124
  }
11423
12125
  function readCrawledAt(layout) {
11424
- const body = readJsonSoft(path9.join(layout.dir, KIT_CRAWLED_AT_FILE));
12126
+ const body = readJsonSoft(path10.join(layout.dir, KIT_CRAWLED_AT_FILE));
11425
12127
  const models = isRecord5(body) ? body.models : null;
11426
12128
  return isRecord5(models) ? models : {};
11427
12129
  }
@@ -11451,7 +12153,7 @@ function writeCrawledAt(layout, freshKeys, carriedKeys, roundId, started) {
11451
12153
  return sorted;
11452
12154
  }
11453
12155
  function finishRound(layout, models, roundId, started, products) {
11454
- const written = [...new Set(products.filter((rel) => rel && existsSync5(path9.join(layout.dir, rel))))].sort();
12156
+ const written = [...new Set(products.filter((rel) => rel && existsSync5(path10.join(layout.dir, rel))))].sort();
11455
12157
  layout.writeJson(KIT_CRAWLED_AT_FILE, {
11456
12158
  note: CRAWLED_AT_NOTE,
11457
12159
  roundNote: ROUND_NOTE,
@@ -11463,12 +12165,12 @@ function finishRound(layout, models, roundId, started, products) {
11463
12165
  return written;
11464
12166
  }
11465
12167
  function relOf(layout, p) {
11466
- const rel = path9.relative(layout.dir, p);
12168
+ const rel = path10.relative(layout.dir, p);
11467
12169
  if (!rel || rel.startsWith("..")) return p;
11468
- return rel.split(path9.sep).join("/");
12170
+ return rel.split(path10.sep).join("/");
11469
12171
  }
11470
12172
  function productRoundId(root, rel) {
11471
- const p = path9.join(root, rel);
12173
+ const p = path10.join(root, rel);
11472
12174
  if (!existsSync5(p)) return ["missing", null];
11473
12175
  const body = readJsonSoft(p);
11474
12176
  if (body === void 0 || !isRecord5(body)) return ["unreadable", null];
@@ -11477,7 +12179,7 @@ function productRoundId(root, rel) {
11477
12179
  return ["stamped", rid];
11478
12180
  }
11479
12181
  function inspectRound(root) {
11480
- const raw = readJsonSoft(path9.join(root, KIT_CRAWLED_AT_FILE));
12182
+ const raw = readJsonSoft(path10.join(root, KIT_CRAWLED_AT_FILE));
11481
12183
  const ledger = isRecord5(raw) ? raw : {};
11482
12184
  const rid = ledger.roundId;
11483
12185
  const roundId = typeof rid === "string" && rid ? rid : null;
@@ -11485,7 +12187,7 @@ function inspectRound(root) {
11485
12187
  const written = Array.isArray(rawWritten) ? rawWritten : null;
11486
12188
  let ledgerMissing = null;
11487
12189
  if (written !== null) {
11488
- const gone = written.filter((rel) => typeof rel === "string" && !existsSync5(path9.join(root, rel))).sort();
12190
+ const gone = written.filter((rel) => typeof rel === "string" && !existsSync5(path10.join(root, rel))).sort();
11489
12191
  ledgerMissing = { checked: written.length, count: gone.length, files: gone };
11490
12192
  }
11491
12193
  const products = [];
@@ -11605,7 +12307,7 @@ function carriedGatesSchemaProblem(oldGates) {
11605
12307
  function collectCarryOver(layout, freshMetas) {
11606
12308
  const problems = [];
11607
12309
  const carriedMetas = {};
11608
- const metaDir = path9.join(layout.dir, "meta");
12310
+ const metaDir = path10.join(layout.dir, "meta");
11609
12311
  const suffix = `.${DEFAULT_META_TYPE}.json`;
11610
12312
  let names = [];
11611
12313
  try {
@@ -11616,7 +12318,7 @@ function collectCarryOver(layout, freshMetas) {
11616
12318
  for (const name of names) {
11617
12319
  const key = name.slice(0, -suffix.length);
11618
12320
  if (key in freshMetas) continue;
11619
- const file = path9.join(metaDir, name);
12321
+ const file = path10.join(metaDir, name);
11620
12322
  let body;
11621
12323
  try {
11622
12324
  body = JSON.parse(readFileSync3(file, "utf8"));
@@ -11632,7 +12334,7 @@ function collectCarryOver(layout, freshMetas) {
11632
12334
  }
11633
12335
  }
11634
12336
  const carriedGates = [];
11635
- const oldGates = readJsonSoft(path9.join(layout.dir, "gates.json"));
12337
+ const oldGates = readJsonSoft(path10.join(layout.dir, "gates.json"));
11636
12338
  if (oldGates === void 0) {
11637
12339
  problems.push("gates.json: \u6CA1\u6709\u53EF\u6CBF\u7528\u7684\u4E0A\u4E00\u8F6E\u95F8\u8868\uFF08\u4E0D\u5B58\u5728\u6216\u8BFB\u4E0D\u51FA JSON\uFF09");
11638
12340
  } else {
@@ -11749,7 +12451,7 @@ async function runRecon(probe, layout, opts = {}) {
11749
12451
  const writtenPaths = new Set(vdWritten);
11750
12452
  const codeTableFiles = new Set(
11751
12453
  Object.keys(codeTables).filter(
11752
- (k) => unsafeTableKeyReason(k) === null && writtenPaths.has(path9.join(layout.dir, "valuedomain", `${k}.json`))
12454
+ (k) => unsafeTableKeyReason(k) === null && writtenPaths.has(path10.join(layout.dir, "valuedomain", `${k}.json`))
11753
12455
  )
11754
12456
  );
11755
12457
  const { mutation, problems: mutProblems } = await collectMutation(probe, Object.keys(metas).sort());
@@ -11764,7 +12466,7 @@ async function runRecon(probe, layout, opts = {}) {
11764
12466
  });
11765
12467
  products.push(...mappingPaths.map((p) => relOf(layout, p)));
11766
12468
  const sheetsWritten = Math.max(mappingPaths.length - 1, 0);
11767
- let previous = readJsonSoft(path9.join(layout.dir, "fingerprint.json"));
12469
+ let previous = readJsonSoft(path10.join(layout.dir, "fingerprint.json"));
11768
12470
  if (!isRecord5(previous)) previous = null;
11769
12471
  const current = await computeFingerprint(probe);
11770
12472
  products.push(relOf(layout, layout.writeJson("fingerprint.json", current)));
@@ -11860,11 +12562,11 @@ async function runRecon(probe, layout, opts = {}) {
11860
12562
 
11861
12563
  // src/fde/seed/command.ts
11862
12564
  import { existsSync as existsSync8, readFileSync as readFileSync7, readdirSync as readdirSync2, statSync as statSync7 } from "fs";
11863
- import * as path15 from "path";
12565
+ import * as path16 from "path";
11864
12566
 
11865
12567
  // src/fde/seed/risk.ts
11866
12568
  import { readFileSync as readFileSync6, realpathSync, statSync as statSync6 } from "fs";
11867
- import * as path14 from "path";
12569
+ import * as path15 from "path";
11868
12570
 
11869
12571
  // src/fde/seed/key-index.ts
11870
12572
  var MAX_PAGE_SIZE = 1e4;
@@ -11964,7 +12666,7 @@ async function loadKeyIndex(client, model, keyFields, pageSize = PAGE_SIZE_DEFAU
11964
12666
  for (const name of ["id", ...fields]) {
11965
12667
  if (!projected.includes(name)) projected.push(name);
11966
12668
  }
11967
- const path23 = listPath2(model);
12669
+ const path24 = listPath2(model);
11968
12670
  const idx = /* @__PURE__ */ new Map();
11969
12671
  let total = null;
11970
12672
  let pages = 0;
@@ -11981,7 +12683,7 @@ async function loadKeyIndex(client, model, keyFields, pageSize = PAGE_SIZE_DEFAU
11981
12683
  let repeatedIds = 0;
11982
12684
  while (total === null || received < total) {
11983
12685
  const pageNo = pages;
11984
- const out = await client.post(path23, {
12686
+ const out = await client.post(path24, {
11985
12687
  page: pageNo,
11986
12688
  size: pageSize,
11987
12689
  fields: projected,
@@ -12145,7 +12847,7 @@ async function loadKeyIndex(client, model, keyFields, pageSize = PAGE_SIZE_DEFAU
12145
12847
  }
12146
12848
 
12147
12849
  // src/fde/seed/artifacts.ts
12148
- import * as path13 from "path";
12850
+ import * as path14 from "path";
12149
12851
  import { existsSync as existsSync7, readFileSync as readFileSync5, statSync as statSync5 } from "fs";
12150
12852
 
12151
12853
  // src/fde/seed/errors.ts
@@ -12165,7 +12867,7 @@ var TEXT_SUFFIXES = [".csv", ".tsv"];
12165
12867
 
12166
12868
  // src/fde/seed/source.ts
12167
12869
  import { existsSync as existsSync6, openSync as openSync3, readSync as readSync2, closeSync as closeSync3, statSync as statSync4 } from "fs";
12168
- import * as path12 from "path";
12870
+ import * as path13 from "path";
12169
12871
 
12170
12872
  // src/fde/seed/container.ts
12171
12873
  import { openSync as openSync2, readSync, closeSync as closeSync2, statSync as statSync3 } from "fs";
@@ -12173,8 +12875,8 @@ var CFB_MAGIC = Buffer.from([208, 207, 17, 224, 161, 177, 26, 225]);
12173
12875
  var ENCRYPTED_PACKAGE = Buffer.from("EncryptedPackage", "utf16le");
12174
12876
  var MAX_ENTRY_BYTES = 128 * 1024 * 1024;
12175
12877
  var SCAN_CHUNK_BYTES = 1024 * 1024;
12176
- function scanFor(path23, needle = ENCRYPTED_PACKAGE, budget = MAX_ENTRY_BYTES) {
12177
- const fd = openSync2(path23, "r");
12878
+ function scanFor(path24, needle = ENCRYPTED_PACKAGE, budget = MAX_ENTRY_BYTES) {
12879
+ const fd = openSync2(path24, "r");
12178
12880
  try {
12179
12881
  let tail = Buffer.alloc(0);
12180
12882
  let seen = 0;
@@ -12195,9 +12897,9 @@ function scanFor(path23, needle = ENCRYPTED_PACKAGE, budget = MAX_ENTRY_BYTES) {
12195
12897
  closeSync2(fd);
12196
12898
  }
12197
12899
  }
12198
- function isCfb(path23) {
12199
- if (statSync3(path23).size < CFB_MAGIC.length) return false;
12200
- const fd = openSync2(path23, "r");
12900
+ function isCfb(path24) {
12901
+ if (statSync3(path24).size < CFB_MAGIC.length) return false;
12902
+ const fd = openSync2(path24, "r");
12201
12903
  try {
12202
12904
  const head = Buffer.alloc(CFB_MAGIC.length);
12203
12905
  const n = readSync(fd, head, 0, CFB_MAGIC.length, 0);
@@ -12206,9 +12908,9 @@ function isCfb(path23) {
12206
12908
  closeSync2(fd);
12207
12909
  }
12208
12910
  }
12209
- function classifyCfb(path23, budget = MAX_ENTRY_BYTES) {
12210
- if (!isCfb(path23)) return "not-cfb";
12211
- switch (scanFor(path23, ENCRYPTED_PACKAGE, budget)) {
12911
+ function classifyCfb(path24, budget = MAX_ENTRY_BYTES) {
12912
+ if (!isCfb(path24)) return "not-cfb";
12913
+ switch (scanFor(path24, ENCRYPTED_PACKAGE, budget)) {
12212
12914
  case "found":
12213
12915
  return "encrypted";
12214
12916
  case "absent":
@@ -12220,7 +12922,7 @@ function classifyCfb(path23, budget = MAX_ENTRY_BYTES) {
12220
12922
 
12221
12923
  // src/fde/seed/delimited.ts
12222
12924
  import { readFileSync as readFileSync4 } from "fs";
12223
- import * as path10 from "path";
12925
+ import * as path11 from "path";
12224
12926
 
12225
12927
  // src/fde/seed/columns.ts
12226
12928
  function resolveColumns(headerCells, dataRows, label, origin, filename, notes) {
@@ -12323,7 +13025,7 @@ var defaultDecoderFactory = (encoding) => {
12323
13025
  return "unavailable";
12324
13026
  }
12325
13027
  };
12326
- function parseDelimited(text2, delimiter) {
13028
+ function parseDelimited(text3, delimiter) {
12327
13029
  const records = [];
12328
13030
  let record = [];
12329
13031
  let field = "";
@@ -12340,11 +13042,11 @@ function parseDelimited(text2, delimiter) {
12340
13042
  record = [];
12341
13043
  started = false;
12342
13044
  };
12343
- while (i < text2.length) {
12344
- const ch = text2[i];
13045
+ while (i < text3.length) {
13046
+ const ch = text3[i];
12345
13047
  if (quoted) {
12346
13048
  if (ch === '"') {
12347
- if (text2[i + 1] === '"') {
13049
+ if (text3[i + 1] === '"') {
12348
13050
  field += '"';
12349
13051
  i += 2;
12350
13052
  continue;
@@ -12369,7 +13071,7 @@ function parseDelimited(text2, delimiter) {
12369
13071
  i++;
12370
13072
  continue;
12371
13073
  }
12372
- if (ch === "\r" && text2[i + 1] === "\n") {
13074
+ if (ch === "\r" && text3[i + 1] === "\n") {
12373
13075
  pushRecord();
12374
13076
  i += 2;
12375
13077
  continue;
@@ -12387,7 +13089,7 @@ function parseDelimited(text2, delimiter) {
12387
13089
  return records;
12388
13090
  }
12389
13091
  function readDelimited(file, suffix, sheet, headerRow, notes, makeDecoder = defaultDecoderFactory) {
12390
- const filename = path10.basename(file);
13092
+ const filename = path11.basename(file);
12391
13093
  if (sheet !== null && sheet !== void 0) {
12392
13094
  throw new SourceError(
12393
13095
  "sheet-not-applicable",
@@ -12396,7 +13098,7 @@ function readDelimited(file, suffix, sheet, headerRow, notes, makeDecoder = defa
12396
13098
  );
12397
13099
  }
12398
13100
  const data = readFileSync4(file);
12399
- let text2 = null;
13101
+ let text3 = null;
12400
13102
  const unavailable = [];
12401
13103
  for (const encoding of CSV_ENCODINGS) {
12402
13104
  const dec = makeDecoder(encoding);
@@ -12405,13 +13107,13 @@ function readDelimited(file, suffix, sheet, headerRow, notes, makeDecoder = defa
12405
13107
  continue;
12406
13108
  }
12407
13109
  try {
12408
- text2 = dec.decode(data);
13110
+ text3 = dec.decode(data);
12409
13111
  break;
12410
13112
  } catch {
12411
13113
  continue;
12412
13114
  }
12413
13115
  }
12414
- if (text2 === null) {
13116
+ if (text3 === null) {
12415
13117
  if (unavailable.length > 0) {
12416
13118
  throw new SourceError(
12417
13119
  "decoder-unavailable",
@@ -12425,8 +13127,8 @@ function readDelimited(file, suffix, sheet, headerRow, notes, makeDecoder = defa
12425
13127
  "\u5728 Excel \u91CC\u53E6\u5B58\u4E3A\u300CCSV UTF-8\u300D\u518D\u5BFC"
12426
13128
  );
12427
13129
  }
12428
- if (text2.charCodeAt(0) === 65279) text2 = text2.slice(1);
12429
- const records = parseDelimited(text2, suffix === ".tsv" ? " " : ",");
13130
+ if (text3.charCodeAt(0) === 65279) text3 = text3.slice(1);
13131
+ const records = parseDelimited(text3, suffix === ".tsv" ? " " : ",");
12430
13132
  if (records.length < headerRow) {
12431
13133
  throw new SourceError(
12432
13134
  "bad-header",
@@ -12468,7 +13170,7 @@ function readDelimited(file, suffix, sheet, headerRow, notes, makeDecoder = defa
12468
13170
  }
12469
13171
 
12470
13172
  // src/fde/seed/xlsx.ts
12471
- import * as path11 from "path";
13173
+ import * as path12 from "path";
12472
13174
 
12473
13175
  // src/fde/seed/zip.ts
12474
13176
  import yauzl from "yauzl";
@@ -12550,8 +13252,8 @@ function readEntryText(zf, entry, label, cap) {
12550
13252
  (e) => reject2(new SourceError("not-xlsx", `${label} \u89E3\u538B\u5931\u8D25\uFF1A${e.message}`, "\u6587\u4EF6\u635F\u574F\u4E86\uFF0C\u91CD\u65B0\u5BFC\u51FA\u4E00\u4EFD"))
12551
13253
  );
12552
13254
  stream.on("end", () => {
12553
- const text2 = Buffer.concat(chunks).toString("utf8");
12554
- if (!checked && /<!DOCTYPE|<!ENTITY/i.test(text2.slice(0, PROLOG_PEEK_BYTES))) {
13255
+ const text3 = Buffer.concat(chunks).toString("utf8");
13256
+ if (!checked && /<!DOCTYPE|<!ENTITY/i.test(text3.slice(0, PROLOG_PEEK_BYTES))) {
12555
13257
  reject2(
12556
13258
  new SourceError(
12557
13259
  "xml-doctype-rejected",
@@ -12561,7 +13263,7 @@ function readEntryText(zf, entry, label, cap) {
12561
13263
  );
12562
13264
  return;
12563
13265
  }
12564
- resolve6(text2);
13266
+ resolve6(text3);
12565
13267
  });
12566
13268
  });
12567
13269
  });
@@ -12609,17 +13311,17 @@ function attr(attrs, name) {
12609
13311
  for (const [k, v] of Object.entries(attrs)) if (localName(k) === name) return v;
12610
13312
  return void 0;
12611
13313
  }
12612
- function walk3(text2, h) {
13314
+ function walk3(text3, h) {
12613
13315
  const p = saxParser(true, { trim: false, normalize: false, position: false });
12614
13316
  p.onopentag = (node) => h.open?.(localName(node.name), node.attributes);
12615
13317
  p.ontext = (t) => h.text?.(t);
12616
13318
  p.oncdata = (t) => h.text?.(t);
12617
13319
  p.onclosetag = (tag) => h.close?.(localName(tag));
12618
- p.write(text2).close();
13320
+ p.write(text3).close();
12619
13321
  }
12620
- function parseRels(text2) {
13322
+ function parseRels(text3) {
12621
13323
  const out = [];
12622
- walk3(text2, {
13324
+ walk3(text3, {
12623
13325
  open(local, attrs) {
12624
13326
  if (local !== "Relationship") return;
12625
13327
  const id = attr(attrs, "Id");
@@ -12629,9 +13331,9 @@ function parseRels(text2) {
12629
13331
  });
12630
13332
  return out;
12631
13333
  }
12632
- function parseWorkbookSheets(text2) {
13334
+ function parseWorkbookSheets(text3) {
12633
13335
  const out = [];
12634
- walk3(text2, {
13336
+ walk3(text3, {
12635
13337
  open(local, attrs) {
12636
13338
  if (local !== "sheet") return;
12637
13339
  const name = attr(attrs, "name");
@@ -12641,13 +13343,13 @@ function parseWorkbookSheets(text2) {
12641
13343
  });
12642
13344
  return out;
12643
13345
  }
12644
- function parseSharedStrings(text2) {
13346
+ function parseSharedStrings(text3) {
12645
13347
  const out = [];
12646
13348
  let depth = 0;
12647
13349
  let inRPh = 0;
12648
13350
  let inT = false;
12649
13351
  let buf = "";
12650
- walk3(text2, {
13352
+ walk3(text3, {
12651
13353
  open(local) {
12652
13354
  if (local === "si") {
12653
13355
  depth = 1;
@@ -12787,7 +13489,7 @@ function cellValue(c, shared, filename) {
12787
13489
  const trimmed = raw.trim();
12788
13490
  return trimmed === "" ? null : trimmed;
12789
13491
  }
12790
- function readSheetText(text2, shared, headerRow, filename, notes) {
13492
+ function readSheetText(text3, shared, headerRow, filename, notes) {
12791
13493
  let headerCells = null;
12792
13494
  const rawBody = /* @__PURE__ */ new Map();
12793
13495
  let prevRow = 0;
@@ -12810,7 +13512,7 @@ function readSheetText(text2, shared, headerRow, filename, notes) {
12810
13512
  }
12811
13513
  cur = null;
12812
13514
  };
12813
- walk3(text2, {
13515
+ walk3(text3, {
12814
13516
  open(local, attrs) {
12815
13517
  if (local === "row") {
12816
13518
  const r = attr(attrs, "r");
@@ -12909,7 +13611,7 @@ function readSheetText(text2, shared, headerRow, filename, notes) {
12909
13611
  return { header, rows: assemble(header, body, headerRow) };
12910
13612
  }
12911
13613
  async function readXlsx(file, sheet, headerRow, notes, maxEntryBytes) {
12912
- const filename = path11.basename(file);
13614
+ const filename = path12.basename(file);
12913
13615
  const parts = await openParts(file, filename, maxEntryBytes);
12914
13616
  try {
12915
13617
  if (!parts.names.has("xl/workbook.xml")) {
@@ -12999,7 +13701,7 @@ function startsWithPk(file) {
12999
13701
  async function readTable(file, options = {}) {
13000
13702
  const sheet = options.sheet ?? null;
13001
13703
  const headerRow = options.headerRow ?? 1;
13002
- const filename = path12.basename(file);
13704
+ const filename = path13.basename(file);
13003
13705
  if (headerRow < 1) {
13004
13706
  throw new SourceError(
13005
13707
  "bad-header-row",
@@ -13010,7 +13712,7 @@ async function readTable(file, options = {}) {
13010
13712
  if (!existsSync6(file) || !statSync4(file).isFile()) {
13011
13713
  throw new SourceError("not-found", `\u627E\u4E0D\u5230\u6E90\u8868 ${file}`, "\u786E\u8BA4\u8DEF\u5F84\uFF0C\u4EE5\u53CA\u6587\u4EF6\u662F\u5426\u8FD8\u5728\u5171\u4EAB\u76D8\u4E0A\u6CA1\u540C\u6B65\u4E0B\u6765");
13012
13714
  }
13013
- const suffix = path12.extname(file).toLowerCase();
13715
+ const suffix = path13.extname(file).toLowerCase();
13014
13716
  if (suffix === ".xls") {
13015
13717
  throw classifyContainer(file, filename, "legacy-xls", options.scanBudgetBytes);
13016
13718
  }
@@ -13051,8 +13753,8 @@ var JsonSyntaxError = class extends Error {
13051
13753
  };
13052
13754
  var WHITESPACE = /* @__PURE__ */ new Set([" ", " ", "\n", "\r"]);
13053
13755
  var Reader = class {
13054
- constructor(text2) {
13055
- this.text = text2;
13756
+ constructor(text3) {
13757
+ this.text = text3;
13056
13758
  }
13057
13759
  text;
13058
13760
  i = 0;
@@ -13252,8 +13954,8 @@ var Reader = class {
13252
13954
  return value;
13253
13955
  }
13254
13956
  };
13255
- function parseJsonSource(text2) {
13256
- return new Reader(text2.replace(/^\uFEFF/, "")).parseDocument();
13957
+ function parseJsonSource(text3) {
13958
+ return new Reader(text3.replace(/^\uFEFF/, "")).parseDocument();
13257
13959
  }
13258
13960
 
13259
13961
  // src/fde/seed/artifacts.ts
@@ -13383,15 +14085,15 @@ function loadMapping(file) {
13383
14085
  if (!existsSync7(file) || !statSync5(file).isFile()) {
13384
14086
  throw new MappingError("not-found", `\u627E\u4E0D\u5230\u6620\u5C04\u5DE5\u4EF6 ${file}`, "\u786E\u8BA4\u8DEF\u5F84\uFF1B\u5DE5\u4EF6\u4E00\u822C\u5728 work/mapping.json");
13385
14087
  }
13386
- let text2;
14088
+ let text3;
13387
14089
  try {
13388
- text2 = new TextDecoder("utf-8", { fatal: true }).decode(readFileSync5(file));
14090
+ text3 = new TextDecoder("utf-8", { fatal: true }).decode(readFileSync5(file));
13389
14091
  } catch {
13390
14092
  throw new MappingError("undecodable", `${file} \u4E0D\u662F UTF-8 \u7F16\u7801`, "\u5728\u7F16\u8F91\u5668\u91CC\u53E6\u5B58\u4E3A UTF-8 \u518D\u8BD5");
13391
14093
  }
13392
14094
  let body;
13393
14095
  try {
13394
- body = parseJsonSource(text2);
14096
+ body = parseJsonSource(text3);
13395
14097
  } catch (e) {
13396
14098
  if (e instanceof JsonSyntaxError && e.kind === "duplicate-key") {
13397
14099
  throw new MappingError(
@@ -13444,11 +14146,11 @@ function loadModel(raw, where) {
13444
14146
  onlyKeys(obj, MODEL_KEYS, where);
13445
14147
  const onExistingRaw = obj.get("onExisting");
13446
14148
  return {
13447
- model: text(required(obj, "model", where), `${where}.model`),
14149
+ model: text2(required(obj, "model", where), `${where}.model`),
13448
14150
  source: loadSource(required(obj, "source", where), `${where}.source`),
13449
14151
  businessKey: loadBusinessKey(obj.get("businessKey"), `${where}.businessKey`),
13450
14152
  // `onExisting` 缺失**不在这里报** —— 见模块头注释的分工表。
13451
- onExisting: onExistingRaw === void 0 || onExistingRaw === null ? null : text(onExistingRaw, `${where}.onExisting`),
14153
+ onExisting: onExistingRaw === void 0 || onExistingRaw === null ? null : text2(onExistingRaw, `${where}.onExisting`),
13452
14154
  columns: loadColumns(obj.get("columns"), `${where}.columns`),
13453
14155
  constants: loadConstants(obj.get("constants"), `${where}.constants`),
13454
14156
  valueMap: loadValueMap(obj.get("valueMap"), `${where}.valueMap`)
@@ -13458,7 +14160,7 @@ function loadSource(raw, where) {
13458
14160
  const obj = asObject(raw, where);
13459
14161
  onlyKeys(obj, ["file", "sheet", "headerRow"], where);
13460
14162
  const sheetRaw = obj.get("sheet");
13461
- const sheet = sheetRaw === void 0 || sheetRaw === null ? null : text(sheetRaw, `${where}.sheet`);
14163
+ const sheet = sheetRaw === void 0 || sheetRaw === null ? null : text2(sheetRaw, `${where}.sheet`);
13462
14164
  const headerRowRaw = obj.get("headerRow");
13463
14165
  const headerRow = headerRowRaw === void 0 ? DEFAULT_HEADER_ROW : headerRowRaw;
13464
14166
  if (typeof headerRow !== "number" || !Number.isInteger(headerRow) || headerRow < 1) {
@@ -13468,7 +14170,7 @@ function loadSource(raw, where) {
13468
14170
  "\u8868\u5934\u884C\u53F7\u4ECE 1 \u8D77\u7B97\uFF08\u7B2C 1 \u884C\u5C31\u662F 1\uFF09\uFF0C\u4E0D\u662F\u4ECE 0"
13469
14171
  );
13470
14172
  }
13471
- return { file: text(required(obj, "file", where), `${where}.file`), sheet, headerRow };
14173
+ return { file: text2(required(obj, "file", where), `${where}.file`), sheet, headerRow };
13472
14174
  }
13473
14175
  function loadBusinessKey(raw, where) {
13474
14176
  if (raw === void 0 || raw === null) return null;
@@ -13478,7 +14180,7 @@ function loadBusinessKey(raw, where) {
13478
14180
  const refs = /* @__PURE__ */ new Map();
13479
14181
  if (refsRaw !== void 0 && refsRaw !== null) {
13480
14182
  for (const [field, ref] of asObject(refsRaw, `${where}.resolveBy`)) {
13481
- refs.set(text(field, `${where}.resolveBy \u7684\u952E`), loadResolveBy(ref, `${where}.resolveBy.${field}`));
14183
+ refs.set(text2(field, `${where}.resolveBy \u7684\u952E`), loadResolveBy(ref, `${where}.resolveBy.${field}`));
13482
14184
  }
13483
14185
  }
13484
14186
  return {
@@ -13491,8 +14193,8 @@ function loadResolveBy(raw, where) {
13491
14193
  const ref = asObject(raw, where);
13492
14194
  onlyKeys(ref, ["model", "keyField"], where);
13493
14195
  return {
13494
- model: text(required(ref, "model", where), `${where}.model`),
13495
- keyField: text(required(ref, "keyField", where), `${where}.keyField`)
14196
+ model: text2(required(ref, "model", where), `${where}.model`),
14197
+ keyField: text2(required(ref, "keyField", where), `${where}.keyField`)
13496
14198
  };
13497
14199
  }
13498
14200
  function loadColumns(raw, where) {
@@ -13510,8 +14212,8 @@ function loadColumns(raw, where) {
13510
14212
  onlyKeys(obj, ["source", "field", "resolveBy"], spot);
13511
14213
  const rb = obj.get("resolveBy");
13512
14214
  return {
13513
- source: text(required(obj, "source", spot), `${spot}.source`),
13514
- field: text(required(obj, "field", spot), `${spot}.field`),
14215
+ source: text2(required(obj, "source", spot), `${spot}.source`),
14216
+ field: text2(required(obj, "field", spot), `${spot}.field`),
13515
14217
  resolveBy: rb === void 0 || rb === null ? null : loadResolveBy(rb, `${spot}.resolveBy`)
13516
14218
  };
13517
14219
  });
@@ -13594,7 +14296,7 @@ function onlyKeys(obj, allowed, where) {
13594
14296
  );
13595
14297
  }
13596
14298
  }
13597
- function text(value, where) {
14299
+ function text2(value, where) {
13598
14300
  if (typeof value !== "string" || !value.trim()) {
13599
14301
  throw new MappingError(
13600
14302
  "bad-shape",
@@ -13612,7 +14314,7 @@ function textList(value, where) {
13612
14314
  '\u590D\u5408\u952E\u5199\u6210 ["a", "b"]\uFF1B\u5355\u5B57\u6BB5\u952E\u4E5F\u8981\u7528\u6570\u7EC4'
13613
14315
  );
13614
14316
  }
13615
- return value.map((item, i) => text(item, `${where}[${i}]`));
14317
+ return value.map((item, i) => text2(item, `${where}[${i}]`));
13616
14318
  }
13617
14319
  var NOTE_PROVENANCE = ["model", "file"];
13618
14320
  function stamp(note, model, file) {
@@ -13629,14 +14331,14 @@ function stamp(note, model, file) {
13629
14331
  }
13630
14332
  async function scanSources(mapping, baseDir, options = {}) {
13631
14333
  const read = options.readTableImpl ?? readTable;
13632
- const base = baseDir ?? path13.dirname(mapping.path);
14334
+ const base = baseDir ?? path14.dirname(mapping.path);
13633
14335
  const headers = /* @__PURE__ */ new Map();
13634
14336
  const rows = /* @__PURE__ */ new Map();
13635
14337
  const notes = [];
13636
14338
  const problems = [];
13637
14339
  const takenBy = /* @__PURE__ */ new Map();
13638
14340
  for (const [index, mm] of mapping.models.entries()) {
13639
- const file = path13.join(base, mm.source.file);
14341
+ const file = path14.join(base, mm.source.file);
13640
14342
  const owner = takenBy.get(mm.model);
13641
14343
  if (owner !== void 0) {
13642
14344
  problems.push(
@@ -13807,7 +14509,7 @@ function checkOnExisting(mm) {
13807
14509
  return [];
13808
14510
  }
13809
14511
  function checkSourceRef(mm) {
13810
- const suffix = path13.extname(mm.source.file).toLowerCase();
14512
+ const suffix = path14.extname(mm.source.file).toLowerCase();
13811
14513
  if (!SUPPORTED_SUFFIXES.includes(suffix)) {
13812
14514
  return [
13813
14515
  problem(
@@ -14748,16 +15450,16 @@ function rowCycles(parents) {
14748
15450
  const cycles = [];
14749
15451
  for (const start of [...parents.keys()].sort((a, b) => a - b)) {
14750
15452
  if (done.has(start)) continue;
14751
- const path23 = [];
15453
+ const path24 = [];
14752
15454
  const seen = /* @__PURE__ */ new Map();
14753
15455
  let node = start;
14754
15456
  while (node !== void 0 && !seen.has(node) && !done.has(node)) {
14755
- seen.set(node, path23.length);
14756
- path23.push(node);
15457
+ seen.set(node, path24.length);
15458
+ path24.push(node);
14757
15459
  node = parents.get(node);
14758
15460
  }
14759
- if (node !== void 0 && seen.has(node)) cycles.push(path23.slice(seen.get(node)));
14760
- for (const n of path23) done.add(n);
15461
+ if (node !== void 0 && seen.has(node)) cycles.push(path24.slice(seen.get(node)));
15462
+ for (const n of path24) done.add(n);
14761
15463
  }
14762
15464
  return cycles;
14763
15465
  }
@@ -15112,13 +15814,13 @@ var NEEDS_SHEET = [
15112
15814
  ];
15113
15815
  function whyNoSheetNoChecks(sourceFile) {
15114
15816
  const workbook = SHEETED_SUFFIXES.includes(
15115
- path14.extname(sourceFile).toLowerCase()
15817
+ path15.extname(sourceFile).toLowerCase()
15116
15818
  );
15117
- let text2 = `\u{1F534} \u4F9D\u8D56\u8FD9\u4EFD sheet \u7684 ${NEEDS_SHEET.length} \u7EC4\u5224\u636E**\u4E00\u7EC4\u90FD\u6CA1\u8DD1**\uFF1A${NEEDS_SHEET.join("\uFF1B")}`;
15819
+ let text3 = `\u{1F534} \u4F9D\u8D56\u8FD9\u4EFD sheet \u7684 ${NEEDS_SHEET.length} \u7EC4\u5224\u636E**\u4E00\u7EC4\u90FD\u6CA1\u8DD1**\uFF1A${NEEDS_SHEET.join("\uFF1B")}`;
15118
15820
  if (!workbook) {
15119
- text2 += "\u3002\u26A0\uFE0F \u540C\u4E00\u6A21\u578B\u7684 RISK_CHECKS_SKIPPED \u62A5\u7684\u662F**\u66F4\u5C0F\u7684\u6570** \u2014\u2014 \u5B83\u53EA\u6570\u300C\u80FD\u8DD1\u800C\u8FD9\u4E00\u8F6E\u6CA1\u8DD1\u300D\u7684\u7EC4\uFF0C\u800C\u8FD9\u5F20\u6E90\u8868\u4E0D\u662F .xlsx/.xlsm\uFF0C\u65E5\u671F\u5E8F\u5217\u53F7\u90A3\u7EC4\u7B97**\u4E0D\u9002\u7528**\uFF08checks \u91CC applicable=false\uFF09\u3001\u4E0D\u8BA1\u5728\u5185\u3002\u4E24\u4E2A\u6570\u5206\u6BCD\u4E0D\u540C\uFF0C\u4E0D\u662F\u77DB\u76FE";
15821
+ text3 += "\u3002\u26A0\uFE0F \u540C\u4E00\u6A21\u578B\u7684 RISK_CHECKS_SKIPPED \u62A5\u7684\u662F**\u66F4\u5C0F\u7684\u6570** \u2014\u2014 \u5B83\u53EA\u6570\u300C\u80FD\u8DD1\u800C\u8FD9\u4E00\u8F6E\u6CA1\u8DD1\u300D\u7684\u7EC4\uFF0C\u800C\u8FD9\u5F20\u6E90\u8868\u4E0D\u662F .xlsx/.xlsm\uFF0C\u65E5\u671F\u5E8F\u5217\u53F7\u90A3\u7EC4\u7B97**\u4E0D\u9002\u7528**\uFF08checks \u91CC applicable=false\uFF09\u3001\u4E0D\u8BA1\u5728\u5185\u3002\u4E24\u4E2A\u6570\u5206\u6BCD\u4E0D\u540C\uFF0C\u4E0D\u662F\u77DB\u76FE";
15120
15822
  }
15121
- return text2;
15823
+ return text3;
15122
15824
  }
15123
15825
  var PREMISE_BLOCKS3 = {
15124
15826
  // 工件拼不出赋值集合 ⇒ 不知道哪些字段被赋了值。
@@ -15196,7 +15898,7 @@ function unsafeRelReason(rel) {
15196
15898
  if (hasDotDotComponent(rel)) {
15197
15899
  return `\u542B \`..\` \u5206\u91CF\uFF0C\u4F1A\u8BFB\u5230 recon \u4EA7\u7269\u76EE\u5F55\u4E4B\u5916\uFF1A${JSON.stringify(rel)}`;
15198
15900
  }
15199
- if (path14.isAbsolute(rel) || rel.startsWith("/") || rel.startsWith("\\")) {
15901
+ if (path15.isAbsolute(rel) || rel.startsWith("/") || rel.startsWith("\\")) {
15200
15902
  return `\u662F\u7EDD\u5BF9\u8DEF\u5F84\uFF0C\u4E0D\u662F recon \u4EA7\u7269\u91CC\u7684\u76F8\u5BF9\u4F4D\u7F6E\uFF1A${JSON.stringify(rel)}`;
15201
15903
  }
15202
15904
  return null;
@@ -15224,7 +15926,7 @@ var ReconView = class {
15224
15926
  resolve(rel) {
15225
15927
  const reason = unsafeRelReason(rel);
15226
15928
  if (reason !== null) return { file: null, reason };
15227
- const file = path14.join(this.dir, rel);
15929
+ const file = path15.join(this.dir, rel);
15228
15930
  if (!isInside(realOf(file), realOf(this.dir))) {
15229
15931
  return { file: null, reason: `\u89E3\u6790\u4E4B\u540E\u843D\u5728 recon \u4EA7\u7269\u76EE\u5F55\u4E4B\u5916\uFF1A${file}` };
15230
15932
  }
@@ -15234,16 +15936,16 @@ var ReconView = class {
15234
15936
  const { file, reason } = this.resolve(rel);
15235
15937
  if (file === null) return { body: null, failure: "unreadable", detail: reason };
15236
15938
  if (!isFile(file)) return { body: null, failure: "missing", detail: `${file} \u4E0D\u5B58\u5728` };
15237
- let text2;
15939
+ let text3;
15238
15940
  try {
15239
- text2 = decodeUtf8(readFileSync6(file));
15941
+ text3 = decodeUtf8(readFileSync6(file));
15240
15942
  } catch (e) {
15241
15943
  const why = e instanceof Utf8Error ? `${file} \u4E0D\u662F UTF-8 \u7F16\u7801` : `${file} \u8BFB\u4E0D\u4E86\uFF1A${e.message}`;
15242
15944
  return { body: null, failure: "unreadable", detail: why };
15243
15945
  }
15244
15946
  let body;
15245
15947
  try {
15246
- body = JSON.parse(text2);
15948
+ body = JSON.parse(text3);
15247
15949
  } catch (e) {
15248
15950
  return { body: null, failure: "unreadable", detail: `${file} \u4E0D\u662F\u5408\u6CD5 JSON\uFF1A${e.message}` };
15249
15951
  }
@@ -15257,7 +15959,7 @@ var ReconView = class {
15257
15959
  const cached = this.sheets.get(modelKey);
15258
15960
  if (cached !== void 0) return cached;
15259
15961
  const rel = `${MAPPING_SUBDIR}/${modelKey}.json`;
15260
- const got = { ...this.readJson(rel), path: path14.join(this.dir, rel) };
15962
+ const got = { ...this.readJson(rel), path: path15.join(this.dir, rel) };
15261
15963
  this.sheets.set(modelKey, got);
15262
15964
  return got;
15263
15965
  }
@@ -15306,15 +16008,15 @@ var ReconView = class {
15306
16008
  const { file, reason } = this.resolve(ENUMS_FILE);
15307
16009
  if (file === null) return { index: null, failure: "unreadable", detail: reason };
15308
16010
  if (!isFile(file)) return { index: null, failure: "missing", detail: `${file} \u4E0D\u5B58\u5728` };
15309
- let text2;
16011
+ let text3;
15310
16012
  try {
15311
- text2 = decodeUtf8(readFileSync6(file));
16013
+ text3 = decodeUtf8(readFileSync6(file));
15312
16014
  } catch (e) {
15313
16015
  const why = e instanceof Utf8Error ? `${file} \u4E0D\u662F UTF-8 \u7F16\u7801` : `${file} \u8BFB\u4E0D\u4E86\uFF1A${e.message}`;
15314
16016
  return { index: null, failure: "unreadable", detail: why };
15315
16017
  }
15316
16018
  const index = /* @__PURE__ */ new Map();
15317
- const lines = text2.split("\n");
16019
+ const lines = text3.split("\n");
15318
16020
  for (let i = 0; i < lines.length; i += 1) {
15319
16021
  const line = lines[i];
15320
16022
  if (!line.trim()) continue;
@@ -15359,14 +16061,14 @@ function isFile(p) {
15359
16061
  }
15360
16062
  function realOf(p) {
15361
16063
  const rest = [];
15362
- let cur = path14.resolve(p);
16064
+ let cur = path15.resolve(p);
15363
16065
  for (; ; ) {
15364
16066
  try {
15365
- return path14.join(realpathSync(cur), ...rest);
16067
+ return path15.join(realpathSync(cur), ...rest);
15366
16068
  } catch {
15367
- const parent = path14.dirname(cur);
15368
- if (parent === cur) return path14.resolve(p);
15369
- rest.unshift(path14.basename(cur));
16069
+ const parent = path15.dirname(cur);
16070
+ if (parent === cur) return path15.resolve(p);
16071
+ rest.unshift(path15.basename(cur));
15370
16072
  cur = parent;
15371
16073
  }
15372
16074
  }
@@ -15964,7 +16666,7 @@ function noteProblems(notes) {
15964
16666
  const model = n.model;
15965
16667
  const file = n.file;
15966
16668
  const column = n.column;
15967
- const suffix = typeof file === "string" ? path14.extname(file).toLowerCase() : "";
16669
+ const suffix = typeof file === "string" ? path15.extname(file).toLowerCase() : "";
15968
16670
  const notation = NOTATION_BY_SUFFIX[suffix] ?? NOTATION_UNKNOWN;
15969
16671
  out.push(
15970
16672
  problem3(
@@ -16134,7 +16836,7 @@ function riskModel(mm, entry, recon, tables, plan = null) {
16134
16836
  );
16135
16837
  block("AC6_PREMISE_SOURCE_ROWS_EMPTY");
16136
16838
  }
16137
- if (!SHEETED_SUFFIXES.includes(path14.extname(mm.source.file).toLowerCase())) {
16839
+ if (!SHEETED_SUFFIXES.includes(path15.extname(mm.source.file).toLowerCase())) {
16138
16840
  notApplicable.set(CHECK_DATE_SERIAL, WHY_NOT_A_WORKBOOK);
16139
16841
  } else if (rows === void 0) {
16140
16842
  block(WHY_NO_SOURCE_ROWS, [CHECK_DATE_SERIAL]);
@@ -16393,19 +17095,19 @@ var MAPPING_FILE = "mapping.json";
16393
17095
  var OFFLINE_COMMANDS = ["find", "values"];
16394
17096
  function seedWorkDir(args) {
16395
17097
  if (args.work) return args.work;
16396
- return path15.join(args.out, WORK_DIRNAME, tenantSegment(String(args.tenant)));
17098
+ return path16.join(args.out, WORK_DIRNAME, tenantSegment(String(args.tenant)));
16397
17099
  }
16398
17100
  function seedMappingPath(args, work) {
16399
- return args.mapping ? args.mapping : path15.join(work, MAPPING_FILE);
17101
+ return args.mapping ? args.mapping : path16.join(work, MAPPING_FILE);
16400
17102
  }
16401
17103
  function seedBaselines(out, tenant) {
16402
- const base = path15.join(out, "recon", tenantSegment(String(tenant)));
17104
+ const base = path16.join(out, "recon", tenantSegment(String(tenant)));
16403
17105
  if (!existsSync8(base) || !statSync7(base).isDirectory()) return [base, []];
16404
17106
  const found = [];
16405
17107
  for (const name of readdirSync2(base).sort()) {
16406
- const reconDir = path15.join(base, name);
17108
+ const reconDir = path16.join(base, name);
16407
17109
  if (!statSync7(reconDir).isDirectory()) continue;
16408
- const indexFile = path15.join(reconDir, "index", "fields.jsonl");
17110
+ const indexFile = path16.join(reconDir, "index", "fields.jsonl");
16409
17111
  if (existsSync8(indexFile)) found.push({ indexFile, reconDir });
16410
17112
  }
16411
17113
  return [base, found];
@@ -16537,7 +17239,7 @@ function existingJournalStop(journalPath, entries) {
16537
17239
  }
16538
17240
 
16539
17241
  // src/fde/seed/plan-io.ts
16540
- import * as path16 from "path";
17242
+ import * as path17 from "path";
16541
17243
  var PLAN_JSON_KEYS = [
16542
17244
  "version",
16543
17245
  "roundId",
@@ -16674,7 +17376,7 @@ var PlanReadError = class extends Error {
16674
17376
  };
16675
17377
  function readImportPlan(out) {
16676
17378
  const work = new WorkLayout(out);
16677
- const target = path16.join(out, IMPORT_PLAN_FILE);
17379
+ const target = path17.join(out, IMPORT_PLAN_FILE);
16678
17380
  if (!work.exists(IMPORT_PLAN_FILE)) {
16679
17381
  throw new PlanReadError(
16680
17382
  "plan-missing",
@@ -16868,7 +17570,7 @@ function rowFromJson(r) {
16868
17570
  import { createHash as createHash4 } from "crypto";
16869
17571
  import { existsSync as existsSync9, statSync as statSync8 } from "fs";
16870
17572
  import * as os3 from "os";
16871
- import * as path17 from "path";
17573
+ import * as path18 from "path";
16872
17574
  var JOURNAL_FILE = "journal.jsonl";
16873
17575
  var STATUSES = ["done", "skipped", "failed", "unknown", "quarantined"];
16874
17576
  var STEP_SEND = "send";
@@ -16936,21 +17638,21 @@ function nowStamp(at = /* @__PURE__ */ new Date()) {
16936
17638
  function stampOf(at) {
16937
17639
  return at.toISOString().replace(/Z$/, "+00:00");
16938
17640
  }
16939
- function parseStamp(text2) {
16940
- if (typeof text2 !== "string" || !text2.trim()) {
16941
- return [null, `\u4E0D\u662F\u4E00\u4E2A\u975E\u7A7A\u5B57\u7B26\u4E32\uFF1A${JSON.stringify(text2)}`];
17641
+ function parseStamp(text3) {
17642
+ if (typeof text3 !== "string" || !text3.trim()) {
17643
+ return [null, `\u4E0D\u662F\u4E00\u4E2A\u975E\u7A7A\u5B57\u7B26\u4E32\uFF1A${JSON.stringify(text3)}`];
16942
17644
  }
16943
- let normalised = text2.trim();
17645
+ let normalised = text3.trim();
16944
17646
  if (/[Zz]$/.test(normalised)) normalised = `${normalised.slice(0, -1)}+00:00`;
16945
17647
  if (!/(?:[+-]\d{2}:?\d{2})$/.test(normalised)) {
16946
17648
  return [
16947
17649
  null,
16948
- `${JSON.stringify(text2)} \u6CA1\u6709\u65F6\u533A\u504F\u79FB \u2014\u2014 \u5B83\u662F\u672C\u673A\u65F6\u95F4\u8FD8\u662F UTC \u65E0\u4ECE\u5F97\u77E5\uFF0C\u4E24\u79CD\u89E3\u91CA\u5DEE\u51FA\u6765\u7684\u5C0F\u65F6\u6570\u8DB3\u4EE5\u628A\u300C\u9648\u65E7\u300D\u5224\u6210\u300C\u6D3B\u7740\u300D`
17650
+ `${JSON.stringify(text3)} \u6CA1\u6709\u65F6\u533A\u504F\u79FB \u2014\u2014 \u5B83\u662F\u672C\u673A\u65F6\u95F4\u8FD8\u662F UTC \u65E0\u4ECE\u5F97\u77E5\uFF0C\u4E24\u79CD\u89E3\u91CA\u5DEE\u51FA\u6765\u7684\u5C0F\u65F6\u6570\u8DB3\u4EE5\u628A\u300C\u9648\u65E7\u300D\u5224\u6210\u300C\u6D3B\u7740\u300D`
16949
17651
  ];
16950
17652
  }
16951
17653
  const moment = new Date(normalised);
16952
17654
  if (Number.isNaN(moment.getTime())) {
16953
- return [null, `\u4E0D\u662F\u80FD\u89E3\u6790\u7684 ISO 8601 \u65F6\u95F4\u6233\uFF1A${JSON.stringify(text2)}`];
17655
+ return [null, `\u4E0D\u662F\u80FD\u89E3\u6790\u7684 ISO 8601 \u65F6\u95F4\u6233\uFF1A${JSON.stringify(text3)}`];
16954
17656
  }
16955
17657
  return [moment, ""];
16956
17658
  }
@@ -16974,8 +17676,8 @@ function canonicalise(value, at = "$") {
16974
17676
  return out;
16975
17677
  }
16976
17678
  function payloadHash(payload) {
16977
- const text2 = JSON.stringify(canonicalise(payload));
16978
- return `sha256:${createHash4("sha256").update(text2, "utf8").digest("hex")}`;
17679
+ const text3 = JSON.stringify(canonicalise(payload));
17680
+ return `sha256:${createHash4("sha256").update(text3, "utf8").digest("hex")}`;
16979
17681
  }
16980
17682
  function businessKeyOf(value) {
16981
17683
  if (typeof value === "string" || !Array.isArray(value)) {
@@ -17142,7 +17844,7 @@ var Journal = class _Journal {
17142
17844
  constructor(workDir, entries = [], exists = false, waivers = []) {
17143
17845
  this.workDir = workDirOf(workDir);
17144
17846
  this.layout = new WorkLayout(this.workDir);
17145
- this.path = path17.join(this.workDir, JOURNAL_FILE);
17847
+ this.path = path18.join(this.workDir, JOURNAL_FILE);
17146
17848
  this.entries = [...entries];
17147
17849
  this.waivers = [...waivers];
17148
17850
  this.exists = exists;
@@ -17156,11 +17858,11 @@ var Journal = class _Journal {
17156
17858
  */
17157
17859
  static load(p) {
17158
17860
  const work = workDirOf(p);
17159
- const target = path17.join(work, JOURNAL_FILE);
17861
+ const target = path18.join(work, JOURNAL_FILE);
17160
17862
  if (!existsSync9(target)) return new _Journal(work, [], false);
17161
- let text2;
17863
+ let text3;
17162
17864
  try {
17163
- text2 = new WorkLayout(work).readText(JOURNAL_FILE);
17865
+ text3 = new WorkLayout(work).readText(JOURNAL_FILE);
17164
17866
  } catch (e) {
17165
17867
  if (e instanceof TypeError) {
17166
17868
  throw new JournalError(
@@ -17177,7 +17879,7 @@ var Journal = class _Journal {
17177
17879
  }
17178
17880
  const entries = [];
17179
17881
  const waivers = [];
17180
- text2.split("\n").forEach((line, i) => {
17882
+ text3.split("\n").forEach((line, i) => {
17181
17883
  if (!line.trim()) return;
17182
17884
  const where = `${target} \u7B2C ${i + 1} \u884C`;
17183
17885
  let row;
@@ -17452,18 +18154,18 @@ function sameIdentity(a, b) {
17452
18154
  return a.length === b.length && a.every((x, i) => x === b[i]);
17453
18155
  }
17454
18156
  function readLease(layout, file = LEASE_FILE) {
17455
- const p = path17.join(layout.dir, file);
18157
+ const p = path18.join(layout.dir, file);
17456
18158
  if (!existsSync9(p)) return [null, `${p} \u4E0D\u5B58\u5728`];
17457
- let text2;
18159
+ let text3;
17458
18160
  try {
17459
- text2 = layout.readText(file);
18161
+ text3 = layout.readText(file);
17460
18162
  } catch (e) {
17461
18163
  if (e instanceof TypeError) return [null, `${p} \u4E0D\u662F UTF-8 \u7F16\u7801`];
17462
18164
  return [null, `${p} \u8BFB\u4E0D\u4E86\uFF1A${String(e)}`];
17463
18165
  }
17464
18166
  let body;
17465
18167
  try {
17466
- body = JSON.parse(text2);
18168
+ body = JSON.parse(text3);
17467
18169
  } catch (e) {
17468
18170
  return [null, `${p} \u4E0D\u662F\u5408\u6CD5 JSON\uFF1A${String(e)}`];
17469
18171
  }
@@ -17511,7 +18213,7 @@ var Lease = class {
17511
18213
  beatMark;
17512
18214
  constructor(layout, spec, reclaimed = null, clock = SYSTEM_CLOCK) {
17513
18215
  this.layout = layout;
17514
- this.path = path17.join(layout.dir, LEASE_FILE);
18216
+ this.path = path18.join(layout.dir, LEASE_FILE);
17515
18217
  this.host = spec.host;
17516
18218
  this.pid = spec.pid;
17517
18219
  this.roundId = spec.roundId;
@@ -17579,7 +18281,7 @@ var Lease = class {
17579
18281
  throw new LeaseViolation(
17580
18282
  "lease-unwritable",
17581
18283
  `\u76D6\u5FC3\u8DF3\u65F6\u5199\u4E0D\u8FDB\u79DF\u7EA6\u6587\u4EF6 ${this.path}\uFF1A${String(e)}`,
17582
- `**\u8FD9\u4E00\u6B21\u5FC3\u8DF3\u6CA1\u6709\u76D6\u4E0A**\uFF0C\u79DF\u7EA6\u6587\u4EF6\u7684\u5185\u5BB9**\u6CA1\u6709\u88AB\u6539\u52A8**\uFF08\u4E34\u65F6\u6587\u4EF6\u5DF2\u6536\u62FE\u6389\uFF0C\u6539\u540D\u6CA1\u9876\u4E0A\u53BB\uFF09\u3002${leaseStampNote(held.heartbeatAt, beat, attemptedAt)}\u5199\u4E4B\u524D\u521A\u6838\u5BF9\u8FC7\u8EAB\u4EFD \u2014\u2014 **\u90A3\u4E00\u6B21\u8BFB\u5230\u7684**\u79DF\u7EA6\u662F\u6211\u65B9\u7684\u3002\u4E09\u79CD\u5E38\u89C1\u6210\u56E0\uFF1A\u2460 \u78C1\u76D8\u6EE1\uFF1B\u2461 \u76EE\u5F55\u53EA\u8BFB\u6216\u6743\u9650\u4E0D\u8DB3\uFF1B\u2462 \u4ECB\u8D28\u51FA\u9519\u3002**\u5148\u505C\u624B\u518D\u5904\u7406**\uFF1A\u5DF2\u7ECF\u53D1\u51FA\u53BB\u7684\u5199\u90FD\u8BB0\u5728 ${path17.dirname(this.path)} \u7684\u53F0\u8D26\u91CC\uFF08\u5199\u524D\u843D\u8D26\uFF1A\u53D1\u8BF7\u6C42\u4E4B\u524D\u5148 begin \u843D\u4E00\u6761 unknown\uFF09\u3002${LEASE_JUDGE_SIGNPOST}`
18284
+ `**\u8FD9\u4E00\u6B21\u5FC3\u8DF3\u6CA1\u6709\u76D6\u4E0A**\uFF0C\u79DF\u7EA6\u6587\u4EF6\u7684\u5185\u5BB9**\u6CA1\u6709\u88AB\u6539\u52A8**\uFF08\u4E34\u65F6\u6587\u4EF6\u5DF2\u6536\u62FE\u6389\uFF0C\u6539\u540D\u6CA1\u9876\u4E0A\u53BB\uFF09\u3002${leaseStampNote(held.heartbeatAt, beat, attemptedAt)}\u5199\u4E4B\u524D\u521A\u6838\u5BF9\u8FC7\u8EAB\u4EFD \u2014\u2014 **\u90A3\u4E00\u6B21\u8BFB\u5230\u7684**\u79DF\u7EA6\u662F\u6211\u65B9\u7684\u3002\u4E09\u79CD\u5E38\u89C1\u6210\u56E0\uFF1A\u2460 \u78C1\u76D8\u6EE1\uFF1B\u2461 \u76EE\u5F55\u53EA\u8BFB\u6216\u6743\u9650\u4E0D\u8DB3\uFF1B\u2462 \u4ECB\u8D28\u51FA\u9519\u3002**\u5148\u505C\u624B\u518D\u5904\u7406**\uFF1A\u5DF2\u7ECF\u53D1\u51FA\u53BB\u7684\u5199\u90FD\u8BB0\u5728 ${path18.dirname(this.path)} \u7684\u53F0\u8D26\u91CC\uFF08\u5199\u524D\u843D\u8D26\uFF1A\u53D1\u8BF7\u6C42\u4E4B\u524D\u5148 begin \u843D\u4E00\u6761 unknown\uFF09\u3002${LEASE_JUDGE_SIGNPOST}`
17583
18285
  );
17584
18286
  }
17585
18287
  this.beatMark = this.clock.monotonic();
@@ -17625,7 +18327,7 @@ function acquireLease(workDir, roundId, clock = SYSTEM_CLOCK) {
17625
18327
  );
17626
18328
  }
17627
18329
  const layout = new WorkLayout(workDirOf(workDir));
17628
- const p = path17.join(layout.dir, LEASE_FILE);
18330
+ const p = path18.join(layout.dir, LEASE_FILE);
17629
18331
  const me = [hostname2(), process.pid, roundId];
17630
18332
  const now = clock.now();
17631
18333
  const fresh = new Lease(
@@ -18448,7 +19150,7 @@ function applyReportText(report) {
18448
19150
 
18449
19151
  // src/fde/seed/drift.ts
18450
19152
  import { existsSync as existsSync10, readFileSync as readFileSync8, realpathSync as realpathSync2, statSync as statSync9 } from "fs";
18451
- import * as path18 from "path";
19153
+ import * as path19 from "path";
18452
19154
  var VERDICT_SAME = "same";
18453
19155
  var VERDICT_DIVERGED = "diverged";
18454
19156
  var VERDICT_INCOMPARABLE = "incomparable";
@@ -18475,17 +19177,17 @@ function resolveBaselineDir(outRoot, baselineRef) {
18475
19177
  return [null, CAUSE_PLAN_HAS_NO_BASELINE];
18476
19178
  }
18477
19179
  const ref = String(baselineRef);
18478
- const root = path18.join(outRoot, RECON_DIRNAME);
19180
+ const root = path19.join(outRoot, RECON_DIRNAME);
18479
19181
  const parts = ref.split(/[\\/]+/);
18480
- if (!ref || parts.includes("..") || path18.isAbsolute(ref) || /^[A-Za-z]:/.test(ref)) {
19182
+ if (!ref || parts.includes("..") || path19.isAbsolute(ref) || /^[A-Za-z]:/.test(ref)) {
18481
19183
  return [null, CAUSE_BASELINE_NOT_ON_DISK];
18482
19184
  }
18483
- const base = path18.join(root, ref);
19185
+ const base = path19.join(root, ref);
18484
19186
  let inside;
18485
19187
  try {
18486
19188
  const realRoot = realpathSync2(root);
18487
19189
  const realBase = realpathSync2(base);
18488
- inside = realBase === realRoot || realBase.startsWith(realRoot + path18.sep);
19190
+ inside = realBase === realRoot || realBase.startsWith(realRoot + path19.sep);
18489
19191
  } catch {
18490
19192
  inside = false;
18491
19193
  }
@@ -18499,7 +19201,7 @@ function loadRecordedFingerprint(outRoot, baselineRef) {
18499
19201
  if (cause !== null) return [null, cause];
18500
19202
  let body;
18501
19203
  try {
18502
- body = JSON.parse(readFileSync8(path18.join(base, FINGERPRINT_FILE), "utf-8"));
19204
+ body = JSON.parse(readFileSync8(path19.join(base, FINGERPRINT_FILE), "utf-8"));
18503
19205
  } catch {
18504
19206
  return [null, CAUSE_FINGERPRINT_UNREADABLE];
18505
19207
  }
@@ -19103,8 +19805,8 @@ function isZeroNetwork(args) {
19103
19805
  function askedTheDatabase(recon) {
19104
19806
  return recon.premises.length > 0;
19105
19807
  }
19106
- function indent(text2) {
19107
- return text2.split("\n").join("\n ");
19808
+ function indent(text3) {
19809
+ return text3.split("\n").join("\n ");
19108
19810
  }
19109
19811
  function verifyAttention(delivery, recon) {
19110
19812
  const agreeing = new Set(AGREEING_VERDICTS);
@@ -19349,7 +20051,7 @@ function writeRisk(risk, out) {
19349
20051
 
19350
20052
  // src/fde/seed/value-hints.ts
19351
20053
  import { existsSync as existsSync11, readFileSync as readFileSync9 } from "fs";
19352
- import * as path19 from "path";
20054
+ import * as path20 from "path";
19353
20055
  var HINT_REF = (domain) => ` \u503C\uFF1A\u586B id\uFF08\u4E0D\u662F code\uFF09\u2190 ${domain}`;
19354
20056
  var HINT_NO_DOMAIN = (to) => ` \u503C\uFF1A\u586B ${to} \u7684 id\uFF08\u4E0D\u662F code\uFF09\uFF1B\u65E0\u5BF9\u7167\u8868\uFF0C\u6309\u4E1A\u52A1\u952E\u73B0\u67E5`;
19355
20057
  var HINT_ENUM = (n, model) => ` \u503C\uFF1A\u679A\u4E3E ${n} \u9879 \u2190 mapping/${model}.json`;
@@ -19365,7 +20067,7 @@ function isLocalName(name) {
19365
20067
  if (typeof name !== "string" || name.length === 0) return false;
19366
20068
  if (name.includes("/") || name.includes("\\")) return false;
19367
20069
  if (name === "." || name === "..") return false;
19368
- return !path19.isAbsolute(name);
20070
+ return !path20.isAbsolute(name);
19369
20071
  }
19370
20072
  var readJson = (file) => {
19371
20073
  try {
@@ -19385,7 +20087,7 @@ var ValueHints = class {
19385
20087
  /** → `{modelKey: completeness}`;**索引根本读不到时返回 `null`**(与「读到了但是空的」分开)。 */
19386
20088
  domainIndex() {
19387
20089
  if (this.domains === void 0) {
19388
- const body = readJson(path19.join(this.root, "valuedomain", "_index.json"));
20090
+ const body = readJson(path20.join(this.root, "valuedomain", "_index.json"));
19389
20091
  const by = isRec(body) ? body.byCompleteness : void 0;
19390
20092
  if (!isRec(by)) {
19391
20093
  this.domains = null;
@@ -19406,7 +20108,7 @@ var ValueHints = class {
19406
20108
  if (!this.sheets.has(key)) {
19407
20109
  let fields = null;
19408
20110
  if (isLocalName(key)) {
19409
- const body = readJson(path19.join(this.root, "mapping", `${key}.json`));
20111
+ const body = readJson(path20.join(this.root, "mapping", `${key}.json`));
19410
20112
  const rows = isRec(body) ? body.fields : void 0;
19411
20113
  if (Array.isArray(rows)) {
19412
20114
  fields = /* @__PURE__ */ new Map();
@@ -19424,7 +20126,7 @@ var ValueHints = class {
19424
20126
  const index = this.domainIndex();
19425
20127
  const completeness = index === null ? void 0 : index.get(target);
19426
20128
  const pointer = ref.valueDomain;
19427
- const landed = isLocalName(target) && existsSync11(path19.join(this.root, "valuedomain", `${target}.json`));
20129
+ const landed = isLocalName(target) && existsSync11(path20.join(this.root, "valuedomain", `${target}.json`));
19428
20130
  let line;
19429
20131
  if (pointer && completeness && completeness !== "unavailable" && landed) {
19430
20132
  line = HINT_REF(String(pointer));
@@ -19491,10 +20193,10 @@ var VISIBLE_DIMENSIONS = /* @__PURE__ */ new Set(["name", "key", "model"]);
19491
20193
  var asList = (v) => v === null || v === void 0 ? [] : Array.isArray(v) ? v : [v];
19492
20194
  var str2 = (v) => v === null || v === void 0 ? "" : String(v);
19493
20195
  var bytes = (s) => Buffer.byteLength(s, "utf-8");
19494
- function loadRows(text2) {
20196
+ function loadRows(text3) {
19495
20197
  const rows = [];
19496
20198
  const problems = [];
19497
- const lines = text2.split("\n");
20199
+ const lines = text3.split("\n");
19498
20200
  lines.forEach((raw, i) => {
19499
20201
  const line = raw.trim();
19500
20202
  if (!line) return;
@@ -19615,7 +20317,7 @@ function renderFind(hits, term, total, options = {}) {
19615
20317
 
19616
20318
  // src/fde/seed/values.ts
19617
20319
  import { existsSync as existsSync12, readFileSync as readFileSync10 } from "fs";
19618
- import * as path20 from "path";
20320
+ import * as path21 from "path";
19619
20321
  var readJson2 = (file) => {
19620
20322
  try {
19621
20323
  return JSON.parse(readFileSync10(file, "utf-8"));
@@ -19662,13 +20364,13 @@ function valuesRoundCaveat(round) {
19662
20364
  return VALUES_ROUND_MIXED(String(state ?? "unknown"));
19663
20365
  }
19664
20366
  function renderValues(root, model, options = {}) {
19665
- const indexBody = readJson2(path20.join(root, "valuedomain", "_index.json"));
20367
+ const indexBody = readJson2(path21.join(root, "valuedomain", "_index.json"));
19666
20368
  const byCompleteness = isRec2(indexBody) ? indexBody.byCompleteness : void 0;
19667
20369
  if (!isRec2(byCompleteness)) {
19668
20370
  return {
19669
20371
  ok: false,
19670
20372
  kind: "index-unreadable",
19671
- message: `\u8BFB\u4E0D\u5230 valuedomain/_index.json\uFF08${root}\uFF09\u2014\u2014 \u53EF\u80FD\u662F\uFF1A\u8FD9\u4EFD\u57FA\u7EBF\u7531\u66F4\u65E9\u7248\u672C\u722C\u7684\u3001\u4F60\u6CA1\u62F7 valuedomain/ \u76EE\u5F55\u8FC7\u6765\u3001\u6216\u8005\u90A3\u4E2A\u6587\u4EF6\u574F\u4E86\u3002\u5148 \`ls ${path20.join(root, "valuedomain")}\` \u770B\u4E00\u773C\uFF1B\u786E\u5B9E\u6CA1\u6709\u5C31\u91CD\u8DD1\u4E00\u6B21 recon\u3002`
20373
+ message: `\u8BFB\u4E0D\u5230 valuedomain/_index.json\uFF08${root}\uFF09\u2014\u2014 \u53EF\u80FD\u662F\uFF1A\u8FD9\u4EFD\u57FA\u7EBF\u7531\u66F4\u65E9\u7248\u672C\u722C\u7684\u3001\u4F60\u6CA1\u62F7 valuedomain/ \u76EE\u5F55\u8FC7\u6765\u3001\u6216\u8005\u90A3\u4E2A\u6587\u4EF6\u574F\u4E86\u3002\u5148 \`ls ${path21.join(root, "valuedomain")}\` \u770B\u4E00\u773C\uFF1B\u786E\u5B9E\u6CA1\u6709\u5C31\u91CD\u8DD1\u4E00\u6B21 recon\u3002`
19672
20374
  };
19673
20375
  }
19674
20376
  let completeness;
@@ -19679,7 +20381,7 @@ function renderValues(root, model, options = {}) {
19679
20381
  }
19680
20382
  }
19681
20383
  if (completeness === void 0) {
19682
- if (isLocalName(model) && existsSync12(path20.join(root, "mapping", `${model}.json`))) {
20384
+ if (isLocalName(model) && existsSync12(path21.join(root, "mapping", `${model}.json`))) {
19683
20385
  return {
19684
20386
  ok: false,
19685
20387
  kind: "not-a-code-table",
@@ -19689,10 +20391,10 @@ function renderValues(root, model, options = {}) {
19689
20391
  return {
19690
20392
  ok: false,
19691
20393
  kind: "model-not-in-baseline",
19692
- message: `\u57FA\u7EBF\u91CC\u6CA1\u6709\u8FD9\u4E2A\u6A21\u578B\uFF1A${model}\u3002\`ls ${path20.join(root, "mapping")}\` \u770B\u6709\u54EA\u4E9B\u3002`
20394
+ message: `\u57FA\u7EBF\u91CC\u6CA1\u6709\u8FD9\u4E2A\u6A21\u578B\uFF1A${model}\u3002\`ls ${path21.join(root, "mapping")}\` \u770B\u6709\u54EA\u4E9B\u3002`
19693
20395
  };
19694
20396
  }
19695
- const file = path20.join(root, "valuedomain", `${model}.json`);
20397
+ const file = path21.join(root, "valuedomain", `${model}.json`);
19696
20398
  if (!isLocalName(model) || !existsSync12(file)) {
19697
20399
  return {
19698
20400
  ok: false,
@@ -19807,7 +20509,7 @@ function buildCarrierResult(carrier, verdict2, options = {}) {
19807
20509
 
19808
20510
  // src/fde/triage/probe.ts
19809
20511
  import { readFileSync as readFileSync11 } from "fs";
19810
- import * as path21 from "path";
20512
+ import * as path22 from "path";
19811
20513
  var WORKSPACES_PATH = "/api/tenant-extension/workspaces";
19812
20514
  var MODELS_REL = "models.json";
19813
20515
  var FIELDS_REL = "index/fields.jsonl";
@@ -19834,10 +20536,10 @@ function unavailableCell(carrier, err) {
19834
20536
  });
19835
20537
  }
19836
20538
  function readArtifactJson(dir, rel) {
19837
- return JSON.parse(readFileSync11(path21.join(dir, rel), "utf8"));
20539
+ return JSON.parse(readFileSync11(path22.join(dir, rel), "utf8"));
19838
20540
  }
19839
20541
  function readArtifactJsonl(dir, rel) {
19840
- const body = readFileSync11(path21.join(dir, rel), "utf8");
20542
+ const body = readFileSync11(path22.join(dir, rel), "utf8");
19841
20543
  const rows = [];
19842
20544
  for (const line of body.split("\n")) {
19843
20545
  const trimmed = line.trim();
@@ -20258,8 +20960,8 @@ var META_JOURNAL_FILE = "meta-lifecycle.jsonl";
20258
20960
  function workspaceLayer(workspaceKey) {
20259
20961
  return WORKSPACE_LAYER_PREFIX + (workspaceKey || "");
20260
20962
  }
20261
- function contentHash(text2) {
20262
- return `sha256:${createHash5("sha256").update(text2, "utf-8").digest("hex")}`;
20963
+ function contentHash(text3) {
20964
+ return `sha256:${createHash5("sha256").update(text3, "utf-8").digest("hex")}`;
20263
20965
  }
20264
20966
  function metaFileUrl(metaPath2) {
20265
20967
  return `${TENANT_META_FILE_PATH}?path=${encodeURIComponent(metaPath2)}`;
@@ -20775,7 +21477,7 @@ async function runActiveVerify(client, args) {
20775
21477
  let missing = [];
20776
21478
  let verifyCode = VERIFY_CRASHED;
20777
21479
  let bindingState = BINDING_UNTOUCHED;
20778
- let pending;
21480
+ let pending2;
20779
21481
  let raised = false;
20780
21482
  try {
20781
21483
  const off = await client.put(DEV_MODE_PATH, unbindPayload());
@@ -20853,7 +21555,7 @@ async function runActiveVerify(client, args) {
20853
21555
  }
20854
21556
  verifyCode = code || VERIFY_OK;
20855
21557
  } catch (e) {
20856
- pending = e;
21558
+ pending2 = e;
20857
21559
  raised = true;
20858
21560
  } finally {
20859
21561
  const [rebindStep, state, restoreCode] = await rebind(client, args.workspaceKey, w);
@@ -20866,11 +21568,11 @@ async function runActiveVerify(client, args) {
20866
21568
  rebindStep.recovery,
20867
21569
  verdict(restoreCode, done, bindingState, layer, w, present, missing),
20868
21570
  verifyCode,
20869
- pending
21571
+ pending2
20870
21572
  );
20871
21573
  }
20872
21574
  }
20873
- if (raised) throw pending;
21575
+ if (raised) throw pending2;
20874
21576
  return verdict(code, done, bindingState, layer, w, present, missing);
20875
21577
  }
20876
21578
 
@@ -20904,16 +21606,16 @@ var CNB_FAVICON_URL = `${CNB_ORIGIN}/favicon.ico`;
20904
21606
 
20905
21607
  // src/jira/client.ts
20906
21608
  import { execFileSync } from "child_process";
20907
- import { promises as fs11 } from "fs";
21609
+ import { promises as fs12 } from "fs";
20908
21610
  import os4 from "os";
20909
- import path22 from "path";
20910
- var JIRA_TOKEN_FILE = () => process.env.JIRA_TOKEN_FILE || path22.join(os4.homedir(), ".config", "hcm", "jira-token");
21611
+ import path23 from "path";
21612
+ var JIRA_TOKEN_FILE = () => process.env.JIRA_TOKEN_FILE || path23.join(os4.homedir(), ".config", "hcm", "jira-token");
20911
21613
  async function jiraTokenSource() {
20912
21614
  if (process.env.JIRA_TOKEN?.trim()) return { token: process.env.JIRA_TOKEN.trim(), from: "\u73AF\u5883\u53D8\u91CF JIRA_TOKEN" };
20913
21615
  const file = JIRA_TOKEN_FILE();
20914
21616
  try {
20915
- const stat = await fs11.stat(file);
20916
- const value = (await fs11.readFile(file, "utf8")).trim();
21617
+ const stat = await fs12.stat(file);
21618
+ const value = (await fs12.readFile(file, "utf8")).trim();
20917
21619
  if (value) {
20918
21620
  if (stat.mode & 63) process.stderr.write(`[jira] \u8B66\u544A\uFF1A${file} \u5BF9\u5176\u4ED6\u7528\u6237\u53EF\u8BFB\uFF08chmod 600 \u6536\u7D27\uFF09
20919
21621
  `);
@@ -20967,11 +21669,11 @@ var JiraClient = class {
20967
21669
  body: init.body !== void 0 ? JSON.stringify(init.body) : void 0,
20968
21670
  signal: AbortSignal.timeout(this.timeoutMs)
20969
21671
  });
20970
- const text2 = await res.text();
21672
+ const text3 = await res.text();
20971
21673
  if (!res.ok) {
20972
- let detail = text2.slice(0, 600);
21674
+ let detail = text3.slice(0, 600);
20973
21675
  try {
20974
- const j = JSON.parse(text2);
21676
+ const j = JSON.parse(text3);
20975
21677
  const msgs = [...j.errorMessages ?? [], ...Object.entries(j.errors ?? {}).map(([k, v]) => `${k}: ${v}`)];
20976
21678
  if (msgs.length) detail = msgs.join("\uFF1B");
20977
21679
  } catch {
@@ -20979,7 +21681,7 @@ var JiraClient = class {
20979
21681
  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" : "";
20980
21682
  throw new Error(`Jira ${method} ${p} \u2192 ${res.status}\uFF1A${detail}${hint}`);
20981
21683
  }
20982
- return text2 ? JSON.parse(text2) : null;
21684
+ return text3 ? JSON.parse(text3) : null;
20983
21685
  }
20984
21686
  serverInfo() {
20985
21687
  return this.api("/rest/api/2/serverInfo");
@@ -21096,9 +21798,9 @@ async function createJiraClient(opts = {}) {
21096
21798
 
21097
21799
  // src/jira/refs.ts
21098
21800
  var REF_RE = /hcm\/(hcm_nx_(?:core|cli|cloud))(?:#|\/-\/issues\/)(\d+)/g;
21099
- function linkedRepoRefs(text2) {
21801
+ function linkedRepoRefs(text3) {
21100
21802
  const out = /* @__PURE__ */ new Map();
21101
- for (const m of String(text2 ?? "").matchAll(REF_RE)) {
21803
+ for (const m of String(text3 ?? "").matchAll(REF_RE)) {
21102
21804
  out.set(`hcm/${m[1]}#${m[2]}`, { repo: `hcm/${m[1]}`, number: m[2] });
21103
21805
  }
21104
21806
  return [...out.values()];
@@ -21123,6 +21825,7 @@ export {
21123
21825
  APPLY_PROBLEM_CODES,
21124
21826
  PROBLEM_CODES as ARTIFACT_PROBLEM_CODES,
21125
21827
  AUTH_INFO_PATH,
21828
+ AUTH_SESSION_INFO_PATH,
21126
21829
  ApplyInvariantError,
21127
21830
  ApplyPremiseError,
21128
21831
  BINDING_RESTORED,
@@ -21149,6 +21852,9 @@ export {
21149
21852
  CHANGE_UNKNOWN,
21150
21853
  CHANGE_WRITTEN,
21151
21854
  CHECK_GROUPS2 as CHECK_GROUPS,
21855
+ CLI_AUTHORIZE_PATH,
21856
+ CLI_EXCHANGE_PATH,
21857
+ CLI_VERIFICATION_PATH,
21152
21858
  CNB_FAVICON_URL,
21153
21859
  CNB_ORIGIN,
21154
21860
  CODE_BINDING_ELSEWHERE,
@@ -21189,6 +21895,7 @@ export {
21189
21895
  EFFECT_UNKNOWN,
21190
21896
  EFFECT_WRITES,
21191
21897
  ENUM_SHOW,
21898
+ ENV_FILE,
21192
21899
  EXEMPTIBLE_CODES,
21193
21900
  EXEMPTION_CODES,
21194
21901
  EXEMPTION_REQUIRED_KEYS,
@@ -21201,6 +21908,8 @@ export {
21201
21908
  GATE_COMPONENTS,
21202
21909
  HCM_LANG_ENV,
21203
21910
  HcmClient,
21911
+ IMPERSONATION_ACTIVE_PATH,
21912
+ IMPERSONATION_START_PATH,
21204
21913
  IMPORT_PLAN_FILE,
21205
21914
  INIT_EXIT_CODES,
21206
21915
  JIRA_BASE,
@@ -21335,6 +22044,8 @@ export {
21335
22044
  applyReportToJson,
21336
22045
  archiveDir,
21337
22046
  askedTheDatabase,
22047
+ assertDangerWrite,
22048
+ assertExpectedTenant,
21338
22049
  assertNotReservedEnvName,
21339
22050
  assertSafeReferencePath,
21340
22051
  assertSafeSkillFilePath,
@@ -21361,6 +22072,7 @@ export {
21361
22072
  classifyStatus,
21362
22073
  clearMetaCache,
21363
22074
  clearModelCache,
22075
+ cliAuthorizationExpired,
21364
22076
  commandsFor,
21365
22077
  compareFingerprint,
21366
22078
  computeFingerprint,
@@ -21388,6 +22100,7 @@ export {
21388
22100
  detectDirectInteractionPending,
21389
22101
  detectPasswordChangeChallenge,
21390
22102
  discardedColumnLines,
22103
+ discoverProjectEnv,
21391
22104
  displayWidth,
21392
22105
  downloadDocument,
21393
22106
  enforceDriftGate,
@@ -21395,6 +22108,7 @@ export {
21395
22108
  envDir,
21396
22109
  envFile,
21397
22110
  envsDir,
22111
+ exchangeBrowserAuthorization,
21398
22112
  existingJournalStop,
21399
22113
  exitCodeFor,
21400
22114
  explainJacksonError,
@@ -21411,6 +22125,7 @@ export {
21411
22125
  fieldByName,
21412
22126
  filterByStage,
21413
22127
  find,
22128
+ findEnvByEndpoint,
21414
22129
  findLastAssistantSeq,
21415
22130
  firstLine,
21416
22131
  flattenSkills,
@@ -21426,6 +22141,7 @@ export {
21426
22141
  getTenantMeta,
21427
22142
  globalConfigFile,
21428
22143
  guessMimeType,
22144
+ hasPendingImpersonationSessions,
21429
22145
  hcmConfigDir,
21430
22146
  hitRank,
21431
22147
  httpProbe,
@@ -21482,11 +22198,13 @@ export {
21482
22198
  modelKeys,
21483
22199
  needsRefresh,
21484
22200
  newRoundId,
22201
+ normalizeOrigin,
21485
22202
  normalizeReferences,
21486
22203
  notAsked,
21487
22204
  oneShot,
21488
22205
  packDataPackage,
21489
22206
  parseConfirmToolName,
22207
+ parseEnvYaml,
21490
22208
  parseFixture,
21491
22209
  parseInteractionRequest,
21492
22210
  parseInteractionResolved,
@@ -21501,6 +22219,8 @@ export {
21501
22219
  planRc,
21502
22220
  planSummaryLine,
21503
22221
  planVsBaselinePremise,
22222
+ pollDeviceAuthorization,
22223
+ printResolvedEnvironment,
21504
22224
  probeAll,
21505
22225
  probeExtensionSource,
21506
22226
  profileDir,
@@ -21511,17 +22231,21 @@ export {
21511
22231
  readImportPlan,
21512
22232
  readMiniContext,
21513
22233
  readPullManifest,
22234
+ readSessionPrincipal,
21514
22235
  rebind,
21515
22236
  rebindPayload,
21516
22237
  refreshToken,
22238
+ releasePendingImpersonationSessions,
21517
22239
  remove,
21518
22240
  renameIdentity,
22241
+ renderEnvYaml,
21519
22242
  renderFind,
21520
22243
  renderRound,
21521
22244
  renderTriage,
21522
22245
  renderValues,
21523
22246
  replHistoryFile,
21524
22247
  repoIssueUrl,
22248
+ requestCliAuthorization,
21525
22249
  resetSettingItem,
21526
22250
  resolveActiveEnv,
21527
22251
  resolveActiveIdentity,
@@ -21530,6 +22254,8 @@ export {
21530
22254
  resolveBaselineDir,
21531
22255
  resolveChironBase,
21532
22256
  resolveCredentialStoreMode,
22257
+ resolveEnvContext,
22258
+ resolveProjectEnvironment,
21533
22259
  resolveRefs,
21534
22260
  resolveSkillInstallOrder,
21535
22261
  riskFromArtifacts,
@@ -21542,6 +22268,7 @@ export {
21542
22268
  runMiniSmokeChecks,
21543
22269
  runRecon,
21544
22270
  runTriageRound,
22271
+ safeCliAuthorizationError,
21545
22272
  safeSegment,
21546
22273
  saveConversationState,
21547
22274
  saveEnv,
@@ -21557,6 +22284,7 @@ export {
21557
22284
  sendMessageAndStream,
21558
22285
  shelfPartition,
21559
22286
  snakeToCamel,
22287
+ startImpersonation,
21560
22288
  tenantSegment,
21561
22289
  toAcceptLanguage,
21562
22290
  toJson,
@@ -21568,6 +22296,7 @@ export {
21568
22296
  unbindPayload,
21569
22297
  update,
21570
22298
  uploadDocument,
22299
+ validateCliAuthorizationUrl,
21571
22300
  validateMetaContent,
21572
22301
  validateMiniProject,
21573
22302
  validateScriptManifest,