dsh-world 0.7.3 → 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.
- package/CHANGELOG.md +52 -0
- package/NOTES.md +37 -17
- package/README.md +14 -7
- package/client/index.js +37 -2
- package/lib/abortable.d.ts +1 -0
- package/lib/abortable.js +17 -0
- package/lib/compaction.js +2 -2
- package/lib/compactionSwap.d.ts +23 -14
- package/lib/compactionSwap.js +90 -36
- package/lib/console/homeApply.js +1 -12
- package/lib/console/routes.d.ts +1 -0
- package/lib/console/routes.js +10 -0
- package/lib/console/snapshot.d.ts +4 -0
- package/lib/console/snapshot.js +3 -0
- package/lib/ecosystem/bridge/bridge.d.ts +2 -2
- package/lib/ecosystem/bridge/bridge.js +24 -11
- package/lib/ecosystem/qq-native/home.d.ts +2 -1
- package/lib/ecosystem/qq-native/home.js +6 -2
- package/lib/ecosystem/qq-native/images.d.ts +9 -0
- package/lib/ecosystem/qq-native/images.js +69 -0
- package/lib/ecosystem/qq-native/index.d.ts +1 -0
- package/lib/ecosystem/qq-native/index.js +8 -2
- package/lib/ecosystem/qq-native/snowluma.d.ts +1 -0
- package/lib/ecosystem/qq-native/snowluma.js +13 -4
- package/lib/ecosystem/shared/turn.d.ts +3 -0
- package/lib/ecosystem/shared/turn.js +9 -2
- package/lib/ecosystem/wechat/home.d.ts +3 -0
- package/lib/ecosystem/wechat/home.js +12 -4
- package/lib/ecosystem/wechat/index.js +3 -1
- package/lib/ecosystem/wechat/supervisor.d.ts +1 -1
- package/lib/ecosystem/wechat/supervisor.js +5 -1
- package/lib/hostContract.d.ts +6 -0
- package/lib/index.d.ts +1 -1
- package/lib/index.js +85 -47
- package/lib/life/home.js +8 -2
- package/lib/life/photoTools.js +60 -26
- package/lib/life/runtime.js +2 -0
- package/lib/memoryTools.d.ts +1 -1
- package/lib/memoryTools.js +1 -1
- package/lib/mood.d.ts +57 -0
- package/lib/mood.js +95 -0
- package/lib/moodTools.d.ts +6 -0
- package/lib/moodTools.js +30 -0
- package/lib/persona.js +7 -0
- package/lib/promptSection.d.ts +9 -13
- package/lib/promptSection.js +63 -80
- package/lib/runtime.d.ts +21 -2
- package/lib/runtime.js +148 -39
- package/lib/self.d.ts +1 -1
- package/lib/self.js +1 -1
- package/lib/sourceArchive.d.ts +1 -5
- package/lib/sourceArchive.js +31 -14
- package/lib/types.d.ts +2 -0
- package/lib/worldScope.d.ts +2 -4
- package/lib/worldScope.js +6 -6
- package/package.json +1 -1
- package/src/ecosystem/wechat/windows/README.md +5 -3
- package/src/ecosystem/wechat/windows/adapter.py +23 -2
- package/src/ecosystem/wechat/windows/engine/NOTICE.md +6 -0
- package/src/ecosystem/wechat/windows/engine/profiles.json +28 -0
- package/src/ecosystem/wechat/windows/sender.py +6 -2
- package/templates/world-prompt.md +6 -3
|
@@ -5,6 +5,9 @@ import { askTurn, createChannelQueue } from "../shared/turn.js";
|
|
|
5
5
|
import { incomingText } from "./messages.js";
|
|
6
6
|
import { admit } from "../../worldScope.js";
|
|
7
7
|
export const WECHAT_REPLY_TIMEOUT_MS = 3 * 60_000;
|
|
8
|
+
/** Ran out of time before her home took the words in: nothing was handed over, so asking again later repeats nothing. */
|
|
9
|
+
export class WechatHomeBusy extends Error {
|
|
10
|
+
}
|
|
8
11
|
/** One home, serialized channel requests; each caller receives only its own final answer. */
|
|
9
12
|
export function createWechatHome(deps) {
|
|
10
13
|
const queue = createChannelQueue('WeChat', { limit: 32, timeoutMs: WECHAT_REPLY_TIMEOUT_MS, timers: deps.timers });
|
|
@@ -14,13 +17,16 @@ export function createWechatHome(deps) {
|
|
|
14
17
|
const media = channelMedia(suppliedMedia, identity);
|
|
15
18
|
const reference = channelReference(suppliedReference, identity);
|
|
16
19
|
return queue.run(async (cancelled) => {
|
|
20
|
+
// Until the words are handed over, running out of time only means she was busy (#busy).
|
|
21
|
+
const handedOver = cancelled.catch((error) => { throw new WechatHomeBusy(error.message, { cause: error }); });
|
|
22
|
+
handedOver.catch(() => { });
|
|
17
23
|
// Checked again after every wait: the session may leave her world meanwhile.
|
|
18
|
-
const agent = admit(deps.inWorld, await Promise.race([deps.home(identity),
|
|
19
|
-
await Promise.race([agent.whenIdle(),
|
|
24
|
+
const agent = admit(deps.inWorld, await Promise.race([deps.home(identity), handedOver]));
|
|
25
|
+
await Promise.race([agent.whenIdle(), handedOver]);
|
|
20
26
|
admit(deps.inWorld, agent);
|
|
21
27
|
if ((reference?.image || [...context, ...media].some(message => message.image || message.reference?.image)) && !deps.images)
|
|
22
28
|
throw new Error('Image admission is unavailable');
|
|
23
|
-
const images = await Promise.race([deps.images?.(identity, [...context, ...media], reference) ?? Promise.resolve([]),
|
|
29
|
+
const images = await Promise.race([deps.images?.(identity, [...context, ...media], reference) ?? Promise.resolve([]), handedOver]);
|
|
24
30
|
queue.alive();
|
|
25
31
|
const content = incomingText(text, reference);
|
|
26
32
|
const source = content ? { kind: 'user', identity } : { kind: 'dsh-world-channel-context', form: 'recall' };
|
|
@@ -34,7 +40,9 @@ export function createWechatHome(deps) {
|
|
|
34
40
|
const instructions = parts.length || images.length
|
|
35
41
|
? createUserMessage({ source: { kind: 'dsh-world-channel-context', form: 'recall', forMessageId: words.id }, content: [...(parts.length ? [{ type: 'text', text: parts.join('\n') }] : []), ...images] })
|
|
36
42
|
: undefined;
|
|
37
|
-
|
|
43
|
+
// What she sends to this chat herself is her answer; the rest of her turn is not this request's to wait for.
|
|
44
|
+
const answered = (sent) => sent.kind === 'dsh-world-wechat-outgoing' && sent.identity.conversationId === identity.conversationId;
|
|
45
|
+
const reply = await askTurn(deps.ctx, agent, words, { name: 'WeChat', context: instructions, cancelled, inWorld: deps.inWorld, answered });
|
|
38
46
|
queue.alive();
|
|
39
47
|
return { id: words.id, text: reply };
|
|
40
48
|
});
|
|
@@ -3,7 +3,7 @@ import { readFileSync, rmSync } from 'node:fs';
|
|
|
3
3
|
import { jsonObject, knownHost, readBody, sendJson } from "../../http.js";
|
|
4
4
|
import { speakerIdentity } from "../shared/identity.js";
|
|
5
5
|
import { durableWrite } from "../../life/lifeStore.js";
|
|
6
|
-
import { createWechatHome } from "./home.js";
|
|
6
|
+
import { createWechatHome, WechatHomeBusy } from "./home.js";
|
|
7
7
|
import { channelContext, channelMedia, channelReference } from "../shared/context.js";
|
|
8
8
|
import { admitContextImages } from "./images.js";
|
|
9
9
|
import { dirname, join } from 'node:path';
|
|
@@ -173,6 +173,8 @@ export function createWechatModule(deps) {
|
|
|
173
173
|
return { status: 200, body: { accepted: true, ...(await home.ask(text, identity, context, media, reference)) } };
|
|
174
174
|
}
|
|
175
175
|
catch (error) {
|
|
176
|
+
if (error instanceof WechatHomeBusy)
|
|
177
|
+
return { status: 409, body: { error: 'home busy; message not taken in, ask again later' } };
|
|
176
178
|
deps.ctx.logger.warn('dsh-world WeChat request failed:', error);
|
|
177
179
|
return { status: 503, body: { error: 'home request failed; delivery must be checked before retrying' } };
|
|
178
180
|
}
|
|
@@ -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.
|
|
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.
|
|
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/hostContract.d.ts
CHANGED
|
@@ -23,6 +23,12 @@ declare module '@deepseek-ai/dsh-llm' {
|
|
|
23
23
|
'dsh-world-life': {
|
|
24
24
|
kind: 'dsh-world-life';
|
|
25
25
|
};
|
|
26
|
+
/** 她在 mood.md 里写的心情值:快照,不是谁说的话,不进归档。 */
|
|
27
|
+
'dsh-world-mood': {
|
|
28
|
+
kind: 'dsh-world-mood';
|
|
29
|
+
form: 'snapshot';
|
|
30
|
+
worldId: string;
|
|
31
|
+
};
|
|
26
32
|
'dsh-world-channel-context': {
|
|
27
33
|
kind: 'dsh-world-channel-context';
|
|
28
34
|
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):
|
|
207
|
+
export declare function apply(ctx: Context, config: Config): void;
|
package/lib/index.js
CHANGED
|
@@ -13,13 +13,14 @@ 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 {
|
|
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";
|
|
20
20
|
import { createLifeRuntime } from "./life/runtime.js";
|
|
21
21
|
import { createOutlet } from "./ecosystem/shared/outlets.js";
|
|
22
22
|
import { readPersona, writePersona } from "./persona.js";
|
|
23
|
+
import { MOOD_FILE } from "./mood.js";
|
|
23
24
|
import { qqRoute } from "./ecosystem/qq/route.js";
|
|
24
25
|
import { createConsoleDoors, discoverSnowlumaHome } from "./ecosystem/qq/panel.js";
|
|
25
26
|
import { createMemory } from "./memory.js";
|
|
@@ -48,7 +49,7 @@ export const Config = z.object({
|
|
|
48
49
|
worldId: z.string().default('default'), agentPreset: z.string().default('standard'), timeZone: z.string().default(systemTimeZone),
|
|
49
50
|
companionName: z.string(), partnerName: z.string(),
|
|
50
51
|
archiveScope: z.union([z.const('home').description('仅家会话'), z.const('workspace').description('家所在工作区'), z.transform(z.const('world').hidden(), () => 'workspace').hidden()]).default('workspace').description('记忆归档范围,修改后重启生效'),
|
|
51
|
-
//
|
|
52
|
+
// Only a profile-level stock row can be switched automatically. Session presets own their compaction.
|
|
52
53
|
replaceCompaction: z.boolean().default(true),
|
|
53
54
|
life: z.boolean().default(true), diaryDir: z.string(), fallbackWakeTime: z.string().pattern(CLOCK_TIME).default('09:00'),
|
|
54
55
|
selfFile: z.string(), worldPromptFile: z.string(), alarmTemplateFile: z.string(), personaFile: z.string(),
|
|
@@ -101,7 +102,7 @@ function profileWorlds(root) {
|
|
|
101
102
|
const existing = root.get('dshWorldProfile');
|
|
102
103
|
if (existing)
|
|
103
104
|
return existing;
|
|
104
|
-
const worlds = { rooms: new Map(), consoles: new Map(),
|
|
105
|
+
const worlds = { rooms: new Map(), consoles: new Map(), profileEdits: Promise.resolve() };
|
|
105
106
|
root.provide('dshWorldProfile', worlds);
|
|
106
107
|
guardWorldContext(root, (session, worldId) => {
|
|
107
108
|
if (worldId !== undefined)
|
|
@@ -111,6 +112,11 @@ function profileWorlds(root) {
|
|
|
111
112
|
if (token !== undefined)
|
|
112
113
|
return token;
|
|
113
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);
|
|
114
120
|
});
|
|
115
121
|
return worlds;
|
|
116
122
|
}
|
|
@@ -119,7 +125,7 @@ function profileWorlds(root) {
|
|
|
119
125
|
* memory block, persona, world prompt, archive and life line come and go together. The switch is kept in
|
|
120
126
|
* `<world>/world.json`, so it outlasts a restart.
|
|
121
127
|
*/
|
|
122
|
-
export
|
|
128
|
+
export function apply(ctx, config) {
|
|
123
129
|
const { root } = ctx;
|
|
124
130
|
const { worldId } = config;
|
|
125
131
|
if (!validWorldId(worldId))
|
|
@@ -153,6 +159,7 @@ export async function apply(ctx, config) {
|
|
|
153
159
|
ctx.effect(() => () => photoStore?.close(), 'dsh-world album');
|
|
154
160
|
// Her self-description lives in her room whether or not the life line runs; she writes it with her file tools.
|
|
155
161
|
const selfFile = config.selfFile || join(worldDir, 'room', '我是谁.md');
|
|
162
|
+
const moodFile = join(roomDir, MOOD_FILE);
|
|
156
163
|
const personaFile = config.personaFile || join(worldDir, 'persona.md');
|
|
157
164
|
const worldPromptFile = config.worldPromptFile || join(worldDir, 'world-prompt.md');
|
|
158
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') };
|
|
@@ -194,11 +201,10 @@ export async function apply(ctx, config) {
|
|
|
194
201
|
async function startMemory(fresh) {
|
|
195
202
|
if (memory || disposed)
|
|
196
203
|
return;
|
|
197
|
-
const prompt = { file: worldPromptFile, persona: personaFile, conversationsDir: join(worldDir, 'conversations'), names: names(), memoryTools: true, ...(config.life ? { life: options } : {}) };
|
|
198
|
-
const runtime = createWorldRuntime(ctx, { ...memoryConfig, selfFile }, store, { prompt, names, isHome: id => isHome(id), archiveSession, inWorkspace, memory: memoryService }, power.memoryTurns, power.coldHours);
|
|
199
|
-
memory = runtime;
|
|
200
204
|
try {
|
|
201
|
-
|
|
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 });
|
|
202
208
|
faults.clear('memory');
|
|
203
209
|
}
|
|
204
210
|
catch (error) {
|
|
@@ -223,6 +229,7 @@ export async function apply(ctx, config) {
|
|
|
223
229
|
});
|
|
224
230
|
return () => {
|
|
225
231
|
disposed = true;
|
|
232
|
+
memory?.cancelCatchUp();
|
|
226
233
|
return changeWorld(async () => {
|
|
227
234
|
try {
|
|
228
235
|
await stopLifeLine?.();
|
|
@@ -233,41 +240,36 @@ export async function apply(ctx, config) {
|
|
|
233
240
|
});
|
|
234
241
|
};
|
|
235
242
|
}, 'dsh-world memory line');
|
|
243
|
+
// Archive replay may outlast a host reload. Register all effects in this apply call.
|
|
236
244
|
if (power.running())
|
|
237
|
-
|
|
245
|
+
lifecycle = startMemory(false);
|
|
238
246
|
// The host's workspace service may come up after this plugin; what the first catch-up could not place is read then.
|
|
239
247
|
ctx.inject(['workspaceRegistry'], injected => {
|
|
240
248
|
void changeWorld(async () => { if (!disposed)
|
|
241
249
|
await memory?.retryCatchUp(); }).catch(error => injected.logger.error(error));
|
|
242
250
|
});
|
|
243
251
|
// The console and the life line need the desktop host.
|
|
244
|
-
ctx.inject(['sessionController', 'permissionPresets', 'webServer'],
|
|
252
|
+
ctx.inject(['sessionController', 'permissionPresets', 'webServer'], lifeCtx => {
|
|
245
253
|
const webServer = lifeCtx.webServer;
|
|
246
254
|
const host = hostLife(lifeCtx);
|
|
247
255
|
const configEditor = lifeCtx.get('configEditor');
|
|
248
|
-
const
|
|
249
|
-
|
|
256
|
+
const profileDir = () => lifeCtx.get('profileContext')?.dir;
|
|
257
|
+
const swap = () => swapCompactionOnce({ enabled: config.replaceCompaction && !lifeCtx.get('agentPresets') && !hasAgentPresets(configEditor), profileDir: profileDir(), done: power.compactionSwapped, markDone: power.markCompactionSwapped,
|
|
250
258
|
report: message => { faults.set('compaction-swap', message); lifeCtx.logger.warn(`dsh-world: ${message}`); } });
|
|
259
|
+
const repair = async () => {
|
|
260
|
+
const dir = profileDir();
|
|
261
|
+
if (configEditor && dir)
|
|
262
|
+
await repairCopiedPresets({ editor: configEditor, profileDir: dir, report: message => { faults.set('preset-repair', message); lifeCtx.logger.warn(`dsh-world: ${message}`); } });
|
|
263
|
+
};
|
|
251
264
|
// Different worlds may edit the same profile or preset on startup.
|
|
252
|
-
const
|
|
253
|
-
// The preset row the editor rewrites is active only once the host has finished loading.
|
|
254
|
-
const appReady = lifeCtx.get('appReady');
|
|
255
|
-
if (!appReady)
|
|
256
|
-
void swapCompaction();
|
|
257
|
-
else
|
|
258
|
-
lifeCtx.effect(() => {
|
|
259
|
-
let closed = false;
|
|
260
|
-
const cancel = appReady.onReady(() => { if (!closed)
|
|
261
|
-
void swapCompaction(); });
|
|
262
|
-
return () => { closed = true; cancel(); };
|
|
263
|
-
}, 'dsh-world compaction swap');
|
|
265
|
+
const editProfile = (edit) => worlds.profileEdits = worlds.profileEdits.then(edit, edit);
|
|
264
266
|
const permissions = createWorkspacePermissions(lifeCtx, options.roomDir, power);
|
|
265
267
|
// SnowLuma 的控制台在 OneBot 通道关闭时仍可用。
|
|
266
268
|
const doors = createConsoleDoors({ worldDir, snowlumaHome: config.qqNative?.snowlumaHome ?? '' });
|
|
267
269
|
const unregisterQq = webServer.register(qqRoute(prefix, config.allowedHosts, doors, () => qqNative?.status() ?? null, patch => qqNative?.update(patch) ?? null));
|
|
268
270
|
lifeCtx.effect(() => () => unregisterQq(), 'dsh-world qq route');
|
|
269
271
|
let life;
|
|
270
|
-
const
|
|
272
|
+
const hostAbort = new AbortController();
|
|
271
273
|
const sdkAvailable = () => { try {
|
|
272
274
|
import.meta.resolve('@snowluma/sdk');
|
|
273
275
|
return true;
|
|
@@ -277,8 +279,7 @@ export async function apply(ctx, config) {
|
|
|
277
279
|
return false;
|
|
278
280
|
throw error;
|
|
279
281
|
} };
|
|
280
|
-
const qqSdk = createQqSdkInstaller({ available: sdkAvailable, profile: () => lifeCtx.get('profileContext'), signal:
|
|
281
|
-
lifeCtx.effect(() => () => sdkAbort.abort(new Error('世界插件已卸载')), 'dsh-world SDK installation');
|
|
282
|
+
const qqSdk = createQqSdkInstaller({ available: sdkAvailable, profile: () => lifeCtx.get('profileContext'), signal: hostAbort.signal });
|
|
282
283
|
let qqChange = 0;
|
|
283
284
|
const homeApply = createHomeApply({
|
|
284
285
|
ctx: lifeCtx,
|
|
@@ -308,7 +309,7 @@ export async function apply(ctx, config) {
|
|
|
308
309
|
if (wechat || !config.wechat)
|
|
309
310
|
return;
|
|
310
311
|
await wechatClosing;
|
|
311
|
-
if (wechat || life !== current || disposed || !power.running() || !power.wechatEnabled())
|
|
312
|
+
if (wechat || life !== current || disposed || hostAbort.signal.aborted || !power.running() || !power.wechatEnabled())
|
|
312
313
|
return;
|
|
313
314
|
const groupSessions = createChannelSessions({ ctx: lifeCtx, host, store, roomDir: options.roomDir, roomTitle: roomTitle(names()), agentPreset: config.agentPreset });
|
|
314
315
|
channels = groupSessions;
|
|
@@ -344,7 +345,7 @@ export async function apply(ctx, config) {
|
|
|
344
345
|
if (!sdkAvailable())
|
|
345
346
|
throw new Error('QQ 缺少 SnowLuma SDK,请关闭再开启 QQ,按需安装依赖');
|
|
346
347
|
const { createQqNativeModule } = await import("./ecosystem/qq-native/index.js");
|
|
347
|
-
if (qqNative || life !== current || !power.running() || !power.qqEnabled())
|
|
348
|
+
if (qqNative || life !== current || disposed || hostAbort.signal.aborted || !power.running() || !power.qqEnabled())
|
|
348
349
|
return;
|
|
349
350
|
const groupSessions = createChannelSessions({ ctx: lifeCtx, host, store, roomDir: options.roomDir, roomTitle: roomTitle(names()), agentPreset: config.agentPreset });
|
|
350
351
|
qqChannels = groupSessions;
|
|
@@ -398,32 +399,43 @@ export async function apply(ctx, config) {
|
|
|
398
399
|
async function startLife(resumed) {
|
|
399
400
|
if (!lifeStore || life)
|
|
400
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
|
+
};
|
|
401
410
|
try {
|
|
402
411
|
await lifeStop;
|
|
403
|
-
if (disposed)
|
|
412
|
+
if (disposed || hostAbort.signal.aborted)
|
|
404
413
|
return;
|
|
405
414
|
const outlets = config.outlets.map(outlet => createOutlet(outlet, () => host.origin()));
|
|
406
415
|
const notifier = { ...(config.toast && toastSupported() ? { toast: windowsToast(config.toastAppId || undefined) } : {}), outlets };
|
|
407
|
-
const
|
|
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())
|
|
408
417
|
homeApply.request(); } });
|
|
409
|
-
life = current;
|
|
410
|
-
isHome =
|
|
418
|
+
life = current = runtime;
|
|
419
|
+
isHome = runtime.isHome;
|
|
411
420
|
if (config.bridge) {
|
|
412
|
-
bridge = createBridge({ ctx: lifeCtx, prefix, home: () =>
|
|
421
|
+
bridge = createBridge({ ctx: lifeCtx, prefix, home: () => runtime.home(), inWorld: inWorldSession, outlets, origin: () => host.origin(), file: join(worldDir, 'bridge.json'), name: names().companion });
|
|
413
422
|
bridge.start();
|
|
414
423
|
}
|
|
415
424
|
if (config.wechat && power.wechatEnabled())
|
|
416
|
-
await startWechat(
|
|
425
|
+
await startWechat(runtime);
|
|
417
426
|
if (config.qqNative?.enabled && power.qqEnabled())
|
|
418
|
-
await startQqNative(
|
|
427
|
+
await startQqNative(runtime);
|
|
428
|
+
if (disposed || hostAbort.signal.aborted)
|
|
429
|
+
return;
|
|
419
430
|
faults.clear('life');
|
|
420
|
-
|
|
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));
|
|
421
436
|
}
|
|
422
437
|
catch (error) {
|
|
423
|
-
|
|
424
|
-
await stopLife();
|
|
425
|
-
faults.set('life', `生活线没能启动:${errorText(error)}`);
|
|
426
|
-
lifeCtx.logger.error(error);
|
|
438
|
+
await failed(error);
|
|
427
439
|
}
|
|
428
440
|
}
|
|
429
441
|
function stopLife() {
|
|
@@ -437,14 +449,18 @@ export async function apply(ctx, config) {
|
|
|
437
449
|
return lifeStop = Promise.all([lifeStop, closingWechat, homeApply.cancel()]).then(() => { });
|
|
438
450
|
}
|
|
439
451
|
stopLifeLine = stopLife;
|
|
440
|
-
lifeCtx.effect(() => () =>
|
|
452
|
+
lifeCtx.effect(() => () => {
|
|
453
|
+
hostAbort.abort(new Error('世界插件已卸载'));
|
|
454
|
+
return changeWorld(stopLife);
|
|
455
|
+
}, 'dsh-world life line');
|
|
441
456
|
// The host matches exact routes before the longest prefix, so this path never reaches the console.
|
|
442
457
|
if (config.bridge)
|
|
443
458
|
lifeCtx.effect(() => webServer.register(bridgeRoute(prefix, () => bridge, config.allowedHosts)), 'dsh-world bridge route');
|
|
444
459
|
if (config.bridge)
|
|
445
460
|
lifeCtx.effect(() => webServer.register(compactRoute(prefix, () => bridge, () => !power.running() || !life ? '请先启动世界生活线' : homeApply.request(), config.allowedHosts)), 'dsh-world compact route');
|
|
446
461
|
// Her album lives in her room, so the console shows it whether or not the life line is running.
|
|
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,
|
|
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,
|
|
448
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()] });
|
|
449
465
|
const actions = {
|
|
450
466
|
start: () => changeWorld(async () => {
|
|
@@ -471,6 +487,12 @@ export async function apply(ctx, config) {
|
|
|
471
487
|
}
|
|
472
488
|
}),
|
|
473
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),
|
|
474
496
|
prompts: () => ({
|
|
475
497
|
persona: readPersona(personaFile),
|
|
476
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 },
|
|
@@ -492,7 +514,7 @@ export async function apply(ctx, config) {
|
|
|
492
514
|
if (patch.qq === true) {
|
|
493
515
|
try {
|
|
494
516
|
restartRequired = await qqSdk.ensure();
|
|
495
|
-
|
|
517
|
+
hostAbort.signal.throwIfAborted();
|
|
496
518
|
faults.clear('qq-sdk');
|
|
497
519
|
}
|
|
498
520
|
catch (error) {
|
|
@@ -555,8 +577,24 @@ export async function apply(ctx, config) {
|
|
|
555
577
|
}
|
|
556
578
|
};
|
|
557
579
|
}, 'dsh-world world list');
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
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();
|
|
561
599
|
});
|
|
562
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
|
-
|
|
58
|
-
throw new Error('生活线已停止');
|
|
64
|
+
assertRunning();
|
|
59
65
|
untitled = sessionId;
|
|
60
66
|
firstTurn = sessionId;
|
|
61
67
|
deps.moveIn(sessionId);
|
package/lib/life/photoTools.js
CHANGED
|
@@ -1,44 +1,78 @@
|
|
|
1
|
-
import {
|
|
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
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
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
|
-
|
|
13
|
-
|
|
14
|
-
|
|
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
|
-
|
|
22
|
-
|
|
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: '
|
|
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
|
-
|
|
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));
|
package/lib/life/runtime.js
CHANGED
|
@@ -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.
|
package/lib/memoryTools.d.ts
CHANGED
|
@@ -11,7 +11,7 @@ import type { MemoryService } from './memory.ts';
|
|
|
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
13
|
/**
|
|
14
|
-
* Gives world sessions their tools (long-term memory), whatever the life line does: a session has them
|
|
14
|
+
* Gives world sessions their tools (long-term memory, her mood), whatever the life line does: a session has them
|
|
15
15
|
* while it is in her world, and loses them when it leaves. A registration that fails is a fault, never a broken agent.
|
|
16
16
|
*/
|
|
17
17
|
export declare function createWorldToolRegistry(deps: {
|
package/lib/memoryTools.js
CHANGED
|
@@ -54,7 +54,7 @@ export function memoryTools(service, inside) {
|
|
|
54
54
|
];
|
|
55
55
|
}
|
|
56
56
|
/**
|
|
57
|
-
* Gives world sessions their tools (long-term memory), whatever the life line does: a session has them
|
|
57
|
+
* Gives world sessions their tools (long-term memory, her mood), whatever the life line does: a session has them
|
|
58
58
|
* while it is in her world, and loses them when it leaves. A registration that fails is a fault, never a broken agent.
|
|
59
59
|
*/
|
|
60
60
|
export function createWorldToolRegistry(deps) {
|