dsh-world 0.7.0 → 0.7.2

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 (84) hide show
  1. package/CHANGELOG.md +379 -347
  2. package/INSTALL.md +314 -314
  3. package/LICENSE +21 -21
  4. package/NOTES.md +32 -10
  5. package/README.md +7 -6
  6. package/client/index.js +58 -3
  7. package/cordis.patch.yml +6 -6
  8. package/lib/archive.d.ts +3 -1
  9. package/lib/archive.js +6 -4
  10. package/lib/console/routes.d.ts +7 -0
  11. package/lib/console/routes.js +26 -8
  12. package/lib/console/snapshot.d.ts +7 -0
  13. package/lib/console/snapshot.js +3 -2
  14. package/lib/ecosystem/qq/route.d.ts +2 -1
  15. package/lib/ecosystem/qq/route.js +10 -2
  16. package/lib/ecosystem/qq-native/batch.d.ts +2 -0
  17. package/lib/ecosystem/qq-native/batch.js +3 -1
  18. package/lib/ecosystem/qq-native/home.d.ts +1 -0
  19. package/lib/ecosystem/qq-native/home.js +10 -3
  20. package/lib/ecosystem/qq-native/index.d.ts +2 -0
  21. package/lib/ecosystem/qq-native/index.js +21 -4
  22. package/lib/ecosystem/qq-native/native-bridge.js +5 -2
  23. package/lib/ecosystem/qq-native/replies.d.ts +7 -1
  24. package/lib/ecosystem/qq-native/replies.js +30 -1
  25. package/lib/ecosystem/shared/context.d.ts +6 -1
  26. package/lib/ecosystem/shared/context.js +6 -1
  27. package/lib/ecosystem/shared/identity.d.ts +12 -0
  28. package/lib/ecosystem/shared/identity.js +17 -1
  29. package/lib/ecosystem/shared/turn.d.ts +8 -5
  30. package/lib/ecosystem/shared/turn.js +16 -17
  31. package/lib/ecosystem/wechat/archive.d.ts +2 -0
  32. package/lib/ecosystem/wechat/archive.js +3 -1
  33. package/lib/ecosystem/wechat/home.js +9 -4
  34. package/lib/ecosystem/wechat/messages.d.ts +11 -0
  35. package/lib/ecosystem/wechat/messages.js +9 -1
  36. package/lib/ecosystem/wechat/sending.js +36 -9
  37. package/lib/ecosystem/wechat/supervisor.d.ts +11 -2
  38. package/lib/ecosystem/wechat/supervisor.js +90 -9
  39. package/lib/history.d.ts +6 -4
  40. package/lib/history.js +61 -12
  41. package/lib/hostContract.d.ts +4 -1
  42. package/lib/index.d.ts +1 -0
  43. package/lib/index.js +27 -7
  44. package/lib/life/activity.d.ts +2 -0
  45. package/lib/life/activity.js +1 -1
  46. package/lib/life/alarm.d.ts +12 -4
  47. package/lib/life/alarm.js +21 -6
  48. package/lib/life/diary.d.ts +6 -0
  49. package/lib/life/diary.js +23 -2
  50. package/lib/life/runtime.d.ts +1 -0
  51. package/lib/life/runtime.js +57 -9
  52. package/lib/life/toolRegistry.d.ts +4 -3
  53. package/lib/life/toolRegistry.js +13 -3
  54. package/lib/life/types.d.ts +6 -1
  55. package/lib/memory.js +1 -4
  56. package/lib/memoryFiles.d.ts +1 -4
  57. package/lib/memoryFiles.js +18 -43
  58. package/lib/memoryStore.d.ts +1 -3
  59. package/lib/memoryStore.js +1 -1
  60. package/lib/memoryTools.js +2 -2
  61. package/lib/promptSection.d.ts +5 -4
  62. package/lib/promptSection.js +9 -8
  63. package/lib/runtime.d.ts +8 -3
  64. package/lib/runtime.js +60 -94
  65. package/lib/sourceArchive.js +4 -5
  66. package/lib/store.d.ts +1 -1
  67. package/lib/store.js +1 -1
  68. package/lib/types.d.ts +1 -4
  69. package/lib/worldPrompt.js +1 -1
  70. package/lib/worldSwitch.d.ts +15 -1
  71. package/lib/worldSwitch.js +24 -1
  72. package/package.json +1 -1
  73. package/scripts/compact-home.mjs +29 -29
  74. package/scripts/enable-tool-free-compaction.ps1 +33 -33
  75. package/scripts/import-stickers.mjs +17 -17
  76. package/scripts/update-world.mjs +2 -2
  77. package/src/ecosystem/wechat/windows/README.md +5 -3
  78. package/src/ecosystem/wechat/windows/adapter.py +6 -0
  79. package/src/ecosystem/wechat/windows/engine/NOTICE.md +6 -0
  80. package/src/ecosystem/wechat/windows/engine/build.ps1 +8 -2
  81. package/src/ecosystem/wechat/windows/engine/profiles.json +142 -114
  82. package/src/ecosystem/wechat/windows/presence.py +109 -109
  83. package/src/ecosystem/wechat/windows/sender.py +17 -5
  84. package/templates/alarm.md +1 -1
package/lib/runtime.js CHANGED
@@ -1,23 +1,29 @@
1
1
  import { createSystemMessage, createUserMessage, isAgentLoopRequest } from '@deepseek-ai/dsh-llm';
2
2
  import "./hostContract.js";
3
+ import { isOrdinarySession } from "./archive.js";
3
4
  import { Faults } from "./faults.js";
4
5
  import { createHistory, excludePresentMessages, renderHistory } from "./history.js";
5
6
  import { createWorldToolRegistry, memoryTools } from "./memoryTools.js";
6
7
  import { createPromptSections } from "./promptSection.js";
7
- import { belongsToWorld, createSourceArchive, inWorld, isCorruptSessionLog, isNotFound } from "./sourceArchive.js";
8
+ import { belongsToWorld, createSourceArchive, inWorld } from "./sourceArchive.js";
8
9
  import { worldNames } from "./worldPrompt.js";
9
10
  import { reassembleOnChange } from "./worldScope.js";
10
- import { DEFAULT_MEMORY_TURNS } from "./worldSwitch.js";
11
+ import { DEFAULT_COLD_HOURS, DEFAULT_MEMORY_TURNS } from "./worldSwitch.js";
11
12
  const memorySource = 'dsh-world-history';
12
- const worldSources = [memorySource];
13
+ const isMemoryBlock = (event) => event?.type === 'user/message' && event.data.source.kind === memorySource;
13
14
  /**
14
15
  * The memory line: her conversations are archived as they happen, and every world session gets a memory
15
- * block of the newest turns at its start and after each successful compaction, never in between, so it stays
16
- * inside the provider-cached prefix. `home` archives the current home; `workspace` uses host membership. The memory block still
16
+ * block of the newest turns at its start, after each successful compaction and when it speaks again after being cold,
17
+ * never in between, so it stays inside the provider-cached prefix. `home` archives the current home; `workspace` uses host membership. The memory block still
17
18
  * goes to every world session in her workspace (`inWorkspace`), independently of the archive scope.
18
19
  * `memoryTurns` is read each time a block is built (default 200).
20
+ *
21
+ * A session silent for `coldHours` (read at each turn start, default 24) is cold (#36): its provider cache has most
22
+ * 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.
19
25
  */
20
- export function createWorldRuntime(ctx, config, store, world, memoryTurns = () => DEFAULT_MEMORY_TURNS) {
26
+ export function createWorldRuntime(ctx, config, store, world, memoryTurns = () => DEFAULT_MEMORY_TURNS, coldHours = () => DEFAULT_COLD_HOURS, now = Date.now) {
21
27
  if (config.archiveScope === 'workspace' && !world?.archiveSession)
22
28
  throw new Error('Workspace archive requires the host workspace selection');
23
29
  const archivedByScope = world?.archiveSession ?? ((sessionId) => config.archiveScope !== 'home' || !!world?.isHome(sessionId));
@@ -42,7 +48,6 @@ export function createWorldRuntime(ctx, config, store, world, memoryTurns = () =
42
48
  const tools = toolSets.length ? createWorldToolRegistry({ tools: inside => toolSets.flatMap(make => make(inside)), inWorld: agent => !stopped && included(agent.session), faults, logger: ctx.logger }) : undefined;
43
49
  /** The memory tools follow world membership, whatever the life line does. */
44
50
  const syncTools = (agent) => !tools ? false : included(agent.session) ? tools.attach(agent) : tools.detach(agent);
45
- const attaching = new WeakMap();
46
51
  const disposers = [];
47
52
  let stopping;
48
53
  let stopped = false;
@@ -50,51 +55,32 @@ export function createWorldRuntime(ctx, config, store, world, memoryTurns = () =
50
55
  * Whether the session may carry her world: her preset, or a memory block inherited onto its surface (a delegated
51
56
  * child of her session). Everything else is never read from disk or tracked. The check stays in memory.
52
57
  */
53
- const mayCarryWorld = (session) => belongsToWorld(session, config) || memory.has(session) || session.surface.nodes.some(seq => {
54
- const event = session.eventAt(seq);
55
- return event?.type === 'user/message' && worldSources.includes(event.data.source.kind);
56
- });
57
- /** Restore the loop position; recalled blocks are located directly on the current surface. */
58
- async function readMemoryState(session) {
59
- let position = { turn: 1, step: 1 };
60
- // A session the host is still creating may not be readable yet (#27); it has no step to restore.
61
- const handle = await ctx.sessionPersistence.open(session.id, 'read').catch(error => { if (isNotFound(error))
62
- return undefined; throw error; });
63
- if (handle)
64
- try {
65
- for (let offset = 0;; offset += 128) {
66
- const { events } = await handle.read(offset, 128);
67
- if (!events.length)
68
- break;
69
- for (const event of events) {
70
- if (event.type === 'step/start')
71
- position = { turn: event.data.turn, step: event.data.step };
72
- }
73
- }
74
- }
75
- finally {
76
- await handle.close();
77
- }
58
+ const mayCarryWorld = (session) => belongsToWorld(session, config) || memory.has(session) || session.surface.nodes.some(seq => isMemoryBlock(session.eventAt(seq)));
59
+ function newMemoryState(session) {
78
60
  const inScope = included(session);
79
- return { reload: true, position, retiring: [], inScope, restart: !inScope && belongsToWorld(session, config) };
61
+ return { reload: true, position: { turn: 1, step: 1 }, retiring: [], inScope, restart: !inScope && belongsToWorld(session, config) };
62
+ }
63
+ /**
64
+ * Archive failures never stop her talking: they stay in the health list, and what she said meanwhile is replayed
65
+ * from the host's log, from the archive's last committed position, once a later replay succeeds.
66
+ */
67
+ async function archiveNow(sessionId) {
68
+ if (archived(sessionId))
69
+ await faults.track(`archive:${sessionId}`, `会话 ${sessionId} 归档登记失败`, () => store.commitRecords([], store.progress(sessionId))).catch(() => { });
70
+ await archive.schedule(sessionId).catch(() => { });
80
71
  }
81
72
  /**
82
73
  * Marks our recalled blocks on the surface for retirement. The empty system node that retires one is accepted by
83
74
  * the host only inside an open turn and step, which pre-step and attach are not, so `flushRetired` writes it from
84
75
  * the step's request hook, after the step has started and before the request is assembled (#22).
85
76
  */
86
- function retireMemory(session, state, kinds = worldSources) {
87
- const found = session.surface.nodes.filter(seq => {
88
- const event = session.eventAt(seq);
89
- return event?.type === 'user/message' && kinds.includes(event.data.source.kind);
90
- });
77
+ function retireMemory(session, state) {
78
+ const found = session.surface.nodes.filter(seq => isMemoryBlock(session.eventAt(seq)));
91
79
  state.retiring = [...new Set([...state.retiring, ...found])];
92
80
  if (found.length)
93
81
  state.restart = true;
94
- if (kinds.includes(memorySource)) {
95
- state.reload = true;
96
- state.pendingId = undefined;
97
- }
82
+ state.reload = true;
83
+ state.pendingId = undefined;
98
84
  }
99
85
  /** Where memory blocks sit on a session's surface, for the log: positions and event types only, never message text. */
100
86
  function memoryNodesOn(session) {
@@ -110,7 +96,7 @@ export function createWorldRuntime(ctx, config, store, world, memoryTurns = () =
110
96
  catch {
111
97
  continue;
112
98
  }
113
- if (message?.source?.kind && worldSources.includes(message.source.kind))
99
+ if (message?.source?.kind === memorySource)
114
100
  found.push(`#${seq}(${event.type})`);
115
101
  }
116
102
  return found.length ? found.slice(0, 8).join('、') + (found.length > 8 ? `…共 ${found.length} 个` : '') : '无';
@@ -129,38 +115,18 @@ export function createWorldRuntime(ctx, config, store, world, memoryTurns = () =
129
115
  const { session } = agent;
130
116
  if (memory.has(session) || !mayCarryWorld(session))
131
117
  return;
132
- const pending = attaching.get(session);
133
- if (pending)
134
- return pending;
135
- const job = faults.track(`memory:${session.id}`, `会话 ${session.id} 记忆初始化失败`, async () => {
136
- if (included(session)) {
137
- if (archived(session.id))
138
- await store.commitRecords([], store.progress(session.id));
139
- await archive.schedule(session.id);
140
- }
141
- const state = await readMemoryState(session);
142
- // Retiring writes a system/message, which the host only accepts inside an open turn and step; attach runs
143
- // between turns, so an out-of-scope block is retired by the next pre-step (before any request) instead (#22).
144
- memory.set(session, state);
145
- });
146
- attaching.set(session, job);
147
- try {
148
- await job;
149
- }
150
- finally {
151
- attaching.delete(session);
152
- }
118
+ // Retiring writes a system/message, which the host only accepts inside an open turn and step; attach runs
119
+ // between turns, so an out-of-scope block is retired by the next pre-step (before any request) instead (#22).
120
+ memory.set(session, newMemoryState(session));
121
+ if (included(session))
122
+ await archiveNow(session.id);
153
123
  }
154
- /** Retire old blocks, then admit fresh memory through the host's normal append path (#21). */
124
+ /** Retire old blocks, then admit fresh memory through the host's normal append path (#21). The caller checks the scope after the wait. */
155
125
  async function freshBlock(session, state) {
156
- const turns = await history.loadRecentTurns(config.worldId, memoryTurns(), archivedByScope);
157
- if (!included(session)) {
158
- retireMemory(session, state);
159
- return undefined;
160
- }
126
+ const turns = await history.loadRecentTurns(memoryTurns(), archivedByScope);
161
127
  const present = new Set(session.deriveMessages().map(message => message.id));
162
128
  const text = renderHistory(excludePresentMessages(turns, present), config.timeZone, names(), config.archiveScope === 'home');
163
- retireMemory(session, state, [memorySource]);
129
+ retireMemory(session, state);
164
130
  return text ? createUserMessage({ content: [{ type: 'text', text }], source: { kind: memorySource, form: 'recall' } }) : undefined;
165
131
  }
166
132
  /** Reads what the first catch-up had to leave, once the host can say which sessions belong to her. */
@@ -175,8 +141,6 @@ export function createWorldRuntime(ctx, config, store, world, memoryTurns = () =
175
141
  try {
176
142
  disposers.push(ctx.on('session/event', (session, event) => {
177
143
  const state = memory.get(session);
178
- if (state && event.type === 'step/start')
179
- state.position = { turn: event.data.turn, step: event.data.step };
180
144
  const compacted = event.type === 'compaction/end' && event.data.error === undefined;
181
145
  if (state && event.type === 'user/message' && event.data.id === state.pendingId) {
182
146
  state.reload = false;
@@ -185,19 +149,23 @@ export function createWorldRuntime(ctx, config, store, world, memoryTurns = () =
185
149
  if (state && compacted) {
186
150
  state.reload = true;
187
151
  }
188
- if (compacted)
152
+ // The host assembles the system prompt after turn/start, so a cold session's first request already has both.
153
+ const cold = !!state && event.type === 'turn/start' && state.lastRequestAt !== undefined && now() - state.lastRequestAt >= coldHours() * 60 * 60_000;
154
+ if (cold)
155
+ state.reload = true;
156
+ if (compacted || cold)
189
157
  prompts?.refresh(session);
190
- if (session.header.origin === 'subagent' || (session.header.delegationDepth ?? 0) > 0 || (!config.archiveScope && !belongsToWorld(session, config)))
158
+ if (!isOrdinarySession(session.header))
191
159
  return;
192
160
  if (event.type === 'assistant/message' || event.type === 'turn/end' || event.type === 'turn/start' || event.type === 'compaction/end' || (event.type === 'user/message' && event.data.source.kind === 'user'))
193
161
  void archive.schedule(session.id).catch(() => { });
194
162
  }));
195
163
  // 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.
164
+ // every retry (#27); attach never rejects, and its archive failures stay in the health list.
197
165
  disposers.push(ctx.on('agent/created', ({ agent }) => {
198
166
  prompts?.add(agent);
199
167
  syncTools(agent);
200
- void attach(agent).catch(error => ctx.logger.warn(`dsh-world: 会话 ${agent.id} 记忆初始化失败,第一次请求前会再试:`, error));
168
+ void attach(agent);
201
169
  return undefined;
202
170
  }));
203
171
  if (tools) {
@@ -225,37 +193,42 @@ export function createWorldRuntime(ctx, config, store, world, memoryTurns = () =
225
193
  if (!included(agent.session))
226
194
  return leave();
227
195
  state.inScope = true;
228
- await archive.schedule(agent.id);
196
+ await archiveNow(agent.id);
229
197
  signal.throwIfAborted();
230
198
  if (!included(agent.session))
231
199
  return leave();
232
200
  if (!state.reload)
233
201
  return decision;
234
- let block;
235
- await faults.track(`memory:${agent.id}`, `会话 ${agent.id} 记忆刷新失败`, async () => { block = await freshBlock(agent.session, state); });
202
+ // A block that cannot be built leaves the old one in place; she talks on, the fault shows, and the next step tries again.
203
+ let block, built = true;
204
+ await faults.track(`memory:${agent.id}`, `会话 ${agent.id} 记忆刷新失败`, async () => { block = await freshBlock(agent.session, state); }).catch(() => { built = false; });
236
205
  if (!included(agent.session))
237
206
  return leave();
238
207
  signal.throwIfAborted();
239
- if (!included(agent.session))
240
- return leave();
241
- if (state.reload && !block)
208
+ if (!built)
209
+ return decision;
210
+ if (!block) {
242
211
  state.reload = false;
243
- if (!block)
244
212
  return decision;
213
+ }
245
214
  state.pendingId = block.id;
246
215
  return { ...decision, messages: [block, ...decision.messages] };
247
216
  }));
248
217
  // The step is open here and its request is not built yet: the one place retired blocks can be written validly.
249
218
  disposers.push(ctx.on('agent/request', async function (payload, next) {
250
219
  const state = memory.get(payload.agent.session);
220
+ if (state) {
221
+ state.position = { turn: payload.turn, step: payload.step };
222
+ state.lastRequestAt = now();
223
+ }
251
224
  if (state?.retiring.length)
252
- flushRetired(payload.agent.session, state, { turn: payload.turn, step: payload.step });
225
+ flushRetired(payload.agent.session, state, state.position);
253
226
  return next();
254
227
  }));
255
228
  disposers.push(ctx.on('llm/stream', async function* (request, next) {
256
229
  const agent = isAgentLoopRequest(request) && request.sessionId ? ctx.agents.get(request.sessionId) : undefined;
257
230
  const owned = agent && included(agent.session);
258
- const inRequest = agent && !owned ? request.messages.filter(message => !!message.source?.kind && worldSources.includes(message.source.kind)).length : 0;
231
+ const inRequest = agent && !owned ? request.messages.filter(message => message.source?.kind === memorySource).length : 0;
259
232
  const placed = !!agent && !owned && !!prompts?.active(agent.session);
260
233
  if (agent && !owned && (placed || inRequest)) {
261
234
  const state = memory.get(agent.session);
@@ -285,14 +258,7 @@ export function createWorldRuntime(ctx, config, store, world, memoryTurns = () =
285
258
  await archive.skip(agent.id);
286
259
  for (const agent of ctx.agents.list()) {
287
260
  prompts?.add(agent);
288
- try {
289
- await attach(agent);
290
- }
291
- catch (error) {
292
- if (!isCorruptSessionLog(error))
293
- throw error;
294
- ctx.logger.warn(`dsh-world: 会话 ${agent.id} 记忆初始化失败,已隔离:`, error);
295
- }
261
+ await attach(agent);
296
262
  }
297
263
  }
298
264
  catch (error) {
@@ -1,23 +1,22 @@
1
1
  import { SessionId } from '@deepseek-ai/dsh-session';
2
- import { extractConversationRecords } from "./archive.js";
2
+ import { extractConversationRecords, isOrdinarySession } from "./archive.js";
3
3
  import { wechatDeliveryPatch } from "./ecosystem/wechat/archive.js";
4
4
  import { errorText, Faults } from "./faults.js";
5
5
  const pageSize = 128;
6
6
  /** Unreadable logs are isolated per source; their archive gaps remain visible until replay succeeds. */
7
7
  export function isCorruptSessionLog(error) {
8
8
  const text = error instanceof Error ? `${error.name} ${error.message}` : String(error ?? '');
9
- return /stored log is corrupt|SessionFormatError|does not match an open turn/i.test(text);
9
+ return /stored log is corrupt|SessionFormatError|does not match (?:an|the) open turn/i.test(text);
10
10
  }
11
11
  export function belongsToWorld(session, config) {
12
12
  const header = session.header;
13
- return header.agentPreset === config.agentPreset && header.origin !== 'subagent' && (header.delegationDepth ?? 0) === 0;
13
+ return header.agentPreset === config.agentPreset && isOrdinarySession(header);
14
14
  }
15
15
  /** One of her sessions that is also in her room's workspace; without a membership test, any of her sessions. */
16
16
  export function inWorld(session, config, inWorkspace) {
17
17
  return belongsToWorld(session, config) && (inWorkspace?.(session.id) ?? true);
18
18
  }
19
19
  export const isNotFound = (error) => error instanceof Error && error.name === 'SessionPersistenceNotFoundError';
20
- const ordinary = (header) => header.origin !== 'subagent' && (header.delegationDepth ?? 0) === 0;
21
20
  /**
22
21
  * Copies her conversations from the host's session logs into the archive. Each session is replayed from where
23
22
  * the archive left off; replays run one at a time, and a session already queued is not queued twice. Sessions
@@ -134,7 +133,7 @@ export function createSourceArchive(ctx, config, store, archived = () => true) {
134
133
  const visited = new Set();
135
134
  for (let offset = 0; offset < snapshots.length; offset += pageSize) {
136
135
  for (const { header } of snapshots.slice(offset, offset + pageSize)) {
137
- if (!ordinary(header) || (!config.archiveScope && header.agentPreset !== config.agentPreset) || !archived(header.id))
136
+ if (!isOrdinarySession(header) || !archived(header.id))
138
137
  continue;
139
138
  visited.add(header.id);
140
139
  await replayOne(header.id);
package/lib/store.d.ts CHANGED
@@ -12,7 +12,7 @@ export declare function createArchiveStore(config: WorldConfig & {
12
12
  hasRecord: (recordId: string) => boolean;
13
13
  updateRecord: (recordId: string, revise: (record: ConversationRecord) => Pick<ConversationRecord, "content" | "wechatDelivery"> & Partial<SpeakerIdentity>) => Promise<void>;
14
14
  readPage: (query: PageQuery) => Promise<RecordPage>;
15
- readTurn: (_worldId: string, turnId: string, afterSeq?: number, limit?: number) => Promise<ConversationRecord[]>;
15
+ readTurn: (turnId: string, afterSeq?: number, limit?: number) => Promise<ConversationRecord[]>;
16
16
  progress: (sessionId: string) => ExportProgress;
17
17
  forgetProgress: (sessionId: string) => void;
18
18
  sourcePage: (afterId?: string, limit?: number) => string[];
package/lib/store.js CHANGED
@@ -145,7 +145,7 @@ export function createArchiveStore(config) {
145
145
  });
146
146
  flushExports();
147
147
  }
148
- async function readTurn(_worldId, turnId, afterSeq = -1, limit = pageSize) {
148
+ async function readTurn(turnId, afterSeq = -1, limit = pageSize) {
149
149
  flushExports();
150
150
  return db.prepare('SELECT * FROM records WHERE turnId=? AND sourceSeq>? ORDER BY sourceSeq LIMIT ?').all(turnId, afterSeq, limit).map(decode);
151
151
  }
package/lib/types.d.ts CHANGED
@@ -97,11 +97,9 @@ export interface ConversationRecord extends Partial<SpeakerIdentity> {
97
97
  }
98
98
  export interface ArchiveScope {
99
99
  worldId: string;
100
- agentPreset: string;
101
100
  header: SessionHeader;
102
101
  inheritedEventCount: number;
103
102
  turn: number;
104
- archiveScope?: MemoryArchiveScope;
105
103
  }
106
104
  export interface ArchiveCursor {
107
105
  date: string;
@@ -110,7 +108,6 @@ export interface ArchiveCursor {
110
108
  maxSequence: number;
111
109
  }
112
110
  export interface PageQuery {
113
- worldId: string;
114
111
  before?: ArchiveCursor;
115
112
  limit: number;
116
113
  }
@@ -125,5 +122,5 @@ export interface ConversationTurn {
125
122
  }
126
123
  export interface ArchiveReader {
127
124
  readPage(query: PageQuery): Promise<RecordPage>;
128
- readTurn(worldId: string, turnId: string, afterSeq?: number, limit?: number): Promise<ConversationRecord[]>;
125
+ readTurn(turnId: string, afterSeq?: number, limit?: number): Promise<ConversationRecord[]>;
129
126
  }
@@ -50,6 +50,6 @@ export function renderWorldPrompt(prompt, template, self, home) {
50
50
  const { life, names } = prompt;
51
51
  return renderTemplate(template, { life: Boolean(life), home, selfFile: Boolean(self), conversationsDir: Boolean(prompt.conversationsDir), memoryTools: Boolean(prompt.memoryTools) }, {
52
52
  name: names.companion, partner: names.partner, homeTitle: homeTitle(names), selfFile: self?.file ?? '', self: self?.text ?? '', conversationsDir: prompt.conversationsDir ?? '',
53
- ...(life ? { roomDir: life.roomDir, diaryDir: life.diaryDir, fallbackWakeTime: life.fallbackWakeTime } : {}),
53
+ ...(life ? { roomDir: life.roomDir, diaryDir: life.diaryDir, fallbackWakeTime: life.schedule().wake } : {}),
54
54
  });
55
55
  }
@@ -1,6 +1,8 @@
1
1
  import { type MemoryArchiveScope } from './archiveSelection.ts';
2
2
  /** How many of the newest turns the memory block carries when nothing else is set. */
3
3
  export declare const DEFAULT_MEMORY_TURNS = 200;
4
+ /** Hours a session stays silent before its next turn re-reads her memory block and prompt (#36); see `runtime.ts`. */
5
+ export declare const DEFAULT_COLD_HOURS = 24, MAX_COLD_HOURS = 720;
4
6
  /** WeChat group messages read before a mention, and seconds a private image waits for its companions. */
5
7
  export declare const DEFAULT_WECHAT_CONTEXT = 5, MAX_WECHAT_CONTEXT = 20;
6
8
  export declare const DEFAULT_WECHAT_BUFFER_SECONDS = 3, MAX_WECHAT_BUFFER_SECONDS = 30;
@@ -10,7 +12,7 @@ export declare const DEFAULT_WECHAT_BUFFER_SECONDS = 3, MAX_WECHAT_BUFFER_SECOND
10
12
  * spend a day, and how many recent turns her memory block carries. A world that already has a life line from before the switch existed is running; a new one waits
11
13
  * for its partner to press start.
12
14
  */
13
- export declare function createWorldSwitch(worldDir: string, configuredScope?: MemoryArchiveScope): {
15
+ export declare function createWorldSwitch(worldDir: string, configuredScope?: MemoryArchiveScope, configuredWake?: string): {
14
16
  archiveScope: () => MemoryArchiveScope;
15
17
  selectedArchiveScope: () => MemoryArchiveScope;
16
18
  restartRequired: () => boolean;
@@ -31,6 +33,9 @@ export declare function createWorldSwitch(worldDir: string, configuredScope?: Me
31
33
  /** Turns in her memory block; read when a block is built, so a change shows from the next session start or compaction. */
32
34
  memoryTurns: () => number;
33
35
  setMemoryTurns(turns: number | undefined): void;
36
+ /** Read at every turn start, so a change applies from the next turn of each session. */
37
+ coldHours: () => number;
38
+ setColdHours(hours: number | undefined): void;
34
39
  /**
35
40
  * The console's switches for the WeChat and QQ modules; both are off until someone turns them on. QQ's SDK is an
36
41
  * optional dependency, so its code is not even loaded before then. WeChat used to default to on, so a world that
@@ -42,6 +47,14 @@ export declare function createWorldSwitch(worldDir: string, configuredScope?: Me
42
47
  wechat?: boolean;
43
48
  qq?: boolean;
44
49
  }): void;
50
+ /** Her evening look back and her morning wake when nothing is pending; the configured `fallbackWakeTime` is the morning's default. */
51
+ reviewTime: () => string;
52
+ wakeTime: () => string;
53
+ /** A field left out stays as it is; null goes back to its default. */
54
+ setSchedule(next: {
55
+ review?: string | null;
56
+ wake?: string | null;
57
+ }): void;
45
58
  /** Read by the WeChat adapter on its next poll; a batch already waiting keeps the value it started with. */
46
59
  wechatContext: () => number;
47
60
  wechatBufferSeconds: () => number;
@@ -52,6 +65,7 @@ export declare function createWorldSwitch(worldDir: string, configuredScope?: Me
52
65
  };
53
66
  export type WorldSwitch = ReturnType<typeof createWorldSwitch>;
54
67
  export declare const validTurns: (value: unknown) => value is number;
68
+ export declare const validColdHours: (value: unknown) => value is number;
55
69
  export declare const validWorkspacePermission: (value: unknown) => value is string;
56
70
  export declare const validWechatContext: (value: unknown) => value is number;
57
71
  export declare const validWechatBuffer: (value: unknown) => value is number;
@@ -2,8 +2,11 @@ import { existsSync, readFileSync } from 'node:fs';
2
2
  import { join } from 'node:path';
3
3
  import { durableWrite } from "./life/lifeStore.js";
4
4
  import { validArchiveScope } from "./archiveSelection.js";
5
+ import { DEFAULT_REVIEW_TIME, validClockTime } from "./life/alarm.js";
5
6
  /** How many of the newest turns the memory block carries when nothing else is set. */
6
7
  export const DEFAULT_MEMORY_TURNS = 200;
8
+ /** Hours a session stays silent before its next turn re-reads her memory block and prompt (#36); see `runtime.ts`. */
9
+ export const DEFAULT_COLD_HOURS = 24, MAX_COLD_HOURS = 720;
7
10
  /** WeChat group messages read before a mention, and seconds a private image waits for its companions. */
8
11
  export const DEFAULT_WECHAT_CONTEXT = 5, MAX_WECHAT_CONTEXT = 20;
9
12
  export const DEFAULT_WECHAT_BUFFER_SECONDS = 3, MAX_WECHAT_BUFFER_SECONDS = 30;
@@ -13,13 +16,14 @@ export const DEFAULT_WECHAT_BUFFER_SECONDS = 3, MAX_WECHAT_BUFFER_SECONDS = 30;
13
16
  * spend a day, and how many recent turns her memory block carries. A world that already has a life line from before the switch existed is running; a new one waits
14
17
  * for its partner to press start.
15
18
  */
16
- export function createWorldSwitch(worldDir, configuredScope = 'workspace') {
19
+ export function createWorldSwitch(worldDir, configuredScope = 'workspace', configuredWake = '09:00') {
17
20
  const file = join(worldDir, 'world.json');
18
21
  const stored = existsSync(file) ? JSON.parse(readFileSync(file, 'utf8')) : undefined;
19
22
  let settings = {
20
23
  running: stored ? stored.running === true : existsSync(join(worldDir, 'life.json')),
21
24
  ...(typeof stored?.dailyBudget === 'number' ? { dailyBudget: stored.dailyBudget } : {}),
22
25
  ...(validTurns(stored?.memoryTurns) ? { memoryTurns: stored.memoryTurns } : {}),
26
+ ...(validColdHours(stored?.coldHours) ? { coldHours: stored.coldHours } : {}),
23
27
  ...(validArchiveScope(stored?.archiveScope) ? { archiveScope: stored.archiveScope } : {}),
24
28
  ...(validWorkspacePermission(stored?.workspacePermission) ? { workspacePermission: stored.workspacePermission } : {}),
25
29
  ...(validWechatContext(stored?.wechatContext) ? { wechatContext: stored.wechatContext } : {}),
@@ -28,6 +32,8 @@ export function createWorldSwitch(worldDir, configuredScope = 'workspace') {
28
32
  ...(typeof stored?.qqEnabled === 'boolean' ? { qqEnabled: stored.qqEnabled } : {}),
29
33
  ...(stored?.compactAfterReview === false ? { compactAfterReview: false } : {}),
30
34
  ...(stored?.compactionSwapped === true ? { compactionSwapped: true } : {}),
35
+ ...(validClockTime(stored?.reviewTime) ? { reviewTime: stored.reviewTime } : {}),
36
+ ...(validClockTime(stored?.wakeTime) ? { wakeTime: stored.wakeTime } : {}),
31
37
  };
32
38
  const activeScope = settings.archiveScope ?? configuredScope;
33
39
  function save(next) {
@@ -72,6 +78,12 @@ export function createWorldSwitch(worldDir, configuredScope = 'workspace') {
72
78
  const { memoryTurns: _old, ...rest } = settings;
73
79
  save(turns === undefined || turns === DEFAULT_MEMORY_TURNS ? rest : { ...rest, memoryTurns: turns });
74
80
  },
81
+ /** Read at every turn start, so a change applies from the next turn of each session. */
82
+ coldHours: () => settings.coldHours ?? DEFAULT_COLD_HOURS,
83
+ setColdHours(hours) {
84
+ const { coldHours: _old, ...rest } = settings;
85
+ save(hours === undefined || hours === DEFAULT_COLD_HOURS ? rest : { ...rest, coldHours: hours });
86
+ },
75
87
  /**
76
88
  * The console's switches for the WeChat and QQ modules; both are off until someone turns them on. QQ's SDK is an
77
89
  * optional dependency, so its code is not even loaded before then. WeChat used to default to on, so a world that
@@ -84,6 +96,16 @@ export function createWorldSwitch(worldDir, configuredScope = 'workspace') {
84
96
  const wechat = next.wechat ?? wechatEnabled ?? existsSync(join(worldDir, 'wechat-outbox.sqlite')), qq = next.qq ?? qqEnabled === true;
85
97
  save({ ...rest, wechatEnabled: wechat, ...(qq ? { qqEnabled: true } : {}) });
86
98
  },
99
+ /** Her evening look back and her morning wake when nothing is pending; the configured `fallbackWakeTime` is the morning's default. */
100
+ reviewTime: () => settings.reviewTime ?? DEFAULT_REVIEW_TIME,
101
+ wakeTime: () => settings.wakeTime ?? configuredWake,
102
+ /** A field left out stays as it is; null goes back to its default. */
103
+ setSchedule(next) {
104
+ const { reviewTime: oldReview, wakeTime: oldWake, ...rest } = settings;
105
+ const review = next.review === undefined ? oldReview : next.review ?? undefined;
106
+ const wake = next.wake === undefined ? oldWake : next.wake ?? undefined;
107
+ save({ ...rest, ...(review === undefined || review === DEFAULT_REVIEW_TIME ? {} : { reviewTime: review }), ...(wake === undefined || wake === configuredWake ? {} : { wakeTime: wake }) });
108
+ },
87
109
  /** Read by the WeChat adapter on its next poll; a batch already waiting keeps the value it started with. */
88
110
  wechatContext: () => settings.wechatContext ?? DEFAULT_WECHAT_CONTEXT,
89
111
  wechatBufferSeconds: () => settings.wechatBufferSeconds ?? DEFAULT_WECHAT_BUFFER_SECONDS,
@@ -96,6 +118,7 @@ export function createWorldSwitch(worldDir, configuredScope = 'workspace') {
96
118
  };
97
119
  }
98
120
  export const validTurns = (value) => typeof value === 'number' && Number.isInteger(value) && value >= 1;
121
+ export const validColdHours = (value) => typeof value === 'number' && Number.isInteger(value) && value >= 1 && value <= MAX_COLD_HOURS;
99
122
  export const validWorkspacePermission = (value) => typeof value === 'string' && value.trim().length > 0;
100
123
  export const validWechatContext = (value) => typeof value === 'number' && Number.isInteger(value) && value >= 1 && value <= MAX_WECHAT_CONTEXT;
101
124
  export const validWechatBuffer = (value) => typeof value === 'number' && Number.isFinite(value) && value >= 0 && value <= MAX_WECHAT_BUFFER_SECONDS;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-world",
3
- "version": "0.7.0",
3
+ "version": "0.7.2",
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": {
@@ -1,29 +1,29 @@
1
- #!/usr/bin/env node
2
- // Asks a running world to compact her home conversation once (held behind her running turn).
3
- // Needs `bridge: true` in the plugin config. Usage: node scripts/compact-home.mjs [world directory]
4
- // The world directory defaults to $DSH_WORLD_DIR, then ~/.dsh/worlds/<the only world there>.
5
- import { existsSync, readFileSync, readdirSync } from 'node:fs';
6
- import { homedir } from 'node:os';
7
- import { join } from 'node:path';
8
-
9
- function worldDir() {
10
- if (process.argv[2]) return process.argv[2];
11
- if (process.env.DSH_WORLD_DIR) return process.env.DSH_WORLD_DIR;
12
- const root = join(homedir(), '.dsh', 'worlds');
13
- const worlds = existsSync(root) ? readdirSync(root, { withFileTypes: true }).filter(entry => entry.isDirectory()).map(entry => entry.name) : [];
14
- if (worlds.length !== 1) throw new Error(`找不到唯一的世界目录,请把路径作为参数传入(在 ${root} 下找到 ${worlds.length} 个)`);
15
- return join(root, worlds[0]);
16
- }
17
-
18
- try {
19
- const file = join(worldDir(), 'bridge.json');
20
- if (!existsSync(file)) throw new Error(`没有 ${file}:世界没有在运行,或者没有开启 bridge`);
21
- const { origin, token } = JSON.parse(readFileSync(file, 'utf8'));
22
- const response = await fetch(new URL('/dsh-world/bridge/compact', origin), { method: 'POST', headers: { 'x-dsh-world-token': token }, signal: AbortSignal.timeout(15000) });
23
- const body = await response.json().catch(() => ({}));
24
- if (response.status === 202) console.log('已请求压缩家会话;她正在忙的话会等这一轮结束后再压缩。');
25
- else { console.error(`没有受理(${response.status}):${body.error ?? '未知原因'}`); process.exitCode = 1; }
26
- } catch (error) {
27
- console.error(error instanceof Error ? error.message : String(error));
28
- process.exitCode = 1;
29
- }
1
+ #!/usr/bin/env node
2
+ // Asks a running world to compact her home conversation once (held behind her running turn).
3
+ // Needs `bridge: true` in the plugin config. Usage: node scripts/compact-home.mjs [world directory]
4
+ // The world directory defaults to $DSH_WORLD_DIR, then ~/.dsh/worlds/<the only world there>.
5
+ import { existsSync, readFileSync, readdirSync } from 'node:fs';
6
+ import { homedir } from 'node:os';
7
+ import { join } from 'node:path';
8
+
9
+ function worldDir() {
10
+ if (process.argv[2]) return process.argv[2];
11
+ if (process.env.DSH_WORLD_DIR) return process.env.DSH_WORLD_DIR;
12
+ const root = join(homedir(), '.dsh', 'worlds');
13
+ const worlds = existsSync(root) ? readdirSync(root, { withFileTypes: true }).filter(entry => entry.isDirectory()).map(entry => entry.name) : [];
14
+ if (worlds.length !== 1) throw new Error(`找不到唯一的世界目录,请把路径作为参数传入(在 ${root} 下找到 ${worlds.length} 个)`);
15
+ return join(root, worlds[0]);
16
+ }
17
+
18
+ try {
19
+ const file = join(worldDir(), 'bridge.json');
20
+ if (!existsSync(file)) throw new Error(`没有 ${file}:世界没有在运行,或者没有开启 bridge`);
21
+ const { origin, token } = JSON.parse(readFileSync(file, 'utf8'));
22
+ const response = await fetch(new URL('/dsh-world/bridge/compact', origin), { method: 'POST', headers: { 'x-dsh-world-token': token }, signal: AbortSignal.timeout(15000) });
23
+ const body = await response.json().catch(() => ({}));
24
+ if (response.status === 202) console.log('已请求压缩家会话;她正在忙的话会等这一轮结束后再压缩。');
25
+ else { console.error(`没有受理(${response.status}):${body.error ?? '未知原因'}`); process.exitCode = 1; }
26
+ } catch (error) {
27
+ console.error(error instanceof Error ? error.message : String(error));
28
+ process.exitCode = 1;
29
+ }
@@ -1,33 +1,33 @@
1
- param(
2
- [Parameter(Mandatory = $true)]
3
- [string] $profilePath
4
- )
5
-
6
- $ErrorActionPreference = 'Stop'
7
- try {
8
- $resolvedProfile = (Resolve-Path -LiteralPath $profilePath).Path
9
- $packagePath = Join-Path $resolvedProfile 'package.json'
10
- $patchPath = Join-Path $resolvedProfile 'cordis.patch.yml'
11
- $package = Get-Content -LiteralPath $packagePath -Raw | ConvertFrom-Json
12
- if (-not $package.dependencies.'dsh-world') {
13
- throw 'Install the built dsh-world package in this profile before enabling its compaction backend.'
14
- }
15
- $content = [System.IO.File]::ReadAllText($patchPath)
16
- if ($content -match '(?m)^\s*name:\s*[''"'']?dsh-world/compaction[''"'']?\s*$') {
17
- Write-Output 'Tool-free compaction is already configured.'
18
- return
19
- }
20
- $pattern = '(?m)^(\s*name:\s*)([''"'']?)@deepseek-ai/dsh-compaction-basic\2([ \t]*(?:#.*)?\r?)$'
21
- $matchesFound = [regex]::Matches($content, $pattern)
22
- if ($matchesFound.Count -ne 1) {
23
- throw "Expected exactly one explicit compaction-basic entry in cordis.patch.yml; found $($matchesFound.Count). No configuration was changed."
24
- }
25
- $updated = [regex]::Replace($content, $pattern, '${1}''dsh-world/compaction''${3}')
26
- $backupPath = "$patchPath.dsh-world.$([Guid]::NewGuid().ToString('N')).bak"
27
- $temporaryPath = "$patchPath.$([Guid]::NewGuid().ToString('N')).tmp"
28
- [System.IO.File]::WriteAllText($temporaryPath, $updated, [System.Text.UTF8Encoding]::new($false))
29
- [System.IO.File]::Replace($temporaryPath, $patchPath, $backupPath)
30
- Write-Output "Configured tool-free compaction. Restart this DSH profile to load it. Backup: $backupPath"
31
- } catch {
32
- throw "Cannot configure dsh-world compaction: $($_.Exception.Message)"
33
- }
1
+ param(
2
+ [Parameter(Mandatory = $true)]
3
+ [string] $profilePath
4
+ )
5
+
6
+ $ErrorActionPreference = 'Stop'
7
+ try {
8
+ $resolvedProfile = (Resolve-Path -LiteralPath $profilePath).Path
9
+ $packagePath = Join-Path $resolvedProfile 'package.json'
10
+ $patchPath = Join-Path $resolvedProfile 'cordis.patch.yml'
11
+ $package = Get-Content -LiteralPath $packagePath -Raw | ConvertFrom-Json
12
+ if (-not $package.dependencies.'dsh-world') {
13
+ throw 'Install the built dsh-world package in this profile before enabling its compaction backend.'
14
+ }
15
+ $content = [System.IO.File]::ReadAllText($patchPath)
16
+ if ($content -match '(?m)^\s*name:\s*[''"'']?dsh-world/compaction[''"'']?\s*$') {
17
+ Write-Output 'Tool-free compaction is already configured.'
18
+ return
19
+ }
20
+ $pattern = '(?m)^(\s*name:\s*)([''"'']?)@deepseek-ai/dsh-compaction-basic\2([ \t]*(?:#.*)?\r?)$'
21
+ $matchesFound = [regex]::Matches($content, $pattern)
22
+ if ($matchesFound.Count -ne 1) {
23
+ throw "Expected exactly one explicit compaction-basic entry in cordis.patch.yml; found $($matchesFound.Count). No configuration was changed."
24
+ }
25
+ $updated = [regex]::Replace($content, $pattern, '${1}''dsh-world/compaction''${3}')
26
+ $backupPath = "$patchPath.dsh-world.$([Guid]::NewGuid().ToString('N')).bak"
27
+ $temporaryPath = "$patchPath.$([Guid]::NewGuid().ToString('N')).tmp"
28
+ [System.IO.File]::WriteAllText($temporaryPath, $updated, [System.Text.UTF8Encoding]::new($false))
29
+ [System.IO.File]::Replace($temporaryPath, $patchPath, $backupPath)
30
+ Write-Output "Configured tool-free compaction. Restart this DSH profile to load it. Backup: $backupPath"
31
+ } catch {
32
+ throw "Cannot configure dsh-world compaction: $($_.Exception.Message)"
33
+ }