dsh-world 0.7.1 → 0.7.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +29 -0
- package/INSTALL.md +314 -314
- package/LICENSE +21 -21
- package/NOTES.md +34 -15
- package/README.md +22 -8
- package/client/index.js +85 -28
- package/cordis.patch.yml +6 -6
- package/lib/archiveSelection.d.ts +6 -2
- package/lib/archiveSelection.js +21 -12
- package/lib/compaction.d.ts +7 -0
- package/lib/compaction.js +16 -7
- package/lib/console/routes.d.ts +4 -3
- package/lib/console/routes.js +18 -12
- package/lib/console/snapshot.d.ts +3 -3
- package/lib/console/snapshot.js +1 -4
- package/lib/ecosystem/bridge/bridge.d.ts +5 -0
- package/lib/ecosystem/bridge/bridge.js +2 -1
- package/lib/ecosystem/bridge/route.d.ts +4 -6
- package/lib/ecosystem/bridge/route.js +34 -58
- package/lib/ecosystem/qq/panel.d.ts +0 -1
- package/lib/ecosystem/qq/route.d.ts +6 -7
- package/lib/ecosystem/qq/route.js +10 -10
- package/lib/ecosystem/qq/snowluma-start.d.ts +1 -0
- package/lib/ecosystem/qq/snowluma-start.js +41 -8
- package/lib/ecosystem/qq/supervisor.d.ts +1 -2
- package/lib/ecosystem/qq/supervisor.js +4 -2
- package/lib/ecosystem/qq-native/home.d.ts +1 -0
- package/lib/ecosystem/qq-native/home.js +10 -3
- package/lib/ecosystem/qq-native/index.js +19 -4
- package/lib/ecosystem/qq-native/native-bridge.d.ts +0 -1
- package/lib/ecosystem/qq-native/native-bridge.js +5 -4
- package/lib/ecosystem/qq-native/replies.d.ts +3 -2
- package/lib/ecosystem/qq-native/replies.js +15 -4
- package/lib/ecosystem/qq-native/snowluma.js +11 -2
- package/lib/ecosystem/shared/context.d.ts +5 -0
- package/lib/ecosystem/shared/context.js +5 -0
- package/lib/ecosystem/wechat/index.d.ts +0 -1
- package/lib/ecosystem/wechat/index.js +6 -5
- package/lib/hostContract.d.ts +17 -1
- package/lib/index.d.ts +1 -0
- package/lib/index.js +126 -47
- package/lib/life/toolRegistry.js +2 -2
- package/lib/memoryFiles.d.ts +0 -1
- package/lib/memoryStore.d.ts +0 -1
- package/lib/memoryStore.js +0 -1
- package/lib/memoryTools.d.ts +0 -1
- package/lib/memoryTools.js +2 -3
- package/lib/promptSection.d.ts +10 -7
- package/lib/promptSection.js +80 -33
- package/lib/runtime.d.ts +12 -3
- package/lib/runtime.js +150 -29
- package/lib/sourceArchive.d.ts +4 -2
- package/lib/sourceArchive.js +19 -5
- package/lib/store.js +2 -1
- package/lib/types.d.ts +1 -1
- package/lib/worldPrompt.d.ts +2 -3
- package/lib/worldPrompt.js +2 -3
- package/lib/worldRoutes.d.ts +9 -0
- package/lib/worldRoutes.js +29 -0
- package/lib/worldScope.d.ts +5 -5
- package/lib/worldScope.js +16 -7
- package/lib/worldSwitch.d.ts +7 -2
- package/lib/worldSwitch.js +11 -1
- package/package.json +17 -16
- 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/README.md +1 -1
- package/src/ecosystem/wechat/windows/README.md +6 -4
- package/src/ecosystem/wechat/windows/adapter.py +4 -2
- package/src/ecosystem/wechat/windows/engine/NOTICE.md +6 -0
- package/src/ecosystem/wechat/windows/engine/profiles.json +142 -114
- package/src/ecosystem/wechat/windows/presence.py +109 -109
- package/templates/alarm.md +2 -2
- package/templates/world-prompt.md +8 -2
package/lib/runtime.d.ts
CHANGED
|
@@ -5,14 +5,23 @@ import { type WorldPromptSource } from './promptSection.ts';
|
|
|
5
5
|
import type { ArchiveStore } from './store.ts';
|
|
6
6
|
import type { WorldConfig } from './types.ts';
|
|
7
7
|
export type { WorldPromptSource } from './promptSection.ts';
|
|
8
|
+
/** A session can outlive its world. Authorization returns false for a stopped world and undefined outside it. */
|
|
9
|
+
export declare function guardWorldContext(ctx: Context, authorize: (session: Session, worldId?: string) => symbol | false | undefined): void;
|
|
8
10
|
/**
|
|
9
11
|
* The memory line: her conversations are archived as they happen, and every world session gets a memory
|
|
10
|
-
* block of the newest turns at its start
|
|
11
|
-
* inside the provider-cached prefix. `home` archives the current home; `workspace` uses host membership. The memory block still
|
|
12
|
+
* block of the newest turns at its start, after each successful compaction and when it speaks again after being cold,
|
|
13
|
+
* never in between, so it stays inside the provider-cached prefix. `home` archives the current home; `workspace` uses host membership. The memory block still
|
|
12
14
|
* goes to every world session in her workspace (`inWorkspace`), independently of the archive scope.
|
|
13
15
|
* `memoryTurns` is read each time a block is built (default 200).
|
|
16
|
+
*
|
|
17
|
+
* A session silent for `coldHours` (read at each turn start, default 24) is cold (#36): its provider cache has most
|
|
18
|
+
* likely expired (DeepSeek clears an unused one "usually within a few hours to a few days", best effort), so its next
|
|
19
|
+
* turn first summarizes the old conversation, then re-reads her memory block and prompt as a newly opened session
|
|
20
|
+
* would: that first request misses the cache anyway, and every later step carries the summary instead of the whole old
|
|
21
|
+
* conversation. A conversation in progress does not pause that long, so its cached prefix stays whole.
|
|
14
22
|
*/
|
|
15
|
-
export declare function createWorldRuntime(ctx: Context, config: WorldConfig, store: ArchiveStore, world?: WorldPromptSource, memoryTurns?: () => number): {
|
|
23
|
+
export declare function createWorldRuntime(ctx: Context, config: WorldConfig, store: ArchiveStore, world?: WorldPromptSource, memoryTurns?: () => number, coldHours?: () => number, now?: () => number): {
|
|
24
|
+
scopeToken: symbol;
|
|
16
25
|
start: (options?: {
|
|
17
26
|
fresh?: boolean;
|
|
18
27
|
}) => Promise<void>;
|
package/lib/runtime.js
CHANGED
|
@@ -1,24 +1,109 @@
|
|
|
1
|
-
import { createSystemMessage, createUserMessage, isAgentLoopRequest } from '@deepseek-ai/dsh-llm';
|
|
1
|
+
import { createSystemMessage, createUserMessage, isAgentLoopRequest, LlmError } from '@deepseek-ai/dsh-llm';
|
|
2
2
|
import "./hostContract.js";
|
|
3
3
|
import { isOrdinarySession } from "./archive.js";
|
|
4
|
+
import { compactsWhole } from "./compaction.js";
|
|
5
|
+
import { compactionFor } from "./console/homeApply.js";
|
|
4
6
|
import { Faults } from "./faults.js";
|
|
5
7
|
import { createHistory, excludePresentMessages, renderHistory } from "./history.js";
|
|
6
8
|
import { createWorldToolRegistry, memoryTools } from "./memoryTools.js";
|
|
7
|
-
import { createPromptSections } from "./promptSection.js";
|
|
8
|
-
import { belongsToWorld, createSourceArchive, inWorld } from "./sourceArchive.js";
|
|
9
|
+
import { createPromptSections, WORLD_PROMPT_PREFIX } from "./promptSection.js";
|
|
10
|
+
import { belongsToWorld, createSourceArchive, inWorld, sessionPreset } from "./sourceArchive.js";
|
|
9
11
|
import { worldNames } from "./worldPrompt.js";
|
|
10
12
|
import { reassembleOnChange } from "./worldScope.js";
|
|
11
|
-
import { DEFAULT_MEMORY_TURNS } from "./worldSwitch.js";
|
|
13
|
+
import { DEFAULT_COLD_HOURS, DEFAULT_MEMORY_TURNS } from "./worldSwitch.js";
|
|
12
14
|
const memorySource = 'dsh-world-history';
|
|
13
|
-
const
|
|
15
|
+
const isRecall = (source, worldId) => source?.kind === memorySource && (worldId === undefined || source.worldId === undefined || source.worldId === worldId);
|
|
16
|
+
function recallNodes(session, match) {
|
|
17
|
+
return session.surface.nodes.filter(seq => {
|
|
18
|
+
const event = session.eventAt(seq);
|
|
19
|
+
return event?.type === 'user/message' && match(event.data.source);
|
|
20
|
+
});
|
|
21
|
+
}
|
|
22
|
+
/** Empty system nodes retire recall from the model's context and leave the original events intact. */
|
|
23
|
+
function retireRecall(session, retiring, position) {
|
|
24
|
+
for (const seq of retiring) {
|
|
25
|
+
if (!session.surface.nodes.includes(seq))
|
|
26
|
+
continue;
|
|
27
|
+
session.append('system/message', { ...position, message: createSystemMessage('') }, { surfaceOp: { op: 'replace', startSeq: seq, endSeq: seq }, sourceEventSeqs: [seq] });
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
/** A session can outlive its world. Authorization returns false for a stopped world and undefined outside it. */
|
|
31
|
+
export function guardWorldContext(ctx, authorize) {
|
|
32
|
+
const assemblies = new WeakMap();
|
|
33
|
+
const previousPrompts = new WeakMap();
|
|
34
|
+
const revoked = (source, session) => {
|
|
35
|
+
if (source?.kind === memorySource)
|
|
36
|
+
return !session || !authorize(session, source.worldId);
|
|
37
|
+
return source?.kind === 'dsh-world-channel-context' && (!session || !authorize(session));
|
|
38
|
+
};
|
|
39
|
+
ctx.on('system-prompt/assemble', async (_assembly, context, next) => {
|
|
40
|
+
const result = await next();
|
|
41
|
+
if (context.signal && context.agent) {
|
|
42
|
+
const section = result.sections.find(section => section.name.startsWith(WORLD_PROMPT_PREFIX));
|
|
43
|
+
if (section) {
|
|
44
|
+
const worldId = section.name.slice(WORLD_PROMPT_PREFIX.length).split(':', 1)[0];
|
|
45
|
+
assemblies.set(context.signal, { worldId, token: authorize(context.agent.session, worldId) || undefined });
|
|
46
|
+
}
|
|
47
|
+
else
|
|
48
|
+
assemblies.delete(context.signal);
|
|
49
|
+
}
|
|
50
|
+
return result;
|
|
51
|
+
}, { prepend: true });
|
|
52
|
+
ctx.on('agent/pre-step', async ({ agent, signal }, next) => {
|
|
53
|
+
const decision = await next();
|
|
54
|
+
if (decision.kind !== 'enter')
|
|
55
|
+
return decision;
|
|
56
|
+
const { session } = agent;
|
|
57
|
+
const token = assemblies.get(signal)?.token;
|
|
58
|
+
const previous = previousPrompts.get(session);
|
|
59
|
+
const promptChanged = previous && (!token || previous.token !== token);
|
|
60
|
+
return promptChanged || recallNodes(session, source => revoked(source, session)).length ? { ...decision, startsRequestSeries: true } : decision;
|
|
61
|
+
});
|
|
62
|
+
ctx.on('agent/request', ({ agent: { session }, turn, step }, next) => {
|
|
63
|
+
retireRecall(session, recallNodes(session, source => revoked(source, session)), { turn, step });
|
|
64
|
+
return next();
|
|
65
|
+
});
|
|
66
|
+
ctx.on('llm/stream', async function* (request, next) {
|
|
67
|
+
const compaction = request.purpose === 'compaction';
|
|
68
|
+
if (!compaction && !isAgentLoopRequest(request)) {
|
|
69
|
+
yield* next();
|
|
70
|
+
return;
|
|
71
|
+
}
|
|
72
|
+
const session = request.sessionId ? ctx.get('sessions')?.get(request.sessionId) : undefined;
|
|
73
|
+
// Both compaction engines replay the saved prompt without assembling a new one.
|
|
74
|
+
const prompt = compaction ? session && previousPrompts.get(session) : request.signal && assemblies.get(request.signal);
|
|
75
|
+
if (!compaction && session && prompt)
|
|
76
|
+
previousPrompts.set(session, prompt);
|
|
77
|
+
const scope = session && (compaction || prompt) ? authorize(session, prompt?.worldId) : undefined;
|
|
78
|
+
const stalePrompt = prompt && (!scope || (!compaction && scope !== prompt.token));
|
|
79
|
+
const failure = { code: 'DSH_WORLD_SCOPE_CHANGED', message: compaction
|
|
80
|
+
? 'dsh-world: 世界已停止或会话已离开世界工作区,已取消压缩。'
|
|
81
|
+
: 'dsh-world: 世界权限已变化,已阻止携带旧世界上下文的请求,请重新发送。' };
|
|
82
|
+
if (scope === false || stalePrompt || request.messages.some(message => revoked(message.source, session))) {
|
|
83
|
+
yield { type: 'finish', reason: { kind: 'error', failure } };
|
|
84
|
+
return;
|
|
85
|
+
}
|
|
86
|
+
if (!compaction && session && !prompt)
|
|
87
|
+
previousPrompts.delete(session);
|
|
88
|
+
yield* next();
|
|
89
|
+
if (compaction && session && scope && authorize(session, prompt?.worldId) !== scope)
|
|
90
|
+
throw new LlmError(failure.message, failure.code);
|
|
91
|
+
});
|
|
92
|
+
}
|
|
14
93
|
/**
|
|
15
94
|
* The memory line: her conversations are archived as they happen, and every world session gets a memory
|
|
16
|
-
* block of the newest turns at its start
|
|
17
|
-
* inside the provider-cached prefix. `home` archives the current home; `workspace` uses host membership. The memory block still
|
|
95
|
+
* block of the newest turns at its start, after each successful compaction and when it speaks again after being cold,
|
|
96
|
+
* never in between, so it stays inside the provider-cached prefix. `home` archives the current home; `workspace` uses host membership. The memory block still
|
|
18
97
|
* goes to every world session in her workspace (`inWorkspace`), independently of the archive scope.
|
|
19
98
|
* `memoryTurns` is read each time a block is built (default 200).
|
|
99
|
+
*
|
|
100
|
+
* A session silent for `coldHours` (read at each turn start, default 24) is cold (#36): its provider cache has most
|
|
101
|
+
* likely expired (DeepSeek clears an unused one "usually within a few hours to a few days", best effort), so its next
|
|
102
|
+
* turn first summarizes the old conversation, then re-reads her memory block and prompt as a newly opened session
|
|
103
|
+
* would: that first request misses the cache anyway, and every later step carries the summary instead of the whole old
|
|
104
|
+
* conversation. A conversation in progress does not pause that long, so its cached prefix stays whole.
|
|
20
105
|
*/
|
|
21
|
-
export function createWorldRuntime(ctx, config, store, world, memoryTurns = () => DEFAULT_MEMORY_TURNS) {
|
|
106
|
+
export function createWorldRuntime(ctx, config, store, world, memoryTurns = () => DEFAULT_MEMORY_TURNS, coldHours = () => DEFAULT_COLD_HOURS, now = Date.now) {
|
|
22
107
|
if (config.archiveScope === 'workspace' && !world?.archiveSession)
|
|
23
108
|
throw new Error('Workspace archive requires the host workspace selection');
|
|
24
109
|
const archivedByScope = world?.archiveSession ?? ((sessionId) => config.archiveScope !== 'home' || !!world?.isHome(sessionId));
|
|
@@ -36,11 +121,12 @@ export function createWorldRuntime(ctx, config, store, world, memoryTurns = () =
|
|
|
36
121
|
const history = createHistory(store);
|
|
37
122
|
const names = () => world?.names?.() ?? world?.prompt.names ?? worldNames(config);
|
|
38
123
|
const included = (session) => inWorld(session, config, world?.inWorkspace);
|
|
124
|
+
const ownMemory = (source) => isRecall(source, config.worldId);
|
|
39
125
|
const faults = new Faults();
|
|
40
126
|
const prompts = world && createPromptSections(config, world, { logger: ctx.logger });
|
|
41
127
|
const memory = new WeakMap();
|
|
42
|
-
const
|
|
43
|
-
const tools =
|
|
128
|
+
const service = world?.memory;
|
|
129
|
+
const tools = service ? createWorldToolRegistry({ tools: inside => memoryTools(service, inside), inWorld: agent => !stopped && included(agent.session), faults, logger: ctx.logger }) : undefined;
|
|
44
130
|
/** The memory tools follow world membership, whatever the life line does. */
|
|
45
131
|
const syncTools = (agent) => !tools ? false : included(agent.session) ? tools.attach(agent) : tools.detach(agent);
|
|
46
132
|
const disposers = [];
|
|
@@ -50,10 +136,13 @@ export function createWorldRuntime(ctx, config, store, world, memoryTurns = () =
|
|
|
50
136
|
* Whether the session may carry her world: her preset, or a memory block inherited onto its surface (a delegated
|
|
51
137
|
* child of her session). Everything else is never read from disk or tracked. The check stays in memory.
|
|
52
138
|
*/
|
|
53
|
-
const mayCarryWorld = (session) => belongsToWorld(session, config) || memory.has(session) || session.surface.nodes.some(seq =>
|
|
139
|
+
const mayCarryWorld = (session) => belongsToWorld(session, config) || memory.has(session) || session.surface.nodes.some(seq => {
|
|
140
|
+
const event = session.eventAt(seq);
|
|
141
|
+
return event?.type === 'user/message' && ownMemory(event.data.source);
|
|
142
|
+
});
|
|
54
143
|
function newMemoryState(session) {
|
|
55
144
|
const inScope = included(session);
|
|
56
|
-
return { reload: true, position: { turn: 1, step: 1 }, retiring: [], inScope, restart: !inScope && belongsToWorld(session, config) };
|
|
145
|
+
return { reload: true, cold: false, position: { turn: 1, step: 1 }, retiring: [], inScope, restart: !inScope && belongsToWorld(session, config) };
|
|
57
146
|
}
|
|
58
147
|
/**
|
|
59
148
|
* Archive failures never stop her talking: they stay in the health list, and what she said meanwhile is replayed
|
|
@@ -69,8 +158,8 @@ export function createWorldRuntime(ctx, config, store, world, memoryTurns = () =
|
|
|
69
158
|
* the host only inside an open turn and step, which pre-step and attach are not, so `flushRetired` writes it from
|
|
70
159
|
* the step's request hook, after the step has started and before the request is assembled (#22).
|
|
71
160
|
*/
|
|
72
|
-
function retireMemory(session, state) {
|
|
73
|
-
const found = session
|
|
161
|
+
function retireMemory(session, state, all = false) {
|
|
162
|
+
const found = recallNodes(session, all ? source => isRecall(source) : ownMemory);
|
|
74
163
|
state.retiring = [...new Set([...state.retiring, ...found])];
|
|
75
164
|
if (found.length)
|
|
76
165
|
state.restart = true;
|
|
@@ -96,15 +185,10 @@ export function createWorldRuntime(ctx, config, store, world, memoryTurns = () =
|
|
|
96
185
|
}
|
|
97
186
|
return found.length ? found.slice(0, 8).join('、') + (found.length > 8 ? `…共 ${found.length} 个` : '') : '无';
|
|
98
187
|
}
|
|
99
|
-
/** Empty system nodes retire only our recalled blocks and derive no model message; original logs stay intact. */
|
|
100
188
|
function flushRetired(session, state, position) {
|
|
101
189
|
const retiring = state.retiring;
|
|
102
190
|
state.retiring = [];
|
|
103
|
-
|
|
104
|
-
if (!session.surface.nodes.includes(seq))
|
|
105
|
-
continue;
|
|
106
|
-
session.append('system/message', { ...position, message: createSystemMessage('') }, { surfaceOp: { op: 'replace', startSeq: seq, endSeq: seq }, sourceEventSeqs: [seq] });
|
|
107
|
-
}
|
|
191
|
+
retireRecall(session, retiring, position);
|
|
108
192
|
}
|
|
109
193
|
async function attach(agent) {
|
|
110
194
|
const { session } = agent;
|
|
@@ -117,12 +201,30 @@ export function createWorldRuntime(ctx, config, store, world, memoryTurns = () =
|
|
|
117
201
|
await archiveNow(session.id);
|
|
118
202
|
}
|
|
119
203
|
/** Retire old blocks, then admit fresh memory through the host's normal append path (#21). The caller checks the scope after the wait. */
|
|
204
|
+
/**
|
|
205
|
+
* A cold turn's first step summarizes the old conversation before anything is admitted, so the host's own context
|
|
206
|
+
* admission sees the compacted surface. Only the tool-free compaction can do this inside a turn; without it, or when it
|
|
207
|
+
* fails, the memory block and prompt are still rebuilt and the failure shows in health.
|
|
208
|
+
*/
|
|
209
|
+
async function compactCold(agent, step, pending, signal) {
|
|
210
|
+
const state = memory.get(agent.session);
|
|
211
|
+
if (!state?.cold)
|
|
212
|
+
return;
|
|
213
|
+
state.cold = false;
|
|
214
|
+
if (step !== 1 || !pending || signal.aborted || !included(agent.session))
|
|
215
|
+
return;
|
|
216
|
+
const engine = compactionFor(ctx, agent);
|
|
217
|
+
if (!compactsWhole(engine))
|
|
218
|
+
return;
|
|
219
|
+
await faults.track(`cold:${agent.id}`, `会话 ${agent.id} 久未开口后的压缩失败,已改为只重读记忆块和人设`, async () => { await engine.compactWhole(agent, signal); }).catch(() => { });
|
|
220
|
+
}
|
|
120
221
|
async function freshBlock(session, state) {
|
|
121
222
|
const turns = await history.loadRecentTurns(memoryTurns(), archivedByScope);
|
|
122
223
|
const present = new Set(session.deriveMessages().map(message => message.id));
|
|
123
224
|
const text = renderHistory(excludePresentMessages(turns, present), config.timeZone, names(), config.archiveScope === 'home');
|
|
124
|
-
|
|
125
|
-
|
|
225
|
+
// A session entering this workspace can still carry an inherited recall from another world.
|
|
226
|
+
retireMemory(session, state, included(session));
|
|
227
|
+
return text ? createUserMessage({ content: [{ type: 'text', text }], source: { kind: memorySource, form: 'recall', worldId: config.worldId } }) : undefined;
|
|
126
228
|
}
|
|
127
229
|
/** Reads what the first catch-up had to leave, once the host can say which sessions belong to her. */
|
|
128
230
|
async function retryCatchUp() {
|
|
@@ -135,6 +237,13 @@ export function createWorldRuntime(ctx, config, store, world, memoryTurns = () =
|
|
|
135
237
|
async function start(options = {}) {
|
|
136
238
|
try {
|
|
137
239
|
disposers.push(ctx.on('session/event', (session, event) => {
|
|
240
|
+
if (event.type === 'agent-preset/selected') {
|
|
241
|
+
const agent = ctx.agents.get(session.id);
|
|
242
|
+
if (agent) {
|
|
243
|
+
prompts?.add(agent);
|
|
244
|
+
syncTools(agent);
|
|
245
|
+
}
|
|
246
|
+
}
|
|
138
247
|
const state = memory.get(session);
|
|
139
248
|
const compacted = event.type === 'compaction/end' && event.data.error === undefined;
|
|
140
249
|
if (state && event.type === 'user/message' && event.data.id === state.pendingId) {
|
|
@@ -144,7 +253,13 @@ export function createWorldRuntime(ctx, config, store, world, memoryTurns = () =
|
|
|
144
253
|
if (state && compacted) {
|
|
145
254
|
state.reload = true;
|
|
146
255
|
}
|
|
147
|
-
|
|
256
|
+
// The host assembles the system prompt after turn/start, so a cold session's first request already has both.
|
|
257
|
+
const cold = !!state && event.type === 'turn/start' && state.lastRequestAt !== undefined && now() - state.lastRequestAt >= coldHours() * 60 * 60_000;
|
|
258
|
+
if (cold) {
|
|
259
|
+
state.reload = true;
|
|
260
|
+
state.cold = true;
|
|
261
|
+
}
|
|
262
|
+
if (compacted || cold)
|
|
148
263
|
prompts?.refresh(session);
|
|
149
264
|
if (!isOrdinarySession(session.header))
|
|
150
265
|
return;
|
|
@@ -166,11 +281,14 @@ export function createWorldRuntime(ctx, config, store, world, memoryTurns = () =
|
|
|
166
281
|
}
|
|
167
282
|
// Admitted ahead of the step's new input; the host's own admission order (contexts, time-context last) is kept.
|
|
168
283
|
disposers.push(ctx.on('agent/pre-step', async (payload, next) => {
|
|
169
|
-
|
|
284
|
+
await compactCold(payload.agent, payload.step, payload.messages.length, payload.signal);
|
|
285
|
+
let decision = await next();
|
|
170
286
|
const { agent, step, signal } = payload;
|
|
171
287
|
// An empty first step ends the turn; any later step runs anyway, so adding to it is safe.
|
|
172
288
|
if (decision.kind !== 'enter' || (step === 1 && !decision.messages.length) || signal.aborted || !mayCarryWorld(agent.session))
|
|
173
289
|
return decision;
|
|
290
|
+
if (prompts?.takeRestart(agent.session))
|
|
291
|
+
decision = { ...decision, startsRequestSeries: true };
|
|
174
292
|
await attach(agent);
|
|
175
293
|
const state = memory.get(agent.session);
|
|
176
294
|
const leave = () => {
|
|
@@ -208,8 +326,10 @@ export function createWorldRuntime(ctx, config, store, world, memoryTurns = () =
|
|
|
208
326
|
// The step is open here and its request is not built yet: the one place retired blocks can be written validly.
|
|
209
327
|
disposers.push(ctx.on('agent/request', async function (payload, next) {
|
|
210
328
|
const state = memory.get(payload.agent.session);
|
|
211
|
-
if (state)
|
|
329
|
+
if (state) {
|
|
212
330
|
state.position = { turn: payload.turn, step: payload.step };
|
|
331
|
+
state.lastRequestAt = now();
|
|
332
|
+
}
|
|
213
333
|
if (state?.retiring.length)
|
|
214
334
|
flushRetired(payload.agent.session, state, state.position);
|
|
215
335
|
return next();
|
|
@@ -217,7 +337,7 @@ export function createWorldRuntime(ctx, config, store, world, memoryTurns = () =
|
|
|
217
337
|
disposers.push(ctx.on('llm/stream', async function* (request, next) {
|
|
218
338
|
const agent = isAgentLoopRequest(request) && request.sessionId ? ctx.agents.get(request.sessionId) : undefined;
|
|
219
339
|
const owned = agent && included(agent.session);
|
|
220
|
-
const inRequest = agent && !owned ? request.messages.filter(message => message.source
|
|
340
|
+
const inRequest = agent && !owned ? request.messages.filter(message => ownMemory(message.source)).length : 0;
|
|
221
341
|
const placed = !!agent && !owned && !!prompts?.active(agent.session);
|
|
222
342
|
if (agent && !owned && (placed || inRequest)) {
|
|
223
343
|
const state = memory.get(agent.session);
|
|
@@ -227,7 +347,7 @@ export function createWorldRuntime(ctx, config, store, world, memoryTurns = () =
|
|
|
227
347
|
state.restart = true;
|
|
228
348
|
}
|
|
229
349
|
const reasons = [inRequest ? `请求里还带着 ${inRequest} 条世界记忆块` : '', placed ? '世界提示还挂在会话上' : ''].filter(Boolean).join(';');
|
|
230
|
-
ctx.logger.warn(`dsh-world: 阻止了会话 ${agent.id}(预设 ${agent.session
|
|
350
|
+
ctx.logger.warn(`dsh-world: 阻止了会话 ${agent.id}(预设 ${sessionPreset(agent.session) ?? '无'})的一次请求,它不在世界工作区里。原因:${reasons}。${state ? '已尝试退役记忆块' : '这个会话没有记忆状态,没法退役'};退役后会话表面上仍有的记忆节点:${memoryNodesOn(agent.session)}。DSH_WORLD_SCOPE_CHANGED`);
|
|
231
351
|
yield { type: 'finish', reason: { kind: 'error', failure: { code: 'DSH_WORLD_SCOPE_CHANGED', message: 'dsh-world: 会话已离开世界工作区,已阻止携带世界上下文的请求,请重新发送。' } } };
|
|
232
352
|
return;
|
|
233
353
|
}
|
|
@@ -243,10 +363,11 @@ export function createWorldRuntime(ctx, config, store, world, memoryTurns = () =
|
|
|
243
363
|
await archive.catchUp(options.fresh);
|
|
244
364
|
if (options.fresh)
|
|
245
365
|
for (const agent of ctx.agents.list())
|
|
246
|
-
if (
|
|
366
|
+
if (included(agent.session))
|
|
247
367
|
await archive.skip(agent.id);
|
|
248
368
|
for (const agent of ctx.agents.list()) {
|
|
249
369
|
prompts?.add(agent);
|
|
370
|
+
syncTools(agent);
|
|
250
371
|
await attach(agent);
|
|
251
372
|
}
|
|
252
373
|
}
|
|
@@ -265,5 +386,5 @@ export function createWorldRuntime(ctx, config, store, world, memoryTurns = () =
|
|
|
265
386
|
await archive.flush();
|
|
266
387
|
})();
|
|
267
388
|
}
|
|
268
|
-
return { start, retryCatchUp, refreshPrompt: (session) => { prompts?.refresh(session); }, flush: archive.flush, stop, faults: () => [...faults.list(), ...archive.faults()] };
|
|
389
|
+
return { scopeToken: Symbol(), start, retryCatchUp, refreshPrompt: (session) => { prompts?.refresh(session); }, flush: archive.flush, stop, faults: () => [...faults.list(), ...archive.faults()] };
|
|
269
390
|
}
|
package/lib/sourceArchive.d.ts
CHANGED
|
@@ -2,11 +2,13 @@ import type { Context } from '@deepseek-ai/cordis';
|
|
|
2
2
|
import { type Session } from '@deepseek-ai/dsh-session';
|
|
3
3
|
import type { ArchiveStore } from './store.ts';
|
|
4
4
|
import type { WorldConfig } from './types.ts';
|
|
5
|
+
/** The header is creation-time metadata; later selections in the log decide the current preset. */
|
|
6
|
+
export declare function sessionPreset(session: Session): string | undefined;
|
|
5
7
|
/** Unreadable logs are isolated per source; their archive gaps remain visible until replay succeeds. */
|
|
6
8
|
export declare function isCorruptSessionLog(error: unknown): boolean;
|
|
7
|
-
export declare function belongsToWorld(session:
|
|
9
|
+
export declare function belongsToWorld(session: Session, config: WorldConfig): boolean;
|
|
8
10
|
/** One of her sessions that is also in her room's workspace; without a membership test, any of her sessions. */
|
|
9
|
-
export declare function inWorld(session:
|
|
11
|
+
export declare function inWorld(session: Session, config: WorldConfig, inWorkspace?: (sessionId: string) => boolean): boolean;
|
|
10
12
|
export declare const isNotFound: (error: unknown) => boolean;
|
|
11
13
|
/**
|
|
12
14
|
* Copies her conversations from the host's session logs into the archive. Each session is replayed from where
|
package/lib/sourceArchive.js
CHANGED
|
@@ -1,16 +1,30 @@
|
|
|
1
|
-
import { SessionId } from '@deepseek-ai/dsh-session';
|
|
1
|
+
import { SessionId, SessionLogOffset } from '@deepseek-ai/dsh-session';
|
|
2
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;
|
|
6
|
+
const sessionPresets = new WeakMap();
|
|
7
|
+
/** The header is creation-time metadata; later selections in the log decide the current preset. */
|
|
8
|
+
export function sessionPreset(session) {
|
|
9
|
+
const state = sessionPresets.get(session) ?? { nextSeq: 0, preset: session.header.agentPreset };
|
|
10
|
+
const end = session.seq;
|
|
11
|
+
for (let from = state.nextSeq; from < end; from += pageSize) {
|
|
12
|
+
for (const event of session.snapshotEvents(SessionLogOffset(from), SessionLogOffset(Math.min(from + pageSize, end)))) {
|
|
13
|
+
if (event.type === 'agent-preset/selected')
|
|
14
|
+
state.preset = event.data.agentPreset;
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
state.nextSeq = end;
|
|
18
|
+
sessionPresets.set(session, state);
|
|
19
|
+
return state.preset;
|
|
20
|
+
}
|
|
6
21
|
/** Unreadable logs are isolated per source; their archive gaps remain visible until replay succeeds. */
|
|
7
22
|
export function isCorruptSessionLog(error) {
|
|
8
23
|
const text = error instanceof Error ? `${error.name} ${error.message}` : String(error ?? '');
|
|
9
|
-
return /stored log is corrupt|SessionFormatError|does not match an open turn/i.test(text);
|
|
24
|
+
return /stored log is corrupt|SessionFormatError|does not match (?:an|the) open turn/i.test(text);
|
|
10
25
|
}
|
|
11
26
|
export function belongsToWorld(session, config) {
|
|
12
|
-
|
|
13
|
-
return header.agentPreset === config.agentPreset && isOrdinarySession(header);
|
|
27
|
+
return isOrdinarySession(session.header) && sessionPreset(session) === config.agentPreset;
|
|
14
28
|
}
|
|
15
29
|
/** One of her sessions that is also in her room's workspace; without a membership test, any of her sessions. */
|
|
16
30
|
export function inWorld(session, config, inWorkspace) {
|
|
@@ -54,7 +68,7 @@ export function createSourceArchive(ctx, config, store, archived = () => true) {
|
|
|
54
68
|
let { nextSeq, turn } = store.progress(id);
|
|
55
69
|
while (true) {
|
|
56
70
|
const { events } = await handle.read(nextSeq, pageSize);
|
|
57
|
-
if (!events.length)
|
|
71
|
+
if (!events.length || (!skip && !archived(sessionId)))
|
|
58
72
|
break;
|
|
59
73
|
const records = events.flatMap(event => {
|
|
60
74
|
if (event.type === 'turn/start')
|
package/lib/store.js
CHANGED
|
@@ -3,10 +3,11 @@ import { closeSync, existsSync, fstatSync, fsyncSync, ftruncateSync, mkdirSync,
|
|
|
3
3
|
import { join } from 'node:path';
|
|
4
4
|
import { formatLocalTime } from "./timeContext.js";
|
|
5
5
|
import { createMemoryStore } from "./memoryStore.js";
|
|
6
|
+
import { validWorldId } from "./worldRoutes.js";
|
|
6
7
|
const pageSize = 128;
|
|
7
8
|
export function createArchiveStore(config) {
|
|
8
9
|
// The world id becomes a directory name.
|
|
9
|
-
if (
|
|
10
|
+
if (!validWorldId(config.worldId))
|
|
10
11
|
throw new TypeError('dsh-world: invalid worldId');
|
|
11
12
|
const worldRoot = join(config.root, 'worlds', config.worldId);
|
|
12
13
|
const directory = join(worldRoot, 'conversations');
|
package/lib/types.d.ts
CHANGED
|
@@ -54,7 +54,7 @@ export interface WorldConfig {
|
|
|
54
54
|
mutedUntil?: string;
|
|
55
55
|
/** SnowLuma 装在哪;空着就靠猜(D:\SnowLuma、C:\SnowLuma、~/SnowLuma)。 */
|
|
56
56
|
snowlumaHome?: string;
|
|
57
|
-
/** 看门狗:通道开着时盯住 wsUrl
|
|
57
|
+
/** 看门狗:通道开着时盯住 wsUrl 的端口,不通且没有实例时按 snowlumaHome 拉起。默认开。 */
|
|
58
58
|
supervise?: boolean;
|
|
59
59
|
/** 阳台:让这台机器上别的程序能跟家里说话(一行一条 JSON 的 WebSocket)。port 为 0 就不开。 */
|
|
60
60
|
bridge?: {
|
package/lib/worldPrompt.d.ts
CHANGED
|
@@ -43,9 +43,8 @@ export declare function readTemplate(file: string | undefined): TemplateRead;
|
|
|
43
43
|
*/
|
|
44
44
|
export declare function renderTemplate(template: string, flags: Record<string, boolean>, values: Record<string, string>): string;
|
|
45
45
|
/**
|
|
46
|
-
* The one world prompt every world session carries in its system prompt.
|
|
47
|
-
*
|
|
48
|
-
* line's tools live in the home alone; the template tells other sessions where to find them.
|
|
46
|
+
* The one world prompt every world session carries in its system prompt. The world line's tools live in the home alone;
|
|
47
|
+
* the template tells other sessions where to find them.
|
|
49
48
|
*/
|
|
50
49
|
export declare function renderWorldPrompt(prompt: WorldPrompt, template: string, self: {
|
|
51
50
|
file: string;
|
package/lib/worldPrompt.js
CHANGED
|
@@ -42,9 +42,8 @@ export function renderTemplate(template, flags, values) {
|
|
|
42
42
|
return text.replace(/\{\{(\w+)\}\}/g, (tag, name) => values[name] ?? tag).replace(/[ \t]+\n/g, '\n').replace(/\n{3,}/g, '\n\n').trim();
|
|
43
43
|
}
|
|
44
44
|
/**
|
|
45
|
-
* The one world prompt every world session carries in its system prompt.
|
|
46
|
-
*
|
|
47
|
-
* line's tools live in the home alone; the template tells other sessions where to find them.
|
|
45
|
+
* The one world prompt every world session carries in its system prompt. The world line's tools live in the home alone;
|
|
46
|
+
* the template tells other sessions where to find them.
|
|
48
47
|
*/
|
|
49
48
|
export function renderWorldPrompt(prompt, template, self, home) {
|
|
50
49
|
const { life, names } = prompt;
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { IncomingMessage, ServerResponse } from 'node:http';
|
|
2
|
+
export declare const WORLDS_PATH = "/dsh-world/worlds";
|
|
3
|
+
export declare const validWorldId: (id: string) => boolean;
|
|
4
|
+
export declare const worldPath: (id: string) => string;
|
|
5
|
+
export declare function worldListRoute(worlds: ReadonlyMap<string, readonly string[]>): {
|
|
6
|
+
kind: "exact";
|
|
7
|
+
path: string;
|
|
8
|
+
handler(req: IncomingMessage, res: ServerResponse): void;
|
|
9
|
+
};
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { knownHost, sendJson } from "./http.js";
|
|
2
|
+
export const WORLDS_PATH = '/dsh-world/worlds';
|
|
3
|
+
export const validWorldId = (id) => /^[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}$/.test(id);
|
|
4
|
+
export const worldPath = (id) => `${WORLDS_PATH}/${id}`;
|
|
5
|
+
export function worldListRoute(worlds) {
|
|
6
|
+
return {
|
|
7
|
+
kind: 'exact', path: WORLDS_PATH,
|
|
8
|
+
handler(req, res) {
|
|
9
|
+
const ids = [...worlds].filter(([, hosts]) => knownHost(req.headers.host, hosts)).map(([id]) => id).sort();
|
|
10
|
+
if (!ids.length || req.headers['sec-fetch-site'] === 'cross-site') {
|
|
11
|
+
sendJson(res, { status: 403, body: { error: 'forbidden' } });
|
|
12
|
+
return;
|
|
13
|
+
}
|
|
14
|
+
if (req.method !== 'GET') {
|
|
15
|
+
sendJson(res, { status: 405, body: { error: 'method not allowed' }, headers: { allow: 'GET' } });
|
|
16
|
+
return;
|
|
17
|
+
}
|
|
18
|
+
const { searchParams } = new URL(req.url ?? WORLDS_PATH, 'http://localhost');
|
|
19
|
+
const limit = Number(searchParams.get('limit') ?? 20), offset = Number(searchParams.get('offset') ?? 0);
|
|
20
|
+
if (!Number.isSafeInteger(limit) || limit < 1 || limit > 100 || !Number.isSafeInteger(offset) || offset < 0) {
|
|
21
|
+
sendJson(res, { status: 400, body: { error: '世界列表分页参数无效' } });
|
|
22
|
+
return;
|
|
23
|
+
}
|
|
24
|
+
const worldIds = ids.slice(offset, offset + limit);
|
|
25
|
+
const nextOffset = offset + worldIds.length < ids.length ? offset + worldIds.length : null;
|
|
26
|
+
sendJson(res, { status: 200, body: { worldIds, nextOffset } });
|
|
27
|
+
},
|
|
28
|
+
};
|
|
29
|
+
}
|
package/lib/worldScope.d.ts
CHANGED
|
@@ -3,7 +3,7 @@ import type { Agent } from '@deepseek-ai/dsh-agent';
|
|
|
3
3
|
import type { Session } from '@deepseek-ai/dsh-session';
|
|
4
4
|
import type { ToolDefinition } from '@deepseek-ai/dsh-tools';
|
|
5
5
|
/**
|
|
6
|
-
* Her world
|
|
6
|
+
* Her world and persona reach only her preset's sessions in her room's workspace. A
|
|
7
7
|
* session can join or leave the workspace at any time, so every way in checks again where it matters: before an
|
|
8
8
|
* injection, after every wait, and when a tool runs.
|
|
9
9
|
*/
|
|
@@ -13,10 +13,10 @@ export declare class OutsideWorldError extends Error {
|
|
|
13
13
|
}
|
|
14
14
|
/** The agent, if it is (still) in her world; without a predicate every agent is. */
|
|
15
15
|
export declare function admit(inWorld: InWorld | undefined, agent: Agent): Agent;
|
|
16
|
-
/** The
|
|
17
|
-
export declare function
|
|
16
|
+
/** The same scope check controls step admission and execution; older hosts ignore the registration condition. */
|
|
17
|
+
export declare function registerScopedTool(agent: Agent, tool: ToolDefinition, inside: () => boolean, left?: () => void): () => void;
|
|
18
18
|
/**
|
|
19
|
-
*
|
|
20
|
-
*
|
|
19
|
+
* DSH 0.2.2 selects tools before prompt assembly, so synchronize at turn start and between steps as well.
|
|
20
|
+
* The assembly check still catches membership changes while a request is being prepared.
|
|
21
21
|
*/
|
|
22
22
|
export declare function reassembleOnChange(ctx: Context, sync: (agent: Agent) => boolean): () => void;
|
package/lib/worldScope.js
CHANGED
|
@@ -7,20 +7,29 @@ export function admit(inWorld, agent) {
|
|
|
7
7
|
throw new OutsideWorldError();
|
|
8
8
|
return agent;
|
|
9
9
|
}
|
|
10
|
-
/** The
|
|
11
|
-
export function
|
|
12
|
-
|
|
10
|
+
/** The same scope check controls step admission and execution; older hosts ignore the registration condition. */
|
|
11
|
+
export function registerScopedTool(agent, tool, inside, left) {
|
|
12
|
+
const register = agent.ctx.tools.register.bind(agent.ctx.tools);
|
|
13
|
+
return register({ ...tool, execute: (args, exec) => {
|
|
13
14
|
if (!inside()) {
|
|
14
15
|
left?.();
|
|
15
16
|
throw new OutsideWorldError();
|
|
16
17
|
}
|
|
17
18
|
return tool.execute(args, exec);
|
|
18
|
-
} };
|
|
19
|
+
} }, { when: inside });
|
|
19
20
|
}
|
|
20
21
|
/**
|
|
21
|
-
*
|
|
22
|
-
*
|
|
22
|
+
* DSH 0.2.2 selects tools before prompt assembly, so synchronize at turn start and between steps as well.
|
|
23
|
+
* The assembly check still catches membership changes while a request is being prepared.
|
|
23
24
|
*/
|
|
24
25
|
export function reassembleOnChange(ctx, sync) {
|
|
25
|
-
|
|
26
|
+
const beforeStep = ctx.on('session/event', (session, event) => {
|
|
27
|
+
if (event.type !== 'turn/start' && event.type !== 'step/end')
|
|
28
|
+
return;
|
|
29
|
+
const agent = ctx.get('agents')?.get(session.id);
|
|
30
|
+
if (agent)
|
|
31
|
+
sync(agent);
|
|
32
|
+
});
|
|
33
|
+
const assemble = ctx.on('system-prompt/assemble', (_assembly, context, next) => context.agent && sync(context.agent) ? context.agent.ctx.systemPrompt.assemble(context) : next());
|
|
34
|
+
return () => { beforeStep(); assemble(); };
|
|
26
35
|
}
|
package/lib/worldSwitch.d.ts
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import { type MemoryArchiveScope } from './archiveSelection.ts';
|
|
2
2
|
/** How many of the newest turns the memory block carries when nothing else is set. */
|
|
3
3
|
export declare const DEFAULT_MEMORY_TURNS = 200;
|
|
4
|
+
/** Hours a session stays silent before its next turn re-reads her memory block and prompt (#36); see `runtime.ts`. */
|
|
5
|
+
export declare const DEFAULT_COLD_HOURS = 24, MAX_COLD_HOURS = 720;
|
|
4
6
|
/** WeChat group messages read before a mention, and seconds a private image waits for its companions. */
|
|
5
7
|
export declare const DEFAULT_WECHAT_CONTEXT = 5, MAX_WECHAT_CONTEXT = 20;
|
|
6
8
|
export declare const DEFAULT_WECHAT_BUFFER_SECONDS = 3, MAX_WECHAT_BUFFER_SECONDS = 30;
|
|
@@ -17,7 +19,7 @@ export declare function createWorldSwitch(worldDir: string, configuredScope?: Me
|
|
|
17
19
|
setArchiveScope(scope: MemoryArchiveScope): void;
|
|
18
20
|
workspacePermission: () => string;
|
|
19
21
|
setWorkspacePermission(permission: string): void;
|
|
20
|
-
/**
|
|
22
|
+
/** Compact the home after the evening look back unless the partner turns it off. */
|
|
21
23
|
compactAfterReview: () => boolean;
|
|
22
24
|
setCompactAfterReview(on: boolean): void;
|
|
23
25
|
/** Whether the profile has been switched to the tool-free compaction (by this plugin or by hand); asked once, so putting the stock one back sticks. */
|
|
@@ -31,6 +33,9 @@ export declare function createWorldSwitch(worldDir: string, configuredScope?: Me
|
|
|
31
33
|
/** Turns in her memory block; read when a block is built, so a change shows from the next session start or compaction. */
|
|
32
34
|
memoryTurns: () => number;
|
|
33
35
|
setMemoryTurns(turns: number | undefined): void;
|
|
36
|
+
/** Read at every turn start, so a change applies from the next turn of each session. */
|
|
37
|
+
coldHours: () => number;
|
|
38
|
+
setColdHours(hours: number | undefined): void;
|
|
34
39
|
/**
|
|
35
40
|
* The console's switches for the WeChat and QQ modules; both are off until someone turns them on. QQ's SDK is an
|
|
36
41
|
* optional dependency, so its code is not even loaded before then. WeChat used to default to on, so a world that
|
|
@@ -58,8 +63,8 @@ export declare function createWorldSwitch(worldDir: string, configuredScope?: Me
|
|
|
58
63
|
bufferSeconds?: number | null;
|
|
59
64
|
}): void;
|
|
60
65
|
};
|
|
61
|
-
export type WorldSwitch = ReturnType<typeof createWorldSwitch>;
|
|
62
66
|
export declare const validTurns: (value: unknown) => value is number;
|
|
67
|
+
export declare const validColdHours: (value: unknown) => value is number;
|
|
63
68
|
export declare const validWorkspacePermission: (value: unknown) => value is string;
|
|
64
69
|
export declare const validWechatContext: (value: unknown) => value is number;
|
|
65
70
|
export declare const validWechatBuffer: (value: unknown) => value is number;
|