dsh-world 0.6.5 → 0.7.0

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 (59) hide show
  1. package/CHANGELOG.md +34 -0
  2. package/CONTRIBUTING.md +163 -161
  3. package/INSTALL.md +314 -314
  4. package/LICENSE +21 -21
  5. package/NOTES.md +173 -0
  6. package/README.md +236 -235
  7. package/client/index.js +849 -738
  8. package/cordis.patch.yml +6 -6
  9. package/lib/compaction.d.ts +19 -0
  10. package/lib/compaction.js +34 -10
  11. package/lib/compactionSwap.d.ts +29 -2
  12. package/lib/compactionSwap.js +62 -7
  13. package/lib/console/homeApply.d.ts +11 -2
  14. package/lib/console/homeApply.js +36 -7
  15. package/lib/console/routes.d.ts +8 -0
  16. package/lib/console/routes.js +32 -0
  17. package/lib/console/snapshot.d.ts +3 -0
  18. package/lib/console/snapshot.js +2 -1
  19. package/lib/ecosystem/bridge/route.d.ts +7 -0
  20. package/lib/ecosystem/bridge/route.js +30 -0
  21. package/lib/hostContract.d.ts +1 -0
  22. package/lib/index.js +37 -12
  23. package/lib/memory.d.ts +57 -0
  24. package/lib/memory.js +210 -0
  25. package/lib/memoryFiles.d.ts +53 -0
  26. package/lib/memoryFiles.js +193 -0
  27. package/lib/memoryStore.d.ts +114 -0
  28. package/lib/memoryStore.js +159 -0
  29. package/lib/memoryTools.d.ts +31 -0
  30. package/lib/memoryTools.js +106 -0
  31. package/lib/promptSection.d.ts +5 -5
  32. package/lib/promptSection.js +12 -12
  33. package/lib/runtime.d.ts +1 -1
  34. package/lib/runtime.js +84 -29
  35. package/lib/sourceArchive.d.ts +1 -0
  36. package/lib/sourceArchive.js +1 -1
  37. package/lib/store.d.ts +14 -0
  38. package/lib/store.js +11 -1
  39. package/lib/worldPrompt.d.ts +6 -0
  40. package/lib/worldPrompt.js +7 -1
  41. package/lib/worldSwitch.d.ts +3 -2
  42. package/lib/worldSwitch.js +7 -6
  43. package/package.json +128 -115
  44. package/scripts/compact-home.mjs +29 -0
  45. package/scripts/enable-tool-free-compaction.ps1 +33 -33
  46. package/scripts/import-stickers.mjs +17 -17
  47. package/scripts/update-world.mjs +5 -3
  48. package/src/ecosystem/wechat/windows/README.md +6 -4
  49. package/src/ecosystem/wechat/windows/adapter.py +80 -31
  50. package/src/ecosystem/wechat/windows/engine/NOTICE.md +1 -1
  51. package/src/ecosystem/wechat/windows/engine/bridge.cpp +9 -1
  52. package/src/ecosystem/wechat/windows/engine/profiles.json +114 -58
  53. package/src/ecosystem/wechat/windows/native.py +4 -1
  54. package/src/ecosystem/wechat/windows/outgoing.py +21 -0
  55. package/src/ecosystem/wechat/windows/presence.py +109 -109
  56. package/src/ecosystem/wechat/windows/sender.py +9 -1
  57. package/templates/alarm.md +3 -4
  58. package/templates/world-prompt-memory.md +10 -0
  59. package/templates/world-prompt.md +7 -2
package/lib/runtime.js CHANGED
@@ -2,11 +2,14 @@ import { createSystemMessage, createUserMessage, isAgentLoopRequest } from '@dee
2
2
  import "./hostContract.js";
3
3
  import { Faults } from "./faults.js";
4
4
  import { createHistory, excludePresentMessages, renderHistory } from "./history.js";
5
+ import { createWorldToolRegistry, memoryTools } from "./memoryTools.js";
5
6
  import { createPromptSections } from "./promptSection.js";
6
- import { belongsToWorld, createSourceArchive, inWorld, isCorruptSessionLog } from "./sourceArchive.js";
7
+ import { belongsToWorld, createSourceArchive, inWorld, isCorruptSessionLog, isNotFound } from "./sourceArchive.js";
7
8
  import { worldNames } from "./worldPrompt.js";
9
+ import { reassembleOnChange } from "./worldScope.js";
8
10
  import { DEFAULT_MEMORY_TURNS } from "./worldSwitch.js";
9
11
  const memorySource = 'dsh-world-history';
12
+ const worldSources = [memorySource];
10
13
  /**
11
14
  * The memory line: her conversations are archived as they happen, and every world session gets a memory
12
15
  * block of the newest turns at its start and after each successful compaction, never in between, so it stays
@@ -33,37 +36,45 @@ export function createWorldRuntime(ctx, config, store, world, memoryTurns = () =
33
36
  const names = () => world?.names?.() ?? world?.prompt.names ?? worldNames(config);
34
37
  const included = (session) => inWorld(session, config, world?.inWorkspace);
35
38
  const faults = new Faults();
36
- const prompts = world && createPromptSections(config, world, { faults, logger: ctx.logger });
39
+ const prompts = world && createPromptSections(config, world, { logger: ctx.logger });
37
40
  const memory = new WeakMap();
41
+ const toolSets = [world?.memory ? (inside) => memoryTools(world.memory, inside) : undefined].filter(make => !!make);
42
+ const tools = toolSets.length ? createWorldToolRegistry({ tools: inside => toolSets.flatMap(make => make(inside)), inWorld: agent => !stopped && included(agent.session), faults, logger: ctx.logger }) : undefined;
43
+ /** The memory tools follow world membership, whatever the life line does. */
44
+ const syncTools = (agent) => !tools ? false : included(agent.session) ? tools.attach(agent) : tools.detach(agent);
38
45
  const attaching = new WeakMap();
39
46
  const disposers = [];
40
47
  let stopping;
48
+ let stopped = false;
41
49
  /**
42
50
  * Whether the session may carry her world: her preset, or a memory block inherited onto its surface (a delegated
43
51
  * child of her session). Everything else is never read from disk or tracked. The check stays in memory.
44
52
  */
45
53
  const mayCarryWorld = (session) => belongsToWorld(session, config) || memory.has(session) || session.surface.nodes.some(seq => {
46
54
  const event = session.eventAt(seq);
47
- return event?.type === 'user/message' && event.data.source.kind === memorySource;
55
+ return event?.type === 'user/message' && worldSources.includes(event.data.source.kind);
48
56
  });
49
57
  /** Restore the loop position; recalled blocks are located directly on the current surface. */
50
58
  async function readMemoryState(session) {
51
59
  let position = { turn: 1, step: 1 };
52
- const handle = await ctx.sessionPersistence.open(session.id, 'read');
53
- try {
54
- for (let offset = 0;; offset += 128) {
55
- const { events } = await handle.read(offset, 128);
56
- if (!events.length)
57
- break;
58
- for (const event of events) {
59
- if (event.type === 'step/start')
60
- position = { turn: event.data.turn, step: event.data.step };
60
+ // A session the host is still creating may not be readable yet (#27); it has no step to restore.
61
+ const handle = await ctx.sessionPersistence.open(session.id, 'read').catch(error => { if (isNotFound(error))
62
+ return undefined; throw error; });
63
+ if (handle)
64
+ try {
65
+ for (let offset = 0;; offset += 128) {
66
+ const { events } = await handle.read(offset, 128);
67
+ if (!events.length)
68
+ break;
69
+ for (const event of events) {
70
+ if (event.type === 'step/start')
71
+ position = { turn: event.data.turn, step: event.data.step };
72
+ }
61
73
  }
62
74
  }
63
- }
64
- finally {
65
- await handle.close();
66
- }
75
+ finally {
76
+ await handle.close();
77
+ }
67
78
  const inScope = included(session);
68
79
  return { reload: true, position, retiring: [], inScope, restart: !inScope && belongsToWorld(session, config) };
69
80
  }
@@ -72,15 +83,37 @@ export function createWorldRuntime(ctx, config, store, world, memoryTurns = () =
72
83
  * the host only inside an open turn and step, which pre-step and attach are not, so `flushRetired` writes it from
73
84
  * the step's request hook, after the step has started and before the request is assembled (#22).
74
85
  */
75
- function retireMemory(session, state) {
76
- state.retiring = session.surface.nodes.filter(seq => {
86
+ function retireMemory(session, state, kinds = worldSources) {
87
+ const found = session.surface.nodes.filter(seq => {
77
88
  const event = session.eventAt(seq);
78
- return event?.type === 'user/message' && event.data.source.kind === memorySource;
89
+ return event?.type === 'user/message' && kinds.includes(event.data.source.kind);
79
90
  });
80
- if (state.retiring.length)
91
+ state.retiring = [...new Set([...state.retiring, ...found])];
92
+ if (found.length)
81
93
  state.restart = true;
82
- state.reload = true;
83
- state.pendingId = undefined;
94
+ if (kinds.includes(memorySource)) {
95
+ state.reload = true;
96
+ state.pendingId = undefined;
97
+ }
98
+ }
99
+ /** Where memory blocks sit on a session's surface, for the log: positions and event types only, never message text. */
100
+ function memoryNodesOn(session) {
101
+ const found = [];
102
+ for (const seq of session.surface.nodes) {
103
+ const event = session.eventAt(seq);
104
+ if (!event)
105
+ continue;
106
+ let message;
107
+ try {
108
+ message = session.deriveEventMessage(event);
109
+ }
110
+ catch {
111
+ continue;
112
+ }
113
+ if (message?.source?.kind && worldSources.includes(message.source.kind))
114
+ found.push(`#${seq}(${event.type})`);
115
+ }
116
+ return found.length ? found.slice(0, 8).join('、') + (found.length > 8 ? `…共 ${found.length} 个` : '') : '无';
84
117
  }
85
118
  /** Empty system nodes retire only our recalled blocks and derive no model message; original logs stay intact. */
86
119
  function flushRetired(session, state, position) {
@@ -127,7 +160,7 @@ export function createWorldRuntime(ctx, config, store, world, memoryTurns = () =
127
160
  }
128
161
  const present = new Set(session.deriveMessages().map(message => message.id));
129
162
  const text = renderHistory(excludePresentMessages(turns, present), config.timeZone, names(), config.archiveScope === 'home');
130
- retireMemory(session, state);
163
+ retireMemory(session, state, [memorySource]);
131
164
  return text ? createUserMessage({ content: [{ type: 'text', text }], source: { kind: memorySource, form: 'recall' } }) : undefined;
132
165
  }
133
166
  /** Reads what the first catch-up had to leave, once the host can say which sessions belong to her. */
@@ -149,8 +182,9 @@ export function createWorldRuntime(ctx, config, store, world, memoryTurns = () =
149
182
  state.reload = false;
150
183
  state.pendingId = undefined;
151
184
  }
152
- if (state && compacted)
185
+ if (state && compacted) {
153
186
  state.reload = true;
187
+ }
154
188
  if (compacted)
155
189
  prompts?.refresh(session);
156
190
  if (session.header.origin === 'subagent' || (session.header.delegationDepth ?? 0) > 0 || (!config.archiveScope && !belongsToWorld(session, config)))
@@ -158,7 +192,19 @@ export function createWorldRuntime(ctx, config, store, world, memoryTurns = () =
158
192
  if (event.type === 'assistant/message' || event.type === 'turn/end' || event.type === 'turn/start' || event.type === 'compaction/end' || (event.type === 'user/message' && event.data.source.kind === 'user'))
159
193
  void archive.schedule(session.id).catch(() => { });
160
194
  }));
161
- disposers.push(ctx.on('agent/created', async ({ agent }) => { prompts?.add(agent); await attach(agent); return undefined; }));
195
+ // The host fails the whole session creation when a creation listener rejects, leaving an empty session behind on
196
+ // every retry (#27). Memory is set up again before the first request, and a failure here stays in the health list.
197
+ disposers.push(ctx.on('agent/created', ({ agent }) => {
198
+ prompts?.add(agent);
199
+ syncTools(agent);
200
+ void attach(agent).catch(error => ctx.logger.warn(`dsh-world: 会话 ${agent.id} 记忆初始化失败,第一次请求前会再试:`, error));
201
+ return undefined;
202
+ }));
203
+ if (tools) {
204
+ disposers.push(reassembleOnChange(ctx, syncTools));
205
+ disposers.push(ctx.on('agent/pre-step', ({ agent }, next) => { syncTools(agent); return next(); }, { prepend: true }));
206
+ disposers.push(ctx.on('agent/disposed', ({ agent }) => tools.forget(agent)));
207
+ }
162
208
  // Admitted ahead of the step's new input; the host's own admission order (contexts, time-context last) is kept.
163
209
  disposers.push(ctx.on('agent/pre-step', async (payload, next) => {
164
210
  const decision = await next();
@@ -189,10 +235,13 @@ export function createWorldRuntime(ctx, config, store, world, memoryTurns = () =
189
235
  await faults.track(`memory:${agent.id}`, `会话 ${agent.id} 记忆刷新失败`, async () => { block = await freshBlock(agent.session, state); });
190
236
  if (!included(agent.session))
191
237
  return leave();
192
- if (!block) {
238
+ signal.throwIfAborted();
239
+ if (!included(agent.session))
240
+ return leave();
241
+ if (state.reload && !block)
193
242
  state.reload = false;
243
+ if (!block)
194
244
  return decision;
195
- }
196
245
  state.pendingId = block.id;
197
246
  return { ...decision, messages: [block, ...decision.messages] };
198
247
  }));
@@ -206,13 +255,17 @@ export function createWorldRuntime(ctx, config, store, world, memoryTurns = () =
206
255
  disposers.push(ctx.on('llm/stream', async function* (request, next) {
207
256
  const agent = isAgentLoopRequest(request) && request.sessionId ? ctx.agents.get(request.sessionId) : undefined;
208
257
  const owned = agent && included(agent.session);
209
- if (agent && !owned && (prompts?.active(agent.session) || request.messages.some(message => message.source?.kind === memorySource))) {
258
+ const inRequest = agent && !owned ? request.messages.filter(message => !!message.source?.kind && worldSources.includes(message.source.kind)).length : 0;
259
+ const placed = !!agent && !owned && !!prompts?.active(agent.session);
260
+ if (agent && !owned && (placed || inRequest)) {
210
261
  const state = memory.get(agent.session);
211
262
  if (state) {
212
263
  retireMemory(agent.session, state);
213
264
  flushRetired(agent.session, state, state.position);
214
265
  state.restart = true;
215
266
  }
267
+ const reasons = [inRequest ? `请求里还带着 ${inRequest} 条世界记忆块` : '', placed ? '世界提示还挂在会话上' : ''].filter(Boolean).join(';');
268
+ ctx.logger.warn(`dsh-world: 阻止了会话 ${agent.id}(预设 ${agent.session.header.agentPreset ?? '无'})的一次请求,它不在世界工作区里。原因:${reasons}。${state ? '已尝试退役记忆块' : '这个会话没有记忆状态,没法退役'};退役后会话表面上仍有的记忆节点:${memoryNodesOn(agent.session)}。DSH_WORLD_SCOPE_CHANGED`);
216
269
  yield { type: 'finish', reason: { kind: 'error', failure: { code: 'DSH_WORLD_SCOPE_CHANGED', message: 'dsh-world: 会话已离开世界工作区,已阻止携带世界上下文的请求,请重新发送。' } } };
217
270
  return;
218
271
  }
@@ -249,11 +302,13 @@ export function createWorldRuntime(ctx, config, store, world, memoryTurns = () =
249
302
  }
250
303
  function stop() {
251
304
  return stopping ??= (async () => {
305
+ stopped = true;
252
306
  prompts?.clear();
307
+ tools?.clear();
253
308
  for (const dispose of disposers.splice(0).reverse())
254
309
  dispose();
255
310
  await archive.flush();
256
311
  })();
257
312
  }
258
- return { start, retryCatchUp, refreshPrompt: (session) => prompts?.refresh(session), flush: archive.flush, stop, faults: () => [...faults.list(), ...archive.faults()] };
313
+ return { start, retryCatchUp, refreshPrompt: (session) => { prompts?.refresh(session); }, flush: archive.flush, stop, faults: () => [...faults.list(), ...archive.faults()] };
259
314
  }
@@ -7,6 +7,7 @@ export declare function isCorruptSessionLog(error: unknown): boolean;
7
7
  export declare function belongsToWorld(session: Pick<Session, 'header'>, config: WorldConfig): boolean;
8
8
  /** One of her sessions that is also in her room's workspace; without a membership test, any of her sessions. */
9
9
  export declare function inWorld(session: Pick<Session, 'header' | 'id'>, config: WorldConfig, inWorkspace?: (sessionId: string) => boolean): boolean;
10
+ export declare const isNotFound: (error: unknown) => boolean;
10
11
  /**
11
12
  * Copies her conversations from the host's session logs into the archive. Each session is replayed from where
12
13
  * the archive left off; replays run one at a time, and a session already queued is not queued twice. Sessions
@@ -16,7 +16,7 @@ export function belongsToWorld(session, config) {
16
16
  export function inWorld(session, config, inWorkspace) {
17
17
  return belongsToWorld(session, config) && (inWorkspace?.(session.id) ?? true);
18
18
  }
19
- const isNotFound = (error) => error instanceof Error && error.name === 'SessionPersistenceNotFoundError';
19
+ export const isNotFound = (error) => error instanceof Error && error.name === 'SessionPersistenceNotFoundError';
20
20
  const ordinary = (header) => header.origin !== 'subagent' && (header.delegationDepth ?? 0) === 0;
21
21
  /**
22
22
  * Copies her conversations from the host's session logs into the archive. Each session is replayed from where
package/lib/store.d.ts CHANGED
@@ -26,5 +26,19 @@ export declare function createArchiveStore(config: WorldConfig & {
26
26
  delivery: (recordId: string) => DeliveryState | undefined;
27
27
  registerDelivery: (recordId: string, total: number) => void;
28
28
  updateDelivery: (recordId: string, revise: (previous: DeliveryState) => DeliveryState) => void;
29
+ memory: {
30
+ find: (params: import("./memoryStore.ts").FindParams, sessions: readonly string[], upTo: number, take: number) => ConversationRecord[];
31
+ item: (record: ConversationRecord, query: string | undefined) => import("./memoryStore.ts").MemoryItem;
32
+ byRecordId: (recordId: string) => ConversationRecord | undefined;
33
+ refSession: (ref: string) => string | undefined;
34
+ read: (ref: string, canSee: (sessionId: string) => boolean) => import("./memoryStore.ts").ReadResult;
35
+ sessionIds: () => string[];
36
+ snapshot: () => {
37
+ head: number;
38
+ revisions: number;
39
+ };
40
+ revised: () => void;
41
+ };
42
+ snapshotTo: (file: string) => void;
29
43
  };
30
44
  export type ArchiveStore = ReturnType<typeof createArchiveStore>;
package/lib/store.js CHANGED
@@ -2,6 +2,7 @@ import { DatabaseSync } from 'node:sqlite';
2
2
  import { closeSync, existsSync, fstatSync, fsyncSync, ftruncateSync, mkdirSync, openSync, writeSync } from 'node:fs';
3
3
  import { join } from 'node:path';
4
4
  import { formatLocalTime } from "./timeContext.js";
5
+ import { createMemoryStore } from "./memoryStore.js";
5
6
  const pageSize = 128;
6
7
  export function createArchiveStore(config) {
7
8
  // The world id becomes a directory name.
@@ -37,6 +38,8 @@ export function createArchiveStore(config) {
37
38
  throw error;
38
39
  }
39
40
  }
41
+ /** Long-term memory reads the records table on this connection; it keeps nothing of its own in the database. */
42
+ const memory = createMemoryStore(db, { timeZone: config.timeZone });
40
43
  const decode = (row) => JSON.parse(row.body);
41
44
  const dayOf = (record) => formatLocalTime(new Date(record.occurredAt), config.timeZone).slice(0, 10);
42
45
  /**
@@ -135,6 +138,7 @@ export function createArchiveStore(config) {
135
138
  if (body === row.body)
136
139
  return;
137
140
  db.prepare('UPDATE records SET body=? WHERE recordId=?').run(body, recordId);
141
+ memory.revised();
138
142
  // A changed line invalidates later byte offsets; rebuild this day from the canonical database.
139
143
  db.prepare('UPDATE records SET fileOffset=NULL, fileBytes=NULL WHERE day=?').run(row.day);
140
144
  db.prepare('UPDATE days SET exportedBytes=0 WHERE day=?').run(row.day);
@@ -160,6 +164,12 @@ export function createArchiveStore(config) {
160
164
  const row = db.prepare("SELECT count(*) AS records, count(DISTINCT json_extract(body, '$.sourceSessionId')) AS sessions FROM records").get();
161
165
  return { records: Number(row?.records ?? 0), sessions: Number(row?.sessions ?? 0) };
162
166
  }
167
+ /** A consistent copy of the whole archive database (originals and index), for forking an experiment branch from one snapshot. */
168
+ function snapshotTo(file) {
169
+ if (existsSync(file))
170
+ throw new Error('snapshot target already exists');
171
+ db.prepare('VACUUM INTO ?').run(file);
172
+ }
163
173
  function close() { if (!closed) {
164
174
  closed = true;
165
175
  db.close();
@@ -187,5 +197,5 @@ export function createArchiveStore(config) {
187
197
  });
188
198
  }
189
199
  return { commitRecords, hasRecord, updateRecord, readPage, readTurn, progress, forgetProgress, sourcePage, stats, close,
190
- channelSession, bindChannelSession, delivery, registerDelivery, updateDelivery };
200
+ channelSession, bindChannelSession, delivery, registerDelivery, updateDelivery, memory, snapshotTo };
191
201
  }
@@ -1,6 +1,10 @@
1
1
  import type { LifeOptions } from './life/types.ts';
2
2
  /** The template shipped with the plugin; a `world-prompt.md` in the world directory replaces it. */
3
3
  export declare const DEFAULT_TEMPLATE_FILE: string;
4
+ /** The sections an older custom template lacks; she can paste them in (see README). */
5
+ export declare const MEMORY_SNIPPET_FILE: string;
6
+ /** Which of the memory variables a template does not use, so the console can say what her prompt does not mention. */
7
+ export declare function memoryTemplateGaps(template: string): string[];
4
8
  export interface WorldNames {
5
9
  companion: string;
6
10
  partner: string;
@@ -23,6 +27,8 @@ export interface WorldPrompt {
23
27
  names: WorldNames;
24
28
  /** Present when the life line runs: room, diary, world line, ask-first rules. */
25
29
  life?: LifeOptions;
30
+ /** The memory_find and memory_read tools are on her sessions. */
31
+ memoryTools?: boolean;
26
32
  }
27
33
  export interface TemplateRead {
28
34
  text: string;
@@ -2,6 +2,12 @@ import { existsSync, readFileSync } from 'node:fs';
2
2
  import { fileURLToPath } from 'node:url';
3
3
  /** The template shipped with the plugin; a `world-prompt.md` in the world directory replaces it. */
4
4
  export const DEFAULT_TEMPLATE_FILE = fileURLToPath(new URL('../templates/world-prompt.md', import.meta.url));
5
+ /** The sections an older custom template lacks; she can paste them in (see README). */
6
+ export const MEMORY_SNIPPET_FILE = fileURLToPath(new URL('../templates/world-prompt-memory.md', import.meta.url));
7
+ /** Which of the memory variables a template does not use, so the console can say what her prompt does not mention. */
8
+ export function memoryTemplateGaps(template) {
9
+ return ['memoryTools'].filter(name => !new RegExp(String.raw `\{\{[#^]?${name}\}\}`).test(template));
10
+ }
5
11
  /** No name is assumed for anyone's companion: an unnamed one is the neutral TA. */
6
12
  export function worldNames(config) {
7
13
  return { companion: config.companionName?.trim() || 'TA', partner: config.partnerName?.trim() || '伙伴' };
@@ -42,7 +48,7 @@ export function renderTemplate(template, flags, values) {
42
48
  */
43
49
  export function renderWorldPrompt(prompt, template, self, home) {
44
50
  const { life, names } = prompt;
45
- return renderTemplate(template, { life: Boolean(life), home, selfFile: Boolean(self), conversationsDir: Boolean(prompt.conversationsDir) }, {
51
+ return renderTemplate(template, { life: Boolean(life), home, selfFile: Boolean(self), conversationsDir: Boolean(prompt.conversationsDir), memoryTools: Boolean(prompt.memoryTools) }, {
46
52
  name: names.companion, partner: names.partner, homeTitle: homeTitle(names), selfFile: self?.file ?? '', self: self?.text ?? '', conversationsDir: prompt.conversationsDir ?? '',
47
53
  ...(life ? { roomDir: life.roomDir, diaryDir: life.diaryDir, fallbackWakeTime: life.fallbackWakeTime } : {}),
48
54
  });
@@ -32,8 +32,9 @@ export declare function createWorldSwitch(worldDir: string, configuredScope?: Me
32
32
  memoryTurns: () => number;
33
33
  setMemoryTurns(turns: number | undefined): void;
34
34
  /**
35
- * The console's switches for the WeChat and QQ modules. WeChat is on unless turned off; QQ, whose SDK is an
36
- * optional dependency, is off until turned on, so its code is not even loaded before someone asks for it.
35
+ * The console's switches for the WeChat and QQ modules; both are off until someone turns them on. QQ's SDK is an
36
+ * optional dependency, so its code is not even loaded before then. WeChat used to default to on, so a world that
37
+ * never stored a choice but whose WeChat module has already run (it keeps its outbox) stays on after the upgrade.
37
38
  */
38
39
  wechatEnabled: () => boolean;
39
40
  qqEnabled: () => boolean;
@@ -24,7 +24,7 @@ export function createWorldSwitch(worldDir, configuredScope = 'workspace') {
24
24
  ...(validWorkspacePermission(stored?.workspacePermission) ? { workspacePermission: stored.workspacePermission } : {}),
25
25
  ...(validWechatContext(stored?.wechatContext) ? { wechatContext: stored.wechatContext } : {}),
26
26
  ...(validWechatBuffer(stored?.wechatBufferSeconds) ? { wechatBufferSeconds: stored.wechatBufferSeconds } : {}),
27
- ...(stored?.wechatEnabled === false ? { wechatEnabled: false } : {}),
27
+ ...(typeof stored?.wechatEnabled === 'boolean' ? { wechatEnabled: stored.wechatEnabled } : {}),
28
28
  ...(typeof stored?.qqEnabled === 'boolean' ? { qqEnabled: stored.qqEnabled } : {}),
29
29
  ...(stored?.compactAfterReview === false ? { compactAfterReview: false } : {}),
30
30
  ...(stored?.compactionSwapped === true ? { compactionSwapped: true } : {}),
@@ -73,15 +73,16 @@ export function createWorldSwitch(worldDir, configuredScope = 'workspace') {
73
73
  save(turns === undefined || turns === DEFAULT_MEMORY_TURNS ? rest : { ...rest, memoryTurns: turns });
74
74
  },
75
75
  /**
76
- * The console's switches for the WeChat and QQ modules. WeChat is on unless turned off; QQ, whose SDK is an
77
- * optional dependency, is off until turned on, so its code is not even loaded before someone asks for it.
76
+ * The console's switches for the WeChat and QQ modules; both are off until someone turns them on. QQ's SDK is an
77
+ * optional dependency, so its code is not even loaded before then. WeChat used to default to on, so a world that
78
+ * never stored a choice but whose WeChat module has already run (it keeps its outbox) stays on after the upgrade.
78
79
  */
79
- wechatEnabled: () => settings.wechatEnabled !== false,
80
+ wechatEnabled: () => settings.wechatEnabled ?? existsSync(join(worldDir, 'wechat-outbox.sqlite')),
80
81
  qqEnabled: () => settings.qqEnabled === true,
81
82
  setModules(next) {
82
83
  const { wechatEnabled, qqEnabled, ...rest } = settings;
83
- const wechat = next.wechat ?? wechatEnabled !== false, qq = next.qq ?? qqEnabled === true;
84
- save({ ...rest, ...(wechat ? {} : { wechatEnabled: false }), ...(qq ? { qqEnabled: true } : {}) });
84
+ const wechat = next.wechat ?? wechatEnabled ?? existsSync(join(worldDir, 'wechat-outbox.sqlite')), qq = next.qq ?? qqEnabled === true;
85
+ save({ ...rest, wechatEnabled: wechat, ...(qq ? { qqEnabled: true } : {}) });
85
86
  },
86
87
  /** Read by the WeChat adapter on its next poll; a batch already waiting keeps the value it started with. */
87
88
  wechatContext: () => settings.wechatContext ?? DEFAULT_WECHAT_CONTEXT,
package/package.json CHANGED
@@ -1,115 +1,128 @@
1
- {
2
- "name": "dsh-world",
3
- "version": "0.6.5",
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
- "license": "MIT",
6
- "publishConfig": {
7
- "registry": "https://registry.npmjs.org/",
8
- "access": "public"
9
- },
10
- "repository": {
11
- "type": "git",
12
- "url": "git+https://github.com/chenkezhen480/dsh-world.git"
13
- },
14
- "type": "module",
15
- "main": "lib/index.js",
16
- "types": "lib/index.d.ts",
17
- "exports": {
18
- ".": {
19
- "types": "./lib/index.d.ts",
20
- "default": "./lib/index.js"
21
- },
22
- "./compaction": {
23
- "types": "./lib/compaction.d.ts",
24
- "default": "./lib/compaction.js"
25
- },
26
- "./client": "./client/index.js",
27
- "./package.json": "./package.json"
28
- },
29
- "files": [
30
- "lib",
31
- "client",
32
- "src/ecosystem/wechat/windows",
33
- "src/ecosystem/README.md",
34
- "templates",
35
- "cordis.patch.yml",
36
- "README.md",
37
- "INSTALL.md",
38
- "CONTRIBUTING.md",
39
- "CHANGELOG.md",
40
- "assets",
41
- "scripts/enable-tool-free-compaction.ps1",
42
- "scripts/update-world.mjs",
43
- "scripts/import-stickers.mjs"
44
- ],
45
- "engines": {
46
- "node": ">=22.16.0",
47
- "dsh": ">=0.2.1-rc.2 <0.3.0-0"
48
- },
49
- "scripts": {
50
- "build": "node -e \"require('fs').rmSync('lib',{recursive:true,force:true})\" && tsc -p tsconfig.build.json",
51
- "typecheck": "tsc --noEmit",
52
- "test": "node --experimental-strip-types --disable-warning=ExperimentalWarning --test",
53
- "test:package": "node scripts/check-package.mjs",
54
- "prepack": "npm run typecheck && npm run build"
55
- },
56
- "dsh": {
57
- "bundle": {
58
- "patch": "./cordis.patch.yml"
59
- },
60
- "client": {
61
- "inject": [
62
- "@deepseek-ai/dsh-client-ui-settings"
63
- ],
64
- "platform": "web"
65
- },
66
- "compatibility": {
67
- "dshReleases": {
68
- "0.2.1-rc.2": "compatible",
69
- "0.2.1-rc.3": "compatible"
70
- }
71
- }
72
- },
73
- "dependencies": {
74
- "ws": "^8.18.0"
75
- },
76
- "peerDependencies": {
77
- "@snowluma/sdk": "^2.2.1",
78
- "@deepseek-ai/dsh-plugin-manager": ">=0.2.1-rc.3 <0.3.0-0",
79
- "@deepseek-ai/dsh-atomic-write": ">=0.2.1-rc.3 <0.3.0-0",
80
- "@deepseek-ai/cordis": "~4.0.5",
81
- "@deepseek-ai/dsh-agent": ">=0.2.1-rc.2 <0.3.0-0",
82
- "@deepseek-ai/dsh-attachment": ">=0.2.1-rc.2 <0.3.0-0",
83
- "@deepseek-ai/dsh-compaction": ">=0.2.1-rc.2 <0.3.0-0",
84
- "@deepseek-ai/dsh-home-paths": ">=0.2.1-rc.2 <0.3.0-0",
85
- "@deepseek-ai/dsh-llm": ">=0.2.1-rc.2 <0.3.0-0",
86
- "@deepseek-ai/dsh-session": ">=0.2.1-rc.2 <0.3.0-0",
87
- "@deepseek-ai/dsh-session-persistence": ">=0.2.1-rc.2 <0.3.0-0",
88
- "@deepseek-ai/dsh-tools": ">=0.2.1-rc.2 <0.3.0-0",
89
- "@deepseek-ai/schemastery": "~3.18.5",
90
- "@deepseek-ai/dsh-commands": ">=0.2.1-rc.2 <0.3.0-0"
91
- },
92
- "peerDependenciesMeta": {
93
- "@snowluma/sdk": {
94
- "optional": true
95
- },
96
- "@deepseek-ai/dsh-plugin-manager": {
97
- "optional": true
98
- },
99
- "@deepseek-ai/dsh-atomic-write": {
100
- "optional": true
101
- }
102
- },
103
- "devDependencies": {
104
- "@snowluma/sdk": "2.2.1",
105
- "@deepseek-ai/dsh-agent-loop": "0.2.1-rc.2",
106
- "@deepseek-ai/dsh-compaction-basic": "0.2.1-rc.2",
107
- "@deepseek-ai/dsh-session-persistence-jsonl": "0.2.1-rc.2",
108
- "@deepseek-ai/dsh-session-projection": "0.2.1-rc.2",
109
- "@deepseek-ai/dsh-system-prompt": "0.2.1-rc.2",
110
- "@deepseek-ai/dsh-token-meter": "0.2.1-rc.2",
111
- "@deepseek-ai/dsh-tools": "0.2.1-rc.2",
112
- "@types/node": "^22.16.0",
113
- "typescript": "^5.9.3"
114
- }
115
- }
1
+ {
2
+ "name": "dsh-world",
3
+ "version": "0.7.0",
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
+ "license": "MIT",
6
+ "publishConfig": {
7
+ "registry": "https://registry.npmjs.org/",
8
+ "access": "public"
9
+ },
10
+ "repository": {
11
+ "type": "git",
12
+ "url": "git+https://github.com/chenkezhen480/dsh-world.git"
13
+ },
14
+ "type": "module",
15
+ "main": "lib/index.js",
16
+ "types": "lib/index.d.ts",
17
+ "exports": {
18
+ ".": {
19
+ "types": "./lib/index.d.ts",
20
+ "default": "./lib/index.js"
21
+ },
22
+ "./compaction": {
23
+ "types": "./lib/compaction.d.ts",
24
+ "default": "./lib/compaction.js"
25
+ },
26
+ "./client": "./client/index.js",
27
+ "./package.json": "./package.json"
28
+ },
29
+ "files": [
30
+ "lib",
31
+ "client",
32
+ "src/ecosystem/wechat/windows",
33
+ "src/ecosystem/README.md",
34
+ "templates",
35
+ "cordis.patch.yml",
36
+ "README.md",
37
+ "INSTALL.md",
38
+ "CONTRIBUTING.md",
39
+ "CHANGELOG.md",
40
+ "NOTES.md",
41
+ "assets",
42
+ "scripts/enable-tool-free-compaction.ps1",
43
+ "scripts/update-world.mjs",
44
+ "scripts/import-stickers.mjs",
45
+ "scripts/compact-home.mjs"
46
+ ],
47
+ "engines": {
48
+ "node": ">=22.16.0",
49
+ "dsh": ">=0.2.1-rc.2 <0.3.0-0"
50
+ },
51
+ "scripts": {
52
+ "build": "node -e \"require('fs').rmSync('lib',{recursive:true,force:true})\" && tsc -p tsconfig.build.json",
53
+ "typecheck": "tsc --noEmit",
54
+ "test": "node --experimental-strip-types --disable-warning=ExperimentalWarning --test",
55
+ "test:package": "node scripts/check-package.mjs",
56
+ "prepack": "npm run typecheck && npm run build"
57
+ },
58
+ "dsh": {
59
+ "bundle": {
60
+ "patch": "./cordis.patch.yml"
61
+ },
62
+ "client": {
63
+ "inject": [
64
+ "@deepseek-ai/dsh-client-ui-settings"
65
+ ],
66
+ "platform": "web"
67
+ },
68
+ "compatibility": {
69
+ "dshReleases": {
70
+ "0.2.1-rc.2": "compatible",
71
+ "0.2.1-rc.3": "compatible",
72
+ "0.2.1-rc.5": "compatible"
73
+ }
74
+ }
75
+ },
76
+ "dependencies": {
77
+ "ws": "^8.18.0"
78
+ },
79
+ "peerDependencies": {
80
+ "@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"
94
+ },
95
+ "peerDependenciesMeta": {
96
+ "@snowluma/sdk": {
97
+ "optional": true
98
+ },
99
+ "@deepseek-ai/dsh-plugin-manager": {
100
+ "optional": true
101
+ },
102
+ "@deepseek-ai/dsh-atomic-write": {
103
+ "optional": true
104
+ }
105
+ },
106
+ "devDependencies": {
107
+ "@snowluma/sdk": "2.2.1",
108
+ "@deepseek-ai/dsh-agent-loop": "0.2.1-rc.2",
109
+ "@deepseek-ai/dsh-compaction-basic": "0.2.1-rc.2",
110
+ "@deepseek-ai/dsh-session-persistence-jsonl": "0.2.1-rc.2",
111
+ "@deepseek-ai/dsh-session-projection": "0.2.1-rc.2",
112
+ "@deepseek-ai/dsh-system-prompt": "0.2.1-rc.2",
113
+ "@deepseek-ai/dsh-token-meter": "0.2.1-rc.2",
114
+ "@deepseek-ai/dsh-tools": "0.2.1-rc.2",
115
+ "@types/node": "^22.16.0",
116
+ "typescript": "^5.9.3",
117
+ "@deepseek-ai/cordis": "4.0.5",
118
+ "@deepseek-ai/schemastery": "3.18.5",
119
+ "@deepseek-ai/dsh-agent": "0.2.1-rc.2",
120
+ "@deepseek-ai/dsh-attachment": "0.2.1-rc.2",
121
+ "@deepseek-ai/dsh-commands": "0.2.1-rc.2",
122
+ "@deepseek-ai/dsh-compaction": "0.2.1-rc.2",
123
+ "@deepseek-ai/dsh-home-paths": "0.2.1-rc.2",
124
+ "@deepseek-ai/dsh-llm": "0.2.1-rc.2",
125
+ "@deepseek-ai/dsh-session": "0.2.1-rc.2",
126
+ "@deepseek-ai/dsh-session-persistence": "0.2.1-rc.2"
127
+ }
128
+ }