cortico-world-feast 0.7.0 → 0.7.1

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,5 +1,37 @@
1
1
  # 更新日志
2
2
 
3
+ ## 0.7.1
4
+
5
+ **和「生图工作室」联动:穿着、地点跟着日程走**
6
+
7
+ 0.7.0 给日程加了 `outfit` / `scene` / `props` / `situation` 字段,但「只是纯文本,不接生图素材库」——她很少填,模板兜底也不带穿搭。这一版把这条界限打开了:两个 World 各跑各的,不调对方的工具(契约不允许),只靠**共享素材库的文件约定 + 提示词里各写一句指向对方**。
8
+
9
+ **扫库(`src/life/wardrobe.js`)**
10
+
11
+ 读生图工作室的素材库下 `characters / outfits / scenes / props` 每个条目的 `entry.json`,带缓存(mtime 没变就不重扫)。**库目录自动跟 imggen 走**:优先读 Coo config 里 `worlds.imggen.libraryRoot`(用户在 imggen 那边改了库目录,这边自动跟上,不会摸到空库);读不到再降级到默认 `<数据目录>/imggen-library`;`lifeWardrobeDir` 可手动覆盖。config.json 是 Coo 整份重写的,解析失败时等 200ms 重试一次再降级,避开「读到写一半的文件」窗口。**读不到就静默降级**:目录不存在、entry.json 坏了、四类全空——一律返回空库,绝不抛错、绝不影响她的一天、绝不影响生图工作室。
12
+
13
+ **自动补 `outfit`**
14
+
15
+ 模型没填时按优先级补:① 模型自己填的(能对上库就归一成正名,对不上保留原词)→ ② 情境穿搭 `outfitByContext`(她显式配的「睡前→睡衣」习惯)→ ③ 情境默认(没配习惯时,按 situation 关键词查内置常识表,库里 find 到才用——这是库能开箱即用的关键)→ ④ 延续上一段(没标情境或情境没命中时,接着上一段穿;睡觉那段不延续)→ ⑤ 场景默认 → ⑥ 她的 `defaultOutfit`。睡觉段没标情境不硬猜。`scene` / `props` 也归一成正名,让 `imggen_draw` 的别名解析更稳。
16
+
17
+ **散图条目安全**
18
+
19
+ 参考库支持散图条目(直接把图片丢进目录不建子文件夹),没有 `entry.json`。读取逻辑只认目录、且目录里有合法 `entry.json` 才是标准条目;图片文件、无 entry.json 的目录、坏 JSON 一律跳过,不让整个库读崩。
20
+
21
+ **提示词指向句**
22
+
23
+ `envPromptVars()` 的 `{{feast_life_block}}` 里加一句「想发图时穿着地点按日程来」(库非空才加,几十 token 常驻,一天变一两次级别);`planEventText` 列出衣柜/场景/道具和穿搭习惯,让她写日程时用库里的正名。对方在他们的 ENV_PROMPT 加反向的一句就够了。
24
+
25
+ **配置**
26
+
27
+ - `lifeWardrobeOn`(默认开):联动总开关。关掉 = 纯文本日程,不扫库、不补、不注入。
28
+ - `lifeWardrobeDir`(默认空):素材库目录手动覆盖,最高优先级。留空时自动跟 imggen 的 `libraryRoot`,读不到再降级到 `<数据目录>/imggen-library`。
29
+ - `lifeWardrobeAutoOutfit`(默认开):自动补 outfit。关掉 = 只列库不补。
30
+
31
+ **没做的(刻意)**
32
+
33
+ 不做双向共享状态文件、不调 `imggen_draw`、不让对方读我们的日程文件——都接近契约禁止的「一个 World 依赖另一个扩展」。联动靠「共享库 + 提示词指认」,她自己在同一回合里串起来。
34
+
3
35
  ## 0.7.0
4
36
 
5
37
  **她的一天:一套她自己给自己排的日程**
@@ -37,7 +69,7 @@
37
69
 
38
70
  **界限**
39
71
 
40
- - `scene` / `outfit` / `props` 只是纯文本,**不接生图素材库**。
72
+ - `scene` / `outfit` / `props` 只是纯文本,**不接生图素材库**(0.7.1 起这条界限被联动打开,见上)。
41
73
  - 日程存 `<数据目录>/feast/life/YYYY-MM-DD.json`,一天一个文件、原子写。**三份数据互不牵连**(吃过的 / 攒的桌 / 她的日子)——存储页因此变三项。
42
74
  - `envPromptVars()` 全程 `try/catch`,**永不抛错**(抛错会把 World 卸载)。关掉时返回空字符串而不是 `null`——`null` 会把整份 `ENV_PROMPT` 一起省略。
43
75
  - **`lifeFreeGoal` 是叫醒上限,不是任务额度**:到了只表示不再按点叫,想动随时能动、记了照样算;清单只是例子;`feast_life_start` 不用等叫醒。
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cortico-world-feast",
3
- "version": "0.7.0",
3
+ "version": "0.7.1",
4
4
  "description": "一桌菜 · 给 Coo 一张会端菜的桌子:800 道带九维口味的菜(28 个菜系组),她能自己挑,主人能从面板端一道或整桌过去,也能和她一起吃一顿。0.7.0 起她还有自己的日子:每晚自己写明天怎么过,到点过自己的时间、做完记一笔。",
5
5
  "license": "MIT",
6
6
  "author": "青",
@@ -45,13 +45,13 @@
45
45
  "node": ">=22.6"
46
46
  },
47
47
  "scripts": {
48
- "test": "node test/dishes.test.mjs && node test/eat.test.mjs && node test/state.test.mjs && node test/combos.test.mjs && node test/together.test.mjs && node test/life.test.mjs && node test/life-world.test.mjs && node test/world.test.mjs && node test/panels.test.mjs",
48
+ "test": "node test/dishes.test.mjs && node test/eat.test.mjs && node test/state.test.mjs && node test/combos.test.mjs && node test/together.test.mjs && node test/life.test.mjs && node test/wardrobe.test.mjs && node test/life-world.test.mjs && node test/world.test.mjs && node test/panels.test.mjs",
49
49
  "dishes": "node tools/validate-dishes.mjs",
50
50
  "selfcheck": "node tools/selfcheck.mjs",
51
51
  "check:install": "node tools/check-install.mjs",
52
52
  "check:publish": "node tools/publish-check.mjs --online",
53
53
  "describe": "node tools/make-describe.mjs",
54
- "prepublishOnly": "node tools/validate-dishes.mjs && node tools/selfcheck.mjs && node tools/publish-check.mjs --online && node test/dishes.test.mjs && node test/eat.test.mjs && node test/state.test.mjs && node test/combos.test.mjs && node test/together.test.mjs && node test/life.test.mjs && node test/life-world.test.mjs && node test/world.test.mjs && node test/panels.test.mjs && node tools/make-describe.mjs --check"
54
+ "prepublishOnly": "node tools/validate-dishes.mjs && node tools/selfcheck.mjs && node tools/publish-check.mjs --online && node test/dishes.test.mjs && node test/eat.test.mjs && node test/state.test.mjs && node test/combos.test.mjs && node test/together.test.mjs && node test/life.test.mjs && node test/wardrobe.test.mjs && node test/life-world.test.mjs && node test/world.test.mjs && node test/panels.test.mjs && node tools/make-describe.mjs --check"
55
55
  },
56
56
  "cortico": {
57
57
  "kind": "world",
package/src/config.js CHANGED
@@ -98,6 +98,13 @@ export const DEFAULTS = Object.freeze({
98
98
  ].join('\n'),
99
99
  /** 做完要不要提醒她跟主人说一句。 */
100
100
  lifeFreeAskReport: true,
101
+ // ---- 生图工作室联动(0.7.1)----
102
+ /** 联动总开关:扫素材库、列给 Coo、自动补 outfit、注入指向句。关掉=纯文本日程,不碰库。 */
103
+ lifeWardrobeOn: true,
104
+ /** 素材库目录;留空 = 用默认路径 <数据目录>/imggen-library(和生图工作室默认一致)。 */
105
+ lifeWardrobeDir: '',
106
+ /** 自动补 outfit:模型没填时按「延续上一段 > 情境穿搭 > 场景默认 > 默认服饰」补。关掉只列库不补。 */
107
+ lifeWardrobeAutoOutfit: true,
101
108
  });
102
109
 
103
110
  const ZH = {
@@ -173,6 +180,12 @@ const ZH = {
173
180
  lifeFreeMenuDesc: '原样贴进叫醒事件里,措辞上明确写着「这些只是例子,不照着也行」。默认只写通用说法(不点名别的扩展的工具——World 不该依赖别的扩展)。想让她真用上某个工具,在这里写明,例如「去花语乡转转(bloom_inbox peek)」。改完下一档生效。',
174
181
  lifeFreeAskReport: '做完说一声',
175
182
  lifeFreeAskReportDesc: '开启时,叫醒和记账回执都会提醒她「跟主人说一句你刚才玩了什么」。',
183
+ lifeWardrobeOn: '生图联动',
184
+ lifeWardrobeOnDesc: '扫生图工作室的素材库(<数据目录>/imggen-library),写日程时列出衣柜/场景/道具和穿搭习惯,模型没填 outfit 时按习惯自动补,并在提示词里加一句指向生图工作室。关掉=纯文本日程,不碰库、不联动。库读不到时自动静默降级,不影响她的一天。',
185
+ lifeWardrobeDir: '素材库目录',
186
+ lifeWardrobeDirDesc: '生图工作室的素材库根目录;留空时自动读 imggen 的 libraryRoot(用户在 imggen 那边改了库目录,这边自动跟上),读不到再降级到 <数据目录>/imggen-library。手动填这里只用于 imggen 没配 libraryRoot 又想指定路径的情况。',
187
+ lifeWardrobeAutoOutfit: '自动补穿着',
188
+ lifeWardrobeAutoOutfitDesc: '模型没写 outfit 时,按「延续上一段 > 情境穿搭(睡前→睡衣这种)> 场景默认 > 她的默认服饰」补上。关掉=只列库不补,写成什么就是什么。',
176
189
  },
177
190
  storage: {
178
191
  label: '吃过的记录',
@@ -257,6 +270,12 @@ const EN = {
257
270
  lifeFreeMenuDesc: 'Pasted verbatim into the wake-up event, worded so it is clear these are only examples. Defaults stay generic on purpose — a World must not depend on another extension. To point her at a specific tool, name it here, e.g. "go for a walk (bloom_inbox peek)".',
258
271
  lifeFreeAskReport: 'Tell the owner',
259
272
  lifeFreeAskReportDesc: 'When on, both the wake-up and the logging receipt remind her to say one sentence about what she just did.',
273
+ lifeWardrobeOn: 'Image-gen link',
274
+ lifeWardrobeOnDesc: 'Scans the image-gen studio library (<dataDir>/imggen-library), lists wardrobe/scene/props and outfit habits when she writes her day, auto-fills outfit from habits when the model leaves it blank, and adds one line in the prompt pointing at the studio. Off = plain-text schedule, no library, no link. Degrades silently when the library is missing; her day is never affected.',
275
+ lifeWardrobeDir: 'Library root',
276
+ lifeWardrobeDirDesc: 'Root of the image-gen studio library; blank = auto-follow imggen libraryRoot (if the user changed it in imggen, this follows), then fall back to <dataDir>/imggen-library. Set this manually only when imggen has no libraryRoot and you need a specific path.',
277
+ lifeWardrobeAutoOutfit: 'Auto-fill outfit',
278
+ lifeWardrobeAutoOutfitDesc: 'When the model omits outfit, fill it by: carry the previous slot > context habit (bedtime→pyjamas) > scene default > her default outfit. Off = list the library but do not fill; whatever she wrote stays.',
260
279
  },
261
280
  storage: {
262
281
  label: 'Eating history',
@@ -524,6 +543,24 @@ export function configGroup(language = 'zh') {
524
543
  description: t.lifeFreeAskReportDesc,
525
544
  'x-hot': true,
526
545
  },
546
+ [`${K}.lifeWardrobeOn`]: {
547
+ type: 'boolean',
548
+ title: t.lifeWardrobeOn,
549
+ description: t.lifeWardrobeOnDesc,
550
+ 'x-hot': true,
551
+ },
552
+ [`${K}.lifeWardrobeDir`]: {
553
+ type: 'string',
554
+ title: t.lifeWardrobeDir,
555
+ description: t.lifeWardrobeDirDesc,
556
+ 'x-hot': true,
557
+ },
558
+ [`${K}.lifeWardrobeAutoOutfit`]: {
559
+ type: 'boolean',
560
+ title: t.lifeWardrobeAutoOutfit,
561
+ description: t.lifeWardrobeAutoOutfitDesc,
562
+ 'x-hot': true,
563
+ },
527
564
  },
528
565
  },
529
566
  };
package/src/life/index.js CHANGED
@@ -6,3 +6,4 @@ export * from './store.js';
6
6
  export * from './inject.js';
7
7
  export * from './plan.js';
8
8
  export * from './free.js';
9
+ export * from './wardrobe.js';
@@ -26,7 +26,7 @@ function timeLabel(precision, minute) {
26
26
  const placeOf = (it) => (it.scene || it.location ? `(${it.scene || it.location})` : '');
27
27
 
28
28
  /** 环境提示词里那一整段;关掉「她的一天」时返回空字符串。 */
29
- export function envBlock({ today, tomorrow = null, cfg = {}, tz = 'Asia/Shanghai', nowMs = Date.now(), who = {} } = {}) {
29
+ export function envBlock({ today, tomorrow = null, cfg = {}, tz = 'Asia/Shanghai', nowMs = Date.now(), who = {}, wardrobe = '' } = {}) {
30
30
  if (cfg.lifeEnabled === false) return '';
31
31
  const z = zonedNow(tz, nowMs);
32
32
  const lines = [
@@ -50,6 +50,8 @@ export function envBlock({ today, tomorrow = null, cfg = {}, tz = 'Asia/Shanghai
50
50
  }
51
51
  const voice = voiceText(cfg, who);
52
52
  if (voice) lines.push(voice);
53
+ // 生图联动指向句:库非空才加(wardrobeHintLine 的结果),进前缀(一天变一两次级别,不变)。
54
+ if (wardrobe) lines.push(wardrobe);
53
55
  lines.push(priorityLine(who.name));
54
56
  lines.push(TOOL_LINE);
55
57
  return safe(lines.join('\n'));
package/src/life/plan.js CHANGED
@@ -8,18 +8,25 @@
8
8
  import { cleanDay } from './store.js';
9
9
  import { dateLabel } from './time.js';
10
10
 
11
- /** 事件正文:给她的写作要求(她看得到),也是工具参数的格式说明。 */
12
- export function planEventText({ date, type, recent = '', mealSlots = '11:30,18:00', who = {} } = {}) {
11
+ /**
12
+ * 事件正文:给她的写作要求(她看得到),也是工具参数的格式说明。
13
+ *
14
+ * `wardrobe` 是 wardrobeText(lib) 的结果:库非空时在这里列出衣柜/场景/道具/穿搭习惯,
15
+ * 让她写日程时 outfit / scene / props 用库里的正名,生图工作室那边解析才稳。
16
+ * 库读不到就是空串,这段就省掉(不强指不存在的东西)。
17
+ */
18
+ export function planEventText({ date, type, recent = '', mealSlots = '11:30,18:00', who = {}, wardrobe = '' } = {}) {
13
19
  const name = who.name || '她';
14
20
  const lines = [
15
21
  `【一桌菜 · 她的一天】该想想 ${dateLabel(date)}(${date})怎么过了。不是主人找你,也不是待办,是你自己的日子。`,
16
22
  `这一天按「${type?.name || '普通的一天'}」来:${type?.guide || '照你平常的样子过一天。'}`,
17
23
  ];
18
24
  if (recent) lines.push(`最近几天:\n${recent}`);
25
+ if (wardrobe) lines.push(wardrobe);
19
26
  lines.push(`饭点照旧是 ${mealSlots},别把这两段排成别的事;吃饭那几段可以写去哪儿吃、和谁一起。`);
20
- lines.push('想好之后用 feast_life_plan 交回:date 填这一天,dayType 填日型的 id,title 一句话,mood 一句话,items 从 00:00 排到 24:00、不重叠不留空档,每段写 { start, end, activity, location, detail },想写穿了什么、手边有什么也可以加 outfit / props。');
27
+ lines.push('想好之后用 feast_life_plan 交回:date 填这一天,dayType 填日型的 id,title 一句话,mood 一句话,items 从 00:00 排到 24:00、不重叠不留空档,每段写 { start, end, activity, location, detail },想写穿了什么、手边有什么也可以加 outfit / props / situation / scene。');
21
28
  lines.push('写的是你自己想做的事,不是任务清单;不必工整,也不用跟主人解释。交回来记好了就行,回一句「想好了」都算多。');
22
- lines.push(`(${name}临时改主意时用 feast_life_adjust;忘了自己刚才在干嘛用 feast_life_now。)`);
29
+ lines.push(`(${name}临时改主意时用 feast_life_adjust;忘了自己刚才在干嘛用 feast_life_now。想发图时穿着地点按日程里写的来。)`);
23
30
  return lines.join('\n');
24
31
  }
25
32
 
@@ -0,0 +1,446 @@
1
+ /**
2
+ * 「她的一天」×「生图工作室」联动(0.7.1)。
3
+ *
4
+ * World 契约不允许一个 World 调另一个扩展的工具,也不允许一个 World 依赖另一个扩展。
5
+ * 所以联动只做两件事,都**不碰对方的代码**:
6
+ *
7
+ * 1. **共享素材库的文件约定**:双方都读 `<数据目录>/imggen-library/`。
8
+ * 这里扫 `characters / outfits / scenes / props` 下每个条目的 `entry.json`,
9
+ * 把名字、别名、标签、情境穿搭(`outfitByContext`)、默认服饰(`defaultOutfit`)
10
+ * 读出来,列给 Coo 写日程时参考,并按优先级自动补 `outfit`。
11
+ *
12
+ * 2. **提示词里各写一句指向对方**:envBlock 里加一句「想发图时穿着地点按日程来」,
13
+ * planEventText 里列出衣柜;让对方自己在 ENV_PROMPT 加反向的一句。
14
+ *
15
+ * **降级是第一公民**:库读不到、目录不存在、entry.json 坏了——一律静默返回空库,
16
+ * 绝不抛错、绝不影响她的一天、绝不影响生图工作室。整个模块对外的每个函数都 try/catch。
17
+ *
18
+ * 字段来源(2026-11-10 读的真实 entry.json):
19
+ * { name, aliases:[], tags:[], desc, defaultOutfit, outfitByContext:{情境:服饰名}, cover }
20
+ * 同一套字段在四类条目里都有(scenes / props 的 outfitByContext / defaultOutfit 是空的,
21
+ * 但字段名一致,所以一套解析逻辑通吃)。
22
+ */
23
+ import { readFile, readdir, stat } from 'node:fs/promises';
24
+ import { join } from 'node:path';
25
+
26
+ const KINDS = ['characters', 'outfits', 'scenes', 'props'];
27
+ const text = (v, max) => (typeof v === 'string' ? v.replace(/\s+/g, ' ').trim().slice(0, max) : '');
28
+ const list = (v, max = 40) => (Array.isArray(v) ? v : []).map((x) => text(x, max)).filter(Boolean);
29
+
30
+ /**
31
+ * 空库:读不到时返回这个。`empty: true` 让调用方一句 `if (lib.empty)` 就能判断。
32
+ * 字段齐全(都是空数组),调用方不用判 undefined。
33
+ */
34
+ export function emptyWardrobe() {
35
+ return { characters: [], outfits: [], scenes: [], props: [], empty: true, at: 0 };
36
+ }
37
+
38
+ /**
39
+ * 库目录:cfg.lifeWardrobeDir 留空 = 用默认路径 <dataDir>/imggen-library。
40
+ *
41
+ * 这是**同步**版本,只处理手动覆盖和默认路径。`loadWardrobe` 用异步的
42
+ * `resolveWardrobeDir`,它还会去读 imggen 的 libraryRoot(见下)。
43
+ */
44
+ export function wardrobeDir(dataDir, cfgDir) {
45
+ const d = typeof cfgDir === 'string' ? cfgDir.trim() : '';
46
+ return d || join(dataDir, 'imggen-library');
47
+ }
48
+
49
+ /**
50
+ * 读 Coo config 里的 `worlds.imggen.libraryRoot`。
51
+ *
52
+ * 用户会在 imggen 那边改库目录(真实案例 `H:\大肥鱼桌宠\生图文件`),按默认路径读
53
+ * 会摸到空库、静默降级后联动永远不发生。这里自动跟上 imggen 的配置。
54
+ *
55
+ * 读 config 文件**不算 World 间依赖**:只是读一个文件,不调 imggen 的工具、不读它的
56
+ * 状态。config 路径按 dataDir 的父目录找(`<dataDir>/../config.json`)。
57
+ * 读不到、没有 worlds.imggen、或 libraryRoot 为空——一律返回空串,交给默认兜底。
58
+ *
59
+ * config.json 是 Coo **整份重写**的(改任何配置项都会重写一次),存在「读到写了一半
60
+ * 的文件」的窗口。解析失败时**等 200ms 重试一次**,再失败才降级——否则用户改配置
61
+ * 的那一瞬间正好触发读库,会误判成「没配置」掉回默认路径。
62
+ */
63
+ export async function readImggenRoot(dataDir) {
64
+ const tryOnce = async () => {
65
+ try {
66
+ const cfgPath = join(dataDir, '..', 'config.json');
67
+ const raw = JSON.parse(await readFile(cfgPath, 'utf8'));
68
+ const root = raw?.worlds?.imggen?.libraryRoot;
69
+ return typeof root === 'string' && root.trim() ? root.trim() : '';
70
+ } catch {
71
+ return null; // 区分「读不到/解析失败」(null) 和「读到了但没配」('')
72
+ }
73
+ };
74
+ const first = await tryOnce();
75
+ if (first !== null) return first;
76
+ // 写一半的文件窗口:等 200ms 再读一次。
77
+ await new Promise((r) => setTimeout(r, 200));
78
+ const second = await tryOnce();
79
+ return second ?? '';
80
+ }
81
+
82
+ /**
83
+ * 异步解析库目录,优先级:
84
+ * 1. cfg.lifeWardrobeDir(手动覆盖,最高)
85
+ * 2. Coo config 里 worlds.imggen.libraryRoot(自动跟 imggen)
86
+ * 3. <dataDir>/imggen-library(默认兜底)
87
+ */
88
+ export async function resolveWardrobeDir(dataDir, cfgDir) {
89
+ const manual = typeof cfgDir === 'string' ? cfgDir.trim() : '';
90
+ if (manual) return manual;
91
+ const imggenRoot = await readImggenRoot(dataDir);
92
+ if (imggenRoot) return imggenRoot;
93
+ return join(dataDir, 'imggen-library');
94
+ }
95
+
96
+ /**
97
+ * 读一个条目的 entry.json。坏文件跳过,不抛——一个手改坏的 json 不该让整个库读不出来。
98
+ * 返回 null 表示这个目录没有合法条目。
99
+ */
100
+ async function readEntry(dirPath) {
101
+ let raw;
102
+ try {
103
+ raw = JSON.parse(await readFile(join(dirPath, 'entry.json'), 'utf8'));
104
+ } catch {
105
+ return null;
106
+ }
107
+ if (!raw || typeof raw !== 'object') return null;
108
+ const name = text(raw.name, 40);
109
+ if (!name) return null;
110
+ const ctx = raw.outfitByContext && typeof raw.outfitByContext === 'object' ? raw.outfitByContext : {};
111
+ const outfitByContext = {};
112
+ for (const [k, v] of Object.entries(ctx)) {
113
+ const kk = text(k, 20);
114
+ const vv = text(v, 40);
115
+ if (kk && vv) outfitByContext[kk] = vv;
116
+ }
117
+ return {
118
+ name,
119
+ aliases: list(raw.aliases, 40),
120
+ tags: list(raw.tags, 30),
121
+ desc: text(raw.desc, 200),
122
+ defaultOutfit: text(raw.defaultOutfit, 60),
123
+ outfitByContext,
124
+ };
125
+ }
126
+
127
+ /** 扫某一类(characters/outfits/...)下所有子目录。 */
128
+ async function readKind(rootPath, kind) {
129
+ const kindDir = join(rootPath, kind);
130
+ let names = [];
131
+ try {
132
+ names = await readdir(kindDir, { withFileTypes: true });
133
+ } catch {
134
+ return [];
135
+ }
136
+ const out = [];
137
+ for (const ent of names) {
138
+ if (ent.isDirectory?.() !== true && ent.isDirectory !== true) continue;
139
+ if (ent.name.startsWith('.')) continue;
140
+ const entry = await readEntry(join(kindDir, ent.name));
141
+ if (entry) out.push(entry);
142
+ }
143
+ return out;
144
+ }
145
+
146
+ /**
147
+ * 缓存:以「目录路径」为 key。缓存命中时先 stat 目录,mtime 没变就直接用,
148
+ * 变了才重扫——每 30 秒一拍去读整个库太浪费。
149
+ *
150
+ * 缓存是模块级的(进程内单例)。测试里想强制重读,传 `force: true`。
151
+ */
152
+ const CACHE = new Map();
153
+
154
+ /**
155
+ * 加载素材库。永远不抛:出错就返回空库。
156
+ *
157
+ * @param {string} dataDir 数据目录
158
+ * @param {object} opts { cfgDir?: 覆盖库目录, force?: 强制重扫 }
159
+ * @returns {Promise<object>} 库;读不到就是空库(empty:true)
160
+ */
161
+ export async function loadWardrobe(dataDir, opts = {}) {
162
+ try {
163
+ // 优先级:手动覆盖 > imggen 的 libraryRoot > 默认路径。
164
+ // resolveWardrobeDir 会去读 Coo config,读不到就降级到默认。
165
+ const dir = await resolveWardrobeDir(dataDir, opts.cfgDir);
166
+ let mtime = 0;
167
+ try {
168
+ mtime = (await stat(dir)).mtimeMs;
169
+ } catch {
170
+ // 目录不存在:静默降级。但缓存里可能有旧的(目录被删了),清掉。
171
+ CACHE.delete(dir);
172
+ return emptyWardrobe();
173
+ }
174
+ const cached = CACHE.get(dir);
175
+ if (cached && !opts.force && cached.at === mtime) return cached.lib;
176
+
177
+ const lib = { empty: false, at: mtime };
178
+ let total = 0;
179
+ for (const kind of KINDS) {
180
+ const items = await readKind(dir, kind);
181
+ lib[kind] = items;
182
+ total += items.length;
183
+ }
184
+ if (total === 0) {
185
+ // 目录在但四类全空:也当空库,调用方就不用列「(空)」了。
186
+ return emptyWardrobe();
187
+ }
188
+ lib.empty = false;
189
+ CACHE.set(dir, { lib, at: mtime });
190
+ return lib;
191
+ } catch {
192
+ return emptyWardrobe();
193
+ }
194
+ }
195
+
196
+ /** 同步清缓存(测试用)。 */
197
+ export function clearWardrobeCache() {
198
+ CACHE.clear();
199
+ }
200
+
201
+ // ---------------------------------------------------------------------------
202
+ // 自动补 outfit
203
+ // ---------------------------------------------------------------------------
204
+
205
+ /**
206
+ * 情境默认表:situation 关键词 → 推荐的 outfit 名。
207
+ *
208
+ * entry.json 里只有显式配的 `outfitByContext`(`{"睡前":"睡衣"}`),没有「situation 自带
209
+ * 默认服饰」这份数据——那是 imggen 代码里的逻辑,我们读文件拿不到。为了让没配
210
+ * outfitByContext 的用户也能「开箱即用」(situation=睡前 时自动有睡衣),这里内置一份
211
+ * 常识默认表,库里 find 到对应 outfit 才用、find 不到就跳过(不编不存在的衣服)。
212
+ *
213
+ * situation 做包含匹配:「准备睡觉」含「睡」→ 睡衣;但字段通常是「睡前」这种短词,
214
+ * 直接查表也行。表里的 outfit 名是库里常见的正名(睡衣、通勤衬衫…),不同库可能没有,
215
+ * find 不到就继续往下走优先级。
216
+ *
217
+ * 这张表可被 cfg 覆盖(暂未开配置项,预留)。
218
+ */
219
+ const SITUATION_DEFAULTS = [
220
+ { hint: '睡', outfit: '睡衣' },
221
+ { hint: '刚醒', outfit: '睡衣' },
222
+ { hint: '通勤', outfit: '通勤衬衫' },
223
+ { hint: '上班', outfit: '通勤衬衫' },
224
+ { hint: '工作', outfit: '通勤衬衫' },
225
+ { hint: '休闲', outfit: '居家针织服' },
226
+ { hint: '居家', outfit: '居家针织服' },
227
+ { hint: '在家', outfit: '居家针织服' },
228
+ { hint: '出门', outfit: '外出外套' },
229
+ { hint: '外出', outfit: '外出外套' },
230
+ { hint: '逛街', outfit: '外出外套' },
231
+ { hint: '洗澡', outfit: '浴袍' },
232
+ { hint: '沐浴', outfit: '浴袍' },
233
+ { hint: '游泳', outfit: '泳装' },
234
+ { hint: '海边', outfit: '泳装' },
235
+ ];
236
+
237
+ /** 按 situation 关键词查情境默认表,返回推荐的 outfit 名(库里有的才算数,由调用方 find)。 */
238
+ function situationDefaultOutfit(situation) {
239
+ const sit = text(situation, 20);
240
+ if (!sit) return '';
241
+ for (const rule of SITUATION_DEFAULTS) {
242
+ if (sit.includes(rule.hint)) return rule.outfit;
243
+ }
244
+ return '';
245
+ }
246
+
247
+ /**
248
+ * 在库里找一个名字(精确名 / 别名 / 唯一包含)。找不到返回 null。
249
+ * 不依赖生图工作室那边的 findEntry:我们自己照着实现一份,保证库改了字段名我们这边不崩。
250
+ */
251
+ export function findWardrobeItem(lib, kind, name) {
252
+ const items = lib?.[kind];
253
+ if (!Array.isArray(items) || !name) return null;
254
+ const n = String(name).trim();
255
+ if (!n) return null;
256
+ let hit = items.find((it) => it.name === n);
257
+ if (hit) return hit;
258
+ hit = items.find((it) => it.aliases?.includes(n));
259
+ if (hit) return hit;
260
+ // 唯一包含:多个都包含就不取(歧义)。
261
+ const contains = items.filter((it) => it.name.includes(n) || it.aliases?.some((a) => a.includes(n)));
262
+ return contains.length === 1 ? contains[0] : null;
263
+ }
264
+
265
+ /**
266
+ * 按优先级补一段日程的 outfit。
267
+ *
268
+ * 优先级(对方补充确认后定稿):
269
+ * 1. 模型自己填的(item.outfit 非空)——直接用,只在库里能对上时归一成正名;对不上保留原词
270
+ * 2. 情境穿搭 outfitByContext[处境] ——她显式配的「睡前→睡衣」习惯,最该用
271
+ * 3. 情境默认 ——没配习惯时,按 situation 关键词查常识表(睡前→睡衣),库里 find 到才用
272
+ * 4. 延续上一段(prevOutfit)——没标情境、或情境习惯和默认都没命中时,接着上一段穿
273
+ * (起床、连续在家;睡觉那段不延续)
274
+ * 5. 场景默认 —— 库里某个场景的 defaultOutfit
275
+ * 6. 她的 defaultOutfit —— 人物条目里的默认服饰(最后兜底)
276
+ *
277
+ * 「情境默认」这级是库能开箱即用的关键:没配 outfitByContext 的用户,靠 situation
278
+ * 也能穿对衣服(睡前自动有睡衣)。它读的是 feast 内置的常识表,不依赖 imggen 代码。
279
+ *
280
+ * 库为空时返回原 outfit(不补),保证「读不到库」和「库是空的」都不改日程内容。
281
+ *
282
+ * @returns {{ outfit?: string, source?: string }} 补全结果;outfit 为空表示没补到
283
+ */
284
+ export function autoOutfit(item, lib, prevOutfit = '') {
285
+ if (!item || typeof item !== 'object') return { outfit: '', source: '' };
286
+ if (lib?.empty !== false) return { outfit: text(item.outfit, 40), source: item.outfit ? 'model' : '' };
287
+
288
+ // 1. 模型填的:能对上库就归一成正名(让 imggen_draw 解析时更稳),对不上也保留原值。
289
+ if (item.outfit) {
290
+ const match = findWardrobeItem(lib, 'outfits', item.outfit);
291
+ return { outfit: match ? match.name : text(item.outfit, 40), source: 'model' };
292
+ }
293
+
294
+ const sleeping = /睡/.test(String(item.activity));
295
+ const char = lib.characters[0];
296
+ const sit = text(item.situation, 20);
297
+
298
+ // 2. 情境穿搭:她标了 situation 且习惯里有这一条——这是她自己写的强信号,最该用。
299
+ if (char?.outfitByContext && sit) {
300
+ const v = char.outfitByContext[sit];
301
+ if (v) {
302
+ const match = findWardrobeItem(lib, 'outfits', v);
303
+ return { outfit: match ? match.name : v, source: 'context' };
304
+ }
305
+ }
306
+
307
+ // 3. 情境默认:没配习惯时,按 situation 关键词查常识表。库里 find 到才用,find 不到跳过。
308
+ if (sit) {
309
+ const def = situationDefaultOutfit(sit);
310
+ if (def) {
311
+ const match = findWardrobeItem(lib, 'outfits', def);
312
+ if (match) return { outfit: match.name, source: 'situation-default' };
313
+ }
314
+ }
315
+
316
+ // 睡觉但没标情境、也没命中情境习惯/默认:不硬猜(不该给人物默认服饰——睡觉穿女仆裙不对)。
317
+ if (sleeping) return { outfit: '', source: '' };
318
+
319
+ // 4. 延续上一段:没标情境、或情境习惯和默认都没命中时,接着上一段穿(起床、连续在家)。
320
+ if (prevOutfit) {
321
+ const match = findWardrobeItem(lib, 'outfits', prevOutfit);
322
+ return { outfit: match ? match.name : prevOutfit, source: 'carry' };
323
+ }
324
+
325
+ // 5. 场景默认:库里某个场景的 defaultOutfit(现在场景条目里这个字段都是空的,补不出)。
326
+ if (item.scene) {
327
+ const sc = findWardrobeItem(lib, 'scenes', item.scene);
328
+ if (sc?.defaultOutfit) {
329
+ const match = findWardrobeItem(lib, 'outfits', sc.defaultOutfit);
330
+ return { outfit: match ? match.name : sc.defaultOutfit, source: 'scene' };
331
+ }
332
+ }
333
+
334
+ // 6. 人物的 defaultOutfit(最后兜底)。
335
+ if (char?.defaultOutfit) {
336
+ const match = findWardrobeItem(lib, 'outfits', char.defaultOutfit);
337
+ return { outfit: match ? match.name : char.defaultOutfit, source: 'default' };
338
+ }
339
+
340
+ return { outfit: '', source: '' };
341
+ }
342
+
343
+ /**
344
+ * 给一整天的 items 补 outfit。按时间顺序,前一段的 outfit 传给下一段(延续)。
345
+ *
346
+ * 只补空槽,不覆盖模型填好的。返回**新数组**,不改原 items。
347
+ * 也补 scene 的正名归一(能对上库就用正名),让 imggen_draw 的别名解析更稳。
348
+ */
349
+ export function enrichItems(items, lib) {
350
+ if (!Array.isArray(items) || !items.length) return items;
351
+ if (lib?.empty !== false) return items;
352
+ let prevOutfit = '';
353
+ return items.map((it) => {
354
+ const next = { ...it };
355
+ if (it.scene) {
356
+ const sc = findWardrobeItem(lib, 'scenes', it.scene);
357
+ if (sc) next.scene = sc.name;
358
+ }
359
+ if (it.props?.length) {
360
+ next.props = it.props.map((p) => {
361
+ const m = findWardrobeItem(lib, 'props', p);
362
+ return m ? m.name : p;
363
+ });
364
+ }
365
+ const { outfit, source } = autoOutfit(it, lib, prevOutfit);
366
+ if (outfit && !it.outfit) {
367
+ next.outfit = outfit;
368
+ next.outfitSource = source;
369
+ } else if (it.outfit) {
370
+ // 归一成正名(autoOutfit 的第 1 级会做,这里也保证 enrich 后是正名)。
371
+ const m = findWardrobeItem(lib, 'outfits', it.outfit);
372
+ if (m) next.outfit = m.name;
373
+ }
374
+ prevOutfit = next.outfit || prevOutfit;
375
+ return next;
376
+ });
377
+ }
378
+
379
+ // ---------------------------------------------------------------------------
380
+ // 给模型看的文本
381
+ // ---------------------------------------------------------------------------
382
+
383
+ function entryLine(it, kindLabel) {
384
+ const parts = [it.name];
385
+ if (it.aliases.length) parts.push(`别名 ${it.aliases.join('/')}`);
386
+ if (it.tags.length) parts.push(`标签 ${it.tags.slice(0, 6).join('、')}`);
387
+ if (it.defaultOutfit) parts.push(`默认服饰:${it.defaultOutfit}`);
388
+ const ctx = Object.entries(it.outfitByContext);
389
+ if (ctx.length) parts.push(`情境穿搭:${ctx.map(([k, v]) => `${k}→${v}`).join(';')}`);
390
+ if (it.desc) parts.push(it.desc);
391
+ return `- ${parts.join(';')}`;
392
+ }
393
+
394
+ /**
395
+ * 给 planEventText 用的素材库列表。
396
+ *
397
+ * 库为空时返回空串(调用方直接判断要不要加这段)。
398
+ * 只列**能帮她写日程的**:人物的习惯、衣柜、场景、道具;不列 desc 里太长的设定文。
399
+ */
400
+ export function wardrobeText(lib) {
401
+ if (lib?.empty !== false) return '';
402
+ const sections = [];
403
+ if (lib.characters.length) {
404
+ sections.push(['人物', lib.characters.map((c) => {
405
+ const parts = [c.name];
406
+ if (c.aliases.length) parts.push(`别名 ${c.aliases.join('/')}`);
407
+ if (c.defaultOutfit) parts.push(`平时穿:${c.defaultOutfit}`);
408
+ const ctx = Object.entries(c.outfitByContext);
409
+ if (ctx.length) parts.push(`情境穿搭:${ctx.map(([k, v]) => `${k}→${v}`).join(';')}`);
410
+ return `- ${parts.join(';')}`;
411
+ })]);
412
+ }
413
+ if (lib.outfits.length) {
414
+ sections.push(['衣柜', lib.outfits.map((o) => entryLine(o, 'outfit'))]);
415
+ }
416
+ if (lib.scenes.length) {
417
+ sections.push(['场景', lib.scenes.map((s) => {
418
+ const parts = [s.name];
419
+ if (s.aliases.length) parts.push(`别名 ${s.aliases.join('/')}`);
420
+ if (s.desc) parts.push(s.desc);
421
+ return `- ${parts.join(';')}`;
422
+ })]);
423
+ }
424
+ if (lib.props.length) {
425
+ sections.push(['道具', lib.props.map((p) => entryLine(p, 'prop'))]);
426
+ }
427
+ if (!sections.length) return '';
428
+ const lines = ['(生图素材库里有这些,写日程时 outfit / scene / props 尽量用这里的正名,库里没有的写进 outfitNote:)'];
429
+ for (const [label, items] of sections) {
430
+ lines.push(label + ':');
431
+ lines.push(...items);
432
+ }
433
+ return lines.join('\n');
434
+ }
435
+
436
+ /**
437
+ * 给 envBlock 用的指向句。
438
+ *
439
+ * 库为空时返回空串——没有素材库就没法联动,不强加一句指向不存在的东西。
440
+ * 这句进系统前缀(一天变一两次的),几十 token 常驻。
441
+ */
442
+ export function wardrobeHintLine(lib) {
443
+ if (lib?.empty !== false) return '';
444
+ const names = lib.characters.map((c) => c.name).join('、') || '';
445
+ return `(生图工作室的素材库在同一个数据目录下。想发图时,穿着、地点、情境按你日程里写的来——${names ? `尤其是 ${names} ` : ''}的穿搭习惯。imggen_draw 的 outfits / scene / props / situation 填你日程里写的名字就行。)`;
446
+ }
package/src/world.js CHANGED
@@ -30,6 +30,10 @@ import {
30
30
  pickDayType, planEventText, planFreeTick, playDoneText, readDay, readPlay, recentSummary, recordPlay,
31
31
  segmentKey, skipFreeToday, templateDay, writeDay, writePlay, zonedNow,
32
32
  } from './life/index.js';
33
+ import {
34
+ autoOutfit, clearWardrobeCache, emptyWardrobe, enrichItems, loadWardrobe,
35
+ wardrobeHintLine, wardrobeText,
36
+ } from './life/wardrobe.js';
33
37
  import { briefLine, filterDishes, findDish, findDishExact, loadDishes, pickFew, pickOne, tasteProfile } from './dishes.js';
34
38
  import {
35
39
  MAX_TABLE, PRESETS, adhocCombo, comboIdFrom, comboProblem, comboSize, findCombo, findPreset,
@@ -314,6 +318,8 @@ export class FeastWorld {
314
318
  #lifeSegment = null;
315
319
  /** 今天的自由时间记录(叫醒过哪几档、记了几笔)。懒加载,见 #freePlay。 */
316
320
  #play = null;
321
+ /** 生图素材库快照:envPromptVars() 是同步的,不能 await,读这里。tick 里刷新(见 #lifeEnsure)。 */
322
+ #wardrobe = emptyWardrobe();
317
323
 
318
324
  constructor(opts = {}) {
319
325
  this.id = ID;
@@ -397,6 +403,31 @@ export class FeastWorld {
397
403
  return this.cfg?.lifeEnabled !== false;
398
404
  }
399
405
 
406
+ /** 生图联动总开关。lifeWardrobeOn 关掉=不扫库、不列、不补、不注入。 */
407
+ #wardrobeOn() {
408
+ return this.#lifeOn() && this.cfg?.lifeWardrobeOn !== false;
409
+ }
410
+
411
+ #wardrobeAutoOutfit() {
412
+ return this.cfg?.lifeWardrobeAutoOutfit !== false;
413
+ }
414
+
415
+ /**
416
+ * 刷新素材库快照(tick 里调,每拍一次;缓存命中时只 stat 不重扫)。
417
+ * 开关关着、或库读不到,都让 #wardrobe 停在空库——envBlock / planEventText 判 empty 就跳过。
418
+ *
419
+ * 库目录由 loadWardrobe 内部解析(优先级:lifeWardrobeDir > imggen 的 libraryRoot > 默认),
420
+ * 这里只传 dataDir 和手动覆盖。
421
+ */
422
+ async #refreshWardrobe() {
423
+ if (!this.#wardrobeOn()) { this.#wardrobe = emptyWardrobe(); return; }
424
+ try {
425
+ this.#wardrobe = await loadWardrobe(this.dataDir, { cfgDir: this.cfg?.lifeWardrobeDir });
426
+ } catch {
427
+ this.#wardrobe = emptyWardrobe();
428
+ }
429
+ }
430
+
400
431
  // -------------------------------------------------------------------------
401
432
  // 提示词
402
433
  // -------------------------------------------------------------------------
@@ -415,8 +446,9 @@ export class FeastWorld {
415
446
  const z = zonedNow(this.timezone, now);
416
447
  const today = this.#lifeToday?.date === z.date ? this.#lifeToday : null;
417
448
  const tomorrow = this.#lifeTomorrow?.items?.length ? this.#lifeTomorrow : null;
449
+ const wardrobe = this.#wardrobeOn() ? wardrobeHintLine(this.#wardrobe) : '';
418
450
  return {
419
- feast_life_block: envBlock({ today, tomorrow, cfg: this.cfg, tz: this.timezone, nowMs: now }),
451
+ feast_life_block: envBlock({ today, tomorrow, cfg: this.cfg, tz: this.timezone, nowMs: now, wardrobe }),
420
452
  };
421
453
  } catch (err) {
422
454
  this.#host?.log?.warn?.('一桌菜:她的一天环境提示词算不出来', { err: msg(err) });
@@ -1445,13 +1477,19 @@ export class FeastWorld {
1445
1477
  /** 今天没有日程(或还停在占位)就模板兜底;到点请 Coo 自己写明天。 */
1446
1478
  async #lifeEnsure(now) {
1447
1479
  if (!this.#lifeOn()) return;
1480
+ // 先刷新素材库快照:envBlock / planEventText / enrichItems 都读它。缓存命中时只 stat。
1481
+ await this.#refreshWardrobe();
1448
1482
  const z = zonedNow(this.timezone, now);
1449
1483
  const today = await readDay(this.dataDir, z.date);
1450
1484
  if (!today || today.source === 'pending' || !today.items.length) {
1451
- const filled = templateDay(z.date, {
1485
+ let filled = templateDay(z.date, {
1452
1486
  dayTypeId: this.#lifeDayType(), rand: this.#random, now,
1453
1487
  by: 'catch-up', maxItems: this.#lifeMaxItems(),
1454
1488
  });
1489
+ // 模板日程也补 outfit(库非空时)——否则模板兜底的日子永远没穿着,联动断在兜底上。
1490
+ if (this.#wardrobeOn() && this.#wardrobeAutoOutfit()) {
1491
+ filled = { ...filled, items: enrichItems(filled.items, this.#wardrobe) };
1492
+ }
1455
1493
  await writeDay(this.dataDir, filled);
1456
1494
  this.#lifeToday = filled;
1457
1495
  } else {
@@ -1483,13 +1521,14 @@ export class FeastWorld {
1483
1521
  if (!host?.pushEvent) throw new Error('宿主没有 pushEvent');
1484
1522
  const recent = await recentSummary(this.dataDir, fromDate, 3);
1485
1523
  const slots = typeof this.cfg?.mealSlots === 'string' ? this.cfg.mealSlots : DEFAULTS.mealSlots;
1524
+ const wardrobe = this.#wardrobeOn() ? wardrobeText(this.#wardrobe) : '';
1486
1525
  await host.pushEvent({
1487
1526
  type: EVENT_LIFE_PLAN,
1488
1527
  source: this.id,
1489
1528
  senderKey: 'feast-life-plan',
1490
1529
  origin: 'internal',
1491
1530
  ts: new Date(now).toISOString(),
1492
- text: planEventText({ date, type, recent, mealSlots: slots }),
1531
+ text: planEventText({ date, type, recent, mealSlots: slots, wardrobe }),
1493
1532
  meta: { date, dayType: type.id },
1494
1533
  }, { deliver: true, trigger: 'flush' });
1495
1534
  }
@@ -1583,6 +1622,11 @@ export class FeastWorld {
1583
1622
  } catch (err) {
1584
1623
  return { text: `[记日程失败] ${msg(err)}`, failed: true };
1585
1624
  }
1625
+ // 生图联动:库非空且开关开着时,按习惯补 outfit / 归一 scene 正名。
1626
+ // 只补空槽,不覆盖她自己填的;库读不到就是空库,enrichItems 直接原样返回。
1627
+ if (this.#wardrobeOn() && this.#wardrobeAutoOutfit()) {
1628
+ day = { ...day, items: enrichItems(day.items, this.#wardrobe) };
1629
+ }
1586
1630
  day.by = 'coo';
1587
1631
  await writeDay(this.dataDir, day);
1588
1632
  this.#cacheLifeDay(day, now);