dsh-world 0.7.2 → 0.7.4

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 (78) hide show
  1. package/CHANGELOG.md +403 -379
  2. package/INSTALL.md +314 -314
  3. package/LICENSE +21 -21
  4. package/NOTES.md +23 -13
  5. package/README.md +22 -7
  6. package/client/index.js +74 -27
  7. package/cordis.patch.yml +6 -6
  8. package/lib/archiveSelection.d.ts +6 -2
  9. package/lib/archiveSelection.js +21 -12
  10. package/lib/compaction.d.ts +7 -0
  11. package/lib/compaction.js +18 -9
  12. package/lib/compactionSwap.d.ts +17 -0
  13. package/lib/compactionSwap.js +68 -6
  14. package/lib/console/routes.d.ts +2 -3
  15. package/lib/console/routes.js +7 -8
  16. package/lib/console/snapshot.d.ts +1 -3
  17. package/lib/console/snapshot.js +0 -3
  18. package/lib/ecosystem/bridge/bridge.d.ts +5 -0
  19. package/lib/ecosystem/bridge/bridge.js +2 -1
  20. package/lib/ecosystem/bridge/route.d.ts +4 -6
  21. package/lib/ecosystem/bridge/route.js +34 -58
  22. package/lib/ecosystem/qq/panel.d.ts +0 -1
  23. package/lib/ecosystem/qq/route.d.ts +6 -7
  24. package/lib/ecosystem/qq/route.js +10 -10
  25. package/lib/ecosystem/qq/snowluma-start.d.ts +1 -0
  26. package/lib/ecosystem/qq/snowluma-start.js +41 -8
  27. package/lib/ecosystem/qq/supervisor.d.ts +1 -2
  28. package/lib/ecosystem/qq/supervisor.js +4 -2
  29. package/lib/ecosystem/qq-native/index.js +2 -0
  30. package/lib/ecosystem/qq-native/native-bridge.d.ts +0 -1
  31. package/lib/ecosystem/qq-native/native-bridge.js +0 -2
  32. package/lib/ecosystem/qq-native/snowluma.js +11 -2
  33. package/lib/ecosystem/shared/turn.d.ts +3 -0
  34. package/lib/ecosystem/shared/turn.js +9 -2
  35. package/lib/ecosystem/wechat/home.d.ts +3 -0
  36. package/lib/ecosystem/wechat/home.js +12 -4
  37. package/lib/ecosystem/wechat/index.d.ts +0 -1
  38. package/lib/ecosystem/wechat/index.js +9 -6
  39. package/lib/hostContract.d.ts +19 -0
  40. package/lib/index.js +117 -49
  41. package/lib/life/toolRegistry.js +2 -2
  42. package/lib/memoryFiles.d.ts +0 -1
  43. package/lib/memoryStore.d.ts +0 -1
  44. package/lib/memoryStore.js +0 -1
  45. package/lib/memoryTools.d.ts +0 -1
  46. package/lib/memoryTools.js +2 -3
  47. package/lib/mood.d.ts +28 -0
  48. package/lib/mood.js +69 -0
  49. package/lib/promptSection.d.ts +7 -5
  50. package/lib/promptSection.js +74 -28
  51. package/lib/runtime.d.ts +6 -2
  52. package/lib/runtime.js +163 -26
  53. package/lib/self.d.ts +1 -1
  54. package/lib/self.js +1 -1
  55. package/lib/sourceArchive.d.ts +4 -2
  56. package/lib/sourceArchive.js +18 -4
  57. package/lib/store.js +2 -1
  58. package/lib/types.d.ts +3 -1
  59. package/lib/worldPrompt.d.ts +2 -3
  60. package/lib/worldPrompt.js +2 -3
  61. package/lib/worldRoutes.d.ts +9 -0
  62. package/lib/worldRoutes.js +29 -0
  63. package/lib/worldScope.d.ts +5 -5
  64. package/lib/worldScope.js +16 -7
  65. package/lib/worldSwitch.d.ts +1 -2
  66. package/lib/worldSwitch.js +1 -1
  67. package/package.json +17 -16
  68. package/scripts/compact-home.mjs +29 -29
  69. package/scripts/enable-tool-free-compaction.ps1 +33 -33
  70. package/scripts/import-stickers.mjs +17 -17
  71. package/scripts/update-world.mjs +2 -2
  72. package/src/ecosystem/README.md +1 -1
  73. package/src/ecosystem/wechat/windows/README.md +3 -3
  74. package/src/ecosystem/wechat/windows/adapter.py +21 -3
  75. package/src/ecosystem/wechat/windows/engine/profiles.json +142 -142
  76. package/src/ecosystem/wechat/windows/presence.py +109 -109
  77. package/templates/alarm.md +2 -2
  78. package/templates/world-prompt.md +11 -2
@@ -1,38 +1,64 @@
1
+ import { statSync } from 'node:fs';
2
+ import { isDeepStrictEqual } from 'node:util';
1
3
  import { readPersona, renderPersona } from "./persona.js";
2
4
  import { renderSelf } from "./self.js";
3
5
  import { belongsToWorld, inWorld } from "./sourceArchive.js";
4
- import { readTemplate, renderWorldPrompt } from "./worldPrompt.js";
6
+ import { DEFAULT_TEMPLATE_FILE, readTemplate, renderWorldPrompt } from "./worldPrompt.js";
5
7
  import { reassembleOnChange } from "./worldScope.js";
8
+ export const WORLD_PROMPT_PREFIX = 'dsh-world:';
6
9
  /** The stock "You are an AI agent powered by DeepSeek Harness." line; a section of the same name on her agent shadows it. */
7
10
  const HARNESS_IDENTITY = 'harness:identity';
11
+ function cachePromptFile(file, read) {
12
+ let cached;
13
+ return force => {
14
+ let version = '';
15
+ try {
16
+ const stat = file ? statSync(file, { throwIfNoEntry: false }) : undefined;
17
+ if (stat)
18
+ version = `${stat.ino}:${stat.size}:${stat.mtimeMs}:${stat.ctimeMs}`;
19
+ }
20
+ catch {
21
+ cached = undefined;
22
+ return read();
23
+ }
24
+ if (!force && cached?.version === version)
25
+ return cached.value;
26
+ const value = read();
27
+ cached = { version, value };
28
+ return value;
29
+ };
30
+ }
8
31
  /**
9
32
  * Her persona and the world prompt both reach only sessions of her preset inside the world's workspace, and come and
10
33
  * go together as a session enters or leaves it: the preset alone is DSH's default `standard` for most setups, so it
11
34
  * would turn every unrelated session into her (#37). Both are sections of the session's system prompt so she sees them on every
12
- * request. They are read when the session opens and again after each successful compaction (the host assembles
13
- * the system prompt before pre-step, so the refresh happens on compaction/end), when a cold session speaks again
14
- * (`coldHours` in `runtime.ts`, on turn/start) or on explicit console application, so the prompt stays in the provider-cached prefix. Whether the session is her home is asked per request.
35
+ * request. Checking the files during assembly also covers compression outside DSH (#42). The prompt stays in the
36
+ * provider-cached prefix while its content is the same. Whether the session is her home is asked per request.
15
37
  *
16
38
  * Her persona takes the place of DeepSeek Harness's stock identity line, but never of a persona someone has set: it is its own
17
39
  * section placed right after the host's persona slot, so a system persona the deployment or her preset already has stays
18
40
  * where it is and hers follows it.
19
41
  */
20
42
  export function createPromptSections(config, world, deps) {
43
+ const sectionName = WORLD_PROMPT_PREFIX + config.worldId;
21
44
  const entries = new Map();
22
45
  const agents = new WeakMap();
23
- function read(includeWorld) {
24
- const persona = world.prompt.persona ? renderPersona(readPersona(world.prompt.persona)) : '';
25
- const names = world.names?.() ?? world.prompt.names;
26
- if (!includeWorld)
27
- return { template: '', persona, names };
46
+ const persona = cachePromptFile(world.prompt.persona, () => ({
47
+ persona: world.prompt.persona ? renderPersona(readPersona(world.prompt.persona)) : '',
48
+ names: world.names?.() ?? world.prompt.names,
49
+ }));
50
+ const template = cachePromptFile(world.prompt.file ?? DEFAULT_TEMPLATE_FILE, () => {
28
51
  const template = readTemplate(world.prompt.file);
29
52
  if (template.error)
30
53
  deps.logger.warn(`dsh-world: ${template.error}`);
31
- return {
32
- template: template.text,
33
- ...(config.selfFile ? { self: { file: config.selfFile, text: renderSelf(config.selfFile) } } : {}),
34
- persona, names,
35
- };
54
+ return template.text;
55
+ });
56
+ const self = cachePromptFile(config.selfFile, () => config.selfFile ? { file: config.selfFile, text: renderSelf(config.selfFile) } : undefined);
57
+ let forceRead = false;
58
+ function read() {
59
+ const force = forceRead;
60
+ forceRead = false;
61
+ return { template: template(force), self: self(force), ...persona(force) };
36
62
  }
37
63
  /** Registers her persona while the session is in her workspace and she has one; drops it otherwise. */
38
64
  function placePersona(agent, entry) {
@@ -46,7 +72,7 @@ export function createPromptSections(config, world, deps) {
46
72
  const prompt = agent.ctx.systemPrompt;
47
73
  const order = prompt.getSectionOrder('DEPLOYMENT_PERSONA_PREFIX') ?? 0;
48
74
  const text = () => entry.text.persona;
49
- const persona = prompt.section({ name: 'dsh-world-persona', order: order + 1, interpolate: false, text });
75
+ const persona = prompt.section({ name: sectionName + ':persona', order: order + 1, interpolate: false, text });
50
76
  // DeepSeek Harness's own identity line gives way to hers; a persona someone set in DSH sits in its own slot and is left alone.
51
77
  // If a preset already put its own words on that identity slot for this agent, they stay exactly as written.
52
78
  let identity;
@@ -56,44 +82,64 @@ export function createPromptSections(config, world, deps) {
56
82
  catch { /* the slot is already taken for this agent */ }
57
83
  entry.persona = () => { persona(); identity?.(); };
58
84
  }
85
+ function refresh(agent, entry) {
86
+ const text = read();
87
+ if (isDeepStrictEqual(text, entry.text))
88
+ return false;
89
+ entry.text = text;
90
+ entry.restart = true;
91
+ placePersona(agent, entry);
92
+ return true;
93
+ }
59
94
  return {
60
95
  add(agent) {
61
96
  if (entries.has(agent) || !belongsToWorld(agent.session, config))
62
97
  return;
63
98
  let disposeWorld;
64
- /** Places or removes the world prompt and her persona as the session enters or leaves her workspace; true when it did. */
65
- const sync = () => {
66
- if (inWorld(agent.session, config, world.inWorkspace) === entry.active)
99
+ /** Reassemble if the placement or the content changed since the host collected the sections. */
100
+ const sync = (current) => {
101
+ if (current !== agent)
67
102
  return false;
68
- entry.active = !entry.active;
103
+ const active = inWorld(agent.session, config, world.inWorkspace);
104
+ if (active === entry.active)
105
+ return active && refresh(agent, entry);
106
+ entry.active = active;
107
+ entry.restart = true;
69
108
  if (!entry.active) {
70
109
  disposeWorld?.();
71
110
  disposeWorld = undefined;
72
111
  placePersona(agent, entry);
73
112
  return true;
74
113
  }
75
- entry.text = read(true);
76
- disposeWorld = agent.ctx.systemPrompt.section({ name: 'dsh-world', order: 50, interpolate: false, text: () => renderWorldPrompt({ ...world.prompt, names: entry.text.names }, entry.text.template, entry.text.self, world.isHome(agent.id)) });
114
+ entry.text = read();
115
+ disposeWorld = agent.ctx.systemPrompt.section({ name: sectionName, order: 50, interpolate: false, text: () => renderWorldPrompt({ ...world.prompt, names: entry.text.names }, entry.text.template, entry.text.self, world.isHome(agent.id)) });
77
116
  placePersona(agent, entry);
78
117
  return true;
79
118
  };
80
119
  const disposeSync = reassembleOnChange(agent.ctx, sync);
81
- const entry = { text: read(false), active: false, dispose: () => { disposeSync(); disposeWorld?.(); } };
120
+ const entry = { text: { template: '', persona: '', names: world.prompt.names }, active: false, restart: false, dispose: () => { disposeSync(); disposeWorld?.(); } };
82
121
  entries.set(agent, entry);
83
122
  agents.set(agent.session, agent);
84
- sync();
123
+ sync(agent);
85
124
  },
86
125
  active(session) {
87
126
  const agent = agents.get(session);
88
127
  return !!(agent && entries.get(agent)?.active);
89
128
  },
90
- refresh(session) {
129
+ /** On in-history routes, start a new series to replace the old prompt instead of appending to it. */
130
+ takeRestart(session) {
91
131
  const agent = agents.get(session);
92
132
  const entry = agent && entries.get(agent);
93
- if (!agent || !entry)
94
- return;
95
- entry.text = read(entry.active);
96
- placePersona(agent, entry);
133
+ if (!entry?.restart)
134
+ return false;
135
+ entry.restart = false;
136
+ return true;
137
+ },
138
+ refresh(session) {
139
+ const agent = agents.get(session);
140
+ // A compaction can finish after the current step assembled its prompt.
141
+ if (agent && entries.get(agent)?.active)
142
+ forceRead = true;
97
143
  },
98
144
  clear() {
99
145
  for (const entry of entries.values())
package/lib/runtime.d.ts CHANGED
@@ -5,6 +5,8 @@ import { type WorldPromptSource } from './promptSection.ts';
5
5
  import type { ArchiveStore } from './store.ts';
6
6
  import type { WorldConfig } from './types.ts';
7
7
  export type { WorldPromptSource } from './promptSection.ts';
8
+ /** A session can outlive its world. Authorization returns false for a stopped world and undefined outside it. */
9
+ export declare function guardWorldContext(ctx: Context, authorize: (session: Session, worldId?: string) => symbol | false | undefined): void;
8
10
  /**
9
11
  * The memory line: her conversations are archived as they happen, and every world session gets a memory
10
12
  * block of the newest turns at its start, after each successful compaction and when it speaks again after being cold,
@@ -14,10 +16,12 @@ export type { WorldPromptSource } from './promptSection.ts';
14
16
  *
15
17
  * A session silent for `coldHours` (read at each turn start, default 24) is cold (#36): its provider cache has most
16
18
  * likely expired (DeepSeek clears an unused one "usually within a few hours to a few days", best effort), so its next
17
- * turn re-reads her memory block and prompt as a newly opened session would, at the cost of at most one uncached
18
- * request. A conversation in progress does not pause that long, so its cached prefix stays whole.
19
+ * turn first summarizes the old conversation, then re-reads her memory block and prompt as a newly opened session
20
+ * would: that first request misses the cache anyway, and every later step carries the summary instead of the whole old
21
+ * conversation. A conversation in progress does not pause that long, so its cached prefix stays whole.
19
22
  */
20
23
  export declare function createWorldRuntime(ctx: Context, config: WorldConfig, store: ArchiveStore, world?: WorldPromptSource, memoryTurns?: () => number, coldHours?: () => number, now?: () => number): {
24
+ scopeToken: symbol;
21
25
  start: (options?: {
22
26
  fresh?: boolean;
23
27
  }) => Promise<void>;
package/lib/runtime.js CHANGED
@@ -1,16 +1,97 @@
1
- import { createSystemMessage, createUserMessage, isAgentLoopRequest } from '@deepseek-ai/dsh-llm';
1
+ import { createSystemMessage, createUserMessage, isAgentLoopRequest, LlmError } from '@deepseek-ai/dsh-llm';
2
2
  import "./hostContract.js";
3
3
  import { isOrdinarySession } from "./archive.js";
4
+ import { compactsWhole } from "./compaction.js";
5
+ import { compactionFor } from "./console/homeApply.js";
4
6
  import { Faults } from "./faults.js";
5
7
  import { createHistory, excludePresentMessages, renderHistory } from "./history.js";
8
+ import { MOOD_CLEARED, moodText, readMood } from "./mood.js";
6
9
  import { createWorldToolRegistry, memoryTools } from "./memoryTools.js";
7
- import { createPromptSections } from "./promptSection.js";
8
- import { belongsToWorld, createSourceArchive, inWorld } from "./sourceArchive.js";
10
+ import { createPromptSections, WORLD_PROMPT_PREFIX } from "./promptSection.js";
11
+ import { belongsToWorld, createSourceArchive, inWorld, sessionPreset } from "./sourceArchive.js";
9
12
  import { worldNames } from "./worldPrompt.js";
10
13
  import { reassembleOnChange } from "./worldScope.js";
11
14
  import { DEFAULT_COLD_HOURS, DEFAULT_MEMORY_TURNS } from "./worldSwitch.js";
12
15
  const memorySource = 'dsh-world-history';
13
- const isMemoryBlock = (event) => event?.type === 'user/message' && event.data.source.kind === memorySource;
16
+ const moodSource = 'dsh-world-mood';
17
+ const isRecall = (source, worldId) => source?.kind === memorySource && (worldId === undefined || source.worldId === undefined || source.worldId === worldId);
18
+ function recallNodes(session, match) {
19
+ return session.surface.nodes.filter(seq => {
20
+ const event = session.eventAt(seq);
21
+ return event?.type === 'user/message' && match(event.data.source);
22
+ });
23
+ }
24
+ /** Empty system nodes retire recall from the model's context and leave the original events intact. */
25
+ function retireRecall(session, retiring, position) {
26
+ for (const seq of retiring) {
27
+ if (!session.surface.nodes.includes(seq))
28
+ continue;
29
+ session.append('system/message', { ...position, message: createSystemMessage('') }, { surfaceOp: { op: 'replace', startSeq: seq, endSeq: seq }, sourceEventSeqs: [seq] });
30
+ }
31
+ }
32
+ /** A session can outlive its world. Authorization returns false for a stopped world and undefined outside it. */
33
+ export function guardWorldContext(ctx, authorize) {
34
+ const assemblies = new WeakMap();
35
+ const previousPrompts = new WeakMap();
36
+ const revoked = (source, session) => {
37
+ if (source?.kind === memorySource || source?.kind === moodSource)
38
+ return !session || !authorize(session, source.worldId);
39
+ return source?.kind === 'dsh-world-channel-context' && (!session || !authorize(session));
40
+ };
41
+ ctx.on('system-prompt/assemble', async (_assembly, context, next) => {
42
+ const result = await next();
43
+ if (context.signal && context.agent) {
44
+ const section = result.sections.find(section => section.name.startsWith(WORLD_PROMPT_PREFIX));
45
+ if (section) {
46
+ const worldId = section.name.slice(WORLD_PROMPT_PREFIX.length).split(':', 1)[0];
47
+ assemblies.set(context.signal, { worldId, token: authorize(context.agent.session, worldId) || undefined });
48
+ }
49
+ else
50
+ assemblies.delete(context.signal);
51
+ }
52
+ return result;
53
+ }, { prepend: true });
54
+ ctx.on('agent/pre-step', async ({ agent, signal }, next) => {
55
+ const decision = await next();
56
+ if (decision.kind !== 'enter')
57
+ return decision;
58
+ const { session } = agent;
59
+ const token = assemblies.get(signal)?.token;
60
+ const previous = previousPrompts.get(session);
61
+ const promptChanged = previous && (!token || previous.token !== token);
62
+ return promptChanged || recallNodes(session, source => revoked(source, session)).length ? { ...decision, startsRequestSeries: true } : decision;
63
+ });
64
+ ctx.on('agent/request', ({ agent: { session }, turn, step }, next) => {
65
+ retireRecall(session, recallNodes(session, source => revoked(source, session)), { turn, step });
66
+ return next();
67
+ });
68
+ ctx.on('llm/stream', async function* (request, next) {
69
+ const compaction = request.purpose === 'compaction';
70
+ if (!compaction && !isAgentLoopRequest(request)) {
71
+ yield* next();
72
+ return;
73
+ }
74
+ const session = request.sessionId ? ctx.get('sessions')?.get(request.sessionId) : undefined;
75
+ // Both compaction engines replay the saved prompt without assembling a new one.
76
+ const prompt = compaction ? session && previousPrompts.get(session) : request.signal && assemblies.get(request.signal);
77
+ if (!compaction && session && prompt)
78
+ previousPrompts.set(session, prompt);
79
+ const scope = session && (compaction || prompt) ? authorize(session, prompt?.worldId) : undefined;
80
+ const stalePrompt = prompt && (!scope || (!compaction && scope !== prompt.token));
81
+ const failure = { code: 'DSH_WORLD_SCOPE_CHANGED', message: compaction
82
+ ? 'dsh-world: 世界已停止或会话已离开世界工作区,已取消压缩。'
83
+ : 'dsh-world: 世界权限已变化,已阻止携带旧世界上下文的请求,请重新发送。' };
84
+ if (scope === false || stalePrompt || request.messages.some(message => revoked(message.source, session))) {
85
+ yield { type: 'finish', reason: { kind: 'error', failure } };
86
+ return;
87
+ }
88
+ if (!compaction && session && !prompt)
89
+ previousPrompts.delete(session);
90
+ yield* next();
91
+ if (compaction && session && scope && authorize(session, prompt?.worldId) !== scope)
92
+ throw new LlmError(failure.message, failure.code);
93
+ });
94
+ }
14
95
  /**
15
96
  * The memory line: her conversations are archived as they happen, and every world session gets a memory
16
97
  * block of the newest turns at its start, after each successful compaction and when it speaks again after being cold,
@@ -20,8 +101,9 @@ const isMemoryBlock = (event) => event?.type === 'user/message' && event.data.so
20
101
  *
21
102
  * A session silent for `coldHours` (read at each turn start, default 24) is cold (#36): its provider cache has most
22
103
  * 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.
104
+ * turn first summarizes the old conversation, then re-reads her memory block and prompt as a newly opened session
105
+ * would: that first request misses the cache anyway, and every later step carries the summary instead of the whole old
106
+ * conversation. A conversation in progress does not pause that long, so its cached prefix stays whole.
25
107
  */
26
108
  export function createWorldRuntime(ctx, config, store, world, memoryTurns = () => DEFAULT_MEMORY_TURNS, coldHours = () => DEFAULT_COLD_HOURS, now = Date.now) {
27
109
  if (config.archiveScope === 'workspace' && !world?.archiveSession)
@@ -41,11 +123,12 @@ export function createWorldRuntime(ctx, config, store, world, memoryTurns = () =
41
123
  const history = createHistory(store);
42
124
  const names = () => world?.names?.() ?? world?.prompt.names ?? worldNames(config);
43
125
  const included = (session) => inWorld(session, config, world?.inWorkspace);
126
+ const ownMemory = (source) => isRecall(source, config.worldId);
44
127
  const faults = new Faults();
45
128
  const prompts = world && createPromptSections(config, world, { logger: ctx.logger });
46
129
  const memory = new WeakMap();
47
- const toolSets = [world?.memory ? (inside) => memoryTools(world.memory, inside) : undefined].filter(make => !!make);
48
- const tools = toolSets.length ? createWorldToolRegistry({ tools: inside => toolSets.flatMap(make => make(inside)), inWorld: agent => !stopped && included(agent.session), faults, logger: ctx.logger }) : undefined;
130
+ const service = world?.memory;
131
+ const tools = service ? createWorldToolRegistry({ tools: inside => memoryTools(service, inside), inWorld: agent => !stopped && included(agent.session), faults, logger: ctx.logger }) : undefined;
49
132
  /** The memory tools follow world membership, whatever the life line does. */
50
133
  const syncTools = (agent) => !tools ? false : included(agent.session) ? tools.attach(agent) : tools.detach(agent);
51
134
  const disposers = [];
@@ -55,10 +138,13 @@ export function createWorldRuntime(ctx, config, store, world, memoryTurns = () =
55
138
  * Whether the session may carry her world: her preset, or a memory block inherited onto its surface (a delegated
56
139
  * child of her session). Everything else is never read from disk or tracked. The check stays in memory.
57
140
  */
58
- const mayCarryWorld = (session) => belongsToWorld(session, config) || memory.has(session) || session.surface.nodes.some(seq => isMemoryBlock(session.eventAt(seq)));
141
+ const mayCarryWorld = (session) => belongsToWorld(session, config) || memory.has(session) || session.surface.nodes.some(seq => {
142
+ const event = session.eventAt(seq);
143
+ return event?.type === 'user/message' && ownMemory(event.data.source);
144
+ });
59
145
  function newMemoryState(session) {
60
146
  const inScope = included(session);
61
- return { reload: true, position: { turn: 1, step: 1 }, retiring: [], inScope, restart: !inScope && belongsToWorld(session, config) };
147
+ return { reload: true, cold: false, position: { turn: 1, step: 1 }, retiring: [], inScope, restart: !inScope && belongsToWorld(session, config) };
62
148
  }
63
149
  /**
64
150
  * Archive failures never stop her talking: they stay in the health list, and what she said meanwhile is replayed
@@ -74,8 +160,8 @@ export function createWorldRuntime(ctx, config, store, world, memoryTurns = () =
74
160
  * the host only inside an open turn and step, which pre-step and attach are not, so `flushRetired` writes it from
75
161
  * the step's request hook, after the step has started and before the request is assembled (#22).
76
162
  */
77
- function retireMemory(session, state) {
78
- const found = session.surface.nodes.filter(seq => isMemoryBlock(session.eventAt(seq)));
163
+ function retireMemory(session, state, all = false) {
164
+ const found = recallNodes(session, all ? source => isRecall(source) : ownMemory);
79
165
  state.retiring = [...new Set([...state.retiring, ...found])];
80
166
  if (found.length)
81
167
  state.restart = true;
@@ -101,15 +187,32 @@ export function createWorldRuntime(ctx, config, store, world, memoryTurns = () =
101
187
  }
102
188
  return found.length ? found.slice(0, 8).join('、') + (found.length > 8 ? `…共 ${found.length} 个` : '') : '无';
103
189
  }
104
- /** Empty system nodes retire only our recalled blocks and derive no model message; original logs stay intact. */
190
+ /** The text of her latest mood snapshot still on the surface, if any. */
191
+ function latestMood(session) {
192
+ const seq = recallNodes(session, source => source?.kind === moodSource && source.worldId === config.worldId).at(-1);
193
+ const event = seq === undefined ? undefined : session.eventAt(seq);
194
+ return event?.type === 'user/message' ? event.data.content.flatMap(block => block.type === 'text' ? [block.text] : []).join('') : undefined;
195
+ }
196
+ /**
197
+ * Her mood rides just before the time block, appended like it: only when it differs from the latest one on the
198
+ * surface, never replacing an old one, so the cached prefix stays whole and compaction clears them all.
199
+ */
200
+ function moodMessage(session) {
201
+ if (!config.moodFile)
202
+ return undefined;
203
+ const mood = readMood(config.moodFile);
204
+ if (mood.kind === 'failed')
205
+ faults.set('mood', `mood.md 读不出来:${mood.message}`);
206
+ else
207
+ faults.clear('mood');
208
+ const latest = latestMood(session);
209
+ const text = moodText(mood) ?? (latest === undefined ? undefined : MOOD_CLEARED);
210
+ return text === undefined || text === latest ? undefined : createUserMessage({ content: [{ type: 'text', text }], source: { kind: moodSource, form: 'snapshot', worldId: config.worldId } });
211
+ }
105
212
  function flushRetired(session, state, position) {
106
213
  const retiring = state.retiring;
107
214
  state.retiring = [];
108
- for (const seq of retiring) {
109
- if (!session.surface.nodes.includes(seq))
110
- continue;
111
- session.append('system/message', { ...position, message: createSystemMessage('') }, { surfaceOp: { op: 'replace', startSeq: seq, endSeq: seq }, sourceEventSeqs: [seq] });
112
- }
215
+ retireRecall(session, retiring, position);
113
216
  }
114
217
  async function attach(agent) {
115
218
  const { session } = agent;
@@ -122,12 +225,30 @@ export function createWorldRuntime(ctx, config, store, world, memoryTurns = () =
122
225
  await archiveNow(session.id);
123
226
  }
124
227
  /** Retire old blocks, then admit fresh memory through the host's normal append path (#21). The caller checks the scope after the wait. */
228
+ /**
229
+ * A cold turn's first step summarizes the old conversation before anything is admitted, so the host's own context
230
+ * admission sees the compacted surface. Only the tool-free compaction can do this inside a turn; without it, or when it
231
+ * fails, the memory block and prompt are still rebuilt and the failure shows in health.
232
+ */
233
+ async function compactCold(agent, step, pending, signal) {
234
+ const state = memory.get(agent.session);
235
+ if (!state?.cold)
236
+ return;
237
+ state.cold = false;
238
+ if (step !== 1 || !pending || signal.aborted || !included(agent.session))
239
+ return;
240
+ const engine = compactionFor(ctx, agent);
241
+ if (!compactsWhole(engine))
242
+ return;
243
+ await faults.track(`cold:${agent.id}`, `会话 ${agent.id} 久未开口后的压缩失败,已改为只重读记忆块和人设`, async () => { await engine.compactWhole(agent, signal); }).catch(() => { });
244
+ }
125
245
  async function freshBlock(session, state) {
126
246
  const turns = await history.loadRecentTurns(memoryTurns(), archivedByScope);
127
247
  const present = new Set(session.deriveMessages().map(message => message.id));
128
248
  const text = renderHistory(excludePresentMessages(turns, present), config.timeZone, names(), config.archiveScope === 'home');
129
- retireMemory(session, state);
130
- return text ? createUserMessage({ content: [{ type: 'text', text }], source: { kind: memorySource, form: 'recall' } }) : undefined;
249
+ // A session entering this workspace can still carry an inherited recall from another world.
250
+ retireMemory(session, state, included(session));
251
+ return text ? createUserMessage({ content: [{ type: 'text', text }], source: { kind: memorySource, form: 'recall', worldId: config.worldId } }) : undefined;
131
252
  }
132
253
  /** Reads what the first catch-up had to leave, once the host can say which sessions belong to her. */
133
254
  async function retryCatchUp() {
@@ -140,6 +261,13 @@ export function createWorldRuntime(ctx, config, store, world, memoryTurns = () =
140
261
  async function start(options = {}) {
141
262
  try {
142
263
  disposers.push(ctx.on('session/event', (session, event) => {
264
+ if (event.type === 'agent-preset/selected') {
265
+ const agent = ctx.agents.get(session.id);
266
+ if (agent) {
267
+ prompts?.add(agent);
268
+ syncTools(agent);
269
+ }
270
+ }
143
271
  const state = memory.get(session);
144
272
  const compacted = event.type === 'compaction/end' && event.data.error === undefined;
145
273
  if (state && event.type === 'user/message' && event.data.id === state.pendingId) {
@@ -151,8 +279,10 @@ export function createWorldRuntime(ctx, config, store, world, memoryTurns = () =
151
279
  }
152
280
  // The host assembles the system prompt after turn/start, so a cold session's first request already has both.
153
281
  const cold = !!state && event.type === 'turn/start' && state.lastRequestAt !== undefined && now() - state.lastRequestAt >= coldHours() * 60 * 60_000;
154
- if (cold)
282
+ if (cold) {
155
283
  state.reload = true;
284
+ state.cold = true;
285
+ }
156
286
  if (compacted || cold)
157
287
  prompts?.refresh(session);
158
288
  if (!isOrdinarySession(session.header))
@@ -175,11 +305,14 @@ export function createWorldRuntime(ctx, config, store, world, memoryTurns = () =
175
305
  }
176
306
  // Admitted ahead of the step's new input; the host's own admission order (contexts, time-context last) is kept.
177
307
  disposers.push(ctx.on('agent/pre-step', async (payload, next) => {
178
- const decision = await next();
308
+ await compactCold(payload.agent, payload.step, payload.messages.length, payload.signal);
309
+ let decision = await next();
179
310
  const { agent, step, signal } = payload;
180
311
  // An empty first step ends the turn; any later step runs anyway, so adding to it is safe.
181
312
  if (decision.kind !== 'enter' || (step === 1 && !decision.messages.length) || signal.aborted || !mayCarryWorld(agent.session))
182
313
  return decision;
314
+ if (prompts?.takeRestart(agent.session))
315
+ decision = { ...decision, startsRequestSeries: true };
183
316
  await attach(agent);
184
317
  const state = memory.get(agent.session);
185
318
  const leave = () => {
@@ -197,6 +330,9 @@ export function createWorldRuntime(ctx, config, store, world, memoryTurns = () =
197
330
  signal.throwIfAborted();
198
331
  if (!included(agent.session))
199
332
  return leave();
333
+ const mood = moodMessage(agent.session);
334
+ if (mood)
335
+ decision = { ...decision, messages: [...decision.messages, mood] };
200
336
  if (!state.reload)
201
337
  return decision;
202
338
  // A block that cannot be built leaves the old one in place; she talks on, the fault shows, and the next step tries again.
@@ -228,7 +364,7 @@ export function createWorldRuntime(ctx, config, store, world, memoryTurns = () =
228
364
  disposers.push(ctx.on('llm/stream', async function* (request, next) {
229
365
  const agent = isAgentLoopRequest(request) && request.sessionId ? ctx.agents.get(request.sessionId) : undefined;
230
366
  const owned = agent && included(agent.session);
231
- const inRequest = agent && !owned ? request.messages.filter(message => message.source?.kind === memorySource).length : 0;
367
+ const inRequest = agent && !owned ? request.messages.filter(message => ownMemory(message.source)).length : 0;
232
368
  const placed = !!agent && !owned && !!prompts?.active(agent.session);
233
369
  if (agent && !owned && (placed || inRequest)) {
234
370
  const state = memory.get(agent.session);
@@ -238,7 +374,7 @@ export function createWorldRuntime(ctx, config, store, world, memoryTurns = () =
238
374
  state.restart = true;
239
375
  }
240
376
  const reasons = [inRequest ? `请求里还带着 ${inRequest} 条世界记忆块` : '', placed ? '世界提示还挂在会话上' : ''].filter(Boolean).join(';');
241
- ctx.logger.warn(`dsh-world: 阻止了会话 ${agent.id}(预设 ${agent.session.header.agentPreset ?? '无'})的一次请求,它不在世界工作区里。原因:${reasons}。${state ? '已尝试退役记忆块' : '这个会话没有记忆状态,没法退役'};退役后会话表面上仍有的记忆节点:${memoryNodesOn(agent.session)}。DSH_WORLD_SCOPE_CHANGED`);
377
+ ctx.logger.warn(`dsh-world: 阻止了会话 ${agent.id}(预设 ${sessionPreset(agent.session) ?? '无'})的一次请求,它不在世界工作区里。原因:${reasons}。${state ? '已尝试退役记忆块' : '这个会话没有记忆状态,没法退役'};退役后会话表面上仍有的记忆节点:${memoryNodesOn(agent.session)}。DSH_WORLD_SCOPE_CHANGED`);
242
378
  yield { type: 'finish', reason: { kind: 'error', failure: { code: 'DSH_WORLD_SCOPE_CHANGED', message: 'dsh-world: 会话已离开世界工作区,已阻止携带世界上下文的请求,请重新发送。' } } };
243
379
  return;
244
380
  }
@@ -254,10 +390,11 @@ export function createWorldRuntime(ctx, config, store, world, memoryTurns = () =
254
390
  await archive.catchUp(options.fresh);
255
391
  if (options.fresh)
256
392
  for (const agent of ctx.agents.list())
257
- if (belongsToWorld(agent.session, config))
393
+ if (included(agent.session))
258
394
  await archive.skip(agent.id);
259
395
  for (const agent of ctx.agents.list()) {
260
396
  prompts?.add(agent);
397
+ syncTools(agent);
261
398
  await attach(agent);
262
399
  }
263
400
  }
@@ -276,5 +413,5 @@ export function createWorldRuntime(ctx, config, store, world, memoryTurns = () =
276
413
  await archive.flush();
277
414
  })();
278
415
  }
279
- return { start, retryCatchUp, refreshPrompt: (session) => { prompts?.refresh(session); }, flush: archive.flush, stop, faults: () => [...faults.list(), ...archive.faults()] };
416
+ return { scopeToken: Symbol(), start, retryCatchUp, refreshPrompt: (session) => { prompts?.refresh(session); }, flush: archive.flush, stop, faults: () => [...faults.list(), ...archive.faults()] };
280
417
  }
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.
@@ -2,11 +2,13 @@ import type { Context } from '@deepseek-ai/cordis';
2
2
  import { type Session } from '@deepseek-ai/dsh-session';
3
3
  import type { ArchiveStore } from './store.ts';
4
4
  import type { WorldConfig } from './types.ts';
5
+ /** The header is creation-time metadata; later selections in the log decide the current preset. */
6
+ export declare function sessionPreset(session: Session): string | undefined;
5
7
  /** Unreadable logs are isolated per source; their archive gaps remain visible until replay succeeds. */
6
8
  export declare function isCorruptSessionLog(error: unknown): boolean;
7
- export declare function belongsToWorld(session: Pick<Session, 'header'>, config: WorldConfig): boolean;
9
+ export declare function belongsToWorld(session: Session, config: WorldConfig): boolean;
8
10
  /** One of her sessions that is also in her room's workspace; without a membership test, any of her sessions. */
9
- export declare function inWorld(session: Pick<Session, 'header' | 'id'>, config: WorldConfig, inWorkspace?: (sessionId: string) => boolean): boolean;
11
+ export declare function inWorld(session: Session, config: WorldConfig, inWorkspace?: (sessionId: string) => boolean): boolean;
10
12
  export declare const isNotFound: (error: unknown) => boolean;
11
13
  /**
12
14
  * Copies her conversations from the host's session logs into the archive. Each session is replayed from where
@@ -1,16 +1,30 @@
1
- import { SessionId } from '@deepseek-ai/dsh-session';
1
+ import { SessionId, SessionLogOffset } from '@deepseek-ai/dsh-session';
2
2
  import { extractConversationRecords, isOrdinarySession } from "./archive.js";
3
3
  import { wechatDeliveryPatch } from "./ecosystem/wechat/archive.js";
4
4
  import { errorText, Faults } from "./faults.js";
5
5
  const pageSize = 128;
6
+ const sessionPresets = new WeakMap();
7
+ /** The header is creation-time metadata; later selections in the log decide the current preset. */
8
+ export function sessionPreset(session) {
9
+ const state = sessionPresets.get(session) ?? { nextSeq: 0, preset: session.header.agentPreset };
10
+ const end = session.seq;
11
+ for (let from = state.nextSeq; from < end; from += pageSize) {
12
+ for (const event of session.snapshotEvents(SessionLogOffset(from), SessionLogOffset(Math.min(from + pageSize, end)))) {
13
+ if (event.type === 'agent-preset/selected')
14
+ state.preset = event.data.agentPreset;
15
+ }
16
+ }
17
+ state.nextSeq = end;
18
+ sessionPresets.set(session, state);
19
+ return state.preset;
20
+ }
6
21
  /** Unreadable logs are isolated per source; their archive gaps remain visible until replay succeeds. */
7
22
  export function isCorruptSessionLog(error) {
8
23
  const text = error instanceof Error ? `${error.name} ${error.message}` : String(error ?? '');
9
24
  return /stored log is corrupt|SessionFormatError|does not match (?:an|the) open turn/i.test(text);
10
25
  }
11
26
  export function belongsToWorld(session, config) {
12
- const header = session.header;
13
- return header.agentPreset === config.agentPreset && isOrdinarySession(header);
27
+ return isOrdinarySession(session.header) && sessionPreset(session) === config.agentPreset;
14
28
  }
15
29
  /** One of her sessions that is also in her room's workspace; without a membership test, any of her sessions. */
16
30
  export function inWorld(session, config, inWorkspace) {
@@ -54,7 +68,7 @@ export function createSourceArchive(ctx, config, store, archived = () => true) {
54
68
  let { nextSeq, turn } = store.progress(id);
55
69
  while (true) {
56
70
  const { events } = await handle.read(nextSeq, pageSize);
57
- if (!events.length)
71
+ if (!events.length || (!skip && !archived(sessionId)))
58
72
  break;
59
73
  const records = events.flatMap(event => {
60
74
  if (event.type === 'turn/start')
package/lib/store.js CHANGED
@@ -3,10 +3,11 @@ import { closeSync, existsSync, fstatSync, fsyncSync, ftruncateSync, mkdirSync,
3
3
  import { join } from 'node:path';
4
4
  import { formatLocalTime } from "./timeContext.js";
5
5
  import { createMemoryStore } from "./memoryStore.js";
6
+ import { validWorldId } from "./worldRoutes.js";
6
7
  const pageSize = 128;
7
8
  export function createArchiveStore(config) {
8
9
  // The world id becomes a directory name.
9
- if (!/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}$/.test(config.worldId))
10
+ if (!validWorldId(config.worldId))
10
11
  throw new TypeError('dsh-world: invalid worldId');
11
12
  const worldRoot = join(config.root, 'worlds', config.worldId);
12
13
  const directory = join(worldRoot, 'conversations');
package/lib/types.d.ts CHANGED
@@ -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. */
@@ -54,7 +56,7 @@ export interface WorldConfig {
54
56
  mutedUntil?: string;
55
57
  /** SnowLuma 装在哪;空着就靠猜(D:\SnowLuma、C:\SnowLuma、~/SnowLuma)。 */
56
58
  snowlumaHome?: string;
57
- /** 看门狗:通道开着时盯住 wsUrl 的端口,不通就按 snowlumaHome 把 SnowLuma 拉起来。默认开。 */
59
+ /** 看门狗:通道开着时盯住 wsUrl 的端口,不通且没有实例时按 snowlumaHome 拉起。默认开。 */
58
60
  supervise?: boolean;
59
61
  /** 阳台:让这台机器上别的程序能跟家里说话(一行一条 JSON 的 WebSocket)。port 为 0 就不开。 */
60
62
  bridge?: {
@@ -43,9 +43,8 @@ export declare function readTemplate(file: string | undefined): TemplateRead;
43
43
  */
44
44
  export declare function renderTemplate(template: string, flags: Record<string, boolean>, values: Record<string, string>): string;
45
45
  /**
46
- * The one world prompt every world session carries in its system prompt. `template` and `self` are read at
47
- * session start, after compaction or on explicit console application, so ordinary saves keep the cached prefix. The world
48
- * line's tools live in the home alone; the template tells other sessions where to find them.
46
+ * The one world prompt every world session carries in its system prompt. The world line's tools live in the home alone;
47
+ * the template tells other sessions where to find them.
49
48
  */
50
49
  export declare function renderWorldPrompt(prompt: WorldPrompt, template: string, self: {
51
50
  file: string;