@wkgeo/cli 1.1.3 → 1.1.4

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/CHANGELOG.md CHANGED
@@ -4,6 +4,28 @@
4
4
 
5
5
  ---
6
6
 
7
+ ## 未发布 · 2026-11-10
8
+
9
+ **新增 `data` 命令组(数据交换,全部只读)**:`wkgeo data chat|stats|usage`。
10
+
11
+ - `data chat`:AI 客服会话 / 单会话消息(`/aikefu`,读 MaxKB 只读库);`--from/--to`(北京自然日)、
12
+ `--channel`(MaxKB `chat_user_type`)、`--chat <会话ID>`(消息分页)、`--page/--limit`;
13
+ 问答正文默认 `maskPii` 脱敏、IP 只给掩码(`--raw` 才原文;`--out` 落盘跟随当前模式)。
14
+ - `data stats`:按日 PV / UV / IP 唯一数 + Top 页面 / 来源(`/analytics` 新增只读动作 `statRange`,
15
+ 支持任意日期区间 ≤366 天;`totals` 整段去重、`days[]` 逐日去重)。
16
+ - `data usage`:按日 / 模型 / 站点的大模型请求数、token、费用(`/admin` 的 `llmCostSummary`);
17
+ **令牌 scope 需含 `llm:cost_read`**,缺了 exit 3 并打印精确重授权命令。
18
+ - 统一:`--site <ID|域名>`(域名/短域/站名在本地用 `listSites` 换 ID,`www.` 互认)、`--from/--to`、
19
+ `--json|--text`、`--out <file.csv|file.json>`(CSV 带 UTF-8 BOM)。
20
+ - `/analytics` `/aikefu` 补 **CLI Bearer 只读通道**(只放行 `access:'read'`,写动作进 handler 前 403;
21
+ Cookie 通道行为不变);`/admin` 作为只读前缀登记(不改既有路由)。
22
+
23
+ **修复线上 P1**:`wkgeo-cli-fc` 是网关签名目标,`Authorization` 会被 ACS3 覆盖,而它以前只读
24
+ `authorization` 头 ⇒ 所有 `/cli` 动作 401(`wkgeo sites list` 都跑不了)。改走共享件
25
+ `_shared/client-authorization.js` 的 ACS3-gated 还原后恢复。
26
+
27
+ ---
28
+
7
29
  ## 1.1.3 · 2026-11-09
8
30
 
9
31
  **`wkgeo publish` 拦「站点没有自有域名」**(2026-11-09,与 CMS 后台发布按钮同口径):站点唯一地址是平台
package/README.md CHANGED
@@ -798,6 +798,67 @@ wkgeo overview dashboard # 数据看板快照(存储 / 流量
798
798
 
799
799
  > AI 类命令(`aiLogList` 等 7 条)后台功能还没做完(老板 2026-10-29),本批**没有**迁、CLI 也**不提供**对应子命令 —— 别在脚本里当它存在。
800
800
 
801
+ ### 数据交换命令(`data chat|stats|usage`,2026-11-10 老板单)
802
+
803
+ 老板要的「数据交换」第一块:**本地 CLI 能拿到三类只读数据**,默认表格、`--json` 给稳定结构、
804
+ `--out` 落 CSV / JSON 给下游交换。三条命令全部**只读**,没有任何 `--confirm` 写动作。
805
+
806
+ ```bash
807
+ # ① AI 客服会话 / 消息(数据在 MaxKB,服务端按本站 application_id 强制过滤)
808
+ wkgeo data chat # 会话列表(最新在前;默认不限日期)
809
+ wkgeo data chat --from 2026-11-01 --to 2026-11-10 # 按日期筛(北京自然日,闭区间)
810
+ wkgeo data chat --channel ANONYMOUS_USER # 按渠道筛(MaxKB chat_user_type)
811
+ wkgeo data chat --chat <会话ID> --limit 50 # 单会话消息(按对话顺序;分页)
812
+ wkgeo data chat --out chat.csv # 落 CSV(正文仍是脱敏后的)
813
+
814
+ # ② 访问统计(按日 PV / UV / IP 唯一数 + Top 页面 / 来源)
815
+ wkgeo data stats # 默认最近 7 天(含今天)
816
+ wkgeo data stats --from 2026-11-01 --to 2026-11-10 --top 20
817
+ wkgeo data stats --out stats.json # 完整结构(含 days / top_pages / top_referrers)
818
+
819
+ # ③ 大模型消耗(按日 / 模型 / 站点:请求数、token、费用)
820
+ wkgeo data usage # 默认最近 7 天
821
+ wkgeo data usage --model deepseek-flash --from 2026-11-01 --to 2026-11-10
822
+ wkgeo data usage --out usage.csv # CSV 落「按日」明细
823
+ ```
824
+
825
+ **统一参数**:`--site <ID|域名>`(域名/短域/站名会在本地用 `listSites` 换成 ID)、
826
+ `--from` / `--to`(`YYYY-MM-DD`,北京自然日,闭区间;`stats` / `usage` 默认最近 7 天,`chat` 默认不限)、
827
+ `--page` / `--limit`(只有 `chat` 分页)、`--json` / `--text`、`--out <file.csv|file.json>`。
828
+
829
+ **输出字段(`--json` 的 `data`,下游交换按这些键取值)**:
830
+
831
+ | 命令 | 顶层字段 | 行字段 |
832
+ |---|---|---|
833
+ | `data chat`(会话) | `site_id` `view:"sessions"` `from` `to` `channel` `page` `page_size` `total` `channels[]` `rows[]` | `chat_id` `channel` `record_count` `ip`(掩码)`started_at` `last_at` |
834
+ | `data chat --chat`(消息) | `site_id` `view:"messages"` `chat_id` `page` `page_size` `total` `rows[]` | `record_id` `chat_id` `index` `question` `answer` `message_tokens` `answer_tokens` `run_time_ms` `vote` `created_at` |
835
+ | `data stats` | `site_id` `from` `to` `timezone` `totals{pv,uv,unique_ips,visits,bots}` `days[]` `top_pages[]` `top_referrers[]` | 日:`day pv uv unique_ips visits bots`;页:`path pv uv unique_ips last_at`;来源:`domain hits uv` |
836
+ | `data usage` | `site_id` `from` `to` `days` `model` `currency:"CNY"` `total{calls,errors,prompt_tokens,completion_tokens,total_tokens,cached_tokens,cost_yuan,cost_cents}` `by_day[]` `by_model[]` `by_site[]` `by_action[]` | `day`/`model`/`site_id`+`site_name`/`biz_action`、`calls`、`total_tokens`、`cost_yuan` |
837
+
838
+ **六条口径(踩过就知道为什么写在这里)**:
839
+
840
+ 1. **正文默认脱敏**:`data chat` 的 `question` / `answer` 走 `maskPii`(手机号留 3+4、邮箱打码、IP 留前三段);
841
+ `--raw` 才原样。`--out` 落盘**同样按当前模式**脱敏 —— 红线是「不导出未脱敏 PII 到仓库」,默认就是安全的。
842
+ 2. **不提供 IP 清单**:访问统计只存不可逆 `ip_hash`(`unique_ips` 是数量),客服会话的 `ip` 只给掩码样例。
843
+ 这是隐私口径(`docs/功能-访问统计-埋点注入.md` §7),不是缺口。
844
+ 3. **区间合计 ≠ 按日相加**:`stats.totals` 是整段去重(一次 `count(distinct)`),`days[]` 是逐日去重;
845
+ 跨日把 UV/IP 相加会把人算重,所以两个口径分开给。
846
+ 4. **`data usage` 需要 scope `llm:cost_read`**(默认登录 scope 不含)。缺了会 exit 3 并打印精确的重授权命令:
847
+ ```bash
848
+ wkgeo login --scope "site:read site:write attachment:read attachment:write template:read template:write billing:self llm:cost_read"
849
+ ```
850
+ 旧令牌不会自动获得新能力;重授权后再跑即可。数据源是超管 `llmCostSummary`(`llm_usage` UNION `llm_tool_usage`),
851
+ 数据范围随身份:平台管理员看全量,普通账号只看自己名下站点。
852
+ 5. **站点身份走 CLI Bearer 只读通道**:`/analytics` / `/aikefu` 以前只认 CMS Cookie;2026-11-10 起补了
853
+ **只读** Bearer 通道(无 Cookie + 有 Bearer ⇒ 只放行 `access:'read'`,站点从 `x-cms-site` 取并复核成员关系;
854
+ 写动作在进 handler 前就 403)。浏览器 Cookie 通道行为不变。
855
+ 6. **`--site` 传域名**是本地解析(`listSites` 里按 domain / custom_domain / 短域 / 站名匹配,`www.` 互认);
856
+ 解析不到直接 exit 2 并让你改用站点 ID,**不会**把域名当 ID 丢给服务端(那只会换来一个无意义的 400)。
857
+
858
+ > 顺带修掉一个线上 P1:`wkgeo-cli-fc` 是网关签名目标,`Authorization` 会被 ACS3 覆盖,
859
+ > 而它以前只读 `authorization` 头 ⇒ **所有 `/cli` 动作 401**(`wkgeo sites list` 都跑不了)。
860
+ > 2026-11-10 起改走共享件 `_shared/client-authorization.js` 的 ACS3-gated 还原,`/cli` 恢复正常。
861
+
801
862
  ### 「钱包余额支付」到底发生在哪一步(**别被命令名骗了**)
802
863
 
803
864
  服务端 `placeOrder()` 的行为是:**下单时就先用余额抵扣**,余额够就立刻 `moveWallet(-金额)` +
@@ -1040,7 +1101,7 @@ cli/
1040
1101
  ├── scripts/
1041
1102
  │ ├── e2e-site.mjs 建站全链路端到端(建站→短域→可选绑域→发布→首页 200+指纹;**默认不删站**,真跑要 --confirm)
1042
1103
  │ ├── live-verify.mjs 真环境**可逆**端到端验证(--write 才做写操作)
1043
- │ ├── live-sql.mjs 只读 SQL 排查工具(写语句直接拒绝)
1104
+ │ ├── live-sql.mjs 只读 SQL 排查工具(写语句直接拒绝;**默认真库 RDS**,旧网关要 --channel=legacy --legacy-ok)
1044
1105
  │ ├── build-zip.mjs 打 zip(自实现 ZIP 写入,零依赖)
1045
1106
  │ └── build-exe.mjs 独立可执行方案(默认只打印,`--sea` 跑离线两步)
1046
1107
  └── docs/设备码授权-服务端最小方案.md
@@ -1055,7 +1116,7 @@ node scripts/e2e-site.mjs --confirm --pool global --keep # 真建站(**留
1055
1116
  node scripts/build-zip.mjs # 打 zip(带安全闸门扫描)
1056
1117
  node scripts/live-verify.mjs # 真环境只读验证(需本机测试账号,见发布流程 §7)
1057
1118
  node scripts/live-verify.mjs --write # 追加可逆写操作(建站→下单→支付→退款→回收,零残留)
1058
- node scripts/live-sql.mjs --sql "select …" # 只读查库(只允许 SELECT)
1119
+ node scripts/live-sql.mjs --sql "select …" # 只读查库(只允许 SELECT;默认走真库 RDS)
1059
1120
  ```
1060
1121
 
1061
1122
  设备码这条路的**真环境**端到端验证在云函数测试目录(默认只读,实跑需显式开关):
package/SKILL.md CHANGED
@@ -243,6 +243,39 @@ wkgeo overview dashboard # 数据看板快照(存储/流量/费
243
243
  * 写命令**默认 dry-run**,`--confirm` 才发;`config review` 另需 `--review-token`(只走请求头,不打印)。
244
244
  * AI 类命令(`aiLogList` 等 7 条)**本批没迁**(后台功能未完成),别假设存在。
245
245
 
246
+ ### 4.0.5 数据交换命令(`data chat|stats|usage`,2026-11-10)
247
+
248
+ 三类**只读**运营数据的稳定导出(默认表格,`--json` 给下游,`--out` 落 CSV/JSON):
249
+
250
+ ```bash
251
+ wkgeo data chat # AI 客服会话(最新在前;正文默认脱敏、IP 只给掩码)
252
+ wkgeo data chat --from 2026-11-01 --to 2026-11-10 --channel ANONYMOUS_USER
253
+ wkgeo data chat --chat <会话ID> --limit 50 # 单会话消息(按对话顺序,分页)
254
+ wkgeo data chat --out chat.csv # 导出(仍是脱敏后的内容;--raw 才原文)
255
+
256
+ wkgeo data stats # 最近 7 天:按日 PV/UV/IP 唯一数 + Top 页面/来源
257
+ wkgeo data stats --from 2026-11-01 --to 2026-11-10 --top 20 --out stats.json
258
+
259
+ wkgeo data usage # 最近 7 天:按日/模型/站点 的请求数、token、费用
260
+ wkgeo data usage --model deepseek-flash --out usage.csv
261
+ ```
262
+
263
+ 稳定结构(`--json` 的 `data`):
264
+ - chat 会话:`site_id` `view:"sessions"` `from` `to` `channel` `page` `page_size` `total` `channels[]` `rows[]`
265
+ (行:`chat_id` `channel` `record_count` `ip` `started_at` `last_at`)
266
+ - chat 消息:`site_id` `view:"messages"` `chat_id` `page` `page_size` `total` `rows[]`
267
+ (行:`record_id` `chat_id` `index` `question` `answer` `message_tokens` `answer_tokens` `run_time_ms` `vote` `created_at`)
268
+ - stats:`site_id` `from` `to` `timezone` `totals{pv,uv,unique_ips,visits,bots}` `days[]` `top_pages[]` `top_referrers[]`
269
+ - usage:`site_id` `from` `to` `days` `model` `currency` `total{calls,errors,prompt_tokens,completion_tokens,total_tokens,cached_tokens,cost_yuan,cost_cents}` `by_day[]` `by_model[]` `by_site[]` `by_action[]`
270
+
271
+ 四条必读口径:
272
+ 1. `--site <ID|域名>`:域名/短域/站名在**本地**用 `listSites` 换 ID(`www.` 互认);换不到就 exit 2,不会把域名丢给服务端。
273
+ 2. `--from/--to` 是**北京自然日闭区间**;`stats`/`usage` 默认最近 7 天,`chat` 默认不限。
274
+ 3. `data usage` 要令牌 scope 含 **`llm:cost_read`**(默认不含);缺了 exit 3 并打印精确的 `wkgeo login --scope "… llm:cost_read"`。
275
+ 数据源 = 超管 `llmCostSummary`(`llm_usage` UNION `llm_tool_usage`),平台管理员看全量、普通账号只看自己名下站点。
276
+ 4. 隐私:`stats` 只给 IP **数量**(库里只有 `ip_hash`,无明文 IP);`chat` 正文默认 `maskPii` 脱敏、IP 只给掩码样例。
277
+ 红线是「不导出未脱敏 PII」⇒ 默认就安全,`--raw` 只用于本地排查,别把 `--raw --out` 的结果进仓库。
278
+
246
279
  ### 4.1 站点管理入口(`sites list`)
247
280
 
248
281
  `sites list` 是"先看清我在哪、再决定下一步"的命令(2026-10-22 起):
package/lib/api.mjs CHANGED
@@ -117,6 +117,20 @@ export const GATEWAY_PREFIXES = Object.freeze({
117
117
  member: 'wkgeo-plugin-member',
118
118
  channel: 'wkgeo-plugin-channel-code',
119
119
  'ai-tools': 'wkgeo-plugin-ai-tools',
120
+ /**
121
+ * ★ 2026-11-10(数据交换单):三个**只读**数据面,供 `wkgeo data chat|stats|usage` 用。
122
+ *
123
+ * · `aikefu` → `wkgeo-plugin-aikefu`(MaxKB 会话/消息,只读库)
124
+ * · `analytics` → `wkgeo-plugin-analytics`(PV / UV / IP 唯一数、Top 页面/来源)
125
+ * · `admin` → `wkgeo-admin`(大模型费用账单 `llmCostSummary`,只读位 `llm:cost_read`)
126
+ *
127
+ * 为什么现在才登记:这三个前缀网关早就有了(`wkgeo-gw` 的 `defaultRoutes`),
128
+ * 但 CLI 以前没有命令要打它们。**只登记前缀,不改任何现有动作的路由**:
129
+ * `fnOf()` 的默认仍是 `cli`,只有显式 `prefix:` 才会走这三条。
130
+ */
131
+ aikefu: 'wkgeo-plugin-aikefu',
132
+ analytics: 'wkgeo-plugin-analytics',
133
+ admin: 'wkgeo-admin',
120
134
  });
121
135
 
122
136
  /** 前缀是否合法(HTTP 层的唯一闸门:不认的前缀直接报用法错误,绝不瞎打) */
@@ -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];
@@ -241,10 +241,10 @@ export const domainOrderCommand = {
241
241
  /* ============================== 云解析(真写) ============================== */
242
242
 
243
243
  const DNS_FLAGS = {
244
- domain: { type: 'string', desc: '完整域名(服务端按最长后缀找 zone,如 cli-e2e.wkago.com ⇒ zone wkago.com)' },
244
+ domain: { type: 'string', desc: '完整域名(服务端按最长后缀找 zone,如 demo.example.com ⇒ zone example.com)' },
245
245
  type: { type: 'string', desc: '记录类型:A / AAAA / CNAME / TXT / MX / SRV / CAA' },
246
246
  value: { type: 'string', desc: '记录值(CNAME 填目标域名,TXT 填文本)' },
247
- rr: { type: 'string', desc: '主机记录(不填就从域名里推:cli-e2e.wkago.com ⇒ cli-e2e)' },
247
+ rr: { type: 'string', desc: '主机记录(不填就从域名里推:demo.example.com ⇒ demo)' },
248
248
  ttl: { type: 'string', desc: 'TTL 秒(600–86400,默认 600)' },
249
249
  'record-id': { type: 'string', desc: '记录 ID(update / delete 必填,来自 domain zone list)' },
250
250
  yes: { type: 'boolean', desc: '删除必须显式确认' },
@@ -255,7 +255,7 @@ export const domainZoneListCommand = {
255
255
  summary: '列账号里某个域名的真实解析记录(自持 alidns,不是"照抄表")',
256
256
  usage: 'wkgeo domain zone list --domain <域名> [--type <类型>] [--rr <主机记录>] [--json]',
257
257
  flags: { domain: DNS_FLAGS.domain, type: DNS_FLAGS.type, rr: DNS_FLAGS.rr },
258
- examples: ['wkgeo domain zone list --domain wkago.com', 'wkgeo domain zone list --domain cli-e2e.wkago.com --type CNAME'],
258
+ examples: ['wkgeo domain zone list --domain example.com', 'wkgeo domain zone list --domain demo.example.com --type CNAME'],
259
259
  notes: ['只想看"我还该加哪几条解析"?用 `wkgeo domain dns`(那张是给客户照抄的表)。'],
260
260
  async run(ctx) {
261
261
  const { out, flags } = ctx;
@@ -290,8 +290,8 @@ export const domainZoneAddCommand = {
290
290
  usage: 'wkgeo domain zone add --domain <域名> --type <类型> --value <值> [--rr <主机>] [--ttl <秒>] [--json]',
291
291
  flags: { domain: DNS_FLAGS.domain, type: DNS_FLAGS.type, value: DNS_FLAGS.value, rr: DNS_FLAGS.rr, ttl: DNS_FLAGS.ttl },
292
292
  examples: [
293
- 'wkgeo domain zone add --domain cli-e2e.wkago.com --type CNAME --value c-cli-e2e.intl.wkgeo.com.cn',
294
- 'wkgeo domain zone add --domain _verify.wkago.com --type TXT --value "verify=abc"',
293
+ 'wkgeo domain zone add --domain demo.example.com --type CNAME --value c-demo.intl.wkgeo.com.cn',
294
+ 'wkgeo domain zone add --domain _verify.example.com --type TXT --value "verify=abc"',
295
295
  ],
296
296
  notes: [
297
297
  '写完立刻回读:**回读值不符会报 502**(这时记录可能已经写进去了,先去 `domain zone list` 看一眼,别急着重加)。',
@@ -358,7 +358,7 @@ export const domainZoneDeleteCommand = {
358
358
  summary: '删一条解析(必须 --yes;重复删是幂等的)',
359
359
  usage: 'wkgeo domain zone delete --domain <域名> --record-id <记录ID> --yes',
360
360
  flags: { domain: DNS_FLAGS.domain, 'record-id': DNS_FLAGS['record-id'], yes: DNS_FLAGS.yes },
361
- examples: ['wkgeo domain zone delete --domain cli-e2e.wkago.com --record-id 8123456 --yes'],
361
+ examples: ['wkgeo domain zone delete --domain demo.example.com --record-id 8123456 --yes'],
362
362
  notes: ['删错一条解析 = 线上事故,所以这里强制 `--yes`。'],
363
363
  async run(ctx) {
364
364
  const { out, flags } = ctx;
@@ -382,7 +382,7 @@ export const domainZoneDeleteCommand = {
382
382
  const ESA_FLAGS = {
383
383
  pool: { type: 'string', desc: '池位:id / set_code / 站点名(如 intl-1、intl.wkgeo.com.cn)' },
384
384
  site: { type: 'string', desc: '站点 id(与 --pool 二选一)' },
385
- host: { type: 'string', desc: '要接的完整域名(如 cli-e2e.wkago.com)' },
385
+ host: { type: 'string', desc: '要接的完整域名(如 demo.example.com)' },
386
386
  endpoint: { type: 'string', desc: '回源桶端点(默认复用池行 origin 记录)' },
387
387
  'record-id': { type: 'string', desc: 'ESA 回源记录 id(不填按记录名自动查)' },
388
388
  'no-cert': { type: 'boolean', desc: '不申请免费证书(只接域名)' },
@@ -419,7 +419,7 @@ export const esaRecordCommand = {
419
419
  summary: '建/改 ESA 的 S3 回源记录(同值幂等;记录名必须是单标签子域)',
420
420
  usage: 'wkgeo esa record --pool <池位> --host <域名> [--endpoint <桶端点>]',
421
421
  flags: { pool: ESA_FLAGS.pool, site: ESA_FLAGS.site, host: ESA_FLAGS.host, endpoint: ESA_FLAGS.endpoint },
422
- examples: ['wkgeo esa record --pool intl-1 --host cli-e2e.wkago.com'],
422
+ examples: ['wkgeo esa record --pool intl-1 --host demo.example.com'],
423
423
  notes: [
424
424
  '记录名 = `c-<slug>.<池域>`(单标签,ESA 的硬要求);HostPolicy 必须是 follow_origin_domain。',
425
425
  '写后回读:源站类型 / Data / HostPolicy 任何一项不符都会报错。',
@@ -450,7 +450,7 @@ export const esaHostnameCommand = {
450
450
  summary: '接 CustomHostname + 申请免费证书(幂等;100 次/小时限流,别重试)',
451
451
  usage: 'wkgeo esa hostname --pool <池位> --host <域名> [--record-id <id>] [--no-cert]',
452
452
  flags: { pool: ESA_FLAGS.pool, site: ESA_FLAGS.site, host: ESA_FLAGS.host, 'record-id': ESA_FLAGS['record-id'], 'no-cert': ESA_FLAGS['no-cert'] },
453
- examples: ['wkgeo esa hostname --pool intl-1 --host cli-e2e.wkago.com'],
453
+ examples: ['wkgeo esa hostname --pool intl-1 --host demo.example.com'],
454
454
  notes: [
455
455
  '**先有回源记录再接域名**:没回源记录也没给 --record-id 会直接 400(避免接出个黑洞)。',
456
456
  '证书是免费 DV,DNS 必须先解析到 ESA 才能签下来;签不下来不会假装成功。',
@@ -484,7 +484,7 @@ export const esaKvCommand = {
484
484
  summary: '把域名写进边缘路由 KV(`host:<域名>` → 站点目录,写后 GetKv 回读)',
485
485
  usage: 'wkgeo esa kv --host <域名> --site-id <站点id>',
486
486
  flags: { host: ESA_FLAGS.host, 'site-id': { type: 'string', desc: '站点 id(KV 的值就是它,边缘据此改写路径)' } },
487
- examples: ['wkgeo esa kv --host cli-e2e.wkago.com --site-id 8f0c…'],
487
+ examples: ['wkgeo esa kv --host demo.example.com --site-id 8f0c…'],
488
488
  notes: [
489
489
  'KV 值是**站点 id**(= 桶里的顶层目录),边缘路由器命中后把 `/<path>` 改写成 `/<siteId>/<path>`。',
490
490
  'BatchPutKv 回 200 只代表"收到",不代表生效 —— 所以这里强制 GetKv 回读,读不到就是失败。',
@@ -202,6 +202,14 @@ import {
202
202
  import { contentCheckCommand, contentFillCommand } from './content.mjs';
203
203
  /* `content apply` 本体在 `cli/lib/manifest-apply.mjs`(只管建站内容契约;模板契约那条已拆成 `content fill`) */
204
204
  import { contentApplyCommand } from '../manifest-apply.mjs';
205
+ /**
206
+ * ★ 2026-11-10(老板单「数据交换」):`data` 组 = 三类运营数据的**只读**导出。
207
+ * chat AI 客服会话 / 单会话消息(`/aikefu` → MaxKB 只读库;正文默认脱敏、IP 只给掩码);
208
+ * stats 访问统计按日 PV / UV / IP 唯一数 + Top 页面 / 来源(`/analytics` → `statRange`);
209
+ * usage 大模型消耗按日 / 模型 / 站点(`/admin` → `llmCostSummary`,需 scope `llm:cost_read`)。
210
+ * 统一参数:`--site <ID|域名>` / `--from` / `--to` / `--page` `/`--limit` / `--json|--text` / `--out <csv|json>`。
211
+ */
212
+ import { DATA_COMMANDS } from './data.mjs';
205
213
  /**
206
214
  * ★ 2026-10-30(task-4):\`seo\` 组 = **本地站点产物**的 SEO 工具,四条纯本地命令(不联网、不写库)。
207
215
  * audit 13 项加权评分 + issues[](报告命令,恒 exit 0);
@@ -238,6 +246,8 @@ export const COMMANDS = [
238
246
  contentApplyCommand,
239
247
  contentFillCommand,
240
248
  contentCheckCommand,
249
+ /* ★ 2026-11-10:数据交换三件套(chat / stats / usage,全部只读) */
250
+ ...DATA_COMMANDS,
241
251
  /* ★ task-4:本地站点产物的 SEO 工具(audit / llms / schema / files),不联网、不写库 */
242
252
  ...seoCommands,
243
253
  /* ★ task-5:本地站点产物的 GEO 工具(audit / llms / robots / brands / report),不联网、不写库 */
@@ -464,6 +474,8 @@ const GROUP_SUMMARY = {
464
474
  overview: '站点总览:栏目内容素材计数 / 账号级流量账单(仅平台管理员)/ 控制台首页快照(只读)',
465
475
  content:
466
476
  '内容原语:apply = 建站清单(site-manifest.json)落站 · fill = 模板内容契约(sections[]/pages[])填库 · check 契约↔库↔前台自检 + 9 维评分(两条写命令默认 dry-run、逐栏目 upsert、幂等、未知字段拒绝)',
477
+ data:
478
+ '数据交换(只读):chat = AI 客服会话/单会话消息(正文默认脱敏、IP 只给掩码)· stats = 按日 PV/UV/IP 唯一数 + Top 页面/来源 · usage = 按日/模型/站点的大模型请求数/token/费用(需 scope llm:cost_read);`--out` 落 CSV/JSON',
467
479
  template:
468
480
  '模板工具链:init 取基础库 / validate 契约九关 / capture 载图 / verify 像素自比 / score 评分 / anim 动画 / pack 打包 / publish 发布 / preview 预览',
469
481
  templates:
@@ -837,7 +837,9 @@ export const plansListCommand = {
837
837
  *
838
838
  * ⚠️ 只开放 `--name`(改站名)。**`--remark` 目前发不通,CLI 必须如实报缺口**:
839
839
  * 服务端 `updateSite` 的字段白名单是
840
- * `name / template_id / status / settings / domain / domains / expires_at / asset_storage_mode`
840
+ * `name / template_id / settings / domain / domains / expires_at / asset_storage_mode`
841
+ * (★ 2026-11-11 task-85:`status` 已移出白名单,显式传会回 400 `STATUS_NOT_EDITABLE`,
842
+ * 上下架走 `siteOffline` / `siteOnline`)
841
843
  * —— 没有 remark;`public.site` 表里也没有这一列(remark 只存在于 customer / wallet_txn /
842
844
  * user_debt / invoice_request / site_quota_purchase 这些别的表)。
843
845
  * 白名单外的 key 会被**静默忽略**,所以"传了就返回成功"是假成功。与其假装能改备注,
@@ -53,6 +53,8 @@ import {
53
53
  const PUBLISH_POLL_MS = 2000;
54
54
  /** 素材列表翻页上限(每页 100 × N 桶) */
55
55
  const ASSET_PAGE_CAP = 5;
56
+ /** 首页栏目 slug(与后台 `isHomeCategorySlug` 同一口径:首页永远进导航) */
57
+ const HOME_SLUGS = new Set(['home', 'index']);
56
58
 
57
59
  /** task-95:建站模式(与三条云上链路同一口径:默认 optimize) */
58
60
  const BUILD_MODES = ['optimize', 'origin_copy'];
@@ -636,8 +638,70 @@ function createApplyEngine({ ctx, site, manifest, itemErrors, warnings, dryRun }
636
638
  }
637
639
 
638
640
  /* ── 栏目 ─────────────────────────────────────────────────── */
641
+
642
+ /** 本次清单 `menus[]` 声明的导航 path(懒算一次;`menus[]` 是导航唯一真相) */
643
+ let navPathsMemo = null;
644
+ function navPaths() {
645
+ if (!navPathsMemo) {
646
+ navPathsMemo = new Set();
647
+ for (const one of flattenMenus(manifest.menus)) {
648
+ const p = normalizePath(one.path);
649
+ if (p) navPathsMemo.add(p);
650
+ }
651
+ }
652
+ return navPathsMemo;
653
+ }
654
+
655
+ /**
656
+ * 这个栏目该不该进前台导航(老板 2026-11-13 口径:「首页板块一律用隐藏栏目承载」)。
657
+ *
658
+ * @returns {true|false|undefined} `undefined` = 本次**不动**导航字段(老清单:没写 `inMenu`、
659
+ * 也没声明 `menus[]` ⇒ 服务端默认 true,行为与改造前完全一致)。
660
+ *
661
+ * 判定顺序(`menus[]` 是导航唯一真相,`categories[].inMenu` 只是补充):
662
+ * 1. 在 `menus[]` 里 ⇒ `true`(老的显式导航行为不变);同时又写 `inMenu:false` ⇒ 按导航为准并告警;
663
+ * 2. 不在 `menus[]` 里、显式 `inMenu:false` ⇒ `false`(首页板块 / 隐藏栏目);
664
+ * 3. 不在 `menus[]` 里、显式 `inMenu:true` ⇒ `true`(清单没声明导航时也能手动进导航);
665
+ * 4. 没写 `inMenu`、但清单**声明了**导航 ⇒ `false`(没被导航引用就不进导航);
666
+ * 5. 没写 `inMenu`、清单也没有 `menus[]` ⇒ `undefined`(老行为,不碰)。
667
+ */
668
+ function navStateOf(cat, catPath) {
669
+ const nav = navPaths();
670
+ const p = normalizePath(catPath);
671
+ const inNav = nav.size > 0 && Boolean(p) && nav.has(p);
672
+ if (inNav) {
673
+ if (cat.inMenu === false) {
674
+ warnings.push({
675
+ path: `categories.${cat.slug}.inMenu`,
676
+ message: '写了 inMenu:false,但它出现在 menus[] 里 —— 按导航为准(进导航);要隐藏就从 menus[] 里去掉',
677
+ });
678
+ }
679
+ return true;
680
+ }
681
+ /**
682
+ * 首页永远进导航:`menus[].path` 的契约是 `/xxx/`,**写不出 `/`**
683
+ * (JSON Schema `^/[a-z0-9]...` + 校验都拦),所以「不在 menus[] 里」对首页没有意义。
684
+ * 判据与后台一致:slug = `home` / `index`(服务端 `isHomeCategorySlug`)或 path 为 `/`。
685
+ */
686
+ if (nav.size > 0 && (p === '/' || HOME_SLUGS.has(String(cat.slug || '').toLowerCase()))) return true;
687
+ if (cat.inMenu === false) return false;
688
+ if (cat.inMenu === true) return true;
689
+ return nav.size > 0 ? false : undefined;
690
+ }
691
+
639
692
  async function stageCategories() {
640
693
  const entries = [];
694
+ /**
695
+ * 映射判据(`site-mapping-contract.mjs`):manifest 的 `type` 落成哪个 `kind` 由它一处说了算。
696
+ * 加载不到(npm 包里没有 `aliyun/` 目录)⇒ `null`,退回 `cat.kind`,行为与改造前一致。
697
+ *
698
+ * ⚠️ 原来这里只有 `const mapped = contract ? … : null`,**`contract` 从没赋值过** ⇒ 只要有
699
+ * `categories[]` 就抛 `ReferenceError: contract is not defined`(`content apply` 一直是坏的;
700
+ * 之前没有用例覆盖「apply 带栏目」,所以没被发现)。这一行是补上的加载点。
701
+ */
702
+ const contract = await loadSiteMappingContract();
703
+ /** 本次按口径落成隐藏的栏目(集中一条告警,免得刷屏) */
704
+ const hidden = [];
641
705
  for (const cat of sortCategoriesForApply(manifest.categories)) {
642
706
  const item = `category:${cat.slug}`;
643
707
  if (blocked.has(item)) continue;
@@ -690,6 +754,9 @@ function createApplyEngine({ ctx, site, manifest, itemErrors, warnings, dryRun }
690
754
  const kind = mapped ? mapped.kind : cat.kind;
691
755
  /** 模板绑定先过契约(计划期就定下来:不合法 ⇒ 空串 + 一条 ⚠,创建 / 更新两条分支共用) */
692
756
  const templateFile = await resolveManifestTemplateFile(cat, kind);
757
+ /** 导航归属:true / false / undefined(undefined = 本次不动,老行为) */
758
+ const inMenu = navStateOf(cat, wantPath);
759
+ if (inMenu === false) hidden.push(cat.name);
693
760
 
694
761
  if (!existing) {
695
762
  const entry = {
@@ -698,7 +765,7 @@ function createApplyEngine({ ctx, site, manifest, itemErrors, warnings, dryRun }
698
765
  planned: 'create',
699
766
  action: 'create',
700
767
  label,
701
- detail: `新建栏目(${kind})${templateFile ? ` 模板 ${templateFile}` : ''}`,
768
+ detail: `新建栏目(${kind}${inMenu === false ? ',不进导航' : ''})${templateFile ? ` 模板 ${templateFile}` : ''}`,
702
769
  };
703
770
  entry.run = async (row) => {
704
771
  const payload = { name: cat.name, slug: cat.slug, kind, sort: cat.sort };
@@ -710,6 +777,11 @@ function createApplyEngine({ ctx, site, manifest, itemErrors, warnings, dryRun }
710
777
  if (cat.description) payload.description = cat.description;
711
778
  if (cat.seoDescription) payload.seo_description = cat.seoDescription;
712
779
  if (cat.seoKeywords) payload.seo_keywords = cat.seoKeywords;
780
+ /**
781
+ * 关键:**建的时候就带上导航归属**。以前这里没有 `in_menu`,服务端默认 true,
782
+ * 于是「首页·XXX」建完就挂在导航里,只能事后手动 `categories update --no-in-menu` 补。
783
+ */
784
+ if (inMenu !== undefined) payload.in_menu = inMenu;
713
785
  const saved = await call('categorySave', payload);
714
786
  let id = String((saved && (saved.id || saved.categoryId)) || '');
715
787
  if (!id) {
@@ -743,6 +815,8 @@ function createApplyEngine({ ctx, site, manifest, itemErrors, warnings, dryRun }
743
815
  description: cat.description,
744
816
  seoDescription: cat.seoDescription,
745
817
  seoKeywords: cat.seoKeywords,
818
+ /** 已有栏目也按同一口径纠正导航归属(以前只摘「不在清单里」的,清单内的永远留在导航) */
819
+ inMenu,
746
820
  });
747
821
  state.catIdBySlug.set(cat.slug, {
748
822
  id: String(existing.id),
@@ -762,6 +836,14 @@ function createApplyEngine({ ctx, site, manifest, itemErrors, warnings, dryRun }
762
836
  };
763
837
  entries.push(entry);
764
838
  }
839
+ if (hidden.length) {
840
+ warnings.push({
841
+ path: 'categories',
842
+ message:
843
+ `${hidden.length} 个栏目不在 menus[] 里,按口径落成隐藏栏目(in_menu=false):${hidden.join('、')}` +
844
+ ' —— 要进导航就把它们写进 menus[]',
845
+ });
846
+ }
765
847
  return entries;
766
848
  }
767
849
 
@@ -991,6 +1073,13 @@ function createApplyEngine({ ctx, site, manifest, itemErrors, warnings, dryRun }
991
1073
  async function stageMenus() {
992
1074
  const entries = [];
993
1075
  const flat = flattenMenus(manifest.menus);
1076
+ /**
1077
+ * 清单没写 `menus[]` ⇒ **本次不动导航**(老清单行为不变)。
1078
+ *
1079
+ * 注意这里**不再**兜底「把清单里的栏目摘出导航」:清单内的导航归属在 `stageCategories`
1080
+ * 里按 `menus[]` 一次定好(见 `navStateOf`:没被引用 ⇒ 建的时候就是 `in_menu=false`)。
1081
+ * 如果在这里再摘一遍,没有 `menus[]` 的老清单会连整站导航一起被摘空(以前正是这么绕开的)。
1082
+ */
994
1083
  if (!flat.length) return entries;
995
1084
  if (!dryRun) {
996
1085
  /* 栏目阶段可能刚建出一批:落库后以服务端为准重建 path 索引(服务端算 path,本地不猜) */
@@ -1045,9 +1134,16 @@ function createApplyEngine({ ctx, site, manifest, itemErrors, warnings, dryRun }
1045
1134
  for (const row of state.cats) {
1046
1135
  if (row.builtin === true) continue;
1047
1136
  if (row.in_menu !== true) continue;
1048
- if (manifestCatIds.has(String(row.id))) continue; /* 清单里的栏目:认 ID 不认 path(服务端 path 可能与 manifest 写法不同) */
1137
+ /**
1138
+ * 清单里的栏目:导航归属已由 `stageCategories` 按 `menus[]` 决定(建/改时带 `in_menu`),
1139
+ * 这里再摘一次只会多出一条重复条目。只跳过**清单里**的,清单外的照样按老逻辑摘。
1140
+ * 认 ID 不认 path(服务端 path 可能与 manifest 写法不同)。
1141
+ */
1142
+ if (manifestCatIds.has(String(row.id))) continue;
1049
1143
  const p = normalizePath(row.path);
1050
1144
  if (!p || whitelist.has(p)) continue;
1145
+ /* 首页(`/`)不在 menus[] 里是因为契约写不出 `/`,不是"没被引用"—— 永远留在导航 */
1146
+ if (p === '/') continue;
1051
1147
  const item = `menu:${p}`;
1052
1148
  const entry = {
1053
1149
  kind: 'menu',
@@ -1217,6 +1313,11 @@ function diffCategory(row, want) {
1217
1313
  payload.sort = want.sort;
1218
1314
  changes.push(`sort:${row.sort} → ${want.sort}`);
1219
1315
  }
1316
+ /* 导航归属:`undefined` = 本次不动(老清单);只比布尔值,避免把服务端默认值当成「有变」 */
1317
+ if (typeof want.inMenu === 'boolean' && Boolean(row.in_menu) !== want.inMenu) {
1318
+ payload.in_menu = want.inMenu;
1319
+ changes.push(`导航:${row.in_menu ? '显示' : '隐藏'} → ${want.inMenu ? '显示' : '隐藏'}`);
1320
+ }
1220
1321
  if (want.templateFile && normTemplate(row.template_path) !== normTemplate(want.templateFile)) {
1221
1322
  payload.template_path = want.templateFile;
1222
1323
  changes.push(`模板:${row.template_path || '(空)'} → ${want.templateFile}`);
@@ -181,6 +181,10 @@
181
181
  "type": "number",
182
182
  "description": "同级排序,默认按声明顺序 ×10"
183
183
  },
184
+ "inMenu": {
185
+ "type": "boolean",
186
+ "description": "是否显示在前台导航(也认 in_menu)。不写 = 按 menus[] 反推:清单声明了导航但没引用它 ⇒ 隐藏(in_menu=false);首页独立板块(首页·XXX)就该这样隐藏"
187
+ },
184
188
  "templateFile": {
185
189
  "type": "string",
186
190
  "pattern": "\\.html$",
package/lib/manifest.mjs CHANGED
@@ -433,6 +433,22 @@ export function validateManifest(doc, opts = {}) {
433
433
  if (declaredPath && !PATH_RE.test(declaredPath)) {
434
434
  fail(`${at}.path`, `path 形如 "/product/"(前后都有斜杠),收到 "${declaredPath}"`);
435
435
  }
436
+ /**
437
+ * 导航归属(老板 2026-11-13 口径:「首页板块一律用隐藏栏目承载」)。
438
+ *
439
+ * 契约写法 `inMenu`(也认服务端字段名 `in_menu`);**不写**时由 `menus[]` 反推:
440
+ * 清单声明了导航但没引用这个栏目 ⇒ 落 `in_menu=false`(见 manifest-apply.mjs 的 `navStateOf`)。
441
+ * 这里只做取值解析与类型校验,反推逻辑放在落地层(需要本次清单的 menus[] 全景)。
442
+ */
443
+ const inMenuRaw = raw.inMenu !== undefined ? raw.inMenu : raw.in_menu;
444
+ let inMenu;
445
+ if (inMenuRaw !== undefined && inMenuRaw !== null) {
446
+ if (typeof inMenuRaw !== 'boolean') {
447
+ fail(`${at}.inMenu`, `inMenu 必须是 true / false,收到 "${oneLine(String(inMenuRaw), 20)}"`);
448
+ } else {
449
+ inMenu = inMenuRaw;
450
+ }
451
+ }
436
452
 
437
453
  /* fields:栏目自己的自定义字段 */
438
454
  const fields = [];
@@ -488,6 +504,7 @@ export function validateManifest(doc, opts = {}) {
488
504
  seoKeywords,
489
505
  description: text(raw.description),
490
506
  fields,
507
+ inMenu,
491
508
  declaredPath: declaredPath ? normalizePath(declaredPath) : '',
492
509
  path: '',
493
510
  level: 0,
@@ -942,6 +959,12 @@ export function manifestJsonSchema() {
942
959
  },
943
960
  parent: str({ description: '父栏目 slug 或 path;子栏目继承父的类型' }),
944
961
  sort: { type: 'number', description: '同级排序,默认按声明顺序 ×10' },
962
+ inMenu: {
963
+ type: 'boolean',
964
+ description:
965
+ '是否显示在前台导航(也认 in_menu)。不写 = 按 menus[] 反推:清单声明了导航但没引用它 ⇒ 隐藏(in_menu=false);' +
966
+ '首页独立板块(首页·XXX)就该这样隐藏',
967
+ },
945
968
  templateFile: str({ pattern: '\\.html$', description: '本站已有的模板文件(如 list.html),必须是 .html' }),
946
969
  description: str({ description: '栏目简介,落 description' }),
947
970
  seoDescription: str({ maxLength: LIMITS.seoDescriptionChars, description: '回退读 seo.description' }),
@@ -44,7 +44,11 @@ const MIME = {
44
44
  '.js': 'application/javascript; charset=utf-8',
45
45
  };
46
46
 
47
- const DEFAULT_BUCKET = 'wkgeocom';
47
+ /**
48
+ * 模板母版落点桶(可用 `OSS_BUCKET` 覆盖)。
49
+ * 2026-11-11(t180 切桶):`wkgeocom` → `wkgeo-cn`(旧桶只读保留,删桶前必须切走)。
50
+ */
51
+ const DEFAULT_BUCKET = 'wkgeo-cn';
48
52
  const DEFAULT_REGION = 'oss-cn-shanghai';
49
53
 
50
54
  const mimeOf = (rel) => MIME[path.extname(rel).toLowerCase()] || 'application/octet-stream';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wkgeo/cli",
3
- "version": "1.1.3",
3
+ "version": "1.1.4",
4
4
  "description": "云站平台官方命令行客户端(@wkgeo/cli):授权登录一次,之后建站 / 下单 / 钱包支付 / 查余额都不用再登录(OAuth 授权码 + PKCE,公共客户端,零第三方依赖)",
5
5
  "keywords": [
6
6
  "wkgeo",