dsh-world 0.7.4 → 0.7.6

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 (68) hide show
  1. package/CHANGELOG.md +76 -0
  2. package/CONTRIBUTING.md +11 -0
  3. package/NOTES.md +73 -16
  4. package/README.md +14 -7
  5. package/client/index.js +43 -3
  6. package/lib/abortable.d.ts +1 -0
  7. package/lib/abortable.js +17 -0
  8. package/lib/compaction.d.ts +6 -1
  9. package/lib/compaction.js +8 -3
  10. package/lib/compactionSwap.d.ts +9 -17
  11. package/lib/compactionSwap.js +27 -35
  12. package/lib/console/homeApply.js +1 -12
  13. package/lib/console/routes.d.ts +1 -0
  14. package/lib/console/routes.js +10 -0
  15. package/lib/console/snapshot.d.ts +4 -0
  16. package/lib/console/snapshot.js +3 -0
  17. package/lib/ecosystem/bridge/bridge.d.ts +2 -2
  18. package/lib/ecosystem/bridge/bridge.js +24 -11
  19. package/lib/ecosystem/qq-native/home.d.ts +2 -1
  20. package/lib/ecosystem/qq-native/home.js +6 -2
  21. package/lib/ecosystem/qq-native/images.d.ts +13 -0
  22. package/lib/ecosystem/qq-native/images.js +76 -0
  23. package/lib/ecosystem/qq-native/index.d.ts +1 -0
  24. package/lib/ecosystem/qq-native/index.js +8 -2
  25. package/lib/ecosystem/qq-native/snowluma.d.ts +1 -0
  26. package/lib/ecosystem/qq-native/snowluma.js +13 -4
  27. package/lib/ecosystem/wechat/index.d.ts +5 -0
  28. package/lib/ecosystem/wechat/index.js +3 -1
  29. package/lib/ecosystem/wechat/presence.d.ts +5 -1
  30. package/lib/ecosystem/wechat/presence.js +22 -13
  31. package/lib/ecosystem/wechat/supervisor.d.ts +1 -1
  32. package/lib/ecosystem/wechat/supervisor.js +5 -1
  33. package/lib/elsewhere.d.ts +34 -0
  34. package/lib/elsewhere.js +40 -0
  35. package/lib/history.d.ts +5 -0
  36. package/lib/history.js +5 -0
  37. package/lib/hostContract.d.ts +6 -0
  38. package/lib/index.d.ts +1 -1
  39. package/lib/index.js +84 -46
  40. package/lib/life/home.js +8 -2
  41. package/lib/life/photoTools.js +60 -26
  42. package/lib/life/runtime.js +2 -0
  43. package/lib/memoryTools.d.ts +4 -3
  44. package/lib/memoryTools.js +11 -4
  45. package/lib/mood.d.ts +38 -5
  46. package/lib/mood.js +56 -13
  47. package/lib/moodTools.d.ts +6 -0
  48. package/lib/moodTools.js +30 -0
  49. package/lib/persona.js +7 -0
  50. package/lib/promptSection.d.ts +11 -13
  51. package/lib/promptSection.js +63 -80
  52. package/lib/runtime.d.ts +21 -2
  53. package/lib/runtime.js +162 -53
  54. package/lib/sessionNews.d.ts +17 -0
  55. package/lib/sessionNews.js +55 -0
  56. package/lib/sourceArchive.d.ts +1 -5
  57. package/lib/sourceArchive.js +31 -14
  58. package/lib/store.d.ts +6 -0
  59. package/lib/store.js +17 -3
  60. package/lib/worldScope.d.ts +2 -4
  61. package/lib/worldScope.js +6 -6
  62. package/package.json +1 -1
  63. package/src/ecosystem/wechat/windows/README.md +4 -2
  64. package/src/ecosystem/wechat/windows/adapter.py +6 -1
  65. package/src/ecosystem/wechat/windows/engine/NOTICE.md +6 -0
  66. package/src/ecosystem/wechat/windows/engine/profiles.json +28 -0
  67. package/src/ecosystem/wechat/windows/sender.py +6 -2
  68. package/templates/world-prompt.md +1 -1
@@ -1,6 +1,7 @@
1
1
  import { randomBytes } from 'node:crypto';
2
2
  import { copyFileSync, existsSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
3
3
  import { join } from 'node:path';
4
+ import { isDeepStrictEqual } from 'node:util';
4
5
  const STOCK = '@deepseek-ai/dsh-compaction-basic';
5
6
  const OURS = 'dsh-world/compaction';
6
7
  const stock = /^(\s*name:\s*)(['"]?)@deepseek-ai\/dsh-compaction-basic\2([ \t]*(?:#.*)?\r?)$/gm;
@@ -66,40 +67,32 @@ function removeRows(rows, match) {
66
67
  }
67
68
  return removed;
68
69
  }
69
- const isCompaction = (row) => row.name === STOCK || row.name === OURS;
70
- /** The preset's config with its one stock compaction row renamed to ours; the input is not changed. */
71
- export function swapPresetConfig(config) {
72
- const next = structuredClone(config);
73
- const rows = rowsWhere(next?.plugins, isCompaction);
74
- if (rows.some(row => row.name === OURS))
75
- return { status: 'already' };
76
- if (rows.length !== 1)
77
- return { status: 'unchanged', reason: rows.length ? `预设里有 ${rows.length} 条原版压缩配置,无法确定改哪一条` : '预设里没有原版压缩那一行' };
78
- rows[0].name = OURS;
79
- return { status: 'swapped', config: next };
80
- }
81
70
  const PRESET = '@deepseek-ai/dsh-agent-preset';
82
- /**
83
- * DSH's Web host composes the stock compaction inside each preset, so the profile has no row to rename. The host's
84
- * preset editor writes the whole preset into the profile when a partner edits it; this does the same for her preset
85
- * with only the compaction row changed. That copy no longer follows later DSH updates to the preset.
86
- */
87
- export async function swapPresetCompaction(editor, presetId, profileDir) {
88
- const entry = editor.entries().find(row => row.options.name === PRESET && row.options.config?.id === presetId);
89
- if (!entry)
90
- return { status: 'unchanged', reason: `没有找到预设 ${presetId}` };
91
- const first = swapPresetConfig(entry.options.config);
92
- if (first.status !== 'swapped')
93
- return first;
71
+ const isPreset = (entry) => entry.options.name === PRESET;
72
+ const plugins = (config) => config?.plugins;
73
+ const usesWorldCompaction = (config) => rowsWhere(plugins(config), row => row.name === OURS).length > 0;
74
+ export const hasAgentPresets = (editor) => editor?.entries().some(isPreset) ?? false;
75
+ function overriddenCompactionPreset(editor, id) {
76
+ if (!editor.entries().some(entry => isPreset(entry) && presetId(entry) === id && usesWorldCompaction(entry.options.config)))
77
+ return;
78
+ return editor.configuration?.().find(({ entry, override }) => isPreset(entry) && presetId(entry) === id && usesWorldCompaction(override));
79
+ }
80
+ export function compactionPresetOverride(editor, id, profileDir) {
81
+ const row = overriddenCompactionPreset(editor, id);
82
+ return row ? { preset: id, canRestore: Boolean(profileDir && Array.isArray(plugins(row.inherited))) } : null;
83
+ }
84
+ /** Return the inherited value through DSH's editor so it removes the profile override. */
85
+ export async function restoreCompactionPreset(editor, id, profileDir) {
86
+ const row = overriddenCompactionPreset(editor, id);
87
+ if (!row || !Array.isArray(plugins(row.inherited)))
88
+ throw new Error(`预设 ${id} 没有可还原的压缩覆盖`);
94
89
  const file = join(profileDir, 'cordis.patch.yml');
95
- const backup = existsSync(file) ? backupBeside(file) : undefined;
96
- await editor.edit(entry, raw => {
97
- const result = swapPresetConfig(raw);
98
- if (result.status !== 'swapped')
99
- throw new Error(`预设 ${presetId} 在写入前变了:${result.status === 'unchanged' ? result.reason : '已经换过'}`);
100
- return result.config;
90
+ await editor.edit(row.entry, (raw, inherited) => {
91
+ if (!isDeepStrictEqual(raw, row.override) || !Array.isArray(plugins(inherited)))
92
+ throw new Error(`预设 ${id} 已变化,请刷新后再试`);
93
+ backupBeside(file);
94
+ return inherited;
101
95
  });
102
- return { status: 'swapped', backup: backup ?? '(原来没有 cordis.patch.yml)', preset: presetId };
103
96
  }
104
97
  // DSH 0.2.2 folded `list_agents` into the subagent-control package. A preset copied on 0.2.1 still names this row, and
105
98
  // DSH then refuses to mount that whole preset, so no session using it can be resumed.
@@ -150,12 +143,12 @@ export async function repairCopiedPresets(deps) {
150
143
  * remembered only when it succeeded or was already done, so a partner who later puts the stock one back is left alone,
151
144
  * while a profile this could not read is looked at again next start.
152
145
  */
153
- export async function swapCompactionOnce(deps) {
146
+ export function swapCompactionOnce(deps) {
154
147
  if (!deps.enabled || deps.done() || !deps.profileDir)
155
148
  return;
156
149
  let result;
157
150
  try {
158
- result = await (deps.swap ?? swapStockCompaction)(deps.profileDir);
151
+ result = swapStockCompaction(deps.profileDir);
159
152
  }
160
153
  catch (error) {
161
154
  deps.report(`没能把压缩换成 dsh-world 的“只留对话”压缩:${error instanceof Error ? error.message : String(error)}`);
@@ -168,6 +161,5 @@ export async function swapCompactionOnce(deps) {
168
161
  deps.markDone();
169
162
  if (result.status !== 'swapped')
170
163
  return;
171
- const copied = result.preset ? `预设 ${result.preset} 已整份写进 profile,之后 DSH 升级对这个预设的改动不会自动进来;` : '';
172
- deps.report(`已把 profile 的压缩换成 dsh-world 的“只留对话”压缩,重启 DSH 后生效(原文件备份在 ${result.backup})。${copied}不想换:恢复备份,并在 dsh-world 配置里写 replaceCompaction: false。`);
164
+ deps.report(`已把 profile 的压缩换成 dsh-world 的“只留对话”压缩,重启 DSH 后生效(原文件备份在 ${result.backup})。不想换:恢复备份,并在 dsh-world 配置里写 replaceCompaction: false。`);
173
165
  }
@@ -1,4 +1,4 @@
1
- import { addAbortListener } from 'node:events';
1
+ import { abortable } from "../abortable.js";
2
2
  import { ManualCompactionError } from '@deepseek-ai/dsh-compaction';
3
3
  import { errorText } from "../faults.js";
4
4
  /**
@@ -17,17 +17,6 @@ function failureText(error) {
17
17
  parts.push(errorText(current));
18
18
  return parts.join(':');
19
19
  }
20
- async function abortable(promise, signal) {
21
- signal.throwIfAborted();
22
- let listener;
23
- const aborted = new Promise((_, reject) => { listener = addAbortListener(signal, () => reject(signal.reason)); });
24
- try {
25
- return await Promise.race([promise, aborted]);
26
- }
27
- finally {
28
- listener[Symbol.dispose]();
29
- }
30
- }
31
20
  /** One explicit request, held behind existing turns and cancelled with the life line. */
32
21
  export function createHomeApply(deps) {
33
22
  let state = { status: 'idle' };
@@ -22,6 +22,7 @@ export interface ConsoleActions {
22
22
  stop(): Promise<void>;
23
23
  /** Enqueue one application of saved prompts and idle-home compaction; returns a refusal, if any. */
24
24
  applyHome(): string | undefined;
25
+ restoreCompactionPreset(): Promise<void>;
25
26
  prompts(): {
26
27
  persona: Persona;
27
28
  worldPrompt: {
@@ -4,6 +4,7 @@ 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
+ import { errorText } from "../faults.js";
7
8
  /** A write must carry this header; a page on another site cannot add it without a CORS preflight, which is never answered. */
8
9
  export const WRITE_HEADER = 'x-dsh-world';
9
10
  const MAX_BODY_BYTES = 64 * 1024;
@@ -52,6 +53,15 @@ async function write(actions, path, body) {
52
53
  const refused = actions.applyHome();
53
54
  return refused ? bad(refused) : ok();
54
55
  }
56
+ case '/console/restore-compaction-preset': {
57
+ try {
58
+ await actions.restoreCompactionPreset();
59
+ return ok();
60
+ }
61
+ catch (error) {
62
+ return bad(errorText(error));
63
+ }
64
+ }
55
65
  case '/console/persona': {
56
66
  const layers = persona(body);
57
67
  if (!layers)
@@ -10,6 +10,7 @@ import type { HomeApplyState } from './homeApply.ts';
10
10
  import type { PhotoStore } from '../life/photos.ts';
11
11
  import type { DailySchedule } from '../life/types.ts';
12
12
  import type { MemoryService } from '../memory.ts';
13
+ import type { compactionPresetOverride } from '../compactionSwap.ts';
13
14
  export declare function estimateTokens(text: string): number;
14
15
  export interface SnapshotDeps {
15
16
  ctx: Context;
@@ -21,10 +22,13 @@ export interface SnapshotDeps {
21
22
  /** The running life line; undefined while her world is stopped. */
22
23
  life(): LifeRuntime | undefined;
23
24
  homeApply?(): HomeApplyState;
25
+ compactionPreset?(): ReturnType<typeof compactionPresetOverride>;
24
26
  photos?(): PhotoStore;
25
27
  /** Long-term memory: the console's lookups and the health of its index. */
26
28
  longTerm?: MemoryService;
27
29
  diaryDir: string;
30
+ /** Her mood file, shown read-only; absent in a console without a room. */
31
+ moodFile?: string;
28
32
  running(): boolean;
29
33
  /** CNY a day for her home; undefined is no limit. */
30
34
  dailyBudget(): number | undefined;
@@ -1,6 +1,7 @@
1
1
  import { SessionId } from '@deepseek-ai/dsh-session';
2
2
  import { createHistory, renderHistory } from "../history.js";
3
3
  import { createDiaryReader } from "../life/diary.js";
4
+ import { moodView } from "../mood.js";
4
5
  const SNAPSHOT_TTL_MS = 5000;
5
6
  export function estimateTokens(text) {
6
7
  const cjk = (text.match(/[㐀-鿿豈-﫿 -〿＀-￯]/g) ?? []).length;
@@ -28,11 +29,13 @@ export function consoleSources(deps) {
28
29
  schedule: deps.schedule?.() ?? null,
29
30
  life: life ? { homeSessionId: life.homeSessionId, status: home ? home.status : 'cold', alarm: life.alarm, review: life.review, recentWakes: lifeStore?.wakes().slice(-5).reverse() ?? [] } : null,
30
31
  homeApply: deps.homeApply?.() ?? null,
32
+ compactionPreset: deps.compactionPreset?.() ?? null,
31
33
  health: [...(life?.faults ?? []), ...deps.faults()],
32
34
  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() },
33
35
  wechat: deps.wechat?.() ?? null,
34
36
  compactions: lifeStore?.compactions().slice(-5).reverse() ?? [],
35
37
  diaryDates: diary.dates(), activityDays: lifeStore?.activityDays() ?? [],
38
+ mood: deps.moodFile ? moodView(deps.moodFile) : null,
36
39
  native,
37
40
  modules: deps.modules?.() ?? null,
38
41
  };
@@ -28,8 +28,8 @@ export interface BridgeDeps {
28
28
  name?: string;
29
29
  }
30
30
  /**
31
- * A local app's way into her home: its words arrive as her partner's own (source `user`), and the first
32
- * visible text she says after they are admitted goes to the outlets. Only the latest words are tracked.
31
+ * A local app's way into her home: its words arrive as her partner's own (source `user`). The final
32
+ * reply after admission goes to the outlets when that turn completes. Only the latest words are tracked.
33
33
  */
34
34
  export declare function createBridge(deps: BridgeDeps): {
35
35
  start: () => void;
@@ -13,8 +13,8 @@ export class HomeUnavailable extends Error {
13
13
  }
14
14
  const labels = (name) => ({ reply: `${name}的回复`, busy: `「${name}在忙」`, reach: `${name}找你的话` });
15
15
  /**
16
- * A local app's way into her home: its words arrive as her partner's own (source `user`), and the first
17
- * visible text she says after they are admitted goes to the outlets. Only the latest words are tracked.
16
+ * A local app's way into her home: its words arrive as her partner's own (source `user`). The final
17
+ * reply after admission goes to the outlets when that turn completes. Only the latest words are tracked.
18
18
  */
19
19
  export function createBridge(deps) {
20
20
  const { ctx } = deps;
@@ -56,18 +56,31 @@ export function createBridge(deps) {
56
56
  disposers.push(ctx.on('session/event', (session, event) => {
57
57
  if (!tracked || session.id !== tracked.sessionId)
58
58
  return;
59
- if (event.type === 'user/message' && event.data.id === tracked.id) {
60
- tracked.admitted = true;
59
+ if (event.type === 'user/message') {
60
+ if (event.data.id === tracked.id)
61
+ tracked.admitted = true;
62
+ else if (tracked.admitted && event.data.source.kind === 'user')
63
+ untrack();
61
64
  return;
62
65
  }
63
- if (event.type !== 'assistant/message' || !tracked.admitted)
66
+ if (!tracked.admitted)
64
67
  return;
65
- const visible = event.data.message.content.flatMap(block => block.type === 'text' ? [block.text] : []).join('\n');
66
- const reply = pushOf(visible, 'reply', name, safeOrigin());
67
- if (!reply.text && !reply.images)
68
- return;
69
- untrack();
70
- send(reply);
68
+ if (event.type === 'assistant/message') {
69
+ const { content } = event.data.message;
70
+ // Text accompanying a tool call can be narration, including when the tool itself ends the turn.
71
+ tracked.finalText = content.some(block => block.type === 'tool-call') ? undefined
72
+ : content.flatMap(block => block.type === 'text' ? [block.text] : []).join('\n');
73
+ }
74
+ // The next turn end in this session closes the turn that admitted the words, even when steered in.
75
+ if (event.type === 'turn/end') {
76
+ const { finalText } = tracked;
77
+ untrack();
78
+ if (event.data.reason.kind !== 'completed' || !finalText)
79
+ return;
80
+ const reply = pushOf(finalText, 'reply', name, safeOrigin());
81
+ if (reply.text || reply.images)
82
+ send(reply);
83
+ }
71
84
  }));
72
85
  try {
73
86
  durableWrite(deps.file, JSON.stringify({ origin: deps.origin(), ...bridgePaths(deps.prefix), token, pid: process.pid, startedAt: clock().toISOString(), name }, null, 2));
@@ -1,5 +1,6 @@
1
1
  import type { Context } from '@deepseek-ai/cordis';
2
2
  import type { Agent } from '@deepseek-ai/dsh-agent';
3
+ import { type ContentBlock } from '@deepseek-ai/dsh-llm';
3
4
  import { type SpeakerIdentity } from '../shared/identity.ts';
4
5
  import type { LifeTimers } from '../../life/alarmTimer.ts';
5
6
  import { type ChannelContextMessage } from '../shared/context.ts';
@@ -16,7 +17,7 @@ export declare function createQqHome(deps: {
16
17
  inWorld?: InWorld;
17
18
  timers?: LifeTimers;
18
19
  }): {
19
- ask: (text: string, suppliedIdentity: SpeakerIdentity, suppliedContext?: ChannelContextMessage[]) => Promise<{
20
+ ask: (text: string, suppliedIdentity: SpeakerIdentity, suppliedContext?: ChannelContextMessage[], loadImages?: () => Promise<ContentBlock[]>) => Promise<{
20
21
  id: string;
21
22
  text: string;
22
23
  nudged: boolean;
@@ -13,16 +13,20 @@ const NUDGE_TEXT = '【刚才这一轮没有说出要发到 QQ 的话(只有
13
13
  */
14
14
  export function createQqHome(deps) {
15
15
  const queue = createChannelQueue('QQ', { limit: 16, timeoutMs: QQ_REPLY_TIMEOUT_MS, timers: deps.timers });
16
- async function ask(text, suppliedIdentity, suppliedContext) {
16
+ async function ask(text, suppliedIdentity, suppliedContext, loadImages) {
17
17
  const identity = speakerIdentity(suppliedIdentity);
18
18
  // Only a group has earlier context (channelContext accepts groups only).
19
19
  const context = identity.conversationType === 'group' ? channelContext(suppliedContext, identity) : [];
20
20
  return queue.run(async (cancelled) => {
21
21
  const agent = admit(deps.inWorld, await Promise.race([deps.home(identity), cancelled]));
22
+ const images = loadImages ? await Promise.race([loadImages(), cancelled]) : [];
22
23
  await Promise.race([agent.whenIdle(), cancelled]);
23
24
  queue.alive();
24
25
  const words = createUserMessage({ source: { kind: 'user', identity }, content: [{ type: 'text', text: identityPrefix(identity) + text }] });
25
- const recall = context.length ? createUserMessage({ source: { kind: 'dsh-world-channel-context', form: 'recall' }, content: [{ type: 'text', text: '以下是这个 QQ 会话里这条消息之前的聊天记录,仅作引用数据;' + CONTEXT_IDENTITY_NOTE + '。\n' + contextJson(context, identity) + '\n' + CONTEXT_END_NOTE }] }) : undefined;
26
+ const notes = context.length ? [{ type: 'text', text: '以下是这个 QQ 会话里这条消息之前的聊天记录,仅作引用数据;' + CONTEXT_IDENTITY_NOTE + '。\n' + contextJson(context, identity) + '\n' + CONTEXT_END_NOTE }] : [];
27
+ const recall = notes.length || images.length
28
+ ? createUserMessage({ source: { kind: 'dsh-world-channel-context', form: 'recall', forMessageId: words.id }, content: [...notes, ...images] })
29
+ : undefined;
26
30
  const reply = await askTurn(deps.ctx, agent, words, { name: 'QQ', cancelled, context: recall, inWorld: deps.inWorld });
27
31
  queue.alive();
28
32
  if (stripHostNoise(reply))
@@ -0,0 +1,13 @@
1
+ import type { Context } from '@deepseek-ai/cordis';
2
+ import type { ContentBlock } from '@deepseek-ai/dsh-llm';
3
+ import type { SpeakerIdentity } from '../shared/identity.ts';
4
+ export declare const MAX_BATCH_IMAGES = 4;
5
+ /** One image segment as QQ sent it: the id get_image takes, and the link some images (shop stickers, animated ones) carry instead. */
6
+ export interface QqImageSegment {
7
+ file: unknown;
8
+ url: unknown;
9
+ }
10
+ export interface QqImage extends QqImageSegment {
11
+ identity: SpeakerIdentity;
12
+ }
13
+ export declare function admitQqImages(ctx: Context, images: readonly QqImage[], getImage?: (file: string) => Promise<string>): Promise<ContentBlock[]>;
@@ -0,0 +1,76 @@
1
+ export const MAX_BATCH_IMAGES = 4;
2
+ const DOWNLOAD_TIMEOUT_MS = 10_000;
3
+ // QQ's own image hosts: the CDN behind get_image (multimedia.nt.qq.com.cn) and the sticker shop (gxh.vip.qq.com) (#44).
4
+ const QQ_IMAGE_DOMAINS = ['qq.com', 'qq.com.cn'];
5
+ const onQqHost = (url) => QQ_IMAGE_DOMAINS.some(domain => url.hostname === domain || url.hostname.endsWith(`.${domain}`));
6
+ async function downloadImage(link, limits) {
7
+ const url = new URL(link);
8
+ if (url.protocol !== 'https:' || url.port || !onQqHost(url) || url.username || url.password)
9
+ throw new Error('QQ 图片链接不受支持');
10
+ const controller = new AbortController();
11
+ try {
12
+ const response = await fetch(url, {
13
+ redirect: 'error',
14
+ signal: AbortSignal.any([controller.signal, AbortSignal.timeout(DOWNLOAD_TIMEOUT_MS)]),
15
+ });
16
+ const contentType = response.headers.get('content-type')?.split(';')[0]?.trim().toLowerCase();
17
+ const mediaType = limits.mediaTypes.find(type => type === contentType);
18
+ if (!response.ok || !response.body || !mediaType)
19
+ throw new Error('QQ 图片响应无效');
20
+ if (Number(response.headers.get('content-length')) > limits.maxImageBytes)
21
+ throw new Error('QQ 图片超过大小限制');
22
+ const chunks = [];
23
+ let bytes = 0;
24
+ for await (const chunk of response.body) {
25
+ bytes += chunk.byteLength;
26
+ if (bytes > limits.maxImageBytes)
27
+ throw new Error('QQ 图片超过大小限制');
28
+ chunks.push(chunk);
29
+ }
30
+ return { data: Buffer.concat(chunks, bytes), mediaType };
31
+ }
32
+ finally {
33
+ controller.abort();
34
+ }
35
+ }
36
+ // get_image first, as verified for ordinary pictures; the segment's own link when get_image has no usable answer.
37
+ async function fetchQqImage({ file, url }, limits, getImage) {
38
+ const viaFile = typeof file === 'string' && /^[a-z0-9_-][a-z0-9_.-]{0,255}$/i.test(file) && getImage
39
+ ? getImage(file).then(link => downloadImage(link, limits)) : Promise.reject(new Error('QQ 图片标识无效'));
40
+ return viaFile.catch(error => {
41
+ if (typeof url !== 'string' || !url)
42
+ throw error;
43
+ return downloadImage(url, limits);
44
+ });
45
+ }
46
+ export async function admitQqImages(ctx, images, getImage) {
47
+ if (!images.length)
48
+ return [];
49
+ const unavailable = { type: 'text', text: '本次有 QQ 图片未能读取,请勿假装看过。' };
50
+ const store = ctx.get('attachments');
51
+ if (!store)
52
+ return [unavailable];
53
+ const limits = store.imageLimits;
54
+ const selected = images.slice(0, Math.min(MAX_BATCH_IMAGES, limits.maxImagesPerMessage));
55
+ const downloads = await Promise.allSettled(selected.map(image => fetchQqImage(image, limits, getImage)));
56
+ const content = [];
57
+ let remainingBytes = limits.maxMessageImageBytes;
58
+ let saved = 0;
59
+ for (const [index, result] of downloads.entries()) {
60
+ if (result.status === 'rejected' || result.value.data.byteLength > remainingBytes)
61
+ continue;
62
+ try {
63
+ const [attachment] = await store.saveImages([result.value]);
64
+ if (!attachment)
65
+ continue;
66
+ const { platformMessageId, speakerId, speakerName } = selected[index].identity;
67
+ content.push({ type: 'text', text: `下面是本次收到的第 ${index + 1} 张 QQ 图片,来源:${JSON.stringify({ messageId: platformMessageId, speakerId, speakerName })}。` }, { type: 'image', attachment });
68
+ remainingBytes -= result.value.data.byteLength;
69
+ saved++;
70
+ }
71
+ catch { /* 一张无法保存时仍交付同批的其他图片和文字。 */ }
72
+ }
73
+ if (saved < images.length)
74
+ content.push(unavailable);
75
+ return content;
76
+ }
@@ -90,6 +90,7 @@ export interface QqTransport {
90
90
  sendPrivate(userId: string, parts: string | QqPart[]): Promise<{
91
91
  messageId: string;
92
92
  }>;
93
+ getImage?(file: string): Promise<string>;
93
94
  /** 发账号收藏表情(不是消息段,单发一条);测试替身可以不实现。 */
94
95
  sendCustomFace?(emojiId: string, target: {
95
96
  groupId?: string;
@@ -4,6 +4,7 @@ import { dirname, join } from 'node:path';
4
4
  import { speakerIdentity, conversationKey } from "../shared/identity.js";
5
5
  import { createBridge } from "./snowluma.js";
6
6
  import { createQqHome } from "./home.js";
7
+ import { admitQqImages, MAX_BATCH_IMAGES } from "./images.js";
7
8
  import { createBatcher } from "./batch.js";
8
9
  import { createOutbox } from "./outbox.js";
9
10
  import { planReply, stripHostNoise } from "./replies.js";
@@ -218,7 +219,9 @@ export function createQqNativeModule(deps) {
218
219
  pushContext(key, { id: messageId || String(Date.now()), occurredAt: new Date().toISOString(), text, identity }, config.contextMessages);
219
220
  return;
220
221
  }
221
- batches.add(key, { text, identity, who: speakerName });
222
+ const images = (message.segments ?? []).filter(segment => segment?.type === 'image')
223
+ .slice(0, MAX_BATCH_IMAGES + 1).map(segment => ({ file: segment.data?.file, url: segment.data?.url }));
224
+ batches.add(key, { text, identity, who: speakerName, images });
222
225
  }
223
226
  async function answer(key, gathered) {
224
227
  const config = settings();
@@ -231,7 +234,10 @@ export function createQqNativeModule(deps) {
231
234
  const text = gathered.length === 1 ? gathered[0].text : gathered.map(item => isGroup && item.who ? `${item.who}: ${item.text}` : item.text).join('\n');
232
235
  answering.add(key);
233
236
  try {
234
- const reply = await home.ask(text, identity, contexts.get(key) ?? []);
237
+ const images = gathered.flatMap(item => item.images.map(image => ({ ...image, identity: item.identity })));
238
+ const reply = await home.ask(text, identity, contexts.get(key) ?? [], images.length
239
+ ? () => admitQqImages(deps.ctx, images, client?.getImage?.bind(client))
240
+ : undefined);
235
241
  const words = stripHostNoise(reply.text);
236
242
  // 提醒过一次还是没有能发的话:不发,但要留下痕迹,分得清「她没说出话」和「路丢了」(#34);
237
243
  // 只剩复述的聊天记录、工具标签这些(#35)也一样。
@@ -79,6 +79,7 @@ export declare function createBridge(options: Loose): {
79
79
  sendPrivate(userId: Loose, parts: Loose): Promise<{
80
80
  messageId: string;
81
81
  }>;
82
+ getImage(file: string): Promise<string>;
82
83
  /**
83
84
  * 发账号收藏表情:它走 `send_custom_face`,不是消息段,只能单发一条。`emojiId` 可以是 emoji_id、
84
85
  * 第几个(1 起),或者一个意思(「开心」)——按备注挑。
@@ -140,9 +140,9 @@ function escapeOutgoingText(value) {
140
140
  * @returns {string}
141
141
  */
142
142
  export function segmentsToText(message) {
143
- // 有些 OneBot 实现直接把纯文本消息放在 message 字段里(string)
143
+ // CQ 字符串里的图片链接也不交给模型,取图只使用解析出的 file 标识。
144
144
  if (typeof message === 'string')
145
- return message.trim();
145
+ return message.replace(/\[CQ:image(?:,[^\]]*)?\]/g, '[图片]').trim();
146
146
  const list = Array.isArray(message)
147
147
  ? message
148
148
  : (message && typeof message === 'object' ? [message] : []);
@@ -169,9 +169,8 @@ export function segmentsToText(message) {
169
169
  case 'mface':
170
170
  out.push(`[表情${d.summary ? `:${d.summary}` : ''}]`);
171
171
  break;
172
- // 带上 file 名:光写「[图片]」等于把图丢了,有 file 才能再向 OneBot 换直链。
173
172
  case 'image':
174
- out.push(d.file ? `[图片 file=${d.file}]` : '[图片]');
173
+ out.push('[图片]');
175
174
  break;
176
175
  case 'record':
177
176
  out.push(d.file ? `[语音 file=${d.file}]` : '[语音]');
@@ -601,6 +600,16 @@ export function createBridge(options) {
601
600
  throw new Error(`sendPrivate: 无效的 QQ 号 ${JSON.stringify(userId ?? null)}`);
602
601
  return enqueueSend('private', id, parts);
603
602
  },
603
+ async getImage(file) {
604
+ if (!client)
605
+ throw new Error('QQ 桥未启动或已停止,无法取图');
606
+ const { url, file_url: fileUrl } = (await client.getImage({ file }, { timeoutMs: SEND_TIMEOUT_MS })) ?? {};
607
+ if (typeof url === 'string' && url)
608
+ return url;
609
+ if (typeof fileUrl === 'string' && fileUrl)
610
+ return fileUrl;
611
+ throw new Error('SnowLuma 未返回图片直链');
612
+ },
604
613
  /**
605
614
  * 发账号收藏表情:它走 `send_custom_face`,不是消息段,只能单发一条。`emojiId` 可以是 emoji_id、
606
615
  * 第几个(1 起),或者一个意思(「开心」)——按备注挑。
@@ -20,7 +20,12 @@ export declare function createWechatModule(deps: {
20
20
  record?(reply: PreparedReply): Promise<string>;
21
21
  receipt?(receipt: WechatReceipt): Promise<void>;
22
22
  }): {
23
+ /** The quiet groups, for her alarm; groups with unread messages are news from elsewhere instead. */
23
24
  presence: (now: Date) => string | undefined;
25
+ elsewhere: {
26
+ look: string;
27
+ news: (now: Date) => import("../../elsewhere.ts").ElsewhereNews[];
28
+ };
24
29
  status(): {
25
30
  contextMessages: number;
26
31
  bufferSeconds: number;
@@ -180,7 +180,9 @@ export function createWechatModule(deps) {
180
180
  }
181
181
  }
182
182
  return {
183
- presence: (now) => !stopped && accountState === 'online' ? presence.summary(now) : undefined,
183
+ /** The quiet groups, for her alarm; groups with unread messages are news from elsewhere instead. */
184
+ presence: (now) => !stopped && accountState === 'online' ? presence.quiet(now) : undefined,
185
+ elsewhere: { look: '微信群用 wechat_history 看', news: now => !stopped && accountState === 'online' ? presence.unread(now) : [] },
184
186
  status() { return { ...sending.status(), lastContactAt: lastContactAt ?? null, account: accountState ?? null, ...settings() }; },
185
187
  start() {
186
188
  durableWrite(deps.file, JSON.stringify({ origin: deps.origin(), token, path, pid: process.pid, protocol: 4, references: true }, null, 2));
@@ -1,6 +1,10 @@
1
+ import { type ElsewhereNews } from '../../elsewhere.ts';
1
2
  /** Ephemeral host view of the adapter's durable, account-bound counters. */
2
3
  export declare function createWechatPresence(): {
3
4
  clear(): void;
4
5
  accept(value: unknown): void;
5
- summary(now: Date): string | undefined;
6
+ /** Groups with messages she has not read: news from elsewhere, told once per change. */
7
+ unread(now: Date): ElsewhereNews[];
8
+ /** How long the groups with nothing unread have been quiet, for her alarm: whether to speak up there is hers. */
9
+ quiet(now: Date): string | undefined;
6
10
  };
@@ -1,13 +1,16 @@
1
+ import { ago } from "../../elsewhere.js";
1
2
  const clean = (value) => [...value.replace(/[\r\n\u0000-\u001f「」]/g, ' ')].slice(0, 40).join('');
2
3
  // The adapter permits a 60-second poll; leave one poll and a control-request margin before expiry.
3
4
  const PRESENCE_TTL_MS = 2 * 60_000 + 5_000;
4
- function ago(milliseconds) {
5
- const minutes = Math.max(0, Math.floor(milliseconds / 60_000));
6
- return minutes < 1 ? '刚刚' : minutes < 60 ? `${minutes} 分钟前` : minutes < 1440 ? `${Math.floor(minutes / 60)} 小时前` : `${Math.floor(minutes / 1440)} 天前`;
7
- }
8
5
  /** Ephemeral host view of the adapter's durable, account-bound counters. */
9
6
  export function createWechatPresence() {
10
7
  let groups = [], observedAt = 0;
8
+ /** What the adapter last reported, while it is recent enough to stand for now; stale data cannot assert a quiet group. */
9
+ const current = (now) => {
10
+ const age = now.getTime() - observedAt;
11
+ return age < -60_000 || age > PRESENCE_TTL_MS ? [] : groups;
12
+ };
13
+ const speaker = (row) => row.lastSelf ? '我自己' : row.lastSpeaker;
11
14
  return {
12
15
  clear() { groups = []; observedAt = 0; },
13
16
  accept(value) {
@@ -38,18 +41,24 @@ export function createWechatPresence() {
38
41
  groups = next;
39
42
  observedAt = at;
40
43
  },
41
- summary(now) {
42
- const age = now.getTime() - observedAt;
43
- if (!groups.length || age < -60_000 || age > PRESENCE_TTL_MS)
44
+ /** Groups with messages she has not read: news from elsewhere, told once per change. */
45
+ unread(now) {
46
+ return current(now).filter(row => row.count > 0).sort((a, b) => b.lastAt - a.lastAt).map(row => ({
47
+ key: `wechat:${row.chatId}`, mark: `${row.count}:${row.lastAt}`,
48
+ text: `微信群「${row.name}」${row.count > 99 ? '99+' : row.count} 条我还没看到,最后是${speaker(row)}(${ago(now.getTime() - row.lastAt)})`,
49
+ }));
50
+ },
51
+ /** How long the groups with nothing unread have been quiet, for her alarm: whether to speak up there is hers. */
52
+ quiet(now) {
53
+ const rows = current(now).filter(row => !row.count);
54
+ if (!rows.length)
44
55
  return;
45
- const entries = [...groups].sort((a, b) => Number(b.count > 0) - Number(a.count > 0) || b.lastAt - a.lastAt).slice(0, 8).map(row => {
46
- const speaker = row.lastSelf ? '我自己' : row.lastSpeaker;
56
+ const entries = [...rows].sort((a, b) => b.lastAt - a.lastAt).slice(0, 8).map(row => {
47
57
  const elapsed = ago(now.getTime() - row.lastAt);
48
- return row.count ? `「${row.name}」${row.count > 99 ? '99+' : row.count} 条未读,最后是${speaker}(${elapsed})`
49
- : `「${row.name}」${elapsed.endsWith('前') ? elapsed.slice(0, -1) + '没人说话' : '刚刚有发言'},最后是${speaker}`;
58
+ return `「${row.name}」${elapsed.endsWith('前') ? elapsed.slice(0, -1) + '没人说话' : '刚刚有发言'},最后是${speaker(row)}`;
50
59
  });
51
- if (groups.length > entries.length)
52
- entries.push(`另有 ${groups.length - entries.length} 个群`);
60
+ if (rows.length > entries.length)
61
+ entries.push(`另有 ${rows.length - entries.length} 个群`);
53
62
  return '微信:' + entries.join(';');
54
63
  },
55
64
  };
@@ -32,7 +32,7 @@ export interface AdapterSupervisorDeps {
32
32
  /**
33
33
  * Runs the Windows WeChat adapter for as long as the world's WeChat module lives: started with the module,
34
34
  * restarted with a growing delay when it exits or cannot start (a file missing during an upgrade comes back),
35
- * and stopped (its whole process tree) with the module. An exit that says a person must act is not retried. An exit
35
+ * and stopped (its whole process tree) with the module. Unsupported builds and exits that need a person halt. An exit
36
36
  * that says the native bridge needs building is answered by building it once into the `engine` folder beside the
37
37
  * adapter's config (where the adapter looks) and starting it again; a build that fails, or still does not match,
38
38
  * stops with what to do. The adapter itself waits for the same WeChat account to log in again, so a WeChat
@@ -10,6 +10,8 @@ export const BUILD_SCRIPT = fileURLToPath(new URL('../../../src/ecosystem/wechat
10
10
  export const EXIT_NEEDS_HUMAN = 2;
11
11
  /** The adapter exits with this when no build of the native bridge matches its source (an upgrade changed it). */
12
12
  export const EXIT_NEEDS_BUILD = 3;
13
+ /** The adapter exits with this when its Weixin.dll cannot be matched to a supported build. */
14
+ const EXIT_UNSUPPORTED_BUILD = 4;
13
15
  const MAX_LOG_BYTES = 1024 * 1024;
14
16
  const HEALTHY_MS = 60_000;
15
17
  const BUILD_BY_HAND = '请在仓库里运行 wechat.ps1 Build,再在控制台重启适配器';
@@ -35,7 +37,7 @@ function lastLine(file, from) {
35
37
  /**
36
38
  * Runs the Windows WeChat adapter for as long as the world's WeChat module lives: started with the module,
37
39
  * restarted with a growing delay when it exits or cannot start (a file missing during an upgrade comes back),
38
- * and stopped (its whole process tree) with the module. An exit that says a person must act is not retried. An exit
40
+ * and stopped (its whole process tree) with the module. Unsupported builds and exits that need a person halt. An exit
39
41
  * that says the native bridge needs building is answered by building it once into the `engine` folder beside the
40
42
  * adapter's config (where the adapter looks) and starting it again; a build that fails, or still does not match,
41
43
  * stops with what to do. The adapter itself waits for the same WeChat account to log in again, so a WeChat
@@ -162,6 +164,8 @@ export function createAdapterSupervisor(deps) {
162
164
  }
163
165
  else if (code === EXIT_NEEDS_BUILD)
164
166
  rebuild();
167
+ else if (code === EXIT_UNSUPPORTED_BUILD)
168
+ halted(said ?? '当前微信构建无法匹配受支持的版本,已停止自动重启');
165
169
  else {
166
170
  deps.log(`dsh-world WeChat adapter exited (${text}); restarting`);
167
171
  schedule();