dsh-world 0.6.5 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/CHANGELOG.md +34 -0
  2. package/CONTRIBUTING.md +163 -161
  3. package/INSTALL.md +314 -314
  4. package/LICENSE +21 -21
  5. package/NOTES.md +173 -0
  6. package/README.md +236 -235
  7. package/client/index.js +849 -738
  8. package/cordis.patch.yml +6 -6
  9. package/lib/compaction.d.ts +19 -0
  10. package/lib/compaction.js +34 -10
  11. package/lib/compactionSwap.d.ts +29 -2
  12. package/lib/compactionSwap.js +62 -7
  13. package/lib/console/homeApply.d.ts +11 -2
  14. package/lib/console/homeApply.js +36 -7
  15. package/lib/console/routes.d.ts +8 -0
  16. package/lib/console/routes.js +32 -0
  17. package/lib/console/snapshot.d.ts +3 -0
  18. package/lib/console/snapshot.js +2 -1
  19. package/lib/ecosystem/bridge/route.d.ts +7 -0
  20. package/lib/ecosystem/bridge/route.js +30 -0
  21. package/lib/hostContract.d.ts +1 -0
  22. package/lib/index.js +37 -12
  23. package/lib/memory.d.ts +57 -0
  24. package/lib/memory.js +210 -0
  25. package/lib/memoryFiles.d.ts +53 -0
  26. package/lib/memoryFiles.js +193 -0
  27. package/lib/memoryStore.d.ts +114 -0
  28. package/lib/memoryStore.js +159 -0
  29. package/lib/memoryTools.d.ts +31 -0
  30. package/lib/memoryTools.js +106 -0
  31. package/lib/promptSection.d.ts +5 -5
  32. package/lib/promptSection.js +12 -12
  33. package/lib/runtime.d.ts +1 -1
  34. package/lib/runtime.js +84 -29
  35. package/lib/sourceArchive.d.ts +1 -0
  36. package/lib/sourceArchive.js +1 -1
  37. package/lib/store.d.ts +14 -0
  38. package/lib/store.js +11 -1
  39. package/lib/worldPrompt.d.ts +6 -0
  40. package/lib/worldPrompt.js +7 -1
  41. package/lib/worldSwitch.d.ts +3 -2
  42. package/lib/worldSwitch.js +7 -6
  43. package/package.json +128 -115
  44. package/scripts/compact-home.mjs +29 -0
  45. package/scripts/enable-tool-free-compaction.ps1 +33 -33
  46. package/scripts/import-stickers.mjs +17 -17
  47. package/scripts/update-world.mjs +5 -3
  48. package/src/ecosystem/wechat/windows/README.md +6 -4
  49. package/src/ecosystem/wechat/windows/adapter.py +80 -31
  50. package/src/ecosystem/wechat/windows/engine/NOTICE.md +1 -1
  51. package/src/ecosystem/wechat/windows/engine/bridge.cpp +9 -1
  52. package/src/ecosystem/wechat/windows/engine/profiles.json +114 -58
  53. package/src/ecosystem/wechat/windows/native.py +4 -1
  54. package/src/ecosystem/wechat/windows/outgoing.py +21 -0
  55. package/src/ecosystem/wechat/windows/presence.py +109 -109
  56. package/src/ecosystem/wechat/windows/sender.py +9 -1
  57. package/templates/alarm.md +3 -4
  58. package/templates/world-prompt-memory.md +10 -0
  59. package/templates/world-prompt.md +7 -2
package/cordis.patch.yml CHANGED
@@ -1,6 +1,6 @@
1
- # Inserts the dsh-world row enabled: with no config it serves the standard preset as a world named
2
- # "default" in the system time zone. Override the row by id in a profile to name the companion, pick
3
- # another preset or turn on the life line (see README).
4
- - insert:
5
- - id: dsh-world
6
- name: dsh-world
1
+ # Inserts the dsh-world row enabled: with no config it serves the standard preset as a world named
2
+ # "default" in the system time zone. Override the row by id in a profile to name the companion, pick
3
+ # another preset or turn on the life line (see README).
4
+ - insert:
5
+ - id: dsh-world
6
+ name: dsh-world
@@ -20,8 +20,14 @@ declare module '@deepseek-ai/dsh-session/types' {
20
20
  'plugin:dsh-world/compaction-request': SummaryAudit;
21
21
  }
22
22
  }
23
+ /**
24
+ * `thresholdRatio`: compaction starts at this share of the context window. `defaultContextWindow`: the window assumed for a model
25
+ * whose adapter declares none. `headroomTokens` no longer takes anything off the trigger; it only sizes the summary reply when
26
+ * `maxTokens` is unset.
27
+ */
23
28
  interface Policy {
24
29
  thresholdRatio: number;
30
+ defaultContextWindow: number;
25
31
  headroomTokens: number;
26
32
  summarizationProvider: string;
27
33
  summarizationModel: string;
@@ -42,6 +48,12 @@ export interface ToolFreeCompactionConfig extends Partial<Policy> {
42
48
  * provider-cached prefix. Assistant text split around a removed call is rejoined.
43
49
  */
44
50
  export declare function toolFreeMessages(messages: readonly Message[]): Message[];
51
+ /** Compaction starts at `ratio` of the window, or earlier when a reply of `reserved` tokens would then no longer fit after the prompt. */
52
+ export declare function compactionThreshold(input: {
53
+ contextWindow: number;
54
+ ratio: number;
55
+ reserved: number;
56
+ }): number;
45
57
  /**
46
58
  * Replacement for `@deepseek-ai/dsh-compaction-basic`: drops every tool call,
47
59
  * tool result, tool schema and reasoning block from the compacted span, then
@@ -53,6 +65,7 @@ export default class ToolFreeCompaction extends CompactionEngine {
53
65
  timeZone: z<string, string, "plain">;
54
66
  auto: z<boolean, boolean, "plain">;
55
67
  thresholdRatio: z<number, number, "plain">;
68
+ defaultContextWindow: z<number, number, "plain">;
56
69
  headroomTokens: z<number, number, "plain">;
57
70
  summarizationProvider: z<string, string, "plain">;
58
71
  summarizationModel: z<string, string, "plain">;
@@ -62,6 +75,7 @@ export default class ToolFreeCompaction extends CompactionEngine {
62
75
  provider?: string | null | undefined;
63
76
  model?: string | null | undefined;
64
77
  thresholdRatio?: number | null | undefined;
78
+ defaultContextWindow?: number | null | undefined;
65
79
  headroomTokens?: number | null | undefined;
66
80
  summarizationProvider?: string | null | undefined;
67
81
  summarizationModel?: string | null | undefined;
@@ -71,6 +85,7 @@ export default class ToolFreeCompaction extends CompactionEngine {
71
85
  provider: z<string, string, "defined">;
72
86
  model: z<string, string, "defined">;
73
87
  thresholdRatio: z<number, number, "plain">;
88
+ defaultContextWindow: z<number, number, "plain">;
74
89
  headroomTokens: z<number, number, "plain">;
75
90
  summarizationProvider: z<string, string, "plain">;
76
91
  summarizationModel: z<string, string, "plain">;
@@ -81,6 +96,7 @@ export default class ToolFreeCompaction extends CompactionEngine {
81
96
  timeZone: z<string, string, "plain">;
82
97
  auto: z<boolean, boolean, "plain">;
83
98
  thresholdRatio: z<number, number, "plain">;
99
+ defaultContextWindow: z<number, number, "plain">;
84
100
  headroomTokens: z<number, number, "plain">;
85
101
  summarizationProvider: z<string, string, "plain">;
86
102
  summarizationModel: z<string, string, "plain">;
@@ -90,6 +106,7 @@ export default class ToolFreeCompaction extends CompactionEngine {
90
106
  provider?: string | null | undefined;
91
107
  model?: string | null | undefined;
92
108
  thresholdRatio?: number | null | undefined;
109
+ defaultContextWindow?: number | null | undefined;
93
110
  headroomTokens?: number | null | undefined;
94
111
  summarizationProvider?: string | null | undefined;
95
112
  summarizationModel?: string | null | undefined;
@@ -99,6 +116,7 @@ export default class ToolFreeCompaction extends CompactionEngine {
99
116
  provider: z<string, string, "defined">;
100
117
  model: z<string, string, "defined">;
101
118
  thresholdRatio: z<number, number, "plain">;
119
+ defaultContextWindow: z<number, number, "plain">;
102
120
  headroomTokens: z<number, number, "plain">;
103
121
  summarizationProvider: z<string, string, "plain">;
104
122
  summarizationModel: z<string, string, "plain">;
@@ -110,6 +128,7 @@ export default class ToolFreeCompaction extends CompactionEngine {
110
128
  private readonly overrides;
111
129
  private readonly timeZone;
112
130
  private readonly warnedTargets;
131
+ private readonly assumedWindows;
113
132
  private readonly overflowRetries;
114
133
  private readonly overflowAgents;
115
134
  constructor(ctx: Context, config?: ToolFreeCompactionConfig);
package/lib/compaction.js CHANGED
@@ -28,6 +28,14 @@ export function toolFreeMessages(messages) {
28
28
  for (const message of messages) {
29
29
  if (message.role === 'tool')
30
30
  continue;
31
+ // A mid-history update (memory block, tool change) may only follow a user turn on DeepSeek Messages. A tool result was
32
+ // that turn after a tool call; with it removed, such an update would sit between two replies and the request is refused.
33
+ // What these updates carry is provided again after compaction, so the summary loses nothing.
34
+ if (message.role === 'system' || message.role === 'developer') {
35
+ if (kept.findLast(previous => previous.role === 'user' || previous.role === 'assistant')?.role === 'user')
36
+ kept.push(message);
37
+ continue;
38
+ }
31
39
  if (message.role !== 'assistant') {
32
40
  kept.push(message);
33
41
  continue;
@@ -53,11 +61,18 @@ function routedTarget(session) {
53
61
  }
54
62
  function resolvePolicy(config) {
55
63
  return {
56
- thresholdRatio: config.thresholdRatio ?? 0.9, headroomTokens: config.headroomTokens ?? 65536,
64
+ thresholdRatio: config.thresholdRatio ?? 0.75, defaultContextWindow: config.defaultContextWindow ?? 1_048_576, headroomTokens: config.headroomTokens ?? 65536,
57
65
  summarizationProvider: config.summarizationProvider ?? '', summarizationModel: config.summarizationModel ?? '',
58
66
  maxTokens: config.maxTokens ?? config.headroomTokens ?? 65536, maxOverflowRetries: config.maxOverflowRetries ?? 1,
59
67
  };
60
68
  }
69
+ /** Compaction starts at `ratio` of the window, or earlier when a reply of `reserved` tokens would then no longer fit after the prompt. */
70
+ export function compactionThreshold(input) {
71
+ const fits = input.contextWindow - input.reserved;
72
+ if (fits <= 0)
73
+ throw new Error(`a ${input.reserved}-token reply leaves no room in a ${input.contextWindow}-token window`);
74
+ return Math.floor(Math.min(input.contextWindow * input.ratio, fits));
75
+ }
61
76
  /** Pressure failures specific to one routed model; warned once per target. */
62
77
  class TargetConfigError extends Error {
63
78
  targetKey;
@@ -72,14 +87,15 @@ export default class ToolFreeCompaction extends CompactionEngine {
72
87
  static inject = ['llm', 'tokenMeter', 'sessions'];
73
88
  static Config = z.object({
74
89
  timeZone: z.string(), auto: z.boolean(),
75
- thresholdRatio: z.number(), headroomTokens: z.natural(), summarizationProvider: z.string(), summarizationModel: z.string(),
90
+ thresholdRatio: z.number(), defaultContextWindow: z.natural(), headroomTokens: z.natural(), summarizationProvider: z.string(), summarizationModel: z.string(),
76
91
  maxTokens: z.natural(), maxOverflowRetries: z.natural(),
77
- modelPolicies: z.array(z.object({ provider: z.string().required(), model: z.string().required(), thresholdRatio: z.number(), headroomTokens: z.natural(), summarizationProvider: z.string(), summarizationModel: z.string(), maxTokens: z.natural(), maxOverflowRetries: z.natural() })),
92
+ modelPolicies: z.array(z.object({ provider: z.string().required(), model: z.string().required(), thresholdRatio: z.number(), defaultContextWindow: z.natural(), headroomTokens: z.natural(), summarizationProvider: z.string(), summarizationModel: z.string(), maxTokens: z.natural(), maxOverflowRetries: z.natural() })),
78
93
  });
79
94
  policy;
80
95
  overrides;
81
96
  timeZone;
82
97
  warnedTargets = new Set();
98
+ assumedWindows = new Set();
83
99
  overflowRetries = new WeakMap();
84
100
  overflowAgents = new WeakMap();
85
101
  constructor(ctx, config = {}) {
@@ -175,14 +191,22 @@ export default class ToolFreeCompaction extends CompactionEngine {
175
191
  const info = await this.ctx.llm.resolveModelInfo(target.provider, target.model, signal);
176
192
  assertNoActiveCompaction(agent.session, 'automatic pressure compaction');
177
193
  const key = `${target.provider}/${target.model}`;
178
- if (!info.context)
179
- throw new TargetConfigError(key, `dsh-world/compaction: no context capacity for ${key}; configure contextWindow on that adapter model`);
180
- const { contextWindow } = info.context;
194
+ let contextWindow = info.context?.contextWindow;
195
+ if (contextWindow === undefined) {
196
+ contextWindow = policy.defaultContextWindow;
197
+ if (!this.assumedWindows.has(key)) {
198
+ this.assumedWindows.add(key);
199
+ this.ctx.logger.warn(`dsh-world/compaction: ${key} declares no contextWindow; assuming ${contextWindow} tokens, so compaction starts at ${Math.floor(contextWindow * policy.thresholdRatio)}. If its real window is smaller, set contextWindow on that adapter model, or defaultContextWindow for it in modelPolicies.`);
200
+ }
201
+ }
181
202
  const reserved = agent.session.requestHeader()?.config.maxTokens ?? info.defaultMaxTokens ?? 0;
182
- const pressureBudget = contextWindow - reserved - policy.headroomTokens;
183
- if (pressureBudget <= 0)
184
- throw new TargetConfigError(key, `dsh-world/compaction: ${key} reserves ${reserved} completion and ${policy.headroomTokens} headroom tokens of its ${contextWindow}-token window, leaving no pressure budget`);
185
- const threshold = Math.floor(Math.min(contextWindow * policy.thresholdRatio, pressureBudget));
203
+ let threshold;
204
+ try {
205
+ threshold = compactionThreshold({ contextWindow, ratio: policy.thresholdRatio, reserved });
206
+ }
207
+ catch (error) {
208
+ throw new TargetConfigError(key, `dsh-world/compaction: ${key}: ${error instanceof Error ? error.message : String(error)}`);
209
+ }
186
210
  if (meter.measure(agent.session).totalTokens < threshold)
187
211
  return null;
188
212
  const range = selectWholeRange(agent.session, meter.measure(agent.session));
@@ -1,6 +1,7 @@
1
1
  export type CompactionSwap = {
2
2
  status: 'swapped';
3
3
  backup: string;
4
+ preset?: string;
4
5
  } | {
5
6
  status: 'already';
6
7
  } | {
@@ -14,6 +15,31 @@ export type CompactionSwap = {
14
15
  * stock row is there, keeps a backup beside it and swaps atomically; DSH has to be restarted to load the new backend.
15
16
  */
16
17
  export declare function swapStockCompaction(profileDir: string): CompactionSwap;
18
+ /** The preset's config with its one stock compaction row renamed to ours; the input is not changed. */
19
+ export declare function swapPresetConfig(config: unknown): {
20
+ status: 'swapped';
21
+ config: unknown;
22
+ } | Exclude<CompactionSwap, {
23
+ status: 'swapped';
24
+ }>;
25
+ /** DSH's own editor for profile rows: the one its settings pages save through, which also reloads the row. */
26
+ export interface ConfigEditor {
27
+ entries(): ConfigEntry[];
28
+ edit(entry: ConfigEntry, change: (raw: unknown, inherited: unknown) => unknown): Promise<void>;
29
+ }
30
+ interface ConfigEntry {
31
+ options: {
32
+ id?: string;
33
+ name?: string;
34
+ config?: unknown;
35
+ };
36
+ }
37
+ /**
38
+ * DSH's Web host composes the stock compaction inside each preset, so the profile has no row to rename. The host's
39
+ * preset editor writes the whole preset into the profile when a partner edits it; this does the same for her preset
40
+ * with only the compaction row changed. That copy no longer follows later DSH updates to the preset.
41
+ */
42
+ export declare function swapPresetCompaction(editor: ConfigEditor, presetId: string, profileDir: string): Promise<CompactionSwap>;
17
43
  /**
18
44
  * Once per world, when the plugin first runs in a profile: make the profile use the tool-free compaction. The attempt is
19
45
  * remembered only when it succeeded or was already done, so a partner who later puts the stock one back is left alone,
@@ -25,5 +51,6 @@ export declare function swapCompactionOnce(deps: {
25
51
  done(): boolean;
26
52
  markDone(): void;
27
53
  report(message: string): void;
28
- swap?: (profileDir: string) => CompactionSwap;
29
- }): void;
54
+ swap?: (profileDir: string) => CompactionSwap | Promise<CompactionSwap>;
55
+ }): Promise<void>;
56
+ export {};
@@ -1,8 +1,15 @@
1
1
  import { randomBytes } from 'node:crypto';
2
2
  import { copyFileSync, existsSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
3
3
  import { join } from 'node:path';
4
+ const STOCK = '@deepseek-ai/dsh-compaction-basic';
5
+ const OURS = 'dsh-world/compaction';
4
6
  const stock = /^(\s*name:\s*)(['"]?)@deepseek-ai\/dsh-compaction-basic\2([ \t]*(?:#.*)?\r?)$/gm;
5
7
  const ours = /^\s*name:\s*['"]?dsh-world\/compaction['"]?\s*$/m;
8
+ function backupBeside(file) {
9
+ const backup = `${file}.dsh-world.${randomBytes(16).toString('hex')}.bak`;
10
+ copyFileSync(file, backup);
11
+ return backup;
12
+ }
6
13
  /**
7
14
  * Replaces the profile's stock compaction row with `dsh-world/compaction`, the same edit as
8
15
  * `scripts/enable-tool-free-compaction.ps1`: a bundle patch cannot do it, because the stock row is written out in the
@@ -19,9 +26,8 @@ export function swapStockCompaction(profileDir) {
19
26
  const rows = [...text.matchAll(stock)];
20
27
  if (rows.length !== 1)
21
28
  return { status: 'unchanged', reason: rows.length ? `找到 ${rows.length} 条原版压缩配置,无法确定改哪一条` : '没有找到原版压缩那一行(可能已换成别的压缩,或写法不同)' };
22
- const backup = `${file}.dsh-world.${randomBytes(16).toString('hex')}.bak`;
29
+ const backup = backupBeside(file);
23
30
  const temporary = `${file}.${randomBytes(16).toString('hex')}.tmp`;
24
- copyFileSync(file, backup);
25
31
  try {
26
32
  writeFileSync(temporary, text.replace(stock, "$1'dsh-world/compaction'$3"), 'utf8');
27
33
  renameSync(temporary, file);
@@ -32,25 +38,74 @@ export function swapStockCompaction(profileDir) {
32
38
  }
33
39
  return { status: 'swapped', backup };
34
40
  }
41
+ /** The compaction rows in a preset's plugin list, including those nested in groups (where DSH's Web host isolates it). */
42
+ function compactionRows(rows, found = []) {
43
+ if (!Array.isArray(rows))
44
+ return found;
45
+ for (const row of rows) {
46
+ if (row?.name === STOCK || row?.name === OURS)
47
+ found.push(row);
48
+ if (row?.group)
49
+ compactionRows(row.config, found);
50
+ }
51
+ return found;
52
+ }
53
+ /** The preset's config with its one stock compaction row renamed to ours; the input is not changed. */
54
+ export function swapPresetConfig(config) {
55
+ const next = structuredClone(config);
56
+ const rows = compactionRows(next?.plugins);
57
+ if (rows.some(row => row.name === OURS))
58
+ return { status: 'already' };
59
+ if (rows.length !== 1)
60
+ return { status: 'unchanged', reason: rows.length ? `预设里有 ${rows.length} 条原版压缩配置,无法确定改哪一条` : '预设里没有原版压缩那一行' };
61
+ rows[0].name = OURS;
62
+ return { status: 'swapped', config: next };
63
+ }
64
+ /**
65
+ * DSH's Web host composes the stock compaction inside each preset, so the profile has no row to rename. The host's
66
+ * preset editor writes the whole preset into the profile when a partner edits it; this does the same for her preset
67
+ * with only the compaction row changed. That copy no longer follows later DSH updates to the preset.
68
+ */
69
+ export async function swapPresetCompaction(editor, presetId, profileDir) {
70
+ const entry = editor.entries().find(row => row.options.name === '@deepseek-ai/dsh-agent-preset' && row.options.config?.id === presetId);
71
+ if (!entry)
72
+ return { status: 'unchanged', reason: `没有找到预设 ${presetId}` };
73
+ const first = swapPresetConfig(entry.options.config);
74
+ if (first.status !== 'swapped')
75
+ return first;
76
+ const file = join(profileDir, 'cordis.patch.yml');
77
+ const backup = existsSync(file) ? backupBeside(file) : undefined;
78
+ await editor.edit(entry, raw => {
79
+ const result = swapPresetConfig(raw);
80
+ if (result.status !== 'swapped')
81
+ throw new Error(`预设 ${presetId} 在写入前变了:${result.status === 'unchanged' ? result.reason : '已经换过'}`);
82
+ return result.config;
83
+ });
84
+ return { status: 'swapped', backup: backup ?? '(原来没有 cordis.patch.yml)', preset: presetId };
85
+ }
35
86
  /**
36
87
  * Once per world, when the plugin first runs in a profile: make the profile use the tool-free compaction. The attempt is
37
88
  * remembered only when it succeeded or was already done, so a partner who later puts the stock one back is left alone,
38
89
  * while a profile this could not read is looked at again next start.
39
90
  */
40
- export function swapCompactionOnce(deps) {
91
+ export async function swapCompactionOnce(deps) {
41
92
  if (!deps.enabled || deps.done() || !deps.profileDir)
42
93
  return;
43
94
  let result;
44
95
  try {
45
- result = (deps.swap ?? swapStockCompaction)(deps.profileDir);
96
+ result = await (deps.swap ?? swapStockCompaction)(deps.profileDir);
46
97
  }
47
98
  catch (error) {
48
99
  deps.report(`没能把压缩换成 dsh-world 的“只留对话”压缩:${error instanceof Error ? error.message : String(error)}`);
49
100
  return;
50
101
  }
51
- if (result.status === 'unchanged')
102
+ if (result.status === 'unchanged') {
103
+ deps.report(`没有换成 dsh-world 的“只留对话”压缩(${result.reason}):自动压缩仍由预设自带的压缩负责,dsh-world 的 75% 触发线不生效;控制台的“应用并压缩”和回顾后压缩照常可用。`);
52
104
  return;
105
+ }
53
106
  deps.markDone();
54
- if (result.status === 'swapped')
55
- deps.report(`已把 profile 的压缩换成 dsh-world 的“只留对话”压缩,重启 DSH 后生效(原文件备份在 ${result.backup})。不想换:恢复备份,并在 dsh-world 配置里写 replaceCompaction: false。`);
107
+ if (result.status !== 'swapped')
108
+ return;
109
+ const copied = result.preset ? `预设 ${result.preset} 已整份写进 profile,之后 DSH 升级对这个预设的改动不会自动进来;` : '';
110
+ deps.report(`已把 profile 的压缩换成 dsh-world 的“只留对话”压缩,重启 DSH 后生效(原文件备份在 ${result.backup})。${copied}不想换:恢复备份,并在 dsh-world 配置里写 replaceCompaction: false。`);
56
111
  }
@@ -11,14 +11,23 @@ interface HomeApplyDeps {
11
11
  ctx: Context;
12
12
  home(): Promise<Agent>;
13
13
  isHome(agent: Agent): boolean;
14
- compaction(): Pick<CompactionEngine, 'compactNow'> | undefined;
14
+ /** The engine her home actually compacts with; on the Web host it sits inside the session's preset, not on the host. */
15
+ compaction(agent: Agent): Pick<CompactionEngine, 'compactNow'> | undefined;
15
16
  refresh(session: Session): void;
16
17
  changed(): void;
18
+ /** The console health entry for a failed request; undefined clears it. */
19
+ fault(message: string | undefined): void;
17
20
  }
21
+ /**
22
+ * DSH's Web host composes compaction inside each session's preset, an isolated realm the host plane cannot see; the
23
+ * host-plane service is what the TUI, or a profile that inserts one at the top level, provides.
24
+ */
25
+ export declare function compactionFor(ctx: Pick<Context, 'get'>, agent: Agent): Pick<CompactionEngine, 'compactNow'> | undefined;
18
26
  /** One explicit request, held behind existing turns and cancelled with the life line. */
19
27
  export declare function createHomeApply(deps: HomeApplyDeps): {
20
28
  snapshot: () => HomeApplyState;
21
- request(): string | undefined;
29
+ /** Failures, including a missing engine, arrive later as the `failed` state. */
30
+ request(): undefined;
22
31
  cancel(): Promise<void>;
23
32
  };
24
33
  export {};
@@ -1,6 +1,22 @@
1
1
  import { addAbortListener } from 'node:events';
2
2
  import { ManualCompactionError } from '@deepseek-ai/dsh-compaction';
3
3
  import { errorText } from "../faults.js";
4
+ /**
5
+ * DSH's Web host composes compaction inside each session's preset, an isolated realm the host plane cannot see; the
6
+ * host-plane service is what the TUI, or a profile that inserts one at the top level, provides.
7
+ */
8
+ export function compactionFor(ctx, agent) {
9
+ const preset = ctx.get('agentPresets')?.serviceFor?.(agent, 'compaction');
10
+ return preset ?? ctx.get('compaction');
11
+ }
12
+ const unavailable = '未加载压缩服务:家会话所用的预设里和宿主上都没有压缩插件';
13
+ /** The manual compaction error says only which stage failed; what actually went wrong is in its cause. */
14
+ function failureText(error) {
15
+ const parts = [];
16
+ for (let current = error; current !== undefined && parts.length < 4; current = current instanceof Error ? current.cause : undefined)
17
+ parts.push(errorText(current));
18
+ return parts.join(':');
19
+ }
4
20
  async function abortable(promise, signal) {
5
21
  signal.throwIfAborted();
6
22
  let listener;
@@ -18,10 +34,25 @@ export function createHomeApply(deps) {
18
34
  let controller;
19
35
  let pending;
20
36
  const stopped = new Error('世界已停止');
21
- function update(next) { state = next; deps.changed(); }
22
- async function run(engine, operation) {
37
+ function update(next) {
38
+ state = next;
39
+ deps.changed();
40
+ // The state only lives in memory, and the nightly request after the review has no one watching it.
41
+ if (next.status === 'failed') {
42
+ deps.ctx.logger.warn(`dsh-world: ${next.message ?? ''}`);
43
+ deps.fault(next.message);
44
+ }
45
+ else if (next.status === 'done') {
46
+ deps.ctx.logger.info(`dsh-world: ${next.message ?? ''}`);
47
+ deps.fault(undefined);
48
+ }
49
+ }
50
+ async function run(operation) {
23
51
  const { signal } = operation;
24
52
  const agent = await abortable(deps.home(), signal);
53
+ const engine = deps.compaction(agent);
54
+ if (!engine)
55
+ throw new Error(unavailable);
25
56
  const check = () => {
26
57
  if (!signal.aborted && !deps.isHome(agent))
27
58
  operation.abort(new Error('家会话已变化,请重新提交'));
@@ -78,17 +109,15 @@ export function createHomeApply(deps) {
78
109
  }
79
110
  return {
80
111
  snapshot: () => state,
112
+ /** Failures, including a missing engine, arrive later as the `failed` state. */
81
113
  request() {
82
114
  if (pending)
83
115
  return;
84
- const engine = deps.compaction();
85
- if (!engine)
86
- return '未加载压缩服务,请先启用 DSH 压缩插件';
87
116
  controller = new AbortController();
88
117
  const { signal } = controller;
89
118
  update({ status: 'waiting' });
90
- pending = run(engine, controller).catch(error => {
91
- update({ ...state, status: signal.reason === stopped ? 'cancelled' : 'failed', message: signal.reason === stopped ? '已取消应用并压缩家会话。' : `应用并压缩失败:${errorText(signal.aborted ? signal.reason : error)}` });
119
+ pending = run(controller).catch(error => {
120
+ update({ ...state, status: signal.reason === stopped ? 'cancelled' : 'failed', message: signal.reason === stopped ? '已取消应用并压缩家会话。' : `应用并压缩失败:${failureText(signal.aborted ? signal.reason : error)}` });
92
121
  }).finally(() => { controller = undefined; pending = undefined; });
93
122
  return undefined;
94
123
  },
@@ -3,6 +3,7 @@ import { type JsonResult } from '../http.ts';
3
3
  import { type Persona } from '../persona.ts';
4
4
  import { type MemoryArchiveScope } from '../archiveSelection.ts';
5
5
  import type { PhotoStore } from '../life/photos.ts';
6
+ import { type MemoryContent, type MemoryPage } from '../memory.ts';
6
7
  export declare const CONSOLE_PREFIX = "/dsh-world";
7
8
  /** A write must carry this header; a page on another site cannot add it without a CORS preflight, which is never answered. */
8
9
  export declare const WRITE_HEADER = "x-dsh-world";
@@ -12,6 +13,9 @@ export interface ConsoleSources {
12
13
  diary(date: string): string | undefined;
13
14
  photos?(limit: number, offset: number): ReturnType<PhotoStore['list']>;
14
15
  photo?(id: string): ReturnType<PhotoStore['image']>;
16
+ /** The same lookups the memory tools make; they check the query themselves. */
17
+ memoryFind?(input: Record<string, unknown>): Promise<MemoryPage>;
18
+ memoryRead?(input: Record<string, unknown>): Promise<MemoryContent>;
15
19
  }
16
20
  /** What the console can change: whether her world runs, and her persona and world prompt. */
17
21
  export interface ConsoleActions {
@@ -24,6 +28,10 @@ export interface ConsoleActions {
24
28
  worldPrompt: {
25
29
  text: string;
26
30
  custom: boolean;
31
+ memory?: {
32
+ missing: string[];
33
+ snippet: string;
34
+ };
27
35
  };
28
36
  };
29
37
  savePersona(persona: Partial<Persona>): void;
@@ -2,10 +2,34 @@ import { jsonObject, knownHost, readBody, sendJson } from "../http.js";
2
2
  import { PERSONA_LAYERS } from "../persona.js";
3
3
  import { validTurns, validWechatBuffer, validWechatContext, validWorkspacePermission, MAX_WECHAT_BUFFER_SECONDS, MAX_WECHAT_CONTEXT } from "../worldSwitch.js";
4
4
  import { validArchiveScope } from "../archiveSelection.js";
5
+ import { MemoryError } from "../memory.js";
5
6
  export const CONSOLE_PREFIX = '/dsh-world';
6
7
  /** A write must carry this header; a page on another site cannot add it without a CORS preflight, which is never answered. */
7
8
  export const WRITE_HEADER = 'x-dsh-world';
8
9
  const MAX_BODY_BYTES = 64 * 1024;
10
+ const MEMORY_STATUS = { invalidQuery: 400, invalidRef: 400, invalidCursor: 400, notFound: 404, outOfScope: 403, cursorExpired: 409, sourceChanged: 409, scopeChanged: 409, readFailed: 500 };
11
+ /** Query-string values to the shape the tools take: a number that is not one stays NaN and is refused by the shared check. */
12
+ function memoryInput(params, numbers, flags, lists) {
13
+ const input = {};
14
+ for (const [key, value] of params) {
15
+ if (value === '')
16
+ continue;
17
+ input[key] = numbers.includes(key) ? Number(value) : flags.includes(key) ? value === '1' || value === 'true' : lists.includes(key) ? value.split(',') : value;
18
+ }
19
+ return input;
20
+ }
21
+ async function memoryCall(run) {
22
+ if (!run)
23
+ return { status: 404, body: { error: '记忆查找不可用' } };
24
+ try {
25
+ return ok(await run());
26
+ }
27
+ catch (error) {
28
+ if (error instanceof MemoryError)
29
+ return { status: MEMORY_STATUS[error.code], body: { error: error.message, code: error.code } };
30
+ throw error;
31
+ }
32
+ }
9
33
  const ok = (body = { ok: true }) => ({ status: 200, body });
10
34
  const bad = (error) => ({ status: 400, body: { error } });
11
35
  function persona(body) {
@@ -123,6 +147,14 @@ export async function handleConsole(sources, actions, request) {
123
147
  return text === undefined ? { status: 404, body: { error: 'no diary for this date' } } : ok({ date, text });
124
148
  }
125
149
  case '/console/prompts': return ok(actions.prompts());
150
+ case '/console/memory/find': {
151
+ const input = memoryInput(url.searchParams, ['limit'], ['history'], ['kinds']);
152
+ return memoryCall(sources.memoryFind && (() => sources.memoryFind(input)));
153
+ }
154
+ case '/console/memory/read': {
155
+ const input = memoryInput(url.searchParams, ['offset', 'limit'], [], []);
156
+ return memoryCall(sources.memoryRead && (() => sources.memoryRead(input)));
157
+ }
126
158
  case '/console/photos': {
127
159
  const limit = Number(url.searchParams.get('limit') ?? 20), offset = Number(url.searchParams.get('offset') ?? 0);
128
160
  if (!Number.isSafeInteger(limit) || limit < 1 || limit > 100 || !Number.isSafeInteger(offset) || offset < 0)
@@ -8,6 +8,7 @@ import type { MemoryArchiveScope } from '../archiveSelection.ts';
8
8
  import type { ConsoleSources } from './routes.ts';
9
9
  import type { HomeApplyState } from './homeApply.ts';
10
10
  import type { PhotoStore } from '../life/photos.ts';
11
+ import type { MemoryService } from '../memory.ts';
11
12
  export declare function estimateTokens(text: string): number;
12
13
  export interface SnapshotDeps {
13
14
  ctx: Context;
@@ -20,6 +21,8 @@ export interface SnapshotDeps {
20
21
  life(): LifeRuntime | undefined;
21
22
  homeApply?(): HomeApplyState;
22
23
  photos?(): PhotoStore;
24
+ /** Long-term memory: the console's lookups and the health of its index. */
25
+ longTerm?: MemoryService;
23
26
  diaryDir: string;
24
27
  running(): boolean;
25
28
  /** CNY a day for her home; undefined is no limit. */
@@ -30,7 +30,7 @@ export function consoleSources(deps) {
30
30
  life: life ? { homeSessionId: life.homeSessionId, status: home ? home.status : 'cold', alarm: life.alarm, review: life.review, recentWakes: lifeStore?.wakes().slice(-5).reverse() ?? [] } : null,
31
31
  homeApply: deps.homeApply?.() ?? null,
32
32
  health: [...(life?.faults ?? []), ...deps.faults()],
33
- memory: { turns: turns.length, windowTurns: window, archiveScope, selectedArchiveScope, restartRequired: archiveScope !== selectedArchiveScope, approxTokens: estimateTokens(renderHistory(turns, config.timeZone, deps.names(), archiveScope === 'home')), oldest: turns.at(-1)?.messages[0]?.occurredAt, ...archive.stats() },
33
+ memory: { index: deps.longTerm?.status() ?? null, turns: turns.length, windowTurns: window, archiveScope, selectedArchiveScope, restartRequired: archiveScope !== selectedArchiveScope, approxTokens: estimateTokens(renderHistory(turns, config.timeZone, deps.names(), archiveScope === 'home')), oldest: turns.at(-1)?.messages[0]?.occurredAt, ...archive.stats() },
34
34
  wechat: deps.wechat?.() ?? null,
35
35
  compactions: lifeStore?.compactions().slice(-5).reverse() ?? [],
36
36
  diaryDates: diary.dates(), activityDays: lifeStore?.activityDays() ?? [],
@@ -55,5 +55,6 @@ export function consoleSources(deps) {
55
55
  photos: (limit, offset) => { if (!deps.photos)
56
56
  throw new Error('相册不可用'); return deps.photos().list(limit, offset); },
57
57
  photo: id => deps.photos?.().image(id),
58
+ ...(deps.longTerm ? { memoryFind: (input) => deps.longTerm.find(input), memoryRead: (input) => deps.longTerm.read(input) } : {}),
58
59
  };
59
60
  }
@@ -1,9 +1,16 @@
1
1
  import type { IncomingMessage, ServerResponse } from 'node:http';
2
2
  import { type Bridge } from './bridge.ts';
3
3
  export declare const BRIDGE_PATH = "/dsh-world/bridge/say";
4
+ export declare const COMPACT_PATH = "/dsh-world/bridge/compact";
4
5
  /** The one outside route that changes something: a local app hands her partner's words to her home. */
5
6
  export declare function bridgeRoute(bridge: () => Bridge | undefined, allowedHosts?: readonly string[]): {
6
7
  kind: "exact";
7
8
  path: string;
8
9
  handler: (req: IncomingMessage, res: ServerResponse) => Promise<void>;
9
10
  };
11
+ /** Asks for one compaction of her home, held behind her running turn; the same token as the words route. */
12
+ export declare function compactRoute(bridge: () => Bridge | undefined, request: () => string | undefined, allowedHosts?: readonly string[]): {
13
+ kind: "exact";
14
+ path: string;
15
+ handler: (req: IncomingMessage, res: ServerResponse) => Promise<void>;
16
+ };
@@ -1,6 +1,7 @@
1
1
  import { jsonObject, knownHost, readBody, sendJson } from "../../http.js";
2
2
  import { HomeUnavailable } from "./bridge.js";
3
3
  export const BRIDGE_PATH = '/dsh-world/bridge/say';
4
+ export const COMPACT_PATH = '/dsh-world/bridge/compact';
4
5
  const MAX_BODY_BYTES = 32 * 1024;
5
6
  const MAX_TEXT = 2000;
6
7
  const bad = { status: 400, body: { error: 'bad request' } };
@@ -44,3 +45,32 @@ export function bridgeRoute(bridge, allowedHosts = []) {
44
45
  },
45
46
  };
46
47
  }
48
+ async function handleCompact(bridge, request, req, allowedHosts) {
49
+ if (req.method !== 'POST')
50
+ return { status: 405, body: { error: 'method not allowed' }, headers: { allow: 'POST' } };
51
+ const token = req.headers['x-dsh-world-token'];
52
+ if (req.headers['sec-fetch-site'] === 'cross-site' || !knownHost(req.headers.host, allowedHosts))
53
+ return { status: 403, body: { error: 'forbidden' } };
54
+ if (!bridge)
55
+ return unavailable;
56
+ if (!bridge.checkToken(Array.isArray(token) ? undefined : token))
57
+ return { status: 403, body: { error: 'forbidden' } };
58
+ const refused = request();
59
+ return refused ? { status: 409, body: { error: refused } } : { status: 202, body: { accepted: true } };
60
+ }
61
+ /** Asks for one compaction of her home, held behind her running turn; the same token as the words route. */
62
+ export function compactRoute(bridge, request, allowedHosts = []) {
63
+ return {
64
+ kind: 'exact', path: COMPACT_PATH,
65
+ handler: async (req, res) => {
66
+ let result;
67
+ try {
68
+ result = await handleCompact(bridge(), request, req, allowedHosts);
69
+ }
70
+ catch {
71
+ result = { status: 500, body: { error: 'internal error' } };
72
+ }
73
+ sendJson(res, result);
74
+ },
75
+ };
76
+ }
@@ -10,6 +10,7 @@ declare module '@deepseek-ai/dsh-llm' {
10
10
  'dsh-world-life': {
11
11
  kind: 'dsh-world-life';
12
12
  };
13
+ /** 她图谱里的卡片:消息里提到她记过的名字时追加,压缩后重来,不进归档。 */
13
14
  'dsh-world-channel-context': {
14
15
  kind: 'dsh-world-channel-context';
15
16
  form: 'recall';