dsh-fish-home 0.1.1 → 0.1.3

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,24 @@
1
+ ## 0.1.3 — 2026-11-21
2
+
3
+ - 收菜、出售及原地补种可一单完成;卖本批新收的菜或鱼不用先查数量。补种期间给这单留出原地和种子,代理继续照料其它地块。
4
+ - 修复普通聊天未统一计入本地心情和陪伴的问题;提示可区分插件心情与本地兜底,并说明六项数值的来源。
5
+ - 所有作物均支持巨型,菜田按 3×3 判定,花田每朵花成熟时单独判定。普通播种可一单种满并按实际缺口补买;巨型这一步失败不会撤回已完成的鱼塘或农活步骤。
6
+ - 巨型作物按同品种当日售价的 1.8 倍出售,菜田按九份普通菜计价,花田按一份普通花计价。DSH 可查单价,成熟提醒与收获回执按实际收成计数,出售显示到账与余量,不混扣普通收成。
7
+ - 农活查询直接显示总空位,收获失败区分空田、没种该作物和未成熟;同批唯一品种可自动接续放苗。超过本轮写入限制仍可查询,工具不会被卸载。
8
+ - `fish_home status` 一次查询实际位置、活动、身体感受和有效心情;留存未主动推送的近期场景体验。已送达的场景摘要不会在状态和可选的会话现场中再出现。
9
+ - 稍累时,等当前活动结束后会找地方休息;农活结束、手需要清洗时会去洗手。料理动作保持原样,整理厨房不会恢复个人清爽。
10
+ - 修复右上角退出图标的悬停提示空白。
11
+ - 重新生成可独立启动的纯净房间包;通过原更新脚本替换程序,保留已有存档和自定义配置。
12
+
13
+ ## 0.1.2 — 2026-11-21
14
+
15
+ - 农活工具改成 `batch` / `list` 两个入口:同一轮可以一次提交多种作物的出售、买种和播种,重复请求复用原回执,每轮最多执行两批,避免模型逐格、逐品种循环调用。
16
+ - 鱼鱼窝设置增加「显示我的小菜园」,只控制庭院工具栏的显示,不影响地块、池塘或自动照料。
17
+ - 悬停提示增加命中缓冲,聊天气泡加宽并放大,长句更容易阅读。
18
+ - 修复没有星汐或文本日记时自动把更新当天当成相伴起始日的问题,保留房间存档天数作为兜底。
19
+ - 修复「检查更新」的路由重复拼了一段路径、点了没反应的问题。
20
+ - 保留本地更新脚本的存档备份、回滚和自定义配置保护逻辑。
21
+
1
22
  ## 0.1.1 — 2026-11-20
2
23
 
3
24
  - 回忆簿支持配置 .md / .txt 文件或文件夹;没有星汐插件时可用文本日记和存档起始日计算相伴天数。
package/README.md CHANGED
@@ -78,7 +78,8 @@
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
+ - **批量收种**。用一次 `batch` 交整单:`actions` 只填 `replant` 会收获并原地补种(可用 `item` 指定品种);要顺手卖菜就按 `harvest` → `sell` → `replant` 排。`sell` 省略品种和数量时只卖本批刚入包的作物或成鱼。默认用背包里的种子,允许花金币买种子才填 `buyMissing: true`。回执会写明已完成的步骤和余额。
82
+ - **种满与巨型候选**。普通 `plant` 用 `fill: true` 自动算空位;菜田用 `layout: "giant"` 自动找 3×3,九格同种全熟时有一次 15% 的机会。花田用普通播种,每朵花成熟时独立有 15% 的机会变异。只有获准花金币才加 `buyMissing: true`,按实际可种和库存补买;允许碎地备用才加 `fallback: "normal"`。收、卖、播种可以仍在一批内完成。
82
83
  - **集市**。商店里的「集市行情」和 fish_home 的 market、price 共用售价。每天北京时间零点更新,明日预告也可提前查询。price 可按 kind 或 item 筛选。
83
84
 
84
85
  ## 画架
@@ -138,7 +139,7 @@ Windows 就是 `C:\Users\<你>\.dsh\fish-home-room\`,打开里面要能直接
138
139
 
139
140
  内置房间使用原版蓝色大肥鱼模型和配套动作。
140
141
 
141
- 回忆簿可在 DSH 设置里的「上下文与回忆」填写纯文本记忆路径、日记路径和相伴起始日;逐轮 runtime-context 默认关闭,需要时可按需查询现场,天气、成熟与生活里程碑、消费和场景事件也能分别控制是否通知绑定会话。模型制作:水原镜,MMD 转换与绑定:耶栗Yaki。模型的署名和原始使用规约随房间本体一起下发(房间目录 `dist/models/dayu-mmd/` 里的 `使用规约.txt` 和 `MODEL-CREDITS.md`),请一并保留。
142
+ 回忆簿可在 DSH 设置里的「上下文与回忆」填写纯文本记忆路径、日记路径和相伴起始日;逐轮 runtime-context 默认关闭。`fish_home status` 可一次读到所在位置、活动、身体感受和心情;重要天气变化、成熟与生活里程碑、消费和场景事件仍分别控制是否通知绑定会话。模型制作:水原镜,MMD 转换与绑定:耶栗Yaki。模型的署名和原始使用规约随房间本体一起下发(房间目录 `dist/models/dayu-mmd/` 里的 `使用规约.txt` 和 `MODEL-CREDITS.md`),请一并保留。
142
143
 
143
144
  卡包大部分立绘来源于 B站 UP 主 **ZipZipPipe**,版权归原作者,随游戏一起分发、未作修改。
144
145
 
package/lib/host.js CHANGED
@@ -95,7 +95,7 @@ const 默认配置 = {
95
95
  睡着不理: true,
96
96
  // 动态现场默认不塞进每一轮 runtime-context;需要时用 fish_home 查明细。
97
97
  每轮注入现场: false,
98
- 上下文策略版本: 2,
98
+ 上下文策略版本: 3,
99
99
  状态变化通知: true,
100
100
  主动生活通知: { milestone: true, wallet: true, scene: true },
101
101
  文本记忆路径: '',
@@ -109,9 +109,23 @@ function 读配置() {
109
109
  const 合 = { ...默认配置, ...(存 && typeof 存 === 'object' ? 存 : {}) }
110
110
  // 0.1.0 曾把现场上下文默认塞进每一轮。升级后强制迁移一次,
111
111
  // 否则旧的 fish-room.json 会把新默认值重新覆盖回 true。
112
- if (Number(存?.上下文策略版本 || 0) < 2) {
112
+ const 上下文迁移 = Number(存?.上下文策略版本 || 0)
113
+ if (上下文迁移 < 2) {
113
114
  合.每轮注入现场 = false
114
- 合.上下文策略版本 = 2
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
115
129
  try { fs.mkdirSync(家, { recursive: true }); fs.writeFileSync(配置路, JSON.stringify(合, null, 2), 'utf8') } catch {}
116
130
  }
117
131
  合.开 = 合.开 !== false
@@ -125,20 +139,14 @@ function 读配置() {
125
139
  delete 合.上次醒来招呼
126
140
  合.睡着不理 = 合.睡着不理 !== false
127
141
  合.每轮注入现场 = 合.每轮注入现场 === true
128
- 合.上下文策略版本 = 2
142
+ 合.上下文策略版本 = 3
129
143
  合.状态变化通知 = 合.状态变化通知 !== false
130
144
  合.主动生活通知 = Object.fromEntries(['milestone','wallet','scene'].map(key=>[key,合.主动生活通知?.[key]!==false]))
131
145
  合.文本记忆路径 = String(合.文本记忆路径 || '').trim()
132
146
  合.文本日记路径 = String(合.文本日记路径 || '').trim()
133
147
  合.相伴起始日 = /^\d{4}-\d{2}-\d{2}$/.test(String(合.相伴起始日 || '')) ? String(合.相伴起始日) : ''
134
- if (!合.相伴起始日) {
135
- const now = new Intl.DateTimeFormat('sv-SE', { timeZone: 'Asia/Shanghai' }).format(new Date())
136
- 合.相伴起始日 = now
137
- try {
138
- fs.mkdirSync(家, { recursive: true })
139
- fs.writeFileSync(配置路, JSON.stringify(合, null, 2), 'utf8')
140
- } catch (error) {}
141
- }
148
+ // 没有来源时保持空白,让房间自己的存档天数作为兜底。
149
+
142
150
  合.会话 = String(合.会话 || '').trim()
143
151
  合.令牌 = String(合.令牌 || '').trim()
144
152
  const 秒 = Number(合.心跳秒)
@@ -827,7 +835,7 @@ function 起来(ctx, 配置参数 = {}) {
827
835
  if (快 && 快.pond) 家当.push('池塘 ' + (Number(快.pond.条数) || 0) + '/' + (Number(快.pond.容量) || 8))
828
836
  if (快 && 快.卡册) 家当.push('卡册 ' + (Number(快.卡册.已集) || 0) + '/' + (Number(快.卡册.总) || 0))
829
837
  const 攒 = 家当.length ? (现场 ? '' : '上次同步:') + 家当.join(' · ') + '。' : ''
830
- const 最近 = 生活事件.filter(e => e.sessionId === 目标会话() && Date.now() - e.at < 5 * 60000 && ['milestone','farm'].includes(e.kind)).slice(-2)
838
+ const 最近 = 生活事件.filter(e => e.sessionId === 目标会话() && Date.now() - e.at < 5 * 60000 && !e.notified && ['milestone','farm'].includes(e.kind)).slice(-2)
831
839
  .map((x) => String((x && x.text) || '').trim())
832
840
  .filter(Boolean)
833
841
  .map((t) => (t.length > 24 ? t.slice(0, 24) + '…' : t))
@@ -842,10 +850,12 @@ function 起来(ctx, 配置参数 = {}) {
842
850
  function 状态通知文本(previous, next, oldWeather = '') {
843
851
  const lines = []
844
852
  const after = next?.snapshot || {}
845
- const newWeather = String(after.weather || 房间环境?.weather || '')
846
- if (oldWeather && newWeather && oldWeather !== newWeather) {
847
- const labels = { clear: '晴天', cloudy: '阴天', rain: '下雨', snow: '下雪', storm: '雷雨' }
848
- lines.push('窗外天气变成' + (labels[newWeather] || newWeather) + '。')
853
+ const newWeather = String(after.weather || '')
854
+ const labels = { clear: '晴天', cloudy: '阴天', rain: '下雨', snow: '下雪', storm: '雷雨' }
855
+ const affectsOutdoors = value => ['rain','snow','storm'].includes(value);
856
+ if (Object.hasOwn(labels,oldWeather) && Object.hasOwn(labels,newWeather) && oldWeather !== newWeather &&
857
+ (affectsOutdoors(oldWeather)||affectsOutdoors(newWeather))) {
858
+ lines.push(affectsOutdoors(newWeather) ? '窗外天气变了:'+labels[newWeather]+'。' : '窗外的雨雪停了。');
849
859
  }
850
860
  return lines
851
861
  }
@@ -888,6 +898,33 @@ function 起来(ctx, 配置参数 = {}) {
888
898
  return '当前安排:'+[地点名字[activity?.room],label].filter(Boolean).join(' · ')+'。';
889
899
  }
890
900
 
901
+ function 身体简报(live) {
902
+ const lines=[活动简报(live.activity,live.observation,live.presence)];
903
+ const observation=live.observation;
904
+ const fresh = value => Number.isFinite(value?.at)&&Date.now()-value.at<36000;
905
+ if (lines[0]==='活动:闲着。') lines[0]='当前安排:闲着。';
906
+ if (fresh(live.presence) && live.presence.visible && observation?.activityId===live.activity?.id &&
907
+ ['moving','blocked'].includes(observation?.phase) && fresh(observation)) {
908
+ const dest=地点名字[live.activity?.room];
909
+ if (dest) lines.push((observation.phase==='moving'?'正在去':'暂时没走到')+dest+',安排是'+String(live.activity.label||'').slice(0,30)+'。');
910
+ }
911
+ const feelings=[];
912
+ const {energy,satiety,hygiene}=live.needs||{};
913
+ if (Number.isFinite(energy)&&energy<55) feelings.push(energy<35?'很累':'有点累');
914
+ if (Number.isFinite(satiety)&&satiety<54) feelings.push(satiety<40?'饿了':'有点饿');
915
+ if (Number.isFinite(hygiene)&&hygiene<65) feelings.push(hygiene<35?'想洗漱':'想洗洗手');
916
+ if (Number.isFinite(energy)&&Number.isFinite(satiety)&&Number.isFinite(hygiene)&&!feelings.length) feelings.push('状态还好');
917
+ if (Number.isFinite(live.mood)) {
918
+ const source=live.mood来源==='feiyu-mood'?'(鱼的心情)':live.mood来源==='local'?'(本地)':'';
919
+ feelings.push('心情 '+Math.round(live.mood)+'/100'+source);
920
+ }
921
+ if (feelings.length) lines.push('身体:'+feelings.join(',')+'。');
922
+ const scene=最近场景?.sid===目标会话() && Date.now()-最近场景.at<SCENE_TTL_MS ? 最近场景.text : '';
923
+ const recent=scene || live.recentBodyActivity;
924
+ if (recent) lines.push('刚才:'+String(recent).trim().slice(0,100).replace(/[。!?]+$/,'')+'。');
925
+ return lines.join('');
926
+ }
927
+
891
928
  // 房间时间 + 画架工具,都挂在绑定的那间会话上(跟心情插件一样按 agent 实例记)
892
929
  const 上下文挂着 = new Map() // scoped registrations and their disposers
893
930
  function 画工具() {
@@ -978,12 +1015,12 @@ function 起来(ctx, 配置参数 = {}) {
978
1015
  function 鱼鱼窝工具() {
979
1016
  return {
980
1017
  name: 'fish_home',
981
- description: '鱼鱼窝的生活数据。what 的可选范围:status(当前地点和活动)、farm(田里种的、还有多久熟、剩什么种子和收成)、pond(池塘几条鱼、什么鱼、多久能捞)、cards(卡册集了多少、还差哪几张、哪几张还没到珠光)、pity(卡池保底和下一抽概率,不花金币)、price(完整价目,可按类别 kind 或品名 item 筛选)、market(今天和明天的行情摘要)、wallet(正式存档的当前金币、星尘和星辉)、today(今天做过什么)、weather(庭院当前天气)、forecast(设置地区的三天预报)、all(全看一遍)。',
1018
+ description: '鱼鱼窝的生活数据。what 的可选范围:status(实际地点、身体感受、心情和一条近期身体经历)、farm(田里种的、还有多久熟、剩什么种子和收成)、pond(池塘几条鱼、什么鱼、多久能捞)、cards(卡册集了多少、还差哪几张、哪几张还没到珠光)、pity(卡池保底和下一抽概率,不花金币)、price(完整价目,可按类别 kind 或品名 item 筛选)、market(今天和明天的行情摘要)、wallet(正式存档的当前金币、星尘和星辉)、today(今天做过什么)、weather(庭院当前天气)、forecast(设置地区的三天预报)、all(全看一遍)。',
982
1019
  parameters: {
983
1020
  type: 'object',
984
1021
  properties: {
985
1022
  what: { type: 'string', enum: ['status','farm','pond','cards','pity','wallet','price','market','today','weather','forecast','all'], description:'要看哪一块' },
986
- kind: {type:'string',enum:['crop','flower','fish','all'],description:'价目类别,省略时列出全部'},
1023
+ kind: {type:'string',enum:['crop','flower','fish','giant','all'],description:'价目类别。giant 查巨型作物,省略时列出普通商品。'},
987
1024
  item: {type:'string',description:'价目查询可填一个品名或 ID'},
988
1025
  },
989
1026
  required: ['what'],
@@ -1018,6 +1055,14 @@ function 起来(ctx, 配置参数 = {}) {
1018
1055
  }
1019
1056
  if (要==='market'||要==='price') {
1020
1057
  try {
1058
+ if(args.kind==='giant'){
1059
+ const {market,giantItems=[]}=await roomRequest('/api/farm',undefined,8000,exec?.signal);
1060
+ const query=String(args.item||'').trim().toLowerCase();
1061
+ const matches=giantItems.filter(item=>!query||item.id.includes(query)||item.name.toLowerCase().includes(query));
1062
+ if(!matches.length)return {ok:false,说:'没有匹配的巨型作物。'};
1063
+ const lines=matches.map(item=>`${item.name} · 今日售 ${item.sellPrice} / 明日售 ${item.tomorrowSellPrice} 金币`);
1064
+ return {ok:true,说:[`巨型作物单份售价(${market.today.date})`,...lines].join('\n')};
1065
+ }
1021
1066
  const {market}=await roomRequest('/api/farm/market',undefined,8000,exec?.signal);
1022
1067
  const lines=[market.today.date+' · '+market.today.note,market.tomorrow.date+' 预告 · '+market.tomorrow.note];
1023
1068
  if (要==='market'&&!args.item&&!args.kind) return {ok:true,说:lines.join('\n')};
@@ -1061,36 +1106,33 @@ function 起来(ctx, 配置参数 = {}) {
1061
1106
  }
1062
1107
  if (要 === 'status' || 要 === 'all') {
1063
1108
  try {
1064
- const live = await roomRequest('/api/life/activity', undefined, 5000, exec?.signal);
1065
- const 说 = 活动简报(live.activity, live.observation, live.presence);
1109
+ const live = await roomRequest('/api/life/activity?status=1', undefined, 5000, exec?.signal);
1110
+ const 说 = 身体简报(live);
1066
1111
  if (要 === 'status') return {ok:true, 说};
1067
1112
  段.push(说);
1068
1113
  } catch (error) {
1069
1114
  if (要 === 'status') return {ok:false, 说: '暂时读不到鱼鱼窝的当前状态。'};
1070
1115
  }
1071
1116
  }
1117
+ if (要 === 'farm' || 要 === 'all') {
1118
+ try {
1119
+ const data = await roomRequest('/api/farm', undefined, 8000, exec?.signal);
1120
+ const 说 = farmSummary(data, 'farm');
1121
+ if (要 === 'farm') return {ok:true,说};
1122
+ 段.push(说);
1123
+ } catch (error) {
1124
+ const 说 = '暂时读不到当前田地:' + error.message;
1125
+ if (要 === 'farm') return {ok:false,说};
1126
+ 段.push(说);
1127
+ }
1128
+ }
1072
1129
  const 快 = 最近状态 && 最近状态.snapshot
1073
1130
  if (!快 && 段.length) return {ok:true, 说:段.join('\n\n')};
1074
1131
  if (!快) return { ok: false, 说: '房间那边还没报上来,等一下再问。' }
1075
- const 田 = 快.farm || null
1076
1132
  const 池 = 快.pond || null
1077
1133
  const 册 = 快.卡册 || null
1078
1134
 
1079
1135
  if (要 === 'all')段.push('行情可用 fish_home 的 market 或 price 单独查看。');
1080
- if ((要 === 'farm' || 要 === 'all') && 田) {
1081
- const 行 = []
1082
- 行.push(`田里 ${田.planted} 块种着,${田.空地} 块空着`)
1083
- for (const 批 of 田.作物 || []) {
1084
- const 名 = String(批.cropId || '')
1085
- 行.push(` ${名} ${批.块数} 块` + (批.熟 ? `,熟了 ${批.熟} 块` : `,最快还要 ${批.最快分钟} 分钟`))
1086
- }
1087
- const 种 = Object.entries(田.种子 || {}).map(([k, v]) => `${k}×${v}`).join('、')
1088
- const 收 = Object.entries(田.收成 || {}).map(([k, v]) => `${k}×${v}`).join('、')
1089
- 行.push(`背包种子:${种 || '空'};收成:${收 || '空'}`)
1090
- 行.push(田.autoCare ? '开启了自动照料;启用自动播种时,空地会用背包种子补种。' : '自动照料关闭。')
1091
- if (Number(田.ready)) 行.push('可用 fish_home_farm 一次收获。item 可指定品种。');
1092
- 段.push(行.join('\n'))
1093
- }
1094
1136
  if ((要 === 'pond' || 要 === 'all') && 池) {
1095
1137
  const 行 = [`池塘 ${池.条数}/${池.容量} 条`]
1096
1138
  for (const 鱼 of 池.鱼 || []) 行.push(` ${鱼.species}:` + (鱼.ready ? '能捞了' : `还要 ${鱼.剩余分钟} 分钟`))
@@ -1333,8 +1375,11 @@ function 起来(ctx, 配置参数 = {}) {
1333
1375
  redirect: 'error', signal: signal ? AbortSignal.any([signal, deadline]) : deadline,
1334
1376
  ...(params === undefined ? {} : { method: 'POST', headers: {'content-type':'application/json'}, body: JSON.stringify(params) }),
1335
1377
  });
1378
+ if (route==='/api/farm/plant-giant-batch' && response.status===404) {
1379
+ throw new Error('当前房间还没更新到支持整块 3×3 播种的版本;这一步没有买种或播种。');
1380
+ }
1336
1381
  const result = await response.json();
1337
- if (result.ok === false || !response.ok) throw Object.assign(new Error(result.say || result.说 || result.error || '鱼鱼窝没有完成这次操作。'),{code:result.code});
1382
+ if (result.ok === false || !response.ok) throw Object.assign(new Error(result.say || result.说 || result.error || '鱼鱼窝没有完成这次操作。'),{code:result.code,result});
1338
1383
  return result;
1339
1384
  }
1340
1385
 
@@ -1408,11 +1453,23 @@ function 起来(ctx, 配置参数 = {}) {
1408
1453
  return Object.entries(items).map(([id,n])=>id+'×'+n).join('、')||'空';
1409
1454
  }
1410
1455
 
1456
+ function saleReceipt(result) {
1457
+ const {id,name,n,unitPrice} = result.卖出;
1458
+ const summary = `卖了 ${n} 份${name},入账 ${result.得了} 金币。`;
1459
+ if (!id.startsWith('giant_')) return summary;
1460
+ const remaining = result.wallet?.giants?.[id.slice('giant_'.length)] || 0;
1461
+ return `${summary} 每份 ${unitPrice} 金币,背包还剩 ${remaining} 份${name}。`;
1462
+ }
1463
+
1411
1464
  function farmSummary(data,scope='all') {
1412
1465
  const farm=data.farm;
1413
1466
  const lines=[];
1414
1467
  if(scope!=='pond') {
1415
1468
  const groups=new Map();
1469
+ const giants=farm.giants || [];
1470
+ const giantNames=new Map((data.giantItems || []).map(item=>[item.cropId,item.name]));
1471
+ const giantName=cropId=>giantNames.get(cropId) || `巨型${cropId}`;
1472
+ const occupiedByGiants=new Set(giants.flatMap(item=>item.plotIds));
1416
1473
  let emptyVegetables=0,emptyFlowers=0;
1417
1474
  for(const plot of farm.plots){
1418
1475
  if(!plot.cropId){
@@ -1420,14 +1477,22 @@ function 起来(ctx, 配置参数 = {}) {
1420
1477
  else emptyVegetables++;
1421
1478
  continue;
1422
1479
  }
1480
+ if (occupiedByGiants.has(plot.id)) continue;
1423
1481
  const group=groups.get(plot.cropId)||{growing:0,ready:0};
1424
1482
  if(plot.ready)group.ready++;
1425
1483
  else group.growing++;
1426
1484
  groups.set(plot.cropId,group);
1427
1485
  }
1428
- lines.push('菜田空 '+emptyVegetables+' 格,花田空 '+emptyFlowers+' 格。');
1486
+ lines.push(`总空位 ${emptyVegetables+emptyFlowers} 格:菜田 ${emptyVegetables}、花田 ${emptyFlowers}。`);
1429
1487
  if(groups.size)lines.push([...groups].map(([id,g])=>id+' '+g.growing+' 格生长、'+g.ready+' 格成熟').join(';')+'。');
1430
- lines.push('种子:'+inventoryLine(data.seeds)+'。收成:'+inventoryLine({...data.crops,...Object.fromEntries(Object.entries(data.giants||{}).map(([id,n])=>['giant_'+id,n]))})+'。');
1488
+ if (giants.length) {
1489
+ const counts=new Map();
1490
+ for (const giant of giants) counts.set(giant.cropId,(counts.get(giant.cropId)||0)+1);
1491
+ const mature=[...counts].map(([id,n])=>`${giantName(id)}×${n}`).join('、');
1492
+ lines.push(`田里已长成:${mature},共占 ${occupiedByGiants.size} 格。`);
1493
+ }
1494
+ const inventory=Object.entries(data.giants||{}).map(([id,n])=>`${giantName(id)}×${n}`).join('、');
1495
+ lines.push(`种子:${inventoryLine(data.seeds)}。普通收成:${inventoryLine(data.crops)}。巨型收成:${inventory||'空'}。`);
1431
1496
  if(farm.autoCare&&data.自动播种开启)lines.push('自动补种已开,鱼鱼会使用背包种子种空地。');
1432
1497
  }
1433
1498
  if(scope!=='farm'){
@@ -1452,52 +1517,198 @@ function 起来(ctx, 配置参数 = {}) {
1452
1517
  return lines.join(' ');
1453
1518
  }
1454
1519
 
1520
+ const 每轮农活上限 = 2;
1521
+
1455
1522
  function 农活工具() {
1456
- const 进行中的批量操作 = new Set()
1457
- const rounds = new WeakMap()
1523
+ const operations = ['plant','water','harvest','replant','buy','sell','stock','feed','catch'];
1524
+ const actionFields = {
1525
+ op: {type:'string',enum:operations},
1526
+ item: {type:'string',description:'品种 ID 或中文名。replant 省略时处理成熟作物;sell 省略时卖本批新收获,指定巨型收成用巨型品名或 kind=giant 加普通品名;stock 省略时接同一批中唯一买过的鱼种。'},
1527
+ count: {type:'integer',minimum:1,maximum:999,description:'数量。收获、浇水、补种和捞鱼默认全部符合条件的。'},
1528
+ kind: {type:'string',enum:['seed','fish','crop','giant'],description:'仅用于买卖。'},
1529
+ zone: {type:'string',enum:['vegetable','flower'],description:'限制浇水和收获范围。播种自动选对应田地。'},
1530
+ bed: {type:'integer',minimum:0,maximum:2,description:'可指定 0 到 2 号菜畦播种、浇水或收获。'},
1531
+ buyMissing: {type:'boolean',description:'用于 plant 或 replant。允许花金币时填 true,只买实际种得下且缺的种子。'},
1532
+ fill: {type:'boolean',description:'仅用于普通 plant;种满用 true,按执行时的空格数播种,省略 count。'},
1533
+ layout: {type:'string',enum:['giant'],description:'只用于菜田的 plant,giant 会找完整 3×3。花田普通播种,每朵花成熟时独立判定。'},
1534
+ fallback: {type:'string',enum:['normal'],description:'仅用于 layout=giant。用户明确接受没整区时普通种,才填 normal。'},
1535
+ };
1536
+ let pending = Promise.resolve();
1537
+
1538
+ async function plan(args, catalog) {
1539
+ const {op, zone, bed, kind, layout, fallback} = args;
1540
+ const item = string(args.item);
1541
+ if (layout!==undefined&&(op!=='plant'||layout!=='giant')||fallback!==undefined&&(layout!=='giant'||fallback!=='normal')) {
1542
+ throw new Error('整块和备用布局只能用于 plant;layout 填 giant,允许普通备用时 fallback 填 normal。');
1543
+ }
1544
+ const count = args.count ?? (['harvest','water','replant'].includes(op) ? 65 : op==='catch' ? 8 : 1);
1545
+ if (args.fill!==undefined&&(typeof args.fill!=='boolean'||op!=='plant'||layout==='giant'||(args.fill&&args.count!==undefined))) throw new Error('种满用普通 plant 加 fill=true,不用填写 count。');
1546
+ if (args.buyMissing!==undefined&&(typeof args.buyMissing!=='boolean'||!['plant','replant'].includes(op))) throw new Error('buyMissing 只用于播种或补种。');
1547
+ if (!operations.includes(op)) throw new Error('请选择有效的农活。');
1548
+ if (args.plotId!==undefined) throw new Error('使用品种和数量批量操作,不需要地块编号。');
1549
+ if (!Number.isSafeInteger(count) || count<1 || count>999) throw new Error('数量必须是 1 到 999 的整数。');
1550
+ if (['plant','water','harvest','replant'].includes(op) && count>65) throw new Error('田地操作一次最多 65 格。');
1551
+ if (['stock','catch'].includes(op) && count>8) throw new Error('池塘操作一次最多 8 条。');
1552
+ if (zone!==undefined && !['vegetable','flower'].includes(zone)) throw new Error('请选择菜田或花田。');
1553
+ if (bed!==undefined && (![0,1,2].includes(bed)||zone==='flower'||!['plant','water','harvest','replant'].includes(op))) throw new Error('请指定 0 到 2 号菜畦;花田不按菜畦编号。');
1554
+ if (op==='feed') return {op, route:'feed', payload:{}};
1555
+ if (op==='sell' && !item) {
1556
+ if (args.count!==undefined || kind!==undefined) throw new Error('只卖本批收获时不用填 count 或 kind;要指定数量或分类请填品种。');
1557
+ return {op,route:'sell-current',payload:{}};
1558
+ }
1559
+ if (op==='replant' && !item) {
1560
+ if (zone!==undefined || bed!==undefined) throw new Error('原地补种不需要指定田地。');
1561
+ return {op,route:op,payload:{count,buyMissing:args.buyMissing===true}};
1562
+ }
1563
+ if (['water','harvest'].includes(op) && !item) return {op, route:op+'-batch', payload:{count,zone,bed}};
1564
+ if (op==='catch' && !item) return {op, route:'catch-batch', payload:{count}};
1565
+
1566
+ const data = await catalog();
1567
+ const seeds = data.商店 || [], fish = data.鱼 || [], giants = data.giantItems || [];
1568
+ const match = list => list.find(x => x.id===item || x.name===item);
1569
+ if (op==='buy' || op==='sell') {
1570
+ const goods = op==='buy' && kind==='fish' ? fish : op==='buy' && kind==='seed' ? seeds : [...seeds,...fish,...(op==='sell'?giants:[])];
1571
+ const found = op==='sell' && kind==='giant'
1572
+ ? match(giants) || giants.find(giant=>giant.cropId===match(seeds)?.id)
1573
+ : match(goods);
1574
+ if (!found) throw new Error('找不到商品 '+item+'。');
1575
+ const category = fish.includes(found) ? 'fish' : giants.includes(found) ? 'giant' : op==='buy' ? 'seed' : 'crop';
1576
+ if (kind && kind!==category) throw new Error(found.name+'的商品分类不符。');
1577
+ if (op==='buy' && count>99) throw new Error('一次可以买 1 到 99 份。');
1578
+ return {op, route:op, name:found.name, payload:{kind:category,id:found.id,数量:count}};
1579
+ }
1580
+ if (op==='stock' || op==='catch') {
1581
+ const species = match(fish);
1582
+ if (!species) throw new Error('请指定有效的鱼种。');
1583
+ return {op, route:op+'-batch', name:species.name, payload:{item:species.id,count}};
1584
+ }
1585
+ if (op==='replant') {
1586
+ if (zone!==undefined || bed!==undefined) throw new Error('原地补种不需要指定田地。');
1587
+ const crop = item && match(seeds);
1588
+ if (item && !crop) throw new Error('商店里没有「'+item+'」这个作物品种。');
1589
+ return {op, route:op, name:crop?.name, payload:{item:crop?.id,count,buyMissing:args.buyMissing===true}};
1590
+ }
1591
+ const crop = match(seeds);
1592
+ if (!crop && layout==='giant') return {op,route:'invalid-giant',payload:{item,bed},localError:`${bed===undefined?'巨型播种':'菜畦 '+bed}:商店里没有「${item||'未指定品种'}」这种种子,这一步没买种或播种。`};
1593
+ if (!crop) throw new Error('商店里没有「'+item+'」这种作物;这与田里是否成熟无关。');
1594
+ if (op==='plant' && (zone && zone!==(Number(crop.tier)===5?'flower':'vegetable') || bed!==undefined&&Number(crop.tier)===5)) {
1595
+ throw new Error(`${crop.name}要种在${Number(crop.tier)===5?'花田,不指定菜畦':'菜田'}。`);
1596
+ }
1597
+ if (layout==='giant' && Number(crop.tier)!==5) {
1598
+ if (args.count!==undefined && count!==9) return {op,route:'invalid-giant',payload:{item,bed},localError:'菜田 3×3 固定种 9 格,count 可以省略。'};
1599
+ if (!crop.巨大) return {op,route:'invalid-giant',payload:{item,bed},localError:crop.name+'在当前房间不能长成巨型。可尝试:'+seeds.filter(seed=>seed.巨大).map(seed=>seed.name).join('、')+'。'};
1600
+ return {op,route:'plant-giant-batch',name:crop.name,payload:{cropId:crop.id,bed,buyMissing:args.buyMissing===true,fallback}};
1601
+ }
1602
+ const payload = op==='plant' ? {cropId:crop.id,count,bed,...(args.fill?{fill:true}:{}),...(args.buyMissing?{buyMissing:true}:{})} : {item:crop.id,count,zone,bed};
1603
+ return {op, route:op+'-batch', name:crop.name, payload};
1604
+ }
1605
+
1606
+ // Previous harvests in this batch provide exact plot IDs for a subsequent replant.
1607
+ async function harvestForBatch(payload, write, work) {
1608
+ const before = await work.farm();
1609
+ const harvested = await write('harvest-batch',payload);
1610
+ work.update(harvested);
1611
+ const plots = new Map(before.plots.map(plot=>[plot.id,plot]));
1612
+ const claimed = harvested.harvestedPlots || (harvested.plotIds||[]).map(id=>({id,cropId:payload.item||plots.get(id)?.cropId}));
1613
+ for (const {id,cropId} of claimed) if (cropId) work.harvested.set(id,cropId);
1614
+ harvested.claimed = claimed;
1615
+ return harvested;
1616
+ }
1617
+
1618
+ async function executeAction(action, write, work, harvestOptions) {
1619
+ const {op, route, payload, name} = action;
1620
+ if (action.localError) return {ok:false,说:action.localError,wallet:work.wallet};
1621
+ if (route==='sell-current') {
1622
+ if (!work.lots.size) return {ok:false,说:'本批没有新收获可在此步出售,现有库存没有扣减。',wallet:work.wallet};
1623
+ const lines=[];
1624
+ let ok=true;
1625
+ const lots=[...work.lots.values()];
1626
+ for (const {id,kind,name,quantity} of lots) {
1627
+ try {
1628
+ const sold=await write('sell',{id,kind,数量:quantity});
1629
+ work.update(sold);
1630
+ work.consume(id,sold.卖出.n);
1631
+ lines.push(saleReceipt(sold));
1632
+ } catch(error) {
1633
+ ok=false; work.update(error.result||{}); lines.push(`${name}没有卖出:${error.message}`);
1634
+ }
1635
+ }
1636
+ if (lots.some(lot=>lot.kind==='fish')) lines.push('卖完后鱼篓成鱼:'+inventoryLine(work.wallet?.fish)+'。');
1637
+ return {ok,说:lines.join(' '),wallet:work.wallet};
1638
+ }
1639
+ if (op==='replant') {
1640
+ const {item,count,buyMissing} = payload;
1641
+ const prior = [...work.harvested].filter(([,crop])=>!item || crop===item);
1642
+ const lines = [];
1643
+ let wallet, allOk = true;
1644
+ if (!prior.length) {
1645
+ const result = await harvestForBatch({item,count,forReplant:true},write,work);
1646
+ work.collect(result.collectedItems);
1647
+ lines.push(result.say); wallet=result.wallet;
1648
+ }
1649
+ const exact = prior.length ? prior.slice(0,count) : [...work.harvested].filter(([,crop])=>!item || crop===item);
1650
+ const groups = new Map();
1651
+ for (const [id,crop] of exact) {
1652
+ if (!groups.has(crop)) groups.set(crop,[]);
1653
+ groups.get(crop).push(id);
1654
+ }
1655
+ wallet ??= work.wallet;
1656
+ if (!groups.size) return {ok:false,说:lines.join(' ')||'没有可补种的地块。',wallet};
1657
+ for (const [crop,plotIds] of groups) {
1658
+ try {
1659
+ const missing=Math.max(0,plotIds.length-(wallet.seeds?.[crop]||0));
1660
+ if (buyMissing && missing) {
1661
+ const bought=await write('buy',{kind:'seed',id:crop,数量:missing}); work.update(bought); wallet=bought.wallet;
1662
+ lines.push(`补买了 ${bought.买到.n} 份种子,花费 ${bought.花了} 金币。`);
1663
+ }
1664
+ if (!(wallet.seeds?.[crop]>0)) {
1665
+ allOk=false; lines.push(`收成已入账,缺少种子,${plotIds.length} 格未补种。`); continue;
1666
+ }
1667
+ const planted=await write('plant-batch',{cropId:crop,count:plotIds.length,plotIds});
1668
+ work.update(planted); wallet=planted.wallet; lines.push(planted.say);
1669
+ for (const id of planted.plotIds||[]) work.harvested.delete(id);
1670
+ if (planted.count<plotIds.length) { allOk=false; lines.push(`还有 ${plotIds.length-planted.count} 格未补种。`); }
1671
+ } catch(error) { work.update(error.result || {}); wallet=work.wallet; allOk=false; lines.push('收成已入账,补种未全部完成:'+error.message); }
1672
+ }
1673
+ return {ok:allOk,说:lines.join(' '),wallet};
1674
+ }
1675
+ const result = op==='harvest' && harvestOptions.forReplant
1676
+ ? await harvestForBatch({...payload,...harvestOptions},write,work)
1677
+ : await write(route,{...payload,...harvestOptions});
1678
+ work.update(result);
1679
+ let 说 = result.say;
1680
+ if (op==='buy') 说 = `买了 ${result.买到.n} 份${name}${payload.kind==='fish'?'鱼苗':'种子'},花费 ${result.花了} 金币。`;
1681
+ if (op==='sell') {
1682
+ work.consume(payload.id,result.卖出.n);
1683
+ 说 = saleReceipt(result);
1684
+ }
1685
+ work.collect(result.collectedItems);
1686
+ if (op==='stock' || op==='catch') 说 = 鱼塘回执(result,op,name);
1687
+ return {ok:true,说,wallet:result.wallet,claimed:result.claimed};
1688
+ }
1689
+
1458
1690
  return {
1459
1691
  name:'fish_home_farm',
1460
- description:'批量种田、养鱼与买卖。收熟作物并补种同品种,一次用 replant + item;获准花钱补足种子时加 buyMissing:true,不用先查地、分别收、买、种或查余额。仅收获、浇水或捞鱼,省略 item 一次处理全部,count 可限量。种 10 格用 plant + item + count。list 默认摘要,scope:layout 看 3×3 布局。',
1692
+ description:'种田、养鱼和买卖。用一次 batch 交全单。收、卖、原地补种可按 actions 顺序填 harvest → sell → replant;replant 会用本批刚收的地。sell 不填品种和数量,只卖本批刚收获或刚捞的,免查背包。只收后补种时,actions 里放一项 replant(可填 item)。种满某片田用 plant + fill=true,不查地、不猜数量;菜田巨型候选用 plant + layout=giant 找 3×3。花田普通播种,每朵花成熟时独立有 15% 概率变异。获准花钱才用 buyMissing,不另加 buy。stock 可用同批唯一买过的鱼种。没空区直接回报,允许普通备选才填 fallback=normal。以回执为准,无需重复查询。',
1461
1693
  parameters:{type:'object',properties:{
1462
- op:{type:'string',enum:['list','plant','water','harvest','replant','buy','sell','stock','feed','catch']},
1463
- buyMissing:{type:'boolean',description:'仅用于 replant;明确允许花金币时才填 true,按缺少的份数补买。默认只用现有种子。'},
1464
- item:{type:'string',description:'品种 ID 或中文名。'},
1465
- kind:{type:'string',enum:['seed','fish','crop','giant'],description:'商品分类,仅用于买卖。'},
1466
- zone:{type:'string',enum:['vegetable','flower'],description:'批量浇水或收获的分区,省略则处理两区。'},
1467
- bed:{type:'integer',minimum:0,maximum:2,description:'指定 0 到 2 号菜畦,适用于播种,或用 list+layout 看逐格布局。'},
1468
- count:{type:'integer',minimum:1,maximum:999,description:'数量。收获、浇水、补种和捞鱼默认全部符合条件的;播种和放养默认 1。'},
1469
- scope:{type:'string',enum:['farm','pond','layout','all'],description:'list 的查询范围,layout 查看真实 3×3 布局。'},
1694
+ op:{type:'string',enum:['batch','list']},
1695
+ actions:{type:'array',minItems:1,maxItems:16,items:{type:'object',properties:actionFields,required:['op'],additionalProperties:false},description:'batch 的完整操作列表,按顺序执行。多个品种各放一项,数量填 count。'},
1696
+ scope:{type:'string',enum:['farm','pond','layout','all'],description:'list 的查询范围。'},
1697
+ bed:{type:'integer',minimum:0,maximum:2,description:'list + layout 时展开指定菜畦。'},
1470
1698
  },required:['op'],additionalProperties:false},
1471
1699
  output:textOutput,
1472
1700
  async execute(args={}, exec) {
1473
- const {op, zone, bed} = args;
1474
- const item=string(args.item);
1475
- const count=args.count??(['harvest','water','replant'].includes(op)?65:op==='catch'?8:1);
1476
- const operations=['list','plant','water','harvest','replant','buy','sell','stock','feed','catch'];
1701
+ const {op,bed} = args;
1477
1702
  const request = (route,params) => roomRequest('/api/farm'+route,params,8000,exec?.signal);
1478
- const activeTurn=当前轮.get(目标会话());
1479
- if(activeTurn&&!rounds.has(activeTurn))rounds.set(activeTurn,new Set());
1480
- const tried=activeTurn&&rounds.get(activeTurn);
1481
- const once = async (kind,payload,run) => {
1482
- const key=JSON.stringify([kind,Object.fromEntries(Object.entries(payload||{}).sort(([a],[b])=>a.localeCompare(b)))]);
1483
- if(进行中的批量操作.has(key)||tried?.has(key)){
1484
- throw Object.assign(new Error('这项相同的操作本轮已提交,请使用原回执。'),{code:'DUPLICATE_FARM_OPERATION'});
1485
- }
1486
- tried?.add(key);
1487
- 进行中的批量操作.add(key);
1488
- try{return await run()}
1489
- finally{进行中的批量操作.delete(key)}
1490
- };
1491
- const write = (kind,payload) => request('/'+kind,{...payload,requestId:randomUUID(),actor:'dayu'});
1492
- const mutate = (kind,payload) => once(kind,payload,()=>write(kind,payload));
1703
+
1493
1704
  try {
1494
- if(!operations.includes(op))throw new Error('需要有效的 op。');
1495
- if(!Number.isSafeInteger(count)||count<1||count>999)throw new Error('数量必须是正整数。');
1496
1705
  if(op==='list') {
1497
1706
  if(args.scope!=='layout')return {ok:true,说:farmSummary(await request(''),args.scope)};
1498
1707
  if(bed!==undefined&&![0,1,2].includes(bed))throw new Error('菜畦编号为 0 到 2。');
1499
- const {beds}=await request('/layout'+(bed===undefined?'':'?bed='+bed));
1500
- const lines=[];
1708
+ const {beds,flowers}=await request('/layout'+(bed===undefined?'':'?bed='+bed));
1709
+ const emptyVeg=beds.reduce((n,field)=>n+field.blocks.reduce((sum,b)=>sum+b.empty,0),0);
1710
+ const emptyFlowers=flowers?.filter(p=>!p.cropId).length;
1711
+ const lines=[bed===undefined?(flowers?`总空位 ${emptyVeg+emptyFlowers} 格:菜田 ${emptyVeg}、花田 ${emptyFlowers}。`:`菜田共空 ${emptyVeg} 格。`):`菜畦 ${bed} 共空 ${emptyVeg} 格。`];
1501
1712
  for(const field of beds){
1502
1713
  const blocks=field.blocks.map((block,i)=>{
1503
1714
  const marks=block.crops.map(c=>c.name+'×'+c.count);
@@ -1508,71 +1719,106 @@ function 起来(ctx, 配置参数 = {}) {
1508
1719
  });
1509
1720
  lines.push('bed-'+field.bed+'\n'+blocks.join('\n'));
1510
1721
  }
1722
+ if (flowers) lines.push('花田:'+flowers.map(p=>p.cropId?(p.giant?'巨型 ':'')+p.cropId:'空').join(' · '));
1511
1723
  return {ok:true,说:lines.join('\n\n')};
1512
1724
  }
1513
- if(op==='feed')return {ok:true,说:(await mutate('feed',{})).say};
1514
- if(args.plotId!==undefined)throw new Error('播种、浇水和收获已改成批量。请用 item、zone 或 count,不需要地块编号。');
1515
- if(['plant','water','harvest','replant'].includes(op)&&count>65)throw new Error('田地操作一次最多 65 格。');
1516
- if(['stock','catch'].includes(op)&&count>8)throw new Error('池塘操作一次最多 8 条。');
1517
- if(['water','harvest'].includes(op)&&!item){
1518
- const result = await mutate(op+'-batch',{count,zone});
1519
- return {ok:true,说:result.say};
1520
- }
1521
- if(op==='catch'&&!item){
1522
- const result=await mutate('catch-batch',{count});
1523
- return {ok:true,说:鱼塘回执(result,'catch')};
1725
+ // Keep accepting old single-action requests while the model learns the new schema.
1726
+ const entries = op==='batch' ? args.actions : [args];
1727
+ if (!Array.isArray(entries) || !entries.length || entries.length>16) throw new Error('请在 actions 中填写 1 到 16 项农活。');
1728
+ let catalog;
1729
+ const getCatalog = () => catalog ??= request('');
1730
+ const turn = 当前轮.get(目标会话());
1731
+ const actions = [];
1732
+ for (const [index, entry] of entries.entries()) {
1733
+ try {
1734
+ if (!entry || typeof entry!=='object' || Array.isArray(entry)) throw new Error('请填写操作对象。');
1735
+ if (op==='batch' && Object.keys(entry).some(key=>!Object.hasOwn(actionFields,key))) throw new Error('该项包含不支持的参数。');
1736
+ let normalized=entry;
1737
+ if (entry.op==='stock' && !string(entry.item)) {
1738
+ const purchased=new Set(actions.filter(step=>step.op==='buy'&&step.payload.kind==='fish').map(step=>step.payload.id));
1739
+ if (purchased.size!==1) throw new Error('放苗请指定鱼种;同一批前面只买了一种鱼苗时可以省略。');
1740
+ normalized={...entry,item:[...purchased][0]};
1741
+ }
1742
+ const action=await plan(normalized,getCatalog);
1743
+ if (action.route==='sell-current' && !actions.some(prev=>['harvest','replant','catch'].includes(prev.op))) {
1744
+ throw new Error('只卖本批收获时,请在 sell 前安排收获或捞鱼;要卖背包库存请指定品种和数量。');
1745
+ }
1746
+ actions.push(action);
1747
+ } catch (error) {
1748
+ throw new Error(op==='batch' ? `整批未执行:第 ${index+1} 项:${error.message.replace(/[。;]+$/,'')}。前面的项目也没有提交。` : error.message);
1749
+ }
1524
1750
  }
1525
- const data=await request('');
1526
- const seeds=data.商店||[], fish=data.鱼||[], giants=data.giantItems||[];
1527
- const match=catalog=>catalog.find(x=>x.id===item||x.name===item);
1528
- if(op==='replant'){
1529
- const crop=match(seeds);
1530
- if(!crop||zone!==undefined||bed!==undefined)throw new Error('收后补种需要一个作物品种,不用填 zone 或 bed。');
1531
- return await once('replant',{item:crop.id,count,buyMissing:args.buyMissing===true},async()=>{
1532
- const harvested=await write('harvest-batch',{item:crop.id,count});
1533
- const plots=harvested.plotIds?.length||0;
1534
- const lines=[harvested.say];
1535
- let wallet=harvested.wallet;
1536
- try{
1537
- const missing=Math.max(0,plots-(wallet.seeds?.[crop.id]||0));
1538
- if(args.buyMissing===true&&missing){
1539
- const bought=await write('buy',{kind:'seed',id:crop.id,数量:missing});
1540
- wallet=bought.wallet;
1541
- lines.push(`补买了 ${bought.买到.n} 份种子,花费 ${bought.花了} 金币。`);
1751
+ const run = async () => {
1752
+ const progress = turn ? (turn.farmWork ??= {batches:0,receipts:new Map()}) : {batches:0,receipts:new Map()};
1753
+ const keys = actions.map(({route,payload},index)=>JSON.stringify([route,payload,...(route==='sell-current'
1754
+ ? [actions.slice(0,index).filter(action=>['harvest','replant','catch'].includes(action.op)).map(action=>[action.route,action.payload])]
1755
+ : [])]));
1756
+ const hasNewWork = keys.some(key=>!progress.receipts.has(key));
1757
+ if (hasNewWork && progress.batches>=每轮农活上限) return {ok:false,说:'本轮已执行两次农活操作。请根据已有回执回复,剩余操作下一轮再安排。'};
1758
+ let committed=false;
1759
+ const write=async (route,payload)=>{
1760
+ const result=await request('/'+route,{...payload,requestId:randomUUID(),actor:'dayu'});
1761
+ if (result.code!=='ALREADY_FULL') committed=true;
1762
+ return result;
1763
+ };
1764
+ let currentFarm;
1765
+ const work = {harvested:new Map(),lots:new Map(),wallet:null,
1766
+ collect(items){for (const item of items||[]) {
1767
+ const lot=this.lots.get(item.id);
1768
+ this.lots.set(item.id,{...item,quantity:(lot?.quantity||0)+item.quantity});
1769
+ }},consume(id,quantity){
1770
+ const lot=this.lots.get(id);
1771
+ if (!lot) return;
1772
+ lot.quantity-=quantity;
1773
+ if (lot.quantity<=0) this.lots.delete(id);
1774
+ },async farm(){
1775
+ if (!currentFarm) { const data=await getCatalog(); currentFarm=data.farm; this.wallet ??= data.wallet||data; }
1776
+ return currentFarm;
1777
+ },update(data){
1778
+ if (data.farm) currentFarm=data.farm;
1779
+ if (data.wallet) this.wallet=data.wallet;
1780
+ }};
1781
+ let lastWallet;
1782
+ const results = [];
1783
+ for (const [index, action] of actions.entries()) {
1784
+ if (exec?.signal?.aborted) break;
1785
+ const key = keys[index];
1786
+ let result = progress.receipts.get(key);
1787
+ const repeated = Boolean(result);
1788
+ if (!repeated) {
1789
+ const harvestOptions = {};
1790
+ if (action.op==='harvest') {
1791
+ const next=actions.slice(index+1);
1792
+ if (next.some(step=>step.op==='replant' &&
1793
+ (!step.payload.item || !action.payload.item || step.payload.item===action.payload.item))) harvestOptions.forReplant=true;
1794
+ const giant=next.find(step=>step.route==='plant-giant-batch');
1795
+ if (giant) harvestOptions.forGiant={cropId:giant.payload.cropId,bed:giant.payload.bed};
1542
1796
  }
1543
- if((wallet.seeds?.[crop.id]||0)>0&&plots){
1544
- const planted=await write('plant-batch',{cropId:crop.id,count:plots,plotIds:harvested.plotIds});
1545
- wallet=planted.wallet;
1546
- lines.push(planted.say);
1547
- if(planted.count<plots)lines.push(`还有 ${plots-planted.count} 格没有补种。`);
1548
- }else lines.push('背包没有种子,已收获,未补种。');
1549
- }catch(error){lines.push('已收获;补种流程未全部完成:'+error.message);}
1550
- return {ok:true,说:lines.join(' ')+' 余额 '+wallet.coins+' 金币。'};
1551
- });
1552
- }
1553
- if(op==='buy'||op==='sell'){
1554
- const found=match(op==='buy'?(args.kind==='fish'?fish:args.kind==='seed'?seeds:[...seeds,...fish]):[...seeds,...fish,...giants]);
1555
- if(!found)throw new Error('找不到这个商品。用 fish_home 的 price 查看商店。');
1556
- const kind=args.kind||(fish.includes(found)?'fish':giants.includes(found)?'giant':op==='buy'?'seed':'crop');
1557
- if(op==='buy'&&(!['seed','fish'].includes(kind)||count>99))throw new Error('一次可以买 1 到 99 份。');
1558
- const result=await mutate(op,{kind,id:found.id,数量:count});
1559
- const summary=op==='buy'?'买了 '+count+' 份'+found.name+',花费 '+result.花了+' 金币。':'卖了 '+count+' 份'+found.name+',入账 '+result.得了+' 金币。';
1560
- return {ok:true,说:summary+'余额 '+result.wallet.coins+' 金币。'};
1561
- }
1562
- if(op==='catch'||op==='stock'){
1563
- const species=match(fish)?.id;
1564
- if(species){
1565
- const result=await mutate(op+'-batch',{item:species,count});
1566
- return {ok:true,说:鱼塘回执(result,op,match(fish)?.name)};
1797
+ try { result = await executeAction(action,write,work,harvestOptions); }
1798
+ catch (error) { work.update(error.result || {}); result = {ok:false,说:error.message,wallet:error.result?.wallet}; }
1799
+ progress.receipts.set(key,result);
1800
+ }
1801
+ if (repeated && result.claimed) {
1802
+ const farm=await work.farm();
1803
+ const empty=new Set(farm.plots.filter(plot=>!plot.cropId).map(plot=>plot.id));
1804
+ for (const {id,cropId} of result.claimed) if (cropId&&empty.has(id)) work.harvested.set(id,cropId);
1805
+ }
1806
+ if (!repeated && result.wallet) lastWallet = result.wallet;
1807
+ const label = action.name ? action.name+':' : '';
1808
+ const receipt = repeated ? '本轮已提交,原回执:'+result.说 : result.说;
1809
+ results.push({ok:result.ok,说:op==='batch'?`${index+1}. ${label}${receipt}`:receipt});
1567
1810
  }
1568
- throw new Error('请指定有效的鱼种。要捞不限品种的成鱼,可只填写数量。');
1569
- }
1570
- const crop=item?match(seeds):null;
1571
- if((item||op==='plant')&&!crop)throw new Error('请指定有效的种子或作物品种。');
1572
- const payload=op==='plant'?{cropId:crop.id,count,bed}:{item:crop?.id,count,zone};
1573
- return {ok:true,说:(await mutate(op+'-batch',payload)).say};
1811
+ if (committed) progress.batches++;
1812
+ const lines = results.map(row=>row.说);
1813
+ if (op==='batch' && results.some(row=>!row.ok)) lines.unshift('各项独立结算,已完成的操作已入账;未完成的见下。');
1814
+ if (results.length<actions.length) lines.push(`已停止,还有 ${actions.length-results.length} 项未提交。`);
1815
+ if (lastWallet && (op==='batch' || ['replant','buy','sell'].includes(op))) lines.push(`余额 ${lastWallet.coins} 金币。`);
1816
+ return {ok:results.length===actions.length&&results.every(row=>row.ok),说:lines.join(op==='batch'?'\n':' ')};
1817
+ };
1818
+ const receipt = pending.then(run);
1819
+ pending = receipt.catch(()=>{});
1820
+ return await receipt;
1574
1821
  } catch (error) {
1575
- if(error.code==='DUPLICATE_FARM_OPERATION')return {ok:true,说:error.message};
1576
1822
  return {ok:false,说:error.message};
1577
1823
  }
1578
1824
  },
@@ -1741,6 +1987,8 @@ function 起来(ctx, 配置参数 = {}) {
1741
1987
 
1742
1988
  // 会话一醒就把房间时间挂上(这时候才有 agent.ctx.systemPrompt 可挂)
1743
1989
  if (event.type === 'turn/start') {
1990
+ const existing = 当前轮.get(sid);
1991
+ if (existing && existing.turn===event.data?.turn) return;
1744
1992
  当前轮.set(sid, { turn: event.data?.turn, replies: [], direct: false, 身体工具:false })
1745
1993
  挂agent工具(找agent(sid))
1746
1994
  // 「她开始想了」——房间那边收到就冒个气泡,别让人干等
@@ -2159,7 +2407,7 @@ function 起来(ctx, 配置参数 = {}) {
2159
2407
  let 体
2160
2408
  try { 体 = await 读体(req) } catch (error) { return 回错(res, 400, 'BAD_BODY', String((error && error.message) || error)) }
2161
2409
  if (!体 || 体.schema !== PET_STATE_SCHEMA) return 回错(res, 400, 'BAD_SCHEMA', '这份数据的版本不对')
2162
- const 旧天气 = String(房间环境?.weather || '')
2410
+ const 旧天气 = String(最近状态?.snapshot?.weather || '')
2163
2411
  收下环境(体.snapshot)
2164
2412
  if(typeof 体.room?.url==='string'){
2165
2413
  try{
@@ -2226,13 +2474,15 @@ function 起来(ctx, 配置参数 = {}) {
2226
2474
  try {
2227
2475
  await agent.followup({id:randomUUID(),role:'user',source:{kind:'fish-home-life'},
2228
2476
  content:[{type:'text',text:'【鱼鱼窝】'+事件.text.slice(0,300)}]})
2477
+ 事件.notified = true
2229
2478
  } catch (error) {
2230
2479
  return 回错(res,502,'SEND_FAILED','生活事件没送进会话')
2231
2480
  } finally {互动送达中.delete(id)}
2232
2481
  }
2233
2482
  }
2234
- if (事件.kind === 'scene' && 配置.开 && 目标会话() && Math.abs(Date.now() - 事件.at) < SCENE_TTL_MS) {
2235
- 最近场景 = { sid: targetSession, at: 事件.at, text: 事件.text.slice(0, 240) }
2483
+ if (事件.kind === 'scene' && 配置.开 && targetSession && Math.abs(Date.now() - 事件.at) < SCENE_TTL_MS) {
2484
+ // A scene already delivered as a message does not need a second copy in context or status.
2485
+ if (事件.at >= (最近场景?.at||0)) 最近场景 = 事件.notified ? null : { sid: targetSession, at: 事件.at, text: 事件.text.slice(0, 240) }
2236
2486
  }
2237
2487
  生活事件.push(事件)
2238
2488
  if (生活事件.length > 200) 生活事件.shift()
@@ -2446,7 +2696,7 @@ function 起来(ctx, 配置参数 = {}) {
2446
2696
  const 自查更新 = createSelfUpdate({ packageRoot: fileURLToPath(new URL('..', import.meta.url)), diag: 记一笔 })
2447
2697
  // 「查更新」和「一键更新」这两个路由由 selfupdate 自己注册 —— 跟其它五个插件是同一份实现。
2448
2698
  // 准入用同源检查:本机别的网页不该能触发安装。
2449
- 自查更新.register(ctx, 管理前缀 + '/update', (req) => (同源(req) ? null : { 码: 403, 说: '只给本页用' }))
2699
+ 自查更新.register(ctx, 管理前缀, (req) => (同源(req) ? null : { 码: 403, 说: '只给本页用' }))
2450
2700
 
2451
2701
  // 房间本体:插件不带它(三百多兆),所以设置页得告诉人「装没装、去哪下」。
2452
2702
  // 找的路径顺序跟启动时完全一致,不然会出现「界面说装了、启动却说找不到」。
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-fish-home",
3
- "version": "0.1.1",
3
+ "version": "0.1.3",
4
4
  "description": "鱼鱼窝:把「大肥鱼的小日子」那个 3D 房间接进 DSH —— 房间里打字能送到会话里,会话里回的话、她自己打的字,都顺着事件流回到房间里。",
5
5
  "license": "SEE LICENSE IN LICENSE",
6
6
  "engines": {