dsh-world 0.7.2 → 0.7.4

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.
Files changed (78) hide show
  1. package/CHANGELOG.md +403 -379
  2. package/INSTALL.md +314 -314
  3. package/LICENSE +21 -21
  4. package/NOTES.md +23 -13
  5. package/README.md +22 -7
  6. package/client/index.js +74 -27
  7. package/cordis.patch.yml +6 -6
  8. package/lib/archiveSelection.d.ts +6 -2
  9. package/lib/archiveSelection.js +21 -12
  10. package/lib/compaction.d.ts +7 -0
  11. package/lib/compaction.js +18 -9
  12. package/lib/compactionSwap.d.ts +17 -0
  13. package/lib/compactionSwap.js +68 -6
  14. package/lib/console/routes.d.ts +2 -3
  15. package/lib/console/routes.js +7 -8
  16. package/lib/console/snapshot.d.ts +1 -3
  17. package/lib/console/snapshot.js +0 -3
  18. package/lib/ecosystem/bridge/bridge.d.ts +5 -0
  19. package/lib/ecosystem/bridge/bridge.js +2 -1
  20. package/lib/ecosystem/bridge/route.d.ts +4 -6
  21. package/lib/ecosystem/bridge/route.js +34 -58
  22. package/lib/ecosystem/qq/panel.d.ts +0 -1
  23. package/lib/ecosystem/qq/route.d.ts +6 -7
  24. package/lib/ecosystem/qq/route.js +10 -10
  25. package/lib/ecosystem/qq/snowluma-start.d.ts +1 -0
  26. package/lib/ecosystem/qq/snowluma-start.js +41 -8
  27. package/lib/ecosystem/qq/supervisor.d.ts +1 -2
  28. package/lib/ecosystem/qq/supervisor.js +4 -2
  29. package/lib/ecosystem/qq-native/index.js +2 -0
  30. package/lib/ecosystem/qq-native/native-bridge.d.ts +0 -1
  31. package/lib/ecosystem/qq-native/native-bridge.js +0 -2
  32. package/lib/ecosystem/qq-native/snowluma.js +11 -2
  33. package/lib/ecosystem/shared/turn.d.ts +3 -0
  34. package/lib/ecosystem/shared/turn.js +9 -2
  35. package/lib/ecosystem/wechat/home.d.ts +3 -0
  36. package/lib/ecosystem/wechat/home.js +12 -4
  37. package/lib/ecosystem/wechat/index.d.ts +0 -1
  38. package/lib/ecosystem/wechat/index.js +9 -6
  39. package/lib/hostContract.d.ts +19 -0
  40. package/lib/index.js +117 -49
  41. package/lib/life/toolRegistry.js +2 -2
  42. package/lib/memoryFiles.d.ts +0 -1
  43. package/lib/memoryStore.d.ts +0 -1
  44. package/lib/memoryStore.js +0 -1
  45. package/lib/memoryTools.d.ts +0 -1
  46. package/lib/memoryTools.js +2 -3
  47. package/lib/mood.d.ts +28 -0
  48. package/lib/mood.js +69 -0
  49. package/lib/promptSection.d.ts +7 -5
  50. package/lib/promptSection.js +74 -28
  51. package/lib/runtime.d.ts +6 -2
  52. package/lib/runtime.js +163 -26
  53. package/lib/self.d.ts +1 -1
  54. package/lib/self.js +1 -1
  55. package/lib/sourceArchive.d.ts +4 -2
  56. package/lib/sourceArchive.js +18 -4
  57. package/lib/store.js +2 -1
  58. package/lib/types.d.ts +3 -1
  59. package/lib/worldPrompt.d.ts +2 -3
  60. package/lib/worldPrompt.js +2 -3
  61. package/lib/worldRoutes.d.ts +9 -0
  62. package/lib/worldRoutes.js +29 -0
  63. package/lib/worldScope.d.ts +5 -5
  64. package/lib/worldScope.js +16 -7
  65. package/lib/worldSwitch.d.ts +1 -2
  66. package/lib/worldSwitch.js +1 -1
  67. package/package.json +17 -16
  68. package/scripts/compact-home.mjs +29 -29
  69. package/scripts/enable-tool-free-compaction.ps1 +33 -33
  70. package/scripts/import-stickers.mjs +17 -17
  71. package/scripts/update-world.mjs +2 -2
  72. package/src/ecosystem/README.md +1 -1
  73. package/src/ecosystem/wechat/windows/README.md +3 -3
  74. package/src/ecosystem/wechat/windows/adapter.py +21 -3
  75. package/src/ecosystem/wechat/windows/engine/profiles.json +142 -142
  76. package/src/ecosystem/wechat/windows/presence.py +109 -109
  77. package/templates/alarm.md +2 -2
  78. package/templates/world-prompt.md +11 -2
package/lib/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { existsSync, readFileSync, rmSync } from 'node:fs';
2
- import { join } from 'node:path';
2
+ import { dirname, join } from 'node:path';
3
3
  // DSH's HMR reconciles the profile once at every start and drops, as failed imports, the profile modules whose import
4
4
  // has not finished (dsh-hmr `reconcileProfile`). The QQ module is imported later and is the only way to `ws`, a CommonJS
5
5
  // package: dropped halfway, Node fails it with ERR_INTERNAL_ASSERTION and QQ switched on at boot never starts. Loaded
@@ -13,17 +13,18 @@ import { consoleRoute } from "./console/routes.js";
13
13
  import { consoleSources } from "./console/snapshot.js";
14
14
  import { compactionFor, createHomeApply } from "./console/homeApply.js";
15
15
  import { errorText, Faults } from "./faults.js";
16
- import { swapCompactionOnce, swapPresetCompaction, swapStockCompaction } from "./compactionSwap.js";
16
+ import { repairCopiedPresets, swapCompactionOnce, swapPresetCompaction, swapStockCompaction } from "./compactionSwap.js";
17
17
  import { hostLife } from "./life/host.js";
18
18
  import { createLifeStore, durableWrite } from "./life/lifeStore.js";
19
19
  import { toastSupported, windowsToast } from "./life/notify.js";
20
20
  import { createLifeRuntime } from "./life/runtime.js";
21
21
  import { createOutlet } from "./ecosystem/shared/outlets.js";
22
22
  import { readPersona, writePersona } from "./persona.js";
23
+ import { MOOD_FILE } from "./mood.js";
23
24
  import { qqRoute } from "./ecosystem/qq/route.js";
24
25
  import { createConsoleDoors, discoverSnowlumaHome } from "./ecosystem/qq/panel.js";
25
26
  import { createMemory } from "./memory.js";
26
- import { createWorldRuntime } from "./runtime.js";
27
+ import { createWorldRuntime, guardWorldContext } from "./runtime.js";
27
28
  import { createArchiveStore } from "./store.js";
28
29
  import { DEFAULT_TEMPLATE_FILE, MEMORY_SNIPPET_FILE, memoryTemplateGaps, roomTitle, worldNames } from "./worldPrompt.js";
29
30
  import { createWorldSwitch } from "./worldSwitch.js";
@@ -32,16 +33,17 @@ import { createWechatModule } from "./ecosystem/wechat/index.js";
32
33
  import { createWechatRecorder } from "./ecosystem/wechat/archive.js";
33
34
  import { createAdapterSupervisor } from "./ecosystem/wechat/supervisor.js";
34
35
  import { createChannelSessions } from "./ecosystem/shared/sessions.js";
35
- import { createArchiveSelection, createWorkspaceMembership } from "./archiveSelection.js";
36
+ import { canonicalPath, createArchiveSelection, createWorkspaceMembership } from "./archiveSelection.js";
36
37
  import { inWorld } from "./sourceArchive.js";
38
+ import { validWorldId, worldListRoute, worldPath } from "./worldRoutes.js";
37
39
  import { createWorkspacePermissions } from "./workspacePermissions.js";
38
40
  import { createPhotoStore } from "./life/photos.js";
39
41
  import { createQqSdkInstaller } from "./ecosystem/qq-native/sdkInstall.js";
40
42
  export { createWorldRuntime } from "./runtime.js";
41
43
  export const name = 'dsh-world';
42
44
  export const inject = ['agents', 'sessions', 'sessionPersistence', 'llm'];
43
- // One companion per profile is the usual case, so it works as installed: the standard preset, a world named
44
- // default and the system time zone, with the life line on (it needs the desktop host's services and stays off without them).
45
+ // The installed default uses the standard preset, a world named default and the system time zone.
46
+ // The life line is on by default and needs the desktop host's services.
45
47
  const systemTimeZone = Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC';
46
48
  export const Config = z.object({
47
49
  worldId: z.string().default('default'), agentPreset: z.string().default('standard'), timeZone: z.string().default(systemTimeZone),
@@ -53,7 +55,7 @@ export const Config = z.object({
53
55
  selfFile: z.string(), worldPromptFile: z.string(), alarmTemplateFile: z.string(), personaFile: z.string(),
54
56
  // Where her words go outside DSH; no app is known by name (see README for the push body).
55
57
  outlets: z.array(z.object({ name: z.string().required(), url: z.string(), urlFile: z.string(), path: z.string(), kinds: z.array(z.union([z.const('reply'), z.const('busy'), z.const('reach')])) })).default([]),
56
- // A local app may hand her partner's words to her home through POST /dsh-world/bridge/say.
58
+ // A local app reads bridge.json to send words to this world's home.
57
59
  bridge: z.boolean().default(false),
58
60
  qqNative: z.object({
59
61
  enabled: z.boolean().default(false),
@@ -76,7 +78,7 @@ export const Config = z.object({
76
78
  // SnowLuma 装在哪:控制台那扇门要去它的 config/runtime.json 拿地址与端口。空着就按 D:\SnowLuma、
77
79
  // C:\SnowLuma、~/SnowLuma 挨个认(认「里面有 config/runtime.json」这一条)。
78
80
  snowlumaHome: z.string().default(''),
79
- // 看门狗:通道开着时每 30 秒探一次 wsUrl 的端口,不通就把 SnowLuma 拉起来。不想让插件动手就关掉,面板上的按钮照旧能用。
81
+ // 看门狗:每 30 秒探一次 wsUrl 的端口,不通且没有实例时才拉起。关掉后面板上的按钮照旧能用。
80
82
  supervise: z.boolean().default(true),
81
83
  // 谁和她的家会话共用一个入口。'owner'(默认)=群各自独立、私聊用她的家;'all'=都用她的家;
82
84
  // 'none'=谁都不绑,每个入口各建一个 —— 开发测试 QQ 的时候填 none,回合就不会走进步话生活的家里。
@@ -96,14 +98,43 @@ export const Config = z.object({
96
98
  // The console and the bridge answer only this machine by name, plus these (a LAN address or domain behind a proxy).
97
99
  allowedHosts: z.array(z.string()).default([]),
98
100
  });
101
+ function profileWorlds(root) {
102
+ const existing = root.get('dshWorldProfile');
103
+ if (existing)
104
+ return existing;
105
+ const worlds = { rooms: new Map(), consoles: new Map(), profileEdits: Promise.resolve() };
106
+ root.provide('dshWorldProfile', worlds);
107
+ guardWorldContext(root, (session, worldId) => {
108
+ if (worldId !== undefined)
109
+ return worlds.rooms.get(worldId)?.authorize(session);
110
+ for (const room of worlds.rooms.values()) {
111
+ const token = room.authorize(session);
112
+ if (token !== undefined)
113
+ return token;
114
+ }
115
+ });
116
+ return worlds;
117
+ }
99
118
  /**
100
119
  * Her world runs only after her partner presses start in the world console, and stops when they press stop:
101
120
  * memory block, persona, world prompt, archive and life line come and go together. The switch is kept in
102
121
  * `<world>/world.json`, so it outlasts a restart.
103
122
  */
104
123
  export async function apply(ctx, config) {
124
+ const { root } = ctx;
125
+ const { worldId } = config;
126
+ if (!validWorldId(worldId))
127
+ throw new TypeError('dsh-world: invalid worldId');
128
+ const worlds = profileWorlds(root);
105
129
  const dshHome = resolveDshHome();
106
- const worldDir = join(dshHome, 'worlds', config.worldId);
130
+ const worldDir = join(dshHome, 'worlds', worldId);
131
+ const roomDir = join(worldDir, 'room');
132
+ const prefix = worldPath(worldId);
133
+ const roomPath = canonicalPath(roomDir);
134
+ const dataPath = canonicalPath(worldDir);
135
+ if ([...worlds.rooms].some(([id, room]) => id.toLowerCase() === worldId.toLowerCase() || canonicalPath(room.path) === roomPath || canonicalPath(dirname(room.path)) === dataPath)) {
136
+ throw new Error(`dsh-world: worldId ${worldId} 与已加载的世界重复`);
137
+ }
107
138
  const store = createArchiveStore({ ...config, root: dshHome });
108
139
  const power = createWorldSwitch(worldDir, config.archiveScope ?? 'workspace', config.fallbackWakeTime);
109
140
  const memoryConfig = { ...config, archiveScope: power.archiveScope() };
@@ -125,7 +156,6 @@ export async function apply(ctx, config) {
125
156
  const selfFile = config.selfFile || join(worldDir, 'room', '我是谁.md');
126
157
  const personaFile = config.personaFile || join(worldDir, 'persona.md');
127
158
  const worldPromptFile = config.worldPromptFile || join(worldDir, 'world-prompt.md');
128
- const roomDir = join(worldDir, 'room');
129
159
  const options = { worldDir, roomDir, diaryDir: config.diaryDir || join(worldDir, 'diary'), selfFile, schedule: () => ({ review: power.reviewTime(), wake: power.wakeTime() }), timeZone: config.timeZone, alarmFile: config.alarmTemplateFile || join(worldDir, 'alarm.md') };
130
160
  /** The name in her persona comes first, then the configured one. */
131
161
  const names = () => worldNames({ ...config, companionName: readPersona(personaFile).名字 || config.companionName });
@@ -145,10 +175,9 @@ export async function apply(ctx, config) {
145
175
  })();
146
176
  const storedHome = () => lifeStore?.read().homeSessionId;
147
177
  let isHome = id => id === storedHome();
148
- /** Whose conversations her archive keeps (the home, or her whole workspace). */
149
- const archiveSession = createArchiveSelection(ctx, power.archiveScope(), id => isHome(id), options.roomDir);
150
178
  /** Where her world reaches: her room's workspace, and in it the sessions of her preset. */
151
- const inWorkspace = createWorkspaceMembership(ctx, options.roomDir);
179
+ const inWorkspace = createWorkspaceMembership(ctx, roomDir, () => Array.from(worlds.rooms.values(), room => room.path));
180
+ const archiveSession = createArchiveSelection(power.archiveScope(), id => isHome(id), inWorkspace);
152
181
  const inWorldSession = (session) => inWorld(session, config, inWorkspace);
153
182
  /** Long-term memory over the archive and her own files; the tools and the console are two doors to it. */
154
183
  const memoryService = createMemory({ store: store.memory, timeZone: config.timeZone, sources: { diaryDir: options.diaryDir }, visible: id => archiveSession(id) });
@@ -156,21 +185,25 @@ export async function apply(ctx, config) {
156
185
  const memoryHealth = () => memoryService.status().failures.map(failure => `记忆来源 ${failure.sourceId}:${failure.message}`);
157
186
  let memory;
158
187
  let stopLifeLine;
188
+ let disposed = false;
189
+ let lifecycle = Promise.resolve();
190
+ const changeWorld = (change) => lifecycle = lifecycle.then(change, change);
159
191
  /**
160
192
  * A memory line that cannot start is a fault, never a failed plugin: the console must still open to say so, and
161
193
  * the life line and channels run on. Stopping and starting the world from the console tries again.
162
194
  */
163
195
  async function startMemory(fresh) {
164
- if (memory)
196
+ if (memory || disposed)
165
197
  return;
166
198
  const prompt = { file: worldPromptFile, persona: personaFile, conversationsDir: join(worldDir, 'conversations'), names: names(), memoryTools: true, ...(config.life ? { life: options } : {}) };
167
- const runtime = createWorldRuntime(ctx, { ...memoryConfig, selfFile }, store, { prompt, names, isHome: id => isHome(id), archiveSession, inWorkspace, memory: memoryService }, power.memoryTurns, power.coldHours);
199
+ const runtime = createWorldRuntime(ctx, { ...memoryConfig, selfFile, moodFile: join(roomDir, MOOD_FILE) }, store, { prompt, names, isHome: id => isHome(id), archiveSession, inWorkspace, memory: memoryService }, power.memoryTurns, power.coldHours);
200
+ memory = runtime;
168
201
  try {
169
202
  await runtime.start({ fresh });
170
- memory = runtime;
171
203
  faults.clear('memory');
172
204
  }
173
205
  catch (error) {
206
+ memory = undefined;
174
207
  faults.set('memory', `记忆线没能启动:${errorText(error)}`);
175
208
  ctx.logger.error(error);
176
209
  }
@@ -180,45 +213,65 @@ export async function apply(ctx, config) {
180
213
  memory = undefined;
181
214
  await running?.stop();
182
215
  }
183
- ctx.effect(() => async () => {
184
- try {
185
- await stopLifeLine?.();
186
- }
187
- finally {
188
- await stopMemory().finally(() => store.close());
189
- }
216
+ ctx.effect(() => {
217
+ worlds.rooms.set(worldId, {
218
+ path: roomDir,
219
+ authorize: session => {
220
+ if (!inWorldSession(session))
221
+ return undefined;
222
+ return !disposed && power.running() && memory ? memory.scopeToken : false;
223
+ },
224
+ });
225
+ return () => {
226
+ disposed = true;
227
+ return changeWorld(async () => {
228
+ try {
229
+ await stopLifeLine?.();
230
+ }
231
+ finally {
232
+ await stopMemory().finally(() => store.close()).finally(() => worlds.rooms.delete(worldId));
233
+ }
234
+ });
235
+ };
190
236
  }, 'dsh-world memory line');
191
237
  if (power.running())
192
- await startMemory(false);
238
+ await changeWorld(() => startMemory(false));
193
239
  // The host's workspace service may come up after this plugin; what the first catch-up could not place is read then.
194
- ctx.inject(['workspaceRegistry'], injected => { void memory?.retryCatchUp().catch(error => injected.logger.error(error)); });
240
+ ctx.inject(['workspaceRegistry'], injected => {
241
+ void changeWorld(async () => { if (!disposed)
242
+ await memory?.retryCatchUp(); }).catch(error => injected.logger.error(error));
243
+ });
195
244
  // The console and the life line need the desktop host.
196
245
  ctx.inject(['sessionController', 'permissionPresets', 'webServer'], async (lifeCtx) => {
197
246
  const webServer = lifeCtx.webServer;
198
247
  const host = hostLife(lifeCtx);
199
248
  const configEditor = lifeCtx.get('configEditor');
200
- const swapCompaction = () => swapCompactionOnce({ enabled: config.replaceCompaction, profileDir: lifeCtx.get('profileContext')?.dir, done: power.compactionSwapped, markDone: power.markCompactionSwapped,
249
+ const profileDir = () => lifeCtx.get('profileContext')?.dir;
250
+ const swap = () => swapCompactionOnce({ enabled: config.replaceCompaction, profileDir: profileDir(), done: power.compactionSwapped, markDone: power.markCompactionSwapped,
201
251
  swap: async (dir) => { const row = swapStockCompaction(dir); return row.status === 'unchanged' && configEditor ? swapPresetCompaction(configEditor, config.agentPreset, dir) : row; },
202
252
  report: message => { faults.set('compaction-swap', message); lifeCtx.logger.warn(`dsh-world: ${message}`); } });
253
+ const repair = async () => {
254
+ const dir = profileDir();
255
+ if (configEditor && dir)
256
+ await repairCopiedPresets({ editor: configEditor, profileDir: dir, report: message => { faults.set('preset-repair', message); lifeCtx.logger.warn(`dsh-world: ${message}`); } });
257
+ };
258
+ // Different worlds may edit the same profile or preset on startup.
259
+ const editProfile = () => worlds.profileEdits = worlds.profileEdits.then(swap, swap).then(repair, repair);
203
260
  // The preset row the editor rewrites is active only once the host has finished loading.
204
261
  const appReady = lifeCtx.get('appReady');
205
262
  if (!appReady)
206
- void swapCompaction();
263
+ void editProfile();
207
264
  else
208
265
  lifeCtx.effect(() => {
209
266
  let closed = false;
210
267
  const cancel = appReady.onReady(() => { if (!closed)
211
- void swapCompaction(); });
268
+ void editProfile(); });
212
269
  return () => { closed = true; cancel(); };
213
270
  }, 'dsh-world compaction swap');
214
271
  const permissions = createWorkspacePermissions(lifeCtx, options.roomDir, power);
215
- // QQ 的两扇门:她自己那条 OneBot 通道的状态与开关,以及 SnowLuma 的控制台。**无条件注册** —— 通道
216
- // 关着的时候 /native 回 null,而 SnowLuma 那扇门跟通道没关系。(这里原来还有一半是给外面那个
217
- // qq-bridge 进程用的,连 qqBridgeDir 一起在 2026-10-27 拆掉了。当时的教训:那条路由是注册在「有桥
218
- // 目录」这个分支里的,配置一摘,整片 /dsh-world/qq/* 就全 404,界面也一起没了。所以现在它不再挂在
219
- // 任何配置上 —— 端点先存在,功能再按需开关。)
272
+ // SnowLuma 的控制台在 OneBot 通道关闭时仍可用。
220
273
  const doors = createConsoleDoors({ worldDir, snowlumaHome: config.qqNative?.snowlumaHome ?? '' });
221
- const unregisterQq = webServer.register(qqRoute(config.allowedHosts, doors, () => qqNative?.status() ?? null, patch => qqNative?.update(patch) ?? null));
274
+ const unregisterQq = webServer.register(qqRoute(prefix, config.allowedHosts, doors, () => qqNative?.status() ?? null, patch => qqNative?.update(patch) ?? null));
222
275
  lifeCtx.effect(() => () => unregisterQq(), 'dsh-world qq route');
223
276
  let life;
224
277
  const sdkAbort = new AbortController();
@@ -262,6 +315,8 @@ export async function apply(ctx, config) {
262
315
  if (wechat || !config.wechat)
263
316
  return;
264
317
  await wechatClosing;
318
+ if (wechat || life !== current || disposed || !power.running() || !power.wechatEnabled())
319
+ return;
265
320
  const groupSessions = createChannelSessions({ ctx: lifeCtx, host, store, roomDir: options.roomDir, roomTitle: roomTitle(names()), agentPreset: config.agentPreset });
266
321
  channels = groupSessions;
267
322
  wechat = createWechatModule({ ctx: lifeCtx, worldId: config.worldId, inWorld: inWorldSession, home: identity => identity.conversationType === 'group' ? groupSessions.open(identity) : current.home(), origin: () => host.origin(), file: join(worldDir, 'wechat.json'), incomingDir: join(worldDir, 'wechat-incoming'), allowedHosts: config.allowedHosts, settings: () => ({ contextMessages: power.wechatContext(), bufferSeconds: power.wechatBufferSeconds() }),
@@ -352,6 +407,8 @@ export async function apply(ctx, config) {
352
407
  return;
353
408
  try {
354
409
  await lifeStop;
410
+ if (disposed)
411
+ return;
355
412
  const outlets = config.outlets.map(outlet => createOutlet(outlet, () => host.origin()));
356
413
  const notifier = { ...(config.toast && toastSupported() ? { toast: windowsToast(config.toastAppId || undefined) } : {}), outlets };
357
414
  const current = createLifeRuntime({ ctx: lifeCtx, config: { ...config, companionName: names().companion }, options, store: lifeStore, host, notifier, dailyBudget: power.dailyBudget, inWorkspace, photos, alarmContext: now => wechat?.presence(now), afterReview: () => { if (power.compactAfterReview())
@@ -359,7 +416,7 @@ export async function apply(ctx, config) {
359
416
  life = current;
360
417
  isHome = current.isHome;
361
418
  if (config.bridge) {
362
- bridge = createBridge({ ctx: lifeCtx, home: () => current.home(), inWorld: inWorldSession, outlets, origin: () => host.origin(), file: join(worldDir, 'bridge.json'), name: names().companion });
419
+ bridge = createBridge({ ctx: lifeCtx, prefix, home: () => current.home(), inWorld: inWorldSession, outlets, origin: () => host.origin(), file: join(worldDir, 'bridge.json'), name: names().companion });
363
420
  bridge.start();
364
421
  }
365
422
  if (config.wechat && power.wechatEnabled())
@@ -387,18 +444,18 @@ export async function apply(ctx, config) {
387
444
  return lifeStop = Promise.all([lifeStop, closingWechat, homeApply.cancel()]).then(() => { });
388
445
  }
389
446
  stopLifeLine = stopLife;
390
- lifeCtx.effect(() => () => stopLife(), 'dsh-world life line');
447
+ lifeCtx.effect(() => () => changeWorld(stopLife), 'dsh-world life line');
391
448
  // The host matches exact routes before the longest prefix, so this path never reaches the console.
392
449
  if (config.bridge)
393
- lifeCtx.effect(() => webServer.register(bridgeRoute(() => bridge, config.allowedHosts)), 'dsh-world bridge route');
450
+ lifeCtx.effect(() => webServer.register(bridgeRoute(prefix, () => bridge, config.allowedHosts)), 'dsh-world bridge route');
394
451
  if (config.bridge)
395
- lifeCtx.effect(() => webServer.register(compactRoute(() => bridge, () => !power.running() || !life ? '请先启动世界生活线' : homeApply.request(), config.allowedHosts)), 'dsh-world compact route');
452
+ lifeCtx.effect(() => webServer.register(compactRoute(prefix, () => bridge, () => !power.running() || !life ? '请先启动世界生活线' : homeApply.request(), config.allowedHosts)), 'dsh-world compact route');
396
453
  // Her album lives in her room, so the console shows it whether or not the life line is running.
397
454
  const sources = consoleSources({ ctx: lifeCtx, config: memoryConfig, archive: store, longTerm: memoryService, names, ...(lifeStore ? { lifeStore } : {}), life: () => life, homeApply: homeApply.snapshot, compactAfterReview: power.compactAfterReview, ...(config.life ? { schedule: () => ({ review: power.reviewTime(), wake: power.wakeTime(), defaults: { review: DEFAULT_REVIEW_TIME, wake: config.fallbackWakeTime } }) } : {}), photos, diaryDir: options.diaryDir, running: power.running, dailyBudget: power.dailyBudget, memoryTurns: power.memoryTurns, coldHours: power.coldHours, selectedArchiveScope: power.selectedArchiveScope, workspacePermissions: permissions.snapshot, wechat: () => wechat ? { ...wechat.status(), adapter: adapter?.status() ?? null } : undefined, archiveSession, native: () => qqNative?.status() ?? null,
398
455
  modules: () => ({ wechat: { available: config.wechat, enabled: power.wechatEnabled(), running: wechat !== undefined }, qq: { available: Boolean(config.qqNative?.enabled), enabled: power.qqEnabled(), running: qqNative !== undefined, ...(qqSdk.needsRestart() ? { restartRequired: true } : {}) } }), faults: () => [...faults.list(), ...(adapter?.status().error ? [`微信适配器:${adapter.status().error}`] : []), ...(memory?.faults() ?? []), ...(bridge?.faults() ?? []), ...memoryHealth()] });
399
456
  const actions = {
400
- async start() {
401
- if (power.running())
457
+ start: () => changeWorld(async () => {
458
+ if (disposed || power.running())
402
459
  return;
403
460
  power.set(true);
404
461
  try {
@@ -408,19 +465,18 @@ export async function apply(ctx, config) {
408
465
  finally {
409
466
  sources.invalidate();
410
467
  }
411
- },
412
- async stop() {
413
- if (!power.running())
468
+ }),
469
+ stop: () => changeWorld(async () => {
470
+ if (disposed || !power.running())
414
471
  return;
415
472
  power.set(false);
416
- await stopLife();
417
473
  try {
418
- await stopMemory();
474
+ await stopLife();
419
475
  }
420
476
  finally {
421
- sources.invalidate();
477
+ await stopMemory().finally(() => sources.invalidate());
422
478
  }
423
- },
479
+ }),
424
480
  applyHome: () => !power.running() || !life ? '请先启动世界生活线' : homeApply.request(),
425
481
  prompts: () => ({
426
482
  persona: readPersona(personaFile),
@@ -494,8 +550,20 @@ export async function apply(ctx, config) {
494
550
  else
495
551
  rmSync(worldPromptFile, { force: true }); },
496
552
  };
497
- lifeCtx.effect(() => webServer.register(consoleRoute(sources, actions, config.allowedHosts)), 'dsh-world console routes');
553
+ lifeCtx.effect(() => webServer.register(consoleRoute(prefix, sources, actions, config.allowedHosts)), 'dsh-world console routes');
554
+ lifeCtx.effect(() => {
555
+ worlds.unregisterList ??= webServer.register(worldListRoute(worlds.consoles));
556
+ worlds.consoles.set(worldId, config.allowedHosts);
557
+ return () => {
558
+ worlds.consoles.delete(worldId);
559
+ if (!worlds.consoles.size) {
560
+ worlds.unregisterList?.();
561
+ delete worlds.unregisterList;
562
+ }
563
+ };
564
+ }, 'dsh-world world list');
498
565
  if (power.running())
499
- await startLife(false);
566
+ await changeWorld(async () => { if (!disposed && power.running())
567
+ await startLife(false); });
500
568
  });
501
569
  }
@@ -1,5 +1,5 @@
1
1
  import { errorText } from "../faults.js";
2
- import { scopedTool } from "../worldScope.js";
2
+ import { registerScopedTool } from "../worldScope.js";
3
3
  const ALARM_TOOLS = ['plan_next', 'check_alarm', 'cancel_alarm'];
4
4
  const HOME_TOOLS = ['reach_out', 'keep_photo', 'list_photos', 'forget_photo'];
5
5
  /** Disposes in reverse; a disposer whose agent scope is already gone may throw and is skipped. */
@@ -24,7 +24,7 @@ export function createToolRegistry(deps) {
24
24
  try {
25
25
  for (const tool of tools)
26
26
  if (names.includes(tool.name))
27
- done.push(agent.ctx.tools.register(scopedTool(tool, () => deps.inWorld(agent))));
27
+ done.push(registerScopedTool(agent, tool, () => deps.inWorld(agent)));
28
28
  }
29
29
  catch (error) {
30
30
  undo(done);
@@ -46,5 +46,4 @@ export declare function createAuthorFiles(sources: MemorySources, timeZone: stri
46
46
  message: string;
47
47
  }[];
48
48
  };
49
- export type AuthorFiles = ReturnType<typeof createAuthorFiles>;
50
49
  export {};
@@ -80,7 +80,6 @@ export declare function decodeRef(ref: string): {
80
80
  };
81
81
  export declare const chatRef: (recordId: string, content: string) => string;
82
82
  export declare const fileRef: (sourceId: string, content: string) => string;
83
- export declare const refHash: (content: string) => string;
84
83
  /** Explicit links only: a line `引用:memory:<ref> memory:<ref>`. */
85
84
  export declare function extractLinks(content: string): string[];
86
85
  /** The instant a local calendar day starts in the zone, with the offset it has then. */
@@ -29,7 +29,6 @@ export function decodeRef(ref) {
29
29
  const hashOf = (content) => sha(content).slice(0, 12);
30
30
  export const chatRef = (recordId, content) => encodeRef(['c', recordId, hashOf(content)]);
31
31
  export const fileRef = (sourceId, content) => encodeRef(['a', sourceId, hashOf(content)]);
32
- export const refHash = hashOf;
33
32
  /** Explicit links only: a line `引用:memory:<ref> memory:<ref>`. */
34
33
  export function extractLinks(content) {
35
34
  const found = new Set();
@@ -10,7 +10,6 @@ import type { MemoryService } from './memory.ts';
10
10
  /** What a tool call returns is resent on every later turn of the loop, so it is kept short: fewer hits, shorter excerpts, no bookkeeping fields. */
11
11
  export declare const TOOL_FIND_LIMIT = 8, TOOL_EXCERPT_CHARS = 200, TOOL_READ_LIMIT = 2000;
12
12
  export declare function memoryTools(service: MemoryService, inside: () => boolean): ToolDefinition[];
13
- export declare const MEMORY_TOOL_NAMES: readonly ["memory_find", "memory_read"];
14
13
  /**
15
14
  * Gives world sessions their tools (long-term memory), whatever the life line does: a session has them
16
15
  * while it is in her world, and loses them when it leaves. A registration that fails is a fault, never a broken agent.
@@ -1,6 +1,6 @@
1
1
  import { defineTool } from '@deepseek-ai/dsh-tools';
2
2
  import { errorText } from "./faults.js";
3
- import { OutsideWorldError, scopedTool } from "./worldScope.js";
3
+ import { OutsideWorldError, registerScopedTool } from "./worldScope.js";
4
4
  const output = { schema: { type: 'string' }, render: (_args, value) => [{ type: 'text', text: value }] };
5
5
  /**
6
6
  * The two tools over long-term memory. They run on the same service as the console; the world and scope are the
@@ -53,7 +53,6 @@ export function memoryTools(service, inside) {
53
53
  }),
54
54
  ];
55
55
  }
56
- export const MEMORY_TOOL_NAMES = ['memory_find', 'memory_read'];
57
56
  /**
58
57
  * Gives world sessions their tools (long-term memory), whatever the life line does: a session has them
59
58
  * while it is in her world, and loses them when it leaves. A registration that fails is a fault, never a broken agent.
@@ -81,7 +80,7 @@ export function createWorldToolRegistry(deps) {
81
80
  const done = [];
82
81
  try {
83
82
  for (const tool of deps.tools(() => deps.inWorld(agent)))
84
- done.push(agent.ctx.tools.register(scopedTool(tool, () => deps.inWorld(agent))));
83
+ done.push(registerScopedTool(agent, tool, () => deps.inWorld(agent)));
85
84
  registered.set(agent, done);
86
85
  deps.faults.clear(key(agent));
87
86
  return true;
package/lib/mood.d.ts ADDED
@@ -0,0 +1,28 @@
1
+ /** Her mood, kept in her room. The plugin never writes it: it only reads it back to her. */
2
+ export declare const MOOD_FILE = "mood.md";
3
+ /** Always shown, at 0 when she has not set them, so one snapshot compares with the next. */
4
+ export declare const DEFAULT_MOODS: readonly ["开心", "兴奋", "平静", "累", "困", "烦", "难过", "紧张"];
5
+ export type Mood = {
6
+ kind: 'none';
7
+ } | {
8
+ kind: 'failed';
9
+ message: string;
10
+ } | {
11
+ kind: 'mood';
12
+ values: Map<string, number>;
13
+ trivia: string[];
14
+ cut: boolean;
15
+ unread: number;
16
+ };
17
+ /**
18
+ * One thing per line. A line ending in a number after a space, a full-width space or a colon is a mood `名字 数值`,
19
+ * its value a whole number from 0 to 10; a line ending in anything else is a small thing beside her mood. A later line
20
+ * for the same mood wins. A mood line she got wrong is counted, never taken as a small thing.
21
+ */
22
+ export declare function parseMood(text: string): Mood;
23
+ /** A missing or blank file is `none`, not every mood at 0; a file that cannot be read is `failed`. */
24
+ export declare function readMood(path: string): Mood;
25
+ /** Shown once after an earlier snapshot when she has emptied or removed the file, so the old values stop counting. */
26
+ export declare const MOOD_CLEARED = "\u3010\u6211\u7684\u5FC3\u60C5\u503C\u3011\u73B0\u5728\u6CA1\u6709\u5FC3\u60C5\u503C\uFF08mood.md \u4E0D\u5728\u6216\u662F\u7A7A\u7684\uFF09\uFF0C\u4E4B\u524D\u90A3\u6761\u4E0D\u518D\u7B97\u6570\u3002";
27
+ /** What she reads just before the time block, in her own voice; undefined when there is nothing to show. */
28
+ export declare function moodText(mood: Mood): string | undefined;
package/lib/mood.js ADDED
@@ -0,0 +1,69 @@
1
+ import { readFileSync, statSync } from 'node:fs';
2
+ import { errorText } from "./faults.js";
3
+ /** Her mood, kept in her room. The plugin never writes it: it only reads it back to her. */
4
+ export const MOOD_FILE = 'mood.md';
5
+ /** Always shown, at 0 when she has not set them, so one snapshot compares with the next. */
6
+ export const DEFAULT_MOODS = ['开心', '兴奋', '平静', '累', '困', '烦', '难过', '紧张'];
7
+ const MAX_NAME = 12, MAX_TRIVIA_LINES = 3, MAX_TRIVIA_CHARS = 12;
8
+ /**
9
+ * One thing per line. A line ending in a number after a space, a full-width space or a colon is a mood `名字 数值`,
10
+ * its value a whole number from 0 to 10; a line ending in anything else is a small thing beside her mood. A later line
11
+ * for the same mood wins. A mood line she got wrong is counted, never taken as a small thing.
12
+ */
13
+ export function parseMood(text) {
14
+ const values = new Map(), trivia = [];
15
+ let cut = false, unread = 0;
16
+ for (const raw of text.replace(/^/, '').split(/\r?\n/)) {
17
+ const line = raw.trim();
18
+ if (!line)
19
+ continue;
20
+ const pair = /^(.*?)[\s ::]+([+-]?\d+(?:\.\d+)?)$/u.exec(line);
21
+ if (pair) {
22
+ const name = pair[1].trim(), value = Number(pair[2]);
23
+ if (!name || Array.from(name).length > MAX_NAME || !Number.isInteger(value) || value < 0 || value > 10)
24
+ unread++;
25
+ else
26
+ values.set(name, value);
27
+ continue;
28
+ }
29
+ if (trivia.length === MAX_TRIVIA_LINES) {
30
+ cut = true;
31
+ continue;
32
+ }
33
+ const chars = Array.from(line);
34
+ if (chars.length > MAX_TRIVIA_CHARS)
35
+ cut = true;
36
+ trivia.push(chars.slice(0, MAX_TRIVIA_CHARS).join(''));
37
+ }
38
+ return values.size || trivia.length || unread ? { kind: 'mood', values, trivia, cut, unread } : { kind: 'none' };
39
+ }
40
+ /** A missing or blank file is `none`, not every mood at 0; a file that cannot be read is `failed`. */
41
+ export function readMood(path) {
42
+ try {
43
+ if (!statSync(path).isFile())
44
+ return { kind: 'failed', message: '不是普通文件' };
45
+ return parseMood(readFileSync(path, 'utf8'));
46
+ }
47
+ catch (error) {
48
+ if (error.code === 'ENOENT')
49
+ return { kind: 'none' };
50
+ return { kind: 'failed', message: errorText(error) };
51
+ }
52
+ }
53
+ /** Shown once after an earlier snapshot when she has emptied or removed the file, so the old values stop counting. */
54
+ export const MOOD_CLEARED = '【我的心情值】现在没有心情值(mood.md 不在或是空的),之前那条不再算数。';
55
+ /** What she reads just before the time block, in her own voice; undefined when there is nothing to show. */
56
+ export function moodText(mood) {
57
+ if (mood.kind === 'none')
58
+ return undefined;
59
+ if (mood.kind === 'failed')
60
+ return '【我的心情值】mood.md 读不出来,之前那条不再算数。';
61
+ const shown = DEFAULT_MOODS.map(name => `${name} ${mood.values.get(name) ?? 0}`);
62
+ const own = [...mood.values].filter(([name]) => !DEFAULT_MOODS.includes(name)).map(([name, value]) => `${name} ${value}`);
63
+ const lines = [`【我的心情值】${shown.join(' · ')}${own.length ? `|我自己加的:${own.join(' · ')}` : ''}(以最新一条为准)`];
64
+ if (mood.trivia.length)
65
+ lines.push(`旁边:${mood.trivia.join(';')}${mood.cut ? '……后面还有' : ''}`);
66
+ if (mood.unread)
67
+ lines.push(`(mood.md 里有 ${mood.unread} 行没读懂)`);
68
+ return lines.join('\n');
69
+ }
@@ -2,13 +2,14 @@ import type { Agent } from '@deepseek-ai/dsh-agent';
2
2
  import type { Session } from '@deepseek-ai/dsh-session';
3
3
  import type { WorldConfig } from './types.ts';
4
4
  import { type WorldNames, type WorldPrompt } from './worldPrompt.ts';
5
+ export declare const WORLD_PROMPT_PREFIX = "dsh-world:";
5
6
  export interface WorldPromptSource {
6
7
  prompt: WorldPrompt;
7
8
  isHome(sessionId: string): boolean;
8
9
  archiveSession?(sessionId: string): boolean;
9
- /** Resolved with the saved prompt text, so renaming does not change an existing cached prefix. */
10
+ /** Resolved with the persona, so a rename appears in both parts of the prompt together. */
10
11
  names?(): WorldNames;
11
- /** Her room's workspace; her world (all but the persona) reaches only its sessions. Absent, every session of hers. */
12
+ /** Her room's workspace; her world and persona reach only its sessions. Absent, every session of hers. */
12
13
  inWorkspace?(sessionId: string): boolean;
13
14
  /** Long-term memory; its two tools are registered on world sessions. */
14
15
  memory?: import('./memory.ts').MemoryService;
@@ -17,9 +18,8 @@ export interface WorldPromptSource {
17
18
  * Her persona and the world prompt both reach only sessions of her preset inside the world's workspace, and come and
18
19
  * go together as a session enters or leaves it: the preset alone is DSH's default `standard` for most setups, so it
19
20
  * would turn every unrelated session into her (#37). Both are sections of the session's system prompt so she sees them on every
20
- * request. They are read when the session opens and again after each successful compaction (the host assembles
21
- * the system prompt before pre-step, so the refresh happens on compaction/end), when a cold session speaks again
22
- * (`coldHours` in `runtime.ts`, on turn/start) or on explicit console application, so the prompt stays in the provider-cached prefix. Whether the session is her home is asked per request.
21
+ * request. Checking the files during assembly also covers compression outside DSH (#42). The prompt stays in the
22
+ * provider-cached prefix while its content is the same. Whether the session is her home is asked per request.
23
23
  *
24
24
  * Her persona takes the place of DeepSeek Harness's stock identity line, but never of a persona someone has set: it is its own
25
25
  * section placed right after the host's persona slot, so a system persona the deployment or her preset already has stays
@@ -32,6 +32,8 @@ export declare function createPromptSections(config: WorldConfig, world: WorldPr
32
32
  }): {
33
33
  add(agent: Agent): void;
34
34
  active(session: Session): boolean;
35
+ /** On in-history routes, start a new series to replace the old prompt instead of appending to it. */
36
+ takeRestart(session: Session): boolean;
35
37
  refresh(session: Session): void;
36
38
  clear(): void;
37
39
  };