dsh-world 0.7.1 → 0.7.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/INSTALL.md +314 -314
  3. package/LICENSE +21 -21
  4. package/NOTES.md +34 -15
  5. package/README.md +22 -8
  6. package/client/index.js +85 -28
  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 +16 -7
  12. package/lib/console/routes.d.ts +4 -3
  13. package/lib/console/routes.js +18 -12
  14. package/lib/console/snapshot.d.ts +3 -3
  15. package/lib/console/snapshot.js +1 -4
  16. package/lib/ecosystem/bridge/bridge.d.ts +5 -0
  17. package/lib/ecosystem/bridge/bridge.js +2 -1
  18. package/lib/ecosystem/bridge/route.d.ts +4 -6
  19. package/lib/ecosystem/bridge/route.js +34 -58
  20. package/lib/ecosystem/qq/panel.d.ts +0 -1
  21. package/lib/ecosystem/qq/route.d.ts +6 -7
  22. package/lib/ecosystem/qq/route.js +10 -10
  23. package/lib/ecosystem/qq/snowluma-start.d.ts +1 -0
  24. package/lib/ecosystem/qq/snowluma-start.js +41 -8
  25. package/lib/ecosystem/qq/supervisor.d.ts +1 -2
  26. package/lib/ecosystem/qq/supervisor.js +4 -2
  27. package/lib/ecosystem/qq-native/home.d.ts +1 -0
  28. package/lib/ecosystem/qq-native/home.js +10 -3
  29. package/lib/ecosystem/qq-native/index.js +19 -4
  30. package/lib/ecosystem/qq-native/native-bridge.d.ts +0 -1
  31. package/lib/ecosystem/qq-native/native-bridge.js +5 -4
  32. package/lib/ecosystem/qq-native/replies.d.ts +3 -2
  33. package/lib/ecosystem/qq-native/replies.js +15 -4
  34. package/lib/ecosystem/qq-native/snowluma.js +11 -2
  35. package/lib/ecosystem/shared/context.d.ts +5 -0
  36. package/lib/ecosystem/shared/context.js +5 -0
  37. package/lib/ecosystem/wechat/index.d.ts +0 -1
  38. package/lib/ecosystem/wechat/index.js +6 -5
  39. package/lib/hostContract.d.ts +17 -1
  40. package/lib/index.d.ts +1 -0
  41. package/lib/index.js +126 -47
  42. package/lib/life/toolRegistry.js +2 -2
  43. package/lib/memoryFiles.d.ts +0 -1
  44. package/lib/memoryStore.d.ts +0 -1
  45. package/lib/memoryStore.js +0 -1
  46. package/lib/memoryTools.d.ts +0 -1
  47. package/lib/memoryTools.js +2 -3
  48. package/lib/promptSection.d.ts +10 -7
  49. package/lib/promptSection.js +80 -33
  50. package/lib/runtime.d.ts +12 -3
  51. package/lib/runtime.js +150 -29
  52. package/lib/sourceArchive.d.ts +4 -2
  53. package/lib/sourceArchive.js +19 -5
  54. package/lib/store.js +2 -1
  55. package/lib/types.d.ts +1 -1
  56. package/lib/worldPrompt.d.ts +2 -3
  57. package/lib/worldPrompt.js +2 -3
  58. package/lib/worldRoutes.d.ts +9 -0
  59. package/lib/worldRoutes.js +29 -0
  60. package/lib/worldScope.d.ts +5 -5
  61. package/lib/worldScope.js +16 -7
  62. package/lib/worldSwitch.d.ts +7 -2
  63. package/lib/worldSwitch.js +11 -1
  64. package/package.json +17 -16
  65. package/scripts/compact-home.mjs +29 -29
  66. package/scripts/enable-tool-free-compaction.ps1 +33 -33
  67. package/scripts/import-stickers.mjs +17 -17
  68. package/scripts/update-world.mjs +2 -2
  69. package/src/ecosystem/README.md +1 -1
  70. package/src/ecosystem/wechat/windows/README.md +6 -4
  71. package/src/ecosystem/wechat/windows/adapter.py +4 -2
  72. package/src/ecosystem/wechat/windows/engine/NOTICE.md +6 -0
  73. package/src/ecosystem/wechat/windows/engine/profiles.json +142 -114
  74. package/src/ecosystem/wechat/windows/presence.py +109 -109
  75. package/templates/alarm.md +2 -2
  76. package/templates/world-prompt.md +8 -2
package/lib/index.js CHANGED
@@ -1,5 +1,10 @@
1
1
  import { existsSync, readFileSync, rmSync } from 'node:fs';
2
- import { join } from 'node:path';
2
+ import { dirname, join } from 'node:path';
3
+ // DSH's HMR reconciles the profile once at every start and drops, as failed imports, the profile modules whose import
4
+ // has not finished (dsh-hmr `reconcileProfile`). The QQ module is imported later and is the only way to `ws`, a CommonJS
5
+ // package: dropped halfway, Node fails it with ERR_INTERNAL_ASSERTION and QQ switched on at boot never starts. Loaded
6
+ // with the plugin, `ws` is complete before that reconciliation runs.
7
+ import 'ws';
3
8
  import z from '@deepseek-ai/schemastery';
4
9
  import { resolveDshHome } from '@deepseek-ai/dsh-home-paths';
5
10
  import { createBridge } from "./ecosystem/bridge/bridge.js";
@@ -18,7 +23,7 @@ import { readPersona, writePersona } from "./persona.js";
18
23
  import { qqRoute } from "./ecosystem/qq/route.js";
19
24
  import { createConsoleDoors, discoverSnowlumaHome } from "./ecosystem/qq/panel.js";
20
25
  import { createMemory } from "./memory.js";
21
- import { createWorldRuntime } from "./runtime.js";
26
+ import { createWorldRuntime, guardWorldContext } from "./runtime.js";
22
27
  import { createArchiveStore } from "./store.js";
23
28
  import { DEFAULT_TEMPLATE_FILE, MEMORY_SNIPPET_FILE, memoryTemplateGaps, roomTitle, worldNames } from "./worldPrompt.js";
24
29
  import { createWorldSwitch } from "./worldSwitch.js";
@@ -27,16 +32,17 @@ import { createWechatModule } from "./ecosystem/wechat/index.js";
27
32
  import { createWechatRecorder } from "./ecosystem/wechat/archive.js";
28
33
  import { createAdapterSupervisor } from "./ecosystem/wechat/supervisor.js";
29
34
  import { createChannelSessions } from "./ecosystem/shared/sessions.js";
30
- import { createArchiveSelection, createWorkspaceMembership } from "./archiveSelection.js";
35
+ import { canonicalPath, createArchiveSelection, createWorkspaceMembership } from "./archiveSelection.js";
31
36
  import { inWorld } from "./sourceArchive.js";
37
+ import { validWorldId, worldListRoute, worldPath } from "./worldRoutes.js";
32
38
  import { createWorkspacePermissions } from "./workspacePermissions.js";
33
39
  import { createPhotoStore } from "./life/photos.js";
34
40
  import { createQqSdkInstaller } from "./ecosystem/qq-native/sdkInstall.js";
35
41
  export { createWorldRuntime } from "./runtime.js";
36
42
  export const name = 'dsh-world';
37
43
  export const inject = ['agents', 'sessions', 'sessionPersistence', 'llm'];
38
- // One companion per profile is the usual case, so it works as installed: the standard preset, a world named
39
- // default and the system time zone, with the life line on (it needs the desktop host's services and stays off without them).
44
+ // The installed default uses the standard preset, a world named default and the system time zone.
45
+ // The life line is on by default and needs the desktop host's services.
40
46
  const systemTimeZone = Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC';
41
47
  export const Config = z.object({
42
48
  worldId: z.string().default('default'), agentPreset: z.string().default('standard'), timeZone: z.string().default(systemTimeZone),
@@ -48,7 +54,7 @@ export const Config = z.object({
48
54
  selfFile: z.string(), worldPromptFile: z.string(), alarmTemplateFile: z.string(), personaFile: z.string(),
49
55
  // Where her words go outside DSH; no app is known by name (see README for the push body).
50
56
  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([]),
51
- // A local app may hand her partner's words to her home through POST /dsh-world/bridge/say.
57
+ // A local app reads bridge.json to send words to this world's home.
52
58
  bridge: z.boolean().default(false),
53
59
  qqNative: z.object({
54
60
  enabled: z.boolean().default(false),
@@ -71,7 +77,7 @@ export const Config = z.object({
71
77
  // SnowLuma 装在哪:控制台那扇门要去它的 config/runtime.json 拿地址与端口。空着就按 D:\SnowLuma、
72
78
  // C:\SnowLuma、~/SnowLuma 挨个认(认「里面有 config/runtime.json」这一条)。
73
79
  snowlumaHome: z.string().default(''),
74
- // 看门狗:通道开着时每 30 秒探一次 wsUrl 的端口,不通就把 SnowLuma 拉起来。不想让插件动手就关掉,面板上的按钮照旧能用。
80
+ // 看门狗:每 30 秒探一次 wsUrl 的端口,不通且没有实例时才拉起。关掉后面板上的按钮照旧能用。
75
81
  supervise: z.boolean().default(true),
76
82
  // 谁和她的家会话共用一个入口。'owner'(默认)=群各自独立、私聊用她的家;'all'=都用她的家;
77
83
  // 'none'=谁都不绑,每个入口各建一个 —— 开发测试 QQ 的时候填 none,回合就不会走进步话生活的家里。
@@ -91,14 +97,43 @@ export const Config = z.object({
91
97
  // The console and the bridge answer only this machine by name, plus these (a LAN address or domain behind a proxy).
92
98
  allowedHosts: z.array(z.string()).default([]),
93
99
  });
100
+ function profileWorlds(root) {
101
+ const existing = root.get('dshWorldProfile');
102
+ if (existing)
103
+ return existing;
104
+ const worlds = { rooms: new Map(), consoles: new Map(), compactionSwap: Promise.resolve() };
105
+ root.provide('dshWorldProfile', worlds);
106
+ guardWorldContext(root, (session, worldId) => {
107
+ if (worldId !== undefined)
108
+ return worlds.rooms.get(worldId)?.authorize(session);
109
+ for (const room of worlds.rooms.values()) {
110
+ const token = room.authorize(session);
111
+ if (token !== undefined)
112
+ return token;
113
+ }
114
+ });
115
+ return worlds;
116
+ }
94
117
  /**
95
118
  * Her world runs only after her partner presses start in the world console, and stops when they press stop:
96
119
  * memory block, persona, world prompt, archive and life line come and go together. The switch is kept in
97
120
  * `<world>/world.json`, so it outlasts a restart.
98
121
  */
99
122
  export async function apply(ctx, config) {
123
+ const { root } = ctx;
124
+ const { worldId } = config;
125
+ if (!validWorldId(worldId))
126
+ throw new TypeError('dsh-world: invalid worldId');
127
+ const worlds = profileWorlds(root);
100
128
  const dshHome = resolveDshHome();
101
- const worldDir = join(dshHome, 'worlds', config.worldId);
129
+ const worldDir = join(dshHome, 'worlds', worldId);
130
+ const roomDir = join(worldDir, 'room');
131
+ const prefix = worldPath(worldId);
132
+ const roomPath = canonicalPath(roomDir);
133
+ const dataPath = canonicalPath(worldDir);
134
+ if ([...worlds.rooms].some(([id, room]) => id.toLowerCase() === worldId.toLowerCase() || canonicalPath(room.path) === roomPath || canonicalPath(dirname(room.path)) === dataPath)) {
135
+ throw new Error(`dsh-world: worldId ${worldId} 与已加载的世界重复`);
136
+ }
102
137
  const store = createArchiveStore({ ...config, root: dshHome });
103
138
  const power = createWorldSwitch(worldDir, config.archiveScope ?? 'workspace', config.fallbackWakeTime);
104
139
  const memoryConfig = { ...config, archiveScope: power.archiveScope() };
@@ -120,7 +155,6 @@ export async function apply(ctx, config) {
120
155
  const selfFile = config.selfFile || join(worldDir, 'room', '我是谁.md');
121
156
  const personaFile = config.personaFile || join(worldDir, 'persona.md');
122
157
  const worldPromptFile = config.worldPromptFile || join(worldDir, 'world-prompt.md');
123
- const roomDir = join(worldDir, 'room');
124
158
  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') };
125
159
  /** The name in her persona comes first, then the configured one. */
126
160
  const names = () => worldNames({ ...config, companionName: readPersona(personaFile).名字 || config.companionName });
@@ -140,10 +174,9 @@ export async function apply(ctx, config) {
140
174
  })();
141
175
  const storedHome = () => lifeStore?.read().homeSessionId;
142
176
  let isHome = id => id === storedHome();
143
- /** Whose conversations her archive keeps (the home, or her whole workspace). */
144
- const archiveSession = createArchiveSelection(ctx, power.archiveScope(), id => isHome(id), options.roomDir);
145
177
  /** Where her world reaches: her room's workspace, and in it the sessions of her preset. */
146
- const inWorkspace = createWorkspaceMembership(ctx, options.roomDir);
178
+ const inWorkspace = createWorkspaceMembership(ctx, roomDir, () => Array.from(worlds.rooms.values(), room => room.path));
179
+ const archiveSession = createArchiveSelection(power.archiveScope(), id => isHome(id), inWorkspace);
147
180
  const inWorldSession = (session) => inWorld(session, config, inWorkspace);
148
181
  /** Long-term memory over the archive and her own files; the tools and the console are two doors to it. */
149
182
  const memoryService = createMemory({ store: store.memory, timeZone: config.timeZone, sources: { diaryDir: options.diaryDir }, visible: id => archiveSession(id) });
@@ -151,38 +184,72 @@ export async function apply(ctx, config) {
151
184
  const memoryHealth = () => memoryService.status().failures.map(failure => `记忆来源 ${failure.sourceId}:${failure.message}`);
152
185
  let memory;
153
186
  let stopLifeLine;
187
+ let disposed = false;
188
+ let lifecycle = Promise.resolve();
189
+ const changeWorld = (change) => lifecycle = lifecycle.then(change, change);
190
+ /**
191
+ * A memory line that cannot start is a fault, never a failed plugin: the console must still open to say so, and
192
+ * the life line and channels run on. Stopping and starting the world from the console tries again.
193
+ */
154
194
  async function startMemory(fresh) {
155
- if (memory)
195
+ if (memory || disposed)
156
196
  return;
157
197
  const prompt = { file: worldPromptFile, persona: personaFile, conversationsDir: join(worldDir, 'conversations'), names: names(), memoryTools: true, ...(config.life ? { life: options } : {}) };
158
- memory = createWorldRuntime(ctx, { ...memoryConfig, selfFile }, store, { prompt, names, isHome: id => isHome(id), archiveSession, inWorkspace, memory: memoryService }, power.memoryTurns);
159
- await memory.start({ fresh });
198
+ const runtime = createWorldRuntime(ctx, { ...memoryConfig, selfFile }, store, { prompt, names, isHome: id => isHome(id), archiveSession, inWorkspace, memory: memoryService }, power.memoryTurns, power.coldHours);
199
+ memory = runtime;
200
+ try {
201
+ await runtime.start({ fresh });
202
+ faults.clear('memory');
203
+ }
204
+ catch (error) {
205
+ memory = undefined;
206
+ faults.set('memory', `记忆线没能启动:${errorText(error)}`);
207
+ ctx.logger.error(error);
208
+ }
160
209
  }
161
210
  async function stopMemory() {
162
211
  const running = memory;
163
212
  memory = undefined;
164
213
  await running?.stop();
165
214
  }
166
- ctx.effect(() => async () => {
167
- try {
168
- await stopLifeLine?.();
169
- }
170
- finally {
171
- await stopMemory().finally(() => store.close());
172
- }
215
+ ctx.effect(() => {
216
+ worlds.rooms.set(worldId, {
217
+ path: roomDir,
218
+ authorize: session => {
219
+ if (!inWorldSession(session))
220
+ return undefined;
221
+ return !disposed && power.running() && memory ? memory.scopeToken : false;
222
+ },
223
+ });
224
+ return () => {
225
+ disposed = true;
226
+ return changeWorld(async () => {
227
+ try {
228
+ await stopLifeLine?.();
229
+ }
230
+ finally {
231
+ await stopMemory().finally(() => store.close()).finally(() => worlds.rooms.delete(worldId));
232
+ }
233
+ });
234
+ };
173
235
  }, 'dsh-world memory line');
174
236
  if (power.running())
175
- await startMemory(false);
237
+ await changeWorld(() => startMemory(false));
176
238
  // The host's workspace service may come up after this plugin; what the first catch-up could not place is read then.
177
- ctx.inject(['workspaceRegistry'], injected => { void memory?.retryCatchUp().catch(error => injected.logger.error(error)); });
239
+ ctx.inject(['workspaceRegistry'], injected => {
240
+ void changeWorld(async () => { if (!disposed)
241
+ await memory?.retryCatchUp(); }).catch(error => injected.logger.error(error));
242
+ });
178
243
  // The console and the life line need the desktop host.
179
244
  ctx.inject(['sessionController', 'permissionPresets', 'webServer'], async (lifeCtx) => {
180
245
  const webServer = lifeCtx.webServer;
181
246
  const host = hostLife(lifeCtx);
182
247
  const configEditor = lifeCtx.get('configEditor');
183
- const swapCompaction = () => swapCompactionOnce({ enabled: config.replaceCompaction, profileDir: lifeCtx.get('profileContext')?.dir, done: power.compactionSwapped, markDone: power.markCompactionSwapped,
248
+ const swap = () => swapCompactionOnce({ enabled: config.replaceCompaction, profileDir: lifeCtx.get('profileContext')?.dir, done: power.compactionSwapped, markDone: power.markCompactionSwapped,
184
249
  swap: async (dir) => { const row = swapStockCompaction(dir); return row.status === 'unchanged' && configEditor ? swapPresetCompaction(configEditor, config.agentPreset, dir) : row; },
185
250
  report: message => { faults.set('compaction-swap', message); lifeCtx.logger.warn(`dsh-world: ${message}`); } });
251
+ // Different worlds may edit the same profile or preset on startup.
252
+ const swapCompaction = () => worlds.compactionSwap = worlds.compactionSwap.then(swap, swap);
186
253
  // The preset row the editor rewrites is active only once the host has finished loading.
187
254
  const appReady = lifeCtx.get('appReady');
188
255
  if (!appReady)
@@ -195,13 +262,9 @@ export async function apply(ctx, config) {
195
262
  return () => { closed = true; cancel(); };
196
263
  }, 'dsh-world compaction swap');
197
264
  const permissions = createWorkspacePermissions(lifeCtx, options.roomDir, power);
198
- // QQ 的两扇门:她自己那条 OneBot 通道的状态与开关,以及 SnowLuma 的控制台。**无条件注册** —— 通道
199
- // 关着的时候 /native 回 null,而 SnowLuma 那扇门跟通道没关系。(这里原来还有一半是给外面那个
200
- // qq-bridge 进程用的,连 qqBridgeDir 一起在 2026-10-27 拆掉了。当时的教训:那条路由是注册在「有桥
201
- // 目录」这个分支里的,配置一摘,整片 /dsh-world/qq/* 就全 404,界面也一起没了。所以现在它不再挂在
202
- // 任何配置上 —— 端点先存在,功能再按需开关。)
265
+ // SnowLuma 的控制台在 OneBot 通道关闭时仍可用。
203
266
  const doors = createConsoleDoors({ worldDir, snowlumaHome: config.qqNative?.snowlumaHome ?? '' });
204
- const unregisterQq = webServer.register(qqRoute(config.allowedHosts, doors, () => qqNative?.status() ?? null, patch => qqNative?.update(patch) ?? null));
267
+ const unregisterQq = webServer.register(qqRoute(prefix, config.allowedHosts, doors, () => qqNative?.status() ?? null, patch => qqNative?.update(patch) ?? null));
205
268
  lifeCtx.effect(() => () => unregisterQq(), 'dsh-world qq route');
206
269
  let life;
207
270
  const sdkAbort = new AbortController();
@@ -245,6 +308,8 @@ export async function apply(ctx, config) {
245
308
  if (wechat || !config.wechat)
246
309
  return;
247
310
  await wechatClosing;
311
+ if (wechat || life !== current || disposed || !power.running() || !power.wechatEnabled())
312
+ return;
248
313
  const groupSessions = createChannelSessions({ ctx: lifeCtx, host, store, roomDir: options.roomDir, roomTitle: roomTitle(names()), agentPreset: config.agentPreset });
249
314
  channels = groupSessions;
250
315
  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() }),
@@ -335,6 +400,8 @@ export async function apply(ctx, config) {
335
400
  return;
336
401
  try {
337
402
  await lifeStop;
403
+ if (disposed)
404
+ return;
338
405
  const outlets = config.outlets.map(outlet => createOutlet(outlet, () => host.origin()));
339
406
  const notifier = { ...(config.toast && toastSupported() ? { toast: windowsToast(config.toastAppId || undefined) } : {}), outlets };
340
407
  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())
@@ -342,7 +409,7 @@ export async function apply(ctx, config) {
342
409
  life = current;
343
410
  isHome = current.isHome;
344
411
  if (config.bridge) {
345
- bridge = createBridge({ ctx: lifeCtx, home: () => current.home(), inWorld: inWorldSession, outlets, origin: () => host.origin(), file: join(worldDir, 'bridge.json'), name: names().companion });
412
+ bridge = createBridge({ ctx: lifeCtx, prefix, home: () => current.home(), inWorld: inWorldSession, outlets, origin: () => host.origin(), file: join(worldDir, 'bridge.json'), name: names().companion });
346
413
  bridge.start();
347
414
  }
348
415
  if (config.wechat && power.wechatEnabled())
@@ -370,18 +437,18 @@ export async function apply(ctx, config) {
370
437
  return lifeStop = Promise.all([lifeStop, closingWechat, homeApply.cancel()]).then(() => { });
371
438
  }
372
439
  stopLifeLine = stopLife;
373
- lifeCtx.effect(() => () => stopLife(), 'dsh-world life line');
440
+ lifeCtx.effect(() => () => changeWorld(stopLife), 'dsh-world life line');
374
441
  // The host matches exact routes before the longest prefix, so this path never reaches the console.
375
442
  if (config.bridge)
376
- lifeCtx.effect(() => webServer.register(bridgeRoute(() => bridge, config.allowedHosts)), 'dsh-world bridge route');
443
+ lifeCtx.effect(() => webServer.register(bridgeRoute(prefix, () => bridge, config.allowedHosts)), 'dsh-world bridge route');
377
444
  if (config.bridge)
378
- lifeCtx.effect(() => webServer.register(compactRoute(() => bridge, () => !power.running() || !life ? '请先启动世界生活线' : homeApply.request(), config.allowedHosts)), 'dsh-world compact route');
445
+ lifeCtx.effect(() => webServer.register(compactRoute(prefix, () => bridge, () => !power.running() || !life ? '请先启动世界生活线' : homeApply.request(), config.allowedHosts)), 'dsh-world compact route');
379
446
  // Her album lives in her room, so the console shows it whether or not the life line is running.
380
- 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, selectedArchiveScope: power.selectedArchiveScope, workspacePermissions: permissions.snapshot, wechat: () => wechat ? { ...wechat.status(), adapter: adapter?.status() ?? null } : undefined, archiveSession, native: () => qqNative?.status() ?? null,
447
+ 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,
381
448
  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()] });
382
449
  const actions = {
383
- async start() {
384
- if (power.running())
450
+ start: () => changeWorld(async () => {
451
+ if (disposed || power.running())
385
452
  return;
386
453
  power.set(true);
387
454
  try {
@@ -391,19 +458,18 @@ export async function apply(ctx, config) {
391
458
  finally {
392
459
  sources.invalidate();
393
460
  }
394
- },
395
- async stop() {
396
- if (!power.running())
461
+ }),
462
+ stop: () => changeWorld(async () => {
463
+ if (disposed || !power.running())
397
464
  return;
398
465
  power.set(false);
399
- await stopLife();
400
466
  try {
401
- await stopMemory();
467
+ await stopLife();
402
468
  }
403
469
  finally {
404
- sources.invalidate();
470
+ await stopMemory().finally(() => sources.invalidate());
405
471
  }
406
- },
472
+ }),
407
473
  applyHome: () => !power.running() || !life ? '请先启动世界生活线' : homeApply.request(),
408
474
  prompts: () => ({
409
475
  persona: readPersona(personaFile),
@@ -412,6 +478,7 @@ export async function apply(ctx, config) {
412
478
  savePersona: persona => { writePersona(personaFile, { ...readPersona(personaFile), ...persona }); sources.invalidate(); },
413
479
  setDailyBudget: yuan => { power.setDailyBudget(yuan); sources.invalidate(); },
414
480
  setMemoryTurns: turns => { power.setMemoryTurns(turns); sources.invalidate(); },
481
+ setColdHours: hours => { power.setColdHours(hours); sources.invalidate(); },
415
482
  setWorkspacePermission: permission => { permissions.set(permission); sources.invalidate(); },
416
483
  setCompactAfterReview: on => { power.setCompactAfterReview(on); sources.invalidate(); },
417
484
  setSchedule: next => { power.setSchedule(next); life?.reschedule(); sources.invalidate(); },
@@ -476,8 +543,20 @@ export async function apply(ctx, config) {
476
543
  else
477
544
  rmSync(worldPromptFile, { force: true }); },
478
545
  };
479
- lifeCtx.effect(() => webServer.register(consoleRoute(sources, actions, config.allowedHosts)), 'dsh-world console routes');
546
+ lifeCtx.effect(() => webServer.register(consoleRoute(prefix, sources, actions, config.allowedHosts)), 'dsh-world console routes');
547
+ lifeCtx.effect(() => {
548
+ worlds.unregisterList ??= webServer.register(worldListRoute(worlds.consoles));
549
+ worlds.consoles.set(worldId, config.allowedHosts);
550
+ return () => {
551
+ worlds.consoles.delete(worldId);
552
+ if (!worlds.consoles.size) {
553
+ worlds.unregisterList?.();
554
+ delete worlds.unregisterList;
555
+ }
556
+ };
557
+ }, 'dsh-world world list');
480
558
  if (power.running())
481
- await startLife(false);
559
+ await changeWorld(async () => { if (!disposed && power.running())
560
+ await startLife(false); });
482
561
  });
483
562
  }
@@ -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;
@@ -2,23 +2,24 @@ 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;
15
16
  }
16
17
  /**
17
- * Her persona follows the configured preset; the world prompt is limited to the world's workspace.
18
- * Both are sections of the session's system prompt so she sees them on every
19
- * request. They are read when the session opens and again after each successful compaction (the host assembles
20
- * the system prompt before pre-step, so the refresh happens on compaction/end) or explicit console application, so the prompt
21
- * stays in the provider-cached prefix. Whether the session is her home is asked per request.
18
+ * Her persona and the world prompt both reach only sessions of her preset inside the world's workspace, and come and
19
+ * go together as a session enters or leaves it: the preset alone is DSH's default `standard` for most setups, so it
20
+ * would turn every unrelated session into her (#37). Both are sections of the session's system prompt so she sees them on every
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.
22
23
  *
23
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
24
25
  * section placed right after the host's persona slot, so a system persona the deployment or her preset already has stays
@@ -31,6 +32,8 @@ export declare function createPromptSections(config: WorldConfig, world: WorldPr
31
32
  }): {
32
33
  add(agent: Agent): void;
33
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;
34
37
  refresh(session: Session): void;
35
38
  clear(): void;
36
39
  };
@@ -1,41 +1,68 @@
1
+ import { statSync } from 'node:fs';
2
+ import { isDeepStrictEqual } from 'node:util';
1
3
  import { readPersona, renderPersona } from "./persona.js";
2
4
  import { renderSelf } from "./self.js";
3
5
  import { belongsToWorld, inWorld } from "./sourceArchive.js";
4
- import { readTemplate, renderWorldPrompt } from "./worldPrompt.js";
6
+ import { DEFAULT_TEMPLATE_FILE, readTemplate, renderWorldPrompt } from "./worldPrompt.js";
5
7
  import { reassembleOnChange } from "./worldScope.js";
8
+ export const WORLD_PROMPT_PREFIX = 'dsh-world:';
6
9
  /** The stock "You are an AI agent powered by DeepSeek Harness." line; a section of the same name on her agent shadows it. */
7
10
  const HARNESS_IDENTITY = 'harness:identity';
11
+ function cachePromptFile(file, read) {
12
+ let cached;
13
+ return force => {
14
+ let version = '';
15
+ try {
16
+ const stat = file ? statSync(file, { throwIfNoEntry: false }) : undefined;
17
+ if (stat)
18
+ version = `${stat.ino}:${stat.size}:${stat.mtimeMs}:${stat.ctimeMs}`;
19
+ }
20
+ catch {
21
+ cached = undefined;
22
+ return read();
23
+ }
24
+ if (!force && cached?.version === version)
25
+ return cached.value;
26
+ const value = read();
27
+ cached = { version, value };
28
+ return value;
29
+ };
30
+ }
8
31
  /**
9
- * Her persona follows the configured preset; the world prompt is limited to the world's workspace.
10
- * Both are sections of the session's system prompt so she sees them on every
11
- * request. They are read when the session opens and again after each successful compaction (the host assembles
12
- * the system prompt before pre-step, so the refresh happens on compaction/end) or explicit console application, so the prompt
13
- * stays in the provider-cached prefix. Whether the session is her home is asked per request.
32
+ * Her persona and the world prompt both reach only sessions of her preset inside the world's workspace, and come and
33
+ * go together as a session enters or leaves it: the preset alone is DSH's default `standard` for most setups, so it
34
+ * would turn every unrelated session into her (#37). Both are sections of the session's system prompt so she sees them on every
35
+ * request. Checking the files during assembly also covers compression outside DSH (#42). The prompt stays in the
36
+ * provider-cached prefix while its content is the same. Whether the session is her home is asked per request.
14
37
  *
15
38
  * Her persona takes the place of DeepSeek Harness's stock identity line, but never of a persona someone has set: it is its own
16
39
  * section placed right after the host's persona slot, so a system persona the deployment or her preset already has stays
17
40
  * where it is and hers follows it.
18
41
  */
19
42
  export function createPromptSections(config, world, deps) {
43
+ const sectionName = WORLD_PROMPT_PREFIX + config.worldId;
20
44
  const entries = new Map();
21
45
  const agents = new WeakMap();
22
- function read(includeWorld) {
23
- const persona = world.prompt.persona ? renderPersona(readPersona(world.prompt.persona)) : '';
24
- const names = world.names?.() ?? world.prompt.names;
25
- if (!includeWorld)
26
- return { template: '', persona, names };
46
+ const persona = cachePromptFile(world.prompt.persona, () => ({
47
+ persona: world.prompt.persona ? renderPersona(readPersona(world.prompt.persona)) : '',
48
+ names: world.names?.() ?? world.prompt.names,
49
+ }));
50
+ const template = cachePromptFile(world.prompt.file ?? DEFAULT_TEMPLATE_FILE, () => {
27
51
  const template = readTemplate(world.prompt.file);
28
52
  if (template.error)
29
53
  deps.logger.warn(`dsh-world: ${template.error}`);
30
- return {
31
- template: template.text,
32
- ...(config.selfFile ? { self: { file: config.selfFile, text: renderSelf(config.selfFile) } } : {}),
33
- persona, names,
34
- };
54
+ return template.text;
55
+ });
56
+ const self = cachePromptFile(config.selfFile, () => config.selfFile ? { file: config.selfFile, text: renderSelf(config.selfFile) } : undefined);
57
+ let forceRead = false;
58
+ function read() {
59
+ const force = forceRead;
60
+ forceRead = false;
61
+ return { template: template(force), self: self(force), ...persona(force) };
35
62
  }
36
- /** Registers her persona when she has one and drops it when she has none. */
63
+ /** Registers her persona while the session is in her workspace and she has one; drops it otherwise. */
37
64
  function placePersona(agent, entry) {
38
- if (!entry.text.persona) {
65
+ if (!entry.active || !entry.text.persona) {
39
66
  entry.persona?.();
40
67
  delete entry.persona;
41
68
  return;
@@ -45,7 +72,7 @@ export function createPromptSections(config, world, deps) {
45
72
  const prompt = agent.ctx.systemPrompt;
46
73
  const order = prompt.getSectionOrder('DEPLOYMENT_PERSONA_PREFIX') ?? 0;
47
74
  const text = () => entry.text.persona;
48
- const persona = prompt.section({ name: 'dsh-world-persona', order: order + 1, interpolate: false, text });
75
+ const persona = prompt.section({ name: sectionName + ':persona', order: order + 1, interpolate: false, text });
49
76
  // DeepSeek Harness's own identity line gives way to hers; a persona someone set in DSH sits in its own slot and is left alone.
50
77
  // If a preset already put its own words on that identity slot for this agent, they stay exactly as written.
51
78
  let identity;
@@ -55,44 +82,64 @@ export function createPromptSections(config, world, deps) {
55
82
  catch { /* the slot is already taken for this agent */ }
56
83
  entry.persona = () => { persona(); identity?.(); };
57
84
  }
85
+ function refresh(agent, entry) {
86
+ const text = read();
87
+ if (isDeepStrictEqual(text, entry.text))
88
+ return false;
89
+ entry.text = text;
90
+ entry.restart = true;
91
+ placePersona(agent, entry);
92
+ return true;
93
+ }
58
94
  return {
59
95
  add(agent) {
60
96
  if (entries.has(agent) || !belongsToWorld(agent.session, config))
61
97
  return;
62
98
  let disposeWorld;
63
- /** Places or removes the world prompt as the session enters or leaves her workspace; true when it did. */
64
- const sync = () => {
65
- if (inWorld(agent.session, config, world.inWorkspace) === entry.active)
99
+ /** Reassemble if the placement or the content changed since the host collected the sections. */
100
+ const sync = (current) => {
101
+ if (current !== agent)
66
102
  return false;
67
- entry.active = !entry.active;
103
+ const active = inWorld(agent.session, config, world.inWorkspace);
104
+ if (active === entry.active)
105
+ return active && refresh(agent, entry);
106
+ entry.active = active;
107
+ entry.restart = true;
68
108
  if (!entry.active) {
69
109
  disposeWorld?.();
70
110
  disposeWorld = undefined;
111
+ placePersona(agent, entry);
71
112
  return true;
72
113
  }
73
- entry.text = read(true);
74
- disposeWorld = agent.ctx.systemPrompt.section({ name: 'dsh-world', order: 50, interpolate: false, text: () => renderWorldPrompt({ ...world.prompt, names: entry.text.names }, entry.text.template, entry.text.self, world.isHome(agent.id)) });
114
+ entry.text = read();
115
+ disposeWorld = agent.ctx.systemPrompt.section({ name: sectionName, order: 50, interpolate: false, text: () => renderWorldPrompt({ ...world.prompt, names: entry.text.names }, entry.text.template, entry.text.self, world.isHome(agent.id)) });
75
116
  placePersona(agent, entry);
76
117
  return true;
77
118
  };
78
119
  const disposeSync = reassembleOnChange(agent.ctx, sync);
79
- const entry = { text: read(false), active: false, dispose: () => { disposeSync(); disposeWorld?.(); } };
120
+ const entry = { text: { template: '', persona: '', names: world.prompt.names }, active: false, restart: false, dispose: () => { disposeSync(); disposeWorld?.(); } };
80
121
  entries.set(agent, entry);
81
122
  agents.set(agent.session, agent);
82
- sync();
83
- placePersona(agent, entry);
123
+ sync(agent);
84
124
  },
85
125
  active(session) {
86
126
  const agent = agents.get(session);
87
127
  return !!(agent && entries.get(agent)?.active);
88
128
  },
89
- refresh(session) {
129
+ /** On in-history routes, start a new series to replace the old prompt instead of appending to it. */
130
+ takeRestart(session) {
90
131
  const agent = agents.get(session);
91
132
  const entry = agent && entries.get(agent);
92
- if (!agent || !entry)
93
- return;
94
- entry.text = read(entry.active);
95
- placePersona(agent, entry);
133
+ if (!entry?.restart)
134
+ return false;
135
+ entry.restart = false;
136
+ return true;
137
+ },
138
+ refresh(session) {
139
+ const agent = agents.get(session);
140
+ // A compaction can finish after the current step assembled its prompt.
141
+ if (agent && entries.get(agent)?.active)
142
+ forceRead = true;
96
143
  },
97
144
  clear() {
98
145
  for (const entry of entries.values())