dsh-fish-home 0.1.0 → 0.1.2

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,3 +1,23 @@
1
+ ## 0.1.2 — 2026-11-21
2
+
3
+ - 农活工具改成 `batch` / `list` 两个入口:同一轮可以一次提交多种作物的出售、买种和播种,重复请求复用原回执,每轮最多执行两批,避免模型逐格、逐品种循环调用。
4
+ - 鱼鱼窝设置增加「显示我的小菜园」,只控制庭院工具栏的显示,不影响地块、池塘或自动照料。
5
+ - 悬停提示增加命中缓冲,聊天气泡加宽并放大,长句更容易阅读。
6
+ - 修复没有星汐或文本日记时自动把更新当天当成相伴起始日的问题,保留房间存档天数作为兜底。
7
+ - 修复「检查更新」的路由重复拼了一段路径、点了没反应的问题。
8
+ - 保留本地更新脚本的存档备份、回滚和自定义配置保护逻辑。
9
+
10
+ ## 0.1.1 — 2026-11-20
11
+
12
+ - 回忆簿支持配置 .md / .txt 文件或文件夹;没有星汐插件时可用文本日记和存档起始日计算相伴天数。
13
+ - 默认关闭每轮 runtime-context,改为状态真正变化时通知绑定会话;设置页增加用量提示和开关。
14
+ - 画图工具支持 DSH 图片附件回传,也支持 reference 参考图走图生图接口。
15
+ - 放大聊天气泡和悬停提示的可停留区域;批量农活工具明确一次完成,减少重复工具调用。
16
+ - 旧版配置升级时关闭逐轮 runtime-context,并卸载已挂载的旧上下文,避免每次工具回合重复计入输入。
17
+ - 农活工具为同一轮内的相同批量请求去重;新增一次调用完成同类收获、按许可补买种子和补种。
18
+ - 回复明确说自己要去房间或坐下时,本地房间跟随执行一次;工具已安排移动/活动时不重复驱动。
19
+ - 纯净房间包提供安全更新脚本:先备份旧运行文件,只替换程序与 dist,失败时自动恢复,存档和根目录配置保留。
20
+
1
21
  ## 0.1.0 — 2026-11-19
2
22
 
3
23
  - 内置鱼鱼窝运行版,支持从 DSH 侧栏启动和关闭,首次启动自动建立独立存档并发现绑定会话。
package/README.md CHANGED
@@ -78,6 +78,7 @@
78
78
  - **卡册**。fish_home_card 按卡名或 ID 一次看一张图,抽卡和兑换只返回文字。fish_home_draw 加上 op=exchange 可换金币、星辉或指定卡。金币兑换数量填消耗的星尘,星辉兑换数量填要得到的星辉。
79
79
 
80
80
  - **田地布局**。fish_home_farm 的 list 使用 scope=layout 查看菜畦按 3×3 分组的作物。加 bed=0、1 或 2 可看该菜畦每个格子。
81
+ - **批量收种**。一次说清作物,用 `op=replant,item=...` 会批量收成熟的同类作物并用背包种子补种;明确允许花金币时再加 `buyMissing=true`,整套流程只需一次工具调用。
81
82
  - **集市**。商店里的「集市行情」和 fish_home 的 market、price 共用售价。每天北京时间零点更新,明日预告也可提前查询。price 可按 kind 或 item 筛选。
82
83
 
83
84
  ## 画架
@@ -127,13 +128,17 @@ dsh plugin --profile <你的 profile> add dsh-fish-home
127
128
 
128
129
  Windows 就是 `C:\Users\<你>\.dsh\fish-home-room\`,打开里面要能直接看到 `app-server.js`(别再套一层文件夹)。
129
130
 
131
+ 已有鱼鱼窝要更新时,先用房间右上角的退出按钮关闭后台,再双击**旧房间目录**里的 `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 重新打开鱼鱼窝即可。
132
+
130
133
  想放别处,设环境变量 `FISH_ROOM_DIR` 指向那个目录。
131
134
 
132
135
  **③ 重启一次 DSH**
133
136
 
134
137
  重启完绑定会话,再从侧栏打开。电脑上需要 Node.js 22.13 或更新版本。房间默认在本机 `5178` 端口,首次启动时在 `~/.dsh/fish-home-data` 建立空存档,插件更新时会继续用这份。
135
138
 
136
- 内置房间使用原版蓝色大肥鱼模型和配套动作。模型制作:水原镜,MMD 转换与绑定:耶栗Yaki。模型的署名和原始使用规约随房间本体一起下发(房间目录 `dist/models/dayu-mmd/` 里的 `使用规约.txt`,以及房间根下的 `MODEL-CREDITS.md`),请一并保留。
139
+ 内置房间使用原版蓝色大肥鱼模型和配套动作。
140
+
141
+ 回忆簿可在 DSH 设置里的「上下文与回忆」填写纯文本记忆路径、日记路径和相伴起始日;逐轮 runtime-context 默认关闭,需要时可按需查询现场,天气、成熟与生活里程碑、消费和场景事件也能分别控制是否通知绑定会话。模型制作:水原镜,MMD 转换与绑定:耶栗Yaki。模型的署名和原始使用规约随房间本体一起下发(房间目录 `dist/models/dayu-mmd/` 里的 `使用规约.txt` 和 `MODEL-CREDITS.md`),请一并保留。
137
142
 
138
143
  卡包大部分立绘来源于 B站 UP 主 **ZipZipPipe**,版权归原作者,随游戏一起分发、未作修改。
139
144
 
@@ -0,0 +1,60 @@
1
+ // 解析她在自然回复里已经明确说出的身体意图。
2
+ // 这是工具调用漏掉时的本地兜底,不把解析结果写回会话,也不生成可见命令。
3
+
4
+ const DESTINATIONS = [
5
+ ['garden', /(?:庭院|院子|院里|外面|院外)/],
6
+ ['pond', /(?:池塘|鱼塘|池边)/],
7
+ ['field', /(?:菜田|花田|田地|菜园|田里)/],
8
+ ['kitchen', /厨房/],
9
+ ['bathroom', /(?:洗漱区|卫生间|浴室)/],
10
+ ['bedroom', /卧室/],
11
+ ['living', /客厅/],
12
+ ['study', /(?:书房|书桌)/],
13
+ ['studio', /(?:画画区|画架)/],
14
+ ['observatory', /(?:观星区|望远镜)/],
15
+ ['indoor', /(?:房间|屋里|屋内|室内|家里)/],
16
+ ]
17
+
18
+ const SEATS = [
19
+ ['seat-extra-beanbag', /(?:懒人沙发|豆袋|软软的沙发)/],
20
+ ['living-sofa', /沙发/],
21
+ ['courtyard-swing', /秋千/],
22
+ ['courtyard-picnic', /野餐垫|野餐/],
23
+ ['courtyard-lounger', /躺椅/],
24
+ ['courtyard-stool-1', /石凳/],
25
+ ['seat-WindowSeat', /藤椅/],
26
+ ['study-reading-chair', /(?:椅子|椅)/],
27
+ ]
28
+
29
+ // 只收可直接执行的眼下动作。转述、猜测、回忆和疑问保持为聊天。
30
+ const REJECT = /(?:不要|别|不想|不去|不回|不会|不能|没(?:有)?|不是|无需|不用|如果|要不要|建议|请你|你可以|你应该|让你|昨天|刚才|以前|上次|等会|待会|明天|以后|想象|梦里|假装|只是说|可以吗|好吗)/
31
+ const LEAD = /^(?:[((] ?)?(?:那我|我(?:已经|正在|现在|这就|先|正|就)?|那就|这就|现在就|马上|先)?\s*/
32
+ const WALK = /^(?:回(?:到|去)?|去|走(?:到|去)|前往|进(?:到|入)?)\s*/
33
+ const SIT = /^(?:去)?(?:在|到)?(?:坐(?:到|在|上)?|躺(?:在|到|上)?|窝在|荡)\s*/
34
+ const SIT_TAIL = /^(?:的)?(?:上|里|边|旁|中)?(?:坐|躺|窝|歇|休息|待着)/
35
+
36
+ export function 识别身体意图(text) {
37
+ const sentences = String(text || '').match(/[^。!?!?;;\n]+[。!?!?;;]?/g) || []
38
+ for (const raw of sentences) {
39
+ if (/[??“”「」『』"`]/.test(raw)) continue
40
+ const sentence = raw.trim().replace(/[。!?!?;;]$/, '')
41
+ const clause = sentence.split(/[,,、::]/,1)[0].trim()
42
+ if (!clause || REJECT.test(clause)) continue
43
+ const body = clause.replace(LEAD, '')
44
+ const action = SIT.exec(body)
45
+ const seatText = action ? body.slice(action[0].length) : body.replace(/^(?:去|在)/, '')
46
+ for (const [id, pattern] of SEATS) {
47
+ const seat = pattern.exec(seatText)
48
+ if (seat?.index === 0 && (action || SIT_TAIL.test(seatText.slice(seat[0].length)))) {
49
+ return { key: `sit:${id}`, command: 'sit', args: { id }, matched: sentence }
50
+ }
51
+ }
52
+ const movement = WALK.exec(body)
53
+ if (!movement) continue
54
+ const target = body.slice(movement[0].length)
55
+ for (const [dest, pattern] of DESTINATIONS) {
56
+ if (pattern.exec(target)?.index === 0) return { key: `move:${dest}`, command: 'moveTo', args: { dest }, matched: sentence }
57
+ }
58
+ }
59
+ return null
60
+ }
package/lib/client.js CHANGED
@@ -391,6 +391,36 @@ window.__ModuleLoader__.load({
391
391
  onChange: (e) => 存({ 睡着不理: e.target.checked }),
392
392
  }), '关掉之后睡着也照常回话(逃生门,默认开)')))
393
393
 
394
+ , 卡('上下文与回忆', '默认不把现场数据塞进每一轮 runtime-context;需要时让她调用 fish_home 查询。',
395
+ h('div', null,
396
+ 行('状态变化时通知', h('input', {
397
+ type: 'checkbox', checked: 态.状态变化通知 !== false,
398
+ onChange: (e) => 存({ 状态变化通知: e.target.checked }),
399
+ }), '天气真正变化时,单独告诉绑定会话。'),
400
+ 行('每轮注入现场', h('input', {
401
+ type: 'checkbox', checked: 态.每轮注入现场 === true,
402
+ onChange: (e) => 存({ 每轮注入现场: e.target.checked }),
403
+ }), '打开后每轮都会增加一段 runtime-context,可能增加用量。'),
404
+ ...[['milestone','成熟与生活里程碑'],['wallet','金币与商店变动'],['scene','拎起、秋千等场景互动']].map(([key,label]) =>
405
+ 行(label, h('input', {
406
+ type: 'checkbox', checked: 态.主动生活通知?.[key] !== false,
407
+ onChange: (e) => 存({ 主动生活通知: { ...(态.主动生活通知 || {}), [key]: e.target.checked } }),
408
+ }), '这类事件会单独发给绑定会话,可能触发一次模型回复。')),
409
+ 行('记忆文本路径', h('input', {
410
+ style: S.input, value: 态.文本记忆路径 || '', placeholder: 'D:\\鱼鱼\\memory.md 或文件夹',
411
+ onChange: (e) => 设态((x) => ({ ...x, 文本记忆路径: e.target.value })),
412
+ onBlur: (e) => 存({ 文本记忆路径: e.target.value.trim() }),
413
+ }), '支持 .md / .txt 文件或文件夹;段落会显示为“记住的事”。'),
414
+ 行('日记文本路径', h('input', {
415
+ style: S.input, value: 态.文本日记路径 || '', placeholder: 'D:\\鱼鱼\\日记',
416
+ onChange: (e) => 设态((x) => ({ ...x, 文本日记路径: e.target.value })),
417
+ onBlur: (e) => 存({ 文本日记路径: e.target.value.trim() }),
418
+ }), '支持按日期命名的 .md / .txt 文件或文件夹;没有星汐时也能作为相伴天数来源。'),
419
+ 行('相伴起始日', h('input', {
420
+ style: S.input, type: 'date', value: 态.相伴起始日 || '',
421
+ onChange: (e) => 存({ 相伴起始日: e.target.value }),
422
+ }), '没有可读日记时使用这个日期计算存档天数。')))
423
+
394
424
  , 卡('接哪间会话', '房间里说的话会送进这一间;她回的话也顺着这条路回来',
395
425
  h('div', null,
396
426
  行('会话', h('select', {
@@ -471,6 +501,7 @@ window.__ModuleLoader__.load({
471
501
  ? '装好了' + (本体.版本 ? ':鱼鱼窝 ' + 本体.版本 : '') + '(' + 本体.目录 + ')'
472
502
  : '还没装' + (本体.版本 ? '(看到版本 ' + 本体.版本 + ',但没找到 app-server.js)' : '') + ' —— 下下来解压到 ' + 本体.目录)
473
503
  : '正在看…'),
504
+ 本体?.已装 ? h('div', { style:S.hint }, '更新房间:退出后台,再运行房间目录里的 update-fish-home.cmd 选择新版 ZIP。旧版没有脚本时,从新 ZIP 只复制两个 update-fish-home 文件到旧目录。存档会保留。') : null,
474
505
  h('div', { style: { display: 'flex', gap: 8, marginTop: 8, flexWrap: 'wrap' } },
475
506
  本体 && 本体.下载页
476
507
  ? h('a', { href: 本体.下载页, target: '_blank', rel: 'noopener', style: { ...S.btn, textDecoration: 'none', display: 'inline-block' } }, 本体.已装 ? '去 Releases 看看' : '去下载')
package/lib/host.js CHANGED
@@ -21,6 +21,7 @@ import { setTimeout as 睡 } from 'node:timers/promises'
21
21
  import { randomUUID, timingSafeEqual } from 'node:crypto'
22
22
  import { 读星汐, 收回忆, 筛回忆, 收天数 } from './memory.mjs'
23
23
  import { 鱼鱼窝图标 } from './icon.mjs'
24
+ import { 识别身体意图 } from './body-intent.mjs'
24
25
 
25
26
  export const name = 'fish-home'
26
27
  // 这几个都是宿主必备的服务;写进 inject 才能直接 ctx.agents 这么用
@@ -92,12 +93,41 @@ const 默认配置 = {
92
93
  待推设置: [],
93
94
  // 睡着就不理人:关掉 = pre-step 完全放行(最后一道逃生门)
94
95
  睡着不理: true,
96
+ // 动态现场默认不塞进每一轮 runtime-context;需要时用 fish_home 查明细。
97
+ 每轮注入现场: false,
98
+ 上下文策略版本: 3,
99
+ 状态变化通知: true,
100
+ 主动生活通知: { milestone: true, wallet: true, scene: true },
101
+ 文本记忆路径: '',
102
+ 文本日记路径: '',
103
+ 相伴起始日: '',
95
104
  }
96
105
 
97
106
  function 读配置() {
98
107
  let 存 = {}
99
108
  try { 存 = JSON.parse(fs.readFileSync(配置路, 'utf8')) } catch (e) { 存 = {} }
100
109
  const 合 = { ...默认配置, ...(存 && typeof 存 === 'object' ? 存 : {}) }
110
+ // 0.1.0 曾把现场上下文默认塞进每一轮。升级后强制迁移一次,
111
+ // 否则旧的 fish-room.json 会把新默认值重新覆盖回 true。
112
+ const 上下文迁移 = Number(存?.上下文策略版本 || 0)
113
+ if (上下文迁移 < 2) {
114
+ 合.每轮注入现场 = false
115
+ }
116
+ if (上下文迁移 < 3) {
117
+ // 0.1.1 早期版本在没有星汐日记时把「今天」误写成相伴起始日,
118
+ // 让存档天数兜底看起来像从更新当天重新开始。只有这个自动生成的
119
+ // 近两天日期才清掉;用户在设置里填过的旧日期保留。
120
+ const 今天 = new Intl.DateTimeFormat('sv-SE', { timeZone: 'Asia/Shanghai' }).format(new Date())
121
+ const 旧日 = String(存?.相伴起始日 || '')
122
+ const 今天毫秒 = Date.parse(今天 + 'T00:00:00Z')
123
+ const 旧日毫秒 = Date.parse(旧日 + 'T00:00:00Z')
124
+ const 近两天自动日 = /^\d{4}-\d{2}-\d{2}$/.test(旧日) && Number.isFinite(旧日毫秒) && Math.abs(今天毫秒 - 旧日毫秒) <= 2 * 86400000
125
+ if (近两天自动日 && !String(存?.文本日记路径 || '').trim() && !String(存?.文本记忆路径 || '').trim()) 合.相伴起始日 = ''
126
+ }
127
+ if (上下文迁移 < 3) {
128
+ 合.上下文策略版本 = 3
129
+ try { fs.mkdirSync(家, { recursive: true }); fs.writeFileSync(配置路, JSON.stringify(合, null, 2), 'utf8') } catch {}
130
+ }
101
131
  合.开 = 合.开 !== false
102
132
  合.开机自启 = 合.开机自启 === true
103
133
  合.转发主动开口 = 合.转发主动开口 !== false
@@ -108,6 +138,15 @@ function 读配置() {
108
138
  : []
109
139
  delete 合.上次醒来招呼
110
140
  合.睡着不理 = 合.睡着不理 !== false
141
+ 合.每轮注入现场 = 合.每轮注入现场 === true
142
+ 合.上下文策略版本 = 3
143
+ 合.状态变化通知 = 合.状态变化通知 !== false
144
+ 合.主动生活通知 = Object.fromEntries(['milestone','wallet','scene'].map(key=>[key,合.主动生活通知?.[key]!==false]))
145
+ 合.文本记忆路径 = String(合.文本记忆路径 || '').trim()
146
+ 合.文本日记路径 = String(合.文本日记路径 || '').trim()
147
+ 合.相伴起始日 = /^\d{4}-\d{2}-\d{2}$/.test(String(合.相伴起始日 || '')) ? String(合.相伴起始日) : ''
148
+ // 没有来源时保持空白,让房间自己的存档天数作为兜底。
149
+
111
150
  合.会话 = String(合.会话 || '').trim()
112
151
  合.令牌 = String(合.令牌 || '').trim()
113
152
  const 秒 = Number(合.心跳秒)
@@ -719,9 +758,28 @@ function 起来(ctx, 配置参数 = {}) {
719
758
  const 已请求画画 = new Map()
720
759
  let 最近说过的 = ''
721
760
  let 最近说话时 = 0
761
+ let 上次状态通知 = { key: '', at: 0 }
722
762
  // 房间里的钟:几点、白天夜里、天气(房间那边每隔几秒报一次)
723
763
  let 房间环境 = null
724
764
  let 事件计数 = 0
765
+ let 上次身体意图 = { key: '', at: 0 }
766
+
767
+ async function 跟随身体意图(text, sid) {
768
+ const intent = 识别身体意图(text)
769
+ if (!intent || !配置.开 || !房间地址 || sid!==目标会话()) return
770
+ const at = Date.now()
771
+ if (intent.key === 上次身体意图.key && at - 上次身体意图.at < 10000) return
772
+ 上次身体意图 = { key: intent.key, at }
773
+ try {
774
+ const result = await roomRequest('/api/command', {
775
+ name: intent.command, args: intent.args, wait: true,
776
+ }, 30000)
777
+ if (!result?.ok) 记一笔('身体跟随未执行:' + String(result?.error || result?.说 || '房间没有接受动作'))
778
+ } catch (error) {
779
+ // 失败只记本地日志,不再把解释发回会话,避免形成“她说话→插件再发命令”的回声。
780
+ 记一笔('身体跟随跳过:' + String(error?.message || error))
781
+ }
782
+ }
725
783
 
726
784
  function 收下环境(来源) {
727
785
  if (!来源 || typeof 来源 !== 'object') return
@@ -789,6 +847,32 @@ function 起来(ctx, 配置参数 = {}) {
789
847
  return 正文 && '【鱼鱼窝】' + 正文
790
848
  }
791
849
 
850
+ function 状态通知文本(previous, next, oldWeather = '') {
851
+ const lines = []
852
+ const after = next?.snapshot || {}
853
+ const newWeather = String(after.weather || 房间环境?.weather || '')
854
+ if (oldWeather && newWeather && oldWeather !== newWeather) {
855
+ const labels = { clear: '晴天', cloudy: '阴天', rain: '下雨', snow: '下雪', storm: '雷雨' }
856
+ lines.push('窗外天气变成' + (labels[newWeather] || newWeather) + '。')
857
+ }
858
+ return lines
859
+ }
860
+
861
+ function 推送状态变化(previous, next, oldWeather = '') {
862
+ if (!配置.开 || !配置.状态变化通知 || !previous?.snapshot || !next?.snapshot || !目标会话()) return
863
+ const agent = 找agent(目标会话())
864
+ if (!agent || typeof agent.followup !== 'function') return
865
+ const lines = 状态通知文本(previous, next, oldWeather)
866
+ if (!lines.length) return
867
+ const key = lines.join('|')
868
+ if (key === 上次状态通知.key && Date.now() - 上次状态通知.at < 30000) return
869
+ 上次状态通知 = { key, at: Date.now() }
870
+ void agent.followup({
871
+ id: randomUUID(), role: 'user', source: { kind: 'fish-home-state' },
872
+ content: [{ type: 'text', text: '【鱼鱼窝状态更新】' + lines.join(' ') }],
873
+ }).catch(() => {})
874
+ }
875
+
792
876
  const 地点名字={bedroom:'卧室',living:'客厅',kitchen:'厨房',bathroom:'洗漱区',study:'书房',studio:'画画区',garden:'庭院',observatory:'观星区'};
793
877
  const 实际地点 = {...地点名字, field:'菜田', pond:'池塘边', swing:'秋千旁', indoor:'屋内'};
794
878
  const 实际活动 = {idle:'闲着', walk:'走路', sit:'坐着', sleep:'睡觉', nap:'小憩', cook:'料理', clean:'整理', paint:'画画', music:'听音乐', water:'浇水', wash:'洗手', brush:'洗漱', exercise:'锻炼', stargaze:'观星', stretch:'伸懒腰', plant:'播种', harvest:'收菜', stock:'放鱼苗', pickup:'被拎起来了'};
@@ -822,6 +906,7 @@ function 起来(ctx, 配置参数 = {}) {
822
906
  type: 'object',
823
907
  properties: {
824
908
  prompt: { type: 'string', description: '图像内容' },
909
+ reference: { type: 'string', description: '可选参考图:本机图片路径、http(s) 图片地址或 data:image/...;填写后使用图生图' },
825
910
  },
826
911
  required: ['prompt'],
827
912
  additionalProperties: false,
@@ -829,10 +914,13 @@ function 起来(ctx, 配置参数 = {}) {
829
914
  output: {
830
915
  schema: {
831
916
  type: 'object',
832
- properties: { ok: { type: 'boolean' }, 说: { type: 'string' } },
917
+ properties: { ok: { type: 'boolean' }, 说: { type: 'string' }, attachment: { type: 'object', additionalProperties: true } },
833
918
  required: ['ok'],
834
919
  },
835
- render: (_args, 结果) => [{ type: 'text', text: String((结果 && 结果.说) || '') }],
920
+ render: (_args, 结果) => [
921
+ { type: 'text', text: String((结果 && 结果.说) || '') },
922
+ ...(结果?.attachment ? [{ type: 'image', attachment: 结果.attachment }] : []),
923
+ ],
836
924
  },
837
925
  async execute(args = {}) {
838
926
  const 话 = String((args && args.prompt) || '').trim()
@@ -840,11 +928,20 @@ function 起来(ctx, 配置参数 = {}) {
840
928
  const 设置 = await 读房间设置(5000, 房间地址 || 默认房间地址)
841
929
  if ((设置.画图 ?? 配置.画图) === false) return {ok:false, 说:'鱼鱼窝的画图开关关着。'}
842
930
  if (!连接们.size) return {ok:false, 说:'鱼鱼窝后台还没连上,画架暂时收不到画。'}
843
- const 结果 = await 画一张(话)
931
+ const 结果 = await 画一张(话, args.reference)
844
932
  if (!结果.ok) return { ok: false, 说: 结果.说 }
845
933
  // 图太大,不进历史缓冲,只发给现在连着的
846
934
  发事件('paint.image', { b64: 结果.b64, mime: 结果.mime, prompt: 话.slice(0, 200) }, true)
847
- return {ok:true, 说:连接们.size ? '画好了,已发往鱼鱼窝的画架和画册。' : '画好了,但鱼鱼窝刚刚断开,画作没有送到。'}
935
+ const out = { ok:true, 说:连接们.size ? '画好了,已发往鱼鱼窝的画架和画册。' : '画好了,但鱼鱼窝刚刚断开,画作没有送到。' }
936
+ const attachments = imageContext?.get('attachments')
937
+ if (attachments?.saveImage) {
938
+ try {
939
+ const data = Buffer.from(结果.b64, 'base64')
940
+ const attachment = await attachments.saveImage({ data, mediaType: 结果.mime || 'image/png', name: '鱼鱼窝画作.png' })
941
+ out.attachment = attachment
942
+ } catch (error) {}
943
+ }
944
+ return out
848
945
  },
849
946
  }
850
947
  }
@@ -1045,7 +1142,7 @@ function 起来(ctx, 配置参数 = {}) {
1045
1142
  const result=await response.json();
1046
1143
  if(!response.ok)return {ok:false,说:result.error||'活动暂不可用。'};
1047
1144
  const 说=id ? '已安排:'+(result.activity?.label||id)+'。' : 活动简报(result.activity,result.observation,result.presence);
1048
- if(id)return {ok:true,说,activity:result.activity};
1145
+ if(id){标记本轮身体工具();return {ok:true,说,activity:result.activity};}
1049
1146
  return {ok:true,说,activity:result.activity,observation:result.observation,options:result.options};
1050
1147
  }catch{return {ok:false,说:'鱼鱼窝暂未连通。'};}
1051
1148
  },
@@ -1308,6 +1405,7 @@ function 起来(ctx, 配置参数 = {}) {
1308
1405
  }
1309
1406
  if(!result.presence?.visible||result.presence.place!==dest)return {ok:false,说:beforeMove+'页面还没有确认到达。刷新鱼鱼窝后再试。'};
1310
1407
  const location=实际地点[dest]||raw;
1408
+ 标记本轮身体工具()
1311
1409
  return {ok:true,说:beforeMove+'已到达「'+location+'」。'+活动简报(null,null,result.presence)};
1312
1410
  } catch (error) { return {ok:false,说:beforeMove+'没走成:'+error.message}; }
1313
1411
  },
@@ -1362,30 +1460,113 @@ function 起来(ctx, 配置参数 = {}) {
1362
1460
  return lines.join(' ');
1363
1461
  }
1364
1462
 
1463
+ const 每轮农活上限 = 2;
1464
+
1365
1465
  function 农活工具() {
1466
+ const operations = ['plant','water','harvest','replant','buy','sell','stock','feed','catch'];
1467
+ const actionFields = {
1468
+ op: {type:'string',enum:operations},
1469
+ item: {type:'string',description:'品种 ID 或中文名。'},
1470
+ count: {type:'integer',minimum:1,maximum:999,description:'数量。收获、浇水、补种和捞鱼默认全部符合条件的。'},
1471
+ kind: {type:'string',enum:['seed','fish','crop','giant'],description:'仅用于买卖。'},
1472
+ zone: {type:'string',enum:['vegetable','flower'],description:'仅用于浇水和收获。播种按品种自动选菜田或花田。'},
1473
+ bed: {type:'integer',minimum:0,maximum:2,description:'仅用于指定 0 到 2 号菜畦播种。'},
1474
+ buyMissing: {type:'boolean',description:'仅用于 replant。用户允许花金币补买种子时才填 true。'},
1475
+ };
1476
+ let pending = Promise.resolve();
1477
+
1478
+ async function plan(args, catalog) {
1479
+ const {op, zone, bed, kind} = args;
1480
+ const item = string(args.item);
1481
+ const count = args.count ?? (['harvest','water','replant'].includes(op) ? 65 : op==='catch' ? 8 : 1);
1482
+ if (!operations.includes(op)) throw new Error('请选择有效的农活。');
1483
+ if (args.plotId!==undefined) throw new Error('使用品种和数量批量操作,不需要地块编号。');
1484
+ if (!Number.isSafeInteger(count) || count<1 || count>999) throw new Error('数量必须是 1 到 999 的整数。');
1485
+ if (['plant','water','harvest','replant'].includes(op) && count>65) throw new Error('田地操作一次最多 65 格。');
1486
+ if (['stock','catch'].includes(op) && count>8) throw new Error('池塘操作一次最多 8 条。');
1487
+ if (zone!==undefined && !['vegetable','flower'].includes(zone)) throw new Error('请选择菜田或花田。');
1488
+ if (bed!==undefined && ![0,1,2].includes(bed)) throw new Error('菜畦编号为 0 到 2。');
1489
+ if (op==='feed') return {op, route:'feed', payload:{}};
1490
+ if (['water','harvest'].includes(op) && !item) return {op, route:op+'-batch', payload:{count,zone}};
1491
+ if (op==='catch' && !item) return {op, route:'catch-batch', payload:{count}};
1492
+
1493
+ const data = await catalog();
1494
+ const seeds = data.商店 || [], fish = data.鱼 || [], giants = data.giantItems || [];
1495
+ const match = list => list.find(x => x.id===item || x.name===item);
1496
+ if (op==='buy' || op==='sell') {
1497
+ const goods = op==='buy' && kind==='fish' ? fish : op==='buy' && kind==='seed' ? seeds : [...seeds,...fish,...(op==='sell'?giants:[])];
1498
+ const found = match(goods);
1499
+ if (!found) throw new Error('找不到商品 '+item+'。');
1500
+ const category = fish.includes(found) ? 'fish' : giants.includes(found) ? 'giant' : op==='buy' ? 'seed' : 'crop';
1501
+ if (kind && kind!==category) throw new Error(found.name+'的商品分类不符。');
1502
+ if (op==='buy' && count>99) throw new Error('一次可以买 1 到 99 份。');
1503
+ return {op, route:op, name:found.name, payload:{kind:category,id:found.id,数量:count}};
1504
+ }
1505
+ if (op==='stock' || op==='catch') {
1506
+ const species = match(fish);
1507
+ if (!species) throw new Error('请指定有效的鱼种。');
1508
+ return {op, route:op+'-batch', name:species.name, payload:{item:species.id,count}};
1509
+ }
1510
+ const crop = match(seeds);
1511
+ if (!crop) throw new Error('找不到作物 '+item+'。');
1512
+ if (op==='replant') {
1513
+ if (zone!==undefined || bed!==undefined) throw new Error('收后补种会用原地块,不用指定田地。');
1514
+ return {op, route:op, name:crop.name, payload:{item:crop.id,count,buyMissing:args.buyMissing===true}};
1515
+ }
1516
+ const payload = op==='plant' ? {cropId:crop.id,count,bed} : {item:crop.id,count,zone};
1517
+ return {op, route:op+'-batch', name:crop.name, payload};
1518
+ }
1519
+
1520
+ async function executeAction(action, write) {
1521
+ const {op, route, payload, name} = action;
1522
+ if (op==='replant') {
1523
+ const {item,count,buyMissing} = payload;
1524
+ const harvested = await write('harvest-batch',{item,count});
1525
+ const plots = harvested.plotIds?.length || 0;
1526
+ let wallet = harvested.wallet;
1527
+ const lines = [harvested.say];
1528
+ try {
1529
+ const missing = Math.max(0,plots-(wallet.seeds?.[item]||0));
1530
+ if (buyMissing && missing) {
1531
+ const bought = await write('buy',{kind:'seed',id:item,数量:missing});
1532
+ wallet = bought.wallet;
1533
+ lines.push(`补买了 ${bought.买到.n} 份种子,花费 ${bought.花了} 金币。`);
1534
+ }
1535
+ if (plots && (wallet.seeds?.[item]||0)>0) {
1536
+ const planted = await write('plant-batch',{cropId:item,count:plots,plotIds:harvested.plotIds});
1537
+ wallet = planted.wallet;
1538
+ lines.push(planted.say);
1539
+ if (planted.count<plots) lines.push(`还有 ${plots-planted.count} 格没有补种。`);
1540
+ } else if (plots) lines.push('背包没有种子,已收获,未补种。');
1541
+ return {ok:true,说:lines.join(' '),wallet};
1542
+ } catch (error) {
1543
+ lines.push('已收获,补种未全部完成:'+error.message);
1544
+ return {ok:false,说:lines.join(' '),wallet};
1545
+ }
1546
+ }
1547
+ const result = await write(route,payload);
1548
+ let 说 = result.say;
1549
+ if (op==='buy') 说 = `买了 ${result.买到.n} 份${name},花费 ${result.花了} 金币。`;
1550
+ if (op==='sell') 说 = `卖了 ${result.卖出.n} 份${name},入账 ${result.得了} 金币。`;
1551
+ if (op==='stock' || op==='catch') 说 = 鱼塘回执(result,op,name);
1552
+ return {ok:true,说,wallet:result.wallet};
1553
+ }
1554
+
1366
1555
  return {
1367
1556
  name:'fish_home_farm',
1368
- description:'批量种田、养鱼与买卖。种 10 格萝卜只调用一次 plant,传 item:萝卜 和 count:10。water 或 harvest 一次处理全部符合条件的地块,可用 zone、item、count 筛选。stock 或 catch 一次处理指定数量的鱼。list 默认看摘要,scope:layout 看六个 3×3 区,指定 bed 可以看这个菜畦每格的作物。',
1557
+ description:'种田、养鱼和买卖。执行任务用一次 batch,把所有品种及步骤按顺序放进 actions。先卖、再买种、再播种都放同一批。收获后原地回种用 replant。回执已含结果和余额,完成后直接回复。只查询用 list,无需在操作前后例行查询。每轮最多提交两批。',
1369
1558
  parameters:{type:'object',properties:{
1370
- op:{type:'string',enum:['list','plant','water','harvest','buy','sell','stock','feed','catch']},
1371
- item:{type:'string',description:'品种 ID 或中文名。'},
1372
- kind:{type:'string',enum:['seed','fish','crop','giant'],description:'商品分类,仅用于买卖。'},
1373
- zone:{type:'string',enum:['vegetable','flower'],description:'批量浇水或收获的分区,省略则处理两区。'},
1374
- bed:{type:'integer',minimum:0,maximum:2,description:'指定 0 到 2 号菜畦,适用于播种,或用 list+layout 看逐格布局。'},
1375
- count:{type:'integer',minimum:1,maximum:999,description:'数量。播种最多 65 格;浇水和收获默认全部;放养和捞鱼最多 8 条,默认 1。'},
1376
- scope:{type:'string',enum:['farm','pond','layout','all'],description:'list 的查询范围,layout 查看真实 3×3 布局。'},
1559
+ op:{type:'string',enum:['batch','list']},
1560
+ actions:{type:'array',minItems:1,maxItems:16,items:{type:'object',properties:actionFields,required:['op'],additionalProperties:false},description:'batch 的完整操作列表,按顺序执行。多个品种各放一项,数量填 count。'},
1561
+ scope:{type:'string',enum:['farm','pond','layout','all'],description:'list 的查询范围。'},
1562
+ bed:{type:'integer',minimum:0,maximum:2,description:'list + layout 时展开指定菜畦。'},
1377
1563
  },required:['op'],additionalProperties:false},
1378
1564
  output:textOutput,
1379
1565
  async execute(args={}, exec) {
1380
- const {op, zone, bed} = args;
1381
- const item=string(args.item);
1382
- const count=args.count??(['harvest','water'].includes(op)?65:1);
1383
- const operations=['list','plant','water','harvest','buy','sell','stock','feed','catch'];
1566
+ const {op,bed} = args;
1384
1567
  const request = (route,params) => roomRequest('/api/farm'+route,params,8000,exec?.signal);
1385
- const mutate = (kind,payload) => request('/'+kind,{...payload,requestId:randomUUID(),actor:'dayu'});
1568
+ const write = (route,payload) => request('/'+route,{...payload,requestId:randomUUID(),actor:'dayu'});
1386
1569
  try {
1387
- if(!operations.includes(op))throw new Error('需要有效的 op。');
1388
- if(!Number.isSafeInteger(count)||count<1||count>999)throw new Error('数量必须是正整数。');
1389
1570
  if(op==='list') {
1390
1571
  if(args.scope!=='layout')return {ok:true,说:farmSummary(await request(''),args.scope)};
1391
1572
  if(bed!==undefined&&![0,1,2].includes(bed))throw new Error('菜畦编号为 0 到 2。');
@@ -1403,42 +1584,56 @@ function 起来(ctx, 配置参数 = {}) {
1403
1584
  }
1404
1585
  return {ok:true,说:lines.join('\n\n')};
1405
1586
  }
1406
- if(op==='feed')return {ok:true,说:(await mutate('feed',{})).say};
1407
- if(args.plotId!==undefined)throw new Error('播种、浇水和收获已改成批量。请用 item、zone 或 count,不需要地块编号。');
1408
- if(['plant','water','harvest'].includes(op)&&count>65)throw new Error('田地操作一次最多 65 格。');
1409
- if(['stock','catch'].includes(op)&&count>8)throw new Error('池塘操作一次最多 8 条。');
1410
- if(['water','harvest'].includes(op)&&!item){
1411
- return {ok:true,说:(await mutate(op+'-batch',{count,zone})).say};
1412
- }
1413
- if(op==='catch'&&!item&&args.count!==undefined){
1414
- const result=await mutate('catch-batch',{count});
1415
- return {ok:true,说:鱼塘回执(result,'catch')};
1416
- }
1417
- const data=await request('');
1418
- const seeds=data.商店||[], fish=data.鱼||[], giants=data.giantItems||[];
1419
- const match=catalog=>catalog.find(x=>x.id===item||x.name===item);
1420
- if(op==='buy'||op==='sell'){
1421
- const found=match(op==='buy'?(args.kind==='fish'?fish:args.kind==='seed'?seeds:[...seeds,...fish]):[...seeds,...fish,...giants]);
1422
- if(!found)throw new Error('找不到这个商品。用 fish_home 的 price 查看商店。');
1423
- const kind=args.kind||(fish.includes(found)?'fish':giants.includes(found)?'giant':op==='buy'?'seed':'crop');
1424
- if(op==='buy'&&(!['seed','fish'].includes(kind)||count>99))throw new Error('一次可以买 1 到 99 份。');
1425
- const result=await mutate(op,{kind,id:found.id,数量:count});
1426
- const summary=op==='buy'?'买了 '+count+' 份'+found.name+',花费 '+result.花了+' 金币。':'卖了 '+count+' 份'+found.name+',入账 '+result.得了+' 金币。';
1427
- return {ok:true,说:summary+'余额 '+result.wallet.coins+' 金币。'};
1428
- }
1429
- if(op==='catch'||op==='stock'){
1430
- const species=match(fish)?.id;
1431
- if(species){
1432
- const result=await mutate(op+'-batch',{item:species,count});
1433
- return {ok:true,说:鱼塘回执(result,op,match(fish)?.name)};
1587
+ // Keep accepting old single-action requests while the model learns the new schema.
1588
+ const entries = op==='batch' ? args.actions : [args];
1589
+ if (!Array.isArray(entries) || !entries.length || entries.length>16) throw new Error('请在 actions 中填写 1 到 16 项农活。');
1590
+ let catalog;
1591
+ const getCatalog = () => catalog ??= request('');
1592
+ const turn = 当前轮.get(目标会话());
1593
+ const actions = [];
1594
+ for (const [index, entry] of entries.entries()) {
1595
+ try {
1596
+ if (!entry || typeof entry!=='object' || Array.isArray(entry)) throw new Error('请填写操作对象。');
1597
+ if (op==='batch' && Object.keys(entry).some(key=>!Object.hasOwn(actionFields,key))) throw new Error('该项包含不支持的参数。');
1598
+ actions.push(await plan(entry,getCatalog));
1599
+ } catch (error) {
1600
+ throw new Error(op==='batch' ? `第 ${index+1} 项未提交:${error.message}` : error.message);
1434
1601
  }
1435
- throw new Error('请指定有效的鱼种。要捞不限品种的成鱼,可只填写数量。');
1436
1602
  }
1437
- const crop=item?match(seeds):null;
1438
- if((item||op==='plant')&&!crop)throw new Error('请指定有效的种子或作物品种。');
1439
- const payload=op==='plant'?{cropId:crop.id,count,bed}:{item:crop?.id,count,zone};
1440
- return {ok:true,说:(await mutate(op+'-batch',payload)).say};
1441
- } catch (error) { return {ok:false,说:error.message}; }
1603
+ const run = async () => {
1604
+ const progress = turn ? (turn.farmWork ??= {batches:0,receipts:new Map()}) : {batches:0,receipts:new Map()};
1605
+ const keys = actions.map(({route,payload})=>JSON.stringify([route,payload]));
1606
+ const hasNewWork = keys.some(key=>!progress.receipts.has(key));
1607
+ if (hasNewWork && progress.batches>=每轮农活上限) return {ok:false,说:'本轮已执行两次农活操作。请根据已有回执回复,剩余操作下一轮再安排。'};
1608
+ if (hasNewWork) progress.batches++;
1609
+ let lastWallet;
1610
+ const results = [];
1611
+ for (const [index, action] of actions.entries()) {
1612
+ if (exec?.signal?.aborted) break;
1613
+ const key = keys[index];
1614
+ let result = progress.receipts.get(key);
1615
+ const repeated = Boolean(result);
1616
+ if (!repeated) {
1617
+ try { result = await executeAction(action,write); }
1618
+ catch (error) { result = {ok:false,说:error.message}; }
1619
+ progress.receipts.set(key,result);
1620
+ }
1621
+ if (!repeated && result.wallet) lastWallet = result.wallet;
1622
+ const label = action.name ? action.name+':' : '';
1623
+ const receipt = repeated ? '本轮已提交,原回执:'+result.说 : result.说;
1624
+ results.push({ok:result.ok,说:op==='batch'?`${index+1}. ${label}${receipt}`:receipt});
1625
+ }
1626
+ const lines = results.map(row=>row.说);
1627
+ if (results.length<actions.length) lines.push(`已停止,还有 ${actions.length-results.length} 项未提交。`);
1628
+ if (lastWallet && (op==='batch' || ['replant','buy','sell'].includes(op))) lines.push(`余额 ${lastWallet.coins} 金币。`);
1629
+ return {ok:results.length===actions.length&&results.every(row=>row.ok),说:lines.join(op==='batch'?'\n':' ')};
1630
+ };
1631
+ const receipt = pending.then(run);
1632
+ pending = receipt.catch(()=>{});
1633
+ return await receipt;
1634
+ } catch (error) {
1635
+ return {ok:false,说:error.message};
1636
+ }
1442
1637
  },
1443
1638
  };
1444
1639
  }
@@ -1543,12 +1738,23 @@ function 起来(ctx, 配置参数 = {}) {
1543
1738
  entry.failures.add(name);
1544
1739
  }
1545
1740
  }
1546
- if (typeof agent.ctx.systemPrompt?.context==='function') {
1547
- register('fish-home context',()=>agent.ctx.systemPrompt.context({name:'fish-home',order:950,text:()=>房间那句()}));
1741
+ const contextKey='fish-home context';
1742
+ if (配置.每轮注入现场 && typeof agent.ctx.systemPrompt?.context==='function') {
1743
+ register(contextKey,()=>agent.ctx.systemPrompt.context({name:'fish-home',order:950,text:()=>房间那句()}));
1744
+ } else if (entry.off们.has(contextKey)) {
1745
+ try { entry.off们.get(contextKey)?.() } catch {}
1746
+ entry.off们.delete(contextKey)
1548
1747
  }
1549
1748
  if (typeof agent.ctx.tools?.register==='function') {
1550
1749
  for (const create of [画工具,睡眠工具,鱼鱼窝工具,日常工具,抽卡工具,卡面工具,菜谱工具,走过去工具,农活工具,看一眼工具]) {
1551
1750
  const tool = create();
1751
+ if (tool.name==='fish_home_farm' && 当前轮.get(target)?.farmWork?.batches>=每轮农活上限) {
1752
+ const off = entry.off们.get(tool.name);
1753
+ if (typeof off==='function') {
1754
+ try { off(); entry.off们.delete(tool.name); } catch {}
1755
+ }
1756
+ continue;
1757
+ }
1552
1758
  register(tool.name,()=>agent.ctx.tools.register(tool));
1553
1759
  }
1554
1760
  }
@@ -1585,6 +1791,11 @@ function 起来(ctx, 配置参数 = {}) {
1585
1791
  return 配置.会话 ? 会话键(配置.会话) : ''
1586
1792
  }
1587
1793
 
1794
+ function 标记本轮身体工具() {
1795
+ const 轮=当前轮.get(目标会话())
1796
+ if(轮)轮.身体工具=true
1797
+ }
1798
+
1588
1799
  /* ── 会话事件:DSH → 房间 ── */
1589
1800
  function 收到会话事件(session, event) {
1590
1801
  if (!配置.开) return
@@ -1596,7 +1807,9 @@ function 起来(ctx, 配置参数 = {}) {
1596
1807
 
1597
1808
  // 会话一醒就把房间时间挂上(这时候才有 agent.ctx.systemPrompt 可挂)
1598
1809
  if (event.type === 'turn/start') {
1599
- 当前轮.set(sid, { turn: event.data?.turn, replies: [], direct: false })
1810
+ const existing = 当前轮.get(sid);
1811
+ if (existing && existing.turn===event.data?.turn) return;
1812
+ 当前轮.set(sid, { turn: event.data?.turn, replies: [], direct: false, 身体工具:false })
1600
1813
  挂agent工具(找agent(sid))
1601
1814
  // 「她开始想了」——房间那边收到就冒个气泡,别让人干等
1602
1815
  发事件('chat.thinking', { at: Date.now() })
@@ -1612,8 +1825,8 @@ function 起来(ctx, 配置参数 = {}) {
1612
1825
  const 票 = 待回.get(sid)?.get(d.message?.id || d.id)
1613
1826
  if (票 && !轮.replies.includes(票)) 轮.replies.push(票)
1614
1827
  }
1615
- if (轮 && (类 === 'fish-home-touch' || 类 === 'fish-home-paint' || 类 === 'fish-home-life')) 轮.direct = true
1616
- if (类 === 'fish-home' || 类 === 'fish-home-life') return // 房间自己说的话,不再回声
1828
+ if (轮 && (类 === 'fish-home-touch' || 类 === 'fish-home-paint' || 类 === 'fish-home-life' || 类 === 'fish-home-state')) 轮.direct = true
1829
+ if (类 === 'fish-home' || 类 === 'fish-home-life' || 类 === 'fish-home-state') return // 房间自己说的话,不再回声
1617
1830
  if (是注入(类)) return // 运行环境 / 时间 / 别的插件
1618
1831
  const 文 = String(提取正文(d.message || d) || '').trim()
1619
1832
  if (!文) return
@@ -1647,6 +1860,9 @@ function 起来(ctx, 配置参数 = {}) {
1647
1860
  if (!完成 || !上 || 上.turn !== d.turn) return
1648
1861
  const 文 = String(上.text || '').trim()
1649
1862
  if (!文) return
1863
+ // 工具调用是首选;如果模型只在自然回复里说了明确动作,
1864
+ // 这里把一次身体意图交给房间执行,避免“嘴上已经坐下,画面还站着”。
1865
+ if (!轮?.身体工具 && !轮?.direct && (单.length || 配置.转发主动开口)) void 跟随身体意图(文, sid)
1650
1866
  if (单.length) {
1651
1867
  // DSH can claim several followups in one turn; emit the reply once.
1652
1868
  发事件('chat.reply', { requestId: 单[0].requestId, requestIds: 单.map(x => x.requestId), text: 文, messageId: 上.messageId || '', turn: d.turn })
@@ -1931,7 +2147,7 @@ function 起来(ctx, 配置参数 = {}) {
1931
2147
  if (!目标) return 回(res, 200, { ok: true, schema: SCHEMA, total: 0, items: [] })
1932
2148
  try {
1933
2149
  const 星汐 = 读星汐(家)
1934
- const 全部 = 收回忆(家, 目标, 星汐)
2150
+ const 全部 = 收回忆(家, 目标, 星汐, { 记忆路径: 配置.文本记忆路径, 日记路径: 配置.文本日记路径 })
1935
2151
  const 结果 = 筛回忆(全部, { q, kind, limit, offset })
1936
2152
  回(res, 200, { ok: true, schema: SCHEMA, sessionId: 目标, total: 结果.total, items: 结果.items })
1937
2153
  } catch (error) {
@@ -1947,7 +2163,7 @@ function 起来(ctx, 配置参数 = {}) {
1947
2163
  const 目标 = 目标会话()
1948
2164
  if (!目标) return 回(res, 200, { ok: true, schema: SCHEMA, since: '', days: 0 })
1949
2165
  try {
1950
- const r = 收天数(家, 目标, 读星汐(家))
2166
+ const r = 收天数(家, 目标, 读星汐(家), { 日记路径: 配置.文本日记路径, 相伴起始日: 配置.相伴起始日 })
1951
2167
  回(res, 200, { ok: true, schema: SCHEMA, sessionId: 目标, since: r.since, days: r.days })
1952
2168
  } catch (error) {
1953
2169
  回错(res, 500, 'DAYS_FAILED', String((error && error.message) || error))
@@ -2011,6 +2227,7 @@ function 起来(ctx, 配置参数 = {}) {
2011
2227
  let 体
2012
2228
  try { 体 = await 读体(req) } catch (error) { return 回错(res, 400, 'BAD_BODY', String((error && error.message) || error)) }
2013
2229
  if (!体 || 体.schema !== PET_STATE_SCHEMA) return 回错(res, 400, 'BAD_SCHEMA', '这份数据的版本不对')
2230
+ const 旧天气 = String(房间环境?.weather || '')
2014
2231
  收下环境(体.snapshot)
2015
2232
  if(typeof 体.room?.url==='string'){
2016
2233
  try{
@@ -2023,6 +2240,7 @@ function 起来(ctx, 配置参数 = {}) {
2023
2240
  if (typeof reportedAction==='string' && 睡眠缓存.值?.ok && 睡眠缓存.值.睡着!==(reportedAction==='sleep')) {
2024
2241
  睡眠缓存 = {at:0,值:null};
2025
2242
  }
2243
+ const 旧状态 = 最近状态
2026
2244
  最近状态 = {
2027
2245
  revision: ++状态版本,
2028
2246
  at: Number(体.at) || Date.now(),
@@ -2030,6 +2248,7 @@ function 起来(ctx, 配置参数 = {}) {
2030
2248
  recent: Array.isArray(体.recent) ? 体.recent.slice(-5) : [],
2031
2249
  recentChat: Array.isArray(体.recentChat) ? 体.recentChat.slice(-6) : [],
2032
2250
  }
2251
+ 推送状态变化(旧状态, 最近状态, 旧天气)
2033
2252
  return 回(res, 200, { ok: true, revision: 最近状态.revision })
2034
2253
  })
2035
2254
 
@@ -2068,7 +2287,7 @@ function 起来(ctx, 配置参数 = {}) {
2068
2287
  }
2069
2288
  const directLife = 事件.kind==='milestone' || 事件.kind==='wallet' || (事件.kind==='scene' && ['pickup','swing'].includes(体.reaction))
2070
2289
  const maxAge = 事件.kind==='scene' ? SCENE_TTL_MS : 10*60000
2071
- if (directLife && 事件.text && Date.now()-事件.at<maxAge && 配置.开 && targetSession) {
2290
+ if (directLife && 配置.主动生活通知[事件.kind] && 事件.text && Date.now()-事件.at<maxAge && 配置.开 && targetSession) {
2072
2291
  const agent=找agent(targetSession)
2073
2292
  if(typeof agent?.followup==='function'){
2074
2293
  if(id)互动送达中.add(id)
@@ -2256,6 +2475,12 @@ function 起来(ctx, 配置参数 = {}) {
2256
2475
  开: 配置.开,
2257
2476
  开机自启: 配置.开机自启,
2258
2477
  睡着不理: 配置.睡着不理,
2478
+ 每轮注入现场: 配置.每轮注入现场,
2479
+ 状态变化通知: 配置.状态变化通知,
2480
+ 主动生活通知: 配置.主动生活通知,
2481
+ 文本记忆路径: 配置.文本记忆路径,
2482
+ 文本日记路径: 配置.文本日记路径,
2483
+ 相伴起始日: 配置.相伴起始日,
2259
2484
  会话: 目标,
2260
2485
  会话活着: Boolean(目标 && 找agent(目标)),
2261
2486
  转发主动开口: 配置.转发主动开口,
@@ -2289,7 +2514,7 @@ function 起来(ctx, 配置参数 = {}) {
2289
2514
  const 自查更新 = createSelfUpdate({ packageRoot: fileURLToPath(new URL('..', import.meta.url)), diag: 记一笔 })
2290
2515
  // 「查更新」和「一键更新」这两个路由由 selfupdate 自己注册 —— 跟其它五个插件是同一份实现。
2291
2516
  // 准入用同源检查:本机别的网页不该能触发安装。
2292
- 自查更新.register(ctx, 管理前缀 + '/update', (req) => (同源(req) ? null : { 码: 403, 说: '只给本页用' }))
2517
+ 自查更新.register(ctx, 管理前缀, (req) => (同源(req) ? null : { 码: 403, 说: '只给本页用' }))
2293
2518
 
2294
2519
  // 房间本体:插件不带它(三百多兆),所以设置页得告诉人「装没装、去哪下」。
2295
2520
  // 找的路径顺序跟启动时完全一致,不然会出现「界面说装了、启动却说找不到」。
@@ -2409,6 +2634,13 @@ function 起来(ctx, 配置参数 = {}) {
2409
2634
  if (体.开 !== undefined) 补丁.开 = Boolean(体.开)
2410
2635
  if (体.开机自启 !== undefined) 补丁.开机自启 = Boolean(体.开机自启)
2411
2636
  if (体.睡着不理 !== undefined) 补丁.睡着不理 = Boolean(体.睡着不理)
2637
+ if (体.每轮注入现场 !== undefined) 补丁.每轮注入现场 = Boolean(体.每轮注入现场)
2638
+ if (体.状态变化通知 !== undefined) 补丁.状态变化通知 = Boolean(体.状态变化通知)
2639
+ if (体.主动生活通知 && typeof 体.主动生活通知==='object') 补丁.主动生活通知=Object.fromEntries(
2640
+ ['milestone','wallet','scene'].map(key=>[key,typeof 体.主动生活通知[key]==='boolean'?体.主动生活通知[key]:配置.主动生活通知[key]]))
2641
+ for (const 键 of ['文本记忆路径', '文本日记路径', '相伴起始日']) {
2642
+ if (体[键] !== undefined)补丁[键] = String(体[键] || '').trim()
2643
+ }
2412
2644
  if (体.会话 !== undefined) 补丁.会话 = String(体.会话 || '').trim()
2413
2645
  if (体.转发主动开口 !== undefined) 补丁.转发主动开口 = Boolean(体.转发主动开口)
2414
2646
  if (体.心跳秒 !== undefined) {
@@ -2519,7 +2751,7 @@ function 起来(ctx, 配置参数 = {}) {
2519
2751
  if (req.method !== 'POST') return 回错(res, 405, 'METHOD', '要用 POST')
2520
2752
  let 体
2521
2753
  try { 体 = await 读体(req) } catch (error) { return 回错(res, 400, 'BAD_BODY', String((error && error.message) || error)) }
2522
- const 结果 = await 画一张(体 && 体.prompt)
2754
+ const 结果 = await 画一张(体 && 体.prompt, 体 && 体.reference)
2523
2755
  if (!结果.ok) return 回错(res, 结果.码 || 502, 结果.代号 || 'PAINT_FAILED', 结果.说)
2524
2756
  return 回(res, 200, { ok: true, mime: 结果.mime, b64: 结果.b64, 模型: 配置.画图模型 })
2525
2757
  }
@@ -2537,7 +2769,7 @@ function 起来(ctx, 配置参数 = {}) {
2537
2769
  })
2538
2770
 
2539
2771
  /** 调一次生图接口,拿回 base64。地址 / 密钥 / 模型都从设置里来。 */
2540
- async function 画一张(prompt) {
2772
+ async function 画一张(prompt, reference = '') {
2541
2773
  const 地址 = String(配置.画图地址 || '').trim().replace(/\/+$/, '')
2542
2774
  const 密钥 = String(配置.画图密钥 || '').trim()
2543
2775
  const 模型 = String(配置.画图模型 || '').trim()
@@ -2562,12 +2794,34 @@ function 起来(ctx, 配置参数 = {}) {
2562
2794
  const 控 = new AbortController()
2563
2795
  const 定 = setTimeout(() => 控.abort(), 120000)
2564
2796
  try {
2565
- const r = await fetch(基 + '/images/generations', {
2566
- method: 'POST',
2567
- headers: { 'content-type': 'application/json', authorization: 'Bearer ' + 密钥 },
2568
- body: JSON.stringify(要的),
2569
- signal: 控.signal,
2570
- })
2797
+ const 参考 = typeof reference === 'string' ? reference.trim().slice(0, 4000) : ''
2798
+ let r
2799
+ if (参考) {
2800
+ let imageData, imageType = 'image/png'
2801
+ if (/^data:image\//i.test(参考)) {
2802
+ const m = /^data:(image\/[^;]+);base64,(.+)$/i.exec(参考)
2803
+ if (!m) return { ok: false, 码: 400, 代号: 'BAD_REFERENCE', 说: '参考图 data URL 格式不对。' }
2804
+ imageType = m[1]; imageData = Buffer.from(m[2], 'base64')
2805
+ } else if (/^https?:\/\//i.test(参考)) {
2806
+ const image = await fetch(参考, { redirect: 'error', signal: 控.signal })
2807
+ if (!image.ok) return { ok: false, 码: 400, 代号: 'BAD_REFERENCE', 说: '参考图地址读不到。' }
2808
+ imageType = image.headers.get('content-type')?.split(';')[0] || imageType
2809
+ imageData = Buffer.from(await image.arrayBuffer())
2810
+ } else {
2811
+ imageData = await fs.promises.readFile(path.resolve(参考))
2812
+ }
2813
+ const form = new FormData()
2814
+ form.append('model', 模型); form.append('prompt', 话); form.append('n', '1'); form.append('size', String(配置.画图尺寸 || '1024x1024')); form.append('response_format', 'b64_json')
2815
+ form.append('image', new Blob([imageData], { type: imageType }), 'reference.png')
2816
+ r = await fetch(基 + '/images/edits', { method: 'POST', headers: { authorization: 'Bearer ' + 密钥 }, body: form, signal: 控.signal })
2817
+ } else {
2818
+ r = await fetch(基 + '/images/generations', {
2819
+ method: 'POST',
2820
+ headers: { 'content-type': 'application/json', authorization: 'Bearer ' + 密钥 },
2821
+ body: JSON.stringify(要的),
2822
+ signal: 控.signal,
2823
+ })
2824
+ }
2571
2825
  const 文 = await r.text()
2572
2826
  if (!r.ok) {
2573
2827
  记一笔('生图失败 HTTP ' + r.status)
package/lib/memory.mjs CHANGED
@@ -78,6 +78,56 @@ export function 收日记(夹) {
78
78
  return 出
79
79
  }
80
80
 
81
+ function 文本文件们(来源) {
82
+ const 路 = String(来源 || '').trim()
83
+ if (!路) return []
84
+ try {
85
+ const stat = fs.statSync(路)
86
+ if (stat.isFile()) return [路]
87
+ if (!stat.isDirectory()) return []
88
+ return fs.readdirSync(路, { withFileTypes: true })
89
+ .filter((entry) => entry.isFile() && /\.(?:md|txt)$/i.test(entry.name))
90
+ .map((entry) => path.join(路, entry.name))
91
+ .sort()
92
+ } catch (error) { return [] }
93
+ }
94
+
95
+ function 文本日期(路, stat) {
96
+ const 名 = path.basename(路)
97
+ const 命中 = /(\d{4}-\d{2}-\d{2})/.exec(名)
98
+ if (命中) return 命中[1]
99
+ return stat?.mtime ? new Date(stat.mtime).toISOString().slice(0, 10) : ''
100
+ }
101
+
102
+ /** 纯文本适配器:允许把一整个 md/txt 文件夹接进回忆簿。 */
103
+ export function 收文本(来源, kind = 'fact') {
104
+ const 出 = []
105
+ for (const 路 of 文本文件们(来源)) {
106
+ let 文 = ''
107
+ let stat = null
108
+ try { 文 = fs.readFileSync(路, 'utf8'); stat = fs.statSync(路) } catch (error) { continue }
109
+ const 日期 = 文本日期(路, stat)
110
+ const 名 = path.basename(路, path.extname(路))
111
+ const 块 = kind === 'daily'
112
+ ? [文.trim()]
113
+ : 文.split(/\n\s*\n/).map((part) => part.trim()).filter(Boolean)
114
+ 块.forEach((正文, index) => {
115
+ if (!正文) return
116
+ const id = `text:${kind}:${路}:${index}`
117
+ 出.push({
118
+ id,
119
+ at: 日期 ? 日期 + 'T23:59:59' : '',
120
+ kind,
121
+ title: kind === 'daily' ? (日期 || 名) : (名 || '文本记录'),
122
+ text: 正文,
123
+ source: '文本文件',
124
+ tags: [],
125
+ })
126
+ })
127
+ }
128
+ return 出
129
+ }
130
+
81
131
  /** 记忆卡:## 章名 下面是条目,一行一条 */
82
132
  export function 收记忆卡(路) {
83
133
  const p = String(路 || '').trim()
@@ -116,11 +166,15 @@ function 会话档案(家目录, 会话, 配置) {
116
166
  return String(配置.绑定?.['session-' + bare] || 配置.绑定?.[bare] || path.join(家目录, 'xingxi', '会话', 'session-' + bare)).trim()
117
167
  }
118
168
 
119
- export function 收天数(家目录, 会话, 星汐) {
169
+ export function 收天数(家目录, 会话, 星汐, 来源 = {}) {
120
170
  const 配置 = 星汐 || 读星汐(家目录)
121
- const 最早 = 收日记(会话档案(家目录, 会话, 配置)).at(-1)
122
- if (!最早) return { since: '', days: 0 }
123
- const since = 最早.title
171
+ const 自定义 = 收文本(来源.日记路径, 'daily')
172
+ const 最早 = [...收日记(会话档案(家目录, 会话, 配置)), ...自定义]
173
+ .filter((item) => /^\d{4}-\d{2}-\d{2}$/.test(String(item.title || '')))
174
+ .sort((a, b) => String(a.title).localeCompare(String(b.title)))[0]
175
+ const 起始 = 最早?.title || String(来源.相伴起始日 || '').trim()
176
+ if (!起始) return { since: '', days: 0 }
177
+ const since = 起始
124
178
  const today = new Intl.DateTimeFormat('sv-SE', { timeZone: 'Asia/Shanghai' }).format(new Date())
125
179
  const days = Math.floor((Date.parse(today + 'T00:00:00Z') - Date.parse(since + 'T00:00:00Z')) / 86400000) + 1
126
180
  return { since, days: Math.max(1, days) }
@@ -132,13 +186,15 @@ export function 收天数(家目录, 会话, 星汐) {
132
186
  * @param {string} 会话 绑定的会话 id(session-…)
133
187
  * @param {object} 星汐 读星汐() 的结果
134
188
  */
135
- export function 收回忆(家目录, 会话, 星汐) {
189
+ export function 收回忆(家目录, 会话, 星汐, 来源 = {}) {
136
190
  const 配置 = 星汐 || 读星汐(家目录)
137
191
  const 日记夹 = 会话档案(家目录, 会话, 配置)
138
192
  // ⚠ 记忆卡(成长)已经不要了 —— 一行一句像流水账,面板上那个按钮也删了。
139
193
  return [
140
194
  ...读鱼的记忆(家目录, 会话),
141
195
  ...收日记(日记夹),
196
+ ...收文本(来源.记忆路径, 'fact'),
197
+ ...收文本(来源.日记路径, 'daily'),
142
198
  ]
143
199
  }
144
200
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-fish-home",
3
- "version": "0.1.0",
3
+ "version": "0.1.2",
4
4
  "description": "鱼鱼窝:把「大肥鱼的小日子」那个 3D 房间接进 DSH —— 房间里打字能送到会话里,会话里回的话、她自己打的字,都顺着事件流回到房间里。",
5
5
  "license": "SEE LICENSE IN LICENSE",
6
6
  "engines": {