cortico-world-fun 0.2.0 → 0.3.0

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/src/world.js CHANGED
@@ -14,7 +14,7 @@
14
14
  * `lifeFreeMenu` 那一行顺手一提,或者她自己 `fun_start`。
15
15
  * 这是刻意的——两套叫醒会互相抢时间轴,而联动本来靠的就是提示词。
16
16
  *
17
- * 状态是纯 JSON,落在 `<dataDir>/fun/state.json`;历史保留,跨天仅清理过期行程。
17
+ * 状态是纯 JSON,落在 `<dataDir>/fun/state.json`;历史保留,跨天超时的行程等待续逛或收摊。
18
18
  *
19
19
  * 红线(World 契约):不调别的 World 的工具、不读别人的状态或日程文件、
20
20
  * `envPromptVars()` 永不抛错、`create()` 保持纯。
@@ -44,9 +44,15 @@ import { filterEventsForArea } from './events.js';
44
44
  import { aquariumDetail, aquariumEventDetail } from './aquarium.js';
45
45
  import { applyChoice, choiceForEvent } from './choices.js';
46
46
  import { addWish, changeWish, fulfillWishes } from './wishes.js';
47
+ import { explorationFor } from './exploration.js';
48
+ import { branchChoiceFor, branchFollowup } from './branches.js';
49
+ import { addMoment, timelineFor, normalizeRoute, storeRoute, routeText } from './journeys.js';
50
+ import { recommendVenue } from './recommendations.js';
51
+ import { StoryLibrary, storyResultText } from './story-library.js';
52
+ import { pickStory, advanceStoryChoice } from './story-packs.js';
47
53
  import {
48
54
  buySouvenir, closeSession, dayIn, enterVenue, favoriteTrip, hmIn, isStale, minutesIn,
49
- newState, normalizeState, recentPlaceIds, recordConsume,
55
+ newState, normalizeState, outingMinutes, outingStatus, recentPlaceIds, recordConsume,
50
56
  takePhoto, tripDay, tripSummary, visitedText, wanderOnce,
51
57
  } from './state.js';
52
58
 
@@ -73,7 +79,7 @@ export const FUN_TOOL_DECLS = [
73
79
  {
74
80
  name: 'fun_places',
75
81
  tags: ['read', 'snapshot'],
76
- description: '查询当前可去地点,默认按营业状态和拥挤度排序;all 列出全部,kind 筛选类别。地点名以此工具返回为准。',
82
+ description: '查询地点、当前可逛项目及心愿的合适时段。',
77
83
  parameters: {
78
84
  type: 'object',
79
85
  properties: {
@@ -124,25 +130,36 @@ export const FUN_TOOL_DECLS = [
124
130
  {
125
131
  name: 'fun_choice',
126
132
  tags: ['write'],
127
- description: '处理 fun_wander 回执中出现的待选择事件。按回执提供的 choiceId 和 optionId 选一个,不会凭空添加收获。',
133
+ description: '按待选回执的选项处理当前事件,也可略过。',
128
134
  parameters: {
129
135
  type: 'object',
130
136
  properties: {
131
137
  choiceId: { type: 'string', description: '待选择事件回执给出的 choiceId。' },
132
- optionId: { type: 'string', description: '待选择事件回执给出的 optionId。' },
138
+ optionId: { type: 'string', description: '使用回执中的 optionId,或填 skip 略过。' },
133
139
  },
134
140
  required: ['choiceId', 'optionId'],
135
141
  additionalProperties: false,
136
142
  },
137
143
  },
144
+ {
145
+ name: 'fun_resume',
146
+ tags: ['write'],
147
+ description: '继续未逛完的行程,返回进度和待选事件。',
148
+ parameters: {
149
+ type: 'object',
150
+ properties: { id: { type: 'string', description: 'fun_view 提供的未完行程 ID。' } },
151
+ required: ['id'], additionalProperties: false,
152
+ },
153
+ },
138
154
  {
139
155
  name: 'fun_home',
140
156
  tags: ['write'],
141
- description: '结束当前行程并返回摘要及记录提示。note 可选,记录一句本趟感受。',
157
+ description: '收摊并把已发生的经历记入纪念册。',
142
158
  parameters: {
143
159
  type: 'object',
144
160
  properties: {
145
161
  note: { type: 'string', description: '这一趟怎么样,一句话,可选。' },
162
+ draftId: { type: 'string', description: '要按已有记录结束未完行程时,填 fun_view 提供的 ID。结束正在逛的行程时不填。' },
146
163
  },
147
164
  additionalProperties: false,
148
165
  },
@@ -156,14 +173,32 @@ export const FUN_TOOL_DECLS = [
156
173
  properties: {},
157
174
  },
158
175
  },
176
+ {
177
+ name: 'fun_route',
178
+ tags: ['write'],
179
+ description: '规划两站出门、前往下一站、改下一站或取消后续;不自动移动。',
180
+ parameters: { type: 'object', properties: {
181
+ action: { type: 'string', enum: ['plan', 'status', 'next', 'change', 'cancel'] },
182
+ places: { type: 'array', items: { type: 'string' }, minItems: 2, maxItems: 2, description: 'plan 时填两个不同地点正名或 ID。' },
183
+ id: { type: 'string', description: 'next/change/cancel 时填回执中的路线 ID。' },
184
+ place: { type: 'string', description: 'change 时的新下一站;只改尚未去的站。' },
185
+ company: { type: 'string', description: 'plan 时的同行人,可选。' },
186
+ }, required: ['action'], additionalProperties: false },
187
+ },
159
188
  {
160
189
  name: 'fun_view',
161
190
  tags: ['read', 'snapshot'],
162
- description: '按需查询近期或珍藏的行程记录。',
191
+ description: '查询行程,可按地点、同行人、日期或关键词检索。',
163
192
  parameters: {
164
193
  type: 'object',
165
194
  properties: {
166
195
  count: { type: 'integer', description: '看最近几趟,默认 5。', minimum: 1, maximum: 20 },
196
+ query: { type: 'string', description: '搜索地点、项目、备注、小事或纪念品。' },
197
+ place: { type: 'string', description: '只看这个地点的行程,正名或别名。' },
198
+ company: { type: 'string', description: '只看与这位同行人的行程。' },
199
+ from: { type: 'string', description: '开始日期 YYYY-MM-DD,包含当天。' },
200
+ to: { type: 'string', description: '结束日期 YYYY-MM-DD,包含当天。' },
201
+ id: { type: 'string', description: '精确查看一个已有行程 ID。' },
167
202
  },
168
203
  additionalProperties: false,
169
204
  },
@@ -205,6 +240,20 @@ export const FUN_TOOL_DECLS = [
205
240
  additionalProperties: false,
206
241
  },
207
242
  },
243
+ {
244
+ name: 'fun_story',
245
+ tags: ['write'],
246
+ description: '管理本地地点剧情包,校验和预览只读,导入或启停须指定操作。',
247
+ parameters: { type: 'object', properties: {
248
+ action: { type: 'string', enum: ['list', 'template', 'validate', 'preview', 'export', 'import', 'enable', 'disable', 'remove'] },
249
+ id: { type: 'string', description: '已有剧情包 ID,来自 list。' },
250
+ json: { type: 'string', description: '完整剧情包 JSON,最多 32 KB;validate/preview 不保存。' },
251
+ placeId: { type: 'string', description: 'template 绑定的真实地点 ID,可来自自填地点;list 提供可用 ID。' },
252
+ area: { type: 'string', description: 'preview 的项目,默认使用起始节点项目。' },
253
+ time: { type: 'string', description: 'preview 的测试时刻 HH:MM,默认当前本地时刻。' },
254
+ replace: { type: 'boolean', description: 'import 覆盖已有同 ID 自定义包时才设 true。' },
255
+ }, required: ['action'], additionalProperties: false },
256
+ },
208
257
  {
209
258
  name: 'fun_shelf',
210
259
  tags: ['read', 'snapshot'],
@@ -232,6 +281,7 @@ export class FunWorld {
232
281
  #userVenues = null;
233
282
  /** B 阶段:预设覆盖层 `{ [presetId]: {字段: 值} }`,稀疏、只存改过的字段。 */
234
283
  #overrides = {};
284
+ #storyLibrary;
235
285
 
236
286
  constructor(opts = {}) {
237
287
  this.id = ID;
@@ -243,6 +293,7 @@ export class FunWorld {
243
293
  this.#now = typeof opts.now === 'function' ? opts.now : () => Date.now();
244
294
  this.#random = typeof opts.random === 'function' ? opts.random : Math.random;
245
295
  this.#persist = typeof opts.persist === 'function' ? opts.persist : null;
296
+ this.#storyLibrary = new StoryLibrary({ file: this.storiesFile(), venues: () => this.#places(), visits: (id) => this.#state ? this.#history(id)?.visitCount ?? 0 : 0, nowMin: () => minutesIn(this.timezone, this.#now()) });
246
297
  }
247
298
 
248
299
  // -------------------------------------------------------------------------
@@ -310,6 +361,8 @@ export class FunWorld {
310
361
  return join(this.dataDir, 'fun', 'venues.json');
311
362
  }
312
363
 
364
+ storiesFile() { return join(this.dataDir, 'fun', 'stories.json'); }
365
+
313
366
  // -------------------------------------------------------------------------
314
367
  // 场所:预设 + 用户自填
315
368
  // -------------------------------------------------------------------------
@@ -379,9 +432,11 @@ export class FunWorld {
379
432
 
380
433
  #runTool(name, args) {
381
434
  return this.#serial(async () => {
435
+ const previous = this.#state ? structuredClone(this.#state) : null;
382
436
  try {
383
437
  return await this.#tool(name, args);
384
438
  } catch (err) {
439
+ this.#state = previous;
385
440
  return { text: `[${name} 失败] ${msg(err)}`, failed: true };
386
441
  }
387
442
  });
@@ -394,8 +449,10 @@ export class FunWorld {
394
449
  case 'fun_go': return await this.#goTool(args);
395
450
  case 'fun_wander': return await this.#wanderTool(args);
396
451
  case 'fun_choice': return await this.#choiceTool(args);
452
+ case 'fun_resume': return await this.#resumeTool(args.id);
397
453
  case 'fun_home': return await this.#homeTool(args);
398
454
  case 'fun_start': return this.#startTool();
455
+ case 'fun_route': return await this.#routeTool(args);
399
456
  case 'fun_view': return this.#viewTool(args);
400
457
  case 'fun_wishes': { this.#state = this.#normalizeState(); return { text: this.#wishesText() }; }
401
458
  case 'fun_wish': {
@@ -404,10 +461,80 @@ export class FunWorld {
404
461
  }
405
462
  case 'fun_keepsake': return await this.#keepsakeTool(args);
406
463
  case 'fun_shelf': return this.#shelfTool(args);
464
+ case 'fun_story': {
465
+ const result = await this.#storyLibrary.act(args);
466
+ return { text: storyResultText(result), ...(result.ok ? {} : { failed: true }) };
467
+ }
407
468
  default: return { text: `[${name} 失败] 不认识这个工具。`, failed: true };
408
469
  }
409
470
  }
410
471
 
472
+ async #routeTool(args) {
473
+ const next = this.#normalizeState();
474
+ const action = args?.action;
475
+ if (action === 'status') return { text: next.route ? routeText(next.route) : '当前没有待继续的路线。' };
476
+ if (action === 'plan') {
477
+ if (next.route || next.session || next.draft) return { text: '请先处理当前行程或路线,再规划新的两站出门。', failed: true };
478
+ if (!Array.isArray(args.places) || args.places.length !== 2) return { text: '请指定两个不同地点。', failed: true };
479
+ const venues = args.places.map((p) => findVenue(this.#places(), p));
480
+ if (venues.some((v) => !v) || venues[0].id === venues[1].id) return { text: '两个地点须存在且不同;用 fun_places 查看清单。', failed: true };
481
+ next.routeSeq += 1;
482
+ const route = { id: 'route-' + this.#now() + '-' + next.routeSeq, stops: venues.map((v) => ({ placeId: v.id, placeName: v.name })), company: typeof args.company === 'string' ? args.company.trim().slice(0, 40) : '', nextIndex: 0, status: 'planned', tripIds: [], startedAt: this.#now() };
483
+ storeRoute(next, route);
484
+ await this.#commitState(next);
485
+ return { text: routeText(route) + '。准备好后用 fun_route 的 next 并填 id 前往第一站。' };
486
+ }
487
+ const route = next.route;
488
+ if (!route || args.id !== route.id) return { text: '找不到当前这条路线,请用 fun_route status 查看。', failed: true };
489
+ if (action === 'cancel') {
490
+ route.status = 'cancelled';
491
+ storeRoute(next, route);
492
+ await this.#commitState(next);
493
+ return { text: '已取消后续路线;正在逛的行程和已经保存的记录保留。' };
494
+ }
495
+ if (action === 'change') {
496
+ const index = next.session?.routeId === route.id || next.draft?.routeId === route.id ? route.nextIndex + 1 : route.nextIndex;
497
+ if (index > 1) return { text: '已经没有尚未去的下一站。', failed: true };
498
+ const venue = findVenue(this.#places(), args.place);
499
+ if (!venue || route.stops.some((stop, i) => i !== index && stop.placeId === venue.id)) return { text: '新下一站须是另一处现有地点。', failed: true };
500
+ route.stops[index] = { placeId: venue.id, placeName: venue.name };
501
+ storeRoute(next, route);
502
+ await this.#commitState(next);
503
+ return { text: routeText(route) + '。没有自动出发。' };
504
+ }
505
+ if (action === 'next') {
506
+ if (next.session || next.draft) return { text: '这一站还没有收摊,请先完成或处理未完行程。', failed: true };
507
+ const stop = route.stops[route.nextIndex];
508
+ if (!stop || !this.#places().some((v) => v.id === stop.placeId)) return { text: '下一站已不在地点清单,可 change 换一站或 cancel 取消后续。', failed: true };
509
+ return this.#goTool({ place: stop.placeId, company: route.company });
510
+ }
511
+ return { text: '可用 plan/status/next/change/cancel。', failed: true };
512
+ }
513
+
514
+ #queryTrips(args = {}) {
515
+ const value = (v) => typeof v === 'string' ? v.trim().toLocaleLowerCase() : '';
516
+ const query = value(args.query), company = value(args.company), place = value(args.place);
517
+ const venue = place ? findVenue(this.#places(), args.place) : null;
518
+ return this.#savedTrips().filter((t) => {
519
+ if (args.id && t.id !== args.id || args.placeId && t.placeId !== args.placeId) return false;
520
+ if (args.kept && !(this.#state.keepsakeTrips ?? []).some((k) => k.id === t.id)) return false;
521
+ if (place && (venue ? t.placeId !== venue.id : !value(t.placeName).includes(place))) return false;
522
+ if (company && !value(t.company).includes(company)) return false;
523
+ const day = tripDay(t, this.timezone);
524
+ if (args.from && (!day || day < args.from) || args.to && (!day || day > args.to)) return false;
525
+ if (query && !value([t.placeName, t.company, t.note, ...(t.visited ?? []).map((v) => v.area + ' ' + v.note), ...(t.events ?? []), ...(t.souvenirs ?? []), ...(t.photos ?? []), ...(t.choices ?? []).map((c) => c.result)].join(' ')).includes(query)) return false;
526
+ return true;
527
+ });
528
+ }
529
+
530
+ #tripLookup(args = {}, requireId = false) {
531
+ if (requireId && (typeof args.id !== 'string' || !args.id)) return { ok: false, error: '缺少行程 ID。' };
532
+ const ids = new Set(this.#queryTrips(args).map((t) => t.id));
533
+ const trips = this.#bookData().trips.filter((t) => ids.has(t.id));
534
+ if (requireId && !trips.length) return { ok: false, error: '详细行程已不在近期或珍藏记录中。' };
535
+ return { ok: true, trips };
536
+ }
537
+
411
538
  #wishesText() {
412
539
  const labels = { active: '想去', paused: '暂缓', completed: '已完成', cancelled: '已取消' };
413
540
  const wishes = this.#state.wishes ?? [];
@@ -415,18 +542,60 @@ export class FunWorld {
415
542
  return ['出游心愿(不会催促):', ...wishes.map((w) => `- [${labels[w.status]}] ${w.placeName}${w.target ? ` · ${w.target}` : ''}${w.reason ? `:${w.reason}` : ''}(ID:${w.id})`)].join('\n');
416
543
  }
417
544
 
545
+ #outings(now = this.#now()) {
546
+ return outingStatus(this.#state, dayIn(this.timezone, now), now, this.#ttlMin(), this.timezone);
547
+ }
548
+
549
+ #draftHint(draft) {
550
+ return `「${draft.placeName}」还有一趟未逛完(ID:${draft.id})。用 fun_resume 填 id 继续,或用 fun_home 填 draftId 按已有记录收摊。`;
551
+ }
552
+
553
+ #choiceHint(choice) {
554
+ return [
555
+ `待选择事件(choiceId:${choice.id}):${choice.prompt}`,
556
+ [...choice.options.map((o) => `${o.id}:${o.label}`), 'skip:略过'].join(' / '),
557
+ '用 fun_choice 填 choiceId 和 optionId,再继续下一处。',
558
+ ].join('\n');
559
+ }
560
+
561
+ async #resumeTool(id) {
562
+ const next = this.#normalizeState();
563
+ const draft = next.draft;
564
+ if (!draft || id !== draft.id || next.session) {
565
+ return { text: '找不到可继续的这趟行程,请用 fun_view 查看当前状态。', failed: true };
566
+ }
567
+ if (!this.#places().some((v) => v.id === draft.placeId)) {
568
+ return { text: `「${draft.placeName}」已不在地点清单。可用 fun_home 填 draftId 按已有记录收摊。`, failed: true };
569
+ }
570
+ const now = this.#now();
571
+ draft.pausedMs += Math.max(0, now - draft.lastAt);
572
+ draft.lastAt = now;
573
+ next.session = draft;
574
+ next.draft = null;
575
+ await this.#commitState(next);
576
+ return { text: [`接着逛「${draft.placeName}」。${visitedText(draft)}。`,
577
+ draft.pendingChoice ? this.#choiceHint(draft.pendingChoice) : '接着用 fun_wander 逛下一处。',
578
+ ].join('\n') };
579
+ }
580
+
418
581
  async #choiceTool(args) {
419
- const session = this.#state.session;
582
+ const next = this.#normalizeState();
583
+ if (next.draft) return { text: this.#draftHint(next.draft), failed: true };
584
+ const session = next.session;
420
585
  if (!session?.pendingChoice) return { text: '现在没有待选择的事件。', failed: true };
421
- if (args?.choiceId !== session.pendingChoice.id) return { text: '这不是当前这条待选择事件,请按最新回执里的 choiceId 选择。', failed: true };
422
- const result = applyChoice(session.pendingChoice, args?.optionId);
423
- if (!result.ok) return { text: result.error, failed: true };
424
- session.choices = Array.isArray(session.choices) ? session.choices : [];
425
- session.choices.push({ event: result.choice.event, option: result.option.id, result: result.option.result, at: this.#now() });
586
+ const choice = session.pendingChoice;
587
+ if (args?.choiceId !== choice.id) return { text: this.#choiceHint(choice), failed: true };
588
+ const skip = args?.optionId === 'skip';
589
+ const result = skip ? null : applyChoice(choice, args?.optionId);
590
+ if (result && !result.ok) return { text: `${result.error}\n${this.#choiceHint(choice)}`, failed: true };
591
+ const now = this.#now();
592
+ session.choices.push({ event: choice.event, option: args.optionId, result: skip ? '略过了这次选择' : result.option.result, at: now });
593
+ addMoment(session, 'choice', skip ? '略过了这次选择' : result.option.result, now, choice.area, choice.event);
594
+ session.storyProgress = advanceStoryChoice(session.storyProgress, choice.id, args.optionId);
426
595
  session.pendingChoice = null;
427
- session.lastAt = this.#now();
428
- await this.#save();
429
- return { text: `你选择了「${result.option.label}」。${result.option.result}。` };
596
+ session.lastAt = now;
597
+ await this.#commitState(next);
598
+ return { text: skip ? '略过了这次选择,可以接着逛。' : `你选择了「${result.option.label}」。${result.option.result}。` };
430
599
  }
431
600
 
432
601
  async #manageWish(args) {
@@ -458,18 +627,49 @@ export class FunWorld {
458
627
  return result.completed;
459
628
  }
460
629
 
461
- #wishRecommendation(venue, nowMin) {
462
- if (hoursState(venue, nowMin) === 'closed') return '';
463
- const wish = (this.#state.wishes ?? []).find((w) => w.status === 'active' && w.placeId === venue.id
464
- && (w.type !== 'phase' || phaseLabelAt(venue, nowMin) === w.target)
465
- && (w.type !== 'area' || areasNow(venue, nowMin).includes(w.target))
466
- && (w.type !== 'souvenir' || venue.souvenirs.includes(w.target)));
467
- return wish ? `有个心愿:${wish.type === 'visit' ? `想去${venue.name}` : `想${wish.type === 'souvenir' ? '拿到' : '看看'}${wish.target}`}${wish.reason ? `(${wish.reason})` : ''}` : '';
630
+ #history(placeId, today = dayIn(this.timezone, this.#now())) {
631
+ const recent = historyFor(this.#savedTrips(), placeId, today, this.timezone);
632
+ const permanent = explorationFor(this.#state.exploration, placeId);
633
+ if (!permanent) return recent;
634
+ const items = (this.#state.collection ?? []).filter((x) => x.placeId === placeId);
635
+ return { ...recent, visitCount: permanent.visits, firstDay: permanent.firstDay,
636
+ lastDay: permanent.lastDay, lastDayPhrase: dayPhrase(permanent.lastDay, today),
637
+ areas: permanent.areas.map((area) => ({ area, times: permanent.areaCounts[area] || 1 })).sort((a,b) => b.times - a.times),
638
+ photos: permanent.photos.map((spot) => ({ spot, times: 1 })),
639
+ souvenirs: items.map((x) => ({ item: x.name, times: x.times })), ate: recent?.ate ?? [],
640
+ events: [...new Set([...permanent.events, ...(recent?.events ?? [])])], phases: permanent.phases,
641
+ };
642
+ }
643
+
644
+ #recommendations(picks, nowMin, now) {
645
+ const day = dayIn(this.timezone, now);
646
+ const memories = this.#savedTrips();
647
+ const wishes = this.#state.wishes;
648
+ return picks.map((p) => ({
649
+ ...p,
650
+ ...recommendVenue(p.venue, nowMin, wishes, this.#history(p.venue.id, day)),
651
+ })).sort((a, b) => rankOf(a.state) - rankOf(b.state)
652
+ || Number(Boolean(b.wishReason)) - Number(Boolean(a.wishReason)));
653
+ }
654
+
655
+ #upcomingWish(recommendations) {
656
+ let next = null;
657
+ for (const { venue, upcomingWish } of recommendations) {
658
+ if (upcomingWish && (!next || upcomingWish.minutesAway < next.minutesAway)) {
659
+ next = { ...upcomingWish, placeName: venue.name };
660
+ }
661
+ }
662
+ return next ? `下个适合实现心愿的时段 · ${next.placeName} · ${next.text}` : '';
468
663
  }
469
664
 
470
- #wishRank(picks, nowMin) {
471
- return picks.map((p, i) => ({ ...p, i, wishReason: this.#wishRecommendation(p.venue, nowMin) }))
472
- .sort((a, b) => rankOf(a.state) - rankOf(b.state) || Number(Boolean(b.wishReason)) - Number(Boolean(a.wishReason)) || a.i - b.i);
665
+ #recommendationLine(pick, detailed = false) {
666
+ const { venue, state, phase, areas, wishReason, revisitReason } = pick;
667
+ const bits = [`${venue.name}(${[STATE_LABEL[state], phase, CROWD_LABEL[venue.crowd] || '人不少'].filter(Boolean).join(',')})`];
668
+ if (detailed) bits.push(`${venue.hours.open}–${venue.hours.close}`);
669
+ if (areas.length && detailed) bits.push(`现在能逛:${areas.slice(0, 5).join('、')}`);
670
+ if (wishReason) bits.push(wishReason);
671
+ if (revisitReason) bits.push(revisitReason);
672
+ return `- ${bits.join(';')}`;
473
673
  }
474
674
 
475
675
  #placesTool(args) {
@@ -507,24 +707,20 @@ export class FunWorld {
507
707
  } else {
508
708
  picks = allPlaces(nowMin, avoid, places);
509
709
  }
510
- picks = this.#wishRank(picks, nowMin);
710
+ picks = this.#recommendations(picks, nowMin, now);
711
+ const upcomingWish = this.#upcomingWish(picks);
511
712
  if (!all && !kindFilter) picks = picks.slice(0, count);
512
713
 
513
714
  const lines = [`这会儿 ${hmIn(this.timezone, now)},能去逛的:`];
514
- for (const { venue, state, wishReason } of picks) {
515
- const bits = [`${venue.name}(${STATE_LABEL[state]},${CROWD_LABEL[venue.crowd] || '人不少'})`];
516
- bits.push(`${venue.hours.open}–${venue.hours.close}`);
517
- bits.push(`能逛:${venue.areas.slice(0, 5).join('、')}`);
518
- if (wishReason) bits.push(wishReason);
519
- lines.push(`- ${bits.join(';')}`);
520
- }
521
- if (this.#state.session) {
522
- lines.push(`(你正在「${this.#state.session.placeName}」逛着,${visitedText(this.#state.session)};要换地方先 fun_home 收个摊。)`);
523
- }
715
+ lines.push(...picks.map((p) => this.#recommendationLine(p, true)));
716
+ if (upcomingWish) lines.push(upcomingWish);
717
+ const { session, draft } = this.#outings(now);
718
+ if (session) lines.push(`(你正在「${session.placeName}」逛着,${visitedText(session)};要换地方先 fun_home 收个摊。)`);
719
+ if (draft) lines.push(this.#draftHint(draft));
524
720
  if (!all && !kindFilter && places.length > picks.length) {
525
721
  lines.push(`(一共 ${places.length} 处,这里只排了 ${picks.length} 处;想看全的就 all 填 true,只想看室内/户外/夜就填 kind。)`);
526
722
  }
527
- lines.push('定了就用 fun_go(place 填地方名)进门。');
723
+ if (!draft) lines.push('定了就用 fun_go(place 填地方名)进门。');
528
724
  return { text: lines.join('\n') };
529
725
  }
530
726
 
@@ -532,6 +728,7 @@ export class FunWorld {
532
728
  const now = this.#now();
533
729
  const day = dayIn(this.timezone, now);
534
730
  this.#state = this.#normalizeState();
731
+ if (this.#state.draft) return { text: this.#draftHint(this.#state.draft), failed: true };
535
732
 
536
733
  const places = this.#places();
537
734
  const venue = findVenue(places, args?.place);
@@ -540,6 +737,10 @@ export class FunWorld {
540
737
  return { text: `没听说过「${args?.place ?? ''}」这处。现在能去的是:${names}。\n(拿不准就 fun_places 看看,或者 all 填 true 列全部。)`, failed: true };
541
738
  }
542
739
 
740
+ const route = this.#state.route;
741
+ if (route && venue.id !== route.stops[route.nextIndex]?.placeId && !this.#state.session) {
742
+ return { text: routeText(route) + '。要换目的地可先 fun_route change,或 cancel 取消后续。', failed: true };
743
+ }
543
744
  const state = hoursState(venue, minutesIn(this.timezone, now));
544
745
  const company = typeof args?.company === 'string' ? args.company.trim() : '';
545
746
  const { session, already } = enterVenue(this.#state, venue, now, this.#random, company);
@@ -548,7 +749,16 @@ export class FunWorld {
548
749
  text: `你已经在「${this.#state.session.placeName}」逛着了(${visitedText(this.#state.session)})。\n要么接着 fun_wander,要么 fun_home 收了再换地方。`,
549
750
  };
550
751
  }
551
- const completedWishes = this.#completeWishes({ placeId: venue.id, phase: phaseLabelAt(venue, minutesIn(this.timezone, now)) });
752
+ const enteredPhase = phaseLabelAt(venue, minutesIn(this.timezone, now));
753
+ session.phases = enteredPhase ? [enteredPhase] : [];
754
+ addMoment(session, 'enter', '进了' + venue.name, now);
755
+ if (route) {
756
+ session.routeId = route.id;
757
+ session.routeOrder = route.nextIndex + 1;
758
+ route.status = 'active';
759
+ storeRoute(this.#state, route);
760
+ }
761
+ const completedWishes = this.#completeWishes({ placeId: venue.id, phase: enteredPhase });
552
762
  await this.#save();
553
763
 
554
764
  // 时段气氛:江边清早和夜里不是一回事,所以描写和可逛的项目都按此刻取。
@@ -556,6 +766,7 @@ export class FunWorld {
556
766
  const label = phaseLabelAt(venue, nowMin);
557
767
 
558
768
  const lines = [`进了${venue.name}${label ? `(${label})` : ''}。`, descNow(venue, nowMin)];
769
+ if (route) lines.push(routeText(route) + ' · 第' + session.routeOrder + '站。');
559
770
  if (completedWishes.length) lines.push(`完成了心愿:${completedWishes.map((w) => w.target || `去${w.placeName}`).join('、')}。`);
560
771
  if (args?.company) lines.push(`跟${String(args.company).slice(0, 40)}一起。`);
561
772
  if (state === 'closingSoon') lines.push(`(快到打烊时间了,${venue.hours.close} 就关,别排太长的队。)`);
@@ -572,7 +783,7 @@ export class FunWorld {
572
783
  }
573
784
 
574
785
  // 去过的痕迹:只讲记得住的、只讲这一处的。没来过就一个字都不提。
575
- const history = historyFor(this.#state.trips, venue.id, day, this.timezone);
786
+ const history = this.#history(venue.id, day);
576
787
  if (history) {
577
788
  const memory = memoryLine(history, day);
578
789
  const bits = [];
@@ -584,7 +795,7 @@ export class FunWorld {
584
795
  // 只在够格时出现(5 趟起),且和上面那句分开放,免得事实和关系糊成一团。
585
796
  const regular = regularLine(history, venue.name);
586
797
  if (regular) lines.push(regular);
587
- const prog = progressFor(venue, this.#state.trips);
798
+ const prog = progressFor(venue, this.#state.trips, this.#state.collection, this.#state.exploration);
588
799
  if (prog.areas.left.length) {
589
800
  lines.push(`还没去过:${prog.areas.left.slice(0, 4).join('、')}${prog.areas.left.length > 4 ? ` 等 ${prog.areas.left.length} 处` : ''}。`);
590
801
  }
@@ -600,9 +811,8 @@ export class FunWorld {
600
811
  const day = dayIn(this.timezone, now);
601
812
  this.#state = this.#normalizeState();
602
813
  const session = this.#state.session;
603
- if (session?.pendingChoice) {
604
- return { text: `上一处还有待选择事件(choiceId:${session.pendingChoice.id}),请先用 fun_choice 选择后再继续。` };
605
- }
814
+ if (this.#state.draft) return { text: this.#draftHint(this.#state.draft), failed: true };
815
+ if (session?.pendingChoice) return { text: this.#choiceHint(session.pendingChoice) };
606
816
  if (!session) {
607
817
  return { text: '你还没进门呢。先用 fun_places 选地点,再用 fun_go 进门。' };
608
818
  }
@@ -627,7 +837,7 @@ export class FunWorld {
627
837
  const liveAreas = areasNow(venue, nowMin);
628
838
  // 小事件里要滤掉「她以前真做过」那些,否则去过几次就成了复读机
629
839
  // (上次买了吧唧,这次又抽到「吧唧挑了半天」——那件事这次没发生)。
630
- const pastHistory = historyFor(this.#state.trips, venue.id, day, this.timezone);
840
+ const pastHistory = this.#history(venue.id, day);
631
841
  const liveEvents = filterRepeatedEvents(eventsNow(venue, nowMin), pastHistory);
632
842
  // 少见事件:来过才轮到(内容是按「熟人」写的),而且只是**有机会**。
633
843
  // 两池都先滤掉碰过的,再按 `eventPool` 决定这次从哪个池子里抽。
@@ -706,16 +916,39 @@ export class FunWorld {
706
916
  }
707
917
  // 项目和已验证的收获确定后才抽事件,避免串项目或凭空获得东西。
708
918
  if (picked) {
919
+ let story = null;
920
+ try { story = pickStory(this.#storyLibrary.catalog(), venue, picked.area, nowMin, session, visitsBefore); }
921
+ catch (error) { this.#host?.log?.warn?.('剧情包未能触发,继续普通游逛', { error: msg(error) }); }
922
+ let choice = null;
923
+ if (story) {
924
+ picked.event = story.event;
925
+ session.storyProgress = story.progress;
926
+ choice = story.choice;
927
+ } else {
709
928
  const common = filterEventsForArea(liveEvents, picked.area, venue, session);
710
929
  const rare = filterEventsForArea(rarePool, picked.area, venue, session);
711
930
  const chosenPool = eventPool(common, rare, visitsBefore, this.#random);
712
- picked.event = pickEvent(chosenPool, session.events, this.#random);
713
- if (picked.event) {
714
- session.events.push(picked.event);
715
- const choice = choiceForEvent(picked.event, { area: picked.area });
716
- if (choice && !session.pendingChoice) session.pendingChoice = choice;
931
+ const followup = branchFollowup(venue.id, picked.area, session, nowMin);
932
+ picked.event = followup?.event ?? pickEvent(chosenPool, session.events, this.#random);
933
+ if (followup) session.branchSeen.push(followup.id);
934
+ choice = followup ? null : choiceForEvent(picked.event, { area: picked.area });
935
+ if (!choice && !followup) {
936
+ choice = branchChoiceFor(venue.id, picked.area, session, nowMin);
937
+ if (choice) picked.event = choice.event;
938
+ }
717
939
  }
940
+ if (picked.event) session.events.push(picked.event);
941
+ if (choice && !session.pendingChoice) session.pendingChoice = choice;
718
942
  }
943
+ if (picked) {
944
+ if (phaseName && !session.phases.includes(phaseName)) session.phases.push(phaseName);
945
+ addMoment(session, 'area', picked.area + (args?.note ? ' · ' + String(args.note).slice(0, 120) : ''), now, picked.area);
946
+ if (picked.event) addMoment(session, 'event', picked.event, now, picked.area, picked.event);
947
+ }
948
+ if (bought && !bought.duplicate) addMoment(session, 'buy', '买了' + bought.item, now, picked?.area);
949
+ if (shot && !shot.duplicate) addMoment(session, 'photo', '在' + shot.spot + '拍了照', now, picked?.area);
950
+ if (ate && !ate.duplicate) addMoment(session, 'consume', ate.verb + '了' + ate.item, now, picked?.area);
951
+
719
952
  const completedWishes = this.#completeWishes({ placeId: venue.id, area: picked?.area ?? '', phase: phaseName, souvenirs: bought && !bought.duplicate ? [bought.item] : [] });
720
953
  await this.#save();
721
954
 
@@ -739,10 +972,7 @@ export class FunWorld {
739
972
  const detail = aquariumEventDetail(picked.event, picked.area);
740
973
  if (detail) lines.push(detail);
741
974
  if (session.pendingChoice?.event === picked.event) {
742
- const c = session.pendingChoice;
743
- lines.push(`需要你选一下(choiceId:${c.id}):${c.prompt}`);
744
- lines.push(c.options.map((o) => `${o.id}:${o.label}`).join(' / '));
745
- lines.push('请用 fun_choice 填 choiceId 和 optionId;选完再继续下一处。');
975
+ lines.push(this.#choiceHint(session.pendingChoice));
746
976
  }
747
977
  }
748
978
  const last = session.visited[session.visited.length - 1];
@@ -764,22 +994,37 @@ export class FunWorld {
764
994
 
765
995
  async #homeTool(args) {
766
996
  const now = this.#now();
767
- const day = dayIn(this.timezone, now);
768
- this.#state = this.#normalizeState();
769
- if (!this.#state.session) {
770
- return { text: '你这会儿没在逛啊。想出门就 fun_go,先挑一处地方。' };
997
+ const next = this.#normalizeState();
998
+ if (args?.draftId !== undefined && (!next.draft || args.draftId !== next.draft.id || next.session)) {
999
+ return { text: '找不到要收摊的未完行程,请用 fun_view 查看当前状态。', failed: true };
771
1000
  }
772
-
773
- const venue = this.#places().find((v) => v.id === this.#state.session.placeId)
774
- ?? { name: this.#state.session.placeName, scene: this.#state.session.scene };
775
- // day 按**本地时区**算好传进去:trip 里存的是 leftDay,
776
- // 读纪念册的人就不用拿 leftAt 去猜时区(以前用 UTC 猜,早上 8 点前会偏一天)。
777
- const closed = closeSession(this.#state, now, args?.note, day);
778
- await this.#save();
1001
+ if (next.draft && args?.draftId === undefined) return { text: this.#draftHint(next.draft), failed: true };
1002
+ const outing = next.session ?? next.draft;
1003
+ if (!outing) return { text: '你这会儿没在逛啊。想出门就 fun_go,先挑一处地方。' };
1004
+
1005
+ const endAt = next.draft ? (outing.lastAt || outing.enteredAt || now) : now;
1006
+ if (outing.pendingChoice) {
1007
+ outing.storyProgress = advanceStoryChoice(outing.storyProgress, outing.pendingChoice.id, 'skip');
1008
+ outing.choices.push({ event: outing.pendingChoice.event, option: 'skip', result: '收摊时未作选择', at: endAt });
1009
+ }
1010
+ next.session = outing;
1011
+ next.draft = null;
1012
+ const venue = this.#places().find((v) => v.id === outing.placeId)
1013
+ ?? { name: outing.placeName, scene: outing.scene };
1014
+ const closed = closeSession(next, endAt, args?.note, dayIn(this.timezone, endAt), this.timezone);
1015
+ const route = (next.routes ?? []).find((r) => r.id === outing.routeId);
1016
+ if (route) {
1017
+ if (!route.tripIds.includes(closed.trip.id)) route.tripIds.push(closed.trip.id);
1018
+ route.nextIndex = outing.routeOrder;
1019
+ if (route.status !== 'cancelled') route.status = route.nextIndex >= 2 ? 'completed' : 'between';
1020
+ storeRoute(next, route);
1021
+ }
1022
+ await this.#commitState(next);
779
1023
 
780
1024
  const { trip, stayedMin, note } = closed;
781
1025
  const summary = tripSummary(trip);
782
1026
  const lines = [`收摊:这一趟在${summary}。`];
1027
+ if (route) lines.push(routeText(route) + (route.status === 'between' ? '。想继续时用 fun_route next 并填路线 id;也可 change 换下一站或 cancel 提前结束。' : '。'));
783
1028
  if (stayedMin >= 5) lines.push(`待了大约 ${stayedMin} 分钟。`);
784
1029
  if (note) lines.push(`(你记的:${note})`);
785
1030
 
@@ -808,13 +1053,14 @@ export class FunWorld {
808
1053
  const now = this.#now();
809
1054
  const nowMin = minutesIn(this.timezone, now);
810
1055
  const places = this.#places();
811
- const picks = this.#wishRank(allPlaces(nowMin, recentPlaceIds(this.#state, 2), places), nowMin).slice(0, 5);
1056
+ const picks = this.#recommendations(allPlaces(nowMin, recentPlaceIds(this.#state, 2), places), nowMin, now);
812
1057
  const lines = [`这会儿 ${hmIn(this.timezone, now)}。想现在就出门的话,能去:`];
813
- for (const { venue, state, wishReason } of picks) {
814
- lines.push(`- ${venue.name}(${STATE_LABEL[state]},${CROWD_LABEL[venue.crowd] || '人不少'})${wishReason ? `;${wishReason}` : ''}`);
815
- }
1058
+ lines.push(...picks.slice(0, 5).map((p) => this.#recommendationLine(p)));
1059
+ const upcomingWish = this.#upcomingWish(picks);
1060
+ if (upcomingWish) lines.push(upcomingWish);
816
1061
  lines.push(`(一共 ${places.length} 处,fun_places all 填 true 能看全,kind 填「室内」「户外」「夜」能只看一类。)`);
817
- lines.push('选好后用 fun_go 进门;逛完用 fun_home 收摊。');
1062
+ const { draft } = this.#outings(now);
1063
+ lines.push(draft ? this.#draftHint(draft) : '选好后用 fun_go 进门;逛完用 fun_home 收摊。');
818
1064
  return { text: lines.join('\n') };
819
1065
  }
820
1066
 
@@ -834,14 +1080,18 @@ export class FunWorld {
834
1080
 
835
1081
  #viewTool(args) {
836
1082
  const count = clampInt(args?.count, 1, 20, 5);
837
- const trips = this.#savedTrips().filter((t) => !args?.kept || (this.#state.keepsakeTrips ?? []).some((k) => k.id === t.id)).slice(0, count);
838
- if (!trips.length && !this.#state.session) {
839
- return { text: '纪念册还是空的——还没收过摊。想出门就 fun_start 或 fun_places 看看。' };
1083
+ const trips = this.#queryTrips(args).slice(0, count);
1084
+ const { session, draft } = this.#outings();
1085
+ if (!trips.length && !session && !draft) {
1086
+ return { text: this.#savedTrips().length ? '没有找到符合条件的行程。' : '纪念册还是空的——还没收过摊。想出门就 fun_start 或 fun_places 看看。' };
840
1087
  }
841
1088
  const lines = [];
842
- if (this.#state.session) {
843
- lines.push(`正在逛:${tripSummary(this.#state.session)}。`);
1089
+ if (session) {
1090
+ lines.push(`正在逛:${tripSummary(session)}。`);
1091
+ if (session.pendingChoice) lines.push(this.#choiceHint(session.pendingChoice));
844
1092
  }
1093
+ if (draft) { lines.push(this.#draftHint(draft), `已有记录:${tripSummary(draft)}。`); if (draft.pendingChoice) lines.push(this.#choiceHint(draft.pendingChoice)); }
1094
+ if (this.#state.route) lines.push(routeText(this.#state.route));
845
1095
  if (trips.length) {
846
1096
  lines.push('去过的地方:');
847
1097
  for (const t of trips) {
@@ -850,6 +1100,7 @@ export class FunWorld {
850
1100
  const archived = !(this.#state.trips ?? []).some((x) => x.id === t.id);
851
1101
  lines.push(`- ${when} ${tripSummary(t)}${kept ? '(已珍藏)' : ''}${archived && !kept ? '(近期行程已归档)' : ''}`);
852
1102
  lines.push(` 行程 ID:${t.id}`);
1103
+ if (t.routeId) lines.push(' 同次出门:' + t.routeId + ' · 第' + t.routeOrder + '站');
853
1104
  if (t.note) lines.push(` (你记的:${t.note})`);
854
1105
  }
855
1106
  }
@@ -897,7 +1148,7 @@ export class FunWorld {
897
1148
 
898
1149
  const lines = [];
899
1150
  if (only) {
900
- const prog = progressFor(only, allMemories, this.#state.collection);
1151
+ const prog = progressFor(only, allMemories, this.#state.collection, this.#state.exploration);
901
1152
  lines.push('进度按当前场所清单统计;移除或改名的旧项目仍保留在回忆中。');
902
1153
  const group = target;
903
1154
  lines.push(`${only.name}的架子(去过 ${prog.visits} 次):`);
@@ -939,7 +1190,7 @@ export class FunWorld {
939
1190
  }
940
1191
  // 哪几处快集齐了:这是「再去一次把它补完」的钩子,比总数有用。
941
1192
  const close = places
942
- .map((v) => ({ v, p: progressFor(v, trips, this.#state.collection) }))
1193
+ .map((v) => ({ v, p: progressFor(v, trips, this.#state.collection, this.#state.exploration) }))
943
1194
  .filter((x) => x.p.visits > 0 && x.p.areas.total > 0)
944
1195
  .sort((a, b) => b.p.percent - a.p.percent || b.p.visits - a.p.visits)
945
1196
  .slice(0, 3);
@@ -1031,15 +1282,20 @@ export class FunWorld {
1031
1282
  return normalizeState(this.#state, dayIn(this.timezone, now), now, this.#ttlMin(), this.timezone);
1032
1283
  }
1033
1284
 
1034
- async #save() {
1035
- if (!this.#state) return;
1285
+ async #save(state = this.#state) {
1286
+ if (!state) return;
1036
1287
  const file = this.stateFile();
1037
1288
  await mkdir(dirname(file), { recursive: true });
1038
1289
  const tmp = `${file}.tmp`;
1039
- await writeFile(tmp, JSON.stringify(this.#state, null, 2), 'utf8');
1290
+ await writeFile(tmp, JSON.stringify(state, null, 2), 'utf8');
1040
1291
  await rename(tmp, file);
1041
1292
  }
1042
1293
 
1294
+ async #commitState(next) {
1295
+ await this.#save(next);
1296
+ this.#state = next;
1297
+ }
1298
+
1043
1299
  #serial(task) {
1044
1300
  const run = () => task();
1045
1301
  const result = this.#queue.then(run, run);
@@ -1060,11 +1316,10 @@ export class FunWorld {
1060
1316
  const t = text(this.language);
1061
1317
  const p = panelText(this.language);
1062
1318
  const now = this.#now();
1063
- const state = this.#state ?? newState(dayIn(this.timezone, now));
1319
+ const { session, draft } = this.#outings(now);
1064
1320
  const nowMin = minutesIn(this.timezone, now);
1065
1321
  const places = this.#places();
1066
1322
  const openCount = places.filter((v) => hoursState(v, nowMin) !== 'closed').length;
1067
- const session = state.session;
1068
1323
  const badges = [
1069
1324
  {
1070
1325
  label: t.badgePlaces,
@@ -1080,13 +1335,14 @@ export class FunWorld {
1080
1335
  tone: 'on',
1081
1336
  });
1082
1337
  }
1338
+ if (draft) badges.unshift({ label: '未逛完', value: draft.placeName, tone: 'plain' });
1083
1339
  return {
1084
1340
  label: t.label,
1085
1341
  lamps: [{
1086
1342
  label: t.lamp,
1087
1343
  state: this.#started ? 'online' : 'offline',
1088
1344
  hint: this.#started
1089
- ? (session ? `正在${session.placeName}逛:${visitedText(session)}` : '没在逛')
1345
+ ? (session ? `正在${session.placeName}逛:${visitedText(session)}` : (draft ? `「${draft.placeName}」还没逛完` : '没在逛'))
1090
1346
  : t.stopped,
1091
1347
  }],
1092
1348
  badges,
@@ -1097,11 +1353,12 @@ export class FunWorld {
1097
1353
  description: p.places.description,
1098
1354
  // getMethods 是**只读**方法;save/remove/reset/resetAll 是写方法,
1099
1355
  // 单独声明给宿主看,免得面板被当成纯展示、宿主判定它不需要刷新。
1100
- getMethods: ['list', 'blank'],
1101
- methods: ['save', 'remove', 'reset', 'resetAll'],
1356
+ getMethods: ['list', 'blank', 'history'],
1357
+ methods: ['save', 'remove', 'reset', 'resetAll', 'resume', 'closeDraft'],
1102
1358
  },
1103
1359
  { id: 'book', title: p.book.title, description: p.book.description, getMethods: ['list'], methods: ['favorite', 'wish'] },
1104
- { id: 'shelf', title: p.shelf.title, description: p.shelf.description, getMethods: ['list'] },
1360
+ { id: 'shelf', title: p.shelf.title, description: p.shelf.description, getMethods: ['list', 'trip'] },
1361
+ { id: 'stories', title: this.language === 'en' ? 'Story packs' : '地点剧情包', description: '导入、校验、预览和管理本地原创剧情包。', getMethods: ['list', 'template', 'validate', 'preview', 'export'], methods: ['import', 'enable', 'disable', 'remove'] },
1105
1362
  ],
1106
1363
  invoke: (panel, method, args) => this.#invoke(panel, method, args ?? []),
1107
1364
  config: [configGroup(this.language)],
@@ -1144,9 +1401,25 @@ export class FunWorld {
1144
1401
  async #invoke(panel, method, args) {
1145
1402
  try {
1146
1403
  this.#ensureStarted();
1404
+ if (panel === 'stories') {
1405
+ const reads = ['list', 'template', 'validate', 'preview', 'export'];
1406
+ const writes = ['import', 'enable', 'disable', 'remove'];
1407
+ const payload = { ...(args?.[0] ?? {}), action: method };
1408
+ if (reads.includes(method)) return await this.#storyLibrary.act(payload);
1409
+ if (writes.includes(method)) return await this.#serial(() => this.#storyLibrary.act(payload));
1410
+ throw new Error('不支持的剧情包操作');
1411
+ }
1147
1412
  if (panel === 'places') {
1148
1413
  switch (method) {
1149
1414
  case 'list': return this.#placesData();
1415
+ case 'history': return typeof args?.[0]?.placeId === 'string' ? this.#tripLookup({ placeId: args[0].placeId }) : { ok: false, error: '缺少地点 ID。' };
1416
+ case 'resume':
1417
+ case 'closeDraft': {
1418
+ const id = args?.[0]?.id;
1419
+ if (typeof id !== 'string' || !id) return { ok: false, error: '缺少未完行程 ID,请刷新后重试。' };
1420
+ const result = await this.#serial(() => method === 'resume' ? this.#resumeTool(id) : this.#homeTool({ draftId: id }));
1421
+ return result.failed ? { ok: false, error: result.text } : { ok: true, text: result.text.split('\n')[0] };
1422
+ }
1150
1423
  // 写方法:只动用户的 venues.json,绝不动预设常量。
1151
1424
  case 'save': return await this.#saveVenue(args?.[0] ?? args ?? {});
1152
1425
  case 'remove': return await this.#removeVenue(args?.[0]?.id ?? args?.id);
@@ -1159,7 +1432,7 @@ export class FunWorld {
1159
1432
  }
1160
1433
  if (panel === 'book') {
1161
1434
  switch (method) {
1162
- case 'list': this.#state = this.#normalizeState(); return this.#bookData();
1435
+ case 'list': return this.#bookData();
1163
1436
  case 'favorite': return await this.#favorite(args?.[0]?.id, args?.[0]?.keep !== false);
1164
1437
  case 'wish': return await this.#serial(() => this.#manageWish(args?.[0] ?? {}));
1165
1438
  default: throw new Error(`book 没有 ${method} 这个方法`);
@@ -1168,6 +1441,7 @@ export class FunWorld {
1168
1441
  if (panel === 'shelf') {
1169
1442
  switch (method) {
1170
1443
  case 'list': return this.#shelfData();
1444
+ case 'trip': return this.#tripLookup({ id: args?.[0]?.id }, true);
1171
1445
  default: throw new Error(`shelf 没有 ${method} 这个方法`);
1172
1446
  }
1173
1447
  }
@@ -1290,9 +1564,9 @@ export class FunWorld {
1290
1564
  const tz = this.timezone;
1291
1565
  const st = this.#state ?? newState(dayIn(tz, now));
1292
1566
  const recent = recentPlaceIds(st, 3);
1293
- const all = this.#places();
1294
- const places = all.map((v) => {
1295
- const state = hoursState(v, nowMin);
1567
+ const { session, draft } = this.#outings(now);
1568
+ const recommendations = this.#recommendations(allPlaces(nowMin, recent, this.#places()), nowMin, now);
1569
+ const places = recommendations.map(({ venue: v, state, phase, areas, wishReason, revisitReason }) => {
1296
1570
  return {
1297
1571
  id: v.id,
1298
1572
  name: v.name,
@@ -1320,15 +1594,17 @@ export class FunWorld {
1320
1594
  randomEvents: v.randomEvents ?? [],
1321
1595
  recommendedOutfit: v.recommendedOutfit,
1322
1596
  food: v.food ? { label: v.food.label, items: v.food.items, verb: v.food.verb } : null,
1323
- areas: areasNow(v, nowMin),
1597
+ areas: state === 'closed' ? areasNow(v, nowMin) : areas,
1598
+ wishReason,
1599
+ revisitReason,
1324
1600
  areaCount: v.areas.length,
1325
1601
  souvenirs: v.souvenirs,
1326
1602
  photoSpots: v.photoSpots,
1327
1603
  recent: recent.includes(v.id),
1328
1604
  // 去过几次:面板上标「去过 3 次」比什么都不说有用。
1329
- visitCount: historyFor(st.trips, v.id, dayIn(tz, now), tz)?.visitCount ?? 0,
1605
+ visitCount: this.#history(v.id, dayIn(tz, now))?.visitCount ?? 0,
1330
1606
  // 时段:现在处于哪一段、这一处共有哪几段(面板上做「换时间来是另一副样子」的提示)
1331
- phase: phaseLabelAt(v, nowMin) || null,
1607
+ phase: phase || null,
1332
1608
  phases: Array.isArray(v.phases) ? v.phases.map((x) => ({
1333
1609
  key: x.key, label: x.label, from: x.from, to: x.to,
1334
1610
  overridesDesc: typeof x.desc === 'string' && Boolean(x.desc.trim()),
@@ -1338,8 +1614,7 @@ export class FunWorld {
1338
1614
  food: hasFood(v) ? { label: v.food.label, items: v.food.items, verb: v.food.verb } : null,
1339
1615
  };
1340
1616
  });
1341
- // 开着的排前面;面板不截断,全部场所都给它,前端自己分组。
1342
- places.sort((a, b) => rankOf(a.state) - rankOf(b.state));
1617
+
1343
1618
 
1344
1619
  return {
1345
1620
  ok: true,
@@ -1355,25 +1630,39 @@ export class FunWorld {
1355
1630
  openCount: places.filter((x) => x.state !== 'closed').length,
1356
1631
  total: places.length,
1357
1632
  places,
1358
- session: st.session ? {
1359
- placeId: st.session.placeId,
1360
- placeName: st.session.placeName,
1361
- scene: st.session.scene,
1362
- outfit: st.session.outfit,
1363
- company: st.session.company || '',
1364
- enteredHm: hmIn(tz, st.session.enteredAt),
1365
- lastHm: hmIn(tz, st.session.lastAt),
1366
- stayedMin: Math.max(0, Math.round((now - st.session.enteredAt) / 60000)),
1367
- stale: isStale(st.session, now, this.#ttlMin()),
1368
- visited: st.session.visited.map((v) => ({ area: v.area, note: v.note, hm: hmIn(tz, v.at) })),
1369
- souvenirs: st.session.souvenirs,
1370
- photos: st.session.photos,
1371
- ate: (st.session.ate ?? []).map((x) => ({ item: x.item, verb: x.verb, hm: hmIn(tz, x.at) })),
1372
- events: st.session.events,
1373
- pendingChoice: st.session.pendingChoice ?? null,
1374
- choices: st.session.choices ?? [],
1375
- venueAreaCount: places.find((v) => v.id === st.session.placeId)?.areas.length ?? null,
1376
- } : null,
1633
+ session: this.#outingData(session, places, now),
1634
+ draft: this.#outingData(draft, places, now, true),
1635
+ upcomingWish: this.#upcomingWish(recommendations),
1636
+ recommendationIds: recommendations.filter((p) => p.state !== 'closed').slice(0, 3).map((p) => p.venue.id),
1637
+ route: this.#state.route ? structuredClone(this.#state.route) : null,
1638
+ };
1639
+ }
1640
+
1641
+ #outingData(outing, places, now, isDraft = false) {
1642
+ if (!outing) return null;
1643
+ const tz = this.timezone;
1644
+ const venue = places.find((v) => v.id === outing.placeId);
1645
+ return {
1646
+ id: outing.id,
1647
+ placeId: outing.placeId,
1648
+ placeName: outing.placeName,
1649
+ scene: outing.scene,
1650
+ outfit: outing.outfit,
1651
+ company: outing.company || '',
1652
+ enteredHm: hmIn(tz, outing.enteredAt),
1653
+ lastHm: hmIn(tz, outing.lastAt),
1654
+ lastDay: dayIn(tz, outing.lastAt),
1655
+ stayedMin: outingMinutes(outing, isDraft ? outing.lastAt : now),
1656
+ stale: isStale(outing, now, this.#ttlMin()),
1657
+ visited: outing.visited.map((v) => ({ area: v.area, note: v.note, hm: hmIn(tz, v.at) })),
1658
+ souvenirs: outing.souvenirs,
1659
+ photos: outing.photos,
1660
+ ate: (outing.ate ?? []).map((x) => ({ item: x.item, verb: x.verb, hm: hmIn(tz, x.at) })),
1661
+ events: outing.events,
1662
+ pendingChoice: outing.pendingChoice ?? null,
1663
+ choices: outing.choices ?? [],
1664
+ venueAreaCount: venue?.areas.length ?? null,
1665
+ canResume: Boolean(venue),
1377
1666
  };
1378
1667
  }
1379
1668
 
@@ -1387,6 +1676,7 @@ export class FunWorld {
1387
1676
  const tz = this.timezone;
1388
1677
  const now = this.#now();
1389
1678
  const st = this.#state ?? newState(dayIn(tz, now));
1679
+ const { session, draft } = this.#outings(now);
1390
1680
  const recentIds = new Set((st.trips ?? []).map((t) => t.id));
1391
1681
  const keptIds = new Set((st.keepsakeTrips ?? []).map((t) => t.id));
1392
1682
  const keptTrips = new Map((st.keepsakeTrips ?? []).map((t) => [t.id, t]));
@@ -1397,6 +1687,10 @@ export class FunWorld {
1397
1687
  .map((t) => ({
1398
1688
  id: t.id,
1399
1689
  kept: keptIds.has(t.id) || t.favorite === true,
1690
+ routeId: t.routeId || '',
1691
+ routeOrder: t.routeOrder || 0,
1692
+ timeline: timelineFor(t, tz),
1693
+ timelineTruncated: t.timelineTruncated === true,
1400
1694
  archived: !recentIds.has(t.id),
1401
1695
  placeId: t.placeId,
1402
1696
  placeName: t.placeName,
@@ -1407,7 +1701,7 @@ export class FunWorld {
1407
1701
  day: tripDay(t, this.timezone),
1408
1702
  enteredHm: t.enteredAt ? hmIn(tz, t.enteredAt) : '',
1409
1703
  leftHm: t.leftAt ? hmIn(tz, t.leftAt) : '',
1410
- stayedMin: t.leftAt && t.enteredAt ? Math.max(0, Math.round((t.leftAt - t.enteredAt) / 60000)) : 0,
1704
+ stayedMin: t.leftAt && t.enteredAt ? outingMinutes(t, t.leftAt) : 0,
1411
1705
  note: t.note || '',
1412
1706
  visited: t.visited.map((v) => v.area),
1413
1707
  souvenirs: t.souvenirs,
@@ -1438,8 +1732,10 @@ export class FunWorld {
1438
1732
  photoCount: trips.reduce((n, t) => n + t.photos.length, 0),
1439
1733
  visitedAreaCount: trips.reduce((n, t) => n + t.visited.length, 0),
1440
1734
  mostVisited,
1735
+ routes: structuredClone(st.routes ?? []),
1441
1736
  trips,
1442
- session: st.session ? { placeName: st.session.placeName, summary: tripSummary(st.session) } : null,
1737
+ session: session ? { placeName: session.placeName, summary: tripSummary(session) } : null,
1738
+ draft: draft ? { placeName: draft.placeName, summary: tripSummary(draft) } : null,
1443
1739
  };
1444
1740
  }
1445
1741
 
@@ -1458,19 +1754,20 @@ export class FunWorld {
1458
1754
  const detailMemories = new Map(allMemories.map((t) => [t.id, t]));
1459
1755
  for (const item of rack.items) {
1460
1756
  item.memories = (st.collection ?? []).find((x) => x.key === item.key)?.tripIds
1461
- ?.map((id) => detailMemories.get(id)).filter(Boolean).map((t) => ({ day: tripDay(t, this.timezone), summary: tripSummary(t), note: t.note, company: t.company })) ?? item.memories;
1757
+ ?.map((id) => detailMemories.get(id)).filter(Boolean).map((t) => ({ id: t.id, day: tripDay(t, this.timezone), summary: tripSummary(t), note: t.note, company: t.company })) ?? item.memories;
1462
1758
  if (item.memories.length < item.times) item.archivedCount = item.times - item.memories.length;
1463
1759
  }
1464
1760
  const places = this.#places();
1465
1761
 
1466
1762
  // 每一处都给进度:面板上按「去过但没逛遍」排前面,没去过的排最后。
1467
1763
  const progress = places.map((v) => {
1468
- const p = progressFor(v, trips, st.collection);
1764
+ const p = progressFor(v, trips, st.collection, st.exploration);
1469
1765
  return {
1470
1766
  placeId: v.id,
1471
1767
  placeName: v.name,
1472
1768
  scene: v.scene,
1473
1769
  visits: p.visits,
1770
+ phases: explorationFor(st.exploration, v.id)?.phases ?? [],
1474
1771
  percent: p.percent,
1475
1772
  areas: { done: p.areas.done, total: p.areas.total, left: p.areas.left, complete: p.areas.complete },
1476
1773
  souvenirs: { done: p.souvenirs.done, total: p.souvenirs.total, left: p.souvenirs.left, complete: p.souvenirs.complete },
@@ -1502,10 +1799,11 @@ export class FunWorld {
1502
1799
 
1503
1800
  /** 清空她的出游记录(存储页「清掉」)。只清 state 这一份,不碰别的 World。 */
1504
1801
  async #clearState() {
1505
- this.#state = newState(dayIn(this.timezone, this.#now()));
1506
- await this.#save();
1507
- this.#host?.log?.info?.('娱乐时间:出游记录已清空');
1508
- return { ok: true };
1802
+ return this.#serial(async () => {
1803
+ await this.#commitState(newState(dayIn(this.timezone, this.#now())));
1804
+ this.#host?.log?.info?.('娱乐时间:出游记录已清空');
1805
+ return { ok: true };
1806
+ });
1509
1807
  }
1510
1808
 
1511
1809
  // -------------------------------------------------------------------------
@@ -1521,6 +1819,7 @@ export class FunWorld {
1521
1819
  const venueFile = await this.#loadVenueFile();
1522
1820
  this.#userVenues = venueFile.venues;
1523
1821
  this.#overrides = venueFile.overrides;
1822
+ await this.#storyLibrary.load();
1524
1823
  this.#started = true;
1525
1824
  this.#host?.log?.info?.('娱乐时间已启动', {
1526
1825
  places: this.#places().length,
@@ -1533,8 +1832,10 @@ export class FunWorld {
1533
1832
 
1534
1833
  async stop() {
1535
1834
  this.#started = false;
1536
- try { await this.#save(); } catch { /* 停的时候存不上就算了 */ }
1537
- this.#host = null;
1835
+ await this.#serial(async () => {
1836
+ try { await this.#save(); } catch { /* 停的时候存不上就算了 */ }
1837
+ this.#host = null;
1838
+ });
1538
1839
  }
1539
1840
  }
1540
1841