dsh-world 0.7.3 → 0.7.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/CHANGELOG.md +52 -0
  2. package/NOTES.md +37 -17
  3. package/README.md +14 -7
  4. package/client/index.js +37 -2
  5. package/lib/abortable.d.ts +1 -0
  6. package/lib/abortable.js +17 -0
  7. package/lib/compaction.js +2 -2
  8. package/lib/compactionSwap.d.ts +23 -14
  9. package/lib/compactionSwap.js +90 -36
  10. package/lib/console/homeApply.js +1 -12
  11. package/lib/console/routes.d.ts +1 -0
  12. package/lib/console/routes.js +10 -0
  13. package/lib/console/snapshot.d.ts +4 -0
  14. package/lib/console/snapshot.js +3 -0
  15. package/lib/ecosystem/bridge/bridge.d.ts +2 -2
  16. package/lib/ecosystem/bridge/bridge.js +24 -11
  17. package/lib/ecosystem/qq-native/home.d.ts +2 -1
  18. package/lib/ecosystem/qq-native/home.js +6 -2
  19. package/lib/ecosystem/qq-native/images.d.ts +9 -0
  20. package/lib/ecosystem/qq-native/images.js +69 -0
  21. package/lib/ecosystem/qq-native/index.d.ts +1 -0
  22. package/lib/ecosystem/qq-native/index.js +8 -2
  23. package/lib/ecosystem/qq-native/snowluma.d.ts +1 -0
  24. package/lib/ecosystem/qq-native/snowluma.js +13 -4
  25. package/lib/ecosystem/shared/turn.d.ts +3 -0
  26. package/lib/ecosystem/shared/turn.js +9 -2
  27. package/lib/ecosystem/wechat/home.d.ts +3 -0
  28. package/lib/ecosystem/wechat/home.js +12 -4
  29. package/lib/ecosystem/wechat/index.js +3 -1
  30. package/lib/ecosystem/wechat/supervisor.d.ts +1 -1
  31. package/lib/ecosystem/wechat/supervisor.js +5 -1
  32. package/lib/hostContract.d.ts +6 -0
  33. package/lib/index.d.ts +1 -1
  34. package/lib/index.js +85 -47
  35. package/lib/life/home.js +8 -2
  36. package/lib/life/photoTools.js +60 -26
  37. package/lib/life/runtime.js +2 -0
  38. package/lib/memoryTools.d.ts +1 -1
  39. package/lib/memoryTools.js +1 -1
  40. package/lib/mood.d.ts +57 -0
  41. package/lib/mood.js +95 -0
  42. package/lib/moodTools.d.ts +6 -0
  43. package/lib/moodTools.js +30 -0
  44. package/lib/persona.js +7 -0
  45. package/lib/promptSection.d.ts +9 -13
  46. package/lib/promptSection.js +63 -80
  47. package/lib/runtime.d.ts +21 -2
  48. package/lib/runtime.js +148 -39
  49. package/lib/self.d.ts +1 -1
  50. package/lib/self.js +1 -1
  51. package/lib/sourceArchive.d.ts +1 -5
  52. package/lib/sourceArchive.js +31 -14
  53. package/lib/types.d.ts +2 -0
  54. package/lib/worldScope.d.ts +2 -4
  55. package/lib/worldScope.js +6 -6
  56. package/package.json +1 -1
  57. package/src/ecosystem/wechat/windows/README.md +5 -3
  58. package/src/ecosystem/wechat/windows/adapter.py +23 -2
  59. package/src/ecosystem/wechat/windows/engine/NOTICE.md +6 -0
  60. package/src/ecosystem/wechat/windows/engine/profiles.json +28 -0
  61. package/src/ecosystem/wechat/windows/sender.py +6 -2
  62. package/templates/world-prompt.md +6 -3
package/lib/mood.d.ts ADDED
@@ -0,0 +1,57 @@
1
+ /** Her mood, kept in her room. The plugin never writes it: it only reads it back to her. */
2
+ export declare const MOOD_FILE = "mood.md";
3
+ /**
4
+ * The fixed set, always shown in this order and at 0 when unset, so one snapshot compares with the next. Free words
5
+ * would pile up as near-synonyms (高兴 beside 开心) with no end; what the set cannot say goes into the small things.
6
+ */
7
+ export declare const MOODS: readonly ["开心", "兴奋", "平静", "安心", "烦", "生气", "紧张", "难过", "累", "孤单", "想念"];
8
+ export type Mood = {
9
+ kind: 'none';
10
+ } | {
11
+ kind: 'failed';
12
+ message: string;
13
+ } | {
14
+ kind: 'mood';
15
+ values: Map<string, number>;
16
+ trivia: string[];
17
+ cut: boolean;
18
+ unread: number;
19
+ outside: string[];
20
+ };
21
+ /**
22
+ * One thing per line. A line ending in a number after a space, a full-width space or a colon is a mood `名字 数值`,
23
+ * its value a whole number from 0 to 10; a line ending in anything else is a small thing beside her mood. A later line
24
+ * for the same mood wins. A mood line she got wrong is counted, and a name outside the set is named back to her;
25
+ * neither is ever taken as a small thing.
26
+ */
27
+ export declare function parseMood(text: string): Mood;
28
+ /** A missing or blank file is `none`, not every mood at 0; a file that cannot be read is `failed`. */
29
+ export declare function readMood(path: string): Mood;
30
+ /** Shown once after an earlier snapshot when she has emptied or removed the file, so the old values stop counting. */
31
+ export declare const MOOD_CLEARED = "\u3010\u6211\u7684\u5FC3\u60C5\u503C\u3011\u73B0\u5728\u6CA1\u6709\u5FC3\u60C5\u503C\uFF08mood.md \u4E0D\u5728\u6216\u662F\u7A7A\u7684\uFF09\uFF0C\u4E4B\u524D\u90A3\u6761\u4E0D\u518D\u7B97\u6570\uFF1B\u60F3\u8BB0\u7684\u65F6\u5019\u7528 set_mood\u3002";
32
+ export interface MoodValue {
33
+ name: string;
34
+ value: number;
35
+ }
36
+ /** Every mood of the set in its order, at 0 when she has not set it. */
37
+ export declare function moodValues(mood: Extract<Mood, {
38
+ kind: 'mood';
39
+ }>): MoodValue[];
40
+ /** What she reads just before the time block, in her own voice; undefined when there is nothing to show. */
41
+ export declare function moodText(mood: Mood): string | undefined;
42
+ export type MoodView = {
43
+ kind: 'none';
44
+ } | {
45
+ kind: 'failed';
46
+ message: string;
47
+ } | {
48
+ kind: 'mood';
49
+ values: MoodValue[];
50
+ trivia: string[];
51
+ cut: boolean;
52
+ unread: number;
53
+ outside: string[];
54
+ updatedAt: string | null;
55
+ };
56
+ /** The world console's read-only view: what she reads, plus when she last changed the file. */
57
+ export declare function moodView(path: string): MoodView;
package/lib/mood.js ADDED
@@ -0,0 +1,95 @@
1
+ import { readFileSync, statSync } from 'node:fs';
2
+ import { errorText } from "./faults.js";
3
+ /** Her mood, kept in her room. The plugin never writes it: it only reads it back to her. */
4
+ export const MOOD_FILE = 'mood.md';
5
+ /**
6
+ * The fixed set, always shown in this order and at 0 when unset, so one snapshot compares with the next. Free words
7
+ * would pile up as near-synonyms (高兴 beside 开心) with no end; what the set cannot say goes into the small things.
8
+ */
9
+ export const MOODS = ['开心', '兴奋', '平静', '安心', '烦', '生气', '紧张', '难过', '累', '孤单', '想念'];
10
+ const known = (name) => MOODS.includes(name);
11
+ const MAX_TRIVIA_LINES = 3, MAX_TRIVIA_CHARS = 12;
12
+ /**
13
+ * One thing per line. A line ending in a number after a space, a full-width space or a colon is a mood `名字 数值`,
14
+ * its value a whole number from 0 to 10; a line ending in anything else is a small thing beside her mood. A later line
15
+ * for the same mood wins. A mood line she got wrong is counted, and a name outside the set is named back to her;
16
+ * neither is ever taken as a small thing.
17
+ */
18
+ export function parseMood(text) {
19
+ const values = new Map(), trivia = [], outside = [];
20
+ let cut = false, unread = 0;
21
+ for (const raw of text.replace(/^/, '').split(/\r?\n/)) {
22
+ const line = raw.trim();
23
+ if (!line)
24
+ continue;
25
+ const pair = /^(.*?)[\s ::]+([+-]?\d+(?:\.\d+)?)$/u.exec(line);
26
+ if (pair) {
27
+ const name = pair[1].trim(), value = Number(pair[2]);
28
+ if (!name || !Number.isInteger(value) || value < 0 || value > 10)
29
+ unread++;
30
+ else if (!known(name)) {
31
+ if (!outside.includes(name))
32
+ outside.push(name);
33
+ }
34
+ else
35
+ values.set(name, value);
36
+ continue;
37
+ }
38
+ if (trivia.length === MAX_TRIVIA_LINES) {
39
+ cut = true;
40
+ continue;
41
+ }
42
+ const chars = Array.from(line);
43
+ if (chars.length > MAX_TRIVIA_CHARS)
44
+ cut = true;
45
+ trivia.push(chars.slice(0, MAX_TRIVIA_CHARS).join(''));
46
+ }
47
+ return values.size || trivia.length || unread || outside.length ? { kind: 'mood', values, trivia, cut, unread, outside } : { kind: 'none' };
48
+ }
49
+ /** A missing or blank file is `none`, not every mood at 0; a file that cannot be read is `failed`. */
50
+ export function readMood(path) {
51
+ try {
52
+ if (!statSync(path).isFile())
53
+ return { kind: 'failed', message: '不是普通文件' };
54
+ return parseMood(readFileSync(path, 'utf8'));
55
+ }
56
+ catch (error) {
57
+ if (error.code === 'ENOENT')
58
+ return { kind: 'none' };
59
+ return { kind: 'failed', message: errorText(error) };
60
+ }
61
+ }
62
+ /** Shown once after an earlier snapshot when she has emptied or removed the file, so the old values stop counting. */
63
+ export const MOOD_CLEARED = '【我的心情值】现在没有心情值(mood.md 不在或是空的),之前那条不再算数;想记的时候用 set_mood。';
64
+ /** Every mood of the set in its order, at 0 when she has not set it. */
65
+ export function moodValues(mood) {
66
+ return MOODS.map(name => ({ name, value: mood.values.get(name) ?? 0 }));
67
+ }
68
+ const outsideNote = (names) => `(${names.join('、')} 不在固定的心情里,没有算进去;换成最接近的那个,细的写进小事)`;
69
+ /** What she reads just before the time block, in her own voice; undefined when there is nothing to show. */
70
+ export function moodText(mood) {
71
+ if (mood.kind === 'none')
72
+ return undefined;
73
+ if (mood.kind === 'failed')
74
+ return '【我的心情值】mood.md 读不出来,之前那条不再算数;可以用 set_mood 重新记。';
75
+ const lines = [`【我的心情值】${moodValues(mood).map(value => `${value.name} ${value.value}`).join(' · ')}(以最新一条为准,用 set_mood 改)`];
76
+ if (mood.trivia.length)
77
+ lines.push(`旁边:${mood.trivia.join(';')}${mood.cut ? '……后面还有' : ''}`);
78
+ if (mood.outside.length)
79
+ lines.push(outsideNote(mood.outside));
80
+ if (mood.unread)
81
+ lines.push(`(mood.md 里有 ${mood.unread} 行没读懂)`);
82
+ return lines.join('\n');
83
+ }
84
+ /** The world console's read-only view: what she reads, plus when she last changed the file. */
85
+ export function moodView(path) {
86
+ const mood = readMood(path);
87
+ if (mood.kind !== 'mood')
88
+ return mood;
89
+ let updatedAt = null;
90
+ try {
91
+ updatedAt = statSync(path).mtime.toISOString();
92
+ }
93
+ catch { /* removed since it was read; the values still stand */ }
94
+ return { kind: 'mood', values: moodValues(mood), trivia: mood.trivia, cut: mood.cut, unread: mood.unread, outside: mood.outside, updatedAt };
95
+ }
@@ -0,0 +1,6 @@
1
+ import { type ToolDefinition } from '@deepseek-ai/dsh-tools';
2
+ /**
3
+ * One call to write her mood, so it is no harder to change than to feel: the whole of mood.md is replaced with what she
4
+ * passes. A line she got wrong refuses the write and says why, instead of leaving her a file the snapshot cannot read.
5
+ */
6
+ export declare function moodTools(file: string, inside: () => boolean): ToolDefinition[];
@@ -0,0 +1,30 @@
1
+ import { defineTool } from '@deepseek-ai/dsh-tools';
2
+ import { durableWrite } from "./life/lifeStore.js";
3
+ import { MOODS, parseMood } from "./mood.js";
4
+ import { OutsideWorldError } from "./worldScope.js";
5
+ const output = { schema: { type: 'string' }, render: (_args, value) => [{ type: 'text', text: value }] };
6
+ /**
7
+ * One call to write her mood, so it is no harder to change than to feel: the whole of mood.md is replaced with what she
8
+ * passes. A line she got wrong refuses the write and says why, instead of leaving her a file the snapshot cannot read.
9
+ */
10
+ export function moodTools(file, inside) {
11
+ return [defineTool({
12
+ name: 'set_mood',
13
+ description: `记下我此刻的心情,由我自己决定什么时候记、记什么。mood 整份替换 room/mood.md,一行一件:「名字 数值」是一种心情,数值是 0 到 10 的整数,比如「开心 6」;名字只能是固定的这几个:${MOODS.join('、')},没写的算 0。想说得更细,写进不以数字结尾的行,那是心情旁边的小事,最多三行。记下后,下一步就在时间前面看到。`,
14
+ parameters: { mood: { type: 'string', required: true } },
15
+ output,
16
+ execute: async ({ mood }) => {
17
+ if (!inside())
18
+ throw new OutsideWorldError();
19
+ const parsed = parseMood(typeof mood === 'string' ? mood : '');
20
+ if (parsed.kind === 'none')
21
+ throw new Error('没有写任何心情,这次没有改动');
22
+ if (parsed.kind === 'mood' && parsed.outside.length)
23
+ throw new Error(`${parsed.outside.join('、')} 不在固定的心情里,这次没有改动:只能用 ${MOODS.join('、')};更细的感受写进小事那几行`);
24
+ if (parsed.kind === 'mood' && parsed.unread)
25
+ throw new Error(`有 ${parsed.unread} 行没读懂,这次没有改动:心情要写成「名字 数值」,数值是 0 到 10 的整数`);
26
+ durableWrite(file, `${mood.trim()}\n`);
27
+ return '已记下。';
28
+ },
29
+ })];
30
+ }
package/lib/persona.js CHANGED
@@ -11,6 +11,13 @@ export function readPersona(file) {
11
11
  sections = parseSections(readFileSync(file, 'utf8'), PERSONA_LAYERS);
12
12
  }
13
13
  catch { /* treated as not written */ }
14
+ // The name also goes into channel metadata, so a custom heading cannot be part of it.
15
+ const name = sections.get('名字') ?? '';
16
+ const customHeading = name.search(/^## .+/m);
17
+ if (customHeading >= 0) {
18
+ sections.set('名字', name.slice(0, customHeading).trimEnd());
19
+ sections.set('补充', [name.slice(customHeading), sections.get('补充')].filter(Boolean).join('\n\n'));
20
+ }
14
21
  return Object.fromEntries(PERSONA_LAYERS.map(layer => [layer, sections.get(layer) ?? '']));
15
22
  }
16
23
  /** Only layers with text are kept; a persona with none removes the file. */
@@ -1,8 +1,13 @@
1
1
  import type { Agent } from '@deepseek-ai/dsh-agent';
2
2
  import type { Session } from '@deepseek-ai/dsh-session';
3
+ import type { AssembleContext } from '@deepseek-ai/dsh-system-prompt';
3
4
  import type { WorldConfig } from './types.ts';
4
5
  import { type WorldNames, type WorldPrompt } from './worldPrompt.ts';
5
- export declare const WORLD_PROMPT_PREFIX = "dsh-world:";
6
+ export declare const assembledWorlds: WeakMap<AssembleContext, {
7
+ worldId: string;
8
+ token: symbol;
9
+ text: string;
10
+ }>;
6
11
  export interface WorldPromptSource {
7
12
  prompt: WorldPrompt;
8
13
  isHome(sessionId: string): boolean;
@@ -14,18 +19,8 @@ export interface WorldPromptSource {
14
19
  /** Long-term memory; its two tools are registered on world sessions. */
15
20
  memory?: import('./memory.ts').MemoryService;
16
21
  }
17
- /**
18
- * Her persona and the world prompt both reach only sessions of her preset inside the world's workspace, and come and
19
- * go together as a session enters or leaves it: the preset alone is DSH's default `standard` for most setups, so it
20
- * would turn every unrelated session into her (#37). Both are sections of the session's system prompt so she sees them on every
21
- * request. Checking the files during assembly also covers compression outside DSH (#42). The prompt stays in the
22
- * provider-cached prefix while its content is the same. Whether the session is her home is asked per request.
23
- *
24
- * Her persona takes the place of DeepSeek Harness's stock identity line, but never of a persona someone has set: it is its own
25
- * section placed right after the host's persona slot, so a system persona the deployment or her preset already has stays
26
- * where it is and hers follows it.
27
- */
28
- export declare function createPromptSections(config: WorldConfig, world: WorldPromptSource, deps: {
22
+ /** Replace the system prompt only for this world's preset and workspace. */
23
+ export declare function createPromptSections(config: WorldConfig, world: WorldPromptSource, token: symbol, deps: {
29
24
  logger: {
30
25
  warn(...args: unknown[]): void;
31
26
  };
@@ -35,5 +30,6 @@ export declare function createPromptSections(config: WorldConfig, world: WorldPr
35
30
  /** On in-history routes, start a new series to replace the old prompt instead of appending to it. */
36
31
  takeRestart(session: Session): boolean;
37
32
  refresh(session: Session): void;
33
+ forget: (agent: Agent) => void;
38
34
  clear(): void;
39
35
  };
@@ -1,13 +1,12 @@
1
1
  import { statSync } from 'node:fs';
2
- import { isDeepStrictEqual } from 'node:util';
3
2
  import { readPersona, renderPersona } from "./persona.js";
4
3
  import { renderSelf } from "./self.js";
5
4
  import { belongsToWorld, inWorld } from "./sourceArchive.js";
6
5
  import { DEFAULT_TEMPLATE_FILE, readTemplate, renderWorldPrompt } from "./worldPrompt.js";
7
- import { reassembleOnChange } from "./worldScope.js";
8
- export const WORLD_PROMPT_PREFIX = 'dsh-world:';
9
- /** The stock "You are an AI agent powered by DeepSeek Harness." line; a section of the same name on her agent shadows it. */
10
- const HARNESS_IDENTITY = 'harness:identity';
6
+ import { syncBetweenSteps } from "./worldScope.js";
7
+ // The complete prompt uses DSH's section name, so the request guard reads ownership from the assembly context.
8
+ export const assembledWorlds = new WeakMap();
9
+ const promptSlots = new WeakMap();
11
10
  function cachePromptFile(file, read) {
12
11
  let cached;
13
12
  return force => {
@@ -28,19 +27,8 @@ function cachePromptFile(file, read) {
28
27
  return value;
29
28
  };
30
29
  }
31
- /**
32
- * Her persona and the world prompt both reach only sessions of her preset inside the world's workspace, and come and
33
- * go together as a session enters or leaves it: the preset alone is DSH's default `standard` for most setups, so it
34
- * would turn every unrelated session into her (#37). Both are sections of the session's system prompt so she sees them on every
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.
37
- *
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
39
- * section placed right after the host's persona slot, so a system persona the deployment or her preset already has stays
40
- * where it is and hers follows it.
41
- */
42
- export function createPromptSections(config, world, deps) {
43
- const sectionName = WORLD_PROMPT_PREFIX + config.worldId;
30
+ /** Replace the system prompt only for this world's preset and workspace. */
31
+ export function createPromptSections(config, world, token, deps) {
44
32
  const entries = new Map();
45
33
  const agents = new WeakMap();
46
34
  const persona = cachePromptFile(world.prompt.persona, () => ({
@@ -55,76 +43,76 @@ export function createPromptSections(config, world, deps) {
55
43
  });
56
44
  const self = cachePromptFile(config.selfFile, () => config.selfFile ? { file: config.selfFile, text: renderSelf(config.selfFile) } : undefined);
57
45
  let forceRead = false;
58
- function read() {
46
+ function render(agent) {
59
47
  const force = forceRead;
60
48
  forceRead = false;
61
- return { template: template(force), self: self(force), ...persona(force) };
49
+ const card = persona(force);
50
+ const body = renderWorldPrompt({ ...world.prompt, names: card.names }, template(force), self(force), world.isHome(agent.id));
51
+ return [card.persona, body].filter(Boolean).join('\n\n');
62
52
  }
63
- /** Registers her persona while the session is in her workspace and she has one; drops it otherwise. */
64
- function placePersona(agent, entry) {
65
- if (!entry.active || !entry.text.persona) {
66
- entry.persona?.();
67
- delete entry.persona;
53
+ function sync(agent, entry) {
54
+ const active = inWorld(agent.session, config, world.inWorkspace);
55
+ if (active === Boolean(entry.disposePrompt))
68
56
  return;
69
- }
70
- if (entry.persona)
57
+ if (!active) {
58
+ entry.disposePrompt?.();
71
59
  return;
72
- const prompt = agent.ctx.systemPrompt;
73
- const order = prompt.getSectionOrder('DEPLOYMENT_PERSONA_PREFIX') ?? 0;
74
- const text = () => entry.text.persona;
75
- const persona = prompt.section({ name: sectionName + ':persona', order: order + 1, interpolate: false, text });
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.
77
- // If a preset already put its own words on that identity slot for this agent, they stay exactly as written.
78
- let identity;
79
- try {
80
- identity = prompt.section({ name: HARNESS_IDENTITY, order: prompt.getSectionOrder('HARNESS_IDENTITY'), interpolate: false, text: () => '' });
81
60
  }
82
- catch { /* the slot is already taken for this agent */ }
83
- entry.persona = () => { persona(); identity?.(); };
84
- }
85
- function refresh(agent, entry) {
86
- const text = read();
87
- if (isDeepStrictEqual(text, entry.text))
88
- return false;
89
- entry.text = text;
61
+ // A session moving between worlds can reach the new world's listener before the old one.
62
+ promptSlots.get(agent)?.();
63
+ const prompt = agent.ctx.systemPrompt;
64
+ const dispose = prompt.section({
65
+ // Shadow the preset's own persona slot. Minimal already marks that slot as complete.
66
+ name: 'deployment:persona-prefix',
67
+ order: prompt.getSectionOrder('DEPLOYMENT_PERSONA_PREFIX'),
68
+ complete: true,
69
+ interpolate: false,
70
+ text: context => {
71
+ const text = render(agent);
72
+ assembledWorlds.set(context, { worldId: config.worldId, token, text });
73
+ if (text !== entry.text) {
74
+ entry.text = text;
75
+ entry.restart = true;
76
+ }
77
+ return text;
78
+ },
79
+ });
90
80
  entry.restart = true;
91
- placePersona(agent, entry);
92
- return true;
81
+ const release = () => {
82
+ dispose();
83
+ entry.restart = true;
84
+ promptSlots.delete(agent);
85
+ delete entry.disposePrompt;
86
+ };
87
+ entry.disposePrompt = release;
88
+ promptSlots.set(agent, release);
89
+ }
90
+ function forget(agent) {
91
+ const entry = entries.get(agent);
92
+ if (!entry)
93
+ return;
94
+ entry.disposeSync();
95
+ entry.disposePrompt?.();
96
+ entries.delete(agent);
97
+ if (agents.get(agent.session) === agent)
98
+ agents.delete(agent.session);
93
99
  }
94
100
  return {
95
101
  add(agent) {
96
102
  if (entries.has(agent) || !belongsToWorld(agent.session, config))
97
103
  return;
98
- let disposeWorld;
99
- /** Reassemble if the placement or the content changed since the host collected the sections. */
100
- const sync = (current) => {
101
- if (current !== agent)
102
- return false;
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;
108
- if (!entry.active) {
109
- disposeWorld?.();
110
- disposeWorld = undefined;
111
- placePersona(agent, entry);
112
- return true;
113
- }
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)) });
116
- placePersona(agent, entry);
117
- return true;
118
- };
119
- const disposeSync = reassembleOnChange(agent.ctx, sync);
120
- const entry = { text: { template: '', persona: '', names: world.prompt.names }, active: false, restart: false, dispose: () => { disposeSync(); disposeWorld?.(); } };
104
+ // The host captures complete sections before assembly listeners and restores them afterwards.
105
+ const entry = { restart: false, disposeSync: syncBetweenSteps(agent.ctx, current => {
106
+ if (current === agent)
107
+ sync(agent, entry);
108
+ }) };
121
109
  entries.set(agent, entry);
122
110
  agents.set(agent.session, agent);
123
- sync(agent);
111
+ sync(agent, entry);
124
112
  },
125
113
  active(session) {
126
114
  const agent = agents.get(session);
127
- return !!(agent && entries.get(agent)?.active);
115
+ return !!(agent && entries.get(agent)?.disposePrompt);
128
116
  },
129
117
  /** On in-history routes, start a new series to replace the old prompt instead of appending to it. */
130
118
  takeRestart(session) {
@@ -138,18 +126,13 @@ export function createPromptSections(config, world, deps) {
138
126
  refresh(session) {
139
127
  const agent = agents.get(session);
140
128
  // A compaction can finish after the current step assembled its prompt.
141
- if (agent && entries.get(agent)?.active)
129
+ if (agent && entries.get(agent)?.disposePrompt)
142
130
  forceRead = true;
143
131
  },
132
+ forget,
144
133
  clear() {
145
- for (const entry of entries.values())
146
- for (const dispose of [entry.dispose, entry.persona]) {
147
- try {
148
- dispose?.();
149
- }
150
- catch { /* agent scope already gone */ }
151
- }
152
- entries.clear();
134
+ for (const agent of entries.keys())
135
+ forget(agent);
153
136
  },
154
137
  };
155
138
  }
package/lib/runtime.d.ts CHANGED
@@ -1,12 +1,30 @@
1
1
  import type { Context } from '@deepseek-ai/cordis';
2
- import type { Session } from '@deepseek-ai/dsh-session';
2
+ import { type Session } from '@deepseek-ai/dsh-session';
3
3
  import './hostContract.ts';
4
4
  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
+ type RequestPosition = {
9
+ turn: number;
10
+ step: number;
11
+ };
12
+ declare const promptRecord = "plugin:dsh-world/system-prompt";
13
+ declare const legacyPromptReset = "plugin:dsh-world/legacy-prompt-reset";
14
+ interface WorldPromptIdentity {
15
+ worldId: string;
16
+ digest: string;
17
+ }
18
+ interface PromptRecord extends WorldPromptIdentity, RequestPosition {
19
+ }
20
+ declare module '@deepseek-ai/dsh-session' {
21
+ interface PluginRecordMap {
22
+ [promptRecord]: PromptRecord;
23
+ [legacyPromptReset]: Record<string, never>;
24
+ }
25
+ }
8
26
  /** 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;
27
+ export declare function guardWorldContext(ctx: Context, authorize: (session: Session, worldId?: string) => symbol | false | undefined, hasWorldRoom: (session: Session) => boolean): void;
10
28
  /**
11
29
  * The memory line: her conversations are archived as they happen, and every world session gets a memory
12
30
  * block of the newest turns at its start, after each successful compaction and when it speaks again after being cold,
@@ -26,6 +44,7 @@ export declare function createWorldRuntime(ctx: Context, config: WorldConfig, st
26
44
  fresh?: boolean;
27
45
  }) => Promise<void>;
28
46
  retryCatchUp: () => Promise<void>;
47
+ cancelCatchUp: () => void;
29
48
  refreshPrompt: (session: Session) => void;
30
49
  flush: () => Promise<void>;
31
50
  stop: () => Promise<void>;