dsh-aiyayi 1.5.41 → 1.5.42
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 +35 -2
- package/README.md +10 -0
- package/cordis.patch.yml +28 -0
- package/lib/own-tools.js +3 -0
- package/lib/pkg-stats.js +714 -0
- package/lib/toolkit.js +18 -1
- package/package.json +3 -1
package/CHANGELOG.md
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
> **维护约定**:新版本发布时在顶部加条目。本文件由 README 正文拆出(2026-11-09 重构):版本条目与踩坑记录原文照录,数字、时间、日期一律不改(量化保真是本插件的规矩)。版本事实以 npm registry 为准。
|
|
4
4
|
>
|
|
5
|
-
> **npm 发布一览(2026-11-12 核对 registry,`npm view dsh-aiyayi versions --json`)**:latest = **1.5.38**(2026-11-12 已发布;本次发版版为 **1.5.39**——toolkit 三件套注册失败修复 + feishu_bind 自动绑定,publish 留待下一步单独执行,发布后以 registry 为准)。已发布:1.0.0、…、1.5.7、**1.5.14**、**1.5.15**、**1.5.16**、**1.5.17**、**1.5.20**、**1.5.21**、**1.5.22**、**1.5.23**、**1.5.24**、**1.5.25**、**1.5.26**、**1.5.27**、**1.5.28**、**1.5.29**、**1.5.30**、**1.5.31**、**1.5.32**、**1.5.33**、**1.5.34**、**1.5.35**、**1.5.36**、**1.5.37**;跳号 1.3.0、1.4.1、1.4.2、1.5.0、1.5.1、1.5.2、1.5.3、**1.5.8–1.5.13** 从未发布到 npm(本地开发线:1.5.8–1.5.11 飞书桥接、1.5.12 思考纪律约束、1.5.13 内置技能同步+feishu-setup 骨架);1.5.14 已发布(坑 #58–#67 修复);1.5.15 已发布(扫码接入改造);1.5.16 已发布(feishu-setup 技能脚本入包);1.5.17 已发布(坑 #68 重入保护修复);**1.5.18 / 1.5.19 也从未发布到 npm**(见下方 1.5.18 / 1.5.19 条目——它们的代码最终随 1.5.20 一起进 npm);**1.5.20 已发布**(飞书正文改走 interactive 卡片 + lark_md,含 1.5.19 附件收发与问答卡片、1.5.20 markdown 渲染,以及 create-bot v6 权限集中化);**1.5.21 已发布**(修飞书回复正文首尾空白行,坑 #72);**1.5.22 已发布**(多应用多长连接改造+chat 归属机制,见下方 1.5.22 条目);**1.5.23–1.5.25 已发布**(230001 边界/补 import/补 feishuCode 挖码三轮装版断言增量修复,见下方对应条目);**1.5.26 已发布**(回发多文本段覆盖丢段修复,坑 #73,见下方 1.5.26 条目);**1.5.27 已发布**(微信通道并入,默认关闭,见下方 1.5.27 条目);**1.5.28 已发布**(PowerShell 版本体检 + 微信通道收尾,见下方 1.5.28 条目);**1.5.29 已发布**(发布包排除 `test/` + 测试残留空目录清理,见下方 1.5.29 条目);**1.5.30 已发布**(create-bot 注释改用 `<记忆根>` 占位,见下方 1.5.30 条目);**1.5.31 已发布**(PowerShell 体检 `major:null` 根因修复:探测链补上 powershell.exe 一级,见下方 1.5.31 条目);**1.5.32 已发布**(行为变更:首次提示同时告知微信 ClawBot 能力 + 「对接默认落到发起对接的会话」固化为 persona 准则/文档;不含路由代码改动,见下方 1.5.32 条目);**1.5.33 已发布**(同一准则落成代码:未绑定 chat 三档复用,不再无条件新建会话,见下方 1.5.33 条目);**1.5.34 已发布**(纯测试修复:`presence-clock` 跨午夜偶发失败,`lib/` 零改动,见下方 1.5.34 条目);**1.5.35 已发布**(`feishu_status` 新增最近入站路由回看 `inboundRouting` 字段,见下方 1.5.35 条目);**1.5.36 已发布**(飞书连接状态失真修复,见下方 1.5.36 条目);**1.5.37 已发布**(压缩前沉淀机制 precompact,见下方 1.5.37 条目);**1.5.38 已发布**(工具包中间层首批 toolkit_cmd / toolkit_read / toolkit_write,见下方 1.5.38 条目);**1.5.39 为本次发版版**(toolkit 三件套注册失败修复 + feishu_bind 自动绑定,见下方 1.5.39 条目;publish 留待下一步,以 registry 为准);**1.5.40 为当前开发版**(toolkit 执行输出对齐 output.schema——宿主对输出也做 schema 校验,见下方 1.5.40 条目与坑 #78;仅本地提交,不 push 不 publish);**1.5.41
|
|
5
|
+
> **npm 发布一览(2026-11-12 核对 registry,`npm view dsh-aiyayi versions --json`)**:latest = **1.5.38**(2026-11-12 已发布;本次发版版为 **1.5.39**——toolkit 三件套注册失败修复 + feishu_bind 自动绑定,publish 留待下一步单独执行,发布后以 registry 为准)。已发布:1.0.0、…、1.5.7、**1.5.14**、**1.5.15**、**1.5.16**、**1.5.17**、**1.5.20**、**1.5.21**、**1.5.22**、**1.5.23**、**1.5.24**、**1.5.25**、**1.5.26**、**1.5.27**、**1.5.28**、**1.5.29**、**1.5.30**、**1.5.31**、**1.5.32**、**1.5.33**、**1.5.34**、**1.5.35**、**1.5.36**、**1.5.37**;跳号 1.3.0、1.4.1、1.4.2、1.5.0、1.5.1、1.5.2、1.5.3、**1.5.8–1.5.13** 从未发布到 npm(本地开发线:1.5.8–1.5.11 飞书桥接、1.5.12 思考纪律约束、1.5.13 内置技能同步+feishu-setup 骨架);1.5.14 已发布(坑 #58–#67 修复);1.5.15 已发布(扫码接入改造);1.5.16 已发布(feishu-setup 技能脚本入包);1.5.17 已发布(坑 #68 重入保护修复);**1.5.18 / 1.5.19 也从未发布到 npm**(见下方 1.5.18 / 1.5.19 条目——它们的代码最终随 1.5.20 一起进 npm);**1.5.20 已发布**(飞书正文改走 interactive 卡片 + lark_md,含 1.5.19 附件收发与问答卡片、1.5.20 markdown 渲染,以及 create-bot v6 权限集中化);**1.5.21 已发布**(修飞书回复正文首尾空白行,坑 #72);**1.5.22 已发布**(多应用多长连接改造+chat 归属机制,见下方 1.5.22 条目);**1.5.23–1.5.25 已发布**(230001 边界/补 import/补 feishuCode 挖码三轮装版断言增量修复,见下方对应条目);**1.5.26 已发布**(回发多文本段覆盖丢段修复,坑 #73,见下方 1.5.26 条目);**1.5.27 已发布**(微信通道并入,默认关闭,见下方 1.5.27 条目);**1.5.28 已发布**(PowerShell 版本体检 + 微信通道收尾,见下方 1.5.28 条目);**1.5.29 已发布**(发布包排除 `test/` + 测试残留空目录清理,见下方 1.5.29 条目);**1.5.30 已发布**(create-bot 注释改用 `<记忆根>` 占位,见下方 1.5.30 条目);**1.5.31 已发布**(PowerShell 体检 `major:null` 根因修复:探测链补上 powershell.exe 一级,见下方 1.5.31 条目);**1.5.32 已发布**(行为变更:首次提示同时告知微信 ClawBot 能力 + 「对接默认落到发起对接的会话」固化为 persona 准则/文档;不含路由代码改动,见下方 1.5.32 条目);**1.5.33 已发布**(同一准则落成代码:未绑定 chat 三档复用,不再无条件新建会话,见下方 1.5.33 条目);**1.5.34 已发布**(纯测试修复:`presence-clock` 跨午夜偶发失败,`lib/` 零改动,见下方 1.5.34 条目);**1.5.35 已发布**(`feishu_status` 新增最近入站路由回看 `inboundRouting` 字段,见下方 1.5.35 条目);**1.5.36 已发布**(飞书连接状态失真修复,见下方 1.5.36 条目);**1.5.37 已发布**(压缩前沉淀机制 precompact,见下方 1.5.37 条目);**1.5.38 已发布**(工具包中间层首批 toolkit_cmd / toolkit_read / toolkit_write,见下方 1.5.38 条目);**1.5.39 为本次发版版**(toolkit 三件套注册失败修复 + feishu_bind 自动绑定,见下方 1.5.39 条目;publish 留待下一步,以 registry 为准);**1.5.40 为当前开发版**(toolkit 执行输出对齐 output.schema——宿主对输出也做 schema 校验,见下方 1.5.40 条目与坑 #78;仅本地提交,不 push 不 publish);**1.5.41 为当前发版版**(Toolbox 真异步能力 + watch_read 异步工具 + mem_sync 同步工具,见下方 1.5.41 条目与坑 #79/#80;2026-11-12T07:17:11Z 已发布到 npm,latest);**1.5.42 为当前开发版**(新增 `pkg_stats` 同步工具——npm 下载量 + GitHub/Gitee/GitCode 仓库热度,见下方 1.5.42 条目;仅本地提交,不 push 不 publish)。
|
|
6
6
|
>
|
|
7
7
|
> **环境标识约定(2026-11-10 新增)**:写版本条目/坑条目时,**顺手记录当时的 智能体工具-智能体模式-模型供应商-模型**(如 **DSH-创造模式-loomy讯飞-GLM5.3FLASH**),写在条目内(紧跟 git 记录行、或坑条目首行),方便回溯该条目是在哪套智能体/模型环境下产出与验证的。
|
|
8
8
|
|
|
@@ -10,6 +10,39 @@
|
|
|
10
10
|
|
|
11
11
|
---
|
|
12
12
|
|
|
13
|
+
## 1.5.42(2026-11-12 新增:`pkg_stats` 工具——查 npm 下载量与代码仓热度,同步)
|
|
14
|
+
|
|
15
|
+
- 环境:DSH-执行智能体(DeepSeek Harness 子会话,模型名未确证)
|
|
16
|
+
- **改了什么(新增 `lib/pkg-stats.js` + 测试;改 `lib/toolkit.js` / `own-tools.js` / `package.json` / `README.md` / `cordis.patch.yml` 注释;既有 5 工具行为不变)**:
|
|
17
|
+
- `lib/pkg-stats.js`(新增):同步工具 `pkg_stats`。参数全可省——`package`(默认 `dsh-aiyayi`,支持 `@scope/name`)、`repo`(默认 `BayiHY/dsh-aiyayi`)。
|
|
18
|
+
- **npm 下载量**:`api.npmjs.org/downloads/point/{last-day,last-week,last-month}/<pkg>` 三个窗口**并发**取,每个窗口原样带回 `downloads/start/end`。
|
|
19
|
+
- **npm 版本**:`registry.npmjs.org/<pkg>` 直接 HTTP GET(**不 shell 调 npm**——本机 `.npmrc` 默认指 npmmirror 镜像),取 `dist-tags.latest` 与 `time[latest]`。
|
|
20
|
+
- **GitHub**:直连 `api.github.com/repos/{owner}/{repo}` 优先;失败走 `gh-proxy.com` 代理兜底。`github.source` 标 `direct` / `gh-proxy` / 空串,调用方能看见数据到底从哪来。
|
|
21
|
+
- **Gitee**:`gitee.com/api/v5/repos/{owner}/{repo}`。
|
|
22
|
+
- **GitCode**:`gitcode.com/api/v5/repos/{owner}/{repo}`(**白名单只有六条,不含 `api.gitcode.com`**,故走主站路径)。
|
|
23
|
+
- 返回:`{ok, package, version, repo, npm:{lastDay,lastWeek,lastMonth,versionPublishedAt,unavailable}, github:{stars,forks,watchers,openIssues,unavailable,source}, gitee:{...}, gitcode:{stars,forks,unavailable}, fetchedAt, error}`。
|
|
24
|
+
- **失败隔离**:每个平台自己吞错,只把原因写进**自己那段**的 `unavailable`,其余照常返回;**全失败也返回合法结构**(`ok:false`),绝不抛未捕获异常。
|
|
25
|
+
- **安全(四层)**:①**域名白名单**精确主机名匹配(`api.npmjs.org` / `registry.npmjs.org` / `api.github.com` / `gh-proxy.com` / `gitee.com` / `gitcode.com`),非白名单主机**请求根本不发**(`assertAllowedUrl` 直接抛);只允许 https、URL 不许带凭据。②`repo` 两段只允许 `A-Za-z0-9._-`(拒 `.` / `..` / 空白 / `?` `#` `%` `\`),`package` 按 `[@scope/]name` 校验,拼接前**逐段 `encodeURIComponent`**。③`gh-proxy.com` 是**第三方代理**(把 GitHub 路径原样交给它转发,等于把 owner/repo 暴露给它、会进其访问日志),只在直连失败时用,`pkgStatsAllowGithubProxy:false` 可关(单测断言关掉后**一次都不打**)。④15 秒总预算(`pkgStatsTimeoutMs`)+ 单请求 8 秒(`pkgStatsRequestTimeoutMs`)+ GitHub 直连 4 秒快速失败(`pkgStatsGithubDirectTimeoutMs`)。
|
|
26
|
+
- `lib/toolkit.js`:导入 `PKG_STATS_SCHEMA / executePkgStats / shapePkgStatsOutput`,`TOOL_NAMES` 扩到 **6**,`DEFAULT_CONFIG` 加 5 个 `pkgStats*` 配置项,`builtins` 数组挂 `[PKG_STATS_SCHEMA, (args) => executePkgStats(args, { cfg, logUsage, warn })]`,`__testing` 导出 `shapePkgStatsOutput`。
|
|
27
|
+
- `lib/own-tools.js`:`OWN_TOOLS` 加 `pkg_stats`。
|
|
28
|
+
- `package.json`:version 1.5.42;exports/files 白名单加 `./pkg-stats` / `lib/pkg-stats.js`。
|
|
29
|
+
- `cordis.patch.yml`:toolkit 段按前例补 1.5.42 注释(**只加注释,默认行为不变**,`pkgStats*` 项以注释形式给出默认值)。
|
|
30
|
+
- `README.md`:工具箱表格加 `pkg_stats` 一行 + 三个实测注意点(end 滞后 / GitHub 需代理 / GitCode 无匿名 API + Gitee watchers 语义);文件清单加 `lib/pkg-stats.js`。
|
|
31
|
+
- **为什么**:本体想知道"这包有多少人在用、仓库热不热",以前得派检索员翻网页——GitHub 直连还不通。收成一个同步工具:几个 GET、2-4 秒出结果,比派子代省一整轮;且把三个实测坑(end 滞后、直连不通、无匿名 API)**写进返回结构**,以后不会误读。
|
|
32
|
+
- **踩坑记录(都是当场实测的,不是推测)**:
|
|
33
|
+
1. **npm 统计 API 的 `end` 日期滞后约 2 天,"last-day" 不是今天**。2026-11-12 15:3x 实测:`last-day` 返 `{downloads:744,start:"2026-11-10",end:"2026-11-10"}`(不是 11-12);`last-week` 4549(11-04→11-10);`last-month` 4851(10-12→11-10)。→ 所以三个窗口**必须原样带回 start/end**,否则以后必然误读成"今天的下载量"。
|
|
34
|
+
2. **GitHub API 直连在本机不通**。`api.github.com/repos/BayiHY/dsh-aiyayi`:PowerShell 报"基础连接已经关闭"、node fetch 报 `fetch failed`(cause ECONNRESET,curl 报 `(35) Recv failure: Connection was reset`)。兜底 `https://gh-proxy.com/https://api.github.com/repos/...` 可用(实测 200,`x-ratelimit-remaining=143/5000`,会限流;403 时把 `message` 原样带回)。
|
|
35
|
+
3. **GitCode 无匿名 API**。`gitcode.com/api/v5/repos/BayiHY/dsh-aiyayi` → **400** `{"error_code":400,"error_message":"Orchestration error: Invalid header parameter: private-token, required"}`;`api.gitcode.com/api/v5/...` → **401** `401 Unauthorized,Please check whether the current request carries an invalid token...`。两个主机都要 token,**且 `api.gitcode.com` 不在六条白名单里**(精确主机名匹配),所以工具走 `gitcode.com` 主站路径、把服务端 `error_message` 原话带进 `unavailable`。页面上的 star/fork 是异步渲染的 **UI 数字**(实测第一次 0、第二次 125 的"下载使用量"),**不作接口确证、不抓页面**。
|
|
36
|
+
4. **Gitee 的 `watchers_count` 是"关注数"**,语义与 GitHub 的 watchers 不同——同一仓库 GitHub watchers=0、Gitee watchers=1。日报里两个数字不可混着比。
|
|
37
|
+
5. **npm registry 必须显式走 `registry.npmjs.org`**:本机 `.npmrc` 默认指 npmmirror 镜像,所以工具里直接 `https://registry.npmjs.org/<pkg>` HTTP GET,**不 shell 调 npm**。
|
|
38
|
+
6. **scoped 包名编码**:实测 `registry.npmjs.org/@types/node` 与 `%40types/node` 都返 200(等价),本工具产出的是 `%40scope/pkg`(逐段编码,`/` 保留)。npm downloads API 同理。
|
|
39
|
+
7. **单测当场抓出两个真 bug,已修**:① `assertSafeSegment` 原来会 `trim()`,导致 `repo="owner/ name"` 被**静默改写成 `owner/name`** 发出去——参数静默改写比报错更难查,现改为不 trim、带内部空白直接拒;② `withBudget` 的兜底定时器原来 `unref()`,当 mock fetch 永不 resolve 时它是唯一撑着事件循环的东西,unref 后 Node 直接退出,单测报 `Detected unsettled top-level await` + 退出码 0——有界计时器不 unref 不会漏活进程,现去掉 unref 并写明原因。
|
|
40
|
+
- **测试**:新增 `test/pkg-stats.test.mjs`(**135 条断言,全 mock fetch、不打真网**)。覆盖:schema 结构(单 type 字符串 / required 列全顶层与三层子对象 / additionalProperties:false / 全篇无 type 数组 / description 写明三个坑);各平台正常返回(含 **start/end 原样带回**的断言);只敲白名单域名且全是 GET、GitHub 直连成功时**不打代理**;scoped 包名逐段编码;**GitHub 三路**(直连成功 source=direct / 直连抛错走代理 source=gh-proxy / 直连+代理双挂时 403 `rate limit` 原话进 unavailable 且不抛 / 配置关掉代理后一次都不打代理 / 404 带原话);GitCode 400 带 `error_message` 与 UI 数字不作确证;**全平台失败**(500 / 网络层抛错两条路)结构仍合法且 `ok:false`;**超时**(mock fetch 永不 resolve → 300ms 预算内收口、五个平台 unavailable 都说超时、不抛);**白名单与注入**(5 条应拒 URL + 6 个白名单主机应放行 + 10 条坏 repo + 8 条坏 package + 合法形态放行 + 参数非法时返回合法结构而非抛);归一函数对脏输入(null/字符串/NaN/Infinity/负数/小数);注册面(TOOL_NAMES=6、DEFAULT_CONFIG 五项、own-tools 放行、经 `apply()` 注册、经 execute 壳真调一次);`render` 四条分支都能出文本不抛;源码静态核对(白名单冻结、注释写明第三方代理、无 `child_process` 痕迹、`fetchImpl` 只在 `fetchJson` 里调用一次)。
|
|
41
|
+
- `test/toolkit.test.mjs` / `test/toolkit-async.test.mjs` 因工具数 5→6 同步更新了注册断言("五个工具已注册"→"六个"、"list 变 6"→"list 变 7" 等)。
|
|
42
|
+
- 全量 `node --test`(显式传 **37** 个 `test/*.test.mjs` 文件):**165 项,162 过 3 挂**(挂 = alarm-inject / home-relocate / tools-surface 环境基线,与 1.5.35/1.5.39/1.5.40/1.5.41 条目同基线),**零新增失败**。基线 36 个文件 / 164 项 / 161 过 3 挂,本版 +1 个文件(165 项 / 162 过 / 3 挂),零新增失败。
|
|
43
|
+
- **实网实测(不是 mock,2026-11-12 15:33 本机)**:`executePkgStats({})` 耗时 **2434ms**,`ok=true`,`version=1.5.41`,`lastDay=744`(11-10)/`lastWeek=4549`/`lastMonth=4851`,`versionPublishedAt=2026-11-12T07:17:11.900Z`,`github.source="gh-proxy"`(直连确实不通),`gitee.watchers=1`,`gitcode.unavailable` 带 400 与 `private-token` 原话;输出过 schema 校验(无缺字段、无多余键)。
|
|
44
|
+
- 打包与 npm publish **不在本次范围**:本版只做版本号对齐 + **本地 commit**,不 push、不 publish、不动 profile。
|
|
45
|
+
|
|
13
46
|
## 1.5.41(2026-11-12 新增:Toolbox 真异步能力 + `watch_read` 异步工具、`mem_sync` 同步工具)
|
|
14
47
|
|
|
15
48
|
- 环境:DSH-执行智能体(DeepSeek Harness 子会话,模型名未确证)
|
|
@@ -32,7 +65,7 @@
|
|
|
32
65
|
- **单测当场抓出一个真 bug,已修(坑 #80)**:`git status --porcelain` 默认 `core.quotepath=true`,非 ASCII 路径输出成 C 风格转义(`?? "\346\226\260\347\254\224\350\256\260.md"`),拿它 join 目录拼不出真文件 → 读不到 → **静默跳过 → 带 `token=` 的文件被 `add -A` 提交了**。修法两层:git 调用统一加 `-c core.quotepath=false`,status 改 `--porcelain -z`(NUL 分隔、路径原样),`untrackedFiles()` 同时容忍 `-z` 与换行两种形态。修前该断言("未跟踪文件里的 token= 也拒绝")实测 FAIL,修后 PASS。
|
|
33
66
|
- 全量 `node --test`(显式传 36 个 `test/*.test.mjs` 文件):**164 项,161 过 3 挂**(挂 = alarm-inject / home-relocate / tools-surface 环境基线,与 1.5.35/1.5.39/1.5.40 条目同基线),**零新增失败**。`test/toolkit.test.mjs` 因工具数 3→5 同步更新了注册断言(原"三个工具已注册"/"list 变 4"按新数量改写,并加一行显式盯住五件套)。
|
|
34
67
|
- 文档:`docs/经验-工具真异步与宿主同步await.md`(新建,四条:宿主同步 await 的事实与源码位置 / 两条异步路子与为何选 followup / 坑 #65+#68 的具体规避写法 / 本 helper 的使用范式 + 坑 #80)。
|
|
35
|
-
- 打包与 npm publish
|
|
68
|
+
- 打包与 npm publish:**2026-11-12 李浩拍板后已完成发版第二段**。三远端 push 到 `6d5448a`(gitcode/gitee/github,ls-remote 三路核对一致);npm publish 到 `https://registry.npmjs.org/`(显式 `--registry`,`.npmrc` 默认指 npmmirror),tarball sha1 `d8c96ead92d69568cac564dcea4cb2e10feea4d4`、integrity `sha512-7ih7JTMf2CXN63VTCZwUKh6RukDBuK3x1nrhJQarVRWaiG623l6911Lzz6S4URdf/JnSRAWMIJ3vrr786S8rLg==`、**51 个文件**(比 1.5.40 的 49 个多 2 个 = 两个新文件),发布时刻 **2026-11-12T07:17:11Z**,registry `gitHead=6d5448a`;desktop profile 已 `pnpm add --save-exact dsh-aiyayi@1.5.41`,51 个包内文件与 tarball **逐个 SHA256 全部一致(0 diff)**。**未重启 DSH**(李浩自己重启后实机验货)。
|
|
36
69
|
|
|
37
70
|
## 1.5.40(2026-11-12 修复:toolkit_cmd / toolkit_write 执行输出不符 output.schema——宿主对工具输出也做 schema 校验,条件性返回字段必须与 schema 对齐,坑 #78)
|
|
38
71
|
|
package/README.md
CHANGED
|
@@ -67,6 +67,7 @@ GUI 新建会话 → agent preset 选「**阿依娅伊**」。聊天即可;她
|
|
|
67
67
|
| `toolkit_write` | 同步 | 受限写入(记忆根白名单,64KB,原子写 + .bak) | `{ok, path, bytes, backupPath, ...}` |
|
|
68
68
|
| `watch_read` | **异步** | 手表取数(电量/步数/睡眠/血氧/心率,入 SQLite) | 立刻 `{status:'started', taskId, hint}`;25-100 秒后结果作为一条**消息推回会话** |
|
|
69
69
|
| `mem_sync` | 同步 | 记忆仓库提交 + 推 gitee/gitcode master(提交前扫敏感内容) | `{status, commit, pushed:[{remote,ok,error}], hits, hint}` |
|
|
70
|
+
| `pkg_stats` | 同步 | npm 下载量(昨/7 天/30 天)+ latest 版本 + GitHub/Gitee/GitCode 热度 | `{ok, package, version, repo, npm:{lastDay,lastWeek,lastMonth,...}, github, gitee, gitcode, fetchedAt}` |
|
|
70
71
|
|
|
71
72
|
异步工具的范式(以后加长任务工具照这个写,细节见 `docs/经验-工具真异步与宿主同步await.md`):
|
|
72
73
|
|
|
@@ -80,6 +81,14 @@ startDetachedTask({ exec, kind: 'watch_read', hint: '已开始取数…', run: a
|
|
|
80
81
|
|
|
81
82
|
调用留痕统一落 `<记忆根>/toolkit/usage.jsonl`(同步工具按次记,异步工具记 `started` + 完成两条)。
|
|
82
83
|
|
|
84
|
+
`pkg_stats` 的三个实测注意点(1.5.42,写死在工具行为里):
|
|
85
|
+
|
|
86
|
+
- **npm 统计的 `end` 日期滞后约 2 天**——`last-day` 不是"今天"。所以三个窗口都把 `start`/`end` 原样带回,别把这数当当日实况。
|
|
87
|
+
- **GitHub 直连在本机不通**(`Recv failure: Connection was reset`),兜底走第三方代理 **gh-proxy.com**——该代理会看到你查询的仓库路径(`owner/repo` 会进它的访问日志);`github.source` 会标 `direct` / `gh-proxy`,不放心就把 `pkgStatsAllowGithubProxy` 设 `false`。
|
|
88
|
+
- **GitCode 没有匿名 API**(`private-token` 必需,400/401),`gitcode.stars/forks` 恒为 0 且 `unavailable` 写明原因;页面上的 star 数是异步渲染的 UI 数字,不作接口确证。**Gitee 的 `watchers_count` 是"关注数"**(与 GitHub 的 watchers 语义不同,本仓库实测 1)。
|
|
89
|
+
|
|
90
|
+
请求只走白名单域名(`api.npmjs.org` / `registry.npmjs.org` / `api.github.com` / `gh-proxy.com` / `gitee.com` / `gitcode.com`,精确主机名匹配),`repo`/`package` 参数做字符校验 + 逐段编码,整次调用 15 秒总预算。
|
|
91
|
+
|
|
83
92
|
- **续接(continuable)**:本体、小伙伴、检索员都是 continuable——DSH 重启后 `send_message` 一条消息即可冷唤醒续接;续接前 `list_agents` 现查 ID,别凭记忆敲(详见[更新日志](./CHANGELOG.md) 1.4.4 条目)。
|
|
84
93
|
|
|
85
94
|
## 文件
|
|
@@ -101,6 +110,7 @@ npm 包为平铺结构(仓库若保留 bundle/ 子目录,发布时把其内
|
|
|
101
110
|
- `lib/toolkit.js` — aiyayi-toolkit 工具包中间层插件(1.5.38;首批 3 工具:`toolkit_cmd` 只读命令白名单执行 / `toolkit_read` 文件探测 + 小文件读取 / `toolkit_write` 受限写入;调用留痕落 `<记忆根>/toolkit/usage.jsonl`;简单状态型查询本体直调、不派小伙伴。1.5.39 修复 type 数组 schema 导致三件套注册全败的问题,坑 #77;1.5.40 修执行输出对齐 output.schema——宿主对工具输出也做 schema 校验,条件性返回字段一律用约定值,坑 #78)
|
|
102
111
|
- `lib/toolkit-async.js` — aiyayi-toolkit 的**真异步能力**(1.5.41):`startDetachedTask()` 立刻返回 `{status:'started', taskId}`、把 `run()` 甩到下一轮宏任务;跑完(含失败/超时)经 `exec.agent.followup(createUserMessage(...))` 把结果作为一条消息注入会话,并有进程内 task 表可查。为什么走 followup 而不是 `ctx.jobs`:后者是 producer 侧能力,`preset-aiyayi` 本体没挂 `tool-jobs`。坑 #65(source 禁 undefined)/ #68(投递前让出宿主 publish 宏任务)/ #79(宿主同步 await 工具)的规避写法都收在这一个文件里
|
|
103
112
|
- `lib/toolkit-extra.js` — 1.5.41 新增的两个具体工具:`watch_read`(**异步**,手表取数,立刻返回 taskId,后台跑 `skg_probe/ble_direct/watch_read.py`,任务级总超时 180s,结果/超时/失败都推回会话)+ `mem_sync`(**同步**,记忆仓库 `git status --porcelain -z` → `git diff HEAD` 全文 + 未跟踪文件敏感内容扫描 → add/commit → 依次 push gitee/gitcode master;越界一律拒绝,坑 #80 的 quotepath 陷阱也在这里修)
|
|
113
|
+
- `lib/pkg-stats.js` — 1.5.42 新增的 `pkg_stats`(**同步**):npm 三个下载窗口(含 `start`/`end` 原样,npm 的 end 滞后约 2 天)+ registry 的 latest 版本与发布时间 + GitHub / Gitee / GitCode 的 star / fork / watcher / open issues。域名白名单(精确主机名)+ 参数逐段校验编码 + 15 秒总预算;某平台挂了只写进它自己的 `unavailable`,其余照常返回,绝不抛。
|
|
104
114
|
- `lib/feishu.js` — aiyayi-feishu 飞书桥接宿主插件(1.5.8 起;跨会话服务,长连接收消息、按指令路由到 aiyayi 会话、回发;凭读取记忆根 `feishu/config.json`)
|
|
105
115
|
- `lib/feishu-logic.js` — 飞书纯逻辑(路由/映射/文本抽取/三档复用决策/**长连接状态机**,无外部依赖,可单测;test/feishu-route.test.mjs、test/feishu-reuse-session.test.mjs、test/feishu-status.test.mjs 覆盖)
|
|
106
116
|
- `skills/feishu-setup/` — 内置技能(1.5.13 起随包自动同步到 DSH 技能根):飞书机器人安装/验证/排障全流程(含 2026-11-10 扫码接入改造说明;脚本 `scripts/create-bot.js` v5 等由技能同步维护)
|
package/cordis.patch.yml
CHANGED
|
@@ -225,6 +225,21 @@
|
|
|
225
225
|
# · mem_sync(同步,记忆仓库提交推双远端)——git status/diff 扫描敏感内容
|
|
226
226
|
# → add/commit(阿依娅伊 <aiyayi@local>)→ 依次 push gitee/gitcode master;
|
|
227
227
|
# 越界或命中密钥一律拒绝并回脱敏行号。
|
|
228
|
+
# 1.5.42 起再加一个同步工具(同样"几秒内完成"这一档):
|
|
229
|
+
# · pkg_stats(同步,查 npm 下载量与代码仓热度)——npm 三个下载窗口
|
|
230
|
+
# (last-day/week/month,**start/end 原样带回**:npm 的 end 滞后约 2 天,
|
|
231
|
+
# "last-day" 不是今天)+ registry 的 latest 版本与发布时间 + GitHub /
|
|
232
|
+
# Gitee / GitCode 的 star / fork / watcher / open issues。
|
|
233
|
+
# 只允许 https GET 到白名单域名(精确主机名):api.npmjs.org /
|
|
234
|
+
# registry.npmjs.org / api.github.com / gh-proxy.com / gitee.com / gitcode.com;
|
|
235
|
+
# repo/package 参数逐段字符校验 + 编码;整次调用 15 秒总预算。
|
|
236
|
+
# 某平台挂了只写进它自己那段的 unavailable,其余照常返回,绝不抛。
|
|
237
|
+
# ⚠ **gh-proxy.com 是第三方代理**(GitHub 直连在本机不通时的兜底):它会
|
|
238
|
+
# 看到你查询的仓库路径(owner/repo 进它的访问日志),不放心就设
|
|
239
|
+
# pkgStatsAllowGithubProxy: false 关掉这条兜底。
|
|
240
|
+
# ⚠ GitCode 无匿名 API(private-token 必需),stars/forks 恒为 0 且
|
|
241
|
+
# unavailable 写明原因;页面上的 star 数是 UI 数字,不作接口确证。
|
|
242
|
+
# ⚠ Gitee 的 watchers_count 是"关注数",语义与 GitHub watchers 不同。
|
|
228
243
|
- id: aiyayi-toolkit
|
|
229
244
|
name: 'dsh-aiyayi/toolkit'
|
|
230
245
|
config:
|
|
@@ -273,6 +288,19 @@
|
|
|
273
288
|
# - gitee
|
|
274
289
|
# - gitcode
|
|
275
290
|
# memBranch: master
|
|
291
|
+
# ── 1.5.42 新增项(同上:这里只写"本机需要显式给"的;以下全是代码默认值,
|
|
292
|
+
# 取消注释即生效,不改默认行为)──
|
|
293
|
+
# pkg_stats:默认查询目标(本体一般不用传参)。
|
|
294
|
+
# pkgStatsDefaultPackage: dsh-aiyayi
|
|
295
|
+
# pkgStatsDefaultRepo: BayiHY/dsh-aiyayi
|
|
296
|
+
# pkg_stats:整次调用总预算 / 单请求预算 / GitHub 直连快速失败预算(ms)。
|
|
297
|
+
# pkgStatsTimeoutMs: 15000
|
|
298
|
+
# pkgStatsRequestTimeoutMs: 8000
|
|
299
|
+
# pkgStatsGithubDirectTimeoutMs: 4000
|
|
300
|
+
# pkg_stats:GitHub 直连失败时是否允许走第三方代理 gh-proxy.com 兜底。
|
|
301
|
+
# ⚠ 该代理能看到你查询的仓库路径(owner/repo 进它的访问日志);
|
|
302
|
+
# 不放心就设 false(此后 GitHub 段只报"直连失败"原因)。
|
|
303
|
+
# pkgStatsAllowGithubProxy: true
|
|
276
304
|
- id: aiyayi-restrict
|
|
277
305
|
name: 'dsh-aiyayi/restrict'
|
|
278
306
|
- id: time-context
|
package/lib/own-tools.js
CHANGED
|
@@ -43,6 +43,9 @@ export const OWN_TOOLS = [
|
|
|
43
43
|
// 立刻返回 taskId,结果经 followup 推回会话)/ mem_sync(同步记忆仓库提交推双远端)。
|
|
44
44
|
'watch_read',
|
|
45
45
|
'mem_sync',
|
|
46
|
+
// 1.5.42:工具箱第三个具体工具——pkg_stats(同步查 npm 下载量 + 代码仓热度:
|
|
47
|
+
// GitHub / Gitee / GitCode,某平台挂了只影响它自己那段)。
|
|
48
|
+
'pkg_stats',
|
|
46
49
|
]
|
|
47
50
|
|
|
48
51
|
/** 宿主提供的、她该留着的对话与委派工具。retriever 1.3.0 起加入(派检索员)。 */
|
package/lib/pkg-stats.js
ADDED
|
@@ -0,0 +1,714 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* aiyayi-toolkit / `pkg_stats`(1.5.42 新增):查 npm 下载量 + 代码仓热度(**同步**)。
|
|
3
|
+
*
|
|
4
|
+
* 为什么同步:都是几个 HTTP GET,实测 0.3–4.5 秒;按 1.5.41 的分档原则(坑 #79:宿主
|
|
5
|
+
* agent loop 同步 await 工具),这种"几秒内出结果"的活直接同步返回最省事——不用 followup、
|
|
6
|
+
* 不用惦记 task 表。
|
|
7
|
+
*
|
|
8
|
+
* 各平台**实测事实**(2026-11-12 本机复核,见 docs/经验-宿主工具schema校验与feishu_bind自动绑定.md):
|
|
9
|
+
* · npm 统计 API(api.npmjs.org)可用,但 **end 日期滞后约 2 天**——`last-day` 不是"今天",
|
|
10
|
+
* 所以每个窗口都把 start/end 原样带回,不给调用方留"这数是今天的"的误读空间。
|
|
11
|
+
* · GitHub API **直连在本机不通**(curl `(35) Recv failure`、fetch `fetch failed`),
|
|
12
|
+
* 兜底走 `gh-proxy.com` 第三方代理;代理会限流(403 时原样带回 message)。
|
|
13
|
+
* · **GitCode 没有匿名 API**:`gitcode.com/api/v5/...` 返 400
|
|
14
|
+
* `Invalid header parameter: private-token, required`,`api.gitcode.com/api/v5/...` 返 401,
|
|
15
|
+
* 两者都要 private-token。页面上的 star/fork 是异步渲染的 UI 数字,不是接口确证,
|
|
16
|
+
* 本工具**不去抓页面**,一律把原因写进 `gitcode.unavailable`。
|
|
17
|
+
* · Gitee API 可用;注意 `watchers_count` 是"关注数"(本仓库 1),与 GitHub 的 watchers 语义不同。
|
|
18
|
+
* · npm registry 必须显式走 `registry.npmjs.org`(本机 .npmrc 默认指 npmmirror 镜像),
|
|
19
|
+
* 这里直接 HTTP GET,不 shell 调 npm。
|
|
20
|
+
*
|
|
21
|
+
* 安全(四层,都在本文件里):
|
|
22
|
+
* 1. **域名白名单**:只允许 https GET 到 api.npmjs.org / registry.npmjs.org / api.github.com /
|
|
23
|
+
* gh-proxy.com / gitee.com / gitcode.com;其他主机一律抛错、请求根本不发。
|
|
24
|
+
* 2. **参数字符校验**:owner / repo 段落只允许 `A-Za-z0-9._-`(且不许 `.`/`..`),
|
|
25
|
+
* npm 包名按 `[@scope/]name` 形态校验;拼接前再 `encodeURIComponent`,双重防注入。
|
|
26
|
+
* 3. **gh-proxy.com 是第三方代理**:它能看到你查询的仓库路径(owner/repo 会出现在它的
|
|
27
|
+
* 访问日志里)。只有 GitHub 直连失败时才用它,且可用 `pkgStatsAllowGithubProxy: false` 关掉。
|
|
28
|
+
* 4. 总量兜底:整次调用 15 秒总预算(`pkgStatsTimeoutMs`),单请求 ≤ 8 秒
|
|
29
|
+
* (`pkgStatsRequestTimeoutMs`);超时如实落进对应字段的 unavailable,绝不抛未捕获异常。
|
|
30
|
+
*
|
|
31
|
+
* 输出形状一律从 `shapePkgStatsOutput()` 单一出口归一(坑 #78 的教训):
|
|
32
|
+
* · type 只能单字符串;properties 全列进 required;additionalProperties:false 时不许返回未声明字段;
|
|
33
|
+
* · 可空语义用**约定值**(空串 / 0 / false)承担,绝不用 null 或"字段缺失";
|
|
34
|
+
* · 取不到的项一律写 `unavailable: "原因"`,不编、不静默吞。
|
|
35
|
+
*/
|
|
36
|
+
|
|
37
|
+
const TEXT_BLOCK = (text) => [{ type: 'text', text }]
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* 可访问的域名白名单(只允许 https GET,**精确主机名匹配**,子域不自动放行)。
|
|
41
|
+
* 这份清单是任务书钦定的六条,一条不多——所以 GitCode 那一路只能打
|
|
42
|
+
* `gitcode.com`(主站路径),**打不到它真正在用的 `api.gitcode.com`**
|
|
43
|
+
* (后者不在白名单里,见 collectGitcode 的注释)。宁可少一条数据也不私自放宽白名单。
|
|
44
|
+
*/
|
|
45
|
+
export const ALLOWED_HOSTS = Object.freeze([
|
|
46
|
+
'api.npmjs.org',
|
|
47
|
+
'registry.npmjs.org',
|
|
48
|
+
'api.github.com',
|
|
49
|
+
'gh-proxy.com', // 第三方代理,见文件头安全第 3 条
|
|
50
|
+
'gitee.com',
|
|
51
|
+
'gitcode.com',
|
|
52
|
+
])
|
|
53
|
+
|
|
54
|
+
const ALLOWED_HOST_SET = new Set(ALLOWED_HOSTS)
|
|
55
|
+
|
|
56
|
+
/** 统一 UA(npm/GitHub 都要求带 UA,否则可能 403)。 */
|
|
57
|
+
const USER_AGENT = 'dsh-aiyayi-pkg-stats (+https://github.com/BayiHY/dsh-aiyayi)'
|
|
58
|
+
|
|
59
|
+
/** 默认值(也可被 cordis.patch.yml 的 config 覆盖)。 */
|
|
60
|
+
export const PKG_STATS_DEFAULTS = Object.freeze({
|
|
61
|
+
pkgStatsDefaultPackage: 'dsh-aiyayi',
|
|
62
|
+
pkgStatsDefaultRepo: 'BayiHY/dsh-aiyayi',
|
|
63
|
+
pkgStatsTimeoutMs: 15000,
|
|
64
|
+
pkgStatsRequestTimeoutMs: 8000,
|
|
65
|
+
pkgStatsAllowGithubProxy: true,
|
|
66
|
+
// GitHub 直连快速失败预算:本机直连是 reset,给 4 秒足够判死,别把 15 秒预算烧在它身上。
|
|
67
|
+
pkgStatsGithubDirectTimeoutMs: 4000,
|
|
68
|
+
})
|
|
69
|
+
|
|
70
|
+
/* ================================================================== *
|
|
71
|
+
* 一、URL 白名单 + 参数校验(防注入)
|
|
72
|
+
* ================================================================== */
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* 断言 URL 只指向白名单主机(并只允许 https、不带凭据)。
|
|
76
|
+
* 不合规直接抛——请求根本不会发出去,这是白名单的落点。
|
|
77
|
+
* @returns {URL}
|
|
78
|
+
*/
|
|
79
|
+
export function assertAllowedUrl(rawUrl) {
|
|
80
|
+
let url
|
|
81
|
+
try {
|
|
82
|
+
url = new URL(String(rawUrl ?? ''))
|
|
83
|
+
} catch {
|
|
84
|
+
throw new Error(`非法 URL:${String(rawUrl ?? '')}`)
|
|
85
|
+
}
|
|
86
|
+
if (url.protocol !== 'https:') throw new Error(`只允许 https,拒绝 ${url.protocol}//${url.host}`)
|
|
87
|
+
if (url.username || url.password) throw new Error('URL 不允许携带凭据')
|
|
88
|
+
const host = url.hostname.toLowerCase()
|
|
89
|
+
if (!ALLOWED_HOST_SET.has(host)) {
|
|
90
|
+
throw new Error(`域名不在白名单:${host}(只允许 ${ALLOWED_HOSTS.join(' / ')})`)
|
|
91
|
+
}
|
|
92
|
+
return url
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** 单段名字校验:只允许字母数字 `-_.`,不许空、不许 `.`/`..`、限长 100。
|
|
96
|
+
* **不 trim 单段**:`owner/ name` 这种带内部空格的一律拒绝,不做"悄悄改成 owner/name"
|
|
97
|
+
* 的静默改写(参数被改写比被拒绝更难查)。整体参数的空白在 normalizePkgStatsArgs 里去掉。 */
|
|
98
|
+
export function assertSafeSegment(value, label = 'segment') {
|
|
99
|
+
const text = String(value ?? '')
|
|
100
|
+
if (!text) throw new Error(`${label} 不能为空`)
|
|
101
|
+
if (text.length > 100) throw new Error(`${label} 过长:${text.length} 字符`)
|
|
102
|
+
if (text === '.' || text === '..') throw new Error(`${label} 不允许是 ${text}`)
|
|
103
|
+
if (!/^[A-Za-z0-9._-]+$/.test(text)) {
|
|
104
|
+
throw new Error(`${label} 含非法字符:${text}(只允许字母数字 - _ .,且不许带空白)`)
|
|
105
|
+
}
|
|
106
|
+
return text
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** npm 包名校验:`name` 或 `@scope/name`,两段各自只允许 `A-Za-z0-9._~-`(npm 允许 ~)。 */
|
|
110
|
+
export function assertSafePackageName(value) {
|
|
111
|
+
const text = String(value ?? '').trim()
|
|
112
|
+
if (!text) throw new Error('package 不能为空')
|
|
113
|
+
if (text.length > 140) throw new Error(`package 过长:${text.length} 字符`)
|
|
114
|
+
const parts = text.split('/')
|
|
115
|
+
if (parts.length > 2) throw new Error(`package 形态非法:${text}`)
|
|
116
|
+
const check = (part, label) => {
|
|
117
|
+
if (!part) throw new Error(`package 形态非法:${text}(${label} 为空)`)
|
|
118
|
+
if (!/^[A-Za-z0-9._~-]+$/.test(part)) throw new Error(`package 含非法字符:${text}`)
|
|
119
|
+
}
|
|
120
|
+
if (parts.length === 2) {
|
|
121
|
+
if (!parts[0].startsWith('@')) throw new Error(`package 形态非法:${text}(带 / 时必须是 @scope/name)`)
|
|
122
|
+
check(parts[0].slice(1), 'scope')
|
|
123
|
+
check(parts[1], 'name')
|
|
124
|
+
} else {
|
|
125
|
+
check(parts[0], 'name')
|
|
126
|
+
}
|
|
127
|
+
return text
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/** npm API 路径:`@scope/name` → `@scope/name`(逐段编码,别把 / 也编码掉)。 */
|
|
131
|
+
export function encodePackagePath(pkgName) {
|
|
132
|
+
return String(pkgName).split('/').map((part) => encodeURIComponent(part)).join('/')
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/** 参数归一:缺省走 config → 内置默认;给了就校验。 */
|
|
136
|
+
export function normalizePkgStatsArgs(args = {}, cfg = {}) {
|
|
137
|
+
const pkgRaw = String(args?.package ?? '').trim() || String(cfg?.pkgStatsDefaultPackage ?? '').trim() || PKG_STATS_DEFAULTS.pkgStatsDefaultPackage
|
|
138
|
+
const repoRaw = String(args?.repo ?? '').trim() || String(cfg?.pkgStatsDefaultRepo ?? '').trim() || PKG_STATS_DEFAULTS.pkgStatsDefaultRepo
|
|
139
|
+
const pkg = assertSafePackageName(pkgRaw)
|
|
140
|
+
const parts = repoRaw.split('/').filter((part) => part !== '')
|
|
141
|
+
if (parts.length !== 2) throw new Error(`repo 形态非法:${repoRaw}(应形如 owner/name)`)
|
|
142
|
+
const [owner, name] = parts
|
|
143
|
+
// 注意:owner/name 这里**不 trim**——带内部空白的写法直接由 assertSafeSegment 拒掉,
|
|
144
|
+
// 免得 `owner/ name` 被悄悄改成 `owner/name` 发出去(参数静默改写比报错更难查)。
|
|
145
|
+
return {
|
|
146
|
+
package: pkg,
|
|
147
|
+
repo: `${assertSafeSegment(owner, 'repo.owner')}/${assertSafeSegment(name, 'repo.name')}`,
|
|
148
|
+
owner: assertSafeSegment(owner, 'repo.owner'),
|
|
149
|
+
name: assertSafeSegment(name, 'repo.name'),
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/* ================================================================== *
|
|
154
|
+
* 二、HTTP:单请求超时 + 错误体原样带回
|
|
155
|
+
* ================================================================== */
|
|
156
|
+
|
|
157
|
+
/** 从错误里判断是不是超时(AbortSignal.timeout 抛 TimeoutError;手工 abort 抛 AbortError)。 */
|
|
158
|
+
function isTimeoutError(error) {
|
|
159
|
+
const name = String(error?.name ?? '')
|
|
160
|
+
return name === 'TimeoutError' || name === 'AbortError' || /aborted due to timeout/i.test(String(error?.message ?? ''))
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/** 错误一句话(含 timeout 归类)。 */
|
|
164
|
+
export function describeError(error, budgetMs = 0) {
|
|
165
|
+
if (isTimeoutError(error)) return `超时(${budgetMs || '?'}ms 内没响应)`
|
|
166
|
+
const message = String(error?.message ?? error ?? '').trim()
|
|
167
|
+
const cause = String(error?.cause?.code ?? error?.cause?.message ?? '').trim()
|
|
168
|
+
const base = message || '未知错误'
|
|
169
|
+
if (cause && !base.includes(cause)) return `${base}(${cause})`
|
|
170
|
+
return base
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/** HTTP 失败一句话:状态码 + 服务端 message 原文(403 限流要能看见原因)。
|
|
174
|
+
* 兼容各家不同的错误字段名:`message`(GitHub/Gitee)/ `error`(npm)/ `error_message`(GitCode)。
|
|
175
|
+
* `status:0` 表示请求在传输层就挂了(连不上/被 reset/超时),此时**没有状态码**,
|
|
176
|
+
* 要把 `error` 里的底层原因(如 ECONNRESET)原样带上,否则只剩一句无用的 "HTTP 0"。 */
|
|
177
|
+
export function describeHttpFailure(response, label) {
|
|
178
|
+
const prefix = label ? `${label}:` : ''
|
|
179
|
+
const status = Number(response?.status) || 0
|
|
180
|
+
let detail = ''
|
|
181
|
+
if (response?.json && typeof response.json === 'object') {
|
|
182
|
+
const json = response.json
|
|
183
|
+
detail = String(json.message ?? json.error ?? json.error_message ?? json.msg ?? '').trim()
|
|
184
|
+
}
|
|
185
|
+
if (!detail) detail = String(response?.text ?? '').slice(0, 300).replace(/\s+/g, ' ').trim()
|
|
186
|
+
if (status === 0) {
|
|
187
|
+
const reason = String(response?.error ?? '').trim()
|
|
188
|
+
// `error` 是 fetchJson 兜住的网络层原因(可能是 describeError 的中文描述,也可能只是 HTTP 0)
|
|
189
|
+
const base = reason && reason !== 'HTTP 0' ? reason : '请求未拿到 HTTP 响应'
|
|
190
|
+
return `${prefix}${base}${detail ? `:${detail}` : ''}`
|
|
191
|
+
}
|
|
192
|
+
return `${prefix}HTTP ${status}${detail ? `:${detail}` : ''}`
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/**
|
|
196
|
+
* 发一个 GET 并尽力解析 JSON。
|
|
197
|
+
* @param {string} url
|
|
198
|
+
* @param {{deadline:number, requestTimeoutMs:number, fetchImpl:Function, headers?:object}} options
|
|
199
|
+
* @returns {Promise<{ok:boolean, status:number, text:string, json:any, error:string}>}
|
|
200
|
+
* 网络层/超时失败时 `error` 非空且 `ok:false`(**不抛**,调用方按平台归类)。
|
|
201
|
+
*/
|
|
202
|
+
export async function fetchJson(url, options = {}) {
|
|
203
|
+
const { deadline = Date.now() + 15000, requestTimeoutMs = 8000, fetchImpl = globalThis.fetch, headers = {} } = options
|
|
204
|
+
assertAllowedUrl(url) // 白名单不符直接抛:这是唯一会抛的分支(配置/参数错,属于调用方错误)
|
|
205
|
+
const remaining = deadline - Date.now()
|
|
206
|
+
if (remaining <= 0) return { ok: false, status: 0, text: '', json: null, error: '总超时(15 秒预算已用完,请求未发)' }
|
|
207
|
+
const budgetMs = Math.max(500, Math.min(requestTimeoutMs, remaining))
|
|
208
|
+
try {
|
|
209
|
+
const response = await fetchImpl(url, {
|
|
210
|
+
method: 'GET',
|
|
211
|
+
redirect: 'follow',
|
|
212
|
+
headers: { accept: 'application/json', 'user-agent': USER_AGENT, ...headers },
|
|
213
|
+
signal: AbortSignal.timeout(budgetMs),
|
|
214
|
+
})
|
|
215
|
+
let text = ''
|
|
216
|
+
try {
|
|
217
|
+
text = await response.text()
|
|
218
|
+
} catch (error) {
|
|
219
|
+
return { ok: false, status: response?.status ?? 0, text: '', json: null, error: describeError(error, budgetMs) }
|
|
220
|
+
}
|
|
221
|
+
let json = null
|
|
222
|
+
if (text) {
|
|
223
|
+
try {
|
|
224
|
+
json = JSON.parse(text)
|
|
225
|
+
} catch {
|
|
226
|
+
json = null
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
const ok = response?.ok === true
|
|
230
|
+
return { ok, status: response?.status ?? 0, text, json, error: ok ? '' : `HTTP ${response?.status ?? '?'}` }
|
|
231
|
+
} catch (error) {
|
|
232
|
+
return { ok: false, status: 0, text: '', json: null, error: describeError(error, budgetMs) }
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/**
|
|
237
|
+
* 总预算兜底:就算注进来的 fetch 完全不看 signal,也不让整次调用超过 15 秒。
|
|
238
|
+
* 超时返回 `{timedOut:true}`,不抛。
|
|
239
|
+
*
|
|
240
|
+
* **这个定时器故意不 `unref()`**:它是有界的一次性计时(最长 15 秒,`finally` 里必清),
|
|
241
|
+
* 而且当某个 fetch 永不 resolve 时,它往往是**唯一还撑着事件循环的东西**——
|
|
242
|
+
* unref 掉会让 Node 认为没事可做、直接退出,表现是 `unsettled top-level await`
|
|
243
|
+
* 加一个退出码 0(单测当场踩到过)。有界计时器不 unref 不会漏活进程。
|
|
244
|
+
*/
|
|
245
|
+
export function withBudget(promise, deadline, hint = '总超时') {
|
|
246
|
+
const remaining = Math.max(0, deadline - Date.now())
|
|
247
|
+
let timer = null
|
|
248
|
+
const timeout = new Promise((done) => {
|
|
249
|
+
timer = setTimeout(() => done({ timedOut: true, error: `${hint}(${remaining}ms 预算已用完)` }), remaining)
|
|
250
|
+
})
|
|
251
|
+
return Promise.race([
|
|
252
|
+
Promise.resolve(promise).catch((error) => ({ timedOut: false, error: describeError(error) })),
|
|
253
|
+
timeout,
|
|
254
|
+
]).finally(() => {
|
|
255
|
+
if (timer) clearTimeout(timer)
|
|
256
|
+
})
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
/* ================================================================== *
|
|
260
|
+
* 三、各平台采集(每个都自己吞错,只回 unavailable)
|
|
261
|
+
* ================================================================== */
|
|
262
|
+
|
|
263
|
+
const NPM_WINDOWS = [
|
|
264
|
+
['lastDay', 'last-day'],
|
|
265
|
+
['lastWeek', 'last-week'],
|
|
266
|
+
['lastMonth', 'last-month'],
|
|
267
|
+
]
|
|
268
|
+
|
|
269
|
+
function emptyWindow() {
|
|
270
|
+
return { downloads: 0, start: '', end: '', unavailable: '' }
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
/** npm 三个下载窗口(逐窗口独立成败,一个失败不影响另外两个)。 */
|
|
274
|
+
export async function collectNpmDownloads(pkg, options = {}) {
|
|
275
|
+
const results = await Promise.all(NPM_WINDOWS.map(async ([key, window]) => {
|
|
276
|
+
const url = `https://api.npmjs.org/downloads/point/${window}/${encodePackagePath(pkg)}`
|
|
277
|
+
const res = await fetchJson(url, options)
|
|
278
|
+
if (!res.ok) {
|
|
279
|
+
return [key, { ...emptyWindow(), unavailable: describeHttpFailure({ ...res, json: res.json }, `npm ${window}`) }]
|
|
280
|
+
}
|
|
281
|
+
const downloads = res.json?.downloads
|
|
282
|
+
if (!Number.isFinite(downloads)) {
|
|
283
|
+
return [key, { ...emptyWindow(), unavailable: `npm ${window}:返回里没有 downloads 字段` }]
|
|
284
|
+
}
|
|
285
|
+
// start/end 原样带回:npm 的 end 日期滞后约 2 天,"last-day" 不是今天(实测坑)。
|
|
286
|
+
return [key, {
|
|
287
|
+
downloads: Math.max(0, Math.trunc(downloads)),
|
|
288
|
+
start: String(res.json?.start ?? ''),
|
|
289
|
+
end: String(res.json?.end ?? ''),
|
|
290
|
+
unavailable: '',
|
|
291
|
+
}]
|
|
292
|
+
}))
|
|
293
|
+
return Object.fromEntries(results)
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
/** npm registry:latest 版本号 + 发布时间(直接 HTTP GET,不 shell 调 npm)。 */
|
|
297
|
+
export async function collectNpmVersion(pkg, options = {}) {
|
|
298
|
+
const url = `https://registry.npmjs.org/${encodePackagePath(pkg)}`
|
|
299
|
+
const res = await fetchJson(url, { ...options, requestTimeoutMs: Math.max(options.requestTimeoutMs ?? 8000, 8000) })
|
|
300
|
+
if (!res.ok) return { version: '', publishedAt: '', unavailable: describeHttpFailure(res, 'npm registry') }
|
|
301
|
+
const latest = String(res.json?.['dist-tags']?.latest ?? '').trim()
|
|
302
|
+
if (!latest) return { version: '', publishedAt: '', unavailable: 'npm registry:返回里没有 dist-tags.latest' }
|
|
303
|
+
const publishedAt = String(res.json?.time?.[latest] ?? '').trim()
|
|
304
|
+
return { version: latest, publishedAt, unavailable: publishedAt ? '' : 'npm registry:没有该版本的发布时间' }
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
function shapeRepoCounts(json) {
|
|
308
|
+
const num = (value) => (Number.isFinite(value) ? Math.max(0, Math.trunc(value)) : 0)
|
|
309
|
+
// 主字段按 GitHub/Gitee 的 `*_count` 命名;同时容忍简写(`stars`/`forks`/`watchers`),
|
|
310
|
+
// 免得某个平台换个字段名就整段归 0(GitCode 这类平台文档不一,留个兜底)。
|
|
311
|
+
return {
|
|
312
|
+
stars: num(json?.stargazers_count ?? json?.stars),
|
|
313
|
+
forks: num(json?.forks_count ?? json?.forks),
|
|
314
|
+
watchers: num(json?.watchers_count ?? json?.subscribers_count ?? json?.watchers),
|
|
315
|
+
openIssues: num(json?.open_issues_count ?? json?.open_issues ?? json?.issues),
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
/**
|
|
320
|
+
* GitHub:直连 api.github.com 优先,失败走 gh-proxy.com 第三方代理。
|
|
321
|
+
*
|
|
322
|
+
* ⚠ **gh-proxy.com 是第三方代理**:把 `https://api.github.com/repos/{owner}/{repo}` 整个路径
|
|
323
|
+
* 交给它转发,等于把你查询的仓库路径暴露给这个第三方(会进它的访问日志)。只在本机直连
|
|
324
|
+
* 失败时用它,`pkgStatsAllowGithubProxy: false` 可关掉这条兜底。
|
|
325
|
+
*/
|
|
326
|
+
export async function collectGithub(owner, name, options = {}) {
|
|
327
|
+
const { cfg = {}, ...fetchOptions } = options
|
|
328
|
+
const allowProxy = cfg?.pkgStatsAllowGithubProxy !== false
|
|
329
|
+
const directTimeout = Number(cfg?.pkgStatsGithubDirectTimeoutMs) || PKG_STATS_DEFAULTS.pkgStatsGithubDirectTimeoutMs
|
|
330
|
+
const directUrl = `https://api.github.com/repos/${owner}/${name}`
|
|
331
|
+
const direct = await fetchJson(directUrl, { ...fetchOptions, requestTimeoutMs: Math.min(fetchOptions.requestTimeoutMs ?? 8000, directTimeout) })
|
|
332
|
+
if (direct.ok) {
|
|
333
|
+
return { ...shapeRepoCounts(direct.json), unavailable: '', source: 'direct' }
|
|
334
|
+
}
|
|
335
|
+
const directReason = describeHttpFailure(direct, 'api.github.com')
|
|
336
|
+
|
|
337
|
+
if (!allowProxy) {
|
|
338
|
+
return { stars: 0, forks: 0, watchers: 0, openIssues: 0, unavailable: `直连失败(${directReason});按配置 pkgStatsAllowGithubProxy=false 不走代理`, source: '' }
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
// 代理形态:把 GitHub 的 URL 原样作为路径段交给 gh-proxy.com。
|
|
342
|
+
const proxyUrl = `https://gh-proxy.com/https://api.github.com/repos/${owner}/${name}`
|
|
343
|
+
const proxied = await fetchJson(proxyUrl, fetchOptions)
|
|
344
|
+
if (proxied.ok) {
|
|
345
|
+
return { ...shapeRepoCounts(proxied.json), unavailable: '', source: 'gh-proxy' }
|
|
346
|
+
}
|
|
347
|
+
const proxyReason = describeHttpFailure(proxied, 'gh-proxy.com')
|
|
348
|
+
return {
|
|
349
|
+
stars: 0,
|
|
350
|
+
forks: 0,
|
|
351
|
+
watchers: 0,
|
|
352
|
+
openIssues: 0,
|
|
353
|
+
unavailable: `两路都失败:直连(${directReason});第三方代理 gh-proxy.com(${proxyReason})`,
|
|
354
|
+
source: '',
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
/** Gitee(可用;watchers_count 语义是"关注数",与 GitHub watchers 不同)。 */
|
|
359
|
+
export async function collectGitee(owner, name, options = {}) {
|
|
360
|
+
const url = `https://gitee.com/api/v5/repos/${owner}/${name}`
|
|
361
|
+
const res = await fetchJson(url, options)
|
|
362
|
+
if (!res.ok) {
|
|
363
|
+
return { stars: 0, forks: 0, watchers: 0, openIssues: 0, unavailable: describeHttpFailure(res, 'gitee') }
|
|
364
|
+
}
|
|
365
|
+
return { ...shapeRepoCounts(res.json), unavailable: '' }
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
/**
|
|
369
|
+
* GitCode:**没有匿名 API**(实测 `gitcode.com/api/v5/...` 返 400
|
|
370
|
+
* `Invalid header parameter: private-token, required`;`api.gitcode.com/api/v5/...` 返 401,
|
|
371
|
+
* 两者都要 private-token)。
|
|
372
|
+
*
|
|
373
|
+
* **为什么打 gitcode.com 而不是 api.gitcode.com**:白名单是任务书钦定的六条,
|
|
374
|
+
* `api.gitcode.com` 不在其中(精确主机名匹配,不放子域)。所以这一路走主站路径
|
|
375
|
+
* `gitcode.com/api/v5/...`——它在白名单内,且服务端会把**真实原因原话**带回来
|
|
376
|
+
* (error_message),正好满足"取不到就如实报原因"的要求。
|
|
377
|
+
*
|
|
378
|
+
* 这里仍然发一次请求的意义:如果哪天 GitCode 开了匿名访问,这行代码会自动接上;
|
|
379
|
+
* 页面上看到的 star/fork 是异步渲染的 **UI 数字**,不是接口确证,本工具不抓页面。
|
|
380
|
+
*/
|
|
381
|
+
export async function collectGitcode(owner, name, options = {}) {
|
|
382
|
+
const url = `https://gitcode.com/api/v5/repos/${owner}/${name}`
|
|
383
|
+
const res = await fetchJson(url, options)
|
|
384
|
+
if (res.ok) {
|
|
385
|
+
const counts = shapeRepoCounts(res.json)
|
|
386
|
+
return { stars: counts.stars, forks: counts.forks, unavailable: '' }
|
|
387
|
+
}
|
|
388
|
+
const reason = describeHttpFailure(res, 'gitcode.com/api/v5')
|
|
389
|
+
const hint = res.status === 401 || res.status === 400
|
|
390
|
+
? '(GitCode 无匿名 API,需 private-token;本工具不带任何凭据,故取不到。页面上的 star/fork 是 UI 数字,不作接口确证)'
|
|
391
|
+
: ''
|
|
392
|
+
return { stars: 0, forks: 0, unavailable: `${reason}${hint}` }
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
/* ================================================================== *
|
|
396
|
+
* 四、主流程
|
|
397
|
+
* ================================================================== */
|
|
398
|
+
|
|
399
|
+
/** 平台级不可用原因(npm 整体失败时给)。 */
|
|
400
|
+
function firstUnavailable(list) {
|
|
401
|
+
for (const item of list) if (item?.unavailable) return item.unavailable
|
|
402
|
+
return ''
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
/**
|
|
406
|
+
* pkg_stats 主流程(同步返回,内部并发请求,总预算 15 秒)。
|
|
407
|
+
* @param {{package?:string, repo?:string}} args
|
|
408
|
+
* @param {{cfg?:object, logUsage?:Function, warn?:Function, fetchImpl?:Function, now?:Function}} deps
|
|
409
|
+
* @returns {Promise<object>} 恒为 shapePkgStatsOutput 归一的合法形状;除参数非法外不抛。
|
|
410
|
+
*/
|
|
411
|
+
export async function executePkgStats(args = {}, deps = {}) {
|
|
412
|
+
const { cfg = {}, logUsage, warn, fetchImpl = globalThis.fetch, now = () => new Date() } = deps
|
|
413
|
+
const startedAt = now()
|
|
414
|
+
const rec = {
|
|
415
|
+
ts: startedAt.toISOString(),
|
|
416
|
+
tool: 'pkg_stats',
|
|
417
|
+
args: '',
|
|
418
|
+
status: 'success',
|
|
419
|
+
denyReason: '',
|
|
420
|
+
durationMs: 0,
|
|
421
|
+
outBytes: 0,
|
|
422
|
+
truncated: false,
|
|
423
|
+
ok: false,
|
|
424
|
+
exitCode: null,
|
|
425
|
+
error: '',
|
|
426
|
+
}
|
|
427
|
+
const started = Date.now()
|
|
428
|
+
|
|
429
|
+
let normalized
|
|
430
|
+
try {
|
|
431
|
+
normalized = normalizePkgStatsArgs(args, cfg)
|
|
432
|
+
} catch (error) {
|
|
433
|
+
const message = String(error?.message ?? error)
|
|
434
|
+
rec.status = 'denied'
|
|
435
|
+
rec.denyReason = message
|
|
436
|
+
rec.args = `package=${String(args?.package ?? '')} repo=${String(args?.repo ?? '')}`.slice(0, 200)
|
|
437
|
+
rec.error = message
|
|
438
|
+
rec.durationMs = Date.now() - started
|
|
439
|
+
try {
|
|
440
|
+
logUsage?.(rec)
|
|
441
|
+
} catch {
|
|
442
|
+
/* 留痕自己不该抛 */
|
|
443
|
+
}
|
|
444
|
+
return shapePkgStatsOutput({
|
|
445
|
+
ok: false,
|
|
446
|
+
package: '',
|
|
447
|
+
version: '',
|
|
448
|
+
repo: '',
|
|
449
|
+
error: `参数不合法:${message}`,
|
|
450
|
+
fetchedAt: startedAt.toISOString(),
|
|
451
|
+
})
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
const timeoutMs = Number(cfg?.pkgStatsTimeoutMs) || PKG_STATS_DEFAULTS.pkgStatsTimeoutMs
|
|
455
|
+
const requestTimeoutMs = Number(cfg?.pkgStatsRequestTimeoutMs) || PKG_STATS_DEFAULTS.pkgStatsRequestTimeoutMs
|
|
456
|
+
const deadline = started + timeoutMs
|
|
457
|
+
const fetchOptions = { deadline, requestTimeoutMs, fetchImpl }
|
|
458
|
+
rec.args = `package=${normalized.package} repo=${normalized.repo}`
|
|
459
|
+
|
|
460
|
+
// 各平台**并发**跑:总耗时 ≈ 最慢那个,而不是七次请求相加。
|
|
461
|
+
const [windowResults, registryResult, githubResult, giteeResult, gitcodeResult] = await Promise.all([
|
|
462
|
+
withBudget(collectNpmDownloads(normalized.package, fetchOptions), deadline, '总超时(npm 下载量)'),
|
|
463
|
+
withBudget(collectNpmVersion(normalized.package, fetchOptions), deadline, '总超时(npm registry)'),
|
|
464
|
+
withBudget(collectGithub(normalized.owner, normalized.name, { ...fetchOptions, cfg }), deadline, '总超时(GitHub)'),
|
|
465
|
+
withBudget(collectGitee(normalized.owner, normalized.name, fetchOptions), deadline, '总超时(Gitee)'),
|
|
466
|
+
withBudget(collectGitcode(normalized.owner, normalized.name, fetchOptions), deadline, '总超时(GitCode)'),
|
|
467
|
+
])
|
|
468
|
+
|
|
469
|
+
// 每个分支都要能落成"合法的空壳 + unavailable",绝不因为某个平台炸掉就少字段。
|
|
470
|
+
const windows = windowResults?.timedOut
|
|
471
|
+
? Object.fromEntries(NPM_WINDOWS.map(([key]) => [key, { ...emptyWindow(), unavailable: windowResults.error }]))
|
|
472
|
+
: (windowResults ?? {})
|
|
473
|
+
const lastDay = windows.lastDay ?? { ...emptyWindow(), unavailable: 'npm:未取到 last-day' }
|
|
474
|
+
const lastWeek = windows.lastWeek ?? { ...emptyWindow(), unavailable: 'npm:未取到 last-week' }
|
|
475
|
+
const lastMonth = windows.lastMonth ?? { ...emptyWindow(), unavailable: 'npm:未取到 last-month' }
|
|
476
|
+
|
|
477
|
+
const npmVersion = registryResult?.timedOut
|
|
478
|
+
? { version: '', publishedAt: '', unavailable: registryResult.error }
|
|
479
|
+
: (registryResult ?? { version: '', publishedAt: '', unavailable: 'npm registry:未取到' })
|
|
480
|
+
const github = githubResult?.timedOut
|
|
481
|
+
? { stars: 0, forks: 0, watchers: 0, openIssues: 0, unavailable: githubResult.error, source: '' }
|
|
482
|
+
: (githubResult ?? { stars: 0, forks: 0, watchers: 0, openIssues: 0, unavailable: 'GitHub:未取到', source: '' })
|
|
483
|
+
const gitee = giteeResult?.timedOut
|
|
484
|
+
? { stars: 0, forks: 0, watchers: 0, openIssues: 0, unavailable: giteeResult.error }
|
|
485
|
+
: (giteeResult ?? { stars: 0, forks: 0, watchers: 0, openIssues: 0, unavailable: 'Gitee:未取到' })
|
|
486
|
+
const gitcode = gitcodeResult?.timedOut
|
|
487
|
+
? { stars: 0, forks: 0, unavailable: gitcodeResult.error }
|
|
488
|
+
: (gitcodeResult ?? { stars: 0, forks: 0, unavailable: 'GitCode:未取到' })
|
|
489
|
+
|
|
490
|
+
const npmUnavailable = firstUnavailable([lastDay, lastWeek, lastMonth])
|
|
491
|
+
const anyNpmWindow = !lastDay.unavailable || !lastWeek.unavailable || !lastMonth.unavailable
|
|
492
|
+
const ok = anyNpmWindow || !npmVersion.unavailable || !github.unavailable || !gitee.unavailable
|
|
493
|
+
|
|
494
|
+
const errorParts = []
|
|
495
|
+
if (!ok) {
|
|
496
|
+
errorParts.push(`全部平台都没取到:npm(${npmUnavailable || 'registry 失败'})、GitHub(${github.unavailable || '失败'})、Gitee(${gitee.unavailable || '失败'})`)
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
const fetchedAt = new Date().toISOString()
|
|
500
|
+
const result = shapePkgStatsOutput({
|
|
501
|
+
ok,
|
|
502
|
+
package: normalized.package,
|
|
503
|
+
version: npmVersion.version,
|
|
504
|
+
repo: normalized.repo,
|
|
505
|
+
npm: {
|
|
506
|
+
lastDay,
|
|
507
|
+
lastWeek,
|
|
508
|
+
lastMonth,
|
|
509
|
+
versionPublishedAt: npmVersion.publishedAt,
|
|
510
|
+
unavailable: anyNpmWindow ? '' : `npm 下载量全部失败:${npmUnavailable || '未知原因'}`,
|
|
511
|
+
},
|
|
512
|
+
github,
|
|
513
|
+
gitee,
|
|
514
|
+
gitcode,
|
|
515
|
+
fetchedAt,
|
|
516
|
+
error: errorParts.join(';'),
|
|
517
|
+
})
|
|
518
|
+
|
|
519
|
+
rec.status = ok ? 'success' : 'error'
|
|
520
|
+
rec.ok = ok
|
|
521
|
+
rec.error = result.error
|
|
522
|
+
rec.outBytes = JSON.stringify(result).length
|
|
523
|
+
rec.durationMs = Date.now() - started
|
|
524
|
+
try {
|
|
525
|
+
logUsage?.(rec)
|
|
526
|
+
} catch {
|
|
527
|
+
/* 留痕失败不影响结果 */
|
|
528
|
+
}
|
|
529
|
+
try {
|
|
530
|
+
warn?.(`aiyayi-toolkit: pkg_stats ${result.package}@${result.version || '?'} ok=${ok} ${rec.durationMs}ms`)
|
|
531
|
+
} catch {
|
|
532
|
+
/* logger 缺了就算了 */
|
|
533
|
+
}
|
|
534
|
+
return result
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
/* ================================================================== *
|
|
538
|
+
* 五、输出归一 + schema
|
|
539
|
+
* ================================================================== */
|
|
540
|
+
|
|
541
|
+
function shapeWindow(raw) {
|
|
542
|
+
const downloads = Number.isFinite(raw?.downloads) ? Math.max(0, Math.trunc(raw.downloads)) : 0
|
|
543
|
+
return {
|
|
544
|
+
downloads,
|
|
545
|
+
start: String(raw?.start ?? ''),
|
|
546
|
+
end: String(raw?.end ?? ''),
|
|
547
|
+
unavailable: String(raw?.unavailable ?? ''),
|
|
548
|
+
}
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
function shapeCount(raw, key) {
|
|
552
|
+
const value = raw?.[key]
|
|
553
|
+
return Number.isFinite(value) ? Math.max(0, Math.trunc(value)) : 0
|
|
554
|
+
}
|
|
555
|
+
|
|
556
|
+
/** pkg_stats 输出归一:字段与 PKG_STATS_SCHEMA.output.schema 一一对应。 */
|
|
557
|
+
export function shapePkgStatsOutput(raw = {}) {
|
|
558
|
+
const npm = raw?.npm ?? {}
|
|
559
|
+
return {
|
|
560
|
+
ok: raw?.ok === true,
|
|
561
|
+
package: String(raw?.package ?? ''),
|
|
562
|
+
version: String(raw?.version ?? ''),
|
|
563
|
+
repo: String(raw?.repo ?? ''),
|
|
564
|
+
npm: {
|
|
565
|
+
lastDay: shapeWindow(npm.lastDay),
|
|
566
|
+
lastWeek: shapeWindow(npm.lastWeek),
|
|
567
|
+
lastMonth: shapeWindow(npm.lastMonth),
|
|
568
|
+
versionPublishedAt: String(npm.versionPublishedAt ?? ''),
|
|
569
|
+
unavailable: String(npm.unavailable ?? ''),
|
|
570
|
+
},
|
|
571
|
+
github: {
|
|
572
|
+
stars: shapeCount(raw?.github, 'stars'),
|
|
573
|
+
forks: shapeCount(raw?.github, 'forks'),
|
|
574
|
+
watchers: shapeCount(raw?.github, 'watchers'),
|
|
575
|
+
openIssues: shapeCount(raw?.github, 'openIssues'),
|
|
576
|
+
unavailable: String(raw?.github?.unavailable ?? ''),
|
|
577
|
+
source: String(raw?.github?.source ?? ''),
|
|
578
|
+
},
|
|
579
|
+
gitee: {
|
|
580
|
+
stars: shapeCount(raw?.gitee, 'stars'),
|
|
581
|
+
forks: shapeCount(raw?.gitee, 'forks'),
|
|
582
|
+
watchers: shapeCount(raw?.gitee, 'watchers'),
|
|
583
|
+
openIssues: shapeCount(raw?.gitee, 'openIssues'),
|
|
584
|
+
unavailable: String(raw?.gitee?.unavailable ?? ''),
|
|
585
|
+
},
|
|
586
|
+
gitcode: {
|
|
587
|
+
stars: shapeCount(raw?.gitcode, 'stars'),
|
|
588
|
+
forks: shapeCount(raw?.gitcode, 'forks'),
|
|
589
|
+
unavailable: String(raw?.gitcode?.unavailable ?? ''),
|
|
590
|
+
},
|
|
591
|
+
fetchedAt: String(raw?.fetchedAt ?? ''),
|
|
592
|
+
error: String(raw?.error ?? ''),
|
|
593
|
+
}
|
|
594
|
+
}
|
|
595
|
+
|
|
596
|
+
const WINDOW_SCHEMA = {
|
|
597
|
+
type: 'object',
|
|
598
|
+
additionalProperties: false,
|
|
599
|
+
properties: {
|
|
600
|
+
downloads: { type: 'integer', description: '该窗口内的下载次数(取不到时为 0,看 unavailable)。' },
|
|
601
|
+
start: { type: 'string', description: '统计窗口起始日(YYYY-MM-DD,原样来自 npm)。' },
|
|
602
|
+
end: { type: 'string', description: '统计窗口结束日(YYYY-MM-DD,原样来自 npm)。⚠ npm 的 end 滞后约 2 天,"last-day" 不是今天。' },
|
|
603
|
+
unavailable: { type: 'string', description: '取不到的原因;成功时为空字符串。' },
|
|
604
|
+
},
|
|
605
|
+
required: ['downloads', 'start', 'end', 'unavailable'],
|
|
606
|
+
}
|
|
607
|
+
|
|
608
|
+
export const PKG_STATS_SCHEMA = {
|
|
609
|
+
name: 'pkg_stats',
|
|
610
|
+
description:
|
|
611
|
+
'同步:查一个 npm 包的下载量(昨日/近 7 天/近 30 天,含统计窗口 start/end 原样)与 latest 版本、发布时间,外加同一仓库在 GitHub / Gitee / GitCode 的热度(star / fork / watcher / open issues)。参数都可省(默认 dsh-aiyayi / BayiHY/dsh-aiyayi)。几秒内返回;某个平台挂了只影响它自己那一段,失败原因写在对应字段的 unavailable 里(取不到不编数)。注意:① npm 统计的 end 日期滞后约 2 天,"last-day" 不是今天;② GitHub 直连在本机不通时经第三方代理 gh-proxy.com 兜底(该代理会看到你查询的仓库路径);③ GitCode 无匿名 API,stars/forks 恒为 0 且 unavailable 说明原因。',
|
|
612
|
+
parameters: {
|
|
613
|
+
type: 'object',
|
|
614
|
+
additionalProperties: false,
|
|
615
|
+
properties: {
|
|
616
|
+
package: { type: 'string', description: 'npm 包名(默认 dsh-aiyayi;支持 @scope/name)。只允许字母数字与 . _ ~ -。' },
|
|
617
|
+
repo: { type: 'string', description: '代码仓 owner/name(默认 BayiHY/dsh-aiyayi;两段只允许字母数字与 . _ -)。' },
|
|
618
|
+
},
|
|
619
|
+
required: [],
|
|
620
|
+
},
|
|
621
|
+
output: {
|
|
622
|
+
schema: {
|
|
623
|
+
type: 'object',
|
|
624
|
+
additionalProperties: false,
|
|
625
|
+
properties: {
|
|
626
|
+
ok: { type: 'boolean', description: '是否至少有一个平台取到了数据(全失败为 false,但结构仍然合法)。' },
|
|
627
|
+
package: { type: 'string', description: '查询的 npm 包名;参数非法时为空字符串。' },
|
|
628
|
+
version: { type: 'string', description: 'npm latest 版本号;取不到时为空字符串(原因见 npm.unavailable)。' },
|
|
629
|
+
repo: { type: 'string', description: '查询的 owner/name;参数非法时为空字符串。' },
|
|
630
|
+
npm: {
|
|
631
|
+
type: 'object',
|
|
632
|
+
additionalProperties: false,
|
|
633
|
+
properties: {
|
|
634
|
+
lastDay: WINDOW_SCHEMA,
|
|
635
|
+
lastWeek: WINDOW_SCHEMA,
|
|
636
|
+
lastMonth: WINDOW_SCHEMA,
|
|
637
|
+
versionPublishedAt: { type: 'string', description: 'latest 版本的发布时间(ISO,来自 registry 的 time 字段);取不到时为空字符串。' },
|
|
638
|
+
unavailable: { type: 'string', description: 'npm 下载量整体失败的原因;只要有一个窗口成功就为空字符串。' },
|
|
639
|
+
},
|
|
640
|
+
required: ['lastDay', 'lastWeek', 'lastMonth', 'versionPublishedAt', 'unavailable'],
|
|
641
|
+
},
|
|
642
|
+
github: {
|
|
643
|
+
type: 'object',
|
|
644
|
+
additionalProperties: false,
|
|
645
|
+
properties: {
|
|
646
|
+
stars: { type: 'integer', description: 'star 数(取不到时为 0,看 unavailable)。' },
|
|
647
|
+
forks: { type: 'integer', description: 'fork 数(取不到时为 0)。' },
|
|
648
|
+
watchers: { type: 'integer', description: 'GitHub 的 watchers_count(取不到时为 0)。' },
|
|
649
|
+
openIssues: { type: 'integer', description: 'open issues 数(取不到时为 0)。' },
|
|
650
|
+
unavailable: { type: 'string', description: '取不到的原因(直连与代理两路都会写上);成功时为空字符串。' },
|
|
651
|
+
source: { type: 'string', description: '数据来源:"direct"=直连 api.github.com;"gh-proxy"=经第三方代理 gh-proxy.com;空字符串=没取到。' },
|
|
652
|
+
},
|
|
653
|
+
required: ['stars', 'forks', 'watchers', 'openIssues', 'unavailable', 'source'],
|
|
654
|
+
},
|
|
655
|
+
gitee: {
|
|
656
|
+
type: 'object',
|
|
657
|
+
additionalProperties: false,
|
|
658
|
+
properties: {
|
|
659
|
+
stars: { type: 'integer', description: 'star 数(取不到时为 0)。' },
|
|
660
|
+
forks: { type: 'integer', description: 'fork 数(取不到时为 0)。' },
|
|
661
|
+
watchers: { type: 'integer', description: 'Gitee 的 watchers_count = 关注数,语义与 GitHub watchers 不同(本仓库实测 1)。' },
|
|
662
|
+
openIssues: { type: 'integer', description: 'open issues 数(取不到时为 0)。' },
|
|
663
|
+
unavailable: { type: 'string', description: '取不到的原因;成功时为空字符串。' },
|
|
664
|
+
},
|
|
665
|
+
required: ['stars', 'forks', 'watchers', 'openIssues', 'unavailable'],
|
|
666
|
+
},
|
|
667
|
+
gitcode: {
|
|
668
|
+
type: 'object',
|
|
669
|
+
additionalProperties: false,
|
|
670
|
+
properties: {
|
|
671
|
+
stars: { type: 'integer', description: 'star 数(GitCode 无匿名 API,正常恒为 0,看 unavailable)。' },
|
|
672
|
+
forks: { type: 'integer', description: 'fork 数(同上,正常恒为 0)。' },
|
|
673
|
+
unavailable: { type: 'string', description: '取不到的原因(无匿名 API / HTTP 状态 + 服务端原话);取到时为空字符串。' },
|
|
674
|
+
},
|
|
675
|
+
required: ['stars', 'forks', 'unavailable'],
|
|
676
|
+
},
|
|
677
|
+
fetchedAt: { type: 'string', description: '本次采集完成时间(ISO)。' },
|
|
678
|
+
error: { type: 'string', description: '整体失败/参数非法的一句话原因;正常时为空字符串。' },
|
|
679
|
+
},
|
|
680
|
+
required: ['ok', 'package', 'version', 'repo', 'npm', 'github', 'gitee', 'gitcode', 'fetchedAt', 'error'],
|
|
681
|
+
},
|
|
682
|
+
render: (_args, value) => {
|
|
683
|
+
if (!value.package) return TEXT_BLOCK(`pkg_stats 参数不合法:${value.error}`)
|
|
684
|
+
const lines = [`${value.package}${value.version ? `@${value.version}` : ''}(${value.repo})`]
|
|
685
|
+
const win = (label, item) => (item.unavailable
|
|
686
|
+
? ` ${label}:取不到(${item.unavailable})`
|
|
687
|
+
: ` ${label}:${item.downloads} 次(${item.start} → ${item.end})`)
|
|
688
|
+
lines.push(win('昨日', value.npm.lastDay))
|
|
689
|
+
lines.push(win('近 7 天', value.npm.lastWeek))
|
|
690
|
+
lines.push(win('近 30 天', value.npm.lastMonth))
|
|
691
|
+
if (value.npm.versionPublishedAt) lines.push(` 发布时间:${value.npm.versionPublishedAt}`)
|
|
692
|
+
if (value.npm.unavailable) lines.push(` npm:${value.npm.unavailable}`)
|
|
693
|
+
const repoLine = (label, item) => (item.unavailable
|
|
694
|
+
? ` ${label}:取不到(${item.unavailable})`
|
|
695
|
+
: ` ${label}:★${item.stars} fork ${item.forks} watch ${item.watchers} issues ${item.openIssues}`)
|
|
696
|
+
lines.push(repoLine('GitHub', value.github))
|
|
697
|
+
if (value.github.source === 'gh-proxy') lines.push(' (GitHub 直连失败,数据经第三方代理 gh-proxy.com)')
|
|
698
|
+
lines.push(repoLine('Gitee', value.gitee))
|
|
699
|
+
lines.push(value.gitcode.unavailable
|
|
700
|
+
? ` GitCode:取不到(${value.gitcode.unavailable})`
|
|
701
|
+
: ` GitCode:★${value.gitcode.stars} fork ${value.gitcode.forks}`)
|
|
702
|
+
if (value.error) lines.push(`!${value.error}`)
|
|
703
|
+
return TEXT_BLOCK(lines.join('\n'))
|
|
704
|
+
},
|
|
705
|
+
},
|
|
706
|
+
}
|
|
707
|
+
|
|
708
|
+
/** 给单测的出口(生产路径都走上面的导出函数)。 */
|
|
709
|
+
export const __testing = {
|
|
710
|
+
isTimeoutError,
|
|
711
|
+
emptyWindow,
|
|
712
|
+
NPM_WINDOWS,
|
|
713
|
+
USER_AGENT,
|
|
714
|
+
}
|
package/lib/toolkit.js
CHANGED
|
@@ -57,6 +57,7 @@ import {
|
|
|
57
57
|
shapeMemSyncOutput,
|
|
58
58
|
shapeWatchOutput,
|
|
59
59
|
} from './toolkit-extra.js'
|
|
60
|
+
import { PKG_STATS_SCHEMA, executePkgStats, shapePkgStatsOutput } from './pkg-stats.js'
|
|
60
61
|
|
|
61
62
|
/** Loader 身份。 */
|
|
62
63
|
export const name = 'aiyayi-toolkit'
|
|
@@ -65,7 +66,7 @@ export const name = 'aiyayi-toolkit'
|
|
|
65
66
|
export const inject = ['tools']
|
|
66
67
|
|
|
67
68
|
/** 本中间层自注册的工具名(own-tools 白名单 + 工具目录共用)。 */
|
|
68
|
-
export const TOOL_NAMES = ['toolkit_cmd', 'toolkit_read', 'toolkit_write', 'watch_read', 'mem_sync']
|
|
69
|
+
export const TOOL_NAMES = ['toolkit_cmd', 'toolkit_read', 'toolkit_write', 'watch_read', 'mem_sync', 'pkg_stats']
|
|
69
70
|
|
|
70
71
|
/** 默认配置。全部可被 cordis.patch.yml 的 config 覆盖(数组整体替换)。 */
|
|
71
72
|
export const DEFAULT_CONFIG = {
|
|
@@ -120,6 +121,19 @@ export const DEFAULT_CONFIG = {
|
|
|
120
121
|
// mem_sync(1.5.41,同步):提交后推哪些远端、推哪个分支(顺序即汇报顺序)。
|
|
121
122
|
memPushRemotes: ['gitee', 'gitcode'],
|
|
122
123
|
memBranch: 'master',
|
|
124
|
+
// pkg_stats(1.5.42,同步):查 npm 下载量 + 代码仓热度。
|
|
125
|
+
// 默认查询目标(本体一般不用传参)。
|
|
126
|
+
pkgStatsDefaultPackage: 'dsh-aiyayi',
|
|
127
|
+
pkgStatsDefaultRepo: 'BayiHY/dsh-aiyayi',
|
|
128
|
+
// 整次调用的总预算与单请求预算(ms)。总预算是硬兜底:就算某次 fetch 不认 signal,
|
|
129
|
+
// 也不会让这一轮工具调用卡过 15 秒(宿主同步 await,坑 #79)。
|
|
130
|
+
pkgStatsTimeoutMs: 15000,
|
|
131
|
+
pkgStatsRequestTimeoutMs: 8000,
|
|
132
|
+
// GitHub 直连失败时是否允许走第三方代理 gh-proxy.com 兜底。
|
|
133
|
+
// ⚠ 该代理能看到你查询的仓库路径(owner/repo 会进它的访问日志);不放心就设 false。
|
|
134
|
+
pkgStatsAllowGithubProxy: true,
|
|
135
|
+
// GitHub 直连的快速失败预算(本机直连是 reset,4 秒足够判死,别把总预算烧在它身上)。
|
|
136
|
+
pkgStatsGithubDirectTimeoutMs: 4000,
|
|
123
137
|
}
|
|
124
138
|
|
|
125
139
|
const TEXT_BLOCK = (text) => [{ type: 'text', text }]
|
|
@@ -1028,6 +1042,8 @@ export function apply(ctx, config) {
|
|
|
1028
1042
|
[WATCH_SCHEMA, (args, exec) => executeWatchRead(args, { cfg, logUsage, warn, exec })],
|
|
1029
1043
|
// 同步:git status/diff/commit/push 几秒内完成,直接返回(不需要 followup)。
|
|
1030
1044
|
[MEM_SYNC_SCHEMA, (args) => executeMemSync(args, { cfg, logUsage, warn })],
|
|
1045
|
+
// 1.5.42 同步:几个 HTTP GET(总预算 15 秒),某平台挂了只影响它自己那段。
|
|
1046
|
+
[PKG_STATS_SCHEMA, (args) => executePkgStats(args, { cfg, logUsage, warn })],
|
|
1031
1047
|
]
|
|
1032
1048
|
for (const [def, impl] of builtins) {
|
|
1033
1049
|
try {
|
|
@@ -1063,4 +1079,5 @@ export const __testing = {
|
|
|
1063
1079
|
ringTrim,
|
|
1064
1080
|
shapeWatchOutput,
|
|
1065
1081
|
shapeMemSyncOutput,
|
|
1082
|
+
shapePkgStatsOutput,
|
|
1066
1083
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-aiyayi",
|
|
3
|
-
"version": "1.5.
|
|
3
|
+
"version": "1.5.42",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"author": "巴依浩爷 (bayihy)",
|
|
6
6
|
"keywords": [
|
|
@@ -31,6 +31,7 @@
|
|
|
31
31
|
"./toolkit": "./lib/toolkit.js",
|
|
32
32
|
"./toolkit-async": "./lib/toolkit-async.js",
|
|
33
33
|
"./toolkit-extra": "./lib/toolkit-extra.js",
|
|
34
|
+
"./pkg-stats": "./lib/pkg-stats.js",
|
|
34
35
|
"./icon": "./icon.svg"
|
|
35
36
|
},
|
|
36
37
|
"files": [
|
|
@@ -50,6 +51,7 @@
|
|
|
50
51
|
"lib/toolkit.js",
|
|
51
52
|
"lib/toolkit-async.js",
|
|
52
53
|
"lib/toolkit-extra.js",
|
|
54
|
+
"lib/pkg-stats.js",
|
|
53
55
|
"lib/weixin.js",
|
|
54
56
|
"lib/weixin/",
|
|
55
57
|
"skills",
|