dsh-world 0.7.4 → 0.7.6

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 +76 -0
  2. package/CONTRIBUTING.md +11 -0
  3. package/NOTES.md +73 -16
  4. package/README.md +14 -7
  5. package/client/index.js +43 -3
  6. package/lib/abortable.d.ts +1 -0
  7. package/lib/abortable.js +17 -0
  8. package/lib/compaction.d.ts +6 -1
  9. package/lib/compaction.js +8 -3
  10. package/lib/compactionSwap.d.ts +9 -17
  11. package/lib/compactionSwap.js +27 -35
  12. package/lib/console/homeApply.js +1 -12
  13. package/lib/console/routes.d.ts +1 -0
  14. package/lib/console/routes.js +10 -0
  15. package/lib/console/snapshot.d.ts +4 -0
  16. package/lib/console/snapshot.js +3 -0
  17. package/lib/ecosystem/bridge/bridge.d.ts +2 -2
  18. package/lib/ecosystem/bridge/bridge.js +24 -11
  19. package/lib/ecosystem/qq-native/home.d.ts +2 -1
  20. package/lib/ecosystem/qq-native/home.js +6 -2
  21. package/lib/ecosystem/qq-native/images.d.ts +13 -0
  22. package/lib/ecosystem/qq-native/images.js +76 -0
  23. package/lib/ecosystem/qq-native/index.d.ts +1 -0
  24. package/lib/ecosystem/qq-native/index.js +8 -2
  25. package/lib/ecosystem/qq-native/snowluma.d.ts +1 -0
  26. package/lib/ecosystem/qq-native/snowluma.js +13 -4
  27. package/lib/ecosystem/wechat/index.d.ts +5 -0
  28. package/lib/ecosystem/wechat/index.js +3 -1
  29. package/lib/ecosystem/wechat/presence.d.ts +5 -1
  30. package/lib/ecosystem/wechat/presence.js +22 -13
  31. package/lib/ecosystem/wechat/supervisor.d.ts +1 -1
  32. package/lib/ecosystem/wechat/supervisor.js +5 -1
  33. package/lib/elsewhere.d.ts +34 -0
  34. package/lib/elsewhere.js +40 -0
  35. package/lib/history.d.ts +5 -0
  36. package/lib/history.js +5 -0
  37. package/lib/hostContract.d.ts +6 -0
  38. package/lib/index.d.ts +1 -1
  39. package/lib/index.js +84 -46
  40. package/lib/life/home.js +8 -2
  41. package/lib/life/photoTools.js +60 -26
  42. package/lib/life/runtime.js +2 -0
  43. package/lib/memoryTools.d.ts +4 -3
  44. package/lib/memoryTools.js +11 -4
  45. package/lib/mood.d.ts +38 -5
  46. package/lib/mood.js +56 -13
  47. package/lib/moodTools.d.ts +6 -0
  48. package/lib/moodTools.js +30 -0
  49. package/lib/persona.js +7 -0
  50. package/lib/promptSection.d.ts +11 -13
  51. package/lib/promptSection.js +63 -80
  52. package/lib/runtime.d.ts +21 -2
  53. package/lib/runtime.js +162 -53
  54. package/lib/sessionNews.d.ts +17 -0
  55. package/lib/sessionNews.js +55 -0
  56. package/lib/sourceArchive.d.ts +1 -5
  57. package/lib/sourceArchive.js +31 -14
  58. package/lib/store.d.ts +6 -0
  59. package/lib/store.js +17 -3
  60. package/lib/worldScope.d.ts +2 -4
  61. package/lib/worldScope.js +6 -6
  62. package/package.json +1 -1
  63. package/src/ecosystem/wechat/windows/README.md +4 -2
  64. package/src/ecosystem/wechat/windows/adapter.py +6 -1
  65. package/src/ecosystem/wechat/windows/engine/NOTICE.md +6 -0
  66. package/src/ecosystem/wechat/windows/engine/profiles.json +28 -0
  67. package/src/ecosystem/wechat/windows/sender.py +6 -2
  68. package/templates/world-prompt.md +1 -1
@@ -0,0 +1,34 @@
1
+ import type { Session } from '@deepseek-ai/dsh-session';
2
+ /** One place she is not, as facts only (how many she has not seen, who spoke last, how long ago), never the words. */
3
+ export interface ElsewhereNews {
4
+ /** Stable for the place, e.g. `wechat:family@chatroom`. */
5
+ key: string;
6
+ /** Changes whenever there is something new there; the same mark is not told twice. */
7
+ mark: string;
8
+ text: string;
9
+ }
10
+ /** Where news comes from: a WeChat account's groups, her other sessions, later other platforms. */
11
+ export interface ElsewhereSource {
12
+ /** How she looks for herself, e.g. `微信群用 wechat_history 看`. */
13
+ look: string;
14
+ /** What is pending for this session now; a place with nothing she has not seen is left out. */
15
+ news(now: Date, session: Session): ElsewhereNews[];
16
+ }
17
+ export declare function ago(milliseconds: number): string;
18
+ export declare const ELSEWHERE_HEADER = "\u3010\u522B\u5904\u7684\u52A8\u9759\u3011\u6211\u4E0D\u5728\u573A\u7684\u5730\u65B9\u6512\u4E0B\u7684\u6D88\u606F\uFF0C\u53EA\u662F\u8BA9\u6211\u77E5\u9053\uFF0C\u4E0D\u662F\u5BF9\u6211\u8BF4\u7684\u8BDD\uFF1B\u8981\u4E0D\u8981\u770B\u3001\u8981\u4E0D\u8981\u56DE\uFF0C\u6211\u81EA\u5DF1\u51B3\u5B9A\u3002";
19
+ export declare function renderElsewhere(groups: readonly {
20
+ look: string;
21
+ news: readonly ElsewhereNews[];
22
+ }[]): string;
23
+ /**
24
+ * The one way news from elsewhere reaches her: sources register here, and each session is told what is new since it
25
+ * was last told. An event is told once; whatever she has not looked at comes back with the next news from that place.
26
+ */
27
+ export declare function createElsewhere(): {
28
+ register(source: ElsewhereSource): () => void;
29
+ /** The block of what is new for this session, marking it told; undefined when nothing is. */
30
+ take(session: Session, now: Date): string | undefined;
31
+ /** What she was told is gone from her view (compaction, leaving her world): tell again what is still pending. */
32
+ retell(session: Session): void;
33
+ };
34
+ export type Elsewhere = ReturnType<typeof createElsewhere>;
@@ -0,0 +1,40 @@
1
+ export function ago(milliseconds) {
2
+ const minutes = Math.max(0, Math.floor(milliseconds / 60_000));
3
+ return minutes < 1 ? '刚刚' : minutes < 60 ? `${minutes} 分钟前` : minutes < 1440 ? `${Math.floor(minutes / 60)} 小时前` : `${Math.floor(minutes / 1440)} 天前`;
4
+ }
5
+ export const ELSEWHERE_HEADER = '【别处的动静】我不在场的地方攒下的消息,只是让我知道,不是对我说的话;要不要看、要不要回,我自己决定。';
6
+ export function renderElsewhere(groups) {
7
+ return [ELSEWHERE_HEADER, ...groups.flatMap(group => group.news.map(news => `- ${news.text}`)), `(${groups.map(group => group.look).join(';')})`].join('\n');
8
+ }
9
+ /**
10
+ * The one way news from elsewhere reaches her: sources register here, and each session is told what is new since it
11
+ * was last told. An event is told once; whatever she has not looked at comes back with the next news from that place.
12
+ */
13
+ export function createElsewhere() {
14
+ const sources = new Set();
15
+ const told = new WeakMap();
16
+ return {
17
+ register(source) {
18
+ sources.add(source);
19
+ return () => { sources.delete(source); };
20
+ },
21
+ /** The block of what is new for this session, marking it told; undefined when nothing is. */
22
+ take(session, now) {
23
+ const previous = told.get(session) ?? new Map();
24
+ const marks = new Map(), groups = [];
25
+ for (const source of sources) {
26
+ const pending = source.news(now, session);
27
+ for (const news of pending)
28
+ marks.set(news.key, news.mark);
29
+ const fresh = pending.filter(news => previous.get(news.key) !== news.mark);
30
+ if (fresh.length)
31
+ groups.push({ look: source.look, news: fresh });
32
+ }
33
+ // A place she has since caught up with is forgotten, so its next message is news again.
34
+ told.set(session, marks);
35
+ return groups.length ? renderElsewhere(groups) : undefined;
36
+ },
37
+ /** What she was told is gone from her view (compaction, leaving her world): tell again what is still pending. */
38
+ retell(session) { told.delete(session); },
39
+ };
40
+ }
package/lib/history.d.ts CHANGED
@@ -15,4 +15,9 @@ export declare function shortenLocalImages(content: string): string;
15
15
  * name, so the memory reads as hers rather than a generic assistant's. `homeOnly` (archiveScope home) says the
16
16
  * memory is her time at home.
17
17
  */
18
+ /**
19
+ * Said wherever a group session meets what was said elsewhere (her recent chats, news from elsewhere): those words
20
+ * are between her and one person, and a group is the wrong place to repeat them.
21
+ */
22
+ export declare const GROUP_PRIVACY = "\u6211\u73B0\u5728\u5728\u7FA4\u91CC\u3002\u5BB6\u91CC\u548C\u79C1\u804A\u91CC\u7684\u8BDD\u662F\u6211\u548C\u5BF9\u65B9\u4E4B\u95F4\u7684\uFF1A\u4E0D\u628A\u539F\u8BDD\u548C\u7EC6\u8282\u5E26\u8FDB\u7FA4\u91CC\u8BF4\uFF0C\u4E5F\u4E0D\u66FF\u8C01\u8F6C\u8FF0\uFF1B\u7FA4\u91CC\u6709\u4EBA\u95EE\u8D77\uFF0C\u5C31\u5E26\u8FC7\u53BB\uFF0C\u4E0D\u4E71\u8BF4\u3002";
18
23
  export declare function renderHistory(turns: readonly ConversationTurn[], timeZone: string, names: WorldNames, homeOnly?: boolean): string;
package/lib/history.js CHANGED
@@ -98,6 +98,11 @@ function sentState({ status, confirmed, total }) {
98
98
  * name, so the memory reads as hers rather than a generic assistant's. `homeOnly` (archiveScope home) says the
99
99
  * memory is her time at home.
100
100
  */
101
+ /**
102
+ * Said wherever a group session meets what was said elsewhere (her recent chats, news from elsewhere): those words
103
+ * are between her and one person, and a group is the wrong place to repeat them.
104
+ */
105
+ export const GROUP_PRIVACY = '我现在在群里。家里和私聊里的话是我和对方之间的:不把原话和细节带进群里说,也不替谁转述;群里有人问起,就带过去,不乱说。';
101
106
  export function renderHistory(turns, timeZone, names, homeOnly = false) {
102
107
  const selfName = names.companion;
103
108
  if (!turns.length)
@@ -29,6 +29,12 @@ declare module '@deepseek-ai/dsh-llm' {
29
29
  form: 'snapshot';
30
30
  worldId: string;
31
31
  };
32
+ /** 别处的动静:她不在场的地方攒下多少条、最后是谁,只是事实,不是谁说的话,不进归档。 */
33
+ 'dsh-world-elsewhere': {
34
+ kind: 'dsh-world-elsewhere';
35
+ form: 'notice';
36
+ worldId: string;
37
+ };
32
38
  'dsh-world-channel-context': {
33
39
  kind: 'dsh-world-channel-context';
34
40
  form: 'recall';
package/lib/index.d.ts CHANGED
@@ -204,4 +204,4 @@ export declare const Config: z<Schemastery.ObjectS<NoInfer<{
204
204
  * memory block, persona, world prompt, archive and life line come and go together. The switch is kept in
205
205
  * `<world>/world.json`, so it outlasts a restart.
206
206
  */
207
- export declare function apply(ctx: Context, config: Config): Promise<void>;
207
+ export declare function apply(ctx: Context, config: Config): void;
package/lib/index.js CHANGED
@@ -13,7 +13,7 @@ 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 { repairCopiedPresets, swapCompactionOnce, swapPresetCompaction, swapStockCompaction } from "./compactionSwap.js";
16
+ import { compactionPresetOverride, hasAgentPresets, repairCopiedPresets, restoreCompactionPreset, swapCompactionOnce } 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";
@@ -21,6 +21,7 @@ import { createLifeRuntime } from "./life/runtime.js";
21
21
  import { createOutlet } from "./ecosystem/shared/outlets.js";
22
22
  import { readPersona, writePersona } from "./persona.js";
23
23
  import { MOOD_FILE } from "./mood.js";
24
+ import { createElsewhere } from "./elsewhere.js";
24
25
  import { qqRoute } from "./ecosystem/qq/route.js";
25
26
  import { createConsoleDoors, discoverSnowlumaHome } from "./ecosystem/qq/panel.js";
26
27
  import { createMemory } from "./memory.js";
@@ -49,7 +50,7 @@ export const Config = z.object({
49
50
  worldId: z.string().default('default'), agentPreset: z.string().default('standard'), timeZone: z.string().default(systemTimeZone),
50
51
  companionName: z.string(), partnerName: z.string(),
51
52
  archiveScope: z.union([z.const('home').description('仅家会话'), z.const('workspace').description('家所在工作区'), z.transform(z.const('world').hidden(), () => 'workspace').hidden()]).default('workspace').description('记忆归档范围,修改后重启生效'),
52
- // Install means the tool-free compaction: the first start rewrites the profile's stock compaction row (see README); false leaves it alone.
53
+ // Only a profile-level stock row can be switched automatically. Session presets own their compaction.
53
54
  replaceCompaction: z.boolean().default(true),
54
55
  life: z.boolean().default(true), diaryDir: z.string(), fallbackWakeTime: z.string().pattern(CLOCK_TIME).default('09:00'),
55
56
  selfFile: z.string(), worldPromptFile: z.string(), alarmTemplateFile: z.string(), personaFile: z.string(),
@@ -112,6 +113,11 @@ function profileWorlds(root) {
112
113
  if (token !== undefined)
113
114
  return token;
114
115
  }
116
+ }, session => {
117
+ if (!session.header.cwd)
118
+ return false;
119
+ const cwd = canonicalPath(session.header.cwd);
120
+ return [...worlds.rooms.values()].some(room => canonicalPath(room.path) === cwd);
115
121
  });
116
122
  return worlds;
117
123
  }
@@ -120,7 +126,7 @@ function profileWorlds(root) {
120
126
  * memory block, persona, world prompt, archive and life line come and go together. The switch is kept in
121
127
  * `<world>/world.json`, so it outlasts a restart.
122
128
  */
123
- export async function apply(ctx, config) {
129
+ export function apply(ctx, config) {
124
130
  const { root } = ctx;
125
131
  const { worldId } = config;
126
132
  if (!validWorldId(worldId))
@@ -154,6 +160,9 @@ export async function apply(ctx, config) {
154
160
  ctx.effect(() => () => photoStore?.close(), 'dsh-world album');
155
161
  // Her self-description lives in her room whether or not the life line runs; she writes it with her file tools.
156
162
  const selfFile = config.selfFile || join(worldDir, 'room', '我是谁.md');
163
+ const moodFile = join(roomDir, MOOD_FILE);
164
+ /** Every source of news from where she is not registers here; the world runtime tells her sessions. */
165
+ const elsewhere = createElsewhere();
157
166
  const personaFile = config.personaFile || join(worldDir, 'persona.md');
158
167
  const worldPromptFile = config.worldPromptFile || join(worldDir, 'world-prompt.md');
159
168
  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') };
@@ -195,11 +204,10 @@ export async function apply(ctx, config) {
195
204
  async function startMemory(fresh) {
196
205
  if (memory || disposed)
197
206
  return;
198
- const prompt = { file: worldPromptFile, persona: personaFile, conversationsDir: join(worldDir, 'conversations'), names: names(), memoryTools: true, ...(config.life ? { life: options } : {}) };
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;
201
207
  try {
202
- await runtime.start({ fresh });
208
+ const prompt = { file: worldPromptFile, persona: personaFile, conversationsDir: join(worldDir, 'conversations'), names: names(), memoryTools: true, ...(config.life ? { life: options } : {}) };
209
+ memory = createWorldRuntime(ctx, { ...memoryConfig, selfFile, moodFile }, store, { prompt, names, isHome: id => isHome(id), archiveSession, inWorkspace, memory: memoryService, elsewhere }, power.memoryTurns, power.coldHours);
210
+ await memory.start({ fresh });
203
211
  faults.clear('memory');
204
212
  }
205
213
  catch (error) {
@@ -224,6 +232,7 @@ export async function apply(ctx, config) {
224
232
  });
225
233
  return () => {
226
234
  disposed = true;
235
+ memory?.cancelCatchUp();
227
236
  return changeWorld(async () => {
228
237
  try {
229
238
  await stopLifeLine?.();
@@ -234,21 +243,21 @@ export async function apply(ctx, config) {
234
243
  });
235
244
  };
236
245
  }, 'dsh-world memory line');
246
+ // Archive replay may outlast a host reload. Register all effects in this apply call.
237
247
  if (power.running())
238
- await changeWorld(() => startMemory(false));
248
+ lifecycle = startMemory(false);
239
249
  // The host's workspace service may come up after this plugin; what the first catch-up could not place is read then.
240
250
  ctx.inject(['workspaceRegistry'], injected => {
241
251
  void changeWorld(async () => { if (!disposed)
242
252
  await memory?.retryCatchUp(); }).catch(error => injected.logger.error(error));
243
253
  });
244
254
  // The console and the life line need the desktop host.
245
- ctx.inject(['sessionController', 'permissionPresets', 'webServer'], async (lifeCtx) => {
255
+ ctx.inject(['sessionController', 'permissionPresets', 'webServer'], lifeCtx => {
246
256
  const webServer = lifeCtx.webServer;
247
257
  const host = hostLife(lifeCtx);
248
258
  const configEditor = lifeCtx.get('configEditor');
249
259
  const profileDir = () => lifeCtx.get('profileContext')?.dir;
250
- const swap = () => swapCompactionOnce({ enabled: config.replaceCompaction, profileDir: profileDir(), done: power.compactionSwapped, markDone: power.markCompactionSwapped,
251
- swap: async (dir) => { const row = swapStockCompaction(dir); return row.status === 'unchanged' && configEditor ? swapPresetCompaction(configEditor, config.agentPreset, dir) : row; },
260
+ const swap = () => swapCompactionOnce({ enabled: config.replaceCompaction && !lifeCtx.get('agentPresets') && !hasAgentPresets(configEditor), profileDir: profileDir(), done: power.compactionSwapped, markDone: power.markCompactionSwapped,
252
261
  report: message => { faults.set('compaction-swap', message); lifeCtx.logger.warn(`dsh-world: ${message}`); } });
253
262
  const repair = async () => {
254
263
  const dir = profileDir();
@@ -256,25 +265,14 @@ export async function apply(ctx, config) {
256
265
  await repairCopiedPresets({ editor: configEditor, profileDir: dir, report: message => { faults.set('preset-repair', message); lifeCtx.logger.warn(`dsh-world: ${message}`); } });
257
266
  };
258
267
  // Different worlds may edit the same profile or preset on startup.
259
- const editProfile = () => worlds.profileEdits = worlds.profileEdits.then(swap, swap).then(repair, repair);
260
- // The preset row the editor rewrites is active only once the host has finished loading.
261
- const appReady = lifeCtx.get('appReady');
262
- if (!appReady)
263
- void editProfile();
264
- else
265
- lifeCtx.effect(() => {
266
- let closed = false;
267
- const cancel = appReady.onReady(() => { if (!closed)
268
- void editProfile(); });
269
- return () => { closed = true; cancel(); };
270
- }, 'dsh-world compaction swap');
268
+ const editProfile = (edit) => worlds.profileEdits = worlds.profileEdits.then(edit, edit);
271
269
  const permissions = createWorkspacePermissions(lifeCtx, options.roomDir, power);
272
270
  // SnowLuma 的控制台在 OneBot 通道关闭时仍可用。
273
271
  const doors = createConsoleDoors({ worldDir, snowlumaHome: config.qqNative?.snowlumaHome ?? '' });
274
272
  const unregisterQq = webServer.register(qqRoute(prefix, config.allowedHosts, doors, () => qqNative?.status() ?? null, patch => qqNative?.update(patch) ?? null));
275
273
  lifeCtx.effect(() => () => unregisterQq(), 'dsh-world qq route');
276
274
  let life;
277
- const sdkAbort = new AbortController();
275
+ const hostAbort = new AbortController();
278
276
  const sdkAvailable = () => { try {
279
277
  import.meta.resolve('@snowluma/sdk');
280
278
  return true;
@@ -284,8 +282,7 @@ export async function apply(ctx, config) {
284
282
  return false;
285
283
  throw error;
286
284
  } };
287
- const qqSdk = createQqSdkInstaller({ available: sdkAvailable, profile: () => lifeCtx.get('profileContext'), signal: sdkAbort.signal });
288
- lifeCtx.effect(() => () => sdkAbort.abort(new Error('世界插件已卸载')), 'dsh-world SDK installation');
285
+ const qqSdk = createQqSdkInstaller({ available: sdkAvailable, profile: () => lifeCtx.get('profileContext'), signal: hostAbort.signal });
289
286
  let qqChange = 0;
290
287
  const homeApply = createHomeApply({
291
288
  ctx: lifeCtx,
@@ -308,6 +305,7 @@ export async function apply(ctx, config) {
308
305
  let adapter;
309
306
  let channels;
310
307
  let unregisterWechat;
308
+ let unregisterWechatNews;
311
309
  let lifeStop;
312
310
  let wechatClosing = Promise.resolve();
313
311
  /** Starts the WeChat module (its tools, route and, when configured, the adapter) against the running life line. */
@@ -315,7 +313,7 @@ export async function apply(ctx, config) {
315
313
  if (wechat || !config.wechat)
316
314
  return;
317
315
  await wechatClosing;
318
- if (wechat || life !== current || disposed || !power.running() || !power.wechatEnabled())
316
+ if (wechat || life !== current || disposed || hostAbort.signal.aborted || !power.running() || !power.wechatEnabled())
319
317
  return;
320
318
  const groupSessions = createChannelSessions({ ctx: lifeCtx, host, store, roomDir: options.roomDir, roomTitle: roomTitle(names()), agentPreset: config.agentPreset });
321
319
  channels = groupSessions;
@@ -323,6 +321,7 @@ export async function apply(ctx, config) {
323
321
  ...createWechatRecorder(store, config.worldId, archiveSession) });
324
322
  wechat.start();
325
323
  unregisterWechat = webServer.register(wechat.route);
324
+ unregisterWechatNews = elsewhere.register(wechat.elsewhere);
326
325
  if (config.wechatAdapter?.python && config.wechatAdapter.config) {
327
326
  adapter = createAdapterSupervisor({ python: config.wechatAdapter.python, config: config.wechatAdapter.config, logFile: join(worldDir, 'wechat-adapter.log'), log: message => lifeCtx.logger.warn(message) });
328
327
  adapter.start();
@@ -332,6 +331,8 @@ export async function apply(ctx, config) {
332
331
  function stopWechat() {
333
332
  unregisterWechat?.();
334
333
  unregisterWechat = undefined;
334
+ unregisterWechatNews?.();
335
+ unregisterWechatNews = undefined;
335
336
  const closingAdapter = adapter?.stop();
336
337
  adapter = undefined;
337
338
  const closing = Promise.all([closingAdapter, wechat?.stop()]).then(() => { });
@@ -351,7 +352,7 @@ export async function apply(ctx, config) {
351
352
  if (!sdkAvailable())
352
353
  throw new Error('QQ 缺少 SnowLuma SDK,请关闭再开启 QQ,按需安装依赖');
353
354
  const { createQqNativeModule } = await import("./ecosystem/qq-native/index.js");
354
- if (qqNative || life !== current || !power.running() || !power.qqEnabled())
355
+ if (qqNative || life !== current || disposed || hostAbort.signal.aborted || !power.running() || !power.qqEnabled())
355
356
  return;
356
357
  const groupSessions = createChannelSessions({ ctx: lifeCtx, host, store, roomDir: options.roomDir, roomTitle: roomTitle(names()), agentPreset: config.agentPreset });
357
358
  qqChannels = groupSessions;
@@ -405,32 +406,43 @@ export async function apply(ctx, config) {
405
406
  async function startLife(resumed) {
406
407
  if (!lifeStore || life)
407
408
  return;
409
+ let current;
410
+ const failed = async (error) => {
411
+ if (disposed || hostAbort.signal.aborted || life !== current)
412
+ return;
413
+ faults.set('life', `生活线没能启动:${errorText(error)}`);
414
+ lifeCtx.logger.error(error);
415
+ await stopLife();
416
+ };
408
417
  try {
409
418
  await lifeStop;
410
- if (disposed)
419
+ if (disposed || hostAbort.signal.aborted)
411
420
  return;
412
421
  const outlets = config.outlets.map(outlet => createOutlet(outlet, () => host.origin()));
413
422
  const notifier = { ...(config.toast && toastSupported() ? { toast: windowsToast(config.toastAppId || undefined) } : {}), outlets };
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())
423
+ const runtime = 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())
415
424
  homeApply.request(); } });
416
- life = current;
417
- isHome = current.isHome;
425
+ life = current = runtime;
426
+ isHome = runtime.isHome;
418
427
  if (config.bridge) {
419
- bridge = createBridge({ ctx: lifeCtx, prefix, home: () => current.home(), inWorld: inWorldSession, outlets, origin: () => host.origin(), file: join(worldDir, 'bridge.json'), name: names().companion });
428
+ bridge = createBridge({ ctx: lifeCtx, prefix, home: () => runtime.home(), inWorld: inWorldSession, outlets, origin: () => host.origin(), file: join(worldDir, 'bridge.json'), name: names().companion });
420
429
  bridge.start();
421
430
  }
422
431
  if (config.wechat && power.wechatEnabled())
423
- await startWechat(current);
432
+ await startWechat(runtime);
424
433
  if (config.qqNative?.enabled && power.qqEnabled())
425
- await startQqNative(current);
434
+ await startQqNative(runtime);
435
+ if (disposed || hostAbort.signal.aborted)
436
+ return;
426
437
  faults.clear('life');
427
- await current.start({ resumed });
438
+ const started = runtime.start({ resumed });
439
+ if (resumed)
440
+ await started;
441
+ else
442
+ void started.catch(error => changeWorld(() => failed(error))).finally(sources.invalidate).catch(error => lifeCtx.logger.error(error));
428
443
  }
429
444
  catch (error) {
430
- // The console still opens and says why, instead of looking as if the life line were simply off.
431
- await stopLife();
432
- faults.set('life', `生活线没能启动:${errorText(error)}`);
433
- lifeCtx.logger.error(error);
445
+ await failed(error);
434
446
  }
435
447
  }
436
448
  function stopLife() {
@@ -444,14 +456,18 @@ export async function apply(ctx, config) {
444
456
  return lifeStop = Promise.all([lifeStop, closingWechat, homeApply.cancel()]).then(() => { });
445
457
  }
446
458
  stopLifeLine = stopLife;
447
- lifeCtx.effect(() => () => changeWorld(stopLife), 'dsh-world life line');
459
+ lifeCtx.effect(() => () => {
460
+ hostAbort.abort(new Error('世界插件已卸载'));
461
+ return changeWorld(stopLife);
462
+ }, 'dsh-world life line');
448
463
  // The host matches exact routes before the longest prefix, so this path never reaches the console.
449
464
  if (config.bridge)
450
465
  lifeCtx.effect(() => webServer.register(bridgeRoute(prefix, () => bridge, config.allowedHosts)), 'dsh-world bridge route');
451
466
  if (config.bridge)
452
467
  lifeCtx.effect(() => webServer.register(compactRoute(prefix, () => bridge, () => !power.running() || !life ? '请先启动世界生活线' : homeApply.request(), config.allowedHosts)), 'dsh-world compact route');
453
468
  // Her album lives in her room, so the console shows it whether or not the life line is running.
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,
469
+ const sources = consoleSources({ ctx: lifeCtx, config: memoryConfig, archive: store, moodFile, 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,
470
+ compactionPreset: () => configEditor ? compactionPresetOverride(configEditor, config.agentPreset, profileDir()) : null,
455
471
  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()] });
456
472
  const actions = {
457
473
  start: () => changeWorld(async () => {
@@ -478,6 +494,12 @@ export async function apply(ctx, config) {
478
494
  }
479
495
  }),
480
496
  applyHome: () => !power.running() || !life ? '请先启动世界生活线' : homeApply.request(),
497
+ restoreCompactionPreset: () => editProfile(async () => {
498
+ const dir = profileDir();
499
+ if (!configEditor || !dir)
500
+ throw new Error('宿主配置编辑服务不可用');
501
+ await restoreCompactionPreset(configEditor, config.agentPreset, dir);
502
+ }).finally(sources.invalidate),
481
503
  prompts: () => ({
482
504
  persona: readPersona(personaFile),
483
505
  worldPrompt: existsSync(worldPromptFile) ? (text => ({ text, custom: true, memory: { missing: memoryTemplateGaps(text), snippet: readFileSync(MEMORY_SNIPPET_FILE, 'utf8') } }))(readFileSync(worldPromptFile, 'utf8')) : { text: readFileSync(DEFAULT_TEMPLATE_FILE, 'utf8'), custom: false },
@@ -499,7 +521,7 @@ export async function apply(ctx, config) {
499
521
  if (patch.qq === true) {
500
522
  try {
501
523
  restartRequired = await qqSdk.ensure();
502
- sdkAbort.signal.throwIfAborted();
524
+ hostAbort.signal.throwIfAborted();
503
525
  faults.clear('qq-sdk');
504
526
  }
505
527
  catch (error) {
@@ -562,8 +584,24 @@ export async function apply(ctx, config) {
562
584
  }
563
585
  };
564
586
  }, 'dsh-world world list');
565
- if (power.running())
566
- await changeWorld(async () => { if (!disposed && power.running())
567
- await startLife(false); });
587
+ const ready = () => {
588
+ if (disposed || hostAbort.signal.aborted)
589
+ return;
590
+ void editProfile(async () => { try {
591
+ swap();
592
+ }
593
+ finally {
594
+ await repair();
595
+ } }).catch(error => lifeCtx.logger.error(error));
596
+ if (power.running())
597
+ void changeWorld(async () => { if (power.running())
598
+ await startLife(false); }).catch(error => lifeCtx.logger.error(error));
599
+ };
600
+ // Home restoration and profile edits can call host services that wait for boot to finish.
601
+ const appReady = lifeCtx.get('appReady');
602
+ if (appReady)
603
+ lifeCtx.effect(() => appReady.onReady(ready), 'dsh-world host ready');
604
+ else
605
+ ready();
568
606
  });
569
607
  }
package/lib/life/home.js CHANGED
@@ -14,6 +14,8 @@ export function createHome(deps) {
14
14
  let untitled;
15
15
  /** A new home before its first turn ends. */
16
16
  let firstTurn;
17
+ function assertRunning() { if (deps.stopped())
18
+ throw new Error('生活线已停止'); }
17
19
  async function rename(sessionId) {
18
20
  try {
19
21
  await host.rename(sessionId, deps.title);
@@ -27,9 +29,11 @@ export function createHome(deps) {
27
29
  }
28
30
  }
29
31
  async function ready(agent) {
32
+ assertRunning();
30
33
  admit(deps.inWorld, agent);
31
34
  if (untitled === agent.id && await rename(agent.id) && untitled === agent.id)
32
35
  untitled = undefined;
36
+ assertRunning();
33
37
  deps.opened(agent);
34
38
  return agent;
35
39
  }
@@ -42,10 +46,13 @@ export function createHome(deps) {
42
46
  return workspace;
43
47
  }
44
48
  async function build() {
49
+ assertRunning();
45
50
  const workspace = await room();
51
+ assertRunning();
46
52
  const current = deps.current();
47
53
  if (current && !host.isArchived(current)) {
48
54
  const agent = await host.resolveAgent(current);
55
+ assertRunning();
49
56
  if (agent) {
50
57
  // A home built before her room was a workspace moves in.
51
58
  if (!workspace.sessionIds.includes(agent.id))
@@ -54,8 +61,7 @@ export function createHome(deps) {
54
61
  }
55
62
  }
56
63
  const sessionId = await host.createSession(deps.roomDir, deps.agentPreset, workspace.id);
57
- if (deps.stopped())
58
- throw new Error('生活线已停止');
64
+ assertRunning();
59
65
  untitled = sessionId;
60
66
  firstTurn = sessionId;
61
67
  deps.moveIn(sessionId);
@@ -1,44 +1,78 @@
1
- import { SessionSeq } from '@deepseek-ai/dsh-session';
1
+ import { readFile, stat } from 'node:fs/promises';
2
+ import { basename, resolve } from 'node:path';
2
3
  import { defineTool } from '@deepseek-ai/dsh-tools';
3
- /** Channel images stay in recall data, linked to the current message rather than shared memory. */
4
- function currentImages(agent) {
5
- let messageId;
6
- for (let seq = agent.session.seq - 1; seq >= 0; seq--) {
7
- const event = agent.session.eventAt(SessionSeq(seq));
8
- if (event?.type === 'turn/start' || event?.type === 'turn/end')
9
- break;
10
- if (event?.type !== 'user/message')
4
+ const MAX_FILE_BYTES = 20 * 1024 * 1024;
5
+ /**
6
+ * Every image still in front of her: the images on her session's surface, newest message first and in their own order
7
+ * inside a message, so 0 is the newest. A compacted image has left the surface, and with it this list.
8
+ */
9
+ function visibleImages(agent) {
10
+ const { session } = agent, nodes = session.surface.nodes, found = [];
11
+ for (let index = nodes.length - 1; index >= 0; index--) {
12
+ const event = session.eventAt(nodes[index]);
13
+ if (!event)
11
14
  continue;
12
- const source = event.data.source;
13
- if (source.kind === 'user' || (source.kind === 'dsh-world-channel-context' && !source.forMessageId)) {
14
- if (messageId !== undefined)
15
- return [];
16
- messageId = event.data.id;
17
- const images = event.data.content.flatMap(block => block.type === 'image' ? [block.attachment] : []);
18
- if (images.length)
19
- return images;
15
+ let message;
16
+ try {
17
+ message = session.deriveEventMessage(event);
20
18
  }
21
- else if (source.kind === 'dsh-world-channel-context' && messageId !== undefined && source.forMessageId === messageId) {
22
- return event.data.content.flatMap(block => block.type === 'image' ? [block.attachment] : []);
19
+ catch {
20
+ continue;
23
21
  }
22
+ for (const block of message?.content ?? [])
23
+ if (block.type === 'image')
24
+ found.push(block.attachment);
24
25
  }
25
- return [];
26
+ return found;
27
+ }
28
+ /** Only the four image types the attachment service keeps; the bytes decide, never the file name. */
29
+ function mediaTypeOf(bytes) {
30
+ const starts = (...head) => head.every((byte, at) => bytes[at] === byte);
31
+ if (starts(0x89, 0x50, 0x4e, 0x47))
32
+ return 'image/png';
33
+ if (starts(0xff, 0xd8, 0xff))
34
+ return 'image/jpeg';
35
+ if (starts(0x47, 0x49, 0x46, 0x38))
36
+ return 'image/gif';
37
+ if (starts(0x52, 0x49, 0x46, 0x46) && bytes[8] === 0x57 && bytes[9] === 0x45 && bytes[10] === 0x42 && bytes[11] === 0x50)
38
+ return 'image/webp';
39
+ return undefined;
40
+ }
41
+ /** A picture on her computer: committed to the host's attachment store like any channel image, then read back verified. */
42
+ async function fileImage(attachments, path, signal) {
43
+ const info = await stat(path).catch(() => undefined);
44
+ if (!info?.isFile())
45
+ throw new Error(`没有找到这个图片文件:${path}`);
46
+ if (info.size > MAX_FILE_BYTES)
47
+ throw new Error('图片文件最多 20MB');
48
+ const data = new Uint8Array(await readFile(path, { signal }));
49
+ const mediaType = mediaTypeOf(data);
50
+ if (!mediaType)
51
+ throw new Error('只能收藏 png、jpg、webp、gif 图片');
52
+ return attachments.readImage(await attachments.saveImage({ data, mediaType, name: basename(path) }), signal);
26
53
  }
27
54
  export function photoTools(deps) {
28
55
  const output = { schema: { type: 'string' }, render: (_args, value) => [{ type: 'text', text: value }] };
29
56
  const check = () => { if (!deps.inside())
30
57
  throw new Error('相册工具只能在当前家会话的世界工作区内使用'); };
31
58
  return [
32
- defineTool({ name: 'keep_photo', description: '想收藏当前消息里值得长期保留的图片时使用,由我自己决定。index 从 0 开始,只能选本轮最新消息中的图片(含本轮已读取的微信图片和引用图);照片保存到我的相册,不自动加入之后每轮上下文。description 最多 500 字,tags 最多 8 个、每个 40 字。', parameters: { index: { type: 'integer' }, description: { type: 'string' }, tags: { type: 'array', items: { type: 'string' } } }, output,
33
- execute: async ({ index = 0, description = '', tags = [] }, context) => {
59
+ defineTool({ name: 'keep_photo', description: '想收藏一张值得长期保留的图片时使用,由我自己决定。两种来源:不填 path 时,index 选我眼前的图片,0 是最新的一张,往前数依次加 1,聊天里收到的、引用的、工具读出来的都算;填 path 时,收藏电脑上的一个图片文件(png、jpg、webp、gif,最多 20MB,相对路径从我的房间算起)。照片保存到我的相册,不自动加入之后每轮上下文。description 最多 500 字,tags 最多 8 个、每个 40 字。', parameters: { index: { type: 'integer' }, path: { type: 'string' }, description: { type: 'string' }, tags: { type: 'array', items: { type: 'string' } } }, output,
60
+ execute: async ({ index = 0, path, description = '', tags = [] }, context) => {
34
61
  check();
35
- const images = currentImages(deps.agent);
36
- if (!Number.isSafeInteger(index) || index < 0 || index >= images.length)
37
- throw new Error('index 必须指向本轮最新用户消息中的图片');
38
62
  const attachments = deps.attachments();
39
63
  if (!attachments)
40
64
  throw new Error('宿主图片存储不可用');
41
- const image = await attachments.readImage(images[index], context.signal);
65
+ let image;
66
+ if (typeof path === 'string' && path.trim())
67
+ image = await fileImage(attachments, resolve(deps.agent.session.header.cwd ?? '', path.trim()), context.signal);
68
+ else {
69
+ const images = visibleImages(deps.agent);
70
+ if (!images.length)
71
+ throw new Error('我眼前现在没有图片;电脑上的图片可以用 path 指定文件');
72
+ if (!Number.isSafeInteger(index) || index < 0 || index >= images.length)
73
+ throw new Error(`index 超出范围:我眼前现在一共有 ${images.length} 张图片,0 是最新的一张`);
74
+ image = await attachments.readImage(images[index], context.signal);
75
+ }
42
76
  context.signal.throwIfAborted();
43
77
  check();
44
78
  return JSON.stringify(deps.store().keep(image, description, tags));
@@ -492,6 +492,8 @@ export function createLifeRuntime(deps) {
492
492
  record(() => store.write(state));
493
493
  try {
494
494
  const agent = await home.open();
495
+ if (stopped)
496
+ return;
495
497
  faults.clear('home');
496
498
  reconcile(agent);
497
499
  // The morning fallback is the plugin's, not a plan of hers: starting again wakes her rather than leaving her asleep till then.
@@ -9,13 +9,14 @@ import type { MemoryService } from './memory.ts';
9
9
  */
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
- export declare function memoryTools(service: MemoryService, inside: () => boolean): ToolDefinition[];
12
+ /** `looked`: she paged the newest lines of one chat source (no query, newest first, first page), so it is caught up. */
13
+ export declare function memoryTools(service: MemoryService, inside: () => boolean, looked?: (sourceId: string) => void): ToolDefinition[];
13
14
  /**
14
- * Gives world sessions their tools (long-term memory), whatever the life line does: a session has them
15
+ * Gives world sessions their tools (long-term memory, her mood), whatever the life line does: a session has them
15
16
  * while it is in her world, and loses them when it leaves. A registration that fails is a fault, never a broken agent.
16
17
  */
17
18
  export declare function createWorldToolRegistry(deps: {
18
- tools(inside: () => boolean): ToolDefinition[];
19
+ tools(inside: () => boolean, agent: Agent): ToolDefinition[];
19
20
  inWorld(agent: Agent): boolean;
20
21
  faults: Faults;
21
22
  logger: {