beautx-cli 1.0.2
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/README.md +282 -0
- package/dist/analyze-D4-U3EMZ.mjs +67 -0
- package/dist/api-CLlWvZ6D.mjs +56 -0
- package/dist/audio-BVEMBKjq.mjs +15 -0
- package/dist/cli.d.mts +1 -0
- package/dist/cli.mjs +34 -0
- package/dist/config-JuoIzFRK.mjs +14 -0
- package/dist/consultant-Cw1YwwtS.mjs +11 -0
- package/dist/content-Yo_WIT7q.mjs +46 -0
- package/dist/current-Bxh7Kreq.mjs +24 -0
- package/dist/customer-ClOadzRU.mjs +11 -0
- package/dist/doc-Ct90pWPu.mjs +15 -0
- package/dist/env-callback-B0J77QAo.mjs +349 -0
- package/dist/env-vars-CXEHR_mk.mjs +231 -0
- package/dist/fields-k9uXoI1-.mjs +70 -0
- package/dist/focus-DjNe5aAC.mjs +11 -0
- package/dist/format-CUmIaybA.mjs +7253 -0
- package/dist/get-Bvvpjak0.mjs +32 -0
- package/dist/kb-O5-Jsef7.mjs +14 -0
- package/dist/list-BfwcxhuB.mjs +51 -0
- package/dist/list-BtTJth6J.mjs +82 -0
- package/dist/list-CQ0BANsf.mjs +72 -0
- package/dist/list-CjvUJxab.mjs +40 -0
- package/dist/list-D5PQ9UFX.mjs +64 -0
- package/dist/list-DHuUNbzL.mjs +57 -0
- package/dist/list-Du1j8C6e.mjs +67 -0
- package/dist/list-Dyo2l4T0.mjs +82 -0
- package/dist/list-LLKHw4PC.mjs +82 -0
- package/dist/mcp-args-CYOCdClW.mjs +31 -0
- package/dist/mcp-client-CiA9h1aX.mjs +260 -0
- package/dist/mcp-result-BIkVZJmx.mjs +62 -0
- package/dist/project-access-DsvRpcxJ.mjs +274 -0
- package/dist/project-i7Ff3qdR.mjs +15 -0
- package/dist/project-store-DXTSwGKR.mjs +55 -0
- package/dist/qa-BYv1cNLv.mjs +48 -0
- package/dist/resistance-TNgE3tbY.mjs +11 -0
- package/dist/rolldown-runtime-YLnNgb9a.mjs +35 -0
- package/dist/search-Cq5goTou.mjs +67 -0
- package/dist/summary-DPEcAZs9.mjs +74 -0
- package/dist/text-BcZKHHRe.mjs +39 -0
- package/dist/use-BUuilhDM.mjs +39 -0
- package/dist/util-CztO5pc3.mjs +46 -0
- package/dist/visit-nsou1UG-.mjs +14 -0
- package/package.json +44 -0
|
@@ -0,0 +1,260 @@
|
|
|
1
|
+
import { n as __exportAll } from "./rolldown-runtime-YLnNgb9a.mjs";
|
|
2
|
+
import { _ as MissingGatewayError, a as isTokenExpired, c as readCredentials, d as resolveEndpoints, g as MissingAccessTokenError, l as readEnv, n as assertEndpointsValid, o as needsRefresh, p as AccessTokenExpiredError, t as ENV_KEYS, v as MissingRefreshTokenError, y as RefreshFailedError } from "./env-vars-CXEHR_mk.mjs";
|
|
3
|
+
import { t as invalidateProjectAccessCache } from "./project-access-DsvRpcxJ.mjs";
|
|
4
|
+
import { i as debugLogInfo, n as persistTokensToHost, r as debugLogError } from "./env-callback-B0J77QAo.mjs";
|
|
5
|
+
import { randomUUID } from "node:crypto";
|
|
6
|
+
//#region src/core/token-refresh.ts
|
|
7
|
+
/**
|
|
8
|
+
* Silent OAuth refresh_token grant — used by ensureAuth, not exposed as a command.
|
|
9
|
+
*/
|
|
10
|
+
async function refreshAccessToken(authUrl, refreshToken) {
|
|
11
|
+
const base = authUrl.replace(/\/$/, "");
|
|
12
|
+
const body = new URLSearchParams({
|
|
13
|
+
grant_type: "refresh_token",
|
|
14
|
+
refresh_token: refreshToken
|
|
15
|
+
});
|
|
16
|
+
const clientId = process.env.MCP_CLIENT_ID?.trim();
|
|
17
|
+
if (clientId) body.set("client_id", clientId);
|
|
18
|
+
const resp = await fetch(`${base}/oauth/token`, {
|
|
19
|
+
method: "POST",
|
|
20
|
+
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
|
21
|
+
body: body.toString(),
|
|
22
|
+
signal: AbortSignal.timeout(3e4)
|
|
23
|
+
});
|
|
24
|
+
const parsed = await resp.json().catch(() => ({}));
|
|
25
|
+
if (!resp.ok) {
|
|
26
|
+
const msg = parsed.error_description ?? parsed.error ?? resp.statusText;
|
|
27
|
+
throw new RefreshFailedError(String(msg));
|
|
28
|
+
}
|
|
29
|
+
const access = parsed.access_token;
|
|
30
|
+
if (typeof access !== "string" || !access) throw new RefreshFailedError("响应缺少 access_token");
|
|
31
|
+
return {
|
|
32
|
+
access_token: access,
|
|
33
|
+
refresh_token: typeof parsed.refresh_token === "string" ? parsed.refresh_token : void 0,
|
|
34
|
+
expires_in: typeof parsed.expires_in === "number" ? parsed.expires_in : void 0,
|
|
35
|
+
scope: typeof parsed.scope === "string" ? parsed.scope : void 0
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
//#endregion
|
|
39
|
+
//#region src/core/ensure-auth.ts
|
|
40
|
+
/**
|
|
41
|
+
* Pre-MCP auth guard — refresh tokens via Host callback when expiring soon.
|
|
42
|
+
*/
|
|
43
|
+
/**
|
|
44
|
+
* Ensure MCP_TOKEN is valid before an MCP call.
|
|
45
|
+
* Refreshes via OAuth + Host env callback when within REFRESH_BUFFER_MS of expiry.
|
|
46
|
+
*/
|
|
47
|
+
async function ensureAuth(opts = {}) {
|
|
48
|
+
const endpoints = resolveEndpoints();
|
|
49
|
+
const creds = readCredentials();
|
|
50
|
+
if (!(opts.force === true) && creds.accessToken && !isTokenExpired(creds.expiresAt) && !needsRefresh(creds.expiresAt)) return;
|
|
51
|
+
if (!creds.refreshToken) {
|
|
52
|
+
if (!creds.accessToken) throw new MissingAccessTokenError();
|
|
53
|
+
if (isTokenExpired(creds.expiresAt)) throw new AccessTokenExpiredError();
|
|
54
|
+
throw new MissingRefreshTokenError();
|
|
55
|
+
}
|
|
56
|
+
if (!endpoints.authUrl?.trim()) throw new RefreshFailedError("缺少 auth_url");
|
|
57
|
+
const tokens = await refreshAccessToken(endpoints.authUrl, creds.refreshToken);
|
|
58
|
+
const expiresAtMs = tokens.expires_in != null ? Date.now() + tokens.expires_in * 1e3 : Date.now() + 9e5;
|
|
59
|
+
await persistTokensToHost(tokens.access_token, tokens.refresh_token ?? creds.refreshToken, expiresAtMs);
|
|
60
|
+
invalidateProjectAccessCache();
|
|
61
|
+
}
|
|
62
|
+
//#endregion
|
|
63
|
+
//#region src/core/config.ts
|
|
64
|
+
/**
|
|
65
|
+
* MCP gateway configuration — env-only resolution.
|
|
66
|
+
*/
|
|
67
|
+
async function resolveMcpConfig() {
|
|
68
|
+
await ensureAuth();
|
|
69
|
+
const endpoints = resolveEndpoints();
|
|
70
|
+
if (!endpoints.gatewayUrl?.trim()) throw new MissingGatewayError();
|
|
71
|
+
assertEndpointsValid(endpoints);
|
|
72
|
+
const token = readEnv(ENV_KEYS.MCP_TOKEN);
|
|
73
|
+
if (!token) throw new MissingAccessTokenError();
|
|
74
|
+
return {
|
|
75
|
+
gatewayUrl: endpoints.gatewayUrl.replace(/\/$/, ""),
|
|
76
|
+
token,
|
|
77
|
+
authUrl: endpoints.authUrl.replace(/\/$/, "")
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
//#endregion
|
|
81
|
+
//#region src/core/mcp-client.ts
|
|
82
|
+
/**
|
|
83
|
+
* MCP JSON-RPC client — sends tools/call requests to the MCP gateway.
|
|
84
|
+
*
|
|
85
|
+
* Auth refresh is handled by ensureAuth() before resolveMcpConfig(); this module
|
|
86
|
+
* only reads MCP_TOKEN from env when issuing the HTTP request.
|
|
87
|
+
*/
|
|
88
|
+
var mcp_client_exports = /* @__PURE__ */ __exportAll({
|
|
89
|
+
MCP_CALL_SOURCE: () => MCP_CALL_SOURCE,
|
|
90
|
+
MCP_SERVICE_CODE: () => MCP_SERVICE_CODE,
|
|
91
|
+
McpGatewayError: () => McpGatewayError,
|
|
92
|
+
mcpCall: () => mcpCall,
|
|
93
|
+
unwrapMcpToolEnvelope: () => unwrapMcpToolEnvelope
|
|
94
|
+
});
|
|
95
|
+
/**
|
|
96
|
+
* The single MCP serviceCode every tool is registered under.
|
|
97
|
+
*
|
|
98
|
+
* ⚠️ 必须与 MCP 网关 Registry 里注册的 serviceCode 完全一致。改这里即可全局生效。
|
|
99
|
+
*/
|
|
100
|
+
const MCP_SERVICE_CODE = "beautx-cli";
|
|
101
|
+
/**
|
|
102
|
+
* Call-origin label sent on every MCP tools/call for audit / LangGraph metadata.
|
|
103
|
+
* Change this single constant to retag all beautx-cli traffic.
|
|
104
|
+
*/
|
|
105
|
+
const MCP_CALL_SOURCE = "beautx-cli";
|
|
106
|
+
/**
|
|
107
|
+
* Unwrap MCP tools/call result → BFF {@code { code, msg, data }} envelope.
|
|
108
|
+
*
|
|
109
|
+
* Gateway returns JSON-RPC {@code result.content[0].data}; some callers may
|
|
110
|
+
* already pass a bare envelope — both shapes are accepted.
|
|
111
|
+
*/
|
|
112
|
+
function unwrapMcpToolEnvelope(mcpResult) {
|
|
113
|
+
if (mcpResult && typeof mcpResult === "object") {
|
|
114
|
+
const obj = mcpResult;
|
|
115
|
+
const content = obj.content;
|
|
116
|
+
if (Array.isArray(content) && content.length > 0) {
|
|
117
|
+
const first = content[0];
|
|
118
|
+
if (first && typeof first === "object" && "data" in first) return first.data;
|
|
119
|
+
}
|
|
120
|
+
if ("code" in obj || "data" in obj || "msg" in obj) return obj;
|
|
121
|
+
}
|
|
122
|
+
return {};
|
|
123
|
+
}
|
|
124
|
+
const ERROR_HINTS = {
|
|
125
|
+
TOKEN_MISSING: "由 Host 注入 MCP_TOKEN",
|
|
126
|
+
TOKEN_INVALID: "由 Host 重新换票后更新 MCP_TOKEN",
|
|
127
|
+
TOKEN_EXPIRED: "由 Host 重新换票后更新 MCP_TOKEN / REFRESH_TOKEN",
|
|
128
|
+
TOKEN_AUD_MISMATCH: "确认 token 为 MCP 网关签发且 scope 含 mcp:invoke",
|
|
129
|
+
POLICY_DENIED: "无权访问该服务,请联系管理员确认 serviceCode 权限",
|
|
130
|
+
SERVICE_NOT_FOUND: "serviceCode 不存在,请确认网关侧已注册",
|
|
131
|
+
RATE_LIMITED: "请求被限流,请稍后重试",
|
|
132
|
+
UPSTREAM_ERROR: "上游服务异常,请稍后重试"
|
|
133
|
+
};
|
|
134
|
+
var McpGatewayError = class extends Error {
|
|
135
|
+
code;
|
|
136
|
+
hint;
|
|
137
|
+
status;
|
|
138
|
+
constructor(status, code, message) {
|
|
139
|
+
super(message);
|
|
140
|
+
this.name = "McpGatewayError";
|
|
141
|
+
this.code = code;
|
|
142
|
+
this.status = status;
|
|
143
|
+
this.hint = ERROR_HINTS[code] ?? `MCP 网关错误: ${code}`;
|
|
144
|
+
}
|
|
145
|
+
};
|
|
146
|
+
async function mcpCall(toolName, opts) {
|
|
147
|
+
if (toolName !== "project-list") {
|
|
148
|
+
const rawProjectId = opts.arguments?.project_id;
|
|
149
|
+
if (rawProjectId != null && String(rawProjectId).trim()) {
|
|
150
|
+
const { assertProjectAllowed } = await import("./project-access-DsvRpcxJ.mjs").then((n) => n.n);
|
|
151
|
+
await assertProjectAllowed(String(rawProjectId).trim());
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
return mcpCallOnce(toolName, opts, false);
|
|
155
|
+
}
|
|
156
|
+
async function mcpCallOnce(toolName, opts, retriedAfterRefresh) {
|
|
157
|
+
const config = await resolveMcpConfig();
|
|
158
|
+
const serviceCode = opts.serviceCode ?? "beautx-cli";
|
|
159
|
+
const url = `${config.gatewayUrl}/mcp/${serviceCode}`;
|
|
160
|
+
const argumentsWithCallSource = {
|
|
161
|
+
call_source: MCP_CALL_SOURCE,
|
|
162
|
+
...augmentWireArguments(toolName, opts.arguments)
|
|
163
|
+
};
|
|
164
|
+
const body = JSON.stringify({
|
|
165
|
+
jsonrpc: "2.0",
|
|
166
|
+
id: randomUUID(),
|
|
167
|
+
method: "tools/call",
|
|
168
|
+
params: {
|
|
169
|
+
name: toolName,
|
|
170
|
+
arguments: argumentsWithCallSource
|
|
171
|
+
}
|
|
172
|
+
});
|
|
173
|
+
const resp = await fetch(url, {
|
|
174
|
+
method: "POST",
|
|
175
|
+
headers: {
|
|
176
|
+
Accept: "application/json, text/event-stream",
|
|
177
|
+
"Content-Type": "application/json",
|
|
178
|
+
Authorization: `Bearer ${config.token}`
|
|
179
|
+
},
|
|
180
|
+
body,
|
|
181
|
+
signal: AbortSignal.timeout(opts.timeoutMs ?? 3e4)
|
|
182
|
+
});
|
|
183
|
+
debugLogInfo("mcp_call", {
|
|
184
|
+
toolName,
|
|
185
|
+
serviceCode,
|
|
186
|
+
url,
|
|
187
|
+
status: resp.status,
|
|
188
|
+
ok: resp.ok
|
|
189
|
+
});
|
|
190
|
+
const ct = resp.headers.get("content-type") || "";
|
|
191
|
+
let parsed;
|
|
192
|
+
if (ct.includes("application/json")) parsed = await resp.json();
|
|
193
|
+
else if (ct.includes("text/event-stream")) parsed = parseSseJson(await resp.text());
|
|
194
|
+
else parsed = await resp.text();
|
|
195
|
+
if (!resp.ok) {
|
|
196
|
+
const errBody = parsed;
|
|
197
|
+
const code = errBody?.error ?? errBody?.code ?? `HTTP_${resp.status}`;
|
|
198
|
+
const message = errBody?.message ?? errBody?.msg ?? errBody?.error_description ?? resp.statusText;
|
|
199
|
+
if (!retriedAfterRefresh && (code === "TOKEN_EXPIRED" || resp.status === 401)) {
|
|
200
|
+
await ensureAuth({ force: true });
|
|
201
|
+
return mcpCallOnce(toolName, opts, true);
|
|
202
|
+
}
|
|
203
|
+
debugLogError("mcp_gateway_error", {
|
|
204
|
+
toolName,
|
|
205
|
+
status: resp.status,
|
|
206
|
+
code,
|
|
207
|
+
message,
|
|
208
|
+
body: errBody
|
|
209
|
+
});
|
|
210
|
+
throw new McpGatewayError(resp.status, code, message);
|
|
211
|
+
}
|
|
212
|
+
const rpcResult = parsed;
|
|
213
|
+
if (rpcResult.error) throw new McpGatewayError(resp.status, `RPC_${rpcResult.error.code}`, rpcResult.error.message);
|
|
214
|
+
if (rpcResult.result?.isError) {
|
|
215
|
+
debugLogError("mcp_tool_error", {
|
|
216
|
+
toolName,
|
|
217
|
+
data: rpcResult.result
|
|
218
|
+
});
|
|
219
|
+
return {
|
|
220
|
+
status: resp.status,
|
|
221
|
+
ok: false,
|
|
222
|
+
data: rpcResult.result
|
|
223
|
+
};
|
|
224
|
+
}
|
|
225
|
+
return {
|
|
226
|
+
status: resp.status,
|
|
227
|
+
ok: true,
|
|
228
|
+
data: rpcResult.result ?? parsed
|
|
229
|
+
};
|
|
230
|
+
}
|
|
231
|
+
/** Gateway billing for project-list reads project_id from Host env; not a CLI flag. */
|
|
232
|
+
function augmentWireArguments(toolName, args) {
|
|
233
|
+
if (toolName !== "project-list") return args;
|
|
234
|
+
const { project_id: _drop, ...rest } = args;
|
|
235
|
+
const estateId = readEnv(ENV_KEYS.ESTATE_ID);
|
|
236
|
+
if (!estateId) return rest;
|
|
237
|
+
return {
|
|
238
|
+
...rest,
|
|
239
|
+
project_id: estateId
|
|
240
|
+
};
|
|
241
|
+
}
|
|
242
|
+
/**
|
|
243
|
+
* Extract the JSON-RPC payload from an SSE response body. MCP streamable-HTTP
|
|
244
|
+
* encodes the response as one or more `data:` events; we take the last event
|
|
245
|
+
* whose data parses as JSON. Falls back to the raw text if none parse.
|
|
246
|
+
*/
|
|
247
|
+
function parseSseJson(raw) {
|
|
248
|
+
let last;
|
|
249
|
+
for (const line of raw.split(/\r?\n/)) {
|
|
250
|
+
if (!line.startsWith("data:")) continue;
|
|
251
|
+
const payload = line.slice(5).trim();
|
|
252
|
+
if (!payload || payload === "[DONE]") continue;
|
|
253
|
+
try {
|
|
254
|
+
last = JSON.parse(payload);
|
|
255
|
+
} catch {}
|
|
256
|
+
}
|
|
257
|
+
return last ?? raw;
|
|
258
|
+
}
|
|
259
|
+
//#endregion
|
|
260
|
+
export { unwrapMcpToolEnvelope as i, mcpCall as n, mcp_client_exports as r, MCP_SERVICE_CODE as t };
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { i as unwrapMcpToolEnvelope, n as mcpCall } from "./mcp-client-CiA9h1aX.mjs";
|
|
2
|
+
import { n as writeError, r as writeResult } from "./format-CUmIaybA.mjs";
|
|
3
|
+
//#region src/core/mcp-result.ts
|
|
4
|
+
/**
|
|
5
|
+
* Normalize MCP tool responses for agent-friendly stdout (TOON tabular arrays).
|
|
6
|
+
*/
|
|
7
|
+
function exitApiError(result, format) {
|
|
8
|
+
writeError({
|
|
9
|
+
code: "API_ERROR",
|
|
10
|
+
status: result.status,
|
|
11
|
+
body: result.data
|
|
12
|
+
}, format);
|
|
13
|
+
process.exit(1);
|
|
14
|
+
}
|
|
15
|
+
/** Paginated BFF envelope → `{ page, size, total, [itemsKey], count }`. */
|
|
16
|
+
function writeMcpPageResult(result, format, options) {
|
|
17
|
+
if (!result.ok) exitApiError(result, format);
|
|
18
|
+
const envelope = unwrapMcpToolEnvelope(result.data);
|
|
19
|
+
const code = envelope.code;
|
|
20
|
+
if (code != null && String(code) !== "0") {
|
|
21
|
+
writeError({
|
|
22
|
+
code: "API_ERROR",
|
|
23
|
+
message: envelope.msg ?? String(code),
|
|
24
|
+
body: envelope
|
|
25
|
+
}, format);
|
|
26
|
+
process.exit(1);
|
|
27
|
+
}
|
|
28
|
+
const pageData = envelope.data ?? {};
|
|
29
|
+
const rows = Array.isArray(pageData.content) ? pageData.content : [];
|
|
30
|
+
const items = options.mapItems ? options.mapItems(rows) : rows;
|
|
31
|
+
writeResult({
|
|
32
|
+
page: pageData.page ?? options.defaultPage ?? 1,
|
|
33
|
+
size: pageData.size ?? options.defaultSize ?? 10,
|
|
34
|
+
total: pageData.total ?? items.length,
|
|
35
|
+
[options.itemsKey]: items,
|
|
36
|
+
count: items.length
|
|
37
|
+
}, format);
|
|
38
|
+
}
|
|
39
|
+
/** Unwrap `{ code, msg, data }` and write inner `data` only. */
|
|
40
|
+
function writeMcpDataResult(result, format, transform) {
|
|
41
|
+
if (!result.ok) exitApiError(result, format);
|
|
42
|
+
const envelope = unwrapMcpToolEnvelope(result.data);
|
|
43
|
+
const code = envelope.code;
|
|
44
|
+
if (code != null && String(code) !== "0") {
|
|
45
|
+
writeError({
|
|
46
|
+
code: "API_ERROR",
|
|
47
|
+
message: envelope.msg ?? String(code),
|
|
48
|
+
body: envelope
|
|
49
|
+
}, format);
|
|
50
|
+
process.exit(1);
|
|
51
|
+
}
|
|
52
|
+
const inner = envelope.data ?? envelope;
|
|
53
|
+
writeResult(transform ? transform(inner) : inner, format);
|
|
54
|
+
}
|
|
55
|
+
async function mcpCallPage(toolName, args, format, options, callOpts) {
|
|
56
|
+
writeMcpPageResult(await mcpCall(toolName, {
|
|
57
|
+
arguments: args,
|
|
58
|
+
timeoutMs: callOpts?.timeoutMs
|
|
59
|
+
}), format, options);
|
|
60
|
+
}
|
|
61
|
+
//#endregion
|
|
62
|
+
export { writeMcpDataResult as n, mcpCallPage as t };
|
|
@@ -0,0 +1,274 @@
|
|
|
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";
|
|
3
|
+
var InsufficientCreditError = class extends Error {
|
|
4
|
+
code = "INSUFFICIENT_CREDIT";
|
|
5
|
+
hint = "(该项目下)用户积分余额不足,无法继续查询;请告知用户联系管理员充值";
|
|
6
|
+
projectId;
|
|
7
|
+
remaining;
|
|
8
|
+
constructor(projectId, remaining) {
|
|
9
|
+
super(`项目 ${projectId} 积分余额不足(剩余 ${remaining})`);
|
|
10
|
+
this.name = "InsufficientCreditError";
|
|
11
|
+
this.projectId = projectId;
|
|
12
|
+
this.remaining = remaining;
|
|
13
|
+
}
|
|
14
|
+
};
|
|
15
|
+
var CreditAccountNotFoundError = class extends Error {
|
|
16
|
+
code = "CREDIT_ACCOUNT_NOT_FOUND";
|
|
17
|
+
hint = "当前用户在该项目下暂无积分账户;请告知用户联系管理员开通或充值后再试";
|
|
18
|
+
projectId;
|
|
19
|
+
constructor(projectId) {
|
|
20
|
+
super(`项目 ${projectId} 未找到积分账户`);
|
|
21
|
+
this.name = "CreditAccountNotFoundError";
|
|
22
|
+
this.projectId = projectId;
|
|
23
|
+
}
|
|
24
|
+
};
|
|
25
|
+
var CreditCheckFailedError = class extends Error {
|
|
26
|
+
code = "CREDIT_CHECK_FAILED";
|
|
27
|
+
hint = "积分余额查询失败,请稍后重试;若持续失败请联系管理员";
|
|
28
|
+
projectId;
|
|
29
|
+
constructor(projectId, detail) {
|
|
30
|
+
super(detail ?? `无法查询项目 ${projectId} 的积分余额`);
|
|
31
|
+
this.name = "CreditCheckFailedError";
|
|
32
|
+
this.projectId = projectId;
|
|
33
|
+
}
|
|
34
|
+
};
|
|
35
|
+
async function assertCreditRemaining(projectId) {
|
|
36
|
+
const id = projectId?.trim();
|
|
37
|
+
if (!id) return;
|
|
38
|
+
const remaining = await fetchCreditRemaining(requireUserId(), id);
|
|
39
|
+
if (remaining > 0) return;
|
|
40
|
+
throw new InsufficientCreditError(id, remaining);
|
|
41
|
+
}
|
|
42
|
+
async function fetchCreditRemaining(userId, projectId) {
|
|
43
|
+
const { callbackBaseUrl } = resolveEndpoints();
|
|
44
|
+
const url = new URL(`/api/wang-claw/out/credit/users/${encodeURIComponent(userId)}/remaining`, callbackBaseUrl);
|
|
45
|
+
url.searchParams.set("projectId", projectId);
|
|
46
|
+
let resp;
|
|
47
|
+
try {
|
|
48
|
+
resp = await fetch(url, {
|
|
49
|
+
method: "GET",
|
|
50
|
+
headers: { Accept: "application/json" },
|
|
51
|
+
signal: AbortSignal.timeout(1e4)
|
|
52
|
+
});
|
|
53
|
+
} catch (err) {
|
|
54
|
+
throw new CreditCheckFailedError(projectId, `积分余额查询请求失败: ${err instanceof Error ? err.message : String(err)}`);
|
|
55
|
+
}
|
|
56
|
+
let body;
|
|
57
|
+
try {
|
|
58
|
+
body = await resp.json();
|
|
59
|
+
} catch {
|
|
60
|
+
throw new CreditCheckFailedError(projectId, `积分余额查询返回非 JSON(HTTP ${resp.status})`);
|
|
61
|
+
}
|
|
62
|
+
if (resp.status === 404) throw new CreditAccountNotFoundError(projectId);
|
|
63
|
+
if (!resp.ok) {
|
|
64
|
+
const msg = extractEnvelopeMessage(body) ?? resp.statusText;
|
|
65
|
+
throw new CreditCheckFailedError(projectId, `积分余额查询失败(HTTP ${resp.status}): ${msg}`);
|
|
66
|
+
}
|
|
67
|
+
const envelope = body;
|
|
68
|
+
if (envelope.code != null && String(envelope.code) !== "0") throw new CreditCheckFailedError(projectId, envelope.msg ?? `积分余额查询业务错误: ${envelope.code}`);
|
|
69
|
+
const raw = envelope.data?.remaining;
|
|
70
|
+
const remaining = typeof raw === "number" ? raw : Number(raw);
|
|
71
|
+
if (Number.isNaN(remaining)) throw new CreditCheckFailedError(projectId, "积分余额响应缺少 data.remaining");
|
|
72
|
+
return remaining;
|
|
73
|
+
}
|
|
74
|
+
function extractEnvelopeMessage(body) {
|
|
75
|
+
if (!body || typeof body !== "object") return void 0;
|
|
76
|
+
const msg = body.msg;
|
|
77
|
+
return typeof msg === "string" && msg.trim() ? msg.trim() : void 0;
|
|
78
|
+
}
|
|
79
|
+
//#endregion
|
|
80
|
+
//#region src/core/project-access.ts
|
|
81
|
+
/**
|
|
82
|
+
* Allowed estate (project) guard for CLI — validates project_id against
|
|
83
|
+
* {@code project-list} before MCP calls (in-process TTL cache).
|
|
84
|
+
*/
|
|
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
|
+
const PROJECT_ACCESS_TTL_MS = 300 * 1e3;
|
|
93
|
+
const PROJECT_LIST_PAGE_SIZE = 100;
|
|
94
|
+
let cache = null;
|
|
95
|
+
var ProjectNotAllowedError = class extends Error {
|
|
96
|
+
code = "PROJECT_NOT_ALLOWED";
|
|
97
|
+
hint = "运行 `wangai-cli project list` 查看有权限的项目,或使用 `wangai-cli project use` 切换";
|
|
98
|
+
projectId;
|
|
99
|
+
constructor(projectId) {
|
|
100
|
+
super(`项目 ${projectId} 不在当前用户有权限且已开通 APP_CLAW 的项目列表中`);
|
|
101
|
+
this.name = "ProjectNotAllowedError";
|
|
102
|
+
this.projectId = projectId;
|
|
103
|
+
}
|
|
104
|
+
};
|
|
105
|
+
function invalidateProjectAccessCache() {
|
|
106
|
+
cache = null;
|
|
107
|
+
}
|
|
108
|
+
function resolveCacheTenantId() {
|
|
109
|
+
const fromEnv = readEnv(ENV_KEYS.TENANT_ID);
|
|
110
|
+
if (fromEnv) return fromEnv;
|
|
111
|
+
return readActiveProject()?.tenantId?.trim() ?? "";
|
|
112
|
+
}
|
|
113
|
+
function cacheIsValid(state, tenantId) {
|
|
114
|
+
return state.tenantId === tenantId && Date.now() - state.fetchedAt < 3e5;
|
|
115
|
+
}
|
|
116
|
+
function pickStringField(row, ...keys) {
|
|
117
|
+
for (const key of keys) {
|
|
118
|
+
const value = row[key];
|
|
119
|
+
if (value != null && String(value).trim()) return String(value).trim();
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
function parseProjectListRow(raw) {
|
|
123
|
+
const row = raw && typeof raw === "object" ? raw : {};
|
|
124
|
+
return {
|
|
125
|
+
estateId: pickStringField(row, "estateId", "estate_id", "projectId", "project_id") ?? "",
|
|
126
|
+
tenantId: pickStringField(row, "tenantId", "tenant_id"),
|
|
127
|
+
tenantName: pickStringField(row, "tenantName", "tenant_name"),
|
|
128
|
+
estateName: pickStringField(row, "estateName", "estate_name", "projectName", "project_name")
|
|
129
|
+
};
|
|
130
|
+
}
|
|
131
|
+
/** project-list is tenant-scoped; fall back to Host TENANT_ID when row omits it. */
|
|
132
|
+
function finalizeResolvedProject(partial) {
|
|
133
|
+
const tenantId = partial.tenantId?.trim() || readEnv(ENV_KEYS.TENANT_ID)?.trim();
|
|
134
|
+
if (!tenantId) throw new ConfigInvalidError("无法解析 tenantId", "请确认沙箱已注入 TENANT_ID,或联系平台排查 project-list 返回");
|
|
135
|
+
return {
|
|
136
|
+
tenantId,
|
|
137
|
+
tenantName: partial.tenantName?.trim() ?? "",
|
|
138
|
+
projectId: partial.projectId,
|
|
139
|
+
projectName: partial.projectName?.trim() ?? ""
|
|
140
|
+
};
|
|
141
|
+
}
|
|
142
|
+
function isHostActiveEstate(projectId) {
|
|
143
|
+
const activeEstateId = readEnv(ENV_KEYS.ESTATE_ID)?.trim();
|
|
144
|
+
return Boolean(activeEstateId && activeEstateId === projectId);
|
|
145
|
+
}
|
|
146
|
+
/**
|
|
147
|
+
* Ensure {@code projectId} is in the gateway project-list roster.
|
|
148
|
+
* Uses a short-lived in-process cache keyed by tenant id.
|
|
149
|
+
*/
|
|
150
|
+
async function assertProjectAllowed(projectId) {
|
|
151
|
+
const id = projectId?.trim();
|
|
152
|
+
if (!id) return;
|
|
153
|
+
if (!isHostActiveEstate(id)) {
|
|
154
|
+
const tenantId = resolveCacheTenantId();
|
|
155
|
+
if (cache && cacheIsValid(cache, tenantId)) {
|
|
156
|
+
if (!cache.allowedEstateIds.has(id)) {
|
|
157
|
+
if (cache.complete) throw new ProjectNotAllowedError(id);
|
|
158
|
+
await loadAllowedProjectsUntilResolved(id, tenantId);
|
|
159
|
+
}
|
|
160
|
+
} else await loadAllowedProjectsUntilResolved(id, tenantId);
|
|
161
|
+
}
|
|
162
|
+
await assertCreditRemaining(id);
|
|
163
|
+
}
|
|
164
|
+
/**
|
|
165
|
+
* Resolve tenant/project metadata for {@code project use} from project-list.
|
|
166
|
+
* Names are display-only (Host env); IDs come from the roster row.
|
|
167
|
+
*/
|
|
168
|
+
async function resolveProjectForUse(projectId) {
|
|
169
|
+
const id = projectId?.trim();
|
|
170
|
+
if (!id) throw new ConfigInvalidError("缺少 project_id", "运行 `wangai-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
|
+
}
|
|
182
|
+
}
|
|
183
|
+
const row = await lookupProjectRow(id);
|
|
184
|
+
await assertCreditRemaining(id);
|
|
185
|
+
return finalizeResolvedProject(row);
|
|
186
|
+
}
|
|
187
|
+
async function lookupProjectRow(projectId) {
|
|
188
|
+
let page = 1;
|
|
189
|
+
let fetchedCount = 0;
|
|
190
|
+
while (true) {
|
|
191
|
+
const { content, total } = await fetchProjectListPage(page, PROJECT_LIST_PAGE_SIZE);
|
|
192
|
+
fetchedCount += content.length;
|
|
193
|
+
for (const row of content) if (row.estateId === projectId) return {
|
|
194
|
+
tenantId: row.tenantId ?? "",
|
|
195
|
+
tenantName: row.tenantName ?? "",
|
|
196
|
+
projectId,
|
|
197
|
+
projectName: row.estateName ?? ""
|
|
198
|
+
};
|
|
199
|
+
if (content.length === 0 || fetchedCount >= total) throw new ProjectNotAllowedError(projectId);
|
|
200
|
+
page += 1;
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
async function loadAllowedProjectsUntilResolved(projectId, tenantId) {
|
|
204
|
+
const ids = cache && cache.tenantId === tenantId ? new Set(cache.allowedEstateIds) : /* @__PURE__ */ new Set();
|
|
205
|
+
let page = 1;
|
|
206
|
+
let fetchedCount = 0;
|
|
207
|
+
while (true) {
|
|
208
|
+
const { content, total } = await fetchProjectListPage(page, PROJECT_LIST_PAGE_SIZE);
|
|
209
|
+
fetchedCount += content.length;
|
|
210
|
+
for (const row of content) if (row.estateId) ids.add(row.estateId);
|
|
211
|
+
if (ids.has(projectId)) {
|
|
212
|
+
const complete = content.length === 0 || fetchedCount >= total;
|
|
213
|
+
cache = {
|
|
214
|
+
tenantId,
|
|
215
|
+
allowedEstateIds: ids,
|
|
216
|
+
fetchedAt: Date.now(),
|
|
217
|
+
complete
|
|
218
|
+
};
|
|
219
|
+
return;
|
|
220
|
+
}
|
|
221
|
+
if (content.length === 0 || fetchedCount >= total) {
|
|
222
|
+
cache = {
|
|
223
|
+
tenantId,
|
|
224
|
+
allowedEstateIds: ids,
|
|
225
|
+
fetchedAt: Date.now(),
|
|
226
|
+
complete: true
|
|
227
|
+
};
|
|
228
|
+
throw new ProjectNotAllowedError(projectId);
|
|
229
|
+
}
|
|
230
|
+
page += 1;
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
function normalizeProjectListPage(page) {
|
|
234
|
+
return {
|
|
235
|
+
total: page.total,
|
|
236
|
+
content: page.content.map((row) => row.estateId ? row : parseProjectListRow(row))
|
|
237
|
+
};
|
|
238
|
+
}
|
|
239
|
+
async function fetchProjectListPage(page, size) {
|
|
240
|
+
const { mcpCall, unwrapMcpToolEnvelope } = await import("./mcp-client-CiA9h1aX.mjs").then((n) => n.r);
|
|
241
|
+
const result = await mcpCall("project-list", { arguments: {
|
|
242
|
+
page,
|
|
243
|
+
size
|
|
244
|
+
} });
|
|
245
|
+
if (!result.ok) {
|
|
246
|
+
const detail = extractMcpFailureDetail(result.data);
|
|
247
|
+
throw new ConfigInvalidError(detail ? `无法拉取项目列表以校验 project_id: ${detail}` : "无法拉取项目列表以校验 project_id", "检查 MCP 网关与 token 是否正常;大租户可先用 Host 预置当前项目");
|
|
248
|
+
}
|
|
249
|
+
const envelope = unwrapMcpToolEnvelope(result.data);
|
|
250
|
+
const code = envelope.code;
|
|
251
|
+
if (code != null && String(code) !== "0") throw new ConfigInvalidError(envelope.msg ?? "拉取项目列表失败", "运行 `wangai-cli project list` 确认权限");
|
|
252
|
+
const pageData = envelope.data ?? {};
|
|
253
|
+
const rows = Array.isArray(pageData.content) ? pageData.content : [];
|
|
254
|
+
return normalizeProjectListPage({
|
|
255
|
+
content: rows.map((row) => parseProjectListRow(row)),
|
|
256
|
+
total: pageData.total ?? rows.length
|
|
257
|
+
});
|
|
258
|
+
}
|
|
259
|
+
function extractMcpFailureDetail(data) {
|
|
260
|
+
if (!data || typeof data !== "object") return void 0;
|
|
261
|
+
const content = data.content;
|
|
262
|
+
if (!Array.isArray(content) || content.length === 0) return void 0;
|
|
263
|
+
const first = content[0];
|
|
264
|
+
if (!first || typeof first !== "object") return void 0;
|
|
265
|
+
const text = first.text;
|
|
266
|
+
if (typeof text === "string" && text.trim()) return text.trim();
|
|
267
|
+
if (text && typeof text === "object") {
|
|
268
|
+
const envelope = text;
|
|
269
|
+
const msg = envelope.msg ?? envelope.message;
|
|
270
|
+
if (typeof msg === "string" && msg.trim()) return msg.trim();
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
//#endregion
|
|
274
|
+
export { project_access_exports as n, resolveProjectForUse as r, invalidateProjectAccessCache as t };
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { defineCommand } from "citty";
|
|
2
|
+
//#region src/commands/project/index.ts
|
|
3
|
+
var project_default = defineCommand({
|
|
4
|
+
meta: {
|
|
5
|
+
name: "project",
|
|
6
|
+
description: "查询 / 切换激活项目"
|
|
7
|
+
},
|
|
8
|
+
subCommands: {
|
|
9
|
+
list: () => import("./list-DHuUNbzL.mjs").then((m) => m.default),
|
|
10
|
+
use: () => import("./use-BUuilhDM.mjs").then((m) => m.default),
|
|
11
|
+
current: () => import("./current-Bxh7Kreq.mjs").then((m) => m.default)
|
|
12
|
+
}
|
|
13
|
+
});
|
|
14
|
+
//#endregion
|
|
15
|
+
export { project_default as default };
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { l as readEnv, s as readActiveProject, t as ENV_KEYS } from "./env-vars-CXEHR_mk.mjs";
|
|
2
|
+
import { t as persistActiveProjectToHost } from "./env-callback-B0J77QAo.mjs";
|
|
3
|
+
//#region src/core/project-store.ts
|
|
4
|
+
/**
|
|
5
|
+
* Active estate (楼盘) — env-only; Host is the persistence layer via callback.
|
|
6
|
+
*/
|
|
7
|
+
async function loadActiveProject() {
|
|
8
|
+
return readActiveProject();
|
|
9
|
+
}
|
|
10
|
+
async function switchActiveProjectViaCallback(p) {
|
|
11
|
+
await persistActiveProjectToHost({
|
|
12
|
+
tenantId: p.tenantId,
|
|
13
|
+
tenantName: p.tenantName,
|
|
14
|
+
projectId: p.projectId,
|
|
15
|
+
projectName: p.projectName
|
|
16
|
+
});
|
|
17
|
+
return {
|
|
18
|
+
...p,
|
|
19
|
+
updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
20
|
+
source: "env"
|
|
21
|
+
};
|
|
22
|
+
}
|
|
23
|
+
var NoActiveProjectError = class extends Error {
|
|
24
|
+
code = "NO_ACTIVE_PROJECT";
|
|
25
|
+
hint = "先用 `wangai-cli project list [--keyword <kw>]` 查看可选楼盘,再用 `wangai-cli project use --project-id <id>` 激活;或由 Host 预置当前项目。";
|
|
26
|
+
constructor() {
|
|
27
|
+
super("当前未设置激活楼盘");
|
|
28
|
+
this.name = "NoActiveProjectError";
|
|
29
|
+
}
|
|
30
|
+
};
|
|
31
|
+
async function requireActiveProject() {
|
|
32
|
+
const p = await loadActiveProject();
|
|
33
|
+
if (!p?.projectId) throw new NoActiveProjectError();
|
|
34
|
+
return p;
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Project switching is blocked only in the aike app (XB_APP_ID=aike).
|
|
38
|
+
*/
|
|
39
|
+
var ProjectSwitchNotAllowedError = class extends Error {
|
|
40
|
+
code = "PROJECT_SWITCH_NOT_ALLOWED";
|
|
41
|
+
hint = "当前应用(XB_APP_ID=aike)不允许通过 CLI 切换楼盘,请使用 UI 切换。";
|
|
42
|
+
constructor() {
|
|
43
|
+
super("无法切换楼盘:不允许在当前应用下切换");
|
|
44
|
+
this.name = "ProjectSwitchNotAllowedError";
|
|
45
|
+
}
|
|
46
|
+
};
|
|
47
|
+
function assertProjectSwitchAllowed() {
|
|
48
|
+
if (!isProjectSwitchAllowed()) throw new ProjectSwitchNotAllowedError();
|
|
49
|
+
}
|
|
50
|
+
/** Whether CLI may run `project use` (false only when XB_APP_ID=aike). */
|
|
51
|
+
function isProjectSwitchAllowed() {
|
|
52
|
+
return readEnv(ENV_KEYS.XB_APP_ID).toLowerCase() !== "aike";
|
|
53
|
+
}
|
|
54
|
+
//#endregion
|
|
55
|
+
export { switchActiveProjectViaCallback as a, requireActiveProject as i, isProjectSwitchAllowed as n, loadActiveProject as r, assertProjectSwitchAllowed as t };
|