dsh-aiyayi 1.5.37 → 1.5.38
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 +18 -1
- package/README.md +1 -0
- package/cordis.patch.yml +38 -0
- package/lib/own-tools.js +5 -0
- package/lib/toolkit.js +953 -0
- 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.
|
|
5
|
+
> **npm 发布一览(2026-11-12 核对 registry,`npm view dsh-aiyayi versions --json`)**:latest = **1.5.38**(本次发版版;registry 实况 latest 已为 **1.5.37**,2026-11-12 发版前核对 dist-tags 确认,1.5.38 的 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 条目;publish 留待下一步,以 registry 为准)。
|
|
6
6
|
>
|
|
7
7
|
> **环境标识约定(2026-11-10 新增)**:写版本条目/坑条目时,**顺手记录当时的 智能体工具-智能体模式-模型供应商-模型**(如 **DSH-创造模式-loomy讯飞-GLM5.3FLASH**),写在条目内(紧跟 git 记录行、或坑条目首行),方便回溯该条目是在哪套智能体/模型环境下产出与验证的。
|
|
8
8
|
|
|
@@ -10,6 +10,23 @@
|
|
|
10
10
|
|
|
11
11
|
---
|
|
12
12
|
|
|
13
|
+
## 1.5.38(2026-11-12 新增:工具包中间层首批——`toolkit_cmd` / `toolkit_read` / `toolkit_write`)
|
|
14
|
+
|
|
15
|
+
- 环境:DSH-执行智能体(DeepSeek Harness 子会话,模型名未确证)
|
|
16
|
+
- **改了什么(新增 `lib/toolkit.js` + 测试,挂载与白名单接线;无既有工具行为变更)**:
|
|
17
|
+
- `lib/toolkit.js`(新增,`aiyayi-toolkit`):工具包中间层首批 3 工具(设计方案 docs/开发方案-工具包中间层.md)。分工原则:**简单结果状态型**查询(输出短、一次性、不需提炼)本体直接调、不用派小伙伴;**大量结果型**(翻文件堆、要提炼归纳的)照旧派 subagent / retriever。工具本身坏了(报错、行为异常)再派人修。
|
|
18
|
+
1. `toolkit_cmd` —— 只读命令执行:白名单前缀**整词**校验(git log/status/diff/show、npm view/search、node --version、ls/dir/type/cat/head/tail/wc/where/which 等,可配置;大小写不敏感),白名单外(publish/push/install/rm/del/mkdir/cp/mv 等一切写变更类)一律拒绝;shell 元字符(重定向 `>` `>>`、管道 `|`、命令替换 `$(`、反引号、串接 `;`)一并拒绝,防白名单命令被拼接滥用;命令动词黑名单(publish/push/rm 等)双保险不误伤白名单命令;调用参数脱敏(token/bearer/URL 凭据打码);输出超 2048 字符(可配置)截断并标注 `[truncated]`;默认 30s 超时杀进程。底层 `child_process.spawn` 在插件进程内执行——DSH 的 pwsh/file 沙箱是宿主对宿主工具的约束,插件内进程拿不到那层钩子,所以**白名单收敛就是本工具的安全层**(这也是把命令面收窄到"只读前缀 + 禁元字符"的原因)。
|
|
19
|
+
2. `toolkit_read` —— 文件探测 + 小文件读取:exists/size/mtime/isFile/isDir + 前 maxBytes(默认 8KB,上限 64KB)内容。读是安全的,不限路径;读不到返回 `exists:false`(是正常答案不是错误)。
|
|
20
|
+
3. `toolkit_write` —— 受限写入:路径白名单(默认 = 记忆根(动态解析,搬家自动跟随)+ `writeExtraPaths` 配置,可 `writePaths` 整体接管),限 64KB;原子写(临时文件 + rename);覆盖前自动留时间戳 `.bak`。
|
|
21
|
+
- **调用留痕(初版重点,供后续按使用痕迹优化)**:每次调用追加一条 JSONL 到 `<记忆根>/toolkit/usage.jsonl`(目录不存在自建;环形 500 行,超限保留最新):`{ ts, tool, args(脱敏摘要), status(success/denied/timeout/truncated/error), denyReason, durationMs, outBytes, truncated, ok, exitCode, error }`。写留痕本身 try/catch,失败只 warn,绝不影响工具结果。
|
|
22
|
+
- `lib/own-tools.js`:`OWN_TOOLS` 加 `toolkit_cmd` / `toolkit_read` / `toolkit_write`(运行时由 registerOwnTool 收集,这里防漏放行)。
|
|
23
|
+
- `cordis.patch.yml` preset-aiyayi 挂载 `aiyayi-toolkit`(config:cmdWhitelist 19 条只读前缀 / cmdTimeoutMs 30000 / maxOutputChars 2048 / readMaxBytes 8192 / writeMaxBytes 65536 / writeExtraPaths 本机 docs 目录 / usageEnabled true / usageMaxLines 500)。
|
|
24
|
+
- `package.json`:exports 与 files 白名单加 `./toolkit` / `lib/toolkit.js`。
|
|
25
|
+
- **为什么**:本体每次想看个 git status / 查个 npm view / 量个文件大小,都要派小伙伴或检索员走一整轮 subagent 开销;中间层把"简单结果状态型"查询收进本体直调的 3 个受限工具,省轮次;留痕(usage.jsonl)让后续能按真实使用痕迹继续优化工具面。
|
|
26
|
+
- **测试**:新增 `test/toolkit.test.mjs`(独立断言脚本风格,check() + `ALL PASS` / exit code,103 项断言;临时沙盘 + 指路文件隔离,绝不碰真实记忆根)。覆盖:白名单整词匹配(`git logfile` 这类前缀粘连不放行)、大小写不敏感、写变更类命令(npm publish / git push / rm -rf / mkdir / node --eval)全拒、shell 元字符(重定向/追加/管道/命令替换/反引号/串接)拒绝、动词黑名单不误伤白名单命令、参数脱敏三形态、输出截断与长度、真实执行 ok/stdout/exitCode/durationMs、超时(kill + exitCode null)、read 探测/小读/maxBytes clamp/空路径不抛、write 目录自建/落盘一致/覆盖留 .bak/usage.jsonl 留痕与环形裁剪。
|
|
27
|
+
- 版本号对齐:`package.json` version 与本条目均为 `1.5.38`(cordis.patch.yml 已无 reloadTag 字段,无需对齐)。
|
|
28
|
+
- 打包与 npm publish **不在本次范围**:本版只做版本号对齐 + 推 git(gitcode / gitee / github 三远端),打包与 npm 发布留作下一步单独执行。
|
|
29
|
+
|
|
13
30
|
## 1.5.37(2026-11-12 新增:压缩前沉淀机制 precompact——先保知识,再清流水)
|
|
14
31
|
|
|
15
32
|
- 环境:DSH-执行智能体(DeepSeek Harness 子会话,模型名未确证)
|
package/README.md
CHANGED
|
@@ -73,6 +73,7 @@ npm 包为平铺结构(仓库若保留 bundle/ 子目录,发布时把其内
|
|
|
73
73
|
- `lib/doc.js` — aiyayi-doc 文档解析插件(1.4.0,挂检索员 preset;ZIP/XML 最小解析零依赖 + 动态加载 shipped libreoffice-kit 做 pdf 页图与旧版转换)
|
|
74
74
|
- `lib/own-tools.js` — 她的工具名单单一真源(注册处登记、放行处判定,防手写白名单漂移)
|
|
75
75
|
- `lib/precompact.js` — aiyayi-precompact 压缩前沉淀检查插件(1.5.37;在 dsh-compaction-basic 动手压缩前,把值得沉淀的任务闭环/结论/新经验先落盘为经验文档+记忆+索引,失败不阻塞主流程;`precompact_run` 显式工具入口 + 接近阈值自动触发)
|
|
76
|
+
- `lib/toolkit.js` — aiyayi-toolkit 工具包中间层插件(1.5.38;首批 3 工具:`toolkit_cmd` 只读命令白名单执行 / `toolkit_read` 文件探测 + 小文件读取 / `toolkit_write` 受限写入;调用留痕落 `<记忆根>/toolkit/usage.jsonl`;简单状态型查询本体直调、不派小伙伴)
|
|
76
77
|
- `lib/feishu.js` — aiyayi-feishu 飞书桥接宿主插件(1.5.8 起;跨会话服务,长连接收消息、按指令路由到 aiyayi 会话、回发;凭读取记忆根 `feishu/config.json`)
|
|
77
78
|
- `lib/feishu-logic.js` — 飞书纯逻辑(路由/映射/文本抽取/三档复用决策/**长连接状态机**,无外部依赖,可单测;test/feishu-route.test.mjs、test/feishu-reuse-session.test.mjs、test/feishu-status.test.mjs 覆盖)
|
|
78
79
|
- `skills/feishu-setup/` — 内置技能(1.5.13 起随包自动同步到 DSH 技能根):飞书机器人安装/验证/排障全流程(含 2026-11-10 扫码接入改造说明;脚本 `scripts/create-bot.js` v5 等由技能同步维护)
|
package/cordis.patch.yml
CHANGED
|
@@ -214,6 +214,44 @@
|
|
|
214
214
|
memoryPath: 事情/经验
|
|
215
215
|
# docsDir 不设 → 默认落记忆根下 docs/(可改成工作区 docs 目录)。
|
|
216
216
|
updateIndex: true
|
|
217
|
+
# 工具包中间层(首批 3 工具):toolkit_cmd(只读命令,白名单收敛)/ toolkit_read
|
|
218
|
+
# (文件探测+小文件读取)/ toolkit_write(受限写入:记忆根+白名单目录,64KB,
|
|
219
|
+
# 原子写+自动 .bak)。简单状态型查询本体直接调,不用派小伙伴;留痕落
|
|
220
|
+
# <记忆根>/toolkit/usage.jsonl(环形 500 行)。数组一律整体替换(不是叠加)。
|
|
221
|
+
- id: aiyayi-toolkit
|
|
222
|
+
name: 'dsh-aiyayi/toolkit'
|
|
223
|
+
config:
|
|
224
|
+
# 只读命令白名单(前缀整词匹配;白名单外一律拒绝)。
|
|
225
|
+
cmdWhitelist:
|
|
226
|
+
- git log
|
|
227
|
+
- git status
|
|
228
|
+
- git diff
|
|
229
|
+
- git show
|
|
230
|
+
- npm view
|
|
231
|
+
- npm search
|
|
232
|
+
- pnpm -v
|
|
233
|
+
- pnpm --version
|
|
234
|
+
- node --version
|
|
235
|
+
- node -v
|
|
236
|
+
- ls
|
|
237
|
+
- dir
|
|
238
|
+
- type
|
|
239
|
+
- cat
|
|
240
|
+
- head
|
|
241
|
+
- tail
|
|
242
|
+
- wc
|
|
243
|
+
- where
|
|
244
|
+
- which
|
|
245
|
+
cmdTimeoutMs: 30000
|
|
246
|
+
maxOutputChars: 2048
|
|
247
|
+
readMaxBytes: 8192
|
|
248
|
+
writeMaxBytes: 65536
|
|
249
|
+
# 写入白名单:writePaths: null(默认)= 记忆根(动态解析,搬家自动跟随)
|
|
250
|
+
# + writeExtraPaths;给数组则完全接管。工作区 docs 是本机路径,走追加项。
|
|
251
|
+
writeExtraPaths:
|
|
252
|
+
- D:\AI\TRAE_PRO\阿依娅依\docs
|
|
253
|
+
usageEnabled: true
|
|
254
|
+
usageMaxLines: 500
|
|
217
255
|
- id: aiyayi-restrict
|
|
218
256
|
name: 'dsh-aiyayi/restrict'
|
|
219
257
|
- id: time-context
|
package/lib/own-tools.js
CHANGED
|
@@ -34,6 +34,11 @@ export const OWN_TOOLS = [
|
|
|
34
34
|
'weixin_unbind',
|
|
35
35
|
// 压缩前沉淀(1.5.37,lib/precompact.js):本体显式调用的沉淀检查工具。
|
|
36
36
|
'precompact_run',
|
|
37
|
+
// 工具包中间层(lib/toolkit.js,首批 3 工具):本体可直接调的简单状态型工具
|
|
38
|
+
// (只读命令 / 文件探测小读 / 受限写入),运行时由 registerOwnTool 收集,这里防漏放行。
|
|
39
|
+
'toolkit_cmd',
|
|
40
|
+
'toolkit_read',
|
|
41
|
+
'toolkit_write',
|
|
37
42
|
]
|
|
38
43
|
|
|
39
44
|
/** 宿主提供的、她该留着的对话与委派工具。retriever 1.3.0 起加入(派检索员)。 */
|
package/lib/toolkit.js
ADDED
|
@@ -0,0 +1,953 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* aiyayi-toolkit — 工具包中间层(首批 3 工具:cmd / read / write)。
|
|
3
|
+
*
|
|
4
|
+
* 设计方案:docs/开发方案-工具包中间层.md(中间层三要素 = 工具目录 + 注册/反注册 + 调用转发)。
|
|
5
|
+
*
|
|
6
|
+
* 分工原则(方案 §1.2):**简单结果状态型**查询(输出短、一次性、不需提炼)由中间层
|
|
7
|
+
* 直接处理,本体异步可调、不用派小伙伴;**大量结果型**(要翻文件堆、要提炼归纳的)
|
|
8
|
+
* 照旧派 subagent / retriever。工具本身坏了(报错、行为异常)再派人修。
|
|
9
|
+
*
|
|
10
|
+
* 首批三工具(全部中间层封装,本体可调):
|
|
11
|
+
* 1. toolkit_cmd —— 只读命令执行:白名单前缀校验(git log/status/diff/show、npm view/search、
|
|
12
|
+
* node --version、ls/dir/type/cat/head/tail/wc/where/which 等,可配置),
|
|
13
|
+
* 白名单外(publish/push/install/rm/del/mkdir/cp/mv 等一切写变更类)一律拒绝;
|
|
14
|
+
* shell 元字符(管道/重定向/命令替换)一并拒绝,防止白名单命令被拼接滥用;
|
|
15
|
+
* 输出超 2KB(2048 字符,可配置)截断并标注 [truncated];默认 30s 超时杀进程。
|
|
16
|
+
* 底层 child_process.spawn 在插件进程内执行——DSH 的 pwsh/file 沙箱是宿主
|
|
17
|
+
* 对宿主工具的约束,插件内进程拿不到那层钩子,所以**白名单收敛就是本工具
|
|
18
|
+
* 的安全层**(这也是把命令面收窄到"只读前缀 + 禁元字符"的原因)。
|
|
19
|
+
* 2. toolkit_read —— 文件探测 + 小文件读取:exists/size/mtime/isFile/isDir + 前 maxBytes(默认
|
|
20
|
+
* 8KB,上限 64KB)内容。读是安全的,不限路径;读不到 exists:false。
|
|
21
|
+
* 3. toolkit_write —— 受限写入:路径白名单(默认 = 记忆根 + writeExtraPaths 配置,可用 writePaths
|
|
22
|
+
* 整体接管),限 64KB;原子写(临时文件 + rename);覆盖前自动留时间戳 .bak。
|
|
23
|
+
*
|
|
24
|
+
* 调用留痕(初版重点,供后续按使用痕迹优化):
|
|
25
|
+
* 每次调用追加一条 JSONL 到 <记忆根>/toolkit/usage.jsonl(目录不存在自建):
|
|
26
|
+
* { ts, tool, args(脱敏摘要), status(success/denied/timeout/truncated/error),
|
|
27
|
+
* denyReason, durationMs, outBytes, truncated, ok, exitCode, error }。
|
|
28
|
+
* 环形控制:超过 usageMaxLines(默认 500)行时保留最新。写留痕本身 try/catch,
|
|
29
|
+
* 失败只 warn,绝不影响工具结果。readUsage(n) 读最近 n 条(本版导出函数,后续可暴露成工具)。
|
|
30
|
+
*
|
|
31
|
+
* 注册范式同 precompact/net:apply(ctx, config) 里 registerOwnTool + ctx.tools.register
|
|
32
|
+
* (disposer 存进工具目录,卸载时统一反注册);**全程 try/catch,失败只禁用对应工具,
|
|
33
|
+
* 绝不阻塞插件激活**(同 feishu/weixin/precompact 思路)。
|
|
34
|
+
*/
|
|
35
|
+
import { spawn } from 'node:child_process'
|
|
36
|
+
import {
|
|
37
|
+
appendFileSync,
|
|
38
|
+
closeSync,
|
|
39
|
+
copyFileSync,
|
|
40
|
+
mkdirSync,
|
|
41
|
+
openSync,
|
|
42
|
+
readFileSync,
|
|
43
|
+
readSync,
|
|
44
|
+
renameSync,
|
|
45
|
+
rmSync,
|
|
46
|
+
statSync,
|
|
47
|
+
writeFileSync,
|
|
48
|
+
} from 'node:fs'
|
|
49
|
+
import { dirname, join, resolve, sep } from 'node:path'
|
|
50
|
+
import { resolveRoot } from './home.js'
|
|
51
|
+
import { registerOwnTool } from './own-tools.js'
|
|
52
|
+
|
|
53
|
+
/** Loader 身份。 */
|
|
54
|
+
export const name = 'aiyayi-toolkit'
|
|
55
|
+
|
|
56
|
+
/** 需要的服务:注册工具要 tools。 */
|
|
57
|
+
export const inject = ['tools']
|
|
58
|
+
|
|
59
|
+
/** 本中间层首批自注册的工具名(own-tools 白名单 + 工具目录共用)。 */
|
|
60
|
+
export const TOOL_NAMES = ['toolkit_cmd', 'toolkit_read', 'toolkit_write']
|
|
61
|
+
|
|
62
|
+
/** 默认配置。全部可被 cordis.patch.yml 的 config 覆盖(数组整体替换)。 */
|
|
63
|
+
export const DEFAULT_CONFIG = {
|
|
64
|
+
// toolkit_cmd:只读命令白名单(前缀匹配,整词——"git log" 不会放过 "git logfile")。
|
|
65
|
+
cmdWhitelist: [
|
|
66
|
+
'git log', 'git status', 'git diff', 'git show',
|
|
67
|
+
'npm view', 'npm search',
|
|
68
|
+
'pnpm -v', 'pnpm --version',
|
|
69
|
+
'node --version', 'node -v',
|
|
70
|
+
'ls', 'dir', 'type', 'cat', 'head', 'tail', 'wc', 'where', 'which',
|
|
71
|
+
],
|
|
72
|
+
// toolkit_cmd:变更类命令黑名单(第一词命中给更明确的拒绝理由;真正的门是白名单)。
|
|
73
|
+
cmdDenyWords: [
|
|
74
|
+
'publish', 'push', 'install', 'uninstall', 'add', 'commit', 'clean', 'reset', 'rebase', 'merge',
|
|
75
|
+
'rm', 'del', 'erase', 'rmdir', 'rd', 'mkdir', 'md', 'cp', 'copy', 'mv', 'move', 'ren', 'rename',
|
|
76
|
+
'touch', 'kill', 'taskkill', 'stop-process', 'shutdown', 'restart', 'format', 'diskpart',
|
|
77
|
+
'reg', 'regedit', 'setx', 'remove-item', 'ri', 'set-content', 'add-content',
|
|
78
|
+
'curl', 'wget', 'invoke-webrequest', 'iwr', 'invoke-expression', 'iex',
|
|
79
|
+
],
|
|
80
|
+
// toolkit_cmd:默认超时(ms)与单次调用超时上限(防 args.timeoutMs 把进程挂死)。
|
|
81
|
+
cmdTimeoutMs: 30000,
|
|
82
|
+
cmdTimeoutMaxMs: 120000,
|
|
83
|
+
// toolkit_cmd:返回 stdout/stderr 的截断长度(字符)与收集硬上限(超出丢弃、防内存爆)。
|
|
84
|
+
maxOutputChars: 2048,
|
|
85
|
+
collectCapBytes: 1024 * 1024,
|
|
86
|
+
// toolkit_read:默认与单次读取上限(字节)。
|
|
87
|
+
readMaxBytes: 8 * 1024,
|
|
88
|
+
readMaxBytesCap: 64 * 1024,
|
|
89
|
+
// toolkit_write:单次写入上限(字节)。
|
|
90
|
+
writeMaxBytes: 64 * 1024,
|
|
91
|
+
// toolkit_write:写入白名单。null(默认)= 记忆根(resolveRoot 动态解析,搬家自动跟随)
|
|
92
|
+
// + writeExtraPaths;给了数组 = 完全接管(记忆根也要自己列进去)。
|
|
93
|
+
writePaths: null,
|
|
94
|
+
// toolkit_write:在默认白名单之上追加的目录(放机器相关的路径,如工作区 docs/)。
|
|
95
|
+
writeExtraPaths: [],
|
|
96
|
+
// 调用留痕:开关 / 环形上限(行)/ 落盘路径(null = <记忆根>/toolkit/usage.jsonl)。
|
|
97
|
+
usageEnabled: true,
|
|
98
|
+
usageMaxLines: 500,
|
|
99
|
+
usagePath: null,
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
const TEXT_BLOCK = (text) => [{ type: 'text', text }]
|
|
103
|
+
|
|
104
|
+
/** 单次调用的留痕记录骨架(字段齐全,方便以后按字段做统计)。 */
|
|
105
|
+
function makeRec(tool, argsSummary) {
|
|
106
|
+
return {
|
|
107
|
+
ts: new Date().toISOString(),
|
|
108
|
+
tool,
|
|
109
|
+
args: String(argsSummary ?? ''),
|
|
110
|
+
status: 'success',
|
|
111
|
+
denyReason: '',
|
|
112
|
+
durationMs: 0,
|
|
113
|
+
outBytes: 0,
|
|
114
|
+
truncated: false,
|
|
115
|
+
ok: false,
|
|
116
|
+
exitCode: null,
|
|
117
|
+
error: '',
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/* ------------------------------------------------------------------ *
|
|
122
|
+
* 纯函数助手(导出给单测;无副作用)
|
|
123
|
+
* ------------------------------------------------------------------ */
|
|
124
|
+
|
|
125
|
+
/** 命令第一词(用于变更类黑名单提示)。 */
|
|
126
|
+
export function firstWord(cmd) {
|
|
127
|
+
return String(cmd ?? '').trim().split(/\s+/)[0]?.toLowerCase() ?? ''
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* 只读白名单前缀匹配(整词):命令等于前缀,或以「前缀 + 空格」开头才放行。
|
|
132
|
+
* 比较统一小写(Windows 命令大小写不敏感;POSIX 下宽一点无害)。
|
|
133
|
+
* @returns {string|null} 命中的前缀;没命中返回 null。
|
|
134
|
+
*/
|
|
135
|
+
export function matchesWhitelist(cmd, list) {
|
|
136
|
+
const text = String(cmd ?? '').trim().toLowerCase()
|
|
137
|
+
if (!text) return null
|
|
138
|
+
for (const entry of Array.isArray(list) ? list : []) {
|
|
139
|
+
const prefix = String(entry ?? '').trim().toLowerCase()
|
|
140
|
+
if (!prefix) continue
|
|
141
|
+
if (text === prefix || text.startsWith(`${prefix} `)) return prefix
|
|
142
|
+
}
|
|
143
|
+
return null
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/**
|
|
147
|
+
* shell 元字符检查:白名单命令一旦带这些字符就可能被拼接成写操作
|
|
148
|
+
* (`git log > file` 写文件、`git status | rm -rf` 管道串联、`$(...)`/反引号命令替换)。
|
|
149
|
+
* 注意:括号**不在**禁列——以 `(` 开头的子 shell 命令永远匹配不上任何白名单前缀
|
|
150
|
+
* (白名单门在后面),而命令替换必须经 `$(` 或反引号,两者都被拦;
|
|
151
|
+
* 禁括号会误伤 `node -e "console.log(...)"` 这类合法参数,得不偿失。
|
|
152
|
+
* @returns {string|null} 命中的第一个元字符;干净返回 null。
|
|
153
|
+
*/
|
|
154
|
+
export function findShellMetachar(cmd) {
|
|
155
|
+
const text = String(cmd ?? '')
|
|
156
|
+
const blocked = text.match(/[|&;<>`$\r\n]/)
|
|
157
|
+
return blocked ? blocked[0] : null
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/**
|
|
161
|
+
* 变更类黑名单命中,用于给更明确的拒绝理由。动词可能在第一个词
|
|
162
|
+
* (`rm -rf`)也可能在第二个词(`npm publish` / `git push`),所以查前两个词
|
|
163
|
+
* (跳过 `-` 开头的开关词,避免 `dir /b` 之类误伤)。真正的门仍是白名单。
|
|
164
|
+
*/
|
|
165
|
+
export function findDenyWord(cmd, words) {
|
|
166
|
+
const denySet = new Set(
|
|
167
|
+
(Array.isArray(words) ? words : [])
|
|
168
|
+
.map((w) => String(w ?? '').trim().toLowerCase())
|
|
169
|
+
.filter(Boolean),
|
|
170
|
+
)
|
|
171
|
+
if (denySet.size === 0) return null
|
|
172
|
+
const parts = String(cmd ?? '').trim().toLowerCase().split(/\s+/).filter(Boolean)
|
|
173
|
+
for (const word of parts.slice(0, 2)) {
|
|
174
|
+
if (word.startsWith('-')) continue
|
|
175
|
+
if (denySet.has(word)) return word
|
|
176
|
+
}
|
|
177
|
+
return null
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/** 超长截断并标注 [truncated](按字符数)。 */
|
|
181
|
+
export function truncateWithMark(text, maxChars) {
|
|
182
|
+
const s = String(text ?? '')
|
|
183
|
+
const max = Number.isInteger(maxChars) && maxChars > 0 ? maxChars : 2048
|
|
184
|
+
if (s.length <= max) return { text: s, truncated: false }
|
|
185
|
+
return { text: `${s.slice(0, max)}\n[truncated]`, truncated: true }
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/**
|
|
189
|
+
* 参数摘要脱敏:token/password/secret/key/bearer 等值打码,URL 用户名密码打码。
|
|
190
|
+
* 留痕是给"以后看使用痕迹"用的,摘要里不该留凭证。
|
|
191
|
+
*/
|
|
192
|
+
export function redactSensitive(text) {
|
|
193
|
+
let s = String(text ?? '')
|
|
194
|
+
s = s.replace(/(bearer\s+)\S+/gi, '$1***')
|
|
195
|
+
s = s.replace(/(--?(?:token|password|passwd|secret|apikey|api-key|api_key|key|auth|authorization)[\s=])\S+/gi, '$1***')
|
|
196
|
+
s = s.replace(/\b(?:sk|ghp|gho|github_pat|xoxb|xoxp)-[A-Za-z0-9_-]{8,}/g, '***')
|
|
197
|
+
s = s.replace(/([A-Za-z][A-Za-z0-9+.-]*:\/\/)[^/\s@]+:[^/\s@]+@/g, '$1***@')
|
|
198
|
+
return s
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/** 摘要统一限长,防一条留痕被超长命令撑爆。 */
|
|
202
|
+
function capSummary(text, max = 300) {
|
|
203
|
+
const s = String(text ?? '')
|
|
204
|
+
return s.length <= max ? s : `${s.slice(0, max)}…`
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/* ------------------------------------------------------------------ *
|
|
208
|
+
* 调用留痕:JSONL 追加 + 环形控制 + 读取
|
|
209
|
+
* ------------------------------------------------------------------ */
|
|
210
|
+
|
|
211
|
+
/** 留痕文件路径:config.usagePath 优先;默认 <记忆根>/toolkit/usage.jsonl(动态跟随记忆根)。 */
|
|
212
|
+
export function usageFilePath(cfg) {
|
|
213
|
+
const merged = mergeConfig(cfg)
|
|
214
|
+
if (merged.usagePath) return resolve(String(merged.usagePath))
|
|
215
|
+
const { root } = resolveRoot()
|
|
216
|
+
return join(root, 'toolkit', 'usage.jsonl')
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/** 环形控制:超过 max 行时重写文件只留最新 max 行(含损坏行原样计数,不解析)。 */
|
|
220
|
+
function ringTrim(file, max) {
|
|
221
|
+
let raw
|
|
222
|
+
try {
|
|
223
|
+
raw = readFileSync(file, 'utf8')
|
|
224
|
+
} catch {
|
|
225
|
+
return
|
|
226
|
+
}
|
|
227
|
+
const lines = raw.split('\n').filter((line) => line.trim().length > 0)
|
|
228
|
+
if (lines.length <= max) return
|
|
229
|
+
try {
|
|
230
|
+
writeFileSync(file, `${lines.slice(lines.length - max).join('\n')}\n`, 'utf8')
|
|
231
|
+
} catch {
|
|
232
|
+
/* 重写失败不影响主流程(调用方已兜) */
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/**
|
|
237
|
+
* 造一个留痕写入器。返回的函数永远不抛:写不进就 warn(同 feishu/weixin/precompact
|
|
238
|
+
* "失败只禁用不炸"的思路——留痕是观测手段,不能反过来挡工具)。
|
|
239
|
+
* @param {object} cfg 合并后配置
|
|
240
|
+
* @param {(msg:string)=>void} [warn] 告警出口(apply 传 ctx.logger.warn)
|
|
241
|
+
*/
|
|
242
|
+
export function createUsageLogger(cfg, warn) {
|
|
243
|
+
const merged = mergeConfig(cfg)
|
|
244
|
+
return function logUsage(rec) {
|
|
245
|
+
if (merged.usageEnabled === false) return
|
|
246
|
+
try {
|
|
247
|
+
const file = usageFilePath(merged)
|
|
248
|
+
mkdirSync(dirname(file), { recursive: true })
|
|
249
|
+
appendFileSync(file, `${JSON.stringify(rec)}\n`, 'utf8')
|
|
250
|
+
ringTrim(file, Math.max(1, Number(merged.usageMaxLines) || 500))
|
|
251
|
+
} catch (error) {
|
|
252
|
+
try {
|
|
253
|
+
warn?.(`aiyayi-toolkit: 调用留痕写入失败(已跳过,不影响工具结果): ${error?.message ?? error}`)
|
|
254
|
+
} catch {
|
|
255
|
+
/* 连 logger 都没有就算了 */
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
/**
|
|
262
|
+
* 读最近 n 条留痕(损坏行跳过,不抛)。本版只做导出函数,
|
|
263
|
+
* 以后要给本体看使用统计时再包成工具(方案 §4:用工具可自主,造工具需验收)。
|
|
264
|
+
* @returns {Array<object>} 最近 n 条记录(时间正序);文件不存在/全损坏返回 []。
|
|
265
|
+
*/
|
|
266
|
+
export function readUsage(n = 50, cfg) {
|
|
267
|
+
const merged = mergeConfig(cfg)
|
|
268
|
+
const want = Number.isInteger(n) && n > 0 ? n : 50
|
|
269
|
+
try {
|
|
270
|
+
const raw = readFileSync(usageFilePath(merged), 'utf8')
|
|
271
|
+
const records = []
|
|
272
|
+
for (const line of raw.split('\n')) {
|
|
273
|
+
const text = line.trim()
|
|
274
|
+
if (!text) continue
|
|
275
|
+
try {
|
|
276
|
+
const obj = JSON.parse(text)
|
|
277
|
+
if (obj && typeof obj === 'object' && !Array.isArray(obj)) records.push(obj)
|
|
278
|
+
} catch {
|
|
279
|
+
/* 损坏行跳过——留痕是观测数据,坏一行不值得让读取整个失败 */
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
return records.slice(-want)
|
|
283
|
+
} catch {
|
|
284
|
+
return []
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
/* ------------------------------------------------------------------ *
|
|
289
|
+
* 工具实现 1:toolkit_cmd —— 只读命令执行
|
|
290
|
+
* ------------------------------------------------------------------ */
|
|
291
|
+
|
|
292
|
+
/** 收集 stdout/stderr:带硬上限(collectCapBytes),超出就丢弃剩余,防内存被大输出打爆。 */
|
|
293
|
+
function makeCollector(cap) {
|
|
294
|
+
const chunks = []
|
|
295
|
+
let bytes = 0
|
|
296
|
+
let overflow = false
|
|
297
|
+
return {
|
|
298
|
+
push(chunk) {
|
|
299
|
+
if (bytes >= cap) {
|
|
300
|
+
overflow = true
|
|
301
|
+
return
|
|
302
|
+
}
|
|
303
|
+
const buf = Buffer.from(chunk)
|
|
304
|
+
chunks.push(buf.subarray(0, cap - bytes))
|
|
305
|
+
bytes += buf.length
|
|
306
|
+
if (bytes >= cap) overflow = true
|
|
307
|
+
},
|
|
308
|
+
text() {
|
|
309
|
+
return Buffer.concat(chunks).toString('utf8')
|
|
310
|
+
},
|
|
311
|
+
overflow,
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
/** 杀进程树:Windows 上 child.kill() 只杀 shell 不杀孙进程,用 taskkill /T /F 兜底。 */
|
|
316
|
+
function killTree(child) {
|
|
317
|
+
try {
|
|
318
|
+
if (process.platform === 'win32' && child?.pid) {
|
|
319
|
+
spawn('taskkill', ['/pid', String(child.pid), '/T', '/F'], { windowsHide: true, stdio: 'ignore' })
|
|
320
|
+
} else {
|
|
321
|
+
child?.kill?.('SIGKILL')
|
|
322
|
+
}
|
|
323
|
+
} catch {
|
|
324
|
+
/* 已经退了就算了 */
|
|
325
|
+
}
|
|
326
|
+
try {
|
|
327
|
+
child?.kill?.()
|
|
328
|
+
} catch {
|
|
329
|
+
/* 同上 */
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
/** 掐掉截断留下的半个多字节字符(尾部连续 10xxxxxx 时回退到本字符起点)。 */
|
|
334
|
+
function utf8Safe(buf) {
|
|
335
|
+
let end = buf.length
|
|
336
|
+
let i = end - 1
|
|
337
|
+
let extra = 0
|
|
338
|
+
while (i >= 0 && extra < 4 && (buf[i] & 0xc0) === 0x80) {
|
|
339
|
+
extra += 1
|
|
340
|
+
i -= 1
|
|
341
|
+
}
|
|
342
|
+
if (i >= 0) {
|
|
343
|
+
const b = buf[i]
|
|
344
|
+
const need = b >= 0xf0 ? 3 : b >= 0xe0 ? 2 : b >= 0xc0 ? 1 : 0
|
|
345
|
+
if (need > 0 && extra < need) end = i
|
|
346
|
+
}
|
|
347
|
+
return buf.subarray(0, end).toString('utf8')
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
/**
|
|
351
|
+
* toolkit_cmd 实现:白名单校验 → spawn(shell:true)→ 截断 → 结构化返回。
|
|
352
|
+
* 全路径不抛:拒绝/超时/失败都以 {ok:false, ...} 返回,方便本体直接读字段。
|
|
353
|
+
* @param {{cmd:string, cwd?:string, timeoutMs?:number}} args
|
|
354
|
+
* @param {object} cfg 合并后配置
|
|
355
|
+
* @param {Function} [log] 留痕写入器
|
|
356
|
+
*/
|
|
357
|
+
export async function runCmd(args, cfg, log) {
|
|
358
|
+
const merged = mergeConfig(cfg)
|
|
359
|
+
const cmd = String(args?.cmd ?? '').trim()
|
|
360
|
+
const rec = makeRec('toolkit_cmd', capSummary(redactSensitive(cmd)))
|
|
361
|
+
const started = Date.now()
|
|
362
|
+
|
|
363
|
+
/** 统一出口:填耗时与截断信息、留痕、返回。 */
|
|
364
|
+
const finish = (result, status) => {
|
|
365
|
+
rec.status = status
|
|
366
|
+
rec.durationMs = Date.now() - started
|
|
367
|
+
rec.outBytes = (result.stdout?.length ?? 0) + (result.stderr?.length ?? 0)
|
|
368
|
+
rec.truncated = result.truncated === true
|
|
369
|
+
rec.ok = result.ok === true
|
|
370
|
+
rec.exitCode = result.exitCode ?? null
|
|
371
|
+
rec.denyReason = result.denied === true ? String(result.reason ?? '') : ''
|
|
372
|
+
rec.error = String(result.error ?? '')
|
|
373
|
+
// 返回结构里也要带 durationMs(任务书口径:{ok, cmd, stdout, stderr, exitCode, durationMs})。
|
|
374
|
+
result.durationMs = rec.durationMs
|
|
375
|
+
try {
|
|
376
|
+
log?.(rec)
|
|
377
|
+
} catch {
|
|
378
|
+
/* 留痕器自己不该抛,再兜一层 */
|
|
379
|
+
}
|
|
380
|
+
return result
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
if (!cmd) {
|
|
384
|
+
return finish({ ok: false, cmd, stdout: '', stderr: '', exitCode: null, denied: false, timedOut: false, reason: '', error: 'cmd 不能为空' }, 'error')
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
// 1) shell 元字符:防白名单命令被重定向/管道/命令替换拼接成写操作。
|
|
388
|
+
const meta = findShellMetachar(cmd)
|
|
389
|
+
if (meta) {
|
|
390
|
+
return finish({
|
|
391
|
+
ok: false, cmd, stdout: '', stderr: '', exitCode: null, denied: true, timedOut: false,
|
|
392
|
+
reason: `命令含 shell 元字符 "${meta}"(禁止重定向/管道/命令替换),已拒绝`,
|
|
393
|
+
}, 'denied')
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
// 2) 变更类黑名单:第一词命中就给明确理由(publish/push/install/rm/del/mkdir/cp/mv…)。
|
|
397
|
+
const deny = findDenyWord(cmd, merged.cmdDenyWords)
|
|
398
|
+
if (deny) {
|
|
399
|
+
return finish({
|
|
400
|
+
ok: false, cmd, stdout: '', stderr: '', exitCode: null, denied: true, timedOut: false,
|
|
401
|
+
reason: `"${deny}" 是写变更类命令,toolkit_cmd 只执行只读命令,已拒绝`,
|
|
402
|
+
}, 'denied')
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
// 3) 只读白名单前缀(真正的门,白名单外一律拒绝)。
|
|
406
|
+
const prefix = matchesWhitelist(cmd, merged.cmdWhitelist)
|
|
407
|
+
if (!prefix) {
|
|
408
|
+
return finish({
|
|
409
|
+
ok: false, cmd, stdout: '', stderr: '', exitCode: null, denied: true, timedOut: false,
|
|
410
|
+
reason: `命令不在只读白名单内(前缀须命中如 git log / git status / npm view / ls / dir / cat 等),已拒绝`,
|
|
411
|
+
}, 'denied')
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
// 4) cwd 校验(给了就必须是存在的目录)。
|
|
415
|
+
let cwd
|
|
416
|
+
if (args?.cwd != null && String(args.cwd).trim()) {
|
|
417
|
+
cwd = resolve(String(args.cwd).trim())
|
|
418
|
+
try {
|
|
419
|
+
if (!statSync(cwd).isDirectory()) throw new Error('不是目录')
|
|
420
|
+
} catch {
|
|
421
|
+
return finish({ ok: false, cmd, stdout: '', stderr: '', exitCode: null, denied: false, timedOut: false, reason: '', error: `cwd 不存在或不是目录:${cwd}` }, 'error')
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
// 5) 超时:单次可调,但夹在 [200, cmdTimeoutMaxMs]。
|
|
426
|
+
const timeoutMs = Number.isInteger(args?.timeoutMs) && args.timeoutMs >= 200
|
|
427
|
+
? Math.min(args.timeoutMs, merged.cmdTimeoutMaxMs)
|
|
428
|
+
: merged.cmdTimeoutMs
|
|
429
|
+
|
|
430
|
+
const base = { ok: false, cmd, exitCode: null, denied: false, timedOut: false, reason: '', error: '', whitelisted: prefix }
|
|
431
|
+
const out = makeCollector(merged.collectCapBytes)
|
|
432
|
+
const err = makeCollector(merged.collectCapBytes)
|
|
433
|
+
|
|
434
|
+
return await new Promise((done) => {
|
|
435
|
+
let child
|
|
436
|
+
try {
|
|
437
|
+
child = spawn(cmd, { shell: true, cwd, windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] })
|
|
438
|
+
} catch (error) {
|
|
439
|
+
done(finish({ ...base, stdout: '', stderr: '', error: `进程拉起失败:${error?.message ?? error}` }, 'error'))
|
|
440
|
+
return
|
|
441
|
+
}
|
|
442
|
+
let settled = false
|
|
443
|
+
let timedOut = false
|
|
444
|
+
const timer = setTimeout(() => {
|
|
445
|
+
// 超时:立刻结算返回(不等 close)——Windows 上杀掉 shell 后孙进程可能还握着
|
|
446
|
+
// stdio 管道,close 事件要等它退出才触发,等下去超时就名存实亡了。
|
|
447
|
+
timedOut = true
|
|
448
|
+
killTree(child)
|
|
449
|
+
settle(
|
|
450
|
+
{ ...base, stdout: out.text(), stderr: err.text(), timedOut: true, error: `命令超过 ${timeoutMs}ms 未结束,已杀进程` },
|
|
451
|
+
'timeout',
|
|
452
|
+
)
|
|
453
|
+
}, timeoutMs)
|
|
454
|
+
if (typeof timer.unref === 'function') timer.unref()
|
|
455
|
+
|
|
456
|
+
const settle = (result, status) => {
|
|
457
|
+
if (settled) return
|
|
458
|
+
settled = true
|
|
459
|
+
clearTimeout(timer)
|
|
460
|
+
// 收集器里已经是完整 utf8 文本(Buffer.concat 后一次性解码);这里只做截断。
|
|
461
|
+
const co = truncateWithMark(result.stdout ?? '', merged.maxOutputChars)
|
|
462
|
+
const ce = truncateWithMark(result.stderr ?? '', merged.maxOutputChars)
|
|
463
|
+
done(finish(
|
|
464
|
+
{
|
|
465
|
+
...result,
|
|
466
|
+
stdout: co.text,
|
|
467
|
+
stderr: ce.text,
|
|
468
|
+
truncated: co.truncated || ce.truncated || out.overflow || err.overflow,
|
|
469
|
+
},
|
|
470
|
+
status,
|
|
471
|
+
))
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
if (child.stdout) child.stdout.on('data', (chunk) => out.push(chunk))
|
|
475
|
+
if (child.stderr) child.stderr.on('data', (chunk) => err.push(chunk))
|
|
476
|
+
child.on('error', (error) => {
|
|
477
|
+
clearTimeout(timer)
|
|
478
|
+
settle({ ...base, stdout: out.text(), stderr: err.text(), error: `进程执行失败:${error?.message ?? error}` }, 'error')
|
|
479
|
+
})
|
|
480
|
+
child.on('close', (code) => {
|
|
481
|
+
if (timedOut) {
|
|
482
|
+
settle({ ...base, stdout: out.text(), stderr: err.text(), timedOut: true, error: `命令超过 ${timeoutMs}ms 未结束,已杀进程` }, 'timeout')
|
|
483
|
+
return
|
|
484
|
+
}
|
|
485
|
+
const exitCode = typeof code === 'number' ? code : null
|
|
486
|
+
settle(
|
|
487
|
+
{
|
|
488
|
+
...base,
|
|
489
|
+
ok: exitCode === 0,
|
|
490
|
+
stdout: out.text(),
|
|
491
|
+
stderr: err.text(),
|
|
492
|
+
exitCode,
|
|
493
|
+
reason: exitCode === 0 ? '' : `命令退出码非 0(${exitCode}),详见 stderr`,
|
|
494
|
+
},
|
|
495
|
+
exitCode === 0 ? (out.overflow || err.overflow ? 'truncated' : 'success') : 'error',
|
|
496
|
+
)
|
|
497
|
+
})
|
|
498
|
+
})
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
/* ------------------------------------------------------------------ *
|
|
502
|
+
* 工具实现 2:toolkit_read —— 文件探测 + 小文件读取
|
|
503
|
+
* ------------------------------------------------------------------ */
|
|
504
|
+
|
|
505
|
+
/**
|
|
506
|
+
* toolkit_read 实现:探测 + 读前 maxBytes。读是安全的,不限路径;读不到 exists:false。
|
|
507
|
+
* @param {{path:string, maxBytes?:number}} args
|
|
508
|
+
*/
|
|
509
|
+
export function doRead(args, cfg, log) {
|
|
510
|
+
const merged = mergeConfig(cfg)
|
|
511
|
+
const rawPath = String(args?.path ?? '').trim()
|
|
512
|
+
const rec = makeRec('toolkit_read', capSummary(redactSensitive(rawPath)))
|
|
513
|
+
const started = Date.now()
|
|
514
|
+
const finish = (result, status) => {
|
|
515
|
+
rec.status = status
|
|
516
|
+
rec.durationMs = Date.now() - started
|
|
517
|
+
rec.outBytes = result.content?.length ?? 0
|
|
518
|
+
rec.truncated = result.truncated === true
|
|
519
|
+
rec.ok = result.ok === true
|
|
520
|
+
rec.error = String(result.error ?? '')
|
|
521
|
+
try {
|
|
522
|
+
log?.(rec)
|
|
523
|
+
} catch {
|
|
524
|
+
/* 兜一层 */
|
|
525
|
+
}
|
|
526
|
+
return result
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
if (!rawPath) {
|
|
530
|
+
return finish({ ok: false, exists: false, path: rawPath, size: 0, mtime: null, content: '', isFile: false, isDir: false, truncated: false, error: 'path 不能为空' }, 'error')
|
|
531
|
+
}
|
|
532
|
+
const maxBytes = Number.isInteger(args?.maxBytes) && args.maxBytes > 0
|
|
533
|
+
? Math.min(args.maxBytes, merged.readMaxBytesCap)
|
|
534
|
+
: merged.readMaxBytes
|
|
535
|
+
|
|
536
|
+
const target = resolve(rawPath)
|
|
537
|
+
let stats
|
|
538
|
+
try {
|
|
539
|
+
stats = statSync(target)
|
|
540
|
+
} catch (error) {
|
|
541
|
+
if (error?.code === 'ENOENT' || error?.code === 'ENOTDIR') {
|
|
542
|
+
// 读不到是正常答案,不是失败。
|
|
543
|
+
return finish({ ok: true, exists: false, path: target, size: 0, mtime: null, content: '', isFile: false, isDir: false, truncated: false }, 'success')
|
|
544
|
+
}
|
|
545
|
+
return finish({ ok: false, exists: false, path: target, size: 0, mtime: null, content: '', isFile: false, isDir: false, truncated: false, error: `探测失败:${error?.code ?? ''} ${error?.message ?? error}` }, 'error')
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
if (stats.isDirectory()) {
|
|
549
|
+
return finish({ ok: true, exists: true, path: target, size: 0, mtime: stats.mtime.toISOString(), content: '', isFile: false, isDir: true, truncated: false }, 'success')
|
|
550
|
+
}
|
|
551
|
+
if (!stats.isFile()) {
|
|
552
|
+
return finish({ ok: false, exists: true, path: target, size: stats.size, mtime: stats.mtime.toISOString(), content: '', isFile: false, isDir: false, truncated: false, error: '既不是常规文件也不是目录(符号链接/设备等),不读' }, 'error')
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
const truncated = stats.size > maxBytes
|
|
556
|
+
let content = ''
|
|
557
|
+
try {
|
|
558
|
+
const fd = openSync(target, 'r')
|
|
559
|
+
try {
|
|
560
|
+
const buf = Buffer.alloc(Math.min(maxBytes, stats.size))
|
|
561
|
+
const read = readSync(fd, buf, 0, buf.length, 0)
|
|
562
|
+
content = utf8Safe(buf.subarray(0, read))
|
|
563
|
+
} finally {
|
|
564
|
+
closeSync(fd)
|
|
565
|
+
}
|
|
566
|
+
} catch (error) {
|
|
567
|
+
return finish({ ok: false, exists: true, path: target, size: stats.size, mtime: stats.mtime.toISOString(), content: '', isFile: true, isDir: false, truncated: false, error: `读取失败:${error?.code ?? ''} ${error?.message ?? error}` }, 'error')
|
|
568
|
+
}
|
|
569
|
+
return finish(
|
|
570
|
+
{ ok: true, exists: true, path: target, size: stats.size, mtime: stats.mtime.toISOString(), content, isFile: true, isDir: false, truncated },
|
|
571
|
+
truncated ? 'truncated' : 'success',
|
|
572
|
+
)
|
|
573
|
+
}
|
|
574
|
+
|
|
575
|
+
/* ------------------------------------------------------------------ *
|
|
576
|
+
* 工具实现 3:toolkit_write —— 受限文件写入
|
|
577
|
+
* ------------------------------------------------------------------ */
|
|
578
|
+
|
|
579
|
+
/** 路径同一性(Windows 大小写不敏感)。 */
|
|
580
|
+
function samePath(left, right) {
|
|
581
|
+
const a = resolve(left)
|
|
582
|
+
const b = resolve(right)
|
|
583
|
+
return process.platform === 'win32' ? a.toLowerCase() === b.toLowerCase() : a === b
|
|
584
|
+
}
|
|
585
|
+
|
|
586
|
+
/** child 是否在 parent 里(按规范化路径前缀比,不是字符串包含)。 */
|
|
587
|
+
function isInside(child, parent) {
|
|
588
|
+
if (samePath(child, parent)) return true
|
|
589
|
+
const a = resolve(child)
|
|
590
|
+
const b = resolve(parent)
|
|
591
|
+
const [left, right] = process.platform === 'win32' ? [a.toLowerCase(), b.toLowerCase()] : [a, b]
|
|
592
|
+
const prefix = right.endsWith(sep) ? right : `${right}${sep}`
|
|
593
|
+
return left.startsWith(prefix)
|
|
594
|
+
}
|
|
595
|
+
|
|
596
|
+
/** 生效的写入白名单根目录(每次调用现算:记忆根支持运行时热切换)。 */
|
|
597
|
+
function effectiveWriteRoots(merged) {
|
|
598
|
+
const custom = Array.isArray(merged.writePaths) && merged.writePaths.length > 0 ? merged.writePaths : null
|
|
599
|
+
const roots = []
|
|
600
|
+
if (custom) {
|
|
601
|
+
for (const item of custom) {
|
|
602
|
+
if (typeof item === 'string' && item.trim()) roots.push(resolve(item.trim()))
|
|
603
|
+
}
|
|
604
|
+
return roots
|
|
605
|
+
}
|
|
606
|
+
// 默认:记忆根(resolveRoot 动态解析,搬家自动跟随)+ writeExtraPaths(机器相关路径放配置)。
|
|
607
|
+
try {
|
|
608
|
+
const { root, reachable } = resolveRoot()
|
|
609
|
+
if (root && reachable) roots.push(resolve(root))
|
|
610
|
+
} catch {
|
|
611
|
+
/* 记忆根解析失败就不含它——后面白名单校验会拒绝,绝不静默放宽到别处 */
|
|
612
|
+
}
|
|
613
|
+
for (const item of Array.isArray(merged.writeExtraPaths) ? merged.writeExtraPaths : []) {
|
|
614
|
+
if (typeof item === 'string' && item.trim()) roots.push(resolve(item.trim()))
|
|
615
|
+
}
|
|
616
|
+
return roots
|
|
617
|
+
}
|
|
618
|
+
|
|
619
|
+
/** 文件名时间戳:`YYYYMMDD-HHMMSS`。 */
|
|
620
|
+
function stampSec() {
|
|
621
|
+
const now = new Date()
|
|
622
|
+
const pad = (n) => String(n).padStart(2, '0')
|
|
623
|
+
return `${now.getFullYear()}${pad(now.getMonth() + 1)}${pad(now.getDate())}-${pad(now.getHours())}${pad(now.getMinutes())}${pad(now.getSeconds())}`
|
|
624
|
+
}
|
|
625
|
+
|
|
626
|
+
/**
|
|
627
|
+
* toolkit_write 实现:白名单校验 → 64KB 限幅 → .bak 备份 → 原子写(tmp + rename)。
|
|
628
|
+
* @param {{path:string, content:string}} args
|
|
629
|
+
*/
|
|
630
|
+
export function doWrite(args, cfg, log) {
|
|
631
|
+
const merged = mergeConfig(cfg)
|
|
632
|
+
const rawPath = String(args?.path ?? '').trim()
|
|
633
|
+
const rec = makeRec('toolkit_write', capSummary(redactSensitive(rawPath)))
|
|
634
|
+
const started = Date.now()
|
|
635
|
+
const finish = (result, status) => {
|
|
636
|
+
rec.status = status
|
|
637
|
+
rec.durationMs = Date.now() - started
|
|
638
|
+
rec.outBytes = result.bytes ?? 0
|
|
639
|
+
rec.denyReason = result.denied === true ? String(result.reason ?? '') : ''
|
|
640
|
+
rec.ok = result.ok === true
|
|
641
|
+
rec.error = String(result.error ?? '')
|
|
642
|
+
try {
|
|
643
|
+
log?.(rec)
|
|
644
|
+
} catch {
|
|
645
|
+
/* 兜一层 */
|
|
646
|
+
}
|
|
647
|
+
return result
|
|
648
|
+
}
|
|
649
|
+
|
|
650
|
+
if (!rawPath) {
|
|
651
|
+
return finish({ ok: false, path: rawPath, bytes: 0, backupPath: null, denied: true, reason: 'path 不能为空' }, 'denied')
|
|
652
|
+
}
|
|
653
|
+
|
|
654
|
+
const target = resolve(rawPath)
|
|
655
|
+
const roots = effectiveWriteRoots(merged)
|
|
656
|
+
const inside = roots.find((root) => isInside(target, root))
|
|
657
|
+
if (!inside) {
|
|
658
|
+
return finish({
|
|
659
|
+
ok: false, path: target, bytes: 0, backupPath: null, denied: true,
|
|
660
|
+
reason: `目标路径不在写入白名单内。允许的根目录:${roots.length > 0 ? roots.join(';') : '(空——记忆根不可达且未配置 writePaths/writeExtraPaths)'}`,
|
|
661
|
+
}, 'denied')
|
|
662
|
+
}
|
|
663
|
+
|
|
664
|
+
const content = args?.content == null ? '' : String(args.content)
|
|
665
|
+
const bytes = Buffer.byteLength(content, 'utf8')
|
|
666
|
+
if (bytes > merged.writeMaxBytes) {
|
|
667
|
+
return finish({
|
|
668
|
+
ok: false, path: target, bytes, backupPath: null, denied: true,
|
|
669
|
+
reason: `内容 ${bytes} 字节,超过单次写入上限 ${merged.writeMaxBytes} 字节(64KB)——大文件请派小伙伴用文件工具写`,
|
|
670
|
+
}, 'denied')
|
|
671
|
+
}
|
|
672
|
+
|
|
673
|
+
// 目标若已存在且是目录 → 拒绝(没法用文件覆盖目录)。
|
|
674
|
+
let existed = false
|
|
675
|
+
try {
|
|
676
|
+
existed = statSync(target).isFile()
|
|
677
|
+
if (!existed) {
|
|
678
|
+
return finish({ ok: false, path: target, bytes, backupPath: null, denied: false, reason: '', error: '目标已存在且不是常规文件(目录?),已拒绝' }, 'error')
|
|
679
|
+
}
|
|
680
|
+
} catch {
|
|
681
|
+
existed = false
|
|
682
|
+
}
|
|
683
|
+
|
|
684
|
+
// 覆盖前备份:同目录 `原名.bak-YYYYMMDD-HHMMSS`,撞名追加序号。
|
|
685
|
+
let backupPath = null
|
|
686
|
+
if (existed) {
|
|
687
|
+
const dir = dirname(target)
|
|
688
|
+
const base = target.slice(dir.length + 1)
|
|
689
|
+
let candidate = join(dir, `${base}.bak-${stampSec()}`)
|
|
690
|
+
let suffix = 2
|
|
691
|
+
while (true) {
|
|
692
|
+
try {
|
|
693
|
+
statSync(candidate)
|
|
694
|
+
candidate = join(dir, `${base}.bak-${stampSec()}-${suffix}`)
|
|
695
|
+
suffix += 1
|
|
696
|
+
continue
|
|
697
|
+
} catch {
|
|
698
|
+
break
|
|
699
|
+
}
|
|
700
|
+
}
|
|
701
|
+
try {
|
|
702
|
+
copyFileSync(target, candidate)
|
|
703
|
+
backupPath = candidate
|
|
704
|
+
} catch (error) {
|
|
705
|
+
return finish({ ok: false, path: target, bytes, backupPath: null, denied: false, reason: '', error: `备份失败(未写入):${error?.code ?? ''} ${error?.message ?? error}` }, 'error')
|
|
706
|
+
}
|
|
707
|
+
}
|
|
708
|
+
|
|
709
|
+
// 原子写:先写同目录临时文件再 rename(rename 同目录内是原子的;跨目录不做——临时文件与目标同目录)。
|
|
710
|
+
const dir = dirname(target)
|
|
711
|
+
const tmp = join(dir, `${target.slice(dir.length + 1)}.tmp-${process.pid}-${Date.now()}`)
|
|
712
|
+
try {
|
|
713
|
+
mkdirSync(dir, { recursive: true })
|
|
714
|
+
writeFileSync(tmp, content, 'utf8')
|
|
715
|
+
renameSync(tmp, target)
|
|
716
|
+
} catch (error) {
|
|
717
|
+
// 清理残留的临时文件(best effort,失败不影响错误上报)。
|
|
718
|
+
try {
|
|
719
|
+
rmSync(tmp, { force: true })
|
|
720
|
+
} catch {
|
|
721
|
+
/* tmp 不在了就算了 */
|
|
722
|
+
}
|
|
723
|
+
return finish({ ok: false, path: target, bytes, backupPath, denied: false, reason: '', error: `写入失败:${error?.code ?? ''} ${error?.message ?? error}` }, 'error')
|
|
724
|
+
}
|
|
725
|
+
return finish({ ok: true, path: target, bytes, backupPath, denied: false, reason: '' }, 'success')
|
|
726
|
+
}
|
|
727
|
+
|
|
728
|
+
/* ------------------------------------------------------------------ *
|
|
729
|
+
* 工具定义(schema + 渲染)——注册范式照 lib/net.js / lib/precompact.js
|
|
730
|
+
* ------------------------------------------------------------------ */
|
|
731
|
+
|
|
732
|
+
const CMD_SCHEMA = {
|
|
733
|
+
name: 'toolkit_cmd',
|
|
734
|
+
description:
|
|
735
|
+
'只读命令执行(工具包中间层):跑白名单内的只读命令(git log/status/diff/show、npm view/search、node --version、ls/dir/type/cat/head/tail/wc/where/which 等)。任何写变更类命令(publish/push/install/rm/del/mkdir/cp/mv 等)和带管道/重定向的命令一律拒绝;输出超 2KB 截断并标注 [truncated];默认 30 秒超时杀进程。适合"看一眼就知道"的状态查询(git 在什么状态、某依赖装没装);输出大、要提炼归纳的活照旧派 subagent / retriever。',
|
|
736
|
+
parameters: {
|
|
737
|
+
type: 'object',
|
|
738
|
+
additionalProperties: false,
|
|
739
|
+
properties: {
|
|
740
|
+
cmd: { type: 'string', description: '要执行的只读命令(整条命令行字符串)。' },
|
|
741
|
+
cwd: { type: 'string', description: '工作目录(可选,必须是已存在的目录;git 命令常指定仓库路径)。' },
|
|
742
|
+
timeoutMs: { type: 'integer', description: '超时毫秒数(可选,默认 30000,上限 120000)。' },
|
|
743
|
+
},
|
|
744
|
+
required: ['cmd'],
|
|
745
|
+
},
|
|
746
|
+
output: {
|
|
747
|
+
schema: {
|
|
748
|
+
type: 'object',
|
|
749
|
+
additionalProperties: false,
|
|
750
|
+
properties: {
|
|
751
|
+
ok: { type: 'boolean' },
|
|
752
|
+
cmd: { type: 'string' },
|
|
753
|
+
stdout: { type: 'string' },
|
|
754
|
+
stderr: { type: 'string' },
|
|
755
|
+
exitCode: { type: ['integer', 'null'] },
|
|
756
|
+
durationMs: { type: 'integer' },
|
|
757
|
+
truncated: { type: 'boolean' },
|
|
758
|
+
denied: { type: 'boolean' },
|
|
759
|
+
timedOut: { type: 'boolean' },
|
|
760
|
+
reason: { type: 'string' },
|
|
761
|
+
whitelisted: { type: 'string' },
|
|
762
|
+
},
|
|
763
|
+
required: ['ok', 'cmd', 'stdout', 'stderr', 'exitCode', 'durationMs', 'truncated', 'denied', 'timedOut'],
|
|
764
|
+
},
|
|
765
|
+
render: (_args, value) => {
|
|
766
|
+
if (value.denied) return TEXT_BLOCK(`已拒绝(只读白名单外):${value.reason}`)
|
|
767
|
+
if (value.timedOut) return TEXT_BLOCK(`超时(已杀进程):${value.cmd}\n${value.stdout ?? ''}`)
|
|
768
|
+
const head = `退出码 ${value.exitCode},耗时 ${value.durationMs}ms${value.truncated ? ',输出已截断' : ''}`
|
|
769
|
+
const parts = [head]
|
|
770
|
+
if (value.stdout) parts.push(`--- stdout ---\n${value.stdout}`)
|
|
771
|
+
if (value.stderr) parts.push(`--- stderr ---\n${value.stderr}`)
|
|
772
|
+
if (value.error) parts.push(`error: ${value.error}`)
|
|
773
|
+
return TEXT_BLOCK(parts.join('\n'))
|
|
774
|
+
},
|
|
775
|
+
},
|
|
776
|
+
}
|
|
777
|
+
|
|
778
|
+
const READ_SCHEMA = {
|
|
779
|
+
name: 'toolkit_read',
|
|
780
|
+
description:
|
|
781
|
+
'文件探测 + 小文件读取(工具包中间层):返回 {exists, size, mtime, isFile, isDir, content}。默认读前 8KB(maxBytes 可调,上限 64KB),目录只报属性不给内容。不限路径、读不到返回 exists:false——适合确认文件/目录在不在、读标志位和小配置。要消化整份大文档、翻文件堆找内容,派 retriever。',
|
|
782
|
+
parameters: {
|
|
783
|
+
type: 'object',
|
|
784
|
+
additionalProperties: false,
|
|
785
|
+
properties: {
|
|
786
|
+
path: { type: 'string', description: '文件或目录路径。' },
|
|
787
|
+
maxBytes: { type: 'integer', description: '最多读多少字节(默认 8192,上限 65536)。' },
|
|
788
|
+
},
|
|
789
|
+
required: ['path'],
|
|
790
|
+
},
|
|
791
|
+
output: {
|
|
792
|
+
schema: {
|
|
793
|
+
type: 'object',
|
|
794
|
+
additionalProperties: false,
|
|
795
|
+
properties: {
|
|
796
|
+
ok: { type: 'boolean' },
|
|
797
|
+
exists: { type: 'boolean' },
|
|
798
|
+
path: { type: 'string' },
|
|
799
|
+
size: { type: 'integer' },
|
|
800
|
+
mtime: { type: ['string', 'null'] },
|
|
801
|
+
content: { type: 'string' },
|
|
802
|
+
isFile: { type: 'boolean' },
|
|
803
|
+
isDir: { type: 'boolean' },
|
|
804
|
+
truncated: { type: 'boolean' },
|
|
805
|
+
error: { type: 'string' },
|
|
806
|
+
},
|
|
807
|
+
required: ['ok', 'exists', 'path', 'size', 'isFile', 'isDir', 'truncated'],
|
|
808
|
+
},
|
|
809
|
+
render: (_args, value) => {
|
|
810
|
+
if (value.error && !value.ok) return TEXT_BLOCK(`读取失败:${value.path}(${value.error})`)
|
|
811
|
+
if (!value.exists) return TEXT_BLOCK(`不存在:${value.path}`)
|
|
812
|
+
if (value.isDir) return TEXT_BLOCK(`是目录:${value.path}(mtime ${value.mtime ?? ''})`)
|
|
813
|
+
const head = `${value.path}(${value.size} 字节${value.truncated ? `,已读前 ${value.content?.length ?? 0} 字符并截断` : ''})`
|
|
814
|
+
return TEXT_BLOCK(`${head}\n--- content ---\n${value.content ?? ''}`)
|
|
815
|
+
},
|
|
816
|
+
},
|
|
817
|
+
}
|
|
818
|
+
|
|
819
|
+
const WRITE_SCHEMA = {
|
|
820
|
+
name: 'toolkit_write',
|
|
821
|
+
description:
|
|
822
|
+
'受限文件写入(工具包中间层):只能写白名单目录内的文件(默认 = 记忆根 + 配置追加目录;白名单外一律拒绝并会列出允许的根目录)。单次限 64KB;原子写(先写临时文件再 rename);覆盖已有文件前自动在同目录留时间戳 .bak 备份并返回 backupPath。适合落盘状态、写经验/记录文档;大文件与代码工程改动派 subagent 用文件工具。',
|
|
823
|
+
parameters: {
|
|
824
|
+
type: 'object',
|
|
825
|
+
additionalProperties: false,
|
|
826
|
+
properties: {
|
|
827
|
+
path: { type: 'string', description: '目标文件路径(必须在写入白名单内)。' },
|
|
828
|
+
content: { type: 'string', description: '要写入的全文(UTF-8,≤64KB)。' },
|
|
829
|
+
},
|
|
830
|
+
required: ['path', 'content'],
|
|
831
|
+
},
|
|
832
|
+
output: {
|
|
833
|
+
schema: {
|
|
834
|
+
type: 'object',
|
|
835
|
+
additionalProperties: false,
|
|
836
|
+
properties: {
|
|
837
|
+
ok: { type: 'boolean' },
|
|
838
|
+
path: { type: 'string' },
|
|
839
|
+
bytes: { type: 'integer' },
|
|
840
|
+
backupPath: { type: ['string', 'null'] },
|
|
841
|
+
denied: { type: 'boolean' },
|
|
842
|
+
reason: { type: 'string' },
|
|
843
|
+
error: { type: 'string' },
|
|
844
|
+
},
|
|
845
|
+
required: ['ok', 'path', 'bytes'],
|
|
846
|
+
},
|
|
847
|
+
render: (_args, value) => {
|
|
848
|
+
if (value.denied) return TEXT_BLOCK(`写入已拒绝:${value.reason}`)
|
|
849
|
+
if (!value.ok) return TEXT_BLOCK(`写入失败:${value.path}(${value.error || value.reason})`)
|
|
850
|
+
return TEXT_BLOCK(`已写入 ${value.path}(${value.bytes} 字节)${value.backupPath ? `;原文件已备份到 ${value.backupPath}` : '(新建,无备份)'}`)
|
|
851
|
+
},
|
|
852
|
+
},
|
|
853
|
+
}
|
|
854
|
+
|
|
855
|
+
/* ------------------------------------------------------------------ *
|
|
856
|
+
* 中间层骨架:工具目录(名字 → 定义 + disposer + 底层实现)+ add/remove/list
|
|
857
|
+
* ------------------------------------------------------------------ */
|
|
858
|
+
|
|
859
|
+
/**
|
|
860
|
+
* apply:挂三个内置工具。全程 try/catch——单个工具注册失败只禁用它自己,
|
|
861
|
+
* 绝不阻塞插件激活(同 feishu/weixin/precompact 思路)。
|
|
862
|
+
* @param {object} ctx preset 作用域内的 agent 上下文(需要 tools 服务)
|
|
863
|
+
* @param {object} [config] cordis.patch.yml 里的 config
|
|
864
|
+
* @returns {{list:Function, add:Function, remove:Function, cfg:object}} 工具目录的操作句柄
|
|
865
|
+
* (loader 不使用返回值;暴露出来给测试与后续管理入口用)
|
|
866
|
+
*/
|
|
867
|
+
export function apply(ctx, config) {
|
|
868
|
+
const cfg = mergeConfig(config)
|
|
869
|
+
const warn = (msg) => {
|
|
870
|
+
try {
|
|
871
|
+
ctx?.logger?.warn?.(msg)
|
|
872
|
+
} catch {
|
|
873
|
+
/* logger 缺了就算了 */
|
|
874
|
+
}
|
|
875
|
+
}
|
|
876
|
+
|
|
877
|
+
// own-tools 白名单登记(restrict 单一真源,静态兜底表在 own-tools.js 里同步维护)。
|
|
878
|
+
try {
|
|
879
|
+
for (const toolName of TOOL_NAMES) registerOwnTool(toolName)
|
|
880
|
+
} catch (error) {
|
|
881
|
+
warn(`aiyayi-toolkit: own-tools 登记失败(工具可能被 restrict 挡住): ${error?.message ?? error}`)
|
|
882
|
+
}
|
|
883
|
+
|
|
884
|
+
/**
|
|
885
|
+
* 工具目录(方案 §2.3 要素 1):名字 → { 定义, disposer, source }。
|
|
886
|
+
* disposer 来自 ctx.tools.register()(方案 §6.1:官方返回值,精确反注册)。
|
|
887
|
+
*/
|
|
888
|
+
const registry = new Map()
|
|
889
|
+
|
|
890
|
+
/** add:注册一个工具并登记目录;同名重复注册直接返回旧 disposer(幂等)。 */
|
|
891
|
+
const add = (toolName, def, impl) => {
|
|
892
|
+
if (registry.has(toolName)) return registry.get(toolName).disposer
|
|
893
|
+
const disposer = ctx.tools.register({ ...def, execute: impl })
|
|
894
|
+
registry.set(toolName, { def, disposer, source: 'builtin' })
|
|
895
|
+
return disposer
|
|
896
|
+
}
|
|
897
|
+
|
|
898
|
+
/** remove:精确反注册(调 disposer + 移出目录)。 */
|
|
899
|
+
const remove = (toolName) => {
|
|
900
|
+
const entry = registry.get(toolName)
|
|
901
|
+
if (!entry) return false
|
|
902
|
+
registry.delete(toolName)
|
|
903
|
+
try {
|
|
904
|
+
entry.disposer?.()
|
|
905
|
+
} catch (error) {
|
|
906
|
+
warn(`aiyayi-toolkit: 反注册 ${toolName} 时 disposer 报错: ${error?.message ?? error}`)
|
|
907
|
+
}
|
|
908
|
+
return true
|
|
909
|
+
}
|
|
910
|
+
|
|
911
|
+
/** list:当前已注册的工具名。 */
|
|
912
|
+
const list = () => [...registry.keys()]
|
|
913
|
+
|
|
914
|
+
// 挂三个内置工具:转发壳把调用交给底层实现,并带配置与留痕(方案 §2.3 要素 3)。
|
|
915
|
+
const logUsage = createUsageLogger(cfg, warn)
|
|
916
|
+
const builtins = [
|
|
917
|
+
[CMD_SCHEMA, (args) => runCmd(args, cfg, logUsage)],
|
|
918
|
+
[READ_SCHEMA, (args) => doRead(args, cfg, logUsage)],
|
|
919
|
+
[WRITE_SCHEMA, (args) => doWrite(args, cfg, logUsage)],
|
|
920
|
+
]
|
|
921
|
+
for (const [def, impl] of builtins) {
|
|
922
|
+
try {
|
|
923
|
+
add(def.name, def, impl)
|
|
924
|
+
} catch (error) {
|
|
925
|
+
warn(`aiyayi-toolkit: 工具 ${def.name} 注册失败(该工具本次不可用,其余不受影响): ${error?.message ?? error}`)
|
|
926
|
+
}
|
|
927
|
+
}
|
|
928
|
+
|
|
929
|
+
// 插件卸载兜底:把目录里还挂着的全部精确反注册,避免注册泄漏。
|
|
930
|
+
try {
|
|
931
|
+
ctx.effect(
|
|
932
|
+
() => () => {
|
|
933
|
+
for (const toolName of [...registry.keys()]) remove(toolName)
|
|
934
|
+
},
|
|
935
|
+
'aiyayi-toolkit.dispose()',
|
|
936
|
+
)
|
|
937
|
+
} catch (error) {
|
|
938
|
+
warn(`aiyayi-toolkit: 卸载钩子注册失败: ${error?.message ?? error}`)
|
|
939
|
+
}
|
|
940
|
+
|
|
941
|
+
return { list, add, remove, cfg }
|
|
942
|
+
}
|
|
943
|
+
|
|
944
|
+
/** 配置合并(数组整体替换,不做深合并——白名单语义要的是"换成这份",不是"叠加"。)。 */
|
|
945
|
+
export function mergeConfig(config) {
|
|
946
|
+
return { ...DEFAULT_CONFIG, ...(config ?? {}) }
|
|
947
|
+
}
|
|
948
|
+
|
|
949
|
+
/* 测试出口:只给单测用。 */
|
|
950
|
+
export const __testing = {
|
|
951
|
+
makeRec,
|
|
952
|
+
ringTrim,
|
|
953
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-aiyayi",
|
|
3
|
-
"version": "1.5.
|
|
3
|
+
"version": "1.5.38",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"author": "巴依浩爷 (bayihy)",
|
|
6
6
|
"keywords": [
|
|
@@ -28,6 +28,7 @@
|
|
|
28
28
|
"./feishu-logic": "./lib/feishu-logic.js",
|
|
29
29
|
"./weixin": "./lib/weixin.js",
|
|
30
30
|
"./precompact": "./lib/precompact.js",
|
|
31
|
+
"./toolkit": "./lib/toolkit.js",
|
|
31
32
|
"./icon": "./icon.svg"
|
|
32
33
|
},
|
|
33
34
|
"files": [
|
|
@@ -44,6 +45,7 @@
|
|
|
44
45
|
"lib/feishu.js",
|
|
45
46
|
"lib/feishu-logic.js",
|
|
46
47
|
"lib/precompact.js",
|
|
48
|
+
"lib/toolkit.js",
|
|
47
49
|
"lib/weixin.js",
|
|
48
50
|
"lib/weixin/",
|
|
49
51
|
"skills",
|