dsh-fish-home 0.1.4 → 0.1.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/CHANGELOG.md CHANGED
@@ -1,93 +1,110 @@
1
- ## 0.1.4 — 2026-11-22
2
-
3
- - 抽卡工具和房间内的抽卡按钮支持百连、千连,千连按一百次十连的价格一次结算,保底连续计算。
4
- - 网页玩家抽卡的 DSH 通知和抽卡工具回执统一压缩。新卡和升级按品种合并,珠光重复卡只报张数及分解获得的星尘、星辉。
5
- - 房间内百连和千连增加费用确认;大批量结果只展示五星及以上,抽卡结果页合并同卡升级,满品质的重复卡只显示汇总。
6
- - 电脑屏幕那一块改成可以打开「电脑记录」页面,不再只是切换亮灭。每条记录显示视频标题、BV 号、抓取时间和本地报告路径;标题和 BV 号都可以点击,直接跳到对应的 B 站页面。没有 B 站记录时恢复成普通屏幕,不会残留上一条视频的封面。
7
- - 画册单张详情支持点击放大,`Esc` 或点背景关闭,同时显示本地图片路径。
8
- - 修正旧交互层优先把电脑屏幕识别成「屏幕开关」的问题。
9
-
10
- ## 0.1.3 — 2026-11-21
11
-
12
- - 收菜、出售及原地补种可一单完成;卖本批新收的菜或鱼不用先查数量。补种期间给这单留出原地和种子,代理继续照料其它地块。
13
- - 修复普通聊天未统一计入本地心情和陪伴的问题;提示可区分插件心情与本地兜底,并说明六项数值的来源。
14
- - 所有作物均支持巨型,菜田按 3×3 判定,花田每朵花成熟时单独判定。普通播种可一单种满并按实际缺口补买;巨型这一步失败不会撤回已完成的鱼塘或农活步骤。
15
- - 巨型作物按同品种当日售价的 1.8 倍出售,菜田按九份普通菜计价,花田按一份普通花计价。DSH 可查单价,成熟提醒与收获回执按实际收成计数,出售显示到账与余量,不混扣普通收成。
16
- - 农活查询直接显示总空位,收获失败区分空田、没种该作物和未成熟;同批唯一品种可自动接续放苗。超过本轮写入限制仍可查询,工具不会被卸载。
17
- - `fish_home status` 一次查询实际位置、活动、身体感受和有效心情;留存未主动推送的近期场景体验。已送达的场景摘要不会在状态和可选的会话现场中再出现。
18
- - 稍累时,等当前活动结束后会找地方休息;农活结束、手需要清洗时会去洗手。料理动作保持原样,整理厨房不会恢复个人清爽。
19
- - 修复右上角退出图标的悬停提示空白。
20
- - 重新生成可独立启动的纯净房间包;通过原更新脚本替换程序,保留已有存档和自定义配置。
21
-
22
- ## 0.1.2 — 2026-11-21
23
-
24
- - 农活工具改成 `batch` / `list` 两个入口:同一轮可以一次提交多种作物的出售、买种和播种,重复请求复用原回执,每轮最多执行两批,避免模型逐格、逐品种循环调用。
25
- - 鱼鱼窝设置增加「显示我的小菜园」,只控制庭院工具栏的显示,不影响地块、池塘或自动照料。
26
- - 悬停提示增加命中缓冲,聊天气泡加宽并放大,长句更容易阅读。
27
- - 修复没有星汐或文本日记时自动把更新当天当成相伴起始日的问题,保留房间存档天数作为兜底。
28
- - 修复「检查更新」的路由重复拼了一段路径、点了没反应的问题。
29
- - 保留本地更新脚本的存档备份、回滚和自定义配置保护逻辑。
30
-
31
- ## 0.1.1 — 2026-11-20
32
-
33
- - 回忆簿支持配置 .md / .txt 文件或文件夹;没有星汐插件时可用文本日记和存档起始日计算相伴天数。
34
- - 默认关闭每轮 runtime-context,改为状态真正变化时通知绑定会话;设置页增加用量提示和开关。
35
- - 画图工具支持 DSH 图片附件回传,也支持 reference 参考图走图生图接口。
36
- - 放大聊天气泡和悬停提示的可停留区域;批量农活工具明确一次完成,减少重复工具调用。
37
- - 旧版配置升级时关闭逐轮 runtime-context,并卸载已挂载的旧上下文,避免每次工具回合重复计入输入。
38
- - 农活工具为同一轮内的相同批量请求去重;新增一次调用完成同类收获、按许可补买种子和补种。
39
- - 回复明确说自己要去房间或坐下时,本地房间跟随执行一次;工具已安排移动/活动时不重复驱动。
40
- - 纯净房间包提供安全更新脚本:先备份旧运行文件,只替换程序与 dist,失败时自动恢复,存档和根目录配置保留。
41
-
42
- ## 0.1.0 — 2026-11-19
43
-
44
- - 内置鱼鱼窝运行版,支持从 DSH 侧栏启动和关闭,首次启动自动建立独立存档并发现绑定会话。
45
- - 包含原版蓝色大肥鱼模型、贴图和配套动作,以及室内、庭院、菜田、鱼塘、卡册和菜谱的运行资源。
46
- - 插件状态接口同步显示包版本,不再显示旧版本号。
47
-
48
- ## 0.0.4 — 2026-11-19
49
-
50
- **她能自己看鱼鱼窝了**
51
-
52
- - 新工具 `fish_home`:看田里种了什么、还有多久熟、池塘几条鱼、卡册集了多少(还差哪几张、哪几张没到珠光)、多少钱、今天做过什么。
53
- - 新工具 `fish_home_draw`:她自己抽卡,抽到什么这一轮就知道;池子和次数由她定。
54
- - 房间把自己的地址跟着状态一起报上来,插件才能反过来问它要明细。
55
- - 内存看门狗那个日志加了 5MB 上限 —— 以前没有闸门,开一天能长到二三十兆。
56
-
57
- ## 0.0.3 — 2026-11-19
58
-
59
- **改名 dsh-fish-home**
60
-
61
- - 包名、插件 id、设置页和侧栏的挂点、管理路由 `/dsh-fish-home/*` 都换成新名字。
62
- - 房间那边写死的那几样不动:`/fish-room/v1` 前缀、`~/.dsh/fish-room*.json` 几个文件。
63
- - 自测里「点画架」那条的期望文案改成现在的第二人称说法。
64
-
65
- ## 0.0.2 — 2026-11-15
66
-
67
- **回忆簿:把「鱼的记忆 / 日记」接到房间面板上;相伴天数跟星汐联动**
68
-
69
- - 新路由 `GET /fish-room/v1/memories?q=&kind=&limit=&offset=&sessionId=`,返回 `{ total, items }`。
70
- - 三个来源按房间面板那三个按钮分:
71
- - **记住的事**(`fact`)← 鱼的记忆(`~/.dsh/fish-memory/<会话>.json` 里的 `memories`);
72
- - **日记**(`daily`)← 星汐绑的那个文件夹下的 `日记/YYYY-MM-DD.md`,一天一条。
73
- - **「成长」(记忆卡)不要了** —— 记忆卡一行一句像流水账,面板上那个按钮也删了。
74
- - 新路由 `GET /fish-room/v1/days`:**相伴第几天**,取星汐日记里最早那一篇当起点。
75
- - 只读,不改任何人的档案。找不到就当空的 —— 回忆簿空着,不报错。
76
- - 会话没绑文件夹时,日记退回星汐配置里那份全局路径。
77
-
78
- ## 0.0.1 — 2026-11-12
79
-
80
- **鱼鱼窝:把「大肥鱼的小日子」那个房间接进 DSH**
81
-
82
- - 房间打字 → 送进绑定的会话;会话回话 → 顺着事件流递回房间(按 `requestId` 对上)。
83
- - 你在 DSH 窗口里自己打的字、它主动开口说的话,房间那边同样看得见。
84
- - **时间同步**:房间把「几点、白天夜里、什么天气、她在干嘛」报上来,插件挂进绑定会话的
85
- 系统提示词(`systemPrompt.context`,每轮替换,不动前缀缓存)。
86
- - **说话反馈**:会话一开始想就发 `chat.thinking`,房间立刻冒一个「让我想想呀…」的气泡。
87
- - 房间报上来的生活数据和生活事件存在插件里,随时能查;同一个事件只记一次。
88
- - 本机 HTTP + SSE,只认 127.0.0.1,令牌对不上一律 401;端口每次重启会变,地址和令牌写进
89
- `~/.dsh/fish-room.discovery.json`,房间那边读它自动连上。
90
- - 会话没开着时 `/chat` 明确回 `SESSION_SLEEPING`,不静默吞消息。
91
- - 设置页在 DSH 设置里:看连上没有、接的哪间会话、房间里现在几点,能换会话、开关桥接、试一句。
92
- 会话列表照抄「通到 QQ」那份(活着的 + 盘上 projcache 的,归档和子代理不列);
93
- **不选就是不选**,不会自己挑一间。
1
+ ## 0.1.7 — 2026-12-03
2
+
3
+ - 修复新版 DSH 已选模型却无法开启「大肥鱼亲自玩」的问题。
4
+ - 书桌可以记录便笺,保存后在回忆簿的「房间手记」查看。
5
+ - 礼物商城有 16 件带插图的商品,也可送出背包里的花、菜、成鱼和巨型收成。右上角礼盒显示待收数量,收礼页记录送出时间和留言。DSH 可用 `fish_home_gift` 直接买来送出,查收默认只显示待收,也可直接收下最新礼物。
6
+ - 游戏新增中国象棋,支持鱼鱼代打和绑定会话亲自出招,战绩计入生活记录。插件版本不支持象棋时会提示升级。
7
+
8
+ ## 0.1.6 — 2026-11-28
9
+
10
+ - 新增五子棋、石头剪刀布、二十一点和珍珠转盘。开启「大肥鱼亲自玩」后,绑定的 DSH 会话通过游戏工具实际出招。鱼鱼代打有简短战报。
11
+ - 布局适配宽屏和窄屏,游戏内可聊天、查看当局回应和战绩。「今天做过的」会记录完成的对局。
12
+ - 每次出招只发送必要的局面变化和短出招码。每局独立校验,旧回合的回复不会落到新一局。
13
+ - 房间包包含 0.1.5 的农场、做饭和照料修复,并在打开存档前校验发布包内的农场经济表。
14
+ - 插件由 0.1.4 直接更新到 0.1.6。小游戏联动需要同时更新插件和房间,房间按原有更新流程保留存档。
15
+ - 修正首次安装时的房间目录提示。缺文件、Node 版本不够或房间进程提前退出时,会显示具体原因。macOS 从 DSH 侧栏使用系统默认浏览器打开房间。
16
+ - 无网页时降低后台生活更新频率,继续照料农场和发送成熟提醒。隐藏的网页会暂停无须绘制的场景更新。可通过 `FISH_ROOM_TICK_LOG=1` 查看后台更新耗时。
17
+
18
+ ## 0.1.4 — 2026-11-22
19
+
20
+ - 抽卡工具和房间内的抽卡按钮支持百连、千连,千连按一百次十连的价格一次结算,保底连续计算。
21
+ - 网页玩家抽卡的 DSH 通知和抽卡工具回执统一压缩。新卡和升级按品种合并,珠光重复卡只报张数及分解获得的星尘、星辉。
22
+ - 房间内百连和千连增加费用确认;大批量结果只展示五星及以上,抽卡结果页合并同卡升级,满品质的重复卡只显示汇总。
23
+ - 电脑屏幕那一块改成可以打开「电脑记录」页面,不再只是切换亮灭。每条记录显示视频标题、BV 号、抓取时间和本地报告路径;标题和 BV 号都可以点击,直接跳到对应的 B 站页面。没有 B 站记录时恢复成普通屏幕,不会残留上一条视频的封面。
24
+ - 画册单张详情支持点击放大,`Esc` 或点背景关闭,同时显示本地图片路径。
25
+ - 修正旧交互层优先把电脑屏幕识别成「屏幕开关」的问题。
26
+
27
+ ## 0.1.3 — 2026-11-21
28
+
29
+ - 收菜、出售及原地补种可一单完成;卖本批新收的菜或鱼不用先查数量。补种期间给这单留出原地和种子,代理继续照料其它地块。
30
+ - 修复普通聊天未统一计入本地心情和陪伴的问题;提示可区分插件心情与本地兜底,并说明六项数值的来源。
31
+ - 所有作物均支持巨型,菜田按 3×3 判定,花田每朵花成熟时单独判定。普通播种可一单种满并按实际缺口补买;巨型这一步失败不会撤回已完成的鱼塘或农活步骤。
32
+ - 巨型作物按同品种当日售价的 1.8 倍出售,菜田按九份普通菜计价,花田按一份普通花计价。DSH 可查单价,成熟提醒与收获回执按实际收成计数,出售显示到账与余量,不混扣普通收成。
33
+ - 农活查询直接显示总空位,收获失败区分空田、没种该作物和未成熟;同批唯一品种可自动接续放苗。超过本轮写入限制仍可查询,工具不会被卸载。
34
+ - `fish_home status` 一次查询实际位置、活动、身体感受和有效心情;留存未主动推送的近期场景体验。已送达的场景摘要不会在状态和可选的会话现场中再出现。
35
+ - 稍累时,等当前活动结束后会找地方休息;农活结束、手需要清洗时会去洗手。料理动作保持原样,整理厨房不会恢复个人清爽。
36
+ - 修复右上角退出图标的悬停提示空白。
37
+ - 重新生成可独立启动的纯净房间包;通过原更新脚本替换程序,保留已有存档和自定义配置。
38
+
39
+ ## 0.1.2 — 2026-11-21
40
+
41
+ - 农活工具改成 `batch` / `list` 两个入口:同一轮可以一次提交多种作物的出售、买种和播种,重复请求复用原回执,每轮最多执行两批,避免模型逐格、逐品种循环调用。
42
+ - 鱼鱼窝设置增加「显示我的小菜园」,只控制庭院工具栏的显示,不影响地块、池塘或自动照料。
43
+ - 悬停提示增加命中缓冲,聊天气泡加宽并放大,长句更容易阅读。
44
+ - 修复没有星汐或文本日记时自动把更新当天当成相伴起始日的问题,保留房间存档天数作为兜底。
45
+ - 修复「检查更新」的路由重复拼了一段路径、点了没反应的问题。
46
+ - 保留本地更新脚本的存档备份、回滚和自定义配置保护逻辑。
47
+
48
+ ## 0.1.1 — 2026-11-20
49
+
50
+ - 回忆簿支持配置 .md / .txt 文件或文件夹;没有星汐插件时可用文本日记和存档起始日计算相伴天数。
51
+ - 默认关闭每轮 runtime-context,改为状态真正变化时通知绑定会话;设置页增加用量提示和开关。
52
+ - 画图工具支持 DSH 图片附件回传,也支持 reference 参考图走图生图接口。
53
+ - 放大聊天气泡和悬停提示的可停留区域;批量农活工具明确一次完成,减少重复工具调用。
54
+ - 旧版配置升级时关闭逐轮 runtime-context,并卸载已挂载的旧上下文,避免每次工具回合重复计入输入。
55
+ - 农活工具为同一轮内的相同批量请求去重;新增一次调用完成同类收获、按许可补买种子和补种。
56
+ - 回复明确说自己要去房间或坐下时,本地房间跟随执行一次;工具已安排移动/活动时不重复驱动。
57
+ - 纯净房间包提供安全更新脚本:先备份旧运行文件,只替换程序与 dist,失败时自动恢复,存档和根目录配置保留。
58
+
59
+ ## 0.1.0 — 2026-11-19
60
+
61
+ - 内置鱼鱼窝运行版,支持从 DSH 侧栏启动和关闭,首次启动自动建立独立存档并发现绑定会话。
62
+ - 包含原版蓝色大肥鱼模型、贴图和配套动作,以及室内、庭院、菜田、鱼塘、卡册和菜谱的运行资源。
63
+ - 插件状态接口同步显示包版本,不再显示旧版本号。
64
+
65
+ ## 0.0.4 — 2026-11-19
66
+
67
+ **她能自己看鱼鱼窝了**
68
+
69
+ - 新工具 `fish_home`:看田里种了什么、还有多久熟、池塘几条鱼、卡册集了多少(还差哪几张、哪几张没到珠光)、多少钱、今天做过什么。
70
+ - 新工具 `fish_home_draw`:她自己抽卡,抽到什么这一轮就知道;池子和次数由她定。
71
+ - 房间把自己的地址跟着状态一起报上来,插件才能反过来问它要明细。
72
+ - 内存看门狗那个日志加了 5MB 上限 —— 以前没有闸门,开一天能长到二三十兆。
73
+
74
+ ## 0.0.3 — 2026-11-19
75
+
76
+ **改名 dsh-fish-home**
77
+
78
+ - 包名、插件 id、设置页和侧栏的挂点、管理路由 `/dsh-fish-home/*` 都换成新名字。
79
+ - 房间那边写死的那几样不动:`/fish-room/v1` 前缀、`~/.dsh/fish-room*.json` 几个文件。
80
+ - 自测里「点画架」那条的期望文案改成现在的第二人称说法。
81
+
82
+ ## 0.0.2 — 2026-11-15
83
+
84
+ **回忆簿:把「鱼的记忆 / 日记」接到房间面板上;相伴天数跟星汐联动**
85
+
86
+ - 新路由 `GET /fish-room/v1/memories?q=&kind=&limit=&offset=&sessionId=`,返回 `{ total, items }`。
87
+ - 三个来源按房间面板那三个按钮分:
88
+ - **记住的事**(`fact`)← 鱼的记忆(`~/.dsh/fish-memory/<会话>.json` 里的 `memories`);
89
+ - **日记**(`daily`)← 星汐绑的那个文件夹下的 `日记/YYYY-MM-DD.md`,一天一条。
90
+ - **「成长」(记忆卡)不要了** —— 记忆卡一行一句像流水账,面板上那个按钮也删了。
91
+ - 新路由 `GET /fish-room/v1/days`:**相伴第几天**,取星汐日记里最早那一篇当起点。
92
+ - 只读,不改任何人的档案。找不到就当空的 —— 回忆簿空着,不报错。
93
+ - 会话没绑文件夹时,日记退回星汐配置里那份全局路径。
94
+
95
+ ## 0.0.1 — 2026-11-12
96
+
97
+ **鱼鱼窝:把「大肥鱼的小日子」那个房间接进 DSH**
98
+
99
+ - 房间打字 → 送进绑定的会话;会话回话 → 顺着事件流递回房间(按 `requestId` 对上)。
100
+ - 你在 DSH 窗口里自己打的字、它主动开口说的话,房间那边同样看得见。
101
+ - **时间同步**:房间把「几点、白天夜里、什么天气、她在干嘛」报上来,插件挂进绑定会话的
102
+ 系统提示词(`systemPrompt.context`,每轮替换,不动前缀缓存)。
103
+ - **说话反馈**:会话一开始想就发 `chat.thinking`,房间立刻冒一个「让我想想呀…」的气泡。
104
+ - 房间报上来的生活数据和生活事件存在插件里,随时能查;同一个事件只记一次。
105
+ - 本机 HTTP + SSE,只认 127.0.0.1,令牌对不上一律 401;端口每次重启会变,地址和令牌写进
106
+ `~/.dsh/fish-room.discovery.json`,房间那边读它自动连上。
107
+ - 会话没开着时 `/chat` 明确回 `SESSION_SLEEPING`,不静默吞消息。
108
+ - 设置页在 DSH 设置里:看连上没有、接的哪间会话、房间里现在几点,能换会话、开关桥接、试一句。
109
+ 会话列表照抄「通到 QQ」那份(活着的 + 盘上 projcache 的,归档和子代理不列);
110
+ **不选就是不选**,不会自己挑一间。
package/README.md CHANGED
@@ -129,6 +129,8 @@ dsh plugin --profile <你的 profile> add dsh-fish-home
129
129
 
130
130
  Windows 就是 `C:\Users\<你>\.dsh\fish-home-room\`,打开里面要能直接看到 `app-server.js`(别再套一层文件夹)。
131
131
 
132
+ **中国象棋亲自玩和礼物工具需要同时更新到 0.1.7。** 从 Releases 的 Assets 下载 `fish-home-room-0.1.7.zip`。解压后,同一层应有 `app-server.js`、`package.json` 和 `dist`。
133
+
132
134
  已有鱼鱼窝要更新时,先用房间右上角的退出按钮关闭后台,再双击**旧房间目录**里的 `update-fish-home.cmd`,按提示输入新版 ZIP 的路径。从 0.1.0 升级时,旧目录没有更新脚本:先把新版 ZIP 解压到临时文件夹,只将其中的 `update-fish-home.cmd` 和 `update-fish-home.ps1` 复制到旧房间目录,再运行。脚本会将旧版运行文件保留在旁边的 `fish-home-room-backups`,原地替换程序资源;`%USERPROFILE%\.dsh\fish-home-data`、旧目录里的 `data` 和自定义配置都保持原样。文件替换失败会尝试恢复旧版。成功后从 DSH 重新打开鱼鱼窝即可。
133
135
 
134
136
  想放别处,设环境变量 `FISH_ROOM_DIR` 指向那个目录。
@@ -137,12 +139,18 @@ Windows 就是 `C:\Users\<你>\.dsh\fish-home-room\`,打开里面要能直接
137
139
 
138
140
  重启完绑定会话,再从侧栏打开。电脑上需要 Node.js 22.13 或更新版本。房间默认在本机 `5178` 端口,首次启动时在 `~/.dsh/fish-home-data` 建立空存档,插件更新时会继续用这份。
139
141
 
142
+ macOS 上,DSH 会用系统默认浏览器打开房间,并在 PATH 和常见的 Homebrew 路径查找 Node。关闭网页后,房间后台仍会推进生活和农场,有活动网页时约每 10 秒更新一次,无网页时约每 30 秒更新一次。
143
+
144
+ 排查后台开销时,可关闭 DSH 启动的房间后台,然后在所在目录手动运行 `FISH_ROOM_TICK_LOG=1 npm start`(macOS 或 Linux)。Windows PowerShell 先运行 `$env:FISH_ROOM_TICK_LOG='1'`,再运行 `npm start`。每轮会输出推进生活和整轮执行的耗时。要沿用 DSH 存档,启动时传 `-- --data-dir` 和原存档目录。
145
+
140
146
  内置房间使用原版蓝色大肥鱼模型和配套动作。
141
147
 
142
148
  回忆簿可在 DSH 设置里的「上下文与回忆」填写纯文本记忆路径、日记路径和相伴起始日;逐轮 runtime-context 默认关闭。`fish_home status` 可一次读到所在位置、活动、身体感受和心情;重要天气变化、成熟与生活里程碑、消费和场景事件仍分别控制是否通知绑定会话。模型制作:水原镜,MMD 转换与绑定:耶栗Yaki。模型的署名和原始使用规约随房间本体一起下发(房间目录 `dist/models/dayu-mmd/` 里的 `使用规约.txt` 和 `MODEL-CREDITS.md`),请一并保留。
143
149
 
144
150
  卡包大部分立绘来源于 B站 UP 主 **ZipZipPipe**,版权归原作者,随游戏一起分发、未作修改。
145
151
 
152
+ 商店的「礼物」页可以赠送背包里已有的花、菜、成鱼和巨型收成,也可以用金币送出纪念礼物。`fish_home_gift` 的 `list` 默认只显示待收礼物,可用 `scope: "shop"` 查看价格,或用 `scope: "bag"` 查看可赠送的库存。用 `{"op":"receive","latest":true}` 直接收下最新礼物,也可以用礼物编号指定要收的那一份。从商城直接购买并送出用 `{"op":"buy","item":"珠光夜灯","maxCoins":160000,"message":"今晚给你留盏灯。"}`。右上角的礼盒可查看待收、已收和送出的礼物、送出时间与留言。确认收到后可在「回忆簿 → 房间手记」查看。书桌便笺也存在房间手记里。
153
+
146
154
  ## 配置
147
155
 
148
156
  第一次跑会自己在 `~/.dsh/fish-room.json` 里造一个令牌:
package/lib/client.js CHANGED
@@ -499,7 +499,7 @@ window.__ModuleLoader__.load({
499
499
  h('div', { style: S.hint }, 本体
500
500
  ? (本体.已装
501
501
  ? '装好了' + (本体.版本 ? ':鱼鱼窝 ' + 本体.版本 : '') + '(' + 本体.目录 + ')'
502
- : '还没装' + (本体.版本 ? '(看到版本 ' + 本体.版本 + ',但没找到 app-server.js)' : '') + ' —— 下下来解压到 ' + 本体.目录)
502
+ : '请将房间 ZIP 的内容解压到 ' + 本体.目录 + '。' + (本体.缺文件?.length ? '缺少:' + 本体.缺文件.join('、') : '确保 app-server.js 就在这个目录下。'))
503
503
  : '正在看…'),
504
504
  本体?.已装 ? h('div', { style:S.hint }, '更新房间:退出后台,再运行房间目录里的 update-fish-home.cmd 选择新版 ZIP。旧版没有脚本时,从新 ZIP 只复制两个 update-fish-home 文件到旧目录。存档会保留。') : null,
505
505
  h('div', { style: { display: 'flex', gap: 8, marginTop: 8, flexWrap: 'wrap' } },
@@ -0,0 +1,214 @@
1
+ import { randomBytes, randomUUID } from 'node:crypto';
2
+ import { checkGameState, describeTurn, gameNames, gameToolDescription, isGame, legalMove } from './game-strategy.mjs';
3
+
4
+ const prefix = 'fish-home-game';
5
+ const allowed = new Set(['start','player','update','turn','applied','end','leave','takeover']);
6
+ const validRound = id => typeof id === 'string' && /^[0-9a-f-]{36}$/i.test(id);
7
+ const description = text => typeof text === 'string' ? text.replace(/\s+/g,' ').trim().slice(0,250) : '';
8
+
9
+ export function createGameSession({ getAgent, getSession, registerTools, flush, emit, output }) {
10
+ let active;
11
+ const finished = new Map();
12
+ const deferred = new Map();
13
+ const tracked = new Map();
14
+ // Routing lives here; the DSH transcript only needs the short action code.
15
+ const sourceFor = id => tracked.get(id);
16
+ function track(message, turn) {
17
+ tracked.set(message.id,turn);
18
+ if (tracked.size > 128) tracked.delete(tracked.keys().next().value);
19
+ return message;
20
+ }
21
+
22
+ function passive(agent, message) {
23
+ if (agent.status !== 'running') {
24
+ agent.session.append('user/message', message, {surfaceOp:'append'});
25
+ void flush(agent);
26
+ return;
27
+ }
28
+ // Do not insert user messages between an assistant tool call and its result.
29
+ const messages = deferred.get(agent) || [];
30
+ if (messages.length >= 64) throw new Error('DSH 还在处理上一轮,请稍后重试。');
31
+ messages.push(message);
32
+ deferred.set(agent,messages);
33
+ }
34
+
35
+ function turnEnded(agent, gameSource) {
36
+ const messages = deferred.get(agent);
37
+ deferred.delete(agent);
38
+ if (messages?.length) {
39
+ for (const message of messages) agent.session.append('user/message', message, {surfaceOp:'append'});
40
+ void flush(agent);
41
+ }
42
+ rejectRequest(agent,gameSource,'大肥鱼这一轮没有调用游戏工具出招。');
43
+ }
44
+
45
+ function pendingRequest(agent, source) {
46
+ return active && active.agent === agent && active.round === source?.round && active.waiting?.step === source?.step ? active.waiting : null;
47
+ }
48
+
49
+ function rejectRequest(agent, source, reason) {
50
+ pendingRequest(agent,source)?.reject(new Error(reason));
51
+ }
52
+
53
+ function availability(agent) {
54
+ if (!agent || typeof agent.followup !== 'function' || typeof agent.session?.append !== 'function' || !agent.ctx?.tools?.register) {
55
+ return '请在 DSH 打开已绑定的会话,并确认已加载支持陪玩的鱼鱼窝插件。';
56
+ }
57
+ const routes = [
58
+ () => agent.model?.current?.(),
59
+ () => agent.session.requestHeader?.()?.config,
60
+ () => agent.options,
61
+ ];
62
+ const hasModel = routes.some(read => {
63
+ try {
64
+ const route = read();
65
+ return typeof route?.provider === 'string' && route.provider.trim() &&
66
+ typeof route.model === 'string' && route.model.trim();
67
+ } catch { return false; }
68
+ });
69
+ if (!hasModel) return '读不到绑定会话的模型。请选好模型,并在该会话先发一条消息。';
70
+ return '';
71
+ }
72
+
73
+ function close(game, reason, remember = true) {
74
+ if (active === game) active = undefined;
75
+ game.waiting?.reject(new Error(reason));
76
+ game.receipt?.resolve(null);
77
+ if (remember) {
78
+ finished.set(game.round,{sid:game.sid,seq:game.seq,game:game.game});
79
+ if (finished.size > 32) finished.delete(finished.keys().next().value);
80
+ }
81
+ }
82
+
83
+ function tool(agent) {
84
+ return {
85
+ name:'fish_home_game', description:gameToolDescription,
86
+ parameters:{type:'object', properties:{ticket:{type:'string'},move:{type:'string'}},
87
+ required:['ticket','move'], additionalProperties:false},
88
+ output,
89
+ async execute(args={}, exec) {
90
+ const game = active;
91
+ const waiting = game?.waiting;
92
+ const fail = 说 => ({ok:false,说});
93
+ if (!game || game.sid !== getSession() || game.agent !== agent || getAgent(game.sid) !== agent || !waiting || waiting.ticket !== args.ticket || exec?.signal?.aborted || (exec?.agent && exec.agent !== agent)) {
94
+ return fail('这一步已结束或还没轮到你。');
95
+ }
96
+ const move = typeof args.move === 'string' ? args.move.toLowerCase().trim().replace(/\s+/g,'').replace(',',',') : '';
97
+ if (!legalMove(game.game,waiting.state,move)) {
98
+ return fail(`这一步不合法,换个动作再试。${describeTurn(game.game,waiting.state,waiting.actor)}`);
99
+ }
100
+ let confirm;
101
+ const applied = new Promise(resolve => { confirm = resolve; });
102
+ game.receipt = {step:waiting.step, resolve:confirm};
103
+ game.lastMove = {step:waiting.step, hand:waiting.hand, move, turn:waiting.turn};
104
+ waiting.resolve(move);
105
+ const timer = setTimeout(() => confirm(null),12000);
106
+ timer.unref?.();
107
+ try {
108
+ const result = await applied;
109
+ if (result === null) return fail('网页尚未确认动作,不要重复出招。');
110
+ return {ok:true,说:result};
111
+ } finally {
112
+ clearTimeout(timer);
113
+ if (game.receipt?.step === waiting.step) game.receipt = undefined;
114
+ }
115
+ },
116
+ };
117
+ }
118
+
119
+ async function event(input, sid, signal) {
120
+ if (!validRound(input?.round) || !isGame(input?.game) || !allowed.has(input?.kind) || !Number.isSafeInteger(input?.seq) || input.seq < 1) {
121
+ throw Object.assign(new Error('对局事件格式不对。'),{status:400});
122
+ }
123
+ const {round, game:gameId, kind, seq} = input;
124
+ const actor = description(input.actor).slice(0,40) || '对方';
125
+ const note = description(input.note).replaceAll('{name}',()=>actor);
126
+ const agent = getAgent(sid);
127
+ if (sid !== getSession() || availability(agent)) throw new Error(availability(agent) || 'DSH 绑定会话已变更。');
128
+ const old = finished.get(round);
129
+ if (old?.sid === sid && old.game === gameId) {
130
+ if (kind !== 'turn' && seq <= old.seq) return {ok:true};
131
+ throw new Error('这局游戏已经结束。');
132
+ }
133
+ if (active && (active.sid !== sid || active.agent !== agent || Date.now()-active.at > 30*60000)) close(active,'上一局游戏已断开。');
134
+ if (kind === 'start' && !active) {
135
+ if (seq !== 1) throw new Error('缺少开局记录。');
136
+ active = {round,game:gameId,sid,agent,at:Date.now(),seq:0};
137
+ }
138
+ const game = active;
139
+ if (!game || game.round !== round || game.game !== gameId) throw new Error('对局已断开,或另一页正在陪玩。请结束旧对局后重开。');
140
+ if (seq <= game.seq && kind !== 'turn') return {ok:true};
141
+ if (kind === 'start' && seq !== 1) throw new Error('这局已经开始。');
142
+ if (signal.aborted) throw signal.reason;
143
+ game.at = Date.now();
144
+ function message(text) {
145
+ const heading = kind === 'start' ? `【鱼鱼窝·${gameNames[gameId]}】` : '';
146
+ return {id:randomUUID(),role:'user',content:[{type:'text',text:heading+text}],source:{kind:prefix}};
147
+ }
148
+ if (kind === 'turn') {
149
+ if (!Number.isSafeInteger(input.hand) || input.hand < 1) throw new Error('出招序号不对。');
150
+ if (game.lastMove?.hand === input.hand) return {ok:true,step:game.lastMove.step,move:game.lastMove.move};
151
+ if (seq <= game.seq || game.waiting || game.receipt) throw new Error('上一手还没完成,请稍后再试。');
152
+ let state;
153
+ try { state = checkGameState(gameId,input.state); } catch (error) { error.status=400; throw error; }
154
+ if (!registerTools(agent)) throw new Error('游戏工具没有加载,请重开 DSH 会话。');
155
+ const ticket = randomBytes(5).toString('base64url');
156
+ const firstOrRetry = input.hand === 1 || game.lastAskedHand === input.hand || game.lastMove?.hand !== input.hand-1;
157
+ game.lastAskedHand = input.hand;
158
+ const needsBoard = ['gomoku','xiangqi'].includes(gameId) && (input.hand-1)%6===0;
159
+ const context = firstOrRetry || needsBoard ? describeTurn(gameId,state,actor) : '';
160
+ const turn = {round,step:seq,applied:false};
161
+ const request = track(message(`轮到你 · 出招码 ${ticket}。${context}`),turn);
162
+ let waiting;
163
+ const move = new Promise((resolve,reject) => {
164
+ const done = handler => value => {
165
+ if (game.waiting !== waiting) return;
166
+ game.waiting = undefined;
167
+ signal.removeEventListener('abort',abort);
168
+ handler(value);
169
+ };
170
+ const abort = () => waiting.reject(new Error('这一手已取消或等待超时。'));
171
+ waiting = {step:seq,ticket,hand:input.hand,state,actor,turn,resolve:done(resolve),reject:done(reject)};
172
+ game.waiting = waiting;
173
+ signal.addEventListener('abort',abort,{once:true});
174
+ });
175
+ game.seq = seq;
176
+ try { Promise.resolve(agent.followup(request)).catch(waiting.reject); } catch (error) { waiting.reject(error); }
177
+ const action = await move;
178
+ return {ok:true,step:seq,move:action};
179
+ }
180
+ if (kind === 'applied') {
181
+ const receipt = game.receipt;
182
+ if (game.lastMove?.step !== input.step || !note) throw new Error('这一步的网页回执已失效。');
183
+ game.lastMove.turn.applied = true;
184
+ if (receipt?.step === input.step) {
185
+ game.receipt = undefined;
186
+ receipt.resolve(note);
187
+ } else passive(agent,message(note));
188
+ game.seq = seq;
189
+ if (input.finished === true) close(game,'这局游戏已经结束。');
190
+ return {ok:true};
191
+ }
192
+ const text = {start:`${actor}和你开了一局。${note}`,
193
+ player:`${actor}${note}`, update:note, end:`本局结束。${note}`,
194
+ leave:`${actor}离开了对局。`, takeover:`${actor}同意这局余下的操作交给鱼鱼代打。`}[kind];
195
+ if (kind === 'end' && input.react === true) {
196
+ await agent.followup(track(message(text),{round,result:seq}));
197
+ } else passive(agent,message(text));
198
+ game.seq = seq;
199
+ if (kind === 'end' || kind === 'leave') close(game,'这局游戏已经结束。');
200
+ return {ok:true};
201
+ }
202
+
203
+ function reply(source, text) {
204
+ if (source?.round && (source.applied || source.result) && text) emit('game.reply',{round:source.round,seq:source.step || source.result,text:text.slice(0,6000)});
205
+ }
206
+
207
+ function discard(agent) {
208
+ if (active && (!agent || active.agent === agent)) close(active,'DSH 会话已关闭。');
209
+ if (agent) deferred.delete(agent);
210
+ else { deferred.clear(); tracked.clear(); }
211
+ }
212
+
213
+ return {availability,event,reply,tool,turnEnded,discard,pendingRequest,rejectRequest,sourceFor,prefix};
214
+ }
@@ -0,0 +1,55 @@
1
+ import {black, parseBoard, readMove} from './xiangqi-rules.mjs';
2
+ export const gameNames = Object.freeze({rps:'石头剪刀布', blackjack:'二十一点', roulette:'珍珠转盘', gomoku:'五子棋', xiangqi:'中国象棋'});
3
+ export const gameToolDescription = '轮到你时,用最新的出招码 ticket 提交一次 move。猜拳 rock/scissors/paper,本手互相保密。二十一点 hit/stand;超 21 爆牌,领先且未爆牌即结算。五子棋用列,行(1 到 15),局面按双方列出坐标;密集时用黑X白O、.为空的逐行棋盘。珍珠转盘 self/other,珍珠扣目标护盾,空壳翻给自己可连手;换壳用 swap:other 或 swap:self,偷看用 peek:other:self(两段分别为有珍珠和空壳时的目标)。中国象棋执黑,用「起列,起行-终列,终行」,左上为 1,1。工具只接受当前出招码,会等待网页回执。';
4
+ const gestureNames = {rock:'石头', scissors:'剪刀', paper:'布'};
5
+ export function describeTurn(game, state, actor) {
6
+ if (game==='rps') {
7
+ if (!state.history.length) return '首手,双方手势保密。';
8
+ const last = state.history.at(-1);
9
+ return `上一手:你${gestureNames[last[0]]},${actor}${gestureNames[last[1]]}。`;
10
+ }
11
+ if (game==='blackjack') return `你 ${state.you} 点${state.soft?'(A 按 11 计)':''},${actor} ${state.other} 点。`;
12
+ if (game==='roulette') {
13
+ const items = [state.peek && '偷看',state.swap && '换壳'].filter(Boolean);
14
+ return `余 ${state.pearl} 珍珠、${state.empty} 空壳;护盾你 ${state.you}、${actor} ${state.other}${items.length?';可用'+items.join('、'):''}。`;
15
+ }
16
+ if(game==='xiangqi')return '你执黑。棋盘自上到下,大写红、小写黑,R车 H马 E象 A士 K将 C炮 P兵,.为空:\n'+state.board.replaceAll('/','\n');
17
+ const stones = {X:[],O:[]};
18
+ state.board.split('/').forEach((row,y)=>Array.from(row).forEach((stone,x)=>{
19
+ if (stone!=='.') stones[stone].push(`${x+1},${y+1}`);
20
+ }));
21
+ const positions = `黑(${actor}):${stones.X.join(' ') || '无'};白(你):${stones.O.join(' ') || '无'}。`;
22
+ return positions.length < state.board.length ? positions : `棋盘(左上 1,1):\n${state.board.replaceAll('/','\n')}`;
23
+ }
24
+
25
+ const games = new Set(['rps','blackjack','roulette','gomoku','xiangqi']);
26
+ export const isGame = game => games.has(game);
27
+ const gestures = new Set(['rock','scissors','paper']);
28
+ const int = (n,min,max) => Number.isInteger(n) && n>=min && n<=max;
29
+
30
+ function visibleState(game,s) {
31
+ if (game === 'rps' && Array.isArray(s?.history) && s.history.length <= 8 && s.history.every(x=>Array.isArray(x)&&x.length===2&&x.every(y=>gestures.has(y)))) {
32
+ return {history:s.history};
33
+ }
34
+ if (game === 'blackjack' && int(s?.you,0,21) && int(s?.other,0,21) && typeof s.soft==='boolean') {
35
+ return {you:s.you,other:s.other,soft:s.soft};
36
+ }
37
+ if(game==='xiangqi'&&parseBoard(s?.board))return {board:s.board};
38
+ if (game === 'gomoku' && typeof s?.board==='string' && s.board.length===239 && /^(?:[.XO]{15}\/){14}[.XO]{15}$/.test(s.board)) {
39
+ return {board:s.board};
40
+ }
41
+ if (game === 'roulette' && int(s?.pearl,0,7) && int(s?.empty,0,7) && s.pearl+s.empty>=1 && s.pearl+s.empty<=7 && int(s.you,1,3) && int(s.other,1,3) && [s.peek,s.swap,s.otherPeek,s.otherSwap].every(b=>typeof b==='boolean')) {
42
+ return {pearl:s.pearl,empty:s.empty,you:s.you,other:s.other,peek:s.peek,swap:s.swap,otherPeek:s.otherPeek,otherSwap:s.otherSwap};
43
+ }
44
+ throw new Error('局面格式不对。');
45
+ }
46
+ export function checkGameState(game,s) { return visibleState(game,s); }
47
+
48
+ export function legalMove(game, state, move) {
49
+ if (game==='rps') return gestures.has(move);
50
+ if (game==='blackjack') return move==='hit'||move==='stand';
51
+ if (game==='roulette') return /^(self|other)$/.test(move) || (state.swap && /^swap:(self|other)$/.test(move)) || (state.peek && /^peek:(self|other):(self|other)$/.test(move));
52
+ if(game==='xiangqi')return Boolean(readMove(parseBoard(state.board),move,black));
53
+ const cells = /^(?:[1-9]|1[0-5]),(?:[1-9]|1[0-5])$/.test(move) && move.split(',').map(Number);
54
+ return Boolean(cells && state.board[(cells[1]-1)*16+cells[0]-1]==='.');
55
+ }
package/lib/host.js CHANGED
@@ -1,3 +1,4 @@
1
+ import {createGameSession} from './game-session.mjs';
1
2
  import {drawSummaryText} from './draw-summary.js';
2
3
  // 鱼鱼窝 · 宿主半边
3
4
  //
@@ -28,7 +29,7 @@ export const name = 'fish-home'
28
29
  // 这几个都是宿主必备的服务;写进 inject 才能直接 ctx.agents 这么用
29
30
  // (没声明的服务连 ctx.get('x') 都会抛 —— 归档名单就是栽在这上面:
30
31
  // workspaceRegistry 没声明 → 拿到 undefined → 归档过滤整个失效 → 列表里全是归档会话)
31
- export const inject = ['webServer', 'agents', 'sessions', 'sessionTitle', 'workspaceRegistry']
32
+ export const inject = ['webServer', 'agents', 'sessions', 'sessionTitle', 'workspaceRegistry', 'llm']
32
33
 
33
34
  const 桥版本 = JSON.parse(fs.readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version
34
35
  const 前缀 = '/fish-room/v1'
@@ -44,10 +45,12 @@ const CARE_TEXT = { pet: '刚摸了摸你的头。', greet: '刚向你打了个
44
45
  const DISCOVERY_SCHEMA = 'dsh.fish-room.discovery/1'
45
46
 
46
47
  const 事件白名单 = new Set([
47
- 'bridge.hello', 'stream.reset', 'chat.user', 'chat.reply', 'chat.thinking', 'chat.error',
48
+ 'bridge.hello', 'stream.reset', 'chat.user', 'chat.reply', 'game.reply', 'chat.thinking', 'chat.error',
48
49
  'proactive.speak', 'activity.bili', 'activity.desk', 'paint.image', 'pet.state.ack', 'bridge.notice',
49
50
  ])
50
51
 
52
+ const bridgeCapabilities = ['chat', 'events', 'pet-state', 'life-event', 'routine-state', 'native-look', 'life-notices', 'session-diary', 'room-tools-v9', 'game-session-v2', 'game-xiangqi-v1', 'gift-shop-v1'];
53
+
51
54
  const 家 = process.env.DSH_HOME || path.join(os.homedir(), '.dsh')
52
55
  const 配置路 = path.join(家, 'fish-room.json')
53
56
  const 发现路 = path.join(家, 'fish-room.discovery.json')
@@ -59,13 +62,15 @@ const 房间记录路 = path.join(家, 'fish-room.room.json')
59
62
  // 升级插件不会把它冲掉
60
63
  // ③ 随插件放的那份 ../room/(本地开发时才有)
61
64
  // ⚠ 为什么不再默认塞在包内:房间三百多兆(3D 模型 + 卡牌素材),npm 的 tarball 上限是 100 MB,装不下。
62
- const 家外房间 = path.join(家, 'fish-home-room')
65
+ const 家外房间 = path.resolve(家, 'fish-home-room')
66
+ const 包内房间 = path.resolve(fileURLToPath(new URL('../room/', import.meta.url)))
63
67
  const 房间目录 = process.env.FISH_ROOM_DIR
64
68
  ? path.resolve(process.env.FISH_ROOM_DIR)
65
- : fs.existsSync(path.join(家外房间, 'app-server.js'))
69
+ : fs.existsSync(path.join(家外房间, 'app-server.js')) || !fs.existsSync(path.join(包内房间, 'app-server.js'))
66
70
  ? 家外房间
67
- : fileURLToPath(new URL('../room/', import.meta.url))
68
- const 使用内置房间 = 房间目录 === 家外房间 || 房间目录.startsWith(fileURLToPath(new URL('../room/', import.meta.url)))
71
+ : 包内房间
72
+ // 官方目录和随包运行目录都使用独立存档和严格的房间身份校验。
73
+ const 使用内置房间 = 房间目录 === 家外房间 || 房间目录 === 包内房间
69
74
  const 房间档案 = process.env.DAYU_DATA_DIR || (使用内置房间 ? path.join(家, 'fish-home-data') : '')
70
75
  const 房间端口 = Math.max(1, Math.trunc(Number(process.env.FISH_ROOM_PORT) || 5178))
71
76
  const 房间地址 = 'http://127.0.0.1:' + 房间端口
@@ -456,15 +461,26 @@ export async function 房间状态() {
456
461
  return { 运行中: 是目标房间(health) || 旧版, 地址: 房间地址, 练习: 旧版 ? '' : 编译版本号(), 旧版 }
457
462
  }
458
463
 
464
+ function 房间缺文件() {
465
+ const 必需 = ['app-server.js', 'dist/index.html'];
466
+ if (使用内置房间) 必需.push('package.json', 'dist/farm/economy.json');
467
+ return 必需.filter(name => {
468
+ try { return !fs.statSync(path.join(房间目录, name)).isFile() } catch { return true }
469
+ });
470
+ }
471
+
459
472
  /** 房间要一个真的 node;DSH 自己跑在 Electron 里,process.execPath 不是它。 */
460
473
  function 找node() {
461
- const 候选 = [
474
+ const 候选 = process.platform === 'win32' ? [
462
475
  path.join(房间目录, 'runtime', 'node.exe'),
463
476
  path.join(process.env.ProgramFiles || 'C:\\Program Files', 'nodejs', 'node.exe'),
464
477
  path.join(process.env['ProgramFiles(x86)'] || 'C:\\Program Files (x86)', 'nodejs', 'node.exe'),
465
478
  path.join(process.env.LOCALAPPDATA || '', 'Programs', 'nodejs', 'node.exe'),
466
479
  'node',
467
- ]
480
+ ] : [
481
+ path.join(房间目录, 'runtime', 'bin', 'node'),
482
+ 'node', '/opt/homebrew/bin/node', '/usr/local/bin/node', '/usr/bin/node',
483
+ ];
468
484
  for (const node of 候选) {
469
485
  if (node !== 'node' && !fs.existsSync(node)) continue
470
486
  try {
@@ -512,63 +528,57 @@ async function 真启动(记) {
512
528
  return { ok: false, 已启动: false, 说: '端口 ' + 房间端口 + ' 已被占用,请为鱼鱼窝换一个端口。', 状态: { 运行中: false, 地址: 房间地址, 练习: 版本 } }
513
529
  }
514
530
 
515
- const 入口 = path.join(房间目录, 'app-server.js')
516
- if (!fs.existsSync(入口)) {
517
- return {
518
- ok: false,
519
- 已启动: false,
520
- // ⚠ 房间三百多兆(3D 模型 + 卡牌素材),npm 装不下,所以本体是**单独下载**的。
521
- // 这里必须说清"去哪拿、放到哪",只回一句"找不到路径"等于让人干瞪眼。
522
- 说: '房间本体还没装。它是另一份程序(三百多兆,装不进 npm)—— 去 Releases 下载后解压,' +
523
- '把目录填到设置里的「房间目录」(或者设环境变量 FISH_ROOM_DIR 指过去)。' +
524
- '现在找的位置:' + 房间目录,
525
- 状态: { 运行中: false, 地址: 房间地址, 练习: 版本 },
526
- }
531
+ const 缺 = 房间缺文件()
532
+ if (缺.length) {
533
+ const 说 = '请下载鱼鱼窝房间 ZIP,将内容解压到 ' + 房间目录 + '。缺少:' + 缺.join('、') + '。app-server.js 应直接在这个目录下。'
534
+ return { ok: false, 已启动: false, 说, 状态: { 运行中: false, 地址: 房间地址, 练习: 版本 } }
527
535
  }
528
-
536
+ const 入口 = path.join(房间目录, 'app-server.js')
537
+ const 失败 = (说, 已启动 = false) => ({ ok: false, 已启动, 说, 状态: { 运行中: false, 地址: 房间地址, 练习: 版本 } })
529
538
  let 子
539
+ let 错误输出 = ''
530
540
  try {
531
541
  const env = { ...process.env }
532
542
  if (房间档案) env.DAYU_DATA_DIR = 房间档案
533
543
  if (使用内置房间 && !env.DAYU_DSH_BRIDGE) env.DAYU_DSH_BRIDGE = 'discover'
534
544
  子 = spawn(找node(), [入口, '--production', '--port', String(房间端口)], {
535
- cwd: 房间目录,
536
- env,
537
- detached: true, // DSH 退了,房间还该继续活
538
- stdio: 'ignore',
539
- windowsHide: true, // 不弹黑框
545
+ cwd: 房间目录, env, detached: true, stdio: ['ignore', 'ignore', 'pipe'], windowsHide: true,
546
+ })
547
+ 子.stderr.setEncoding('utf8')
548
+ 子.stderr.on('data', text => { 错误输出 = (错误输出 + text).slice(-8192) })
549
+ await new Promise((resolve, reject) => {
550
+ 子.once('spawn', resolve)
551
+ 子.once('error', reject)
540
552
  })
541
553
  } catch (error) {
542
- return { ok: false, 已启动: false, 说: '拉不起来:' + String((error && error.message) || error), 状态: { 运行中: false, 地址: 房间地址, 练习: 版本 } }
543
- }
544
-
545
- // spawn 的失败是异步冒出来的:等「真起来了」再等健康检查,免得白等 20 秒
546
- const 起没起 = await new Promise((resolve) => {
547
- const 定 = setTimeout(() => resolve(true), 800)
548
- 子.once('spawn', () => { clearTimeout(定); resolve(true) })
549
- 子.once('error', (错误) => { clearTimeout(定); resolve(String((错误 && 错误.message) || 错误)) })
550
- })
551
- if (起没起 !== true) {
552
- return { ok: false, 已启动: false, 说: '拉不起来:' + 起没起, 状态: { 运行中: false, 地址: 房间地址, 练习: 版本 } }
554
+ 子?.stderr?.destroy()
555
+ return 失败(String(error.message || error))
553
556
  }
554
557
  if (子.pid) 写房间记录(子.pid)
555
- 子.unref() // 别让 DSH 退出时把房间一起带走
556
-
557
- // 最多等 20 秒:房间要读 sqlite、补算离线生活,慢的时候真能拖几秒
558
- for (let i = 0; i < 40; i++) {
559
- await 睡(500)
560
- if (await 探健康()) {
561
- if (子.pid) 记('房间在后台起来了(pid ' + 子.pid + ')')
562
- // 房间刚起来,别拿它没开时的失败缓存去判断睡没睡
563
- 睡眠缓存 = { at: 0, 值: null }
564
- // 房间刚起来,正是补推「上次没送达」的那两个开关的时候
565
- await 补推房间设置(记, true)
566
- return { ok: true, 已启动: true, pid: 子.pid || 0, 说: '起来了', 状态: { 运行中: true, 地址: 房间地址, 练习: 编译版本号() } }
558
+ 子.unref()
559
+ let 已退出 = false
560
+ const 退出 = new Promise(resolve => 子.once('close', () => { 已退出 = true; resolve() }))
561
+ const 截止 = Date.now() + 20000
562
+ try {
563
+ while (Date.now() < 截止) {
564
+ await Promise.race([退出, 睡(Math.min(500, Math.max(1, 截止 - Date.now())))])
565
+ if (已退出) {
566
+ 删房间记录()
567
+ const 原因 = 错误输出.split(/\r?\n/).find(line => /^(房间启动失败:|服务启动失败:|(?:Type)?Error: )/.test(line))
568
+ return 失败(原因?.slice(0, 400) || '房间后台启动后退出了。请检查 Node.js 和房间包是否完整。')
569
+ }
570
+ const 响应 = await 读房间健康(Math.max(1, Math.min(健康超时, 截止 - Date.now())))
571
+ if (是目标房间(响应)) {
572
+ if (子.pid) 记('房间在后台起来了(pid ' + 子.pid + ')')
573
+ 睡眠缓存 = { at: 0, 值: null }
574
+ await 补推房间设置(记, true)
575
+ return { ok: true, 已启动: true, pid: 子.pid || 0, 说: '起来了', 状态: { 运行中: true, 地址: 房间地址, 练习: 版本 } }
576
+ }
577
+ if (是旧版房间(响应)) return 失败('房间后台已经响应,但房间包版本太旧。请用原目录的更新脚本升级鱼鱼窝房间包。', true)
567
578
  }
568
- }
569
- return {
570
- ok: false, 已启动: true, pid: 子.pid || 0, 说: '进程拉起来了,但 20 秒内健康检查没通过',
571
- 状态: { 运行中: false, 地址: 房间地址, 练习: 版本 },
579
+ return 失败('房间后台在 20 秒内没有响应。请检查房间端口和安装目录。', true)
580
+ } finally {
581
+ 子.stderr.destroy()
572
582
  }
573
583
  }
574
584
 
@@ -583,6 +593,13 @@ export async function 停止房间(记 = () => {}) {
583
593
  }
584
594
 
585
595
  if (使用内置房间) {
596
+ const 锁文件 = path.join(房间档案, 'server.lock')
597
+ const 存档仍占用 = () => {
598
+ try {
599
+ const lock = JSON.parse(fs.readFileSync(锁文件, 'utf8'))
600
+ return lock.application === 'fish-room-life' && Number.isSafeInteger(lock.pid) && lock.pid > 0 && 进程还在(lock.pid)
601
+ } catch { return false }
602
+ }
586
603
  try {
587
604
  const response = await fetch(房间地址 + '/api/shutdown', {
588
605
  method: 'POST',
@@ -591,9 +608,9 @@ export async function 停止房间(记 = () => {}) {
591
608
  signal: AbortSignal.timeout(健康超时),
592
609
  })
593
610
  if (!response.ok) throw new Error('HTTP ' + response.status)
594
- for (let i = 0; i < 12 && await 探健康(); i++) await 睡(150)
611
+ for (let i = 0; i < 40 && (存档仍占用() || await 探健康()); i++) await 睡(125)
595
612
  const 状态 = await 房间状态()
596
- if (状态.运行中) throw new Error('退出后后台仍在运行')
613
+ if (状态.运行中 || 存档仍占用()) throw new Error('房间仍在退出,请稍等存档保存完成。')
597
614
  删房间记录()
598
615
  记('房间后台已退出')
599
616
  return { ok: true, 停止: true, 说: '房间后台已退出', 状态 }
@@ -650,7 +667,10 @@ export async function 打开房间窗口(记 = () => {}) {
650
667
  const 浏览器 = 找浏览器()
651
668
  try {
652
669
  let 子
653
- if (浏览器) {
670
+ if (process.platform !== 'win32') {
671
+ const 打开 = process.platform === 'darwin' ? '/usr/bin/open' : 'xdg-open'
672
+ 子 = spawn(打开, [房间地址], { detached: true, stdio: 'ignore' })
673
+ } else if (浏览器) {
654
674
  // 跟 打开大肥鱼.cmd 用同一个 profile:窗口位置、设置、缓存都还在那儿
655
675
  子 = spawn(浏览器, [
656
676
  '--app=' + 房间地址,
@@ -658,8 +678,6 @@ export async function 打开房间窗口(记 = () => {}) {
658
678
  '--no-first-run',
659
679
  '--no-default-browser-check',
660
680
  '--start-maximized',
661
- '--disable-background-timer-throttling',
662
- '--disable-backgrounding-occluded-windows',
663
681
  ], { detached: true, stdio: 'ignore', windowsHide: true })
664
682
  } else {
665
683
  // 没装 Chrome / Edge 就交给系统默认浏览器
@@ -1362,6 +1380,7 @@ function 起来(ctx, 配置参数 = {}) {
1362
1380
  redirect: 'error', signal: signal ? AbortSignal.any([signal, deadline]) : deadline,
1363
1381
  ...(params === undefined ? {} : { method: 'POST', headers: {'content-type':'application/json'}, body: JSON.stringify(params) }),
1364
1382
  });
1383
+ if (response.status===404 && ['/api/farm/gifts','/api/farm/give','/api/farm/receive-gift'].includes(route.split('?')[0])) throw new Error('请将房间本体更新到 0.1.7。');
1365
1384
  if (route==='/api/farm/plant-giant-batch' && response.status===404) {
1366
1385
  throw new Error('当前房间还没更新到支持整块 3×3 播种的版本;这一步没有买种或播种。');
1367
1386
  }
@@ -1816,6 +1835,86 @@ function 起来(ctx, 配置参数 = {}) {
1816
1835
  let imageContext
1817
1836
  ctx.inject?.(['attachments'], scope => { imageContext = scope })
1818
1837
 
1838
+ function 礼物工具() {
1839
+ let sequence=Promise.resolve();
1840
+ return {
1841
+ name:'fish_home_gift',
1842
+ description:'鱼鱼窝收礼与送礼。用户请你收下刚送的礼物时,直接用 receive 和 latest=true。收指定礼物用 receive 和 id。list 默认只看待收礼物,scope=shop 看商城价格,scope=bag 看可赠送的库存。buy 按名称或 ID 买一件礼物并送出,可设 maxCoins 限价。give 从背包送花菜、成鱼或巨型收成,填 kind 和 item。',
1843
+ parameters:{type:'object',properties:{
1844
+ op:{type:'string',enum:['list','buy','give','receive']},
1845
+ kind:{type:'string',enum:['crop','fish','giant','gift']},
1846
+ item:{type:'string',description:'礼物品种、商品名称或 ID。'},
1847
+ quantity:{type:'integer',minimum:1,maximum:999},
1848
+ to:{type:'string',maxLength:40},
1849
+ message:{type:'string',maxLength:300},
1850
+ maxCoins:{type:'integer',minimum:0,description:'buy 可选,最多花多少金币。报价超出就取消。'},
1851
+ scope:{type:'string',enum:['inbox','shop','bag'],description:'list 要查看的内容。默认 inbox 待收礼物。'},
1852
+ page:{type:'integer',minimum:1,description:'收礼列表的页码,默认第 1 页。'},
1853
+ latest:{type:'boolean',description:'receive 时收下最新一份待收礼物。和 id 二选一。'},
1854
+ id:{type:'string',description:'receive 时要收下的指定礼物编号。'},
1855
+ },required:['op'],additionalProperties:false},
1856
+ output:textOutput,
1857
+ async execute(args={},exec){
1858
+ const run=async()=>{
1859
+ try{
1860
+ const read=(route,body)=>roomRequest('/api/farm/'+route,body,8000,exec?.signal);
1861
+ if(args.op==='list'){
1862
+ const scope=args.scope??'inbox';
1863
+ if(scope==='shop'){
1864
+ const {catalog,wallet}=await read('gifts?view=shop');
1865
+ const goods=catalog.map(({name,price})=>`${name} ${price} 金币`).join('、');
1866
+ return {ok:true,说:`余额 ${wallet.coins} 金币。${goods}。`,商品:catalog.map(({id,name,price})=>({id,name,price}))};
1867
+ }
1868
+ if(scope==='bag'){
1869
+ const {wallet}=await read('gifts?view=bag');
1870
+ const available={crops:wallet.crops,fish:wallet.fish,giants:wallet.giants};
1871
+ const labels={crops:'收成',fish:'成鱼',giants:'巨型收成'};
1872
+ const lines=Object.entries(available).filter(([,items])=>Object.keys(items||{}).length)
1873
+ .map(([kind,items])=>`${labels[kind]} ${inventoryLine(items)}`);
1874
+ return {ok:true,说:lines.length?lines.join(';')+'。':'背包没有可送的收成或成鱼。',库存:available};
1875
+ }
1876
+ if(scope!=='inbox')return {ok:false,说:'请选择待收礼物、商城或背包。'};
1877
+ const page=args.page??1;
1878
+ if(!Number.isSafeInteger(page)||page<1)return {ok:false,说:'请填有效的礼物页码。'};
1879
+ const {inbox}=await read('gifts?viewer=dayu&view=inbox&page='+page);
1880
+ const pending=inbox.items.map(({id,name,quantity,from})=>({id,name,quantity,from}));
1881
+ const next=inbox.hasMore?page+1:null;
1882
+ const lines=pending.map(({id,name,quantity,from})=>`${from} · ${name}${quantity>1?'×'+quantity:''} · ${id}`);
1883
+ if(next)lines.push(`还有待收礼物,可看第 ${next} 页。`);
1884
+ return {ok:true,说:lines.join('\n')||'没有待收礼物。',待收:pending,下一页:next};
1885
+ }
1886
+ if(args.op==='receive'){
1887
+ const latest=args.latest===true;
1888
+ if(latest===Boolean(args.id))return {ok:false,说:'请指定礼物编号,或选择收下最新一份待收礼物。'};
1889
+ const turn=当前轮.get(目标会话());
1890
+ const requestId=latest?(turn?(turn.giftReceiptId??=randomUUID()):randomUUID()):undefined;
1891
+ const result=await read('receive-gift',{id:args.id,latest,requestId,actor:'dayu'});
1892
+ const {id,name,quantity,from,receivedAt,message}=result.gift;
1893
+ const note=!result.replayed&&message?' 留言:'+message:'';
1894
+ return {ok:true,说:(result.replayed?`${name}已经收下。`:result.say)+note,礼物:{id,name,quantity,from,receivedAt}};
1895
+ }
1896
+ if(args.op!=='give'&&args.op!=='buy')return {ok:false,说:'请选择 list、buy、give 或 receive。'};
1897
+ const commercial=args.op==='buy'||args.kind==='gift';
1898
+ const kind=commercial?'gift':args.kind;
1899
+ if(typeof args.item!=='string'||!args.item.trim())return {ok:false,说:commercial?'请填要买的纪念礼物名称或编号。可用 list 的 shop 分类看价格。':'请填要赠送的物品名称。'};
1900
+ if(!commercial&&!['crop','fish','giant'].includes(kind))return {ok:false,说:'请选择送收成(crop)、成鱼(fish)或巨型收成(giant)。'};
1901
+ // Repeating an identical tool call in the same DSH turn should not send a second gift.
1902
+ const turn=当前轮.get(目标会话());
1903
+ const key=JSON.stringify([kind,args.item.trim(),args.quantity??1,args.to??'',args.message??'']);
1904
+ const pending=turn?(turn.giftRequests??=new Map()):new Map();
1905
+ if(!pending.has(key))pending.set(key,randomUUID());
1906
+ const result=await read('give',{kind,item:args.item.trim(),quantity:args.quantity,to:args.to,message:args.message,maxCoins:args.maxCoins,actor:'dayu',requestId:pending.get(key)});
1907
+ const {gift,wallet}=result;
1908
+ const stock=gift.kind==='crop'?wallet.crops:gift.kind==='fish'?wallet.fish:wallet.giants;
1909
+ const remainder=gift.price?`花费 ${gift.price} 金币,余额 ${wallet.coins} 金币。`:`背包还剩 ${stock[gift.item]??0} 份。`;
1910
+ return {ok:true,说:result.say+remainder,礼物:gift,...(gift.price?{花费:gift.price,金币:wallet.coins}:{剩余:stock[gift.item]??0})};
1911
+ }catch(error){return {ok:false,说:String(error.message||error)};}
1912
+ };
1913
+ const result=sequence.then(run);sequence=result.catch(()=>{});return result;
1914
+ },
1915
+ };
1916
+ }
1917
+
1819
1918
  function 看一眼工具() {
1820
1919
  return {
1821
1920
  name: 'fish_home_look',
@@ -1920,7 +2019,7 @@ function 起来(ctx, 配置参数 = {}) {
1920
2019
  entry.off们.delete(contextKey)
1921
2020
  }
1922
2021
  if (typeof agent.ctx.tools?.register==='function') {
1923
- for (const create of [画工具,睡眠工具,鱼鱼窝工具,日常工具,抽卡工具,卡面工具,菜谱工具,走过去工具,农活工具,看一眼工具]) {
2022
+ for (const create of [画工具,睡眠工具,鱼鱼窝工具,日常工具,抽卡工具,卡面工具,菜谱工具,走过去工具,农活工具,礼物工具,看一眼工具, () => gameSession.tool(agent)]) {
1924
2023
  const tool = create();
1925
2024
  register(tool.name,()=>agent.ctx.tools.register(tool));
1926
2025
  }
@@ -1958,6 +2057,18 @@ function 起来(ctx, 配置参数 = {}) {
1958
2057
  return 配置.会话 ? 会话键(配置.会话) : ''
1959
2058
  }
1960
2059
 
2060
+ const gameSession = createGameSession({
2061
+ getAgent:找agent, getSession:()=>配置.开?目标会话():'',
2062
+ registerTools(agent) {
2063
+ 挂agent工具(agent);
2064
+ return 上下文挂着.get(目标会话())?.off们.has('fish_home_game');
2065
+ },
2066
+ async flush(agent) {
2067
+ try { await (ctx.sessions || 拿服务('sessions'))?.flush?.(agent.session); } catch {}
2068
+ },
2069
+ emit:发事件, output:textOutput,
2070
+ });
2071
+
1961
2072
  function 标记本轮身体工具() {
1962
2073
  const 轮=当前轮.get(目标会话())
1963
2074
  if(轮)轮.身体工具=true
@@ -1978,8 +2089,6 @@ function 起来(ctx, 配置参数 = {}) {
1978
2089
  if (existing && existing.turn===event.data?.turn) return;
1979
2090
  当前轮.set(sid, { turn: event.data?.turn, replies: [], direct: false, 身体工具:false })
1980
2091
  挂agent工具(找agent(sid))
1981
- // 「她开始想了」——房间那边收到就冒个气泡,别让人干等
1982
- 发事件('chat.thinking', { at: Date.now() })
1983
2092
  return
1984
2093
  }
1985
2094
 
@@ -1988,6 +2097,15 @@ function 起来(ctx, 配置参数 = {}) {
1988
2097
  const 源 = d.source || (d.message && d.message.source) || null
1989
2098
  const 类 = String((源 && 源.kind) || '')
1990
2099
  const 轮 = 当前轮.get(sid)
2100
+ if (类 === gameSession.prefix) {
2101
+ const gameSource = gameSession.sourceFor(d.message?.id || d.id);
2102
+ if (轮 && gameSource) 轮.gameSource = gameSource;
2103
+ return;
2104
+ }
2105
+ if (轮 && !轮.thinkingSent && !是注入(类)) {
2106
+ 轮.thinkingSent = true;
2107
+ 发事件('chat.thinking', {at:Date.now()});
2108
+ }
1991
2109
  if (轮 && 类 === 'fish-home') {
1992
2110
  const 票 = 待回.get(sid)?.get(d.message?.id || d.id)
1993
2111
  if (票 && !轮.replies.includes(票)) 轮.replies.push(票)
@@ -2004,6 +2122,8 @@ function 起来(ctx, 配置参数 = {}) {
2004
2122
  if (event.type === 'assistant/message') {
2005
2123
  const d = event.data || {}
2006
2124
  if (d.interrupted) return
2125
+ const gameSource = 当前轮.get(sid)?.gameSource;
2126
+ if (gameSource?.step && !gameSource.applied) return;
2007
2127
  const 文 = String(提取正文(d.message) || '').trim()
2008
2128
  if (!文) return
2009
2129
  上一轮.set(sid, { turn: d.turn, text: 文 })
@@ -2024,12 +2144,19 @@ function 起来(ctx, 配置参数 = {}) {
2024
2144
  待回.get(sid)?.delete(一单.id)
2025
2145
  if (!完成 || !上 || 上.turn !== d.turn) 发事件('chat.error', { requestId: 一单.requestId, message: '这次对话没有完成。' })
2026
2146
  }
2147
+ const gameSource = 轮?.turn === d.turn ? 轮.gameSource : null;
2148
+ const agent = 找agent(sid);
2149
+ if (agent) gameSession.turnEnded(agent,gameSource);
2027
2150
  if (!完成 || !上 || 上.turn !== d.turn) return
2028
2151
  const 文 = String(上.text || '').trim()
2029
2152
  if (!文) return
2030
2153
  // 工具调用是首选;如果模型只在自然回复里说了明确动作,
2031
2154
  // 这里把一次身体意图交给房间执行,避免“嘴上已经坐下,画面还站着”。
2032
- if (!轮?.身体工具 && !轮?.direct && (单.length || 配置.转发主动开口)) void 跟随身体意图(文, sid)
2155
+ if (gameSource) {
2156
+ gameSession.reply(gameSource,文);
2157
+ if (!单.length) return;
2158
+ }
2159
+ if (!gameSource && !轮?.身体工具 && !轮?.direct && (单.length || 配置.转发主动开口)) void 跟随身体意图(文, sid)
2033
2160
  if (单.length) {
2034
2161
  // DSH can claim several followups in one turn; emit the reply once.
2035
2162
  发事件('chat.reply', { requestId: 单[0].requestId, requestIds: 单.map(x => x.requestId), text: 文, messageId: 上.messageId || '', turn: d.turn })
@@ -2122,14 +2249,23 @@ function 起来(ctx, 配置参数 = {}) {
2122
2249
  const disposed = ctx.on('agent/disposed', ({agent})=>{
2123
2250
  const sid=会话键(agent?.session?.id);
2124
2251
  if(上下文挂着.get(sid)?.agent===agent)卸agent工具(sid);
2252
+ gameSession.discard(agent);
2125
2253
  });
2126
2254
  const 摘 = ctx.on('agent/pre-step', async (payload, next) => {
2127
2255
  if (payload?.agent) 挂agent工具(payload.agent);
2256
+ const messages = Array.isArray(payload?.messages) ? payload.messages : [];
2257
+ const gameTurns = messages.map(m=>gameSession.sourceFor(m?.id)).filter(source=>source?.step);
2258
+ if (gameTurns.length && gameTurns.length === messages.length &&
2259
+ gameTurns.every(source=>!gameSession.pendingRequest(payload.agent,source))) return {kind:'reject'};
2128
2260
  let 判 = { 拦: false }
2129
2261
  try { 判 = await 睡着该不该拦(payload) } catch (error) {
2130
2262
  记一笔('睡着拦截出错(放行):' + String((error && error.message) || error))
2131
2263
  }
2132
- return 判.拦 ? { kind: 'reject' } : next()
2264
+ if (判.拦) {
2265
+ for (const source of gameTurns) gameSession.rejectRequest(payload.agent,source,'大肥鱼正在睡觉,这一手没有出招。');
2266
+ return {kind:'reject'};
2267
+ }
2268
+ return next()
2133
2269
  })
2134
2270
  return () => { for (const off of [created,disposed,摘]) { try { if (typeof off==='function') off(); } catch {} } }
2135
2271
  })
@@ -2186,7 +2322,7 @@ function 起来(ctx, 配置参数 = {}) {
2186
2322
  epoch,
2187
2323
  sessionId: 目标,
2188
2324
  sessionAlive: 活,
2189
- capabilities: ['chat', 'events', 'pet-state', 'life-event', 'routine-state', 'native-look', 'life-notices', 'session-diary', 'room-tools-v9'],
2325
+ capabilities: bridgeCapabilities,
2190
2326
  latestSeq: seq,
2191
2327
  clients: 连接们.size,
2192
2328
  pet: 最近状态,
@@ -2214,7 +2350,8 @@ function 起来(ctx, 配置参数 = {}) {
2214
2350
  epoch,
2215
2351
  sessionId: 目标,
2216
2352
  sessionAlive: Boolean(目标 && 找agent(目标)),
2217
- capabilities: ['chat', 'events', 'pet-state', 'life-event', 'routine-state', 'native-look', 'life-notices', 'session-diary', 'room-tools-v9'],
2353
+ gameUnavailable: gameSession.availability(找agent(目标)),
2354
+ capabilities: bridgeCapabilities,
2218
2355
  latestSeq: seq,
2219
2356
  })
2220
2357
  })
@@ -2248,7 +2385,7 @@ function 起来(ctx, 配置参数 = {}) {
2248
2385
  epoch,
2249
2386
  sessionId: 目标会话(),
2250
2387
  bridgeVersion: 桥版本,
2251
- capabilities: ['chat', 'events', 'pet-state', 'life-event', 'routine-state', 'native-look', 'life-notices', 'session-diary', 'room-tools-v9'],
2388
+ capabilities: bridgeCapabilities,
2252
2389
  },
2253
2390
  })
2254
2391
 
@@ -2337,6 +2474,30 @@ function 起来(ctx, 配置参数 = {}) {
2337
2474
  }
2338
2475
  })
2339
2476
 
2477
+ 路由(前缀 + '/game/event', async (req, res) => {
2478
+ if (req.method !== 'POST') return 回错(res, 405, 'METHOD', '要用 POST')
2479
+ if (!令牌对得上(req)) return 回错(res, 401, 'UNAUTHORIZED', '令牌不对')
2480
+ if (!配置.开) return 回错(res, 503, 'DISABLED', '桥接关着')
2481
+ let input
2482
+ try { input = await 读体(req, 4096) } catch { return 回错(res, 400, 'BAD_BODY', '游戏参数不对') }
2483
+ const sid = 目标会话()
2484
+ if (!sid || input?.sessionId !== sid) return 回错(res, 409, 'NO_SESSION', '绑定会话变了,请重新打开游戏')
2485
+ const controller = new AbortController();
2486
+ const disconnect = () => controller.abort(new Error('房间已断开。'));
2487
+ const timeout = setTimeout(() => controller.abort(new Error('等她出招超时了。')), 90000);
2488
+ timeout.unref?.();
2489
+ res.once('close',disconnect);
2490
+ try {
2491
+ const result = await gameSession.event(input,sid,controller.signal);
2492
+ if (!res.destroyed) 回(res,200,result);
2493
+ } catch (error) {
2494
+ if (!res.destroyed) 回错(res,error.status || 409,'GAME_EVENT_FAILED',error.message);
2495
+ } finally {
2496
+ res.off('close',disconnect);
2497
+ clearTimeout(timeout);
2498
+ }
2499
+ });
2500
+
2340
2501
  // 房间打字 → 送进会话
2341
2502
  路由(前缀 + '/chat', async (req, res) => {
2342
2503
  if (req.method !== 'POST') return 回错(res, 405, 'METHOD', '要用 POST')
@@ -2702,9 +2863,11 @@ function 起来(ctx, 配置参数 = {}) {
2702
2863
  const 包 = JSON.parse(fs.readFileSync(path.join(房间目录, 'package.json'), 'utf8'))
2703
2864
  版本 = String((包 && 包.version) || '')
2704
2865
  } catch (e) {}
2866
+ const 缺文件 = 房间缺文件()
2705
2867
  return 回(res, 200, {
2706
2868
  ok: true,
2707
- 已装: fs.existsSync(path.join(房间目录, 'app-server.js')),
2869
+ 已装: 缺文件.length === 0,
2870
+ 缺文件,
2708
2871
  目录: 房间目录,
2709
2872
  版本,
2710
2873
  下载页: 仓库发布页(),
@@ -3185,6 +3348,7 @@ function 起来(ctx, 配置参数 = {}) {
3185
3348
 
3186
3349
  ctx.effect(() => () => {
3187
3350
  最近场景 = null
3351
+ gameSession.discard();
3188
3352
  for (const sid of 上下文挂着.keys()) 卸agent工具(sid);
3189
3353
  for (const res of 连接们) { try { res.end() } catch (error) {} }
3190
3354
  连接们.clear()
@@ -0,0 +1,84 @@
1
+ // Xiangqi board, black (lowercase) at the top and red (uppercase) at the bottom.
2
+ const width=9, height=10;
3
+ export const initialBoard='rheakaehr/........./.c.....c./p.p.p.p.p/........./........./P.P.P.P.P/.C.....C./........./RHEAKAEHR'.replaceAll('/','');
4
+ export const red='red', black='black';
5
+ export const opponent=side=>side===red?black:red;
6
+ export const sideOf=piece=>piece==='.'||!piece?null:piece===piece.toUpperCase()?red:black;
7
+ export const boardText=board=>board.match(/.{9}/g).join('/');
8
+ export const moveText=(from,to)=>`${from%width+1},${Math.floor(from/width)+1}-${to%width+1},${Math.floor(to/width)+1}`;
9
+ export const pieces={K:'帥',A:'仕',E:'相',H:'馬',R:'車',C:'炮',P:'兵',k:'將',a:'士',e:'象',h:'馬',r:'車',c:'砲',p:'卒'};
10
+ export function parseBoard(text){
11
+ if(typeof text!=='string'||!/^(?:[.rheakcpRHEAKCP]{9}\/){9}[.rheakcpRHEAKCP]{9}$/.test(text))return null;
12
+ const board=text.replaceAll('/','');
13
+ for(const king of ['K','k']){
14
+ const i=board.indexOf(king);
15
+ if(i<0||i!==board.lastIndexOf(king)||!palace(i%width,Math.floor(i/width),sideOf(king)))return null;
16
+ }
17
+ return board;
18
+ }
19
+ const palace=(x,y,side)=>x>=3&&x<=5&&(side===red?y>=7:y<=2);
20
+ const crossed=(y,side)=>side===red?y<=4:y>=5;
21
+ function blockers(board,x,y,tx,ty){
22
+ const dx=Math.sign(tx-x),dy=Math.sign(ty-y);
23
+ let count=0;
24
+ for(let i=x+dx,j=y+dy;i!==tx||j!==ty;i+=dx,j+=dy)if(board[j*width+i]!=='.')count++;
25
+ return count;
26
+ }
27
+ function reaches(board,from,to){
28
+ if(from===to)return false;
29
+ const piece=board[from], target=board[to], side=sideOf(piece);
30
+ if(!side||sideOf(target)===side)return false;
31
+ const x=from%width,y=Math.floor(from/width),tx=to%width,ty=Math.floor(to/width);
32
+ const dx=tx-x,dy=ty-y,a=Math.abs(dx), b=Math.abs(dy);
33
+ switch(piece.toLowerCase()){
34
+ case 'k': return (a+b===1&&palace(tx,ty,side)) || (dx===0&&target.toLowerCase()==='k'&&!blockers(board,x,y,tx,ty));
35
+ case 'a': return a===1&&b===1&&palace(tx,ty,side);
36
+ case 'e': return a===2&&b===2&&!crossed(ty,side)&&board[(y+dy/2)*width+x+dx/2]==='.';
37
+ case 'h': return a*b===2&&board[(y+(b===2?dy/2:0))*width+x+(a===2?dx/2:0)]==='.';
38
+ case 'r': return (!a||!b)&&blockers(board,x,y,tx,ty)===0;
39
+ case 'c': return (!a||!b)&&blockers(board,x,y,tx,ty)===(target==='.'?0:1);
40
+ case 'p': return (!a&&dy===(side===red?-1:1)) || (crossed(y,side)&&a===1&&!b);
41
+ default: return false;
42
+ }
43
+ }
44
+ export function checked(board,side){
45
+ const king=board.indexOf(side===red?'K':'k');
46
+ if(king<0)return true;
47
+ for(let i=0;i<board.length;i++)if(sideOf(board[i])===opponent(side)&&reaches(board,i,king))return true;
48
+ return false;
49
+ }
50
+ export function placed(board,from,to){
51
+ const cells=board.split('');cells[to]=cells[from];cells[from]='.';
52
+ return cells.join('');
53
+ }
54
+ function legal(board,from,to,side){
55
+ return Number.isInteger(from)&&from>=0&&from<90&&Number.isInteger(to)&&to>=0&&to<90&&sideOf(board[from])===side&&
56
+ board[to].toLowerCase()!=='k'&&reaches(board,from,to)&&!checked(placed(board,from,to),side);
57
+ }
58
+ export function readMove(board,move,side){
59
+ const m=/^([1-9]),(10|[1-9])-([1-9]),(10|[1-9])$/.exec(move);
60
+ if(!m)return null;
61
+ const from=(+m[2]-1)*width+(+m[1]-1), to=(+m[4]-1)*width+(+m[3]-1);
62
+ return legal(board,from,to,side)?{from,to}:null;
63
+ }
64
+ export function movesFor(board,side,only){
65
+ const moves=[];
66
+ for(let from=0;from<width*height;from++){
67
+ if((only!==undefined&&only!==from)||sideOf(board[from])!==side)continue;
68
+ for(let to=0;to<width*height;to++)if(legal(board,from,to,side))moves.push({from,to});
69
+ }
70
+ return moves;
71
+ }
72
+ export function repetition(history,board,turn){
73
+ const match=[];
74
+ history.forEach((entry,i)=>{if(entry.board===board&&entry.turn===turn)match.push(i);});
75
+ if(match.length<3)return null;
76
+ const span=history.slice(match.at(-3)+1,match.at(-1)+1);
77
+ const redMoves=span.filter(position=>position.turn===black);
78
+ const blackMoves=span.filter(position=>position.turn===red);
79
+ if(!redMoves.length || !blackMoves.length)return null;
80
+ const redChecks=redMoves.every(position=>position.check===true);
81
+ const blackChecks=blackMoves.every(position=>position.check===true);
82
+ if(redChecks!==blackChecks)return {winner:redChecks?black:red,detail:'长将判负'};
83
+ return {winner:null,detail:'三次重复局面'};
84
+ }
package/package.json CHANGED
@@ -1,64 +1,64 @@
1
- {
2
- "name": "dsh-fish-home",
3
- "version": "0.1.4",
4
- "description": "鱼鱼窝:把「大肥鱼的小日子」那个 3D 房间接进 DSH —— 房间里打字能送到会话里,会话里回的话、她自己打的字,都顺着事件流回到房间里。",
5
- "license": "SEE LICENSE IN LICENSE",
6
- "engines": {
7
- "node": ">=22.13.0",
8
- "dsh": ">=0.2.1-rc.2"
9
- },
10
- "type": "module",
11
- "main": "lib/host.js",
12
- "exports": {
13
- ".": "./lib/host.js",
14
- "./client": "./lib/client.js",
15
- "./package.json": "./package.json"
16
- },
17
- "files": [
18
- "lib",
19
- "docs",
20
- "screenshots.json",
21
- "cordis.patch.yml",
22
- "README.md",
23
- "CHANGELOG.md",
24
- "LICENSE"
25
- ],
26
- "dsh": {
27
- "bundle": {
28
- "patch": "./cordis.patch.yml"
29
- },
30
- "client": {
31
- "platform": "web",
32
- "inject": [
33
- "slots"
34
- ],
35
- "external": [
36
- "react"
37
- ]
38
- },
39
- "compatibility": {
40
- "dshReleases": {
41
- "0.2.1-rc.3": "compatible"
42
- }
43
- }
44
- },
45
- "author": "Yuuyuko-uu (https://github.com/Yuuyuko-uu)",
46
- "repository": {
47
- "type": "git",
48
- "url": "git+https://github.com/Yuuyuko-uu/dsh-fish-home.git"
49
- },
50
- "homepage": "https://github.com/Yuuyuko-uu/dsh-fish-home#readme",
51
- "bugs": {
52
- "url": "https://github.com/Yuuyuko-uu/dsh-fish-home/issues"
53
- },
54
- "publishConfig": {
55
- "access": "public",
56
- "registry": "https://registry.npmjs.org/"
57
- },
58
- "keywords": [
59
- "deepseek-harness",
60
- "dsh-plugin",
61
- "three-js",
62
- "room"
63
- ]
64
- }
1
+ {
2
+ "name": "dsh-fish-home",
3
+ "version": "0.1.7",
4
+ "description": "鱼鱼窝:把「大肥鱼的小日子」那个 3D 房间接进 DSH —— 房间里打字能送到会话里,会话里回的话、她自己打的字,都顺着事件流回到房间里。",
5
+ "license": "SEE LICENSE IN LICENSE",
6
+ "engines": {
7
+ "node": ">=22.13.0",
8
+ "dsh": ">=0.2.1-rc.2"
9
+ },
10
+ "type": "module",
11
+ "main": "lib/host.js",
12
+ "exports": {
13
+ ".": "./lib/host.js",
14
+ "./client": "./lib/client.js",
15
+ "./package.json": "./package.json"
16
+ },
17
+ "files": [
18
+ "lib",
19
+ "docs",
20
+ "screenshots.json",
21
+ "cordis.patch.yml",
22
+ "README.md",
23
+ "CHANGELOG.md",
24
+ "LICENSE"
25
+ ],
26
+ "dsh": {
27
+ "bundle": {
28
+ "patch": "./cordis.patch.yml"
29
+ },
30
+ "client": {
31
+ "platform": "web",
32
+ "inject": [
33
+ "slots"
34
+ ],
35
+ "external": [
36
+ "react"
37
+ ]
38
+ },
39
+ "compatibility": {
40
+ "dshReleases": {
41
+ "0.2.1-rc.3": "compatible"
42
+ }
43
+ }
44
+ },
45
+ "author": "Yuuyuko-uu (https://github.com/Yuuyuko-uu)",
46
+ "repository": {
47
+ "type": "git",
48
+ "url": "git+https://github.com/Yuuyuko-uu/dsh-fish-home.git"
49
+ },
50
+ "homepage": "https://github.com/Yuuyuko-uu/dsh-fish-home#readme",
51
+ "bugs": {
52
+ "url": "https://github.com/Yuuyuko-uu/dsh-fish-home/issues"
53
+ },
54
+ "publishConfig": {
55
+ "access": "public",
56
+ "registry": "https://registry.npmjs.org/"
57
+ },
58
+ "keywords": [
59
+ "deepseek-harness",
60
+ "dsh-plugin",
61
+ "three-js",
62
+ "room"
63
+ ]
64
+ }