dsh-world 0.7.1 → 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.
Files changed (76) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/INSTALL.md +314 -314
  3. package/LICENSE +21 -21
  4. package/NOTES.md +34 -15
  5. package/README.md +22 -8
  6. package/client/index.js +85 -28
  7. package/cordis.patch.yml +6 -6
  8. package/lib/archiveSelection.d.ts +6 -2
  9. package/lib/archiveSelection.js +21 -12
  10. package/lib/compaction.d.ts +7 -0
  11. package/lib/compaction.js +16 -7
  12. package/lib/console/routes.d.ts +4 -3
  13. package/lib/console/routes.js +18 -12
  14. package/lib/console/snapshot.d.ts +3 -3
  15. package/lib/console/snapshot.js +1 -4
  16. package/lib/ecosystem/bridge/bridge.d.ts +5 -0
  17. package/lib/ecosystem/bridge/bridge.js +2 -1
  18. package/lib/ecosystem/bridge/route.d.ts +4 -6
  19. package/lib/ecosystem/bridge/route.js +34 -58
  20. package/lib/ecosystem/qq/panel.d.ts +0 -1
  21. package/lib/ecosystem/qq/route.d.ts +6 -7
  22. package/lib/ecosystem/qq/route.js +10 -10
  23. package/lib/ecosystem/qq/snowluma-start.d.ts +1 -0
  24. package/lib/ecosystem/qq/snowluma-start.js +41 -8
  25. package/lib/ecosystem/qq/supervisor.d.ts +1 -2
  26. package/lib/ecosystem/qq/supervisor.js +4 -2
  27. package/lib/ecosystem/qq-native/home.d.ts +1 -0
  28. package/lib/ecosystem/qq-native/home.js +10 -3
  29. package/lib/ecosystem/qq-native/index.js +19 -4
  30. package/lib/ecosystem/qq-native/native-bridge.d.ts +0 -1
  31. package/lib/ecosystem/qq-native/native-bridge.js +5 -4
  32. package/lib/ecosystem/qq-native/replies.d.ts +3 -2
  33. package/lib/ecosystem/qq-native/replies.js +15 -4
  34. package/lib/ecosystem/qq-native/snowluma.js +11 -2
  35. package/lib/ecosystem/shared/context.d.ts +5 -0
  36. package/lib/ecosystem/shared/context.js +5 -0
  37. package/lib/ecosystem/wechat/index.d.ts +0 -1
  38. package/lib/ecosystem/wechat/index.js +6 -5
  39. package/lib/hostContract.d.ts +17 -1
  40. package/lib/index.d.ts +1 -0
  41. package/lib/index.js +126 -47
  42. package/lib/life/toolRegistry.js +2 -2
  43. package/lib/memoryFiles.d.ts +0 -1
  44. package/lib/memoryStore.d.ts +0 -1
  45. package/lib/memoryStore.js +0 -1
  46. package/lib/memoryTools.d.ts +0 -1
  47. package/lib/memoryTools.js +2 -3
  48. package/lib/promptSection.d.ts +10 -7
  49. package/lib/promptSection.js +80 -33
  50. package/lib/runtime.d.ts +12 -3
  51. package/lib/runtime.js +150 -29
  52. package/lib/sourceArchive.d.ts +4 -2
  53. package/lib/sourceArchive.js +19 -5
  54. package/lib/store.js +2 -1
  55. package/lib/types.d.ts +1 -1
  56. package/lib/worldPrompt.d.ts +2 -3
  57. package/lib/worldPrompt.js +2 -3
  58. package/lib/worldRoutes.d.ts +9 -0
  59. package/lib/worldRoutes.js +29 -0
  60. package/lib/worldScope.d.ts +5 -5
  61. package/lib/worldScope.js +16 -7
  62. package/lib/worldSwitch.d.ts +7 -2
  63. package/lib/worldSwitch.js +11 -1
  64. package/package.json +17 -16
  65. package/scripts/compact-home.mjs +29 -29
  66. package/scripts/enable-tool-free-compaction.ps1 +33 -33
  67. package/scripts/import-stickers.mjs +17 -17
  68. package/scripts/update-world.mjs +2 -2
  69. package/src/ecosystem/README.md +1 -1
  70. package/src/ecosystem/wechat/windows/README.md +6 -4
  71. package/src/ecosystem/wechat/windows/adapter.py +4 -2
  72. package/src/ecosystem/wechat/windows/engine/NOTICE.md +6 -0
  73. package/src/ecosystem/wechat/windows/engine/profiles.json +142 -114
  74. package/src/ecosystem/wechat/windows/presence.py +109 -109
  75. package/templates/alarm.md +2 -2
  76. package/templates/world-prompt.md +8 -2
package/lib/compaction.js CHANGED
@@ -83,6 +83,8 @@ class TargetConfigError extends Error {
83
83
  * tool result, tool schema and reasoning block from the compacted span, then
84
84
  * replaces the whole conversation with one summary paragraph.
85
85
  */
86
+ /** Whether a session's compaction service is this one, which can summarize inside a running turn; DSH's stock one cannot. */
87
+ export const compactsWhole = (engine) => typeof engine?.compactWhole === 'function';
86
88
  export default class ToolFreeCompaction extends CompactionEngine {
87
89
  static inject = ['llm', 'tokenMeter', 'sessions'];
88
90
  static Config = z.object({
@@ -183,10 +185,8 @@ export default class ToolFreeCompaction extends CompactionEngine {
183
185
  if (!target)
184
186
  return null;
185
187
  const meter = this.ctx.tokenMeter;
186
- if (trigger === 'context-overflow') {
187
- const range = selectWholeRange(agent.session, meter.measure(agent.session));
188
- return range && this.compactRegion(range.start, range.end, agent, signal);
189
- }
188
+ if (trigger === 'context-overflow')
189
+ return this.compactWhole(agent, signal);
190
190
  const policy = this.policyFor(target);
191
191
  const info = await this.ctx.llm.resolveModelInfo(target.provider, target.model, signal);
192
192
  assertNoActiveCompaction(agent.session, 'automatic pressure compaction');
@@ -209,15 +209,24 @@ export default class ToolFreeCompaction extends CompactionEngine {
209
209
  }
210
210
  if (meter.measure(agent.session).totalTokens < threshold)
211
211
  return null;
212
- const range = selectWholeRange(agent.session, meter.measure(agent.session));
213
- if (!range)
212
+ const result = await this.compactWhole(agent, signal);
213
+ if (!result)
214
214
  return null;
215
- const result = await this.compactRegion(range.start, range.end, agent, signal);
216
215
  const after = meter.measure(agent.session).totalTokens;
217
216
  if (after >= threshold)
218
217
  throw new Error(`compaction still above threshold after summarizing the whole conversation (${after} estimated tokens >= threshold ${threshold})`);
219
218
  return result;
220
219
  }
220
+ /**
221
+ * Summarizes the whole conversation inside the running turn, before its next request; null when there is nothing to
222
+ * summarize. Besides pressure and overflow, the world runtime calls it on a cold session's first step (#36).
223
+ */
224
+ async compactWhole(agent, signal) {
225
+ if (!routedTarget(agent.session))
226
+ return null;
227
+ const range = selectWholeRange(agent.session, this.ctx.tokenMeter.measure(agent.session));
228
+ return range && this.compactRegion(range.start, range.end, agent, signal);
229
+ }
221
230
  compactRegion(start, end, agent, signal) {
222
231
  return compactSurfaceRegion(this.dependencies(), agent, start, end, { owner: 'current-turn', stability: 'whole-surface' }, signal);
223
232
  }
@@ -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 {
@@ -41,6 +40,8 @@ export interface ConsoleActions {
41
40
  setDailyBudget(yuan: number | undefined): void;
42
41
  /** Turns in her memory block; undefined goes back to the default. */
43
42
  setMemoryTurns(turns: number | undefined): void;
43
+ /** Hours of silence after which a session re-reads her memory and prompt; undefined goes back to the default. */
44
+ setColdHours(hours: number | undefined): void;
44
45
  setArchiveScope(scope: MemoryArchiveScope): boolean;
45
46
  setWorkspacePermission(permission: string): void;
46
47
  /** Whether the evening look back is followed by applying and compacting her home (on unless turned off). */
@@ -73,8 +74,8 @@ export interface ConsoleRequest {
73
74
  body?: Record<string, unknown> | undefined;
74
75
  }
75
76
  /** Reads are open to the console page; writes need POST, the write header and a JSON body. */
76
- export declare function handleConsole(sources: ConsoleSources, actions: ConsoleActions, request: ConsoleRequest): Promise<JsonResult>;
77
- 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[]): {
78
79
  kind: "prefix";
79
80
  path: string;
80
81
  handler: (req: IncomingMessage, res: ServerResponse) => Promise<void>;
@@ -1,10 +1,9 @@
1
1
  import { jsonObject, knownHost, readBody, sendJson } from "../http.js";
2
2
  import { PERSONA_LAYERS } from "../persona.js";
3
- import { validTurns, validWechatBuffer, validWechatContext, validWorkspacePermission, MAX_WECHAT_BUFFER_SECONDS, MAX_WECHAT_CONTEXT } from "../worldSwitch.js";
3
+ import { validColdHours, validTurns, validWechatBuffer, MAX_COLD_HOURS, validWechatContext, validWorkspacePermission, MAX_WECHAT_BUFFER_SECONDS, MAX_WECHAT_CONTEXT } from "../worldSwitch.js";
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;
@@ -68,10 +67,17 @@ async function write(actions, path, body) {
68
67
  return ok();
69
68
  }
70
69
  case '/console/memory': {
71
- const turns = body?.turns;
72
- if (turns !== null && !validTurns(turns))
70
+ const turns = body?.turns, coldHours = body?.coldHours;
71
+ if (turns !== undefined && turns !== null && !validTurns(turns))
73
72
  return bad('turns must be a whole number of at least 1, or null');
74
- actions.setMemoryTurns(turns === null ? undefined : turns);
73
+ if (coldHours !== undefined && coldHours !== null && !validColdHours(coldHours))
74
+ return bad(`coldHours must be a whole number from 1 to ${MAX_COLD_HOURS}, or null`);
75
+ if (turns === undefined && coldHours === undefined)
76
+ return bad('nothing to change');
77
+ if (turns !== undefined)
78
+ actions.setMemoryTurns(turns ?? undefined);
79
+ if (coldHours !== undefined)
80
+ actions.setColdHours(coldHours ?? undefined);
75
81
  return ok();
76
82
  }
77
83
  case '/console/wechat': {
@@ -137,11 +143,11 @@ async function write(actions, path, body) {
137
143
  }
138
144
  }
139
145
  /** Reads are open to the console page; writes need POST, the write header and a JSON body. */
140
- export async function handleConsole(sources, actions, request) {
146
+ export async function handleConsole(prefix, sources, actions, request) {
141
147
  const url = new URL(request.url, 'http://localhost');
142
- if (url.pathname !== CONSOLE_PREFIX && !url.pathname.startsWith(CONSOLE_PREFIX + '/'))
148
+ if (url.pathname !== prefix && !url.pathname.startsWith(prefix + '/'))
143
149
  return { status: 404, body: { error: 'not found' } };
144
- const path = url.pathname.slice(CONSOLE_PREFIX.length);
150
+ const path = url.pathname.slice(prefix.length);
145
151
  if (request.method === 'POST') {
146
152
  if (!request.write)
147
153
  return { status: 403, body: { error: 'forbidden' } };
@@ -175,9 +181,9 @@ export async function handleConsole(sources, actions, request) {
175
181
  default: return { status: 404, body: { error: 'not found' } };
176
182
  }
177
183
  }
178
- export function consoleRoute(sources, actions, allowedHosts = []) {
184
+ export function consoleRoute(prefix, sources, actions, allowedHosts = []) {
179
185
  return {
180
- kind: 'prefix', path: CONSOLE_PREFIX,
186
+ kind: 'prefix', path: prefix,
181
187
  handler: async (req, res) => {
182
188
  let result;
183
189
  try {
@@ -186,7 +192,7 @@ export function consoleRoute(sources, actions, allowedHosts = []) {
186
192
  else {
187
193
  const method = req.method ?? 'GET';
188
194
  const url = new URL(req.url ?? '/', 'http://localhost');
189
- if (method === 'GET' && url.pathname === CONSOLE_PREFIX + '/console/photo') {
195
+ if (method === 'GET' && url.pathname === prefix + '/console/photo') {
190
196
  const image = sources.photo?.(url.searchParams.get('id') ?? '');
191
197
  if (!image) {
192
198
  sendJson(res, { status: 404, body: { error: '找不到这张照片' } });
@@ -198,7 +204,7 @@ export function consoleRoute(sources, actions, allowedHosts = []) {
198
204
  }
199
205
  const write = method === 'POST' && req.headers[WRITE_HEADER] === '1' && String(req.headers['content-type'] ?? '').startsWith('application/json');
200
206
  const body = write ? jsonObject(await readBody(req, MAX_BODY_BYTES)) : undefined;
201
- 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 });
202
208
  }
203
209
  }
204
210
  catch {
@@ -30,6 +30,8 @@ export interface SnapshotDeps {
30
30
  dailyBudget(): number | undefined;
31
31
  /** Turns her memory block carries. */
32
32
  memoryTurns(): number;
33
+ /** Hours of silence after which a session re-reads her memory block and prompt. */
34
+ coldHours?(): number;
33
35
  selectedArchiveScope?(): MemoryArchiveScope;
34
36
  compactAfterReview?(): boolean;
35
37
  /** The evening look back and the morning wake, with what an empty field goes back to; absent without the life line. */
@@ -48,14 +50,12 @@ export interface SnapshotDeps {
48
50
  wechat?(): unknown;
49
51
  /** Whose conversations her archive keeps; the memory block shown is read through it. */
50
52
  archiveSession?(id: string): boolean;
51
- /** Faults outside the life line: the memory line, the bridge, the QQ bridge, starting and stopping. */
53
+ /** Faults outside the life line: the memory line, the bridge, starting and stopping. */
52
54
  faults(): string[];
53
55
  /** Which modules the config allows, whether their console switch is on, and whether they are running now. */
54
56
  modules?(): unknown;
55
57
  /** The OneBot channel she runs herself; null while it is off. */
56
58
  native?(): unknown;
57
- /** The QQ bridge, when the module is on; absent leaves that card out of the console. */
58
- qq?: () => Promise<unknown>;
59
59
  }
60
60
  /** Read-only views for the console; repeated polling within a few seconds reuses one snapshot until `invalidate`. */
61
61
  export declare function consoleSources(deps: SnapshotDeps): ConsoleSources & {
@@ -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,
@@ -31,11 +29,10 @@ export function consoleSources(deps) {
31
29
  life: life ? { homeSessionId: life.homeSessionId, status: home ? home.status : 'cold', alarm: life.alarm, review: life.review, recentWakes: lifeStore?.wakes().slice(-5).reverse() ?? [] } : null,
32
30
  homeApply: deps.homeApply?.() ?? null,
33
31
  health: [...(life?.faults ?? []), ...deps.faults()],
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() },
32
+ memory: { index: deps.longTerm?.status() ?? null, turns: turns.length, windowTurns: window, coldHours: deps.coldHours?.() ?? null, archiveScope, selectedArchiveScope, restartRequired: archiveScope !== selectedArchiveScope, approxTokens: estimateTokens(renderHistory(turns, config.timeZone, deps.names(), archiveScope === 'home')), oldest: turns.at(-1)?.messages[0]?.occurredAt, ...archive.stats() },
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
- export declare const BRIDGE_PATH = "/dsh-world/bridge/say";
4
- export declare const COMPACT_PATH = "/dsh-world/bridge/compact";
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; the same token as the words route. */
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
- async function handleSay(bridge, req, allowedHosts) {
10
- if (req.method !== 'POST')
11
- return { status: 405, body: { error: 'method not allowed' }, headers: { allow: 'POST' } };
12
- const token = req.headers['x-dsh-world-token'];
13
- if (req.headers['sec-fetch-site'] === 'cross-site' || !knownHost(req.headers.host, allowedHosts))
14
- return { status: 403, body: { error: 'forbidden' } };
15
- // While her world is stopped there is no bridge and no token to check against.
16
- if (!bridge)
17
- return unavailable;
18
- if (!bridge.checkToken(Array.isArray(token) ? undefined : token))
19
- return { status: 403, body: { error: 'forbidden' } };
20
- const body = jsonObject(await readBody(req, MAX_BODY_BYTES));
21
- const text = typeof body?.text === 'string' ? body.text.trim() : '';
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: BRIDGE_PATH,
22
+ kind: 'exact', path,
36
23
  handler: async (req, res) => {
37
24
  let result;
38
25
  try {
39
- result = await handleSay(bridge(), req, allowedHosts);
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
- 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 } };
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; 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
- };
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 `/dsh-world/qq` prefix is never eaten
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 /dsh-world/qq/native her own OneBot channel: is it connected, what has it seen, is it replying
8
- * GET /dsh-world/qq/console SnowLuma's console address, with a session token already traded for the
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 /dsh-world/qq/native { autoReply?, bridge?: { port? }, mutedUntil?, allowPrivate?, allowGroups?,
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 /dsh-world/qq/panel-password { username, password } remembers SnowLuma's panel password and
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 `/dsh-world/qq` prefix is never eaten
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 /dsh-world/qq/native her own OneBot channel: is it connected, what has it seen, is it replying
8
- * GET /dsh-world/qq/console SnowLuma's console address, with a session token already traded for the
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 /dsh-world/qq/native { autoReply?, bridge?: { port? }, mutedUntil?, allowPrivate?, allowGroups?,
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 /dsh-world/qq/panel-password { username, password } remembers SnowLuma's panel password and
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: QQ_PREFIX,
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 ?? QQ_PREFIX, 'http://localhost');
128
- const path = url.pathname.slice(QQ_PREFIX.length) || '/';
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,6 @@
1
1
  export interface StartResult {
2
2
  started: boolean;
3
+ alreadyRunning?: boolean;
3
4
  /** `task` = 借计划任务跑的(能活过 DSH 退出);`spawn` = 直接起的(DSH 一退出就没了)。 */
4
5
  how?: 'task' | 'spawn';
5
6
  error?: string;
@@ -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
- spawn(target.exe, target.args, { cwd: homeDir, detached: true, stdio: 'ignore', windowsHide: true }).unref();
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 的端口,不通就把 SnowLuma 拉起来。
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);
@@ -19,6 +19,7 @@ export declare function createQqHome(deps: {
19
19
  ask: (text: string, suppliedIdentity: SpeakerIdentity, suppliedContext?: ChannelContextMessage[]) => Promise<{
20
20
  id: string;
21
21
  text: string;
22
+ nudged: boolean;
22
23
  }>;
23
24
  stop: () => void;
24
25
  };