dsh-world 0.7.2 → 0.7.3
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 +394 -379
- package/INSTALL.md +314 -314
- package/LICENSE +21 -21
- package/NOTES.md +21 -13
- package/README.md +20 -6
- 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 +16 -7
- 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/wechat/index.d.ts +0 -1
- package/lib/ecosystem/wechat/index.js +6 -5
- package/lib/hostContract.d.ts +13 -0
- package/lib/index.js +106 -45
- 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/promptSection.d.ts +7 -5
- package/lib/promptSection.js +74 -28
- package/lib/runtime.d.ts +6 -2
- package/lib/runtime.js +136 -26
- package/lib/sourceArchive.d.ts +4 -2
- package/lib/sourceArchive.js +18 -4
- package/lib/store.js +2 -1
- package/lib/types.d.ts +1 -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 +2 -2
- package/src/ecosystem/wechat/windows/adapter.py +4 -2
- 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 +8 -2
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>;
|
|
@@ -22,6 +22,8 @@ export function createSnowlumaSupervisor(options) {
|
|
|
22
22
|
busy = true;
|
|
23
23
|
try {
|
|
24
24
|
state.alive = await probe(options.host, options.port, options.probeTimeoutMs ?? 3_000);
|
|
25
|
+
if (!state.watching)
|
|
26
|
+
return;
|
|
25
27
|
state.lastCheckAt = new Date().toISOString();
|
|
26
28
|
if (state.alive) {
|
|
27
29
|
state.lastError = null;
|
|
@@ -32,12 +34,12 @@ export function createSnowlumaSupervisor(options) {
|
|
|
32
34
|
return;
|
|
33
35
|
}
|
|
34
36
|
const result = launch();
|
|
35
|
-
state.lastError = result.error ?? (result.started ? null : '拉不起来,原因不明');
|
|
37
|
+
state.lastError = result.error ?? (result.alreadyRunning ? 'SnowLuma 已在运行或启动中,等待 OneBot 端口就绪' : result.started ? null : '拉不起来,原因不明');
|
|
36
38
|
if (result.started) {
|
|
37
39
|
state.restarts += 1;
|
|
38
40
|
state.lastRestartAt = new Date().toISOString();
|
|
39
41
|
}
|
|
40
|
-
options.log(`看门狗:${options.port} 不通,${result.started ? `已拉起 SnowLuma(${result.how})` : 'SnowLuma 没起来'}${state.lastError ? `:${state.lastError}` : ''}`);
|
|
42
|
+
options.log(`看门狗:${options.port} 不通,${result.started ? `已拉起 SnowLuma(${result.how})` : result.alreadyRunning ? '不重复拉起' : 'SnowLuma 没起来'}${state.lastError ? `:${state.lastError}` : ''}`);
|
|
41
43
|
}
|
|
42
44
|
catch (error) {
|
|
43
45
|
state.lastError = error instanceof Error ? error.message : String(error);
|
|
@@ -420,6 +420,8 @@ export function createQqNativeModule(deps) {
|
|
|
420
420
|
startBridge(config);
|
|
421
421
|
disposers.push(forwardOwnTurns());
|
|
422
422
|
client.start().catch((error) => {
|
|
423
|
+
if (stopped)
|
|
424
|
+
return;
|
|
423
425
|
stats.lastError = errorText(error);
|
|
424
426
|
deps.logger.warn('QQ 原生通道首次连接失败:', stats.lastError);
|
|
425
427
|
});
|
|
@@ -35,8 +35,6 @@ export const QUIET_AFTER_SILENCE_MS = 30 * 60_000;
|
|
|
35
35
|
const MAX_TEXT = 4_000;
|
|
36
36
|
/** 每条线最多记几条旧话当上下文。 */
|
|
37
37
|
const MAX_CONTEXT = 12;
|
|
38
|
-
// 默认不开:插件不该不打招呼就在别人的机器上开一个端口。要用的人在控制台那张卡上拨开(拨开就是 3210)。
|
|
39
|
-
export const DEFAULT_BRIDGE_PORT = 0;
|
|
40
38
|
export function createNativeBridge(deps) {
|
|
41
39
|
let server;
|
|
42
40
|
let stopped = false;
|
|
@@ -100,6 +100,14 @@
|
|
|
100
100
|
/** @typedef {'connecting'|'online'|'closed'} BridgeState */
|
|
101
101
|
import { SnowLumaTimeoutError, SnowLumaWebSocketClient, chain, parseSegments, } from '@snowluma/sdk';
|
|
102
102
|
import WebSocket from 'ws';
|
|
103
|
+
class SnowlumaSocket extends WebSocket {
|
|
104
|
+
close(code, reason) {
|
|
105
|
+
// The SDK removes its error listener before closing, but ws emits an error when a handshake is cancelled.
|
|
106
|
+
if (this.readyState === WebSocket.CONNECTING)
|
|
107
|
+
this.once('error', () => { });
|
|
108
|
+
super.close(code, reason);
|
|
109
|
+
}
|
|
110
|
+
}
|
|
103
111
|
// ── 常量 ──────────────────────────────────────────────────────
|
|
104
112
|
const SEND_TIMEOUT_MS = 15000; // 单次发送的外层超时(切片第 6 节:SEND_TIMEOUT_MS = 15000)
|
|
105
113
|
const DEFAULT_SEND_DELAY_MS = 500; // 串行发送间隔的默认值(见实现说明⑤)
|
|
@@ -504,7 +512,7 @@ export function createBridge(options) {
|
|
|
504
512
|
const bot = new SnowLumaWebSocketClient({
|
|
505
513
|
url: opts.wsUrl || DEFAULT_WS_URL,
|
|
506
514
|
// Node 22's built-in WebSocket can error without close; ws lets the SDK settle failed connects.
|
|
507
|
-
webSocket:
|
|
515
|
+
webSocket: SnowlumaSocket,
|
|
508
516
|
// 空串会让鉴权头变成 `Bearer `,某些网关直接 401 —— 必须 || undefined(切片第 1 节)
|
|
509
517
|
accessToken: opts.accessToken || undefined,
|
|
510
518
|
requestTimeoutMs: 30000,
|
|
@@ -560,7 +568,8 @@ export function createBridge(options) {
|
|
|
560
568
|
catch (error) {
|
|
561
569
|
// 首连失败按契约 reject 得清楚;客户端保留,SDK reconnect 会按退避自动重试
|
|
562
570
|
// (closed-before-opening 属于「非用户主动关闭」,重连条件成立),状态保持 connecting
|
|
563
|
-
|
|
571
|
+
if (client === bot)
|
|
572
|
+
log('error', `首次连接失败: ${error?.message ?? error}(SDK 将按退避自动重连)`);
|
|
564
573
|
throw error;
|
|
565
574
|
}
|
|
566
575
|
},
|
|
@@ -4,7 +4,6 @@ import type { IncomingMessage, ServerResponse } from 'node:http';
|
|
|
4
4
|
import { type SpeakerIdentity } from '../shared/identity.ts';
|
|
5
5
|
import type { PreparedReply, WechatReceipt } from './archive.ts';
|
|
6
6
|
import { type InWorld } from '../../worldScope.ts';
|
|
7
|
-
export declare const WECHAT_PATH = "/dsh-world/wechat/ask";
|
|
8
7
|
export declare function createWechatModule(deps: {
|
|
9
8
|
ctx: Context;
|
|
10
9
|
home(identity: SpeakerIdentity): Promise<Agent>;
|
|
@@ -12,9 +12,10 @@ import { createWechatReading } from "./reading.js";
|
|
|
12
12
|
import { createStickerLibrary } from "./stickerLibrary.js";
|
|
13
13
|
import { createStickerTools } from "./stickerTools.js";
|
|
14
14
|
import { createWechatPresence } from "./presence.js";
|
|
15
|
-
import { reassembleOnChange,
|
|
16
|
-
|
|
15
|
+
import { reassembleOnChange, registerScopedTool } from "../../worldScope.js";
|
|
16
|
+
import { worldPath } from "../../worldRoutes.js";
|
|
17
17
|
export function createWechatModule(deps) {
|
|
18
|
+
const path = worldPath(deps.worldId ?? 'default') + '/wechat/ask';
|
|
18
19
|
const token = randomBytes(32).toString('hex');
|
|
19
20
|
const stickerDir = join(dirname(deps.file), 'stickers');
|
|
20
21
|
const stickers = createStickerLibrary(stickerDir);
|
|
@@ -60,7 +61,7 @@ export function createWechatModule(deps) {
|
|
|
60
61
|
const disposers = [];
|
|
61
62
|
try {
|
|
62
63
|
for (const tool of [...sending.tools, reading.tool, reading.imageTool, ...stickerTools])
|
|
63
|
-
disposers.push(agent
|
|
64
|
+
disposers.push(registerScopedTool(agent, tool, () => !stopped && inside(agent), () => detach(agent)));
|
|
64
65
|
attached.set(agent, disposers);
|
|
65
66
|
}
|
|
66
67
|
catch (error) {
|
|
@@ -180,7 +181,7 @@ export function createWechatModule(deps) {
|
|
|
180
181
|
presence: (now) => !stopped && accountState === 'online' ? presence.summary(now) : undefined,
|
|
181
182
|
status() { return { ...sending.status(), lastContactAt: lastContactAt ?? null, account: accountState ?? null, ...settings() }; },
|
|
182
183
|
start() {
|
|
183
|
-
durableWrite(deps.file, JSON.stringify({ origin: deps.origin(), token, path
|
|
184
|
+
durableWrite(deps.file, JSON.stringify({ origin: deps.origin(), token, path, pid: process.pid, protocol: 4, references: true }, null, 2));
|
|
184
185
|
if (inWorld)
|
|
185
186
|
for (const agent of deps.ctx.agents.list())
|
|
186
187
|
attach(agent);
|
|
@@ -202,7 +203,7 @@ export function createWechatModule(deps) {
|
|
|
202
203
|
catch { /* already absent, or a newer module owns the file */ }
|
|
203
204
|
return closing = Promise.allSettled([...requests]).then(() => sending.stop());
|
|
204
205
|
},
|
|
205
|
-
route: { kind: 'exact', path
|
|
206
|
+
route: { kind: 'exact', path, handler: async (req, res) => {
|
|
206
207
|
let result;
|
|
207
208
|
const request = handle(req);
|
|
208
209
|
requests.add(request);
|
package/lib/hostContract.d.ts
CHANGED
|
@@ -1,8 +1,21 @@
|
|
|
1
|
+
declare module '@deepseek-ai/dsh-session/types' {
|
|
2
|
+
interface SessionEventMap {
|
|
3
|
+
'agent-preset/selected': {
|
|
4
|
+
agentPreset: string;
|
|
5
|
+
};
|
|
6
|
+
}
|
|
7
|
+
}
|
|
8
|
+
declare module '@deepseek-ai/dsh-llm/types' {
|
|
9
|
+
interface LlmRequestPurposeMap {
|
|
10
|
+
compaction: true;
|
|
11
|
+
}
|
|
12
|
+
}
|
|
1
13
|
declare module '@deepseek-ai/dsh-llm' {
|
|
2
14
|
interface MessageSourceMap {
|
|
3
15
|
'dsh-world-history': {
|
|
4
16
|
kind: 'dsh-world-history';
|
|
5
17
|
form: 'recall';
|
|
18
|
+
worldId?: string;
|
|
6
19
|
};
|
|
7
20
|
'dsh-world-summary-input': {
|
|
8
21
|
kind: 'dsh-world-summary-input';
|