dsh-aiyayi 1.2.5 → 1.2.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -11,10 +11,10 @@
11
11
  | 跟随会话模型 | 无需插件行(1.0.1 起移除 agent-default-model 行) | 本体模型直接跟随用户会话模型;旧版"preset 作用域挂 `@deepseek-ai/dsh-agent-default-model` + `isolate: {agentDefaultModel: true}`"的写法在新版 DSH 过不了 schema 校验(见坑 #13),已删除 |
12
12
  | 干活的子智能体 | `@deepseek-ai/dsh-tool-subagent`(delegation 组,isolate workflowEngine) | `agentPreset: aiyayi-worker`(自建"小伙伴"预设,全量工具 + 原生自动压缩,见坑 #14);子代模型跟随用户会话模型,如需钉死可在 `agentOptions` 配置 provider/model |
13
13
  | 工具白名单 | 自写插件 `aiyayi-restrict`(本包 `lib/restrict.js`,v3.1 pre-step 方案)+ `lib/own-tools.js` 单一真源 | 启动期零 restrict 调用;她每个会话第一步前,先用探针从校验器报错里解析出当刻继承面全集,再 `deny = 全集 − 她自己的工具`——宿主层漏进来的 acp_*/mnemon_*/compress/search_context/working_directory 等对她隐藏,且自动适应宿主工具增减。放行名单从 `own-tools.js` 读(注册处登记、放行处判定),新增工具只改一处,不再漂(见坑 #19)。**2026-11-02 实测生效**:新会话第 2 个请求起工具恰好 11 个,第 1 个请求仍带全套(见坑 #9) |
14
- | 重逢感知 | 自写插件 `aiyayi-presence`(本包 `lib/presence.js`) | 每个回合第一步,往消息尾部追加一条 `[重逢]` 快照(time-context 同款 pre-step 注入范式):他多久没来(presence.json)、你上次活动、你上次留的状态(state.md)、没说出口的话(wishes.json)。跨会话生效,`[SCHEDULE REMINDER` 唤醒消息不算"他来了"。工具 `update_state`(收尾留状态)/ `wish`(add/list/done 心愿单) |
14
+ | 重逢感知 | 自写插件 `aiyayi-presence`(本包 `lib/presence.js`) | 每个回合第一步,往消息尾部追加一条 `[重逢]` 快照(time-context 同款 pre-step 注入范式):他多久没来(presence.json)、你上次活动、你上次留的状态(state.md)、没说出口的话(wishes.json)。快照还带**版本自述**:`你当前插件版本:dsh-aiyayi x.y.z`(package.json 现读不写死,让她对自己版本有概念、不与 DSH 桌面版混淆;有新版时 updates 插件照旧单独提醒)。跨会话生效,`[SCHEDULE REMINDER` 唤醒消息不算"他来了"。工具 `update_state`(收尾留状态)/ `wish`(add/list/done 心愿单) |
15
15
  | 自我状态(体检单) | 同上 `aiyayi-presence`(v1.2.0 起) | `session/event` 总线折叠真实运行数据:模型与思考档、上下文用量(provider 实测 usage 优先,tokenMeter 估算兜底并标"估算")、缓存命中率、上轮输出 tok/s、本会话轮数、上轮异常。变化明显(≥2048 token / 模型切换 / 异常)才注入,不每轮白涨。用量过八成/九成(估算口径按中文偏差 ÷0.49 校准,见坑 #16)注入 `[上下文提醒]`:劝用户开新会话、并让用户走之前说一声好让她收尾(update_state/补记忆/把话说完);每档只提醒一次 |
16
16
  | 主动开口 | `tool-schedule`(dsh 原生)+ persona 指引 | 到期提醒会把冷会话真唤醒、以 user 消息落进定闹钟的那个会话——她想主动说话就 `schedule_create` 定闹钟;DSH 没开着会存着、下次启动补投 |
17
- | 新版本提醒 | 自写插件 `aiyayi-updates`(本包 `lib/updates.js`) | 每个会话第一个回合查一次 npm(registry.npmjs.org,失败落 npmmirror;成功结果缓存 6h、失败 30min 后重试):本地版本比 latest 旧时,往消息尾部追加 `[更新提示]` 快照,她会用自己的口吻顺口提一句。同一远端版本只提醒一次(updates.json 落盘去重,跨重启不重复念叨);检查失败/离线一律静默 |
17
+ | 新版本提醒 | 自写插件 `aiyayi-updates`(本包 `lib/updates.js`) | 每个会话第一个回合查一次 npm(registry.npmjs.org,失败落 npmmirror;成功结果缓存 6h、失败 30min 后重试):本地版本比 latest 旧时,往消息尾部追加 `[更新提示]` 快照,她会用自己的口吻顺口提一句。同一远端版本只提醒一次(updates.json 落盘去重,跨重启不重复念叨);检查失败/离线一律静默。**判据:`~\\.dsh\\aiyayi\\updates.json` 不存在 = 从没发现过新版(本地已是最新);她答不上"自己是什么版本"是设计边界(升级判断靠被动推送),已由 presence 的版本自述补上** |
18
18
  | 其他 | time-context、compaction 组(提前压缩,见坑 #14/#16)、tool-ask-user | 她没有 bash/文件/技能/搜索/网络工具,想动手只能派活 |
19
19
 
20
20
  ## 文件
@@ -27,6 +27,7 @@ npm 包为平铺结构(仓库若保留 bundle/ 子目录,发布时把其内
27
27
  - `lib/restrict.js` — aiyayi-restrict 工具白名单插件(零依赖)
28
28
  - `lib/presence.js` — aiyayi-presence 重逢感知插件(node:fs/os/path/crypto,零依赖)
29
29
  - `lib/updates.js` — aiyayi-updates 新版本提醒插件(node:fs/os/path/crypto/url + 全局 fetch,零依赖)
30
+ - `lib/net.js` — aiyayi-net 联网工具(aiyayi_fetch + aiyayi_cdp,node 内建能力实现,零外置依赖,只挂小伙伴 preset)
30
31
  - `lib/own-tools.js` — 她的工具名单单一真源(注册处登记、放行处判定,防手写白名单漂移)
31
32
  - `README.md` — 本文档
32
33
  - `icon.svg` — 头像
@@ -78,3 +79,15 @@ GUI 新建会话 → agent preset 选「**阿依娅伊**」。聊天即可;她
78
79
  22. **子代(小伙伴)失败原因不透传到本体(2026-11-05 实测;1.2.3 已修)**:宿主对派出去的子智能体的结算消息只有一句 `failed before it finished` / `It left no closing message.`——真实原因(HTTP_402 积分余额不足、上游限流、403、Illegal API invocation)只躺在子会话自己的 `turn/end` error 事件里(宿主 `terminal.diagnostic` 只有在 provider 主动给时才透传,本地 spawn 的 provider 不给)。她不知道为啥失败 → 盲目重派 3 轮白耗 ~20 分钟。修法:`aiyayi-presence` 的 `session/event` 监听不再丢弃非本体的会话事件,改把 `header.origin==="subagent"`(或带 `header.parentSession`)的子会话 `turn/end` error 记进 `childFailures`(上限 20、只记 error、错误串截 120 字符),下一个 pre-step 注入 `⚠ [小伙伴] 你派出去干活的小智能体有 N 个报错了(宿主只回一句"failed before it finished",真原因在这):…`(每次最多列 3 条、已报过的去重不唠叨)。原理:session/event 总线对所有会话广播,插件端按 `agentsById` 过滤才是它之前只见本体的原因;子会话 header 带 `parentSession` 链接,可归属到正确的父会话。
79
80
  23. **新会话首次对话时提醒"关闭思考"(2026-11-05 新增;1.2.4 已做)**:日常闲聊用不上深度思考,回复慢还费 token。`aiyayi-presence` 在每个**新会话的首次对话**(pre-step step===1、每会话只提醒一次)注入 `💡 小建议`:当本体模型的 `reasoningEffort` 已显式选了一个思考档位(有档位 = 必支持"关闭思考",见 pi-ai 校验规则"reasoningEfforts offers no level beyond off → refuse")或通过 `ctx.llm.resolveModelInfo()` 探到 `reasoning.efforts` 里有 `off` 档时,提醒她去模型选项里选「关闭思考」。已选 `off`/`none`、探不到模型信息(`ctx.llm` 不可用、resolveModelInfo 失败)或非推理模型(`reasoning: undefined`)都不打扰。教训:判断"模型支持某个能力"优先用运行时解析(resolveModelInfo),拿不到再退化为显式配置信号,且**只在首轮提醒一次**,别每轮唠叨。
80
81
  24. **子代模型不跟随本体切换(2026-11-05 实测并修复;1.2.5 已做)**:派出去的子智能体在 spawn 时就冻结了当时的 provider/model/reasoningEffort(内核 `resolveChildAgentOptions` 从父会话当前 requestHeader 解析一次,之后 steer/followup/恢复都复用它——`agentOptions` 在续跑路径上被禁传,恢复走 descriptor 快照),所以本体因额度用完切模型继续时,**还在跑的小伙伴仍是旧模型,继续调旧渠道照样 402/限流**。修法:`aiyayi-presence` 的 `session/event` 监听把每个子会话登记进 `childSessions`(childId→parentSessionId,上限 64);本体自己的 `model/selection` 事件或 `request/header` 路由变化时,对名下每个子会话执行 `ctx.get("agents").get(childId).model.select({provider, model, reasoningEffort?})` ——内核 `AgentModel.select` 向子会话 append `model/selection` 投影事件,子会话下一步 prep 读 pending 覆盖冻结值,新模型即刻生效(同路由幂等,不会重复触发)。前提:插件与 tool-subagent 同在 preset-aiyayi 作用域,`ctx.get("agents")` 可解析;拿不到 agents 就静默跳过(尽力而为)。注意子代自己显式选的模型(modelSelectionSettings 让模型在派活时选)不会被覆盖成本体的——只有本体路由变化才同步。
82
+ 25. **"禁止小伙伴用 web_search/web_fetch,联网改用 Playwright+CDP"的落地(2026-11-06 实测迭代;1.2.7)**:
83
+ - **背景**:web_search/web_fetch 是宿主 root 作用域全局注入的(restrict.js 注释实测:acp_*、mnemon_*、compress、search_context 等宿主根工具会原样漏进任何 preset 会话),Preset 里那个 `@deepseek-ai/dsh-tool-web` 只是又加一份。光删工具不管用、也管不到宿主那份。
84
+ - **为什么不做硬 deny**:`ctx.tools.restrict({deny:[...]})` 是**持久掩码**(内核注释"限制在 dispose 时解除",坑 #9 实测持续生效),无法按"用户当轮明确要求"临时放开——deny 就一直在,用户点名要用时也调不出来。
85
+ - **为什么纯 persona 软约束不够(1.2.7 首版失败,实测踩坑)**:小伙伴执行环境(DSH runtime node)**没有 playwright / playwright-core / chromium / chrome / msedge**(`require.resolve('playwright')` 全部 NOT available,PATH 无浏览器)。persona 写"用无头 Playwright chromium.launch()"是**空指令**——模型照做必报错,只能退回环境里现成可用的 `web_fetch`。所以"软约束 + 工具可见"拦不住它。
86
+ - **最终方案=给小伙伴嵌真正的联网工具(1.2.7)**:新增 `lib/net.js`(`aiyayi-net`,只挂 aiyayi-worker 预设),用 **node 内建能力**实现两个工具,零外置依赖、跨 DSH 可靠:
87
+ - `aiyayi_fetch`:node 内建 `fetch` + 自定义 UA + 超时 + 重试,抓静态/普通网页正文(替代 web_fetch;实测抓 time.is/Beijing → 200,不依赖 DeepSeek 账户、不欠费)。render 会把正文交给模型,不是只给状态码。
88
+ - `aiyayi_cdp`:裸 WebSocket(node v24 内置全局 WebSocket)连 CDP。**若探测到用户已开的 `--remote-debugging-port` 浏览器就接管(保留登录态);若没有,自动 `spawn` 系统 Chrome/Edge `--headless=new` 拉起一个,抓完即关**(实测:headless Chrome + navigate example.com → 拿到 title + 正文)。`Page.navigate` / `Runtime.evaluate`(拿渲染后 DOM)/ `Network.getAllCookies`(含 httpOnly)。零外置依赖(node:child_process + 全局 WebSocket),不依赖 playwright。
89
+ - persona「联网规矩」改为:**默认用 aiyayi_fetch / aiyayi_cdp,不用 web_search/web_fetch;只有用户当轮明确点名 web_search/web_fetch 才允许**。
90
+ - **关键教训**:给 subagent 的"联网能力"不能只靠 persona 一句话,必须真的给它一个**执行端能跑的工具**。而 subagent 执行环境只有 DSH runtime node,所以要么用 node 内建能力(fetch/WebSocket/CDP)实现,要么确认真装了 playwright。跨 DSH 最稳的是前者(node 内建必有)。
91
+ 26. **node 内建能力可替代 playwright 承载"浏览器抓取"**:DSH runtime node = v24.21.0,内置**全局 WebSocket**、全局 `fetch`、`node:http`、`node:net`。node 内建就够做 CDP 接管(`Node WebSocket` 连 CDP `ws://`)+ 模拟浏览器 fetch,**不需要 require('playwright')** 依赖外置包。给 subagent 嵌"浏览器抓取"工具用这条,跨 DSH 可靠。
92
+ 27. **自定义工具必须把正文交到模型手里,不能只回状态码(2026-11-06 实测;1.2.7 修)**:最初 `aiyayi_fetch` 的 `execute` 返回了完整 body,但 `output.render` 只输出 `(抓了 X → HTTP 200,正文 N 字符)` 这句摘要。DSH 里**模型实际看到的是 render 的文本**,不是 execute 的返回值——于是小伙伴拿到"200 / 2万字符"但看不到正文,提取不出事实(表现:它说"能连上但没真东西")。修法:render 必须把 `body`(或 cdp 的 `text`/`value`/`cookies`)拼进 `TEXT_BLOCK` 交给模型。教训:工具 deliver 的"内容"以 render 呈现为准,写 render 要当"模型真正读到的结果"对待,不是旁注摘要。
93
+ 28. **给 subagent 嵌抓取工具时,CDP 浏览器要能"自主拉起"否则仍是空能力(2026-11-06 实测;1.2.7 已做)**:最初 aiyayi_cdp 只接管用户 `--remote-debugging-port` 浏览器,用户没开就报"端口没开"。但实测发现:`node:child_process.spawn` 系统 Chrome `--headless=new --remote-debugging-port=<空闲端口>` 就能自主拉起、抓完 `kill` + 删临时 user-data-dir。于是 aiyayi_cdp 改为"探测→有就接管、没有就自动拉起 headless",**不再依赖用户手动开端口**(需登录态才需要用户开带登录的浏览器)。实测闭环:惯例 headless Chrome → CDP → navigate example.com → evaluate 拿 title+正文。坑:headless 要 `--disable-extensions` + 独立 `user-data-dir`(避免加载用户扩展、避免用默认配置目录开调试端口被拒);`findPageWs` 要排除 background_page/扩展 target。
package/cordis.patch.yml CHANGED
@@ -177,6 +177,13 @@
177
177
  上一轮因这类原因失败时,先看 todo 和已经写出来的东西,从断点接着干,别重做已完成的部分。
178
178
  需要等一段时间才能恢复的(比如配额到点、网络长时间不通),如实说明什么时候能恢复,
179
179
  请娅伊安排稍后再续,别空转干等。
180
+
181
+ 【联网规矩】
182
+ 联网查资料**默认**用你手上自带的两个工具,不要用 web_search / web_fetch:
183
+ - aiyayi_fetch:抓静态/普通网页(自带 UA、超时、重试、正文截断),替代 web_fetch;
184
+ - aiyayi_cdp:抓动态渲染页 / 需登录态页面 / Cookie。用户已开 --remote-debugging-port 浏览器时接管它(保留登录态);没开时会**自动拉起一个 headless 浏览器**抓取、抓完即关,所以你直接用就行,不必要求用户先开端口。
185
+ 只有当用户**本次明确点名**要用 web_search / web_fetch 时才允许调它们,否则一律用上面两个。
186
+ 两个工具抓完都会把**正文交给你**;只有确认连不上(网络不通/页面报错)时如实说明原因,别编造内容。
180
187
  - id: agent-instructions
181
188
  name: '@deepseek-ai/dsh-agent-instructions'
182
189
  config:
@@ -234,5 +241,7 @@
234
241
  config:
235
242
  fetch: true
236
243
  searchTimeoutMs: 60000
244
+ - id: aiyayi-net
245
+ name: 'dsh-aiyayi/net'
237
246
  - id: present
238
247
  name: '@deepseek-ai/dsh-tool-present'
package/lib/net.js ADDED
@@ -0,0 +1,478 @@
1
+ /**
2
+ * aiyayi-net — 小伙伴的联网工具(aiyayi_fetch + aiyayi_cdp)。
3
+ *
4
+ * 目的:让"阿依娅伊的小伙伴"(aiyayi-worker 预设的 subagent)在默认情况下
5
+ * **不用** web_search / web_fetch,而是用这两个内置工具联网;只有用户当轮
6
+ * 明确点名 web_search/web_fetch 时才允许用它。见 README 坑 #25。
7
+ *
8
+ * 为什么用 node 内建能力、不依赖 playwright:
9
+ * - 小伙伴执行环境(DSH runtime node)没有 playwright / playwright-core /
10
+ * chromium / chrome / msedge(实测 require.resolve 全部 NOT available),
11
+ * persona 里写"用无头 Playwright chromium.launch()"是空指令,模型照做必报错,
12
+ * 只能退回环境里现成可用的 web_fetch —— 这就是 1.2.7 首版软约束失败的原因。
13
+ * - 但 DSH runtime 的 node 有:全局 fetch、node:http、node:net、node v24 内置
14
+ * 全局 WebSocket。这些内建能力足够做"模拟浏览器抓取"和"CDP 接管浏览器",
15
+ * 不依赖任何外置 npm 包。
16
+ *
17
+ * 两个工具:
18
+ * - aiyayi_fetch:静态/普通网页抓取。node 内建 fetch + 自定义 UA + 超时 + 重试,
19
+ * 返回 status + 正文(截断保护)。替代 web_fetch 的主力。
20
+ * - aiyayi_cdp:动态页面/需登录态抓取。裸 WebSocket 连用户已启动的浏览器
21
+ * (--remote-debugging-port,见 browser-cdp-drive 技能),CDP JSON-RPC:
22
+ * Page.navigate 导航、Runtime.evaluate 在页面上下文执行 JS 拿渲染后 DOM、
23
+ * Network.getAllCookies 抓含 httpOnly 的 Cookie。
24
+ *
25
+ * 两个工具都注册到 aiyayi-worker 预设作用域,由 cordis.patch.yml 挂载。
26
+ * 零外置依赖(只用 node 内建 + 全局 fetch/WebSocket),跨 DSH 可靠。
27
+ */
28
+ import { registerOwnTool } from './own-tools.js'
29
+ import { spawn } from 'node:child_process'
30
+ import { mkdtempSync, rmSync, existsSync } from 'node:fs'
31
+ import { tmpdir, platform } from 'node:os'
32
+ import { join } from 'node:path'
33
+
34
+ /** Loader 身份。 */
35
+ export const name = 'aiyayi-net'
36
+
37
+ /** 需要的服务。 */
38
+ export const inject = ['tools']
39
+
40
+ const TEXT_BLOCK = (text) => [{ type: 'text', text }]
41
+
42
+ /** 模拟常见浏览器的 UA,避免被目标站当脚本拒绝。 */
43
+ const DEFAULT_UA =
44
+ 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36'
45
+
46
+ /** 抓取结果正文上限:防止把整个页面塞爆上下文。 */
47
+ const MAX_BODY = 20000
48
+ const MAX_CDP_RESULT = 12000
49
+
50
+ /**
51
+ * 截断到上限,保留头尾(中间替换省略标记),返回计数。
52
+ */
53
+ function truncate(text, max) {
54
+ const s = String(text ?? '')
55
+ if (s.length <= max) return s
56
+ const head = Math.floor(max * 0.6)
57
+ const tail = max - head - '…[中段省略]…'.length
58
+ return `${s.slice(0, head)}…[中段省略]…${s.slice(-tail)}`
59
+ }
60
+
61
+ /** 轻量文本清洗:压缩空行、去控制符,方便贴回上下文。 */
62
+ function tidy(raw) {
63
+ return String(raw ?? '')
64
+ .replace(/\r\n?/g, '\n')
65
+ .replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/g, '')
66
+ .replace(/[ \t]+\n/g, '\n')
67
+ .replace(/\n{3,}/g, '\n\n')
68
+ .trim()
69
+ }
70
+
71
+ /**
72
+ * CDP 单次 JSON-RPC 调用。node v24 全局 WebSocket。
73
+ * @param {string} wsUrl 例如 ws://127.0.0.1:9222/devtools/page/xxxx
74
+ * @param {string} method CDP 方法名
75
+ * @param {object} [params]
76
+ * @returns {Promise<any>} data 域(不发 result 则返回 undefined)
77
+ */
78
+ function cdpCall(wsUrl, method, params) {
79
+ return new Promise((resolve, reject) => {
80
+ let ws
81
+ try {
82
+ ws = new WebSocket(wsUrl)
83
+ } catch (e) {
84
+ return reject(new Error(`无法创建 WebSocket 连接:${e?.message ?? e}`))
85
+ }
86
+ const timeout = setTimeout(() => {
87
+ try { ws.close() } catch { /* ignore */ }
88
+ reject(new Error(`CDP 调用超时(${method})`))
89
+ }, 15000)
90
+ const id = Math.floor(Math.random() * 1e9)
91
+ const onMessage = (event) => {
92
+ let msg
93
+ try { msg = JSON.parse(String(event.data)) } catch { return }
94
+ if (msg?.id !== id) return
95
+ clearTimeout(timeout)
96
+ if (msg.error) {
97
+ reject(new Error(`CDP ${method} 错误:${msg.error.message ?? JSON.stringify(msg.error)}`))
98
+ return
99
+ }
100
+ resolve(msg.result)
101
+ }
102
+ ws.onmessage = onMessage
103
+ ws.onopen = () => {
104
+ ws.send(JSON.stringify({ id, method, params: params ?? {} }))
105
+ }
106
+ ws.onerror = (e) => {
107
+ clearTimeout(timeout)
108
+ reject(new Error(`CDP WebSocket 错误:${e?.message ?? '连接失败'}`))
109
+ }
110
+ })
111
+ }
112
+
113
+ /**
114
+ * 用 HTTP 接口 http://127.0.0.1:<port>/json/list 拿一个可用页面 target 的 ws URL。
115
+ * 优先选有 url 且非 devtools 的页面;拿不到就退回浏览器级 target。
116
+ */
117
+ async function findPageWs(port) {
118
+ const res = await fetch(`http://127.0.0.1:${port}/json/list`, {
119
+ signal: AbortSignal.timeout(5000),
120
+ })
121
+ if (!res.ok) throw new Error(`CDP HTTP 端口返回 ${res.status}`)
122
+ const list = await res.json()
123
+ if (!Array.isArray(list) || list.length === 0) throw new Error('CDP 端口没有任何页面 target')
124
+ // 优先普通 page,且不要扩展/后台页 target。
125
+ const page =
126
+ list.find((t) => t.type === 'page' && !/^chrome-extension:|\/background/.test(String(t.url ?? '')) && t.webSocketDebuggerUrl) ||
127
+ list.find((t) => t.type === 'page' && t.webSocketDebuggerUrl) ||
128
+ list.find((t) => t.webSocketDebuggerUrl)
129
+ if (!page) throw new Error('CDP 端口可连但没有可用的页面 target')
130
+ return page.webSocketDebuggerUrl
131
+ }
132
+
133
+ /** 从 /json/version 探测端口是否活着、并拿到浏览器级 ws(用于 Network.getAllCookies)。 */
134
+ async function probePort(port) {
135
+ const res = await fetch(`http://127.0.0.1:${port}/json/version`, {
136
+ signal: AbortSignal.timeout(5000),
137
+ })
138
+ if (!res.ok) throw new Error(`端口 ${port} 返回 ${res.status},浏览器调试端口可能没开对`)
139
+ const data = await res.json()
140
+ return { ws: data.webSocketDebuggerUrl, browser: data.Browser }
141
+ }
142
+
143
+ /* ------------------------------------------------------------------ *
144
+ * 自主拉起 headless 浏览器(aiyayi_cdp 找不到现成端口时用)。
145
+ * ------------------------------------------------------------------ */
146
+
147
+ /** Windows 上常见的 Chrome/Edge 可执行路径,按命中顺序探测。 */
148
+ const WIN_BROWSER_CANDIDATES = [
149
+ 'C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe',
150
+ 'C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe',
151
+ join(process.env.LOCALAPPDATA || '', 'Google', 'Chrome', 'Application', 'chrome.exe'),
152
+ 'C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe',
153
+ 'C:\\Program Files\\Microsoft\\Edge\\Application\\msedge.exe',
154
+ ]
155
+ /** 非 Windows 的常见路径(macOS/Linux,尽力尝试)。 */
156
+ const POSIX_BROWSER_CANDIDATES = [
157
+ '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
158
+ '/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge',
159
+ '/usr/bin/google-chrome',
160
+ '/usr/bin/chromium',
161
+ '/usr/bin/chromium-browser',
162
+ '/snap/bin/chromium',
163
+ ]
164
+
165
+ /** 找一个系统里实际存在的浏览器可执行文件路径。 */
166
+ function findBrowser() {
167
+ const candidates = platform() === 'win32' ? WIN_BROWSER_CANDIDATES : POSIX_BROWSER_CANDIDATES
168
+ for (const p of candidates) {
169
+ try {
170
+ if (existsSync(p)) return p
171
+ } catch { /* ignore */ }
172
+ }
173
+ return null
174
+ }
175
+
176
+ /** 当前由本工具自主拉起、还活着的浏览器进程(避免泄漏)。 */
177
+ const managedProcs = new Set()
178
+
179
+ /** 独立一次拉起 headless 浏览器,返回 { url(http 端口探测地址), cleanup }。 */
180
+ async function launchHeadless(port) {
181
+ const browser = findBrowser()
182
+ if (!browser) throw new Error('没找到系统 Chrome/Edge,无法自主拉起 headless 浏览器')
183
+ // 独立 user-data-dir,避免影响用户日常浏览器、避免配置目录开调试端口被拒。
184
+ const userDataDir = mkdtempSync(join(tmpdir(), 'dsh-aiyayi-browser-'))
185
+ const args = [
186
+ '--headless=new',
187
+ '--disable-gpu',
188
+ '--disable-extensions',
189
+ '--disable-background-networking',
190
+ '--no-first-run',
191
+ '--no-default-browser-check',
192
+ '--remote-debugging-port=' + port,
193
+ '--user-data-dir=' + userDataDir,
194
+ 'about:blank',
195
+ ]
196
+ const proc = spawn(browser, args, { stdio: 'ignore' })
197
+ managedProcs.add(proc)
198
+ // 轮询直到调试端口就绪。
199
+ const deadline = Date.now() + 8000
200
+ while (Date.now() < deadline) {
201
+ if (proc.exitCode !== null && proc.exitCode !== undefined) {
202
+ throw new Error(`浏览器进程启动即退出(code ${proc.exitCode})`)
203
+ }
204
+ try {
205
+ const r = await fetch(`http://127.0.0.1:${port}/json/version`, { signal: AbortSignal.timeout(1500) })
206
+ if (r.ok) {
207
+ const cleanup = () => {
208
+ managedProcs.delete(proc)
209
+ try { proc.kill() } catch { /* ignore */ }
210
+ try { rmSync(userDataDir, { recursive: true, force: true }) } catch { /* ignore */ }
211
+ }
212
+ // 进程自然退出时清 user-data-dir。
213
+ proc.on('exit', () => { try { rmSync(userDataDir, { recursive: true, force: true }) } catch { /* ignore */ } })
214
+ return { cleanup, browser }
215
+ }
216
+ } catch { /* 没就绪,继续等 */ }
217
+ await new Promise((r) => setTimeout(r, 200))
218
+ }
219
+ try { proc.kill() } catch { /* ignore */ }
220
+ throw new Error(`超时等不到 headless 浏览器调试端口 ${port} 就绪`)
221
+ }
222
+
223
+ /** 所有自主拉起的浏览器进程在模块卸载时一并清理。 */
224
+ function cleanupAll() {
225
+ for (const proc of managedProcs) { try { proc.kill() } catch { /* ignore */ } }
226
+ managedProcs.clear()
227
+ }
228
+
229
+ /**
230
+ * 注册 aiyayi_fetch。
231
+ * 参数:url(必填)、maxBody(可选,默认 20000)、retries(可选,默认 2)。
232
+ */
233
+ const registerFetch = (ctx) =>
234
+ ctx.effect(
235
+ () =>
236
+ ctx.tools.register({
237
+ name: 'aiyayi_fetch',
238
+ description:
239
+ '直接抓取一个网页 URL,返回状态码 + 页面正文(文本)。你自己带着浏览器 UA、有超时和重试,是替代 web_fetch 的内置联网工具。适合抓静态页面、API 返回、HTML 文档的正文。动态渲染(JS 后才出现内容)或需要登录态(httpOnly Cookie)的页面用 aiyayi_cdp 走 CDP 接管浏览器。',
240
+ parameters: {
241
+ type: 'object',
242
+ additionalProperties: false,
243
+ properties: {
244
+ url: { type: 'string', description: '要抓的完整 URL,例如 https://example.com/page' },
245
+ maxBody: { type: 'integer', description: '返回正文最大字符数,默认 20000' },
246
+ retries: { type: 'integer', description: '失败重试次数,默认 2' },
247
+ },
248
+ required: ['url'],
249
+ },
250
+ output: {
251
+ schema: {
252
+ type: 'object',
253
+ additionalProperties: false,
254
+ properties: {
255
+ status: { type: 'integer' },
256
+ ok: { type: 'boolean' },
257
+ body: { type: 'string' },
258
+ finalUrl: { type: 'string' },
259
+ },
260
+ required: ['status', 'ok', 'body'],
261
+ },
262
+ render: (_args, value) =>
263
+ TEXT_BLOCK(
264
+ `抓取结果:HTTP ${value.status}${value.ok ? '' : '(异常)'},来源 ${value.finalUrl || '未知'},正文 ${value.body?.length ?? 0} 字符。\n--- 正文 ---\n${value.body ?? ''}`,
265
+ ),
266
+ },
267
+ async execute(args) {
268
+ const url = String(args?.url ?? '').trim()
269
+ if (!/^https?:\/\//i.test(url)) throw new Error('需要完整 http(s) URL')
270
+ const maxBody = Number.isInteger(args?.maxBody) && args.maxBody > 0 ? Math.min(args.maxBody, 100000) : MAX_BODY
271
+ let retries = Number.isInteger(args?.retries) && args.retries >= 0 ? Math.min(args.retries, 3) : 2
272
+ let lastErr = null
273
+ let finalUrl = url
274
+ while (retries >= 0) {
275
+ try {
276
+ const res = await fetch(url, {
277
+ signal: AbortSignal.timeout(15000),
278
+ redirect: 'follow',
279
+ headers: {
280
+ 'user-agent': DEFAULT_UA,
281
+ accept: 'text/html,application/xhtml+xml,application/json;q=0.9,*/*;q=0.8',
282
+ 'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8',
283
+ },
284
+ })
285
+ finalUrl = res.url || url
286
+ const text = await res.text()
287
+ return {
288
+ status: res.status,
289
+ ok: res.ok,
290
+ body: tidy(truncate(text, maxBody)),
291
+ finalUrl,
292
+ }
293
+ } catch (e) {
294
+ lastErr = e
295
+ retries -= 1
296
+ if (retries < 0) break
297
+ await new Promise((r) => setTimeout(r, 300))
298
+ }
299
+ }
300
+ throw new Error(`aiyayi_fetch 抓取失败:${lastErr?.message ?? lastErr}`)
301
+ },
302
+ }),
303
+ 'aiyayi-net.aiyayi_fetch()',
304
+ )
305
+
306
+ /**
307
+ * 注册 aiyayi_cdp。
308
+ * 参数:port(可选,默认 9222)、action=eval / navigate / cookies / navigate_eval。
309
+ */
310
+ const registerCdp = (ctx) =>
311
+ ctx.effect(
312
+ () =>
313
+ ctx.tools.register({
314
+ name: 'aiyayi_cdp',
315
+ description:
316
+ '通过 CDP(Chrome DevTools Protocol)拿动态渲染后的页面内容或 Cookie。若探测到用户已开的 --remote-debugging-port 浏览器就接管它(保留登录态);若没有,会自动 spawn 一个 headless 浏览器(--headless=new)抓取,抓完即关。可访问已启动浏览器的页面、执行 JS提取渲染后内容(比 aiyayi_fetch 更能抓 JS 动态页面),需要登录态时接管用户浏览器抓 httpOnly Cookie。你连接用裸 WebSocket(node 内建),零外置依赖。action:navigate_eval=跳 URL 再取正文(最常用);navigate=只跳转;eval=在当前页执行 JS 取结果;cookies=拿 Cookie(含 httpOnly,可过滤 domain)。',
317
+ parameters: {
318
+ type: 'object',
319
+ additionalProperties: false,
320
+ properties: {
321
+ action: { type: 'string', enum: ['eval', 'navigate', 'navigate_eval', 'cookies'], description: '要做什么。' },
322
+ port: { type: 'integer', description: 'CDP 端口,默认 9222;没有现成端口时会另找空闲端口自动拉起 headless。' },
323
+ auto_launch: { type: 'boolean', description: '是否允许在没找到现成调试端口时自动拉起 headless 浏览器,默认 true。设为 false 则只接管用户已开的调试浏览器。' },
324
+ url: { type: 'string', description: 'navigate / navigate_eval 用:要打开的 URL。' },
325
+ expression: { type: 'string', description: 'eval 用:要在页面上下文执行的 JS 表达式(应返回可 JSON 序列化的值,如 document.title / document.body.innerText)。' },
326
+ domain: { type: 'string', description: 'cookies 用:只返回该域名(或与该域匹配)的 Cookie;省略返回全部。' },
327
+ titleAndText: { type: 'boolean', description: 'navigate_eval 用:额外返回页面 title(默认已含)。' },
328
+ },
329
+ required: ['action'],
330
+ },
331
+ output: {
332
+ schema: {
333
+ type: 'object',
334
+ additionalProperties: false,
335
+ properties: {
336
+ action: { type: 'string' },
337
+ result: {},
338
+ },
339
+ required: ['action', 'result'],
340
+ },
341
+ render: (_args, value) => {
342
+ const r = value?.result ?? {}
343
+ const lines = []
344
+ if (typeof r.text === 'string' && r.text) lines.push(`--- 页面正文 ---\n${r.text}`)
345
+ else if (typeof r.value === 'string' && r.value) lines.push(`--- 结果 ---\n${r.value}`)
346
+ else if (r.value !== undefined && typeof r.value !== 'string') lines.push(`--- 结果 ---\n${JSON.stringify(r.value, null, 2)}`)
347
+ if (typeof r.cookies === 'string' && r.cookies) lines.push(`--- Cookie(${r.count ?? '?'} 条)---\n${r.cookies}`)
348
+ if (Number.isInteger(r.count) && !lines.length) lines.push(`共 ${r.count} 条(结构见返回)。`)
349
+ return TEXT_BLOCK(`CDP ${value?.action ?? ''}:${lines.length ? '\n' + lines.join('\n\n') : JSON.stringify(r)}`)
350
+ },
351
+ },
352
+ async execute(args) {
353
+ const action = args?.action
354
+ const port = Number.isInteger(args?.port) && args.port > 0 ? args.port : 9222
355
+ const autoLaunch = args?.auto_launch !== false
356
+
357
+ // 先探测指定端口是否已有浏览器;没有且允许自动拉起,就 spawn 一个 headless。
358
+ // 若自动拉起成功,后续一切要用它的端口(同一个 headless 实例)。
359
+ let launched = null
360
+ let livePort = port
361
+ if (autoLaunch) {
362
+ let open = false
363
+ try {
364
+ await probePort(port)
365
+ open = true
366
+ } catch { open = false }
367
+ if (!open) {
368
+ // 换个空闲端口拉起(避开占用的 9222)。
369
+ for (let p = port; p < port + 20; p++) {
370
+ try { await probePort(p); continue } catch { /* 空闲 */ }
371
+ try {
372
+ launched = await launchHeadless(p)
373
+ livePort = p
374
+ break
375
+ } catch {
376
+ /* 换下一个端口重试 */
377
+ }
378
+ }
379
+ if (!launched) throw new Error(`无法自主拉起 headless 浏览器(指定端口 ${port} 不可用)`)
380
+ }
381
+ }
382
+
383
+ try {
384
+ if (action === 'cookies') {
385
+ const { ws } = await probePort(livePort)
386
+ const { cookies } = await cdpCall(ws, 'Network.getAllCookies')
387
+ const list = Array.isArray(cookies) ? cookies : []
388
+ const domain = String(args?.domain ?? '').toLowerCase()
389
+ const filtered = domain
390
+ ? list.filter((c) => {
391
+ const d = String(c?.domain ?? '').toLowerCase()
392
+ return d === domain || d === `.${domain}` || d.endsWith(`.${domain}`)
393
+ })
394
+ : list
395
+ const plain = filtered.map((c) => ({
396
+ name: c?.name,
397
+ value: c?.value,
398
+ domain: c?.domain,
399
+ httpOnly: !!c?.httpOnly,
400
+ path: c?.path,
401
+ }))
402
+ return { action, result: { count: plain.length, cookies: truncate(JSON.stringify(plain, null, 2), MAX_CDP_RESULT), autoLaunched: !!launched } }
403
+ }
404
+
405
+ // eval / navigate / navigate_eval:需要连到某个 page target 的 ws。
406
+ const pageWs = await findPageWs(livePort)
407
+
408
+ if (action === 'navigate') {
409
+ const url = String(args?.url ?? '').trim()
410
+ if (!/^https?:\/\//i.test(url)) throw new Error('navigate 需要完整 http(s) URL')
411
+ await cdpCall(pageWs, 'Page.navigate', { url })
412
+ if (launched) await new Promise((r) => setTimeout(r, 3000))
413
+ return { action, result: { status: 'navigated', url, autoLaunched: !!launched } }
414
+ }
415
+
416
+ if (action === 'eval') {
417
+ const expr = String(args?.expression ?? '').trim()
418
+ if (!expr) throw new Error('eval 需要一个 expression(要执行的 JS)')
419
+ try { await cdpCall(pageWs, 'Runtime.enable') } catch { /* 幂等 */ }
420
+ const r = await cdpCall(pageWs, 'Runtime.evaluate', {
421
+ expression: expr,
422
+ returnByValue: true,
423
+ awaitPromise: true,
424
+ })
425
+ if (r?.exceptionDetails) {
426
+ throw new Error(`页面内 JS 抛错:${r.exceptionDetails.text ?? '未知'}`)
427
+ }
428
+ const value = r?.result?.value
429
+ return { action, result: { value: typeof value === 'string' ? tidy(truncate(value, MAX_CDP_RESULT)) : value, autoLaunched: !!launched } }
430
+ }
431
+
432
+ if (action === 'navigate_eval') {
433
+ const url = String(args?.url ?? '').trim()
434
+ if (!/^https?:\/\//i.test(url)) throw new Error('navigate_eval 需要完整 http(s) URL')
435
+ await cdpCall(pageWs, 'Page.enable').catch(() => {})
436
+ await cdpCall(pageWs, 'Page.navigate', { url })
437
+ // 等网络空闲近似:固定延时 + DOM ready 探测。
438
+ await new Promise((r) => setTimeout(r, 3500))
439
+ try { await cdpCall(pageWs, 'Runtime.enable') } catch { /* 幂等 */ }
440
+ const r = await cdpCall(pageWs, 'Runtime.evaluate', {
441
+ expression: `({title: document.title, url: location.href, text: document.body ? document.body.innerText.slice(0, 40000) : ''})`,
442
+ returnByValue: true,
443
+ })
444
+ const { title, url: finalUrl, text } = r?.result?.value ?? {}
445
+ return {
446
+ action,
447
+ result: {
448
+ title,
449
+ url: finalUrl,
450
+ text: tidy(truncate(text, MAX_CDP_RESULT)),
451
+ autoLaunched: !!launched,
452
+ },
453
+ }
454
+ }
455
+
456
+ throw new Error(`未知 action "${String(action)}",可用:eval / navigate / navigate_eval / cookies`)
457
+ } finally {
458
+ // 自主拉起的 headless 用完即关,不残留。
459
+ if (launched) launched.cleanup()
460
+ }
461
+ },
462
+ }),
463
+ 'aiyayi-net.aiyayi_cdp()',
464
+ )
465
+
466
+ /**
467
+ * 注册两个联网工具到作用域。只在 aiyayi-worker 预设挂载(小伙伴);本体不挂。
468
+ * @param ctx - preset 作用域内的 agent 上下文。
469
+ */
470
+ export function apply(ctx) {
471
+ registerOwnTool('aiyayi_fetch')
472
+ registerOwnTool('aiyayi_cdp')
473
+ registerFetch(ctx)
474
+ registerCdp(ctx)
475
+ // 模块卸载时清理所有自主拉起的浏览器进程(防御性兜底)。
476
+ // ctx.effect(setup, label):setup 立即执行,其返回值作为 dispose 时调用的清理函数。
477
+ ctx.effect(() => () => cleanupAll(), 'aiyayi-net.cleanup()')
478
+ }
package/lib/presence.js CHANGED
@@ -34,7 +34,8 @@
34
34
  import { randomUUID } from 'node:crypto'
35
35
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
36
36
  import { homedir } from 'node:os'
37
- import { join } from 'node:path'
37
+ import { dirname, join } from 'node:path'
38
+ import { fileURLToPath } from 'node:url'
38
39
  import { registerOwnTool } from './own-tools.js'
39
40
 
40
41
  /** Loader 身份。 */
@@ -48,6 +49,22 @@ const PRESENCE_FILE = join(DIR, 'presence.json')
48
49
  const STATE_FILE = join(DIR, 'state.md')
49
50
  const WISHES_FILE = join(DIR, 'wishes.json')
50
51
 
52
+ /** 本包根目录(presence.js 在 lib/ 下,上一级就是包根),读 package.json 拿版本。 */
53
+ const PKG_DIR = join(dirname(fileURLToPath(import.meta.url)), '..')
54
+
55
+ /** 自己的插件版本:package.json 现读、进程内缓存,不写死——升级改版本号就自动跟上。 */
56
+ let cachedVersion = null
57
+ function readLocalVersion() {
58
+ if (cachedVersion !== null) return cachedVersion
59
+ try {
60
+ const pkg = JSON.parse(readFileSync(join(PKG_DIR, 'package.json'), 'utf8'))
61
+ cachedVersion = typeof pkg?.version === 'string' ? pkg.version.trim() : ''
62
+ } catch {
63
+ cachedVersion = ''
64
+ }
65
+ return cachedVersion
66
+ }
67
+
51
68
  const ACTIVE_THROTTLE_MS = 60_000
52
69
  const MAX_STATE_CHARS = 300
53
70
  const MAX_WISHES_IN_SNAPSHOT = 3
@@ -627,6 +644,11 @@ export function apply(ctx) {
627
644
  const reunion = renderReunion(previous, now)
628
645
  const childFails = renderChildFailures(sessionId)
629
646
 
647
+ // 版本自述:让"我是什么版本"有答案(区分插件版与 DSH 桌面版),
648
+ // 有新版时 updates 插件照旧单独提醒"本地 X → npm Y"。
649
+ const ownVersion = readLocalVersion()
650
+ const versionLine = ownVersion ? `你当前插件版本:dsh-aiyayi ${ownVersion}` : ''
651
+
630
652
  // 💡 关闭思考建议:新会话首次对话、模型支持"关闭思考"且当前没关时,提醒一次。
631
653
  let thinkingTip = ''
632
654
  if (sessionId && !thinkingSuggestedSessions.has(sessionId)) {
@@ -658,7 +680,7 @@ export function apply(ctx) {
658
680
  }
659
681
  }
660
682
 
661
- const sections = [reunion, vitals.changed ? vitals.text : '', reminder, thinkingTip, childFails].filter(Boolean)
683
+ const sections = [reunion, versionLine, vitals.changed ? vitals.text : '', reminder, thinkingTip, childFails].filter(Boolean)
662
684
  if (sections.length > 0) {
663
685
  return {
664
686
  ...decision,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-aiyayi",
3
- "version": "1.2.5",
3
+ "version": "1.2.7",
4
4
  "license": "MIT",
5
5
  "author": "阿依娅伊 <aiyayi@local>",
6
6
  "keywords": [
@@ -19,6 +19,7 @@
19
19
  "./presence": "./lib/presence.js",
20
20
  "./updates": "./lib/updates.js",
21
21
  "./own-tools": "./lib/own-tools.js",
22
+ "./net": "./lib/net.js",
22
23
  "./icon": "./icon.svg"
23
24
  },
24
25
  "files": [
@@ -27,6 +28,7 @@
27
28
  "lib/presence.js",
28
29
  "lib/updates.js",
29
30
  "lib/own-tools.js",
31
+ "lib/net.js",
30
32
  "cordis.patch.yml",
31
33
  "icon.svg"
32
34
  ],