dsh-world 0.6.6 → 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.
- package/CHANGELOG.md +21 -0
- package/CONTRIBUTING.md +163 -161
- package/INSTALL.md +314 -314
- package/LICENSE +21 -21
- package/NOTES.md +173 -152
- package/README.md +236 -227
- package/client/index.js +849 -738
- package/cordis.patch.yml +6 -6
- package/lib/compaction.js +8 -0
- package/lib/compactionSwap.d.ts +29 -2
- package/lib/compactionSwap.js +62 -7
- package/lib/console/homeApply.d.ts +11 -2
- package/lib/console/homeApply.js +36 -7
- package/lib/console/routes.d.ts +8 -0
- package/lib/console/routes.js +32 -0
- package/lib/console/snapshot.d.ts +3 -0
- package/lib/console/snapshot.js +2 -1
- package/lib/ecosystem/bridge/route.d.ts +7 -0
- package/lib/ecosystem/bridge/route.js +30 -0
- package/lib/hostContract.d.ts +1 -0
- package/lib/index.js +37 -12
- package/lib/memory.d.ts +57 -0
- package/lib/memory.js +210 -0
- package/lib/memoryFiles.d.ts +53 -0
- package/lib/memoryFiles.js +193 -0
- package/lib/memoryStore.d.ts +114 -0
- package/lib/memoryStore.js +159 -0
- package/lib/memoryTools.d.ts +31 -0
- package/lib/memoryTools.js +106 -0
- package/lib/promptSection.d.ts +2 -0
- package/lib/runtime.d.ts +1 -1
- package/lib/runtime.js +61 -29
- package/lib/sourceArchive.d.ts +1 -0
- package/lib/sourceArchive.js +1 -1
- package/lib/store.d.ts +14 -0
- package/lib/store.js +11 -1
- package/lib/worldPrompt.d.ts +6 -0
- package/lib/worldPrompt.js +7 -1
- package/package.json +128 -117
- package/scripts/compact-home.mjs +29 -0
- package/scripts/enable-tool-free-compaction.ps1 +33 -33
- package/scripts/import-stickers.mjs +17 -17
- package/scripts/update-world.mjs +5 -3
- package/src/ecosystem/wechat/windows/README.md +6 -4
- package/src/ecosystem/wechat/windows/adapter.py +80 -31
- package/src/ecosystem/wechat/windows/engine/NOTICE.md +1 -1
- package/src/ecosystem/wechat/windows/engine/bridge.cpp +9 -1
- package/src/ecosystem/wechat/windows/engine/profiles.json +114 -58
- package/src/ecosystem/wechat/windows/native.py +4 -1
- package/src/ecosystem/wechat/windows/outgoing.py +21 -0
- package/src/ecosystem/wechat/windows/presence.py +109 -109
- package/src/ecosystem/wechat/windows/sender.py +9 -1
- package/templates/alarm.md +3 -4
- package/templates/world-prompt-memory.md +10 -0
- 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
|
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;
|
package/lib/compactionSwap.d.ts
CHANGED
|
@@ -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 {};
|
package/lib/compactionSwap.js
CHANGED
|
@@ -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 =
|
|
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
|
|
55
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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 {};
|
package/lib/console/homeApply.js
CHANGED
|
@@ -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) {
|
|
22
|
-
|
|
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(
|
|
91
|
-
update({ ...state, status: signal.reason === stopped ? 'cancelled' : 'failed', message: signal.reason === stopped ? '已取消应用并压缩家会话。' : `应用并压缩失败:${
|
|
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
|
},
|
package/lib/console/routes.d.ts
CHANGED
|
@@ -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;
|
package/lib/console/routes.js
CHANGED
|
@@ -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. */
|
package/lib/console/snapshot.js
CHANGED
|
@@ -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
|
+
}
|
package/lib/hostContract.d.ts
CHANGED
package/lib/index.js
CHANGED
|
@@ -3,12 +3,12 @@ import { join } from 'node:path';
|
|
|
3
3
|
import z from '@deepseek-ai/schemastery';
|
|
4
4
|
import { resolveDshHome } from '@deepseek-ai/dsh-home-paths';
|
|
5
5
|
import { createBridge } from "./ecosystem/bridge/bridge.js";
|
|
6
|
-
import { bridgeRoute } from "./ecosystem/bridge/route.js";
|
|
6
|
+
import { bridgeRoute, compactRoute } from "./ecosystem/bridge/route.js";
|
|
7
7
|
import { consoleRoute } from "./console/routes.js";
|
|
8
8
|
import { consoleSources } from "./console/snapshot.js";
|
|
9
|
-
import { createHomeApply } from "./console/homeApply.js";
|
|
9
|
+
import { compactionFor, createHomeApply } from "./console/homeApply.js";
|
|
10
10
|
import { errorText, Faults } from "./faults.js";
|
|
11
|
-
import { swapCompactionOnce } from "./compactionSwap.js";
|
|
11
|
+
import { swapCompactionOnce, swapPresetCompaction, swapStockCompaction } from "./compactionSwap.js";
|
|
12
12
|
import { hostLife } from "./life/host.js";
|
|
13
13
|
import { createLifeStore, durableWrite } from "./life/lifeStore.js";
|
|
14
14
|
import { toastSupported, windowsToast } from "./life/notify.js";
|
|
@@ -17,9 +17,10 @@ import { createOutlet } from "./ecosystem/shared/outlets.js";
|
|
|
17
17
|
import { readPersona, writePersona } from "./persona.js";
|
|
18
18
|
import { qqRoute } from "./ecosystem/qq/route.js";
|
|
19
19
|
import { createConsoleDoors, discoverSnowlumaHome } from "./ecosystem/qq/panel.js";
|
|
20
|
+
import { createMemory } from "./memory.js";
|
|
20
21
|
import { createWorldRuntime } from "./runtime.js";
|
|
21
22
|
import { createArchiveStore } from "./store.js";
|
|
22
|
-
import { DEFAULT_TEMPLATE_FILE, roomTitle, worldNames } from "./worldPrompt.js";
|
|
23
|
+
import { DEFAULT_TEMPLATE_FILE, MEMORY_SNIPPET_FILE, memoryTemplateGaps, roomTitle, worldNames } from "./worldPrompt.js";
|
|
23
24
|
import { createWorldSwitch } from "./worldSwitch.js";
|
|
24
25
|
import { createWechatModule } from "./ecosystem/wechat/index.js";
|
|
25
26
|
import { createWechatRecorder } from "./ecosystem/wechat/archive.js";
|
|
@@ -118,7 +119,8 @@ export async function apply(ctx, config) {
|
|
|
118
119
|
const selfFile = config.selfFile || join(worldDir, 'room', '我是谁.md');
|
|
119
120
|
const personaFile = config.personaFile || join(worldDir, 'persona.md');
|
|
120
121
|
const worldPromptFile = config.worldPromptFile || join(worldDir, 'world-prompt.md');
|
|
121
|
-
const
|
|
122
|
+
const roomDir = join(worldDir, 'room');
|
|
123
|
+
const options = { worldDir, roomDir, diaryDir: config.diaryDir || join(worldDir, 'diary'), selfFile, fallbackWakeTime: config.fallbackWakeTime, timeZone: config.timeZone, alarmFile: config.alarmTemplateFile || join(worldDir, 'alarm.md') };
|
|
122
124
|
/** The name in her persona comes first, then the configured one. */
|
|
123
125
|
const names = () => worldNames({ ...config, companionName: readPersona(personaFile).名字 || config.companionName });
|
|
124
126
|
const lifeStore = (() => {
|
|
@@ -142,13 +144,17 @@ export async function apply(ctx, config) {
|
|
|
142
144
|
/** Where her world reaches: her room's workspace, and in it the sessions of her preset. */
|
|
143
145
|
const inWorkspace = createWorkspaceMembership(ctx, options.roomDir);
|
|
144
146
|
const inWorldSession = (session) => inWorld(session, config, inWorkspace);
|
|
147
|
+
/** Long-term memory over the archive and her own files; the tools and the console are two doors to it. */
|
|
148
|
+
const memoryService = createMemory({ store: store.memory, timeZone: config.timeZone, sources: { diaryDir: options.diaryDir }, visible: id => archiveSession(id) });
|
|
149
|
+
/** What is wrong with long-term memory, in the console's health list: a source that could not be read. */
|
|
150
|
+
const memoryHealth = () => memoryService.status().failures.map(failure => `记忆来源 ${failure.sourceId}:${failure.message}`);
|
|
145
151
|
let memory;
|
|
146
152
|
let stopLifeLine;
|
|
147
153
|
async function startMemory(fresh) {
|
|
148
154
|
if (memory)
|
|
149
155
|
return;
|
|
150
|
-
const prompt = { file: worldPromptFile, persona: personaFile, conversationsDir: join(worldDir, 'conversations'), names: names(), ...(config.life ? { life: options } : {}) };
|
|
151
|
-
memory = createWorldRuntime(ctx, { ...memoryConfig, selfFile }, store, { prompt, names, isHome: id => isHome(id), archiveSession, inWorkspace }, power.memoryTurns);
|
|
156
|
+
const prompt = { file: worldPromptFile, persona: personaFile, conversationsDir: join(worldDir, 'conversations'), names: names(), memoryTools: true, ...(config.life ? { life: options } : {}) };
|
|
157
|
+
memory = createWorldRuntime(ctx, { ...memoryConfig, selfFile }, store, { prompt, names, isHome: id => isHome(id), archiveSession, inWorkspace, memory: memoryService }, power.memoryTurns);
|
|
152
158
|
await memory.start({ fresh });
|
|
153
159
|
}
|
|
154
160
|
async function stopMemory() {
|
|
@@ -172,8 +178,21 @@ export async function apply(ctx, config) {
|
|
|
172
178
|
ctx.inject(['sessionController', 'permissionPresets', 'webServer'], async (lifeCtx) => {
|
|
173
179
|
const webServer = lifeCtx.webServer;
|
|
174
180
|
const host = hostLife(lifeCtx);
|
|
175
|
-
|
|
181
|
+
const configEditor = lifeCtx.get('configEditor');
|
|
182
|
+
const swapCompaction = () => swapCompactionOnce({ enabled: config.replaceCompaction, profileDir: lifeCtx.get('profileContext')?.dir, done: power.compactionSwapped, markDone: power.markCompactionSwapped,
|
|
183
|
+
swap: async (dir) => { const row = swapStockCompaction(dir); return row.status === 'unchanged' && configEditor ? swapPresetCompaction(configEditor, config.agentPreset, dir) : row; },
|
|
176
184
|
report: message => { faults.set('compaction-swap', message); lifeCtx.logger.warn(`dsh-world: ${message}`); } });
|
|
185
|
+
// The preset row the editor rewrites is active only once the host has finished loading.
|
|
186
|
+
const appReady = lifeCtx.get('appReady');
|
|
187
|
+
if (!appReady)
|
|
188
|
+
void swapCompaction();
|
|
189
|
+
else
|
|
190
|
+
lifeCtx.effect(() => {
|
|
191
|
+
let closed = false;
|
|
192
|
+
const cancel = appReady.onReady(() => { if (!closed)
|
|
193
|
+
void swapCompaction(); });
|
|
194
|
+
return () => { closed = true; cancel(); };
|
|
195
|
+
}, 'dsh-world compaction swap');
|
|
177
196
|
const permissions = createWorkspacePermissions(lifeCtx, options.roomDir, power);
|
|
178
197
|
// QQ 的两扇门:她自己那条 OneBot 通道的状态与开关,以及 SnowLuma 的控制台。**无条件注册** —— 通道
|
|
179
198
|
// 关着的时候 /native 回 null,而 SnowLuma 那扇门跟通道没关系。(这里原来还有一半是给外面那个
|
|
@@ -202,10 +221,14 @@ export async function apply(ctx, config) {
|
|
|
202
221
|
home: async () => { if (!life)
|
|
203
222
|
throw new Error('请先启动世界生活线'); return life.home(); },
|
|
204
223
|
isHome: agent => !!life?.isHome(agent.id) && ctx.agents.get(agent.id) === agent && !host.isArchived(agent.id) && inWorldSession(agent.session),
|
|
205
|
-
compaction:
|
|
224
|
+
compaction: agent => compactionFor(lifeCtx, agent),
|
|
206
225
|
refresh: session => { if (!memory)
|
|
207
226
|
throw new Error('世界记忆线已停止'); memory.refreshPrompt(session); },
|
|
208
227
|
changed: () => sources.invalidate(),
|
|
228
|
+
fault: message => { if (message)
|
|
229
|
+
faults.set('home-apply', message);
|
|
230
|
+
else
|
|
231
|
+
faults.clear('home-apply'); },
|
|
209
232
|
});
|
|
210
233
|
let bridge;
|
|
211
234
|
let wechat;
|
|
@@ -350,9 +373,11 @@ export async function apply(ctx, config) {
|
|
|
350
373
|
// The host matches exact routes before the longest prefix, so this path never reaches the console.
|
|
351
374
|
if (config.bridge)
|
|
352
375
|
lifeCtx.effect(() => webServer.register(bridgeRoute(() => bridge, config.allowedHosts)), 'dsh-world bridge route');
|
|
376
|
+
if (config.bridge)
|
|
377
|
+
lifeCtx.effect(() => webServer.register(compactRoute(() => bridge, () => !power.running() || !life ? '请先启动世界生活线' : homeApply.request(), config.allowedHosts)), 'dsh-world compact route');
|
|
353
378
|
// Her album lives in her room, so the console shows it whether or not the life line is running.
|
|
354
|
-
const sources = consoleSources({ ctx: lifeCtx, config: memoryConfig, archive: store, names, ...(lifeStore ? { lifeStore } : {}), life: () => life, homeApply: homeApply.snapshot, compactAfterReview: power.compactAfterReview, photos, diaryDir: options.diaryDir, running: power.running, dailyBudget: power.dailyBudget, memoryTurns: power.memoryTurns, selectedArchiveScope: power.selectedArchiveScope, workspacePermissions: permissions.snapshot, wechat: () => wechat ? { ...wechat.status(), adapter: adapter?.status() ?? null } : undefined, archiveSession, native: () => qqNative?.status() ?? null,
|
|
355
|
-
modules: () => ({ wechat: { available: config.wechat, enabled: power.wechatEnabled(), running: wechat !== undefined }, qq: { available: Boolean(config.qqNative?.enabled), enabled: power.qqEnabled(), running: qqNative !== undefined, ...(qqSdk.needsRestart() ? { restartRequired: true } : {}) } }), faults: () => [...faults.list(), ...(memory?.faults() ?? []), ...(bridge?.faults() ?? [])] });
|
|
379
|
+
const sources = consoleSources({ ctx: lifeCtx, config: memoryConfig, archive: store, longTerm: memoryService, names, ...(lifeStore ? { lifeStore } : {}), life: () => life, homeApply: homeApply.snapshot, compactAfterReview: power.compactAfterReview, photos, diaryDir: options.diaryDir, running: power.running, dailyBudget: power.dailyBudget, memoryTurns: power.memoryTurns, selectedArchiveScope: power.selectedArchiveScope, workspacePermissions: permissions.snapshot, wechat: () => wechat ? { ...wechat.status(), adapter: adapter?.status() ?? null } : undefined, archiveSession, native: () => qqNative?.status() ?? null,
|
|
380
|
+
modules: () => ({ wechat: { available: config.wechat, enabled: power.wechatEnabled(), running: wechat !== undefined }, qq: { available: Boolean(config.qqNative?.enabled), enabled: power.qqEnabled(), running: qqNative !== undefined, ...(qqSdk.needsRestart() ? { restartRequired: true } : {}) } }), faults: () => [...faults.list(), ...(memory?.faults() ?? []), ...(bridge?.faults() ?? []), ...memoryHealth()] });
|
|
356
381
|
const actions = {
|
|
357
382
|
async start() {
|
|
358
383
|
if (power.running())
|
|
@@ -381,7 +406,7 @@ export async function apply(ctx, config) {
|
|
|
381
406
|
applyHome: () => !power.running() || !life ? '请先启动世界生活线' : homeApply.request(),
|
|
382
407
|
prompts: () => ({
|
|
383
408
|
persona: readPersona(personaFile),
|
|
384
|
-
worldPrompt: existsSync(worldPromptFile) ? { text: readFileSync(
|
|
409
|
+
worldPrompt: existsSync(worldPromptFile) ? (text => ({ text, custom: true, memory: { missing: memoryTemplateGaps(text), snippet: readFileSync(MEMORY_SNIPPET_FILE, 'utf8') } }))(readFileSync(worldPromptFile, 'utf8')) : { text: readFileSync(DEFAULT_TEMPLATE_FILE, 'utf8'), custom: false },
|
|
385
410
|
}),
|
|
386
411
|
savePersona: persona => { writePersona(personaFile, { ...readPersona(personaFile), ...persona }); sources.invalidate(); },
|
|
387
412
|
setDailyBudget: yuan => { power.setDailyBudget(yuan); sources.invalidate(); },
|