dsh-world 0.7.2 → 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.
Files changed (68) hide show
  1. package/CHANGELOG.md +394 -379
  2. package/INSTALL.md +314 -314
  3. package/LICENSE +21 -21
  4. package/NOTES.md +21 -13
  5. package/README.md +20 -6
  6. package/client/index.js +74 -27
  7. package/cordis.patch.yml +6 -6
  8. package/lib/archiveSelection.d.ts +6 -2
  9. package/lib/archiveSelection.js +21 -12
  10. package/lib/compaction.d.ts +7 -0
  11. package/lib/compaction.js +16 -7
  12. package/lib/console/routes.d.ts +2 -3
  13. package/lib/console/routes.js +7 -8
  14. package/lib/console/snapshot.d.ts +1 -3
  15. package/lib/console/snapshot.js +0 -3
  16. package/lib/ecosystem/bridge/bridge.d.ts +5 -0
  17. package/lib/ecosystem/bridge/bridge.js +2 -1
  18. package/lib/ecosystem/bridge/route.d.ts +4 -6
  19. package/lib/ecosystem/bridge/route.js +34 -58
  20. package/lib/ecosystem/qq/panel.d.ts +0 -1
  21. package/lib/ecosystem/qq/route.d.ts +6 -7
  22. package/lib/ecosystem/qq/route.js +10 -10
  23. package/lib/ecosystem/qq/snowluma-start.d.ts +1 -0
  24. package/lib/ecosystem/qq/snowluma-start.js +41 -8
  25. package/lib/ecosystem/qq/supervisor.d.ts +1 -2
  26. package/lib/ecosystem/qq/supervisor.js +4 -2
  27. package/lib/ecosystem/qq-native/index.js +2 -0
  28. package/lib/ecosystem/qq-native/native-bridge.d.ts +0 -1
  29. package/lib/ecosystem/qq-native/native-bridge.js +0 -2
  30. package/lib/ecosystem/qq-native/snowluma.js +11 -2
  31. package/lib/ecosystem/wechat/index.d.ts +0 -1
  32. package/lib/ecosystem/wechat/index.js +6 -5
  33. package/lib/hostContract.d.ts +13 -0
  34. package/lib/index.js +106 -45
  35. package/lib/life/toolRegistry.js +2 -2
  36. package/lib/memoryFiles.d.ts +0 -1
  37. package/lib/memoryStore.d.ts +0 -1
  38. package/lib/memoryStore.js +0 -1
  39. package/lib/memoryTools.d.ts +0 -1
  40. package/lib/memoryTools.js +2 -3
  41. package/lib/promptSection.d.ts +7 -5
  42. package/lib/promptSection.js +74 -28
  43. package/lib/runtime.d.ts +6 -2
  44. package/lib/runtime.js +136 -26
  45. package/lib/sourceArchive.d.ts +4 -2
  46. package/lib/sourceArchive.js +18 -4
  47. package/lib/store.js +2 -1
  48. package/lib/types.d.ts +1 -1
  49. package/lib/worldPrompt.d.ts +2 -3
  50. package/lib/worldPrompt.js +2 -3
  51. package/lib/worldRoutes.d.ts +9 -0
  52. package/lib/worldRoutes.js +29 -0
  53. package/lib/worldScope.d.ts +5 -5
  54. package/lib/worldScope.js +16 -7
  55. package/lib/worldSwitch.d.ts +1 -2
  56. package/lib/worldSwitch.js +1 -1
  57. package/package.json +17 -16
  58. package/scripts/compact-home.mjs +29 -29
  59. package/scripts/enable-tool-free-compaction.ps1 +33 -33
  60. package/scripts/import-stickers.mjs +17 -17
  61. package/scripts/update-world.mjs +2 -2
  62. package/src/ecosystem/README.md +1 -1
  63. package/src/ecosystem/wechat/windows/README.md +2 -2
  64. package/src/ecosystem/wechat/windows/adapter.py +4 -2
  65. package/src/ecosystem/wechat/windows/engine/profiles.json +142 -142
  66. package/src/ecosystem/wechat/windows/presence.py +109 -109
  67. package/templates/alarm.md +2 -2
  68. package/templates/world-prompt.md +8 -2
package/lib/runtime.js CHANGED
@@ -1,16 +1,95 @@
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
13
  import { DEFAULT_COLD_HOURS, DEFAULT_MEMORY_TURNS } from "./worldSwitch.js";
12
14
  const memorySource = 'dsh-world-history';
13
- const isMemoryBlock = (event) => event?.type === 'user/message' && event.data.source.kind === memorySource;
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
95
  * block of the newest turns at its start, after each successful compaction and when it speaks again after being cold,
@@ -20,8 +99,9 @@ const isMemoryBlock = (event) => event?.type === 'user/message' && event.data.so
20
99
  *
21
100
  * A session silent for `coldHours` (read at each turn start, default 24) is cold (#36): its provider cache has most
22
101
  * likely expired (DeepSeek clears an unused one "usually within a few hours to a few days", best effort), so its next
23
- * turn re-reads her memory block and prompt as a newly opened session would, at the cost of at most one uncached
24
- * request. A conversation in progress does not pause that long, so its cached prefix stays whole.
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.
25
105
  */
26
106
  export function createWorldRuntime(ctx, config, store, world, memoryTurns = () => DEFAULT_MEMORY_TURNS, coldHours = () => DEFAULT_COLD_HOURS, now = Date.now) {
27
107
  if (config.archiveScope === 'workspace' && !world?.archiveSession)
@@ -41,11 +121,12 @@ export function createWorldRuntime(ctx, config, store, world, memoryTurns = () =
41
121
  const history = createHistory(store);
42
122
  const names = () => world?.names?.() ?? world?.prompt.names ?? worldNames(config);
43
123
  const included = (session) => inWorld(session, config, world?.inWorkspace);
124
+ const ownMemory = (source) => isRecall(source, config.worldId);
44
125
  const faults = new Faults();
45
126
  const prompts = world && createPromptSections(config, world, { logger: ctx.logger });
46
127
  const memory = new WeakMap();
47
- const toolSets = [world?.memory ? (inside) => memoryTools(world.memory, inside) : undefined].filter(make => !!make);
48
- const tools = toolSets.length ? createWorldToolRegistry({ tools: inside => toolSets.flatMap(make => make(inside)), inWorld: agent => !stopped && included(agent.session), faults, logger: ctx.logger }) : undefined;
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;
49
130
  /** The memory tools follow world membership, whatever the life line does. */
50
131
  const syncTools = (agent) => !tools ? false : included(agent.session) ? tools.attach(agent) : tools.detach(agent);
51
132
  const disposers = [];
@@ -55,10 +136,13 @@ export function createWorldRuntime(ctx, config, store, world, memoryTurns = () =
55
136
  * Whether the session may carry her world: her preset, or a memory block inherited onto its surface (a delegated
56
137
  * child of her session). Everything else is never read from disk or tracked. The check stays in memory.
57
138
  */
58
- const mayCarryWorld = (session) => belongsToWorld(session, config) || memory.has(session) || session.surface.nodes.some(seq => isMemoryBlock(session.eventAt(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
+ });
59
143
  function newMemoryState(session) {
60
144
  const inScope = included(session);
61
- 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) };
62
146
  }
63
147
  /**
64
148
  * Archive failures never stop her talking: they stay in the health list, and what she said meanwhile is replayed
@@ -74,8 +158,8 @@ export function createWorldRuntime(ctx, config, store, world, memoryTurns = () =
74
158
  * the host only inside an open turn and step, which pre-step and attach are not, so `flushRetired` writes it from
75
159
  * the step's request hook, after the step has started and before the request is assembled (#22).
76
160
  */
77
- function retireMemory(session, state) {
78
- const found = session.surface.nodes.filter(seq => isMemoryBlock(session.eventAt(seq)));
161
+ function retireMemory(session, state, all = false) {
162
+ const found = recallNodes(session, all ? source => isRecall(source) : ownMemory);
79
163
  state.retiring = [...new Set([...state.retiring, ...found])];
80
164
  if (found.length)
81
165
  state.restart = true;
@@ -101,15 +185,10 @@ export function createWorldRuntime(ctx, config, store, world, memoryTurns = () =
101
185
  }
102
186
  return found.length ? found.slice(0, 8).join('、') + (found.length > 8 ? `…共 ${found.length} 个` : '') : '无';
103
187
  }
104
- /** Empty system nodes retire only our recalled blocks and derive no model message; original logs stay intact. */
105
188
  function flushRetired(session, state, position) {
106
189
  const retiring = state.retiring;
107
190
  state.retiring = [];
108
- for (const seq of retiring) {
109
- if (!session.surface.nodes.includes(seq))
110
- continue;
111
- session.append('system/message', { ...position, message: createSystemMessage('') }, { surfaceOp: { op: 'replace', startSeq: seq, endSeq: seq }, sourceEventSeqs: [seq] });
112
- }
191
+ retireRecall(session, retiring, position);
113
192
  }
114
193
  async function attach(agent) {
115
194
  const { session } = agent;
@@ -122,12 +201,30 @@ export function createWorldRuntime(ctx, config, store, world, memoryTurns = () =
122
201
  await archiveNow(session.id);
123
202
  }
124
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
+ }
125
221
  async function freshBlock(session, state) {
126
222
  const turns = await history.loadRecentTurns(memoryTurns(), archivedByScope);
127
223
  const present = new Set(session.deriveMessages().map(message => message.id));
128
224
  const text = renderHistory(excludePresentMessages(turns, present), config.timeZone, names(), config.archiveScope === 'home');
129
- retireMemory(session, state);
130
- return text ? createUserMessage({ content: [{ type: 'text', text }], source: { kind: memorySource, form: 'recall' } }) : undefined;
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;
131
228
  }
132
229
  /** Reads what the first catch-up had to leave, once the host can say which sessions belong to her. */
133
230
  async function retryCatchUp() {
@@ -140,6 +237,13 @@ export function createWorldRuntime(ctx, config, store, world, memoryTurns = () =
140
237
  async function start(options = {}) {
141
238
  try {
142
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
+ }
143
247
  const state = memory.get(session);
144
248
  const compacted = event.type === 'compaction/end' && event.data.error === undefined;
145
249
  if (state && event.type === 'user/message' && event.data.id === state.pendingId) {
@@ -151,8 +255,10 @@ export function createWorldRuntime(ctx, config, store, world, memoryTurns = () =
151
255
  }
152
256
  // The host assembles the system prompt after turn/start, so a cold session's first request already has both.
153
257
  const cold = !!state && event.type === 'turn/start' && state.lastRequestAt !== undefined && now() - state.lastRequestAt >= coldHours() * 60 * 60_000;
154
- if (cold)
258
+ if (cold) {
155
259
  state.reload = true;
260
+ state.cold = true;
261
+ }
156
262
  if (compacted || cold)
157
263
  prompts?.refresh(session);
158
264
  if (!isOrdinarySession(session.header))
@@ -175,11 +281,14 @@ export function createWorldRuntime(ctx, config, store, world, memoryTurns = () =
175
281
  }
176
282
  // Admitted ahead of the step's new input; the host's own admission order (contexts, time-context last) is kept.
177
283
  disposers.push(ctx.on('agent/pre-step', async (payload, next) => {
178
- const decision = await next();
284
+ await compactCold(payload.agent, payload.step, payload.messages.length, payload.signal);
285
+ let decision = await next();
179
286
  const { agent, step, signal } = payload;
180
287
  // An empty first step ends the turn; any later step runs anyway, so adding to it is safe.
181
288
  if (decision.kind !== 'enter' || (step === 1 && !decision.messages.length) || signal.aborted || !mayCarryWorld(agent.session))
182
289
  return decision;
290
+ if (prompts?.takeRestart(agent.session))
291
+ decision = { ...decision, startsRequestSeries: true };
183
292
  await attach(agent);
184
293
  const state = memory.get(agent.session);
185
294
  const leave = () => {
@@ -228,7 +337,7 @@ export function createWorldRuntime(ctx, config, store, world, memoryTurns = () =
228
337
  disposers.push(ctx.on('llm/stream', async function* (request, next) {
229
338
  const agent = isAgentLoopRequest(request) && request.sessionId ? ctx.agents.get(request.sessionId) : undefined;
230
339
  const owned = agent && included(agent.session);
231
- const inRequest = agent && !owned ? request.messages.filter(message => message.source?.kind === memorySource).length : 0;
340
+ const inRequest = agent && !owned ? request.messages.filter(message => ownMemory(message.source)).length : 0;
232
341
  const placed = !!agent && !owned && !!prompts?.active(agent.session);
233
342
  if (agent && !owned && (placed || inRequest)) {
234
343
  const state = memory.get(agent.session);
@@ -238,7 +347,7 @@ export function createWorldRuntime(ctx, config, store, world, memoryTurns = () =
238
347
  state.restart = true;
239
348
  }
240
349
  const reasons = [inRequest ? `请求里还带着 ${inRequest} 条世界记忆块` : '', placed ? '世界提示还挂在会话上' : ''].filter(Boolean).join(';');
241
- ctx.logger.warn(`dsh-world: 阻止了会话 ${agent.id}(预设 ${agent.session.header.agentPreset ?? '无'})的一次请求,它不在世界工作区里。原因:${reasons}。${state ? '已尝试退役记忆块' : '这个会话没有记忆状态,没法退役'};退役后会话表面上仍有的记忆节点:${memoryNodesOn(agent.session)}。DSH_WORLD_SCOPE_CHANGED`);
350
+ ctx.logger.warn(`dsh-world: 阻止了会话 ${agent.id}(预设 ${sessionPreset(agent.session) ?? '无'})的一次请求,它不在世界工作区里。原因:${reasons}。${state ? '已尝试退役记忆块' : '这个会话没有记忆状态,没法退役'};退役后会话表面上仍有的记忆节点:${memoryNodesOn(agent.session)}。DSH_WORLD_SCOPE_CHANGED`);
242
351
  yield { type: 'finish', reason: { kind: 'error', failure: { code: 'DSH_WORLD_SCOPE_CHANGED', message: 'dsh-world: 会话已离开世界工作区,已阻止携带世界上下文的请求,请重新发送。' } } };
243
352
  return;
244
353
  }
@@ -254,10 +363,11 @@ export function createWorldRuntime(ctx, config, store, world, memoryTurns = () =
254
363
  await archive.catchUp(options.fresh);
255
364
  if (options.fresh)
256
365
  for (const agent of ctx.agents.list())
257
- if (belongsToWorld(agent.session, config))
366
+ if (included(agent.session))
258
367
  await archive.skip(agent.id);
259
368
  for (const agent of ctx.agents.list()) {
260
369
  prompts?.add(agent);
370
+ syncTools(agent);
261
371
  await attach(agent);
262
372
  }
263
373
  }
@@ -276,5 +386,5 @@ export function createWorldRuntime(ctx, config, store, world, memoryTurns = () =
276
386
  await archive.flush();
277
387
  })();
278
388
  }
279
- 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()] };
280
390
  }
@@ -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: Pick<Session, 'header'>, config: WorldConfig): boolean;
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: Pick<Session, 'header' | 'id'>, config: WorldConfig, inWorkspace?: (sessionId: string) => boolean): boolean;
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
@@ -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
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
- const header = session.header;
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 (!/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}$/.test(config.worldId))
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 的端口,不通就按 snowlumaHome 把 SnowLuma 拉起来。默认开。 */
57
+ /** 看门狗:通道开着时盯住 wsUrl 的端口,不通且没有实例时按 snowlumaHome 拉起。默认开。 */
58
58
  supervise?: boolean;
59
59
  /** 阳台:让这台机器上别的程序能跟家里说话(一行一条 JSON 的 WebSocket)。port 为 0 就不开。 */
60
60
  bridge?: {
@@ -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. `template` and `self` are read at
47
- * session start, after compaction or on explicit console application, so ordinary saves keep the cached prefix. The world
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;
@@ -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. `template` and `self` are read at
46
- * session start, after compaction or on explicit console application, so ordinary saves keep the cached prefix. The world
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
+ }
@@ -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 reaches only the sessions of her room's workspace (plus her persona, which follows the preset). A
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 tool, refusing to run once its agent has left her world; `left` lets the owner take it away. */
17
- export declare function scopedTool(tool: ToolDefinition, inside: () => boolean, left?: () => void): ToolDefinition;
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
- * Membership can change after `agent/created`, so whatever a session's world providers depend on is synced as its
20
- * system prompt is assembled; when `sync` changed something, the prompt is assembled again to include it.
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 tool, refusing to run once its agent has left her world; `left` lets the owner take it away. */
11
- export function scopedTool(tool, inside, left) {
12
- return { ...tool, execute: (args, exec) => {
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
- * Membership can change after `agent/created`, so whatever a session's world providers depend on is synced as its
22
- * system prompt is assembled; when `sync` changed something, the prompt is assembled again to include it.
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
- return ctx.on('system-prompt/assemble', (_assembly, context, next) => context.agent && sync(context.agent) ? context.agent.ctx.systemPrompt.assemble(context) : next());
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
  }
@@ -19,7 +19,7 @@ export declare function createWorldSwitch(worldDir: string, configuredScope?: Me
19
19
  setArchiveScope(scope: MemoryArchiveScope): void;
20
20
  workspacePermission: () => string;
21
21
  setWorkspacePermission(permission: string): void;
22
- /** After each evening look back her home is applied and compacted, so the 我是谁 she has just rewritten takes effect; on unless the partner turns it off. */
22
+ /** Compact the home after the evening look back unless the partner turns it off. */
23
23
  compactAfterReview: () => boolean;
24
24
  setCompactAfterReview(on: boolean): void;
25
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. */
@@ -63,7 +63,6 @@ export declare function createWorldSwitch(worldDir: string, configuredScope?: Me
63
63
  bufferSeconds?: number | null;
64
64
  }): void;
65
65
  };
66
- export type WorldSwitch = ReturnType<typeof createWorldSwitch>;
67
66
  export declare const validTurns: (value: unknown) => value is number;
68
67
  export declare const validColdHours: (value: unknown) => value is number;
69
68
  export declare const validWorkspacePermission: (value: unknown) => value is string;
@@ -55,7 +55,7 @@ export function createWorldSwitch(worldDir, configuredScope = 'workspace', confi
55
55
  throw new Error('工作区权限必须为非空字符串');
56
56
  save({ ...settings, workspacePermission: permission });
57
57
  },
58
- /** After each evening look back her home is applied and compacted, so the 我是谁 she has just rewritten takes effect; on unless the partner turns it off. */
58
+ /** Compact the home after the evening look back unless the partner turns it off. */
59
59
  compactAfterReview: () => settings.compactAfterReview !== false,
60
60
  setCompactAfterReview(on) {
61
61
  const { compactAfterReview: _old, ...rest } = settings;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-world",
3
- "version": "0.7.2",
3
+ "version": "0.7.3",
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": {
@@ -46,7 +46,7 @@
46
46
  ],
47
47
  "engines": {
48
48
  "node": ">=22.16.0",
49
- "dsh": ">=0.2.1-rc.2 <0.3.0-0"
49
+ "dsh": ">=0.2.1-rc.2 <0.3.0-0 || >=0.2.2-rc.1 <0.3.0-0"
50
50
  },
51
51
  "scripts": {
52
52
  "build": "node -e \"require('fs').rmSync('lib',{recursive:true,force:true})\" && tsc -p tsconfig.build.json",
@@ -69,7 +69,8 @@
69
69
  "dshReleases": {
70
70
  "0.2.1-rc.2": "compatible",
71
71
  "0.2.1-rc.3": "compatible",
72
- "0.2.1-rc.5": "compatible"
72
+ "0.2.1-rc.5": "compatible",
73
+ "0.2.2-rc.1": "compatible"
73
74
  }
74
75
  }
75
76
  },
@@ -78,19 +79,19 @@
78
79
  },
79
80
  "peerDependencies": {
80
81
  "@snowluma/sdk": "^2.2.1",
81
- "@deepseek-ai/dsh-plugin-manager": ">=0.2.1-rc.3 <0.3.0-0",
82
- "@deepseek-ai/dsh-atomic-write": ">=0.2.1-rc.3 <0.3.0-0",
83
- "@deepseek-ai/cordis": "~4.0.5",
84
- "@deepseek-ai/dsh-agent": ">=0.2.1-rc.2 <0.3.0-0",
85
- "@deepseek-ai/dsh-attachment": ">=0.2.1-rc.2 <0.3.0-0",
86
- "@deepseek-ai/dsh-compaction": ">=0.2.1-rc.2 <0.3.0-0",
87
- "@deepseek-ai/dsh-home-paths": ">=0.2.1-rc.2 <0.3.0-0",
88
- "@deepseek-ai/dsh-llm": ">=0.2.1-rc.2 <0.3.0-0",
89
- "@deepseek-ai/dsh-session": ">=0.2.1-rc.2 <0.3.0-0",
90
- "@deepseek-ai/dsh-session-persistence": ">=0.2.1-rc.2 <0.3.0-0",
91
- "@deepseek-ai/dsh-tools": ">=0.2.1-rc.2 <0.3.0-0",
92
- "@deepseek-ai/schemastery": "~3.18.5",
93
- "@deepseek-ai/dsh-commands": ">=0.2.1-rc.2 <0.3.0-0"
82
+ "@deepseek-ai/dsh-plugin-manager": ">=0.2.1-rc.3 <0.3.0-0 || >=0.2.2-rc.1 <0.3.0-0",
83
+ "@deepseek-ai/dsh-atomic-write": ">=0.2.1-rc.3 <0.3.0-0 || >=0.2.2-rc.1 <0.3.0-0",
84
+ "@deepseek-ai/cordis": "~4.0.5 || ~4.1.0",
85
+ "@deepseek-ai/dsh-agent": ">=0.2.1-rc.2 <0.3.0-0 || >=0.2.2-rc.1 <0.3.0-0",
86
+ "@deepseek-ai/dsh-attachment": ">=0.2.1-rc.2 <0.3.0-0 || >=0.2.2-rc.1 <0.3.0-0",
87
+ "@deepseek-ai/dsh-compaction": ">=0.2.1-rc.2 <0.3.0-0 || >=0.2.2-rc.1 <0.3.0-0",
88
+ "@deepseek-ai/dsh-home-paths": ">=0.2.1-rc.2 <0.3.0-0 || >=0.2.2-rc.1 <0.3.0-0",
89
+ "@deepseek-ai/dsh-llm": ">=0.2.1-rc.2 <0.3.0-0 || >=0.2.2-rc.1 <0.3.0-0",
90
+ "@deepseek-ai/dsh-session": ">=0.2.1-rc.2 <0.3.0-0 || >=0.2.2-rc.1 <0.3.0-0",
91
+ "@deepseek-ai/dsh-session-persistence": ">=0.2.1-rc.2 <0.3.0-0 || >=0.2.2-rc.1 <0.3.0-0",
92
+ "@deepseek-ai/dsh-tools": ">=0.2.1-rc.2 <0.3.0-0 || >=0.2.2-rc.1 <0.3.0-0",
93
+ "@deepseek-ai/schemastery": "~3.18.5 || ~3.19.0",
94
+ "@deepseek-ai/dsh-commands": ">=0.2.1-rc.2 <0.3.0-0 || >=0.2.2-rc.1 <0.3.0-0"
94
95
  },
95
96
  "peerDependenciesMeta": {
96
97
  "@snowluma/sdk": {