dsh-world 0.7.3 → 0.7.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/CHANGELOG.md +52 -0
  2. package/NOTES.md +37 -17
  3. package/README.md +14 -7
  4. package/client/index.js +37 -2
  5. package/lib/abortable.d.ts +1 -0
  6. package/lib/abortable.js +17 -0
  7. package/lib/compaction.js +2 -2
  8. package/lib/compactionSwap.d.ts +23 -14
  9. package/lib/compactionSwap.js +90 -36
  10. package/lib/console/homeApply.js +1 -12
  11. package/lib/console/routes.d.ts +1 -0
  12. package/lib/console/routes.js +10 -0
  13. package/lib/console/snapshot.d.ts +4 -0
  14. package/lib/console/snapshot.js +3 -0
  15. package/lib/ecosystem/bridge/bridge.d.ts +2 -2
  16. package/lib/ecosystem/bridge/bridge.js +24 -11
  17. package/lib/ecosystem/qq-native/home.d.ts +2 -1
  18. package/lib/ecosystem/qq-native/home.js +6 -2
  19. package/lib/ecosystem/qq-native/images.d.ts +9 -0
  20. package/lib/ecosystem/qq-native/images.js +69 -0
  21. package/lib/ecosystem/qq-native/index.d.ts +1 -0
  22. package/lib/ecosystem/qq-native/index.js +8 -2
  23. package/lib/ecosystem/qq-native/snowluma.d.ts +1 -0
  24. package/lib/ecosystem/qq-native/snowluma.js +13 -4
  25. package/lib/ecosystem/shared/turn.d.ts +3 -0
  26. package/lib/ecosystem/shared/turn.js +9 -2
  27. package/lib/ecosystem/wechat/home.d.ts +3 -0
  28. package/lib/ecosystem/wechat/home.js +12 -4
  29. package/lib/ecosystem/wechat/index.js +3 -1
  30. package/lib/ecosystem/wechat/supervisor.d.ts +1 -1
  31. package/lib/ecosystem/wechat/supervisor.js +5 -1
  32. package/lib/hostContract.d.ts +6 -0
  33. package/lib/index.d.ts +1 -1
  34. package/lib/index.js +85 -47
  35. package/lib/life/home.js +8 -2
  36. package/lib/life/photoTools.js +60 -26
  37. package/lib/life/runtime.js +2 -0
  38. package/lib/memoryTools.d.ts +1 -1
  39. package/lib/memoryTools.js +1 -1
  40. package/lib/mood.d.ts +57 -0
  41. package/lib/mood.js +95 -0
  42. package/lib/moodTools.d.ts +6 -0
  43. package/lib/moodTools.js +30 -0
  44. package/lib/persona.js +7 -0
  45. package/lib/promptSection.d.ts +9 -13
  46. package/lib/promptSection.js +63 -80
  47. package/lib/runtime.d.ts +21 -2
  48. package/lib/runtime.js +148 -39
  49. package/lib/self.d.ts +1 -1
  50. package/lib/self.js +1 -1
  51. package/lib/sourceArchive.d.ts +1 -5
  52. package/lib/sourceArchive.js +31 -14
  53. package/lib/types.d.ts +2 -0
  54. package/lib/worldScope.d.ts +2 -4
  55. package/lib/worldScope.js +6 -6
  56. package/package.json +1 -1
  57. package/src/ecosystem/wechat/windows/README.md +5 -3
  58. package/src/ecosystem/wechat/windows/adapter.py +23 -2
  59. package/src/ecosystem/wechat/windows/engine/NOTICE.md +6 -0
  60. package/src/ecosystem/wechat/windows/engine/profiles.json +28 -0
  61. package/src/ecosystem/wechat/windows/sender.py +6 -2
  62. package/templates/world-prompt.md +6 -3
package/lib/runtime.js CHANGED
@@ -1,26 +1,34 @@
1
+ import { createHash } from 'node:crypto';
1
2
  import { createSystemMessage, createUserMessage, isAgentLoopRequest, LlmError } from '@deepseek-ai/dsh-llm';
3
+ import { appendPluginRecord, pluginRecordOf, SessionLogOffset } from '@deepseek-ai/dsh-session';
2
4
  import "./hostContract.js";
3
5
  import { isOrdinarySession } from "./archive.js";
4
6
  import { compactsWhole } from "./compaction.js";
5
7
  import { compactionFor } from "./console/homeApply.js";
6
8
  import { Faults } from "./faults.js";
7
9
  import { createHistory, excludePresentMessages, renderHistory } from "./history.js";
10
+ import { MOOD_CLEARED, moodText, readMood } from "./mood.js";
8
11
  import { createWorldToolRegistry, memoryTools } from "./memoryTools.js";
9
- import { createPromptSections, WORLD_PROMPT_PREFIX } from "./promptSection.js";
12
+ import { moodTools } from "./moodTools.js";
13
+ import { assembledWorlds, createPromptSections } from "./promptSection.js";
10
14
  import { belongsToWorld, createSourceArchive, inWorld, sessionPreset } from "./sourceArchive.js";
11
15
  import { worldNames } from "./worldPrompt.js";
12
16
  import { reassembleOnChange } from "./worldScope.js";
13
17
  import { DEFAULT_COLD_HOURS, DEFAULT_MEMORY_TURNS } from "./worldSwitch.js";
14
18
  const memorySource = 'dsh-world-history';
19
+ const moodSource = 'dsh-world-mood';
15
20
  const isRecall = (source, worldId) => source?.kind === memorySource && (worldId === undefined || source.worldId === undefined || source.worldId === worldId);
21
+ const promptRecord = 'plugin:dsh-world/system-prompt';
22
+ const legacyPromptReset = 'plugin:dsh-world/legacy-prompt-reset';
23
+ const digestPrompt = (text) => createHash('sha256').update(text).digest('hex');
16
24
  function recallNodes(session, match) {
17
25
  return session.surface.nodes.filter(seq => {
18
26
  const event = session.eventAt(seq);
19
27
  return event?.type === 'user/message' && match(event.data.source);
20
28
  });
21
29
  }
22
- /** Empty system nodes retire recall from the model's context and leave the original events intact. */
23
- function retireRecall(session, retiring, position) {
30
+ /** Empty system nodes retire old context from the model's view and preserve the original events. */
31
+ function retireContext(session, retiring, position) {
24
32
  for (const seq of retiring) {
25
33
  if (!session.surface.nodes.includes(seq))
26
34
  continue;
@@ -28,22 +36,70 @@ function retireRecall(session, retiring, position) {
28
36
  }
29
37
  }
30
38
  /** A session can outlive its world. Authorization returns false for a stopped world and undefined outside it. */
31
- export function guardWorldContext(ctx, authorize) {
39
+ export function guardWorldContext(ctx, authorize, hasWorldRoom) {
32
40
  const assemblies = new WeakMap();
33
- const previousPrompts = new WeakMap();
41
+ const promptLogs = new WeakMap();
42
+ function promptLog(session) {
43
+ const log = promptLogs.get(session) ?? { nextSeq: 0, owners: new Map(), reset: false, sawWorldContext: false };
44
+ const end = session.seq;
45
+ for (let from = log.nextSeq; from < end; from += 128) {
46
+ for (const event of session.snapshotEvents(SessionLogOffset(from), SessionLogOffset(Math.min(from + 128, end)))) {
47
+ if (event.type === 'step/start')
48
+ delete log.pending;
49
+ if (event.type === 'system/message' && log.pending && event.data.turn === log.pending.turn && event.data.step === log.pending.step) {
50
+ const block = event.data.message.content[0];
51
+ if (block?.type === 'text' && digestPrompt(block.text) === log.pending.digest) {
52
+ log.owners.set(event.data.message.id, { worldId: log.pending.worldId, digest: log.pending.digest });
53
+ }
54
+ }
55
+ if (!log.reset && event.type === 'user/message') {
56
+ const kind = event.data.source.kind;
57
+ log.sawWorldContext ||= kind === memorySource || kind === moodSource || kind === 'dsh-world-channel-context';
58
+ }
59
+ if (event.type === legacyPromptReset && pluginRecordOf(event))
60
+ log.reset = true;
61
+ if (event.type !== promptRecord)
62
+ continue;
63
+ const data = pluginRecordOf(event)?.data;
64
+ if (typeof data?.worldId === 'string' && typeof data.digest === 'string' && typeof data.turn === 'number' && typeof data.step === 'number') {
65
+ log.pending = { worldId: data.worldId, digest: data.digest, turn: data.turn, step: data.step };
66
+ log.reset = true;
67
+ }
68
+ }
69
+ }
70
+ log.nextSeq = end;
71
+ promptLogs.set(session, log);
72
+ return log;
73
+ }
74
+ // Old DSH logs contain a single rendered string with no section boundaries or saved world ownership.
75
+ const needsLegacyReset = (session, log) => !log.reset && (log.sawWorldContext || hasWorldRoom(session));
76
+ function retiredPrompts(session, log, current, reset) {
77
+ if (!reset && !current && !log.owners.size)
78
+ return [];
79
+ return session.surface.nodes.filter(seq => {
80
+ const event = session.eventAt(seq);
81
+ if (event?.type !== 'system/message')
82
+ return false;
83
+ const block = event.data.message.content[0];
84
+ if (block?.type !== 'text')
85
+ return false;
86
+ if (reset)
87
+ return true;
88
+ const owner = log.owners.get(event.data.message.id);
89
+ return current ? (owner?.digest ?? digestPrompt(block.text)) !== current.digest || (!!owner && owner.worldId !== current.worldId) : !!owner;
90
+ });
91
+ }
34
92
  const revoked = (source, session) => {
35
- if (source?.kind === memorySource)
93
+ if (source?.kind === memorySource || source?.kind === moodSource)
36
94
  return !session || !authorize(session, source.worldId);
37
95
  return source?.kind === 'dsh-world-channel-context' && (!session || !authorize(session));
38
96
  };
39
97
  ctx.on('system-prompt/assemble', async (_assembly, context, next) => {
40
98
  const result = await next();
41
99
  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
- }
100
+ const prompt = assembledWorlds.get(context);
101
+ if (prompt)
102
+ assemblies.set(context.signal, { worldId: prompt.worldId, token: prompt.token, digest: digestPrompt(prompt.text) });
47
103
  else
48
104
  assemblies.delete(context.signal);
49
105
  }
@@ -54,13 +110,20 @@ export function guardWorldContext(ctx, authorize) {
54
110
  if (decision.kind !== 'enter')
55
111
  return decision;
56
112
  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;
113
+ const log = promptLog(session);
114
+ return retiredPrompts(session, log, assemblies.get(signal), needsLegacyReset(session, log)).length || recallNodes(session, source => revoked(source, session)).length
115
+ ? { ...decision, startsRequestSeries: true } : decision;
61
116
  });
62
- ctx.on('agent/request', ({ agent: { session }, turn, step }, next) => {
63
- retireRecall(session, recallNodes(session, source => revoked(source, session)), { turn, step });
117
+ ctx.on('agent/request', ({ agent: { session }, turn, step, signal }, next) => {
118
+ const prompt = assemblies.get(signal);
119
+ const log = promptLog(session);
120
+ const reset = needsLegacyReset(session, log);
121
+ retireContext(session, [...retiredPrompts(session, log, prompt, reset), ...recallNodes(session, source => revoked(source, session))], { turn, step });
122
+ // Record ownership before DSH commits the projected system message, including attempts that never reach a provider.
123
+ if (prompt)
124
+ appendPluginRecord(session, promptRecord, { worldId: prompt.worldId, digest: prompt.digest, turn, step });
125
+ else if (reset)
126
+ appendPluginRecord(session, legacyPromptReset, {});
64
127
  return next();
65
128
  });
66
129
  ctx.on('llm/stream', async function* (request, next) {
@@ -70,21 +133,26 @@ export function guardWorldContext(ctx, authorize) {
70
133
  return;
71
134
  }
72
135
  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))) {
136
+ const prompt = !compaction && request.signal ? assemblies.get(request.signal) : undefined;
137
+ const scope = session && authorize(session, prompt?.worldId);
138
+ const stalePrompt = !compaction && scope !== prompt?.token && (Boolean(prompt) || typeof scope === 'symbol');
139
+ // Compaction can replay system messages before a resumed session has taken a new turn.
140
+ const log = session && promptLog(session);
141
+ const legacyCompaction = compaction && scope === undefined && session && log
142
+ && needsLegacyReset(session, log) && request.messages.some(message => message.role === 'system' && message.content.length > 0);
143
+ const unauthorizedPrompt = !!session && !!log?.owners.size && request.messages.some(message => {
144
+ const owner = message.role === 'system' && log.owners.get(message.id);
145
+ return !!owner && !authorize(session, owner.worldId);
146
+ });
147
+ const failure = { code: 'DSH_WORLD_SCOPE_CHANGED', message: legacyCompaction
148
+ ? 'dsh-world: 会话仍带有旧版世界提示词。请先发送一条消息恢复 DSH 提示词,再压缩。'
149
+ : compaction
150
+ ? 'dsh-world: 世界已停止或会话已离开世界工作区,已取消压缩。'
151
+ : 'dsh-world: 世界权限已变化,已阻止携带旧世界上下文的请求,请重新发送。' };
152
+ if (stalePrompt || (compaction && scope === false) || legacyCompaction || unauthorizedPrompt || request.messages.some(message => revoked(message.source, session))) {
83
153
  yield { type: 'finish', reason: { kind: 'error', failure } };
84
154
  return;
85
155
  }
86
- if (!compaction && session && !prompt)
87
- previousPrompts.delete(session);
88
156
  yield* next();
89
157
  if (compaction && session && scope && authorize(session, prompt?.worldId) !== scope)
90
158
  throw new LlmError(failure.message, failure.code);
@@ -123,15 +191,19 @@ export function createWorldRuntime(ctx, config, store, world, memoryTurns = () =
123
191
  const included = (session) => inWorld(session, config, world?.inWorkspace);
124
192
  const ownMemory = (source) => isRecall(source, config.worldId);
125
193
  const faults = new Faults();
126
- const prompts = world && createPromptSections(config, world, { logger: ctx.logger });
194
+ const scopeToken = Symbol();
195
+ const prompts = world && createPromptSections(config, world, scopeToken, { logger: ctx.logger });
127
196
  const memory = new WeakMap();
128
197
  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;
130
- /** The memory tools follow world membership, whatever the life line does. */
198
+ const worldTools = (inside) => [...service ? memoryTools(service, inside) : [], ...config.moodFile ? moodTools(config.moodFile, inside) : []];
199
+ const tools = service || config.moodFile ? createWorldToolRegistry({ tools: worldTools, inWorld: agent => !stopped && included(agent.session), faults, logger: ctx.logger }) : undefined;
200
+ /** The world tools (memory, mood) follow world membership, whatever the life line does. */
131
201
  const syncTools = (agent) => !tools ? false : included(agent.session) ? tools.attach(agent) : tools.detach(agent);
132
202
  const disposers = [];
133
203
  let stopping;
134
204
  let stopped = false;
205
+ const catchUpController = new AbortController();
206
+ const cancelCatchUp = () => catchUpController.abort();
135
207
  /**
136
208
  * Whether the session may carry her world: her preset, or a memory block inherited onto its surface (a delegated
137
209
  * child of her session). Everything else is never read from disk or tracked. The check stays in memory.
@@ -185,10 +257,32 @@ export function createWorldRuntime(ctx, config, store, world, memoryTurns = () =
185
257
  }
186
258
  return found.length ? found.slice(0, 8).join('、') + (found.length > 8 ? `…共 ${found.length} 个` : '') : '无';
187
259
  }
260
+ /** The text of her latest mood snapshot still on the surface, if any. */
261
+ function latestMood(session) {
262
+ const seq = recallNodes(session, source => source?.kind === moodSource && source.worldId === config.worldId).at(-1);
263
+ const event = seq === undefined ? undefined : session.eventAt(seq);
264
+ return event?.type === 'user/message' ? event.data.content.flatMap(block => block.type === 'text' ? [block.text] : []).join('') : undefined;
265
+ }
266
+ /**
267
+ * Her mood rides just before the time block, appended like it: only when it differs from the latest one on the
268
+ * surface, never replacing an old one, so the cached prefix stays whole and compaction clears them all.
269
+ */
270
+ function moodMessage(session) {
271
+ if (!config.moodFile)
272
+ return undefined;
273
+ const mood = readMood(config.moodFile);
274
+ if (mood.kind === 'failed')
275
+ faults.set('mood', `mood.md 读不出来:${mood.message}`);
276
+ else
277
+ faults.clear('mood');
278
+ const latest = latestMood(session);
279
+ const text = moodText(mood) ?? (latest === undefined ? undefined : MOOD_CLEARED);
280
+ return text === undefined || text === latest ? undefined : createUserMessage({ content: [{ type: 'text', text }], source: { kind: moodSource, form: 'snapshot', worldId: config.worldId } });
281
+ }
188
282
  function flushRetired(session, state, position) {
189
283
  const retiring = state.retiring;
190
284
  state.retiring = [];
191
- retireRecall(session, retiring, position);
285
+ retireContext(session, retiring, position);
192
286
  }
193
287
  async function attach(agent) {
194
288
  const { session } = agent;
@@ -231,7 +325,7 @@ export function createWorldRuntime(ctx, config, store, world, memoryTurns = () =
231
325
  if (!undecided)
232
326
  return;
233
327
  undecided = false;
234
- await archive.catchUp();
328
+ await archive.catchUp(false, catchUpController.signal);
235
329
  }
236
330
  /** `fresh`: her world was just started from the console, so what was said while it was stopped is not archived. */
237
331
  async function start(options = {}) {
@@ -274,6 +368,8 @@ export function createWorldRuntime(ctx, config, store, world, memoryTurns = () =
274
368
  void attach(agent);
275
369
  return undefined;
276
370
  }));
371
+ if (prompts)
372
+ disposers.push(ctx.on('agent/disposed', ({ agent }) => prompts.forget(agent)));
277
373
  if (tools) {
278
374
  disposers.push(reassembleOnChange(ctx, syncTools));
279
375
  disposers.push(ctx.on('agent/pre-step', ({ agent }, next) => { syncTools(agent); return next(); }, { prepend: true }));
@@ -306,6 +402,9 @@ export function createWorldRuntime(ctx, config, store, world, memoryTurns = () =
306
402
  signal.throwIfAborted();
307
403
  if (!included(agent.session))
308
404
  return leave();
405
+ const mood = moodMessage(agent.session);
406
+ if (mood)
407
+ decision = { ...decision, messages: [...decision.messages, mood] };
309
408
  if (!state.reload)
310
409
  return decision;
311
410
  // A block that cannot be built leaves the old one in place; she talks on, the fault shows, and the next step tries again.
@@ -360,14 +459,23 @@ export function createWorldRuntime(ctx, config, store, world, memoryTurns = () =
360
459
  yield chunk;
361
460
  }
362
461
  }));
363
- await archive.catchUp(options.fresh);
462
+ // Already-open sessions can start a turn before the background archive catch-up finishes.
463
+ for (const agent of ctx.agents.list()) {
464
+ prompts?.add(agent);
465
+ syncTools(agent);
466
+ }
467
+ const { signal } = catchUpController;
468
+ await archive.catchUp(options.fresh, signal);
364
469
  if (options.fresh)
365
- for (const agent of ctx.agents.list())
470
+ for (const agent of ctx.agents.list()) {
471
+ if (signal.aborted)
472
+ return;
366
473
  if (included(agent.session))
367
474
  await archive.skip(agent.id);
475
+ }
368
476
  for (const agent of ctx.agents.list()) {
369
- prompts?.add(agent);
370
- syncTools(agent);
477
+ if (signal.aborted)
478
+ return;
371
479
  await attach(agent);
372
480
  }
373
481
  }
@@ -379,6 +487,7 @@ export function createWorldRuntime(ctx, config, store, world, memoryTurns = () =
379
487
  function stop() {
380
488
  return stopping ??= (async () => {
381
489
  stopped = true;
490
+ cancelCatchUp();
382
491
  prompts?.clear();
383
492
  tools?.clear();
384
493
  for (const dispose of disposers.splice(0).reverse())
@@ -386,5 +495,5 @@ export function createWorldRuntime(ctx, config, store, world, memoryTurns = () =
386
495
  await archive.flush();
387
496
  })();
388
497
  }
389
- return { scopeToken: Symbol(), start, retryCatchUp, refreshPrompt: (session) => { prompts?.refresh(session); }, flush: archive.flush, stop, faults: () => [...faults.list(), ...archive.faults()] };
498
+ return { scopeToken, start, retryCatchUp, cancelCatchUp, refreshPrompt: (session) => { prompts?.refresh(session); }, flush: archive.flush, stop, faults: () => [...faults.list(), ...archive.faults()] };
390
499
  }
package/lib/self.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  /** Characters of her self-description read per session; she is asked to keep it to what matters. */
2
- export declare const SELF_CAP = 4000;
2
+ export declare const SELF_CAP = 5000;
3
3
  /**
4
4
  * Her 我是谁 file as it goes into `{{self}}`: only what she wrote, tagged so her own headings do not read as
5
5
  * sections of the world prompt. What the file is and that she may rewrite it is the template's to say.
package/lib/self.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { copyFileSync, existsSync, mkdirSync, readFileSync } from 'node:fs';
2
2
  import { basename, dirname, extname, join } from 'node:path';
3
3
  /** Characters of her self-description read per session; she is asked to keep it to what matters. */
4
- export const SELF_CAP = 4000;
4
+ export const SELF_CAP = 5000;
5
5
  /**
6
6
  * Her 我是谁 file as it goes into `{{self}}`: only what she wrote, tagged so her own headings do not read as
7
7
  * sections of the world prompt. What the file is and that she may rewrite it is the template's to say.
@@ -17,12 +17,8 @@ export declare const isNotFound: (error: unknown) => boolean;
17
17
  */
18
18
  export declare function createSourceArchive(ctx: Context, config: WorldConfig, store: ArchiveStore, archived?: (sessionId: string) => boolean): {
19
19
  schedule: (sessionId: string) => Promise<void>;
20
+ catchUp: (skip?: boolean, signal?: AbortSignal) => Promise<void>;
20
21
  faults: () => string[];
21
- /**
22
- * Every session the archive has seen, replayed again so nothing written while the plugin was not loaded is
23
- * missed; with `skip`, what was said while her world was stopped is passed over instead.
24
- */
25
- catchUp(skip?: boolean): Promise<void>;
26
22
  /** Moves past everything a session holds now without keeping it (said while her world was stopped). */
27
23
  skip: (sessionId: string) => Promise<void>;
28
24
  /** Waits for every queued replay; rejects while any session still has an unresolved failure. */
@@ -1,4 +1,5 @@
1
1
  import { SessionId, SessionLogOffset } from '@deepseek-ai/dsh-session';
2
+ import { abortable } from "./abortable.js";
2
3
  import { extractConversationRecords, isOrdinarySession } from "./archive.js";
3
4
  import { wechatDeliveryPatch } from "./ecosystem/wechat/archive.js";
4
5
  import { errorText, Faults } from "./faults.js";
@@ -132,21 +133,20 @@ export function createSourceArchive(ctx, config, store, archived = () => true) {
132
133
  tail = job.catch(error => { ctx.logger.error(error); });
133
134
  return job;
134
135
  }
135
- return {
136
- schedule,
137
- faults: () => faults.list(),
138
- /**
139
- * Every session the archive has seen, replayed again so nothing written while the plugin was not loaded is
140
- * missed; with `skip`, what was said while her world was stopped is passed over instead.
141
- */
142
- async catchUp(skip = false) {
143
- // One session's failure is kept for flush(); it must not stop the sessions after it.
144
- const replayOne = (id) => (skip ? enqueue(() => replay(id, true)) : schedule(id)).catch(() => { });
136
+ /** Replays what was missed, or passes over messages written while the world was stopped when `skip` is set. */
137
+ async function catchUp(skip = false, signal) {
138
+ if (signal?.aborted)
139
+ return;
140
+ // Keep the current replay in the queue so its transaction and file close finish before shutdown.
141
+ const replayOne = (id) => (skip ? enqueue(() => replay(id, true)) : schedule(id)).catch(() => { });
142
+ try {
145
143
  // The host exposes a metadata inventory; every selected message log is still read in pages.
146
- const snapshots = await ctx.sessionPersistence.list();
144
+ const snapshots = await abortable(ctx.sessionPersistence.list({ signal }), signal);
147
145
  const visited = new Set();
148
146
  for (let offset = 0; offset < snapshots.length; offset += pageSize) {
149
147
  for (const { header } of snapshots.slice(offset, offset + pageSize)) {
148
+ if (signal?.aborted)
149
+ return;
150
150
  if (!isOrdinarySession(header) || !archived(header.id))
151
151
  continue;
152
152
  visited.add(header.id);
@@ -154,13 +154,21 @@ export function createSourceArchive(ctx, config, store, archived = () => true) {
154
154
  }
155
155
  }
156
156
  let after = '';
157
- for (let ids = store.sourcePage(after); ids.length; ids = store.sourcePage(after)) {
157
+ while (!signal?.aborted) {
158
+ const ids = store.sourcePage(after);
159
+ if (!ids.length)
160
+ return;
158
161
  for (const id of ids) {
162
+ if (signal?.aborted)
163
+ return;
159
164
  after = id;
160
165
  if (visited.has(id))
161
166
  continue;
162
167
  // A session deleted from the host (not merely archived there) keeps its records but has nothing left to resume.
163
- if (!await ctx.sessionPersistence.stat(SessionId(id))) {
168
+ const exists = await abortable(ctx.sessionPersistence.stat(SessionId(id), { signal }), signal);
169
+ if (signal?.aborted)
170
+ return;
171
+ if (!exists) {
164
172
  forget(id);
165
173
  continue;
166
174
  }
@@ -169,7 +177,16 @@ export function createSourceArchive(ctx, config, store, archived = () => true) {
169
177
  await replayOne(id);
170
178
  }
171
179
  }
172
- },
180
+ }
181
+ catch (error) {
182
+ if (!signal?.aborted || error !== signal.reason)
183
+ throw error;
184
+ }
185
+ }
186
+ return {
187
+ schedule,
188
+ catchUp,
189
+ faults: () => faults.list(),
173
190
  /** Moves past everything a session holds now without keeping it (said while her world was stopped). */
174
191
  skip: (sessionId) => enqueue(() => replay(sessionId, true)),
175
192
  /** Waits for every queued replay; rejects while any session still has an unresolved failure. */
package/lib/types.d.ts CHANGED
@@ -18,6 +18,8 @@ export interface WorldConfig {
18
18
  fallbackWakeTime?: string;
19
19
  /** Her own "who I am" file, part of the world prompt; defaults to `<world>/room/我是谁.md` in the plugin. */
20
20
  selfFile?: string;
21
+ /** Her mood file, read back to her each turn; `<world>/room/mood.md` in the plugin, none when unset. */
22
+ moodFile?: string;
21
23
  /** Her name (home title, notifications, memory labels); TA when unset. */
22
24
  companionName?: string;
23
25
  /** What she calls her partner in the plugin's own words; 伙伴 when unset. */
@@ -15,8 +15,6 @@ export declare class OutsideWorldError extends Error {
15
15
  export declare function admit(inWorld: InWorld | undefined, agent: Agent): Agent;
16
16
  /** The same scope check controls step admission and execution; older hosts ignore the registration condition. */
17
17
  export declare function registerScopedTool(agent: Agent, tool: ToolDefinition, inside: () => boolean, left?: () => void): () => void;
18
- /**
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
- */
18
+ export declare function syncBetweenSteps(ctx: Context, sync: (agent: Agent) => void): () => void;
19
+ /** DSH 0.2.2 selects tools before prompt assembly. Check again during assembly for late changes. */
22
20
  export declare function reassembleOnChange(ctx: Context, sync: (agent: Agent) => boolean): () => void;
package/lib/worldScope.js CHANGED
@@ -18,18 +18,18 @@ export function registerScopedTool(agent, tool, inside, left) {
18
18
  return tool.execute(args, exec);
19
19
  } }, { when: inside });
20
20
  }
21
- /**
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.
24
- */
25
- export function reassembleOnChange(ctx, sync) {
26
- const beforeStep = ctx.on('session/event', (session, event) => {
21
+ export function syncBetweenSteps(ctx, sync) {
22
+ return ctx.on('session/event', (session, event) => {
27
23
  if (event.type !== 'turn/start' && event.type !== 'step/end')
28
24
  return;
29
25
  const agent = ctx.get('agents')?.get(session.id);
30
26
  if (agent)
31
27
  sync(agent);
32
28
  });
29
+ }
30
+ /** DSH 0.2.2 selects tools before prompt assembly. Check again during assembly for late changes. */
31
+ export function reassembleOnChange(ctx, sync) {
32
+ const beforeStep = syncBetweenSteps(ctx, sync);
33
33
  const assemble = ctx.on('system-prompt/assemble', (_assembly, context, next) => context.agent && sync(context.agent) ? context.agent.ctx.systemPrompt.assemble(context) : next());
34
34
  return () => { beforeStep(); assemble(); };
35
35
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-world",
3
- "version": "0.7.3",
3
+ "version": "0.7.5",
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": {
@@ -10,7 +10,7 @@ DSH 端代码在 `src/ecosystem/wechat/`,此目录只负责 Windows 微信收
10
10
  - 收到要交给她的消息后先缓冲(默认 3 秒,`bufferSeconds`):同一聊天、同一发言人在等待中又发来文字(私聊还包括图片),就重新计时,安静下来后合并为一次模型请求;最长等 30 秒、最多 16 条、合并文字不超过 2000 字,私聊最多两张图片。别人发言、引用、表情包等其他类型让批次立即结束。群聊只有 @ 她的消息会等待,同一人随后的文字合并进来,身份仍是 @ 她的那条。批次开始处理后才收到的消息留在微信数据库中,下一轮按序读取,不中断当前回复。
11
11
  - 批次成员保留原平台消息 ID,在同一事务中进入待处理与完成状态;缓冲期间不推进游标,处理中断后保留待核对状态,不自动重跑模型。图片单发仅进入会话图片上下文;图片加文字时只把真实文字按原范围归档。图片及附件引用不写入共享记忆块,是否另行留存其中信息由她自己判断。
12
12
  - 暂不接收视频号分享卡片:卡片会被跳过,不进入宿主会话或共享记忆。视频号卡片解析、视频内容读取,以及朋友圈浏览/发布,均预留为微信模块后续扩展,尚未实现;朋友圈发布需要独立接口,不能复用私聊/群聊发送接口。
13
- - 后台原生发送文字、图片及 GIF 表情,不操作窗口、鼠标、键盘或剪贴板。按 `engine/profiles.json` 中的文件大小与 SHA256 自动选择 Windows x64 微信 4.1.15.13 / 4.1.15.56 / 4.2.0.11 / 4.2.0.12 / 4.2.0.13 的指定构建(4.2 的表情包截取一帧作为图片发送,见下)。未知或匹配不唯一的构建会在加载原生桥前报错。
13
+ - 后台原生发送文字、图片及 GIF 表情,不操作窗口、鼠标、键盘或剪贴板。按 `engine/profiles.json` 中的文件大小与 SHA256 自动选择 Windows x64 微信 4.1.15.13 / 4.1.15.56 / 4.2.0.11 / 4.2.0.12 / 4.2.0.13 / 4.2.0.52 的指定构建(4.2 的表情包截取一帧作为图片发送,见下)。未知或匹配不唯一的构建会在加载原生桥前报错,并暂停自动重启。安装受支持的版本或更新适配器后,可从控制台手动重启。
14
14
  - 发言人使用真实 wxid,消息保持 `role: user`;昵称只作显示。
15
15
  - 每个群按平台、登录账号、聊天类型和群 ID 绑定独立会话,列在原房间工作区下,重启继续复用;群名变化不产生新会话。QQ 的相同参数可使用同一映射结构,但本模块仍只提供微信传输。
16
16
  - 群消息只在微信来源元数据的 `atuserlist` 包含她的真实 wxid 时触发,正文里手打 `@昵称` 不触发。回复携带当前消息之前默认 5 条(控制台可调,1–20)、最多 16KB 的同群上下文,保留各自的发言人 ID;每轮最多读取其中最近两张图片。
@@ -32,7 +32,7 @@ DSH 端代码在 `src/ecosystem/wechat/`,此目录只负责 Windows 微信收
32
32
  - 生成时先记为待发送,适配器逐条核对目标聊天中的本人消息、内容及服务器消息编号,再更新同一条记忆的已确认条数。中断则记录已确认部分与结果不明项;这不是对方已读回执。
33
33
  - 回执先保存在适配器本地,宿主暂时不可用时,重启监听只补报回执,不重发消息。旧版本的待发送记录不会凭空改成已发送。
34
34
  - 宿主队列保存在世界目录 `wechat-outbox.sqlite`。适配器离线时已排队消息会等待恢复;已领取任务按同一 ID 恢复,适配器已有回执时只补报,不再发送。入站处理结果不明时保留 pending,只暂停这一个聊天的接收(其他聊天照常),日志提示人工核对,独立发送任务仍继续轮询;主动发送的待核对消息 ID 为 `outgoing:<发送 ID>`。结果不明的原发送任务不会重发,其余任务按各自 ID 和回执处理。
35
- - 回执、任务领取、账号状态和群读取结果的单键请求遇到 HTTP 502/503/504 或连接错误时最多尝试 5 次,单次网络超时为 5 秒,间隔 1/2/4/8 秒,每次重读 `wechat.json` 的地址和令牌;响应正文读取中断也按此处理,HTTP 错误保留响应正文(最多 1024 字节)。生成回复的请求仍保留 190 秒网络超时,只发送一次,不能因超时或 503 自动再次调用模型。
35
+ - 回执、任务领取、账号状态和群读取结果的单键请求遇到 HTTP 502/503/504 或连接错误时最多尝试 5 次,单次网络超时为 5 秒,间隔 1/2/4/8 秒,每次重读 `wechat.json` 的地址和令牌;响应正文读取中断也按此处理,HTTP 错误保留响应正文(最多 1024 字节)。生成回复的请求仍保留 190 秒网络超时,只发送一次,不能因超时或 503 自动再次调用模型。她在这一轮里用 `wechat_send` 回了这个聊天,请求就此返回,不再等这一轮剩下的事做完。她正忙、插件 3 分钟内没能把消息交给她时,插件回 HTTP 409:消息没有进家里,适配器撤回这批的待确认标记,之后的轮询重新交给她,这个聊天不会因此停下等人核对。
36
36
  - 群会话沿用现有归档范围:`archiveScope: home` 时能读取家的记忆,但群正文不写入共享记忆;群自己的宿主会话日志保留正文,发送状态单独保存,不绕过归档范围。
37
37
  - `archiveScope: workspace` 会归档家所在工作区的普通会话,包括独立群会话;群图片上下文依旧不进入共享归档。控制台修改范围后重启 DSH 生效,回扫范围内历史并按时间重建近期记忆,保留原始日志和旧归档。
38
38
 
@@ -144,10 +144,12 @@ node <dsh-world 包目录>scriptsimport-stickers.mjs C:Usersyou.dshmemes C:Users
144
144
 
145
145
  4.1.15.56 的指纹与 19 个原生地址映射来自 [helper 的版本表](https://github.com/Prometheus-first/helper/blob/main/native/core_version.h)。两版沿用相同请求 ABI、账号核对和消息对象字段布局;版本表选择、地址编码及未知构建拒绝由离线测试覆盖。上游已实测新版文字收发及桥接加载卸载,媒体未逐项重做真实网络操作,详见其 [验证范围](https://github.com/Prometheus-first/helper/blob/main/native/README.md);本项目实测范围见下方日期记录。本次仅更新 Python 和版本表,无须重新编译未改动的 C++ 桥;新增构建或结构发生变化时仍需校准并实测。
146
146
 
147
- 4.2.0.11 与 4.2.0.12 的指纹和地址取自 helper 的版本表。4.2.0.13 的地址由本项目从腾讯签名的 `Weixin.dll` 独立比对得出,基准是从安装包离线解出的 4.2.0.12 DLL。三个 4.2 构建都沿用静态表情发送方式。适配器取 GIF 第一帧转为 PNG,第一帧完全透明或只有一种颜色时改取最后一帧。4.2.0.13 仅更新版本表,已构建当前原生桥的环境可直接使用。来源见 [NOTICE](engine/NOTICE.md)。
147
+ 4.2.0.11 与 4.2.0.12 的指纹和地址取自 helper 的版本表。4.2.0.13 和 4.2.0.52 的地址由本项目从腾讯签名的 `Weixin.dll` 独立比对得出,基准是已核对指纹的 4.2.0.12 DLL。4.2 构建沿用静态表情发送方式。适配器取 GIF 第一帧转为 PNG,第一帧完全透明或只有一种颜色时改取最后一帧。4.2.0.13 和 4.2.0.52 沿用现有原生桥 ABI。来源见 [NOTICE](engine/NOTICE.md)。
148
148
 
149
149
  2026-11-04 已在 Windows 微信 4.2.0.13 上通过 `Probe`,核对了构建指纹、绑定账号及原生调度。实际文字、图片、表情包投递及 DSH 收发联动待验证。
150
150
 
151
+ 2026-11-13 已离线核对 Windows 微信 4.2.0.52 的腾讯签名、DLL 指纹、PE 元数据及原生地址。该版本的已登录 `Probe` 和实际投递待验证。
152
+
151
153
  2026-10-25 已在绑定的专用账号私聊中确认两条独立文字及一条原生表情(类型 47),并在选定家庭群补发确认一张原生表情和一条文字;均核对服务器消息编号,媒体内容同时核对 MD5。首次群会话的技能目录误判已修复并有回归测试。2026-10-26 已确认家庭群真实 @ 触发时读取两张缓存图片、模型描述图片并回群发送成功,附件引用保存在群会话日志,该群共享归档记录数仍为 0。该轮未测独立图片发送和锁屏运行。
152
154
 
153
155
  2026-10-27 已在 Windows 微信 4.1.15.56 上独立验证:构建指纹、绑定账号及原生调度 Probe 通过;13 个数据库密钥通过校验;私聊、群聊各分页读取 40 条历史消息样本,解析到 9 条群历史消息的真实 @ 元数据;解码私聊 1 张及群聊 2 张缓存图片,并完成一条私聊表情的 CDN 下载与解码。经用户明确确认,向已配置私聊各发送一次文字、PNG 和两帧原生 GIF 表情,三条均核对服务器消息编号,两项媒体同时核对 MD5。测试全程未启动 DSH、未调用模型、未向家庭群发送测试消息,原有本地消息游标及待核对状态保持不变。本轮未测 4.1.15.56 下的群实际发送、退出重连、锁屏或 DSH 联动。
@@ -18,7 +18,7 @@ from snapshot import NotSent, SnapshotBusy
18
18
  from groups import DEFAULT_CONTEXT_MESSAGES, mentionedIds, recentContext
19
19
  from incoming import ImageUnavailable, admitReference
20
20
  from binding import WechatOffline
21
- from sender import BuildStale
21
+ from sender import BuildStale, UnsupportedWechatBuild
22
22
  from messages import messageKey, messageOrder, normalizeMessage, messageNormalizer, messageEntry, displayMessage
23
23
  from quotes import MessageContentError, isAppMessage
24
24
  from reading import readHistory
@@ -36,6 +36,8 @@ REPLY_TIMEOUT_SECONDS = 190
36
36
  EXIT_NEEDS_HUMAN = 2
37
37
  # Exit code for "the native bridge must be built again"; the plugin builds it and starts the adapter again.
38
38
  EXIT_NEEDS_BUILD = 3
39
+ # Exit code for a Weixin.dll fingerprint the adapter cannot match to a supported build.
40
+ EXIT_UNSUPPORTED_BUILD = 4
39
41
  # A reply whose send never started (no stable snapshot of the chat) is handed out again this many times in all.
40
42
  SEND_ATTEMPTS = 3
41
43
 
@@ -52,6 +54,10 @@ class HomeRequestError(RuntimeError):
52
54
  pass
53
55
 
54
56
 
57
+ class HomeBusy(RuntimeError):
58
+ """The home ran out of time before taking the message in; asking again later cannot repeat it."""
59
+
60
+
55
61
  @contextmanager
56
62
  def exclusiveRun(directory):
57
63
  import msvcrt
@@ -275,6 +281,11 @@ class MessageStore:
275
281
  self.db.execute('UPDATE cursors SET seq=MAX(seq,?) WHERE chatId=?', (int(row['sort_seq']), chatId))
276
282
  print(f'微信消息 {chatId} / {key}:{error}', file=sys.stderr, flush=True)
277
283
 
284
+ def abandonBatch(self, chatId, rows):
285
+ """Undo `beginBatch` for messages the home never took in, so a later poll hands them over again."""
286
+ with self.db:
287
+ self.db.executemany("DELETE FROM messages WHERE chatId=? AND messageId=? AND status='pending'", [(chatId, messageKey(row)) for row in rows])
288
+
278
289
  def finishBatch(self, chatId, rows):
279
290
  with self.db:
280
291
  result = self.db.executemany("UPDATE messages SET status='done' WHERE chatId=? AND messageId=? AND status='pending'", [(chatId, messageKey(row)) for row in rows])
@@ -352,6 +363,8 @@ def postHome(moduleFile, message):
352
363
  try: detail = error.read(1024).decode('utf-8', errors='replace')
353
364
  except (IncompleteRead, URLError, TimeoutError, ConnectionError) as readError:
354
365
  detail = f'响应正文未读完:{readError}'
366
+ if error.code == 409 and not retryable:
367
+ raise HomeBusy(f'DSH HTTP 409: {detail or error.reason}') from error
355
368
  transient = error.code in (502, 503, 504)
356
369
  failure = HomeRequestError if transient else RuntimeError
357
370
  if not retryable or not transient or attempt == 4:
@@ -567,7 +580,12 @@ def watch(config, database, store, send, ask=askHome, report=reportReceipt, poll
567
580
  mergeFollowing(database, chat, config, message, rows[1:])
568
581
  store.beginBatch(chat['id'], rows)
569
582
  if message:
570
- askWhileSending(config, message, database, store, send, ask, report, poll)
583
+ try: askWhileSending(config, message, database, store, send, ask, report, poll)
584
+ except HomeBusy as error:
585
+ # She is still busy and has not seen it: hand the same messages over on a later poll.
586
+ store.abandonBatch(chat['id'], rows)
587
+ print(f'她还在忙,这条稍后再交给她(不会重复):{chat["id"]} / {messageKey(rows[0])}:{error}', file=sys.stderr, flush=True)
588
+ break
571
589
  store.finishBatch(chat['id'], rows)
572
590
  flushOutgoing(config, database, store, send, poll=poll, report=report)
573
591
  config['_presence'] = dict(observedAt=datetime.now(timezone.utc).isoformat(), groups=store.presence.snapshot(config))
@@ -690,6 +708,9 @@ if __name__ == '__main__':
690
708
  except BuildStale as error:
691
709
  print(f'微信适配器停止:{error}', file=sys.stderr)
692
710
  sys.exit(EXIT_NEEDS_BUILD)
711
+ except UnsupportedWechatBuild as error:
712
+ print(f'微信适配器停止:{error}', file=sys.stderr)
713
+ sys.exit(EXIT_UNSUPPORTED_BUILD)
693
714
  except Exception as error:
694
715
  print(f'微信适配器停止:{error}', file=sys.stderr)
695
716
  sys.exit(1)
@@ -17,3 +17,9 @@ x64 Weixin.dll. The comparison used the 4.2.0.12 DLL extracted from Tencent's
17
17
  installer and verified against the existing profile. Function disassembly,
18
18
  references to the account root, and the context vtable were compared between
19
19
  the two builds.
20
+
21
+ The 4.2.0.52 mapping was independently compared with the fingerprint-verified
22
+ 4.2.0.12 DLL. The new DLL was extracted offline from the Tencent installer
23
+ and its Authenticode signature was verified. The comparison covered x64
24
+ instructions with relocation operands masked, call targets and scheduler
25
+ literals, both account-root references, and context and manager RTTI records.