dsh-world 0.7.0 → 0.7.1
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 +18 -0
- package/INSTALL.md +314 -314
- package/LICENSE +21 -21
- package/NOTES.md +14 -3
- package/README.md +5 -4
- package/client/index.js +47 -2
- package/cordis.patch.yml +6 -6
- package/lib/archive.d.ts +3 -1
- package/lib/archive.js +6 -4
- package/lib/console/routes.d.ts +5 -0
- package/lib/console/routes.js +15 -4
- package/lib/console/snapshot.d.ts +5 -0
- package/lib/console/snapshot.js +2 -1
- package/lib/ecosystem/qq/route.d.ts +2 -1
- package/lib/ecosystem/qq/route.js +10 -2
- package/lib/ecosystem/qq-native/batch.d.ts +2 -0
- package/lib/ecosystem/qq-native/batch.js +3 -1
- package/lib/ecosystem/qq-native/index.d.ts +2 -0
- package/lib/ecosystem/qq-native/index.js +4 -0
- package/lib/ecosystem/qq-native/replies.d.ts +6 -1
- package/lib/ecosystem/qq-native/replies.js +19 -1
- package/lib/ecosystem/shared/context.d.ts +1 -1
- package/lib/ecosystem/shared/context.js +1 -1
- package/lib/ecosystem/shared/identity.d.ts +12 -0
- package/lib/ecosystem/shared/identity.js +17 -1
- package/lib/ecosystem/shared/turn.d.ts +8 -5
- package/lib/ecosystem/shared/turn.js +16 -17
- package/lib/ecosystem/wechat/archive.d.ts +2 -0
- package/lib/ecosystem/wechat/archive.js +3 -1
- package/lib/ecosystem/wechat/home.js +9 -4
- package/lib/ecosystem/wechat/messages.d.ts +11 -0
- package/lib/ecosystem/wechat/messages.js +9 -1
- package/lib/ecosystem/wechat/sending.js +36 -9
- package/lib/ecosystem/wechat/supervisor.d.ts +11 -2
- package/lib/ecosystem/wechat/supervisor.js +90 -9
- package/lib/history.d.ts +6 -4
- package/lib/history.js +61 -12
- package/lib/index.js +7 -5
- package/lib/life/activity.d.ts +2 -0
- package/lib/life/activity.js +1 -1
- package/lib/life/alarm.d.ts +12 -4
- package/lib/life/alarm.js +21 -6
- package/lib/life/diary.d.ts +6 -0
- package/lib/life/diary.js +23 -2
- package/lib/life/runtime.d.ts +1 -0
- package/lib/life/runtime.js +57 -9
- package/lib/life/toolRegistry.d.ts +4 -3
- package/lib/life/toolRegistry.js +13 -3
- package/lib/life/types.d.ts +6 -1
- package/lib/memory.js +1 -4
- package/lib/memoryFiles.d.ts +1 -4
- package/lib/memoryFiles.js +18 -43
- package/lib/memoryStore.d.ts +1 -3
- package/lib/memoryStore.js +1 -1
- package/lib/memoryTools.js +2 -2
- package/lib/runtime.js +44 -89
- package/lib/sourceArchive.js +3 -4
- package/lib/store.d.ts +1 -1
- package/lib/store.js +1 -1
- package/lib/types.d.ts +1 -4
- package/lib/worldPrompt.js +1 -1
- package/lib/worldSwitch.d.ts +9 -1
- package/lib/worldSwitch.js +14 -1
- package/package.json +1 -1
- package/scripts/compact-home.mjs +29 -29
- package/scripts/enable-tool-free-compaction.ps1 +33 -33
- package/scripts/import-stickers.mjs +17 -17
- package/scripts/update-world.mjs +2 -2
- package/src/ecosystem/wechat/windows/README.md +2 -2
- package/src/ecosystem/wechat/windows/adapter.py +6 -0
- package/src/ecosystem/wechat/windows/engine/build.ps1 +8 -2
- package/src/ecosystem/wechat/windows/engine/profiles.json +114 -114
- package/src/ecosystem/wechat/windows/presence.py +109 -109
- package/src/ecosystem/wechat/windows/sender.py +17 -5
- package/templates/alarm.md +1 -1
package/lib/memoryFiles.js
CHANGED
|
@@ -4,7 +4,6 @@ import { errorText } from "./faults.js";
|
|
|
4
4
|
import { formatLocalTime } from "./timeContext.js";
|
|
5
5
|
import { extractLinks, fileRef, localDayStart } from "./memoryStore.js";
|
|
6
6
|
const MAX_FILE_BYTES = 2 * 1024 * 1024, MAX_FILES_PER_DIR = 2000;
|
|
7
|
-
const DIR_DEPTH = { diary: 1, knowledge: 4 };
|
|
8
7
|
const sameFile = (a, b) => a.size === b.size && a.mtimeMs === b.mtimeMs;
|
|
9
8
|
/** Windows compares paths without case. */
|
|
10
9
|
const normalized = (path) => process.platform === 'win32' ? path.toLowerCase() : path;
|
|
@@ -36,8 +35,8 @@ export async function readStable(path, between) {
|
|
|
36
35
|
return { kind: 'failed', message: error instanceof TypeError && /encoded data|decode/i.test(error.message) ? '不是有效的 UTF-8 文本' : errorText(error) };
|
|
37
36
|
}
|
|
38
37
|
}
|
|
39
|
-
/**
|
|
40
|
-
async function listDirectory(root
|
|
38
|
+
/** The diary's own markdown and text files, one level: real paths must stay inside it, so links cannot lead out, and nothing is followed from file contents. */
|
|
39
|
+
async function listDirectory(root) {
|
|
41
40
|
let realRoot;
|
|
42
41
|
try {
|
|
43
42
|
realRoot = await realpath(root);
|
|
@@ -46,16 +45,11 @@ async function listDirectory(root, depth) {
|
|
|
46
45
|
return error.code === 'ENOENT' ? { kind: 'missing' } : { kind: 'failed', message: errorText(error) };
|
|
47
46
|
}
|
|
48
47
|
const files = [];
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
if (!within(realRoot, real) || visited.has(normalized(real)))
|
|
53
|
-
return;
|
|
54
|
-
visited.add(normalized(real));
|
|
55
|
-
for (const entry of await readdir(directory, { withFileTypes: true })) {
|
|
56
|
-
if (entry.name.startsWith('.'))
|
|
48
|
+
try {
|
|
49
|
+
for (const entry of await readdir(root, { withFileTypes: true })) {
|
|
50
|
+
if (entry.name.startsWith('.') || !/\.(md|txt)$/i.test(entry.name))
|
|
57
51
|
continue;
|
|
58
|
-
const path = join(
|
|
52
|
+
const path = join(root, entry.name);
|
|
59
53
|
let target;
|
|
60
54
|
try {
|
|
61
55
|
target = await realpath(path);
|
|
@@ -63,20 +57,12 @@ async function listDirectory(root, depth) {
|
|
|
63
57
|
catch {
|
|
64
58
|
continue;
|
|
65
59
|
}
|
|
66
|
-
if (!within(realRoot, target))
|
|
60
|
+
if (!within(realRoot, target) || !(await stat(path).catch(() => undefined))?.isFile())
|
|
67
61
|
continue;
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
else if (info?.isFile() && /\.(md|txt)$/i.test(entry.name)) {
|
|
72
|
-
if (files.length >= MAX_FILES_PER_DIR)
|
|
73
|
-
throw new Error(`文件超过 ${MAX_FILES_PER_DIR} 个,后面的没有读取`);
|
|
74
|
-
files.push({ path, id: `${prefix}${entry.name}` });
|
|
75
|
-
}
|
|
62
|
+
if (files.length >= MAX_FILES_PER_DIR)
|
|
63
|
+
throw new Error(`文件超过 ${MAX_FILES_PER_DIR} 个,后面的没有读取`);
|
|
64
|
+
files.push({ path, id: entry.name });
|
|
76
65
|
}
|
|
77
|
-
}
|
|
78
|
-
try {
|
|
79
|
-
await walk(root, '', 1);
|
|
80
66
|
return { kind: 'ok', files };
|
|
81
67
|
}
|
|
82
68
|
catch (error) {
|
|
@@ -113,7 +99,7 @@ export function createAuthorFiles(sources, timeZone) {
|
|
|
113
99
|
cache.set(sourceId, { kind, path, stat: result.stat, mtimeMs: result.mtimeMs, content: result.content });
|
|
114
100
|
}
|
|
115
101
|
async function loadDirectory(kind, root) {
|
|
116
|
-
const listing = await listDirectory(root
|
|
102
|
+
const listing = await listDirectory(root);
|
|
117
103
|
const key = `dir:${kind}`;
|
|
118
104
|
if (listing.kind === 'failed') {
|
|
119
105
|
failures.set(key, `${root}:${listing.message}`);
|
|
@@ -133,25 +119,14 @@ export function createAuthorFiles(sources, timeZone) {
|
|
|
133
119
|
}
|
|
134
120
|
}
|
|
135
121
|
async function refreshOnce() {
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
}
|
|
142
|
-
catch (error) {
|
|
143
|
-
failures.set(kind, `${path}:${errorText(error)}`);
|
|
144
|
-
}
|
|
122
|
+
const root = sources.diaryDir;
|
|
123
|
+
if (!root)
|
|
124
|
+
return;
|
|
125
|
+
try {
|
|
126
|
+
await loadDirectory('diary', root);
|
|
145
127
|
}
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
continue;
|
|
149
|
-
try {
|
|
150
|
-
await loadDirectory(kind, root);
|
|
151
|
-
}
|
|
152
|
-
catch (error) {
|
|
153
|
-
failures.set(`dir:${kind}`, `${root}:${errorText(error)}`);
|
|
154
|
-
}
|
|
128
|
+
catch (error) {
|
|
129
|
+
failures.set('dir:diary', `${root}:${errorText(error)}`);
|
|
155
130
|
}
|
|
156
131
|
}
|
|
157
132
|
/** Calls arriving during a refresh join it and make it run once more, so a file saved just now is never missed. */
|
package/lib/memoryStore.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import type { DatabaseSync } from 'node:sqlite';
|
|
2
2
|
import type { ConversationRecord } from './types.ts';
|
|
3
|
-
export declare const MEMORY_KINDS: readonly ["conversation", "diary"
|
|
3
|
+
export declare const MEMORY_KINDS: readonly ["conversation", "diary"];
|
|
4
4
|
export type MemoryKind = typeof MEMORY_KINDS[number];
|
|
5
5
|
/** `message`: when the line was said. `diaryDate`: the day in a diary's file name. `fileObserved`: when the file last changed. */
|
|
6
6
|
export type TimeBasis = 'message' | 'diaryDate' | 'fileObserved';
|
|
@@ -49,8 +49,6 @@ export interface FindParams {
|
|
|
49
49
|
sourceId?: string;
|
|
50
50
|
turnId?: string;
|
|
51
51
|
linkedTo?: string;
|
|
52
|
-
/** Only the current content of a file exists, so this changes nothing; it is accepted so older callers keep working. */
|
|
53
|
-
history: boolean;
|
|
54
52
|
order: 'newest' | 'oldest';
|
|
55
53
|
limit: number;
|
|
56
54
|
cursor?: string;
|
package/lib/memoryStore.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { createHash } from 'node:crypto';
|
|
2
2
|
import { formatLocalTime } from "./timeContext.js";
|
|
3
|
-
export const MEMORY_KINDS = ['conversation', 'diary'
|
|
3
|
+
export const MEMORY_KINDS = ['conversation', 'diary'];
|
|
4
4
|
export class MemoryError extends Error {
|
|
5
5
|
code;
|
|
6
6
|
constructor(code, message, options) { super(message, options); this.name = 'MemoryError'; this.code = code; }
|
package/lib/memoryTools.js
CHANGED
|
@@ -33,10 +33,10 @@ export function memoryTools(service, inside) {
|
|
|
33
33
|
return [
|
|
34
34
|
defineTool({
|
|
35
35
|
name: 'memory_find',
|
|
36
|
-
description: `在我自己的长期记忆里按线索查找:原始聊天(conversation)和日记(diary)。query 是要在原文里照字面找的一小段话(区分大小写,不是搜索语法);没有 query 就按时间或来源翻页。kinds 限定种类;from / to 是带时区的 ISO 时间,左闭右开(日期请换成当天零点,如 2026-10-30T00:00:00+08:00);time 的含义看 timeBasis
|
|
36
|
+
description: `在我自己的长期记忆里按线索查找:原始聊天(conversation)和日记(diary)。query 是要在原文里照字面找的一小段话(区分大小写,不是搜索语法);没有 query 就按时间或来源翻页。kinds 限定种类;from / to 是带时区的 ISO 时间,左闭右开(日期请换成当天零点,如 2026-10-30T00:00:00+08:00);time 的含义看 timeBasis:聊天是发言时间,日记是文件名里的日期(文件名没有日期时是它最后改动的时间,不一定是事情发生的时间)。sourceId 限定来源;turnId 取同一轮的全部发言。limit 默认 8、最多 100;返回 nextCursor 就用 cursor 翻下一页,返回 cursorExpired 说明资料变了、要重新查。零命中不等于从没发生过:返回里若带 coverage,说明有来源没能读到。每条结果的 text 只是摘录,要看原文用它的 ref 调 memory_read。`,
|
|
37
37
|
parameters: {
|
|
38
38
|
query: { type: 'string' }, kinds: { type: 'array', items: { type: 'string' } }, from: { type: 'string' }, to: { type: 'string' }, sourceId: { type: 'string' }, turnId: { type: 'string' },
|
|
39
|
-
linkedTo: { type: 'string' },
|
|
39
|
+
linkedTo: { type: 'string' }, order: { type: 'string' }, limit: { type: 'integer' }, cursor: { type: 'string' },
|
|
40
40
|
},
|
|
41
41
|
output,
|
|
42
42
|
execute: async (input) => JSON.stringify(compactFind(await checked(() => service.find({ limit: TOOL_FIND_LIMIT, ...input })))),
|
package/lib/runtime.js
CHANGED
|
@@ -1,15 +1,16 @@
|
|
|
1
1
|
import { createSystemMessage, createUserMessage, isAgentLoopRequest } from '@deepseek-ai/dsh-llm';
|
|
2
2
|
import "./hostContract.js";
|
|
3
|
+
import { isOrdinarySession } from "./archive.js";
|
|
3
4
|
import { Faults } from "./faults.js";
|
|
4
5
|
import { createHistory, excludePresentMessages, renderHistory } from "./history.js";
|
|
5
6
|
import { createWorldToolRegistry, memoryTools } from "./memoryTools.js";
|
|
6
7
|
import { createPromptSections } from "./promptSection.js";
|
|
7
|
-
import { belongsToWorld, createSourceArchive, inWorld
|
|
8
|
+
import { belongsToWorld, createSourceArchive, inWorld } from "./sourceArchive.js";
|
|
8
9
|
import { worldNames } from "./worldPrompt.js";
|
|
9
10
|
import { reassembleOnChange } from "./worldScope.js";
|
|
10
11
|
import { DEFAULT_MEMORY_TURNS } from "./worldSwitch.js";
|
|
11
12
|
const memorySource = 'dsh-world-history';
|
|
12
|
-
const
|
|
13
|
+
const isMemoryBlock = (event) => event?.type === 'user/message' && event.data.source.kind === memorySource;
|
|
13
14
|
/**
|
|
14
15
|
* The memory line: her conversations are archived as they happen, and every world session gets a memory
|
|
15
16
|
* block of the newest turns at its start and after each successful compaction, never in between, so it stays
|
|
@@ -42,7 +43,6 @@ export function createWorldRuntime(ctx, config, store, world, memoryTurns = () =
|
|
|
42
43
|
const tools = toolSets.length ? createWorldToolRegistry({ tools: inside => toolSets.flatMap(make => make(inside)), inWorld: agent => !stopped && included(agent.session), faults, logger: ctx.logger }) : undefined;
|
|
43
44
|
/** The memory tools follow world membership, whatever the life line does. */
|
|
44
45
|
const syncTools = (agent) => !tools ? false : included(agent.session) ? tools.attach(agent) : tools.detach(agent);
|
|
45
|
-
const attaching = new WeakMap();
|
|
46
46
|
const disposers = [];
|
|
47
47
|
let stopping;
|
|
48
48
|
let stopped = false;
|
|
@@ -50,51 +50,32 @@ export function createWorldRuntime(ctx, config, store, world, memoryTurns = () =
|
|
|
50
50
|
* Whether the session may carry her world: her preset, or a memory block inherited onto its surface (a delegated
|
|
51
51
|
* child of her session). Everything else is never read from disk or tracked. The check stays in memory.
|
|
52
52
|
*/
|
|
53
|
-
const mayCarryWorld = (session) => belongsToWorld(session, config) || memory.has(session) || session.surface.nodes.some(seq =>
|
|
54
|
-
|
|
55
|
-
return event?.type === 'user/message' && worldSources.includes(event.data.source.kind);
|
|
56
|
-
});
|
|
57
|
-
/** Restore the loop position; recalled blocks are located directly on the current surface. */
|
|
58
|
-
async function readMemoryState(session) {
|
|
59
|
-
let position = { turn: 1, step: 1 };
|
|
60
|
-
// A session the host is still creating may not be readable yet (#27); it has no step to restore.
|
|
61
|
-
const handle = await ctx.sessionPersistence.open(session.id, 'read').catch(error => { if (isNotFound(error))
|
|
62
|
-
return undefined; throw error; });
|
|
63
|
-
if (handle)
|
|
64
|
-
try {
|
|
65
|
-
for (let offset = 0;; offset += 128) {
|
|
66
|
-
const { events } = await handle.read(offset, 128);
|
|
67
|
-
if (!events.length)
|
|
68
|
-
break;
|
|
69
|
-
for (const event of events) {
|
|
70
|
-
if (event.type === 'step/start')
|
|
71
|
-
position = { turn: event.data.turn, step: event.data.step };
|
|
72
|
-
}
|
|
73
|
-
}
|
|
74
|
-
}
|
|
75
|
-
finally {
|
|
76
|
-
await handle.close();
|
|
77
|
-
}
|
|
53
|
+
const mayCarryWorld = (session) => belongsToWorld(session, config) || memory.has(session) || session.surface.nodes.some(seq => isMemoryBlock(session.eventAt(seq)));
|
|
54
|
+
function newMemoryState(session) {
|
|
78
55
|
const inScope = included(session);
|
|
79
|
-
return { reload: true, position, retiring: [], inScope, restart: !inScope && belongsToWorld(session, config) };
|
|
56
|
+
return { reload: true, position: { turn: 1, step: 1 }, retiring: [], inScope, restart: !inScope && belongsToWorld(session, config) };
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Archive failures never stop her talking: they stay in the health list, and what she said meanwhile is replayed
|
|
60
|
+
* from the host's log, from the archive's last committed position, once a later replay succeeds.
|
|
61
|
+
*/
|
|
62
|
+
async function archiveNow(sessionId) {
|
|
63
|
+
if (archived(sessionId))
|
|
64
|
+
await faults.track(`archive:${sessionId}`, `会话 ${sessionId} 归档登记失败`, () => store.commitRecords([], store.progress(sessionId))).catch(() => { });
|
|
65
|
+
await archive.schedule(sessionId).catch(() => { });
|
|
80
66
|
}
|
|
81
67
|
/**
|
|
82
68
|
* Marks our recalled blocks on the surface for retirement. The empty system node that retires one is accepted by
|
|
83
69
|
* the host only inside an open turn and step, which pre-step and attach are not, so `flushRetired` writes it from
|
|
84
70
|
* the step's request hook, after the step has started and before the request is assembled (#22).
|
|
85
71
|
*/
|
|
86
|
-
function retireMemory(session, state
|
|
87
|
-
const found = session.surface.nodes.filter(seq =>
|
|
88
|
-
const event = session.eventAt(seq);
|
|
89
|
-
return event?.type === 'user/message' && kinds.includes(event.data.source.kind);
|
|
90
|
-
});
|
|
72
|
+
function retireMemory(session, state) {
|
|
73
|
+
const found = session.surface.nodes.filter(seq => isMemoryBlock(session.eventAt(seq)));
|
|
91
74
|
state.retiring = [...new Set([...state.retiring, ...found])];
|
|
92
75
|
if (found.length)
|
|
93
76
|
state.restart = true;
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
state.pendingId = undefined;
|
|
97
|
-
}
|
|
77
|
+
state.reload = true;
|
|
78
|
+
state.pendingId = undefined;
|
|
98
79
|
}
|
|
99
80
|
/** Where memory blocks sit on a session's surface, for the log: positions and event types only, never message text. */
|
|
100
81
|
function memoryNodesOn(session) {
|
|
@@ -110,7 +91,7 @@ export function createWorldRuntime(ctx, config, store, world, memoryTurns = () =
|
|
|
110
91
|
catch {
|
|
111
92
|
continue;
|
|
112
93
|
}
|
|
113
|
-
if (message?.source?.kind
|
|
94
|
+
if (message?.source?.kind === memorySource)
|
|
114
95
|
found.push(`#${seq}(${event.type})`);
|
|
115
96
|
}
|
|
116
97
|
return found.length ? found.slice(0, 8).join('、') + (found.length > 8 ? `…共 ${found.length} 个` : '') : '无';
|
|
@@ -129,38 +110,18 @@ export function createWorldRuntime(ctx, config, store, world, memoryTurns = () =
|
|
|
129
110
|
const { session } = agent;
|
|
130
111
|
if (memory.has(session) || !mayCarryWorld(session))
|
|
131
112
|
return;
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
if (archived(session.id))
|
|
138
|
-
await store.commitRecords([], store.progress(session.id));
|
|
139
|
-
await archive.schedule(session.id);
|
|
140
|
-
}
|
|
141
|
-
const state = await readMemoryState(session);
|
|
142
|
-
// Retiring writes a system/message, which the host only accepts inside an open turn and step; attach runs
|
|
143
|
-
// between turns, so an out-of-scope block is retired by the next pre-step (before any request) instead (#22).
|
|
144
|
-
memory.set(session, state);
|
|
145
|
-
});
|
|
146
|
-
attaching.set(session, job);
|
|
147
|
-
try {
|
|
148
|
-
await job;
|
|
149
|
-
}
|
|
150
|
-
finally {
|
|
151
|
-
attaching.delete(session);
|
|
152
|
-
}
|
|
113
|
+
// Retiring writes a system/message, which the host only accepts inside an open turn and step; attach runs
|
|
114
|
+
// between turns, so an out-of-scope block is retired by the next pre-step (before any request) instead (#22).
|
|
115
|
+
memory.set(session, newMemoryState(session));
|
|
116
|
+
if (included(session))
|
|
117
|
+
await archiveNow(session.id);
|
|
153
118
|
}
|
|
154
|
-
/** Retire old blocks, then admit fresh memory through the host's normal append path (#21). */
|
|
119
|
+
/** Retire old blocks, then admit fresh memory through the host's normal append path (#21). The caller checks the scope after the wait. */
|
|
155
120
|
async function freshBlock(session, state) {
|
|
156
|
-
const turns = await history.loadRecentTurns(
|
|
157
|
-
if (!included(session)) {
|
|
158
|
-
retireMemory(session, state);
|
|
159
|
-
return undefined;
|
|
160
|
-
}
|
|
121
|
+
const turns = await history.loadRecentTurns(memoryTurns(), archivedByScope);
|
|
161
122
|
const present = new Set(session.deriveMessages().map(message => message.id));
|
|
162
123
|
const text = renderHistory(excludePresentMessages(turns, present), config.timeZone, names(), config.archiveScope === 'home');
|
|
163
|
-
retireMemory(session, state
|
|
124
|
+
retireMemory(session, state);
|
|
164
125
|
return text ? createUserMessage({ content: [{ type: 'text', text }], source: { kind: memorySource, form: 'recall' } }) : undefined;
|
|
165
126
|
}
|
|
166
127
|
/** Reads what the first catch-up had to leave, once the host can say which sessions belong to her. */
|
|
@@ -175,8 +136,6 @@ export function createWorldRuntime(ctx, config, store, world, memoryTurns = () =
|
|
|
175
136
|
try {
|
|
176
137
|
disposers.push(ctx.on('session/event', (session, event) => {
|
|
177
138
|
const state = memory.get(session);
|
|
178
|
-
if (state && event.type === 'step/start')
|
|
179
|
-
state.position = { turn: event.data.turn, step: event.data.step };
|
|
180
139
|
const compacted = event.type === 'compaction/end' && event.data.error === undefined;
|
|
181
140
|
if (state && event.type === 'user/message' && event.data.id === state.pendingId) {
|
|
182
141
|
state.reload = false;
|
|
@@ -187,17 +146,17 @@ export function createWorldRuntime(ctx, config, store, world, memoryTurns = () =
|
|
|
187
146
|
}
|
|
188
147
|
if (compacted)
|
|
189
148
|
prompts?.refresh(session);
|
|
190
|
-
if (
|
|
149
|
+
if (!isOrdinarySession(session.header))
|
|
191
150
|
return;
|
|
192
151
|
if (event.type === 'assistant/message' || event.type === 'turn/end' || event.type === 'turn/start' || event.type === 'compaction/end' || (event.type === 'user/message' && event.data.source.kind === 'user'))
|
|
193
152
|
void archive.schedule(session.id).catch(() => { });
|
|
194
153
|
}));
|
|
195
154
|
// The host fails the whole session creation when a creation listener rejects, leaving an empty session behind on
|
|
196
|
-
// every retry (#27)
|
|
155
|
+
// every retry (#27); attach never rejects, and its archive failures stay in the health list.
|
|
197
156
|
disposers.push(ctx.on('agent/created', ({ agent }) => {
|
|
198
157
|
prompts?.add(agent);
|
|
199
158
|
syncTools(agent);
|
|
200
|
-
void attach(agent)
|
|
159
|
+
void attach(agent);
|
|
201
160
|
return undefined;
|
|
202
161
|
}));
|
|
203
162
|
if (tools) {
|
|
@@ -225,37 +184,40 @@ export function createWorldRuntime(ctx, config, store, world, memoryTurns = () =
|
|
|
225
184
|
if (!included(agent.session))
|
|
226
185
|
return leave();
|
|
227
186
|
state.inScope = true;
|
|
228
|
-
await
|
|
187
|
+
await archiveNow(agent.id);
|
|
229
188
|
signal.throwIfAborted();
|
|
230
189
|
if (!included(agent.session))
|
|
231
190
|
return leave();
|
|
232
191
|
if (!state.reload)
|
|
233
192
|
return decision;
|
|
234
|
-
|
|
235
|
-
|
|
193
|
+
// A block that cannot be built leaves the old one in place; she talks on, the fault shows, and the next step tries again.
|
|
194
|
+
let block, built = true;
|
|
195
|
+
await faults.track(`memory:${agent.id}`, `会话 ${agent.id} 记忆刷新失败`, async () => { block = await freshBlock(agent.session, state); }).catch(() => { built = false; });
|
|
236
196
|
if (!included(agent.session))
|
|
237
197
|
return leave();
|
|
238
198
|
signal.throwIfAborted();
|
|
239
|
-
if (!
|
|
240
|
-
return
|
|
241
|
-
if (
|
|
199
|
+
if (!built)
|
|
200
|
+
return decision;
|
|
201
|
+
if (!block) {
|
|
242
202
|
state.reload = false;
|
|
243
|
-
if (!block)
|
|
244
203
|
return decision;
|
|
204
|
+
}
|
|
245
205
|
state.pendingId = block.id;
|
|
246
206
|
return { ...decision, messages: [block, ...decision.messages] };
|
|
247
207
|
}));
|
|
248
208
|
// The step is open here and its request is not built yet: the one place retired blocks can be written validly.
|
|
249
209
|
disposers.push(ctx.on('agent/request', async function (payload, next) {
|
|
250
210
|
const state = memory.get(payload.agent.session);
|
|
211
|
+
if (state)
|
|
212
|
+
state.position = { turn: payload.turn, step: payload.step };
|
|
251
213
|
if (state?.retiring.length)
|
|
252
|
-
flushRetired(payload.agent.session, state,
|
|
214
|
+
flushRetired(payload.agent.session, state, state.position);
|
|
253
215
|
return next();
|
|
254
216
|
}));
|
|
255
217
|
disposers.push(ctx.on('llm/stream', async function* (request, next) {
|
|
256
218
|
const agent = isAgentLoopRequest(request) && request.sessionId ? ctx.agents.get(request.sessionId) : undefined;
|
|
257
219
|
const owned = agent && included(agent.session);
|
|
258
|
-
const inRequest = agent && !owned ? request.messages.filter(message =>
|
|
220
|
+
const inRequest = agent && !owned ? request.messages.filter(message => message.source?.kind === memorySource).length : 0;
|
|
259
221
|
const placed = !!agent && !owned && !!prompts?.active(agent.session);
|
|
260
222
|
if (agent && !owned && (placed || inRequest)) {
|
|
261
223
|
const state = memory.get(agent.session);
|
|
@@ -285,14 +247,7 @@ export function createWorldRuntime(ctx, config, store, world, memoryTurns = () =
|
|
|
285
247
|
await archive.skip(agent.id);
|
|
286
248
|
for (const agent of ctx.agents.list()) {
|
|
287
249
|
prompts?.add(agent);
|
|
288
|
-
|
|
289
|
-
await attach(agent);
|
|
290
|
-
}
|
|
291
|
-
catch (error) {
|
|
292
|
-
if (!isCorruptSessionLog(error))
|
|
293
|
-
throw error;
|
|
294
|
-
ctx.logger.warn(`dsh-world: 会话 ${agent.id} 记忆初始化失败,已隔离:`, error);
|
|
295
|
-
}
|
|
250
|
+
await attach(agent);
|
|
296
251
|
}
|
|
297
252
|
}
|
|
298
253
|
catch (error) {
|
package/lib/sourceArchive.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { SessionId } from '@deepseek-ai/dsh-session';
|
|
2
|
-
import { extractConversationRecords } from "./archive.js";
|
|
2
|
+
import { extractConversationRecords, isOrdinarySession } from "./archive.js";
|
|
3
3
|
import { wechatDeliveryPatch } from "./ecosystem/wechat/archive.js";
|
|
4
4
|
import { errorText, Faults } from "./faults.js";
|
|
5
5
|
const pageSize = 128;
|
|
@@ -10,14 +10,13 @@ export function isCorruptSessionLog(error) {
|
|
|
10
10
|
}
|
|
11
11
|
export function belongsToWorld(session, config) {
|
|
12
12
|
const header = session.header;
|
|
13
|
-
return header.agentPreset === config.agentPreset &&
|
|
13
|
+
return header.agentPreset === config.agentPreset && isOrdinarySession(header);
|
|
14
14
|
}
|
|
15
15
|
/** One of her sessions that is also in her room's workspace; without a membership test, any of her sessions. */
|
|
16
16
|
export function inWorld(session, config, inWorkspace) {
|
|
17
17
|
return belongsToWorld(session, config) && (inWorkspace?.(session.id) ?? true);
|
|
18
18
|
}
|
|
19
19
|
export const isNotFound = (error) => error instanceof Error && error.name === 'SessionPersistenceNotFoundError';
|
|
20
|
-
const ordinary = (header) => header.origin !== 'subagent' && (header.delegationDepth ?? 0) === 0;
|
|
21
20
|
/**
|
|
22
21
|
* Copies her conversations from the host's session logs into the archive. Each session is replayed from where
|
|
23
22
|
* the archive left off; replays run one at a time, and a session already queued is not queued twice. Sessions
|
|
@@ -134,7 +133,7 @@ export function createSourceArchive(ctx, config, store, archived = () => true) {
|
|
|
134
133
|
const visited = new Set();
|
|
135
134
|
for (let offset = 0; offset < snapshots.length; offset += pageSize) {
|
|
136
135
|
for (const { header } of snapshots.slice(offset, offset + pageSize)) {
|
|
137
|
-
if (!
|
|
136
|
+
if (!isOrdinarySession(header) || !archived(header.id))
|
|
138
137
|
continue;
|
|
139
138
|
visited.add(header.id);
|
|
140
139
|
await replayOne(header.id);
|
package/lib/store.d.ts
CHANGED
|
@@ -12,7 +12,7 @@ export declare function createArchiveStore(config: WorldConfig & {
|
|
|
12
12
|
hasRecord: (recordId: string) => boolean;
|
|
13
13
|
updateRecord: (recordId: string, revise: (record: ConversationRecord) => Pick<ConversationRecord, "content" | "wechatDelivery"> & Partial<SpeakerIdentity>) => Promise<void>;
|
|
14
14
|
readPage: (query: PageQuery) => Promise<RecordPage>;
|
|
15
|
-
readTurn: (
|
|
15
|
+
readTurn: (turnId: string, afterSeq?: number, limit?: number) => Promise<ConversationRecord[]>;
|
|
16
16
|
progress: (sessionId: string) => ExportProgress;
|
|
17
17
|
forgetProgress: (sessionId: string) => void;
|
|
18
18
|
sourcePage: (afterId?: string, limit?: number) => string[];
|
package/lib/store.js
CHANGED
|
@@ -145,7 +145,7 @@ export function createArchiveStore(config) {
|
|
|
145
145
|
});
|
|
146
146
|
flushExports();
|
|
147
147
|
}
|
|
148
|
-
async function readTurn(
|
|
148
|
+
async function readTurn(turnId, afterSeq = -1, limit = pageSize) {
|
|
149
149
|
flushExports();
|
|
150
150
|
return db.prepare('SELECT * FROM records WHERE turnId=? AND sourceSeq>? ORDER BY sourceSeq LIMIT ?').all(turnId, afterSeq, limit).map(decode);
|
|
151
151
|
}
|
package/lib/types.d.ts
CHANGED
|
@@ -97,11 +97,9 @@ export interface ConversationRecord extends Partial<SpeakerIdentity> {
|
|
|
97
97
|
}
|
|
98
98
|
export interface ArchiveScope {
|
|
99
99
|
worldId: string;
|
|
100
|
-
agentPreset: string;
|
|
101
100
|
header: SessionHeader;
|
|
102
101
|
inheritedEventCount: number;
|
|
103
102
|
turn: number;
|
|
104
|
-
archiveScope?: MemoryArchiveScope;
|
|
105
103
|
}
|
|
106
104
|
export interface ArchiveCursor {
|
|
107
105
|
date: string;
|
|
@@ -110,7 +108,6 @@ export interface ArchiveCursor {
|
|
|
110
108
|
maxSequence: number;
|
|
111
109
|
}
|
|
112
110
|
export interface PageQuery {
|
|
113
|
-
worldId: string;
|
|
114
111
|
before?: ArchiveCursor;
|
|
115
112
|
limit: number;
|
|
116
113
|
}
|
|
@@ -125,5 +122,5 @@ export interface ConversationTurn {
|
|
|
125
122
|
}
|
|
126
123
|
export interface ArchiveReader {
|
|
127
124
|
readPage(query: PageQuery): Promise<RecordPage>;
|
|
128
|
-
readTurn(
|
|
125
|
+
readTurn(turnId: string, afterSeq?: number, limit?: number): Promise<ConversationRecord[]>;
|
|
129
126
|
}
|
package/lib/worldPrompt.js
CHANGED
|
@@ -50,6 +50,6 @@ export function renderWorldPrompt(prompt, template, self, home) {
|
|
|
50
50
|
const { life, names } = prompt;
|
|
51
51
|
return renderTemplate(template, { life: Boolean(life), home, selfFile: Boolean(self), conversationsDir: Boolean(prompt.conversationsDir), memoryTools: Boolean(prompt.memoryTools) }, {
|
|
52
52
|
name: names.companion, partner: names.partner, homeTitle: homeTitle(names), selfFile: self?.file ?? '', self: self?.text ?? '', conversationsDir: prompt.conversationsDir ?? '',
|
|
53
|
-
...(life ? { roomDir: life.roomDir, diaryDir: life.diaryDir, fallbackWakeTime: life.
|
|
53
|
+
...(life ? { roomDir: life.roomDir, diaryDir: life.diaryDir, fallbackWakeTime: life.schedule().wake } : {}),
|
|
54
54
|
});
|
|
55
55
|
}
|
package/lib/worldSwitch.d.ts
CHANGED
|
@@ -10,7 +10,7 @@ export declare const DEFAULT_WECHAT_BUFFER_SECONDS = 3, MAX_WECHAT_BUFFER_SECOND
|
|
|
10
10
|
* spend a day, and how many recent turns her memory block carries. A world that already has a life line from before the switch existed is running; a new one waits
|
|
11
11
|
* for its partner to press start.
|
|
12
12
|
*/
|
|
13
|
-
export declare function createWorldSwitch(worldDir: string, configuredScope?: MemoryArchiveScope): {
|
|
13
|
+
export declare function createWorldSwitch(worldDir: string, configuredScope?: MemoryArchiveScope, configuredWake?: string): {
|
|
14
14
|
archiveScope: () => MemoryArchiveScope;
|
|
15
15
|
selectedArchiveScope: () => MemoryArchiveScope;
|
|
16
16
|
restartRequired: () => boolean;
|
|
@@ -42,6 +42,14 @@ export declare function createWorldSwitch(worldDir: string, configuredScope?: Me
|
|
|
42
42
|
wechat?: boolean;
|
|
43
43
|
qq?: boolean;
|
|
44
44
|
}): void;
|
|
45
|
+
/** Her evening look back and her morning wake when nothing is pending; the configured `fallbackWakeTime` is the morning's default. */
|
|
46
|
+
reviewTime: () => string;
|
|
47
|
+
wakeTime: () => string;
|
|
48
|
+
/** A field left out stays as it is; null goes back to its default. */
|
|
49
|
+
setSchedule(next: {
|
|
50
|
+
review?: string | null;
|
|
51
|
+
wake?: string | null;
|
|
52
|
+
}): void;
|
|
45
53
|
/** Read by the WeChat adapter on its next poll; a batch already waiting keeps the value it started with. */
|
|
46
54
|
wechatContext: () => number;
|
|
47
55
|
wechatBufferSeconds: () => number;
|
package/lib/worldSwitch.js
CHANGED
|
@@ -2,6 +2,7 @@ import { existsSync, readFileSync } from 'node:fs';
|
|
|
2
2
|
import { join } from 'node:path';
|
|
3
3
|
import { durableWrite } from "./life/lifeStore.js";
|
|
4
4
|
import { validArchiveScope } from "./archiveSelection.js";
|
|
5
|
+
import { DEFAULT_REVIEW_TIME, validClockTime } from "./life/alarm.js";
|
|
5
6
|
/** How many of the newest turns the memory block carries when nothing else is set. */
|
|
6
7
|
export const DEFAULT_MEMORY_TURNS = 200;
|
|
7
8
|
/** WeChat group messages read before a mention, and seconds a private image waits for its companions. */
|
|
@@ -13,7 +14,7 @@ export const DEFAULT_WECHAT_BUFFER_SECONDS = 3, MAX_WECHAT_BUFFER_SECONDS = 30;
|
|
|
13
14
|
* spend a day, and how many recent turns her memory block carries. A world that already has a life line from before the switch existed is running; a new one waits
|
|
14
15
|
* for its partner to press start.
|
|
15
16
|
*/
|
|
16
|
-
export function createWorldSwitch(worldDir, configuredScope = 'workspace') {
|
|
17
|
+
export function createWorldSwitch(worldDir, configuredScope = 'workspace', configuredWake = '09:00') {
|
|
17
18
|
const file = join(worldDir, 'world.json');
|
|
18
19
|
const stored = existsSync(file) ? JSON.parse(readFileSync(file, 'utf8')) : undefined;
|
|
19
20
|
let settings = {
|
|
@@ -28,6 +29,8 @@ export function createWorldSwitch(worldDir, configuredScope = 'workspace') {
|
|
|
28
29
|
...(typeof stored?.qqEnabled === 'boolean' ? { qqEnabled: stored.qqEnabled } : {}),
|
|
29
30
|
...(stored?.compactAfterReview === false ? { compactAfterReview: false } : {}),
|
|
30
31
|
...(stored?.compactionSwapped === true ? { compactionSwapped: true } : {}),
|
|
32
|
+
...(validClockTime(stored?.reviewTime) ? { reviewTime: stored.reviewTime } : {}),
|
|
33
|
+
...(validClockTime(stored?.wakeTime) ? { wakeTime: stored.wakeTime } : {}),
|
|
31
34
|
};
|
|
32
35
|
const activeScope = settings.archiveScope ?? configuredScope;
|
|
33
36
|
function save(next) {
|
|
@@ -84,6 +87,16 @@ export function createWorldSwitch(worldDir, configuredScope = 'workspace') {
|
|
|
84
87
|
const wechat = next.wechat ?? wechatEnabled ?? existsSync(join(worldDir, 'wechat-outbox.sqlite')), qq = next.qq ?? qqEnabled === true;
|
|
85
88
|
save({ ...rest, wechatEnabled: wechat, ...(qq ? { qqEnabled: true } : {}) });
|
|
86
89
|
},
|
|
90
|
+
/** Her evening look back and her morning wake when nothing is pending; the configured `fallbackWakeTime` is the morning's default. */
|
|
91
|
+
reviewTime: () => settings.reviewTime ?? DEFAULT_REVIEW_TIME,
|
|
92
|
+
wakeTime: () => settings.wakeTime ?? configuredWake,
|
|
93
|
+
/** A field left out stays as it is; null goes back to its default. */
|
|
94
|
+
setSchedule(next) {
|
|
95
|
+
const { reviewTime: oldReview, wakeTime: oldWake, ...rest } = settings;
|
|
96
|
+
const review = next.review === undefined ? oldReview : next.review ?? undefined;
|
|
97
|
+
const wake = next.wake === undefined ? oldWake : next.wake ?? undefined;
|
|
98
|
+
save({ ...rest, ...(review === undefined || review === DEFAULT_REVIEW_TIME ? {} : { reviewTime: review }), ...(wake === undefined || wake === configuredWake ? {} : { wakeTime: wake }) });
|
|
99
|
+
},
|
|
87
100
|
/** Read by the WeChat adapter on its next poll; a batch already waiting keeps the value it started with. */
|
|
88
101
|
wechatContext: () => settings.wechatContext ?? DEFAULT_WECHAT_CONTEXT,
|
|
89
102
|
wechatBufferSeconds: () => settings.wechatBufferSeconds ?? DEFAULT_WECHAT_BUFFER_SECONDS,
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-world",
|
|
3
|
-
"version": "0.7.
|
|
3
|
+
"version": "0.7.1",
|
|
4
4
|
"description": "Cross-session memory, persona and life routines for DSH, with a world console, tool-free compaction, native QQ and Windows WeChat messaging, group history and quoted replies",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"publishConfig": {
|
package/scripts/compact-home.mjs
CHANGED
|
@@ -1,29 +1,29 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
// Asks a running world to compact her home conversation once (held behind her running turn).
|
|
3
|
-
// Needs `bridge: true` in the plugin config. Usage: node scripts/compact-home.mjs [world directory]
|
|
4
|
-
// The world directory defaults to $DSH_WORLD_DIR, then ~/.dsh/worlds/<the only world there>.
|
|
5
|
-
import { existsSync, readFileSync, readdirSync } from 'node:fs';
|
|
6
|
-
import { homedir } from 'node:os';
|
|
7
|
-
import { join } from 'node:path';
|
|
8
|
-
|
|
9
|
-
function worldDir() {
|
|
10
|
-
if (process.argv[2]) return process.argv[2];
|
|
11
|
-
if (process.env.DSH_WORLD_DIR) return process.env.DSH_WORLD_DIR;
|
|
12
|
-
const root = join(homedir(), '.dsh', 'worlds');
|
|
13
|
-
const worlds = existsSync(root) ? readdirSync(root, { withFileTypes: true }).filter(entry => entry.isDirectory()).map(entry => entry.name) : [];
|
|
14
|
-
if (worlds.length !== 1) throw new Error(`找不到唯一的世界目录,请把路径作为参数传入(在 ${root} 下找到 ${worlds.length} 个)`);
|
|
15
|
-
return join(root, worlds[0]);
|
|
16
|
-
}
|
|
17
|
-
|
|
18
|
-
try {
|
|
19
|
-
const file = join(worldDir(), 'bridge.json');
|
|
20
|
-
if (!existsSync(file)) throw new Error(`没有 ${file}:世界没有在运行,或者没有开启 bridge`);
|
|
21
|
-
const { origin, token } = JSON.parse(readFileSync(file, 'utf8'));
|
|
22
|
-
const response = await fetch(new URL('/dsh-world/bridge/compact', origin), { method: 'POST', headers: { 'x-dsh-world-token': token }, signal: AbortSignal.timeout(15000) });
|
|
23
|
-
const body = await response.json().catch(() => ({}));
|
|
24
|
-
if (response.status === 202) console.log('已请求压缩家会话;她正在忙的话会等这一轮结束后再压缩。');
|
|
25
|
-
else { console.error(`没有受理(${response.status}):${body.error ?? '未知原因'}`); process.exitCode = 1; }
|
|
26
|
-
} catch (error) {
|
|
27
|
-
console.error(error instanceof Error ? error.message : String(error));
|
|
28
|
-
process.exitCode = 1;
|
|
29
|
-
}
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Asks a running world to compact her home conversation once (held behind her running turn).
|
|
3
|
+
// Needs `bridge: true` in the plugin config. Usage: node scripts/compact-home.mjs [world directory]
|
|
4
|
+
// The world directory defaults to $DSH_WORLD_DIR, then ~/.dsh/worlds/<the only world there>.
|
|
5
|
+
import { existsSync, readFileSync, readdirSync } from 'node:fs';
|
|
6
|
+
import { homedir } from 'node:os';
|
|
7
|
+
import { join } from 'node:path';
|
|
8
|
+
|
|
9
|
+
function worldDir() {
|
|
10
|
+
if (process.argv[2]) return process.argv[2];
|
|
11
|
+
if (process.env.DSH_WORLD_DIR) return process.env.DSH_WORLD_DIR;
|
|
12
|
+
const root = join(homedir(), '.dsh', 'worlds');
|
|
13
|
+
const worlds = existsSync(root) ? readdirSync(root, { withFileTypes: true }).filter(entry => entry.isDirectory()).map(entry => entry.name) : [];
|
|
14
|
+
if (worlds.length !== 1) throw new Error(`找不到唯一的世界目录,请把路径作为参数传入(在 ${root} 下找到 ${worlds.length} 个)`);
|
|
15
|
+
return join(root, worlds[0]);
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
try {
|
|
19
|
+
const file = join(worldDir(), 'bridge.json');
|
|
20
|
+
if (!existsSync(file)) throw new Error(`没有 ${file}:世界没有在运行,或者没有开启 bridge`);
|
|
21
|
+
const { origin, token } = JSON.parse(readFileSync(file, 'utf8'));
|
|
22
|
+
const response = await fetch(new URL('/dsh-world/bridge/compact', origin), { method: 'POST', headers: { 'x-dsh-world-token': token }, signal: AbortSignal.timeout(15000) });
|
|
23
|
+
const body = await response.json().catch(() => ({}));
|
|
24
|
+
if (response.status === 202) console.log('已请求压缩家会话;她正在忙的话会等这一轮结束后再压缩。');
|
|
25
|
+
else { console.error(`没有受理(${response.status}):${body.error ?? '未知原因'}`); process.exitCode = 1; }
|
|
26
|
+
} catch (error) {
|
|
27
|
+
console.error(error instanceof Error ? error.message : String(error));
|
|
28
|
+
process.exitCode = 1;
|
|
29
|
+
}
|