beautx-cli 1.0.6-beta.2 → 1.0.6-beta.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/README.md +16 -17
  2. package/dist/{analyze-0SATHpUC.mjs → analyze-Cq-Hmoqp.mjs} +6 -6
  3. package/dist/{api-D3JyDoiw.mjs → api-jIGM86TK.mjs} +2 -2
  4. package/dist/{audio-BfNibfXF.mjs → audio-p2QCYFdq.mjs} +3 -3
  5. package/dist/{beauty-plan-DQl_OJNK.mjs → beauty-plan-CgSmAhn8.mjs} +4 -4
  6. package/dist/cli.mjs +7636 -19
  7. package/dist/config-DAVi_CuD.mjs +15 -0
  8. package/dist/{consultant-DbYBzHqQ.mjs → consultant-CPecFRiS.mjs} +1 -1
  9. package/dist/{content-BTHG2DCs.mjs → content-Bq_jEIl6.mjs} +3 -3
  10. package/dist/{current-BDH1xER9.mjs → current-D4fh-53q.mjs} +3 -3
  11. package/dist/{customer-D04eXm64.mjs → customer-DWG47eAT.mjs} +1 -1
  12. package/dist/{deal-analysis-Dpg9VGjK.mjs → deal-analysis-Cn2wCaoU.mjs} +4 -4
  13. package/dist/{doc-CWgdZ_Eh.mjs → doc-DwxREqki.mjs} +3 -3
  14. package/dist/doctor-RwDPp4y3.mjs +37 -0
  15. package/dist/{fields-D-iEk93w.mjs → fields-BGogOrgD.mjs} +4 -4
  16. package/dist/{focus-BMcnVGqT.mjs → focus-BE8BT835.mjs} +1 -1
  17. package/dist/{get-BLdqZ3XJ.mjs → get-BKCE22jj.mjs} +3 -3
  18. package/dist/{kb-BPy6E_uX.mjs → kb-BsiBl_ul.mjs} +2 -2
  19. package/dist/list-BUYSLNqZ.mjs +83 -0
  20. package/dist/{list-JL2fmylz.mjs → list-BYLk3sNv.mjs} +5 -5
  21. package/dist/{list-CB7YZTB4.mjs → list-BcYy7Ejx.mjs} +5 -5
  22. package/dist/{list-C73pWNBd.mjs → list-BmVWcUI7.mjs} +2 -2
  23. package/dist/{list-Ck_kx-iC.mjs → list-BzmkW4Iq.mjs} +5 -5
  24. package/dist/{list-DyePBi8K.mjs → list-Cnz5CuQB.mjs} +5 -5
  25. package/dist/{list-DqXRvhfS.mjs → list-Cs1kF7EB.mjs} +5 -5
  26. package/dist/{list-BMbWa85R.mjs → list-DJscF_8M.mjs} +5 -5
  27. package/dist/{list-DIvD8BvI.mjs → list-DVy4Czfy.mjs} +5 -5
  28. package/dist/{mcp-args-CYOCdClW.mjs → mcp-args-DK3IGaO1.mjs} +1 -1
  29. package/dist/{mcp-client-OuKd8iir.mjs → mcp-client-BTZH22b5.mjs} +37 -76
  30. package/dist/{mcp-result-B5HHO7ap.mjs → mcp-result-De_0PPlD.mjs} +2 -2
  31. package/dist/{portrait-tags-DRQi5JcR.mjs → portrait-tags-I57TgDAx.mjs} +4 -4
  32. package/dist/{project-CEmZCvSp.mjs → project-K-HkeM57.mjs} +3 -3
  33. package/dist/project-access-Bf87OLJP.mjs +2 -0
  34. package/dist/{project-access-O-VSqqVC.mjs → project-access-pTN7ry15.mjs} +20 -30
  35. package/dist/project-store-DDVZ7T4t.mjs +2 -0
  36. package/dist/project-store-Dl35JzZr.mjs +424 -0
  37. package/dist/{qa-B7WbwUts.mjs → qa-gAtF6cSk.mjs} +6 -6
  38. package/dist/{resistance-FtBtoEDl.mjs → resistance-DGU99Bwi.mjs} +1 -1
  39. package/dist/{search-BuMtyCiU.mjs → search-C16CzRep.mjs} +6 -6
  40. package/dist/{summary-Cg79V9oz.mjs → summary-DgpSsQh9.mjs} +5 -5
  41. package/dist/{text-CGOU6uh9.mjs → text-BIIl7PmC.mjs} +5 -5
  42. package/dist/{use-Bzhvb9I3.mjs → use-D_HBqdev.mjs} +8 -6
  43. package/dist/{visit-vaoFdiLr.mjs → visit-DnUPj-8i.mjs} +2 -2
  44. package/dist/{visit-evaluate-BQIyxZeM.mjs → visit-evaluate-DM7oCk6R.mjs} +4 -4
  45. package/dist/{visit-query-args-CDDQ9JJ8.mjs → visit-query-args-BD3Dw-9F.mjs} +3 -3
  46. package/package.json +1 -1
  47. package/dist/config-C8aqUXV7.mjs +0 -14
  48. package/dist/env-callback-CIXEvt0i.mjs +0 -349
  49. package/dist/env-vars-CXEHR_mk.mjs +0 -231
  50. package/dist/format-9T59sVxH.mjs +0 -7253
  51. package/dist/list-FCCClcl-.mjs +0 -64
  52. package/dist/project-store-DHqT0-nk.mjs +0 -55
  53. /package/dist/{util-BtgWHKWv.mjs → util-Bko-nm_R.mjs} +0 -0
@@ -1,5 +1,4 @@
1
- import { n as __exportAll } from "./rolldown-runtime-YLnNgb9a.mjs";
2
- import { d as resolveEndpoints, l as readEnv, m as ConfigInvalidError, s as readActiveProject, t as ENV_KEYS, u as requireUserId } from "./env-vars-CXEHR_mk.mjs";
1
+ import { S as ConfigInvalidError, _ as readEnv, o as loadActiveProject, s as peekCachedActiveProject, u as ENV_KEYS, v as requireUserId, y as resolveEndpoints } from "./project-store-Dl35JzZr.mjs";
3
2
  var InsufficientCreditError = class extends Error {
4
3
  code = "INSUFFICIENT_CREDIT";
5
4
  hint = "(该项目下)用户积分余额不足,无法继续查询;请告知用户联系管理员充值";
@@ -41,7 +40,7 @@ async function assertCreditRemaining(projectId) {
41
40
  }
42
41
  async function fetchCreditRemaining(userId, projectId) {
43
42
  const { callbackBaseUrl } = resolveEndpoints();
44
- const url = new URL(`/api/wang-claw/out/credit/users/${encodeURIComponent(userId)}/remaining`, callbackBaseUrl);
43
+ const url = new URL(`/api/qca-wangclaw/out/v2/credit/users/${encodeURIComponent(userId)}/remaining`, callbackBaseUrl);
45
44
  url.searchParams.set("projectId", projectId);
46
45
  let resp;
47
46
  try {
@@ -82,13 +81,6 @@ function extractEnvelopeMessage(body) {
82
81
  * Allowed estate (project) guard for CLI — validates project_id against
83
82
  * {@code project-list} before MCP calls (in-process TTL cache).
84
83
  */
85
- var project_access_exports = /* @__PURE__ */ __exportAll({
86
- PROJECT_ACCESS_TTL_MS: () => PROJECT_ACCESS_TTL_MS,
87
- ProjectNotAllowedError: () => ProjectNotAllowedError,
88
- assertProjectAllowed: () => assertProjectAllowed,
89
- invalidateProjectAccessCache: () => invalidateProjectAccessCache,
90
- resolveProjectForUse: () => resolveProjectForUse
91
- });
92
84
  const PROJECT_ACCESS_TTL_MS = 300 * 1e3;
93
85
  const PROJECT_LIST_PAGE_SIZE = 100;
94
86
  let cache = null;
@@ -108,7 +100,7 @@ function invalidateProjectAccessCache() {
108
100
  function resolveCacheTenantId() {
109
101
  const fromEnv = readEnv(ENV_KEYS.TENANT_ID);
110
102
  if (fromEnv) return fromEnv;
111
- return readActiveProject()?.tenantId?.trim() ?? "";
103
+ return peekCachedActiveProject()?.tenantId?.trim() ?? "";
112
104
  }
113
105
  function cacheIsValid(state, tenantId) {
114
106
  return state.tenantId === tenantId && Date.now() - state.fetchedAt < 3e5;
@@ -139,9 +131,9 @@ function finalizeResolvedProject(partial) {
139
131
  projectName: partial.projectName?.trim() ?? ""
140
132
  };
141
133
  }
142
- function isHostActiveEstate(projectId) {
143
- const activeEstateId = readEnv(ENV_KEYS.ESTATE_ID)?.trim();
144
- return Boolean(activeEstateId && activeEstateId === projectId);
134
+ function isCachedActiveEstate(projectId) {
135
+ const active = peekCachedActiveProject();
136
+ return Boolean(active?.projectId && active.projectId === projectId);
145
137
  }
146
138
  /**
147
139
  * Ensure {@code projectId} is in the gateway project-list roster.
@@ -150,7 +142,7 @@ function isHostActiveEstate(projectId) {
150
142
  async function assertProjectAllowed(projectId) {
151
143
  const id = projectId?.trim();
152
144
  if (!id) return;
153
- if (!isHostActiveEstate(id)) {
145
+ if (!isCachedActiveEstate(id)) {
154
146
  const tenantId = resolveCacheTenantId();
155
147
  if (cache && cacheIsValid(cache, tenantId)) {
156
148
  if (!cache.allowedEstateIds.has(id)) {
@@ -163,22 +155,20 @@ async function assertProjectAllowed(projectId) {
163
155
  }
164
156
  /**
165
157
  * Resolve tenant/project metadata for {@code project use} from project-list.
166
- * Names are display-only (Host env); IDs come from the roster row.
158
+ * Names are display-only; IDs come from the roster row.
167
159
  */
168
160
  async function resolveProjectForUse(projectId) {
169
161
  const id = projectId?.trim();
170
162
  if (!id) throw new ConfigInvalidError("缺少 project_id", "运行 `beautx-cli project list` 选择项目");
171
- if (isHostActiveEstate(id)) {
172
- const active = readActiveProject();
173
- if (active?.projectId === id) {
174
- await assertCreditRemaining(id);
175
- return finalizeResolvedProject({
176
- tenantId: active.tenantId,
177
- tenantName: active.tenantName,
178
- projectId: id,
179
- projectName: active.projectName
180
- });
181
- }
163
+ const active = await loadActiveProject();
164
+ if (active?.projectId === id) {
165
+ await assertCreditRemaining(id);
166
+ return finalizeResolvedProject({
167
+ tenantId: active.tenantId,
168
+ tenantName: active.tenantName,
169
+ projectId: id,
170
+ projectName: active.projectName
171
+ });
182
172
  }
183
173
  const row = await lookupProjectRow(id);
184
174
  await assertCreditRemaining(id);
@@ -237,14 +227,14 @@ function normalizeProjectListPage(page) {
237
227
  };
238
228
  }
239
229
  async function fetchProjectListPage(page, size) {
240
- const { mcpCall, unwrapMcpToolEnvelope } = await import("./mcp-client-OuKd8iir.mjs").then((n) => n.r);
230
+ const { mcpCall, unwrapMcpToolEnvelope } = await import("./mcp-client-BTZH22b5.mjs").then((n) => n.r);
241
231
  const result = await mcpCall("project-list", { arguments: {
242
232
  page,
243
233
  size
244
234
  } });
245
235
  if (!result.ok) {
246
236
  const detail = extractMcpFailureDetail(result.data);
247
- throw new ConfigInvalidError(detail ? `无法拉取项目列表以校验 project_id: ${detail}` : "无法拉取项目列表以校验 project_id", "检查 MCP 网关与 token 是否正常;大租户可先用 Host 预置当前项目");
237
+ throw new ConfigInvalidError(detail ? `无法拉取项目列表以校验 project_id: ${detail}` : "无法拉取项目列表以校验 project_id", "检查 MCP 网关与 token 是否正常;大租户可先由平台预置当前项目");
248
238
  }
249
239
  const envelope = unwrapMcpToolEnvelope(result.data);
250
240
  const code = envelope.code;
@@ -271,4 +261,4 @@ function extractMcpFailureDetail(data) {
271
261
  }
272
262
  }
273
263
  //#endregion
274
- export { project_access_exports as n, resolveProjectForUse as r, invalidateProjectAccessCache as t };
264
+ export { resolveProjectForUse as a, invalidateProjectAccessCache as i, ProjectNotAllowedError as n, assertProjectAllowed as r, PROJECT_ACCESS_TTL_MS as t };
@@ -0,0 +1,2 @@
1
+ import { o as loadActiveProject } from "./project-store-Dl35JzZr.mjs";
2
+ export { loadActiveProject };
@@ -0,0 +1,424 @@
1
+ //#region src/core/config-errors.ts
2
+ /**
3
+ * Structured config errors for agent-facing hints.
4
+ */
5
+ var MissingGatewayError = class extends Error {
6
+ code = "MISSING_GATEWAY";
7
+ hint = "由 Host 设置 ENV=test(或 prod),CLI 将使用内置网关地址";
8
+ constructor() {
9
+ super("缺少 MCP 网关地址");
10
+ this.name = "MissingGatewayError";
11
+ }
12
+ };
13
+ var MissingAccessTokenError = class extends Error {
14
+ code = "MISSING_ACCESS_TOKEN";
15
+ hint = "向 /out/v2/mcp-token 借 AT 失败:确认沙箱已注入 SANDBOX_*_SECRET,且 PC/App 已完成 MCP 凭证初始化";
16
+ constructor() {
17
+ super("缺少 MCP access token");
18
+ this.name = "MissingAccessTokenError";
19
+ }
20
+ };
21
+ var AccessTokenExpiredError = class extends Error {
22
+ code = "ACCESS_TOKEN_EXPIRED";
23
+ hint = "重新调用 CLI(会向 Token Broker 借新 AT),或先在 PC/App 登录刷新凭证仓";
24
+ constructor() {
25
+ super("MCP access token 已过期");
26
+ this.name = "AccessTokenExpiredError";
27
+ }
28
+ };
29
+ var CurrentProjectFailedError = class extends Error {
30
+ code = "CURRENT_PROJECT_FAILED";
31
+ hint = "读写当前项目失败,请检查 TENANT_ID、USER_ID 与 /out/v2/current-project 服务是否可用";
32
+ status;
33
+ upstreamCode;
34
+ details;
35
+ constructor(message, options) {
36
+ super(message);
37
+ this.name = "CurrentProjectFailedError";
38
+ this.status = options?.status;
39
+ this.upstreamCode = options?.upstreamCode;
40
+ this.details = options?.details;
41
+ if (options?.hint) this.hint = options.hint;
42
+ }
43
+ };
44
+ var ConfigInvalidError = class extends Error {
45
+ code = "CONFIG_INVALID";
46
+ hint;
47
+ constructor(message, hint) {
48
+ super(message);
49
+ this.name = "ConfigInvalidError";
50
+ this.hint = hint;
51
+ }
52
+ };
53
+ //#endregion
54
+ //#region src/core/endpoints.ts
55
+ /** Fallback when Host has not injected ENV (local dev via env.sh only). */
56
+ const DEFAULT_ENV = "test";
57
+ /** ENV value → MCP gateway / auth / Host callback base URLs. */
58
+ const PROFILES = {
59
+ test: {
60
+ gatewayUrl: "https://mcp.test.wangxiaobao.com",
61
+ authUrl: "https://mcp-auth.test.wangxiaobao.com",
62
+ callbackBaseUrl: "https://wangke.test.wangxiaobao.com"
63
+ },
64
+ prod: {
65
+ gatewayUrl: `https://mcp.wangxiaobao.com`,
66
+ authUrl: `https://mcp-auth.wangxiaobao.com`,
67
+ callbackBaseUrl: `https://wangke.wangxiaobao.com`
68
+ }
69
+ };
70
+ function isProfileUrlConfigured(url) {
71
+ return url.startsWith("https://");
72
+ }
73
+ function parseEnvName(raw) {
74
+ if (raw === "test" || raw === "prod") return raw;
75
+ return null;
76
+ }
77
+ //#endregion
78
+ //#region src/core/config-store.ts
79
+ /**
80
+ * Shared config helpers (env-only mode; no file persistence).
81
+ */
82
+ /** Decode JWT exp (seconds) → ms; returns null if not a JWT or no exp. */
83
+ function jwtExpMs(token) {
84
+ const parts = token.split(".");
85
+ if (parts.length < 2) return null;
86
+ try {
87
+ const payload = JSON.parse(Buffer.from(parts[1].replace(/-/g, "+").replace(/_/g, "/"), "base64url").toString("utf8"));
88
+ if (typeof payload.exp === "number") return payload.exp * 1e3;
89
+ } catch {}
90
+ return null;
91
+ }
92
+ //#endregion
93
+ //#region src/core/env-vars.ts
94
+ /**
95
+ * Environment-variable backed CLI state (sandbox single source of truth).
96
+ */
97
+ const ENV_KEYS = {
98
+ ESTATE_ID: "ESTATE_ID",
99
+ ESTATE_NAME: "ESTATE_NAME",
100
+ TENANT_ID: "TENANT_ID",
101
+ TENANT_NAME: "TENANT_NAME",
102
+ USER_ID: "USER_ID",
103
+ USER_NAME: "USER_NAME",
104
+ MCP_TOKEN: "MCP_TOKEN",
105
+ REFRESH_TOKEN: "REFRESH_TOKEN",
106
+ EXPIRES_TIMES: "EXPIRES_TIMES",
107
+ SESSION_ID: "SESSION_ID",
108
+ XB_APP_ID: "XB_APP_ID",
109
+ ENV: "ENV",
110
+ /** 沙箱只读:创建模板时注入,用于 Token Broker 等敏感请求 */
111
+ SANDBOX_TENANT_SECRET: "SANDBOX_TENANT_SECRET",
112
+ /** 沙箱只读:创建用户时注入 */
113
+ SANDBOX_USER_SECRET: "SANDBOX_USER_SECRET"
114
+ };
115
+ /** Refresh when remaining lifetime is below this threshold (ms). */
116
+ const REFRESH_BUFFER_MS = 12e4;
117
+ function readEnv(key) {
118
+ return process.env[key]?.trim() ?? "";
119
+ }
120
+ function syncProcessEnv(pairs) {
121
+ for (const [key, value] of Object.entries(pairs)) process.env[key] = value;
122
+ }
123
+ /**
124
+ * Resolve deployment env from Host-injected `ENV`.
125
+ * Missing ENV falls back to DEFAULT_ENV (local shell only); invalid values error out.
126
+ */
127
+ function resolveDeploymentEnv() {
128
+ const raw = readEnv(ENV_KEYS.ENV);
129
+ if (!raw) return DEFAULT_ENV;
130
+ const parsed = parseEnvName(raw);
131
+ if (!parsed) throw new ConfigInvalidError(`无效 ENV: ${raw}`, "由 Host 注入 ENV=test 或 ENV=prod");
132
+ return parsed;
133
+ }
134
+ /** Whether Host injected ENV (vs CLI local default). */
135
+ function isEnvInjectedByHost() {
136
+ return Boolean(readEnv(ENV_KEYS.ENV));
137
+ }
138
+ function resolveEndpoints() {
139
+ const env = resolveDeploymentEnv();
140
+ const profile = PROFILES[env];
141
+ return {
142
+ env,
143
+ gatewayUrl: profile.gatewayUrl,
144
+ authUrl: profile.authUrl,
145
+ callbackBaseUrl: profile.callbackBaseUrl
146
+ };
147
+ }
148
+ function assertEndpointsValid(endpoints) {
149
+ if (!isProfileUrlConfigured(endpoints.gatewayUrl)) throw new ConfigInvalidError(`环境 ${endpoints.env} 的网关 URL 尚未配置`, "由 Host 设置 ENV=test,或待 prod 域名就绪后设置 ENV=prod");
150
+ if (!isProfileUrlConfigured(endpoints.callbackBaseUrl)) throw new ConfigInvalidError(`环境 ${endpoints.env} 的回调 URL 尚未配置`, "由 Host 设置 ENV=test,或待 prod 域名就绪后设置 ENV=prod");
151
+ }
152
+ function requireUserId() {
153
+ const userId = readEnv(ENV_KEYS.USER_ID);
154
+ if (!userId) throw new ConfigInvalidError("缺少 USER_ID 环境变量", "由 QCA 在沙箱启动时注入 USER_ID");
155
+ return userId;
156
+ }
157
+ function readCredentials() {
158
+ const accessToken = readEnv(ENV_KEYS.MCP_TOKEN) || null;
159
+ const refreshToken = readEnv(ENV_KEYS.REFRESH_TOKEN) || null;
160
+ const expiresRaw = readEnv(ENV_KEYS.EXPIRES_TIMES);
161
+ let expiresAt = null;
162
+ if (expiresRaw) {
163
+ const parsed = Number(expiresRaw);
164
+ if (!Number.isNaN(parsed) && parsed > 0) expiresAt = parsed;
165
+ }
166
+ if (expiresAt == null && accessToken) expiresAt = jwtExpMs(accessToken);
167
+ return {
168
+ accessToken,
169
+ refreshToken,
170
+ expiresAt
171
+ };
172
+ }
173
+ function credentialStatus(creds) {
174
+ if (!creds.accessToken) return {
175
+ configured: false,
176
+ status: "missing",
177
+ expiresAt: null,
178
+ expiresInSec: null
179
+ };
180
+ return buildExpiryView(creds, computeExpiryStatus(creds.expiresAt));
181
+ }
182
+ function buildExpiryView(creds, status) {
183
+ const expiresAt = creds.expiresAt;
184
+ const expiresInSec = expiresAt != null ? Math.max(0, Math.floor((expiresAt - Date.now()) / 1e3)) : null;
185
+ return {
186
+ configured: true,
187
+ status,
188
+ expiresAt: expiresAt ?? null,
189
+ expiresInSec
190
+ };
191
+ }
192
+ function computeExpiryStatus(expiresAt) {
193
+ if (expiresAt == null) return "valid";
194
+ const remaining = expiresAt - Date.now();
195
+ if (remaining <= 0) return "expired";
196
+ if (remaining < 12e4) return "expiring";
197
+ return "valid";
198
+ }
199
+ function needsRefresh(expiresAt, force = false) {
200
+ if (force) return true;
201
+ if (expiresAt == null) return false;
202
+ return expiresAt - Date.now() < REFRESH_BUFFER_MS;
203
+ }
204
+ function isTokenExpired(expiresAt) {
205
+ return expiresAt != null && expiresAt <= Date.now();
206
+ }
207
+ function requireTenantId() {
208
+ const tenantId = readEnv(ENV_KEYS.TENANT_ID);
209
+ if (!tenantId) throw new CurrentProjectFailedError("缺少 TENANT_ID 环境变量", { hint: "由 QCA 在沙箱启动时注入 TENANT_ID" });
210
+ return tenantId;
211
+ }
212
+ async function getCurrentProject(tenantId, wangId) {
213
+ return fetchCurrentProject((tenantId ?? requireTenantId()).trim(), (wangId ?? requireUserId()).trim());
214
+ }
215
+ async function setCurrentProject(input) {
216
+ const tid = (input.tenantId ?? requireTenantId()).trim();
217
+ const wid = (input.wangId ?? requireUserId()).trim();
218
+ const projectId = input.projectId?.trim();
219
+ if (!projectId) throw new CurrentProjectFailedError("projectId 不能为空");
220
+ return putCurrentProject(tid, wid, projectId, input.source?.trim() || "cli_project_use");
221
+ }
222
+ async function fetchCurrentProject(tenantId, wangId) {
223
+ const { callbackBaseUrl } = resolveEndpoints();
224
+ const url = new URL("/api/qca-wangclaw/out/v2/current-project", callbackBaseUrl);
225
+ url.searchParams.set("tenantId", tenantId);
226
+ url.searchParams.set("wangId", wangId);
227
+ let resp;
228
+ try {
229
+ resp = await fetch(url, {
230
+ method: "GET",
231
+ headers: { Accept: "application/json" },
232
+ signal: AbortSignal.timeout(1e4)
233
+ });
234
+ } catch (err) {
235
+ throw new CurrentProjectFailedError(`读取当前项目请求失败: ${err instanceof Error ? err.message : String(err)}`);
236
+ }
237
+ if (resp.status === 404) return null;
238
+ const body = await readJsonBody(resp);
239
+ if (!resp.ok) throwCurrentProjectHttpError("读取当前项目失败", resp.status, body);
240
+ const data = unwrapData(body);
241
+ if (!data) return null;
242
+ return parseRecord(data, tenantId, wangId);
243
+ }
244
+ async function putCurrentProject(tenantId, wangId, projectId, source) {
245
+ const { callbackBaseUrl } = resolveEndpoints();
246
+ const url = new URL("/api/qca-wangclaw/out/v2/current-project", callbackBaseUrl);
247
+ let resp;
248
+ try {
249
+ resp = await fetch(url, {
250
+ method: "PUT",
251
+ headers: {
252
+ Accept: "application/json",
253
+ "Content-Type": "application/json"
254
+ },
255
+ body: JSON.stringify({
256
+ tenantId,
257
+ wangId,
258
+ projectId,
259
+ source
260
+ }),
261
+ signal: AbortSignal.timeout(1e4)
262
+ });
263
+ } catch (err) {
264
+ throw new CurrentProjectFailedError(`写入当前项目请求失败: ${err instanceof Error ? err.message : String(err)}`);
265
+ }
266
+ const body = await readJsonBody(resp);
267
+ if (!resp.ok) throwCurrentProjectHttpError("写入当前项目失败", resp.status, body);
268
+ const data = unwrapData(body);
269
+ if (!data) throw new CurrentProjectFailedError("写入当前项目响应缺少 data");
270
+ return parseRecord(data, tenantId, wangId);
271
+ }
272
+ function unwrapData(body) {
273
+ if (!body || typeof body !== "object") return null;
274
+ const envelope = body;
275
+ if (String(envelope.code) === "404") return null;
276
+ if (envelope.code != null && String(envelope.code) !== "0") throw new CurrentProjectFailedError(envelope.msg ?? `当前项目业务错误: ${envelope.code}`, {
277
+ upstreamCode: String(envelope.code),
278
+ details: body
279
+ });
280
+ if (envelope.data == null) return null;
281
+ if (typeof envelope.data !== "object") return null;
282
+ return envelope.data;
283
+ }
284
+ function parseRecord(data, fallbackTenantId, fallbackWangId) {
285
+ const projectId = pickString(data, "projectId", "currentProjectId", "current_project_id");
286
+ if (!projectId) throw new CurrentProjectFailedError("当前项目响应缺少 projectId");
287
+ return {
288
+ tenantId: pickString(data, "tenantId", "tenant_id") || fallbackTenantId,
289
+ wangId: pickString(data, "wangId", "wang_id") || fallbackWangId,
290
+ projectId,
291
+ source: pickString(data, "source") || "",
292
+ createdAt: pickString(data, "createdAt", "created_at") || void 0,
293
+ updatedAt: pickString(data, "updatedAt", "updated_at") || void 0,
294
+ version: typeof data.version === "number" ? data.version : data.version != null ? Number(data.version) : void 0
295
+ };
296
+ }
297
+ function pickString(obj, ...keys) {
298
+ for (const key of keys) {
299
+ const value = obj[key];
300
+ if (value != null && String(value).trim()) return String(value).trim();
301
+ }
302
+ return "";
303
+ }
304
+ async function readJsonBody(resp) {
305
+ try {
306
+ return await resp.json();
307
+ } catch {
308
+ throw new CurrentProjectFailedError(`当前项目接口返回非 JSON(HTTP ${resp.status})`, { status: resp.status });
309
+ }
310
+ }
311
+ function throwCurrentProjectHttpError(prefix, status, body) {
312
+ const msg = extractEnvelopeMessage(body) ?? "";
313
+ throw new CurrentProjectFailedError(msg ? `${prefix}(HTTP ${status}): ${msg}` : `${prefix}(HTTP ${status})`, {
314
+ status,
315
+ details: body
316
+ });
317
+ }
318
+ function extractEnvelopeMessage(body) {
319
+ if (!body || typeof body !== "object") return void 0;
320
+ const msg = body.msg;
321
+ return typeof msg === "string" && msg.trim() ? msg.trim() : void 0;
322
+ }
323
+ //#endregion
324
+ //#region src/core/project-store.ts
325
+ /**
326
+ * Active project — QCA `/out/v2/current-project` is the only source of truth.
327
+ * Not written into process.env; agents inspect via `beautx-cli project current`.
328
+ */
329
+ const CACHE_TTL_MS = 15e3;
330
+ let cache = null;
331
+ function invalidateActiveProjectCache() {
332
+ cache = null;
333
+ }
334
+ /** Warm-cache peek for guards (null if cold / expired). */
335
+ function peekCachedActiveProject() {
336
+ if (!cache) return null;
337
+ if (Date.now() - cache.fetchedAt >= CACHE_TTL_MS) return null;
338
+ return cache.project;
339
+ }
340
+ /**
341
+ * Load active project from QCA `/out/v2/current-project`.
342
+ * Returns null when no row exists (do not fall back to ESTATE_ID env).
343
+ */
344
+ async function loadActiveProject() {
345
+ if (cache && Date.now() - cache.fetchedAt < CACHE_TTL_MS) return cache.project;
346
+ const remote = await getCurrentProject();
347
+ if (remote?.projectId) {
348
+ const project = toActiveProject(remote);
349
+ cache = {
350
+ project,
351
+ fetchedAt: Date.now()
352
+ };
353
+ return project;
354
+ }
355
+ cache = {
356
+ project: null,
357
+ fetchedAt: Date.now()
358
+ };
359
+ return null;
360
+ }
361
+ async function switchActiveProjectViaCallback(p) {
362
+ const tenantId = p.tenantId?.trim() || readEnv(ENV_KEYS.TENANT_ID);
363
+ await setCurrentProject({
364
+ tenantId,
365
+ projectId: p.projectId,
366
+ source: "cli_project_use"
367
+ });
368
+ const project = {
369
+ tenantId,
370
+ tenantName: p.tenantName ?? "",
371
+ projectId: p.projectId,
372
+ projectName: p.projectName ?? "",
373
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
374
+ source: "qca"
375
+ };
376
+ cache = {
377
+ project,
378
+ fetchedAt: Date.now()
379
+ };
380
+ return project;
381
+ }
382
+ var NoActiveProjectError = class extends Error {
383
+ code = "NO_ACTIVE_PROJECT";
384
+ hint = "先用 `beautx-cli project list [--keyword <kw>]` 查看可选项目,再用 `beautx-cli project use --project-id <id>` 激活;或由平台预置当前项目。查看当前项目:`beautx-cli project current`。";
385
+ constructor() {
386
+ super("当前未设置激活项目");
387
+ this.name = "NoActiveProjectError";
388
+ }
389
+ };
390
+ async function requireActiveProject() {
391
+ const p = await loadActiveProject();
392
+ if (!p?.projectId) throw new NoActiveProjectError();
393
+ return p;
394
+ }
395
+ /**
396
+ * Project switching is blocked only in the aike app (XB_APP_ID=aike).
397
+ */
398
+ var ProjectSwitchNotAllowedError = class extends Error {
399
+ code = "PROJECT_SWITCH_NOT_ALLOWED";
400
+ hint = "当前应用(XB_APP_ID=aike)不允许通过 CLI 切换项目,请使用 UI 切换。";
401
+ constructor() {
402
+ super("无法切换项目:不允许在当前应用下切换");
403
+ this.name = "ProjectSwitchNotAllowedError";
404
+ }
405
+ };
406
+ function assertProjectSwitchAllowed() {
407
+ if (!isProjectSwitchAllowed()) throw new ProjectSwitchNotAllowedError();
408
+ }
409
+ /** Whether CLI may run `project use` (false only when XB_APP_ID=aike). */
410
+ function isProjectSwitchAllowed() {
411
+ return readEnv(ENV_KEYS.XB_APP_ID).toLowerCase() !== "aike";
412
+ }
413
+ function toActiveProject(remote) {
414
+ return {
415
+ tenantId: remote.tenantId || readEnv(ENV_KEYS.TENANT_ID),
416
+ tenantName: "",
417
+ projectId: remote.projectId,
418
+ projectName: "",
419
+ updatedAt: remote.updatedAt || (/* @__PURE__ */ new Date()).toISOString(),
420
+ source: "qca"
421
+ };
422
+ }
423
+ //#endregion
424
+ export { MissingAccessTokenError as C, ConfigInvalidError as S, readEnv as _, isProjectSwitchAllowed as a, syncProcessEnv as b, requireActiveProject as c, assertEndpointsValid as d, credentialStatus as f, readCredentials as g, needsRefresh as h, invalidateActiveProjectCache as i, switchActiveProjectViaCallback as l, isTokenExpired as m, ProjectSwitchNotAllowedError as n, loadActiveProject as o, isEnvInjectedByHost as p, assertProjectSwitchAllowed as r, peekCachedActiveProject as s, NoActiveProjectError as t, ENV_KEYS as u, requireUserId as v, MissingGatewayError as w, AccessTokenExpiredError as x, resolveEndpoints as y };
@@ -1,9 +1,9 @@
1
- import { n as mcpCall } from "./mcp-client-OuKd8iir.mjs";
2
- import { n as writeError, t as formatCliArg } from "./format-9T59sVxH.mjs";
3
- import { n as resolveProjectId, t as projectIdCliArg } from "./mcp-args-CYOCdClW.mjs";
4
- import { n as writeMcpDataResult } from "./mcp-result-B5HHO7ap.mjs";
5
- import { i as requireActiveProject } from "./project-store-DHqT0-nk.mjs";
6
- import { t as csvToArray } from "./util-BtgWHKWv.mjs";
1
+ import { c as requireActiveProject } from "./project-store-Dl35JzZr.mjs";
2
+ import { n as writeError, t as formatCliArg } from "./cli.mjs";
3
+ import { n as mcpCall } from "./mcp-client-BTZH22b5.mjs";
4
+ import { n as resolveProjectId, t as projectIdCliArg } from "./mcp-args-DK3IGaO1.mjs";
5
+ import { n as writeMcpDataResult } from "./mcp-result-De_0PPlD.mjs";
6
+ import { t as csvToArray } from "./util-Bko-nm_R.mjs";
7
7
  import { defineCommand } from "citty";
8
8
  //#region src/commands/qa.ts
9
9
  /**
@@ -5,7 +5,7 @@ var resistance_default = defineCommand({
5
5
  name: "resistance",
6
6
  description: "客户抗性点标签分页查询"
7
7
  },
8
- subCommands: { list: () => import("./list-DIvD8BvI.mjs").then((m) => m.default) }
8
+ subCommands: { list: () => import("./list-DVy4Czfy.mjs").then((m) => m.default) }
9
9
  });
10
10
  //#endregion
11
11
  export { resistance_default as default };
@@ -1,9 +1,9 @@
1
- import { n as mcpCall } from "./mcp-client-OuKd8iir.mjs";
2
- import { n as writeError, t as formatCliArg } from "./format-9T59sVxH.mjs";
3
- import { i as tenantIdCliArg, n as resolveProjectId, r as resolveTenantId, t as projectIdCliArg } from "./mcp-args-CYOCdClW.mjs";
4
- import { n as writeMcpDataResult } from "./mcp-result-B5HHO7ap.mjs";
5
- import { i as requireActiveProject } from "./project-store-DHqT0-nk.mjs";
6
- import { t as csvToArray } from "./util-BtgWHKWv.mjs";
1
+ import { c as requireActiveProject } from "./project-store-Dl35JzZr.mjs";
2
+ import { n as writeError, t as formatCliArg } from "./cli.mjs";
3
+ import { n as mcpCall } from "./mcp-client-BTZH22b5.mjs";
4
+ import { i as tenantIdCliArg, n as resolveProjectId, r as resolveTenantId, t as projectIdCliArg } from "./mcp-args-DK3IGaO1.mjs";
5
+ import { n as writeMcpDataResult } from "./mcp-result-De_0PPlD.mjs";
6
+ import { t as csvToArray } from "./util-Bko-nm_R.mjs";
7
7
  import { defineCommand } from "citty";
8
8
  //#region src/commands/kb/search.ts
9
9
  /**
@@ -1,8 +1,8 @@
1
- import { n as writeError, t as formatCliArg } from "./format-9T59sVxH.mjs";
2
- import { n as resolveProjectId, t as projectIdCliArg } from "./mcp-args-CYOCdClW.mjs";
3
- import { t as mcpCallPage } from "./mcp-result-B5HHO7ap.mjs";
4
- import { i as requireActiveProject } from "./project-store-DHqT0-nk.mjs";
5
- import { i as toLocalDateTime } from "./util-BtgWHKWv.mjs";
1
+ import { c as requireActiveProject } from "./project-store-Dl35JzZr.mjs";
2
+ import { n as writeError, t as formatCliArg } from "./cli.mjs";
3
+ import { n as resolveProjectId, t as projectIdCliArg } from "./mcp-args-DK3IGaO1.mjs";
4
+ import { t as mcpCallPage } from "./mcp-result-De_0PPlD.mjs";
5
+ import { i as toLocalDateTime } from "./util-Bko-nm_R.mjs";
6
6
  import { defineCommand } from "citty";
7
7
  //#region src/commands/visit/summary.ts
8
8
  /**
@@ -1,8 +1,8 @@
1
- import { n as mcpCall } from "./mcp-client-OuKd8iir.mjs";
2
- import { n as writeError, t as formatCliArg } from "./format-9T59sVxH.mjs";
3
- import { n as resolveProjectId, t as projectIdCliArg } from "./mcp-args-CYOCdClW.mjs";
4
- import { n as writeMcpDataResult } from "./mcp-result-B5HHO7ap.mjs";
5
- import { i as requireActiveProject } from "./project-store-DHqT0-nk.mjs";
1
+ import { c as requireActiveProject } from "./project-store-Dl35JzZr.mjs";
2
+ import { n as writeError, t as formatCliArg } from "./cli.mjs";
3
+ import { n as mcpCall } from "./mcp-client-BTZH22b5.mjs";
4
+ import { n as resolveProjectId, t as projectIdCliArg } from "./mcp-args-DK3IGaO1.mjs";
5
+ import { n as writeMcpDataResult } from "./mcp-result-De_0PPlD.mjs";
6
6
  import { defineCommand } from "citty";
7
7
  //#region src/commands/audio/text.ts
8
8
  /**
@@ -1,10 +1,10 @@
1
- import { r as resolveProjectForUse, t as invalidateProjectAccessCache } from "./project-access-O-VSqqVC.mjs";
2
- import { n as writeError, r as writeResult, t as formatCliArg } from "./format-9T59sVxH.mjs";
3
- import { a as switchActiveProjectViaCallback, t as assertProjectSwitchAllowed } from "./project-store-DHqT0-nk.mjs";
1
+ import { i as invalidateActiveProjectCache, l as switchActiveProjectViaCallback, r as assertProjectSwitchAllowed } from "./project-store-Dl35JzZr.mjs";
2
+ import { a as resolveProjectForUse, i as invalidateProjectAccessCache } from "./project-access-pTN7ry15.mjs";
3
+ import { n as writeError, r as writeResult, t as formatCliArg } from "./cli.mjs";
4
4
  import { defineCommand } from "citty";
5
5
  //#region src/commands/project/use.ts
6
6
  /**
7
- * `beautx-cli project use` — persist active tenant/project via Host env callback.
7
+ * `beautx-cli project use` — persist active project via QCA /out/v2/current-project.
8
8
  */
9
9
  var use_default = defineCommand({
10
10
  meta: {
@@ -22,12 +22,14 @@ var use_default = defineCommand({
22
22
  async run({ args }) {
23
23
  try {
24
24
  assertProjectSwitchAllowed();
25
- const saved = await switchActiveProjectViaCallback(await resolveProjectForUse(args["project-id"]));
25
+ const resolved = await resolveProjectForUse(args["project-id"]);
26
+ invalidateActiveProjectCache();
27
+ const saved = await switchActiveProjectViaCallback(resolved);
26
28
  invalidateProjectAccessCache();
27
29
  writeResult({
28
30
  success: true,
29
31
  activeProject: saved,
30
- message: `已切换到「${saved.tenantName} / ${saved.projectName}」`
32
+ message: `已切换到「${saved.tenantName || saved.tenantId} / ${saved.projectName || saved.projectId}」`
31
33
  }, args.format);
32
34
  } catch (err) {
33
35
  writeError(err, args.format);
@@ -6,8 +6,8 @@ var visit_default = defineCommand({
6
6
  description: "客户来访查询"
7
7
  },
8
8
  subCommands: {
9
- list: () => import("./list-CB7YZTB4.mjs").then((m) => m.default),
10
- summary: () => import("./summary-Cg79V9oz.mjs").then((m) => m.default)
9
+ list: () => import("./list-BcYy7Ejx.mjs").then((m) => m.default),
10
+ summary: () => import("./summary-DgpSsQh9.mjs").then((m) => m.default)
11
11
  }
12
12
  });
13
13
  //#endregion