@wkgeo/cli 1.1.3 → 1.1.5

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.
@@ -0,0 +1,694 @@
1
+ /**
2
+ * `data` 命令组 —— **数据交换**(老板 2026-11-10 单):本地 CLI 一把取到三类运营数据。
3
+ *
4
+ * · `wkgeo data chat` AI 客服会话 / 单会话消息(`/aikefu` → `wkgeo-plugin-aikefu`)
5
+ * · `wkgeo data stats` 访问统计按日 PV / UV / IP 唯一数 + Top 页面 / 来源(`/analytics` → `wkgeo-plugin-analytics`)
6
+ * · `wkgeo data usage` 大模型消耗(按站点 / 模型 / 日:请求数、token、费用)(`/admin` → `wkgeo-admin` 的 `llmCostSummary`)
7
+ *
8
+ * ## 为什么单独成组、不复用现有命令
9
+ * 现有命令各有归属(`overview` 是控制台快照、`logs` 是操作日志、`ai` 是**本机**模型)。
10
+ * 这一组只做一件事:**把「对外可交换的数据」按稳定结构吐出来**(默认表格,`--json` 给下游用,
11
+ * `--out` 落 CSV / JSON 文件)。所以字段名一次定死,见各命令的 `notes`。
12
+ *
13
+ * ## 三条硬口径
14
+ * 1. **只读**:三个动作在服务端都是 `access:'read'`;这里没有任何 `--confirm` 写动作。
15
+ * 2. **站点必须先定**:`--site <ID|域名>` > `WKONGAI_SITE` > `wkgeo site use`。
16
+ * 支持域名/短域/站名是**本地解析**(`listSites` 里按 domain / prefix_host / 名称匹配)——
17
+ * 解析不到就报用法错误,绝不把域名当站点 ID 丢给服务端(那会变成一次无意义的 400)。
18
+ * 3. **人产出的正文默认脱敏**:客服问答里可能有手机号 / 邮箱 / IP,`data chat` 默认过
19
+ * `maskPii`(与 `forms entries` / `context export` 同一套);要原文显式加 `--raw`,
20
+ * 并且 `--out` 落盘的也是脱敏后的内容(红线:不导出未脱敏 PII)。
21
+ *
22
+ * ## 身份与网关
23
+ * 三个动作都走 OAuth Bearer(`wkgeo login` 拿的令牌),**不读 CMS Cookie**:
24
+ * · `/aikefu` `/analytics` 是插件函数:2026-11-10 起新增 **CLI Bearer 只读通道**
25
+ * (与 `contact-form` 的 CLI 通道同口径:无 Cookie + Bearer ⇒ 只放行 `access:'read'`,
26
+ * 站点从 `x-cms-site` 取并复核成员关系;写动作在进 handler 前就 403);
27
+ * · `/admin` 的 `llmCostSummary` 是「AI 费用只读位」,令牌 scope 需含 `llm:cost_read`
28
+ * (默认 scope 不含,`data usage` 会给出精确的重授权命令)。
29
+ */
30
+
31
+ import fs from 'node:fs';
32
+ import path from 'node:path';
33
+
34
+ import { CliError, EXIT, UsageError } from '../errors.mjs';
35
+ import { formatMoney, maskPii } from '../format.mjs';
36
+ import { PLATFORM_WEB_ORIGIN } from '../hosts.mjs';
37
+
38
+ /* ------------------------------------------------------------------ 公共:站点 */
39
+
40
+ const SITE_FLAG = {
41
+ site: {
42
+ type: 'string',
43
+ desc: '站点 ID 或域名(默认用 `wkgeo site use` 选中的站点,可用 WKONGAI_SITE 覆盖)',
44
+ },
45
+ };
46
+
47
+ const UUID_RE = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;
48
+
49
+ function hostOf(value) {
50
+ const text = String(value || '').trim().toLowerCase();
51
+ if (!text) return '';
52
+ const noScheme = text.replace(/^https?:\/\//, '');
53
+ return noScheme.split('/')[0].split('?')[0].replace(/:\d+$/, '').replace(/\.$/, '');
54
+ }
55
+
56
+ /** 去 `www.` 再比:`www.example.com` 与 `example.com` 视为同一个站(与后端域名台账口径一致) */
57
+ function bareHost(value) {
58
+ return hostOf(value).replace(/^www\./, '');
59
+ }
60
+
61
+ /**
62
+ * 站点解析:ID 直接用;域名 / 短域 / 站名走 `listSites` 本地匹配。
63
+ *
64
+ * ⚠️ 为什么不把域名丢给服务端:三个动作的站点参数都只认 `site.id::text`
65
+ * (`x-cms-site` 头 + 归属校验),传域名等于没传。这里先换 ID,错误也在这里说清楚。
66
+ */
67
+ async function resolveSiteId(ctx) {
68
+ const flagSite = ctx.flags.site !== undefined && ctx.flags.site !== '' ? String(ctx.flags.site).trim() : '';
69
+ const explicit = flagSite || String((ctx.env && ctx.env.WKONGAI_SITE) || '').trim();
70
+ if (explicit && UUID_RE.test(explicit)) return explicit;
71
+
72
+ if (!explicit) {
73
+ const site = ctx.cmsSite();
74
+ if (site && site.id) return site.id;
75
+ throw new UsageError(
76
+ 'data 命令要指定站点:先 `wkgeo site use <站点ID>`,或加 `--site <站点ID|域名>` / 设 WKONGAI_SITE(站点 ID 见 `wkgeo sites list`)',
77
+ );
78
+ }
79
+
80
+ const wanted = bareHost(explicit) || explicit.toLowerCase();
81
+ let data;
82
+ try {
83
+ data = await ctx.callData('listSites', { limit: 200 });
84
+ } catch (e) {
85
+ throw new UsageError(
86
+ `--site 收到的是「${explicit}」,不是站点 ID;本地要拿站点列表才能换成 ID,但 \`listSites\` 调不通:` +
87
+ `${(e && e.message) || e}\n改用站点 ID(\`wkgeo sites list\` 里看 id 列)再试`,
88
+ );
89
+ }
90
+ const rows = Array.isArray(data) ? data : (data && (data.rows || data.list || data.sites)) || [];
91
+ const hit = rows.find((one) => {
92
+ const hosts = [one.domain, one.custom_domain, one.cms_domain, one.prefix_host, ...(Array.isArray(one.domains) ? one.domains : [])]
93
+ .filter(Boolean)
94
+ .map(bareHost);
95
+ const name = String(one.name || '').trim().toLowerCase();
96
+ return hosts.includes(wanted) || name === explicit.trim().toLowerCase();
97
+ });
98
+ if (!hit || !hit.id) {
99
+ throw new UsageError(
100
+ `--site 里找不到「${explicit}」对应的站点(按域名 / 短域 / 站名都没匹配上)。\n` +
101
+ '先看 `wkgeo sites list`,或直接用站点 ID:`--site <站点ID>`',
102
+ );
103
+ }
104
+ return String(hit.id);
105
+ }
106
+
107
+ /* ------------------------------------------------------------------ 公共:日期 */
108
+
109
+ const DAY_RE = /^(\d{4})-(\d{2})-(\d{2})$/;
110
+
111
+ /** `YYYY-MM-DD` → 北京自然日 key(校验真日期:2026-02-30 这种直接报用法错误) */
112
+ function parseDay(text, flagName) {
113
+ const s = String(text || '').trim();
114
+ const m = DAY_RE.exec(s);
115
+ if (!m) throw new UsageError(`--${flagName} 要写 YYYY-MM-DD(如 2026-11-01),收到:${s}`);
116
+ const y = Number(m[1]);
117
+ const mo = Number(m[2]);
118
+ const d = Number(m[3]);
119
+ const probe = new Date(Date.UTC(y, mo - 1, d));
120
+ if (probe.getUTCFullYear() !== y || probe.getUTCMonth() !== mo - 1 || probe.getUTCDate() !== d) {
121
+ throw new UsageError(`--${flagName} 不是有效日期:${s}`);
122
+ }
123
+ return s;
124
+ }
125
+
126
+ function addDays(day, n) {
127
+ const [y, m, d] = String(day).split('-').map(Number);
128
+ const t = Date.UTC(y, m - 1, d) + n * 86400000;
129
+ const dt = new Date(t);
130
+ const p = (x) => String(x).padStart(2, '0');
131
+ return `${dt.getUTCFullYear()}-${p(dt.getUTCMonth() + 1)}-${p(dt.getUTCDate())}`;
132
+ }
133
+
134
+ /** 北京「今天」(UTC+8 固定、无夏令时;与后端 `beijingDayKey()` 同口径) */
135
+ function beijingToday(nowMs) {
136
+ const t = new Date(Number(nowMs) + 8 * 3600 * 1000);
137
+ const p = (x) => String(x).padStart(2, '0');
138
+ return `${t.getUTCFullYear()}-${p(t.getUTCMonth() + 1)}-${p(t.getUTCDate())}`;
139
+ }
140
+
141
+ /**
142
+ * `--from` / `--to` → 闭区间日期。
143
+ * 默认窗口:`stats` 7 天、`usage` 7 天、`chat` **不限**(全部历史,最新在前)。
144
+ */
145
+ function rangeOf(ctx, { defaultDays = 0, flag }) {
146
+ const toRaw = ctx.flags.to !== undefined && ctx.flags.to !== '' ? String(ctx.flags.to) : '';
147
+ const fromRaw = ctx.flags.from !== undefined && ctx.flags.from !== '' ? String(ctx.flags.from) : '';
148
+ const today = beijingToday(ctx.now());
149
+ let to = toRaw ? parseDay(toRaw, 'to') : today;
150
+ let from = fromRaw ? parseDay(fromRaw, 'from') : defaultDays ? addDays(to, -(defaultDays - 1)) : '';
151
+ if (!from && !toRaw) {
152
+ return { from: '', to: '' };
153
+ }
154
+ if (from && from > to) throw new UsageError(`--from(${from})不能晚于 --to(${to})`);
155
+ const span = Math.round((Date.parse(`${to}T00:00:00Z`) - Date.parse(`${from || to}T00:00:00Z`)) / 86400000) + 1;
156
+ if (span > 366) throw new UsageError(`时间跨度 ${span} 天太长(上限 366 天),请缩小 --from/--to`);
157
+ return { from, to };
158
+ }
159
+
160
+ /** 某天 00:00(北京)→ 该天结束(次日 00:00,左闭右开)的 ISO 串(给 `/admin` 的 from/to 用) */
161
+ function dayStartIso(day) {
162
+ return `${day}T00:00:00+08:00`;
163
+ }
164
+ function dayNextIso(day) {
165
+ return `${addDays(day, 1)}T00:00:00+08:00`;
166
+ }
167
+
168
+ /* ------------------------------------------------------------------ 公共:输出 */
169
+
170
+ function pad2(n) {
171
+ return String(n).padStart(2, '0');
172
+ }
173
+
174
+ /** 北京时间把服务端时间串规范化成 `YYYY-MM-DD HH:mm:ss`(拿不到就原样) */
175
+ function beijingTime(value) {
176
+ if (!value) return '';
177
+ /**
178
+ * MaxKB / PG 的 `timestamptz::text` 常见 `2026-11-09 21:21:30.459372+08`:
179
+ * `+08` 没有分钟、还带小数秒,直接 `new Date()` 在部分 Node 版本会判 Invalid。
180
+ * 先把小数秒去掉、把 `+08` 补成 `+08:00` 再解析;仍解析不了就原样返回(不假装成 1970)。
181
+ */
182
+ const normalized = String(value)
183
+ .trim()
184
+ .replace(/\.\d+/, '')
185
+ .replace(/([+-]\d{2})$/, '$1:00');
186
+ const d = new Date(normalized.replace(' ', 'T'));
187
+ if (Number.isNaN(d.getTime())) return String(value);
188
+ const t = new Date(d.getTime() + 8 * 3600 * 1000);
189
+ return `${t.getUTCFullYear()}-${pad2(t.getUTCMonth() + 1)}-${pad2(t.getUTCDate())} ${pad2(t.getUTCHours())}:${pad2(t.getUTCMinutes())}:${pad2(t.getUTCSeconds())}`;
190
+ }
191
+
192
+ function csvCell(value) {
193
+ const s = value === null || value === undefined ? '' : String(value);
194
+ return /[",\r\n]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s;
195
+ }
196
+
197
+ /** 一组对象 → CSV(表头取**并集**并保持首次出现顺序;UTF-8 BOM 让 Excel 不乱码) */
198
+ function toCsv(rows) {
199
+ const cols = [];
200
+ for (const row of rows) {
201
+ for (const key of Object.keys(row || {})) if (!cols.includes(key)) cols.push(key);
202
+ }
203
+ const lines = [cols.map(csvCell).join(',')];
204
+ for (const row of rows) lines.push(cols.map((key) => csvCell(row ? row[key] : '')).join(','));
205
+ return `\ufeff${lines.join('\r\n')}\r\n`;
206
+ }
207
+
208
+ /**
209
+ * `--out <file>`:`.csv` 落行(扁平表),`.json` 落**完整 payload**(含 totals / 元信息)。
210
+ * 目录不存在就建;已存在直接覆盖(这里只是导出,不做"防覆盖"的确认)。
211
+ * @returns {{path:string, format:'csv'|'json', bytes:number, rows:number}}
212
+ */
213
+ function writeOut(file, payload, rows) {
214
+ const target = path.resolve(String(file));
215
+ const lower = target.toLowerCase();
216
+ const format = lower.endsWith('.csv') ? 'csv' : lower.endsWith('.json') ? 'json' : '';
217
+ if (!format) throw new UsageError(`--out 只支持 .csv / .json(按扩展名决定格式),收到:${file}`);
218
+ fs.mkdirSync(path.dirname(target), { recursive: true });
219
+ const text = format === 'csv' ? toCsv(rows) : `${JSON.stringify(payload, null, 2)}\n`;
220
+ fs.writeFileSync(target, text, 'utf8');
221
+ return { path: target, format, bytes: Buffer.byteLength(text, 'utf8'), rows: rows.length };
222
+ }
223
+
224
+ /** 脱敏:默认把正文 / IP 里的 PII 抹掉;`--raw` 才原样(红线:默认不导出未脱敏 PII) */
225
+ function scrub(text, raw) {
226
+ const s = text === null || text === undefined ? '' : String(text);
227
+ return raw ? s : maskPii(s);
228
+ }
229
+
230
+ /* ══════════════════════════════ data chat ══════════════════════════════ */
231
+
232
+ /** 客服渠道(MaxKB `chat_user_type`)→ 人话 */
233
+ const CHANNEL_LABEL = {
234
+ ANONYMOUS_USER: '匿名访客',
235
+ PLATFORM_USER: '平台用户',
236
+ SYSTEM_USER: '系统',
237
+ };
238
+
239
+ export const dataChatCommand = {
240
+ name: 'data chat',
241
+ summary: 'AI 客服会话与消息(只读;按日期/渠道筛,单会话分页;正文默认脱敏)',
242
+ usage:
243
+ 'wkgeo data chat [--site <ID|域名>] [--from YYYY-MM-DD] [--to YYYY-MM-DD] [--channel <渠道>] [--chat <会话ID>] [--page N] [--limit N] [--raw] [--out <file.csv|file.json>] [--json]',
244
+ args: [],
245
+ flags: {
246
+ ...SITE_FLAG,
247
+ from: { type: 'string', desc: '起始日(含),YYYY-MM-DD;不写 = 不限(全部历史)' },
248
+ to: { type: 'string', desc: '结束日(含),YYYY-MM-DD;不写 = 不限' },
249
+ channel: { type: 'string', desc: '渠道 = MaxKB 的会话用户类型:ANONYMOUS_USER / PLATFORM_USER / SYSTEM_USER(不写 = 全部)' },
250
+ chat: { type: 'string', desc: '只取这个会话的消息(会话 ID 见不带 --chat 时的列表);分页按消息条数' },
251
+ page: { type: 'number', desc: '页码,从 1 开始(默认 1)' },
252
+ limit: { type: 'number', desc: '每页条数 1–200(默认 20)' },
253
+ raw: { type: 'boolean', desc: '正文原样输出(默认按 maskPii 脱敏手机号 / 邮箱 / IP;**导出请勿加**)' },
254
+ out: { type: 'string', desc: '导出到文件:.csv(扁平表)/ .json(完整结构);落盘内容与终端一致(默认脱敏)' },
255
+ },
256
+ examples: [
257
+ 'wkgeo data chat',
258
+ 'wkgeo data chat --from 2026-11-01 --to 2026-11-10 --channel ANONYMOUS_USER',
259
+ 'wkgeo data chat --chat <会话ID> --limit 50',
260
+ 'wkgeo data chat --out chat.csv',
261
+ ],
262
+ notes: [
263
+ '数据源:AI 客服后端 MaxKB 的只读库(`application_chat` / `application_chat_record`),服务端按本站 `application_id` 强制过滤。',
264
+ '渠道 = `chat_user_type`(MaxKB 的访客身份类型);`--channel` 传原文(不区分大小写由服务端归一)。',
265
+ '正文(问/答)默认脱敏;`--raw` 才原样 —— 红线:**不要把未脱敏 PII 导进仓库**。',
266
+ '`ip` 只给**掩码样例**(`203.0.113.*`),不提供完整 IP(平台侧也不存明文)。',
267
+ '单会话消息按 `index` 升序(对话顺序);会话列表按开始时间倒序。',
268
+ '需要 `site:read` + 站点成员/归属;站点没开通 AI 客服会明确报 `NOT_PROVISIONED`。',
269
+ ],
270
+ async run(ctx) {
271
+ const { out } = ctx;
272
+ const siteId = await resolveSiteId(ctx);
273
+ const page = Number.isFinite(ctx.flags.page) && ctx.flags.page > 0 ? Math.floor(ctx.flags.page) : 1;
274
+ const limit = Number.isFinite(ctx.flags.limit) && ctx.flags.limit > 0 ? Math.min(Math.floor(ctx.flags.limit), 200) : 20;
275
+ const chatId = String(ctx.flags.chat || '').trim();
276
+ /** 渠道原文(服务端按 `upper(chat_user_type)` 比对,大小写不敏感) */
277
+ const channel = String(ctx.flags.channel || '').trim();
278
+ const raw = ctx.flags.raw === true;
279
+ const range = chatId ? { from: '', to: '' } : rangeOf(ctx, { defaultDays: 0 });
280
+
281
+ const body = {
282
+ mode: chatId ? 'messages' : 'chats',
283
+ page,
284
+ page_size: limit,
285
+ /* 站点两处都给:header 是服务端 CLI 通道的权威来源,body 里的同名值只用于审计/排查对齐 */
286
+ siteId,
287
+ };
288
+ if (chatId) body.chat_id = chatId;
289
+ if (range.from) body.from = range.from;
290
+ if (range.to) body.to = range.to;
291
+ if (channel) body.channel = channel;
292
+
293
+ const data =
294
+ (await ctx.callData('aikefuSessions', body, {
295
+ prefix: 'aikefu',
296
+ headers: { Origin: PLATFORM_WEB_ORIGIN, 'x-cms-site': siteId },
297
+ })) || {};
298
+
299
+ const rows = (Array.isArray(data.list) ? data.list : []).map((one) =>
300
+ chatId
301
+ ? {
302
+ record_id: String(one.record_id || ''),
303
+ chat_id: String(one.chat_id || ''),
304
+ index: Number(one.index) || 0,
305
+ question: scrub(one.problem_text, raw),
306
+ answer: scrub(one.answer_text, raw),
307
+ message_tokens: Number(one.message_tokens) || 0,
308
+ answer_tokens: Number(one.answer_tokens) || 0,
309
+ run_time_ms: Math.round((Number(one.run_time) || 0) * 1000),
310
+ vote: String(one.vote_status || ''),
311
+ created_at: beijingTime(one.created_at),
312
+ }
313
+ : {
314
+ chat_id: String(one.chat_id || ''),
315
+ channel: String(one.chat_user_type || ''),
316
+ record_count: Number(one.chat_record_count) || 0,
317
+ ip: scrub(one.ip_address, raw),
318
+ started_at: beijingTime(one.started_at),
319
+ last_at: beijingTime(one.last_at),
320
+ },
321
+ );
322
+
323
+ const payload = {
324
+ site_id: siteId,
325
+ view: chatId ? 'messages' : 'sessions',
326
+ chat_id: chatId || null,
327
+ from: range.from || null,
328
+ to: range.to || null,
329
+ channel: channel || null,
330
+ page: Number(data.page) || page,
331
+ page_size: Number(data.page_size) || limit,
332
+ total: Number(data.total) || rows.length,
333
+ channels: Array.isArray(data.channels) ? data.channels : [],
334
+ rows,
335
+ };
336
+ if (ctx.flags.out) payload.out = writeOut(ctx.flags.out, payload, rows);
337
+
338
+ if (!out.json) {
339
+ out.head(`AI 客服${chatId ? `会话 ${chatId} 的消息` : '会话'}(站点 ${siteId})`);
340
+ if (!rows.length) {
341
+ out.line(' (这一页没有数据)');
342
+ } else if (chatId) {
343
+ out.table(
344
+ [
345
+ { title: '时间', key: 'created_at', width: 19 },
346
+ { title: '#', key: 'index', width: 4 },
347
+ { title: '提问', key: 'question', width: 34 },
348
+ { title: '回答', key: 'answer', width: 34 },
349
+ { title: 'tok(in/out)', key: 'tokens', width: 12 },
350
+ ],
351
+ rows.map((one) => ({ ...one, tokens: `${one.message_tokens}/${one.answer_tokens}` })),
352
+ );
353
+ } else {
354
+ out.table(
355
+ [
356
+ { title: '开始时间', key: 'started_at', width: 19 },
357
+ { title: '渠道', key: 'channel', width: 14 },
358
+ { title: '消息数', key: 'record_count', width: 6 },
359
+ { title: 'IP(掩码)', key: 'ip', width: 15 },
360
+ { title: '会话 ID', key: 'chat_id', width: 36 },
361
+ ],
362
+ rows.map((one) => ({ ...one, channel: CHANNEL_LABEL[one.channel] || one.channel || '-' })),
363
+ );
364
+ if (!channel && payload.channels.length) {
365
+ out.line(` 渠道分布:${payload.channels.map((c) => `${c.channel || '未知'} ${c.sessions}`).join(' · ')}`);
366
+ }
367
+ }
368
+ out.line(` 第 ${payload.page} 页 · 每页 ${payload.page_size} 条 · 合计 ${payload.total} 条`);
369
+ if (payload.total > payload.page * payload.page_size) {
370
+ out.info(`看下一页:\`wkgeo data chat${chatId ? ` --chat ${chatId}` : ''} --page ${payload.page + 1}\``);
371
+ }
372
+ if (payload.out) out.info(`已导出:${payload.out.path}(${payload.out.format},${payload.out.rows} 行)`);
373
+ if (!raw) out.info('正文已脱敏(--raw 取原文;导出请保持脱敏)');
374
+ }
375
+ ctx.done(payload);
376
+ return payload;
377
+ },
378
+ };
379
+
380
+ /* ══════════════════════════════ data stats ══════════════════════════════ */
381
+
382
+ export const dataStatsCommand = {
383
+ name: 'data stats',
384
+ summary: '访问统计(按日 PV / UV / IP 唯一数 + Top 页面 / 来源;只读)',
385
+ usage:
386
+ 'wkgeo data stats [--site <ID|域名>] [--from YYYY-MM-DD] [--to YYYY-MM-DD] [--top N] [--out <file.csv|file.json>] [--json]',
387
+ args: [],
388
+ flags: {
389
+ ...SITE_FLAG,
390
+ from: { type: 'string', desc: '起始日(含),YYYY-MM-DD;默认 = 最近 7 天(含今天)' },
391
+ to: { type: 'string', desc: '结束日(含),YYYY-MM-DD;默认 = 今天(北京时间)' },
392
+ top: { type: 'number', desc: 'Top 页面 / 来源各取多少条,1–50(默认 10)' },
393
+ out: { type: 'string', desc: '导出到文件:.csv(按日明细)/ .json(完整结构,含 Top 榜单)' },
394
+ },
395
+ examples: [
396
+ 'wkgeo data stats',
397
+ 'wkgeo data stats --from 2026-11-01 --to 2026-11-10',
398
+ 'wkgeo data stats --top 20 --out stats.json',
399
+ ],
400
+ notes: [
401
+ '数据源:`plug_analytics_event`(服务端按本站 `site_id` + 北京自然日 `stat_date` 聚合)。',
402
+ 'PV = `kind=\'page\'` 条数;UV = `ip_hash × device` 去重(近似访客);IP = `ip_hash` 去重(恒 ≤ UV);机器人不进 PV/UV/IP,单列 `bots`。',
403
+ '**不提供 IP 清单**:平台只存不可逆哈希(`ip_hash`),不保存明文 IP —— 这是隐私口径,不是缺口。',
404
+ '区间的 `totals` 是**整段去重**(UV/IP 不会按日相加),`days[]` 是逐日数字(逐日去重,跨日不合并)。',
405
+ '需要 `site:read` + 站点成员/归属;站点没装/没启用访问统计插件会被服务端明确拒绝。',
406
+ ],
407
+ async run(ctx) {
408
+ const { out } = ctx;
409
+ const siteId = await resolveSiteId(ctx);
410
+ const range = rangeOf(ctx, { defaultDays: 7 });
411
+ const top = Number.isFinite(ctx.flags.top) && ctx.flags.top > 0 ? Math.min(Math.floor(ctx.flags.top), 50) : 10;
412
+
413
+ const data =
414
+ (await ctx.callData(
415
+ 'statRange',
416
+ { from: range.from, to: range.to, limit: top, siteId },
417
+ { prefix: 'analytics', headers: { Origin: PLATFORM_WEB_ORIGIN, 'x-cms-site': siteId } },
418
+ )) || {};
419
+
420
+ const total = data.totals || {};
421
+ const days = (Array.isArray(data.list) ? data.list : []).map((one) => ({
422
+ day: String(one.day || ''),
423
+ pv: Number(one.pv) || 0,
424
+ uv: Number(one.uv) || 0,
425
+ unique_ips: Number(one.unique_ips) || 0,
426
+ visits: Number(one.visits) || 0,
427
+ bots: Number(one.bots) || 0,
428
+ }));
429
+ const topPages = (Array.isArray(data.top_pages) ? data.top_pages : []).map((one) => ({
430
+ path: String(one.path || '/'),
431
+ pv: Number(one.pv) || 0,
432
+ uv: Number(one.uv) || 0,
433
+ unique_ips: Number(one.unique_ips) || 0,
434
+ last_at: beijingTime(one.last_at),
435
+ }));
436
+ const topReferrers = (Array.isArray(data.top_referrers) ? data.top_referrers : []).map((one) => ({
437
+ domain: String(one.domain || ''),
438
+ hits: Number(one.hits) || 0,
439
+ uv: Number(one.uv) || 0,
440
+ }));
441
+
442
+ const payload = {
443
+ site_id: siteId,
444
+ from: String(data.from || range.from),
445
+ to: String(data.to || range.to),
446
+ timezone: String(data.timezone || 'Asia/Shanghai'),
447
+ totals: {
448
+ pv: Number(total.pv) || 0,
449
+ uv: Number(total.uv) || 0,
450
+ unique_ips: Number(total.unique_ips) || 0,
451
+ visits: Number(total.visits) || 0,
452
+ bots: Number(total.bots) || 0,
453
+ },
454
+ days,
455
+ top_pages: topPages,
456
+ top_referrers: topReferrers,
457
+ notes: Array.isArray(data.notes) ? data.notes : [],
458
+ };
459
+ if (ctx.flags.out) payload.out = writeOut(ctx.flags.out, payload, days);
460
+
461
+ if (!out.json) {
462
+ out.head(`访问统计(站点 ${siteId} · ${payload.from} → ${payload.to})`);
463
+ out.table(
464
+ [
465
+ { title: '指标', key: 'label', width: 10 },
466
+ { title: '区间合计', key: 'value', width: 12 },
467
+ { title: '说明', key: 'note', width: 40 },
468
+ ],
469
+ [
470
+ { label: 'PV', value: String(payload.totals.pv), note: '页面浏览条数(排除机器人)' },
471
+ { label: 'UV', value: String(payload.totals.uv), note: 'ip_hash × 设备 去重(近似访客)' },
472
+ { label: 'IP 唯一', value: String(payload.totals.unique_ips), note: '只给数量,平台不存明文 IP' },
473
+ { label: '访问次数', value: String(payload.totals.visits), note: "kind='visit' 会话条数" },
474
+ { label: '机器人', value: String(payload.totals.bots), note: '单列审计,不计入上面四项' },
475
+ ],
476
+ );
477
+ out.head('按日');
478
+ out.table(
479
+ [
480
+ { title: '日期', key: 'day', width: 10 },
481
+ { title: 'PV', key: 'pv', width: 8 },
482
+ { title: 'UV', key: 'uv', width: 8 },
483
+ { title: 'IP', key: 'unique_ips', width: 8 },
484
+ { title: '访问', key: 'visits', width: 8 },
485
+ { title: '机器人', key: 'bots', width: 8 },
486
+ ],
487
+ days,
488
+ );
489
+ out.head('Top 页面');
490
+ out.table(
491
+ [
492
+ { title: '路径', key: 'path', width: 42 },
493
+ { title: 'PV', key: 'pv', width: 8 },
494
+ { title: 'UV', key: 'uv', width: 8 },
495
+ { title: 'IP', key: 'unique_ips', width: 8 },
496
+ { title: '最近访问', key: 'last_at', width: 19 },
497
+ ],
498
+ topPages,
499
+ );
500
+ out.head('Top 来源');
501
+ out.table(
502
+ [
503
+ { title: '来源域名', key: 'domain', width: 34 },
504
+ { title: '次数', key: 'hits', width: 8 },
505
+ { title: 'UV', key: 'uv', width: 8 },
506
+ ],
507
+ topReferrers,
508
+ );
509
+ if (payload.out) out.info(`已导出:${payload.out.path}(${payload.out.format},${payload.out.rows} 行)`);
510
+ }
511
+ ctx.done(payload);
512
+ return payload;
513
+ },
514
+ };
515
+
516
+ /* ══════════════════════════════ data usage ══════════════════════════════ */
517
+
518
+ export const dataUsageCommand = {
519
+ name: 'data usage',
520
+ summary: '大模型消耗(按日 / 模型 / 站点:请求数、token、费用;只读)',
521
+ usage:
522
+ 'wkgeo data usage [--site <ID|域名>] [--from YYYY-MM-DD] [--to YYYY-MM-DD] [--model <模型>] [--out <file.csv|file.json>] [--json]',
523
+ args: [],
524
+ flags: {
525
+ ...SITE_FLAG,
526
+ from: { type: 'string', desc: '起始日(含),YYYY-MM-DD;默认 = 最近 7 天(含今天)' },
527
+ to: { type: 'string', desc: '结束日(含),YYYY-MM-DD;默认 = 今天(北京时间)' },
528
+ model: { type: 'string', desc: '只看某个模型(如 deepseek-flash);不写 = 全部' },
529
+ out: { type: 'string', desc: '导出到文件:.csv(按日明细)/ .json(完整结构,含按模型/站点/用途)' },
530
+ },
531
+ examples: [
532
+ 'wkgeo data usage',
533
+ 'wkgeo data usage --from 2026-11-01 --to 2026-11-10',
534
+ 'wkgeo data usage --model deepseek-flash --out usage.csv',
535
+ ],
536
+ notes: [
537
+ '数据源:`llm_usage` UNION ALL `llm_tool_usage`(超管 `llmCostSummary`,本次只读;按站点 / 模型 / 日 / 用途 / 计量单位聚合)。',
538
+ '金额三份同源:`cost_yuan`(元,展示)/ `cost_cents`(分,兼容)/ `cost_micros` 由服务端给出;CLI 只展示 `cost_yuan`。',
539
+ '**令牌 scope 必须含 `llm:cost_read`**(默认登录 scope 不含)。缺了会明确报错并给出重授权命令,不会静默返回空表。',
540
+ '`--from/--to` 按北京自然日;`--to` 在服务端是左闭右开,CLI 已自动换算成「含当天」。',
541
+ '数据范围随身份:平台管理员看全量;普通账号只看自己名下站点(服务端 `own_sites` 收窄)。',
542
+ ],
543
+ async run(ctx) {
544
+ const { out } = ctx;
545
+ const siteId = await resolveSiteId(ctx);
546
+ const range = rangeOf(ctx, { defaultDays: 7 });
547
+ const model = String(ctx.flags.model || '').trim();
548
+
549
+ const body = {
550
+ days: 7,
551
+ from: dayStartIso(range.from),
552
+ to: dayNextIso(range.to),
553
+ siteId,
554
+ };
555
+ if (model) body.model = model;
556
+
557
+ let data;
558
+ try {
559
+ data = await ctx.callData('llmCostSummary', body, {
560
+ prefix: 'admin',
561
+ headers: { Origin: PLATFORM_WEB_ORIGIN },
562
+ });
563
+ } catch (e) {
564
+ /**
565
+ * `llm:cost_read` 是「AI 费用只读位」,**默认登录 scope 不含**。
566
+ * 这里换成能照做的提示(而不是通用的"令牌能力不足")。
567
+ */
568
+ const msg = String((e && e.message) || e);
569
+ if (/llm:cost_read|令牌范围/.test(msg)) {
570
+ throw new CliError('当前令牌没有「AI 费用」只读权限(缺 scope `llm:cost_read`)', {
571
+ kind: 'forbidden',
572
+ code: 403,
573
+ exitCode: EXIT.AUTH,
574
+ hint:
575
+ '重新授权并带上该 scope:\n' +
576
+ ' wkgeo login --scope "site:read site:write attachment:read attachment:write template:read template:write billing:self llm:cost_read"\n' +
577
+ '(旧令牌不会自动获得新能力;重授权后再跑本命令)',
578
+ details: { missing_scope: 'llm:cost_read' },
579
+ });
580
+ }
581
+ throw e;
582
+ }
583
+
584
+ data = data || {};
585
+ const total = data.total || {};
586
+ const byDay = (Array.isArray(data.by_day) ? data.by_day : []).map((one) => ({
587
+ day: String(one.day || ''),
588
+ calls: Number(one.calls) || 0,
589
+ total_tokens: Number(one.total_tokens) || 0,
590
+ cost_yuan: Number(one.cost_yuan) || 0,
591
+ }));
592
+ const byModel = (Array.isArray(data.by_model) ? data.by_model : []).map((one) => ({
593
+ model: String(one.model || ''),
594
+ calls: Number(one.calls) || 0,
595
+ total_tokens: Number(one.total_tokens) || 0,
596
+ cost_yuan: Number(one.cost_yuan) || 0,
597
+ }));
598
+ const bySite = (Array.isArray(data.by_site) ? data.by_site : []).map((one) => ({
599
+ site_id: String(one.site_id || ''),
600
+ site_name: String(one.site_name || ''),
601
+ calls: Number(one.calls) || 0,
602
+ total_tokens: Number(one.total_tokens) || 0,
603
+ cost_yuan: Number(one.cost_yuan) || 0,
604
+ }));
605
+ const byAction = (Array.isArray(data.by_action) ? data.by_action : []).map((one) => ({
606
+ biz_action: String(one.biz_action || ''),
607
+ calls: Number(one.calls) || 0,
608
+ total_tokens: Number(one.total_tokens) || 0,
609
+ cost_yuan: Number(one.cost_yuan) || 0,
610
+ }));
611
+
612
+ const payload = {
613
+ site_id: siteId,
614
+ from: range.from,
615
+ to: range.to,
616
+ days: Number(data.days) || 7,
617
+ model: model || null,
618
+ currency: 'CNY',
619
+ total: {
620
+ calls: Number(total.calls) || 0,
621
+ errors: Number(total.errors) || 0,
622
+ prompt_tokens: Number(total.prompt_tokens) || 0,
623
+ completion_tokens: Number(total.completion_tokens) || 0,
624
+ total_tokens: Number(total.total_tokens) || 0,
625
+ cached_tokens: Number(total.cached_tokens) || 0,
626
+ cost_yuan: Number(total.cost_yuan) || 0,
627
+ cost_cents: Number(total.cost_cents) || 0,
628
+ },
629
+ by_day: byDay,
630
+ by_model: byModel,
631
+ by_site: bySite,
632
+ by_action: byAction,
633
+ };
634
+ if (ctx.flags.out) payload.out = writeOut(ctx.flags.out, payload, byDay);
635
+
636
+ if (!out.json) {
637
+ out.head(`大模型消耗(站点 ${siteId}${model ? ` · ${model}` : ''} · ${payload.from} → ${payload.to})`);
638
+ out.table(
639
+ [
640
+ { title: '指标', key: 'label', width: 12 },
641
+ { title: '数值', key: 'value', width: 16 },
642
+ { title: '说明', key: 'note', width: 36 },
643
+ ],
644
+ [
645
+ { label: '请求数', value: String(payload.total.calls), note: `其中失败 ${payload.total.errors}` },
646
+ {
647
+ label: 'Token',
648
+ value: String(payload.total.total_tokens),
649
+ note: `输入 ${payload.total.prompt_tokens} / 输出 ${payload.total.completion_tokens} / 缓存命中 ${payload.total.cached_tokens}`,
650
+ },
651
+ { label: '费用', value: formatMoney(payload.total.cost_cents), note: '服务端 cost_cents(分)同源' },
652
+ ],
653
+ );
654
+ out.head('按日');
655
+ out.table(
656
+ [
657
+ { title: '日期', key: 'day', width: 10 },
658
+ { title: '请求', key: 'calls', width: 8 },
659
+ { title: 'Token', key: 'total_tokens', width: 12 },
660
+ { title: '费用', key: 'money', width: 10 },
661
+ ],
662
+ byDay.map((one) => ({ ...one, money: formatMoney(Math.round(one.cost_yuan * 100)) })),
663
+ );
664
+ out.head('按模型');
665
+ out.table(
666
+ [
667
+ { title: '模型', key: 'model', width: 24 },
668
+ { title: '请求', key: 'calls', width: 8 },
669
+ { title: 'Token', key: 'total_tokens', width: 12 },
670
+ { title: '费用', key: 'money', width: 10 },
671
+ ],
672
+ byModel.map((one) => ({ ...one, money: formatMoney(Math.round(one.cost_yuan * 100)) })),
673
+ );
674
+ if (bySite.length > 1) {
675
+ out.head('按站点');
676
+ out.table(
677
+ [
678
+ { title: '站点', key: 'site_name', width: 24 },
679
+ { title: '请求', key: 'calls', width: 8 },
680
+ { title: 'Token', key: 'total_tokens', width: 12 },
681
+ { title: '费用', key: 'money', width: 10 },
682
+ ],
683
+ bySite.map((one) => ({ ...one, money: formatMoney(Math.round(one.cost_yuan * 100)) })),
684
+ );
685
+ }
686
+ if (payload.out) out.info(`已导出:${payload.out.path}(${payload.out.format},${payload.out.rows} 行)`);
687
+ }
688
+ ctx.done(payload);
689
+ return payload;
690
+ },
691
+ };
692
+
693
+ /** 注册表(顺序 = 帮助里的顺序) */
694
+ export const DATA_COMMANDS = [dataChatCommand, dataStatsCommand, dataUsageCommand];