dsh-world 0.7.2 → 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 (68) hide show
  1. package/CHANGELOG.md +394 -379
  2. package/INSTALL.md +314 -314
  3. package/LICENSE +21 -21
  4. package/NOTES.md +21 -13
  5. package/README.md +20 -6
  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 +16 -7
  12. package/lib/console/routes.d.ts +2 -3
  13. package/lib/console/routes.js +7 -8
  14. package/lib/console/snapshot.d.ts +1 -3
  15. package/lib/console/snapshot.js +0 -3
  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/index.js +2 -0
  28. package/lib/ecosystem/qq-native/native-bridge.d.ts +0 -1
  29. package/lib/ecosystem/qq-native/native-bridge.js +0 -2
  30. package/lib/ecosystem/qq-native/snowluma.js +11 -2
  31. package/lib/ecosystem/wechat/index.d.ts +0 -1
  32. package/lib/ecosystem/wechat/index.js +6 -5
  33. package/lib/hostContract.d.ts +13 -0
  34. package/lib/index.js +106 -45
  35. package/lib/life/toolRegistry.js +2 -2
  36. package/lib/memoryFiles.d.ts +0 -1
  37. package/lib/memoryStore.d.ts +0 -1
  38. package/lib/memoryStore.js +0 -1
  39. package/lib/memoryTools.d.ts +0 -1
  40. package/lib/memoryTools.js +2 -3
  41. package/lib/promptSection.d.ts +7 -5
  42. package/lib/promptSection.js +74 -28
  43. package/lib/runtime.d.ts +6 -2
  44. package/lib/runtime.js +136 -26
  45. package/lib/sourceArchive.d.ts +4 -2
  46. package/lib/sourceArchive.js +18 -4
  47. package/lib/store.js +2 -1
  48. package/lib/types.d.ts +1 -1
  49. package/lib/worldPrompt.d.ts +2 -3
  50. package/lib/worldPrompt.js +2 -3
  51. package/lib/worldRoutes.d.ts +9 -0
  52. package/lib/worldRoutes.js +29 -0
  53. package/lib/worldScope.d.ts +5 -5
  54. package/lib/worldScope.js +16 -7
  55. package/lib/worldSwitch.d.ts +1 -2
  56. package/lib/worldSwitch.js +1 -1
  57. package/package.json +17 -16
  58. package/scripts/compact-home.mjs +29 -29
  59. package/scripts/enable-tool-free-compaction.ps1 +33 -33
  60. package/scripts/import-stickers.mjs +17 -17
  61. package/scripts/update-world.mjs +2 -2
  62. package/src/ecosystem/README.md +1 -1
  63. package/src/ecosystem/wechat/windows/README.md +2 -2
  64. package/src/ecosystem/wechat/windows/adapter.py +4 -2
  65. package/src/ecosystem/wechat/windows/engine/profiles.json +142 -142
  66. package/src/ecosystem/wechat/windows/presence.py +109 -109
  67. package/templates/alarm.md +2 -2
  68. package/templates/world-prompt.md +8 -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
@@ -23,7 +23,7 @@ import { readPersona, writePersona } from "./persona.js";
23
23
  import { qqRoute } from "./ecosystem/qq/route.js";
24
24
  import { createConsoleDoors, discoverSnowlumaHome } from "./ecosystem/qq/panel.js";
25
25
  import { createMemory } from "./memory.js";
26
- import { createWorldRuntime } from "./runtime.js";
26
+ import { createWorldRuntime, guardWorldContext } from "./runtime.js";
27
27
  import { createArchiveStore } from "./store.js";
28
28
  import { DEFAULT_TEMPLATE_FILE, MEMORY_SNIPPET_FILE, memoryTemplateGaps, roomTitle, worldNames } from "./worldPrompt.js";
29
29
  import { createWorldSwitch } from "./worldSwitch.js";
@@ -32,16 +32,17 @@ import { createWechatModule } from "./ecosystem/wechat/index.js";
32
32
  import { createWechatRecorder } from "./ecosystem/wechat/archive.js";
33
33
  import { createAdapterSupervisor } from "./ecosystem/wechat/supervisor.js";
34
34
  import { createChannelSessions } from "./ecosystem/shared/sessions.js";
35
- import { createArchiveSelection, createWorkspaceMembership } from "./archiveSelection.js";
35
+ import { canonicalPath, createArchiveSelection, createWorkspaceMembership } from "./archiveSelection.js";
36
36
  import { inWorld } from "./sourceArchive.js";
37
+ import { validWorldId, worldListRoute, worldPath } from "./worldRoutes.js";
37
38
  import { createWorkspacePermissions } from "./workspacePermissions.js";
38
39
  import { createPhotoStore } from "./life/photos.js";
39
40
  import { createQqSdkInstaller } from "./ecosystem/qq-native/sdkInstall.js";
40
41
  export { createWorldRuntime } from "./runtime.js";
41
42
  export const name = 'dsh-world';
42
43
  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).
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.
45
46
  const systemTimeZone = Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC';
46
47
  export const Config = z.object({
47
48
  worldId: z.string().default('default'), agentPreset: z.string().default('standard'), timeZone: z.string().default(systemTimeZone),
@@ -53,7 +54,7 @@ export const Config = z.object({
53
54
  selfFile: z.string(), worldPromptFile: z.string(), alarmTemplateFile: z.string(), personaFile: z.string(),
54
55
  // Where her words go outside DSH; no app is known by name (see README for the push body).
55
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([]),
56
- // 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.
57
58
  bridge: z.boolean().default(false),
58
59
  qqNative: z.object({
59
60
  enabled: z.boolean().default(false),
@@ -76,7 +77,7 @@ export const Config = z.object({
76
77
  // SnowLuma 装在哪:控制台那扇门要去它的 config/runtime.json 拿地址与端口。空着就按 D:\SnowLuma、
77
78
  // C:\SnowLuma、~/SnowLuma 挨个认(认「里面有 config/runtime.json」这一条)。
78
79
  snowlumaHome: z.string().default(''),
79
- // 看门狗:通道开着时每 30 秒探一次 wsUrl 的端口,不通就把 SnowLuma 拉起来。不想让插件动手就关掉,面板上的按钮照旧能用。
80
+ // 看门狗:每 30 秒探一次 wsUrl 的端口,不通且没有实例时才拉起。关掉后面板上的按钮照旧能用。
80
81
  supervise: z.boolean().default(true),
81
82
  // 谁和她的家会话共用一个入口。'owner'(默认)=群各自独立、私聊用她的家;'all'=都用她的家;
82
83
  // 'none'=谁都不绑,每个入口各建一个 —— 开发测试 QQ 的时候填 none,回合就不会走进步话生活的家里。
@@ -96,14 +97,43 @@ export const Config = z.object({
96
97
  // The console and the bridge answer only this machine by name, plus these (a LAN address or domain behind a proxy).
97
98
  allowedHosts: z.array(z.string()).default([]),
98
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
+ }
99
117
  /**
100
118
  * Her world runs only after her partner presses start in the world console, and stops when they press stop:
101
119
  * memory block, persona, world prompt, archive and life line come and go together. The switch is kept in
102
120
  * `<world>/world.json`, so it outlasts a restart.
103
121
  */
104
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);
105
128
  const dshHome = resolveDshHome();
106
- 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
+ }
107
137
  const store = createArchiveStore({ ...config, root: dshHome });
108
138
  const power = createWorldSwitch(worldDir, config.archiveScope ?? 'workspace', config.fallbackWakeTime);
109
139
  const memoryConfig = { ...config, archiveScope: power.archiveScope() };
@@ -125,7 +155,6 @@ export async function apply(ctx, config) {
125
155
  const selfFile = config.selfFile || join(worldDir, 'room', '我是谁.md');
126
156
  const personaFile = config.personaFile || join(worldDir, 'persona.md');
127
157
  const worldPromptFile = config.worldPromptFile || join(worldDir, 'world-prompt.md');
128
- const roomDir = join(worldDir, 'room');
129
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') };
130
159
  /** The name in her persona comes first, then the configured one. */
131
160
  const names = () => worldNames({ ...config, companionName: readPersona(personaFile).名字 || config.companionName });
@@ -145,10 +174,9 @@ export async function apply(ctx, config) {
145
174
  })();
146
175
  const storedHome = () => lifeStore?.read().homeSessionId;
147
176
  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
177
  /** Where her world reaches: her room's workspace, and in it the sessions of her preset. */
151
- 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);
152
180
  const inWorldSession = (session) => inWorld(session, config, inWorkspace);
153
181
  /** Long-term memory over the archive and her own files; the tools and the console are two doors to it. */
154
182
  const memoryService = createMemory({ store: store.memory, timeZone: config.timeZone, sources: { diaryDir: options.diaryDir }, visible: id => archiveSession(id) });
@@ -156,21 +184,25 @@ export async function apply(ctx, config) {
156
184
  const memoryHealth = () => memoryService.status().failures.map(failure => `记忆来源 ${failure.sourceId}:${failure.message}`);
157
185
  let memory;
158
186
  let stopLifeLine;
187
+ let disposed = false;
188
+ let lifecycle = Promise.resolve();
189
+ const changeWorld = (change) => lifecycle = lifecycle.then(change, change);
159
190
  /**
160
191
  * A memory line that cannot start is a fault, never a failed plugin: the console must still open to say so, and
161
192
  * the life line and channels run on. Stopping and starting the world from the console tries again.
162
193
  */
163
194
  async function startMemory(fresh) {
164
- if (memory)
195
+ if (memory || disposed)
165
196
  return;
166
197
  const prompt = { file: worldPromptFile, persona: personaFile, conversationsDir: join(worldDir, 'conversations'), names: names(), memoryTools: true, ...(config.life ? { life: options } : {}) };
167
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;
168
200
  try {
169
201
  await runtime.start({ fresh });
170
- memory = runtime;
171
202
  faults.clear('memory');
172
203
  }
173
204
  catch (error) {
205
+ memory = undefined;
174
206
  faults.set('memory', `记忆线没能启动:${errorText(error)}`);
175
207
  ctx.logger.error(error);
176
208
  }
@@ -180,26 +212,44 @@ export async function apply(ctx, config) {
180
212
  memory = undefined;
181
213
  await running?.stop();
182
214
  }
183
- ctx.effect(() => async () => {
184
- try {
185
- await stopLifeLine?.();
186
- }
187
- finally {
188
- await stopMemory().finally(() => store.close());
189
- }
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
+ };
190
235
  }, 'dsh-world memory line');
191
236
  if (power.running())
192
- await startMemory(false);
237
+ await changeWorld(() => startMemory(false));
193
238
  // 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)); });
239
+ ctx.inject(['workspaceRegistry'], injected => {
240
+ void changeWorld(async () => { if (!disposed)
241
+ await memory?.retryCatchUp(); }).catch(error => injected.logger.error(error));
242
+ });
195
243
  // The console and the life line need the desktop host.
196
244
  ctx.inject(['sessionController', 'permissionPresets', 'webServer'], async (lifeCtx) => {
197
245
  const webServer = lifeCtx.webServer;
198
246
  const host = hostLife(lifeCtx);
199
247
  const configEditor = lifeCtx.get('configEditor');
200
- 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,
201
249
  swap: async (dir) => { const row = swapStockCompaction(dir); return row.status === 'unchanged' && configEditor ? swapPresetCompaction(configEditor, config.agentPreset, dir) : row; },
202
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);
203
253
  // The preset row the editor rewrites is active only once the host has finished loading.
204
254
  const appReady = lifeCtx.get('appReady');
205
255
  if (!appReady)
@@ -212,13 +262,9 @@ export async function apply(ctx, config) {
212
262
  return () => { closed = true; cancel(); };
213
263
  }, 'dsh-world compaction swap');
214
264
  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
- // 任何配置上 —— 端点先存在,功能再按需开关。)
265
+ // SnowLuma 的控制台在 OneBot 通道关闭时仍可用。
220
266
  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));
267
+ const unregisterQq = webServer.register(qqRoute(prefix, config.allowedHosts, doors, () => qqNative?.status() ?? null, patch => qqNative?.update(patch) ?? null));
222
268
  lifeCtx.effect(() => () => unregisterQq(), 'dsh-world qq route');
223
269
  let life;
224
270
  const sdkAbort = new AbortController();
@@ -262,6 +308,8 @@ export async function apply(ctx, config) {
262
308
  if (wechat || !config.wechat)
263
309
  return;
264
310
  await wechatClosing;
311
+ if (wechat || life !== current || disposed || !power.running() || !power.wechatEnabled())
312
+ return;
265
313
  const groupSessions = createChannelSessions({ ctx: lifeCtx, host, store, roomDir: options.roomDir, roomTitle: roomTitle(names()), agentPreset: config.agentPreset });
266
314
  channels = groupSessions;
267
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() }),
@@ -352,6 +400,8 @@ export async function apply(ctx, config) {
352
400
  return;
353
401
  try {
354
402
  await lifeStop;
403
+ if (disposed)
404
+ return;
355
405
  const outlets = config.outlets.map(outlet => createOutlet(outlet, () => host.origin()));
356
406
  const notifier = { ...(config.toast && toastSupported() ? { toast: windowsToast(config.toastAppId || undefined) } : {}), outlets };
357
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())
@@ -359,7 +409,7 @@ export async function apply(ctx, config) {
359
409
  life = current;
360
410
  isHome = current.isHome;
361
411
  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 });
412
+ bridge = createBridge({ ctx: lifeCtx, prefix, home: () => current.home(), inWorld: inWorldSession, outlets, origin: () => host.origin(), file: join(worldDir, 'bridge.json'), name: names().companion });
363
413
  bridge.start();
364
414
  }
365
415
  if (config.wechat && power.wechatEnabled())
@@ -387,18 +437,18 @@ export async function apply(ctx, config) {
387
437
  return lifeStop = Promise.all([lifeStop, closingWechat, homeApply.cancel()]).then(() => { });
388
438
  }
389
439
  stopLifeLine = stopLife;
390
- lifeCtx.effect(() => () => stopLife(), 'dsh-world life line');
440
+ lifeCtx.effect(() => () => changeWorld(stopLife), 'dsh-world life line');
391
441
  // The host matches exact routes before the longest prefix, so this path never reaches the console.
392
442
  if (config.bridge)
393
- 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');
394
444
  if (config.bridge)
395
- 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');
396
446
  // Her album lives in her room, so the console shows it whether or not the life line is running.
397
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,
398
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()] });
399
449
  const actions = {
400
- async start() {
401
- if (power.running())
450
+ start: () => changeWorld(async () => {
451
+ if (disposed || power.running())
402
452
  return;
403
453
  power.set(true);
404
454
  try {
@@ -408,19 +458,18 @@ export async function apply(ctx, config) {
408
458
  finally {
409
459
  sources.invalidate();
410
460
  }
411
- },
412
- async stop() {
413
- if (!power.running())
461
+ }),
462
+ stop: () => changeWorld(async () => {
463
+ if (disposed || !power.running())
414
464
  return;
415
465
  power.set(false);
416
- await stopLife();
417
466
  try {
418
- await stopMemory();
467
+ await stopLife();
419
468
  }
420
469
  finally {
421
- sources.invalidate();
470
+ await stopMemory().finally(() => sources.invalidate());
422
471
  }
423
- },
472
+ }),
424
473
  applyHome: () => !power.running() || !life ? '请先启动世界生活线' : homeApply.request(),
425
474
  prompts: () => ({
426
475
  persona: readPersona(personaFile),
@@ -494,8 +543,20 @@ export async function apply(ctx, config) {
494
543
  else
495
544
  rmSync(worldPromptFile, { force: true }); },
496
545
  };
497
- 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');
498
558
  if (power.running())
499
- await startLife(false);
559
+ await changeWorld(async () => { if (!disposed && power.running())
560
+ await startLife(false); });
500
561
  });
501
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,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
  };
@@ -1,38 +1,64 @@
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
32
  * Her persona and the world prompt both reach only sessions of her preset inside the world's workspace, and come and
10
33
  * go together as a session enters or leaves it: the preset alone is DSH's default `standard` for most setups, so it
11
34
  * would turn every unrelated session into her (#37). Both are sections of the session's system prompt so she sees them on every
12
- * request. They are read when the session opens and again after each successful compaction (the host assembles
13
- * the system prompt before pre-step, so the refresh happens on compaction/end), when a cold session speaks again
14
- * (`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.
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.
15
37
  *
16
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
17
39
  * section placed right after the host's persona slot, so a system persona the deployment or her preset already has stays
18
40
  * where it is and hers follows it.
19
41
  */
20
42
  export function createPromptSections(config, world, deps) {
43
+ const sectionName = WORLD_PROMPT_PREFIX + config.worldId;
21
44
  const entries = new Map();
22
45
  const agents = new WeakMap();
23
- function read(includeWorld) {
24
- const persona = world.prompt.persona ? renderPersona(readPersona(world.prompt.persona)) : '';
25
- const names = world.names?.() ?? world.prompt.names;
26
- if (!includeWorld)
27
- 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, () => {
28
51
  const template = readTemplate(world.prompt.file);
29
52
  if (template.error)
30
53
  deps.logger.warn(`dsh-world: ${template.error}`);
31
- return {
32
- template: template.text,
33
- ...(config.selfFile ? { self: { file: config.selfFile, text: renderSelf(config.selfFile) } } : {}),
34
- persona, names,
35
- };
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) };
36
62
  }
37
63
  /** Registers her persona while the session is in her workspace and she has one; drops it otherwise. */
38
64
  function placePersona(agent, entry) {
@@ -46,7 +72,7 @@ export function createPromptSections(config, world, deps) {
46
72
  const prompt = agent.ctx.systemPrompt;
47
73
  const order = prompt.getSectionOrder('DEPLOYMENT_PERSONA_PREFIX') ?? 0;
48
74
  const text = () => entry.text.persona;
49
- 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 });
50
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.
51
77
  // If a preset already put its own words on that identity slot for this agent, they stay exactly as written.
52
78
  let identity;
@@ -56,44 +82,64 @@ export function createPromptSections(config, world, deps) {
56
82
  catch { /* the slot is already taken for this agent */ }
57
83
  entry.persona = () => { persona(); identity?.(); };
58
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
+ }
59
94
  return {
60
95
  add(agent) {
61
96
  if (entries.has(agent) || !belongsToWorld(agent.session, config))
62
97
  return;
63
98
  let disposeWorld;
64
- /** Places or removes the world prompt and her persona as the session enters or leaves her workspace; true when it did. */
65
- const sync = () => {
66
- 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)
67
102
  return false;
68
- 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;
69
108
  if (!entry.active) {
70
109
  disposeWorld?.();
71
110
  disposeWorld = undefined;
72
111
  placePersona(agent, entry);
73
112
  return true;
74
113
  }
75
- entry.text = read(true);
76
- 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)) });
77
116
  placePersona(agent, entry);
78
117
  return true;
79
118
  };
80
119
  const disposeSync = reassembleOnChange(agent.ctx, sync);
81
- 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?.(); } };
82
121
  entries.set(agent, entry);
83
122
  agents.set(agent.session, agent);
84
- sync();
123
+ sync(agent);
85
124
  },
86
125
  active(session) {
87
126
  const agent = agents.get(session);
88
127
  return !!(agent && entries.get(agent)?.active);
89
128
  },
90
- refresh(session) {
129
+ /** On in-history routes, start a new series to replace the old prompt instead of appending to it. */
130
+ takeRestart(session) {
91
131
  const agent = agents.get(session);
92
132
  const entry = agent && entries.get(agent);
93
- if (!agent || !entry)
94
- return;
95
- entry.text = read(entry.active);
96
- 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;
97
143
  },
98
144
  clear() {
99
145
  for (const entry of entries.values())
package/lib/runtime.d.ts CHANGED
@@ -5,6 +5,8 @@ import { type WorldPromptSource } from './promptSection.ts';
5
5
  import type { ArchiveStore } from './store.ts';
6
6
  import type { WorldConfig } from './types.ts';
7
7
  export type { WorldPromptSource } from './promptSection.ts';
8
+ /** A session can outlive its world. Authorization returns false for a stopped world and undefined outside it. */
9
+ export declare function guardWorldContext(ctx: Context, authorize: (session: Session, worldId?: string) => symbol | false | undefined): void;
8
10
  /**
9
11
  * The memory line: her conversations are archived as they happen, and every world session gets a memory
10
12
  * block of the newest turns at its start, after each successful compaction and when it speaks again after being cold,
@@ -14,10 +16,12 @@ export type { WorldPromptSource } from './promptSection.ts';
14
16
  *
15
17
  * A session silent for `coldHours` (read at each turn start, default 24) is cold (#36): its provider cache has most
16
18
  * likely expired (DeepSeek clears an unused one "usually within a few hours to a few days", best effort), so its next
17
- * turn re-reads her memory block and prompt as a newly opened session would, at the cost of at most one uncached
18
- * request. A conversation in progress does not pause that long, so its cached prefix stays whole.
19
+ * turn first summarizes the old conversation, then re-reads her memory block and prompt as a newly opened session
20
+ * would: that first request misses the cache anyway, and every later step carries the summary instead of the whole old
21
+ * conversation. A conversation in progress does not pause that long, so its cached prefix stays whole.
19
22
  */
20
23
  export declare function createWorldRuntime(ctx: Context, config: WorldConfig, store: ArchiveStore, world?: WorldPromptSource, memoryTurns?: () => number, coldHours?: () => number, now?: () => number): {
24
+ scopeToken: symbol;
21
25
  start: (options?: {
22
26
  fresh?: boolean;
23
27
  }) => Promise<void>;