dsh-world 0.7.2 → 0.7.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +403 -379
- package/INSTALL.md +314 -314
- package/LICENSE +21 -21
- package/NOTES.md +23 -13
- package/README.md +22 -7
- package/client/index.js +74 -27
- package/cordis.patch.yml +6 -6
- package/lib/archiveSelection.d.ts +6 -2
- package/lib/archiveSelection.js +21 -12
- package/lib/compaction.d.ts +7 -0
- package/lib/compaction.js +18 -9
- package/lib/compactionSwap.d.ts +17 -0
- package/lib/compactionSwap.js +68 -6
- package/lib/console/routes.d.ts +2 -3
- package/lib/console/routes.js +7 -8
- package/lib/console/snapshot.d.ts +1 -3
- package/lib/console/snapshot.js +0 -3
- package/lib/ecosystem/bridge/bridge.d.ts +5 -0
- package/lib/ecosystem/bridge/bridge.js +2 -1
- package/lib/ecosystem/bridge/route.d.ts +4 -6
- package/lib/ecosystem/bridge/route.js +34 -58
- package/lib/ecosystem/qq/panel.d.ts +0 -1
- package/lib/ecosystem/qq/route.d.ts +6 -7
- package/lib/ecosystem/qq/route.js +10 -10
- package/lib/ecosystem/qq/snowluma-start.d.ts +1 -0
- package/lib/ecosystem/qq/snowluma-start.js +41 -8
- package/lib/ecosystem/qq/supervisor.d.ts +1 -2
- package/lib/ecosystem/qq/supervisor.js +4 -2
- package/lib/ecosystem/qq-native/index.js +2 -0
- package/lib/ecosystem/qq-native/native-bridge.d.ts +0 -1
- package/lib/ecosystem/qq-native/native-bridge.js +0 -2
- package/lib/ecosystem/qq-native/snowluma.js +11 -2
- package/lib/ecosystem/shared/turn.d.ts +3 -0
- package/lib/ecosystem/shared/turn.js +9 -2
- package/lib/ecosystem/wechat/home.d.ts +3 -0
- package/lib/ecosystem/wechat/home.js +12 -4
- package/lib/ecosystem/wechat/index.d.ts +0 -1
- package/lib/ecosystem/wechat/index.js +9 -6
- package/lib/hostContract.d.ts +19 -0
- package/lib/index.js +117 -49
- package/lib/life/toolRegistry.js +2 -2
- package/lib/memoryFiles.d.ts +0 -1
- package/lib/memoryStore.d.ts +0 -1
- package/lib/memoryStore.js +0 -1
- package/lib/memoryTools.d.ts +0 -1
- package/lib/memoryTools.js +2 -3
- package/lib/mood.d.ts +28 -0
- package/lib/mood.js +69 -0
- package/lib/promptSection.d.ts +7 -5
- package/lib/promptSection.js +74 -28
- package/lib/runtime.d.ts +6 -2
- package/lib/runtime.js +163 -26
- package/lib/self.d.ts +1 -1
- package/lib/self.js +1 -1
- package/lib/sourceArchive.d.ts +4 -2
- package/lib/sourceArchive.js +18 -4
- package/lib/store.js +2 -1
- package/lib/types.d.ts +3 -1
- package/lib/worldPrompt.d.ts +2 -3
- package/lib/worldPrompt.js +2 -3
- package/lib/worldRoutes.d.ts +9 -0
- package/lib/worldRoutes.js +29 -0
- package/lib/worldScope.d.ts +5 -5
- package/lib/worldScope.js +16 -7
- package/lib/worldSwitch.d.ts +1 -2
- package/lib/worldSwitch.js +1 -1
- package/package.json +17 -16
- package/scripts/compact-home.mjs +29 -29
- package/scripts/enable-tool-free-compaction.ps1 +33 -33
- package/scripts/import-stickers.mjs +17 -17
- package/scripts/update-world.mjs +2 -2
- package/src/ecosystem/README.md +1 -1
- package/src/ecosystem/wechat/windows/README.md +3 -3
- package/src/ecosystem/wechat/windows/adapter.py +21 -3
- package/src/ecosystem/wechat/windows/engine/profiles.json +142 -142
- package/src/ecosystem/wechat/windows/presence.py +109 -109
- package/templates/alarm.md +2 -2
- package/templates/world-prompt.md +11 -2
package/lib/compactionSwap.d.ts
CHANGED
|
@@ -26,6 +26,11 @@ export declare function swapPresetConfig(config: unknown): {
|
|
|
26
26
|
export interface ConfigEditor {
|
|
27
27
|
entries(): ConfigEntry[];
|
|
28
28
|
edit(entry: ConfigEntry, change: (raw: unknown, inherited: unknown) => unknown): Promise<void>;
|
|
29
|
+
/** Each row with the value DSH itself supplies beneath the profile's override (DSH 0.2.2 on). */
|
|
30
|
+
configuration?(): {
|
|
31
|
+
entry: ConfigEntry;
|
|
32
|
+
inherited: unknown;
|
|
33
|
+
}[];
|
|
29
34
|
}
|
|
30
35
|
interface ConfigEntry {
|
|
31
36
|
options: {
|
|
@@ -40,6 +45,18 @@ interface ConfigEntry {
|
|
|
40
45
|
* with only the compaction row changed. That copy no longer follows later DSH updates to the preset.
|
|
41
46
|
*/
|
|
42
47
|
export declare function swapPresetCompaction(editor: ConfigEditor, presetId: string, profileDir: string): Promise<CompactionSwap>;
|
|
48
|
+
/** The copied preset without the rows DSH itself no longer ships, or undefined when there is nothing to drop; the input is not changed. */
|
|
49
|
+
export declare function dropRetiredRows(config: unknown, inherited: unknown): unknown;
|
|
50
|
+
/**
|
|
51
|
+
* On every start, drops the retired rows from each preset copied into the profile, with a backup of the profile patch
|
|
52
|
+
* first. Only a row DSH no longer ships beneath the copy goes, so the same copy on DSH 0.2.1 is left alone. The editor
|
|
53
|
+
* reloads the row; sessions that already failed to resume come back after a DSH restart.
|
|
54
|
+
*/
|
|
55
|
+
export declare function repairCopiedPresets(deps: {
|
|
56
|
+
editor: ConfigEditor;
|
|
57
|
+
profileDir: string;
|
|
58
|
+
report(message: string): void;
|
|
59
|
+
}): Promise<void>;
|
|
43
60
|
/**
|
|
44
61
|
* Once per world, when the plugin first runs in a profile: make the profile use the tool-free compaction. The attempt is
|
|
45
62
|
* remembered only when it succeeded or was already done, so a partner who later puts the stock one back is left alone,
|
package/lib/compactionSwap.js
CHANGED
|
@@ -38,22 +38,39 @@ export function swapStockCompaction(profileDir) {
|
|
|
38
38
|
}
|
|
39
39
|
return { status: 'swapped', backup };
|
|
40
40
|
}
|
|
41
|
-
/** The
|
|
42
|
-
function
|
|
41
|
+
/** The rows of a preset's plugin list that match, including those nested in groups (where DSH's Web host isolates compaction). */
|
|
42
|
+
function rowsWhere(rows, match, found = []) {
|
|
43
43
|
if (!Array.isArray(rows))
|
|
44
44
|
return found;
|
|
45
45
|
for (const row of rows) {
|
|
46
|
-
if (row
|
|
46
|
+
if (row && match(row))
|
|
47
47
|
found.push(row);
|
|
48
48
|
if (row?.group)
|
|
49
|
-
|
|
49
|
+
rowsWhere(row.config, match, found);
|
|
50
50
|
}
|
|
51
51
|
return found;
|
|
52
52
|
}
|
|
53
|
+
/** Removes the matching rows in place, groups included, and says how many went. */
|
|
54
|
+
function removeRows(rows, match) {
|
|
55
|
+
if (!Array.isArray(rows))
|
|
56
|
+
return 0;
|
|
57
|
+
let removed = 0;
|
|
58
|
+
for (let index = rows.length - 1; index >= 0; index--) {
|
|
59
|
+
const row = rows[index];
|
|
60
|
+
if (row && match(row)) {
|
|
61
|
+
rows.splice(index, 1);
|
|
62
|
+
removed++;
|
|
63
|
+
}
|
|
64
|
+
else if (row?.group)
|
|
65
|
+
removed += removeRows(row.config, match);
|
|
66
|
+
}
|
|
67
|
+
return removed;
|
|
68
|
+
}
|
|
69
|
+
const isCompaction = (row) => row.name === STOCK || row.name === OURS;
|
|
53
70
|
/** The preset's config with its one stock compaction row renamed to ours; the input is not changed. */
|
|
54
71
|
export function swapPresetConfig(config) {
|
|
55
72
|
const next = structuredClone(config);
|
|
56
|
-
const rows =
|
|
73
|
+
const rows = rowsWhere(next?.plugins, isCompaction);
|
|
57
74
|
if (rows.some(row => row.name === OURS))
|
|
58
75
|
return { status: 'already' };
|
|
59
76
|
if (rows.length !== 1)
|
|
@@ -61,13 +78,14 @@ export function swapPresetConfig(config) {
|
|
|
61
78
|
rows[0].name = OURS;
|
|
62
79
|
return { status: 'swapped', config: next };
|
|
63
80
|
}
|
|
81
|
+
const PRESET = '@deepseek-ai/dsh-agent-preset';
|
|
64
82
|
/**
|
|
65
83
|
* DSH's Web host composes the stock compaction inside each preset, so the profile has no row to rename. The host's
|
|
66
84
|
* preset editor writes the whole preset into the profile when a partner edits it; this does the same for her preset
|
|
67
85
|
* with only the compaction row changed. That copy no longer follows later DSH updates to the preset.
|
|
68
86
|
*/
|
|
69
87
|
export async function swapPresetCompaction(editor, presetId, profileDir) {
|
|
70
|
-
const entry = editor.entries().find(row => row.options.name ===
|
|
88
|
+
const entry = editor.entries().find(row => row.options.name === PRESET && row.options.config?.id === presetId);
|
|
71
89
|
if (!entry)
|
|
72
90
|
return { status: 'unchanged', reason: `没有找到预设 ${presetId}` };
|
|
73
91
|
const first = swapPresetConfig(entry.options.config);
|
|
@@ -83,6 +101,50 @@ export async function swapPresetCompaction(editor, presetId, profileDir) {
|
|
|
83
101
|
});
|
|
84
102
|
return { status: 'swapped', backup: backup ?? '(原来没有 cordis.patch.yml)', preset: presetId };
|
|
85
103
|
}
|
|
104
|
+
// DSH 0.2.2 folded `list_agents` into the subagent-control package. A preset copied on 0.2.1 still names this row, and
|
|
105
|
+
// DSH then refuses to mount that whole preset, so no session using it can be resumed.
|
|
106
|
+
const RETIRED = '@deepseek-ai/dsh-tool-subagent-control/list-agents';
|
|
107
|
+
const isRetired = (row) => row.name === RETIRED;
|
|
108
|
+
/** The copied preset without the rows DSH itself no longer ships, or undefined when there is nothing to drop; the input is not changed. */
|
|
109
|
+
export function dropRetiredRows(config, inherited) {
|
|
110
|
+
if (rowsWhere(inherited?.plugins, isRetired).length)
|
|
111
|
+
return undefined;
|
|
112
|
+
const next = structuredClone(config);
|
|
113
|
+
return removeRows(next?.plugins, isRetired) ? next : undefined;
|
|
114
|
+
}
|
|
115
|
+
const presetId = (entry) => String(entry.options.config?.id ?? entry.options.id);
|
|
116
|
+
/**
|
|
117
|
+
* On every start, drops the retired rows from each preset copied into the profile, with a backup of the profile patch
|
|
118
|
+
* first. Only a row DSH no longer ships beneath the copy goes, so the same copy on DSH 0.2.1 is left alone. The editor
|
|
119
|
+
* reloads the row; sessions that already failed to resume come back after a DSH restart.
|
|
120
|
+
*/
|
|
121
|
+
export async function repairCopiedPresets(deps) {
|
|
122
|
+
const repaired = [];
|
|
123
|
+
let backup = '(原来没有 cordis.patch.yml)';
|
|
124
|
+
try {
|
|
125
|
+
const broken = (deps.editor.configuration?.() ?? []).filter(({ entry, inherited }) => entry.options.name === PRESET && dropRetiredRows(entry.options.config, inherited) !== undefined);
|
|
126
|
+
if (!broken.length)
|
|
127
|
+
return;
|
|
128
|
+
const file = join(deps.profileDir, 'cordis.patch.yml');
|
|
129
|
+
if (existsSync(file))
|
|
130
|
+
backup = backupBeside(file);
|
|
131
|
+
for (const { entry } of broken) {
|
|
132
|
+
await deps.editor.edit(entry, (raw, inherited) => {
|
|
133
|
+
const next = dropRetiredRows(raw, inherited);
|
|
134
|
+
if (next === undefined)
|
|
135
|
+
throw new Error(`预设 ${presetId(entry)} 在写入前变了`);
|
|
136
|
+
return next;
|
|
137
|
+
});
|
|
138
|
+
repaired.push(presetId(entry));
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
catch (error) {
|
|
142
|
+
const done = repaired.length ? `已修好预设 ${repaired.join('、')};` : '';
|
|
143
|
+
deps.report(`${done}没能删掉 profile 预设里 DSH 已不再提供的 list-agents 那一行:${error instanceof Error ? error.message : String(error)}。用这个预设的会话会打不开,可以退出 DSH 后在 cordis.patch.yml 里手动删掉 ${RETIRED} 那一行(原文件备份在 ${backup})。`);
|
|
144
|
+
return;
|
|
145
|
+
}
|
|
146
|
+
deps.report(`已从 profile 里的预设 ${repaired.join('、')} 删掉 DSH 已不再提供的 list-agents 那一行(原文件备份在 ${backup})。重启 DSH 后,用这个预设的会话就能正常打开。`);
|
|
147
|
+
}
|
|
86
148
|
/**
|
|
87
149
|
* Once per world, when the plugin first runs in a profile: make the profile use the tool-free compaction. The attempt is
|
|
88
150
|
* remembered only when it succeeded or was already done, so a partner who later puts the stock one back is left alone,
|
package/lib/console/routes.d.ts
CHANGED
|
@@ -4,7 +4,6 @@ import { type Persona } from '../persona.ts';
|
|
|
4
4
|
import { type MemoryArchiveScope } from '../archiveSelection.ts';
|
|
5
5
|
import type { PhotoStore } from '../life/photos.ts';
|
|
6
6
|
import { type MemoryContent, type MemoryPage } from '../memory.ts';
|
|
7
|
-
export declare const CONSOLE_PREFIX = "/dsh-world";
|
|
8
7
|
/** A write must carry this header; a page on another site cannot add it without a CORS preflight, which is never answered. */
|
|
9
8
|
export declare const WRITE_HEADER = "x-dsh-world";
|
|
10
9
|
export interface ConsoleSources {
|
|
@@ -75,8 +74,8 @@ export interface ConsoleRequest {
|
|
|
75
74
|
body?: Record<string, unknown> | undefined;
|
|
76
75
|
}
|
|
77
76
|
/** Reads are open to the console page; writes need POST, the write header and a JSON body. */
|
|
78
|
-
export declare function handleConsole(sources: ConsoleSources, actions: ConsoleActions, request: ConsoleRequest): Promise<JsonResult>;
|
|
79
|
-
export declare function consoleRoute(sources: ConsoleSources, actions: ConsoleActions, allowedHosts?: readonly string[]): {
|
|
77
|
+
export declare function handleConsole(prefix: string, sources: ConsoleSources, actions: ConsoleActions, request: ConsoleRequest): Promise<JsonResult>;
|
|
78
|
+
export declare function consoleRoute(prefix: string, sources: ConsoleSources, actions: ConsoleActions, allowedHosts?: readonly string[]): {
|
|
80
79
|
kind: "prefix";
|
|
81
80
|
path: string;
|
|
82
81
|
handler: (req: IncomingMessage, res: ServerResponse) => Promise<void>;
|
package/lib/console/routes.js
CHANGED
|
@@ -4,7 +4,6 @@ import { validColdHours, validTurns, validWechatBuffer, MAX_COLD_HOURS, validWec
|
|
|
4
4
|
import { validArchiveScope } from "../archiveSelection.js";
|
|
5
5
|
import { validClockTime } from "../life/alarm.js";
|
|
6
6
|
import { MemoryError } from "../memory.js";
|
|
7
|
-
export const CONSOLE_PREFIX = '/dsh-world';
|
|
8
7
|
/** A write must carry this header; a page on another site cannot add it without a CORS preflight, which is never answered. */
|
|
9
8
|
export const WRITE_HEADER = 'x-dsh-world';
|
|
10
9
|
const MAX_BODY_BYTES = 64 * 1024;
|
|
@@ -144,11 +143,11 @@ async function write(actions, path, body) {
|
|
|
144
143
|
}
|
|
145
144
|
}
|
|
146
145
|
/** Reads are open to the console page; writes need POST, the write header and a JSON body. */
|
|
147
|
-
export async function handleConsole(sources, actions, request) {
|
|
146
|
+
export async function handleConsole(prefix, sources, actions, request) {
|
|
148
147
|
const url = new URL(request.url, 'http://localhost');
|
|
149
|
-
if (url.pathname !==
|
|
148
|
+
if (url.pathname !== prefix && !url.pathname.startsWith(prefix + '/'))
|
|
150
149
|
return { status: 404, body: { error: 'not found' } };
|
|
151
|
-
const path = url.pathname.slice(
|
|
150
|
+
const path = url.pathname.slice(prefix.length);
|
|
152
151
|
if (request.method === 'POST') {
|
|
153
152
|
if (!request.write)
|
|
154
153
|
return { status: 403, body: { error: 'forbidden' } };
|
|
@@ -182,9 +181,9 @@ export async function handleConsole(sources, actions, request) {
|
|
|
182
181
|
default: return { status: 404, body: { error: 'not found' } };
|
|
183
182
|
}
|
|
184
183
|
}
|
|
185
|
-
export function consoleRoute(sources, actions, allowedHosts = []) {
|
|
184
|
+
export function consoleRoute(prefix, sources, actions, allowedHosts = []) {
|
|
186
185
|
return {
|
|
187
|
-
kind: 'prefix', path:
|
|
186
|
+
kind: 'prefix', path: prefix,
|
|
188
187
|
handler: async (req, res) => {
|
|
189
188
|
let result;
|
|
190
189
|
try {
|
|
@@ -193,7 +192,7 @@ export function consoleRoute(sources, actions, allowedHosts = []) {
|
|
|
193
192
|
else {
|
|
194
193
|
const method = req.method ?? 'GET';
|
|
195
194
|
const url = new URL(req.url ?? '/', 'http://localhost');
|
|
196
|
-
if (method === 'GET' && url.pathname ===
|
|
195
|
+
if (method === 'GET' && url.pathname === prefix + '/console/photo') {
|
|
197
196
|
const image = sources.photo?.(url.searchParams.get('id') ?? '');
|
|
198
197
|
if (!image) {
|
|
199
198
|
sendJson(res, { status: 404, body: { error: '找不到这张照片' } });
|
|
@@ -205,7 +204,7 @@ export function consoleRoute(sources, actions, allowedHosts = []) {
|
|
|
205
204
|
}
|
|
206
205
|
const write = method === 'POST' && req.headers[WRITE_HEADER] === '1' && String(req.headers['content-type'] ?? '').startsWith('application/json');
|
|
207
206
|
const body = write ? jsonObject(await readBody(req, MAX_BODY_BYTES)) : undefined;
|
|
208
|
-
result = write && body === undefined ? bad('a JSON object body is required') : await handleConsole(sources, actions, { method, url: req.url ?? '/', write, body });
|
|
207
|
+
result = write && body === undefined ? bad('a JSON object body is required') : await handleConsole(prefix, sources, actions, { method, url: req.url ?? '/', write, body });
|
|
209
208
|
}
|
|
210
209
|
}
|
|
211
210
|
catch {
|
|
@@ -50,14 +50,12 @@ export interface SnapshotDeps {
|
|
|
50
50
|
wechat?(): unknown;
|
|
51
51
|
/** Whose conversations her archive keeps; the memory block shown is read through it. */
|
|
52
52
|
archiveSession?(id: string): boolean;
|
|
53
|
-
/** Faults outside the life line: the memory line, the bridge,
|
|
53
|
+
/** Faults outside the life line: the memory line, the bridge, starting and stopping. */
|
|
54
54
|
faults(): string[];
|
|
55
55
|
/** Which modules the config allows, whether their console switch is on, and whether they are running now. */
|
|
56
56
|
modules?(): unknown;
|
|
57
57
|
/** The OneBot channel she runs herself; null while it is off. */
|
|
58
58
|
native?(): unknown;
|
|
59
|
-
/** The QQ bridge, when the module is on; absent leaves that card out of the console. */
|
|
60
|
-
qq?: () => Promise<unknown>;
|
|
61
59
|
}
|
|
62
60
|
/** Read-only views for the console; repeated polling within a few seconds reuses one snapshot until `invalidate`. */
|
|
63
61
|
export declare function consoleSources(deps: SnapshotDeps): ConsoleSources & {
|
package/lib/console/snapshot.js
CHANGED
|
@@ -19,8 +19,6 @@ export function consoleSources(deps) {
|
|
|
19
19
|
const turns = await history.loadRecentTurns(window, deps.archiveSession);
|
|
20
20
|
const archiveScope = config.archiveScope ?? 'workspace';
|
|
21
21
|
const selectedArchiveScope = deps.selectedArchiveScope?.() ?? archiveScope;
|
|
22
|
-
// Never let a dead bridge take the whole console down with it: a broken QQ module shows as "not running".
|
|
23
|
-
const qq = deps.qq ? await deps.qq().catch(() => null) : null;
|
|
24
22
|
const native = deps.native?.() ?? null;
|
|
25
23
|
return {
|
|
26
24
|
worldId: config.worldId, timeZone: config.timeZone, now: new Date().toISOString(), running: deps.running(), name: deps.names().companion,
|
|
@@ -35,7 +33,6 @@ export function consoleSources(deps) {
|
|
|
35
33
|
wechat: deps.wechat?.() ?? null,
|
|
36
34
|
compactions: lifeStore?.compactions().slice(-5).reverse() ?? [],
|
|
37
35
|
diaryDates: diary.dates(), activityDays: lifeStore?.activityDays() ?? [],
|
|
38
|
-
qq: deps.qq ? qq : null,
|
|
39
36
|
native,
|
|
40
37
|
modules: deps.modules?.() ?? null,
|
|
41
38
|
};
|
|
@@ -3,12 +3,17 @@ import type { Agent } from '@deepseek-ai/dsh-agent';
|
|
|
3
3
|
import { type LifeTimers } from '../../life/alarmTimer.ts';
|
|
4
4
|
import { type Outlet } from '../shared/outlets.ts';
|
|
5
5
|
import { type InWorld } from '../../worldScope.ts';
|
|
6
|
+
export declare const bridgePaths: (prefix: string) => {
|
|
7
|
+
sayPath: string;
|
|
8
|
+
compactPath: string;
|
|
9
|
+
};
|
|
6
10
|
export declare const REPLY_TIMEOUT_MS: number;
|
|
7
11
|
/** The words could not be handed to her home; the route answers 503. */
|
|
8
12
|
export declare class HomeUnavailable extends Error {
|
|
9
13
|
}
|
|
10
14
|
export interface BridgeDeps {
|
|
11
15
|
ctx: Context;
|
|
16
|
+
prefix: string;
|
|
12
17
|
/** The current home, resolving or rebuilding it (the life line's own). */
|
|
13
18
|
home(): Promise<Agent>;
|
|
14
19
|
inWorld?: InWorld;
|
|
@@ -6,6 +6,7 @@ import { errorText, Faults } from "../../faults.js";
|
|
|
6
6
|
import { realTimers } from "../../life/alarmTimer.js";
|
|
7
7
|
import { busyText, pushOf } from "../shared/outlets.js";
|
|
8
8
|
import { admit } from "../../worldScope.js";
|
|
9
|
+
export const bridgePaths = (prefix) => ({ sayPath: prefix + '/bridge/say', compactPath: prefix + '/bridge/compact' });
|
|
9
10
|
export const REPLY_TIMEOUT_MS = 3 * 60_000;
|
|
10
11
|
/** The words could not be handed to her home; the route answers 503. */
|
|
11
12
|
export class HomeUnavailable extends Error {
|
|
@@ -69,7 +70,7 @@ export function createBridge(deps) {
|
|
|
69
70
|
send(reply);
|
|
70
71
|
}));
|
|
71
72
|
try {
|
|
72
|
-
durableWrite(deps.file, JSON.stringify({ origin: deps.origin(), token, pid: process.pid, startedAt: clock().toISOString(), name }, null, 2));
|
|
73
|
+
durableWrite(deps.file, JSON.stringify({ origin: deps.origin(), ...bridgePaths(deps.prefix), token, pid: process.pid, startedAt: clock().toISOString(), name }, null, 2));
|
|
73
74
|
faults.clear('file');
|
|
74
75
|
}
|
|
75
76
|
catch (error) {
|
|
@@ -1,15 +1,13 @@
|
|
|
1
1
|
import type { IncomingMessage, ServerResponse } from 'node:http';
|
|
2
2
|
import { type Bridge } from './bridge.ts';
|
|
3
|
-
|
|
4
|
-
export declare
|
|
5
|
-
/** The one outside route that changes something: a local app hands her partner's words to her home. */
|
|
6
|
-
export declare function bridgeRoute(bridge: () => Bridge | undefined, allowedHosts?: readonly string[]): {
|
|
3
|
+
/** A local app hands her partner's words to her home. */
|
|
4
|
+
export declare function bridgeRoute(prefix: string, bridge: () => Bridge | undefined, allowedHosts?: readonly string[]): {
|
|
7
5
|
kind: "exact";
|
|
8
6
|
path: string;
|
|
9
7
|
handler: (req: IncomingMessage, res: ServerResponse) => Promise<void>;
|
|
10
8
|
};
|
|
11
|
-
/** Asks for one compaction of her home, held behind her running turn
|
|
12
|
-
export declare function compactRoute(bridge: () => Bridge | undefined, request: () => string | undefined, allowedHosts?: readonly string[]): {
|
|
9
|
+
/** Asks for one compaction of her home, held behind her running turn. */
|
|
10
|
+
export declare function compactRoute(prefix: string, bridge: () => Bridge | undefined, request: () => string | undefined, allowedHosts?: readonly string[]): {
|
|
13
11
|
kind: "exact";
|
|
14
12
|
path: string;
|
|
15
13
|
handler: (req: IncomingMessage, res: ServerResponse) => Promise<void>;
|
|
@@ -1,76 +1,52 @@
|
|
|
1
1
|
import { jsonObject, knownHost, readBody, sendJson } from "../../http.js";
|
|
2
|
-
import { HomeUnavailable } from "./bridge.js";
|
|
3
|
-
export const BRIDGE_PATH = '/dsh-world/bridge/say';
|
|
4
|
-
export const COMPACT_PATH = '/dsh-world/bridge/compact';
|
|
2
|
+
import { bridgePaths, HomeUnavailable } from "./bridge.js";
|
|
5
3
|
const MAX_BODY_BYTES = 32 * 1024;
|
|
6
4
|
const MAX_TEXT = 2000;
|
|
7
5
|
const bad = { status: 400, body: { error: 'bad request' } };
|
|
8
6
|
const unavailable = { status: 503, body: { error: 'home unavailable' } };
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
const length = [...text].length;
|
|
23
|
-
if (length < 1 || length > MAX_TEXT)
|
|
24
|
-
return bad;
|
|
25
|
-
try {
|
|
26
|
-
return { status: 202, body: { accepted: true, id: (await bridge.say(text)).id } };
|
|
7
|
+
function bridgePost(path, bridge, allowedHosts, action) {
|
|
8
|
+
async function handle(req) {
|
|
9
|
+
if (req.method !== 'POST')
|
|
10
|
+
return { status: 405, body: { error: 'method not allowed' }, headers: { allow: 'POST' } };
|
|
11
|
+
if (req.headers['sec-fetch-site'] === 'cross-site' || !knownHost(req.headers.host, allowedHosts))
|
|
12
|
+
return { status: 403, body: { error: 'forbidden' } };
|
|
13
|
+
const current = bridge();
|
|
14
|
+
if (!current)
|
|
15
|
+
return unavailable;
|
|
16
|
+
const token = req.headers['x-dsh-world-token'];
|
|
17
|
+
if (!current.checkToken(typeof token === 'string' ? token : undefined))
|
|
18
|
+
return { status: 403, body: { error: 'forbidden' } };
|
|
19
|
+
return action(current, req);
|
|
27
20
|
}
|
|
28
|
-
catch (error) {
|
|
29
|
-
return error instanceof HomeUnavailable ? unavailable : { status: 500, body: { error: 'internal error' } };
|
|
30
|
-
}
|
|
31
|
-
}
|
|
32
|
-
/** The one outside route that changes something: a local app hands her partner's words to her home. */
|
|
33
|
-
export function bridgeRoute(bridge, allowedHosts = []) {
|
|
34
21
|
return {
|
|
35
|
-
kind: 'exact', path
|
|
22
|
+
kind: 'exact', path,
|
|
36
23
|
handler: async (req, res) => {
|
|
37
24
|
let result;
|
|
38
25
|
try {
|
|
39
|
-
result = await
|
|
26
|
+
result = await handle(req);
|
|
40
27
|
}
|
|
41
|
-
catch {
|
|
42
|
-
result = { status: 500, body: { error: 'internal error' } };
|
|
28
|
+
catch (error) {
|
|
29
|
+
result = error instanceof HomeUnavailable ? unavailable : { status: 500, body: { error: 'internal error' } };
|
|
43
30
|
}
|
|
44
31
|
sendJson(res, result);
|
|
45
32
|
},
|
|
46
33
|
};
|
|
47
34
|
}
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
const refused = request();
|
|
59
|
-
return refused ? { status: 409, body: { error: refused } } : { status: 202, body: { accepted: true } };
|
|
35
|
+
/** A local app hands her partner's words to her home. */
|
|
36
|
+
export function bridgeRoute(prefix, bridge, allowedHosts = []) {
|
|
37
|
+
return bridgePost(bridgePaths(prefix).sayPath, bridge, allowedHosts, async (current, req) => {
|
|
38
|
+
const body = jsonObject(await readBody(req, MAX_BODY_BYTES));
|
|
39
|
+
const text = typeof body?.text === 'string' ? body.text.trim() : '';
|
|
40
|
+
const length = [...text].length;
|
|
41
|
+
if (length < 1 || length > MAX_TEXT)
|
|
42
|
+
return bad;
|
|
43
|
+
return { status: 202, body: { accepted: true, id: (await current.say(text)).id } };
|
|
44
|
+
});
|
|
60
45
|
}
|
|
61
|
-
/** Asks for one compaction of her home, held behind her running turn
|
|
62
|
-
export function compactRoute(bridge, request, allowedHosts = []) {
|
|
63
|
-
return {
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
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
|
-
};
|
|
46
|
+
/** Asks for one compaction of her home, held behind her running turn. */
|
|
47
|
+
export function compactRoute(prefix, bridge, request, allowedHosts = []) {
|
|
48
|
+
return bridgePost(bridgePaths(prefix).compactPath, bridge, allowedHosts, () => {
|
|
49
|
+
const refused = request();
|
|
50
|
+
return refused ? { status: 409, body: { error: refused } } : { status: 202, body: { accepted: true } };
|
|
51
|
+
});
|
|
76
52
|
}
|
|
@@ -41,7 +41,6 @@ export declare function createPanelSecrets(worldDir: string): {
|
|
|
41
41
|
remember(username: string, password: string): void;
|
|
42
42
|
forget(): void;
|
|
43
43
|
};
|
|
44
|
-
export type PanelSecrets = ReturnType<typeof createPanelSecrets>;
|
|
45
44
|
/** Trades the panel password for a session token and hands back a URL that opens already logged in. */
|
|
46
45
|
export declare function loginSnowluma(base: string, username: string, password: string, fetchImpl?: typeof fetch): Promise<PanelResult>;
|
|
47
46
|
/** The door the QQ card's button knocks on. */
|
|
@@ -1,16 +1,16 @@
|
|
|
1
1
|
import type { IncomingMessage, ServerResponse } from 'node:http';
|
|
2
2
|
import type { ConsoleDoors } from './panel.ts';
|
|
3
3
|
/**
|
|
4
|
-
* The QQ module's few doors, on the same webServer as the console. The
|
|
4
|
+
* The QQ module's few doors, on the same webServer as the console. The `…/qq` prefix is never eaten
|
|
5
5
|
* by the console's `/dsh-world` prefix (the host matches the longer one first).
|
|
6
6
|
*
|
|
7
|
-
* Read: GET
|
|
8
|
-
* GET
|
|
7
|
+
* Read: GET …/qq/native her own OneBot channel: is it connected, what has it seen, is it replying
|
|
8
|
+
* GET …/qq/console SnowLuma's console address, with a session token already traded for the
|
|
9
9
|
* panel password
|
|
10
|
-
* Write: POST
|
|
10
|
+
* Write: POST …/qq/native { autoReply?, bridge?: { port? }, mutedUntil?, allowPrivate?, allowGroups?,
|
|
11
11
|
* batchQuietMs?, startSnowluma? } the channel's switches, applied together; a new bridge
|
|
12
12
|
* port restarts the balcony on the spot
|
|
13
|
-
* POST
|
|
13
|
+
* POST …/qq/panel-password { username, password } remembers SnowLuma's panel password and
|
|
14
14
|
* trades it for a session token right away
|
|
15
15
|
*
|
|
16
16
|
* Writes require the `x-dsh-world` header: a cross-site page cannot add it (that would trigger a preflight,
|
|
@@ -22,7 +22,6 @@ import type { ConsoleDoors } from './panel.ts';
|
|
|
22
22
|
* console door has nothing to do with it — which is why removing the bridge's config did not have to take
|
|
23
23
|
* this endpoint down with it.
|
|
24
24
|
*/
|
|
25
|
-
export declare const QQ_PREFIX = "/dsh-world/qq";
|
|
26
25
|
export declare const WRITE_HEADER = "x-dsh-world";
|
|
27
26
|
/**
|
|
28
27
|
* What the panel may change about her own channel: replying, the balcony's port, staying quiet until a time
|
|
@@ -40,7 +39,7 @@ export interface NativePatch {
|
|
|
40
39
|
startSnowluma?: true;
|
|
41
40
|
}
|
|
42
41
|
type SetNative = (patch: NativePatch) => unknown;
|
|
43
|
-
export declare function qqRoute(allowedHosts?: readonly string[], doors?: ConsoleDoors, native?: () => unknown, setNative?: SetNative): {
|
|
42
|
+
export declare function qqRoute(worldPrefix: string, allowedHosts?: readonly string[], doors?: ConsoleDoors, native?: () => unknown, setNative?: SetNative): {
|
|
44
43
|
kind: "prefix";
|
|
45
44
|
path: string;
|
|
46
45
|
handler: (req: IncomingMessage, res: ServerResponse) => Promise<void>;
|
|
@@ -1,16 +1,16 @@
|
|
|
1
1
|
import { jsonObject, knownHost, readBody, sendJson } from "../../http.js";
|
|
2
2
|
import { MAX_BATCH_MS } from "../qq-native/batch.js";
|
|
3
3
|
/**
|
|
4
|
-
* The QQ module's few doors, on the same webServer as the console. The
|
|
4
|
+
* The QQ module's few doors, on the same webServer as the console. The `…/qq` prefix is never eaten
|
|
5
5
|
* by the console's `/dsh-world` prefix (the host matches the longer one first).
|
|
6
6
|
*
|
|
7
|
-
* Read: GET
|
|
8
|
-
* GET
|
|
7
|
+
* Read: GET …/qq/native her own OneBot channel: is it connected, what has it seen, is it replying
|
|
8
|
+
* GET …/qq/console SnowLuma's console address, with a session token already traded for the
|
|
9
9
|
* panel password
|
|
10
|
-
* Write: POST
|
|
10
|
+
* Write: POST …/qq/native { autoReply?, bridge?: { port? }, mutedUntil?, allowPrivate?, allowGroups?,
|
|
11
11
|
* batchQuietMs?, startSnowluma? } the channel's switches, applied together; a new bridge
|
|
12
12
|
* port restarts the balcony on the spot
|
|
13
|
-
* POST
|
|
13
|
+
* POST …/qq/panel-password { username, password } remembers SnowLuma's panel password and
|
|
14
14
|
* trades it for a session token right away
|
|
15
15
|
*
|
|
16
16
|
* Writes require the `x-dsh-world` header: a cross-site page cannot add it (that would trigger a preflight,
|
|
@@ -22,7 +22,6 @@ import { MAX_BATCH_MS } from "../qq-native/batch.js";
|
|
|
22
22
|
* console door has nothing to do with it — which is why removing the bridge's config did not have to take
|
|
23
23
|
* this endpoint down with it.
|
|
24
24
|
*/
|
|
25
|
-
export const QQ_PREFIX = '/dsh-world/qq';
|
|
26
25
|
export const WRITE_HEADER = 'x-dsh-world';
|
|
27
26
|
const MAX_BODY_BYTES = 8 * 1024;
|
|
28
27
|
const ok = (body = { ok: true }) => ({ status: 200, body });
|
|
@@ -116,16 +115,17 @@ async function write(doors, path, body, setNative) {
|
|
|
116
115
|
default: return undefined;
|
|
117
116
|
}
|
|
118
117
|
}
|
|
119
|
-
export function qqRoute(allowedHosts = [], doors, native, setNative) {
|
|
118
|
+
export function qqRoute(worldPrefix, allowedHosts = [], doors, native, setNative) {
|
|
119
|
+
const prefix = worldPrefix + '/qq';
|
|
120
120
|
return {
|
|
121
|
-
kind: 'prefix', path:
|
|
121
|
+
kind: 'prefix', path: prefix,
|
|
122
122
|
handler: async (req, res) => {
|
|
123
123
|
if (!allowed(req, allowedHosts)) {
|
|
124
124
|
sendJson(res, { status: 403, body: { error: 'forbidden' } });
|
|
125
125
|
return;
|
|
126
126
|
}
|
|
127
|
-
const url = new URL(req.url ??
|
|
128
|
-
const path = url.pathname.slice(
|
|
127
|
+
const url = new URL(req.url ?? prefix, 'http://localhost');
|
|
128
|
+
const path = url.pathname.slice(prefix.length) || '/';
|
|
129
129
|
try {
|
|
130
130
|
if (req.method === 'GET' && path === '/native') {
|
|
131
131
|
// 她自己接的那条 OneBot 通道。没开就老实回 null,界面据此显示「没开」。
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { spawn, spawnSync } from 'node:child_process';
|
|
2
|
-
import { existsSync } from 'node:fs';
|
|
2
|
+
import { existsSync, realpathSync } from 'node:fs';
|
|
3
3
|
import { join } from 'node:path';
|
|
4
4
|
/**
|
|
5
5
|
* 把 SnowLuma 拉起来一次(面板上的按钮和看门狗共用)。
|
|
@@ -9,6 +9,8 @@ import { join } from 'node:path';
|
|
|
9
9
|
* 才退回直接 spawn,并如实说明这条线只活到 DSH 退出。
|
|
10
10
|
*/
|
|
11
11
|
const TASK = 'SnowLuma-watchdog';
|
|
12
|
+
const START_WAIT_MS = 90_000;
|
|
13
|
+
const pendingStarts = new Map();
|
|
12
14
|
/** SnowLuma 的入口:完整版自带 node.exe,Lite 版用本机 node 跑 index.mjs,再不然是 launcher.bat。 */
|
|
13
15
|
function entry(homeDir) {
|
|
14
16
|
const index = join(homeDir, 'index.mjs');
|
|
@@ -18,17 +20,48 @@ function entry(homeDir) {
|
|
|
18
20
|
return existsSync(launcher) ? { exe: launcher, args: [] } : undefined;
|
|
19
21
|
}
|
|
20
22
|
const schtasks = (...args) => process.platform === 'win32' && spawnSync('schtasks', args, { windowsHide: true, stdio: 'ignore' }).status === 0;
|
|
23
|
+
/** 按安装目录认已有实例,包括 DSH 重启前或用户手动启动的那份。 */
|
|
24
|
+
function isRunning(homeDir) {
|
|
25
|
+
const script = String.raw `$ErrorActionPreference = 'Stop'
|
|
26
|
+
$homeDir = $env:DSH_WORLD_SNOWLUMA_HOME.TrimEnd('\') + '\'
|
|
27
|
+
Get-CimInstance Win32_Process -Filter "Name = 'node.exe' OR Name = 'cmd.exe'" | Where-Object {
|
|
28
|
+
([string]$_.ExecutablePath).StartsWith($homeDir, [StringComparison]::OrdinalIgnoreCase) -or
|
|
29
|
+
([string]$_.CommandLine).Replace('/', '\').IndexOf($homeDir, [StringComparison]::OrdinalIgnoreCase) -ge 0
|
|
30
|
+
} | Select-Object -First 1 -ExpandProperty ProcessId`;
|
|
31
|
+
const result = process.platform === 'win32'
|
|
32
|
+
? spawnSync('powershell.exe', ['-NoProfile', '-NonInteractive', '-EncodedCommand', Buffer.from(script, 'utf16le').toString('base64')], {
|
|
33
|
+
env: { ...process.env, DSH_WORLD_SNOWLUMA_HOME: homeDir }, encoding: 'utf8', windowsHide: true, timeout: 5000,
|
|
34
|
+
})
|
|
35
|
+
: spawnSync('ps', ['-ww', '-axo', 'args='], { encoding: 'utf8', timeout: 5000, ...(process.platform === 'linux' ? { env: { ...process.env, LC_ALL: 'C.UTF-8' } } : {}) });
|
|
36
|
+
if (result.error || result.status !== 0)
|
|
37
|
+
throw new Error(`无法确认 SnowLuma 是否已在运行,未重复启动:${result.error?.message ?? result.stderr?.trim() ?? result.status}`);
|
|
38
|
+
return process.platform === 'win32' ? !!result.stdout.trim() : result.stdout.split(/\r?\n/).some(line => line.includes(`${homeDir}/`));
|
|
39
|
+
}
|
|
21
40
|
export function startSnowluma(homeDir) {
|
|
22
41
|
if (!homeDir || !existsSync(homeDir))
|
|
23
42
|
return { started: false, error: '不知道 SnowLuma 装在哪(填 qqNative.snowlumaHome)' };
|
|
24
|
-
const hasTask = schtasks('/query', '/tn', TASK);
|
|
25
|
-
if (hasTask && schtasks('/run', '/tn', TASK))
|
|
26
|
-
return { started: true, how: 'task' };
|
|
27
|
-
const target = entry(homeDir);
|
|
28
|
-
if (!target)
|
|
29
|
-
return { started: false, error: '这个目录里没有 node.exe / index.mjs / launcher.bat' };
|
|
30
43
|
try {
|
|
31
|
-
|
|
44
|
+
homeDir = realpathSync(homeDir);
|
|
45
|
+
const key = process.platform === 'win32' ? homeDir.toLowerCase() : homeDir;
|
|
46
|
+
const pending = pendingStarts.get(key);
|
|
47
|
+
if (pending && Date.now() < pending.until)
|
|
48
|
+
return pending.error ? { started: false, error: pending.error } : { started: false, alreadyRunning: true };
|
|
49
|
+
pendingStarts.delete(key);
|
|
50
|
+
// shortcut: 仍在运行但端口不通时只报告,不杀外部实例;需要自动恢复卡死时再加受控重启。
|
|
51
|
+
if (isRunning(homeDir))
|
|
52
|
+
return { started: false, alreadyRunning: true };
|
|
53
|
+
const hasTask = schtasks('/query', '/tn', TASK);
|
|
54
|
+
const attempt = { until: Date.now() + START_WAIT_MS };
|
|
55
|
+
if (hasTask && schtasks('/run', '/tn', TASK)) {
|
|
56
|
+
pendingStarts.set(key, attempt);
|
|
57
|
+
return { started: true, how: 'task' };
|
|
58
|
+
}
|
|
59
|
+
const target = entry(homeDir);
|
|
60
|
+
if (!target)
|
|
61
|
+
return { started: false, error: '这个目录里没有 node.exe / index.mjs / launcher.bat' };
|
|
62
|
+
spawn(target.exe, target.args, { cwd: homeDir, detached: true, stdio: 'ignore', windowsHide: true })
|
|
63
|
+
.once('error', error => { attempt.error = error.message; }).unref();
|
|
64
|
+
pendingStarts.set(key, attempt);
|
|
32
65
|
return { started: true, how: 'spawn', ...(hasTask ? { error: '计划任务没跑起来(可能被禁用了),改为直接起;这条线只活到 DSH 退出' } : {}) };
|
|
33
66
|
}
|
|
34
67
|
catch (error) {
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { type StartResult } from './snowluma-start.ts';
|
|
2
2
|
/**
|
|
3
|
-
* SnowLuma 的看门狗:QQ 通道开着,就每隔一段时间探一次 OneBot
|
|
3
|
+
* SnowLuma 的看门狗:QQ 通道开着,就每隔一段时间探一次 OneBot 的端口,不通且没有实例时才拉起。
|
|
4
4
|
* 拉不起来只把原因记在面板上;探活重叠时跳过这一轮,不叠着打。
|
|
5
5
|
*/
|
|
6
6
|
export interface SnowlumaStatus {
|
|
@@ -29,4 +29,3 @@ export declare function createSnowlumaSupervisor(options: {
|
|
|
29
29
|
stop(): void;
|
|
30
30
|
status: () => SnowlumaStatus;
|
|
31
31
|
};
|
|
32
|
-
export type SnowlumaSupervisor = ReturnType<typeof createSnowlumaSupervisor>;
|