dsh-world 0.7.4 → 0.7.5

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 (52) hide show
  1. package/CHANGELOG.md +43 -0
  2. package/NOTES.md +34 -16
  3. package/README.md +12 -6
  4. package/client/index.js +37 -2
  5. package/lib/abortable.d.ts +1 -0
  6. package/lib/abortable.js +17 -0
  7. package/lib/compactionSwap.d.ts +9 -17
  8. package/lib/compactionSwap.js +27 -35
  9. package/lib/console/homeApply.js +1 -12
  10. package/lib/console/routes.d.ts +1 -0
  11. package/lib/console/routes.js +10 -0
  12. package/lib/console/snapshot.d.ts +4 -0
  13. package/lib/console/snapshot.js +3 -0
  14. package/lib/ecosystem/bridge/bridge.d.ts +2 -2
  15. package/lib/ecosystem/bridge/bridge.js +24 -11
  16. package/lib/ecosystem/qq-native/home.d.ts +2 -1
  17. package/lib/ecosystem/qq-native/home.js +6 -2
  18. package/lib/ecosystem/qq-native/images.d.ts +9 -0
  19. package/lib/ecosystem/qq-native/images.js +69 -0
  20. package/lib/ecosystem/qq-native/index.d.ts +1 -0
  21. package/lib/ecosystem/qq-native/index.js +8 -2
  22. package/lib/ecosystem/qq-native/snowluma.d.ts +1 -0
  23. package/lib/ecosystem/qq-native/snowluma.js +13 -4
  24. package/lib/ecosystem/wechat/supervisor.d.ts +1 -1
  25. package/lib/ecosystem/wechat/supervisor.js +5 -1
  26. package/lib/index.d.ts +1 -1
  27. package/lib/index.js +77 -46
  28. package/lib/life/home.js +8 -2
  29. package/lib/life/photoTools.js +60 -26
  30. package/lib/life/runtime.js +2 -0
  31. package/lib/memoryTools.d.ts +1 -1
  32. package/lib/memoryTools.js +1 -1
  33. package/lib/mood.d.ts +33 -4
  34. package/lib/mood.js +38 -12
  35. package/lib/moodTools.d.ts +6 -0
  36. package/lib/moodTools.js +30 -0
  37. package/lib/persona.js +7 -0
  38. package/lib/promptSection.d.ts +9 -13
  39. package/lib/promptSection.js +63 -80
  40. package/lib/runtime.d.ts +21 -2
  41. package/lib/runtime.js +120 -38
  42. package/lib/sourceArchive.d.ts +1 -5
  43. package/lib/sourceArchive.js +31 -14
  44. package/lib/worldScope.d.ts +2 -4
  45. package/lib/worldScope.js +6 -6
  46. package/package.json +1 -1
  47. package/src/ecosystem/wechat/windows/README.md +4 -2
  48. package/src/ecosystem/wechat/windows/adapter.py +6 -1
  49. package/src/ecosystem/wechat/windows/engine/NOTICE.md +6 -0
  50. package/src/ecosystem/wechat/windows/engine/profiles.json +28 -0
  51. package/src/ecosystem/wechat/windows/sender.py +6 -2
  52. package/templates/world-prompt.md +1 -1
@@ -13,8 +13,8 @@ export class HomeUnavailable extends Error {
13
13
  }
14
14
  const labels = (name) => ({ reply: `${name}的回复`, busy: `「${name}在忙」`, reach: `${name}找你的话` });
15
15
  /**
16
- * A local app's way into her home: its words arrive as her partner's own (source `user`), and the first
17
- * visible text she says after they are admitted goes to the outlets. Only the latest words are tracked.
16
+ * A local app's way into her home: its words arrive as her partner's own (source `user`). The final
17
+ * reply after admission goes to the outlets when that turn completes. Only the latest words are tracked.
18
18
  */
19
19
  export function createBridge(deps) {
20
20
  const { ctx } = deps;
@@ -56,18 +56,31 @@ export function createBridge(deps) {
56
56
  disposers.push(ctx.on('session/event', (session, event) => {
57
57
  if (!tracked || session.id !== tracked.sessionId)
58
58
  return;
59
- if (event.type === 'user/message' && event.data.id === tracked.id) {
60
- tracked.admitted = true;
59
+ if (event.type === 'user/message') {
60
+ if (event.data.id === tracked.id)
61
+ tracked.admitted = true;
62
+ else if (tracked.admitted && event.data.source.kind === 'user')
63
+ untrack();
61
64
  return;
62
65
  }
63
- if (event.type !== 'assistant/message' || !tracked.admitted)
66
+ if (!tracked.admitted)
64
67
  return;
65
- const visible = event.data.message.content.flatMap(block => block.type === 'text' ? [block.text] : []).join('\n');
66
- const reply = pushOf(visible, 'reply', name, safeOrigin());
67
- if (!reply.text && !reply.images)
68
- return;
69
- untrack();
70
- send(reply);
68
+ if (event.type === 'assistant/message') {
69
+ const { content } = event.data.message;
70
+ // Text accompanying a tool call can be narration, including when the tool itself ends the turn.
71
+ tracked.finalText = content.some(block => block.type === 'tool-call') ? undefined
72
+ : content.flatMap(block => block.type === 'text' ? [block.text] : []).join('\n');
73
+ }
74
+ // The next turn end in this session closes the turn that admitted the words, even when steered in.
75
+ if (event.type === 'turn/end') {
76
+ const { finalText } = tracked;
77
+ untrack();
78
+ if (event.data.reason.kind !== 'completed' || !finalText)
79
+ return;
80
+ const reply = pushOf(finalText, 'reply', name, safeOrigin());
81
+ if (reply.text || reply.images)
82
+ send(reply);
83
+ }
71
84
  }));
72
85
  try {
73
86
  durableWrite(deps.file, JSON.stringify({ origin: deps.origin(), ...bridgePaths(deps.prefix), token, pid: process.pid, startedAt: clock().toISOString(), name }, null, 2));
@@ -1,5 +1,6 @@
1
1
  import type { Context } from '@deepseek-ai/cordis';
2
2
  import type { Agent } from '@deepseek-ai/dsh-agent';
3
+ import { type ContentBlock } from '@deepseek-ai/dsh-llm';
3
4
  import { type SpeakerIdentity } from '../shared/identity.ts';
4
5
  import type { LifeTimers } from '../../life/alarmTimer.ts';
5
6
  import { type ChannelContextMessage } from '../shared/context.ts';
@@ -16,7 +17,7 @@ export declare function createQqHome(deps: {
16
17
  inWorld?: InWorld;
17
18
  timers?: LifeTimers;
18
19
  }): {
19
- ask: (text: string, suppliedIdentity: SpeakerIdentity, suppliedContext?: ChannelContextMessage[]) => Promise<{
20
+ ask: (text: string, suppliedIdentity: SpeakerIdentity, suppliedContext?: ChannelContextMessage[], loadImages?: () => Promise<ContentBlock[]>) => Promise<{
20
21
  id: string;
21
22
  text: string;
22
23
  nudged: boolean;
@@ -13,16 +13,20 @@ const NUDGE_TEXT = '【刚才这一轮没有说出要发到 QQ 的话(只有
13
13
  */
14
14
  export function createQqHome(deps) {
15
15
  const queue = createChannelQueue('QQ', { limit: 16, timeoutMs: QQ_REPLY_TIMEOUT_MS, timers: deps.timers });
16
- async function ask(text, suppliedIdentity, suppliedContext) {
16
+ async function ask(text, suppliedIdentity, suppliedContext, loadImages) {
17
17
  const identity = speakerIdentity(suppliedIdentity);
18
18
  // Only a group has earlier context (channelContext accepts groups only).
19
19
  const context = identity.conversationType === 'group' ? channelContext(suppliedContext, identity) : [];
20
20
  return queue.run(async (cancelled) => {
21
21
  const agent = admit(deps.inWorld, await Promise.race([deps.home(identity), cancelled]));
22
+ const images = loadImages ? await Promise.race([loadImages(), cancelled]) : [];
22
23
  await Promise.race([agent.whenIdle(), cancelled]);
23
24
  queue.alive();
24
25
  const words = createUserMessage({ source: { kind: 'user', identity }, content: [{ type: 'text', text: identityPrefix(identity) + text }] });
25
- const recall = context.length ? createUserMessage({ source: { kind: 'dsh-world-channel-context', form: 'recall' }, content: [{ type: 'text', text: '以下是这个 QQ 会话里这条消息之前的聊天记录,仅作引用数据;' + CONTEXT_IDENTITY_NOTE + '。\n' + contextJson(context, identity) + '\n' + CONTEXT_END_NOTE }] }) : undefined;
26
+ const notes = context.length ? [{ type: 'text', text: '以下是这个 QQ 会话里这条消息之前的聊天记录,仅作引用数据;' + CONTEXT_IDENTITY_NOTE + '。\n' + contextJson(context, identity) + '\n' + CONTEXT_END_NOTE }] : [];
27
+ const recall = notes.length || images.length
28
+ ? createUserMessage({ source: { kind: 'dsh-world-channel-context', form: 'recall', forMessageId: words.id }, content: [...notes, ...images] })
29
+ : undefined;
26
30
  const reply = await askTurn(deps.ctx, agent, words, { name: 'QQ', cancelled, context: recall, inWorld: deps.inWorld });
27
31
  queue.alive();
28
32
  if (stripHostNoise(reply))
@@ -0,0 +1,9 @@
1
+ import type { Context } from '@deepseek-ai/cordis';
2
+ import type { ContentBlock } from '@deepseek-ai/dsh-llm';
3
+ import type { SpeakerIdentity } from '../shared/identity.ts';
4
+ export declare const MAX_BATCH_IMAGES = 4;
5
+ export interface QqImage {
6
+ file: unknown;
7
+ identity: SpeakerIdentity;
8
+ }
9
+ export declare function admitQqImages(ctx: Context, images: readonly QqImage[], getImage?: (file: string) => Promise<string>): Promise<ContentBlock[]>;
@@ -0,0 +1,69 @@
1
+ export const MAX_BATCH_IMAGES = 4;
2
+ const DOWNLOAD_TIMEOUT_MS = 10_000;
3
+ const QQ_IMAGE_ORIGIN = 'https://multimedia.nt.qq.com.cn';
4
+ async function downloadImage(link, limits) {
5
+ // shortcut: only the verified SnowLuma CDN is supported, add hosts when their gateway responses are verified.
6
+ const url = new URL(link);
7
+ if (url.protocol !== 'https:' || url.origin !== QQ_IMAGE_ORIGIN || url.username || url.password)
8
+ throw new Error('QQ 图片链接不受支持');
9
+ const controller = new AbortController();
10
+ try {
11
+ const response = await fetch(url, {
12
+ redirect: 'error',
13
+ signal: AbortSignal.any([controller.signal, AbortSignal.timeout(DOWNLOAD_TIMEOUT_MS)]),
14
+ });
15
+ const contentType = response.headers.get('content-type')?.split(';')[0]?.trim().toLowerCase();
16
+ const mediaType = limits.mediaTypes.find(type => type === contentType);
17
+ if (!response.ok || !response.body || !mediaType)
18
+ throw new Error('QQ 图片响应无效');
19
+ if (Number(response.headers.get('content-length')) > limits.maxImageBytes)
20
+ throw new Error('QQ 图片超过大小限制');
21
+ const chunks = [];
22
+ let bytes = 0;
23
+ for await (const chunk of response.body) {
24
+ bytes += chunk.byteLength;
25
+ if (bytes > limits.maxImageBytes)
26
+ throw new Error('QQ 图片超过大小限制');
27
+ chunks.push(chunk);
28
+ }
29
+ return { data: Buffer.concat(chunks, bytes), mediaType };
30
+ }
31
+ finally {
32
+ controller.abort();
33
+ }
34
+ }
35
+ export async function admitQqImages(ctx, images, getImage) {
36
+ if (!images.length)
37
+ return [];
38
+ const unavailable = { type: 'text', text: '本次有 QQ 图片未能读取,请勿假装看过。' };
39
+ const store = ctx.get('attachments');
40
+ if (!store || !getImage)
41
+ return [unavailable];
42
+ const limits = store.imageLimits;
43
+ const selected = images.slice(0, Math.min(MAX_BATCH_IMAGES, limits.maxImagesPerMessage));
44
+ const downloads = await Promise.allSettled(selected.map(async ({ file }) => {
45
+ if (typeof file !== 'string' || !/^[a-z0-9_-][a-z0-9_.-]{0,255}$/i.test(file))
46
+ throw new Error('QQ 图片标识无效');
47
+ return downloadImage(await getImage(file), limits);
48
+ }));
49
+ const content = [];
50
+ let remainingBytes = limits.maxMessageImageBytes;
51
+ let saved = 0;
52
+ for (const [index, result] of downloads.entries()) {
53
+ if (result.status === 'rejected' || result.value.data.byteLength > remainingBytes)
54
+ continue;
55
+ try {
56
+ const [attachment] = await store.saveImages([result.value]);
57
+ if (!attachment)
58
+ continue;
59
+ const { platformMessageId, speakerId, speakerName } = selected[index].identity;
60
+ content.push({ type: 'text', text: `下面是本次收到的第 ${index + 1} 张 QQ 图片,来源:${JSON.stringify({ messageId: platformMessageId, speakerId, speakerName })}。` }, { type: 'image', attachment });
61
+ remainingBytes -= result.value.data.byteLength;
62
+ saved++;
63
+ }
64
+ catch { /* 一张无法保存时仍交付同批的其他图片和文字。 */ }
65
+ }
66
+ if (saved < images.length)
67
+ content.push(unavailable);
68
+ return content;
69
+ }
@@ -90,6 +90,7 @@ export interface QqTransport {
90
90
  sendPrivate(userId: string, parts: string | QqPart[]): Promise<{
91
91
  messageId: string;
92
92
  }>;
93
+ getImage?(file: string): Promise<string>;
93
94
  /** 发账号收藏表情(不是消息段,单发一条);测试替身可以不实现。 */
94
95
  sendCustomFace?(emojiId: string, target: {
95
96
  groupId?: string;
@@ -4,6 +4,7 @@ import { dirname, join } from 'node:path';
4
4
  import { speakerIdentity, conversationKey } from "../shared/identity.js";
5
5
  import { createBridge } from "./snowluma.js";
6
6
  import { createQqHome } from "./home.js";
7
+ import { admitQqImages, MAX_BATCH_IMAGES } from "./images.js";
7
8
  import { createBatcher } from "./batch.js";
8
9
  import { createOutbox } from "./outbox.js";
9
10
  import { planReply, stripHostNoise } from "./replies.js";
@@ -218,7 +219,9 @@ export function createQqNativeModule(deps) {
218
219
  pushContext(key, { id: messageId || String(Date.now()), occurredAt: new Date().toISOString(), text, identity }, config.contextMessages);
219
220
  return;
220
221
  }
221
- batches.add(key, { text, identity, who: speakerName });
222
+ const imageFiles = (message.segments ?? []).filter(segment => segment?.type === 'image')
223
+ .slice(0, MAX_BATCH_IMAGES + 1).map(segment => segment.data?.file);
224
+ batches.add(key, { text, identity, who: speakerName, imageFiles });
222
225
  }
223
226
  async function answer(key, gathered) {
224
227
  const config = settings();
@@ -231,7 +234,10 @@ export function createQqNativeModule(deps) {
231
234
  const text = gathered.length === 1 ? gathered[0].text : gathered.map(item => isGroup && item.who ? `${item.who}: ${item.text}` : item.text).join('\n');
232
235
  answering.add(key);
233
236
  try {
234
- const reply = await home.ask(text, identity, contexts.get(key) ?? []);
237
+ const images = gathered.flatMap(item => item.imageFiles.map(file => ({ file, identity: item.identity })));
238
+ const reply = await home.ask(text, identity, contexts.get(key) ?? [], images.length
239
+ ? () => admitQqImages(deps.ctx, images, client?.getImage?.bind(client))
240
+ : undefined);
235
241
  const words = stripHostNoise(reply.text);
236
242
  // 提醒过一次还是没有能发的话:不发,但要留下痕迹,分得清「她没说出话」和「路丢了」(#34);
237
243
  // 只剩复述的聊天记录、工具标签这些(#35)也一样。
@@ -79,6 +79,7 @@ export declare function createBridge(options: Loose): {
79
79
  sendPrivate(userId: Loose, parts: Loose): Promise<{
80
80
  messageId: string;
81
81
  }>;
82
+ getImage(file: string): Promise<string>;
82
83
  /**
83
84
  * 发账号收藏表情:它走 `send_custom_face`,不是消息段,只能单发一条。`emojiId` 可以是 emoji_id、
84
85
  * 第几个(1 起),或者一个意思(「开心」)——按备注挑。
@@ -140,9 +140,9 @@ function escapeOutgoingText(value) {
140
140
  * @returns {string}
141
141
  */
142
142
  export function segmentsToText(message) {
143
- // 有些 OneBot 实现直接把纯文本消息放在 message 字段里(string)
143
+ // CQ 字符串里的图片链接也不交给模型,取图只使用解析出的 file 标识。
144
144
  if (typeof message === 'string')
145
- return message.trim();
145
+ return message.replace(/\[CQ:image(?:,[^\]]*)?\]/g, '[图片]').trim();
146
146
  const list = Array.isArray(message)
147
147
  ? message
148
148
  : (message && typeof message === 'object' ? [message] : []);
@@ -169,9 +169,8 @@ export function segmentsToText(message) {
169
169
  case 'mface':
170
170
  out.push(`[表情${d.summary ? `:${d.summary}` : ''}]`);
171
171
  break;
172
- // 带上 file 名:光写「[图片]」等于把图丢了,有 file 才能再向 OneBot 换直链。
173
172
  case 'image':
174
- out.push(d.file ? `[图片 file=${d.file}]` : '[图片]');
173
+ out.push('[图片]');
175
174
  break;
176
175
  case 'record':
177
176
  out.push(d.file ? `[语音 file=${d.file}]` : '[语音]');
@@ -601,6 +600,16 @@ export function createBridge(options) {
601
600
  throw new Error(`sendPrivate: 无效的 QQ 号 ${JSON.stringify(userId ?? null)}`);
602
601
  return enqueueSend('private', id, parts);
603
602
  },
603
+ async getImage(file) {
604
+ if (!client)
605
+ throw new Error('QQ 桥未启动或已停止,无法取图');
606
+ const { url, file_url: fileUrl } = (await client.getImage({ file }, { timeoutMs: SEND_TIMEOUT_MS })) ?? {};
607
+ if (typeof url === 'string' && url)
608
+ return url;
609
+ if (typeof fileUrl === 'string' && fileUrl)
610
+ return fileUrl;
611
+ throw new Error('SnowLuma 未返回图片直链');
612
+ },
604
613
  /**
605
614
  * 发账号收藏表情:它走 `send_custom_face`,不是消息段,只能单发一条。`emojiId` 可以是 emoji_id、
606
615
  * 第几个(1 起),或者一个意思(「开心」)——按备注挑。
@@ -32,7 +32,7 @@ export interface AdapterSupervisorDeps {
32
32
  /**
33
33
  * Runs the Windows WeChat adapter for as long as the world's WeChat module lives: started with the module,
34
34
  * restarted with a growing delay when it exits or cannot start (a file missing during an upgrade comes back),
35
- * and stopped (its whole process tree) with the module. An exit that says a person must act is not retried. An exit
35
+ * and stopped (its whole process tree) with the module. Unsupported builds and exits that need a person halt. An exit
36
36
  * that says the native bridge needs building is answered by building it once into the `engine` folder beside the
37
37
  * adapter's config (where the adapter looks) and starting it again; a build that fails, or still does not match,
38
38
  * stops with what to do. The adapter itself waits for the same WeChat account to log in again, so a WeChat
@@ -10,6 +10,8 @@ export const BUILD_SCRIPT = fileURLToPath(new URL('../../../src/ecosystem/wechat
10
10
  export const EXIT_NEEDS_HUMAN = 2;
11
11
  /** The adapter exits with this when no build of the native bridge matches its source (an upgrade changed it). */
12
12
  export const EXIT_NEEDS_BUILD = 3;
13
+ /** The adapter exits with this when its Weixin.dll cannot be matched to a supported build. */
14
+ const EXIT_UNSUPPORTED_BUILD = 4;
13
15
  const MAX_LOG_BYTES = 1024 * 1024;
14
16
  const HEALTHY_MS = 60_000;
15
17
  const BUILD_BY_HAND = '请在仓库里运行 wechat.ps1 Build,再在控制台重启适配器';
@@ -35,7 +37,7 @@ function lastLine(file, from) {
35
37
  /**
36
38
  * Runs the Windows WeChat adapter for as long as the world's WeChat module lives: started with the module,
37
39
  * restarted with a growing delay when it exits or cannot start (a file missing during an upgrade comes back),
38
- * and stopped (its whole process tree) with the module. An exit that says a person must act is not retried. An exit
40
+ * and stopped (its whole process tree) with the module. Unsupported builds and exits that need a person halt. An exit
39
41
  * that says the native bridge needs building is answered by building it once into the `engine` folder beside the
40
42
  * adapter's config (where the adapter looks) and starting it again; a build that fails, or still does not match,
41
43
  * stops with what to do. The adapter itself waits for the same WeChat account to log in again, so a WeChat
@@ -162,6 +164,8 @@ export function createAdapterSupervisor(deps) {
162
164
  }
163
165
  else if (code === EXIT_NEEDS_BUILD)
164
166
  rebuild();
167
+ else if (code === EXIT_UNSUPPORTED_BUILD)
168
+ halted(said ?? '当前微信构建无法匹配受支持的版本,已停止自动重启');
165
169
  else {
166
170
  deps.log(`dsh-world WeChat adapter exited (${text}); restarting`);
167
171
  schedule();
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";
@@ -49,7 +49,7 @@ export const Config = z.object({
49
49
  worldId: z.string().default('default'), agentPreset: z.string().default('standard'), timeZone: z.string().default(systemTimeZone),
50
50
  companionName: z.string(), partnerName: z.string(),
51
51
  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.
52
+ // Only a profile-level stock row can be switched automatically. Session presets own their compaction.
53
53
  replaceCompaction: z.boolean().default(true),
54
54
  life: z.boolean().default(true), diaryDir: z.string(), fallbackWakeTime: z.string().pattern(CLOCK_TIME).default('09:00'),
55
55
  selfFile: z.string(), worldPromptFile: z.string(), alarmTemplateFile: z.string(), personaFile: z.string(),
@@ -112,6 +112,11 @@ function profileWorlds(root) {
112
112
  if (token !== undefined)
113
113
  return token;
114
114
  }
115
+ }, session => {
116
+ if (!session.header.cwd)
117
+ return false;
118
+ const cwd = canonicalPath(session.header.cwd);
119
+ return [...worlds.rooms.values()].some(room => canonicalPath(room.path) === cwd);
115
120
  });
116
121
  return worlds;
117
122
  }
@@ -120,7 +125,7 @@ function profileWorlds(root) {
120
125
  * memory block, persona, world prompt, archive and life line come and go together. The switch is kept in
121
126
  * `<world>/world.json`, so it outlasts a restart.
122
127
  */
123
- export async function apply(ctx, config) {
128
+ export function apply(ctx, config) {
124
129
  const { root } = ctx;
125
130
  const { worldId } = config;
126
131
  if (!validWorldId(worldId))
@@ -154,6 +159,7 @@ export async function apply(ctx, config) {
154
159
  ctx.effect(() => () => photoStore?.close(), 'dsh-world album');
155
160
  // Her self-description lives in her room whether or not the life line runs; she writes it with her file tools.
156
161
  const selfFile = config.selfFile || join(worldDir, 'room', '我是谁.md');
162
+ const moodFile = join(roomDir, MOOD_FILE);
157
163
  const personaFile = config.personaFile || join(worldDir, 'persona.md');
158
164
  const worldPromptFile = config.worldPromptFile || join(worldDir, 'world-prompt.md');
159
165
  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 +201,10 @@ export async function apply(ctx, config) {
195
201
  async function startMemory(fresh) {
196
202
  if (memory || disposed)
197
203
  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
204
  try {
202
- await runtime.start({ fresh });
205
+ const prompt = { file: worldPromptFile, persona: personaFile, conversationsDir: join(worldDir, 'conversations'), names: names(), memoryTools: true, ...(config.life ? { life: options } : {}) };
206
+ memory = createWorldRuntime(ctx, { ...memoryConfig, selfFile, moodFile }, store, { prompt, names, isHome: id => isHome(id), archiveSession, inWorkspace, memory: memoryService }, power.memoryTurns, power.coldHours);
207
+ await memory.start({ fresh });
203
208
  faults.clear('memory');
204
209
  }
205
210
  catch (error) {
@@ -224,6 +229,7 @@ export async function apply(ctx, config) {
224
229
  });
225
230
  return () => {
226
231
  disposed = true;
232
+ memory?.cancelCatchUp();
227
233
  return changeWorld(async () => {
228
234
  try {
229
235
  await stopLifeLine?.();
@@ -234,21 +240,21 @@ export async function apply(ctx, config) {
234
240
  });
235
241
  };
236
242
  }, 'dsh-world memory line');
243
+ // Archive replay may outlast a host reload. Register all effects in this apply call.
237
244
  if (power.running())
238
- await changeWorld(() => startMemory(false));
245
+ lifecycle = startMemory(false);
239
246
  // The host's workspace service may come up after this plugin; what the first catch-up could not place is read then.
240
247
  ctx.inject(['workspaceRegistry'], injected => {
241
248
  void changeWorld(async () => { if (!disposed)
242
249
  await memory?.retryCatchUp(); }).catch(error => injected.logger.error(error));
243
250
  });
244
251
  // The console and the life line need the desktop host.
245
- ctx.inject(['sessionController', 'permissionPresets', 'webServer'], async (lifeCtx) => {
252
+ ctx.inject(['sessionController', 'permissionPresets', 'webServer'], lifeCtx => {
246
253
  const webServer = lifeCtx.webServer;
247
254
  const host = hostLife(lifeCtx);
248
255
  const configEditor = lifeCtx.get('configEditor');
249
256
  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; },
257
+ const swap = () => swapCompactionOnce({ enabled: config.replaceCompaction && !lifeCtx.get('agentPresets') && !hasAgentPresets(configEditor), profileDir: profileDir(), done: power.compactionSwapped, markDone: power.markCompactionSwapped,
252
258
  report: message => { faults.set('compaction-swap', message); lifeCtx.logger.warn(`dsh-world: ${message}`); } });
253
259
  const repair = async () => {
254
260
  const dir = profileDir();
@@ -256,25 +262,14 @@ export async function apply(ctx, config) {
256
262
  await repairCopiedPresets({ editor: configEditor, profileDir: dir, report: message => { faults.set('preset-repair', message); lifeCtx.logger.warn(`dsh-world: ${message}`); } });
257
263
  };
258
264
  // 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');
265
+ const editProfile = (edit) => worlds.profileEdits = worlds.profileEdits.then(edit, edit);
271
266
  const permissions = createWorkspacePermissions(lifeCtx, options.roomDir, power);
272
267
  // SnowLuma 的控制台在 OneBot 通道关闭时仍可用。
273
268
  const doors = createConsoleDoors({ worldDir, snowlumaHome: config.qqNative?.snowlumaHome ?? '' });
274
269
  const unregisterQq = webServer.register(qqRoute(prefix, config.allowedHosts, doors, () => qqNative?.status() ?? null, patch => qqNative?.update(patch) ?? null));
275
270
  lifeCtx.effect(() => () => unregisterQq(), 'dsh-world qq route');
276
271
  let life;
277
- const sdkAbort = new AbortController();
272
+ const hostAbort = new AbortController();
278
273
  const sdkAvailable = () => { try {
279
274
  import.meta.resolve('@snowluma/sdk');
280
275
  return true;
@@ -284,8 +279,7 @@ export async function apply(ctx, config) {
284
279
  return false;
285
280
  throw error;
286
281
  } };
287
- const qqSdk = createQqSdkInstaller({ available: sdkAvailable, profile: () => lifeCtx.get('profileContext'), signal: sdkAbort.signal });
288
- lifeCtx.effect(() => () => sdkAbort.abort(new Error('世界插件已卸载')), 'dsh-world SDK installation');
282
+ const qqSdk = createQqSdkInstaller({ available: sdkAvailable, profile: () => lifeCtx.get('profileContext'), signal: hostAbort.signal });
289
283
  let qqChange = 0;
290
284
  const homeApply = createHomeApply({
291
285
  ctx: lifeCtx,
@@ -315,7 +309,7 @@ export async function apply(ctx, config) {
315
309
  if (wechat || !config.wechat)
316
310
  return;
317
311
  await wechatClosing;
318
- if (wechat || life !== current || disposed || !power.running() || !power.wechatEnabled())
312
+ if (wechat || life !== current || disposed || hostAbort.signal.aborted || !power.running() || !power.wechatEnabled())
319
313
  return;
320
314
  const groupSessions = createChannelSessions({ ctx: lifeCtx, host, store, roomDir: options.roomDir, roomTitle: roomTitle(names()), agentPreset: config.agentPreset });
321
315
  channels = groupSessions;
@@ -351,7 +345,7 @@ export async function apply(ctx, config) {
351
345
  if (!sdkAvailable())
352
346
  throw new Error('QQ 缺少 SnowLuma SDK,请关闭再开启 QQ,按需安装依赖');
353
347
  const { createQqNativeModule } = await import("./ecosystem/qq-native/index.js");
354
- if (qqNative || life !== current || !power.running() || !power.qqEnabled())
348
+ if (qqNative || life !== current || disposed || hostAbort.signal.aborted || !power.running() || !power.qqEnabled())
355
349
  return;
356
350
  const groupSessions = createChannelSessions({ ctx: lifeCtx, host, store, roomDir: options.roomDir, roomTitle: roomTitle(names()), agentPreset: config.agentPreset });
357
351
  qqChannels = groupSessions;
@@ -405,32 +399,43 @@ export async function apply(ctx, config) {
405
399
  async function startLife(resumed) {
406
400
  if (!lifeStore || life)
407
401
  return;
402
+ let current;
403
+ const failed = async (error) => {
404
+ if (disposed || hostAbort.signal.aborted || life !== current)
405
+ return;
406
+ faults.set('life', `生活线没能启动:${errorText(error)}`);
407
+ lifeCtx.logger.error(error);
408
+ await stopLife();
409
+ };
408
410
  try {
409
411
  await lifeStop;
410
- if (disposed)
412
+ if (disposed || hostAbort.signal.aborted)
411
413
  return;
412
414
  const outlets = config.outlets.map(outlet => createOutlet(outlet, () => host.origin()));
413
415
  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())
416
+ 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
417
  homeApply.request(); } });
416
- life = current;
417
- isHome = current.isHome;
418
+ life = current = runtime;
419
+ isHome = runtime.isHome;
418
420
  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 });
421
+ bridge = createBridge({ ctx: lifeCtx, prefix, home: () => runtime.home(), inWorld: inWorldSession, outlets, origin: () => host.origin(), file: join(worldDir, 'bridge.json'), name: names().companion });
420
422
  bridge.start();
421
423
  }
422
424
  if (config.wechat && power.wechatEnabled())
423
- await startWechat(current);
425
+ await startWechat(runtime);
424
426
  if (config.qqNative?.enabled && power.qqEnabled())
425
- await startQqNative(current);
427
+ await startQqNative(runtime);
428
+ if (disposed || hostAbort.signal.aborted)
429
+ return;
426
430
  faults.clear('life');
427
- await current.start({ resumed });
431
+ const started = runtime.start({ resumed });
432
+ if (resumed)
433
+ await started;
434
+ else
435
+ void started.catch(error => changeWorld(() => failed(error))).finally(sources.invalidate).catch(error => lifeCtx.logger.error(error));
428
436
  }
429
437
  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);
438
+ await failed(error);
434
439
  }
435
440
  }
436
441
  function stopLife() {
@@ -444,14 +449,18 @@ export async function apply(ctx, config) {
444
449
  return lifeStop = Promise.all([lifeStop, closingWechat, homeApply.cancel()]).then(() => { });
445
450
  }
446
451
  stopLifeLine = stopLife;
447
- lifeCtx.effect(() => () => changeWorld(stopLife), 'dsh-world life line');
452
+ lifeCtx.effect(() => () => {
453
+ hostAbort.abort(new Error('世界插件已卸载'));
454
+ return changeWorld(stopLife);
455
+ }, 'dsh-world life line');
448
456
  // The host matches exact routes before the longest prefix, so this path never reaches the console.
449
457
  if (config.bridge)
450
458
  lifeCtx.effect(() => webServer.register(bridgeRoute(prefix, () => bridge, config.allowedHosts)), 'dsh-world bridge route');
451
459
  if (config.bridge)
452
460
  lifeCtx.effect(() => webServer.register(compactRoute(prefix, () => bridge, () => !power.running() || !life ? '请先启动世界生活线' : homeApply.request(), config.allowedHosts)), 'dsh-world compact route');
453
461
  // 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,
462
+ 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,
463
+ compactionPreset: () => configEditor ? compactionPresetOverride(configEditor, config.agentPreset, profileDir()) : null,
455
464
  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
465
  const actions = {
457
466
  start: () => changeWorld(async () => {
@@ -478,6 +487,12 @@ export async function apply(ctx, config) {
478
487
  }
479
488
  }),
480
489
  applyHome: () => !power.running() || !life ? '请先启动世界生活线' : homeApply.request(),
490
+ restoreCompactionPreset: () => editProfile(async () => {
491
+ const dir = profileDir();
492
+ if (!configEditor || !dir)
493
+ throw new Error('宿主配置编辑服务不可用');
494
+ await restoreCompactionPreset(configEditor, config.agentPreset, dir);
495
+ }).finally(sources.invalidate),
481
496
  prompts: () => ({
482
497
  persona: readPersona(personaFile),
483
498
  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 +514,7 @@ export async function apply(ctx, config) {
499
514
  if (patch.qq === true) {
500
515
  try {
501
516
  restartRequired = await qqSdk.ensure();
502
- sdkAbort.signal.throwIfAborted();
517
+ hostAbort.signal.throwIfAborted();
503
518
  faults.clear('qq-sdk');
504
519
  }
505
520
  catch (error) {
@@ -562,8 +577,24 @@ export async function apply(ctx, config) {
562
577
  }
563
578
  };
564
579
  }, 'dsh-world world list');
565
- if (power.running())
566
- await changeWorld(async () => { if (!disposed && power.running())
567
- await startLife(false); });
580
+ const ready = () => {
581
+ if (disposed || hostAbort.signal.aborted)
582
+ return;
583
+ void editProfile(async () => { try {
584
+ swap();
585
+ }
586
+ finally {
587
+ await repair();
588
+ } }).catch(error => lifeCtx.logger.error(error));
589
+ if (power.running())
590
+ void changeWorld(async () => { if (power.running())
591
+ await startLife(false); }).catch(error => lifeCtx.logger.error(error));
592
+ };
593
+ // Home restoration and profile edits can call host services that wait for boot to finish.
594
+ const appReady = lifeCtx.get('appReady');
595
+ if (appReady)
596
+ lifeCtx.effect(() => appReady.onReady(ready), 'dsh-world host ready');
597
+ else
598
+ ready();
568
599
  });
569
600
  }
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);