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.
Files changed (78) hide show
  1. package/CHANGELOG.md +403 -379
  2. package/INSTALL.md +314 -314
  3. package/LICENSE +21 -21
  4. package/NOTES.md +23 -13
  5. package/README.md +22 -7
  6. package/client/index.js +74 -27
  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 +18 -9
  12. package/lib/compactionSwap.d.ts +17 -0
  13. package/lib/compactionSwap.js +68 -6
  14. package/lib/console/routes.d.ts +2 -3
  15. package/lib/console/routes.js +7 -8
  16. package/lib/console/snapshot.d.ts +1 -3
  17. package/lib/console/snapshot.js +0 -3
  18. package/lib/ecosystem/bridge/bridge.d.ts +5 -0
  19. package/lib/ecosystem/bridge/bridge.js +2 -1
  20. package/lib/ecosystem/bridge/route.d.ts +4 -6
  21. package/lib/ecosystem/bridge/route.js +34 -58
  22. package/lib/ecosystem/qq/panel.d.ts +0 -1
  23. package/lib/ecosystem/qq/route.d.ts +6 -7
  24. package/lib/ecosystem/qq/route.js +10 -10
  25. package/lib/ecosystem/qq/snowluma-start.d.ts +1 -0
  26. package/lib/ecosystem/qq/snowluma-start.js +41 -8
  27. package/lib/ecosystem/qq/supervisor.d.ts +1 -2
  28. package/lib/ecosystem/qq/supervisor.js +4 -2
  29. package/lib/ecosystem/qq-native/index.js +2 -0
  30. package/lib/ecosystem/qq-native/native-bridge.d.ts +0 -1
  31. package/lib/ecosystem/qq-native/native-bridge.js +0 -2
  32. package/lib/ecosystem/qq-native/snowluma.js +11 -2
  33. package/lib/ecosystem/shared/turn.d.ts +3 -0
  34. package/lib/ecosystem/shared/turn.js +9 -2
  35. package/lib/ecosystem/wechat/home.d.ts +3 -0
  36. package/lib/ecosystem/wechat/home.js +12 -4
  37. package/lib/ecosystem/wechat/index.d.ts +0 -1
  38. package/lib/ecosystem/wechat/index.js +9 -6
  39. package/lib/hostContract.d.ts +19 -0
  40. package/lib/index.js +117 -49
  41. package/lib/life/toolRegistry.js +2 -2
  42. package/lib/memoryFiles.d.ts +0 -1
  43. package/lib/memoryStore.d.ts +0 -1
  44. package/lib/memoryStore.js +0 -1
  45. package/lib/memoryTools.d.ts +0 -1
  46. package/lib/memoryTools.js +2 -3
  47. package/lib/mood.d.ts +28 -0
  48. package/lib/mood.js +69 -0
  49. package/lib/promptSection.d.ts +7 -5
  50. package/lib/promptSection.js +74 -28
  51. package/lib/runtime.d.ts +6 -2
  52. package/lib/runtime.js +163 -26
  53. package/lib/self.d.ts +1 -1
  54. package/lib/self.js +1 -1
  55. package/lib/sourceArchive.d.ts +4 -2
  56. package/lib/sourceArchive.js +18 -4
  57. package/lib/store.js +2 -1
  58. package/lib/types.d.ts +3 -1
  59. package/lib/worldPrompt.d.ts +2 -3
  60. package/lib/worldPrompt.js +2 -3
  61. package/lib/worldRoutes.d.ts +9 -0
  62. package/lib/worldRoutes.js +29 -0
  63. package/lib/worldScope.d.ts +5 -5
  64. package/lib/worldScope.js +16 -7
  65. package/lib/worldSwitch.d.ts +1 -2
  66. package/lib/worldSwitch.js +1 -1
  67. package/package.json +17 -16
  68. package/scripts/compact-home.mjs +29 -29
  69. package/scripts/enable-tool-free-compaction.ps1 +33 -33
  70. package/scripts/import-stickers.mjs +17 -17
  71. package/scripts/update-world.mjs +2 -2
  72. package/src/ecosystem/README.md +1 -1
  73. package/src/ecosystem/wechat/windows/README.md +3 -3
  74. package/src/ecosystem/wechat/windows/adapter.py +21 -3
  75. package/src/ecosystem/wechat/windows/engine/profiles.json +142 -142
  76. package/src/ecosystem/wechat/windows/presence.py +109 -109
  77. package/templates/alarm.md +2 -2
  78. package/templates/world-prompt.md +11 -2
@@ -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
  });
@@ -11,7 +11,6 @@ export interface BridgeConfig {
11
11
  title: string;
12
12
  contextMessages: number;
13
13
  }
14
- export declare const DEFAULT_BRIDGE_PORT = 0;
15
14
  export interface BridgeStatus {
16
15
  serving: boolean;
17
16
  port: number;
@@ -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: 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
- log('error', `首次连接失败: ${error?.message ?? error}(SDK 将按退避自动重连)`);
571
+ if (client === bot)
572
+ log('error', `首次连接失败: ${error?.message ?? error}(SDK 将按退避自动重连)`);
564
573
  throw error;
565
574
  }
566
575
  },
@@ -28,10 +28,13 @@ export declare function createChannelQueue(name: string, options: {
28
28
  * she had said before it answered `words` alone and is the answer; nothing after it is, since it may be meant for
29
29
  * whoever cut in, and having said nothing yet is a failure. An interrupted, truncated or unfinished turn is a failure,
30
30
  * so the caller never sends half a message. The session's log is flushed before the answer is returned.
31
+ * A door that sees her answer arrive another way (`answered`, such as a message she sent there herself) stops
32
+ * waiting at it: whatever she goes on to do in that turn is her own, and waiting for it only ran the door out of time.
31
33
  */
32
34
  export declare function askTurn(ctx: Context, agent: Agent, words: UserMessage, options: {
33
35
  name: string;
34
36
  inWorld?: InWorld | undefined;
35
37
  context?: UserMessage | undefined;
36
38
  cancelled?: Promise<never> | undefined;
39
+ answered?: ((source: UserMessage['source']) => boolean) | undefined;
37
40
  }): Promise<string>;
@@ -60,16 +60,18 @@ export function createChannelQueue(name, options) {
60
60
  * she had said before it answered `words` alone and is the answer; nothing after it is, since it may be meant for
61
61
  * whoever cut in, and having said nothing yet is a failure. An interrupted, truncated or unfinished turn is a failure,
62
62
  * so the caller never sends half a message. The session's log is flushed before the answer is returned.
63
+ * A door that sees her answer arrive another way (`answered`, such as a message she sent there herself) stops
64
+ * waiting at it: whatever she goes on to do in that turn is her own, and waiting for it only ran the door out of time.
63
65
  */
64
66
  export async function askTurn(ctx, agent, words, options) {
65
67
  const cancelled = options.cancelled ?? new Promise(() => { });
66
- let admitted = false, failed = false, cut = false, reply = '';
68
+ let admitted = false, failed = false, cut = false, answered = false, reply = '';
67
69
  // Enough to tell, when it fails, which way it went.
68
70
  let seen = 0, last = 'none';
69
71
  let finish;
70
72
  const finished = new Promise(resolve => { finish = resolve; });
71
73
  const dispose = ctx.on('session/event', (session, event) => {
72
- if (session.id !== agent.id || cut)
74
+ if (session.id !== agent.id || cut || answered)
73
75
  return;
74
76
  seen += 1;
75
77
  if (event.type === 'turn/end')
@@ -84,6 +86,11 @@ export async function askTurn(ctx, agent, words, options) {
84
86
  finish();
85
87
  return;
86
88
  }
89
+ if (admitted && options.answered?.(event.data.source)) {
90
+ answered = true;
91
+ finish();
92
+ return;
93
+ }
87
94
  }
88
95
  }
89
96
  if (!admitted)
@@ -6,6 +6,9 @@ import type { LifeTimers } from '../../life/alarmTimer.ts';
6
6
  import { type ChannelContextMessage, type ChannelReference } from '../shared/context.ts';
7
7
  import { type InWorld } from '../../worldScope.ts';
8
8
  export declare const WECHAT_REPLY_TIMEOUT_MS: number;
9
+ /** Ran out of time before her home took the words in: nothing was handed over, so asking again later repeats nothing. */
10
+ export declare class WechatHomeBusy extends Error {
11
+ }
9
12
  /** One home, serialized channel requests; each caller receives only its own final answer. */
10
13
  export declare function createWechatHome(deps: {
11
14
  ctx: Context;
@@ -5,6 +5,9 @@ import { askTurn, createChannelQueue } from "../shared/turn.js";
5
5
  import { incomingText } from "./messages.js";
6
6
  import { admit } from "../../worldScope.js";
7
7
  export const WECHAT_REPLY_TIMEOUT_MS = 3 * 60_000;
8
+ /** Ran out of time before her home took the words in: nothing was handed over, so asking again later repeats nothing. */
9
+ export class WechatHomeBusy extends Error {
10
+ }
8
11
  /** One home, serialized channel requests; each caller receives only its own final answer. */
9
12
  export function createWechatHome(deps) {
10
13
  const queue = createChannelQueue('WeChat', { limit: 32, timeoutMs: WECHAT_REPLY_TIMEOUT_MS, timers: deps.timers });
@@ -14,13 +17,16 @@ export function createWechatHome(deps) {
14
17
  const media = channelMedia(suppliedMedia, identity);
15
18
  const reference = channelReference(suppliedReference, identity);
16
19
  return queue.run(async (cancelled) => {
20
+ // Until the words are handed over, running out of time only means she was busy (#busy).
21
+ const handedOver = cancelled.catch((error) => { throw new WechatHomeBusy(error.message, { cause: error }); });
22
+ handedOver.catch(() => { });
17
23
  // Checked again after every wait: the session may leave her world meanwhile.
18
- const agent = admit(deps.inWorld, await Promise.race([deps.home(identity), cancelled]));
19
- await Promise.race([agent.whenIdle(), cancelled]);
24
+ const agent = admit(deps.inWorld, await Promise.race([deps.home(identity), handedOver]));
25
+ await Promise.race([agent.whenIdle(), handedOver]);
20
26
  admit(deps.inWorld, agent);
21
27
  if ((reference?.image || [...context, ...media].some(message => message.image || message.reference?.image)) && !deps.images)
22
28
  throw new Error('Image admission is unavailable');
23
- const images = await Promise.race([deps.images?.(identity, [...context, ...media], reference) ?? Promise.resolve([]), cancelled]);
29
+ const images = await Promise.race([deps.images?.(identity, [...context, ...media], reference) ?? Promise.resolve([]), handedOver]);
24
30
  queue.alive();
25
31
  const content = incomingText(text, reference);
26
32
  const source = content ? { kind: 'user', identity } : { kind: 'dsh-world-channel-context', form: 'recall' };
@@ -34,7 +40,9 @@ export function createWechatHome(deps) {
34
40
  const instructions = parts.length || images.length
35
41
  ? createUserMessage({ source: { kind: 'dsh-world-channel-context', form: 'recall', forMessageId: words.id }, content: [...(parts.length ? [{ type: 'text', text: parts.join('\n') }] : []), ...images] })
36
42
  : undefined;
37
- const reply = await askTurn(deps.ctx, agent, words, { name: 'WeChat', context: instructions, cancelled, inWorld: deps.inWorld });
43
+ // What she sends to this chat herself is her answer; the rest of her turn is not this request's to wait for.
44
+ const answered = (sent) => sent.kind === 'dsh-world-wechat-outgoing' && sent.identity.conversationId === identity.conversationId;
45
+ const reply = await askTurn(deps.ctx, agent, words, { name: 'WeChat', context: instructions, cancelled, inWorld: deps.inWorld, answered });
38
46
  queue.alive();
39
47
  return { id: words.id, text: reply };
40
48
  });
@@ -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>;
@@ -3,7 +3,7 @@ import { readFileSync, rmSync } from 'node:fs';
3
3
  import { jsonObject, knownHost, readBody, sendJson } from "../../http.js";
4
4
  import { speakerIdentity } from "../shared/identity.js";
5
5
  import { durableWrite } from "../../life/lifeStore.js";
6
- import { createWechatHome } from "./home.js";
6
+ import { createWechatHome, WechatHomeBusy } from "./home.js";
7
7
  import { channelContext, channelMedia, channelReference } from "../shared/context.js";
8
8
  import { admitContextImages } from "./images.js";
9
9
  import { dirname, join } from 'node:path';
@@ -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, scopedTool } from "../../worldScope.js";
16
- export const WECHAT_PATH = '/dsh-world/wechat/ask';
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.ctx.tools.register(scopedTool(tool, () => inside(agent), () => detach(agent))));
64
+ disposers.push(registerScopedTool(agent, tool, () => !stopped && inside(agent), () => detach(agent)));
64
65
  attached.set(agent, disposers);
65
66
  }
66
67
  catch (error) {
@@ -172,6 +173,8 @@ export function createWechatModule(deps) {
172
173
  return { status: 200, body: { accepted: true, ...(await home.ask(text, identity, context, media, reference)) } };
173
174
  }
174
175
  catch (error) {
176
+ if (error instanceof WechatHomeBusy)
177
+ return { status: 409, body: { error: 'home busy; message not taken in, ask again later' } };
175
178
  deps.ctx.logger.warn('dsh-world WeChat request failed:', error);
176
179
  return { status: 503, body: { error: 'home request failed; delivery must be checked before retrying' } };
177
180
  }
@@ -180,7 +183,7 @@ export function createWechatModule(deps) {
180
183
  presence: (now) => !stopped && accountState === 'online' ? presence.summary(now) : undefined,
181
184
  status() { return { ...sending.status(), lastContactAt: lastContactAt ?? null, account: accountState ?? null, ...settings() }; },
182
185
  start() {
183
- durableWrite(deps.file, JSON.stringify({ origin: deps.origin(), token, path: WECHAT_PATH, pid: process.pid, protocol: 4, references: true }, null, 2));
186
+ durableWrite(deps.file, JSON.stringify({ origin: deps.origin(), token, path, pid: process.pid, protocol: 4, references: true }, null, 2));
184
187
  if (inWorld)
185
188
  for (const agent of deps.ctx.agents.list())
186
189
  attach(agent);
@@ -202,7 +205,7 @@ export function createWechatModule(deps) {
202
205
  catch { /* already absent, or a newer module owns the file */ }
203
206
  return closing = Promise.allSettled([...requests]).then(() => sending.stop());
204
207
  },
205
- route: { kind: 'exact', path: WECHAT_PATH, handler: async (req, res) => {
208
+ route: { kind: 'exact', path, handler: async (req, res) => {
206
209
  let result;
207
210
  const request = handle(req);
208
211
  requests.add(request);
@@ -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';
@@ -10,6 +23,12 @@ declare module '@deepseek-ai/dsh-llm' {
10
23
  'dsh-world-life': {
11
24
  kind: 'dsh-world-life';
12
25
  };
26
+ /** 她在 mood.md 里写的心情值:快照,不是谁说的话,不进归档。 */
27
+ 'dsh-world-mood': {
28
+ kind: 'dsh-world-mood';
29
+ form: 'snapshot';
30
+ worldId: string;
31
+ };
13
32
  'dsh-world-channel-context': {
14
33
  kind: 'dsh-world-channel-context';
15
34
  form: 'recall';