dsh-world 0.6.6 → 0.7.1
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 +39 -0
- package/CONTRIBUTING.md +163 -161
- package/NOTES.md +184 -152
- package/README.md +237 -227
- package/client/index.js +894 -738
- package/lib/archive.d.ts +3 -1
- package/lib/archive.js +6 -4
- 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 +13 -0
- package/lib/console/routes.js +43 -0
- package/lib/console/snapshot.d.ts +8 -0
- package/lib/console/snapshot.js +4 -2
- package/lib/ecosystem/bridge/route.d.ts +7 -0
- package/lib/ecosystem/bridge/route.js +30 -0
- package/lib/ecosystem/qq/route.d.ts +2 -1
- package/lib/ecosystem/qq/route.js +10 -2
- package/lib/ecosystem/qq-native/batch.d.ts +2 -0
- package/lib/ecosystem/qq-native/batch.js +3 -1
- package/lib/ecosystem/qq-native/index.d.ts +2 -0
- package/lib/ecosystem/qq-native/index.js +4 -0
- package/lib/ecosystem/qq-native/replies.d.ts +6 -1
- package/lib/ecosystem/qq-native/replies.js +19 -1
- package/lib/ecosystem/shared/context.d.ts +1 -1
- package/lib/ecosystem/shared/context.js +1 -1
- package/lib/ecosystem/shared/identity.d.ts +12 -0
- package/lib/ecosystem/shared/identity.js +17 -1
- package/lib/ecosystem/shared/turn.d.ts +8 -5
- package/lib/ecosystem/shared/turn.js +16 -17
- package/lib/ecosystem/wechat/archive.d.ts +2 -0
- package/lib/ecosystem/wechat/archive.js +3 -1
- package/lib/ecosystem/wechat/home.js +9 -4
- package/lib/ecosystem/wechat/messages.d.ts +11 -0
- package/lib/ecosystem/wechat/messages.js +9 -1
- package/lib/ecosystem/wechat/sending.js +36 -9
- package/lib/ecosystem/wechat/supervisor.d.ts +11 -2
- package/lib/ecosystem/wechat/supervisor.js +90 -9
- package/lib/history.d.ts +6 -4
- package/lib/history.js +61 -12
- package/lib/hostContract.d.ts +1 -0
- package/lib/index.js +41 -14
- package/lib/life/activity.d.ts +2 -0
- package/lib/life/activity.js +1 -1
- package/lib/life/alarm.d.ts +12 -4
- package/lib/life/alarm.js +21 -6
- package/lib/life/diary.d.ts +6 -0
- package/lib/life/diary.js +23 -2
- package/lib/life/runtime.d.ts +1 -0
- package/lib/life/runtime.js +57 -9
- package/lib/life/toolRegistry.d.ts +4 -3
- package/lib/life/toolRegistry.js +13 -3
- package/lib/life/types.d.ts +6 -1
- package/lib/memory.d.ts +57 -0
- package/lib/memory.js +207 -0
- package/lib/memoryFiles.d.ts +50 -0
- package/lib/memoryFiles.js +168 -0
- package/lib/memoryStore.d.ts +112 -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 +62 -75
- package/lib/sourceArchive.d.ts +1 -0
- package/lib/sourceArchive.js +4 -5
- package/lib/store.d.ts +15 -1
- package/lib/store.js +12 -2
- package/lib/types.d.ts +1 -4
- package/lib/worldPrompt.d.ts +6 -0
- package/lib/worldPrompt.js +8 -2
- package/lib/worldSwitch.d.ts +9 -1
- package/lib/worldSwitch.js +14 -1
- package/package.json +128 -117
- package/scripts/compact-home.mjs +29 -0
- package/scripts/update-world.mjs +6 -4
- package/src/ecosystem/wechat/windows/README.md +7 -5
- package/src/ecosystem/wechat/windows/adapter.py +86 -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/build.ps1 +8 -2
- package/src/ecosystem/wechat/windows/engine/profiles.json +56 -0
- package/src/ecosystem/wechat/windows/native.py +4 -1
- package/src/ecosystem/wechat/windows/outgoing.py +21 -0
- package/src/ecosystem/wechat/windows/sender.py +26 -6
- package/templates/alarm.md +3 -4
- package/templates/world-prompt-memory.md +10 -0
- package/templates/world-prompt.md +7 -2
package/lib/archive.d.ts
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import { type ContentBlock } from '@deepseek-ai/dsh-llm';
|
|
2
|
-
import { type SessionEvent } from '@deepseek-ai/dsh-session';
|
|
2
|
+
import { type SessionEvent, type SessionHeader } from '@deepseek-ai/dsh-session';
|
|
3
3
|
import type { ArchiveScope, ConversationRecord } from './types.ts';
|
|
4
4
|
export declare const conversationRecordId: (worldId: string, sessionId: string, messageId: string) => string;
|
|
5
5
|
export declare function visibleText(content: readonly ContentBlock[]): string;
|
|
6
|
+
/** A session someone talks in: not a subagent, not delegated. Only these are archived or carry her world. */
|
|
7
|
+
export declare const isOrdinarySession: (header: Pick<SessionHeader, "origin" | "delegationDepth">) => boolean;
|
|
6
8
|
export declare function extractConversationRecords(event: SessionEvent, scope: ArchiveScope): ConversationRecord[];
|
package/lib/archive.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { createHash } from 'node:crypto';
|
|
2
2
|
import { lastAssistantStreamChunk } from '@deepseek-ai/dsh-llm';
|
|
3
3
|
import { isAppendSurfaceEvent } from '@deepseek-ai/dsh-session';
|
|
4
|
-
import { identityPrefix, speakerIdentity } from "./ecosystem/shared/identity.js";
|
|
4
|
+
import { identityPrefix, legacyIdentityPrefix, speakerIdentity } from "./ecosystem/shared/identity.js";
|
|
5
5
|
import { replyMessages, replyText } from "./ecosystem/wechat/messages.js";
|
|
6
6
|
export const conversationRecordId = (worldId, sessionId, messageId) => createHash('sha256').update(JSON.stringify([worldId, sessionId, messageId])).digest('hex');
|
|
7
7
|
export function visibleText(content) {
|
|
@@ -13,9 +13,11 @@ export function visibleText(content) {
|
|
|
13
13
|
return [];
|
|
14
14
|
}).join('\n');
|
|
15
15
|
}
|
|
16
|
+
/** A session someone talks in: not a subagent, not delegated. Only these are archived or carry her world. */
|
|
17
|
+
export const isOrdinarySession = (header) => header.origin !== 'subagent' && (header.delegationDepth ?? 0) === 0;
|
|
16
18
|
export function extractConversationRecords(event, scope) {
|
|
17
19
|
const { header } = scope;
|
|
18
|
-
if (
|
|
20
|
+
if (!isOrdinarySession(header) || event.seq < scope.inheritedEventCount)
|
|
19
21
|
return [];
|
|
20
22
|
if (event.type !== 'user/message' && event.type !== 'assistant/message')
|
|
21
23
|
return [];
|
|
@@ -30,8 +32,8 @@ export function extractConversationRecords(event, scope) {
|
|
|
30
32
|
if (outgoing && (identity?.channel !== 'wechat' || identity.speakerId !== `wechat:${identity.accountId}`))
|
|
31
33
|
throw new Error('Invalid WeChat outgoing identity');
|
|
32
34
|
const visible = visibleText(message.content);
|
|
33
|
-
const prefix = identity
|
|
34
|
-
const content = outgoing ? `微信待发送给 ${identity.conversationId}(已生成,发送尚未确认):\n${replyText(sentMessages)}` : prefix
|
|
35
|
+
const prefix = identity && [identityPrefix(identity), legacyIdentityPrefix(identity)].find(prefix => visible.startsWith(prefix));
|
|
36
|
+
const content = outgoing ? `微信待发送给 ${identity.conversationId}(已生成,发送尚未确认):\n${replyText(sentMessages)}` : prefix ? visible.slice(prefix.length) : visible;
|
|
35
37
|
if (!content)
|
|
36
38
|
return [];
|
|
37
39
|
const turn = event.type === 'assistant/message' ? event.data.turn : scope.turn;
|
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;
|
|
@@ -37,6 +45,11 @@ export interface ConsoleActions {
|
|
|
37
45
|
setWorkspacePermission(permission: string): void;
|
|
38
46
|
/** Whether the evening look back is followed by applying and compacting her home (on unless turned off). */
|
|
39
47
|
setCompactAfterReview(on: boolean): void;
|
|
48
|
+
/** Local HH:MM of the evening look back and the morning wake; a field left out stays, null goes back to its default. */
|
|
49
|
+
setSchedule(schedule: {
|
|
50
|
+
review?: string | null;
|
|
51
|
+
wake?: string | null;
|
|
52
|
+
}): void;
|
|
40
53
|
/** A field left out stays as it is; null goes back to its default. */
|
|
41
54
|
/** Turns the WeChat and QQ modules on or off now (their tools and routes come and go with the switch). Returns why it cannot, or nothing. */
|
|
42
55
|
setModules(modules: {
|
package/lib/console/routes.js
CHANGED
|
@@ -2,10 +2,35 @@ 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 { validClockTime } from "../life/alarm.js";
|
|
6
|
+
import { MemoryError } from "../memory.js";
|
|
5
7
|
export const CONSOLE_PREFIX = '/dsh-world';
|
|
6
8
|
/** A write must carry this header; a page on another site cannot add it without a CORS preflight, which is never answered. */
|
|
7
9
|
export const WRITE_HEADER = 'x-dsh-world';
|
|
8
10
|
const MAX_BODY_BYTES = 64 * 1024;
|
|
11
|
+
const MEMORY_STATUS = { invalidQuery: 400, invalidRef: 400, invalidCursor: 400, notFound: 404, outOfScope: 403, cursorExpired: 409, sourceChanged: 409, scopeChanged: 409, readFailed: 500 };
|
|
12
|
+
/** Query-string values to the shape the tools take: a number that is not one stays NaN and is refused by the shared check. */
|
|
13
|
+
function memoryInput(params, numbers, lists) {
|
|
14
|
+
const input = {};
|
|
15
|
+
for (const [key, value] of params) {
|
|
16
|
+
if (value === '')
|
|
17
|
+
continue;
|
|
18
|
+
input[key] = numbers.includes(key) ? Number(value) : lists.includes(key) ? value.split(',') : value;
|
|
19
|
+
}
|
|
20
|
+
return input;
|
|
21
|
+
}
|
|
22
|
+
async function memoryCall(run) {
|
|
23
|
+
if (!run)
|
|
24
|
+
return { status: 404, body: { error: '记忆查找不可用' } };
|
|
25
|
+
try {
|
|
26
|
+
return ok(await run());
|
|
27
|
+
}
|
|
28
|
+
catch (error) {
|
|
29
|
+
if (error instanceof MemoryError)
|
|
30
|
+
return { status: MEMORY_STATUS[error.code], body: { error: error.message, code: error.code } };
|
|
31
|
+
throw error;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
9
34
|
const ok = (body = { ok: true }) => ({ status: 200, body });
|
|
10
35
|
const bad = (error) => ({ status: 400, body: { error } });
|
|
11
36
|
function persona(body) {
|
|
@@ -81,6 +106,16 @@ async function write(actions, path, body) {
|
|
|
81
106
|
actions.setCompactAfterReview(body.on);
|
|
82
107
|
return ok();
|
|
83
108
|
}
|
|
109
|
+
case '/console/schedule': {
|
|
110
|
+
const review = body?.review, wake = body?.wake;
|
|
111
|
+
for (const [name, value] of [['review', review], ['wake', wake]])
|
|
112
|
+
if (value !== undefined && value !== null && !validClockTime(value))
|
|
113
|
+
return bad(`${name} must be HH:MM (00:00–23:59), or null`);
|
|
114
|
+
if (review === undefined && wake === undefined)
|
|
115
|
+
return bad('nothing to change');
|
|
116
|
+
actions.setSchedule({ ...(review === undefined ? {} : { review: review }), ...(wake === undefined ? {} : { wake: wake }) });
|
|
117
|
+
return ok();
|
|
118
|
+
}
|
|
84
119
|
case '/console/workspace-permission': {
|
|
85
120
|
if (!validWorkspacePermission(body?.permission))
|
|
86
121
|
return bad('工作区权限必须为非空字符串');
|
|
@@ -123,6 +158,14 @@ export async function handleConsole(sources, actions, request) {
|
|
|
123
158
|
return text === undefined ? { status: 404, body: { error: 'no diary for this date' } } : ok({ date, text });
|
|
124
159
|
}
|
|
125
160
|
case '/console/prompts': return ok(actions.prompts());
|
|
161
|
+
case '/console/memory/find': {
|
|
162
|
+
const input = memoryInput(url.searchParams, ['limit'], ['kinds']);
|
|
163
|
+
return memoryCall(sources.memoryFind && (() => sources.memoryFind(input)));
|
|
164
|
+
}
|
|
165
|
+
case '/console/memory/read': {
|
|
166
|
+
const input = memoryInput(url.searchParams, ['offset', 'limit'], []);
|
|
167
|
+
return memoryCall(sources.memoryRead && (() => sources.memoryRead(input)));
|
|
168
|
+
}
|
|
126
169
|
case '/console/photos': {
|
|
127
170
|
const limit = Number(url.searchParams.get('limit') ?? 20), offset = Number(url.searchParams.get('offset') ?? 0);
|
|
128
171
|
if (!Number.isSafeInteger(limit) || limit < 1 || limit > 100 || !Number.isSafeInteger(offset) || offset < 0)
|
|
@@ -8,6 +8,8 @@ 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 { DailySchedule } from '../life/types.ts';
|
|
12
|
+
import type { MemoryService } from '../memory.ts';
|
|
11
13
|
export declare function estimateTokens(text: string): number;
|
|
12
14
|
export interface SnapshotDeps {
|
|
13
15
|
ctx: Context;
|
|
@@ -20,6 +22,8 @@ export interface SnapshotDeps {
|
|
|
20
22
|
life(): LifeRuntime | undefined;
|
|
21
23
|
homeApply?(): HomeApplyState;
|
|
22
24
|
photos?(): PhotoStore;
|
|
25
|
+
/** Long-term memory: the console's lookups and the health of its index. */
|
|
26
|
+
longTerm?: MemoryService;
|
|
23
27
|
diaryDir: string;
|
|
24
28
|
running(): boolean;
|
|
25
29
|
/** CNY a day for her home; undefined is no limit. */
|
|
@@ -28,6 +32,10 @@ export interface SnapshotDeps {
|
|
|
28
32
|
memoryTurns(): number;
|
|
29
33
|
selectedArchiveScope?(): MemoryArchiveScope;
|
|
30
34
|
compactAfterReview?(): boolean;
|
|
35
|
+
/** The evening look back and the morning wake, with what an empty field goes back to; absent without the life line. */
|
|
36
|
+
schedule?(): DailySchedule & {
|
|
37
|
+
defaults: DailySchedule;
|
|
38
|
+
};
|
|
31
39
|
workspacePermissions?(): {
|
|
32
40
|
defaultPermission: string;
|
|
33
41
|
options: {
|
package/lib/console/snapshot.js
CHANGED
|
@@ -16,7 +16,7 @@ export function consoleSources(deps) {
|
|
|
16
16
|
const life = deps.life()?.snapshot();
|
|
17
17
|
const home = life?.homeSessionId ? deps.ctx.agents.get(SessionId(life.homeSessionId)) : undefined;
|
|
18
18
|
const window = deps.memoryTurns();
|
|
19
|
-
const turns = await history.loadRecentTurns(
|
|
19
|
+
const turns = await history.loadRecentTurns(window, deps.archiveSession);
|
|
20
20
|
const archiveScope = config.archiveScope ?? 'workspace';
|
|
21
21
|
const selectedArchiveScope = deps.selectedArchiveScope?.() ?? archiveScope;
|
|
22
22
|
// Never let a dead bridge take the whole console down with it: a broken QQ module shows as "not running".
|
|
@@ -27,10 +27,11 @@ export function consoleSources(deps) {
|
|
|
27
27
|
budget: { daily: deps.dailyBudget() ?? null, today: life?.spend ?? null },
|
|
28
28
|
workspace: deps.workspacePermissions?.() ?? null,
|
|
29
29
|
compactAfterReview: deps.compactAfterReview?.() ?? null,
|
|
30
|
+
schedule: deps.schedule?.() ?? null,
|
|
30
31
|
life: life ? { homeSessionId: life.homeSessionId, status: home ? home.status : 'cold', alarm: life.alarm, review: life.review, recentWakes: lifeStore?.wakes().slice(-5).reverse() ?? [] } : null,
|
|
31
32
|
homeApply: deps.homeApply?.() ?? null,
|
|
32
33
|
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() },
|
|
34
|
+
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
35
|
wechat: deps.wechat?.() ?? null,
|
|
35
36
|
compactions: lifeStore?.compactions().slice(-5).reverse() ?? [],
|
|
36
37
|
diaryDates: diary.dates(), activityDays: lifeStore?.activityDays() ?? [],
|
|
@@ -55,5 +56,6 @@ export function consoleSources(deps) {
|
|
|
55
56
|
photos: (limit, offset) => { if (!deps.photos)
|
|
56
57
|
throw new Error('相册不可用'); return deps.photos().list(limit, offset); },
|
|
57
58
|
photo: id => deps.photos?.().image(id),
|
|
59
|
+
...(deps.longTerm ? { memoryFind: (input) => deps.longTerm.find(input), memoryRead: (input) => deps.longTerm.read(input) } : {}),
|
|
58
60
|
};
|
|
59
61
|
}
|
|
@@ -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
|
+
}
|
|
@@ -8,7 +8,7 @@ import type { ConsoleDoors } from './panel.ts';
|
|
|
8
8
|
* GET /dsh-world/qq/console SnowLuma's console address, with a session token already traded for the
|
|
9
9
|
* panel password
|
|
10
10
|
* Write: POST /dsh-world/qq/native { autoReply?, bridge?: { port? }, mutedUntil?, allowPrivate?, allowGroups?,
|
|
11
|
-
* startSnowluma? } the channel's switches, applied together; a new bridge
|
|
11
|
+
* batchQuietMs?, startSnowluma? } the channel's switches, applied together; a new bridge
|
|
12
12
|
* port restarts the balcony on the spot
|
|
13
13
|
* POST /dsh-world/qq/panel-password { username, password } remembers SnowLuma's panel password and
|
|
14
14
|
* trades it for a session token right away
|
|
@@ -36,6 +36,7 @@ export interface NativePatch {
|
|
|
36
36
|
mutedUntil?: string | null;
|
|
37
37
|
allowPrivate?: string[];
|
|
38
38
|
allowGroups?: string[];
|
|
39
|
+
batchQuietMs?: number;
|
|
39
40
|
startSnowluma?: true;
|
|
40
41
|
}
|
|
41
42
|
type SetNative = (patch: NativePatch) => unknown;
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { jsonObject, knownHost, readBody, sendJson } from "../../http.js";
|
|
2
|
+
import { MAX_BATCH_MS } from "../qq-native/batch.js";
|
|
2
3
|
/**
|
|
3
4
|
* The QQ module's few doors, on the same webServer as the console. The `/dsh-world/qq` prefix is never eaten
|
|
4
5
|
* by the console's `/dsh-world` prefix (the host matches the longer one first).
|
|
@@ -7,7 +8,7 @@ import { jsonObject, knownHost, readBody, sendJson } from "../../http.js";
|
|
|
7
8
|
* GET /dsh-world/qq/console SnowLuma's console address, with a session token already traded for the
|
|
8
9
|
* panel password
|
|
9
10
|
* Write: POST /dsh-world/qq/native { autoReply?, bridge?: { port? }, mutedUntil?, allowPrivate?, allowGroups?,
|
|
10
|
-
* startSnowluma? } the channel's switches, applied together; a new bridge
|
|
11
|
+
* batchQuietMs?, startSnowluma? } the channel's switches, applied together; a new bridge
|
|
11
12
|
* port restarts the balcony on the spot
|
|
12
13
|
* POST /dsh-world/qq/panel-password { username, password } remembers SnowLuma's panel password and
|
|
13
14
|
* trades it for a session token right away
|
|
@@ -70,6 +71,13 @@ async function write(doors, path, body, setNative) {
|
|
|
70
71
|
return bad('mutedUntil 要是能解析的 ISO 时间,或者 null');
|
|
71
72
|
patch.mutedUntil = until === null || !until.trim() ? null : until.trim();
|
|
72
73
|
}
|
|
74
|
+
// 合批窗口:同一个人在这么多毫秒内连发几句,合成一次问。给 0 就是每句单独回;一批从第一句起最多等 MAX_BATCH_MS,再长也没用。
|
|
75
|
+
if (body?.batchQuietMs !== undefined) {
|
|
76
|
+
const ms = body.batchQuietMs;
|
|
77
|
+
if (typeof ms !== 'number' || !Number.isInteger(ms) || ms < 0 || ms > MAX_BATCH_MS)
|
|
78
|
+
return bad(`batchQuietMs 要是 0 到 ${MAX_BATCH_MS} 之间的整数(毫秒)`);
|
|
79
|
+
patch.batchQuietMs = ms;
|
|
80
|
+
}
|
|
73
81
|
if (body?.startSnowluma === true)
|
|
74
82
|
patch.startSnowluma = true;
|
|
75
83
|
// 阳台:外面那条线开在哪个端口。换端口会打断已经连上的线,所以只认一个整数,别的一律拒。
|
|
@@ -85,7 +93,7 @@ async function write(doors, path, body, setNative) {
|
|
|
85
93
|
patch.bridge = { port };
|
|
86
94
|
}
|
|
87
95
|
if (!Object.keys(patch).length)
|
|
88
|
-
return bad('autoReply、bridge、mutedUntil、allowPrivate、allowGroups、startSnowluma 至少要给一个');
|
|
96
|
+
return bad('autoReply、bridge、mutedUntil、allowPrivate、allowGroups、batchQuietMs、startSnowluma 至少要给一个');
|
|
89
97
|
return ok(setNative(patch));
|
|
90
98
|
}
|
|
91
99
|
case '/open': {
|
|
@@ -3,6 +3,8 @@
|
|
|
3
3
|
* row, and asking her each half sentence on its own costs a turn apiece. The quiet window restarts with every
|
|
4
4
|
* message but never stretches past `maxMs` from the first, so a busy group still gets its answer.
|
|
5
5
|
*/
|
|
6
|
+
/** The longest a batch waits from its first message, so a quiet window past it changes nothing. */
|
|
7
|
+
export declare const MAX_BATCH_MS = 30000;
|
|
6
8
|
export declare function createBatcher<T>(options: {
|
|
7
9
|
quietMs(): number;
|
|
8
10
|
maxMs?: number;
|
|
@@ -3,8 +3,10 @@
|
|
|
3
3
|
* row, and asking her each half sentence on its own costs a turn apiece. The quiet window restarts with every
|
|
4
4
|
* message but never stretches past `maxMs` from the first, so a busy group still gets its answer.
|
|
5
5
|
*/
|
|
6
|
+
/** The longest a batch waits from its first message, so a quiet window past it changes nothing. */
|
|
7
|
+
export const MAX_BATCH_MS = 30_000;
|
|
6
8
|
export function createBatcher(options) {
|
|
7
|
-
const maxMs = options.maxMs ??
|
|
9
|
+
const maxMs = options.maxMs ?? MAX_BATCH_MS;
|
|
8
10
|
const open = new Map();
|
|
9
11
|
return {
|
|
10
12
|
add(key, item) {
|
|
@@ -73,6 +73,8 @@ export interface QqNativeStatus {
|
|
|
73
73
|
groupTrigger: 'mention' | 'all';
|
|
74
74
|
/** 静默到什么时候;没在静默就是 null。 */
|
|
75
75
|
mutedUntil: string | null;
|
|
76
|
+
/** 同一个人连发几句合成一次问的窗口(毫秒)。 */
|
|
77
|
+
batchQuietMs: number;
|
|
76
78
|
supervisor: SnowlumaStatus;
|
|
77
79
|
/** 这次请求按下「拉起 SnowLuma」的结果。 */
|
|
78
80
|
launch?: StartResult;
|